-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathterminal_title.cpp
More file actions
112 lines (96 loc) · 2.89 KB
/
Copy pathterminal_title.cpp
File metadata and controls
112 lines (96 loc) · 2.89 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
#include "terminal_title.hpp"
#include <iostream>
#include <algorithm>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#endif
namespace acecode {
namespace {
constexpr size_t kMaxTitleBytes = 256;
size_t utf8_safe_prefix(const std::string& text, size_t max_bytes) {
const size_t limit = std::min(max_bytes, text.size());
size_t i = 0;
size_t last_valid = 0;
while (i < limit) {
const unsigned char c = static_cast<unsigned char>(text[i]);
size_t seq_len = 0;
if ((c & 0x80u) == 0) {
seq_len = 1;
} else if ((c & 0xE0u) == 0xC0u) {
seq_len = 2;
} else if ((c & 0xF0u) == 0xE0u) {
seq_len = 3;
} else if ((c & 0xF8u) == 0xF0u) {
seq_len = 4;
} else {
break;
}
if (i + seq_len > limit || i + seq_len > text.size()) break;
bool valid = true;
for (size_t j = 1; j < seq_len; ++j) {
const unsigned char cc = static_cast<unsigned char>(text[i + j]);
if ((cc & 0xC0u) != 0x80u) { valid = false; break; }
}
if (!valid) break;
i += seq_len;
last_valid = i;
}
return last_valid;
}
} // namespace
void set_terminal_title(std::string_view text) {
#ifdef _WIN32
if (text.empty()) {
SetConsoleTitleW(L"");
return;
}
int len = MultiByteToWideChar(CP_UTF8, 0, text.data(),
static_cast<int>(text.size()),
nullptr, 0);
if (len <= 0) {
SetConsoleTitleA(std::string(text).c_str());
return;
}
std::wstring wide(static_cast<size_t>(len), L'\0');
MultiByteToWideChar(CP_UTF8, 0, text.data(),
static_cast<int>(text.size()),
wide.data(), len);
SetConsoleTitleW(wide.c_str());
#else
std::string buf;
buf.reserve(text.size() + 6);
buf.append("\x1b]2;");
buf.append(text.data(), text.size());
buf.append("\x1b\\");
std::cout.write(buf.data(), static_cast<std::streamsize>(buf.size()));
std::cout.flush();
#endif
}
void clear_terminal_title() {
set_terminal_title(std::string_view{});
}
bool sanitize_title(std::string& inout, std::string& error_out) {
error_out.clear();
for (unsigned char c : inout) {
// Reject any C0 control byte. OSC 2 is single-line; tabs/newlines are
// also rejected to keep the rendered title predictable.
if (c < 0x20 || c == 0x7F) {
error_out = "invalid control character";
return false;
}
}
if (inout.size() > kMaxTitleBytes) {
size_t cut = utf8_safe_prefix(inout, kMaxTitleBytes);
if (cut == 0) {
error_out = "invalid encoding";
return false;
}
inout.resize(cut);
error_out = "truncated";
}
return true;
}
} // namespace acecode