]> git.sur5r.net Git - i3/i3status/blob - src/print_time.c
fix: use SYSCONFDIR in error message
[i3/i3status] / src / print_time.c
1 // vim:ts=4:sw=4:expandtab
2 #include <config.h>
3 #include <time.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <stdbool.h>
7 #include <locale.h>
8 #include <yajl/yajl_gen.h>
9 #include <yajl/yajl_version.h>
10
11 #include "i3status.h"
12
13 static bool local_timezone_init = false;
14 static const char *local_timezone = NULL;
15 static const char *current_timezone = NULL;
16
17 void set_timezone(const char *tz) {
18     if (!local_timezone_init) {
19         /* First call, initialize. */
20         local_timezone = getenv("TZ");
21         local_timezone_init = true;
22     }
23     if (tz == NULL || tz[0] == '\0') {
24         /* User wants localtime. */
25         tz = local_timezone;
26     }
27     if (tz != current_timezone) {
28         if (tz) {
29             setenv("TZ", tz, 1);
30         } else {
31             unsetenv("TZ");
32         }
33         current_timezone = tz;
34     }
35     tzset();
36 }
37
38 void print_time(yajl_gen json_gen, char *buffer, const char *title, const char *format, const char *tz, const char *locale, const char *format_time, bool hide_if_equals_localtime, time_t t) {
39     const char *walk;
40     char *outwalk = buffer;
41     struct tm local_tm, tm;
42     char timebuf[1024];
43
44     if (title != NULL)
45         INSTANCE(title);
46
47     set_timezone(NULL);
48     localtime_r(&t, &local_tm);
49
50     set_timezone(tz);
51     localtime_r(&t, &tm);
52
53     // When hide_if_equals_localtime is true, compare local and target time to display only if different
54     time_t local_t = mktime(&local_tm);
55     double diff = difftime(local_t, t);
56     if (hide_if_equals_localtime && diff == 0.0) {
57         goto out;
58     }
59
60     if (locale != NULL) {
61         setlocale(LC_ALL, locale);
62     }
63
64     if (format_time == NULL) {
65         strftime(timebuf, sizeof(timebuf), format, &tm);
66         maybe_escape_markup(timebuf, &outwalk);
67     } else {
68         for (walk = format; *walk != '\0'; walk++) {
69             if (*walk != '%') {
70                 *(outwalk++) = *walk;
71
72             } else if (BEGINS_WITH(walk + 1, "time")) {
73                 strftime(timebuf, sizeof(timebuf), format_time, &tm);
74                 maybe_escape_markup(timebuf, &outwalk);
75                 walk += strlen("time");
76
77             } else {
78                 *(outwalk++) = '%';
79             }
80         }
81     }
82
83     if (locale != NULL) {
84         setlocale(LC_ALL, "");
85     }
86
87 out:
88     *outwalk = '\0';
89     OUTPUT_FULL_TEXT(buffer);
90 }