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
137  if (pop_index >= ibuffer_len)
138    pop_index = 0;
139
140  return (1);
141}
142
143/* Stuff KEY into the *front* of the input buffer.
144   Returns non-zero if successful, zero if there is
145   no space left in the buffer. */
146int
147_rl_unget_char (key)
148     int key;
149{
150  if (ibuffer_space ())
151    {
152      pop_index--;
153      if (pop_index < 0)
154	pop_index = ibuffer_len - 1;
155      ibuffer[pop_index] = key;
156      return (1);
157    }
158  return (0);
159}
160
161int
162_rl_pushed_input_available ()
163{
164  return (push_index != pop_index);
165}
166
167/* If a character is available to be read, then read it and stuff it into
168   IBUFFER.  Otherwise, just return.  Returns number of characters read
169   (0 if none available) and -1 on error (EIO). */
170static int
171rl_gather_tyi ()
172{
173  int tty;
174  register int tem, result;
175  int chars_avail, k;
176  char input;
177#if defined(HAVE_SELECT)
178  fd_set readfds, exceptfds;
179  struct timeval timeout;
180#endif
181
182  tty = fileno (rl_instream);
183
184#if defined (HAVE_SELECT)
185  FD_ZERO (&readfds);
186  FD_ZERO (&exceptfds);
187  FD_SET (tty, &readfds);
188  FD_SET (tty, &exceptfds);
189  timeout.tv_sec = 0;
190  timeout.tv_usec = _keyboard_input_timeout;
191  result = select (tty + 1, &readfds, (fd_set *)NULL, &exceptfds, &timeout);
192  if (result <= 0)
193    return 0;	/* Nothing to read. */
194#endif
195
196  result = -1;
197#if defined (FIONREAD)
198  errno = 0;
199  result = ioctl (tty, FIONREAD, &chars_avail);
200  if (result == -1 && errno == EIO)
201    return -1;
202#endif
203
204#if defined (O_NDELAY)
205  if (result == -1)
206    {
207      tem = fcntl (tty, F_GETFL, 0);
208
209      fcntl (tty, F_SETFL, (tem | O_NDELAY));
210      chars_avail = read (tty, &input, 1);
211
212      fcntl (tty, F_SETFL, tem);
213      if (chars_avail == -1 && errno == EAGAIN)
214	return 0;
215      if (chars_avail == 0)	/* EOF */
216	{
217	  rl_stuff_char (EOF);
218	  return (0);
219	}
220    }
221#endif /* O_NDELAY */
222
223#if defined (__MINGW32__)
224  /* We use getch to read console input, so use the same
225     mechanism to check for more.  Otherwise, we don't know.  */
226  if (isatty (fileno (rl_instream)))
227    chars_avail = _kbhit ();
228  else
229    chars_avail = 0;
230  result = 0;
231#endif
232
233  /* If there's nothing available, don't waste time trying to read
234     something. */
235  if (chars_avail <= 0)
236    return 0;
237
238  tem = ibuffer_space ();
239
240  if (chars_avail > tem)
241    chars_avail = tem;
242
243  /* One cannot read all of the available input.  I can only read a single
244     character at a time, or else programs which require input can be
245     thwarted.  If the buffer is larger than one character, I lose.
246     Damn! */
247  if (tem < ibuffer_len)
248    chars_avail = 0;
249
250  if (result != -1)
251    {
252      while (chars_avail--)
253	{
254	  k = (*rl_getc_function) (rl_instream);
255	  rl_stuff_char (k);
256	  if (k == NEWLINE || k == RETURN)
257	    break;
258	}
259    }
260  else
261    {
262      if (chars_avail)
263	rl_stuff_char (input);
264    }
265
266  return 1;
267}
268
269int
270rl_set_keyboard_input_timeout (u)
271     int u;
272{
273  int o;
274
275  o = _keyboard_input_timeout;
276  if (u > 0)
277    _keyboard_input_timeout = u;
278  return (o);
279}
280
281/* Is there input available to be read on the readline input file
282   descriptor?  Only works if the system has select(2) or FIONREAD.
283   Uses the value of _keyboard_input_timeout as the timeout; if another
284   readline function wants to specify a timeout and not leave it up to
285   the user, it should use _rl_input_queued(timeout_value_in_microseconds)
286   instead. */
287int
288_rl_input_available ()
289{
290#if defined(HAVE_SELECT)
291  fd_set readfds, exceptfds;
292  struct timeval timeout;
293#endif
294#if !defined (HAVE_SELECT) && defined(FIONREAD)
295  int chars_avail;
296#endif
297  int tty;
298
299  tty = fileno (rl_instream);
300
301#if defined (HAVE_SELECT)
302  FD_ZERO (&readfds);
303  FD_ZERO (&exceptfds);
304  FD_SET (tty, &readfds);
305  FD_SET (tty, &exceptfds);
306  timeout.tv_sec = 0;
307  timeout.tv_usec = _keyboard_input_timeout;
308  return (select (tty + 1, &readfds, (fd_set *)NULL, &exceptfds, &timeout) > 0);
309#else
310
311#if defined (FIONREAD)
312  if (ioctl (tty, FIONREAD, &chars_avail) == 0)
313    return (chars_avail);
314#endif
315
316#endif
317
318#if defined (__MINGW32__)
319  /* We use getch to read console input, so use the same
320     mechanism to check for more.  Otherwise, we don't know.  */
321  if (isatty (fileno (rl_instream)))
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 (push_index >= ibuffer_len)
381    push_index = 0;
382
383  return 1;
384}
385
386/* Make C be the next command to be executed. */
387int
388rl_execute_next (c)
389     int c;
390{
391  rl_pending_input = c;
392  RL_SETSTATE (RL_STATE_INPUTPENDING);
393  return 0;
394}
395
396/* Clear any pending input pushed with rl_execute_next() */
397int
398rl_clear_pending_input ()
399{
400  rl_pending_input = 0;
401  RL_UNSETSTATE (RL_STATE_INPUTPENDING);
402  return 0;
403}
404
405/* **************************************************************** */
406/*								    */
407/*			     Character Input			    */
408/*								    */
409/* **************************************************************** */
410
411/* Read a key, including pending input. */
412int
413rl_read_key ()
414{
415  int c;
416
417  rl_key_sequence_length++;
418
419  if (rl_pending_input)
420    {
421      c = rl_pending_input;
422      rl_clear_pending_input ();
423    }
424  else
425    {
426      /* If input is coming from a macro, then use that. */
427      if (c = _rl_next_macro_key ())
428	return (c);
429
430      /* If the user has an event function, then call it periodically. */
431      if (rl_event_hook)
432	{
433	  while (rl_event_hook && rl_get_char (&c) == 0)
434	    {
435	      (*rl_event_hook) ();
436	      if (rl_done)		/* XXX - experimental */
437		return ('\n');
438	      if (rl_gather_tyi () < 0)	/* XXX - EIO */
439		{
440		  rl_done = 1;
441		  return ('\n');
442		}
443	    }
444	}
445      else
446	{
447	  if (rl_get_char (&c) == 0)
448	    c = (*rl_getc_function) (rl_instream);
449	}
450    }
451
452  return (c);
453}
454
455int
456rl_getc (stream)
457     FILE *stream;
458{
459  int result;
460  unsigned char c;
461
462  while (1)
463    {
464#if defined (__MINGW32__)
465      if (isatty (fileno (stream)))
466	return (getch ());
467#endif
468      result = read (fileno (stream), &c, sizeof (unsigned char));
469
470      if (result == sizeof (unsigned char))
471	return (c);
472
473      /* If zero characters are returned, then the file that we are
474	 reading from is empty!  Return EOF in that case. */
475      if (result == 0)
476	return (EOF);
477
478#if defined (__BEOS__)
479      if (errno == EINTR)
480	continue;
481#endif
482
483#if defined (EWOULDBLOCK)
484#  define X_EWOULDBLOCK EWOULDBLOCK
485#else
486#  define X_EWOULDBLOCK -99
487#endif
488
489#if defined (EAGAIN)
490#  define X_EAGAIN EAGAIN
491#else
492#  define X_EAGAIN -99
493#endif
494
495      if (errno == X_EWOULDBLOCK || errno == X_EAGAIN)
496	{
497	  if (sh_unset_nodelay_mode (fileno (stream)) < 0)
498	    return (EOF);
499	  continue;
500	}
501
502#undef X_EWOULDBLOCK
503#undef X_EAGAIN
504
505      /* If the error that we received was SIGINT, then try again,
506	 this is simply an interrupted system call to read ().
507	 Otherwise, some error ocurred, also signifying EOF. */
508      if (errno != EINTR)
509	return (EOF);
510    }
511}
512
513#if defined (HANDLE_MULTIBYTE)
514/* read multibyte char */
515int
516_rl_read_mbchar (mbchar, size)
517     char *mbchar;
518     int size;
519{
520  int mb_len = 0;
521  size_t mbchar_bytes_length;
522  wchar_t wc;
523  mbstate_t ps, ps_back;
524
525  memset(&ps, 0, sizeof (mbstate_t));
526  memset(&ps_back, 0, sizeof (mbstate_t));
527
528  while (mb_len < size)
529    {
530      RL_SETSTATE(RL_STATE_MOREINPUT);
531      mbchar[mb_len++] = rl_read_key ();
532      RL_UNSETSTATE(RL_STATE_MOREINPUT);
533
534      mbchar_bytes_length = mbrtowc (&wc, mbchar, mb_len, &ps);
535      if (mbchar_bytes_length == (size_t)(-1))
536	break;		/* invalid byte sequence for the current locale */
537      else if (mbchar_bytes_length == (size_t)(-2))
538	{
539	  /* shorted bytes */
540	  ps = ps_back;
541	  continue;
542	}
543      else if (mbchar_bytes_length == 0)
544	{
545	  mbchar[0] = '\0';	/* null wide character */
546	  mb_len = 1;
547	  break;
548	}
549      else if (mbchar_bytes_length > (size_t)(0))
550	break;
551    }
552
553  return mb_len;
554}
555
556/* Read a multibyte-character string whose first character is FIRST into
557   the buffer MB of length MBLEN.  Returns the last character read, which
558   may be FIRST.  Used by the search functions, among others.  Very similar
559   to _rl_read_mbchar. */
560int
561_rl_read_mbstring (first, mb, mblen)
562     int first;
563     char *mb;
564     int mblen;
565{
566  int i, c;
567  mbstate_t ps;
568
569  c = first;
570  memset (mb, 0, mblen);
571  for (i = 0; i < mblen; i++)
572    {
573      mb[i] = (char)c;
574      memset (&ps, 0, sizeof (mbstate_t));
575      if (_rl_get_char_len (mb, &ps) == -2)
576	{
577	  /* Read more for multibyte character */
578	  RL_SETSTATE (RL_STATE_MOREINPUT);
579	  c = rl_read_key ();
580	  RL_UNSETSTATE (RL_STATE_MOREINPUT);
581	}
582      else
583	break;
584    }
585  return c;
586}
587#endif /* HANDLE_MULTIBYTE */
588