TextPage.vue 21 KB

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