TextPage.vue 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  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 sleep(50);
  364. const page = this.$refs.scrollingPage;
  365. let i = 0;
  366. while (!this.stopScrolling) {
  367. page.style.transition = `${this.scrollingDelay}ms ${this.scrollingType}`;
  368. page.style.transform = `translateY(-${this.lineHeight}px)`;
  369. if (i > 0) {
  370. this.doDown();
  371. if (this.linesDown.length <= this.pageLineCount + 1) {
  372. this.stopScrolling = true;
  373. }
  374. }
  375. await transitionFinish(this.scrollingDelay + 201);
  376. page.style.transition = '';
  377. page.style.transform = 'none';
  378. page.offsetHeight;
  379. i++;
  380. }
  381. this.resolveTransitionFinish = null;
  382. this.doingScrolling = false;
  383. this.$emit('stop-scrolling');
  384. }
  385. async stopTextScrolling() {
  386. this.stopScrolling = true;
  387. const page = this.$refs.scrollingPage;
  388. page.style.transition = '';
  389. page.style.transform = 'none';
  390. page.offsetHeight;
  391. while (this.doingScrolling) await sleep(10);
  392. }
  393. draw() {
  394. if (this.doingScrolling) {
  395. const lines = this.getLines(this.bookPos);
  396. this.linesDown = lines.linesDown;
  397. this.linesUp = lines.linesUp;
  398. this.page1 = this.drawPage(lines.linesDown);
  399. this.debouncedDrawStatusBar();
  400. return;
  401. }
  402. if (this.w < minLayoutWidth) {
  403. this.page1 = null;
  404. this.page2 = null;
  405. this.statusBar = null;
  406. return;
  407. }
  408. if (this.book && this.bookPos > 0 && this.bookPos >= this.parsed.textLength) {
  409. this.doEnd();
  410. return;
  411. }
  412. if (this.pageChangeDirectionDown && this.pagePrepared && this.bookPos == this.bookPosPrepared) {
  413. this.toggleLayout = !this.toggleLayout;
  414. this.linesDown = this.linesDownNext;
  415. this.linesUp = this.linesUpNext;
  416. this.doPageTransition();
  417. } else {
  418. const lines = this.getLines(this.bookPos);
  419. this.linesDown = lines.linesDown;
  420. this.linesUp = lines.linesUp;
  421. /*if (this.toggleLayout)
  422. this.page1 = this.drawPage(lines.linesDown);
  423. else
  424. this.page2 = this.drawPage(lines.linesDown);*/
  425. this.debouncedUpdatePage(lines.linesDown);
  426. }
  427. this.pagePrepared = false;
  428. this.debouncedPrepareNextPage();
  429. this.debouncedDrawStatusBar();
  430. if (this.book && this.linesDown && this.linesDown.length < this.pageLineCount)
  431. this.doEnd();
  432. }
  433. doPageTransition() {
  434. if (this.currentTransition) {
  435. //this.currentTransition
  436. //this.pageChangeTransitionSpeed
  437. //this.pageChangeDirectionDown
  438. //curr to next transition
  439. //пока заглушка
  440. }
  441. this.currentTransition = '';
  442. this.pageChangeDirectionDown = false;//true только если PgDown
  443. }
  444. getLines(bookPos) {
  445. if (!this.parsed || this.pageLineCount < 1)
  446. return {};
  447. return {
  448. linesDown: this.parsed.getLines(bookPos, 2*this.pageLineCount),
  449. linesUp: this.parsed.getLines(bookPos, -2*this.pageLineCount)
  450. };
  451. }
  452. drawPage(lines) {
  453. if (!this.lastBook || this.pageLineCount < 1 || !this.book || !lines || !this.parsed.textLength)
  454. return '';
  455. const spaceWidth = this.measureText(' ', {});
  456. let out = `<div class="layout" style="width: ${this.realWidth}px; height: ${this.realHeight}px;` +
  457. ` color: ${this.textColor}">`;
  458. let len = lines.length;
  459. len = (len > this.pageLineCount + 1 ? this.pageLineCount + 1 : len);
  460. let y = this.fontSize*this.textShift;
  461. for (let i = 0; i < len; i++) {
  462. const line = lines[i];
  463. /* line:
  464. {
  465. begin: Number,
  466. end: Number,
  467. first: Boolean,
  468. last: Boolean,
  469. parts: array of {
  470. style: {bold: Boolean, italic: Boolean, center: Boolean}
  471. text: String,
  472. }
  473. }*/
  474. let indent = line.first ? this.p : 0;
  475. let lineText = '';
  476. let center = false;
  477. let centerStyle = {};
  478. for (const part of line.parts) {
  479. lineText += part.text;
  480. center = center || part.style.center;
  481. if (part.style.center)
  482. centerStyle = part.style;
  483. }
  484. let filled = false;
  485. // если выравнивание по ширине включено
  486. if (this.textAlignJustify && !line.last && !center) {
  487. const words = lineText.split(' ');
  488. if (words.length > 1) {
  489. const spaceCount = words.length - 1;
  490. const space = (this.w - line.width + spaceWidth*spaceCount)/spaceCount;
  491. let x = indent;
  492. for (const part of line.parts) {
  493. const font = this.fontByStyle(part.style);
  494. let partWords = part.text.split(' ');
  495. for (let i = 0; i < partWords.length; i++) {
  496. let word = partWords[i];
  497. out += this.drawHelper.fillText(word, x, y, font);
  498. x += this.measureText(word, part.style) + (i < partWords.length - 1 ? space : 0);
  499. }
  500. }
  501. filled = true;
  502. }
  503. }
  504. // просто выводим текст
  505. if (!filled) {
  506. let x = indent;
  507. x = (center ? (this.w - this.measureText(lineText, centerStyle))/2 : x);
  508. for (const part of line.parts) {
  509. let text = part.text;
  510. const font = this.fontByStyle(part.style);
  511. out += this.drawHelper.fillText(text, x, y, font);
  512. x += this.measureText(text, part.style);
  513. }
  514. }
  515. y += this.lineHeight;
  516. }
  517. out += '</div>';
  518. return out;
  519. }
  520. drawStatusBar(message) {
  521. if (this.w < minLayoutWidth) {
  522. this.statusBar = null;
  523. return;
  524. }
  525. if (this.showStatusBar && this.linesDown && this.pageLineCount > 0) {
  526. const lines = this.linesDown;
  527. let i = this.pageLineCount;
  528. if (this.keepLastToFirst)
  529. i--;
  530. i = (i > lines.length - 1 ? lines.length - 1 : i);
  531. if (i >= 0) {
  532. if (!message)
  533. message = this.statusBarMessage;
  534. if (!message)
  535. message = this.title;
  536. this.statusBar = this.drawHelper.drawStatusBar(this.statusBarTop, this.statusBarHeight,
  537. lines[i].end, this.parsed.textLength, message);
  538. this.bookPosSeen = lines[i].end;
  539. }
  540. } else {
  541. this.statusBar = '';
  542. }
  543. }
  544. blinkCachedLoadMessage(state) {
  545. if (state === 'finish') {
  546. this.statusBarMessage = '';
  547. } else if (state) {
  548. this.statusBarMessage = 'Книга загружена из кеша';
  549. } else {
  550. this.statusBarMessage = ' ';
  551. }
  552. this.drawStatusBar();
  553. }
  554. async lazyParsePara() {
  555. if (!this.parsed || this.doingLazyParse)
  556. return;
  557. this.doingLazyParse = true;
  558. let j = 0;
  559. let k = 0;
  560. let prevPerc = 0;
  561. this.stopLazyParse = false;
  562. for (let i = 0; i < this.parsed.para.length; i++) {
  563. j++;
  564. if (j > 1) {
  565. await sleep(1);
  566. j = 0;
  567. }
  568. if (this.stopLazyParse)
  569. break;
  570. this.parsed.parsePara(i);
  571. k++;
  572. if (k > 100) {
  573. let perc = Math.round(i/this.parsed.para.length*100);
  574. if (perc != prevPerc)
  575. this.drawStatusBar(`Обработка текста ${perc}%`);
  576. prevPerc = perc;
  577. k = 0;
  578. }
  579. }
  580. this.drawStatusBar();
  581. this.doingLazyParse = false;
  582. }
  583. async refreshTime() {
  584. if (!this.timeRefreshing) {
  585. this.timeRefreshing = true;
  586. await sleep(60*1000);
  587. if (this.book && this.parsed.textLength) {
  588. this.debouncedDrawStatusBar();
  589. }
  590. this.timeRefreshing = false;
  591. this.refreshTime();
  592. }
  593. }
  594. prepareNextPage() {
  595. // подготовка следующей страницы заранее
  596. if (!this.book || !this.parsed.textLength || !this.linesDown || this.pageLineCount < 1)
  597. return;
  598. let i = this.pageLineCount;
  599. if (this.keepLastToFirst)
  600. i--;
  601. if (i >= 0 && this.linesDown.length > i) {
  602. this.bookPosPrepared = this.linesDown[i].begin;
  603. const lines = this.getLines(this.bookPosPrepared);
  604. this.linesDownNext = lines.linesDown;
  605. this.linesUpNext = lines.linesUp;
  606. if (this.toggleLayout)
  607. this.page2 = this.drawPage(lines.linesDown);//наоборот
  608. else
  609. this.page1 = this.drawPage(lines.linesDown);
  610. this.pagePrepared = true;
  611. }
  612. }
  613. doDown() {
  614. if (this.linesDown && this.linesDown.length > this.pageLineCount && this.pageLineCount > 0) {
  615. this.bookPos = this.linesDown[1].begin;
  616. }
  617. }
  618. doUp() {
  619. if (this.linesUp && this.linesUp.length > 1 && this.pageLineCount > 0) {
  620. this.bookPos = this.linesUp[1].begin;
  621. }
  622. }
  623. doPageDown() {
  624. if (this.linesDown && this.pageLineCount > 0) {
  625. let i = this.pageLineCount;
  626. if (this.keepLastToFirst)
  627. i--;
  628. if (i >= 0 && this.linesDown.length >= 2*i) {
  629. this.currentTransition = this.pageChangeTransition;
  630. this.pageChangeDirectionDown = true;
  631. this.bookPos = this.linesDown[i].begin;
  632. } else
  633. this.doEnd();
  634. }
  635. }
  636. doPageUp() {
  637. if (this.linesUp && this.pageLineCount > 0) {
  638. let i = this.pageLineCount;
  639. if (this.keepLastToFirst)
  640. i--;
  641. i = (i > this.linesUp.length - 1 ? this.linesUp.length - 1 : i);
  642. if (i >= 0 && this.linesUp.length > i) {
  643. this.currentTransition = this.pageChangeTransition;
  644. this.pageChangeDirectionDown = false;
  645. this.bookPos = this.linesUp[i].begin;
  646. }
  647. }
  648. }
  649. doHome() {
  650. this.bookPos = 0;
  651. }
  652. doEnd() {
  653. if (this.parsed.para.length && this.pageLineCount > 0) {
  654. let i = this.parsed.para.length - 1;
  655. let lastPos = this.parsed.para[i].offset + this.parsed.para[i].length - 1;
  656. const lines = this.parsed.getLines(lastPos, -this.pageLineCount);
  657. if (lines) {
  658. i = this.pageLineCount - 1;
  659. i = (i > lines.length - 1 ? lines.length - 1 : i);
  660. this.bookPos = lines[i].begin;
  661. }
  662. }
  663. }
  664. doToolBarToggle() {
  665. this.$emit('tool-bar-toggle');
  666. }
  667. keyHook(event) {
  668. //console.log(event.code);
  669. if (event.type == 'keydown') {
  670. switch (event.code) {
  671. case 'ArrowDown':
  672. this.doDown();
  673. break;
  674. case 'ArrowUp':
  675. this.doUp();
  676. break;
  677. case 'PageDown':
  678. case 'ArrowRight':
  679. case 'Space':
  680. this.doPageDown();
  681. break;
  682. case 'PageUp':
  683. case 'ArrowLeft':
  684. case 'Backspace':
  685. this.doPageUp();
  686. break;
  687. case 'Home':
  688. this.doHome();
  689. break;
  690. case 'End':
  691. this.doEnd();
  692. break;
  693. case 'Enter':
  694. case 'Backquote'://`
  695. case 'KeyF':
  696. this.$emit('full-screen-toogle');
  697. break;
  698. case 'Tab':
  699. this.doToolBarToggle();
  700. event.preventDefault();
  701. event.stopPropagation();
  702. break;
  703. }
  704. }
  705. }
  706. async startClickRepeat(pointX, pointY) {
  707. this.repX = pointX;
  708. this.repY = pointY;
  709. if (!this.repInit && this.repDoing) {
  710. this.repInit = true;
  711. let delay = 400;
  712. while (this.repDoing) {
  713. this.handleClick(pointX, pointY);
  714. await sleep(delay);
  715. if (delay > 15)
  716. delay *= 0.8;
  717. }
  718. this.repInit = false;
  719. }
  720. }
  721. endClickRepeat() {
  722. this.repDoing = false;
  723. }
  724. onTouchStart(event) {
  725. if (!this.mobile)
  726. return;
  727. this.endClickRepeat();
  728. if (event.touches.length == 1) {
  729. const touch = event.touches[0];
  730. const rect = event.target.getBoundingClientRect();
  731. const x = touch.pageX - rect.left;
  732. const y = touch.pageY - rect.top;
  733. if (this.handleClick(x, y)) {
  734. this.repDoing = true;
  735. this.debouncedStartClickRepeat(x, y);
  736. }
  737. }
  738. }
  739. onTouchEnd() {
  740. if (!this.mobile)
  741. return;
  742. this.endClickRepeat();
  743. }
  744. onTouchCancel() {
  745. if (!this.mobile)
  746. return;
  747. this.endClickRepeat();
  748. }
  749. onMouseDown(event) {
  750. if (this.mobile)
  751. return;
  752. this.endClickRepeat();
  753. if (event.button == 0) {
  754. if (this.handleClick(event.offsetX, event.offsetY)) {
  755. this.repDoing = true;
  756. this.debouncedStartClickRepeat(event.offsetX, event.offsetY);
  757. }
  758. } else if (event.button == 1) {
  759. this.$emit('scrolling-toggle');
  760. } else if (event.button == 2) {
  761. this.doToolBarToggle();
  762. }
  763. }
  764. onMouseUp() {
  765. if (this.mobile)
  766. return;
  767. this.endClickRepeat();
  768. }
  769. onMouseWheel(event) {
  770. if (this.mobile)
  771. return;
  772. if (event.deltaY > 0) {
  773. this.doDown();
  774. } else if (event.deltaY < 0) {
  775. this.doUp();
  776. }
  777. }
  778. onStatusBarClick() {
  779. window.open(this.meta.url, '_blank');
  780. }
  781. handleClick(pointX, pointY) {
  782. const mouseLegend = {
  783. 40: {30: 'PgUp', 100: 'PgDown'},
  784. 60: {40: 'Up', 60: 'Menu', 100: 'Down'},
  785. 100: {30: 'PgUp', 100: 'PgDown'}
  786. };
  787. const w = pointX/this.realWidth*100;
  788. const h = pointY/this.realHeight*100;
  789. let action = '';
  790. loops: {
  791. for (const x in mouseLegend) {
  792. for (const y in mouseLegend[x]) {
  793. if (w < x && h < y) {
  794. action = mouseLegend[x][y];
  795. break loops;
  796. }
  797. }
  798. }
  799. }
  800. switch (action) {
  801. case 'Down' ://Down
  802. this.doDown();
  803. break;
  804. case 'Up' ://Up
  805. this.doUp();
  806. break;
  807. case 'PgDown' ://PgDown
  808. this.doPageDown();
  809. break;
  810. case 'PgUp' ://PgUp
  811. this.doPageUp();
  812. break;
  813. case 'Menu' :
  814. this.doToolBarToggle();
  815. break;
  816. default :
  817. // Nothing
  818. }
  819. return (action && action != 'Menu');
  820. }
  821. }
  822. //-----------------------------------------------------------------------------
  823. </script>
  824. <style scoped>
  825. .main {
  826. flex: 1;
  827. margin: 0;
  828. padding: 0;
  829. overflow: hidden;
  830. position: relative;
  831. min-width: 200px;
  832. }
  833. .layout {
  834. margin: 0;
  835. padding: 0;
  836. position: absolute;
  837. z-index: 10;
  838. }
  839. .back {
  840. z-index: 5;
  841. }
  842. .events {
  843. z-index: 20;
  844. background-color: rgba(0,0,0,0);
  845. }
  846. </style>