BookParser.js 36 KB

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