TextPage.vue 16 KB

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