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