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