TextPage.vue 40 KB

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