2009-03-16 Gonzalo Paniagua Javier <gonzalo@novell.com>
[mono.git] / mono / metadata / console-io.c
1 /*
2  * console-io.c: ConsoleDriver internal calls
3  *
4  * Author:
5  *      Gonzalo Paniagua Javier (gonzalo@ximian.com)
6  *
7  * Copyright (C) 2005-2008 Novell, Inc. (http://www.novell.com)
8  */
9
10 #include <config.h>
11 #include <glib.h>
12 #include <stdio.h>
13 #include <string.h>
14 #include <errno.h>
15 #include <signal.h>
16 #ifdef HAVE_SYS_TIME_H
17 #include <sys/time.h>
18 #endif
19 #include <sys/types.h>
20 #ifdef HAVE_UNISTD_H
21 #include <unistd.h>
22 #endif
23 #include <mono/metadata/appdomain.h>
24 #include <mono/metadata/object-internals.h>
25 #include <mono/metadata/class-internals.h>
26 #include <mono/metadata/domain-internals.h>
27 #include <mono/metadata/metadata.h>
28 #include <mono/metadata/threadpool.h>
29 /* On solaris, curses.h must come before both termios.h and term.h */
30 #ifdef HAVE_CURSES_H
31 #include <curses.h>
32 #endif
33 #ifdef HAVE_TERMIOS_H
34 #include <termios.h>
35 #endif
36 #ifdef HAVE_TERM_H
37 #include <term.h>
38 #endif
39 /* Needed for FIONREAD under solaris */
40 #ifdef HAVE_SYS_FILIO_H
41 #include <sys/filio.h>
42 #endif
43 #ifndef TIOCGWINSZ
44 #ifdef HAVE_SYS_IOCTL_H
45 #include <sys/ioctl.h>
46 #endif
47 #endif
48
49 #include <mono/metadata/console-io.h>
50 #include <mono/metadata/exception.h>
51
52 static gboolean setup_finished;
53 static gboolean atexit_called;
54
55 /* The string used to return the terminal to its previous state */
56 static gchar *teardown_str;
57
58 /* The string used to set the terminal into keypad xmit mode after SIGCONT is received */
59 static gchar *keypad_xmit_str;
60
61 #ifdef HAVE_TERMIOS_H
62 /* This is the last state used by Mono, used after a CONT signal is received */
63 static struct termios mono_attr;
64 #endif
65
66 #if defined (PLATFORM_WIN32) || defined (MONO_NULL_TTYDRIVER)
67 MonoBoolean
68 ves_icall_System_ConsoleDriver_Isatty (HANDLE handle)
69 {
70         MONO_ARCH_SAVE_REGS;
71
72         return (GetFileType (handle) == FILE_TYPE_CHAR);
73 }
74
75 MonoBoolean
76 ves_icall_System_ConsoleDriver_SetEcho (MonoBoolean want_echo)
77 {
78         return FALSE;
79 }
80
81 MonoBoolean
82 ves_icall_System_ConsoleDriver_SetBreak (MonoBoolean want_break)
83 {
84         return FALSE;
85 }
86
87 gint32
88 ves_icall_System_ConsoleDriver_InternalKeyAvailable (gint32 timeout)
89 {
90         return FALSE;
91 }
92
93 MonoBoolean
94 ves_icall_System_ConsoleDriver_TtySetup (MonoString *keypad, MonoString *teardown, char *verase, char *vsusp, char*intr, int **size)
95 {
96         return FALSE;
97 }
98
99 #else
100 static struct termios initial_attr;
101
102 MonoBoolean
103 ves_icall_System_ConsoleDriver_Isatty (HANDLE handle)
104 {
105         MONO_ARCH_SAVE_REGS;
106
107         return isatty (GPOINTER_TO_INT (handle));
108 }
109
110 static MonoBoolean
111 set_property (gint property, gboolean value)
112 {
113         struct termios attr;
114         gboolean callset = FALSE;
115         gboolean check;
116         
117         MONO_ARCH_SAVE_REGS;
118
119         if (tcgetattr (STDIN_FILENO, &attr) == -1)
120                 return FALSE;
121
122         check = (attr.c_lflag & property) != 0;
123         if ((value || check) && !(value && check)) {
124                 callset = TRUE;
125                 if (value)
126                         attr.c_lflag |= property;
127                 else
128                         attr.c_lflag &= ~property;
129         }
130
131         if (!callset)
132                 return TRUE;
133
134         if (tcsetattr (STDIN_FILENO, TCSANOW, &attr) == -1)
135                 return FALSE;
136
137         mono_attr = attr;
138         return TRUE;
139 }
140
141 MonoBoolean
142 ves_icall_System_ConsoleDriver_SetEcho (MonoBoolean want_echo)
143 {
144         
145         return set_property (ECHO, want_echo);
146 }
147
148 MonoBoolean
149 ves_icall_System_ConsoleDriver_SetBreak (MonoBoolean want_break)
150 {
151         return set_property (IGNBRK, !want_break);
152 }
153
154 gint32
155 ves_icall_System_ConsoleDriver_InternalKeyAvailable (gint32 timeout)
156 {
157         fd_set rfds;
158         struct timeval tv;
159         struct timeval *tvptr;
160         div_t divvy;
161         int ret, nbytes;
162
163         MONO_ARCH_SAVE_REGS;
164
165         do {
166                 FD_ZERO (&rfds);
167                 FD_SET (STDIN_FILENO, &rfds);
168                 if (timeout >= 0) {
169                         divvy = div (timeout, 1000);
170                         tv.tv_sec = divvy.quot;
171                         tv.tv_usec = divvy.rem;
172                         tvptr = &tv;
173                 } else {
174                         tvptr = NULL;
175                 }
176                 ret = select (STDIN_FILENO + 1, &rfds, NULL, NULL, tvptr);
177         } while (ret == -1 && errno == EINTR);
178
179         if (ret > 0) {
180                 nbytes = 0;
181                 ret = ioctl (STDIN_FILENO, FIONREAD, &nbytes);
182                 if (ret >= 0)
183                         ret = nbytes;
184         }
185
186         return (ret > 0) ? ret : 0;
187 }
188
189 static gint32 cols_and_lines;
190
191 #ifdef TIOCGWINSZ
192 static int
193 terminal_get_dimensions (void)
194 {
195         struct winsize ws;
196
197         if (ioctl (STDIN_FILENO, TIOCGWINSZ, &ws) == 0)
198                 return (ws.ws_col << 16) | ws.ws_row;
199
200         return -1;
201 }
202 #else
203 static int
204 terminal_get_dimensions (void)
205 {
206         return -1;
207 }
208 #endif
209
210 static void
211 tty_teardown (void)
212 {
213         MONO_ARCH_SAVE_REGS;
214
215         if (!setup_finished)
216                 return;
217
218         if (teardown_str != NULL) {
219                 write (STDOUT_FILENO, teardown_str, strlen (teardown_str));
220                 g_free (teardown_str);
221                 teardown_str = NULL;
222         }
223
224         tcflush (STDIN_FILENO, TCIFLUSH);
225         tcsetattr (STDIN_FILENO, TCSANOW, &initial_attr);
226         set_property (ECHO, TRUE);
227         setup_finished = FALSE;
228 }
229
230 static void
231 do_console_cancel_event (void)
232 {
233         static MonoClassField *cancel_handler_field;
234         MonoDomain *domain = mono_domain_get ();
235         MonoClass *klass;
236         MonoDelegate *load_value;
237         MonoMethod *method;
238         MonoMethodMessage *msg;
239         MonoMethod *im;
240
241         if (!domain->domain)
242                 return;
243
244         klass = mono_class_from_name (mono_defaults.corlib, "System", "Console");
245         if (klass == NULL)
246                 return;
247
248         if (cancel_handler_field == NULL) {
249                 cancel_handler_field = mono_class_get_field_from_name (klass, "cancel_handler");
250                 g_assert (cancel_handler_field);
251         }
252
253         mono_field_static_get_value (mono_class_vtable (domain, klass), cancel_handler_field, &load_value);
254         if (load_value == NULL)
255                 return;
256
257         klass = load_value->object.vtable->klass;
258         method = mono_class_get_method_from_name (klass, "BeginInvoke", -1);
259         g_assert (method != NULL);
260         im = mono_get_delegate_invoke (method->klass);
261         msg = mono_method_call_message_new (method, NULL, im, NULL, NULL);
262         mono_thread_pool_add ((MonoObject *) load_value, msg, NULL, NULL);
263 }
264
265 static gboolean in_sigint;
266 static void
267 sigint_handler (int signo)
268 {
269         MONO_ARCH_SAVE_REGS;
270
271         if (in_sigint)
272                 return;
273
274         in_sigint = TRUE;
275         do_console_cancel_event ();
276         in_sigint = FALSE;
277 }
278
279 static struct sigaction save_sigcont, save_sigint, save_sigwinch;
280
281 static void
282 sigcont_handler (int signo, void *the_siginfo, void *data)
283 {
284         // Ignore error, there is not much we can do in the sigcont handler.
285         tcsetattr (STDIN_FILENO, TCSANOW, &mono_attr);
286
287         if (keypad_xmit_str != NULL)
288                 write (STDOUT_FILENO, keypad_xmit_str, strlen (keypad_xmit_str));
289
290         // Call previous handler
291         if (save_sigcont.sa_sigaction != NULL &&
292             save_sigcont.sa_sigaction != (void *)SIG_DFL &&
293             save_sigcont.sa_sigaction != (void *)SIG_IGN)
294                 (*save_sigcont.sa_sigaction) (signo, the_siginfo, data);
295 }
296
297 static void
298 sigwinch_handler (int signo, void *the_siginfo, void *data)
299 {
300         int dims = terminal_get_dimensions ();
301         if (dims != -1)
302                 cols_and_lines = dims;
303         
304         // Call previous handler
305         if (save_sigwinch.sa_sigaction != NULL &&
306             save_sigwinch.sa_sigaction != (void *)SIG_DFL &&
307             save_sigwinch.sa_sigaction != (void *)SIG_IGN)
308                 (*save_sigwinch.sa_sigaction) (signo, the_siginfo, data);
309 }
310
311 void
312 console_set_signal_handlers ()
313 {
314         struct sigaction sigcont, sigint, sigwinch;
315
316         memset (&sigcont, 0, sizeof (struct sigaction));
317         memset (&sigint, 0, sizeof (struct sigaction));
318         memset (&sigwinch, 0, sizeof (struct sigaction));
319         
320         // Continuing
321         sigcont.sa_handler = (void *) sigcont_handler;
322         sigcont.sa_flags = 0;
323         sigemptyset (&sigcont.sa_mask);
324         sigaction (SIGCONT, &sigcont, &save_sigcont);
325         
326         // Interrupt handler
327         sigint.sa_handler = sigint_handler;
328         sigint.sa_flags = 0;
329         sigemptyset (&sigint.sa_mask);
330         sigaction (SIGINT, &sigint, &save_sigint);
331
332         // Window size changed
333         sigwinch.sa_handler = (void *) sigwinch_handler;
334         sigwinch.sa_flags = 0;
335         sigemptyset (&sigwinch.sa_mask);
336         sigaction (SIGWINCH, &sigwinch, &save_sigwinch);
337 }
338
339 //
340 // Currently unused, should we ever call the restore handler?
341 // Perhaps before calling into Process.Start?
342 //
343 void
344 console_restore_signal_handlers ()
345 {
346         sigaction (SIGCONT, &save_sigcont, NULL);
347         sigaction (SIGINT, &save_sigint, NULL);
348         sigaction (SIGWINCH, &save_sigwinch, NULL);
349 }
350
351 MonoBoolean
352 ves_icall_System_ConsoleDriver_TtySetup (MonoString *keypad, MonoString *teardown, MonoArray **control_chars, int **size)
353 {
354         int dims;
355         int i;
356
357         MONO_ARCH_SAVE_REGS;
358
359         dims = terminal_get_dimensions ();
360         if (dims == -1){
361                 int cols = 0, rows = 0;
362                                       
363                 char *str = getenv ("COLUMNS");
364                 if (str != NULL)
365                         cols = atoi (str);
366                 str = getenv ("LINES");
367                 if (str != NULL)
368                         rows = atoi (str);
369
370                 if (cols != 0 && rows != 0)
371                         cols_and_lines = (cols << 16) | rows;
372                 else
373                         cols_and_lines = -1;
374         } else {
375                 cols_and_lines = dims;
376         }
377         
378         *size = &cols_and_lines;
379
380         *control_chars = mono_array_new (mono_domain_get (), mono_defaults.byte_class, sizeof (mono_attr.c_cc));
381         if (tcgetattr (STDIN_FILENO, &initial_attr) == -1)
382                 return FALSE;
383
384         for (i = 0; i < sizeof (mono_attr.c_cc); i++)
385                 mono_array_set (*control_chars, gchar, i, mono_attr.c_cc [i]);
386         mono_attr = initial_attr;
387         mono_attr.c_lflag &= ~(ICANON);
388         mono_attr.c_iflag &= ~(IXON|IXOFF);
389         mono_attr.c_cc [VMIN] = 1;
390         mono_attr.c_cc [VTIME] = 0;
391         if (tcsetattr (STDIN_FILENO, TCSANOW, &mono_attr) == -1)
392                 return FALSE;
393
394         mono_array_set (*control_chars, gchar, VMIN, mono_attr.c_cc [VMIN]);
395         mono_array_set (*control_chars, gchar, VTIME, mono_attr.c_cc [VTIME]);
396         /* If initialized from another appdomain... */
397         if (setup_finished)
398                 return TRUE;
399
400         keypad_xmit_str = keypad != NULL ? mono_string_to_utf8 (keypad) : NULL;
401         
402         console_set_signal_handlers ();
403         setup_finished = TRUE;
404         if (!atexit_called) {
405                 if (teardown != NULL)
406                         teardown_str = mono_string_to_utf8 (teardown);
407
408                 atexit (tty_teardown);
409         }
410
411         return TRUE;
412 }
413
414 #endif /* !PLATFORM_WIN32 */