diff --git a/include/modules/custom.hpp b/include/modules/custom.hpp index bb0204fd..f0553831 100644 --- a/include/modules/custom.hpp +++ b/include/modules/custom.hpp @@ -13,7 +13,8 @@ class Custom : public ALabel { Custom(const std::string, const Json::Value&); auto update() -> void; private: - void worker(); + void delayWorker(); + void continuousWorker(); const std::string name_; waybar::util::SleeperThread thread_; diff --git a/include/util/chrono.hpp b/include/util/chrono.hpp index 39695b4f..828273a4 100644 --- a/include/util/chrono.hpp +++ b/include/util/chrono.hpp @@ -70,7 +70,7 @@ struct SleeperThread { condvar_.notify_all(); } - ~SleeperThread() + auto stop() { do_run_ = false; condvar_.notify_all(); @@ -79,6 +79,11 @@ struct SleeperThread { } } + ~SleeperThread() + { + stop(); + } + private: std::thread thread_; std::condition_variable condvar_; diff --git a/resources/config b/resources/config index f17acc3a..da3012bb 100644 --- a/resources/config +++ b/resources/config @@ -62,6 +62,7 @@ "custom/spotify": { "format": " {}", "max-length": 40, + "interval": 30, // Remove this if your script is endless and write in loop "exec": "$HOME/.config/waybar/mediaplayer.sh", // Script in resources folder "exec-if": "pgrep spotify" } diff --git a/src/modules/custom.cpp b/src/modules/custom.cpp index a47d5085..16ed621b 100644 --- a/src/modules/custom.cpp +++ b/src/modules/custom.cpp @@ -7,12 +7,16 @@ waybar::modules::Custom::Custom(const std::string name, if (!config_["exec"]) { throw std::runtime_error(name_ + " has no exec path."); } - worker(); + if (config_["interval"]) { + delayWorker(); + } else { + continuousWorker(); + } } -void waybar::modules::Custom::worker() +void waybar::modules::Custom::delayWorker() { - uint32_t interval = config_["interval"] ? config_["inveral"].asUInt() : 30; + auto interval = config_["interval"].asUInt(); thread_ = [this, interval] { bool can_update = true; if (config_["exec-if"]) { @@ -31,6 +35,34 @@ void waybar::modules::Custom::worker() }; } +void waybar::modules::Custom::continuousWorker() +{ + auto cmd = config_["exec"].asString(); + FILE* fp(popen(cmd.c_str(), "r")); + if (!fp) { + throw std::runtime_error("Unable to open " + cmd); + } + thread_ = [this, fp] { + char* buff = nullptr; + size_t len = 0; + if (getline(&buff, &len, fp) == -1) { + thread_.stop(); + output_ = { 1, "" }; + dp.emit(); + return; + } + + std::string output = buff; + + // Remove last newline + if (!output.empty() && output[output.length()-1] == '\n') { + output.erase(output.length()-1); + } + output_ = { 0, output }; + dp.emit(); + }; +} + auto waybar::modules::Custom::update() -> void { // Hide label if output is empty