Waybar/src/modules/memory.cpp

42 lines
1.4 KiB
C++
Raw Normal View History

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-08-26 23:36:25 +00:00
: ALabel(config, "{}%")
2018-08-08 23:42:52 +00:00
{
2018-08-16 12:29:41 +00:00
label_.set_name("memory");
2018-10-26 07:27:16 +00:00
uint32_t interval = config_["interval"].isUInt() ? config_["interval"].asUInt() : 30;
2018-08-16 12:29:41 +00:00
thread_ = [this, interval] {
2018-08-20 12:50:45 +00:00
dp.emit();
2018-08-16 12:29:41 +00:00
thread_.sleep_for(chrono::seconds(interval));
2018-08-08 23:42:52 +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();
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));
}
void waybar::modules::Memory::parseMeminfo()
{
int memtotal, memfree, memavail, membuffer, memcache;
FILE* info = fopen("/proc/meminfo","r");
if(fscanf (info, "MemTotal: %d kB MemFree: %d kB Buffers: %d kB Cached: %d kB",&memtotal, &memfree, &membuffer, &memcache) < 4) { // Old meminfo format
rewind(info);
2018-11-08 20:09:56 +00:00
if(fscanf(info, "MemTotal: %d kB MemFree: %d kB MemAvailable: %d kB Buffers: %d kB Cached: %d kB",&memtotal, &memfree, &memavail, &membuffer, &memcache) < 5) { // Current meminfo format
memtotal_ = -1;
memfree_ = -1;
} else {
memtotal_ = memtotal;
memfree_ = memavail;
}
} else {
memtotal_ = memtotal;
memfree_ = memfree + (membuffer + memcache);
2018-08-09 10:05:48 +00:00
}
2018-11-08 20:09:56 +00:00
fclose(info);
2018-08-09 10:05:48 +00:00
}