TextPage.vue 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  1. <template>
  2. <div ref="main" class="main">
  3. <div class="layout back">
  4. <div v-html="background"></div>
  5. <!-- img -->
  6. </div>
  7. <div v-show="toggleLayout" ref="scrollBox1" class="layout" style="overflow: hidden">
  8. <div ref="scrollingPage" class="layout" @transitionend="onScrollingTransitionEnd">
  9. <div v-html="page1"></div>
  10. </div>
  11. </div>
  12. <div v-show="!toggleLayout" ref="scrollBox2" class="layout" style="overflow: hidden">
  13. <div v-html="page2"></div>
  14. </div>
  15. <div v-show="showStatusBar" ref="statusBar" class="layout">
  16. <div v-html="statusBar"></div>
  17. </div>
  18. <div ref="layoutEvents" class="layout events" @mousedown.prevent.stop="onMouseDown" @mouseup.prevent.stop="onMouseUp"
  19. @wheel.prevent.stop="onMouseWheel"
  20. @touchstart.stop="onTouchStart" @touchend.stop="onTouchEnd" @touchcancel.prevent.stop="onTouchCancel"
  21. oncontextmenu="return false;">
  22. <div v-show="showStatusBar" v-html="statusBarClickable" @mousedown.prevent.stop @touchstart.stop
  23. @click.prevent.stop="onStatusBarClick"></div>
  24. <div v-show="fontsLoading" ref="fontsLoading"></div>
  25. </div>
  26. <!-- невидимым делать нельзя, вовремя не подгружаютя шрифты -->
  27. <canvas ref="offscreenCanvas" class="layout" style="width: 0px; height: 0px"></canvas>
  28. </div>
  29. </template>
  30. <script>
  31. //-----------------------------------------------------------------------------
  32. import Vue from 'vue';
  33. import Component from 'vue-class-component';
  34. import {loadCSS} from 'fg-loadcss';
  35. import _ from 'lodash';
  36. import {sleep} from '../../../share/utils';
  37. import bookManager from '../share/bookManager';
  38. import DrawHelper from './DrawHelper';
  39. import rstore from '../../../store/modules/reader';
  40. const minLayoutWidth = 100;
  41. export default @Component({
  42. watch: {
  43. bookPos: function(newValue) {
  44. this.debouncedEmitPosChange(newValue);
  45. this.draw();
  46. },
  47. settings: function() {
  48. this.debouncedLoadSettings();
  49. },
  50. },
  51. })
  52. class TextPage extends Vue {
  53. toggleLayout = false;
  54. showStatusBar = false;
  55. background = null;
  56. page1 = null;
  57. page2 = null;
  58. statusBar = null;
  59. statusBarClickable = null;
  60. fontsLoading = null;
  61. lastBook = null;
  62. bookPos = 0;
  63. fontStyle = null;
  64. fontSize = null;
  65. fontName = null;
  66. meta = null;
  67. created() {
  68. this.drawHelper = new DrawHelper();
  69. this.commit = this.$store.commit;
  70. this.dispatch = this.$store.dispatch;
  71. this.config = this.$store.state.config;
  72. this.reader = this.$store.state.reader;
  73. this.debouncedEmitPosChange = _.debounce((newValue) => {
  74. this.$emit('book-pos-changed', {bookPos: newValue, bookPosSeen: this.bookPosSeen});
  75. }, 1000);
  76. this.debouncedStartClickRepeat = _.debounce((x, y) => {
  77. this.startClickRepeat(x, y);
  78. }, 800);
  79. this.debouncedPrepareNextPage = _.debounce(() => {
  80. this.prepareNextPage();
  81. }, 100);
  82. this.debouncedDrawStatusBar = _.throttle(() => {
  83. this.drawStatusBar();
  84. }, 60);
  85. this.debouncedLoadSettings = _.debounce(() => {
  86. this.loadSettings();
  87. }, 50);
  88. this.debouncedUpdatePage = _.debounce((lines) => {
  89. this.toggleLayout = !this.toggleLayout;
  90. if (this.toggleLayout)
  91. this.page1 = this.drawPage(lines);
  92. else
  93. this.page2 = this.drawPage(lines);
  94. this.doPageTransition();
  95. }, 10);
  96. this.$root.$on('resize', () => {this.$nextTick(this.onResize)});
  97. this.mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent);
  98. /*
  99. const settings = Object.assign({}, this.settings);
  100. let updated = false;
  101. for (let prop in rstore.settingDefaults) {
  102. if (!settings.hasOwnProperty(prop)) {
  103. settings[prop] = rstore.settingDefaults[prop];
  104. updated = true;
  105. }
  106. }
  107. if (updated)
  108. this.commit('reader/setSettings', settings);
  109. */
  110. }
  111. mounted() {
  112. this.context = this.$refs.offscreenCanvas.getContext('2d');
  113. }
  114. hex2rgba(hex, alpha = 1) {
  115. const [r, g, b] = hex.match(/\w\w/g).map(x => parseInt(x, 16));
  116. return `rgba(${r},${g},${b},${alpha})`;
  117. }
  118. calcDrawProps() {
  119. //preloaded fonts
  120. this.fontList = [`12px ${this.fontName}`];
  121. //widths
  122. this.realWidth = this.$refs.main.clientWidth;
  123. this.realHeight = this.$refs.main.clientHeight;
  124. this.$refs.layoutEvents.style.width = this.realWidth + 'px';
  125. this.$refs.layoutEvents.style.height = this.realHeight + 'px';
  126. this.w = this.realWidth - 2*this.indentLR;
  127. this.h = this.realHeight - (this.showStatusBar ? this.statusBarHeight : 0) - 2*this.indentTB;
  128. this.lineHeight = this.fontSize + this.lineInterval;
  129. this.pageLineCount = 1 + Math.floor((this.h - this.fontSize)/this.lineHeight);
  130. if (this.parsed) {
  131. this.parsed.p = this.p;
  132. this.parsed.w = this.w;// px, ширина текста
  133. this.parsed.font = this.font;
  134. this.parsed.wordWrap = this.wordWrap;
  135. let t = '';
  136. while (this.measureText(t, {}) < this.w) t += 'Щ';
  137. this.parsed.maxWordLength = t.length - 1;
  138. this.parsed.measureText = this.measureText;
  139. }
  140. //сообщение "Загрузка шрифтов..."
  141. const flText = 'Загрузка шрифта...';
  142. this.$refs.fontsLoading.innerHTML = flText;
  143. const fontsLoadingStyle = this.$refs.fontsLoading.style;
  144. fontsLoadingStyle.position = 'absolute';
  145. fontsLoadingStyle.fontSize = this.fontSize + 'px';
  146. fontsLoadingStyle.top = (this.realHeight/2 - 2*this.fontSize) + 'px';
  147. fontsLoadingStyle.left = (this.realWidth - this.measureText(flText, {}))/2 + 'px';
  148. //stuff
  149. this.statusBarColor = this.hex2rgba(this.textColor || '#000000', this.statusBarColorAlpha);
  150. this.currentTransition = '';
  151. this.pageChangeDirectionDown = true;
  152. this.fontShift = this.fontVertShift/100;
  153. this.textShift = this.textVertShift/100 + this.fontShift;
  154. //drawHelper
  155. this.drawHelper.realWidth = this.realWidth;
  156. this.drawHelper.realHeight = this.realHeight;
  157. this.drawHelper.backgroundColor = this.backgroundColor;
  158. this.drawHelper.statusBarColor = this.statusBarColor;
  159. this.drawHelper.fontName = this.fontName;
  160. this.drawHelper.fontShift = this.fontShift;
  161. this.drawHelper.measureText = this.measureText;
  162. this.drawHelper.measureTextFont = this.measureTextFont;
  163. this.$refs.statusBar.style.left = '0px';
  164. this.$refs.statusBar.style.top = (this.statusBarTop ? 1 : this.realHeight - this.statusBarHeight) + 'px';
  165. this.statusBarClickable = this.drawHelper.statusBarClickable(this.statusBarTop, this.statusBarHeight);
  166. //scrolling page
  167. const pageDelta = this.h - (this.pageLineCount*this.lineHeight - this.lineInterval);
  168. let y = this.indentTB + pageDelta/2;
  169. if (this.showStatusBar)
  170. y += this.statusBarHeight*(this.statusBarTop ? 1 : 0);
  171. const page1 = this.$refs.scrollBox1;
  172. const page2 = this.$refs.scrollBox2;
  173. page1.style.width = this.w + 'px';
  174. page2.style.width = this.w + 'px';
  175. page1.style.height = (this.h - pageDelta) + 'px';
  176. page2.style.height = (this.h - pageDelta) + 'px';
  177. page1.style.top = y + 'px';
  178. page2.style.top = y + 'px';
  179. page1.style.left = this.indentLR + 'px';
  180. page2.style.left = this.indentLR + 'px';
  181. }
  182. measureText(text, style) {// eslint-disable-line no-unused-vars
  183. this.context.font = this.fontByStyle(style);
  184. return this.context.measureText(text).width;
  185. }
  186. measureTextFont(text, font) {// eslint-disable-line no-unused-vars
  187. this.context.font = font;
  188. return this.context.measureText(text).width;
  189. }
  190. async checkLoadedFonts() {
  191. let loaded = await Promise.all(this.fontList.map(font => document.fonts.check(font)));
  192. if (loaded.some(r => !r)) {
  193. loaded = await Promise.all(this.fontList.map(font => document.fonts.load(font)));
  194. if (loaded.some(r => !r.length))
  195. throw new Error('some font not loaded');
  196. }
  197. }
  198. async loadFonts() {
  199. this.fontsLoading = true;
  200. if (!this.fontsLoaded)
  201. this.fontsLoaded = {};
  202. //загрузка дин.шрифта
  203. const loaded = this.fontsLoaded[this.fontCssUrl];
  204. if (this.fontCssUrl && !loaded) {
  205. loadCSS(this.fontCssUrl);
  206. this.fontsLoaded[this.fontCssUrl] = 1;
  207. }
  208. const waitingTime = 10*1000;
  209. const delay = 100;
  210. let i = 0;
  211. //ждем шрифты
  212. while (i < waitingTime/delay) {
  213. i++;
  214. try {
  215. await this.checkLoadedFonts();
  216. i = waitingTime;
  217. } catch (e) {
  218. await sleep(delay);
  219. }
  220. }
  221. if (i !== waitingTime) {
  222. this.$notify.error({
  223. title: 'Ошибка загрузки',
  224. message: 'Некоторые шрифты не удалось загрузить'
  225. });
  226. }
  227. this.fontsLoading = false;
  228. }
  229. getSettings() {
  230. const settings = this.settings;
  231. for (let prop in rstore.settingDefaults) {
  232. this[prop] = settings[prop];
  233. }
  234. const wf = this.webFontName;
  235. const i = _.findIndex(rstore.webFonts, ['name', wf]);
  236. if (wf && i >= 0) {
  237. this.fontName = wf;
  238. this.fontCssUrl = rstore.webFonts[i].css;
  239. this.fontVertShift = settings.fontShifts[wf] || 0;
  240. }
  241. }
  242. async calcPropsAndLoadFonts(omitLoadFonts) {
  243. this.calcDrawProps();
  244. this.setBackground();
  245. if (!omitLoadFonts)
  246. await this.loadFonts();
  247. this.draw();
  248. // шрифты хрен знает когда подгружаются, поэтому
  249. const parsed = this.parsed;
  250. if (!parsed.force) {
  251. let i = 0;
  252. parsed.force = true;
  253. while (i < 10) {
  254. await sleep(1000);
  255. if (this.parsed != parsed)
  256. break;
  257. this.draw();
  258. i++;
  259. }
  260. parsed.force = false;
  261. }
  262. }
  263. loadSettings() {
  264. (async() => {
  265. let fontName = this.fontName;
  266. this.getSettings();
  267. await this.calcPropsAndLoadFonts(fontName == this.fontName);
  268. })();
  269. }
  270. showBook() {
  271. this.$refs.main.focus();
  272. this.toggleLayout = false;
  273. this.book = null;
  274. this.meta = null;
  275. this.fb2 = null;
  276. this.parsed = null;
  277. this.linesUp = null;
  278. this.linesDown = null;
  279. this.getSettings();
  280. this.calcDrawProps();
  281. this.draw();// пока не загрузили, очистим канвас
  282. if (this.lastBook) {
  283. (async() => {
  284. //подождем ленивый парсинг
  285. this.stopLazyParse = true;
  286. while (this.doingLazyParse) await sleep(10);
  287. const isParsed = await bookManager.hasBookParsed(this.lastBook);
  288. if (!isParsed) {
  289. return;
  290. }
  291. this.book = await bookManager.getBook(this.lastBook);
  292. this.meta = bookManager.metaOnly(this.book);
  293. this.fb2 = this.meta.fb2;
  294. const authorName = _.compact([
  295. this.fb2.lastName,
  296. this.fb2.firstName,
  297. this.fb2.middleName
  298. ]).join(' ');
  299. this.title = _.compact([
  300. authorName,
  301. this.fb2.bookTitle
  302. ]).join(' - ');
  303. this.$root.$emit('set-app-title', this.title);
  304. this.parsed = this.book.parsed;
  305. this.page1 = null;
  306. this.page2 = null;
  307. this.statusBar = null;
  308. await this.stopTextScrolling();
  309. this.calcPropsAndLoadFonts();
  310. this.refreshTime();
  311. if (this.lazyParseEnabled)
  312. this.lazyParsePara();
  313. })();
  314. }
  315. }
  316. setBackground() {
  317. this.background = `<div class="layout" style="width: ${this.realWidth}px; height: ${this.realHeight}px;` +
  318. ` background-color: ${this.backgroundColor}"></div>`;
  319. }
  320. async onResize() {
  321. this.page1 = null;
  322. this.page2 = null;
  323. this.statusBar = null;
  324. this.calcDrawProps();
  325. this.setBackground();
  326. this.draw();
  327. }
  328. get settings() {
  329. return this.$store.state.reader.settings;
  330. }
  331. get font() {
  332. return `${this.fontStyle} ${this.fontWeight} ${this.fontSize}px ${this.fontName}`;
  333. }
  334. fontByStyle(style) {
  335. return `${style.italic ? 'italic' : this.fontStyle} ${style.bold ? 'bold' : this.fontWeight} ${this.fontSize}px ${this.fontName}`;
  336. }
  337. onScrollingTransitionEnd() {
  338. if (this.resolveTransitionFinish)
  339. this.resolveTransitionFinish();
  340. }
  341. async startTextScrolling() {
  342. if (this.doingScrolling || !this.book || !this.parsed.textLength || !this.linesDown || this.pageLineCount < 1 ||
  343. this.linesDown.length <= this.pageLineCount) {
  344. this.$emit('stop-scrolling');
  345. return;
  346. }
  347. this.stopScrolling = false;
  348. this.doingScrolling = true;
  349. const transitionFinish = (timeout) => {
  350. return new Promise(async(resolve) => {
  351. this.resolveTransitionFinish = resolve;
  352. let wait = timeout/100;
  353. while (wait > 0 && !this.stopScrolling) {
  354. wait--;
  355. await sleep(100);
  356. }
  357. resolve();
  358. });
  359. };
  360. if (!this.toggleLayout)
  361. this.page1 = this.page2;
  362. this.toggleLayout = true;
  363. await this.$nextTick();
  364. await sleep(50);
  365. const page = this.$refs.scrollingPage;
  366. let i = 0;
  367. while (!this.stopScrolling) {
  368. page.style.transition = `${this.scrollingDelay}ms ${this.scrollingType}`;
  369. page.style.transform = `translateY(-${this.lineHeight}px)`;
  370. if (i > 0) {
  371. this.doDown();
  372. if (this.linesDown.length <= this.pageLineCount + 1) {
  373. this.stopScrolling = true;
  374. }
  375. }
  376. await transitionFinish(this.scrollingDelay + 201);
  377. page.style.transition = '';
  378. page.style.transform = 'none';
  379. page.offsetHeight;
  380. i++;
  381. }
  382. this.resolveTransitionFinish = null;
  383. this.doingScrolling = false;
  384. this.$emit('stop-scrolling');
  385. }
  386. async stopTextScrolling() {
  387. this.stopScrolling = true;
  388. const page = this.$refs.scrollingPage;
  389. page.style.transition = '';
  390. page.style.transform = 'none';
  391. page.offsetHeight;
  392. while (this.doingScrolling) await sleep(10);
  393. }
  394. draw() {
  395. if (this.doingScrolling) {
  396. const lines = this.getLines(this.bookPos);
  397. this.linesDown = lines.linesDown;
  398. this.linesUp = lines.linesUp;
  399. this.page1 = this.drawPage(lines.linesDown);
  400. this.debouncedDrawStatusBar();
  401. return;
  402. }
  403. if (this.w < minLayoutWidth) {
  404. this.page1 = null;
  405. this.page2 = null;
  406. this.statusBar = null;
  407. return;
  408. }
  409. if (this.book && this.bookPos > 0 && this.bookPos >= this.parsed.textLength) {
  410. this.doEnd();
  411. return;
  412. }
  413. if (this.pageChangeDirectionDown && this.pagePrepared && this.bookPos == this.bookPosPrepared) {
  414. this.toggleLayout = !this.toggleLayout;
  415. this.linesDown = this.linesDownNext;
  416. this.linesUp = this.linesUpNext;
  417. this.doPageTransition();
  418. } else {
  419. const lines = this.getLines(this.bookPos);
  420. this.linesDown = lines.linesDown;
  421. this.linesUp = lines.linesUp;
  422. /*if (this.toggleLayout)
  423. this.page1 = this.drawPage(lines.linesDown);
  424. else
  425. this.page2 = this.drawPage(lines.linesDown);*/
  426. this.debouncedUpdatePage(lines.linesDown);
  427. }
  428. this.pagePrepared = false;
  429. this.debouncedPrepareNextPage();
  430. this.debouncedDrawStatusBar();
  431. if (this.book && this.linesDown && this.linesDown.length < this.pageLineCount)
  432. this.doEnd();
  433. }
  434. doPageTransition() {
  435. if (this.currentTransition) {
  436. //this.currentTransition
  437. //this.pageChangeTransitionSpeed
  438. //this.pageChangeDirectionDown
  439. //curr to next transition
  440. //пока заглушка
  441. }
  442. this.currentTransition = '';
  443. this.pageChangeDirectionDown = false;//true только если PgDown
  444. }
  445. getLines(bookPos) {
  446. if (!this.parsed || this.pageLineCount < 1)
  447. return {};
  448. return {
  449. linesDown: this.parsed.getLines(bookPos, 2*this.pageLineCount),
  450. linesUp: this.parsed.getLines(bookPos, -2*this.pageLineCount)
  451. };
  452. }
  453. drawPage(lines) {
  454. if (!this.lastBook || this.pageLineCount < 1 || !this.book || !lines || !this.parsed.textLength)
  455. return '';
  456. const spaceWidth = this.measureText(' ', {});
  457. let out = `<div class="layout" style="width: ${this.realWidth}px; height: ${this.realHeight}px;` +
  458. ` color: ${this.textColor}">`;
  459. let len = lines.length;
  460. len = (len > this.pageLineCount + 1 ? this.pageLineCount + 1 : len);
  461. let y = this.fontSize*this.textShift;
  462. for (let i = 0; i < len; i++) {
  463. const line = lines[i];
  464. /* line:
  465. {
  466. begin: Number,
  467. end: Number,
  468. first: Boolean,
  469. last: Boolean,
  470. parts: array of {
  471. style: {bold: Boolean, italic: Boolean, center: Boolean}
  472. text: String,
  473. }
  474. }*/
  475. let indent = line.first ? this.p : 0;
  476. let lineText = '';
  477. let center = false;
  478. let centerStyle = {};
  479. for (const part of line.parts) {
  480. lineText += part.text;
  481. center = center || part.style.center;
  482. if (part.style.center)
  483. centerStyle = part.style;
  484. }
  485. let filled = false;
  486. // если выравнивание по ширине включено
  487. if (this.textAlignJustify && !line.last && !center) {
  488. const words = lineText.split(' ');
  489. if (words.length > 1) {
  490. const spaceCount = words.length - 1;
  491. const space = (this.w - line.width + spaceWidth*spaceCount)/spaceCount;
  492. let x = indent;
  493. for (const part of line.parts) {
  494. const font = this.fontByStyle(part.style);
  495. let partWords = part.text.split(' ');
  496. for (let i = 0; i < partWords.length; i++) {
  497. let word = partWords[i];
  498. out += this.drawHelper.fillText(word, x, y, font);
  499. x += this.measureText(word, part.style) + (i < partWords.length - 1 ? space : 0);
  500. }
  501. }
  502. filled = true;
  503. }
  504. }
  505. // просто выводим текст
  506. if (!filled) {
  507. let x = indent;
  508. x = (center ? (this.w - this.measureText(lineText, centerStyle))/2 : x);
  509. for (const part of line.parts) {
  510. let text = part.text;
  511. const font = this.fontByStyle(part.style);
  512. out += this.drawHelper.fillText(text, x, y, font);
  513. x += this.measureText(text, part.style);
  514. }
  515. }
  516. y += this.lineHeight;
  517. }
  518. out += '</div>';
  519. return out;
  520. }
  521. drawStatusBar(message) {
  522. if (this.w < minLayoutWidth) {
  523. this.statusBar = null;
  524. return;
  525. }
  526. if (this.showStatusBar && this.linesDown && this.pageLineCount > 0) {
  527. const lines = this.linesDown;
  528. let i = this.pageLineCount;
  529. if (this.keepLastToFirst)
  530. i--;
  531. i = (i > lines.length - 1 ? lines.length - 1 : i);
  532. if (i >= 0) {
  533. if (!message)
  534. message = this.statusBarMessage;
  535. if (!message)
  536. message = this.title;
  537. this.statusBar = this.drawHelper.drawStatusBar(this.statusBarTop, this.statusBarHeight,
  538. lines[i].end, this.parsed.textLength, message);
  539. this.bookPosSeen = lines[i].end;
  540. }
  541. } else {
  542. this.statusBar = '';
  543. }
  544. }
  545. blinkCachedLoadMessage(state) {
  546. if (state === 'finish') {
  547. this.statusBarMessage = '';
  548. } else if (state) {
  549. this.statusBarMessage = 'Книга загружена из кеша';
  550. } else {
  551. this.statusBarMessage = ' ';
  552. }
  553. this.drawStatusBar();
  554. }
  555. async lazyParsePara() {
  556. if (!this.parsed || this.doingLazyParse)
  557. return;
  558. this.doingLazyParse = true;
  559. let j = 0;
  560. let k = 0;
  561. let prevPerc = 0;
  562. this.stopLazyParse = false;
  563. for (let i = 0; i < this.parsed.para.length; i++) {
  564. j++;
  565. if (j > 1) {
  566. await sleep(1);
  567. j = 0;
  568. }
  569. if (this.stopLazyParse)
  570. break;
  571. this.parsed.parsePara(i);
  572. k++;
  573. if (k > 100) {
  574. let perc = Math.round(i/this.parsed.para.length*100);
  575. if (perc != prevPerc)
  576. this.drawStatusBar(`Обработка текста ${perc}%`);
  577. prevPerc = perc;
  578. k = 0;
  579. }
  580. }
  581. this.drawStatusBar();
  582. this.doingLazyParse = false;
  583. }
  584. async refreshTime() {
  585. if (!this.timeRefreshing) {
  586. this.timeRefreshing = true;
  587. await sleep(60*1000);
  588. if (this.book && this.parsed.textLength) {
  589. this.debouncedDrawStatusBar();
  590. }
  591. this.timeRefreshing = false;
  592. this.refreshTime();
  593. }
  594. }
  595. prepareNextPage() {
  596. // подготовка следующей страницы заранее
  597. if (!this.book || !this.parsed.textLength || !this.linesDown || this.pageLineCount < 1)
  598. return;
  599. let i = this.pageLineCount;
  600. if (this.keepLastToFirst)
  601. i--;
  602. if (i >= 0 && this.linesDown.length > i) {
  603. this.bookPosPrepared = this.linesDown[i].begin;
  604. const lines = this.getLines(this.bookPosPrepared);
  605. this.linesDownNext = lines.linesDown;
  606. this.linesUpNext = lines.linesUp;
  607. if (this.toggleLayout)
  608. this.page2 = this.drawPage(lines.linesDown);//наоборот
  609. else
  610. this.page1 = this.drawPage(lines.linesDown);
  611. this.pagePrepared = true;
  612. }
  613. }
  614. doDown() {
  615. if (this.linesDown && this.linesDown.length > this.pageLineCount && this.pageLineCount > 0) {
  616. this.bookPos = this.linesDown[1].begin;
  617. }
  618. }
  619. doUp() {
  620. if (this.linesUp && this.linesUp.length > 1 && this.pageLineCount > 0) {
  621. this.bookPos = this.linesUp[1].begin;
  622. }
  623. }
  624. doPageDown() {
  625. if (this.linesDown && this.pageLineCount > 0) {
  626. let i = this.pageLineCount;
  627. if (this.keepLastToFirst)
  628. i--;
  629. if (i >= 0 && this.linesDown.length >= 2*i) {
  630. this.currentTransition = this.pageChangeTransition;
  631. this.pageChangeDirectionDown = true;
  632. this.bookPos = this.linesDown[i].begin;
  633. } else
  634. this.doEnd();
  635. }
  636. }
  637. doPageUp() {
  638. if (this.linesUp && this.pageLineCount > 0) {
  639. let i = this.pageLineCount;
  640. if (this.keepLastToFirst)
  641. i--;
  642. i = (i > this.linesUp.length - 1 ? this.linesUp.length - 1 : i);
  643. if (i >= 0 && this.linesUp.length > i) {
  644. this.currentTransition = this.pageChangeTransition;
  645. this.pageChangeDirectionDown = false;
  646. this.bookPos = this.linesUp[i].begin;
  647. }
  648. }
  649. }
  650. doHome() {
  651. this.bookPos = 0;
  652. }
  653. doEnd() {
  654. if (this.parsed.para.length && this.pageLineCount > 0) {
  655. let i = this.parsed.para.length - 1;
  656. let lastPos = this.parsed.para[i].offset + this.parsed.para[i].length - 1;
  657. const lines = this.parsed.getLines(lastPos, -this.pageLineCount);
  658. if (lines) {
  659. i = this.pageLineCount - 1;
  660. i = (i > lines.length - 1 ? lines.length - 1 : i);
  661. this.bookPos = lines[i].begin;
  662. }
  663. }
  664. }
  665. doToolBarToggle() {
  666. this.$emit('tool-bar-toggle');
  667. }
  668. keyHook(event) {
  669. //console.log(event.code);
  670. if (event.type == 'keydown') {
  671. switch (event.code) {
  672. case 'ArrowDown':
  673. this.doDown();
  674. break;
  675. case 'ArrowUp':
  676. this.doUp();
  677. break;
  678. case 'PageDown':
  679. case 'ArrowRight':
  680. case 'Space':
  681. this.doPageDown();
  682. break;
  683. case 'PageUp':
  684. case 'ArrowLeft':
  685. case 'Backspace':
  686. this.doPageUp();
  687. break;
  688. case 'Home':
  689. this.doHome();
  690. break;
  691. case 'End':
  692. this.doEnd();
  693. break;
  694. case 'Enter':
  695. case 'Backquote'://`
  696. case 'KeyF':
  697. this.$emit('full-screen-toogle');
  698. break;
  699. case 'Tab':
  700. this.doToolBarToggle();
  701. event.preventDefault();
  702. event.stopPropagation();
  703. break;
  704. }
  705. }
  706. }
  707. async startClickRepeat(pointX, pointY) {
  708. this.repX = pointX;
  709. this.repY = pointY;
  710. if (!this.repInit && this.repDoing) {
  711. this.repInit = true;
  712. let delay = 400;
  713. while (this.repDoing) {
  714. this.handleClick(pointX, pointY);
  715. await sleep(delay);
  716. if (delay > 15)
  717. delay *= 0.8;
  718. }
  719. this.repInit = false;
  720. }
  721. }
  722. endClickRepeat() {
  723. this.repDoing = false;
  724. }
  725. onTouchStart(event) {
  726. if (!this.mobile)
  727. return;
  728. this.endClickRepeat();
  729. if (event.touches.length == 1) {
  730. const touch = event.touches[0];
  731. const rect = event.target.getBoundingClientRect();
  732. const x = touch.pageX - rect.left;
  733. const y = touch.pageY - rect.top;
  734. if (this.handleClick(x, y)) {
  735. this.repDoing = true;
  736. this.debouncedStartClickRepeat(x, y);
  737. }
  738. }
  739. }
  740. onTouchEnd() {
  741. if (!this.mobile)
  742. return;
  743. this.endClickRepeat();
  744. }
  745. onTouchCancel() {
  746. if (!this.mobile)
  747. return;
  748. this.endClickRepeat();
  749. }
  750. onMouseDown(event) {
  751. if (this.mobile)
  752. return;
  753. this.endClickRepeat();
  754. if (event.button == 0) {
  755. if (this.handleClick(event.offsetX, event.offsetY)) {
  756. this.repDoing = true;
  757. this.debouncedStartClickRepeat(event.offsetX, event.offsetY);
  758. }
  759. } else if (event.button == 1) {
  760. this.$emit('scrolling-toggle');
  761. } else if (event.button == 2) {
  762. this.doToolBarToggle();
  763. }
  764. }
  765. onMouseUp() {
  766. if (this.mobile)
  767. return;
  768. this.endClickRepeat();
  769. }
  770. onMouseWheel(event) {
  771. if (this.mobile)
  772. return;
  773. if (event.deltaY > 0) {
  774. this.doDown();
  775. } else if (event.deltaY < 0) {
  776. this.doUp();
  777. }
  778. }
  779. onStatusBarClick() {
  780. window.open(this.meta.url, '_blank');
  781. }
  782. handleClick(pointX, pointY) {
  783. const mouseLegend = {
  784. 40: {30: 'PgUp', 100: 'PgDown'},
  785. 60: {40: 'Up', 60: 'Menu', 100: 'Down'},
  786. 100: {30: 'PgUp', 100: 'PgDown'}
  787. };
  788. const w = pointX/this.realWidth*100;
  789. const h = pointY/this.realHeight*100;
  790. let action = '';
  791. loops: {
  792. for (const x in mouseLegend) {
  793. for (const y in mouseLegend[x]) {
  794. if (w < x && h < y) {
  795. action = mouseLegend[x][y];
  796. break loops;
  797. }
  798. }
  799. }
  800. }
  801. switch (action) {
  802. case 'Down' ://Down
  803. this.doDown();
  804. break;
  805. case 'Up' ://Up
  806. this.doUp();
  807. break;
  808. case 'PgDown' ://PgDown
  809. this.doPageDown();
  810. break;
  811. case 'PgUp' ://PgUp
  812. this.doPageUp();
  813. break;
  814. case 'Menu' :
  815. this.doToolBarToggle();
  816. break;
  817. default :
  818. // Nothing
  819. }
  820. return (action && action != 'Menu');
  821. }
  822. }
  823. //-----------------------------------------------------------------------------
  824. </script>
  825. <style scoped>
  826. .main {
  827. flex: 1;
  828. margin: 0;
  829. padding: 0;
  830. overflow: hidden;
  831. position: relative;
  832. min-width: 200px;
  833. }
  834. .layout {
  835. margin: 0;
  836. padding: 0;
  837. position: absolute;
  838. z-index: 10;
  839. }
  840. .back {
  841. z-index: 5;
  842. }
  843. .events {
  844. z-index: 20;
  845. background-color: rgba(0,0,0,0);
  846. }
  847. </style>