TextPage.vue 40 KB

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