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];
32 struct btr_node *stdout_btrn;
33 bool last_write_was_status;
40 static struct i9e_private i9e_private, *i9ep = &i9e_private;
43 * Return the error state of the i9e task.
45 * This is mainly useful for other tasks to tell whether the i9e task is still
48 * \return A negative return value of zero means the i9e task terminated. Only
49 * in this case it is safe to call ie9_close().
51 int i9e_get_error(void)
53 return task_status(i9ep->task);
56 static bool is_prefix(const char *partial, const char *full, size_t len)
59 len = strlen(partial);
60 return !strncmp(partial, full, len);
64 * Generator function for command completion. STATE lets us know whether
65 * to start from scratch; without any state (i.e. STATE == 0), then we
66 * start at the top of the list.
68 static char *command_generator(const char *text, int state)
70 static int list_index, len;
72 struct i9e_client_info *ici = i9ep->ici;
74 rl_attempted_completion_over = 1; /* disable filename completion */
76 * If this is a new word to complete, initialize now. This includes
77 * saving the length of TEXT for efficiency, and initializing the index
84 /* Return the next name which partially matches from the command list. */
85 while ((name = ici->completers[list_index].name)) {
87 if (is_prefix(text, name, len))
88 return para_strdup(name);
90 return NULL; /* no names matched */
93 static void reset_completion_result(struct i9e_completion_result *cr)
95 cr->dont_append_space = false;
96 cr->filename_completion_desired = false;
100 static void create_matches(struct i9e_completion_info *ci,
101 struct i9e_completer *completers,
102 struct i9e_completion_result *cr)
106 reset_completion_result(cr);
108 ret = create_argv(ci->buffer, " ", &ci->argv);
109 if (ret < 0 || !ci->argv[0])
113 ci->word_num = compute_word_num(ci->buffer, " ", ci->point);
114 for (i = 0; completers[i].name; i++) {
115 if (strcmp(completers[i].name, ci->argv[0]) != 0)
117 completers[i].completer(ci, cr);
120 PARA_DEBUG_LOG("current word: %d (%s)\n", ci->word_num,
121 ci->argv[ci->word_num]);
123 for (i = 0; cr->matches[i]; i++)
124 PARA_DEBUG_LOG("match %d: %s\n", i, cr->matches[i]);
127 static char *completion_generator(const char *word, int state)
129 static int list_index;
130 static char **argv, **matches;
131 struct i9e_completer *completers = i9ep->ici->completers;
132 struct i9e_completion_info ci = {
133 .word = (char *)word,
135 .buffer = rl_line_buffer,
137 struct i9e_completion_result cr = {.matches = NULL};
141 /* clean up previous matches and set defaults */
147 rl_completion_append_character = ' ';
148 rl_completion_suppress_append = false;
149 rl_attempted_completion_over = true;
151 create_matches(&ci, completers, &cr);
153 matches = cr.matches;
155 rl_completion_suppress_append = cr.dont_append_space;
156 rl_attempted_completion_over = !cr.filename_completion_desired;
160 return matches[list_index++];
164 * Attempt to complete on the contents of TEXT. START and END bound the
165 * region of rl_line_buffer that contains the word to complete. TEXT is
166 * the word to complete. We can use the entire contents of rl_line_buffer
167 * in case we want to do some simple parsing. Return the array of matches,
168 * or NULL if there aren't any.
170 static char **i9e_completer(const char *text, int start, __a_unused int end)
172 struct i9e_client_info *ici = i9ep->ici;
174 if (!ici->completers)
176 /* Complete on command names if this is the first word in the line. */
178 return rl_completion_matches(text, command_generator);
179 return rl_completion_matches(text, completion_generator);
183 * Prepare writing to stdout.
185 * \param producer The buffer tree node which produces output.
187 * The i9e subsystem maintains a buffer tree node which may be attached to
188 * another node which generates output (a "producer"). When attached, the i9e
189 * buffer tree node copies the buffers generated by the producer to stdout.
191 * This function attaches the i9e input queue to an output queue of \a
196 void i9e_attach_to_stdout(struct btr_node *producer)
198 btr_remove_node(&i9ep->stdout_btrn);
199 i9ep->stdout_btrn = btr_new_node(&(struct btr_node_description)
200 EMBRACE(.name = "interactive_stdout", .parent = producer));
201 rl_set_keymap(i9ep->bare_km);
204 static void wipe_bottom_line(void)
207 int n = i9ep->num_columns;
210 * For reasons beyond my understanding, writing more than 68 characters
211 * here causes MacOS to mess up the terminal. Writing a line of spaces
212 * in smaller chunks works fine though. Weird.
214 fprintf(i9ep->stderr_stream, "\r");
216 if (n >= sizeof(x)) {
217 fprintf(i9ep->stderr_stream, "%s", x);
222 fprintf(i9ep->stderr_stream, "%s", x);
225 fprintf(i9ep->stderr_stream, "\r");
228 #ifndef RL_FREE_KEYMAP_DECLARED
230 * Free all storage associated with a keymap.
232 * This function is not declared in the readline headers although the symbol is
233 * exported and the function is documented in the readline info file. So we
234 * have to declare it here.
236 * \param keymap The keymap to deallocate.
238 void rl_free_keymap(Keymap keymap);
242 * Reset the terminal and save the in-memory command line history.
244 * This should be called before the caller exits.
248 char *hf = i9ep->ici->history_file;
250 rl_free_keymap(i9ep->bare_km);
251 rl_callback_handler_remove();
257 static void clear_bottom_line(void)
262 if (rl_point == 0 && rl_end == 0)
263 return wipe_bottom_line();
265 * We might have a multi-line input that needs to be wiped here, so the
266 * simple printf("\r<space>\r") is insufficient. To workaround this, we
267 * remove the whole line, redisplay and restore the killed text.
270 text = rl_copy_text(0, rl_end);
271 rl_kill_full_line(0, 0);
273 wipe_bottom_line(); /* wipe out the prompt */
274 rl_insert_text(text);
279 static bool input_available(void)
282 struct timeval tv = {0, 0};
286 FD_SET(i9ep->ici->fds[0], &rfds);
287 ret = para_select(1, &rfds, NULL, &tv);
291 static void i9e_line_handler(char *line)
294 struct btr_node *dummy;
297 i9ep->input_eof = true;
303 dummy = btr_new_node(&(struct btr_node_description)
304 EMBRACE(.name = "dummy line handler"));
305 i9e_attach_to_stdout(dummy);
306 ret = i9ep->ici->line_handler(line);
308 PARA_WARNING_LOG("%s\n", para_strerror(-ret));
310 btr_remove_node(&dummy);
315 static int i9e_post_select(__a_unused struct sched *s, __a_unused void *context)
318 struct i9e_client_info *ici = i9ep->ici;
320 size_t sz, consumed = 0;
325 ret = -E_I9E_TERM_RQ;
326 if (i9ep->caught_sigterm)
329 if (i9ep->caught_sigint)
331 while (input_available())
332 rl_callback_read_char();
333 if (!i9ep->stdout_btrn)
335 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
343 sz = btr_next_buffer(i9ep->stdout_btrn, &buf);
346 if (i9ep->last_write_was_status)
347 fprintf(i9ep->stderr_stream, "\n");
348 i9ep->last_write_was_status = false;
349 ret = xwrite(ici->fds[1], buf, sz);
352 btr_consume(i9ep->stdout_btrn, ret);
354 if (ret == sz && consumed < 10000)
358 if (i9ep->stdout_btrn) {
360 btr_remove_node(&i9ep->stdout_btrn);
361 rl_set_keymap(i9ep->standard_km);
362 rl_set_prompt(i9ep->ici->prompt);
368 i9ep->caught_sigint = false;
372 static void i9e_pre_select(struct sched *s, __a_unused void *context)
376 if (i9ep->input_eof || i9ep->caught_sigint || i9ep->caught_sigterm) {
380 if (i9ep->stdout_btrn) {
381 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
387 para_fd_set(i9ep->ici->fds[1], &s->wfds, &s->max_fileno);
390 * fd[0] might have been reset to blocking mode if our job was moved to
391 * the background due to CTRL-Z or SIGSTOP, so set the fd back to
394 ret = mark_fd_nonblocking(i9ep->ici->fds[0]);
396 PARA_WARNING_LOG("set to nonblock failed: (fd0 %d, %s)\n",
397 i9ep->ici->fds[0], para_strerror(-ret));
398 para_fd_set(i9ep->ici->fds[0], &s->rfds, &s->max_fileno);
401 static void update_winsize(void)
404 int ret = ioctl(i9ep->ici->fds[2], TIOCGWINSZ, (char *)&w);
407 assert(w.ws_col < sizeof(i9ep->empty_line));
408 i9ep->num_columns = w.ws_col;
410 i9ep->num_columns = 80;
412 memset(i9ep->empty_line, ' ', i9ep->num_columns);
413 i9ep->empty_line[i9ep->num_columns] = '\0';
416 static int dispatch_key(__a_unused int count, __a_unused int key)
420 for (i = i9ep->num_key_bindings - 1; i >= 0; i--) {
421 if (strcmp(rl_executing_keyseq, i9ep->ici->bound_keyseqs[i]))
423 ret = i9ep->ici->key_handler(i);
424 return ret < 0? ret : 0;
430 * Register the i9e task and initialize readline.
432 * \param ici The i9e configuration parameters set by the caller.
433 * \param s The scheduler instance to add the i9e task to.
435 * The caller must allocate and initialize the structure \a ici points to.
439 int i9e_open(struct i9e_client_info *ici, struct sched *s)
443 if (!isatty(ici->fds[0]))
444 return -E_I9E_SETUPTERM;
445 ret = mark_fd_nonblocking(ici->fds[0]);
448 ret = mark_fd_nonblocking(ici->fds[1]);
451 i9ep->task = task_register(&(struct task_info) {
453 .pre_select = i9e_pre_select,
454 .post_select = i9e_post_select,
458 rl_readline_name = "para_i9e";
459 rl_basic_word_break_characters = " ";
460 rl_attempted_completion_function = i9e_completer;
462 i9ep->stderr_stream = fdopen(ici->fds[2], "w");
463 setvbuf(i9ep->stderr_stream, NULL, _IONBF, 0);
465 i9ep->standard_km = rl_get_keymap();
466 i9ep->bare_km = rl_make_bare_keymap();
467 if (ici->bound_keyseqs) {
470 /* bind each key sequence to the our dispatcher */
471 for (i = 0; (seq = ici->bound_keyseqs[i]); i++)
472 rl_generic_bind(ISFUNC, seq, (char *)dispatch_key,
474 i9ep->num_key_bindings = i;
476 if (ici->history_file)
477 read_history(ici->history_file);
480 rl_callback_handler_install("", i9e_line_handler);
481 i9e_attach_to_stdout(ici->producer);
483 rl_callback_handler_install(i9ep->ici->prompt, i9e_line_handler);
487 static void reset_line_state(void)
489 if (i9ep->stdout_btrn)
492 rl_reset_line_state();
493 rl_forced_update_display();
497 * The log function of the i9e subsystem.
499 * \param ll Severity log level.
500 * \param fmt Printf-like format string.
502 * This clears the bottom line of the terminal if necessary and writes the
503 * string given by \a fmt to fd[2], where fd[] is the array provided earlier in
506 __printf_2_3 void i9e_log(int ll, const char* fmt,...)
510 if (ll < i9ep->ici->loglevel)
514 vfprintf(i9ep->stderr_stream, fmt, argp);
517 i9ep->last_write_was_status = false;
521 * Print the current status to stderr.
523 * \param buf The text to print.
524 * \param len The number of bytes in \a buf.
526 * This clears the bottom line, moves to the beginning of the line and prints
527 * the given text. If the length of this text exceeds the width of the
528 * terminal, the text is shortened by leaving out a part in the middle.
530 void ie9_print_status_bar(char *buf, unsigned len)
532 size_t x = i9ep->num_columns, y = (x - 4) / 2;
537 fprintf(i9ep->stderr_stream, "\r%s", buf);
538 fprintf(i9ep->stderr_stream, " .. ");
539 fprintf(i9ep->stderr_stream, "%s", buf + len - y);
545 strcpy(scratch + 1, buf);
546 memset(scratch + 1 + len, ' ', y);
547 scratch[1 + len + y] = '\r';
548 scratch[2 + len + y] = '\0';
549 fprintf(i9ep->stderr_stream, "\r%s", scratch);
551 i9ep->last_write_was_status = true;
555 * Tell i9e that the caller received a signal.
557 * \param sig_num The number of the signal received.
559 void i9e_signal_dispatch(int sig_num)
561 if (sig_num == SIGWINCH)
562 return update_winsize();
563 if (sig_num == SIGINT) {
564 fprintf(i9ep->stderr_stream, "\n");
565 rl_replace_line ("", false /* clear_undo */);
567 i9ep->caught_sigint = true;
569 if (sig_num == SIGTERM)
570 i9ep->caught_sigterm = true;
574 * Wrapper for select(2) which does not restart on interrupts.
576 * \param n \sa \ref para_select().
577 * \param readfds \sa \ref para_select().
578 * \param writefds \sa \ref para_select().
579 * \param timeout_tv \sa \ref para_select().
581 * \return \sa \ref para_select().
583 * The only difference between this function and \ref para_select() is that
584 * \ref i9e_select() returns zero if the select call returned \p EINTR.
586 int i9e_select(int n, fd_set *readfds, fd_set *writefds,
587 struct timeval *timeout_tv)
589 int ret = select(n, readfds, writefds, NULL, timeout_tv);
595 ret = -ERRNO_TO_PARA_ERROR(errno);
601 * Return the possible completions for a given word.
603 * \param word The word to complete.
604 * \param string_list All possible words in this context.
605 * \param result String list is returned here.
607 * This function never fails. If no completion was found, a string list of
608 * length zero is returned. In any case, the result must be freed by the caller
609 * using \ref free_argv().
611 * This function is independent of readline and may be called before
614 * \return The number of possible completions.
616 int i9e_extract_completions(const char *word, char **string_list,
619 char **matches = para_malloc(sizeof(char *));
620 int match_count = 0, matches_len = 1;
622 int len = strlen(word);
624 for (p = string_list; *p; p++) {
625 if (!is_prefix(word, *p, len))
628 if (match_count >= matches_len) {
630 matches = para_realloc(matches,
631 matches_len * sizeof(char *));
633 matches[match_count - 1] = para_strdup(*p);
635 matches[match_count] = NULL;
641 * Return the list of partially matching words.
643 * \param word The command to complete.
644 * \param completers The array containing all command names.
646 * This is similar to \ref i9e_extract_completions(), but completes on the
647 * command names in \a completers.
649 * \return See \ref i9e_extract_completions().
651 char **i9e_complete_commands(const char *word, struct i9e_completer *completers)
655 int i, match_count, len = strlen(word);
658 * In contrast to completing against an arbitrary string list, here we
659 * know all possible completions and expect that there will not be many
660 * of them. So it should be OK to iterate twice over all commands which
661 * simplifies the code a bit.
663 for (i = 0, match_count = 0; (cmd = completers[i].name); i++) {
664 if (is_prefix(word, cmd, len))
667 matches = para_malloc((match_count + 1) * sizeof(*matches));
668 for (i = 0, match_count = 0; (cmd = completers[i].name); i++)
669 if (is_prefix(word, cmd, len))
670 matches[match_count++] = para_strdup(cmd);
671 matches[match_count] = NULL;
676 * Complete according to the given options.
678 * \param opts All available options.
679 * \param ci Information which was passed to the completer.
680 * \param cr Result pointer.
682 * This convenience helper can be used to complete an option. The array of all
683 * possible options is passed as the first argument. Flags, i.e. options
684 * without an argument, are expected to be listed as strings of type "-X" in \a
685 * opts while options which require an argument should be passed with a
686 * trailing "=" character like "-X=".
688 * If the word can be uniquely completed to a flag option, an additional space
689 * character is appended to the output. For non-flag options no space character
692 void i9e_complete_option(char **opts, struct i9e_completion_info *ci,
693 struct i9e_completion_result *cr)
697 num_matches = i9e_extract_completions(ci->word, opts, &cr->matches);
698 if (num_matches == 1) {
699 char *opt = cr->matches[0];
700 char c = opt[strlen(opt) - 1];
702 cr->dont_append_space = true;
707 * Print possible completions to stdout.
709 * \param completers The array of completion functions.
711 * At the end of the output a line starting with "-o=", followed by the
712 * (possibly empty) list of completion options is printed. Currently, the only
713 * two completion options are "nospace" and "filenames". The former indicates
714 * that no space should be appended even for a unique match while the latter
715 * indicates that usual filename completion should be performed in addition to
716 * the previously printed options.
720 int i9e_print_completions(struct i9e_completer *completers)
722 struct i9e_completion_result cr;
723 struct i9e_completion_info ci;
728 reset_completion_result(&cr);
729 buf = getenv("COMP_POINT");
730 ci.point = buf? atoi(buf) : 0;
731 ci.buffer = para_strdup(getenv("COMP_LINE"));
733 ci.argc = create_argv(ci.buffer, " ", &ci.argv);
734 ci.word_num = compute_word_num(ci.buffer, " ", ci.point);
736 end = ci.buffer + ci.point;
737 for (p = end; p > ci.buffer && *p != ' '; p--)
743 ci.word = para_malloc(n + 1);
744 strncpy(ci.word, p, n);
747 PARA_DEBUG_LOG("line: %s, point: %d (%c), wordnum: %d, word: %s\n",
748 ci.buffer, ci.point, ci.buffer[ci.point], ci.word_num, ci.word);
749 if (ci.word_num == 0)
750 cr.matches = i9e_complete_commands(ci.word, completers);
752 create_matches(&ci, completers, &cr);
754 if (cr.matches && cr.matches[0]) {
755 for (i = 0; cr.matches[i]; i++)
756 printf("%s\n", cr.matches[i]);
760 if (cr.dont_append_space)
762 if (cr.filename_completion_desired)
763 printf(",filenames");
765 free_argv(cr.matches);