BookParser.js 33 KB

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