-
Notifications
You must be signed in to change notification settings - Fork 294
Expand file tree
/
Copy pathterm_util.cpp
More file actions
117 lines (97 loc) · 2.65 KB
/
Copy pathterm_util.cpp
File metadata and controls
117 lines (97 loc) · 2.65 KB
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
113
114
115
116
117
#include "term_util.h"
#include <windows.h>
#include <iostream>
#include <string>
#include <mutex>
#include <paramkit.h>
std::mutex g_stdOutMutex;
bool hh::util::get_current_color(int descriptor, WORD &color)
{
HANDLE hConsole = GetStdHandle(descriptor);
if (hConsole == INVALID_HANDLE_VALUE || hConsole == NULL) {
return false;
}
return paramkit::get_console_color(hConsole, color);
}
WORD hh::util::set_color(WORD color)
{
WORD old_color = 7;
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
if (hConsole == INVALID_HANDLE_VALUE || hConsole == NULL) {
return old_color;
}
if (paramkit::get_console_color(hConsole, old_color)) {
SetConsoleTextAttribute(hConsole, color);
}
return old_color;
}
void hh::util::print_in_color(WORD color, const std::string &text)
{
const std::lock_guard<std::mutex> stdOutLock(g_stdOutMutex);
paramkit::print_in_color(color, text);
}
std::string hh::util::wstring_to_utf8(const std::wstring& wstr)
{
if (wstr.empty())
return {};
int size = WideCharToMultiByte(
CP_UTF8,
0,
wstr.data(),
static_cast<int>(wstr.size()),
nullptr,
0,
nullptr,
nullptr);
if (size == 0) {
//throw std::runtime_error("WideCharToMultiByte failed");
std::wcerr << "WideCharToMultiByte failed for: " << wstr << std::endl;
return {};
}
std::string result(size, '\0');
int converted = WideCharToMultiByte(
CP_UTF8,
0,
wstr.data(),
static_cast<int>(wstr.size()),
result.data(),
size,
nullptr,
nullptr);
if (converted == 0) {
//throw std::runtime_error("WideCharToMultiByte failed");
std::wcerr << "WideCharToMultiByte failed for: " << wstr << std::endl;
return {};
}
return result;
}
std::wstring hh::util::utf8_to_wstring(const std::string& utf8)
{
if (utf8.empty())
return {};
int size = MultiByteToWideChar(
CP_UTF8,
0,
utf8.data(),
static_cast<int>(utf8.size()),
nullptr,
0);
if (size == 0) {
//throw std::runtime_error("MultiByteToWideChar failed");
std::cerr << "MultiByteToWideChar failed for: " << utf8 << std::endl;
return {};
}
std::wstring result(size, L'\0');
int converted = MultiByteToWideChar(
CP_UTF8,
0,
utf8.data(),
static_cast<int>(utf8.size()),
result.data(),
size);
if (converted == 0) {
std::cerr << "MultiByteToWideChar failed for: " << utf8 << std::endl;
return {};
}
return result;
}