TextPage.vue 42 KB

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