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