TextPage.vue 22 KB

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