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;
37 static struct i9e_private i9e_private, *i9ep = &i9e_private;
39 static bool is_prefix(const char *partial, const char *full, size_t len)
42 len = strlen(partial);
43 return !strncmp(partial, full, len);
47 * Generator function for command completion. STATE lets us know whether
48 * to start from scratch; without any state (i.e. STATE == 0), then we
49 * start at the top of the list.
51 static char *command_generator(const char *text, int state)
53 static int list_index, len;
55 struct i9e_client_info *ici = i9ep->ici;
57 rl_attempted_completion_over = 1; /* disable filename completion */
59 * If this is a new word to complete, initialize now. This includes
60 * saving the length of TEXT for efficiency, and initializing the index
67 /* Return the next name which partially matches from the command list. */
68 while ((name = ici->completers[list_index].name)) {
70 if (is_prefix(text, name, len))
71 return para_strdup(name);
73 return NULL; /* no names matched */
76 static void reset_completion_result(struct i9e_completion_result *cr)
78 cr->dont_append_space = false;
79 cr->filename_completion_desired = false;
83 static void create_matches(struct i9e_completion_info *ci,
84 struct i9e_completer *completers,
85 struct i9e_completion_result *cr)
89 reset_completion_result(cr);
91 ret = create_argv(ci->buffer, " ", &ci->argv);
92 if (ret < 0 || !ci->argv[0])
96 ci->word_num = compute_word_num(ci->buffer, " ", ci->point);
97 for (i = 0; completers[i].name; i++) {
98 if (strcmp(completers[i].name, ci->argv[0]) != 0)
100 completers[i].completer(ci, cr);
103 PARA_DEBUG_LOG("current word: %d (%s)\n", ci->word_num,
104 ci->argv[ci->word_num]);
106 for (i = 0; cr->matches[i]; i++)
107 PARA_DEBUG_LOG("match %d: %s\n", i, cr->matches[i]);
110 static char *completion_generator(const char *word, int state)
112 static int list_index;
113 static char **argv, **matches;
114 struct i9e_completer *completers = i9ep->ici->completers;
115 struct i9e_completion_info ci = {
116 .word = (char *)word,
118 .buffer = rl_line_buffer,
120 struct i9e_completion_result cr = {.matches = NULL};
124 /* clean up previous matches and set defaults */
130 rl_completion_append_character = ' ';
131 rl_completion_suppress_append = false;
132 rl_attempted_completion_over = true;
134 create_matches(&ci, completers, &cr);
136 matches = cr.matches;
138 rl_completion_suppress_append = cr.dont_append_space;
139 rl_attempted_completion_over = !cr.filename_completion_desired;
143 return matches[list_index++];
147 * Attempt to complete on the contents of TEXT. START and END bound the
148 * region of rl_line_buffer that contains the word to complete. TEXT is
149 * the word to complete. We can use the entire contents of rl_line_buffer
150 * in case we want to do some simple parsing. Return the array of matches,
151 * or NULL if there aren't any.
153 static char **i9e_completer(const char *text, int start, __a_unused int end)
155 struct i9e_client_info *ici = i9ep->ici;
157 if (!ici->completers)
159 /* Complete on command names if this is the first word in the line. */
161 return rl_completion_matches(text, command_generator);
162 return rl_completion_matches(text, completion_generator);
166 * Prepare writing to stdout.
168 * \param producer The buffer tree node which produces output.
170 * The i9e subsystem maintains a buffer tree node which may be attached to
171 * another node which generates output (a "producer"). When attached, the i9e
172 * buffer tree node copies the buffers generated by the producer to stdout.
174 * This function attaches the i9e input queue to an output queue of \a
179 void i9e_attach_to_stdout(struct btr_node *producer)
181 assert(!i9ep->stdout_btrn);
182 i9ep->stdout_btrn = btr_new_node(&(struct btr_node_description)
183 EMBRACE(.name = "interactive_stdout", .parent = producer));
187 * Reset the terminal and save the in-memory command line history.
189 * This should be called before the caller exits.
193 char *hf = i9ep->ici->history_file;
195 rl_deprep_terminal();
196 fprintf(i9ep->stderr_stream, "\n");
201 static void wipe_bottom_line(void)
203 fprintf(i9ep->stderr_stream, "\r%s\r", i9ep->empty_line);
206 static void clear_bottom_line(void)
211 if (rl_point == 0 && rl_end == 0)
212 return wipe_bottom_line();
214 * We might have a multi-line input that needs to be wiped here, so the
215 * simple printf("\r<space>\r") is insufficient. To workaround this, we
216 * remove the whole line, redisplay and restore the killed text.
219 text = rl_copy_text(0, rl_end);
220 rl_kill_full_line(0, 0);
222 wipe_bottom_line(); /* wipe out the prompt */
223 rl_insert_text(text);
227 static bool input_available(void)
230 struct timeval tv = {0, 0};
234 FD_SET(i9ep->ici->fds[0], &rfds);
235 ret = para_select(1, &rfds, NULL, &tv);
239 static void i9e_line_handler(char *line)
243 i9ep->line_handler_running = true;
244 ret = i9ep->ici->line_handler(line);
245 i9ep->line_handler_running = false;
247 PARA_WARNING_LOG("%s\n", para_strerror(-ret));
251 rl_set_prompt(i9ep->ici->prompt);
257 i9ep->input_eof = true;
261 static void i9e_input(void)
264 rl_callback_read_char();
265 } while (input_available());
268 static void i9e_post_select(struct sched *s, struct task *t)
271 struct btr_node *btrn = i9ep->stdout_btrn;
272 struct i9e_client_info *ici = i9ep->ici;
276 if (i9ep->input_eof) {
277 t->error = -E_I9E_EOF;
281 i9ep->caught_sigint = false;
282 if (FD_ISSET(ici->fds[0], &s->rfds))
286 if (i9ep->caught_sigint)
288 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
291 sz = btr_next_buffer(btrn, &buf);
294 ret = xwrite(ici->fds[1], buf, sz);
297 btr_consume(btrn, ret);
300 btr_remove_node(&i9ep->stdout_btrn);
301 rl_set_prompt(i9ep->ici->prompt);
302 rl_forced_update_display();
307 static void i9e_pre_select(struct sched *s, __a_unused struct task *t)
311 if (i9ep->input_eof || i9ep->caught_sigint) {
315 if (i9ep->stdout_btrn) {
316 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
322 para_fd_set(i9ep->ici->fds[1], &s->wfds, &s->max_fileno);
325 * fd[0] might have been reset to blocking mode if our job was moved to
326 * the background due to CTRL-Z or SIGSTOP, so set the fd back to
329 ret = mark_fd_nonblocking(i9ep->ici->fds[0]);
331 PARA_WARNING_LOG("set to nonblock failed: (fd0 %d, %s)\n",
332 i9ep->ici->fds[0], para_strerror(-ret));
333 para_fd_set(i9ep->ici->fds[0], &s->rfds, &s->max_fileno);
336 static void update_winsize(void)
339 int ret = ioctl(i9ep->ici->fds[2], TIOCGWINSZ, (char *)&w);
340 int num_columns = 80;
343 assert(w.ws_col < sizeof(i9ep->empty_line));
344 num_columns = w.ws_col;
346 memset(i9ep->empty_line, ' ', num_columns);
347 i9ep->empty_line[num_columns] = '\0';
351 * Register the i9e task and initialize readline.
353 * \param ici The i9e configuration parameters set by the caller.
354 * \param s The scheduler instance to add the i9e task to.
356 * The caller must allocate and initialize the structure \a ici points to.
359 * \sa \ref register_task().
361 int i9e_open(struct i9e_client_info *ici, struct sched *s)
365 if (!isatty(ici->fds[0]))
366 return -E_I9E_SETUPTERM;
367 ret = mark_fd_nonblocking(ici->fds[0]);
370 ret = mark_fd_nonblocking(ici->fds[1]);
373 i9ep->task.pre_select = i9e_pre_select;
374 i9ep->task.post_select = i9e_post_select;
375 sprintf(i9ep->task.status, "i9e");
376 register_task(s, &i9ep->task);
377 rl_readline_name = "para_i9e";
378 rl_basic_word_break_characters = " ";
379 rl_attempted_completion_function = i9e_completer;
381 i9ep->stderr_stream = fdopen(ici->fds[2], "w");
382 setvbuf(i9ep->stderr_stream, NULL, _IONBF, 0);
384 if (ici->history_file)
385 read_history(ici->history_file);
387 rl_callback_handler_install(i9ep->ici->prompt, i9e_line_handler);
391 static void reset_line_state(void)
393 if (i9ep->line_handler_running)
396 rl_reset_line_state();
397 rl_forced_update_display();
401 * The log function of the i9e subsystem.
403 * \param ll Severity log level.
404 * \param fmt Printf-like format string.
406 * This clears the bottom line of the terminal if necessary and writes the
407 * string given by \a fmt to fd[2], where fd[] is the array provided earlier in
410 __printf_2_3 void i9e_log(int ll, const char* fmt,...)
414 if (ll < i9ep->ici->loglevel)
416 if (i9ep->line_handler_running == false)
419 vfprintf(i9ep->stderr_stream, fmt, argp);
425 * Tell i9e that the caller received a signal.
427 * \param sig_num The number of the signal received.
429 * Currently the function only cares about \p SIGINT, but this may change.
431 void i9e_signal_dispatch(int sig_num)
433 if (sig_num == SIGINT) {
434 fprintf(i9ep->stderr_stream, "\n");
435 rl_replace_line ("", false /* clear_undo */);
437 i9ep->caught_sigint = true;
442 * Wrapper for select(2) which does not restart on interrupts.
444 * \param n \sa \ref para_select().
445 * \param readfds \sa \ref para_select().
446 * \param writefds \sa \ref para_select().
447 * \param timeout_tv \sa \ref para_select().
449 * \return \sa \ref para_select().
451 * The only difference between this function and \ref para_select() is that
452 * \ref i9e_select() returns zero if the select call returned \p EINTR.
454 int i9e_select(int n, fd_set *readfds, fd_set *writefds,
455 struct timeval *timeout_tv)
457 int ret = select(n, readfds, writefds, NULL, timeout_tv);
463 ret = -ERRNO_TO_PARA_ERROR(errno);
469 * Return the possible completions for a given word.
471 * \param word The word to complete.
472 * \param string_list All possible words in this context.
473 * \param result String list is returned here.
475 * This function never fails. If no completion was found, a string list of
476 * length zero is returned. In any case, the result must be freed by the caller
477 * using \ref free_argv().
479 * This function is independent of readline and may be called before
482 * \return The number of possible completions.
484 int i9e_extract_completions(const char *word, char **string_list,
487 char **matches = para_malloc(sizeof(char *));
488 int match_count = 0, matches_len = 1;
490 int len = strlen(word);
492 for (p = string_list; *p; p++) {
493 if (!is_prefix(word, *p, len))
496 if (match_count >= matches_len) {
498 matches = para_realloc(matches,
499 matches_len * sizeof(char *));
501 matches[match_count - 1] = para_strdup(*p);
503 matches[match_count] = NULL;
509 * Return the list of partially matching words.
511 * \param word The command to complete.
512 * \param completers The array containing all command names.
514 * This is similar to \ref i9e_extract_completions(), but completes on the
515 * command names in \a completers.
517 * \return See \ref i9e_extract_completions().
519 char **i9e_complete_commands(const char *word, struct i9e_completer *completers)
523 int i, match_count, len = strlen(word);
526 * In contrast to completing against an arbitrary string list, here we
527 * know all possible completions and expect that there will not be many
528 * of them. So it should be OK to iterate twice over all commands which
529 * simplifies the code a bit.
531 for (i = 0, match_count = 0; (cmd = completers[i].name); i++) {
532 if (is_prefix(word, cmd, len))
535 matches = para_malloc((match_count + 1) * sizeof(*matches));
536 for (i = 0, match_count = 0; (cmd = completers[i].name); i++)
537 if (is_prefix(word, cmd, len))
538 matches[match_count++] = para_strdup(cmd);
539 matches[match_count] = NULL;
544 * Complete according to the given options.
546 * \param opts All available options.
547 * \param ci Information which was passed to the completer.
548 * \param cr Result pointer.
550 * This convenience helper can be used to complete an option. The array of all
551 * possible options is passed as the first argument. Flags, i.e. options
552 * without an argument, are expected to be listed as strings of type "-X" in \a
553 * opts while options which require an argument should be passed with a
554 * trailing "=" character like "-X=".
556 * If the word can be uniquely completed to a flag option, an additional space
557 * character is appended to the output. For non-flag options no space character
560 void i9e_complete_option(char **opts, struct i9e_completion_info *ci,
561 struct i9e_completion_result *cr)
565 num_matches = i9e_extract_completions(ci->word, opts, &cr->matches);
566 if (num_matches == 1) {
567 char *opt = cr->matches[0];
568 char c = opt[strlen(opt) - 1];
570 cr->dont_append_space = true;
575 * Print possible completions to stdout.
577 * \param completers The array of completion functions.
579 * At the end of the output a line starting with "-o=", followed by the
580 * (possibly empty) list of completion options is printed. Currently, the only
581 * two completion options are "nospace" and "filenames". The former indicates
582 * that no space should be appended even for a unique match while the latter
583 * indicates that usual filename completion should be performed in addition to
584 * the previously printed options.
588 int i9e_print_completions(struct i9e_completer *completers)
590 struct i9e_completion_result cr;
591 struct i9e_completion_info ci;
596 reset_completion_result(&cr);
597 buf = getenv("COMP_POINT");
598 ci.point = buf? atoi(buf) : 0;
599 ci.buffer = para_strdup(getenv("COMP_LINE"));
601 ci.argc = create_argv(ci.buffer, " ", &ci.argv);
602 ci.word_num = compute_word_num(ci.buffer, " ", ci.point);
604 end = ci.buffer + ci.point;
605 for (p = end; p > ci.buffer && *p != ' '; p--)
611 ci.word = para_malloc(n + 1);
612 strncpy(ci.word, p, n);
615 PARA_DEBUG_LOG("line: %s, point: %d (%c), wordnum: %d, word: %s\n",
616 ci.buffer, ci.point, ci.buffer[ci.point], ci.word_num, ci.word);
617 if (ci.word_num == 0)
618 cr.matches = i9e_complete_commands(ci.word, completers);
620 create_matches(&ci, completers, &cr);
622 if (cr.matches && cr.matches[0]) {
623 for (i = 0; cr.matches[i]; i++)
624 printf("%s\n", cr.matches[i]);
628 if (cr.dont_append_space)
630 if (cr.filename_completion_desired)
631 printf(",filenames");
633 free_argv(cr.matches);