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