TextPage.vue 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287
  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. if (i > 0) {
  488. this.doDown();
  489. await utils.sleep(1);
  490. await this.$nextTick();
  491. if (this.linesDown.length <= this.pageLineCount + 1) {
  492. this.stopScrolling = true;
  493. }
  494. }
  495. page.style.transition = `${this.scrollingDelay}ms ${this.scrollingType}`;
  496. page.style.transform = `translateY(-${this.lineHeight}px)`;
  497. await transitionFinish(this.scrollingDelay);
  498. page.style.transition = '';
  499. page.style.transform = 'none';
  500. page.offsetHeight;
  501. i++;
  502. }
  503. this.resolveTransition1Finish = null;
  504. this.doingScrolling = false;
  505. this.doStopScrolling();
  506. this.draw();
  507. }
  508. async stopTextScrolling() {
  509. this.stopScrolling = true;
  510. const page = this.$refs.scrollingPage1;
  511. page.style.transition = '';
  512. page.style.transform = 'none';
  513. page.offsetHeight;
  514. while (this.doingScrolling) await utils.sleep(10);
  515. }
  516. draw() {
  517. //scrolling
  518. if (this.doingScrolling) {
  519. this.currentAnimation = '';
  520. if (this.cachedPos == this.bookPos) {
  521. this.linesDown = this.linesCached.linesDown;
  522. this.linesUp = this.linesCached.linesUp;
  523. this.page1 = this.pageCached;
  524. } else {
  525. const lines = this.getLines(this.bookPos);
  526. this.linesDown = lines.linesDown;
  527. this.linesUp = lines.linesUp;
  528. this.page1 = this.drawHelper.drawPage(lines.linesDown, true);
  529. }
  530. //caching next
  531. if (this.cachedPageTimer)
  532. clearTimeout(this.cachedPageTimer);
  533. this.cachedPageTimer = setTimeout(() => {
  534. if (this.linesDown && this.linesDown.length > this.pageLineCount && this.pageLineCount > 0) {
  535. this.cachedPos = this.linesDown[1].begin;
  536. this.linesCached = this.getLines(this.cachedPos);
  537. this.pageCached = this.drawHelper.drawPage(this.linesCached.linesDown, true);
  538. }
  539. this.cachedPageTimer = null;
  540. }, 20);
  541. this.debouncedDrawStatusBar();
  542. return;
  543. }
  544. //check
  545. if (this.w < minLayoutWidth) {
  546. this.page1 = null;
  547. this.page2 = null;
  548. this.statusBar = null;
  549. return;
  550. }
  551. if (this.book && this.bookPos > 0 && this.bookPos >= this.parsed.textLength) {
  552. this.doEnd(true, false);
  553. return;
  554. }
  555. const lines = this.getLines(this.bookPos);
  556. this.linesDown = lines.linesDown;
  557. this.linesUp = lines.linesUp;
  558. this.debouncedUpdatePage(lines.linesDown);
  559. this.debouncedDrawStatusBar();
  560. this.debouncedDrawPageDividerAndOrnament();
  561. if (this.book && this.linesDown && this.linesDown.length < this.pageLineCount) {
  562. this.doEnd(true, false);
  563. return;
  564. }
  565. }
  566. onPage1AnimationEnd() {
  567. if (this.resolveAnimation1Finish)
  568. this.resolveAnimation1Finish();
  569. }
  570. onPage2AnimationEnd() {
  571. if (this.resolveAnimation2Finish)
  572. this.resolveAnimation2Finish();
  573. }
  574. async doPageAnimation() {
  575. if (this.currentAnimation && !this.inAnimation) {
  576. this.inAnimation = true;
  577. const animation1Finish = this.generateWaitingFunc('resolveAnimation1Finish', 'stopAnimation');
  578. const animation2Finish = this.generateWaitingFunc('resolveAnimation2Finish', 'stopAnimation');
  579. const transition1Finish = this.generateWaitingFunc('resolveTransition1Finish', 'stopAnimation');
  580. const transition2Finish = this.generateWaitingFunc('resolveTransition2Finish', 'stopAnimation');
  581. const duration = Math.round(3000*(1 - this.pageChangeAnimationSpeed/100));
  582. let page1 = this.$refs.scrollingPage1;
  583. let page2 = this.$refs.scrollingPage2;
  584. switch (this.currentAnimation) {
  585. case 'thaw':
  586. await this.drawHelper.doPageAnimationThaw(page1, page2,
  587. duration, this.pageChangeDirectionDown, animation1Finish);
  588. break;
  589. case 'blink':
  590. await this.drawHelper.doPageAnimationBlink(page1, page2,
  591. duration, this.pageChangeDirectionDown, animation1Finish, animation2Finish);
  592. break;
  593. case 'rightShift':
  594. await this.drawHelper.doPageAnimationRightShift(page1, page2,
  595. duration, this.pageChangeDirectionDown, transition1Finish);
  596. break;
  597. case 'downShift':
  598. page1.style.height = this.scrollHeight + 'px';
  599. page2.style.height = this.scrollHeight + 'px';
  600. await this.drawHelper.doPageAnimationDownShift(page1, page2,
  601. duration, this.pageChangeDirectionDown, transition1Finish);
  602. page1.style.height = this.scrollHeight + this.lineHeight + 'px';
  603. page2.style.height = this.scrollHeight + this.lineHeight + 'px';
  604. break;
  605. case 'rotate':
  606. await this.drawHelper.doPageAnimationRotate(page1, page2,
  607. duration, this.pageChangeDirectionDown, transition1Finish, transition2Finish);
  608. break;
  609. case 'flip':
  610. await this.drawHelper.doPageAnimationFlip(page1, page2,
  611. duration, this.pageChangeDirectionDown, transition1Finish, transition2Finish, this.backgroundColor);
  612. break;
  613. }
  614. this.resolveAnimation1Finish = null;
  615. this.resolveAnimation2Finish = null;
  616. this.resolveTransition1Finish = null;
  617. this.resolveTransition2Finish = null;
  618. page1.style.animation = '';
  619. page2.style.animation = '';
  620. page1.style.transition = '';
  621. page1.style.transform = 'none';
  622. page1.offsetHeight;
  623. page2.style.transition = '';
  624. page2.style.transform = 'none';
  625. page2.offsetHeight;
  626. this.currentAnimation = '';
  627. this.pageChangeDirectionDown = false;//true только если PgDown
  628. this.inAnimation = false;
  629. this.stopAnimation = false;
  630. }
  631. }
  632. getLines(bookPos) {
  633. if (!this.parsed || this.pageLineCount < 1)
  634. return {};
  635. return {
  636. linesDown: this.parsed.getLines(bookPos, 2*this.pageLineCount),
  637. linesUp: this.parsed.getLines(bookPos, -2*this.pageLineCount)
  638. };
  639. }
  640. drawStatusBar(message) {
  641. if (this.w < minLayoutWidth) {
  642. this.statusBar = null;
  643. return;
  644. }
  645. if (this.showStatusBar && this.linesDown && this.pageLineCount > 0) {
  646. const lines = this.linesDown;
  647. let i = this.pageLineCount;
  648. if (this.keepLastToFirst)
  649. i--;
  650. i = (i > lines.length - 1 ? lines.length - 1 : i);
  651. if (i >= 0) {
  652. if (!message)
  653. message = this.statusBarMessage;
  654. if (!message)
  655. message = this.title;
  656. //check image num
  657. let imageNum = 0;
  658. const len = (lines.length > 2 ? 2 : lines.length);
  659. loop:
  660. for (let j = 0; j < len; j++) {
  661. const line = lines[j];
  662. for (const part of line.parts) {
  663. if (part.image) {
  664. imageNum = part.image.num;
  665. break loop;
  666. }
  667. }
  668. }
  669. //drawing
  670. this.statusBar = this.drawHelper.drawStatusBar(this.statusBarTop, this.statusBarHeight,
  671. lines[i].end, this.parsed.textLength, message, imageNum, this.parsed.images.length);
  672. this.bookPosSeen = lines[i].end;
  673. }
  674. } else {
  675. this.statusBar = '';
  676. }
  677. }
  678. drawPageDividerAndOrnament() {
  679. if (this.dualPageMode) {
  680. this.pageDivider = `<div class="layout" style="width: ${this.realWidth}px; height: ${this.scrollHeight}px; ` +
  681. `top: ${(this.showStatusBar && this.statusBarTop ? this.statusBarHeight + 1 : 0)}px; position: relative;">` +
  682. `<div class="fit row justify-center items-center no-wrap">` +
  683. `<div style="height: ${Math.round(this.scrollHeight*this.dualDivHeight/100)}px; width: ${this.dualDivWidth}px; ` +
  684. `box-shadow: 0 0 ${this.dualDivShadowWidth}px ${this.dualDivRgbaColor}; ` +
  685. `background-image: url(&quot;data:image/svg+xml;utf8,<svg width='100%' height='100%' xmlns='http://www.w3.org/2000/svg'>` +
  686. `<line x1='${this.dualDivWidth/2}' y1='0' x2='${this.dualDivWidth/2}' y2='100%' stroke='${this.dualDivRgbaColor}' ` +
  687. `stroke-width='${this.dualDivWidth}' stroke-dasharray='${this.dualDivStrokeFill} ${this.dualDivStrokeGap}'/>` +
  688. `</svg>&quot;);">` +
  689. `</div>` +
  690. `</div>` +
  691. `</div>`;
  692. } else {
  693. this.pageDivider = null;
  694. }
  695. }
  696. blinkCachedLoadMessage(state) {
  697. if (state === 'finish') {
  698. this.statusBarMessage = '';
  699. } else if (state) {
  700. this.statusBarMessage = 'Книга загружена из кэша';
  701. } else {
  702. this.statusBarMessage = ' ';
  703. }
  704. this.drawStatusBar();
  705. }
  706. async lazyParsePara() {
  707. if (!this.parsed || this.doingLazyParse)
  708. return;
  709. this.doingLazyParse = true;
  710. let j = 0;
  711. let k = 0;
  712. let prevPerc = 0;
  713. this.stopLazyParse = false;
  714. for (let i = 0; i < this.parsed.para.length; i++) {
  715. j++;
  716. if (j > 1) {
  717. await utils.sleep(1);
  718. j = 0;
  719. }
  720. if (this.stopLazyParse)
  721. break;
  722. this.parsed.parsePara(i);
  723. k++;
  724. if (k > 100) {
  725. let perc = Math.round(i/this.parsed.para.length*100);
  726. if (perc != prevPerc)
  727. this.drawStatusBar(`Обработка текста ${perc}%`);
  728. prevPerc = perc;
  729. k = 0;
  730. }
  731. }
  732. this.drawStatusBar();
  733. this.doingLazyParse = false;
  734. }
  735. async refreshTime() {
  736. if (!this.timeRefreshing) {
  737. this.timeRefreshing = true;
  738. await utils.sleep(60*1000);
  739. if (this.book && this.parsed.textLength) {
  740. this.debouncedDrawStatusBar();
  741. }
  742. this.timeRefreshing = false;
  743. this.refreshTime();
  744. }
  745. }
  746. doDown() {
  747. if (this.linesDown && this.linesDown.length > this.pageLineCount && this.pageLineCount > 0) {
  748. this.userBookPosChange = true;
  749. this.bookPos = this.linesDown[1].begin;
  750. }
  751. }
  752. doUp() {
  753. if (this.linesUp && this.linesUp.length > 1 && this.pageLineCount > 0) {
  754. this.userBookPosChange = true;
  755. this.bookPos = this.linesUp[1].begin;
  756. }
  757. }
  758. doPageDown() {
  759. if (this.linesDown && this.pageLineCount > 0) {
  760. let i = this.pageLineCount;
  761. if (this.keepLastToFirst)
  762. i--;
  763. if (i >= 0 && this.linesDown.length >= 2*i + (this.keepLastToFirst ? 1 : 0)) {
  764. this.currentAnimation = this.pageChangeAnimation;
  765. this.pageChangeDirectionDown = true;
  766. this.userBookPosChange = true;
  767. this.bookPos = this.linesDown[i].begin;
  768. } else
  769. this.doEnd();
  770. }
  771. }
  772. doPageUp() {
  773. if (this.linesUp && this.pageLineCount > 0) {
  774. let i = this.pageLineCount;
  775. if (this.keepLastToFirst)
  776. i--;
  777. i = (i > this.linesUp.length - 1 ? this.linesUp.length - 1 : i);
  778. if (i >= 0 && this.linesUp.length > i) {
  779. this.currentAnimation = this.pageChangeAnimation;
  780. this.pageChangeDirectionDown = false;
  781. this.userBookPosChange = true;
  782. this.bookPos = this.linesUp[i].begin;
  783. }
  784. }
  785. }
  786. doHome() {
  787. this.currentAnimation = this.pageChangeAnimation;
  788. this.pageChangeDirectionDown = false;
  789. this.userBookPosChange = true;
  790. this.bookPos = 0;
  791. }
  792. doEnd(noAni, isUser = true) {
  793. if (this.parsed.para.length && this.pageLineCount > 0) {
  794. let i = this.parsed.para.length - 1;
  795. let lastPos = this.parsed.para[i].offset + this.parsed.para[i].length - 1;
  796. const lines = this.parsed.getLines(lastPos, -this.pageLineCount);
  797. if (lines) {
  798. i = this.pageLineCount - 1;
  799. i = (i > lines.length - 1 ? lines.length - 1 : i);
  800. if (!noAni)
  801. this.currentAnimation = this.pageChangeAnimation;
  802. this.pageChangeDirectionDown = true;
  803. this.userBookPosChange = isUser;
  804. this.bookPos = lines[i].begin;
  805. }
  806. }
  807. }
  808. doToolBarToggle(event) {
  809. this.$emit('do-action', {action: 'switchToolbar', event});
  810. }
  811. doScrollingToggle() {
  812. this.$emit('do-action', {action: 'scrolling', event});
  813. }
  814. doFullScreenToggle() {
  815. this.$emit('do-action', {action: 'fullScreen', event});
  816. }
  817. doStopScrolling() {
  818. this.$emit('do-action', {action: 'stopScrolling', event});
  819. }
  820. async doFontSizeInc() {
  821. if (!this.settingsChanging) {
  822. this.settingsChanging = true;
  823. const newSize = (this.settings.fontSize + 1 < 200 ? this.settings.fontSize + 1 : 100);
  824. this.commit('reader/setSettings', {fontSize: newSize});
  825. await utils.sleep(50);
  826. this.settingsChanging = false;
  827. }
  828. }
  829. async doFontSizeDec() {
  830. if (!this.settingsChanging) {
  831. this.settingsChanging = true;
  832. const newSize = (this.settings.fontSize - 1 > 5 ? this.settings.fontSize - 1 : 5);
  833. this.commit('reader/setSettings', {fontSize: newSize});
  834. await utils.sleep(50);
  835. this.settingsChanging = false;
  836. }
  837. }
  838. async doScrollingSpeedUp() {
  839. if (!this.settingsChanging) {
  840. this.settingsChanging = true;
  841. const newDelay = (this.settings.scrollingDelay - 50 > 1 ? this.settings.scrollingDelay - 50 : 1);
  842. this.commit('reader/setSettings', {scrollingDelay: newDelay});
  843. await utils.sleep(50);
  844. this.settingsChanging = false;
  845. }
  846. }
  847. async doScrollingSpeedDown() {
  848. if (!this.settingsChanging) {
  849. this.settingsChanging = true;
  850. const newDelay = (this.settings.scrollingDelay + 50 < 10000 ? this.settings.scrollingDelay + 50 : 10000);
  851. this.commit('reader/setSettings', {scrollingDelay: newDelay});
  852. await utils.sleep(50);
  853. this.settingsChanging = false;
  854. }
  855. }
  856. async startClickRepeat(pointX, pointY) {
  857. this.repX = pointX;
  858. this.repY = pointY;
  859. if (!this.repInit && this.repDoing) {
  860. this.repInit = true;
  861. let delay = 400;
  862. while (this.repDoing) {
  863. this.handleClick(pointX, pointY);
  864. await utils.sleep(delay);
  865. if (delay > 15)
  866. delay *= 0.8;
  867. }
  868. this.repInit = false;
  869. }
  870. }
  871. endClickRepeat() {
  872. this.repDoing = false;
  873. }
  874. onTouchStart(event) {
  875. if (!this.$root.isMobileDevice)
  876. return;
  877. this.endClickRepeat();
  878. if (event.touches.length == 1) {
  879. const touch = event.touches[0];
  880. const rect = event.target.getBoundingClientRect();
  881. const x = touch.pageX - rect.left;
  882. const y = touch.pageY - rect.top;
  883. const hc = this.handleClick(x, y, new Set(['Menu']));
  884. if (hc) {
  885. if (hc != 'Menu') {
  886. this.repDoing = true;
  887. this.debouncedStartClickRepeat(x, y);
  888. } else {
  889. this.startTouch = {x, y};
  890. }
  891. }
  892. }
  893. }
  894. onTouchMove(event) {
  895. if (this.startTouch) {
  896. event.preventDefault();
  897. }
  898. }
  899. onTouchEnd(event) {
  900. if (!this.$root.isMobileDevice)
  901. return;
  902. this.endClickRepeat();
  903. if (event.changedTouches.length == 1) {
  904. const touch = event.changedTouches[0];
  905. const rect = event.target.getBoundingClientRect();
  906. const x = touch.pageX - rect.left;
  907. const y = touch.pageY - rect.top;
  908. if (this.startTouch) {
  909. const dy = this.startTouch.y - y;
  910. const dx = this.startTouch.x - x;
  911. this.startTouch = null;
  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. if (this.touchMode) {
  928. this.touchMode = 2;
  929. return;
  930. }
  931. (async() => {
  932. this.touchMode = 1;
  933. let i = 20;
  934. while (i-- > 0 && this.touchMode === 1)
  935. await utils.sleep(10);
  936. if (this.touchMode === 1)
  937. this.doToolBarToggle();
  938. else
  939. this.doFullScreenToggle();
  940. this.touchMode = 0;
  941. })();
  942. }
  943. }
  944. }
  945. }
  946. onTouchCancel() {
  947. if (!this.$root.isMobileDevice)
  948. return;
  949. this.endClickRepeat();
  950. }
  951. onMouseDown(event) {
  952. if (this.$root.isMobileDevice)
  953. return;
  954. this.endClickRepeat();
  955. if (event.button == 0) {
  956. const hc = this.handleClick(event.offsetX, event.offsetY);
  957. if (hc && hc != 'Menu') {
  958. this.repDoing = true;
  959. this.debouncedStartClickRepeat(event.offsetX, event.offsetY);
  960. }
  961. } else if (event.button == 1) {
  962. this.doScrollingToggle();
  963. } else if (event.button == 2) {
  964. this.doToolBarToggle(event);
  965. }
  966. }
  967. onMouseUp() {
  968. if (this.$root.isMobileDevice)
  969. return;
  970. this.endClickRepeat();
  971. }
  972. onMouseWheel(event) {
  973. if (this.$root.isMobileDevice)
  974. return;
  975. if (event.deltaY > 0) {
  976. this.doDown();
  977. } else if (event.deltaY < 0) {
  978. this.doUp();
  979. }
  980. }
  981. onStatusBarClick() {
  982. const url = this.meta.url;
  983. if (url && url.indexOf('disk://') != 0) {
  984. window.open(url, '_blank');
  985. } else {
  986. this.$root.stdDialog.alert('Оригинал недоступен, т.к. файл книги был загружен с локального диска.', ' ', {color: 'info'});
  987. }
  988. }
  989. getClickAction(pointX, pointY) {
  990. const w = pointX/this.realWidth*100;
  991. const h = pointY/this.realHeight*100;
  992. let action = '';
  993. loops: {
  994. for (const x in clickMap) {
  995. for (const y in clickMap[x]) {
  996. if (w < x && h < y) {
  997. action = clickMap[x][y];
  998. break loops;
  999. }
  1000. }
  1001. }
  1002. }
  1003. return action;
  1004. }
  1005. handleClick(pointX, pointY, exclude) {
  1006. const action = this.getClickAction(pointX, pointY);
  1007. if (!exclude || !exclude.has(action)) {
  1008. switch (action) {
  1009. case 'Down' ://Down
  1010. this.doDown();
  1011. break;
  1012. case 'Up' ://Up
  1013. this.doUp();
  1014. break;
  1015. case 'PgDown' ://PgDown
  1016. this.doPageDown();
  1017. break;
  1018. case 'PgUp' ://PgUp
  1019. this.doPageUp();
  1020. break;
  1021. case 'Menu' :
  1022. this.doToolBarToggle();
  1023. break;
  1024. default :
  1025. // Nothing
  1026. }
  1027. }
  1028. return action;
  1029. }
  1030. copyText(event) {
  1031. //все это для того, чтобы правильно расставить переносы \n при копировании текста
  1032. //прямо с текущей страницы
  1033. //подготовка, вытаскиваем весь текст страницы
  1034. const lines = this.getLines(this.bookPos);
  1035. const decodedLines = [];
  1036. for (const line of lines.linesDown) {
  1037. let lineText = '';
  1038. for (const part of line.parts) {
  1039. lineText += part.text;
  1040. }
  1041. decodedLines.push({text: he.decode(lineText), first: line.first});
  1042. }
  1043. let i = 0;
  1044. const findDecoded = (line) => {
  1045. for (let j = i; j < decodedLines.length; j++) {
  1046. const decoded = decodedLines[j];
  1047. if (decoded.text.indexOf(line) >= 0) {
  1048. i = j;
  1049. return decoded;
  1050. }
  1051. }
  1052. return;
  1053. }
  1054. const selection = document.getSelection();
  1055. const splitted = selection.toString().split(/[\n\r]/);
  1056. let filtered = '';
  1057. //формируем filtered, учитывая переносы из decodedLines
  1058. for (const line of splitted) {
  1059. const found = findDecoded(line);
  1060. if (found && found.first) {
  1061. filtered += (filtered ? '\n' : '') + line;
  1062. } else {
  1063. filtered += (filtered ? '\r ' : '') + line;
  1064. }
  1065. }
  1066. //маленькие хитрости, убираем переносы по слогам
  1067. filtered = filtered.replace(/-\r /g, '').replace(/\r /g, ' ');
  1068. event.clipboardData.setData('text/plain', filtered);
  1069. }
  1070. }
  1071. export default vueComponent(TextPage);
  1072. //-----------------------------------------------------------------------------
  1073. </script>
  1074. <style scoped>
  1075. .main {
  1076. flex: 1;
  1077. margin: 0;
  1078. padding: 0;
  1079. overflow: hidden;
  1080. position: relative;
  1081. min-width: 200px;
  1082. }
  1083. .layout {
  1084. margin: 0;
  1085. padding: 0;
  1086. position: absolute;
  1087. z-index: 10;
  1088. }
  1089. .over-hidden {
  1090. overflow: hidden;
  1091. }
  1092. .on-top {
  1093. z-index: 100;
  1094. }
  1095. .back {
  1096. z-index: 5;
  1097. }
  1098. .events {
  1099. z-index: 20;
  1100. background-color: rgba(0,0,0,0);
  1101. }
  1102. </style>