TextPage.vue 43 KB

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