]> mj.ucw.cz Git - checkmail.git/blob - cm.c
49d0f6508e40b50ac7f0dfb51de2789fcb04b7e5
[checkmail.git] / cm.c
1 /*
2  *      Incoming Mail Checker
3  *
4  *      (c) 2005--2010 Martin Mares <mj@ucw.cz>
5  */
6
7 #define _GNU_SOURCE
8
9 #include <stdio.h>
10 #include <string.h>
11 #include <stdlib.h>
12 #include <ctype.h>
13 #include <getopt.h>
14 #include <fcntl.h>
15 #include <glob.h>
16 #include <fnmatch.h>
17 #include <sys/stat.h>
18 #include <unistd.h>
19 #include <pwd.h>
20 #include <time.h>
21 #include <sys/types.h>
22 #include <sys/wait.h>
23
24 #ifdef CONFIG_WIDE_CURSES
25 #include <ncursesw/ncurses.h>
26 #else
27 #include <curses.h>
28 #endif
29
30 #include "util.h"
31 #include "clists.h"
32 #include "charset.h"
33
34 static int check_interval = 30;
35 static int force_refresh;
36 static int allow_bells = 1;
37 static int allow_osd = 1;
38 static int minimum_priority;
39 static time_t last_scan_time;
40 static char *run_cmd = "mutt -f %s";
41
42 struct options {
43   int priority;
44   int hide;
45   int hide_if_empty;
46   int highlight;
47   int beep;
48   int snippets;
49   int show_flagged;
50   int sender_personal;
51   int sender_mbox;
52   int hotkey;
53   int led;
54   int osd;
55 };
56
57 struct option_node {
58   cnode n;
59   struct options o;
60   char pattern[1];
61 };
62
63 struct pattern_node {
64   cnode n;
65   char *name;
66   char pattern[1];
67 };
68
69 static clist options, patterns;
70 static struct options global_options = {
71   .sender_personal = 1
72 };
73
74 struct mbox {
75   cnode n;
76   struct options o;
77   char *name;
78   char *path;
79   int index;
80   int scanning;
81   int seen;
82   time_t last_time;
83   time_t display_valid_until;
84   int last_size, last_pos;
85   int total, new, flagged;
86   int last_total, last_new, last_flagged;
87   int last_beep_new;
88   int force_refresh;
89   int snippet_is_new;
90   char sender_snippet[128];
91   char subject_snippet[128];
92 };
93
94 static clist mboxes;
95 static struct mbox **mbox_array;
96 static int num_mboxes, mbox_array_size;
97
98 struct osd_opt_node {
99   cnode n;
100   char *val;
101   char key[1];
102 };
103
104 static clist osd_opts;
105
106 static void redraw_line(int i);
107 static void rethink_display(int notify);
108
109 static void
110 add_pattern(char *patt)
111 {
112   struct pattern_node *n = xmalloc(sizeof(*n) + strlen(patt));
113   strcpy(n->pattern, patt);
114   if (patt = strchr(n->pattern, '='))
115     {
116       *patt++ = 0;
117       n->name = patt;
118     }
119   else
120     n->name = NULL;
121   clist_add_tail(&patterns, &n->n);
122 }
123
124 static void
125 add_inbox(void)
126 {
127   struct passwd *p = getpwuid(getuid());
128   if (!p)
129     die("You don't exist, go away!");
130   char buf[sizeof("/var/mail/") + strlen(p->pw_name) + 7];
131   sprintf(buf, "/var/mail/%s=INBOX", p->pw_name);
132   add_pattern(buf);
133 }
134
135 static void
136 init_options(struct options *o)
137 {
138   o->priority = -1;
139   o->hide = -1;
140   o->hide_if_empty = -1;
141   o->beep = -1;
142   o->highlight = -1;
143   o->snippets = -1;
144   o->show_flagged = -1;
145   o->sender_personal = -1;
146   o->sender_mbox = -1;
147   o->hotkey = -1;
148   o->led = -1;
149   o->osd = -1;
150 }
151
152 static void
153 setup_options(struct mbox *b)
154 {
155   b->o = global_options;
156   CLIST_FOR_EACH(struct option_node *, n, options)
157     if (!fnmatch(n->pattern, b->name, 0))
158       {
159         debug("\tApplied options %s\n", n->pattern);
160 #define MERGE(f) if (n->o.f >= 0) b->o.f = n->o.f
161         MERGE(priority);
162         MERGE(hide);
163         MERGE(hide_if_empty);
164         MERGE(highlight);
165         MERGE(beep);
166         MERGE(snippets);
167         MERGE(show_flagged);
168         MERGE(sender_personal);
169         MERGE(sender_mbox);
170         MERGE(hotkey);
171         MERGE(led);
172         MERGE(osd);
173       }
174 }
175
176 static void
177 add_osd_opt(char *arg)
178 {
179   struct osd_opt_node *n = xmalloc(sizeof(*n) + strlen(arg));
180   strcpy(n->key, arg);
181   n->val = strchr(n->key, '=');
182   if (!n->val)
183     die("Malformed OSD option");
184   *n->val++ = 0;
185   clist_add_tail(&osd_opts, &n->n);
186 }
187
188 static char *
189 mbox_name(char *path)
190 {
191   char *c = strrchr(path, '/');
192   return c ? (c+1) : path;
193 }
194
195 static struct mbox *
196 add_mbox(clist *l, char *path, char *name)
197 {
198   struct mbox *b = xmalloc(sizeof(*b));
199   bzero(b, sizeof(*b));
200   b->path = xstrdup(path);
201   b->name = xstrdup(name);
202
203   if (name)
204     {
205       cnode *prev = l->head.prev;
206       while (prev != &l->head && strcmp(((struct mbox *)prev)->name, name) > 0)
207         prev = prev->prev;
208       clist_insert_after(&b->n, prev);
209     }
210   else
211     clist_add_tail(l, &b->n);
212
213   return b;
214 }
215
216 static void
217 del_mbox(struct mbox *b)
218 {
219   clist_remove(&b->n);
220   free(b->path);
221   free(b->name);
222   free(b);
223 }
224
225 static struct mbox *
226 find_mbox(clist *l, char *path)
227 {
228   CLIST_FOR_EACH(struct mbox *, b, *l)
229     if (!strcmp(b->path, path))
230       return b;
231   return NULL;
232 }
233
234 static inline int
235 mbox_active_p(struct mbox *b)
236 {
237   if (b->o.priority < minimum_priority)
238     return 0;
239   if (b->o.hide)
240     return 0;
241   return 1;
242 }
243
244 static inline int
245 mbox_visible_p(struct mbox *b)
246 {
247   if (!mbox_active_p(b))
248     return 0;
249   if (b->scanning < 0)
250     return 1;
251   if (b->o.hide_if_empty && !b->total)
252     return 0;
253   return 1;
254 }
255
256 static void
257 prepare_snippets(struct mbox *b, char *sender, char *subject)
258 {
259   char *pos, *term;
260
261   while (*sender == ' ' || *sender == '\t')
262     sender++;
263   while (*subject == ' ' || *subject == '\t')
264     subject++;
265
266   pos = b->sender_snippet;
267   term = pos + sizeof(b->sender_snippet) - 1;
268   if (sender[0] && (b->o.sender_mbox || b->o.sender_personal))
269     add_addr_snippet(&pos, term, sender, b->o.sender_mbox, b->o.sender_personal);
270   else
271     *pos = 0;
272
273   pos = b->subject_snippet;
274   term = pos + sizeof(b->subject_snippet) - 1;
275   if (subject[0])
276     add_subject_snippet(&pos, term, subject);
277   else
278     add_snippet_raw(&pos, term, "No subject");
279 }
280
281 static void
282 build_snippet(char *buf, char *term, struct mbox *b)
283 {
284   if (b->sender_snippet[0])
285     {
286       add_snippet(&buf, term, b->sender_snippet);
287       add_snippet_raw(&buf, term, ": ");
288     }
289   add_snippet(&buf, term, b->subject_snippet);
290 }
291
292 static int mb_fd, mb_pos;
293 static unsigned char mb_buf[4096], *mb_cc, *mb_end;
294
295 static void
296 mb_reset(int pos)
297 {
298   mb_cc = mb_end = mb_buf;
299   mb_pos = pos;
300 }
301
302 static void
303 mb_seek(uns pos)
304 {
305   lseek(mb_fd, pos, SEEK_SET);
306   mb_reset(pos);
307 }
308
309 static int
310 mb_tell(void)
311 {
312   return mb_pos - (mb_end - mb_cc);
313 }
314
315 static int
316 mb_ll_get(void)
317 {
318   int len = read(mb_fd, mb_buf, sizeof(mb_buf));
319   mb_cc = mb_buf;
320   if (len <= 0)
321     {
322       mb_end = mb_buf;
323       return -1;
324     }
325   else
326     {
327       mb_end = mb_buf + len;
328       mb_pos += len;
329       return *mb_cc++;
330     }
331 }
332
333 static inline int
334 mb_get(void)
335 {
336   return (mb_cc < mb_end) ? *mb_cc++ : mb_ll_get();
337 }
338
339 static void
340 mb_unget(int c)
341 {
342   if (c >= 0)
343     mb_cc--;
344 }
345
346 static int
347 mb_check(const char *p, int len)
348 {
349   while (len--)
350     {
351       if (mb_get() != *p++)
352         return 0;
353     }
354   return 1;
355 }
356
357 static void
358 scan_mbox(struct mbox *b, struct stat *st)
359 {
360   char buf[1024], sender[1024], subject[1024];
361   int c;
362   int compressed = 0;
363   const char from[] = "\nFrom ";
364
365   if (!st->st_size)
366     {
367       b->total = b->new = b->flagged = 0;
368       b->last_pos = 0;
369       return;
370     }
371
372   /* FIXME: Should we do some locking? */
373
374   mb_fd = open(b->path, O_RDONLY);
375   if (mb_fd < 0)
376     {
377       debug("[open failed: %m] ");
378       b->total = b->new = b->flagged = -1;
379       return;
380     }
381
382   char signature[2];
383   c = read(mb_fd, signature, 2);
384   lseek(mb_fd, 0, SEEK_SET);
385
386   if (c == 2 && !memcmp(signature, "\037\213", 2)) //gzip
387     {
388       debug("[decompressing] ");
389       int fds[2];
390       if (pipe(fds))
391         die("pipe failed: %m");
392       int pid = fork();
393       if (pid < 0)
394         die("fork failed: %m");
395       if (!pid)
396         {
397           if (dup2(mb_fd, 0) < 0 || dup2(fds[1], 1) < 0)
398             die("dup2 failed: %m");
399           close(fds[0]);
400           close(fds[1]);
401           close(mb_fd);
402           execlp("gzip", "gzip", "-cd", NULL);
403           die("Cannot execute gzip: %m");
404         }
405       close(fds[1]);
406       close(mb_fd);
407       mb_fd = fds[0];
408       compressed = 1;
409     }
410   mb_reset(0);
411
412   int incremental = 0;
413   if (b->last_size && b->last_pos && st->st_size > b->last_size && !b->force_refresh && !compressed)
414     {
415       mb_seek(b->last_pos);
416       if (mb_check(from, 6))
417         {
418           debug("[incremental] ");
419           incremental = 1;
420         }
421       else
422         {
423           debug("[incremental failed] ");
424           mb_seek(0);
425         }
426     }
427   if (!incremental)
428     {
429       if (!mb_check(from+1, 5))
430         {
431           debug("[inconsistent] ");
432           b->total = b->new = b->flagged = -1;
433           goto done;
434         }
435       b->total = b->new = b->flagged = 0;
436       b->last_total = b->last_new = b->last_flagged = 0;
437       b->snippet_is_new = 0;
438     }
439   else
440     {
441       b->total = b->last_total;
442       b->new = b->last_new;
443       b->flagged = b->last_flagged;
444     }
445
446   for(;;)
447     {
448       b->last_pos = mb_tell() - 5;
449       if (b->last_pos)
450         b->last_pos--;          // last_pos should be the previous \n character
451       b->last_total = b->total;
452       b->last_new = b->new;
453       b->last_flagged = b->flagged;
454       while ((c = mb_get()) >= 0 && c != '\n')
455         ;
456
457       int new = 1;
458       int flagged = 0;
459       sender[0] = 0;
460       subject[0] = 0;
461       for (;;)
462         {
463           uns i = 0;
464           for (;;)
465             {
466               c = mb_get();
467               if (c < 0)
468                 {
469                   debug("[truncated] ");
470                   goto done;
471                 }
472               if (c == '\n')
473                 {
474                   int fold = -1;
475                   do
476                     {
477                       fold++;
478                       c = mb_get();
479                     }
480                   while (c == ' ' || c == '\t');
481                   mb_unget(c);
482                   if (!fold)
483                     break;
484                   c = ' ';
485                 }
486               if (c == '\r')
487                 continue;
488               if (i < sizeof(buf) - 1)
489                 buf[i++] = c;
490             }
491           buf[i] = 0;
492           if (!buf[0])
493             break;
494           if (!strncasecmp(buf, "Status:", 7))
495             new = 0;
496           else if (!strncasecmp(buf, "X-Status:", 9) && strchr(buf+9, 'F'))
497             flagged = 1;
498           else if (!strncasecmp(buf, "From:", 5))
499             strcpy(sender, buf+5);
500           else if (!strncasecmp(buf, "Subject:", 8))
501             strcpy(subject, buf+8);
502         }
503
504       b->total++;
505       if (new)
506         b->new++;
507       if (flagged)
508         b->flagged++;
509       if (debug_mode > 1)
510         debug("new=%d flagged=%d sender=<%s> subject=<%s>\n", new, flagged, sender, subject);
511       if (new || (flagged && !b->snippet_is_new))
512         {
513           b->snippet_is_new = new;
514           prepare_snippets(b, sender, subject);
515         }
516
517       int ct = 1;
518       while (from[ct])
519         {
520           c = mb_get();
521           if (c < 0)
522             goto done;
523           if (c != from[ct++])
524             ct = (c == '\n');
525         }
526     }
527
528  done:
529   close(mb_fd);
530   if (compressed)
531     {
532       int status;
533       if (wait(&status) < 0 || !WIFEXITED(status) || WEXITSTATUS(status))
534         b->total = b->new = b->flagged = -1;
535     }
536 }
537
538 static void
539 scan(int notify)
540 {
541   debug("Searching for mailboxes (notify=%d)...\n", notify);
542   last_scan_time = time(NULL);
543   CLIST_FOR_EACH(struct pattern_node *, p, patterns)
544     {
545       debug("Trying pattern %s (name %s)\n", p->pattern, p->name);
546       glob_t g;
547       int err = glob(p->pattern, GLOB_ERR | GLOB_NOSORT | GLOB_TILDE | GLOB_TILDE_CHECK, NULL, &g);
548       if (err && err != GLOB_NOMATCH)
549         die("Failed to glob %s: %m", p->pattern);
550       for (uns i=0; i<g.gl_pathc; i++)
551         {
552           char *name = g.gl_pathv[i];
553           struct mbox *b = find_mbox(&mboxes, name);
554           if (!b)
555             {
556               b = add_mbox(&mboxes, name, (p->name ? p->name : mbox_name(name)));
557               debug("Discovered mailbox %s (%s)\n", b->name, b->path);
558               setup_options(b);
559               b->scanning = -1;
560             }
561           b->seen = 1;
562         }
563       globfree(&g);
564     }
565
566   struct mbox *tmp;
567   CLIST_FOR_EACH_DELSAFE(struct mbox *, b, mboxes, tmp)
568     {
569       if (b->seen)
570         b->seen = 0;
571       else
572         {
573           debug("Lost mailbox %s\n", b->name);
574           del_mbox(b);
575         }
576     }
577
578   rethink_display(0);
579
580   debug("Scanning mailboxes...\n");
581   CLIST_FOR_EACH(struct mbox *, b, mboxes)
582     {
583       struct stat st;
584       debug("%s: ", b->name);
585       if (!mbox_active_p(b))
586         {
587           debug("inactive\n");
588           continue;
589         }
590       if (force_refresh)
591         b->force_refresh = 1;
592       if (stat(b->path, &st) < 0)
593         {
594           b->total = b->new = b->flagged = -1;
595           debug("%m\n");
596         }
597       else if (!b->last_time || st.st_mtime != b->last_time || st.st_size != b->last_size || b->force_refresh)
598         {
599           b->scanning = 1;
600           redraw_line(b->index);
601           refresh();
602
603           scan_mbox(b, &st);
604           b->last_time = st.st_mtime;
605           b->last_size = st.st_size;
606           debug("%d %d %d (stopped at %d of %d)\n", b->total, b->new, b->flagged, b->last_pos, b->last_size);
607
608           b->scanning = 0;
609           redraw_line(b->index);
610           refresh();
611         }
612       else if (b->display_valid_until <= last_scan_time)
613         {
614           debug("not changed, but needs redraw\n");
615           redraw_line(b->index);
616         }
617       else
618         debug("not changed\n");
619       b->force_refresh = 0;
620     }
621   force_refresh = 0;
622
623   debug("Scan finished\n");
624   last_scan_time = time(NULL);
625   rethink_display(notify);
626 }
627
628 #ifdef CONFIG_X11
629
630 #include <X11/Xlib.h>
631 #include <X11/Xatom.h>
632
633 static Display *x11_dpy;
634 static unsigned leds_care, leds_have, leds_want;
635
636 static Atom osd_pty;
637 static unsigned osd_care;
638 #define OSD_MSG_SIZE 1024
639 static char osd_last_msg[OSD_MSG_SIZE];
640
641 static void
642 x11_init(void)
643 {
644   leds_care = (global_options.led >= 0 ? (1 << global_options.led) : 0);
645   osd_care = (global_options.osd >= 0);
646   CLIST_FOR_EACH(struct option_node *, o, options)
647     {
648       if (o->o.led > 0)
649         leds_care |= (1 << o->o.led);
650       if (o->o.osd > 0)
651         osd_care = 1;
652     }
653
654   if (!leds_care && !osd_care)
655     {
656       debug("X11: No mailbox wants LEDs or OSD\n");
657       return;
658     }
659   if (!getenv("DISPLAY"))
660     {
661       debug("X11: Do not have X display\n");
662       return;
663     }
664   if (!(x11_dpy = XOpenDisplay(NULL)))
665     die("Cannot open X display, although the DISPLAY variable is set");
666
667   if (osd_care)
668     {
669       osd_pty = XInternAtom(x11_dpy, "OSD_QUEUE", False);
670       if (!osd_pty)
671         die("Cannot intern OSD_QUEUE atom");
672
673       // If OSD options contain no message, add one
674       int seen_msg = 0;
675       CLIST_FOR_EACH(struct osd_opt_node *, n, osd_opts)
676         if (!n->key[0])
677           seen_msg = 1;
678       if (!seen_msg)
679         {
680           add_osd_opt("=%40f");
681           add_osd_opt("=%40s");
682           add_osd_opt("=");
683           add_osd_opt("=(and %m more)");
684         }
685     }
686
687   leds_have = ~0U;
688   debug("X11: Initialized\n");
689 }
690
691 static void
692 sync_leds(void)
693 {
694   if (leds_want == leds_have)
695     return;
696
697   debug("LEDS: have %02x, want %02x, care %02x\n", leds_have, leds_want, leds_care);
698   for (int i=1; i<10; i++)
699     if (leds_care & (leds_have ^ leds_want) & (1 << i))
700       {
701         XKeyboardControl cc;
702         cc.led = i;
703         cc.led_mode = (leds_want & (1 << i)) ? LedModeOn : LedModeOff;
704         XChangeKeyboardControl(x11_dpy, KBLed | KBLedMode, &cc);
705       }
706   XFlush(x11_dpy);
707   leds_have = leds_want;
708 }
709
710 static void
711 rethink_leds(void)
712 {
713   if (!leds_care || !x11_dpy)
714     return;
715
716   leds_want = 0;
717   CLIST_FOR_EACH(struct mbox *, b, mboxes)
718     if (b->o.led > 0 && b->new)
719       leds_want |= (1 << b->o.led);
720   sync_leds();
721 }
722
723 struct osd_params {
724   struct mbox *mbox;
725   int total_new;
726 };
727
728 static int
729 format_osd_string(char *dest, char *src, struct osd_params *par)
730 {
731   char *stop = dest + OSD_MSG_SIZE - 1;
732   char numbuf[16];
733
734   while (*src && dest < stop)
735     {
736       if (*src == '%')
737         {
738           src++;
739           int size = 0;
740           while (*src >= '0' && *src <= '9')
741             size = 10*size + *src++ - '0';
742           if (!size || size > stop-dest)
743             size = dest-stop;
744
745           int spec = *src++;
746           if (!spec)
747             break;
748
749           char *arg = numbuf;
750           switch (spec)
751             {
752             case 'f':
753               arg = par->mbox->sender_snippet;
754               break;
755             case 's':
756               arg = par->mbox->subject_snippet;
757               break;
758             case 'n':
759               snprintf(numbuf, sizeof(numbuf), "%d", par->total_new);
760               break;
761             case 'm':
762               if (par->total_new < 2)
763                 return 0;
764               snprintf(numbuf, sizeof(numbuf), "%d", par->total_new - 1);
765               break;
766             case '%':
767               arg = "%";
768               break;
769             default:
770               arg = "???";
771               break;
772             }
773
774           while (*arg && size)
775             {
776               *dest++ = *arg++;
777               size--;
778             }
779         }
780       else
781         *dest++ = *src++;
782     }
783   *dest = 0;
784   return 1;
785 }
786
787 static void
788 format_osd(char *msg, struct osd_params *par)
789 {
790   if (!par->mbox)
791     {
792       msg[0] = 0;
793       return;
794     }
795
796   unsigned pos = 0;
797   unsigned have_text = 0;
798   CLIST_FOR_EACH(struct osd_opt_node *, n, osd_opts)
799     {
800       char buf[OSD_MSG_SIZE];
801       if (!format_osd_string(buf, n->val, par))
802         continue;
803       if (!n->key[0] && buf[0])
804         have_text = 1;
805       pos += snprintf(msg+pos, OSD_MSG_SIZE-pos-1, "%s:%s\n", n->key, buf);
806       if (pos > OSD_MSG_SIZE-1)
807         {
808           pos = sprintf(msg, "OSD message too long!\n");
809           break;
810         }
811     }
812   if (have_text)
813     msg[pos++] = '\n';
814   else
815     pos = 0;
816   msg[pos] = 0;
817 }
818
819 static void
820 debug_osd_msg(char *msg)
821 {
822   if (!debug_mode)
823     return;
824   fprintf(stderr, "OSD: <");
825   while (*msg)
826     {
827       fputc((*msg != '\n' ? *msg : '|'), stderr);
828       msg++;
829     }
830   fprintf(stderr, ">\n");
831 }
832
833 static void
834 rethink_osd(int notify)
835 {
836   if (!osd_care || !x11_dpy || !allow_osd)
837     {
838       osd_last_msg[0] = 0;
839       return;
840     }
841
842   struct osd_params p = { .mbox = NULL, .total_new = 0 };
843   CLIST_FOR_EACH(struct mbox *, b, mboxes)
844     if (b->o.osd > 0)
845       {
846         p.total_new += b->new;
847         if (b->new && (!p.mbox || p.mbox->o.priority < b->o.priority))
848           p.mbox = b;
849       }
850
851   char new_msg[OSD_MSG_SIZE];
852   format_osd(new_msg, &p);
853   debug_osd_msg(new_msg);
854   if (strcmp(new_msg, osd_last_msg))
855     {
856       strcpy(osd_last_msg, new_msg);
857       if (notify && new_msg[0])
858         {
859           debug("OSD: Sending to daemon\n");
860           XChangeProperty(x11_dpy, DefaultRootWindow(x11_dpy), osd_pty, XA_STRING, 8, PropModeAppend, (unsigned char *) new_msg, strlen(new_msg));
861           XFlush(x11_dpy);
862         }
863       else
864         debug("OSD: No changes\n");
865     }
866 }
867
868 static void
869 x11_cleanup(void)
870 {
871   if (!x11_dpy)
872     return;
873
874   leds_want = 0;
875   sync_leds();
876 }
877
878 #else
879
880 static void x11_init(void) { }
881 static void rethink_leds(void) { }
882 static void rethink_osd(int notify UNUSED) { }
883 static void x11_cleanup(void) { }
884
885 #endif
886
887 static int cursor_at, cursor_max;
888
889 static unsigned is_active, is_pos;      // incremental search
890 static char is_buf[64];
891
892 enum {
893   M_IDLE,
894   M_SCAN,
895   M_NEW,
896   M_FLAG,
897   M_BAD,
898   M_INCSEARCH,
899   M_MAX
900 };
901 static int attrs[3][2][M_MAX];          // active (2=incsearch), hilite, status
902
903 static void
904 redraw_line(int i)
905 {
906   move(i, 0);
907   if (i < cursor_max)
908     {
909       struct mbox *b = mbox_array[i];
910       int cc = (cursor_at == i ? (is_active ? 2 : 1) : 0);
911       int hi = b->o.highlight;
912       unsigned namepos = 0;
913       unsigned namelen = strlen(b->name);
914       int valid = 3600;
915
916       attrset(attrs[cc][hi][M_IDLE]);
917       if (b->o.hotkey)
918         printw("%c ", b->o.hotkey);
919       else if (cc)
920         printw("> ");
921       else
922         printw("  ");
923       if (cc == 2)
924         {
925           attrset(attrs[cc][hi][M_INCSEARCH]);
926           for (namepos=0; namepos < is_pos && namepos < 20; namepos++)
927             addch(is_buf[namepos]);
928         }
929       if (b->new)
930         attrset(attrs[cc][hi][M_NEW]);
931       else if (b->flagged && b->o.show_flagged)
932         attrset(attrs[cc][hi][M_FLAG]);
933       else
934         attrset(attrs[cc][hi][M_IDLE]);
935       while (namepos < namelen)
936         addch(b->name[namepos++]);
937       while (namepos++ < 20)
938         addch(' ');
939       if (b->scanning < 0)
940         ;
941       else if (b->scanning)
942         {
943           attrset(attrs[cc][hi][M_SCAN]);
944           printw("[SCANNING]");
945         }
946       else if (b->total < 0)
947         {
948           attrset(attrs[cc][hi][M_BAD]);
949           printw("BROKEN");
950         }
951       else
952         {
953           attrset(attrs[cc][hi][M_IDLE]);
954           printw("%6d ", b->total);
955           int snip = 0;
956           if (b->new)
957             {
958               attrset(attrs[cc][hi][M_NEW]);
959               printw("%6d  ", b->new);
960               attrset(attrs[cc][hi][M_IDLE]);
961               int age = (last_scan_time - b->last_time);
962               if (age < 0)
963                 age = 0;
964               if (age < 3600)
965                 {
966                   printw("%2d min  ", age/60);
967                   valid = 60;
968                 }
969               else if (age < 86400)
970                 printw("%2d hr%c  ", age/3600, (age >= 7200 ? 's' : ' '));
971               else
972                 printw("        ");
973               snip = 1;
974             }
975           else if (b->flagged && b->o.show_flagged)
976             {
977               attrset(attrs[cc][hi][M_FLAG]);
978               printw("%6d  ", b->flagged);
979               attrset(attrs[cc][hi][M_IDLE]);
980               printw("        ");
981               attrset(attrs[cc][0][M_FLAG]);    /* We avoid the highlight intentionally */
982               snip = 1;
983             }
984           if (snip && b->o.snippets)
985             {
986               int xx, yy;
987               getyx(stdscr, yy, xx);
988               int remains = COLS-1-xx;
989               (void) yy;
990
991               char snip[256];
992               build_snippet(snip, snip + sizeof(snip) - 1, b);
993
994               if (snip[0] && remains > 2)
995                 {
996 #ifdef CONFIG_WIDE_CURSES
997                   size_t len = strlen(snip)+1;
998                   wchar_t snip2[len];
999                   mbstowcs(snip2, snip, len);
1000                   addnwstr(snip2, remains);
1001 #else
1002                   printw("%-.*s", remains, snip);
1003 #endif
1004                 }
1005             }
1006         }
1007       b->display_valid_until = last_scan_time + valid;
1008     }
1009   attrset(attrs[0][0][M_IDLE]);
1010   clrtoeol();
1011 }
1012
1013 static void
1014 redraw_all(void)
1015 {
1016   cursor_max = num_mboxes;
1017   if (cursor_max > LINES-1)
1018     cursor_max = LINES-1;
1019   if (cursor_at >= cursor_max)
1020     cursor_at = cursor_max - 1;
1021   if (cursor_at < 0)
1022     cursor_at = 0;
1023
1024   for (int i=0; i<cursor_max; i++)
1025     redraw_line(i);
1026   move(cursor_max, 0);
1027   if (!cursor_max)
1028     {
1029       printw("(no mailboxes found)");
1030       clrtoeol();
1031       move(1, 0);
1032     }
1033   clrtobot();
1034 }
1035
1036 static void
1037 rethink_display(int notify)
1038 {
1039   int i = 0;
1040   int changed = 0;
1041   int beeeep = 0;
1042   CLIST_FOR_EACH(struct mbox *, b, mboxes)
1043     if (mbox_visible_p(b))
1044       {
1045         b->index = i;
1046         if (i >= num_mboxes || mbox_array[i] != b)
1047           {
1048             changed = 1;
1049             if (i >= mbox_array_size)
1050               {
1051                 mbox_array_size = (mbox_array_size ? 2*mbox_array_size : 16);
1052                 mbox_array = xrealloc(mbox_array, sizeof(struct mbox *) * mbox_array_size);
1053               }
1054             mbox_array[i] = b;
1055           }
1056         if (b->o.beep && b->new > b->last_beep_new)
1057           beeeep = 1;
1058         b->last_beep_new = b->new;
1059         i++;
1060       }
1061   if (i != num_mboxes)
1062     changed = 1;
1063   num_mboxes = i;
1064
1065   if (changed)
1066     {
1067       redraw_all();
1068       refresh();
1069     }
1070   rethink_leds();
1071   rethink_osd(notify);
1072   if (beeeep && allow_bells && notify)
1073     beep();
1074 }
1075
1076 static void
1077 term_init(void)
1078 {
1079   initscr();
1080   cbreak();
1081   noecho();
1082   nonl();
1083   intrflush(stdscr, FALSE);
1084   keypad(stdscr, TRUE);
1085   curs_set(0);
1086
1087   static const int attrs_mono[2][M_MAX] = {
1088         [0] = { [M_IDLE] = 0,
1089                 [M_SCAN] = A_BOLD,
1090                 [M_NEW] = A_BOLD,
1091                 [M_FLAG] = 0,
1092                 [M_BAD] = A_DIM,
1093                 [M_INCSEARCH] = A_REVERSE },
1094         [1] = { [M_IDLE] = 0,
1095                 [M_SCAN] = A_BOLD,
1096                 [M_NEW] = A_REVERSE | A_BOLD,
1097                 [M_FLAG] = A_REVERSE,
1098                 [M_BAD] = A_DIM,
1099                 [M_INCSEARCH] = A_REVERSE },
1100   };
1101   for (int i=0; i<2; i++)
1102     for (int j=0; j<M_MAX; j++)
1103       {
1104         attrs[0][i][j] = attrs_mono[i][j];
1105         attrs[1][i][j] = attrs_mono[i][j] | A_UNDERLINE;
1106         attrs[2][i][j] = attrs_mono[i][j] | A_UNDERLINE;
1107       }
1108
1109   if (has_colors())
1110     {
1111       start_color();
1112       if (COLOR_PAIRS >= 12)
1113         {
1114           init_pair(1, COLOR_YELLOW, COLOR_BLACK);
1115           init_pair(2, COLOR_RED, COLOR_BLACK);
1116           init_pair(3, COLOR_WHITE, COLOR_BLUE);
1117           init_pair(4, COLOR_YELLOW, COLOR_BLUE);
1118           init_pair(5, COLOR_RED, COLOR_BLUE);
1119           init_pair(6, COLOR_GREEN, COLOR_BLACK);
1120           init_pair(7, COLOR_GREEN, COLOR_BLUE);
1121           init_pair(8, COLOR_WHITE, COLOR_MAGENTA);
1122           init_pair(9, COLOR_YELLOW, COLOR_MAGENTA);
1123           init_pair(10, COLOR_GREEN, COLOR_MAGENTA);
1124           init_pair(11, COLOR_RED, COLOR_MAGENTA);
1125           init_pair(12, COLOR_BLACK, COLOR_YELLOW);
1126           static const int attrs_color[3][2][M_MAX] = {
1127              [0][0] = { [M_IDLE] = 0,
1128                         [M_SCAN] = COLOR_PAIR(1),
1129                         [M_NEW] = COLOR_PAIR(1),
1130                         [M_FLAG] = COLOR_PAIR(6),
1131                         [M_BAD] = COLOR_PAIR(2) },
1132              [0][1] = { [M_IDLE] = A_BOLD,
1133                         [M_SCAN] = COLOR_PAIR(1),
1134                         [M_NEW] = COLOR_PAIR(1) | A_BOLD,
1135                         [M_FLAG] = COLOR_PAIR(6) | A_BOLD,
1136                         [M_BAD] = COLOR_PAIR(2) | A_BOLD },
1137              [1][0] = { [M_IDLE] = COLOR_PAIR(3),
1138                         [M_SCAN] = COLOR_PAIR(4),
1139                         [M_NEW] = COLOR_PAIR(4),
1140                         [M_FLAG] = COLOR_PAIR(7),
1141                         [M_BAD] = COLOR_PAIR(5) },
1142              [1][1] = { [M_IDLE] = COLOR_PAIR(3) | A_BOLD,
1143                         [M_SCAN] = COLOR_PAIR(4),
1144                         [M_NEW] = COLOR_PAIR(4) | A_BOLD,
1145                         [M_FLAG] = COLOR_PAIR(7) | A_BOLD,
1146                         [M_BAD] = COLOR_PAIR(5) | A_BOLD },
1147              [2][0] = { [M_IDLE] = COLOR_PAIR(8),
1148                         [M_SCAN] = COLOR_PAIR(9),
1149                         [M_NEW] = COLOR_PAIR(9),
1150                         [M_FLAG] = COLOR_PAIR(10),
1151                         [M_BAD] = COLOR_PAIR(11),
1152                         [M_INCSEARCH] = COLOR_PAIR(12) | A_DIM },
1153              [2][1] = { [M_IDLE] = COLOR_PAIR(8) | A_BOLD,
1154                         [M_SCAN] = COLOR_PAIR(9),
1155                         [M_NEW] = COLOR_PAIR(9) | A_BOLD,
1156                         [M_FLAG] = COLOR_PAIR(10) | A_BOLD,
1157                         [M_BAD] = COLOR_PAIR(11) | A_BOLD,
1158                         [M_INCSEARCH] = COLOR_PAIR(12) },
1159           };
1160           memcpy(attrs, attrs_color, sizeof(attrs));
1161         }
1162     }
1163 }
1164
1165 static void
1166 term_cleanup(void)
1167 {
1168   endwin();
1169 }
1170
1171 static void
1172 print_status(char *status)
1173 {
1174   move(LINES-1, 0);
1175   if (status)
1176     printw("%s", status);
1177   clrtoeol();
1178   refresh();
1179 }
1180
1181 static void
1182 scan_and_redraw(int notify)
1183 {
1184   print_status("Busy...");
1185   scan(notify);
1186   print_status(NULL);
1187 }
1188
1189 static void
1190 move_cursor(int i)
1191 {
1192   if (i >= 0 && i < cursor_max && i != cursor_at)
1193     {
1194       int old = cursor_at;
1195       cursor_at = i;
1196       redraw_line(old);
1197       redraw_line(i);
1198     }
1199 }
1200
1201 static void
1202 next_active(int since, int step)
1203 {
1204   if (!cursor_max)
1205     return;
1206   since = (since+cursor_max) % cursor_max;
1207   step = (step+cursor_max) % cursor_max;
1208   int besti = -1;
1209   int bestp = -1;
1210   int i = since;
1211   do
1212     {
1213       struct mbox *b = mbox_array[i];
1214       if (b->new && b->o.priority > bestp)
1215         {
1216           besti = i;
1217           bestp = b->o.priority;
1218         }
1219       i = (i+step) % cursor_max;
1220     }
1221   while (i != since);
1222   if (besti >= 0)
1223     move_cursor(besti);
1224 }
1225
1226 static void
1227 mbox_run(struct mbox *b)
1228 {
1229   char cmd[strlen(run_cmd) + strlen(b->path) + 16];
1230   sprintf(cmd, run_cmd, b->path);
1231   term_cleanup();
1232   system(cmd);
1233   term_init();
1234   redraw_all();
1235   refresh();
1236   b->force_refresh = 1;
1237   scan_and_redraw(0);
1238 }
1239
1240 static void
1241 enter_incsearch(void)
1242 {
1243   print_status("Incremental search...");
1244   is_active = 1;
1245   is_pos = 0;
1246   redraw_line(cursor_at);
1247 }
1248
1249 static int
1250 handle_incsearch(int ch)
1251 {
1252   if ((ch == KEY_BACKSPACE || ch == KEY_DC) && is_pos)
1253     --is_pos;
1254   else if (ch >= ' ' && ch <= '~')
1255     {
1256       if (is_pos < sizeof(is_buf) - 1)
1257         is_buf[is_pos++] = ch;
1258     }
1259   else
1260     {
1261       print_status(NULL);
1262       is_active = 0;
1263       is_pos = 0;
1264       redraw_line(cursor_at);
1265       return 0;
1266     }
1267
1268   is_buf[is_pos] = 0;
1269   for (int i=0; i<cursor_max; i++)
1270     {
1271       struct mbox *b = mbox_array[i];
1272       if (!strncmp(b->name, is_buf, is_pos))
1273         {
1274           if (i != cursor_at)
1275             {
1276               move_cursor(i);
1277               return 1;
1278             }
1279           break;
1280         }
1281     }
1282
1283   redraw_line(cursor_at);
1284   return 1;
1285 }
1286
1287 #define STR2(c) #c
1288 #define STR(c) STR2(c)
1289
1290 static void NONRET
1291 usage(void)
1292 {
1293   fprintf(stderr, "Usage: cm [<options>] [<mbox-pattern> | <mbox>[=<name>]] ...\n\
1294 \n\
1295 Options:\n\
1296 -c <interval>\t\tScan mailboxes every <interval> seconds (default is 30)\n\
1297 -d\t\t\tLog debug messages to stderr\n\
1298 -i\t\t\tInclude user's INBOX\n\
1299 -m <cmd>\t\tCommand to run on the selected mailbox, %%s gets replaced by mailbox path\n\
1300 -o <pattern>=<opts>\tSet mailbox options\n\
1301 -o <opts>\t\tSet default options for all mailboxes\n\
1302 -p <pri>\t\tSet minimum priority to show\n\
1303 -s <key>=<val>\t\tSet on-screen display options (consult OSDD docs)\n\
1304 \n\
1305 Mailbox options (set with `-o', use upper case to negate):\n\
1306 0-9\t\t\tSet mailbox priority (0=default)\n\
1307 b\t\t\tBeep when a message arrives\n\
1308 d\t\t\tSend an on-screen-display message (requires OSDD)\n\
1309 e\t\t\tHide from display if empty\n\
1310 f\t\t\tShow flagged messages if there are no new ones\n\
1311 h\t\t\tHide from display\n\
1312 l<led>\t\t\tLight a keyboard led (1-9) if running on X display\n\
1313 m\t\t\tShow mailbox name of the sender\n\
1314 p\t\t\tShow personal info (full name) of the sender\n\
1315 s\t\t\tShow message snippets\n\
1316 t\t\t\tHighlight the entry\n\
1317 !<key>\t\t\tSet hot key\n\
1318 \n\
1319 CheckMail " STR(VERSION) ", (c) " STR(YEAR) " Martin Mares <mj@ucw.cz>\n\
1320 It can be freely distributed and used according to the GNU GPL v2.\n\
1321 ");
1322   exit(1);
1323 }
1324
1325 static void
1326 parse_options(char *c)
1327 {
1328   struct options *o;
1329   char *sep;
1330   if (sep = strchr(c, '='))
1331     {
1332       struct option_node *n = xmalloc(sizeof(*n) + sep-c);
1333       memcpy(n->pattern, c, sep-c);
1334       n->pattern[sep-c] = 0;
1335       clist_add_tail(&options, &n->n);
1336       o = &n->o;
1337       init_options(o);
1338       c = sep+1;
1339     }
1340   else
1341     o = &global_options;
1342
1343   int x;
1344   while (x = *c++)
1345     if (x >= '0' && x <= '9')
1346       o->priority = x - '0';
1347     else if (x == '!' && *c)
1348       o->hotkey = *c++;
1349     else if (x == 'l' && *c >= '1' && *c <= '9')
1350       o->led = *c++ - '0';
1351     else
1352       {
1353         int value = !!islower(x);
1354         switch (tolower(x))
1355           {
1356           case 'b':
1357             o->beep = value;
1358             break;
1359           case 'd':
1360             o->osd = value;
1361             break;
1362           case 'e':
1363             o->hide_if_empty = value;
1364             break;
1365           case 'f':
1366             o->show_flagged = value;
1367             break;
1368           case 'h':
1369             o->hide = value;
1370             break;
1371           case 'm':
1372             o->sender_mbox = value;
1373             break;
1374           case 'p':
1375             o->sender_personal = value;
1376             break;
1377           case 's':
1378             o->snippets = value;
1379             break;
1380           case 't':
1381             o->highlight = value;
1382             break;
1383           default:
1384             fprintf(stderr, "Invalid mailbox option `%c'\n", x);
1385             usage();
1386           }
1387       }
1388 }
1389
1390 int
1391 main(int argc, char **argv)
1392 {
1393   clist_init(&mboxes);
1394   clist_init(&options);
1395   clist_init(&patterns);
1396   clist_init(&osd_opts);
1397
1398   int c;
1399   while ((c = getopt(argc, argv, "c:dim:o:p:s:")) >= 0)
1400     switch (c)
1401       {
1402       case 'c':
1403         check_interval = atol(optarg);
1404         if (check_interval <= 0)
1405           usage();
1406         break;
1407       case 'd':
1408         debug_mode++;
1409         break;
1410       case 'i':
1411         add_inbox();
1412         break;
1413       case 'm':
1414         run_cmd = optarg;
1415         break;
1416       case 'o':
1417         parse_options(optarg);
1418         break;
1419       case 'p':
1420         minimum_priority = atol(optarg);
1421         break;
1422       case 's':
1423         add_osd_opt(optarg);
1424         break;
1425       default:
1426         usage();
1427       }
1428   while (optind < argc)
1429     add_pattern(argv[optind++]);
1430
1431   charset_init();
1432   term_init();
1433   x11_init();
1434   scan_and_redraw(0);
1435   next_active(0, 1);
1436
1437   int should_exit = 0;
1438 restart:
1439   while (!should_exit)
1440     {
1441       time_t now = time(NULL);
1442       int remains = last_scan_time + check_interval - now;
1443       if (force_refresh)
1444         scan_and_redraw(0);
1445       if (remains <= 0)
1446         scan_and_redraw(1);
1447       else
1448         {
1449           remains *= 10;
1450           halfdelay((remains > 255) ? 255 : remains);
1451           int ch = getch();
1452           if (ch < 0)
1453             continue;
1454           if (is_active && handle_incsearch(ch))
1455             {
1456               refresh();
1457               continue;
1458             }
1459           for (int i=0; i<num_mboxes; i++)
1460             if (ch == mbox_array[i]->o.hotkey)
1461               {
1462                 if (i < cursor_max)
1463                   cursor_at = i;
1464                 mbox_run(mbox_array[i]);
1465                 goto restart;
1466               }
1467           switch (ch)
1468             {
1469             case 'q':
1470               should_exit = 1;
1471               break;
1472             case 'j':
1473             case KEY_DOWN:
1474               move_cursor(cursor_at+1);
1475               break;
1476             case 'k':
1477             case KEY_UP:
1478               move_cursor(cursor_at-1);
1479               break;
1480             case '^':
1481             case KEY_HOME:
1482             case KEY_PPAGE:
1483               move_cursor(0);
1484               break;
1485             case '$':
1486             case KEY_END:
1487             case KEY_NPAGE:
1488               move_cursor(cursor_max-1);
1489               break;
1490             case '\t':
1491               next_active(cursor_at+1, 1);
1492               break;
1493             case '`':
1494               next_active(cursor_at-1, -1);
1495               break;
1496             case '\r':
1497             case '\n':
1498               if (cursor_at < cursor_max)
1499                 mbox_run(mbox_array[cursor_at]);
1500               break;
1501             case 'l' & 0x1f:
1502               clearok(stdscr, TRUE);
1503               redraw_all();
1504               refresh();
1505               break;
1506             case 'r' & 0x1f:
1507               force_refresh = 1;
1508               break;
1509             case 'b':
1510               allow_bells = 1;
1511               print_status("Bells and whistles are now enabled. Toot!");
1512               break;
1513             case 'B':
1514               allow_bells = 0;
1515               print_status("Bells and whistles are now disabled. Pssst!");
1516               break;
1517             case 'd':
1518               allow_osd = 1;
1519               print_status("On-screen display is now enabled.");
1520               break;
1521             case 'D':
1522               allow_osd = 0;
1523               print_status("On-screen display is now disabled. Watch your step.");
1524               break;
1525             case '/':
1526               enter_incsearch();
1527               break;
1528             default:
1529               if (ch >= '0' && ch <= '9')
1530                 {
1531                   minimum_priority = ch - '0';
1532                   scan_and_redraw(0);
1533                 }
1534               else
1535                 debug("Pressed unknown key %d\n", ch);
1536             }
1537           refresh();
1538         }
1539     }
1540
1541   x11_cleanup();
1542   term_cleanup();
1543   return 0;
1544 }