BookParser.js 32 KB

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