r_conscale
[xreader.git] / xreaderfmt.d
blob7f23034bbbc52e2d3aece9bebc1bcedd9c089520
1 /* Written by Ketmar // Invisible Vector <ketmar@ketmar.no-ip.org>
2 * Understanding is not required. Only obedience.
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 module xreaderfmt;
19 import core.time;
21 import std.concurrency;
23 import iv.strex;
25 import arsd.simpledisplay;
26 import arsd.image;
28 import iv.cmdcon;
29 import iv.nanovg;
30 import iv.nanovg.oui.blendish;
31 import iv.vfs;
32 import iv.vfs.io;
34 import booktext;
36 import xreadercfg;
37 import xlayouter;
40 // ////////////////////////////////////////////////////////////////////////// //
41 BookText loadBook (string fname) {
42 __gshared bool eliteShipsLoaded = false;
44 import std.path;
45 //import core.memory : GC;
46 fname = fname.expandTilde.absolutePath;
47 //conwriteln("loading '", fname, "'...");
48 //GC.disable();
49 auto stt = MonoTime.currTime;
50 auto book = new BookText(fname);
51 //GC.enable();
52 //GC.collect();
53 { conwriteln("loaded: '", fname, "' in ", (MonoTime.currTime-stt).total!"msecs", " milliseconds"); }
55 string[] lines;
56 string[] comments;
57 try {
58 foreach (string line; VFile(buildPath(RcDir, ".lastfile")).byLineCopy) {
59 if (line != fname) {
60 lines ~= line;
61 } else {
62 while (lines.length && lines[$-1].isComment) {
63 comments ~= lines[$-1];
64 lines = lines[0..$-1];
68 } catch (Exception) {}
69 try { import std.file; mkdirRecurse(RcDir); } catch (Exception) {}
70 auto fo = VFile(buildPath(RcDir, ".lastfile"), "w");
71 foreach (string s; lines) fo.writeln(s);
72 foreach_reverse (string s; comments) fo.writeln(s);
73 fo.writeln(fname);
75 stateFileName = buildPath(RcDir, fname.baseName~".rc");
77 if (!eliteShipsLoaded) {
78 loadEliteShips();
79 eliteShipsLoaded = true;
82 return book;
86 // ////////////////////////////////////////////////////////////////////////// //
87 private struct ImageInfo {
88 enum MaxIdleFrames = 5;
89 int iid;
90 TrueColorImage img;
91 int framesNotUsed;
94 private __gshared ImageInfo[] nvgImageIds;
97 void releaseImages (NVGContext vg) {
98 if (nvgImageIds.length) {
99 foreach (ref ImageInfo nfo; nvgImageIds) {
100 if (nfo.iid >= 0) {
101 if (++nfo.framesNotUsed > ImageInfo.MaxIdleFrames) {
102 //conwriteln("freeing image with id ", nfo.iid);
103 vg.deleteImage(nfo.iid);
104 nfo.iid = -1;
105 nfo.img = null;
113 private int registerImage (NVGContext vg, TrueColorImage img) {
114 if (vg is null || img is null) return -1;
115 uint freeIdx = uint.max;
116 foreach (immutable idx, ref ImageInfo nfo; nvgImageIds) {
117 if (nfo.img is img) {
118 assert(nfo.iid >= 0);
119 nfo.framesNotUsed = 0;
120 return nfo.iid;
122 if (freeIdx != uint.max && nfo.iid < 0) freeIdx = cast(uint)idx;
124 int iid = vg.createImageFromMemoryImage(img); //vg.createImageRGBA(img.width, img.height, img.imageData.bytes[], NVGImageFlags.None);
125 if (iid < 0) return -1;
126 nvgImageIds ~= ImageInfo(iid, img, 0);
127 return iid;
131 class BookImage : LayObject {
132 BookText book;
133 uint imageidx;
134 TrueColorImage img;
135 this (BookText abook, uint aidx) { book = abook; imageidx = aidx; img = book.images[aidx].img; }
136 override int width () { return img.width; }
137 override int spacewidth () { return 0; }
138 override int height () { return img.height; }
139 override int ascent () { return img.height; }
140 override int descent () { return 0; }
141 override bool canbreak () { return true; }
142 override bool spaced () { return false; }
143 override void draw (NVGContext vg, float x, float y) {
144 y -= img.height;
145 vg.save();
146 scope(exit) vg.restore();
147 vg.beginPath();
148 int iid = vg.registerImage(img);
149 if (iid < 0) return;
150 vg.fillPaint(vg.imagePattern(x, y, img.width, img.height, 0, iid));
151 //vg.globalAlpha(0.5);
152 vg.rect(x, y, img.width, img.height);
153 vg.fill();
158 // ////////////////////////////////////////////////////////////////////////// //
159 class BookMetadata {
160 static struct Anc {
161 dstring name;
162 uint wordidx; // first word
164 Anc[] sections;
165 Anc[uint] hrefs; // `name` is dest
166 Anc[] ids;
170 // ////////////////////////////////////////////////////////////////////////// //
171 private void fixFont (LayText lay) {
172 if (lay.fontStyle.italic) {
173 if (lay.fontStyle.bold) lay.fontStyle.fontface = lay.fontFaceId("textz");
174 else lay.fontStyle.fontface = lay.fontFaceId("texti");
175 } else if (lay.fontStyle.bold) {
176 if (lay.fontStyle.italic) lay.fontStyle.fontface = lay.fontFaceId("textz");
177 else lay.fontStyle.fontface = lay.fontFaceId("textb");
178 } else {
179 lay.fontStyle.fontface = lay.fontFaceId("text");
183 private void setNormalStyle (LayText lay) {
184 lay.fontStyle.resetAttrs;
185 lay.fontStyle.fontsize = fsizeText;
186 lay.fontStyle.color = colorText.asUint;
187 lay.lineStyle.leftpad = 0;
188 lay.lineStyle.rightpad = 0;
189 lay.lineStyle.paraIndent = 3;
190 if (optJustify) lay.lineStyle.setJustify; else lay.lineStyle.setLeft;
191 fixFont(lay);
194 private void setTitleStyle (LayText lay) {
195 lay.fontStyle.resetAttrs;
196 lay.fontStyle.bold = true;
197 lay.fontStyle.fontsize = fsizeText+4;
198 lay.fontStyle.color = colorText.asUint;
199 lay.lineStyle.leftpad = 0;
200 lay.lineStyle.rightpad = 0;
201 lay.lineStyle.paraIndent = 0;
202 lay.lineStyle.setCenter;
203 fixFont(lay);
206 private void setSubtitleStyle (LayText lay) {
207 lay.fontStyle.resetAttrs;
208 lay.fontStyle.bold = true;
209 lay.fontStyle.fontsize = fsizeText+2;
210 lay.fontStyle.color = colorText.asUint;
211 lay.lineStyle.leftpad = 0;
212 lay.lineStyle.rightpad = 0;
213 lay.lineStyle.paraIndent = 0;
214 lay.lineStyle.setCenter;
215 fixFont(lay);
218 private void setCiteStyle (LayText lay) {
219 lay.fontStyle.resetAttrs;
220 lay.fontStyle.italic = true;
221 lay.fontStyle.fontsize = fsizeText;
222 lay.fontStyle.color = colorText.asUint;
223 lay.lineStyle.leftpad = fsizeText*3;
224 lay.lineStyle.rightpad = fsizeText*3;
225 lay.lineStyle.paraIndent = 3;
226 if (optJustify) lay.lineStyle.setJustify; else lay.lineStyle.setLeft;
227 fixFont(lay);
230 private void setEpigraphStyle (LayText lay) {
231 lay.fontStyle.resetAttrs;
232 lay.fontStyle.italic = true;
233 lay.fontStyle.fontsize = fsizeText;
234 lay.fontStyle.color = colorText.asUint;
235 lay.lineStyle.leftpad = lay.width/3;
236 lay.lineStyle.rightpad = 0;
237 lay.lineStyle.paraIndent = 0;
238 lay.lineStyle.setRight;
239 fixFont(lay);
242 private void setPoemStyle (LayText lay) {
243 lay.fontStyle.resetAttrs;
244 lay.fontStyle.italic = true;
245 lay.fontStyle.fontsize = fsizeText;
246 lay.fontStyle.color = colorText.asUint;
247 lay.lineStyle.leftpad = fsizeText*3;
248 lay.lineStyle.rightpad = 0;
249 lay.lineStyle.paraIndent = 0;
250 lay.lineStyle.setLeft;
251 fixFont(lay);
255 // ////////////////////////////////////////////////////////////////////////// //
256 public BookMetadata formatBook (BookText book, LayText lay) {
257 assert(book !is null);
259 BookMetadata meta = new BookMetadata();
261 void dumpTree (Tag ct) {
262 while (ct !is null) {
263 conwriteln("tag: ", ct.name);
264 ct = ct.parent;
268 void badTag (Tag tag, string msg=null) {
269 import std.string : format, indexOf;
270 assert(tag !is null);
271 dumpTree(tag);
272 if (msg.length == 0) msg = "invalid tag: '%s'";
273 if (msg.indexOf("%s") >= 0) {
274 throw new Exception(msg.format(tag.name));
275 } else {
276 throw new Exception(msg);
280 void saveTagId (Tag tag) {
281 if (tag.id.length) {
282 import std.conv : to;
283 meta.ids ~= BookMetadata.Anc(tag.id.to!dstring, lay.nextWordIndex);
287 void putImage (Tag tag) {
288 if (tag is null || tag.href.length < 2 || tag.href[0] != '#') return;
289 string iid = tag.href[1..$];
290 //conwriteln("searching for image with href '", iid, "' (", book.images.length, ")");
291 foreach (immutable idx, ref BookText.Image img; book.images) {
292 if (iid == img.id) {
293 //conwriteln("image '", img.id, "' found");
294 lay.putObject(new BookImage(book, cast(uint)idx));
295 return;
300 void putParaContentInternal (Tag ct, int boldc=0, int italicc=0, int underc=0) {
301 if (ct is null) return;
302 auto c = lay.fontStyle.color;
303 scope(exit) lay.fontStyle.color = c;
304 saveTagId(ct);
305 switch (ct.name) {
306 case "strong": ++boldc; lay.fontStyle.bold = true; break;
307 case "emphasis": ++italicc; lay.fontStyle.italic = true; break;
308 case "image": putImage(ct); return;
309 case "style": return;
310 case "a":
311 if (ct.href.length) {
312 import std.conv : to;
313 //conwriteln("href found: '", ct.href, "' (", lay.nextWordIndex, ")");
314 meta.hrefs[lay.nextWordIndex] = BookMetadata.Anc(ct.href.to!dstring, lay.nextWordIndex);
315 ++underc;
316 lay.fontStyle.href = true;
317 lay.fontStyle.underline = true;
318 lay.fontStyle.color = colorTextHref.asUint;
320 break;
321 case "sub": break; // some idiotic files has this
322 case "sup": break; // some idiotic files has this
323 case "": lay.put(ct.text); return;
324 default: badTag(ct);
326 fixFont(lay);
327 foreach (Tag tag; ct.children) putParaContentInternal(tag, boldc, italicc, underc);
328 switch (ct.name) {
329 case "strong": if (--boldc == 0) lay.fontStyle.bold = false; break;
330 case "emphasis": if (--italicc == 0) lay.fontStyle.italic = false; break;
331 case "a": if (--underc == 0) lay.fontStyle.underline = false; lay.fontStyle.href = false; break;
332 default:
334 fixFont(lay);
337 bool onlyImagePara (Tag ct) {
338 if (ct is null) return false;
339 int count;
340 foreach (Tag tag; ct.children) {
341 if (tag.name.length == 0) {
342 // text
343 if (tag.text.xstrip.length != 0) return false;
344 continue;
346 if (count != 0 || tag.name != "image") return false;
347 ++count;
349 return (count == 1);
352 void putTagContents (Tag ct, int boldc=0, int italicc=0, int underc=0) {
353 if (ct is null) return;
354 saveTagId(ct);
355 if (onlyImagePara(ct)) {
356 lay.pushStyles();
357 scope(exit) lay.popStyles;
358 lay.lineStyle.setCenter;
359 foreach (Tag tag; ct.children) putParaContentInternal(tag, boldc, italicc, underc);
360 } else {
361 foreach (Tag tag; ct.children) putParaContentInternal(tag, boldc, italicc, underc);
363 lay.endPara();
366 void putParas (Tag ct) {
367 saveTagId(ct);
368 foreach (Tag tag; ct.children) {
369 if (tag.name.length == 0) continue;
370 if (tag.name == "p") putTagContents(tag);
371 else if (tag.name == "empty-line") lay.endLine();
372 else if (tag.name == "text-author") {}
373 else if (tag.name == "strong") putTagContents(tag, 1);
374 else badTag(tag);
378 void putAuthor (Tag ct) {
379 saveTagId(ct);
380 foreach (Tag tag; ct.children) {
381 if (tag.name.length == 0) continue;
382 if (tag.name == "text-author") {
383 putTagContents(tag);
384 lay.endPara();
389 void putCite (Tag ct) {
390 lay.pushStyles();
391 scope(exit) lay.popStyles;
392 setCiteStyle(lay);
393 putParas(ct);
394 putAuthor(ct);
397 void putEpigraph (Tag ct) {
398 lay.pushStyles();
399 scope(exit) lay.popStyles;
400 setEpigraphStyle(lay);
401 putParas(ct);
402 putAuthor(ct);
405 void putStanza (Tag ct) {
406 saveTagId(ct);
407 foreach (Tag tag; ct.children) {
408 if (tag.name.length == 0) continue;
409 if (tag.name == "text-author") continue;
410 if (tag.name == "title") badTag(tag, "titles in stanzas are not supported yet");
411 if (tag.name == "subtitle") badTag(tag, "subtitles in stanzas are not supported yet");
412 if (tag.name == "epigraph") badTag(tag, "epigraphs in poems are not supported yet");
413 if (tag.name == "date") continue;
414 if (tag.name == "v") { putTagContents(tag); continue; }
415 badTag(tag);
419 void putPoem (Tag ct) {
420 saveTagId(ct);
421 lay.pushStyles();
422 scope(exit) lay.popStyles;
423 setPoemStyle(lay);
424 // put epigraph (not yet)
425 // put title and subtitle
426 foreach (Tag tag; ct.children) {
427 if (tag.name == "title") {
428 lay.pushStyles();
429 scope(exit) lay.popStyles;
430 putParas(tag);
431 lay.endPara(); // space
432 } else if (tag.name == "subtitle") {
433 lay.pushStyles();
434 scope(exit) lay.popStyles;
435 putParas(tag);
436 //lay.endPara(); // space
439 lay.endPara;
440 foreach (Tag tag; ct.children) {
441 if (tag.name.length == 0) continue;
442 if (tag.name == "text-author") continue;
443 if (tag.name == "title") continue;
444 if (tag.name == "subtitle") continue;
445 if (tag.name == "epigraph") badTag(tag, "epigraphs in poems are not supported yet");
446 if (tag.name == "date") continue;
447 if (tag.name == "stanza") { putStanza(tag); lay.put(LayText.EndParaCh); continue; }
448 badTag(tag);
450 putAuthor(ct);
453 void putSection (Tag sc) {
454 bool sectionRegistered = false;
456 void registerSection (Tag tag) {
457 import std.conv : to;
458 if (sectionRegistered) return;
459 sectionRegistered = true;
460 string text = tag.textContent.xstrip;
461 //lay.sections ~= lay.curWordIndex;
462 string name;
463 while (text.length) {
464 char ch = text.ptr[0];
465 text = text[1..$];
466 if (ch <= ' ' || ch == 127) {
467 if (name.length == 0) continue;
468 if (ch != '\n') ch = ' ';
469 if (ch == '\n') {
470 if (name[$-1] > ' ') name ~= "\n...";
471 text = text.xstrip;
472 } else {
473 if (name[$-1] > ' ') name ~= ' ';
475 } else {
476 name ~= ch;
479 name = xstrip(name);
480 if (name.length == 0) name = "* * *";
481 meta.sections ~= BookMetadata.Anc(name.to!dstring, lay.nextWordIndex);
484 saveTagId(sc);
485 foreach (Tag tag; sc.children) {
486 if (tag.name.length == 0) continue;
487 if (tag.name == "title") {
488 lay.pushStyles();
489 scope(exit) lay.popStyles;
490 setTitleStyle(lay);
491 registerSection(tag);
492 putParas(tag);
493 } else if (tag.name == "subtitle") {
494 lay.pushStyles();
495 scope(exit) lay.popStyles;
496 setSubtitleStyle(lay);
497 registerSection(tag);
498 putParas(tag);
499 } else if (tag.name == "epigraph") {
500 lay.pushStyles();
501 scope(exit) lay.popStyles;
502 setEpigraphStyle(lay);
503 putEpigraph(tag);
504 } else if (tag.name == "section") {
505 lay.pushStyles();
506 scope(exit) lay.popStyles;
507 setNormalStyle(lay);
508 putSection(tag);
509 } else if (tag.name == "p") {
510 putTagContents(tag);
511 } else if (tag.name == "image") {
512 lay.pushStyles();
513 scope(exit) lay.popStyles;
514 lay.lineStyle.leftpad = 0;
515 lay.lineStyle.rightpad = 0;
516 lay.lineStyle.paraIndent = 0;
517 lay.lineStyle.setCenter;
518 putImage(tag);
519 lay.endPara();
520 } else if (tag.name == "empty-line") {
521 lay.endPara();
522 } else if (tag.name == "cite") {
523 putCite(tag);
524 } else if (tag.name == "table") {
525 lay.pushStyles();
526 scope(exit) lay.popStyles;
527 lay.fontStyle.fontsize += 8;
528 lay.lineStyle.setCenter;
529 lay.put("TABLE SKIPPED");
530 lay.endPara();
531 } else if (tag.name == "poem") {
532 putPoem(tag);
533 } else if (tag.name == "image") {
534 } else if (tag.name == "style") {
535 } else {
536 badTag(tag);
539 lay.endPara;
542 foreach (Tag tag; book.content.children) {
543 if (tag.name == "title") {
544 lay.pushStyles();
545 scope(exit) lay.popStyles;
546 setTitleStyle(lay);
547 lay.endPara();
548 putParas(tag);
549 lay.endPara();
550 } else if (tag.name == "subtitle") {
551 lay.pushStyles();
552 scope(exit) lay.popStyles;
553 setTitleStyle(lay);
554 putParas(tag);
555 lay.endPara();
556 } else if (tag.name == "epigraph") {
557 putEpigraph(tag);
558 } else if (tag.name == "section") {
559 lay.pushStyles();
560 scope(exit) lay.popStyles;
561 setNormalStyle(lay);
562 putSection(tag);
563 } else if (tag.name == "image") {
564 putImage(tag);
568 lay.finalize();
570 return meta;
574 // ////////////////////////////////////////////////////////////////////////// //
575 private __gshared LayFontStash laf; // layouter font stash
578 // ////////////////////////////////////////////////////////////////////////// //
579 private void loadFmtFonts () {
580 laf = new LayFontStash();
582 laf.addFont("text", textFontName);
583 laf.addFont("texti", textiFontName);
584 laf.addFont("textb", textbFontName);
585 laf.addFont("textz", textzFontName);
587 laf.addFont("mono", monoFontName);
588 laf.addFont("monoi", monoiFontName);
589 laf.addFont("monob", monobFontName);
590 laf.addFont("monoz", monozFontName);
594 // ////////////////////////////////////////////////////////////////////////// //
595 // messages
596 struct ReformatWork {
597 shared(BookText) booktext;
598 string bookFileName;
599 int w, h;
602 struct ReformatWorkComplete {
603 int w, h;
604 shared(BookText) booktext;
605 shared(LayText) laytext;
606 shared(BookMetadata) meta;
609 struct QuitWork {
613 // ////////////////////////////////////////////////////////////////////////// //
614 void reformatThreadFn (Tid ownerTid) {
615 bool doQuit = false;
616 loadFmtFonts();
617 BookText book;
618 string newFileName;
619 int newW = -1, newH = -1;
620 while (!doQuit) {
621 book = null;
622 newFileName = null;
623 newW = newH = -1;
624 receive(
625 (ReformatWork w) {
626 //{ conwriteln("reformat request received..."); }
627 book = cast(BookText)w.booktext;
628 newFileName = w.bookFileName;
629 newW = w.w;
630 newH = w.h;
631 if (newW < 1) newW = 1;
632 if (newH < 1) newH = 1;
634 (QuitWork w) {
635 doQuit = true;
638 if (!doQuit && newW > 0 && newH > 0) {
639 try {
640 if (book is null) {
641 //conwriteln("loading new book: '", newFileName, "'");
642 book = loadBook(newFileName);
645 int maxWidth = newW-4-2-BND_SCROLLBAR_WIDTH-2;
646 if (maxWidth < 64) maxWidth = 64;
648 // layout text
649 //conwriteln("layouting...");
650 auto stt = MonoTime.currTime;
651 auto lay = new LayText(laf, maxWidth);
652 lay.fontStyle.color = colorText.asUint;
654 auto meta = book.formatBook(lay);
656 auto ett = MonoTime.currTime-stt;
657 conwriteln("layouted in ", ett.total!"msecs", " milliseconds");
658 auto res = ReformatWorkComplete(newW, newH, cast(shared)book, cast(shared)lay, cast(shared)meta);
659 send(ownerTid, res);
660 } catch (Throwable e) {
661 // here, we are dead and fucked (the exact order doesn't matter)
662 import core.stdc.stdlib : abort;
663 import core.stdc.stdio : fprintf, stderr;
664 import core.memory : GC;
665 import core.thread : thread_suspendAll;
666 GC.disable(); // yeah
667 thread_suspendAll(); // stop right here, you criminal scum!
668 auto s = e.toString();
669 fprintf(stderr, "\n=== FATAL ===\n%.*s\n", cast(uint)s.length, s.ptr);
670 abort(); // die, you bitch!
674 send(ownerTid, QuitWork());