Skip to content
Myr

dmenu.c

This file

Path

dmenu.c

346 lines · 10.6 KiB · C

Last changed by

dmenu: fix --index desync when an input entry is droppedStephen Talleybefore adoptiona9d4cab

History of this file

Take it

1#include "dmenu.h"2#include "column.h"3#include "icon.h"45#include <stdlib.h>6#include <stdbool.h>7#include <string.h>8#include <stdio.h>9#include <errno.h>10#include <sys/types.h>11#include <fcntl.h>12#include <poll.h>13#include <uchar.h>14#include <unistd.h>1516#include <tllist.h>1718#define LOG_MODULE "dmenu"19#define LOG_ENABLE_DBG 020#include "log.h"21#include "char32.h"22#include "event.h"23#include "macros.h"24#include "xmalloc.h"2526void27dmenu_load_entries(struct application_list *applications, char delim,28                   const char *with_nth_format, const char *match_nth_format,29                   char nth_delim, int event_fd, int abort_fd)30{31    tll(struct application *) entries = tll_init();3233    size_t size = 0;34    size_t alloc_size = 16384;35    char *buffer = xmalloc(alloc_size);3637    int flags = fcntl(STDIN_FILENO, F_GETFL);38    if (flags < 0 || fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK) < 0) {39        LOG_ERRNO("failed to set O_NONBLOCK on stdin");40        goto out;41    }4243    size_t app_idx = 0;4445    errno = 0;46    while (true) {47        struct pollfd fds[] = {48            {.fd = STDIN_FILENO, .events = POLLIN},4950            /* Must be last */51            {.fd = abort_fd, .events = POLLIN},52        };5354        size_t count = ALEN(fds);55        if (abort_fd < 0)56            count--;5758        int ret = poll(fds, count, -1);59        if (ret < 0) {60            LOG_ERRNO("failed to poll stdin");61            break;62        }6364        if (fds[1].revents & (POLLIN | POLLHUP)) {65            LOG_DBG("aborted");66            break;67        }6869        /* Increase size of input buffer, if necessary */70        if (size >= alloc_size - 2) {71            LOG_DBG("increasing input buffer size %zu -> %zu",72                    alloc_size, alloc_size * 2);7374            alloc_size *= 2;75            buffer = xrealloc(buffer, alloc_size);76        }7778        ssize_t bytes_read = read(79            STDIN_FILENO, &buffer[size], alloc_size - size - 1);8081        if (bytes_read < 0) {82            if (errno == EINTR)83                continue;84            LOG_ERRNO("failed to read from stdin");85            break;86        } else if (bytes_read == 0 && size == 0) {87            /* No more data on stdin, and all buffered data consumed */88            break;89        }9091        size += bytes_read;9293        /*94         * Consume as much as possible from the input buffer95         *96         * Input buffer may contain many lines, resulting in multiple97         * applications being added.98         *99         * Input buffer may not even contain a single line, in which100         * case we can't consume anything at all.101         *102         * Input buffer may contain one or more full lines, followed103         * by a final partial line. If stdin has been closed104         * (i.e. there's no more input to read), then treat the last,105         * partial line as a complete line (i.e. pretend it's followed106         * by a delimiter). But, if stdin is still open, don't consume107         * the last, partial line. Instead, wait for more input.108         */109        while (size > 0) {110            char *delim_at = memchr(buffer, delim, size);111            if (delim_at == NULL) {112                if (bytes_read > 0) {113                    /* No delimiter yet, wait for more data */114                    LOG_DBG("no delimiter found, waiting for more data...");115                    break;116                } else {117                    /* No delimiter, but stdin has been closed. Treat118                       the last chunk of data as a complete line. */119                    LOG_DBG("last line: pointing delim_at to the end of the buffer");120                    delim_at = &buffer[size];121                    size++;122                }123            }124125            const size_t entry_len = delim_at - buffer;126            *delim_at = '\0';127128            /*129             * Support Rofi’s extended dmenu protocol. One can specify130             * an icon by appending ‘\0icon\x1f<icon-name>’ to the131             * entry:132             *133             *  “hello world\0icon\x1ffirefox”134             *135             * We also support fallback icons using comma-separated values.136             * When the primary icon is not found, subsequent icons in the137             * list will be tried until one is successfully loaded:138             *139             *  “hello world\0icon\x1ffirefox,web-browser,application-x-executable”140             */141            char *icon_name = NULL;142            const char *extra = memchr(buffer, '\0', entry_len);143144            if (extra != NULL) {145                const size_t extra_len = delim_at - extra;146147                /*148                 * 'extra' is "\0icon\x1f" - 6 characters. Require149                 * *more* than 6, since icon *name* cannot be empty150                 */151                if (extra_len > 6 && memcmp(extra, "\0icon\x1f", 6) == 0)152                    icon_name = xstrndup(extra + 6, delim_at - (extra + 6));153            }154155            LOG_DBG("%s (icon=%s)", buffer, icon_name);156157            char32_t *wline = ambstoc32(buffer);158159            /* Consume entry from input buffer */160            const size_t consume = delim_at + 1 - buffer;161            assert(consume <= size);162163            memmove(buffer, delim_at + 1, size - consume);164            size -= consume;165166            /*167             * Every delimited chunk of stdin -- valid or not -- occupies one168             * ordinal position in the original input, and --index promises169             * to return that original position. The counter must therefore170             * advance here even when the entry itself is dropped for being171             * unusable (e.g. invalid multibyte data, such as an upstream172             * producer truncating a line mid UTF-8 sequence). Skipping the173             * increment on this path silently shifts the index of every174             * subsequent entry by one for each dropped entry, so an175             * unrelated later item gets selected/executed instead of the176             * one the user actually picked.177             */178            if (wline == NULL) {179                free(icon_name);180                app_idx++;181                continue;182            }183184            char32_t *title = with_nth_format == NULL185                ? xc32dup(wline)186                : nth_column(wline, nth_delim, with_nth_format);187188            char32_t *lowercase = xc32dup(title);189            for (size_t i = 0; i < c32len(lowercase); i++)190                lowercase[i] = toc32lower(lowercase[i]);191192            char32_t *match_nth = match_nth_format != NULL193                ? nth_column(wline, nth_delim, match_nth_format)194                : NULL;195196            if (match_nth != NULL) {197                for (size_t i = 0; i < c32len(match_nth); i++)198                    match_nth[i] = toc32lower(match_nth[i]);199            }200201            struct application *app = xmalloc(sizeof(*app));202            *app = (struct application){203                .index = app_idx++,204                .dmenu_input = wline,205                .dmenu_match_nth = match_nth,206                .dmenu_match_nth_len = match_nth != NULL ? c32len(match_nth) : 0,207                .title = title,208                .title_lowercase = lowercase,209                .title_len = c32len(lowercase),210                .icon = {.name = icon_name},211                .visible = true,212            };213214            tll_push_back(entries, app);215        }216217        if (event_fd >= 0) {218            mtx_lock(&applications->lock);219220            const size_t new_count = applications->count + tll_length(entries);221            if (new_count > 0) {222                applications->v = xreallocarray(223                    applications->v, new_count, sizeof(applications->v[0]));224225                size_t i = applications->count;226                tll_foreach(entries, it) {227                    applications->v[i++] = it->item;228                    tll_remove(entries, it);229                }230231                assert(i == new_count);232                applications->count = applications->visible_count = new_count;233                send_event(event_fd, EVENT_APPS_SOME_LOADED);234            }235236            mtx_unlock(&applications->lock);237        }238    }239240    free(buffer);241242out:243244    if (tll_length(entries) == 0)245        return;246247    mtx_lock(&applications->lock);248249    const size_t new_count = applications->count + tll_length(entries);250    applications->v = xreallocarray(251        applications->v, new_count, sizeof(applications->v[0]));252253    size_t i = applications->count;254    tll_foreach(entries, it) {255        applications->v[i++] = it->item;256        tll_remove(entries, it);257    }258259    applications->count = applications->visible_count = new_count;260    mtx_unlock(&applications->lock);261262    tll_free(entries);263}264265bool266dmenu_execute(const struct application *app, ssize_t index,267              const struct prompt *prompt, enum dmenu_mode format,268              const char *nth_format, char nth_delim)269{270    switch (format) {271    case DMENU_MODE_TEXT: {272        const char32_t *output = app != NULL273            ? app->dmenu_input274            : prompt_text(prompt);275276        char32_t *column_output = NULL;277        if (nth_format != NULL) {278            column_output = nth_column(output, nth_delim, nth_format);279            output = column_output;280        }281282        char *text = ac32tombs(output);283        if (text != NULL)284            printf("%s\n", text);285286        free(column_output);287        free(text);288        break;289    }290291    case DMENU_MODE_INDEX:292        printf("%zd\n", index);293        break;294    }295296    return true;297}298299static void300try_icon_list(struct application *app, icon_theme_list_t themes, int icon_size)301{302    if (app->icon.name == NULL || strchr(app->icon.name, ',') == NULL)303        return;304305    if (app->icon.type != ICON_NONE) {306        return;307    }308309    char *icon_list = xstrdup(app->icon.name);310    char *saveptr = NULL;311312    for (char *icon_name = strtok_r(icon_list, ",", &saveptr);313         icon_name != NULL;314         icon_name = strtok_r(NULL, ",", &saveptr))315    {316        free(app->icon.name);317        app->icon.name = xstrdup(icon_name);318319        app->icon.type = ICON_NONE;320        app->icon.path = NULL;321        app->icon.svg = NULL;322        app->icon.png = NULL;323324        struct application_list temp_list = {325            .v = &app,326            .count = 1,327            .visible_count = 1328        };329330        icon_lookup_application_icons(themes, icon_size, &temp_list);331332        if (app->icon.type != ICON_NONE)333            break;334    }335336    free(icon_list);337}338339void340dmenu_try_icon_list(struct application_list *applications, icon_theme_list_t themes, int icon_size)341{342    for (size_t i = 0; i < applications->count; i++) {343        struct application *app = applications->v[i];344        try_icon_list(app, themes, icon_size);345    }346}