TextPage.vue 42 KB

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