TextPage.vue 42 KB

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