Waybar/src/modules/battery.cpp

57 lines
1.4 KiB
C++
Raw Normal View History

2018-08-08 21:54:58 +00:00
#include "modules/battery.hpp"
2018-08-09 11:30:11 +00:00
waybar::modules::Battery::Battery(Json::Value config)
: _config(config)
2018-08-08 21:54:58 +00:00
{
try {
for (auto &node : fs::directory_iterator(_data_dir)) {
2018-08-09 09:21:08 +00:00
if (fs::is_directory(node) && fs::exists(node / "capacity")
&& fs::exists(node / "status")) {
2018-08-08 21:54:58 +00:00
_batteries.push_back(node);
}
}
} catch (fs::filesystem_error &e) {
std::cerr << e.what() << std::endl;
}
2018-08-09 08:50:16 +00:00
_label.get_style_context()->add_class("battery");
2018-08-08 21:54:58 +00:00
_thread = [this] {
update();
_thread.sleep_for(chrono::minutes(1));
};
}
auto waybar::modules::Battery::update() -> void
{
try {
2018-08-09 09:21:08 +00:00
int total = 0;
bool charging = false;
2018-08-08 21:54:58 +00:00
for (auto &bat : _batteries) {
2018-08-09 09:21:08 +00:00
int capacity;
2018-08-08 21:54:58 +00:00
std::string status;
2018-08-09 09:21:08 +00:00
std::ifstream(bat / "capacity") >> capacity;
total += capacity;
2018-08-08 21:54:58 +00:00
std::ifstream(bat / "status") >> status;
if (status == "Charging") {
2018-08-09 09:21:08 +00:00
charging = true;
2018-08-08 21:54:58 +00:00
}
}
2018-08-09 09:21:08 +00:00
if (charging == true) {
_label.get_style_context()->add_class("charging");
} else {
_label.get_style_context()->remove_class("charging");
}
2018-08-09 11:30:11 +00:00
auto format = _config["format"] ? _config["format"].asString() : "{}%";
_label.set_text(fmt::format(format, total / _batteries.size()));
_label.set_tooltip_text(charging ? "Charging" : "Discharging");
2018-08-08 21:54:58 +00:00
} catch (std::exception &e) {
std::cerr << e.what() << std::endl;
}
}
waybar::modules::Battery::operator Gtk::Widget &()
{
return _label;
}