BookParser.js 32 KB

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