bemenu/client/client.c

81 lines
1.8 KiB
C
Raw Normal View History

2014-03-18 17:35:10 +00:00
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <bemenu.h>
2014-03-18 17:35:10 +00:00
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;
2014-04-12 16:59:21 +00:00
size_t pos;
char *s = buffer;
while ((pos = strcspn(s, "\n")) != 0) {
size_t next = pos + (s[pos] != 0);
2014-04-12 16:59:21 +00:00
s[pos] = 0;
bmItem *item = bmItemNew(s);
if (!item)
break;
bmMenuAddItem(menu, item);
s += next;
}
free(buffer);
}
2014-03-18 17:35:10 +00:00
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);
2014-04-12 11:15:37 +00:00
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);
2014-03-18 17:35:10 +00:00
}
/* vim: set ts=8 sw=4 tw=0 :*/