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