Waybar/src/modules/memory.cpp

67 lines
2.2 KiB
C++
Raw Normal View History

2018-08-08 23:42:52 +00:00
#include "modules/memory.hpp"
2018-12-18 16:30:54 +00:00
waybar::modules::Memory::Memory(const std::string& id, const Json::Value& config)
: ALabel(config, "memory", id, "{}%", 30) {
2018-11-23 10:57:37 +00:00
thread_ = [this] {
2018-08-20 12:50:45 +00:00
dp.emit();
2018-11-23 10:57:37 +00:00
thread_.sleep_for(interval_);
2018-08-08 23:42:52 +00:00
};
}
2018-08-08 23:42:52 +00:00
2019-04-18 15:52:00 +00:00
auto waybar::modules::Memory::update() -> void {
2018-11-08 20:09:56 +00:00
parseMeminfo();
2018-11-09 21:55:25 +00:00
if (memtotal_ > 0 && memfree_ >= 0) {
auto total_ram_gigabytes = memtotal_ / std::pow(1024, 2);
int used_ram_percentage = 100 * (memtotal_ - memfree_) / memtotal_;
2018-11-09 15:24:13 +00:00
auto used_ram_gigabytes = (memtotal_ - memfree_) / std::pow(1024, 2);
auto available_ram_gigabytes = memfree_ / std::pow(1024, 2);
getState(used_ram_percentage);
label_.set_markup(fmt::format(format_,
used_ram_percentage,
fmt::arg("total", total_ram_gigabytes),
fmt::arg("percentage", used_ram_percentage),
fmt::arg("used", used_ram_gigabytes),
fmt::arg("avail", available_ram_gigabytes)));
2019-02-22 10:35:26 +00:00
if (tooltipEnabled()) {
label_.set_tooltip_text(fmt::format("{:.{}f}Gb used", used_ram_gigabytes, 1));
}
2018-12-18 16:30:54 +00:00
event_box_.show();
2018-11-09 15:24:13 +00:00
} else {
2018-12-18 16:30:54 +00:00
event_box_.hide();
2018-11-09 15:24:13 +00:00
}
2018-11-08 20:09:56 +00:00
}
2019-04-18 15:52:00 +00:00
void waybar::modules::Memory::parseMeminfo() {
2019-04-24 10:37:24 +00:00
int64_t memfree = -1, membuffer = -1, memcache = -1, memavail = -1;
2018-11-09 21:55:25 +00:00
std::ifstream info(data_dir_);
if (!info.is_open()) {
throw std::runtime_error("Can't open " + data_dir_);
}
2018-11-09 15:24:13 +00:00
std::string line;
2018-11-09 21:55:25 +00:00
while (getline(info, line)) {
2019-04-24 10:37:24 +00:00
auto posDelim = line.find(':');
2018-11-09 21:55:25 +00:00
if (posDelim == std::string::npos) {
continue;
}
std::string name = line.substr(0, posDelim);
2019-04-24 10:37:24 +00:00
int64_t value = std::stol(line.substr(posDelim + 1));
2018-11-09 15:24:13 +00:00
2018-11-09 21:55:25 +00:00
if (name.compare("MemTotal") == 0) {
memtotal_ = value;
} else if (name.compare("MemAvailable") == 0) {
memavail = value;
} else if (name.compare("MemFree") == 0) {
memfree = value;
} else if (name.compare("Buffers") == 0) {
membuffer = value;
} else if (name.compare("Cached") == 0) {
memcache = value;
}
2019-04-18 15:52:00 +00:00
if (memtotal_ > 0 && (memavail >= 0 || (memfree > -1 && membuffer > -1 && memcache > -1))) {
2018-11-09 21:55:25 +00:00
break;
2018-11-08 20:09:56 +00:00
}
2018-08-09 10:05:48 +00:00
}
2018-11-09 21:55:25 +00:00
memfree_ = memavail >= 0 ? memavail : memfree + membuffer + memcache;
2018-08-09 10:05:48 +00:00
}