TextPage.vue 40 KB

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