BookParser.js 32 KB

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