Unify CLI/TUI interface to readline tab completion.
[external/binutils.git] / gdb / tui / tui-io.c
1 /* TUI support I/O functions.
2
3    Copyright (C) 1998-2015 Free Software Foundation, Inc.
4
5    Contributed by Hewlett-Packard Company.
6
7    This file is part of GDB.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
21
22 #include "defs.h"
23 #include "target.h"
24 #include "event-loop.h"
25 #include "event-top.h"
26 #include "command.h"
27 #include "top.h"
28 #include "tui/tui.h"
29 #include "tui/tui-data.h"
30 #include "tui/tui-io.h"
31 #include "tui/tui-command.h"
32 #include "tui/tui-win.h"
33 #include "tui/tui-wingeneral.h"
34 #include "tui/tui-file.h"
35 #include "ui-out.h"
36 #include "cli-out.h"
37 #include <fcntl.h>
38 #include <signal.h>
39 #include "filestuff.h"
40 #include "completer.h"
41 #include "gdb_curses.h"
42
43 /* This redefines CTRL if it is not already defined, so it must come
44    after terminal state releated include files like <term.h> and
45    "gdb_curses.h".  */
46 #include "readline/readline.h"
47
48 int
49 key_is_start_sequence (int ch)
50 {
51   return (ch == 27);
52 }
53
54 int
55 key_is_end_sequence (int ch)
56 {
57   return (ch == 126);
58 }
59
60 int
61 key_is_backspace (int ch)
62 {
63   return (ch == 8);
64 }
65
66 int
67 key_is_command_char (int ch)
68 {
69   return ((ch == KEY_NPAGE) || (ch == KEY_PPAGE)
70           || (ch == KEY_LEFT) || (ch == KEY_RIGHT)
71           || (ch == KEY_UP) || (ch == KEY_DOWN)
72           || (ch == KEY_SF) || (ch == KEY_SR)
73           || (ch == (int)'\f') 
74           || key_is_start_sequence (ch));
75 }
76
77 /* Use definition from readline 4.3.  */
78 #undef CTRL_CHAR
79 #define CTRL_CHAR(c) \
80      ((c) < control_character_threshold && (((c) & 0x80) == 0))
81
82 /* This file controls the IO interactions between gdb and curses.
83    When the TUI is enabled, gdb has two modes a curses and a standard
84    mode.
85
86    In curses mode, the gdb outputs are made in a curses command
87    window.  For this, the gdb_stdout and gdb_stderr are redirected to
88    the specific ui_file implemented by TUI.  The output is handled by
89    tui_puts().  The input is also controlled by curses with
90    tui_getc().  The readline library uses this function to get its
91    input.  Several readline hooks are installed to redirect readline
92    output to the TUI (see also the note below).
93
94    In normal mode, the gdb outputs are restored to their origin, that
95    is as if TUI is not used.  Readline also uses its original getc()
96    function with stdin.
97
98    Note SCz/2001-07-21: the current readline is not clean in its
99    management of the output.  Even if we install a redisplay handler,
100    it sometimes writes on a stdout file.  It is important to redirect
101    every output produced by readline, otherwise the curses window will
102    be garbled.  This is implemented with a pipe that TUI reads and
103    readline writes to.  A gdb input handler is created so that reading
104    the pipe is handled automatically.  This will probably not work on
105    non-Unix platforms.  The best fix is to make readline clean enougth
106    so that is never write on stdout.
107
108    Note SCz/2002-09-01: we now use more readline hooks and it seems
109    that with them we don't need the pipe anymore (verified by creating
110    the pipe and closing its end so that write causes a SIGPIPE).  The
111    old pipe code is still there and can be conditionally removed by
112    #undef TUI_USE_PIPE_FOR_READLINE.  */
113
114 /* For gdb 5.3, prefer to continue the pipe hack as a backup wheel.  */
115 #ifdef HAVE_PIPE
116 #define TUI_USE_PIPE_FOR_READLINE
117 #endif
118 /* #undef TUI_USE_PIPE_FOR_READLINE */
119
120 /* TUI output files.  */
121 static struct ui_file *tui_stdout;
122 static struct ui_file *tui_stderr;
123 struct ui_out *tui_out;
124
125 /* GDB output files in non-curses mode.  */
126 static struct ui_file *tui_old_stdout;
127 static struct ui_file *tui_old_stderr;
128 struct ui_out *tui_old_uiout;
129
130 /* Readline previous hooks.  */
131 static rl_getc_func_t *tui_old_rl_getc_function;
132 static rl_voidfunc_t *tui_old_rl_redisplay_function;
133 static rl_vintfunc_t *tui_old_rl_prep_terminal;
134 static rl_voidfunc_t *tui_old_rl_deprep_terminal;
135 static int tui_old_rl_echoing_p;
136
137 /* Readline output stream.
138    Should be removed when readline is clean.  */
139 static FILE *tui_rl_outstream;
140 static FILE *tui_old_rl_outstream;
141 #ifdef TUI_USE_PIPE_FOR_READLINE
142 static int tui_readline_pipe[2];
143 #endif
144
145 /* The last gdb prompt that was registered in readline.
146    This may be the main gdb prompt or a secondary prompt.  */
147 static char *tui_rl_saved_prompt;
148
149 static int tui_handle_resize_during_io (int, int);
150
151 static void
152 tui_putc (char c)
153 {
154   char buf[2];
155
156   buf[0] = c;
157   buf[1] = 0;
158   tui_puts (buf);
159 }
160
161 /* Print the string in the curses command window.  */
162 void
163 tui_puts (const char *string)
164 {
165   static int tui_skip_line = -1;
166   char c;
167   WINDOW *w;
168
169   w = TUI_CMD_WIN->generic.handle;
170   while ((c = *string++) != 0)
171     {
172       /* Catch annotation and discard them.  We need two \032 and
173          discard until a \n is seen.  */
174       if (c == '\032')
175         {
176           tui_skip_line++;
177         }
178       else if (tui_skip_line != 1)
179         {
180           tui_skip_line = -1;
181           /* Expand TABs, since ncurses on MS-Windows doesn't.  */
182           if (c == '\t')
183             {
184               int line, col;
185
186               getyx (w, line, col);
187               do
188                 {
189                   waddch (w, ' ');
190                   col++;
191                 } while ((col % 8) != 0);
192             }
193           else
194             waddch (w, c);
195         }
196       else if (c == '\n')
197         tui_skip_line = -1;
198     }
199   getyx (w, TUI_CMD_WIN->detail.command_info.cur_line,
200          TUI_CMD_WIN->detail.command_info.curch);
201   TUI_CMD_WIN->detail.command_info.start_line
202     = TUI_CMD_WIN->detail.command_info.cur_line;
203
204   /* We could defer the following.  */
205   wrefresh (w);
206   fflush (stdout);
207 }
208
209 /* Readline callback.
210    Redisplay the command line with its prompt after readline has
211    changed the edited text.  */
212 void
213 tui_redisplay_readline (void)
214 {
215   int prev_col;
216   int height;
217   int col, line;
218   int c_pos;
219   int c_line;
220   int in;
221   WINDOW *w;
222   char *prompt;
223   int start_line;
224
225   /* Detect when we temporarily left SingleKey and now the readline
226      edit buffer is empty, automatically restore the SingleKey
227      mode.  The restore must only be done if the command has finished.
228      The command could call prompt_for_continue and we must not
229      restore SingleKey so that the prompt and normal keymap are used.  */
230   if (tui_current_key_mode == TUI_ONE_COMMAND_MODE && rl_end == 0
231       && immediate_quit == 0)
232     tui_set_key_mode (TUI_SINGLE_KEY_MODE);
233
234   if (tui_current_key_mode == TUI_SINGLE_KEY_MODE)
235     prompt = "";
236   else
237     prompt = tui_rl_saved_prompt;
238   
239   c_pos = -1;
240   c_line = -1;
241   w = TUI_CMD_WIN->generic.handle;
242   start_line = TUI_CMD_WIN->detail.command_info.start_line;
243   wmove (w, start_line, 0);
244   prev_col = 0;
245   height = 1;
246   for (in = 0; prompt && prompt[in]; in++)
247     {
248       waddch (w, prompt[in]);
249       getyx (w, line, col);
250       if (col <= prev_col)
251         height++;
252       prev_col = col;
253     }
254   for (in = 0; in <= rl_end; in++)
255     {
256       unsigned char c;
257       
258       if (in == rl_point)
259         {
260           getyx (w, c_line, c_pos);
261         }
262
263       if (in == rl_end)
264         break;
265
266       c = (unsigned char) rl_line_buffer[in];
267       if (CTRL_CHAR (c) || c == RUBOUT)
268         {
269           waddch (w, '^');
270           waddch (w, CTRL_CHAR (c) ? UNCTRL (c) : '?');
271         }
272       else if (c == '\t')
273         {
274           /* Expand TABs, since ncurses on MS-Windows doesn't.  */
275           getyx (w, line, col);
276           do
277             {
278               waddch (w, ' ');
279               col++;
280             } while ((col % 8) != 0);
281         }
282       else
283         {
284           waddch (w, c);
285         }
286       if (c == '\n')
287         {
288           getyx (w, TUI_CMD_WIN->detail.command_info.start_line,
289                  TUI_CMD_WIN->detail.command_info.curch);
290         }
291       getyx (w, line, col);
292       if (col < prev_col)
293         height++;
294       prev_col = col;
295     }
296   wclrtobot (w);
297   getyx (w, TUI_CMD_WIN->detail.command_info.start_line,
298          TUI_CMD_WIN->detail.command_info.curch);
299   if (c_line >= 0)
300     {
301       wmove (w, c_line, c_pos);
302       TUI_CMD_WIN->detail.command_info.cur_line = c_line;
303       TUI_CMD_WIN->detail.command_info.curch = c_pos;
304     }
305   TUI_CMD_WIN->detail.command_info.start_line -= height - 1;
306
307   wrefresh (w);
308   fflush(stdout);
309 }
310
311 /* Readline callback to prepare the terminal.  It is called once each
312    time we enter readline.  Terminal is already setup in curses
313    mode.  */
314 static void
315 tui_prep_terminal (int notused1)
316 {
317   /* Save the prompt registered in readline to correctly display it.
318      (we can't use gdb_prompt() due to secondary prompts and can't use
319      rl_prompt because it points to an alloca buffer).  */
320   xfree (tui_rl_saved_prompt);
321   tui_rl_saved_prompt = rl_prompt != NULL ? xstrdup (rl_prompt) : NULL;
322 }
323
324 /* Readline callback to restore the terminal.  It is called once each
325    time we leave readline.  There is nothing to do in curses mode.  */
326 static void
327 tui_deprep_terminal (void)
328 {
329 }
330
331 #ifdef TUI_USE_PIPE_FOR_READLINE
332 /* Read readline output pipe and feed the command window with it.
333    Should be removed when readline is clean.  */
334 static void
335 tui_readline_output (int error, gdb_client_data data)
336 {
337   int size;
338   char buf[256];
339
340   size = read (tui_readline_pipe[0], buf, sizeof (buf) - 1);
341   if (size > 0 && tui_active)
342     {
343       buf[size] = 0;
344       tui_puts (buf);
345     }
346 }
347 #endif
348
349 /* TUI version of displayer.crlf.  */
350
351 static void
352 tui_mld_crlf (const struct match_list_displayer *displayer)
353 {
354   tui_putc ('\n');
355 }
356
357 /* TUI version of displayer.putch.  */
358
359 static void
360 tui_mld_putch (const struct match_list_displayer *displayer, int ch)
361 {
362   tui_putc (ch);
363 }
364
365 /* TUI version of displayer.puts.  */
366
367 static void
368 tui_mld_puts (const struct match_list_displayer *displayer, const char *s)
369 {
370   tui_puts (s);
371 }
372
373 /* TUI version of displayer.flush.  */
374
375 static void
376 tui_mld_flush (const struct match_list_displayer *displayer)
377 {
378   wrefresh (TUI_CMD_WIN->generic.handle);
379 }
380
381 /* TUI version of displayer.erase_entire_line.  */
382
383 static void
384 tui_mld_erase_entire_line (const struct match_list_displayer *displayer)
385 {
386   WINDOW *w = TUI_CMD_WIN->generic.handle;
387
388   wmove (w, TUI_CMD_WIN->detail.command_info.cur_line, 0);
389   wclrtoeol (w);
390   wmove (w, TUI_CMD_WIN->detail.command_info.cur_line, 0);
391 }
392
393 /* TUI version of displayer.beep.  */
394
395 static void
396 tui_mld_beep (const struct match_list_displayer *displayer)
397 {
398   beep ();
399 }
400
401 /* Helper function for tui_mld_read_key.
402    This temporarily replaces tui_getc for use during tab-completion
403    match list display.  */
404
405 static int
406 tui_mld_getc (FILE *fp)
407 {
408   WINDOW *w = TUI_CMD_WIN->generic.handle;
409   int c = wgetch (w);
410
411   c = tui_handle_resize_during_io (c, 1);
412
413   return c;
414 }
415
416 /* TUI version of displayer.read_key.  */
417
418 static int
419 tui_mld_read_key (const struct match_list_displayer *displayer)
420 {
421   rl_getc_func_t *prev = rl_getc_function;
422   int c;
423
424   /* We can't use tui_getc as we need NEWLINE to not get emitted.  */
425   rl_getc_function = tui_mld_getc;
426   c = rl_read_key ();
427   rl_getc_function = prev;
428   return c;
429 }
430
431 /* TUI version of rl_completion_display_matches_hook.
432    See gdb_display_match_list for a description of the arguments.  */
433
434 static void
435 tui_rl_display_match_list (char **matches, int len, int max)
436 {
437   struct match_list_displayer displayer;
438
439   rl_get_screen_size (&displayer.height, &displayer.width);
440   displayer.crlf = tui_mld_crlf;
441   displayer.putch = tui_mld_putch;
442   displayer.puts = tui_mld_puts;
443   displayer.flush = tui_mld_flush;
444   displayer.erase_entire_line = tui_mld_erase_entire_line;
445   displayer.beep = tui_mld_beep;
446   displayer.read_key = tui_mld_read_key;
447
448   gdb_display_match_list (matches, len, max, &displayer);
449 }
450
451 /* Setup the IO for curses or non-curses mode.
452    - In non-curses mode, readline and gdb use the standard input and
453    standard output/error directly.
454    - In curses mode, the standard output/error is controlled by TUI
455    with the tui_stdout and tui_stderr.  The output is redirected in
456    the curses command window.  Several readline callbacks are installed
457    so that readline asks for its input to the curses command window
458    with wgetch().  */
459 void
460 tui_setup_io (int mode)
461 {
462   extern int _rl_echoing_p;
463
464   if (mode)
465     {
466       /* Redirect readline to TUI.  */
467       tui_old_rl_redisplay_function = rl_redisplay_function;
468       tui_old_rl_deprep_terminal = rl_deprep_term_function;
469       tui_old_rl_prep_terminal = rl_prep_term_function;
470       tui_old_rl_getc_function = rl_getc_function;
471       tui_old_rl_outstream = rl_outstream;
472       tui_old_rl_echoing_p = _rl_echoing_p;
473       rl_redisplay_function = tui_redisplay_readline;
474       rl_deprep_term_function = tui_deprep_terminal;
475       rl_prep_term_function = tui_prep_terminal;
476       rl_getc_function = tui_getc;
477       _rl_echoing_p = 0;
478       rl_outstream = tui_rl_outstream;
479       rl_prompt = 0;
480       rl_completion_display_matches_hook = tui_rl_display_match_list;
481       rl_already_prompted = 0;
482
483       /* Keep track of previous gdb output.  */
484       tui_old_stdout = gdb_stdout;
485       tui_old_stderr = gdb_stderr;
486       tui_old_uiout = current_uiout;
487
488       /* Reconfigure gdb output.  */
489       gdb_stdout = tui_stdout;
490       gdb_stderr = tui_stderr;
491       gdb_stdlog = gdb_stdout;  /* for moment */
492       gdb_stdtarg = gdb_stderr; /* for moment */
493       gdb_stdtargerr = gdb_stderr;      /* for moment */
494       current_uiout = tui_out;
495
496       /* Save tty for SIGCONT.  */
497       savetty ();
498     }
499   else
500     {
501       /* Restore gdb output.  */
502       gdb_stdout = tui_old_stdout;
503       gdb_stderr = tui_old_stderr;
504       gdb_stdlog = gdb_stdout;  /* for moment */
505       gdb_stdtarg = gdb_stderr; /* for moment */
506       gdb_stdtargerr = gdb_stderr;      /* for moment */
507       current_uiout = tui_old_uiout;
508
509       /* Restore readline.  */
510       rl_redisplay_function = tui_old_rl_redisplay_function;
511       rl_deprep_term_function = tui_old_rl_deprep_terminal;
512       rl_prep_term_function = tui_old_rl_prep_terminal;
513       rl_getc_function = tui_old_rl_getc_function;
514       rl_outstream = tui_old_rl_outstream;
515       rl_completion_display_matches_hook = 0;
516       _rl_echoing_p = tui_old_rl_echoing_p;
517       rl_already_prompted = 0;
518
519       /* Save tty for SIGCONT.  */
520       savetty ();
521     }
522 }
523
524 #ifdef SIGCONT
525 /* Catch SIGCONT to restore the terminal and refresh the screen.  */
526 static void
527 tui_cont_sig (int sig)
528 {
529   if (tui_active)
530     {
531       /* Restore the terminal setting because another process (shell)
532          might have changed it.  */
533       resetty ();
534
535       /* Force a refresh of the screen.  */
536       tui_refresh_all_win ();
537
538       /* Update cursor position on the screen.  */
539       wmove (TUI_CMD_WIN->generic.handle,
540              TUI_CMD_WIN->detail.command_info.start_line,
541              TUI_CMD_WIN->detail.command_info.curch);
542       wrefresh (TUI_CMD_WIN->generic.handle);
543     }
544   signal (sig, tui_cont_sig);
545 }
546 #endif
547
548 /* Initialize the IO for gdb in curses mode.  */
549 void
550 tui_initialize_io (void)
551 {
552 #ifdef SIGCONT
553   signal (SIGCONT, tui_cont_sig);
554 #endif
555
556   /* Create tui output streams.  */
557   tui_stdout = tui_fileopen (stdout);
558   tui_stderr = tui_fileopen (stderr);
559   tui_out = tui_out_new (tui_stdout);
560
561   /* Create the default UI.  */
562   tui_old_uiout = cli_out_new (gdb_stdout);
563
564 #ifdef TUI_USE_PIPE_FOR_READLINE
565   /* Temporary solution for readline writing to stdout: redirect
566      readline output in a pipe, read that pipe and output the content
567      in the curses command window.  */
568   if (gdb_pipe_cloexec (tui_readline_pipe) != 0)
569     error (_("Cannot create pipe for readline"));
570
571   tui_rl_outstream = fdopen (tui_readline_pipe[1], "w");
572   if (tui_rl_outstream == 0)
573     error (_("Cannot redirect readline output"));
574
575   setvbuf (tui_rl_outstream, (char*) NULL, _IOLBF, 0);
576
577 #ifdef O_NONBLOCK
578   (void) fcntl (tui_readline_pipe[0], F_SETFL, O_NONBLOCK);
579 #else
580 #ifdef O_NDELAY
581   (void) fcntl (tui_readline_pipe[0], F_SETFL, O_NDELAY);
582 #endif
583 #endif
584   add_file_handler (tui_readline_pipe[0], tui_readline_output, 0);
585 #else
586   tui_rl_outstream = stdout;
587 #endif
588 }
589
590 /* Get a character from the command window.  This is called from the
591    readline package.  */
592 int
593 tui_getc (FILE *fp)
594 {
595   int ch;
596   WINDOW *w;
597
598   w = TUI_CMD_WIN->generic.handle;
599
600 #ifdef TUI_USE_PIPE_FOR_READLINE
601   /* Flush readline output.  */
602   tui_readline_output (0, 0);
603 #endif
604
605   ch = wgetch (w);
606   ch = tui_handle_resize_during_io (ch, 0);
607
608   /* The \n must be echoed because it will not be printed by
609      readline.  */
610   if (ch == '\n')
611     {
612       /* When hitting return with an empty input, gdb executes the last
613          command.  If we emit a newline, this fills up the command window
614          with empty lines with gdb prompt at beginning.  Instead of that,
615          stay on the same line but provide a visual effect to show the
616          user we recognized the command.  */
617       if (rl_end == 0)
618         {
619           wmove (w, TUI_CMD_WIN->detail.command_info.cur_line, 0);
620
621           /* Clear the line.  This will blink the gdb prompt since
622              it will be redrawn at the same line.  */
623           wclrtoeol (w);
624           wrefresh (w);
625           napms (20);
626         }
627       else
628         {
629           wmove (w, TUI_CMD_WIN->detail.command_info.cur_line,
630                  TUI_CMD_WIN->detail.command_info.curch);
631           waddch (w, ch);
632         }
633     }
634   
635   if (key_is_command_char (ch))
636     {                           /* Handle prev/next/up/down here.  */
637       ch = tui_dispatch_ctrl_char (ch);
638     }
639   
640   if (ch == '\n' || ch == '\r' || ch == '\f')
641     TUI_CMD_WIN->detail.command_info.curch = 0;
642   if (ch == KEY_BACKSPACE)
643     return '\b';
644
645   if (async_command_editing_p && key_is_start_sequence (ch))
646     {
647       int ch_pending;
648
649       nodelay (w, TRUE);
650       ch_pending = wgetch (w);
651       nodelay (w, FALSE);
652
653       /* If we have pending input following a start sequence, call the stdin
654          event handler again because ncurses may have already read and stored
655          the input into its internal buffer, meaning that we won't get an stdin
656          event for it.  If we don't compensate for this missed stdin event, key
657          sequences as Alt_F (^[f) will not behave promptly.
658
659          (We only compensates for the missed 2nd byte of a key sequence because
660          2-byte sequences are by far the most commonly used. ncurses may have
661          buffered a larger, 3+-byte key sequence though it remains to be seen
662          whether it is useful to compensate for all the bytes of such
663          sequences.)  */
664       if (ch_pending != ERR)
665         {
666           ungetch (ch_pending);
667           call_stdin_event_handler_again_p = 1;
668         }
669     }
670
671   return ch;
672 }
673
674 /* Utility function to expand TABs in a STRING into spaces.  STRING
675    will be displayed starting at column COL, and is assumed to include
676    no newlines.  The returned expanded string is malloc'ed.  */
677
678 char *
679 tui_expand_tabs (const char *string, int col)
680 {
681   int n_adjust;
682   const char *s;
683   char *ret, *q;
684
685   /* 1. How many additional characters do we need?  */
686   for (n_adjust = 0, s = string; s; )
687     {
688       s = strpbrk (s, "\t");
689       if (s)
690         {
691           col += (s - string) + n_adjust;
692           /* Adjustment for the next tab stop, minus one for the TAB
693              we replace with spaces.  */
694           n_adjust += 8 - (col % 8) - 1;
695           s++;
696         }
697     }
698
699   /* Allocate the copy.  */
700   ret = q = xmalloc (strlen (string) + n_adjust + 1);
701
702   /* 2. Copy the original string while replacing TABs with spaces.  */
703   for (s = string; s; )
704     {
705       char *s1 = strpbrk (s, "\t");
706       if (s1)
707         {
708           if (s1 > s)
709             {
710               strncpy (q, s, s1 - s);
711               q += s1 - s;
712               col += s1 - s;
713             }
714           do {
715             *q++ = ' ';
716             col++;
717           } while ((col % 8) != 0);
718           s1++;
719         }
720       else
721         strcpy (q, s);
722       s = s1;
723     }
724
725   return ret;
726 }
727
728 /* Cleanup when a resize has occured.
729    Returns the character that must be processed.  */
730
731 static int
732 tui_handle_resize_during_io (int original_ch, int for_completion)
733 {
734   if (tui_win_resized ())
735     {
736       tui_resize_all ();
737       tui_refresh_all_win ();
738       tui_set_win_resized_to (FALSE);
739       if (!for_completion)
740         {
741           dont_repeat ();
742           return '\n';
743         }
744     }
745
746   return original_ch;
747 }