TextPage.vue 14 KB

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