1 /* Copyright (C) 2011 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
3 /** \file interactive.c Readline abstraction for interactive sessions. */
8 #include <readline/readline.h>
9 #include <readline/history.h>
10 #include <sys/ioctl.h>
14 #include "buffer_tree.h"
17 #include "interactive.h"
22 struct i9e_client_info *ici;
26 char empty_line[1000];
27 char key_sequence[32];
28 unsigned key_sequence_length;
30 struct btr_node *stdout_btrn;
31 bool last_write_was_status;
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 task_status(i9ep->task);
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));
200 rl_set_keymap(i9ep->bare_km);
203 static void wipe_bottom_line(void)
205 fprintf(i9ep->stderr_stream, "\r%s\r", i9ep->empty_line);
208 #ifndef RL_FREE_KEYMAP_DECLARED
210 * Free all storage associated with a keymap.
212 * This function is not declared in the readline headers although the symbol is
213 * exported and the function is documented in the readline info file. So we
214 * have to declare it here.
216 * \param keymap The keymap to deallocate.
218 void rl_free_keymap(Keymap keymap);
222 * Reset the terminal and save the in-memory command line history.
224 * This should be called before the caller exits.
228 char *hf = i9ep->ici->history_file;
230 rl_free_keymap(i9ep->bare_km);
231 rl_callback_handler_remove();
235 fcntl(i9ep->ici->fds[0], F_SETFL, i9ep->fd_flags[0]);
236 fcntl(i9ep->ici->fds[1], F_SETFL, i9ep->fd_flags[1]);
239 static void clear_bottom_line(void)
244 if (rl_point == 0 && rl_end == 0)
245 return wipe_bottom_line();
247 * We might have a multi-line input that needs to be wiped here, so the
248 * simple printf("\r<space>\r") is insufficient. To workaround this, we
249 * remove the whole line, redisplay and restore the killed text.
252 text = rl_copy_text(0, rl_end);
253 rl_kill_full_line(0, 0);
255 wipe_bottom_line(); /* wipe out the prompt */
256 rl_insert_text(text);
261 static bool input_available(void)
264 struct timeval tv = {0, 0};
268 FD_SET(i9ep->ici->fds[0], &rfds);
269 ret = para_select(1, &rfds, NULL, &tv);
273 static void i9e_line_handler(char *line)
276 struct btr_node *dummy;
279 i9ep->input_eof = true;
285 dummy = btr_new_node(&(struct btr_node_description)
286 EMBRACE(.name = "dummy line handler"));
287 i9e_attach_to_stdout(dummy);
288 ret = i9ep->ici->line_handler(line);
290 PARA_WARNING_LOG("%s\n", para_strerror(-ret));
292 btr_remove_node(&dummy);
297 static int i9e_post_select(__a_unused struct sched *s, __a_unused void *context)
300 struct i9e_client_info *ici = i9ep->ici;
302 size_t sz, consumed = 0;
307 ret = -E_I9E_TERM_RQ;
308 if (i9ep->caught_sigterm)
311 if (i9ep->caught_sigint)
313 while (input_available()) {
314 if (i9ep->stdout_btrn) {
315 unsigned len = i9ep->key_sequence_length;
316 assert(len < sizeof(i9ep->key_sequence) - 1);
317 buf = i9ep->key_sequence + len;
318 ret = read(i9ep->ici->fds[0], buf, 1);
320 ret = -ERRNO_TO_PARA_ERROR(errno);
328 i9ep->key_sequence_length++;
329 rl_stuff_char((int)(unsigned char)*buf);
331 rl_callback_read_char();
334 if (!i9ep->stdout_btrn)
336 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
344 sz = btr_next_buffer(i9ep->stdout_btrn, &buf);
347 if (i9ep->last_write_was_status)
348 fprintf(i9ep->stderr_stream, "\n");
349 i9ep->last_write_was_status = false;
350 ret = xwrite(ici->fds[1], buf, sz);
353 btr_consume(i9ep->stdout_btrn, ret);
355 if (ret == sz && consumed < 10000)
359 if (i9ep->stdout_btrn) {
361 btr_remove_node(&i9ep->stdout_btrn);
362 rl_set_keymap(i9ep->standard_km);
363 rl_set_prompt(i9ep->ici->prompt);
369 i9ep->caught_sigint = false;
373 static void i9e_pre_select(struct sched *s, __a_unused void *context)
377 if (i9ep->input_eof || i9ep->caught_sigint || i9ep->caught_sigterm) {
381 if (i9ep->stdout_btrn) {
382 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
388 para_fd_set(i9ep->ici->fds[1], &s->wfds, &s->max_fileno);
391 * fd[0] might have been reset to blocking mode if our job was moved to
392 * the background due to CTRL-Z or SIGSTOP, so set the fd back to
395 ret = mark_fd_nonblocking(i9ep->ici->fds[0]);
397 PARA_WARNING_LOG("set to nonblock failed: (fd0 %d, %s)\n",
398 i9ep->ici->fds[0], para_strerror(-ret));
399 para_fd_set(i9ep->ici->fds[0], &s->rfds, &s->max_fileno);
402 static void update_winsize(void)
405 int ret = ioctl(i9ep->ici->fds[2], TIOCGWINSZ, (char *)&w);
408 assert(w.ws_col < sizeof(i9ep->empty_line));
409 i9ep->num_columns = w.ws_col;
411 i9ep->num_columns = 80;
413 memset(i9ep->empty_line, ' ', i9ep->num_columns);
414 i9ep->empty_line[i9ep->num_columns] = '\0';
417 static int dispatch_key(__a_unused int count, __a_unused int key)
422 if (i9ep->key_sequence_length == 0)
424 for (i = i9ep->num_key_bindings - 1; i >= 0; i--) {
425 if (strcmp(i9ep->key_sequence, i9ep->ici->bound_keyseqs[i]))
427 i9ep->key_sequence[0] = '\0';
428 i9ep->key_sequence_length = 0;
429 ret = i9ep->ici->key_handler(i);
430 return ret < 0? ret : 0;
432 PARA_WARNING_LOG("ignoring key %d\n", i9ep->key_sequence[0]);
434 * We received an undefined key sequence. Throw away the first byte,
435 * and try to parse the remainder.
437 memmove(i9ep->key_sequence, i9ep->key_sequence + 1,
438 i9ep->key_sequence_length); /* move also terminating zero byte */
439 i9ep->key_sequence_length--;
444 * Register the i9e task and initialize readline.
446 * \param ici The i9e configuration parameters set by the caller.
447 * \param s The scheduler instance to add the i9e task to.
449 * The caller must allocate and initialize the structure \a ici points to.
453 int i9e_open(struct i9e_client_info *ici, struct sched *s)
457 memset(i9ep, 0, sizeof(struct i9e_private));
458 if (!isatty(ici->fds[0]))
459 return -E_I9E_SETUPTERM;
460 ret = fcntl(ici->fds[0], F_GETFL);
462 return -E_I9E_SETUPTERM;
463 i9ep->fd_flags[0] = ret;
464 ret = fcntl(ici->fds[1], F_GETFL);
466 return -E_I9E_SETUPTERM;
467 i9ep->fd_flags[1] = ret;
468 ret = mark_fd_nonblocking(ici->fds[0]);
471 ret = mark_fd_nonblocking(ici->fds[1]);
474 i9ep->task = task_register(&(struct task_info) {
476 .pre_select = i9e_pre_select,
477 .post_select = i9e_post_select,
481 rl_readline_name = "para_i9e";
482 rl_basic_word_break_characters = " ";
483 rl_attempted_completion_function = i9e_completer;
485 i9ep->stderr_stream = fdopen(ici->fds[2], "w");
486 setvbuf(i9ep->stderr_stream, NULL, _IONBF, 0);
488 i9ep->standard_km = rl_get_keymap();
489 i9ep->bare_km = rl_make_bare_keymap();
490 if (ici->bound_keyseqs) {
493 /* bind each key sequence to our dispatcher */
494 for (i = 0; (seq = ici->bound_keyseqs[i]); i++) {
495 if (strlen(seq) >= sizeof(i9ep->key_sequence) - 1) {
496 PARA_WARNING_LOG("ignoring overlong key %s\n",
500 if (rl_bind_keyseq_in_map(seq,
501 dispatch_key, i9ep->bare_km) != 0)
502 PARA_WARNING_LOG("could not bind #%d: %s\n", i, seq);
504 i9ep->num_key_bindings = i;
506 if (ici->history_file)
507 read_history(ici->history_file);
510 rl_callback_handler_install("", i9e_line_handler);
511 i9e_attach_to_stdout(ici->producer);
513 rl_callback_handler_install(i9ep->ici->prompt, i9e_line_handler);
517 static void reset_line_state(void)
519 if (i9ep->stdout_btrn)
522 rl_reset_line_state();
523 rl_forced_update_display();
527 * The log function of the i9e subsystem.
529 * \param ll Severity log level.
530 * \param fmt Printf-like format string.
532 * This clears the bottom line of the terminal if necessary and writes the
533 * string given by \a fmt to fd[2], where fd[] is the array provided earlier in
536 __printf_2_3 void i9e_log(int ll, const char* fmt,...)
540 if (ll < i9ep->ici->loglevel)
544 vfprintf(i9ep->stderr_stream, fmt, argp);
547 i9ep->last_write_was_status = false;
551 * Print the current status to stderr.
553 * \param buf The text to print.
554 * \param len The number of bytes in \a buf.
556 * This clears the bottom line, moves to the beginning of the line and prints
557 * the given text. If the length of this text exceeds the width of the
558 * terminal, the text is shortened by leaving out a part in the middle.
560 void ie9_print_status_bar(char *buf, unsigned len)
562 size_t x = i9ep->num_columns, y = (x - 4) / 2;
567 fprintf(i9ep->stderr_stream, "\r%s", buf);
568 fprintf(i9ep->stderr_stream, " .. ");
569 fprintf(i9ep->stderr_stream, "%s", buf + len - y);
575 strcpy(scratch + 1, buf);
576 memset(scratch + 1 + len, ' ', y);
577 scratch[1 + len + y] = '\r';
578 scratch[2 + len + y] = '\0';
579 fprintf(i9ep->stderr_stream, "\r%s", scratch);
581 i9ep->last_write_was_status = true;
585 * Tell i9e that the caller received a signal.
587 * \param sig_num The number of the signal received.
589 void i9e_signal_dispatch(int sig_num)
591 if (sig_num == SIGWINCH)
592 return update_winsize();
593 if (sig_num == SIGINT) {
594 fprintf(i9ep->stderr_stream, "\n");
595 rl_replace_line ("", false /* clear_undo */);
597 i9ep->caught_sigint = true;
599 if (sig_num == SIGTERM)
600 i9ep->caught_sigterm = true;
604 * Wrapper for select(2) which does not restart on interrupts.
606 * \param n \sa \ref para_select().
607 * \param readfds \sa \ref para_select().
608 * \param writefds \sa \ref para_select().
609 * \param timeout_tv \sa \ref para_select().
611 * \return \sa \ref para_select().
613 * The only difference between this function and \ref para_select() is that
614 * \ref i9e_select() returns zero if the select call returned \p EINTR.
616 int i9e_select(int n, fd_set *readfds, fd_set *writefds,
617 struct timeval *timeout_tv)
619 int ret = select(n, readfds, writefds, NULL, timeout_tv);
625 ret = -ERRNO_TO_PARA_ERROR(errno);
631 * Return the possible completions for a given word.
633 * \param word The word to complete.
634 * \param string_list All possible words in this context.
635 * \param result String list is returned here.
637 * This function never fails. If no completion was found, a string list of
638 * length zero is returned. In any case, the result must be freed by the caller
639 * using \ref free_argv().
641 * This function is independent of readline and may be called before
644 * \return The number of possible completions.
646 int i9e_extract_completions(const char *word, char **string_list,
649 char **matches = para_malloc(sizeof(char *));
650 int match_count = 0, matches_len = 1;
652 int len = strlen(word);
654 for (p = string_list; *p; p++) {
655 if (!is_prefix(word, *p, len))
658 if (match_count >= matches_len) {
660 matches = para_realloc(matches,
661 matches_len * sizeof(char *));
663 matches[match_count - 1] = para_strdup(*p);
665 matches[match_count] = NULL;
671 * Return the list of partially matching words.
673 * \param word The command to complete.
674 * \param completers The array containing all command names.
676 * This is similar to \ref i9e_extract_completions(), but completes on the
677 * command names in \a completers.
679 * \return See \ref i9e_extract_completions().
681 char **i9e_complete_commands(const char *word, struct i9e_completer *completers)
685 int i, match_count, len = strlen(word);
688 * In contrast to completing against an arbitrary string list, here we
689 * know all possible completions and expect that there will not be many
690 * of them. So it should be OK to iterate twice over all commands which
691 * simplifies the code a bit.
693 for (i = 0, match_count = 0; (cmd = completers[i].name); i++) {
694 if (is_prefix(word, cmd, len))
697 matches = para_malloc((match_count + 1) * sizeof(*matches));
698 for (i = 0, match_count = 0; (cmd = completers[i].name); i++)
699 if (is_prefix(word, cmd, len))
700 matches[match_count++] = para_strdup(cmd);
701 matches[match_count] = NULL;
706 * Complete according to the given options.
708 * \param opts All available options.
709 * \param ci Information which was passed to the completer.
710 * \param cr Result pointer.
712 * This convenience helper can be used to complete an option. The array of all
713 * possible options is passed as the first argument. Flags, i.e. options
714 * without an argument, are expected to be listed as strings of type "-X" in \a
715 * opts while options which require an argument should be passed with a
716 * trailing "=" character like "-X=".
718 * If the word can be uniquely completed to a flag option, an additional space
719 * character is appended to the output. For non-flag options no space character
722 void i9e_complete_option(char **opts, struct i9e_completion_info *ci,
723 struct i9e_completion_result *cr)
727 num_matches = i9e_extract_completions(ci->word, opts, &cr->matches);
728 if (num_matches == 1) {
729 char *opt = cr->matches[0];
730 char c = opt[strlen(opt) - 1];
732 cr->dont_append_space = true;
737 * Print possible completions to stdout.
739 * \param completers The array of completion functions.
741 * At the end of the output a line starting with "-o=", followed by the
742 * (possibly empty) list of completion options is printed. Currently, the only
743 * two completion options are "nospace" and "filenames". The former indicates
744 * that no space should be appended even for a unique match while the latter
745 * indicates that usual filename completion should be performed in addition to
746 * the previously printed options.
750 int i9e_print_completions(struct i9e_completer *completers)
752 struct i9e_completion_result cr;
753 struct i9e_completion_info ci;
758 reset_completion_result(&cr);
759 buf = getenv("COMP_POINT");
760 ci.point = buf? atoi(buf) : 0;
761 ci.buffer = para_strdup(getenv("COMP_LINE"));
763 ci.argc = create_argv(ci.buffer, " ", &ci.argv);
764 ci.word_num = compute_word_num(ci.buffer, " ", ci.point);
766 /* determine the current word to complete */
767 end = ci.buffer + ci.point;
770 if (ci.point == 0 || ci.buffer[ci.point - 1] == ' ') {
771 ci.word = para_strdup(NULL);
773 } else /* The cursor is positioned right after a word */
776 for (p = end; p > ci.buffer && *p != ' '; p--)
781 ci.word = para_malloc(n + 1);
782 strncpy(ci.word, p, n);
785 PARA_DEBUG_LOG("line: %s, point: %d (%c), wordnum: %d, word: %s\n",
786 ci.buffer, ci.point, ci.buffer[ci.point], ci.word_num, ci.word);
787 if (ci.word_num == 0)
788 cr.matches = i9e_complete_commands(ci.word, completers);
790 create_matches(&ci, completers, &cr);
792 if (cr.matches && cr.matches[0]) {
793 for (i = 0; cr.matches[i]; i++)
794 printf("%s\n", cr.matches[i]);
798 if (cr.dont_append_space)
800 if (cr.filename_completion_desired)
801 printf(",filenames");
803 free_argv(cr.matches);