BookParser.js 37 KB

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