CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
hrydgard

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: hrydgard/ppsspp
Path: blob/master/Common/Log/ConsoleListener.cpp
Views: 1401
1
// Copyright (C) 2003 Dolphin Project.
2
3
// This program is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU General Public License as published by
5
// the Free Software Foundation, version 2.0 or later versions.
6
7
// This program is distributed in the hope that it will be useful,
8
// but WITHOUT ANY WARRANTY; without even the implied warranty of
9
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
// GNU General Public License 2.0 for more details.
11
12
// A copy of the GPL 2.0 should have been included with the program.
13
// If not, see http://www.gnu.org/licenses/
14
15
// Official SVN repository and contact information can be found at
16
// http://code.google.com/p/dolphin-emu/
17
18
#include "ppsspp_config.h"
19
20
#if PPSSPP_PLATFORM(WINDOWS) && !PPSSPP_PLATFORM(UWP)
21
#include <atomic>
22
#include <algorithm> // min
23
#include <array>
24
#include <cstring>
25
#include <string> // System: To be able to add strings with "+"
26
#include <math.h>
27
#include <process.h>
28
#include "Common/CommonWindows.h"
29
30
#ifndef _MSC_VER
31
#include <unistd.h>
32
#endif
33
34
#include "Common/Thread/ThreadUtil.h"
35
#include "Common/Data/Encoding/Utf8.h"
36
#include "Common/CommonTypes.h"
37
#include "Common/Log/ConsoleListener.h"
38
#include "Common/StringUtils.h"
39
40
const int LOG_PENDING_MAX = 120 * 10000;
41
const int LOG_LATENCY_DELAY_MS = 20;
42
const int LOG_SHUTDOWN_DELAY_MS = 250;
43
const int LOG_MAX_DISPLAY_LINES = 4000;
44
45
static bool g_Initialized;
46
47
ConsoleListener::ConsoleListener() : hidden_(true) {
48
useColor_ = true;
49
50
// useThread_ = false;
51
52
if (useThread_ && !hTriggerEvent) {
53
hTriggerEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
54
InitializeCriticalSection(&criticalSection);
55
logPending_ = new char[LOG_PENDING_MAX];
56
}
57
58
_dbg_assert_(!g_Initialized);
59
g_Initialized = true;
60
61
logPendingReadPos_.store(0);
62
logPendingWritePos_.store(0);
63
}
64
65
ConsoleListener::~ConsoleListener() {
66
g_Initialized = false;
67
Close();
68
}
69
70
// Handle console event
71
bool WINAPI ConsoleHandler(DWORD msgType) {
72
if (msgType == CTRL_C_EVENT) {
73
OutputDebugString(L"Ctrl-C!\n");
74
return TRUE;
75
} else if (msgType == CTRL_CLOSE_EVENT) {
76
OutputDebugString(L"Close console window!\n");
77
return TRUE;
78
}
79
/*
80
Other messages:
81
CTRL_BREAK_EVENT Ctrl-Break pressed
82
CTRL_LOGOFF_EVENT User log off
83
CTRL_SHUTDOWN_EVENT System shutdown
84
*/
85
return FALSE;
86
}
87
88
// Open console window - width and height is the size of console window
89
// Name is the window title
90
void ConsoleListener::Init(bool AutoOpen, int Width, int Height) {
91
openWidth_ = Width;
92
openHeight_ = Height;
93
if (AutoOpen) {
94
Open();
95
hidden_ = false;
96
}
97
}
98
99
void ConsoleListener::Open() {
100
if (!GetConsoleWindow()) {
101
// Open the console window and create the window handle for GetStdHandle()
102
AllocConsole();
103
hWnd = GetConsoleWindow();
104
ShowWindow(hWnd, SW_SHOWDEFAULT);
105
// disable console close button
106
HMENU hMenu = GetSystemMenu(hWnd, false);
107
EnableMenuItem(hMenu,SC_CLOSE,MF_GRAYED|MF_BYCOMMAND);
108
// Save the window handle that AllocConsole() created
109
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
110
// Set console handler
111
if (SetConsoleCtrlHandler((PHANDLER_ROUTINE)ConsoleHandler, TRUE)) {
112
OutputDebugStringA("Console handler is installed!\n");
113
}
114
// Set the console window title
115
SetConsoleTitle(L"PPSSPP Debug Console");
116
SetConsoleCP(CP_UTF8);
117
SetConsoleOutputCP(CP_UTF8);
118
119
// Set letter space
120
LetterSpace(openWidth_, LOG_MAX_DISPLAY_LINES);
121
//MoveWindow(GetConsoleWindow(), 200,200, 800,800, true);
122
} else {
123
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
124
}
125
126
if (useThread_ && hTriggerEvent != NULL && !thread_.joinable()) {
127
thread_ = std::thread([&] {
128
SetCurrentThreadName("Console");
129
LogWriterThread();
130
});
131
}
132
}
133
134
void ConsoleListener::Show(bool bShow) {
135
if (bShow && hidden_) {
136
if (!IsOpen()) {
137
Open();
138
}
139
ShowWindow(GetConsoleWindow(), SW_SHOW);
140
hidden_ = false;
141
} else if (!bShow && !hidden_) {
142
ShowWindow(GetConsoleWindow(), SW_HIDE);
143
hidden_ = true;
144
}
145
}
146
147
void ConsoleListener::UpdateHandle() {
148
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
149
}
150
151
// Close the console window and close the eventual file handle
152
void ConsoleListener::Close() {
153
if (thread_.joinable()) {
154
logPendingWritePos_.store((u32)-1, std::memory_order_release);
155
SetEvent(hTriggerEvent);
156
thread_.join();
157
}
158
if (hTriggerEvent) {
159
DeleteCriticalSection(&criticalSection);
160
CloseHandle(hTriggerEvent);
161
hTriggerEvent = nullptr;
162
}
163
if (logPending_) {
164
delete [] logPending_;
165
logPending_ = nullptr;
166
}
167
168
if (hConsole) {
169
FreeConsole();
170
hConsole = nullptr;
171
}
172
}
173
174
bool ConsoleListener::IsOpen() {
175
return (hConsole != nullptr);
176
}
177
178
// LetterSpace: SetConsoleScreenBufferSize and SetConsoleWindowInfo are
179
// dependent on each other, that's the reason for the additional checks.
180
void ConsoleListener::BufferWidthHeight(int BufferWidth, int BufferHeight, int ScreenWidth, int ScreenHeight, bool BufferFirst) {
181
_dbg_assert_msg_(IsOpen(), "Don't call this before opening the console.");
182
BOOL SB, SW;
183
if (BufferFirst) {
184
// Change screen buffer size
185
COORD Co = {(SHORT)BufferWidth, (SHORT)BufferHeight};
186
SB = SetConsoleScreenBufferSize(hConsole, Co);
187
// Change the screen buffer window size
188
SMALL_RECT coo = {(SHORT)0, (SHORT)0, (SHORT)ScreenWidth, (SHORT)ScreenHeight}; // top, left, right, bottom
189
SW = SetConsoleWindowInfo(hConsole, TRUE, &coo);
190
} else {
191
// Change the screen buffer window size
192
SMALL_RECT coo = {(SHORT)0, (SHORT)0, (SHORT)ScreenWidth, (SHORT)ScreenHeight}; // top, left, right, bottom
193
SW = SetConsoleWindowInfo(hConsole, TRUE, &coo);
194
// Change screen buffer size
195
COORD Co = {(SHORT)BufferWidth, (SHORT)BufferHeight};
196
SB = SetConsoleScreenBufferSize(hConsole, Co);
197
}
198
}
199
200
void ConsoleListener::LetterSpace(int Width, int Height) {
201
_dbg_assert_msg_(IsOpen(), "Don't call this before opening the console.");
202
// Get console info
203
CONSOLE_SCREEN_BUFFER_INFO ConInfo;
204
GetConsoleScreenBufferInfo(hConsole, &ConInfo);
205
206
int OldBufferWidth = ConInfo.dwSize.X;
207
int OldBufferHeight = ConInfo.dwSize.Y;
208
int OldScreenWidth = (ConInfo.srWindow.Right - ConInfo.srWindow.Left);
209
int OldScreenHeight = (ConInfo.srWindow.Bottom - ConInfo.srWindow.Top);
210
211
int NewBufferWidth = Width;
212
int NewBufferHeight = Height;
213
int NewScreenWidth = NewBufferWidth - 1;
214
int NewScreenHeight = OldScreenHeight;
215
216
// Width
217
BufferWidthHeight(NewBufferWidth, OldBufferHeight, NewScreenWidth, OldScreenHeight, (NewBufferWidth > OldScreenWidth-1));
218
// Height
219
BufferWidthHeight(NewBufferWidth, NewBufferHeight, NewScreenWidth, NewScreenHeight, (NewBufferHeight > OldScreenHeight-1));
220
221
// Resize the window too
222
// MoveWindow(GetConsoleWindow(), 200,200, (Width*8 + 50),(NewScreenHeight*12 + 200), true);
223
}
224
225
COORD ConsoleListener::GetCoordinates(int BytesRead, int BufferWidth) {
226
COORD Ret = {0, 0};
227
// Full rows
228
int Step = (int)floor((float)BytesRead / (float)BufferWidth);
229
Ret.Y += Step;
230
// Partial row
231
Ret.X = BytesRead - (BufferWidth * Step);
232
return Ret;
233
}
234
235
void ConsoleListener::LogWriterThread() {
236
char *logLocal = new char[LOG_PENDING_MAX];
237
int logLocalSize = 0;
238
239
while (true) {
240
WaitForSingleObject(hTriggerEvent, INFINITE);
241
Sleep(LOG_LATENCY_DELAY_MS);
242
243
u32 logRemotePos = logPendingWritePos_.load(std::memory_order_acquire);
244
if (logRemotePos == (u32)-1) {
245
break;
246
} else if (logRemotePos == logPendingReadPos_) {
247
continue;
248
} else {
249
EnterCriticalSection(&criticalSection);
250
logRemotePos = logPendingWritePos_.load(std::memory_order_acquire);
251
252
int start = 0;
253
if (logRemotePos < logPendingReadPos_) {
254
const int count = LOG_PENDING_MAX - logPendingReadPos_;
255
memcpy(logLocal + start, logPending_ + logPendingReadPos_, count);
256
257
start = count;
258
logPendingReadPos_ = 0;
259
}
260
261
const int count = logRemotePos - logPendingReadPos_;
262
memcpy(logLocal + start, logPending_ + logPendingReadPos_, count);
263
264
logPendingReadPos_ += count;
265
LeaveCriticalSection(&criticalSection);
266
267
// Double check.
268
if (logPendingWritePos_ == (u32)-1) {
269
break;
270
}
271
272
logLocalSize = start + count;
273
}
274
275
for (char *Text = logLocal, *End = logLocal + logLocalSize; Text < End; ) {
276
LogLevel Level = LogLevel::LINFO;
277
278
char *next = (char *) memchr(Text + 1, '\033', End - Text);
279
size_t Len = next - Text;
280
if (!next) {
281
Len = End - Text;
282
}
283
284
if (Text[0] == '\033' && Text + 1 < End) {
285
Level = (LogLevel)(Text[1] - '0');
286
Len -= 2;
287
Text += 2;
288
}
289
290
// Make sure we didn't start quitting. This is kinda slow.
291
if (logPendingWritePos_ == (u32)-1) {
292
break;
293
}
294
295
WriteToConsole(Level, Text, Len);
296
Text += Len;
297
}
298
}
299
300
delete [] logLocal;
301
}
302
303
void ConsoleListener::SendToThread(LogLevel Level, const char *Text) {
304
// Oops, we're already quitting. Just do nothing.
305
if (logPendingWritePos_ == (u32)-1) {
306
return;
307
}
308
309
int Len = (int)strlen(Text);
310
if (Len > LOG_PENDING_MAX)
311
Len = LOG_PENDING_MAX - 16;
312
313
char ColorAttr[16] = "";
314
int ColorLen = 0;
315
if (useColor_) {
316
// Not ANSI, since the console doesn't support it, but ANSI-like.
317
snprintf(ColorAttr, 16, "\033%d", Level);
318
// For now, rather than properly support it.
319
_dbg_assert_msg_(strlen(ColorAttr) == 2, "Console logging doesn't support > 9 levels.");
320
ColorLen = (int)strlen(ColorAttr);
321
}
322
323
EnterCriticalSection(&criticalSection);
324
u32 logWritePos = logPendingWritePos_.load();
325
u32 prevLogWritePos = logWritePos;
326
if (logWritePos + ColorLen + Len >= LOG_PENDING_MAX) {
327
for (int i = 0; i < ColorLen; ++i) {
328
logPending_[(logWritePos + i) % LOG_PENDING_MAX] = ColorAttr[i];
329
}
330
logWritePos += ColorLen;
331
if (logWritePos >= LOG_PENDING_MAX)
332
logWritePos -= LOG_PENDING_MAX;
333
334
int start = 0;
335
if (logWritePos < LOG_PENDING_MAX && logWritePos + Len >= LOG_PENDING_MAX) {
336
const int count = LOG_PENDING_MAX - logWritePos;
337
memcpy(logPending_ + logWritePos, Text, count);
338
start = count;
339
logWritePos = 0;
340
}
341
const int count = Len - start;
342
if (count > 0) {
343
memcpy(logPending_ + logWritePos, Text + start, count);
344
logWritePos += count;
345
}
346
} else {
347
memcpy(logPending_ + logWritePos, ColorAttr, ColorLen);
348
memcpy(logPending_ + logWritePos + ColorLen, Text, Len);
349
logWritePos += ColorLen + Len;
350
}
351
352
// Oops, we passed the read pos.
353
if (prevLogWritePos < logPendingReadPos_ && logWritePos >= logPendingReadPos_) {
354
char *nextNewline = (char *) memchr(logPending_ + logWritePos, '\n', LOG_PENDING_MAX - logWritePos);
355
if (nextNewline == NULL && logWritePos > 0)
356
nextNewline = (char *) memchr(logPending_, '\n', logWritePos);
357
358
// Okay, have it go right after the next newline.
359
if (nextNewline != NULL)
360
logPendingReadPos_ = (u32)(nextNewline - logPending_ + 1);
361
}
362
363
// Double check we didn't start quitting.
364
if (logPendingWritePos_ == (u32) -1) {
365
LeaveCriticalSection(&criticalSection);
366
return;
367
}
368
369
logPendingWritePos_.store(logWritePos, std::memory_order::memory_order_release);
370
LeaveCriticalSection(&criticalSection);
371
372
SetEvent(hTriggerEvent);
373
}
374
375
void ConsoleListener::WriteToConsole(LogLevel Level, const char *Text, size_t Len) {
376
_dbg_assert_msg_(IsOpen(), "Don't call this before opening the console.");
377
378
/*
379
const int MAX_BYTES = 1024*10;
380
char Str[MAX_BYTES];
381
va_list ArgPtr;
382
int Cnt;
383
va_start(ArgPtr, Text);
384
Cnt = vsnprintf(Str, MAX_BYTES, Text, ArgPtr);
385
va_end(ArgPtr);
386
*/
387
DWORD cCharsWritten;
388
WORD Color;
389
static wchar_t tempBuf[2048];
390
391
switch (Level) {
392
case LogLevel::LNOTICE: // light green
393
Color = FOREGROUND_GREEN | FOREGROUND_INTENSITY;
394
break;
395
case LogLevel::LERROR: // light red
396
Color = FOREGROUND_RED | FOREGROUND_INTENSITY;
397
break;
398
case LogLevel::LWARNING: // light yellow
399
Color = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY;
400
break;
401
case LogLevel::LINFO: // cyan
402
Color = FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY;
403
break;
404
case LogLevel::LDEBUG: // gray
405
Color = FOREGROUND_INTENSITY;
406
break;
407
default: // off-white
408
Color = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
409
break;
410
}
411
if (Len > 10) {
412
// First 10 chars white
413
SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
414
int wlen = MultiByteToWideChar(CP_UTF8, 0, Text, (int)Len, NULL, NULL);
415
MultiByteToWideChar(CP_UTF8, 0, Text, (int)Len, tempBuf, wlen);
416
WriteConsole(hConsole, tempBuf, 10, &cCharsWritten, NULL);
417
Text += 10;
418
Len -= 10;
419
}
420
SetConsoleTextAttribute(hConsole, Color);
421
int wlen = MultiByteToWideChar(CP_UTF8, 0, Text, (int)Len, NULL, NULL);
422
MultiByteToWideChar(CP_UTF8, 0, Text, (int)Len, tempBuf, wlen);
423
WriteConsole(hConsole, tempBuf, (DWORD)wlen, &cCharsWritten, NULL);
424
}
425
426
void ConsoleListener::PixelSpace(int Left, int Top, int Width, int Height, bool Resize) {
427
_dbg_assert_msg_(IsOpen(), "Don't call this before opening the console.");
428
// Check size
429
if (Width < 8 || Height < 12) return;
430
431
std::string SLog = "";
432
433
// Get console info
434
CONSOLE_SCREEN_BUFFER_INFO ConInfo;
435
GetConsoleScreenBufferInfo(hConsole, &ConInfo);
436
DWORD BufferSize = ConInfo.dwSize.X * ConInfo.dwSize.Y;
437
438
// ---------------------------------------------------------------------
439
// Save the current text
440
// ------------------------
441
DWORD cCharsRead = 0;
442
COORD coordScreen = { 0, 0 };
443
444
static const int MAX_BYTES = 1024 * 16;
445
446
std::vector<std::array<wchar_t, MAX_BYTES>> Str;
447
std::vector<std::array<WORD, MAX_BYTES>> Attr;
448
449
// ReadConsoleOutputAttribute seems to have a limit at this level
450
static const int ReadBufferSize = MAX_BYTES - 32;
451
452
DWORD cAttrRead = ReadBufferSize;
453
DWORD BytesRead = 0;
454
while (BytesRead < BufferSize) {
455
Str.resize(Str.size() + 1);
456
if (!ReadConsoleOutputCharacter(hConsole, Str.back().data(), ReadBufferSize, coordScreen, &cCharsRead))
457
SLog += StringFromFormat("WriteConsoleOutputCharacter error");
458
459
Attr.resize(Attr.size() + 1);
460
if (!ReadConsoleOutputAttribute(hConsole, Attr.back().data(), ReadBufferSize, coordScreen, &cAttrRead))
461
SLog += StringFromFormat("WriteConsoleOutputAttribute error");
462
463
// Break on error
464
if (cAttrRead == 0) break;
465
BytesRead += cAttrRead;
466
coordScreen = GetCoordinates(BytesRead, ConInfo.dwSize.X);
467
}
468
// Letter space
469
int LWidth = (int)(floor((float)Width / 8.0f) - 1.0f);
470
int LHeight = (int)(floor((float)Height / 12.0f) - 1.0f);
471
int LBufWidth = LWidth + 1;
472
int LBufHeight = (int)floor((float)BufferSize / (float)LBufWidth);
473
// Change screen buffer size
474
LetterSpace(LBufWidth, LBufHeight);
475
476
477
ClearScreen(true);
478
coordScreen.Y = 0;
479
coordScreen.X = 0;
480
DWORD cCharsWritten = 0;
481
482
int BytesWritten = 0;
483
DWORD cAttrWritten = 0;
484
for (size_t i = 0; i < Attr.size(); i++) {
485
if (!WriteConsoleOutputCharacter(hConsole, Str[i].data(), ReadBufferSize, coordScreen, &cCharsWritten))
486
SLog += StringFromFormat("WriteConsoleOutputCharacter error");
487
if (!WriteConsoleOutputAttribute(hConsole, Attr[i].data(), ReadBufferSize, coordScreen, &cAttrWritten))
488
SLog += StringFromFormat("WriteConsoleOutputAttribute error");
489
490
BytesWritten += cAttrWritten;
491
coordScreen = GetCoordinates(BytesWritten, LBufWidth);
492
}
493
494
const int OldCursor = ConInfo.dwCursorPosition.Y * ConInfo.dwSize.X + ConInfo.dwCursorPosition.X;
495
COORD Coo = GetCoordinates(OldCursor, LBufWidth);
496
SetConsoleCursorPosition(hConsole, Coo);
497
498
// if (SLog.length() > 0) Log(LogLevel::LNOTICE, SLog.c_str());
499
500
// Resize the window too
501
if (Resize) {
502
MoveWindow(GetConsoleWindow(), Left, Top, (Width + 100), Height, true);
503
}
504
}
505
506
void ConsoleListener::Log(const LogMessage &msg) {
507
char buf[2048];
508
snprintf(buf, sizeof(buf), "%s %s %s", msg.timestamp, msg.header, msg.msg.c_str());
509
buf[sizeof(buf) - 2] = '\n';
510
buf[sizeof(buf) - 1] = '\0';
511
512
if (!useThread_ && IsOpen())
513
WriteToConsole(msg.level, buf, strlen(buf));
514
else
515
SendToThread(msg.level, buf);
516
}
517
518
// Clear console screen
519
void ConsoleListener::ClearScreen(bool Cursor) {
520
_dbg_assert_msg_(IsOpen(), "Don't call this before opening the console.");
521
522
CONSOLE_SCREEN_BUFFER_INFO csbi;
523
GetConsoleScreenBufferInfo(hConsole, &csbi);
524
DWORD dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
525
// Write space to the entire console
526
DWORD cCharsWritten;
527
COORD coordScreen = { 0, 0 };
528
FillConsoleOutputCharacter(hConsole, TEXT(' '), dwConSize, coordScreen, &cCharsWritten);
529
GetConsoleScreenBufferInfo(hConsole, &csbi);
530
FillConsoleOutputAttribute(hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten);
531
// Reset cursor
532
if (Cursor) {
533
SetConsoleCursorPosition(hConsole, coordScreen);
534
}
535
}
536
537
#endif // PPSSPP_PLATFORM(WINDOWS)
538
539