]> git.ipfire.org Git - thirdparty/util-linux.git/blob - misc-utils/cal.c
tests: logger with socat device
[thirdparty/util-linux.git] / misc-utils / cal.c
1 /*
2 * Copyright (c) 1989, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Kim Letkeman.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37 /* 1999-02-01 Jean-Francois Bignolles: added option '-m' to display
38 * monday as the first day of the week.
39 * 1999-02-22 Arkadiusz Miƛkiewicz <misiek@pld.ORG.PL>
40 * - added Native Language Support
41 *
42 * 2000-09-01 Michael Charles Pruznick <dummy@netwiz.net>
43 * Added "-3" option to print prev/next month with current.
44 * Added over-ridable default NUM_MONTHS and "-1" option to
45 * get traditional output when -3 is the default. I hope that
46 * enough people will like -3 as the default that one day the
47 * product can be shipped that way.
48 *
49 * 2001-05-07 Pablo Saratxaga <pablo@mandrakesoft.com>
50 * Fixed the bugs with multi-byte charset (zg: cjk, utf-8)
51 * displaying. made the 'month year' ("%s %d") header translatable
52 * so it can be adapted to conventions used by different languages
53 * added support to read "first_weekday" locale information
54 * still to do: support for 'cal_direction' (will require a major
55 * rewrite of the displaying) and proper handling of RTL scripts
56 */
57
58 #include <sys/types.h>
59
60 #include <ctype.h>
61 #include <getopt.h>
62 #include <stdint.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <time.h>
67 #include <unistd.h>
68 #include <errno.h>
69
70 #include "c.h"
71 #include "closestream.h"
72 #include "colors.h"
73 #include "nls.h"
74 #include "mbsalign.h"
75 #include "strutils.h"
76
77 static int has_term = 0;
78 static const char *Senter = "", *Sexit = ""; /* enter and exit standout mode */
79
80 #if defined(HAVE_LIBNCURSES) || defined(HAVE_LIBNCURSESW)
81 # ifdef HAVE_NCURSES_H
82 # include <ncurses.h>
83 # elif defined(HAVE_NCURSES_NCURSES_H)
84 # include <ncurses/ncurses.h>
85 # endif
86 # include <term.h>
87
88 static int setup_terminal(char *term)
89 {
90 int ret;
91
92 if (setupterm(term, STDOUT_FILENO, &ret) != OK || ret != 1)
93 return -1;
94 return 0;
95 }
96
97 static void my_putstring(char *s)
98 {
99 if (has_term)
100 putp(s);
101 else
102 fputs(s, stdout);
103 }
104
105 static const char *my_tgetstr(char *s __attribute__((__unused__)), char *ss)
106 {
107 const char *ret = NULL;
108
109 if (has_term)
110 ret = tigetstr(ss);
111 if (!ret || ret == (char *)-1)
112 return "";
113 return ret;
114 }
115
116 #elif defined(HAVE_LIBTERMCAP)
117 # include <termcap.h>
118
119 static char termbuffer[4096];
120 static char tcbuffer[4096];
121 static char *strbuf = termbuffer;
122
123 static int setup_terminal(char *term)
124 {
125 if (tgetent(tcbuffer, term) < 0)
126 return -1;
127 return 0;
128 }
129
130 static void my_putstring(char *s)
131 {
132 if (has_term)
133 tputs(s, 1, putchar);
134 else
135 fputs(s, stdout);
136 }
137
138 static const char *my_tgetstr(char *s, char *ss __attribute__((__unused__)))
139 {
140 const char *ret = NULL;
141
142 if (has_term)
143 ret = tgetstr(s, &strbuf);
144 if (!ret)
145 return "";
146 return ret;
147 }
148
149 #else /* ! (HAVE_LIBTERMCAP || HAVE_LIBNCURSES || HAVE_LIBNCURSESW) */
150
151 static void my_putstring(char *s)
152 {
153 fputs(s, stdout);
154 }
155
156 #endif /* end of LIBTERMCAP / NCURSES */
157
158
159 #include "widechar.h"
160
161 /* allow compile-time define to over-ride default */
162 #ifndef NUM_MONTHS
163 # define NUM_MONTHS 1
164 #endif
165
166 #if ( NUM_MONTHS != 1 && NUM_MONTHS !=3 )
167 # error NUM_MONTHS must be 1 or 3
168 #endif
169
170 enum {
171 SUNDAY = 0,
172 MONDAY,
173 TUESDAY,
174 WEDNESDAY,
175 THURSDAY,
176 FRIDAY,
177 SATURDAY,
178 DAYS_IN_WEEK,
179 NONEDAY
180 };
181
182 #define FIRST_WEEKDAY SATURDAY /* Jan 1st, 1 was a Saturday */
183 #define REFORMATION_YEAR 1752 /* Signed-off-by: Lord Chesterfield */
184 #define REFORMATION_MONTH 9 /* September */
185 #define FIRST_MISSING_DAY 639799 /* 3 Sep 1752 */
186 #define NUMBER_MISSING_DAYS 11 /* 11 day correction */
187 #define YDAY_AFTER_MISSING 258 /* 14th in Sep 1752 */
188
189 #define DAYS_IN_YEAR 365 /* the common case, leap years are calculated */
190 #define MONTHS_IN_YEAR 12
191 #define DAYS_IN_MONTH 31
192 #define MAXDAYS 42 /* slots in a month array */
193 #define SPACE -1 /* used in day array */
194
195 #define SMALLEST_YEAR 1
196
197 #define DAY_LEN 3 /* 3 spaces per day */
198 #define WEEK_LEN (DAYS_IN_WEEK * DAY_LEN)
199 #define HEAD_SEP 2
200 #define MONTH_COLS 3 /* month columns in year view */
201 #define WNUM_LEN 3
202
203 #define TODAY_FLAG 0x400 /* flag day for highlighting */
204
205 #define FMT_ST_CHARS 300 /* 90 suffices in most locales */
206
207 static const int days_in_month[2][13] = {
208 {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
209 {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
210 };
211
212 enum {
213 WEEK_NUM_DISABLED = 0,
214 WEEK_NUM_MASK=0xff,
215 WEEK_NUM_ISO=0x100,
216 WEEK_NUM_US=0x200,
217 };
218
219 /* utf-8 can have up to 6 bytes per char; and an extra byte for ending \0 */
220 static char day_headings[(WEEK_LEN + 1) * 6 + 1];
221
222 struct cal_request {
223 int day;
224 int month;
225 int32_t year;
226 int week;
227 };
228
229 struct cal_control {
230 const char *full_month[MONTHS_IN_YEAR]; /* month names */
231 int colormode; /* day and week number highlight */
232 int num_months; /* number of months horizontally in print out */
233 int weekstart; /* day the week starts, often Sun or Mon */
234 int weektype; /* WEEK_TYPE_{NONE,ISO,US} */
235 size_t day_width; /* day width in characters in printout */
236 size_t week_width; /* 7 * day_width + possible week num */
237 int gutter_width; /* spaces in between horizontal month outputs */
238 struct cal_request req; /* the times user is interested */
239 unsigned int julian:1, /* julian output */
240 yflag:1, /* print whole year */
241 header_hint:1; /* does month name + year need two lines to fit */
242 };
243
244 struct cal_month {
245 int days[MAXDAYS]; /* the day numbers, or SPACE */
246 int weeks[MAXDAYS / DAYS_IN_WEEK];
247 int month;
248 int32_t year;
249 struct cal_month *next;
250 };
251
252 /* function prototypes */
253 static int leap_year(int32_t year);
254 static void headers_init(struct cal_control *ctl);
255 static void set_consecutive_months(struct cal_month *month, int m, int32_t y);
256 static void cal_fill_month(struct cal_month *month, const struct cal_control *ctl);
257 static void cal_output_header(struct cal_month *month, const struct cal_control *ctl);
258 static void cal_output_months(struct cal_month *month, const struct cal_control *ctl);
259 static void monthly(const struct cal_control *ctl);
260 static void monthly3(const struct cal_control *ctl);
261 static void yearly(const struct cal_control *ctl);
262 static int day_in_year(int day, int month, int32_t year);
263 static int day_in_week(int day, int month, int32_t year);
264 static int week_number(int day, int month, int32_t year, const struct cal_control *ctl);
265 static int week_to_day(const struct cal_control *ctl);
266 static int center_str(const char *src, char *dest, size_t dest_size, size_t width);
267 static void center(const char *str, size_t len, int separate);
268 static void __attribute__((__noreturn__)) usage(FILE *out);
269
270 int main(int argc, char **argv)
271 {
272 struct tm *local_time;
273 time_t now;
274 int ch;
275 static struct cal_control ctl = {
276 .weekstart = SUNDAY,
277 .num_months = NUM_MONTHS,
278 .colormode = UL_COLORMODE_UNDEF,
279 .weektype = WEEK_NUM_DISABLED,
280 .day_width = DAY_LEN,
281 .gutter_width = 2,
282 .req.day = 0,
283 .req.month = 0
284 };
285
286 enum {
287 OPT_COLOR = CHAR_MAX + 1
288 };
289
290 static const struct option longopts[] = {
291 {"one", no_argument, NULL, '1'},
292 {"three", no_argument, NULL, '3'},
293 {"sunday", no_argument, NULL, 's'},
294 {"monday", no_argument, NULL, 'm'},
295 {"julian", no_argument, NULL, 'j'},
296 {"year", no_argument, NULL, 'y'},
297 {"week", optional_argument, NULL, 'w'},
298 {"color", optional_argument, NULL, OPT_COLOR},
299 {"version", no_argument, NULL, 'V'},
300 {"help", no_argument, NULL, 'h'},
301 {NULL, 0, NULL, 0}
302 };
303
304 setlocale(LC_ALL, "");
305 bindtextdomain(PACKAGE, LOCALEDIR);
306 textdomain(PACKAGE);
307 atexit(close_stdout);
308
309 #if defined(HAVE_LIBNCURSES) || defined(HAVE_LIBNCURSESW) || defined(HAVE_LIBTERMCAP)
310 {
311 char *term = getenv("TERM");
312
313 if (term) {
314 has_term = setup_terminal(term) == 0;
315 if (has_term) {
316 Senter = my_tgetstr("so","smso");
317 Sexit = my_tgetstr("se","rmso");
318 }
319 }
320 }
321 #endif
322
323 /*
324 * The traditional Unix cal utility starts the week at Sunday,
325 * while ISO 8601 starts at Monday. We read the start day from
326 * the locale database, which can be overridden with the
327 * -s (Sunday) or -m (Monday) options.
328 */
329 #if HAVE_DECL__NL_TIME_WEEK_1STDAY
330 /*
331 * You need to use 2 locale variables to get the first day of the week.
332 * This is needed to support first_weekday=2 and first_workday=1 for
333 * the rare case where working days span across 2 weeks.
334 * This shell script shows the combinations and calculations involved:
335 *
336 * for LANG in en_US ru_RU fr_FR csb_PL POSIX; do
337 * printf "%s:\t%s + %s -1 = " $LANG $(locale week-1stday first_weekday)
338 * date -d"$(locale week-1stday) +$(($(locale first_weekday)-1))day" +%w
339 * done
340 *
341 * en_US: 19971130 + 1 -1 = 0 #0 = sunday
342 * ru_RU: 19971130 + 2 -1 = 1
343 * fr_FR: 19971201 + 1 -1 = 1
344 * csb_PL: 19971201 + 2 -1 = 2
345 * POSIX: 19971201 + 7 -1 = 0
346 */
347 {
348 int wfd;
349 union { unsigned int word; char *string; } val;
350 val.string = nl_langinfo(_NL_TIME_WEEK_1STDAY);
351
352 wfd = val.word;
353 wfd = day_in_week(wfd % 100, (wfd / 100) % 100, wfd / (100 * 100));
354 ctl.weekstart = (wfd + *nl_langinfo(_NL_TIME_FIRST_WEEKDAY) - 1) % DAYS_IN_WEEK;
355 }
356 #endif
357
358 while ((ch = getopt_long(argc, argv, "13mjsywVh", longopts, NULL)) != -1)
359 switch(ch) {
360 case '1':
361 ctl.num_months = 1; /* default */
362 break;
363 case '3':
364 ctl.num_months = 3;
365 break;
366 case 's':
367 ctl.weekstart = SUNDAY; /* default */
368 break;
369 case 'm':
370 ctl.weekstart = MONDAY;
371 break;
372 case 'j':
373 ctl.julian = 1;
374 ctl.day_width = DAY_LEN + 1;
375 break;
376 case 'y':
377 ctl.yflag = 1;
378 break;
379 case 'w':
380 if (optarg) {
381 ctl.req.week = strtos32_or_err(optarg,
382 _("invalid week argument"));
383 if (ctl.req.week < 1 || 53 < ctl.req.week)
384 errx(EXIT_FAILURE,_("illegal week value: use 1-53"));
385 }
386 ctl.weektype = WEEK_NUM_US; /* default per weekstart */
387 break;
388 case OPT_COLOR:
389 ctl.colormode = UL_COLORMODE_AUTO;
390 if (optarg)
391 ctl.colormode = colormode_or_err(optarg,
392 _("unsupported color mode"));
393 break;
394 case 'V':
395 printf(UTIL_LINUX_VERSION);
396 return EXIT_SUCCESS;
397 case 'h':
398 usage(stdout);
399 case '?':
400 default:
401 usage(stderr);
402 }
403 argc -= optind;
404 argv += optind;
405
406 if (ctl.weektype) {
407 ctl.weektype = ctl.req.week & WEEK_NUM_MASK;
408 ctl.weektype |= (ctl.weekstart == MONDAY ? WEEK_NUM_ISO : WEEK_NUM_US);
409 ctl.week_width = (ctl.day_width * DAYS_IN_WEEK) + WNUM_LEN;
410 } else
411 ctl.week_width = ctl.day_width * DAYS_IN_WEEK;
412
413 time(&now);
414 local_time = localtime(&now);
415
416 switch(argc) {
417 case 3:
418 ctl.req.day = strtos32_or_err(*argv++, _("illegal day value"));
419 if (ctl.req.day < 1 || DAYS_IN_MONTH < ctl.req.day)
420 errx(EXIT_FAILURE, _("illegal day value: use 1-%d"), DAYS_IN_MONTH);
421 /* FALLTHROUGH */
422 case 2:
423 ctl.req.month = strtos32_or_err(*argv++, _("illegal month value: use 1-12"));
424 if (ctl.req.month < 1 || MONTHS_IN_YEAR < ctl.req.month)
425 errx(EXIT_FAILURE, _("illegal month value: use 1-12"));
426 /* FALLTHROUGH */
427 case 1:
428 ctl.req.year = strtos32_or_err(*argv++, _("illegal year value"));
429 if (ctl.req.year < SMALLEST_YEAR)
430 errx(EXIT_FAILURE, _("illegal year value: use positive integer"));
431 if (ctl.req.year == INT32_MAX)
432 errx(EXIT_FAILURE, _("illegal year value"));
433 if (ctl.req.day) {
434 int dm = days_in_month[leap_year(ctl.req.year)][ctl.req.month];
435 if (ctl.req.day > dm)
436 errx(EXIT_FAILURE, _("illegal day value: use 1-%d"), dm);
437 ctl.req.day = day_in_year(ctl.req.day, ctl.req.month, ctl.req.year);
438 } else if ((int32_t) (local_time->tm_year + 1900) == ctl.req.year) {
439 ctl.req.day = local_time->tm_yday + 1;
440 }
441 if (!ctl.req.month && !ctl.req.week) {
442 ctl.req.month = local_time->tm_mon + 1;
443 ctl.yflag = 1;
444 }
445 break;
446 case 0:
447 ctl.req.day = local_time->tm_yday + 1;
448 ctl.req.year = local_time->tm_year + 1900;
449 ctl.req.month = local_time->tm_mon + 1;
450 break;
451 default:
452 usage(stderr);
453 }
454
455 if (0 < ctl.req.week) {
456 int yday = week_to_day(&ctl);
457 int leap = leap_year(ctl.req.year);
458 int m = 1;
459
460 if (yday < 1)
461 errx(EXIT_FAILURE, _("illegal week value: year %d "
462 "doesn't have week %d"),
463 ctl.req.year, ctl.req.week);
464 while (m <= 12 && yday > days_in_month[leap][m])
465 yday -= days_in_month[leap][m++];
466 if (m > 12) {
467 /* In some years (e.g. 2010 in ISO mode) it's possible
468 * to have a remnant of week 53 starting the year yet
469 * the year in question ends during 52, in this case
470 * we're assuming that early remnant is being referred
471 * to if 53 is given as argument. */
472 if (ctl.req.week != week_number(31, 12, ctl.req.year - 1, &ctl))
473 errx(EXIT_FAILURE,
474 _("illegal week value: year %d "
475 "doesn't have week %d"),
476 ctl.req.year, ctl.req.week);
477 }
478 if (!ctl.req.month)
479 ctl.req.month = 12 < m ? 1 : m;
480 }
481
482 headers_init(&ctl);
483
484 if (!colors_init(ctl.colormode, "cal")) {
485 ctl.req.day = 0;
486 ctl.weektype &= ~WEEK_NUM_MASK;
487 }
488
489 if (ctl.yflag) {
490 if (ctl.julian)
491 ctl.num_months = MONTH_COLS - 1;
492 else
493 ctl.num_months = MONTH_COLS;
494 ctl.gutter_width = 3;
495 yearly(&ctl);
496 } else if (ctl.num_months == 1)
497 monthly(&ctl);
498 else if (ctl.num_months == 3)
499 monthly3(&ctl);
500
501 return EXIT_SUCCESS;
502 }
503
504 /* leap year -- account for gregorian reformation in 1752 */
505 static int leap_year(int32_t year)
506 {
507 if (year <= REFORMATION_YEAR)
508 return !(year % 4);
509 else
510 return ( !(year % 4) && (year % 100) ) || !(year % 400);
511 }
512
513 static void headers_init(struct cal_control *ctl)
514 {
515 size_t i, wd;
516 char *cur_dh = day_headings;
517 char tmp[FMT_ST_CHARS];
518 size_t year_len;
519
520 year_len = snprintf(tmp, sizeof(tmp), "%d", ctl->req.year);
521
522 for (i = 0; i < DAYS_IN_WEEK; i++) {
523 size_t space_left;
524 wd = (i + ctl->weekstart) % DAYS_IN_WEEK;
525
526 if (i)
527 strcat(cur_dh++, " ");
528 space_left = sizeof(day_headings) - (cur_dh - day_headings);
529
530 if (space_left <= (ctl->day_width - 1))
531 break;
532 cur_dh += center_str(nl_langinfo(ABDAY_1 + wd), cur_dh,
533 space_left, ctl->day_width - 1);
534 }
535
536 for (i = 0; i < MONTHS_IN_YEAR; i++) {
537 ctl->full_month[i] = nl_langinfo(MON_1 + i);
538 /* The +1 after year_len is space in between month and year. */
539 if (ctl->week_width < strlen(ctl->full_month[i]) + year_len + 1)
540 ctl->header_hint = 1;
541 }
542 }
543
544 static void set_consecutive_months(struct cal_month *month, int m, int32_t y)
545 {
546 struct cal_month *i;
547 for (i = month; i; i = i->next) {
548 i->month = m++;
549 i->year = y;
550 if (MONTHS_IN_YEAR < m) {
551 m = 1;
552 y++;
553 }
554 }
555 }
556
557 static void cal_fill_month(struct cal_month *month, const struct cal_control *ctl)
558 {
559 int first_week_day = day_in_week(1, month->month, month->year);
560 int month_days;
561 int i, j, weeklines = 0;
562
563 if (ctl->julian)
564 j = day_in_year(1, month->month, month->year);
565 else
566 j = 1;
567 month_days = j + days_in_month[leap_year(month->year)][month->month];
568
569 /* True when Sunday is not first day in the output week. */
570 if (ctl->weekstart) {
571 first_week_day -= ctl->weekstart;
572 if (first_week_day < 0)
573 first_week_day = DAYS_IN_WEEK - ctl->weekstart;
574 month_days += ctl->weekstart - 1;
575 }
576
577 /* Fill day array. */
578 for (i = 0; i < MAXDAYS; i++) {
579 if (0 < first_week_day) {
580 month->days[i] = SPACE;
581 first_week_day--;
582 continue;
583 }
584 if (j < month_days) {
585 if (month->year == 1752 && month->month == 9 && (j == 3 || j == 247))
586 j += NUMBER_MISSING_DAYS;
587 month->days[i] = j;
588 j++;
589 continue;
590 }
591 month->days[i] = SPACE;
592 weeklines++;
593 }
594
595 /* Add week numbers */
596 if (ctl->weektype) {
597 int weeknum = week_number(1, month->month, month->year, ctl);
598 weeklines = MAXDAYS / DAYS_IN_WEEK - weeklines / DAYS_IN_WEEK;
599 for (i = 0; i < MAXDAYS / DAYS_IN_WEEK; i++) {
600 if (0 < weeklines)
601 month->weeks[i] = weeknum++;
602 else
603 month->weeks[i] = SPACE;
604 weeklines--;
605 if (52 < weeknum && i == 0)
606 weeknum = week_number(month->days[DAYS_IN_WEEK * (i + 1)], 1, month->year, ctl);
607 else if (52 < weeknum)
608 weeknum = week_number(31, 12, month->year, ctl);
609 }
610 }
611 }
612
613 static void cal_output_header(struct cal_month *month, const struct cal_control *ctl)
614 {
615 char out[FMT_ST_CHARS];
616 struct cal_month *i;
617
618 if (ctl->header_hint || ctl->yflag) {
619 for (i = month; i; i = i->next) {
620 sprintf(out, _("%s"), ctl->full_month[i->month - 1]);
621 center(out, ctl->week_width - 1, i->next == NULL ? 0 : ctl->gutter_width);
622 }
623 if (!ctl->yflag) {
624 my_putstring("\n");
625 for (i = month; i; i = i->next) {
626 sprintf(out, _("%d"), i->year);
627 center(out, ctl->week_width - 1, i->next == NULL ? 0 : ctl->gutter_width);
628 }
629 }
630 } else {
631 for (i = month; i; i = i->next) {
632 sprintf(out, _("%s %d"), ctl->full_month[i->month - 1], i->year);
633 center(out, ctl->week_width - 1, i->next == NULL ? 0 : ctl->gutter_width);
634 }
635 }
636 my_putstring("\n");
637 for (i = month; i; i = i->next) {
638 if (ctl->weektype) {
639 if (ctl->julian)
640 sprintf(out, "%*s%s", (int)ctl->day_width - 1, "", day_headings);
641 else
642 sprintf(out, "%*s%s", (int)ctl->day_width, "", day_headings);
643 my_putstring(out);
644 } else
645 my_putstring(day_headings);
646 if (i->next != NULL) {
647 sprintf(out, "%*s", ctl->gutter_width, "");
648 my_putstring(out);
649 }
650 }
651 my_putstring("\n");
652 }
653
654 static void cal_output_months(struct cal_month *month, const struct cal_control *ctl)
655 {
656 char out[FMT_ST_CHARS];
657 int reqday, week_line, d;
658 int skip;
659 struct cal_month *i;
660
661 for (week_line = 0; week_line < MAXDAYS / DAYS_IN_WEEK; week_line++) {
662 for (i = month; i; i = i->next) {
663 /* Determine the day that should be highlighted. */
664 reqday = 0;
665 if (i->month == ctl->req.month && i->year == ctl->req.year) {
666 if (ctl->julian)
667 reqday = ctl->req.day;
668 else
669 reqday =
670 ctl->req.day + 1 - day_in_year(1, i->month,
671 i->year);
672 }
673
674 if (ctl->weektype) {
675 if (0 < i->weeks[week_line]) {
676 if ((ctl->weektype & WEEK_NUM_MASK) ==
677 i->weeks[week_line])
678 sprintf(out, "%s%2d%s", Senter, i->weeks[week_line],
679 Sexit);
680 else
681 sprintf(out, "%2d", i->weeks[week_line]);
682 } else
683 sprintf(out, "%2s", "");
684 my_putstring(out);
685 skip = ctl->day_width;
686 } else
687 /* First day of the week is one char narrower than the other days,
688 * unless week number is printed. */
689 skip = ctl->day_width - 1;
690
691 for (d = DAYS_IN_WEEK * week_line;
692 d < DAYS_IN_WEEK * week_line + DAYS_IN_WEEK; d++) {
693 if (0 < i->days[d]) {
694 if (reqday == i->days[d])
695 sprintf(out, "%*s%s%*d%s", skip - (ctl->julian ? 3 : 2),
696 "", Senter, (ctl->julian ? 3 : 2),
697 i->days[d], Sexit);
698 else
699 sprintf(out, "%*d", skip, i->days[d]);
700 } else
701 sprintf(out, "%*s", skip, "");
702 my_putstring(out);
703 if (skip < (int)ctl->day_width)
704 skip++;
705 }
706 if (i->next != NULL) {
707 sprintf(out, "%*s", ctl->gutter_width, "");
708 my_putstring(out);
709 }
710 }
711 if (i == NULL) {
712 sprintf(out, "%*s\n", ctl->gutter_width - (ctl->yflag ? 0 : 1), "");
713 my_putstring(out);
714 }
715 }
716 }
717
718 static void monthly(const struct cal_control *ctl)
719 {
720 struct cal_month month;
721
722 month.month = ctl->req.month;
723 month.year = ctl->req.year;
724 month.next = NULL;
725
726 cal_fill_month(&month, ctl);
727
728 cal_output_header(&month, ctl);
729 cal_output_months(&month, ctl);
730 }
731
732 static void monthly3(const struct cal_control *ctl)
733 {
734 struct cal_month m1, m2, m3, *i;
735 int first_month;
736 int32_t first_year;
737
738 m1.next = &m2;
739 m2.next = &m3;
740 m3.next = NULL;
741
742 if (ctl->req.month == 1) {
743 first_month = MONTHS_IN_YEAR;
744 first_year = ctl->req.year - 1;
745 } else {
746 first_month = ctl->req.month - 1;
747 first_year = ctl->req.year;
748 }
749
750 set_consecutive_months(&m1, first_month, first_year);
751 for (i = &m1; i; i = i->next)
752 cal_fill_month(i, ctl);
753 cal_output_header(&m1, ctl);
754 cal_output_months(&m1, ctl);
755 }
756
757 static void yearly(const struct cal_control *ctl)
758 {
759 struct cal_month m1, m2, m3, *i;
760 int month;
761 char out[FMT_ST_CHARS];
762 int year_width = 0;
763
764 m1.next = &m2;
765 if (ctl->julian)
766 m2.next = NULL;
767 else {
768 m2.next = &m3;
769 m3.next = NULL;
770 }
771
772 /* year header */
773 for (i = &m1; i; i = i->next)
774 year_width += ctl->week_width + 1;
775 if (ctl->julian)
776 year_width--;
777 sprintf(out, "%d", ctl->req.year);
778 center(out, year_width, 0);
779 my_putstring("\n\n");
780
781 for (month = 1; month < MONTHS_IN_YEAR; month += ctl->julian ? 2 : 3) {
782 set_consecutive_months(&m1, month, ctl->req.year);
783 for (i = &m1; i; i = i->next)
784 cal_fill_month(i, ctl);
785 cal_output_header(&m1, ctl);
786 cal_output_months(&m1, ctl);
787 }
788 /* Is empty line at the end year output really needed? */
789 my_putstring("\n");
790 }
791
792 /*
793 * day_in_year --
794 * return the 1 based day number within the year
795 */
796 static int day_in_year(int day, int month, int32_t year)
797 {
798 int i, leap;
799
800 leap = leap_year(year);
801 for (i = 1; i < month; i++)
802 day += days_in_month[leap][i];
803 return day;
804 }
805
806 /*
807 * day_in_week
808 * return the 0 based day number for any date from 1 Jan. 1 to
809 * 31 Dec. 9999. Assumes the Gregorian reformation eliminates
810 * 3 Sep. 1752 through 13 Sep. 1752, and returns invalid weekday
811 * during the period of 11 days.
812 */
813 static int day_in_week(int day, int month, int32_t year)
814 {
815 static const int reform[] = {
816 SUNDAY, WEDNESDAY, TUESDAY, FRIDAY, SUNDAY, WEDNESDAY,
817 FRIDAY, MONDAY, THURSDAY, SATURDAY, TUESDAY, THURSDAY
818 };
819 static const int old[] = {
820 FRIDAY, MONDAY, SUNDAY, WEDNESDAY, FRIDAY, MONDAY,
821 WEDNESDAY, SATURDAY, TUESDAY, THURSDAY, SUNDAY, TUESDAY
822 };
823 if (year != 1753)
824 year -= month < 3;
825 else
826 year -= (month < 3) + 14;
827 if (REFORMATION_YEAR < year
828 || (year == REFORMATION_YEAR && 9 < month)
829 || (year == REFORMATION_YEAR && month == 9 && 13 < day)) {
830 int64_t long_year = year;
831 return (long_year + (year / 4) - (year / 100) + (year / 400) + reform[month - 1] +
832 day) % 7;
833 }
834 if (year < REFORMATION_YEAR
835 || (year == REFORMATION_YEAR && month < 9)
836 || (year == REFORMATION_YEAR && month == 9 && day < 3))
837 return (year + year / 4 + old[month - 1] + day) % 7;
838 return NONEDAY;
839 }
840
841 /*
842 * week_number
843 * return the week number of a given date, 1..53.
844 * Supports ISO-8601 and North American modes.
845 * Day may be given as Julian day of the year mode, in which
846 * case the month is disregarded entirely.
847 */
848 static int week_number(int day, int month, int32_t year, const struct cal_control *ctl)
849 {
850 int fday = 0, yday;
851 int wday = day_in_week(1, 1, year);
852
853 if (ctl->weektype & WEEK_NUM_ISO)
854 fday = wday + (wday >= FRIDAY ? -2 : 5);
855 else
856 /* WEEK_NUM_US
857 * - according to gcal, the first Sun is in the first week
858 * - according to wikipedia, the first Sat is in the first week
859 */
860 fday = wday + (wday == SUNDAY ? 6 : -1);
861
862 /* For julian dates the month can be set to 1, the global julian
863 * variable cannot be relied upon here, because we may recurse
864 * internally for 31.12. which would not work. */
865 if (day > 31)
866 month = 1;
867
868 yday = day_in_year(day,month,year);
869 if (year == REFORMATION_YEAR) {
870 if (yday >= YDAY_AFTER_MISSING)
871 fday -= NUMBER_MISSING_DAYS;
872 }
873
874 /* Last year is last year */
875 if (yday + fday < 7)
876 return week_number(31, 12, year - 1, ctl);
877
878 /* Or it could be part of the next year. The reformation year had less
879 * days than 365 making this check invalid, but reformation year ended
880 * on Sunday and in week 51, so it's ok here. */
881 if (ctl->weektype == WEEK_NUM_ISO && yday >= 363
882 && day_in_week(day, month, year) >= MONDAY
883 && day_in_week(day, month, year) <= WEDNESDAY
884 && day_in_week(31, 12, year) >= MONDAY
885 && day_in_week(31, 12, year) <= WEDNESDAY)
886 return week_number(1, 1, year + 1, ctl);
887
888 return (yday + fday) / 7;
889 }
890
891 /*
892 * week_to_day
893 * return the yday of the first day in a given week inside
894 * the given year. This may be something other than Monday
895 * for ISO-8601 modes. For North American numbering this
896 * always returns a Sunday.
897 */
898 static int week_to_day(const struct cal_control *ctl)
899 {
900 int yday, wday;
901
902 wday = day_in_week(1, 1, ctl->req.year);
903 yday = ctl->req.week * 7 - wday;
904
905 if (ctl->weektype & WEEK_NUM_ISO)
906 yday -= (wday >= FRIDAY ? -2 : 5);
907 else
908 yday -= (wday == SUNDAY ? 6 : -1); /* WEEK_NUM_US */
909 if (yday <= 0)
910 return 1;
911
912 return yday;
913 }
914
915 /*
916 * Center string, handling multibyte characters appropriately.
917 * In addition if the string is too large for the width it's truncated.
918 * The number of trailing spaces may be 1 less than the number of leading spaces.
919 */
920 static int center_str(const char* src, char* dest,
921 size_t dest_size, size_t width)
922 {
923 return mbsalign(src, dest, dest_size, &width,
924 MBS_ALIGN_CENTER, MBA_UNIBYTE_FALLBACK);
925 }
926
927 static void center(const char *str, size_t len, int separate)
928 {
929 char lineout[FMT_ST_CHARS];
930
931 center_str(str, lineout, ARRAY_SIZE(lineout), len);
932 my_putstring(lineout);
933
934 if (separate) {
935 snprintf(lineout, sizeof(lineout), "%*s", separate, "");
936 my_putstring(lineout);
937 }
938 }
939
940 static void __attribute__ ((__noreturn__)) usage(FILE * out)
941 {
942 fputs(USAGE_HEADER, out);
943 fprintf(out, _(" %s [options] [[[day] month] year]\n"), program_invocation_short_name);
944
945 fputs(USAGE_SEPARATOR, out);
946 fputs(_("Display a calendar, or some part of it.\n"), out);
947 fputs(_("Without any arguments, display the current month.\n"), out);
948
949 fputs(USAGE_OPTIONS, out);
950 fputs(_(" -1, --one show only a single month (default)\n"), out);
951 fputs(_(" -3, --three show three months spanning the date\n"), out);
952 fputs(_(" -s, --sunday Sunday as first day of week\n"), out);
953 fputs(_(" -m, --monday Monday as first day of week\n"), out);
954 fputs(_(" -j, --julian output Julian dates\n"), out);
955 fputs(_(" -y, --year show the whole year\n"), out);
956 fputs(_(" -w, --week[=<num>] show US or ISO-8601 week numbers\n"), out);
957 fputs(_(" --color[=<when>] colorize messages (auto, always or never)\n"), out);
958 fprintf(out,
959 " %s\n", USAGE_COLORS_DEFAULT);
960
961 fputs(USAGE_SEPARATOR, out);
962 fputs(USAGE_HELP, out);
963 fputs(USAGE_VERSION, out);
964 fprintf(out, USAGE_MAN_TAIL("cal(1)"));
965
966 exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
967 }