616f57b90c37b025538f4bdf9224de7a9fda461f
[mmh] / uip / folder.c
1 /*
2 ** folder(s).c -- set/list the current message and/or folder
3 **             -- push/pop a folder onto/from the folder stack
4 **             -- list the folder stack
5 **
6 ** This code is Copyright (c) 2002, 2008, by the authors of nmh.  See the
7 ** COPYRIGHT file in the root directory of the nmh distribution for
8 ** complete copyright information.
9 */
10
11 #include <h/mh.h>
12 #include <h/crawl_folders.h>
13 #include <h/utils.h>
14 #include <errno.h>
15
16 static struct swit switches[] = {
17 #define ALLSW  0
18         { "all", 0 },
19 #define NALLSW  1
20         { "noall", 0 },
21 #define CREATSW  2
22         { "create", 0 },
23 #define NCREATSW  3
24         { "nocreate", 0 },
25 #define FASTSW  4
26         { "fast", 0 },
27 #define NFASTSW  5
28         { "nofast", 0 },
29 #define HDRSW  6
30         { "header", 0 },
31 #define NHDRSW  7
32         { "noheader", 0 },
33 #define PACKSW  8
34         { "pack", 0 },
35 #define NPACKSW  9
36         { "nopack", 0 },
37 #define VERBSW  10
38         { "verbose", 0 },
39 #define NVERBSW  11
40         { "noverbose", 0 },
41 #define RECURSW  12
42         { "recurse", 0 },
43 #define NRECRSW  13
44         { "norecurse", 0 },
45 #define TOTALSW  14
46         { "total", 0 },
47 #define NTOTLSW  15
48         { "nototal", 0 },
49 #define LISTSW  16
50         { "list", 0 },
51 #define NLISTSW  17
52         { "nolist", 0 },
53 #define PRNTSW  18
54         { "print", 0 },
55 #define NPRNTSW  19
56         { "noprint", -4 },
57 #define PUSHSW  20
58         { "push", 0 },
59 #define POPSW  21
60         { "pop", 0 },
61 #define VERSIONSW  22
62         { "version", 0 },
63 #define HELPSW  23
64         { "help", 0 },
65         { NULL, 0 }
66 };
67
68 static int fshort   = 0;  /* output only folder names */
69 static int fcreat   = 0;  /* should we ask to create new folders? */
70 static int fpack    = 0;  /* are we packing the folder? */
71 static int fverb    = 0;  /* print actions taken while packing folder */
72 static int fheader  = 0;  /* should we output a header? */
73 static int frecurse = 0;  /* recurse through subfolders */
74 static int ftotal   = 0;  /* should we output the totals? */
75 static int all      = 0;  /* should we output all folders */
76
77 static int total_folders = 0;  /* total number of folders */
78
79 static char *nmhdir;
80 static char *stack = "Folder-Stack";
81 static char folder[BUFSIZ];
82
83 /*
84 ** Structure to hold information about
85 ** folders as we scan them.
86 */
87 struct FolderInfo {
88         char *name;
89         int nummsg;
90         int curmsg;
91         int lowmsg;
92         int hghmsg;
93         int others;  /* others == 1 if other files in folder */
94         int error;  /* error == 1 for unreadable folder */
95 };
96
97 /*
98 ** Dynamically allocated space to hold
99 ** all the folder information.
100 */
101 static struct FolderInfo *fi;
102 static int maxFolderInfo;
103
104 /*
105 ** static prototypes
106 */
107 static int get_folder_info(char *, char *);
108 static crawl_callback_t get_folder_info_callback;
109 static void print_folders(void);
110 static int sfold(struct msgs *, char *);
111 static void readonly_folders(void);
112 static int folder_pack(struct msgs **, int);
113
114
115 int
116 main(int argc, char **argv)
117 {
118         int printsw = 0, listsw = 0;
119         int pushsw = 0, popsw = 0;
120         char *cp, *dp, *msg = NULL, *argfolder = NULL;
121         char **ap, **argp, buf[BUFSIZ], **arguments;
122
123 #ifdef LOCALE
124         setlocale(LC_ALL, "");
125 #endif
126         invo_name = mhbasename(argv[0]);
127
128         /* read user profile/context */
129         context_read();
130
131         /*
132         ** If program was invoked with name ending
133         ** in `s', then add switch `-all'.
134         */
135         if (argv[0][strlen(argv[0]) - 1] == 's')
136                 all = 1;
137
138         arguments = getarguments(invo_name, argc, argv, 1);
139         argp = arguments;
140
141         while ((cp = *argp++)) {
142                 if (*cp == '-') {
143                         switch (smatch(++cp, switches)) {
144                         case AMBIGSW:
145                                 ambigsw(cp, switches);
146                                 done(1);
147                         case UNKWNSW:
148                                 adios(NULL, "-%s unknown", cp);
149
150                         case HELPSW:
151                                 snprintf(buf, sizeof(buf), "%s [+folder] [msg] [switches]", invo_name);
152                                 print_help(buf, switches, 1);
153                                 done(1);
154                         case VERSIONSW:
155                                 print_version(invo_name);
156                                 done(1);
157
158                         case ALLSW:
159                                 all = 1;
160                                 continue;
161
162                         case NALLSW:
163                                 all = 0;
164                                 continue;
165
166                         case CREATSW:
167                                 fcreat = 1;
168                                 continue;
169                         case NCREATSW:
170                                 fcreat = -1;
171                                 continue;
172
173                         case FASTSW:
174                                 fshort++;
175                                 continue;
176                         case NFASTSW:
177                                 fshort = 0;
178                                 continue;
179
180                         case HDRSW:
181                                 fheader = 1;
182                                 continue;
183                         case NHDRSW:
184                                 fheader = -1;
185                                 continue;
186
187                         case PACKSW:
188                                 fpack++;
189                                 continue;
190                         case NPACKSW:
191                                 fpack = 0;
192                                 continue;
193
194                         case VERBSW:
195                                 fverb++;
196                                 continue;
197                         case NVERBSW:
198                                 fverb = 0;
199                                 continue;
200
201                         case RECURSW:
202                                 frecurse++;
203                                 continue;
204                         case NRECRSW:
205                                 frecurse = 0;
206                                 continue;
207
208                         case TOTALSW:
209                                 ftotal = 1;
210                                 continue;
211                         case NTOTLSW:
212                                 ftotal = -1;
213                                 continue;
214
215                         case PRNTSW:
216                                 printsw = 1;
217                                 continue;
218                         case NPRNTSW:
219                                 printsw = 0;
220                                 continue;
221
222                         case LISTSW:
223                                 listsw = 1;
224                                 continue;
225                         case NLISTSW:
226                                 listsw = 0;
227                                 continue;
228
229                         case PUSHSW:
230                                 pushsw = 1;
231                                 listsw = 1;
232                                 popsw  = 0;
233                                 continue;
234                         case POPSW:
235                                 popsw  = 1;
236                                 listsw = 1;
237                                 pushsw = 0;
238                                 continue;
239                         }
240                 }
241                 if (*cp == '+' || *cp == '@') {
242                         if (argfolder)
243                                 adios(NULL, "only one folder at a time!");
244                         else
245                                 argfolder = getcpy(expandfol(cp));
246                 } else {
247                         if (msg)
248                                 adios(NULL, "only one (current) message at a time!");
249                         else
250                                 msg = cp;
251                 }
252         }
253
254         nmhdir = concat(toabsdir("+"), "/", NULL);
255
256         /*
257         ** If we aren't working with the folder stack
258         ** (-push, -pop, -list) then the default is to print.
259         */
260         if (pushsw == 0 && popsw == 0 && listsw == 0)
261                 printsw++;
262
263         /* Pushing a folder onto the folder stack */
264         if (pushsw) {
265                 if (!argfolder) {
266                         /* If no folder is given, the current folder and */
267                         /* the top of the folder stack are swapped. */
268                         if ((cp = context_find(stack))) {
269                                 dp = getcpy(cp);
270                                 ap = brkstring(dp, " ", "\n");
271                                 argfolder = getcpy(*ap++);
272                         } else {
273                                 adios(NULL, "no other folder");
274                         }
275                         for (cp = getcpy(getcurfol()); *ap; ap++)
276                                 cp = add(*ap, add(" ", cp));
277                         free(dp);
278                         context_replace(stack, cp);  /* update folder stack */
279                 } else {
280                         /* update folder stack */
281                         context_replace(stack, (cp = context_find (stack)) ?
282                                         concat(getcurfol(), " ", cp, NULL) :
283                                         getcpy(getcurfol()));
284                 }
285         }
286
287         /* Popping a folder off of the folder stack */
288         if (popsw) {
289                 if (argfolder)
290                         adios(NULL, "sorry, no folders allowed with -pop");
291                 if ((cp = context_find(stack))) {
292                         dp = getcpy(cp);
293                         ap = brkstring(dp, " ", "\n");
294                         argfolder = getcpy(*ap++);
295                 } else {
296                         adios(NULL, "folder stack empty");
297                 }
298                 if (*ap) {
299                         /* if there's anything left in the stack */
300                         cp = getcpy(*ap++);
301                         for (; *ap; ap++)
302                                 cp = add(*ap, add(" ", cp));
303                         context_replace(stack, cp);  /* update folder stack */
304                 } else {
305                         /* delete folder stack entry from context */
306                         context_del(stack);
307                 }
308                 free(dp);
309         }
310         if (pushsw || popsw) {
311                 cp = toabsdir(argfolder);
312                 if (access(cp, F_OK) == NOTOK)
313                         adios(cp, "unable to find folder");
314                 /* update current folder   */
315                 context_replace(curfolder, argfolder);
316                 context_save();  /* save the context file   */
317                 argfolder = NULL;
318         }
319
320         /* Listing the folder stack */
321         if (listsw) {
322                 printf("%s", argfolder ? argfolder : getcurfol());
323                 if ((cp = context_find(stack))) {
324                         dp = getcpy(cp);
325                         for (ap = brkstring(dp, " ", "\n"); *ap; ap++)
326                                 printf(" %s", *ap);
327                         free(dp);
328                 }
329                 printf("\n");
330
331                 if (!printsw)
332                         done(0);
333         }
334
335         /* Allocate initial space to record folder information */
336         maxFolderInfo = CRAWL_NUMFOLDERS;
337         fi = mh_xmalloc(maxFolderInfo * sizeof(*fi));
338
339         /*
340         ** Scan the folders
341         */
342         if (all || ftotal > 0) {
343                 /*
344                 ** If no folder is given, do them all
345                 */
346                 /*
347                 ** change directory to base of nmh directory for
348                 ** crawl_folders
349                 */
350                 if (chdir(nmhdir) == NOTOK)
351                         adios(nmhdir, "unable to change directory to");
352                 if (!argfolder) {
353                         if (msg)
354                                 admonish(NULL, "no folder given for message %s", msg);
355                         readonly_folders(); /* do any readonly folders */
356                         strncpy(folder, (cp = context_find(curfolder)) ?
357                                         cp : "", sizeof(folder));
358                         crawl_folders(".", get_folder_info_callback, NULL);
359                 } else {
360                         strncpy(folder, argfolder, sizeof(folder));
361                         if (get_folder_info(argfolder, msg)) {
362                                 /* update current folder */
363                                 context_replace(curfolder, argfolder);
364                                 context_save();
365                         }
366                         /*
367                         ** Since recurse wasn't done in get_folder_info(),
368                         ** we still need to list all level-1 sub-folders.
369                         */
370                         if (!frecurse)
371                                 crawl_folders(folder, get_folder_info_callback,
372                                                 NULL);
373                 }
374         } else {
375                 strncpy(folder, argfolder ? argfolder : getcurfol(),
376                                 sizeof(folder));
377
378                 /*
379                 ** Check if folder exists.  If not, then see if
380                 ** we should create it, or just exit.
381                 */
382                 create_folder(toabsdir(folder), fcreat, done);
383
384                 if (get_folder_info(folder, msg) && argfolder) {
385                         /* update current folder */
386                         context_replace(curfolder, argfolder);
387                         }
388         }
389
390         /*
391         ** Print out folder information
392         */
393         print_folders();
394
395         context_save();
396         done(0);
397         return 1;
398 }
399
400 static int
401 get_folder_info_body(char *fold, char *msg, boolean *crawl_children)
402 {
403         int i, retval = 1;
404         struct msgs *mp = NULL;
405
406         i = total_folders++;
407
408         /*
409         ** if necessary, reallocate the space
410         ** for folder information
411         */
412         if (total_folders >= maxFolderInfo) {
413                 maxFolderInfo += CRAWL_NUMFOLDERS;
414                 fi = mh_xrealloc(fi, maxFolderInfo * sizeof(*fi));
415         }
416
417         fi[i].name   = fold;
418         fi[i].nummsg = 0;
419         fi[i].curmsg = 0;
420         fi[i].lowmsg = 0;
421         fi[i].hghmsg = 0;
422         fi[i].others = 0;
423         fi[i].error  = 0;
424
425         if ((ftotal > 0) || !fshort || msg || fpack) {
426                 /*
427                 ** create message structure and get folder info
428                 */
429                 if (!(mp = folder_read(fold))) {
430                         admonish(NULL, "unable to read folder %s", fold);
431                         return 0;
432                 }
433
434                 /* set the current message */
435                 if (msg && !sfold(mp, msg))
436                         retval = 0;
437
438                 if (fpack) {
439                         if (folder_pack(&mp, fverb) == -1)
440                                 done(1);
441                         seq_save(mp);  /* synchronize the sequences */
442                         context_save();  /* save the context file */
443                 }
444
445                 /* record info for this folder */
446                 if ((ftotal > 0) || !fshort) {
447                         fi[i].nummsg = mp->nummsg;
448                         fi[i].curmsg = mp->curmsg;
449                         fi[i].lowmsg = mp->lowmsg;
450                         fi[i].hghmsg = mp->hghmsg;
451                         fi[i].others = other_files(mp);
452                 }
453
454                 folder_free(mp); /* free folder/message structure */
455         }
456
457         *crawl_children = (frecurse && (fshort || fi[i].others)
458                 && (fi[i].error == 0));
459         return retval;
460 }
461
462 static boolean
463 get_folder_info_callback(char *fold, void *baton)
464 {
465         boolean crawl_children;
466         get_folder_info_body(fold, NULL, &crawl_children);
467         fflush(stdout);
468         return crawl_children;
469 }
470
471 static int
472 get_folder_info(char *fold, char *msg)
473 {
474         boolean crawl_children;
475         int retval;
476
477         retval = get_folder_info_body(fold, msg, &crawl_children);
478
479         if (crawl_children) {
480                 crawl_folders(fold, get_folder_info_callback, NULL);
481         }
482 return retval;
483 }
484
485 /*
486 ** Print folder information
487 */
488
489 static void
490 print_folders(void)
491 {
492         int i, len, hasempty = 0, curprinted;
493         int maxlen = 0, maxnummsg = 0, maxlowmsg = 0;
494         int maxhghmsg = 0, maxcurmsg = 0, total_msgs = 0;
495         int nummsgdigits, lowmsgdigits;
496         int hghmsgdigits, curmsgdigits;
497         char tmpname[BUFSIZ];
498
499         /*
500         ** compute a few values needed to for
501         ** printing various fields
502         */
503         for (i = 0; i < total_folders; i++) {
504                 /* length of folder name */
505                 len = strlen(fi[i].name);
506                 if (len > maxlen)
507                         maxlen = len;
508
509                 /* If folder has error, skip the rest */
510                 if (fi[i].error)
511                         continue;
512
513                 /* calculate total number of messages */
514                 total_msgs += fi[i].nummsg;
515
516                 /* maximum number of messages */
517                 if (fi[i].nummsg > maxnummsg)
518                         maxnummsg = fi[i].nummsg;
519
520                 /* maximum low message */
521                 if (fi[i].lowmsg > maxlowmsg)
522                         maxlowmsg = fi[i].lowmsg;
523
524                 /* maximum high message */
525                 if (fi[i].hghmsg > maxhghmsg)
526                         maxhghmsg = fi[i].hghmsg;
527
528                 /* maximum current message */
529                 if (fi[i].curmsg >= fi[i].lowmsg &&
530                         fi[i].curmsg <= fi[i].hghmsg &&
531                         fi[i].curmsg > maxcurmsg)
532                         maxcurmsg = fi[i].curmsg;
533
534                 /* check for empty folders */
535                 if (fi[i].nummsg == 0)
536                         hasempty = 1;
537         }
538         nummsgdigits = num_digits(maxnummsg);
539         lowmsgdigits = num_digits(maxlowmsg);
540         hghmsgdigits = num_digits(maxhghmsg);
541         curmsgdigits = num_digits(maxcurmsg);
542
543         if (hasempty && nummsgdigits < 2)
544                 nummsgdigits = 2;
545
546         /*
547         ** Print the header
548         */
549         if (fheader > 0 || (all && !fshort && fheader >= 0))
550                 printf("%-*s %*s %-*s; %-*s %*s\n",
551                                 maxlen+1, "FOLDER",
552                                 nummsgdigits + 13, "# MESSAGES",
553                                 lowmsgdigits + hghmsgdigits + 4, " RANGE",
554                                 curmsgdigits + 4, "CUR",
555                                 9, "(OTHERS)");
556
557         /*
558         ** Print folder information
559         */
560         if (all || fshort || ftotal < 1) {
561                 for (i = 0; i < total_folders; i++) {
562                         if (fshort) {
563                                 printf("%s\n", fi[i].name);
564                                 continue;
565                         }
566
567                         /* Add `+' to end of name, if folder is current */
568                         if (strcmp(folder, fi[i].name)!=0)
569                                 snprintf(tmpname, sizeof(tmpname), "%s",
570                                                 fi[i].name);
571                         else
572                                 snprintf(tmpname, sizeof(tmpname), "%s+",
573                                                 fi[i].name);
574
575                         if (fi[i].error) {
576                                 printf("%-*s is unreadable\n", maxlen+1,
577                                                 tmpname);
578                                 continue;
579                         }
580
581                         printf("%-*s ", maxlen+1, tmpname);
582
583                         curprinted = 0; /* remember if we print cur */
584                         if (fi[i].nummsg == 0) {
585                                 printf("has %*s messages%*s", nummsgdigits, "no", fi[i].others ? lowmsgdigits + hghmsgdigits + 5 : 0, "");
586                         } else {
587                                 printf("has %*d message%s  (%*d-%*d)",
588                                                 nummsgdigits, fi[i].nummsg,
589                                                 (fi[i].nummsg == 1) ?
590                                                 " " : "s",
591                                                 lowmsgdigits, fi[i].lowmsg,
592                                                 hghmsgdigits, fi[i].hghmsg);
593                                 if (fi[i].curmsg >= fi[i].lowmsg && fi[i].curmsg <= fi[i].hghmsg) {
594                                         curprinted = 1;
595                                         printf("; cur=%*d", curmsgdigits,
596                                                         fi[i].curmsg);
597                                 }
598                         }
599
600                         if (fi[i].others)
601                                 printf(";%*s (others)", curprinted ?
602                                                 0 : curmsgdigits + 6, "");
603                         printf(".\n");
604                 }
605         }
606
607         /*
608         ** Print folder/message totals
609         */
610         if (ftotal > 0 || (all && !fshort && ftotal >= 0)) {
611                 if (all)
612                         printf("\n");
613                 printf("TOTAL = %d message%c in %d folder%s.\n",
614                                 total_msgs, total_msgs != 1 ? 's' : ' ',
615                                 total_folders, total_folders != 1 ? "s" : "");
616         }
617
618         fflush(stdout);
619 }
620
621 /*
622 ** Set the current message and sychronize sequences
623 */
624
625 static int
626 sfold(struct msgs *mp, char *msg)
627 {
628         /* parse the message range/sequence/name and set SELECTED */
629         if (!m_convert(mp, msg))
630                 return 0;
631
632         if (mp->numsel > 1) {
633                 admonish(NULL, "only one message at a time!");
634                 return 0;
635         }
636         seq_setprev(mp);  /* set the previous-sequence */
637         seq_setcur(mp, mp->lowsel);  /* set current message */
638         seq_save(mp);  /* synchronize message sequences */
639         context_save();  /* save the context file */
640
641         return 1;
642 }
643
644
645 /*
646 ** Do the read only folders
647 */
648
649 static void
650 readonly_folders(void)
651 {
652         int atrlen;
653         char atrcur[BUFSIZ];
654         register struct node *np;
655
656         snprintf(atrcur, sizeof(atrcur), "atr-%s-", seq_cur);
657         atrlen = strlen(atrcur);
658
659         for (np = m_defs; np; np = np->n_next)
660                 if (strncmp(np->n_name, atrcur, atrlen)==0 &&
661                                 strncmp(np->n_name+atrlen, nmhdir, strlen(nmhdir))!=0)
662                         /* Why do we exclude absolute path names? --meillo */
663                         get_folder_info(np->n_name + atrlen, NULL);
664 }
665
666
667 /*
668 ** pack (renumber) the messages in a folder
669 ** into a contiguous range from 1 to n.
670 ** Return -1 if error, else return 0.
671 */
672 static int
673 folder_pack(struct msgs **mpp, int verbose)
674 {
675         int hole, msgnum, newcurrent = 0;
676         char newmsg[BUFSIZ], oldmsg[BUFSIZ];
677         struct msgs *mp;
678
679         mp = *mpp;
680
681         /*
682         ** Just return if folder is empty.
683         */
684         if (mp->nummsg == 0)
685                 return 0;
686
687         /*
688         ** Make sure we have message status space allocated
689         ** for all numbers from 1 to current high message.
690         */
691         if (mp->lowoff > 1) {
692                 if ((mp = folder_realloc(mp, 1, mp->hghmsg)))
693                         *mpp = mp;
694                 else {
695                         advise(NULL, "unable to allocate folder storage");
696                         return -1;
697                 }
698         }
699
700         for (msgnum = mp->lowmsg, hole = 1; msgnum <= mp->hghmsg; msgnum++) {
701                 if (does_exist(mp, msgnum)) {
702                         if (msgnum != hole) {
703                                 strncpy(newmsg, m_name(hole), sizeof(newmsg));
704                                 strncpy(oldmsg, m_name(msgnum), sizeof(oldmsg));
705                                 if (verbose)
706                                         printf("message %s becomes %s\n", oldmsg, newmsg);
707
708                                 /*
709                                 ** Invoke the external refile hook for each
710                                 ** message being renamed.  This is done
711                                 ** before the file is renamed so that the
712                                 ** old message file is around for the hook.
713                                 */
714
715                                 snprintf(oldmsg, sizeof (oldmsg), "%s/%d",
716                                                 mp->foldpath, msgnum);
717                                 snprintf(newmsg, sizeof (newmsg), "%s/%d",
718                                                 mp->foldpath, hole);
719                                 ext_hook("ref-hook", oldmsg, newmsg);
720
721                                 /* move the message file */
722                                 if (rename(oldmsg, newmsg) == -1) {
723                                         advise(newmsg, "unable to rename %s to", oldmsg);
724                                         return -1;
725                                 }
726
727                                 /* check if this is the current message */
728                                 if (msgnum == mp->curmsg)
729                                         newcurrent = hole;
730
731                                 /* copy the attribute flags for this message */
732                                 copy_msg_flags(mp, hole, msgnum);
733
734                                 if (msgnum == mp->lowsel)
735                                         mp->lowsel = hole;
736                                 if (msgnum == mp->hghsel)
737                                         mp->hghsel = hole;
738
739                                 /*
740                                 ** mark that sequence information has
741                                 ** been modified
742                                 */
743                                 mp->msgflags |= SEQMOD;
744                         }
745                         hole++;
746                 }
747         }
748
749         /* record the new number for the high/low message */
750         mp->lowmsg = 1;
751         mp->hghmsg = hole - 1;
752
753         if (newcurrent)
754                 seq_setcur(mp, newcurrent);
755
756         return 0;
757 }