Generally bring in additional sf_buf improvements from FreeBSD-5. Separate
[dragonfly.git] / usr.bin / calendar / day.c
1 /*
2  * Copyright (c) 1989, 1993, 1994
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * $FreeBSD: src/usr.bin/calendar/day.c,v 1.13.2.5 2003/04/06 20:04:57 dwmalone Exp $
34  * $DragonFly: src/usr.bin/calendar/day.c,v 1.3 2003/10/02 17:42:26 hmp Exp $
35  */
36
37 #include <sys/types.h>
38 #include <sys/uio.h>
39 #include <ctype.h>
40 #include <err.h>
41 #include <locale.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <time.h>
46
47 #include "pathnames.h"
48 #include "calendar.h"
49
50 struct tm *tp;
51 int *cumdays, offset, yrdays;
52 char dayname[10];
53
54
55 /* 1-based month, 0-based days, cumulative */
56 int daytab[][14] = {
57         { 0, -1, 30, 58, 89, 119, 150, 180, 211, 242, 272, 303, 333, 364 },
58         { 0, -1, 30, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
59 };
60
61 static char const *days[] = {
62         "sun", "mon", "tue", "wed", "thu", "fri", "sat", NULL,
63 };
64
65 static const char *months[] = {
66         "jan", "feb", "mar", "apr", "may", "jun",
67         "jul", "aug", "sep", "oct", "nov", "dec", NULL,
68 };
69
70 static struct fixs fndays[8];         /* full national days names */
71 static struct fixs ndays[8];          /* short national days names */
72
73 static struct fixs fnmonths[13];      /* full national months names */
74 static struct fixs nmonths[13];       /* short national month names */
75
76
77 void setnnames(void)
78 {
79         char buf[80];
80         int i, l;
81         struct tm tm;
82
83         for (i = 0; i < 7; i++) {
84                 tm.tm_wday = i;
85                 strftime(buf, sizeof(buf), "%a", &tm);
86                 for (l = strlen(buf);
87                      l > 0 && isspace((unsigned char)buf[l - 1]);
88                      l--)
89                         ;
90                 buf[l] = '\0';
91                 if (ndays[i].name != NULL)
92                         free(ndays[i].name);
93                 if ((ndays[i].name = strdup(buf)) == NULL)
94                         errx(1, "cannot allocate memory");
95                 ndays[i].len = strlen(buf);
96
97                 strftime(buf, sizeof(buf), "%A", &tm);
98                 for (l = strlen(buf);
99                      l > 0 && isspace((unsigned char)buf[l - 1]);
100                      l--)
101                         ;
102                 buf[l] = '\0';
103                 if (fndays[i].name != NULL)
104                         free(fndays[i].name);
105                 if ((fndays[i].name = strdup(buf)) == NULL)
106                         errx(1, "cannot allocate memory");
107                 fndays[i].len = strlen(buf);
108         }
109
110         for (i = 0; i < 12; i++) {
111                 tm.tm_mon = i;
112                 strftime(buf, sizeof(buf), "%b", &tm);
113                 for (l = strlen(buf);
114                      l > 0 && isspace((unsigned char)buf[l - 1]);
115                      l--)
116                         ;
117                 buf[l] = '\0';
118                 if (nmonths[i].name != NULL)
119                         free(nmonths[i].name);
120                 if ((nmonths[i].name = strdup(buf)) == NULL)
121                         errx(1, "cannot allocate memory");
122                 nmonths[i].len = strlen(buf);
123
124                 strftime(buf, sizeof(buf), "%B", &tm);
125                 for (l = strlen(buf);
126                      l > 0 && isspace((unsigned char)buf[l - 1]);
127                      l--)
128                         ;
129                 buf[l] = '\0';
130                 if (fnmonths[i].name != NULL)
131                         free(fnmonths[i].name);
132                 if ((fnmonths[i].name = strdup(buf)) == NULL)
133                         errx(1, "cannot allocate memory");
134                 fnmonths[i].len = strlen(buf);
135         }
136 }
137
138 void
139 settime(time_t now)
140 {
141         char *oldl, *lbufp;
142
143         tp = localtime(&now);
144         if ( isleap(tp->tm_year + 1900) ) {
145                 yrdays = 366;
146                 cumdays = daytab[1];
147         } else {
148                 yrdays = 365;
149                 cumdays = daytab[0];
150         }
151         /* Friday displays Monday's events */
152         offset = tp->tm_wday == Friday ? 3 : 1;
153         header[5].iov_base = dayname;
154
155         oldl = NULL;
156         lbufp = setlocale(LC_TIME, NULL);
157         if (lbufp != NULL && (oldl = strdup(lbufp)) == NULL)
158                 errx(1, "cannot allocate memory");
159         (void) setlocale(LC_TIME, "C");
160         header[5].iov_len = strftime(dayname, sizeof(dayname), "%A", tp);
161         (void) setlocale(LC_TIME, (oldl != NULL ? oldl : ""));
162         if (oldl != NULL)
163                 free(oldl);
164
165         setnnames();
166 }
167
168 /* convert Day[/Month][/Year] into unix time (since 1970)
169  * Day: two digits, Month: two digits, Year: digits
170  */
171 time_t Mktime (char *dp)
172 {
173     time_t t;
174     int d, m, y;
175     struct tm tm;
176
177     (void)time(&t);
178     tp = localtime(&t);
179
180     tm.tm_sec = 0;
181     tm.tm_min = 0;
182     tm.tm_hour = 0;
183     tm.tm_wday = 0;
184     tm.tm_mday = tp->tm_mday;
185     tm.tm_mon = tp->tm_mon;
186     tm.tm_year = tp->tm_year;
187
188     switch (sscanf(dp, "%d.%d.%d", &d, &m, &y)) {
189     case 3:
190         if (y > 1900)
191             y -= 1900;
192         tm.tm_year = y;
193         /* FALLTHROUGH */
194     case 2:
195         tm.tm_mon = m - 1;
196         /* FALLTHROUGH */
197     case 1:
198         tm.tm_mday = d;
199     }
200
201 #ifdef DEBUG
202     fprintf(stderr, "Mktime: %d %d %s\n", (int)mktime(&tm), (int)t,
203            asctime(&tm));
204 #endif
205     return(mktime(&tm));
206 }
207
208 /*
209  * Possible date formats include any combination of:
210  *      3-charmonth                     (January, Jan, Jan)
211  *      3-charweekday                   (Friday, Monday, mon.)
212  *      numeric month or day            (1, 2, 04)
213  *
214  * Any character may separate them, or they may not be separated.  Any line,
215  * following a line that is matched, that starts with "whitespace", is shown
216  * along with the matched line.
217  */
218 int
219 isnow(char *endp, int *monthp, int *dayp, int *varp)
220 {
221         int day, flags, month = 0, v1, v2;
222
223         /*
224          * CONVENTION
225          *
226          * Month:     1-12
227          * Monthname: Jan .. Dec
228          * Day:       1-31
229          * Weekday:   Mon-Sun
230          *
231          */
232
233         flags = 0;
234
235         /* read first field */
236         /* didn't recognize anything, skip it */
237         if (!(v1 = getfield(endp, &endp, &flags)))
238                 return (0);
239
240         /* Easter or Easter depending days */
241         if (flags & F_EASTER)
242             day = v1 - 1; /* days since January 1 [0-365] */
243
244          /*
245           * 1. {Weekday,Day} XYZ ...
246           *
247           *    where Day is > 12
248           */
249         else if (flags & F_ISDAY || v1 > 12) {
250
251                 /* found a day; day: 1-31 or weekday: 1-7 */
252                 day = v1;
253
254                 /* {Day,Weekday} {Month,Monthname} ... */
255                 /* if no recognizable month, assume just a day alone
256                  * in other words, find month or use current month */
257                 if (!(month = getfield(endp, &endp, &flags)))
258                         month = tp->tm_mon + 1;
259         }
260
261         /* 2. {Monthname} XYZ ... */
262         else if (flags & F_ISMONTH) {
263                 month = v1;
264
265                 /* Monthname {day,weekday} */
266                 /* if no recognizable day, assume the first day in month */
267                 if (!(day = getfield(endp, &endp, &flags)))
268                         day = 1;
269         }
270
271         /* Hm ... */
272         else {
273                 v2 = getfield(endp, &endp, &flags);
274
275                 /*
276                  * {Day} {Monthname} ...
277                  * where Day <= 12
278                  */
279                 if (flags & F_ISMONTH) {
280                         day = v1;
281                         month = v2;
282                         *varp = 0;
283                 }
284
285                 /* {Month} {Weekday,Day} ...  */
286                 else {
287                         /* F_ISDAY set, v2 > 12, or no way to tell */
288                         month = v1;
289                         /* if no recognizable day, assume the first */
290                         day = v2 ? v2 : 1;
291                         *varp = 0;
292                 }
293         }
294
295         /* convert Weekday into *next*  Day,
296          * e.g.: 'Sunday' -> 22
297          *       'SundayLast' -> ??
298          */
299         if (flags & F_ISDAY) {
300 #ifdef DEBUG
301             fprintf(stderr, "\nday: %d %s month %d\n", day, endp, month);
302 #endif
303
304             *varp = 1;
305             /* variable weekday, SundayLast, MondayFirst ... */
306             if (day < 0 || day >= 10) {
307
308                 /* negative offset; last, -4 .. -1 */
309                 if (day < 0) {
310                     v1 = day/10 - 1;          /* offset -4 ... -1 */
311                     day = 10 + (day % 10);    /* day 1 ... 7 */
312
313                     /* day, eg '22nd' */
314                     v2 = tp->tm_mday + (((day - 1) - tp->tm_wday + 7) % 7);
315
316                     /* (month length - day) / 7 + 1 */
317                     if (cumdays[month+1] - cumdays[month] >= v2
318                         && ((int)((cumdays[month+1] -
319                                cumdays[month] - v2) / 7) + 1) == -v1)
320                         /* bingo ! */
321                         day = v2;
322
323                     /* set to yesterday */
324                     else {
325                         day = tp->tm_mday - 1;
326                         if (day == 0)
327                             return (0);
328                     }
329                 }
330
331                 /* first, second ... +1 ... +5 */
332                 else {
333                     v1 = day/10;        /* offset: +1 (first Sunday) ... */
334                     day = day % 10;
335
336                     /* day, eg '22th' */
337                     v2 = tp->tm_mday + (((day - 1) - tp->tm_wday + 7) % 7);
338
339                     /* Hurrah! matched */
340                     if ( ((v2 - 1 + 7) / 7) == v1 )
341                         day = v2;
342
343                     /* set to yesterday */
344                     else {
345                         day = tp->tm_mday - 1;
346                         if (day == 0)
347                             return (0);
348                     }
349                 }
350             }
351
352             /* wired */
353             else {
354                 day = tp->tm_mday + (((day - 1) - tp->tm_wday + 7) % 7);
355                 *varp = 1;
356             }
357         }
358
359         if (!(flags & F_EASTER)) {
360             *monthp = month;
361             *dayp = day;
362             day = cumdays[month] + day;
363         }
364         else {
365             for (v1 = 0; day > cumdays[v1]; v1++)
366                 ;
367             *monthp = v1 - 1;
368             *dayp = day - cumdays[v1 - 1];
369             *varp = 1;
370         }
371
372 #ifdef DEBUG
373         fprintf(stderr, "day2: day %d(%d-%d) yday %d\n", *dayp, day, cumdays[month], tp->tm_yday);
374 #endif
375         /* if today or today + offset days */
376         if (day >= tp->tm_yday - f_dayBefore &&
377             day <= tp->tm_yday + offset + f_dayAfter)
378                 return (1);
379
380         /* if number of days left in this year + days to event in next year */
381         if (yrdays - tp->tm_yday + day <= offset + f_dayAfter ||
382             /* a year backward, eg. 6 Jan and 10 days before -> 27. Dec */
383             tp->tm_yday + day - f_dayBefore < 0
384             )
385                 return (1);
386         return (0);
387 }
388
389
390 int
391 getmonth(char *s)
392 {
393         const char **p;
394         struct fixs *n;
395
396         for (n = fnmonths; n->name; ++n)
397                 if (!strncasecmp(s, n->name, n->len))
398                         return ((n - fnmonths) + 1);
399         for (n = nmonths; n->name; ++n)
400                 if (!strncasecmp(s, n->name, n->len))
401                         return ((n - nmonths) + 1);
402         for (p = months; *p; ++p)
403                 if (!strncasecmp(s, *p, 3))
404                         return ((p - months) + 1);
405         return (0);
406 }
407
408
409 int
410 getday(char *s)
411 {
412         const char **p;
413         struct fixs *n;
414
415         for (n = fndays; n->name; ++n)
416                 if (!strncasecmp(s, n->name, n->len))
417                         return ((n - fndays) + 1);
418         for (n = ndays; n->name; ++n)
419                 if (!strncasecmp(s, n->name, n->len))
420                         return ((n - ndays) + 1);
421         for (p = days; *p; ++p)
422                 if (!strncasecmp(s, *p, 3))
423                         return ((p - days) + 1);
424         return (0);
425 }
426
427 /* return offset for variable weekdays
428  * -1 -> last weekday in month
429  * +1 -> first weekday in month
430  * ... etc ...
431  */
432 int
433 getdayvar(char *s)
434 {
435         int offs;
436
437
438         offs = strlen(s);
439
440
441         /* Sun+1 or Wednesday-2
442          *    ^              ^   */
443
444         /* fprintf(stderr, "x: %s %s %d\n", s, s + offs - 2, offs); */
445         switch(*(s + offs - 2)) {
446         case '-':
447             return(-(atoi(s + offs - 1)));
448             break;
449         case '+':
450             return(atoi(s + offs - 1));
451             break;
452         }
453
454
455         /*
456          * some aliases: last, first, second, third, fourth
457          */
458
459         /* last */
460         if      (offs > 4 && !strcasecmp(s + offs - 4, "last"))
461             return(-1);
462         else if (offs > 5 && !strcasecmp(s + offs - 5, "first"))
463             return(+1);
464         else if (offs > 6 && !strcasecmp(s + offs - 6, "second"))
465             return(+2);
466         else if (offs > 5 && !strcasecmp(s + offs - 5, "third"))
467             return(+3);
468         else if (offs > 6 && !strcasecmp(s + offs - 6, "fourth"))
469             return(+4);
470
471
472         /* no offset detected */
473         return(0);
474 }