OSDN Git Service

Implemented startup and error handling functions.
[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 #include <MUtils/Terminal.h>
24
25 //Internal
26 #include <MUtils/Global.h>
27 #include <MUtils/OSSupport.h>
28 #include "CriticalSection_Win32.h"
29
30 //Windows includes
31 #define NOMINMAX
32 #define WIN32_LEAN_AND_MEAN 1
33 #include <Windows.h>
34
35 //Qt
36 #include <QFile>
37 #include <QStringList>
38
39 //CRT
40 #include <iostream>
41 #include <fstream>
42 #include <io.h>
43 #include <fcntl.h>
44 #include <ctime>
45
46 //Lock
47 static MUtils::Internal::CriticalSection g_terminal_lock;
48
49 #ifdef _MSC_VER
50 #define stricmp(X,Y) _stricmp((X),(Y))
51 #endif
52
53 ///////////////////////////////////////////////////////////////////////////////
54 // HELPER FUNCTIONS
55 ///////////////////////////////////////////////////////////////////////////////
56
57 static void make_timestamp(char *timestamp, const size_t &buffsize)
58 {
59         time_t rawtime;
60         struct tm timeinfo;
61
62         time(&rawtime);
63         if(localtime_s(&timeinfo, &rawtime) == 0)
64         {
65                 strftime(timestamp, 32, "%H:%M:%S", &timeinfo);
66         }
67         else
68         {
69                 timestamp[0] = '\0';
70         }
71 }
72
73 static const char *clean_str(char *str)
74 {
75         //Clean
76         char *ptr = &str[0];
77         while((*ptr) && isspace(*ptr))
78         {
79                 *(ptr++) = 0x20;
80         }
81
82         //Trim left
83         while((*str) && isspace(*str))
84         {
85                 str++;
86         }
87
88         //Trim right
89         size_t pos = strlen(str);
90         while(pos > 0)
91         {
92                 if(isspace(str[--pos]))
93                 {
94                         str[pos] = '\0';
95                         continue;
96                 }
97                 break;
98         }
99
100         return str;
101 }
102
103 ///////////////////////////////////////////////////////////////////////////////
104 // TERMINAL SETUP
105 ///////////////////////////////////////////////////////////////////////////////
106
107 static bool g_terminal_attached = false;
108 static QScopedPointer<std::filebuf> g_filebufStdOut;
109 static QScopedPointer<std::filebuf> g_filebufStdErr;
110 static QScopedPointer<QFile> g_log_file;
111
112 void MUtils::Terminal::setup(int &argc, char **argv, const bool forceEnabled)
113 {
114         MUtils::Internal::CSLocker lock(g_terminal_lock);
115         bool enableConsole = (MUTILS_DEBUG) || forceEnabled;
116
117         if(_environ)
118         {
119                 wchar_t *logfile = NULL; size_t logfile_len = 0;
120                 if(!_wdupenv_s(&logfile, &logfile_len, L"MUTILS_LOGFILE"))
121                 {
122                         if(logfile && (logfile_len > 0))
123                         {
124                                 g_log_file.reset(new QFile(MUTILS_QSTR(logfile)));
125                                 if(g_log_file->open(QIODevice::WriteOnly))
126                                 {
127                                         static const char MARKER[3] = { char(0xEF), char(0xBB), char(0xBF) };
128                                         g_log_file->write(MARKER, 3);
129                                 }
130                                 free(logfile);
131                         }
132                 }
133         }
134
135         if(!MUTILS_DEBUG)
136         {
137                 for(int i = 0; i < argc; i++)
138                 {
139                         if(!stricmp(argv[i], "--console"))
140                         {
141                                 enableConsole = true;
142                         }
143                         else if(!stricmp(argv[i], "--no-console"))
144                         {
145                                 enableConsole = false;
146                         }
147                 }
148         }
149
150         if(enableConsole)
151         {
152                 if(!g_terminal_attached)
153                 {
154                         if(AllocConsole() != FALSE)
155                         {
156                                 SetConsoleCtrlHandler(NULL, TRUE);
157                                 SetConsoleTitle(L"LameXP - Audio Encoder Front-End | Debug Console");
158                                 SetConsoleOutputCP(CP_UTF8);
159                                 g_terminal_attached = true;
160                         }
161                 }
162                 
163                 if(g_terminal_attached)
164                 {
165                         //-------------------------------------------------------------------
166                         //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
167                         //-------------------------------------------------------------------
168                         const int flags = _O_WRONLY | _O_U8TEXT;
169                         const int hCrtStdOut = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), flags);
170                         const int hCrtStdErr = _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE ), flags);
171                         FILE *const hfStdOut = (hCrtStdOut >= 0) ? _fdopen(hCrtStdOut, "wb") : NULL;
172                         FILE *const hfStdErr = (hCrtStdErr >= 0) ? _fdopen(hCrtStdErr, "wb") : NULL;
173                         if(hfStdOut)
174                         {
175                                 *stdout = *hfStdOut;
176                                 g_filebufStdOut.reset(new std::filebuf(hfStdOut));
177                                 std::cout.rdbuf(g_filebufStdOut.data());
178                         }
179                         if(hfStdErr)
180                         {
181                                 *stderr = *hfStdErr;
182                                 g_filebufStdErr.reset(new std::filebuf(hfStdErr));
183                                 std::cerr.rdbuf(g_filebufStdErr.data());
184                         }
185                 }
186
187                 HWND hwndConsole = GetConsoleWindow();
188                 if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
189                 {
190                         HMENU hMenu = GetSystemMenu(hwndConsole, 0);
191                         EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
192                         RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
193
194                         SetWindowPos (hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
195                         SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX) & (~WS_MINIMIZEBOX));
196                         SetWindowPos (hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
197                 }
198         }
199 }
200
201 ///////////////////////////////////////////////////////////////////////////////
202 // TERMINAL COLORS
203 ///////////////////////////////////////////////////////////////////////////////
204
205 //Colors
206 static const WORD COLOR_RED    = FOREGROUND_RED | FOREGROUND_INTENSITY;
207 static const WORD COLOR_YELLOW = FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY;
208 static const WORD COLOR_WHITE  = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY;
209 static const WORD COLOR_DEFAULT= FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
210
211 static void set_terminal_color(FILE* file, const WORD &attributes)
212 {
213         const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(file)));
214         if((hConsole != NULL) && (hConsole != INVALID_HANDLE_VALUE))
215         {
216                 SetConsoleTextAttribute(hConsole, attributes);
217         }
218 }
219
220 ///////////////////////////////////////////////////////////////////////////////
221 // WRITE TO TERMINAL
222 ///////////////////////////////////////////////////////////////////////////////
223
224 static const char *const FORMAT = "[%c][%s] %s\r\n";
225 static const char *const GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
226
227 static void write_logfile_helper(QFile *const file, const int &type, const char *const message)
228 {
229         static char input[1024], output[1024], timestamp[32];
230         make_timestamp(timestamp, 32);
231         strncpy_s(input, 1024, message, _TRUNCATE);
232         const char *const temp = clean_str(input);
233
234         switch(type)
235         {
236         case QtCriticalMsg:
237         case QtFatalMsg:
238                 _snprintf_s(output, 1024, FORMAT, 'C', timestamp, temp);
239                 break;
240         case QtWarningMsg:
241                 _snprintf_s(output, 1024, FORMAT, 'W', timestamp, temp);
242                 break;
243         default:
244                 _snprintf_s(output, 1024, FORMAT, 'I', timestamp, temp);
245                 break;
246         }
247
248         file->write(output);
249         file->flush();
250 }
251
252 static void write_debugger_helper(const int &type, const char *const message)
253 {
254         static char input[1024], output[1024], timestamp[32];
255         make_timestamp(timestamp, 32);
256         strncpy_s(input, 1024, message, _TRUNCATE);
257         const char *const temp = clean_str(input);
258
259         switch(type)
260         {
261         case QtCriticalMsg:
262         case QtFatalMsg:
263                 _snprintf_s(output, 1024, FORMAT, 'C', timestamp, temp);
264                 break;
265         case QtWarningMsg:
266                 _snprintf_s(output, 1024, FORMAT, 'W', timestamp, temp);
267                 break;
268         default:
269                 _snprintf_s(output, 1024, FORMAT, 'I', timestamp, temp);
270                 break;
271         }
272
273         OutputDebugStringA(output);
274 }
275
276 static void write_terminal_helper(const int &type, const char *const message)
277 {
278         if(_isatty(_fileno(stderr)))
279         {
280                 UINT oldOutputCP = GetConsoleOutputCP();
281                 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(CP_UTF8);
282
283                 switch(type)
284                 {
285                 case QtCriticalMsg:
286                 case QtFatalMsg:
287                         set_terminal_color(stderr, COLOR_RED);
288                         fprintf(stderr, GURU_MEDITATION);
289                         fprintf(stderr, "%s\n", message);
290                         fflush(stderr);
291                         break;
292                 case QtWarningMsg:
293                         set_terminal_color(stderr, COLOR_YELLOW);
294                         fprintf(stderr, "%s\n", message);
295                         fflush(stderr);
296                         break;
297                 default:
298                         set_terminal_color(stderr, COLOR_WHITE);
299                         fprintf(stderr, "%s\n", message);
300                         fflush(stderr);
301                         break;
302                 }
303         
304                 set_terminal_color(stderr, COLOR_DEFAULT);
305                 if(oldOutputCP != CP_UTF8)
306                 {
307                         SetConsoleOutputCP(oldOutputCP);
308                 }
309         }
310 }
311
312 void MUtils::Terminal::write(const int &type, const char *const message)
313 {
314         MUtils::Internal::CSLocker lock(g_terminal_lock);
315
316         if(g_terminal_attached)
317         {
318                 write_terminal_helper(type, message);
319         }
320         else
321         {
322                 write_debugger_helper(type, message);
323         }
324
325         if(!g_log_file.isNull())
326         {
327                 write_logfile_helper(g_log_file.data(), type, message);
328         }
329 }