OSDN Git Service

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