Ruby  2.7.1p83(2020-03-31revisiona0c7c23c9cec0d0ffcba012279cd652d28ad5bf3)
console.c
Go to the documentation of this file.
1 /* -*- c-file-style: "ruby" -*- */
2 /*
3  * console IO module
4  */
5 #include "ruby.h"
6 #include "ruby/io.h"
7 #include "ruby/thread.h"
8 
9 #ifdef HAVE_UNISTD_H
10 #include <unistd.h>
11 #endif
12 #ifdef HAVE_FCNTL_H
13 #include <fcntl.h>
14 #endif
15 #ifdef HAVE_SYS_IOCTL_H
16 #include <sys/ioctl.h>
17 #endif
18 
19 #if defined HAVE_TERMIOS_H
20 # include <termios.h>
21 typedef struct termios conmode;
22 
23 static int
24 setattr(int fd, conmode *t)
25 {
26  while (tcsetattr(fd, TCSANOW, t)) {
27  if (errno != EINTR) return 0;
28  }
29  return 1;
30 }
31 # define getattr(fd, t) (tcgetattr(fd, t) == 0)
32 #elif defined HAVE_TERMIO_H
33 # include <termio.h>
34 typedef struct termio conmode;
35 # define setattr(fd, t) (ioctl(fd, TCSETAF, t) == 0)
36 # define getattr(fd, t) (ioctl(fd, TCGETA, t) == 0)
37 #elif defined HAVE_SGTTY_H
38 # include <sgtty.h>
39 typedef struct sgttyb conmode;
40 # ifdef HAVE_STTY
41 # define setattr(fd, t) (stty(fd, t) == 0)
42 # else
43 # define setattr(fd, t) (ioctl((fd), TIOCSETP, (t)) == 0)
44 # endif
45 # ifdef HAVE_GTTY
46 # define getattr(fd, t) (gtty(fd, t) == 0)
47 # else
48 # define getattr(fd, t) (ioctl((fd), TIOCGETP, (t)) == 0)
49 # endif
50 #elif defined _WIN32
51 #include <winioctl.h>
52 #include <conio.h>
53 typedef DWORD conmode;
54 
55 #define LAST_ERROR rb_w32_map_errno(GetLastError())
56 #define SET_LAST_ERROR (errno = LAST_ERROR, 0)
57 
58 static int
59 setattr(int fd, conmode *t)
60 {
61  int x = SetConsoleMode((HANDLE)rb_w32_get_osfhandle(fd), *t);
62  if (!x) errno = LAST_ERROR;
63  return x;
64 }
65 
66 static int
67 getattr(int fd, conmode *t)
68 {
69  int x = GetConsoleMode((HANDLE)rb_w32_get_osfhandle(fd), t);
70  if (!x) errno = LAST_ERROR;
71  return x;
72 }
73 #endif
74 #ifndef SET_LAST_ERROR
75 #define SET_LAST_ERROR (0)
76 #endif
77 
78 static ID id_getc, id_console, id_close, id_min, id_time, id_intr;
79 #if ENABLE_IO_GETPASS
80 static ID id_gets;
81 #endif
82 
83 #ifndef HAVE_RB_F_SEND
84 static ID id___send__;
85 
86 static VALUE
87 rb_f_send(int argc, VALUE *argv, VALUE recv)
88 {
89  VALUE sym = argv[0];
90  ID vid = rb_check_id(&sym);
91  if (vid) {
92  --argc;
93  ++argv;
94  }
95  else {
96  vid = id___send__;
97  }
98  return rb_funcallv(recv, vid, argc, argv);
99 }
100 #endif
101 
102 typedef struct {
103  int vmin;
104  int vtime;
105  int intr;
106 } rawmode_arg_t;
107 
108 static rawmode_arg_t *
109 rawmode_opt(int *argcp, VALUE *argv, int min_argc, int max_argc, rawmode_arg_t *opts)
110 {
111  int argc = *argcp;
112  rawmode_arg_t *optp = NULL;
113  VALUE vopts = Qnil;
114 #ifdef RB_SCAN_ARGS_PASS_CALLED_KEYWORDS
115  argc = rb_scan_args(argc, argv, "*:", NULL, &vopts);
116 #else
117  if (argc > min_argc) {
118  vopts = rb_check_hash_type(argv[argc-1]);
119  if (!NIL_P(vopts)) {
120  argv[argc-1] = vopts;
121  vopts = rb_extract_keywords(&argv[argc-1]);
122  if (!argv[argc-1]) *argcp = --argc;
123  if (!vopts) vopts = Qnil;
124  }
125  }
126 #endif
128  if (!NIL_P(vopts)) {
129  VALUE vmin = rb_hash_aref(vopts, ID2SYM(id_min));
130  VALUE vtime = rb_hash_aref(vopts, ID2SYM(id_time));
131  VALUE intr = rb_hash_aref(vopts, ID2SYM(id_intr));
132  /* default values by `stty raw` */
133  opts->vmin = 1;
134  opts->vtime = 0;
135  opts->intr = 0;
136  if (!NIL_P(vmin)) {
137  opts->vmin = NUM2INT(vmin);
138  optp = opts;
139  }
140  if (!NIL_P(vtime)) {
141  VALUE v10 = INT2FIX(10);
142  vtime = rb_funcall3(vtime, '*', 1, &v10);
143  opts->vtime = NUM2INT(vtime);
144  optp = opts;
145  }
146  switch (intr) {
147  case Qtrue:
148  opts->intr = 1;
149  optp = opts;
150  break;
151  case Qfalse:
152  opts->intr = 0;
153  optp = opts;
154  break;
155  case Qnil:
156  break;
157  default:
158  rb_raise(rb_eArgError, "true or false expected as intr: %"PRIsVALUE,
159  intr);
160  }
161  }
162  return optp;
163 }
164 
165 static void
166 set_rawmode(conmode *t, void *arg)
167 {
168 #ifdef HAVE_CFMAKERAW
169  cfmakeraw(t);
170  t->c_lflag &= ~(ECHOE|ECHOK);
171 #elif defined HAVE_TERMIOS_H || defined HAVE_TERMIO_H
172  t->c_iflag &= ~(IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK|ISTRIP|INLCR|IGNCR|ICRNL|IXON|IXOFF|IXANY|IMAXBEL);
173  t->c_oflag &= ~OPOST;
174  t->c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHONL|ICANON|ISIG|IEXTEN|XCASE);
175  t->c_cflag &= ~(CSIZE|PARENB);
176  t->c_cflag |= CS8;
177  t->c_cc[VMIN] = 1;
178  t->c_cc[VTIME] = 0;
179 #elif defined HAVE_SGTTY_H
180  t->sg_flags &= ~ECHO;
181  t->sg_flags |= RAW;
182 #elif defined _WIN32
183  *t = 0;
184 #endif
185  if (arg) {
186  const rawmode_arg_t *r = arg;
187 #ifdef VMIN
188  if (r->vmin >= 0) t->c_cc[VMIN] = r->vmin;
189 #endif
190 #ifdef VTIME
191  if (r->vtime >= 0) t->c_cc[VTIME] = r->vtime;
192 #endif
193 #ifdef ISIG
194  if (r->intr) {
195  t->c_iflag |= BRKINT;
196  t->c_lflag |= ISIG;
197  t->c_oflag |= OPOST;
198  }
199 #endif
200  (void)r;
201  }
202 }
203 
204 static void
205 set_cookedmode(conmode *t, void *arg)
206 {
207 #if defined HAVE_TERMIOS_H || defined HAVE_TERMIO_H
208  t->c_iflag |= (BRKINT|ISTRIP|ICRNL|IXON);
209  t->c_oflag |= OPOST;
210  t->c_lflag |= (ECHO|ECHOE|ECHOK|ECHONL|ICANON|ISIG|IEXTEN);
211 #elif defined HAVE_SGTTY_H
212  t->sg_flags |= ECHO;
213  t->sg_flags &= ~RAW;
214 #elif defined _WIN32
215  *t |= ENABLE_ECHO_INPUT|ENABLE_LINE_INPUT|ENABLE_PROCESSED_INPUT;
216 #endif
217 }
218 
219 static void
220 set_noecho(conmode *t, void *arg)
221 {
222 #if defined HAVE_TERMIOS_H || defined HAVE_TERMIO_H
223  t->c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
224 #elif defined HAVE_SGTTY_H
225  t->sg_flags &= ~ECHO;
226 #elif defined _WIN32
227  *t &= ~ENABLE_ECHO_INPUT;
228 #endif
229 }
230 
231 static void
232 set_echo(conmode *t, void *arg)
233 {
234 #if defined HAVE_TERMIOS_H || defined HAVE_TERMIO_H
235  t->c_lflag |= (ECHO | ECHOE | ECHOK | ECHONL);
236 #elif defined HAVE_SGTTY_H
237  t->sg_flags |= ECHO;
238 #elif defined _WIN32
239  *t |= ENABLE_ECHO_INPUT;
240 #endif
241 }
242 
243 static int
244 echo_p(conmode *t)
245 {
246 #if defined HAVE_TERMIOS_H || defined HAVE_TERMIO_H
247  return (t->c_lflag & (ECHO | ECHONL)) != 0;
248 #elif defined HAVE_SGTTY_H
249  return (t->sg_flags & ECHO) != 0;
250 #elif defined _WIN32
251  return (*t & ENABLE_ECHO_INPUT) != 0;
252 #endif
253 }
254 
255 static int
256 set_ttymode(int fd, conmode *t, void (*setter)(conmode *, void *), void *arg)
257 {
258  conmode r;
259  if (!getattr(fd, t)) return 0;
260  r = *t;
261  setter(&r, arg);
262  return setattr(fd, &r);
263 }
264 
265 #define GetReadFD(fptr) ((fptr)->fd)
266 
267 static inline int
268 get_write_fd(const rb_io_t *fptr)
269 {
270  VALUE wio = fptr->tied_io_for_writing;
271  rb_io_t *ofptr;
272  if (!wio) return fptr->fd;
273  GetOpenFile(wio, ofptr);
274  return ofptr->fd;
275 }
276 #define GetWriteFD(fptr) get_write_fd(fptr)
277 
278 #define FD_PER_IO 2
279 
280 static VALUE
281 ttymode(VALUE io, VALUE (*func)(VALUE), VALUE farg, void (*setter)(conmode *, void *), void *arg)
282 {
283  rb_io_t *fptr;
284  int status = -1;
285  int error = 0;
286  int fd[FD_PER_IO];
287  conmode t[FD_PER_IO];
288  VALUE result = Qnil;
289 
290  GetOpenFile(io, fptr);
291  fd[0] = GetReadFD(fptr);
292  if (fd[0] != -1) {
293  if (set_ttymode(fd[0], t+0, setter, arg)) {
294  status = 0;
295  }
296  else {
297  error = errno;
298  fd[0] = -1;
299  }
300  }
301  fd[1] = GetWriteFD(fptr);
302  if (fd[1] != -1 && fd[1] != fd[0]) {
303  if (set_ttymode(fd[1], t+1, setter, arg)) {
304  status = 0;
305  }
306  else {
307  error = errno;
308  fd[1] = -1;
309  }
310  }
311  if (status == 0) {
312  result = rb_protect(func, farg, &status);
313  }
314  GetOpenFile(io, fptr);
315  if (fd[0] != -1 && fd[0] == GetReadFD(fptr)) {
316  if (!setattr(fd[0], t+0)) {
317  error = errno;
318  status = -1;
319  }
320  }
321  if (fd[1] != -1 && fd[1] != fd[0] && fd[1] == GetWriteFD(fptr)) {
322  if (!setattr(fd[1], t+1)) {
323  error = errno;
324  status = -1;
325  }
326  }
327  if (status) {
328  if (status == -1) {
329  rb_syserr_fail(error, 0);
330  }
331  rb_jump_tag(status);
332  }
333  return result;
334 }
335 
336 #if !defined _WIN32
341 };
342 
343 static VALUE
344 ttymode_callback(VALUE args)
345 {
346  struct ttymode_callback_args *argp = (struct ttymode_callback_args *)args;
347  return argp->func(argp->io, argp->farg);
348 }
349 
350 static VALUE
351 ttymode_with_io(VALUE io, VALUE (*func)(VALUE, VALUE), VALUE farg, void (*setter)(conmode *, void *), void *arg)
352 {
353  struct ttymode_callback_args cargs;
354  cargs.func = func;
355  cargs.io = io;
356  cargs.farg = farg;
357  return ttymode(io, ttymode_callback, (VALUE)&cargs, setter, arg);
358 }
359 #endif
360 
361 /*
362  * call-seq:
363  * io.raw(min: nil, time: nil, intr: nil) {|io| }
364  *
365  * Yields +self+ within raw mode, and returns the result of the block.
366  *
367  * STDIN.raw(&:gets)
368  *
369  * will read and return a line without echo back and line editing.
370  *
371  * The parameter +min+ specifies the minimum number of bytes that
372  * should be received when a read operation is performed. (default: 1)
373  *
374  * The parameter +time+ specifies the timeout in _seconds_ with a
375  * precision of 1/10 of a second. (default: 0)
376  *
377  * If the parameter +intr+ is +true+, enables break, interrupt, quit,
378  * and suspend special characters.
379  *
380  * Refer to the manual page of termios for further details.
381  *
382  * You must require 'io/console' to use this method.
383  */
384 static VALUE
385 console_raw(int argc, VALUE *argv, VALUE io)
386 {
387  rawmode_arg_t opts, *optp = rawmode_opt(&argc, argv, 0, 0, &opts);
388  return ttymode(io, rb_yield, io, set_rawmode, optp);
389 }
390 
391 /*
392  * call-seq:
393  * io.raw!(min: nil, time: nil, intr: nil) -> io
394  *
395  * Enables raw mode, and returns +io+.
396  *
397  * If the terminal mode needs to be back, use <code>io.raw { ... }</code>.
398  *
399  * See IO#raw for details on the parameters.
400  *
401  * You must require 'io/console' to use this method.
402  */
403 static VALUE
404 console_set_raw(int argc, VALUE *argv, VALUE io)
405 {
406  conmode t;
407  rb_io_t *fptr;
408  int fd;
409  rawmode_arg_t opts, *optp = rawmode_opt(&argc, argv, 0, 0, &opts);
410 
411  GetOpenFile(io, fptr);
412  fd = GetReadFD(fptr);
413  if (!getattr(fd, &t)) rb_sys_fail(0);
414  set_rawmode(&t, optp);
415  if (!setattr(fd, &t)) rb_sys_fail(0);
416  return io;
417 }
418 
419 /*
420  * call-seq:
421  * io.cooked {|io| }
422  *
423  * Yields +self+ within cooked mode.
424  *
425  * STDIN.cooked(&:gets)
426  *
427  * will read and return a line with echo back and line editing.
428  *
429  * You must require 'io/console' to use this method.
430  */
431 static VALUE
432 console_cooked(VALUE io)
433 {
434  return ttymode(io, rb_yield, io, set_cookedmode, NULL);
435 }
436 
437 /*
438  * call-seq:
439  * io.cooked!
440  *
441  * Enables cooked mode.
442  *
443  * If the terminal mode needs to be back, use io.cooked { ... }.
444  *
445  * You must require 'io/console' to use this method.
446  */
447 static VALUE
448 console_set_cooked(VALUE io)
449 {
450  conmode t;
451  rb_io_t *fptr;
452  int fd;
453 
454  GetOpenFile(io, fptr);
455  fd = GetReadFD(fptr);
456  if (!getattr(fd, &t)) rb_sys_fail(0);
457  set_cookedmode(&t, NULL);
458  if (!setattr(fd, &t)) rb_sys_fail(0);
459  return io;
460 }
461 
462 #ifndef _WIN32
463 static VALUE
464 getc_call(VALUE io)
465 {
466  return rb_funcallv(io, id_getc, 0, 0);
467 }
468 #else
469 static void *
470 nogvl_getch(void *p)
471 {
472  int len = 0;
473  wint_t *buf = p, c = _getwch();
474 
475  switch (c) {
476  case WEOF:
477  break;
478  case 0x00:
479  case 0xe0:
480  buf[len++] = c;
481  c = _getwch();
482  /* fall through */
483  default:
484  buf[len++] = c;
485  break;
486  }
487  return (void *)(VALUE)len;
488 }
489 #endif
490 
491 /*
492  * call-seq:
493  * io.getch(min: nil, time: nil, intr: nil) -> char
494  *
495  * Reads and returns a character in raw mode.
496  *
497  * See IO#raw for details on the parameters.
498  *
499  * You must require 'io/console' to use this method.
500  */
501 static VALUE
502 console_getch(int argc, VALUE *argv, VALUE io)
503 {
504  rawmode_arg_t opts, *optp = rawmode_opt(&argc, argv, 0, 0, &opts);
505 #ifndef _WIN32
506  return ttymode(io, getc_call, io, set_rawmode, optp);
507 #else
508  rb_io_t *fptr;
509  VALUE str;
510  wint_t c;
511  int w, len;
512  char buf[8];
513  wint_t wbuf[2];
514  struct timeval *to = NULL, tv;
515 
516  GetOpenFile(io, fptr);
517  if (optp) {
518  if (optp->vtime) {
519  to = &tv;
520  tv.tv_sec = optp->vtime / 10;
521  tv.tv_usec = (optp->vtime % 10) * 100000;
522  }
523  if (optp->vmin != 1) {
524  rb_warning("min option ignored");
525  }
526  if (optp->intr) {
527  w = rb_wait_for_single_fd(fptr->fd, RB_WAITFD_IN, to);
528  if (w < 0) rb_eof_error();
529  if (!(w & RB_WAITFD_IN)) return Qnil;
530  }
531  else {
532  rb_warning("vtime option ignored if intr flag is unset");
533  }
534  }
535  len = (int)(VALUE)rb_thread_call_without_gvl(nogvl_getch, wbuf, RUBY_UBF_IO, 0);
536  switch (len) {
537  case 0:
538  return Qnil;
539  case 2:
540  buf[0] = (char)wbuf[0];
541  c = wbuf[1];
542  len = 1;
543  do {
544  buf[len++] = (unsigned char)c;
545  } while ((c >>= CHAR_BIT) && len < (int)sizeof(buf));
546  return rb_str_new(buf, len);
547  default:
548  c = wbuf[0];
549  len = rb_uv_to_utf8(buf, c);
552  }
553 #endif
554 }
555 
556 /*
557  * call-seq:
558  * io.noecho {|io| }
559  *
560  * Yields +self+ with disabling echo back.
561  *
562  * STDIN.noecho(&:gets)
563  *
564  * will read and return a line without echo back.
565  *
566  * You must require 'io/console' to use this method.
567  */
568 static VALUE
569 console_noecho(VALUE io)
570 {
571  return ttymode(io, rb_yield, io, set_noecho, NULL);
572 }
573 
574 /*
575  * call-seq:
576  * io.echo = flag
577  *
578  * Enables/disables echo back.
579  * On some platforms, all combinations of this flags and raw/cooked
580  * mode may not be valid.
581  *
582  * You must require 'io/console' to use this method.
583  */
584 static VALUE
585 console_set_echo(VALUE io, VALUE f)
586 {
587  conmode t;
588  rb_io_t *fptr;
589  int fd;
590 
591  GetOpenFile(io, fptr);
592  fd = GetReadFD(fptr);
593  if (!getattr(fd, &t)) rb_sys_fail(0);
594  if (RTEST(f))
595  set_echo(&t, NULL);
596  else
597  set_noecho(&t, NULL);
598  if (!setattr(fd, &t)) rb_sys_fail(0);
599  return io;
600 }
601 
602 /*
603  * call-seq:
604  * io.echo? -> true or false
605  *
606  * Returns +true+ if echo back is enabled.
607  *
608  * You must require 'io/console' to use this method.
609  */
610 static VALUE
611 console_echo_p(VALUE io)
612 {
613  conmode t;
614  rb_io_t *fptr;
615  int fd;
616 
617  GetOpenFile(io, fptr);
618  fd = GetReadFD(fptr);
619  if (!getattr(fd, &t)) rb_sys_fail(0);
620  return echo_p(&t) ? Qtrue : Qfalse;
621 }
622 
623 static const rb_data_type_t conmode_type = {
624  "console-mode",
626  0, 0,
628 };
629 static VALUE cConmode;
630 
631 static VALUE
632 conmode_alloc(VALUE klass)
633 {
634  return rb_data_typed_object_zalloc(klass, sizeof(conmode), &conmode_type);
635 }
636 
637 static VALUE
638 conmode_new(VALUE klass, const conmode *t)
639 {
640  VALUE obj = conmode_alloc(klass);
641  *(conmode *)DATA_PTR(obj) = *t;
642  return obj;
643 }
644 
645 static VALUE
646 conmode_init_copy(VALUE obj, VALUE obj2)
647 {
648  conmode *t = rb_check_typeddata(obj, &conmode_type);
649  conmode *t2 = rb_check_typeddata(obj2, &conmode_type);
650  *t = *t2;
651  return obj;
652 }
653 
654 static VALUE
655 conmode_set_echo(VALUE obj, VALUE f)
656 {
657  conmode *t = rb_check_typeddata(obj, &conmode_type);
658  if (RTEST(f))
659  set_echo(t, NULL);
660  else
661  set_noecho(t, NULL);
662  return obj;
663 }
664 
665 static VALUE
666 conmode_set_raw(int argc, VALUE *argv, VALUE obj)
667 {
668  conmode *t = rb_check_typeddata(obj, &conmode_type);
669  rawmode_arg_t opts, *optp = rawmode_opt(&argc, argv, 0, 0, &opts);
670 
671  set_rawmode(t, optp);
672  return obj;
673 }
674 
675 static VALUE
676 conmode_raw_new(int argc, VALUE *argv, VALUE obj)
677 {
678  conmode *r = rb_check_typeddata(obj, &conmode_type);
679  conmode t = *r;
680  rawmode_arg_t opts, *optp = rawmode_opt(&argc, argv, 0, 0, &opts);
681 
682  set_rawmode(&t, optp);
683  return conmode_new(rb_obj_class(obj), &t);
684 }
685 
686 /*
687  * call-seq:
688  * io.console_mode -> mode
689  *
690  * Returns a data represents the current console mode.
691  *
692  * You must require 'io/console' to use this method.
693  */
694 static VALUE
695 console_conmode_get(VALUE io)
696 {
697  conmode t;
698  rb_io_t *fptr;
699  int fd;
700 
701  GetOpenFile(io, fptr);
702  fd = GetReadFD(fptr);
703  if (!getattr(fd, &t)) rb_sys_fail(0);
704 
705  return conmode_new(cConmode, &t);
706 }
707 
708 /*
709  * call-seq:
710  * io.console_mode = mode
711  *
712  * Sets the console mode to +mode+.
713  *
714  * You must require 'io/console' to use this method.
715  */
716 static VALUE
717 console_conmode_set(VALUE io, VALUE mode)
718 {
719  conmode *t, r;
720  rb_io_t *fptr;
721  int fd;
722 
723  TypedData_Get_Struct(mode, conmode, &conmode_type, t);
724  r = *t;
725  GetOpenFile(io, fptr);
726  fd = GetReadFD(fptr);
727  if (!setattr(fd, &r)) rb_sys_fail(0);
728 
729  return mode;
730 }
731 
732 #if defined TIOCGWINSZ
733 typedef struct winsize rb_console_size_t;
734 #define getwinsize(fd, buf) (ioctl((fd), TIOCGWINSZ, (buf)) == 0)
735 #define setwinsize(fd, buf) (ioctl((fd), TIOCSWINSZ, (buf)) == 0)
736 #define winsize_row(buf) (buf)->ws_row
737 #define winsize_col(buf) (buf)->ws_col
738 #elif defined _WIN32
739 typedef CONSOLE_SCREEN_BUFFER_INFO rb_console_size_t;
740 #define getwinsize(fd, buf) ( \
741  GetConsoleScreenBufferInfo((HANDLE)rb_w32_get_osfhandle(fd), (buf)) || \
742  SET_LAST_ERROR)
743 #define winsize_row(buf) ((buf)->srWindow.Bottom - (buf)->srWindow.Top + 1)
744 #define winsize_col(buf) (buf)->dwSize.X
745 #endif
746 
747 #if defined TIOCGWINSZ || defined _WIN32
748 #define USE_CONSOLE_GETSIZE 1
749 #endif
750 
751 #ifdef USE_CONSOLE_GETSIZE
752 /*
753  * call-seq:
754  * io.winsize -> [rows, columns]
755  *
756  * Returns console size.
757  *
758  * You must require 'io/console' to use this method.
759  */
760 static VALUE
761 console_winsize(VALUE io)
762 {
763  rb_io_t *fptr;
764  int fd;
765  rb_console_size_t ws;
766 
767  GetOpenFile(io, fptr);
768  fd = GetWriteFD(fptr);
769  if (!getwinsize(fd, &ws)) rb_sys_fail(0);
770  return rb_assoc_new(INT2NUM(winsize_row(&ws)), INT2NUM(winsize_col(&ws)));
771 }
772 
773 /*
774  * call-seq:
775  * io.winsize = [rows, columns]
776  *
777  * Tries to set console size. The effect depends on the platform and
778  * the running environment.
779  *
780  * You must require 'io/console' to use this method.
781  */
782 static VALUE
783 console_set_winsize(VALUE io, VALUE size)
784 {
785  rb_io_t *fptr;
786  rb_console_size_t ws;
787 #if defined _WIN32
788  HANDLE wh;
789  int newrow, newcol;
790  BOOL ret;
791 #endif
792  VALUE row, col, xpixel, ypixel;
793  const VALUE *sz;
794  int fd;
795  long sizelen;
796 
797  GetOpenFile(io, fptr);
798  size = rb_Array(size);
799  if ((sizelen = RARRAY_LEN(size)) != 2 && sizelen != 4) {
801  "wrong number of arguments (given %ld, expected 2 or 4)",
802  sizelen);
803  }
804  sz = RARRAY_CONST_PTR(size);
805  row = sz[0], col = sz[1], xpixel = ypixel = Qnil;
806  if (sizelen == 4) xpixel = sz[2], ypixel = sz[3];
807  fd = GetWriteFD(fptr);
808 #if defined TIOCSWINSZ
809  ws.ws_row = ws.ws_col = ws.ws_xpixel = ws.ws_ypixel = 0;
810 #define SET(m) ws.ws_##m = NIL_P(m) ? 0 : (unsigned short)NUM2UINT(m)
811  SET(row);
812  SET(col);
813  SET(xpixel);
814  SET(ypixel);
815 #undef SET
816  if (!setwinsize(fd, &ws)) rb_sys_fail(0);
817 #elif defined _WIN32
818  wh = (HANDLE)rb_w32_get_osfhandle(fd);
819 #define SET(m) new##m = NIL_P(m) ? 0 : (unsigned short)NUM2UINT(m)
820  SET(row);
821  SET(col);
822 #undef SET
823  if (!NIL_P(xpixel)) (void)NUM2UINT(xpixel);
824  if (!NIL_P(ypixel)) (void)NUM2UINT(ypixel);
825  if (!GetConsoleScreenBufferInfo(wh, &ws)) {
826  rb_syserr_fail(LAST_ERROR, "GetConsoleScreenBufferInfo");
827  }
828  ws.dwSize.X = newcol;
829  ret = SetConsoleScreenBufferSize(wh, ws.dwSize);
830  ws.srWindow.Left = 0;
831  ws.srWindow.Top = 0;
832  ws.srWindow.Right = newcol-1;
833  ws.srWindow.Bottom = newrow-1;
834  if (!SetConsoleWindowInfo(wh, TRUE, &ws.srWindow)) {
835  rb_syserr_fail(LAST_ERROR, "SetConsoleWindowInfo");
836  }
837  /* retry when shrinking buffer after shrunk window */
838  if (!ret && !SetConsoleScreenBufferSize(wh, ws.dwSize)) {
839  rb_syserr_fail(LAST_ERROR, "SetConsoleScreenBufferInfo");
840  }
841  /* remove scrollbar if possible */
842  if (!SetConsoleWindowInfo(wh, TRUE, &ws.srWindow)) {
843  rb_syserr_fail(LAST_ERROR, "SetConsoleWindowInfo");
844  }
845 #endif
846  return io;
847 }
848 #endif
849 
850 #ifdef _WIN32
851 static VALUE
853 {
854  rb_io_t *fptr;
855  HANDLE h;
856  DWORD num;
857 
858  GetOpenFile(io, fptr);
859  h = (HANDLE)rb_w32_get_osfhandle(GetReadFD(fptr));
860  while (GetNumberOfConsoleInputEvents(h, &num) && num > 0) {
861  INPUT_RECORD rec;
862  if (ReadConsoleInput(h, &rec, 1, &num)) {
863  if (rec.EventType == WINDOW_BUFFER_SIZE_EVENT) {
864  rb_yield(Qnil);
865  }
866  }
867  }
868  return io;
869 }
870 #else
871 #define console_check_winsize_changed rb_f_notimplement
872 #endif
873 
874 /*
875  * call-seq:
876  * io.iflush
877  *
878  * Flushes input buffer in kernel.
879  *
880  * You must require 'io/console' to use this method.
881  */
882 static VALUE
883 console_iflush(VALUE io)
884 {
885  rb_io_t *fptr;
886  int fd;
887 
888  GetOpenFile(io, fptr);
889  fd = GetReadFD(fptr);
890 #if defined HAVE_TERMIOS_H || defined HAVE_TERMIO_H
891  if (tcflush(fd, TCIFLUSH)) rb_sys_fail(0);
892 #endif
893  (void)fd;
894  return io;
895 }
896 
897 /*
898  * call-seq:
899  * io.oflush
900  *
901  * Flushes output buffer in kernel.
902  *
903  * You must require 'io/console' to use this method.
904  */
905 static VALUE
906 console_oflush(VALUE io)
907 {
908  rb_io_t *fptr;
909  int fd;
910 
911  GetOpenFile(io, fptr);
912  fd = GetWriteFD(fptr);
913 #if defined HAVE_TERMIOS_H || defined HAVE_TERMIO_H
914  if (tcflush(fd, TCOFLUSH)) rb_sys_fail(0);
915 #endif
916  (void)fd;
917  return io;
918 }
919 
920 /*
921  * call-seq:
922  * io.ioflush
923  *
924  * Flushes input and output buffers in kernel.
925  *
926  * You must require 'io/console' to use this method.
927  */
928 static VALUE
929 console_ioflush(VALUE io)
930 {
931  rb_io_t *fptr;
932 #if defined HAVE_TERMIOS_H || defined HAVE_TERMIO_H
933  int fd1, fd2;
934 #endif
935 
936  GetOpenFile(io, fptr);
937 #if defined HAVE_TERMIOS_H || defined HAVE_TERMIO_H
938  fd1 = GetReadFD(fptr);
939  fd2 = GetWriteFD(fptr);
940  if (fd2 != -1 && fd1 != fd2) {
941  if (tcflush(fd1, TCIFLUSH)) rb_sys_fail(0);
942  if (tcflush(fd2, TCOFLUSH)) rb_sys_fail(0);
943  }
944  else {
945  if (tcflush(fd1, TCIOFLUSH)) rb_sys_fail(0);
946  }
947 #endif
948  return io;
949 }
950 
951 static VALUE
952 console_beep(VALUE io)
953 {
954  rb_io_t *fptr;
955  int fd;
956 
957  GetOpenFile(io, fptr);
958  fd = GetWriteFD(fptr);
959 #ifdef _WIN32
960  (void)fd;
961  MessageBeep(0);
962 #else
963  if (write(fd, "\a", 1) < 0)
964  rb_sys_fail(0);
965 #endif
966  return io;
967 }
968 
969 static int
970 mode_in_range(VALUE val, int high, const char *modename)
971 {
972  int mode;
973  if (NIL_P(val)) return 0;
974  if (!RB_INTEGER_TYPE_P(val)) {
975  wrong_value:
976  rb_raise(rb_eArgError, "wrong %s mode: %"PRIsVALUE, modename, val);
977  }
978  if ((mode = NUM2INT(val)) < 0 || mode > high) {
979  goto wrong_value;
980  }
981  return mode;
982 }
983 
984 #if defined _WIN32
985 static VALUE
986 console_goto(VALUE io, VALUE y, VALUE x)
987 {
988  rb_io_t *fptr;
989  int fd;
990  COORD pos;
991 
992  GetOpenFile(io, fptr);
993  fd = GetWriteFD(fptr);
994  pos.X = NUM2UINT(x);
995  pos.Y = NUM2UINT(y);
996  if (!SetConsoleCursorPosition((HANDLE)rb_w32_get_osfhandle(fd), pos)) {
997  rb_syserr_fail(LAST_ERROR, 0);
998  }
999  return io;
1000 }
1001 
1002 static VALUE
1003 console_cursor_pos(VALUE io)
1004 {
1005  rb_io_t *fptr;
1006  int fd;
1007  rb_console_size_t ws;
1008 
1009  GetOpenFile(io, fptr);
1010  fd = GetWriteFD(fptr);
1011  if (!GetConsoleScreenBufferInfo((HANDLE)rb_w32_get_osfhandle(fd), &ws)) {
1012  rb_syserr_fail(LAST_ERROR, 0);
1013  }
1014  return rb_assoc_new(UINT2NUM(ws.dwCursorPosition.Y), UINT2NUM(ws.dwCursorPosition.X));
1015 }
1016 
1017 static VALUE
1018 console_move(VALUE io, int y, int x)
1019 {
1020  rb_io_t *fptr;
1021  HANDLE h;
1022  rb_console_size_t ws;
1023  COORD *pos = &ws.dwCursorPosition;
1024 
1025  GetOpenFile(io, fptr);
1026  h = (HANDLE)rb_w32_get_osfhandle(GetWriteFD(fptr));
1027  if (!GetConsoleScreenBufferInfo(h, &ws)) {
1028  rb_syserr_fail(LAST_ERROR, 0);
1029  }
1030  pos->X += x;
1031  pos->Y += y;
1032  if (!SetConsoleCursorPosition(h, *pos)) {
1033  rb_syserr_fail(LAST_ERROR, 0);
1034  }
1035  return io;
1036 }
1037 
1038 static VALUE
1039 console_goto_column(VALUE io, VALUE val)
1040 {
1041  rb_io_t *fptr;
1042  HANDLE h;
1043  rb_console_size_t ws;
1044  COORD *pos = &ws.dwCursorPosition;
1045 
1046  GetOpenFile(io, fptr);
1047  h = (HANDLE)rb_w32_get_osfhandle(GetWriteFD(fptr));
1048  if (!GetConsoleScreenBufferInfo(h, &ws)) {
1049  rb_syserr_fail(LAST_ERROR, 0);
1050  }
1051  pos->X = NUM2INT(val);
1052  if (!SetConsoleCursorPosition(h, *pos)) {
1053  rb_syserr_fail(LAST_ERROR, 0);
1054  }
1055  return io;
1056 }
1057 
1058 static void
1059 constat_clear(HANDLE handle, WORD attr, DWORD len, COORD pos)
1060 {
1061  DWORD written;
1062 
1063  FillConsoleOutputAttribute(handle, attr, len, pos, &written);
1064  FillConsoleOutputCharacterW(handle, L' ', len, pos, &written);
1065 }
1066 
1067 static VALUE
1068 console_erase_line(VALUE io, VALUE val)
1069 {
1070  rb_io_t *fptr;
1071  HANDLE h;
1072  rb_console_size_t ws;
1073  COORD *pos = &ws.dwCursorPosition;
1074  DWORD w;
1075  int mode = mode_in_range(val, 2, "line erase");
1076 
1077  GetOpenFile(io, fptr);
1078  h = (HANDLE)rb_w32_get_osfhandle(GetWriteFD(fptr));
1079  if (!GetConsoleScreenBufferInfo(h, &ws)) {
1080  rb_syserr_fail(LAST_ERROR, 0);
1081  }
1082  w = winsize_col(&ws);
1083  switch (mode) {
1084  case 0: /* after cursor */
1085  w -= pos->X;
1086  break;
1087  case 1: /* before *and* cursor */
1088  w = pos->X + 1;
1089  pos->X = 0;
1090  break;
1091  case 2: /* entire line */
1092  pos->X = 0;
1093  break;
1094  }
1095  constat_clear(h, ws.wAttributes, w, *pos);
1096  return io;
1097 }
1098 
1099 static VALUE
1100 console_erase_screen(VALUE io, VALUE val)
1101 {
1102  rb_io_t *fptr;
1103  HANDLE h;
1104  rb_console_size_t ws;
1105  COORD *pos = &ws.dwCursorPosition;
1106  DWORD w;
1107  int mode = mode_in_range(val, 3, "screen erase");
1108 
1109  GetOpenFile(io, fptr);
1110  h = (HANDLE)rb_w32_get_osfhandle(GetWriteFD(fptr));
1111  if (!GetConsoleScreenBufferInfo(h, &ws)) {
1112  rb_syserr_fail(LAST_ERROR, 0);
1113  }
1114  w = winsize_col(&ws);
1115  switch (mode) {
1116  case 0: /* erase after cursor */
1117  w = (w * (ws.srWindow.Bottom - pos->Y + 1) - pos->X);
1118  break;
1119  case 1: /* erase before *and* cursor */
1120  w = (w * (pos->Y - ws.srWindow.Top) + pos->X + 1);
1121  pos->X = 0;
1122  pos->Y = ws.srWindow.Top;
1123  break;
1124  case 2: /* erase entire screen */
1125  w = (w * winsize_row(&ws));
1126  pos->X = 0;
1127  pos->Y = ws.srWindow.Top;
1128  break;
1129  case 3: /* erase entire screen */
1130  w = (w * ws.dwSize.Y);
1131  pos->X = 0;
1132  pos->Y = 0;
1133  break;
1134  }
1135  constat_clear(h, ws.wAttributes, w, *pos);
1136  return io;
1137 }
1138 
1139 static VALUE
1140 console_scroll(VALUE io, int line)
1141 {
1142  rb_io_t *fptr;
1143  HANDLE h;
1144  rb_console_size_t ws;
1145 
1146  GetOpenFile(io, fptr);
1147  h = (HANDLE)rb_w32_get_osfhandle(GetWriteFD(fptr));
1148  if (!GetConsoleScreenBufferInfo(h, &ws)) {
1149  rb_syserr_fail(LAST_ERROR, 0);
1150  }
1151  if (line) {
1152  SMALL_RECT scroll;
1153  COORD destination;
1154  CHAR_INFO fill;
1155  scroll.Left = 0;
1156  scroll.Top = line > 0 ? line : 0;
1157  scroll.Right = winsize_col(&ws) - 1;
1158  scroll.Bottom = winsize_row(&ws) - 1 + (line < 0 ? line : 0);
1159  destination.X = 0;
1160  destination.Y = line < 0 ? -line : 0;
1161  fill.Char.UnicodeChar = L' ';
1162  fill.Attributes = ws.wAttributes;
1163 
1164  ScrollConsoleScreenBuffer(h, &scroll, NULL, destination, &fill);
1165  }
1166  return io;
1167 }
1168 
1169 #include "win32_vk.inc"
1170 
1171 static VALUE
1173 {
1174  int vk = -1;
1175 
1176  if (FIXNUM_P(k)) {
1177  vk = NUM2UINT(k);
1178  }
1179  else {
1180  const struct vktable *t;
1181  const char *kn;
1182  if (SYMBOL_P(k)) {
1183  k = rb_sym2str(k);
1184  kn = RSTRING_PTR(k);
1185  }
1186  else {
1187  kn = StringValuePtr(k);
1188  }
1189  t = console_win32_vk(kn, RSTRING_LEN(k));
1190  if (!t || (vk = (short)t->vk) == -1) {
1191  rb_raise(rb_eArgError, "unknown virtual key code: % "PRIsVALUE, k);
1192  }
1193  }
1194  return GetKeyState(vk) & 0x80 ? Qtrue : Qfalse;
1195 }
1196 #else
1197 struct query_args {
1198  const char *qstr;
1199  int opt;
1200 };
1201 
1202 static int
1203 direct_query(VALUE io, const struct query_args *query)
1204 {
1205  if (RB_TYPE_P(io, T_FILE)) {
1206  rb_io_t *fptr;
1207  VALUE wio;
1208  GetOpenFile(io, fptr);
1209  wio = fptr->tied_io_for_writing;
1210  if (wio) {
1211  VALUE s = rb_str_new_cstr(query->qstr);
1212  rb_io_write(wio, s);
1213  rb_io_flush(wio);
1214  return 1;
1215  }
1216  if (write(fptr->fd, query->qstr, strlen(query->qstr)) != -1) {
1217  return 1;
1218  }
1219  if (fptr->fd == 0 &&
1220  write(1, query->qstr, strlen(query->qstr)) != -1) {
1221  return 1;
1222  }
1223  }
1224  return 0;
1225 }
1226 
1227 static VALUE
1228 read_vt_response(VALUE io, VALUE query)
1229 {
1230  struct query_args *qargs = (struct query_args *)query;
1231  VALUE result, b;
1232  int opt = 0;
1233  int num = 0;
1234  if (qargs) {
1235  opt = qargs->opt;
1236  if (!direct_query(io, qargs)) return Qnil;
1237  }
1238  if (rb_io_getbyte(io) != INT2FIX(0x1b)) return Qnil;
1239  if (rb_io_getbyte(io) != INT2FIX('[')) return Qnil;
1240  result = rb_ary_new();
1241  while (!NIL_P(b = rb_io_getbyte(io))) {
1242  int c = NUM2UINT(b);
1243  if (c == ';') {
1244  rb_ary_push(result, INT2NUM(num));
1245  num = 0;
1246  }
1247  else if (ISDIGIT(c)) {
1248  num = num * 10 + c - '0';
1249  }
1250  else if (opt && c == opt) {
1251  opt = 0;
1252  }
1253  else {
1254  char last = (char)c;
1255  rb_ary_push(result, INT2NUM(num));
1256  b = rb_str_new(&last, 1);
1257  break;
1258  }
1259  }
1260  return rb_ary_push(result, b);
1261 }
1262 
1263 static VALUE
1264 console_vt_response(int argc, VALUE *argv, VALUE io, const struct query_args *qargs)
1265 {
1266  rawmode_arg_t opts, *optp = rawmode_opt(&argc, argv, 0, 1, &opts);
1267  VALUE query = (VALUE)qargs;
1268  VALUE ret = ttymode_with_io(io, read_vt_response, query, set_rawmode, optp);
1269  return ret;
1270 }
1271 
1272 static VALUE
1273 console_cursor_pos(VALUE io)
1274 {
1275  static const struct query_args query = {"\033[6n", 0};
1276  VALUE resp = console_vt_response(0, 0, io, &query);
1277  VALUE row, column, term;
1278  unsigned int r, c;
1279  if (!RB_TYPE_P(resp, T_ARRAY) || RARRAY_LEN(resp) != 3) return Qnil;
1280  term = RARRAY_AREF(resp, 2);
1281  if (!RB_TYPE_P(term, T_STRING) || RSTRING_LEN(term) != 1) return Qnil;
1282  if (RSTRING_PTR(term)[0] != 'R') return Qnil;
1283  row = RARRAY_AREF(resp, 0);
1284  column = RARRAY_AREF(resp, 1);
1285  rb_ary_resize(resp, 2);
1286  r = NUM2UINT(row) - 1;
1287  c = NUM2UINT(column) - 1;
1288  RARRAY_ASET(resp, 0, INT2NUM(r));
1289  RARRAY_ASET(resp, 1, INT2NUM(c));
1290  return resp;
1291 }
1292 
1293 static VALUE
1294 console_goto(VALUE io, VALUE y, VALUE x)
1295 {
1296  rb_io_write(io, rb_sprintf("\x1b[%d;%dH", NUM2UINT(y)+1, NUM2UINT(x)+1));
1297  return io;
1298 }
1299 
1300 static VALUE
1301 console_move(VALUE io, int y, int x)
1302 {
1303  if (x || y) {
1304  VALUE s = rb_str_new_cstr("");
1305  if (y) rb_str_catf(s, "\x1b[%d%c", y < 0 ? -y : y, y < 0 ? 'A' : 'B');
1306  if (x) rb_str_catf(s, "\x1b[%d%c", x < 0 ? -x : x, x < 0 ? 'D' : 'C');
1307  rb_io_write(io, s);
1308  rb_io_flush(io);
1309  }
1310  return io;
1311 }
1312 
1313 static VALUE
1314 console_goto_column(VALUE io, VALUE val)
1315 {
1316  rb_io_write(io, rb_sprintf("\x1b[%dG", NUM2UINT(val)+1));
1317  return io;
1318 }
1319 
1320 static VALUE
1321 console_erase_line(VALUE io, VALUE val)
1322 {
1323  int mode = mode_in_range(val, 2, "line erase");
1324  rb_io_write(io, rb_sprintf("\x1b[%dK", mode));
1325  return io;
1326 }
1327 
1328 static VALUE
1329 console_erase_screen(VALUE io, VALUE val)
1330 {
1331  int mode = mode_in_range(val, 3, "screen erase");
1332  rb_io_write(io, rb_sprintf("\x1b[%dJ", mode));
1333  return io;
1334 }
1335 
1336 static VALUE
1337 console_scroll(VALUE io, int line)
1338 {
1339  if (line) {
1340  VALUE s = rb_sprintf("\x1b[%d%c", line < 0 ? -line : line,
1341  line < 0 ? 'T' : 'S');
1342  rb_io_write(io, s);
1343  }
1344  return io;
1345 }
1346 # define console_key_pressed_p rb_f_notimplement
1347 #endif
1348 
1349 static VALUE
1350 console_cursor_set(VALUE io, VALUE cpos)
1351 {
1352  cpos = rb_convert_type(cpos, T_ARRAY, "Array", "to_ary");
1353  if (RARRAY_LEN(cpos) != 2) rb_raise(rb_eArgError, "expected 2D coordinate");
1354  return console_goto(io, RARRAY_AREF(cpos, 0), RARRAY_AREF(cpos, 1));
1355 }
1356 
1357 static VALUE
1358 console_cursor_up(VALUE io, VALUE val)
1359 {
1360  return console_move(io, -NUM2INT(val), 0);
1361 }
1362 
1363 static VALUE
1364 console_cursor_down(VALUE io, VALUE val)
1365 {
1366  return console_move(io, +NUM2INT(val), 0);
1367 }
1368 
1369 static VALUE
1370 console_cursor_left(VALUE io, VALUE val)
1371 {
1372  return console_move(io, 0, -NUM2INT(val));
1373 }
1374 
1375 static VALUE
1376 console_cursor_right(VALUE io, VALUE val)
1377 {
1378  return console_move(io, 0, +NUM2INT(val));
1379 }
1380 
1381 static VALUE
1382 console_scroll_forward(VALUE io, VALUE val)
1383 {
1384  return console_scroll(io, +NUM2INT(val));
1385 }
1386 
1387 static VALUE
1388 console_scroll_backward(VALUE io, VALUE val)
1389 {
1390  return console_scroll(io, -NUM2INT(val));
1391 }
1392 
1393 static VALUE
1394 console_clear_screen(VALUE io)
1395 {
1396  console_erase_screen(io, INT2FIX(2));
1397  console_goto(io, INT2FIX(0), INT2FIX(0));
1398  return io;
1399 }
1400 
1401 /*
1402  * call-seq:
1403  * IO.console -> #<File:/dev/tty>
1404  * IO.console(sym, *args)
1405  *
1406  * Returns an File instance opened console.
1407  *
1408  * If +sym+ is given, it will be sent to the opened console with
1409  * +args+ and the result will be returned instead of the console IO
1410  * itself.
1411  *
1412  * You must require 'io/console' to use this method.
1413  */
1414 static VALUE
1415 console_dev(int argc, VALUE *argv, VALUE klass)
1416 {
1417  VALUE con = 0;
1418  rb_io_t *fptr;
1419  VALUE sym = 0;
1420 
1422  if (argc) {
1423  Check_Type(sym = argv[0], T_SYMBOL);
1424  }
1425  if (klass == rb_cIO) klass = rb_cFile;
1426  if (rb_const_defined(klass, id_console)) {
1427  con = rb_const_get(klass, id_console);
1428  if (!RB_TYPE_P(con, T_FILE) ||
1429  (!(fptr = RFILE(con)->fptr) || GetReadFD(fptr) == -1)) {
1430  rb_const_remove(klass, id_console);
1431  con = 0;
1432  }
1433  }
1434  if (sym) {
1435  if (sym == ID2SYM(id_close) && argc == 1) {
1436  if (con) {
1437  rb_io_close(con);
1438  rb_const_remove(klass, id_console);
1439  con = 0;
1440  }
1441  return Qnil;
1442  }
1443  }
1444  if (!con) {
1445  VALUE args[2];
1446 #if defined HAVE_TERMIOS_H || defined HAVE_TERMIO_H || defined HAVE_SGTTY_H
1447 # define CONSOLE_DEVICE "/dev/tty"
1448 #elif defined _WIN32
1449 # define CONSOLE_DEVICE "con$"
1450 # define CONSOLE_DEVICE_FOR_READING "conin$"
1451 # define CONSOLE_DEVICE_FOR_WRITING "conout$"
1452 #endif
1453 #ifndef CONSOLE_DEVICE_FOR_READING
1454 # define CONSOLE_DEVICE_FOR_READING CONSOLE_DEVICE
1455 #endif
1456 #ifdef CONSOLE_DEVICE_FOR_WRITING
1457  VALUE out;
1458  rb_io_t *ofptr;
1459 #endif
1460  int fd;
1461 
1462 #ifdef CONSOLE_DEVICE_FOR_WRITING
1463  fd = rb_cloexec_open(CONSOLE_DEVICE_FOR_WRITING, O_RDWR, 0);
1464  if (fd < 0) return Qnil;
1465  rb_update_max_fd(fd);
1466  args[1] = INT2FIX(O_WRONLY);
1467  args[0] = INT2NUM(fd);
1468  out = rb_class_new_instance(2, args, klass);
1469 #endif
1471  if (fd < 0) {
1472 #ifdef CONSOLE_DEVICE_FOR_WRITING
1473  rb_io_close(out);
1474 #endif
1475  return Qnil;
1476  }
1477  rb_update_max_fd(fd);
1478  args[1] = INT2FIX(O_RDWR);
1479  args[0] = INT2NUM(fd);
1480  con = rb_class_new_instance(2, args, klass);
1481  GetOpenFile(con, fptr);
1482  fptr->pathv = rb_obj_freeze(rb_str_new2(CONSOLE_DEVICE));
1483 #ifdef CONSOLE_DEVICE_FOR_WRITING
1484  GetOpenFile(out, ofptr);
1485  ofptr->pathv = fptr->pathv;
1486  fptr->tied_io_for_writing = out;
1487  ofptr->mode |= FMODE_SYNC;
1488 #endif
1489  fptr->mode |= FMODE_SYNC;
1490  rb_const_set(klass, id_console, con);
1491  }
1492  if (sym) {
1493  return rb_f_send(argc, argv, con);
1494  }
1495  return con;
1496 }
1497 
1498 /*
1499  * call-seq:
1500  * io.getch(min: nil, time: nil, intr: nil) -> char
1501  *
1502  * See IO#getch.
1503  */
1504 static VALUE
1505 io_getch(int argc, VALUE *argv, VALUE io)
1506 {
1507  return rb_funcallv(io, id_getc, argc, argv);
1508 }
1509 
1510 #if ENABLE_IO_GETPASS
1511 static VALUE
1512 puts_call(VALUE io)
1513 {
1514  return rb_io_write(io, rb_default_rs);
1515 }
1516 
1517 static VALUE
1518 getpass_call(VALUE io)
1519 {
1520  return ttymode(io, rb_io_gets, io, set_noecho, NULL);
1521 }
1522 
1523 static void
1524 prompt(int argc, VALUE *argv, VALUE io)
1525 {
1526  if (argc > 0 && !NIL_P(argv[0])) {
1527  VALUE str = argv[0];
1529  rb_io_write(io, str);
1530  }
1531 }
1532 
1533 static VALUE
1534 str_chomp(VALUE str)
1535 {
1536  if (!NIL_P(str)) {
1537  str = rb_funcallv(str, rb_intern("chomp!"), 0, 0);
1538  }
1539  return str;
1540 }
1541 
1542 /*
1543  * call-seq:
1544  * io.getpass(prompt=nil) -> string
1545  *
1546  * Reads and returns a line without echo back.
1547  * Prints +prompt+ unless it is +nil+.
1548  *
1549  * You must require 'io/console' to use this method.
1550  */
1551 static VALUE
1552 console_getpass(int argc, VALUE *argv, VALUE io)
1553 {
1554  VALUE str, wio;
1555 
1556  rb_check_arity(argc, 0, 1);
1557  wio = rb_io_get_write_io(io);
1558  if (wio == io && io == rb_stdin) wio = rb_stderr;
1559  prompt(argc, argv, wio);
1560  str = rb_ensure(getpass_call, io, puts_call, wio);
1561  return str_chomp(str);
1562 }
1563 
1564 /*
1565  * call-seq:
1566  * io.getpass(prompt=nil) -> string
1567  *
1568  * See IO#getpass.
1569  */
1570 static VALUE
1571 io_getpass(int argc, VALUE *argv, VALUE io)
1572 {
1573  VALUE str;
1574 
1575  rb_check_arity(argc, 0, 1);
1576  prompt(argc, argv, io);
1577  str = str_chomp(rb_funcallv(io, id_gets, 0, 0));
1578  puts_call(io);
1579  return str;
1580 }
1581 #endif
1582 
1583 /*
1584  * IO console methods
1585  */
1586 void
1588 {
1589 #undef rb_intern
1590  id_getc = rb_intern("getc");
1591 #if ENABLE_IO_GETPASS
1592  id_gets = rb_intern("gets");
1593 #endif
1594  id_console = rb_intern("console");
1595  id_close = rb_intern("close");
1596  id_min = rb_intern("min");
1597  id_time = rb_intern("time");
1598  id_intr = rb_intern("intr");
1599 #ifndef HAVE_RB_F_SEND
1600  id___send__ = rb_intern("__send__");
1601 #endif
1602  InitVM(console);
1603 }
1604 
1605 void
1607 {
1608  rb_define_method(rb_cIO, "raw", console_raw, -1);
1609  rb_define_method(rb_cIO, "raw!", console_set_raw, -1);
1610  rb_define_method(rb_cIO, "cooked", console_cooked, 0);
1611  rb_define_method(rb_cIO, "cooked!", console_set_cooked, 0);
1612  rb_define_method(rb_cIO, "getch", console_getch, -1);
1613  rb_define_method(rb_cIO, "echo=", console_set_echo, 1);
1614  rb_define_method(rb_cIO, "echo?", console_echo_p, 0);
1615  rb_define_method(rb_cIO, "console_mode", console_conmode_get, 0);
1616  rb_define_method(rb_cIO, "console_mode=", console_conmode_set, 1);
1617  rb_define_method(rb_cIO, "noecho", console_noecho, 0);
1618  rb_define_method(rb_cIO, "winsize", console_winsize, 0);
1619  rb_define_method(rb_cIO, "winsize=", console_set_winsize, 1);
1620  rb_define_method(rb_cIO, "iflush", console_iflush, 0);
1621  rb_define_method(rb_cIO, "oflush", console_oflush, 0);
1622  rb_define_method(rb_cIO, "ioflush", console_ioflush, 0);
1623  rb_define_method(rb_cIO, "beep", console_beep, 0);
1624  rb_define_method(rb_cIO, "goto", console_goto, 2);
1625  rb_define_method(rb_cIO, "cursor", console_cursor_pos, 0);
1626  rb_define_method(rb_cIO, "cursor=", console_cursor_set, 1);
1627  rb_define_method(rb_cIO, "cursor_up", console_cursor_up, 1);
1628  rb_define_method(rb_cIO, "cursor_down", console_cursor_down, 1);
1629  rb_define_method(rb_cIO, "cursor_left", console_cursor_left, 1);
1630  rb_define_method(rb_cIO, "cursor_right", console_cursor_right, 1);
1631  rb_define_method(rb_cIO, "goto_column", console_goto_column, 1);
1632  rb_define_method(rb_cIO, "erase_line", console_erase_line, 1);
1633  rb_define_method(rb_cIO, "erase_screen", console_erase_screen, 1);
1634  rb_define_method(rb_cIO, "scroll_forward", console_scroll_forward, 1);
1635  rb_define_method(rb_cIO, "scroll_backward", console_scroll_backward, 1);
1636  rb_define_method(rb_cIO, "clear_screen", console_clear_screen, 0);
1638  rb_define_method(rb_cIO, "check_winsize_changed", console_check_winsize_changed, 0);
1639 #if ENABLE_IO_GETPASS
1640  rb_define_method(rb_cIO, "getpass", console_getpass, -1);
1641 #endif
1642  rb_define_singleton_method(rb_cIO, "console", console_dev, -1);
1643  {
1644  VALUE mReadable = rb_define_module_under(rb_cIO, "generic_readable");
1645  rb_define_method(mReadable, "getch", io_getch, -1);
1646 #if ENABLE_IO_GETPASS
1647  rb_define_method(mReadable, "getpass", io_getpass, -1);
1648 #endif
1649  }
1650  {
1651  /* :stopdoc: */
1652  cConmode = rb_define_class_under(rb_cIO, "ConsoleMode", rb_cObject);
1653  rb_define_alloc_func(cConmode, conmode_alloc);
1654  rb_undef_method(cConmode, "initialize");
1655  rb_define_method(cConmode, "initialize_copy", conmode_init_copy, 1);
1656  rb_define_method(cConmode, "echo=", conmode_set_echo, 1);
1657  rb_define_method(cConmode, "raw!", conmode_set_raw, -1);
1658  rb_define_method(cConmode, "raw", conmode_raw_new, -1);
1659  /* :startdoc: */
1660  }
1661 }
rb_io_gets
VALUE rb_io_gets(VALUE)
Definition: io.c:3573
ID
unsigned long ID
Definition: ruby.h:103
obj
const VALUE VALUE obj
Definition: rb_mjit_min_header-2.7.1.h:5703
Check_Type
#define Check_Type(v, t)
Definition: ruby.h:595
TRUE
#define TRUE
Definition: nkf.h:175
RFILE
#define RFILE(obj)
Definition: ruby.h:1276
rb_check_id
ID rb_check_id(volatile VALUE *)
Returns ID for the given name if it is interned already, or 0.
Definition: symbol.c:919
rb_assoc_new
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Definition: array.c:896
rb_str_new2
#define rb_str_new2
Definition: intern.h:903
rb_default_rs
RUBY_EXTERN VALUE rb_default_rs
Definition: intern.h:586
klass
VALUE klass
Definition: rb_mjit_min_header-2.7.1.h:13179
rb_io_close
VALUE rb_io_close(VALUE)
Definition: io.c:4820
rb_const_defined
int rb_const_defined(VALUE, ID)
Definition: variable.c:2682
rb_define_module_under
VALUE rb_define_module_under(VALUE outer, const char *name)
Definition: class.c:797
rb_stderr
RUBY_EXTERN VALUE rb_stderr
Definition: ruby.h:2090
ISDIGIT
#define ISDIGIT(c)
Definition: ruby.h:2312
rb_warning
void rb_warning(const char *fmt,...)
Definition: error.c:334
query_args::opt
int opt
Definition: console.c:1199
INT2FIX
#define INT2FIX(i)
Definition: ruby.h:263
FD_PER_IO
#define FD_PER_IO
Definition: console.c:278
Init_console
void Init_console(void)
Definition: console.c:1587
RSTRING_PTR
#define RSTRING_PTR(str)
Definition: ruby.h:1009
rb_io_t::pathv
VALUE pathv
Definition: io.h:72
rb_str_new_cstr
#define rb_str_new_cstr(str)
Definition: rb_mjit_min_header-2.7.1.h:6078
GetWriteFD
#define GetWriteFD(fptr)
Definition: console.c:276
rb_hash_aref
VALUE rb_hash_aref(VALUE hash, VALUE key)
Definition: hash.c:2032
RB_WAITFD_IN
#define RB_WAITFD_IN
Definition: io.h:51
rb_default_external_encoding
rb_encoding * rb_default_external_encoding(void)
Definition: encoding.c:1427
SET
#define SET(a, b, c, d, k, s, Ti)
VALUE
unsigned long VALUE
Definition: ruby.h:102
rb_eArgError
VALUE rb_eArgError
Definition: error.c:923
rb_intern
#define rb_intern(str)
RB_TYPE_P
#define RB_TYPE_P(obj, type)
Definition: ruby.h:560
console_check_winsize_changed
#define console_check_winsize_changed
Definition: console.c:871
UINT2NUM
#define UINT2NUM(x)
Definition: ruby.h:1610
DWORD
IUnknown DWORD
Definition: win32ole.c:33
arg
VALUE arg
Definition: rb_mjit_min_header-2.7.1.h:5562
rb_stdin
RUBY_EXTERN VALUE rb_stdin
Definition: ruby.h:2090
rb_define_singleton_method
void rb_define_singleton_method(VALUE obj, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a singleton method for obj.
Definition: class.c:1755
CHAR_BIT
#define CHAR_BIT
Definition: ruby.h:227
rb_const_set
void rb_const_set(VALUE, ID, VALUE)
Definition: variable.c:2752
rb_define_method
void rb_define_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Definition: class.c:1551
INT2NUM
#define INT2NUM(x)
Definition: ruby.h:1609
wint_t
unsigned int wint_t
Definition: rb_mjit_min_header-2.7.1.h:901
rb_str_new
#define rb_str_new(str, len)
Definition: rb_mjit_min_header-2.7.1.h:6077
Qfalse
#define Qfalse
Definition: ruby.h:467
InitVM_console
void InitVM_console(void)
Definition: console.c:1606
RARRAY_ASET
#define RARRAY_ASET(a, i, v)
Definition: ruby.h:1102
rb_const_remove
VALUE rb_const_remove(VALUE, ID)
Definition: variable.c:2490
rb_io_t::fd
int fd
Definition: io.h:68
NULL
#define NULL
Definition: _sdbm.c:101
char
#define char
Definition: rb_mjit_min_header-2.7.1.h:2844
PRIsVALUE
#define PRIsVALUE
Definition: ruby.h:166
last
unsigned int last
Definition: nkf.c:4324
ID2SYM
#define ID2SYM(x)
Definition: ruby.h:414
strlen
size_t strlen(const char *)
T_SYMBOL
#define T_SYMBOL
Definition: ruby.h:540
rb_eof_error
void rb_eof_error(void)
Definition: io.c:697
rb_cFile
VALUE rb_cFile
Definition: file.c:159
L
#define L(x)
Definition: asm.h:125
rb_undef_method
void rb_undef_method(VALUE klass, const char *name)
Definition: class.c:1575
rb_protect
VALUE rb_protect(VALUE(*proc)(VALUE), VALUE data, int *pstate)
Protects a function call from potential global escapes from the function.
Definition: eval.c:1072
rb_check_arity
#define rb_check_arity
Definition: intern.h:347
InitVM
#define InitVM(ext)
Definition: ruby.h:2329
CONSOLE_DEVICE_FOR_READING
#define CONSOLE_DEVICE_FOR_READING
UNLIMITED_ARGUMENTS
#define UNLIMITED_ARGUMENTS
Definition: intern.h:57
RUBY_TYPED_DEFAULT_FREE
#define RUBY_TYPED_DEFAULT_FREE
Definition: ruby.h:1203
rb_raise
void rb_raise(VALUE exc, const char *fmt,...)
Definition: error.c:2669
FMODE_SYNC
#define FMODE_SYNC
Definition: io.h:112
T_FILE
#define T_FILE
Definition: ruby.h:534
NUM2UINT
#define NUM2UINT(x)
Definition: ruby.h:716
console_key_pressed_p
#define console_key_pressed_p
Definition: console.c:1346
void
void
Definition: rb_mjit_min_header-2.7.1.h:13198
rb_obj_class
VALUE rb_obj_class(VALUE)
Equivalent to Object#class in Ruby.
Definition: object.c:217
rb_io_flush
VALUE rb_io_flush(VALUE)
Definition: io.c:1903
rb_data_typed_object_zalloc
VALUE rb_data_typed_object_zalloc(VALUE klass, size_t size, const rb_data_type_t *type)
rb_syserr_fail
void rb_syserr_fail(int e, const char *mesg)
Definition: error.c:2781
DATA_PTR
#define DATA_PTR(dta)
Definition: ruby.h:1175
rb_Array
VALUE rb_Array(VALUE)
Equivalent to Kernel#Array in Ruby.
Definition: object.c:3684
ttymode_callback_args
Definition: console.c:337
query_args::qstr
const char * qstr
Definition: console.c:1198
h
size_t st_index_t h
Definition: rb_mjit_min_header-2.7.1.h:5423
rb_jump_tag
void rb_jump_tag(int tag)
Continues the exception caught by rb_protect() and rb_eval_string_protect().
Definition: eval.c:884
sym
#define sym(x)
Definition: date_core.c:3716
query_args
Definition: console.c:1197
max_argc
const rb_iseq_t const int const int const int max_argc
Definition: rb_mjit_min_header-2.7.1.h:13427
rb_ary_push
VALUE rb_ary_push(VALUE ary, VALUE item)
Definition: array.c:1195
ruby.h
rb_update_max_fd
void rb_update_max_fd(int fd)
Definition: io.c:218
rb_obj_freeze
VALUE rb_obj_freeze(VALUE)
Make the object unmodifiable.
Definition: object.c:1080
term
const char term
Definition: id.c:37
RUBY_UBF_IO
#define RUBY_UBF_IO
Definition: intern.h:945
rb_sys_fail
void rb_sys_fail(const char *mesg)
Definition: error.c:2793
obj2
VALUE obj2
Definition: rb_mjit_min_header-2.7.1.h:7510
rb_io_get_write_io
VALUE rb_io_get_write_io(VALUE io)
Definition: io.c:745
rb_thread_call_without_gvl
void * rb_thread_call_without_gvl(void *(*func)(void *), void *data1, rb_unblock_function_t *ubf, void *data2)
RARRAY_AREF
#define RARRAY_AREF(a, i)
Definition: ruby.h:1101
StringValuePtr
#define StringValuePtr(v)
Definition: ruby.h:603
size
int size
Definition: encoding.c:58
EINTR
#define EINTR
Definition: rb_mjit_min_header-2.7.1.h:10866
rb_ary_resize
VALUE rb_ary_resize(VALUE ary, long len)
expands or shrinks ary to len elements.
Definition: array.c:1955
FIXNUM_P
#define FIXNUM_P(f)
Definition: ruby.h:396
write
_ssize_t write(int __fd, const void *__buf, size_t __nbyte)
ttymode_callback_args::func
VALUE(* func)(VALUE, VALUE)
Definition: console.c:338
StringValueCStr
#define StringValueCStr(v)
Definition: ruby.h:604
RARRAY_CONST_PTR
#define RARRAY_CONST_PTR(a)
Definition: ruby.h:1072
timeval::tv_sec
time_t tv_sec
Definition: missing.h:54
ttymode_callback_args::io
VALUE io
Definition: console.c:339
rb_w32_get_osfhandle
SOCKET rb_w32_get_osfhandle(int)
Definition: win32.c:1078
rb_utf8_str_new
#define rb_utf8_str_new(str, len)
Definition: rb_mjit_min_header-2.7.1.h:6080
RARRAY_LEN
#define RARRAY_LEN(a)
Definition: ruby.h:1070
rb_scan_args
#define rb_scan_args(argc, argvp, fmt,...)
Definition: rb_mjit_min_header-2.7.1.h:6333
rb_check_hash_type
VALUE rb_check_hash_type(VALUE hash)
Definition: hash.c:1847
rb_cObject
RUBY_EXTERN VALUE rb_cObject
Definition: ruby.h:2010
rb_extract_keywords
VALUE rb_extract_keywords(VALUE *orighash)
Definition: class.c:1868
rb_cloexec_open
int rb_cloexec_open(const char *pathname, int flags, mode_t mode)
Definition: io.c:292
rb_uv_to_utf8
int rb_uv_to_utf8(char[6], unsigned long)
Definition: pack.c:1651
buf
unsigned char buf[MIME_BUF_SIZE]
Definition: nkf.c:4322
TypedData_Get_Struct
#define TypedData_Get_Struct(obj, type, data_type, sval)
Definition: ruby.h:1252
error
const rb_iseq_t const char * error
Definition: rb_mjit_min_header-2.7.1.h:13428
T_ARRAY
#define T_ARRAY
Definition: ruby.h:530
argv
char ** argv
Definition: ruby.c:223
f
#define f
rb_io_t::mode
int mode
Definition: io.h:69
rawmode_arg_t::intr
int intr
Definition: console.c:105
rb_sprintf
VALUE rb_sprintf(const char *format,...)
Definition: sprintf.c:1197
timeval
Definition: missing.h:53
str
char str[HTML_ESCAPE_MAX_LEN+1]
Definition: escape.c:18
rawmode_arg_t::vtime
int vtime
Definition: console.c:104
rb_convert_type
VALUE rb_convert_type(VALUE, int, const char *, const char *)
Converts an object into another type.
Definition: object.c:2900
RUBY_TYPED_FREE_IMMEDIATELY
#define RUBY_TYPED_FREE_IMMEDIATELY
Definition: ruby.h:1207
rb_wait_for_single_fd
int rb_wait_for_single_fd(int fd, int events, struct timeval *tv)
Definition: thread.c:4276
int
__inline__ int
Definition: rb_mjit_min_header-2.7.1.h:2807
rb_io_getbyte
VALUE rb_io_getbyte(VALUE)
Definition: io.c:4215
NIL_P
#define NIL_P(v)
Definition: ruby.h:482
io.h
argc
int argc
Definition: ruby.c:222
rb_funcall3
#define rb_funcall3
Definition: ruby.h:1896
rawmode_arg_t
Definition: console.c:102
rb_io_write
VALUE rb_io_write(VALUE, VALUE)
Definition: io.c:1804
rb_data_type_struct
Definition: ruby.h:1148
GetOpenFile
#define GetOpenFile(obj, fp)
Definition: io.h:127
rb_check_typeddata
void * rb_check_typeddata(VALUE obj, const rb_data_type_t *data_type)
Definition: error.c:889
Qtrue
#define Qtrue
Definition: ruby.h:468
rb_str_catf
VALUE rb_str_catf(VALUE str, const char *format,...)
Definition: sprintf.c:1237
errno
int errno
len
uint8_t len
Definition: escape.c:17
SYMBOL_P
#define SYMBOL_P(x)
Definition: ruby.h:413
rb_class_new_instance
VALUE rb_class_new_instance(int, const VALUE *, VALUE)
Allocates and initializes an instance of klass.
Definition: object.c:1955
rb_io_t::tied_io_for_writing
VALUE tied_io_for_writing
Definition: io.h:77
T_STRING
#define T_STRING
Definition: ruby.h:528
rb_define_class_under
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition: class.c:698
rb_sym2str
VALUE rb_sym2str(VALUE)
Definition: symbol.c:784
rawmode_arg_t::vmin
int vmin
Definition: console.c:103
rb_yield
VALUE rb_yield(VALUE)
Definition: vm_eval.c:1237
RB_INTEGER_TYPE_P
#define RB_INTEGER_TYPE_P(obj)
Definition: ruby_missing.h:15
rb_ensure
VALUE rb_ensure(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*e_proc)(VALUE), VALUE data2)
An equivalent to ensure clause.
Definition: eval.c:1115
rb_ary_new
VALUE rb_ary_new(void)
Definition: array.c:723
NUM2INT
#define NUM2INT(x)
Definition: ruby.h:715
Qnil
#define Qnil
Definition: ruby.h:469
thread.h
rb_io_t
Definition: io.h:66
ttymode_callback_args::farg
VALUE farg
Definition: console.c:340
RSTRING_LEN
#define RSTRING_LEN(str)
Definition: ruby.h:1005
rb_str_conv_enc
VALUE rb_str_conv_enc(VALUE str, rb_encoding *from, rb_encoding *to)
Definition: string.c:1030
rb_define_alloc_func
void rb_define_alloc_func(VALUE, rb_alloc_func_t)
RTEST
#define RTEST(v)
Definition: ruby.h:481
rb_cIO
RUBY_EXTERN VALUE rb_cIO
Definition: ruby.h:2030
GetReadFD
#define GetReadFD(fptr)
Definition: console.c:265
RUBY_TYPED_WB_PROTECTED
#define RUBY_TYPED_WB_PROTECTED
Definition: ruby.h:1208
min_argc
const rb_iseq_t const int const int min_argc
Definition: rb_mjit_min_header-2.7.1.h:13427
rb_funcallv
#define rb_funcallv(recv, mid, argc, argv)
Definition: rb_mjit_min_header-2.7.1.h:7826
rb_const_get
VALUE rb_const_get(VALUE, ID)
Definition: variable.c:2387