BookParser.js 37 KB

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