TextPage.vue 40 KB

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