fixed incorrect text size calculation
[xreader.git] / xreader.d
blob08d2c7b18174c17050ec9ba116561631de27908a
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 is aliced;
19 import core.time;
21 import std.concurrency;
22 import std.net.curl;
23 import std.regex;
25 import arsd.simpledisplay;
26 import arsd.image;
28 import iv.nanovega;
29 import iv.nanovega.textlayouter;
30 import iv.nanovega.blendish;
31 import iv.nanovega.perf;
33 import iv.sdbm;
34 import iv.strex;
36 import iv.cmdcongl;
38 import iv.vfs;
39 import iv.vfs.io;
41 import xmodel;
42 import xiniz;
44 import booktext;
46 import xreadercfg;
47 import xreaderui;
48 import xreaderifs;
49 import xreaderfmt;
51 import eworld;
52 import ewbillboard;
54 //version = debug_draw;
57 // ////////////////////////////////////////////////////////////////////////// //
58 __gshared int oglConScale = 1;
61 // ////////////////////////////////////////////////////////////////////////// //
62 __gshared string bookFileName;
64 __gshared int formatWorks = -1;
65 __gshared NVGContext vg = null;
66 __gshared PerfGraph fps;
67 __gshared bool fpsVisible = false;
68 __gshared BookText bookText;
69 __gshared string newBookFileName;
70 __gshared uint[] posstack;
71 __gshared SimpleWindow sdwindow;
72 __gshared LayTextC laytext;
73 __gshared BookInfo[] recentFiles;
74 __gshared BookMetadata bookmeta;
76 __gshared int textHeight;
78 __gshared int toMove = 0; // for smooth scroller
79 __gshared int topY = 0;
80 __gshared int arrowDir = 0;
81 __gshared int arrowSpeed = 0;
83 __gshared int newYLine = -1; // index
84 __gshared float newYAlpha;
85 __gshared bool newYFade = false;
86 __gshared MonoTime nextFadeTime;
88 __gshared NVGImage curImg, curImgWhite;
89 __gshared int mouseX = -666, mouseY = -666;
90 __gshared bool mouseHigh = false;
91 __gshared bool mouseHidden = false;
92 __gshared MonoTime lastMMove;
93 __gshared float mouseAlpha = 1.0f;
94 __gshared int mouseFadingAway = false;
96 __gshared bool needRedrawFlag = true;
98 __gshared bool firstFormat = true;
100 __gshared bool inGalaxyMap = false;
101 __gshared PopupMenu currPopup;
102 __gshared void delegate (int item) onPopupSelect;
103 __gshared bool delegate (KeyEvent event) onPopupKeyEvent; // return `true` to close menu
104 __gshared int shipModelIndex = 0;
105 __gshared bool popupNoShipKill = false;
107 __gshared bool doSaveCheck = false;
108 __gshared MonoTime nextSaveTime;
111 // ////////////////////////////////////////////////////////////////////////// //
112 void refresh () { needRedrawFlag = true; }
113 void refreshed () { needRedrawFlag = false; }
115 bool needRedraw () {
116 return (needRedrawFlag || (currPopup !is null && currPopup.needRedraw));
120 @property bool inMenu () { return (currPopup !is null); }
121 void closeMenu () { if (currPopup !is null) currPopup.destroy; currPopup = null; onPopupSelect = null; onPopupKeyEvent = null; }
124 void setShip (int idx) {
125 if (eliteShipFiles.length) {
126 import core.memory : GC;
127 if (idx >= eliteShipFiles.length) idx = cast(int)eliteShipFiles.length-1;
128 if (idx < 0) idx = 0;
129 if (shipModelIndex == idx && shipModel !is null) return;
130 // remove old ship
131 shipModelIndex = idx;
132 if (shipModel !is null) {
133 shipModel.glUnload();
134 shipModel.freeData();
135 shipModel.destroy;
136 shipModel = null;
138 GC.collect();
139 // load new ship
140 try {
141 shipModel = new EliteModel(eliteShipFiles[shipModelIndex]);
142 shipModel.glUpload();
143 shipModel.freeImages();
144 } catch (Exception e) {}
145 //shipModel = eliteShips[shipModelIndex];
146 GC.collect();
150 void ensureShipModel () {
151 if (eliteShipFiles.length && shipModel is null) {
152 import std.random : uniform;
153 setShip(uniform!"[)"(0, eliteShipFiles.length));
157 void freeShipModel () {
158 if (!showShip && !inMenu && shipModel !is null) {
159 import core.memory : GC;
160 shipModel.glUnload();
161 shipModel.freeData();
162 shipModel.destroy;
163 shipModel = null;
164 GC.collect();
169 void loadState () {
170 try {
171 int widx = -1;
172 xiniParse(VFile(stateFileName),
173 "wordindex", &widx,
175 if (widx >= 0) goTo(widx);
176 } catch (Exception) {}
179 void doSaveState (bool forced=false) {
180 if (!forced) {
181 if (formatWorks != 0) return;
182 if (!doSaveCheck) return;
183 auto ct = MonoTime.currTime;
184 if (ct < nextSaveTime) return;
185 } else {
186 if (laytext is null || laytext.lineCount == 0 || formatWorks != 0) return;
188 try {
189 auto fo = VFile(stateFileName, "w");
190 if (laytext !is null && laytext.lineCount) {
191 auto lnum = laytext.findLineAtY(topY);
192 if (lnum >= 0) fo.writeln("wordindex=", laytext.line(lnum).wstart);
194 } catch (Exception) {}
195 doSaveCheck = false;
198 void stateChanged () {
199 if (!doSaveCheck) {
200 doSaveCheck = true;
201 nextSaveTime = MonoTime.currTime+10.seconds;
206 void hardScrollBy (int delta) {
207 if (delta == 0 || laytext is null || laytext.lineCount == 0) return;
208 int oldY = topY;
209 topY += delta;
210 if (topY >= laytext.textHeight-textHeight) topY = cast(int)laytext.textHeight-textHeight;
211 if (topY < 0) topY = 0;
212 if (topY != oldY) {
213 stateChanged();
214 refresh();
218 void scrollBy (int delta) {
219 if (delta == 0 || laytext is null || laytext.lineCount == 0) return;
220 toMove += delta;
221 newYFade = true;
222 newYAlpha = 1;
223 if (delta < 0) {
224 // scrolling up, mark top line
225 newYLine = laytext.findLineAtY(topY);
226 } else {
227 // scrolling down, mark bottom line
228 newYLine = laytext.findLineAtY(topY+textHeight-2);
230 version(none) {
231 conwriteln("scrollBy: delta=", delta, "; newYLine=", newYLine, "; topLine=", laytext.findLineAtY(topY));
233 if (newYLine < 0) newYFade = false;
237 void goHome () {
238 if (laytext is null) return;
239 if (topY != 0) {
240 topY = 0;
241 stateChanged();
242 refresh();
247 void goEnd () {
248 if (laytext is null || laytext.lineCount < 2) return;
249 auto newY = laytext.line(laytext.lineCount-1).y;
250 if (newY >= laytext.textHeight-textHeight) newY = cast(int)laytext.textHeight-textHeight;
251 if (newY < 0) newY = 0;
252 if (newY != topY) {
253 topY = newY;
254 stateChanged();
255 refresh();
260 void goTo (uint widx) {
261 if (laytext is null) return;
262 auto lidx = laytext.findLineWithWord(widx);
263 if (lidx != -1) {
264 assert(lidx < laytext.lineCount);
265 toMove = 0;
266 if (topY != laytext.line(lidx).y) {
267 topY = laytext.line(lidx).y;
268 stateChanged();
269 refresh();
271 version(none) {
272 conwriteln("goto: widx=", widx, "; lidx=", lidx, "; fwn=", laytext.line(lidx).wstart, "; topY=", topY);
273 auto lnum = laytext.findLineAtY(topY);
274 conwriteln(" newlnum=", lnum, "; lidx.y=", laytext.line(lidx).y, "; lnum.y=", laytext.line(lnum).y);
280 void pushPosition () {
281 if (laytext is null || laytext.lineCount == 0) return;
282 auto lidx = laytext.findLineAtY(topY);
283 if (lidx >= 0) posstack ~= laytext.line(lidx).wstart;
286 void popPosition () {
287 if (posstack.length == 0) return;
288 auto widx = posstack[$-1];
289 posstack.length -= 1;
290 posstack.assumeSafeAppend;
291 goTo(widx);
295 void gotoSection (int sn) {
296 if (laytext is null || laytext.lineCount == 0 || bookmeta is null) return;
297 if (sn < 0 || sn >= bookmeta.sections.length) return;
298 auto lidx = laytext.findLineWithWord(bookmeta.sections[sn].wordidx);
299 if (lidx >= 0) {
300 auto newY = laytext.line(lidx).y;
301 if (newY != topY) {
302 topY = newY;
303 stateChanged();
304 refresh();
310 void relayout (bool forced=false) {
311 if (laytext !is null) {
312 uint widx;
313 auto lidx = laytext.findLineAtY(topY);
314 if (lidx >= 0) widx = laytext.line(lidx).wstart;
315 int maxWidth = GWidth-4-2-BND_SCROLLBAR_WIDTH-2;
316 //if (maxWidth < MinWinWidth) maxWidth = MinWinWidth;
318 import core.time;
319 auto stt = MonoTime.currTime;
320 laytext.relayout(maxWidth, forced);
321 auto ett = MonoTime.currTime-stt;
322 conwriteln("relayouted in ", ett.total!"msecs", " milliseconds; lines:", laytext.lineCount, "; words:", laytext.nextWordIndex);
324 goTo(widx);
325 refresh();
330 void drawShipName () {
331 if (shipModel is null || shipModel.name.length == 0) return;
332 vg.fontFaceId(uiFont);
333 vg.textAlign(NVGTextAlign.H.Left, NVGTextAlign.V.Baseline);
334 vg.fontSize(fsizeUI);
335 auto w = vg.bndLabelWidth(-1, shipModel.name)+8;
336 float h = BND_WIDGET_HEIGHT+8;
337 float mx = (GWidth-w)/2.0;
338 float my = (GHeight-h)-8;
339 vg.bndMenuBackground(mx, my, w, h, BND_CORNER_NONE);
340 vg.bndMenuItem(mx+4, my+4, w-8, BND_WIDGET_HEIGHT, BND_DEFAULT, -1, shipModel.name);
341 if (shipModel.dispName && shipModel.dispName != shipModel.name) {
342 my -= BND_WIDGET_HEIGHT+16;
343 w = vg.bndLabelWidth(-1, shipModel.dispName)+8;
344 mx = (GWidth-w)/2.0;
345 vg.bndMenuBackground(mx, my, w, h, BND_CORNER_NONE);
346 vg.bndMenuItem(mx+4, my+4, w-8, BND_WIDGET_HEIGHT, BND_DEFAULT, -1, shipModel.dispName);
351 void createSectionMenu () {
352 closeMenu();
353 //conwriteln("lc=", laytext.lineCount, "; bm: ", (bookmeta !is null));
354 if (laytext is null || laytext.lineCount == 0 || bookmeta is null) { freeShipModel(); return; }
355 currPopup = new PopupMenu(vg, "Sections"d, () {
356 dstring[] items;
357 foreach (const ref sc; bookmeta.sections) items ~= sc.name;
358 return items;
360 currPopup.allowFiltering = true;
361 //conwriteln(currPopup.items.length);
362 // find current section
363 currPopup.itemIndex = 0;
364 auto lidx = laytext.findLineAtY(topY);
365 if (lidx >= 0 && bookmeta.sections.length > 0) {
366 foreach (immutable sidx, const ref sc; bookmeta.sections) {
367 auto sline = laytext.findLineWithWord(sc.wordidx);
368 if (sline >= 0 && lidx >= sline) currPopup.itemIndex = cast(int)sidx;
371 onPopupSelect = (int item) { gotoSection(item); };
375 void createQuitMenu (bool wantYes) {
376 closeMenu();
377 currPopup = new PopupMenu(vg, "Quit?"d, () {
378 return ["Yes"d, "No"d];
380 currPopup.itemIndex = (wantYes ? 0 : 1);
381 onPopupSelect = (int item) { if (item == 0) concmd("quit"); };
385 void createRecentMenu () {
386 closeMenu();
387 if (recentFiles.length == 0) recentFiles = loadDetailedHistory();
388 if (recentFiles.length == 0) { freeShipModel(); return; }
389 currPopup = new PopupMenu(vg, "Recent files"d, () {
390 import std.conv : to;
391 dstring[] res;
392 foreach (const ref BookInfo bi; recentFiles) {
393 string s = bi.title;
394 if (bi.seqname.length) {
395 s ~= " (";
396 if (bi.seqnum) { s ~= to!string(bi.seqnum); s ~= ": "; }
397 //conwriteln(bi.seqname);
398 s ~= bi.seqname;
399 s ~= ")";
401 if (bi.author.length) { s ~= " \xe2\x80\x94 "; s ~= bi.author; }
402 res ~= s.to!dstring;
404 return res;
406 currPopup.allowFiltering = true;
407 currPopup.itemIndex = cast(int)recentFiles.length-1;
408 onPopupSelect = (int item) {
409 newBookFileName = recentFiles[item].diskfile;
410 popupNoShipKill = true;
412 onPopupKeyEvent = (KeyEvent event) {
413 if (event == "Delete" && currPopup.isCurValid) {
414 auto idx = currPopup.itemIndex;
415 if (idx >= 0 && idx < recentFiles.length) {
416 removeFileFromHistory(recentFiles[idx].diskfile);
417 currPopup.removeItem(idx);
418 foreach (immutable c; idx+1..recentFiles.length) recentFiles[c-1] = recentFiles[c];
419 recentFiles.length -= 1;
420 recentFiles.assumeSafeAppend;
423 return false; // don't close menu
428 bool menuKey (KeyEvent event) {
429 if (formatWorks != 0) return false;
430 if (!inMenu) return false;
431 if (inGalaxyMap) return false;
432 if (!event.pressed) return false;
433 if (currPopup is null) return false;
434 auto res = currPopup.onKey(event);
435 if (res == PopupMenu.Close) {
436 closeMenu();
437 freeShipModel();
438 refresh();
439 } else if (res >= 0) {
440 if (onPopupSelect !is null) onPopupSelect(res);
441 closeMenu();
442 if (popupNoShipKill) popupNoShipKill = false; else freeShipModel();
443 refresh();
444 } else if (res == PopupMenu.NotMine) {
445 if (onPopupKeyEvent !is null && onPopupKeyEvent(event)) {
446 closeMenu();
447 freeShipModel();
448 refresh();
451 return true;
455 bool menuChar (dchar dch) {
456 if (formatWorks != 0) return false;
457 if (!inMenu) return false;
458 if (inGalaxyMap) return false;
459 if (currPopup is null) return false;
460 auto res = currPopup.onChar(dch);
461 if (res == PopupMenu.Close) {
462 closeMenu();
463 freeShipModel();
464 refresh();
465 } else if (res >= 0) {
466 if (onPopupSelect !is null) onPopupSelect(res);
467 closeMenu();
468 if (popupNoShipKill) popupNoShipKill = false; else freeShipModel();
469 refresh();
471 return true;
475 bool menuMouse (MouseEvent event) {
476 if (formatWorks != 0) return false;
477 if (!inMenu) return false;
478 if (inGalaxyMap) return false;
479 if (currPopup is null) return false;
480 auto res = currPopup.onMouse(event);
481 if (res == PopupMenu.Close) {
482 closeMenu();
483 freeShipModel();
484 refresh();
485 } else if (res >= 0) {
486 if (onPopupSelect !is null) onPopupSelect(res);
487 closeMenu();
488 if (popupNoShipKill) popupNoShipKill = false; else freeShipModel();
489 refresh();
491 return true;
495 bool readerKey (KeyEvent event) {
496 if (formatWorks != 0) return false;
497 if (!event.pressed) {
498 switch (event.key) {
499 case Key.Up: arrowDir = 0; return true;
500 case Key.Down: arrowDir = 0; return true;
501 default:
503 return false;
505 switch (event.key) {
506 case Key.Space:
507 if (event.modifierState&ModifierState.shift) {
508 //goto case Key.PageUp;
509 hardScrollBy(toMove); toMove = 0;
510 scrollBy(-textHeight/3*2);
511 } else {
512 //goto case Key.PageDown;
513 hardScrollBy(toMove); toMove = 0;
514 scrollBy(textHeight/3*2);
516 break;
517 case Key.Backspace:
518 popPosition();
519 break;
520 case Key.PageUp:
521 hardScrollBy(toMove); toMove = 0;
522 hardScrollBy(-(textHeight > 32 ? textHeight-32 : textHeight));
523 break;
524 case Key.PageDown:
525 hardScrollBy(toMove); toMove = 0;
526 hardScrollBy(textHeight > 32 ? textHeight-32 : textHeight);
527 break;
528 case Key.Up:
529 //scrollBy(-8);
530 arrowDir = -1;
531 break;
532 case Key.Down:
533 //scrollBy(8);
534 arrowDir = 1;
535 break;
536 case Key.H:
537 if (laytext !is null) {
538 if (event == "C-H") goEnd(); else goHome();
540 break;
541 default:
543 return true;
547 bool controlKey (KeyEvent event) {
548 if (!event.pressed) return false;
549 switch (event.key) {
550 case Key.Escape:
551 if (inGalaxyMap) { inGalaxyMap = false; refresh(); return true; }
552 if (inMenu) { closeMenu(); freeShipModel(); refresh(); return true; }
553 if (showShip) { showShip = false; freeShipModel(); refresh(); return true; }
554 ensureShipModel();
555 createQuitMenu(true);
556 refresh();
557 return true;
558 case Key.P: if (event.modifierState == ModifierState.ctrl) { concmd("r_fps toggle"); return true; } break;
559 case Key.I: if (event.modifierState == ModifierState.ctrl) { concmd("r_interference toggle"); return true; } break;
560 case Key.N: if (event.modifierState == ModifierState.ctrl) { concmd("r_sbleft toggle"); return true; } break;
561 case Key.C: if (event.modifierState == ModifierState.ctrl) { if (addIf()) refresh(); return true; } break;
562 case Key.E:
563 if (event.modifierState == ModifierState.ctrl && eliteShipFiles.length > 0) {
564 if (!inMenu) {
565 showShip = !showShip;
566 if (showShip) ensureShipModel(); else freeShipModel();
567 refresh();
569 return true;
571 break;
572 case Key.Q: if (event.modifierState == ModifierState.ctrl) { concmd("quit"); return true; } break;
573 case Key.B: if (formatWorks == 0 && !inMenu && !inGalaxyMap && event.modifierState == ModifierState.ctrl) { pushPosition(); return true; } break;
574 case Key.S:
575 if (formatWorks == 0 && !showShip && !inMenu && !inGalaxyMap) {
576 ensureShipModel();
577 createSectionMenu();
578 refresh();
580 break;
581 case Key.L:
582 if (formatWorks == 0 && event.modifierState == ModifierState.alt) {
583 ensureShipModel();
584 createRecentMenu();
585 refresh();
587 break;
588 case Key.M:
589 if (!inMenu && !showShip) {
590 inGalaxyMap = !inGalaxyMap;
591 refresh();
593 break;
594 case Key.R:
595 if (formatWorks == 0 && event.modifierState == ModifierState.ctrl) relayout(true);
596 break;
597 case Key.Home: if (showShip) { setShip(0); return true; } break;
598 case Key.End: if (showShip) { setShip(cast(int)eliteShipFiles.length); return true; } break;
599 case Key.Up: case Key.Left: if (showShip) { setShip(shipModelIndex-1); return true; } break;
600 case Key.Down: case Key.Right: if (showShip) { setShip(shipModelIndex+1); return true; } break;
601 default:
603 return showShip;
606 int startX () { pragma(inline, true); return (sbLeft ? 2+BND_SCROLLBAR_WIDTH+2 : 4); }
607 int endX () { pragma(inline, true); return startX+GWidth-4-2-BND_SCROLLBAR_WIDTH-2-1; }
609 int startY () { pragma(inline, true); return (GHeight-textHeight)/2; }
610 int endY () { pragma(inline, true); return startY+textHeight-1; }
613 // ////////////////////////////////////////////////////////////////////////// //
614 void run () {
615 if (GWidth < MinWinWidth) GWidth = MinWinWidth;
616 if (GHeight < MinWinHeight) GHeight = MinWinHeight;
618 bookText = loadBook(bookFileName);
620 setOpenGLContextVersion(3, 0); // it's enough
621 //openGLContextCompatible = false;
623 sdwindow = new SimpleWindow(GWidth, GHeight, bookText.title~" \xe2\x80\x94 "~bookText.authorFirst~" "~bookText.authorLast, OpenGlOptions.yes, Resizability.allowResizing);
624 sdwindow.hideCursor(); // we will do our own
625 sdwindow.setMinSize(MinWinWidth, MinWinHeight);
627 version(X11) sdwindow.closeQuery = delegate () { concmd("quit"); };
629 auto stt = MonoTime.currTime;
630 auto prevt = MonoTime.currTime;
631 auto curt = prevt;
632 textHeight = GHeight-8;
634 MonoTime nextIfTime = MonoTime.currTime;
636 lastMMove = MonoTime.currTime;
638 auto childTid = spawn(&reformatThreadFn, thisTid);
639 childTid.setMaxMailboxSize(128, OnCrowding.block);
640 thisTid.setMaxMailboxSize(128, OnCrowding.block);
642 void loadAndFormat (string filename) {
643 assert(formatWorks <= 0);
644 bookText = null;
645 laytext = null;
646 newYLine = -1;
647 //formatWorks = -1; //FIXME
648 firstFormat = true;
649 newYFade = false;
650 toMove = 0;
651 recentFiles = null;
652 arrowDir = 0;
653 arrowSpeed = 0;
654 //sdwindow.redrawOpenGlSceneNow();
655 //bookText = loadBook(newBookFileName);
656 //newBookFileName = null;
657 //reformat();
658 //if (formatWorks < 0) formatWorks = 1; else ++formatWorks;
659 formatWorks = 1;
660 //conwriteln("*** loading new book: '", filename, "'");
661 childTid.send(ReformatWork(null, filename, GWidth, GHeight));
662 refresh();
665 void reformat () {
666 if (formatWorks < 0) formatWorks = 1; else ++formatWorks;
667 childTid.send(ReformatWork(cast(shared)bookText, null, GWidth, GHeight));
668 refresh();
671 void formatComplete (ref ReformatWorkComplete w) {
672 scope(exit) { import core.memory : GC; GC.collect(); GC.minimize(); }
674 auto lt = cast(LayTextC)w.laytext;
675 scope(exit) if (lt) lt.freeMemory();
676 w.laytext = null;
678 BookMetadata meta = cast(BookMetadata)w.meta;
679 w.meta = null;
681 BookText bt = cast(BookText)w.booktext;
682 w.booktext = null;
683 if (bt !is bookText) {
684 bookText = bt;
685 bookmeta = meta;
686 firstFormat = true;
687 sdwindow.title = bookText.title~" \xe2\x80\x94 "~bookText.authorFirst~" "~bookText.authorLast;
688 } else if (bookmeta is null) {
689 bookmeta = meta;
692 if (isQuitRequested || formatWorks <= 0) return;
693 --formatWorks;
695 if (w.w != GWidth) {
696 if (formatWorks == 0) reformat();
697 return;
700 if (formatWorks != 0) return;
701 freeShipModel();
703 uint widx = 0;
704 if (!firstFormat && laytext !is null && laytext.lineCount) {
705 auto lidx = laytext.findLineAtY(topY);
706 if (lidx >= 0) widx = laytext.line(lidx).wstart;
708 if (laytext !is null) laytext.freeMemory();
709 laytext = lt;
710 lt = null;
711 if (firstFormat) {
712 loadState();
713 firstFormat = false;
714 doSaveCheck = false;
715 stateChanged();
716 } else {
717 goTo(widx);
719 refresh();
722 void closeWindow () {
723 doSaveState(true); // forced state save
724 if (!sdwindow.closed && vg !is null) {
725 curImg.clear();
726 curImgWhite.clear();
727 freeShipModel();
728 vg.kill();
729 vg = null;
730 sdwindow.close();
734 sdwindow.visibleForTheFirstTime = delegate () {
735 sdwindow.setAsCurrentOpenGlContext(); // make this window active
736 sdwindow.vsync = false;
737 //sdwindow.useGLFinish = false;
738 //glbindLoadFunctions();
740 try {
741 NVGContextFlag[4] flagList;
742 uint flagCount = 0;
743 if (flagNanoAA) flagList[flagCount++] = NVGContextFlag.Antialias;
744 if (flagNanoSS) flagList[flagCount++] = NVGContextFlag.StencilStrokes;
745 if (flagNanoFAA) flagList[flagCount++] = NVGContextFlag.FontAA; else flagList[flagCount++] = NVGContextFlag.FontNoAA;
746 vg = nvgCreateContext(flagList[0..flagCount]);
747 if (vg is null) {
748 conwriteln("Could not init nanovg.");
749 assert(0);
750 //sdwindow.close();
752 loadFonts(vg);
753 curImg = createCursorImage(vg);
754 curImgWhite = createCursorImage(vg, true);
755 fps = new PerfGraph("Frame Time", PerfGraph.Style.FPS, "ui");
756 } catch (Exception e) {
757 conwriteln("ERROR: ", e.msg);
758 concmd("quit");
759 return;
762 reformat();
764 refresh();
765 sdwindow.redrawOpenGlScene();
766 refresh();
769 sdwindow.windowResized = delegate (int w, int h) {
770 //conwriteln("w=", w, "; h=", h);
771 //if (w < MinWinWidth) w = MinWinWidth;
772 //if (h < MinWinHeight) h = MinWinHeight;
773 glViewport(0, 0, w, h);
774 GWidth = w;
775 GHeight = h;
776 textHeight = GHeight-8;
777 //reformat();
778 relayout();
779 refresh();
782 sdwindow.redrawOpenGlScene = delegate () {
783 if (isQuitRequested) return;
785 glconResize(GWidth/oglConScale, GHeight/oglConScale, oglConScale);
787 __gshared int cnt;
788 conwriteln("cnt=", cnt++);
791 //glClearColor(0, 0, 0, 0);
792 //glClearColor(0.18, 0.18, 0.18, 0);
793 glClearColor(colorBack.r, colorBack.g, colorBack.b, 0);
794 glClear(glNVGClearFlags|EliteModel.glClearFlags);
796 refreshed();
797 needRedrawFlag = (fps !is null && fpsVisible);
798 if (vg is null) return;
800 scope(exit) vg.releaseImages();
801 vg.beginFrame(GWidth, GHeight, 1);
802 drawIfs(vg);
803 // draw scrollbar
805 float curHeight = (laytext !is null ? topY : 0);
806 float th = (laytext !is null ? laytext.textHeight-textHeight : 0);
807 if (th <= 0) { curHeight = 0; th = 1; }
808 float sz = cast(float)(GHeight-4)/th;
809 if (sz > 1) sz = 1; else if (sz < 0.05) sz = 0.05;
810 int sx = (sbLeft ? 2 : GWidth-BND_SCROLLBAR_WIDTH-2);
811 vg.bndScrollSlider(sx, 2, BND_SCROLLBAR_WIDTH, GHeight-4, BND_DEFAULT, curHeight/th, sz);
813 if (laytext is null) {
814 if (shipModel is null) {
815 vg.beginPath();
816 vg.fillColor(colorText);
817 int drawY = (GHeight-textHeight)/2;
818 vg.intersectScissor((sbLeft ? 2+BND_SCROLLBAR_WIDTH+2 : 4), drawY, GWidth-4-2-BND_SCROLLBAR_WIDTH-2, textHeight);
819 vg.fontFaceId(textFont);
820 vg.fontSize(fsizeText);
821 vg.textAlign(NVGTextAlign.H.Center, NVGTextAlign.V.Middle);
822 vg.text(GWidth/2, GHeight/2, "REFORMATTING");
823 vg.fill();
826 // draw text page
827 int markerY = -666;
828 if (laytext !is null && laytext.lineCount) {
829 vg.beginPath();
830 vg.fillColor(colorText);
831 int drawY = startY;
832 vg.intersectScissor((sbLeft ? 2+BND_SCROLLBAR_WIDTH+2 : 4), drawY, GWidth-4-2-BND_SCROLLBAR_WIDTH-2, textHeight);
833 //FIXME: not GHeight!
834 int lidx = laytext.findLineAtY(topY);
835 if (lidx >= 0 && lidx < laytext.lineCount) {
836 drawY -= topY-laytext.line(lidx).y;
837 vg.textAlign(NVGTextAlign.H.Left, NVGTextAlign.V.Baseline);
838 LayFontStyle lastStyle;
839 int startx = startX;
840 bool setColor = true;
841 while (lidx < laytext.lineCount && drawY < GHeight) {
842 auto ln = laytext.line(lidx);
843 foreach (ref LayWord w; laytext.lineWords(lidx)) {
844 if (lastStyle != w.style || setColor) {
845 if (w.style.fontface != lastStyle.fontface) vg.fontFace(laytext.fontFace(w.style.fontface));
846 vg.fontSize(w.style.fontsize);
847 auto c = NVGColor(w.style.color);
848 vg.fillColor(c);
849 //vg.strokeColor(c);
850 lastStyle = w.style;
851 setColor = false;
853 // line highlighting
854 if (newYFade && newYLine == lidx) vg.fillColor(nvgLerpRGBA(colorText, colorTextHi, newYAlpha));
855 auto oid = w.objectIdx;
856 if (oid >= 0) {
857 vg.fill();
858 laytext.objectAtIndex(oid).draw(vg, startx+w.x, drawY+ln.h+ln.desc);
859 vg.beginPath();
860 } else {
861 vg.text(startx+w.x, drawY+ln.h+ln.desc, laytext.wordText(w));
863 //TODO: draw lines over whitespace
864 if (lastStyle.underline) vg.rect(startx+w.x, drawY+ln.h+ln.desc+1, w.w, 1);
865 if (lastStyle.strike) vg.rect(startx+w.x, drawY+ln.h+ln.desc-w.asc/3, w.w, 2);
866 if (lastStyle.overline) vg.rect(startx+w.x, drawY+ln.h+ln.desc-w.asc-1, w.w, 1);
867 version(debug_draw) {
868 vg.fill();
869 vg.beginPath();
870 vg.strokeWidth(1);
871 vg.strokeColor(nvgRGB(0, 0, 255));
872 vg.rect(startx+w.x, drawY, w.w, w.h);
873 vg.stroke();
874 vg.beginPath();
876 if (newYFade && newYLine == lidx) vg.fillColor(NVGColor(lastStyle.color));
878 if (newYFade && newYLine == lidx) markerY = drawY;
879 drawY += ln.h;
880 ++lidx;
883 vg.fill();
885 // draw scroll marker
886 if (markerY != -666) {
887 vg.beginPath();
888 vg.fillColor(NVGColor(0.3f, 0.3f, 0.3f, newYAlpha));
889 vg.rect(startX, markerY, GWidth, 2);
890 vg.fill();
892 // dim text
893 if (!showShip) {
894 if (colorDim.a != 1) {
895 //vg.scissor(0, 0, GWidth, GHeight);
896 vg.resetScissor;
897 vg.beginPath();
898 vg.fillColor(colorDim);
899 vg.rect(0, 0, GWidth, GHeight);
900 vg.fill();
903 // dim more if menu is active
904 if (inMenu || showShip || formatWorks != 0) {
905 //vg.scissor(0, 0, GWidth, GHeight);
906 vg.resetScissor;
907 vg.beginPath();
908 //vg.globalAlpha(0.5);
909 vg.fillColor(nvgRGBA(0, 0, 0, (showShip || formatWorks != 0 ? 127 : 64)));
910 vg.rect(0, 0, GWidth, GHeight);
911 vg.fill();
913 if (shipModel !is null) {
914 vg.endFrame();
915 float zz = shipModel.bbox[1].z-shipModel.bbox[0].z;
916 zz += 10;
917 lightsClear();
919 lightAdd(
920 0, 60, 60,
921 1.0, 0.0, 0.0
924 lightAdd(
925 //0, 0, -60,
926 0, 0, -zz,
927 1.0, 1.0, 1.0
929 drawModel(shipAngle, shipModel);
930 vg.beginFrame(GWidth, GHeight, 1);
931 drawShipName();
932 //vg.endFrame();
934 if (formatWorks == 0) {
935 if (inMenu) {
936 //vg.beginFrame(GWidth, GHeight, 1);
937 //vg.scissor(0, 0, GWidth, GHeight);
938 vg.resetScissor;
939 currPopup.draw();
940 //vg.endFrame();
943 if (fps !is null && fpsVisible) {
944 //vg.beginFrame(GWidth, GHeight, 1);
945 //vg.scissor(0, 0, GWidth, GHeight);
946 vg.resetScissor;
947 fps.render(vg, GWidth-fps.width-4, GHeight-fps.height-4);
948 //vg.endFrame();
950 if (inGalaxyMap) drawGalaxy(vg);
951 // mouse cursor
952 if (curImg.valid && !mouseHidden) {
953 int w, h;
954 //vg.beginFrame(GWidth, GHeight, 1);
955 vg.beginPath();
956 //vg.scissor(0, 0, GWidth, GHeight);
957 vg.resetScissor;
958 vg.imageSize(curImg, w, h);
959 if (mouseFadingAway) {
960 mouseAlpha -= 0.1;
961 if (mouseAlpha <= 0) { mouseFadingAway = false; mouseHidden = true; }
962 } else {
963 mouseAlpha = 1.0f;
965 vg.globalAlpha(mouseAlpha);
966 if (!mouseHigh) {
967 vg.fillPaint(vg.imagePattern(mouseX, mouseY, w, h, 0, curImg, 1));
968 } else {
969 vg.fillPaint(vg.imagePattern(mouseX, mouseY, w, h, 0, curImgWhite, 1));
971 vg.rect(mouseX, mouseY, w, h);
972 vg.fill();
974 if (mouseHigh) {
975 vg.beginPath();
976 vg.fillPaint(vg.imagePattern(mouseX, mouseY, w, h, 0, curImgWhite, 0.4));
977 vg.rect(mouseX, mouseY, w, h);
978 vg.fill();
981 //vg.endFrame();
983 vg.endFrame();
984 glconDraw();
987 void processThreads () {
988 ReformatWorkComplete wd;
989 for (;;) {
990 bool workDone = false;
991 auto res = receiveTimeout(Duration.zero,
992 (QuitWork w) {
993 formatWorks = -1;
995 (ReformatWorkComplete w) {
996 wd = w;
997 workDone = true;
1000 if (!res) { assert(!workDone); break; }
1001 if (workDone) { workDone = false; formatComplete(wd); }
1005 auto lastTimerEventTime = MonoTime.currTime;
1006 bool somethingVisible = true;
1008 sdwindow.visibilityChanged = delegate (bool vis) {
1009 //import core.stdc.stdio; printf("VISCHANGED: %s\n", (vis ? "tan" : "ona").ptr);
1010 somethingVisible = vis;
1013 conRegVar!fpsVisible("r_fps", "show fps indicator", (self, valstr) { refresh(); });
1014 conRegVar!inGalaxyMap("r_galaxymap", "show Elite galaxy map", (self, valstr) { refresh(); });
1016 conRegVar!interAllowed("r_interference", "show interference", (self, valstr) { refresh(); });
1017 conRegVar!sbLeft("r_sbleft", "show scrollbar at the left side", (self, valstr) { refresh(); });
1019 conRegVar!showShip("r_showship", "show Elite ship", (self, valstr) {
1020 if (eliteShipFiles.length == 0) return false;
1021 return true;
1023 (self, valstr) {
1024 if (showShip) ensureShipModel(); else freeShipModel();
1025 refresh();
1029 conRegFunc!(() {
1030 if (currPopup !is null) {
1031 currPopup.destroy;
1032 currPopup = null;
1033 freeShipModel();
1034 refresh();
1036 onPopupSelect = null;
1037 })("menu_close", "close current popup menu");
1039 conRegFunc!(() {
1040 if (formatWorks == 0 && !showShip && !inGalaxyMap) {
1041 currPopup.destroy;
1042 currPopup = null;
1043 ensureShipModel();
1044 createSectionMenu();
1045 refresh();
1047 })("menu_section", "show section menu");
1049 conRegFunc!(() {
1050 if (formatWorks == 0 && !showShip && !inGalaxyMap) {
1051 currPopup.destroy;
1052 currPopup = null;
1053 ensureShipModel();
1054 createRecentMenu();
1055 refresh();
1057 })("menu_recent", "show recent menu");
1059 sdwindow.eventLoop(1000/34,
1060 delegate () {
1061 processThreads();
1062 if (sdwindow.closed) return;
1063 conProcessQueue();
1064 if (isQuitRequested) { closeWindow(); return; }
1065 auto ctt = MonoTime.currTime;
1068 auto spass = (ctt-lastTimerEventTime).total!"msecs";
1069 //if (spass >= 30) { import core.stdc.stdio; printf("WARNING: too long frame time: %u\n", cast(uint)spass); }
1070 //{ import core.stdc.stdio; printf("FRAME TIME: %u\n", cast(uint)spass); }
1071 lastTimerEventTime = ctt;
1072 // update FPS timer
1073 prevt = curt;
1074 //curt = MonoTime.currTime;
1075 curt = ctt;
1076 //auto secs = cast(double)((curt-stt).total!"msecs")/1000.0;
1077 auto dt = cast(double)((curt-prevt).total!"msecs")/1000.0;
1078 if (fps !is null) fps.update(dt);
1081 // smooth scrolling
1082 if (formatWorks == 0) {
1083 enum Delta = 92*2;
1084 if (toMove != 0) {
1085 import std.math : abs;
1086 immutable int sign = (toMove < 0 ? -1 : 1);
1087 // change speed
1088 if (arrowSpeed == 0) arrowSpeed = 16;
1089 if (abs(toMove) <= arrowSpeed) {
1090 arrowSpeed /= 2;
1091 if (arrowSpeed < 4) arrowSpeed = 4;
1092 } else {
1093 arrowSpeed *= 2;
1094 if (arrowSpeed > Delta) arrowSpeed = Delta;
1096 // calc move distance
1097 int sc = arrowSpeed;
1098 if (sc > abs(toMove)) sc = abs(toMove);
1099 hardScrollBy(sc*sign);
1100 toMove -= sc*sign;
1101 if (toMove == 0) arrowSpeed = 0;
1102 nextFadeTime = ctt+500.msecs;
1103 refresh();
1104 } else if (arrowDir) {
1105 if ((arrowDir < 0 && arrowSpeed > 0) || (arrowDir > 0 && arrowSpeed < 0)) arrowSpeed += arrowDir*4;
1106 arrowSpeed += arrowDir*2;
1107 if (arrowSpeed < -64) arrowSpeed = -64; else if (arrowSpeed > 64) arrowSpeed = 64;
1108 hardScrollBy(arrowSpeed);
1109 refresh();
1110 } else if (arrowSpeed != 0) {
1111 if (arrowSpeed < 0) {
1112 if ((arrowSpeed += 4) > 0) arrowSpeed = 0;
1113 } else {
1114 if ((arrowSpeed -= 4) < 0) arrowSpeed = 0;
1116 if (arrowSpeed) {
1117 hardScrollBy(arrowSpeed);
1118 refresh();
1121 // highlight fading
1122 if (newYFade) {
1123 if (ctt >= nextFadeTime) {
1124 if ((newYAlpha -= 0.1) <= 0) {
1125 newYFade = false;
1126 } else {
1127 nextFadeTime = ctt+25.msecs;
1129 refresh();
1133 // interference processing
1134 if (ctt >= nextIfTime) {
1135 import std.random : uniform;
1136 if (uniform!"[]"(0, 100) >= 50) { if (addIf()) refresh(); }
1137 nextIfTime += (uniform!"[]"(50, 1500)).msecs;
1139 if (processIfs()) refresh();
1140 // ship rotation
1141 if (shipModel !is null) {
1142 shipAngle -= 1;
1143 if (shipAngle < 359) shipAngle += 360;
1144 refresh();
1146 // mouse autohide
1147 if (!mouseFadingAway) {
1148 if (!mouseHidden && !mouseHigh) {
1149 if ((ctt-lastMMove).total!"msecs" > 2500) {
1150 //mouseHidden = true;
1151 mouseFadingAway = true;
1152 mouseAlpha = 1.0f;
1153 refresh();
1157 if (somethingVisible) {
1158 // sadly, to keep framerate we have to redraw each frame, or driver will throw us out of the ship
1159 if (/*needRedraw*/true) sdwindow.redrawOpenGlSceneNow();
1160 } else {
1161 refresh();
1163 doSaveState();
1164 // load new book?
1165 if (newBookFileName.length && formatWorks == 0 && vg !is null) {
1166 doSaveState(true); // forced state save
1167 closeMenu();
1168 ensureShipModel();
1169 loadAndFormat(newBookFileName);
1170 newBookFileName = null;
1171 sdwindow.redrawOpenGlSceneNow();
1172 //refresh();
1175 delegate (KeyEvent event) {
1176 if (sdwindow.closed) return;
1177 if (glconKeyEvent(event)) return;
1178 if (event.key == Key.PadEnter) event.key = Key.Enter;
1179 if ((event.modifierState&ModifierState.numLock) == 0) {
1180 switch (event.key) {
1181 case Key.Pad0: event.key = Key.Insert; break;
1182 case Key.PadDot: event.key = Key.Delete; break;
1183 case Key.Pad1: event.key = Key.End; break;
1184 case Key.Pad2: event.key = Key.Down; break;
1185 case Key.Pad3: event.key = Key.PageDown; break;
1186 case Key.Pad4: event.key = Key.Left; break;
1187 case Key.Pad6: event.key = Key.Right; break;
1188 case Key.Pad7: event.key = Key.Home; break;
1189 case Key.Pad8: event.key = Key.Up; break;
1190 case Key.Pad9: event.key = Key.PageUp; break;
1191 //case Key.PadEnter: event.key = Key.Enter; break;
1192 default:
1195 if (controlKey(event)) return;
1196 if (menuKey(event)) return;
1197 if (readerKey(event)) return;
1199 delegate (MouseEvent event) {
1200 if (sdwindow.closed) return;
1202 int linkAt (int msx, int msy) {
1203 if (laytext !is null && bookmeta !is null) {
1204 if (msx >= startX && msx <= endX && msy >= startY && msy <= endY) {
1205 auto widx = laytext.wordAtXY(msx-startX, topY+msy-startY);
1206 if (widx >= 0) {
1207 //conwriteln("word at (", msx-startX, ",", msy-startY, "): ", widx);
1208 auto w = laytext.wordByIndex(widx);
1209 while (widx >= 0) {
1210 //conwriteln("word #", widx, "; href=", w.style.href);
1211 if (!w.style.href) break;
1212 if (auto hr = w.wordNum in bookmeta.hrefs) {
1213 dstring href = hr.name;
1214 if (href.length > 1 && href[0] == '#') {
1215 href = href[1..$];
1216 foreach (const ref id; bookmeta.ids) {
1217 if (id.name == href) {
1218 //pushPosition();
1219 //goTo(id.wordidx);
1220 return id.wordidx;
1223 //conwriteln("id '", hr.name, "' not found!");
1224 return -1;
1227 --widx;
1228 --w;
1233 return -1;
1236 lastMMove = MonoTime.currTime;
1237 if (mouseHidden || mouseFadingAway) {
1238 mouseHidden = false;
1239 mouseFadingAway = false;
1240 mouseAlpha = 1.0f;
1241 refresh();
1243 if (mouseX != event.x || mouseY != event.y) {
1244 mouseX = event.x;
1245 mouseY = event.y;
1246 refresh();
1248 if (!menuMouse(event) && !showShip) {
1249 if (event.type == MouseEventType.buttonPressed) {
1250 switch (event.button) {
1251 case MouseButton.wheelUp: hardScrollBy(-42); break;
1252 case MouseButton.wheelDown: hardScrollBy(42); break;
1253 case MouseButton.left:
1254 auto wid = linkAt(event.x, event.y);
1255 if (wid >= 0) {
1256 pushPosition();
1257 goTo(wid);
1259 break;
1260 case MouseButton.right:
1261 popPosition();
1262 break;
1263 default:
1267 mouseHigh = (linkAt(event.x, event.y) >= 0);
1269 delegate (dchar ch) {
1270 if (sdwindow.closed) return;
1271 if (glconCharEvent(ch)) return;
1272 if (menuChar(ch)) return;
1273 //if (ch == '`') { concmd("r_console tan"); return; }
1276 closeWindow();
1278 childTid.send(QuitWork());
1279 while (formatWorks >= 0) processThreads();
1283 // ////////////////////////////////////////////////////////////////////////// //
1284 struct FlibustaUrl {
1285 string fullUrl; // onion
1286 string host;
1287 string id;
1289 this (const(char)[] aurl) {
1290 import std.format : format;
1291 aurl = aurl.xstrip();
1292 auto flibustaRE = regex(`^(?:https?://)?(?:www\.)?flibusta\.[^/]+/b/(\d+)`);
1293 auto ct = aurl.matchFirst(flibustaRE);
1294 if (!ct.empty) {
1295 fullUrl = "http://flibustahezeous3.onion/b/%s/fb2".format(ct[1]);
1296 id = ct[1].idup;
1297 host = "flibustahezeous3.onion";
1298 } else {
1299 // add protocol
1300 auto protoRE = regex(`^([^:/]+):`);
1301 auto protoMt = aurl.matchFirst(protoRE);
1302 if (protoMt.empty) fullUrl = "http:%s%s".format((aurl[0] == '/' ? "" : "//"), aurl);
1303 // add host
1304 auto hostRE = regex(`^(?:[^:/]+)://([^/]+)`);
1305 auto hostMt = fullUrl.matchFirst(hostRE);
1306 if (hostMt.empty) { fullUrl = null; return; }
1307 host = hostMt[1].idup;
1311 @property bool valid () const pure nothrow @safe @nogc { pragma(inline, true); return (fullUrl.length > 0); }
1312 @property bool isFlibusta () const pure nothrow @safe @nogc { pragma(inline, true); return (id.length > 0); }
1313 @property bool isOnion () const pure nothrow @safe @nogc { pragma(inline, true); return host.endsWithCI(".onion"); }
1317 // ////////////////////////////////////////////////////////////////////////// //
1318 __gshared SDBM dbCache = null;
1321 void dbOpenCache () {
1322 if (dbCache is null) {
1323 import std.file : exists, mkdirRecurse;
1324 import std.path;
1325 string xfn = buildPath(RcDir, "cache");
1326 xfn.mkdirRecurse();
1327 xfn = buildPath(xfn, ".cache.db");
1328 dbCache = new SDBM(xfn, SDBM.WRITER|SDBM.CREAT|SDBM.NOLCK);
1333 char[] dbBuildNamePathById (char[] dest, const(char)[] id) {
1334 import core.stdc.stdio : snprintf;
1335 assert(id.length > 0);
1336 assert(dest.length > 0);
1337 auto len = snprintf(dest.ptr, dest.length, "/files/%.*s/name", cast(uint)id.length, id.ptr);
1338 if (len < 1 || len >= dest.length) assert(0, "out of destination buffer");
1339 return dest[0..len];
1343 string dbFindInCache() (in auto ref FlibustaUrl furl) {
1344 if (!furl.valid) return null;
1345 dbOpenCache();
1346 char[128] keybuf = void;
1347 auto dbpath = dbBuildNamePathById(keybuf[], furl.id);
1348 string fname = dbCache.get!string(dbpath);
1349 if (fname.length == 0) return null;
1350 import std.file : exists;
1351 try {
1352 if (fname.exists) return fname;
1353 } catch (Exception e) {}
1354 // no such file, remove it from database
1355 dbCache.del(dbpath);
1356 return null;
1360 void dbPutToCache() (in auto ref FlibustaUrl furl, const(char)[] fname) {
1361 if (!furl.valid || fname.length == 0) return;
1362 dbOpenCache();
1363 char[128] keybuf = void;
1364 dbCache.put(dbBuildNamePathById(keybuf[], furl.id), fname);
1368 void dbCloseCache () {
1369 if (dbCache is null) return;
1370 scope(exit) {
1371 delete dbCache;
1372 import core.memory : GC;
1373 GC.collect();
1374 GC.minimize();
1379 void dbCleanupCache () {
1380 dbOpenCache();
1381 bool[string] dead;
1382 auto xre = regex(`^/files/(.+)/name$`);
1383 dbCache.itInit();
1384 nextkey: for (;;) {
1385 auto key = dbCache.itNext();
1386 if (key is null) break;
1387 //writeln("[", key, "]");
1388 auto mt = key.matchFirst(xre);
1389 if (mt.empty) continue;
1390 auto fname = dbCache.get!string(key);
1391 if (fname.length != 0) {
1392 try {
1393 import std.file : exists;
1394 if (fname.exists) continue nextkey;
1395 } catch (Exception e) {}
1397 dead[key.idup] = true; // oops
1399 foreach (string k; dead.byKey) {
1400 //writeln("deleting stale cache record for '", k, "'");
1401 dbCache.del(k);
1403 dead.clear();
1407 // ////////////////////////////////////////////////////////////////////////// //
1408 // returns file name
1409 string fileDown() (in auto ref FlibustaUrl furl) {
1410 if (!furl.valid || !furl.isFlibusta) return null;
1412 string cachedFName = dbFindInCache(furl);
1413 if (cachedFName.length) return cachedFName;
1415 // content-disposition: attachment; filename="Divov_Sled-zombi.1lzb6Q.96382.fb2.zip"
1416 auto cdRE0 = regex(`^\s*attachment\s*;\s*filename="(.+?)"`, "i");
1417 auto cdRE1 = regex(`^\s*attachment\s*;\s*filename=([^;]+?)`, "i");
1419 auto http = HTTP(furl.host);
1420 http.method = HTTP.Method.get;
1421 http.url = furl.fullUrl;
1423 string fname = null;
1424 string tmpfname = null;
1425 string fnps = null;
1426 bool alreadyDowned = false;
1427 VFile fo;
1429 http.onReceiveHeader = delegate (in char[] key, in char[] value) {
1430 //writeln(key ~ ": " ~ value);
1431 if (key.strEquCI("content-disposition")) {
1432 auto ct = value.matchFirst(cdRE0);
1433 if (ct.empty) ct = value.matchFirst(cdRE1);
1434 if (ct[1].length) {
1435 auto fnp = ct[1].xstrip;
1436 auto lslpos = fnp.lastIndexOf('/');
1437 if (lslpos > 0) fnp = fnp[lslpos+1..$];
1438 if (fnp.length == 0) {
1439 fname = null;
1440 } else {
1441 import std.file : exists, mkdirRecurse;
1442 import std.path;
1443 string xfn = buildPath(RcDir, "cache");
1444 xfn.mkdirRecurse();
1445 char[] xxname;
1446 xxname.reserve(fnp.length);
1447 foreach (char ch; fnp) {
1448 if (ch <= ' ' || ch == 127) ch = '_';
1449 xxname ~= ch;
1451 fnps = cast(string)xxname; // it is safe to cast here
1452 fname = buildPath(xfn, fnps);
1453 tmpfname = fname~".down.part";
1455 if (fname.exists) {
1456 alreadyDowned = true;
1457 throw new Exception("already here");
1458 //throw new FileAlreadyDowned("already here");
1461 //write("\r", fnp, " [", furl.fullUrl, "]\e[K");
1467 http.onReceive = delegate (ubyte[] data) {
1468 if (!fo.isOpen) {
1469 if (fname.length == 0) throw new Exception("no file name found in headers");
1470 //writeln(" downloading to ", fname);
1471 fo = VFile(tmpfname, "w");
1473 fo.rawWriteExact(data);
1474 return data.length;
1477 MonoTime lastProgTime = MonoTime.zero;
1478 enum BarLength = 68;
1479 bool doProgUpdate = true;
1480 char[1024] buf = void;
1481 int oldDots = -1, oldPrc = -1;
1482 uint bufpos = 0;
1483 int stickPos = 1;
1484 immutable string stickStr = `|/-\`;
1486 // will set `doProgUpdate`, and update `oldXXX`
1487 void buildPBar (usize dlTotal, usize dlNow) {
1488 void put (const(char)[] s...) nothrow {
1489 if (s.length == 0) return;
1490 if (bufpos >= buf.length) return;
1491 int left = cast(int)buf.length-bufpos;
1492 if (s.length > left) s = s[0..left];
1493 assert(s.length > 0);
1494 import core.stdc.string : memcpy;
1495 memcpy(buf.ptr+bufpos, s.ptr, s.length);
1496 bufpos += cast(int)s.length;
1498 void putprc (int prc) {
1499 if (prc < 0) prc = 0; else if (prc > 100) prc = 100;
1500 if (bufpos >= buf.length || buf.length-bufpos < 5) return; // oops
1501 import core.stdc.stdio;
1502 bufpos += cast(int)snprintf(buf.ptr+bufpos, 5, "%3d%%", prc);
1504 void putCommaNum (usize n, usize max=0) {
1505 char[128] buf = void;
1506 if (max < n) {
1507 put(intWithCommas(buf[], n));
1508 } else {
1509 auto len = intWithCommas(buf[], max).length;
1510 auto pt = intWithCommas(buf[], n);
1511 while (len-- > pt.length) put(" ");
1512 put(pt);
1515 bufpos = 0;
1516 put("\r");
1517 put(fnps);
1518 put(" [");
1519 auto barpos = bufpos;
1520 foreach (immutable _; 0..BarLength) put(" ");
1521 put("]");
1522 if (dlTotal > 0) {
1523 int prc = cast(int)(cast(ulong)100*dlNow/dlTotal);
1524 if (prc < 0) prc = 0; else if (prc > 100) prc = 100;
1525 int dots = cast(int)(cast(ulong)BarLength*dlNow/dlTotal);
1526 if (dots < 0) dots = 0; else if (dots > BarLength) dots = BarLength;
1527 if (prc != oldPrc || dots != oldDots) {
1528 doProgUpdate = true;
1529 oldPrc = prc;
1530 oldDots = dots;
1532 put(" [");
1533 putCommaNum(dlNow, dlTotal);
1534 put("/");
1535 putCommaNum(dlTotal);
1536 put("] ");
1537 putprc(prc);
1538 // dots
1539 foreach (immutable dp; 0..dots) if (barpos+dp < buf.length) buf[barpos+dp] = '.';
1540 } else {
1541 put("?\e[K");
1542 if (oldDots != -1 || oldPrc != -1) doProgUpdate = true;
1543 oldDots = -1;
1544 oldPrc = -1;
1548 http.onProgress = delegate (usize dltotal, usize dlnow, usize ultotal, usize ulnow) {
1549 //writeln("Progress ", dltotal, ", ", dlnow, ", ", ultotal, ", ", ulnow);
1550 if (fname.length == 0) {
1551 auto ct = MonoTime.currTime;
1552 if ((ct-lastProgTime).total!"msecs" >= 100) {
1553 write("\x08", stickStr[stickPos]);
1554 stickPos = (stickPos+1)%cast(int)stickStr.length;
1555 lastProgTime = ct;
1557 return 0;
1559 buildPBar(dltotal, dlnow);
1560 if (doProgUpdate) { write("\e[?7l", buf[0..bufpos], "\e[K\e[?7h"); doProgUpdate = false; }
1561 //if (dltotal == 0) return 0;
1562 //auto ct = MonoTime.currTime;
1563 //if ((ct-lastProgTime).total!"msecs" < 1000) return 0;
1564 //lastProgTime = ct;
1565 //writef("\r%s [%s] -- [%s/%s] %3u%%\e[K", fnps, host, intWithCommas(dlnow), intWithCommas(dltotal), 100UL*dlnow/dltotal);
1566 return 0;
1569 if (furl.isOnion) {
1570 http.proxyType = HTTP.CurlProxy.socks5_hostname;
1571 http.proxy = "127.0.0.1";
1572 http.proxyPort = 9050;
1575 try {
1576 //write("downloading from [", host, "]: ", realUrl, " ... ");
1577 write("downloading from Flibusta: ", furl.fullUrl, " ... ", stickStr[0]);
1578 http.perform();
1579 if (fo.isOpen) {
1580 buildPBar(cast(uint)fo.size, cast(uint)fo.size);
1581 } else {
1582 buildPBar(1, 1);
1584 writeln(buf[0..bufpos], "\e[K");
1585 //write("\r\e[K");
1586 } catch (Exception e) {
1587 if (/*cast(FileAlreadyDowned)e*/alreadyDowned) {
1588 write("\r", fname, " already downloaded.\e[K");
1589 return fname; // already here
1591 if (tmpfname.length) {
1592 import std.exception : collectException;
1593 import std.file : remove;
1594 collectException(tmpfname.remove);
1596 throw e;
1599 if (fo.isOpen) {
1600 // something was downloaded, rename it
1601 import std.file : rename;
1602 fo.close();
1603 rename(tmpfname, fname);
1604 dbPutToCache(furl, fname);
1605 return fname;
1608 return null;
1612 // ////////////////////////////////////////////////////////////////////////// //
1613 void main (string[] args) {
1614 import std.path;
1616 conRegVar!oglConScale(1, 4, "r_conscale", "console scale");
1618 conProcessQueue(256*1024); // load config
1619 conProcessArgs!true(args);
1620 conProcessQueue(256*1024);
1622 universe = Galaxy(0);
1624 if (args.length == 1) {
1625 try {
1626 string lnn;
1627 foreach (string line; VFile(buildPath(RcDir, ".lastfile")).byLineCopy) {
1628 if (!line.isComment) lnn = line;
1630 if (lnn.length) args ~= lnn;
1631 } catch (Exception) {}
1632 } else {
1633 if (args.length != 2) assert(0, "invalid number of arguments");
1634 auto furl = FlibustaUrl(args[1]);
1635 if (furl.valid && furl.isFlibusta) {
1636 dbCleanupCache();
1637 scope(exit) dbCloseCache();
1638 string fn = fileDown(furl);
1639 if (fn.length == 0) assert(0, "can't download file");
1640 args[1] = fn;
1644 if (args.length == 1) assert(0, "no filename");
1646 readConfig();
1648 bookFileName = args[1];
1649 run();