]> git.tuebingen.mpg.de Git - paraslash.git/blob - interactive.c
interactive: Add producer to struct i9e_client_info.
[paraslash.git] / interactive.c
1 /*
2  * Copyright (C) 2011-2012 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file interactive.c Readline abstraction for interactive sessions. */
8
9 #include <regex.h>
10 #include <stdbool.h>
11 #include <curses.h>
12 #include <readline/readline.h>
13 #include <readline/history.h>
14 #include <sys/ioctl.h>
15 #include <assert.h>
16 #include <signal.h>
17
18 #include "para.h"
19 #include "fd.h"
20 #include "buffer_tree.h"
21 #include "list.h"
22 #include "sched.h"
23 #include "interactive.h"
24 #include "string.h"
25 #include "error.h"
26
27 struct i9e_private {
28         struct i9e_client_info *ici;
29         FILE *stderr_stream;
30         int num_columns;
31         char empty_line[1000];
32         struct task task;
33         struct btr_node *stdout_btrn;
34         bool line_handler_running;
35         bool input_eof;
36         bool caught_sigint;
37         bool caught_sigterm;
38 };
39 static struct i9e_private i9e_private, *i9ep = &i9e_private;
40
41 /**
42  * Return the error state of the i9e task.
43  *
44  * This is mainly useful for other tasks to tell whether the i9e task is still
45  * running.
46  *
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().
49  */
50 int i9e_get_error(void)
51 {
52         return i9ep->task.error;
53 }
54
55 static bool is_prefix(const char *partial, const char *full, size_t len)
56 {
57         if (len == 0)
58                 len = strlen(partial);
59         return !strncmp(partial, full, len);
60 }
61
62 /*
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.
66  */
67 static char *command_generator(const char *text, int state)
68 {
69         static int list_index, len;
70         const char *name;
71         struct i9e_client_info *ici = i9ep->ici;
72
73         rl_attempted_completion_over = 1; /* disable filename completion */
74         /*
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
77          * variable to 0.
78          */
79         if (state == 0) {
80                 list_index = 0;
81                 len = strlen(text);
82         }
83         /* Return the next name which partially matches from the command list. */
84         while ((name = ici->completers[list_index].name)) {
85                 list_index++;
86                 if (is_prefix(text, name, len))
87                         return para_strdup(name);
88         }
89         return NULL; /* no names matched */
90 }
91
92 static void reset_completion_result(struct i9e_completion_result *cr)
93 {
94         cr->dont_append_space = false;
95         cr->filename_completion_desired = false;
96         cr->matches = NULL;
97 }
98
99 static void create_matches(struct i9e_completion_info *ci,
100                 struct i9e_completer *completers,
101                 struct i9e_completion_result *cr)
102 {
103         int i, ret;
104
105         reset_completion_result(cr);
106
107         ret = create_argv(ci->buffer, " ", &ci->argv);
108         if (ret < 0 || !ci->argv[0])
109                 return;
110
111         ci->argc = ret;
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)
115                         continue;
116                 completers[i].completer(ci, cr);
117                 break;
118         }
119         PARA_DEBUG_LOG("current word: %d (%s)\n", ci->word_num,
120                 ci->argv[ci->word_num]);
121         if (cr->matches)
122                 for (i = 0; cr->matches[i]; i++)
123                         PARA_DEBUG_LOG("match %d: %s\n", i, cr->matches[i]);
124 }
125
126 static char *completion_generator(const char *word, int state)
127 {
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,
133                 .point = rl_point,
134                 .buffer = rl_line_buffer,
135         };
136         struct i9e_completion_result cr = {.matches = NULL};
137
138         if (state != 0)
139                 goto out;
140         /* clean up previous matches and set defaults */
141         free(matches);
142         matches = NULL;
143         free_argv(argv);
144         argv = NULL;
145         list_index = 0;
146         rl_completion_append_character = ' ';
147         rl_completion_suppress_append = false;
148         rl_attempted_completion_over = true;
149
150         create_matches(&ci, completers, &cr);
151
152         matches = cr.matches;
153         argv = ci.argv;
154         rl_completion_suppress_append = cr.dont_append_space;
155         rl_attempted_completion_over = !cr.filename_completion_desired;
156 out:
157         if (!matches)
158                 return NULL;
159         return matches[list_index++];
160 }
161
162 /*
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.
168  */
169 static char **i9e_completer(const char *text, int start, __a_unused int end)
170 {
171         struct i9e_client_info *ici = i9ep->ici;
172
173         if (!ici->completers)
174                 return NULL;
175         /* Complete on command names if this is the first word in the line. */
176         if (start == 0)
177                 return rl_completion_matches(text, command_generator);
178         return rl_completion_matches(text, completion_generator);
179 }
180
181 /**
182  * Prepare writing to stdout.
183  *
184  * \param producer The buffer tree node which produces output.
185  *
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.
189  *
190  * This function attaches the i9e input queue to an output queue of \a
191  * producer.
192  *
193  * \return Standard.
194  */
195 void i9e_attach_to_stdout(struct btr_node *producer)
196 {
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 }
201
202 static void wipe_bottom_line(void)
203 {
204         char x[] = "          ";
205         int n = i9ep->num_columns;
206
207         /*
208          * For reasons beyond my understanding, writing more than 68 characters
209          * here causes MacOS to mess up the terminal. Writing a line of spaces
210          * in smaller chunks works fine though. Weird.
211          */
212         fprintf(i9ep->stderr_stream, "\r");
213         while (n > 0) {
214                 if (n >= sizeof(x)) {
215                         fprintf(i9ep->stderr_stream, "%s", x);
216                         n -= sizeof(x);
217                         continue;
218                 }
219                 x[n] = '\0';
220                 fprintf(i9ep->stderr_stream, "%s", x);
221                 break;
222         }
223         fprintf(i9ep->stderr_stream, "\r");
224 }
225
226 /**
227  * Reset the terminal and save the in-memory command line history.
228  *
229  * This should be called before the caller exits.
230  */
231 void i9e_close(void)
232 {
233         char *hf = i9ep->ici->history_file;
234
235         rl_deprep_terminal();
236         if (hf)
237                 write_history(hf);
238         wipe_bottom_line();
239 }
240
241 static void clear_bottom_line(void)
242 {
243         int point;
244         char *text;
245
246         if (rl_point == 0 && rl_end == 0)
247                 return wipe_bottom_line();
248         /*
249          * We might have a multi-line input that needs to be wiped here, so the
250          * simple printf("\r<space>\r") is insufficient. To workaround this, we
251          * remove the whole line, redisplay and restore the killed text.
252          */
253         point = rl_point;
254         text = rl_copy_text(0, rl_end);
255         rl_kill_full_line(0, 0);
256         rl_redisplay();
257         wipe_bottom_line(); /* wipe out the prompt */
258         rl_insert_text(text);
259         rl_point = point;
260 }
261
262 static bool input_available(void)
263 {
264         fd_set rfds;
265         struct timeval tv = {0, 0};
266         int ret;
267
268         FD_ZERO(&rfds);
269         FD_SET(i9ep->ici->fds[0], &rfds);
270         ret = para_select(1, &rfds, NULL, &tv);
271         return ret > 0;
272 }
273
274 static void i9e_line_handler(char *line)
275 {
276         int ret;
277
278         ret = i9ep->ici->line_handler(line);
279         if (ret < 0)
280                 PARA_WARNING_LOG("%s\n", para_strerror(-ret));
281         rl_set_prompt("");
282         if (line) {
283                 if (!*line)
284                         rl_set_prompt(i9ep->ici->prompt);
285                 else
286                         add_history(line);
287                 free(line);
288         } else {
289                 rl_set_prompt("");
290                 i9ep->input_eof = true;
291         }
292 }
293
294 static void i9e_input(void)
295 {
296         do {
297                 rl_callback_read_char();
298         } while (input_available());
299 }
300
301 static void i9e_post_select(struct sched *s, struct task *t)
302 {
303         int ret;
304         struct btr_node *btrn = i9ep->stdout_btrn;
305         struct i9e_client_info *ici = i9ep->ici;
306         char *buf;
307         size_t sz;
308
309         ret = -E_I9E_EOF;
310         if (i9ep->input_eof)
311                 goto rm_btrn;
312         ret = -E_I9E_TERM_RQ;
313         if (i9ep->caught_sigterm)
314                 goto rm_btrn;
315         if (!btrn) {
316                 i9ep->caught_sigint = false;
317                 if (FD_ISSET(ici->fds[0], &s->rfds))
318                         i9e_input();
319                 return;
320         }
321         ret = 0;
322         if (i9ep->caught_sigint)
323                 goto rm_btrn;
324         ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
325         if (ret < 0)
326                 goto rm_btrn;
327         sz = btr_next_buffer(btrn, &buf);
328         if (sz == 0)
329                 goto out;
330         ret = xwrite(ici->fds[1], buf, sz);
331         if (ret < 0)
332                 goto rm_btrn;
333         btr_consume(btrn, ret);
334         goto out;
335 rm_btrn:
336         btr_remove_node(&i9ep->stdout_btrn);
337         rl_set_prompt(i9ep->ici->prompt);
338         rl_redisplay();
339 out:
340         t->error = 0;
341 }
342
343 static void i9e_pre_select(struct sched *s, __a_unused struct task *t)
344 {
345         int ret;
346
347         if (i9ep->input_eof || i9ep->caught_sigint || i9ep->caught_sigterm) {
348                 sched_min_delay(s);
349                 return;
350         }
351         if (i9ep->stdout_btrn) {
352                 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
353                 if (ret < 0) {
354                         sched_min_delay(s);
355                         return;
356                 }
357                 if (ret > 0)
358                         para_fd_set(i9ep->ici->fds[1], &s->wfds, &s->max_fileno);
359         }
360         /*
361          * fd[0] might have been reset to blocking mode if our job was moved to
362          * the background due to CTRL-Z or SIGSTOP, so set the fd back to
363          * nonblocking mode.
364          */
365         ret = mark_fd_nonblocking(i9ep->ici->fds[0]);
366         if (ret < 0)
367                 PARA_WARNING_LOG("set to nonblock failed: (fd0 %d, %s)\n",
368                         i9ep->ici->fds[0], para_strerror(-ret));
369         para_fd_set(i9ep->ici->fds[0], &s->rfds, &s->max_fileno);
370 }
371
372 static void update_winsize(void)
373 {
374         struct winsize w;
375         int ret = ioctl(i9ep->ici->fds[2], TIOCGWINSZ, (char *)&w);
376
377         if (ret >= 0) {
378                 assert(w.ws_col < sizeof(i9ep->empty_line));
379                 i9ep->num_columns = w.ws_col;
380         } else
381                 i9ep->num_columns = 80;
382
383         memset(i9ep->empty_line, ' ', i9ep->num_columns);
384         i9ep->empty_line[i9ep->num_columns] = '\0';
385 }
386
387 /**
388  * Register the i9e task and initialize readline.
389  *
390  * \param ici The i9e configuration parameters set by the caller.
391  * \param s The scheduler instance to add the i9e task to.
392  *
393  * The caller must allocate and initialize the structure \a ici points to.
394  *
395  * \return Standard.
396  * \sa \ref register_task().
397  */
398 int i9e_open(struct i9e_client_info *ici, struct sched *s)
399 {
400         int ret;
401
402         if (!isatty(ici->fds[0]))
403                 return -E_I9E_SETUPTERM;
404         ret = mark_fd_nonblocking(ici->fds[0]);
405         if (ret < 0)
406                 return ret;
407         ret = mark_fd_nonblocking(ici->fds[1]);
408         if (ret < 0)
409                 return ret;
410         i9ep->task.pre_select = i9e_pre_select;
411         i9ep->task.post_select = i9e_post_select;
412         sprintf(i9ep->task.status, "i9e");
413         register_task(s, &i9ep->task);
414         rl_readline_name = "para_i9e";
415         rl_basic_word_break_characters = " ";
416         rl_attempted_completion_function = i9e_completer;
417         i9ep->ici = ici;
418         i9ep->stderr_stream = fdopen(ici->fds[2], "w");
419         setvbuf(i9ep->stderr_stream, NULL, _IONBF, 0);
420
421         if (ici->history_file)
422                 read_history(ici->history_file);
423         update_winsize();
424         if (ici->producer) {
425                 rl_callback_handler_install("", i9e_line_handler);
426                 i9e_attach_to_stdout(ici->producer);
427         } else
428                 rl_callback_handler_install(i9ep->ici->prompt, i9e_line_handler);
429         return 1;
430 }
431
432 static void reset_line_state(void)
433 {
434         if (i9ep->stdout_btrn)
435                 return;
436         rl_on_new_line();
437         rl_reset_line_state();
438         rl_forced_update_display();
439 }
440
441 /**
442  * The log function of the i9e subsystem.
443  *
444  * \param ll Severity log level.
445  * \param fmt Printf-like format string.
446  *
447  * This clears the bottom line of the terminal if necessary and writes the
448  * string given by \a fmt to fd[2], where fd[] is the array provided earlier in
449  * \ref i9e_open().
450  */
451 __printf_2_3 void i9e_log(int ll, const char* fmt,...)
452 {
453         va_list argp;
454
455         if (ll < i9ep->ici->loglevel)
456                 return;
457         clear_bottom_line();
458         va_start(argp, fmt);
459         vfprintf(i9ep->stderr_stream, fmt, argp);
460         va_end(argp);
461         reset_line_state();
462 }
463
464 /**
465  * Tell i9e that the caller received a signal.
466  *
467  * \param sig_num The number of the signal received.
468  *
469  * Currently the function only cares about \p SIGINT, but this may change.
470  */
471 void i9e_signal_dispatch(int sig_num)
472 {
473         if (sig_num == SIGWINCH)
474                 return update_winsize();
475         if (sig_num == SIGINT) {
476                 fprintf(i9ep->stderr_stream, "\n");
477                 rl_replace_line ("", false /* clear_undo */);
478                 reset_line_state();
479                 i9ep->caught_sigint = true;
480         }
481         if (sig_num == SIGTERM)
482                 i9ep->caught_sigterm = true;
483 }
484
485 /**
486  * Wrapper for select(2) which does not restart on interrupts.
487  *
488  * \param n \sa \ref para_select().
489  * \param readfds \sa \ref para_select().
490  * \param writefds \sa \ref para_select().
491  * \param timeout_tv \sa \ref para_select().
492  *
493  * \return \sa \ref para_select().
494  *
495  * The only difference between this function and \ref para_select() is that
496  * \ref i9e_select() returns zero if the select call returned \p EINTR.
497  */
498 int i9e_select(int n, fd_set *readfds, fd_set *writefds,
499                 struct timeval *timeout_tv)
500 {
501         int ret = select(n, readfds, writefds, NULL, timeout_tv);
502
503         if (ret < 0) {
504                 if (errno == EINTR)
505                         ret = 0;
506                 else
507                         ret = -ERRNO_TO_PARA_ERROR(errno);
508         }
509         return ret;
510 }
511
512 /**
513  * Return the possible completions for a given word.
514  *
515  * \param word The word to complete.
516  * \param string_list All possible words in this context.
517  * \param result String list is returned here.
518  *
519  * This function never fails. If no completion was found, a string list of
520  * length zero is returned. In any case, the result must be freed by the caller
521  * using \ref free_argv().
522  *
523  * This function is independent of readline and may be called before
524  * i9e_open().
525  *
526  * \return The number of possible completions.
527  */
528 int i9e_extract_completions(const char *word, char **string_list,
529                 char ***result)
530 {
531         char **matches = para_malloc(sizeof(char *));
532         int match_count = 0, matches_len = 1;
533         char **p;
534         int len = strlen(word);
535
536         for (p = string_list; *p; p++) {
537                 if (!is_prefix(word, *p, len))
538                         continue;
539                 match_count++;
540                 if (match_count >= matches_len) {
541                         matches_len *= 2;
542                         matches = para_realloc(matches,
543                                 matches_len * sizeof(char *));
544                 }
545                 matches[match_count - 1] = para_strdup(*p);
546         }
547         matches[match_count] = NULL;
548         *result = matches;
549         return match_count;
550 }
551
552 /**
553  * Return the list of partially matching words.
554  *
555  * \param word The command to complete.
556  * \param completers The array containing all command names.
557  *
558  * This is similar to \ref i9e_extract_completions(), but completes on the
559  * command names in \a completers.
560  *
561  * \return See \ref i9e_extract_completions().
562  */
563 char **i9e_complete_commands(const char *word, struct i9e_completer *completers)
564 {
565         char **matches;
566         const char *cmd;
567         int i, match_count, len = strlen(word);
568
569         /*
570          * In contrast to completing against an arbitrary string list, here we
571          * know all possible completions and expect that there will not be many
572          * of them. So it should be OK to iterate twice over all commands which
573          * simplifies the code a bit.
574          */
575         for (i = 0, match_count = 0; (cmd = completers[i].name); i++) {
576                 if (is_prefix(word, cmd, len))
577                         match_count++;
578         }
579         matches = para_malloc((match_count + 1) * sizeof(*matches));
580         for (i = 0, match_count = 0; (cmd = completers[i].name); i++)
581                 if (is_prefix(word, cmd, len))
582                         matches[match_count++] = para_strdup(cmd);
583         matches[match_count] = NULL;
584         return matches;
585 }
586
587 /**
588  * Complete according to the given options.
589  *
590  * \param opts All available options.
591  * \param ci Information which was passed to the completer.
592  * \param cr Result pointer.
593  *
594  * This convenience helper can be used to complete an option. The array of all
595  * possible options is passed as the first argument. Flags, i.e. options
596  * without an argument, are expected to be listed as strings of type "-X" in \a
597  * opts while options which require an argument should be passed with a
598  * trailing "=" character like "-X=".
599  *
600  * If the word can be uniquely completed to a flag option, an additional space
601  * character is appended to the output. For non-flag options no space character
602  * is appended.
603  */
604 void i9e_complete_option(char **opts, struct i9e_completion_info *ci,
605                 struct i9e_completion_result *cr)
606 {
607         int num_matches;
608
609         num_matches = i9e_extract_completions(ci->word, opts, &cr->matches);
610         if (num_matches == 1) {
611                 char *opt = cr->matches[0];
612                 char c = opt[strlen(opt) - 1];
613                 if (c == '=')
614                         cr->dont_append_space = true;
615         }
616 }
617
618 /**
619  * Print possible completions to stdout.
620  *
621  * \param completers The array of completion functions.
622  *
623  * At the end of the output a line starting with "-o=", followed by the
624  * (possibly empty) list of completion options is printed. Currently, the only
625  * two completion options are "nospace" and "filenames". The former indicates
626  * that no space should be appended even for a unique match while the latter
627  * indicates that usual filename completion should be performed in addition to
628  * the previously printed options.
629  *
630  * \return Standard.
631  */
632 int i9e_print_completions(struct i9e_completer *completers)
633 {
634         struct i9e_completion_result cr;
635         struct i9e_completion_info ci;
636         char *buf;
637         const char *end, *p;
638         int i, n, ret;
639
640         reset_completion_result(&cr);
641         buf = getenv("COMP_POINT");
642         ci.point = buf? atoi(buf) : 0;
643         ci.buffer = para_strdup(getenv("COMP_LINE"));
644
645         ci.argc = create_argv(ci.buffer, " ", &ci.argv);
646         ci.word_num = compute_word_num(ci.buffer, " ", ci.point);
647
648         end = ci.buffer + ci.point;
649         for (p = end; p > ci.buffer && *p != ' '; p--)
650                 ; /* nothing */
651         if (*p == ' ')
652                 p++;
653
654         n = end - p + 1;
655         ci.word = para_malloc(n + 1);
656         strncpy(ci.word, p, n);
657         ci.word[n] = '\0';
658
659         PARA_DEBUG_LOG("line: %s, point: %d (%c), wordnum: %d, word: %s\n",
660                 ci.buffer, ci.point, ci.buffer[ci.point], ci.word_num, ci.word);
661         if (ci.word_num == 0)
662                 cr.matches = i9e_complete_commands(ci.word, completers);
663         else
664                 create_matches(&ci, completers, &cr);
665         ret = 0;
666         if (cr.matches && cr.matches[0]) {
667                 for (i = 0; cr.matches[i]; i++)
668                         printf("%s\n", cr.matches[i]);
669                 ret = 1;
670         }
671         printf("-o=");
672         if (cr.dont_append_space)
673                 printf("nospace");
674         if (cr.filename_completion_desired)
675                 printf(",filenames");
676         printf("\n");
677         free_argv(cr.matches);
678         free_argv(ci.argv);
679         free(ci.buffer);
680         free(ci.word);
681         return ret;
682 }