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;
41 static bool is_prefix(const char *partial, const char *full, size_t len)
44 len = strlen(partial);
45 return !strncmp(partial, full, len);
49 * Generator function for command completion. STATE lets us know whether
50 * to start from scratch; without any state (i.e. STATE == 0), then we
51 * start at the top of the list.
53 static char *command_generator(const char *text, int state)
55 static int list_index, len;
57 struct i9e_client_info *ici = i9ep->ici;
59 rl_attempted_completion_over = 1; /* disable filename completion */
61 * If this is a new word to complete, initialize now. This includes
62 * saving the length of TEXT for efficiency, and initializing the index
69 /* Return the next name which partially matches from the command list. */
70 while ((name = ici->completers[list_index].name)) {
72 if (is_prefix(text, name, len))
73 return para_strdup(name);
75 return NULL; /* no names matched */
78 static void reset_completion_result(struct i9e_completion_result *cr)
80 cr->dont_append_space = false;
81 cr->filename_completion_desired = false;
85 static void create_matches(struct i9e_completion_info *ci,
86 struct i9e_completer *completers,
87 struct i9e_completion_result *cr)
91 reset_completion_result(cr);
93 ret = create_argv(ci->buffer, " ", &ci->argv);
94 if (ret < 0 || !ci->argv[0])
98 ci->word_num = compute_word_num(ci->buffer, " ", ci->point);
99 for (i = 0; completers[i].name; i++) {
100 if (strcmp(completers[i].name, ci->argv[0]) != 0)
102 completers[i].completer(ci, cr);
105 PARA_DEBUG_LOG("current word: %d (%s)\n", ci->word_num,
106 ci->argv[ci->word_num]);
108 for (i = 0; cr->matches[i]; i++)
109 PARA_DEBUG_LOG("match %d: %s\n", i, cr->matches[i]);
112 static char *completion_generator(const char *word, int state)
114 static int list_index;
115 static char **argv, **matches;
116 struct i9e_completer *completers = i9ep->ici->completers;
117 struct i9e_completion_info ci = {
118 .word = (char *)word,
120 .buffer = rl_line_buffer,
122 struct i9e_completion_result cr = {.matches = NULL};
126 /* clean up previous matches and set defaults */
132 rl_completion_append_character = ' ';
133 rl_completion_suppress_append = false;
134 rl_attempted_completion_over = true;
136 create_matches(&ci, completers, &cr);
138 matches = cr.matches;
140 rl_completion_suppress_append = cr.dont_append_space;
141 rl_attempted_completion_over = !cr.filename_completion_desired;
145 return matches[list_index++];
149 * Attempt to complete on the contents of TEXT. START and END bound the
150 * region of rl_line_buffer that contains the word to complete. TEXT is
151 * the word to complete. We can use the entire contents of rl_line_buffer
152 * in case we want to do some simple parsing. Return the array of matches,
153 * or NULL if there aren't any.
155 static char **i9e_completer(const char *text, int start, __a_unused int end)
157 struct i9e_client_info *ici = i9ep->ici;
159 if (!ici->completers)
161 /* Complete on command names if this is the first word in the line. */
163 return rl_completion_matches(text, command_generator);
164 return rl_completion_matches(text, completion_generator);
168 * Prepare writing to stdout.
170 * \param producer The buffer tree node which produces output.
172 * The i9e subsystem maintains a buffer tree node which may be attached to
173 * another node which generates output (a "producer"). When attached, the i9e
174 * buffer tree node copies the buffers generated by the producer to stdout.
176 * This function attaches the i9e input queue to an output queue of \a
181 void i9e_attach_to_stdout(struct btr_node *producer)
183 btr_remove_node(&i9ep->stdout_btrn);
184 i9ep->stdout_btrn = btr_new_node(&(struct btr_node_description)
185 EMBRACE(.name = "interactive_stdout", .parent = producer));
188 static void wipe_bottom_line(void)
191 int n = i9ep->num_columns;
194 * For reasons beyond my understanding, writing more than 68 characters
195 * here causes MacOS to mess up the terminal. Writing a line of spaces
196 * in smaller chunks works fine though. Weird.
198 fprintf(i9ep->stderr_stream, "\r");
200 if (n >= sizeof(x)) {
201 fprintf(i9ep->stderr_stream, "%s", x);
206 fprintf(i9ep->stderr_stream, "%s", x);
209 fprintf(i9ep->stderr_stream, "\r");
213 * Reset the terminal and save the in-memory command line history.
215 * This should be called before the caller exits.
219 char *hf = i9ep->ici->history_file;
221 rl_deprep_terminal();
227 static void clear_bottom_line(void)
232 if (rl_point == 0 && rl_end == 0)
233 return wipe_bottom_line();
235 * We might have a multi-line input that needs to be wiped here, so the
236 * simple printf("\r<space>\r") is insufficient. To workaround this, we
237 * remove the whole line, redisplay and restore the killed text.
240 text = rl_copy_text(0, rl_end);
241 rl_kill_full_line(0, 0);
243 wipe_bottom_line(); /* wipe out the prompt */
244 rl_insert_text(text);
248 static bool input_available(void)
251 struct timeval tv = {0, 0};
255 FD_SET(i9ep->ici->fds[0], &rfds);
256 ret = para_select(1, &rfds, NULL, &tv);
260 static void i9e_line_handler(char *line)
264 ret = i9ep->ici->line_handler(line);
266 PARA_WARNING_LOG("%s\n", para_strerror(-ret));
270 rl_set_prompt(i9ep->ici->prompt);
276 i9ep->input_eof = true;
280 static void i9e_input(void)
283 rl_callback_read_char();
284 } while (input_available());
287 static void i9e_post_select(struct sched *s, struct task *t)
290 struct btr_node *btrn = i9ep->stdout_btrn;
291 struct i9e_client_info *ici = i9ep->ici;
298 ret = -E_I9E_TERM_RQ;
299 if (i9ep->caught_sigterm)
302 i9ep->caught_sigint = false;
303 if (FD_ISSET(ici->fds[0], &s->rfds))
308 if (i9ep->caught_sigint)
310 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
313 sz = btr_next_buffer(btrn, &buf);
316 ret = xwrite(ici->fds[1], buf, sz);
319 btr_consume(btrn, ret);
322 btr_remove_node(&i9ep->stdout_btrn);
323 rl_set_prompt(i9ep->ici->prompt);
329 static void i9e_pre_select(struct sched *s, __a_unused struct task *t)
333 if (i9ep->input_eof || i9ep->caught_sigint || i9ep->caught_sigterm) {
337 if (i9ep->stdout_btrn) {
338 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
344 para_fd_set(i9ep->ici->fds[1], &s->wfds, &s->max_fileno);
347 * fd[0] might have been reset to blocking mode if our job was moved to
348 * the background due to CTRL-Z or SIGSTOP, so set the fd back to
351 ret = mark_fd_nonblocking(i9ep->ici->fds[0]);
353 PARA_WARNING_LOG("set to nonblock failed: (fd0 %d, %s)\n",
354 i9ep->ici->fds[0], para_strerror(-ret));
355 para_fd_set(i9ep->ici->fds[0], &s->rfds, &s->max_fileno);
358 static void update_winsize(void)
361 int ret = ioctl(i9ep->ici->fds[2], TIOCGWINSZ, (char *)&w);
364 assert(w.ws_col < sizeof(i9ep->empty_line));
365 i9ep->num_columns = w.ws_col;
367 i9ep->num_columns = 80;
369 memset(i9ep->empty_line, ' ', i9ep->num_columns);
370 i9ep->empty_line[i9ep->num_columns] = '\0';
374 * Register the i9e task and initialize readline.
376 * \param ici The i9e configuration parameters set by the caller.
377 * \param s The scheduler instance to add the i9e task to.
379 * The caller must allocate and initialize the structure \a ici points to.
382 * \sa \ref register_task().
384 int i9e_open(struct i9e_client_info *ici, struct sched *s)
388 if (!isatty(ici->fds[0]))
389 return -E_I9E_SETUPTERM;
390 ret = mark_fd_nonblocking(ici->fds[0]);
393 ret = mark_fd_nonblocking(ici->fds[1]);
396 i9ep->task.pre_select = i9e_pre_select;
397 i9ep->task.post_select = i9e_post_select;
398 sprintf(i9ep->task.status, "i9e");
399 register_task(s, &i9ep->task);
400 rl_readline_name = "para_i9e";
401 rl_basic_word_break_characters = " ";
402 rl_attempted_completion_function = i9e_completer;
404 i9ep->stderr_stream = fdopen(ici->fds[2], "w");
405 setvbuf(i9ep->stderr_stream, NULL, _IONBF, 0);
407 if (ici->history_file)
408 read_history(ici->history_file);
410 rl_callback_handler_install(i9ep->ici->prompt, i9e_line_handler);
414 static void reset_line_state(void)
416 if (i9ep->stdout_btrn)
419 rl_reset_line_state();
420 rl_forced_update_display();
424 * The log function of the i9e subsystem.
426 * \param ll Severity log level.
427 * \param fmt Printf-like format string.
429 * This clears the bottom line of the terminal if necessary and writes the
430 * string given by \a fmt to fd[2], where fd[] is the array provided earlier in
433 __printf_2_3 void i9e_log(int ll, const char* fmt,...)
437 if (ll < i9ep->ici->loglevel)
441 vfprintf(i9ep->stderr_stream, fmt, argp);
447 * Tell i9e that the caller received a signal.
449 * \param sig_num The number of the signal received.
451 * Currently the function only cares about \p SIGINT, but this may change.
453 void i9e_signal_dispatch(int sig_num)
455 if (sig_num == SIGWINCH)
456 return update_winsize();
457 if (sig_num == SIGINT) {
458 fprintf(i9ep->stderr_stream, "\n");
459 rl_replace_line ("", false /* clear_undo */);
461 i9ep->caught_sigint = true;
463 if (sig_num == SIGTERM)
464 i9ep->caught_sigterm = true;
468 * Wrapper for select(2) which does not restart on interrupts.
470 * \param n \sa \ref para_select().
471 * \param readfds \sa \ref para_select().
472 * \param writefds \sa \ref para_select().
473 * \param timeout_tv \sa \ref para_select().
475 * \return \sa \ref para_select().
477 * The only difference between this function and \ref para_select() is that
478 * \ref i9e_select() returns zero if the select call returned \p EINTR.
480 int i9e_select(int n, fd_set *readfds, fd_set *writefds,
481 struct timeval *timeout_tv)
483 int ret = select(n, readfds, writefds, NULL, timeout_tv);
489 ret = -ERRNO_TO_PARA_ERROR(errno);
495 * Return the possible completions for a given word.
497 * \param word The word to complete.
498 * \param string_list All possible words in this context.
499 * \param result String list is returned here.
501 * This function never fails. If no completion was found, a string list of
502 * length zero is returned. In any case, the result must be freed by the caller
503 * using \ref free_argv().
505 * This function is independent of readline and may be called before
508 * \return The number of possible completions.
510 int i9e_extract_completions(const char *word, char **string_list,
513 char **matches = para_malloc(sizeof(char *));
514 int match_count = 0, matches_len = 1;
516 int len = strlen(word);
518 for (p = string_list; *p; p++) {
519 if (!is_prefix(word, *p, len))
522 if (match_count >= matches_len) {
524 matches = para_realloc(matches,
525 matches_len * sizeof(char *));
527 matches[match_count - 1] = para_strdup(*p);
529 matches[match_count] = NULL;
535 * Return the list of partially matching words.
537 * \param word The command to complete.
538 * \param completers The array containing all command names.
540 * This is similar to \ref i9e_extract_completions(), but completes on the
541 * command names in \a completers.
543 * \return See \ref i9e_extract_completions().
545 char **i9e_complete_commands(const char *word, struct i9e_completer *completers)
549 int i, match_count, len = strlen(word);
552 * In contrast to completing against an arbitrary string list, here we
553 * know all possible completions and expect that there will not be many
554 * of them. So it should be OK to iterate twice over all commands which
555 * simplifies the code a bit.
557 for (i = 0, match_count = 0; (cmd = completers[i].name); i++) {
558 if (is_prefix(word, cmd, len))
561 matches = para_malloc((match_count + 1) * sizeof(*matches));
562 for (i = 0, match_count = 0; (cmd = completers[i].name); i++)
563 if (is_prefix(word, cmd, len))
564 matches[match_count++] = para_strdup(cmd);
565 matches[match_count] = NULL;
570 * Complete according to the given options.
572 * \param opts All available options.
573 * \param ci Information which was passed to the completer.
574 * \param cr Result pointer.
576 * This convenience helper can be used to complete an option. The array of all
577 * possible options is passed as the first argument. Flags, i.e. options
578 * without an argument, are expected to be listed as strings of type "-X" in \a
579 * opts while options which require an argument should be passed with a
580 * trailing "=" character like "-X=".
582 * If the word can be uniquely completed to a flag option, an additional space
583 * character is appended to the output. For non-flag options no space character
586 void i9e_complete_option(char **opts, struct i9e_completion_info *ci,
587 struct i9e_completion_result *cr)
591 num_matches = i9e_extract_completions(ci->word, opts, &cr->matches);
592 if (num_matches == 1) {
593 char *opt = cr->matches[0];
594 char c = opt[strlen(opt) - 1];
596 cr->dont_append_space = true;
601 * Print possible completions to stdout.
603 * \param completers The array of completion functions.
605 * At the end of the output a line starting with "-o=", followed by the
606 * (possibly empty) list of completion options is printed. Currently, the only
607 * two completion options are "nospace" and "filenames". The former indicates
608 * that no space should be appended even for a unique match while the latter
609 * indicates that usual filename completion should be performed in addition to
610 * the previously printed options.
614 int i9e_print_completions(struct i9e_completer *completers)
616 struct i9e_completion_result cr;
617 struct i9e_completion_info ci;
622 reset_completion_result(&cr);
623 buf = getenv("COMP_POINT");
624 ci.point = buf? atoi(buf) : 0;
625 ci.buffer = para_strdup(getenv("COMP_LINE"));
627 ci.argc = create_argv(ci.buffer, " ", &ci.argv);
628 ci.word_num = compute_word_num(ci.buffer, " ", ci.point);
630 end = ci.buffer + ci.point;
631 for (p = end; p > ci.buffer && *p != ' '; p--)
637 ci.word = para_malloc(n + 1);
638 strncpy(ci.word, p, n);
641 PARA_DEBUG_LOG("line: %s, point: %d (%c), wordnum: %d, word: %s\n",
642 ci.buffer, ci.point, ci.buffer[ci.point], ci.word_num, ci.word);
643 if (ci.word_num == 0)
644 cr.matches = i9e_complete_commands(ci.word, completers);
646 create_matches(&ci, completers, &cr);
648 if (cr.matches && cr.matches[0]) {
649 for (i = 0; cr.matches[i]; i++)
650 printf("%s\n", cr.matches[i]);
654 if (cr.dont_append_space)
656 if (cr.filename_completion_desired)
657 printf(",filenames");
659 free_argv(cr.matches);