-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathConsoleControl.h
112 lines (105 loc) · 2.73 KB
/
ConsoleControl.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#pragma once
#include <cstdio>
#include <map>
#include <string>
#ifdef _WIN32
#define NOMINMAX
#include <windows.h>
#undef NOMINMAX
#else
#endif
enum ConsoleColor
{
CONSOLE_COLOR_NONE = -1,
CONSOLE_COLOR_RED = 4,
CONSOLE_COLOR_LIGHT_RED = 12,
CONSOLE_COLOR_GREEN = 2,
CONSOLE_COLOR_LIGHT_GREEN = 10,
CONSOLE_COLOR_BLUE = 1,
CONSOLE_COLOR_LIGHT_BLUE = 9,
CONSOLE_COLOR_WHITE = 7,
CONSOLE_COLOR_BLACK = 0,
};
class ConsoleControl
{
private:
ConsoleControl()
{
if (color_map_.empty())
{
color_map_ = {
{ CONSOLE_COLOR_NONE, "\\e[0m" },
{ CONSOLE_COLOR_RED, "\\e[0;31m" },
{ CONSOLE_COLOR_LIGHT_RED, "\\e[1;31m" },
{ CONSOLE_COLOR_GREEN, "\\e[0;32m" },
{ CONSOLE_COLOR_LIGHT_GREEN, "\\e[1;32m" },
{ CONSOLE_COLOR_BLUE, "\\e[0;34m" },
{ CONSOLE_COLOR_LIGHT_BLUE, "\\e[1;34m" },
{ CONSOLE_COLOR_WHITE, "\\e[1;37m" },
{ CONSOLE_COLOR_BLACK, "\\e[0;30m" },
};
#ifdef _WIN32
CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbiInfo);
old_color_ = csbiInfo.wAttributes;
#endif
}
}
unsigned short old_color_;
std::map<int, std::string> color_map_;
static ConsoleControl* getInstance()
{
static ConsoleControl console_control;
return &console_control;
}
private:
ConsoleControl(ConsoleControl&) = delete;
ConsoleControl& operator=(ConsoleControl&) = delete;
public:
static void setColor(ConsoleColor c)
{
setColor(static_cast<int>(c));
}
static void setColor(int c)
{
auto cc = getInstance();
#ifdef _MSC_VER
if (c != CONSOLE_COLOR_NONE)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), c);
}
else
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), cc->old_color_);
}
#else
fprintf(stderr, "%s", cc->color_map_[c].c_str());
#endif
}
static void resetColor()
{
setColor(CONSOLE_COLOR_NONE);
}
static void moveUp(int l = 1)
{
#ifdef _MSC_VER
CONSOLE_SCREEN_BUFFER_INFO info;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
info.dwCursorPosition.Y -= l;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), info.dwCursorPosition);
#else
if (l > 0)
{
fprintf(stderr, "\e[%dA", l);
}
else if (l < 0)
{
for (int i = 0; i < -l; i++) { fprintf(stderr, "\n"); }
}
#endif
}
static void moveDown(int l = 1)
{
moveUp(-l);
}
};