TextPage.vue 17 KB

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