summaryrefslogtreecommitdiff
path: root/client/client.c
blob: 2f95d524ac17292bf77abb2f96b3228b03872777 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <bemenu.h>

static void readItemsToMenuFromStdin(bmMenu *menu)
{
    assert(menu);

    size_t step = 1024, allocated;
    char *buffer;

    if (!(buffer = malloc((allocated = step))))
        return;

    size_t read;
    while ((read = fread(buffer + (allocated - step), 1, step, stdin)) == step) {
        void *tmp;
        if (!(tmp = realloc(buffer, (allocated += step)))) {
            free(buffer);
            return;
        }
        buffer = tmp;
    }
    buffer[allocated - step + read - 1] = 0;

    size_t pos;
    char *s = buffer;
    while ((pos = strcspn(s, "\n")) != 0) {
        size_t next = pos + (s[pos] != 0);
        s[pos] = 0;

        bmItem *item = bmItemNew(s);
        if (!item)
            break;

        bmMenuAddItem(menu, item);
        s += next;
    }

    free(buffer);
}

int main(int argc, char **argv)
{
    (void)argc, (void)argv;

    bmMenu *menu = bmMenuNew(BM_DRAW_MODE_CURSES);
    if (!menu)
        return EXIT_FAILURE;

    bmMenuSetTitle(menu, "bemenu");
    readItemsToMenuFromStdin(menu);

    bmKey key;
    unsigned int unicode;
    int status = 0;
    do {
        bmMenuRender(menu);
        key = bmMenuGetKey(menu, &unicode);
    } while ((status = bmMenuRunWithKey(menu, key, unicode)) == BM_RUN_RESULT_RUNNING);

    if (status == BM_RUN_RESULT_SELECTED) {
        unsigned int i, count;
        bmItem **items = bmMenuGetSelectedItems(menu, &count);
        for (i = 0; i < count; ++i) {
            const char *text = bmItemGetText(items[i]);
            printf("%s\n", (text ? text : ""));
        }

        if (!count && bmMenuGetFilter(menu))
            printf("%s\n", bmMenuGetFilter(menu));
    }

    bmMenuFree(menu);
    return (status == BM_RUN_RESULT_SELECTED ? EXIT_SUCCESS : EXIT_FAILURE);
}

/* vim: set ts=8 sw=4 tw=0 :*/