Arkanjo 0.2
A tool for find code duplicated functions in codebases
Loading...
Searching...
No Matches
posix_utils.cpp
Go to the documentation of this file.
2
3#include <termios.h>
4#include <sys/ioctl.h>
5#include <unistd.h>
6#include <sys/utsname.h>
7#include <tuple>
8
9int convert_16_bit_to_8_bit(const std::string& hex16) {
10 try {
11 unsigned long value = std::stoul(hex16, nullptr, 16);
12 return static_cast<int>(value / 256);
13 } catch (...) {
14 return 0;
15 }
16}
17
18std::tuple<int, int, int> UtilsOSDependable::parse_terminal_color_response(const std::string& response) {
19 const size_t start_pos = response.find("rgb:");
20 if (start_pos == std::string::npos) {
21 return {0, 0, 0};
22 }
23
24 const size_t end_pos = response.find("\033\\", start_pos);
25 if (end_pos == std::string::npos) {
26 return {0, 0, 0};
27 }
28
29 std::string rgb_str = response.substr(start_pos + 4, end_pos - (start_pos + 4));
30
31 replace(rgb_str.begin(), rgb_str.end(), '/', ' ');
32
33 std::istringstream iss(rgb_str);
34 std::string r_hex, g_hex, b_hex;
35 iss >> r_hex >> g_hex >> b_hex;
36
37 int r = convert_16_bit_to_8_bit(r_hex);
38 int g = convert_16_bit_to_8_bit(g_hex);
39 int b = convert_16_bit_to_8_bit(b_hex);
40
41 return {r, g, b};
42}
43
44std::string UtilsOSDependable::capture_terminal_response() {
45 termios oldt, newt;
46 tcgetattr(STDIN_FILENO, &oldt);
47 newt = oldt;
48 newt.c_lflag &= ~(ICANON | ECHO);
49 tcsetattr(STDIN_FILENO, TCSANOW, &newt);
50
51 int oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
52 fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
53
54 std::cout << "\033]11;?\033\\";
55 std::cout.flush();
56
57 std::string response;
58 char ch;
59 timeval tv;
60 tv.tv_sec = 0;
61 tv.tv_usec = 100000; // 100ms timeout
62
63 fd_set readfds;
64 FD_ZERO(&readfds);
65 FD_SET(STDIN_FILENO, &readfds);
66
67 while (select(STDIN_FILENO + 1, &readfds, NULL, NULL, &tv) > 0) {
68 if (read(STDIN_FILENO, &ch, 1) > 0) {
69 response += ch;
70 } else {
71 break;
72 }
73 }
74
75 tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
76 fcntl(STDIN_FILENO, F_SETFL, oldf);
77
78 return response;
79}
80
81float UtilsOSDependable::get_terminal_bg_color_luminance() {
82 if (!isatty(fileno(stdout)) || !isatty(fileno(stdin))) {
83 return 0;
84 }
85
86 std::string color_str = capture_terminal_response();
87 auto [r, g, b] = parse_terminal_color_response(color_str);
88 float luminance = 0.2126 * (r / 255.0) + 0.7152 * (g / 255.0) + 0.0722 * (b / 255.0);
89
90 return luminance;
91}
92
94 return get_terminal_bg_color_luminance() <= 0.5;
95}
96
97int UtilsOSDependable::run_process(const char* cmd, char* const argv[]) {
98 execvp(cmd, argv);
99 return -1;
100}
static int run_process(const char *cmd, char *const argv[])
Executes an external program, replacing the current process (exec-style).
static bool is_bg_color_dark()
Determines if terminal background color is dark.
utility functions
int convert_16_bit_to_8_bit(const std::string &hex16)