TextPage.vue 19 KB

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