1/* input.c -- character input functions for readline. */
2
3/* Copyright (C) 1994-2005 Free Software Foundation, Inc.
4
5   This file is part of the GNU Readline Library, a library for
6   reading lines of text with interactive input and history editing.
7
8   The GNU Readline Library is free software; you can redistribute it
9   and/or modify it under the terms of the GNU General Public License
10   as published by the Free Software Foundation; either version 2, or
11   (at your option) any later version.
12
13   The GNU Readline Library is distributed in the hope that it will be
14   useful, but WITHOUT ANY WARRANTY; without even the implied warranty
15   of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18   The GNU General Public License is often shipped with GNU software, and
19   is generally kept in a file called COPYING or LICENSE.  If you do not
20   have a copy of the license, write to the Free Software Foundation,
21   59 Temple Place, Suite 330, Boston, MA 02111 USA. */
22#define READLINE_LIBRARY
23
24#if defined (__TANDEM)
25#  include <floss.h>
26#endif
27
28#if defined (HAVE_CONFIG_H)
29#  include <config.h>
30#endif
31
32#include <sys/types.h>
33#include <fcntl.h>
34#if defined (HAVE_SYS_FILE_H)
35#  include <sys/file.h>
36#endif /* HAVE_SYS_FILE_H */
37
38#if defined (HAVE_UNISTD_H)
39#  include <unistd.h>
40#endif /* HAVE_UNISTD_H */
41
42#if defined (HAVE_STDLIB_H)
43#  include <stdlib.h>
44#else
45#  include "ansi_stdlib.h"
46#endif /* HAVE_STDLIB_H */
47
48#if defined (HAVE_SELECT)
49#  if !defined (HAVE_SYS_SELECT_H) || !defined (M_UNIX)
50#    include <sys/time.h>
51#  endif
52#endif /* HAVE_SELECT */
53#if defined (HAVE_SYS_SELECT_H)
54#  include <sys/select.h>
55#endif
56
57#if defined (FIONREAD_IN_SYS_IOCTL)
58#  include <sys/ioctl.h>
59#endif
60
61#include <stdio.h>
62#include <errno.h>
63
64#if !defined (errno)
65extern int errno;
66#endif /* !errno */
67
68/* System-specific feature definitions and include files. */
69#include "rldefs.h"
70#include "rlmbutil.h"
71
72/* Some standard library routines. */
73#include "readline.h"
74
75#include "rlprivate.h"
76#include "rlshell.h"
77#include "xmalloc.h"
78
79/* What kind of non-blocking I/O do we have? */
80#if !defined (O_NDELAY) && defined (O_NONBLOCK)
81#  define O_NDELAY O_NONBLOCK	/* Posix style */
82#endif
83
84/* Non-null means it is a pointer to a function to run while waiting for
85   character input. */
86rl_hook_func_t *rl_event_hook = (rl_hook_func_t *)NULL;
87
88rl_getc_func_t *rl_getc_function = rl_getc;
89
90static int _keyboard_input_timeout = 100000;		/* 0.1 seconds; it's in usec */
91
92static int ibuffer_space PARAMS((void));
93static int rl_get_char PARAMS((int *));
94static int rl_gather_tyi PARAMS((void));
95
96/* **************************************************************** */
97/*								    */
98/*			Character Input Buffering       	    */
99/*								    */
100/* **************************************************************** */
101
102static int pop_index, push_index;
103static unsigned char ibuffer[512];
104static int ibuffer_len = sizeof (ibuffer) - 1;
105
106#define any_typein (push_index != pop_index)
107
108int
109_rl_any_typein ()
110{
111  return any_typein;
112}
113
114/* Return the amount of space available in the buffer for stuffing
115   characters. */
116static int
117ibuffer_space ()
118{
119  if (pop_index > push_index)
120    return (pop_index - push_index - 1);
121  else
122    return (ibuffer_len - (push_index - pop_index));
123}
124
125/* Get a key from the buffer of characters to be read.
126   Return the key in KEY.
127   Result is KEY if there was a key, or 0 if there wasn't. */
128static int
129rl_get_char (key)
130     int *key;
131{
132  if (push_index == pop_index)
133    return (0);
134
135  *key = ibuffer[pop_index++];
136#if 0
137  if (pop_index >= ibuffer_len)
138#else
139  if (pop_index > ibuffer_len)
140#endif
141    pop_index = 0;
142
143  return (1);
144}
145
146/* Stuff KEY into the *front* of the input buffer.
147   Returns non-zero if successful, zero if there is
148   no space left in the buffer. */
149int
150_rl_unget_char (key)
151     int key;
152{
153  if (ibuffer_space ())
154    {
155      pop_index--;
156      if (pop_index < 0)
157	pop_index = ibuffer_len - 1;
158      ibuffer[pop_index] = key;
159      return (1);
160    }
161  return (0);
162}
163
164int
165_rl_pushed_input_available ()
166{
167  return (push_index != pop_index);
168}
169
170/* If a character is available to be read, then read it and stuff it into
171   IBUFFER.  Otherwise, just return.  Returns number of characters read
172   (0 if none available) and -1 on error (EIO). */
173static int
174rl_gather_tyi ()
175{
176  int tty;
177  register int tem, result;
178  int chars_avail, k;
179  char input;
180#if defined(HAVE_SELECT)
181  fd_set readfds, exceptfds;
182  struct timeval timeout;
183#endif
184
185  chars_avail = 0;
186  tty = fileno (rl_instream);
187
188#if defined (HAVE_SELECT)
189  FD_ZERO (&readfds);
190  FD_ZERO (&exceptfds);
191  FD_SET (tty, &readfds);
192  FD_SET (tty, &exceptfds);
193  timeout.tv_sec = 0;
194  timeout.tv_usec = _keyboard_input_timeout;
195  result = select (tty + 1, &readfds, (fd_set *)NULL, &exceptfds, &timeout);
196  if (result <= 0)
197    return 0;	/* Nothing to read. */
198#endif
199
200  result = -1;
201#if defined (FIONREAD)
202  errno = 0;
203  result = ioctl (tty, FIONREAD, &chars_avail);
204  if (result == -1 && errno == EIO)
205    return -1;
206#endif
207
208#if defined (O_NDELAY)
209  if (result == -1)
210    {
211      tem = fcntl (tty, F_GETFL, 0);
212
213      fcntl (tty, F_SETFL, (tem | O_NDELAY));
214      chars_avail = read (tty, &input, 1);
215
216      fcntl (tty, F_SETFL, tem);
217      if (chars_avail == -1 && errno == EAGAIN)
218	return 0;
219      if (chars_avail == 0)	/* EOF */
220	{
221	  rl_stuff_char (EOF);
222	  return (0);
223	}
224    }
225#endif /* O_NDELAY */
226
227#if defined (__MINGW32__)
228  /* Use getch/_kbhit to check for available console input, in the same way
229     that we read it normally. */
230   chars_avail = isatty (tty) ? _kbhit () : 0;
231   result = 0;
232#endif
233
234  /* If there's nothing available, don't waste time trying to read
235     something. */
236  if (chars_avail <= 0)
237    return 0;
238
239  tem = ibuffer_space ();
240
241  if (chars_avail > tem)
242    chars_avail = tem;
243
244  /* One cannot read all of the available input.  I can only read a single
245     character at a time, or else programs which require input can be
246     thwarted.  If the buffer is larger than one character, I lose.
247     Damn! */
248  if (tem < ibuffer_len)
249    chars_avail = 0;
250
251  if (result != -1)
252    {
253      while (chars_avail--)
254	{
255	  k = (*rl_getc_function) (rl_instream);
256	  if (rl_stuff_char (k) == 0)
257	    break;			/* some problem; no more room */
258	  if (k == NEWLINE || k == RETURN)
259	    break;
260	}
261    }
262  else
263    {
264      if (chars_avail)
265	rl_stuff_char (input);
266    }
267
268  return 1;
269}
270
271int
272rl_set_keyboard_input_timeout (u)
273     int u;
274{
275  int o;
276
277  o = _keyboard_input_timeout;
278  if (u >= 0)
279    _keyboard_input_timeout = u;
280  return (o);
281}
282
283/* Is there input available to be read on the readline input file
284   descriptor?  Only works if the system has select(2) or FIONREAD.
285   Uses the value of _keyboard_input_timeout as the timeout; if another
286   readline function wants to specify a timeout and not leave it up to
287   the user, it should use _rl_input_queued(timeout_value_in_microseconds)
288   instead. */
289int
290_rl_input_available ()
291{
292#if defined(HAVE_SELECT)
293  fd_set readfds, exceptfds;
294  struct timeval timeout;
295#endif
296#if !defined (HAVE_SELECT) && defined(FIONREAD)
297  int chars_avail;
298#endif
299  int tty;
300
301  tty = fileno (rl_instream);
302
303#if defined (HAVE_SELECT)
304  FD_ZERO (&readfds);
305  FD_ZERO (&exceptfds);
306  FD_SET (tty, &readfds);
307  FD_SET (tty, &exceptfds);
308  timeout.tv_sec = 0;
309  timeout.tv_usec = _keyboard_input_timeout;
310  return (select (tty + 1, &readfds, (fd_set *)NULL, &exceptfds, &timeout) > 0);
311#else
312
313#if defined (FIONREAD)
314  if (ioctl (tty, FIONREAD, &chars_avail) == 0)
315    return (chars_avail);
316#endif
317
318#endif
319
320#if defined (__MINGW32__)
321  if (isatty (tty))
322    return (_kbhit ());
323#endif
324
325  return 0;
326}
327
328int
329_rl_input_queued (t)
330     int t;
331{
332  int old_timeout, r;
333
334  old_timeout = rl_set_keyboard_input_timeout (t);
335  r = _rl_input_available ();
336  rl_set_keyboard_input_timeout (old_timeout);
337  return r;
338}
339
340void
341_rl_insert_typein (c)
342     int c;
343{
344  int key, t, i;
345  char *string;
346
347  i = key = 0;
348  string = (char *)xmalloc (ibuffer_len + 1);
349  string[i++] = (char) c;
350
351  while ((t = rl_get_char (&key)) &&
352	 _rl_keymap[key].type == ISFUNC &&
353	 _rl_keymap[key].function == rl_insert)
354    string[i++] = key;
355
356  if (t)
357    _rl_unget_char (key);
358
359  string[i] = '\0';
360  rl_insert_text (string);
361  free (string);
362}
363
364/* Add KEY to the buffer of characters to be read.  Returns 1 if the
365   character was stuffed correctly; 0 otherwise. */
366int
367rl_stuff_char (key)
368     int key;
369{
370  if (ibuffer_space () == 0)
371    return 0;
372
373  if (key == EOF)
374    {
375      key = NEWLINE;
376      rl_pending_input = EOF;
377      RL_SETSTATE (RL_STATE_INPUTPENDING);
378    }
379  ibuffer[push_index++] = key;
380#if 0
381  if (push_index >= ibuffer_len)
382#else
383  if (push_index > ibuffer_len)
384#endif
385    push_index = 0;
386
387  return 1;
388}
389
390/* Make C be the next command to be executed. */
391int
392rl_execute_next (c)
393     int c;
394{
395  rl_pending_input = c;
396  RL_SETSTATE (RL_STATE_INPUTPENDING);
397  return 0;
398}
399
400/* Clear any pending input pushed with rl_execute_next() */
401int
402rl_clear_pending_input ()
403{
404  rl_pending_input = 0;
405  RL_UNSETSTATE (RL_STATE_INPUTPENDING);
406  return 0;
407}
408
409/* **************************************************************** */
410/*								    */
411/*			     Character Input			    */
412/*								    */
413/* **************************************************************** */
414
415/* Read a key, including pending input. */
416int
417rl_read_key ()
418{
419  int c;
420
421  rl_key_sequence_length++;
422
423  if (rl_pending_input)
424    {
425      c = rl_pending_input;
426      rl_clear_pending_input ();
427    }
428  else
429    {
430      /* If input is coming from a macro, then use that. */
431      if (c = _rl_next_macro_key ())
432	return (c);
433
434      /* If the user has an event function, then call it periodically. */
435      if (rl_event_hook)
436	{
437	  while (rl_event_hook && rl_get_char (&c) == 0)
438	    {
439	      (*rl_event_hook) ();
440	      if (rl_done)		/* XXX - experimental */
441		return ('\n');
442	      if (rl_gather_tyi () < 0)	/* XXX - EIO */
443		{
444		  rl_done = 1;
445		  return ('\n');
446		}
447	    }
448	}
449      else
450	{
451	  if (rl_get_char (&c) == 0)
452	    c = (*rl_getc_function) (rl_instream);
453	}
454    }
455
456  return (c);
457}
458
459int
460rl_getc (stream)
461     FILE *stream;
462{
463  int result;
464  unsigned char c;
465
466  while (1)
467    {
468#if defined (__MINGW32__)
469      if (isatty (fileno (stream)))
470	return (getch ());
471#endif
472      result = read (fileno (stream), &c, sizeof (unsigned char));
473
474      if (result == sizeof (unsigned char))
475	return (c);
476
477      /* If zero characters are returned, then the file that we are
478	 reading from is empty!  Return EOF in that case. */
479      if (result == 0)
480	return (EOF);
481
482#if defined (__BEOS__)
483      if (errno == EINTR)
484	continue;
485#endif
486
487#if defined (EWOULDBLOCK)
488#  define X_EWOULDBLOCK EWOULDBLOCK
489#else
490#  define X_EWOULDBLOCK -99
491#endif
492
493#if defined (EAGAIN)
494#  define X_EAGAIN EAGAIN
495#else
496#  define X_EAGAIN -99
497#endif
498
499      if (errno == X_EWOULDBLOCK || errno == X_EAGAIN)
500	{
501	  if (sh_unset_nodelay_mode (fileno (stream)) < 0)
502	    return (EOF);
503	  continue;
504	}
505
506#undef X_EWOULDBLOCK
507#undef X_EAGAIN
508
509      /* If the error that we received was SIGINT, then try again,
510	 this is simply an interrupted system call to read ().
511	 Otherwise, some error ocurred, also signifying EOF. */
512      if (errno != EINTR)
513	return (RL_ISSTATE (RL_STATE_READCMD) ? READERR : EOF);
514    }
515}
516
517#if defined (HANDLE_MULTIBYTE)
518/* read multibyte char */
519int
520_rl_read_mbchar (mbchar, size)
521     char *mbchar;
522     int size;
523{
524  int mb_len, c;
525  size_t mbchar_bytes_length;
526  wchar_t wc;
527  mbstate_t ps, ps_back;
528
529  memset(&ps, 0, sizeof (mbstate_t));
530  memset(&ps_back, 0, sizeof (mbstate_t));
531
532  mb_len = 0;
533  while (mb_len < size)
534    {
535      RL_SETSTATE(RL_STATE_MOREINPUT);
536      c = rl_read_key ();
537      RL_UNSETSTATE(RL_STATE_MOREINPUT);
538
539      if (c < 0)
540	break;
541
542      mbchar[mb_len++] = c;
543
544      mbchar_bytes_length = mbrtowc (&wc, mbchar, mb_len, &ps);
545      if (mbchar_bytes_length == (size_t)(-1))
546	break;		/* invalid byte sequence for the current locale */
547      else if (mbchar_bytes_length == (size_t)(-2))
548	{
549	  /* shorted bytes */
550	  ps = ps_back;
551	  continue;
552	}
553      else if (mbchar_bytes_length == 0)
554	{
555	  mbchar[0] = '\0';	/* null wide character */
556	  mb_len = 1;
557	  break;
558	}
559      else if (mbchar_bytes_length > (size_t)(0))
560	break;
561    }
562
563  return mb_len;
564}
565
566/* Read a multibyte-character string whose first character is FIRST into
567   the buffer MB of length MLEN.  Returns the last character read, which
568   may be FIRST.  Used by the search functions, among others.  Very similar
569   to _rl_read_mbchar. */
570int
571_rl_read_mbstring (first, mb, mlen)
572     int first;
573     char *mb;
574     int mlen;
575{
576  int i, c;
577  mbstate_t ps;
578
579  c = first;
580  memset (mb, 0, mlen);
581  for (i = 0; c >= 0 && i < mlen; i++)
582    {
583      mb[i] = (char)c;
584      memset (&ps, 0, sizeof (mbstate_t));
585      if (_rl_get_char_len (mb, &ps) == -2)
586	{
587	  /* Read more for multibyte character */
588	  RL_SETSTATE (RL_STATE_MOREINPUT);
589	  c = rl_read_key ();
590	  RL_UNSETSTATE (RL_STATE_MOREINPUT);
591	}
592      else
593	break;
594    }
595  return c;
596}
597#endif /* HANDLE_MULTIBYTE */
598