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