TextPage.vue 37 KB

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