TextPage.vue 16 KB

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