BookParser.js 35 KB

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