OSDN Git Service

Bump version.
[mutilities/MUtilities.git] / src / Terminal_Win32.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2019 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 QAtomicInt g_terminal_attached;
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 //Terminal icon
76 static HICON g_terminal_icon = NULL;
77
78 ///////////////////////////////////////////////////////////////////////////////
79 // HELPER FUNCTIONS
80 ///////////////////////////////////////////////////////////////////////////////
81
82 static inline void make_timestamp(char *timestamp, const size_t &buffsize)
83 {
84         time_t rawtime;
85         struct tm timeinfo;
86
87         time(&rawtime);
88         if(localtime_s(&timeinfo, &rawtime) == 0)
89         {
90                 strftime(timestamp, buffsize, "%H:%M:%S", &timeinfo);
91         }
92         else
93         {
94                 timestamp[0] = '\0';
95         }
96 }
97
98 static inline bool null_or_whitespace(const char *const str)
99 {
100         if (str)
101         {
102                 size_t pos = 0;
103                 while (str[pos])
104                 {
105                         if (!(isspace(str[pos]) || iscntrl(str[pos])))
106                         {
107                                 return false;
108                         }
109                         pos++;
110                 }
111         }
112         return true;
113 }
114
115 static inline size_t clean_string(char *const str)
116 {
117         bool space_flag = true;
118         size_t src = 0, out = 0;
119
120         while (str[src])
121         {
122                 if (isspace(str[src]) || iscntrl(str[src])) /*replace any space-sequence with a single space character*/
123                 {
124                         src++;
125                         if (!space_flag)
126                         {
127                                 space_flag = true;
128                                 str[out++] = 0x20;
129                         }
130                 }
131                 else /*otherwise we'll just copy over the current character*/
132                 {
133                         if (src != out)
134                         {
135                                 str[out] = str[src];
136                         }
137                         space_flag = false;
138                         out++; src++;
139                 }
140         }
141
142         if (space_flag && (out > 0)) /*trim trailing space, if any*/
143         {
144                 out--;
145         }
146
147         str[out] = NULL;
148         return out;
149 }
150
151 static inline void set_hicon(HICON *const ptr, const HICON val)
152 {
153         if (*ptr)
154         {
155                 DestroyIcon(*ptr);
156         }
157         *ptr = val;
158 }
159
160 ///////////////////////////////////////////////////////////////////////////////
161 // TERMINAL SETUP
162 ///////////////////////////////////////////////////////////////////////////////
163
164 static inline std::filebuf *terminal_connect(FILE *const fs, std::ostream &os)
165 {
166         std::filebuf *result = NULL;
167         FILE *temp;
168         if (freopen_s(&temp, "CONOUT$", "wb", fs) == 0)
169         {
170                 os.rdbuf(result = new std::filebuf(temp));
171         }
172         return result;
173 }
174
175 static void terminal_shutdown(void)
176 {
177         MUtils::Internal::CSLocker lock(g_terminal_lock);
178
179         if (g_terminal_attached.fetchAndStoreOrdered(0) > 0)
180         {
181                 g_fileBuf_stdout.reset();
182                 g_fileBuf_stderr.reset();
183                 FILE *temp[2];
184                 if(stdout) freopen_s(&temp[0], "NUL", "wb", stdout);
185                 if(stderr) freopen_s(&temp[1], "NUL", "wb", stderr);
186                 FreeConsole();
187                 set_hicon(&g_terminal_icon, NULL);
188         }
189 }
190
191 void MUtils::Terminal::setup(int &argc, char **argv, const char* const appName, const bool forceEnabled)
192 {
193         MUtils::Internal::CSLocker lock(g_terminal_lock);
194         bool enableConsole = (MUTILS_DEBUG) || forceEnabled;
195
196         if(_environ)
197         {
198                 wchar_t *logfile = NULL; size_t logfile_len = 0;
199                 if(!_wdupenv_s(&logfile, &logfile_len, L"MUTILS_LOGFILE"))
200                 {
201                         if(logfile && (logfile_len > 0))
202                         {
203                                 g_terminal_log_file.reset(new QFile(MUTILS_QSTR(logfile)));
204                                 if(g_terminal_log_file->open(QIODevice::WriteOnly))
205                                 {
206                                         static const char MARKER[3] = { char(0xEF), char(0xBB), char(0xBF) };
207                                         g_terminal_log_file->write(MARKER, 3);
208                                 }
209                                 free(logfile);
210                         }
211                 }
212         }
213
214         if(!MUTILS_DEBUG)
215         {
216                 for(int i = 0; i < argc; i++)
217                 {
218                         if(!stricmp(argv[i], "--console"))
219                         {
220                                 enableConsole = true;
221                         }
222                         else if(!stricmp(argv[i], "--no-console"))
223                         {
224                                 enableConsole = false;
225                         }
226                 }
227         }
228
229         if(enableConsole)
230         {
231                 if(!g_terminal_attached.fetchAndStoreOrdered(1))
232                 {
233                         if(AllocConsole() != FALSE)
234                         {
235                                 SetConsoleOutputCP(CP_UTF8);
236                                 SetConsoleCtrlHandler(NULL, TRUE);
237                                 if(appName && appName[0])
238                                 {
239                                         char title[128];
240                                         _snprintf_s(title, 128, _TRUNCATE, "%s | Debug Console", appName);
241                                         SetConsoleTitleA(title);
242                                 }
243                         }
244                         else
245                         {
246                                 g_terminal_attached.fetchAndStoreOrdered(0); /*failed*/
247                         }
248                 }
249
250                 if(MUTILS_BOOLIFY(g_terminal_attached))
251                 {
252                         g_fileBuf_stdout.reset(terminal_connect(stdout, std::cout));
253                         g_fileBuf_stderr.reset(terminal_connect(stderr, std::cerr));
254
255                         atexit(terminal_shutdown);
256
257                         const HWND hwndConsole = GetConsoleWindow();
258                         if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
259                         {
260                                 HMENU hMenu = GetSystemMenu(hwndConsole, 0);
261                                 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
262                                 RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
263
264                                 SetWindowPos (hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
265                                 SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX) & (~WS_MINIMIZEBOX));
266                                 SetWindowPos (hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
267                         }
268                 }
269         }
270 }
271
272 ///////////////////////////////////////////////////////////////////////////////
273 // TERMINAL COLORS
274 ///////////////////////////////////////////////////////////////////////////////
275
276 //Colors
277 static const WORD COLOR_RED    = FOREGROUND_RED | FOREGROUND_INTENSITY;
278 static const WORD COLOR_YELLOW = FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY;
279 static const WORD COLOR_WHITE  = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY;
280 static const WORD COLOR_DEFAULT= FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
281
282 static void set_terminal_color(FILE *const fp, const WORD &attributes)
283 {
284         if(_isatty(_fileno(fp)))
285         {
286                 const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(fp)));
287                 if (VALID_HANLDE(hConsole))
288                 {
289                         SetConsoleTextAttribute(hConsole, attributes);
290                 }
291         }
292 }
293
294 ///////////////////////////////////////////////////////////////////////////////
295 // WRITE TO TERMINAL
296 ///////////////////////////////////////////////////////////////////////////////
297
298 static const char *const FORMAT = "[%c][%s] %s\r\n";
299 static const char *const GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
300
301 static void write_to_logfile(QFile *const file, const int &type, const char *const message)
302 {
303         int len = -1;
304
305         if (null_or_whitespace(message))
306         {
307                 return; /*don't write empty message to log file*/
308         }
309
310         static char timestamp[32];
311         make_timestamp(timestamp, 32);
312
313         switch(type)
314         {
315         case QtCriticalMsg:
316         case QtFatalMsg:
317                 len = _snprintf_s(g_conOutBuff, BUFF_SIZE, _TRUNCATE, FORMAT, 'C', timestamp, message);
318                 break;
319         case QtWarningMsg:
320                 len = _snprintf_s(g_conOutBuff, BUFF_SIZE, _TRUNCATE, FORMAT, 'W', timestamp, message);
321                 break;
322         default:
323                 len = _snprintf_s(g_conOutBuff, BUFF_SIZE, _TRUNCATE, FORMAT, 'I', timestamp, message);
324                 break;
325         }
326
327         if (len > 0)
328         {
329                 if (clean_string(g_conOutBuff) > 0)
330                 {
331                         file->write(g_conOutBuff);
332                         file->flush();
333                 }
334         }
335 }
336
337 static void write_to_debugger(const int &type, const char *const message)
338 {
339         int len = -1;
340
341         if (null_or_whitespace(message))
342         {
343                 return; /*don't send empty message to debugger*/
344         }
345
346         static char timestamp[32];
347         make_timestamp(timestamp, 32);
348
349         switch(type)
350         {
351         case QtCriticalMsg:
352         case QtFatalMsg:
353                 len = _snprintf_s(g_conOutBuff, BUFF_SIZE, _TRUNCATE, FORMAT, 'C', timestamp, message);
354                 break;
355         case QtWarningMsg:
356                 len = _snprintf_s(g_conOutBuff, BUFF_SIZE, _TRUNCATE, FORMAT, 'W', timestamp, message);
357                 break;
358         default:
359                 len = _snprintf_s(g_conOutBuff, BUFF_SIZE, _TRUNCATE, FORMAT, 'I', timestamp, message);
360                 break;
361         }
362
363         if (len > 0)
364         {
365                 if (clean_string(g_conOutBuff) > 0)
366                 {
367                         OutputDebugStringA(g_conOutBuff);
368                 }
369         }
370 }
371
372 static void write_to_terminal(const int &type, const char *const message)
373 {
374         switch(type)
375         {
376         case QtCriticalMsg:
377         case QtFatalMsg:
378                 set_terminal_color(stderr, COLOR_RED);
379                 fprintf(stderr, GURU_MEDITATION);
380                 fprintf(stderr, "%s\n", message);
381                 break;
382         case QtWarningMsg:
383                 set_terminal_color(stderr, COLOR_YELLOW);
384                 fprintf(stderr, "%s\n", message);
385                 break;
386         default:
387                 set_terminal_color(stderr, COLOR_WHITE);
388                 fprintf(stderr, "%s\n", message);
389                 break;
390         }
391
392         fflush(stderr);
393 }
394
395 void MUtils::Terminal::write(const int &type, const char *const message)
396 {
397         MUtils::Internal::CSLocker lock(g_terminal_lock);
398
399         if(MUTILS_BOOLIFY(g_terminal_attached))
400         {
401                 write_to_terminal(type, message);
402         }
403         else
404         {
405                 write_to_debugger(type, message);
406         }
407
408         if(!g_terminal_log_file.isNull())
409         {
410                 write_to_logfile(g_terminal_log_file.data(), type, message);
411         }
412 }
413
414 ///////////////////////////////////////////////////////////////////////////////
415 // TERMINAL ICON
416 ///////////////////////////////////////////////////////////////////////////////
417
418 void MUtils::Terminal::set_icon(const QIcon &icon)
419 {
420         MUtils::Internal::CSLocker lock(g_terminal_lock);
421
422         if(MUTILS_BOOLIFY(g_terminal_attached) && (!(icon.isNull() || MUtils::OS::running_on_wine())))
423         {
424                 if(const HICON hIcon = (HICON) MUtils::Win32Utils::qicon_to_hicon(&icon, 16, 16))
425                 {
426                         typedef BOOL(__stdcall *SetConsoleIconFun)(HICON);
427                         bool success = false;
428                         if (const SetConsoleIconFun pSetConsoleIconFun = MUtils::Win32Utils::resolve<SetConsoleIconFun>(QLatin1String("kernel32"), QLatin1String("SetConsoleIcon")))
429                         {
430                                 const DWORD before = GetLastError();
431                                 if (pSetConsoleIconFun(hIcon))
432                                 {
433                                         success = true;
434                                 }
435                                 else
436                                 {
437                                         const DWORD error = GetLastError();
438                                         qWarning("SetConsoleIcon() has failed! [Error: 0x%08X]", error);
439                                 }
440                         }
441                         if (!success)
442                         {
443                                 const HWND hwndConsole = GetConsoleWindow();
444                                 if ((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
445                                 {
446                                         SendMessage(hwndConsole, WM_SETICON, ICON_SMALL, LPARAM(hIcon));
447                                         success = true;
448                                 }
449                         }
450                         if (success)
451                         {
452                                 set_hicon(&g_terminal_icon, hIcon);
453                         }
454                 }
455         }
456 }