Fix whitespace indent -> tab indent

This commit is contained in:
aristocratos 2023-07-26 14:38:48 +02:00
parent 33faa01910
commit aca2e4be75
22 changed files with 591 additions and 591 deletions

View File

@ -4,7 +4,7 @@
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
@ -93,9 +93,9 @@ namespace Global {
string exit_error_msg; string exit_error_msg;
atomic<bool> thread_exception (false); atomic<bool> thread_exception (false);
bool debuginit{}; // defaults to false bool debuginit{}; // defaults to false
bool debug{}; // defaults to false bool debug{}; // defaults to false
bool utf_force{}; // defaults to false bool utf_force{}; // defaults to false
uint64_t start_time; uint64_t start_time;
@ -105,8 +105,8 @@ namespace Global {
atomic<bool> should_sleep (false); atomic<bool> should_sleep (false);
atomic<bool> _runner_started (false); atomic<bool> _runner_started (false);
bool arg_tty{}; // defaults to false bool arg_tty{}; // defaults to false
bool arg_low_color{}; // defaults to false bool arg_low_color{}; // defaults to false
int arg_preset = -1; int arg_preset = -1;
} }
@ -355,14 +355,14 @@ namespace Runner {
pthread_mutex_t& pt_mutex; pthread_mutex_t& pt_mutex;
public: public:
int status; int status;
thread_lock(pthread_mutex_t& mtx) : pt_mutex(mtx) { thread_lock(pthread_mutex_t& mtx) : pt_mutex(mtx) {
pthread_mutex_init(&pt_mutex, NULL); pthread_mutex_init(&pt_mutex, NULL);
status = pthread_mutex_lock(&pt_mutex); status = pthread_mutex_lock(&pt_mutex);
} }
~thread_lock() { ~thread_lock() {
if (status == 0) if (status == 0)
pthread_mutex_unlock(&pt_mutex); pthread_mutex_unlock(&pt_mutex);
} }
}; };
//* Wrapper for raising priviliges when using SUID bit //* Wrapper for raising priviliges when using SUID bit
@ -370,18 +370,18 @@ namespace Runner {
int status = -1; int status = -1;
public: public:
gain_priv() { gain_priv() {
if (Global::real_uid != Global::set_uid) if (Global::real_uid != Global::set_uid)
this->status = seteuid(Global::set_uid); this->status = seteuid(Global::set_uid);
} }
~gain_priv() { ~gain_priv() {
if (status == 0) if (status == 0)
status = seteuid(Global::real_uid); status = seteuid(Global::real_uid);
} }
}; };
string output; string output;
string empty_bg; string empty_bg;
bool pause_output{}; // defaults to false bool pause_output{}; // defaults to false
sigset_t mask; sigset_t mask;
pthread_t runner_id; pthread_t runner_id;
pthread_mutex_t mtx; pthread_mutex_t mtx;
@ -437,7 +437,7 @@ namespace Runner {
} }
//? ------------------------------- Secondary thread: async launcher and drawing ---------------------------------- //? ------------------------------- Secondary thread: async launcher and drawing ----------------------------------
void * _runner(void *) { void * _runner(void *) {
//? Block some signals in this thread to avoid deadlock from any signal handlers trying to stop this thread //? Block some signals in this thread to avoid deadlock from any signal handlers trying to stop this thread
sigemptyset(&mask); sigemptyset(&mask);
// sigaddset(&mask, SIGINT); // sigaddset(&mask, SIGINT);
@ -480,8 +480,8 @@ namespace Runner {
//! DEBUG stats //! DEBUG stats
if (Global::debug) { if (Global::debug) {
if (debug_bg.empty() or redraw) if (debug_bg.empty() or redraw)
Runner::debug_bg = Draw::createBox(2, 2, 33, 8, "", true, "μs"); Runner::debug_bg = Draw::createBox(2, 2, 33, 8, "", true, "μs");
@ -517,7 +517,7 @@ namespace Runner {
if (Global::debug) debug_timer("cpu", draw_done); if (Global::debug) debug_timer("cpu", draw_done);
} }
catch (const std::exception& e) { catch (const std::exception& e) {
throw std::runtime_error("Cpu:: -> " + string{e.what()}); throw std::runtime_error("Cpu:: -> " + string{e.what()});
} }
} }
@ -537,7 +537,7 @@ namespace Runner {
if (Global::debug) debug_timer("mem", draw_done); if (Global::debug) debug_timer("mem", draw_done);
} }
catch (const std::exception& e) { catch (const std::exception& e) {
throw std::runtime_error("Mem:: -> " + string{e.what()}); throw std::runtime_error("Mem:: -> " + string{e.what()});
} }
} }
@ -557,7 +557,7 @@ namespace Runner {
if (Global::debug) debug_timer("net", draw_done); if (Global::debug) debug_timer("net", draw_done);
} }
catch (const std::exception& e) { catch (const std::exception& e) {
throw std::runtime_error("Net:: -> " + string{e.what()}); throw std::runtime_error("Net:: -> " + string{e.what()});
} }
} }
@ -577,12 +577,12 @@ namespace Runner {
if (Global::debug) debug_timer("proc", draw_done); if (Global::debug) debug_timer("proc", draw_done);
} }
catch (const std::exception& e) { catch (const std::exception& e) {
throw std::runtime_error("Proc:: -> " + string{e.what()}); throw std::runtime_error("Proc:: -> " + string{e.what()});
} }
} }
} }
catch (const std::exception& e) { catch (const std::exception& e) {
Global::exit_error_msg = "Exception in runner thread -> " + string{e.what()}; Global::exit_error_msg = "Exception in runner thread -> " + string{e.what()};
Global::thread_exception = true; Global::thread_exception = true;
Input::interrupt = true; Input::interrupt = true;
stopping = true; stopping = true;
@ -659,7 +659,7 @@ namespace Runner {
//? ------------------------------------------ Secondary thread end ----------------------------------------------- //? ------------------------------------------ Secondary thread end -----------------------------------------------
//* Runs collect and draw in a secondary thread, unlocks and locks config to update cached values //* Runs collect and draw in a secondary thread, unlocks and locks config to update cached values
void run(const string& box, bool no_update, bool force_redraw) { void run(const string& box, bool no_update, bool force_redraw) {
atomic_wait_for(active, true, 5000); atomic_wait_for(active, true, 5000);
if (active) { if (active) {
Logger::error("Stall in Runner thread, restarting!"); Logger::error("Stall in Runner thread, restarting!");
@ -827,7 +827,7 @@ int main(int argc, char **argv) {
} }
else { else {
string found; string found;
bool set_failure{}; // defaults to false bool set_failure{}; // defaults to false
for (const auto loc_env : array{"LANG", "LC_ALL"}) { for (const auto loc_env : array{"LANG", "LC_ALL"}) {
if (std::getenv(loc_env) != NULL and str_to_upper(s_replace((string)std::getenv(loc_env), "-", "")).ends_with("UTF8")) { if (std::getenv(loc_env) != NULL and str_to_upper(s_replace((string)std::getenv(loc_env), "-", "")).ends_with("UTF8")) {
found = std::getenv(loc_env); found = std::getenv(loc_env);
@ -923,7 +923,7 @@ int main(int argc, char **argv) {
Shared::init(); Shared::init();
} }
catch (const std::exception& e) { catch (const std::exception& e) {
Global::exit_error_msg = "Exception in Shared::init() -> " + string{e.what()}; Global::exit_error_msg = "Exception in Shared::init() -> " + string{e.what()};
clean_quit(1); clean_quit(1);
} }
@ -1035,7 +1035,7 @@ int main(int argc, char **argv) {
} }
} }
catch (const std::exception& e) { catch (const std::exception& e) {
Global::exit_error_msg = "Exception in main loop -> " + string{e.what()}; Global::exit_error_msg = "Exception in main loop -> " + string{e.what()};
clean_quit(1); clean_quit(1);
} }

View File

@ -4,7 +4,7 @@
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
@ -103,7 +103,7 @@ namespace Config {
{"proc_left", "#* Show proc box on left side of screen instead of right."}, {"proc_left", "#* Show proc box on left side of screen instead of right."},
{"proc_filter_kernel", "#* (Linux) Filter processes tied to the Linux kernel(similar behavior to htop)."}, {"proc_filter_kernel", "#* (Linux) Filter processes tied to the Linux kernel(similar behavior to htop)."},
{"cpu_graph_upper", "#* Sets the CPU stat shown in upper half of the CPU graph, \"total\" is always available.\n" {"cpu_graph_upper", "#* Sets the CPU stat shown in upper half of the CPU graph, \"total\" is always available.\n"
"#* Select from a list of detected attributes from the options menu."}, "#* Select from a list of detected attributes from the options menu."},
@ -234,7 +234,7 @@ namespace Config {
{"proc_cpu_graphs", true}, {"proc_cpu_graphs", true},
{"proc_info_smaps", false}, {"proc_info_smaps", false},
{"proc_left", false}, {"proc_left", false},
{"proc_filter_kernel", false}, {"proc_filter_kernel", false},
{"cpu_invert_lower", true}, {"cpu_invert_lower", true},
{"cpu_single_graph", false}, {"cpu_single_graph", false},
{"cpu_bottom", false}, {"cpu_bottom", false},
@ -383,7 +383,7 @@ namespace Config {
return false; return false;
} }
catch (const std::exception& e) { catch (const std::exception& e) {
validError = string{e.what()}; validError = string{e.what()};
return false; return false;
} }
@ -503,7 +503,7 @@ namespace Config {
boolsTmp.clear(); boolsTmp.clear();
} }
catch (const std::exception& e) { catch (const std::exception& e) {
Global::exit_error_msg = "Exception during Config::unlock() : " + string{e.what()}; Global::exit_error_msg = "Exception during Config::unlock() : " + string{e.what()};
clean_quit(1); clean_quit(1);
} }

View File

@ -4,7 +4,7 @@
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
@ -65,7 +65,7 @@ namespace Config {
bool _locked(const string& name); bool _locked(const string& name);
//* Return bool for config key <name> //* Return bool for config key <name>
inline bool getB(const string& name) { return bools.at(name); } inline bool getB(const string& name) { return bools.at(name); }
//* Return integer for config key <name> //* Return integer for config key <name>
inline const int& getI(const string& name) { return ints.at(name); } inline const int& getI(const string& name) { return ints.at(name); }
@ -81,7 +81,7 @@ namespace Config {
bool stringValid(const string& name, const string& value); bool stringValid(const string& name, const string& value);
//* Set config key <name> to bool <value> //* Set config key <name> to bool <value>
inline void set(const string& name, bool value) { inline void set(const string& name, bool value) {
if (_locked(name)) boolsTmp.insert_or_assign(name, value); if (_locked(name)) boolsTmp.insert_or_assign(name, value);
else bools.at(name) = value; else bools.at(name) = value;
} }

View File

@ -106,8 +106,8 @@ namespace Draw {
if (redraw) banner.clear(); if (redraw) banner.clear();
if (banner.empty()) { if (banner.empty()) {
string b_color, bg, fg, oc, letter; string b_color, bg, fg, oc, letter;
auto lowcolor = Config::getB("lowcolor"); auto lowcolor = Config::getB("lowcolor");
auto tty_mode = Config::getB("tty_mode"); auto tty_mode = Config::getB("tty_mode");
for (size_t z = 0; const auto& line : Global::Banner_src) { for (size_t z = 0; const auto& line : Global::Banner_src) {
if (const auto w = ulen(line[1]); w > width) width = w; if (const auto w = ulen(line[1]); w > width) width = w;
if (tty_mode) { if (tty_mode) {
@ -217,7 +217,7 @@ namespace Draw {
return first + Fx::bl + "" + Fx::ubl + uresize(text.substr(pos), limit - ulen(first)); return first + Fx::bl + "" + Fx::ubl + uresize(text.substr(pos), limit - ulen(first));
} }
catch (const std::exception& e) { catch (const std::exception& e) {
Logger::error("In TextEdit::operator() : " + string{e.what()}); Logger::error("In TextEdit::operator() : " + string{e.what()});
} }
} }
return text.substr(0, pos) + Fx::bl + "" + Fx::ubl + text.substr(pos); return text.substr(0, pos) + Fx::bl + "" + Fx::ubl + text.substr(pos);
@ -227,16 +227,16 @@ namespace Draw {
this->text.clear(); this->text.clear();
} }
string createBox(const int x, const int y, const int width, string createBox(const int x, const int y, const int width,
const int height, string line_color, bool fill, const int height, string line_color, bool fill,
const string title, const string title2, const int num) { const string title, const string title2, const int num) {
string out; string out;
if (line_color.empty()) if (line_color.empty())
line_color = Theme::c("div_line"); line_color = Theme::c("div_line");
auto tty_mode = Config::getB("tty_mode"); auto tty_mode = Config::getB("tty_mode");
auto rounded = Config::getB("rounded_corners"); auto rounded = Config::getB("rounded_corners");
const string numbering = (num == 0) ? "" : Theme::c("hi_fg") + (tty_mode ? std::to_string(num) : Symbols::superscript.at(clamp(num, 0, 9))); const string numbering = (num == 0) ? "" : Theme::c("hi_fg") + (tty_mode ? std::to_string(num) : Symbols::superscript.at(clamp(num, 0, 9)));
const auto& right_up = (tty_mode or not rounded ? Symbols::right_up : Symbols::round_right_up); const auto& right_up = (tty_mode or not rounded ? Symbols::right_up : Symbols::round_right_up);
const auto& left_up = (tty_mode or not rounded ? Symbols::left_up : Symbols::round_left_up); const auto& left_up = (tty_mode or not rounded ? Symbols::left_up : Symbols::round_left_up);
@ -246,12 +246,12 @@ namespace Draw {
out = Fx::reset + line_color; out = Fx::reset + line_color;
//? Draw horizontal lines //? Draw horizontal lines
for (const int& hpos : {y, y + height - 1}) { for (const int& hpos : {y, y + height - 1}) {
out += Mv::to(hpos, x) + Symbols::h_line * (width - 1); out += Mv::to(hpos, x) + Symbols::h_line * (width - 1);
} }
//? Draw vertical lines and fill if enabled //? Draw vertical lines and fill if enabled
for (const int& hpos : iota(y + 1, y + height - 1)) { for (const int& hpos : iota(y + 1, y + height - 1)) {
out += Mv::to(hpos, x) + Symbols::v_line out += Mv::to(hpos, x) + Symbols::v_line
+ ((fill) ? string(width - 2, ' ') : Mv::r(width - 2)) + ((fill) ? string(width - 2, ' ') : Mv::r(width - 2))
+ Symbols::v_line; + Symbols::v_line;
@ -289,8 +289,8 @@ namespace Draw {
{"/uptime", ""} {"/uptime", ""}
}; };
static time_t c_time{}; // defaults to 0 static time_t c_time{}; // defaults to 0
static size_t clock_len{}; // defaults to 0 static size_t clock_len{}; // defaults to 0
static string clock_str; static string clock_str;
if (auto n_time = time(NULL); not force and n_time == c_time) if (auto n_time = time(NULL); not force and n_time == c_time)
@ -303,7 +303,7 @@ namespace Draw {
} }
auto& out = Global::clock; auto& out = Global::clock;
auto cpu_bottom = Config::getB("cpu_bottom"); auto cpu_bottom = Config::getB("cpu_bottom");
const auto& x = Cpu::x; const auto& x = Cpu::x;
const auto y = (cpu_bottom ? Cpu::y + Cpu::height - 1 : Cpu::y); const auto y = (cpu_bottom ? Cpu::y + Cpu::height - 1 : Cpu::y);
const auto& width = Cpu::width; const auto& width = Cpu::width;
@ -343,8 +343,8 @@ namespace Draw {
//* Meter class ------------------------------------------------------------------------------------------------------------> //* Meter class ------------------------------------------------------------------------------------------------------------>
Meter::Meter() {} Meter::Meter() {}
Meter::Meter(const int width, const string& color_gradient, bool invert) Meter::Meter(const int width, const string& color_gradient, bool invert)
: width(width), color_gradient(color_gradient), invert(invert) {} : width(width), color_gradient(color_gradient), invert(invert) {}
string Meter::operator()(int value) { string Meter::operator()(int value) {
if (width < 1) return ""; if (width < 1) return "";
@ -366,7 +366,7 @@ namespace Draw {
//* Graph class ------------------------------------------------------------------------------------------------------------> //* Graph class ------------------------------------------------------------------------------------------------------------>
void Graph::_create(const deque<long long>& data, int data_offset) { void Graph::_create(const deque<long long>& data, int data_offset) {
bool mult = (data.size() - data_offset > 1); bool mult = (data.size() - data_offset > 1);
const auto& graph_symbol = Symbols::graph_symbols.at(symbol + '_' + (invert ? "down" : "up")); const auto& graph_symbol = Symbols::graph_symbols.at(symbol + '_' + (invert ? "down" : "up"));
array<int, 2> result; array<int, 2> result;
const float mod = (height == 1) ? 0.3 : 0.1; const float mod = (height == 1) ? 0.3 : 0.1;
@ -436,11 +436,11 @@ namespace Draw {
Graph::Graph() {} Graph::Graph() {}
Graph::Graph(int width, int height, const string& color_gradient, Graph::Graph(int width, int height, const string& color_gradient,
const deque<long long>& data, const string& symbol, const deque<long long>& data, const string& symbol,
bool invert, bool no_zero, long long max_value, long long offset) bool invert, bool no_zero, long long max_value, long long offset)
: width(width), height(height), color_gradient(color_gradient), : width(width), height(height), color_gradient(color_gradient),
invert(invert), no_zero(no_zero), offset(offset) { invert(invert), no_zero(no_zero), offset(offset) {
if (Config::getB("tty_mode") or symbol == "tty") this->symbol = "tty"; if (Config::getB("tty_mode") or symbol == "tty") this->symbol = "tty";
else if (symbol != "default") this->symbol = symbol; else if (symbol != "default") this->symbol = symbol;
else this->symbol = Config::getS("graph_symbol"); else this->symbol = Config::getS("graph_symbol");
@ -464,7 +464,7 @@ namespace Draw {
this->_create(data, data_offset); this->_create(data, data_offset);
} }
string& Graph::operator()(const deque<long long>& data, bool data_same) { string& Graph::operator()(const deque<long long>& data, bool data_same) {
if (data_same) return out; if (data_same) return out;
//? Make room for new characters on graph //? Make room for new characters on graph
@ -504,26 +504,26 @@ namespace Cpu {
vector<Draw::Graph> core_graphs; vector<Draw::Graph> core_graphs;
vector<Draw::Graph> temp_graphs; vector<Draw::Graph> temp_graphs;
string draw(const cpu_info& cpu, bool force_redraw, bool data_same) { string draw(const cpu_info& cpu, bool force_redraw, bool data_same) {
if (Runner::stopping) return ""; if (Runner::stopping) return "";
if (force_redraw) redraw = true; if (force_redraw) redraw = true;
bool show_temps = (Config::getB("check_temp") and got_sensors); bool show_temps = (Config::getB("check_temp") and got_sensors);
auto single_graph = Config::getB("cpu_single_graph"); auto single_graph = Config::getB("cpu_single_graph");
bool hide_cores = show_temps and (cpu_temp_only or not Config::getB("show_coretemp")); bool hide_cores = show_temps and (cpu_temp_only or not Config::getB("show_coretemp"));
const int extra_width = (hide_cores ? max(6, 6 * b_column_size) : 0); const int extra_width = (hide_cores ? max(6, 6 * b_column_size) : 0);
auto& graph_up_field = Config::getS("cpu_graph_upper"); auto& graph_up_field = Config::getS("cpu_graph_upper");
auto& graph_lo_field = Config::getS("cpu_graph_lower"); auto& graph_lo_field = Config::getS("cpu_graph_lower");
auto tty_mode = Config::getB("tty_mode"); auto tty_mode = Config::getB("tty_mode");
auto& graph_symbol = (tty_mode ? "tty" : Config::getS("graph_symbol_cpu")); auto& graph_symbol = (tty_mode ? "tty" : Config::getS("graph_symbol_cpu"));
auto& graph_bg = Symbols::graph_symbols.at((graph_symbol == "default" ? Config::getS("graph_symbol") + "_up" : graph_symbol + "_up")).at(6); auto& graph_bg = Symbols::graph_symbols.at((graph_symbol == "default" ? Config::getS("graph_symbol") + "_up" : graph_symbol + "_up")).at(6);
auto& temp_scale = Config::getS("temp_scale"); auto& temp_scale = Config::getS("temp_scale");
auto cpu_bottom = Config::getB("cpu_bottom"); auto cpu_bottom = Config::getB("cpu_bottom");
const string& title_left = Theme::c("cpu_box") + (cpu_bottom ? Symbols::title_left_down : Symbols::title_left); const string& title_left = Theme::c("cpu_box") + (cpu_bottom ? Symbols::title_left_down : Symbols::title_left);
const string& title_right = Theme::c("cpu_box") + (cpu_bottom ? Symbols::title_right_down : Symbols::title_right); const string& title_right = Theme::c("cpu_box") + (cpu_bottom ? Symbols::title_right_down : Symbols::title_right);
static int bat_pos = 0, bat_len = 0; static int bat_pos = 0, bat_len = 0;
if (cpu.cpu_percent.at("total").empty() if (cpu.cpu_percent.at("total").empty()
or cpu.core_percent.at(0).empty() or cpu.core_percent.at(0).empty()
or (show_temps and cpu.temp.at(0).empty())) return ""; or (show_temps and cpu.temp.at(0).empty())) return "";
string out; string out;
out.reserve(width * height); out.reserve(width * height);
@ -550,15 +550,15 @@ namespace Cpu {
//? Graphs & meters //? Graphs & meters
graph_upper = Draw::Graph{x + width - b_width - 3, graph_up_height, "cpu", cpu.cpu_percent.at(graph_up_field), graph_symbol, false, true}; graph_upper = Draw::Graph{x + width - b_width - 3, graph_up_height, "cpu", cpu.cpu_percent.at(graph_up_field), graph_symbol, false, true};
cpu_meter = Draw::Meter{b_width - (show_temps ? 23 - (b_column_size <= 1 and b_columns == 1 ? 6 : 0) : 11), "cpu"}; cpu_meter = Draw::Meter{b_width - (show_temps ? 23 - (b_column_size <= 1 and b_columns == 1 ? 6 : 0) : 11), "cpu"};
if (not single_graph) { if (not single_graph) {
graph_lower = Draw::Graph{ graph_lower = Draw::Graph{
x + width - b_width - 3, x + width - b_width - 3,
graph_low_height, "cpu", graph_low_height, "cpu",
cpu.cpu_percent.at(graph_lo_field), cpu.cpu_percent.at(graph_lo_field),
graph_symbol, graph_symbol,
Config::getB("cpu_invert_lower"), true Config::getB("cpu_invert_lower"), true
}; };
} }
if (mid_line) { if (mid_line) {
out += Mv::to(y + graph_up_height + 1, x) + Fx::ub + Theme::c("cpu_box") + Symbols::div_left + Theme::c("div_line") out += Mv::to(y + graph_up_height + 1, x) + Fx::ub + Theme::c("cpu_box") + Symbols::div_left + Theme::c("div_line")
@ -587,8 +587,8 @@ namespace Cpu {
//? Draw battery if enabled and present //? Draw battery if enabled and present
if (Config::getB("show_battery") and has_battery) { if (Config::getB("show_battery") and has_battery) {
static int old_percent{}; // defaults to = 0 static int old_percent{}; // defaults to = 0
static long old_seconds{}; // defaults to = 0 static long old_seconds{}; // defaults to = 0
static string old_status; static string old_status;
static Draw::Meter bat_meter {10, "cpu", true}; static Draw::Meter bat_meter {10, "cpu", true};
static const unordered_flat_map<string, string> bat_symbols = { static const unordered_flat_map<string, string> bat_symbols = {
@ -659,7 +659,7 @@ namespace Cpu {
} }
out += Theme::c("div_line") + Symbols::v_line; out += Theme::c("div_line") + Symbols::v_line;
} catch (const std::exception& e) { throw std::runtime_error("graphs, clock, meter : " + string{e.what()}); } } catch (const std::exception& e) { throw std::runtime_error("graphs, clock, meter : " + string{e.what()}); }
//? Core text and graphs //? Core text and graphs
int cx = 0, cy = 1, cc = 0, core_width = (b_column_size == 0 ? 2 : 3); int cx = 0, cy = 1, cc = 0, core_width = (b_column_size == 0 ? 2 : 3);
@ -741,17 +741,17 @@ namespace Mem {
unordered_flat_map<string, Draw::Meter> disk_meters_free; unordered_flat_map<string, Draw::Meter> disk_meters_free;
unordered_flat_map<string, Draw::Graph> io_graphs; unordered_flat_map<string, Draw::Graph> io_graphs;
string draw(const mem_info& mem, bool force_redraw, bool data_same) { string draw(const mem_info& mem, bool force_redraw, bool data_same) {
if (Runner::stopping) return ""; if (Runner::stopping) return "";
if (force_redraw) redraw = true; if (force_redraw) redraw = true;
auto show_swap = Config::getB("show_swap"); auto show_swap = Config::getB("show_swap");
auto swap_disk = Config::getB("swap_disk"); auto swap_disk = Config::getB("swap_disk");
auto show_disks = Config::getB("show_disks"); auto show_disks = Config::getB("show_disks");
auto show_io_stat = Config::getB("show_io_stat"); auto show_io_stat = Config::getB("show_io_stat");
auto io_mode = Config::getB("io_mode"); auto io_mode = Config::getB("io_mode");
auto io_graph_combined = Config::getB("io_graph_combined"); auto io_graph_combined = Config::getB("io_graph_combined");
auto use_graphs = Config::getB("mem_graphs"); auto use_graphs = Config::getB("mem_graphs");
auto tty_mode = Config::getB("tty_mode"); auto tty_mode = Config::getB("tty_mode");
auto& graph_symbol = (tty_mode ? "tty" : Config::getS("graph_symbol_mem")); auto& graph_symbol = (tty_mode ? "tty" : Config::getS("graph_symbol_mem"));
auto& graph_bg = Symbols::graph_symbols.at((graph_symbol == "default" ? Config::getS("graph_symbol") + "_up" : graph_symbol + "_up")).at(6); auto& graph_bg = Symbols::graph_symbols.at((graph_symbol == "default" ? Config::getS("graph_symbol") + "_up" : graph_symbol + "_up")).at(6);
auto totalMem = Mem::get_totalMem(); auto totalMem = Mem::get_totalMem();
@ -817,20 +817,20 @@ namespace Mem {
if (io_graph_combined) { if (io_graph_combined) {
deque<long long> combined(disk.io_read.size(), 0); deque<long long> combined(disk.io_read.size(), 0);
rng::transform(disk.io_read, disk.io_write, combined.begin(), std::plus<long long>()); rng::transform(disk.io_read, disk.io_write, combined.begin(), std::plus<long long>());
io_graphs[name] = Draw::Graph{ io_graphs[name] = Draw::Graph{
disks_width - (io_mode ? 0 : 6), disks_width - (io_mode ? 0 : 6),
disks_io_h, "available", combined, disks_io_h, "available", combined,
graph_symbol, false, true, speed}; graph_symbol, false, true, speed};
} }
else { else {
io_graphs[name + "_read"] = Draw::Graph{ io_graphs[name + "_read"] = Draw::Graph{
disks_width, half_height, "free", disks_width, half_height, "free",
disk.io_read, graph_symbol, false, disk.io_read, graph_symbol, false,
true, speed}; true, speed};
io_graphs[name + "_write"] = Draw::Graph{ io_graphs[name + "_write"] = Draw::Graph{
disks_width, disks_io_h - half_height, disks_width, disks_io_h - half_height,
"used", disk.io_write, graph_symbol, "used", disk.io_write, graph_symbol,
true, true, speed}; true, true, speed};
} }
} }
} }
@ -900,7 +900,7 @@ namespace Mem {
if (show_disks) { if (show_disks) {
const auto& disks = mem.disks; const auto& disks = mem.disks;
cx = mem_width; cy = 0; cx = mem_width; cy = 0;
bool big_disk = disks_width >= 25; bool big_disk = disks_width >= 25;
divider = Mv::l(1) + Theme::c("div_line") + Symbols::div_left + Symbols::h_line * disks_width + Theme::c("mem_box") + Fx::ub + Symbols::div_right + Mv::l(disks_width); divider = Mv::l(1) + Theme::c("div_line") + Symbols::div_left + Symbols::h_line * disks_width + Theme::c("mem_box") + Fx::ub + Symbols::div_right + Mv::l(disks_width);
const string hu_div = Theme::c("div_line") + Symbols::h_line + Theme::c("main_fg"); const string hu_div = Theme::c("div_line") + Symbols::h_line + Theme::c("main_fg");
if (io_mode) { if (io_mode) {
@ -995,12 +995,12 @@ namespace Net {
unordered_flat_map<string, Draw::Graph> graphs; unordered_flat_map<string, Draw::Graph> graphs;
string box; string box;
string draw(const net_info& net, bool force_redraw, bool data_same) { string draw(const net_info& net, bool force_redraw, bool data_same) {
if (Runner::stopping) return ""; if (Runner::stopping) return "";
if (force_redraw) redraw = true; if (force_redraw) redraw = true;
auto net_sync = Config::getB("net_sync"); auto net_sync = Config::getB("net_sync");
auto net_auto = Config::getB("net_auto"); auto net_auto = Config::getB("net_auto");
auto tty_mode = Config::getB("tty_mode"); auto tty_mode = Config::getB("tty_mode");
auto& graph_symbol = (tty_mode ? "tty" : Config::getS("graph_symbol_net")); auto& graph_symbol = (tty_mode ? "tty" : Config::getS("graph_symbol_net"));
string ip_addr = (net.ipv4.empty() ? net.ipv6 : net.ipv4); string ip_addr = (net.ipv4.empty() ? net.ipv6 : net.ipv4);
if (old_ip != ip_addr) { if (old_ip != ip_addr) {
@ -1022,13 +1022,13 @@ namespace Net {
graphs.clear(); graphs.clear();
if (net.bandwidth.at("download").empty() or net.bandwidth.at("upload").empty()) if (net.bandwidth.at("download").empty() or net.bandwidth.at("upload").empty())
return out + Fx::reset; return out + Fx::reset;
graphs["download"] = Draw::Graph{ graphs["download"] = Draw::Graph{
width - b_width - 2, u_graph_height, "download", width - b_width - 2, u_graph_height, "download",
net.bandwidth.at("download"), graph_symbol, net.bandwidth.at("download"), graph_symbol,
false, true, down_max}; false, true, down_max};
graphs["upload"] = Draw::Graph{ graphs["upload"] = Draw::Graph{
width - b_width - 2, d_graph_height, "upload", width - b_width - 2, d_graph_height, "upload",
net.bandwidth.at("upload"), graph_symbol, true, true, up_max}; net.bandwidth.at("upload"), graph_symbol, true, true, up_max};
//? Interface selector and buttons //? Interface selector and buttons
@ -1109,7 +1109,7 @@ namespace Proc {
auto selected = Config::getI("proc_selected"); auto selected = Config::getI("proc_selected");
auto last_selected = Config::getI("proc_last_selected"); auto last_selected = Config::getI("proc_last_selected");
const int select_max = (Config::getB("show_detailed") ? Proc::select_max - 8 : Proc::select_max); const int select_max = (Config::getB("show_detailed") ? Proc::select_max - 8 : Proc::select_max);
auto vim_keys = Config::getB("vim_keys"); auto vim_keys = Config::getB("vim_keys");
int numpids = Proc::numpids; int numpids = Proc::numpids;
if ((cmd_key == "up" or (vim_keys and cmd_key == "k")) and selected > 0) { if ((cmd_key == "up" or (vim_keys and cmd_key == "k")) and selected > 0) {
@ -1164,18 +1164,18 @@ namespace Proc {
return (not changed ? -1 : selected); return (not changed ? -1 : selected);
} }
string draw(const vector<proc_info>& plist, bool force_redraw, bool data_same) { string draw(const vector<proc_info>& plist, bool force_redraw, bool data_same) {
if (Runner::stopping) return ""; if (Runner::stopping) return "";
auto proc_tree = Config::getB("proc_tree"); auto proc_tree = Config::getB("proc_tree");
bool show_detailed = (Config::getB("show_detailed") and cmp_equal(Proc::detailed.last_pid, Config::getI("detailed_pid"))); bool show_detailed = (Config::getB("show_detailed") and cmp_equal(Proc::detailed.last_pid, Config::getI("detailed_pid")));
bool proc_gradient = (Config::getB("proc_gradient") and not Config::getB("lowcolor") and Theme::gradients.contains("proc")); bool proc_gradient = (Config::getB("proc_gradient") and not Config::getB("lowcolor") and Theme::gradients.contains("proc"));
auto proc_colors = Config::getB("proc_colors"); auto proc_colors = Config::getB("proc_colors");
auto tty_mode = Config::getB("tty_mode"); auto tty_mode = Config::getB("tty_mode");
auto& graph_symbol = (tty_mode ? "tty" : Config::getS("graph_symbol_proc")); auto& graph_symbol = (tty_mode ? "tty" : Config::getS("graph_symbol_proc"));
auto& graph_bg = Symbols::graph_symbols.at((graph_symbol == "default" ? Config::getS("graph_symbol") + "_up" : graph_symbol + "_up")).at(6); auto& graph_bg = Symbols::graph_symbols.at((graph_symbol == "default" ? Config::getS("graph_symbol") + "_up" : graph_symbol + "_up")).at(6);
auto mem_bytes = Config::getB("proc_mem_bytes"); auto mem_bytes = Config::getB("proc_mem_bytes");
auto vim_keys = Config::getB("vim_keys"); auto vim_keys = Config::getB("vim_keys");
auto show_graphs = Config::getB("proc_cpu_graphs"); auto show_graphs = Config::getB("proc_cpu_graphs");
start = Config::getI("proc_start"); start = Config::getI("proc_start");
selected = Config::getI("proc_selected"); selected = Config::getI("proc_selected");
const int y = show_detailed ? Proc::y + 8 : Proc::y; const int y = show_detailed ? Proc::y + 8 : Proc::y;
@ -1210,7 +1210,7 @@ namespace Proc {
//? Detailed box //? Detailed box
if (show_detailed) { if (show_detailed) {
bool alive = detailed.status != "Dead"; bool alive = detailed.status != "Dead";
dgraph_x = x; dgraph_x = x;
dgraph_width = max(width / 3, width - 121); dgraph_width = max(width / 3, width - 121);
d_width = width - dgraph_width - 1; d_width = width - dgraph_width - 1;
@ -1282,7 +1282,7 @@ namespace Proc {
} }
//? Filter //? Filter
auto filtering = Config::getB("proc_filtering"); // ? filter(20) : Config::getS("proc_filter")) auto filtering = Config::getB("proc_filtering"); // ? filter(20) : Config::getS("proc_filter"))
const auto filter_text = (filtering) ? filter(max(6, width - 58)) : uresize(Config::getS("proc_filter"), max(6, width - 58)); const auto filter_text = (filtering) ? filter(max(6, width - 58)) : uresize(Config::getS("proc_filter"), max(6, width - 58));
out += Mv::to(y, x+9) + title_left + (not filter_text.empty() ? Fx::b : "") + Theme::c("hi_fg") + 'f' out += Mv::to(y, x+9) + title_left + (not filter_text.empty() ? Fx::b : "") + Theme::c("hi_fg") + 'f'
+ Theme::c("title") + (not filter_text.empty() ? ' ' + filter_text : "ilter") + Theme::c("title") + (not filter_text.empty() ? ' ' + filter_text : "ilter")
@ -1363,7 +1363,7 @@ namespace Proc {
//? Draw details box if shown //? Draw details box if shown
if (show_detailed) { if (show_detailed) {
bool alive = detailed.status != "Dead"; bool alive = detailed.status != "Dead";
const int item_fit = floor((double)(d_width - 2) / 10); const int item_fit = floor((double)(d_width - 2) / 10);
const int item_width = floor((double)(d_width - 2) / min(item_fit, 8)); const int item_width = floor((double)(d_width - 2) / min(item_fit, 8));
@ -1422,7 +1422,7 @@ namespace Proc {
} }
//? Update graphs for processes with above 0.0% cpu usage, delete if below 0.1% 10x times //? Update graphs for processes with above 0.0% cpu usage, delete if below 0.1% 10x times
bool has_graph = show_graphs ? p_counters.contains(p.pid) : false; bool has_graph = show_graphs ? p_counters.contains(p.pid) : false;
if (show_graphs and ((p.cpu_p > 0 and not has_graph) or (not data_same and has_graph))) { if (show_graphs and ((p.cpu_p > 0 and not has_graph) or (not data_same and has_graph))) {
if (not has_graph) { if (not has_graph) {
p_graphs[p.pid] = Draw::Graph{5, 1, "", {}, graph_symbol}; p_graphs[p.pid] = Draw::Graph{5, 1, "", {}, graph_symbol};
@ -1579,10 +1579,10 @@ namespace Draw {
void calcSizes() { void calcSizes() {
atomic_wait(Runner::active); atomic_wait(Runner::active);
Config::unlock(); Config::unlock();
auto boxes = Config::getS("shown_boxes"); auto boxes = Config::getS("shown_boxes");
auto cpu_bottom = Config::getB("cpu_bottom"); auto cpu_bottom = Config::getB("cpu_bottom");
auto mem_below_net = Config::getB("mem_below_net"); auto mem_below_net = Config::getB("mem_below_net");
auto proc_left = Config::getB("proc_left"); auto proc_left = Config::getB("proc_left");
Cpu::box.clear(); Cpu::box.clear();
Mem::box.clear(); Mem::box.clear();
@ -1612,7 +1612,7 @@ namespace Draw {
//* Calculate and draw cpu box outlines //* Calculate and draw cpu box outlines
if (Cpu::shown) { if (Cpu::shown) {
using namespace Cpu; using namespace Cpu;
bool show_temp = (Config::getB("check_temp") and got_sensors); bool show_temp = (Config::getB("check_temp") and got_sensors);
width = round((double)Term::width * width_p / 100); width = round((double)Term::width * width_p / 100);
height = max(8, (int)ceil((double)Term::height * (trim(boxes) == "cpu" ? 100 : height_p) / 100)); height = max(8, (int)ceil((double)Term::height * (trim(boxes) == "cpu" ? 100 : height_p) / 100));
x = 1; x = 1;
@ -1651,9 +1651,9 @@ namespace Draw {
//* Calculate and draw mem box outlines //* Calculate and draw mem box outlines
if (Mem::shown) { if (Mem::shown) {
using namespace Mem; using namespace Mem;
auto show_disks = Config::getB("show_disks"); auto show_disks = Config::getB("show_disks");
auto swap_disk = Config::getB("swap_disk"); auto swap_disk = Config::getB("swap_disk");
auto mem_graphs = Config::getB("mem_graphs"); auto mem_graphs = Config::getB("mem_graphs");
width = round((double)Term::width * (Proc::shown ? width_p : 100) / 100); width = round((double)Term::width * (Proc::shown ? width_p : 100) / 100);
height = ceil((double)Term::height * (100 - Cpu::height_p * Cpu::shown - Net::height_p * Net::shown) / 100) + 1; height = ceil((double)Term::height * (100 - Cpu::height_p * Cpu::shown - Net::height_p * Net::shown) / 100) + 1;

View File

@ -66,8 +66,8 @@ namespace Draw {
//* An editable text field //* An editable text field
class TextEdit { class TextEdit {
size_t pos{}; // defaults to 0 size_t pos{}; // defaults to 0
size_t upos{}; // defaults to 0 size_t upos{}; // defaults to 0
bool numeric; bool numeric;
public: public:
string text; string text;
@ -79,11 +79,11 @@ namespace Draw {
}; };
//* Create a box and return as a string //* Create a box and return as a string
string createBox(const int x, const int y, const int width, string createBox(const int x, const int y, const int width,
const int height, string line_color = "", bool fill = false, const int height, string line_color = "", bool fill = false,
const string title = "", const string title2 = "", const int num = 0); const string title = "", const string title2 = "", const int num = 0);
bool update_clock(bool force = false); bool update_clock(bool force = false);
//* Class holding a percentage meter //* Class holding a percentage meter
class Meter { class Meter {
@ -93,7 +93,7 @@ namespace Draw {
array<string, 101> cache; array<string, 101> cache;
public: public:
Meter(); Meter();
Meter(const int width, const string& color_gradient, bool invert = false); Meter(const int width, const string& color_gradient, bool invert = false);
//* Return a string representation of the meter with given value //* Return a string representation of the meter with given value
string operator()(int value); string operator()(int value);
@ -115,15 +115,15 @@ namespace Draw {
public: public:
Graph(); Graph();
Graph(int width, int height, Graph(int width, int height,
const string& color_gradient, const string& color_gradient,
const deque<long long>& data, const deque<long long>& data,
const string& symbol="default", const string& symbol="default",
bool invert=false, bool no_zero=false, bool invert=false, bool no_zero=false,
long long max_value=0, long long offset=0); long long max_value=0, long long offset=0);
//* Add last value from back of <data> and return string representation of graph //* Add last value from back of <data> and return string representation of graph
string& operator()(const deque<long long>& data, bool data_same=false); string& operator()(const deque<long long>& data, bool data_same=false);
//* Return string representation of graph //* Return string representation of graph
string& operator()(); string& operator()();

View File

@ -4,7 +4,7 @@
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
@ -238,8 +238,8 @@ namespace Input {
void process(const string& key) { void process(const string& key) {
if (key.empty()) return; if (key.empty()) return;
try { try {
auto filtering = Config::getB("proc_filtering"); auto filtering = Config::getB("proc_filtering");
auto vim_keys = Config::getB("vim_keys"); auto vim_keys = Config::getB("vim_keys");
auto help_key = (vim_keys ? "H" : "h"); auto help_key = (vim_keys ? "H" : "h");
auto kill_key = (vim_keys ? "K" : "k"); auto kill_key = (vim_keys ? "K" : "k");
//? Global input actions //? Global input actions
@ -297,12 +297,12 @@ namespace Input {
if (key == "enter" or key == "down") { if (key == "enter" or key == "down") {
Config::set("proc_filter", Proc::filter.text); Config::set("proc_filter", Proc::filter.text);
Config::set("proc_filtering", false); Config::set("proc_filtering", false);
old_filter.clear(); old_filter.clear();
if(key == "down"){ if(key == "down"){
process("down"); process("down");
return; return;
} }
} }
else if (key == "escape" or key == "mouse_click") { else if (key == "escape" or key == "mouse_click") {
Config::set("proc_filter", old_filter); Config::set("proc_filter", old_filter);
Config::set("proc_filtering", false); Config::set("proc_filtering", false);
@ -549,7 +549,7 @@ namespace Input {
} }
catch (const std::exception& e) { catch (const std::exception& e) {
throw std::runtime_error("Input::process(\"" + key + "\") : " + string{e.what()}); throw std::runtime_error("Input::process(\"" + key + "\") : " + string{e.what()});
} }
} }

View File

@ -4,7 +4,7 @@
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,

View File

@ -617,19 +617,19 @@ namespace Menu {
"Show cpu graph for each process.", "Show cpu graph for each process.",
"", "",
"True or False"}, "True or False"},
{"proc_filter_kernel", {"proc_filter_kernel",
"(Linux) Filter kernel processes from output.", "(Linux) Filter kernel processes from output.",
"", "",
"Set to 'True' to filter out internal", "Set to 'True' to filter out internal",
"processes started by the Linux kernel."}, "processes started by the Linux kernel."},
} }
}; };
msgBox::msgBox() {} msgBox::msgBox() {}
msgBox::msgBox(int width, int boxtype, vector<string> content, string title) msgBox::msgBox(int width, int boxtype, vector<string> content, string title)
: width(width), boxtype(boxtype) { : width(width), boxtype(boxtype) {
auto tty_mode = Config::getB("tty_mode"); auto tty_mode = Config::getB("tty_mode");
auto rounded = Config::getB("rounded_corners"); auto rounded = Config::getB("rounded_corners");
const auto& right_up = (tty_mode or not rounded ? Symbols::right_up : Symbols::round_right_up); const auto& right_up = (tty_mode or not rounded ? Symbols::right_up : Symbols::round_right_up);
const auto& left_up = (tty_mode or not rounded ? Symbols::left_up : Symbols::round_left_up); const auto& left_up = (tty_mode or not rounded ? Symbols::left_up : Symbols::round_left_up);
const auto& right_down = (tty_mode or not rounded ? Symbols::right_down : Symbols::round_right_down); const auto& right_down = (tty_mode or not rounded ? Symbols::right_down : Symbols::round_right_down);
@ -718,10 +718,10 @@ namespace Menu {
}; };
int signalChoose(const string& key) { int signalChoose(const string& key) {
auto s_pid = (Config::getB("show_detailed") and Config::getI("selected_pid") == 0 ? Config::getI("detailed_pid") : Config::getI("selected_pid")); auto s_pid = (Config::getB("show_detailed") and Config::getI("selected_pid") == 0 ? Config::getI("detailed_pid") : Config::getI("selected_pid"));
static int x{}; // defaults to 0 static int x{}; // defaults to 0
static int y{}; // defaults to 0 static int y{}; // defaults to 0
static int selected_signal = -1; static int selected_signal = -1;
if (bg.empty()) selected_signal = -1; if (bg.empty()) selected_signal = -1;
auto& out = Global::overlay; auto& out = Global::overlay;
@ -848,7 +848,7 @@ namespace Menu {
} }
int signalSend(const string& key) { int signalSend(const string& key) {
auto s_pid = (Config::getB("show_detailed") and Config::getI("selected_pid") == 0 ? Config::getI("detailed_pid") : Config::getI("selected_pid")); auto s_pid = (Config::getB("show_detailed") and Config::getI("selected_pid") == 0 ? Config::getI("detailed_pid") : Config::getI("selected_pid"));
if (s_pid == 0) return Closed; if (s_pid == 0) return Closed;
if (redraw) { if (redraw) {
atomic_wait(Runner::active); atomic_wait(Runner::active);
@ -921,11 +921,11 @@ namespace Menu {
int mainMenu(const string& key) { int mainMenu(const string& key) {
enum MenuItems { Options, Help, Quit }; enum MenuItems { Options, Help, Quit };
static int y{}; // defaults to 0 static int y{}; // defaults to 0
static int selected{}; // defaults to 0 static int selected{}; // defaults to 0
static vector<string> colors_selected; static vector<string> colors_selected;
static vector<string> colors_normal; static vector<string> colors_normal;
auto tty_mode = Config::getB("tty_mode"); auto tty_mode = Config::getB("tty_mode");
if (bg.empty()) selected = 0; if (bg.empty()) selected = 0;
int retval = Changed; int retval = Changed;
@ -1000,18 +1000,18 @@ namespace Menu {
int optionsMenu(const string& key) { int optionsMenu(const string& key) {
enum Predispositions { isBool, isInt, isString, is2D, isBrowseable, isEditable}; enum Predispositions { isBool, isInt, isString, is2D, isBrowseable, isEditable};
static int y{}; // defaults to 0 static int y{}; // defaults to 0
static int x{}; // defaults to 0 static int x{}; // defaults to 0
static int height{}; // defaults to 0 static int height{}; // defaults to 0
static int page{}; // defaults to 0 static int page{}; // defaults to 0
static int pages{}; // defaults to 0 static int pages{}; // defaults to 0
static int selected{}; // defaults to 0 static int selected{}; // defaults to 0
static int select_max{}; // defaults to 0 static int select_max{}; // defaults to 0
static int item_height{}; // defaults to 0 static int item_height{}; // defaults to 0
static int selected_cat{}; // defaults to 0 static int selected_cat{}; // defaults to 0
static int max_items{}; // defaults to 0 static int max_items{}; // defaults to 0
static int last_sel{}; // defaults to 0 static int last_sel{}; // defaults to 0
static bool editing{}; // defaults to false static bool editing{}; // defaults to false
static Draw::TextEdit editor; static Draw::TextEdit editor;
static string warnings; static string warnings;
static bitset<8> selPred; static bitset<8> selPred;
@ -1030,8 +1030,8 @@ namespace Menu {
{"cpu_sensor", std::cref(Cpu::available_sensors)}, {"cpu_sensor", std::cref(Cpu::available_sensors)},
{"selected_battery", std::cref(Config::available_batteries)}, {"selected_battery", std::cref(Config::available_batteries)},
}; };
auto tty_mode = Config::getB("tty_mode"); auto tty_mode = Config::getB("tty_mode");
auto vim_keys = Config::getB("vim_keys"); auto vim_keys = Config::getB("vim_keys");
if (max_items == 0) { if (max_items == 0) {
for (const auto& cat : categories) { for (const auto& cat : categories) {
if ((int)cat.size() > max_items) max_items = cat.size(); if ((int)cat.size() > max_items) max_items = cat.size();
@ -1043,9 +1043,9 @@ namespace Menu {
Theme::updateThemes(); Theme::updateThemes();
} }
int retval = Changed; int retval = Changed;
bool recollect{}; // defaults to false bool recollect{}; // defaults to false
bool screen_redraw{}; // defaults to false bool screen_redraw{}; // defaults to false
bool theme_refresh{}; // defaults to false bool theme_refresh{}; // defaults to false
//? Draw background if needed else process input //? Draw background if needed else process input
if (redraw) { if (redraw) {
@ -1338,11 +1338,11 @@ namespace Menu {
} }
int helpMenu(const string& key) { int helpMenu(const string& key) {
static int y{}; // defaults to 0 static int y{}; // defaults to 0
static int x{}; // defaults to 0 static int x{}; // defaults to 0
static int height{}; // defaults to 0 static int height{}; // defaults to 0
static int page{}; // defaults to 0 static int page{}; // defaults to 0
static int pages{}; // defaults to 0 static int pages{}; // defaults to 0
if (bg.empty()) page = 0; if (bg.empty()) page = 0;
int retval = Changed; int retval = Changed;

View File

@ -46,12 +46,12 @@ namespace Menu {
//? Strings in content vector is not checked for box width overflow //? Strings in content vector is not checked for box width overflow
class msgBox { class msgBox {
string box_contents, button_left, button_right; string box_contents, button_left, button_right;
int height{}; // defaults to 0 int height{}; // defaults to 0
int width{}; // defaults to 0 int width{}; // defaults to 0
int boxtype{}; // defaults to 0 int boxtype{}; // defaults to 0
int selected{}; // defaults to 0 int selected{}; // defaults to 0
int x{}; // defaults to 0 int x{}; // defaults to 0
int y{}; // defaults to 0 int y{}; // defaults to 0
public: public:
enum BoxTypes { OK, YES_NO, NO_YES }; enum BoxTypes { OK, YES_NO, NO_YES };
enum msgReturn { enum msgReturn {

View File

@ -26,7 +26,7 @@ using namespace Tools;
namespace Proc { namespace Proc {
void proc_sorter(vector<proc_info>& proc_vec, const string& sorting, bool reverse, bool tree) { void proc_sorter(vector<proc_info>& proc_vec, const string& sorting, bool reverse, bool tree) {
if (reverse) { if (reverse) {
switch (v_index(sort_vector, sorting)) { switch (v_index(sort_vector, sorting)) {
case 0: rng::stable_sort(proc_vec, rng::less{}, &proc_info::pid); break; case 0: rng::stable_sort(proc_vec, rng::less{}, &proc_info::pid); break;
@ -70,7 +70,7 @@ namespace Proc {
} }
} }
void tree_sort(vector<tree_proc>& proc_vec, const string& sorting, bool reverse, int& c_index, const int index_max, bool collapsed) { void tree_sort(vector<tree_proc>& proc_vec, const string& sorting, bool reverse, int& c_index, const int index_max, bool collapsed) {
if (proc_vec.size() > 1) { if (proc_vec.size() > 1) {
if (reverse) { if (reverse) {
switch (v_index(sort_vector, sorting)) { switch (v_index(sort_vector, sorting)) {
@ -98,8 +98,8 @@ namespace Proc {
} }
} }
void _tree_gen(proc_info& cur_proc, vector<proc_info>& in_procs, vector<tree_proc>& out_procs, void _tree_gen(proc_info& cur_proc, vector<proc_info>& in_procs, vector<tree_proc>& out_procs,
int cur_depth, bool collapsed, const string& filter, bool found, bool no_update, bool should_filter) { int cur_depth, bool collapsed, const string& filter, bool found, bool no_update, bool should_filter) {
auto cur_pos = out_procs.size(); auto cur_pos = out_procs.size();
bool filtering = false; bool filtering = false;
@ -132,7 +132,7 @@ namespace Proc {
std::string_view cmd_view = cur_proc.cmd; std::string_view cmd_view = cur_proc.cmd;
cmd_view = cmd_view.substr((size_t)0, std::min(cmd_view.find(' '), cmd_view.size())); cmd_view = cmd_view.substr((size_t)0, std::min(cmd_view.find(' '), cmd_view.size()));
cmd_view = cmd_view.substr(std::min(cmd_view.find_last_of('/') + 1, cmd_view.size())); cmd_view = cmd_view.substr(std::min(cmd_view.find_last_of('/') + 1, cmd_view.size()));
cur_proc.short_cmd = string{cmd_view}; cur_proc.short_cmd = string{cmd_view};
} }
} }
else { else {

View File

@ -68,7 +68,7 @@ namespace Runner {
extern bool pause_output; extern bool pause_output;
extern string debug_bg; extern string debug_bg;
void run(const string& box="", bool no_update = false, bool force_redraw = false); void run(const string& box="", bool no_update = false, bool force_redraw = false);
void stop(); void stop();
} }
@ -116,10 +116,10 @@ namespace Cpu {
}; };
//* Collect cpu stats and temperatures //* Collect cpu stats and temperatures
auto collect(bool no_update = false) -> cpu_info&; auto collect(bool no_update = false) -> cpu_info&;
//* Draw contents of cpu box using <cpu> as source //* Draw contents of cpu box using <cpu> as source
string draw(const cpu_info& cpu, bool force_redraw = false, bool data_same = false); string draw(const cpu_info& cpu, bool force_redraw = false, bool data_same = false);
//* Parse /proc/cpu info for mapping of core ids //* Parse /proc/cpu info for mapping of core ids
auto get_core_mapping() -> unordered_flat_map<int, int>; auto get_core_mapping() -> unordered_flat_map<int, int>;
@ -133,20 +133,20 @@ namespace Mem {
extern string box; extern string box;
extern int x, y, width, height, min_width, min_height; extern int x, y, width, height, min_width, min_height;
extern bool has_swap, shown, redraw; extern bool has_swap, shown, redraw;
const array mem_names { "used"s, "available"s, "cached"s, "free"s }; const array mem_names { "used"s, "available"s, "cached"s, "free"s };
const array swap_names { "swap_used"s, "swap_free"s }; const array swap_names { "swap_used"s, "swap_free"s };
extern int disk_ios; extern int disk_ios;
struct disk_info { struct disk_info {
std::filesystem::path dev; std::filesystem::path dev;
string name; string name;
string fstype{}; // defaults to "" string fstype{}; // defaults to ""
std::filesystem::path stat{}; // defaults to "" std::filesystem::path stat{}; // defaults to ""
int64_t total{}; // defaults to 0 int64_t total{}; // defaults to 0
int64_t used{}; // defaults to 0 int64_t used{}; // defaults to 0
int64_t free{}; // defaults to 0 int64_t free{}; // defaults to 0
int used_percent{}; // defaults to 0 int used_percent{}; // defaults to 0
int free_percent{}; // defaults to 0 int free_percent{}; // defaults to 0
array<int64_t, 3> old_io = {0, 0, 0}; array<int64_t, 3> old_io = {0, 0, 0};
deque<long long> io_read = {}; deque<long long> io_read = {};
@ -169,10 +169,10 @@ namespace Mem {
uint64_t get_totalMem(); uint64_t get_totalMem();
//* Collect mem & disks stats //* Collect mem & disks stats
auto collect(bool no_update = false) -> mem_info&; auto collect(bool no_update = false) -> mem_info&;
//* Draw contents of mem box using <mem> as source //* Draw contents of mem box using <mem> as source
string draw(const mem_info& mem, bool force_redraw = false, bool data_same = false); string draw(const mem_info& mem, bool force_redraw = false, bool data_same = false);
} }
@ -186,29 +186,29 @@ namespace Net {
extern unordered_flat_map<string, uint64_t> graph_max; extern unordered_flat_map<string, uint64_t> graph_max;
struct net_stat { struct net_stat {
uint64_t speed{}; // defaults to 0 uint64_t speed{}; // defaults to 0
uint64_t top{}; // defaults to 0 uint64_t top{}; // defaults to 0
uint64_t total{}; // defaults to 0 uint64_t total{}; // defaults to 0
uint64_t last{}; // defaults to 0 uint64_t last{}; // defaults to 0
uint64_t offset{}; // defaults to 0 uint64_t offset{}; // defaults to 0
uint64_t rollover{}; // defaults to 0 uint64_t rollover{}; // defaults to 0
}; };
struct net_info { struct net_info {
unordered_flat_map<string, deque<long long>> bandwidth = { {"download", {}}, {"upload", {}} }; unordered_flat_map<string, deque<long long>> bandwidth = { {"download", {}}, {"upload", {}} };
unordered_flat_map<string, net_stat> stat = { {"download", {}}, {"upload", {}} }; unordered_flat_map<string, net_stat> stat = { {"download", {}}, {"upload", {}} };
string ipv4{}; // defaults to "" string ipv4{}; // defaults to ""
string ipv6{}; // defaults to "" string ipv6{}; // defaults to ""
bool connected{}; // defaults to false bool connected{}; // defaults to false
}; };
extern unordered_flat_map<string, net_info> current_net; extern unordered_flat_map<string, net_info> current_net;
//* Collect net upload/download stats //* Collect net upload/download stats
auto collect(bool no_update=false) -> net_info&; auto collect(bool no_update=false) -> net_info&;
//* Draw contents of net box using <net> as source //* Draw contents of net box using <net> as source
string draw(const net_info& net, bool force_redraw = false, bool data_same = false); string draw(const net_info& net, bool force_redraw = false, bool data_same = false);
} }
namespace Proc { namespace Proc {
@ -251,32 +251,32 @@ namespace Proc {
//* Container for process information //* Container for process information
struct proc_info { struct proc_info {
size_t pid{}; // defaults to 0 size_t pid{}; // defaults to 0
string name{}; // defaults to "" string name{}; // defaults to ""
string cmd{}; // defaults to "" string cmd{}; // defaults to ""
string short_cmd{}; // defaults to "" string short_cmd{}; // defaults to ""
size_t threads{}; // defaults to 0 size_t threads{}; // defaults to 0
int name_offset{}; // defaults to 0 int name_offset{}; // defaults to 0
string user{}; // defaults to "" string user{}; // defaults to ""
uint64_t mem{}; // defaults to 0 uint64_t mem{}; // defaults to 0
double cpu_p{}; // defaults to = 0.0 double cpu_p{}; // defaults to = 0.0
double cpu_c{}; // defaults to = 0.0 double cpu_c{}; // defaults to = 0.0
char state = '0'; char state = '0';
int64_t p_nice{}; // defaults to 0 int64_t p_nice{}; // defaults to 0
uint64_t ppid{}; // defaults to 0 uint64_t ppid{}; // defaults to 0
uint64_t cpu_s{}; // defaults to 0 uint64_t cpu_s{}; // defaults to 0
uint64_t cpu_t{}; // defaults to 0 uint64_t cpu_t{}; // defaults to 0
string prefix{}; // defaults to "" string prefix{}; // defaults to ""
size_t depth{}; // defaults to 0 size_t depth{}; // defaults to 0
size_t tree_index{}; // defaults to 0 size_t tree_index{}; // defaults to 0
bool collapsed{}; // defaults to false bool collapsed{}; // defaults to false
bool filtered{}; // defaults to false bool filtered{}; // defaults to false
}; };
//* Container for process info box //* Container for process info box
struct detail_container { struct detail_container {
size_t last_pid{}; // defaults to 0 size_t last_pid{}; // defaults to 0
bool skip_smaps{}; // defaults to false bool skip_smaps{}; // defaults to false
proc_info entry; proc_info entry;
string elapsed, parent, status, io_read, io_write, memory; string elapsed, parent, status, io_read, io_write, memory;
long long first_mem = -1; long long first_mem = -1;
@ -288,13 +288,13 @@ namespace Proc {
extern detail_container detailed; extern detail_container detailed;
//* Collect and sort process information from /proc //* Collect and sort process information from /proc
auto collect(bool no_update = false) -> vector<proc_info>&; auto collect(bool no_update = false) -> vector<proc_info>&;
//* Update current selection and view, returns -1 if no change otherwise the current selection //* Update current selection and view, returns -1 if no change otherwise the current selection
int selection(const string& cmd_key); int selection(const string& cmd_key);
//* Draw contents of proc box using <plist> as data source //* Draw contents of proc box using <plist> as data source
string draw(const vector<proc_info>& plist, bool force_redraw = false, bool data_same = false); string draw(const vector<proc_info>& plist, bool force_redraw = false, bool data_same = false);
struct tree_proc { struct tree_proc {
std::reference_wrapper<proc_info> entry; std::reference_wrapper<proc_info> entry;
@ -302,14 +302,14 @@ namespace Proc {
}; };
//* Sort vector of proc_info's //* Sort vector of proc_info's
void proc_sorter(vector<proc_info>& proc_vec, const string& sorting, bool reverse, bool tree = false); void proc_sorter(vector<proc_info>& proc_vec, const string& sorting, bool reverse, bool tree = false);
//* Recursive sort of process tree //* Recursive sort of process tree
void tree_sort(vector<tree_proc>& proc_vec, const string& sorting, void tree_sort(vector<tree_proc>& proc_vec, const string& sorting,
bool reverse, int& c_index, const int index_max, bool collapsed = false); bool reverse, int& c_index, const int index_max, bool collapsed = false);
//* Generate process tree list //* Generate process tree list
void _tree_gen(proc_info& cur_proc, vector<proc_info>& in_procs, vector<tree_proc>& out_procs, void _tree_gen(proc_info& cur_proc, vector<proc_info>& in_procs, vector<tree_proc>& out_procs,
int cur_depth, bool collapsed, const string& filter, int cur_depth, bool collapsed, const string& filter,
bool found = false, bool no_update = false, bool should_filter = false); bool found = false, bool no_update = false, bool should_filter = false);
} }

View File

@ -4,7 +4,7 @@
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
@ -150,15 +150,15 @@ namespace Theme {
} }
} }
string hex_to_color(string hexa, bool t_to_256, const string& depth) { string hex_to_color(string hexa, bool t_to_256, const string& depth) {
if (hexa.size() > 1) { if (hexa.size() > 1) {
hexa.erase(0, 1); hexa.erase(0, 1);
for (auto& c : hexa) { for (auto& c : hexa) {
if (not isxdigit(c)) { if (not isxdigit(c)) {
Logger::error("Invalid hex value: " + hexa); Logger::error("Invalid hex value: " + hexa);
return ""; return "";
} }
} }
string pre = Fx::e + (depth == "fg" ? "38" : "48") + ";" + (t_to_256 ? "5;" : "2;"); string pre = Fx::e + (depth == "fg" ? "38" : "48") + ";" + (t_to_256 ? "5;" : "2;");
if (hexa.size() == 2) { if (hexa.size() == 2) {
@ -189,7 +189,7 @@ namespace Theme {
return ""; return "";
} }
string dec_to_color(int r, int g, int b, bool t_to_256, const string& depth) { string dec_to_color(int r, int g, int b, bool t_to_256, const string& depth) {
string pre = Fx::e + (depth == "fg" ? "38" : "48") + ";" + (t_to_256 ? "5;" : "2;"); string pre = Fx::e + (depth == "fg" ? "38" : "48") + ";" + (t_to_256 ? "5;" : "2;");
r = std::clamp(r, 0, 255); r = std::clamp(r, 0, 255);
g = std::clamp(g, 0, 255); g = std::clamp(g, 0, 255);
@ -203,17 +203,17 @@ namespace Theme {
array<int, 3> hex_to_dec(string hexa) { array<int, 3> hex_to_dec(string hexa) {
if (hexa.size() > 1) { if (hexa.size() > 1) {
hexa.erase(0, 1); hexa.erase(0, 1);
for (auto& c : hexa) { for (auto& c : hexa) {
if (not isxdigit(c)) if (not isxdigit(c))
return array{-1, -1, -1}; return array{-1, -1, -1};
} }
if (hexa.size() == 2) { if (hexa.size() == 2) {
int h_int = stoi(hexa, nullptr, 16); int h_int = stoi(hexa, nullptr, 16);
return array{h_int, h_int, h_int}; return array{h_int, h_int, h_int};
} }
else if (hexa.size() == 6) { else if (hexa.size() == 6) {
return array{ return array{
stoi(hexa.substr(0, 2), nullptr, 16), stoi(hexa.substr(0, 2), nullptr, 16),
stoi(hexa.substr(2, 2), nullptr, 16), stoi(hexa.substr(2, 2), nullptr, 16),
stoi(hexa.substr(4, 2), nullptr, 16) stoi(hexa.substr(4, 2), nullptr, 16)
@ -227,7 +227,7 @@ namespace Theme {
void generateColors(const unordered_flat_map<string, string>& source) { void generateColors(const unordered_flat_map<string, string>& source) {
vector<string> t_rgb; vector<string> t_rgb;
string depth; string depth;
bool t_to_256 = Config::getB("lowcolor"); bool t_to_256 = Config::getB("lowcolor");
colors.clear(); rgbs.clear(); colors.clear(); rgbs.clear();
for (const auto& [name, color] : Default_theme) { for (const auto& [name, color] : Default_theme) {
if (name == "main_bg" and not Config::getB("theme_background")) { if (name == "main_bg" and not Config::getB("theme_background")) {
@ -253,11 +253,11 @@ namespace Theme {
} }
else if (not source.at(name).empty()) { else if (not source.at(name).empty()) {
t_rgb = ssplit(source.at(name)); t_rgb = ssplit(source.at(name));
if (t_rgb.size() != 3) { if (t_rgb.size() != 3) {
Logger::error("Invalid RGB decimal value: \"" + source.at(name) + "\""); Logger::error("Invalid RGB decimal value: \"" + source.at(name) + "\"");
} else { } else {
colors[name] = dec_to_color(stoi(t_rgb[0]), stoi(t_rgb[1]), stoi(t_rgb[2]), t_to_256, depth); colors[name] = dec_to_color(stoi(t_rgb[0]), stoi(t_rgb[1]), stoi(t_rgb[2]), t_to_256, depth);
rgbs[name] = array{stoi(t_rgb[0]), stoi(t_rgb[1]), stoi(t_rgb[2])}; rgbs[name] = array{stoi(t_rgb[0]), stoi(t_rgb[1]), stoi(t_rgb[2])};
} }
} }
@ -290,16 +290,16 @@ namespace Theme {
//* Generate color gradients from two or three colors, 101 values indexed 0-100 //* Generate color gradients from two or three colors, 101 values indexed 0-100
void generateGradients() { void generateGradients() {
gradients.clear(); gradients.clear();
bool t_to_256 = Config::getB("lowcolor"); bool t_to_256 = Config::getB("lowcolor");
//? Insert values for processes greyscale gradient and processes color gradient //? Insert values for processes greyscale gradient and processes color gradient
rgbs.insert({ rgbs.insert({
{ "proc_start", rgbs["main_fg"] }, { "proc_start", rgbs["main_fg"] },
{ "proc_mid", {-1, -1, -1} }, { "proc_mid", {-1, -1, -1} },
{ "proc_end", rgbs["inactive_fg"] }, { "proc_end", rgbs["inactive_fg"] },
{ "proc_color_start", rgbs["inactive_fg"] }, { "proc_color_start", rgbs["inactive_fg"] },
{ "proc_color_mid", {-1, -1, -1} }, { "proc_color_mid", {-1, -1, -1} },
{ "proc_color_end", rgbs["process_start"] }, { "proc_color_end", rgbs["process_start"] },
}); });
for (const auto& [name, source_arr] : rgbs) { for (const auto& [name, source_arr] : rgbs) {
@ -322,10 +322,10 @@ namespace Theme {
//? Split iteration in two passes of 50 + 51 instead of one pass of 101 if gradient has start, mid and end values defined //? Split iteration in two passes of 50 + 51 instead of one pass of 101 if gradient has start, mid and end values defined
int current_range = (input_colors[1][0] >= 0) ? 50 : 100; int current_range = (input_colors[1][0] >= 0) ? 50 : 100;
for (int rgb : iota(0, 3)) { for (int rgb : iota(0, 3)) {
int start = 0, offset = 0; int start = 0, offset = 0;
int end = (current_range == 50) ? 1 : 2; int end = (current_range == 50) ? 1 : 2;
for (int i : iota(0, 101)) { for (int i : iota(0, 101)) {
output_colors[i][rgb] = input_colors[start][rgb] + (i - offset) * (input_colors[end][rgb] - input_colors[start][rgb]) / current_range; output_colors[i][rgb] = input_colors[start][rgb] + (i - offset) * (input_colors[end][rgb] - input_colors[start][rgb]) / current_range;
//? Switch source arrays from start->mid to mid->end at 50 passes if mid is defined //? Switch source arrays from start->mid to mid->end at 50 passes if mid is defined
@ -360,7 +360,7 @@ namespace Theme {
const string base_name = rtrim(c.first, "_start"); const string base_name = rtrim(c.first, "_start");
string section = "_start"; string section = "_start";
int split = colors.at(base_name + "_mid").empty() ? 50 : 33; int split = colors.at(base_name + "_mid").empty() ? 50 : 33;
for (int i : iota(0, 101)) { for (int i : iota(0, 101)) {
gradients[base_name][i] = colors.at(base_name + section); gradients[base_name][i] = colors.at(base_name + section);
if (i == split) { if (i == split) {
section = (split == 33) ? "_mid" : "_end"; section = (split == 33) ? "_mid" : "_end";

View File

@ -4,7 +4,7 @@
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
@ -40,13 +40,13 @@ namespace Theme {
//* Args hexa: ["#000000"-"#ffffff"] for color, ["#00"-"#ff"] for greyscale //* Args hexa: ["#000000"-"#ffffff"] for color, ["#00"-"#ff"] for greyscale
//* t_to_256: [true|false] convert 24bit value to 256 color value //* t_to_256: [true|false] convert 24bit value to 256 color value
//* depth: ["fg"|"bg"] for either a foreground color or a background color //* depth: ["fg"|"bg"] for either a foreground color or a background color
string hex_to_color(string hexa, bool t_to_256=false, const string& depth="fg"); string hex_to_color(string hexa, bool t_to_256=false, const string& depth="fg");
//* Generate escape sequence for 24-bit or 256 color and return as a string //* Generate escape sequence for 24-bit or 256 color and return as a string
//* Args r: [0-255], g: [0-255], b: [0-255] //* Args r: [0-255], g: [0-255], b: [0-255]
//* t_to_256: [true|false] convert 24bit value to 256 color value //* t_to_256: [true|false] convert 24bit value to 256 color value
//* depth: ["fg"|"bg"] for either a foreground color or a background color //* depth: ["fg"|"bg"] for either a foreground color or a background color
string dec_to_color(int r, int g, int b, bool t_to_256=false, const string& depth="fg"); string dec_to_color(int r, int g, int b, bool t_to_256=false, const string& depth="fg");
//* Update list of paths for available themes //* Update list of paths for available themes
void updateThemes(); void updateThemes();

View File

@ -55,9 +55,9 @@ namespace rng = std::ranges;
//* Collection of escape codes and functions for terminal manipulation //* Collection of escape codes and functions for terminal manipulation
namespace Term { namespace Term {
atomic<bool> initialized{}; // defaults to false atomic<bool> initialized{}; // defaults to false
atomic<int> width{}; // defaults to 0 atomic<int> width{}; // defaults to 0
atomic<int> height{}; // defaults to 0 atomic<int> height{}; // defaults to 0
string current_tty; string current_tty;
namespace { namespace {
@ -99,10 +99,10 @@ namespace Term {
} }
auto get_min_size(const string& boxes) -> array<int, 2> { auto get_min_size(const string& boxes) -> array<int, 2> {
bool cpu = boxes.find("cpu") != string::npos; bool cpu = boxes.find("cpu") != string::npos;
bool mem = boxes.find("mem") != string::npos; bool mem = boxes.find("mem") != string::npos;
bool net = boxes.find("net") != string::npos; bool net = boxes.find("net") != string::npos;
bool proc = boxes.find("proc") != string::npos; bool proc = boxes.find("proc") != string::npos;
int width = 0; int width = 0;
if (mem) width = Mem::min_width; if (mem) width = Mem::min_width;
else if (net) width = Mem::min_width; else if (net) width = Mem::min_width;
@ -121,7 +121,7 @@ namespace Term {
initialized = (bool)isatty(STDIN_FILENO); initialized = (bool)isatty(STDIN_FILENO);
if (initialized) { if (initialized) {
tcgetattr(STDIN_FILENO, &initial_settings); tcgetattr(STDIN_FILENO, &initial_settings);
current_tty = (ttyname(STDIN_FILENO) != NULL ? static_cast<string>(ttyname(STDIN_FILENO)) : "unknown"); current_tty = (ttyname(STDIN_FILENO) != NULL ? static_cast<string>(ttyname(STDIN_FILENO)) : "unknown");
//? Disable stream sync //? Disable stream sync
cin.sync_with_stdio(false); cin.sync_with_stdio(false);
@ -206,9 +206,9 @@ namespace Tools {
return chars; return chars;
} }
string uresize(string str, const size_t len, bool wide) { string uresize(string str, const size_t len, bool wide) {
if (len < 1 or str.empty()) if (len < 1 or str.empty())
return ""; return "";
if (wide) { if (wide) {
try { try {
@ -236,9 +236,9 @@ namespace Tools {
return str; return str;
} }
string luresize(string str, const size_t len, bool wide) { string luresize(string str, const size_t len, bool wide) {
if (len < 1 or str.empty()) if (len < 1 or str.empty())
return ""; return "";
for (size_t x = 0, last_pos = 0, i = str.size() - 1; i > 0 ; i--) { for (size_t x = 0, last_pos = 0, i = str.size() - 1; i > 0 ; i--) {
if (wide and static_cast<unsigned char>(str.at(i)) > 0xef) { if (wide and static_cast<unsigned char>(str.at(i)) > 0xef) {
@ -267,19 +267,19 @@ namespace Tools {
} }
string ltrim(const string& str, const string& t_str) { string ltrim(const string& str, const string& t_str) {
std::string_view str_v{str}; std::string_view str_v{str};
while (str_v.starts_with(t_str)) while (str_v.starts_with(t_str))
str_v.remove_prefix(t_str.size()); str_v.remove_prefix(t_str.size());
return string{str_v}; return string{str_v};
} }
string rtrim(const string& str, const string& t_str) { string rtrim(const string& str, const string& t_str) {
std::string_view str_v{str}; std::string_view str_v{str};
while (str_v.ends_with(t_str)) while (str_v.ends_with(t_str))
str_v.remove_suffix(t_str.size()); str_v.remove_suffix(t_str.size());
return string{str_v}; return string{str_v};
} }
auto ssplit(const string& str, const char& delim) -> vector<string> { auto ssplit(const string& str, const char& delim) -> vector<string> {
@ -293,56 +293,56 @@ namespace Tools {
return out; return out;
} }
string ljust(string str, const size_t x, bool utf, bool wide, bool limit) { string ljust(string str, const size_t x, bool utf, bool wide, bool limit) {
if (utf) { if (utf) {
if (limit and ulen(str, wide) > x) if (limit and ulen(str, wide) > x)
return uresize(str, x, wide); return uresize(str, x, wide);
return str + string(max((int)(x - ulen(str)), 0), ' '); return str + string(max((int)(x - ulen(str)), 0), ' ');
} }
else { else {
if (limit and str.size() > x) { if (limit and str.size() > x) {
str.resize(x); str.resize(x);
return str; return str;
} }
return str + string(max((int)(x - str.size()), 0), ' '); return str + string(max((int)(x - str.size()), 0), ' ');
} }
} }
string rjust(string str, const size_t x, bool utf, bool wide, bool limit) { string rjust(string str, const size_t x, bool utf, bool wide, bool limit) {
if (utf) { if (utf) {
if (limit and ulen(str, wide) > x) if (limit and ulen(str, wide) > x)
return uresize(str, x, wide); return uresize(str, x, wide);
return string(max((int)(x - ulen(str)), 0), ' ') + str; return string(max((int)(x - ulen(str)), 0), ' ') + str;
} }
else { else {
if (limit and str.size() > x) { if (limit and str.size() > x) {
str.resize(x); str.resize(x);
return str; return str;
}; };
return string(max((int)(x - str.size()), 0), ' ') + str; return string(max((int)(x - str.size()), 0), ' ') + str;
} }
} }
string cjust(string str, const size_t x, bool utf, bool wide, bool limit) { string cjust(string str, const size_t x, bool utf, bool wide, bool limit) {
if (utf) { if (utf) {
if (limit and ulen(str, wide) > x) if (limit and ulen(str, wide) > x)
return uresize(str, x, wide); return uresize(str, x, wide);
return string(max((int)ceil((double)(x - ulen(str)) / 2), 0), ' ') + str + string(max((int)floor((double)(x - ulen(str)) / 2), 0), ' '); return string(max((int)ceil((double)(x - ulen(str)) / 2), 0), ' ') + str + string(max((int)floor((double)(x - ulen(str)) / 2), 0), ' ');
} }
else { else {
if (limit and str.size() > x) { if (limit and str.size() > x) {
str.resize(x); str.resize(x);
return str; return str;
} }
return string(max((int)ceil((double)(x - str.size()) / 2), 0), ' ') + str + string(max((int)floor((double)(x - str.size()) / 2), 0), ' '); return string(max((int)ceil((double)(x - str.size()) / 2), 0), ' ') + str + string(max((int)floor((double)(x - str.size()) / 2), 0), ' ');
} }
} }
string trans(const string& str) { string trans(const string& str) {
std::string_view oldstr{str}; std::string_view oldstr{str};
string newstr; string newstr;
newstr.reserve(str.size()); newstr.reserve(str.size());
for (size_t pos; (pos = oldstr.find(' ')) != string::npos;) { for (size_t pos; (pos = oldstr.find(' ')) != string::npos;) {
@ -352,7 +352,7 @@ namespace Tools {
newstr.append(Mv::r(x)); newstr.append(Mv::r(x));
oldstr.remove_prefix(pos + x); oldstr.remove_prefix(pos + x);
} }
return (newstr.empty()) ? str : newstr + string{oldstr}; return (newstr.empty()) ? str : newstr + string{oldstr};
} }
string sec_to_dhms(size_t seconds, bool no_days, bool no_seconds) { string sec_to_dhms(size_t seconds, bool no_days, bool no_seconds) {
@ -366,37 +366,37 @@ namespace Tools {
return out; return out;
} }
string floating_humanizer(uint64_t value, bool shorten, size_t start, bool bit, bool per_second) { string floating_humanizer(uint64_t value, bool shorten, size_t start, bool bit, bool per_second) {
string out; string out;
const size_t mult = (bit) ? 8 : 1; const size_t mult = (bit) ? 8 : 1;
bool mega = Config::getB("base_10_sizes"); bool mega = Config::getB("base_10_sizes");
// taking advantage of type deduction for array creation (since C++17) // taking advantage of type deduction for array creation (since C++17)
// combined with string literals (operator""s) // combined with string literals (operator""s)
static const array mebiUnits_bit { static const array mebiUnits_bit {
"bit"s, "Kib"s, "Mib"s, "bit"s, "Kib"s, "Mib"s,
"Gib"s, "Tib"s, "Pib"s, "Gib"s, "Tib"s, "Pib"s,
"Eib"s, "Zib"s, "Yib"s, "Eib"s, "Zib"s, "Yib"s,
"Bib"s, "GEb"s "Bib"s, "GEb"s
}; };
static const array mebiUnits_byte { static const array mebiUnits_byte {
"Byte"s, "KiB"s, "MiB"s, "Byte"s, "KiB"s, "MiB"s,
"GiB"s, "TiB"s, "PiB"s, "GiB"s, "TiB"s, "PiB"s,
"EiB"s, "ZiB"s, "YiB"s, "EiB"s, "ZiB"s, "YiB"s,
"BiB"s, "GEB"s "BiB"s, "GEB"s
}; };
static const array megaUnits_bit { static const array megaUnits_bit {
"bit"s, "Kb"s, "Mb"s, "bit"s, "Kb"s, "Mb"s,
"Gb"s, "Tb"s, "Pb"s, "Gb"s, "Tb"s, "Pb"s,
"Eb"s, "Zb"s, "Yb"s, "Eb"s, "Zb"s, "Yb"s,
"Bb"s, "Gb"s "Bb"s, "Gb"s
}; };
static const array megaUnits_byte { static const array megaUnits_byte {
"Byte"s, "KB"s, "MB"s, "Byte"s, "KB"s, "MB"s,
"GB"s, "TB"s, "PB"s, "GB"s, "TB"s, "PB"s,
"EB"s, "ZB"s, "YB"s, "EB"s, "ZB"s, "YB"s,
"BB"s, "GB"s "BB"s, "GB"s
}; };
const auto& units = (bit) ? ( mega ? megaUnits_bit : mebiUnits_bit) : ( mega ? megaUnits_byte : mebiUnits_byte); const auto& units = (bit) ? ( mega ? megaUnits_bit : mebiUnits_bit) : ( mega ? megaUnits_byte : mebiUnits_byte);
value *= 100 * mult; value *= 100 * mult;
@ -423,29 +423,29 @@ namespace Tools {
} }
if (out.empty()) { if (out.empty()) {
out = to_string(value); out = to_string(value);
if (not mega and out.size() == 4 and start > 0) { if (not mega and out.size() == 4 and start > 0) {
out.pop_back(); out.pop_back();
out.insert(2, "."); out.insert(2, ".");
} }
else if (out.size() == 3 and start > 0) { else if (out.size() == 3 and start > 0) {
out.insert(1, "."); out.insert(1, ".");
} }
else if (out.size() >= 2) { else if (out.size() >= 2) {
out.resize(out.size() - 2); out.resize(out.size() - 2);
} }
} }
if (shorten) { if (shorten) {
auto f_pos = out.find('.'); auto f_pos = out.find('.');
if (f_pos == 1 and out.size() > 3) { if (f_pos == 1 and out.size() > 3) {
out = to_string(round(stod(out) * 10) / 10).substr(0,3); out = to_string(round(stod(out) * 10) / 10).substr(0,3);
} }
else if (f_pos != string::npos) { else if (f_pos != string::npos) {
out = to_string((int)round(stod(out))); out = to_string((int)round(stod(out)));
} }
if (out.size() > 3) { if (out.size() > 3) {
out = to_string((int)(out[0] - '0') + 1); out = to_string((int)(out[0] - '0') + 1);
start++; start++;
} }
out.push_back(units[start][0]); out.push_back(units[start][0]);
} }
else out += " " + units[start]; else out += " " + units[start];
@ -455,18 +455,18 @@ namespace Tools {
} }
std::string operator*(const string& str, int64_t n) { std::string operator*(const string& str, int64_t n) {
if (n < 1 or str.empty()) { if (n < 1 or str.empty()) {
return ""; return "";
} }
else if (n == 1) { else if (n == 1) {
return str; return str;
} }
string new_str; string new_str;
new_str.reserve(str.size() * n); new_str.reserve(str.size() * n);
for (; n > 0; n--) for (; n > 0; n--)
new_str.append(str); new_str.append(str);
return new_str; return new_str;
} }
@ -479,11 +479,11 @@ namespace Tools {
return ss.str(); return ss.str();
} }
void atomic_wait(const atomic<bool>& atom, bool old) noexcept { void atomic_wait(const atomic<bool>& atom, bool old) noexcept {
while (atom.load(std::memory_order_relaxed) == old ) busy_wait(); while (atom.load(std::memory_order_relaxed) == old ) busy_wait();
} }
void atomic_wait_for(const atomic<bool>& atom, bool old, const uint64_t wait_ms) noexcept { void atomic_wait_for(const atomic<bool>& atom, bool old, const uint64_t wait_ms) noexcept {
const uint64_t start_time = time_ms(); const uint64_t start_time = time_ms();
while (atom.load(std::memory_order_relaxed) == old and (time_ms() - start_time < wait_ms)) sleep_ms(1); while (atom.load(std::memory_order_relaxed) == old and (time_ms() - start_time < wait_ms)) sleep_ms(1);
} }
@ -505,7 +505,7 @@ namespace Tools {
for (string readstr; getline(file, readstr); out += readstr); for (string readstr; getline(file, readstr); out += readstr);
} }
catch (const std::exception& e) { catch (const std::exception& e) {
Logger::error("readfile() : Exception when reading " + string{path} + " : " + e.what()); Logger::error("readfile() : Exception when reading " + string{path} + " : " + e.what());
return fallback; return fallback;
} }
return (out.empty() ? fallback : out); return (out.empty() ? fallback : out);
@ -526,7 +526,7 @@ namespace Tools {
string hostname() { string hostname() {
char host[HOST_NAME_MAX]; char host[HOST_NAME_MAX];
gethostname(host, HOST_NAME_MAX); gethostname(host, HOST_NAME_MAX);
return string{host}; return string{host};
} }
string username() { string username() {
@ -551,14 +551,14 @@ namespace Logger {
int status = -1; int status = -1;
public: public:
lose_priv() { lose_priv() {
if (geteuid() != Global::real_uid) { if (geteuid() != Global::real_uid) {
this->status = seteuid(Global::real_uid); this->status = seteuid(Global::real_uid);
} }
} }
~lose_priv() { ~lose_priv() {
if (status == 0) { if (status == 0) {
status = seteuid(Global::set_uid); status = seteuid(Global::set_uid);
} }
} }
}; };
@ -576,25 +576,25 @@ namespace Logger {
auto old_log = logfile; auto old_log = logfile;
old_log += ".1"; old_log += ".1";
if (fs::exists(old_log)) if (fs::exists(old_log))
fs::remove(old_log, ec); fs::remove(old_log, ec);
if (not ec) if (not ec)
fs::rename(logfile, old_log, ec); fs::rename(logfile, old_log, ec);
} }
if (not ec) { if (not ec) {
std::ofstream lwrite(logfile, std::ios::app); std::ofstream lwrite(logfile, std::ios::app);
if (first) { if (first) {
first = false; first = false;
lwrite << "\n" << strf_time(tdf) << "===> btop++ v." << Global::Version << "\n"; lwrite << "\n" << strf_time(tdf) << "===> btop++ v." << Global::Version << "\n";
} }
lwrite << strf_time(tdf) << log_levels.at(level) << ": " << msg << "\n"; lwrite << strf_time(tdf) << log_levels.at(level) << ": " << msg << "\n";
} }
else logfile.clear(); else logfile.clear();
} }
catch (const std::exception& e) { catch (const std::exception& e) {
logfile.clear(); logfile.clear();
throw std::runtime_error("Exception in Logger::log_write() : " + string{e.what()}); throw std::runtime_error("Exception in Logger::log_write() : " + string{e.what()});
} }
} }
} }

View File

@ -91,19 +91,19 @@ namespace Fx {
//* Collection of escape codes and functions for cursor manipulation //* Collection of escape codes and functions for cursor manipulation
namespace Mv { namespace Mv {
//* Move cursor to <line>, <column> //* Move cursor to <line>, <column>
inline string to(int line, int col) { return Fx::e + to_string(line) + ';' + to_string(col) + 'f'; } inline string to(int line, int col) { return Fx::e + to_string(line) + ';' + to_string(col) + 'f'; }
//* Move cursor right <x> columns //* Move cursor right <x> columns
inline string r(int x) { return Fx::e + to_string(x) + 'C'; } inline string r(int x) { return Fx::e + to_string(x) + 'C'; }
//* Move cursor left <x> columns //* Move cursor left <x> columns
inline string l(int x) { return Fx::e + to_string(x) + 'D'; } inline string l(int x) { return Fx::e + to_string(x) + 'D'; }
//* Move cursor up x lines //* Move cursor up x lines
inline string u(int x) { return Fx::e + to_string(x) + 'A'; } inline string u(int x) { return Fx::e + to_string(x) + 'A'; }
//* Move cursor down x lines //* Move cursor down x lines
inline string d(int x) { return Fx::e + to_string(x) + 'B'; } inline string d(int x) { return Fx::e + to_string(x) + 'B'; }
//* Save cursor position //* Save cursor position
const string save = Fx::e + "s"; const string save = Fx::e + "s";
@ -155,15 +155,15 @@ namespace Tools {
size_t wide_ulen(const std::wstring& w_str); size_t wide_ulen(const std::wstring& w_str);
//* Return number of UTF8 characters in a string (wide=true for column size needed on terminal) //* Return number of UTF8 characters in a string (wide=true for column size needed on terminal)
inline size_t ulen(const string& str, bool wide = false) { inline size_t ulen(const string& str, bool wide = false) {
return (wide ? wide_ulen(str) : std::ranges::count_if(str, [](char c) { return (static_cast<unsigned char>(c) & 0xC0) != 0x80; })); return (wide ? wide_ulen(str) : std::ranges::count_if(str, [](char c) { return (static_cast<unsigned char>(c) & 0xC0) != 0x80; }));
} }
//* Resize a string consisting of UTF8 characters (only reduces size) //* Resize a string consisting of UTF8 characters (only reduces size)
string uresize(const string str, const size_t len, bool wide = false); string uresize(const string str, const size_t len, bool wide = false);
//* Resize a string consisting of UTF8 characters from left (only reduces size) //* Resize a string consisting of UTF8 characters from left (only reduces size)
string luresize(const string str, const size_t len, bool wide = false); string luresize(const string str, const size_t len, bool wide = false);
//* Replace <from> in <str> with <to> and return new string //* Replace <from> in <str> with <to> and return new string
string s_replace(const string& str, const string& from, const string& to); string s_replace(const string& str, const string& from, const string& to);
@ -200,11 +200,11 @@ namespace Tools {
//* Check if string <str> contains string <find_val>, while ignoring case //* Check if string <str> contains string <find_val>, while ignoring case
inline bool s_contains_ic(const string& str, const string& find_val) { inline bool s_contains_ic(const string& str, const string& find_val) {
auto it = std::search( auto it = std::search(
str.begin(), str.end(), str.begin(), str.end(),
find_val.begin(), find_val.end(), find_val.begin(), find_val.end(),
[](char ch1, char ch2) { return std::toupper(ch1) == std::toupper(ch2); } [](char ch1, char ch2) { return std::toupper(ch1) == std::toupper(ch2); }
); );
return it != str.end(); return it != str.end();
} }
@ -265,35 +265,35 @@ namespace Tools {
auto ssplit(const string& str, const char& delim = ' ') -> vector<string>; auto ssplit(const string& str, const char& delim = ' ') -> vector<string>;
//* Put current thread to sleep for <ms> milliseconds //* Put current thread to sleep for <ms> milliseconds
inline void sleep_ms(const size_t& ms) { inline void sleep_ms(const size_t& ms) {
std::this_thread::sleep_for(std::chrono::milliseconds(ms)); std::this_thread::sleep_for(std::chrono::milliseconds(ms));
} }
//* Put current thread to sleep for <micros> microseconds //* Put current thread to sleep for <micros> microseconds
inline void sleep_micros(const size_t& micros) { inline void sleep_micros(const size_t& micros) {
std::this_thread::sleep_for(std::chrono::microseconds(micros)); std::this_thread::sleep_for(std::chrono::microseconds(micros));
} }
//* Left justify string <str> if <x> is greater than <str> length, limit return size to <x> by default //* Left justify string <str> if <x> is greater than <str> length, limit return size to <x> by default
string ljust(string str, const size_t x, bool utf = false, bool wide = false, bool limit = true); string ljust(string str, const size_t x, bool utf = false, bool wide = false, bool limit = true);
//* Right justify string <str> if <x> is greater than <str> length, limit return size to <x> by default //* Right justify string <str> if <x> is greater than <str> length, limit return size to <x> by default
string rjust(string str, const size_t x, bool utf = false, bool wide = false, bool limit = true); string rjust(string str, const size_t x, bool utf = false, bool wide = false, bool limit = true);
//* Center justify string <str> if <x> is greater than <str> length, limit return size to <x> by default //* Center justify string <str> if <x> is greater than <str> length, limit return size to <x> by default
string cjust(string str, const size_t x, bool utf = false, bool wide = false, bool limit = true); string cjust(string str, const size_t x, bool utf = false, bool wide = false, bool limit = true);
//* Replace whitespaces " " with escape code for move right //* Replace whitespaces " " with escape code for move right
string trans(const string& str); string trans(const string& str);
//* Convert seconds to format "<days>d <hours>:<minutes>:<seconds>" and return string //* Convert seconds to format "<days>d <hours>:<minutes>:<seconds>" and return string
string sec_to_dhms(size_t seconds, bool no_days = false, bool no_seconds = false); string sec_to_dhms(size_t seconds, bool no_days = false, bool no_seconds = false);
//* Scales up in steps of 1024 to highest positive value unit and returns string with unit suffixed //* Scales up in steps of 1024 to highest positive value unit and returns string with unit suffixed
//* bit=True or defaults to bytes //* bit=True or defaults to bytes
//* start=int to set 1024 multiplier starting unit //* start=int to set 1024 multiplier starting unit
//* short=True always returns 0 decimals and shortens unit to 1 character //* short=True always returns 0 decimals and shortens unit to 1 character
string floating_humanizer(uint64_t value, bool shorten = false, size_t start = 0, bool bit = false, bool per_second = false); string floating_humanizer(uint64_t value, bool shorten = false, size_t start = 0, bool bit = false, bool per_second = false);
//* Add std::string operator * : Repeat string <str> <n> number of times //* Add std::string operator * : Repeat string <str> <n> number of times
std::string operator*(const string& str, int64_t n); std::string operator*(const string& str, int64_t n);
@ -316,21 +316,21 @@ namespace Tools {
#endif #endif
} }
void atomic_wait(const atomic<bool>& atom, bool old = true) noexcept; void atomic_wait(const atomic<bool>& atom, bool old = true) noexcept;
void atomic_wait_for(const atomic<bool>& atom, bool old = true, const uint64_t wait_ms = 0) noexcept; void atomic_wait_for(const atomic<bool>& atom, bool old = true, const uint64_t wait_ms = 0) noexcept;
//* Sets atomic<bool> to true on construct, sets to false on destruct //* Sets atomic<bool> to true on construct, sets to false on destruct
class atomic_lock { class atomic_lock {
atomic<bool>& atom; atomic<bool>& atom;
bool not_true{}; // defaults to false bool not_true{}; // defaults to false
public: public:
atomic_lock(atomic<bool>& atom, bool wait = false); atomic_lock(atomic<bool>& atom, bool wait = false);
~atomic_lock(); ~atomic_lock();
}; };
//* Read a complete file and return as a string //* Read a complete file and return as a string
string readfile(const std::filesystem::path& path, const string& fallback = ""); string readfile(const std::filesystem::path& path, const string& fallback = "");
//* Convert a celsius value to celsius, fahrenheit, kelvin or rankin and return tuple with new value and unit. //* Convert a celsius value to celsius, fahrenheit, kelvin or rankin and return tuple with new value and unit.
auto celsius_to(const long long& celsius, const string& scale) -> tuple<long long, string>; auto celsius_to(const long long& celsius, const string& scale) -> tuple<long long, string>;

View File

@ -4,7 +4,7 @@
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
@ -120,12 +120,12 @@ namespace Shared {
//? Shared global variables init //? Shared global variables init
int mib[2]; int mib[2];
mib[0] = CTL_HW; mib[0] = CTL_HW;
mib[1] = HW_NCPU; mib[1] = HW_NCPU;
int ncpu; int ncpu;
size_t len = sizeof(ncpu); size_t len = sizeof(ncpu);
if (sysctl(mib, 2, &ncpu, &len, NULL, 0) == -1) { if (sysctl(mib, 2, &ncpu, &len, NULL, 0) == -1) {
Logger::warning("Could not determine number of cores, defaulting to 1."); Logger::warning("Could not determine number of cores, defaulting to 1.");
} else { } else {
coreCount = ncpu; coreCount = ncpu;
} }
@ -205,12 +205,12 @@ namespace Cpu {
const array<string, 10> time_names = {"user", "nice", "system", "idle"}; const array<string, 10> time_names = {"user", "nice", "system", "idle"};
unordered_flat_map<string, long long> cpu_old = { unordered_flat_map<string, long long> cpu_old = {
{"totals", 0}, {"totals", 0},
{"idles", 0}, {"idles", 0},
{"user", 0}, {"user", 0},
{"nice", 0}, {"nice", 0},
{"system", 0}, {"system", 0},
{"idle", 0} {"idle", 0}
}; };
string get_cpuName() { string get_cpuName() {
@ -398,7 +398,7 @@ namespace Cpu {
return {percent, seconds, status}; return {percent, seconds, status};
} }
auto collect(bool no_update) -> cpu_info & { auto collect(bool no_update) -> cpu_info & {
if (Runner::stopping or (no_update and not current_cpu.cpu_percent.at("total").empty())) if (Runner::stopping or (no_update and not current_cpu.cpu_percent.at("total").empty()))
return current_cpu; return current_cpu;
auto &cpu = current_cpu; auto &cpu = current_cpu;
@ -555,17 +555,17 @@ namespace Mem {
} }
} }
void collect_disk(unordered_flat_map<string, disk_info> &disks, unordered_flat_map<string, string> &mapping) { void collect_disk(unordered_flat_map<string, disk_info> &disks, unordered_flat_map<string, string> &mapping) {
// this bit is for 'regular' mounts // this bit is for 'regular' mounts
static struct statinfo cur; static struct statinfo cur;
long double etime = 0; long double etime = 0;
uint64_t total_bytes_read; uint64_t total_bytes_read;
uint64_t total_bytes_write; uint64_t total_bytes_write;
static std::unique_ptr<struct devinfo, decltype(std::free)*> curDevInfo (reinterpret_cast<struct devinfo*>(std::calloc(1, sizeof(struct devinfo))), std::free); static std::unique_ptr<struct devinfo, decltype(std::free)*> curDevInfo (reinterpret_cast<struct devinfo*>(std::calloc(1, sizeof(struct devinfo))), std::free);
cur.dinfo = curDevInfo.get(); cur.dinfo = curDevInfo.get();
if (devstat_getdevs(NULL, &cur) != -1) { if (devstat_getdevs(NULL, &cur) != -1) {
for (int i = 0; i < cur.dinfo->numdevs; i++) { for (int i = 0; i < cur.dinfo->numdevs; i++) {
auto d = cur.dinfo->devices[i]; auto d = cur.dinfo->devices[i];
string devStatName = "/dev/" + string(d.device_name) + std::to_string(d.unit_number); string devStatName = "/dev/" + string(d.device_name) + std::to_string(d.unit_number);
@ -617,17 +617,17 @@ namespace Mem {
} }
} }
} }
auto collect(bool no_update) -> mem_info & { auto collect(bool no_update) -> mem_info & {
if (Runner::stopping or (no_update and not current_mem.percent.at("used").empty())) if (Runner::stopping or (no_update and not current_mem.percent.at("used").empty()))
return current_mem; return current_mem;
auto show_swap = Config::getB("show_swap"); auto show_swap = Config::getB("show_swap");
auto show_disks = Config::getB("show_disks"); auto show_disks = Config::getB("show_disks");
auto swap_disk = Config::getB("swap_disk"); auto swap_disk = Config::getB("swap_disk");
auto &mem = current_mem; auto &mem = current_mem;
static bool snapped = (getenv("BTOP_SNAPPED") != NULL); static bool snapped = (getenv("BTOP_SNAPPED") != NULL);
int mib[4]; int mib[4];
u_int memActive, memWire, cachedMem, freeMem; u_int memActive, memWire, cachedMem, freeMem;
@ -693,7 +693,7 @@ namespace Mem {
double uptime = system_uptime(); double uptime = system_uptime();
auto &disks_filter = Config::getS("disks_filter"); auto &disks_filter = Config::getS("disks_filter");
bool filter_exclude = false; bool filter_exclude = false;
// auto only_physical = Config::getB("only_physical"); // auto only_physical = Config::getB("only_physical");
auto &disks = mem.disks; auto &disks = mem.disks;
vector<string> filter; vector<string> filter;
if (not disks_filter.empty()) { if (not disks_filter.empty()) {
@ -711,7 +711,7 @@ namespace Mem {
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
auto fstype = string(stfs[i].f_fstypename); auto fstype = string(stfs[i].f_fstypename);
if (fstype == "autofs" || fstype == "devfs" || fstype == "linprocfs" || fstype == "procfs" || fstype == "tmpfs" || fstype == "linsysfs" || if (fstype == "autofs" || fstype == "devfs" || fstype == "linprocfs" || fstype == "procfs" || fstype == "tmpfs" || fstype == "linsysfs" ||
fstype == "fdesckfs") { fstype == "fdesckfs") {
// in memory filesystems -> not useful to show // in memory filesystems -> not useful to show
continue; continue;
} }
@ -826,11 +826,11 @@ namespace Net {
auto operator()() -> struct ifaddrs * { return ifaddr; } auto operator()() -> struct ifaddrs * { return ifaddr; }
}; };
auto collect(bool no_update) -> net_info & { auto collect(bool no_update) -> net_info & {
auto &net = current_net; auto &net = current_net;
auto &config_iface = Config::getS("net_iface"); auto &config_iface = Config::getS("net_iface");
auto net_sync = Config::getB("net_sync"); auto net_sync = Config::getB("net_sync");
auto net_auto = Config::getB("net_auto"); auto net_auto = Config::getB("net_auto");
auto new_timestamp = time_ms(); auto new_timestamp = time_ms();
if (not no_update and errors < 3) { if (not no_update and errors < 3) {
@ -985,7 +985,7 @@ namespace Net {
auto sorted_interfaces = interfaces; auto sorted_interfaces = interfaces;
rng::sort(sorted_interfaces, [&](const auto &a, const auto &b) { rng::sort(sorted_interfaces, [&](const auto &a, const auto &b) {
return cmp_greater(net.at(a).stat["download"].total + net.at(a).stat["upload"].total, return cmp_greater(net.at(a).stat["download"].total + net.at(a).stat["upload"].total,
net.at(b).stat["download"].total + net.at(b).stat["upload"].total); net.at(b).stat["download"].total + net.at(b).stat["upload"].total);
}); });
selected_iface.clear(); selected_iface.clear();
//? Try to set to a connected interface //? Try to set to a connected interface
@ -1008,8 +1008,8 @@ namespace Net {
for (const auto &sel : {0, 1}) { for (const auto &sel : {0, 1}) {
if (rescale or max_count[dir][sel] >= 5) { if (rescale or max_count[dir][sel] >= 5) {
const long long avg_speed = (net[selected_iface].bandwidth[dir].size() > 5 const long long avg_speed = (net[selected_iface].bandwidth[dir].size() > 5
? std::accumulate(net.at(selected_iface).bandwidth.at(dir).rbegin(), net.at(selected_iface).bandwidth.at(dir).rbegin() + 5, 0ll) / 5 ? std::accumulate(net.at(selected_iface).bandwidth.at(dir).rbegin(), net.at(selected_iface).bandwidth.at(dir).rbegin() + 5, 0ll) / 5
: net[selected_iface].stat[dir].speed); : net[selected_iface].stat[dir].speed);
graph_max[dir] = max(uint64_t(avg_speed * (sel == 0 ? 1.3 : 3.0)), (uint64_t)10 << 10); graph_max[dir] = max(uint64_t(avg_speed * (sel == 0 ? 1.3 : 3.0)), (uint64_t)10 << 10);
max_count[dir][0] = max_count[dir][1] = 0; max_count[dir][0] = max_count[dir][1] = 0;
redraw = true; redraw = true;
@ -1110,17 +1110,17 @@ namespace Proc {
} }
//* Collects and sorts process information from /proc //* Collects and sorts process information from /proc
auto collect(bool no_update) -> vector<proc_info> & { auto collect(bool no_update) -> vector<proc_info> & {
const auto &sorting = Config::getS("proc_sorting"); const auto &sorting = Config::getS("proc_sorting");
auto reverse = Config::getB("proc_reversed"); auto reverse = Config::getB("proc_reversed");
const auto &filter = Config::getS("proc_filter"); const auto &filter = Config::getS("proc_filter");
auto per_core = Config::getB("proc_per_core"); auto per_core = Config::getB("proc_per_core");
auto tree = Config::getB("proc_tree"); auto tree = Config::getB("proc_tree");
auto show_detailed = Config::getB("show_detailed"); auto show_detailed = Config::getB("show_detailed");
const size_t detailed_pid = Config::getI("detailed_pid"); const size_t detailed_pid = Config::getI("detailed_pid");
bool should_filter = current_filter != filter; bool should_filter = current_filter != filter;
if (should_filter) current_filter = filter; if (should_filter) current_filter = filter;
bool sorted_change = (sorting != current_sort or reverse != current_rev or should_filter); bool sorted_change = (sorting != current_sort or reverse != current_rev or should_filter);
if (sorted_change) { if (sorted_change) {
current_sort = sorting; current_sort = sorting;
current_rev = reverse; current_rev = reverse;
@ -1156,12 +1156,12 @@ namespace Proc {
const double timeNow = currentTime.tv_sec + (currentTime.tv_usec / 1'000'000); const double timeNow = currentTime.tv_sec + (currentTime.tv_usec / 1'000'000);
int count = 0; int count = 0;
char buf[_POSIX2_LINE_MAX]; char buf[_POSIX2_LINE_MAX];
Shared::kvm_openfiles_wrapper kd(NULL, _PATH_DEVNULL, NULL, O_RDONLY, buf); Shared::kvm_openfiles_wrapper kd(NULL, _PATH_DEVNULL, NULL, O_RDONLY, buf);
const struct kinfo_proc* kprocs = kvm_getprocs(kd(), KERN_PROC_PROC, 0, &count); const struct kinfo_proc* kprocs = kvm_getprocs(kd(), KERN_PROC_PROC, 0, &count);
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
const struct kinfo_proc* kproc = &kprocs[i]; const struct kinfo_proc* kproc = &kprocs[i];
const size_t pid = (size_t)kproc->ki_pid; const size_t pid = (size_t)kproc->ki_pid;
if (pid < 1) continue; if (pid < 1) continue;
found.push_back(pid); found.push_back(pid);

View File

@ -63,8 +63,8 @@ namespace Cpu {
vector<string> available_sensors = {"Auto"}; vector<string> available_sensors = {"Auto"};
cpu_info current_cpu; cpu_info current_cpu;
fs::path freq_path = "/sys/devices/system/cpu/cpufreq/policy0/scaling_cur_freq"; fs::path freq_path = "/sys/devices/system/cpu/cpufreq/policy0/scaling_cur_freq";
bool got_sensors{}; // defaults to false bool got_sensors{}; // defaults to false
bool cpu_temp_only{}; // defaults to false bool cpu_temp_only{}; // defaults to false
//* Populate found_sensors map //* Populate found_sensors map
bool get_sensors(); bool get_sensors();
@ -78,9 +78,9 @@ namespace Cpu {
struct Sensor { struct Sensor {
fs::path path; fs::path path;
string label; string label;
int64_t temp{}; // defaults to 0 int64_t temp{}; // defaults to 0
int64_t high{}; // defaults to 0 int64_t high{}; // defaults to 0
int64_t crit{}; // defaults to 0 int64_t crit{}; // defaults to 0
}; };
unordered_flat_map<string, Sensor> found_sensors; unordered_flat_map<string, Sensor> found_sensors;
@ -162,10 +162,10 @@ namespace Cpu {
bool has_battery = true; bool has_battery = true;
tuple<int, long, string> current_bat; tuple<int, long, string> current_bat;
const array time_names { const array time_names {
"user"s, "nice"s, "system"s, "idle"s, "iowait"s, "user"s, "nice"s, "system"s, "idle"s, "iowait"s,
"irq"s, "softirq"s, "steal"s, "guest"s, "guest_nice"s "irq"s, "softirq"s, "steal"s, "guest"s, "guest_nice"s
}; };
unordered_flat_map<string, long long> cpu_old = { unordered_flat_map<string, long long> cpu_old = {
{"totals", 0}, {"totals", 0},
@ -408,14 +408,14 @@ namespace Cpu {
} }
string get_cpuHz() { string get_cpuHz() {
static int failed{}; // defaults to 0 static int failed{}; // defaults to 0
if (failed > 4) if (failed > 4)
return ""s; return ""s;
string cpuhz; string cpuhz;
try { try {
double hz{}; // defaults to 0.0 double hz{}; // defaults to 0.0
//? Try to get freq from /sys/devices/system/cpu/cpufreq/policy first (faster) //? Try to get freq from /sys/devices/system/cpu/cpufreq/policy first (faster)
if (not freq_path.empty()) { if (not freq_path.empty()) {
hz = stod(readfile(freq_path, "0.0")) / 1000; hz = stod(readfile(freq_path, "0.0")) / 1000;
@ -440,8 +440,8 @@ namespace Cpu {
} }
} }
if (hz <= 1 or hz >= 1000000) if (hz <= 1 or hz >= 1000000)
throw std::runtime_error("Failed to read /sys/devices/system/cpu/cpufreq/policy and /proc/cpuinfo."); throw std::runtime_error("Failed to read /sys/devices/system/cpu/cpufreq/policy and /proc/cpuinfo.");
if (hz >= 1000) { if (hz >= 1000) {
if (hz >= 10000) cpuhz = to_string((int)round(hz / 1000)); // Future proof until we reach THz speeds :) if (hz >= 10000) cpuhz = to_string((int)round(hz / 1000)); // Future proof until we reach THz speeds :)
@ -471,9 +471,9 @@ namespace Cpu {
//? Try to get core mapping from /proc/cpuinfo //? Try to get core mapping from /proc/cpuinfo
ifstream cpuinfo(Shared::procPath / "cpuinfo"); ifstream cpuinfo(Shared::procPath / "cpuinfo");
if (cpuinfo.good()) { if (cpuinfo.good()) {
int cpu{}; // defaults to 0 int cpu{}; // defaults to 0
int core{}; // defaults to 0 int core{}; // defaults to 0
int n{}; // defaults to 0 int n{}; // defaults to 0
for (string instr; cpuinfo >> instr;) { for (string instr; cpuinfo >> instr;) {
if (instr == "processor") { if (instr == "processor") {
cpuinfo.ignore(SSmax, ':'); cpuinfo.ignore(SSmax, ':');
@ -666,7 +666,7 @@ namespace Cpu {
return {percent, seconds, status}; return {percent, seconds, status};
} }
auto collect(bool no_update) -> cpu_info& { auto collect(bool no_update) -> cpu_info& {
if (Runner::stopping or (no_update and not current_cpu.cpu_percent.at("total").empty())) return current_cpu; if (Runner::stopping or (no_update and not current_cpu.cpu_percent.at("total").empty())) return current_cpu;
auto& cpu = current_cpu; auto& cpu = current_cpu;
@ -808,10 +808,10 @@ namespace Cpu {
} }
namespace Mem { namespace Mem {
bool has_swap{}; // defaults to false bool has_swap{}; // defaults to false
vector<string> fstab; vector<string> fstab;
fs::file_time_type fstab_time; fs::file_time_type fstab_time;
int disk_ios{}; // defaults to 0 int disk_ios{}; // defaults to 0
vector<string> last_found; vector<string> last_found;
//?* Find the filepath to the specified ZFS object's stat file //?* Find the filepath to the specified ZFS object's stat file
@ -836,12 +836,12 @@ namespace Mem {
return totalMem; return totalMem;
} }
auto collect(bool no_update) -> mem_info& { auto collect(bool no_update) -> mem_info& {
if (Runner::stopping or (no_update and not current_mem.percent.at("used").empty())) return current_mem; if (Runner::stopping or (no_update and not current_mem.percent.at("used").empty())) return current_mem;
auto show_swap = Config::getB("show_swap"); auto show_swap = Config::getB("show_swap");
auto swap_disk = Config::getB("swap_disk"); auto swap_disk = Config::getB("swap_disk");
auto show_disks = Config::getB("show_disks"); auto show_disks = Config::getB("show_disks");
auto zfs_arc_cached = Config::getB("zfs_arc_cached"); auto zfs_arc_cached = Config::getB("zfs_arc_cached");
auto totalMem = get_totalMem(); auto totalMem = get_totalMem();
auto& mem = current_mem; auto& mem = current_mem;
@ -935,9 +935,9 @@ namespace Mem {
try { try {
auto& disks_filter = Config::getS("disks_filter"); auto& disks_filter = Config::getS("disks_filter");
bool filter_exclude = false; bool filter_exclude = false;
auto use_fstab = Config::getB("use_fstab"); auto use_fstab = Config::getB("use_fstab");
auto only_physical = Config::getB("only_physical"); auto only_physical = Config::getB("only_physical");
auto zfs_hide_datasets = Config::getB("zfs_hide_datasets"); auto zfs_hide_datasets = Config::getB("zfs_hide_datasets");
auto& disks = mem.disks; auto& disks = mem.disks;
ifstream diskread; ifstream diskread;
@ -1208,14 +1208,14 @@ namespace Mem {
while (cmp_greater(disk.io_activity.size(), width * 2)) disk.io_activity.pop_front(); while (cmp_greater(disk.io_activity.size(), width * 2)) disk.io_activity.pop_front();
} }
} else { } else {
Logger::debug("Error in Mem::collect() : when opening " + string{disk.stat}); Logger::debug("Error in Mem::collect() : when opening " + string{disk.stat});
} }
diskread.close(); diskread.close();
} }
old_uptime = uptime; old_uptime = uptime;
} }
catch (const std::exception& e) { catch (const std::exception& e) {
Logger::warning("Error in Mem::collect() : " + string{e.what()}); Logger::warning("Error in Mem::collect() : " + string{e.what()});
} }
} }
@ -1276,13 +1276,13 @@ namespace Mem {
bool zfs_collect_pool_total_stats(struct disk_info &disk) { bool zfs_collect_pool_total_stats(struct disk_info &disk) {
ifstream diskread; ifstream diskread;
int64_t bytes_read; int64_t bytes_read;
int64_t bytes_write; int64_t bytes_write;
int64_t io_ticks; int64_t io_ticks;
int64_t bytes_read_total{}; // defaults to 0 int64_t bytes_read_total{}; // defaults to 0
int64_t bytes_write_total{}; // defaults to 0 int64_t bytes_write_total{}; // defaults to 0
int64_t io_ticks_total{}; // defaults to 0 int64_t io_ticks_total{}; // defaults to 0
int64_t objects_read{}; // defaults to 0 int64_t objects_read{}; // defaults to 0
// looking through all files that start with 'objset' // looking through all files that start with 'objset'
for (const auto& file: fs::directory_iterator(disk.stat)) { for (const auto& file: fs::directory_iterator(disk.stat)) {
@ -1358,11 +1358,11 @@ namespace Net {
net_info empty_net = {}; net_info empty_net = {};
vector<string> interfaces; vector<string> interfaces;
string selected_iface; string selected_iface;
int errors{}; // defaults to 0 int errors{}; // defaults to 0
unordered_flat_map<string, uint64_t> graph_max = { {"download", {}}, {"upload", {}} }; unordered_flat_map<string, uint64_t> graph_max = { {"download", {}}, {"upload", {}} };
unordered_flat_map<string, array<int, 2>> max_count = { {"download", {}}, {"upload", {}} }; unordered_flat_map<string, array<int, 2>> max_count = { {"download", {}}, {"upload", {}} };
bool rescale{true}; bool rescale{true};
uint64_t timestamp{}; // defaults to 0 uint64_t timestamp{}; // defaults to 0
//* RAII wrapper for getifaddrs //* RAII wrapper for getifaddrs
class getifaddr_wrapper { class getifaddr_wrapper {
@ -1374,12 +1374,12 @@ namespace Net {
auto operator()() -> struct ifaddrs* { return ifaddr; } auto operator()() -> struct ifaddrs* { return ifaddr; }
}; };
auto collect(bool no_update) -> net_info& { auto collect(bool no_update) -> net_info& {
if (Runner::stopping) return empty_net; if (Runner::stopping) return empty_net;
auto& net = current_net; auto& net = current_net;
auto& config_iface = Config::getS("net_iface"); auto& config_iface = Config::getS("net_iface");
auto net_sync = Config::getB("net_sync"); auto net_sync = Config::getB("net_sync");
auto net_auto = Config::getB("net_auto"); auto net_auto = Config::getB("net_auto");
auto new_timestamp = time_ms(); auto new_timestamp = time_ms();
if (not no_update and errors < 3) { if (not no_update and errors < 3) {
@ -1451,7 +1451,7 @@ namespace Net {
auto& saved_stat = net.at(iface).stat.at(dir); auto& saved_stat = net.at(iface).stat.at(dir);
auto& bandwidth = net.at(iface).bandwidth.at(dir); auto& bandwidth = net.at(iface).bandwidth.at(dir);
uint64_t val{}; // defaults to 0 uint64_t val{}; // defaults to 0
try { val = (uint64_t)stoull(readfile(sys_file, "0")); } try { val = (uint64_t)stoull(readfile(sys_file, "0")); }
catch (const std::invalid_argument&) {} catch (const std::invalid_argument&) {}
catch (const std::out_of_range&) {} catch (const std::out_of_range&) {}
@ -1572,15 +1572,15 @@ namespace Proc {
unordered_flat_map<string, string> uid_user; unordered_flat_map<string, string> uid_user;
string current_sort; string current_sort;
string current_filter; string current_filter;
bool current_rev{}; // defaults to false bool current_rev{}; // defaults to false
fs::file_time_type passwd_time; fs::file_time_type passwd_time;
uint64_t cputimes; uint64_t cputimes;
int collapse = -1, expand = -1; int collapse = -1, expand = -1;
uint64_t old_cputimes{}; // defaults to 0 uint64_t old_cputimes{}; // defaults to 0
atomic<int> numpids{}; // defaults to 0 atomic<int> numpids{}; // defaults to 0
int filter_found{}; // defaults to 0 int filter_found{}; // defaults to 0
detail_container detailed; detail_container detailed;
constexpr size_t KTHREADD = 2; constexpr size_t KTHREADD = 2;
@ -1684,19 +1684,19 @@ namespace Proc {
} }
//* Collects and sorts process information from /proc //* Collects and sorts process information from /proc
auto collect(bool no_update) -> vector<proc_info>& { auto collect(bool no_update) -> vector<proc_info>& {
if (Runner::stopping) return current_procs; if (Runner::stopping) return current_procs;
const auto& sorting = Config::getS("proc_sorting"); const auto& sorting = Config::getS("proc_sorting");
auto reverse = Config::getB("proc_reversed"); auto reverse = Config::getB("proc_reversed");
const auto& filter = Config::getS("proc_filter"); const auto& filter = Config::getS("proc_filter");
auto per_core = Config::getB("proc_per_core"); auto per_core = Config::getB("proc_per_core");
auto should_filter_kernel = Config::getB("proc_filter_kernel"); auto should_filter_kernel = Config::getB("proc_filter_kernel");
auto tree = Config::getB("proc_tree"); auto tree = Config::getB("proc_tree");
auto show_detailed = Config::getB("show_detailed"); auto show_detailed = Config::getB("show_detailed");
const size_t detailed_pid = Config::getI("detailed_pid"); const size_t detailed_pid = Config::getI("detailed_pid");
bool should_filter = current_filter != filter; bool should_filter = current_filter != filter;
if (should_filter) current_filter = filter; if (should_filter) current_filter = filter;
bool sorted_change = (sorting != current_sort or reverse != current_rev or should_filter); bool sorted_change = (sorting != current_sort or reverse != current_rev or should_filter);
if (sorted_change) { if (sorted_change) {
current_sort = sorting; current_sort = sorting;
current_rev = reverse; current_rev = reverse;
@ -1712,7 +1712,7 @@ namespace Proc {
const int cmult = (per_core) ? Shared::coreCount : 1; const int cmult = (per_core) ? Shared::coreCount : 1;
bool got_detailed = false; bool got_detailed = false;
static size_t proc_clear_count{}; // defaults to 0 static size_t proc_clear_count{}; // defaults to 0
//* Use pids from last update if only changing filter, sorting or tree options //* Use pids from last update if only changing filter, sorting or tree options
if (no_update and not current_procs.empty()) { if (no_update and not current_procs.empty()) {
@ -1787,7 +1787,7 @@ namespace Proc {
//? Check if pid already exists in current_procs //? Check if pid already exists in current_procs
auto find_old = rng::find(current_procs, pid, &proc_info::pid); auto find_old = rng::find(current_procs, pid, &proc_info::pid);
bool no_cache{}; // defaults to false bool no_cache{}; // defaults to false
if (find_old == current_procs.end()) { if (find_old == current_procs.end()) {
current_procs.push_back({pid}); current_procs.push_back({pid});
find_old = current_procs.end() - 1; find_old = current_procs.end() - 1;
@ -2070,6 +2070,6 @@ namespace Tools {
catch (const std::invalid_argument&) {} catch (const std::invalid_argument&) {}
catch (const std::out_of_range&) {} catch (const std::out_of_range&) {}
} }
throw std::runtime_error("Failed get uptime from from " + string{Shared::procPath} + "/uptime"); throw std::runtime_error("Failed get uptime from from " + string{Shared::procPath} + "/uptime");
} }
} }

View File

@ -4,7 +4,7 @@
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
@ -194,12 +194,12 @@ namespace Cpu {
const array<string, 10> time_names = {"user", "nice", "system", "idle"}; const array<string, 10> time_names = {"user", "nice", "system", "idle"};
unordered_flat_map<string, long long> cpu_old = { unordered_flat_map<string, long long> cpu_old = {
{"totals", 0}, {"totals", 0},
{"idles", 0}, {"idles", 0},
{"user", 0}, {"user", 0},
{"nice", 0}, {"nice", 0},
{"system", 0}, {"system", 0},
{"idle", 0} {"idle", 0}
}; };
string get_cpuName() { string get_cpuName() {
@ -443,7 +443,7 @@ namespace Cpu {
return {percent, seconds, status}; return {percent, seconds, status};
} }
auto collect(bool no_update) -> cpu_info & { auto collect(bool no_update) -> cpu_info & {
if (Runner::stopping or (no_update and not current_cpu.cpu_percent.at("total").empty())) if (Runner::stopping or (no_update and not current_cpu.cpu_percent.at("total").empty()))
return current_cpu; return current_cpu;
auto &cpu = current_cpu; auto &cpu = current_cpu;
@ -604,7 +604,7 @@ namespace Mem {
} }
/* Get the list of all drive objects. */ /* Get the list of all drive objects. */
if (IOServiceGetMatchingServices(libtop_master_port, if (IOServiceGetMatchingServices(libtop_master_port,
IOServiceMatching("IOMediaBSDClient"), &drive_list)) { IOServiceMatching("IOMediaBSDClient"), &drive_list)) {
Logger::error("Error in IOServiceGetMatchingServices()"); Logger::error("Error in IOServiceGetMatchingServices()");
return; return;
} }
@ -664,15 +664,15 @@ namespace Mem {
} }
} }
auto collect(bool no_update) -> mem_info & { auto collect(bool no_update) -> mem_info & {
if (Runner::stopping or (no_update and not current_mem.percent.at("used").empty())) if (Runner::stopping or (no_update and not current_mem.percent.at("used").empty()))
return current_mem; return current_mem;
auto show_swap = Config::getB("show_swap"); auto show_swap = Config::getB("show_swap");
auto show_disks = Config::getB("show_disks"); auto show_disks = Config::getB("show_disks");
auto swap_disk = Config::getB("swap_disk"); auto swap_disk = Config::getB("swap_disk");
auto &mem = current_mem; auto &mem = current_mem;
static bool snapped = (getenv("BTOP_SNAPPED") != NULL); static bool snapped = (getenv("BTOP_SNAPPED") != NULL);
vm_statistics64 p; vm_statistics64 p;
mach_msg_type_number_t info_size = HOST_VM_INFO64_COUNT; mach_msg_type_number_t info_size = HOST_VM_INFO64_COUNT;
@ -714,7 +714,7 @@ namespace Mem {
double uptime = system_uptime(); double uptime = system_uptime();
auto &disks_filter = Config::getS("disks_filter"); auto &disks_filter = Config::getS("disks_filter");
bool filter_exclude = false; bool filter_exclude = false;
// auto only_physical = Config::getB("only_physical"); // auto only_physical = Config::getB("only_physical");
auto &disks = mem.disks; auto &disks = mem.disks;
vector<string> filter; vector<string> filter;
if (not disks_filter.empty()) { if (not disks_filter.empty()) {
@ -844,11 +844,11 @@ namespace Net {
auto operator()() -> struct ifaddrs * { return ifaddr; } auto operator()() -> struct ifaddrs * { return ifaddr; }
}; };
auto collect(bool no_update) -> net_info & { auto collect(bool no_update) -> net_info & {
auto &net = current_net; auto &net = current_net;
auto &config_iface = Config::getS("net_iface"); auto &config_iface = Config::getS("net_iface");
auto net_sync = Config::getB("net_sync"); auto net_sync = Config::getB("net_sync");
auto net_auto = Config::getB("net_auto"); auto net_auto = Config::getB("net_auto");
auto new_timestamp = time_ms(); auto new_timestamp = time_ms();
if (not no_update and errors < 3) { if (not no_update and errors < 3) {
@ -1001,7 +1001,7 @@ namespace Net {
auto sorted_interfaces = interfaces; auto sorted_interfaces = interfaces;
rng::sort(sorted_interfaces, [&](const auto &a, const auto &b) { rng::sort(sorted_interfaces, [&](const auto &a, const auto &b) {
return cmp_greater(net.at(a).stat["download"].total + net.at(a).stat["upload"].total, return cmp_greater(net.at(a).stat["download"].total + net.at(a).stat["upload"].total,
net.at(b).stat["download"].total + net.at(b).stat["upload"].total); net.at(b).stat["download"].total + net.at(b).stat["upload"].total);
}); });
selected_iface.clear(); selected_iface.clear();
//? Try to set to a connected interface //? Try to set to a connected interface
@ -1024,8 +1024,8 @@ namespace Net {
for (const auto &sel : {0, 1}) { for (const auto &sel : {0, 1}) {
if (rescale or max_count[dir][sel] >= 5) { if (rescale or max_count[dir][sel] >= 5) {
const long long avg_speed = (net[selected_iface].bandwidth[dir].size() > 5 const long long avg_speed = (net[selected_iface].bandwidth[dir].size() > 5
? std::accumulate(net.at(selected_iface).bandwidth.at(dir).rbegin(), net.at(selected_iface).bandwidth.at(dir).rbegin() + 5, 0ll) / 5 ? std::accumulate(net.at(selected_iface).bandwidth.at(dir).rbegin(), net.at(selected_iface).bandwidth.at(dir).rbegin() + 5, 0ll) / 5
: net[selected_iface].stat[dir].speed); : net[selected_iface].stat[dir].speed);
graph_max[dir] = max(uint64_t(avg_speed * (sel == 0 ? 1.3 : 3.0)), (uint64_t)10 << 10); graph_max[dir] = max(uint64_t(avg_speed * (sel == 0 ? 1.3 : 3.0)), (uint64_t)10 << 10);
max_count[dir][0] = max_count[dir][1] = 0; max_count[dir][0] = max_count[dir][1] = 0;
redraw = true; redraw = true;
@ -1126,17 +1126,17 @@ namespace Proc {
} }
//* Collects and sorts process information from /proc //* Collects and sorts process information from /proc
auto collect(bool no_update) -> vector<proc_info> & { auto collect(bool no_update) -> vector<proc_info> & {
const auto &sorting = Config::getS("proc_sorting"); const auto &sorting = Config::getS("proc_sorting");
auto reverse = Config::getB("proc_reversed"); auto reverse = Config::getB("proc_reversed");
const auto &filter = Config::getS("proc_filter"); const auto &filter = Config::getS("proc_filter");
auto per_core = Config::getB("proc_per_core"); auto per_core = Config::getB("proc_per_core");
auto tree = Config::getB("proc_tree"); auto tree = Config::getB("proc_tree");
auto show_detailed = Config::getB("show_detailed"); auto show_detailed = Config::getB("show_detailed");
const size_t detailed_pid = Config::getI("detailed_pid"); const size_t detailed_pid = Config::getI("detailed_pid");
bool should_filter = current_filter != filter; bool should_filter = current_filter != filter;
if (should_filter) current_filter = filter; if (should_filter) current_filter = filter;
bool sorted_change = (sorting != current_sort or reverse != current_rev or should_filter); bool sorted_change = (sorting != current_sort or reverse != current_rev or should_filter);
if (sorted_change) { if (sorted_change) {
current_sort = sorting; current_sort = sorting;
current_rev = reverse; current_rev = reverse;

View File

@ -4,7 +4,7 @@
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
@ -74,8 +74,8 @@ double getValue(IOHIDServiceClientRef sc) {
long long Cpu::ThermalSensors::getSensors() { long long Cpu::ThermalSensors::getSensors() {
CFDictionaryRef thermalSensors = matching(0xff00, 5); // 65280_10 = FF00_16 CFDictionaryRef thermalSensors = matching(0xff00, 5); // 65280_10 = FF00_16
// thermalSensors's PrimaryUsagePage should be 0xff00 for M1 chip, instead of 0xff05 // thermalSensors's PrimaryUsagePage should be 0xff00 for M1 chip, instead of 0xff05
// can be checked by ioreg -lfx // can be checked by ioreg -lfx
IOHIDEventSystemClientRef system = IOHIDEventSystemClientCreate(kCFAllocatorDefault); IOHIDEventSystemClientRef system = IOHIDEventSystemClientCreate(kCFAllocatorDefault);
IOHIDEventSystemClientSetMatching(system, thermalSensors); IOHIDEventSystemClientSetMatching(system, thermalSensors);
CFArrayRef matchingsrvs = IOHIDEventSystemClientCopyServices(system); CFArrayRef matchingsrvs = IOHIDEventSystemClientCopyServices(system);

View File

@ -4,7 +4,7 @@
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,

View File

@ -4,7 +4,7 @@
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
@ -35,10 +35,10 @@ static UInt32 _strtoul(char *str, int size, int base) {
static void _ultostr(char *str, UInt32 val) { static void _ultostr(char *str, UInt32 val) {
str[0] = '\0'; str[0] = '\0';
sprintf(str, "%c%c%c%c", sprintf(str, "%c%c%c%c",
(unsigned int)val >> 24, (unsigned int)val >> 24,
(unsigned int)val >> 16, (unsigned int)val >> 16,
(unsigned int)val >> 8, (unsigned int)val >> 8,
(unsigned int)val); (unsigned int)val);
} }
namespace Cpu { namespace Cpu {
@ -65,7 +65,7 @@ namespace Cpu {
} }
} }
SMCConnection::~SMCConnection() { SMCConnection::~SMCConnection() {
IOServiceClose(conn); IOServiceClose(conn);
} }
long long SMCConnection::getSMCTemp(char *key) { long long SMCConnection::getSMCTemp(char *key) {
@ -141,10 +141,10 @@ namespace Cpu {
structureOutputSize = sizeof(SMCKeyData_t); structureOutputSize = sizeof(SMCKeyData_t);
return IOConnectCallStructMethod(conn, index, return IOConnectCallStructMethod(conn, index,
// inputStructure // inputStructure
inputStructure, structureInputSize, inputStructure, structureInputSize,
// ouputStructure // ouputStructure
outputStructure, &structureOutputSize); outputStructure, &structureOutputSize);
} }
} // namespace Cpu } // namespace Cpu

View File

@ -4,7 +4,7 @@
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
@ -104,7 +104,7 @@ namespace Cpu {
long long getTemp(int core); long long getTemp(int core);
private: private:
kern_return_t SMCReadKey(UInt32Char_t key, SMCVal_t *val); kern_return_t SMCReadKey(UInt32Char_t key, SMCVal_t *val);
long long getSMCTemp(char *key); long long getSMCTemp(char *key);
kern_return_t SMCCall(int index, SMCKeyData_t *inputStructure, SMCKeyData_t *outputStructure); kern_return_t SMCCall(int index, SMCKeyData_t *inputStructure, SMCKeyData_t *outputStructure);