TextPage.vue 40 KB

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