TextPage.vue 44 KB

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