text relayouting now works
[xreader.git] / xreader.d
blob065b74137822c482c84de78a539fa397bef4f35e
1 /* Written by Ketmar // Invisible Vector <ketmar@ketmar.no-ip.org>f
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 xreader;
19 import core.time;
21 import std.concurrency;
23 import arsd.simpledisplay;
24 import arsd.color;
25 import arsd.png;
26 import arsd.jpeg;
28 import iv.nanovg;
29 import iv.nanovg.oui.blendish;
30 import iv.nanovg.perf;
32 import iv.strex;
34 import iv.vfs;
35 import iv.vfs.io;
37 import xmodel;
38 import xiniz;
40 import booktext;
42 import xreadercfg;
43 import xreaderui;
44 import xreaderifs;
45 import xreaderfmt;
46 import xlayouter;
48 import eworld;
49 import ewbillboard;
51 //version = debug_draw;
54 // ////////////////////////////////////////////////////////////////////////// //
55 void run (string bookFileName) {
56 int formatWorks = -1;
57 NVGContext vg = null;
58 PerfGraph fps;
59 bool fpsVisible = false;
60 BookText booktext;
61 string newBookFileName;
63 if (GWidth < 64) GWidth = 64;
64 if (GHeight < 64) GHeight = 64;
66 uint[] posstack;
68 bool doQuit = false;
70 booktext = loadBook(bookFileName);
72 //setOpenGLContextVersion(3, 2); // up to GLSL 150
73 setOpenGLContextVersion(2, 0); // it's enough
74 //openGLContextCompatible = false;
76 auto sdwindow = new SimpleWindow(GWidth, GHeight, booktext.title~" -- "~booktext.authorFirst~" "~booktext.authorLast, OpenGlOptions.yes, Resizablity.allowResizing);
77 sdwindow.hideCursor(); // we will do our own
79 auto stt = MonoTime.currTime;
80 auto prevt = MonoTime.currTime;
81 auto curt = prevt;
82 float dt = 0, secs = 0;
83 LayText laytext;
84 int textHeight = GHeight-8;
85 bool doSaveCheck = false;
86 MonoTime nextSaveTime;
88 MonoTime nextIfTime = MonoTime.currTime;
90 BookInfo[] recentFiles;
91 BookMetadata bookmeta;
93 int toMove = 0; // for smooth scroller
94 int topY = 0;
95 int arrowDir = 0;
97 int newYLine = -1; // index
98 float newYAlpha;
99 bool newYFade = false;
100 MonoTime nextFadeTime;
102 int curImg = -1;
103 int mouseX = -666, mouseY = -666;
104 bool mouseHidden = false;
105 auto lastMMove = MonoTime.currTime;
107 bool needRedrawFlag = true;
109 bool firstFormat = true;
111 bool inGalaxyMap = false;
112 PopupMenu currPopup;
113 void delegate (int item) onPopupSelect;
114 int shipModelIndex = 0;
115 bool popupNoShipKill = false;
117 void refresh () { needRedrawFlag = true; }
118 void refreshed () { needRedrawFlag = false; }
120 bool needRedraw () {
121 return (needRedrawFlag || (currPopup !is null && currPopup.needRedraw));
124 @property bool inMenu () { return (currPopup !is null); }
125 void closeMenu () { if (currPopup !is null) currPopup.destroy; currPopup = null; onPopupSelect = null; }
127 auto childTid = spawn(&reformatThreadFn, thisTid);
128 childTid.setMaxMailboxSize(128, OnCrowding.block);
129 thisTid.setMaxMailboxSize(128, OnCrowding.block);
131 void setShip (int idx) {
132 if (eliteShipFiles.length) {
133 import core.memory : GC;
134 if (idx >= eliteShipFiles.length) idx = cast(int)eliteShipFiles.length-1;
135 if (idx < 0) idx = 0;
136 if (shipModelIndex == idx && shipModel !is null) return;
137 // remove old ship
138 shipModelIndex = idx;
139 if (shipModel !is null) {
140 shipModel.glUnload();
141 shipModel.freeData();
142 shipModel.destroy;
143 shipModel = null;
145 GC.collect();
146 // load new ship
147 try {
148 shipModel = new EliteModel(eliteShipFiles[shipModelIndex]);
149 shipModel.glUpload();
150 shipModel.freeImages();
151 } catch (Exception e) {}
152 //shipModel = eliteShips[shipModelIndex];
153 GC.collect();
157 void ensureShipModel () {
158 if (eliteShipFiles.length && shipModel is null) {
159 import std.random : uniform;
160 setShip(uniform!"[)"(0, eliteShipFiles.length));
164 void freeShipModel () {
165 if (!showShip && !inMenu && shipModel !is null) {
166 import core.memory : GC;
167 shipModel.glUnload();
168 shipModel.freeData();
169 shipModel.destroy;
170 shipModel = null;
171 GC.collect();
175 void doSaveState (bool forced=false) {
176 if (!forced) {
177 if (formatWorks != 0) return;
178 if (!doSaveCheck) return;
179 auto ct = MonoTime.currTime;
180 if (ct < nextSaveTime) return;
181 } else {
182 if (laytext is null || laytext.lineCount == 0 || formatWorks != 0) return;
184 try {
185 auto fo = VFile(stateFileName, "w");
186 if (laytext !is null && laytext.lineCount) {
187 auto lnum = laytext.findLineWithY(topY);
188 if (lnum >= 0) fo.writeln("wordindex=", laytext.line(lnum).wstart);
190 } catch (Exception) {}
191 doSaveCheck = false;
194 void stateChanged () {
195 if (!doSaveCheck) {
196 doSaveCheck = true;
197 nextSaveTime = MonoTime.currTime+10.seconds;
201 void hardScrollBy (int delta) {
202 if (delta == 0 || laytext is null || laytext.lineCount == 0) return;
203 int oldY = topY;
204 topY += delta;
205 if (topY >= laytext.textHeight-textHeight) topY = cast(int)laytext.textHeight-textHeight;
206 if (topY < 0) topY = 0;
207 if (topY != oldY) {
208 stateChanged();
209 refresh();
213 void scrollBy (int delta) {
214 if (delta == 0 || laytext is null || laytext.lineCount == 0) return;
215 toMove += delta;
216 newYFade = true;
217 newYAlpha = 1;
218 if (delta < 0) {
219 // scrolling up, mark top line
220 newYLine = laytext.findLineWithY(topY);
221 } else {
222 // scrolling down, mark bottom line
223 newYLine = laytext.findLineWithY(topY+textHeight-2);
225 version(none) {
226 import std.stdio;
227 writeln("scrollBy: delta=", delta, "; newYLine=", newYLine, "; topLine=", laytext.findLineWithY(topY));
229 if (newYLine < 0) newYFade = false;
232 void goHome () {
233 if (laytext is null) return;
234 if (topY != 0) {
235 topY = 0;
236 stateChanged();
237 refresh();
241 void goTo (uint widx) {
242 if (laytext is null) return;
243 auto lidx = laytext.findLineWithWord(widx);
244 if (lidx != -1) {
245 assert(lidx < laytext.lineCount);
246 toMove = 0;
247 if (topY != laytext.line(lidx).y) {
248 topY = laytext.line(lidx).y;
249 stateChanged();
250 refresh();
252 version(none) {
253 import std.stdio;
254 writeln("goto: widx=", widx, "; lidx=", lidx, "; fwn=", laytext.line(lidx).wstart, "; topY=", topY);
255 auto lnum = laytext.findLineWithY(topY);
256 writeln(" newlnum=", lnum, "; lidx.y=", laytext.line(lidx).y, "; lnum.y=", laytext.line(lnum).y);
261 void loadState () {
262 try {
263 int widx = -1;
264 xiniParse(VFile(stateFileName),
265 "wordindex", &widx,
267 if (widx >= 0) goTo(widx);
268 } catch (Exception) {}
271 void loadAndFormat (string filename) {
272 assert(formatWorks <= 0);
273 booktext = null;
274 laytext = null;
275 newYLine = -1;
276 //formatWorks = -1; //FIXME
277 firstFormat = true;
278 newYFade = false;
279 toMove = 0;
280 recentFiles = null;
281 arrowDir = 0;
282 //sdwindow.redrawOpenGlSceneNow();
283 //booktext = loadBook(newBookFileName);
284 //newBookFileName = null;
285 //reformat();
286 //if (formatWorks < 0) formatWorks = 1; else ++formatWorks;
287 formatWorks = 1;
288 //writeln("*** loading new book: '", filename, "'");
289 childTid.send(ReformatWork(null, filename, GWidth, GHeight));
290 refresh();
293 void reformat () {
294 if (formatWorks < 0) formatWorks = 1; else ++formatWorks;
295 childTid.send(ReformatWork(cast(shared)booktext, null, GWidth, GHeight));
296 refresh();
299 void formatComplete (ref ReformatWorkComplete w) {
300 scope(exit) { import core.memory : GC; GC.collect(); GC.minimize(); }
302 auto lt = cast(LayText)w.laytext;
303 scope(exit) if (lt) lt.freeMemory();
304 w.laytext = null;
306 BookMetadata meta = cast(BookMetadata)w.meta;
307 w.meta = null;
309 BookText bt = cast(BookText)w.booktext;
310 w.booktext = null;
311 if (bt !is booktext) {
312 booktext = bt;
313 bookmeta = meta;
314 firstFormat = true;
315 sdwindow.title = booktext.title~" -- "~booktext.authorFirst~" "~booktext.authorLast;
316 flushGui();
317 } else if (bookmeta is null) {
318 bookmeta = meta;
321 if (doQuit || formatWorks <= 0) return;
322 --formatWorks;
324 if (w.w != GWidth) {
325 if (formatWorks == 0) reformat();
326 return;
329 if (formatWorks != 0) return;
330 freeShipModel();
332 uint widx = 0;
333 if (!firstFormat && laytext !is null && laytext.lineCount) {
334 auto lidx = laytext.findLineWithY(topY);
335 if (lidx >= 0) widx = laytext.line(lidx).wstart;
337 if (laytext !is null) laytext.freeMemory();
338 laytext = lt;
339 lt = null;
340 if (firstFormat) {
341 loadState();
342 firstFormat = false;
343 doSaveCheck = false;
344 stateChanged();
345 } else {
346 goTo(widx);
348 refresh();
351 void pushPosition () {
352 if (laytext is null || laytext.lineCount == 0) return;
353 auto lidx = laytext.findLineWithY(topY);
354 if (lidx >= 0) posstack ~= laytext.line(lidx).wstart;
357 void popPosition () {
358 if (posstack.length == 0) return;
359 auto widx = posstack[$-1];
360 posstack.length -= 1;
361 posstack.assumeSafeAppend;
362 goTo(widx);
365 void gotoSection (int sn) {
366 if (laytext is null || laytext.lineCount == 0 || bookmeta is null) return;
367 if (sn < 0 || sn >= bookmeta.sections.length) return;
368 auto lidx = laytext.findLineWithWord(bookmeta.sections[sn].wordidx);
369 if (lidx >= 0) {
370 auto newY = laytext.line(lidx).y;
371 if (newY != topY) {
372 topY = newY;
373 stateChanged();
374 refresh();
379 sdwindow.closeQuery = delegate () { doQuit = true; };
381 void closeWindow () {
382 doSaveState(true); // forced state save
383 if (!sdwindow.closed && vg !is null) {
384 if (curImg >= 0) { vg.deleteImage(curImg); curImg = -1; }
385 freeShipModel();
386 vg.deleteGL2();
387 vg = null;
388 sdwindow.close();
392 sdwindow.visibleForTheFirstTime = delegate () {
393 sdwindow.setAsCurrentOpenGlContext(); // make this window active
394 sdwindow.vsync = false;
395 //sdwindow.useGLFinish = false;
396 //glbindLoadFunctions();
398 try {
399 uint flags = NVG_DEBUG;
400 if (flagNanoAA) flags |= NVG_ANTIALIAS;
401 if (flagNanoSS) flags |= NVG_STENCIL_STROKES;
402 vg = createGL2NVG(flags);
403 if (vg is null) {
404 import std.stdio;
405 writeln("Could not init nanovg.");
406 assert(0);
407 //sdwindow.close();
409 loadFonts(vg);
410 curImg = createCursorImage(vg);
411 fps = new PerfGraph("Frame Time", PerfGraph.Style.FPS, "ui");
412 } catch (Exception e) {
413 import std.stdio : stderr;
414 stderr.writeln("ERROR: ", e.msg);
415 doQuit = true;
416 return;
419 reformat();
421 refresh();
422 sdwindow.redrawOpenGlScene();
423 refresh();
426 void relayout (bool forced=false) {
427 if (laytext !is null) {
428 uint widx;
429 auto lidx = laytext.findLineWithY(topY);
430 if (lidx >= 0) widx = laytext.line(lidx).wstart;
431 int maxWidth = GWidth-4-2-BND_SCROLLBAR_WIDTH-2;
432 if (maxWidth < 64) maxWidth = 64;
434 import core.time;
435 auto stt = MonoTime.currTime;
436 laytext.relayout(maxWidth, forced);
437 writeln("relayouted in ", (MonoTime.currTime-stt).total!"msecs", " milliseconds; lines:", laytext.lineCount, "; words:", laytext.nextWordIndex);
439 goTo(widx);
440 refresh();
444 sdwindow.windowResized = delegate (int w, int h) {
445 //writeln("w=", w, "; h=", h);
446 if (w < 64) w = 64;
447 if (h < 64) h = 64;
448 glViewport(0, 0, w, h);
449 GWidth = w;
450 GHeight = h;
451 textHeight = GHeight-8;
452 //reformat();
453 relayout();
456 void drawShipName () {
457 if (shipModel is null || shipModel.name.length == 0) return;
458 vg.fontFaceId(uiFont);
459 vg.textAlign(NVGAlign.Left|NVGAlign.Baseline);
460 vg.fontSize(fsizeUI);
461 auto w = vg.bndLabelWidth(-1, shipModel.name)+8;
462 float h = BND_WIDGET_HEIGHT+8;
463 float mx = (GWidth-w)/2.0;
464 float my = (GHeight-h)-8;
465 vg.bndMenuBackground(mx, my, w, h, BND_CORNER_NONE);
466 vg.bndMenuItem(mx+4, my+4, w-8, BND_WIDGET_HEIGHT, BND_DEFAULT, -1, shipModel.name);
467 if (shipModel.dispName && shipModel.dispName != shipModel.name) {
468 my -= BND_WIDGET_HEIGHT+16;
469 w = vg.bndLabelWidth(-1, shipModel.dispName)+8;
470 mx = (GWidth-w)/2.0;
471 vg.bndMenuBackground(mx, my, w, h, BND_CORNER_NONE);
472 vg.bndMenuItem(mx+4, my+4, w-8, BND_WIDGET_HEIGHT, BND_DEFAULT, -1, shipModel.dispName);
476 void createSectionMenu () {
477 closeMenu();
478 writeln("lc=", laytext.lineCount, "; bm: ", (bookmeta !is null));
479 if (laytext is null || laytext.lineCount == 0 || bookmeta is null) { freeShipModel(); return; }
480 currPopup = new PopupMenu(vg, "Sections"d, () {
481 dstring[] items;
482 foreach (const ref sc; bookmeta.sections) items ~= sc.name;
483 return items;
485 writeln(currPopup.items.length);
486 // find current section
487 currPopup.curItemIdx = 0;
488 auto lidx = laytext.findLineWithY(topY);
489 if (lidx >= 0 && bookmeta.sections.length > 0) {
490 foreach (immutable sidx, const ref sc; bookmeta.sections) {
491 auto sline = laytext.findLineWithWord(sc.wordidx);
492 if (sline >= 0 && lidx >= sline) currPopup.curItemIdx = cast(int)sidx;
495 onPopupSelect = (int item) { gotoSection(item); };
498 void createQuitMenu (bool wantYes) {
499 closeMenu();
500 currPopup = new PopupMenu(vg, "Quit?"d, () {
501 return ["Yes"d, "No"d];
503 currPopup.curItemIdx = (wantYes ? 0 : 1);
504 onPopupSelect = (int item) { if (item == 0) doQuit = true; };
507 void createRecentMenu () {
508 closeMenu();
509 if (recentFiles.length == 0) recentFiles = loadDetailedHistory();
510 if (recentFiles.length == 0) { freeShipModel(); return; }
511 currPopup = new PopupMenu(vg, "Recent files"d, () {
512 import std.conv : to;
513 dstring[] res;
514 foreach (const ref BookInfo bi; recentFiles) {
515 string s = bi.title;
516 if (bi.seqname.length) {
517 s ~= " (";
518 if (bi.seqnum) { s ~= to!string(bi.seqnum); s ~= ": "; }
519 //writeln(bi.seqname);
520 s ~= bi.seqname;
521 s ~= ")";
523 if (bi.author.length) { s ~= " -- "; s ~= bi.author; }
524 res ~= s.to!dstring;
526 return res;
528 currPopup.curItemIdx = cast(int)recentFiles.length-1;
529 onPopupSelect = (int item) {
530 newBookFileName = recentFiles[item].diskfile;
531 popupNoShipKill = true;
535 bool menuKey (KeyEvent event) {
536 if (formatWorks != 0) return false;
537 if (!inMenu) return false;
538 if (inGalaxyMap) return false;
539 if (!event.pressed) return false;
540 auto res = currPopup.onKey(event);
541 if (res == PopupMenu.Close) {
542 closeMenu();
543 freeShipModel();
544 refresh();
545 } else if (res >= 0) {
546 if (onPopupSelect !is null) onPopupSelect(res);
547 closeMenu();
548 if (popupNoShipKill) popupNoShipKill = false; else freeShipModel();
549 refresh();
551 return true;
554 bool menuMouse (MouseEvent event) {
555 if (formatWorks != 0) return false;
556 if (!inMenu) return false;
557 if (inGalaxyMap) return false;
558 auto res = currPopup.onMouse(event);
559 if (res == PopupMenu.Close) {
560 closeMenu();
561 freeShipModel();
562 refresh();
563 } else if (res >= 0) {
564 if (onPopupSelect !is null) onPopupSelect(res);
565 closeMenu();
566 if (popupNoShipKill) popupNoShipKill = false; else freeShipModel();
567 refresh();
569 return true;
572 bool readerKey (KeyEvent event) {
573 if (formatWorks != 0) return false;
574 if (!event.pressed) {
575 switch (event.key) {
576 case Key.Up: arrowDir = 0; return true;
577 case Key.Down: arrowDir = 0; return true;
578 default:
580 return false;
582 switch (event.key) {
583 case Key.Space:
584 if (event.modifierState&ModifierState.shift) {
585 //goto case Key.PageUp;
586 hardScrollBy(toMove); toMove = 0;
587 scrollBy(-textHeight/3*2);
588 } else {
589 //goto case Key.PageDown;
590 hardScrollBy(toMove); toMove = 0;
591 scrollBy(textHeight/3*2);
593 break;
594 case Key.Backspace:
595 popPosition();
596 break;
597 case Key.PageUp:
598 hardScrollBy(toMove); toMove = 0;
599 hardScrollBy(-(textHeight > 32 ? textHeight-32 : textHeight));
600 break;
601 case Key.PageDown:
602 hardScrollBy(toMove); toMove = 0;
603 hardScrollBy(textHeight > 32 ? textHeight-32 : textHeight);
604 break;
605 case Key.Up:
606 //scrollBy(-8);
607 arrowDir = -1;
608 break;
609 case Key.Down:
610 //scrollBy(8);
611 arrowDir = 1;
612 break;
613 case Key.H:
614 goHome();
615 break;
616 default:
618 return true;
621 bool controlKey (KeyEvent event) {
622 if (!event.pressed) return false;
623 switch (event.key) {
624 case Key.Escape:
625 if (inGalaxyMap) { inGalaxyMap = false; refresh(); return true; }
626 if (inMenu) { closeMenu(); freeShipModel(); refresh(); return true; }
627 if (showShip) { showShip = false; freeShipModel(); refresh(); return true; }
628 ensureShipModel();
629 createQuitMenu(true);
630 refresh();
631 return true;
632 case Key.P: if (event.modifierState == ModifierState.ctrl) { fpsVisible = !fpsVisible; refresh(); return true; } break;
633 case Key.I: if (event.modifierState == ModifierState.ctrl) { interAllowed = !interAllowed; refresh(); return true; } break;
634 case Key.N: if (event.modifierState == ModifierState.ctrl) { sbLeft = !sbLeft; refresh(); return true; } break;
635 case Key.C: if (event.modifierState == ModifierState.ctrl) { if (addIf()) refresh(); return true; } break;
636 case Key.E:
637 if (event.modifierState == ModifierState.ctrl && eliteShipFiles.length > 0) {
638 if (!inMenu) {
639 showShip = !showShip;
640 if (showShip) ensureShipModel(); else freeShipModel();
641 refresh();
643 return true;
645 break;
646 case Key.Q: if (event.modifierState == ModifierState.ctrl) { doQuit = true; return true; } break;
647 case Key.B: if (formatWorks == 0 && !inMenu && !inGalaxyMap && event.modifierState == ModifierState.ctrl) { pushPosition(); return true; } break;
648 case Key.S:
649 if (formatWorks == 0 && !showShip && !inMenu && !inGalaxyMap) {
650 ensureShipModel();
651 createSectionMenu();
652 refresh();
654 break;
655 case Key.L:
656 if (formatWorks == 0 && event.modifierState == ModifierState.alt) {
657 ensureShipModel();
658 createRecentMenu();
659 refresh();
661 break;
662 case Key.M:
663 if (!inMenu && !showShip) {
664 inGalaxyMap = !inGalaxyMap;
665 refresh();
667 break;
668 case Key.R:
669 if (formatWorks == 0 && event.modifierState == ModifierState.ctrl) relayout(true);
670 break;
671 case Key.Home: if (showShip) { setShip(0); return true; } break;
672 case Key.End: if (showShip) { setShip(cast(int)eliteShipFiles.length); return true; } break;
673 case Key.Up: case Key.Left: if (showShip) { setShip(shipModelIndex-1); return true; } break;
674 case Key.Down: case Key.Right: if (showShip) { setShip(shipModelIndex+1); return true; } break;
675 default:
677 return showShip;
680 sdwindow.redrawOpenGlScene = delegate () {
681 if (doQuit) return;
682 // timers
683 prevt = curt;
684 curt = MonoTime.currTime;
685 secs = cast(double)((curt-stt).total!"msecs")/1000.0;
686 dt = cast(double)((curt-prevt).total!"msecs")/1000.0;
688 //glClearColor(0, 0, 0, 0);
689 //glClearColor(0.18, 0.18, 0.18, 0);
690 glClearColor(colorBack.r, colorBack.g, colorBack.b, 0);
691 glClear(glNVGClearFlags|EliteModel.glClearFlags);
693 refreshed();
694 needRedrawFlag = (fps !is null && fpsVisible);
695 if (fps !is null) fps.update(dt);
696 if (vg is null) return;
698 vg.beginFrame(GWidth, GHeight, 1);
699 drawIfs(vg);
700 // draw scrollbar
702 float curHeight = (laytext !is null ? topY : 0);
703 float th = (laytext !is null ? laytext.textHeight-textHeight : 0);
704 if (th <= 0) { curHeight = 0; th = 1; }
705 float sz = cast(float)(GHeight-4)/th;
706 if (sz > 1) sz = 1; else if (sz < 0.05) sz = 0.05;
707 int sx = (sbLeft ? 2 : GWidth-BND_SCROLLBAR_WIDTH-2);
708 vg.bndScrollBar(sx, 2, BND_SCROLLBAR_WIDTH, GHeight-4, BND_DEFAULT, curHeight/th, sz);
710 if (laytext is null) {
711 if (shipModel is null) {
712 vg.beginPath();
713 vg.fillColor(colorText);
714 int drawY = (GHeight-textHeight)/2;
715 vg.intersectScissor((sbLeft ? 2+BND_SCROLLBAR_WIDTH+2 : 4), drawY, GWidth-4-2-BND_SCROLLBAR_WIDTH-2, textHeight);
716 vg.fontFaceId(textFont);
717 vg.fontSize(fsizeText);
718 vg.textAlign(NVGAlign.Center|NVGAlign.Middle);
719 vg.text(GWidth/2, GHeight/2, "REFORMATTING");
720 vg.fill();
723 // draw text page
724 if (laytext !is null && laytext.lineCount) {
725 vg.beginPath();
726 vg.fillColor(colorText);
727 int drawY = (GHeight-textHeight)/2;
728 vg.intersectScissor((sbLeft ? 2+BND_SCROLLBAR_WIDTH+2 : 4), drawY, GWidth-4-2-BND_SCROLLBAR_WIDTH-2, textHeight);
729 //FIXME: not GHeight!
730 int lidx = laytext.findLineWithY(topY);
731 if (lidx >= 0 && lidx < laytext.lineCount) {
732 drawY -= topY-laytext.line(lidx).y;
733 vg.textAlign(NVGAlign.Left|NVGAlign.Baseline);
734 LayFontStyle lastStyle;
735 int startx = (sbLeft ? 2+BND_SCROLLBAR_WIDTH+2 : 4);
736 while (lidx < laytext.lineCount && drawY < GHeight) {
737 auto ln = laytext.line(lidx);
738 foreach (ref LayWord w; laytext.lineWords(lidx)) {
739 if (lastStyle != w.style) {
740 if (w.style.fontface != lastStyle.fontface) {
741 vg.fontFace(laytext.fontFace(w.style.fontface));
743 vg.fontSize(w.style.fontsize);
744 auto c = NVGColor(w.style.color);
745 vg.fillColor(c);
746 //vg.strokeColor(c);
747 lastStyle = w.style;
749 // line highlighting
750 if (newYFade && newYLine == lidx) vg.fillColor(nvgLerpRGBA(colorText, colorTextHi, newYAlpha));
751 vg.text(startx+w.x, drawY+ln.h+ln.desc, laytext.wordText(w));
752 //TODO: draw lines over whitespace
753 if (lastStyle.underline) vg.rect(startx+w.x, drawY+ln.h+ln.desc+1, w.w, 1);
754 if (lastStyle.strike) vg.rect(startx+w.x, drawY+ln.h+ln.desc-w.asc/2, w.w, 1);
755 if (lastStyle.overline) vg.rect(startx+w.x, drawY+ln.h+ln.desc-w.asc-1, w.w, 1);
756 version(debug_draw) {
757 vg.fill();
758 vg.beginPath();
759 vg.strokeWidth(1);
760 vg.strokeColor(nvgRGB(0, 0, 255));
761 vg.rect(startx+w.x, drawY, w.w, w.h);
762 vg.stroke();
763 vg.beginPath();
765 if (newYFade && newYLine == lidx) vg.fillColor(NVGColor(lastStyle.color));
767 drawY += ln.h;
768 ++lidx;
771 vg.fill();
773 // dim text
774 if (!showShip) {
775 if (colorDim.a != 1) {
776 //vg.scissor(0, 0, GWidth, GHeight);
777 vg.resetScissor;
778 vg.beginPath();
779 vg.fillColor(colorDim);
780 vg.rect(0, 0, GWidth, GHeight);
781 vg.fill();
784 // dim more if menu is active
785 if (inMenu || showShip || formatWorks != 0) {
786 //vg.scissor(0, 0, GWidth, GHeight);
787 vg.resetScissor;
788 vg.beginPath();
789 //vg.globalAlpha(0.5);
790 vg.fillColor(nvgRGBA(0, 0, 0, (showShip || formatWorks != 0 ? 127 : 64)));
791 vg.rect(0, 0, GWidth, GHeight);
792 vg.fill();
794 vg.endFrame();
795 if (shipModel !is null) {
796 float zz = shipModel.bbox[1].z-shipModel.bbox[0].z;
797 zz += 10;
798 lightsClear();
800 lightAdd(
801 0, 60, 60,
802 1.0, 0.0, 0.0
805 lightAdd(
806 //0, 0, -60,
807 0, 0, -zz,
808 1.0, 1.0, 1.0
810 drawModel(shipAngle, shipModel);
811 vg.beginFrame(GWidth, GHeight, 1);
812 drawShipName();
813 vg.endFrame();
815 if (formatWorks == 0) {
816 if (inMenu) {
817 vg.beginFrame(GWidth, GHeight, 1);
818 //vg.scissor(0, 0, GWidth, GHeight);
819 vg.resetScissor;
820 currPopup.draw();
821 vg.endFrame();
824 if (fps !is null && fpsVisible) {
825 vg.beginFrame(GWidth, GHeight, 1);
826 //vg.scissor(0, 0, GWidth, GHeight);
827 vg.resetScissor;
828 fps.render(vg, GWidth-fps.width-4, GHeight-fps.height-4);
829 vg.endFrame();
831 if (inGalaxyMap) drawGalaxy(vg);
832 // mouse cursor
833 if (curImg >= 0 && !mouseHidden) {
834 int w, h;
835 vg.beginFrame(GWidth, GHeight, 1);
836 vg.beginPath();
837 //vg.scissor(0, 0, GWidth, GHeight);
838 vg.resetScissor;
839 vg.imageSize(curImg, &w, &h);
840 vg.fillPaint(vg.imagePattern(mouseX, mouseY, w, h, 0, curImg, 1));
841 vg.rect(mouseX, mouseY, w, h);
842 vg.fill();
843 vg.endFrame();
847 void processThreads () {
848 ReformatWorkComplete wd;
849 for (;;) {
850 bool workDone = false;
851 auto res = receiveTimeout(Duration.zero,
852 (QuitWork w) {
853 formatWorks = -1;
855 (ReformatWorkComplete w) {
856 wd = w;
857 workDone = true;
860 if (!res) { assert(!workDone); break; }
861 if (workDone) { workDone = false; formatComplete(wd); }
865 sdwindow.eventLoop(1000/35,
866 delegate () {
867 processThreads();
868 if (sdwindow.closed) return;
869 if (doQuit) { closeWindow(); return; }
870 auto ctt = MonoTime.currTime;
871 // smooth scrolling
872 if (formatWorks == 0) {
873 enum Delta = 92*2;
874 if (toMove < 0) {
875 int sc = -toMove;
876 if (sc > Delta) sc = Delta;
877 hardScrollBy(-sc);
878 toMove += sc;
879 nextFadeTime = ctt+500.msecs;
880 } else if (toMove > 0) {
881 int sc = toMove;
882 if (sc > Delta) sc = Delta;
883 hardScrollBy(sc);
884 toMove -= sc;
885 nextFadeTime = ctt+500.msecs;
886 } else if (arrowDir) {
887 hardScrollBy(arrowDir*6*2);
889 // highlight fading
890 if (newYFade) {
891 if (ctt >= nextFadeTime) {
892 if ((newYAlpha -= 0.1) <= 0) {
893 newYFade = false;
894 } else {
895 nextFadeTime = ctt+25.msecs;
897 refresh();
901 // interference processing
902 if (ctt >= nextIfTime) {
903 import std.random : uniform;
904 if (uniform!"[]"(0, 100) >= 50) { if (addIf()) refresh(); }
905 nextIfTime += (uniform!"[]"(50, 1500)).msecs;
907 if (processIfs()) refresh();
908 // ship rotation
909 if (shipModel !is null) {
910 shipAngle -= 1;
911 if (shipAngle < 359) shipAngle += 360;
912 refresh();
914 // mouse autohide
915 if (!mouseHidden) {
916 if ((ctt-lastMMove).total!"msecs" > 2500) {
917 mouseHidden = true;
918 refresh();
921 if (needRedraw) sdwindow.redrawOpenGlSceneNow();
922 doSaveState();
923 // load new book?
924 if (newBookFileName.length && formatWorks == 0) {
925 doSaveState(true); // forced state save
926 closeMenu();
927 ensureShipModel();
928 loadAndFormat(newBookFileName);
929 newBookFileName = null;
930 sdwindow.redrawOpenGlSceneNow();
931 //refresh();
934 delegate (KeyEvent event) {
935 if (sdwindow.closed) return;
936 if (event.key == Key.PadEnter) event.key = Key.Enter;
937 if ((event.modifierState&ModifierState.numLock) == 0) {
938 switch (event.key) {
939 case Key.Pad0: event.key = Key.Insert; break;
940 case Key.PadDot: event.key = Key.Delete; break;
941 case Key.Pad1: event.key = Key.End; break;
942 case Key.Pad2: event.key = Key.Down; break;
943 case Key.Pad3: event.key = Key.PageDown; break;
944 case Key.Pad4: event.key = Key.Left; break;
945 case Key.Pad6: event.key = Key.Right; break;
946 case Key.Pad7: event.key = Key.Home; break;
947 case Key.Pad8: event.key = Key.Up; break;
948 case Key.Pad9: event.key = Key.PageUp; break;
949 //case Key.PadEnter: event.key = Key.Enter; break;
950 default:
953 if (controlKey(event)) return;
954 if (menuKey(event)) return;
955 if (readerKey(event)) return;
957 delegate (MouseEvent event) {
958 lastMMove = MonoTime.currTime;
959 if (mouseHidden) {
960 mouseHidden = false;
961 refresh();
963 if (mouseX != event.x || mouseY != event.y) {
964 mouseX = event.x;
965 mouseY = event.y;
966 refresh();
968 menuMouse(event);
970 delegate (dchar ch) {
971 //if (ch == 'q') { doQuit = true; return; }
974 closeWindow();
976 childTid.send(QuitWork());
977 while (formatWorks >= 0) processThreads();
981 // ////////////////////////////////////////////////////////////////////////// //
982 void main (string[] args) {
983 import std.path;
984 RcDir = RcDir.expandTilde.absolutePath;
985 //writeln(RcDir);
987 universe = Galaxy(0);
989 if (args.length == 1) {
990 try {
991 string lnn;
992 foreach (string line; VFile(buildPath(RcDir, ".lastfile")).byLineCopy) {
993 if (!line.isComment) lnn = line;
995 if (lnn.length) args ~= lnn;
996 } catch (Exception) {}
998 if (args.length == 1) assert(0, "no filename");
1000 readConfig();
1002 run(args[1]);