TextPage.vue 18 KB

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