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