2018-08-10 14:26:46 +00:00
|
|
|
#include "modules/custom.hpp"
|
|
|
|
#include <iostream>
|
|
|
|
|
2018-08-16 12:29:41 +00:00
|
|
|
waybar::modules::Custom::Custom(const std::string &name, Json::Value config)
|
|
|
|
: name_(name), config_(std::move(config))
|
2018-08-10 14:26:46 +00:00
|
|
|
{
|
2018-08-16 12:29:41 +00:00
|
|
|
if (!config_["exec"]) {
|
|
|
|
throw std::runtime_error(name_ + " has no exec path.");
|
|
|
|
}
|
2018-08-16 15:09:51 +00:00
|
|
|
if (config_["max-length"]) {
|
|
|
|
label_.set_max_width_chars(config_["max-length"].asUInt());
|
|
|
|
label_.set_ellipsize(Pango::EllipsizeMode::ELLIPSIZE_END);
|
|
|
|
}
|
2018-08-16 12:29:41 +00:00
|
|
|
uint32_t interval = config_["interval"] ? config_["inveral"].asUInt() : 30;
|
|
|
|
thread_ = [this, interval] {
|
2018-08-11 00:40:13 +00:00
|
|
|
Glib::signal_idle().connect_once(sigc::mem_fun(*this, &Custom::update));
|
2018-08-16 12:29:41 +00:00
|
|
|
thread_.sleep_for(chrono::seconds(interval));
|
2018-08-10 14:26:46 +00:00
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
auto waybar::modules::Custom::update() -> void
|
|
|
|
{
|
2018-08-16 12:29:41 +00:00
|
|
|
std::array<char, 128> buffer = {0};
|
2018-08-10 14:26:46 +00:00
|
|
|
std::string output;
|
2018-08-16 12:29:41 +00:00
|
|
|
std::shared_ptr<FILE> fp(popen(config_["exec"].asCString(), "r"), pclose);
|
2018-08-10 14:26:46 +00:00
|
|
|
if (!fp) {
|
2018-08-16 12:29:41 +00:00
|
|
|
std::cerr << name_ + " can't exec " + config_["exec"].asString() << std::endl;
|
2018-08-10 14:26:46 +00:00
|
|
|
return;
|
|
|
|
}
|
2018-08-16 12:29:41 +00:00
|
|
|
|
|
|
|
while (feof(fp.get()) == 0) {
|
|
|
|
if (fgets(buffer.data(), 128, fp.get()) != nullptr) {
|
2018-08-10 14:26:46 +00:00
|
|
|
output += buffer.data();
|
2018-08-16 12:29:41 +00:00
|
|
|
}
|
2018-08-10 14:26:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Remove last newline
|
|
|
|
if (!output.empty() && output[output.length()-1] == '\n') {
|
|
|
|
output.erase(output.length()-1);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Hide label if output is empty
|
2018-08-10 15:05:12 +00:00
|
|
|
if (output.empty()) {
|
2018-08-16 12:29:41 +00:00
|
|
|
label_.hide();
|
2018-08-16 15:59:45 +00:00
|
|
|
label_.set_name("");
|
2018-08-10 15:05:12 +00:00
|
|
|
} else {
|
2018-08-16 12:29:41 +00:00
|
|
|
label_.set_name("custom-" + name_);
|
|
|
|
auto format = config_["format"] ? config_["format"].asString() : "{}";
|
2018-08-16 15:09:51 +00:00
|
|
|
auto str = fmt::format(format, output);
|
|
|
|
label_.set_text(str);
|
|
|
|
label_.set_tooltip_text(str);
|
2018-08-16 12:29:41 +00:00
|
|
|
label_.show();
|
2018-08-10 14:26:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
waybar::modules::Custom::operator Gtk::Widget &() {
|
2018-08-16 12:29:41 +00:00
|
|
|
return label_;
|
2018-08-10 14:26:46 +00:00
|
|
|
}
|