2 * Copyright (C) 2011 Andre Noll <maan@tuebingen.mpg.de>
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>
18 #include "buffer_tree.h"
21 #include "interactive.h"
26 struct i9e_client_info *ici;
30 char empty_line[1000];
31 char key_sequence[32];
32 unsigned key_sequence_length;
34 struct btr_node *stdout_btrn;
35 bool last_write_was_status;
42 static struct i9e_private i9e_private, *i9ep = &i9e_private;
45 * Return the error state of the i9e task.
47 * This is mainly useful for other tasks to tell whether the i9e task is still
50 * \return A negative return value of zero means the i9e task terminated. Only
51 * in this case it is safe to call ie9_close().
53 int i9e_get_error(void)
55 return task_status(i9ep->task);
58 static bool is_prefix(const char *partial, const char *full, size_t len)
61 len = strlen(partial);
62 return !strncmp(partial, full, len);
66 * Generator function for command completion. STATE lets us know whether
67 * to start from scratch; without any state (i.e. STATE == 0), then we
68 * start at the top of the list.
70 static char *command_generator(const char *text, int state)
72 static int list_index, len;
74 struct i9e_client_info *ici = i9ep->ici;
76 rl_attempted_completion_over = 1; /* disable filename completion */
78 * If this is a new word to complete, initialize now. This includes
79 * saving the length of TEXT for efficiency, and initializing the index
86 /* Return the next name which partially matches from the command list. */
87 while ((name = ici->completers[list_index].name)) {
89 if (is_prefix(text, name, len))
90 return para_strdup(name);
92 return NULL; /* no names matched */
95 static void reset_completion_result(struct i9e_completion_result *cr)
97 cr->dont_append_space = false;
98 cr->filename_completion_desired = false;
102 static void create_matches(struct i9e_completion_info *ci,
103 struct i9e_completer *completers,
104 struct i9e_completion_result *cr)
108 reset_completion_result(cr);
110 ret = create_argv(ci->buffer, " ", &ci->argv);
111 if (ret < 0 || !ci->argv[0])
115 ci->word_num = compute_word_num(ci->buffer, " ", ci->point);
116 for (i = 0; completers[i].name; i++) {
117 if (strcmp(completers[i].name, ci->argv[0]) != 0)
119 completers[i].completer(ci, cr);
122 PARA_DEBUG_LOG("current word: %d (%s)\n", ci->word_num,
123 ci->argv[ci->word_num]);
125 for (i = 0; cr->matches[i]; i++)
126 PARA_DEBUG_LOG("match %d: %s\n", i, cr->matches[i]);
129 static char *completion_generator(const char *word, int state)
131 static int list_index;
132 static char **argv, **matches;
133 struct i9e_completer *completers = i9ep->ici->completers;
134 struct i9e_completion_info ci = {
135 .word = (char *)word,
137 .buffer = rl_line_buffer,
139 struct i9e_completion_result cr = {.matches = NULL};
143 /* clean up previous matches and set defaults */
149 rl_completion_append_character = ' ';
150 rl_completion_suppress_append = false;
151 rl_attempted_completion_over = true;
153 create_matches(&ci, completers, &cr);
155 matches = cr.matches;
157 rl_completion_suppress_append = cr.dont_append_space;
158 rl_attempted_completion_over = !cr.filename_completion_desired;
162 return matches[list_index++];
166 * Attempt to complete on the contents of TEXT. START and END bound the
167 * region of rl_line_buffer that contains the word to complete. TEXT is
168 * the word to complete. We can use the entire contents of rl_line_buffer
169 * in case we want to do some simple parsing. Return the array of matches,
170 * or NULL if there aren't any.
172 static char **i9e_completer(const char *text, int start, __a_unused int end)
174 struct i9e_client_info *ici = i9ep->ici;
176 if (!ici->completers)
178 /* Complete on command names if this is the first word in the line. */
180 return rl_completion_matches(text, command_generator);
181 return rl_completion_matches(text, completion_generator);
185 * Prepare writing to stdout.
187 * \param producer The buffer tree node which produces output.
189 * The i9e subsystem maintains a buffer tree node which may be attached to
190 * another node which generates output (a "producer"). When attached, the i9e
191 * buffer tree node copies the buffers generated by the producer to stdout.
193 * This function attaches the i9e input queue to an output queue of \a
198 void i9e_attach_to_stdout(struct btr_node *producer)
200 btr_remove_node(&i9ep->stdout_btrn);
201 i9ep->stdout_btrn = btr_new_node(&(struct btr_node_description)
202 EMBRACE(.name = "interactive_stdout", .parent = producer));
203 rl_set_keymap(i9ep->bare_km);
206 static void wipe_bottom_line(void)
209 int n = i9ep->num_columns;
212 * For reasons beyond my understanding, writing more than 68 characters
213 * here causes MacOS to mess up the terminal. Writing a line of spaces
214 * in smaller chunks works fine though. Weird.
216 fprintf(i9ep->stderr_stream, "\r");
218 if (n >= sizeof(x)) {
219 fprintf(i9ep->stderr_stream, "%s", x);
224 fprintf(i9ep->stderr_stream, "%s", x);
227 fprintf(i9ep->stderr_stream, "\r");
230 #ifndef RL_FREE_KEYMAP_DECLARED
232 * Free all storage associated with a keymap.
234 * This function is not declared in the readline headers although the symbol is
235 * exported and the function is documented in the readline info file. So we
236 * have to declare it here.
238 * \param keymap The keymap to deallocate.
240 void rl_free_keymap(Keymap keymap);
244 * Reset the terminal and save the in-memory command line history.
246 * This should be called before the caller exits.
250 char *hf = i9ep->ici->history_file;
252 rl_free_keymap(i9ep->bare_km);
253 rl_callback_handler_remove();
259 static void clear_bottom_line(void)
264 if (rl_point == 0 && rl_end == 0)
265 return wipe_bottom_line();
267 * We might have a multi-line input that needs to be wiped here, so the
268 * simple printf("\r<space>\r") is insufficient. To workaround this, we
269 * remove the whole line, redisplay and restore the killed text.
272 text = rl_copy_text(0, rl_end);
273 rl_kill_full_line(0, 0);
275 wipe_bottom_line(); /* wipe out the prompt */
276 rl_insert_text(text);
281 static bool input_available(void)
284 struct timeval tv = {0, 0};
288 FD_SET(i9ep->ici->fds[0], &rfds);
289 ret = para_select(1, &rfds, NULL, &tv);
293 static void i9e_line_handler(char *line)
296 struct btr_node *dummy;
299 i9ep->input_eof = true;
305 dummy = btr_new_node(&(struct btr_node_description)
306 EMBRACE(.name = "dummy line handler"));
307 i9e_attach_to_stdout(dummy);
308 ret = i9ep->ici->line_handler(line);
310 PARA_WARNING_LOG("%s\n", para_strerror(-ret));
312 btr_remove_node(&dummy);
317 static int i9e_post_select(__a_unused struct sched *s, __a_unused void *context)
320 struct i9e_client_info *ici = i9ep->ici;
322 size_t sz, consumed = 0;
327 ret = -E_I9E_TERM_RQ;
328 if (i9ep->caught_sigterm)
331 if (i9ep->caught_sigint)
333 while (input_available()) {
334 if (i9ep->stdout_btrn) {
335 unsigned len = i9ep->key_sequence_length;
336 assert(len < sizeof(i9ep->key_sequence) - 1);
337 buf = i9ep->key_sequence + len;
338 ret = read(i9ep->ici->fds[0], buf, 1);
340 ret = -ERRNO_TO_PARA_ERROR(errno);
347 i9ep->key_sequence_length++;
348 rl_stuff_char((int)(unsigned char)*buf);
350 rl_callback_read_char();
353 if (!i9ep->stdout_btrn)
355 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
363 sz = btr_next_buffer(i9ep->stdout_btrn, &buf);
366 if (i9ep->last_write_was_status)
367 fprintf(i9ep->stderr_stream, "\n");
368 i9ep->last_write_was_status = false;
369 ret = xwrite(ici->fds[1], buf, sz);
372 btr_consume(i9ep->stdout_btrn, ret);
374 if (ret == sz && consumed < 10000)
378 if (i9ep->stdout_btrn) {
380 btr_remove_node(&i9ep->stdout_btrn);
381 rl_set_keymap(i9ep->standard_km);
382 rl_set_prompt(i9ep->ici->prompt);
388 i9ep->caught_sigint = false;
392 static void i9e_pre_select(struct sched *s, __a_unused void *context)
396 if (i9ep->input_eof || i9ep->caught_sigint || i9ep->caught_sigterm) {
400 if (i9ep->stdout_btrn) {
401 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
407 para_fd_set(i9ep->ici->fds[1], &s->wfds, &s->max_fileno);
410 * fd[0] might have been reset to blocking mode if our job was moved to
411 * the background due to CTRL-Z or SIGSTOP, so set the fd back to
414 ret = mark_fd_nonblocking(i9ep->ici->fds[0]);
416 PARA_WARNING_LOG("set to nonblock failed: (fd0 %d, %s)\n",
417 i9ep->ici->fds[0], para_strerror(-ret));
418 para_fd_set(i9ep->ici->fds[0], &s->rfds, &s->max_fileno);
421 static void update_winsize(void)
424 int ret = ioctl(i9ep->ici->fds[2], TIOCGWINSZ, (char *)&w);
427 assert(w.ws_col < sizeof(i9ep->empty_line));
428 i9ep->num_columns = w.ws_col;
430 i9ep->num_columns = 80;
432 memset(i9ep->empty_line, ' ', i9ep->num_columns);
433 i9ep->empty_line[i9ep->num_columns] = '\0';
436 static int dispatch_key(__a_unused int count, __a_unused int key)
441 if (i9ep->key_sequence_length == 0)
443 for (i = i9ep->num_key_bindings - 1; i >= 0; i--) {
444 if (strcmp(i9ep->key_sequence, i9ep->ici->bound_keyseqs[i]))
446 i9ep->key_sequence[0] = '\0';
447 i9ep->key_sequence_length = 0;
448 ret = i9ep->ici->key_handler(i);
449 return ret < 0? ret : 0;
451 PARA_WARNING_LOG("ignoring key %d\n", i9ep->key_sequence[0]);
453 * We received an undefined key sequence. Throw away the first byte,
454 * and try to parse the remainder.
456 memmove(i9ep->key_sequence, i9ep->key_sequence + 1,
457 i9ep->key_sequence_length); /* move also terminating zero byte */
458 i9ep->key_sequence_length--;
463 * Register the i9e task and initialize readline.
465 * \param ici The i9e configuration parameters set by the caller.
466 * \param s The scheduler instance to add the i9e task to.
468 * The caller must allocate and initialize the structure \a ici points to.
472 int i9e_open(struct i9e_client_info *ici, struct sched *s)
476 memset(i9ep, 0, sizeof(struct i9e_private));
477 if (!isatty(ici->fds[0]))
478 return -E_I9E_SETUPTERM;
479 ret = mark_fd_nonblocking(ici->fds[0]);
482 ret = mark_fd_nonblocking(ici->fds[1]);
485 i9ep->task = task_register(&(struct task_info) {
487 .pre_select = i9e_pre_select,
488 .post_select = i9e_post_select,
492 rl_readline_name = "para_i9e";
493 rl_basic_word_break_characters = " ";
494 rl_attempted_completion_function = i9e_completer;
496 i9ep->stderr_stream = fdopen(ici->fds[2], "w");
497 setvbuf(i9ep->stderr_stream, NULL, _IONBF, 0);
499 i9ep->standard_km = rl_get_keymap();
500 i9ep->bare_km = rl_make_bare_keymap();
501 if (ici->bound_keyseqs) {
504 /* bind each key sequence to our dispatcher */
505 for (i = 0; (seq = ici->bound_keyseqs[i]); i++) {
506 if (strlen(seq) >= sizeof(i9ep->key_sequence) - 1) {
507 PARA_WARNING_LOG("ignoring overlong key %s\n",
511 if (rl_bind_keyseq_in_map(seq,
512 dispatch_key, i9ep->bare_km) != 0)
513 PARA_WARNING_LOG("could not bind #%d: %s\n", i, seq);
515 i9ep->num_key_bindings = i;
517 if (ici->history_file)
518 read_history(ici->history_file);
521 rl_callback_handler_install("", i9e_line_handler);
522 i9e_attach_to_stdout(ici->producer);
524 rl_callback_handler_install(i9ep->ici->prompt, i9e_line_handler);
528 static void reset_line_state(void)
530 if (i9ep->stdout_btrn)
533 rl_reset_line_state();
534 rl_forced_update_display();
538 * The log function of the i9e subsystem.
540 * \param ll Severity log level.
541 * \param fmt Printf-like format string.
543 * This clears the bottom line of the terminal if necessary and writes the
544 * string given by \a fmt to fd[2], where fd[] is the array provided earlier in
547 __printf_2_3 void i9e_log(int ll, const char* fmt,...)
551 if (ll < i9ep->ici->loglevel)
555 vfprintf(i9ep->stderr_stream, fmt, argp);
558 i9ep->last_write_was_status = false;
562 * Print the current status to stderr.
564 * \param buf The text to print.
565 * \param len The number of bytes in \a buf.
567 * This clears the bottom line, moves to the beginning of the line and prints
568 * the given text. If the length of this text exceeds the width of the
569 * terminal, the text is shortened by leaving out a part in the middle.
571 void ie9_print_status_bar(char *buf, unsigned len)
573 size_t x = i9ep->num_columns, y = (x - 4) / 2;
578 fprintf(i9ep->stderr_stream, "\r%s", buf);
579 fprintf(i9ep->stderr_stream, " .. ");
580 fprintf(i9ep->stderr_stream, "%s", buf + len - y);
586 strcpy(scratch + 1, buf);
587 memset(scratch + 1 + len, ' ', y);
588 scratch[1 + len + y] = '\r';
589 scratch[2 + len + y] = '\0';
590 fprintf(i9ep->stderr_stream, "\r%s", scratch);
592 i9ep->last_write_was_status = true;
596 * Tell i9e that the caller received a signal.
598 * \param sig_num The number of the signal received.
600 void i9e_signal_dispatch(int sig_num)
602 if (sig_num == SIGWINCH)
603 return update_winsize();
604 if (sig_num == SIGINT) {
605 fprintf(i9ep->stderr_stream, "\n");
606 rl_replace_line ("", false /* clear_undo */);
608 i9ep->caught_sigint = true;
610 if (sig_num == SIGTERM)
611 i9ep->caught_sigterm = true;
615 * Wrapper for select(2) which does not restart on interrupts.
617 * \param n \sa \ref para_select().
618 * \param readfds \sa \ref para_select().
619 * \param writefds \sa \ref para_select().
620 * \param timeout_tv \sa \ref para_select().
622 * \return \sa \ref para_select().
624 * The only difference between this function and \ref para_select() is that
625 * \ref i9e_select() returns zero if the select call returned \p EINTR.
627 int i9e_select(int n, fd_set *readfds, fd_set *writefds,
628 struct timeval *timeout_tv)
630 int ret = select(n, readfds, writefds, NULL, timeout_tv);
636 ret = -ERRNO_TO_PARA_ERROR(errno);
642 * Return the possible completions for a given word.
644 * \param word The word to complete.
645 * \param string_list All possible words in this context.
646 * \param result String list is returned here.
648 * This function never fails. If no completion was found, a string list of
649 * length zero is returned. In any case, the result must be freed by the caller
650 * using \ref free_argv().
652 * This function is independent of readline and may be called before
655 * \return The number of possible completions.
657 int i9e_extract_completions(const char *word, char **string_list,
660 char **matches = para_malloc(sizeof(char *));
661 int match_count = 0, matches_len = 1;
663 int len = strlen(word);
665 for (p = string_list; *p; p++) {
666 if (!is_prefix(word, *p, len))
669 if (match_count >= matches_len) {
671 matches = para_realloc(matches,
672 matches_len * sizeof(char *));
674 matches[match_count - 1] = para_strdup(*p);
676 matches[match_count] = NULL;
682 * Return the list of partially matching words.
684 * \param word The command to complete.
685 * \param completers The array containing all command names.
687 * This is similar to \ref i9e_extract_completions(), but completes on the
688 * command names in \a completers.
690 * \return See \ref i9e_extract_completions().
692 char **i9e_complete_commands(const char *word, struct i9e_completer *completers)
696 int i, match_count, len = strlen(word);
699 * In contrast to completing against an arbitrary string list, here we
700 * know all possible completions and expect that there will not be many
701 * of them. So it should be OK to iterate twice over all commands which
702 * simplifies the code a bit.
704 for (i = 0, match_count = 0; (cmd = completers[i].name); i++) {
705 if (is_prefix(word, cmd, len))
708 matches = para_malloc((match_count + 1) * sizeof(*matches));
709 for (i = 0, match_count = 0; (cmd = completers[i].name); i++)
710 if (is_prefix(word, cmd, len))
711 matches[match_count++] = para_strdup(cmd);
712 matches[match_count] = NULL;
717 * Complete according to the given options.
719 * \param opts All available options.
720 * \param ci Information which was passed to the completer.
721 * \param cr Result pointer.
723 * This convenience helper can be used to complete an option. The array of all
724 * possible options is passed as the first argument. Flags, i.e. options
725 * without an argument, are expected to be listed as strings of type "-X" in \a
726 * opts while options which require an argument should be passed with a
727 * trailing "=" character like "-X=".
729 * If the word can be uniquely completed to a flag option, an additional space
730 * character is appended to the output. For non-flag options no space character
733 void i9e_complete_option(char **opts, struct i9e_completion_info *ci,
734 struct i9e_completion_result *cr)
738 num_matches = i9e_extract_completions(ci->word, opts, &cr->matches);
739 if (num_matches == 1) {
740 char *opt = cr->matches[0];
741 char c = opt[strlen(opt) - 1];
743 cr->dont_append_space = true;
748 * Print possible completions to stdout.
750 * \param completers The array of completion functions.
752 * At the end of the output a line starting with "-o=", followed by the
753 * (possibly empty) list of completion options is printed. Currently, the only
754 * two completion options are "nospace" and "filenames". The former indicates
755 * that no space should be appended even for a unique match while the latter
756 * indicates that usual filename completion should be performed in addition to
757 * the previously printed options.
761 int i9e_print_completions(struct i9e_completer *completers)
763 struct i9e_completion_result cr;
764 struct i9e_completion_info ci;
769 reset_completion_result(&cr);
770 buf = getenv("COMP_POINT");
771 ci.point = buf? atoi(buf) : 0;
772 ci.buffer = para_strdup(getenv("COMP_LINE"));
774 ci.argc = create_argv(ci.buffer, " ", &ci.argv);
775 ci.word_num = compute_word_num(ci.buffer, " ", ci.point);
777 end = ci.buffer + ci.point;
778 for (p = end; p > ci.buffer && *p != ' '; p--)
784 ci.word = para_malloc(n + 1);
785 strncpy(ci.word, p, n);
788 PARA_DEBUG_LOG("line: %s, point: %d (%c), wordnum: %d, word: %s\n",
789 ci.buffer, ci.point, ci.buffer[ci.point], ci.word_num, ci.word);
790 if (ci.word_num == 0)
791 cr.matches = i9e_complete_commands(ci.word, completers);
793 create_matches(&ci, completers, &cr);
795 if (cr.matches && cr.matches[0]) {
796 for (i = 0; cr.matches[i]; i++)
797 printf("%s\n", cr.matches[i]);
801 if (cr.dont_append_space)
803 if (cr.filename_completion_desired)
804 printf(",filenames");
806 free_argv(cr.matches);