BookParser.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  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. findParaIndex(bookPos) {
  387. let result = undefined;
  388. //дихотомия
  389. let first = 0;
  390. let last = this.para.length - 1;
  391. while (first < last) {
  392. let mid = first + Math.floor((last - first)/2);
  393. if (bookPos <= this.para[mid].offset + this.para[mid].length - 1)
  394. last = mid;
  395. else
  396. first = mid + 1;
  397. }
  398. if (last >= 0) {
  399. const ofs = this.para[last].offset;
  400. if (bookPos >= ofs && bookPos < ofs + this.para[last].length)
  401. result = last;
  402. }
  403. return result;
  404. }
  405. splitToStyle(s) {
  406. let result = [];/*array of {
  407. style: {bold: Boolean, italic: Boolean, center: Boolean, space: Number},
  408. image: {local: Boolean, inline: Boolean, id: String},
  409. text: String,
  410. }*/
  411. let style = {};
  412. let image = {};
  413. const onTextNode = async(text) => {// eslint-disable-line no-unused-vars
  414. result.push({
  415. style: Object.assign({}, style),
  416. image,
  417. text
  418. });
  419. };
  420. const onStartNode = async(elemName, tail) => {// eslint-disable-line no-unused-vars
  421. switch (elemName) {
  422. case 'strong':
  423. style.bold = true;
  424. break;
  425. case 'emphasis':
  426. style.italic = true;
  427. break;
  428. case 'center':
  429. style.center = true;
  430. break;
  431. case 'space': {
  432. let attrs = sax.getAttrsSync(tail);
  433. if (attrs.w && attrs.w.value)
  434. style.space = attrs.w.value;
  435. break;
  436. }
  437. case 'image': {
  438. let attrs = sax.getAttrsSync(tail);
  439. if (attrs.href && attrs.href.value) {
  440. let id = attrs.href.value;
  441. let local = false;
  442. if (id[0] == '#') {
  443. id = id.substr(1);
  444. local = true;
  445. }
  446. image = {local, inline: false, id};
  447. }
  448. break;
  449. }
  450. case 'image-inline': {
  451. let attrs = sax.getAttrsSync(tail);
  452. if (attrs.href && attrs.href.value) {
  453. let id = attrs.href.value;
  454. let local = false;
  455. if (id[0] == '#') {
  456. id = id.substr(1);
  457. local = true;
  458. }
  459. result.push({
  460. style: Object.assign({}, style),
  461. image: {local, inline: true, id},
  462. text: ''
  463. });
  464. }
  465. break;
  466. }
  467. }
  468. };
  469. const onEndNode = async(elemName) => {// eslint-disable-line no-unused-vars
  470. switch (elemName) {
  471. case 'strong':
  472. style.bold = false;
  473. break;
  474. case 'emphasis':
  475. style.italic = false;
  476. break;
  477. case 'center':
  478. style.center = false;
  479. break;
  480. case 'space':
  481. style.space = 0;
  482. break;
  483. case 'image':
  484. image = {};
  485. break;
  486. case 'image-inline':
  487. break;
  488. }
  489. };
  490. sax.parseSync(s, {
  491. onStartNode, onEndNode, onTextNode
  492. });
  493. //длинные слова (или белиберду без пробелов) тоже разобьем
  494. const maxWordLength = this.maxWordLength;
  495. const parts = result;
  496. result = [];
  497. for (const part of parts) {
  498. let p = part;
  499. if (!p.image.id) {
  500. let i = 0;
  501. let spaceIndex = -1;
  502. while (i < p.text.length) {
  503. if (p.text[i] == ' ')
  504. spaceIndex = i;
  505. if (i - spaceIndex >= maxWordLength && i < p.text.length - 1 &&
  506. this.measureText(p.text.substr(spaceIndex + 1, i - spaceIndex), p.style) >= this.w - this.p) {
  507. result.push({style: p.style, image: p.image, text: p.text.substr(0, i + 1)});
  508. p = {style: p.style, image: p.image, text: p.text.substr(i + 1)};
  509. spaceIndex = -1;
  510. i = -1;
  511. }
  512. i++;
  513. }
  514. }
  515. result.push(p);
  516. }
  517. return result;
  518. }
  519. splitToSlogi(word) {
  520. let result = [];
  521. const glas = new Set(['а', 'А', 'о', 'О', 'и', 'И', 'е', 'Е', 'ё', 'Ё', 'э', 'Э', 'ы', 'Ы', 'у', 'У', 'ю', 'Ю', 'я', 'Я']);
  522. const soglas = new Set([
  523. 'б', 'в', 'г', 'д', 'ж', 'з', 'й', 'к', 'л', 'м', 'н', 'п', 'р', 'с', 'т', 'ф', 'х', 'ц', 'ч', 'ш', 'щ',
  524. 'Б', 'В', 'Г', 'Д', 'Ж', 'З', 'Й', 'К', 'Л', 'М', 'Н', 'П', 'Р', 'С', 'Т', 'Ф', 'Х', 'Ч', 'Ц', 'Ш', 'Щ'
  525. ]);
  526. const znak = new Set(['ь', 'Ь', 'ъ', 'Ъ', 'й', 'Й']);
  527. const alpha = new Set([...glas, ...soglas, ...znak]);
  528. let slog = '';
  529. let slogLen = 0;
  530. const len = word.length;
  531. word += ' ';
  532. for (let i = 0; i < len; i++) {
  533. slog += word[i];
  534. if (alpha.has(word[i]))
  535. slogLen++;
  536. if (slogLen > 1 && i < len - 2 && (
  537. //гласная, а следом не 2 согласные буквы
  538. (glas.has(word[i]) && !(soglas.has(word[i + 1]) &&
  539. soglas.has(word[i + 2])) && alpha.has(word[i + 1]) && alpha.has(word[i + 2])
  540. ) ||
  541. //предыдущая не согласная буква, текущая согласная, а следом согласная и согласная|гласная буквы
  542. (alpha.has(word[i - 1]) && !soglas.has(word[i - 1]) &&
  543. soglas.has(word[i]) && soglas.has(word[i + 1]) &&
  544. (glas.has(word[i + 2]) || soglas.has(word[i + 2])) &&
  545. alpha.has(word[i + 1]) && alpha.has(word[i + 2])
  546. ) ||
  547. //мягкий или твердый знак или Й
  548. (znak.has(word[i]) && alpha.has(word[i + 1]) && alpha.has(word[i + 2])) ||
  549. (word[i] == '-')
  550. ) &&
  551. //нельзя оставлять окончания на ь, ъ, й
  552. !(znak.has(word[i + 2]) && !alpha.has(word[i + 3]))
  553. ) {
  554. result.push(slog);
  555. slog = '';
  556. slogLen = 0;
  557. }
  558. }
  559. if (slog)
  560. result.push(slog);
  561. return result;
  562. }
  563. parsePara(paraIndex) {
  564. const para = this.para[paraIndex];
  565. if (!this.force &&
  566. para.parsed &&
  567. para.parsed.testWidth === this.testWidth &&
  568. para.parsed.w === this.w &&
  569. para.parsed.p === this.p &&
  570. para.parsed.wordWrap === this.wordWrap &&
  571. para.parsed.maxWordLength === this.maxWordLength &&
  572. para.parsed.font === this.font &&
  573. para.parsed.cutEmptyParagraphs === this.cutEmptyParagraphs &&
  574. para.parsed.addEmptyParagraphs === this.addEmptyParagraphs &&
  575. para.parsed.showImages === this.showImages &&
  576. para.parsed.imageHeightLines === this.imageHeightLines &&
  577. para.parsed.imageFitWidth === this.imageFitWidth &&
  578. para.parsed.compactTextPerc === this.compactTextPerc
  579. )
  580. return para.parsed;
  581. const parsed = {
  582. testWidth: this.testWidth,
  583. w: this.w,
  584. p: this.p,
  585. wordWrap: this.wordWrap,
  586. maxWordLength: this.maxWordLength,
  587. font: this.font,
  588. cutEmptyParagraphs: this.cutEmptyParagraphs,
  589. addEmptyParagraphs: this.addEmptyParagraphs,
  590. showImages: this.showImages,
  591. imageHeightLines: this.imageHeightLines,
  592. imageFitWidth: this.imageFitWidth,
  593. compactTextPerc: this.compactTextPerc,
  594. visible: true, //вычисляется позже
  595. };
  596. const lines = []; /* array of
  597. {
  598. begin: Number,
  599. end: Number,
  600. first: Boolean,
  601. last: Boolean,
  602. parts: array of {
  603. style: {bold: Boolean, italic: Boolean, center: Boolean},
  604. image: {local: Boolean, inline: Boolean, id: String, imageLine: Number, lineCount: Number, paraIndex: Number, w: Number, h: Number},
  605. text: String,
  606. }
  607. }*/
  608. let parts = this.splitToStyle(para.text);
  609. //инициализация парсера
  610. let line = {begin: para.offset, parts: []};
  611. let paragraphText = '';//текст параграфа
  612. let partText = '';//накапливаемый кусок со стилем
  613. let str = '';//измеряемая строка
  614. let prevStr = '';//строка без крайнего слова
  615. let j = 0;//номер строки
  616. let style = {};
  617. let ofs = 0;//смещение от начала параграфа para.offset
  618. let imgW = 0;
  619. let imageInPara = false;
  620. const compactWidth = this.measureText('W', {})*this.compactTextPerc/100;
  621. // тут начинается самый замес, перенос по слогам и стилизация, а также изображения
  622. for (const part of parts) {
  623. style = part.style;
  624. paragraphText += part.text;
  625. //изображения
  626. if (part.image.id && !part.image.inline) {
  627. imageInPara = true;
  628. let bin = this.binary[part.image.id];
  629. if (!bin)
  630. bin = {h: 1, w: 1};
  631. let lineCount = this.imageHeightLines;
  632. let c = Math.ceil(bin.h/this.lineHeight);
  633. const maxH = lineCount*this.lineHeight;
  634. let maxH2 = maxH;
  635. if (this.imageFitWidth && bin.w > this.w) {
  636. maxH2 = bin.h*this.w/bin.w;
  637. c = Math.ceil(maxH2/this.lineHeight);
  638. }
  639. lineCount = (c < lineCount ? c : lineCount);
  640. let imageHeight = (maxH2 < maxH ? maxH2 : maxH);
  641. imageHeight = (imageHeight <= bin.h ? imageHeight : bin.h);
  642. let imageWidth = (bin.h > imageHeight ? bin.w*imageHeight/bin.h : bin.w);
  643. let i = 0;
  644. for (; i < lineCount - 1; i++) {
  645. line.end = para.offset + ofs;
  646. line.first = (j == 0);
  647. line.last = false;
  648. line.parts.push({style, text: ' ', image: {
  649. local: part.image.local,
  650. inline: false,
  651. id: part.image.id,
  652. imageLine: i,
  653. lineCount,
  654. paraIndex,
  655. w: imageWidth,
  656. h: imageHeight,
  657. }});
  658. lines.push(line);
  659. line = {begin: line.end + 1, parts: []};
  660. ofs++;
  661. j++;
  662. }
  663. line.first = (j == 0);
  664. line.last = true;
  665. line.parts.push({style, text: ' ',
  666. image: {local: part.image.local, inline: false, id: part.image.id,
  667. imageLine: i, lineCount, paraIndex, w: imageWidth, h: imageHeight}
  668. });
  669. continue;
  670. }
  671. if (part.image.id && part.image.inline && this.showImages) {
  672. const bin = this.binary[part.image.id];
  673. if (bin) {
  674. let imgH = (bin.h > this.fontSize ? this.fontSize : bin.h);
  675. imgW += bin.w*imgH/bin.h;
  676. line.parts.push({style, text: '',
  677. image: {local: part.image.local, inline: true, id: part.image.id}});
  678. }
  679. }
  680. let words = part.text.split(' ');
  681. let sp1 = '';
  682. let sp2 = '';
  683. for (let i = 0; i < words.length; i++) {
  684. const word = words[i];
  685. ofs += word.length + (i < words.length - 1 ? 1 : 0);
  686. if (word == '' && i > 0 && i < words.length - 1)
  687. continue;
  688. str += sp1 + word;
  689. let p = (j == 0 ? parsed.p : 0) + imgW;
  690. p = (style.space ? p + parsed.p*style.space : p);
  691. let w = this.measureText(str, style) + p;
  692. let wordTail = word;
  693. if (w > parsed.w + compactWidth && prevStr != '') {
  694. if (parsed.wordWrap) {//по слогам
  695. let slogi = this.splitToSlogi(word);
  696. if (slogi.length > 1) {
  697. let s = prevStr + sp1;
  698. let ss = sp1;
  699. let pw;
  700. const slogiLen = slogi.length;
  701. for (let k = 0; k < slogiLen - 1; k++) {
  702. let slog = slogi[0];
  703. let ww = this.measureText(s + slog + (slog[slog.length - 1] == '-' ? '' : '-'), style) + p;
  704. if (ww <= parsed.w + compactWidth) {
  705. s += slog;
  706. ss += slog;
  707. } else
  708. break;
  709. pw = ww;
  710. slogi.shift();
  711. }
  712. if (pw) {
  713. partText += ss + (ss[ss.length - 1] == '-' ? '' : '-');
  714. wordTail = slogi.join('');
  715. }
  716. }
  717. }
  718. if (partText != '')
  719. line.parts.push({style, text: partText});
  720. if (line.parts.length) {//корявенько, коррекция при переносе, отрефакторить не вышло
  721. let t = line.parts[line.parts.length - 1].text;
  722. if (t[t.length - 1] == ' ') {
  723. line.parts[line.parts.length - 1].text = t.trimRight();
  724. }
  725. }
  726. line.end = para.offset + ofs - wordTail.length - 1 - (i < words.length - 1 ? 1 : 0);
  727. if (line.end - line.begin < 0)
  728. console.error(`Parse error, empty line in paragraph ${paraIndex}`);
  729. line.first = (j == 0);
  730. line.last = false;
  731. lines.push(line);
  732. line = {begin: line.end + 1, parts: []};
  733. partText = '';
  734. sp2 = '';
  735. str = wordTail;
  736. imgW = 0;
  737. j++;
  738. }
  739. prevStr = str;
  740. partText += sp2 + wordTail;
  741. sp1 = ' ';
  742. sp2 = ' ';
  743. }
  744. if (partText != '')
  745. line.parts.push({style, text: partText});
  746. partText = '';
  747. }
  748. if (line.parts.length) {//корявенько, коррекция при переносе
  749. let t = line.parts[line.parts.length - 1].text;
  750. if (t[t.length - 1] == ' ') {
  751. line.parts[line.parts.length - 1].text = t.trimRight();
  752. }
  753. line.end = para.offset + para.length - 1;
  754. if (line.end - line.begin < 0)
  755. console.error(`Parse error, empty line in paragraph ${paraIndex}`);
  756. line.first = (j == 0);
  757. line.last = true;
  758. lines.push(line);
  759. } else {//подстраховка
  760. if (lines.length) {
  761. line = lines[lines.length - 1];
  762. const end = para.offset + para.length - 1;
  763. if (line.end != end)
  764. console.error(`Parse error, wrong end in paragraph ${paraIndex}`);
  765. line.end = end;
  766. }
  767. }
  768. //parsed.visible
  769. if (imageInPara) {
  770. parsed.visible = this.showImages;
  771. } else {
  772. parsed.visible = !(
  773. (para.addIndex > this.addEmptyParagraphs) ||
  774. (para.addIndex == 0 && this.cutEmptyParagraphs && paragraphText.trim() == '')
  775. );
  776. }
  777. parsed.lines = lines;
  778. para.parsed = parsed;
  779. return parsed;
  780. }
  781. findLineIndex(bookPos, lines) {
  782. let result = undefined;
  783. //дихотомия
  784. let first = 0;
  785. let last = lines.length - 1;
  786. while (first < last) {
  787. let mid = first + Math.floor((last - first)/2);
  788. if (bookPos <= lines[mid].end)
  789. last = mid;
  790. else
  791. first = mid + 1;
  792. }
  793. if (last >= 0) {
  794. if (bookPos >= lines[last].begin && bookPos <= lines[last].end)
  795. result = last;
  796. }
  797. return result;
  798. }
  799. getLines(bookPos, n) {
  800. let result = [];
  801. let paraIndex = this.findParaIndex(bookPos);
  802. if (paraIndex === undefined)
  803. return null;
  804. if (n > 0) {
  805. let parsed = this.parsePara(paraIndex);
  806. let i = this.findLineIndex(bookPos, parsed.lines);
  807. if (i === undefined)
  808. return null;
  809. while (n > 0) {
  810. if (parsed.visible) {
  811. result.push(parsed.lines[i]);
  812. n--;
  813. }
  814. i++;
  815. if (i >= parsed.lines.length) {
  816. paraIndex++;
  817. if (paraIndex < this.para.length)
  818. parsed = this.parsePara(paraIndex);
  819. else
  820. break;
  821. i = 0;
  822. }
  823. }
  824. } else if (n < 0) {
  825. n = -n;
  826. let parsed = this.parsePara(paraIndex);
  827. let i = this.findLineIndex(bookPos, parsed.lines);
  828. if (i === undefined)
  829. return null;
  830. while (n > 0) {
  831. if (parsed.visible) {
  832. result.push(parsed.lines[i]);
  833. n--;
  834. }
  835. i--;
  836. if (i < 0) {
  837. paraIndex--;
  838. if (paraIndex >= 0)
  839. parsed = this.parsePara(paraIndex);
  840. else
  841. break;
  842. i = parsed.lines.length - 1;
  843. }
  844. }
  845. }
  846. if (!result.length)
  847. result = null;
  848. return result;
  849. }
  850. }