Ruby  2.5.0dev(2017-10-22revision60238)
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 
8 #ifdef HAVE_UNISTD_H
9 #include <unistd.h>
10 #endif
11 #ifdef HAVE_FCNTL_H
12 #include <fcntl.h>
13 #endif
14 #ifdef HAVE_SYS_IOCTL_H
15 #include <sys/ioctl.h>
16 #endif
17 #ifndef RARRAY_CONST_PTR
18 # define RARRAY_CONST_PTR(ary) RARRAY_PTR(ary)
19 #endif
20 #ifndef HAVE_RB_FUNCALLV
21 # define rb_funcallv rb_funcall2
22 #endif
23 
24 #if defined HAVE_TERMIOS_H
25 # include <termios.h>
26 typedef struct termios conmode;
27 
28 static int
29 setattr(int fd, conmode *t)
30 {
31  while (tcsetattr(fd, TCSAFLUSH, t)) {
32  if (errno != EINTR) return 0;
33  }
34  return 1;
35 }
36 # define getattr(fd, t) (tcgetattr(fd, t) == 0)
37 #elif defined HAVE_TERMIO_H
38 # include <termio.h>
39 typedef struct termio conmode;
40 # define setattr(fd, t) (ioctl(fd, TCSETAF, t) == 0)
41 # define getattr(fd, t) (ioctl(fd, TCGETA, t) == 0)
42 #elif defined HAVE_SGTTY_H
43 # include <sgtty.h>
44 typedef struct sgttyb conmode;
45 # ifdef HAVE_STTY
46 # define setattr(fd, t) (stty(fd, t) == 0)
47 # else
48 # define setattr(fd, t) (ioctl((fd), TIOCSETP, (t)) == 0)
49 # endif
50 # ifdef HAVE_GTTY
51 # define getattr(fd, t) (gtty(fd, t) == 0)
52 # else
53 # define getattr(fd, t) (ioctl((fd), TIOCGETP, (t)) == 0)
54 # endif
55 #elif defined _WIN32
56 #include <winioctl.h>
57 typedef DWORD conmode;
58 
59 #define LAST_ERROR rb_w32_map_errno(GetLastError())
60 #define SET_LAST_ERROR (errno = LAST_ERROR, 0)
61 
62 static int
63 setattr(int fd, conmode *t)
64 {
65  int x = SetConsoleMode((HANDLE)rb_w32_get_osfhandle(fd), *t);
66  if (!x) errno = LAST_ERROR;
67  return x;
68 }
69 
70 static int
71 getattr(int fd, conmode *t)
72 {
73  int x = GetConsoleMode((HANDLE)rb_w32_get_osfhandle(fd), t);
74  if (!x) errno = LAST_ERROR;
75  return x;
76 }
77 #endif
78 #ifndef SET_LAST_ERROR
79 #define SET_LAST_ERROR (0)
80 #endif
81 
82 static ID id_getc, id_console, id_close, id_min, id_time;
83 #if ENABLE_IO_GETPASS
84 static ID id_gets;
85 #endif
86 
87 #ifndef HAVE_RB_F_SEND
88 static ID id___send__;
89 
90 static VALUE
91 rb_f_send(int argc, VALUE *argv, VALUE recv)
92 {
93  VALUE sym = argv[0];
94  ID vid = rb_check_id(&sym);
95  if (vid) {
96  --argc;
97  ++argv;
98  }
99  else {
100  vid = id___send__;
101  }
102  return rb_funcallv(recv, vid, argc, argv);
103 }
104 #endif
105 
106 #ifndef HAVE_RB_SYM2STR
107 # define rb_sym2str(sym) rb_id2str(SYM2ID(sym))
108 #endif
109 
110 typedef struct {
111  int vmin;
112  int vtime;
113 } rawmode_arg_t;
114 
115 static rawmode_arg_t *
116 rawmode_opt(int argc, VALUE *argv, rawmode_arg_t *opts)
117 {
118  rawmode_arg_t *optp = NULL;
119  VALUE vopts;
120  rb_scan_args(argc, argv, "0:", &vopts);
121  if (!NIL_P(vopts)) {
122  VALUE vmin = rb_hash_aref(vopts, ID2SYM(id_min));
123  VALUE vtime = rb_hash_aref(vopts, ID2SYM(id_time));
124  /* default values by `stty raw` */
125  opts->vmin = 1;
126  opts->vtime = 0;
127  if (!NIL_P(vmin)) {
128  opts->vmin = NUM2INT(vmin);
129  optp = opts;
130  }
131  if (!NIL_P(vtime)) {
132  VALUE v10 = INT2FIX(10);
133  vtime = rb_funcall3(vtime, '*', 1, &v10);
134  opts->vtime = NUM2INT(vtime);
135  optp = opts;
136  }
137  }
138  return optp;
139 }
140 
141 static void
142 set_rawmode(conmode *t, void *arg)
143 {
144 #ifdef HAVE_CFMAKERAW
145  cfmakeraw(t);
146  t->c_lflag &= ~(ECHOE|ECHOK);
147 #elif defined HAVE_TERMIOS_H || defined HAVE_TERMIO_H
148  t->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
149  t->c_oflag &= ~OPOST;
150  t->c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHONL|ICANON|ISIG|IEXTEN);
151  t->c_cflag &= ~(CSIZE|PARENB);
152  t->c_cflag |= CS8;
153 #elif defined HAVE_SGTTY_H
154  t->sg_flags &= ~ECHO;
155  t->sg_flags |= RAW;
156 #elif defined _WIN32
157  *t = 0;
158 #endif
159 #if defined HAVE_TERMIOS_H || defined HAVE_TERMIO_H
160  if (arg) {
161  const rawmode_arg_t *r = arg;
162  if (r->vmin >= 0) t->c_cc[VMIN] = r->vmin;
163  if (r->vtime >= 0) t->c_cc[VTIME] = r->vtime;
164  }
165 #endif
166 }
167 
168 static void
169 set_cookedmode(conmode *t, void *arg)
170 {
171 #if defined HAVE_TERMIOS_H || defined HAVE_TERMIO_H
172  t->c_iflag |= (BRKINT|ISTRIP|ICRNL|IXON);
173  t->c_oflag |= OPOST;
174  t->c_lflag |= (ECHO|ECHOE|ECHOK|ECHONL|ICANON|ISIG|IEXTEN);
175 #elif defined HAVE_SGTTY_H
176  t->sg_flags |= ECHO;
177  t->sg_flags &= ~RAW;
178 #elif defined _WIN32
179  *t |= ENABLE_ECHO_INPUT|ENABLE_LINE_INPUT|ENABLE_PROCESSED_INPUT;
180 #endif
181 }
182 
183 static void
184 set_noecho(conmode *t, void *arg)
185 {
186 #if defined HAVE_TERMIOS_H || defined HAVE_TERMIO_H
187  t->c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
188 #elif defined HAVE_SGTTY_H
189  t->sg_flags &= ~ECHO;
190 #elif defined _WIN32
191  *t &= ~ENABLE_ECHO_INPUT;
192 #endif
193 }
194 
195 static void
196 set_echo(conmode *t, void *arg)
197 {
198 #if defined HAVE_TERMIOS_H || defined HAVE_TERMIO_H
199  t->c_lflag |= (ECHO | ECHOE | ECHOK | ECHONL);
200 #elif defined HAVE_SGTTY_H
201  t->sg_flags |= ECHO;
202 #elif defined _WIN32
203  *t |= ENABLE_ECHO_INPUT;
204 #endif
205 }
206 
207 static int
208 echo_p(conmode *t)
209 {
210 #if defined HAVE_TERMIOS_H || defined HAVE_TERMIO_H
211  return (t->c_lflag & (ECHO | ECHONL)) != 0;
212 #elif defined HAVE_SGTTY_H
213  return (t->sg_flags & ECHO) != 0;
214 #elif defined _WIN32
215  return (*t & ENABLE_ECHO_INPUT) != 0;
216 #endif
217 }
218 
219 static int
220 set_ttymode(int fd, conmode *t, void (*setter)(conmode *, void *), void *arg)
221 {
222  conmode r;
223  if (!getattr(fd, t)) return 0;
224  r = *t;
225  setter(&r, arg);
226  return setattr(fd, &r);
227 }
228 
229 #define GetReadFD(fptr) ((fptr)->fd)
230 
231 static inline int
232 get_write_fd(const rb_io_t *fptr)
233 {
234  VALUE wio = fptr->tied_io_for_writing;
235  rb_io_t *ofptr;
236  if (!wio) return fptr->fd;
237  GetOpenFile(wio, ofptr);
238  return ofptr->fd;
239 }
240 #define GetWriteFD(fptr) get_write_fd(fptr)
241 
242 #define FD_PER_IO 2
243 
244 static VALUE
245 ttymode(VALUE io, VALUE (*func)(VALUE), void (*setter)(conmode *, void *), void *arg)
246 {
247  rb_io_t *fptr;
248  int status = -1;
249  int error = 0;
250  int fd[FD_PER_IO];
251  conmode t[FD_PER_IO];
252  VALUE result = Qnil;
253 
254  GetOpenFile(io, fptr);
255  fd[0] = GetReadFD(fptr);
256  if (fd[0] != -1) {
257  if (set_ttymode(fd[0], t+0, setter, arg)) {
258  status = 0;
259  }
260  else {
261  error = errno;
262  fd[0] = -1;
263  }
264  }
265  fd[1] = GetWriteFD(fptr);
266  if (fd[1] != -1 && fd[1] != fd[0]) {
267  if (set_ttymode(fd[1], t+1, setter, arg)) {
268  status = 0;
269  }
270  else {
271  error = errno;
272  fd[1] = -1;
273  }
274  }
275  if (status == 0) {
276  result = rb_protect(func, io, &status);
277  }
278  GetOpenFile(io, fptr);
279  if (fd[0] != -1 && fd[0] == GetReadFD(fptr)) {
280  if (!setattr(fd[0], t+0)) {
281  error = errno;
282  status = -1;
283  }
284  }
285  if (fd[1] != -1 && fd[1] != fd[0] && fd[1] == GetWriteFD(fptr)) {
286  if (!setattr(fd[1], t+1)) {
287  error = errno;
288  status = -1;
289  }
290  }
291  if (status) {
292  if (status == -1) {
293  rb_syserr_fail(error, 0);
294  }
295  rb_jump_tag(status);
296  }
297  return result;
298 }
299 
300 /*
301  * call-seq:
302  * io.raw(min: nil, time: nil) {|io| }
303  *
304  * Yields +self+ within raw mode.
305  *
306  * STDIN.raw(&:gets)
307  *
308  * will read and return a line without echo back and line editing.
309  *
310  * You must require 'io/console' to use this method.
311  */
312 static VALUE
313 console_raw(int argc, VALUE *argv, VALUE io)
314 {
315  rawmode_arg_t opts, *optp = rawmode_opt(argc, argv, &opts);
316  return ttymode(io, rb_yield, set_rawmode, optp);
317 }
318 
319 /*
320  * call-seq:
321  * io.raw!(min: nil, time: nil)
322  *
323  * Enables raw mode.
324  *
325  * If the terminal mode needs to be back, use io.raw { ... }.
326  *
327  * You must require 'io/console' to use this method.
328  */
329 static VALUE
330 console_set_raw(int argc, VALUE *argv, VALUE io)
331 {
332  conmode t;
333  rb_io_t *fptr;
334  int fd;
335  rawmode_arg_t opts, *optp = rawmode_opt(argc, argv, &opts);
336 
337  GetOpenFile(io, fptr);
338  fd = GetReadFD(fptr);
339  if (!getattr(fd, &t)) rb_sys_fail(0);
340  set_rawmode(&t, optp);
341  if (!setattr(fd, &t)) rb_sys_fail(0);
342  return io;
343 }
344 
345 /*
346  * call-seq:
347  * io.cooked {|io| }
348  *
349  * Yields +self+ within cooked mode.
350  *
351  * STDIN.cooked(&:gets)
352  *
353  * will read and return a line with echo back and line editing.
354  *
355  * You must require 'io/console' to use this method.
356  */
357 static VALUE
358 console_cooked(VALUE io)
359 {
360  return ttymode(io, rb_yield, set_cookedmode, NULL);
361 }
362 
363 /*
364  * call-seq:
365  * io.cooked!
366  *
367  * Enables cooked mode.
368  *
369  * If the terminal mode needs to be back, use io.cooked { ... }.
370  *
371  * You must require 'io/console' to use this method.
372  */
373 static VALUE
374 console_set_cooked(VALUE io)
375 {
376  conmode t;
377  rb_io_t *fptr;
378  int fd;
379 
380  GetOpenFile(io, fptr);
381  fd = GetReadFD(fptr);
382  if (!getattr(fd, &t)) rb_sys_fail(0);
383  set_cookedmode(&t, NULL);
384  if (!setattr(fd, &t)) rb_sys_fail(0);
385  return io;
386 }
387 
388 static VALUE
389 getc_call(VALUE io)
390 {
391  return rb_funcallv(io, id_getc, 0, 0);
392 }
393 
394 /*
395  * call-seq:
396  * io.getch(min: nil, time: nil) -> char
397  *
398  * Reads and returns a character in raw mode.
399  *
400  * You must require 'io/console' to use this method.
401  */
402 static VALUE
403 console_getch(int argc, VALUE *argv, VALUE io)
404 {
405  rawmode_arg_t opts, *optp = rawmode_opt(argc, argv, &opts);
406  return ttymode(io, getc_call, set_rawmode, optp);
407 }
408 
409 /*
410  * call-seq:
411  * io.noecho {|io| }
412  *
413  * Yields +self+ with disabling echo back.
414  *
415  * STDIN.noecho(&:gets)
416  *
417  * will read and return a line without echo back.
418  *
419  * You must require 'io/console' to use this method.
420  */
421 static VALUE
422 console_noecho(VALUE io)
423 {
424  return ttymode(io, rb_yield, set_noecho, NULL);
425 }
426 
427 /*
428  * call-seq:
429  * io.echo = flag
430  *
431  * Enables/disables echo back.
432  * On some platforms, all combinations of this flags and raw/cooked
433  * mode may not be valid.
434  *
435  * You must require 'io/console' to use this method.
436  */
437 static VALUE
438 console_set_echo(VALUE io, VALUE f)
439 {
440  conmode t;
441  rb_io_t *fptr;
442  int fd;
443 
444  GetOpenFile(io, fptr);
445  fd = GetReadFD(fptr);
446  if (!getattr(fd, &t)) rb_sys_fail(0);
447  if (RTEST(f))
448  set_echo(&t, NULL);
449  else
450  set_noecho(&t, NULL);
451  if (!setattr(fd, &t)) rb_sys_fail(0);
452  return io;
453 }
454 
455 /*
456  * call-seq:
457  * io.echo? -> true or false
458  *
459  * Returns +true+ if echo back is enabled.
460  *
461  * You must require 'io/console' to use this method.
462  */
463 static VALUE
464 console_echo_p(VALUE io)
465 {
466  conmode t;
467  rb_io_t *fptr;
468  int fd;
469 
470  GetOpenFile(io, fptr);
471  fd = GetReadFD(fptr);
472  if (!getattr(fd, &t)) rb_sys_fail(0);
473  return echo_p(&t) ? Qtrue : Qfalse;
474 }
475 
476 #if defined TIOCGWINSZ
477 typedef struct winsize rb_console_size_t;
478 #define getwinsize(fd, buf) (ioctl((fd), TIOCGWINSZ, (buf)) == 0)
479 #define setwinsize(fd, buf) (ioctl((fd), TIOCSWINSZ, (buf)) == 0)
480 #define winsize_row(buf) (buf)->ws_row
481 #define winsize_col(buf) (buf)->ws_col
482 #elif defined _WIN32
483 typedef CONSOLE_SCREEN_BUFFER_INFO rb_console_size_t;
484 #define getwinsize(fd, buf) ( \
485  GetConsoleScreenBufferInfo((HANDLE)rb_w32_get_osfhandle(fd), (buf)) || \
486  SET_LAST_ERROR)
487 #define winsize_row(buf) ((buf)->srWindow.Bottom - (buf)->srWindow.Top + 1)
488 #define winsize_col(buf) (buf)->dwSize.X
489 #endif
490 
491 #if defined TIOCGWINSZ || defined _WIN32
492 #define USE_CONSOLE_GETSIZE 1
493 #endif
494 
495 #ifdef USE_CONSOLE_GETSIZE
496 /*
497  * call-seq:
498  * io.winsize -> [rows, columns]
499  *
500  * Returns console size.
501  *
502  * You must require 'io/console' to use this method.
503  */
504 static VALUE
505 console_winsize(VALUE io)
506 {
507  rb_io_t *fptr;
508  int fd;
509  rb_console_size_t ws;
510 
511  GetOpenFile(io, fptr);
512  fd = GetWriteFD(fptr);
513  if (!getwinsize(fd, &ws)) rb_sys_fail(0);
514  return rb_assoc_new(INT2NUM(winsize_row(&ws)), INT2NUM(winsize_col(&ws)));
515 }
516 
517 /*
518  * call-seq:
519  * io.winsize = [rows, columns]
520  *
521  * Tries to set console size. The effect depends on the platform and
522  * the running environment.
523  *
524  * You must require 'io/console' to use this method.
525  */
526 static VALUE
527 console_set_winsize(VALUE io, VALUE size)
528 {
529  rb_io_t *fptr;
530  rb_console_size_t ws;
531 #if defined _WIN32
532  HANDLE wh;
533  int newrow, newcol;
534  BOOL ret;
535 #endif
536  VALUE row, col, xpixel, ypixel;
537  const VALUE *sz;
538  int fd;
539  long sizelen;
540 
541  GetOpenFile(io, fptr);
542  size = rb_Array(size);
543  if ((sizelen = RARRAY_LEN(size)) != 2 && sizelen != 4) {
545  "wrong number of arguments (given %ld, expected 2 or 4)",
546  sizelen);
547  }
548  sz = RARRAY_CONST_PTR(size);
549  row = sz[0], col = sz[1], xpixel = ypixel = Qnil;
550  if (sizelen == 4) xpixel = sz[2], ypixel = sz[3];
551  fd = GetWriteFD(fptr);
552 #if defined TIOCSWINSZ
553  ws.ws_row = ws.ws_col = ws.ws_xpixel = ws.ws_ypixel = 0;
554 #define SET(m) ws.ws_##m = NIL_P(m) ? 0 : (unsigned short)NUM2UINT(m)
555  SET(row);
556  SET(col);
557  SET(xpixel);
558  SET(ypixel);
559 #undef SET
560  if (!setwinsize(fd, &ws)) rb_sys_fail(0);
561 #elif defined _WIN32
562  wh = (HANDLE)rb_w32_get_osfhandle(fd);
563 #define SET(m) new##m = NIL_P(m) ? 0 : (unsigned short)NUM2UINT(m)
564  SET(row);
565  SET(col);
566 #undef SET
567  if (!NIL_P(xpixel)) (void)NUM2UINT(xpixel);
568  if (!NIL_P(ypixel)) (void)NUM2UINT(ypixel);
569  if (!GetConsoleScreenBufferInfo(wh, &ws)) {
570  rb_syserr_fail(LAST_ERROR, "GetConsoleScreenBufferInfo");
571  }
572  ws.dwSize.X = newcol;
573  ret = SetConsoleScreenBufferSize(wh, ws.dwSize);
574  ws.srWindow.Left = 0;
575  ws.srWindow.Top = 0;
576  ws.srWindow.Right = newcol-1;
577  ws.srWindow.Bottom = newrow-1;
578  if (!SetConsoleWindowInfo(wh, TRUE, &ws.srWindow)) {
579  rb_syserr_fail(LAST_ERROR, "SetConsoleWindowInfo");
580  }
581  /* retry when shrinking buffer after shrunk window */
582  if (!ret && !SetConsoleScreenBufferSize(wh, ws.dwSize)) {
583  rb_syserr_fail(LAST_ERROR, "SetConsoleScreenBufferInfo");
584  }
585  /* remove scrollbar if possible */
586  if (!SetConsoleWindowInfo(wh, TRUE, &ws.srWindow)) {
587  rb_syserr_fail(LAST_ERROR, "SetConsoleWindowInfo");
588  }
589 #endif
590  return io;
591 }
592 #endif
593 
594 /*
595  * call-seq:
596  * io.iflush
597  *
598  * Flushes input buffer in kernel.
599  *
600  * You must require 'io/console' to use this method.
601  */
602 static VALUE
603 console_iflush(VALUE io)
604 {
605  rb_io_t *fptr;
606  int fd;
607 
608  GetOpenFile(io, fptr);
609  fd = GetReadFD(fptr);
610 #if defined HAVE_TERMIOS_H || defined HAVE_TERMIO_H
611  if (tcflush(fd, TCIFLUSH)) rb_sys_fail(0);
612 #endif
613  (void)fd;
614  return io;
615 }
616 
617 /*
618  * call-seq:
619  * io.oflush
620  *
621  * Flushes output buffer in kernel.
622  *
623  * You must require 'io/console' to use this method.
624  */
625 static VALUE
626 console_oflush(VALUE io)
627 {
628  rb_io_t *fptr;
629  int fd;
630 
631  GetOpenFile(io, fptr);
632  fd = GetWriteFD(fptr);
633 #if defined HAVE_TERMIOS_H || defined HAVE_TERMIO_H
634  if (tcflush(fd, TCOFLUSH)) rb_sys_fail(0);
635 #endif
636  (void)fd;
637  return io;
638 }
639 
640 /*
641  * call-seq:
642  * io.ioflush
643  *
644  * Flushes input and output buffers in kernel.
645  *
646  * You must require 'io/console' to use this method.
647  */
648 static VALUE
649 console_ioflush(VALUE io)
650 {
651  rb_io_t *fptr;
652 #if defined HAVE_TERMIOS_H || defined HAVE_TERMIO_H
653  int fd1, fd2;
654 #endif
655 
656  GetOpenFile(io, fptr);
657 #if defined HAVE_TERMIOS_H || defined HAVE_TERMIO_H
658  fd1 = GetReadFD(fptr);
659  fd2 = GetWriteFD(fptr);
660  if (fd2 != -1 && fd1 != fd2) {
661  if (tcflush(fd1, TCIFLUSH)) rb_sys_fail(0);
662  if (tcflush(fd2, TCOFLUSH)) rb_sys_fail(0);
663  }
664  else {
665  if (tcflush(fd1, TCIOFLUSH)) rb_sys_fail(0);
666  }
667 #endif
668  return io;
669 }
670 
671 static VALUE
672 console_beep(VALUE io)
673 {
674  rb_io_t *fptr;
675  int fd;
676 
677  GetOpenFile(io, fptr);
678  fd = GetWriteFD(fptr);
679 #ifdef _WIN32
680  (void)fd;
681  MessageBeep(0);
682 #else
683  if (write(fd, "\a", 1) < 0)
684  rb_sys_fail(0);
685 #endif
686  return io;
687 }
688 
689 #if defined _WIN32
690 static VALUE
691 console_goto(VALUE io, VALUE x, VALUE y)
692 {
693  rb_io_t *fptr;
694  int fd;
695  COORD pos;
696 
697  GetOpenFile(io, fptr);
698  fd = GetWriteFD(fptr);
699  pos.X = NUM2UINT(x);
700  pos.Y = NUM2UINT(y);
701  if (!SetConsoleCursorPosition((HANDLE)rb_w32_get_osfhandle(fd), pos)) {
702  rb_syserr_fail(LAST_ERROR, 0);
703  }
704  return io;
705 }
706 
707 static VALUE
709 {
710  rb_io_t *fptr;
711  int fd;
712  rb_console_size_t ws;
713 
714  GetOpenFile(io, fptr);
715  fd = GetWriteFD(fptr);
716  if (!GetConsoleScreenBufferInfo((HANDLE)rb_w32_get_osfhandle(fd), &ws)) {
717  rb_syserr_fail(LAST_ERROR, 0);
718  }
719  return rb_assoc_new(UINT2NUM(ws.dwCursorPosition.X), UINT2NUM(ws.dwCursorPosition.Y));
720 }
721 
722 static VALUE
724 {
725  cpos = rb_convert_type(cpos, T_ARRAY, "Array", "to_ary");
726  if (RARRAY_LEN(cpos) != 2) rb_raise(rb_eArgError, "expected 2D coordinate");
727  return console_goto(io, RARRAY_AREF(cpos, 0), RARRAY_AREF(cpos, 1));
728 }
729 
730 #include "win32_vk.inc"
731 
732 static VALUE
734 {
735  int vk = -1;
736 
737  if (FIXNUM_P(k)) {
738  vk = NUM2UINT(k);
739  }
740  else {
741  const struct vktable *t;
742  const char *kn;
743  if (SYMBOL_P(k)) {
744  k = rb_sym2str(k);
745  kn = RSTRING_PTR(k);
746  }
747  else {
748  kn = StringValuePtr(k);
749  }
750  t = console_win32_vk(kn, RSTRING_LEN(k));
751  if (!t || (vk = (short)t->vk) == -1) {
752  rb_raise(rb_eArgError, "unknown virtual key code: % "PRIsVALUE, k);
753  }
754  }
755  return GetKeyState(vk) & 0x80 ? Qtrue : Qfalse;
756 }
757 #else
758 # define console_goto rb_f_notimplement
759 # define console_cursor_pos rb_f_notimplement
760 # define console_cursor_set rb_f_notimplement
761 # define console_key_pressed_p rb_f_notimplement
762 #endif
763 
764 /*
765  * call-seq:
766  * IO.console -> #<File:/dev/tty>
767  * IO.console(sym, *args)
768  *
769  * Returns an File instance opened console.
770  *
771  * If +sym+ is given, it will be sent to the opened console with
772  * +args+ and the result will be returned instead of the console IO
773  * itself.
774  *
775  * You must require 'io/console' to use this method.
776  */
777 static VALUE
778 console_dev(int argc, VALUE *argv, VALUE klass)
779 {
780  VALUE con = 0;
781  rb_io_t *fptr;
782  VALUE sym = 0;
783 
785  if (argc) {
786  Check_Type(sym = argv[0], T_SYMBOL);
787  }
788  if (klass == rb_cIO) klass = rb_cFile;
789  if (rb_const_defined(klass, id_console)) {
790  con = rb_const_get(klass, id_console);
791  if (!RB_TYPE_P(con, T_FILE) ||
792  (!(fptr = RFILE(con)->fptr) || GetReadFD(fptr) == -1)) {
793  rb_const_remove(klass, id_console);
794  con = 0;
795  }
796  }
797  if (sym) {
798  if (sym == ID2SYM(id_close) && argc == 1) {
799  if (con) {
800  rb_io_close(con);
801  rb_const_remove(klass, id_console);
802  con = 0;
803  }
804  return Qnil;
805  }
806  }
807  if (!con) {
808  VALUE args[2];
809 #if defined HAVE_TERMIOS_H || defined HAVE_TERMIO_H || defined HAVE_SGTTY_H
810 # define CONSOLE_DEVICE "/dev/tty"
811 #elif defined _WIN32
812 # define CONSOLE_DEVICE "con$"
813 # define CONSOLE_DEVICE_FOR_READING "conin$"
814 # define CONSOLE_DEVICE_FOR_WRITING "conout$"
815 #endif
816 #ifndef CONSOLE_DEVICE_FOR_READING
817 # define CONSOLE_DEVICE_FOR_READING CONSOLE_DEVICE
818 #endif
819 #ifdef CONSOLE_DEVICE_FOR_WRITING
820  VALUE out;
821  rb_io_t *ofptr;
822 #endif
823  int fd;
824 
825 #ifdef CONSOLE_DEVICE_FOR_WRITING
826  fd = rb_cloexec_open(CONSOLE_DEVICE_FOR_WRITING, O_RDWR, 0);
827  if (fd < 0) return Qnil;
828  rb_update_max_fd(fd);
829  args[1] = INT2FIX(O_WRONLY);
830  args[0] = INT2NUM(fd);
831  out = rb_class_new_instance(2, args, klass);
832 #endif
834  if (fd < 0) {
835 #ifdef CONSOLE_DEVICE_FOR_WRITING
836  rb_io_close(out);
837 #endif
838  return Qnil;
839  }
840  rb_update_max_fd(fd);
841  args[1] = INT2FIX(O_RDWR);
842  args[0] = INT2NUM(fd);
843  con = rb_class_new_instance(2, args, klass);
844  GetOpenFile(con, fptr);
845  fptr->pathv = rb_obj_freeze(rb_str_new2(CONSOLE_DEVICE));
846 #ifdef CONSOLE_DEVICE_FOR_WRITING
847  GetOpenFile(out, ofptr);
848  ofptr->pathv = fptr->pathv;
849  fptr->tied_io_for_writing = out;
850  ofptr->mode |= FMODE_SYNC;
851 #endif
852  fptr->mode |= FMODE_SYNC;
853  rb_const_set(klass, id_console, con);
854  }
855  if (sym) {
856  return rb_f_send(argc, argv, con);
857  }
858  return con;
859 }
860 
861 /*
862  * call-seq:
863  * io.getch(min: nil, time: nil) -> char
864  *
865  * See IO#getch.
866  */
867 static VALUE
868 io_getch(int argc, VALUE *argv, VALUE io)
869 {
870  return rb_funcallv(io, id_getc, argc, argv);
871 }
872 
873 #if ENABLE_IO_GETPASS
874 static VALUE
875 puts_call(VALUE io)
876 {
877  return rb_io_write(io, rb_default_rs);
878 }
879 
880 static VALUE
881 getpass_call(VALUE io)
882 {
883  return ttymode(io, rb_io_gets, set_noecho, NULL);
884 }
885 
886 static void
887 prompt(int argc, VALUE *argv, VALUE io)
888 {
889  if (argc > 0 && !NIL_P(argv[0])) {
890  VALUE str = argv[0];
891  StringValueCStr(str);
892  rb_check_safe_obj(str);
893  rb_io_write(io, str);
894  }
895 }
896 
897 static VALUE
898 str_chomp(VALUE str)
899 {
900  if (!NIL_P(str)) {
901  str = rb_funcallv(str, rb_intern("chomp!"), 0, 0);
902  }
903  return str;
904 }
905 
906 /*
907  * call-seq:
908  * io.getpass(prompt=nil) -> string
909  *
910  * Reads and returns a line without echo back.
911  * Prints +prompt+ unless it is +nil+.
912  *
913  * You must require 'io/console' to use this method.
914  */
915 static VALUE
916 console_getpass(int argc, VALUE *argv, VALUE io)
917 {
918  VALUE str, wio;
919 
920  rb_check_arity(argc, 0, 1);
921  wio = rb_io_get_write_io(io);
922  if (wio == io && io == rb_stdin) wio = rb_stderr;
923  prompt(argc, argv, wio);
924  str = rb_ensure(getpass_call, io, puts_call, wio);
925  return str_chomp(str);
926 }
927 
928 /*
929  * call-seq:
930  * io.getpass(prompt=nil) -> string
931  *
932  * See IO#getpass.
933  */
934 static VALUE
935 io_getpass(int argc, VALUE *argv, VALUE io)
936 {
937  VALUE str;
938 
939  rb_check_arity(argc, 0, 1);
940  prompt(argc, argv, io);
941  str = str_chomp(rb_funcallv(io, id_gets, 0, 0));
942  puts_call(io);
943  return str;
944 }
945 #endif
946 
947 /*
948  * IO console methods
949  */
950 void
952 {
953 #undef rb_intern
954  id_getc = rb_intern("getc");
955 #if ENABLE_IO_GETPASS
956  id_gets = rb_intern("gets");
957 #endif
958  id_console = rb_intern("console");
959  id_close = rb_intern("close");
960  id_min = rb_intern("min");
961  id_time = rb_intern("time");
962 #ifndef HAVE_RB_F_SEND
963  id___send__ = rb_intern("__send__");
964 #endif
965  InitVM(console);
966 }
967 
968 void
970 {
971  rb_define_method(rb_cIO, "raw", console_raw, -1);
972  rb_define_method(rb_cIO, "raw!", console_set_raw, -1);
973  rb_define_method(rb_cIO, "cooked", console_cooked, 0);
974  rb_define_method(rb_cIO, "cooked!", console_set_cooked, 0);
975  rb_define_method(rb_cIO, "getch", console_getch, -1);
976  rb_define_method(rb_cIO, "echo=", console_set_echo, 1);
977  rb_define_method(rb_cIO, "echo?", console_echo_p, 0);
978  rb_define_method(rb_cIO, "noecho", console_noecho, 0);
979  rb_define_method(rb_cIO, "winsize", console_winsize, 0);
980  rb_define_method(rb_cIO, "winsize=", console_set_winsize, 1);
981  rb_define_method(rb_cIO, "iflush", console_iflush, 0);
982  rb_define_method(rb_cIO, "oflush", console_oflush, 0);
983  rb_define_method(rb_cIO, "ioflush", console_ioflush, 0);
984  rb_define_method(rb_cIO, "beep", console_beep, 0);
985  rb_define_method(rb_cIO, "goto", console_goto, 2);
989 #if ENABLE_IO_GETPASS
990  rb_define_method(rb_cIO, "getpass", console_getpass, -1);
991 #endif
992  rb_define_singleton_method(rb_cIO, "console", console_dev, -1);
993  {
994  VALUE mReadable = rb_define_module_under(rb_cIO, "generic_readable");
995  rb_define_method(mReadable, "getch", io_getch, -1);
996 #if ENABLE_IO_GETPASS
997  rb_define_method(mReadable, "getpass", io_getpass, -1);
998 #endif
999  }
1000 }
#define SET(a, b, c, d, k, s, Ti)
#define T_SYMBOL
Definition: ruby.h:508
ID rb_check_id(volatile VALUE *)
Returns ID for the given name if it is interned already, or 0.
Definition: symbol.c:915
#define GetReadFD(fptr)
Definition: console.c:229
VALUE rb_protect(VALUE(*proc)(VALUE), VALUE data, int *pstate)
Protects a function call from potential global escapes from the function.
Definition: eval.c:992
#define RARRAY_LEN(a)
Definition: ruby.h:1019
void rb_syserr_fail(int e, const char *mesg)
Definition: error.c:2391
#define console_cursor_set
Definition: console.c:760
#define INT2NUM(x)
Definition: ruby.h:1538
void rb_update_max_fd(int fd)
Definition: io.c:191
#define FD_PER_IO
Definition: console.c:242
#define NUM2INT(x)
Definition: ruby.h:684
void Init_console(void)
Definition: console.c:951
#define NUM2UINT(x)
Definition: ruby.h:685
void rb_define_singleton_method(VALUE obj, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a singleton method for obj.
Definition: class.c:1716
int rb_cloexec_open(const char *pathname, int flags, mode_t mode)
Definition: io.c:257
void rb_raise(VALUE exc, const char *fmt,...)
Definition: error.c:2284
#define InitVM(ext)
Definition: ruby.h:2164
void rb_jump_tag(int tag)
Continues the exception caught by rb_protect() and rb_eval_string_protect().
Definition: eval.c:821
#define Qtrue
Definition: ruby.h:437
Definition: io.h:62
SOCKET rb_w32_get_osfhandle(int)
Definition: win32.c:1064
RUBY_EXTERN VALUE rb_stdin
Definition: ruby.h:1971
#define rb_check_arity
Definition: intern.h:298
VALUE rb_cFile
Definition: file.c:139
#define GetWriteFD(fptr)
Definition: console.c:240
#define Check_Type(v, t)
Definition: ruby.h:562
int rb_const_defined(VALUE, ID)
Definition: variable.c:2537
#define T_ARRAY
Definition: ruby.h:498
VALUE rb_io_write(VALUE, VALUE)
Definition: io.c:1510
#define RFILE(obj)
Definition: ruby.h:1206
VALUE rb_ensure(VALUE(*b_proc)(ANYARGS), VALUE data1, VALUE(*e_proc)(ANYARGS), VALUE data2)
An equivalent to ensure clause.
Definition: eval.c:1035
#define FIXNUM_P(f)
Definition: ruby.h:365
#define GetOpenFile(obj, fp)
Definition: io.h:120
void InitVM_console(void)
Definition: console.c:969
VALUE rb_eArgError
Definition: error.c:802
#define sym(x)
Definition: date_core.c:3721
int mode
Definition: io.h:65
#define RB_TYPE_P(obj, type)
Definition: ruby.h:527
VALUE rb_io_get_write_io(VALUE io)
Definition: io.c:670
IUnknown DWORD
Definition: win32ole.c:32
#define CONSOLE_DEVICE_FOR_READING
#define UINT2NUM(x)
Definition: ruby.h:1539
#define console_key_pressed_p
Definition: console.c:761
#define NIL_P(v)
Definition: ruby.h:451
int fd
Definition: io.h:64
int argc
Definition: ruby.c:187
#define Qfalse
Definition: ruby.h:436
VALUE rb_Array(VALUE)
Equivalent to Kernel#Array in Ruby.
Definition: object.c:3592
#define rb_str_new2
Definition: intern.h:835
#define console_goto
Definition: console.c:758
void rb_sys_fail(const char *mesg)
Definition: error.c:2403
VALUE rb_const_get(VALUE, ID)
Definition: variable.c:2292
RUBY_EXTERN VALUE rb_cIO
Definition: ruby.h:1913
#define RSTRING_LEN(str)
Definition: ruby.h:971
VALUE rb_yield(VALUE)
Definition: vm_eval.c:973
#define RARRAY_CONST_PTR(a)
Definition: ruby.h:1021
int errno
#define TRUE
Definition: nkf.h:175
VALUE rb_obj_freeze(VALUE)
call-seq: obj.freeze -> obj
Definition: object.c:1331
VALUE rb_io_gets(VALUE)
Definition: io.c:3281
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Definition: class.c:1908
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Definition: array.c:639
#define PRIsVALUE
Definition: ruby.h:135
unsigned long ID
Definition: ruby.h:86
VALUE tied_io_for_writing
Definition: io.h:73
#define Qnil
Definition: ruby.h:438
void rb_const_set(VALUE, ID, VALUE)
Definition: variable.c:2573
VALUE rb_io_close(VALUE)
Definition: io.c:4501
unsigned long VALUE
Definition: ruby.h:85
#define rb_funcallv
Definition: console.c:21
VALUE rb_define_module_under(VALUE outer, const char *name)
Definition: class.c:790
#define StringValueCStr(v)
Definition: ruby.h:571
RUBY_EXTERN VALUE rb_default_rs
Definition: intern.h:517
#define RSTRING_PTR(str)
Definition: ruby.h:975
RUBY_EXTERN VALUE rb_stderr
Definition: ruby.h:1971
int size
Definition: encoding.c:57
#define f
#define INT2FIX(i)
Definition: ruby.h:232
#define UNLIMITED_ARGUMENTS
Definition: intern.h:44
#define RARRAY_AREF(a, i)
Definition: ruby.h:1033
VALUE rb_hash_aref(VALUE hash, VALUE key)
Definition: hash.c:831
VALUE rb_convert_type(VALUE, int, const char *, const char *)
Converts an object into another type.
Definition: object.c:2965
#define rb_funcall3
Definition: ruby.h:1792
VALUE pathv
Definition: io.h:68
#define RTEST(v)
Definition: ruby.h:450
VALUE rb_class_new_instance(int, const VALUE *, VALUE)
Allocates and initializes an instance of klass.
Definition: object.c:2170
void rb_check_safe_obj(VALUE)
Definition: safe.c:117
#define T_FILE
Definition: ruby.h:502
#define console_cursor_pos
Definition: console.c:759
#define ID2SYM(x)
Definition: ruby.h:383
#define FMODE_SYNC
Definition: io.h:106
#define StringValuePtr(v)
Definition: ruby.h:570
#define rb_intern(str)
#define SYMBOL_P(x)
Definition: ruby.h:382
VALUE rb_const_remove(VALUE, ID)
Definition: variable.c:2344
#define NULL
Definition: _sdbm.c:102
void rb_define_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Definition: class.c:1515
char ** argv
Definition: ruby.c:188
#define rb_sym2str(sym)
Definition: console.c:107