BookParser.js 34 KB

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