feat(Bar): handle widget size changes

This commit is contained in:
Alex 2019-04-24 12:37:24 +02:00
parent 90d89fe974
commit 311c34ecbc
28 changed files with 175 additions and 137 deletions

View File

@ -10,7 +10,7 @@ namespace waybar {
class ALabel : public IModule { class ALabel : public IModule {
public: public:
ALabel(const Json::Value &, const std::string format, uint16_t interval = 0); ALabel(const Json::Value &, const std::string &format, uint16_t interval = 0);
virtual ~ALabel(); virtual ~ALabel();
virtual auto update() -> void; virtual auto update() -> void;
virtual std::string getIcon(uint16_t, const std::string &alt = ""); virtual std::string getIcon(uint16_t, const std::string &alt = "");

View File

@ -56,7 +56,7 @@ class Bar {
void setupAltFormatKeyForModuleList(const char *module_list_name); void setupAltFormatKeyForModuleList(const char *module_list_name);
uint32_t width_ = 0; uint32_t width_ = 0;
uint32_t height_ = 30; uint32_t height_ = 1;
Gtk::Box left_; Gtk::Box left_;
Gtk::Box center_; Gtk::Box center_;
Gtk::Box right_; Gtk::Box right_;

View File

@ -25,10 +25,10 @@ class Client {
std::vector<std::unique_ptr<Bar>> bars; std::vector<std::unique_ptr<Bar>> bars;
private: private:
Client(); Client() = default;
void setupConfigs(const std::string &config, const std::string &style); void setupConfigs(const std::string &config, const std::string &style);
void bindInterfaces(); void bindInterfaces();
const std::string getValidPath(std::vector<std::string> paths); const std::string getValidPath(const std::vector<std::string> &paths);
void handleOutput(std::unique_ptr<struct waybar_output> &output); void handleOutput(std::unique_ptr<struct waybar_output> &output);
bool isValidOutput(const Json::Value &config, std::unique_ptr<struct waybar_output> &output); bool isValidOutput(const Json::Value &config, std::unique_ptr<struct waybar_output> &output);
auto setupConfig() -> void; auto setupConfig() -> void;

View File

@ -20,7 +20,7 @@ namespace waybar::modules::SNI {
class Item : public sigc::trackable { class Item : public sigc::trackable {
public: public:
Item(std::string, std::string, const Json::Value&); Item(const std::string&, const std::string&, const Json::Value&);
~Item() = default; ~Item() = default;
std::string bus_name; std::string bus_name;
@ -58,7 +58,7 @@ class Item : public sigc::trackable {
void updateImage(); void updateImage();
Glib::RefPtr<Gdk::Pixbuf> extractPixBuf(GVariant* variant); Glib::RefPtr<Gdk::Pixbuf> extractPixBuf(GVariant* variant);
Glib::RefPtr<Gdk::Pixbuf> getIconByName(std::string name, int size); Glib::RefPtr<Gdk::Pixbuf> getIconByName(const std::string& name, int size);
static void onMenuDestroyed(Item* self); static void onMenuDestroyed(Item* self);
bool makeMenu(GdkEventButton* const& ev); bool makeMenu(GdkEventButton* const& ev);
bool handleClick(GdkEventButton* const& /*ev*/); bool handleClick(GdkEventButton* const& /*ev*/);

View File

@ -24,8 +24,8 @@ class Ipc {
Json::Value payload; Json::Value payload;
}; };
sigc::signal<void, const struct ipc_response> signal_event; sigc::signal<void, const struct ipc_response&> signal_event;
sigc::signal<void, const struct ipc_response> signal_cmd; sigc::signal<void, const struct ipc_response&> signal_cmd;
void sendCmd(uint32_t type, const std::string &payload = ""); void sendCmd(uint32_t type, const std::string &payload = "");
void subscribe(const std::string &payload); void subscribe(const std::string &payload);

View File

@ -16,7 +16,7 @@ class Mode : public ALabel {
auto update() -> void; auto update() -> void;
private: private:
void onEvent(const struct Ipc::ipc_response); void onEvent(const struct Ipc::ipc_response&);
void worker(); void worker();
const Bar& bar_; const Bar& bar_;

View File

@ -17,10 +17,10 @@ class Window : public ALabel {
auto update() -> void; auto update() -> void;
private: private:
void onEvent(const struct Ipc::ipc_response); void onEvent(const struct Ipc::ipc_response&);
void onCmd(const struct Ipc::ipc_response); void onCmd(const struct Ipc::ipc_response&);
void worker(); void worker();
std::tuple<int, std::string> getFocusedNode(Json::Value nodes); std::tuple<int, std::string> getFocusedNode(const Json::Value& nodes);
void getFocusedWindow(); void getFocusedWindow();
const Bar& bar_; const Bar& bar_;

View File

@ -19,8 +19,8 @@ class Workspaces : public IModule {
operator Gtk::Widget&(); operator Gtk::Widget&();
private: private:
void onCmd(const struct Ipc::ipc_response); void onCmd(const struct Ipc::ipc_response&);
void onEvent(const struct Ipc::ipc_response); void onEvent(const struct Ipc::ipc_response&);
void worker(); void worker();
bool filterButtons(); bool filterButtons();
Gtk::Button& addButton(const Json::Value&); Gtk::Button& addButton(const Json::Value&);

View File

@ -1,7 +1,7 @@
{ {
"layer": "top", // Waybar at top layer "layer": "top", // Waybar at top layer
// "position": "bottom", // Waybar position (top|bottom|left|right) // "position": "bottom", // Waybar position (top|bottom|left|right)
// "height": 30, // Waybar height "height": 30, // Waybar height (to be removed for auto height)
// "width": 1280, // Waybar width // "width": 1280, // Waybar width
// Choose the order of the modules // Choose the order of the modules
"modules-left": ["sway/workspaces", "sway/mode", "custom/media"], "modules-left": ["sway/workspaces", "sway/mode", "custom/media"],

View File

@ -3,11 +3,11 @@
#include <iostream> #include <iostream>
waybar::ALabel::ALabel(const Json::Value& config, const std::string format, uint16_t interval) waybar::ALabel::ALabel(const Json::Value& config, const std::string& format, uint16_t interval)
: config_(config), : config_(config),
format_(config_["format"].isString() ? config_["format"].asString() : format), format_(config_["format"].isString() ? config_["format"].asString() : format),
interval_(config_["interval"] == "once" interval_(config_["interval"] == "once"
? std::chrono::seconds(100000000) ? std::chrono::seconds(std::numeric_limits<int>::infinity())
: std::chrono::seconds( : std::chrono::seconds(
config_["interval"].isUInt() ? config_["interval"].asUInt() : interval)), config_["interval"].isUInt() ? config_["interval"].asUInt() : interval)),
default_format_(format_) { default_format_(format_) {
@ -33,7 +33,7 @@ waybar::ALabel::ALabel(const Json::Value& config, const std::string format, uint
} }
waybar::ALabel::~ALabel() { waybar::ALabel::~ALabel() {
for (const auto &pid : pid_) { for (const auto& pid : pid_) {
if (pid != -1) { if (pid != -1) {
kill(-pid, 9); kill(-pid, 9);
} }

View File

@ -17,7 +17,7 @@ waybar::Bar::Bar(struct waybar_output* w_output)
if (output->config["position"] == "right" || output->config["position"] == "left") { if (output->config["position"] == "right" || output->config["position"] == "left") {
height_ = 0; height_ = 0;
width_ = 30; width_ = 1;
} }
window.set_size_request(width_, height_); window.set_size_request(width_, height_);
@ -42,6 +42,38 @@ waybar::Bar::Bar(struct waybar_output* w_output)
auto height = output->config["height"].isUInt() ? output->config["height"].asUInt() : height_; auto height = output->config["height"].isUInt() ? output->config["height"].asUInt() : height_;
auto width = output->config["width"].isUInt() ? output->config["width"].asUInt() : width_; auto width = output->config["width"].isUInt() ? output->config["width"].asUInt() : width_;
window.signal_configure_event().connect_notify([&](GdkEventConfigure* ev) {
auto tmp_height = height_;
auto tmp_width = width_;
if (ev->height > static_cast<int>(height_)) {
// Default minimal value
if (height_ != 1) {
std::cout << fmt::format(MIN_HEIGHT_MSG, height_, ev->height) << std::endl;
}
if (output->config["height"].isUInt()) {
std::cout << "Height size is defined in the config file so it will stay like that"
<< std::endl;
} else {
tmp_height = ev->height;
}
}
if (ev->width > static_cast<int>(width_)) {
// Default minimal value
if (width_ != 1) {
std::cout << fmt::format(MIN_WIDTH_MSG, width_, ev->width) << std::endl;
}
if (output->config["width"].isUInt()) {
std::cout << "Height size is defined in the config file so it will stay like that"
<< std::endl;
} else {
tmp_width = ev->width;
}
}
if (tmp_width != width_ || tmp_height != height_) {
zwlr_layer_surface_v1_set_size(layer_surface, tmp_width, tmp_height);
}
});
std::size_t anchor = ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP; std::size_t anchor = ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP;
if (output->config["position"] == "bottom") { if (output->config["position"] == "bottom") {
anchor = ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM; anchor = ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM;
@ -83,21 +115,21 @@ void waybar::Bar::setupAltFormatKeyForModule(const std::string& module_name) {
std::string str_click = click.asString(); std::string str_click = click.asString();
if (str_click == "click-right") { if (str_click == "click-right") {
module["format-alt-click"] = 3u; module["format-alt-click"] = 3U;
} else if (str_click == "click-middle") { } else if (str_click == "click-middle") {
module["format-alt-click"] = 2u; module["format-alt-click"] = 2U;
} else if (str_click == "click-backward") { } else if (str_click == "click-backward") {
module["format-alt-click"] = 8u; module["format-alt-click"] = 8U;
} else if (str_click == "click-forward") { } else if (str_click == "click-forward") {
module["format-alt-click"] = 9u; module["format-alt-click"] = 9U;
} else { } else {
module["format-alt-click"] = 1u; // default click-left module["format-alt-click"] = 1U; // default click-left
} }
} else { } else {
module["format-alt-click"] = 1u; module["format-alt-click"] = 1U;
} }
} else { } else {
module["format-alt-click"] = 1u; module["format-alt-click"] = 1U;
} }
} }
} }
@ -117,15 +149,21 @@ void waybar::Bar::setupAltFormatKeyForModuleList(const char* module_list_name) {
void waybar::Bar::handleSignal(int signal) { void waybar::Bar::handleSignal(int signal) {
for (auto& module : modules_left_) { for (auto& module : modules_left_) {
auto* custom = dynamic_cast<waybar::modules::Custom*>(module.get()); auto* custom = dynamic_cast<waybar::modules::Custom*>(module.get());
if (custom) custom->refresh(signal); if (custom != nullptr) {
custom->refresh(signal);
}
} }
for (auto& module : modules_center_) { for (auto& module : modules_center_) {
auto* custom = dynamic_cast<waybar::modules::Custom*>(module.get()); auto* custom = dynamic_cast<waybar::modules::Custom*>(module.get());
if (custom) custom->refresh(signal); if (custom != nullptr) {
custom->refresh(signal);
}
} }
for (auto& module : modules_right_) { for (auto& module : modules_right_) {
auto* custom = dynamic_cast<waybar::modules::Custom*>(module.get()); auto* custom = dynamic_cast<waybar::modules::Custom*>(module.get());
if (custom) custom->refresh(signal); if (custom != nullptr) {
custom->refresh(signal);
}
} }
} }
@ -137,19 +175,13 @@ void waybar::Bar::layerSurfaceHandleConfigure(void* data, struct zwlr_layer_surf
o->height_ = height; o->height_ = height;
o->window.set_size_request(o->width_, o->height_); o->window.set_size_request(o->width_, o->height_);
o->window.resize(o->width_, o->height_); o->window.resize(o->width_, o->height_);
zwlr_layer_surface_v1_set_exclusive_zone(o->layer_surface,
int min_width, min_height; o->vertical ? o->width_ : o->height_);
o->window.get_size(min_width, min_height); std::cout << fmt::format(BAR_SIZE_MSG,
if (o->height_ < static_cast<uint32_t>(min_height)) { o->width_ == 1 ? "auto" : std::to_string(o->width_),
std::cout << fmt::format(MIN_HEIGHT_MSG, o->height_, min_height) << std::endl; o->height_ == 1 ? "auto" : std::to_string(o->height_),
o->height_ = min_height; o->output->name)
} << std::endl;
if (o->width_ < static_cast<uint32_t>(min_width)) {
std::cout << fmt::format(MIN_WIDTH_MSG, o->height_, min_width) << std::endl;
o->width_ = min_width;
}
std::cout << fmt::format(BAR_SIZE_MSG, o->width_, o->height_, o->output->name) << std::endl;
wl_surface_commit(o->surface); wl_surface_commit(o->surface);
} }
zwlr_layer_surface_v1_ack_configure(surface, serial); zwlr_layer_surface_v1_ack_configure(surface, serial);

View File

@ -4,14 +4,12 @@
#include "util/clara.hpp" #include "util/clara.hpp"
#include "util/json.hpp" #include "util/json.hpp"
waybar::Client::Client() {}
waybar::Client *waybar::Client::inst() { waybar::Client *waybar::Client::inst() {
static Client *c = new Client(); static auto c = new Client();
return c; return c;
} }
const std::string waybar::Client::getValidPath(std::vector<std::string> paths) { const std::string waybar::Client::getValidPath(const std::vector<std::string> &paths) {
wordexp_t p; wordexp_t p;
for (const std::string &path : paths) { for (const std::string &path : paths) {
@ -212,7 +210,7 @@ void waybar::Client::bindInterfaces() {
}; };
wl_registry_add_listener(registry, &registry_listener, this); wl_registry_add_listener(registry, &registry_listener, this);
wl_display_roundtrip(wl_display); wl_display_roundtrip(wl_display);
if (!layer_shell || !xdg_output_manager) { if (layer_shell == nullptr || xdg_output_manager == nullptr) {
throw std::runtime_error("Failed to acquire required resources."); throw std::runtime_error("Failed to acquire required resources.");
} }
} }

View File

@ -4,7 +4,7 @@ waybar::Factory::Factory(const Bar& bar, const Json::Value& config) : bar_(bar),
waybar::IModule* waybar::Factory::makeModule(const std::string& name) const { waybar::IModule* waybar::Factory::makeModule(const std::string& name) const {
try { try {
auto hash_pos = name.find("#"); auto hash_pos = name.find('#');
auto ref = name.substr(0, hash_pos); auto ref = name.substr(0, hash_pos);
auto id = hash_pos != std::string::npos ? name.substr(hash_pos + 1) : ""; auto id = hash_pos != std::string::npos ? name.substr(hash_pos + 1) : "";
if (ref == "battery") { if (ref == "battery") {

View File

@ -120,9 +120,9 @@ waybar::modules::Backlight::Backlight(const std::string &name, const Json::Value
auto udev_fd = udev_monitor_get_fd(mon.get()); auto udev_fd = udev_monitor_get_fd(mon.get());
auto epoll_fd = FileDescriptor{epoll_create1(0)}; auto epoll_fd = FileDescriptor{epoll_create1(EPOLL_CLOEXEC)};
check_neq(epoll_fd.get(), -1, "epoll init failed: "); check_neq(epoll_fd.get(), -1, "epoll init failed: ");
epoll_event ctl_event; epoll_event ctl_event{};
ctl_event.events = EPOLLIN; ctl_event.events = EPOLLIN;
ctl_event.data.fd = udev_fd; ctl_event.data.fd = udev_fd;

View File

@ -115,7 +115,7 @@ const std::string waybar::modules::Battery::getState(uint8_t capacity) const {
if (config_["states"].isObject()) { if (config_["states"].isObject()) {
for (auto it = config_["states"].begin(); it != config_["states"].end(); ++it) { for (auto it = config_["states"].begin(); it != config_["states"].end(); ++it) {
if (it->isUInt() && it.key().isString()) { if (it->isUInt() && it.key().isString()) {
states.push_back({it.key().asString(), it->asUInt()}); states.emplace_back(it.key().asString(), it->asUInt());
} }
} }
} }

View File

@ -14,10 +14,11 @@ waybar::modules::Clock::Clock(const std::string& id, const Json::Value& config)
auto sub_m = auto sub_m =
std::chrono::duration_cast<std::chrono::seconds>(time_s.time_since_epoch()).count() % std::chrono::duration_cast<std::chrono::seconds>(time_s.time_since_epoch()).count() %
interval_.count(); interval_.count();
if (sub_m > 0) if (sub_m > 0) {
thread_.sleep_until(timeout - std::chrono::seconds(sub_m - 1)); thread_.sleep_until(timeout - std::chrono::seconds(sub_m - 1));
else } else {
thread_.sleep_until(timeout - std::chrono::seconds(sub_m)); thread_.sleep_until(timeout - std::chrono::seconds(sub_m));
}
}; };
} }

View File

@ -25,7 +25,7 @@ auto waybar::modules::Cpu::update() -> void {
uint16_t waybar::modules::Cpu::getCpuLoad() { uint16_t waybar::modules::Cpu::getCpuLoad() {
struct sysinfo info = {0}; struct sysinfo info = {0};
if (sysinfo(&info) == 0) { if (sysinfo(&info) == 0) {
float f_load = 1.f / (1u << SI_LOAD_SHIFT); float f_load = 1.F / (1U << SI_LOAD_SHIFT);
uint16_t load = info.loads[0] * f_load * 100 / get_nprocs(); uint16_t load = info.loads[0] * f_load * 100 / get_nprocs();
return load; return load;
} }
@ -70,7 +70,7 @@ std::vector<std::tuple<size_t, size_t>> waybar::modules::Cpu::parseCpuinfo() {
} }
std::stringstream sline(line.substr(5)); std::stringstream sline(line.substr(5));
std::vector<size_t> times; std::vector<size_t> times;
for (size_t time; sline >> time; times.push_back(time)) for (size_t time = 0; sline >> time; times.push_back(time))
; ;
size_t idle_time = 0; size_t idle_time = 0;
@ -79,7 +79,7 @@ std::vector<std::tuple<size_t, size_t>> waybar::modules::Cpu::parseCpuinfo() {
idle_time = times[3]; idle_time = times[3];
total_time = std::accumulate(times.begin(), times.end(), 0); total_time = std::accumulate(times.begin(), times.end(), 0);
} }
cpuinfo.push_back({idle_time, total_time}); cpuinfo.emplace_back(idle_time, total_time);
} }
return cpuinfo; return cpuinfo;
} }

View File

@ -19,7 +19,7 @@ waybar::modules::IdleInhibitor::IdleInhibitor(const std::string& id, const Bar&
} }
waybar::modules::IdleInhibitor::~IdleInhibitor() { waybar::modules::IdleInhibitor::~IdleInhibitor() {
if (idle_inhibitor_) { if (idle_inhibitor_ != nullptr) {
zwp_idle_inhibitor_v1_destroy(idle_inhibitor_); zwp_idle_inhibitor_v1_destroy(idle_inhibitor_);
idle_inhibitor_ = nullptr; idle_inhibitor_ = nullptr;
} }
@ -41,7 +41,7 @@ auto waybar::modules::IdleInhibitor::update() -> void {
bool waybar::modules::IdleInhibitor::handleToggle(GdkEventButton* const& e) { bool waybar::modules::IdleInhibitor::handleToggle(GdkEventButton* const& e) {
if (e->button == 1) { if (e->button == 1) {
label_.get_style_context()->remove_class(status_); label_.get_style_context()->remove_class(status_);
if (idle_inhibitor_) { if (idle_inhibitor_ != nullptr) {
zwp_idle_inhibitor_v1_destroy(idle_inhibitor_); zwp_idle_inhibitor_v1_destroy(idle_inhibitor_);
idle_inhibitor_ = nullptr; idle_inhibitor_ = nullptr;
status_ = "deactivated"; status_ = "deactivated";

View File

@ -28,19 +28,19 @@ auto waybar::modules::Memory::update() -> void {
} }
void waybar::modules::Memory::parseMeminfo() { void waybar::modules::Memory::parseMeminfo() {
long memfree = -1, membuffer = -1, memcache = -1, memavail = -1; int64_t memfree = -1, membuffer = -1, memcache = -1, memavail = -1;
std::ifstream info(data_dir_); std::ifstream info(data_dir_);
if (!info.is_open()) { if (!info.is_open()) {
throw std::runtime_error("Can't open " + data_dir_); throw std::runtime_error("Can't open " + data_dir_);
} }
std::string line; std::string line;
while (getline(info, line)) { while (getline(info, line)) {
auto posDelim = line.find(":"); auto posDelim = line.find(':');
if (posDelim == std::string::npos) { if (posDelim == std::string::npos) {
continue; continue;
} }
std::string name = line.substr(0, posDelim); std::string name = line.substr(0, posDelim);
long value = std::stol(line.substr(posDelim + 1)); int64_t value = std::stol(line.substr(posDelim + 1));
if (name.compare("MemTotal") == 0) { if (name.compare("MemTotal") == 0) {
memtotal_ = value; memtotal_ = value;

View File

@ -68,7 +68,7 @@ void waybar::modules::Network::createInfoSocket() {
nl_socket_disable_seq_check(info_sock_); nl_socket_disable_seq_check(info_sock_);
nl_socket_set_nonblocking(info_sock_); nl_socket_set_nonblocking(info_sock_);
nl_socket_modify_cb(info_sock_, NL_CB_VALID, NL_CB_CUSTOM, handleEvents, this); nl_socket_modify_cb(info_sock_, NL_CB_VALID, NL_CB_CUSTOM, handleEvents, this);
efd_ = epoll_create1(0); efd_ = epoll_create1(EPOLL_CLOEXEC);
if (efd_ < 0) { if (efd_ < 0) {
throw std::runtime_error("Can't create epoll"); throw std::runtime_error("Can't create epoll");
} }
@ -114,7 +114,7 @@ void waybar::modules::Network::worker() {
} }
thread_timer_.sleep_for(interval_); thread_timer_.sleep_for(interval_);
}; };
std::array<struct epoll_event, EPOLL_MAX> events; std::array<struct epoll_event, EPOLL_MAX> events{};
thread_ = [this, &events] { thread_ = [this, &events] {
int ec = epoll_wait(efd_, events.data(), EPOLL_MAX, -1); int ec = epoll_wait(efd_, events.data(), EPOLL_MAX, -1);
if (ec > 0) { if (ec > 0) {

View File

@ -99,9 +99,13 @@ bool waybar::modules::Pulseaudio::handleScroll(GdkEventScroll *e) {
} }
if (direction_up) { if (direction_up) {
if (volume_ + 1 < 100) pa_cvolume_inc(&pa_volume, change); if (volume_ + 1 < 100) {
pa_cvolume_inc(&pa_volume, change);
}
} else { } else {
if (volume_ - 1 > 0) pa_cvolume_dec(&pa_volume, change); if (volume_ - 1 > 0) {
pa_cvolume_dec(&pa_volume, change);
}
} }
pa_context_set_sink_volume_by_index(context_, sink_idx_, &pa_volume, volumeModifyCb, this); pa_context_set_sink_volume_by_index(context_, sink_idx_, &pa_volume, volumeModifyCb, this);
@ -116,13 +120,8 @@ void waybar::modules::Pulseaudio::subscribeCb(pa_context * conte
pa_subscription_event_type_t type, uint32_t idx, pa_subscription_event_type_t type, uint32_t idx,
void *data) { void *data) {
unsigned facility = type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK; unsigned facility = type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK;
if (facility == PA_SUBSCRIPTION_EVENT_SINK) {
switch (facility) { pa_context_get_sink_info_by_index(context, idx, sinkInfoCb, data);
case PA_SUBSCRIPTION_EVENT_SINK:
pa_context_get_sink_info_by_index(context, idx, sinkInfoCb, data);
break;
default:
break;
} }
} }
@ -131,7 +130,7 @@ void waybar::modules::Pulseaudio::subscribeCb(pa_context * conte
*/ */
void waybar::modules::Pulseaudio::volumeModifyCb(pa_context *c, int success, void *data) { void waybar::modules::Pulseaudio::volumeModifyCb(pa_context *c, int success, void *data) {
auto pa = static_cast<waybar::modules::Pulseaudio *>(data); auto pa = static_cast<waybar::modules::Pulseaudio *>(data);
if (success) { if (success != 0) {
pa_context_get_sink_info_by_index(pa->context_, pa->sink_idx_, sinkInfoCb, data); pa_context_get_sink_info_by_index(pa->context_, pa->sink_idx_, sinkInfoCb, data);
} }
} }
@ -146,10 +145,10 @@ void waybar::modules::Pulseaudio::sinkInfoCb(pa_context * /*context*/, const pa_
pa->pa_volume_ = i->volume; pa->pa_volume_ = i->volume;
float volume = static_cast<float>(pa_cvolume_avg(&(pa->pa_volume_))) / float{PA_VOLUME_NORM}; float volume = static_cast<float>(pa_cvolume_avg(&(pa->pa_volume_))) / float{PA_VOLUME_NORM};
pa->sink_idx_ = i->index; pa->sink_idx_ = i->index;
pa->volume_ = std::round(volume * 100.0f); pa->volume_ = std::round(volume * 100.0F);
pa->muted_ = i->mute != 0; pa->muted_ = i->mute != 0;
pa->desc_ = i->description; pa->desc_ = i->description;
pa->port_name_ = i->active_port ? i->active_port->name : "Unknown"; pa->port_name_ = i->active_port != nullptr ? i->active_port->name : "Unknown";
pa->dp.emit(); pa->dp.emit();
} }
} }

View File

@ -1,8 +1,7 @@
#include "modules/sni/host.hpp" #include "modules/sni/host.hpp"
#include <iostream> #include <iostream>
using namespace waybar::modules::SNI; namespace waybar::modules::SNI {
Host::Host(const std::size_t id, const Json::Value& config, Host::Host(const std::size_t id, const Json::Value& config,
const std::function<void(std::unique_ptr<Item>&)>& on_add, const std::function<void(std::unique_ptr<Item>&)>& on_add,
@ -96,7 +95,7 @@ void Host::registerHost(GObject* src, GAsyncResult* res, gpointer data) {
g_signal_connect(host->watcher_, "item-registered", G_CALLBACK(&Host::itemRegistered), data); g_signal_connect(host->watcher_, "item-registered", G_CALLBACK(&Host::itemRegistered), data);
g_signal_connect(host->watcher_, "item-unregistered", G_CALLBACK(&Host::itemUnregistered), data); g_signal_connect(host->watcher_, "item-unregistered", G_CALLBACK(&Host::itemUnregistered), data);
auto items = sn_watcher_dup_registered_items(host->watcher_); auto items = sn_watcher_dup_registered_items(host->watcher_);
if (items) { if (items != nullptr) {
for (uint32_t i = 0; items[i] != nullptr; i += 1) { for (uint32_t i = 0; items[i] != nullptr; i += 1) {
host->addRegisteredItem(items[i]); host->addRegisteredItem(items[i]);
} }
@ -122,7 +121,7 @@ void Host::itemUnregistered(SnWatcher* watcher, const gchar* service, gpointer d
} }
std::tuple<std::string, std::string> Host::getBusNameAndObjectPath(const std::string service) { std::tuple<std::string, std::string> Host::getBusNameAndObjectPath(const std::string service) {
auto it = service.find("/"); auto it = service.find('/');
if (it != std::string::npos) { if (it != std::string::npos) {
return {service.substr(0, it), service.substr(it)}; return {service.substr(0, it), service.substr(it)};
} }
@ -134,3 +133,5 @@ void Host::addRegisteredItem(std::string service) {
items_.emplace_back(new Item(bus_name, object_path, config_)); items_.emplace_back(new Item(bus_name, object_path, config_));
on_add_(items_.back()); on_add_(items_.back());
} }
}

View File

@ -1,14 +1,13 @@
#include "modules/sni/item.hpp" #include "modules/sni/item.hpp"
#include <glibmm/main.h> #include <glibmm/main.h>
#include <iostream> #include <iostream>
using namespace Glib; namespace waybar::modules::SNI {
static const ustring SNI_INTERFACE_NAME = sn_item_interface_info()->name; static const Glib::ustring SNI_INTERFACE_NAME = sn_item_interface_info()->name;
static const unsigned UPDATE_DEBOUNCE_TIME = 10; static const unsigned UPDATE_DEBOUNCE_TIME = 10;
waybar::modules::SNI::Item::Item(std::string bn, std::string op, const Json::Value& config) Item::Item(const std::string& bn, const std::string& op, const Json::Value& config)
: bus_name(bn), : bus_name(bn),
object_path(op), object_path(op),
icon_size(16), icon_size(16),
@ -34,7 +33,7 @@ waybar::modules::SNI::Item::Item(std::string bn, std::string op, const Json::Val
interface); interface);
} }
void waybar::modules::SNI::Item::proxyReady(Glib::RefPtr<Gio::AsyncResult>& result) { void Item::proxyReady(Glib::RefPtr<Gio::AsyncResult>& result) {
try { try {
this->proxy_ = Gio::DBus::Proxy::create_for_bus_finish(result); this->proxy_ = Gio::DBus::Proxy::create_for_bus_finish(result);
/* Properties are already cached during object creation */ /* Properties are already cached during object creation */
@ -69,11 +68,11 @@ void waybar::modules::SNI::Item::proxyReady(Glib::RefPtr<Gio::AsyncResult>& resu
} }
template <typename T> template <typename T>
T get_variant(VariantBase& value) { T get_variant(Glib::VariantBase& value) {
return VariantBase::cast_dynamic<Variant<T>>(value).get(); return Glib::VariantBase::cast_dynamic<Glib::Variant<T>>(value).get();
} }
void waybar::modules::SNI::Item::setProperty(const ustring& name, VariantBase& value) { void Item::setProperty(const Glib::ustring& name, Glib::VariantBase& value) {
if (name == "Category") { if (name == "Category") {
category = get_variant<std::string>(value); category = get_variant<std::string>(value);
} else if (name == "Id") { } else if (name == "Id") {
@ -112,29 +111,30 @@ void waybar::modules::SNI::Item::setProperty(const ustring& name, VariantBase& v
} }
} }
void waybar::modules::SNI::Item::getUpdatedProperties() { void Item::getUpdatedProperties() {
update_pending_ = false; update_pending_ = false;
auto params = VariantContainerBase::create_tuple({Variant<ustring>::create(SNI_INTERFACE_NAME)}); auto params = Glib::VariantContainerBase::create_tuple(
{Glib::Variant<Glib::ustring>::create(SNI_INTERFACE_NAME)});
proxy_->call("org.freedesktop.DBus.Properties.GetAll", proxy_->call("org.freedesktop.DBus.Properties.GetAll",
sigc::mem_fun(*this, &Item::processUpdatedProperties), sigc::mem_fun(*this, &Item::processUpdatedProperties),
params); params);
}; };
void waybar::modules::SNI::Item::processUpdatedProperties(Glib::RefPtr<Gio::AsyncResult>& _result) { void Item::processUpdatedProperties(Glib::RefPtr<Gio::AsyncResult>& _result) {
try { try {
auto result = proxy_->call_finish(_result); auto result = proxy_->call_finish(_result);
// extract "a{sv}" from VariantContainerBase // extract "a{sv}" from VariantContainerBase
Variant<std::map<ustring, VariantBase>> properties_variant; Glib::Variant<std::map<Glib::ustring, Glib::VariantBase>> properties_variant;
result.get_child(properties_variant); result.get_child(properties_variant);
auto properties = properties_variant.get(); auto properties = properties_variant.get();
for (const auto& [name, value] : properties) { for (const auto& [name, value] : properties) {
VariantBase old_value; Glib::VariantBase old_value;
proxy_->get_cached_property(old_value, name); proxy_->get_cached_property(old_value, name);
if (!value.equal(old_value)) { if (!value.equal(old_value)) {
proxy_->set_cached_property(name, value); proxy_->set_cached_property(name, value);
setProperty(name, const_cast<VariantBase&>(value)); setProperty(name, const_cast<Glib::VariantBase&>(value));
} }
} }
@ -147,8 +147,8 @@ void waybar::modules::SNI::Item::processUpdatedProperties(Glib::RefPtr<Gio::Asyn
} }
} }
void waybar::modules::SNI::Item::onSignal(const ustring& sender_name, const ustring& signal_name, void Item::onSignal(const Glib::ustring& sender_name, const Glib::ustring& signal_name,
const VariantContainerBase& arguments) { const Glib::VariantContainerBase& arguments) {
if (!update_pending_ && signal_name.compare(0, 3, "New") == 0) { if (!update_pending_ && signal_name.compare(0, 3, "New") == 0) {
/* Debounce signals and schedule update of all properties. /* Debounce signals and schedule update of all properties.
* Based on behavior of Plasma dataengine for StatusNotifierItem. * Based on behavior of Plasma dataengine for StatusNotifierItem.
@ -161,7 +161,7 @@ void waybar::modules::SNI::Item::onSignal(const ustring& sender_name, const ustr
static void pixbuf_data_deleter(const guint8* data) { g_free((void*)data); } static void pixbuf_data_deleter(const guint8* data) { g_free((void*)data); }
Glib::RefPtr<Gdk::Pixbuf> waybar::modules::SNI::Item::extractPixBuf(GVariant* variant) { Glib::RefPtr<Gdk::Pixbuf> Item::extractPixBuf(GVariant* variant) {
GVariantIter* it; GVariantIter* it;
g_variant_get(variant, "a(iiay)", &it); g_variant_get(variant, "a(iiay)", &it);
if (it == nullptr) { if (it == nullptr) {
@ -213,7 +213,7 @@ Glib::RefPtr<Gdk::Pixbuf> waybar::modules::SNI::Item::extractPixBuf(GVariant* va
return Glib::RefPtr<Gdk::Pixbuf>{}; return Glib::RefPtr<Gdk::Pixbuf>{};
} }
void waybar::modules::SNI::Item::updateImage() { void Item::updateImage() {
image.set_from_icon_name("image-missing", Gtk::ICON_SIZE_MENU); image.set_from_icon_name("image-missing", Gtk::ICON_SIZE_MENU);
image.set_pixel_size(icon_size); image.set_pixel_size(icon_size);
if (!icon_name.empty()) { if (!icon_name.empty()) {
@ -244,8 +244,7 @@ void waybar::modules::SNI::Item::updateImage() {
} }
} }
Glib::RefPtr<Gdk::Pixbuf> waybar::modules::SNI::Item::getIconByName(std::string name, Glib::RefPtr<Gdk::Pixbuf> Item::getIconByName(const std::string& name, int request_size) {
int request_size) {
int tmp_size = 0; int tmp_size = 0;
icon_theme->rescan_if_needed(); icon_theme->rescan_if_needed();
auto sizes = icon_theme->get_icon_sizes(name.c_str()); auto sizes = icon_theme->get_icon_sizes(name.c_str());
@ -277,12 +276,12 @@ Glib::RefPtr<Gdk::Pixbuf> waybar::modules::SNI::Item::getIconByName(std::string
name.c_str(), tmp_size, Gtk::IconLookupFlags::ICON_LOOKUP_FORCE_SIZE); name.c_str(), tmp_size, Gtk::IconLookupFlags::ICON_LOOKUP_FORCE_SIZE);
} }
void waybar::modules::SNI::Item::onMenuDestroyed(Item* self) { void Item::onMenuDestroyed(Item* self) {
self->gtk_menu = nullptr; self->gtk_menu = nullptr;
self->dbus_menu = nullptr; self->dbus_menu = nullptr;
} }
bool waybar::modules::SNI::Item::makeMenu(GdkEventButton* const& ev) { bool Item::makeMenu(GdkEventButton* const& ev) {
if (gtk_menu == nullptr) { if (gtk_menu == nullptr) {
if (!menu.empty()) { if (!menu.empty()) {
dbus_menu = dbusmenu_gtkmenu_new(bus_name.data(), menu.data()); dbus_menu = dbusmenu_gtkmenu_new(bus_name.data(), menu.data());
@ -305,9 +304,9 @@ bool waybar::modules::SNI::Item::makeMenu(GdkEventButton* const& ev) {
return false; return false;
} }
bool waybar::modules::SNI::Item::handleClick(GdkEventButton* const& ev) { bool Item::handleClick(GdkEventButton* const& ev) {
auto parameters = VariantContainerBase::create_tuple( auto parameters = Glib::VariantContainerBase::create_tuple(
{Variant<int>::create(ev->x), Variant<int>::create(ev->y)}); {Glib::Variant<int>::create(ev->x), Glib::Variant<int>::create(ev->y)});
if ((ev->button == 1 && item_is_menu) || ev->button == 3) { if ((ev->button == 1 && item_is_menu) || ev->button == 3) {
if (!makeMenu(ev)) { if (!makeMenu(ev)) {
proxy_->call("ContextMenu", parameters); proxy_->call("ContextMenu", parameters);
@ -322,3 +321,5 @@ bool waybar::modules::SNI::Item::handleClick(GdkEventButton* const& ev) {
} }
return false; return false;
} }
} // namespace waybar::modules::SNI

View File

@ -1,36 +1,42 @@
#include "modules/sni/tray.hpp" #include "modules/sni/tray.hpp"
#include <iostream> #include <iostream>
waybar::modules::SNI::Tray::Tray(const std::string& id, const Bar& bar, const Json::Value& config) namespace waybar::modules::SNI {
Tray::Tray(const std::string& id, const Bar& bar, const Json::Value& config)
: config_(config), : config_(config),
box_(bar.vertical ? Gtk::ORIENTATION_VERTICAL : Gtk::ORIENTATION_HORIZONTAL, 0), box_(bar.vertical ? Gtk::ORIENTATION_VERTICAL : Gtk::ORIENTATION_HORIZONTAL, 0),
watcher_(),
host_(nb_hosts_, config, std::bind(&Tray::onAdd, this, std::placeholders::_1), host_(nb_hosts_, config, std::bind(&Tray::onAdd, this, std::placeholders::_1),
std::bind(&Tray::onRemove, this, std::placeholders::_1)) { std::bind(&Tray::onRemove, this, std::placeholders::_1)) {
box_.set_name("tray");
if (!id.empty()) {
box_.get_style_context()->add_class(id);
}
if (config_["spacing"].isUInt()) { if (config_["spacing"].isUInt()) {
box_.set_spacing(config_["spacing"].asUInt()); box_.set_spacing(config_["spacing"].asUInt());
} }
nb_hosts_ += 1; nb_hosts_ += 1;
dp.emit();
} }
void waybar::modules::SNI::Tray::onAdd(std::unique_ptr<Item>& item) { void Tray::onAdd(std::unique_ptr<Item>& item) {
box_.pack_start(item->event_box); box_.pack_start(item->event_box);
dp.emit(); dp.emit();
} }
void waybar::modules::SNI::Tray::onRemove(std::unique_ptr<Item>& item) { void Tray::onRemove(std::unique_ptr<Item>& item) {
box_.remove(item->event_box); box_.remove(item->event_box);
dp.emit(); dp.emit();
} }
auto waybar::modules::SNI::Tray::update() -> void { auto Tray::update() -> void {
if (box_.get_children().size() > 0) { if (box_.get_children().empty()) {
box_.set_name("tray"); box_.hide();
box_.show_all();
} else { } else {
box_.set_name(""); box_.show_all();
} }
} }
waybar::modules::SNI::Tray::operator Gtk::Widget&() { return box_; } Tray::operator Gtk::Widget&() { return box_; }
}

View File

@ -19,14 +19,14 @@ Watcher::~Watcher() {
bus_name_id_ = 0; bus_name_id_ = 0;
} }
if (hosts_ != NULL) { if (hosts_ != nullptr) {
g_slist_free_full(hosts_, gfWatchFree); g_slist_free_full(hosts_, gfWatchFree);
hosts_ = NULL; hosts_ = nullptr;
} }
if (items_ != NULL) { if (items_ != nullptr) {
g_slist_free_full(items_, gfWatchFree); g_slist_free_full(items_, gfWatchFree);
items_ = NULL; items_ = nullptr;
} }
g_dbus_interface_skeleton_unexport(G_DBUS_INTERFACE_SKELETON(watcher_)); g_dbus_interface_skeleton_unexport(G_DBUS_INTERFACE_SKELETON(watcher_));
} }
@ -122,7 +122,7 @@ gboolean Watcher::handleRegisterItem(Watcher* obj, GDBusMethodInvocation* invoca
Watcher::GfWatch* Watcher::gfWatchFind(GSList* list, const gchar* bus_name, Watcher::GfWatch* Watcher::gfWatchFind(GSList* list, const gchar* bus_name,
const gchar* object_path) { const gchar* object_path) {
for (GSList* l = list; l != nullptr; l = g_slist_next(l)) { for (GSList* l = list; l != nullptr; l = g_slist_next(l)) {
GfWatch* watch = static_cast<GfWatch*>(l->data); auto watch = static_cast<GfWatch*>(l->data);
if (g_strcmp0(watch->bus_name, bus_name) == 0 && if (g_strcmp0(watch->bus_name, bus_name) == 0 &&
g_strcmp0(watch->object_path, object_path) == 0) { g_strcmp0(watch->object_path, object_path) == 0) {
return watch; return watch;
@ -132,11 +132,11 @@ Watcher::GfWatch* Watcher::gfWatchFind(GSList* list, const gchar* bus_name,
} }
void Watcher::gfWatchFree(gpointer data) { void Watcher::gfWatchFree(gpointer data) {
GfWatch* watch; auto watch = static_cast<GfWatch*>(data);
watch = (GfWatch*)data; if (watch->watch_id > 0) {
g_bus_unwatch_name(watch->watch_id);
if (watch->watch_id > 0) g_bus_unwatch_name(watch->watch_id); }
g_free(watch->service); g_free(watch->service);
g_free(watch->bus_name); g_free(watch->bus_name);
@ -184,8 +184,8 @@ void Watcher::updateRegisteredItems(SnWatcher* obj) {
GVariantBuilder builder; GVariantBuilder builder;
g_variant_builder_init(&builder, G_VARIANT_TYPE("as")); g_variant_builder_init(&builder, G_VARIANT_TYPE("as"));
for (GSList* l = items_; l != nullptr; l = g_slist_next(l)) { for (GSList* l = items_; l != nullptr; l = g_slist_next(l)) {
GfWatch* watch = static_cast<GfWatch*>(l->data); auto watch = static_cast<GfWatch*>(l->data);
gchar* item = g_strdup_printf("%s%s", watch->bus_name, watch->object_path); gchar* item = g_strdup_printf("%s%s", watch->bus_name, watch->object_path);
g_variant_builder_add(&builder, "s", item); g_variant_builder_add(&builder, "s", item);
g_free(item); g_free(item);
} }

View File

@ -8,14 +8,14 @@ Mode::Mode(const std::string& id, const Bar& bar, const Json::Value& config)
if (!id.empty()) { if (!id.empty()) {
label_.get_style_context()->add_class(id); label_.get_style_context()->add_class(id);
} }
ipc_.subscribe("[ \"mode\" ]"); ipc_.subscribe(R"(["mode"])");
ipc_.signal_event.connect(sigc::mem_fun(*this, &Mode::onEvent)); ipc_.signal_event.connect(sigc::mem_fun(*this, &Mode::onEvent));
// Launch worker // Launch worker
worker(); worker();
dp.emit(); dp.emit();
} }
void Mode::onEvent(const struct Ipc::ipc_response res) { void Mode::onEvent(const struct Ipc::ipc_response &res) {
if (res.payload["change"] != "default") { if (res.payload["change"] != "default") {
mode_ = res.payload["change"].asString(); mode_ = res.payload["change"].asString();
} else { } else {

View File

@ -12,7 +12,7 @@ Window::Window(const std::string& id, const Bar& bar, const Json::Value& config)
label_.set_hexpand(true); label_.set_hexpand(true);
label_.set_ellipsize(Pango::EllipsizeMode::ELLIPSIZE_END); label_.set_ellipsize(Pango::EllipsizeMode::ELLIPSIZE_END);
} }
ipc_.subscribe("[\"window\",\"workspace\"]"); ipc_.subscribe(R"(["window","workspace"])");
ipc_.signal_event.connect(sigc::mem_fun(*this, &Window::onEvent)); ipc_.signal_event.connect(sigc::mem_fun(*this, &Window::onEvent));
ipc_.signal_cmd.connect(sigc::mem_fun(*this, &Window::onCmd)); ipc_.signal_cmd.connect(sigc::mem_fun(*this, &Window::onCmd));
getFocusedWindow(); getFocusedWindow();
@ -20,7 +20,7 @@ Window::Window(const std::string& id, const Bar& bar, const Json::Value& config)
worker(); worker();
} }
void Window::onEvent(const struct Ipc::ipc_response res) { void Window::onEvent(const struct Ipc::ipc_response& res) {
auto data = res.payload; auto data = res.payload;
// Check for waybar prevents flicker when hovering window module // Check for waybar prevents flicker when hovering window module
if ((data["change"] == "focus" || data["change"] == "title") && if ((data["change"] == "focus" || data["change"] == "title") &&
@ -38,7 +38,7 @@ void Window::onEvent(const struct Ipc::ipc_response res) {
} }
} }
void Window::onCmd(const struct Ipc::ipc_response res) { void Window::onCmd(const struct Ipc::ipc_response& res) {
auto [id, name] = getFocusedNode(res.payload["nodes"]); auto [id, name] = getFocusedNode(res.payload["nodes"]);
windowId_ = id; windowId_ = id;
window_ = name; window_ = name;
@ -62,7 +62,7 @@ auto Window::update() -> void {
} }
} }
std::tuple<int, std::string> Window::getFocusedNode(Json::Value nodes) { std::tuple<int, std::string> Window::getFocusedNode(const Json::Value& nodes) {
for (auto const& node : nodes) { for (auto const& node : nodes) {
if (node["focused"].asBool() && node["type"] == "con") { if (node["focused"].asBool() && node["type"] == "con") {
return {node["id"].asInt(), node["name"].asString()}; return {node["id"].asInt(), node["name"].asString()};

View File

@ -11,7 +11,7 @@ Workspaces::Workspaces(const std::string &id, const Bar &bar, const Json::Value
if (!id.empty()) { if (!id.empty()) {
box_.get_style_context()->add_class(id); box_.get_style_context()->add_class(id);
} }
ipc_.subscribe("[ \"workspace\" ]"); ipc_.subscribe(R"(["workspace"])");
ipc_.signal_event.connect(sigc::mem_fun(*this, &Workspaces::onEvent)); ipc_.signal_event.connect(sigc::mem_fun(*this, &Workspaces::onEvent));
ipc_.signal_cmd.connect(sigc::mem_fun(*this, &Workspaces::onCmd)); ipc_.signal_cmd.connect(sigc::mem_fun(*this, &Workspaces::onCmd));
ipc_.sendCmd(IPC_GET_WORKSPACES); ipc_.sendCmd(IPC_GET_WORKSPACES);
@ -19,9 +19,9 @@ Workspaces::Workspaces(const std::string &id, const Bar &bar, const Json::Value
worker(); worker();
} }
void Workspaces::onEvent(const struct Ipc::ipc_response res) { ipc_.sendCmd(IPC_GET_WORKSPACES); } void Workspaces::onEvent(const struct Ipc::ipc_response &res) { ipc_.sendCmd(IPC_GET_WORKSPACES); }
void Workspaces::onCmd(const struct Ipc::ipc_response res) { void Workspaces::onCmd(const struct Ipc::ipc_response &res) {
if (res.type == IPC_GET_WORKSPACES) { if (res.type == IPC_GET_WORKSPACES) {
if (res.payload.isArray()) { if (res.payload.isArray()) {
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
@ -209,7 +209,7 @@ const std::string Workspaces::getCycleWorkspace(std::vector<Json::Value>::iterat
} }
std::string Workspaces::trimWorkspaceName(std::string name) { std::string Workspaces::trimWorkspaceName(std::string name) {
std::size_t found = name.find(":"); std::size_t found = name.find(':');
if (found != std::string::npos) { if (found != std::string::npos) {
return name.substr(found + 1); return name.substr(found + 1);
} }