1 /**
2  * @file win32/consolewaiter.cpp
3  * @brief Win32 event/timeout handling, listens for console input
4  *
5  * (c) 2013-2016 by Mega Limited, Auckland, New Zealand
6  *
7  * This file is part of the MEGA SDK - Client Access Engine.
8  *
9  * Applications using the MEGA API must present a valid application key
10  * and comply with the the rules set forth in the Terms of Service.
11  *
12  * The MEGA SDK is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15  *
16  * @copyright Simplified (2-clause) BSD License.
17  *
18  * You should have received a copy of the license along with this
19  * program.
20  */
21 
22 #include "mega.h"
23 #include "megaconsolewaiter.h"
24 #include "megaconsole.h"
25 
26 namespace mega {
WinConsoleWaiter(WinConsole * con)27 WinConsoleWaiter::WinConsoleWaiter(WinConsole* con)
28 #ifdef NO_READLINE
29     : console(con)
30 #endif
31 {
32 #ifndef NO_READLINE
33     DWORD dwMode;
34 
35     hInput = GetStdHandle(STD_INPUT_HANDLE);
36 
37     GetConsoleMode(hInput, &dwMode);
38     SetConsoleMode(hInput, dwMode & ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT));
39     FlushConsoleInputBuffer(hInput);
40 #endif
41 }
42 
43 // wait for events (socket, I/O completion, timeout + application events)
44 // ds specifies the maximum amount of time to wait in deciseconds (or ~0 if no
45 // timeout scheduled)
wait()46 int WinConsoleWaiter::wait()
47 {
48     int r;
49 #ifdef NO_READLINE
50 
51     if (console)
52     {
53 
54         addhandle(console->inputAvailableHandle(), 0);
55     }
56 #else
57     addhandle(hInput, 0);
58 #endif
59 
60     // aggregated wait
61     r = WinWaiter::wait();
62 
63     // is it a network- or filesystem-triggered wakeup?
64     if (r)
65     {
66         return r;
67     }
68 
69 #ifdef NO_READLINE
70     if (console && console->consolePeek())
71     {
72         return HAVESTDIN;
73     }
74 #else
75     // FIXME: improve this gruesome nonblocking console read-simulating kludge
76     if (_kbhit())
77     {
78         return HAVESTDIN;
79     }
80 
81     // this assumes that the user isn't typing too fast
82     INPUT_RECORD ir[1024];
83     DWORD dwNum;
84     ReadConsoleInput(hInput, ir, 1024, &dwNum);
85 #endif
86     return 0;
87 }
88 } // namespace
89