]> git.ipfire.org Git - thirdparty/util-linux.git/blob - misc-utils/cal.c
[clang-tidy] do not use else after return
[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 overridable default MONTHS_IN_ROW 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 #include "optutils.h"
77 #include "timeutils.h"
78 #include "ttyutils.h"
79
80 #define DOY_MONTH_WIDTH 27 /* -j month width */
81 #define DOM_MONTH_WIDTH 20 /* month width */
82
83 static int has_term = 0;
84 static const char *Senter = "", *Sexit = ""; /* enter and exit standout mode */
85
86 #if defined(HAVE_LIBNCURSES) || defined(HAVE_LIBNCURSESW)
87 # if defined(HAVE_NCURSESW_TERM_H)
88 # include <ncursesw/term.h>
89 # elif defined(HAVE_NCURSES_TERM_H)
90 # include <ncurses/term.h>
91 # elif defined(HAVE_TERM_H)
92 # include <term.h>
93 # endif
94 #endif
95
96 static int setup_terminal(char *term
97 #if !defined(HAVE_LIBNCURSES) && !defined(HAVE_LIBNCURSESW)
98 __attribute__((__unused__))
99 #endif
100 )
101 {
102 #if defined(HAVE_LIBNCURSES) || defined(HAVE_LIBNCURSESW)
103 int ret;
104
105 if (setupterm(term, STDOUT_FILENO, &ret) != 0 || ret != 1)
106 return -1;
107 #endif
108 return 0;
109 }
110
111 static void my_putstring(const char *s)
112 {
113 #if defined(HAVE_LIBNCURSES) || defined(HAVE_LIBNCURSESW)
114 if (has_term)
115 putp(s);
116 else
117 #endif
118 fputs(s, stdout);
119 }
120
121 static const char *my_tgetstr(char *ss
122 #if !defined(HAVE_LIBNCURSES) && !defined(HAVE_LIBNCURSESW)
123 __attribute__((__unused__))
124 #endif
125 )
126 {
127 const char *ret = NULL;
128
129 #if defined(HAVE_LIBNCURSES) || defined(HAVE_LIBNCURSESW)
130 if (has_term)
131 ret = tigetstr(ss);
132 #endif
133 if (!ret || ret == (char *)-1)
134 return "";
135 return ret;
136 }
137
138 #include "widechar.h"
139
140 enum {
141 GREGORIAN = INT32_MIN,
142 ISO = INT32_MIN,
143 GB1752 = 1752,
144 DEFAULT_REFORM_YEAR = 1752,
145 JULIAN = INT32_MAX
146 };
147
148 enum {
149 SUNDAY = 0,
150 MONDAY,
151 TUESDAY,
152 WEDNESDAY,
153 THURSDAY,
154 FRIDAY,
155 SATURDAY,
156 DAYS_IN_WEEK,
157 NONEDAY
158 };
159
160 enum {
161 JANUARY = 1,
162 FEBRUARY,
163 MARCH,
164 APRIL,
165 MAY,
166 JUNE,
167 JULY,
168 AUGUST,
169 SEPTEMBER,
170 OCTOBER,
171 NOVEMBER,
172 DECEMBER
173 };
174
175 #define REFORMATION_MONTH SEPTEMBER
176 #define NUMBER_MISSING_DAYS 11 /* 11 day correction */
177 #define YDAY_AFTER_MISSING 258 /* 14th in Sep 1752 */
178
179 #define MONTHS_IN_YEAR DECEMBER
180 #define DAYS_IN_MONTH 31
181 #define MAXDAYS 42 /* slots in a month array */
182 #define SPACE -1 /* used in day array */
183
184 #define SMALLEST_YEAR 1
185
186 #define DAY_LEN 3 /* 3 spaces per day */
187 #define WEEK_LEN (DAYS_IN_WEEK * DAY_LEN)
188 #define MONTHS_IN_YEAR_ROW 3 /* month columns in year view */
189 #define WNUM_LEN 3
190
191 #define FMT_ST_CHARS 300 /* 90 suffices in most locales */
192
193 static const int days_in_month[2][13] = {
194 {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
195 {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
196 };
197
198 enum {
199 WEEK_NUM_DISABLED = 0,
200 WEEK_NUM_MASK=0xff,
201 WEEK_NUM_ISO=0x100,
202 WEEK_NUM_US=0x200,
203 };
204
205 /* utf-8 can have up to 6 bytes per char; and an extra byte for ending \0 */
206 static char day_headings[(WEEK_LEN + 1) * 6 + 1];
207
208 struct cal_request {
209 int day;
210 int month;
211 int32_t year;
212 int week;
213 int start_month;
214 };
215
216 struct cal_control {
217 const char *full_month[MONTHS_IN_YEAR]; /* month names */
218 const char *abbr_month[MONTHS_IN_YEAR]; /* abbreviated month names */
219
220 int reform_year; /* Gregorian reform year */
221 int colormode; /* day and week number highlight */
222 int num_months; /* number of requested months */
223 int span_months; /* span the date */
224 int months_in_row; /* number of months horizontally in print out */
225 int weekstart; /* day the week starts, often Sun or Mon */
226 int weektype; /* WEEK_TYPE_{NONE,ISO,US} */
227 size_t day_width; /* day width in characters in printout */
228 size_t week_width; /* 7 * day_width + possible week num */
229 int gutter_width; /* spaces in between horizontal month outputs */
230 struct cal_request req; /* the times user is interested */
231 unsigned int julian:1, /* julian output */
232 header_year:1, /* print year number */
233 header_hint:1; /* does month name + year need two lines to fit */
234 };
235
236 struct cal_month {
237 int days[MAXDAYS]; /* the day numbers, or SPACE */
238 int weeks[MAXDAYS / DAYS_IN_WEEK];
239 int month;
240 int32_t year;
241 struct cal_month *next;
242 };
243
244 /* function prototypes */
245 static int leap_year(const struct cal_control *ctl, int32_t year);
246 static int monthname_to_number(struct cal_control *ctl, const char *name);
247 static void headers_init(struct cal_control *ctl);
248 static void cal_fill_month(struct cal_month *month, const struct cal_control *ctl);
249 static void cal_output_header(struct cal_month *month, const struct cal_control *ctl);
250 static void cal_output_months(struct cal_month *month, const struct cal_control *ctl);
251 static void monthly(const struct cal_control *ctl);
252 static void yearly(const struct cal_control *ctl);
253 static int day_in_year(const struct cal_control *ctl, int day,
254 int month, int32_t year);
255 static int day_in_week(const struct cal_control *ctl, int day,
256 int month, int32_t year);
257 static int week_number(int day, int month, int32_t year, const struct cal_control *ctl);
258 static int week_to_day(const struct cal_control *ctl);
259 static int center_str(const char *src, char *dest, size_t dest_size, size_t width);
260 static void center(const char *str, size_t len, int separate);
261 static int parse_reform_year(const char *reform_year);
262 static void __attribute__((__noreturn__)) usage(void);
263
264 #ifdef TEST_CAL
265 static time_t cal_time(time_t *t)
266 {
267 char *str = getenv("CAL_TEST_TIME");
268
269 if (str) {
270 uint64_t x = strtou64_or_err(str, "failed to parse CAL_TEST_TIME");
271
272 *t = x;
273 return *t;
274 }
275
276 return time(t);
277 }
278 #else
279 # define cal_time(t) time(t)
280 #endif
281
282 int main(int argc, char **argv)
283 {
284 struct tm local_time;
285 char *term;
286 time_t now;
287 int ch = 0, yflag = 0, Yflag = 0;
288
289 static struct cal_control ctl = {
290 .reform_year = DEFAULT_REFORM_YEAR,
291 .weekstart = SUNDAY,
292 .span_months = 0,
293 .colormode = UL_COLORMODE_UNDEF,
294 .weektype = WEEK_NUM_DISABLED,
295 .day_width = DAY_LEN,
296 .gutter_width = 2,
297 .req.day = 0,
298 .req.month = 0
299 };
300
301 enum {
302 OPT_COLOR = CHAR_MAX + 1,
303 OPT_ISO,
304 OPT_REFORM
305 };
306
307 static const struct option longopts[] = {
308 {"one", no_argument, NULL, '1'},
309 {"three", no_argument, NULL, '3'},
310 {"sunday", no_argument, NULL, 's'},
311 {"monday", no_argument, NULL, 'm'},
312 {"julian", no_argument, NULL, 'j'},
313 {"months", required_argument, NULL, 'n'},
314 {"span", no_argument, NULL, 'S'},
315 {"year", no_argument, NULL, 'y'},
316 {"week", optional_argument, NULL, 'w'},
317 {"color", optional_argument, NULL, OPT_COLOR},
318 {"reform", required_argument, NULL, OPT_REFORM},
319 {"iso", no_argument, NULL, OPT_ISO},
320 {"version", no_argument, NULL, 'V'},
321 {"twelve", no_argument, NULL, 'Y'},
322 {"help", no_argument, NULL, 'h'},
323 {NULL, 0, NULL, 0}
324 };
325
326 static const ul_excl_t excl[] = { /* rows and cols in ASCII order */
327 { 'Y','n','y' },
328 { 0 }
329 };
330 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
331
332 setlocale(LC_ALL, "");
333 bindtextdomain(PACKAGE, LOCALEDIR);
334 textdomain(PACKAGE);
335 close_stdout_atexit();
336
337 term = getenv("TERM");
338 if (term) {
339 has_term = setup_terminal(term) == 0;
340 if (has_term) {
341 Senter = my_tgetstr("smso");
342 Sexit = my_tgetstr("rmso");
343 }
344 }
345
346 /*
347 * The traditional Unix cal utility starts the week at Sunday,
348 * while ISO 8601 starts at Monday. We read the start day from
349 * the locale database, which can be overridden with the
350 * -s (Sunday) or -m (Monday) options.
351 */
352 #if HAVE_DECL__NL_TIME_WEEK_1STDAY
353 /*
354 * You need to use 2 locale variables to get the first day of the week.
355 * This is needed to support first_weekday=2 and first_workday=1 for
356 * the rare case where working days span across 2 weeks.
357 * This shell script shows the combinations and calculations involved:
358 *
359 * for LANG in en_US ru_RU fr_FR csb_PL POSIX; do
360 * printf "%s:\t%s + %s -1 = " $LANG $(locale week-1stday first_weekday)
361 * date -d"$(locale week-1stday) +$(($(locale first_weekday)-1))day" +%w
362 * done
363 *
364 * en_US: 19971130 + 1 -1 = 0 #0 = sunday
365 * ru_RU: 19971130 + 2 -1 = 1
366 * fr_FR: 19971201 + 1 -1 = 1
367 * csb_PL: 19971201 + 2 -1 = 2
368 * POSIX: 19971201 + 7 -1 = 0
369 */
370 {
371 int wfd;
372 union { unsigned int word; char *string; } val;
373 val.string = nl_langinfo(_NL_TIME_WEEK_1STDAY);
374
375 wfd = val.word;
376 wfd = day_in_week(&ctl, wfd % 100, (wfd / 100) % 100,
377 wfd / (100 * 100));
378 ctl.weekstart = (wfd + *nl_langinfo(_NL_TIME_FIRST_WEEKDAY) - 1) % DAYS_IN_WEEK;
379 }
380 #endif
381 while ((ch = getopt_long(argc, argv, "13mjn:sSywYVh", longopts, NULL)) != -1) {
382
383 err_exclusive_options(ch, longopts, excl, excl_st);
384
385 switch(ch) {
386 case '1':
387 ctl.num_months = 1;
388 break;
389 case '3':
390 ctl.num_months = 3;
391 ctl.span_months = 1;
392 break;
393 case 's':
394 ctl.weekstart = SUNDAY; /* default */
395 break;
396 case 'm':
397 ctl.weekstart = MONDAY;
398 break;
399 case 'j':
400 ctl.julian = 1;
401 ctl.day_width = DAY_LEN + 1;
402 break;
403 case 'y':
404 yflag = 1;
405 break;
406 case 'Y':
407 Yflag = 1;
408 break;
409 case 'n':
410 ctl.num_months = strtou32_or_err(optarg,
411 _("invalid month argument"));
412 break;
413 case 'S':
414 ctl.span_months = 1;
415 break;
416 case 'w':
417 if (optarg) {
418 ctl.req.week = strtos32_or_err(optarg,
419 _("invalid week argument"));
420 if (ctl.req.week < 1 || 54 < ctl.req.week)
421 errx(EXIT_FAILURE,_("illegal week value: use 1-54"));
422 }
423 ctl.weektype = WEEK_NUM_US; /* default per weekstart */
424 break;
425 case OPT_COLOR:
426 ctl.colormode = UL_COLORMODE_AUTO;
427 if (optarg)
428 ctl.colormode = colormode_or_err(optarg,
429 _("unsupported color mode"));
430 break;
431 case OPT_REFORM:
432 ctl.reform_year = parse_reform_year(optarg);
433 break;
434 case OPT_ISO:
435 ctl.reform_year = ISO;
436 break;
437 case 'V':
438 print_version(EXIT_SUCCESS);
439 case 'h':
440 usage();
441 default:
442 errtryhelp(EXIT_FAILURE);
443 }
444 }
445
446 argc -= optind;
447 argv += optind;
448
449 if (ctl.weektype) {
450 ctl.weektype = ctl.req.week & WEEK_NUM_MASK;
451 ctl.weektype |= (ctl.weekstart == MONDAY ? WEEK_NUM_ISO : WEEK_NUM_US);
452 ctl.week_width = (ctl.day_width * DAYS_IN_WEEK) + WNUM_LEN;
453 } else
454 ctl.week_width = ctl.day_width * DAYS_IN_WEEK;
455 /*
456 * The day_width includes the space between days,
457 * as there is no leading space, remove 1
458 * */
459 ctl.week_width -= 1;
460
461 if (argc == 1 && !isdigit_string(*argv)) {
462 usec_t x;
463 /* cal <timestamp> */
464 if (parse_timestamp(*argv, &x) == 0)
465 now = (time_t) (x / 1000000);
466 /* cal <monthname> */
467 else if ((ctl.req.month = monthname_to_number(&ctl, *argv)) > 0)
468 cal_time(&now); /* this year */
469 else
470 errx(EXIT_FAILURE, _("failed to parse timestamp or unknown month name: %s"), *argv);
471 argc = 0;
472 } else
473 cal_time(&now);
474
475 localtime_r(&now, &local_time);
476
477 switch(argc) {
478 case 3:
479 ctl.req.day = strtos32_or_err(*argv++, _("illegal day value"));
480 if (ctl.req.day < 1 || DAYS_IN_MONTH < ctl.req.day)
481 errx(EXIT_FAILURE, _("illegal day value: use 1-%d"), DAYS_IN_MONTH);
482 /* fallthrough */
483 case 2:
484 if (isdigit(**argv))
485 ctl.req.month = strtos32_or_err(*argv++, _("illegal month value: use 1-12"));
486 else {
487 ctl.req.month = monthname_to_number(&ctl, *argv);
488 if (ctl.req.month < 0)
489 errx(EXIT_FAILURE, _("unknown month name: %s"), *argv);
490 argv++;
491 }
492 if (ctl.req.month < 1 || MONTHS_IN_YEAR < ctl.req.month)
493 errx(EXIT_FAILURE, _("illegal month value: use 1-12"));
494 /* fallthrough */
495 case 1:
496 ctl.req.year = strtos32_or_err(*argv++, _("illegal year value"));
497 if (ctl.req.year < SMALLEST_YEAR)
498 errx(EXIT_FAILURE, _("illegal year value: use positive integer"));
499 if (ctl.req.year == JULIAN)
500 errx(EXIT_FAILURE, _("illegal year value"));
501 if (ctl.req.day) {
502 int dm = days_in_month[leap_year(&ctl, ctl.req.year)]
503 [ctl.req.month];
504 if (ctl.req.day > dm)
505 errx(EXIT_FAILURE, _("illegal day value: use 1-%d"), dm);
506 ctl.req.day = day_in_year(&ctl, ctl.req.day,
507 ctl.req.month, ctl.req.year);
508 } else if ((int32_t) (local_time.tm_year + 1900) == ctl.req.year) {
509 ctl.req.day = local_time.tm_yday + 1;
510 }
511 if (!ctl.req.month && !ctl.req.week) {
512 ctl.req.month = local_time.tm_mon + 1;
513 if (!ctl.num_months)
514 yflag = 1;
515 }
516 break;
517 case 0:
518 ctl.req.day = local_time.tm_yday + 1;
519 ctl.req.year = local_time.tm_year + 1900;
520 if (!ctl.req.month)
521 ctl.req.month = local_time.tm_mon + 1;
522 break;
523 default:
524 warnx(_("bad usage"));
525 errtryhelp(EXIT_FAILURE);
526 }
527
528 if (0 < ctl.req.week) {
529 int yday = week_to_day(&ctl);
530 int leap = leap_year(&ctl, ctl.req.year);
531 int m = 1;
532
533 if (yday < 1)
534 errx(EXIT_FAILURE, _("illegal week value: year %d "
535 "doesn't have week %d"),
536 ctl.req.year, ctl.req.week);
537 while (m <= DECEMBER && yday > days_in_month[leap][m])
538 yday -= days_in_month[leap][m++];
539 if (DECEMBER < m && ctl.weektype & WEEK_NUM_ISO) {
540 /* In some years (e.g. 2010 in ISO mode) it's possible
541 * to have a remnant of week 53 starting the year yet
542 * the year in question ends during 52, in this case
543 * we're assuming that early remnant is being referred
544 * to if 53 is given as argument. */
545 if (ctl.req.week != week_number(31, DECEMBER, ctl.req.year - 1, &ctl))
546 errx(EXIT_FAILURE,
547 _("illegal week value: year %d "
548 "doesn't have week %d"),
549 ctl.req.year, ctl.req.week);
550 }
551 if (!ctl.req.month)
552 ctl.req.month = MONTHS_IN_YEAR < m ? 1 : m;
553 }
554
555 headers_init(&ctl);
556
557 if (colors_init(ctl.colormode, "cal") == 0) {
558 /*
559 * If standout mode available (Senter and Sexit are set) and
560 * user or terminal-colors.d do not disable colors than
561 * ignore colors_init().
562 */
563 if (*Senter && *Sexit && colors_mode() != UL_COLORMODE_NEVER) {
564 /* let use standout mode */
565 ;
566 } else {
567 /* disable */
568 Senter = ""; Sexit = "";
569 ctl.req.day = 0;
570 ctl.weektype &= ~WEEK_NUM_MASK;
571 }
572 }
573
574 if (yflag || Yflag) {
575 ctl.gutter_width = 3;
576 if (!ctl.num_months)
577 ctl.num_months = MONTHS_IN_YEAR;
578 if (yflag) {
579 ctl.req.start_month = 1; /* start from Jan */
580 ctl.header_year = 1; /* print year number */
581 }
582 }
583
584 if (ctl.num_months > 1 && ctl.months_in_row == 0) {
585 ctl.months_in_row = MONTHS_IN_YEAR_ROW; /* default */
586
587 if (isatty(STDOUT_FILENO)) {
588 int w, mw, extra, new_n;
589
590 w = get_terminal_width(80);
591 mw = ctl.julian ? DOY_MONTH_WIDTH : DOM_MONTH_WIDTH;
592
593 if (w < mw)
594 w = mw;
595
596 extra = ((w / mw) - 1) * ctl.gutter_width;
597 new_n = (w - extra) / mw;
598
599 if (new_n < MONTHS_IN_YEAR_ROW)
600 ctl.months_in_row = new_n > 0 ? new_n : 1;
601 }
602 } else if (!ctl.months_in_row)
603 ctl.months_in_row = 1;
604
605 if (!ctl.num_months)
606 ctl.num_months = 1; /* display at least one month */
607
608 if (yflag || Yflag)
609 yearly(&ctl);
610 else
611 monthly(&ctl);
612
613 return EXIT_SUCCESS;
614 }
615
616 /* leap year -- account for gregorian reformation in 1752 */
617 static int leap_year(const struct cal_control *ctl, int32_t year)
618 {
619 if (year <= ctl->reform_year)
620 return !(year % 4);
621
622 return ( !(year % 4) && (year % 100) ) || !(year % 400);
623 }
624
625 static void init_monthnames(struct cal_control *ctl)
626 {
627 size_t i;
628
629 if (ctl->full_month[0] != NULL)
630 return; /* already initialized */
631
632 for (i = 0; i < MONTHS_IN_YEAR; i++)
633 ctl->full_month[i] = nl_langinfo(ALTMON_1 + i);
634 }
635
636 static void init_abbr_monthnames(struct cal_control *ctl)
637 {
638 size_t i;
639
640 if (ctl->abbr_month[0] != NULL)
641 return; /* already initialized */
642
643 for (i = 0; i < MONTHS_IN_YEAR; i++)
644 ctl->abbr_month[i] = nl_langinfo(_NL_ABALTMON_1 + i);
645 }
646
647 static int monthname_to_number(struct cal_control *ctl, const char *name)
648 {
649 size_t i;
650
651 init_monthnames(ctl);
652 for (i = 0; i < MONTHS_IN_YEAR; i++)
653 if (strcasecmp(ctl->full_month[i], name) == 0)
654 return i + 1;
655
656 init_abbr_monthnames(ctl);
657 for (i = 0; i < MONTHS_IN_YEAR; i++)
658 if (strcasecmp(ctl->abbr_month[i], name) == 0)
659 return i + 1;
660
661 return -EINVAL;
662 }
663
664 static void headers_init(struct cal_control *ctl)
665 {
666 size_t i, wd;
667 char *cur_dh = day_headings;
668 char tmp[FMT_ST_CHARS];
669 int year_len;
670
671 year_len = snprintf(tmp, sizeof(tmp), "%04d", ctl->req.year);
672
673 if (year_len < 0 || (size_t)year_len >= sizeof(tmp)) {
674 /* XXX impossible error */
675 return;
676 }
677
678 for (i = 0; i < DAYS_IN_WEEK; i++) {
679 size_t space_left;
680 wd = (i + ctl->weekstart) % DAYS_IN_WEEK;
681
682 if (i)
683 strcat(cur_dh++, " ");
684 space_left = sizeof(day_headings) - (cur_dh - day_headings);
685
686 if (space_left <= (ctl->day_width - 1))
687 break;
688 cur_dh += center_str(nl_langinfo(ABDAY_1 + wd), cur_dh,
689 space_left, ctl->day_width - 1);
690 }
691
692 init_monthnames(ctl);
693
694 for (i = 0; i < MONTHS_IN_YEAR; i++) {
695 /* The +1 after year_len is space in between month and year. */
696 if (ctl->week_width < strlen(ctl->full_month[i]) + year_len)
697 ctl->header_hint = 1;
698 }
699 }
700
701 static void cal_fill_month(struct cal_month *month, const struct cal_control *ctl)
702 {
703 int first_week_day = day_in_week(ctl, 1, month->month, month->year);
704 int month_days;
705 int i, j, weeklines = 0;
706
707 if (ctl->julian)
708 j = day_in_year(ctl, 1, month->month, month->year);
709 else
710 j = 1;
711 month_days = j + days_in_month[leap_year(ctl, month->year)][month->month];
712
713 /* True when Sunday is not first day in the output week. */
714 if (ctl->weekstart) {
715 first_week_day -= ctl->weekstart;
716 if (first_week_day < 0)
717 first_week_day = DAYS_IN_WEEK - ctl->weekstart;
718 month_days += ctl->weekstart - 1;
719 }
720
721 /* Fill day array. */
722 for (i = 0; i < MAXDAYS; i++) {
723 if (0 < first_week_day) {
724 month->days[i] = SPACE;
725 first_week_day--;
726 continue;
727 }
728 if (j < month_days) {
729 if (month->year == ctl->reform_year &&
730 month->month == REFORMATION_MONTH &&
731 (j == 3 || j == 247))
732 j += NUMBER_MISSING_DAYS;
733 month->days[i] = j;
734 j++;
735 continue;
736 }
737 month->days[i] = SPACE;
738 weeklines++;
739 }
740
741 /* Add week numbers */
742 if (ctl->weektype) {
743 int weeknum = week_number(1, month->month, month->year, ctl);
744 weeklines = MAXDAYS / DAYS_IN_WEEK - weeklines / DAYS_IN_WEEK;
745 for (i = 0; i < MAXDAYS / DAYS_IN_WEEK; i++) {
746 if (0 < weeklines) {
747 if (52 < weeknum)
748 weeknum = week_number(month->days[i * DAYS_IN_WEEK], month->month, month->year, ctl);
749 month->weeks[i] = weeknum++;
750 } else
751 month->weeks[i] = SPACE;
752 weeklines--;
753 }
754 }
755 }
756
757 static void cal_output_header(struct cal_month *month, const struct cal_control *ctl)
758 {
759 char out[FMT_ST_CHARS];
760 struct cal_month *i;
761
762 if (ctl->header_hint || ctl->header_year) {
763 for (i = month; i; i = i->next) {
764 snprintf(out, sizeof(out), "%s", ctl->full_month[i->month - 1]);
765 center(out, ctl->week_width, i->next == NULL ? 0 : ctl->gutter_width);
766 }
767 if (!ctl->header_year) {
768 my_putstring("\n");
769 for (i = month; i; i = i->next) {
770 snprintf(out, sizeof(out), "%04d", i->year);
771 center(out, ctl->week_width, i->next == NULL ? 0 : ctl->gutter_width);
772 }
773 }
774 } else {
775 for (i = month; i; i = i->next) {
776 snprintf(out, sizeof(out), "%s %04d", ctl->full_month[i->month - 1], i->year);
777 center(out, ctl->week_width, i->next == NULL ? 0 : ctl->gutter_width);
778 }
779 }
780 my_putstring("\n");
781 for (i = month; i; i = i->next) {
782 if (ctl->weektype) {
783 if (ctl->julian)
784 snprintf(out, sizeof(out), "%*s%s", (int)ctl->day_width - 1, "", day_headings);
785 else
786 snprintf(out, sizeof(out), "%*s%s", (int)ctl->day_width, "", day_headings);
787 my_putstring(out);
788 } else
789 my_putstring(day_headings);
790 if (i->next != NULL) {
791 snprintf(out, sizeof(out), "%*s", ctl->gutter_width, "");
792 my_putstring(out);
793 }
794 }
795 my_putstring("\n");
796 }
797
798 static void cal_output_months(struct cal_month *month, const struct cal_control *ctl)
799 {
800 char out[FMT_ST_CHARS];
801 int reqday, week_line, d;
802 int skip;
803 struct cal_month *i;
804
805 for (week_line = 0; week_line < MAXDAYS / DAYS_IN_WEEK; week_line++) {
806 for (i = month; i; i = i->next) {
807 /* Determine the day that should be highlighted. */
808 reqday = 0;
809 if (i->month == ctl->req.month && i->year == ctl->req.year) {
810 if (ctl->julian)
811 reqday = ctl->req.day;
812 else
813 reqday = ctl->req.day + 1 -
814 day_in_year(ctl, 1, i->month,
815 i->year);
816 }
817
818 if (ctl->weektype) {
819 if (0 < i->weeks[week_line]) {
820 if ((ctl->weektype & WEEK_NUM_MASK) ==
821 i->weeks[week_line])
822 snprintf(out, sizeof(out), "%s%2d%s",
823 Senter, i->weeks[week_line],
824 Sexit);
825 else
826 snprintf(out, sizeof(out), "%2d", i->weeks[week_line]);
827 } else
828 snprintf(out, sizeof(out), "%2s", "");
829 my_putstring(out);
830 skip = ctl->day_width;
831 } else
832 /* First day of the week is one char narrower than the other days,
833 * unless week number is printed. */
834 skip = ctl->day_width - 1;
835
836 for (d = DAYS_IN_WEEK * week_line;
837 d < DAYS_IN_WEEK * week_line + DAYS_IN_WEEK; d++) {
838 if (0 < i->days[d]) {
839 if (reqday == i->days[d])
840 snprintf(out, sizeof(out), "%*s%s%*d%s",
841 skip - (ctl->julian ? 3 : 2),
842 "", Senter, (ctl->julian ? 3 : 2),
843 i->days[d], Sexit);
844 else
845 snprintf(out, sizeof(out), "%*d", skip, i->days[d]);
846 } else
847 snprintf(out, sizeof(out), "%*s", skip, "");
848 my_putstring(out);
849 if (skip < (int)ctl->day_width)
850 skip++;
851 }
852 if (i->next != NULL) {
853 snprintf(out, sizeof(out), "%*s", ctl->gutter_width, "");
854 my_putstring(out);
855 }
856 }
857 if (i == NULL)
858 my_putstring("\n");
859 }
860 }
861
862 static void monthly(const struct cal_control *ctl)
863 {
864 struct cal_month m1,m2,m3, *m;
865 int i, rows, month = ctl->req.start_month ? ctl->req.start_month : ctl->req.month;
866 int32_t year = ctl->req.year;
867
868 /* cal -3, cal -Y --span, etc. */
869 if (ctl->span_months) {
870 int new_month = month - ctl->num_months / 2;
871 if (new_month < 1) {
872 new_month *= -1;
873 year -= (new_month / MONTHS_IN_YEAR) + 1;
874
875 if (new_month > MONTHS_IN_YEAR)
876 new_month %= MONTHS_IN_YEAR;
877 month = MONTHS_IN_YEAR - new_month;
878 } else
879 month = new_month;
880 }
881
882 m1.next = (ctl->months_in_row > 1) ? &m2 : NULL;
883 m2.next = (ctl->months_in_row > 2) ? &m3 : NULL;
884 m3.next = NULL;
885
886 rows = (ctl->num_months - 1) / ctl->months_in_row;
887 for (i = 0; i < rows + 1 ; i++){
888 if (i == rows){
889 switch (ctl->num_months % ctl->months_in_row){
890 case 1:
891 m1.next = NULL;
892 /* fallthrough */
893 case 2:
894 m2.next = NULL;
895 /* fallthrough */
896 }
897 }
898 for (m = &m1; m; m = m->next){
899 m->month = month++;
900 m->year = year;
901 if (MONTHS_IN_YEAR < month) {
902 year++;
903 month = 1;
904 }
905 cal_fill_month(m, ctl);
906 }
907 cal_output_header(&m1, ctl);
908 cal_output_months(&m1, ctl);
909 }
910 }
911
912 static void yearly(const struct cal_control *ctl)
913 {
914 char out[FMT_ST_CHARS];
915 int year_width;
916
917 year_width = ctl->months_in_row * (ctl->week_width) +
918 (ctl->months_in_row - 1) * ctl->gutter_width;
919
920 if (ctl->header_year) {
921 snprintf(out, sizeof(out), "%04d", ctl->req.year);
922 center(out, year_width, 0);
923 my_putstring("\n\n");
924 }
925 monthly(ctl);
926 }
927
928 /*
929 * day_in_year --
930 * return the 1 based day number within the year
931 */
932 static int day_in_year(const struct cal_control *ctl,
933 int day, int month, int32_t year)
934 {
935 int i, leap;
936
937 leap = leap_year(ctl, year);
938 for (i = 1; i < month; i++)
939 day += days_in_month[leap][i];
940 return day;
941 }
942
943 /*
944 * day_in_week
945 * return the 0 based day number for any date from 1 Jan. 1 to
946 * 31 Dec. 9999. Assumes the Gregorian reformation eliminates
947 * 3 Sep. 1752 through 13 Sep. 1752, and returns invalid weekday
948 * during the period of 11 days.
949 */
950 static int day_in_week(const struct cal_control *ctl, int day,
951 int month, int32_t year)
952 {
953 /*
954 * The magic constants in the reform[] array are, in a simplified
955 * sense, the remaining days after slicing into one week periods the total
956 * days from the beginning of the year to the target month. That is,
957 * weeks + reform[] days gets us to the target month. The exception is,
958 * that for the months past February 'DOY - 1' must be used.
959 *
960 * DoY (Day of Year): total days to the target month
961 *
962 * Month 1 2 3 4 5 6 7 8 9 10 11 12
963 * DoY 0 31 59 90 120 151 181 212 243 273 304 334
964 * DoY % 7 0 3
965 * DoY - 1 % 7 - -- 2 5 0 3 5 1 4 6 2 4
966 * reform[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
967 *
968 * Note: these calculations are for non leap years.
969 */
970 static const int reform[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
971 static const int old[] = { 5, 1, 0, 3, 5, 1, 3, 6, 2, 4, 0, 2 };
972
973 if (year != ctl->reform_year + 1)
974 year -= month < MARCH;
975 else
976 year -= (month < MARCH) + 14;
977 if (ctl->reform_year < year
978 || (year == ctl->reform_year && REFORMATION_MONTH < month)
979 || (year == ctl->reform_year
980 && month == REFORMATION_MONTH && 13 < day)) {
981 return ((int64_t) year + (year / 4)
982 - (year / 100) + (year / 400)
983 + reform[month - 1] + day) % DAYS_IN_WEEK;
984 }
985 if (year < ctl->reform_year
986 || (year == ctl->reform_year && month < REFORMATION_MONTH)
987 || (year == ctl->reform_year && month == REFORMATION_MONTH && day < 3))
988 return ((int64_t) year + year / 4 + old[month - 1] + day)
989 % DAYS_IN_WEEK;
990 return NONEDAY;
991 }
992
993 /*
994 * week_number
995 * return the week number of a given date, 1..54.
996 * Supports ISO-8601 and North American modes.
997 * Day may be given as Julian day of the year mode, in which
998 * case the month is disregarded entirely.
999 */
1000 static int week_number(int day, int month, int32_t year, const struct cal_control *ctl)
1001 {
1002 int fday = 0, yday;
1003 const int wday = day_in_week(ctl, 1, JANUARY, year);
1004
1005 if (ctl->weektype & WEEK_NUM_ISO)
1006 fday = wday + (wday >= FRIDAY ? -2 : 5);
1007 else {
1008 /* WEEK_NUM_US: Jan 1 is always First week, that may
1009 * begin previous year. That means there is very seldom
1010 * more than 52 weeks, */
1011 fday = wday + 6;
1012 }
1013 /* For julian dates the month can be set to 1, the global julian
1014 * variable cannot be relied upon here, because we may recurse
1015 * internally for 31.12. which would not work. */
1016 if (day > DAYS_IN_MONTH)
1017 month = JANUARY;
1018
1019 yday = day_in_year(ctl, day, month, year);
1020 if (year == ctl->reform_year && yday >= YDAY_AFTER_MISSING)
1021 fday -= NUMBER_MISSING_DAYS;
1022
1023 /* Last year is last year */
1024 if (yday + fday < DAYS_IN_WEEK)
1025 return week_number(31, DECEMBER, year - 1, ctl);
1026
1027 /* Or it could be part of the next year. The reformation year had less
1028 * days than 365 making this check invalid, but reformation year ended
1029 * on Sunday and in week 51, so it's ok here. */
1030 if (ctl->weektype == WEEK_NUM_ISO && yday >= 363
1031 && day_in_week(ctl, day, month, year) >= MONDAY
1032 && day_in_week(ctl, day, month, year) <= WEDNESDAY
1033 && day_in_week(ctl, 31, DECEMBER, year) >= MONDAY
1034 && day_in_week(ctl, 31, DECEMBER, year) <= WEDNESDAY)
1035 return week_number(1, JANUARY, year + 1, ctl);
1036
1037 return (yday + fday) / DAYS_IN_WEEK;
1038 }
1039
1040 /*
1041 * week_to_day
1042 * return the yday of the first day in a given week inside
1043 * the given year. This may be something other than Monday
1044 * for ISO-8601 modes. For North American numbering this
1045 * always returns a Sunday.
1046 */
1047 static int week_to_day(const struct cal_control *ctl)
1048 {
1049 int yday, wday;
1050
1051 wday = day_in_week(ctl, 1, JANUARY, ctl->req.year);
1052 yday = ctl->req.week * DAYS_IN_WEEK - wday;
1053
1054 if (ctl->req.year == ctl->reform_year && yday >= YDAY_AFTER_MISSING)
1055 yday += NUMBER_MISSING_DAYS;
1056
1057 if (ctl->weektype & WEEK_NUM_ISO)
1058 yday -= (wday >= FRIDAY ? -2 : 5);
1059 else
1060 yday -= 6; /* WEEK_NUM_US */
1061 if (yday <= 0)
1062 return 1;
1063
1064 return yday;
1065 }
1066
1067 /*
1068 * Center string, handling multibyte characters appropriately.
1069 * In addition if the string is too large for the width it's truncated.
1070 * The number of trailing spaces may be 1 less than the number of leading spaces.
1071 */
1072 static int center_str(const char* src, char* dest,
1073 size_t dest_size, size_t width)
1074 {
1075 return mbsalign(src, dest, dest_size, &width,
1076 MBS_ALIGN_CENTER, MBA_UNIBYTE_FALLBACK);
1077 }
1078
1079 static void center(const char *str, size_t len, int separate)
1080 {
1081 char lineout[FMT_ST_CHARS];
1082
1083 center_str(str, lineout, ARRAY_SIZE(lineout), len);
1084 my_putstring(lineout);
1085
1086 if (separate) {
1087 snprintf(lineout, sizeof(lineout), "%*s", separate, "");
1088 my_putstring(lineout);
1089 }
1090 }
1091
1092 static int parse_reform_year(const char *reform_year)
1093 {
1094 size_t i;
1095
1096 struct reform {
1097 char *name;
1098 int val;
1099 };
1100
1101 struct reform years[] = {
1102 {"gregorian", GREGORIAN},
1103 {"iso", ISO},
1104 {"1752", GB1752},
1105 {"julian", JULIAN},
1106 };
1107
1108 for (i = 0; i < ARRAY_SIZE(years); i++) {
1109 if (strcasecmp(reform_year, years[i].name) == 0) {
1110 return years[i].val;
1111 }
1112 }
1113 errx(EXIT_FAILURE, "invalid --reform value: '%s'", reform_year);
1114 }
1115
1116 static void __attribute__((__noreturn__)) usage(void)
1117 {
1118 FILE *out = stdout;
1119 fputs(USAGE_HEADER, out);
1120 fprintf(out, _(" %s [options] [[[day] month] year]\n"), program_invocation_short_name);
1121 fprintf(out, _(" %s [options] <timestamp|monthname>\n"), program_invocation_short_name);
1122
1123 fputs(USAGE_SEPARATOR, out);
1124 fputs(_("Display a calendar, or some part of it.\n"), out);
1125 fputs(_("Without any arguments, display the current month.\n"), out);
1126
1127 fputs(USAGE_OPTIONS, out);
1128 fputs(_(" -1, --one show only a single month (default)\n"), out);
1129 fputs(_(" -3, --three show three months spanning the date\n"), out);
1130 fputs(_(" -n, --months <num> show num months starting with date's month\n"), out);
1131 fputs(_(" -S, --span span the date when displaying multiple months\n"), out);
1132 fputs(_(" -s, --sunday Sunday as first day of week\n"), out);
1133 fputs(_(" -m, --monday Monday as first day of week\n"), out);
1134 fputs(_(" -j, --julian use day-of-year for all calendars\n"), out);
1135 fputs(_(" --reform <val> Gregorian reform date (1752|gregorian|iso|julian)\n"), out);
1136 fputs(_(" --iso alias for --reform=iso\n"), out);
1137 fputs(_(" -y, --year show the whole year\n"), out);
1138 fputs(_(" -Y, --twelve show the next twelve months\n"), out);
1139 fputs(_(" -w, --week[=<num>] show US or ISO-8601 week numbers\n"), out);
1140 fprintf(out,
1141 _(" --color[=<when>] colorize messages (%s, %s or %s)\n"), "auto", "always", "never");
1142 fprintf(out,
1143 " %s\n", USAGE_COLORS_DEFAULT);
1144
1145 fputs(USAGE_SEPARATOR, out);
1146 printf(USAGE_HELP_OPTIONS(23));
1147 printf(USAGE_MAN_TAIL("cal(1)"));
1148
1149 exit(EXIT_SUCCESS);
1150 }