#define AL_LOG_SECTION "color_palette" #include #include "color_palette.h" struct camu_color_palette global_color_palette = { 0 }; #ifdef NAUNET_HAS_JSON #include #include static char *special_colors[2] = { "background", "foreground" }; static char *normal_colors[16] = { "color0", "color1", "color2", "color3", "color4", "color5", "color6", "color7", "color8", "color9", "color10", "color11", "color12", "color13", "color14", "color15" }; #endif bool camu_color_palette_init(str *path) { #ifdef NAUNET_HAS_JSON struct nn_file file; if (!nn_file_exists(path) || !nn_file_open(&file, path, NNWT_FILE_READONLY)) { return false; } str buffer; nn_file_read_as_str(&file, &buffer); nn_file_close(&file); json_error_t error; json_t *root = json_loadb(buffer.data, buffer.length, 0, &error); al_str_free(&buffer); if (!root) { log_error("Failed to load %.*s as a json (%s).", al_str_x(path), error.text); return false; } bool parsed = true; json_t *special = json_object_get(root, "special"); if (!special) { log_error("\"special\" field missing from the color palette."); parsed = false; goto out; } json_t *colors = json_object_get(root, "colors"); if (!colors) { log_error("\"colors\" field missing from the color palette."); parsed = false; goto out; } json_t *object; const char *color; u32 value; u32 index; bool to_long_error; for (u32 i = 0; i < ARRAY_SIZE(special_colors); i++) { object = json_object_get(special, special_colors[i]); if (!object) { log_error("Couldn't find special color: %s.", special_colors[i]); return false; } color = json_string_value(object); index = (color[0] == '#') ? 1 : 0; value = (u32)al_str_to_long(&al_str_w((char *)color, index, 6), 16, &to_long_error); if (!to_long_error) { global_color_palette.colors[i] = value; } else { log_warn("%s is not a valid hex color.", normal_colors[i]); } } for (u32 i = 0; i < ARRAY_SIZE(normal_colors); i++) { object = json_object_get(colors, normal_colors[i]); if (!object) { log_error("Couldn't find color: %s.", normal_colors[i]); return false; } color = json_string_value(object); index = (color[0] == '#') ? 1 : 0; value = (u32)al_str_to_long(&al_str_w((char *)color, index, 6), 16, &to_long_error); if (!to_long_error) { global_color_palette.colors[i + 2] = value; } else { log_warn("%s is not a valid hex color.", normal_colors[i]); } } out: json_decref(root); return parsed; #else (void)path; return false; #endif }