aboutsummaryrefslogtreecommitdiff
path: root/ask.c
blob: 38f32018d799be6d67888a1f3d2f0aa195c6c43b (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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/* ask - a simple command line asker
 * Copyright 2019 Bruce Hill
 * Released under the MIT License (see LICENSE for details)
 * Usage: ask [-p | --password] [-q | --quickpick] [prompt [initial value]]
 *    -p: password mode
 *    -q: quickpick mode (exit when only one option remains)
 */
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <termios.h>
#include <unistd.h>

#include "bterm.h"

static int password = 0, quickpick = 0, case_sensitive = 0, to_skip = 0;

#define LOWERCASE(c) ('A' <= (c) && (c) <= 'Z' ? ((c) + 'a' - 'A') : (c))
#define EQ(a, b) (case_sensitive ? (a) == (b) : LOWERCASE(a) == LOWERCASE(b))

static inline void *memcheck(void *p)
{
    if (!p) {
        fprintf(stderr, "Memory allocation failure\n");
        exit(1);
    }
    return p;
}

static int score(const char *str, const char *patt)
{
    if (!patt[0]) return 0;
    int score = 0;
    const char *sp = str, *pp = patt;
    while (*sp && !EQ(*sp, *pp)) ++sp;
    while (*sp && *pp && EQ(*sp, *pp)) {
        ++score;
        ++sp;
        ++pp;
    }
    for (; *pp; ++sp, ++pp) {
        while (*sp && !EQ(*sp, *pp)) ++sp;
        if (!*sp) return 0;
    }
    if (*pp && !*sp) return 0;
    return score;
}

static void draw_line(FILE *out, const char *line, const char *hl, const char *cur)
{
    int dim = 0, backtrack = 0;
    for (const char *pl = line, *phl = hl; *pl; pl++) {
        if (phl >= cur) ++backtrack;
        if (case_sensitive ? *pl == *phl : LOWERCASE(*pl) == LOWERCASE(*phl)) {
            ++phl;
            if (dim) {
                fputs("\033[22m", out);
                dim = 0;
            }
        } else if (!dim) {
            fputs("\033[2m", out);
            dim = 1;
        }
        fputc(*pl, out);
    }
    if (backtrack)
        fprintf(out, "\033[%dD", backtrack);
}

/*
 * A basic fuzzy matcher and line inputter
 */
static char *get_input(FILE *in, FILE *out, const char *prompt, const char *initial, int nopts, char **opts)
{
    size_t cap = initial ? strlen(initial) + 100 : 100;
    char *buf = memcheck(calloc(cap, 1));
    char *picked = NULL;
    int b = 0, len = 0;
    if (initial) {
        if (!strcpy(buf, initial)) return NULL;
        len = (int)strlen(initial);
        b = len;
        fputs(initial, out);
    }

    // Show cursor and set to blinking line:
    while (1) {
        fputs("\033[G\033[K\033[0m", out);
        if (prompt) {
            fputs("\033[1G\033[K\033[37;1m", out);
            fputs(prompt, out);
            fputs("\033[0m", out);
        }
        picked = NULL;
        case_sensitive = 0;
        for (const char *p = buf; *p; ++p)
            case_sensitive |= ('A' <= *p && *p <= 'Z');

        int ncandidates = 0;
        for (int i = 0; i < nopts; i++)
            ncandidates += score(opts[i], buf) > 0;

        int bestscore = 0;
        char *best = NULL;
        int skipped = 0;
        for (int i = 0; i < nopts; i++) {
            int s = score(opts[i], buf);
            if (s && skipped < to_skip) {
                ++skipped;
                continue;
            }
            if (s > bestscore) {
                best = opts[i];
                bestscore = s;
            }
        }
        if (quickpick && ncandidates == 1 && best)
            return best;

        picked = best;
        if (best) {
            draw_line(out, best, buf, &buf[b]);
        } else {
            if (nopts > 0)
                fprintf(out, "\033[0;31m%s\033[0m", buf);
            else
                fprintf(out, "\033[0m%s\033[0m", buf);
            if (b < (int)strlen(buf))
                fprintf(out, "\033[%dD", (int)strlen(buf) - b);
        }
        fflush(out);
        int key;
      skip_redraw:
        key = bgetkey(in, NULL, NULL, -1);
        switch (key) {
            case -1: case -2: case -3: goto skip_redraw;
            case '\r':
                // TODO: support backslash-enter
                goto finished;
            case KEY_CTRL_C: case KEY_ESC:
                free(buf);
                buf = NULL;
                picked = NULL;
                goto finished;
            case KEY_CTRL_A:
                if (b > 0) b = 0;
                break;
            case KEY_CTRL_E:
                if (b < len) b = len;
                break;
            case KEY_CTRL_U: {
                int to_clear = b;
                if (to_clear) {
                    memmove(buf, buf+b, (size_t)(len-b));
                    buf[len -= b] = 0;
                    b = 0;
                }
                break;
            }
            case KEY_CTRL_K:
                if (b < len)
                    buf[len = b] = 0;
                break;
            case KEY_CTRL_N:
                if (ncandidates)
                    to_skip = (to_skip + 1) % ncandidates;
                break;
            case KEY_CTRL_P:
                if (ncandidates)
                    to_skip = (to_skip + ncandidates - 1) % ncandidates;
                break;
            case KEY_BACKSPACE: case KEY_BACKSPACE2:
                if (b > 0) {
                    --b;
                    memmove(buf+b, buf+b+1, (size_t)(len-b));
                    buf[--len] = 0;
                }
                break;
            case KEY_DELETE: case KEY_CTRL_D:
                if (b < len) {
                    memmove(buf+b, buf+b+1, (size_t)(len-b));
                    buf[--len] = 0;
                }
                break;
            case KEY_ARROW_LEFT: case KEY_CTRL_B:
                if (b > 0) --b;
                break;
            case KEY_ARROW_RIGHT: case KEY_CTRL_F:
                if (b < len) ++b;
                break;
            default:
                if (' ' <= key && key <= '~') {
                    if (len + 1 >= (int)cap)
                        buf = memcheck(realloc(buf, (cap += 100)));
                    if (b < len)
                        memmove(buf+b+1, buf+b, (size_t)(len-b+1));
                    buf[b++] = (char)key;
                    buf[++len] = 0;
                }
                break;
        }
    }
  finished:
    if (picked) picked = memcheck(strdup(picked));
    else picked = buf;
    return picked;
}

int main(int argc, char *argv[])
{
    FILE *tty_in = fopen("/dev/tty", "r");
    FILE *tty_out = fopen("/dev/tty", "w");
    struct termios orig_termios, bb_termios;
    tcgetattr(fileno(tty_out), &orig_termios);
    cfmakeraw(&bb_termios);
    if (tcsetattr(fileno(tty_out), TCSAFLUSH, &bb_termios) == -1)
        return 1;

    char *prompt = NULL, *initial = NULL;
    char **lines = NULL;
    size_t linescap = 0, linecap = 0;
    int nlines = 0;
    char *line = NULL;
    struct pollfd pfd = {STDIN_FILENO, POLLIN, 0};
    if (poll(&pfd, 1, 50) > 0) {
        while ((getline(&line, &linecap, stdin)) >= 0) {
            if ((size_t)nlines >= linescap)
                lines = memcheck(realloc(lines, (linescap += 100)*sizeof(char*)));
            if (!line[0]) continue;
            if (line[strlen(line)-1] == '\n')
                line[strlen(line)-1] = '\0';
            lines[nlines++] = memcheck(strdup(line));
        }
    }
    int a = 1;
    while (a < argc) {
        if (strcmp(argv[a], "-p") == 0 || strcmp(argv[a], "--password") == 0) {
            password = 1;
        } else if (strcmp(argv[a], "-q") == 0 || strcmp(argv[a], "--quickpick") == 0) {
            quickpick = 1;
        } else break;
        ++a;
    }
    if (!prompt && a < argc) prompt = argv[a++];
    if (!initial && a < argc) initial = argv[a++];

    while (a < argc) {
        if ((size_t)nlines >= linescap)
            lines = memcheck(realloc(lines, (linescap += 100)*sizeof(char*)));
        lines[nlines++] = argv[a++];
    }

    char *output = get_input(tty_in, tty_out, prompt, initial, nlines, lines);

    fputs("\033[G\033[K\033[0m", tty_out);
    fflush(tty_out);
    tcsetattr(fileno(tty_out), TCSAFLUSH, &orig_termios);
    fclose(tty_out);
    tty_out = NULL;
    fclose(tty_in);
    tty_in = NULL;

    if (!output) return 1;

    puts(output);
    free(output);

    // This doesn't free the memory in lines, but it doesn't need to because
    // the program is exiting
    return 0;
}
// vim: ts=4 sw=0 et cino=L2,l1,(0,W4,m1