TextPage.vue 22 KB

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