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