TextPage.vue 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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 = 34;// 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 = true;//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.$root.$emit('set-app-title', _.compact([
  127. this.fb2.lastName,
  128. this.fb2.middleName,
  129. this.fb2.firstName,
  130. '-',
  131. this.fb2.bookTitle
  132. ]).join(' '));
  133. const parsed = this.book.parsed;
  134. this.parsed = parsed;
  135. this.calcDrawProps();
  136. await this.loadFonts();
  137. this.drawPage();
  138. })();
  139. }
  140. }
  141. onResize() {
  142. this.calcDrawProps();
  143. this.drawPage();
  144. }
  145. get font() {
  146. return `${this.fontStyle} ${this.fontSize}px ${this.fontName}`;
  147. }
  148. fontByStyle(style) {
  149. return `${style.italic ? 'italic' : ''} ${style.bold ? 'bold' : ''} ${this.fontSize}px ${this.fontName}`;
  150. }
  151. fontBySize(size) {
  152. return `${size}px ${this.fontName}`;
  153. }
  154. drawPercentBar(x, y, w, h) {
  155. const context = this.context;
  156. const pad = 3;
  157. const fh = h - 2*pad;
  158. context.font = 'bold ' + this.fontBySize(fh);
  159. const t1 = `${Math.floor(this.bookPos/1000)}k/${Math.floor(this.parsed.textLength/1000)}k`;
  160. const w1 = this.measureText(t1) + fh/2;
  161. const read = this.bookPos/this.parsed.textLength;
  162. const t2 = (read*100).toFixed(2) + '%';
  163. const w2 = this.measureText(t2);
  164. let w3 = w - w1 - w2;
  165. if (w1 + w2 <= w)
  166. context.fillText(t1, x, y + h - 1);
  167. if (w3 > 20 && w1 + w2 + w3 <= w) {
  168. const barWidth = w - w1 - w2 - fh/2;
  169. context.strokeRect(x + w1, y + pad, barWidth, fh);
  170. context.fillRect(x + w1 + 3, y + pad + 3, (barWidth - 6)*read, fh - 6);
  171. }
  172. if (w1 <= w)
  173. context.fillText(t2, x + w1 + w3, y + h - 1);
  174. }
  175. drawStatusBar() {
  176. const context = this.context;
  177. context.fillStyle = this.statusBarColor;
  178. context.strokeStyle = this.statusBarColor;
  179. const h = (this.statusBarTop ? 0 : this.realHeight - this.statusBarHeight);
  180. const lh = (this.statusBarTop ? this.statusBarHeight : h);
  181. context.fillRect(0, lh, this.realWidth, 1);
  182. this.drawPercentBar(this.w/2, h, this.w/2, this.statusBarHeight);
  183. }
  184. drawPage() {
  185. if (!this.lastBook)
  186. return;
  187. //пустой канвас
  188. const canvas = this.canvas;
  189. const context = this.context;
  190. context.fillStyle = this.backgroundColor;
  191. context.fillRect(0, 0, canvas.width, canvas.height);
  192. if (!this.book || !this.parsed.textLength)
  193. return;
  194. if (this.showStatusBar) {
  195. this.drawStatusBar();
  196. }
  197. context.font = this.font;
  198. context.fillStyle = this.textColor;
  199. const spaceWidth = this.context.measureText(' ').width;
  200. const lines = this.parsed.getLines(this.bookPos, this.pageLineCount + 1);
  201. let y = -this.lineInterval/2 + (this.h - this.pageLineCount*this.lineHeight)/2;
  202. if (this.showStatusBar)
  203. y += this.statusBarHeight*(this.statusBarTop ? 1 : -1);
  204. let len = lines.length;
  205. len = (len > this.pageLineCount ? len = this.pageLineCount : len);
  206. for (let i = 0; i < len; i++) {
  207. const line = lines[i];
  208. /* line:
  209. {
  210. begin: Number,
  211. end: Number,
  212. first: Boolean,
  213. last: Boolean,
  214. parts: array of {
  215. style: {bold: Boolean, italic: Boolean}
  216. text: String,
  217. }
  218. }*/
  219. let indent = this.indent + (line.first ? this.p : 0);
  220. y += this.lineHeight;
  221. let filled = false;
  222. // если выравнивание по ширине включено
  223. if (this.textAlignJustify && !line.last) {
  224. let lineText = '';
  225. for (const part of line.parts) {
  226. lineText += part.text;
  227. }
  228. const words = lineText.split(' ');
  229. if (words.length > 1) {
  230. const spaceCount = words.length - 1;
  231. const space = (this.w - line.width + spaceWidth*spaceCount)/spaceCount;
  232. let x = indent;
  233. for (const part of line.parts) {
  234. context.font = this.fontByStyle(part.style);
  235. let partWords = part.text.split(' ');
  236. for (let i = 0; i < partWords.length; i++) {
  237. let word = partWords[i];
  238. context.fillText(word, x, y);
  239. x += this.measureText(word) + (i < partWords.length - 1 ? space : 0);
  240. }
  241. }
  242. filled = true;
  243. }
  244. }
  245. // просто выводим текст
  246. if (!filled) {
  247. let x = indent;
  248. for (const part of line.parts) {
  249. let text = part.text;
  250. context.font = this.fontByStyle(part.style);
  251. context.fillText(text, x, y);
  252. x += this.measureText(text);
  253. }
  254. }
  255. }
  256. this.linesUp = this.parsed.getLines(this.bookPos, -(this.pageLineCount + 1));
  257. this.linesDown = lines;
  258. }
  259. doDown() {
  260. if (this.linesDown && this.linesDown.length > 1) {
  261. this.bookPos = this.linesDown[1].begin;
  262. }
  263. }
  264. doUp() {
  265. if (this.linesUp && this.linesUp.length > 1) {
  266. this.bookPos = this.linesUp[1].begin;
  267. }
  268. }
  269. doPageDown() {
  270. if (this.linesDown) {
  271. let i = this.pageLineCount;
  272. i--;
  273. if (i >= 0 && this.linesDown.length > i) {
  274. this.bookPos = this.linesDown[i].begin;
  275. }
  276. }
  277. }
  278. doPageUp() {
  279. if (this.linesUp) {
  280. let i = this.pageLineCount;
  281. i--;
  282. i = (i > this.linesUp.length - 1 ? this.linesUp.length - 1 : i);
  283. if (i >= 0 && this.linesUp.length > i) {
  284. this.bookPos = this.linesUp[i].begin;
  285. }
  286. }
  287. }
  288. doHome() {
  289. this.bookPos = 0;
  290. }
  291. doEnd() {
  292. if (this.parsed.para.length) {
  293. const lastPara = this.parsed.para[this.parsed.para.length - 1];
  294. this.bookPos = lastPara.offset + lastPara.length - 1;
  295. }
  296. }
  297. doToolBarToggle() {
  298. this.$emit('tool-bar-toggle');
  299. }
  300. keyHook(event) {
  301. if (event.type == 'keydown') {
  302. switch (event.code) {
  303. case 'ArrowDown':
  304. this.doDown();
  305. break;
  306. case 'ArrowUp':
  307. this.doUp();
  308. break;
  309. case 'PageDown':
  310. case 'ArrowRight':
  311. case 'Enter':
  312. case 'Space':
  313. this.doPageDown();
  314. break;
  315. case 'PageUp':
  316. case 'ArrowLeft':
  317. case 'Backspace':
  318. this.doPageUp();
  319. break;
  320. case 'Home':
  321. this.doHome();
  322. break;
  323. case 'End':
  324. this.doEnd();
  325. break;
  326. }
  327. }
  328. }
  329. async startClickRepeat(pointX, pointY) {
  330. if (!this.repInit) {
  331. this.repInit = true;
  332. this.repStart = true;
  333. await sleep(1000);
  334. if (this.debouncedRepStart) {
  335. this.debouncedRepStart = false;
  336. this.repInit = false;
  337. await this.startClickRepeat(pointX, pointY);
  338. }
  339. if (this.repStart) {
  340. this.repDoing = true;
  341. let delay = 500;
  342. while (this.repDoing) {
  343. this.handleClick(pointX, pointY);
  344. await sleep(delay);
  345. if (delay > 20)
  346. delay *= 0.7;
  347. }
  348. }
  349. this.repInit = false;
  350. } else {
  351. this.debouncedRepStart = true;
  352. }
  353. }
  354. endClickRepeat() {
  355. this.repStart = false;
  356. this.repDoing = false;
  357. this.debouncedRepStart = false;
  358. }
  359. onTouchStart(event) {
  360. this.endClickRepeat();
  361. if (event.touches.length == 1) {
  362. const touch = event.touches[0];
  363. this.handleClick(touch.clientX, touch.clientY);
  364. this.startClickRepeat(touch.clientX, touch.clientY);
  365. }
  366. }
  367. onTouchEnd() {
  368. this.endClickRepeat();
  369. }
  370. onMouseDown(event) {
  371. this.endClickRepeat();
  372. if (event.button == 0) {
  373. this.handleClick(event.clientX, event.clientY);
  374. this.startClickRepeat(event.clientX, event.clientY);
  375. } else if (event.button == 2) {
  376. this.doToolBarToggle();
  377. }
  378. }
  379. onMouseUp() {
  380. this.endClickRepeat();
  381. }
  382. onMouseWheel(event) {
  383. if (event.deltaY > 0) {
  384. this.doDown();
  385. } else if (event.deltaY < 0) {
  386. this.doUp();
  387. }
  388. }
  389. handleClick(pointX, pointY) {
  390. const mouseLegend = {
  391. 40: {30: 'PgUp', 100: 'PgDown'},
  392. 60: {40: 'Up', 60: 'Menu', 100: 'Down'},
  393. 100: {30: 'PgUp', 100: 'PgDown'}
  394. };
  395. const w = pointX/this.realWidth*100;
  396. const h = pointY/this.realHeight*100;
  397. let action = '';
  398. loops: {
  399. for (const x in mouseLegend) {
  400. for (const y in mouseLegend[x]) {
  401. if (w < x && h < y) {
  402. action = mouseLegend[x][y];
  403. break loops;
  404. }
  405. }
  406. }
  407. }
  408. switch (action) {
  409. case 'Down' ://Down
  410. this.doDown();
  411. break;
  412. case 'Up' ://Up
  413. this.doUp();
  414. break;
  415. case 'PgDown' ://PgDown
  416. this.doPageDown();
  417. break;
  418. case 'PgUp' ://PgUp
  419. this.doPageUp();
  420. break;
  421. case 'Menu' :
  422. this.doToolBarToggle();
  423. break;
  424. default :
  425. // Nothing
  426. }
  427. return !!action;
  428. }
  429. }
  430. //-----------------------------------------------------------------------------
  431. </script>
  432. <style scoped>
  433. .main {
  434. flex: 1;
  435. margin: 0;
  436. padding: 0;
  437. overflow: hidden;
  438. }
  439. .canvas {
  440. margin: 0;
  441. padding: 0;
  442. }
  443. </style>