TextPage.vue 44 KB

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