OSDN Git Service

0dcc7f25faa59305db0066aa5e549abd011e8315
[mutilities/MUtilities.git] / src / Terminal_Win32.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2014 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 #include <QLibrary>
40
41 //CRT
42 #include <iostream>
43 #include <fstream>
44 #include <io.h>
45 #include <fcntl.h>
46 #include <ctime>
47
48 #ifdef _MSC_VER
49 #define stricmp(X,Y) _stricmp((X),(Y))
50 #endif
51
52 ///////////////////////////////////////////////////////////////////////////////
53 // HELPER FUNCTIONS
54 ///////////////////////////////////////////////////////////////////////////////
55
56 static void make_timestamp(char *timestamp, const size_t &buffsize)
57 {
58         time_t rawtime;
59         struct tm timeinfo;
60
61         time(&rawtime);
62         if(localtime_s(&timeinfo, &rawtime) == 0)
63         {
64                 strftime(timestamp, 32, "%H:%M:%S", &timeinfo);
65         }
66         else
67         {
68                 timestamp[0] = '\0';
69         }
70 }
71
72 static const char *clean_str(char *str)
73 {
74         //Clean
75         char *ptr = &str[0];
76         while((*ptr) && isspace(*ptr))
77         {
78                 *(ptr++) = 0x20;
79         }
80
81         //Trim left
82         while((*str) && isspace(*str))
83         {
84                 str++;
85         }
86
87         //Trim right
88         size_t pos = strlen(str);
89         while(pos > 0)
90         {
91                 if(isspace(str[--pos]))
92                 {
93                         str[pos] = '\0';
94                         continue;
95                 }
96                 break;
97         }
98
99         return str;
100 }
101
102 ///////////////////////////////////////////////////////////////////////////////
103 // HELPER MACROS
104 ///////////////////////////////////////////////////////////////////////////////
105
106 #define REPLACE_STANDARD_STREAM(TYPE, HANDLE) do \
107 { \
108         const int fd_##TYPE = _open_osfhandle((intptr_t)GetStdHandle(HANDLE), flags); \
109         FILE *const file_##TYPE = (fd_##TYPE >= 0) ? _fdopen(fd_##TYPE, "wb") : NULL; \
110         if(file_##TYPE) \
111         { \
112                 g_terminal_backup_file_##TYPE = *(std##TYPE); \
113                 *(std##TYPE) = *(file_##TYPE); \
114                 g_terminal_filebuf_##TYPE.reset(new std::filebuf(file_##TYPE)); \
115                 g_terminal_backup_fbuf_##TYPE = std::c##TYPE.rdbuf(); \
116                 std::c##TYPE.rdbuf(g_terminal_filebuf_##TYPE.data()); \
117         } \
118 } \
119 while(0)
120
121 #define RESTORE_STANDARD_STREAM(TYPE) do \
122 { \
123         if(!g_terminal_filebuf_##TYPE.isNull()) \
124         { \
125                 *(std##TYPE) = g_terminal_backup_file_##TYPE; \
126                 std::c##TYPE.rdbuf(g_terminal_backup_fbuf_##TYPE); \
127                 g_terminal_filebuf_##TYPE.reset(NULL); \
128         } \
129 } \
130 while(0)
131
132 ///////////////////////////////////////////////////////////////////////////////
133 // TERMINAL VARIABLES
134 ///////////////////////////////////////////////////////////////////////////////
135
136 //Critical section
137 static MUtils::Internal::CriticalSection g_terminal_lock;
138
139 //Terminal replacement streams
140 static bool                         g_terminal_attached = false;
141 static QScopedPointer<std::filebuf> g_terminal_filebuf_out;
142 static QScopedPointer<std::filebuf> g_terminal_filebuf_err;
143
144 //Backup of original streams
145 static FILE                         g_terminal_backup_file_out;
146 static FILE                         g_terminal_backup_file_err;
147 static std::streambuf*              g_terminal_backup_fbuf_out;
148 static std::streambuf*              g_terminal_backup_fbuf_err;
149
150 //The log file
151 static QScopedPointer<QFile>        g_terminal_log_file;
152
153 ///////////////////////////////////////////////////////////////////////////////
154 // TERMINAL EXIT
155 ///////////////////////////////////////////////////////////////////////////////
156
157 static void terminal_restore(void)
158 {
159         MUtils::Internal::CSLocker lock(g_terminal_lock);
160
161         if(g_terminal_attached)
162         {
163                 RESTORE_STANDARD_STREAM(out);
164                 RESTORE_STANDARD_STREAM(err);
165                 FreeConsole();
166                 g_terminal_attached = false;
167         }
168 }
169
170 ///////////////////////////////////////////////////////////////////////////////
171 // TERMINAL SETUP
172 ///////////////////////////////////////////////////////////////////////////////
173
174 void MUtils::Terminal::setup(int &argc, char **argv, const char* const appName, const bool forceEnabled)
175 {
176         MUtils::Internal::CSLocker lock(g_terminal_lock);
177         bool enableConsole = (MUTILS_DEBUG) || forceEnabled;
178
179         if(_environ)
180         {
181                 wchar_t *logfile = NULL; size_t logfile_len = 0;
182                 if(!_wdupenv_s(&logfile, &logfile_len, L"MUTILS_LOGFILE"))
183                 {
184                         if(logfile && (logfile_len > 0))
185                         {
186                                 g_terminal_log_file.reset(new QFile(MUTILS_QSTR(logfile)));
187                                 if(g_terminal_log_file->open(QIODevice::WriteOnly))
188                                 {
189                                         static const char MARKER[3] = { char(0xEF), char(0xBB), char(0xBF) };
190                                         g_terminal_log_file->write(MARKER, 3);
191                                 }
192                                 free(logfile);
193                         }
194                 }
195         }
196
197         if(!MUTILS_DEBUG)
198         {
199                 for(int i = 0; i < argc; i++)
200                 {
201                         if(!stricmp(argv[i], "--console"))
202                         {
203                                 enableConsole = true;
204                         }
205                         else if(!stricmp(argv[i], "--no-console"))
206                         {
207                                 enableConsole = false;
208                         }
209                 }
210         }
211
212         if(enableConsole)
213         {
214                 if(!g_terminal_attached)
215                 {
216                         if(AllocConsole() != FALSE)
217                         {
218                                 SetConsoleOutputCP(CP_UTF8);
219                                 SetConsoleCtrlHandler(NULL, TRUE);
220                                 if(appName && appName[0])
221                                 {
222                                         char title[128];
223                                         _snprintf_s(title, 128, _TRUNCATE, "%s | Debug Console", appName);
224                                         SetConsoleTitleA(title);
225                                 }
226                                 g_terminal_attached = true;
227                         }
228                 }
229
230                 if(g_terminal_attached)
231                 {
232                         //-------------------------------------------------------------------
233                         //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
234                         //-------------------------------------------------------------------
235                         const int flags = _O_WRONLY | _O_U8TEXT;
236                         REPLACE_STANDARD_STREAM(out, STD_OUTPUT_HANDLE);
237                         REPLACE_STANDARD_STREAM(err, STD_ERROR_HANDLE );
238                         atexit(terminal_restore);
239
240                         const HWND hwndConsole = GetConsoleWindow();
241                         if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
242                         {
243                                 HMENU hMenu = GetSystemMenu(hwndConsole, 0);
244                                 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
245                                 RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
246
247                                 SetWindowPos (hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
248                                 SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX) & (~WS_MINIMIZEBOX));
249                                 SetWindowPos (hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
250                         }
251                 }
252         }
253 }
254
255 ///////////////////////////////////////////////////////////////////////////////
256 // TERMINAL COLORS
257 ///////////////////////////////////////////////////////////////////////////////
258
259 //Colors
260 static const WORD COLOR_RED    = FOREGROUND_RED | FOREGROUND_INTENSITY;
261 static const WORD COLOR_YELLOW = FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY;
262 static const WORD COLOR_WHITE  = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY;
263 static const WORD COLOR_DEFAULT= FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
264
265 static void set_terminal_color(FILE* file, const WORD &attributes)
266 {
267         const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(file)));
268         if((hConsole != NULL) && (hConsole != INVALID_HANDLE_VALUE))
269         {
270                 SetConsoleTextAttribute(hConsole, attributes);
271         }
272 }
273
274 ///////////////////////////////////////////////////////////////////////////////
275 // WRITE TO TERMINAL
276 ///////////////////////////////////////////////////////////////////////////////
277
278 static const char *const FORMAT = "[%c][%s] %s\r\n";
279 static const char *const GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
280
281 static void write_logfile_helper(QFile *const file, const int &type, const char *const message)
282 {
283         static char input[1024], output[1024], timestamp[32];
284         make_timestamp(timestamp, 32);
285         strncpy_s(input, 1024, message, _TRUNCATE);
286         const char *const temp = clean_str(input);
287
288         switch(type)
289         {
290         case QtCriticalMsg:
291         case QtFatalMsg:
292                 _snprintf_s(output, 1024, FORMAT, 'C', timestamp, temp);
293                 break;
294         case QtWarningMsg:
295                 _snprintf_s(output, 1024, FORMAT, 'W', timestamp, temp);
296                 break;
297         default:
298                 _snprintf_s(output, 1024, FORMAT, 'I', timestamp, temp);
299                 break;
300         }
301
302         file->write(output);
303         file->flush();
304 }
305
306 static void write_debugger_helper(const int &type, const char *const message)
307 {
308         static char input[1024], output[1024], timestamp[32];
309         make_timestamp(timestamp, 32);
310         strncpy_s(input, 1024, message, _TRUNCATE);
311         const char *const temp = clean_str(input);
312
313         switch(type)
314         {
315         case QtCriticalMsg:
316         case QtFatalMsg:
317                 _snprintf_s(output, 1024, FORMAT, 'C', timestamp, temp);
318                 break;
319         case QtWarningMsg:
320                 _snprintf_s(output, 1024, FORMAT, 'W', timestamp, temp);
321                 break;
322         default:
323                 _snprintf_s(output, 1024, FORMAT, 'I', timestamp, temp);
324                 break;
325         }
326
327         OutputDebugStringA(output);
328 }
329
330 static void write_terminal_helper(const int &type, const char *const message)
331 {
332         if(_isatty(_fileno(stderr)))
333         {
334                 UINT oldOutputCP = GetConsoleOutputCP();
335                 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(CP_UTF8);
336
337                 switch(type)
338                 {
339                 case QtCriticalMsg:
340                 case QtFatalMsg:
341                         set_terminal_color(stderr, COLOR_RED);
342                         fprintf(stderr, GURU_MEDITATION);
343                         fprintf(stderr, "%s\n", message);
344                         fflush(stderr);
345                         break;
346                 case QtWarningMsg:
347                         set_terminal_color(stderr, COLOR_YELLOW);
348                         fprintf(stderr, "%s\n", message);
349                         fflush(stderr);
350                         break;
351                 default:
352                         set_terminal_color(stderr, COLOR_WHITE);
353                         fprintf(stderr, "%s\n", message);
354                         fflush(stderr);
355                         break;
356                 }
357         
358                 set_terminal_color(stderr, COLOR_DEFAULT);
359                 if(oldOutputCP != CP_UTF8)
360                 {
361                         SetConsoleOutputCP(oldOutputCP);
362                 }
363         }
364 }
365
366 void MUtils::Terminal::write(const int &type, const char *const message)
367 {
368         MUtils::Internal::CSLocker lock(g_terminal_lock);
369
370         if(g_terminal_attached)
371         {
372                 write_terminal_helper(type, message);
373         }
374         else
375         {
376                 write_debugger_helper(type, message);
377         }
378
379         if(!g_terminal_log_file.isNull())
380         {
381                 write_logfile_helper(g_terminal_log_file.data(), type, message);
382         }
383 }
384
385 ///////////////////////////////////////////////////////////////////////////////
386 // TERMINAL ICON
387 ///////////////////////////////////////////////////////////////////////////////
388
389 void MUtils::Terminal::set_icon(const QIcon &icon)
390 {
391         MUtils::Internal::CSLocker lock(g_terminal_lock);
392
393         if(g_terminal_attached && (!(icon.isNull() || MUtils::OS::running_on_wine())))
394         {
395                 QLibrary kernel32("kernel32.dll");
396                 if(kernel32.load())
397                 {
398                         typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
399                         if(SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon"))
400                         {
401                                 if(HICON hIcon = qicon_to_hicon(icon, 16, 16))
402                                 {
403                                         SetConsoleIconPtr(hIcon);
404                                         DestroyIcon(hIcon);
405                                 }
406                         }
407                 }
408         }
409 }