better parser for broken quoted encoding (starting dot)
[chiroptera.git] / chiroptera.d
blob493dccd5b4f08eb60fc1ec98a21f549cd6a3aafa
1 /* E-Mail Client
2 * coded by Ketmar // Invisible Vector <ketmar@ketmar.no-ip.org>
3 * Understanding is not required. Only obedience.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 3 of the License ONLY.
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 chiroptera /*is aliced*/;
19 //version = test_round_rect;
20 version = article_can_into_html;
22 import core.atomic;
23 import core.time;
24 import std.concurrency;
26 //import arsd.email;
27 //import arsd.htmltotext;
28 import arsd.simpledisplay;
29 import arsd.png;
31 version(article_can_into_html) {
32 import arsd.characterencodings;
33 import arsd.color;
34 import arsd.dom;
35 import arsd.htmltotext;
38 import iv.alice;
39 import iv.bclamp;
40 import iv.encoding;
41 import iv.cmdcon;
42 import iv.cmdcongl;
43 import iv.lockfile;
44 import iv.sdpyutil;
45 import iv.strex;
46 import iv.sq3;
47 import iv.timer : DurTimer = Timer;
48 import iv.utfutil;
49 import iv.vfs.io;
50 import iv.vfs.util;
52 import iv.egra;
54 import chibackend;
55 import chibackend.net;
57 import chievents;
58 import dialogs;
59 import receiver;
62 // ////////////////////////////////////////////////////////////////////////// //
63 static immutable string ChiroStyle = `
64 MainPaneWindow {
65 //// group list ////
66 grouplist-divline: white;
67 grouplist-dots: rgb(80, 80, 80);
69 grouplist-back: #222;
70 // group with unread messages
71 grouplist-unread-text: #0ff;
72 // normal group
73 grouplist-normal-text: rgb(255, 187, 0);
74 grouplist-normal-child-text: rgb(225, 97, 0);
75 // spam group
76 grouplist-spam-text: #800;
77 // main accounts group
78 grouplist-accounts-text: rgb(220, 220, 0);
79 grouplist-accounts-child-text: rgb(160, 160, 250);
80 // account inbox group
81 grouplist-inbox-text: rgb(90, 90, 180);
84 grouplist-cursor-back: #088;
85 // group with unread messages
86 grouplist-cursor-unread-text: #0ff;
87 // normal group
88 grouplist-cursor-normal-text: rgb(255, 187, 0);
89 grouplist-cursor-normal-child-text: rgb(225, 97, 0);
90 // spam group
91 grouplist-cursor-spam-text: #800;
92 // main accounts group
93 grouplist-cursor-accounts-text: rgb(220, 220, 0);
94 grouplist-cursor-accounts-child-text: rgb(160, 160, 250);
95 // account inbox group
96 grouplist-cursor-inbox-text: rgb(90, 90, 180);
98 grouplist-cursor-outline: black;
100 //// thread list ////
101 threadlist-divline: white;
102 threadlist-back: #222;
103 threadlist-dots: #444;
105 threadlist-normal-back: transparent;
106 threadlist-normal-dots: #444;
107 threadlist-normal-subj-text: rgb(215, 87, 0);
108 threadlist-normal-from-text: rgb(215, 87, 0);
109 threadlist-normal-mail-text: rgb(155, 27, 0);
110 threadlist-normal-time-text: rgb(215, 87, 0);
111 threadlist-normal-strike-line: transparent;
113 threadlist-unread-back: transparent;
114 threadlist-unread-dots: #444;
115 threadlist-unread-subj-text: white;
116 threadlist-unread-from-text: white;
117 threadlist-unread-mail-text: yellow;
118 threadlist-unread-time-text: white;
119 threadlist-unread-strike-line: transparent;
121 threadlist-soft-del-back: transparent;
122 threadlist-soft-del-dots: #444;
123 threadlist-soft-del-subj-text: #800;
124 threadlist-soft-del-from-text: #800;
125 threadlist-soft-del-mail-text: #800;
126 threadlist-soft-del-time-text: #800;
127 threadlist-soft-del-strike-line: #800;
129 threadlist-hard-del-back: transparent;
130 threadlist-hard-del-dots: #444;
131 threadlist-hard-del-subj-text: red;
132 threadlist-hard-del-from-text: red;
133 threadlist-hard-del-mail-text: red;
134 threadlist-hard-del-time-text: red;
135 threadlist-hard-del-strike-line: red;
137 threadlist-twit-back: transparent;
138 threadlist-twit-dots: #444;
139 threadlist-twit-subj-text: #400;
140 threadlist-twit-from-text: #400;
141 threadlist-twit-mail-text: #400;
142 threadlist-twit-time-text: #400;
143 threadlist-twit-strike-line: transparent;
145 threadlist-cursor-normal-back: #088;
146 threadlist-cursor-dots: #444;
147 threadlist-cursor-normal-subj-text: rgb(215, 87, 0);
148 threadlist-cursor-normal-from-text: rgb(215, 87, 0);
149 threadlist-cursor-normal-mail-text: rgb(155, 27, 0);
150 threadlist-cursor-normal-time-text: rgb(215, 87, 0);
151 threadlist-cursor-normal-strike-line: transparent;
152 threadlist-cursor-normal-outline: black;
154 threadlist-cursor-unread-back: #088;
155 threadlist-cursor-unread-dots: #444;
156 threadlist-cursor-unread-subj-text: white;
157 threadlist-cursor-unread-from-text: white;
158 threadlist-cursor-unread-mail-text: yellow;
159 threadlist-cursor-unread-time-text: white;
160 threadlist-cursor-unread-strike-line: transparent;
161 threadlist-cursor-unread-outline: black;
163 threadlist-cursor-soft-del-back: #066;
164 threadlist-cursor-soft-del-dots: #444;
165 threadlist-cursor-soft-del-subj-text: #800;
166 threadlist-cursor-soft-del-from-text: #800;
167 threadlist-cursor-soft-del-mail-text: #800;
168 threadlist-cursor-soft-del-time-text: #800;
169 threadlist-cursor-soft-del-strike-line: #800;
171 threadlist-cursor-hard-del-back: #066;
172 threadlist-cursor-hard-del-dots: #444;
173 threadlist-cursor-hard-del-subj-text: red;
174 threadlist-cursor-hard-del-from-text: red;
175 threadlist-cursor-hard-del-mail-text: red;
176 threadlist-cursor-hard-del-time-text: red;
177 threadlist-cursor-hard-del-strike-line: red;
179 threadlist-cursor-twit-back: #066;
180 threadlist-cursor-twit-dots: #444;
181 threadlist-cursor-twit-subj-text: #400;
182 threadlist-cursor-twit-from-text: #400;
183 threadlist-cursor-twit-mail-text: #400;
184 threadlist-cursor-twit-time-text: #400;
185 threadlist-cursor-twit-strike-line: #400;
188 //// message header ////
189 msg-header-back: rgb(20, 20, 20);
190 msg-header-from: #088;
191 msg-header-to: #088;
192 msg-header-subj: #088;
193 msg-header-date: #088;
194 msg-header-divline: #bbb;
197 //// message text ////
198 msg-text-back: rgb(37, 37, 37);
199 msg-text-text: rgb(174, 174, 174);
200 msg-text-quote0: #880;
201 msg-text-quote1: #088;
202 msg-text-link: rgb(0, 200, 200);
203 msg-text-html-sign: rgb(128, 0, 128);
205 msg-text-link-hover: rgb(0, 255, 255);
207 msg-text-link-pressed: rgb(255, 0, 255);
209 //// message text twit ////
210 //twit-shade: rgba(0, 0, 80, 127);
211 twit-shade: rgb(0, 0, 40);
212 twit-text: red;
213 twit-outline: black;
217 HintWindow {
218 frame: white;
219 title-back: white;
220 title-text: black;
222 back: rgb(0, 0, 80);
223 text: rgb(155, 155, 155);
227 MessageWindow {
228 frame: white;
229 title-back: white;
230 title-text: black;
232 back: rgb(0, 0, 80);
233 text: rgb(255, 255, 0);
234 bar-back: rgb(90, 90, 180);
235 back: red;
240 // ////////////////////////////////////////////////////////////////////////// //
241 private __gshared bool ChiroTimerExEnabled = false;
244 // ////////////////////////////////////////////////////////////////////////// //
245 public __gshared string mailRootDir = "/mnt/bigass/Mail";
248 shared static this () {
249 import core.stdc.stdlib : getenv;
250 const(char)* home = getenv("HOME");
251 if (home !is null && home[0] == '/' && home[1] && home[1] != '/') {
252 import std.string : fromStringz;
253 mailRootDir = home.fromStringz.idup;
254 if (mailRootDir.length == 0) assert(0, "wtf?!");
255 if (mailRootDir[$-1] != '/') mailRootDir ~= "/";
256 mailRootDir ~= "Mail";
261 // ////////////////////////////////////////////////////////////////////////// //
262 __gshared NotificationAreaIcon trayicon;
263 __gshared Image[6] trayimages;
264 __gshared MemoryImage[6] icons; // 0: normal
267 // ////////////////////////////////////////////////////////////////////////// //
268 // with tagid
269 struct ArticleId {
270 uint tagid = 0;
271 uint uid = 0;
273 bool valid () const nothrow @safe @nogc { pragma(inline, true); return (tagid && uid); }
274 void clear () nothrow @safe @nogc { pragma(inline, true); tagid = uid = 0; }
276 bool opEqual (const ref ArticleId other) const nothrow @safe @nogc {
277 pragma(inline, true);
278 return (valid && other.valid && tagid == other.tagid && uid == other.uid);
283 // ////////////////////////////////////////////////////////////////////////// //
284 static immutable ubyte[] iconsZipData = cast(immutable(ubyte)[])import("databin/icons.zip");
287 // ////////////////////////////////////////////////////////////////////////// //
288 struct MailReplacement {
289 string oldmail;
290 string newmail;
291 string newname;
294 __gshared MailReplacement[string] repmailreps;
297 // ////////////////////////////////////////////////////////////////////////// //
298 string getBrowserCommand (bool forceOpera) {
299 __gshared string browser;
300 if (forceOpera) return "opera";
301 if (browser.length == 0) {
302 import core.stdc.stdlib : getenv;
303 const(char)* evar = getenv("BROWSER");
304 if (evar !is null && evar[0]) {
305 import std.string : fromStringz;
306 browser = evar.fromStringz.idup;
307 } else {
308 browser = "opera";
311 return browser;
315 // ////////////////////////////////////////////////////////////////////////// //
317 private void setXStr (ref char[] dest, SQ3Text src) {
318 delete dest;
319 if (src.length == 0) return;
320 dest = new char[src.length];
321 dest[] = src[];
326 // ////////////////////////////////////////////////////////////////////////// //
327 class FolderInfo {
328 uint tagid; // 0 means "ephemeral"
329 DynStr name;
330 const(char)[] visname; // slice of the `name`
331 int depth;
332 uint unreadCount;
333 // used in rescanner;
334 bool seen;
336 ~this () nothrow @trusted @nogc { clear(); }
338 void clear () nothrow @trusted @nogc {
339 visname = null;
340 name.clear();
343 // ephemeral folders doesn't exist, they are here only for visual purposes
344 bool ephemeral () const nothrow @safe @nogc { pragma(inline, true); return (tagid == 0); }
346 void calcDepthVisName () {
347 depth = 0;
348 visname = name[0..$];
349 if (visname.length == 0 || visname == "/" || visname[0] == '#') return;
350 visname = visname[1..$];
351 foreach (immutable char ch; visname) if (ch == '/') ++depth;
352 auto spos = visname.lastIndexOf('/');
353 if (spos >= 0) visname = visname[spos+1..$];
356 static int findByFullName (const(char)[] aname) {
357 if (aname.length == 0) return -1;
358 foreach (immutable idx, const FolderInfo fi; folderList) {
359 if (fi.name == aname) return cast(int)idx;
361 return -1;
364 bool needEphemeral () const {
365 if (depth == 0) return false;
366 assert(name.length > 1 && name[0] == '/');
367 const(char)[] n = name[0..$];
368 while (n.length) {
369 if (findByFullName(n) < 0) return true;
370 auto spos = n.lastIndexOf('/');
371 if (spos <= 0) return false;
372 n = n[0..spos];
374 return false;
377 void createEphemerals () const {
378 if (depth == 0) return;
379 assert(name.length > 1 && name[0] == '/');
380 const(char)[] n = name[0..$];
381 while (n.length) {
382 auto spos = n.lastIndexOf('/');
383 if (spos <= 0) break;
384 n = n[0..spos];
385 //conwriteln(" n=<", n, ">; spos=", spos);
386 if (findByFullName(n) < 0) {
387 //conwriteln(" creating: '", n, "'");
388 //foreach (const FolderInfo nfi; folderList) conwriteln(" <", nfi.name, "> : <", nfi.visname, "> : ", nfi.depth);
389 FolderInfo newfi = new FolderInfo;
390 newfi.tagid = 0;
391 newfi.name = n;
392 newfi.unreadCount = 0;
393 newfi.seen = true;
394 newfi.calcDepthVisName();
395 folderList ~= newfi;
401 __gshared FolderInfo[] folderList;
402 __gshared uint folderDataVersion = uint.max;
405 //FIXME: make this faster
406 //FIXME: force-append account folders
407 // returns `true` if something was changed
408 bool rescanFolders () {
409 import std.conv : to;
410 bool res = false;
412 if (folderList.length != 0 && dbView.getDataVersion() == folderDataVersion) return false; // nothing to do here
414 bool needsort = false;
415 foreach (FolderInfo fi; folderList) fi.seen = false;
417 // unhide any folder tags with unread messages
418 static stmtUnhide = LazyStatement!"View"(`
419 UPDATE tagnames
421 hidden=0
422 WHERE
423 hidden=1 AND
424 (tag='#spam' OR (tag<>'' AND SUBSTR(tag, 1, 1)='/')) AND
425 EXISTS (SELECT uid FROM threads WHERE tagid=tagnames.tagid AND appearance=`~(cast(int)Appearance.Unread).to!string~`)
426 ;`);
427 stmtUnhide.st.doAll();
429 static auto stmtGet = LazyStatement!"View"(`
430 SELECT
431 tagid AS tagid
432 , tag AS name
433 FROM tagnames
434 WHERE
435 tag='#spam' OR
436 (hidden=0 AND tag<>'' AND SUBSTR(tag, 1, 1)='/')
437 ;`);
439 static auto stmtGetUnread = LazyStatement!"View"(`
440 SELECT
441 COUNT(uid) AS unread
442 FROM threads
443 WHERE tagid=:tagid AND appearance=`~(cast(int)Appearance.Unread).to!string~`
444 ;`);
446 foreach (auto row; stmtGet.st.range) {
447 bool append = true;
448 uint tagid = row.tagid!uint;
449 foreach (FolderInfo fi; folderList) {
450 if (fi.tagid == tagid) {
451 append = false;
452 fi.seen = true;
453 if (fi.name != row.name!SQ3Text) {
454 fi.name = row.name!SQ3Text;
455 fi.calcDepthVisName();
456 needsort = true;
458 break;
461 if (append) {
462 needsort = true;
463 FolderInfo newfi = new FolderInfo();
464 newfi.tagid = tagid;
465 newfi.name = row.name!SQ3Text;
466 newfi.unreadCount = 0;
467 newfi.seen = true;
468 newfi.calcDepthVisName();
469 folderList ~= newfi;
473 // remove unseen folders
474 for (usize f = 0; f < folderList.length; ) {
475 if (!folderList[f].seen && !folderList[f].ephemeral) {
476 needsort = true;
477 folderList[f].clear();
478 delete folderList[f];
479 foreach (immutable c; f+1..folderList.length) folderList[c-1] = folderList[c];
480 folderList[$-1] = null;
481 folderList.length -= 1;
482 } else {
483 ++f;
487 if (needsort) {
488 // remove all epemerals
489 for (usize f = 0; f < folderList.length; ) {
490 if (folderList[f].ephemeral) {
491 folderList[f].clear();
492 delete folderList[f];
493 foreach (immutable c; f+1..folderList.length) folderList[c-1] = folderList[c];
494 folderList[$-1] = null;
495 folderList.length -= 1;
496 } else {
497 ++f;
501 // readd all ephemerals
502 for (;;) {
503 bool again = false;
504 foreach (FolderInfo fi; folderList) {
505 if (fi.needEphemeral) {
506 //conwriteln("ephemeral for '", fi.name, "'");
507 again = true;
508 fi.createEphemerals();
509 break;
512 if (!again) break;
515 static bool isAccount (const(char)[] s) pure nothrow @trusted @nogc {
516 if (!s.startsWith("/accounts")) return false;
517 return (s.length == 9 || s[9] == '/');
520 import std.algorithm.sorting : sort;
521 folderList.sort!((const FolderInfo a, const FolderInfo b) {
522 if (a.name == b.name) return false;
523 if (isAccount(a.name) && !isAccount(b.name)) return true; // a < b
524 if (!isAccount(a.name) && isAccount(b.name)) return false; // a >= b
525 if (a.name[0] == '#' && b.name[0] != '#') return false; // a >= b
526 if (a.name[0] != '#' && b.name[0] == '#') return true; // a < b
527 return (a.name < b.name);
529 res = true;
532 // check unread counts
533 foreach (FolderInfo fi; folderList) {
534 if (fi.ephemeral) continue;
535 foreach (auto row; stmtGetUnread.st.bind(":tagid", fi.tagid).range) {
536 if (fi.unreadCount != row.unread!uint) {
537 res = true;
538 fi.unreadCount = row.unread!uint;
543 setupTrayAnimation();
544 folderDataVersion = dbView.getDataVersion();
545 //conwriteln("ver=", folderDataVersion);
546 return res;
550 // ////////////////////////////////////////////////////////////////////////// //
551 __gshared bool dbg_dump_keynames;
554 // ////////////////////////////////////////////////////////////////////////// //
555 class TrayAnimationStepEvent {}
556 __gshared TrayAnimationStepEvent evTrayAnimationStep;
557 shared static this () { evTrayAnimationStep = new TrayAnimationStepEvent(); }
559 __gshared int trayAnimationIndex = 0; // 0: no animation
560 __gshared int trayAnimationDir = 1; // direction
561 __gshared uint trayAnimDataVersion = uint.max;
564 // ////////////////////////////////////////////////////////////////////////// //
565 void trayPostAnimationEvent () {
566 if (vbwin !is null && !vbwin.eventQueued!TrayAnimationStepEvent) vbwin.postTimeout(evTrayAnimationStep, 100);
570 void trayDoAnimationStep () {
571 if (trayicon is null || trayicon.closed) return; // no tray icon
572 if (vbwin is null || vbwin.closed) return;
573 if (trayAnimationIndex == 0) return; // no animation
574 trayPostAnimationEvent();
575 if (trayAnimationDir < 0) {
576 if (--trayAnimationIndex == 1) trayAnimationDir = 1;
577 } else {
578 if (++trayAnimationIndex == trayimages.length-1) trayAnimationDir = -1;
580 trayicon.icon = trayimages[trayAnimationIndex];
581 //vbwin.icon = icons[trayAnimationIndex];
582 //vbwin.sendDummyEvent(); // or it won't redraw itself
583 //flushGui(); // or it may not redraw itself
587 // ////////////////////////////////////////////////////////////////////////// //
588 void trayStartAnimation () {
589 if (trayicon is null) return; // no tray icon
590 if (trayAnimationIndex == 0) {
591 trayAnimationIndex = 1;
592 trayAnimationDir = 1;
593 trayicon.icon = trayimages[1];
594 vbwin.icon = icons[1];
595 flushGui(); // or it may not redraw itself
596 trayPostAnimationEvent();
601 void trayStopAnimation () {
602 if (trayicon is null) return; // no tray icon
603 if (trayAnimationIndex != 0) {
604 trayAnimationIndex = 0;
605 trayAnimationDir = 1;
606 trayicon.icon = trayimages[0];
607 vbwin.icon = icons[0];
608 flushGui(); // or it may not redraw itself
613 // check if we have to start/stop animation, and do it
614 void setupTrayAnimation () {
615 import std.conv : to;
616 static auto stmtGetUnread = LazyStatement!"View"(`
617 SELECT 1
618 FROM threads
619 WHERE appearance=`~(cast(int)Appearance.Unread).to!string~`
620 LIMIT 1
621 ;`);
623 if (trayicon is null) return; // no tray icon
625 immutable uint dver = dbView.getDataVersion();
626 //conwriteln("TRAY: dver=", dver, "; trv=", trayAnimDataVersion);
627 if (dver == trayAnimDataVersion) return;
628 trayAnimDataVersion = dver;
630 foreach (auto row; stmtGetUnread.st.range) {
631 //conwriteln("TRAY: start anim!");
632 trayStartAnimation();
633 return;
635 //conwriteln("TRAY: stop anim!");
636 trayStopAnimation();
640 // ////////////////////////////////////////////////////////////////////////// //
641 __gshared string[string] mainAppKeyBindings;
643 void clearBindings () {
644 mainAppKeyBindings.clear();
648 void mainAppBind (ConString kname, ConString concmd) {
649 KeyEvent evt = KeyEvent.parse(kname);
650 if (concmd.length) {
651 mainAppKeyBindings[evt.toStr] = concmd.idup;
652 } else {
653 mainAppKeyBindings.remove(evt.toStr);
658 void mainAppUnbind (ConString kname) {
659 KeyEvent evt = KeyEvent.parse(kname);
660 mainAppKeyBindings.remove(evt.toStr);
664 void setupDefaultBindings () {
665 //mainAppBind("C-L", "dbg_font_window");
666 mainAppBind("C-Q", "quit_prompt");
668 mainAppBind("N", "next_unread ona");
669 mainAppBind("S-N", "next_unread tan");
670 mainAppBind("M", "next_unread ona");
671 mainAppBind("S-M", "next_unread tan");
673 mainAppBind("U", "mark_unread");
674 mainAppBind("R", "mark_read");
676 mainAppBind("Space", "artext_page_down");
677 mainAppBind("S-Space", "artext_page_up");
678 mainAppBind("M-Up", "artext_line_up");
679 mainAppBind("M-Down", "artext_line_down");
681 mainAppBind("Up", "article_prev");
682 mainAppBind("Down", "article_next");
683 mainAppBind("PageUp", "article_pgup");
684 mainAppBind("PageDown", "article_pgdown");
685 mainAppBind("Home", "article_to_first");
686 mainAppBind("End", "article_to_last");
687 mainAppBind("C-Up", "article_scroll_up");
688 mainAppBind("C-Down", "article_scroll_down");
690 mainAppBind("C-PageUp", "folder_prev");
691 mainAppBind("C-PageDown", "folder_next");
693 mainAppBind("M-O", "folder_options");
695 //mainAppBind("C-M-U", "folder_update");
696 mainAppBind("C-S-I", "update_all");
697 mainAppBind("C-H", "article_dump_headers");
699 mainAppBind("C-Backslash", "find_mine");
701 //mainAppBind("C-Slash", "article_to_parent");
702 //mainAppBind("C-Comma", "article_to_prev_sib");
703 //mainAppBind("C-Period", "article_to_next_sib");
705 //mainAppBind("C-Insert", "article_copy_url_to_clipboard");
706 mainAppBind("C-M-K", "article_twit_thread");
707 mainAppBind("T", "article_edit_poster_title");
709 mainAppBind("C-R", "article_reply");
710 mainAppBind("S-R", "article_reply_to_from");
712 mainAppBind("S-P", "new_post");
714 //mainAppBind("S-Enter", "article_open_in_browser");
715 //mainAppBind("M-Enter", "article_open_in_browser tan");
717 mainAppBind("Delete", "article_softdelete_toggle");
718 mainAppBind("C-Delete", "article_harddelete_toggle");
722 // ////////////////////////////////////////////////////////////////////////// //
723 struct ImgViewCommand {
724 string filename;
727 private void imageViewThread (Tid ownerTid) {
728 string fname;
729 try {
730 conwriteln("waiting for the message...");
731 receive(
732 (ImgViewCommand cmd) {
733 fname = cmd.filename;
736 conwriteln("got filename: \"", fname, "\"");
738 try {
739 import std.process;
740 //FIXME: make regvar for image viewer
741 //auto pid = execute(["keh", attfname], null, Config.detached);
742 //pid.wait();
743 import std.stdio : File;
744 auto frd = File("/dev/null");
745 auto fwr = File("/dev/null", "w");
746 auto pid = spawnProcess(["keh", fname], frd, fwr, fwr, null, Config.none/*detached*/);
747 pid.wait();
748 } catch (Exception e) {
749 conwriteln("ERROR executing image viewer: ", e.msg);
751 } catch (Throwable e) {
752 // here, we are dead and fucked (the exact order doesn't matter)
753 //import core.stdc.stdlib : abort;
754 import core.stdc.stdio : fprintf, stderr;
755 //import core.memory : GC;
756 import core.thread : thread_suspendAll;
757 //GC.disable(); // yeah
758 //thread_suspendAll(); // stop right here, you criminal scum!
759 auto s = e.toString();
760 fprintf(stderr, "\n=== FATAL ===\n%.*s\n", cast(uint)s.length, s.ptr);
762 try {
763 import std.file : remove;
764 if (fname.length) {
765 conwriteln("deleting file \"", fname, "\"");
766 remove(fname);
768 } catch (Exception e) {}
772 // ////////////////////////////////////////////////////////////////////////// //
773 void initConsole () {
774 import std.functional : toDelegate;
776 conRegVar!scrollKeepLines("scroll_keep_lines", "number of lines to keep on page up or page down.");
777 conRegVar!unreadTimeoutInterval("t_unread_timeout", "timout to mark keyboard-selected message as unread (<1: don't mark)");
778 conRegVar!preferHtmlContent("prefer_html_content", "prefer html content when both html and plain are present?");
779 conRegVar!detectHtmlContent("detect_html_content", "detect html content in plain text?");
781 conRegFunc!clearBindings("binds_app_clear", "clear main application keybindings");
782 conRegFunc!setupDefaultBindings("binds_app_default", "*append* default application bindings");
783 conRegFunc!mainAppBind("bind_app", "add main application binding");
784 conRegFunc!mainAppUnbind("unbind_app", "remove main application binding");
787 // //////////////////////////////////////////////////////////////////// //
788 conRegFunc!((ConString filename) {
789 if (filename.length == 0) return;
790 import std.path : buildPath;
791 auto fname = buildPath(mailRootDir, filename);
792 char[] text;
793 scope(exit) delete text;
794 bool sayError = false;
795 try {
796 auto fl = VFile(fname);
797 sayError = true;
798 conwriteln("loading style file '", fname, "'...");
799 auto sz = fl.size;
800 if (sz > 1024*1024*32) { conwriteln("ERROR: style file too big!"); return; }
801 if (sz == 0) return;
802 text = new char[cast(usize)sz];
803 fl.rawReadExact(text);
804 fl.close();
805 } catch (Exception) {
806 if (sayError) conwriteln("ERROR reading style file!");
807 return;
809 try {
810 defaultColorStyle.parseStyle(text);
811 } catch (Exception e) {
812 conwriteln("ERROR parsing style: ", e.msg);
814 })("load_style", "load widget style");
817 // //////////////////////////////////////////////////////////////////// //
818 conRegFunc!(() {
819 auto qww = new YesNoWindow("Quit?", "Do you really want to quit?", true);
820 qww.onYes = () { concmd("quit"); };
821 //qww.addModal();
822 })("quit_prompt", "quit with prompt");
825 // //////////////////////////////////////////////////////////////////// //
826 conRegFunc!((ConString url, bool forceOpera=false) {
827 if (url.length) {
828 import std.stdio : File;
829 import std.process;
830 try {
831 auto frd = File("/dev/null");
832 auto fwr = File("/dev/null", "w");
833 spawnProcess([getBrowserCommand(forceOpera), url.idup], frd, fwr, fwr, null, Config.detached);
834 } catch (Exception e) {
835 conwriteln("ERROR executing URL viewer (", e.msg, ")");
838 })("open_url", "open given url in a browser");
841 // //////////////////////////////////////////////////////////////////// //
842 conRegFunc!(() {
843 receiverForceUpdateAll();
844 })("update_all", "mark all groups for updating");
847 // //////////////////////////////////////////////////////////////////// //
848 conRegFunc!(() {
849 if (mainPane !is null && mainPane.folderUpOne()) {
850 postScreenRebuild();
852 })("folder_prev", "go to previous group");
854 conRegFunc!(() {
855 if (mainPane !is null && mainPane.folderDownOne()) {
856 postScreenRebuild();
858 })("folder_next", "go to next group");
861 // //////////////////////////////////////////////////////////////////// //
862 conRegFunc!(() {
863 if (vbwin is null || vbwin.closed) return;
864 if (mainPane is null) return;
865 if (chiroGetMessageExactRead(mainPane.lastDecodedTid, mainPane.msglistCurrUId)) {
866 chiroSetMessageUnread(mainPane.lastDecodedTid, mainPane.msglistCurrUId);
867 postScreenRebuild();
868 setupTrayAnimation();
870 })("mark_unread", "mark current message as unread");
872 conRegFunc!(() {
873 if (vbwin is null || vbwin.closed) return;
874 if (mainPane is null) return;
875 if (chiroGetMessageUnread(mainPane.lastDecodedTid, mainPane.msglistCurrUId)) {
876 chiroSetMessageRead(mainPane.lastDecodedTid, mainPane.msglistCurrUId);
877 setupTrayAnimation();
878 postScreenRebuild();
880 })("mark_read", "mark current message as read");
882 conRegFunc!((bool allowNextGroup=false) {
883 if (vbwin is null || vbwin.closed) return;
884 if (mainPane is null) return;
885 // try current group
886 if (mainPane.lastDecodedTid != 0) {
887 auto uid = chiroGetPaneNextUnread(mainPane.msglistCurrUId);
888 if (uid) {
889 // i found her!
890 if (uid == mainPane.msglistCurrUId) return;
891 mainPane.msglistCurrUId = uid;
892 mainPane.threadListPositionDirty();
893 chiroSetMessageRead(mainPane.lastDecodedTid, mainPane.msglistCurrUId);
894 setupTrayAnimation();
895 postScreenRebuild();
896 return;
899 // try other groups?
900 if (!allowNextGroup) return;
901 int idx = mainPane.folderCurrIndex;
902 foreach (; 0..cast(int)folderList.length) {
903 idx = (idx+1)%cast(int)folderList.length;
904 if (idx == mainPane.folderCurrIndex) continue;
905 if (folderList[idx].ephemeral) continue;
906 if (folderList[idx].unreadCount == 0) continue;
907 mainPane.folderSetToIndex(idx);
908 auto uid = chiroGetPaneNextUnread(/*mainPane.msglistCurrUId*/0);
909 if (uid) {
910 // i found her!
911 if (uid == mainPane.msglistCurrUId) return;
912 mainPane.msglistCurrUId = uid;
913 mainPane.threadListPositionDirty();
914 chiroSetMessageRead(mainPane.lastDecodedTid, mainPane.msglistCurrUId);
915 setupTrayAnimation();
916 postScreenRebuild();
917 return;
920 })("next_unread", "move to next unread message; bool arg: can skip to next group?");
923 // //////////////////////////////////////////////////////////////////// //
924 conRegFunc!(() {
925 if (mainPane !is null) mainPane.scrollByPageUp();
926 })("artext_page_up", "do pageup on article text");
928 conRegFunc!(() {
929 if (mainPane !is null) mainPane.scrollByPageDown();
930 })("artext_page_down", "do pagedown on article text");
932 conRegFunc!(() {
933 if (mainPane !is null) mainPane.scrollBy(-1);
934 })("artext_line_up", "do lineup on article text");
936 conRegFunc!(() {
937 if (mainPane !is null) mainPane.scrollBy(1);
938 })("artext_line_down", "do linedown on article text");
940 // //////////////////////////////////////////////////////////////////// //
941 /*FIXME
942 conRegFunc!((bool forceOpera=false) {
943 if (auto fldx = getActiveFolder) {
944 fldx.withBaseReader((abase, cur, top, alist) {
945 if (cur < alist.length) {
946 abase.loadContent(alist[cur]);
947 if (auto art = abase[alist[cur]]) {
948 scope(exit) art.releaseContent();
949 auto path = art.getHeaderValue("path:");
950 //conwriteln("path: [", path, "]");
951 if (path.startsWithCI("digitalmars.com!.POSTED.")) {
952 import std.stdio : File;
953 import std.process;
954 //http://forum.dlang.org/post/hhyqqpoatbpwkprbvfpj@forum.dlang.org
955 string id = art.msgid;
956 if (id.length > 2 && id[0] == '<' && id[$-1] == '>') id = id[1..$-1];
957 auto pid = spawnProcess(
958 [getBrowserCommand(forceOpera), "http://forum.dlang.org/post/"~id],
959 File("/dev/zero"), File("/dev/null"), File("/dev/null"),
961 pid.wait();
967 })("article_open_in_browser", "open the current article in browser (dlang forum)");
970 /*FIXME
971 conRegFunc!(() {
972 if (auto fldx = getActiveFolder) {
973 fldx.withBaseReader((abase, cur, top, alist) {
974 if (cur < alist.length) {
975 if (auto art = abase[alist[cur]]) {
976 auto path = art.getHeaderValue("path:");
977 if (path.startsWithCI("digitalmars.com!.POSTED.")) {
978 //http://forum.dlang.org/post/hhyqqpoatbpwkprbvfpj@forum.dlang.org
979 string id = art.msgid;
980 if (id.length > 2 && id[0] == '<' && id[$-1] == '>') id = id[1..$-1];
981 id = "http://forum.dlang.org/post/"~id;
982 setClipboardText(vbwin, id);
983 setPrimarySelection(vbwin, id);
989 })("article_copy_url_to_clipboard", "copy the url of the current article to clipboard (dlang forum)");
993 // //////////////////////////////////////////////////////////////////// //
994 conRegFunc!((ConString oldmail, ConString newmail, ConString newname) {
995 if (oldmail.length) {
996 if (newmail.length == 0) {
997 repmailreps.remove(oldmail.idup);
998 } else {
999 MailReplacement mr;
1000 mr.oldmail = oldmail.idup;
1001 mr.newmail = newmail.idup;
1002 mr.newname = newname.idup;
1003 repmailreps[mr.oldmail] = mr;
1006 })("append_replyto_mail_replacement", "append replacement for reply mails");
1009 // //////////////////////////////////////////////////////////////////// //
1010 conRegFunc!(() {
1011 if (mainPane !is null && mainPane.threadListUp()) {
1012 postScreenRebuild();
1014 })("article_prev", "go to previous article");
1016 conRegFunc!(() {
1017 if (mainPane !is null && mainPane.threadListDown()) {
1018 postScreenRebuild();
1020 })("article_next", "go to next article");
1022 conRegFunc!(() {
1023 if (mainPane !is null && mainPane.threadListPageUp()) {
1024 postScreenRebuild();
1026 })("article_pgup", "artiles list: page up");
1028 conRegFunc!(() {
1029 if (mainPane !is null && mainPane.threadListPageDown()) {
1030 postScreenRebuild();
1032 })("article_pgdown", "artiles list: page down");
1034 conRegFunc!(() {
1035 if (mainPane !is null && mainPane.threadListScrollUp(movecurrent:false)) {
1036 postScreenRebuild();
1038 })("article_scroll_up", "scroll article list up");
1040 conRegFunc!(() {
1041 if (mainPane !is null && mainPane.threadListScrollDown(movecurrent:false)) {
1042 postScreenRebuild();
1044 })("article_scroll_down", "scroll article list up");
1046 conRegFunc!(() {
1047 if (mainPane !is null && mainPane.threadListHome()) {
1048 postScreenRebuild();
1050 })("article_to_first", "go to first article");
1052 conRegFunc!(() {
1053 if (mainPane !is null && mainPane.threadListEnd()) {
1054 postScreenRebuild();
1056 })("article_to_last", "go to last article");
1059 // //////////////////////////////////////////////////////////////////// //
1060 conRegFunc!(() {
1061 auto pw = new PostWindow();
1062 //pw.setFrom("goo boo!");
1063 pw.caption = "WRITE NEW MESSAGE";
1065 uint tid = mainPane.lastDecodedTid;
1066 if (tid) {
1067 dynstring tn = chiroGetTagName(tid);
1068 if (tn.length) {
1069 foreach (auto row; dbConf.statement(`
1070 SELECT name AS name, realname AS realname, email AS email, nntpgroup AS nntpgroup
1071 FROM accounts
1072 WHERE inbox=:inbox
1073 LIMIT 1
1074 ;`).bindConstText(":inbox", tn.getData).range)
1076 //pw.desttag = tn; // no need to
1077 pw.accname = row.name!SQ3Text;
1078 pw.setFrom(row.realname!SQ3Text, row.email!SQ3Text);
1079 pw.to.focus();
1083 })("new_post", "post a new article or message");
1086 // //////////////////////////////////////////////////////////////////// //
1087 static void doReplyXX (string repfld) {
1088 if (vbwin is null || vbwin.closed) return;
1089 if (mainPane is null) return;
1090 if (!mainPane.msglistCurrUId) return;
1092 auto pw = new PostWindow();
1093 pw.ed.focus();
1095 dynstring accname;
1096 foreach (auto row; dbView.statement(`
1097 SELECT DISTINCT(tagid) AS tagid, tt.tag AS name
1098 FROM threads
1099 INNER JOIN tagnames AS tt USING(tagid)
1100 WHERE uid=:uid AND name LIKE 'account:%'
1101 ;`).bind(":uid", mainPane.msglistCurrUId).range)
1103 auto name = row.name!SQ3Text;
1104 if (name.startsWith("account:")) {
1105 accname = name[8..$];
1106 if (accname.length) {
1107 pw.accname = accname;
1108 break;
1113 if (accname.length == 0) {
1114 conwriteln("ERROR: source account not found!");
1115 vbwin.beep();
1116 } else {
1117 conwriteln("account: ", accname);
1120 dynstring fldvalue;
1122 foreach (auto row; dbStore.statement(`
1123 SELECT ChiroHdr_Field(ChiroUnpack(data), :fldname) AS fldvalue
1124 FROM messages
1125 WHERE uid=:uid
1126 ORDER BY uid
1127 LIMIT 1
1128 `).bind(":uid", mainPane.msglistCurrUId).bindConstText(":fldname", repfld).range)
1130 fldvalue = row.fldvalue!SQ3Text.decodeSubj;
1133 if (fldvalue.length == 0 && !repfld.strEquCI("From")) {
1134 foreach (auto row; dbStore.statement(`
1135 SELECT ChiroHdr_Field(ChiroUnpack(data), :fldname) AS fldvalue
1136 FROM messages
1137 WHERE uid=:uid
1138 ORDER BY uid
1139 LIMIT 1
1140 `).bind(":uid", mainPane.msglistCurrUId).bindConstText(":fldname", "From").range)
1142 fldvalue = row.fldvalue!SQ3Text.decodeSubj;
1146 pw.to.str = fldvalue;
1147 dynstring cpt = dynstring("Reply to: ")~fldvalue;
1148 cpt ~= " (field: ";
1149 cpt ~= repfld;
1150 cpt ~= ")";
1151 pw.caption = cpt;
1153 dynstring fromname;
1154 foreach (auto row; dbView.statement(`
1155 SELECT subj AS subj, from_name AS fromname
1156 FROM info
1157 WHERE uid=:uid
1158 LIMIT 1
1159 `).bind(":uid", mainPane.msglistCurrUId).range)
1161 fromname = row.fromname!SQ3Text;
1162 dynstring s = "Re: ";
1163 s ~= row.subj!SQ3Text;
1164 pw.subj.str = s;
1167 foreach (auto row; dbView.statement(`
1168 SELECT ChiroUnpack(content) AS content
1169 FROM content_text
1170 WHERE uid=:uid
1171 LIMIT 1
1172 `).bind(":uid", mainPane.msglistCurrUId).range)
1174 pw.ed.addText(fromname);
1175 pw.ed.addText(" wrote:\n");
1176 pw.ed.addText("\n");
1177 dynstring text = row.content!SQ3Text;
1178 foreach (SQ3Text s; text.byLine) {
1179 if (s.length == 0 || s[0] == '>') pw.ed.addText(">"); else pw.ed.addText("> ");
1180 pw.ed.addText(s);
1181 pw.ed.addText("\n");
1183 pw.ed.addText("\n");
1184 pw.ed.reformat();
1187 foreach (auto row; dbConf.statement(`
1188 SELECT
1189 accid AS accid
1190 --, name AS name
1191 , recvserver AS recvserver
1192 , sendserver AS sendserver
1193 , realname AS realname
1194 , email AS email
1195 , nntpgroup AS nntpgroup
1196 FROM accounts
1197 WHERE name=:accname --AND sendserver<>'' AND email<>''
1198 LIMIT 1
1199 `).bindConstText(":accname", accname.getData).range)
1202 conwriteln("GROUP: <", row.nntpgroup!SQ3Text, ">");
1203 conwriteln("NAME: <", row.realname!SQ3Text, ">");
1204 conwriteln("EMAIL: <", row.email!SQ3Text, ">");
1206 dynstring frm;
1207 if (row.realname!SQ3Text.length) {
1208 frm = row.realname!SQ3Text;
1209 frm ~= " <";
1210 frm ~= row.email!SQ3Text;
1211 frm ~= ">";
1212 } else {
1213 frm = row.email!SQ3Text;
1215 pw.setFrom(frm);
1217 if (row.nntpgroup!SQ3Text.length) {
1218 pw.to.str = dynstring("newsgroup: ")~row.nntpgroup!SQ3Text;
1219 pw.to.readonly = true;
1220 pw.to.disabled = true;
1221 pw.allowAccountChange = false;
1222 pw.nntp = true;
1226 writeln("getting msgid...");
1227 foreach (auto row; dbView.statement(`
1228 SELECT msgid AS msgid
1229 FROM msgids
1230 WHERE uid=:uid
1231 LIMIT 1
1232 `).bind(":uid", mainPane.msglistCurrUId).range)
1234 conwriteln("MSGID: |", row.msgid!SQ3Text);
1235 if (pw.references.length) pw.references ~= " ";
1236 // two times, one for references field
1237 if (pw.references.length) pw.references ~= " ";
1238 pw.references ~= row.msgid!SQ3Text;
1239 if (pw.references.length) pw.references ~= " ";
1240 pw.references ~= row.msgid!SQ3Text;
1243 writeln("select references...");
1244 foreach (auto row; dbView.statement(`
1245 SELECT msgid AS msgid
1246 FROM refids
1247 WHERE uid=:uid
1248 ORDER BY idx
1249 `).bind(":uid", mainPane.msglistCurrUId).range)
1251 conwriteln("REF: |", row.msgid!SQ3Text);
1252 if (pw.references.length) pw.references ~= " ";
1253 pw.references ~= row.msgid!SQ3Text;
1256 pw.desttag = chiroGetTagName(mainPane.lastDecodedTid);
1259 static void doReply (string repfld) {
1260 try {
1261 doReplyXX(repfld);
1262 } catch (Exception e) {
1263 conwriteln("EXCEPTION: ", e.msg);
1264 auto s = e.toString();
1265 conwriteln(s);
1269 conRegFunc!(() { doReply("Reply-To"); })("article_reply", "reply to the current article with \"reply-to\" field");
1270 conRegFunc!(() { doReply("From"); })("article_reply_to_from", "reply to the current article with \"from\" field");
1273 // //////////////////////////////////////////////////////////////////// //
1274 conRegFunc!(() {
1275 if (vbwin is null || vbwin.closed) return;
1276 if (mainPane is null) return;
1277 if (mainPane.msglistCurrUId) {
1278 //messageBogoMarkHam(mainPane.msglistCurrUId);
1279 foreach (auto mrow; dbStore.statement(`SELECT ChiroUnpack(data) AS data FROM messages WHERE uid=:uid LIMIT 1;`).bind(":uid", mainPane.msglistCurrUId).range) {
1280 try {
1281 import core.stdc.stdio : snprintf;
1282 char[128] fname = void;
1283 auto len = snprintf(fname.ptr, fname.length, "~/Mail/_bots/z_eml_%u.eml", cast(uint)mainPane.msglistCurrUId);
1284 auto fo = VFile(fname[0..len], "w");
1285 fo.writeln(mrow.data!SQ3Text.xstripright);
1286 fo.close();
1287 conwriteln("article exported to: ", fname[0..len]);
1288 } catch (Exception e) {
1292 })("article_export", "export current article as raw text");
1295 conRegFunc!(() {
1296 if (vbwin is null || vbwin.closed) return;
1297 if (mainPane is null) return;
1298 if (mainPane.msglistCurrUId) {
1299 messageBogoMarkHam(mainPane.msglistCurrUId);
1300 //TODO: move out of spam
1302 })("article_mark_ham", "mark current article as ham");
1305 conRegFunc!(() {
1306 if (vbwin is null || vbwin.closed) return;
1307 if (mainPane is null) return;
1308 if (mainPane.msglistCurrUId) {
1309 immutable uint uid = mainPane.msglistCurrUId;
1310 // move to the next message
1311 if (!mainPane.threadListDown()) mainPane.threadListUp();
1312 conwriteln("calling bogofilter...");
1313 messageBogoMarkSpam(uid);
1314 conwriteln("adding '#spam' tag");
1315 immutable bool updatePane = chiroMessageAddTag(uid, "#spam");
1316 conwriteln("removing other virtual folder tags...");
1317 DynStr[] tags;
1318 scope(exit) delete tags;
1319 tags.reserve(32);
1320 static auto stGetMsgTags = LazyStatement!"View"(`
1321 SELECT DISTINCT(tagid) AS tagid, tt.tag AS name
1322 FROM threads
1323 INNER JOIN tagnames AS tt USING(tagid)
1324 WHERE uid=:uid
1325 ;`);
1326 foreach (auto row; stGetMsgTags.st.bind(":uid", uid).range) {
1327 auto tag = row.name!SQ3Text;
1328 conwriteln(" tag: ", tag);
1329 if (tag.startsWith("/")) tags ~= DynStr(tag);
1331 foreach (ref DynStr tn; tags) {
1332 conwriteln("removing tag '", tn.getData, "'...");
1333 chiroMessageRemoveTag(uid, tn.getData);
1335 conwriteln("done marking as spam.");
1336 if (updatePane) {
1337 mainPane.switchToFolderTid(mainPane.lastDecodedTid, forced:true);
1338 } else {
1339 // rescan folder
1340 mainPane.updateViewsIfTid(chiroGetTagUid("#spam"));
1342 postScreenRebuild();
1344 })("article_mark_spam", "mark current article as spam");
1347 // //////////////////////////////////////////////////////////////////// //
1348 conRegFunc!((ConString fldname) {
1349 if (vbwin is null || vbwin.closed) return;
1350 if (mainPane is null) return;
1351 if (!mainPane.msglistCurrUId) return;
1352 immutable uint uid = mainPane.msglistCurrUId;
1354 fldname = fldname.xstrip;
1355 while (fldname.length && fldname[$-1] == '/') fldname = fldname[0..$-1].xstrip;
1356 immutable bool isforced = (fldname.length && fldname[0] == '!');
1357 if (isforced) fldname = fldname[1..$];
1358 if (fldname.length == 0) {
1359 conwriteln("ERROR: cannot move to empty folder");
1360 return;
1362 if (fldname[0].isalnum) {
1363 conwriteln("ERROR: invalid folder name '", fldname, "'");
1364 return;
1367 uint tagid;
1368 if (!isforced) {
1369 tagid = chiroGetTagUid(fldname);
1370 } else {
1371 tagid = chiroAppendTag(fldname, hidden:(fldname[0] == '#' ? 1 : 0));
1373 if (!tagid) {
1374 conwriteln("ERROR: invalid folder name '", fldname, "'");
1375 return;
1378 immutable bool updatePane = chiroMessageAddTag(uid, fldname);
1379 DynStr[] tags;
1380 scope(exit) delete tags;
1381 tags.reserve(32);
1382 static auto stGetMsgTags = LazyStatement!"View"(`
1383 SELECT DISTINCT(tagid) AS tagid, tt.tag AS name
1384 FROM threads
1385 INNER JOIN tagnames AS tt USING(tagid)
1386 WHERE uid=:uid
1387 ;`);
1388 foreach (auto row; stGetMsgTags.st.bind(":uid", uid).range) {
1389 auto tag = row.name!SQ3Text;
1390 conwriteln(" tag: ", tag);
1391 if (tag.startsWith("account:")) continue;
1392 if (tag != fldname) tags ~= DynStr(tag);
1394 foreach (ref DynStr tn; tags) {
1395 conwriteln("removing tag '", tn.getData, "'...");
1396 chiroMessageRemoveTag(uid, tn.getData);
1398 if (updatePane) {
1399 mainPane.switchToFolderTid(mainPane.lastDecodedTid, forced:true);
1400 } else {
1401 // rescan folder
1402 mainPane.updateViewsIfTid(chiroGetTagUid("#spam"));
1404 postScreenRebuild();
1405 })("article_move_to_folder", "move article to existing folder");
1408 // //////////////////////////////////////////////////////////////////// //
1409 version(none) {
1410 conRegFunc!(() {
1411 /*FIXME
1412 if (auto fld = getActiveFolder) {
1413 fld.moveToParent();
1414 postScreenRebuild();
1417 })("article_to_parent", "jump to parent article, if any");
1419 conRegFunc!(() {
1420 /*FIXME
1421 if (auto fld = getActiveFolder) {
1422 fld.moveToPrevSib();
1423 postScreenRebuild();
1426 })("article_to_prev_sib", "jump to previous sibling");
1428 conRegFunc!(() {
1429 /*FIXME
1430 if (auto fld = getActiveFolder) {
1431 fld.moveToNextSib();
1432 postScreenRebuild();
1435 })("article_to_next_sib", "jump to next sibling");
1438 // //////////////////////////////////////////////////////////////////// //
1439 conRegFunc!(() {
1440 if (vbwin is null || vbwin.closed) return;
1441 if (mainPane is null) return;
1442 if (mainPane.lastDecodedTid == 0 || mainPane.msglistCurrUId == 0) return;
1443 DynStr tagname = chiroGetTagName(mainPane.lastDecodedTid);
1444 if (!globmatch(tagname.getData, "/dmars_ng/*")) return;
1445 // get from
1446 DynStr fromMail, fromName;
1447 if (!chiroGetMessageFrom(mainPane.msglistCurrUId, ref fromMail, ref fromName)) return;
1448 if (fromMail.length == 0 && fromName.length == 0) return;
1449 //writeln("!!! email=", fromMail.getData, "; name=", fromName.getData, "|");
1451 uint twitid = 0;
1452 DynStr twtitle;
1453 DynStr twname;
1454 DynStr twemail;
1455 DynStr twnotes;
1456 DynStr twtagglob = "/dmars_ng/*";
1457 bool withName = false;
1459 static auto stFindTwit = LazyStatement!"Conf"(`
1460 SELECT
1461 etwitid AS twitid
1462 , tagglob AS tagglob
1463 , email AS email
1464 , name AS name
1465 , title AS title
1466 , notes AS notes
1467 FROM emailtwits
1468 WHERE email=:email AND name=:name
1469 ;`);
1471 static auto stAddTwit = LazyStatement!"Conf"(`
1472 INSERT INTO emailtwits
1473 ( tagglob, email, name, title, notes)
1474 VALUES(:tagglob,:email,:name,:title,:notes)
1475 ;`);
1477 static auto stModifyTwit = LazyStatement!"Conf"(`
1478 UPDATE emailtwits
1480 tagglob=:tagglob
1481 , email=:email
1482 , name=:name
1483 , title=:title
1484 , notes=:notes
1485 WHERE etwitid=:twitid
1486 ;`);
1488 static auto stRemoveTwitAuto = LazyStatement!"Conf"(`
1489 DELETE FROM msgidtwits
1490 WHERE etwitid=:twitid
1491 ;`);
1493 static auto stRemoveTwit = LazyStatement!"Conf"(`
1494 DELETE FROM emailtwits
1495 WHERE etwitid=:twitid
1496 ;`);
1498 stFindTwit.st
1499 .bindConstText(":email", fromMail.getData)
1500 .bindConstText(":name", fromName.getData);
1501 foreach (auto row; stFindTwit.st.range) {
1502 //conwriteln("!!!", row.twitid!uint, "; mail=", row.email!SQ3Text, "; name=", row.name!SQ3Text, "; title=", row.title!SQ3Text.recodeToKOI8);
1503 if (!globmatch(tagname.getData, row.tagglob!SQ3Text)) continue;
1504 twitid = row.twitid!uint;
1505 twtitle = row.title!SQ3Text;
1506 twname = row.name!SQ3Text;
1507 twemail = row.email!SQ3Text;
1508 twtagglob = row.tagglob!SQ3Text;
1509 twnotes = row.notes!SQ3Text;
1510 withName = (fromName.length != 0);
1511 break;
1514 if (!twitid && fromName.length) {
1515 stFindTwit.st
1516 .bindConstText(":email", fromMail.getData)
1517 .bindConstText(":name", "");
1518 foreach (auto row; stFindTwit.st.range) {
1519 //conwriteln("!!!", row.twitid!uint, "; mail=", row.email!SQ3Text, "; name=", row.name!SQ3Text, "; title=", row.title!SQ3Text.recodeToKOI8);
1520 if (!globmatch(tagname.getData, row.tagglob!SQ3Text)) continue;
1521 twitid = row.twitid!uint;
1522 twtitle = row.title!SQ3Text;
1523 twname = row.name!SQ3Text;
1524 twemail = row.email!SQ3Text;
1525 twtagglob = row.tagglob!SQ3Text;
1526 twnotes = row.notes!SQ3Text;
1527 withName = false;
1528 break;
1532 //conwriteln("twitid: ", twitid, "; title=", twtitle.getData.recodeToKOI8);
1534 auto tw = new TitlerWindow((twitid ? twname : fromName), (twitid ? twemail : fromMail), twtagglob, twtitle);
1535 tw.onSelected = delegate (name, email, glob, title) {
1536 if (email.length == 0 && name.length == 0) return false;
1537 if (glob.length == 0) return false;
1538 if (email.length && email[0] == '@') return false;
1539 title = title.xstrip;
1540 if (twitid) {
1541 if (title.length == 0) {
1542 // remove twit
1543 conwriteln("removing twit...");
1544 stRemoveTwitAuto.st.bind(":twitid", twitid).doAll();
1545 stRemoveTwit.st.bind(":twitid", twitid).doAll();
1546 } else {
1547 // change twit
1548 conwriteln("changing twit...");
1549 stModifyTwit.st
1550 .bind(":twitid", twitid)
1551 .bindConstText(":tagglob", glob)
1552 .bindConstText(":email", email)
1553 .bindConstText(":name", name)
1554 .bindConstText(":title", title)
1555 .bindConstText(":notes", twnotes.getData, allowNull:true)
1556 .doAll();
1558 } else {
1559 if (title.length == 0) return false;
1560 // new twit
1561 conwriteln("adding twit...");
1562 stAddTwit.st
1563 .bindConstText(":tagglob", glob)
1564 .bindConstText(":email", email)
1565 .bindConstText(":name", name)
1566 .bindConstText(":title", title)
1567 .bindConstText(":notes", null, allowNull:true)
1568 .doAll();
1571 if (vbwin && !vbwin.closed) vbwin.postEvent(new RecalcAllTwitsEvent());
1572 return true;
1574 })("article_edit_poster_title", "edit poster's title of the current article");
1577 // //////////////////////////////////////////////////////////////////// //
1578 conRegFunc!(() {
1579 if (vbwin is null || vbwin.closed) return;
1580 if (mainPane is null) return;
1581 if (mainPane.lastDecodedTid == 0 || mainPane.msglistCurrUId == 0) return;
1582 DynStr tagname = chiroGetTagName(mainPane.lastDecodedTid);
1583 if (!globmatch(tagname.getData, "/dmars_ng/*")) return;
1584 int mute = chiroGetMessageMute(mainPane.lastDecodedTid, mainPane.msglistCurrUId);
1585 // check for non-automatic mutes
1586 if (mute != Mute.Normal && mute <= Mute.ThreadStart) return;
1587 createTwitByMsgid(mainPane.msglistCurrUId);
1588 mainPane.switchToFolderTid(mainPane.lastDecodedTid, forced:true);
1589 postScreenRebuild();
1590 })("article_twit_thread", "twit current thread");
1592 conRegFunc!(() {
1593 if (vbwin is null || vbwin.closed) return;
1594 if (mainPane is null) return;
1595 int app = chiroGetMessageAppearance(mainPane.lastDecodedTid, mainPane.msglistCurrUId);
1596 if (app >= 0) {
1597 //conwriteln("oldapp: ", app, " (", isSoftDeleted(app), ")");
1598 immutable bool wasPurged = (app == Appearance.SoftDeletePurge);
1599 app =
1600 app == Appearance.SoftDeletePurge ? Appearance.SoftDeleteUser :
1601 isSoftDeleted(app) ? Appearance.Read :
1602 Appearance.SoftDeleteUser;
1603 //conwriteln("newapp: ", app);
1604 chiroSetMessageAppearance(mainPane.lastDecodedTid, mainPane.msglistCurrUId, cast(Appearance)app);
1605 if (!wasPurged && isSoftDeleted(app)) mainPane.threadListDown();
1606 postScreenRebuild();
1608 })("article_softdelete_toggle", "toggle \"soft deleted\" flag on current article");
1610 conRegFunc!(() {
1611 if (vbwin is null || vbwin.closed) return;
1612 if (mainPane is null) return;
1613 int app = chiroGetMessageAppearance(mainPane.lastDecodedTid, mainPane.msglistCurrUId);
1614 if (app >= 0) {
1615 //conwriteln("oldapp: ", app);
1616 app =
1617 app == Appearance.SoftDeletePurge ? Appearance.Read :
1618 isSoftDeleted(app) ? Appearance.SoftDeletePurge :
1619 Appearance.SoftDeletePurge;
1620 //conwriteln("newapp: ", app);
1621 chiroSetMessageAppearance(mainPane.lastDecodedTid, mainPane.msglistCurrUId, cast(Appearance)app);
1622 if (app == Appearance.SoftDeletePurge) mainPane.threadListDown();
1623 postScreenRebuild();
1625 })("article_harddelete_toggle", "toggle \"hard deleted\" flag on current article");
1628 // //////////////////////////////////////////////////////////////////// //
1629 conRegFunc!(() {
1630 if (vbwin is null || vbwin.closed) return;
1631 if (mainPane is null) return;
1632 DynStr hdrs = chiroMessageHeaders(mainPane.msglistCurrUId);
1633 if (hdrs.length == 0) return;
1634 conwriteln("============================");
1635 conwriteln("message uid: ", mainPane.msglistCurrUId);
1636 conwriteln(" tag tagid: ", mainPane.lastDecodedTid);
1637 conwriteln("============================");
1638 forEachHeaderLine(hdrs.getData, (const(char)[] line) {
1639 conwriteln(" ", line.xstripright);
1640 return true; // go on
1642 })("article_dump_headers", "dump article headers");
1644 conRegFunc!(() {
1645 if (vbwin is null || vbwin.closed) return;
1646 if (mainPane is null) return;
1647 DynStr hdrs = chiroMessageHeaders(mainPane.msglistCurrUId);
1648 if (hdrs.length == 0) return;
1649 conwriteln("============================");
1650 conwriteln("message uid: ", mainPane.msglistCurrUId);
1651 conwriteln(" tag tagid: ", mainPane.lastDecodedTid);
1652 conwriteln("============================");
1653 auto bogo = messageBogoCheck(mainPane.msglistCurrUId);
1654 conwriteln("BOGO RESULT: ", bogo);
1655 })("article_bogo_check", "check article with bogofilter (purely informational)");
1657 conRegFunc!(() {
1658 if (mainPane !is null && mainPane.lastDecodedTid) {
1659 conwriteln("relinking ", mainPane.lastDecodedTid, " (", chiroGetTagName(mainPane.lastDecodedTid).getData, ")...");
1660 chiroSupportRelinkTagThreads(mainPane.lastDecodedTid);
1661 mainPane.switchToFolderTid(mainPane.lastDecodedTid, forced:true);
1662 postScreenRebuild();
1664 })("folder_rebuild_index", "rebuild thread index");
1666 conRegFunc!(() {
1667 if (vbwin && !vbwin.closed && mainPane !is null /*&& mainPane.lastDecodedTid*/) {
1668 vbwin.postEvent(new RecalcAllTwitsEvent());
1670 })("folder_rebuild_twits", "rebuild all twits");
1672 conRegFunc!(() {
1673 if (mainPane !is null && mainPane.folderCurrTag.length) {
1674 auto w = new TagOptionsWindow(mainPane.folderCurrTag.getData);
1675 w.onUpdated = delegate void (tagname) {
1676 if (vbwin && !vbwin.closed && mainPane !is null && mainPane.lastDecodedTagName == tagname) {
1677 mainPane.switchToFolderTid(mainPane.lastDecodedTid, forced:true);
1680 postScreenRebuild();
1682 })("folder_options", "show options window");
1685 conRegFunc!(() {
1686 if (auto fld = getActiveFolder) {
1687 fld.withBase(delegate (abase) {
1688 uint idx = fld.curidx;
1689 if (idx >= fld.length) {
1690 idx = 0;
1691 } else if (auto art = abase[fld.baseidx(idx)]) {
1692 if (art.frommail.indexOf("ketmar@ketmar.no-ip.org") >= 0) {
1693 idx = (idx+1)%fld.length;
1696 foreach (immutable _; 0..fld.length) {
1697 auto art = abase[fld.baseidx(idx)];
1698 if (art !is null) {
1699 if (art.frommail.indexOf("ketmar@ketmar.no-ip.org") >= 0) {
1700 fld.curidx = cast(int)idx;
1701 postScreenRebuild();
1702 return;
1705 idx = (idx+1)%fld.length;
1709 })("find_mine", "find mine article");
1712 // //////////////////////////////////////////////////////////////////// //
1713 conRegVar!dbg_dump_keynames("dbg_dump_key_names", "dump key names");
1716 // //////////////////////////////////////////////////////////////////// //
1717 conRegFunc!((uint idx) {
1718 if (vbwin is null || vbwin.closed) return;
1719 if (mainPane is null) return;
1720 if (mainPane.msglistCurrUId == 0) return;
1722 static auto statAttaches = LazyStatement!"View"(`
1723 SELECT
1724 idx AS idx
1725 , mime AS mime
1726 , name AS name
1727 , ChiroUnpack(content) AS content
1728 FROM attaches
1729 WHERE uid=:uid
1730 ORDER BY idx
1731 ;`);
1732 char[128] buf = void;
1733 uint attidx = 0;
1734 foreach (auto row; statAttaches.st.bind(":uid", mainPane.msglistCurrUId).range) {
1735 import core.stdc.stdio : snprintf;
1736 if (idx != 0) { --idx; ++attidx; continue; }
1737 if (!row.mime!SQ3Text.startsWith("image")) return;
1738 auto name = row.name!SQ3Text.getExtension;
1739 if (name.length == 0) return;
1740 try {
1741 DynStr fname;
1742 fname = "/tmp/_viewimage_";
1744 import std.uuid;
1745 UUID id = randomUUID();
1746 foreach (immutable ubyte b; id.data[]) {
1747 fname ~= "0123456789abcdef"[b>>4];
1748 fname ~= "0123456789abcdef"[b&0x0f];
1750 fname ~= name;
1752 conwriteln("writing attach #", attidx, " to '", fname.getData, "'");
1753 VFile fo = VFile(fname.getData, "w");
1754 fo.rawWriteExact(row.content!SQ3Text);
1755 fo.close();
1757 auto vtid = spawn(&imageViewThread, thisTid);
1758 string fnamestr = fname.getData.idup;
1759 vtid.send(ImgViewCommand(fnamestr));
1760 } catch (Exception e) {
1761 conwriteln("ERROR writing attachment: ", e.msg);
1763 break;
1765 })("attach_view", "view attached image: attach_view index");
1768 // //////////////////////////////////////////////////////////////////// //
1769 conRegFunc!((uint idx, ConString userfname=null) {
1770 if (vbwin is null || vbwin.closed) return;
1771 if (mainPane is null) return;
1772 if (mainPane.msglistCurrUId == 0) return;
1774 static auto statAttaches = LazyStatement!"View"(`
1775 SELECT
1776 idx AS idx
1777 , mime AS mime
1778 , name AS name
1779 , ChiroUnpack(content) AS content
1780 FROM attaches
1781 WHERE uid=:uid
1782 ORDER BY idx
1783 ;`);
1784 char[128] buf = void;
1785 uint attidx = 0;
1786 foreach (auto row; statAttaches.st.bind(":uid", mainPane.msglistCurrUId).range) {
1787 import core.stdc.stdio : snprintf;
1788 if (idx != 0) { --idx; ++attidx; continue; }
1789 try {
1790 auto name = row.name!SQ3Text/*.decodeSubj*/;
1791 DynStr fname;
1793 if (userfname.length) {
1794 fname = userfname;
1795 } else {
1796 fname = "/tmp/";
1797 name = name.sanitizeFileNameStr;
1798 if (name.length == 0) {
1799 auto len = snprintf(buf.ptr, buf.sizeof, "attach_%02u.bin", attidx);
1800 fname ~= buf[0..cast(usize)len];
1801 } else {
1802 fname ~= name;
1806 conwriteln("writing attach #", attidx, " to '", fname.getData, "'");
1807 VFile fo = VFile(fname.getData, "w");
1808 fo.rawWriteExact(row.content!SQ3Text);
1809 fo.close();
1810 } catch (Exception e) {
1811 conwriteln("ERROR writing attachment: ", e.msg);
1813 break;
1815 })("attach_save", "save attach: attach_save index [filename]");
1819 // ////////////////////////////////////////////////////////////////////////// //
1820 //FIXME: turn into property
1821 final class ArticleTextScrollEvent {}
1822 __gshared ArticleTextScrollEvent evArticleScroll;
1823 shared static this () {
1824 evArticleScroll = new ArticleTextScrollEvent();
1827 void postArticleScroll () {
1828 if (vbwin !is null && !vbwin.eventQueued!ArticleTextScrollEvent) vbwin.postTimeout(evArticleScroll, 25);
1832 // ////////////////////////////////////////////////////////////////////////// //
1833 class MarkAsUnreadEvent {
1834 uint tagid;
1835 uint uid;
1838 __gshared int unreadTimeoutInterval = 600;
1839 __gshared int scrollKeepLines = 3;
1840 __gshared bool preferHtmlContent = false;
1841 __gshared bool detectHtmlContent = true;
1844 void postMarkAsUnreadEvent () {
1845 if (unreadTimeoutInterval > 0 && unreadTimeoutInterval < 10000 && vbwin !is null && mainPane !is null) {
1846 if (!mainPane.msglistCurrUId) return;
1847 if (chiroGetMessageUnread(mainPane.lastDecodedTid, mainPane.msglistCurrUId)) {
1848 //conwriteln("setting new unread timer");
1849 auto evt = new MarkAsUnreadEvent();
1850 evt.tagid = mainPane.lastDecodedTid;
1851 evt.uid = mainPane.msglistCurrUId;
1852 vbwin.postTimeout(evt, unreadTimeoutInterval);
1858 // ////////////////////////////////////////////////////////////////////////// //
1859 __gshared MainPaneWindow mainPane;
1862 final class MainPaneWindow : SubWindow {
1863 dynstring[] emlines; // in utf
1864 uint emlinesBeforeAttaches;
1865 uint lastDecodedUId;
1866 uint lastDecodedTid; // for which folder we last build our view?
1867 uint lastMaxTidUid;
1868 DynStr lastDecodedTagName;
1869 DynStr arttoname;
1870 DynStr arttomail;
1871 DynStr artfromname;
1872 DynStr artfrommail;
1873 DynStr artsubj;
1874 DynStr arttime;
1875 int articleTextTopLine = 0;
1876 int articleDestTextTopLine = 0;
1877 //__gshared Timer unreadTimer; // as main pane is never destroyed, there's no need to kill the timer
1878 //__gshared Folder unreadFolder;
1879 //__gshared uint unreadIdx;
1880 int linesInHeader;
1881 // folder view
1882 DynStr folderTopTag = null;
1883 DynStr folderCurrTag = null;
1884 int folderTopIndex = 0;
1885 int folderCurrIndex = 0;
1886 // message list view
1887 uint msglistTopUId = 0;
1888 uint msglistCurrUId = 0;
1889 bool saveMsgListPositions = false;
1890 MonoTime lastStateSaveTime;
1891 uint viewDataVersion;
1893 this () {
1894 super(null, GxSize(screenWidth, screenHeight));
1895 allowMinimise = false;
1896 allowDragMove = false;
1897 mType = Type.OnBottom;
1898 add();
1899 loadSavedState();
1900 lastStateSaveTime = MonoTime.currTime;
1901 viewDataVersion = dbView.getDataVersion()-1u;
1904 bool isViewChanged () const nothrow @trusted @nogc {
1905 pragma(inline, true);
1906 return (viewDataVersion != dbView.getDataVersion());
1909 void updateViewsIfTid (uint tid) {
1910 if (tid && lastDecodedTid == tid) {
1911 switchToFolderTid(lastDecodedTid, forced:true);
1915 void checkSaveState () {
1916 if (lastStateSaveTime+dur!"seconds"(30) <= MonoTime.currTime) {
1917 //writeln("saving state...");
1918 saveCurrentState();
1919 lastStateSaveTime = MonoTime.currTime;
1920 if (lastDecodedTid) {
1921 immutable maxuid = chiroGetTreePaneTableMaxUId();
1922 if (maxuid && maxuid > lastMaxTidUid) {
1923 // something was changed in the database, rescal
1924 updateViewsIfTid(lastDecodedTid);
1930 void saveCurrentState () {
1931 transacted!"Conf"{
1932 chiroSetOption("/mainpane/folders/toptid", folderTopTag);
1933 chiroSetOption("/mainpane/folders/currtid", folderCurrTag);
1934 saveThreadListPositions(transaction:false);
1938 void loadSavedState () {
1939 chiroGetOption(folderTopTag, "/mainpane/folders/toptid");
1940 chiroGetOption(folderCurrTag, "/mainpane/folders/currtid");
1941 //conwriteln("curr: ", folderCurrTag);
1942 //conwriteln(" top: ", folderTopTag);
1943 rescanFolders(forced:true);
1947 private void threadListPositionDirty () nothrow @safe @nogc {
1948 saveMsgListPositions = true;
1951 private void saveThreadListPositionsInternal () {
1952 if (lastDecodedTagName.length == 0) return;
1953 import core.stdc.stdio : snprintf;
1954 const(char)[] tn = lastDecodedTagName.getData;
1955 char[128] xname = void;
1956 auto xlen = snprintf(xname.ptr, xname.sizeof, "/mainpane/msgview/current%.*s", cast(uint)tn.length, tn.ptr);
1957 chiroSetOptionUInts(xname[0..xlen], msglistTopUId, msglistCurrUId);
1960 private void saveThreadListPositions (immutable bool transaction=true) {
1961 if (!saveMsgListPositions) return;
1962 saveMsgListPositions = false;
1963 if (lastDecodedTid == 0) return;
1964 if (transaction) {
1965 transacted!"Conf"(&saveThreadListPositionsInternal);
1966 } else {
1967 saveThreadListPositionsInternal();
1971 private void loadThreadListPositions () {
1972 saveMsgListPositions = false;
1973 msglistTopUId = msglistCurrUId = 0;
1974 if (lastDecodedTid == 0) return;
1975 import core.stdc.stdio : snprintf;
1976 char[128] xname = void;
1977 const(char)[] tn = lastDecodedTagName.getData;
1978 auto xlen = snprintf(xname.ptr, xname.sizeof, "/mainpane/msgview/current%.*s", cast(uint)tn.length, tn.ptr);
1979 chiroGetOptionUInts(ref msglistTopUId, ref msglistCurrUId, xname[0..xlen]);
1980 setupUnreadTimer();
1984 private int getFolderMonthLimit () {
1985 version(none) {
1986 import core.stdc.stdio : snprintf;
1987 char[1024] xname = void;
1988 if (lastDecodedTid == 0) return chiroGetOption!int("/mainpane/msgview/monthlimit", 6);
1989 bool exists;
1990 const(char)[] tn = lastDecodedTagName.getData;
1991 for (;;) {
1992 auto len = snprintf(xname.ptr, xname.sizeof, "/mainpane/msgview/monthlimit%.*s", cast(uint)tn.length, tn.ptr);
1993 int v = chiroGetOptionEx!int(xname[0..len], out exists);
1994 //writeln(tn, " :: ", v, " :: ", exists);
1995 if (exists) return v;
1996 auto slp = tn.lastIndexOf('/', 1);
1997 if (slp <= 0) break;
1998 tn = tn[0..slp];
2000 return chiroGetOption!int("/mainpane/msgview/monthlimit", 6);
2001 } else {
2002 if (lastDecodedTid == 0) return chiroGetOption!int("/mainpane/msgview/monthlimit", 6);
2003 return chiroGetTagMonthLimit(lastDecodedTagName.getData, 6);
2008 void rescanFolders (bool forced=false) {
2009 if (!.rescanFolders()) { if (!forced) return; }
2010 folderTopIndex = folderCurrIndex = 0;
2011 bool foundTop = false, foundCurr = false;
2012 foreach (immutable idx, const FolderInfo fi; folderList) {
2013 if (!foundTop && fi.name == folderTopTag) { foundTop = true; folderTopIndex = cast(int)idx; }
2014 if (!foundCurr && fi.name == folderCurrTag) { foundCurr = true; folderCurrIndex = cast(int)idx; }
2016 if (!foundTop) folderTopTag.clear();
2017 if (!foundCurr) folderCurrTag.clear();
2020 void folderMakeCurVisible () {
2021 rescanFolders();
2022 if (folderList.length) {
2023 if (folderCurrIndex >= folderList.length) folderCurrIndex = cast(uint)folderList.length-1;
2024 if (folderTopIndex >= folderList.length) folderTopIndex = cast(uint)folderList.length-1;
2025 if (folderCurrIndex-3 < folderTopIndex) {
2026 folderTopIndex = folderCurrIndex-3;
2027 if (folderTopIndex < 0) folderTopIndex = 0;
2029 int hgt = screenHeight/(gxTextHeightUtf+2)-1;
2030 if (hgt < 1) hgt = 1;
2031 if (folderCurrIndex+2 > folderTopIndex+hgt) {
2032 folderTopIndex = (folderCurrIndex+2 > hgt ? folderCurrIndex+2-hgt : 0);
2033 if (folderTopIndex < 0) folderTopIndex = 0;
2035 if (folderTopTag != folderList[folderTopIndex].name) folderTopTag = folderList[folderTopIndex].name;
2036 if (folderCurrTag != folderList[folderCurrIndex].name) folderCurrTag = folderList[folderCurrIndex].name;
2037 } else {
2038 folderCurrIndex = folderTopIndex = 0;
2042 private void switchToFolderTid (const uint tid, bool forced=false) {
2043 //setupTrayAnimation();
2044 if (!forced && tid == lastDecodedTid) return;
2045 if (lastDecodedTid != 0) {
2046 // also, move down if deleted
2047 immutable uint origmsgid = msglistCurrUId;
2048 bool godown = true; // go down first
2049 for (;;) {
2050 int app = chiroGetMessageAppearance(lastDecodedTid, msglistCurrUId);
2051 if (app != Appearance.SoftDeletePurge) break;
2052 immutable uint muid =
2053 (godown ? chiroGetTreePaneTableNextUid(msglistCurrUId) :
2054 chiroGetTreePaneTablePrevUid(msglistCurrUId));
2055 // anyway
2056 threadListPositionDirty();
2057 if (!muid || muid == msglistCurrUId) {
2058 // oops
2059 // restore position
2060 msglistCurrUId = origmsgid;
2061 // change direction
2062 godown = !godown;
2063 if (godown) break; // down again? we're done
2064 } else {
2065 msglistCurrUId = muid;
2068 chiroDeletePurgedWithTag(lastDecodedTid);
2069 saveThreadListPositions();
2071 // rescan
2072 lastDecodedTid = tid;
2073 if (tid != 0) {
2074 lastDecodedTagName = chiroGetTagName(tid);
2075 immutable int monthlimit = getFolderMonthLimit();
2076 chiroCreateTreePaneTable(tid, lastmonthes:monthlimit);
2077 // load position
2078 loadThreadListPositions();
2079 // top
2080 if (!chiroIsTreePaneTableUidValid(msglistTopUId)) {
2081 msglistTopUId = chiroGetTreePaneTableIndex2Uid(0);
2082 threadListPositionDirty();
2084 // current
2085 if (!chiroIsTreePaneTableUidValid(msglistCurrUId)) {
2086 msglistCurrUId = chiroGetTreePaneTableIndex2Uid(0);
2087 threadListPositionDirty();
2089 lastMaxTidUid = chiroGetTreePaneTableMaxUId();
2090 setupUnreadTimer();
2091 } else {
2092 lastDecodedTagName.clear();
2093 msglistTopUId = 0;
2094 msglistCurrUId = 0;
2095 chiroClearTreePaneTable();
2099 void folderSetToIndex (int idx) {
2100 if (idx < 0 || idx >= folderList.length) return;
2101 if (idx == folderCurrIndex) return;
2102 folderCurrIndex = idx;
2103 folderCurrTag = folderList[folderCurrIndex].name;
2104 switchToFolderTid(folderList[folderCurrIndex].tagid);
2107 bool folderUpOne () {
2108 if (folderList.length == 0) return false;
2109 if (folderCurrIndex <= 0) return false;
2110 --folderCurrIndex;
2111 folderCurrTag = folderList[folderCurrIndex].name;
2112 setupUnreadTimer();
2113 return true;
2116 bool folderDownOne () {
2117 if (folderList.length == 0) return false;
2118 if (folderCurrIndex+1 >= cast(int)folderList.length) return false;
2119 ++folderCurrIndex;
2120 folderCurrTag = folderList[folderCurrIndex].name;
2121 setupUnreadTimer();
2122 return true;
2125 bool threadListHome () {
2126 if (lastDecodedTid == 0) return false;
2127 immutable uint firstUid = chiroGetTreePaneTableFirstUid();
2128 if (!firstUid || firstUid == msglistCurrUId) return false;
2129 msglistCurrUId = firstUid;
2130 threadListPositionDirty();
2131 setupUnreadTimer();
2132 return true;
2135 bool threadListEnd () {
2136 if (lastDecodedTid == 0) return false;
2137 immutable uint lastUid = chiroGetTreePaneTableLastUid();
2138 if (!lastUid || lastUid == msglistCurrUId) return false;
2139 msglistCurrUId = lastUid;
2140 threadListPositionDirty();
2141 setupUnreadTimer();
2142 return true;
2145 bool threadListUp () {
2146 import iv.timer;
2147 if (lastDecodedTid == 0) return false;
2148 auto ctm = Timer(true);
2149 immutable uint prevUid = chiroGetTreePaneTablePrevUid(msglistCurrUId);
2150 ctm.stop;
2151 if (ChiroTimerExEnabled) writeln("threadListUp time: ", ctm);
2152 if (!prevUid || prevUid == msglistCurrUId) return false;
2153 msglistCurrUId = prevUid;
2154 threadListPositionDirty();
2155 setupUnreadTimer();
2156 return true;
2159 bool threadListDown () {
2160 import iv.timer;
2161 if (lastDecodedTid == 0) return false;
2162 auto ctm = Timer(true);
2163 immutable uint nextUid = chiroGetTreePaneTableNextUid(msglistCurrUId);
2164 ctm.stop;
2165 if (ChiroTimerExEnabled) writeln("threadListDown time: ", ctm);
2166 if (!nextUid || nextUid == msglistCurrUId) return false;
2167 msglistCurrUId = nextUid;
2168 threadListPositionDirty();
2169 setupUnreadTimer();
2170 return true;
2173 bool threadListScrollUp (bool movecurrent) {
2174 import iv.timer;
2175 if (lastDecodedTid == 0) return false;
2176 auto ctm = Timer(true);
2177 immutable uint topPrevUid = chiroGetTreePaneTablePrevUid(msglistTopUId);
2178 ctm.stop;
2179 if (ChiroTimerExEnabled) conwriteln("threadListScrollUp: prevtop time: ", ctm);
2180 if (!topPrevUid || topPrevUid == msglistTopUId) return false;
2181 ctm.restart;
2182 immutable uint currPrevUid = (movecurrent ? chiroGetTreePaneTablePrevUid(msglistCurrUId) : 0);
2183 ctm.stop;
2184 if (movecurrent && ChiroTimerExEnabled) conwriteln("threadListScrollUp: prevcurr time: ", ctm);
2185 if (movecurrent && !currPrevUid) return false;
2186 msglistTopUId = topPrevUid;
2187 if (movecurrent) {
2188 msglistCurrUId = currPrevUid;
2189 setupUnreadTimer();
2191 threadListPositionDirty();
2192 return true;
2195 bool threadListScrollDown (bool movecurrent) {
2196 import iv.timer;
2197 if (lastDecodedTid == 0) return false;
2198 auto ctm = Timer(true);
2199 immutable uint currNextUid = (movecurrent ? chiroGetTreePaneTableNextUid(msglistCurrUId) : 0);
2200 ctm.stop;
2201 if (movecurrent && ChiroTimerExEnabled) writeln("threadListScrollDown: nextcurr time: ", ctm);
2202 if (movecurrent && (!currNextUid || currNextUid == msglistCurrUId)) return false;
2203 ctm.restart;
2204 immutable uint topNextUid = chiroGetTreePaneTableNextUid(msglistTopUId);
2205 ctm.stop;
2206 if (ChiroTimerExEnabled) writeln("threadListScrollDown: nexttop time: ", ctm);
2207 if (!topNextUid) return false;
2208 msglistTopUId = topNextUid;
2209 if (movecurrent) {
2210 msglistCurrUId = currNextUid;
2211 setupUnreadTimer();
2213 threadListPositionDirty();
2214 return true;
2217 bool threadListPageUp () {
2218 import iv.timer;
2219 bool res = false;
2220 int hgt = guiThreadListHeight/gxTextHeightUtf-1;
2221 if (hgt < 1) hgt = 1;
2222 auto ctm = Timer(true);
2223 foreach (; 0..hgt) {
2224 if (!threadListScrollUp(movecurrent:true)) break;
2225 res = true;
2227 ctm.stop;
2228 if (ChiroTimerExEnabled) writeln("threadListPageUp time: ", ctm);
2229 if (res) setupUnreadTimer();
2230 return res;
2233 bool threadListPageDown () {
2234 import iv.timer;
2235 bool res = false;
2236 int hgt = guiThreadListHeight/gxTextHeightUtf-1;
2237 if (hgt < 1) hgt = 1;
2238 auto ctm = Timer(true);
2239 foreach (; 0..hgt) {
2240 if (!threadListScrollDown(movecurrent:true)) break;
2241 res = true;
2243 ctm.stop;
2244 if (ChiroTimerExEnabled) writeln("threadListPageDown time: ", ctm);
2245 if (res) setupUnreadTimer();
2246 return res;
2250 // //////////////////////////////////////////////////////////////////// //
2251 static struct WebLink {
2252 int ly; // in lines
2253 int x, len; // in pixels
2254 dynstring url;
2255 dynstring text; // visual text
2256 int attachnum = -1;
2257 bool nofirst = false;
2259 @property bool isAttach () const pure nothrow @safe @nogc { return (attachnum >= 0); }
2262 WebLink[] emurls;
2263 int lastUrlIndex = -1;
2265 void appendUrl (in ref WebLink wl) {
2266 immutable oldcap = emurls.capacity;
2267 if (oldcap && emurls.length < oldcap) {
2268 import core.stdc.string : memset;
2269 memset(emurls.ptr+emurls.length, 0, (oldcap-emurls.length)*emurls[0].sizeof);
2271 emurls ~= WebLink();
2272 if (emurls.capacity > oldcap) {
2273 import core.stdc.string : memset;
2274 memset(emurls.ptr+oldcap, 0, (emurls.capacity-oldcap)*emurls[0].sizeof);
2276 emurls[$-1] = wl;
2279 void appendEmLine () {
2280 immutable oldcap = emlines.capacity;
2281 if (oldcap && emlines.length < oldcap) {
2282 import core.stdc.string : memset;
2283 memset(emlines.ptr+emlines.length, 0, (oldcap-emlines.length)*emlines[0].sizeof);
2285 emlines ~= dynstring();
2286 if (emlines.capacity > oldcap) {
2287 import core.stdc.string : memset;
2288 memset(emlines.ptr+oldcap, 0, (emlines.capacity-oldcap)*emlines[0].sizeof);
2292 void appendEmLine (in ref dynstring s) {
2293 appendEmLine();
2294 emlines[$-1] = s;
2297 void appendEmLine (const(char)[] buf) {
2298 appendEmLine();
2299 emlines[$-1] = dynstring(buf);
2302 void clearDecodedText () {
2303 import core.stdc.string : memset;
2304 if (emlines.length) {
2305 //{ import core.stdc.stdio : stderr, fprintf; fprintf(stderr, "000: *** clearing %u emlines (%u) ***\n", cast(uint)emlines.length, cast(uint)emlines.capacity); }
2306 foreach (ref dynstring s; emlines) s.clear();
2307 //{ import core.stdc.stdio : stderr, fprintf; fprintf(stderr, "001: *** clearing %u emlines (%u) ***\n", cast(uint)emlines.length, cast(uint)emlines.capacity); }
2308 immutable maxsz = (emlines.capacity > emlines.length ? emlines.capacity : emlines.length);
2309 memset(emlines.ptr, 0, maxsz*emlines[0].sizeof);
2310 //{ import core.stdc.stdio : stderr, fprintf; fprintf(stderr, "002: *** clearing %u emlines (%u) ***\n", cast(uint)emlines.length, cast(uint)emlines.capacity); }
2311 emlines.length = 0;
2312 //{ import core.stdc.stdio : stderr, fprintf; fprintf(stderr, "003: *** clearing %u emlines (%u) ***\n", cast(uint)emlines.length, cast(uint)emlines.capacity); }
2313 //!if (emlines.capacity) emlines.assumeSafeAppend;
2314 //{ import core.stdc.stdio : stderr, fprintf; fprintf(stderr, "004: *** clearing %u emlines (%u) ***\n", cast(uint)emlines.length, cast(uint)emlines.capacity); }
2315 if (emlines.capacity) memset(emlines.ptr, 0, emlines.capacity*emlines[0].sizeof);
2316 //{ import core.stdc.stdio : stderr, fprintf; fprintf(stderr, "005: *** clearing %u emlines (%u) ***\n", cast(uint)emlines.length, cast(uint)emlines.capacity); }
2318 if (emurls.capacity || emurls.length) {
2319 foreach (ref WebLink l; emurls) { l.url.clear(); l.text.clear(); }
2320 immutable maxsz = (emurls.capacity > emurls.length ? emurls.capacity : emurls.length);
2321 memset(emurls.ptr, 0, maxsz*emurls[0].sizeof);
2322 emurls.length = 0;
2323 //!if (emurls.capacity) emurls.assumeSafeAppend;
2324 if (emurls.capacity) memset(emurls.ptr, 0, emurls.capacity*emurls[0].sizeof);
2326 lastDecodedUId = 0;
2327 articleTextTopLine = 0;
2328 articleDestTextTopLine = 0;
2329 lastUrlIndex = -1;
2330 arttoname.clear();
2331 arttomail.clear();
2332 artfromname.clear();
2333 artfrommail.clear();
2334 artsubj.clear();
2335 arttime.clear();
2338 // <0: not on url
2339 int findUrlIndexAt (int mx, int my) {
2340 int tpX0 = guiGroupListWidth+2+1;
2341 int tpX1 = screenWidth-1-guiMessageTextLPad*2-guiScrollbarWidth;
2342 int tpY0 = guiThreadListHeight+1;
2343 int tpY1 = screenHeight-1;
2345 int y = tpY0+linesInHeader*gxTextHeightUtf+2+1+guiMessageTextVPad;
2347 if (mx < tpX0 || mx > tpX1) return -1;
2348 if (my < y || my > tpY1) return -1;
2350 mx -= tpX0;
2352 // yeah, i can easily calculate this, i know
2353 uint idx = articleTextTopLine;
2354 while (idx < emlines.length && y < screenHeight) {
2355 if (my >= y && my < y+gxTextHeightUtf) {
2356 foreach (immutable uidx, const ref WebLink wl; emurls) {
2357 //conwriteln("checking url [#", uidx, "]; idx=", idx, "; ly=", wl.ly);
2358 if (wl.ly == idx) {
2359 if (mx >= wl.x && mx < wl.x+wl.len) return cast(int)uidx;
2363 ++idx;
2364 y += gxTextHeightUtf+guiMessageTextInterline;
2367 return -1;
2370 WebLink* findUrlAt (int mx, int my) {
2371 auto uidx = findUrlIndexAt(mx, my);
2372 return (uidx >= 0 ? &emurls[uidx] : null);
2375 private void emlDetectUrls (uint textlines) {
2376 lastUrlIndex = -1;
2379 if (textlines > emlines.length) textlines = cast(uint)emlines.length; // just in case
2380 foreach (immutable cy, dynstring s; emlines[0..textlines]) {
2381 if (s.length == 0) continue;
2382 detectUrl(s.getData(), 0, (const(char)[] url, usize spos, usize epos) {
2383 WebLink wl;
2384 wl.nofirst = (spos > 0);
2385 wl.ly = cast(int)cy;
2386 auto kr = GxKerning(4, 0);
2387 s[0..epos].utfByDCharSPos(delegate (dchar ch, usize stpos) {
2388 int w = kr.fixWidthPre(ch);
2389 if (stpos == spos) wl.x = w;
2391 wl.len = kr.finalWidth-wl.x;
2392 wl.url = wl.text = s[spos..epos];
2393 for (;;) {
2394 auto pp = wl.url.indexOf("..");
2395 if (pp < 0) break;
2396 wl.url = wl.url[0..pp]~wl.url[pp+1..$];
2398 appendUrl(wl); //emurls ~= wl;
2399 return true; // go on
2403 int attachcount = 0;
2404 foreach (immutable uint cy; textlines..cast(uint)emlines.length) {
2405 dynstring s = emlines[cy];
2406 if (s.length == 0) continue;
2407 auto spos = s.indexOf("attach:");
2408 if (spos < 0) continue;
2409 auto epos = spos+7;
2410 while (epos < s.length && s.ptr[epos] > ' ') ++epos;
2411 //if (attachcount >= parts.length) break;
2412 WebLink wl;
2413 wl.nofirst = (spos > 0);
2414 wl.ly = cast(int)cy;
2415 //wl.x = gxTextWidthUtf(s[0..spos]);
2416 //wl.len = gxTextWidthUtf(s[spos..epos]);
2417 auto kr = GxKerning(4, 0);
2418 s[0..epos].utfByDCharSPos(delegate (dchar ch, usize stpos) {
2419 int w = kr.fixWidthPre(ch);
2420 if (stpos == spos) wl.x = w;
2422 wl.len = kr.finalWidth-wl.x;
2423 wl.url = wl.text = s[spos..epos];
2424 //if (spos > 0) ++wl.x; // this makes text bolder, no need to
2425 wl.attachnum = attachcount;
2426 //wl.attachfname = s[spos+7..epos];
2427 //wl.part = parts[attachcount];
2428 ++attachcount;
2429 appendUrl(wl); //emurls ~= wl;
2433 bool needToDecodeArticleTextNL (uint uid) const nothrow @trusted @nogc {
2434 return (lastDecodedUId != uid);
2437 // fld is locked here
2438 void decodeArticleTextNL (uint uid) {
2439 static auto stmtGet = LazyStatement!"View"(`
2440 SELECT
2441 from_name AS fromName
2442 , from_mail AS fromMail
2443 , to_name AS toName
2444 , to_mail AS toMail
2445 , subj AS subj
2446 , datetime(threads.time, 'unixepoch') AS time
2447 , ChiroUnpack(content_text.content) AS text
2448 , ChiroUnpack(content_html.content) AS html
2449 FROM info
2450 INNER JOIN threads USING(uid)
2451 INNER JOIN content_text USING(uid)
2452 INNER JOIN content_html USING(uid)
2453 WHERE uid=:uid
2454 LIMIT 1
2455 ;`);
2457 if (!needToDecodeArticleTextNL(uid)) return;
2459 //if (uid == 0) { clearDecodedText(); return; }
2460 //conwriteln("200: em.len=", emlines.length);
2461 clearDecodedText();
2462 //conwriteln("201: em.len=", emlines.length);
2463 lastDecodedUId = uid;
2465 // get article content
2466 //FIXME: see `art.getTextContent()` for GPG decryption!
2467 DynStr artcontent;
2468 bool ishtml = false;
2469 bool htmlheader = false;
2470 foreach (auto row; stmtGet.st.bind(":uid", uid).range) {
2471 auto text = row.text!SQ3Text;
2472 auto html = row.html!SQ3Text;
2473 bool isHtml = ((text.xstrip.length == 0 || preferHtmlContent) && html.xstrip.length != 0);
2474 bool forceHtml = false;
2475 if (detectHtmlContent && !isHtml && html.xstrip.length == 0 && text.xstrip.length != 0) {
2476 auto tmp = text.xstrip;
2477 if (tmp.startsWithCI("<!DOCTYPE")) forceHtml = true;
2479 //conwriteln("! ", text.xstrip.length, " ! ", html.xstrip.length);
2480 if (isHtml || forceHtml) {
2481 version(article_can_into_html) {
2482 try {
2483 string s = htmlToText((forceHtml ? text.idup : html.idup), false);
2484 //conwriteln("000: ac.len=", artcontent.length);
2485 artcontent ~= s;
2486 //conwriteln("001: ac.len=", artcontent.length);
2487 artcontent.removeASCIICtrls();
2488 //conwriteln("002: ac.len=", artcontent.length);
2489 htmlheader = true;
2490 } catch (Exception e) {
2491 artcontent ~= (forceHtml ? text : html);
2493 } else {
2494 artcontent ~= (forceHtml ? text : html);
2496 ishtml = true;
2497 } else if (text.length != 0) {
2498 artcontent ~= text;
2499 } else {
2500 artcontent ~= "no text content";
2502 arttoname = row.toName!SQ3Text;
2503 arttomail = row.toMail!SQ3Text;
2504 artfromname = row.fromName!SQ3Text;
2505 artfrommail = row.fromMail!SQ3Text;
2506 artsubj = row.subj!SQ3Text;
2507 arttime = row.time!SQ3Text;
2508 if (artsubj.length == 0) artsubj = "no subject";
2511 if (artcontent.length == 0) return; // no text
2512 //conwriteln("100: ac.len=", artcontent.length, "; em.len=", emlines.length);
2513 appendEmLine(); //emlines ~= dynstring(); // hack; this dummy line will be removed
2514 //conwriteln("101: ac.len=", artcontent.length, "; em.len=", emlines.length);
2515 bool skipEmptyLines = true;
2517 if (htmlheader) {
2518 appendEmLine("\x01==============================================");
2519 appendEmLine("\x01--- HTML CONTENT ---");
2520 appendEmLine("\x01==============================================");
2521 //emlines ~= null;
2524 bool lastEndsWithSpace () { return (emlines[$-1].length ? emlines[$-1][$-1] == ' ' : false); }
2526 int lastQLevel = 0;
2528 static dynstring addQuotes (dynstring s, int qlevel) {
2529 enum QuoteStr = ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ";
2530 if (qlevel <= 0) return s;
2531 if (qlevel > QuoteStr.length-1) qlevel = cast(int)QuoteStr.length-1;
2532 return dynstring(QuoteStr[$-qlevel-1..$])~s;
2535 // returns quote level
2536 static int removeQuoting (ref ConString s) {
2537 // calculate quote level
2538 int qlevel = 0;
2539 if (s.length && s[0] == '>') {
2540 usize lastqpos = 0, pos = 0;
2541 while (pos < s.length) {
2542 if (s.ptr[pos] != '>') {
2543 if (s.ptr[pos] != ' ') break;
2544 } else {
2545 lastqpos = pos;
2546 ++qlevel;
2548 ++pos;
2550 if (s.length-lastqpos > 1 && s.ptr[lastqpos+1] == ' ') ++lastqpos;
2551 ++lastqpos;
2552 s = s[lastqpos..$];
2554 return qlevel;
2557 bool inCode = false;
2559 void putLine (ConString s) {
2560 int qlevel = (ishtml ? 0 : removeQuoting(s));
2561 //conwriteln("qlevel=", qlevel, "; s=[", s, "]");
2562 // empty line: just insert it
2563 if (s.length == 0) {
2564 if (skipEmptyLines) return;
2565 if (qlevel == 0 && emlines[$-1].xstripright.length == 0) return;
2566 appendEmLine(addQuotes(dynstring(), qlevel).xstripright);
2567 } else {
2568 if (s.xstrip.length == 0) {
2569 if (skipEmptyLines) return;
2570 if (qlevel == 0 && emlines[$-1].xstripright.length == 0) return;
2572 skipEmptyLines = false;
2573 // join code lines if it is possible
2574 if (inCode && qlevel == lastQLevel && lastEndsWithSpace) {
2575 //conwriteln("<", s, ">");
2576 emlines[$-1] ~= addQuotes(dynstring(s.xstrip), qlevel);
2577 return;
2579 // two spaces at the beginning usually means "this is code"; don't wrap it
2580 if (s.length >= 1 && s[0] == '\t') {
2581 appendEmLine(addQuotes(dynstring(s), qlevel));
2582 // join next lines if it is possible
2583 inCode = true;
2584 //conwriteln("[", s, "]");
2585 lastQLevel = qlevel;
2586 return;
2588 inCode = false;
2589 // can we append?
2590 bool newline = false;
2591 if (lastQLevel != qlevel || !lastEndsWithSpace) {
2592 newline = true;
2593 } else {
2594 // append words
2595 //while (s.length > 1 && s.ptr[0] <= ' ') s = s[1..$];
2597 while (s.length) {
2598 usize epos = 0;
2599 if (newline) {
2600 while (epos < s.length && s.ptr[epos] <= ' ') ++epos;
2601 } else {
2602 //assert(s[0] > ' ');
2603 while (epos < s.length && s.ptr[epos] <= ' ') ++epos;
2605 while (epos < s.length && s.ptr[epos] > ' ') ++epos;
2606 auto xlen = epos;
2607 while (epos < s.length && s.ptr[epos] <= ' ') ++epos;
2608 if (!newline && emlines[$-1].length+xlen <= 80) {
2609 // no wrapping, continue last line
2610 emlines[$-1] ~= s[0..epos];
2611 } else {
2612 newline = false;
2613 // wrapping; new line
2614 appendEmLine(addQuotes(dynstring(s[0..epos]), qlevel));
2616 s = s[epos..$];
2618 if (newline) appendEmLine(addQuotes(dynstring(), qlevel));
2620 lastQLevel = qlevel;
2623 try {
2624 //foreach (ConString s; LineIterator!false(art.getTextContent)) putLine(s);
2625 const(char)[] buf = artcontent;
2626 while (buf.length) {
2627 usize epos = skipOneLine(buf, 0);
2628 usize eend = epos;
2629 if (eend >= 2 && buf[eend-2] == '\r' && buf[eend-1] == '\n') eend -= 2;
2630 else if (eend >= 1 && buf[eend-1] == '\n') eend -= 1;
2631 putLine(buf[0..eend]);
2632 buf = buf[epos..$];
2634 // remove first dummy line
2635 if (emlines.length) emlines = emlines[1..$];
2636 // remove trailing empty lines
2637 while (emlines.length && emlines[$-1].xstrip.length == 0) emlines.length -= 1;
2638 } catch (Exception e) {
2639 conwriteln("================================= ERROR: ", e.msg, " =================================");
2640 conwriteln(e.toString);
2644 // attaches
2645 auto lcount = cast(uint)emlines.length;
2646 emlinesBeforeAttaches = lcount;
2648 uint attcount = 0;
2649 static auto statAttaches = LazyStatement!"View"(`
2650 SELECT
2651 idx AS idx
2652 , mime AS mime
2653 , name AS name
2654 FROM attaches
2655 WHERE uid=:uid
2656 ORDER BY idx
2657 ;`);
2658 foreach (auto row; statAttaches.st.bind(":uid", uid).range) {
2659 import core.stdc.stdio : snprintf;
2660 if (attcount == 0) { appendEmLine(); appendEmLine(); }
2661 DynStr att;
2662 char[128] buf = void;
2663 //if (type.length == 0) type = "unknown/unknown";
2664 //string s = " [%02s] attach:%s -- %s".format(attcount, Article.fixAttachmentName(filename), type);
2665 auto mime = row.mime!SQ3Text;
2666 auto name = row.name!SQ3Text/*.decodeSubj*/;
2667 auto len = snprintf(buf.ptr, buf.sizeof, " [%2u] attach:%.*s -- %.*s",
2668 attcount, cast(uint)name.length, name.ptr, cast(uint)mime.length, mime.ptr);
2669 assert(len > 0);
2670 if (len > buf.sizeof) len = cast(int)buf.sizeof;
2671 appendEmLine(buf[0..len]);
2672 ++attcount;
2674 /*FIXME
2675 art.forEachAttachment(delegate(ConString type, ConString filename) {
2676 if (attcount == 0) { emlines ~= null; emlines ~= null; }
2677 import std.format : format;
2678 if (type.length == 0) type = "unknown/unknown";
2679 string s = " [%02s] attach:%s -- %s".format(attcount, Article.fixAttachmentName(filename), type);
2680 emlines ~= s;
2681 ++attcount;
2682 return false;
2685 emlDetectUrls(lcount);
2688 @property int visibleArticleLines () {
2689 int y = guiThreadListHeight+1+linesInHeader*gxTextHeightUtf+2+guiMessageTextVPad;
2690 return (screenHeight-y)/(gxTextHeightUtf+guiMessageTextInterline);
2693 void normalizeArticleTopLine () {
2694 int lines = visibleArticleLines;
2695 if (lines < 1 || emlines.length <= lines) {
2696 articleTextTopLine = 0;
2697 articleDestTextTopLine = 0;
2698 } else {
2699 if (articleTextTopLine < 0) articleTextTopLine = 0;
2700 if (articleTextTopLine+lines > emlines.length) {
2701 articleTextTopLine = cast(int)emlines.length-lines;
2702 if (articleTextTopLine < 0) articleTextTopLine = 0;
2707 void doScrollStep () {
2708 auto oldtop = articleTextTopLine;
2709 foreach (immutable _; 0..6) {
2710 normalizeArticleTopLine();
2711 if (articleDestTextTopLine < articleTextTopLine) {
2712 --articleTextTopLine;
2713 } else if (articleDestTextTopLine > articleTextTopLine) {
2714 ++articleTextTopLine;
2715 } else {
2716 break;
2718 normalizeArticleTopLine();
2720 if (articleTextTopLine == oldtop) {
2721 // can't scroll anymore
2722 articleDestTextTopLine = articleTextTopLine;
2723 return;
2725 postScreenRebuild();
2726 postArticleScroll();
2729 void scrollBy (int delta) {
2730 articleDestTextTopLine += delta;
2731 doScrollStep();
2734 void scrollByPageUp () {
2735 int lines = visibleArticleLines-scrollKeepLines;
2736 if (lines < 1) lines = 1;
2737 scrollBy(-lines);
2740 void scrollByPageDown () {
2741 int lines = visibleArticleLines-scrollKeepLines;
2742 if (lines < 1) lines = 1;
2743 scrollBy(lines);
2746 // ////////////////////////////////////////////////////////////////// //
2747 // this also fixes current/top uids
2748 void getAndFixThreadListIndicies (out int topidx, out int curridx) {
2749 int hgt = guiThreadListHeight/gxTextHeightUtf-1;
2750 if (hgt < 1) hgt = 1;
2752 topidx = chiroGetTreePaneTableUid2Index(msglistTopUId);
2753 immutable origTopIdx = topidx;
2754 if (topidx < 0) topidx = 0;
2755 curridx = chiroGetTreePaneTableUid2Index(msglistCurrUId);
2756 immutable origCurrIdx = curridx;
2757 if (curridx < 0) curridx = 0;
2759 //conwriteln("topuid: ", msglistTopUId, "; topidx=", topidx);
2760 //conwriteln("curruid: ", msglistCurrUId, "; curridx=", curridx);
2762 if (curridx-3 < topidx) {
2763 topidx = curridx-3;
2764 if (topidx < 0) topidx = 0;
2766 if (curridx+3 > topidx+hgt) {
2767 topidx = (curridx+3 > hgt ? curridx+3-hgt : 0);
2768 if (topidx < 0) topidx = 0;
2771 if (origCurrIdx != curridx || msglistCurrUId == 0) {
2772 immutable ocurr = msglistCurrUId;
2773 msglistCurrUId = chiroGetTreePaneTableIndex2Uid(curridx);
2774 if (ocurr != msglistCurrUId) {
2775 threadListPositionDirty();
2776 setupUnreadTimer();
2780 if (origTopIdx != topidx || msglistTopUId == 0) {
2781 immutable otop = msglistTopUId;
2782 msglistTopUId = chiroGetTreePaneTableIndex2Uid(topidx);
2783 if (otop != msglistTopUId) threadListPositionDirty();
2787 void setupUnreadTimer () {
2788 postMarkAsUnreadEvent();
2791 // //////////////////////////////////////////////////////////////////// //
2792 //TODO: move parts to widgets
2793 override void onPaint () {
2794 viewDataVersion = dbView.getDataVersion();
2795 gxClipReset();
2797 gxFillRect(0, 0, guiGroupListWidth, screenHeight, getColor("grouplist-back"));
2798 gxVLine(guiGroupListWidth, 0, screenHeight, getColor("grouplist-divline"));
2800 gxFillRect(guiGroupListWidth+1, 0, screenWidth, guiThreadListHeight, getColor("threadlist-back"));
2801 gxHLine(guiGroupListWidth+1, guiThreadListHeight, screenWidth, getColor("threadlist-divline"));
2803 // ////////////////////////////////////////////////////////////////// //
2804 void drawArticle (uint uid) {
2805 import core.stdc.stdio : snprintf;
2806 import std.format : format;
2807 import std.datetime;
2808 char[128] tbuf;
2809 const(char)[] tbufs;
2811 void xfmt (string s, const(char)[][] strs...) {
2812 int dpos = 0;
2813 void puts (const(char)[] s...) {
2814 foreach (char ch; s) {
2815 if (dpos >= tbuf.length) break;
2816 tbuf[dpos++] = ch;
2819 while (s.length) {
2820 if (strs.length && s.length > 1 && s[0] == '%' && s[1] == 's') {
2821 puts(strs[0]);
2822 strs = strs[1..$];
2823 s = s[2..$];
2824 } else {
2825 puts(s[0]);
2826 s = s[1..$];
2829 tbufs = tbuf[0..dpos];
2832 if (needToDecodeArticleTextNL(uid)) {
2833 decodeArticleTextNL(uid);
2837 gxClipX0 = guiGroupListWidth+2;
2838 gxClipX1 = screenWidth-1;
2839 gxClipY0 = guiThreadListHeight+1;
2840 gxClipY1 = screenHeight-1;
2842 gxClipRect = GxRect(GxPoint(guiGroupListWidth+2, guiThreadListHeight+1), GxPoint(screenWidth-1, screenHeight-1));
2844 int msx = lastMouseX;
2845 int msy = lastMouseY;
2847 int curDrawYMul = 1;
2849 // header
2850 immutable int hdrHeight = (3+(arttoname.length || arttomail.length ? 1 : 0))*gxTextHeightUtf+2;
2851 gxFillRect(gxClipRect.x0, gxClipRect.y0, gxClipRect.x1-gxClipRect.x0+1, hdrHeight, getColor("msg-header-back"));
2853 if (artfromname.length) {
2854 xfmt("From: %s <%s>", artfromname, artfrommail);
2855 } else {
2856 xfmt("From: %s", artfrommail);
2858 gxDrawTextUtf(gxClipRect.x0+guiMessageTextLPad, gxClipRect.y0+0*gxTextHeightUtf+1, tbufs, getColor("msg-header-from"));
2859 if (arttoname.length || arttomail.length) {
2860 if (arttoname.length) {
2861 xfmt("To: %s <%s>", arttoname, arttomail);
2862 } else {
2863 xfmt("To: %s", arttomail);
2865 gxDrawTextUtf(gxClipRect.x0+guiMessageTextLPad, gxClipRect.y0+curDrawYMul*gxTextHeightUtf+1, tbufs, getColor("msg-header-to"));
2866 ++curDrawYMul;
2868 xfmt("Subject: %s", (artsubj.length ? artsubj : "no subject"));
2869 gxDrawTextUtf(gxClipRect.x0+guiMessageTextLPad, gxClipRect.y0+curDrawYMul*gxTextHeightUtf+1, tbufs, getColor("msg-header-subj"));
2870 ++curDrawYMul;
2872 //auto t = SysTime.fromUnixTime(arttime);
2873 //auto tlen = snprintf(tbuf.ptr, tbuf.length, "Date: %04d/%02d/%02d %02d:%02d:%02d", t.year, t.month, t.day, t.hour, t.minute, t.second);
2874 auto tlen = snprintf(tbuf.ptr, tbuf.length, "Date: %.*s", cast(uint)arttime.length, arttime.ptr);
2875 gxDrawTextUtf(gxClipRect.x0+guiMessageTextLPad, gxClipRect.y0+curDrawYMul*gxTextHeightUtf+1, tbuf[0..tlen], getColor("msg-header-date"));
2876 ++curDrawYMul;
2880 // text
2881 linesInHeader = curDrawYMul;
2882 int y = gxClipRect.y0+curDrawYMul*gxTextHeightUtf+2;
2884 gxHLine(gxClipRect.x0, y, gxClipRect.x1-gxClipRect.x0+1, getColor("msg-header-divline"));
2885 ++y;
2886 gxFillRect(gxClipRect.x0, y, gxClipRect.x1-gxClipRect.x0+1, screenHeight-y, getColor("msg-text-back"));
2887 y += guiMessageTextVPad;
2889 immutable sty = y;
2891 normalizeArticleTopLine();
2893 bool drawUpMark = (articleTextTopLine > 0);
2894 bool drawDownMark = false;
2896 immutable uint messageTextNormalColor = getColor("msg-text-text");
2897 immutable uint messageTextQuote0Color = getColor("msg-text-quote0");
2898 immutable uint messageTextQuote1Color = getColor("msg-text-quote1");
2899 immutable uint messageTextHtmlHeaderColor = getColor("msg-text-html-sign");
2900 immutable uint messageTextLinkColor = getColor("msg-text-link");
2901 immutable uint messageTextLinkHoverColor = getColor("msg-text-link-hover");
2902 immutable uint messageTextLinkPressedColor = getColor("msg-text-link-pressed");
2904 uint idx = articleTextTopLine;
2905 bool msvisible = isMouseVisible;
2906 bool checkQuotes = true;
2907 if (emlines.length && emlines[0].length && emlines[0][0] == 1) {
2908 // html content
2909 checkQuotes = false;
2911 while (idx < emlines.length && y < screenHeight) {
2912 int qlevel = 0;
2913 dynstring s = emlines[idx];
2915 if (checkQuotes) {
2916 foreach (immutable char ch; s) {
2917 if (ch <= ' ') continue;
2918 if (ch != '>') break;
2919 ++qlevel;
2923 uint clr = messageTextNormalColor;
2924 if (qlevel) {
2925 final switch (qlevel%2) {
2926 case 0: clr = messageTextQuote0Color; break;
2927 case 1: clr = messageTextQuote1Color; break;
2931 if (!checkQuotes && s.length && s[0] == 1) {
2932 clr = messageTextHtmlHeaderColor;
2933 s = s[1..$];
2936 gxDrawTextUtfOpt(GxDrawTextOptions.TabColor(4, clr), gxClipRect.x0+guiMessageTextLPad, y, s);
2938 foreach (const ref WebLink wl; emurls) {
2939 if (wl.ly == idx) {
2940 uint lclr = messageTextLinkColor;
2941 if (msvisible && msy >= y && msy < y+gxTextHeightUtf &&
2942 msx >= gxClipRect.x0+1+guiMessageTextLPad+wl.x &&
2943 msx < gxClipRect.x0+1+guiMessageTextLPad+wl.x+wl.len)
2945 lclr = (lastMouseLeft ? messageTextLinkPressedColor : messageTextLinkHoverColor);
2946 //lclr = getColor("msg-text-link", (lastMouseLeft ? "pressed" : "hover"));
2948 gxDrawTextUtfOpt(GxDrawTextOptions.TabColorFirstFull(4, lclr, wl.nofirst), gxClipRect.x0+guiMessageTextLPad+wl.x, y, wl.text);
2952 if (gxClipRect.y1-y < gxTextHeightUtf && emlines.length-idx > 0) drawDownMark = true;
2954 ++idx;
2955 y += gxTextHeightUtf+guiMessageTextInterline;
2958 //gxDrawTextOutScaledUtf(1, gxClipRect.x1-gxTextWidthUtf(triangleDownStr)-3, sty, triangleDownStr, (drawUpMark ? gxRGB!(255, 255, 255) : gxRGB!(85, 85, 85)), gxRGB!(0, 69, 69));
2959 //gxDrawTextOutScaledUtf(1, gxClipRect.x1-gxTextWidthUtf(triangleUpStr)-3, gxClipRect.y1-7, triangleUpStr, (drawDownMark ? gxRGB!(255, 255, 255) : gxRGB!(85, 85, 85)), gxRGB!(0, 69, 69));
2961 gxDrawScrollBar(GxRect(gxClipRect.x1-10, sty+10, 5, gxClipRect.y1-sty-17), cast(int)emlines.length-1, idx-1);
2963 bool twited = false;
2964 DynStr twittext = chiroGetMessageTwit(lastDecodedTid, uid, out twited);
2965 if (twited) {
2966 immutable uint clr = getColor("twit-shade");
2968 foreach (immutable dy; gxClipRect.y0+3*gxTextHeightUtf+2..gxClipRect.y1+1) {
2969 foreach (immutable dx; gxClipRect.x0..gxClipRect.x1+1) {
2970 if ((dx^dy)&1) gxPutPixel(dx, dy, clr);
2974 GxRect rc = gxClipRect;
2975 rc.y0 = rc.y0+3*gxTextHeightUtf+2;
2976 gxDashRect(rc, clr);
2978 if (twittext.length) {
2979 immutable ofdz = egraFontSize;
2980 scope(exit) egraFontSize = ofdz;
2981 egraFontSize = 150;
2982 int tx = gxClipRect.x0+(gxClipRect.width-gxTextWidthUtf(twittext))/2-1;
2983 int ty = gxClipRect.y0+(gxClipRect.height-gxTextHeightUtf)/2-1;
2984 gxDrawTextOutUtf(tx, ty, twittext, getColor("twit-text"), getColor("twit-outline"));
2989 // ////////////////////////////////////////////////////////////////// //
2990 void drawThreadList () {
2991 uint tid = 0;
2992 if (folderCurrIndex >= 0 && folderCurrIndex < folderList.length) tid = folderList[folderCurrIndex].tagid;
2993 switchToFolderTid(tid);
2995 // find indicies
2996 int topidx, curridx;
2997 getAndFixThreadListIndicies(out topidx, out curridx);
2999 int hgt = (guiThreadListHeight+gxTextHeightUtf-1)/gxTextHeightUtf;
3000 if (hgt < 1) hgt = 1;
3002 gxClipRect.x0 = guiGroupListWidth+2;
3003 gxClipRect.x1 = screenWidth-1-5;
3004 gxClipRect.y0 = 0;
3005 gxClipRect.y1 = guiThreadListHeight-1;
3006 immutable uint origX0 = gxClipRect.x0;
3007 immutable uint origX1 = gxClipRect.x1;
3008 immutable uint origY0 = gxClipRect.y0;
3009 immutable uint origY1 = gxClipRect.y1;
3010 int y = 0;
3012 static uint darkenBy (in uint clr, in int val) pure nothrow @safe @nogc {
3013 pragma(inline, true);
3014 return
3015 val ?
3016 (clr&0xff_00_00_00)|
3017 (cast(uint)clampToByte(cast(int)(cast(ubyte)(clr>>16))-val)<<16)|
3018 (cast(uint)clampToByte(cast(int)(cast(ubyte)(clr>>8))-val)<<8)|
3019 (cast(uint)clampToByte(cast(int)(cast(ubyte)clr)-val)) :
3020 clr;
3023 chiroGetPaneTablePage(topidx, hgt,
3024 delegate (int pgofs, /* offset from the page start, from zero and up to `limit` */
3025 int iid, /* item id, never zero */
3026 uint uid, /* msguid, never zero */
3027 uint parentuid, /* parent msguid, may be zero */
3028 uint level, /* threading level, from zero */
3029 Appearance appearance, /* see above */
3030 Mute mute, /* see above */
3031 SQ3Text date, /* string representation of receiving date and time */
3032 SQ3Text subj, /* message subject, can be empty string */
3033 SQ3Text fromName, /* message sender name, can be empty string */
3034 SQ3Text fromMail, /* message sender email, can be empty string */
3035 SQ3Text title) /* title from twiting */
3037 import std.format : format;
3038 import std.datetime;
3040 if (y >= guiThreadListHeight) return;
3041 if (subj.length == 0) subj = "no subject";
3043 gxClipRect.x0 = origX0;
3044 gxClipRect.x1 = origX1;
3046 int darken = (level != 0 && appearance != Appearance.Unread ? 40 : 0);
3048 string style = "normal";
3049 if (appearance == Appearance.Unread) {
3050 style = "unread";
3051 darken = 0;
3052 } else {
3053 if (mute > Mute.Normal) { style = "twit"; darken = 0; }
3055 if (isSoftDeleted(appearance)) {
3056 darken = 0;
3057 style = (appearance == Appearance.SoftDeletePurge ? "hard-del" : "soft-del");
3060 char[64] stfull = void;
3061 usize stpos = 0;
3062 if (uid == msglistCurrUId) {
3063 static immutable string sc = "cursor-";
3064 stpos = sc.length;
3065 stfull[0..stpos] = sc;
3067 stfull[stpos..stpos+style.length] = style;
3068 const(char)[] stname = stfull[0..stpos+style.length];
3070 char[128] stx = void;
3071 const(char)[] buildStyle (const(char)[] stt) {
3072 static immutable string sc = "threadlist-";
3073 stx[0..sc.length] = sc;
3074 usize xpos = sc.length;
3075 stx[xpos..xpos+stname.length] = stname;
3076 xpos += stname.length;
3077 stx[xpos++] = '-';
3078 stx[xpos..xpos+stt.length] = stt;
3079 xpos += stt.length;
3080 return stx[0..xpos];
3083 //conwriteln("STNAME: <", stname, ">; darken=", darken);
3085 immutable uint clrBack = getColor(buildStyle("back"));
3086 immutable uint clrOut = getColor(buildStyle("outline"));
3087 immutable uint clrFrom = darkenBy(getColor(buildStyle("from-text")), darken);
3088 immutable uint clrMail = darkenBy(getColor(buildStyle("mail-text")), darken);
3089 immutable uint clrSubj = darkenBy(getColor(buildStyle("subj-text")), darken);
3090 immutable uint clrTime = darkenBy(getColor(buildStyle("time-text")), darken);
3092 // background
3093 if (!gxIsTransparent(clrBack)) gxFillRect(gxClipRect.x0, y, gxClipRect.width-1, gxTextHeightUtf, clrBack);
3094 gxClipRect.x0 = gxClipRect.x0+1;
3095 gxClipRect.x1 = gxClipRect.x1-1;
3097 // time
3098 int timewdt = gxDrawTextOutUtf(gxClipRect.x1-gxTextWidthUtf(date), y, date, clrTime, clrOut);
3099 if (timewdt%8) timewdt = (timewdt|7)+1;
3101 SQ3Text from = fromName;
3103 auto vp = from.indexOf(" via Digitalmars-");
3104 if (vp > 0) {
3105 from = from[0..vp].xstrip;
3106 if (from.length == 0) from = "anonymous";
3110 // from/mail
3111 gxClipRect.x1 = gxClipRect.x1-/*(13*6+4)*2+33*/timewdt;
3112 enum FromWidth = 22*6*2+88;
3113 gxDrawTextOutUtf(gxClipRect.x1-FromWidth, y, from, clrFrom, clrOut);
3114 gxDrawTextOutUtf(gxClipRect.x1-FromWidth+gxTextWidthUtf(from)+4, y, "<", clrMail, clrOut);
3115 gxDrawTextOutUtf(gxClipRect.x1-FromWidth+gxTextWidthUtf(from)+4+gxTextWidthUtf("<")+1, y, fromMail, clrMail, clrOut);
3116 gxDrawTextOutUtf(gxClipRect.x1-FromWidth+gxTextWidthUtf(from)+4+gxTextWidthUtf("<")+1+gxTextWidthUtf(fromMail)+1, y, ">", clrMail, clrOut);
3117 gxClipRect.x1 = gxClipRect.x1-FromWidth-6;
3119 // subj
3120 gxDrawTextOutUtf(gxClipRect.x0+level*3, y, subj, clrSubj, clrOut);
3122 // nesting dots
3123 if (level) {
3124 immutable uint clrDot = getColor(buildStyle("dots"));
3125 foreach (immutable dx; 0..level) gxPutPixel(gxClipRect.x0+1+dx*3, y+gxTextHeightUtf/2, clrDot);
3128 // deleted strike line
3129 if (isSoftDeleted(appearance)) {
3130 immutable uint clrLine = getColor(buildStyle("strike-line"));
3131 if (!gxIsTransparent(clrLine)) {
3132 gxClipRect.x0 = origX0;
3133 gxClipRect.x1 = origX1;
3134 gxHLine(gxClipRect.x0, y+gxTextHeightUtf/2, gxClipRect.x1-gxClipRect.x0+1, clrLine);
3135 if (appearance == Appearance.SoftDeletePurge) {
3136 gxHLine(gxClipRect.x0, y+gxTextHeightUtf/2+1, gxClipRect.x1-gxClipRect.x0+1, clrLine);
3141 y += gxTextHeightUtf;
3145 // draw progressbar
3146 if (msglistCurrUId) {
3147 gxClipRect.x0 = origX0;
3148 gxClipRect.x1 = origX1+5;
3149 gxClipRect.y0 = origY0;
3150 gxClipRect.y1 = origY1;
3151 gxDrawScrollBar(GxRect(gxClipRect.x1-5, gxClipRect.y0, 4, gxClipRect.height-1),
3152 cast(int)chiroGetTreePaneTableCount()-1, curridx);
3155 drawArticle(msglistCurrUId);
3158 // ////////////////////////////////////////////////////////////////// //
3159 void drawFolders () {
3160 immutable uint clrNormal = getColor("grouplist-normal-text");
3161 immutable uint clrNormalCursor = getColor("grouplist-cursor-normal-text");
3162 immutable uint clrNormalChild = getColor("grouplist-normal-child-text");
3163 immutable uint clrNormalChildCursor = getColor("grouplist-cursor-normal-child-text");
3164 immutable uint clrDots = getColor("grouplist-dots");
3165 immutable uint clrNormOutline = getColor("grouplist-outline");
3166 immutable uint clrCurOutline = getColor("grouplist-cursor-outline");
3168 folderMakeCurVisible();
3169 int ofsx = 2;
3170 int ofsy = 1;
3171 foreach (immutable idx, const FolderInfo fi; folderList) {
3172 if (idx < folderTopIndex) continue;
3173 if (ofsy >= screenHeight) break;
3174 gxClipReset();
3176 immutable int depth = fi.depth;
3177 uint clr = (depth ? clrNormalChild : clrNormal);
3178 uint clrOut = clrNormOutline;
3180 immutable bool isCursor = (idx == folderCurrIndex);
3181 if (isCursor) {
3182 gxFillRect(0, ofsy-1, guiGroupListWidth, (gxTextHeightUtf+2), getColor("grouplist-cursor-back"));
3183 clr = (depth ? clrNormalChildCursor : clrNormalCursor);
3184 clrOut = clrCurOutline;
3186 gxClipRect.x0 = ofsx-1;
3187 gxClipRect.y0 = ofsy;
3188 gxClipRect.x1 = guiGroupListWidth-3;
3190 if (fi.unreadCount) {
3191 clr = getColor(isCursor ? "grouplist-cursor-unread-text" : "grouplist-unread-text");
3192 } else if (depth == 0) {
3193 if (fi.name == "#spam") clr = getColor(isCursor ? "grouplist-cursor-spam-text" : "grouplist-spam-text");
3194 else if (fi.name == "/accounts") clr = getColor(isCursor ? "grouplist-cursor-accounts-text" : "grouplist-accounts-text");
3195 } else if (depth == 1 && fi.name.startsWith("/accounts/")) {
3196 clr = getColor(isCursor ? "grouplist-cursor-accounts-child-text" : "grouplist-accounts-child-text");
3197 } else if (fi.name.startsWith("/accounts/") && fi.name.endsWith("/inbox")) {
3198 clr = getColor(isCursor ? "grouplist-cursor-inbox-text" : "grouplist-inbox-text");
3200 foreach (immutable dd; 0..depth) gxPutPixel(ofsx+dd*6+2, ofsy+gxTextHeightUtf/2, clrDots);
3201 gxDrawTextOutUtf(ofsx+depth*6, ofsy, fi.visname, clr, clrOut);
3202 ofsy += gxTextHeightUtf+2;
3206 drawFolders();
3207 drawThreadList();
3208 //setupTrayAnimation();
3210 version(test_round_rect) {
3211 gxClipReset();
3212 gxFillRoundedRect(lastMouseX-16, lastMouseY-16, 128, 96, rrad, /*gxSolidWhite*/gxRGBA!(0, 255, 0, 127));
3213 //gxDrawRoundedRect(lastMouseX-16, lastMouseY-16, 128, 96, rrad, gxRGBA!(0, 255, 0, 127));
3217 version(test_round_rect) {
3218 int rrad = 16;
3221 override bool onKeySink (KeyEvent event) {
3222 if (event.pressed) {
3223 version(test_round_rect) {
3224 if (event == "Plus") { ++rrad; postScreenRebuild(); return true; }
3225 if (event == "Minus") { --rrad; postScreenRebuild(); return true; }
3227 if (dbg_dump_keynames) conwriteln("key: ", event.toStr, ": ", event.modifierState&ModifierState.windows);
3228 //foreach (const ref kv; mainAppKeyBindings.byKeyValue) if (event == kv.key) concmd(kv.value);
3229 char[64] kname;
3230 if (auto cmdp = event.toStrBuf(kname[]) in mainAppKeyBindings) {
3231 concmd(*cmdp);
3232 return true;
3234 // debug
3236 if (event == "S-Up") {
3237 if (folderTop > 0) --folderTop;
3238 postScreenRebuild();
3239 return true;
3241 if (event == "S-Down") {
3242 if (folderTop+1 < folders.length) ++folderTop;
3243 postScreenRebuild();
3244 return true;
3247 //if (event == "Tab") { new PostWindow(); return true; }
3248 //if (event == "Tab") { new SelectPopBoxWindow(null); return true; }
3250 return super.onKeySink(event);
3253 // returning `false` to avoid screen rebuilding by dispatcher
3254 override bool onMouseSink (MouseEvent event) {
3255 int mx = event.x;
3256 int my = event.y;
3257 // button press
3258 if (event.type == MouseEventType.buttonPressed && event.button == MouseButton.left) {
3259 // select folder
3260 if (mx >= 0 && mx < guiGroupListWidth && my >= 0 && my < screenHeight) {
3261 uint fnum = my/(gxTextHeightUtf+2)+folderTopIndex;
3262 if (fnum >= 0 && fnum != folderCurrIndex && folderCurrIndex < folderList.length) {
3263 folderCurrIndex = fnum;
3264 postScreenRebuild();
3266 return false;
3268 // select post
3269 if (mx > guiGroupListWidth && mx < screenWidth && my >= 0 && my < guiThreadListHeight) {
3270 if (lastDecodedTid != 0) {
3271 my /= gxTextHeightUtf;
3272 // find indicies
3273 int topidx, curridx;
3274 getAndFixThreadListIndicies(out topidx, out curridx);
3275 int newidx = topidx+my;
3276 if (curridx != newidx) {
3277 uint newuid = chiroGetTreePaneTableIndex2Uid(newidx);
3278 if (newuid && newuid != msglistCurrUId) {
3279 chiroSetMessageRead(lastDecodedTid, newuid);
3280 msglistCurrUId = newuid;
3281 setupTrayAnimation();
3282 postScreenRebuild();
3285 return false;
3287 } else {
3288 auto uidx = findUrlIndexAt(mx, my);
3289 if (uidx != lastUrlIndex || lastUrlIndex >= 0) { lastUrlIndex = uidx; postScreenRebuild(); }
3292 // wheel
3293 if (event.type == MouseEventType.buttonPressed && (event.button == MouseButton.wheelUp || event.button == MouseButton.wheelDown)) {
3294 // folder
3295 if (mx >= 0 && mx < guiGroupListWidth && my >= 0 && my < screenHeight) {
3296 if (event.button == MouseButton.wheelUp) {
3297 if (folderCurrIndex > 0) {
3298 --folderCurrIndex;
3299 postScreenRebuild();
3301 } else {
3302 if (folderCurrIndex+1 < folderList.length) {
3303 ++folderCurrIndex;
3304 postScreenRebuild();
3307 return false;
3309 // post
3310 if (mx > guiGroupListWidth && mx < screenWidth && my >= 0 && my < guiThreadListHeight) {
3311 if (event.button == MouseButton.wheelUp) {
3312 if (threadListUp()) postScreenRebuild();
3313 } else {
3314 if (threadListDown()) postScreenRebuild();
3316 return false;
3318 // text
3319 if (mx > guiGroupListWidth && mx < screenWidth && my > guiThreadListHeight && my < screenHeight) {
3320 enum ScrollLines = 2;
3321 if (event.button == MouseButton.wheelUp) scrollBy(-ScrollLines); else scrollBy(ScrollLines);
3322 postScreenRebuild();
3323 return false;
3326 // button release
3327 if (event.type == MouseEventType.buttonReleased && event.button == MouseButton.left) {
3328 // try url
3329 auto uidx = findUrlIndexAt(mx, my);
3330 auto url = findUrlAt(mx, my);
3331 if (url !is null) {
3332 if (url.isAttach) {
3333 if (event.modifierState&(ModifierState.alt|ModifierState.shift|ModifierState.ctrl)) {
3334 concmdf!"attach_save %s"(url.attachnum);
3335 } else {
3336 concmdf!"attach_view %s"(url.attachnum);
3338 } else {
3339 if (event.modifierState&(ModifierState.shift|ModifierState.ctrl)) {
3340 //conwriteln("link-to-clipboard: <", url.url, ">");
3341 setClipboardText(vbwin, url.url.getData.idup); // it is safe to cast here
3342 setPrimarySelection(vbwin, url.url.getData.idup); // it is safe to cast here
3343 conwriteln("url copied to the clipboard.");
3344 } else {
3345 //conwriteln("link-open: <", url.url, ">");
3346 concmdf!"open_url \"%s\" %s"(url.url, ((event.modifierState&ModifierState.alt) != 0));
3349 postScreenRebuild();
3350 } else {
3351 if (lastUrlIndex >= 0) postScreenRebuild();
3353 lastUrlIndex = uidx;
3355 if (event.type == MouseEventType.motion) {
3356 auto uidx = findUrlIndexAt(mx, my);
3357 if (uidx != lastUrlIndex) { lastUrlIndex = uidx; postScreenRebuild(); return false; }
3361 if (event.type == MouseEventType.buttonPressed || event.type == MouseEventType.buttonReleased) {
3362 postScreenRebuild();
3363 } else {
3364 // for OpenGL, this rebuilds the whole screen anyway
3365 postScreenRepaint();
3369 return false;
3374 // ////////////////////////////////////////////////////////////////////////// //
3375 __gshared LockFile mainLockFile;
3378 void checkMainLockFile () {
3379 import std.path : buildPath;
3380 mainLockFile = LockFile(buildPath(mailRootDir, ".chiroptera2.lock"));
3381 if (!mainLockFile.tryLock) {
3382 mainLockFile.close();
3383 //assert(0, "already running");
3384 conwriteln("another copy of Chiroptera is running, disabling updater.");
3385 receiverDisable();
3390 void main (string[] args) {
3392 import etc.linux.memoryerror;
3393 bool setMH = true;
3394 int idx = 1;
3395 while (idx < args.length) {
3396 string a = args[idx++];
3397 if (a == "--") break;
3398 if (a == "--gdb") {
3399 setMH = false;
3400 --idx;
3401 foreach (immutable c; idx+1..args.length) args[c-1] = args[c];
3404 if (setMH) registerMemoryErrorHandler();
3407 defaultColorStyle.parseStyle(ChiroStyle);
3409 glconAllowOpenGLRender = false;
3411 checkMainLockFile();
3412 scope(exit) mainLockFile.close();
3414 sdpyWindowClass = "Chiroptera";
3415 //glconShowKey = "M-Grave";
3417 initConsole();
3418 //FIXME
3419 //hitwitInitConsole();
3421 clearBindings();
3422 setupDefaultBindings();
3424 concmd("exec chiroptera.rc tan");
3425 concmd("load_style userstyle.rc");
3427 //FIXME
3428 //scanFolders();
3430 //FIXME:concmdf!"exec %s/accounts.rc tan"(mailRootDir);
3431 //FIXME:concmdf!"exec %s/addressbook.rc tan"(mailRootDir);
3432 //FIXME:concmdf!"exec %s/filters.rc tan"(mailRootDir);
3433 //FIXME:concmdf!"exec %s/highlights.rc tan"(mailRootDir);
3434 //FIXME:concmdf!"exec %s/twits.rc tan"(mailRootDir);
3435 //FIXME:concmdf!"exec %s/twit_threads.rc tan"(mailRootDir);
3436 //FIXME:concmdf!"exec %s/auto_twits.rc tan"(mailRootDir);
3437 //FIXME:concmdf!"exec %s/auto_twit_threads.rc tan"(mailRootDir);
3438 //FIXME:concmdf!"exec %s/repreps.rc tan"(mailRootDir);
3439 conProcessQueue(); // load config
3440 conProcessArgs!true(args);
3442 chiroOpenStorageDB();
3443 chiroOpenViewDB();
3444 chiroOpenConfDB();
3445 //ChiroTimerEnabled = true;
3446 //ChiroTimerExEnabled = true;
3448 rescanFolders();
3450 egraCreateSystemWindow("Chiroptera", allowResize:true);
3452 static if (is(typeof(&vbwin.closeQuery))) {
3453 vbwin.closeQuery = delegate () { concmd("quit"); egraPostDoConCommands(); };
3457 vbwin.windowResized = delegate (int wdt, int hgt) {
3458 egraSdpyOnWindowResized(wdt, hgt);
3460 // TODO: fix gui sizes
3461 if (vbwin.closed) return;
3463 double glwFrac = cast(double)guiGroupListWidth/screenWidth;
3464 double tlhFrac = cast(double)guiThreadListHeight/screenHeight;
3466 if (wdt < screenEffScale*32) wdt = screenEffScale;
3467 if (hgt < screenEffScale*32) hgt = screenEffScale;
3468 int newwdt = (wdt+screenEffScale-1)/screenEffScale;
3469 int newhgt = (hgt+screenEffScale-1)/screenEffScale;
3471 guiGroupListWidth = cast(int)(glwFrac*newwdt+0.5);
3472 guiThreadListHeight = cast(int)(tlhFrac*newhgt+0.5);
3474 if (guiGroupListWidth < 12) guiGroupListWidth = 12;
3475 if (guiThreadListHeight < 16) guiThreadListHeight = 16;
3479 vbwin.addEventListener((QuitEvent evt) {
3480 if (vbwin.closed) return;
3481 if (isQuitRequested) { vbwin.close(); return; }
3482 vbwin.close();
3486 vbwin.addEventListener((TrayAnimationStepEvent evt) {
3487 if (vbwin.closed) return;
3488 if (isQuitRequested) { vbwin.close(); return; }
3489 trayDoAnimationStep();
3493 HintWindow uphintWindow;
3495 vbwin.addEventListener((UpdatingAccountEvent evt) {
3496 DynStr accName = chiroGetAccountName(evt.accid);
3497 if (accName.length) {
3498 DynStr msg = "updating: ";
3499 msg ~= accName;
3500 if (uphintWindow !is null) {
3501 uphintWindow.message = msg;
3502 } else {
3503 uphintWindow = new HintWindow(msg);
3504 uphintWindow.y0 = guiThreadListHeight+1+(3*gxTextHeightUtf+2-uphintWindow.height)/2;
3506 postScreenRebuild();
3510 vbwin.addEventListener((UpdatingAccountCompleteEvent evt) {
3511 if (uphintWindow is null) return;
3512 DynStr accName = chiroGetAccountName(evt.accid);
3513 if (accName.length) {
3514 DynStr msg = "done: ";
3515 msg ~= accName;
3516 uphintWindow.message = msg;
3517 postScreenRebuild();
3521 vbwin.addEventListener((UpdatingCompleteEvent evt) {
3522 if (uphintWindow) {
3523 uphintWindow.close();
3524 uphintWindow = null;
3526 if (vbwin is null || vbwin.closed) return;
3527 setupTrayAnimation(); // check if we have to start/stop animation, and do it
3528 postScreenRebuild();
3531 vbwin.addEventListener((TagThreadsUpdatedEvent evt) {
3532 if (vbwin is null || vbwin.closed) return;
3533 if (mainPane is null) return;
3534 if (evt.tagid && mainPane.lastDecodedTid == evt.tagid) {
3535 // force view pane rebuild
3536 mainPane.switchToFolderTid(evt.tagid, forced:true);
3537 postScreenRebuild();
3542 ProgressWindow recalcHintWindow;
3544 vbwin.addEventListener((RecalcAllTwitsEvent evt) {
3545 if (vbwin !is null && !vbwin.closed) {
3546 glconHide();
3547 if (recalcHintWindow !is null) recalcHintWindow.close();
3548 recalcHintWindow = new ProgressWindow("recalculating twits");
3549 egraRebuildScreen();
3550 } else {
3551 recalcHintWindow = null;
3554 disableMailboxUpdates();
3555 scope(exit) enableMailboxUpdates();
3556 chiroRecalcAllTwits((msg, curr, total) {
3557 if (recalcHintWindow is null) return;
3558 if (recalcHintWindow.setProgress(msg, curr, total)) {
3559 egraRebuildScreen();
3563 if (vbwin !is null && !vbwin.closed) {
3564 if (recalcHintWindow !is null) recalcHintWindow.close();
3565 if (mainPane !is null) mainPane.switchToFolderTid(mainPane.lastDecodedTid, forced:true);
3566 postScreenRebuild();
3570 vbwin.addEventListener((ArticleTextScrollEvent evt) {
3571 if (vbwin is null || vbwin.closed) return;
3572 if (mainPane is null) return;
3573 mainPane.doScrollStep();
3576 vbwin.addEventListener((MarkAsUnreadEvent evt) {
3577 if (vbwin is null || vbwin.closed) return;
3578 if (mainPane is null) return;
3579 //conwriteln("unread timer fired");
3580 if (mainPane.lastDecodedTid == evt.tagid && evt.uid == mainPane.msglistCurrUId) {
3581 //conwriteln("*** unread timer hit!");
3582 chiroSetMessageRead(evt.tagid, evt.uid);
3583 setupTrayAnimation();
3584 postScreenRebuild();
3588 void firstTimeInit () {
3589 // create notification icon
3590 if (trayicon is null) {
3591 auto drv = vfsAddPak(wrapMemoryRO(iconsZipData[]), "", "databinz/icons.zip:");
3592 scope(exit) vfsRemovePak(drv);
3593 try {
3594 foreach (immutable idx; 0..6) {
3595 string fname = "databinz/icons.zip:icons";
3596 if (idx == 0) {
3597 fname ~= "/main.png";
3598 } else {
3599 import std.format : format;
3600 fname = "%s/bat%s.png".format(fname, idx-1);
3602 auto fl = VFile(fname);
3603 if (fl.size == 0 || fl.size > 1024*1024) throw new Exception("fucked icon");
3604 auto pngraw = new ubyte[](cast(uint)fl.size);
3605 fl.rawReadExact(pngraw);
3606 auto img = readPng(pngraw);
3607 if (img is null) throw new Exception("fucked icon");
3608 icons[idx] = imageFromPng(img);
3610 foreach (immutable idx, MemoryImage img; icons[]) {
3611 trayimages[idx] = Image.fromMemoryImage(img);
3613 vbwin.icon = icons[0];
3614 trayicon = new NotificationAreaIcon("Chiroptera", trayimages[0], (MouseButton button) {
3615 scope(exit) if (!conQueueEmpty()) egraPostDoConCommands();
3616 if (button == MouseButton.left) vbwin.switchToWindow();
3617 if (button == MouseButton.middle) concmd("quit");
3619 setupTrayAnimation();
3620 flushGui(); // or it may not redraw itself
3621 } catch (Exception e) {
3622 conwriteln("ERROR loading icons: ", e.msg);
3627 vbwin.visibleForTheFirstTime = delegate () {
3628 egraFirstTimeInit();
3629 firstTimeInit();
3632 mainPane = new MainPaneWindow();
3633 egraSkipScreenClear = true; // main pane is fullscreen
3635 postScreenRebuild();
3636 repostHideMouse();
3638 receiverInit();
3640 MonoTime lastCollect = MonoTime.currTime;
3641 vbwin.eventLoop(1000*10,
3642 delegate () {
3643 egraProcessConsole();
3644 if (mainPane !is null) {
3645 if (mainPane.isViewChanged) postScreenRebuild();
3646 mainPane.checkSaveState();
3647 setupTrayAnimation();
3650 immutable ctt = MonoTime.currTime;
3651 if ((ctt-lastCollect).total!"minutes" >= 1) {
3652 import core.memory : GC;
3653 lastCollect = ctt;
3654 GC.collect();
3655 GC.minimize();
3659 delegate (KeyEvent event) {
3660 egraOnKey(event);
3661 if (mainPane !is null && mainPane.isViewChanged) postScreenRebuild();
3663 delegate (MouseEvent event) {
3664 egraOnMouse(event);
3665 if (mainPane !is null && mainPane.isViewChanged) postScreenRebuild();
3667 delegate (dchar ch) {
3668 egraOnChar(ch);
3669 if (mainPane !is null && mainPane.isViewChanged) postScreenRebuild();
3673 mainPane.saveCurrentState();
3675 trayimages[] = null;
3676 if (trayicon !is null && !trayicon.closed) { trayicon.close(); trayicon = null; }
3677 flushGui();
3678 receiverDeinit();
3679 conProcessQueue(int.max/4);