BookParser.js 32 KB

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