3 This file is part of libmspio
4 Copyright © 2008 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
13 #include <msp/core/except.h>
27 Console::Console(unsigned n)
30 throw InvalidParameterValue("Invalid parameter for Console::Console");
32 mode=(n==0 ? M_READ : M_WRITE);
37 case 0: handle=GetStdHandle(STD_INPUT_HANDLE); break;
38 case 1: handle=GetStdHandle(STD_OUTPUT_HANDLE); break;
39 case 2: handle=GetStdHandle(STD_ERROR_HANDLE); break;
45 tcgetattr(handle, &orig_attr);
56 tcsetattr(handle, TCSADRAIN, &orig_attr);
60 void Console::set_block(bool b)
63 // XXX Dunno how to do this in win32
66 int flags=fcntl(0, F_GETFL);
67 flags=(flags&~O_NONBLOCK) | (b?0:O_NONBLOCK);
68 fcntl(0, F_SETFL, flags);
72 void Console::set_local_echo(bool e)
75 throw InvalidState("Local echo can only be set on input console");
79 GetConsoleMode(handle, &m);
80 SetConsoleMode(handle, (m&~ENABLE_ECHO_INPUT) | (e?ENABLE_ECHO_INPUT:0));
84 t.c_lflag=(t.c_lflag&~ECHO) | (e?ECHO:0);
85 tcsetattr(0, TCSADRAIN, &t);
89 void Console::set_line_buffer(bool l)
92 throw InvalidState("Line buffering can only be set on input console");
96 GetConsoleMode(handle, &m);
97 SetConsoleMode(handle, (m&~ENABLE_LINE_INPUT) | (l?ENABLE_LINE_INPUT:0));
99 // XXX ICANON does more than just set line buffering, may need a bit more thought
102 t.c_lflag=(t.c_lflag&~ICANON) | (l?ICANON:0);
103 tcsetattr(0, TCSADRAIN, &t);
107 Handle Console::get_event_handle()
112 unsigned Console::do_write(const char *buf, unsigned len)
115 throw InvalidState("Console is not writable");
119 if(!WriteFile(handle, buf, len, &ret, 0))
120 throw SystemError("Writing to console failed", GetLastError());
122 int ret=::write(1, buf, len);
124 throw SystemError("Writing to console failed", errno);
130 unsigned Console::do_read(char *buf, unsigned len)
133 throw InvalidState("Console is not readable");
137 if(!ReadFile(handle, buf, len, &ret, 0))
138 throw SystemError("Reading from console failed", GetLastError());
140 int ret=::read(0, buf, len);
146 throw SystemError("Reading from console failed", errno);
155 Console &Console::instance(unsigned n)
157 static Console in(0);
158 static Console out(1);
159 static Console err(2);
168 throw InvalidParameterValue("Unknown Console instance requested");
171 Console &cin=Console::instance(0);
172 Console &cout=Console::instance(1);
173 Console &cerr=Console::instance(2);