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