Handle screens disconnection (#29)

pull/31/head
Alex 2018-08-19 13:39:57 +02:00 committed by GitHub
parent ce50a627be
commit 6705134034
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
23 changed files with 205 additions and 133 deletions

View File

@ -4,17 +4,18 @@
#include <gtkmm.h> #include <gtkmm.h>
#include "wlr-layer-shell-unstable-v1-client-protocol.h" #include "wlr-layer-shell-unstable-v1-client-protocol.h"
#include "xdg-output-unstable-v1-client-protocol.h" #include "xdg-output-unstable-v1-client-protocol.h"
#include "IModule.hpp"
namespace waybar { namespace waybar {
class Client; class Client;
class Factory;
class Bar { class Bar {
public: public:
Bar(Client&, std::unique_ptr<struct wl_output *>&&); Bar(Client&, std::unique_ptr<struct wl_output *>&&, uint32_t wl_name);
Bar(const Bar&) = delete; Bar(const Bar&) = delete;
auto setWidth(uint32_t) -> void;
auto toggle() -> void; auto toggle() -> void;
Client& client; Client& client;
@ -22,7 +23,8 @@ class Bar {
struct wl_surface *surface; struct wl_surface *surface;
struct zwlr_layer_surface_v1 *layer_surface; struct zwlr_layer_surface_v1 *layer_surface;
std::unique_ptr<struct wl_output *> output; std::unique_ptr<struct wl_output *> output;
std::string outputName; std::string output_name;
uint32_t wl_name;
bool visible = true; bool visible = true;
private: private:
static void handleLogicalPosition(void *, struct zxdg_output_v1 *, int32_t, static void handleLogicalPosition(void *, struct zxdg_output_v1 *, int32_t,
@ -41,6 +43,7 @@ class Bar {
auto setupConfig() -> void; auto setupConfig() -> void;
auto setupWidgets() -> void; auto setupWidgets() -> void;
auto setupCss() -> void; auto setupCss() -> void;
void getModules(Factory factory, const std::string& pos);
uint32_t width_ = 0; uint32_t width_ = 0;
uint32_t height_ = 30; uint32_t height_ = 30;
@ -48,6 +51,9 @@ class Bar {
Glib::RefPtr<Gtk::StyleContext> style_context_; Glib::RefPtr<Gtk::StyleContext> style_context_;
Glib::RefPtr<Gtk::CssProvider> css_provider_; Glib::RefPtr<Gtk::CssProvider> css_provider_;
struct zxdg_output_v1 *xdg_output_; struct zxdg_output_v1 *xdg_output_;
std::vector<std::unique_ptr<waybar::IModule>> modules_left_;
std::vector<std::unique_ptr<waybar::IModule>> modules_center_;
std::vector<std::unique_ptr<waybar::IModule>> modules_right_;
}; };
} }

View File

@ -19,7 +19,7 @@ class Client {
Client(int argc, char *argv[]); Client(int argc, char *argv[]);
int main(int argc, char *argv[]); int main(int argc, char *argv[]);
Gtk::Main gtk_main; Glib::RefPtr<Gtk::Application> gtk_app;
std::string css_file; std::string css_file;
std::string config_file; std::string config_file;
Glib::RefPtr<Gdk::Display> gdk_display; Glib::RefPtr<Gdk::Display> gdk_display;

View File

@ -16,7 +16,7 @@ namespace waybar {
class Factory { class Factory {
public: public:
Factory(Bar &bar, Json::Value config); Factory(Bar &bar, Json::Value config);
IModule *makeModule(const std::string &name); IModule* makeModule(const std::string &name);
private: private:
Bar &_bar; Bar &_bar;
Json::Value _config; Json::Value _config;

View File

@ -16,6 +16,7 @@ namespace fs = std::filesystem;
class Battery : public ALabel { class Battery : public ALabel {
public: public:
Battery(Json::Value); Battery(Json::Value);
~Battery();
auto update() -> void; auto update() -> void;
private: private:
std::string getIcon(uint16_t percentage); std::string getIcon(uint16_t percentage);
@ -24,6 +25,7 @@ class Battery : public ALabel {
util::SleeperThread thread_; util::SleeperThread thread_;
std::vector<fs::path> batteries_; std::vector<fs::path> batteries_;
int fd_;
}; };
} }

View File

@ -14,6 +14,7 @@ namespace waybar::modules {
class Network : public ALabel { class Network : public ALabel {
public: public:
Network(Json::Value); Network(Json::Value);
~Network();
auto update() -> void; auto update() -> void;
private: private:
static uint64_t netlinkRequest(int, void*, uint32_t, uint32_t groups = 0); static uint64_t netlinkRequest(int, void*, uint32_t, uint32_t groups = 0);

View File

@ -10,6 +10,7 @@ namespace waybar::modules {
class Pulseaudio : public ALabel { class Pulseaudio : public ALabel {
public: public:
Pulseaudio(Json::Value); Pulseaudio(Json::Value);
~Pulseaudio();
auto update() -> void; auto update() -> void;
private: private:
static void subscribeCb(pa_context*, pa_subscription_event_type_t, static void subscribeCb(pa_context*, pa_subscription_event_type_t,

View File

@ -12,6 +12,7 @@ namespace waybar::modules::sway {
class Window : public ALabel { class Window : public ALabel {
public: public:
Window(waybar::Bar&, Json::Value); Window(waybar::Bar&, Json::Value);
~Window();
auto update() -> void; auto update() -> void;
private: private:
std::string getFocusedNode(Json::Value nodes); std::string getFocusedNode(Json::Value nodes);

View File

@ -12,6 +12,7 @@ namespace waybar::modules::sway {
class Workspaces : public IModule { class Workspaces : public IModule {
public: public:
Workspaces(waybar::Bar&, Json::Value); Workspaces(waybar::Bar&, Json::Value);
~Workspaces();
auto update() -> void; auto update() -> void;
operator Gtk::Widget &(); operator Gtk::Widget &();
private: private:

View File

@ -5,6 +5,7 @@
#include <functional> #include <functional>
#include <condition_variable> #include <condition_variable>
#include <thread> #include <thread>
#include <gtkmm.h>
namespace waybar::chrono { namespace waybar::chrono {
@ -14,18 +15,6 @@ using clock = std::chrono::system_clock;
using duration = clock::duration; using duration = clock::duration;
using time_point = std::chrono::time_point<clock, duration>; using time_point = std::chrono::time_point<clock, duration>;
inline struct timespec to_timespec(time_point t) noexcept
{
long secs = duration_cast<seconds>(t.time_since_epoch()).count();
long nsc = duration_cast<nanoseconds>(t.time_since_epoch() % seconds(1)).count();
return {secs, nsc};
}
inline time_point to_time_point(struct timespec t) noexcept
{
return time_point(duration_cast<duration>(seconds(t.tv_sec) + nanoseconds(t.tv_nsec)));
}
} }
namespace waybar::util { namespace waybar::util {
@ -34,59 +23,71 @@ struct SleeperThread {
SleeperThread() = default; SleeperThread() = default;
SleeperThread(std::function<void()> func) SleeperThread(std::function<void()> func)
: thread{[this, func] { : thread_{[this, func] {
do { while(true) {
func();
} while (do_run);
}}
{ {
defined = true; std::lock_guard<std::mutex> lock(mutex_);
if (!do_run_) {
break;
} }
}
func();
}
}}
{}
SleeperThread& operator=(std::function<void()> func) SleeperThread& operator=(std::function<void()> func)
{ {
thread = std::thread([this, func] { thread_ = std::thread([this, func] {
do { while(true) {
{
std::lock_guard<std::mutex> lock(mutex_);
if (!do_run_) {
break;
}
}
func(); func();
} while (do_run); }
}); });
defined = true;
return *this; return *this;
} }
auto sleep_for(chrono::duration dur) auto sleep_for(chrono::duration dur)
{ {
auto lock = std::unique_lock(mutex); auto lock = std::unique_lock(mutex_);
return condvar.wait_for(lock, dur); return condvar_.wait_for(lock, dur);
} }
auto sleep_until(chrono::time_point time) auto sleep_until(chrono::time_point time)
{ {
auto lock = std::unique_lock(mutex); auto lock = std::unique_lock(mutex_);
return condvar.wait_until(lock, time); return condvar_.wait_until(lock, time);
} }
auto wake_up() auto wake_up()
{ {
condvar.notify_all(); condvar_.notify_all();
} }
~SleeperThread() ~SleeperThread()
{ {
do_run = false; do_run_ = false;
if (defined) { condvar_.notify_all();
condvar.notify_all(); auto native_handle = thread_.native_handle();
thread.join(); pthread_cancel(native_handle);
if (thread_.joinable()) {
thread_.join();
} }
} }
sigc::signal<void> sig_update;
private: private:
std::thread thread; std::thread thread_;
std::condition_variable condvar; std::condition_variable condvar_;
std::mutex mutex; std::mutex mutex_;
bool defined = false; bool do_run_ = true;
bool do_run = true;
}; };
} }

View File

@ -14,6 +14,9 @@ struct JsonParser {
{ {
Json::Value root; Json::Value root;
std::string err; std::string err;
if (_reader == nullptr) {
throw std::runtime_error("Unable to parse");
}
bool res = bool res =
_reader->parse(data.c_str(), data.c_str() + data.size(), &root, &err); _reader->parse(data.c_str(), data.c_str() + data.size(), &root, &err);
if (!res) if (!res)
@ -24,6 +27,7 @@ struct JsonParser {
~JsonParser() ~JsonParser()
{ {
delete _reader; delete _reader;
_reader = nullptr;
} }
private: private:

View File

@ -6,7 +6,7 @@ project(
) )
cpp_args = [] cpp_args = []
cpp_link_args = [] cpp_link_args = ['-g']
if false # libc++ if false # libc++
cpp_args += ['-stdlib=libc++'] cpp_args += ['-stdlib=libc++']

View File

@ -3,9 +3,10 @@
#include "factory.hpp" #include "factory.hpp"
#include "util/json.hpp" #include "util/json.hpp"
waybar::Bar::Bar(Client &client, std::unique_ptr<struct wl_output *> &&p_output) waybar::Bar::Bar(Client &client,
std::unique_ptr<struct wl_output *> &&p_output, uint32_t p_wl_name)
: client(client), window{Gtk::WindowType::WINDOW_TOPLEVEL}, : client(client), window{Gtk::WindowType::WINDOW_TOPLEVEL},
output(std::move(p_output)) output(std::move(p_output)), wl_name(std::move(p_wl_name))
{ {
static const struct zxdg_output_v1_listener xdgOutputListener = { static const struct zxdg_output_v1_listener xdgOutputListener = {
.logical_position = handleLogicalPosition, .logical_position = handleLogicalPosition,
@ -22,29 +23,39 @@ waybar::Bar::Bar(Client &client, std::unique_ptr<struct wl_output *> &&p_output)
setupConfig(); setupConfig();
setupCss(); setupCss();
setupWidgets(); setupWidgets();
if (config_["height"]) {
height_ = config_["height"].asUInt();
}
Gtk::Widget& wrap(window); Gtk::Widget& wrap(window);
gtk_widget_realize(wrap.gobj()); gtk_widget_realize(wrap.gobj());
GdkWindow *gdk_window = gtk_widget_get_window(wrap.gobj()); GdkWindow *gdk_window = gtk_widget_get_window(wrap.gobj());
gdk_wayland_window_set_use_custom_surface(gdk_window); gdk_wayland_window_set_use_custom_surface(gdk_window);
surface = gdk_wayland_window_get_wl_surface(gdk_window); surface = gdk_wayland_window_get_wl_surface(gdk_window);
std::size_t layer_top = config_["layer"] == "top" std::size_t layer_top = config_["layer"] == "top"
? ZWLR_LAYER_SHELL_V1_LAYER_TOP : ZWLR_LAYER_SHELL_V1_LAYER_BOTTOM; ? ZWLR_LAYER_SHELL_V1_LAYER_TOP : ZWLR_LAYER_SHELL_V1_LAYER_BOTTOM;
layer_surface = zwlr_layer_shell_v1_get_layer_surface( layer_surface = zwlr_layer_shell_v1_get_layer_surface(
client.layer_shell, surface, *output, layer_top, "waybar"); client.layer_shell, surface, *output, layer_top, "waybar");
std::size_t position_bottom = config_["position"] == "bottom"
? ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM : ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP;
zwlr_layer_surface_v1_set_anchor(layer_surface, position_bottom
| ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT | ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT);
zwlr_layer_surface_v1_set_size(layer_surface, width_, height_);
static const struct zwlr_layer_surface_v1_listener layer_surface_listener = { static const struct zwlr_layer_surface_v1_listener layer_surface_listener = {
.configure = layerSurfaceHandleConfigure, .configure = layerSurfaceHandleConfigure,
.closed = layerSurfaceHandleClosed, .closed = layerSurfaceHandleClosed,
}; };
zwlr_layer_surface_v1_add_listener(layer_surface, zwlr_layer_surface_v1_add_listener(layer_surface,
&layer_surface_listener, this); &layer_surface_listener, this);
std::size_t anchor = ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT
| ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT;
if (config_["position"] == "bottom") {
anchor |= ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM;
} else {
anchor |= ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP;
}
auto height = config_["height"] ? config_["height"].asUInt() : height_;
auto width = config_["width"] ? config_["width"].asUInt() : width_;
zwlr_layer_surface_v1_set_anchor(layer_surface, anchor);
zwlr_layer_surface_v1_set_exclusive_zone(layer_surface, height);
zwlr_layer_surface_v1_set_size(layer_surface, width, height);
wl_surface_commit(surface); wl_surface_commit(surface);
} }
@ -71,7 +82,7 @@ void waybar::Bar::handleName(void* data, struct zxdg_output_v1* /*xdg_output*/,
const char* name) const char* name)
{ {
auto o = static_cast<waybar::Bar *>(data); auto o = static_cast<waybar::Bar *>(data);
o->outputName = name; o->output_name = name;
} }
void waybar::Bar::handleDescription(void* /*data*/, void waybar::Bar::handleDescription(void* /*data*/,
@ -86,13 +97,17 @@ void waybar::Bar::layerSurfaceHandleConfigure(void* data,
{ {
auto o = static_cast<waybar::Bar *>(data); auto o = static_cast<waybar::Bar *>(data);
o->window.show_all(); o->window.show_all();
o->setWidth(o->config_["width"] ? o->config_["width"].asUInt() : width);
zwlr_layer_surface_v1_ack_configure(surface, serial); zwlr_layer_surface_v1_ack_configure(surface, serial);
if (o->height_ != height) { if (width != o->width_ || height != o->height_) {
height = o->height_; o->width_ = width;
std::cout << fmt::format("New Height: {}", height) << std::endl; o->height_ = height;
zwlr_layer_surface_v1_set_size(surface, o->width_, height); std::cout << fmt::format(
zwlr_layer_surface_v1_set_exclusive_zone(surface, o->visible ? height : 0); "Bar configured (width: {}, height: {}) for output: {}",
o->width_, o->height_, o->output_name) << std::endl;
o->window.set_size_request(o->width_, o->height_);
o->window.resize(o->width_, o->height_);
zwlr_layer_surface_v1_set_exclusive_zone(surface, o->height_);
zwlr_layer_surface_v1_set_size(surface, o->width_, o->height_);
wl_surface_commit(o->surface); wl_surface_commit(o->surface);
} }
} }
@ -101,24 +116,13 @@ void waybar::Bar::layerSurfaceHandleClosed(void* data,
struct zwlr_layer_surface_v1* /*surface*/) struct zwlr_layer_surface_v1* /*surface*/)
{ {
auto o = static_cast<waybar::Bar *>(data); auto o = static_cast<waybar::Bar *>(data);
std::cout << "Bar removed from output: " + o->output_name << std::endl;
zwlr_layer_surface_v1_destroy(o->layer_surface); zwlr_layer_surface_v1_destroy(o->layer_surface);
o->layer_surface = nullptr; wl_output_destroy(*o->output);
wl_surface_destroy(o->surface); zxdg_output_v1_destroy(o->xdg_output_);
o->surface = nullptr; o->modules_left_.clear();
o->window.close(); o->modules_center_.clear();
} o->modules_right_.clear();
auto waybar::Bar::setWidth(uint32_t width) -> void
{
if (width == width_) {
return;
}
std::cout << fmt::format("Bar width configured: {}", width) << std::endl;
width_ = width;
window.set_size_request(width);
window.resize(width, height_);
zwlr_layer_surface_v1_set_size(layer_surface, width, height_ + 1);
wl_surface_commit(surface);
} }
auto waybar::Bar::toggle() -> void auto waybar::Bar::toggle() -> void
@ -154,6 +158,27 @@ auto waybar::Bar::setupCss() -> void
} }
} }
void waybar::Bar::getModules(Factory factory, const std::string& pos)
{
if (config_[pos]) {
for (const auto &name : config_[pos]) {
try {
if (pos == "modules-left") {
modules_left_.emplace_back(factory.makeModule(name.asString()));
}
if (pos == "modules-center") {
modules_center_.emplace_back(factory.makeModule(name.asString()));
}
if (pos == "modules-right") {
modules_right_.emplace_back(factory.makeModule(name.asString()));
}
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
}
}
}
}
auto waybar::Bar::setupWidgets() -> void auto waybar::Bar::setupWidgets() -> void
{ {
auto &left = *Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 0)); auto &left = *Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 0));
@ -167,30 +192,17 @@ auto waybar::Bar::setupWidgets() -> void
box.pack_end(right, true, true); box.pack_end(right, true, true);
Factory factory(*this, config_); Factory factory(*this, config_);
getModules(factory, "modules-left");
if (config_["modules-left"]) { getModules(factory, "modules-center");
for (const auto &name : config_["modules-left"]) { getModules(factory, "modules-right");
auto module = factory.makeModule(name.asString()); for (auto& module : modules_left_) {
if (module != nullptr) {
left.pack_start(*module, false, true, 0); left.pack_start(*module, false, true, 0);
} }
for (auto& module : modules_center_) {
center.pack_start(*module, true, true, 0);
} }
} std::reverse(modules_right_.begin(), modules_right_.end());
if (config_["modules-center"]) { for (auto& module : modules_right_) {
for (const auto &name : config_["modules-center"]) {
auto module = factory.makeModule(name.asString());
if (module != nullptr) {
center.pack_start(*module, true, false, 0);
}
}
}
if (config_["modules-right"]) {
std::reverse(config_["modules-right"].begin(), config_["modules-right"].end());
for (const auto &name : config_["modules-right"]) {
auto module = factory.makeModule(name.asString());
if (module != nullptr) {
right.pack_end(*module, false, false, 0); right.pack_end(*module, false, false, 0);
} }
}
}
} }

View File

@ -1,7 +1,8 @@
#include "client.hpp" #include "client.hpp"
waybar::Client::Client(int argc, char* argv[]) waybar::Client::Client(int argc, char* argv[])
: gtk_main(argc, argv), gdk_display(Gdk::Display::get_default()), : gtk_app(Gtk::Application::create(argc, argv, "org.alexays.waybar")),
gdk_display(Gdk::Display::get_default()),
wl_display(gdk_wayland_display_get_wl_display(gdk_display->gobj())) wl_display(gdk_wayland_display_get_wl_display(gdk_display->gobj()))
{ {
auto getFirstValidPath = [] (std::vector<std::string> possiblePaths) { auto getFirstValidPath = [] (std::vector<std::string> possiblePaths) {
@ -48,7 +49,7 @@ void waybar::Client::handleGlobal(void *data, struct wl_registry *registry,
*output = static_cast<struct wl_output *>(wl_registry_bind(registry, name, *output = static_cast<struct wl_output *>(wl_registry_bind(registry, name,
&wl_output_interface, version)); &wl_output_interface, version));
if (o->xdg_output_manager != nullptr) { if (o->xdg_output_manager != nullptr) {
o->bars.emplace_back(std::make_unique<Bar>(*o, std::move(output))); o->bars.emplace_back(std::make_unique<Bar>(*o, std::move(output), name));
} }
} else if (strcmp(interface, wl_seat_interface.name) == 0) { } else if (strcmp(interface, wl_seat_interface.name) == 0) {
o->seat = static_cast<struct wl_seat *>(wl_registry_bind(registry, name, o->seat = static_cast<struct wl_seat *>(wl_registry_bind(registry, name,
@ -61,10 +62,16 @@ void waybar::Client::handleGlobal(void *data, struct wl_registry *registry,
} }
} }
void waybar::Client::handleGlobalRemove(void* /*data*/, void waybar::Client::handleGlobalRemove(void* data,
struct wl_registry* /*registry*/, uint32_t /*name*/) struct wl_registry* /*registry*/, uint32_t name)
{ {
// TODO(someone) auto o = static_cast<waybar::Client *>(data);
for (auto it = o->bars.begin(); it != o->bars.end(); ++it) {
if ((**it).wl_name == name) {
o->bars.erase(it);
break;
}
}
} }
void waybar::Client::bindInterfaces() void waybar::Client::bindInterfaces()
@ -81,7 +88,8 @@ void waybar::Client::bindInterfaces()
int waybar::Client::main(int /*argc*/, char* /*argv*/[]) int waybar::Client::main(int /*argc*/, char* /*argv*/[])
{ {
bindInterfaces(); bindInterfaces();
Gtk::Main::run(); gtk_app->hold();
gtk_app->run();
bars.clear(); bars.clear();
zxdg_output_manager_v1_destroy(xdg_output_manager); zxdg_output_manager_v1_destroy(xdg_output_manager);
zwlr_layer_shell_v1_destroy(layer_shell); zwlr_layer_shell_v1_destroy(layer_shell);

View File

@ -4,7 +4,7 @@ waybar::Factory::Factory(Bar &bar, Json::Value config)
: _bar(bar), _config(std::move(config)) : _bar(bar), _config(std::move(config))
{} {}
waybar::IModule *waybar::Factory::makeModule(const std::string &name) waybar::IModule* waybar::Factory::makeModule(const std::string &name)
{ {
try { try {
if (name == "battery") { if (name == "battery") {
@ -34,13 +34,12 @@ waybar::IModule *waybar::Factory::makeModule(const std::string &name)
if (name.compare(0, 7, "custom/") == 0 && name.size() > 7) { if (name.compare(0, 7, "custom/") == 0 && name.size() > 7) {
return new waybar::modules::Custom(name.substr(7), _config[name]); return new waybar::modules::Custom(name.substr(7), _config[name]);
} }
std::cerr << "Unknown module: " + name << std::endl;
} catch (const std::exception& e) { } catch (const std::exception& e) {
auto err = fmt::format("Disabling module \"{}\", {}", name, e.what()); auto err = fmt::format("Disabling module \"{}\", {}", name, e.what());
std::cerr << err << std::endl; throw std::runtime_error(err);
} catch (...) { } catch (...) {
auto err = fmt::format("Disabling module \"{}\", Unknown reason", name); auto err = fmt::format("Disabling module \"{}\", Unknown reason", name);
std::cerr << err << std::endl; throw std::runtime_error(err);
} }
return nullptr; throw std::runtime_error("Unknown module: " + name);
} }

View File

@ -16,26 +16,32 @@ waybar::modules::Battery::Battery(Json::Value config)
if (batteries_.empty()) { if (batteries_.empty()) {
throw std::runtime_error("No batteries."); throw std::runtime_error("No batteries.");
} }
auto fd = inotify_init1(IN_CLOEXEC); fd_ = inotify_init1(IN_CLOEXEC);
if (fd == -1) { if (fd_ == -1) {
throw std::runtime_error("Unable to listen batteries."); throw std::runtime_error("Unable to listen batteries.");
} }
for (auto &bat : batteries_) { for (auto &bat : batteries_) {
inotify_add_watch(fd, (bat / "uevent").c_str(), IN_ACCESS); inotify_add_watch(fd_, (bat / "uevent").c_str(), IN_ACCESS);
} }
// Trigger first value // Trigger first values
Glib::signal_idle().connect_once(sigc::mem_fun(*this, &Battery::update)); update();
label_.set_name("battery"); label_.set_name("battery");
thread_ = [this, fd] { thread_.sig_update.connect(sigc::mem_fun(*this, &Battery::update));
thread_ = [this] {
struct inotify_event event = {0}; struct inotify_event event = {0};
int nbytes = read(fd, &event, sizeof(event)); int nbytes = read(fd_, &event, sizeof(event));
if (nbytes != sizeof(event)) { if (nbytes != sizeof(event)) {
return; return;
} }
Glib::signal_idle().connect_once(sigc::mem_fun(*this, &Battery::update)); thread_.sig_update.emit();
}; };
} }
waybar::modules::Battery::~Battery()
{
close(fd_);
}
auto waybar::modules::Battery::update() -> void auto waybar::modules::Battery::update() -> void
{ {
try { try {

View File

@ -5,9 +5,10 @@ waybar::modules::Clock::Clock(Json::Value config)
{ {
label_.set_name("clock"); label_.set_name("clock");
uint32_t interval = config_["interval"] ? config_["inveral"].asUInt() : 60; uint32_t interval = config_["interval"] ? config_["inveral"].asUInt() : 60;
thread_.sig_update.connect(sigc::mem_fun(*this, &Clock::update));
thread_ = [this, interval] { thread_ = [this, interval] {
auto now = waybar::chrono::clock::now(); auto now = waybar::chrono::clock::now();
Glib::signal_idle().connect_once(sigc::mem_fun(*this, &Clock::update)); thread_.sig_update.emit();
auto timeout = std::chrono::floor<std::chrono::seconds>(now auto timeout = std::chrono::floor<std::chrono::seconds>(now
+ std::chrono::seconds(interval)); + std::chrono::seconds(interval));
thread_.sleep_until(timeout); thread_.sleep_until(timeout);

View File

@ -5,8 +5,9 @@ waybar::modules::Cpu::Cpu(Json::Value config)
{ {
label_.set_name("cpu"); label_.set_name("cpu");
uint32_t interval = config_["interval"] ? config_["inveral"].asUInt() : 10; uint32_t interval = config_["interval"] ? config_["inveral"].asUInt() : 10;
thread_.sig_update.connect(sigc::mem_fun(*this, &Cpu::update));
thread_ = [this, interval] { thread_ = [this, interval] {
Glib::signal_idle().connect_once(sigc::mem_fun(*this, &Cpu::update)); thread_.sig_update.emit();
thread_.sleep_for(chrono::seconds(interval)); thread_.sleep_for(chrono::seconds(interval));
}; };
} }

View File

@ -16,10 +16,11 @@ waybar::modules::Custom::Custom(std::string name, Json::Value config)
} }
} }
if (can_update) { if (can_update) {
Glib::signal_idle().connect_once(sigc::mem_fun(*this, &Custom::update)); thread_.sig_update.emit();
} }
thread_.sleep_for(chrono::seconds(interval)); thread_.sleep_for(chrono::seconds(interval));
}; };
thread_.sig_update.connect(sigc::mem_fun(*this, &Custom::update));
} }
auto waybar::modules::Custom::update() -> void auto waybar::modules::Custom::update() -> void

View File

@ -5,8 +5,9 @@ waybar::modules::Memory::Memory(Json::Value config)
{ {
label_.set_name("memory"); label_.set_name("memory");
uint32_t interval = config_["interval"] ? config_["inveral"].asUInt() : 30; uint32_t interval = config_["interval"] ? config_["inveral"].asUInt() : 30;
thread_.sig_update.connect(sigc::mem_fun(*this, &Memory::update));
thread_ = [this, interval] { thread_ = [this, interval] {
Glib::signal_idle().connect_once(sigc::mem_fun(*this, &Memory::update)); thread_.sig_update.emit();
thread_.sleep_for(chrono::seconds(interval)); thread_.sleep_for(chrono::seconds(interval));
}; };
} }

View File

@ -29,8 +29,10 @@ waybar::modules::Network::Network(Json::Value config)
} }
} }
label_.set_name("network"); label_.set_name("network");
// Trigger first values
getInfo(); getInfo();
Glib::signal_idle().connect_once(sigc::mem_fun(*this, &Network::update)); update();
thread_.sig_update.connect(sigc::mem_fun(*this, &Network::update));
thread_ = [this] { thread_ = [this] {
char buf[4096]; char buf[4096];
uint64_t len = netlinkResponse(sock_fd_, buf, sizeof(buf), uint64_t len = netlinkResponse(sock_fd_, buf, sizeof(buf),
@ -67,11 +69,16 @@ waybar::modules::Network::Network(Json::Value config)
} }
if (need_update) { if (need_update) {
getInfo(); getInfo();
Glib::signal_idle().connect_once(sigc::mem_fun(*this, &Network::update)); thread_.sig_update.emit();
} }
}; };
} }
waybar::modules::Network::~Network()
{
close(sock_fd_);
}
auto waybar::modules::Network::update() -> void auto waybar::modules::Network::update() -> void
{ {
auto format = config_["format"] ? config_["format"].asString() : "{ifname}"; auto format = config_["format"] ? config_["format"].asString() : "{ifname}";

View File

@ -28,6 +28,13 @@ waybar::modules::Pulseaudio::Pulseaudio(Json::Value config)
pa_threaded_mainloop_unlock(mainloop_); pa_threaded_mainloop_unlock(mainloop_);
} }
waybar::modules::Pulseaudio::~Pulseaudio()
{
mainloop_api_->quit(mainloop_api_, 0);
pa_threaded_mainloop_stop(mainloop_);
pa_threaded_mainloop_free(mainloop_);
}
void waybar::modules::Pulseaudio::contextStateCb(pa_context *c, void *data) void waybar::modules::Pulseaudio::contextStateCb(pa_context *c, void *data)
{ {
auto pa = static_cast<waybar::modules::Pulseaudio *>(data); auto pa = static_cast<waybar::modules::Pulseaudio *>(data);

View File

@ -10,6 +10,7 @@ waybar::modules::sway::Window::Window(Bar &bar, Json::Value config)
ipc_eventfd_ = ipcOpenSocket(socketPath); ipc_eventfd_ = ipcOpenSocket(socketPath);
ipcSingleCommand(ipc_eventfd_, IPC_SUBSCRIBE, "[ \"window\" ]"); ipcSingleCommand(ipc_eventfd_, IPC_SUBSCRIBE, "[ \"window\" ]");
getFocusedWindow(); getFocusedWindow();
thread_.sig_update.connect(sigc::mem_fun(*this, &Window::update));
thread_ = [this] { thread_ = [this] {
try { try {
auto res = ipcRecvResponse(ipc_eventfd_); auto res = ipcRecvResponse(ipc_eventfd_);
@ -17,7 +18,7 @@ waybar::modules::sway::Window::Window(Bar &bar, Json::Value config)
if ((parsed["change"] == "focus" || parsed["change"] == "title") if ((parsed["change"] == "focus" || parsed["change"] == "title")
&& parsed["container"]["focused"].asBool()) { && parsed["container"]["focused"].asBool()) {
window_ = parsed["container"]["name"].asString(); window_ = parsed["container"]["name"].asString();
Glib::signal_idle().connect_once(sigc::mem_fun(*this, &Window::update)); thread_.sig_update.emit();
} }
} catch (const std::exception& e) { } catch (const std::exception& e) {
std::cerr << e.what() << std::endl; std::cerr << e.what() << std::endl;
@ -25,6 +26,12 @@ waybar::modules::sway::Window::Window(Bar &bar, Json::Value config)
}; };
} }
waybar::modules::sway::Window::~Window()
{
close(ipcfd_);
close(ipc_eventfd_);
}
auto waybar::modules::sway::Window::update() -> void auto waybar::modules::sway::Window::update() -> void
{ {
label_.set_text(window_); label_.set_text(window_);

View File

@ -9,30 +9,35 @@ waybar::modules::sway::Workspaces::Workspaces(Bar &bar, Json::Value config)
ipcfd_ = ipcOpenSocket(socketPath); ipcfd_ = ipcOpenSocket(socketPath);
ipc_eventfd_ = ipcOpenSocket(socketPath); ipc_eventfd_ = ipcOpenSocket(socketPath);
ipcSingleCommand(ipc_eventfd_, IPC_SUBSCRIBE, "[ \"workspace\" ]"); ipcSingleCommand(ipc_eventfd_, IPC_SUBSCRIBE, "[ \"workspace\" ]");
thread_.sig_update.connect(sigc::mem_fun(*this, &Workspaces::update));
thread_ = [this] { thread_ = [this] {
try { try {
// Wait for the name of the output // Wait for the name of the output
if (!config_["all-outputs"].asBool() && bar_.outputName.empty()) { if (!config_["all-outputs"].asBool() && bar_.output_name.empty()) {
while (bar_.outputName.empty()) { while (bar_.output_name.empty()) {
thread_.sleep_for(chrono::milliseconds(150)); thread_.sleep_for(chrono::milliseconds(150));
} }
} else if (!workspaces_.empty()) { } else if (!workspaces_.empty()) {
ipcRecvResponse(ipc_eventfd_); ipcRecvResponse(ipc_eventfd_);
} }
std::lock_guard<std::mutex> lock(mutex_); thread_.sig_update.emit();
auto res = ipcSingleCommand(ipcfd_, IPC_GET_WORKSPACES, "");
workspaces_ = parser_.parse(res.payload);
Glib::signal_idle()
.connect_once(sigc::mem_fun(*this, &Workspaces::update));
} catch (const std::exception& e) { } catch (const std::exception& e) {
std::cerr << e.what() << std::endl; std::cerr << e.what() << std::endl;
} }
}; };
} }
waybar::modules::sway::Workspaces::~Workspaces()
{
close(ipcfd_);
close(ipc_eventfd_);
}
auto waybar::modules::sway::Workspaces::update() -> void auto waybar::modules::sway::Workspaces::update() -> void
{ {
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
auto res = ipcSingleCommand(ipcfd_, IPC_GET_WORKSPACES, "");
workspaces_ = parser_.parse(res.payload);
bool needReorder = false; bool needReorder = false;
for (auto it = buttons_.begin(); it != buttons_.end();) { for (auto it = buttons_.begin(); it != buttons_.end();) {
auto ws = std::find_if(workspaces_.begin(), workspaces_.end(), auto ws = std::find_if(workspaces_.begin(), workspaces_.end(),
@ -46,7 +51,7 @@ auto waybar::modules::sway::Workspaces::update() -> void
} }
for (auto node : workspaces_) { for (auto node : workspaces_) {
if (!config_["all-outputs"].asBool() if (!config_["all-outputs"].asBool()
&& bar_.outputName != node["output"].asString()) { && bar_.output_name != node["output"].asString()) {
continue; continue;
} }
auto it = buttons_.find(node["num"].asInt()); auto it = buttons_.find(node["num"].asInt());