From bc9b803189872c0f271d22a5f25c8fd6294cc152 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=A3=CF=84=CE=AD=CF=86=CE=B1=CE=BD=CE=BF=CF=82?= Date: Sun, 2 Oct 2022 15:40:08 +0300 Subject: [PATCH 1/5] Ignore files created by Qt Creator --- .gitignore | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index fc1994b..25ee477 100644 --- a/.gitignore +++ b/.gitignore @@ -53,4 +53,14 @@ btop #do not ignore .github directory -!.github \ No newline at end of file +!.github + +# Ignore files created by Qt Creator +*.config +*.creator +*.creator.user +*.creator.user.* +*.cflags +*.cxxflags +*.files +*.includes From 478a44cc5723beadc11ff362b745b0ff1df704f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=A3=CF=84=CE=AD=CF=86=CE=B1=CE=BD=CE=BF=CF=82?= Date: Sun, 2 Oct 2022 18:52:18 +0300 Subject: [PATCH 2/5] Clean up btop_tools.{hpp,cpp} files --- src/btop_tools.cpp | 41 ++++++++++++++++++++++++++++------------- src/btop_tools.hpp | 36 +++++++++++++++++++++++------------- 2 files changed, 51 insertions(+), 26 deletions(-) diff --git a/src/btop_tools.cpp b/src/btop_tools.cpp index 301e554..dd09696 100644 --- a/src/btop_tools.cpp +++ b/src/btop_tools.cpp @@ -35,7 +35,15 @@ tab-size = 4 #include #include -using std::string_view, std::max, std::floor, std::to_string, std::cin, std::cout, std::flush, robin_hood::unordered_flat_map; +using std::cin; +using std::cout; +using std::floor; +using std::flush; +using std::max; +using std::string_view; +using std::to_string; +using robin_hood::unordered_flat_map; + namespace fs = std::filesystem; namespace rng = std::ranges; @@ -44,9 +52,9 @@ namespace rng = std::ranges; //* Collection of escape codes and functions for terminal manipulation namespace Term { - atomic initialized = false; - atomic width = 0; - atomic height = 0; + atomic initialized{}; // defaults to false + atomic width{}; // defaults to 0 + atomic height{}; // defaults to 0 string current_tty; namespace { @@ -110,7 +118,7 @@ namespace Term { initialized = (bool)isatty(STDIN_FILENO); if (initialized) { tcgetattr(STDIN_FILENO, &initial_settings); - current_tty = (ttyname(STDIN_FILENO) != NULL ? (string)ttyname(STDIN_FILENO) : "unknown"); + current_tty = (ttyname(STDIN_FILENO) != NULL ? static_cast(ttyname(STDIN_FILENO)) : "unknown"); //? Disable stream sync cin.sync_with_stdio(false); @@ -253,14 +261,18 @@ namespace Tools { string ltrim(const string& str, const string& t_str) { string_view str_v = str; - while (str_v.starts_with(t_str)) str_v.remove_prefix(t_str.size()); - return (string)str_v; + while (str_v.starts_with(t_str)) + str_v.remove_prefix(t_str.size()); + + return string{str_v}; } string rtrim(const string& str, const string& t_str) { string_view str_v = str; - while (str_v.ends_with(t_str)) str_v.remove_suffix(t_str.size()); - return (string)str_v; + while (str_v.ends_with(t_str)) + str_v.remove_suffix(t_str.size()); + + return string{str_v}; } auto ssplit(const string& str, const char& delim) -> vector { @@ -318,7 +330,7 @@ namespace Tools { newstr.append(Mv::r(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) { @@ -447,7 +459,7 @@ namespace Tools { string hostname() { char host[HOST_NAME_MAX]; gethostname(host, HOST_NAME_MAX); - return (string)host; + return string{host}; } string username() { @@ -497,14 +509,17 @@ namespace Logger { } if (not ec) { std::ofstream lwrite(logfile, std::ios::app); - if (first) { first = false; lwrite << "\n" << strf_time(tdf) << "===> btop++ v." << Global::Version << "\n";} + if (first) { + first = false; + lwrite << "\n" << strf_time(tdf) << "===> btop++ v." << Global::Version << "\n"; + } lwrite << strf_time(tdf) << log_levels.at(level) << ": " << msg << "\n"; } else logfile.clear(); } catch (const std::exception& e) { 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()}); } } } diff --git a/src/btop_tools.hpp b/src/btop_tools.hpp index 862981a..c4d4279 100644 --- a/src/btop_tools.hpp +++ b/src/btop_tools.hpp @@ -18,16 +18,17 @@ tab-size = 4 #pragma once -#include -#include +#include // for std::ranges::count_if #include #include -#include +#include #include #include -#include +#include +#include #include #include +#include #include #include #ifndef HOST_NAME_MAX @@ -38,7 +39,12 @@ tab-size = 4 #endif #endif -using std::string, std::vector, std::atomic, std::to_string, std::tuple, std::array; +using std::array; +using std::atomic; +using std::string; +using std::to_string; +using std::tuple; +using std::vector; //? ------------------------------------------------- NAMESPACES ------------------------------------------------------ @@ -80,19 +86,19 @@ namespace Fx { //* Collection of escape codes and functions for cursor manipulation namespace Mv { //* Move cursor to , - inline string to(const int& line, const 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 columns - inline string r(const int& x) { return Fx::e + to_string(x) + 'C'; } + inline string r(int x) { return Fx::e + to_string(x) + 'C'; } //* Move cursor left columns - inline string l(const 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 - inline string u(const 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 - inline string d(const int& x) { return Fx::e + to_string(x) + 'B'; } + inline string d(int x) { return Fx::e + to_string(x) + 'B'; } //* Save cursor position const string save = Fx::e + "s"; @@ -254,10 +260,14 @@ namespace Tools { auto ssplit(const string& str, const char& delim = ' ') -> vector; //* Put current thread to sleep for milliseconds - inline void sleep_ms(const size_t& ms) { std::this_thread::sleep_for(std::chrono::milliseconds(ms)); } + inline void sleep_ms(const size_t& ms) { + std::this_thread::sleep_for(std::chrono::milliseconds(ms)); + } //* Put current thread to sleep for microseconds - inline void sleep_micros(const size_t& micros) { std::this_thread::sleep_for(std::chrono::microseconds(micros)); } + inline void sleep_micros(const size_t& micros) { + std::this_thread::sleep_for(std::chrono::microseconds(micros)); + } //* Left justify string if is greater than length, limit return size to by default string ljust(string str, const size_t x, const bool utf=false, const bool wide=false, const bool limit=true); @@ -308,7 +318,7 @@ namespace Tools { //* Sets atomic to true on construct, sets to false on destruct class atomic_lock { atomic& atom; - bool not_true = false; + bool not_true{}; // defaults to false public: atomic_lock(atomic& atom, bool wait=false); ~atomic_lock(); From dfa2a9b9209b20381e1a2a102ec296caf1765978 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=A3=CF=84=CE=AD=CF=86=CE=B1=CE=BD=CE=BF=CF=82?= Date: Sun, 2 Oct 2022 19:09:19 +0300 Subject: [PATCH 3/5] Further improvements --- src/btop_tools.cpp | 33 +++++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/src/btop_tools.cpp b/src/btop_tools.cpp index dd09696..ab93f00 100644 --- a/src/btop_tools.cpp +++ b/src/btop_tools.cpp @@ -44,6 +44,8 @@ using std::string_view; using std::to_string; using robin_hood::unordered_flat_map; +using namespace std::literals; // to use operator""s + namespace fs = std::filesystem; namespace rng = std::ranges; @@ -348,10 +350,33 @@ namespace Tools { string out; const size_t mult = (bit) ? 8 : 1; const bool mega = Config::getB("base_10_sizes"); - static const array mebiUnits_bit = {"bit", "Kib", "Mib", "Gib", "Tib", "Pib", "Eib", "Zib", "Yib", "Bib", "GEb"}; - static const array mebiUnits_byte = {"Byte", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB", "BiB", "GEB"}; - static const array megaUnits_bit = {"bit", "Kb", "Mb", "Gb", "Tb", "Pb", "Eb", "Zb", "Yb", "Bb", "Gb"}; - static const array megaUnits_byte = {"Byte", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB", "BB", "GB"}; + + // taking advantage of type deduction for array creation (since C++17) + // combined with string literals (operator""s) + static const array mebiUnits_bit { + "bit"s, "Kib"s, "Mib"s, + "Gib"s, "Tib"s, "Pib"s, + "Eib"s, "Zib"s, "Yib"s, + "Bib"s, "GEb"s + }; + static const array mebiUnits_byte { + "Byte"s, "KiB"s, "MiB"s, + "GiB"s, "TiB"s, "PiB"s, + "EiB"s, "ZiB"s, "YiB"s, + "BiB"s, "GEB"s + }; + static const array megaUnits_bit { + "bit"s, "Kb"s, "Mb"s, + "Gb"s, "Tb"s, "Pb"s, + "Eb"s, "Zb"s, "Yb"s, + "Bb"s, "Gb"s + }; + static const array megaUnits_byte { + "Byte"s, "KB"s, "MB"s, + "GB"s, "TB"s, "PB"s, + "EB"s, "ZB"s, "YB"s, + "BB"s, "GB"s + }; const auto& units = (bit) ? ( mega ? megaUnits_bit : mebiUnits_bit) : ( mega ? megaUnits_byte : mebiUnits_byte); value *= 100 * mult; From eda68730718e5fcee5545ac30a114f3540eea53e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=A3=CF=84=CE=AD=CF=86=CE=B1=CE=BD=CE=BF=CF=82?= Date: Sun, 2 Oct 2022 21:52:27 +0300 Subject: [PATCH 4/5] Further 'cleanup' --- src/btop_shared.cpp | 8 ++-- src/btop_shared.hpp | 95 +++++++++++++++++++++++++++++---------------- src/btop_theme.cpp | 62 +++++++++++++++++------------ src/btop_theme.hpp | 12 ++++-- 4 files changed, 112 insertions(+), 65 deletions(-) diff --git a/src/btop_shared.cpp b/src/btop_shared.cpp index 94806d5..0e597a1 100644 --- a/src/btop_shared.cpp +++ b/src/btop_shared.cpp @@ -21,7 +21,6 @@ tab-size = 4 #include #include -using std::string_literals::operator""s; namespace rng = std::ranges; using namespace Tools; @@ -99,7 +98,8 @@ namespace Proc { } } - void _tree_gen(proc_info& cur_proc, vector& in_procs, vector& out_procs, int cur_depth, const bool collapsed, const string& filter, bool found, const bool no_update, const bool should_filter) { + void _tree_gen(proc_info& cur_proc, vector& in_procs, vector& out_procs, + int cur_depth, const bool collapsed, const string& filter, bool found, const bool no_update, const bool should_filter) { auto cur_pos = out_procs.size(); bool filtering = false; @@ -132,7 +132,7 @@ namespace Proc { 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(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 { @@ -170,4 +170,4 @@ namespace Proc { } -} \ No newline at end of file +} diff --git a/src/btop_shared.hpp b/src/btop_shared.hpp index 1eb81b6..2fed8a7 100644 --- a/src/btop_shared.hpp +++ b/src/btop_shared.hpp @@ -18,18 +18,26 @@ tab-size = 4 #pragma once -#include -#include -#include +#include #include #include -#include -#include -#include +#include +#include #include +#include +#include +#include #include -using std::string, std::vector, std::deque, robin_hood::unordered_flat_map, std::atomic, std::array, std::tuple; +using robin_hood::unordered_flat_map; +using std::array; +using std::atomic; +using std::deque; +using std::string; +using std::tuple; +using std::vector; + +using namespace std::literals; // for operator""s void term_resize(bool force=false); void banner_gen(); @@ -124,17 +132,21 @@ namespace Mem { extern string box; extern int x, y, width, height, min_width, min_height; extern bool has_swap, shown, redraw; - const array mem_names = {"used", "available", "cached", "free"}; - const array swap_names = {"swap_used", "swap_free"}; + const array mem_names { "used"s, "available"s, "cached"s, "free"s }; + const array swap_names { "swap_used"s, "swap_free"s }; extern int disk_ios; struct disk_info { std::filesystem::path dev; string name; - string fstype = ""; - std::filesystem::path stat = ""; - int64_t total = 0, used = 0, free = 0; - int used_percent = 0, free_percent = 0; + string fstype{}; // defaults to "" + std::filesystem::path stat{}; // defaults to "" + int64_t total{}; // defaults to 0 + int64_t used{}; // defaults to 0 + int64_t free{}; // defaults to 0 + int used_percent{}; // defaults to 0 + int free_percent{}; // defaults to 0 + array old_io = {0, 0, 0}; deque io_read = {}; deque io_write = {}; @@ -173,14 +185,20 @@ namespace Net { extern unordered_flat_map graph_max; struct net_stat { - uint64_t speed = 0, top = 0, total = 0, last = 0, offset = 0, rollover = 0; + uint64_t speed{}; // defaults to 0 + uint64_t top{}; // defaults to 0 + uint64_t total{}; // defaults to 0 + uint64_t last{}; // defaults to 0 + uint64_t offset{}; // defaults to 0 + uint64_t rollover{}; // defaults to 0 }; struct net_info { unordered_flat_map> bandwidth = { {"download", {}}, {"upload", {}} }; unordered_flat_map stat = { {"download", {}}, {"upload", {}} }; - string ipv4 = "", ipv6 = ""; - bool connected = false; + string ipv4{}; // defaults to "" + string ipv6{}; // defaults to "" + bool connected{}; // defaults to false }; extern unordered_flat_map current_net; @@ -232,25 +250,32 @@ namespace Proc { //* Container for process information struct proc_info { - size_t pid = 0; - string name = "", cmd = ""; - string short_cmd = ""; - size_t threads = 0; - int name_offset = 0; - string user = ""; - uint64_t mem = 0; - double cpu_p = 0.0, cpu_c = 0.0; + size_t pid{}; // defaults to 0 + string name{}; // defaults to "" + string cmd{}; // defaults to "" + string short_cmd{}; // defaults to "" + size_t threads{}; // defaults to 0 + int name_offset{}; // defaults to 0 + string user{}; // defaults to "" + uint64_t mem{}; // defaults to 0 + double cpu_p{}; // defaults to = 0.0 + double cpu_c{}; // defaults to = 0.0 char state = '0'; - uint64_t p_nice = 0, ppid = 0, cpu_s = 0, cpu_t = 0; - string prefix = ""; - size_t depth = 0, tree_index = 0; - bool collapsed = false, filtered = false; + uint64_t p_nice{}; // defaults to 0 + uint64_t ppid{}; // defaults to 0 + uint64_t cpu_s{}; // defaults to 0 + uint64_t cpu_t{}; // defaults to 0 + string prefix{}; // defaults to "" + size_t depth{}; // defaults to 0 + size_t tree_index{}; // defaults to 0 + bool collapsed{}; // defaults to false + bool filtered{}; // defaults to false }; //* Container for process info box struct detail_container { - size_t last_pid = 0; - bool skip_smaps = false; + size_t last_pid{}; // defaults to 0 + bool skip_smaps{}; // defaults to false proc_info entry; string elapsed, parent, status, io_read, io_write, memory; long long first_mem = -1; @@ -276,11 +301,15 @@ namespace Proc { }; //* Sort vector of proc_info's - void proc_sorter(vector& proc_vec, const string& sorting, const bool reverse, const bool tree = false); + void proc_sorter(vector& proc_vec, const string& sorting, + const bool reverse, const bool tree = false); //* Recursive sort of process tree - void tree_sort(vector& proc_vec, const string& sorting, const bool reverse, int& c_index, const int index_max, const bool collapsed = false); + void tree_sort(vector& proc_vec, const string& sorting, + const bool reverse, int& c_index, const int index_max, const bool collapsed = false); //* Generate process tree list - void _tree_gen(proc_info& cur_proc, vector& in_procs, vector& out_procs, int cur_depth, const bool collapsed, const string& filter, bool found=false, const bool no_update=false, const bool should_filter=false); + void _tree_gen(proc_info& cur_proc, vector& in_procs, vector& out_procs, + int cur_depth, const bool collapsed, const string& filter, + bool found=false, const bool no_update=false, const bool should_filter=false); } diff --git a/src/btop_theme.cpp b/src/btop_theme.cpp index 116e78b..4a73002 100644 --- a/src/btop_theme.cpp +++ b/src/btop_theme.cpp @@ -17,9 +17,7 @@ tab-size = 4 */ #include -#include #include -#include #include #include @@ -27,9 +25,19 @@ tab-size = 4 #include #include -using std::round, std::vector, std::stoi, std::views::iota, - std::clamp, std::max, std::min, std::ceil, std::to_string; +using std::ceil; +using std::clamp; +using std::max; +using std::min; +using std::quoted; +using std::round; +using std::stoi; +using std::to_string; +using std::vector; +using std::views::iota; + using namespace Tools; + namespace rng = std::ranges; namespace fs = std::filesystem; @@ -152,10 +160,12 @@ namespace Theme { string hex_to_color(string hexa, const bool& t_to_256, const string& depth) { if (hexa.size() > 1) { hexa.erase(0, 1); - for (auto& c : hexa) if (not isxdigit(c)) { - Logger::error("Invalid hex value: " + hexa); - return ""; - } + for (auto& c : hexa) { + if (not isxdigit(c)) { + Logger::error("Invalid hex value: " + hexa); + return ""; + } + } string pre = Fx::e + (depth == "fg" ? "38" : "48") + ";" + (t_to_256 ? "5;" : "2;"); if (hexa.size() == 2) { @@ -200,14 +210,17 @@ namespace Theme { array hex_to_dec(string hexa) { if (hexa.size() > 1) { hexa.erase(0, 1); - for (auto& c : hexa) if (not isxdigit(c)) return array{-1, -1, -1}; + for (auto& c : hexa) { + if (not isxdigit(c)) + return array{-1, -1, -1}; + } if (hexa.size() == 2) { 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) { - return array{ + return array{ stoi(hexa.substr(0, 2), nullptr, 16), stoi(hexa.substr(2, 2), nullptr, 16), stoi(hexa.substr(4, 2), nullptr, 16) @@ -247,11 +260,11 @@ namespace Theme { } else if (not source.at(name).empty()) { t_rgb = ssplit(source.at(name)); - if (t_rgb.size() != 3) - Logger::error("Invalid RGB decimal value: \"" + source.at(name) + "\""); - else { + if (t_rgb.size() != 3) { + Logger::error("Invalid RGB decimal value: \"" + source.at(name) + "\""); + } else { 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])}; } } @@ -287,12 +300,13 @@ namespace Theme { const bool& t_to_256 = Config::getB("lowcolor"); //? Insert values for processes greyscale gradient and processes color gradient - rgbs.insert({ { "proc_start", rgbs["main_fg"] }, - { "proc_mid", {-1, -1, -1} }, - { "proc_end", rgbs["inactive_fg"] }, - { "proc_color_start", rgbs["inactive_fg"] }, - { "proc_color_mid", {-1, -1, -1} }, - { "proc_color_end", rgbs["process_start"] }, + rgbs.insert({ + { "proc_start", rgbs["main_fg"] }, + { "proc_mid", {-1, -1, -1} }, + { "proc_end", rgbs["inactive_fg"] }, + { "proc_color_start", rgbs["inactive_fg"] }, + { "proc_color_mid", {-1, -1, -1} }, + { "proc_color_end", rgbs["process_start"] }, }); for (const auto& [name, source_arr] : rgbs) { @@ -315,10 +329,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 int current_range = (input_colors[1][0] >= 0) ? 50 : 100; - for (const int& rgb : iota(0, 3)) { + for (int rgb : iota(0, 3)) { int start = 0, offset = 0; int end = (current_range == 50) ? 1 : 2; - for (const 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; //? Switch source arrays from start->mid to mid->end at 50 passes if mid is defined @@ -353,7 +367,7 @@ namespace Theme { const string base_name = rtrim(c.first, "_start"); string section = "_start"; int split = colors.at(base_name + "_mid").empty() ? 50 : 33; - for (const int& i : iota(0, 101)) { + for (int i : iota(0, 101)) { gradients[base_name][i] = colors.at(base_name + section); if (i == split) { section = (split == 33) ? "_mid" : "_end"; diff --git a/src/btop_theme.hpp b/src/btop_theme.hpp index fce093a..27c102b 100644 --- a/src/btop_theme.hpp +++ b/src/btop_theme.hpp @@ -18,12 +18,16 @@ tab-size = 4 #pragma once -#include -#include #include #include +#include +#include +#include -using std::string, robin_hood::unordered_flat_map, std::array; +using std::array; +using std::string; +using std::vector; +using robin_hood::unordered_flat_map; namespace Theme { extern std::filesystem::path theme_dir; @@ -63,4 +67,4 @@ namespace Theme { //* Return array of red, green and blue in decimal for color inline const std::array& dec(string name) { return rgbs.at(name); } -} \ No newline at end of file +} From 1fddbc1cd633e22a5eb8f7c7918c4042c942a135 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=A3=CF=84=CE=AD=CF=86=CE=B1=CE=BD=CE=BF=CF=82?= Date: Mon, 3 Oct 2022 00:29:05 +0300 Subject: [PATCH 5/5] Further Cleanup Part 2 --- src/btop.cpp | 66 +++++++++++++++++--------- src/btop_config.cpp | 11 +++-- src/btop_config.hpp | 4 +- src/btop_draw.cpp | 90 ++++++++++++++++++++++++----------- src/btop_draw.hpp | 31 ++++++------ src/btop_input.cpp | 10 ++-- src/btop_input.hpp | 9 +++- src/btop_menu.cpp | 55 ++++++++++++++++------ src/btop_menu.hpp | 12 ++++- src/linux/btop_collect.cpp | 96 ++++++++++++++++++++++++-------------- 10 files changed, 261 insertions(+), 123 deletions(-) diff --git a/src/btop.cpp b/src/btop.cpp index 5aff90c..858d668 100644 --- a/src/btop.cpp +++ b/src/btop.cpp @@ -46,12 +46,23 @@ tab-size = 4 #include #include -using std::string, std::string_view, std::vector, std::atomic, std::endl, std::cout, std::min, std::flush, std::endl; -using std::string_literals::operator""s, std::to_string; +using std::atomic; +using std::cout; +using std::endl; +using std::endl; +using std::flush; +using std::min; +using std::string; +using std::string_view; +using std::to_string; +using std::vector; + namespace fs = std::filesystem; namespace rng = std::ranges; + using namespace Tools; using namespace std::chrono_literals; +using namespace std::literals; namespace Global { const vector> Banner_src = { @@ -80,9 +91,9 @@ namespace Global { string exit_error_msg; atomic thread_exception (false); - bool debuginit = false; - bool debug = false; - bool utf_force = false; + bool debuginit{}; // defaults to false + bool debug{}; // defaults to false + bool utf_force{}; // defaults to false uint64_t start_time; @@ -92,8 +103,8 @@ namespace Global { atomic should_sleep (false); atomic _runner_started (false); - bool arg_tty = false; - bool arg_low_color = false; + bool arg_tty{}; // defaults to false + bool arg_low_color{}; // defaults to false int arg_preset = -1; } @@ -328,8 +339,14 @@ namespace Runner { pthread_mutex_t& pt_mutex; public: int status; - thread_lock(pthread_mutex_t& mtx) : pt_mutex(mtx) { pthread_mutex_init(&pt_mutex, NULL); status = pthread_mutex_lock(&pt_mutex); } - ~thread_lock() { if (status == 0) pthread_mutex_unlock(&pt_mutex); } + thread_lock(pthread_mutex_t& mtx) : pt_mutex(mtx) { + pthread_mutex_init(&pt_mutex, NULL); + status = pthread_mutex_lock(&pt_mutex); + } + ~thread_lock() { + if (status == 0) + pthread_mutex_unlock(&pt_mutex); + } }; //* Wrapper for raising priviliges when using SUID bit @@ -337,16 +354,18 @@ namespace Runner { int status = -1; public: gain_priv() { - if (Global::real_uid != Global::set_uid) this->status = seteuid(Global::set_uid); + if (Global::real_uid != Global::set_uid) + this->status = seteuid(Global::set_uid); } ~gain_priv() { - if (status == 0) status = seteuid(Global::real_uid); + if (status == 0) + status = seteuid(Global::real_uid); } }; string output; string empty_bg; - bool pause_output = false; + bool pause_output{}; // defaults to false sigset_t mask; pthread_t runner_id; pthread_mutex_t mtx; @@ -394,8 +413,7 @@ namespace Runner { } //? ------------------------------- Secondary thread: async launcher and drawing ---------------------------------- - void * _runner(void * _) { - (void)_; + void * _runner(void *) { //? Block some signals in this thread to avoid deadlock from any signal handlers trying to stop this thread sigemptyset(&mask); // sigaddset(&mask, SIGINT); @@ -438,7 +456,9 @@ namespace Runner { //! DEBUG stats if (Global::debug) { - if (debug_bg.empty() or redraw) Runner::debug_bg = Draw::createBox(2, 2, 32, 8, "", true, "debug"); + if (debug_bg.empty() or redraw) + Runner::debug_bg = Draw::createBox(2, 2, 32, 8, "", true, "debug"); + debug_times.clear(); debug_times["total"] = {0, 0}; } @@ -463,7 +483,7 @@ namespace Runner { if (Global::debug) debug_timer("cpu", draw_done); } catch (const std::exception& e) { - throw std::runtime_error("Cpu:: -> " + (string)e.what()); + throw std::runtime_error("Cpu:: -> " + string{e.what()}); } } @@ -483,7 +503,7 @@ namespace Runner { if (Global::debug) debug_timer("mem", draw_done); } catch (const std::exception& e) { - throw std::runtime_error("Mem:: -> " + (string)e.what()); + throw std::runtime_error("Mem:: -> " + string{e.what()}); } } @@ -503,7 +523,7 @@ namespace Runner { if (Global::debug) debug_timer("net", draw_done); } catch (const std::exception& e) { - throw std::runtime_error("Net:: -> " + (string)e.what()); + throw std::runtime_error("Net:: -> " + string{e.what()}); } } @@ -523,12 +543,12 @@ namespace Runner { if (Global::debug) debug_timer("proc", draw_done); } 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) { - 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; Input::interrupt = true; stopping = true; @@ -752,7 +772,7 @@ int main(int argc, char **argv) { } else { string found; - bool set_failure = false; + bool set_failure{}; // defaults to false 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")) { found = std::getenv(loc_env); @@ -848,7 +868,7 @@ int main(int argc, char **argv) { Shared::init(); } 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); } @@ -960,7 +980,7 @@ int main(int argc, char **argv) { } } 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); } diff --git a/src/btop_config.cpp b/src/btop_config.cpp index 479101a..8a38394 100644 --- a/src/btop_config.cpp +++ b/src/btop_config.cpp @@ -26,9 +26,14 @@ tab-size = 4 #include #include -using std::array, std::atomic, std::string_view, std::string_literals::operator""s; +using std::array; +using std::atomic; +using std::string_view; + namespace fs = std::filesystem; namespace rng = std::ranges; + +using namespace std::literals; using namespace Tools; //* Functions and variables for reading and writing the btop config file @@ -378,7 +383,7 @@ namespace Config { return false; } catch (const std::exception& e) { - validError = (string)e.what(); + validError = string{e.what()}; return false; } @@ -498,7 +503,7 @@ namespace Config { boolsTmp.clear(); } 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); } diff --git a/src/btop_config.hpp b/src/btop_config.hpp index 9d2f63c..fc1bd91 100644 --- a/src/btop_config.hpp +++ b/src/btop_config.hpp @@ -23,7 +23,9 @@ tab-size = 4 #include #include -using std::string, std::vector, robin_hood::unordered_flat_map; +using std::string; +using std::vector; +using robin_hood::unordered_flat_map; //* Functions and variables for reading and writing the btop config file namespace Config { diff --git a/src/btop_draw.cpp b/src/btop_draw.cpp index 780c6c1..3c3a41e 100644 --- a/src/btop_draw.cpp +++ b/src/btop_draw.cpp @@ -29,11 +29,21 @@ tab-size = 4 #include #include - -using std::round, std::views::iota, std::string_literals::operator""s, std::clamp, std::array, std::floor, std::max, std::min, - std::to_string, std::cmp_equal, std::cmp_less, std::cmp_greater, std::cmp_less_equal; +using std::array; +using std::clamp; +using std::cmp_equal; +using std::cmp_greater; +using std::cmp_less; +using std::cmp_less_equal; +using std::floor; +using std::max; +using std::min; +using std::round; +using std::to_string; +using std::views::iota; using namespace Tools; +using namespace std::literals; // for operator""s namespace rng = std::ranges; namespace Symbols { @@ -207,7 +217,7 @@ namespace Draw { return first + Fx::bl + "█" + Fx::ubl + uresize(text.substr(pos), limit - ulen(first)); } 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); @@ -217,7 +227,9 @@ namespace Draw { this->text.clear(); } - string createBox(const int x, const int y, const int width, const int height, string line_color, const bool fill, const string title, const string title2, const int num) { + string createBox(const int x, const int y, const int width, + const int height, string line_color, const bool fill, + const string title, const string title2, const int num) { string out; if (line_color.empty()) line_color = Theme::c("div_line"); const auto& tty_mode = Config::getB("tty_mode"); @@ -273,8 +285,9 @@ namespace Draw { {"/host", Tools::hostname()}, {"/uptime", ""} }; - static time_t c_time = 0; - static size_t clock_len = 0; + + static time_t c_time{}; // defaults to 0 + static size_t clock_len{}; // defaults to 0 static string clock_str; if (auto n_time = time(NULL); not force and n_time == c_time) @@ -327,7 +340,8 @@ namespace Draw { //* Meter class ------------------------------------------------------------------------------------------------------------> Meter::Meter() {} - Meter::Meter(const int width, const string& color_gradient, const bool invert) : width(width), color_gradient(color_gradient), invert(invert) {} + Meter::Meter(const int width, const string& color_gradient, const bool invert) + : width(width), color_gradient(color_gradient), invert(invert) {} string Meter::operator()(int value) { if (width < 1) return ""; @@ -419,8 +433,11 @@ namespace Draw { Graph::Graph() {} - Graph::Graph(int width, int height, const string& color_gradient, const deque& data, const string& symbol, bool invert, bool no_zero, long long max_value, long long offset) - : width(width), height(height), color_gradient(color_gradient), invert(invert), no_zero(no_zero), offset(offset) { + Graph::Graph(int width, int height, const string& color_gradient, + const deque& data, const string& symbol, + bool invert, bool no_zero, long long max_value, long long offset) + : width(width), height(height), color_gradient(color_gradient), + invert(invert), no_zero(no_zero), offset(offset) { if (Config::getB("tty_mode") or symbol == "tty") this->symbol = "tty"; else if (symbol != "default") this->symbol = symbol; else this->symbol = Config::getS("graph_symbol"); @@ -500,7 +517,9 @@ namespace Cpu { 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); static int bat_pos = 0, bat_len = 0; - if (cpu.cpu_percent.at("total").empty() or cpu.core_percent.at(0).empty() or (show_temps and cpu.temp.at(0).empty())) return ""; + if (cpu.cpu_percent.at("total").empty() + or cpu.core_percent.at(0).empty() + or (show_temps and cpu.temp.at(0).empty())) return ""; string out; out.reserve(width * height); @@ -527,20 +546,30 @@ namespace Cpu { //? 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}; 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) - graph_lower = Draw::Graph{x + width - b_width - 3, graph_low_height, "cpu", cpu.cpu_percent.at(graph_lo_field), graph_symbol, Config::getB("cpu_invert_lower"), true}; + if (not single_graph) { + graph_lower = Draw::Graph{ + x + width - b_width - 3, + graph_low_height, "cpu", + cpu.cpu_percent.at(graph_lo_field), + graph_symbol, + Config::getB("cpu_invert_lower"), true + }; + } + 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") + Symbols::h_line * (width - b_width - 2) + Symbols::div_right + Mv::to(y + graph_up_height + 1, x + ((width - b_width) / 2) - ((graph_up_field.size() + graph_lo_field.size()) / 2) - 4) + Theme::c("main_fg") + graph_up_field + Mv::r(1) + "▲▼" + Mv::r(1) + graph_lo_field; } + if (b_column_size > 0 or extra_width > 0) { core_graphs.clear(); for (const auto& core_data : cpu.core_percent) { core_graphs.emplace_back(5 * b_column_size + extra_width, 1, "cpu", core_data, graph_symbol); } } + if (show_temps) { temp_graphs.clear(); temp_graphs.emplace_back(5, 1, "temp", cpu.temp.at(0), graph_symbol, false, false, cpu.temp_max, -23); @@ -554,8 +583,8 @@ namespace Cpu { //? Draw battery if enabled and present if (Config::getB("show_battery") and has_battery) { - static int old_percent = 0; - static long old_seconds = 0; + static int old_percent{}; // defaults to = 0 + static long old_seconds{}; // defaults to = 0 static string old_status; static Draw::Meter bat_meter {10, "cpu", true}; static const unordered_flat_map bat_symbols = { @@ -626,7 +655,7 @@ namespace Cpu { } 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 int cx = 0, cy = 1, cc = 0, core_width = (b_column_size == 0 ? 2 : 3); @@ -672,8 +701,6 @@ namespace Cpu { out += Mv::to(b_y + b_height - 2, b_x + cx + 1) + Theme::c("main_fg") + lavg_pre + lavg; } - - redraw = false; return out + Fx::reset; } @@ -771,11 +798,20 @@ namespace Mem { if (io_graph_combined) { deque combined(disk.io_read.size(), 0); rng::transform(disk.io_read, disk.io_write, combined.begin(), std::plus()); - io_graphs[name] = Draw::Graph{disks_width - (io_mode ? 0 : 6), disks_io_h, "available", combined, graph_symbol, false, true, speed}; + io_graphs[name] = Draw::Graph{ + disks_width - (io_mode ? 0 : 6), + disks_io_h, "available", combined, + graph_symbol, false, true, speed}; } else { - io_graphs[name + "_read"] = Draw::Graph{disks_width, half_height, "free", disk.io_read, graph_symbol, false, true, speed}; - io_graphs[name + "_write"] = Draw::Graph{disks_width, disks_io_h - half_height, "used", disk.io_write, graph_symbol, true, true, speed}; + io_graphs[name + "_read"] = Draw::Graph{ + disks_width, half_height, "free", + disk.io_read, graph_symbol, false, + true, speed}; + io_graphs[name + "_write"] = Draw::Graph{ + disks_width, disks_io_h - half_height, + "used", disk.io_write, graph_symbol, + true, true, speed}; } } } @@ -924,8 +960,6 @@ namespace Mem { if (cy < height - 2) out += Mv::to(y+1+cy, x+1+cx) + divider; } - - redraw = false; return out + Fx::reset; } @@ -969,8 +1003,13 @@ namespace Net { graphs.clear(); if (net.bandwidth.at("download").empty() or net.bandwidth.at("upload").empty()) return out + Fx::reset; - graphs["download"] = Draw::Graph{width - b_width - 2, u_graph_height, "download", net.bandwidth.at("download"), graph_symbol, false, true, down_max}; - graphs["upload"] = Draw::Graph{width - b_width - 2, d_graph_height, "upload", net.bandwidth.at("upload"), graph_symbol, true, true, up_max}; + graphs["download"] = Draw::Graph{ + width - b_width - 2, u_graph_height, "download", + net.bandwidth.at("download"), graph_symbol, + false, true, down_max}; + graphs["upload"] = Draw::Graph{ + width - b_width - 2, d_graph_height, "upload", + net.bandwidth.at("upload"), graph_symbol, true, true, up_max}; //? Interface selector and buttons @@ -1020,7 +1059,6 @@ namespace Net { } } - redraw = false; return out + Fx::reset; } diff --git a/src/btop_draw.hpp b/src/btop_draw.hpp index e425845..6da4af5 100644 --- a/src/btop_draw.hpp +++ b/src/btop_draw.hpp @@ -24,7 +24,11 @@ tab-size = 4 #include #include -using std::string, std::array, std::vector, robin_hood::unordered_flat_map, std::deque; +using robin_hood::unordered_flat_map; +using std::array; +using std::deque; +using std::string; +using std::vector; namespace Symbols { const string h_line = "─"; @@ -62,8 +66,8 @@ namespace Draw { //* An editable text field class TextEdit { - size_t pos = 0; - size_t upos = 0; + size_t pos{}; // defaults to 0 + size_t upos{}; // defaults to 0 bool numeric; public: string text; @@ -75,7 +79,9 @@ namespace Draw { }; //* Create a box and return as a string - string createBox(const int x, const int y, const int width, const int height, string line_color="", const bool fill=false, const string title="", const string title2="", const int num=0); + string createBox(const int x, const int y, const int width, + const int height, string line_color="", const bool fill=false, + const string title="", const string title2="", const int num=0); bool update_clock(bool force=false); @@ -109,15 +115,12 @@ namespace Draw { public: Graph(); - Graph( int width, - int height, - const string& color_gradient, - const deque& data, - const string& symbol="default", - bool invert=false, - bool no_zero=false, - long long max_value=0, - long long offset=0); + Graph(int width, int height, + const string& color_gradient, + const deque& data, + const string& symbol="default", + bool invert=false, bool no_zero=false, + long long max_value=0, long long offset=0); //* Add last value from back of and return string representation of graph string& operator()(const deque& data, const bool data_same=false); @@ -134,4 +137,4 @@ namespace Proc { extern Draw::TextEdit filter; extern unordered_flat_map p_graphs; extern unordered_flat_map p_counters; -} \ No newline at end of file +} diff --git a/src/btop_input.cpp b/src/btop_input.cpp index 586dea9..43d7a6d 100644 --- a/src/btop_input.cpp +++ b/src/btop_input.cpp @@ -30,8 +30,11 @@ tab-size = 4 #include #include -using std::cin, std::vector, std::string_literals::operator""s; +using std::cin; +using std::vector; + using namespace Tools; +using namespace std::literals; // for operator""s namespace rng = std::ranges; namespace Input { @@ -545,10 +548,9 @@ namespace Input { } } - 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()}); } } -} \ No newline at end of file +} diff --git a/src/btop_input.hpp b/src/btop_input.hpp index 7342709..2e8c0a4 100644 --- a/src/btop_input.hpp +++ b/src/btop_input.hpp @@ -24,7 +24,12 @@ tab-size = 4 #include #include -using robin_hood::unordered_flat_map, std::array, std::string, std::atomic, std::deque; +using robin_hood::unordered_flat_map; +using std::array; +using std::atomic; +using std::deque; +using std::string; + /* The input functions relies on the following std::cin options being set: cin.sync_with_stdio(false); cin.tie(NULL); @@ -65,4 +70,4 @@ namespace Input { //* Process actions for input void process(const string& key); -} \ No newline at end of file +} diff --git a/src/btop_menu.cpp b/src/btop_menu.cpp index 8037e0f..71696f1 100644 --- a/src/btop_menu.cpp +++ b/src/btop_menu.cpp @@ -32,8 +32,18 @@ tab-size = 4 #include #include -using std::deque, robin_hood::unordered_flat_map, std::array, std::views::iota, std::ref, std::max, std::min, std::ceil, std::clamp; +using robin_hood::unordered_flat_map; +using std::array; +using std::ceil; +using std::clamp; +using std::deque; +using std::max; +using std::min; +using std::ref; +using std::views::iota; + using namespace Tools; + namespace fs = std::filesystem; namespace rng = std::ranges; @@ -41,11 +51,11 @@ namespace Menu { atomic active (false); string bg; - bool redraw = true; + bool redraw{true}; int currentMenu = -1; msgBox messageBox; - int signalToSend = 0; - int signalKillRet = 0; + int signalToSend{}; // defaults to 0 + int signalKillRet{}; // defaults to 0 const array P_Signals = { "0", @@ -713,7 +723,10 @@ namespace Menu { 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")); - static int x = 0, y = 0, selected_signal = -1; + static int x{}; // defaults to 0 + static int y{}; // defaults to 0 + static int selected_signal = -1; + if (bg.empty()) selected_signal = -1; auto& out = Global::overlay; int retval = Changed; @@ -912,7 +925,8 @@ namespace Menu { int mainMenu(const string& key) { enum MenuItems { Options, Help, Quit }; - static int y = 0, selected = 0; + static int y{}; // defaults to 0 + static int selected{}; // defaults to 0 static vector colors_selected; static vector colors_normal; auto& tty_mode = Config::getB("tty_mode"); @@ -969,7 +983,6 @@ namespace Menu { retval = NoChange; } - if (retval == Changed) { auto& out = Global::overlay; out = bg + Fx::reset + Fx::b; @@ -986,14 +999,23 @@ namespace Menu { out += Fx::reset; } - return (redraw ? Changed : retval); } int optionsMenu(const string& key) { enum Predispositions { isBool, isInt, isString, is2D, isBrowseable, isEditable}; - static int y = 0, x = 0, height = 0, page = 0, pages = 0, selected = 0, select_max = 0, item_height = 0, selected_cat = 0, max_items = 0, last_sel = 0; - static bool editing = false; + static int y{}; // defaults to 0 + static int x{}; // defaults to 0 + static int height{}; // defaults to 0 + static int page{}; // defaults to 0 + static int pages{}; // defaults to 0 + static int selected{}; // defaults to 0 + static int select_max{}; // defaults to 0 + static int item_height{}; // defaults to 0 + static int selected_cat{}; // defaults to 0 + static int max_items{}; // defaults to 0 + static int last_sel{}; // defaults to 0 + static bool editing{}; // defaults to false static Draw::TextEdit editor; static string warnings; static bitset<8> selPred; @@ -1025,9 +1047,9 @@ namespace Menu { Theme::updateThemes(); } int retval = Changed; - bool recollect = false; - bool screen_redraw = false; - bool theme_refresh = false; + bool recollect{}; // defaults to false + bool screen_redraw{}; // defaults to false + bool theme_refresh{}; // defaults to false //? Draw background if needed else process input if (redraw) { @@ -1320,7 +1342,12 @@ namespace Menu { } int helpMenu(const string& key) { - static int y = 0, x = 0, height = 0, page = 0, pages = 0; + static int y{}; // defaults to 0 + static int x{}; // defaults to 0 + static int height{}; // defaults to 0 + static int page{}; // defaults to 0 + static int pages{}; // defaults to 0 + if (bg.empty()) page = 0; int retval = Changed; diff --git a/src/btop_menu.hpp b/src/btop_menu.hpp index b4fcab1..0017962 100644 --- a/src/btop_menu.hpp +++ b/src/btop_menu.hpp @@ -25,7 +25,10 @@ tab-size = 4 #include -using std::string, std::atomic, std::vector, std::bitset; +using std::atomic; +using std::bitset; +using std::string; +using std::vector; namespace Menu { @@ -43,7 +46,12 @@ namespace Menu { //? Strings in content vector is not checked for box width overflow class msgBox { string box_contents, button_left, button_right; - int height = 0, width = 0, boxtype = 0, selected = 0, x = 0, y = 0; + int height{}; // defaults to 0 + int width{}; // defaults to 0 + int boxtype{}; // defaults to 0 + int selected{}; // defaults to 0 + int x{}; // defaults to 0 + int y{}; // defaults to 0 public: enum BoxTypes { OK, YES_NO, NO_YES }; enum msgReturn { diff --git a/src/linux/btop_collect.cpp b/src/linux/btop_collect.cpp index e986d35..fca5e99 100644 --- a/src/linux/btop_collect.cpp +++ b/src/linux/btop_collect.cpp @@ -35,12 +35,22 @@ tab-size = 4 #include #include -using std::ifstream, std::numeric_limits, std::streamsize, std::round, std::max, std::min; -using std::clamp, std::string_literals::operator""s, std::cmp_equal, std::cmp_less, std::cmp_greater; +using std::clamp; +using std::cmp_equal; +using std::cmp_greater; +using std::cmp_less; +using std::ifstream; +using std::max; +using std::min; +using std::numeric_limits; +using std::round; +using std::streamsize; + namespace fs = std::filesystem; namespace rng = std::ranges; -using namespace Tools; +using namespace Tools; +using namespace std::literals; // for operator""s //? --------------------------------------------------- FUNCTIONS ----------------------------------------------------- namespace Cpu { @@ -50,7 +60,8 @@ namespace Cpu { vector available_sensors = {"Auto"}; cpu_info current_cpu; fs::path freq_path = "/sys/devices/system/cpu/cpufreq/policy0/scaling_cur_freq"; - bool got_sensors = false, cpu_temp_only = false; + bool got_sensors{}; // defaults to false + bool cpu_temp_only{}; // defaults to false //* Populate found_sensors map bool get_sensors(); @@ -64,9 +75,9 @@ namespace Cpu { struct Sensor { fs::path path; string label; - int64_t temp = 0; - int64_t high = 0; - int64_t crit = 0; + int64_t temp{}; // defaults to 0 + int64_t high{}; // defaults to 0 + int64_t crit{}; // defaults to 0 }; unordered_flat_map found_sensors; @@ -144,7 +155,10 @@ namespace Cpu { bool has_battery = true; tuple current_bat; - const array time_names = {"user", "nice", "system", "idle", "iowait", "irq", "softirq", "steal", "guest", "guest_nice"}; + const array time_names { + "user"s, "nice"s, "system"s, "idle"s, "iowait"s, + "irq"s, "softirq"s, "steal"s, "guest"s, "guest_nice"s + }; unordered_flat_map cpu_old = { {"totals", 0}, @@ -387,11 +401,14 @@ namespace Cpu { } string get_cpuHz() { - static int failed = 0; - if (failed > 4) return ""s; + static int failed{}; // defaults to 0 + + if (failed > 4) + return ""s; + string cpuhz; try { - double hz = 0.0; + double hz{}; // defaults to 0.0 //? Try to get freq from /sys/devices/system/cpu/cpufreq/policy first (faster) if (not freq_path.empty()) { hz = stod(readfile(freq_path, "0.0")) / 1000; @@ -416,7 +433,8 @@ namespace Cpu { } } - if (hz <= 1 or hz >= 1000000) throw std::runtime_error("Failed to read /sys/devices/system/cpu/cpufreq/policy and /proc/cpuinfo."); + if (hz <= 1 or hz >= 1000000) + throw std::runtime_error("Failed to read /sys/devices/system/cpu/cpufreq/policy and /proc/cpuinfo."); if (hz >= 1000) { if (hz >= 10000) cpuhz = to_string((int)round(hz / 1000)); // Future proof until we reach THz speeds :) @@ -428,9 +446,10 @@ namespace Cpu { } catch (const std::exception& e) { - if (++failed < 5) return ""s; + if (++failed < 5) + return ""s; else { - Logger::warning("get_cpuHZ() : " + (string)e.what()); + Logger::warning("get_cpuHZ() : " + string{e.what()}); return ""s; } } @@ -445,7 +464,9 @@ namespace Cpu { //? Try to get core mapping from /proc/cpuinfo ifstream cpuinfo(Shared::procPath / "cpuinfo"); if (cpuinfo.good()) { - int cpu, core, n = 0; + int cpu{}; // defaults to 0 + int core{}; // defaults to 0 + int n{}; // defaults to 0 for (string instr; cpuinfo >> instr;) { if (instr == "processor") { cpuinfo.ignore(SSmax, ':'); @@ -714,9 +735,9 @@ namespace Cpu { } } catch (const std::exception& e) { - Logger::debug("get_cpuHz() : " + (string)e.what()); + Logger::debug("get_cpuHz() : " + string{e.what()}); if (cread.bad()) throw std::runtime_error("Failed to read /proc/stat"); - else throw std::runtime_error("collect() : " + (string)e.what()); + else throw std::runtime_error("collect() : " + string{e.what()}); } if (Config::getB("show_cpu_freq")) @@ -733,10 +754,10 @@ namespace Cpu { } namespace Mem { - bool has_swap = false; + bool has_swap{}; // defaults to false vector fstab; fs::file_time_type fstab_time; - int disk_ios = 0; + int disk_ios{}; // defaults to 0 vector last_found; const std::regex zfs_size_regex("^size\\s+\\d\\s+(\\d+)"); @@ -1114,14 +1135,14 @@ namespace Mem { while (cmp_greater(disk.io_activity.size(), width * 2)) disk.io_activity.pop_front(); } } 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(); } old_uptime = uptime; } catch (const std::exception& e) { - Logger::warning("Error in Mem::collect() : " + (string)e.what()); + Logger::warning("Error in Mem::collect() : " + string{e.what()}); } } @@ -1182,7 +1203,13 @@ namespace Mem { bool zfs_collect_pool_total_stats(struct disk_info &disk) { ifstream diskread; - int64_t bytes_read, bytes_write, io_ticks, bytes_read_total = 0, bytes_write_total = 0, io_ticks_total = 0, objects_read = 0; + int64_t bytes_read; + int64_t bytes_write; + int64_t io_ticks; + int64_t bytes_read_total{}; // defaults to 0 + int64_t bytes_write_total{}; // defaults to 0 + int64_t io_ticks_total{}; // defaults to 0 + int64_t objects_read{}; // defaults to 0 // looking through all files that start with 'objset' for (const auto& file: fs::directory_iterator(disk.stat)) { @@ -1258,11 +1285,11 @@ namespace Net { net_info empty_net = {}; vector interfaces; string selected_iface; - int errors = 0; + int errors{}; // defaults to 0 unordered_flat_map graph_max = { {"download", {}}, {"upload", {}} }; unordered_flat_map> max_count = { {"download", {}}, {"upload", {}} }; - bool rescale = true; - uint64_t timestamp = 0; + bool rescale{true}; + uint64_t timestamp{}; // defaults to 0 //* RAII wrapper for getifaddrs class getifaddr_wrapper { @@ -1296,7 +1323,7 @@ namespace Net { string ipv4, ipv6; //? Iteration over all items in getifaddrs() list - for (auto* ifa = if_wrap(); ifa != NULL; ifa = ifa->ifa_next) { + for (auto* ifa = if_wrap(); ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) continue; family = ifa->ifa_addr->sa_family; const auto& iface = ifa->ifa_name; @@ -1329,7 +1356,7 @@ namespace Net { auto& saved_stat = net.at(iface).stat.at(dir); auto& bandwidth = net.at(iface).bandwidth.at(dir); - uint64_t val = 0; + uint64_t val{}; // defaults to 0 try { val = (uint64_t)stoull(readfile(sys_file, "0")); } catch (const std::invalid_argument&) {} catch (const std::out_of_range&) {} @@ -1450,15 +1477,15 @@ namespace Proc { unordered_flat_map uid_user; string current_sort; string current_filter; - bool current_rev = false; + bool current_rev{}; // defaults to false fs::file_time_type passwd_time; uint64_t cputimes; int collapse = -1, expand = -1; - uint64_t old_cputimes = 0; - atomic numpids = 0; - int filter_found = 0; + uint64_t old_cputimes{}; // defaults to 0 + atomic numpids{}; // defaults to 0 + int filter_found{}; // defaults to 0 detail_container detailed; constexpr size_t KTHREADD = 2; @@ -1589,7 +1616,7 @@ namespace Proc { const int cmult = (per_core) ? Shared::coreCount : 1; bool got_detailed = false; - static size_t proc_clear_count = 0; + static size_t proc_clear_count{}; // defaults to 0 //* Use pids from last update if only changing filter, sorting or tree options if (no_update and not current_procs.empty()) { @@ -1647,6 +1674,7 @@ namespace Proc { for (const auto& d: fs::directory_iterator(Shared::procPath)) { if (Runner::stopping) return current_procs; + if (pread.is_open()) pread.close(); const string pid_str = d.path().filename(); @@ -1662,7 +1690,7 @@ namespace Proc { //? Check if pid already exists in current_procs auto find_old = rng::find(current_procs, pid, &proc_info::pid); - bool no_cache = false; + bool no_cache{}; // defaults to false if (find_old == current_procs.end()) { current_procs.push_back({pid}); find_old = current_procs.end() - 1; @@ -1945,6 +1973,6 @@ namespace Tools { catch (const std::invalid_argument&) {} 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"); } }