TextPage.vue 42 KB

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