Replace numerous instances of xzalloc with XZALLOC
[pspp] / src / ui / terminal / terminal-reader.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2007, 2009, 2010, 2011, 2013 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include <signal.h>
20 #include <unistd.h>
21 #include <fcntl.h>
22 #include <stdbool.h>
23 #include <stdio.h>
24
25 #include "libpspp/str.h"
26
27 #if HAVE_READLINE
28 #include <readline/readline.h>
29 #include <readline/history.h>
30 #include <termios.h>
31
32 static char *history_file;
33
34 static char **complete_command_name (const char *, int, int);
35 static char **dont_complete (const char *, int, int);
36 static char *command_generator (const char *text, int state);
37 #endif
38
39
40 #include "ui/terminal/terminal-reader.h"
41 #include <sys/select.h>
42 #include <sys/time.h>
43 #include <sys/types.h>
44
45 #include <errno.h>
46 #include <stdint.h>
47 #include <stdlib.h>
48
49 #include "data/settings.h"
50 #include "language/command.h"
51 #include "language/lexer/lexer.h"
52 #include "libpspp/assertion.h"
53 #include "libpspp/cast.h"
54 #include "libpspp/message.h"
55 #include "libpspp/prompt.h"
56 #include "libpspp/str.h"
57 #include "libpspp/version.h"
58 #include "output/driver.h"
59 #include "output/journal.h"
60
61 #include "gl/minmax.h"
62 #include "gl/xalloc.h"
63
64 #include "gettext.h"
65 #define _(msgid) gettext (msgid)
66
67 struct terminal_reader
68   {
69     struct lex_reader reader;
70     struct substring s;
71     size_t offset;
72     bool eof;
73   };
74
75 static int n_terminal_readers;
76
77 static void readline_init (void);
78 static void readline_done (void);
79 static bool readline_read (struct substring *, enum prompt_style);
80
81 /* Display a welcoming message. */
82 static void
83 welcome (void)
84 {
85   static bool welcomed = false;
86   if (welcomed)
87     return;
88   welcomed = true;
89   fputs ("PSPP is free software and you are welcome to distribute copies of "
90          "it\nunder certain conditions; type \"show copying.\" to see the "
91          "conditions.\nThere is ABSOLUTELY NO WARRANTY for PSPP; type \"show "
92          "warranty.\" for details.\n", stdout);
93   puts (announced_version);
94   journal_init ();
95 }
96
97 static struct terminal_reader *
98 terminal_reader_cast (struct lex_reader *r)
99 {
100   return UP_CAST (r, struct terminal_reader, reader);
101 }
102
103
104 /* Older libreadline versions do not provide rl_outstream.
105    However, it is almost always going to be the same as stdout. */
106 #if ! HAVE_RL_OUTSTREAM
107 # define rl_outstream stdout
108 #endif
109
110
111 #if HAVE_READLINE
112 /* Similarly, rl_echo_signal_char is fairly recent.
113    We provide our own crude version if it is not present. */
114 #if ! HAVE_RL_ECHO_SIGNAL_CHAR
115 static void
116 rl_echo_signal_char (int sig)
117 {
118 #if HAVE_TERMIOS_H
119   struct termios t;
120   if (0 == tcgetattr (0, &t))
121     {
122       cc_t c = t.c_cc[VINTR];
123
124       if (c >= 0  && c <= 'Z' - 'A')
125         fprintf (rl_outstream, "^%c", 'A' + c - 1);
126       else
127         fprintf (rl_outstream, "%c", c);
128     }
129   else
130 #endif
131     fprintf (rl_outstream, "^C");
132
133   fflush (rl_outstream);
134 }
135 #endif
136 #endif
137
138
139 static size_t
140 terminal_reader_read (struct lex_reader *r_, char *buf, size_t n,
141                       enum prompt_style prompt_style)
142 {
143   struct terminal_reader *r = terminal_reader_cast (r_);
144   size_t chunk;
145
146   if (r->offset >= r->s.length && !r->eof)
147     {
148       welcome ();
149       msg_ui_reset_counts ();
150       output_flush ();
151
152       ss_dealloc (&r->s);
153       if (! readline_read (&r->s, prompt_style))
154         {
155           *buf = '\n';
156           fprintf (rl_outstream, "\n");
157           return 1;
158         }
159       r->offset = 0;
160       r->eof = ss_is_empty (r->s);
161     }
162
163   chunk = MIN (n, r->s.length - r->offset);
164   memcpy (buf, r->s.string + r->offset, chunk);
165   r->offset += chunk;
166   return chunk;
167 }
168
169 static void
170 terminal_reader_close (struct lex_reader *r_)
171 {
172   struct terminal_reader *r = terminal_reader_cast (r_);
173
174   ss_dealloc (&r->s);
175   free (r->reader.file_name);
176   free (r);
177
178   if (!--n_terminal_readers)
179     readline_done ();
180 }
181
182 static struct lex_reader_class terminal_reader_class =
183   {
184     terminal_reader_read,
185     terminal_reader_close
186   };
187
188 /* Creates a source which uses readln to get its line */
189 struct lex_reader *
190 terminal_reader_create (void)
191 {
192   if (!n_terminal_readers++)
193     readline_init ();
194
195   struct terminal_reader *r = XZALLOC (struct terminal_reader);
196   r->reader.class = &terminal_reader_class;
197   r->reader.syntax = SEG_MODE_INTERACTIVE;
198   r->reader.error = LEX_ERROR_TERMINAL;
199   r->reader.file_name = NULL;
200   r->s = ss_empty ();
201   r->offset = 0;
202   r->eof = false;
203   return &r->reader;
204 }
205 \f
206
207
208 static const char *
209 readline_prompt (enum prompt_style style)
210 {
211   switch (style)
212     {
213     case PROMPT_FIRST:
214       return "PSPP> ";
215
216     case PROMPT_LATER:
217       return "    > ";
218
219     case PROMPT_DATA:
220       return "data> ";
221
222     case PROMPT_COMMENT:
223       return "comment> ";
224
225     case PROMPT_DOCUMENT:
226       return "document> ";
227
228     case PROMPT_DO_REPEAT:
229       return "DO REPEAT> ";
230
231     case PROMPT_DEFINE:
232       return "DEFINE> ";
233     }
234
235   NOT_REACHED ();
236 }
237
238
239 #if HAVE_READLINE
240
241 static int pfd[2];
242 static bool sigint_received ;
243
244 /*
245    A function similar to getc from stdio.
246    However this one may be interrupted by SIGINT.
247    If that happens it will return EOF and the global variable
248    sigint_received will be set to true.
249  */
250 static int
251 interruptible_getc (FILE *fp)
252 {
253   int c  = 0;
254   int ret = -1;
255   do
256     {
257       struct timeval timeout = {0, 50000};
258       fd_set what;
259       int max_fd = 0;
260       int fd ;
261       FD_ZERO (&what);
262       fd = fileno (fp);
263       max_fd = (max_fd > fd) ? max_fd : fd;
264       FD_SET (fd, &what);
265       fd = pfd[0];
266       max_fd = (max_fd > fd) ? max_fd : fd;
267       FD_SET (fd, &what);
268       ret = select (max_fd + 1, &what, NULL, NULL, &timeout);
269       if (ret == -1 && errno != EINTR)
270         {
271           perror ("Select failed");
272           continue;
273         }
274
275       if (ret > 0)
276         {
277           if (FD_ISSET (pfd[0], &what))
278             {
279               char dummy[1];
280               read (pfd[0], dummy, 1);
281               sigint_received = true;
282               return EOF;
283             }
284         }
285     }
286   while (ret <= 0);
287
288   /* This will not block! */
289   read (fileno (fp), &c, 1);
290
291   return c;
292 }
293
294 static void
295 handler (int sig)
296 {
297   rl_end = 0;
298
299   write (pfd[1], "x", 1);
300   rl_echo_signal_char (sig);
301 }
302
303
304 static void
305 readline_init (void)
306 {
307   if (0 != pipe2 (pfd, O_NONBLOCK))
308     perror ("Cannot create pipe");
309
310   if (SIG_ERR == signal (SIGINT, handler))
311     perror ("Cannot add signal handler");
312
313   rl_catch_signals = 0;
314   rl_getc_function = interruptible_getc;
315   rl_basic_word_break_characters = "\n";
316   using_history ();
317   stifle_history (500);
318   if (history_file == NULL)
319     {
320       const char *home_dir = getenv ("HOME");
321       if (home_dir != NULL)
322         {
323           history_file = xasprintf ("%s/.pspp_history", home_dir);
324           read_history (history_file);
325         }
326     }
327 }
328
329 static void
330 readline_done (void)
331 {
332   if (history_file != NULL && false == settings_get_testing_mode ())
333     write_history (history_file);
334   clear_history ();
335   free (history_file);
336 }
337
338 /* Prompt the user for a line of input and return it in LINE.
339    Returns true if the LINE should be considered valid, false otherwise.
340  */
341 static bool
342 readline_read (struct substring *line, enum prompt_style style)
343 {
344   char *string;
345
346   rl_attempted_completion_function = (style == PROMPT_FIRST
347                                       ? complete_command_name
348                                       : dont_complete);
349   sigint_received = false;
350   string = readline (readline_prompt (style));
351   if (sigint_received)
352     {
353       *line = ss_empty ();
354       return false;
355     }
356
357   if (string != NULL)
358     {
359       char *end;
360
361       if (string[0])
362         add_history (string);
363
364       end = strchr (string, '\0');
365       *end = '\n';
366       *line = ss_buffer (string, end - string + 1);
367     }
368   else
369     *line = ss_empty ();
370
371   return true;
372 }
373
374 /* Returns a set of command name completions for TEXT.
375    This is of the proper form for assigning to
376    rl_attempted_completion_function. */
377 static char **
378 complete_command_name (const char *text, int start, int end UNUSED)
379 {
380   if (start == 0)
381     {
382       /* Complete command name at start of line. */
383       return rl_completion_matches (text, command_generator);
384     }
385   else
386     {
387       /* Otherwise don't do any completion. */
388       rl_attempted_completion_over = 1;
389       return NULL;
390     }
391 }
392
393 /* Do not do any completion for TEXT. */
394 static char **
395 dont_complete (const char *text UNUSED, int start UNUSED, int end UNUSED)
396 {
397   rl_attempted_completion_over = 1;
398   return NULL;
399 }
400
401 /* If STATE is 0, returns the first command name matching TEXT.
402    Otherwise, returns the next command name matching TEXT.
403    Returns a null pointer when no matches are left. */
404 static char *
405 command_generator (const char *text, int state)
406 {
407   static const struct command *cmd;
408   const char *name;
409
410   if (state == 0)
411     cmd = NULL;
412   name = cmd_complete (text, &cmd);
413   return xstrdup_if_nonnull (name);
414 }
415
416 #else  /* !HAVE_READLINE */
417
418 static const char * the_prompt;
419
420 static void
421 handler (int sig)
422 {
423   if (the_prompt)
424     fputs (the_prompt, stdout);
425   fflush (stdout);
426 }
427
428 static void
429 readline_init (void)
430 {
431   if (SIG_ERR == signal (SIGINT, handler))
432     perror ("Cannot add signal handler");
433 }
434
435 static void
436 readline_done (void)
437 {
438 }
439
440 /* Prompt the user for a line of input and return it in LINE.
441    Returns true if the LINE should be considered valid, false otherwise.
442  */
443 static bool
444 readline_read (struct substring *line, enum prompt_style style)
445 {
446   struct string string;
447   the_prompt = readline_prompt (style);
448
449   fputs (the_prompt, stdout);
450   fflush (stdout);
451   ds_init_empty (&string);
452   ds_read_line (&string, stdin, SIZE_MAX);
453
454   *line = string.ss;
455
456   return true;
457 }
458 #endif /* !HAVE_READLINE */