xref: /netbsd-src/usr.bin/cal/cal.c (revision d710132b4b8ce7f7cccaaf660cb16aa16b4077a0)
1 /*	$NetBSD: cal.c,v 1.15 2003/06/05 00:21:20 atatat Exp $	*/
2 
3 /*
4  * Copyright (c) 1989, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Kim Letkeman.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  */
38 
39 #include <sys/cdefs.h>
40 #ifndef lint
41 __COPYRIGHT("@(#) Copyright (c) 1989, 1993, 1994\n\
42 	The Regents of the University of California.  All rights reserved.\n");
43 #endif /* not lint */
44 
45 #ifndef lint
46 #if 0
47 static char sccsid[] = "@(#)cal.c	8.4 (Berkeley) 4/2/94";
48 #else
49 __RCSID("$NetBSD: cal.c,v 1.15 2003/06/05 00:21:20 atatat Exp $");
50 #endif
51 #endif /* not lint */
52 
53 #include <sys/types.h>
54 
55 #include <ctype.h>
56 #include <err.h>
57 #include <errno.h>
58 #include <limits.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <termcap.h>
63 #include <time.h>
64 #include <tzfile.h>
65 #include <unistd.h>
66 
67 #define	THURSDAY		4		/* for reformation */
68 #define	SATURDAY 		6		/* 1 Jan 1 was a Saturday */
69 
70 #define	FIRST_MISSING_DAY 	639799		/* 3 Sep 1752 */
71 #define	NUMBER_MISSING_DAYS 	11		/* 11 day correction */
72 
73 #define	MAXDAYS			42		/* max slots in a month array */
74 #define	SPACE			-1		/* used in day array */
75 
76 static int days_in_month[2][13] = {
77 	{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
78 	{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
79 };
80 
81 int sep1752[MAXDAYS] = {
82 	SPACE,	SPACE,	1,	2,	14,	15,	16,
83 	17,	18,	19,	20,	21,	22,	23,
84 	24,	25,	26,	27,	28,	29,	30,
85 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
86 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
87 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
88 }, j_sep1752[MAXDAYS] = {
89 	SPACE,	SPACE,	245,	246,	258,	259,	260,
90 	261,	262,	263,	264,	265,	266,	267,
91 	268,	269,	270,	271,	272,	273,	274,
92 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
93 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
94 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
95 }, empty[MAXDAYS] = {
96 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
97 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
98 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
99 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
100 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
101 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
102 };
103 
104 char *month_names[12] = {
105 	"January", "February", "March", "April", "May", "June",
106 	"July", "August", "September", "October", "November", "December",
107 };
108 
109 char *day_headings = " S  M Tu  W Th  F  S";
110 char *j_day_headings = "  S   M  Tu   W  Th   F   S";
111 
112 /* leap year -- account for gregorian reformation in 1752 */
113 #define	leap_year(yr) \
114 	((yr) <= 1752 ? !((yr) % 4) : \
115 	(!((yr) % 4) && ((yr) % 100)) || !((yr) % 400))
116 
117 /* number of centuries since 1700, not inclusive */
118 #define	centuries_since_1700(yr) \
119 	((yr) > 1700 ? (yr) / 100 - 17 : 0)
120 
121 /* number of centuries since 1700 whose modulo of 400 is 0 */
122 #define	quad_centuries_since_1700(yr) \
123 	((yr) > 1600 ? ((yr) - 1600) / 400 : 0)
124 
125 /* number of leap years between year 1 and this year, not inclusive */
126 #define	leap_years_since_year_1(yr) \
127 	((yr) / 4 - centuries_since_1700(yr) + quad_centuries_since_1700(yr))
128 
129 int julian;
130 int hilite;
131 char *md, *me;
132 
133 void	init_hilite(void);
134 int	getnum(const char *);
135 int	ascii_day(char *, int);
136 void	center(char *, int, int);
137 void	day_array(int, int, int *);
138 int	day_in_week(int, int, int);
139 int	day_in_year(int, int, int);
140 void	monthrange(int, int, int, int, int);
141 int	main(int, char **);
142 void	trim_trailing_spaces(char *);
143 void	usage(void);
144 
145 int
146 main(int argc, char **argv)
147 {
148 	struct tm *local_time;
149 	time_t now;
150 	int ch, month, year, yflag;
151 	int before, after;
152 	int yearly = 0;
153 
154 	before = after = 0;
155 	yflag = year = 0;
156 	while ((ch = getopt(argc, argv, "A:B:hjy3")) != -1) {
157 		switch (ch) {
158 		case 'A':
159 			after = getnum(optarg);
160 			break;
161 		case 'B':
162 			before = getnum(optarg);
163 			break;
164 		case 'h':
165 			init_hilite();
166 			break;
167 		case 'j':
168 			julian = 1;
169 			break;
170 		case 'y':
171 			yflag = 1;
172 			break;
173 		case '3':
174 			before = after = 1;
175 			break;
176 		case '?':
177 		default:
178 			usage();
179 			/* NOTREACHED */
180 		}
181 	}
182 
183 	argc -= optind;
184 	argv += optind;
185 
186 	month = 0;
187 	switch (argc) {
188 	case 2:
189 		if ((month = atoi(*argv++)) < 1 || month > 12)
190 			errx(1, "illegal month value: use 1-12");
191 		/* FALLTHROUGH */
192 	case 1:
193 		if ((year = atoi(*argv)) < 1 || year > 9999)
194 			errx(1, "illegal year value: use 1-9999");
195 		break;
196 	case 0:
197 		(void)time(&now);
198 		local_time = localtime(&now);
199 		year = local_time->tm_year + TM_YEAR_BASE;
200 		if (!yflag)
201 			month = local_time->tm_mon + 1;
202 		break;
203 	default:
204 		usage();
205 	}
206 
207 	if (!month) {
208 		/* yearly */
209 		month = 1;
210 		before = 0;
211 		after = 11;
212 		yearly = 1;
213 	}
214 
215 	monthrange(month, year, before, after, yearly);
216 
217 	exit(0);
218 }
219 
220 #define	DAY_LEN		3		/* 3 spaces per day */
221 #define	J_DAY_LEN	4		/* 4 spaces per day */
222 #define	WEEK_LEN	20		/* 7 * 3 - one space at the end */
223 #define	J_WEEK_LEN	27		/* 7 * 4 - one space at the end */
224 #define	HEAD_SEP	2		/* spaces between day headings */
225 #define	J_HEAD_SEP	2
226 #define	MONTH_PER_ROW	3		/* how many monthes in a row */
227 #define	J_MONTH_PER_ROW	2
228 
229 void
230 monthrange(int month, int year, int before, int after, int yearly)
231 {
232 	int startmonth, startyear;
233 	int endmonth, endyear;
234 	int i, row;
235 	int days[3][MAXDAYS];
236 	char lineout[256];
237 	int inayear;
238 	int newyear;
239 	int day_len, week_len, head_sep;
240 	int month_per_row;
241 	int skip, r_off, w_off;
242 
243 	if (julian) {
244 		day_len = J_DAY_LEN;
245 		week_len = J_WEEK_LEN;
246 		head_sep = J_HEAD_SEP;
247 		month_per_row = J_MONTH_PER_ROW;
248 	}
249 	else {
250 		day_len = DAY_LEN;
251 		week_len = WEEK_LEN;
252 		head_sep = HEAD_SEP;
253 		month_per_row = MONTH_PER_ROW;
254 	}
255 
256 	month--;
257 
258 	startyear = year - (before + 12 - 1 - month) / 12;
259 	startmonth = 12 - 1 - ((before + 12 - 1 - month) % 12);
260 	endyear = year + (month + after) / 12;
261 	endmonth = (month + after) % 12;
262 
263 	if (startyear < 0 || endyear > 9999) {
264 		errx(1, "year should be in 1-9999\n");
265 	}
266 
267 	year = startyear;
268 	month = startmonth;
269 	inayear = newyear = (year != endyear || yearly);
270 	if (inayear) {
271 		skip = month % month_per_row;
272 		month -= skip;
273 	}
274 	else {
275 		skip = 0;
276 	}
277 
278 	do {
279 		if (newyear) {
280 			(void)snprintf(lineout, sizeof(lineout), "%d", year);
281 			center(lineout, week_len * month_per_row +
282 			    head_sep * (month_per_row - 1), 0);
283 			(void)printf("\n\n");
284 			newyear = 0;
285 		}
286 
287 		for (i = 0; i < skip; i++)
288 			center("", week_len, head_sep);
289 
290 		for (; i < month_per_row; i++) {
291 			int sep;
292 
293 			if (year == endyear && month + i > endmonth)
294 				break;
295 
296 			sep = (i == month_per_row - 1) ? 0 : head_sep;
297 			day_array(month + i + 1, year, days[i]);
298 			if (inayear) {
299 				center(month_names[month + i], week_len, sep);
300 			}
301 			else {
302 				snprintf(lineout, sizeof(lineout), "%s %d",
303 				    month_names[month + i], year);
304 				center(lineout, week_len, sep);
305 			}
306 		}
307 		printf("\n");
308 
309 		for (i = 0; i < skip; i++)
310 			center("", week_len, head_sep);
311 
312 		for (; i < month_per_row; i++) {
313 			int sep;
314 
315 			if (year == endyear && month + i > endmonth)
316 				break;
317 
318 			sep = (i == month_per_row - 1) ? 0 : head_sep;
319 			printf("%s%*s",
320 			    (julian) ? j_day_headings : day_headings, sep, "");
321 		}
322 		printf("\n");
323 
324 		memset(lineout, ' ', sizeof(lineout));
325 		for (row = 0; row < 6; row++) {
326 			char *p;
327 			for (i = 0; i < skip; i++) {
328 				p = lineout + i * (week_len + 2) + w_off;
329 				memset(p, ' ', week_len);
330 			}
331 			w_off = 0;
332 			for (; i < month_per_row; i++) {
333 				int col, *dp;
334 
335 				if (year == endyear && month + i > endmonth)
336 					break;
337 
338 				p = lineout + i * (week_len + 2) + w_off;
339 				dp = &days[i][row * 7];
340 				for (col = 0; col < 7;
341 				     col++, p += day_len + r_off) {
342 					r_off = ascii_day(p, *dp++);
343 					w_off += r_off;
344 				}
345 			}
346 			*p = '\0';
347 			trim_trailing_spaces(lineout);
348 			(void)printf("%s\n", lineout);
349 		}
350 
351 		skip = 0;
352 		month += month_per_row;
353 		if (month >= 12) {
354 			month -= 12;
355 			year++;
356 			newyear = 1;
357 		}
358 	} while (year < endyear || (year == endyear && month <= endmonth));
359 }
360 
361 /*
362  * day_array --
363  *	Fill in an array of 42 integers with a calendar.  Assume for a moment
364  *	that you took the (maximum) 6 rows in a calendar and stretched them
365  *	out end to end.  You would have 42 numbers or spaces.  This routine
366  *	builds that array for any month from Jan. 1 through Dec. 9999.
367  */
368 void
369 day_array(int month, int year, int *days)
370 {
371 	int day, dw, dm;
372 	time_t t;
373 	struct tm *tm;
374 
375 	t = time(NULL);
376 	tm = localtime(&t);
377 	tm->tm_year += TM_YEAR_BASE;
378 	tm->tm_mon++;
379 	tm->tm_yday++; /* jan 1 is 1 for us, not 0 */
380 
381 	if (month == 9 && year == 1752) {
382 		memmove(days,
383 			julian ? j_sep1752 : sep1752, MAXDAYS * sizeof(int));
384 		return;
385 	}
386 	memmove(days, empty, MAXDAYS * sizeof(int));
387 	dm = days_in_month[leap_year(year)][month];
388 	dw = day_in_week(1, month, year);
389 	day = julian ? day_in_year(1, month, year) : 1;
390 	while (dm--) {
391 		if (hilite && year == tm->tm_year &&
392 		    (julian ? (day == tm->tm_yday) :
393 		     (month == tm->tm_mon && day == tm->tm_mday)))
394 			days[dw++] = -1 - day++;
395 		else
396 			days[dw++] = day++;
397 	}
398 }
399 
400 /*
401  * day_in_year --
402  *	return the 1 based day number within the year
403  */
404 int
405 day_in_year(int day, int month, int year)
406 {
407 	int i, leap;
408 
409 	leap = leap_year(year);
410 	for (i = 1; i < month; i++)
411 		day += days_in_month[leap][i];
412 	return (day);
413 }
414 
415 /*
416  * day_in_week
417  *	return the 0 based day number for any date from 1 Jan. 1 to
418  *	31 Dec. 9999.  Assumes the Gregorian reformation eliminates
419  *	3 Sep. 1752 through 13 Sep. 1752.  Returns Thursday for all
420  *	missing days.
421  */
422 int
423 day_in_week(int day, int month, int year)
424 {
425 	long temp;
426 
427 	temp = (long)(year - 1) * 365 + leap_years_since_year_1(year - 1)
428 	    + day_in_year(day, month, year);
429 	if (temp < FIRST_MISSING_DAY)
430 		return ((temp - 1 + SATURDAY) % 7);
431 	if (temp >= (FIRST_MISSING_DAY + NUMBER_MISSING_DAYS))
432 		return (((temp - 1 + SATURDAY) - NUMBER_MISSING_DAYS) % 7);
433 	return (THURSDAY);
434 }
435 
436 int
437 ascii_day(char *p, int day)
438 {
439 	int display, val, rc;
440 	char *b;
441 	static char *aday[] = {
442 		"",
443 		" 1", " 2", " 3", " 4", " 5", " 6", " 7",
444 		" 8", " 9", "10", "11", "12", "13", "14",
445 		"15", "16", "17", "18", "19", "20", "21",
446 		"22", "23", "24", "25", "26", "27", "28",
447 		"29", "30", "31",
448 	};
449 
450 	if (day == SPACE) {
451 		memset(p, ' ', julian ? J_DAY_LEN : DAY_LEN);
452 		return (0);
453 	}
454 	if (day < 0) {
455 		b = p;
456 		day = -1 - day;
457 	} else
458 		b = NULL;
459 	if (julian) {
460 		if ((val = day / 100) != 0) {
461 			day %= 100;
462 			*p++ = val + '0';
463 			display = 1;
464 		} else {
465 			*p++ = ' ';
466 			display = 0;
467 		}
468 		val = day / 10;
469 		if (val || display)
470 			*p++ = val + '0';
471 		else
472 			*p++ = ' ';
473 		*p++ = day % 10 + '0';
474 	} else {
475 		*p++ = aday[day][0];
476 		*p++ = aday[day][1];
477 	}
478 
479 	rc = 0;
480 	if (b != NULL) {
481 		char *t, h[64];
482 		int l;
483 
484 		l = p - b;
485 		memcpy(h, b, l);
486 		p = b;
487 
488 		if (md != NULL) {
489 			for (t = md; *t; rc++)
490 				*p++ = *t++;
491 			memcpy(p, h, l);
492 			p += l;
493 			for (t = me; *t; rc++)
494 				*p++ = *t++;
495 		} else {
496 			for (t = &h[0]; l--; t++) {
497 				*p++ = *t;
498 				rc++;
499 				*p++ = '\b';
500 				rc++;
501 				*p++ = *t;
502 			}
503 		}
504 
505 	}
506 
507 	*p = ' ';
508 	return (rc);
509 }
510 
511 void
512 trim_trailing_spaces(char *s)
513 {
514 	char *p;
515 
516 	for (p = s; *p; ++p)
517 		continue;
518 	while (p > s && isspace((unsigned char)*--p))
519 		continue;
520 	if (p > s)
521 		++p;
522 	*p = '\0';
523 }
524 
525 void
526 center(char *str, int len, int separate)
527 {
528 
529 	len -= strlen(str);
530 	(void)printf("%*s%s%*s", len / 2, "", str, len / 2 + len % 2, "");
531 	if (separate)
532 		(void)printf("%*s", separate, "");
533 }
534 
535 int
536 getnum(const char *p)
537 {
538 	long result;
539 	char *ep;
540 
541 	errno = 0;
542 	result = strtoul(p, &ep, 10);
543 	if (p[0] == '\0' || *ep != '\0')
544 		goto error;
545 	if (errno == ERANGE && result == ULONG_MAX)
546 		goto error;
547 	if (result > INT_MAX)
548 		goto error;
549 
550 	return (int)result;
551 
552 error:
553 	errx(1, "bad number: %s", p);
554 	/*NOTREACHED*/
555 }
556 
557 void
558 init_hilite(void)
559 {
560 	static char control[128];
561 	char cap[1024];
562 	char *tc;
563 
564 	hilite++;
565 
566 	if (!isatty(fileno(stdout)))
567 		return;
568 
569 	tc = getenv("TERM");
570 	if (tc == NULL)
571 		tc = "dumb";
572 	if (tgetent(&cap[0], tc) != 1)
573 		return;
574 
575 	tc = &control[0];
576 	if ((md = tgetstr(hilite > 1 ? "mr" : "md", &tc)))
577 		*tc++ = '\0';
578 	if ((me = tgetstr("me", &tc)))
579 		*tc++ = '\0';
580 	if (me == NULL || md == NULL)
581 		md = me = NULL;
582 }
583 
584 void
585 usage(void)
586 {
587 
588 	(void)fprintf(stderr,
589 	    "usage: cal [-hjy3] [-B before] [-A after] [[month] year]\n");
590 	exit(1);
591 }
592