BookParser.js 36 KB

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