Skip to content
Myr

config.c

This file

Path

config.c

1,818 lines · 52.6 KiB · C

Last changed by

config: add --mesg, --mesg-mode and --message-color command line optionsSlayerOfTheBadbefore adoption9fb7e6c

History of this file

Take it

1#include "config.h"23#include <sys/types.h>4#include <sys/stat.h>56#include <stdio.h>7#include <assert.h>8#include <errno.h>9#include <fcntl.h>10#include <limits.h>11#include <pwd.h>12#include <stdio.h>13#include <stdlib.h>14#include <string.h>15#include <unistd.h>16#include <ctype.h>1718#define LOG_MODULE "config"19#define LOG_ENABLE_DBG 020#include "log.h"21#include "key-binding.h"22#include "macros.h"23#include "xmalloc.h"24#include "xsnprintf.h"2526const struct anchors_map anchors_map[] = {27    {"top-left", ANCHOR_TOP_LEFT},28    {"top", ANCHOR_TOP},29    {"top-right", ANCHOR_TOP_RIGHT},30    {"left", ANCHOR_LEFT},31    {"center", ANCHOR_CENTER},32    {"right", ANCHOR_RIGHT},33    {"bottom-left", ANCHOR_BOTTOM_LEFT},34    {"bottom", ANCHOR_BOTTOM},35    {"bottom-right", ANCHOR_BOTTOM_RIGHT},36    {NULL, 0},37};3839static const char *const binding_action_map[] = {40    [BIND_ACTION_NONE] = NULL,41    [BIND_ACTION_CANCEL] = "cancel",42    [BIND_ACTION_CURSOR_HOME] = "cursor-home",43    [BIND_ACTION_CURSOR_END] = "cursor-end",44    [BIND_ACTION_CURSOR_LEFT] = "cursor-left",45    [BIND_ACTION_CURSOR_LEFT_WORD] = "cursor-left-word",46    [BIND_ACTION_CURSOR_RIGHT] = "cursor-right",47    [BIND_ACTION_CURSOR_RIGHT_WORD] = "cursor-right-word",48    [BIND_ACTION_DELETE_LINE] = "delete-line",49    [BIND_ACTION_DELETE_PREV] = "delete-prev",50    [BIND_ACTION_DELETE_PREV_WORD] = "delete-prev-word",51    [BIND_ACTION_DELETE_LINE_BACKWARD] = "delete-line-backward",52    [BIND_ACTION_DELETE_NEXT] = "delete-next",53    [BIND_ACTION_DELETE_NEXT_WORD] = "delete-next-word",54    [BIND_ACTION_DELETE_LINE_FORWARD] = "delete-line-forward",55    [BIND_ACTION_INSERT_SELECTED] = "insert-selected",56    [BIND_ACTION_EXPUNGE] = "expunge",57    [BIND_ACTION_CLIPBOARD_PASTE] = "clipboard-paste",58    [BIND_ACTION_PRIMARY_PASTE] = "primary-paste",59    [BIND_ACTION_MATCHES_EXECUTE] = "execute",60    [BIND_ACTION_MATCHES_EXECUTE_OR_NEXT] = "execute-or-next",61    [BIND_ACTION_MATCHES_EXECUTE_INPUT] = "execute-input",62    [BIND_ACTION_MATCHES_PREV] = "prev",63    [BIND_ACTION_MATCHES_PREV_WITH_WRAP] = "prev-with-wrap",64    [BIND_ACTION_MATCHES_PREV_PAGE] = "prev-page",65    [BIND_ACTION_MATCHES_NEXT] = "next",66    [BIND_ACTION_MATCHES_NEXT_WITH_WRAP] = "next-with-wrap",67    [BIND_ACTION_MATCHES_NEXT_PAGE] = "next-page",68    [BIND_ACTION_MATCHES_FIRST] = "first",69    [BIND_ACTION_MATCHES_LAST] = "last",7071    [BIND_ACTION_CUSTOM_1] = "custom-1",72    [BIND_ACTION_CUSTOM_2] = "custom-2",73    [BIND_ACTION_CUSTOM_3] = "custom-3",74    [BIND_ACTION_CUSTOM_4] = "custom-4",75    [BIND_ACTION_CUSTOM_5] = "custom-5",76    [BIND_ACTION_CUSTOM_6] = "custom-6",77    [BIND_ACTION_CUSTOM_7] = "custom-7",78    [BIND_ACTION_CUSTOM_8] = "custom-8",79    [BIND_ACTION_CUSTOM_9] = "custom-9",80    [BIND_ACTION_CUSTOM_10] = "custom-10",81    [BIND_ACTION_CUSTOM_11] = "custom-11",82    [BIND_ACTION_CUSTOM_12] = "custom-12",83    [BIND_ACTION_CUSTOM_13] = "custom-13",84    [BIND_ACTION_CUSTOM_14] = "custom-14",85    [BIND_ACTION_CUSTOM_15] = "custom-15",86    [BIND_ACTION_CUSTOM_16] = "custom-16",87    [BIND_ACTION_CUSTOM_17] = "custom-17",88    [BIND_ACTION_CUSTOM_18] = "custom-18",89    [BIND_ACTION_CUSTOM_19] = "custom-19",9091};9293struct context {94    struct config *conf;95    const char *section;96    const char *key;97    const char *value;9899    const char *path;100    unsigned lineno;101102    bool errors_are_fatal;103};104105#define LOG_CONTEXTUAL_ERR(...)                                         \106    log_contextual(ctx, LOG_CLASS_ERROR, __FILE__, __LINE__, __VA_ARGS__)107108#define LOG_CONTEXTUAL_WARN(...) \109    log_contextual(ctx, LOG_CLASS_WARNING, __FILE__, __LINE__, __VA_ARGS__)110111#define LOG_CONTEXTUAL_ERRNO(...) \112    log_contextual_errno(ctx, __FILE__, __LINE__, __VA_ARGS__)113114115static void PRINTF(5)116log_contextual(struct context *ctx, enum log_class log_class,117               const char *file, int lineno, const char *fmt, ...)118{119    char *formatted_msg = NULL;120    va_list va;121    va_start(va, fmt);122    int ret = vasprintf(&formatted_msg, fmt, va);123    va_end(va);124125    if (unlikely(ret < 0))126        return;127128    bool print_dot = ctx->key != NULL;129    bool print_colon = ctx->value != NULL;130131    if (!print_dot)132        ctx->key = "";133134    if (!print_colon)135        ctx->value = "";136137    log_msg(138        log_class, LOG_MODULE, file, lineno, "%s:%d: [%s]%s%s%s%s: %s",139        ctx->path, ctx->lineno, ctx->section, print_dot ? "." : "",140        ctx->key, print_colon ? ": " : "", ctx->value, formatted_msg);141    free(formatted_msg);142}143144static void PRINTF(4)145log_contextual_errno(struct context *ctx, const char *file, int lineno,146                     const char *fmt, ...)147{148    va_list va;149    va_start(va, fmt);150    char *formatted_msg;151    int ret = vasprintf(&formatted_msg, fmt, va);152    va_end(va);153154    if (unlikely(ret < 0))155        return;156157    bool print_dot = ctx->key != NULL;158    bool print_colon = ctx->value != NULL;159160    if (!print_dot)161        ctx->key = "";162163    if (!print_colon)164        ctx->value = "";165166    log_errno(167        LOG_CLASS_ERROR, LOG_MODULE, file, lineno, "%s:%d: [%s]%s%s%s%s: %s",168        ctx->path, ctx->lineno, ctx->section, print_dot ? "." : "",169        ctx->key, print_colon ? ": " : "", ctx->value, formatted_msg);170171    free(formatted_msg);172}173174struct config_file {175    char *path;       /* Full, absolute, path */176    int fd;           /* FD of file, O_RDONLY */177};178179static struct config_file180open_config(void)181{182    char *path = NULL;183    struct config_file ret = {.path = NULL, .fd = -1};184185    const char *xdg_config_home = getenv("XDG_CONFIG_HOME");186    const char *xdg_config_dirs = getenv("XDG_CONFIG_DIRS");187    const char *home_dir = getenv("HOME");188    char *xdg_config_dirs_copy = NULL;189190    /* First, check XDG_CONFIG_HOME (or .config, if unset) */191    if (xdg_config_home != NULL && xdg_config_home[0] == '/') {192        path = xstrjoin(xdg_config_home, "/fuzzel/fuzzel.ini");193    } else if (home_dir != NULL) {194        path = xstrjoin(home_dir, "/.config/fuzzel/fuzzel.ini");195    }196197    if (path != NULL) {198        int fd = open(path, O_RDONLY | O_CLOEXEC);199200        if (fd >= 0) {201            ret = (struct config_file) {.path = path, .fd = fd};202            path = NULL;203            goto done;204        }205    }206207    xdg_config_dirs_copy = xdg_config_dirs != NULL && xdg_config_dirs[0] != '\0'208        ? xstrdup(xdg_config_dirs)209        : xstrdup("/etc/xdg");210211    if (xdg_config_dirs_copy == NULL || xdg_config_dirs_copy[0] == '\0')212        goto done;213214    for (const char *conf_dir = strtok(xdg_config_dirs_copy, ":");215         conf_dir != NULL;216         conf_dir = strtok(NULL, ":"))217    {218        free(path);219        path = xstrjoin(conf_dir, "/fuzzel/fuzzel.ini");220        int fd = open(path, O_RDONLY | O_CLOEXEC);221        if (fd >= 0) {222            ret = (struct config_file){.path = path, .fd = fd};223            path = NULL;224            goto done;225        }226    }227228done:229    free(xdg_config_dirs_copy);230    free(path);231    return ret;232}233234static void235free_key_binding_list(struct config_key_binding_list *bindings)236{237    free(bindings->arr);238    bindings->arr = NULL;239    bindings->count = 0;240}241242static bool243parse_modifiers(struct context *ctx, const char *text, size_t len,244                struct config_key_modifiers *modifiers)245{246    bool ret = false;247248    *modifiers = (struct config_key_modifiers){0};249250    /* Handle "none" separately because e.g. none+shift is nonsense */251    if (strncmp(text, "none", len) == 0)252        return true;253254    char *copy = xstrndup(text, len);255256    for (char *tok_ctx = NULL, *key = strtok_r(copy, "+", &tok_ctx);257         key != NULL;258         key = strtok_r(NULL, "+", &tok_ctx))259    {260        if (strcmp(key, XKB_MOD_NAME_SHIFT) == 0)261            modifiers->shift = true;262        else if (strcmp(key, XKB_MOD_NAME_CTRL) == 0)263            modifiers->ctrl = true;264        else if (strcmp(key, XKB_MOD_NAME_ALT) == 0)265            modifiers->alt = true;266        else if (strcmp(key, XKB_MOD_NAME_LOGO) == 0)267            modifiers->super = true;268        else {269            LOG_CONTEXTUAL_ERR("not a valid modifier name: %s", key);270            goto out;271        }272    }273274    ret = true;275276out:277    free(copy);278    return ret;279}280281static void282remove_from_key_bindings_list(struct config_key_binding_list *bindings,283                              int action)284{285    size_t remove_first_idx = 0;286    size_t remove_count = 0;287288    for (size_t i = 0; i < bindings->count; i++) {289        struct config_key_binding *binding = &bindings->arr[i];290291        if (binding->action != action)292            continue;293294        if (remove_count++ == 0)295            remove_first_idx = i;296297        assert(remove_first_idx + remove_count - 1 == i);298        //free_key_binding(binding);299    }300301    if (remove_count == 0)302        return;303304    size_t move_count = bindings->count - (remove_first_idx + remove_count);305306    memmove(307        &bindings->arr[remove_first_idx],308        &bindings->arr[remove_first_idx + remove_count],309        move_count * sizeof(bindings->arr[0]));310    bindings->count -= remove_count;311}312313static bool314value_to_key_combos(struct context *ctx, int action,315                    struct config_key_binding_list *bindings)316{317    if (strcasecmp(ctx->value, "none") == 0) {318        remove_from_key_bindings_list(bindings, action);319        return true;320    }321322    /* Count number of combinations */323    size_t combo_count = 1;324    for (const char *p = strchr(ctx->value, ' ');325         p != NULL;326         p = strchr(p + 1, ' '))327    {328        combo_count++;329    }330331    struct config_key_binding new_combos[combo_count];332333    char *copy = xstrdup(ctx->value);334    size_t idx = 0;335336    for (char *tok_ctx = NULL, *combo = strtok_r(copy, " ", &tok_ctx);337         combo != NULL;338         combo = strtok_r(NULL, " ", &tok_ctx),339             idx++)340    {341        struct config_key_binding *new_combo = &new_combos[idx];342        new_combo->action = action;343        new_combo->path = ctx->path;344        new_combo->lineno = ctx->lineno;345346        char *key = strrchr(combo, '+');347348        if (key == NULL) {349            /* No modifiers */350            key = combo;351            new_combo->modifiers = (struct config_key_modifiers){0};352        } else {353            *key = '\0';354            if (!parse_modifiers(ctx, combo, key - combo, &new_combo->modifiers))355                goto err;356            key++;  /* Skip past the '+' */357        }358359        /* Translate key name to symbol */360        new_combo->k.sym = xkb_keysym_from_name(key, 0);361        if (new_combo->k.sym == XKB_KEY_NoSymbol) {362            LOG_CONTEXTUAL_ERR("not a valid XKB key name: %s", key);363            goto err;364        }365    }366367    if (idx == 0) {368        LOG_CONTEXTUAL_ERR(369            "empty binding not allowed (set to 'none' to unmap)");370        goto err;371    }372373    remove_from_key_bindings_list(bindings, action);374375    bindings->arr = xreallocarray(376        bindings->arr,377        bindings->count + combo_count, sizeof(bindings->arr[0]));378379    memcpy(&bindings->arr[bindings->count],380           new_combos,381           combo_count * sizeof(bindings->arr[0]));382    bindings->count += combo_count;383384    free(copy);385    return true;386387err:388    free(copy);389    return false;390}391392static bool393modifiers_equal(const struct config_key_modifiers *mods1,394                const struct config_key_modifiers *mods2)395{396    bool shift = mods1->shift == mods2->shift;397    bool alt = mods1->alt == mods2->alt;398    bool ctrl = mods1->ctrl == mods2->ctrl;399    bool super = mods1->super == mods2->super;400    return shift && alt && ctrl && super;401}402403static char *404modifiers_to_str(const struct config_key_modifiers *mods)405{406    return xasprintf(407        "%s%s%s%s",408        mods->ctrl ? XKB_MOD_NAME_CTRL "+" : "",409        mods->alt ? XKB_MOD_NAME_ALT "+": "",410        mods->super ? XKB_MOD_NAME_LOGO "+": "",411        mods->shift ? XKB_MOD_NAME_SHIFT "+": ""412    );413}414415static bool416resolve_key_binding_collisions(struct config *conf, const char *section_name,417                               const char *const action_map[],418                               struct config_key_binding_list *bindings)419{420    bool ret = true;421422    for (size_t i = 1; i < bindings->count; i++) {423        enum {424            COLLISION_NONE,425            COLLISION_BINDING,426        } collision_type = COLLISION_NONE;427428        const struct config_key_binding *collision_binding = NULL;429430        struct config_key_binding *binding1 = &bindings->arr[i];431        assert(binding1->action != BIND_ACTION_NONE);432433        const struct config_key_modifiers *mods1 = &binding1->modifiers;434435        /* Does our binding collide with another binding? */436        for (ssize_t j = i - 1;437             collision_type == COLLISION_NONE && j >= 0;438             j--)439        {440            const struct config_key_binding *binding2 = &bindings->arr[j];441            assert(binding2->action != BIND_ACTION_NONE);442443            if (binding2->action == binding1->action)444                continue;445446            const struct config_key_modifiers *mods2 = &binding2->modifiers;447448            bool mods_equal = modifiers_equal(mods1, mods2);449            bool sym_equal;450451            sym_equal = binding1->k.sym == binding2->k.sym;452            if (!mods_equal || !sym_equal)453                continue;454455            collision_binding = binding2;456            collision_type = COLLISION_BINDING;457            break;458        }459460        if (collision_type != COLLISION_NONE) {461            char *modifier_names = modifiers_to_str(mods1);462            char sym_name[64];463            xkb_keysym_get_name(binding1->k.sym, sym_name, sizeof(sym_name));464465            switch (collision_type) {466            case COLLISION_NONE:467                break;468469            case COLLISION_BINDING: {470                LOG_ERR(471                    "%s:%d: [%s].%s: %s%s already mapped to '%s'",472                    binding1->path, binding1->lineno, section_name,473                    action_map[binding1->action],474                    modifier_names, sym_name,475                    action_map[collision_binding->action]);476                ret = false;477                break;478            }479            }480481            free(modifier_names);482            //free_key_binding(binding1);483484            /* Remove the most recent binding */485            size_t move_count = bindings->count - (i + 1);486            memmove(&bindings->arr[i], &bindings->arr[i + 1],487                    move_count * sizeof(bindings->arr[0]));488            bindings->count--;489490            i--;491        }492    }493494    return ret;495}496497static bool498str_to_ulong(const char *s, int base, unsigned long *res)499{500    if (s == NULL)501        return false;502503    errno = 0;504    char *end = NULL;505506    *res = strtoul(s, &end, base);507    return errno == 0 && *end == '\0';508}509510static bool511str_to_uint32(const char *s, int base, uint32_t *res)512{513    unsigned long v;514    bool ret = str_to_ulong(s, base, &v);515    if (!ret)516        return false;517    if (v > UINT32_MAX)518        return false;519    *res = v;520    return true;521}522523static bool524str_to_uint16(const char *s, int base, uint16_t *res)525{526    unsigned long v;527    bool ret = str_to_ulong(s, base, &v);528    if (!ret)529        return false;530    if (v > UINT16_MAX)531        return false;532    *res = v;533    return true;534}535536static bool537value_to_str(struct context *ctx, char **res)538{539    free(*res);540    *res = xstrdup(ctx->value);541    return true;542}543544static bool545value_to_wchars(struct context *ctx, char32_t **res)546{547    char32_t *s = ambstoc32(ctx->value);548    if (s == NULL) {549        LOG_CONTEXTUAL_ERR("not a valid string value");550        return false;551    }552553    free(*res);554    *res = s;555    return true;556}557558static bool559value_to_bool(struct context *ctx, bool *res)560{561    static const char *const yes[] = {"on", "true", "yes", "1"};562    static const char *const  no[] = {"off", "false", "no", "0"};563564    for (size_t i = 0; i < ALEN(yes); i++) {565        if (strcasecmp(ctx->value, yes[i]) == 0) {566            *res = true;567            return true;568        }569    }570571    for (size_t i = 0; i < ALEN(no); i++) {572        if (strcasecmp(ctx->value, no[i]) == 0) {573            *res = false;574            return true;575        }576    }577578    LOG_CONTEXTUAL_ERR("invalid boolean value");579    return false;580}581582static bool583value_to_uint32(struct context *ctx, int base, uint32_t *res)584{585    if (!str_to_uint32(ctx->value, base, res)){586        LOG_CONTEXTUAL_ERR(587            "invalid integer value, or outside range 0-%u", UINT32_MAX);588        return false;589    }590    return true;591}592593static bool594value_to_uint16(struct context *ctx, int base, uint16_t *res)595{596    if (!str_to_uint16(ctx->value, base, res)){597        LOG_CONTEXTUAL_ERR(598            "invalid integer value, or outside range 0-%u", UINT32_MAX);599        return false;600    }601    return true;602}603604static bool605value_to_color(struct context *ctx, bool allow_alpha, struct rgba *color)606{607    const char *clr_start = ctx->value;608    if (clr_start[0] == '#')609        clr_start++;610611    if (strlen(clr_start) != 8) {612        LOG_CONTEXTUAL_ERR("not a valid color value");613        return false;614    }615616    uint32_t v;617    if (!str_to_uint32(clr_start, 16, &v)) {618        LOG_CONTEXTUAL_ERR("not a valid color value");619        return false;620    }621622    if (!allow_alpha && (v & 0x000000ff) != 0) {623        LOG_CONTEXTUAL_ERR("color value must not have an alpha component");624        return false;625    }626627    *color = conf_hex_to_rgba(v);628    return true;629}630631static bool632value_to_double(struct context *ctx, float *res)633{634    const char *s = ctx->value;635636    if (s == NULL)637        return false;638639    errno = 0;640    char *end = NULL;641642    *res = strtof(s, &end);643    if (!(errno == 0 && *end == '\0')) {644        LOG_CONTEXTUAL_ERR("invalid decimal value");645        return false;646    }647648    return true;649}650651static bool652value_to_pt_or_px(struct context *ctx, struct pt_or_px *res)653{654    const char *s = ctx->value;655656    size_t len = s != NULL ? strlen(s) : 0;657    if (len >= 2 && s[len - 2] == 'p' && s[len - 1] == 'x') {658        errno = 0;659        char *end = NULL;660661        long value = strtol(s, &end, 10);662        if (!(errno == 0 && end == s + len - 2)) {663            LOG_CONTEXTUAL_ERR("invalid px value (must be on the form 12px)");664            return false;665        }666        res->pt = 0;667        res->px = value;668    } else {669        float value;670        if (!value_to_double(ctx, &value))671            return false;672        res->pt = value;673        res->px = 0;674    }675676    return true;677}678679static bool680value_to_enum(struct context *ctx, const char **value_map, int *res)681{682    size_t str_len = 0;683    size_t count = 0;684685    for (; value_map[count] != NULL; count++) {686        if (strcasecmp(value_map[count], ctx->value) == 0) {687            *res = count;688            return true;689        }690        str_len += strlen(value_map[count]);691    }692693    const size_t size = str_len + count * 4 + 1;694    char valid_values[512];695    size_t idx = 0;696    assert(size < sizeof(valid_values));697698    for (size_t i = 0; i < count; i++)699        idx += xsnprintf(&valid_values[idx], size - idx, "'%s', ", value_map[i]);700701    if (count > 0)702        valid_values[idx - 2] = '\0';703704    LOG_CONTEXTUAL_ERR("not one of %s", valid_values);705    *res = -1;706    return false;707}708709710static bool parse_config_file(711    FILE *f, struct config *conf, const char *path, bool errors_are_fatal);712713static bool714parse_section_main(struct context *ctx)715{716    struct config *conf = ctx->conf;717    const char *key = ctx->key;718    const char *value = ctx->value;719    bool errors_are_fatal = ctx->errors_are_fatal;720721    if (strcmp(key, "include") == 0) {722        char *_include_path = NULL;723        const char *include_path = NULL;724725        if (value[0] == '~' && value[1] == '/') {726            const char *home_dir = getenv("HOME");727728            if (home_dir == NULL) {729                LOG_CONTEXTUAL_ERRNO("failed to expand '~'");730                return false;731            }732733            _include_path = xstrjoin3(home_dir, "/", value + 2);734            include_path = _include_path;735        } else736            include_path = value;737738        if (include_path[0] != '/') {739            LOG_CONTEXTUAL_ERR("not an absolute path");740            free(_include_path);741            return false;742        }743744        FILE *include = fopen(include_path, "re");745746        if (include == NULL) {747            LOG_CONTEXTUAL_ERRNO("failed to open");748            free(_include_path);749            return false;750        }751752        bool ret = parse_config_file(753            include, conf, include_path, errors_are_fatal);754        fclose(include);755756        LOG_INFO("imported sub-configuration from %s", include_path);757        free(_include_path);758        return ret;759    }760761    else if (strcmp(key, "namespace") == 0)762        return value_to_str(ctx, &conf->namespace);763764    else if (strcmp(key, "output") == 0)765        return value_to_str(ctx, &conf->output);766767    else if (strcmp(key, "font") == 0)768        return value_to_str(ctx, &conf->font);769770    else if (strcmp(key, "use-bold") == 0)771        return value_to_bool(ctx, &conf->use_bold);772773    else if (strcmp(key, "dpi-aware") == 0) {774        if (strcmp(value, "auto") == 0)775            conf->dpi_aware = DPI_AWARE_AUTO;776        else {777            bool value;778            if (!value_to_bool(ctx, &value))779                return false;780            conf->dpi_aware = value ? DPI_AWARE_YES : DPI_AWARE_NO;781        }782        return true;783    }784785    else if (strcmp(key, "gamma-correct-blending") == 0)786        return value_to_bool(ctx, &conf->gamma_correct);787788    else if (strcmp(key, "render-workers") == 0)789        return value_to_uint16(ctx, 10, &conf->render_worker_count);790791    else if (strcmp(key, "match-workers") == 0)792        return value_to_uint16(ctx, 10, &conf->match_worker_count);793794    else if (strcmp(key, "prompt") == 0)795        return value_to_wchars(ctx, &conf->prompt);796797    else if (strcmp(key, "placeholder") == 0)798        return value_to_wchars(ctx, &conf->placeholder);799800    else if (strcmp(key, "message") == 0)801        return value_to_wchars(ctx, &conf->message);802803    else if (strcmp(key, "message-mode") == 0) {804        _Static_assert(sizeof(conf->message_mode) == sizeof(int),805                       "enum is not 32-bit");806807        return value_to_enum(808            ctx,809            (const char *[]){"wrap", "expand", NULL},810            (int *)&conf->message_mode);811    }812813    else if (strcmp(key, "icon-theme") == 0)814        return value_to_str(ctx, &conf->icon_theme);815816    else if (strcmp(key, "icons-enabled") == 0)817        return value_to_bool(ctx, &conf->icons_enabled);818819    else if (strcmp(key, "hide-before-typing") == 0)820        return value_to_bool(ctx, &conf->hide_when_prompt_empty);821822    else if (strcmp(key, "list-executables-in-path") == 0)823        return value_to_bool(ctx, &conf->list_executables_in_path);824825    else if (strcmp(key, "fields") == 0) {826        _Static_assert(sizeof(conf->match_fields) == sizeof(int),827            "enum is not 32-bit");828829        enum match_fields match_fields = 0;830831        char *copy = xstrdup(value);832        for (const char *field = strtok(copy, ",");833             field != NULL;834             field = strtok(NULL, ","))835        {836            static const struct {837                const char *name;838                enum match_fields value;839            } map[] = {840                {"filename", MATCH_FILENAME},841                {"name", MATCH_NAME},842                {"generic", MATCH_GENERIC},843                {"exec", MATCH_EXEC},844                {"categories", MATCH_CATEGORIES},845                {"keywords", MATCH_KEYWORDS},846                {"comment", MATCH_COMMENT},847            };848849            enum match_fields field_value = 0;850851            for (size_t i = 0; i < ALEN(map); i++) {852                if (strcmp(field, map[i].name) == 0) {853                    field_value = map[i].value;854                    break;855                }856            }857858            if (field_value == 0) {859                LOG_CONTEXTUAL_ERR(860                    "invalid field name \"%s\", "861                    "must be one of: "862                    "\"filename\", \"name\", \"generic\", \"exec\", "863                    "\"categories\", \"keywords\", \"comment\"",864                    field);865                free(copy);866                return false;867            }868869            match_fields |= field_value;870        }871872        conf->match_fields = match_fields;873        free(copy);874        return true;875    }876877    else if (strcmp(key, "password-character") == 0) {878        char32_t *password_chars = ambstoc32(value);879        if (password_chars == NULL) {880            LOG_CONTEXTUAL_ERR("invalid password character");881            return false;882        }883884        if (c32len(password_chars) > 1) {885            LOG_CONTEXTUAL_ERR(886                "password character must be a single character, or empty");887            free(password_chars);888            return false;889        }890891        conf->password_mode.character = password_chars[0];892        conf->password_mode.character_set = true;893        free(password_chars);894        return true;895    }896897    else if (strcmp(key, "filter-desktop") == 0)898        return value_to_bool(ctx, &conf->filter_desktop);899900    else if (strcmp(key, "match-mode") == 0) {901        _Static_assert(sizeof(conf->match_mode) == sizeof(int),902                       "enum is not 32-bit");903904        return value_to_enum(905            ctx,906            (const char *[]){"exact", "fzf", "fuzzy", NULL},907            (int *)&conf->match_mode);908    }909910    else if (strcmp(key, "sort-result") == 0)911        return value_to_bool(ctx, &conf->sort_result);912913    else if (strcmp(key, "match-counter") == 0)914        return value_to_bool(ctx, &conf->match_counter);915916    else if (strcmp(key, "delayed-filter-ms") == 0)917        return value_to_uint32(ctx, 10, &conf->delayed_filter_ms);918919    else if (strcmp(key, "delayed-filter-limit") == 0)920        return value_to_uint32(ctx, 10, &conf->delayed_filter_limit);921922    else if (strcmp(key, "show-actions") == 0)923        return value_to_bool(ctx, &conf->actions_enabled);924925    else if (strcmp(key, "terminal") == 0)926        return value_to_str(ctx, &conf->terminal);927928    else if (strcmp(key, "launch-prefix") == 0)929        return value_to_str(ctx, &conf->launch_prefix);930931    else if (strcmp(key, "anchor") == 0) {932        enum anchors anchor;933        bool valid_anchor = false;934935        for (size_t i = 0; anchors_map[i].name != NULL; i++) {936            if (strcmp(value, anchors_map[i].name) == 0) {937                anchor = anchors_map[i].value;938                valid_anchor = true;939                break;940            }941        }942943        if (!valid_anchor) {944            LOG_CONTEXTUAL_ERR(945                "invalid anchor \"%s\", "946                "must be one of: "947                "\"center\", \"top-left\", \"top\", \"top-right\", "948                "\"right\", \"bottom-right\", \"bottom\""949                "\"bottom-left\", \"left\"",950                value);951            return false;952        }953954        conf->anchor = anchor;955        return true;956    }957    else if (strcmp(key, "x-margin") == 0)958      return value_to_uint32(ctx, 10, &conf->margin.x);959960    else if (strcmp(key, "y-margin") == 0)961      return value_to_uint32(ctx, 10, &conf->margin.y);962963    else if (strcmp(key, "lines") == 0)964        return value_to_uint32(ctx, 10, &conf->lines);965966    else if (strcmp(key, "minimal-lines") == 0)967        return value_to_bool(ctx, &conf->minimal_lines);968969    else if (strcmp(key, "hide-prompt") == 0)970        return value_to_bool(ctx, &conf->hide_prompt);971972    else if (strcmp(key, "width") == 0)973        return value_to_uint32(ctx, 10, &conf->chars);974975    else if (strcmp(key, "tabs") == 0)976        return value_to_uint32(ctx, 10, &conf->tabs);977978    else if (strcmp(key, "horizontal-pad") == 0)979        return value_to_uint32(ctx, 10, &conf->pad.x);980981    else if (strcmp(key, "vertical-pad") == 0)982        return value_to_uint32(ctx, 10, &conf->pad.y);983984    else if (strcmp(key, "inner-pad") == 0)985        return value_to_uint32(ctx, 10, &conf->pad.inner);986987    else if (strcmp(key, "line-height") == 0)988        return value_to_pt_or_px(ctx, &conf->line_height);989990    else if (strcmp(key, "letter-spacing") == 0)991        return value_to_pt_or_px(ctx, &conf->letter_spacing);992993    else if (strcmp(key, "image-size-ratio") == 0) {994        float ratio;995        if (!value_to_double(ctx, &ratio))996            return false;997998        if (ratio < 0. || ratio > 1.) {999            LOG_CONTEXTUAL_ERR("not in range 0.0 - 1.0");1000            return false;1001        }10021003        conf->image_size_ratio = ratio;1004        return true;1005    }10061007    else if (strcmp(key, "scaling-filter") == 0) {1008        _Static_assert(sizeof(conf->png_scaling_filter) == sizeof(int),1009            "enum is not 32-bit");10101011        return value_to_enum(1012            ctx,1013            (const char *[]){"none", "nearest", "bilinear", "box", "linear",1014                             "cubic", "lanczos2", "lanczos3",1015                             "lanczos3-stretched", NULL},1016            (int *)&conf->png_scaling_filter);1017    }10181019    else if (strcmp(key, "layer") == 0) {1020        if (strcasecmp(value, "top") == 0) {1021            conf->layer = ZWLR_LAYER_SHELL_V1_LAYER_TOP;1022            return true;1023        } else if (strcasecmp(value, "overlay") == 0) {1024            conf->layer = ZWLR_LAYER_SHELL_V1_LAYER_OVERLAY;1025            return true;1026        }10271028        LOG_CONTEXTUAL_ERR("not one of 'top', 'overlay'");1029        return false;1030    }10311032    else if (strcmp(key, "keyboard-focus") == 0) {1033        if (strcasecmp(value, "exclusive") == 0) {1034            conf->keyboard_focus = ZWLR_LAYER_SURFACE_V1_KEYBOARD_INTERACTIVITY_EXCLUSIVE;1035            return true;1036        } else if (strcasecmp(value, "on-demand") == 0) {1037            conf->keyboard_focus = ZWLR_LAYER_SURFACE_V1_KEYBOARD_INTERACTIVITY_ON_DEMAND;1038            return true;1039        }1040        LOG_CONTEXTUAL_ERR("not one of 'exclusive', 'on-demand'");1041        return false;1042    }10431044    else if (strcmp(key, "exit-on-keyboard-focus-loss") == 0)1045        return value_to_bool(ctx, &conf->exit_on_kb_focus_loss);10461047    else if (strcmp(key, "cache") == 0)1048        return value_to_str(ctx, &conf->cache_path);10491050    else if (strcmp(key, "auto-select") == 0)1051        return value_to_bool(ctx, &conf->auto_select);10521053    else if (strcmp(key, "enable-mouse") == 0)1054        return value_to_bool(ctx, &conf->enable_mouse);10551056    else1057        LOG_CONTEXTUAL_ERR("not a valid option: %s", key);10581059    return false;1060}10611062static bool1063parse_section_colors(struct context *ctx)1064{1065    struct config *conf = ctx->conf;1066    const char *key = ctx->key;10671068    if (strcmp(key, "background") == 0)1069        return value_to_color(ctx, true, &conf->colors.background);10701071    else if (strcmp(key, "text") == 0)1072        return value_to_color(ctx, true, &conf->colors.text);10731074    else if (strcmp(key, "message") == 0)1075        return value_to_color(ctx, true, &conf->colors.message);10761077    else if (strcmp(key, "prompt") == 0)1078        return value_to_color(ctx, true, &conf->colors.prompt);10791080    else if (strcmp(key, "placeholder") == 0)1081        return value_to_color(ctx, true, &conf->colors.placeholder);10821083    else if (strcmp(key, "input") == 0)1084        return value_to_color(ctx, true, &conf->colors.input);10851086    else if (strcmp(key, "match") == 0)1087        return value_to_color(ctx, true, &conf->colors.match);10881089    else if (strcmp(key, "selection") == 0)1090        return value_to_color(ctx, true, &conf->colors.selection);10911092    else if (strcmp(key, "selection-text") == 0)1093        return value_to_color(ctx, true, &conf->colors.selection_text);10941095    else if (strcmp(key, "selection-match") == 0)1096        return value_to_color(ctx, true, &conf->colors.selection_match);10971098    else if (strcmp(key, "counter") == 0)1099        return value_to_color(ctx, true, &conf->colors.counter);11001101    else if (strcmp(key, "border") == 0)1102        return value_to_color(ctx, true, &conf->colors.border);11031104    else1105        LOG_CONTEXTUAL_ERR("not a valid option: %s", key);11061107    return false;1108}11091110static bool1111parse_section_border(struct context *ctx)1112{1113    struct config *conf = ctx->conf;1114    const char *key = ctx->key;11151116    if (strcmp(key, "width") == 0)1117        return value_to_uint32(ctx, 10, &conf->border.size);11181119    else if (strcmp(key, "radius") == 0)1120        return value_to_uint32(ctx, 10, &conf->border.radius);11211122    else if (strcmp(key, "selection-radius") == 0)1123        return value_to_uint32(ctx, 10, &conf->selection_border.radius);11241125    else1126        LOG_CONTEXTUAL_ERR("not a valid option: %s", key);11271128    return false;1129}11301131static bool1132parse_section_dmenu(struct context *ctx)1133{1134    struct config *conf = ctx->conf;1135    const char *key = ctx->key;11361137    if (strcmp(key, "mode") == 0) {1138        _Static_assert(sizeof(conf->dmenu.mode) == sizeof(int),1139            "enum is not 32-bit");11401141        return value_to_enum(1142            ctx,1143            (const char *[]){"text", "index", NULL},1144            (int *)&conf->dmenu.mode);1145    }11461147    else if (strcmp(key, "exit-immediately-if-empty") == 0)1148        return value_to_bool(ctx, &conf->dmenu.exit_immediately_if_empty);11491150    else1151        LOG_CONTEXTUAL_ERR("not a valid option: %s", key);11521153    return false;1154}11551156static bool1157parse_section_key_bindings(struct context *ctx)1158{1159    for (int action = 0; action < ALEN(binding_action_map); action++) {1160        if (binding_action_map[action] == NULL)1161            continue;11621163        if (strcmp(ctx->key, binding_action_map[action]) != 0)1164            continue;11651166        if (!value_to_key_combos(ctx, action, &ctx->conf->key_bindings))1167            return false;11681169        return true;1170    }11711172    LOG_CONTEXTUAL_ERR("not a valid action: %s", ctx->key);1173    return false;1174}11751176enum section {1177    SECTION_MAIN,1178    SECTION_COLORS,1179    SECTION_BORDER,1180    SECTION_DMENU,1181    SECTION_KEY_BINDINGS,1182    SECTION_COUNT,1183};11841185/* Function pointer, called for each key/value line */1186typedef bool (*parser_fun_t)(struct context *ctx);11871188static const struct {1189    parser_fun_t fun;1190    const char *name;1191} section_info[] = {1192    [SECTION_MAIN] =         {&parse_section_main, "main"},1193    [SECTION_COLORS] =       {&parse_section_colors, "colors"},1194    [SECTION_BORDER] =       {&parse_section_border, "border"},1195    [SECTION_DMENU] =        {&parse_section_dmenu, "dmenu"},1196    [SECTION_KEY_BINDINGS] = {&parse_section_key_bindings, "key-bindings"},1197};11981199static enum section1200str_to_section(const char *str)1201{1202    for (enum section section = SECTION_MAIN; section < SECTION_COUNT; ++section) {1203        if (strcmp(str, section_info[section].name) == 0)1204            return section;1205    }1206    return SECTION_COUNT;1207}12081209static bool1210parse_key_value(char *kv, const char **section, const char **key, const char **value)1211{1212    bool section_is_needed = section != NULL;12131214    /* Strip leading whitespace */1215    while (isspace(kv[0]))1216        ++kv;12171218    if (section_is_needed)1219        *section = "main";12201221    if (kv[0] == '=')1222        return false;12231224    *key = kv;1225    *value = NULL;12261227    size_t kvlen = strlen(kv);12281229    /* Strip trailing whitespace */1230    while (isspace(kv[kvlen - 1]))1231        kvlen--;1232    kv[kvlen] = '\0';12331234    for (size_t i = 0; i < kvlen; ++i) {1235        if (kv[i] == '.' && section_is_needed) {1236            section_is_needed = false;1237            *section = kv;1238            kv[i] = '\0';1239            if (i == kvlen - 1 || kv[i + 1] == '=') {1240                *key = NULL;1241                return false;1242            }1243            *key = &kv[i + 1];1244        } else if (kv[i] == '=') {1245            kv[i] = '\0';1246            if (i != kvlen - 1)1247                *value = &kv[i + 1];1248            break;1249        }1250    }12511252    if (*value == NULL)1253        return false;12541255    /* Strip trailing whitespace from key (leading stripped earlier) */1256    {1257        assert(!isspace(*key[0]));12581259        char *end = (char *)*key + strlen(*key) - 1;1260        while (isspace(end[0]))1261            end--;1262        end[1] = '\0';1263    }12641265    /* Strip leading whitespace from value (trailing stripped earlier) */1266    while (isspace(*value[0]))1267        ++*value;12681269    /* Un-quote1270     *1271     * Note: this is very simple; we only support the *entire* value1272     * being quoted. That is, no mid-value quotes. Both double and1273     * single quotes are supported.1274     *1275     *  - key="value"              OK1276     *  - key=abc "quote" def  NOT OK1277     *  - key=’value’              OK1278     *1279     * Finally, we support escaping the quote character, and the1280     * escape character itself:1281     *1282     *  - key="value \"quotes\""1283     *  - key="backslash: \\"1284     *1285     * ONLY the "current" quote character can be escaped:1286     *1287     *  key="value \'"   NOt OK (both backslash and single quote is kept)1288     */1289    {1290        char *end = (char *)*value + strlen(*value) - 1;1291        if ((*value[0] == '"' && *end == '"') ||1292            (*value[0] == '\'' && *end == '\''))1293        {1294            const char quote = (*value)[0];1295            (*value)++;1296            *end = '\0';12971298            /* Un-escape */1299            for (char *p = (char *)*value; *p != '\0'; p++) {1300                if (p[0] == '\\' && (p[1] == '\\' || p[1] == quote)) {1301                    memmove(p, p + 1, end - p);1302                }1303            }1304        }1305    }13061307    return true;1308}13091310static bool1311parse_config_file(FILE *f, struct config *conf, const char *path,1312                  bool errors_are_fatal)1313{1314    enum section section = SECTION_MAIN;13151316    char *_line = NULL;1317    size_t count = 0;1318    bool ret = true;13191320#define error_or_continue()                     \1321    {                                           \1322        if (errors_are_fatal) {                 \1323            ret = false;                        \1324            goto done;                          \1325        } else                                  \1326            continue;                           \1327    }13281329    char *section_name = xstrdup("main");13301331    struct context context = {1332        .conf = conf,1333        .section = section_name,1334        .path = path,1335        .lineno = 0,1336        .errors_are_fatal = errors_are_fatal,1337    };1338    struct context *ctx = &context;  /* For LOG_AND_*() */13391340    errno = 0;1341    ssize_t len;13421343    while ((len = getline(&_line, &count, f)) != -1) {1344        context.key = NULL;1345        context.value = NULL;1346        context.lineno++;13471348        char *line = _line;13491350        /* Strip leading whitespace */1351        while (isspace(line[0])) {1352            line++;1353            len--;1354        }13551356        /* Empty line, or comment */1357        if (line[0] == '\0' || line[0] == '#')1358            continue;13591360        /* Strip the trailing newline - may be absent on the last line */1361        if (line[len - 1] == '\n')1362            line[--len] = '\0';13631364        /* Split up into key/value pair + trailing comment separated by blank */1365        char *key_value = line;1366        char *kv_trailing = &line[len - 1];1367        char *comment = &line[1];1368        while (comment[1] != '\0') {1369            if (isblank(comment[0]) && comment[1] == '#') {1370                comment[1] = '\0'; /* Terminate key/value pair */1371                kv_trailing = comment++;1372                break;1373            }1374            comment++;1375        }1376        comment++;13771378        /* Strip trailing whitespace */1379        while (isspace(kv_trailing[0]))1380            kv_trailing--;1381        kv_trailing[1] = '\0';13821383        /* Check for new section */1384        if (key_value[0] == '[') {1385            key_value++;13861387            if (key_value[0] == ']') {1388                LOG_CONTEXTUAL_ERR("empty section name");1389                section = SECTION_COUNT;1390                error_or_continue();1391            }13921393            char *end = strchr(key_value, ']');13941395            if (end == NULL) {1396                context.section = key_value;1397                LOG_CONTEXTUAL_ERR("syntax error: no closing ']'");1398                context.section = section_name;1399                section = SECTION_COUNT;1400                error_or_continue();1401            }14021403            end[0] = '\0';14041405            if (end[1] != '\0') {1406                context.section = key_value;1407                LOG_CONTEXTUAL_ERR("section declaration contains trailing "1408                                   "characters");1409                context.section = section_name;1410                section = SECTION_COUNT;1411                error_or_continue();1412            }14131414            section = str_to_section(key_value);1415            if (section == SECTION_COUNT) {1416                context.section = key_value;1417                LOG_CONTEXTUAL_ERR("invalid section name: %s", key_value);1418                context.section = section_name;1419                error_or_continue();1420            }14211422            free(section_name);1423            section_name = xstrdup(key_value);1424            context.section = section_name;14251426            /* Process next line */1427            continue;1428        }14291430        if (section >= SECTION_COUNT) {1431            /* Last section name was invalid; ignore all keys in it */1432            continue;1433        }14341435        if (!parse_key_value(key_value, NULL, &context.key, &context.value)) {1436            LOG_CONTEXTUAL_ERR("syntax error: key/value pair has no %s",1437                               context.key == NULL ? "key" : "value");1438            error_or_continue();1439        }14401441        LOG_DBG("section=%s, key='%s', value='%s', comment='%s'",1442                section_info[section].name, context.key, context.value, comment);14431444        assert(section >= 0 && section < SECTION_COUNT);14451446        parser_fun_t section_parser = section_info[section].fun;1447        assert(section_parser != NULL);14481449        if (!section_parser(ctx))1450            error_or_continue();1451    }14521453    if (errno != 0) {1454        LOG_ERRNO("failed to read from configuration");1455        if (errors_are_fatal)1456            ret = false;1457    }14581459done:1460    free(section_name);1461    free(_line);1462    return ret;1463}14641465static bool1466overrides_apply(struct config *conf, const config_override_t *overrides,1467                bool errors_are_fatal)1468{1469    if (overrides == NULL)1470        goto resolve_key_bindings;14711472    struct context context = {1473        .conf = conf,1474        .path = "override",1475        .lineno = 0,1476        .errors_are_fatal = errors_are_fatal,1477    };1478    struct context *ctx = &context;14791480    tll_foreach(*overrides, it) {1481        context.lineno++;14821483        if (!parse_key_value(1484                it->item, &context.section, &context.key, &context.value))1485        {1486            LOG_CONTEXTUAL_ERR("syntax error: key/value pair has no %s",1487                               context.key == NULL ? "key" : "value");1488            if (errors_are_fatal)1489                return false;1490            continue;1491        }14921493        if (context.section[0] == '\0') {1494            LOG_CONTEXTUAL_ERR("empty section name");1495            if (errors_are_fatal)1496                return false;1497            continue;1498        }14991500        enum section section = str_to_section(context.section);1501        if (section == SECTION_COUNT) {1502            LOG_CONTEXTUAL_ERR("invalid section name: %s", context.section);1503            if (errors_are_fatal)1504                return false;1505            continue;1506        }1507        parser_fun_t section_parser = section_info[section].fun;1508        assert(section_parser != NULL);15091510        if (!section_parser(ctx)) {1511            if (errors_are_fatal)1512                return false;1513            continue;1514        }1515    }15161517resolve_key_bindings:1518    return resolve_key_binding_collisions(1519        conf, section_info[SECTION_KEY_BINDINGS].name, binding_action_map,1520        &conf->key_bindings);1521}15221523#define m_none       {0}1524#define m_alt        {.alt = true}1525#define m_ctrl       {.ctrl = true}1526#define m_shift      {.shift = true}1527#define m_ctrl_shift {.ctrl = true, .shift = true}15281529static void1530add_default_key_bindings(struct config *conf)1531{1532    static const struct config_key_binding bindings[] = {1533        {BIND_ACTION_CANCEL, m_none, {{XKB_KEY_Escape}}},1534        {BIND_ACTION_CANCEL, m_ctrl, {{XKB_KEY_g}}},1535        {BIND_ACTION_CANCEL, m_ctrl, {{XKB_KEY_c}}},1536        {BIND_ACTION_CANCEL, m_ctrl, {{XKB_KEY_bracketleft}}},15371538        {BIND_ACTION_CURSOR_HOME, m_none, {{XKB_KEY_Home}}},1539        {BIND_ACTION_CURSOR_HOME, m_ctrl, {{XKB_KEY_a}}},15401541        {BIND_ACTION_CURSOR_END, m_none, {{XKB_KEY_End}}},1542        {BIND_ACTION_CURSOR_END, m_ctrl, {{XKB_KEY_e}}},15431544        {BIND_ACTION_CURSOR_LEFT, m_ctrl, {{XKB_KEY_b}}},1545        {BIND_ACTION_CURSOR_LEFT, m_none, {{XKB_KEY_Left}}},15461547        {BIND_ACTION_CURSOR_LEFT_WORD, m_alt, {{XKB_KEY_b}}},1548        {BIND_ACTION_CURSOR_LEFT_WORD, m_ctrl, {{XKB_KEY_Left}}},15491550        {BIND_ACTION_CURSOR_RIGHT, m_ctrl, {{XKB_KEY_f}}},1551        {BIND_ACTION_CURSOR_RIGHT, m_none, {{XKB_KEY_Right}}},15521553        {BIND_ACTION_CURSOR_RIGHT_WORD, m_alt, {{XKB_KEY_f}}},1554        {BIND_ACTION_CURSOR_RIGHT_WORD, m_ctrl, {{XKB_KEY_Right}}},15551556        {BIND_ACTION_DELETE_LINE, m_ctrl_shift, {{XKB_KEY_BackSpace}}},15571558        {BIND_ACTION_DELETE_PREV, m_none, {{XKB_KEY_BackSpace}}},1559        {BIND_ACTION_DELETE_PREV, m_ctrl, {{XKB_KEY_h}}},15601561        {BIND_ACTION_DELETE_PREV_WORD, m_ctrl, {{XKB_KEY_BackSpace}}},1562        {BIND_ACTION_DELETE_PREV_WORD, m_ctrl, {{XKB_KEY_w}}},1563        {BIND_ACTION_DELETE_PREV_WORD, m_alt, {{XKB_KEY_BackSpace}}},15641565        {BIND_ACTION_DELETE_NEXT, m_none, {{XKB_KEY_Delete}}},1566        {BIND_ACTION_DELETE_NEXT, m_none, {{XKB_KEY_KP_Delete}}},1567        {BIND_ACTION_DELETE_NEXT, m_ctrl, {{XKB_KEY_d}}},15681569        {BIND_ACTION_DELETE_NEXT_WORD, m_alt, {{XKB_KEY_d}}},1570        {BIND_ACTION_DELETE_NEXT_WORD, m_ctrl, {{XKB_KEY_Delete}}},1571        {BIND_ACTION_DELETE_NEXT_WORD, m_ctrl, {{XKB_KEY_KP_Delete}}},15721573        {BIND_ACTION_DELETE_LINE_BACKWARD, m_ctrl, {{XKB_KEY_u}}},1574        {BIND_ACTION_DELETE_LINE_FORWARD, m_ctrl, {{XKB_KEY_k}}},15751576        {BIND_ACTION_INSERT_SELECTED, m_ctrl, {{XKB_KEY_Tab}}},15771578        {BIND_ACTION_EXPUNGE, m_shift, {{XKB_KEY_Delete}}},1579        {BIND_ACTION_EXPUNGE, m_shift, {{XKB_KEY_KP_Delete}}},15801581        {BIND_ACTION_CLIPBOARD_PASTE, m_ctrl, {{XKB_KEY_v}}},1582        {BIND_ACTION_CLIPBOARD_PASTE, m_none, {{XKB_KEY_XF86Paste}}},1583        {BIND_ACTION_PRIMARY_PASTE, m_shift, {{XKB_KEY_Insert}}},1584        {BIND_ACTION_PRIMARY_PASTE, m_shift, {{XKB_KEY_KP_Insert}}},15851586        {BIND_ACTION_MATCHES_EXECUTE, m_none, {{XKB_KEY_Return}}},1587        {BIND_ACTION_MATCHES_EXECUTE, m_none, {{XKB_KEY_KP_Enter}}},1588        {BIND_ACTION_MATCHES_EXECUTE, m_ctrl, {{XKB_KEY_y}}},15891590        {BIND_ACTION_MATCHES_EXECUTE_OR_NEXT, m_none, {{XKB_KEY_Tab}}},15911592        {BIND_ACTION_MATCHES_EXECUTE_INPUT, m_shift, {{XKB_KEY_Return}}},1593        {BIND_ACTION_MATCHES_EXECUTE_INPUT, m_shift, {{XKB_KEY_KP_Enter}}},15941595        {BIND_ACTION_MATCHES_PREV, m_none, {{XKB_KEY_Up}}},1596        {BIND_ACTION_MATCHES_PREV, m_ctrl, {{XKB_KEY_p}}},1597        {BIND_ACTION_MATCHES_PREV_WITH_WRAP, m_none, {{XKB_KEY_ISO_Left_Tab}}},15981599        {BIND_ACTION_MATCHES_PREV_PAGE, m_none, {{XKB_KEY_Page_Up}}},1600        {BIND_ACTION_MATCHES_PREV_PAGE, m_none, {{XKB_KEY_KP_Page_Up}}},16011602        {BIND_ACTION_MATCHES_NEXT, m_none, {{XKB_KEY_Down}}},1603        {BIND_ACTION_MATCHES_NEXT, m_ctrl, {{XKB_KEY_n}}},16041605        {BIND_ACTION_MATCHES_NEXT_PAGE, m_none, {{XKB_KEY_Page_Down}}},1606        {BIND_ACTION_MATCHES_NEXT_PAGE, m_none, {{XKB_KEY_KP_Page_Down}}},16071608        {BIND_ACTION_MATCHES_FIRST, m_ctrl, {{XKB_KEY_Home}}},1609        {BIND_ACTION_MATCHES_LAST, m_ctrl, {{XKB_KEY_End}}},16101611        {BIND_ACTION_CUSTOM_1, m_alt, {{XKB_KEY_1}}},1612        {BIND_ACTION_CUSTOM_2, m_alt, {{XKB_KEY_2}}},1613        {BIND_ACTION_CUSTOM_3, m_alt, {{XKB_KEY_3}}},1614        {BIND_ACTION_CUSTOM_4, m_alt, {{XKB_KEY_4}}},1615        {BIND_ACTION_CUSTOM_5, m_alt, {{XKB_KEY_5}}},1616        {BIND_ACTION_CUSTOM_6, m_alt, {{XKB_KEY_6}}},1617        {BIND_ACTION_CUSTOM_7, m_alt, {{XKB_KEY_7}}},1618        {BIND_ACTION_CUSTOM_8, m_alt, {{XKB_KEY_8}}},1619        {BIND_ACTION_CUSTOM_9, m_alt, {{XKB_KEY_9}}},1620        {BIND_ACTION_CUSTOM_10, m_alt, {{XKB_KEY_0}}},1621        {BIND_ACTION_CUSTOM_11, m_alt, {{XKB_KEY_exclam}}},1622        {BIND_ACTION_CUSTOM_12, m_alt, {{XKB_KEY_at}}},1623        {BIND_ACTION_CUSTOM_13, m_alt, {{XKB_KEY_numbersign}}},1624        {BIND_ACTION_CUSTOM_14, m_alt, {{XKB_KEY_dollar}}},1625        {BIND_ACTION_CUSTOM_15, m_alt, {{XKB_KEY_percent}}},1626        {BIND_ACTION_CUSTOM_16, m_alt, {{XKB_KEY_dead_circumflex}}},1627        {BIND_ACTION_CUSTOM_17, m_alt, {{XKB_KEY_ampersand}}},1628        {BIND_ACTION_CUSTOM_18, m_alt, {{XKB_KEY_asterisk}}},1629        {BIND_ACTION_CUSTOM_19, m_alt, {{XKB_KEY_parenleft}}},1630    };16311632    conf->key_bindings.count = ALEN(bindings);1633    conf->key_bindings.arr = xmemdup(bindings, sizeof(bindings));1634}16351636bool1637config_load(struct config *conf, const char *conf_path,1638            const config_override_t *overrides, bool errors_are_fatal)1639{1640    bool ret = !errors_are_fatal;1641    *conf = (struct config) {1642        .output = NULL,1643        .namespace = xstrdup("launcher"),1644        .prompt = xc32dup(U"> "),1645        .placeholder = xc32dup(U""),1646        .search_text = xc32dup(U""),1647        .message = NULL,1648        .message_mode = MESSAGE_MODE_WRAP,1649        .match_fields = MATCH_FILENAME | MATCH_NAME | MATCH_GENERIC,1650        .password_mode = {1651            .character = U'\0',1652            .enabled = false,1653        },1654        .terminal = NULL,1655        .launch_prefix = NULL,1656        .font = xstrdup("monospace"),1657        .use_bold = false,1658        .dpi_aware = DPI_AWARE_AUTO,1659        .gamma_correct = false,1660        .render_worker_count = sysconf(_SC_NPROCESSORS_ONLN),1661        .match_worker_count = sysconf(_SC_NPROCESSORS_ONLN),1662        .filter_desktop = false,1663        .icons_enabled = true,1664        .icon_theme = xstrdup("default"),1665        .hide_when_prompt_empty = false,1666        .actions_enabled = false,1667        .match_mode = MATCH_MODE_FZF,1668        .sort_result = true,1669        .match_counter = false,1670        .delayed_filter_ms = 300,1671        .delayed_filter_limit = 20000,1672        .fuzzy = {1673            .min_length = 3,1674            .max_length_discrepancy = 2,1675            .max_distance = 1,1676        },1677        .dmenu = {1678            .enabled = false,1679            .mode = DMENU_MODE_TEXT,1680            .exit_immediately_if_empty = false,1681            .delim = '\n',1682            .nth_delim = '\t',1683            .with_nth_format = NULL,1684            .accept_nth_format = NULL,1685        },1686        .anchor = ANCHOR_CENTER,1687        .margin = {1688            .x = 0,1689            .y = 0,1690        },1691        .lines = 15,1692        .chars = 30,1693        .tabs = 8,1694        .pad = {1695            .x = 40,1696            .y = 8,1697            .inner = 0,1698        },1699        .colors = {1700            .background = conf_hex_to_rgba(0xfdf6e3ff),1701            .border = conf_hex_to_rgba(0x002b36ff),1702            .text = conf_hex_to_rgba(0x657b83ff),1703            .message = conf_hex_to_rgba(0x657b83ff),1704            .prompt = conf_hex_to_rgba(0x586e75ff),1705            .input = conf_hex_to_rgba(0x657b83ff),1706            .match = conf_hex_to_rgba(0xcb4b16ff),1707            .selection = conf_hex_to_rgba(0xeee8d5ff),1708            .selection_text = conf_hex_to_rgba(0x586e75ff),1709            .selection_match = conf_hex_to_rgba(0xcb4b16ff),1710            .counter = conf_hex_to_rgba(0x93a1a1ff),1711            .placeholder = conf_hex_to_rgba(0x93a1a1ff),1712        },1713        .border = {1714            .size = 1u,1715            .radius = 10u,1716        },1717        .selection_border = {1718            .size = 0u,1719            .radius = 0u,1720        },1721        .image_size_ratio = 0.5,1722        .png_scaling_filter = SCALING_FILTER_BOX,1723        .line_height = {-1, 0.0},1724        .letter_spacing = {0},1725        .layer = ZWLR_LAYER_SHELL_V1_LAYER_OVERLAY,1726        .keyboard_focus = ZWLR_LAYER_SURFACE_V1_KEYBOARD_INTERACTIVITY_EXCLUSIVE,1727        .exit_on_kb_focus_loss = true,1728        .list_executables_in_path = false,1729        .cache_path = NULL,1730        .auto_select = false,1731        .print_timing_info = false,1732        .enable_mouse = true,1733    };17341735    add_default_key_bindings(conf);17361737    struct config_file conf_file = {.path = NULL, .fd = -1};17381739    const char *terminal = getenv("TERMINAL");1740    if (terminal != NULL) {1741        conf->terminal = xstrjoin(terminal, " -e");1742    }17431744    if (conf_path != NULL) {1745        int fd = open(conf_path, O_RDONLY | O_CLOEXEC);1746        if (fd < 0) {1747            LOG_ERRNO("%s: failed to open", conf_path);1748            goto out;1749        }17501751        conf_file.path = xstrdup(conf_path);1752        conf_file.fd = fd;1753    } else {1754        conf_file = open_config();1755        if (conf_file.fd < 0) {1756            LOG_WARN("no configuration found, using defaults");1757            ret = true;1758            goto out;1759        }1760    }17611762    LOG_INFO("loading configuration from %s", conf_file.path);17631764    FILE *f = fdopen(conf_file.fd, "r");1765    if (f == NULL) {1766        LOG_ERRNO("%s: failed to open", conf_file.path);1767        goto out;1768    }17691770    if (!parse_config_file(f, conf, conf_file.path, errors_are_fatal) ||1771        !overrides_apply(conf, overrides, errors_are_fatal))1772    {1773        ret = !errors_are_fatal;1774    } else1775        ret = true;17761777    fclose(f);1778    conf_file.fd = -1;17791780out:17811782    free(conf_file.path);1783    if (conf_file.fd >= 0)1784        close(conf_file.fd);17851786    return ret;1787}17881789void1790config_free(struct config *conf)1791{1792    free(conf->namespace);1793    free(conf->output);1794    free(conf->prompt);1795    free(conf->placeholder);1796    free(conf->search_text);1797    free(conf->message);1798    free(conf->terminal);1799    free(conf->launch_prefix);1800    free(conf->font);1801    free(conf->icon_theme);1802    free(conf->cache_path);1803    free(conf->dmenu.with_nth_format);1804    free(conf->dmenu.accept_nth_format);1805    free(conf->dmenu.match_nth_format);1806    free_key_binding_list(&conf->key_bindings);1807}18081809struct rgba1810conf_hex_to_rgba(uint32_t color)1811{1812    return (struct rgba){1813        .r = (double)((color >> 24) & 0xff) / 255.0,1814        .g = (double)((color >> 16) & 0xff) / 255.0,1815        .b = (double)((color >>  8) & 0xff) / 255.0,1816        .a = (double)((color >>  0) & 0xff) / 255.0,1817    };1818}