TextPage.vue 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  1. <template>
  2. <div ref="main" class="main">
  3. <div class="layout back" @wheel.prevent.stop="onMouseWheel">
  4. <div v-html="background"></div>
  5. <!-- img -->
  6. </div>
  7. <div ref="scrollBox1" class="layout over-hidden" @wheel.prevent.stop="onMouseWheel">
  8. <div ref="scrollingPage1" class="layout over-hidden" @transitionend="onPage1TransitionEnd" @animationend="onPage1AnimationEnd">
  9. <div v-html="page1"></div>
  10. </div>
  11. </div>
  12. <div ref="scrollBox2" class="layout over-hidden" @wheel.prevent.stop="onMouseWheel">
  13. <div ref="scrollingPage2" class="layout over-hidden" @transitionend="onPage2TransitionEnd" @animationend="onPage2AnimationEnd">
  14. <div v-html="page2"></div>
  15. </div>
  16. </div>
  17. <div v-show="showStatusBar" ref="statusBar" class="layout">
  18. <div v-html="statusBar"></div>
  19. </div>
  20. <div v-show="clickControl" ref="layoutEvents" class="layout events" @mousedown.prevent.stop="onMouseDown" @mouseup.prevent.stop="onMouseUp"
  21. @wheel.prevent.stop="onMouseWheel"
  22. @touchstart.stop="onTouchStart" @touchend.stop="onTouchEnd" @touchmove.stop="onTouchMove" @touchcancel.prevent.stop="onTouchCancel"
  23. oncontextmenu="return false;">
  24. <div v-show="showStatusBar && statusBarClickOpen" v-html="statusBarClickable" @mousedown.prevent.stop @touchstart.stop
  25. @click.prevent.stop="onStatusBarClick"></div>
  26. </div>
  27. <div v-show="!clickControl && showStatusBar && statusBarClickOpen" class="layout" v-html="statusBarClickable" @mousedown.prevent.stop @touchstart.stop
  28. @click.prevent.stop="onStatusBarClick">
  29. </div>
  30. <!-- невидимым делать нельзя, вовремя не подгружаютя шрифты -->
  31. <canvas ref="offscreenCanvas" class="layout" style="visibility: hidden"></canvas>
  32. <div ref="measureWidth" style="position: absolute; visibility: hidden"></div>
  33. </div>
  34. </template>
  35. <script>
  36. //-----------------------------------------------------------------------------
  37. import Vue from 'vue';
  38. import Component from 'vue-class-component';
  39. import {loadCSS} from 'fg-loadcss';
  40. import _ from 'lodash';
  41. import * as utils from '../../../share/utils';
  42. import bookManager from '../share/bookManager';
  43. import DrawHelper from './DrawHelper';
  44. import rstore from '../../../store/modules/reader';
  45. import {clickMap} from '../share/clickMap';
  46. const minLayoutWidth = 100;
  47. export default @Component({
  48. watch: {
  49. bookPos: function() {
  50. this.$emit('book-pos-changed', {bookPos: this.bookPos, bookPosSeen: this.bookPosSeen});
  51. this.draw();
  52. },
  53. bookPosSeen: function() {
  54. this.$emit('book-pos-changed', {bookPos: this.bookPos, bookPosSeen: this.bookPosSeen});
  55. },
  56. settings: function() {
  57. this.debouncedLoadSettings();
  58. },
  59. toggleLayout: function() {
  60. this.updateLayout();
  61. },
  62. inAnimation: function() {
  63. this.updateLayout();
  64. },
  65. },
  66. })
  67. class TextPage extends Vue {
  68. toggleLayout = false;
  69. showStatusBar = false;
  70. clickControl = true;
  71. background = null;
  72. page1 = null;
  73. page2 = null;
  74. statusBar = null;
  75. statusBarClickable = null;
  76. lastBook = null;
  77. bookPos = 0;
  78. bookPosSeen = null;
  79. fontStyle = null;
  80. fontSize = null;
  81. fontName = null;
  82. fontWeight = null;
  83. inAnimation = false;
  84. meta = null;
  85. created() {
  86. this.drawHelper = new DrawHelper();
  87. this.commit = this.$store.commit;
  88. this.dispatch = this.$store.dispatch;
  89. this.config = this.$store.state.config;
  90. this.reader = this.$store.state.reader;
  91. this.debouncedStartClickRepeat = _.debounce((x, y) => {
  92. this.startClickRepeat(x, y);
  93. }, 800);
  94. this.debouncedPrepareNextPage = _.debounce(() => {
  95. this.prepareNextPage();
  96. }, 100);
  97. this.debouncedDrawStatusBar = _.throttle(() => {
  98. this.drawStatusBar();
  99. }, 60);
  100. this.debouncedLoadSettings = _.debounce(() => {
  101. this.loadSettings();
  102. }, 50);
  103. this.debouncedUpdatePage = _.debounce(async(lines) => {
  104. if (!this.pageChangeAnimation)
  105. this.toggleLayout = !this.toggleLayout;
  106. else {
  107. this.page2 = this.page1;
  108. this.toggleLayout = true;
  109. }
  110. if (this.toggleLayout)
  111. this.page1 = this.drawHelper.drawPage(lines);
  112. else
  113. this.page2 = this.drawHelper.drawPage(lines);
  114. await this.doPageAnimation();
  115. }, 10);
  116. this.$root.$on('resize', async() => {
  117. this.$nextTick(this.onResize);
  118. await utils.sleep(500);
  119. this.$nextTick(this.onResize);
  120. });
  121. }
  122. mounted() {
  123. this.context = this.$refs.offscreenCanvas.getContext('2d');
  124. }
  125. hex2rgba(hex, alpha = 1) {
  126. const [r, g, b] = hex.match(/\w\w/g).map(x => parseInt(x, 16));
  127. return `rgba(${r},${g},${b},${alpha})`;
  128. }
  129. calcDrawProps() {
  130. const wideLetter = 'Щ';
  131. //preloaded fonts
  132. this.fontList = [`12px ${this.fontName}`];
  133. //widths
  134. this.realWidth = this.$refs.main.clientWidth;
  135. this.realHeight = this.$refs.main.clientHeight;
  136. this.$refs.layoutEvents.style.width = this.realWidth + 'px';
  137. this.$refs.layoutEvents.style.height = this.realHeight + 'px';
  138. const dual = (this.dualPageMode ? 2 : 1);
  139. this.boxW = this.realWidth - 2*this.indentLR;
  140. this.w = this.boxW/dual - (this.dualPageMode ? 2*this.dualIndentLR : 0);
  141. this.scrollHeight = this.realHeight - (this.showStatusBar ? this.statusBarHeight : 0);
  142. this.h = this.scrollHeight - 2*this.indentTB;
  143. this.lineHeight = this.fontSize + this.lineInterval;
  144. this.pageRowsCount = 1 + Math.floor((this.h - this.lineHeight + this.lineInterval/2)/this.lineHeight);
  145. this.pageLineCount = (this.dualPageMode ? this.pageRowsCount*2 : this.pageRowsCount)
  146. //stuff
  147. this.currentAnimation = '';
  148. this.pageChangeDirectionDown = true;
  149. this.fontShift = this.fontVertShift/100;
  150. this.textShift = this.textVertShift/100 + this.fontShift;
  151. //statusBar
  152. this.$refs.statusBar.style.left = '0px';
  153. this.$refs.statusBar.style.top = (this.statusBarTop ? 1 : this.realHeight - this.statusBarHeight) + 'px';
  154. this.statusBarColor = this.hex2rgba(this.textColor || '#000000', this.statusBarColorAlpha);
  155. //drawHelper
  156. this.drawHelper.realWidth = this.realWidth;
  157. this.drawHelper.realHeight = this.realHeight;
  158. this.drawHelper.lastBook = this.lastBook;
  159. this.drawHelper.book = this.book;
  160. this.drawHelper.parsed = this.parsed;
  161. this.drawHelper.pageRowsCount = this.pageRowsCount;
  162. this.drawHelper.pageLineCount = this.pageLineCount;
  163. this.drawHelper.dualPageMode = this.dualPageMode;
  164. this.drawHelper.dualIndentLR = this.dualIndentLR;
  165. this.drawHelper.dualDivWidth = this.dualDivWidth;
  166. this.drawHelper.dualDivHeight = this.dualDivHeight;
  167. this.drawHelper.dualDivColor = this.hex2rgba(this.textColor || '#000000', this.dualDivColorAlpha);
  168. this.drawHelper.dualDivStrokeFill = this.dualDivStrokeFill;
  169. this.drawHelper.dualDivStrokeGap = this.dualDivStrokeGap;
  170. this.drawHelper.backgroundColor = this.backgroundColor;
  171. this.drawHelper.statusBarColor = this.statusBarColor;
  172. this.drawHelper.fontStyle = this.fontStyle;
  173. this.drawHelper.fontWeight = this.fontWeight;
  174. this.drawHelper.fontSize = this.fontSize;
  175. this.drawHelper.fontName = this.fontName;
  176. this.drawHelper.fontShift = this.fontShift;
  177. this.drawHelper.textColor = this.textColor;
  178. this.drawHelper.textShift = this.textShift;
  179. this.drawHelper.p = this.p;
  180. this.drawHelper.boxW = this.boxW;
  181. this.drawHelper.w = this.w;
  182. this.drawHelper.h = this.h;
  183. this.drawHelper.indentLR = this.indentLR;
  184. this.drawHelper.textAlignJustify = this.textAlignJustify;
  185. this.drawHelper.lineHeight = this.lineHeight;
  186. this.drawHelper.context = this.context;
  187. //альтернатива context.measureText
  188. if (!this.context.measureText(wideLetter).width) {
  189. const ctx = this.$refs.measureWidth;
  190. this.drawHelper.measureText = function(text, style) {
  191. ctx.innerText = text;
  192. ctx.style.font = this.fontByStyle(style);
  193. return ctx.clientWidth;
  194. };
  195. this.drawHelper.measureTextFont = function(text, font) {
  196. ctx.innerText = text;
  197. ctx.style.font = font;
  198. return ctx.clientWidth;
  199. }
  200. }
  201. //statusBar
  202. this.statusBarClickable = this.drawHelper.statusBarClickable(this.statusBarTop, this.statusBarHeight);
  203. //parsed
  204. if (this.parsed) {
  205. let wideLine = wideLetter;
  206. if (!this.drawHelper.measureText(wideLine, {}))
  207. throw new Error('Ошибка measureText');
  208. while (this.drawHelper.measureText(wideLine, {}) < this.w) wideLine += wideLetter;
  209. this.parsed.setSettings({
  210. p: this.p,
  211. w: this.w,
  212. font: this.font,
  213. fontSize: this.fontSize,
  214. wordWrap: this.wordWrap,
  215. cutEmptyParagraphs: this.cutEmptyParagraphs,
  216. addEmptyParagraphs: this.addEmptyParagraphs,
  217. maxWordLength: wideLine.length - 1,
  218. lineHeight: this.lineHeight,
  219. showImages: this.showImages,
  220. showInlineImagesInCenter: this.showInlineImagesInCenter,
  221. imageHeightLines: this.imageHeightLines,
  222. imageFitWidth: this.imageFitWidth,
  223. compactTextPerc: this.compactTextPerc,
  224. testWidth: 0,
  225. measureText: this.drawHelper.measureText.bind(this.drawHelper),
  226. });
  227. }
  228. //scrolling page
  229. const pageSpace = this.scrollHeight - this.pageRowsCount*this.lineHeight;
  230. let top = pageSpace/2;
  231. if (this.showStatusBar)
  232. top += this.statusBarHeight*(this.statusBarTop ? 1 : 0);
  233. let page1 = this.$refs.scrollBox1.style;
  234. let page2 = this.$refs.scrollBox2.style;
  235. page1.perspective = page2.perspective = '3072px';
  236. page1.width = page2.width = this.boxW + this.indentLR + 'px';
  237. page1.height = page2.height = this.scrollHeight - (pageSpace > 0 ? pageSpace : 0) + 'px';
  238. page1.top = page2.top = top + 'px';
  239. page1.left = page2.left = this.indentLR + 'px';
  240. page1 = this.$refs.scrollingPage1.style;
  241. page2 = this.$refs.scrollingPage2.style;
  242. page1.width = page2.width = this.boxW + this.indentLR + 'px';
  243. page1.height = page2.height = this.scrollHeight + this.lineHeight + 'px';
  244. }
  245. async checkLoadedFonts() {
  246. let loaded = await Promise.all(this.fontList.map(font => document.fonts.check(font)));
  247. if (loaded.some(r => !r)) {
  248. await Promise.all(this.fontList.map(font => document.fonts.load(font)));
  249. }
  250. }
  251. async loadFonts() {
  252. this.fontsLoading = true;
  253. let close = null;
  254. (async() => {
  255. await utils.sleep(500);
  256. if (this.fontsLoading)
  257. close = this.$root.notify.info('Загрузка шрифта &nbsp;<i class="la la-snowflake icon-rotate" style="font-size: 150%"></i>');
  258. })();
  259. if (!this.fontsLoaded)
  260. this.fontsLoaded = {};
  261. //загрузка дин.шрифта
  262. const loaded = this.fontsLoaded[this.fontCssUrl];
  263. if (this.fontCssUrl && !loaded) {
  264. loadCSS(this.fontCssUrl);
  265. this.fontsLoaded[this.fontCssUrl] = 1;
  266. }
  267. try {
  268. await this.checkLoadedFonts();
  269. } catch (e) {
  270. this.$root.notify.error('Некоторые шрифты не удалось загрузить', 'Ошибка загрузки');
  271. }
  272. this.fontsLoading = false;
  273. if (close)
  274. close();
  275. }
  276. getSettings() {
  277. const settings = this.settings;
  278. for (let prop in rstore.settingDefaults) {
  279. this[prop] = settings[prop];
  280. }
  281. const wf = this.webFontName;
  282. const i = _.findIndex(rstore.webFonts, ['name', wf]);
  283. if (wf && i >= 0) {
  284. this.fontName = wf;
  285. this.fontCssUrl = rstore.webFonts[i].css;
  286. this.fontVertShift = settings.fontShifts[wf] || 0;
  287. }
  288. }
  289. async calcPropsAndLoadFonts(omitLoadFonts) {
  290. this.calcDrawProps();
  291. this.setBackground();
  292. if (!omitLoadFonts)
  293. await this.loadFonts();
  294. if (omitLoadFonts) {
  295. this.draw();
  296. } else {
  297. // ширина шрифта некоторое время выдается неверно,
  298. // не удалось событийно отловить этот момент, поэтому костыль
  299. while (this.checkingFont) {
  300. this.stopCheckingFont = true;
  301. await utils.sleep(100);
  302. }
  303. this.checkingFont = true;
  304. this.stopCheckingFont = false;
  305. try {
  306. const parsed = this.parsed;
  307. let i = 0;
  308. const t = 'Это тестовый текст. Его ширина выдается системой неправильно некоторое время.';
  309. let twprev = 0;
  310. //5 секунд проверяем изменения шрифта
  311. while (!this.stopCheckingFont && i++ < 50 && this.parsed === parsed) {
  312. const tw = this.drawHelper.measureText(t, {});
  313. if (tw !== twprev) {
  314. this.parsed.setSettings({testWidth: tw});
  315. this.draw();
  316. twprev = tw;
  317. }
  318. await utils.sleep(100);
  319. }
  320. } finally {
  321. this.checkingFont = false;
  322. }
  323. }
  324. }
  325. loadSettings() {
  326. (async() => {
  327. let fontName = this.fontName;
  328. this.getSettings();
  329. await this.calcPropsAndLoadFonts(fontName == this.fontName);
  330. })();
  331. }
  332. showBook() {
  333. this.$refs.main.focus();
  334. this.toggleLayout = false;
  335. this.updateLayout();
  336. this.book = null;
  337. this.meta = null;
  338. this.parsed = null;
  339. this.linesUp = null;
  340. this.linesDown = null;
  341. this.statusBarMessage = '';
  342. this.getSettings();
  343. this.calcDrawProps();
  344. this.draw();// пока не загрузили, очистим канвас
  345. if (this.lastBook) {
  346. (async() => {
  347. try {
  348. //подождем ленивый парсинг
  349. this.stopLazyParse = true;
  350. while (this.doingLazyParse) await utils.sleep(10);
  351. const isParsed = await bookManager.hasBookParsed(this.lastBook);
  352. if (!isParsed) {
  353. return;
  354. }
  355. this.book = await bookManager.getBook(this.lastBook);
  356. this.meta = bookManager.metaOnly(this.book);
  357. const bt = utils.getBookTitle(this.meta.fb2);
  358. this.title = bt.fullTitle;
  359. this.$root.$emit('set-app-title', this.title);
  360. this.parsed = this.book.parsed;
  361. this.page1 = null;
  362. this.page2 = null;
  363. this.statusBar = null;
  364. await this.stopTextScrolling();
  365. await this.calcPropsAndLoadFonts();
  366. this.refreshTime();
  367. if (this.lazyParseEnabled)
  368. this.lazyParsePara();
  369. } catch (e) {
  370. this.$root.stdDialog.alert(e.message, 'Ошибка', {color: 'negative'});
  371. }
  372. })();
  373. }
  374. }
  375. updateLayout() {
  376. if (this.inAnimation) {
  377. this.$refs.scrollBox1.style.visibility = 'visible';
  378. this.$refs.scrollBox2.style.visibility = 'visible';
  379. } else if (this.toggleLayout) {
  380. this.$refs.scrollBox1.style.visibility = 'visible';
  381. this.$refs.scrollBox2.style.visibility = 'hidden';
  382. } else {
  383. this.$refs.scrollBox1.style.visibility = 'hidden';
  384. this.$refs.scrollBox2.style.visibility = 'visible';
  385. }
  386. }
  387. setBackground() {
  388. this.background = `<div class="layout ${this.wallpaper}" style="width: ${this.realWidth}px; height: ${this.realHeight}px;` +
  389. ` background-color: ${this.backgroundColor}"></div>`;
  390. }
  391. async onResize() {
  392. try {
  393. this.calcDrawProps();
  394. this.setBackground();
  395. this.draw();
  396. } catch (e) {
  397. //
  398. }
  399. }
  400. get settings() {
  401. return this.$store.state.reader.settings;
  402. }
  403. get font() {
  404. return `${this.fontStyle} ${this.fontWeight} ${this.fontSize}px ${this.fontName}`;
  405. }
  406. onPage1TransitionEnd() {
  407. if (this.resolveTransition1Finish)
  408. this.resolveTransition1Finish();
  409. }
  410. onPage2TransitionEnd() {
  411. if (this.resolveTransition2Finish)
  412. this.resolveTransition2Finish();
  413. }
  414. startSearch(needle) {
  415. this.drawHelper.needle = needle;
  416. this.drawHelper.searching = true;
  417. this.draw();
  418. }
  419. stopSearch() {
  420. this.drawHelper.searching = false;
  421. this.draw();
  422. }
  423. generateWaitingFunc(waitingHandlerName, stopPropertyName) {
  424. const func = (timeout) => {
  425. return new Promise((resolve, reject) => { (async() => {
  426. this[waitingHandlerName] = resolve;
  427. let wait = (timeout + 201)/100;
  428. while (wait > 0 && !this[stopPropertyName]) {
  429. wait--;
  430. await utils.sleep(100);
  431. }
  432. resolve();
  433. })().catch(reject); });
  434. };
  435. return func;
  436. }
  437. async startTextScrolling() {
  438. if (this.doingScrolling || !this.book || !this.parsed.textLength || !this.linesDown || this.pageLineCount < 1 ||
  439. this.linesDown.length <= this.pageLineCount || this.dualPageMode) {
  440. this.doStopScrolling();
  441. return;
  442. }
  443. //ждем анимацию
  444. while (this.inAnimation) await utils.sleep(10);
  445. this.stopScrolling = false;
  446. this.doingScrolling = true;
  447. const transitionFinish = this.generateWaitingFunc('resolveTransition1Finish', 'stopScrolling');
  448. if (!this.toggleLayout)
  449. this.page1 = this.page2;
  450. this.toggleLayout = true;
  451. await this.$nextTick();
  452. await utils.sleep(50);
  453. this.cachedPos = -1;
  454. this.draw();
  455. const page = this.$refs.scrollingPage1;
  456. let i = 0;
  457. while (!this.stopScrolling) {
  458. page.style.transition = `${this.scrollingDelay}ms ${this.scrollingType}`;
  459. page.style.transform = `translateY(-${this.lineHeight}px)`;
  460. if (i > 0) {
  461. this.doDown();
  462. if (this.linesDown.length <= this.pageLineCount + 1) {
  463. this.stopScrolling = true;
  464. }
  465. }
  466. await transitionFinish(this.scrollingDelay);
  467. page.style.transition = '';
  468. page.style.transform = 'none';
  469. page.offsetHeight;
  470. i++;
  471. }
  472. this.resolveTransition1Finish = null;
  473. this.doingScrolling = false;
  474. this.doStopScrolling();
  475. this.draw();
  476. }
  477. async stopTextScrolling() {
  478. this.stopScrolling = true;
  479. const page = this.$refs.scrollingPage1;
  480. page.style.transition = '';
  481. page.style.transform = 'none';
  482. page.offsetHeight;
  483. while (this.doingScrolling) await utils.sleep(10);
  484. }
  485. draw() {
  486. //scrolling
  487. if (this.doingScrolling) {
  488. this.currentAnimation = '';
  489. if (this.cachedPos == this.bookPos) {
  490. this.linesDown = this.linesCached.linesDown;
  491. this.linesUp = this.linesCached.linesUp;
  492. this.page1 = this.pageCached;
  493. } else {
  494. const lines = this.getLines(this.bookPos);
  495. this.linesDown = lines.linesDown;
  496. this.linesUp = lines.linesUp;
  497. this.page1 = this.drawHelper.drawPage(lines.linesDown, true);
  498. }
  499. //caching next
  500. if (this.cachedPageTimer)
  501. clearTimeout(this.cachedPageTimer);
  502. this.cachedPageTimer = setTimeout(() => {
  503. if (this.linesDown && this.linesDown.length > this.pageLineCount && this.pageLineCount > 0) {
  504. this.cachedPos = this.linesDown[1].begin;
  505. this.linesCached = this.getLines(this.cachedPos);
  506. this.pageCached = this.drawHelper.drawPage(this.linesCached.linesDown, true);
  507. }
  508. this.cachedPageTimer = null;
  509. }, 20);
  510. this.debouncedDrawStatusBar();
  511. return;
  512. }
  513. //check
  514. if (this.w < minLayoutWidth) {
  515. this.page1 = null;
  516. this.page2 = null;
  517. this.statusBar = null;
  518. return;
  519. }
  520. if (this.book && this.bookPos > 0 && this.bookPos >= this.parsed.textLength) {
  521. this.doEnd(true);
  522. return;
  523. }
  524. //fast draw prepared
  525. if (!this.pageChangeAnimation && this.pageChangeDirectionDown && this.pagePrepared && this.bookPos == this.bookPosPrepared) {
  526. this.toggleLayout = !this.toggleLayout;
  527. this.linesDown = this.linesDownNext;
  528. this.linesUp = this.linesUpNext;
  529. } else {//normal debounced draw
  530. const lines = this.getLines(this.bookPos);
  531. this.linesDown = lines.linesDown;
  532. this.linesUp = lines.linesUp;
  533. this.debouncedUpdatePage(lines.linesDown);
  534. }
  535. this.pagePrepared = false;
  536. if (!this.pageChangeAnimation)
  537. this.debouncedPrepareNextPage();
  538. this.debouncedDrawStatusBar();
  539. if (this.book && this.linesDown && this.linesDown.length < this.pageLineCount) {
  540. this.doEnd(true);
  541. return;
  542. }
  543. }
  544. onPage1AnimationEnd() {
  545. if (this.resolveAnimation1Finish)
  546. this.resolveAnimation1Finish();
  547. }
  548. onPage2AnimationEnd() {
  549. if (this.resolveAnimation2Finish)
  550. this.resolveAnimation2Finish();
  551. }
  552. async doPageAnimation() {
  553. if (this.currentAnimation && !this.inAnimation) {
  554. this.inAnimation = true;
  555. const animation1Finish = this.generateWaitingFunc('resolveAnimation1Finish', 'stopAnimation');
  556. const animation2Finish = this.generateWaitingFunc('resolveAnimation2Finish', 'stopAnimation');
  557. const transition1Finish = this.generateWaitingFunc('resolveTransition1Finish', 'stopAnimation');
  558. const transition2Finish = this.generateWaitingFunc('resolveTransition2Finish', 'stopAnimation');
  559. const duration = Math.round(3000*(1 - this.pageChangeAnimationSpeed/100));
  560. let page1 = this.$refs.scrollingPage1;
  561. let page2 = this.$refs.scrollingPage2;
  562. switch (this.currentAnimation) {
  563. case 'thaw':
  564. await this.drawHelper.doPageAnimationThaw(page1, page2,
  565. duration, this.pageChangeDirectionDown, animation1Finish);
  566. break;
  567. case 'blink':
  568. await this.drawHelper.doPageAnimationBlink(page1, page2,
  569. duration, this.pageChangeDirectionDown, animation1Finish, animation2Finish);
  570. break;
  571. case 'rightShift':
  572. await this.drawHelper.doPageAnimationRightShift(page1, page2,
  573. duration, this.pageChangeDirectionDown, transition1Finish);
  574. break;
  575. case 'downShift':
  576. page1.style.height = this.scrollHeight + 'px';
  577. page2.style.height = this.scrollHeight + 'px';
  578. await this.drawHelper.doPageAnimationDownShift(page1, page2,
  579. duration, this.pageChangeDirectionDown, transition1Finish);
  580. page1.style.height = this.scrollHeight + this.lineHeight + 'px';
  581. page2.style.height = this.scrollHeight + this.lineHeight + 'px';
  582. break;
  583. case 'rotate':
  584. await this.drawHelper.doPageAnimationRotate(page1, page2,
  585. duration, this.pageChangeDirectionDown, transition1Finish, transition2Finish);
  586. break;
  587. case 'flip':
  588. await this.drawHelper.doPageAnimationFlip(page1, page2,
  589. duration, this.pageChangeDirectionDown, transition1Finish, transition2Finish, this.backgroundColor);
  590. break;
  591. }
  592. this.resolveAnimation1Finish = null;
  593. this.resolveAnimation2Finish = null;
  594. this.resolveTransition1Finish = null;
  595. this.resolveTransition2Finish = null;
  596. page1.style.animation = '';
  597. page2.style.animation = '';
  598. page1.style.transition = '';
  599. page1.style.transform = 'none';
  600. page1.offsetHeight;
  601. page2.style.transition = '';
  602. page2.style.transform = 'none';
  603. page2.offsetHeight;
  604. this.currentAnimation = '';
  605. this.pageChangeDirectionDown = false;//true только если PgDown
  606. this.inAnimation = false;
  607. this.stopAnimation = false;
  608. }
  609. }
  610. getLines(bookPos) {
  611. if (!this.parsed || this.pageLineCount < 1)
  612. return {};
  613. return {
  614. linesDown: this.parsed.getLines(bookPos, 2*this.pageLineCount),
  615. linesUp: this.parsed.getLines(bookPos, -2*this.pageLineCount)
  616. };
  617. }
  618. drawStatusBar(message) {
  619. if (this.w < minLayoutWidth) {
  620. this.statusBar = null;
  621. return;
  622. }
  623. if (this.showStatusBar && this.linesDown && this.pageLineCount > 0) {
  624. const lines = this.linesDown;
  625. let i = this.pageLineCount;
  626. if (this.keepLastToFirst)
  627. i--;
  628. i = (i > lines.length - 1 ? lines.length - 1 : i);
  629. if (i >= 0) {
  630. if (!message)
  631. message = this.statusBarMessage;
  632. if (!message)
  633. message = this.title;
  634. //check image num
  635. let imageNum = 0;
  636. const len = (lines.length > 2 ? 2 : lines.length);
  637. loop:
  638. for (let j = 0; j < len; j++) {
  639. const line = lines[j];
  640. for (const part of line.parts) {
  641. if (part.image) {
  642. imageNum = part.image.num;
  643. break loop;
  644. }
  645. }
  646. }
  647. //drawing
  648. this.statusBar = this.drawHelper.drawStatusBar(this.statusBarTop, this.statusBarHeight,
  649. lines[i].end, this.parsed.textLength, message, imageNum, this.parsed.images.length);
  650. this.bookPosSeen = lines[i].end;
  651. }
  652. } else {
  653. this.statusBar = '';
  654. }
  655. }
  656. blinkCachedLoadMessage(state) {
  657. if (state === 'finish') {
  658. this.statusBarMessage = '';
  659. } else if (state) {
  660. this.statusBarMessage = 'Книга загружена из кэша';
  661. } else {
  662. this.statusBarMessage = ' ';
  663. }
  664. this.drawStatusBar();
  665. }
  666. async lazyParsePara() {
  667. if (!this.parsed || this.doingLazyParse)
  668. return;
  669. this.doingLazyParse = true;
  670. let j = 0;
  671. let k = 0;
  672. let prevPerc = 0;
  673. this.stopLazyParse = false;
  674. for (let i = 0; i < this.parsed.para.length; i++) {
  675. j++;
  676. if (j > 1) {
  677. await utils.sleep(1);
  678. j = 0;
  679. }
  680. if (this.stopLazyParse)
  681. break;
  682. this.parsed.parsePara(i);
  683. k++;
  684. if (k > 100) {
  685. let perc = Math.round(i/this.parsed.para.length*100);
  686. if (perc != prevPerc)
  687. this.drawStatusBar(`Обработка текста ${perc}%`);
  688. prevPerc = perc;
  689. k = 0;
  690. }
  691. }
  692. this.drawStatusBar();
  693. this.doingLazyParse = false;
  694. }
  695. async refreshTime() {
  696. if (!this.timeRefreshing) {
  697. this.timeRefreshing = true;
  698. await utils.sleep(60*1000);
  699. if (this.book && this.parsed.textLength) {
  700. this.debouncedDrawStatusBar();
  701. }
  702. this.timeRefreshing = false;
  703. this.refreshTime();
  704. }
  705. }
  706. prepareNextPage() {
  707. // подготовка следующей страницы заранее
  708. if (!this.book || !this.parsed.textLength || !this.linesDown || this.pageLineCount < 1)
  709. return;
  710. let i = this.pageLineCount;
  711. if (this.keepLastToFirst)
  712. i--;
  713. if (i >= 0 && this.linesDown.length > i) {
  714. this.bookPosPrepared = this.linesDown[i].begin;
  715. const lines = this.getLines(this.bookPosPrepared);
  716. this.linesDownNext = lines.linesDown;
  717. this.linesUpNext = lines.linesUp;
  718. if (this.toggleLayout)
  719. this.page2 = this.drawHelper.drawPage(lines.linesDown);//наоборот
  720. else
  721. this.page1 = this.drawHelper.drawPage(lines.linesDown);
  722. this.pagePrepared = true;
  723. }
  724. }
  725. doDown() {
  726. if (this.linesDown && this.linesDown.length > this.pageLineCount && this.pageLineCount > 0) {
  727. this.bookPos = this.linesDown[1].begin;
  728. }
  729. }
  730. doUp() {
  731. if (this.linesUp && this.linesUp.length > 1 && this.pageLineCount > 0) {
  732. this.bookPos = this.linesUp[1].begin;
  733. }
  734. }
  735. doPageDown() {
  736. if (this.linesDown && this.pageLineCount > 0) {
  737. let i = this.pageLineCount;
  738. if (this.keepLastToFirst)
  739. i--;
  740. if (i >= 0 && this.linesDown.length >= 2*i + (this.keepLastToFirst ? 1 : 0)) {
  741. this.currentAnimation = this.pageChangeAnimation;
  742. this.pageChangeDirectionDown = true;
  743. this.bookPos = this.linesDown[i].begin;
  744. } else
  745. this.doEnd();
  746. }
  747. }
  748. doPageUp() {
  749. if (this.linesUp && this.pageLineCount > 0) {
  750. let i = this.pageLineCount;
  751. if (this.keepLastToFirst)
  752. i--;
  753. i = (i > this.linesUp.length - 1 ? this.linesUp.length - 1 : i);
  754. if (i >= 0 && this.linesUp.length > i) {
  755. this.currentAnimation = this.pageChangeAnimation;
  756. this.pageChangeDirectionDown = false;
  757. this.bookPos = this.linesUp[i].begin;
  758. }
  759. }
  760. }
  761. doHome() {
  762. this.currentAnimation = this.pageChangeAnimation;
  763. this.pageChangeDirectionDown = false;
  764. this.bookPos = 0;
  765. }
  766. doEnd(noAni) {
  767. if (this.parsed.para.length && this.pageLineCount > 0) {
  768. let i = this.parsed.para.length - 1;
  769. let lastPos = this.parsed.para[i].offset + this.parsed.para[i].length - 1;
  770. const lines = this.parsed.getLines(lastPos, -this.pageLineCount);
  771. if (lines) {
  772. i = this.pageLineCount - 1;
  773. i = (i > lines.length - 1 ? lines.length - 1 : i);
  774. if (!noAni)
  775. this.currentAnimation = this.pageChangeAnimation;
  776. this.pageChangeDirectionDown = true;
  777. this.bookPos = lines[i].begin;
  778. }
  779. }
  780. }
  781. doToolBarToggle(event) {
  782. this.$emit('do-action', {action: 'switchToolbar', event});
  783. }
  784. doScrollingToggle() {
  785. this.$emit('do-action', {action: 'scrolling', event});
  786. }
  787. doFullScreenToggle() {
  788. this.$emit('do-action', {action: 'fullScreen', event});
  789. }
  790. doStopScrolling() {
  791. this.$emit('do-action', {action: 'stopScrolling', event});
  792. }
  793. async doFontSizeInc() {
  794. if (!this.settingsChanging) {
  795. this.settingsChanging = true;
  796. const newSize = (this.settings.fontSize + 1 < 200 ? this.settings.fontSize + 1 : 100);
  797. this.commit('reader/setSettings', {fontSize: newSize});
  798. await utils.sleep(50);
  799. this.settingsChanging = false;
  800. }
  801. }
  802. async doFontSizeDec() {
  803. if (!this.settingsChanging) {
  804. this.settingsChanging = true;
  805. const newSize = (this.settings.fontSize - 1 > 5 ? this.settings.fontSize - 1 : 5);
  806. this.commit('reader/setSettings', {fontSize: newSize});
  807. await utils.sleep(50);
  808. this.settingsChanging = false;
  809. }
  810. }
  811. async doScrollingSpeedUp() {
  812. if (!this.settingsChanging) {
  813. this.settingsChanging = true;
  814. const newDelay = (this.settings.scrollingDelay - 50 > 1 ? this.settings.scrollingDelay - 50 : 1);
  815. this.commit('reader/setSettings', {scrollingDelay: newDelay});
  816. await utils.sleep(50);
  817. this.settingsChanging = false;
  818. }
  819. }
  820. async doScrollingSpeedDown() {
  821. if (!this.settingsChanging) {
  822. this.settingsChanging = true;
  823. const newDelay = (this.settings.scrollingDelay + 50 < 10000 ? this.settings.scrollingDelay + 50 : 10000);
  824. this.commit('reader/setSettings', {scrollingDelay: newDelay});
  825. await utils.sleep(50);
  826. this.settingsChanging = false;
  827. }
  828. }
  829. async startClickRepeat(pointX, pointY) {
  830. this.repX = pointX;
  831. this.repY = pointY;
  832. if (!this.repInit && this.repDoing) {
  833. this.repInit = true;
  834. let delay = 400;
  835. while (this.repDoing) {
  836. this.handleClick(pointX, pointY);
  837. await utils.sleep(delay);
  838. if (delay > 15)
  839. delay *= 0.8;
  840. }
  841. this.repInit = false;
  842. }
  843. }
  844. endClickRepeat() {
  845. this.repDoing = false;
  846. }
  847. onTouchStart(event) {
  848. if (!this.$isMobileDevice)
  849. return;
  850. this.endClickRepeat();
  851. if (event.touches.length == 1) {
  852. const touch = event.touches[0];
  853. const rect = event.target.getBoundingClientRect();
  854. const x = touch.pageX - rect.left;
  855. const y = touch.pageY - rect.top;
  856. const hc = this.handleClick(x, y, new Set(['Menu']));
  857. if (hc) {
  858. if (hc != 'Menu') {
  859. this.repDoing = true;
  860. this.debouncedStartClickRepeat(x, y);
  861. } else {
  862. this.startTouch = {x, y};
  863. }
  864. }
  865. }
  866. }
  867. onTouchMove(event) {
  868. if (this.startTouch) {
  869. event.preventDefault();
  870. }
  871. }
  872. onTouchEnd(event) {
  873. if (!this.$isMobileDevice)
  874. return;
  875. this.endClickRepeat();
  876. if (event.changedTouches.length == 1) {
  877. const touch = event.changedTouches[0];
  878. const rect = event.target.getBoundingClientRect();
  879. const x = touch.pageX - rect.left;
  880. const y = touch.pageY - rect.top;
  881. if (this.startTouch) {
  882. const dy = this.startTouch.y - y;
  883. const dx = this.startTouch.x - x;
  884. const moveDelta = 30;
  885. const touchDelta = 15;
  886. if (dy > 0 && Math.abs(dy) >= moveDelta && Math.abs(dy) > Math.abs(dx)) {
  887. //движение вверх
  888. this.doFullScreenToggle();
  889. } else if (dy < 0 && Math.abs(dy) >= moveDelta && Math.abs(dy) > Math.abs(dx)) {
  890. //движение вниз
  891. this.doScrollingToggle();
  892. } else if (dx > 0 && Math.abs(dx) >= moveDelta && Math.abs(dy) < Math.abs(dx)) {
  893. //движение влево
  894. this.doScrollingSpeedDown();
  895. } else if (dx < 0 && Math.abs(dx) >= moveDelta && Math.abs(dy) < Math.abs(dx)) {
  896. //движение вправо
  897. this.doScrollingSpeedUp();
  898. } else if (Math.abs(dy) < touchDelta && Math.abs(dx) < touchDelta) {
  899. this.doToolBarToggle(event);
  900. }
  901. this.startTouch = null;
  902. }
  903. }
  904. }
  905. onTouchCancel() {
  906. if (!this.$isMobileDevice)
  907. return;
  908. this.endClickRepeat();
  909. }
  910. onMouseDown(event) {
  911. if (this.$isMobileDevice)
  912. return;
  913. this.endClickRepeat();
  914. if (event.button == 0) {
  915. const hc = this.handleClick(event.offsetX, event.offsetY);
  916. if (hc && hc != 'Menu') {
  917. this.repDoing = true;
  918. this.debouncedStartClickRepeat(event.offsetX, event.offsetY);
  919. }
  920. } else if (event.button == 1) {
  921. this.doScrollingToggle();
  922. } else if (event.button == 2) {
  923. this.doToolBarToggle(event);
  924. }
  925. }
  926. onMouseUp() {
  927. if (this.$isMobileDevice)
  928. return;
  929. this.endClickRepeat();
  930. }
  931. onMouseWheel(event) {
  932. if (this.$isMobileDevice)
  933. return;
  934. if (event.deltaY > 0) {
  935. this.doDown();
  936. } else if (event.deltaY < 0) {
  937. this.doUp();
  938. }
  939. }
  940. onStatusBarClick() {
  941. const url = this.meta.url;
  942. if (url && url.indexOf('disk://') != 0) {
  943. window.open(url, '_blank');
  944. } else {
  945. this.$root.stdDialog.alert('Оригинал недоступен, т.к. файл книги был загружен с локального диска.', ' ', {color: 'info'});
  946. }
  947. }
  948. getClickAction(pointX, pointY) {
  949. const w = pointX/this.realWidth*100;
  950. const h = pointY/this.realHeight*100;
  951. let action = '';
  952. loops: {
  953. for (const x in clickMap) {
  954. for (const y in clickMap[x]) {
  955. if (w < x && h < y) {
  956. action = clickMap[x][y];
  957. break loops;
  958. }
  959. }
  960. }
  961. }
  962. return action;
  963. }
  964. handleClick(pointX, pointY, exclude) {
  965. const action = this.getClickAction(pointX, pointY);
  966. if (!exclude || !exclude.has(action)) {
  967. switch (action) {
  968. case 'Down' ://Down
  969. this.doDown();
  970. break;
  971. case 'Up' ://Up
  972. this.doUp();
  973. break;
  974. case 'PgDown' ://PgDown
  975. this.doPageDown();
  976. break;
  977. case 'PgUp' ://PgUp
  978. this.doPageUp();
  979. break;
  980. case 'Menu' :
  981. this.doToolBarToggle();
  982. break;
  983. default :
  984. // Nothing
  985. }
  986. }
  987. return action;
  988. }
  989. }
  990. //-----------------------------------------------------------------------------
  991. </script>
  992. <style scoped>
  993. .main {
  994. flex: 1;
  995. margin: 0;
  996. padding: 0;
  997. overflow: hidden;
  998. position: relative;
  999. min-width: 200px;
  1000. }
  1001. .layout {
  1002. margin: 0;
  1003. padding: 0;
  1004. position: absolute;
  1005. z-index: 10;
  1006. }
  1007. .over-hidden {
  1008. overflow: hidden;
  1009. }
  1010. .on-top {
  1011. z-index: 100;
  1012. }
  1013. .back {
  1014. z-index: 5;
  1015. }
  1016. .events {
  1017. z-index: 20;
  1018. background-color: rgba(0,0,0,0);
  1019. }
  1020. </style>
  1021. <style>
  1022. .paper1 {
  1023. background: url("images/paper1.jpg") center;
  1024. background-size: cover;
  1025. }
  1026. .paper2 {
  1027. background: url("images/paper2.jpg") center;
  1028. background-size: cover;
  1029. }
  1030. .paper3 {
  1031. background: url("images/paper3.jpg") center;
  1032. background-size: cover;
  1033. }
  1034. .paper4 {
  1035. background: url("images/paper4.jpg") center;
  1036. background-size: cover;
  1037. }
  1038. .paper5 {
  1039. background: url("images/paper5.jpg") center;
  1040. background-size: cover;
  1041. }
  1042. .paper6 {
  1043. background: url("images/paper6.jpg") center;
  1044. background-size: cover;
  1045. }
  1046. .paper7 {
  1047. background: url("images/paper7.jpg") center;
  1048. background-size: cover;
  1049. }
  1050. .paper8 {
  1051. background: url("images/paper8.jpg") center;
  1052. background-size: cover;
  1053. }
  1054. .paper9 {
  1055. background: url("images/paper9.jpg");
  1056. }
  1057. @keyframes page1-animation-thaw {
  1058. 0% { opacity: 0; }
  1059. 100% { opacity: 1; }
  1060. }
  1061. @keyframes page2-animation-thaw {
  1062. 0% { opacity: 1; }
  1063. 100% { opacity: 0; }
  1064. }
  1065. </style>