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;
43 static struct i9e_private i9e_private, *i9ep = &i9e_private;
46 * Return the error state of the i9e task.
48 * This is mainly useful for other tasks to tell whether the i9e task is still
51 * \return A negative return value of zero means the i9e task terminated. Only
52 * in this case it is safe to call ie9_close().
54 int i9e_get_error(void)
56 return task_status(i9ep->task);
59 static bool is_prefix(const char *partial, const char *full, size_t len)
62 len = strlen(partial);
63 return !strncmp(partial, full, len);
67 * Generator function for command completion. STATE lets us know whether
68 * to start from scratch; without any state (i.e. STATE == 0), then we
69 * start at the top of the list.
71 static char *command_generator(const char *text, int state)
73 static int list_index, len;
75 struct i9e_client_info *ici = i9ep->ici;
77 rl_attempted_completion_over = 1; /* disable filename completion */
79 * If this is a new word to complete, initialize now. This includes
80 * saving the length of TEXT for efficiency, and initializing the index
87 /* Return the next name which partially matches from the command list. */
88 while ((name = ici->completers[list_index].name)) {
90 if (is_prefix(text, name, len))
91 return para_strdup(name);
93 return NULL; /* no names matched */
96 static void reset_completion_result(struct i9e_completion_result *cr)
98 cr->dont_append_space = false;
99 cr->filename_completion_desired = false;
103 static void create_matches(struct i9e_completion_info *ci,
104 struct i9e_completer *completers,
105 struct i9e_completion_result *cr)
109 reset_completion_result(cr);
111 ret = create_argv(ci->buffer, " ", &ci->argv);
112 if (ret < 0 || !ci->argv[0])
116 ci->word_num = compute_word_num(ci->buffer, " ", ci->point);
117 for (i = 0; completers[i].name; i++) {
118 if (strcmp(completers[i].name, ci->argv[0]) != 0)
120 completers[i].completer(ci, cr);
123 PARA_DEBUG_LOG("current word: %d (%s)\n", ci->word_num,
124 ci->argv[ci->word_num]);
126 for (i = 0; cr->matches[i]; i++)
127 PARA_DEBUG_LOG("match %d: %s\n", i, cr->matches[i]);
130 static char *completion_generator(const char *word, int state)
132 static int list_index;
133 static char **argv, **matches;
134 struct i9e_completer *completers = i9ep->ici->completers;
135 struct i9e_completion_info ci = {
136 .word = (char *)word,
138 .buffer = rl_line_buffer,
140 struct i9e_completion_result cr = {.matches = NULL};
144 /* clean up previous matches and set defaults */
150 rl_completion_append_character = ' ';
151 rl_completion_suppress_append = false;
152 rl_attempted_completion_over = true;
154 create_matches(&ci, completers, &cr);
156 matches = cr.matches;
158 rl_completion_suppress_append = cr.dont_append_space;
159 rl_attempted_completion_over = !cr.filename_completion_desired;
163 return matches[list_index++];
167 * Attempt to complete on the contents of TEXT. START and END bound the
168 * region of rl_line_buffer that contains the word to complete. TEXT is
169 * the word to complete. We can use the entire contents of rl_line_buffer
170 * in case we want to do some simple parsing. Return the array of matches,
171 * or NULL if there aren't any.
173 static char **i9e_completer(const char *text, int start, __a_unused int end)
175 struct i9e_client_info *ici = i9ep->ici;
177 if (!ici->completers)
179 /* Complete on command names if this is the first word in the line. */
181 return rl_completion_matches(text, command_generator);
182 return rl_completion_matches(text, completion_generator);
186 * Prepare writing to stdout.
188 * \param producer The buffer tree node which produces output.
190 * The i9e subsystem maintains a buffer tree node which may be attached to
191 * another node which generates output (a "producer"). When attached, the i9e
192 * buffer tree node copies the buffers generated by the producer to stdout.
194 * This function attaches the i9e input queue to an output queue of \a
199 void i9e_attach_to_stdout(struct btr_node *producer)
201 btr_remove_node(&i9ep->stdout_btrn);
202 i9ep->stdout_btrn = btr_new_node(&(struct btr_node_description)
203 EMBRACE(.name = "interactive_stdout", .parent = producer));
204 rl_set_keymap(i9ep->bare_km);
207 static void wipe_bottom_line(void)
209 fprintf(i9ep->stderr_stream, "\r%s\r", i9ep->empty_line);
212 #ifndef RL_FREE_KEYMAP_DECLARED
214 * Free all storage associated with a keymap.
216 * This function is not declared in the readline headers although the symbol is
217 * exported and the function is documented in the readline info file. So we
218 * have to declare it here.
220 * \param keymap The keymap to deallocate.
222 void rl_free_keymap(Keymap keymap);
226 * Reset the terminal and save the in-memory command line history.
228 * This should be called before the caller exits.
232 char *hf = i9ep->ici->history_file;
234 rl_free_keymap(i9ep->bare_km);
235 rl_callback_handler_remove();
239 fcntl(i9ep->ici->fds[0], F_SETFL, i9ep->fd_flags[0]);
240 fcntl(i9ep->ici->fds[1], F_SETFL, i9ep->fd_flags[1]);
243 static void clear_bottom_line(void)
248 if (rl_point == 0 && rl_end == 0)
249 return wipe_bottom_line();
251 * We might have a multi-line input that needs to be wiped here, so the
252 * simple printf("\r<space>\r") is insufficient. To workaround this, we
253 * remove the whole line, redisplay and restore the killed text.
256 text = rl_copy_text(0, rl_end);
257 rl_kill_full_line(0, 0);
259 wipe_bottom_line(); /* wipe out the prompt */
260 rl_insert_text(text);
265 static bool input_available(void)
268 struct timeval tv = {0, 0};
272 FD_SET(i9ep->ici->fds[0], &rfds);
273 ret = para_select(1, &rfds, NULL, &tv);
277 static void i9e_line_handler(char *line)
280 struct btr_node *dummy;
283 i9ep->input_eof = true;
289 dummy = btr_new_node(&(struct btr_node_description)
290 EMBRACE(.name = "dummy line handler"));
291 i9e_attach_to_stdout(dummy);
292 ret = i9ep->ici->line_handler(line);
294 PARA_WARNING_LOG("%s\n", para_strerror(-ret));
296 btr_remove_node(&dummy);
301 static int i9e_post_select(__a_unused struct sched *s, __a_unused void *context)
304 struct i9e_client_info *ici = i9ep->ici;
306 size_t sz, consumed = 0;
311 ret = -E_I9E_TERM_RQ;
312 if (i9ep->caught_sigterm)
315 if (i9ep->caught_sigint)
317 while (input_available()) {
318 if (i9ep->stdout_btrn) {
319 unsigned len = i9ep->key_sequence_length;
320 assert(len < sizeof(i9ep->key_sequence) - 1);
321 buf = i9ep->key_sequence + len;
322 ret = read(i9ep->ici->fds[0], buf, 1);
324 ret = -ERRNO_TO_PARA_ERROR(errno);
331 i9ep->key_sequence_length++;
332 rl_stuff_char((int)(unsigned char)*buf);
334 rl_callback_read_char();
337 if (!i9ep->stdout_btrn)
339 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
347 sz = btr_next_buffer(i9ep->stdout_btrn, &buf);
350 if (i9ep->last_write_was_status)
351 fprintf(i9ep->stderr_stream, "\n");
352 i9ep->last_write_was_status = false;
353 ret = xwrite(ici->fds[1], buf, sz);
356 btr_consume(i9ep->stdout_btrn, ret);
358 if (ret == sz && consumed < 10000)
362 if (i9ep->stdout_btrn) {
364 btr_remove_node(&i9ep->stdout_btrn);
365 rl_set_keymap(i9ep->standard_km);
366 rl_set_prompt(i9ep->ici->prompt);
372 i9ep->caught_sigint = false;
376 static void i9e_pre_select(struct sched *s, __a_unused void *context)
380 if (i9ep->input_eof || i9ep->caught_sigint || i9ep->caught_sigterm) {
384 if (i9ep->stdout_btrn) {
385 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
391 para_fd_set(i9ep->ici->fds[1], &s->wfds, &s->max_fileno);
394 * fd[0] might have been reset to blocking mode if our job was moved to
395 * the background due to CTRL-Z or SIGSTOP, so set the fd back to
398 ret = mark_fd_nonblocking(i9ep->ici->fds[0]);
400 PARA_WARNING_LOG("set to nonblock failed: (fd0 %d, %s)\n",
401 i9ep->ici->fds[0], para_strerror(-ret));
402 para_fd_set(i9ep->ici->fds[0], &s->rfds, &s->max_fileno);
405 static void update_winsize(void)
408 int ret = ioctl(i9ep->ici->fds[2], TIOCGWINSZ, (char *)&w);
411 assert(w.ws_col < sizeof(i9ep->empty_line));
412 i9ep->num_columns = w.ws_col;
414 i9ep->num_columns = 80;
416 memset(i9ep->empty_line, ' ', i9ep->num_columns);
417 i9ep->empty_line[i9ep->num_columns] = '\0';
420 static int dispatch_key(__a_unused int count, __a_unused int key)
425 if (i9ep->key_sequence_length == 0)
427 for (i = i9ep->num_key_bindings - 1; i >= 0; i--) {
428 if (strcmp(i9ep->key_sequence, i9ep->ici->bound_keyseqs[i]))
430 i9ep->key_sequence[0] = '\0';
431 i9ep->key_sequence_length = 0;
432 ret = i9ep->ici->key_handler(i);
433 return ret < 0? ret : 0;
435 PARA_WARNING_LOG("ignoring key %d\n", i9ep->key_sequence[0]);
437 * We received an undefined key sequence. Throw away the first byte,
438 * and try to parse the remainder.
440 memmove(i9ep->key_sequence, i9ep->key_sequence + 1,
441 i9ep->key_sequence_length); /* move also terminating zero byte */
442 i9ep->key_sequence_length--;
447 * Register the i9e task and initialize readline.
449 * \param ici The i9e configuration parameters set by the caller.
450 * \param s The scheduler instance to add the i9e task to.
452 * The caller must allocate and initialize the structure \a ici points to.
456 int i9e_open(struct i9e_client_info *ici, struct sched *s)
460 memset(i9ep, 0, sizeof(struct i9e_private));
461 if (!isatty(ici->fds[0]))
462 return -E_I9E_SETUPTERM;
463 ret = fcntl(ici->fds[0], F_GETFL);
465 return -E_I9E_SETUPTERM;
466 i9ep->fd_flags[0] = ret;
467 ret = fcntl(ici->fds[1], F_GETFL);
469 return -E_I9E_SETUPTERM;
470 i9ep->fd_flags[1] = ret;
471 ret = mark_fd_nonblocking(ici->fds[0]);
474 ret = mark_fd_nonblocking(ici->fds[1]);
477 i9ep->task = task_register(&(struct task_info) {
479 .pre_select = i9e_pre_select,
480 .post_select = i9e_post_select,
484 rl_readline_name = "para_i9e";
485 rl_basic_word_break_characters = " ";
486 rl_attempted_completion_function = i9e_completer;
488 i9ep->stderr_stream = fdopen(ici->fds[2], "w");
489 setvbuf(i9ep->stderr_stream, NULL, _IONBF, 0);
491 i9ep->standard_km = rl_get_keymap();
492 i9ep->bare_km = rl_make_bare_keymap();
493 if (ici->bound_keyseqs) {
496 /* bind each key sequence to our dispatcher */
497 for (i = 0; (seq = ici->bound_keyseqs[i]); i++) {
498 if (strlen(seq) >= sizeof(i9ep->key_sequence) - 1) {
499 PARA_WARNING_LOG("ignoring overlong key %s\n",
503 if (rl_bind_keyseq_in_map(seq,
504 dispatch_key, i9ep->bare_km) != 0)
505 PARA_WARNING_LOG("could not bind #%d: %s\n", i, seq);
507 i9ep->num_key_bindings = i;
509 if (ici->history_file)
510 read_history(ici->history_file);
513 rl_callback_handler_install("", i9e_line_handler);
514 i9e_attach_to_stdout(ici->producer);
516 rl_callback_handler_install(i9ep->ici->prompt, i9e_line_handler);
520 static void reset_line_state(void)
522 if (i9ep->stdout_btrn)
525 rl_reset_line_state();
526 rl_forced_update_display();
530 * The log function of the i9e subsystem.
532 * \param ll Severity log level.
533 * \param fmt Printf-like format string.
535 * This clears the bottom line of the terminal if necessary and writes the
536 * string given by \a fmt to fd[2], where fd[] is the array provided earlier in
539 __printf_2_3 void i9e_log(int ll, const char* fmt,...)
543 if (ll < i9ep->ici->loglevel)
547 vfprintf(i9ep->stderr_stream, fmt, argp);
550 i9ep->last_write_was_status = false;
554 * Print the current status to stderr.
556 * \param buf The text to print.
557 * \param len The number of bytes in \a buf.
559 * This clears the bottom line, moves to the beginning of the line and prints
560 * the given text. If the length of this text exceeds the width of the
561 * terminal, the text is shortened by leaving out a part in the middle.
563 void ie9_print_status_bar(char *buf, unsigned len)
565 size_t x = i9ep->num_columns, y = (x - 4) / 2;
570 fprintf(i9ep->stderr_stream, "\r%s", buf);
571 fprintf(i9ep->stderr_stream, " .. ");
572 fprintf(i9ep->stderr_stream, "%s", buf + len - y);
578 strcpy(scratch + 1, buf);
579 memset(scratch + 1 + len, ' ', y);
580 scratch[1 + len + y] = '\r';
581 scratch[2 + len + y] = '\0';
582 fprintf(i9ep->stderr_stream, "\r%s", scratch);
584 i9ep->last_write_was_status = true;
588 * Tell i9e that the caller received a signal.
590 * \param sig_num The number of the signal received.
592 void i9e_signal_dispatch(int sig_num)
594 if (sig_num == SIGWINCH)
595 return update_winsize();
596 if (sig_num == SIGINT) {
597 fprintf(i9ep->stderr_stream, "\n");
598 rl_replace_line ("", false /* clear_undo */);
600 i9ep->caught_sigint = true;
602 if (sig_num == SIGTERM)
603 i9ep->caught_sigterm = true;
607 * Wrapper for select(2) which does not restart on interrupts.
609 * \param n \sa \ref para_select().
610 * \param readfds \sa \ref para_select().
611 * \param writefds \sa \ref para_select().
612 * \param timeout_tv \sa \ref para_select().
614 * \return \sa \ref para_select().
616 * The only difference between this function and \ref para_select() is that
617 * \ref i9e_select() returns zero if the select call returned \p EINTR.
619 int i9e_select(int n, fd_set *readfds, fd_set *writefds,
620 struct timeval *timeout_tv)
622 int ret = select(n, readfds, writefds, NULL, timeout_tv);
628 ret = -ERRNO_TO_PARA_ERROR(errno);
634 * Return the possible completions for a given word.
636 * \param word The word to complete.
637 * \param string_list All possible words in this context.
638 * \param result String list is returned here.
640 * This function never fails. If no completion was found, a string list of
641 * length zero is returned. In any case, the result must be freed by the caller
642 * using \ref free_argv().
644 * This function is independent of readline and may be called before
647 * \return The number of possible completions.
649 int i9e_extract_completions(const char *word, char **string_list,
652 char **matches = para_malloc(sizeof(char *));
653 int match_count = 0, matches_len = 1;
655 int len = strlen(word);
657 for (p = string_list; *p; p++) {
658 if (!is_prefix(word, *p, len))
661 if (match_count >= matches_len) {
663 matches = para_realloc(matches,
664 matches_len * sizeof(char *));
666 matches[match_count - 1] = para_strdup(*p);
668 matches[match_count] = NULL;
674 * Return the list of partially matching words.
676 * \param word The command to complete.
677 * \param completers The array containing all command names.
679 * This is similar to \ref i9e_extract_completions(), but completes on the
680 * command names in \a completers.
682 * \return See \ref i9e_extract_completions().
684 char **i9e_complete_commands(const char *word, struct i9e_completer *completers)
688 int i, match_count, len = strlen(word);
691 * In contrast to completing against an arbitrary string list, here we
692 * know all possible completions and expect that there will not be many
693 * of them. So it should be OK to iterate twice over all commands which
694 * simplifies the code a bit.
696 for (i = 0, match_count = 0; (cmd = completers[i].name); i++) {
697 if (is_prefix(word, cmd, len))
700 matches = para_malloc((match_count + 1) * sizeof(*matches));
701 for (i = 0, match_count = 0; (cmd = completers[i].name); i++)
702 if (is_prefix(word, cmd, len))
703 matches[match_count++] = para_strdup(cmd);
704 matches[match_count] = NULL;
709 * Complete according to the given options.
711 * \param opts All available options.
712 * \param ci Information which was passed to the completer.
713 * \param cr Result pointer.
715 * This convenience helper can be used to complete an option. The array of all
716 * possible options is passed as the first argument. Flags, i.e. options
717 * without an argument, are expected to be listed as strings of type "-X" in \a
718 * opts while options which require an argument should be passed with a
719 * trailing "=" character like "-X=".
721 * If the word can be uniquely completed to a flag option, an additional space
722 * character is appended to the output. For non-flag options no space character
725 void i9e_complete_option(char **opts, struct i9e_completion_info *ci,
726 struct i9e_completion_result *cr)
730 num_matches = i9e_extract_completions(ci->word, opts, &cr->matches);
731 if (num_matches == 1) {
732 char *opt = cr->matches[0];
733 char c = opt[strlen(opt) - 1];
735 cr->dont_append_space = true;
740 * Print possible completions to stdout.
742 * \param completers The array of completion functions.
744 * At the end of the output a line starting with "-o=", followed by the
745 * (possibly empty) list of completion options is printed. Currently, the only
746 * two completion options are "nospace" and "filenames". The former indicates
747 * that no space should be appended even for a unique match while the latter
748 * indicates that usual filename completion should be performed in addition to
749 * the previously printed options.
753 int i9e_print_completions(struct i9e_completer *completers)
755 struct i9e_completion_result cr;
756 struct i9e_completion_info ci;
761 reset_completion_result(&cr);
762 buf = getenv("COMP_POINT");
763 ci.point = buf? atoi(buf) : 0;
764 ci.buffer = para_strdup(getenv("COMP_LINE"));
766 ci.argc = create_argv(ci.buffer, " ", &ci.argv);
767 ci.word_num = compute_word_num(ci.buffer, " ", ci.point);
769 end = ci.buffer + ci.point;
770 for (p = end; p > ci.buffer && *p != ' '; p--)
776 ci.word = para_malloc(n + 1);
777 strncpy(ci.word, p, n);
780 PARA_DEBUG_LOG("line: %s, point: %d (%c), wordnum: %d, word: %s\n",
781 ci.buffer, ci.point, ci.buffer[ci.point], ci.word_num, ci.word);
782 if (ci.word_num == 0)
783 cr.matches = i9e_complete_commands(ci.word, completers);
785 create_matches(&ci, completers, &cr);
787 if (cr.matches && cr.matches[0]) {
788 for (i = 0; cr.matches[i]; i++)
789 printf("%s\n", cr.matches[i]);
793 if (cr.dont_append_space)
795 if (cr.filename_completion_desired)
796 printf(",filenames");
798 free_argv(cr.matches);