some code to create and show reply window, and to build reply message (no sending...
[chiroptera.git] / chiroptera.d
blob0df35f6d0b9517862ec1348dfb67583e7f895f4e
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 /*FIXME
1066 if (auto fld = getActiveFolder) {
1067 auto postDg = delegate (Account acc) {
1068 conwriteln("post with account '", acc.name, "' (", acc.mail, ")");
1069 auto pw = new PostWindow();
1070 pw.from.str = acc.realname~" <"~acc.mail~">";
1071 pw.from.readonly = true;
1072 if (auto nna = cast(NntpAccount)acc) {
1073 pw.title = "Reply to NNTP "~nna.server~":"~nna.group;
1074 pw.to.str = nna.group;
1075 pw.to.readonly = true;
1076 pw.activeWidget = pw.subj;
1077 } else {
1078 pw.title = "Reply from '"~acc.name~"' ("~acc.mail~")";
1079 pw.to.str = "";
1080 pw.activeWidget = pw.to;
1082 pw.subj.str = "";
1083 pw.acc = acc;
1084 pw.fld = fld;
1087 auto acc = fld.findAccountToPost();
1088 if (acc is null) {
1089 auto wacc = new SelectPopBoxWindow(defaultAcc);
1090 wacc.onSelected = postDg;
1091 } else {
1092 postDg(acc);
1093 acc = defaultAcc;
1095 } else {
1096 conwriteln("post: no active folder");
1099 })("new_post", "post a new article or message");
1102 // //////////////////////////////////////////////////////////////////// //
1103 static void doReplyXX (string repfld) {
1104 if (vbwin is null || vbwin.closed) return;
1105 if (mainPane is null) return;
1106 if (!mainPane.msglistCurrUId) return;
1108 auto pw = new PostWindow();
1109 pw.ed.focus();
1111 dynstring accname;
1112 foreach (auto row; dbView.statement(`
1113 SELECT DISTINCT(tagid) AS tagid, tt.tag AS name
1114 FROM threads
1115 INNER JOIN tagnames AS tt USING(tagid)
1116 WHERE uid=:uid AND name LIKE 'account:%'
1117 ;`).bind(":uid", mainPane.msglistCurrUId).range)
1119 auto name = row.name!SQ3Text;
1120 if (name.startsWith("account:")) {
1121 accname = name[8..$];
1122 if (accname.length) {
1123 pw.accname = accname;
1124 break;
1129 if (accname.length == 0) {
1130 conwriteln("ERROR: source account not found!");
1131 vbwin.beep();
1132 } else {
1133 conwriteln("account: ", accname);
1136 foreach (auto row; dbStore.statement(`
1137 SELECT ChiroHdr_Field(ChiroUnpack(data), :fldname) AS fldvalue
1138 FROM messages
1139 WHERE uid=:uid
1140 ORDER BY uid
1141 LIMIT 1
1142 `).bind(":uid", mainPane.msglistCurrUId).bindConstText(":fldname", repfld).range)
1144 pw.to.str = row.fldvalue!SQ3Text.decodeSubj;
1145 pw.caption = dynstring("Reply to: ")~pw.to.str;
1148 dynstring fromname;
1149 foreach (auto row; dbView.statement(`
1150 SELECT subj AS subj, from_name AS fromname
1151 FROM info
1152 WHERE uid=:uid
1153 LIMIT 1
1154 `).bind(":uid", mainPane.msglistCurrUId).range)
1156 fromname = row.fromname!SQ3Text;
1157 dynstring s = "Re: ";
1158 s ~= row.subj!SQ3Text;
1159 pw.subj.str = s;
1162 foreach (auto row; dbView.statement(`
1163 SELECT ChiroUnpack(content) AS content
1164 FROM content_text
1165 WHERE uid=:uid
1166 LIMIT 1
1167 `).bind(":uid", mainPane.msglistCurrUId).range)
1169 pw.ed.addText(fromname);
1170 pw.ed.addText(" wrote:\n");
1171 pw.ed.addText("\n");
1172 dynstring text = row.content!SQ3Text;
1173 foreach (SQ3Text s; text.byLine) {
1174 if (s.length == 0 || s[0] == '>') pw.ed.addText(">"); else pw.ed.addText("> ");
1175 pw.ed.addText(s);
1176 pw.ed.addText("\n");
1178 pw.ed.addText("\n");
1179 pw.ed.reformat();
1182 foreach (auto row; dbConf.statement(`
1183 SELECT
1184 accid AS accid
1185 --, name AS name
1186 , recvserver AS recvserver
1187 , sendserver AS sendserver
1188 , realname AS realname
1189 , email AS email
1190 , nntpgroup AS nntpgroup
1191 FROM accounts
1192 WHERE name=:accname --AND sendserver<>'' AND email<>''
1193 LIMIT 1
1194 `).bindConstText(":accname", accname.getData).range)
1197 conwriteln("GROUP: <", row.nntpgroup!SQ3Text, ">");
1198 conwriteln("NAME: <", row.realname!SQ3Text, ">");
1199 conwriteln("EMAIL: <", row.email!SQ3Text, ">");
1201 dynstring frm;
1202 if (row.realname!SQ3Text.length) {
1203 frm = row.realname!SQ3Text;
1204 frm ~= " <";
1205 frm ~= row.email!SQ3Text;
1206 frm ~= ">";
1207 } else {
1208 frm = row.email!SQ3Text;
1210 pw.setFrom(frm);
1212 if (row.nntpgroup!SQ3Text.length) {
1213 pw.to.str = dynstring("newsgroup: ")~row.nntpgroup!SQ3Text;
1214 pw.to.readonly = true;
1215 pw.to.disabled = true;
1216 pw.allowAccountChange = false;
1217 pw.nntp = true;
1221 foreach (auto row; dbView.statement(`
1222 SELECT msgid AS msgid
1223 FROM refids
1224 WHERE uid=:uid
1225 ORDER BY idx
1226 `).bind(":uid", mainPane.msglistCurrUId).range)
1228 //conwriteln("REF: |", row.msgid!SQ3Text);
1229 if (pw.references.length) pw.references ~= " ";
1230 pw.references ~= row.msgid!SQ3Text;
1234 static void doReply (string repfld) {
1235 try {
1236 doReplyXX(repfld);
1237 } catch (Exception e) {
1238 conwriteln("EXCEPTION: ", e.msg);
1239 auto s = e.toString();
1240 conwriteln(s);
1244 conRegFunc!(() { doReply("Reply-To"); })("article_reply", "reply to the current article with \"reply-to\" field");
1245 conRegFunc!(() { doReply("From"); })("article_reply_to_from", "reply to the current article with \"from\" field");
1248 // //////////////////////////////////////////////////////////////////// //
1249 conRegFunc!(() {
1250 if (vbwin is null || vbwin.closed) return;
1251 if (mainPane is null) return;
1252 if (mainPane.msglistCurrUId) {
1253 //messageBogoMarkHam(mainPane.msglistCurrUId);
1254 foreach (auto mrow; dbStore.statement(`SELECT ChiroUnpack(data) AS data FROM messages WHERE uid=:uid LIMIT 1;`).bind(":uid", mainPane.msglistCurrUId).range) {
1255 try {
1256 import core.stdc.stdio : snprintf;
1257 char[128] fname = void;
1258 auto len = snprintf(fname.ptr, fname.length, "~/Mail/_bots/z_eml_%u.eml", cast(uint)mainPane.msglistCurrUId);
1259 auto fo = VFile(fname[0..len], "w");
1260 fo.writeln(mrow.data!SQ3Text.xstripright);
1261 fo.close();
1262 conwriteln("article exported to: ", fname[0..len]);
1263 } catch (Exception e) {
1267 })("article_export", "export current article as raw text");
1270 conRegFunc!(() {
1271 if (vbwin is null || vbwin.closed) return;
1272 if (mainPane is null) return;
1273 if (mainPane.msglistCurrUId) {
1274 messageBogoMarkHam(mainPane.msglistCurrUId);
1275 //TODO: move out of spam
1277 })("article_mark_ham", "mark current article as ham");
1280 conRegFunc!(() {
1281 if (vbwin is null || vbwin.closed) return;
1282 if (mainPane is null) return;
1283 if (mainPane.msglistCurrUId) {
1284 immutable uint uid = mainPane.msglistCurrUId;
1285 // move to the next message
1286 if (!mainPane.threadListDown()) mainPane.threadListUp();
1287 conwriteln("calling bogofilter...");
1288 messageBogoMarkSpam(uid);
1289 conwriteln("adding '#spam' tag");
1290 immutable bool updatePane = chiroMessageAddTag(uid, "#spam");
1291 conwriteln("removing other virtual folder tags...");
1292 DynStr[] tags;
1293 scope(exit) delete tags;
1294 tags.reserve(32);
1295 static auto stGetMsgTags = LazyStatement!"View"(`
1296 SELECT DISTINCT(tagid) AS tagid, tt.tag AS name
1297 FROM threads
1298 INNER JOIN tagnames AS tt USING(tagid)
1299 WHERE uid=:uid
1300 ;`);
1301 foreach (auto row; stGetMsgTags.st.bind(":uid", uid).range) {
1302 auto tag = row.name!SQ3Text;
1303 conwriteln(" tag: ", tag);
1304 if (tag.startsWith("/")) tags ~= DynStr(tag);
1306 foreach (ref DynStr tn; tags) {
1307 conwriteln("removing tag '", tn.getData, "'...");
1308 chiroMessageRemoveTag(uid, tn.getData);
1310 conwriteln("done marking as spam.");
1311 if (updatePane) {
1312 mainPane.switchToFolderTid(mainPane.lastDecodedTid, forced:true);
1313 } else {
1314 // rescan folder
1315 mainPane.updateViewsIfTid(chiroGetTagUid("#spam"));
1317 postScreenRebuild();
1319 })("article_mark_spam", "mark current article as spam");
1322 // //////////////////////////////////////////////////////////////////// //
1323 conRegFunc!((ConString fldname) {
1324 if (vbwin is null || vbwin.closed) return;
1325 if (mainPane is null) return;
1326 if (!mainPane.msglistCurrUId) return;
1327 immutable uint uid = mainPane.msglistCurrUId;
1329 fldname = fldname.xstrip;
1330 while (fldname.length && fldname[$-1] == '/') fldname = fldname[0..$-1].xstrip;
1331 immutable bool isforced = (fldname.length && fldname[0] == '!');
1332 if (isforced) fldname = fldname[1..$];
1333 if (fldname.length == 0) {
1334 conwriteln("ERROR: cannot move to empty folder");
1335 return;
1337 if (fldname[0].isalnum) {
1338 conwriteln("ERROR: invalid folder name '", fldname, "'");
1339 return;
1342 uint tagid;
1343 if (!isforced) {
1344 tagid = chiroGetTagUid(fldname);
1345 } else {
1346 tagid = chiroAppendTag(fldname, hidden:(fldname[0] == '#' ? 1 : 0));
1348 if (!tagid) {
1349 conwriteln("ERROR: invalid folder name '", fldname, "'");
1350 return;
1353 immutable bool updatePane = chiroMessageAddTag(uid, fldname);
1354 DynStr[] tags;
1355 scope(exit) delete tags;
1356 tags.reserve(32);
1357 static auto stGetMsgTags = LazyStatement!"View"(`
1358 SELECT DISTINCT(tagid) AS tagid, tt.tag AS name
1359 FROM threads
1360 INNER JOIN tagnames AS tt USING(tagid)
1361 WHERE uid=:uid
1362 ;`);
1363 foreach (auto row; stGetMsgTags.st.bind(":uid", uid).range) {
1364 auto tag = row.name!SQ3Text;
1365 conwriteln(" tag: ", tag);
1366 if (tag.startsWith("account:")) continue;
1367 if (tag != fldname) tags ~= DynStr(tag);
1369 foreach (ref DynStr tn; tags) {
1370 conwriteln("removing tag '", tn.getData, "'...");
1371 chiroMessageRemoveTag(uid, tn.getData);
1373 if (updatePane) {
1374 mainPane.switchToFolderTid(mainPane.lastDecodedTid, forced:true);
1375 } else {
1376 // rescan folder
1377 mainPane.updateViewsIfTid(chiroGetTagUid("#spam"));
1379 postScreenRebuild();
1380 })("article_move_to_folder", "move article to existing folder");
1383 // //////////////////////////////////////////////////////////////////// //
1384 version(none) {
1385 conRegFunc!(() {
1386 /*FIXME
1387 if (auto fld = getActiveFolder) {
1388 fld.moveToParent();
1389 postScreenRebuild();
1392 })("article_to_parent", "jump to parent article, if any");
1394 conRegFunc!(() {
1395 /*FIXME
1396 if (auto fld = getActiveFolder) {
1397 fld.moveToPrevSib();
1398 postScreenRebuild();
1401 })("article_to_prev_sib", "jump to previous sibling");
1403 conRegFunc!(() {
1404 /*FIXME
1405 if (auto fld = getActiveFolder) {
1406 fld.moveToNextSib();
1407 postScreenRebuild();
1410 })("article_to_next_sib", "jump to next sibling");
1413 // //////////////////////////////////////////////////////////////////// //
1414 conRegFunc!(() {
1415 if (vbwin is null || vbwin.closed) return;
1416 if (mainPane is null) return;
1417 if (mainPane.lastDecodedTid == 0 || mainPane.msglistCurrUId == 0) return;
1418 DynStr tagname = chiroGetTagName(mainPane.lastDecodedTid);
1419 if (!globmatch(tagname.getData, "/dmars_ng/*")) return;
1420 // get from
1421 DynStr fromMail, fromName;
1422 if (!chiroGetMessageFrom(mainPane.msglistCurrUId, ref fromMail, ref fromName)) return;
1423 if (fromMail.length == 0 && fromName.length == 0) return;
1424 //writeln("!!! email=", fromMail.getData, "; name=", fromName.getData, "|");
1426 uint twitid = 0;
1427 DynStr twtitle;
1428 DynStr twname;
1429 DynStr twemail;
1430 DynStr twnotes;
1431 DynStr twtagglob = "/dmars_ng/*";
1432 bool withName = false;
1434 static auto stFindTwit = LazyStatement!"Conf"(`
1435 SELECT
1436 etwitid AS twitid
1437 , tagglob AS tagglob
1438 , email AS email
1439 , name AS name
1440 , title AS title
1441 , notes AS notes
1442 FROM emailtwits
1443 WHERE email=:email AND name=:name
1444 ;`);
1446 static auto stAddTwit = LazyStatement!"Conf"(`
1447 INSERT INTO emailtwits
1448 ( tagglob, email, name, title, notes)
1449 VALUES(:tagglob,:email,:name,:title,:notes)
1450 ;`);
1452 static auto stModifyTwit = LazyStatement!"Conf"(`
1453 UPDATE emailtwits
1455 tagglob=:tagglob
1456 , email=:email
1457 , name=:name
1458 , title=:title
1459 , notes=:notes
1460 WHERE etwitid=:twitid
1461 ;`);
1463 static auto stRemoveTwitAuto = LazyStatement!"Conf"(`
1464 DELETE FROM msgidtwits
1465 WHERE etwitid=:twitid
1466 ;`);
1468 static auto stRemoveTwit = LazyStatement!"Conf"(`
1469 DELETE FROM emailtwits
1470 WHERE etwitid=:twitid
1471 ;`);
1473 stFindTwit.st
1474 .bindConstText(":email", fromMail.getData)
1475 .bindConstText(":name", fromName.getData);
1476 foreach (auto row; stFindTwit.st.range) {
1477 //conwriteln("!!!", row.twitid!uint, "; mail=", row.email!SQ3Text, "; name=", row.name!SQ3Text, "; title=", row.title!SQ3Text.recodeToKOI8);
1478 if (!globmatch(tagname.getData, row.tagglob!SQ3Text)) continue;
1479 twitid = row.twitid!uint;
1480 twtitle = row.title!SQ3Text;
1481 twname = row.name!SQ3Text;
1482 twemail = row.email!SQ3Text;
1483 twtagglob = row.tagglob!SQ3Text;
1484 twnotes = row.notes!SQ3Text;
1485 withName = (fromName.length != 0);
1486 break;
1489 if (!twitid && fromName.length) {
1490 stFindTwit.st
1491 .bindConstText(":email", fromMail.getData)
1492 .bindConstText(":name", "");
1493 foreach (auto row; stFindTwit.st.range) {
1494 //conwriteln("!!!", row.twitid!uint, "; mail=", row.email!SQ3Text, "; name=", row.name!SQ3Text, "; title=", row.title!SQ3Text.recodeToKOI8);
1495 if (!globmatch(tagname.getData, row.tagglob!SQ3Text)) continue;
1496 twitid = row.twitid!uint;
1497 twtitle = row.title!SQ3Text;
1498 twname = row.name!SQ3Text;
1499 twemail = row.email!SQ3Text;
1500 twtagglob = row.tagglob!SQ3Text;
1501 twnotes = row.notes!SQ3Text;
1502 withName = false;
1503 break;
1507 //conwriteln("twitid: ", twitid, "; title=", twtitle.getData.recodeToKOI8);
1509 auto tw = new TitlerWindow((twitid ? twname : fromName), (twitid ? twemail : fromMail), twtagglob, twtitle);
1510 tw.onSelected = delegate (name, email, glob, title) {
1511 if (email.length == 0 && name.length == 0) return false;
1512 if (glob.length == 0) return false;
1513 if (email.length && email[0] == '@') return false;
1514 title = title.xstrip;
1515 if (twitid) {
1516 if (title.length == 0) {
1517 // remove twit
1518 conwriteln("removing twit...");
1519 stRemoveTwitAuto.st.bind(":twitid", twitid).doAll();
1520 stRemoveTwit.st.bind(":twitid", twitid).doAll();
1521 } else {
1522 // change twit
1523 conwriteln("changing twit...");
1524 stModifyTwit.st
1525 .bind(":twitid", twitid)
1526 .bindConstText(":tagglob", glob)
1527 .bindConstText(":email", email)
1528 .bindConstText(":name", name)
1529 .bindConstText(":title", title)
1530 .bindConstText(":notes", twnotes.getData, allowNull:true)
1531 .doAll();
1533 } else {
1534 if (title.length == 0) return false;
1535 // new twit
1536 conwriteln("adding twit...");
1537 stAddTwit.st
1538 .bindConstText(":tagglob", glob)
1539 .bindConstText(":email", email)
1540 .bindConstText(":name", name)
1541 .bindConstText(":title", title)
1542 .bindConstText(":notes", null, allowNull:true)
1543 .doAll();
1546 if (vbwin && !vbwin.closed) vbwin.postEvent(new RecalcAllTwitsEvent());
1547 return true;
1549 })("article_edit_poster_title", "edit poster's title of the current article");
1552 // //////////////////////////////////////////////////////////////////// //
1553 conRegFunc!(() {
1554 if (vbwin is null || vbwin.closed) return;
1555 if (mainPane is null) return;
1556 if (mainPane.lastDecodedTid == 0 || mainPane.msglistCurrUId == 0) return;
1557 DynStr tagname = chiroGetTagName(mainPane.lastDecodedTid);
1558 if (!globmatch(tagname.getData, "/dmars_ng/*")) return;
1559 int mute = chiroGetMessageMute(mainPane.lastDecodedTid, mainPane.msglistCurrUId);
1560 // check for non-automatic mutes
1561 if (mute != Mute.Normal && mute <= Mute.ThreadStart) return;
1562 createTwitByMsgid(mainPane.msglistCurrUId);
1563 mainPane.switchToFolderTid(mainPane.lastDecodedTid, forced:true);
1564 postScreenRebuild();
1565 })("article_twit_thread", "twit current thread");
1567 conRegFunc!(() {
1568 if (vbwin is null || vbwin.closed) return;
1569 if (mainPane is null) return;
1570 int app = chiroGetMessageAppearance(mainPane.lastDecodedTid, mainPane.msglistCurrUId);
1571 if (app >= 0) {
1572 //conwriteln("oldapp: ", app, " (", isSoftDeleted(app), ")");
1573 immutable bool wasPurged = (app == Appearance.SoftDeletePurge);
1574 app =
1575 app == Appearance.SoftDeletePurge ? Appearance.SoftDeleteUser :
1576 isSoftDeleted(app) ? Appearance.Read :
1577 Appearance.SoftDeleteUser;
1578 //conwriteln("newapp: ", app);
1579 chiroSetMessageAppearance(mainPane.lastDecodedTid, mainPane.msglistCurrUId, cast(Appearance)app);
1580 if (!wasPurged && isSoftDeleted(app)) mainPane.threadListDown();
1581 postScreenRebuild();
1583 })("article_softdelete_toggle", "toggle \"soft deleted\" flag on current article");
1585 conRegFunc!(() {
1586 if (vbwin is null || vbwin.closed) return;
1587 if (mainPane is null) return;
1588 int app = chiroGetMessageAppearance(mainPane.lastDecodedTid, mainPane.msglistCurrUId);
1589 if (app >= 0) {
1590 //conwriteln("oldapp: ", app);
1591 app =
1592 app == Appearance.SoftDeletePurge ? Appearance.Read :
1593 isSoftDeleted(app) ? Appearance.SoftDeletePurge :
1594 Appearance.SoftDeletePurge;
1595 //conwriteln("newapp: ", app);
1596 chiroSetMessageAppearance(mainPane.lastDecodedTid, mainPane.msglistCurrUId, cast(Appearance)app);
1597 if (app == Appearance.SoftDeletePurge) mainPane.threadListDown();
1598 postScreenRebuild();
1600 })("article_harddelete_toggle", "toggle \"hard deleted\" flag on current article");
1603 // //////////////////////////////////////////////////////////////////// //
1604 conRegFunc!(() {
1605 if (vbwin is null || vbwin.closed) return;
1606 if (mainPane is null) return;
1607 DynStr hdrs = chiroMessageHeaders(mainPane.msglistCurrUId);
1608 if (hdrs.length == 0) return;
1609 conwriteln("============================");
1610 conwriteln("message uid: ", mainPane.msglistCurrUId);
1611 conwriteln(" tag tagid: ", mainPane.lastDecodedTid);
1612 conwriteln("============================");
1613 forEachHeaderLine(hdrs.getData, (const(char)[] line) {
1614 conwriteln(" ", line.xstripright);
1615 return true; // go on
1617 })("article_dump_headers", "dump article headers");
1619 conRegFunc!(() {
1620 if (vbwin is null || vbwin.closed) return;
1621 if (mainPane is null) return;
1622 DynStr hdrs = chiroMessageHeaders(mainPane.msglistCurrUId);
1623 if (hdrs.length == 0) return;
1624 conwriteln("============================");
1625 conwriteln("message uid: ", mainPane.msglistCurrUId);
1626 conwriteln(" tag tagid: ", mainPane.lastDecodedTid);
1627 conwriteln("============================");
1628 auto bogo = messageBogoCheck(mainPane.msglistCurrUId);
1629 conwriteln("BOGO RESULT: ", bogo);
1630 })("article_bogo_check", "check article with bogofilter (purely informational)");
1632 conRegFunc!(() {
1633 if (mainPane !is null && mainPane.lastDecodedTid) {
1634 conwriteln("relinking ", mainPane.lastDecodedTid, " (", chiroGetTagName(mainPane.lastDecodedTid).getData, ")...");
1635 chiroSupportRelinkTagThreads(mainPane.lastDecodedTid);
1636 mainPane.switchToFolderTid(mainPane.lastDecodedTid, forced:true);
1637 postScreenRebuild();
1639 })("folder_rebuild_index", "rebuild thread index");
1641 conRegFunc!(() {
1642 if (vbwin && !vbwin.closed && mainPane !is null /*&& mainPane.lastDecodedTid*/) {
1643 vbwin.postEvent(new RecalcAllTwitsEvent());
1645 })("folder_rebuild_twits", "rebuild all twits");
1647 conRegFunc!(() {
1648 if (mainPane !is null && mainPane.folderCurrTag.length) {
1649 auto w = new TagOptionsWindow(mainPane.folderCurrTag.getData);
1650 w.onUpdated = delegate void (tagname) {
1651 if (vbwin && !vbwin.closed && mainPane !is null && mainPane.lastDecodedTagName == tagname) {
1652 mainPane.switchToFolderTid(mainPane.lastDecodedTid, forced:true);
1655 postScreenRebuild();
1657 })("folder_options", "show options window");
1660 conRegFunc!(() {
1661 if (auto fld = getActiveFolder) {
1662 fld.withBase(delegate (abase) {
1663 uint idx = fld.curidx;
1664 if (idx >= fld.length) {
1665 idx = 0;
1666 } else if (auto art = abase[fld.baseidx(idx)]) {
1667 if (art.frommail.indexOf("ketmar@ketmar.no-ip.org") >= 0) {
1668 idx = (idx+1)%fld.length;
1671 foreach (immutable _; 0..fld.length) {
1672 auto art = abase[fld.baseidx(idx)];
1673 if (art !is null) {
1674 if (art.frommail.indexOf("ketmar@ketmar.no-ip.org") >= 0) {
1675 fld.curidx = cast(int)idx;
1676 postScreenRebuild();
1677 return;
1680 idx = (idx+1)%fld.length;
1684 })("find_mine", "find mine article");
1687 // //////////////////////////////////////////////////////////////////// //
1688 conRegVar!dbg_dump_keynames("dbg_dump_key_names", "dump key names");
1691 // //////////////////////////////////////////////////////////////////// //
1692 conRegFunc!((uint idx) {
1693 if (vbwin is null || vbwin.closed) return;
1694 if (mainPane is null) return;
1695 if (mainPane.msglistCurrUId == 0) return;
1697 static auto statAttaches = LazyStatement!"View"(`
1698 SELECT
1699 idx AS idx
1700 , mime AS mime
1701 , name AS name
1702 , ChiroUnpack(content) AS content
1703 FROM attaches
1704 WHERE uid=:uid
1705 ORDER BY idx
1706 ;`);
1707 char[128] buf = void;
1708 uint attidx = 0;
1709 foreach (auto row; statAttaches.st.bind(":uid", mainPane.msglistCurrUId).range) {
1710 import core.stdc.stdio : snprintf;
1711 if (idx != 0) { --idx; ++attidx; continue; }
1712 if (!row.mime!SQ3Text.startsWith("image")) return;
1713 auto name = row.name!SQ3Text.getExtension;
1714 if (name.length == 0) return;
1715 try {
1716 DynStr fname;
1717 fname = "/tmp/_viewimage_";
1719 import std.uuid;
1720 UUID id = randomUUID();
1721 foreach (immutable ubyte b; id.data[]) {
1722 fname ~= "0123456789abcdef"[b>>4];
1723 fname ~= "0123456789abcdef"[b&0x0f];
1725 fname ~= name;
1727 conwriteln("writing attach #", attidx, " to '", fname.getData, "'");
1728 VFile fo = VFile(fname.getData, "w");
1729 fo.rawWriteExact(row.content!SQ3Text);
1730 fo.close();
1732 auto vtid = spawn(&imageViewThread, thisTid);
1733 string fnamestr = fname.getData.idup;
1734 vtid.send(ImgViewCommand(fnamestr));
1735 } catch (Exception e) {
1736 conwriteln("ERROR writing attachment: ", e.msg);
1738 break;
1740 })("attach_view", "view attached image: attach_view index");
1743 // //////////////////////////////////////////////////////////////////// //
1744 conRegFunc!((uint idx, ConString userfname=null) {
1745 if (vbwin is null || vbwin.closed) return;
1746 if (mainPane is null) return;
1747 if (mainPane.msglistCurrUId == 0) return;
1749 static auto statAttaches = LazyStatement!"View"(`
1750 SELECT
1751 idx AS idx
1752 , mime AS mime
1753 , name AS name
1754 , ChiroUnpack(content) AS content
1755 FROM attaches
1756 WHERE uid=:uid
1757 ORDER BY idx
1758 ;`);
1759 char[128] buf = void;
1760 uint attidx = 0;
1761 foreach (auto row; statAttaches.st.bind(":uid", mainPane.msglistCurrUId).range) {
1762 import core.stdc.stdio : snprintf;
1763 if (idx != 0) { --idx; ++attidx; continue; }
1764 try {
1765 auto name = row.name!SQ3Text/*.decodeSubj*/;
1766 DynStr fname;
1768 if (userfname.length) {
1769 fname = userfname;
1770 } else {
1771 fname = "/tmp/";
1772 name = name.sanitizeFileNameStr;
1773 if (name.length == 0) {
1774 auto len = snprintf(buf.ptr, buf.sizeof, "attach_%02u.bin", attidx);
1775 fname ~= buf[0..cast(usize)len];
1776 } else {
1777 fname ~= name;
1781 conwriteln("writing attach #", attidx, " to '", fname.getData, "'");
1782 VFile fo = VFile(fname.getData, "w");
1783 fo.rawWriteExact(row.content!SQ3Text);
1784 fo.close();
1785 } catch (Exception e) {
1786 conwriteln("ERROR writing attachment: ", e.msg);
1788 break;
1790 })("attach_save", "save attach: attach_save index [filename]");
1794 // ////////////////////////////////////////////////////////////////////////// //
1795 //FIXME: turn into property
1796 final class ArticleTextScrollEvent {}
1797 __gshared ArticleTextScrollEvent evArticleScroll;
1798 shared static this () {
1799 evArticleScroll = new ArticleTextScrollEvent();
1802 void postArticleScroll () {
1803 if (vbwin !is null && !vbwin.eventQueued!ArticleTextScrollEvent) vbwin.postTimeout(evArticleScroll, 25);
1807 // ////////////////////////////////////////////////////////////////////////// //
1808 class MarkAsUnreadEvent {
1809 uint tagid;
1810 uint uid;
1813 __gshared int unreadTimeoutInterval = 600;
1814 __gshared int scrollKeepLines = 3;
1815 __gshared bool preferHtmlContent = false;
1816 __gshared bool detectHtmlContent = true;
1819 void postMarkAsUnreadEvent () {
1820 if (unreadTimeoutInterval > 0 && unreadTimeoutInterval < 10000 && vbwin !is null && mainPane !is null) {
1821 if (!mainPane.msglistCurrUId) return;
1822 if (chiroGetMessageUnread(mainPane.lastDecodedTid, mainPane.msglistCurrUId)) {
1823 //conwriteln("setting new unread timer");
1824 auto evt = new MarkAsUnreadEvent();
1825 evt.tagid = mainPane.lastDecodedTid;
1826 evt.uid = mainPane.msglistCurrUId;
1827 vbwin.postTimeout(evt, unreadTimeoutInterval);
1833 // ////////////////////////////////////////////////////////////////////////// //
1834 __gshared MainPaneWindow mainPane;
1837 final class MainPaneWindow : SubWindow {
1838 dynstring[] emlines; // in utf
1839 uint emlinesBeforeAttaches;
1840 uint lastDecodedUId;
1841 uint lastDecodedTid; // for which folder we last build our view?
1842 uint lastMaxTidUid;
1843 DynStr lastDecodedTagName;
1844 DynStr arttoname;
1845 DynStr arttomail;
1846 DynStr artfromname;
1847 DynStr artfrommail;
1848 DynStr artsubj;
1849 DynStr arttime;
1850 int articleTextTopLine = 0;
1851 int articleDestTextTopLine = 0;
1852 //__gshared Timer unreadTimer; // as main pane is never destroyed, there's no need to kill the timer
1853 //__gshared Folder unreadFolder;
1854 //__gshared uint unreadIdx;
1855 int linesInHeader;
1856 // folder view
1857 DynStr folderTopTag = null;
1858 DynStr folderCurrTag = null;
1859 int folderTopIndex = 0;
1860 int folderCurrIndex = 0;
1861 // message list view
1862 uint msglistTopUId = 0;
1863 uint msglistCurrUId = 0;
1864 bool saveMsgListPositions = false;
1865 MonoTime lastStateSaveTime;
1866 uint viewDataVersion;
1868 this () {
1869 super(null, GxSize(screenWidth, screenHeight));
1870 allowMinimise = false;
1871 allowDragMove = false;
1872 mType = Type.OnBottom;
1873 add();
1874 loadSavedState();
1875 lastStateSaveTime = MonoTime.currTime;
1876 viewDataVersion = dbView.getDataVersion()-1u;
1879 bool isViewChanged () const nothrow @trusted @nogc {
1880 pragma(inline, true);
1881 return (viewDataVersion != dbView.getDataVersion());
1884 void updateViewsIfTid (uint tid) {
1885 if (tid && lastDecodedTid == tid) {
1886 switchToFolderTid(lastDecodedTid, forced:true);
1890 void checkSaveState () {
1891 if (lastStateSaveTime+dur!"seconds"(30) <= MonoTime.currTime) {
1892 //writeln("saving state...");
1893 saveCurrentState();
1894 lastStateSaveTime = MonoTime.currTime;
1895 if (lastDecodedTid) {
1896 immutable maxuid = chiroGetTreePaneTableMaxUId();
1897 if (maxuid && maxuid > lastMaxTidUid) {
1898 // something was changed in the database, rescal
1899 updateViewsIfTid(lastDecodedTid);
1905 void saveCurrentState () {
1906 transacted!"Conf"{
1907 chiroSetOption("/mainpane/folders/toptid", folderTopTag);
1908 chiroSetOption("/mainpane/folders/currtid", folderCurrTag);
1909 saveThreadListPositions(transaction:false);
1913 void loadSavedState () {
1914 chiroGetOption(folderTopTag, "/mainpane/folders/toptid");
1915 chiroGetOption(folderCurrTag, "/mainpane/folders/currtid");
1916 //conwriteln("curr: ", folderCurrTag);
1917 //conwriteln(" top: ", folderTopTag);
1918 rescanFolders(forced:true);
1922 private void threadListPositionDirty () nothrow @safe @nogc {
1923 saveMsgListPositions = true;
1926 private void saveThreadListPositionsInternal () {
1927 if (lastDecodedTagName.length == 0) return;
1928 import core.stdc.stdio : snprintf;
1929 const(char)[] tn = lastDecodedTagName.getData;
1930 char[128] xname = void;
1931 auto xlen = snprintf(xname.ptr, xname.sizeof, "/mainpane/msgview/current%.*s", cast(uint)tn.length, tn.ptr);
1932 chiroSetOptionUInts(xname[0..xlen], msglistTopUId, msglistCurrUId);
1935 private void saveThreadListPositions (immutable bool transaction=true) {
1936 if (!saveMsgListPositions) return;
1937 saveMsgListPositions = false;
1938 if (lastDecodedTid == 0) return;
1939 if (transaction) {
1940 transacted!"Conf"(&saveThreadListPositionsInternal);
1941 } else {
1942 saveThreadListPositionsInternal();
1946 private void loadThreadListPositions () {
1947 saveMsgListPositions = false;
1948 msglistTopUId = msglistCurrUId = 0;
1949 if (lastDecodedTid == 0) return;
1950 import core.stdc.stdio : snprintf;
1951 char[128] xname = void;
1952 const(char)[] tn = lastDecodedTagName.getData;
1953 auto xlen = snprintf(xname.ptr, xname.sizeof, "/mainpane/msgview/current%.*s", cast(uint)tn.length, tn.ptr);
1954 chiroGetOptionUInts(ref msglistTopUId, ref msglistCurrUId, xname[0..xlen]);
1955 setupUnreadTimer();
1959 private int getFolderMonthLimit () {
1960 version(none) {
1961 import core.stdc.stdio : snprintf;
1962 char[1024] xname = void;
1963 if (lastDecodedTid == 0) return chiroGetOption!int("/mainpane/msgview/monthlimit", 6);
1964 bool exists;
1965 const(char)[] tn = lastDecodedTagName.getData;
1966 for (;;) {
1967 auto len = snprintf(xname.ptr, xname.sizeof, "/mainpane/msgview/monthlimit%.*s", cast(uint)tn.length, tn.ptr);
1968 int v = chiroGetOptionEx!int(xname[0..len], out exists);
1969 //writeln(tn, " :: ", v, " :: ", exists);
1970 if (exists) return v;
1971 auto slp = tn.lastIndexOf('/', 1);
1972 if (slp <= 0) break;
1973 tn = tn[0..slp];
1975 return chiroGetOption!int("/mainpane/msgview/monthlimit", 6);
1976 } else {
1977 if (lastDecodedTid == 0) return chiroGetOption!int("/mainpane/msgview/monthlimit", 6);
1978 return chiroGetTagMonthLimit(lastDecodedTagName.getData, 6);
1983 void rescanFolders (bool forced=false) {
1984 if (!.rescanFolders()) { if (!forced) return; }
1985 folderTopIndex = folderCurrIndex = 0;
1986 bool foundTop = false, foundCurr = false;
1987 foreach (immutable idx, const FolderInfo fi; folderList) {
1988 if (!foundTop && fi.name == folderTopTag) { foundTop = true; folderTopIndex = cast(int)idx; }
1989 if (!foundCurr && fi.name == folderCurrTag) { foundCurr = true; folderCurrIndex = cast(int)idx; }
1991 if (!foundTop) folderTopTag.clear();
1992 if (!foundCurr) folderCurrTag.clear();
1995 void folderMakeCurVisible () {
1996 rescanFolders();
1997 if (folderList.length) {
1998 if (folderCurrIndex >= folderList.length) folderCurrIndex = cast(uint)folderList.length-1;
1999 if (folderTopIndex >= folderList.length) folderTopIndex = cast(uint)folderList.length-1;
2000 if (folderCurrIndex-3 < folderTopIndex) {
2001 folderTopIndex = folderCurrIndex-3;
2002 if (folderTopIndex < 0) folderTopIndex = 0;
2004 int hgt = screenHeight/(gxTextHeightUtf+2)-1;
2005 if (hgt < 1) hgt = 1;
2006 if (folderCurrIndex+2 > folderTopIndex+hgt) {
2007 folderTopIndex = (folderCurrIndex+2 > hgt ? folderCurrIndex+2-hgt : 0);
2008 if (folderTopIndex < 0) folderTopIndex = 0;
2010 if (folderTopTag != folderList[folderTopIndex].name) folderTopTag = folderList[folderTopIndex].name;
2011 if (folderCurrTag != folderList[folderCurrIndex].name) folderCurrTag = folderList[folderCurrIndex].name;
2012 } else {
2013 folderCurrIndex = folderTopIndex = 0;
2017 private void switchToFolderTid (const uint tid, bool forced=false) {
2018 //setupTrayAnimation();
2019 if (!forced && tid == lastDecodedTid) return;
2020 saveThreadListPositions();
2021 if (lastDecodedTid != 0) chiroDeletePurgedWithTag(lastDecodedTid);
2022 // rescan
2023 lastDecodedTid = tid;
2024 if (tid != 0) {
2025 lastDecodedTagName = chiroGetTagName(tid);
2026 immutable int monthlimit = getFolderMonthLimit();
2027 chiroCreateTreePaneTable(tid, lastmonthes:monthlimit);
2028 // load position
2029 loadThreadListPositions();
2030 // top
2031 if (!chiroIsTreePaneTableUidValid(msglistTopUId)) {
2032 msglistTopUId = chiroGetTreePaneTableIndex2Uid(0);
2033 threadListPositionDirty();
2035 // current
2036 if (!chiroIsTreePaneTableUidValid(msglistCurrUId)) {
2037 msglistCurrUId = chiroGetTreePaneTableIndex2Uid(0);
2038 threadListPositionDirty();
2040 lastMaxTidUid = chiroGetTreePaneTableMaxUId();
2041 setupUnreadTimer();
2042 } else {
2043 lastDecodedTagName.clear();
2044 msglistTopUId = 0;
2045 msglistCurrUId = 0;
2046 chiroClearTreePaneTable();
2050 void folderSetToIndex (int idx) {
2051 if (idx < 0 || idx >= folderList.length) return;
2052 if (idx == folderCurrIndex) return;
2053 folderCurrIndex = idx;
2054 folderCurrTag = folderList[folderCurrIndex].name;
2055 switchToFolderTid(folderList[folderCurrIndex].tagid);
2058 bool folderUpOne () {
2059 if (folderList.length == 0) return false;
2060 if (folderCurrIndex <= 0) return false;
2061 --folderCurrIndex;
2062 folderCurrTag = folderList[folderCurrIndex].name;
2063 setupUnreadTimer();
2064 return true;
2067 bool folderDownOne () {
2068 if (folderList.length == 0) return false;
2069 if (folderCurrIndex+1 >= cast(int)folderList.length) return false;
2070 ++folderCurrIndex;
2071 folderCurrTag = folderList[folderCurrIndex].name;
2072 setupUnreadTimer();
2073 return true;
2076 bool threadListHome () {
2077 if (lastDecodedTid == 0) return false;
2078 immutable uint firstUid = chiroGetTreePaneTableFirstUid();
2079 if (!firstUid || firstUid == msglistCurrUId) return false;
2080 msglistCurrUId = firstUid;
2081 threadListPositionDirty();
2082 setupUnreadTimer();
2083 return true;
2086 bool threadListEnd () {
2087 if (lastDecodedTid == 0) return false;
2088 immutable uint lastUid = chiroGetTreePaneTableLastUid();
2089 if (!lastUid || lastUid == msglistCurrUId) return false;
2090 msglistCurrUId = lastUid;
2091 threadListPositionDirty();
2092 setupUnreadTimer();
2093 return true;
2096 bool threadListUp () {
2097 import iv.timer;
2098 if (lastDecodedTid == 0) return false;
2099 auto ctm = Timer(true);
2100 immutable uint prevUid = chiroGetTreePaneTablePrevUid(msglistCurrUId);
2101 ctm.stop;
2102 if (ChiroTimerExEnabled) writeln("threadListUp time: ", ctm);
2103 if (!prevUid || prevUid == msglistCurrUId) return false;
2104 msglistCurrUId = prevUid;
2105 threadListPositionDirty();
2106 setupUnreadTimer();
2107 return true;
2110 bool threadListDown () {
2111 import iv.timer;
2112 if (lastDecodedTid == 0) return false;
2113 auto ctm = Timer(true);
2114 immutable uint nextUid = chiroGetTreePaneTableNextUid(msglistCurrUId);
2115 ctm.stop;
2116 if (ChiroTimerExEnabled) writeln("threadListDown time: ", ctm);
2117 if (!nextUid || nextUid == msglistCurrUId) return false;
2118 msglistCurrUId = nextUid;
2119 threadListPositionDirty();
2120 setupUnreadTimer();
2121 return true;
2124 bool threadListScrollUp (bool movecurrent) {
2125 import iv.timer;
2126 if (lastDecodedTid == 0) return false;
2127 auto ctm = Timer(true);
2128 immutable uint topPrevUid = chiroGetTreePaneTablePrevUid(msglistTopUId);
2129 ctm.stop;
2130 if (ChiroTimerExEnabled) conwriteln("threadListScrollUp: prevtop time: ", ctm);
2131 if (!topPrevUid || topPrevUid == msglistTopUId) return false;
2132 ctm.restart;
2133 immutable uint currPrevUid = (movecurrent ? chiroGetTreePaneTablePrevUid(msglistCurrUId) : 0);
2134 ctm.stop;
2135 if (movecurrent && ChiroTimerExEnabled) conwriteln("threadListScrollUp: prevcurr time: ", ctm);
2136 if (movecurrent && !currPrevUid) return false;
2137 msglistTopUId = topPrevUid;
2138 if (movecurrent) {
2139 msglistCurrUId = currPrevUid;
2140 setupUnreadTimer();
2142 threadListPositionDirty();
2143 return true;
2146 bool threadListScrollDown (bool movecurrent) {
2147 import iv.timer;
2148 if (lastDecodedTid == 0) return false;
2149 auto ctm = Timer(true);
2150 immutable uint currNextUid = (movecurrent ? chiroGetTreePaneTableNextUid(msglistCurrUId) : 0);
2151 ctm.stop;
2152 if (movecurrent && ChiroTimerExEnabled) writeln("threadListScrollDown: nextcurr time: ", ctm);
2153 if (movecurrent && (!currNextUid || currNextUid == msglistCurrUId)) return false;
2154 ctm.restart;
2155 immutable uint topNextUid = chiroGetTreePaneTableNextUid(msglistTopUId);
2156 ctm.stop;
2157 if (ChiroTimerExEnabled) writeln("threadListScrollDown: nexttop time: ", ctm);
2158 if (!topNextUid) return false;
2159 msglistTopUId = topNextUid;
2160 if (movecurrent) {
2161 msglistCurrUId = currNextUid;
2162 setupUnreadTimer();
2164 threadListPositionDirty();
2165 return true;
2168 bool threadListPageUp () {
2169 import iv.timer;
2170 bool res = false;
2171 int hgt = guiThreadListHeight/gxTextHeightUtf-1;
2172 if (hgt < 1) hgt = 1;
2173 auto ctm = Timer(true);
2174 foreach (; 0..hgt) {
2175 if (!threadListScrollUp(movecurrent:true)) break;
2176 res = true;
2178 ctm.stop;
2179 if (ChiroTimerExEnabled) writeln("threadListPageUp time: ", ctm);
2180 if (res) setupUnreadTimer();
2181 return res;
2184 bool threadListPageDown () {
2185 import iv.timer;
2186 bool res = false;
2187 int hgt = guiThreadListHeight/gxTextHeightUtf-1;
2188 if (hgt < 1) hgt = 1;
2189 auto ctm = Timer(true);
2190 foreach (; 0..hgt) {
2191 if (!threadListScrollDown(movecurrent:true)) break;
2192 res = true;
2194 ctm.stop;
2195 if (ChiroTimerExEnabled) writeln("threadListPageDown time: ", ctm);
2196 if (res) setupUnreadTimer();
2197 return res;
2201 // //////////////////////////////////////////////////////////////////// //
2202 static struct WebLink {
2203 int ly; // in lines
2204 int x, len; // in pixels
2205 dynstring url;
2206 dynstring text; // visual text
2207 int attachnum = -1;
2208 bool nofirst = false;
2210 @property bool isAttach () const pure nothrow @safe @nogc { return (attachnum >= 0); }
2213 WebLink[] emurls;
2214 int lastUrlIndex = -1;
2216 void appendUrl (in ref WebLink wl) {
2217 immutable oldcap = emurls.capacity;
2218 if (oldcap && emurls.length < oldcap) {
2219 import core.stdc.string : memset;
2220 memset(emurls.ptr+emurls.length, 0, (oldcap-emurls.length)*emurls[0].sizeof);
2222 emurls ~= WebLink();
2223 if (emurls.capacity > oldcap) {
2224 import core.stdc.string : memset;
2225 memset(emurls.ptr+oldcap, 0, (emurls.capacity-oldcap)*emurls[0].sizeof);
2227 emurls[$-1] = wl;
2230 void appendEmLine () {
2231 immutable oldcap = emlines.capacity;
2232 if (oldcap && emlines.length < oldcap) {
2233 import core.stdc.string : memset;
2234 memset(emlines.ptr+emlines.length, 0, (oldcap-emlines.length)*emlines[0].sizeof);
2236 emlines ~= dynstring();
2237 if (emlines.capacity > oldcap) {
2238 import core.stdc.string : memset;
2239 memset(emlines.ptr+oldcap, 0, (emlines.capacity-oldcap)*emlines[0].sizeof);
2243 void appendEmLine (in ref dynstring s) {
2244 appendEmLine();
2245 emlines[$-1] = s;
2248 void appendEmLine (const(char)[] buf) {
2249 appendEmLine();
2250 emlines[$-1] = dynstring(buf);
2253 void clearDecodedText () {
2254 import core.stdc.string : memset;
2255 if (emlines.capacity) {
2256 //{ import core.stdc.stdio : stderr, fprintf; fprintf(stderr, "000: *** clearing %u emlines (%u) ***\n", cast(uint)emlines.length, cast(uint)emlines.capacity); }
2257 foreach (ref dynstring s; emlines) s.clear();
2258 //{ import core.stdc.stdio : stderr, fprintf; fprintf(stderr, "001: *** clearing %u emlines (%u) ***\n", cast(uint)emlines.length, cast(uint)emlines.capacity); }
2259 memset(emlines.ptr, 0, emlines.capacity*emlines[0].sizeof);
2260 //{ import core.stdc.stdio : stderr, fprintf; fprintf(stderr, "002: *** clearing %u emlines (%u) ***\n", cast(uint)emlines.length, cast(uint)emlines.capacity); }
2261 emlines.length = 0;
2262 //{ import core.stdc.stdio : stderr, fprintf; fprintf(stderr, "003: *** clearing %u emlines (%u) ***\n", cast(uint)emlines.length, cast(uint)emlines.capacity); }
2263 if (emlines.capacity) emlines.assumeSafeAppend;
2264 //{ import core.stdc.stdio : stderr, fprintf; fprintf(stderr, "004: *** clearing %u emlines (%u) ***\n", cast(uint)emlines.length, cast(uint)emlines.capacity); }
2265 if (emlines.capacity) memset(emlines.ptr, 0, emlines.capacity*emlines[0].sizeof);
2266 //{ import core.stdc.stdio : stderr, fprintf; fprintf(stderr, "005: *** clearing %u emlines (%u) ***\n", cast(uint)emlines.length, cast(uint)emlines.capacity); }
2268 if (emurls.capacity) {
2269 foreach (ref WebLink l; emurls) { l.url.clear(); l.text.clear(); }
2270 memset(emurls.ptr, 0, emurls.capacity*emurls[0].sizeof);
2271 emurls.length = 0;
2272 if (emurls.capacity) emurls.assumeSafeAppend;
2273 if (emurls.capacity) memset(emurls.ptr, 0, emurls.capacity*emurls[0].sizeof);
2275 lastDecodedUId = 0;
2276 articleTextTopLine = 0;
2277 articleDestTextTopLine = 0;
2278 lastUrlIndex = -1;
2279 arttoname.clear();
2280 arttomail.clear();
2281 artfromname.clear();
2282 artfrommail.clear();
2283 artsubj.clear();
2284 arttime.clear();
2287 // <0: not on url
2288 int findUrlIndexAt (int mx, int my) {
2289 int tpX0 = guiGroupListWidth+2+1;
2290 int tpX1 = screenWidth-1-guiMessageTextLPad*2-guiScrollbarWidth;
2291 int tpY0 = guiThreadListHeight+1;
2292 int tpY1 = screenHeight-1;
2294 int y = tpY0+linesInHeader*gxTextHeightUtf+2+1+guiMessageTextVPad;
2296 if (mx < tpX0 || mx > tpX1) return -1;
2297 if (my < y || my > tpY1) return -1;
2299 mx -= tpX0;
2301 // yeah, i can easily calculate this, i know
2302 uint idx = articleTextTopLine;
2303 while (idx < emlines.length && y < screenHeight) {
2304 if (my >= y && my < y+gxTextHeightUtf) {
2305 foreach (immutable uidx, const ref WebLink wl; emurls) {
2306 //conwriteln("checking url [#", uidx, "]; idx=", idx, "; ly=", wl.ly);
2307 if (wl.ly == idx) {
2308 if (mx >= wl.x && mx < wl.x+wl.len) return cast(int)uidx;
2312 ++idx;
2313 y += gxTextHeightUtf+guiMessageTextInterline;
2316 return -1;
2319 WebLink* findUrlAt (int mx, int my) {
2320 auto uidx = findUrlIndexAt(mx, my);
2321 return (uidx >= 0 ? &emurls[uidx] : null);
2324 private void emlDetectUrls (uint textlines) {
2325 static immutable string[3] protos = [ "https", "http", "ftp" ];
2327 lastUrlIndex = -1;
2329 static sptrdiff urlepos (const(char)[] s, sptrdiff spos) {
2330 assert(spos < s.length);
2331 spos = s.indexOf("://", spos);
2332 assert(spos >= 0);
2333 spos += 3;
2334 // host
2335 while (spos < s.length) {
2336 char ch = s[spos];
2337 if (ch == '/') break;
2338 if (ch <= ' ') return spos;
2339 if (ch != '.' && ch != '-' && !ch.isalnum) return spos;
2340 ++spos;
2342 if (spos >= s.length) return cast(sptrdiff)s.length;
2343 // path
2344 assert(s[spos] == '/');
2345 char[16] brcmap;
2346 usize brlevel = 0;
2347 bool wasSharp = false;
2348 for (; spos < s.length; ++spos) {
2349 import iv.strex : isalnum;
2350 char ch = s[spos];
2351 if (ch <= ' ' || ch == '<' || ch == '>' || ch == '"' || ch == '\'' || ch >= 127) return spos;
2352 // hash
2353 if (ch == '#') {
2354 if (wasSharp) return spos;
2355 wasSharp = true;
2356 brlevel = 0;
2357 continue;
2359 // path delimiter
2360 if (ch == '/') {
2361 brlevel = 0;
2362 continue;
2364 // opening bracket
2365 if (ch == '(' || ch == '{' || ch == '[') {
2366 if (brlevel >= brcmap.length) return spos; // too nested
2367 if (s.length-spos < 2) return spos; // no more chars, ignore
2368 if (!isalnum(s[spos+1]) && s[spos+1] != '_' && s[spos+1] != '%') return spos; // ignore
2369 // looks like URL part
2370 final switch (ch) {
2371 case '(': ch = ')'; break;
2372 case '[': ch = ']'; break;
2373 case '{': ch = '}'; break;
2375 brcmap[brlevel++] = ch;
2376 continue;
2378 // closing bracket
2379 if (ch == ')' || ch == '}' || ch == ']') {
2380 if (brlevel == 0 || ch != brcmap[brlevel-1]) return spos;
2381 --brlevel;
2382 continue;
2384 // other punctuation
2385 if (brlevel == 0 && !isalnum(ch) && ch != '_' && ch != '%') {
2386 // other special chars
2387 if (s.length-spos < 2) return spos; // no more chars, ignore
2388 if (!isalnum(s[spos+1]) && s[spos+1] != '_' && s[spos+1] != '%') {
2389 if (ch == '.' || ch == '!' || ch == ';' || ch == ',' || s[spos+1] != ch) return spos; // ignore
2392 ++spos;
2394 if (spos >= s.length) spos = cast(sptrdiff)s.length;
2395 return spos;
2398 if (textlines > emlines.length) textlines = cast(uint)emlines.length; // just in case
2399 foreach (immutable cy, dynstring s; emlines[0..textlines]) {
2400 if (s.length == 0) continue;
2401 auto pos = s.indexOf("://");
2402 while (pos > 0) {
2403 bool found = false;
2404 auto spos = pos;
2405 foreach (string proto; protos) {
2406 if (spos >= proto.length && proto.strEquCI(s[spos-proto.length..spos])) {
2407 if (spos == proto.length || !s[spos-proto.length-1].isalnum) {
2408 found = true;
2409 spos -= proto.length;
2410 break;
2414 if (found) {
2415 // find URL end
2416 auto epos = urlepos(s, spos);
2417 WebLink wl;
2418 wl.nofirst = (spos > 0);
2419 wl.ly = cast(int)cy;
2420 auto kr = GxKerning(4, 0);
2421 s[0..epos].utfByDCharSPos(delegate (dchar ch, usize stpos) {
2422 int w = kr.fixWidthPre(ch);
2423 if (stpos == spos) wl.x = w;
2425 wl.len = kr.finalWidth-wl.x;
2426 wl.url = wl.text = s[spos..epos];
2427 appendUrl(wl); //emurls ~= wl;
2428 pos = epos;
2429 } else {
2430 ++pos;
2432 pos = s.indexOf("://", pos);
2436 int attachcount = 0;
2437 foreach (immutable uint cy; textlines..cast(uint)emlines.length) {
2438 dynstring s = emlines[cy];
2439 if (s.length == 0) continue;
2440 auto spos = s.indexOf("attach:");
2441 if (spos < 0) continue;
2442 auto epos = spos+7;
2443 while (epos < s.length && s.ptr[epos] > ' ') ++epos;
2444 //if (attachcount >= parts.length) break;
2445 WebLink wl;
2446 wl.nofirst = (spos > 0);
2447 wl.ly = cast(int)cy;
2448 //wl.x = gxTextWidthUtf(s[0..spos]);
2449 //wl.len = gxTextWidthUtf(s[spos..epos]);
2450 auto kr = GxKerning(4, 0);
2451 s[0..epos].utfByDCharSPos(delegate (dchar ch, usize stpos) {
2452 int w = kr.fixWidthPre(ch);
2453 if (stpos == spos) wl.x = w;
2455 wl.len = kr.finalWidth-wl.x;
2456 wl.url = wl.text = s[spos..epos];
2457 //if (spos > 0) ++wl.x; // this makes text bolder, no need to
2458 wl.attachnum = attachcount;
2459 //wl.attachfname = s[spos+7..epos];
2460 //wl.part = parts[attachcount];
2461 ++attachcount;
2462 appendUrl(wl); //emurls ~= wl;
2466 bool needToDecodeArticleTextNL (uint uid) const nothrow @trusted @nogc {
2467 return (lastDecodedUId != uid);
2470 // fld is locked here
2471 void decodeArticleTextNL (uint uid) {
2472 static auto stmtGet = LazyStatement!"View"(`
2473 SELECT
2474 from_name AS fromName
2475 , from_mail AS fromMail
2476 , to_name AS toName
2477 , to_mail AS toMail
2478 , subj AS subj
2479 , datetime(threads.time, 'unixepoch') AS time
2480 , ChiroUnpack(content_text.content) AS text
2481 , ChiroUnpack(content_html.content) AS html
2482 FROM info
2483 INNER JOIN threads USING(uid)
2484 INNER JOIN content_text USING(uid)
2485 INNER JOIN content_html USING(uid)
2486 WHERE uid=:uid
2487 LIMIT 1
2488 ;`);
2490 if (!needToDecodeArticleTextNL(uid)) return;
2492 //if (uid == 0) { clearDecodedText(); return; }
2493 clearDecodedText();
2494 lastDecodedUId = uid;
2496 // get article content
2497 //FIXME: see `art.getTextContent()` for GPG decryption!
2498 DynStr artcontent;
2499 bool ishtml = false;
2500 bool htmlheader = false;
2501 foreach (auto row; stmtGet.st.bind(":uid", uid).range) {
2502 auto text = row.text!SQ3Text;
2503 auto html = row.html!SQ3Text;
2504 bool isHtml = ((text.xstrip.length == 0 || preferHtmlContent) && html.xstrip.length != 0);
2505 bool forceHtml = false;
2506 if (detectHtmlContent && !isHtml && html.xstrip.length == 0 && text.xstrip.length != 0) {
2507 auto tmp = text.xstrip;
2508 if (tmp.startsWithCI("<!DOCTYPE")) forceHtml = true;
2510 //conwriteln("! ", text.xstrip.length, " ! ", html.xstrip.length);
2511 if (isHtml || forceHtml) {
2512 version(article_can_into_html) {
2513 try {
2514 string s = htmlToText((forceHtml ? text.idup : html.idup), false);
2515 artcontent ~= s;
2516 artcontent.removeASCIICtrls();
2517 htmlheader = true;
2518 } catch (Exception e) {
2519 artcontent ~= (forceHtml ? text : html);
2521 } else {
2522 artcontent ~= (forceHtml ? text : html);
2524 ishtml = true;
2525 } else if (text.length != 0) {
2526 artcontent ~= text;
2527 } else {
2528 artcontent ~= "no text content";
2530 arttoname = row.toName!SQ3Text;
2531 arttomail = row.toMail!SQ3Text;
2532 artfromname = row.fromName!SQ3Text;
2533 artfrommail = row.fromMail!SQ3Text;
2534 artsubj = row.subj!SQ3Text;
2535 arttime = row.time!SQ3Text;
2536 if (artsubj.length == 0) artsubj = "no subject";
2539 if (artcontent.length == 0) return; // no text
2540 appendEmLine(); //emlines ~= dynstring(); // hack; this dummy line will be removed
2541 bool skipEmptyLines = true;
2543 if (htmlheader) {
2544 appendEmLine("\x01==============================================");
2545 appendEmLine("\x01--- HTML CONTENT ---");
2546 appendEmLine("\x01==============================================");
2547 //emlines ~= null;
2550 bool lastEndsWithSpace () { return (emlines[$-1].length ? emlines[$-1][$-1] == ' ' : false); }
2552 int lastQLevel = 0;
2554 static dynstring addQuotes (dynstring s, int qlevel) {
2555 enum QuoteStr = ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ";
2556 if (qlevel <= 0) return s;
2557 if (qlevel > QuoteStr.length-1) qlevel = cast(int)QuoteStr.length-1;
2558 return dynstring(QuoteStr[$-qlevel-1..$])~s;
2561 // returns quote level
2562 static int removeQuoting (ref ConString s) {
2563 // calculate quote level
2564 int qlevel = 0;
2565 if (s.length && s[0] == '>') {
2566 usize lastqpos = 0, pos = 0;
2567 while (pos < s.length) {
2568 if (s.ptr[pos] != '>') {
2569 if (s.ptr[pos] != ' ') break;
2570 } else {
2571 lastqpos = pos;
2572 ++qlevel;
2574 ++pos;
2576 if (s.length-lastqpos > 1 && s.ptr[lastqpos+1] == ' ') ++lastqpos;
2577 ++lastqpos;
2578 s = s[lastqpos..$];
2580 return qlevel;
2583 bool inCode = false;
2585 void putLine (ConString s) {
2586 int qlevel = (ishtml ? 0 : removeQuoting(s));
2587 //conwriteln("qlevel=", qlevel, "; s=[", s, "]");
2588 // empty line: just insert it
2589 if (s.length == 0) {
2590 if (skipEmptyLines) return;
2591 if (qlevel == 0 && emlines[$-1].xstripright.length == 0) return;
2592 appendEmLine(addQuotes(dynstring(), qlevel).xstripright);
2593 } else {
2594 if (s.xstrip.length == 0) {
2595 if (skipEmptyLines) return;
2596 if (qlevel == 0 && emlines[$-1].xstripright.length == 0) return;
2598 skipEmptyLines = false;
2599 // join code lines if it is possible
2600 if (inCode && qlevel == lastQLevel && lastEndsWithSpace) {
2601 //conwriteln("<", s, ">");
2602 emlines[$-1] ~= addQuotes(dynstring(s.xstrip), qlevel);
2603 return;
2605 // two spaces at the beginning usually means "this is code"; don't wrap it
2606 if (s.length >= 1 && s[0] == '\t') {
2607 appendEmLine(addQuotes(dynstring(s), qlevel));
2608 // join next lines if it is possible
2609 inCode = true;
2610 //conwriteln("[", s, "]");
2611 lastQLevel = qlevel;
2612 return;
2614 inCode = false;
2615 // can we append?
2616 bool newline = false;
2617 if (lastQLevel != qlevel || !lastEndsWithSpace) {
2618 newline = true;
2619 } else {
2620 // append words
2621 //while (s.length > 1 && s.ptr[0] <= ' ') s = s[1..$];
2623 while (s.length) {
2624 usize epos = 0;
2625 if (newline) {
2626 while (epos < s.length && s.ptr[epos] <= ' ') ++epos;
2627 } else {
2628 //assert(s[0] > ' ');
2629 while (epos < s.length && s.ptr[epos] <= ' ') ++epos;
2631 while (epos < s.length && s.ptr[epos] > ' ') ++epos;
2632 auto xlen = epos;
2633 while (epos < s.length && s.ptr[epos] <= ' ') ++epos;
2634 if (!newline && emlines[$-1].length+xlen <= 80) {
2635 // no wrapping, continue last line
2636 emlines[$-1] ~= s[0..epos];
2637 } else {
2638 newline = false;
2639 // wrapping; new line
2640 appendEmLine(addQuotes(dynstring(s[0..epos]), qlevel));
2642 s = s[epos..$];
2644 if (newline) appendEmLine(addQuotes(dynstring(), qlevel));
2646 lastQLevel = qlevel;
2649 try {
2650 //foreach (ConString s; LineIterator!false(art.getTextContent)) putLine(s);
2651 const(char)[] buf = artcontent;
2652 while (buf.length) {
2653 usize epos = skipOneLine(buf, 0);
2654 usize eend = epos;
2655 if (eend >= 2 && buf[eend-2] == '\r' && buf[eend-1] == '\n') eend -= 2;
2656 else if (eend >= 1 && buf[eend-1] == '\n') eend -= 1;
2657 putLine(buf[0..eend]);
2658 buf = buf[epos..$];
2660 // remove first dummy line
2661 if (emlines.length) emlines = emlines[1..$];
2662 // remove trailing empty lines
2663 while (emlines.length && emlines[$-1].xstrip.length == 0) emlines.length -= 1;
2664 } catch (Exception e) {
2665 conwriteln("================================= ERROR: ", e.msg, " =================================");
2666 conwriteln(e.toString);
2670 // attaches
2671 auto lcount = cast(uint)emlines.length;
2672 emlinesBeforeAttaches = lcount;
2674 uint attcount = 0;
2675 static auto statAttaches = LazyStatement!"View"(`
2676 SELECT
2677 idx AS idx
2678 , mime AS mime
2679 , name AS name
2680 FROM attaches
2681 WHERE uid=:uid
2682 ORDER BY idx
2683 ;`);
2684 foreach (auto row; statAttaches.st.bind(":uid", uid).range) {
2685 import core.stdc.stdio : snprintf;
2686 if (attcount == 0) { appendEmLine(); appendEmLine(); }
2687 DynStr att;
2688 char[128] buf = void;
2689 //if (type.length == 0) type = "unknown/unknown";
2690 //string s = " [%02s] attach:%s -- %s".format(attcount, Article.fixAttachmentName(filename), type);
2691 auto mime = row.mime!SQ3Text;
2692 auto name = row.name!SQ3Text/*.decodeSubj*/;
2693 auto len = snprintf(buf.ptr, buf.sizeof, " [%2u] attach:%.*s -- %.*s",
2694 attcount, cast(uint)name.length, name.ptr, cast(uint)mime.length, mime.ptr);
2695 assert(len > 0);
2696 if (len > buf.sizeof) len = cast(int)buf.sizeof;
2697 appendEmLine(buf[0..len]);
2698 ++attcount;
2700 /*FIXME
2701 art.forEachAttachment(delegate(ConString type, ConString filename) {
2702 if (attcount == 0) { emlines ~= null; emlines ~= null; }
2703 import std.format : format;
2704 if (type.length == 0) type = "unknown/unknown";
2705 string s = " [%02s] attach:%s -- %s".format(attcount, Article.fixAttachmentName(filename), type);
2706 emlines ~= s;
2707 ++attcount;
2708 return false;
2711 emlDetectUrls(lcount);
2714 @property int visibleArticleLines () {
2715 int y = guiThreadListHeight+1+linesInHeader*gxTextHeightUtf+2+guiMessageTextVPad;
2716 return (screenHeight-y)/(gxTextHeightUtf+guiMessageTextInterline);
2719 void normalizeArticleTopLine () {
2720 int lines = visibleArticleLines;
2721 if (lines < 1 || emlines.length <= lines) {
2722 articleTextTopLine = 0;
2723 articleDestTextTopLine = 0;
2724 } else {
2725 if (articleTextTopLine < 0) articleTextTopLine = 0;
2726 if (articleTextTopLine+lines > emlines.length) {
2727 articleTextTopLine = cast(int)emlines.length-lines;
2728 if (articleTextTopLine < 0) articleTextTopLine = 0;
2733 void doScrollStep () {
2734 auto oldtop = articleTextTopLine;
2735 foreach (immutable _; 0..6) {
2736 normalizeArticleTopLine();
2737 if (articleDestTextTopLine < articleTextTopLine) {
2738 --articleTextTopLine;
2739 } else if (articleDestTextTopLine > articleTextTopLine) {
2740 ++articleTextTopLine;
2741 } else {
2742 break;
2744 normalizeArticleTopLine();
2746 if (articleTextTopLine == oldtop) {
2747 // can't scroll anymore
2748 articleDestTextTopLine = articleTextTopLine;
2749 return;
2751 postScreenRebuild();
2752 postArticleScroll();
2755 void scrollBy (int delta) {
2756 articleDestTextTopLine += delta;
2757 doScrollStep();
2760 void scrollByPageUp () {
2761 int lines = visibleArticleLines-scrollKeepLines;
2762 if (lines < 1) lines = 1;
2763 scrollBy(-lines);
2766 void scrollByPageDown () {
2767 int lines = visibleArticleLines-scrollKeepLines;
2768 if (lines < 1) lines = 1;
2769 scrollBy(lines);
2772 // ////////////////////////////////////////////////////////////////// //
2773 // this also fixes current/top uids
2774 void getAndFixThreadListIndicies (out int topidx, out int curridx) {
2775 int hgt = guiThreadListHeight/gxTextHeightUtf-1;
2776 if (hgt < 1) hgt = 1;
2778 topidx = chiroGetTreePaneTableUid2Index(msglistTopUId);
2779 immutable origTopIdx = topidx;
2780 if (topidx < 0) topidx = 0;
2781 curridx = chiroGetTreePaneTableUid2Index(msglistCurrUId);
2782 immutable origCurrIdx = curridx;
2783 if (curridx < 0) curridx = 0;
2785 //conwriteln("topuid: ", msglistTopUId, "; topidx=", topidx);
2786 //conwriteln("curruid: ", msglistCurrUId, "; curridx=", curridx);
2788 if (curridx-3 < topidx) {
2789 topidx = curridx-3;
2790 if (topidx < 0) topidx = 0;
2792 if (curridx+3 > topidx+hgt) {
2793 topidx = (curridx+3 > hgt ? curridx+3-hgt : 0);
2794 if (topidx < 0) topidx = 0;
2797 if (origCurrIdx != curridx || msglistCurrUId == 0) {
2798 immutable ocurr = msglistCurrUId;
2799 msglistCurrUId = chiroGetTreePaneTableIndex2Uid(curridx);
2800 if (ocurr != msglistCurrUId) {
2801 threadListPositionDirty();
2802 setupUnreadTimer();
2806 if (origTopIdx != topidx || msglistTopUId == 0) {
2807 immutable otop = msglistTopUId;
2808 msglistTopUId = chiroGetTreePaneTableIndex2Uid(topidx);
2809 if (otop != msglistTopUId) threadListPositionDirty();
2813 void setupUnreadTimer () {
2814 postMarkAsUnreadEvent();
2817 // //////////////////////////////////////////////////////////////////// //
2818 //TODO: move parts to widgets
2819 override void onPaint () {
2820 viewDataVersion = dbView.getDataVersion();
2821 gxClipReset();
2823 gxFillRect(0, 0, guiGroupListWidth, screenHeight, getColor("grouplist-back"));
2824 gxVLine(guiGroupListWidth, 0, screenHeight, getColor("grouplist-divline"));
2826 gxFillRect(guiGroupListWidth+1, 0, screenWidth, guiThreadListHeight, getColor("threadlist-back"));
2827 gxHLine(guiGroupListWidth+1, guiThreadListHeight, screenWidth, getColor("threadlist-divline"));
2829 // ////////////////////////////////////////////////////////////////// //
2830 void drawArticle (uint uid) {
2831 import core.stdc.stdio : snprintf;
2832 import std.format : format;
2833 import std.datetime;
2834 char[128] tbuf;
2835 const(char)[] tbufs;
2837 void xfmt (string s, const(char)[][] strs...) {
2838 int dpos = 0;
2839 void puts (const(char)[] s...) {
2840 foreach (char ch; s) {
2841 if (dpos >= tbuf.length) break;
2842 tbuf[dpos++] = ch;
2845 while (s.length) {
2846 if (strs.length && s.length > 1 && s[0] == '%' && s[1] == 's') {
2847 puts(strs[0]);
2848 strs = strs[1..$];
2849 s = s[2..$];
2850 } else {
2851 puts(s[0]);
2852 s = s[1..$];
2855 tbufs = tbuf[0..dpos];
2858 if (needToDecodeArticleTextNL(uid)) {
2859 decodeArticleTextNL(uid);
2863 gxClipX0 = guiGroupListWidth+2;
2864 gxClipX1 = screenWidth-1;
2865 gxClipY0 = guiThreadListHeight+1;
2866 gxClipY1 = screenHeight-1;
2868 gxClipRect = GxRect(GxPoint(guiGroupListWidth+2, guiThreadListHeight+1), GxPoint(screenWidth-1, screenHeight-1));
2870 int msx = lastMouseX;
2871 int msy = lastMouseY;
2873 int curDrawYMul = 1;
2875 // header
2876 immutable int hdrHeight = (3+(arttoname.length || arttomail.length ? 1 : 0))*gxTextHeightUtf+2;
2877 gxFillRect(gxClipRect.x0, gxClipRect.y0, gxClipRect.x1-gxClipRect.x0+1, hdrHeight, getColor("msg-header-back"));
2879 if (artfromname.length) {
2880 xfmt("From: %s <%s>", artfromname, artfrommail);
2881 } else {
2882 xfmt("From: %s", artfrommail);
2884 gxDrawTextUtf(gxClipRect.x0+guiMessageTextLPad, gxClipRect.y0+0*gxTextHeightUtf+1, tbufs, getColor("msg-header-from"));
2885 if (arttoname.length || arttomail.length) {
2886 if (arttoname.length) {
2887 xfmt("To: %s <%s>", arttoname, arttomail);
2888 } else {
2889 xfmt("To: %s", arttomail);
2891 gxDrawTextUtf(gxClipRect.x0+guiMessageTextLPad, gxClipRect.y0+curDrawYMul*gxTextHeightUtf+1, tbufs, getColor("msg-header-to"));
2892 ++curDrawYMul;
2894 xfmt("Subject: %s", (artsubj.length ? artsubj : "no subject"));
2895 gxDrawTextUtf(gxClipRect.x0+guiMessageTextLPad, gxClipRect.y0+curDrawYMul*gxTextHeightUtf+1, tbufs, getColor("msg-header-subj"));
2896 ++curDrawYMul;
2898 //auto t = SysTime.fromUnixTime(arttime);
2899 //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);
2900 auto tlen = snprintf(tbuf.ptr, tbuf.length, "Date: %.*s", cast(uint)arttime.length, arttime.ptr);
2901 gxDrawTextUtf(gxClipRect.x0+guiMessageTextLPad, gxClipRect.y0+curDrawYMul*gxTextHeightUtf+1, tbuf[0..tlen], getColor("msg-header-date"));
2902 ++curDrawYMul;
2906 // text
2907 linesInHeader = curDrawYMul;
2908 int y = gxClipRect.y0+curDrawYMul*gxTextHeightUtf+2;
2910 gxHLine(gxClipRect.x0, y, gxClipRect.x1-gxClipRect.x0+1, getColor("msg-header-divline"));
2911 ++y;
2912 gxFillRect(gxClipRect.x0, y, gxClipRect.x1-gxClipRect.x0+1, screenHeight-y, getColor("msg-text-back"));
2913 y += guiMessageTextVPad;
2915 immutable sty = y;
2917 normalizeArticleTopLine();
2919 bool drawUpMark = (articleTextTopLine > 0);
2920 bool drawDownMark = false;
2922 immutable uint messageTextNormalColor = getColor("msg-text-text");
2923 immutable uint messageTextQuote0Color = getColor("msg-text-quote0");
2924 immutable uint messageTextQuote1Color = getColor("msg-text-quote1");
2925 immutable uint messageTextHtmlHeaderColor = getColor("msg-text-html-sign");
2926 immutable uint messageTextLinkColor = getColor("msg-text-link");
2927 immutable uint messageTextLinkHoverColor = getColor("msg-text-link-hover");
2928 immutable uint messageTextLinkPressedColor = getColor("msg-text-link-pressed");
2930 uint idx = articleTextTopLine;
2931 bool msvisible = isMouseVisible;
2932 bool checkQuotes = true;
2933 if (emlines.length && emlines[0].length && emlines[0][0] == 1) {
2934 // html content
2935 checkQuotes = false;
2937 while (idx < emlines.length && y < screenHeight) {
2938 int qlevel = 0;
2939 dynstring s = emlines[idx];
2941 if (checkQuotes) {
2942 foreach (immutable char ch; s) {
2943 if (ch <= ' ') continue;
2944 if (ch != '>') break;
2945 ++qlevel;
2949 uint clr = messageTextNormalColor;
2950 if (qlevel) {
2951 final switch (qlevel%2) {
2952 case 0: clr = messageTextQuote0Color; break;
2953 case 1: clr = messageTextQuote1Color; break;
2957 if (!checkQuotes && s.length && s[0] == 1) {
2958 clr = messageTextHtmlHeaderColor;
2959 s = s[1..$];
2962 gxDrawTextUtfOpt(GxDrawTextOptions.TabColor(4, clr), gxClipRect.x0+guiMessageTextLPad, y, s);
2964 foreach (const ref WebLink wl; emurls) {
2965 if (wl.ly == idx) {
2966 uint lclr = messageTextLinkColor;
2967 if (msvisible && msy >= y && msy < y+gxTextHeightUtf &&
2968 msx >= gxClipRect.x0+1+guiMessageTextLPad+wl.x &&
2969 msx < gxClipRect.x0+1+guiMessageTextLPad+wl.x+wl.len)
2971 lclr = (lastMouseLeft ? messageTextLinkPressedColor : messageTextLinkHoverColor);
2972 //lclr = getColor("msg-text-link", (lastMouseLeft ? "pressed" : "hover"));
2974 gxDrawTextUtfOpt(GxDrawTextOptions.TabColorFirstFull(4, lclr, wl.nofirst), gxClipRect.x0+guiMessageTextLPad+wl.x, y, wl.text);
2978 if (gxClipRect.y1-y < gxTextHeightUtf && emlines.length-idx > 0) drawDownMark = true;
2980 ++idx;
2981 y += gxTextHeightUtf+guiMessageTextInterline;
2984 //gxDrawTextOutScaledUtf(1, gxClipRect.x1-gxTextWidthUtf(triangleDownStr)-3, sty, triangleDownStr, (drawUpMark ? gxRGB!(255, 255, 255) : gxRGB!(85, 85, 85)), gxRGB!(0, 69, 69));
2985 //gxDrawTextOutScaledUtf(1, gxClipRect.x1-gxTextWidthUtf(triangleUpStr)-3, gxClipRect.y1-7, triangleUpStr, (drawDownMark ? gxRGB!(255, 255, 255) : gxRGB!(85, 85, 85)), gxRGB!(0, 69, 69));
2987 gxDrawScrollBar(GxRect(gxClipRect.x1-10, sty+10, 5, gxClipRect.y1-sty-17), cast(int)emlines.length-1, idx-1);
2989 bool twited = false;
2990 DynStr twittext = chiroGetMessageTwit(lastDecodedTid, uid, out twited);
2991 if (twited) {
2992 immutable uint clr = getColor("twit-shade");
2994 foreach (immutable dy; gxClipRect.y0+3*gxTextHeightUtf+2..gxClipRect.y1+1) {
2995 foreach (immutable dx; gxClipRect.x0..gxClipRect.x1+1) {
2996 if ((dx^dy)&1) gxPutPixel(dx, dy, clr);
3000 GxRect rc = gxClipRect;
3001 rc.y0 = rc.y0+3*gxTextHeightUtf+2;
3002 gxDashRect(rc, clr);
3004 if (twittext.length) {
3005 immutable ofdz = egraFontSize;
3006 scope(exit) egraFontSize = ofdz;
3007 egraFontSize = 150;
3008 int tx = gxClipRect.x0+(gxClipRect.width-gxTextWidthUtf(twittext))/2-1;
3009 int ty = gxClipRect.y0+(gxClipRect.height-gxTextHeightUtf)/2-1;
3010 gxDrawTextOutUtf(tx, ty, twittext, getColor("twit-text"), getColor("twit-outline"));
3015 // ////////////////////////////////////////////////////////////////// //
3016 void drawThreadList () {
3017 uint tid = 0;
3018 if (folderCurrIndex >= 0 && folderCurrIndex < folderList.length) tid = folderList[folderCurrIndex].tagid;
3019 switchToFolderTid(tid);
3021 // find indicies
3022 int topidx, curridx;
3023 getAndFixThreadListIndicies(out topidx, out curridx);
3025 int hgt = (guiThreadListHeight+gxTextHeightUtf-1)/gxTextHeightUtf;
3026 if (hgt < 1) hgt = 1;
3028 gxClipRect.x0 = guiGroupListWidth+2;
3029 gxClipRect.x1 = screenWidth-1-5;
3030 gxClipRect.y0 = 0;
3031 gxClipRect.y1 = guiThreadListHeight-1;
3032 immutable uint origX0 = gxClipRect.x0;
3033 immutable uint origX1 = gxClipRect.x1;
3034 immutable uint origY0 = gxClipRect.y0;
3035 immutable uint origY1 = gxClipRect.y1;
3036 int y = 0;
3038 static uint darkenBy (in uint clr, in int val) pure nothrow @safe @nogc {
3039 pragma(inline, true);
3040 return
3041 val ?
3042 (clr&0xff_00_00_00)|
3043 (cast(uint)clampToByte(cast(int)(cast(ubyte)(clr>>16))-val)<<16)|
3044 (cast(uint)clampToByte(cast(int)(cast(ubyte)(clr>>8))-val)<<8)|
3045 (cast(uint)clampToByte(cast(int)(cast(ubyte)clr)-val)) :
3046 clr;
3049 chiroGetPaneTablePage(topidx, hgt,
3050 delegate (int pgofs, /* offset from the page start, from zero and up to `limit` */
3051 int iid, /* item id, never zero */
3052 uint uid, /* msguid, never zero */
3053 uint parentuid, /* parent msguid, may be zero */
3054 uint level, /* threading level, from zero */
3055 Appearance appearance, /* see above */
3056 Mute mute, /* see above */
3057 SQ3Text date, /* string representation of receiving date and time */
3058 SQ3Text subj, /* message subject, can be empty string */
3059 SQ3Text fromName, /* message sender name, can be empty string */
3060 SQ3Text fromMail, /* message sender email, can be empty string */
3061 SQ3Text title) /* title from twiting */
3063 import std.format : format;
3064 import std.datetime;
3066 if (y >= guiThreadListHeight) return;
3067 if (subj.length == 0) subj = "no subject";
3069 gxClipRect.x0 = origX0;
3070 gxClipRect.x1 = origX1;
3072 int darken = (level != 0 && appearance != Appearance.Unread ? 40 : 0);
3074 string style = "normal";
3075 if (appearance == Appearance.Unread) {
3076 style = "unread";
3077 darken = 0;
3078 } else {
3079 if (mute > Mute.Normal) { style = "twit"; darken = 0; }
3081 if (isSoftDeleted(appearance)) {
3082 darken = 0;
3083 style = (appearance == Appearance.SoftDeletePurge ? "hard-del" : "soft-del");
3086 char[64] stfull = void;
3087 usize stpos = 0;
3088 if (uid == msglistCurrUId) {
3089 static immutable string sc = "cursor-";
3090 stpos = sc.length;
3091 stfull[0..stpos] = sc;
3093 stfull[stpos..stpos+style.length] = style;
3094 const(char)[] stname = stfull[0..stpos+style.length];
3096 char[128] stx = void;
3097 const(char)[] buildStyle (const(char)[] stt) {
3098 static immutable string sc = "threadlist-";
3099 stx[0..sc.length] = sc;
3100 usize xpos = sc.length;
3101 stx[xpos..xpos+stname.length] = stname;
3102 xpos += stname.length;
3103 stx[xpos++] = '-';
3104 stx[xpos..xpos+stt.length] = stt;
3105 xpos += stt.length;
3106 return stx[0..xpos];
3109 //conwriteln("STNAME: <", stname, ">; darken=", darken);
3111 immutable uint clrBack = getColor(buildStyle("back"));
3112 immutable uint clrOut = getColor(buildStyle("outline"));
3113 immutable uint clrFrom = darkenBy(getColor(buildStyle("from-text")), darken);
3114 immutable uint clrMail = darkenBy(getColor(buildStyle("mail-text")), darken);
3115 immutable uint clrSubj = darkenBy(getColor(buildStyle("subj-text")), darken);
3116 immutable uint clrTime = darkenBy(getColor(buildStyle("time-text")), darken);
3118 // background
3119 if (!gxIsTransparent(clrBack)) gxFillRect(gxClipRect.x0, y, gxClipRect.width-1, gxTextHeightUtf, clrBack);
3120 gxClipRect.x0 = gxClipRect.x0+1;
3121 gxClipRect.x1 = gxClipRect.x1-1;
3123 // time
3124 int timewdt = gxDrawTextOutUtf(gxClipRect.x1-gxTextWidthUtf(date), y, date, clrTime, clrOut);
3125 if (timewdt%8) timewdt = (timewdt|7)+1;
3127 SQ3Text from = fromName;
3129 auto vp = from.indexOf(" via Digitalmars-");
3130 if (vp > 0) {
3131 from = from[0..vp].xstrip;
3132 if (from.length == 0) from = "anonymous";
3136 // from/mail
3137 gxClipRect.x1 = gxClipRect.x1-/*(13*6+4)*2+33*/timewdt;
3138 enum FromWidth = 22*6*2+88;
3139 gxDrawTextOutUtf(gxClipRect.x1-FromWidth, y, from, clrFrom, clrOut);
3140 gxDrawTextOutUtf(gxClipRect.x1-FromWidth+gxTextWidthUtf(from)+4, y, "<", clrMail, clrOut);
3141 gxDrawTextOutUtf(gxClipRect.x1-FromWidth+gxTextWidthUtf(from)+4+gxTextWidthUtf("<")+1, y, fromMail, clrMail, clrOut);
3142 gxDrawTextOutUtf(gxClipRect.x1-FromWidth+gxTextWidthUtf(from)+4+gxTextWidthUtf("<")+1+gxTextWidthUtf(fromMail)+1, y, ">", clrMail, clrOut);
3143 gxClipRect.x1 = gxClipRect.x1-FromWidth-6;
3145 // subj
3146 gxDrawTextOutUtf(gxClipRect.x0+level*3, y, subj, clrSubj, clrOut);
3148 // nesting dots
3149 if (level) {
3150 immutable uint clrDot = getColor(buildStyle("dots"));
3151 foreach (immutable dx; 0..level) gxPutPixel(gxClipRect.x0+1+dx*3, y+gxTextHeightUtf/2, clrDot);
3154 // deleted strike line
3155 if (isSoftDeleted(appearance)) {
3156 immutable uint clrLine = getColor(buildStyle("strike-line"));
3157 if (!gxIsTransparent(clrLine)) {
3158 gxClipRect.x0 = origX0;
3159 gxClipRect.x1 = origX1;
3160 gxHLine(gxClipRect.x0, y+gxTextHeightUtf/2, gxClipRect.x1-gxClipRect.x0+1, clrLine);
3161 if (appearance == Appearance.SoftDeletePurge) {
3162 gxHLine(gxClipRect.x0, y+gxTextHeightUtf/2+1, gxClipRect.x1-gxClipRect.x0+1, clrLine);
3167 y += gxTextHeightUtf;
3171 // draw progressbar
3172 if (msglistCurrUId) {
3173 gxClipRect.x0 = origX0;
3174 gxClipRect.x1 = origX1+5;
3175 gxClipRect.y0 = origY0;
3176 gxClipRect.y1 = origY1;
3177 gxDrawScrollBar(GxRect(gxClipRect.x1-5, gxClipRect.y0, 4, gxClipRect.height-1),
3178 cast(int)chiroGetTreePaneTableCount()-1, curridx);
3181 drawArticle(msglistCurrUId);
3184 // ////////////////////////////////////////////////////////////////// //
3185 void drawFolders () {
3186 immutable uint clrNormal = getColor("grouplist-normal-text");
3187 immutable uint clrNormalCursor = getColor("grouplist-cursor-normal-text");
3188 immutable uint clrNormalChild = getColor("grouplist-normal-child-text");
3189 immutable uint clrNormalChildCursor = getColor("grouplist-cursor-normal-child-text");
3190 immutable uint clrDots = getColor("grouplist-dots");
3191 immutable uint clrNormOutline = getColor("grouplist-outline");
3192 immutable uint clrCurOutline = getColor("grouplist-cursor-outline");
3194 folderMakeCurVisible();
3195 int ofsx = 2;
3196 int ofsy = 1;
3197 foreach (immutable idx, const FolderInfo fi; folderList) {
3198 if (idx < folderTopIndex) continue;
3199 if (ofsy >= screenHeight) break;
3200 gxClipReset();
3202 immutable int depth = fi.depth;
3203 uint clr = (depth ? clrNormalChild : clrNormal);
3204 uint clrOut = clrNormOutline;
3206 immutable bool isCursor = (idx == folderCurrIndex);
3207 if (isCursor) {
3208 gxFillRect(0, ofsy-1, guiGroupListWidth, (gxTextHeightUtf+2), getColor("grouplist-cursor-back"));
3209 clr = (depth ? clrNormalChildCursor : clrNormalCursor);
3210 clrOut = clrCurOutline;
3212 gxClipRect.x0 = ofsx-1;
3213 gxClipRect.y0 = ofsy;
3214 gxClipRect.x1 = guiGroupListWidth-3;
3216 if (fi.unreadCount) {
3217 clr = getColor(isCursor ? "grouplist-cursor-unread-text" : "grouplist-unread-text");
3218 } else if (depth == 0) {
3219 if (fi.name == "#spam") clr = getColor(isCursor ? "grouplist-cursor-spam-text" : "grouplist-spam-text");
3220 else if (fi.name == "/accounts") clr = getColor(isCursor ? "grouplist-cursor-accounts-text" : "grouplist-accounts-text");
3221 } else if (depth == 1 && fi.name.startsWith("/accounts/")) {
3222 clr = getColor(isCursor ? "grouplist-cursor-accounts-child-text" : "grouplist-accounts-child-text");
3223 } else if (fi.name.startsWith("/accounts/") && fi.name.endsWith("/inbox")) {
3224 clr = getColor(isCursor ? "grouplist-cursor-inbox-text" : "grouplist-inbox-text");
3226 foreach (immutable dd; 0..depth) gxPutPixel(ofsx+dd*6+2, ofsy+gxTextHeightUtf/2, clrDots);
3227 gxDrawTextOutUtf(ofsx+depth*6, ofsy, fi.visname, clr, clrOut);
3228 ofsy += gxTextHeightUtf+2;
3232 drawFolders();
3233 drawThreadList();
3234 //setupTrayAnimation();
3236 version(test_round_rect) {
3237 gxClipReset();
3238 gxFillRoundedRect(lastMouseX-16, lastMouseY-16, 128, 96, rrad, /*gxSolidWhite*/gxRGBA!(0, 255, 0, 127));
3239 //gxDrawRoundedRect(lastMouseX-16, lastMouseY-16, 128, 96, rrad, gxRGBA!(0, 255, 0, 127));
3243 version(test_round_rect) {
3244 int rrad = 16;
3247 override bool onKeySink (KeyEvent event) {
3248 if (event.pressed) {
3249 version(test_round_rect) {
3250 if (event == "Plus") { ++rrad; postScreenRebuild(); return true; }
3251 if (event == "Minus") { --rrad; postScreenRebuild(); return true; }
3253 if (dbg_dump_keynames) conwriteln("key: ", event.toStr, ": ", event.modifierState&ModifierState.windows);
3254 //foreach (const ref kv; mainAppKeyBindings.byKeyValue) if (event == kv.key) concmd(kv.value);
3255 char[64] kname;
3256 if (auto cmdp = event.toStrBuf(kname[]) in mainAppKeyBindings) {
3257 concmd(*cmdp);
3258 return true;
3260 // debug
3262 if (event == "S-Up") {
3263 if (folderTop > 0) --folderTop;
3264 postScreenRebuild();
3265 return true;
3267 if (event == "S-Down") {
3268 if (folderTop+1 < folders.length) ++folderTop;
3269 postScreenRebuild();
3270 return true;
3273 //if (event == "Tab") { new PostWindow(); return true; }
3274 //if (event == "Tab") { new SelectPopBoxWindow(null); return true; }
3276 return super.onKeySink(event);
3279 // returning `false` to avoid screen rebuilding by dispatcher
3280 override bool onMouseSink (MouseEvent event) {
3281 int mx = event.x;
3282 int my = event.y;
3283 // button press
3284 if (event.type == MouseEventType.buttonPressed && event.button == MouseButton.left) {
3285 // select folder
3286 if (mx >= 0 && mx < guiGroupListWidth && my >= 0 && my < screenHeight) {
3287 uint fnum = my/(gxTextHeightUtf+2)+folderTopIndex;
3288 if (fnum >= 0 && fnum != folderCurrIndex && folderCurrIndex < folderList.length) {
3289 folderCurrIndex = fnum;
3290 postScreenRebuild();
3292 return false;
3294 // select post
3295 if (mx > guiGroupListWidth && mx < screenWidth && my >= 0 && my < guiThreadListHeight) {
3296 if (lastDecodedTid != 0) {
3297 my /= gxTextHeightUtf;
3298 // find indicies
3299 int topidx, curridx;
3300 getAndFixThreadListIndicies(out topidx, out curridx);
3301 int newidx = topidx+my;
3302 if (curridx != newidx) {
3303 uint newuid = chiroGetTreePaneTableIndex2Uid(newidx);
3304 if (newuid && newuid != msglistCurrUId) {
3305 chiroSetMessageRead(lastDecodedTid, newuid);
3306 msglistCurrUId = newuid;
3307 setupTrayAnimation();
3308 postScreenRebuild();
3311 return false;
3313 } else {
3314 auto uidx = findUrlIndexAt(mx, my);
3315 if (uidx != lastUrlIndex || lastUrlIndex >= 0) { lastUrlIndex = uidx; postScreenRebuild(); }
3318 // wheel
3319 if (event.type == MouseEventType.buttonPressed && (event.button == MouseButton.wheelUp || event.button == MouseButton.wheelDown)) {
3320 // folder
3321 if (mx >= 0 && mx < guiGroupListWidth && my >= 0 && my < screenHeight) {
3322 if (event.button == MouseButton.wheelUp) {
3323 if (folderCurrIndex > 0) {
3324 --folderCurrIndex;
3325 postScreenRebuild();
3327 } else {
3328 if (folderCurrIndex+1 < folderList.length) {
3329 ++folderCurrIndex;
3330 postScreenRebuild();
3333 return false;
3335 // post
3336 if (mx > guiGroupListWidth && mx < screenWidth && my >= 0 && my < guiThreadListHeight) {
3337 if (event.button == MouseButton.wheelUp) {
3338 if (threadListUp()) postScreenRebuild();
3339 } else {
3340 if (threadListDown()) postScreenRebuild();
3342 return false;
3344 // text
3345 if (mx > guiGroupListWidth && mx < screenWidth && my > guiThreadListHeight && my < screenHeight) {
3346 enum ScrollLines = 2;
3347 if (event.button == MouseButton.wheelUp) scrollBy(-ScrollLines); else scrollBy(ScrollLines);
3348 postScreenRebuild();
3349 return false;
3352 // button release
3353 if (event.type == MouseEventType.buttonReleased && event.button == MouseButton.left) {
3354 // try url
3355 auto uidx = findUrlIndexAt(mx, my);
3356 auto url = findUrlAt(mx, my);
3357 if (url !is null) {
3358 if (url.isAttach) {
3359 if (event.modifierState&(ModifierState.alt|ModifierState.shift|ModifierState.ctrl)) {
3360 concmdf!"attach_save %s"(url.attachnum);
3361 } else {
3362 concmdf!"attach_view %s"(url.attachnum);
3364 } else {
3365 if (event.modifierState&(ModifierState.shift|ModifierState.ctrl)) {
3366 //conwriteln("link-to-clipboard: <", url.url, ">");
3367 setClipboardText(vbwin, url.url.getData.idup); // it is safe to cast here
3368 setPrimarySelection(vbwin, url.url.getData.idup); // it is safe to cast here
3369 conwriteln("url copied to the clipboard.");
3370 } else {
3371 //conwriteln("link-open: <", url.url, ">");
3372 concmdf!"open_url \"%s\" %s"(url.url, ((event.modifierState&ModifierState.alt) != 0));
3375 postScreenRebuild();
3376 } else {
3377 if (lastUrlIndex >= 0) postScreenRebuild();
3379 lastUrlIndex = uidx;
3381 if (event.type == MouseEventType.motion) {
3382 auto uidx = findUrlIndexAt(mx, my);
3383 if (uidx != lastUrlIndex) { lastUrlIndex = uidx; postScreenRebuild(); return false; }
3387 if (event.type == MouseEventType.buttonPressed || event.type == MouseEventType.buttonReleased) {
3388 postScreenRebuild();
3389 } else {
3390 // for OpenGL, this rebuilds the whole screen anyway
3391 postScreenRepaint();
3395 return false;
3400 // ////////////////////////////////////////////////////////////////////////// //
3401 __gshared LockFile mainLockFile;
3404 void checkMainLockFile () {
3405 import std.path : buildPath;
3406 mainLockFile = LockFile(buildPath(mailRootDir, ".chiroptera2.lock"));
3407 if (!mainLockFile.tryLock) {
3408 mainLockFile.close();
3409 //assert(0, "already running");
3410 conwriteln("another copy of Chiroptera is running, disabling updater.");
3411 receiverDisable();
3416 void main (string[] args) {
3418 import etc.linux.memoryerror;
3419 bool setMH = true;
3420 int idx = 1;
3421 while (idx < args.length) {
3422 string a = args[idx++];
3423 if (a == "--") break;
3424 if (a == "--gdb") {
3425 setMH = false;
3426 --idx;
3427 foreach (immutable c; idx+1..args.length) args[c-1] = args[c];
3430 if (setMH) registerMemoryErrorHandler();
3433 defaultColorStyle.parseStyle(ChiroStyle);
3435 glconAllowOpenGLRender = false;
3437 checkMainLockFile();
3438 scope(exit) mainLockFile.close();
3440 sdpyWindowClass = "Chiroptera";
3441 //glconShowKey = "M-Grave";
3443 initConsole();
3444 //FIXME
3445 //hitwitInitConsole();
3447 clearBindings();
3448 setupDefaultBindings();
3450 concmd("exec chiroptera.rc tan");
3451 concmd("load_style userstyle.rc");
3453 //FIXME
3454 //scanFolders();
3456 //FIXME:concmdf!"exec %s/accounts.rc tan"(mailRootDir);
3457 //FIXME:concmdf!"exec %s/addressbook.rc tan"(mailRootDir);
3458 //FIXME:concmdf!"exec %s/filters.rc tan"(mailRootDir);
3459 //FIXME:concmdf!"exec %s/highlights.rc tan"(mailRootDir);
3460 //FIXME:concmdf!"exec %s/twits.rc tan"(mailRootDir);
3461 //FIXME:concmdf!"exec %s/twit_threads.rc tan"(mailRootDir);
3462 //FIXME:concmdf!"exec %s/auto_twits.rc tan"(mailRootDir);
3463 //FIXME:concmdf!"exec %s/auto_twit_threads.rc tan"(mailRootDir);
3464 //FIXME:concmdf!"exec %s/repreps.rc tan"(mailRootDir);
3465 conProcessQueue(); // load config
3466 conProcessArgs!true(args);
3468 chiroOpenStorageDB();
3469 chiroOpenViewDB();
3470 chiroOpenConfDB();
3471 //ChiroTimerEnabled = true;
3472 //ChiroTimerExEnabled = true;
3474 rescanFolders();
3476 egraCreateSystemWindow("Chiroptera", allowResize:true);
3478 static if (is(typeof(&vbwin.closeQuery))) {
3479 vbwin.closeQuery = delegate () { concmd("quit"); egraPostDoConCommands(); };
3483 vbwin.windowResized = delegate (int wdt, int hgt) {
3484 egraSdpyOnWindowResized(wdt, hgt);
3486 // TODO: fix gui sizes
3487 if (vbwin.closed) return;
3489 double glwFrac = cast(double)guiGroupListWidth/screenWidth;
3490 double tlhFrac = cast(double)guiThreadListHeight/screenHeight;
3492 if (wdt < screenEffScale*32) wdt = screenEffScale;
3493 if (hgt < screenEffScale*32) hgt = screenEffScale;
3494 int newwdt = (wdt+screenEffScale-1)/screenEffScale;
3495 int newhgt = (hgt+screenEffScale-1)/screenEffScale;
3497 guiGroupListWidth = cast(int)(glwFrac*newwdt+0.5);
3498 guiThreadListHeight = cast(int)(tlhFrac*newhgt+0.5);
3500 if (guiGroupListWidth < 12) guiGroupListWidth = 12;
3501 if (guiThreadListHeight < 16) guiThreadListHeight = 16;
3505 vbwin.addEventListener((QuitEvent evt) {
3506 if (vbwin.closed) return;
3507 if (isQuitRequested) { vbwin.close(); return; }
3508 vbwin.close();
3512 vbwin.addEventListener((TrayAnimationStepEvent evt) {
3513 if (vbwin.closed) return;
3514 if (isQuitRequested) { vbwin.close(); return; }
3515 trayDoAnimationStep();
3519 HintWindow uphintWindow;
3521 vbwin.addEventListener((UpdatingAccountEvent evt) {
3522 DynStr accName = chiroGetAccountName(evt.accid);
3523 if (accName.length) {
3524 DynStr msg = "updating: ";
3525 msg ~= accName;
3526 if (uphintWindow !is null) {
3527 uphintWindow.message = msg;
3528 } else {
3529 uphintWindow = new HintWindow(msg);
3530 uphintWindow.y0 = guiThreadListHeight+1+(3*gxTextHeightUtf+2-uphintWindow.height)/2;
3532 postScreenRebuild();
3536 vbwin.addEventListener((UpdatingAccountCompleteEvent evt) {
3537 if (uphintWindow is null) return;
3538 DynStr accName = chiroGetAccountName(evt.accid);
3539 if (accName.length) {
3540 DynStr msg = "done: ";
3541 msg ~= accName;
3542 uphintWindow.message = msg;
3543 postScreenRebuild();
3547 vbwin.addEventListener((UpdatingCompleteEvent evt) {
3548 if (uphintWindow) {
3549 uphintWindow.close();
3550 uphintWindow = null;
3552 if (vbwin is null || vbwin.closed) return;
3553 setupTrayAnimation(); // check if we have to start/stop animation, and do it
3554 postScreenRebuild();
3557 vbwin.addEventListener((TagThreadsUpdatedEvent evt) {
3558 if (vbwin is null || vbwin.closed) return;
3559 if (mainPane is null) return;
3560 if (evt.tagid && mainPane.lastDecodedTid == evt.tagid) {
3561 // force view pane rebuild
3562 mainPane.switchToFolderTid(evt.tagid, forced:true);
3563 postScreenRebuild();
3568 ProgressWindow recalcHintWindow;
3570 vbwin.addEventListener((RecalcAllTwitsEvent evt) {
3571 if (vbwin !is null && !vbwin.closed) {
3572 glconHide();
3573 if (recalcHintWindow !is null) recalcHintWindow.close();
3574 recalcHintWindow = new ProgressWindow("recalculating twits");
3575 egraRebuildScreen();
3576 } else {
3577 recalcHintWindow = null;
3580 disableMailboxUpdates();
3581 scope(exit) enableMailboxUpdates();
3582 chiroRecalcAllTwits((msg, curr, total) {
3583 if (recalcHintWindow is null) return;
3584 if (recalcHintWindow.setProgress(msg, curr, total)) {
3585 egraRebuildScreen();
3589 if (vbwin !is null && !vbwin.closed) {
3590 if (recalcHintWindow !is null) recalcHintWindow.close();
3591 if (mainPane !is null) mainPane.switchToFolderTid(mainPane.lastDecodedTid, forced:true);
3592 postScreenRebuild();
3596 vbwin.addEventListener((ArticleTextScrollEvent evt) {
3597 if (vbwin is null || vbwin.closed) return;
3598 if (mainPane is null) return;
3599 mainPane.doScrollStep();
3602 vbwin.addEventListener((MarkAsUnreadEvent evt) {
3603 if (vbwin is null || vbwin.closed) return;
3604 if (mainPane is null) return;
3605 //conwriteln("unread timer fired");
3606 if (mainPane.lastDecodedTid == evt.tagid && evt.uid == mainPane.msglistCurrUId) {
3607 //conwriteln("*** unread timer hit!");
3608 chiroSetMessageRead(evt.tagid, evt.uid);
3609 setupTrayAnimation();
3610 postScreenRebuild();
3614 void firstTimeInit () {
3615 // create notification icon
3616 if (trayicon is null) {
3617 auto drv = vfsAddPak(wrapMemoryRO(iconsZipData[]), "", "databinz/icons.zip:");
3618 scope(exit) vfsRemovePak(drv);
3619 try {
3620 foreach (immutable idx; 0..6) {
3621 string fname = "databinz/icons.zip:icons";
3622 if (idx == 0) {
3623 fname ~= "/main.png";
3624 } else {
3625 import std.format : format;
3626 fname = "%s/bat%s.png".format(fname, idx-1);
3628 auto fl = VFile(fname);
3629 if (fl.size == 0 || fl.size > 1024*1024) throw new Exception("fucked icon");
3630 auto pngraw = new ubyte[](cast(uint)fl.size);
3631 fl.rawReadExact(pngraw);
3632 auto img = readPng(pngraw);
3633 if (img is null) throw new Exception("fucked icon");
3634 icons[idx] = imageFromPng(img);
3636 foreach (immutable idx, MemoryImage img; icons[]) {
3637 trayimages[idx] = Image.fromMemoryImage(img);
3639 vbwin.icon = icons[0];
3640 trayicon = new NotificationAreaIcon("Chiroptera", trayimages[0], (MouseButton button) {
3641 scope(exit) if (!conQueueEmpty()) egraPostDoConCommands();
3642 if (button == MouseButton.left) vbwin.switchToWindow();
3643 if (button == MouseButton.middle) concmd("quit");
3645 setupTrayAnimation();
3646 flushGui(); // or it may not redraw itself
3647 } catch (Exception e) {
3648 conwriteln("ERROR loading icons: ", e.msg);
3653 vbwin.visibleForTheFirstTime = delegate () {
3654 egraFirstTimeInit();
3655 firstTimeInit();
3658 mainPane = new MainPaneWindow();
3659 egraSkipScreenClear = true; // main pane is fullscreen
3661 postScreenRebuild();
3662 repostHideMouse();
3664 receiverInit();
3666 MonoTime lastCollect = MonoTime.currTime;
3667 vbwin.eventLoop(1000*10,
3668 delegate () {
3669 egraProcessConsole();
3670 if (mainPane !is null) {
3671 if (mainPane.isViewChanged) postScreenRebuild();
3672 mainPane.checkSaveState();
3673 setupTrayAnimation();
3676 immutable ctt = MonoTime.currTime;
3677 if ((ctt-lastCollect).total!"minutes" >= 1) {
3678 import core.memory : GC;
3679 lastCollect = ctt;
3680 GC.collect();
3681 GC.minimize();
3685 delegate (KeyEvent event) {
3686 egraOnKey(event);
3687 if (mainPane !is null && mainPane.isViewChanged) postScreenRebuild();
3689 delegate (MouseEvent event) {
3690 egraOnMouse(event);
3691 if (mainPane !is null && mainPane.isViewChanged) postScreenRebuild();
3693 delegate (dchar ch) {
3694 egraOnChar(ch);
3695 if (mainPane !is null && mainPane.isViewChanged) postScreenRebuild();
3699 mainPane.saveCurrentState();
3701 trayimages[] = null;
3702 if (trayicon !is null && !trayicon.closed) { trayicon.close(); trayicon = null; }
3703 flushGui();
3704 receiverDeinit();
3705 conProcessQueue(int.max/4);