TextPage.vue 15 KB

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