TextPage.vue 22 KB

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