2018-08-09 01:42:52 +02:00
|
|
|
#include "modules/memory.hpp"
|
|
|
|
|
2018-08-20 14:50:45 +02:00
|
|
|
waybar::modules::Memory::Memory(const Json::Value& config)
|
2018-08-27 01:36:25 +02:00
|
|
|
: ALabel(config, "{}%")
|
2018-08-09 01:42:52 +02:00
|
|
|
{
|
2018-08-16 14:29:41 +02:00
|
|
|
label_.set_name("memory");
|
2018-10-26 09:27:16 +02:00
|
|
|
uint32_t interval = config_["interval"].isUInt() ? config_["interval"].asUInt() : 30;
|
2018-08-16 14:29:41 +02:00
|
|
|
thread_ = [this, interval] {
|
2018-08-20 14:50:45 +02:00
|
|
|
dp.emit();
|
2018-08-16 14:29:41 +02:00
|
|
|
thread_.sleep_for(chrono::seconds(interval));
|
2018-08-09 01:42:52 +02:00
|
|
|
};
|
2018-08-18 11:43:48 +02:00
|
|
|
}
|
2018-08-09 01:42:52 +02:00
|
|
|
|
2018-08-09 12:05:48 +02:00
|
|
|
auto waybar::modules::Memory::update() -> void
|
|
|
|
{
|
2018-11-08 21:09:56 +01:00
|
|
|
parseMeminfo();
|
2018-11-09 16:24:13 +01:00
|
|
|
if(memtotal_ > 0 && memfree_ >= 0) {
|
|
|
|
int used_ram_percentage = 100 * (memtotal_ - memfree_) / memtotal_;
|
|
|
|
label_.set_text(fmt::format(format_, used_ram_percentage));
|
|
|
|
auto used_ram_gigabytes = (memtotal_ - memfree_) / std::pow(1024, 2);
|
|
|
|
label_.set_tooltip_text(fmt::format("{:.{}f}Gb used", used_ram_gigabytes, 1));
|
|
|
|
label_.show();
|
|
|
|
} else {
|
|
|
|
label_.hide();
|
|
|
|
}
|
2018-11-08 21:09:56 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
void waybar::modules::Memory::parseMeminfo()
|
|
|
|
{
|
2018-11-09 16:24:13 +01:00
|
|
|
long memtotal = -1, memfree = -1, membuffer = -1, memcache = -1, memavail = -1;
|
|
|
|
int count = 0;
|
|
|
|
std::string line;
|
|
|
|
std::ifstream info("/proc/meminfo");
|
|
|
|
if(info.is_open()) {
|
|
|
|
while(getline(info, line)) {
|
|
|
|
auto posDelim = line.find(":");
|
|
|
|
std::string name = line.substr(0, posDelim);
|
|
|
|
long value = std::stol(line.substr(posDelim + 1));
|
|
|
|
|
|
|
|
if(name.compare("MemTotal") == 0) {
|
|
|
|
memtotal = value;
|
|
|
|
count++;
|
|
|
|
} else if(name.compare("MemAvailable") == 0) {
|
|
|
|
memavail = value;
|
|
|
|
count++;
|
|
|
|
} else if(name.compare("MemFree") == 0) {
|
|
|
|
memfree = value;
|
|
|
|
count++;
|
|
|
|
} else if(name.compare("Buffers") == 0) {
|
|
|
|
membuffer = value;
|
|
|
|
count++;
|
|
|
|
} else if(name.compare("Cached") == 0) {
|
|
|
|
memcache = value;
|
|
|
|
count++;
|
|
|
|
}
|
|
|
|
if (count >= 5 || (count >= 4 && memavail >= -1)) {
|
|
|
|
info.close();
|
|
|
|
}
|
2018-11-08 21:09:56 +01:00
|
|
|
}
|
|
|
|
} else {
|
2018-11-09 16:24:13 +01:00
|
|
|
throw std::runtime_error("Can't open /proc/meminfo");
|
|
|
|
}
|
|
|
|
memtotal_ = memtotal;
|
|
|
|
if(memavail >= 0) {
|
|
|
|
memfree_ = memavail;
|
|
|
|
} else {
|
2018-11-08 21:09:56 +01:00
|
|
|
memfree_ = memfree + (membuffer + memcache);
|
2018-08-09 12:05:48 +02:00
|
|
|
}
|
|
|
|
}
|