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);
53 tcsetattr(handle, TCSADRAIN, &orig_attr);
57 void Console::set_block(bool b)
60 // XXX Dunno how to do this in win32
63 int flags=fcntl(0, F_GETFL);
64 flags=(flags&~O_NONBLOCK) | (b?0:O_NONBLOCK);
65 fcntl(0, F_SETFL, flags);
69 void Console::set_local_echo(bool e)
72 throw InvalidState("Local echo can only be set on input console");
76 GetConsoleMode(handle, &m);
77 SetConsoleMode(handle, (m&~ENABLE_ECHO_INPUT) | (e?ENABLE_ECHO_INPUT:0));
81 t.c_lflag=(t.c_lflag&~ECHO) | (e?ECHO:0);
82 tcsetattr(0, TCSADRAIN, &t);
86 void Console::set_line_buffer(bool l)
89 throw InvalidState("Line buffering can only be set on input console");
93 GetConsoleMode(handle, &m);
94 SetConsoleMode(handle, (m&~ENABLE_LINE_INPUT) | (l?ENABLE_LINE_INPUT:0));
96 // XXX ICANON does more than just set line buffering, may need a bit more thought
99 t.c_lflag=(t.c_lflag&~ICANON) | (l?ICANON:0);
100 tcsetattr(0, TCSADRAIN, &t);
104 Handle Console::get_event_handle()
109 unsigned Console::do_write(const char *buf, unsigned len)
112 throw InvalidState("Console is not writable");
116 if(!WriteFile(handle, buf, len, &ret, 0))
117 throw SystemError("Writing to console failed", GetLastError());
119 int ret=::write(1, buf, len);
121 throw SystemError("Writing to console failed", errno);
127 unsigned Console::do_read(char *buf, unsigned len)
130 throw InvalidState("Console is not readable");
134 if(!ReadFile(handle, buf, len, &ret, 0))
135 throw SystemError("Reading from console failed", GetLastError());
137 int ret=::read(0, buf, len);
143 throw SystemError("Reading from console failed", errno);
152 Console &Console::instance(unsigned n)
154 static Console in(0);
155 static Console out(1);
156 static Console err(2);
165 throw InvalidParameterValue("Unknown Console instance requested");
168 Console &cin=Console::instance(0);
169 Console &cout=Console::instance(1);
170 Console &cerr=Console::instance(2);