BookParser.js 37 KB

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