BookParser.js 34 KB

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