2018-08-08 23:42:52 +00:00
|
|
|
#include "modules/memory.hpp"
|
|
|
|
|
2018-08-20 12:50:45 +00:00
|
|
|
waybar::modules::Memory::Memory(const Json::Value& config)
|
2018-11-23 10:57:37 +00:00
|
|
|
: ALabel(config, "{}%", 30)
|
2018-08-08 23:42:52 +00:00
|
|
|
{
|
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-18 09:43:48 +00:00
|
|
|
}
|
2018-08-08 23:42:52 +00:00
|
|
|
|
2018-08-09 10:05:48 +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) {
|
2018-11-09 15:24:13 +00:00
|
|
|
int used_ram_percentage = 100 * (memtotal_ - memfree_) / memtotal_;
|
2018-11-21 19:49:09 +00:00
|
|
|
label_.set_markup(fmt::format(format_, used_ram_percentage));
|
2018-11-09 15:24:13 +00:00
|
|
|
auto used_ram_gigabytes = (memtotal_ - memfree_) / std::pow(1024, 2);
|
|
|
|
label_.set_tooltip_text(fmt::format("{:.{}f}Gb used", used_ram_gigabytes, 1));
|
2018-11-09 21:55:25 +00:00
|
|
|
label_.set_name("memory");
|
2018-11-09 15:24:13 +00:00
|
|
|
label_.show();
|
|
|
|
} else {
|
2018-11-09 21:55:25 +00:00
|
|
|
label_.set_name("");
|
2018-11-09 15:24:13 +00:00
|
|
|
label_.hide();
|
|
|
|
}
|
2018-11-08 20:09:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
void waybar::modules::Memory::parseMeminfo()
|
|
|
|
{
|
2018-11-09 21:55:25 +00:00
|
|
|
long memfree = -1, membuffer = -1, memcache = -1, memavail = -1;
|
|
|
|
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)) {
|
|
|
|
auto posDelim = line.find(":");
|
|
|
|
if (posDelim == std::string::npos) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
std::string name = line.substr(0, posDelim);
|
|
|
|
long 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;
|
|
|
|
}
|
|
|
|
if (memtotal_ > 0 &&
|
|
|
|
(memavail >= 0 || (memfree > -1 && membuffer > -1 && memcache > -1))) {
|
|
|
|
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
|
|
|
}
|