OSDN Git Service

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