reduce dependency on ghcconfig.h
[ghc-base.git] / cbits / consUtils.c
1 /* 
2  * (c) The University of Glasgow 2002
3  *
4  * Win32 Console API support
5  */
6 #if defined(_MSC_VER) || defined(__MINGW32__) || defined(_WIN32) || defined(__CYGWIN__)
7 /* to the end */
8
9 #include "consUtils.h"
10 #include <windows.h>
11 #include <io.h>
12
13 #if defined(__CYGWIN__)
14 #define _get_osfhandle get_osfhandle
15 #endif
16
17 int
18 set_console_buffering__(int fd, int cooked)
19 {
20     HANDLE h;
21     DWORD  st;
22     /* According to GetConsoleMode() docs, it is not possible to
23        leave ECHO_INPUT enabled without also having LINE_INPUT,
24        so we have to turn both off here. */
25     DWORD flgs = ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT;
26     
27     if ( (h = (HANDLE)_get_osfhandle(fd)) != INVALID_HANDLE_VALUE ) {
28         if ( GetConsoleMode(h,&st) &&
29              SetConsoleMode(h, cooked ? (st | ENABLE_LINE_INPUT) : st & ~flgs)  ) {
30             return 0;
31         }
32     }
33     return -1;
34 }
35
36 int
37 set_console_echo__(int fd, int on)
38 {
39     HANDLE h;
40     DWORD  st;
41     DWORD flgs = ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT;
42     
43     if ( (h = (HANDLE)_get_osfhandle(fd)) != INVALID_HANDLE_VALUE ) {
44         if ( GetConsoleMode(h,&st) && 
45              SetConsoleMode(h,( on ? (st | flgs) : (st & ~ENABLE_ECHO_INPUT))) ) {
46             return 0;
47         }
48     }
49     return -1;
50 }
51
52 int
53 get_console_echo__(int fd)
54 {
55     HANDLE h;
56     DWORD  st;
57     
58     if ( (h = (HANDLE)_get_osfhandle(fd)) != INVALID_HANDLE_VALUE ) {
59         if ( GetConsoleMode(h,&st) ) {
60             return (st & ENABLE_ECHO_INPUT ? 1 : 0);
61         }
62     }
63     return -1;
64 }
65
66 int
67 flush_input_console__(int fd)
68 {
69     HANDLE h = (HANDLE)_get_osfhandle(fd);
70     
71     if ( h != INVALID_HANDLE_VALUE ) {
72         /* If the 'fd' isn't connected to a console; treat the flush
73          * operation as a NOP.
74          */
75         DWORD unused;
76         if ( !GetConsoleMode(h,&unused) &&
77              GetLastError() == ERROR_INVALID_HANDLE ) {
78             return 0;
79         }
80         if ( FlushConsoleInputBuffer(h) ) {
81             return 0;
82         }
83     }
84     /* ToDo: translate GetLastError() into something errno-friendly */
85     return -1;
86 }
87
88 #endif /* defined(__MINGW32__) || ... */