TextPage.vue 21 KB

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