2 * vim:ts=4:sw=4:expandtab
4 * i3bar - an xcb-based status- and ws-bar for i3
5 * © 2010-2012 Axel Wagner and contributors (see also: LICENSE)
7 * parse_json_header.c: Parse the JSON protocol header to determine
8 * protocol version and features.
13 #include <sys/types.h>
24 #include <yajl/yajl_common.h>
25 #include <yajl/yajl_parse.h>
26 #include <yajl/yajl_version.h>
38 static int header_integer(void *ctx, long long val) {
39 i3bar_child *child = ctx;
41 switch (current_key) {
46 child->stop_signal = val;
49 child->cont_signal = val;
58 static int header_boolean(void *ctx, int val) {
59 i3bar_child *child = ctx;
61 switch (current_key) {
62 case KEY_CLICK_EVENTS:
63 child->click_events = val;
72 #define CHECK_KEY(name) (stringlen == strlen(name) && \
73 STARTS_WITH((const char *)stringval, stringlen, name))
75 static int header_map_key(void *ctx, const unsigned char *stringval, size_t stringlen) {
76 if (CHECK_KEY("version")) {
77 current_key = KEY_VERSION;
78 } else if (CHECK_KEY("stop_signal")) {
79 current_key = KEY_STOP_SIGNAL;
80 } else if (CHECK_KEY("cont_signal")) {
81 current_key = KEY_CONT_SIGNAL;
82 } else if (CHECK_KEY("click_events")) {
83 current_key = KEY_CLICK_EVENTS;
88 static void child_init(i3bar_child *child) {
90 child->stop_signal = SIGSTOP;
91 child->cont_signal = SIGCONT;
95 * Parse the JSON protocol header to determine protocol version and features.
96 * In case the buffer does not contain a valid header (invalid JSON, or no
97 * version field found), the 'correct' field of the returned header is set to
98 * false. The amount of bytes consumed by parsing the header is returned in
99 * *consumed (if non-NULL).
102 void parse_json_header(i3bar_child *child, const unsigned char *buffer, int length, unsigned int *consumed) {
103 static yajl_callbacks version_callbacks = {
104 .yajl_boolean = header_boolean,
105 .yajl_integer = header_integer,
106 .yajl_map_key = &header_map_key,
111 current_key = NO_KEY;
113 yajl_handle handle = yajl_alloc(&version_callbacks, NULL, child);
114 /* Allow trailing garbage. yajl 1 always behaves that way anyways, but for
115 * yajl 2, we need to be explicit. */
116 yajl_config(handle, yajl_allow_trailing_garbage, 1);
118 yajl_status state = yajl_parse(handle, buffer, length);
119 if (state != yajl_status_ok) {
121 if (consumed != NULL)
124 if (consumed != NULL)
125 *consumed = yajl_get_bytes_consumed(handle);