TextPage.vue 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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. this.canvasShowFirst = !this.canvasShowFirst;
  192. const context = this.context;
  193. if (immediate) {
  194. this.drawPage(context, this.bookPos);
  195. } else {
  196. if (this.pageChangeDirectionDown && this.pagePrepared && this.bookPos == this.bookPosPrepared) {
  197. this.linesDown = this.linesDownNext;
  198. this.linesUp = this.linesUpNext;
  199. this.prepareNextPage();
  200. } else {
  201. this.drawPage(context, this.bookPos);
  202. this.prepareNextPage();
  203. }
  204. if (this.currentTransition) {
  205. //this.currentTransition
  206. //this.pageChangeTransitionSpeed
  207. //this.pageChangeDirectionDown
  208. //curr to next transition
  209. //пока заглушка
  210. }
  211. this.currentTransition = '';
  212. this.pageChangeDirectionDown = false;//true только если PgDown
  213. }
  214. }
  215. drawPage(context, bookPos, nextChangeLines) {
  216. if (!this.lastBook)
  217. return;
  218. context.fillStyle = this.backgroundColor;
  219. context.fillRect(0, 0, this.realWidth, this.realHeight);
  220. if (!this.book || !this.parsed.textLength)
  221. return;
  222. if (this.showStatusBar)
  223. this.drawHelper.drawStatusBar(context, this.statusBarTop, this.statusBarHeight,
  224. this.statusBarColor, bookPos, this.parsed.textLength, this.title);
  225. context.font = this.font;
  226. context.fillStyle = this.textColor;
  227. const spaceWidth = context.measureText(' ').width;
  228. const lines = this.parsed.getLines(bookPos, this.pageLineCount + 1);
  229. if (!nextChangeLines) {
  230. this.linesDown = lines;
  231. this.linesUp = this.parsed.getLines(bookPos, -(this.pageLineCount + 1));
  232. } else {
  233. this.linesDownNext = lines;
  234. this.linesUpNext = this.parsed.getLines(bookPos, -(this.pageLineCount + 1));
  235. }
  236. let y = -this.lineInterval/2 + (this.h - this.pageLineCount*this.lineHeight)/2;
  237. if (this.showStatusBar)
  238. y += this.statusBarHeight*(this.statusBarTop ? 1 : 0);
  239. let len = lines.length;
  240. len = (len > this.pageLineCount ? len = this.pageLineCount : len);
  241. for (let i = 0; i < len; i++) {
  242. const line = lines[i];
  243. /* line:
  244. {
  245. begin: Number,
  246. end: Number,
  247. first: Boolean,
  248. last: Boolean,
  249. parts: array of {
  250. style: {bold: Boolean, italic: Boolean}
  251. text: String,
  252. }
  253. }*/
  254. let indent = this.indent + (line.first ? this.p : 0);
  255. y += this.lineHeight;
  256. let filled = false;
  257. // если выравнивание по ширине включено
  258. if (this.textAlignJustify && !line.last) {
  259. let lineText = '';
  260. for (const part of line.parts) {
  261. lineText += part.text;
  262. }
  263. const words = lineText.split(' ');
  264. if (words.length > 1) {
  265. const spaceCount = words.length - 1;
  266. const space = (this.w - line.width + spaceWidth*spaceCount)/spaceCount;
  267. let x = indent;
  268. for (const part of line.parts) {
  269. context.font = this.fontByStyle(part.style);
  270. let partWords = part.text.split(' ');
  271. for (let i = 0; i < partWords.length; i++) {
  272. let word = partWords[i];
  273. context.fillText(word, x, y);
  274. x += context.measureText(word).width + (i < partWords.length - 1 ? space : 0);
  275. }
  276. }
  277. filled = true;
  278. }
  279. }
  280. // просто выводим текст
  281. if (!filled) {
  282. let x = indent;
  283. for (const part of line.parts) {
  284. let text = part.text;
  285. context.font = this.fontByStyle(part.style);
  286. context.fillText(text, x, y);
  287. x += context.measureText(text).width;
  288. }
  289. }
  290. }
  291. }
  292. async refreshTime() {
  293. if (!this.timeRefreshing) {
  294. this.timeRefreshing = true;
  295. await sleep(60*1000);
  296. if (this.book && this.parsed.textLength) {
  297. this.drawHelper.drawStatusBar(this.context, this.statusBarTop, this.statusBarHeight,
  298. this.statusBarColor, this.bookPos, this.parsed.textLength, this.title);
  299. }
  300. this.timeRefreshing = false;
  301. this.refreshTime();
  302. }
  303. }
  304. prepareNextPage() {
  305. // подготовка следующей страницы заранее
  306. if (!this.book || !this.parsed.textLength)
  307. return;
  308. this.pagePrepared = false;
  309. this.cancelPrepare = false;
  310. if (!this.preparing) {
  311. this.preparing = true;
  312. this.pagePrepared = false;
  313. (async() => {
  314. await sleep(100);
  315. if (this.cancelPrepare) {
  316. this.preparing = false;
  317. return;
  318. }
  319. let i = this.pageLineCount;
  320. if (this.keepLastToFirst)
  321. i--;
  322. if (i >= 0 && this.linesDown.length > i) {
  323. this.bookPosPrepared = this.linesDown[i].begin;
  324. const ctx = (!this.canvasShowFirst ? this.contextPrev : this.contextNext);
  325. this.drawPage(ctx, this.bookPosPrepared, true);
  326. this.pagePrepared = true;
  327. }
  328. this.preparing = false;
  329. })();
  330. } else {
  331. this.cancelPrepare = true;
  332. }
  333. }
  334. doDown() {
  335. if (this.linesDown && this.linesDown.length > 1) {
  336. this.bookPos = this.linesDown[1].begin;
  337. }
  338. }
  339. doUp() {
  340. if (this.linesUp && this.linesUp.length > 1) {
  341. this.bookPos = this.linesUp[1].begin;
  342. }
  343. }
  344. doPageDown() {
  345. if (this.linesDown) {
  346. let i = this.pageLineCount;
  347. if (this.keepLastToFirst)
  348. i--;
  349. if (i >= 0 && this.linesDown.length > i) {
  350. this.currentTransition = this.pageChangeTransition;
  351. this.pageChangeDirectionDown = true;
  352. this.bookPos = this.linesDown[i].begin;
  353. }
  354. }
  355. }
  356. doPageUp() {
  357. if (this.linesUp) {
  358. let i = this.pageLineCount;
  359. if (this.keepLastToFirst)
  360. i--;
  361. i = (i > this.linesUp.length - 1 ? this.linesUp.length - 1 : i);
  362. if (i >= 0 && this.linesUp.length > i) {
  363. this.currentTransition = this.pageChangeTransition;
  364. this.pageChangeDirectionDown = false;
  365. this.bookPos = this.linesUp[i].begin;
  366. }
  367. }
  368. }
  369. doHome() {
  370. this.bookPos = 0;
  371. }
  372. doEnd() {
  373. if (this.parsed.para.length) {
  374. const lastPara = this.parsed.para[this.parsed.para.length - 1];
  375. this.bookPos = lastPara.offset + lastPara.length - 1;
  376. }
  377. }
  378. doToolBarToggle() {
  379. this.$emit('tool-bar-toggle');
  380. }
  381. keyHook(event) {
  382. if (event.type == 'keydown') {
  383. switch (event.code) {
  384. case 'ArrowDown':
  385. this.doDown();
  386. break;
  387. case 'ArrowUp':
  388. this.doUp();
  389. break;
  390. case 'PageDown':
  391. case 'ArrowRight':
  392. case 'Enter':
  393. case 'Space':
  394. this.doPageDown();
  395. break;
  396. case 'PageUp':
  397. case 'ArrowLeft':
  398. case 'Backspace':
  399. this.doPageUp();
  400. break;
  401. case 'Home':
  402. this.doHome();
  403. break;
  404. case 'End':
  405. this.doEnd();
  406. break;
  407. }
  408. }
  409. }
  410. async startClickRepeat(pointX, pointY, debounced) {
  411. this.repX = pointX;
  412. this.repY = pointY;
  413. if (!this.repInit) {
  414. this.repInit = true;
  415. this.repStart = true;
  416. if (!debounced)
  417. await sleep(800);
  418. if (this.debouncedRepStart) {
  419. this.debouncedRepStart = false;
  420. this.repInit = false;
  421. await this.startClickRepeat(this.repX, this.repY, true);
  422. }
  423. if (this.repStart) {
  424. this.repDoing = true;
  425. let delay = 400;
  426. while (this.repDoing) {
  427. this.handleClick(pointX, pointY);
  428. await sleep(delay);
  429. if (delay > 15)
  430. delay *= 0.8;
  431. }
  432. }
  433. this.repInit = false;
  434. } else {
  435. this.debouncedRepStart = true;
  436. }
  437. }
  438. endClickRepeat() {
  439. this.repStart = false;
  440. this.repDoing = false;
  441. this.debouncedRepStart = false;
  442. }
  443. onTouchStart(event) {
  444. this.endClickRepeat();
  445. if (event.touches.length == 1) {
  446. const touch = event.touches[0];
  447. const x = touch.pageX - this.canvas.offsetLeft;
  448. const y = touch.pageY - this.canvas.offsetTop;
  449. this.handleClick(x, y);
  450. this.startClickRepeat(x, y);
  451. }
  452. }
  453. onTouchEnd() {
  454. this.endClickRepeat();
  455. }
  456. onMouseDown(event) {
  457. this.endClickRepeat();
  458. if (event.button == 0) {
  459. const x = event.pageX - this.canvas.offsetLeft;
  460. const y = event.pageY - this.canvas.offsetTop;
  461. this.handleClick(x, y);
  462. this.startClickRepeat(x, y);
  463. } else if (event.button == 2) {
  464. this.doToolBarToggle();
  465. }
  466. }
  467. onMouseUp() {
  468. this.endClickRepeat();
  469. }
  470. onMouseWheel(event) {
  471. if (event.deltaY > 0) {
  472. this.doDown();
  473. } else if (event.deltaY < 0) {
  474. this.doUp();
  475. }
  476. }
  477. handleClick(pointX, pointY) {
  478. const mouseLegend = {
  479. 40: {30: 'PgUp', 100: 'PgDown'},
  480. 60: {40: 'Up', 60: 'Menu', 100: 'Down'},
  481. 100: {30: 'PgUp', 100: 'PgDown'}
  482. };
  483. const w = pointX/this.realWidth*100;
  484. const h = pointY/this.realHeight*100;
  485. let action = '';
  486. loops: {
  487. for (const x in mouseLegend) {
  488. for (const y in mouseLegend[x]) {
  489. if (w < x && h < y) {
  490. action = mouseLegend[x][y];
  491. break loops;
  492. }
  493. }
  494. }
  495. }
  496. switch (action) {
  497. case 'Down' ://Down
  498. this.doDown();
  499. break;
  500. case 'Up' ://Up
  501. this.doUp();
  502. break;
  503. case 'PgDown' ://PgDown
  504. this.doPageDown();
  505. break;
  506. case 'PgUp' ://PgUp
  507. this.doPageUp();
  508. break;
  509. case 'Menu' :
  510. this.doToolBarToggle();
  511. break;
  512. default :
  513. // Nothing
  514. }
  515. return !!action;
  516. }
  517. }
  518. //-----------------------------------------------------------------------------
  519. </script>
  520. <style scoped>
  521. .main {
  522. flex: 1;
  523. margin: 0;
  524. padding: 0;
  525. overflow: hidden;
  526. }
  527. .canvas {
  528. margin: 0;
  529. padding: 0;
  530. }
  531. </style>