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;
30 char empty_line[1000];
32 struct btr_node *stdout_btrn;
33 bool line_handler_running;
38 static struct i9e_private i9e_private, *i9ep = &i9e_private;
40 static bool is_prefix(const char *partial, const char *full, size_t len)
43 len = strlen(partial);
44 return !strncmp(partial, full, len);
48 * Generator function for command completion. STATE lets us know whether
49 * to start from scratch; without any state (i.e. STATE == 0), then we
50 * start at the top of the list.
52 static char *command_generator(const char *text, int state)
54 static int list_index, len;
56 struct i9e_client_info *ici = i9ep->ici;
58 rl_attempted_completion_over = 1; /* disable filename completion */
60 * If this is a new word to complete, initialize now. This includes
61 * saving the length of TEXT for efficiency, and initializing the index
68 /* Return the next name which partially matches from the command list. */
69 while ((name = ici->completers[list_index].name)) {
71 if (is_prefix(text, name, len))
72 return para_strdup(name);
74 return NULL; /* no names matched */
77 static void reset_completion_result(struct i9e_completion_result *cr)
79 cr->dont_append_space = false;
80 cr->filename_completion_desired = false;
84 static void create_matches(struct i9e_completion_info *ci,
85 struct i9e_completer *completers,
86 struct i9e_completion_result *cr)
90 reset_completion_result(cr);
92 ret = create_argv(ci->buffer, " ", &ci->argv);
93 if (ret < 0 || !ci->argv[0])
97 ci->word_num = compute_word_num(ci->buffer, " ", ci->point);
98 for (i = 0; completers[i].name; i++) {
99 if (strcmp(completers[i].name, ci->argv[0]) != 0)
101 completers[i].completer(ci, cr);
104 PARA_DEBUG_LOG("current word: %d (%s)\n", ci->word_num,
105 ci->argv[ci->word_num]);
107 for (i = 0; cr->matches[i]; i++)
108 PARA_DEBUG_LOG("match %d: %s\n", i, cr->matches[i]);
111 static char *completion_generator(const char *word, int state)
113 static int list_index;
114 static char **argv, **matches;
115 struct i9e_completer *completers = i9ep->ici->completers;
116 struct i9e_completion_info ci = {
117 .word = (char *)word,
119 .buffer = rl_line_buffer,
121 struct i9e_completion_result cr = {.matches = NULL};
125 /* clean up previous matches and set defaults */
131 rl_completion_append_character = ' ';
132 rl_completion_suppress_append = false;
133 rl_attempted_completion_over = true;
135 create_matches(&ci, completers, &cr);
137 matches = cr.matches;
139 rl_completion_suppress_append = cr.dont_append_space;
140 rl_attempted_completion_over = !cr.filename_completion_desired;
144 return matches[list_index++];
148 * Attempt to complete on the contents of TEXT. START and END bound the
149 * region of rl_line_buffer that contains the word to complete. TEXT is
150 * the word to complete. We can use the entire contents of rl_line_buffer
151 * in case we want to do some simple parsing. Return the array of matches,
152 * or NULL if there aren't any.
154 static char **i9e_completer(const char *text, int start, __a_unused int end)
156 struct i9e_client_info *ici = i9ep->ici;
158 if (!ici->completers)
160 /* Complete on command names if this is the first word in the line. */
162 return rl_completion_matches(text, command_generator);
163 return rl_completion_matches(text, completion_generator);
167 * Prepare writing to stdout.
169 * \param producer The buffer tree node which produces output.
171 * The i9e subsystem maintains a buffer tree node which may be attached to
172 * another node which generates output (a "producer"). When attached, the i9e
173 * buffer tree node copies the buffers generated by the producer to stdout.
175 * This function attaches the i9e input queue to an output queue of \a
180 void i9e_attach_to_stdout(struct btr_node *producer)
182 btr_remove_node(&i9ep->stdout_btrn);
183 i9ep->stdout_btrn = btr_new_node(&(struct btr_node_description)
184 EMBRACE(.name = "interactive_stdout", .parent = producer));
187 static void wipe_bottom_line(void)
189 fprintf(i9ep->stderr_stream, "\r%s\r", i9ep->empty_line);
193 * Reset the terminal and save the in-memory command line history.
195 * This should be called before the caller exits.
199 char *hf = i9ep->ici->history_file;
201 rl_deprep_terminal();
207 static void clear_bottom_line(void)
212 if (rl_point == 0 && rl_end == 0)
213 return wipe_bottom_line();
215 * We might have a multi-line input that needs to be wiped here, so the
216 * simple printf("\r<space>\r") is insufficient. To workaround this, we
217 * remove the whole line, redisplay and restore the killed text.
220 text = rl_copy_text(0, rl_end);
221 rl_kill_full_line(0, 0);
223 wipe_bottom_line(); /* wipe out the prompt */
224 rl_insert_text(text);
228 static bool input_available(void)
231 struct timeval tv = {0, 0};
235 FD_SET(i9ep->ici->fds[0], &rfds);
236 ret = para_select(1, &rfds, NULL, &tv);
240 static void i9e_line_handler(char *line)
244 ret = i9ep->ici->line_handler(line);
246 PARA_WARNING_LOG("%s\n", para_strerror(-ret));
250 rl_set_prompt(i9ep->ici->prompt);
256 i9ep->input_eof = true;
260 static void i9e_input(void)
263 rl_callback_read_char();
264 } while (input_available());
267 static void i9e_post_select(struct sched *s, struct task *t)
270 struct btr_node *btrn = i9ep->stdout_btrn;
271 struct i9e_client_info *ici = i9ep->ici;
278 ret = -E_I9E_TERM_RQ;
279 if (i9ep->caught_sigterm)
282 i9ep->caught_sigint = false;
283 if (FD_ISSET(ici->fds[0], &s->rfds))
288 if (i9ep->caught_sigint)
290 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
293 sz = btr_next_buffer(btrn, &buf);
296 ret = xwrite(ici->fds[1], buf, sz);
299 btr_consume(btrn, ret);
302 btr_remove_node(&i9ep->stdout_btrn);
303 rl_set_prompt(i9ep->ici->prompt);
309 static void i9e_pre_select(struct sched *s, __a_unused struct task *t)
313 if (i9ep->input_eof || i9ep->caught_sigint || i9ep->caught_sigterm) {
317 if (i9ep->stdout_btrn) {
318 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
324 para_fd_set(i9ep->ici->fds[1], &s->wfds, &s->max_fileno);
327 * fd[0] might have been reset to blocking mode if our job was moved to
328 * the background due to CTRL-Z or SIGSTOP, so set the fd back to
331 ret = mark_fd_nonblocking(i9ep->ici->fds[0]);
333 PARA_WARNING_LOG("set to nonblock failed: (fd0 %d, %s)\n",
334 i9ep->ici->fds[0], para_strerror(-ret));
335 para_fd_set(i9ep->ici->fds[0], &s->rfds, &s->max_fileno);
338 static void update_winsize(void)
341 int ret = ioctl(i9ep->ici->fds[2], TIOCGWINSZ, (char *)&w);
342 int num_columns = 80;
345 assert(w.ws_col < sizeof(i9ep->empty_line));
346 num_columns = w.ws_col;
348 memset(i9ep->empty_line, ' ', num_columns);
349 i9ep->empty_line[num_columns] = '\0';
353 * Register the i9e task and initialize readline.
355 * \param ici The i9e configuration parameters set by the caller.
356 * \param s The scheduler instance to add the i9e task to.
358 * The caller must allocate and initialize the structure \a ici points to.
361 * \sa \ref register_task().
363 int i9e_open(struct i9e_client_info *ici, struct sched *s)
367 if (!isatty(ici->fds[0]))
368 return -E_I9E_SETUPTERM;
369 ret = mark_fd_nonblocking(ici->fds[0]);
372 ret = mark_fd_nonblocking(ici->fds[1]);
375 i9ep->task.pre_select = i9e_pre_select;
376 i9ep->task.post_select = i9e_post_select;
377 sprintf(i9ep->task.status, "i9e");
378 register_task(s, &i9ep->task);
379 rl_readline_name = "para_i9e";
380 rl_basic_word_break_characters = " ";
381 rl_attempted_completion_function = i9e_completer;
383 i9ep->stderr_stream = fdopen(ici->fds[2], "w");
384 setvbuf(i9ep->stderr_stream, NULL, _IONBF, 0);
386 if (ici->history_file)
387 read_history(ici->history_file);
389 rl_callback_handler_install(i9ep->ici->prompt, i9e_line_handler);
393 static void reset_line_state(void)
395 if (i9ep->stdout_btrn)
398 rl_reset_line_state();
399 rl_forced_update_display();
403 * The log function of the i9e subsystem.
405 * \param ll Severity log level.
406 * \param fmt Printf-like format string.
408 * This clears the bottom line of the terminal if necessary and writes the
409 * string given by \a fmt to fd[2], where fd[] is the array provided earlier in
412 __printf_2_3 void i9e_log(int ll, const char* fmt,...)
416 if (ll < i9ep->ici->loglevel)
420 vfprintf(i9ep->stderr_stream, fmt, argp);
426 * Tell i9e that the caller received a signal.
428 * \param sig_num The number of the signal received.
430 * Currently the function only cares about \p SIGINT, but this may change.
432 void i9e_signal_dispatch(int sig_num)
434 if (sig_num == SIGINT) {
435 fprintf(i9ep->stderr_stream, "\n");
436 rl_replace_line ("", false /* clear_undo */);
438 i9ep->caught_sigint = true;
440 if (sig_num == SIGTERM)
441 i9ep->caught_sigterm = true;
445 * Wrapper for select(2) which does not restart on interrupts.
447 * \param n \sa \ref para_select().
448 * \param readfds \sa \ref para_select().
449 * \param writefds \sa \ref para_select().
450 * \param timeout_tv \sa \ref para_select().
452 * \return \sa \ref para_select().
454 * The only difference between this function and \ref para_select() is that
455 * \ref i9e_select() returns zero if the select call returned \p EINTR.
457 int i9e_select(int n, fd_set *readfds, fd_set *writefds,
458 struct timeval *timeout_tv)
460 int ret = select(n, readfds, writefds, NULL, timeout_tv);
466 ret = -ERRNO_TO_PARA_ERROR(errno);
472 * Return the possible completions for a given word.
474 * \param word The word to complete.
475 * \param string_list All possible words in this context.
476 * \param result String list is returned here.
478 * This function never fails. If no completion was found, a string list of
479 * length zero is returned. In any case, the result must be freed by the caller
480 * using \ref free_argv().
482 * This function is independent of readline and may be called before
485 * \return The number of possible completions.
487 int i9e_extract_completions(const char *word, char **string_list,
490 char **matches = para_malloc(sizeof(char *));
491 int match_count = 0, matches_len = 1;
493 int len = strlen(word);
495 for (p = string_list; *p; p++) {
496 if (!is_prefix(word, *p, len))
499 if (match_count >= matches_len) {
501 matches = para_realloc(matches,
502 matches_len * sizeof(char *));
504 matches[match_count - 1] = para_strdup(*p);
506 matches[match_count] = NULL;
512 * Return the list of partially matching words.
514 * \param word The command to complete.
515 * \param completers The array containing all command names.
517 * This is similar to \ref i9e_extract_completions(), but completes on the
518 * command names in \a completers.
520 * \return See \ref i9e_extract_completions().
522 char **i9e_complete_commands(const char *word, struct i9e_completer *completers)
526 int i, match_count, len = strlen(word);
529 * In contrast to completing against an arbitrary string list, here we
530 * know all possible completions and expect that there will not be many
531 * of them. So it should be OK to iterate twice over all commands which
532 * simplifies the code a bit.
534 for (i = 0, match_count = 0; (cmd = completers[i].name); i++) {
535 if (is_prefix(word, cmd, len))
538 matches = para_malloc((match_count + 1) * sizeof(*matches));
539 for (i = 0, match_count = 0; (cmd = completers[i].name); i++)
540 if (is_prefix(word, cmd, len))
541 matches[match_count++] = para_strdup(cmd);
542 matches[match_count] = NULL;
547 * Complete according to the given options.
549 * \param opts All available options.
550 * \param ci Information which was passed to the completer.
551 * \param cr Result pointer.
553 * This convenience helper can be used to complete an option. The array of all
554 * possible options is passed as the first argument. Flags, i.e. options
555 * without an argument, are expected to be listed as strings of type "-X" in \a
556 * opts while options which require an argument should be passed with a
557 * trailing "=" character like "-X=".
559 * If the word can be uniquely completed to a flag option, an additional space
560 * character is appended to the output. For non-flag options no space character
563 void i9e_complete_option(char **opts, struct i9e_completion_info *ci,
564 struct i9e_completion_result *cr)
568 num_matches = i9e_extract_completions(ci->word, opts, &cr->matches);
569 if (num_matches == 1) {
570 char *opt = cr->matches[0];
571 char c = opt[strlen(opt) - 1];
573 cr->dont_append_space = true;
578 * Print possible completions to stdout.
580 * \param completers The array of completion functions.
582 * At the end of the output a line starting with "-o=", followed by the
583 * (possibly empty) list of completion options is printed. Currently, the only
584 * two completion options are "nospace" and "filenames". The former indicates
585 * that no space should be appended even for a unique match while the latter
586 * indicates that usual filename completion should be performed in addition to
587 * the previously printed options.
591 int i9e_print_completions(struct i9e_completer *completers)
593 struct i9e_completion_result cr;
594 struct i9e_completion_info ci;
599 reset_completion_result(&cr);
600 buf = getenv("COMP_POINT");
601 ci.point = buf? atoi(buf) : 0;
602 ci.buffer = para_strdup(getenv("COMP_LINE"));
604 ci.argc = create_argv(ci.buffer, " ", &ci.argv);
605 ci.word_num = compute_word_num(ci.buffer, " ", ci.point);
607 end = ci.buffer + ci.point;
608 for (p = end; p > ci.buffer && *p != ' '; p--)
614 ci.word = para_malloc(n + 1);
615 strncpy(ci.word, p, n);
618 PARA_DEBUG_LOG("line: %s, point: %d (%c), wordnum: %d, word: %s\n",
619 ci.buffer, ci.point, ci.buffer[ci.point], ci.word_num, ci.word);
620 if (ci.word_num == 0)
621 cr.matches = i9e_complete_commands(ci.word, completers);
623 create_matches(&ci, completers, &cr);
625 if (cr.matches && cr.matches[0]) {
626 for (i = 0; cr.matches[i]; i++)
627 printf("%s\n", cr.matches[i]);
631 if (cr.dont_append_space)
633 if (cr.filename_completion_desired)
634 printf(",filenames");
636 free_argv(cr.matches);