2 * Copyright (C) 2011-2012 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file interactive.c Readline abstraction for interactive sessions. */
12 #include <readline/readline.h>
13 #include <readline/history.h>
14 #include <sys/ioctl.h>
20 #include "buffer_tree.h"
23 #include "interactive.h"
28 struct i9e_client_info *ici;
31 char empty_line[1000];
33 struct btr_node *stdout_btrn;
34 bool line_handler_running;
39 static struct i9e_private i9e_private, *i9ep = &i9e_private;
42 * Return the error state of the i9e task.
44 * This is mainly useful for other tasks to tell whether the i9e task is still
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().
50 int i9e_get_error(void)
52 return i9ep->task.error;
55 static bool is_prefix(const char *partial, const char *full, size_t len)
58 len = strlen(partial);
59 return !strncmp(partial, full, len);
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.
67 static char *command_generator(const char *text, int state)
69 static int list_index, len;
71 struct i9e_client_info *ici = i9ep->ici;
73 rl_attempted_completion_over = 1; /* disable filename completion */
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
83 /* Return the next name which partially matches from the command list. */
84 while ((name = ici->completers[list_index].name)) {
86 if (is_prefix(text, name, len))
87 return para_strdup(name);
89 return NULL; /* no names matched */
92 static void reset_completion_result(struct i9e_completion_result *cr)
94 cr->dont_append_space = false;
95 cr->filename_completion_desired = false;
99 static void create_matches(struct i9e_completion_info *ci,
100 struct i9e_completer *completers,
101 struct i9e_completion_result *cr)
105 reset_completion_result(cr);
107 ret = create_argv(ci->buffer, " ", &ci->argv);
108 if (ret < 0 || !ci->argv[0])
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)
116 completers[i].completer(ci, cr);
119 PARA_DEBUG_LOG("current word: %d (%s)\n", ci->word_num,
120 ci->argv[ci->word_num]);
122 for (i = 0; cr->matches[i]; i++)
123 PARA_DEBUG_LOG("match %d: %s\n", i, cr->matches[i]);
126 static char *completion_generator(const char *word, int state)
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,
134 .buffer = rl_line_buffer,
136 struct i9e_completion_result cr = {.matches = NULL};
140 /* clean up previous matches and set defaults */
146 rl_completion_append_character = ' ';
147 rl_completion_suppress_append = false;
148 rl_attempted_completion_over = true;
150 create_matches(&ci, completers, &cr);
152 matches = cr.matches;
154 rl_completion_suppress_append = cr.dont_append_space;
155 rl_attempted_completion_over = !cr.filename_completion_desired;
159 return matches[list_index++];
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.
169 static char **i9e_completer(const char *text, int start, __a_unused int end)
171 struct i9e_client_info *ici = i9ep->ici;
173 if (!ici->completers)
175 /* Complete on command names if this is the first word in the line. */
177 return rl_completion_matches(text, command_generator);
178 return rl_completion_matches(text, completion_generator);
182 * Prepare writing to stdout.
184 * \param producer The buffer tree node which produces output.
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.
190 * This function attaches the i9e input queue to an output queue of \a
195 void i9e_attach_to_stdout(struct btr_node *producer)
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));
202 static void wipe_bottom_line(void)
205 int n = i9ep->num_columns;
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.
212 fprintf(i9ep->stderr_stream, "\r");
214 if (n >= sizeof(x)) {
215 fprintf(i9ep->stderr_stream, "%s", x);
220 fprintf(i9ep->stderr_stream, "%s", x);
223 fprintf(i9ep->stderr_stream, "\r");
227 * Reset the terminal and save the in-memory command line history.
229 * This should be called before the caller exits.
233 char *hf = i9ep->ici->history_file;
235 rl_deprep_terminal();
241 static void clear_bottom_line(void)
246 if (rl_point == 0 && rl_end == 0)
247 return wipe_bottom_line();
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.
254 text = rl_copy_text(0, rl_end);
255 rl_kill_full_line(0, 0);
257 wipe_bottom_line(); /* wipe out the prompt */
258 rl_insert_text(text);
262 static bool input_available(void)
265 struct timeval tv = {0, 0};
269 FD_SET(i9ep->ici->fds[0], &rfds);
270 ret = para_select(1, &rfds, NULL, &tv);
274 static void i9e_line_handler(char *line)
278 ret = i9ep->ici->line_handler(line);
280 PARA_WARNING_LOG("%s\n", para_strerror(-ret));
284 rl_set_prompt(i9ep->ici->prompt);
290 i9ep->input_eof = true;
294 static void i9e_input(void)
297 rl_callback_read_char();
298 } while (input_available());
301 static void i9e_post_select(struct sched *s, struct task *t)
304 struct btr_node *btrn = i9ep->stdout_btrn;
305 struct i9e_client_info *ici = i9ep->ici;
312 ret = -E_I9E_TERM_RQ;
313 if (i9ep->caught_sigterm)
316 i9ep->caught_sigint = false;
317 if (FD_ISSET(ici->fds[0], &s->rfds))
322 if (i9ep->caught_sigint)
324 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
327 sz = btr_next_buffer(btrn, &buf);
330 ret = xwrite(ici->fds[1], buf, sz);
333 btr_consume(btrn, ret);
336 btr_remove_node(&i9ep->stdout_btrn);
337 rl_set_prompt(i9ep->ici->prompt);
343 static void i9e_pre_select(struct sched *s, __a_unused struct task *t)
347 if (i9ep->input_eof || i9ep->caught_sigint || i9ep->caught_sigterm) {
351 if (i9ep->stdout_btrn) {
352 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
358 para_fd_set(i9ep->ici->fds[1], &s->wfds, &s->max_fileno);
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
365 ret = mark_fd_nonblocking(i9ep->ici->fds[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);
372 static void update_winsize(void)
375 int ret = ioctl(i9ep->ici->fds[2], TIOCGWINSZ, (char *)&w);
378 assert(w.ws_col < sizeof(i9ep->empty_line));
379 i9ep->num_columns = w.ws_col;
381 i9ep->num_columns = 80;
383 memset(i9ep->empty_line, ' ', i9ep->num_columns);
384 i9ep->empty_line[i9ep->num_columns] = '\0';
388 * Register the i9e task and initialize readline.
390 * \param ici The i9e configuration parameters set by the caller.
391 * \param s The scheduler instance to add the i9e task to.
393 * The caller must allocate and initialize the structure \a ici points to.
396 * \sa \ref register_task().
398 int i9e_open(struct i9e_client_info *ici, struct sched *s)
402 if (!isatty(ici->fds[0]))
403 return -E_I9E_SETUPTERM;
404 ret = mark_fd_nonblocking(ici->fds[0]);
407 ret = mark_fd_nonblocking(ici->fds[1]);
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;
418 i9ep->stderr_stream = fdopen(ici->fds[2], "w");
419 setvbuf(i9ep->stderr_stream, NULL, _IONBF, 0);
421 if (ici->history_file)
422 read_history(ici->history_file);
425 rl_callback_handler_install("", i9e_line_handler);
426 i9e_attach_to_stdout(ici->producer);
428 rl_callback_handler_install(i9ep->ici->prompt, i9e_line_handler);
432 static void reset_line_state(void)
434 if (i9ep->stdout_btrn)
437 rl_reset_line_state();
438 rl_forced_update_display();
442 * The log function of the i9e subsystem.
444 * \param ll Severity log level.
445 * \param fmt Printf-like format string.
447 * This clears the bottom line of the terminal if necessary and writes the
448 * string given by \a fmt to fd[2], where fd[] is the array provided earlier in
451 __printf_2_3 void i9e_log(int ll, const char* fmt,...)
455 if (ll < i9ep->ici->loglevel)
459 vfprintf(i9ep->stderr_stream, fmt, argp);
465 * Tell i9e that the caller received a signal.
467 * \param sig_num The number of the signal received.
469 * Currently the function only cares about \p SIGINT, but this may change.
471 void i9e_signal_dispatch(int sig_num)
473 if (sig_num == SIGWINCH)
474 return update_winsize();
475 if (sig_num == SIGINT) {
476 fprintf(i9ep->stderr_stream, "\n");
477 rl_replace_line ("", false /* clear_undo */);
479 i9ep->caught_sigint = true;
481 if (sig_num == SIGTERM)
482 i9ep->caught_sigterm = true;
486 * Wrapper for select(2) which does not restart on interrupts.
488 * \param n \sa \ref para_select().
489 * \param readfds \sa \ref para_select().
490 * \param writefds \sa \ref para_select().
491 * \param timeout_tv \sa \ref para_select().
493 * \return \sa \ref para_select().
495 * The only difference between this function and \ref para_select() is that
496 * \ref i9e_select() returns zero if the select call returned \p EINTR.
498 int i9e_select(int n, fd_set *readfds, fd_set *writefds,
499 struct timeval *timeout_tv)
501 int ret = select(n, readfds, writefds, NULL, timeout_tv);
507 ret = -ERRNO_TO_PARA_ERROR(errno);
513 * Return the possible completions for a given word.
515 * \param word The word to complete.
516 * \param string_list All possible words in this context.
517 * \param result String list is returned here.
519 * This function never fails. If no completion was found, a string list of
520 * length zero is returned. In any case, the result must be freed by the caller
521 * using \ref free_argv().
523 * This function is independent of readline and may be called before
526 * \return The number of possible completions.
528 int i9e_extract_completions(const char *word, char **string_list,
531 char **matches = para_malloc(sizeof(char *));
532 int match_count = 0, matches_len = 1;
534 int len = strlen(word);
536 for (p = string_list; *p; p++) {
537 if (!is_prefix(word, *p, len))
540 if (match_count >= matches_len) {
542 matches = para_realloc(matches,
543 matches_len * sizeof(char *));
545 matches[match_count - 1] = para_strdup(*p);
547 matches[match_count] = NULL;
553 * Return the list of partially matching words.
555 * \param word The command to complete.
556 * \param completers The array containing all command names.
558 * This is similar to \ref i9e_extract_completions(), but completes on the
559 * command names in \a completers.
561 * \return See \ref i9e_extract_completions().
563 char **i9e_complete_commands(const char *word, struct i9e_completer *completers)
567 int i, match_count, len = strlen(word);
570 * In contrast to completing against an arbitrary string list, here we
571 * know all possible completions and expect that there will not be many
572 * of them. So it should be OK to iterate twice over all commands which
573 * simplifies the code a bit.
575 for (i = 0, match_count = 0; (cmd = completers[i].name); i++) {
576 if (is_prefix(word, cmd, len))
579 matches = para_malloc((match_count + 1) * sizeof(*matches));
580 for (i = 0, match_count = 0; (cmd = completers[i].name); i++)
581 if (is_prefix(word, cmd, len))
582 matches[match_count++] = para_strdup(cmd);
583 matches[match_count] = NULL;
588 * Complete according to the given options.
590 * \param opts All available options.
591 * \param ci Information which was passed to the completer.
592 * \param cr Result pointer.
594 * This convenience helper can be used to complete an option. The array of all
595 * possible options is passed as the first argument. Flags, i.e. options
596 * without an argument, are expected to be listed as strings of type "-X" in \a
597 * opts while options which require an argument should be passed with a
598 * trailing "=" character like "-X=".
600 * If the word can be uniquely completed to a flag option, an additional space
601 * character is appended to the output. For non-flag options no space character
604 void i9e_complete_option(char **opts, struct i9e_completion_info *ci,
605 struct i9e_completion_result *cr)
609 num_matches = i9e_extract_completions(ci->word, opts, &cr->matches);
610 if (num_matches == 1) {
611 char *opt = cr->matches[0];
612 char c = opt[strlen(opt) - 1];
614 cr->dont_append_space = true;
619 * Print possible completions to stdout.
621 * \param completers The array of completion functions.
623 * At the end of the output a line starting with "-o=", followed by the
624 * (possibly empty) list of completion options is printed. Currently, the only
625 * two completion options are "nospace" and "filenames". The former indicates
626 * that no space should be appended even for a unique match while the latter
627 * indicates that usual filename completion should be performed in addition to
628 * the previously printed options.
632 int i9e_print_completions(struct i9e_completer *completers)
634 struct i9e_completion_result cr;
635 struct i9e_completion_info ci;
640 reset_completion_result(&cr);
641 buf = getenv("COMP_POINT");
642 ci.point = buf? atoi(buf) : 0;
643 ci.buffer = para_strdup(getenv("COMP_LINE"));
645 ci.argc = create_argv(ci.buffer, " ", &ci.argv);
646 ci.word_num = compute_word_num(ci.buffer, " ", ci.point);
648 end = ci.buffer + ci.point;
649 for (p = end; p > ci.buffer && *p != ' '; p--)
655 ci.word = para_malloc(n + 1);
656 strncpy(ci.word, p, n);
659 PARA_DEBUG_LOG("line: %s, point: %d (%c), wordnum: %d, word: %s\n",
660 ci.buffer, ci.point, ci.buffer[ci.point], ci.word_num, ci.word);
661 if (ci.word_num == 0)
662 cr.matches = i9e_complete_commands(ci.word, completers);
664 create_matches(&ci, completers, &cr);
666 if (cr.matches && cr.matches[0]) {
667 for (i = 0; cr.matches[i]; i++)
668 printf("%s\n", cr.matches[i]);
672 if (cr.dont_append_space)
674 if (cr.filename_completion_desired)
675 printf(",filenames");
677 free_argv(cr.matches);