TextPage.vue 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. <template>
  2. <div ref="main" class="main">
  3. <canvas v-show="canvasShowFirst" ref="canvasPrev" class="canvas" @mousedown.prevent.stop="onMouseDown" @mouseup.prevent.stop="onMouseUp"
  4. @wheel.prevent.stop="onMouseWheel"
  5. @touchstart.prevent.stop="onTouchStart" @touchend.prevent.stop="onTouchEnd"
  6. oncontextmenu="return false;">
  7. </canvas>
  8. <canvas v-show="!canvasShowFirst" ref="canvasNext" class="canvas" @mousedown.prevent.stop="onMouseDown" @mouseup.prevent.stop="onMouseUp"
  9. @wheel.prevent.stop="onMouseWheel"
  10. @touchstart.prevent.stop="onTouchStart" @touchend.prevent.stop="onTouchEnd"
  11. oncontextmenu="return false;">
  12. </canvas>
  13. </div>
  14. </template>
  15. <script>
  16. //-----------------------------------------------------------------------------
  17. import Vue from 'vue';
  18. import Component from 'vue-class-component';
  19. import _ from 'lodash';
  20. import {sleep} from '../../../share/utils';
  21. import bookManager from '../share/bookManager';
  22. import DrawHelper from './DrawHelper';
  23. export default @Component({
  24. watch: {
  25. bookPos: function(newValue) {
  26. this.debouncedEmitPosChange(newValue);
  27. this.draw();
  28. },
  29. },
  30. })
  31. class TextPage extends Vue {
  32. canvasShowFirst = false;
  33. lastBook = null;
  34. bookPos = 0;
  35. fontStyle = null;
  36. fontSize = null;
  37. fontName = null;
  38. created() {
  39. this.drawHelper = new DrawHelper();
  40. this.commit = this.$store.commit;
  41. this.dispatch = this.$store.dispatch;
  42. this.config = this.$store.state.config;
  43. this.reader = this.$store.state.reader;
  44. this.debouncedEmitPosChange = _.debounce((newValue) => {
  45. this.$emit('book-pos-changed', {bookPos: newValue});
  46. }, 1000);
  47. this.$root.$on('resize', () => {this.$nextTick(this.onResize)});
  48. }
  49. mounted() {
  50. this.canvasPrev = this.$refs.canvasPrev;
  51. this.canvasNext = this.$refs.canvasNext;
  52. }
  53. hex2rgba(hex, alpha = 1) {
  54. const [r, g, b] = hex.match(/\w\w/g).map(x => parseInt(x, 16));
  55. return `rgba(${r},${g},${b},${alpha})`;
  56. }
  57. async calcDrawProps() {
  58. this.contextPrev = this.canvasPrev.getContext('2d');
  59. this.contextNext = this.canvasNext.getContext('2d');
  60. this.realWidth = this.$refs.main.clientWidth;
  61. this.realHeight = this.$refs.main.clientHeight;
  62. let ratio = window.devicePixelRatio;
  63. if (ratio) {
  64. this.canvasPrev.width = this.realWidth*ratio;
  65. this.canvasPrev.height = this.realHeight*ratio;
  66. this.canvasPrev.style.width = this.$refs.main.clientWidth + 'px';
  67. this.canvasPrev.style.height = this.$refs.main.clientHeight + 'px';
  68. this.contextPrev.scale(ratio, ratio);
  69. this.canvasNext.width = this.realWidth*ratio;
  70. this.canvasNext.height = this.realHeight*ratio;
  71. this.canvasNext.style.width = this.$refs.main.clientWidth + 'px';
  72. this.canvasNext.style.height = this.$refs.main.clientHeight + 'px';
  73. this.contextNext.scale(ratio, ratio);
  74. } else {
  75. this.canvasPrev.width = this.realWidth;
  76. this.canvasPrev.height = this.realHeight;
  77. this.canvasNext.width = this.realWidth;
  78. this.canvasNext.height = this.realHeight;
  79. }
  80. this.contextPrev.textAlign = 'left';
  81. this.contextNext.textAlign = 'left';
  82. this.contextPrev.textBaseline = 'bottom';
  83. this.contextNext.textBaseline = 'bottom';
  84. this.canvasShowFirst = false;
  85. this.w = this.realWidth - 2*this.indent;
  86. this.h = this.realHeight - (this.showStatusBar ? this.statusBarHeight : 0);
  87. this.lineHeight = this.fontSize + this.lineInterval;
  88. this.pageLineCount = Math.floor(this.h/this.lineHeight);
  89. if (this.parsed) {
  90. this.parsed.p = this.p;
  91. this.parsed.w = this.w;// px, ширина текста
  92. this.parsed.font = this.font;
  93. this.parsed.wordWrap = this.wordWrap;
  94. this.parsed.context = this.contextPrev;
  95. this.parsed.fontByStyle = this.fontByStyle;
  96. }
  97. this.statusBarColor = this.hex2rgba(this.textColor, 0.5);
  98. this.currentTransition = '';
  99. this.pageChangeDirectionDown = true;
  100. //drawHelper
  101. this.drawHelper.realWidth = this.realWidth;
  102. this.drawHelper.realHeight = this.realHeight;
  103. this.drawHelper.backgroundColor = this.backgroundColor;
  104. this.drawHelper.statusBarColor = this.statusBarColor;
  105. this.drawHelper.fontName = this.fontName;
  106. }
  107. async loadFonts() {
  108. let loaded = await Promise.all(this.fontList.map(font => document.fonts.check(font)));
  109. if (loaded.some(r => !r)) {
  110. loaded = await Promise.all(this.fontList.map(font => document.fonts.load(font)));
  111. if (loaded.some(r => !r.length))
  112. throw new Error('some font not loaded');
  113. }
  114. }
  115. showBook() {
  116. this.$refs.main.focus();
  117. this.book = null;
  118. this.meta = null;
  119. this.fb2 = null;
  120. this.parsed = null;
  121. this.linesUp = null;
  122. this.linesDown = null;
  123. //preloaded fonts
  124. this.fontList = ['12px ReaderDefault', '12px Arial', '12px ComicSansMS', '12px OpenSans', '12px Roboto', '12px ArialNarrow',
  125. '12px Georgia', '12px Tahoma', '12px Helvetica', '12px CenturySchoolbook'];
  126. //default draw props
  127. this.textColor = '#000000';
  128. this.backgroundColor = '#478355';
  129. this.fontStyle = '';// 'bold','italic'
  130. this.fontSize = 33;// px
  131. this.fontName = 'Arial';
  132. this.lineInterval = 7;// px, межстрочный интервал
  133. this.textAlignJustify = true;// выравнивание по ширине
  134. this.p = 50;// px, отступ параграфа
  135. this.indent = 15;// px, отступ всего текста слева и справа
  136. this.wordWrap = true;
  137. this.keepLastToFirst = true;// перенос последней строки в первую при листании
  138. this.showStatusBar = true;
  139. this.statusBarTop = false;// top, bottom
  140. this.statusBarHeight = 20;// px
  141. this.pageChangeTransition = '';// '' - нет, downShift, rightShift, thaw - протаивание, blink - мерцание
  142. this.pageChangeTransitionSpeed = 50; //0-100%
  143. this.calcDrawProps();
  144. this.draw(true);// пока не загрузили, очистим канвас
  145. if (this.lastBook) {
  146. (async() => {
  147. const isParsed = await bookManager.hasBookParsed(this.lastBook);
  148. if (!isParsed) {
  149. return;
  150. }
  151. this.book = await bookManager.getBook(this.lastBook);
  152. this.meta = bookManager.metaOnly(this.book);
  153. this.fb2 = this.meta.fb2;
  154. this.title = _.compact([
  155. this.fb2.lastName,
  156. this.fb2.middleName,
  157. this.fb2.firstName,
  158. '-',
  159. this.fb2.bookTitle
  160. ]).join(' ');
  161. this.$root.$emit('set-app-title', this.title);
  162. const parsed = this.book.parsed;
  163. this.parsed = parsed;
  164. this.calcDrawProps();
  165. await this.loadFonts();
  166. this.draw();
  167. this.refreshTime();
  168. })();
  169. }
  170. }
  171. onResize() {
  172. this.calcDrawProps();
  173. this.draw(true);
  174. }
  175. get font() {
  176. return `${this.fontStyle} ${this.fontSize}px ${this.fontName}`;
  177. }
  178. fontByStyle(style) {
  179. return `${style.italic ? 'italic' : ''} ${style.bold ? 'bold' : ''} ${this.fontSize}px ${this.fontName}`;
  180. }
  181. get context() {
  182. return (this.canvasShowFirst ? this.contextPrev : this.contextNext);
  183. }
  184. get canvas() {
  185. return (this.canvasShowFirst ? this.canvasPrev : this.canvasNext);
  186. }
  187. draw(immediate) {
  188. this.canvasShowFirst = !this.canvasShowFirst;
  189. const context = this.context;
  190. if (immediate) {
  191. this.drawPage(context, this.bookPos);
  192. } else {
  193. if (this.pageChangeDirectionDown && this.pagePrepared && this.bookPos == this.bookPosPrepared) {
  194. this.linesDown = this.linesDownNext;
  195. this.linesUp = this.linesUpNext;
  196. this.prepareNextPage();
  197. } else {
  198. this.drawPage(context, this.bookPos);
  199. this.prepareNextPage();
  200. }
  201. if (this.currentTransition) {
  202. //this.currentTransition
  203. //this.pageChangeTransitionSpeed
  204. //this.pageChangeDirectionDown
  205. //curr to next transition
  206. //пока заглушка
  207. }
  208. this.currentTransition = '';
  209. this.pageChangeDirectionDown = false;//true только если PgDown
  210. }
  211. }
  212. drawPage(context, bookPos, nextChangeLines) {
  213. if (!this.lastBook)
  214. return;
  215. context.fillStyle = this.backgroundColor;
  216. context.fillRect(0, 0, this.realWidth, this.realHeight);
  217. if (!this.book || !this.parsed.textLength)
  218. return;
  219. if (this.showStatusBar)
  220. this.drawHelper.drawStatusBar(context, this.statusBarTop, this.statusBarHeight,
  221. this.statusBarColor, bookPos, this.parsed.textLength, this.title);
  222. context.font = this.font;
  223. context.fillStyle = this.textColor;
  224. const spaceWidth = context.measureText(' ').width;
  225. const lines = this.parsed.getLines(bookPos, this.pageLineCount + 1);
  226. if (!nextChangeLines) {
  227. this.linesDown = lines;
  228. this.linesUp = this.parsed.getLines(bookPos, -(this.pageLineCount + 1));
  229. } else {
  230. this.linesDownNext = lines;
  231. this.linesUpNext = this.parsed.getLines(bookPos, -(this.pageLineCount + 1));
  232. }
  233. let y = -this.lineInterval/2 + (this.h - this.pageLineCount*this.lineHeight)/2;
  234. if (this.showStatusBar)
  235. y += this.statusBarHeight*(this.statusBarTop ? 1 : 0);
  236. let len = lines.length;
  237. len = (len > this.pageLineCount ? len = this.pageLineCount : len);
  238. for (let i = 0; i < len; i++) {
  239. const line = lines[i];
  240. /* line:
  241. {
  242. begin: Number,
  243. end: Number,
  244. first: Boolean,
  245. last: Boolean,
  246. parts: array of {
  247. style: {bold: Boolean, italic: Boolean}
  248. text: String,
  249. }
  250. }*/
  251. let indent = this.indent + (line.first ? this.p : 0);
  252. y += this.lineHeight;
  253. let filled = false;
  254. // если выравнивание по ширине включено
  255. if (this.textAlignJustify && !line.last) {
  256. let lineText = '';
  257. for (const part of line.parts) {
  258. lineText += part.text;
  259. }
  260. const words = lineText.split(' ');
  261. if (words.length > 1) {
  262. const spaceCount = words.length - 1;
  263. const space = (this.w - line.width + spaceWidth*spaceCount)/spaceCount;
  264. let x = indent;
  265. for (const part of line.parts) {
  266. context.font = this.fontByStyle(part.style);
  267. let partWords = part.text.split(' ');
  268. for (let i = 0; i < partWords.length; i++) {
  269. let word = partWords[i];
  270. context.fillText(word, x, y);
  271. x += context.measureText(word).width + (i < partWords.length - 1 ? space : 0);
  272. }
  273. }
  274. filled = true;
  275. }
  276. }
  277. // просто выводим текст
  278. if (!filled) {
  279. let x = indent;
  280. for (const part of line.parts) {
  281. let text = part.text;
  282. context.font = this.fontByStyle(part.style);
  283. context.fillText(text, x, y);
  284. x += context.measureText(text).width;
  285. }
  286. }
  287. }
  288. }
  289. async refreshTime() {
  290. if (!this.timeRefreshing) {
  291. this.timeRefreshing = true;
  292. await sleep(60*1000);
  293. if (this.book && this.parsed.textLength) {
  294. this.drawHelper.drawStatusBar(this.context, this.statusBarTop, this.statusBarHeight,
  295. this.statusBarColor, this.bookPos, this.parsed.textLength, this.title);
  296. }
  297. this.timeRefreshing = false;
  298. this.refreshTime();
  299. }
  300. }
  301. prepareNextPage() {
  302. // подготовка следующей страницы заранее
  303. if (!this.book || !this.parsed.textLength)
  304. return;
  305. this.pagePrepared = false;
  306. this.cancelPrepare = false;
  307. if (!this.preparing) {
  308. this.preparing = true;
  309. this.pagePrepared = false;
  310. (async() => {
  311. await sleep(100);
  312. if (this.cancelPrepare) {
  313. this.preparing = false;
  314. return;
  315. }
  316. let i = this.pageLineCount;
  317. if (this.keepLastToFirst)
  318. i--;
  319. if (i >= 0 && this.linesDown.length > i) {
  320. this.bookPosPrepared = this.linesDown[i].begin;
  321. const ctx = (!this.canvasShowFirst ? this.contextPrev : this.contextNext);
  322. this.drawPage(ctx, this.bookPosPrepared, true);
  323. this.pagePrepared = true;
  324. }
  325. this.preparing = false;
  326. })();
  327. } else {
  328. this.cancelPrepare = true;
  329. }
  330. }
  331. doDown() {
  332. if (this.linesDown && this.linesDown.length > 1) {
  333. this.bookPos = this.linesDown[1].begin;
  334. }
  335. }
  336. doUp() {
  337. if (this.linesUp && this.linesUp.length > 1) {
  338. this.bookPos = this.linesUp[1].begin;
  339. }
  340. }
  341. doPageDown() {
  342. if (this.linesDown) {
  343. let i = this.pageLineCount;
  344. if (this.keepLastToFirst)
  345. i--;
  346. if (i >= 0 && this.linesDown.length > i) {
  347. this.currentTransition = this.pageChangeTransition;
  348. this.pageChangeDirectionDown = true;
  349. this.bookPos = this.linesDown[i].begin;
  350. }
  351. }
  352. }
  353. doPageUp() {
  354. if (this.linesUp) {
  355. let i = this.pageLineCount;
  356. if (this.keepLastToFirst)
  357. i--;
  358. i = (i > this.linesUp.length - 1 ? this.linesUp.length - 1 : i);
  359. if (i >= 0 && this.linesUp.length > i) {
  360. this.currentTransition = this.pageChangeTransition;
  361. this.pageChangeDirectionDown = false;
  362. this.bookPos = this.linesUp[i].begin;
  363. }
  364. }
  365. }
  366. doHome() {
  367. this.bookPos = 0;
  368. }
  369. doEnd() {
  370. if (this.parsed.para.length) {
  371. const lastPara = this.parsed.para[this.parsed.para.length - 1];
  372. this.bookPos = lastPara.offset + lastPara.length - 1;
  373. }
  374. }
  375. doToolBarToggle() {
  376. this.$emit('tool-bar-toggle');
  377. }
  378. keyHook(event) {
  379. if (event.type == 'keydown') {
  380. switch (event.code) {
  381. case 'ArrowDown':
  382. this.doDown();
  383. break;
  384. case 'ArrowUp':
  385. this.doUp();
  386. break;
  387. case 'PageDown':
  388. case 'ArrowRight':
  389. case 'Enter':
  390. case 'Space':
  391. this.doPageDown();
  392. break;
  393. case 'PageUp':
  394. case 'ArrowLeft':
  395. case 'Backspace':
  396. this.doPageUp();
  397. break;
  398. case 'Home':
  399. this.doHome();
  400. break;
  401. case 'End':
  402. this.doEnd();
  403. break;
  404. }
  405. }
  406. }
  407. async startClickRepeat(pointX, pointY, debounced) {
  408. this.repX = pointX;
  409. this.repY = pointY;
  410. if (!this.repInit) {
  411. this.repInit = true;
  412. this.repStart = true;
  413. if (!debounced)
  414. await sleep(800);
  415. if (this.debouncedRepStart) {
  416. this.debouncedRepStart = false;
  417. this.repInit = false;
  418. await this.startClickRepeat(this.repX, this.repY, true);
  419. }
  420. if (this.repStart) {
  421. this.repDoing = true;
  422. let delay = 400;
  423. while (this.repDoing) {
  424. this.handleClick(pointX, pointY);
  425. await sleep(delay);
  426. if (delay > 15)
  427. delay *= 0.8;
  428. }
  429. }
  430. this.repInit = false;
  431. } else {
  432. this.debouncedRepStart = true;
  433. }
  434. }
  435. endClickRepeat() {
  436. this.repStart = false;
  437. this.repDoing = false;
  438. this.debouncedRepStart = false;
  439. }
  440. onTouchStart(event) {
  441. this.endClickRepeat();
  442. if (event.touches.length == 1) {
  443. const touch = event.touches[0];
  444. const x = touch.pageX - this.canvas.offsetLeft;
  445. const y = touch.pageY - this.canvas.offsetTop;
  446. this.handleClick(x, y);
  447. this.startClickRepeat(x, y);
  448. }
  449. }
  450. onTouchEnd() {
  451. this.endClickRepeat();
  452. }
  453. onMouseDown(event) {
  454. this.endClickRepeat();
  455. if (event.button == 0) {
  456. const x = event.pageX - this.canvas.offsetLeft;
  457. const y = event.pageY - this.canvas.offsetTop;
  458. this.handleClick(x, y);
  459. this.startClickRepeat(x, y);
  460. } else if (event.button == 2) {
  461. this.doToolBarToggle();
  462. }
  463. }
  464. onMouseUp() {
  465. this.endClickRepeat();
  466. }
  467. onMouseWheel(event) {
  468. if (event.deltaY > 0) {
  469. this.doDown();
  470. } else if (event.deltaY < 0) {
  471. this.doUp();
  472. }
  473. }
  474. handleClick(pointX, pointY) {
  475. const mouseLegend = {
  476. 40: {30: 'PgUp', 100: 'PgDown'},
  477. 60: {40: 'Up', 60: 'Menu', 100: 'Down'},
  478. 100: {30: 'PgUp', 100: 'PgDown'}
  479. };
  480. const w = pointX/this.realWidth*100;
  481. const h = pointY/this.realHeight*100;
  482. let action = '';
  483. loops: {
  484. for (const x in mouseLegend) {
  485. for (const y in mouseLegend[x]) {
  486. if (w < x && h < y) {
  487. action = mouseLegend[x][y];
  488. break loops;
  489. }
  490. }
  491. }
  492. }
  493. switch (action) {
  494. case 'Down' ://Down
  495. this.doDown();
  496. break;
  497. case 'Up' ://Up
  498. this.doUp();
  499. break;
  500. case 'PgDown' ://PgDown
  501. this.doPageDown();
  502. break;
  503. case 'PgUp' ://PgUp
  504. this.doPageUp();
  505. break;
  506. case 'Menu' :
  507. this.doToolBarToggle();
  508. break;
  509. default :
  510. // Nothing
  511. }
  512. return !!action;
  513. }
  514. }
  515. //-----------------------------------------------------------------------------
  516. </script>
  517. <style scoped>
  518. .main {
  519. flex: 1;
  520. margin: 0;
  521. padding: 0;
  522. overflow: hidden;
  523. }
  524. .canvas {
  525. margin: 0;
  526. padding: 0;
  527. }
  528. </style>