TextPage.vue 17 KB

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