cd5fa8a81a4878aaf5c65342432a76888ff517f9
[paraslash.git] / interactive.c
1 /*
2 * Copyright (C) 2011-2012 Andre Noll <maan@systemlinux.org>
3 *
4 * Licensed under the GPL v2. For licencing details see COPYING.
5 */
6
7 /** \file interactive.c Readline abstraction for interactive sessions. */
8
9 #include <regex.h>
10 #include <stdbool.h>
11 #include <curses.h>
12 #include <readline/readline.h>
13 #include <readline/history.h>
14 #include <sys/ioctl.h>
15 #include <assert.h>
16 #include <signal.h>
17
18 #include "para.h"
19 #include "fd.h"
20 #include "buffer_tree.h"
21 #include "list.h"
22 #include "sched.h"
23 #include "interactive.h"
24 #include "string.h"
25 #include "error.h"
26
27 struct i9e_private {
28 struct i9e_client_info *ici;
29 FILE *stderr_stream;
30 int num_columns;
31 char empty_line[1000];
32 struct task task;
33 struct btr_node *stdout_btrn;
34 bool line_handler_running;
35 bool input_eof;
36 bool caught_sigint;
37 bool caught_sigterm;
38 };
39 static struct i9e_private i9e_private, *i9ep = &i9e_private;
40
41 /**
42 * Return the error state of the i9e task.
43 *
44 * This is mainly useful for other tasks to tell whether the i9e task is still
45 * running.
46 *
47 * \return A negative return value of zero means the i9e task terminated. Only
48 * in this case it is safe to call ie9_close().
49 */
50 int i9e_get_error(void)
51 {
52 return i9ep->task.error;
53 }
54
55 static bool is_prefix(const char *partial, const char *full, size_t len)
56 {
57 if (len == 0)
58 len = strlen(partial);
59 return !strncmp(partial, full, len);
60 }
61
62 /*
63 * Generator function for command completion. STATE lets us know whether
64 * to start from scratch; without any state (i.e. STATE == 0), then we
65 * start at the top of the list.
66 */
67 static char *command_generator(const char *text, int state)
68 {
69 static int list_index, len;
70 const char *name;
71 struct i9e_client_info *ici = i9ep->ici;
72
73 rl_attempted_completion_over = 1; /* disable filename completion */
74 /*
75 * If this is a new word to complete, initialize now. This includes
76 * saving the length of TEXT for efficiency, and initializing the index
77 * variable to 0.
78 */
79 if (state == 0) {
80 list_index = 0;
81 len = strlen(text);
82 }
83 /* Return the next name which partially matches from the command list. */
84 while ((name = ici->completers[list_index].name)) {
85 list_index++;
86 if (is_prefix(text, name, len))
87 return para_strdup(name);
88 }
89 return NULL; /* no names matched */
90 }
91
92 static void reset_completion_result(struct i9e_completion_result *cr)
93 {
94 cr->dont_append_space = false;
95 cr->filename_completion_desired = false;
96 cr->matches = NULL;
97 }
98
99 static void create_matches(struct i9e_completion_info *ci,
100 struct i9e_completer *completers,
101 struct i9e_completion_result *cr)
102 {
103 int i, ret;
104
105 reset_completion_result(cr);
106
107 ret = create_argv(ci->buffer, " ", &ci->argv);
108 if (ret < 0 || !ci->argv[0])
109 return;
110
111 ci->argc = ret;
112 ci->word_num = compute_word_num(ci->buffer, " ", ci->point);
113 for (i = 0; completers[i].name; i++) {
114 if (strcmp(completers[i].name, ci->argv[0]) != 0)
115 continue;
116 completers[i].completer(ci, cr);
117 break;
118 }
119 PARA_DEBUG_LOG("current word: %d (%s)\n", ci->word_num,
120 ci->argv[ci->word_num]);
121 if (cr->matches)
122 for (i = 0; cr->matches[i]; i++)
123 PARA_DEBUG_LOG("match %d: %s\n", i, cr->matches[i]);
124 }
125
126 static char *completion_generator(const char *word, int state)
127 {
128 static int list_index;
129 static char **argv, **matches;
130 struct i9e_completer *completers = i9ep->ici->completers;
131 struct i9e_completion_info ci = {
132 .word = (char *)word,
133 .point = rl_point,
134 .buffer = rl_line_buffer,
135 };
136 struct i9e_completion_result cr = {.matches = NULL};
137
138 if (state != 0)
139 goto out;
140 /* clean up previous matches and set defaults */
141 free(matches);
142 matches = NULL;
143 free_argv(argv);
144 argv = NULL;
145 list_index = 0;
146 rl_completion_append_character = ' ';
147 rl_completion_suppress_append = false;
148 rl_attempted_completion_over = true;
149
150 create_matches(&ci, completers, &cr);
151
152 matches = cr.matches;
153 argv = ci.argv;
154 rl_completion_suppress_append = cr.dont_append_space;
155 rl_attempted_completion_over = !cr.filename_completion_desired;
156 out:
157 if (!matches)
158 return NULL;
159 return matches[list_index++];
160 }
161
162 /*
163 * Attempt to complete on the contents of TEXT. START and END bound the
164 * region of rl_line_buffer that contains the word to complete. TEXT is
165 * the word to complete. We can use the entire contents of rl_line_buffer
166 * in case we want to do some simple parsing. Return the array of matches,
167 * or NULL if there aren't any.
168 */
169 static char **i9e_completer(const char *text, int start, __a_unused int end)
170 {
171 struct i9e_client_info *ici = i9ep->ici;
172
173 if (!ici->completers)
174 return NULL;
175 /* Complete on command names if this is the first word in the line. */
176 if (start == 0)
177 return rl_completion_matches(text, command_generator);
178 return rl_completion_matches(text, completion_generator);
179 }
180
181 /**
182 * Prepare writing to stdout.
183 *
184 * \param producer The buffer tree node which produces output.
185 *
186 * The i9e subsystem maintains a buffer tree node which may be attached to
187 * another node which generates output (a "producer"). When attached, the i9e
188 * buffer tree node copies the buffers generated by the producer to stdout.
189 *
190 * This function attaches the i9e input queue to an output queue of \a
191 * producer.
192 *
193 * \return Standard.
194 */
195 void i9e_attach_to_stdout(struct btr_node *producer)
196 {
197 btr_remove_node(&i9ep->stdout_btrn);
198 i9ep->stdout_btrn = btr_new_node(&(struct btr_node_description)
199 EMBRACE(.name = "interactive_stdout", .parent = producer));
200 }
201
202 static void wipe_bottom_line(void)
203 {
204 char x[] = " ";
205 int n = i9ep->num_columns;
206
207 /*
208 * For reasons beyond my understanding, writing more than 68 characters
209 * here causes MacOS to mess up the terminal. Writing a line of spaces
210 * in smaller chunks works fine though. Weird.
211 */
212 fprintf(i9ep->stderr_stream, "\r");
213 while (n > 0) {
214 if (n >= sizeof(x)) {
215 fprintf(i9ep->stderr_stream, "%s", x);
216 n -= sizeof(x);
217 continue;
218 }
219 x[n] = '\0';
220 fprintf(i9ep->stderr_stream, "%s", x);
221 break;
222 }
223 fprintf(i9ep->stderr_stream, "\r");
224 }
225
226 /**
227 * Reset the terminal and save the in-memory command line history.
228 *
229 * This should be called before the caller exits.
230 */
231 void i9e_close(void)
232 {
233 char *hf = i9ep->ici->history_file;
234
235 rl_deprep_terminal();
236 if (hf)
237 write_history(hf);
238 wipe_bottom_line();
239 }
240
241 static void clear_bottom_line(void)
242 {
243 int point;
244 char *text;
245
246 if (rl_point == 0 && rl_end == 0)
247 return wipe_bottom_line();
248 /*
249 * We might have a multi-line input that needs to be wiped here, so the
250 * simple printf("\r<space>\r") is insufficient. To workaround this, we
251 * remove the whole line, redisplay and restore the killed text.
252 */
253 point = rl_point;
254 text = rl_copy_text(0, rl_end);
255 rl_kill_full_line(0, 0);
256 rl_redisplay();
257 wipe_bottom_line(); /* wipe out the prompt */
258 rl_insert_text(text);
259 rl_point = point;
260 }
261
262 static bool input_available(void)
263 {
264 fd_set rfds;
265 struct timeval tv = {0, 0};
266 int ret;
267
268 FD_ZERO(&rfds);
269 FD_SET(i9ep->ici->fds[0], &rfds);
270 ret = para_select(1, &rfds, NULL, &tv);
271 return ret > 0;
272 }
273
274 static void i9e_line_handler(char *line)
275 {
276 int ret;
277
278 ret = i9ep->ici->line_handler(line);
279 if (ret < 0)
280 PARA_WARNING_LOG("%s\n", para_strerror(-ret));
281 rl_set_prompt("");
282 if (line) {
283 if (!*line)
284 rl_set_prompt(i9ep->ici->prompt);
285 else
286 add_history(line);
287 free(line);
288 } else {
289 rl_set_prompt("");
290 i9ep->input_eof = true;
291 }
292 }
293
294 static void i9e_input(void)
295 {
296 do {
297 rl_callback_read_char();
298 } while (input_available());
299 }
300
301 static void i9e_post_select(struct sched *s, struct task *t)
302 {
303 int ret;
304 struct btr_node *btrn = i9ep->stdout_btrn;
305 struct i9e_client_info *ici = i9ep->ici;
306 char *buf;
307 size_t sz;
308
309 ret = -E_I9E_EOF;
310 if (i9ep->input_eof)
311 goto rm_btrn;
312 ret = -E_I9E_TERM_RQ;
313 if (i9ep->caught_sigterm)
314 goto rm_btrn;
315 if (!btrn) {
316 i9ep->caught_sigint = false;
317 if (FD_ISSET(ici->fds[0], &s->rfds))
318 i9e_input();
319 return;
320 }
321 ret = 0;
322 if (i9ep->caught_sigint)
323 goto rm_btrn;
324 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
325 if (ret < 0)
326 goto rm_btrn;
327 sz = btr_next_buffer(btrn, &buf);
328 if (sz == 0)
329 goto out;
330 ret = xwrite(ici->fds[1], buf, sz);
331 if (ret < 0)
332 goto rm_btrn;
333 btr_consume(btrn, ret);
334 goto out;
335 rm_btrn:
336 btr_remove_node(&i9ep->stdout_btrn);
337 rl_set_prompt(i9ep->ici->prompt);
338 rl_redisplay();
339 out:
340 t->error = 0;
341 }
342
343 static void i9e_pre_select(struct sched *s, __a_unused struct task *t)
344 {
345 int ret;
346
347 if (i9ep->input_eof || i9ep->caught_sigint || i9ep->caught_sigterm) {
348 sched_min_delay(s);
349 return;
350 }
351 if (i9ep->stdout_btrn) {
352 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
353 if (ret < 0) {
354 sched_min_delay(s);
355 return;
356 }
357 if (ret > 0)
358 para_fd_set(i9ep->ici->fds[1], &s->wfds, &s->max_fileno);
359 }
360 /*
361 * fd[0] might have been reset to blocking mode if our job was moved to
362 * the background due to CTRL-Z or SIGSTOP, so set the fd back to
363 * nonblocking mode.
364 */
365 ret = mark_fd_nonblocking(i9ep->ici->fds[0]);
366 if (ret < 0)
367 PARA_WARNING_LOG("set to nonblock failed: (fd0 %d, %s)\n",
368 i9ep->ici->fds[0], para_strerror(-ret));
369 para_fd_set(i9ep->ici->fds[0], &s->rfds, &s->max_fileno);
370 }
371
372 static void update_winsize(void)
373 {
374 struct winsize w;
375 int ret = ioctl(i9ep->ici->fds[2], TIOCGWINSZ, (char *)&w);
376
377 if (ret >= 0) {
378 assert(w.ws_col < sizeof(i9ep->empty_line));
379 i9ep->num_columns = w.ws_col;
380 } else
381 i9ep->num_columns = 80;
382
383 memset(i9ep->empty_line, ' ', i9ep->num_columns);
384 i9ep->empty_line[i9ep->num_columns] = '\0';
385 }
386
387 /**
388 * Register the i9e task and initialize readline.
389 *
390 * \param ici The i9e configuration parameters set by the caller.
391 * \param s The scheduler instance to add the i9e task to.
392 *
393 * The caller must allocate and initialize the structure \a ici points to.
394 *
395 * \return Standard.
396 * \sa \ref register_task().
397 */
398 int i9e_open(struct i9e_client_info *ici, struct sched *s)
399 {
400 int ret;
401
402 if (!isatty(ici->fds[0]))
403 return -E_I9E_SETUPTERM;
404 ret = mark_fd_nonblocking(ici->fds[0]);
405 if (ret < 0)
406 return ret;
407 ret = mark_fd_nonblocking(ici->fds[1]);
408 if (ret < 0)
409 return ret;
410 i9ep->task.pre_select = i9e_pre_select;
411 i9ep->task.post_select = i9e_post_select;
412 sprintf(i9ep->task.status, "i9e");
413 register_task(s, &i9ep->task);
414 rl_readline_name = "para_i9e";
415 rl_basic_word_break_characters = " ";
416 rl_attempted_completion_function = i9e_completer;
417 i9ep->ici = ici;
418 i9ep->stderr_stream = fdopen(ici->fds[2], "w");
419 setvbuf(i9ep->stderr_stream, NULL, _IONBF, 0);
420
421 if (ici->history_file)
422 read_history(ici->history_file);
423 update_winsize();
424 rl_callback_handler_install(i9ep->ici->prompt, i9e_line_handler);
425 return 1;
426 }
427
428 static void reset_line_state(void)
429 {
430 if (i9ep->stdout_btrn)
431 return;
432 rl_on_new_line();
433 rl_reset_line_state();
434 rl_forced_update_display();
435 }
436
437 /**
438 * The log function of the i9e subsystem.
439 *
440 * \param ll Severity log level.
441 * \param fmt Printf-like format string.
442 *
443 * This clears the bottom line of the terminal if necessary and writes the
444 * string given by \a fmt to fd[2], where fd[] is the array provided earlier in
445 * \ref i9e_open().
446 */
447 __printf_2_3 void i9e_log(int ll, const char* fmt,...)
448 {
449 va_list argp;
450
451 if (ll < i9ep->ici->loglevel)
452 return;
453 clear_bottom_line();
454 va_start(argp, fmt);
455 vfprintf(i9ep->stderr_stream, fmt, argp);
456 va_end(argp);
457 reset_line_state();
458 }
459
460 /**
461 * Tell i9e that the caller received a signal.
462 *
463 * \param sig_num The number of the signal received.
464 *
465 * Currently the function only cares about \p SIGINT, but this may change.
466 */
467 void i9e_signal_dispatch(int sig_num)
468 {
469 if (sig_num == SIGWINCH)
470 return update_winsize();
471 if (sig_num == SIGINT) {
472 fprintf(i9ep->stderr_stream, "\n");
473 rl_replace_line ("", false /* clear_undo */);
474 reset_line_state();
475 i9ep->caught_sigint = true;
476 }
477 if (sig_num == SIGTERM)
478 i9ep->caught_sigterm = true;
479 }
480
481 /**
482 * Wrapper for select(2) which does not restart on interrupts.
483 *
484 * \param n \sa \ref para_select().
485 * \param readfds \sa \ref para_select().
486 * \param writefds \sa \ref para_select().
487 * \param timeout_tv \sa \ref para_select().
488 *
489 * \return \sa \ref para_select().
490 *
491 * The only difference between this function and \ref para_select() is that
492 * \ref i9e_select() returns zero if the select call returned \p EINTR.
493 */
494 int i9e_select(int n, fd_set *readfds, fd_set *writefds,
495 struct timeval *timeout_tv)
496 {
497 int ret = select(n, readfds, writefds, NULL, timeout_tv);
498
499 if (ret < 0) {
500 if (errno == EINTR)
501 ret = 0;
502 else
503 ret = -ERRNO_TO_PARA_ERROR(errno);
504 }
505 return ret;
506 }
507
508 /**
509 * Return the possible completions for a given word.
510 *
511 * \param word The word to complete.
512 * \param string_list All possible words in this context.
513 * \param result String list is returned here.
514 *
515 * This function never fails. If no completion was found, a string list of
516 * length zero is returned. In any case, the result must be freed by the caller
517 * using \ref free_argv().
518 *
519 * This function is independent of readline and may be called before
520 * i9e_open().
521 *
522 * \return The number of possible completions.
523 */
524 int i9e_extract_completions(const char *word, char **string_list,
525 char ***result)
526 {
527 char **matches = para_malloc(sizeof(char *));
528 int match_count = 0, matches_len = 1;
529 char **p;
530 int len = strlen(word);
531
532 for (p = string_list; *p; p++) {
533 if (!is_prefix(word, *p, len))
534 continue;
535 match_count++;
536 if (match_count >= matches_len) {
537 matches_len *= 2;
538 matches = para_realloc(matches,
539 matches_len * sizeof(char *));
540 }
541 matches[match_count - 1] = para_strdup(*p);
542 }
543 matches[match_count] = NULL;
544 *result = matches;
545 return match_count;
546 }
547
548 /**
549 * Return the list of partially matching words.
550 *
551 * \param word The command to complete.
552 * \param completers The array containing all command names.
553 *
554 * This is similar to \ref i9e_extract_completions(), but completes on the
555 * command names in \a completers.
556 *
557 * \return See \ref i9e_extract_completions().
558 */
559 char **i9e_complete_commands(const char *word, struct i9e_completer *completers)
560 {
561 char **matches;
562 const char *cmd;
563 int i, match_count, len = strlen(word);
564
565 /*
566 * In contrast to completing against an arbitrary string list, here we
567 * know all possible completions and expect that there will not be many
568 * of them. So it should be OK to iterate twice over all commands which
569 * simplifies the code a bit.
570 */
571 for (i = 0, match_count = 0; (cmd = completers[i].name); i++) {
572 if (is_prefix(word, cmd, len))
573 match_count++;
574 }
575 matches = para_malloc((match_count + 1) * sizeof(*matches));
576 for (i = 0, match_count = 0; (cmd = completers[i].name); i++)
577 if (is_prefix(word, cmd, len))
578 matches[match_count++] = para_strdup(cmd);
579 matches[match_count] = NULL;
580 return matches;
581 }
582
583 /**
584 * Complete according to the given options.
585 *
586 * \param opts All available options.
587 * \param ci Information which was passed to the completer.
588 * \param cr Result pointer.
589 *
590 * This convenience helper can be used to complete an option. The array of all
591 * possible options is passed as the first argument. Flags, i.e. options
592 * without an argument, are expected to be listed as strings of type "-X" in \a
593 * opts while options which require an argument should be passed with a
594 * trailing "=" character like "-X=".
595 *
596 * If the word can be uniquely completed to a flag option, an additional space
597 * character is appended to the output. For non-flag options no space character
598 * is appended.
599 */
600 void i9e_complete_option(char **opts, struct i9e_completion_info *ci,
601 struct i9e_completion_result *cr)
602 {
603 int num_matches;
604
605 num_matches = i9e_extract_completions(ci->word, opts, &cr->matches);
606 if (num_matches == 1) {
607 char *opt = cr->matches[0];
608 char c = opt[strlen(opt) - 1];
609 if (c == '=')
610 cr->dont_append_space = true;
611 }
612 }
613
614 /**
615 * Print possible completions to stdout.
616 *
617 * \param completers The array of completion functions.
618 *
619 * At the end of the output a line starting with "-o=", followed by the
620 * (possibly empty) list of completion options is printed. Currently, the only
621 * two completion options are "nospace" and "filenames". The former indicates
622 * that no space should be appended even for a unique match while the latter
623 * indicates that usual filename completion should be performed in addition to
624 * the previously printed options.
625 *
626 * \return Standard.
627 */
628 int i9e_print_completions(struct i9e_completer *completers)
629 {
630 struct i9e_completion_result cr;
631 struct i9e_completion_info ci;
632 char *buf;
633 const char *end, *p;
634 int i, n, ret;
635
636 reset_completion_result(&cr);
637 buf = getenv("COMP_POINT");
638 ci.point = buf? atoi(buf) : 0;
639 ci.buffer = para_strdup(getenv("COMP_LINE"));
640
641 ci.argc = create_argv(ci.buffer, " ", &ci.argv);
642 ci.word_num = compute_word_num(ci.buffer, " ", ci.point);
643
644 end = ci.buffer + ci.point;
645 for (p = end; p > ci.buffer && *p != ' '; p--)
646 ; /* nothing */
647 if (*p == ' ')
648 p++;
649
650 n = end - p + 1;
651 ci.word = para_malloc(n + 1);
652 strncpy(ci.word, p, n);
653 ci.word[n] = '\0';
654
655 PARA_DEBUG_LOG("line: %s, point: %d (%c), wordnum: %d, word: %s\n",
656 ci.buffer, ci.point, ci.buffer[ci.point], ci.word_num, ci.word);
657 if (ci.word_num == 0)
658 cr.matches = i9e_complete_commands(ci.word, completers);
659 else
660 create_matches(&ci, completers, &cr);
661 ret = 0;
662 if (cr.matches && cr.matches[0]) {
663 for (i = 0; cr.matches[i]; i++)
664 printf("%s\n", cr.matches[i]);
665 ret = 1;
666 }
667 printf("-o=");
668 if (cr.dont_append_space)
669 printf("nospace");
670 if (cr.filename_completion_desired)
671 printf(",filenames");
672 printf("\n");
673 free_argv(cr.matches);
674 free_argv(ci.argv);
675 free(ci.buffer);
676 free(ci.word);
677 return ret;
678 }