]> git.sur5r.net Git - i3/i3status/blob - src/print_time.c
able to print percentage
[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, time_t t) {
38     const char *walk;
39     char *outwalk = buffer;
40     struct tm tm;
41     char timebuf[1024];
42
43     if (title != NULL)
44         INSTANCE(title);
45
46     set_timezone(tz);
47     localtime_r(&t, &tm);
48
49     if (locale != NULL) {
50         setlocale(LC_ALL, locale);
51     }
52
53     if (format_time == NULL) {
54         strftime(timebuf, sizeof(timebuf), format, &tm);
55         maybe_escape_markup(timebuf, &outwalk);
56     } else {
57         for (walk = format; *walk != '\0'; walk++) {
58             if (*walk != '%') {
59                 *(outwalk++) = *walk;
60
61             } else if (BEGINS_WITH(walk + 1, "time")) {
62                 strftime(timebuf, sizeof(timebuf), format_time, &tm);
63                 maybe_escape_markup(timebuf, &outwalk);
64                 walk += strlen("time");
65
66             } else {
67                 *(outwalk++) = '%';
68             }
69         }
70     }
71
72     if (locale != NULL) {
73         setlocale(LC_ALL, "");
74     }
75
76     *outwalk = '\0';
77     OUTPUT_FULL_TEXT(buffer);
78 }