TextPage.vue 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. <template>
  2. <div ref="main" class="main" @click="onMouseClick">
  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 = 35;// 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, center: Boolean}
  252. text: String,
  253. }
  254. }*/
  255. let indent = this.indent + (line.first ? this.p : 0);
  256. y += this.lineHeight;
  257. let lineText = '';
  258. let center = false;
  259. for (const part of line.parts) {
  260. lineText += part.text;
  261. center = center || part.style.center;
  262. }
  263. let filled = false;
  264. // если выравнивание по ширине включено
  265. if (this.textAlignJustify && !line.last && !center) {
  266. const words = lineText.split(' ');
  267. if (words.length > 1) {
  268. const spaceCount = words.length - 1;
  269. const space = (this.w - line.width + spaceWidth*spaceCount)/spaceCount;
  270. let x = indent;
  271. for (const part of line.parts) {
  272. context.font = this.fontByStyle(part.style);
  273. let partWords = part.text.split(' ');
  274. for (let i = 0; i < partWords.length; i++) {
  275. let word = partWords[i];
  276. context.fillText(word, x, y);
  277. x += context.measureText(word).width + (i < partWords.length - 1 ? space : 0);
  278. }
  279. }
  280. filled = true;
  281. }
  282. }
  283. // просто выводим текст
  284. if (!filled) {
  285. let x = indent;
  286. x = (center ? this.indent + (this.w - context.measureText(lineText).width)/2 : x);
  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. this.drawStatusBar(context, lines);
  296. }
  297. drawStatusBar(context, lines) {
  298. if (!lines)
  299. lines = this.linesDown;
  300. if (this.showStatusBar) {
  301. let i = this.pageLineCount;
  302. if (this.keepLastToFirst)
  303. i--;
  304. i = (i > lines.length - 1 ? lines.length - 1 : i);
  305. this.drawHelper.drawStatusBar(context, this.statusBarTop, this.statusBarHeight,
  306. this.statusBarColor, lines[i].end, this.parsed.textLength, this.title);
  307. }
  308. }
  309. async refreshTime() {
  310. if (!this.timeRefreshing) {
  311. this.timeRefreshing = true;
  312. await sleep(60*1000);
  313. if (this.book && this.parsed.textLength) {
  314. this.drawStatusBar(this.context);
  315. }
  316. this.timeRefreshing = false;
  317. this.refreshTime();
  318. }
  319. }
  320. prepareNextPage() {
  321. // подготовка следующей страницы заранее
  322. if (!this.book || !this.parsed.textLength)
  323. return;
  324. this.pagePrepared = false;
  325. this.cancelPrepare = false;
  326. if (!this.preparing) {
  327. this.preparing = true;
  328. this.pagePrepared = false;
  329. (async() => {
  330. await sleep(100);
  331. if (this.cancelPrepare) {
  332. this.preparing = false;
  333. return;
  334. }
  335. let i = this.pageLineCount;
  336. if (this.keepLastToFirst)
  337. i--;
  338. if (i >= 0 && this.linesDown.length > i) {
  339. this.bookPosPrepared = this.linesDown[i].begin;
  340. const ctx = (!this.canvasShowFirst ? this.contextPrev : this.contextNext);
  341. this.drawPage(ctx, this.bookPosPrepared, true);
  342. this.pagePrepared = true;
  343. }
  344. this.preparing = false;
  345. })();
  346. } else {
  347. this.cancelPrepare = true;
  348. }
  349. }
  350. doDown() {
  351. if (this.linesDown && this.linesDown.length > this.pageLineCount) {
  352. this.bookPos = this.linesDown[1].begin;
  353. }
  354. }
  355. doUp() {
  356. if (this.linesUp && this.linesUp.length > 1) {
  357. this.bookPos = this.linesUp[1].begin;
  358. }
  359. }
  360. doPageDown() {
  361. if (this.linesDown) {
  362. let i = this.pageLineCount;
  363. if (this.keepLastToFirst)
  364. i--;
  365. if (i >= 0 && this.linesDown.length >= 2*i) {
  366. this.currentTransition = this.pageChangeTransition;
  367. this.pageChangeDirectionDown = true;
  368. this.bookPos = this.linesDown[i].begin;
  369. } else
  370. this.doEnd();
  371. }
  372. }
  373. doPageUp() {
  374. if (this.linesUp) {
  375. let i = this.pageLineCount;
  376. if (this.keepLastToFirst)
  377. i--;
  378. i = (i > this.linesUp.length - 1 ? this.linesUp.length - 1 : i);
  379. if (i >= 0 && this.linesUp.length > i) {
  380. this.currentTransition = this.pageChangeTransition;
  381. this.pageChangeDirectionDown = false;
  382. this.bookPos = this.linesUp[i].begin;
  383. }
  384. }
  385. }
  386. doHome() {
  387. this.bookPos = 0;
  388. }
  389. doEnd() {
  390. if (this.parsed.para.length) {
  391. let i = this.parsed.para.length - 1;
  392. let lastPos = this.parsed.para[i].offset + this.parsed.para[i].length - 1;
  393. const lines = this.parsed.getLines(lastPos, -this.pageLineCount);
  394. i = this.pageLineCount - 1;
  395. i = (i > lines.length - 1 ? lines.length - 1 : i);
  396. this.bookPos = lines[i].begin;
  397. }
  398. }
  399. doToolBarToggle() {
  400. this.$emit('tool-bar-toggle');
  401. }
  402. keyHook(event) {
  403. if (event.type == 'keydown') {
  404. switch (event.code) {
  405. case 'ArrowDown':
  406. this.doDown();
  407. break;
  408. case 'ArrowUp':
  409. this.doUp();
  410. break;
  411. case 'PageDown':
  412. case 'ArrowRight':
  413. case 'Enter':
  414. case 'Space':
  415. this.doPageDown();
  416. break;
  417. case 'PageUp':
  418. case 'ArrowLeft':
  419. case 'Backspace':
  420. this.doPageUp();
  421. break;
  422. case 'Home':
  423. this.doHome();
  424. break;
  425. case 'End':
  426. this.doEnd();
  427. break;
  428. }
  429. }
  430. }
  431. async startClickRepeat(pointX, pointY, debounced) {
  432. this.repX = pointX;
  433. this.repY = pointY;
  434. if (!this.repInit) {
  435. this.repInit = true;
  436. this.repStart = true;
  437. if (!debounced)
  438. await sleep(800);
  439. if (this.debouncedRepStart) {
  440. this.debouncedRepStart = false;
  441. this.repInit = false;
  442. await this.startClickRepeat(this.repX, this.repY, true);
  443. }
  444. if (this.repStart) {
  445. this.repDoing = true;
  446. let delay = 400;
  447. while (this.repDoing) {
  448. this.handleClick(pointX, pointY);
  449. await sleep(delay);
  450. if (delay > 15)
  451. delay *= 0.8;
  452. }
  453. }
  454. this.repInit = false;
  455. } else {
  456. this.debouncedRepStart = true;
  457. }
  458. }
  459. endClickRepeat() {
  460. this.repStart = false;
  461. this.repDoing = false;
  462. this.debouncedRepStart = false;
  463. }
  464. onTouchStart(event) {
  465. this.endClickRepeat();
  466. if (event.touches.length == 1) {
  467. const touch = event.touches[0];
  468. const x = touch.pageX - this.canvas.offsetLeft;
  469. const y = touch.pageY - this.canvas.offsetTop;
  470. if (this.handleClick(x, y))
  471. this.startClickRepeat(x, y);
  472. }
  473. }
  474. onTouchEnd() {
  475. this.endClickRepeat();
  476. }
  477. onMouseDown(event) {
  478. this.endClickRepeat();
  479. if (event.button == 0) {
  480. const x = event.pageX - this.canvas.offsetLeft;
  481. const y = event.pageY - this.canvas.offsetTop;
  482. if (this.handleClick(x, y))
  483. this.startClickRepeat(x, y);
  484. } else if (event.button == 2) {
  485. this.doToolBarToggle();
  486. }
  487. }
  488. onMouseUp() {
  489. this.endClickRepeat();
  490. }
  491. onMouseWheel(event) {
  492. if (event.deltaY > 0) {
  493. this.doDown();
  494. } else if (event.deltaY < 0) {
  495. this.doUp();
  496. }
  497. }
  498. checkPointInStatusBar(pointX, pointY) {
  499. let titleBar = {x1: 0, y1: 0, x2: this.realWidth/2, y2: this.statusBarHeight + 1};
  500. if (!this.statusBarTop) {
  501. titleBar.y1 += this.realHeight - this.statusBarHeight + 1;
  502. titleBar.y2 += this.realHeight - this.statusBarHeight + 1;
  503. }
  504. if (pointX >= titleBar.x1 && pointX <= titleBar.x2 &&
  505. pointY >= titleBar.y1 && pointY <= titleBar.y2) {
  506. return true;
  507. }
  508. return false;
  509. }
  510. onMouseClick(event) {
  511. if (this.showStatusBar && this.book) {
  512. const pointX = event.pageX - this.canvas.offsetLeft;
  513. const pointY = event.pageY - this.canvas.offsetTop;
  514. if (this.checkPointInStatusBar(pointX, pointY)) {
  515. window.open(this.meta.url, '_blank');
  516. return false;
  517. }
  518. }
  519. }
  520. handleClick(pointX, pointY) {
  521. const mouseLegend = {
  522. 40: {30: 'PgUp', 100: 'PgDown'},
  523. 60: {40: 'Up', 60: 'Menu', 100: 'Down'},
  524. 100: {30: 'PgUp', 100: 'PgDown'}
  525. };
  526. if (this.showStatusBar && this.book) {
  527. if (this.checkPointInStatusBar(pointX, pointY)) {
  528. return false;
  529. }
  530. }
  531. const w = pointX/this.realWidth*100;
  532. const h = pointY/this.realHeight*100;
  533. let action = '';
  534. loops: {
  535. for (const x in mouseLegend) {
  536. for (const y in mouseLegend[x]) {
  537. if (w < x && h < y) {
  538. action = mouseLegend[x][y];
  539. break loops;
  540. }
  541. }
  542. }
  543. }
  544. switch (action) {
  545. case 'Down' ://Down
  546. this.doDown();
  547. break;
  548. case 'Up' ://Up
  549. this.doUp();
  550. break;
  551. case 'PgDown' ://PgDown
  552. this.doPageDown();
  553. break;
  554. case 'PgUp' ://PgUp
  555. this.doPageUp();
  556. break;
  557. case 'Menu' :
  558. this.doToolBarToggle();
  559. break;
  560. default :
  561. // Nothing
  562. }
  563. return !!action;
  564. }
  565. }
  566. //-----------------------------------------------------------------------------
  567. </script>
  568. <style scoped>
  569. .main {
  570. flex: 1;
  571. margin: 0;
  572. padding: 0;
  573. overflow: hidden;
  574. }
  575. .canvas {
  576. margin: 0;
  577. padding: 0;
  578. }
  579. </style>