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