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