TextPage.vue 36 KB

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