TextPage.vue 41 KB

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