OSDN Git Service

Bump version.
[mutilities/MUtilities.git] / src / Terminal_Win32.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2016 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version, but always including the *additional*
9 // restrictions defined in the "License.txt" file.
10 //
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 // GNU General Public License for more details.
15 //
16 // You should have received a copy of the GNU General Public License along
17 // with this program; if not, write to the Free Software Foundation, Inc.,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 //
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
22
23 //Windows includes
24 #define NOMINMAX
25 #define WIN32_LEAN_AND_MEAN 1
26 #include <Windows.h>
27
28 //Internal
29 #include <MUtils/Terminal.h>
30 #include <MUtils/Global.h>
31 #include <MUtils/OSSupport.h>
32 #include "Utils_Win32.h"
33 #include "CriticalSection_Win32.h"
34
35 //Qt
36 #include <QFile>
37 #include <QStringList>
38 #include <QIcon>
39
40 //CRT
41 #include <iostream>
42 #include <fstream>
43 #include <ctime>
44 #include <stdarg.h>
45 #include <io.h>
46 #include <fcntl.h>
47
48 #ifdef _MSC_VER
49 #define stricmp(X,Y) _stricmp((X),(Y))
50 #endif
51
52 #define VALID_HANLDE(X) (((X) != NULL) && ((X) != INVALID_HANDLE_VALUE))
53
54 ///////////////////////////////////////////////////////////////////////////////
55 // TERMINAL VARIABLES
56 ///////////////////////////////////////////////////////////////////////////////
57
58 //Critical section
59 static MUtils::Internal::CriticalSection g_terminal_lock;
60
61 //Is terminal attached?
62 static volatile bool g_terminal_attached = false;
63
64 //Terminal output buffer
65 static const size_t BUFF_SIZE = 8192;
66 static char g_conOutBuff[BUFF_SIZE] = { '\0' };
67
68 //Buffer objects
69 static QScopedPointer<std::filebuf> g_fileBuf_stdout;
70 static QScopedPointer<std::filebuf> g_fileBuf_stderr;
71
72 //The log file
73 static QScopedPointer<QFile> g_terminal_log_file;
74
75 ///////////////////////////////////////////////////////////////////////////////
76 // HELPER FUNCTIONS
77 ///////////////////////////////////////////////////////////////////////////////
78
79 static inline void make_timestamp(char *timestamp, const size_t &buffsize)
80 {
81         time_t rawtime;
82         struct tm timeinfo;
83
84         time(&rawtime);
85         if(localtime_s(&timeinfo, &rawtime) == 0)
86         {
87                 strftime(timestamp, buffsize, "%H:%M:%S", &timeinfo);
88         }
89         else
90         {
91                 timestamp[0] = '\0';
92         }
93 }
94
95 static inline bool null_or_whitespace(const char *const str)
96 {
97         if (str)
98         {
99                 size_t pos = 0;
100                 while (str[pos])
101                 {
102                         if (!(isspace(str[pos]) || iscntrl(str[pos])))
103                         {
104                                 return false;
105                         }
106                         pos++;
107                 }
108         }
109         return true;
110 }
111
112 static inline size_t clean_string(char *const str)
113 {
114         bool space_flag = true;
115         size_t src = 0, out = 0;
116
117         while (str[src])
118         {
119                 if (isspace(str[src]) || iscntrl(str[src])) /*replace any space-sequence with a single space character*/
120                 {
121                         src++;
122                         if (!space_flag)
123                         {
124                                 space_flag = true;
125                                 str[out++] = 0x20;
126                         }
127                 }
128                 else /*otherwise we'll just copy over the current character*/
129                 {
130                         if (src != out)
131                         {
132                                 str[out] = str[src];
133                         }
134                         space_flag = false;
135                         out++; src++;
136                 }
137         }
138
139         if (space_flag && (out > 0)) /*trim trailing space, if any*/
140         {
141                 out--;
142         }
143
144         str[out] = NULL;
145         return out;
146 }
147
148 ///////////////////////////////////////////////////////////////////////////////
149 // TERMINAL SETUP
150 ///////////////////////////////////////////////////////////////////////////////
151
152 static inline std::filebuf *terminal_connect(FILE *const fs, std::ostream &os)
153 {
154         std::filebuf *result = NULL;
155         FILE *temp;
156         if (freopen_s(&temp, "CONOUT$", "wb", fs) == 0)
157         {
158                 os.rdbuf(result = new std::filebuf(temp));
159         }
160         return result;
161 }
162
163 static void terminal_shutdown(void)
164 {
165         MUtils::Internal::CSLocker lock(g_terminal_lock);
166
167         if (g_terminal_attached)
168         {
169                 g_fileBuf_stdout.reset();
170                 g_fileBuf_stderr.reset();
171                 FILE *temp[2];
172                 if(stdout) freopen_s(&temp[0], "NUL", "wb", stdout);
173                 if(stderr) freopen_s(&temp[1], "NUL", "wb", stderr);
174                 FreeConsole();
175                 g_terminal_attached = false;
176         }
177 }
178
179 void MUtils::Terminal::setup(int &argc, char **argv, const char* const appName, const bool forceEnabled)
180 {
181         MUtils::Internal::CSLocker lock(g_terminal_lock);
182         bool enableConsole = (MUTILS_DEBUG) || forceEnabled;
183
184         if(_environ)
185         {
186                 wchar_t *logfile = NULL; size_t logfile_len = 0;
187                 if(!_wdupenv_s(&logfile, &logfile_len, L"MUTILS_LOGFILE"))
188                 {
189                         if(logfile && (logfile_len > 0))
190                         {
191                                 g_terminal_log_file.reset(new QFile(MUTILS_QSTR(logfile)));
192                                 if(g_terminal_log_file->open(QIODevice::WriteOnly))
193                                 {
194                                         static const char MARKER[3] = { char(0xEF), char(0xBB), char(0xBF) };
195                                         g_terminal_log_file->write(MARKER, 3);
196                                 }
197                                 free(logfile);
198                         }
199                 }
200         }
201
202         if(!MUTILS_DEBUG)
203         {
204                 for(int i = 0; i < argc; i++)
205                 {
206                         if(!stricmp(argv[i], "--console"))
207                         {
208                                 enableConsole = true;
209                         }
210                         else if(!stricmp(argv[i], "--no-console"))
211                         {
212                                 enableConsole = false;
213                         }
214                 }
215         }
216
217         if(enableConsole)
218         {
219                 if(!g_terminal_attached)
220                 {
221                         if(AllocConsole() != FALSE)
222                         {
223                                 SetConsoleOutputCP(CP_UTF8);
224                                 SetConsoleCtrlHandler(NULL, TRUE);
225                                 if(appName && appName[0])
226                                 {
227                                         char title[128];
228                                         _snprintf_s(title, 128, _TRUNCATE, "%s | Debug Console", appName);
229                                         SetConsoleTitleA(title);
230                                 }
231                                 g_terminal_attached = true;
232                         }
233                 }
234
235                 if(g_terminal_attached)
236                 {
237                         g_fileBuf_stdout.reset(terminal_connect(stdout, std::cout));
238                         g_fileBuf_stderr.reset(terminal_connect(stderr, std::cerr));
239
240                         atexit(terminal_shutdown);
241
242                         const HWND hwndConsole = GetConsoleWindow();
243                         if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
244                         {
245                                 HMENU hMenu = GetSystemMenu(hwndConsole, 0);
246                                 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
247                                 RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
248
249                                 SetWindowPos (hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
250                                 SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX) & (~WS_MINIMIZEBOX));
251                                 SetWindowPos (hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
252                         }
253                 }
254         }
255 }
256
257 ///////////////////////////////////////////////////////////////////////////////
258 // TERMINAL COLORS
259 ///////////////////////////////////////////////////////////////////////////////
260
261 //Colors
262 static const WORD COLOR_RED    = FOREGROUND_RED | FOREGROUND_INTENSITY;
263 static const WORD COLOR_YELLOW = FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY;
264 static const WORD COLOR_WHITE  = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY;
265 static const WORD COLOR_DEFAULT= FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
266
267 static void set_terminal_color(FILE *const fp, const WORD &attributes)
268 {
269         if(_isatty(_fileno(fp)))
270         {
271                 const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(fp)));
272                 if (VALID_HANLDE(hConsole))
273                 {
274                         SetConsoleTextAttribute(hConsole, attributes);
275                 }
276         }
277 }
278
279 ///////////////////////////////////////////////////////////////////////////////
280 // WRITE TO TERMINAL
281 ///////////////////////////////////////////////////////////////////////////////
282
283 static const char *const FORMAT = "[%c][%s] %s\r\n";
284 static const char *const GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
285
286 static void write_to_logfile(QFile *const file, const int &type, const char *const message)
287 {
288         int len = -1;
289
290         if (null_or_whitespace(message))
291         {
292                 return; /*don't write empty message to log file*/
293         }
294
295         static char timestamp[32];
296         make_timestamp(timestamp, 32);
297
298         switch(type)
299         {
300         case QtCriticalMsg:
301         case QtFatalMsg:
302                 len = _snprintf_s(g_conOutBuff, BUFF_SIZE, _TRUNCATE, FORMAT, 'C', timestamp, message);
303                 break;
304         case QtWarningMsg:
305                 len = _snprintf_s(g_conOutBuff, BUFF_SIZE, _TRUNCATE, FORMAT, 'W', timestamp, message);
306                 break;
307         default:
308                 len = _snprintf_s(g_conOutBuff, BUFF_SIZE, _TRUNCATE, FORMAT, 'I', timestamp, message);
309                 break;
310         }
311
312         if (len > 0)
313         {
314                 if (clean_string(g_conOutBuff) > 0)
315                 {
316                         file->write(g_conOutBuff);
317                         file->flush();
318                 }
319         }
320 }
321
322 static void write_to_debugger(const int &type, const char *const message)
323 {
324         int len = -1;
325
326         if (null_or_whitespace(message))
327         {
328                 return; /*don't send empty message to debugger*/
329         }
330
331         static char timestamp[32];
332         make_timestamp(timestamp, 32);
333
334         switch(type)
335         {
336         case QtCriticalMsg:
337         case QtFatalMsg:
338                 len = _snprintf_s(g_conOutBuff, BUFF_SIZE, _TRUNCATE, FORMAT, 'C', timestamp, message);
339                 break;
340         case QtWarningMsg:
341                 len = _snprintf_s(g_conOutBuff, BUFF_SIZE, _TRUNCATE, FORMAT, 'W', timestamp, message);
342                 break;
343         default:
344                 len = _snprintf_s(g_conOutBuff, BUFF_SIZE, _TRUNCATE, FORMAT, 'I', timestamp, message);
345                 break;
346         }
347
348         if (len > 0)
349         {
350                 if (clean_string(g_conOutBuff) > 0)
351                 {
352                         OutputDebugStringA(g_conOutBuff);
353                 }
354         }
355 }
356
357 static void write_to_terminal(const int &type, const char *const message)
358 {
359         switch(type)
360         {
361         case QtCriticalMsg:
362         case QtFatalMsg:
363                 set_terminal_color(stderr, COLOR_RED);
364                 fprintf(stderr, GURU_MEDITATION);
365                 fprintf(stderr, "%s\n", message);
366                 break;
367         case QtWarningMsg:
368                 set_terminal_color(stderr, COLOR_YELLOW);
369                 fprintf(stderr, "%s\n", message);
370                 break;
371         default:
372                 set_terminal_color(stderr, COLOR_WHITE);
373                 fprintf(stderr, "%s\n", message);
374                 break;
375         }
376
377         fflush(stderr);
378 }
379
380 void MUtils::Terminal::write(const int &type, const char *const message)
381 {
382         MUtils::Internal::CSLocker lock(g_terminal_lock);
383
384         if(g_terminal_attached)
385         {
386                 write_to_terminal(type, message);
387         }
388         else
389         {
390                 write_to_debugger(type, message);
391         }
392
393         if(!g_terminal_log_file.isNull())
394         {
395                 write_to_logfile(g_terminal_log_file.data(), type, message);
396         }
397 }
398
399 ///////////////////////////////////////////////////////////////////////////////
400 // TERMINAL ICON
401 ///////////////////////////////////////////////////////////////////////////////
402
403 void MUtils::Terminal::set_icon(const QIcon &icon)
404 {
405         MUtils::Internal::CSLocker lock(g_terminal_lock);
406
407         if(g_terminal_attached && (!(icon.isNull() || MUtils::OS::running_on_wine())))
408         {
409                 typedef DWORD(__stdcall *SetConsoleIconFun)(HICON);
410                 if(const SetConsoleIconFun setConsoleIconFun = MUtils::Win32Utils::resolve<SetConsoleIconFun>(QLatin1String("kernel32"), QLatin1String("SetConsoleIcon")))
411                 {
412                         if(HICON hIcon = (HICON) MUtils::Win32Utils::qicon_to_hicon(icon, 16, 16))
413                         {
414                                 setConsoleIconFun(hIcon);
415                                 DestroyIcon(hIcon);
416                         }
417                 }
418         }
419 }