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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
|
#include <curses.h>
#include <fcntl.h>
#include <stdint.h>
#include <sys/wait.h>
#include <sys/poll.h>
#include <sys/fcntl.h>
#include <signal.h>
#include <dirent.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#define LOAD_BUFSIZ 16384
#define INPUT_BUFSIZ 2048
#define CTRL(x) ((x) & 0x1f)
#define MIN(a, b) ((a) > (b) ? (b) : (a))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
struct nav {
ssize_t wmin, wmax, wlen;
ssize_t sel, min, max;
};
struct entry {
size_t full;
size_t visible;
};
static void sigint_handler(int sig);
static const struct sigaction sigint_action = {
.sa_flags = SA_RESTART,
.sa_handler = sigint_handler
};
static struct sigaction sigwinch_action = {
.sa_flags = SA_RESTART,
.sa_handler = SIG_IGN
};
static int child_fd = -1;
static pid_t child_pid = 0;
static const char **child_argv = NULL;
static pid_t hook_pid = -1;
static char hook_key_arg[6] = { 0 };
static char *hook_argv[4] = { NULL, hook_key_arg, NULL, NULL };
static bool hook_io = false;
static char *run_argv[3] = { NULL, NULL, NULL };
static bool run_cmd = false;
static bool run_io = false;
static char *loadbuf = NULL;
static char *output = NULL;
static size_t output_len = 0;
static size_t output_cap = 0;
static struct entry *entries = NULL;
static size_t entries_len = 0;
static size_t entries_cap = 0;
static struct nav output_nav;
static char *inputbuf = NULL;
static size_t inputlen = 0;
static bool split_args = false;
static bool oneshot = false;
static bool errlog = false;
static char delim = '\n';
static char vis_delim = '|';
static void
die(const char *fmt, ...)
{
va_list ap;
fputs("tquery: ", stderr);
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
if (fmt[0] && fmt[strlen(fmt)-1] == ':') {
fputc(' ', stderr);
perror(NULL);
} else {
fputc('\n', stderr);
}
exit(1);
}
static void
nav_update_win(struct nav *nav)
{
nav->wmin = MAX(nav->wmax - nav->wlen, nav->min);
nav->wmax = MIN(nav->wmin + nav->wlen, nav->max);
nav->sel = MAX(MIN(nav->sel, nav->wmax - 1), nav->wmin);
}
static void
nav_init(struct nav *nav)
{
nav->sel = 0;
nav->min = 0;
nav->max = 0;
nav->wlen = 0;
nav->wmin = 0;
nav->wmax = 0;
}
static void
nav_update_bounds(struct nav *nav, int min, int max)
{
nav->min = min;
nav->max = max;
nav_update_win(nav);
}
static void
nav_update_wlen(struct nav *nav, ssize_t wlen)
{
nav->wlen = wlen;
nav_update_win(nav);
}
static void
nav_update_sel(struct nav *nav, ssize_t sel)
{
nav->sel = MAX(MIN(sel, nav->max - 1), nav->min);
if (nav->sel >= nav->wmax) {
nav->wmax = nav->sel + 1;
nav->wmin = MAX(nav->min, nav->wmax - nav->wlen);
} else if (nav->sel < nav->wmin) {
nav->wmin = nav->sel;
nav->wmax = MIN(nav->wmin + nav->wlen, nav->max);
}
}
static void
invoke(const char **argv, pid_t *pid, int *fd, bool in, bool out, bool err)
{
int out_pipe[2];
if (fd) {
if (*fd >= 0) {
close(*fd);
*fd = -1;
}
if (pipe(out_pipe))
die("pipe:");
}
*pid = fork();
if (*pid < 0) die("fork:");
if (!*pid) {
if (child_fd) close(child_fd);
if (!in || !out || !err) {
int zfd = open("/dev/null", O_RDWR);
if (zfd < 0) die("open /dev/null");
if (!in) dup2(zfd, 0);
if (!out) dup2(zfd, 1);
if (!err) dup2(zfd, 2);
close(zfd);
}
if (fd) {
if (out) dup2(out_pipe[1], 1);
close(out_pipe[0]);
close(out_pipe[1]);
}
execvp(argv[0], (char *const *) argv);
die("execv '%s':", argv[0]);
} else {
if (fd) {
*fd = out_pipe[0];
close(out_pipe[1]);
}
}
}
static void *
addcap(void *alloc, size_t dsize, size_t min, size_t *cap)
{
if (min > *cap) {
*cap = *cap * 2;
if (*cap < min) *cap = min;
alloc = realloc(alloc, dsize * *cap);
if (!alloc) die("realloc:");
}
return alloc;
}
static void
load(void)
{
ssize_t nread;
size_t i;
char *c;
nread = read(child_fd, loadbuf, LOAD_BUFSIZ);
if (nread <= 0) {
child_pid = 0;
close(child_fd);
child_fd = -1;
return;
}
output = addcap(output, 1, output_len + (size_t) nread + 1, &output_cap);
memcpy(output + output_len, loadbuf, (size_t) nread);
if (!entries_cap)
entries = addcap(entries, sizeof(struct entry), 1, &entries_cap);
if (!entries_len) {
entries[0].full = 0;
entries[0].visible = 0;
entries_len = 1;
}
c = output + output_len;
for (i = output_len; i < output_len + (size_t) nread; i++, c++) {
if (*c == vis_delim) {
entries[entries_len-1].visible = i+1;
} else if (*c == delim) {
*c = '\0';
entries = addcap(entries, sizeof(struct entry),
entries_len + 1, &entries_cap);
entries[entries_len].full = i + 1;
entries[entries_len].visible = i + 1;
entries_len++;
}
}
output_len += (size_t) nread;
output[output_len] = '\0';
}
static size_t
num_entries()
{
if (!entries_len) return 0;
if (output_len <= entries[entries_len-1].full)
return entries_len-1;
return entries_len;
}
static char *
full_entry(size_t i)
{
return output + entries[i].full;
}
static char *
vis_entry(size_t i)
{
return output + entries[i].visible;
}
static void
unload(void)
{
int status;
if (!child_pid) return;
kill(child_pid, SIGKILL);
do {
waitpid(child_pid, &status, 0);
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
close(child_fd);
child_fd = -1;
child_pid = 0;
}
static void
update(void)
{
const ssize_t miny = 3;
int width, height;
size_t entry_cnt;
ssize_t i, y;
erase();
width = getmaxx(stdscr);
height = getmaxy(stdscr);
entry_cnt = num_entries();
mvprintw(1, 1, "%lu %li %lu %i", output_len,
output_nav.sel, entry_cnt, child_pid);
mvprintw(2, 1, "> %.*s", width - 1, inputbuf);
nav_update_bounds(&output_nav, 0, (int) entry_cnt);
nav_update_wlen(&output_nav, (int) (height - miny));
if (output_len) {
i = output_nav.wmin;
for (y = miny; y < height && i < output_nav.wmax; y++, i++) {
if (i == output_nav.sel)
attr_on(A_REVERSE, NULL);
mvprintw((int) y, 1, "%.*s", width - 1, vis_entry((size_t) i));
if (i == output_nav.sel)
attr_off(A_REVERSE, NULL);
}
}
move(2, (int) (1 + 2 + inputlen));
refresh();
}
static void
spawn(const char *query)
{
static const char *argv[64];
const char **arg;
const char *tok, *ntok, *end;
size_t argc;
entries_len = 0;
output_len = 0;
argc = 0;
for (arg = child_argv; *arg && argc < 64; arg++) {
if (!strcmp(*arg, "{}")) {
arg += 1;
break;
}
argv[argc++] = *arg;
}
if (split_args) {
ntok = tok = query;
while (ntok && *ntok && argc < 64) {
ntok = strchr(tok, ' ');
end = ntok ? ntok : tok + strlen(tok);
argv[argc++] = strndup(tok, (size_t) (end - tok));
tok = ntok + 1;
}
} else if (argc < 64 && query) {
argv[argc++] = query;
}
for (; *arg && argc < 64; arg++) {
argv[argc++] = *arg;
}
if (argc < 64) {
argv[argc++] = NULL;
} else {
die("Too many arguments");
}
if (child_pid) unload();
invoke(argv, &child_pid, &child_fd, false, true, errlog);
}
static void
run(char *input)
{
if (run_io) {
def_prog_mode();
endwin();
}
int status, pid;
run_argv[1] = input;
invoke((const char **)run_argv, &pid, NULL, run_io, run_io, errlog);
do {
int rc = waitpid(pid, &status, 0);
if (rc != pid) die("waitpid:");
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
if (oneshot) exit(0);
if (run_io) {
reset_prog_mode();
}
if (WIFEXITED(status) && WEXITSTATUS(status) == 3)
spawn(inputbuf);
update();
}
static void
hook(uint8_t key, const char *line)
{
int status, rc;
if (!hook_argv[0]) return;
snprintf(hook_argv[1], 6, "%u", key);
free(hook_argv[2]);
hook_argv[2] = strdup(line);
if (hook_io) {
def_prog_mode();
endwin();
}
invoke((const char **)hook_argv, &hook_pid, NULL, hook_io, hook_io, errlog);
do {
rc = waitpid(hook_pid, &status, 0);
if (rc != hook_pid) die("waitpid:");
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
if (hook_io) {
reset_prog_mode();
}
if (WIFEXITED(status) && WEXITSTATUS(status) == 3)
spawn(inputbuf);
update();
}
static void
input(void)
{
bool dirty;
bool reload;
int c;
dirty = false;
reload = false;
while ((c = getch()) != ERR) {
switch (c) {
case KEY_BACKSPACE:
if (inputlen) inputlen--;
dirty = true;
reload = true;
break;
case KEY_PPAGE:
nav_update_sel(&output_nav,
output_nav.sel - output_nav.wlen / 2);
dirty = true;
break;
case KEY_NPAGE:
nav_update_sel(&output_nav,
output_nav.sel + output_nav.wlen / 2);
dirty = true;
break;
case KEY_DOWN:
nav_update_sel(&output_nav, output_nav.sel + 1);
dirty = true;
break;
case KEY_UP:
nav_update_sel(&output_nav, output_nav.sel - 1);
dirty = true;
break;
case '\x1b':
/* TODO: word-wise seek */
switch (getch()) {
case 'c':
break;
case 'd':
break;
}
break;
case CTRL('w'):
inputlen = 0;
dirty = true;
reload = true;
break;
case CTRL('l'):
clear();
dirty = true;
break;
case CTRL('b'):
nav_update_sel(&output_nav, output_nav.min);
dirty = true;
break;
case CTRL('g'):
nav_update_sel(&output_nav, output_nav.max-1);
dirty = true;
break;
case CTRL('x'):
if (output_nav.max > 0 && output_nav.sel >= 0) {
timeout(-1);
hook((uint8_t)getch(), full_entry((size_t)output_nav.sel));
timeout(0);
}
break;
case '\n':
if (output_nav.max > 0 && output_nav.sel >= 0) {
if (run_cmd) {
run(full_entry((size_t) output_nav.sel));
} else {
puts(full_entry((size_t) output_nav.sel));
if (oneshot) exit(0);
}
}
break;
default:
if (c < 32 || c >= 127)
continue;
if (inputlen < INPUT_BUFSIZ - 1)
inputbuf[inputlen++] = (char) c;
reload = true;
dirty = true;
break;
}
inputbuf[inputlen] = '\0';
}
if (dirty) {
if (reload) spawn(inputbuf);
update();
}
}
static void
sigint_handler(int sig)
{
if (child_pid) {
unload();
update();
} else {
exit(0);
}
}
static void
usage(int rc, bool full)
{
fprintf(stderr, "Usage: tquery [OPT..] -- CMD [ARG..]\n");
if (full) {
fprintf(stderr, "\n");
fprintf(stderr, " -h, --help Show this message\n");
fprintf(stderr, " -d, --delim Set input entry delim\n");
fprintf(stderr, " -D, --vis-delim Set visible entry delim\n");
fprintf(stderr, " -o, --oneshot Exit after oneshot selection\n");
fprintf(stderr, " -e, --stderr Dont close child stderr\n");
fprintf(stderr, " -s, --split Split the query into args\n");
fprintf(stderr, " -r, --run Program to run on Enter\n");
fprintf(stderr, " -R, --run-io Program to run interactively on Enter\n");
fprintf(stderr, " -x, --hook Program to run on Ctrl-X\n");
fprintf(stderr, " -X, --hook-io Program to run interactively on Ctrl-X\n");
fprintf(stderr, "\n");
}
exit(rc);
}
static void
parse(int argc, char **argv)
{
char **arg;
for (arg = &argv[1]; *arg; arg++) {
if (!strcmp(*arg, "-h") || !strcmp(*arg, "--help")) {
usage(0, true);
} else if (!strcmp(*arg, "-o") || !strcmp(*arg, "--oneshot")) {
oneshot = true;
} else if (!strcmp(*arg, "-e") || !strcmp(*arg, "--stderr")) {
errlog = true;
} else if (!strcmp(*arg, "-s") || !strcmp(*arg, "--split")) {
split_args = true;
} else if (!strcmp(*arg, "-d") || !strcmp(*arg, "--delim")) {
delim = **++arg;
} else if (!strcmp(*arg, "-D") || !strcmp(*arg, "--vis-delim")) {
vis_delim = **++arg;
} else if (!strcmp(*arg, "-r") || !strcmp(*arg, "--run")) {
run_argv[0] = *++arg;
run_cmd = true;
} else if (!strcmp(*arg, "-R") || !strcmp(*arg, "--run-io")) {
run_argv[0] = *++arg;
run_cmd = true;
run_io = true;
} else if (!strcmp(*arg, "-x") || !strcmp(*arg, "--hook")) {
hook_argv[0] = *++arg;
} else if (!strcmp(*arg, "-X") || !strcmp(*arg, "--hook-io")) {
hook_argv[0] = *++arg;
hook_io = true;
} else if (!strcmp(*arg, "--")) {
child_argv = (const char **)arg + 1;
break;
} else {
die("unknown option '%s'", arg[0]);
}
}
if (!child_argv || !*child_argv)
usage(0, false);
}
int
main(int argc, char **argv)
{
struct pollfd fds[2];
int rc;
parse(argc, argv);
nav_init(&output_nav);
atexit((void (*)()) endwin);
if (!newterm(NULL, stderr, stdin))
die("newterm stdin -> stderr");
cbreak();
noecho();
keypad(stdscr, true);
sigaction(SIGINT, &sigint_action, NULL);
sigaction(SIGWINCH, NULL, &sigwinch_action);
sigwinch_action.sa_flags |= SA_RESTART;
sigaction(SIGWINCH, &sigwinch_action, NULL);
timeout(0);
spawn("");
inputbuf = malloc(INPUT_BUFSIZ);
if (!inputbuf) die("malloc inputbuf:");
loadbuf = malloc(LOAD_BUFSIZ);
if (!loadbuf) die("malloc loadbuf:");
inputlen = 0;
inputbuf[inputlen] = '\0';
update();
while (1) {
fds[0].fd = 0;
fds[0].events = POLLIN;
fds[1].fd = child_fd;
fds[1].events = POLLIN;
rc = poll(fds, child_pid ? 2 : 1, -1);
if (rc < 0 && errno == EINTR) {
update();
continue;
} else if (rc < 0) {
die("select:");
}
if (fds[0].revents & POLLIN) {
input();
} else if (fds[1].revents & POLLIN) {
load();
update();
} else if (fds[1].revents & POLLHUP) {
unload();
update();
}
}
}
|