write -> conwrite
[xreader.git] / xreader.d
blobc78dfa0a8148a0c876a499194f5c0796e2e7c520
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.image;
26 import iv.nanovg;
27 import iv.nanovg.oui.blendish;
28 import iv.nanovg.perf;
30 import iv.strex;
32 import iv.glcmdcon;
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 __gshared bool fpsVisible = false;
60 BookText booktext;
61 string newBookFileName;
63 if (GWidth < MinWinWidth) GWidth = MinWinWidth;
64 if (GHeight < MinWinHeight) GHeight = MinWinHeight;
66 uint[] posstack;
68 booktext = loadBook(bookFileName);
70 //setOpenGLContextVersion(3, 2); // up to GLSL 150
71 setOpenGLContextVersion(2, 0); // it's enough
72 //openGLContextCompatible = false;
74 auto sdwindow = new SimpleWindow(GWidth, GHeight, booktext.title~" \xe2\x80\x94 "~booktext.authorFirst~" "~booktext.authorLast, OpenGlOptions.yes, Resizablity.allowResizing);
75 sdwindow.hideCursor(); // we will do our own
76 sdwindow.setMinSize(MinWinWidth, MinWinHeight);
78 auto stt = MonoTime.currTime;
79 auto prevt = MonoTime.currTime;
80 auto curt = prevt;
81 LayText laytext;
82 int textHeight = GHeight-8;
83 bool doSaveCheck = false;
84 MonoTime nextSaveTime;
86 MonoTime nextIfTime = MonoTime.currTime;
88 BookInfo[] recentFiles;
89 BookMetadata bookmeta;
91 int toMove = 0; // for smooth scroller
92 int topY = 0;
93 int arrowDir = 0;
95 int newYLine = -1; // index
96 float newYAlpha;
97 bool newYFade = false;
98 MonoTime nextFadeTime;
100 int curImg = -1, curImgWhite = -1;
101 int mouseX = -666, mouseY = -666;
102 bool mouseHigh = false;
103 bool mouseHidden = false;
104 auto lastMMove = MonoTime.currTime;
105 float mouseAlpha = 1.0f;
106 int mouseFadingAway = false;
108 bool needRedrawFlag = true;
110 bool firstFormat = true;
112 __gshared bool inGalaxyMap = false;
113 PopupMenu currPopup;
114 void delegate (int item) onPopupSelect;
115 int shipModelIndex = 0;
116 bool popupNoShipKill = false;
118 void refresh () { needRedrawFlag = true; }
119 void refreshed () { needRedrawFlag = false; }
121 bool needRedraw () {
122 return (needRedrawFlag || (currPopup !is null && currPopup.needRedraw));
125 @property bool inMenu () { return (currPopup !is null); }
126 void closeMenu () { if (currPopup !is null) currPopup.destroy; currPopup = null; onPopupSelect = null; }
128 auto childTid = spawn(&reformatThreadFn, thisTid);
129 childTid.setMaxMailboxSize(128, OnCrowding.block);
130 thisTid.setMaxMailboxSize(128, OnCrowding.block);
132 void setShip (int idx) {
133 if (eliteShipFiles.length) {
134 import core.memory : GC;
135 if (idx >= eliteShipFiles.length) idx = cast(int)eliteShipFiles.length-1;
136 if (idx < 0) idx = 0;
137 if (shipModelIndex == idx && shipModel !is null) return;
138 // remove old ship
139 shipModelIndex = idx;
140 if (shipModel !is null) {
141 shipModel.glUnload();
142 shipModel.freeData();
143 shipModel.destroy;
144 shipModel = null;
146 GC.collect();
147 // load new ship
148 try {
149 shipModel = new EliteModel(eliteShipFiles[shipModelIndex]);
150 shipModel.glUpload();
151 shipModel.freeImages();
152 } catch (Exception e) {}
153 //shipModel = eliteShips[shipModelIndex];
154 GC.collect();
158 void ensureShipModel () {
159 if (eliteShipFiles.length && shipModel is null) {
160 import std.random : uniform;
161 setShip(uniform!"[)"(0, eliteShipFiles.length));
165 void freeShipModel () {
166 if (!showShip && !inMenu && shipModel !is null) {
167 import core.memory : GC;
168 shipModel.glUnload();
169 shipModel.freeData();
170 shipModel.destroy;
171 shipModel = null;
172 GC.collect();
176 void doSaveState (bool forced=false) {
177 if (!forced) {
178 if (formatWorks != 0) return;
179 if (!doSaveCheck) return;
180 auto ct = MonoTime.currTime;
181 if (ct < nextSaveTime) return;
182 } else {
183 if (laytext is null || laytext.lineCount == 0 || formatWorks != 0) return;
185 try {
186 auto fo = VFile(stateFileName, "w");
187 if (laytext !is null && laytext.lineCount) {
188 auto lnum = laytext.findLineAtY(topY);
189 if (lnum >= 0) fo.writeln("wordindex=", laytext.line(lnum).wstart);
191 } catch (Exception) {}
192 doSaveCheck = false;
195 void stateChanged () {
196 if (!doSaveCheck) {
197 doSaveCheck = true;
198 nextSaveTime = MonoTime.currTime+10.seconds;
202 void hardScrollBy (int delta) {
203 if (delta == 0 || laytext is null || laytext.lineCount == 0) return;
204 int oldY = topY;
205 topY += delta;
206 if (topY >= laytext.textHeight-textHeight) topY = cast(int)laytext.textHeight-textHeight;
207 if (topY < 0) topY = 0;
208 if (topY != oldY) {
209 stateChanged();
210 refresh();
214 void scrollBy (int delta) {
215 if (delta == 0 || laytext is null || laytext.lineCount == 0) return;
216 toMove += delta;
217 newYFade = true;
218 newYAlpha = 1;
219 if (delta < 0) {
220 // scrolling up, mark top line
221 newYLine = laytext.findLineAtY(topY);
222 } else {
223 // scrolling down, mark bottom line
224 newYLine = laytext.findLineAtY(topY+textHeight-2);
226 version(none) {
227 conwriteln("scrollBy: delta=", delta, "; newYLine=", newYLine, "; topLine=", laytext.findLineAtY(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 conwriteln("goto: widx=", widx, "; lidx=", lidx, "; fwn=", laytext.line(lidx).wstart, "; topY=", topY);
254 auto lnum = laytext.findLineAtY(topY);
255 conwriteln(" newlnum=", lnum, "; lidx.y=", laytext.line(lidx).y, "; lnum.y=", laytext.line(lnum).y);
260 void loadState () {
261 try {
262 int widx = -1;
263 xiniParse(VFile(stateFileName),
264 "wordindex", &widx,
266 if (widx >= 0) goTo(widx);
267 } catch (Exception) {}
270 void loadAndFormat (string filename) {
271 assert(formatWorks <= 0);
272 booktext = null;
273 laytext = null;
274 newYLine = -1;
275 //formatWorks = -1; //FIXME
276 firstFormat = true;
277 newYFade = false;
278 toMove = 0;
279 recentFiles = null;
280 arrowDir = 0;
281 //sdwindow.redrawOpenGlSceneNow();
282 //booktext = loadBook(newBookFileName);
283 //newBookFileName = null;
284 //reformat();
285 //if (formatWorks < 0) formatWorks = 1; else ++formatWorks;
286 formatWorks = 1;
287 //conwriteln("*** loading new book: '", filename, "'");
288 childTid.send(ReformatWork(null, filename, GWidth, GHeight));
289 refresh();
292 void reformat () {
293 if (formatWorks < 0) formatWorks = 1; else ++formatWorks;
294 childTid.send(ReformatWork(cast(shared)booktext, null, GWidth, GHeight));
295 refresh();
298 void formatComplete (ref ReformatWorkComplete w) {
299 scope(exit) { import core.memory : GC; GC.collect(); GC.minimize(); }
301 auto lt = cast(LayText)w.laytext;
302 scope(exit) if (lt) lt.freeMemory();
303 w.laytext = null;
305 BookMetadata meta = cast(BookMetadata)w.meta;
306 w.meta = null;
308 BookText bt = cast(BookText)w.booktext;
309 w.booktext = null;
310 if (bt !is booktext) {
311 booktext = bt;
312 bookmeta = meta;
313 firstFormat = true;
314 sdwindow.title = booktext.title~" \xe2\x80\x94 "~booktext.authorFirst~" "~booktext.authorLast;
315 } else if (bookmeta is null) {
316 bookmeta = meta;
319 if (isQuitRequested || formatWorks <= 0) return;
320 --formatWorks;
322 if (w.w != GWidth) {
323 if (formatWorks == 0) reformat();
324 return;
327 if (formatWorks != 0) return;
328 freeShipModel();
330 uint widx = 0;
331 if (!firstFormat && laytext !is null && laytext.lineCount) {
332 auto lidx = laytext.findLineAtY(topY);
333 if (lidx >= 0) widx = laytext.line(lidx).wstart;
335 if (laytext !is null) laytext.freeMemory();
336 laytext = lt;
337 lt = null;
338 if (firstFormat) {
339 loadState();
340 firstFormat = false;
341 doSaveCheck = false;
342 stateChanged();
343 } else {
344 goTo(widx);
346 refresh();
349 void pushPosition () {
350 if (laytext is null || laytext.lineCount == 0) return;
351 auto lidx = laytext.findLineAtY(topY);
352 if (lidx >= 0) posstack ~= laytext.line(lidx).wstart;
355 void popPosition () {
356 if (posstack.length == 0) return;
357 auto widx = posstack[$-1];
358 posstack.length -= 1;
359 posstack.assumeSafeAppend;
360 goTo(widx);
363 void gotoSection (int sn) {
364 if (laytext is null || laytext.lineCount == 0 || bookmeta is null) return;
365 if (sn < 0 || sn >= bookmeta.sections.length) return;
366 auto lidx = laytext.findLineWithWord(bookmeta.sections[sn].wordidx);
367 if (lidx >= 0) {
368 auto newY = laytext.line(lidx).y;
369 if (newY != topY) {
370 topY = newY;
371 stateChanged();
372 refresh();
377 version(X11) sdwindow.closeQuery = delegate () { concmd("quit"); };
379 void closeWindow () {
380 doSaveState(true); // forced state save
381 if (!sdwindow.closed && vg !is null) {
382 if (curImg >= 0) { vg.deleteImage(curImg); curImg = -1; }
383 if (curImgWhite >= 0) { vg.deleteImage(curImgWhite); curImgWhite = -1; }
384 freeShipModel();
385 vg.deleteGL2();
386 vg = null;
387 sdwindow.close();
391 sdwindow.visibleForTheFirstTime = delegate () {
392 sdwindow.setAsCurrentOpenGlContext(); // make this window active
393 sdwindow.vsync = false;
394 //sdwindow.useGLFinish = false;
395 //glbindLoadFunctions();
397 try {
398 uint flags = NVG_DEBUG;
399 if (flagNanoAA) flags |= NVG_ANTIALIAS;
400 if (flagNanoSS) flags |= NVG_STENCIL_STROKES;
401 vg = createGL2NVG(flags);
402 if (vg is null) {
403 conwriteln("Could not init nanovg.");
404 assert(0);
405 //sdwindow.close();
407 loadFonts(vg);
408 curImg = createCursorImage(vg);
409 curImgWhite = createCursorImage(vg, true);
410 fps = new PerfGraph("Frame Time", PerfGraph.Style.FPS, "ui");
411 } catch (Exception e) {
412 conwriteln("ERROR: ", e.msg);
413 concmd("quit");
414 return;
417 reformat();
419 refresh();
420 sdwindow.redrawOpenGlScene();
421 refresh();
424 void relayout (bool forced=false) {
425 if (laytext !is null) {
426 uint widx;
427 auto lidx = laytext.findLineAtY(topY);
428 if (lidx >= 0) widx = laytext.line(lidx).wstart;
429 int maxWidth = GWidth-4-2-BND_SCROLLBAR_WIDTH-2;
430 //if (maxWidth < MinWinWidth) maxWidth = MinWinWidth;
432 import core.time;
433 auto stt = MonoTime.currTime;
434 laytext.relayout(maxWidth, forced);
435 auto ett = MonoTime.currTime-stt;
436 conwriteln("relayouted in ", ett.total!"msecs", " milliseconds; lines:", laytext.lineCount, "; words:", laytext.nextWordIndex);
438 goTo(widx);
439 refresh();
443 sdwindow.windowResized = delegate (int w, int h) {
444 //conwriteln("w=", w, "; h=", h);
445 //if (w < MinWinWidth) w = MinWinWidth;
446 //if (h < MinWinHeight) h = MinWinHeight;
447 glViewport(0, 0, w, h);
448 GWidth = w;
449 GHeight = h;
450 textHeight = GHeight-8;
451 //reformat();
452 relayout();
453 refresh();
456 void drawShipName () {
457 if (shipModel is null || shipModel.name.length == 0) return;
458 vg.fontFaceId(uiFont);
459 vg.textAlign(NVGTextAlign.H.Left, NVGTextAlign.V.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 //conwriteln("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 //conwriteln(currPopup.items.length);
486 // find current section
487 currPopup.curItemIdx = 0;
488 auto lidx = laytext.findLineAtY(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) concmd("quit"); };
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 //conwriteln(bi.seqname);
520 s ~= bi.seqname;
521 s ~= ")";
523 if (bi.author.length) { s ~= " \xe2\x80\x94 "; 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) { concmd("r_fps toggle"); 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) { concmd("quit"); 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 static int startX () { pragma(inline, true); return (sbLeft ? 2+BND_SCROLLBAR_WIDTH+2 : 4); }
681 static int endX () { pragma(inline, true); return startX+GWidth-4-2-BND_SCROLLBAR_WIDTH-2-1; }
683 int startY () { pragma(inline, true); return (GHeight-textHeight)/2; }
684 int endY () { pragma(inline, true); return startY+textHeight-1; }
686 sdwindow.redrawOpenGlScene = delegate () {
687 if (isQuitRequested) return;
689 oglResizeConsole(GWidth/2, GHeight/2, 2);
691 __gshared int cnt;
692 conwriteln("cnt=", cnt++);
695 //glClearColor(0, 0, 0, 0);
696 //glClearColor(0.18, 0.18, 0.18, 0);
697 glClearColor(colorBack.r, colorBack.g, colorBack.b, 0);
698 glClear(glNVGClearFlags|EliteModel.glClearFlags);
700 refreshed();
701 needRedrawFlag = (fps !is null && fpsVisible);
702 if (vg is null) return;
704 scope(exit) vg.releaseImages();
705 vg.beginFrame(GWidth, GHeight, 1);
706 drawIfs(vg);
707 // draw scrollbar
709 float curHeight = (laytext !is null ? topY : 0);
710 float th = (laytext !is null ? laytext.textHeight-textHeight : 0);
711 if (th <= 0) { curHeight = 0; th = 1; }
712 float sz = cast(float)(GHeight-4)/th;
713 if (sz > 1) sz = 1; else if (sz < 0.05) sz = 0.05;
714 int sx = (sbLeft ? 2 : GWidth-BND_SCROLLBAR_WIDTH-2);
715 vg.bndScrollSlider(sx, 2, BND_SCROLLBAR_WIDTH, GHeight-4, BND_DEFAULT, curHeight/th, sz);
717 if (laytext is null) {
718 if (shipModel is null) {
719 vg.beginPath();
720 vg.fillColor(colorText);
721 int drawY = (GHeight-textHeight)/2;
722 vg.intersectScissor((sbLeft ? 2+BND_SCROLLBAR_WIDTH+2 : 4), drawY, GWidth-4-2-BND_SCROLLBAR_WIDTH-2, textHeight);
723 vg.fontFaceId(textFont);
724 vg.fontSize(fsizeText);
725 vg.textAlign(NVGTextAlign.H.Center, NVGTextAlign.V.Middle);
726 vg.text(GWidth/2, GHeight/2, "REFORMATTING");
727 vg.fill();
730 // draw text page
731 if (laytext !is null && laytext.lineCount) {
732 vg.beginPath();
733 vg.fillColor(colorText);
734 int drawY = startY;
735 vg.intersectScissor((sbLeft ? 2+BND_SCROLLBAR_WIDTH+2 : 4), drawY, GWidth-4-2-BND_SCROLLBAR_WIDTH-2, textHeight);
736 //FIXME: not GHeight!
737 int lidx = laytext.findLineAtY(topY);
738 if (lidx >= 0 && lidx < laytext.lineCount) {
739 drawY -= topY-laytext.line(lidx).y;
740 vg.textAlign(NVGTextAlign.H.Left, NVGTextAlign.V.Baseline);
741 LayFontStyle lastStyle;
742 int startx = startX;
743 while (lidx < laytext.lineCount && drawY < GHeight) {
744 auto ln = laytext.line(lidx);
745 foreach (ref LayWord w; laytext.lineWords(lidx)) {
746 if (lastStyle != w.style) {
747 if (w.style.fontface != lastStyle.fontface) vg.fontFace(laytext.fontFace(w.style.fontface));
748 vg.fontSize(w.style.fontsize);
749 auto c = NVGColor(w.style.color);
750 vg.fillColor(c);
751 //vg.strokeColor(c);
752 lastStyle = w.style;
754 // line highlighting
755 if (newYFade && newYLine == lidx) vg.fillColor(nvgLerpRGBA(colorText, colorTextHi, newYAlpha));
756 auto oid = w.objectIdx;
757 if (oid >= 0) {
758 vg.fill();
759 laytext.objects[oid].draw(vg, startx+w.x, drawY+ln.h+ln.desc);
760 vg.beginPath();
761 } else {
762 vg.text(startx+w.x, drawY+ln.h+ln.desc, laytext.wordText(w));
764 //TODO: draw lines over whitespace
765 if (lastStyle.underline) vg.rect(startx+w.x, drawY+ln.h+ln.desc+1, w.w, 1);
766 if (lastStyle.strike) vg.rect(startx+w.x, drawY+ln.h+ln.desc-w.asc/2, w.w, 1);
767 if (lastStyle.overline) vg.rect(startx+w.x, drawY+ln.h+ln.desc-w.asc-1, w.w, 1);
768 version(debug_draw) {
769 vg.fill();
770 vg.beginPath();
771 vg.strokeWidth(1);
772 vg.strokeColor(nvgRGB(0, 0, 255));
773 vg.rect(startx+w.x, drawY, w.w, w.h);
774 vg.stroke();
775 vg.beginPath();
777 if (newYFade && newYLine == lidx) vg.fillColor(NVGColor(lastStyle.color));
779 drawY += ln.h;
780 ++lidx;
783 vg.fill();
785 // dim text
786 if (!showShip) {
787 if (colorDim.a != 1) {
788 //vg.scissor(0, 0, GWidth, GHeight);
789 vg.resetScissor;
790 vg.beginPath();
791 vg.fillColor(colorDim);
792 vg.rect(0, 0, GWidth, GHeight);
793 vg.fill();
796 // dim more if menu is active
797 if (inMenu || showShip || formatWorks != 0) {
798 //vg.scissor(0, 0, GWidth, GHeight);
799 vg.resetScissor;
800 vg.beginPath();
801 //vg.globalAlpha(0.5);
802 vg.fillColor(nvgRGBA(0, 0, 0, (showShip || formatWorks != 0 ? 127 : 64)));
803 vg.rect(0, 0, GWidth, GHeight);
804 vg.fill();
806 if (shipModel !is null) {
807 vg.endFrame();
808 float zz = shipModel.bbox[1].z-shipModel.bbox[0].z;
809 zz += 10;
810 lightsClear();
812 lightAdd(
813 0, 60, 60,
814 1.0, 0.0, 0.0
817 lightAdd(
818 //0, 0, -60,
819 0, 0, -zz,
820 1.0, 1.0, 1.0
822 drawModel(shipAngle, shipModel);
823 vg.beginFrame(GWidth, GHeight, 1);
824 drawShipName();
825 //vg.endFrame();
827 if (formatWorks == 0) {
828 if (inMenu) {
829 //vg.beginFrame(GWidth, GHeight, 1);
830 //vg.scissor(0, 0, GWidth, GHeight);
831 vg.resetScissor;
832 currPopup.draw();
833 //vg.endFrame();
836 if (fps !is null && fpsVisible) {
837 //vg.beginFrame(GWidth, GHeight, 1);
838 //vg.scissor(0, 0, GWidth, GHeight);
839 vg.resetScissor;
840 fps.render(vg, GWidth-fps.width-4, GHeight-fps.height-4);
841 //vg.endFrame();
843 if (inGalaxyMap) drawGalaxy(vg);
844 // mouse cursor
845 if (curImg >= 0 && !mouseHidden) {
846 int w, h;
847 //vg.beginFrame(GWidth, GHeight, 1);
848 vg.beginPath();
849 //vg.scissor(0, 0, GWidth, GHeight);
850 vg.resetScissor;
851 vg.imageSize(curImg, &w, &h);
852 if (mouseFadingAway) {
853 mouseAlpha -= 0.1;
854 if (mouseAlpha <= 0) { mouseFadingAway = false; mouseHidden = true; }
855 } else {
856 mouseAlpha = 1.0f;
858 vg.globalAlpha(mouseAlpha);
859 if (!mouseHigh) {
860 vg.fillPaint(vg.imagePattern(mouseX, mouseY, w, h, 0, curImg, 1));
861 } else {
862 vg.fillPaint(vg.imagePattern(mouseX, mouseY, w, h, 0, curImgWhite, 1));
864 vg.rect(mouseX, mouseY, w, h);
865 vg.fill();
867 if (mouseHigh) {
868 vg.beginPath();
869 vg.fillPaint(vg.imagePattern(mouseX, mouseY, w, h, 0, curImgWhite, 0.4));
870 vg.rect(mouseX, mouseY, w, h);
871 vg.fill();
874 //vg.endFrame();
876 vg.endFrame();
877 oglDrawConsole();
880 void processThreads () {
881 ReformatWorkComplete wd;
882 for (;;) {
883 bool workDone = false;
884 auto res = receiveTimeout(Duration.zero,
885 (QuitWork w) {
886 formatWorks = -1;
888 (ReformatWorkComplete w) {
889 wd = w;
890 workDone = true;
893 if (!res) { assert(!workDone); break; }
894 if (workDone) { workDone = false; formatComplete(wd); }
898 auto lastTimerEventTime = MonoTime.currTime;
899 bool somethingVisible = true;
901 sdwindow.visibilityChanged = delegate (bool vis) {
902 //import core.stdc.stdio; printf("VISCHANGED: %s\n", (vis ? "tan" : "ona").ptr);
903 somethingVisible = vis;
906 conRegVar!fpsVisible("r_fps", "show fps indicator", (self, valstr) { refresh(); });
907 conRegVar!inGalaxyMap("r_galaxymap", "show Elite galaxy map", (self, valstr) { refresh(); });
909 conRegVar!interAllowed("r_interference", "show interference", (self, valstr) { refresh(); });
910 conRegVar!sbLeft("r_sbleft", "show scrollbar at the left side", (self, valstr) { refresh(); });
912 conRegVar!showShip("r_showship", "show Elite ship", (self, valstr) {
913 if (eliteShipFiles.length == 0) return false;
914 return true;
916 (self, valstr) {
917 if (showShip) ensureShipModel(); else freeShipModel();
918 refresh();
922 conRegFunc!(() {
923 if (currPopup !is null) {
924 currPopup.destroy;
925 currPopup = null;
926 freeShipModel();
927 refresh();
929 onPopupSelect = null;
930 })("menu_close", "close current popup menu");
932 conRegFunc!(() {
933 if (formatWorks == 0 && !showShip && !inGalaxyMap) {
934 currPopup.destroy;
935 currPopup = null;
936 ensureShipModel();
937 createSectionMenu();
938 refresh();
940 })("menu_section", "show section menu");
942 conRegFunc!(() {
943 if (formatWorks == 0 && !showShip && !inGalaxyMap) {
944 currPopup.destroy;
945 currPopup = null;
946 ensureShipModel();
947 createRecentMenu();
948 refresh();
950 })("menu_recent", "show recent menu");
952 sdwindow.eventLoop(1000/34,
953 delegate () {
954 processThreads();
955 if (sdwindow.closed) return;
956 conProcessQueue();
957 if (isQuitRequested) { closeWindow(); return; }
958 auto ctt = MonoTime.currTime;
961 auto spass = (ctt-lastTimerEventTime).total!"msecs";
962 //if (spass >= 30) { import core.stdc.stdio; printf("WARNING: too long frame time: %u\n", cast(uint)spass); }
963 //{ import core.stdc.stdio; printf("FRAME TIME: %u\n", cast(uint)spass); }
964 lastTimerEventTime = ctt;
965 // update FPS timer
966 prevt = curt;
967 //curt = MonoTime.currTime;
968 curt = ctt;
969 //auto secs = cast(double)((curt-stt).total!"msecs")/1000.0;
970 auto dt = cast(double)((curt-prevt).total!"msecs")/1000.0;
971 if (fps !is null) fps.update(dt);
974 // smooth scrolling
975 if (formatWorks == 0) {
976 enum Delta = 92*2;
977 if (toMove < 0) {
978 int sc = -toMove;
979 if (sc > Delta) sc = Delta;
980 hardScrollBy(-sc);
981 toMove += sc;
982 nextFadeTime = ctt+500.msecs;
983 refresh();
984 } else if (toMove > 0) {
985 int sc = toMove;
986 if (sc > Delta) sc = Delta;
987 hardScrollBy(sc);
988 toMove -= sc;
989 nextFadeTime = ctt+500.msecs;
990 refresh();
991 } else if (arrowDir) {
992 hardScrollBy(arrowDir*6*2);
993 refresh();
995 // highlight fading
996 if (newYFade) {
997 if (ctt >= nextFadeTime) {
998 if ((newYAlpha -= 0.1) <= 0) {
999 newYFade = false;
1000 } else {
1001 nextFadeTime = ctt+25.msecs;
1003 refresh();
1007 // interference processing
1008 if (ctt >= nextIfTime) {
1009 import std.random : uniform;
1010 if (uniform!"[]"(0, 100) >= 50) { if (addIf()) refresh(); }
1011 nextIfTime += (uniform!"[]"(50, 1500)).msecs;
1013 if (processIfs()) refresh();
1014 // ship rotation
1015 if (shipModel !is null) {
1016 shipAngle -= 1;
1017 if (shipAngle < 359) shipAngle += 360;
1018 refresh();
1020 // mouse autohide
1021 if (!mouseFadingAway) {
1022 if (!mouseHidden && !mouseHigh) {
1023 if ((ctt-lastMMove).total!"msecs" > 2500) {
1024 //mouseHidden = true;
1025 mouseFadingAway = true;
1026 mouseAlpha = 1.0f;
1027 refresh();
1031 if (somethingVisible) {
1032 // sadly, to keep framerate we have to redraw each frame, or driver will throw us out of the ship
1033 if (/*needRedraw*/true) sdwindow.redrawOpenGlSceneNow();
1034 } else {
1035 refresh();
1037 doSaveState();
1038 // load new book?
1039 if (newBookFileName.length && formatWorks == 0) {
1040 doSaveState(true); // forced state save
1041 closeMenu();
1042 ensureShipModel();
1043 loadAndFormat(newBookFileName);
1044 newBookFileName = null;
1045 sdwindow.redrawOpenGlSceneNow();
1046 //refresh();
1049 delegate (KeyEvent event) {
1050 if (sdwindow.closed) return;
1051 if (conKeyEvent(event)) return;
1052 if (event.key == Key.PadEnter) event.key = Key.Enter;
1053 if ((event.modifierState&ModifierState.numLock) == 0) {
1054 switch (event.key) {
1055 case Key.Pad0: event.key = Key.Insert; break;
1056 case Key.PadDot: event.key = Key.Delete; break;
1057 case Key.Pad1: event.key = Key.End; break;
1058 case Key.Pad2: event.key = Key.Down; break;
1059 case Key.Pad3: event.key = Key.PageDown; break;
1060 case Key.Pad4: event.key = Key.Left; break;
1061 case Key.Pad6: event.key = Key.Right; break;
1062 case Key.Pad7: event.key = Key.Home; break;
1063 case Key.Pad8: event.key = Key.Up; break;
1064 case Key.Pad9: event.key = Key.PageUp; break;
1065 //case Key.PadEnter: event.key = Key.Enter; break;
1066 default:
1069 if (controlKey(event)) return;
1070 if (menuKey(event)) return;
1071 if (readerKey(event)) return;
1073 delegate (MouseEvent event) {
1074 if (sdwindow.closed) return;
1076 int linkAt (int msx, int msy) {
1077 if (laytext !is null && bookmeta !is null) {
1078 if (msx >= startX && msx <= endX && msy >= startY && msy <= endY) {
1079 auto widx = laytext.wordAtXY(msx-startX, topY+msy-startY);
1080 if (widx >= 0) {
1081 //conwriteln("word at (", msx-startX, ",", msy-startY, "): ", widx);
1082 auto w = laytext.wordByIndex(widx);
1083 while (widx >= 0) {
1084 //conwriteln("word #", widx, "; href=", w.style.href);
1085 if (!w.style.href) break;
1086 if (auto hr = w.wordNum in bookmeta.hrefs) {
1087 dstring href = hr.name;
1088 if (href.length > 1 && href[0] == '#') {
1089 href = href[1..$];
1090 foreach (const ref id; bookmeta.ids) {
1091 if (id.name == href) {
1092 //pushPosition();
1093 //goTo(id.wordidx);
1094 return id.wordidx;
1097 //conwriteln("id '", hr.name, "' not found!");
1098 return -1;
1101 --widx;
1102 --w;
1107 return -1;
1110 lastMMove = MonoTime.currTime;
1111 if (mouseHidden || mouseFadingAway) {
1112 mouseHidden = false;
1113 mouseFadingAway = false;
1114 mouseAlpha = 1.0f;
1115 refresh();
1117 if (mouseX != event.x || mouseY != event.y) {
1118 mouseX = event.x;
1119 mouseY = event.y;
1120 refresh();
1122 if (!menuMouse(event) && !showShip) {
1123 if (event.type == MouseEventType.buttonPressed) {
1124 switch (event.button) {
1125 case MouseButton.wheelUp: hardScrollBy(-42); break;
1126 case MouseButton.wheelDown: hardScrollBy(42); break;
1127 case MouseButton.left:
1128 auto wid = linkAt(event.x, event.y);
1129 if (wid >= 0) {
1130 pushPosition();
1131 goTo(wid);
1133 break;
1134 case MouseButton.right:
1135 popPosition();
1136 break;
1137 default:
1141 mouseHigh = (linkAt(event.x, event.y) >= 0);
1143 delegate (dchar ch) {
1144 if (sdwindow.closed) return;
1145 if (conCharEvent(ch)) return;
1146 if (ch == '`') { concmd("r_console tan"); return; }
1149 closeWindow();
1151 childTid.send(QuitWork());
1152 while (formatWorks >= 0) processThreads();
1156 // ////////////////////////////////////////////////////////////////////////// //
1157 void main (string[] args) {
1158 import std.path;
1160 universe = Galaxy(0);
1162 if (args.length == 1) {
1163 try {
1164 string lnn;
1165 foreach (string line; VFile(buildPath(RcDir, ".lastfile")).byLineCopy) {
1166 if (!line.isComment) lnn = line;
1168 if (lnn.length) args ~= lnn;
1169 } catch (Exception) {}
1171 if (args.length == 1) assert(0, "no filename");
1173 readConfig();
1175 run(args[1]);