]> git.tuebingen.mpg.de Git - paraslash.git/blob - interactive.c
7768d36b08ec716718b58396e90549722336f7be
[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         char x[] = "          ";
191         int n = i9ep->num_columns;
192
193         /*
194          * For reasons beyond my understanding, writing more than 68 characters
195          * here causes MacOS to mess up the terminal. Writing a line of spaces
196          * in smaller chunks works fine though. Weird.
197          */
198         fprintf(i9ep->stderr_stream, "\r");
199         while (n > 0) {
200                 if (n >= sizeof(x)) {
201                         fprintf(i9ep->stderr_stream, "%s", x);
202                         n -= sizeof(x);
203                         continue;
204                 }
205                 x[n] = '\0';
206                 fprintf(i9ep->stderr_stream, "%s", x);
207                 break;
208         }
209         fprintf(i9ep->stderr_stream, "\r");
210 }
211
212 /**
213  * Reset the terminal and save the in-memory command line history.
214  *
215  * This should be called before the caller exits.
216  */
217 void i9e_close(void)
218 {
219         char *hf = i9ep->ici->history_file;
220
221         rl_deprep_terminal();
222         if (hf)
223                 write_history(hf);
224         wipe_bottom_line();
225 }
226
227 static void clear_bottom_line(void)
228 {
229         int point;
230         char *text;
231
232         if (rl_point == 0 && rl_end == 0)
233                 return wipe_bottom_line();
234         /*
235          * We might have a multi-line input that needs to be wiped here, so the
236          * simple printf("\r<space>\r") is insufficient. To workaround this, we
237          * remove the whole line, redisplay and restore the killed text.
238          */
239         point = rl_point;
240         text = rl_copy_text(0, rl_end);
241         rl_kill_full_line(0, 0);
242         rl_redisplay();
243         wipe_bottom_line(); /* wipe out the prompt */
244         rl_insert_text(text);
245         rl_point = point;
246 }
247
248 static bool input_available(void)
249 {
250         fd_set rfds;
251         struct timeval tv = {0, 0};
252         int ret;
253
254         FD_ZERO(&rfds);
255         FD_SET(i9ep->ici->fds[0], &rfds);
256         ret = para_select(1, &rfds, NULL, &tv);
257         return ret > 0;
258 }
259
260 static void i9e_line_handler(char *line)
261 {
262         int ret;
263
264         ret = i9ep->ici->line_handler(line);
265         if (ret < 0)
266                 PARA_WARNING_LOG("%s\n", para_strerror(-ret));
267         rl_set_prompt("");
268         if (line) {
269                 if (!*line)
270                         rl_set_prompt(i9ep->ici->prompt);
271                 else
272                         add_history(line);
273                 free(line);
274         } else {
275                 rl_set_prompt("");
276                 i9ep->input_eof = true;
277         }
278 }
279
280 static void i9e_input(void)
281 {
282         do {
283                 rl_callback_read_char();
284         } while (input_available());
285 }
286
287 static void i9e_post_select(struct sched *s, struct task *t)
288 {
289         int ret;
290         struct btr_node *btrn = i9ep->stdout_btrn;
291         struct i9e_client_info *ici = i9ep->ici;
292         char *buf;
293         size_t sz;
294
295         ret = -E_I9E_EOF;
296         if (i9ep->input_eof)
297                 goto rm_btrn;
298         ret = -E_I9E_TERM_RQ;
299         if (i9ep->caught_sigterm)
300                 goto rm_btrn;
301         if (!btrn) {
302                 i9ep->caught_sigint = false;
303                 if (FD_ISSET(ici->fds[0], &s->rfds))
304                         i9e_input();
305                 return;
306         }
307         ret = 0;
308         if (i9ep->caught_sigint)
309                 goto rm_btrn;
310         ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
311         if (ret < 0)
312                 goto rm_btrn;
313         sz = btr_next_buffer(btrn, &buf);
314         if (sz == 0)
315                 goto out;
316         ret = xwrite(ici->fds[1], buf, sz);
317         if (ret < 0)
318                 goto rm_btrn;
319         btr_consume(btrn, ret);
320         goto out;
321 rm_btrn:
322         btr_remove_node(&i9ep->stdout_btrn);
323         rl_set_prompt(i9ep->ici->prompt);
324         rl_redisplay();
325 out:
326         t->error = 0;
327 }
328
329 static void i9e_pre_select(struct sched *s, __a_unused struct task *t)
330 {
331         int ret;
332
333         if (i9ep->input_eof || i9ep->caught_sigint || i9ep->caught_sigterm) {
334                 sched_min_delay(s);
335                 return;
336         }
337         if (i9ep->stdout_btrn) {
338                 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
339                 if (ret < 0) {
340                         sched_min_delay(s);
341                         return;
342                 }
343                 if (ret > 0)
344                         para_fd_set(i9ep->ici->fds[1], &s->wfds, &s->max_fileno);
345         }
346         /*
347          * fd[0] might have been reset to blocking mode if our job was moved to
348          * the background due to CTRL-Z or SIGSTOP, so set the fd back to
349          * nonblocking mode.
350          */
351         ret = mark_fd_nonblocking(i9ep->ici->fds[0]);
352         if (ret < 0)
353                 PARA_WARNING_LOG("set to nonblock failed: (fd0 %d, %s)\n",
354                         i9ep->ici->fds[0], para_strerror(-ret));
355         para_fd_set(i9ep->ici->fds[0], &s->rfds, &s->max_fileno);
356 }
357
358 static void update_winsize(void)
359 {
360         struct winsize w;
361         int ret = ioctl(i9ep->ici->fds[2], TIOCGWINSZ, (char *)&w);
362
363         if (ret >= 0) {
364                 assert(w.ws_col < sizeof(i9ep->empty_line));
365                 i9ep->num_columns = w.ws_col;
366         } else
367                 i9ep->num_columns = 80;
368
369         memset(i9ep->empty_line, ' ', i9ep->num_columns);
370         i9ep->empty_line[i9ep->num_columns] = '\0';
371 }
372
373 /**
374  * Register the i9e task and initialize readline.
375  *
376  * \param ici The i9e configuration parameters set by the caller.
377  * \param s The scheduler instance to add the i9e task to.
378  *
379  * The caller must allocate and initialize the structure \a ici points to.
380  *
381  * \return Standard.
382  * \sa \ref register_task().
383  */
384 int i9e_open(struct i9e_client_info *ici, struct sched *s)
385 {
386         int ret;
387
388         if (!isatty(ici->fds[0]))
389                 return -E_I9E_SETUPTERM;
390         ret = mark_fd_nonblocking(ici->fds[0]);
391         if (ret < 0)
392                 return ret;
393         ret = mark_fd_nonblocking(ici->fds[1]);
394         if (ret < 0)
395                 return ret;
396         i9ep->task.pre_select = i9e_pre_select;
397         i9ep->task.post_select = i9e_post_select;
398         sprintf(i9ep->task.status, "i9e");
399         register_task(s, &i9ep->task);
400         rl_readline_name = "para_i9e";
401         rl_basic_word_break_characters = " ";
402         rl_attempted_completion_function = i9e_completer;
403         i9ep->ici = ici;
404         i9ep->stderr_stream = fdopen(ici->fds[2], "w");
405         setvbuf(i9ep->stderr_stream, NULL, _IONBF, 0);
406
407         if (ici->history_file)
408                 read_history(ici->history_file);
409         update_winsize();
410         rl_callback_handler_install(i9ep->ici->prompt, i9e_line_handler);
411         return 1;
412 }
413
414 static void reset_line_state(void)
415 {
416         if (i9ep->stdout_btrn)
417                 return;
418         rl_on_new_line();
419         rl_reset_line_state();
420         rl_forced_update_display();
421 }
422
423 /**
424  * The log function of the i9e subsystem.
425  *
426  * \param ll Severity log level.
427  * \param fmt Printf-like format string.
428  *
429  * This clears the bottom line of the terminal if necessary and writes the
430  * string given by \a fmt to fd[2], where fd[] is the array provided earlier in
431  * \ref i9e_open().
432  */
433 __printf_2_3 void i9e_log(int ll, const char* fmt,...)
434 {
435         va_list argp;
436
437         if (ll < i9ep->ici->loglevel)
438                 return;
439         clear_bottom_line();
440         va_start(argp, fmt);
441         vfprintf(i9ep->stderr_stream, fmt, argp);
442         va_end(argp);
443         reset_line_state();
444 }
445
446 /**
447  * Tell i9e that the caller received a signal.
448  *
449  * \param sig_num The number of the signal received.
450  *
451  * Currently the function only cares about \p SIGINT, but this may change.
452  */
453 void i9e_signal_dispatch(int sig_num)
454 {
455         if (sig_num == SIGWINCH)
456                 return update_winsize();
457         if (sig_num == SIGINT) {
458                 fprintf(i9ep->stderr_stream, "\n");
459                 rl_replace_line ("", false /* clear_undo */);
460                 reset_line_state();
461                 i9ep->caught_sigint = true;
462         }
463         if (sig_num == SIGTERM)
464                 i9ep->caught_sigterm = true;
465 }
466
467 /**
468  * Wrapper for select(2) which does not restart on interrupts.
469  *
470  * \param n \sa \ref para_select().
471  * \param readfds \sa \ref para_select().
472  * \param writefds \sa \ref para_select().
473  * \param timeout_tv \sa \ref para_select().
474  *
475  * \return \sa \ref para_select().
476  *
477  * The only difference between this function and \ref para_select() is that
478  * \ref i9e_select() returns zero if the select call returned \p EINTR.
479  */
480 int i9e_select(int n, fd_set *readfds, fd_set *writefds,
481                 struct timeval *timeout_tv)
482 {
483         int ret = select(n, readfds, writefds, NULL, timeout_tv);
484
485         if (ret < 0) {
486                 if (errno == EINTR)
487                         ret = 0;
488                 else
489                         ret = -ERRNO_TO_PARA_ERROR(errno);
490         }
491         return ret;
492 }
493
494 /**
495  * Return the possible completions for a given word.
496  *
497  * \param word The word to complete.
498  * \param string_list All possible words in this context.
499  * \param result String list is returned here.
500  *
501  * This function never fails. If no completion was found, a string list of
502  * length zero is returned. In any case, the result must be freed by the caller
503  * using \ref free_argv().
504  *
505  * This function is independent of readline and may be called before
506  * i9e_open().
507  *
508  * \return The number of possible completions.
509  */
510 int i9e_extract_completions(const char *word, char **string_list,
511                 char ***result)
512 {
513         char **matches = para_malloc(sizeof(char *));
514         int match_count = 0, matches_len = 1;
515         char **p;
516         int len = strlen(word);
517
518         for (p = string_list; *p; p++) {
519                 if (!is_prefix(word, *p, len))
520                         continue;
521                 match_count++;
522                 if (match_count >= matches_len) {
523                         matches_len *= 2;
524                         matches = para_realloc(matches,
525                                 matches_len * sizeof(char *));
526                 }
527                 matches[match_count - 1] = para_strdup(*p);
528         }
529         matches[match_count] = NULL;
530         *result = matches;
531         return match_count;
532 }
533
534 /**
535  * Return the list of partially matching words.
536  *
537  * \param word The command to complete.
538  * \param completers The array containing all command names.
539  *
540  * This is similar to \ref i9e_extract_completions(), but completes on the
541  * command names in \a completers.
542  *
543  * \return See \ref i9e_extract_completions().
544  */
545 char **i9e_complete_commands(const char *word, struct i9e_completer *completers)
546 {
547         char **matches;
548         const char *cmd;
549         int i, match_count, len = strlen(word);
550
551         /*
552          * In contrast to completing against an arbitrary string list, here we
553          * know all possible completions and expect that there will not be many
554          * of them. So it should be OK to iterate twice over all commands which
555          * simplifies the code a bit.
556          */
557         for (i = 0, match_count = 0; (cmd = completers[i].name); i++) {
558                 if (is_prefix(word, cmd, len))
559                         match_count++;
560         }
561         matches = para_malloc((match_count + 1) * sizeof(*matches));
562         for (i = 0, match_count = 0; (cmd = completers[i].name); i++)
563                 if (is_prefix(word, cmd, len))
564                         matches[match_count++] = para_strdup(cmd);
565         matches[match_count] = NULL;
566         return matches;
567 }
568
569 /**
570  * Complete according to the given options.
571  *
572  * \param opts All available options.
573  * \param ci Information which was passed to the completer.
574  * \param cr Result pointer.
575  *
576  * This convenience helper can be used to complete an option. The array of all
577  * possible options is passed as the first argument. Flags, i.e. options
578  * without an argument, are expected to be listed as strings of type "-X" in \a
579  * opts while options which require an argument should be passed with a
580  * trailing "=" character like "-X=".
581  *
582  * If the word can be uniquely completed to a flag option, an additional space
583  * character is appended to the output. For non-flag options no space character
584  * is appended.
585  */
586 void i9e_complete_option(char **opts, struct i9e_completion_info *ci,
587                 struct i9e_completion_result *cr)
588 {
589         int num_matches;
590
591         num_matches = i9e_extract_completions(ci->word, opts, &cr->matches);
592         if (num_matches == 1) {
593                 char *opt = cr->matches[0];
594                 char c = opt[strlen(opt) - 1];
595                 if (c == '=')
596                         cr->dont_append_space = true;
597         }
598 }
599
600 /**
601  * Print possible completions to stdout.
602  *
603  * \param completers The array of completion functions.
604  *
605  * At the end of the output a line starting with "-o=", followed by the
606  * (possibly empty) list of completion options is printed. Currently, the only
607  * two completion options are "nospace" and "filenames". The former indicates
608  * that no space should be appended even for a unique match while the latter
609  * indicates that usual filename completion should be performed in addition to
610  * the previously printed options.
611  *
612  * \return Standard.
613  */
614 int i9e_print_completions(struct i9e_completer *completers)
615 {
616         struct i9e_completion_result cr;
617         struct i9e_completion_info ci;
618         char *buf;
619         const char *end, *p;
620         int i, n, ret;
621
622         reset_completion_result(&cr);
623         buf = getenv("COMP_POINT");
624         ci.point = buf? atoi(buf) : 0;
625         ci.buffer = para_strdup(getenv("COMP_LINE"));
626
627         ci.argc = create_argv(ci.buffer, " ", &ci.argv);
628         ci.word_num = compute_word_num(ci.buffer, " ", ci.point);
629
630         end = ci.buffer + ci.point;
631         for (p = end; p > ci.buffer && *p != ' '; p--)
632                 ; /* nothing */
633         if (*p == ' ')
634                 p++;
635
636         n = end - p + 1;
637         ci.word = para_malloc(n + 1);
638         strncpy(ci.word, p, n);
639         ci.word[n] = '\0';
640
641         PARA_DEBUG_LOG("line: %s, point: %d (%c), wordnum: %d, word: %s\n",
642                 ci.buffer, ci.point, ci.buffer[ci.point], ci.word_num, ci.word);
643         if (ci.word_num == 0)
644                 cr.matches = i9e_complete_commands(ci.word, completers);
645         else
646                 create_matches(&ci, completers, &cr);
647         ret = 0;
648         if (cr.matches && cr.matches[0]) {
649                 for (i = 0; cr.matches[i]; i++)
650                         printf("%s\n", cr.matches[i]);
651                 ret = 1;
652         }
653         printf("-o=");
654         if (cr.dont_append_space)
655                 printf("nospace");
656         if (cr.filename_completion_desired)
657                 printf(",filenames");
658         printf("\n");
659         free_argv(cr.matches);
660         free_argv(ci.argv);
661         free(ci.buffer);
662         free(ci.word);
663         return ret;
664 }