BookParser.js 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  1. import he from 'he';
  2. import sax from '../../../../server/core/sax';
  3. import * as utils from '../../../share/utils';
  4. const maxImageLineCount = 100;
  5. export default class BookParser {
  6. constructor(settings) {
  7. if (settings) {
  8. this.showInlineImagesInCenter = settings.showInlineImagesInCenter;
  9. }
  10. // defaults
  11. this.p = 30;// px, отступ параграфа
  12. this.w = 300;// px, ширина страницы
  13. this.wordWrap = false;// перенос по слогам
  14. //заглушка
  15. this.measureText = (text, style) => {// eslint-disable-line no-unused-vars
  16. return text.length*20;
  17. };
  18. }
  19. async parse(data, callback) {
  20. if (!callback)
  21. callback = () => {};
  22. callback(0);
  23. if (data.indexOf('<FictionBook') < 0) {
  24. throw new Error('Неверный формат файла');
  25. }
  26. //defaults
  27. let fb2 = {
  28. bookTitle: '',
  29. };
  30. let path = '';
  31. let tag = '';
  32. let center = false;
  33. let bold = false;
  34. let italic = false;
  35. let space = 0;
  36. let inPara = false;
  37. let isFirstBody = true;
  38. let isFirstSection = true;
  39. let isFirstTitlePara = false;
  40. //изображения
  41. this.binary = {};
  42. let binaryId = '';
  43. let binaryType = '';
  44. let dimPromises = [];
  45. //оглавление
  46. this.contents = [];
  47. let curTitle = {paraIndex: -1, title: '', subtitles: []};
  48. let curSubtitle = {paraIndex: -1, title: ''};
  49. let inTitle = false;
  50. let inSubtitle = false;
  51. let sectionLevel = 0;
  52. let bodyIndex = 0;
  53. let paraIndex = -1;
  54. let paraOffset = 0;
  55. let para = []; /*array of
  56. {
  57. index: Number,
  58. offset: Number, //сумма всех length до этого параграфа
  59. length: Number, //длина text без тегов
  60. text: String, //текст параграфа с вложенными тегами
  61. addIndex: Number, //индекс добавляемого пустого параграфа (addEmptyParagraphs)
  62. }
  63. */
  64. const getImageDimensions = (binaryId, binaryType, data) => {
  65. return new Promise ((resolve, reject) => { (async() => {
  66. const i = new Image();
  67. let resolved = false;
  68. i.onload = () => {
  69. resolved = true;
  70. this.binary[binaryId] = {
  71. w: i.width,
  72. h: i.height,
  73. type: binaryType,
  74. data
  75. };
  76. resolve();
  77. };
  78. i.onerror = reject;
  79. i.src = `data:${binaryType};base64,${data}`;
  80. await utils.sleep(30*1000);
  81. if (!resolved)
  82. reject('Не удалось получить размер изображения');
  83. })().catch(reject); });
  84. };
  85. const getExternalImageDimensions = (src) => {
  86. return new Promise ((resolve, reject) => { (async() => {
  87. const i = new Image();
  88. let resolved = false;
  89. i.onload = () => {
  90. resolved = true;
  91. this.binary[src] = {
  92. w: i.width,
  93. h: i.height,
  94. };
  95. resolve();
  96. };
  97. i.onerror = reject;
  98. i.src = src;
  99. await utils.sleep(30*1000);
  100. if (!resolved)
  101. reject('Не удалось получить размер изображения');
  102. })().catch(reject); });
  103. };
  104. const newParagraph = (text, len, addIndex) => {
  105. paraIndex++;
  106. let p = {
  107. index: paraIndex,
  108. offset: paraOffset,
  109. length: len,
  110. text: text,
  111. addIndex: (addIndex ? addIndex : 0),
  112. };
  113. if (inSubtitle) {
  114. curSubtitle.title += '<p>';
  115. } else if (inTitle) {
  116. curTitle.title += '<p>';
  117. }
  118. para[paraIndex] = p;
  119. paraOffset += p.length;
  120. };
  121. const growParagraph = (text, len) => {
  122. if (paraIndex < 0) {
  123. newParagraph(' ', 1);
  124. growParagraph(text, len);
  125. return;
  126. }
  127. const prevParaIndex = paraIndex;
  128. let p = para[paraIndex];
  129. paraOffset -= p.length;
  130. //добавление пустых (addEmptyParagraphs) параграфов перед текущим
  131. if (p.length == 1 && p.text[0] == ' ' && len > 0) {
  132. paraIndex--;
  133. for (let i = 0; i < 2; i++) {
  134. newParagraph(' ', 1, i + 1);
  135. }
  136. paraIndex++;
  137. p.index = paraIndex;
  138. p.offset = paraOffset;
  139. para[paraIndex] = p;
  140. if (curTitle.paraIndex == prevParaIndex)
  141. curTitle.paraIndex = paraIndex;
  142. if (curSubtitle.paraIndex == prevParaIndex)
  143. curSubtitle.paraIndex = paraIndex;
  144. //уберем начальный пробел
  145. p.length = 0;
  146. p.text = p.text.substr(1);
  147. }
  148. p.length += len;
  149. p.text += text;
  150. if (inSubtitle) {
  151. curSubtitle.title += text;
  152. } else if (inTitle) {
  153. curTitle.title += text;
  154. }
  155. para[paraIndex] = p;
  156. paraOffset += p.length;
  157. };
  158. const onStartNode = (elemName, tail) => {// eslint-disable-line no-unused-vars
  159. if (elemName == '?xml')
  160. return;
  161. tag = elemName;
  162. path += '/' + tag;
  163. if (tag == 'binary') {
  164. let attrs = sax.getAttrsSync(tail);
  165. binaryType = (attrs['content-type'] && attrs['content-type'].value ? attrs['content-type'].value : '');
  166. if (binaryType == 'image/jpeg' || binaryType == 'image/png' || binaryType == 'application/octet-stream')
  167. binaryId = (attrs.id.value ? attrs.id.value : '');
  168. }
  169. if (tag == 'image') {
  170. let attrs = sax.getAttrsSync(tail);
  171. if (attrs.href && attrs.href.value) {
  172. const href = attrs.href.value;
  173. if (href[0] == '#') {//local
  174. if (inPara && !this.showInlineImagesInCenter && !center)
  175. growParagraph(`<image-inline href="${href}"></image-inline>`, 0);
  176. else
  177. newParagraph(`<image href="${href}">${' '.repeat(maxImageLineCount)}</image>`, maxImageLineCount);
  178. if (inPara && this.showInlineImagesInCenter)
  179. newParagraph(' ', 1);
  180. } else {//external
  181. dimPromises.push(getExternalImageDimensions(href));
  182. newParagraph(`<image href="${href}">${' '.repeat(maxImageLineCount)}</image>`, maxImageLineCount);
  183. }
  184. }
  185. }
  186. if (path == '/fictionbook/description/title-info/author') {
  187. if (!fb2.author)
  188. fb2.author = [];
  189. fb2.author.push({});
  190. }
  191. const isPublishSequence = (path == '/fictionbook/description/publish-info/sequence');
  192. if (path == '/fictionbook/description/title-info/sequence' || isPublishSequence) {
  193. if (!fb2.sequence)
  194. fb2.sequence = [];
  195. if (!isPublishSequence || !fb2.sequence.length) {
  196. const attrs = sax.getAttrsSync(tail);
  197. const seq = {};
  198. if (attrs.name && attrs.name.value) {
  199. seq.name = attrs.name.value;
  200. }
  201. if (attrs.number && attrs.number.value) {
  202. seq.number = attrs.number.value;
  203. }
  204. fb2.sequence.push(seq);
  205. }
  206. }
  207. if (path.indexOf('/fictionbook/body') == 0) {
  208. if (tag == 'body') {
  209. if (isFirstBody && fb2.annotation) {
  210. const ann = fb2.annotation.split('<p>').filter(v => v).map(v => utils.removeHtmlTags(v));
  211. ann.forEach(a => {
  212. newParagraph(`<emphasis><space w="1">${a}</space></emphasis>`, a.length);
  213. });
  214. if (ann.length)
  215. newParagraph(' ', 1);
  216. }
  217. if (isFirstBody && fb2.sequence && fb2.sequence.length) {
  218. const bt = utils.getBookTitle(fb2);
  219. if (bt.sequence) {
  220. newParagraph(bt.sequence, bt.sequence.length);
  221. newParagraph(' ', 1);
  222. }
  223. }
  224. if (!isFirstBody)
  225. newParagraph(' ', 1);
  226. isFirstBody = false;
  227. bodyIndex++;
  228. }
  229. if (tag == 'title') {
  230. newParagraph(' ', 1);
  231. isFirstTitlePara = true;
  232. bold = true;
  233. center = true;
  234. inTitle = true;
  235. curTitle = {paraIndex, title: '', inset: sectionLevel, bodyIndex, subtitles: []};
  236. this.contents.push(curTitle);
  237. }
  238. if (tag == 'section') {
  239. if (!isFirstSection)
  240. newParagraph(' ', 1);
  241. isFirstSection = false;
  242. sectionLevel++;
  243. }
  244. if (tag == 'emphasis' || tag == 'strong' || tag == 'sup' || tag == 'sub') {
  245. growParagraph(`<${tag}>`, 0);
  246. }
  247. if ((tag == 'p' || tag == 'empty-line' || tag == 'v')) {
  248. if (!(tag == 'p' && isFirstTitlePara))
  249. newParagraph(' ', 1);
  250. if (tag == 'p') {
  251. inPara = true;
  252. isFirstTitlePara = false;
  253. }
  254. }
  255. if (tag == 'subtitle') {
  256. newParagraph(' ', 1);
  257. isFirstTitlePara = true;
  258. bold = true;
  259. center = true;
  260. if (curTitle.paraIndex < 0) {
  261. curTitle = {paraIndex, title: 'Оглавление', inset: sectionLevel, bodyIndex, subtitles: []};
  262. this.contents.push(curTitle);
  263. }
  264. inSubtitle = true;
  265. curSubtitle = {paraIndex, inset: sectionLevel, title: ''};
  266. curTitle.subtitles.push(curSubtitle);
  267. }
  268. if (tag == 'epigraph' || tag == 'annotation') {
  269. italic = true;
  270. space += 1;
  271. }
  272. if (tag == 'poem') {
  273. newParagraph(' ', 1);
  274. }
  275. if (tag == 'text-author') {
  276. newParagraph(' ', 1);
  277. space += 1;
  278. }
  279. }
  280. };
  281. const onEndNode = (elemName) => {// eslint-disable-line no-unused-vars
  282. if (tag == elemName) {
  283. if (tag == 'binary') {
  284. binaryId = '';
  285. }
  286. if (path.indexOf('/fictionbook/body') == 0) {
  287. if (tag == 'title') {
  288. isFirstTitlePara = false;
  289. bold = false;
  290. center = false;
  291. inTitle = false;
  292. }
  293. if (tag == 'section') {
  294. sectionLevel--;
  295. }
  296. if (tag == 'emphasis' || tag == 'strong' || tag == 'sup' || tag == 'sub') {
  297. growParagraph(`</${tag}>`, 0);
  298. }
  299. if (tag == 'p') {
  300. inPara = false;
  301. }
  302. if (tag == 'subtitle') {
  303. isFirstTitlePara = false;
  304. bold = false;
  305. center = false;
  306. inSubtitle = false;
  307. }
  308. if (tag == 'epigraph' || tag == 'annotation') {
  309. italic = false;
  310. space -= 1;
  311. if (tag == 'annotation')
  312. newParagraph(' ', 1);
  313. }
  314. if (tag == 'stanza') {
  315. newParagraph(' ', 1);
  316. }
  317. if (tag == 'text-author') {
  318. space -= 1;
  319. }
  320. }
  321. path = path.substr(0, path.length - tag.length - 1);
  322. let i = path.lastIndexOf('/');
  323. if (i >= 0) {
  324. tag = path.substr(i + 1);
  325. } else {
  326. tag = path;
  327. }
  328. }
  329. };
  330. const onTextNode = (text) => {// eslint-disable-line no-unused-vars
  331. text = he.decode(text);
  332. text = text.replace(/>/g, '&gt;');
  333. text = text.replace(/</g, '&lt;');
  334. if (text && text.trim() == '')
  335. text = (text.indexOf(' ') >= 0 ? ' ' : '');
  336. if (!text)
  337. return;
  338. text = text.replace(/[\t\n\r\xa0]/g, ' ');
  339. const authorLength = (fb2.author && fb2.author.length ? fb2.author.length : 0);
  340. switch (path) {
  341. case '/fictionbook/description/title-info/author/first-name':
  342. if (authorLength)
  343. fb2.author[authorLength - 1].firstName = text;
  344. break;
  345. case '/fictionbook/description/title-info/author/middle-name':
  346. if (authorLength)
  347. fb2.author[authorLength - 1].middleName = text;
  348. break;
  349. case '/fictionbook/description/title-info/author/last-name':
  350. if (authorLength)
  351. fb2.author[authorLength - 1].lastName = text;
  352. break;
  353. case '/fictionbook/description/title-info/genre':
  354. fb2.genre = text;
  355. break;
  356. case '/fictionbook/description/title-info/date':
  357. fb2.date = text;
  358. break;
  359. case '/fictionbook/description/title-info/book-title':
  360. fb2.bookTitle = text;
  361. break;
  362. case '/fictionbook/description/title-info/id':
  363. fb2.id = text;
  364. break;
  365. }
  366. if (path.indexOf('/fictionbook/description/title-info/annotation') == 0) {
  367. if (!fb2.annotation)
  368. fb2.annotation = '';
  369. if (tag != 'annotation')
  370. fb2.annotation += `<${tag}>${text}</${tag}>`;
  371. else
  372. fb2.annotation += text;
  373. }
  374. let tOpen = (center ? '<center>' : '');
  375. tOpen += (bold ? '<strong>' : '');
  376. tOpen += (italic ? '<emphasis>' : '');
  377. tOpen += (space ? `<space w="${space}">` : '');
  378. let tClose = (space ? '</space>' : '');
  379. tClose += (italic ? '</emphasis>' : '');
  380. tClose += (bold ? '</strong>' : '');
  381. tClose += (center ? '</center>' : '');
  382. if (path.indexOf('/fictionbook/body/title') == 0 ||
  383. path.indexOf('/fictionbook/body/section') == 0 ||
  384. path.indexOf('/fictionbook/body/epigraph') == 0
  385. ) {
  386. growParagraph(`${tOpen}${text}${tClose}`, text.length);
  387. }
  388. if (binaryId) {
  389. dimPromises.push(getImageDimensions(binaryId, binaryType, text));
  390. }
  391. };
  392. const onProgress = async(prog) => {
  393. await utils.sleep(1);
  394. callback(prog);
  395. };
  396. await sax.parse(data, {
  397. onStartNode, onEndNode, onTextNode, onProgress
  398. });
  399. if (dimPromises.length) {
  400. try {
  401. await Promise.all(dimPromises);
  402. } catch (e) {
  403. //
  404. }
  405. }
  406. this.fb2 = fb2;
  407. this.para = para;
  408. this.textLength = paraOffset;
  409. callback(100);
  410. await utils.sleep(10);
  411. return {fb2};
  412. }
  413. findParaIndex(bookPos) {
  414. let result = undefined;
  415. //дихотомия
  416. let first = 0;
  417. let last = this.para.length - 1;
  418. while (first < last) {
  419. let mid = first + Math.floor((last - first)/2);
  420. if (bookPos <= this.para[mid].offset + this.para[mid].length - 1)
  421. last = mid;
  422. else
  423. first = mid + 1;
  424. }
  425. if (last >= 0) {
  426. const ofs = this.para[last].offset;
  427. if (bookPos >= ofs && bookPos < ofs + this.para[last].length)
  428. result = last;
  429. }
  430. return result;
  431. }
  432. splitToStyle(s) {
  433. let result = [];/*array of {
  434. style: {bold: Boolean, italic: Boolean, sup: Boolean, sub: Boolean, center: Boolean, space: Number},
  435. image: {local: Boolean, inline: Boolean, id: String},
  436. text: String,
  437. }*/
  438. let style = {};
  439. let image = {};
  440. const onTextNode = async(text) => {// eslint-disable-line no-unused-vars
  441. result.push({
  442. style: Object.assign({}, style),
  443. image,
  444. text
  445. });
  446. };
  447. const onStartNode = async(elemName, tail) => {// eslint-disable-line no-unused-vars
  448. switch (elemName) {
  449. case 'strong':
  450. style.bold = true;
  451. break;
  452. case 'emphasis':
  453. style.italic = true;
  454. break;
  455. case 'sup':
  456. style.sup = true;
  457. break;
  458. case 'sub':
  459. style.sub = true;
  460. break;
  461. case 'center':
  462. style.center = true;
  463. break;
  464. case 'space': {
  465. let attrs = sax.getAttrsSync(tail);
  466. if (attrs.w && attrs.w.value)
  467. style.space = attrs.w.value;
  468. break;
  469. }
  470. case 'image': {
  471. let attrs = sax.getAttrsSync(tail);
  472. if (attrs.href && attrs.href.value) {
  473. let id = attrs.href.value;
  474. let local = false;
  475. if (id[0] == '#') {
  476. id = id.substr(1);
  477. local = true;
  478. }
  479. image = {local, inline: false, id};
  480. }
  481. break;
  482. }
  483. case 'image-inline': {
  484. let attrs = sax.getAttrsSync(tail);
  485. if (attrs.href && attrs.href.value) {
  486. let id = attrs.href.value;
  487. let local = false;
  488. if (id[0] == '#') {
  489. id = id.substr(1);
  490. local = true;
  491. }
  492. result.push({
  493. style: Object.assign({}, style),
  494. image: {local, inline: true, id},
  495. text: ''
  496. });
  497. }
  498. break;
  499. }
  500. }
  501. };
  502. const onEndNode = async(elemName) => {// eslint-disable-line no-unused-vars
  503. switch (elemName) {
  504. case 'strong':
  505. style.bold = false;
  506. break;
  507. case 'emphasis':
  508. style.italic = false;
  509. break;
  510. case 'sup':
  511. style.sup = false;
  512. break;
  513. case 'sub':
  514. style.sub = false;
  515. break;
  516. case 'center':
  517. style.center = false;
  518. break;
  519. case 'space':
  520. style.space = 0;
  521. break;
  522. case 'image':
  523. image = {};
  524. break;
  525. case 'image-inline':
  526. break;
  527. }
  528. };
  529. sax.parseSync(s, {
  530. onStartNode, onEndNode, onTextNode
  531. });
  532. //длинные слова (или белиберду без пробелов) тоже разобьем
  533. const maxWordLength = this.maxWordLength;
  534. const parts = result;
  535. result = [];
  536. for (const part of parts) {
  537. let p = part;
  538. if (!p.image.id) {
  539. let i = 0;
  540. let spaceIndex = -1;
  541. while (i < p.text.length) {
  542. if (p.text[i] == ' ')
  543. spaceIndex = i;
  544. if (i - spaceIndex >= maxWordLength && i < p.text.length - 1 &&
  545. this.measureText(p.text.substr(spaceIndex + 1, i - spaceIndex), p.style) >= this.w - this.p) {
  546. result.push({style: p.style, image: p.image, text: p.text.substr(0, i + 1)});
  547. p = {style: p.style, image: p.image, text: p.text.substr(i + 1)};
  548. spaceIndex = -1;
  549. i = -1;
  550. }
  551. i++;
  552. }
  553. }
  554. result.push(p);
  555. }
  556. return result;
  557. }
  558. splitToSlogi(word) {
  559. let result = [];
  560. const glas = new Set(['а', 'А', 'о', 'О', 'и', 'И', 'е', 'Е', 'ё', 'Ё', 'э', 'Э', 'ы', 'Ы', 'у', 'У', 'ю', 'Ю', 'я', 'Я']);
  561. const soglas = new Set([
  562. 'б', 'в', 'г', 'д', 'ж', 'з', 'й', 'к', 'л', 'м', 'н', 'п', 'р', 'с', 'т', 'ф', 'х', 'ц', 'ч', 'ш', 'щ',
  563. 'Б', 'В', 'Г', 'Д', 'Ж', 'З', 'Й', 'К', 'Л', 'М', 'Н', 'П', 'Р', 'С', 'Т', 'Ф', 'Х', 'Ч', 'Ц', 'Ш', 'Щ'
  564. ]);
  565. const znak = new Set(['ь', 'Ь', 'ъ', 'Ъ', 'й', 'Й']);
  566. const alpha = new Set([...glas, ...soglas, ...znak]);
  567. let slog = '';
  568. let slogLen = 0;
  569. const len = word.length;
  570. word += ' ';
  571. for (let i = 0; i < len; i++) {
  572. slog += word[i];
  573. if (alpha.has(word[i]))
  574. slogLen++;
  575. if (slogLen > 1 && i < len - 2 && (
  576. //гласная, а следом не 2 согласные буквы
  577. (glas.has(word[i]) && !(soglas.has(word[i + 1]) &&
  578. soglas.has(word[i + 2])) && alpha.has(word[i + 1]) && alpha.has(word[i + 2])
  579. ) ||
  580. //предыдущая не согласная буква, текущая согласная, а следом согласная и согласная|гласная буквы
  581. (alpha.has(word[i - 1]) && !soglas.has(word[i - 1]) &&
  582. soglas.has(word[i]) && soglas.has(word[i + 1]) &&
  583. (glas.has(word[i + 2]) || soglas.has(word[i + 2])) &&
  584. alpha.has(word[i + 1]) && alpha.has(word[i + 2])
  585. ) ||
  586. //мягкий или твердый знак или Й
  587. (znak.has(word[i]) && alpha.has(word[i + 1]) && alpha.has(word[i + 2])) ||
  588. (word[i] == '-')
  589. ) &&
  590. //нельзя оставлять окончания на ь, ъ, й
  591. !(znak.has(word[i + 2]) && !alpha.has(word[i + 3]))
  592. ) {
  593. result.push(slog);
  594. slog = '';
  595. slogLen = 0;
  596. }
  597. }
  598. if (slog)
  599. result.push(slog);
  600. return result;
  601. }
  602. parsePara(paraIndex) {
  603. const para = this.para[paraIndex];
  604. if (!this.force &&
  605. para.parsed &&
  606. para.parsed.testWidth === this.testWidth &&
  607. para.parsed.w === this.w &&
  608. para.parsed.p === this.p &&
  609. para.parsed.wordWrap === this.wordWrap &&
  610. para.parsed.maxWordLength === this.maxWordLength &&
  611. para.parsed.font === this.font &&
  612. para.parsed.cutEmptyParagraphs === this.cutEmptyParagraphs &&
  613. para.parsed.addEmptyParagraphs === this.addEmptyParagraphs &&
  614. para.parsed.showImages === this.showImages &&
  615. para.parsed.imageHeightLines === this.imageHeightLines &&
  616. para.parsed.imageFitWidth === this.imageFitWidth &&
  617. para.parsed.compactTextPerc === this.compactTextPerc
  618. )
  619. return para.parsed;
  620. const parsed = {
  621. testWidth: this.testWidth,
  622. w: this.w,
  623. p: this.p,
  624. wordWrap: this.wordWrap,
  625. maxWordLength: this.maxWordLength,
  626. font: this.font,
  627. cutEmptyParagraphs: this.cutEmptyParagraphs,
  628. addEmptyParagraphs: this.addEmptyParagraphs,
  629. showImages: this.showImages,
  630. imageHeightLines: this.imageHeightLines,
  631. imageFitWidth: this.imageFitWidth,
  632. compactTextPerc: this.compactTextPerc,
  633. visible: true, //вычисляется позже
  634. };
  635. const lines = []; /* array of
  636. {
  637. begin: Number,
  638. end: Number,
  639. first: Boolean,
  640. last: Boolean,
  641. parts: array of {
  642. style: {bold: Boolean, italic: Boolean, center: Boolean},
  643. image: {local: Boolean, inline: Boolean, id: String, imageLine: Number, lineCount: Number, paraIndex: Number, w: Number, h: Number},
  644. text: String,
  645. }
  646. }*/
  647. let parts = this.splitToStyle(para.text);
  648. //инициализация парсера
  649. let line = {begin: para.offset, parts: []};
  650. let paragraphText = '';//текст параграфа
  651. let partText = '';//накапливаемый кусок со стилем
  652. let str = '';//измеряемая строка
  653. let prevStr = '';//строка без крайнего слова
  654. let j = 0;//номер строки
  655. let style = {};
  656. let ofs = 0;//смещение от начала параграфа para.offset
  657. let imgW = 0;
  658. let imageInPara = false;
  659. const compactWidth = this.measureText('W', {})*this.compactTextPerc/100;
  660. // тут начинается самый замес, перенос по слогам и стилизация, а также изображения
  661. for (const part of parts) {
  662. style = part.style;
  663. paragraphText += part.text;
  664. //изображения
  665. if (part.image.id && !part.image.inline) {
  666. imageInPara = true;
  667. let bin = this.binary[part.image.id];
  668. if (!bin)
  669. bin = {h: 1, w: 1};
  670. let lineCount = this.imageHeightLines;
  671. let c = Math.ceil(bin.h/this.lineHeight);
  672. const maxH = lineCount*this.lineHeight;
  673. let maxH2 = maxH;
  674. if (this.imageFitWidth && bin.w > this.w) {
  675. maxH2 = bin.h*this.w/bin.w;
  676. c = Math.ceil(maxH2/this.lineHeight);
  677. }
  678. lineCount = (c < lineCount ? c : lineCount);
  679. let imageHeight = (maxH2 < maxH ? maxH2 : maxH);
  680. imageHeight = (imageHeight <= bin.h ? imageHeight : bin.h);
  681. let imageWidth = (bin.h > imageHeight ? bin.w*imageHeight/bin.h : bin.w);
  682. let i = 0;
  683. for (; i < lineCount - 1; i++) {
  684. line.end = para.offset + ofs;
  685. line.first = (j == 0);
  686. line.last = false;
  687. line.parts.push({style, text: ' ', image: {
  688. local: part.image.local,
  689. inline: false,
  690. id: part.image.id,
  691. imageLine: i,
  692. lineCount,
  693. paraIndex,
  694. w: imageWidth,
  695. h: imageHeight,
  696. }});
  697. lines.push(line);
  698. line = {begin: line.end + 1, parts: []};
  699. ofs++;
  700. j++;
  701. }
  702. line.first = (j == 0);
  703. line.last = true;
  704. line.parts.push({style, text: ' ',
  705. image: {local: part.image.local, inline: false, id: part.image.id,
  706. imageLine: i, lineCount, paraIndex, w: imageWidth, h: imageHeight}
  707. });
  708. continue;
  709. }
  710. if (part.image.id && part.image.inline && this.showImages) {
  711. const bin = this.binary[part.image.id];
  712. if (bin) {
  713. let imgH = (bin.h > this.fontSize ? this.fontSize : bin.h);
  714. imgW += bin.w*imgH/bin.h;
  715. line.parts.push({style, text: '',
  716. image: {local: part.image.local, inline: true, id: part.image.id}});
  717. }
  718. }
  719. let words = part.text.split(' ');
  720. let sp1 = '';
  721. let sp2 = '';
  722. for (let i = 0; i < words.length; i++) {
  723. const word = words[i];
  724. ofs += word.length + (i < words.length - 1 ? 1 : 0);
  725. if (word == '' && i > 0 && i < words.length - 1)
  726. continue;
  727. str += sp1 + word;
  728. let p = (j == 0 ? parsed.p : 0) + imgW;
  729. p = (style.space ? p + parsed.p*style.space : p);
  730. let w = this.measureText(str, style) + p;
  731. let wordTail = word;
  732. if (w > parsed.w + compactWidth && prevStr != '') {
  733. if (parsed.wordWrap) {//по слогам
  734. let slogi = this.splitToSlogi(word);
  735. if (slogi.length > 1) {
  736. let s = prevStr + sp1;
  737. let ss = sp1;
  738. let pw;
  739. const slogiLen = slogi.length;
  740. for (let k = 0; k < slogiLen - 1; k++) {
  741. let slog = slogi[0];
  742. let ww = this.measureText(s + slog + (slog[slog.length - 1] == '-' ? '' : '-'), style) + p;
  743. if (ww <= parsed.w + compactWidth) {
  744. s += slog;
  745. ss += slog;
  746. } else
  747. break;
  748. pw = ww;
  749. slogi.shift();
  750. }
  751. if (pw) {
  752. partText += ss + (ss[ss.length - 1] == '-' ? '' : '-');
  753. wordTail = slogi.join('');
  754. }
  755. }
  756. }
  757. if (partText != '')
  758. line.parts.push({style, text: partText});
  759. if (line.parts.length) {//корявенько, коррекция при переносе, отрефакторить не вышло
  760. let t = line.parts[line.parts.length - 1].text;
  761. if (t[t.length - 1] == ' ') {
  762. line.parts[line.parts.length - 1].text = t.trimRight();
  763. }
  764. }
  765. line.end = para.offset + ofs - wordTail.length - 1 - (i < words.length - 1 ? 1 : 0);
  766. if (line.end - line.begin < 0)
  767. console.error(`Parse error, empty line in paragraph ${paraIndex}`);
  768. line.first = (j == 0);
  769. line.last = false;
  770. lines.push(line);
  771. line = {begin: line.end + 1, parts: []};
  772. partText = '';
  773. sp2 = '';
  774. str = wordTail;
  775. imgW = 0;
  776. j++;
  777. }
  778. prevStr = str;
  779. partText += sp2 + wordTail;
  780. sp1 = ' ';
  781. sp2 = ' ';
  782. }
  783. if (partText != '')
  784. line.parts.push({style, text: partText});
  785. partText = '';
  786. }
  787. if (line.parts.length) {//корявенько, коррекция при переносе
  788. let t = line.parts[line.parts.length - 1].text;
  789. if (t[t.length - 1] == ' ') {
  790. line.parts[line.parts.length - 1].text = t.trimRight();
  791. }
  792. line.end = para.offset + para.length - 1;
  793. if (line.end - line.begin < 0)
  794. console.error(`Parse error, empty line in paragraph ${paraIndex}`);
  795. line.first = (j == 0);
  796. line.last = true;
  797. lines.push(line);
  798. } else {//подстраховка
  799. if (lines.length) {
  800. line = lines[lines.length - 1];
  801. const end = para.offset + para.length - 1;
  802. if (line.end != end)
  803. console.error(`Parse error, wrong end in paragraph ${paraIndex}`);
  804. line.end = end;
  805. }
  806. }
  807. //parsed.visible
  808. if (imageInPara) {
  809. parsed.visible = this.showImages;
  810. } else {
  811. parsed.visible = !(
  812. (para.addIndex > this.addEmptyParagraphs) ||
  813. (para.addIndex == 0 && this.cutEmptyParagraphs && paragraphText.trim() == '')
  814. );
  815. }
  816. parsed.lines = lines;
  817. para.parsed = parsed;
  818. return parsed;
  819. }
  820. findLineIndex(bookPos, lines) {
  821. let result = undefined;
  822. //дихотомия
  823. let first = 0;
  824. let last = lines.length - 1;
  825. while (first < last) {
  826. let mid = first + Math.floor((last - first)/2);
  827. if (bookPos <= lines[mid].end)
  828. last = mid;
  829. else
  830. first = mid + 1;
  831. }
  832. if (last >= 0) {
  833. if (bookPos >= lines[last].begin && bookPos <= lines[last].end)
  834. result = last;
  835. }
  836. return result;
  837. }
  838. getLines(bookPos, n) {
  839. let result = [];
  840. let paraIndex = this.findParaIndex(bookPos);
  841. if (paraIndex === undefined)
  842. return null;
  843. if (n > 0) {
  844. let parsed = this.parsePara(paraIndex);
  845. let i = this.findLineIndex(bookPos, parsed.lines);
  846. if (i === undefined)
  847. return null;
  848. while (n > 0) {
  849. if (parsed.visible) {
  850. result.push(parsed.lines[i]);
  851. n--;
  852. }
  853. i++;
  854. if (i >= parsed.lines.length) {
  855. paraIndex++;
  856. if (paraIndex < this.para.length)
  857. parsed = this.parsePara(paraIndex);
  858. else
  859. break;
  860. i = 0;
  861. }
  862. }
  863. } else if (n < 0) {
  864. n = -n;
  865. let parsed = this.parsePara(paraIndex);
  866. let i = this.findLineIndex(bookPos, parsed.lines);
  867. if (i === undefined)
  868. return null;
  869. while (n > 0) {
  870. if (parsed.visible) {
  871. result.push(parsed.lines[i]);
  872. n--;
  873. }
  874. i--;
  875. if (i < 0) {
  876. paraIndex--;
  877. if (paraIndex >= 0)
  878. parsed = this.parsePara(paraIndex);
  879. else
  880. break;
  881. i = parsed.lines.length - 1;
  882. }
  883. }
  884. }
  885. if (!result.length)
  886. result = null;
  887. return result;
  888. }
  889. }