feat(Custom): handle continuous script

This commit is contained in:
Alexis 2018-09-18 23:15:37 +02:00
parent d5d620e72d
commit 00959c7d65
No known key found for this signature in database
GPG Key ID: 20B1EC2EBBA96BD9
4 changed files with 44 additions and 5 deletions

View File

@ -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_;

View File

@ -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_;

View File

@ -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"
}

View File

@ -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