Added the set_file_time() function.
[MUtilities.git] / src / Terminal_Win32.cpp
blob8731dcb5d1568dd091ef68cf31589cb4988ab68d
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.
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.
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.
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
23 //Windows includes
24 #define NOMINMAX
25 #define WIN32_LEAN_AND_MEAN 1
26 #include <Windows.h>
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"
35 //Qt
36 #include <QFile>
37 #include <QStringList>
38 #include <QIcon>
39 #include <QLibrary>
41 //CRT
42 #include <iostream>
43 #include <fstream>
44 #include <ctime>
45 #include <stdarg.h>
46 #include <io.h>
47 #include <fcntl.h>
49 #ifdef _MSC_VER
50 #define stricmp(X,Y) _stricmp((X),(Y))
51 #endif
53 #define VALID_HANLDE(X) (((X) != NULL) && ((X) != INVALID_HANDLE_VALUE))
55 ///////////////////////////////////////////////////////////////////////////////
56 // TERMINAL VARIABLES
57 ///////////////////////////////////////////////////////////////////////////////
59 //Critical section
60 static MUtils::Internal::CriticalSection g_terminal_lock;
62 //Is terminal attached?
63 static volatile bool g_terminal_attached = false;
65 //Terminal output buffer
66 static const size_t BUFF_SIZE = 8192;
67 static char g_conOutBuff[BUFF_SIZE] = { '\0' };
69 //Buffer objects
70 static QScopedPointer<std::filebuf> g_fileBuf_stdout;
71 static QScopedPointer<std::filebuf> g_fileBuf_stderr;
73 //The log file
74 static QScopedPointer<QFile> g_terminal_log_file;
76 ///////////////////////////////////////////////////////////////////////////////
77 // HELPER FUNCTIONS
78 ///////////////////////////////////////////////////////////////////////////////
80 static inline void make_timestamp(char *timestamp, const size_t &buffsize)
82 time_t rawtime;
83 struct tm timeinfo;
85 time(&rawtime);
86 if(localtime_s(&timeinfo, &rawtime) == 0)
88 strftime(timestamp, buffsize, "%H:%M:%S", &timeinfo);
90 else
92 timestamp[0] = '\0';
96 static inline bool null_or_whitespace(const char *const str)
98 if (str)
100 size_t pos = 0;
101 while (str[pos])
103 if (!(isspace(str[pos]) || iscntrl(str[pos])))
105 return false;
107 pos++;
110 return true;
113 static inline size_t clean_string(char *const str)
115 bool space_flag = true;
116 size_t src = 0, out = 0;
118 while (str[src])
120 if (isspace(str[src]) || iscntrl(str[src])) /*replace any space-sequence with a single space character*/
122 src++;
123 if (!space_flag)
125 space_flag = true;
126 str[out++] = 0x20;
129 else /*otherwise we'll just copy over the current character*/
131 if (src != out)
133 str[out] = str[src];
135 space_flag = false;
136 out++; src++;
140 if (space_flag && (out > 0)) /*trim trailing space, if any*/
142 out--;
145 str[out] = NULL;
146 return out;
149 ///////////////////////////////////////////////////////////////////////////////
150 // TERMINAL SETUP
151 ///////////////////////////////////////////////////////////////////////////////
153 static inline std::filebuf *terminal_connect(FILE *const fs, std::ostream &os)
155 std::filebuf *result = NULL;
156 FILE *temp;
157 if (freopen_s(&temp, "CONOUT$", "wb", fs) == 0)
159 os.rdbuf(result = new std::filebuf(temp));
161 return result;
164 static void terminal_shutdown(void)
166 MUtils::Internal::CSLocker lock(g_terminal_lock);
168 if (g_terminal_attached)
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;
180 void MUtils::Terminal::setup(int &argc, char **argv, const char* const appName, const bool forceEnabled)
182 MUtils::Internal::CSLocker lock(g_terminal_lock);
183 bool enableConsole = (MUTILS_DEBUG) || forceEnabled;
185 if(_environ)
187 wchar_t *logfile = NULL; size_t logfile_len = 0;
188 if(!_wdupenv_s(&logfile, &logfile_len, L"MUTILS_LOGFILE"))
190 if(logfile && (logfile_len > 0))
192 g_terminal_log_file.reset(new QFile(MUTILS_QSTR(logfile)));
193 if(g_terminal_log_file->open(QIODevice::WriteOnly))
195 static const char MARKER[3] = { char(0xEF), char(0xBB), char(0xBF) };
196 g_terminal_log_file->write(MARKER, 3);
198 free(logfile);
203 if(!MUTILS_DEBUG)
205 for(int i = 0; i < argc; i++)
207 if(!stricmp(argv[i], "--console"))
209 enableConsole = true;
211 else if(!stricmp(argv[i], "--no-console"))
213 enableConsole = false;
218 if(enableConsole)
220 if(!g_terminal_attached)
222 if(AllocConsole() != FALSE)
224 SetConsoleOutputCP(CP_UTF8);
225 SetConsoleCtrlHandler(NULL, TRUE);
226 if(appName && appName[0])
228 char title[128];
229 _snprintf_s(title, 128, _TRUNCATE, "%s | Debug Console", appName);
230 SetConsoleTitleA(title);
232 g_terminal_attached = true;
236 if(g_terminal_attached)
238 g_fileBuf_stdout.reset(terminal_connect(stdout, std::cout));
239 g_fileBuf_stderr.reset(terminal_connect(stderr, std::cerr));
241 atexit(terminal_shutdown);
243 const HWND hwndConsole = GetConsoleWindow();
244 if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
246 HMENU hMenu = GetSystemMenu(hwndConsole, 0);
247 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
248 RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
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);
258 ///////////////////////////////////////////////////////////////////////////////
259 // TERMINAL COLORS
260 ///////////////////////////////////////////////////////////////////////////////
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;
268 static void set_terminal_color(FILE *const fp, const WORD &attributes)
270 if(_isatty(_fileno(fp)))
272 const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(fp)));
273 if (VALID_HANLDE(hConsole))
275 SetConsoleTextAttribute(hConsole, attributes);
280 ///////////////////////////////////////////////////////////////////////////////
281 // WRITE TO TERMINAL
282 ///////////////////////////////////////////////////////////////////////////////
284 static const char *const FORMAT = "[%c][%s] %s\r\n";
285 static const char *const GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
287 static void write_to_logfile(QFile *const file, const int &type, const char *const message)
289 int len = -1;
291 if (null_or_whitespace(message))
293 return; /*don't write empty message to log file*/
296 static char timestamp[32];
297 make_timestamp(timestamp, 32);
299 switch(type)
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;
313 if (len > 0)
315 if (clean_string(g_conOutBuff) > 0)
317 file->write(g_conOutBuff);
318 file->flush();
323 static void write_to_debugger(const int &type, const char *const message)
325 int len = -1;
327 if (null_or_whitespace(message))
329 return; /*don't send empty message to debugger*/
332 static char timestamp[32];
333 make_timestamp(timestamp, 32);
335 switch(type)
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;
349 if (len > 0)
351 if (clean_string(g_conOutBuff) > 0)
353 OutputDebugStringA(g_conOutBuff);
358 static void write_to_terminal(const int &type, const char *const message)
360 switch(type)
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;
378 fflush(stderr);
381 void MUtils::Terminal::write(const int &type, const char *const message)
383 MUtils::Internal::CSLocker lock(g_terminal_lock);
385 if(g_terminal_attached)
387 write_to_terminal(type, message);
389 else
391 write_to_debugger(type, message);
394 if(!g_terminal_log_file.isNull())
396 write_to_logfile(g_terminal_log_file.data(), type, message);
400 ///////////////////////////////////////////////////////////////////////////////
401 // TERMINAL ICON
402 ///////////////////////////////////////////////////////////////////////////////
404 void MUtils::Terminal::set_icon(const QIcon &icon)
406 MUtils::Internal::CSLocker lock(g_terminal_lock);
408 if(g_terminal_attached && (!(icon.isNull() || MUtils::OS::running_on_wine())))
410 QLibrary kernel32("kernel32.dll");
411 if(kernel32.load())
413 typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
414 if(SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon"))
416 if(HICON hIcon = qicon_to_hicon(icon, 16, 16))
418 SetConsoleIconPtr(hIcon);
419 DestroyIcon(hIcon);