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;
41 static struct i9e_private i9e_private, *i9ep = &i9e_private;
44 * Return the error state of the i9e task.
46 * This is mainly useful for other tasks to tell whether the i9e task is still
49 * \return A negative return value of zero means the i9e task terminated. Only
50 * in this case it is safe to call ie9_close().
52 int i9e_get_error(void)
54 return i9ep->task.error;
57 static bool is_prefix(const char *partial, const char *full, size_t len)
60 len = strlen(partial);
61 return !strncmp(partial, full, len);
65 * Generator function for command completion. STATE lets us know whether
66 * to start from scratch; without any state (i.e. STATE == 0), then we
67 * start at the top of the list.
69 static char *command_generator(const char *text, int state)
71 static int list_index, len;
73 struct i9e_client_info *ici = i9ep->ici;
75 rl_attempted_completion_over = 1; /* disable filename completion */
77 * If this is a new word to complete, initialize now. This includes
78 * saving the length of TEXT for efficiency, and initializing the index
85 /* Return the next name which partially matches from the command list. */
86 while ((name = ici->completers[list_index].name)) {
88 if (is_prefix(text, name, len))
89 return para_strdup(name);
91 return NULL; /* no names matched */
94 static void reset_completion_result(struct i9e_completion_result *cr)
96 cr->dont_append_space = false;
97 cr->filename_completion_desired = false;
101 static void create_matches(struct i9e_completion_info *ci,
102 struct i9e_completer *completers,
103 struct i9e_completion_result *cr)
107 reset_completion_result(cr);
109 ret = create_argv(ci->buffer, " ", &ci->argv);
110 if (ret < 0 || !ci->argv[0])
114 ci->word_num = compute_word_num(ci->buffer, " ", ci->point);
115 for (i = 0; completers[i].name; i++) {
116 if (strcmp(completers[i].name, ci->argv[0]) != 0)
118 completers[i].completer(ci, cr);
121 PARA_DEBUG_LOG("current word: %d (%s)\n", ci->word_num,
122 ci->argv[ci->word_num]);
124 for (i = 0; cr->matches[i]; i++)
125 PARA_DEBUG_LOG("match %d: %s\n", i, cr->matches[i]);
128 static char *completion_generator(const char *word, int state)
130 static int list_index;
131 static char **argv, **matches;
132 struct i9e_completer *completers = i9ep->ici->completers;
133 struct i9e_completion_info ci = {
134 .word = (char *)word,
136 .buffer = rl_line_buffer,
138 struct i9e_completion_result cr = {.matches = NULL};
142 /* clean up previous matches and set defaults */
148 rl_completion_append_character = ' ';
149 rl_completion_suppress_append = false;
150 rl_attempted_completion_over = true;
152 create_matches(&ci, completers, &cr);
154 matches = cr.matches;
156 rl_completion_suppress_append = cr.dont_append_space;
157 rl_attempted_completion_over = !cr.filename_completion_desired;
161 return matches[list_index++];
165 * Attempt to complete on the contents of TEXT. START and END bound the
166 * region of rl_line_buffer that contains the word to complete. TEXT is
167 * the word to complete. We can use the entire contents of rl_line_buffer
168 * in case we want to do some simple parsing. Return the array of matches,
169 * or NULL if there aren't any.
171 static char **i9e_completer(const char *text, int start, __a_unused int end)
173 struct i9e_client_info *ici = i9ep->ici;
175 if (!ici->completers)
177 /* Complete on command names if this is the first word in the line. */
179 return rl_completion_matches(text, command_generator);
180 return rl_completion_matches(text, completion_generator);
184 * Prepare writing to stdout.
186 * \param producer The buffer tree node which produces output.
188 * The i9e subsystem maintains a buffer tree node which may be attached to
189 * another node which generates output (a "producer"). When attached, the i9e
190 * buffer tree node copies the buffers generated by the producer to stdout.
192 * This function attaches the i9e input queue to an output queue of \a
197 void i9e_attach_to_stdout(struct btr_node *producer)
199 btr_remove_node(&i9ep->stdout_btrn);
200 i9ep->stdout_btrn = btr_new_node(&(struct btr_node_description)
201 EMBRACE(.name = "interactive_stdout", .parent = producer));
202 rl_set_keymap(i9ep->bare_km);
205 static void wipe_bottom_line(void)
208 int n = i9ep->num_columns;
211 * For reasons beyond my understanding, writing more than 68 characters
212 * here causes MacOS to mess up the terminal. Writing a line of spaces
213 * in smaller chunks works fine though. Weird.
215 fprintf(i9ep->stderr_stream, "\r");
217 if (n >= sizeof(x)) {
218 fprintf(i9ep->stderr_stream, "%s", x);
223 fprintf(i9ep->stderr_stream, "%s", x);
226 fprintf(i9ep->stderr_stream, "\r");
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);
241 * Reset the terminal and save the in-memory command line history.
243 * This should be called before the caller exits.
247 char *hf = i9ep->ici->history_file;
249 rl_free_keymap(i9ep->bare_km);
250 rl_callback_handler_remove();
256 static void clear_bottom_line(void)
261 if (rl_point == 0 && rl_end == 0)
262 return wipe_bottom_line();
264 * We might have a multi-line input that needs to be wiped here, so the
265 * simple printf("\r<space>\r") is insufficient. To workaround this, we
266 * remove the whole line, redisplay and restore the killed text.
269 text = rl_copy_text(0, rl_end);
270 rl_kill_full_line(0, 0);
272 wipe_bottom_line(); /* wipe out the prompt */
273 rl_insert_text(text);
277 static bool input_available(void)
280 struct timeval tv = {0, 0};
284 FD_SET(i9ep->ici->fds[0], &rfds);
285 ret = para_select(1, &rfds, NULL, &tv);
289 static void i9e_line_handler(char *line)
293 ret = i9ep->ici->line_handler(line);
295 PARA_WARNING_LOG("%s\n", para_strerror(-ret));
299 rl_set_prompt(i9ep->ici->prompt);
305 i9ep->input_eof = true;
309 static void i9e_post_select(__a_unused struct sched *s, struct task *t)
312 struct i9e_client_info *ici = i9ep->ici;
319 ret = -E_I9E_TERM_RQ;
320 if (i9ep->caught_sigterm)
323 if (i9ep->caught_sigint)
325 while (input_available())
326 rl_callback_read_char();
327 if (!i9ep->stdout_btrn)
329 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
336 sz = btr_next_buffer(i9ep->stdout_btrn, &buf);
339 ret = xwrite(ici->fds[1], buf, sz);
342 btr_consume(i9ep->stdout_btrn, ret);
345 if (i9ep->stdout_btrn) {
346 btr_remove_node(&i9ep->stdout_btrn);
347 rl_set_keymap(i9ep->standard_km);
348 rl_set_prompt(i9ep->ici->prompt);
354 i9ep->caught_sigint = false;
358 static void i9e_pre_select(struct sched *s, __a_unused struct task *t)
362 if (i9ep->input_eof || i9ep->caught_sigint || i9ep->caught_sigterm) {
366 if (i9ep->stdout_btrn) {
367 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
373 para_fd_set(i9ep->ici->fds[1], &s->wfds, &s->max_fileno);
376 * fd[0] might have been reset to blocking mode if our job was moved to
377 * the background due to CTRL-Z or SIGSTOP, so set the fd back to
380 ret = mark_fd_nonblocking(i9ep->ici->fds[0]);
382 PARA_WARNING_LOG("set to nonblock failed: (fd0 %d, %s)\n",
383 i9ep->ici->fds[0], para_strerror(-ret));
384 para_fd_set(i9ep->ici->fds[0], &s->rfds, &s->max_fileno);
387 static void update_winsize(void)
390 int ret = ioctl(i9ep->ici->fds[2], TIOCGWINSZ, (char *)&w);
393 assert(w.ws_col < sizeof(i9ep->empty_line));
394 i9ep->num_columns = w.ws_col;
396 i9ep->num_columns = 80;
398 memset(i9ep->empty_line, ' ', i9ep->num_columns);
399 i9ep->empty_line[i9ep->num_columns] = '\0';
403 * Defined key sequences are mapped to keys starting with this offset. I.e.
404 * pressing the first defined key sequence yields the key number \p KEY_OFFSET.
406 #define KEY_OFFSET 64
408 static int dispatch_key(__a_unused int count, int key)
412 assert(key >= KEY_OFFSET);
413 ret = i9ep->ici->key_handler(key - KEY_OFFSET);
414 return ret < 0? ret : 0;
418 * Register the i9e task and initialize readline.
420 * \param ici The i9e configuration parameters set by the caller.
421 * \param s The scheduler instance to add the i9e task to.
423 * The caller must allocate and initialize the structure \a ici points to.
426 * \sa \ref register_task().
428 int i9e_open(struct i9e_client_info *ici, struct sched *s)
432 if (!isatty(ici->fds[0]))
433 return -E_I9E_SETUPTERM;
434 ret = mark_fd_nonblocking(ici->fds[0]);
437 ret = mark_fd_nonblocking(ici->fds[1]);
440 i9ep->task.pre_select = i9e_pre_select;
441 i9ep->task.post_select = i9e_post_select;
442 sprintf(i9ep->task.status, "i9e");
443 register_task(s, &i9ep->task);
444 rl_readline_name = "para_i9e";
445 rl_basic_word_break_characters = " ";
446 rl_attempted_completion_function = i9e_completer;
448 i9ep->stderr_stream = fdopen(ici->fds[2], "w");
449 setvbuf(i9ep->stderr_stream, NULL, _IONBF, 0);
451 i9ep->standard_km = rl_get_keymap();
452 i9ep->bare_km = rl_make_bare_keymap();
453 if (ici->bound_keyseqs) {
456 /* FIXME: This is an arbitrary constant. */
457 for (i = 0; i < 32 && (seq = ici->bound_keyseqs[i]); i++) {
458 char buf[2] = {KEY_OFFSET + i, '\0'};
459 /* readline needs an allocated buffer for the macro */
460 rl_generic_bind(ISMACR, seq, para_strdup(buf), i9ep->bare_km);
461 rl_bind_key_in_map(KEY_OFFSET + i, dispatch_key, i9ep->bare_km);
464 if (ici->history_file)
465 read_history(ici->history_file);
468 rl_callback_handler_install("", i9e_line_handler);
469 i9e_attach_to_stdout(ici->producer);
470 rl_set_keymap(i9ep->bare_km);
472 rl_callback_handler_install(i9ep->ici->prompt, i9e_line_handler);
476 static void reset_line_state(void)
478 if (i9ep->stdout_btrn)
481 rl_reset_line_state();
482 rl_forced_update_display();
486 * The log function of the i9e subsystem.
488 * \param ll Severity log level.
489 * \param fmt Printf-like format string.
491 * This clears the bottom line of the terminal if necessary and writes the
492 * string given by \a fmt to fd[2], where fd[] is the array provided earlier in
495 __printf_2_3 void i9e_log(int ll, const char* fmt,...)
499 if (ll < i9ep->ici->loglevel)
503 vfprintf(i9ep->stderr_stream, fmt, argp);
509 * Tell i9e that the caller received a signal.
511 * \param sig_num The number of the signal received.
513 * Currently the function only cares about \p SIGINT, but this may change.
515 void i9e_signal_dispatch(int sig_num)
517 if (sig_num == SIGWINCH)
518 return update_winsize();
519 if (sig_num == SIGINT) {
520 fprintf(i9ep->stderr_stream, "\n");
521 rl_replace_line ("", false /* clear_undo */);
523 i9ep->caught_sigint = true;
525 if (sig_num == SIGTERM)
526 i9ep->caught_sigterm = true;
530 * Wrapper for select(2) which does not restart on interrupts.
532 * \param n \sa \ref para_select().
533 * \param readfds \sa \ref para_select().
534 * \param writefds \sa \ref para_select().
535 * \param timeout_tv \sa \ref para_select().
537 * \return \sa \ref para_select().
539 * The only difference between this function and \ref para_select() is that
540 * \ref i9e_select() returns zero if the select call returned \p EINTR.
542 int i9e_select(int n, fd_set *readfds, fd_set *writefds,
543 struct timeval *timeout_tv)
545 int ret = select(n, readfds, writefds, NULL, timeout_tv);
551 ret = -ERRNO_TO_PARA_ERROR(errno);
557 * Return the possible completions for a given word.
559 * \param word The word to complete.
560 * \param string_list All possible words in this context.
561 * \param result String list is returned here.
563 * This function never fails. If no completion was found, a string list of
564 * length zero is returned. In any case, the result must be freed by the caller
565 * using \ref free_argv().
567 * This function is independent of readline and may be called before
570 * \return The number of possible completions.
572 int i9e_extract_completions(const char *word, char **string_list,
575 char **matches = para_malloc(sizeof(char *));
576 int match_count = 0, matches_len = 1;
578 int len = strlen(word);
580 for (p = string_list; *p; p++) {
581 if (!is_prefix(word, *p, len))
584 if (match_count >= matches_len) {
586 matches = para_realloc(matches,
587 matches_len * sizeof(char *));
589 matches[match_count - 1] = para_strdup(*p);
591 matches[match_count] = NULL;
597 * Return the list of partially matching words.
599 * \param word The command to complete.
600 * \param completers The array containing all command names.
602 * This is similar to \ref i9e_extract_completions(), but completes on the
603 * command names in \a completers.
605 * \return See \ref i9e_extract_completions().
607 char **i9e_complete_commands(const char *word, struct i9e_completer *completers)
611 int i, match_count, len = strlen(word);
614 * In contrast to completing against an arbitrary string list, here we
615 * know all possible completions and expect that there will not be many
616 * of them. So it should be OK to iterate twice over all commands which
617 * simplifies the code a bit.
619 for (i = 0, match_count = 0; (cmd = completers[i].name); i++) {
620 if (is_prefix(word, cmd, len))
623 matches = para_malloc((match_count + 1) * sizeof(*matches));
624 for (i = 0, match_count = 0; (cmd = completers[i].name); i++)
625 if (is_prefix(word, cmd, len))
626 matches[match_count++] = para_strdup(cmd);
627 matches[match_count] = NULL;
632 * Complete according to the given options.
634 * \param opts All available options.
635 * \param ci Information which was passed to the completer.
636 * \param cr Result pointer.
638 * This convenience helper can be used to complete an option. The array of all
639 * possible options is passed as the first argument. Flags, i.e. options
640 * without an argument, are expected to be listed as strings of type "-X" in \a
641 * opts while options which require an argument should be passed with a
642 * trailing "=" character like "-X=".
644 * If the word can be uniquely completed to a flag option, an additional space
645 * character is appended to the output. For non-flag options no space character
648 void i9e_complete_option(char **opts, struct i9e_completion_info *ci,
649 struct i9e_completion_result *cr)
653 num_matches = i9e_extract_completions(ci->word, opts, &cr->matches);
654 if (num_matches == 1) {
655 char *opt = cr->matches[0];
656 char c = opt[strlen(opt) - 1];
658 cr->dont_append_space = true;
663 * Print possible completions to stdout.
665 * \param completers The array of completion functions.
667 * At the end of the output a line starting with "-o=", followed by the
668 * (possibly empty) list of completion options is printed. Currently, the only
669 * two completion options are "nospace" and "filenames". The former indicates
670 * that no space should be appended even for a unique match while the latter
671 * indicates that usual filename completion should be performed in addition to
672 * the previously printed options.
676 int i9e_print_completions(struct i9e_completer *completers)
678 struct i9e_completion_result cr;
679 struct i9e_completion_info ci;
684 reset_completion_result(&cr);
685 buf = getenv("COMP_POINT");
686 ci.point = buf? atoi(buf) : 0;
687 ci.buffer = para_strdup(getenv("COMP_LINE"));
689 ci.argc = create_argv(ci.buffer, " ", &ci.argv);
690 ci.word_num = compute_word_num(ci.buffer, " ", ci.point);
692 end = ci.buffer + ci.point;
693 for (p = end; p > ci.buffer && *p != ' '; p--)
699 ci.word = para_malloc(n + 1);
700 strncpy(ci.word, p, n);
703 PARA_DEBUG_LOG("line: %s, point: %d (%c), wordnum: %d, word: %s\n",
704 ci.buffer, ci.point, ci.buffer[ci.point], ci.word_num, ci.word);
705 if (ci.word_num == 0)
706 cr.matches = i9e_complete_commands(ci.word, completers);
708 create_matches(&ci, completers, &cr);
710 if (cr.matches && cr.matches[0]) {
711 for (i = 0; cr.matches[i]; i++)
712 printf("%s\n", cr.matches[i]);
716 if (cr.dont_append_space)
718 if (cr.filename_completion_desired)
719 printf(",filenames");
721 free_argv(cr.matches);