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
157/* If a character is available to be read, then read it and stuff it into
158   IBUFFER.  Otherwise, just return.  Returns number of characters read
159   (0 if none available) and -1 on error (EIO). */
160static int
161rl_gather_tyi ()
162{
163  int tty;
164  register int tem, result;
165  int chars_avail;
166  char input;
167#if defined(HAVE_SELECT)
168  fd_set readfds, exceptfds;
169  struct timeval timeout;
170#endif
171
172  tty = fileno (rl_instream);
173
174#if defined (HAVE_SELECT)
175  FD_ZERO (&readfds);
176  FD_ZERO (&exceptfds);
177  FD_SET (tty, &readfds);
178  FD_SET (tty, &exceptfds);
179  timeout.tv_sec = 0;
180  timeout.tv_usec = _keyboard_input_timeout;
181  result = select (tty + 1, &readfds, (fd_set *)NULL, &exceptfds, &timeout);
182  if (result <= 0)
183    return 0;	/* Nothing to read. */
184#endif
185
186  result = -1;
187#if defined (FIONREAD)
188  errno = 0;
189  result = ioctl (tty, FIONREAD, &chars_avail);
190  if (result == -1 && errno == EIO)
191    return -1;
192#endif
193
194#if defined (O_NDELAY)
195  if (result == -1)
196    {
197      tem = fcntl (tty, F_GETFL, 0);
198
199      fcntl (tty, F_SETFL, (tem | O_NDELAY));
200      chars_avail = read (tty, &input, 1);
201
202      fcntl (tty, F_SETFL, tem);
203      if (chars_avail == -1 && errno == EAGAIN)
204	return 0;
205    }
206#endif /* O_NDELAY */
207
208  /* If there's nothing available, don't waste time trying to read
209     something. */
210  if (chars_avail <= 0)
211    return 0;
212
213  tem = ibuffer_space ();
214
215  if (chars_avail > tem)
216    chars_avail = tem;
217
218  /* One cannot read all of the available input.  I can only read a single
219     character at a time, or else programs which require input can be
220     thwarted.  If the buffer is larger than one character, I lose.
221     Damn! */
222  if (tem < ibuffer_len)
223    chars_avail = 0;
224
225  if (result != -1)
226    {
227      while (chars_avail--)
228	rl_stuff_char ((*rl_getc_function) (rl_instream));
229    }
230  else
231    {
232      if (chars_avail)
233	rl_stuff_char (input);
234    }
235
236  return 1;
237}
238
239int
240rl_set_keyboard_input_timeout (u)
241     int u;
242{
243  int o;
244
245  o = _keyboard_input_timeout;
246  if (u > 0)
247    _keyboard_input_timeout = u;
248  return (o);
249}
250
251/* Is there input available to be read on the readline input file
252   descriptor?  Only works if the system has select(2) or FIONREAD.
253   Uses the value of _keyboard_input_timeout as the timeout; if another
254   readline function wants to specify a timeout and not leave it up to
255   the user, it should use _rl_input_queued(timeout_value_in_microseconds)
256   instead. */
257int
258_rl_input_available ()
259{
260#if defined(HAVE_SELECT)
261  fd_set readfds, exceptfds;
262  struct timeval timeout;
263#endif
264#if !defined (HAVE_SELECT) && defined(FIONREAD)
265  int chars_avail;
266#endif
267  int tty;
268
269  tty = fileno (rl_instream);
270
271#if defined (HAVE_SELECT)
272  FD_ZERO (&readfds);
273  FD_ZERO (&exceptfds);
274  FD_SET (tty, &readfds);
275  FD_SET (tty, &exceptfds);
276  timeout.tv_sec = 0;
277  timeout.tv_usec = _keyboard_input_timeout;
278  return (select (tty + 1, &readfds, (fd_set *)NULL, &exceptfds, &timeout) > 0);
279#else
280
281#if defined (FIONREAD)
282  if (ioctl (tty, FIONREAD, &chars_avail) == 0)
283    return (chars_avail);
284#endif
285
286#endif
287
288  return 0;
289}
290
291int
292_rl_input_queued (t)
293     int t;
294{
295  int old_timeout, r;
296
297  old_timeout = rl_set_keyboard_input_timeout (t);
298  r = _rl_input_available ();
299  rl_set_keyboard_input_timeout (old_timeout);
300  return r;
301}
302
303void
304_rl_insert_typein (c)
305     int c;
306{
307  int key, t, i;
308  char *string;
309
310  i = key = 0;
311  string = (char *)xmalloc (ibuffer_len + 1);
312  string[i++] = (char) c;
313
314  while ((t = rl_get_char (&key)) &&
315	 _rl_keymap[key].type == ISFUNC &&
316	 _rl_keymap[key].function == rl_insert)
317    string[i++] = key;
318
319  if (t)
320    _rl_unget_char (key);
321
322  string[i] = '\0';
323  rl_insert_text (string);
324  free (string);
325}
326
327/* Add KEY to the buffer of characters to be read.  Returns 1 if the
328   character was stuffed correctly; 0 otherwise. */
329int
330rl_stuff_char (key)
331     int key;
332{
333  if (ibuffer_space () == 0)
334    return 0;
335
336  if (key == EOF)
337    {
338      key = NEWLINE;
339      rl_pending_input = EOF;
340      RL_SETSTATE (RL_STATE_INPUTPENDING);
341    }
342  ibuffer[push_index++] = key;
343  if (push_index >= ibuffer_len)
344    push_index = 0;
345
346  return 1;
347}
348
349/* Make C be the next command to be executed. */
350int
351rl_execute_next (c)
352     int c;
353{
354  rl_pending_input = c;
355  RL_SETSTATE (RL_STATE_INPUTPENDING);
356  return 0;
357}
358
359/* Clear any pending input pushed with rl_execute_next() */
360int
361rl_clear_pending_input ()
362{
363  rl_pending_input = 0;
364  RL_UNSETSTATE (RL_STATE_INPUTPENDING);
365  return 0;
366}
367
368/* **************************************************************** */
369/*								    */
370/*			     Character Input			    */
371/*								    */
372/* **************************************************************** */
373
374/* Read a key, including pending input. */
375int
376rl_read_key ()
377{
378  int c;
379
380  rl_key_sequence_length++;
381
382  if (rl_pending_input)
383    {
384      c = rl_pending_input;
385      rl_clear_pending_input ();
386    }
387  else
388    {
389      /* If input is coming from a macro, then use that. */
390      if (c = _rl_next_macro_key ())
391	return (c);
392
393      /* If the user has an event function, then call it periodically. */
394      if (rl_event_hook)
395	{
396	  while (rl_event_hook && rl_get_char (&c) == 0)
397	    {
398	      (*rl_event_hook) ();
399	      if (rl_done)		/* XXX - experimental */
400		return ('\n');
401	      if (rl_gather_tyi () < 0)	/* XXX - EIO */
402		{
403		  rl_done = 1;
404		  return ('\n');
405		}
406	    }
407	}
408      else
409	{
410	  if (rl_get_char (&c) == 0)
411	    c = (*rl_getc_function) (rl_instream);
412	}
413    }
414
415  return (c);
416}
417
418int
419rl_getc (stream)
420     FILE *stream;
421{
422  int result;
423  unsigned char c;
424
425  while (1)
426    {
427      result = read (fileno (stream), &c, sizeof (unsigned char));
428
429      if (result == sizeof (unsigned char))
430	return (c);
431
432      /* If zero characters are returned, then the file that we are
433	 reading from is empty!  Return EOF in that case. */
434      if (result == 0)
435	return (EOF);
436
437#if (defined(__BEOS__) || defined(__HAIKU__))
438      if (errno == EINTR)
439	continue;
440#endif
441
442#if defined (EWOULDBLOCK)
443#  define X_EWOULDBLOCK EWOULDBLOCK
444#else
445#  define X_EWOULDBLOCK -99
446#endif
447
448#if defined (EAGAIN)
449#  define X_EAGAIN EAGAIN
450#else
451#  define X_EAGAIN -99
452#endif
453
454      if (errno == X_EWOULDBLOCK || errno == X_EAGAIN)
455	{
456	  if (sh_unset_nodelay_mode (fileno (stream)) < 0)
457	    return (EOF);
458	  continue;
459	}
460
461#undef X_EWOULDBLOCK
462#undef X_EAGAIN
463
464      /* If the error that we received was SIGINT, then try again,
465	 this is simply an interrupted system call to read ().
466	 Otherwise, some error ocurred, also signifying EOF. */
467      if (errno != EINTR)
468	return (EOF);
469    }
470}
471
472#if defined (HANDLE_MULTIBYTE)
473/* read multibyte char */
474int
475_rl_read_mbchar (mbchar, size)
476     char *mbchar;
477     int size;
478{
479  int mb_len = 0;
480  size_t mbchar_bytes_length;
481  wchar_t wc;
482  mbstate_t ps, ps_back;
483
484  memset(&ps, 0, sizeof (mbstate_t));
485  memset(&ps_back, 0, sizeof (mbstate_t));
486
487  while (mb_len < size)
488    {
489      RL_SETSTATE(RL_STATE_MOREINPUT);
490      mbchar[mb_len++] = rl_read_key ();
491      RL_UNSETSTATE(RL_STATE_MOREINPUT);
492
493      mbchar_bytes_length = mbrtowc (&wc, mbchar, mb_len, &ps);
494      if (mbchar_bytes_length == (size_t)(-1))
495	break;		/* invalid byte sequence for the current locale */
496      else if (mbchar_bytes_length == (size_t)(-2))
497	{
498	  /* shorted bytes */
499	  ps = ps_back;
500	  continue;
501	}
502      else if (mbchar_bytes_length > (size_t)(0))
503	break;
504    }
505
506  return mb_len;
507}
508
509/* Read a multibyte-character string whose first character is FIRST into
510   the buffer MB of length MBLEN.  Returns the last character read, which
511   may be FIRST.  Used by the search functions, among others.  Very similar
512   to _rl_read_mbchar. */
513int
514_rl_read_mbstring (first, mb, mblen)
515     int first;
516     char *mb;
517     int mblen;
518{
519  int i, c;
520  mbstate_t ps;
521
522  c = first;
523  memset (mb, 0, mblen);
524  for (i = 0; i < mblen; i++)
525    {
526      mb[i] = (char)c;
527      memset (&ps, 0, sizeof (mbstate_t));
528      if (_rl_get_char_len (mb, &ps) == -2)
529	{
530	  /* Read more for multibyte character */
531	  RL_SETSTATE (RL_STATE_MOREINPUT);
532	  c = rl_read_key ();
533	  RL_UNSETSTATE (RL_STATE_MOREINPUT);
534	}
535      else
536	break;
537    }
538  return c;
539}
540#endif /* HANDLE_MULTIBYTE */
541