Merge branch 'master' into features/temperature-hwmon-by-name

This commit is contained in:
Alexis Rouillard
2026-07-03 22:11:04 +02:00
committed by GitHub
206 changed files with 4667 additions and 2519 deletions
+26 -21
View File
@@ -33,21 +33,21 @@ std::string toLowerCase(const std::string& input) {
std::optional<std::string> getFileBySuffix(const std::string& dir, const std::string& suffix,
bool check_lower_case) {
if (!std::filesystem::exists(dir)) {
return {};
}
for (const auto& entry : std::filesystem::recursive_directory_iterator(dir)) {
if (entry.is_regular_file()) {
std::string filename = entry.path().filename().string();
if (filename.size() < suffix.size()) {
continue;
}
if ((filename.compare(filename.size() - suffix.size(), suffix.size(), suffix) == 0) ||
(check_lower_case && filename.compare(filename.size() - suffix.size(), suffix.size(),
toLowerCase(suffix)) == 0)) {
return entry.path().string();
try {
for (const auto& entry : std::filesystem::recursive_directory_iterator(dir)) {
if (entry.is_regular_file()) {
std::string filename = entry.path().filename().string();
if (filename.size() < suffix.size()) {
continue;
}
if ((filename.compare(filename.size() - suffix.size(), suffix.size(), suffix) == 0) ||
(check_lower_case && filename.compare(filename.size() - suffix.size(), suffix.size(),
toLowerCase(suffix)) == 0)) {
return entry.path().string();
}
}
}
} catch (const std::filesystem::filesystem_error&) {
}
return {};
@@ -151,19 +151,24 @@ void AAppIconLabel::updateAppIconName(const std::string& app_identifier,
}
void AAppIconLabel::updateAppIcon() {
if (update_app_icon_) {
if (update_app_icon_ || (!iconEnabled() && image_.get_visible())) {
update_app_icon_ = false;
if (app_icon_name_.empty()) {
image_.set_visible(false);
} else if (app_icon_name_.front() == '/') {
auto pixbuf = Gdk::Pixbuf::create_from_file(app_icon_name_);
int scaled_icon_size = app_icon_size_ * image_.get_scale_factor();
pixbuf = Gdk::Pixbuf::create_from_file(app_icon_name_, scaled_icon_size, scaled_icon_size);
try {
int scaled_icon_size = app_icon_size_ * image_.get_scale_factor();
auto pixbuf =
Gdk::Pixbuf::create_from_file(app_icon_name_, scaled_icon_size, scaled_icon_size);
auto surface = Gdk::Cairo::create_surface_from_pixbuf(pixbuf, image_.get_scale_factor(),
image_.get_window());
image_.set(surface);
image_.set_visible(true);
auto surface = Gdk::Cairo::create_surface_from_pixbuf(pixbuf, image_.get_scale_factor(),
image_.get_window());
image_.set(surface);
image_.set_visible(true);
} catch (const Glib::Exception& e) {
spdlog::warn("Failed to load app icon {}: {}", app_icon_name_, std::string(e.what()));
image_.set_visible(false);
}
} else {
image_.set_from_icon_name(app_icon_name_, Gtk::ICON_SIZE_INVALID);
image_.set_visible(true);
+2 -2
View File
@@ -5,8 +5,8 @@
namespace waybar {
AIconLabel::AIconLabel(const Json::Value &config, const std::string &name, const std::string &id,
const std::string &format, uint16_t interval, bool ellipsize,
AIconLabel::AIconLabel(const Json::Value& config, const std::string& name, const std::string& id,
const std::string& format, uint16_t interval, bool ellipsize,
bool enable_click, bool enable_scroll)
: ALabel(config, name, id, format, interval, ellipsize, enable_click, enable_scroll) {
event_box_.remove();
+37 -5
View File
@@ -26,7 +26,7 @@ ALabel::ALabel(const Json::Value& config, const std::string& name, const std::st
: std::chrono::milliseconds(
(config_["interval"].isNumeric()
? std::max(1L, // Minimum 1ms due to millisecond precision
static_cast<long>(config_["interval"].asDouble()) * 1000)
static_cast<long>(config_["interval"].asDouble() * 1000))
: 1000 * (long)interval))),
default_format_(format_) {
label_.set_name(name);
@@ -91,13 +91,17 @@ ALabel::ALabel(const Json::Value& config, const std::string& name, const std::st
// Make the GtkBuilder and check for errors in his parsing
if (gtk_builder_add_from_string(builder, fileContent.str().c_str(), -1, nullptr) == 0U) {
g_object_unref(builder);
throw std::runtime_error("Error found in the file " + menuFile);
}
menu_ = gtk_builder_get_object(builder, "menu");
if (menu_ == nullptr) {
g_object_unref(builder);
throw std::runtime_error("Failed to get 'menu' object from GtkBuilder");
}
// Keep the menu alive after dropping the transient GtkBuilder.
g_object_ref(menu_);
submenus_ = std::map<std::string, GtkMenuItem*>();
menuActionsMap_ = std::map<std::string, std::string>();
@@ -105,11 +109,17 @@ ALabel::ALabel(const Json::Value& config, const std::string& name, const std::st
for (Json::Value::const_iterator it = config_["menu-actions"].begin();
it != config_["menu-actions"].end(); ++it) {
std::string key = it.key().asString();
submenus_[key] = GTK_MENU_ITEM(gtk_builder_get_object(builder, key.c_str()));
auto* item = gtk_builder_get_object(builder, key.c_str());
if (item == nullptr) {
spdlog::warn("Menu item '{}' not found in builder file", key);
continue;
}
submenus_[key] = GTK_MENU_ITEM(item);
menuActionsMap_[key] = it->asString();
g_signal_connect(submenus_[key], "activate", G_CALLBACK(handleGtkMenuEvent),
(gpointer)menuActionsMap_[key].c_str());
}
g_object_unref(builder);
} catch (std::runtime_error& e) {
spdlog::warn("Error while creating the menu : {}. Menu popup not activated.", e.what());
}
@@ -129,6 +139,26 @@ ALabel::ALabel(const Json::Value& config, const std::string& name, const std::st
auto ALabel::update() -> void { AModule::update(); }
bool ALabel::setLabelMarkup(const Glib::ustring& markup) {
if (last_label_markup_ == markup) {
return false;
}
label_.set_markup(markup);
last_label_markup_ = markup;
return true;
}
bool ALabel::setTooltipMarkup(const Glib::ustring& markup) {
if (last_tooltip_markup_ == markup) {
return false;
}
label_.set_tooltip_markup(markup);
last_tooltip_markup_ = markup;
return true;
}
std::string ALabel::getIcon(uint16_t percentage, const std::string& alt, uint16_t max) {
auto format_icons = config_["format-icons"];
if (format_icons.isObject()) {
@@ -141,7 +171,8 @@ std::string ALabel::getIcon(uint16_t percentage, const std::string& alt, uint16_
if (format_icons.isArray()) {
auto size = format_icons.size();
if (size != 0U) {
auto idx = std::clamp(percentage / ((max == 0 ? 100 : max) / size), 0U, size - 1);
auto divisor = std::max(1U, (max == 0 ? 100U : static_cast<unsigned>(max)) / size);
auto idx = std::clamp(percentage / divisor, 0U, size - 1);
format_icons = format_icons[idx];
}
}
@@ -167,7 +198,8 @@ std::string ALabel::getIcon(uint16_t percentage, const std::vector<std::string>&
if (format_icons.isArray()) {
auto size = format_icons.size();
if (size != 0U) {
auto idx = std::clamp(percentage / ((max == 0 ? 100 : max) / size), 0U, size - 1);
auto divisor = std::max(1U, (max == 0 ? 100U : static_cast<unsigned>(max)) / size);
auto idx = std::clamp(percentage / divisor, 0U, size - 1);
format_icons = format_icons[idx];
}
}
@@ -190,7 +222,7 @@ bool waybar::ALabel::handleToggle(GdkEventButton* const& e) {
}
void ALabel::handleGtkMenuEvent(GtkMenuItem* /*menuitem*/, gpointer data) {
waybar::util::command::res res = waybar::util::command::exec((char*)data, "GtkMenu");
waybar::util::command::forkExec((char*)data, "GtkMenu");
}
std::string ALabel::getState(uint8_t value, bool lesser) {
+21 -6
View File
@@ -17,10 +17,14 @@ AModule::AModule(const Json::Value& config, const std::string& name, const std::
isTooltip{config_["tooltip"].isBool() ? config_["tooltip"].asBool() : true},
isExpand{config_["expand"].isBool() ? config_["expand"].asBool() : false},
distance_scrolled_y_(0.0),
distance_scrolled_x_(0.0) {
distance_scrolled_x_(0.0),
cursor_timeout_conn_() {
// Configure module action Map
const Json::Value actions{config_["actions"]};
disable_on_sleep_ =
config_["disable-on-sleep"].isBool() ? config_["disable-on-sleep"].asBool() : false;
for (Json::Value::const_iterator it = actions.begin(); it != actions.end(); ++it) {
if (it.key().isString() && it->isString())
if (!eventActionMap_.contains(it.key().asString())) {
@@ -72,8 +76,12 @@ AModule::AModule(const Json::Value& config, const std::string& name, const std::
// Respect user configuration of cursor
if (config_.isMember("cursor")) {
if (config_["cursor"].isBool() && config_["cursor"].asBool()) {
setCursor(Gdk::HAND2);
if (config_["cursor"].isBool()) {
if (config_["cursor"].asBool()) {
setCursor(Gdk::HAND2);
} else {
setCursor(Gdk::ARROW);
}
} else if (config_["cursor"].isInt()) {
setCursor(Gdk::CursorType(config_["cursor"].asInt()));
} else {
@@ -83,11 +91,18 @@ AModule::AModule(const Json::Value& config, const std::string& name, const std::
}
AModule::~AModule() {
if (cursor_timeout_conn_.connected()) {
cursor_timeout_conn_.disconnect();
}
for (const auto& pid : pid_children_) {
if (pid != -1) {
killpg(pid, SIGTERM);
}
}
if (menu_ != nullptr) {
g_object_unref(menu_);
menu_ = nullptr;
}
}
auto AModule::update() -> void {
@@ -114,7 +129,7 @@ void AModule::setCursor(Gdk::CursorType const& c) {
} else {
// window may not be accessible yet, in this case,
// schedule another call for setting the cursor in 1 sec
Glib::signal_timeout().connect_seconds(
cursor_timeout_conn_ = Glib::signal_timeout().connect_seconds(
[this, c]() {
setCursor(c);
return false;
@@ -166,9 +181,9 @@ bool AModule::handleUserEvent(GdkEventButton* const& e) {
}
// Check that a menu has been configured
if (config_["menu"].isString()) {
if (rec != eventMap_.cend() && config_["menu"].isString()) {
// Check if the event is the one specified for the "menu" option
if (rec->second == config_["menu"].asString()) {
if (rec->second == config_["menu"].asString() && menu_ != nullptr) {
// Popup the menu
gtk_widget_show_all(GTK_WIDGET(menu_));
gtk_menu_popup_at_pointer(GTK_MENU(menu_), reinterpret_cast<GdkEvent*>(e));
+73 -6
View File
@@ -172,6 +172,10 @@ waybar::Bar::Bar(struct waybar_output* w_output, const Json::Value& w_config)
right_.set_spacing(spacing);
}
if (config.isMember("height") && !config["height"].isUInt()) {
spdlog::warn("Invalid type for 'height', expected unsigned integer");
}
height_ = config["height"].isUInt() ? config["height"].asUInt() : 0;
width_ = config["width"].isUInt() ? config["width"].asUInt() : 0;
@@ -229,7 +233,8 @@ waybar::Bar::Bar(struct waybar_output* w_output, const Json::Value& w_config)
gtk_layer_init_for_window(gtk_window);
gtk_layer_set_keyboard_mode(gtk_window, GTK_LAYER_SHELL_KEYBOARD_MODE_NONE);
gtk_layer_set_monitor(gtk_window, output->monitor->gobj());
gtk_layer_set_namespace(gtk_window, "waybar");
gtk_layer_set_namespace(gtk_window,
config["name"].isString() ? config["name"].asCString() : "waybar");
gtk_layer_set_margin(gtk_window, GTK_LAYER_SHELL_EDGE_LEFT, margins_.left);
gtk_layer_set_margin(gtk_window, GTK_LAYER_SHELL_EDGE_RIGHT, margins_.right);
@@ -262,6 +267,16 @@ waybar::Bar::Bar(struct waybar_output* w_output, const Json::Value& w_config)
window.signal_map_event().connect_notify(sigc::mem_fun(*this, &Bar::onMap));
window.signal_unmap().connect([this]() {
spdlog::debug("Output {} unmapped (DPMS off), suspending modules", output->name);
toggleSuspend(true);
});
window.signal_map().connect([this]() {
spdlog::debug("Output {} mapped (DPMS on), resuming modules", output->name);
toggleSuspend(false);
});
#if HAVE_SWAY
if (auto ipc = config["ipc"]; ipc.isBool() && ipc.asBool()) {
bar_id = Client::inst()->bar_id;
@@ -308,6 +323,19 @@ waybar::Bar::Bar(struct waybar_output* w_output, const Json::Value& w_config)
setupWidgets();
window.show_all();
/*
* If gtk-layer-shell's synchronous wait for the initial configure timed out, show_all() can
* return with a configured but not-yet-presented surface. Kick GTK/layer-shell once control has
* returned to the main loop, when any late initial configure has been dispatched and widgets have
* had a chance to allocate/draw.
*/
Glib::signal_idle().connect(sigc::track_obj([this] {
window.queue_resize();
window.queue_draw();
forceLayerCommit();
return false;
}, *this));
if (spdlog::should_log(spdlog::level::debug)) {
// Unfortunately, this function isn't in the C++ bindings, so we have to call the C version.
char* gtk_tree = gtk_style_context_to_string(
@@ -373,7 +401,14 @@ void waybar::Bar::setMode(const struct bar_mode& mode) {
* gtk-layer-shell schedules a commit on the next frame event in GTK, but this could fail in
* certain scenarios, such as fully occluded bar.
*/
gtk_layer_try_force_commit(gtk_window);
forceLayerCommit();
}
void waybar::Bar::forceLayerCommit() {
auto* gtk_window = window.gobj();
if (gtk_window != nullptr && gtk_widget_get_realized(GTK_WIDGET(gtk_window))) {
gtk_layer_try_force_commit(gtk_window);
}
wl_display_flush(Client::inst()->wl_display);
}
@@ -540,13 +575,15 @@ void waybar::Bar::getModules(const Factory& factory, const std::string& pos,
auto vertical = (group != nullptr ? group->getBox().get_orientation()
: box_.get_orientation()) == Gtk::ORIENTATION_VERTICAL;
auto group_config = config[ref];
const Json::Value& group_config = config[ref];
if (group_config["modules"].isNull()) {
spdlog::warn("Group definition '{}' has not been found, group will be hidden", ref);
}
auto* group_module = new waybar::Group(id_name, class_name, group_config, vertical);
getModules(factory, ref, group_module);
module = group_module;
auto group_module =
std::make_unique<waybar::Group>(id_name, class_name, group_config, vertical);
getModules(factory, ref, group_module.get());
module = group_module.release();
} else {
module = factory.makeModule(ref, pos);
}
@@ -649,6 +686,17 @@ void waybar::Bar::onConfigure(GdkEventConfigure* ev) {
configureGlobalOffset(ev->width, ev->height);
spdlog::info(BAR_SIZE_MSG, ev->width, ev->height, output->name);
/*
* gtk-layer-shell waits for the compositor's initial configure while realizing the window. On a
* busy compositor (common during session startup) that wait can time out even though the initial
* configure arrives shortly afterwards. In that case GTK may not schedule the frame commit that
* presents the first layer-surface buffer, leaving an otherwise configured bar invisible. Force a
* commit after every configure so late initial configures, and later compositor-driven resizes,
* always result in a submitted surface state.
*/
window.queue_draw();
forceLayerCommit();
}
void waybar::Bar::configureGlobalOffset(int width, int height) {
@@ -693,3 +741,22 @@ void waybar::Bar::configureGlobalOffset(int width, int height) {
void waybar::Bar::onOutputGeometryChanged() {
configureGlobalOffset(window.get_width(), window.get_height());
}
void waybar::Bar::toggleSuspend(bool suspend) {
auto process_modules = [suspend](Gtk::Box& module_box) {
for (auto* widget : module_box.get_children()) {
auto* module = dynamic_cast<waybar::AModule*>(widget);
if (module && module->shouldSuspend()) {
if (suspend) {
module->suspend();
} else {
module->resume();
}
}
}
};
process_modules(left_);
process_modules(center_);
process_modules(right_);
}
+85 -45
View File
@@ -10,61 +10,74 @@
#include "idle-inhibit-unstable-v1-client-protocol.h"
#include "util/clara.hpp"
#include "util/format.hpp"
#include "util/hex_checker.hpp"
waybar::Client *waybar::Client::inst() {
static auto *c = new Client();
waybar::Client* waybar::Client::inst() {
static auto* c = new Client();
return c;
}
void waybar::Client::handleGlobal(void *data, struct wl_registry *registry, uint32_t name,
const char *interface, uint32_t version) {
auto *client = static_cast<Client *>(data);
void waybar::Client::handleGlobal(void* data, struct wl_registry* registry, uint32_t name,
const char* interface, uint32_t version) {
auto* client = static_cast<Client*>(data);
if (strcmp(interface, zxdg_output_manager_v1_interface.name) == 0 &&
version >= ZXDG_OUTPUT_V1_NAME_SINCE_VERSION) {
client->xdg_output_manager = static_cast<struct zxdg_output_manager_v1 *>(wl_registry_bind(
if (client->xdg_output_manager != nullptr) {
zxdg_output_manager_v1_destroy(client->xdg_output_manager);
client->xdg_output_manager = nullptr;
}
client->xdg_output_manager = static_cast<struct zxdg_output_manager_v1*>(wl_registry_bind(
registry, name, &zxdg_output_manager_v1_interface, ZXDG_OUTPUT_V1_NAME_SINCE_VERSION));
} else if (strcmp(interface, zwp_idle_inhibit_manager_v1_interface.name) == 0) {
client->idle_inhibit_manager = static_cast<struct zwp_idle_inhibit_manager_v1 *>(
if (client->idle_inhibit_manager != nullptr) {
zwp_idle_inhibit_manager_v1_destroy(client->idle_inhibit_manager);
client->idle_inhibit_manager = nullptr;
}
client->idle_inhibit_manager = static_cast<struct zwp_idle_inhibit_manager_v1*>(
wl_registry_bind(registry, name, &zwp_idle_inhibit_manager_v1_interface, 1));
}
}
void waybar::Client::handleGlobalRemove(void *data, struct wl_registry * /*registry*/,
void waybar::Client::handleGlobalRemove(void* data, struct wl_registry* /*registry*/,
uint32_t name) {
// Nothing here
}
void waybar::Client::handleOutput(struct waybar_output &output) {
void waybar::Client::handleOutput(struct waybar_output& output) {
static const struct zxdg_output_v1_listener xdgOutputListener = {
.logical_position = [](void *, struct zxdg_output_v1 *, int32_t, int32_t) {},
.logical_size = [](void *, struct zxdg_output_v1 *, int32_t, int32_t) {},
.logical_position = [](void*, struct zxdg_output_v1*, int32_t, int32_t) {},
.logical_size = [](void*, struct zxdg_output_v1*, int32_t, int32_t) {},
.done = &handleOutputDone,
.name = &handleOutputName,
.description = &handleOutputDescription,
};
// owned by output->monitor; no need to destroy
auto *wl_output = gdk_wayland_monitor_get_wl_output(output.monitor->gobj());
auto* wl_output = gdk_wayland_monitor_get_wl_output(output.monitor->gobj());
output.xdg_output.reset(zxdg_output_manager_v1_get_xdg_output(xdg_output_manager, wl_output));
zxdg_output_v1_add_listener(output.xdg_output.get(), &xdgOutputListener, &output);
}
struct waybar::waybar_output &waybar::Client::getOutput(void *addr) {
struct waybar::waybar_output& waybar::Client::getOutput(void* addr) {
auto it = std::find_if(outputs_.begin(), outputs_.end(),
[&addr](const auto &output) { return &output == addr; });
[&addr](const auto& output) { return &output == addr; });
if (it == outputs_.end()) {
throw std::runtime_error("Unable to find valid output");
}
return *it;
}
std::vector<Json::Value> waybar::Client::getOutputConfigs(struct waybar_output &output) {
std::vector<Json::Value> waybar::Client::getOutputConfigs(struct waybar_output& output) {
return config.getOutputConfigs(output.name, output.identifier);
}
void waybar::Client::handleOutputDone(void *data, struct zxdg_output_v1 * /*xdg_output*/) {
auto *client = waybar::Client::inst();
void waybar::Client::handleOutputDone(void* data, struct zxdg_output_v1* /*xdg_output*/) {
auto* client = waybar::Client::inst();
try {
auto &output = client->getOutput(data);
auto& output = client->getOutput(data);
/**
* Multiple .done events may arrive in batch. In this case libwayland would queue
* xdg_output.destroy and dispatch all pending events, triggering this callback several times
@@ -78,46 +91,68 @@ void waybar::Client::handleOutputDone(void *data, struct zxdg_output_v1 * /*xdg_
output.xdg_output.reset();
spdlog::debug("Output detection done: {} ({})", output.name, output.identifier);
auto configs = client->getOutputConfigs(output);
if (!configs.empty()) {
for (const auto &config : configs) {
client->bars.emplace_back(std::make_unique<Bar>(&output, config));
}
client->pending_outputs_.push_back(&output);
if (!client->bars_scheduled_) {
client->bars_scheduled_ = true;
Glib::signal_idle().connect_once([client]() {
client->createBarsBatch();
}, Glib::PRIORITY_HIGH_IDLE);
}
}
} catch (const std::exception &e) {
} catch (const std::exception& e) {
spdlog::warn("caught exception in zxdg_output_v1_listener::done: {}", e.what());
}
}
void waybar::Client::handleOutputName(void *data, struct zxdg_output_v1 * /*xdg_output*/,
const char *name) {
auto *client = waybar::Client::inst();
void waybar::Client::createBarsBatch() {
pending_outputs_.remove_if([this](auto* output) { return std::none_of(outputs_.begin(), outputs_.end(), [&output](const auto& o) { return &o == output; }); });
for (auto* output : pending_outputs_) {
try {
auto configs = getOutputConfigs(*output);
if (!configs.empty()) {
for (const auto& config : configs) {
bars.emplace_back(std::make_unique<Bar>(output, config));
}
}
} catch (const std::exception& e) {
spdlog::warn("Error creating bar: {}", e.what());
}
}
pending_outputs_.clear();
bars_scheduled_ = false;
}
void waybar::Client::handleOutputName(void* data, struct zxdg_output_v1* /*xdg_output*/,
const char* name) {
auto* client = waybar::Client::inst();
try {
auto &output = client->getOutput(data);
auto& output = client->getOutput(data);
output.name = name;
} catch (const std::exception &e) {
} catch (const std::exception& e) {
spdlog::warn("caught exception in zxdg_output_v1_listener::name: {}", e.what());
}
}
void waybar::Client::handleOutputDescription(void *data, struct zxdg_output_v1 * /*xdg_output*/,
const char *description) {
auto *client = waybar::Client::inst();
void waybar::Client::handleOutputDescription(void* data, struct zxdg_output_v1* /*xdg_output*/,
const char* description) {
auto* client = waybar::Client::inst();
try {
auto &output = client->getOutput(data);
auto& output = client->getOutput(data);
// Description format: "identifier (name)"
auto s = std::string(description);
auto pos = s.find(" (");
output.identifier = pos != std::string::npos ? s.substr(0, pos) : s;
} catch (const std::exception &e) {
} catch (const std::exception& e) {
spdlog::warn("caught exception in zxdg_output_v1_listener::description: {}", e.what());
}
}
void waybar::Client::handleMonitorAdded(Glib::RefPtr<Gdk::Monitor> monitor) {
auto &output = outputs_.emplace_back();
auto& output = outputs_.emplace_back();
output.monitor = std::move(monitor);
handleOutput(output);
}
@@ -146,10 +181,10 @@ void waybar::Client::handleDeferredMonitorRemoval(Glib::RefPtr<Gdk::Monitor> mon
++it;
}
}
outputs_.remove_if([&monitor](const auto &output) { return output.monitor == monitor; });
outputs_.remove_if([&monitor](const auto& output) { return output.monitor == monitor; });
}
const std::string waybar::Client::getStyle(const std::string &style,
const std::string waybar::Client::getStyle(const std::string& style,
std::optional<Appearance> appearance = std::nullopt) {
auto gtk_settings = Gtk::Settings::get_default();
std::optional<std::string> css_file;
@@ -182,7 +217,7 @@ const std::string waybar::Client::getStyle(const std::string &style,
return css_file.value();
};
auto waybar::Client::setupCss(const std::string &css_file) -> void {
auto waybar::Client::setupCss(const std::string& css_file) -> void {
auto screen = Gdk::Screen::get_default();
if (!screen) {
throw std::runtime_error("No default screen");
@@ -194,11 +229,15 @@ auto waybar::Client::setupCss(const std::string &css_file) -> void {
}
css_provider_ = Gtk::CssProvider::create();
if (!css_provider_->load_from_path(css_file)) {
css_provider_.reset();
throw std::runtime_error("Can't open style file");
auto [modified_css, was_transformed] = transform_8bit_to_hex(css_file);
if (was_transformed) {
css_provider_->load_from_data(modified_css);
} else {
if (!css_provider_->load_from_path(css_file)) {
css_provider_.reset();
throw std::runtime_error("Can't open style file");
}
}
Gtk::StyleContext::add_provider_for_screen(screen, css_provider_,
GTK_STYLE_PROVIDER_PRIORITY_USER);
}
@@ -238,7 +277,7 @@ void waybar::Client::bindInterfaces() {
sigc::mem_fun(*this, &Client::handleMonitorRemoved));
}
int waybar::Client::main(int argc, char *argv[]) {
int waybar::Client::main(int argc, char* argv[]) {
bool show_help = false;
bool show_version = false;
std::string config_opt;
@@ -289,9 +328,10 @@ int waybar::Client::main(int argc, char *argv[]) {
}
m_cssFile = getStyle(style_opt);
setupCss(m_cssFile);
m_cssReloadHelper = std::make_unique<CssReloadHelper>(m_cssFile, [&]() { setupCss(m_cssFile); });
m_cssReloadHelper = std::make_unique<CssReloadHelper>(m_cssFile, [&](const std::string& css_file) { setupCss(css_file); });
portal->signal_appearance_changed().connect([&](waybar::Appearance appearance) {
auto css_file = getStyle(style_opt, appearance);
m_cssReloadHelper->changeCssFile(css_file);
setupCss(css_file);
});
@@ -299,7 +339,7 @@ int waybar::Client::main(int argc, char *argv[]) {
if (m_config.isObject() && m_config["reload_style_on_change"].asBool()) {
m_cssReloadHelper->monitorChanges();
} else if (m_config.isArray()) {
for (const auto &conf : m_config) {
for (const auto& conf : m_config) {
if (conf["reload_style_on_change"].asBool()) {
m_cssReloadHelper->monitorChanges();
break;
+28 -28
View File
@@ -23,10 +23,10 @@ const std::vector<std::string> Config::CONFIG_DIRS = {
"/etc/xdg/waybar/", SYSCONFDIR "/xdg/waybar/", "./resources/",
};
const char *Config::CONFIG_PATH_ENV = "WAYBAR_CONFIG_DIR";
const char* Config::CONFIG_PATH_ENV = "WAYBAR_CONFIG_DIR";
std::vector<std::string> Config::tryExpandPath(const std::string &base,
const std::string &filename) {
std::vector<std::string> Config::tryExpandPath(const std::string& base,
const std::string& filename) {
fs::path path;
if (!filename.empty()) {
@@ -65,18 +65,18 @@ std::vector<std::string> Config::tryExpandPath(const std::string &base,
return results;
}
std::optional<std::string> Config::findConfigPath(const std::vector<std::string> &names,
const std::vector<std::string> &dirs) {
if (const char *dir = std::getenv(Config::CONFIG_PATH_ENV)) {
for (const auto &name : names) {
std::optional<std::string> Config::findConfigPath(const std::vector<std::string>& names,
const std::vector<std::string>& dirs) {
if (const char* dir = std::getenv(Config::CONFIG_PATH_ENV)) {
for (const auto& name : names) {
if (auto res = tryExpandPath(dir, name); !res.empty()) {
return res.front();
}
}
}
for (const auto &dir : dirs) {
for (const auto &name : names) {
for (const auto& dir : dirs) {
for (const auto& name : names) {
if (auto res = tryExpandPath(dir, name); !res.empty()) {
return res.front();
}
@@ -85,7 +85,7 @@ std::optional<std::string> Config::findConfigPath(const std::vector<std::string>
return std::nullopt;
}
void Config::setupConfig(Json::Value &dst, const std::string &config_file, int depth) {
void Config::setupConfig(Json::Value& dst, const std::string& config_file, int depth) {
if (depth > 100) {
throw std::runtime_error("Aborting due to likely recursive include in config files");
}
@@ -97,7 +97,7 @@ void Config::setupConfig(Json::Value &dst, const std::string &config_file, int d
util::JsonParser parser;
Json::Value tmp_config = parser.parse(str);
if (tmp_config.isArray()) {
for (auto &config_part : tmp_config) {
for (auto& config_part : tmp_config) {
resolveConfigIncludes(config_part, depth);
}
} else {
@@ -106,18 +106,18 @@ void Config::setupConfig(Json::Value &dst, const std::string &config_file, int d
mergeConfig(dst, tmp_config);
}
std::vector<std::string> Config::findIncludePath(const std::string &name,
const std::vector<std::string> &dirs) {
std::vector<std::string> Config::findIncludePath(const std::string& name,
const std::vector<std::string>& dirs) {
auto match1 = tryExpandPath(name, "");
if (!match1.empty()) {
return match1;
}
if (const char *dir = std::getenv(Config::CONFIG_PATH_ENV)) {
if (const char* dir = std::getenv(Config::CONFIG_PATH_ENV)) {
if (auto res = tryExpandPath(dir, name); !res.empty()) {
return res;
}
}
for (const auto &dir : dirs) {
for (const auto& dir : dirs) {
if (auto res = tryExpandPath(dir, name); !res.empty()) {
return res;
}
@@ -126,14 +126,14 @@ std::vector<std::string> Config::findIncludePath(const std::string &name,
return {};
}
void Config::resolveConfigIncludes(Json::Value &config, int depth) {
void Config::resolveConfigIncludes(Json::Value& config, int depth) {
Json::Value includes = config["include"];
if (includes.isArray()) {
for (const auto &include : includes) {
for (const auto& include : includes) {
spdlog::info("Including resource file: {}", include.asString());
auto matches = findIncludePath(include.asString());
if (!matches.empty()) {
for (const auto &match : matches) {
for (const auto& match : matches) {
setupConfig(config, match, depth + 1);
}
} else {
@@ -144,7 +144,7 @@ void Config::resolveConfigIncludes(Json::Value &config, int depth) {
spdlog::info("Including resource file: {}", includes.asString());
auto matches = findIncludePath(includes.asString());
if (!matches.empty()) {
for (const auto &match : matches) {
for (const auto& match : matches) {
setupConfig(config, match, depth + 1);
}
} else {
@@ -153,12 +153,12 @@ void Config::resolveConfigIncludes(Json::Value &config, int depth) {
}
}
void Config::mergeConfig(Json::Value &a_config_, Json::Value &b_config_) {
void Config::mergeConfig(Json::Value& a_config_, Json::Value& b_config_) {
if (!a_config_) {
// For the first config
a_config_ = b_config_;
} else if (a_config_.isObject() && b_config_.isObject()) {
for (const auto &key : b_config_.getMemberNames()) {
for (const auto& key : b_config_.getMemberNames()) {
// [] creates key with default value. Use `get` to avoid that.
if (a_config_.get(key, Json::Value::nullSingleton()).isObject() &&
b_config_[key].isObject()) {
@@ -174,10 +174,10 @@ void Config::mergeConfig(Json::Value &a_config_, Json::Value &b_config_) {
spdlog::error("Cannot merge config, conflicting or invalid JSON types");
}
}
bool isValidOutput(const Json::Value &config, const std::string &name,
const std::string &identifier) {
bool isValidOutput(const Json::Value& config, const std::string& name,
const std::string& identifier) {
if (config["output"].isArray()) {
for (auto const &output_conf : config["output"]) {
for (auto const& output_conf : config["output"]) {
if (output_conf.isString()) {
auto config_output = output_conf.asString();
if (config_output.substr(0, 1) == "!") {
@@ -211,7 +211,7 @@ bool isValidOutput(const Json::Value &config, const std::string &name,
return true;
}
void Config::load(const std::string &config) {
void Config::load(const std::string& config) {
auto file = config.empty() ? findConfigPath({"config", "config.jsonc"}) : config;
if (!file) {
throw std::runtime_error("Missing required resource files");
@@ -222,11 +222,11 @@ void Config::load(const std::string &config) {
setupConfig(config_, config_file_, 0);
}
std::vector<Json::Value> Config::getOutputConfigs(const std::string &name,
const std::string &identifier) {
std::vector<Json::Value> Config::getOutputConfigs(const std::string& name,
const std::string& identifier) {
std::vector<Json::Value> configs;
if (config_.isArray()) {
for (auto const &config : config_) {
for (auto const& config : config_) {
if (config.isObject() && isValidOutput(config, name, identifier)) {
configs.push_back(config);
}
+14 -1
View File
@@ -64,11 +64,19 @@ Group::Group(const std::string& name, const std::string& id, const Json::Value&
: true);
click_to_reveal = drawer_config["click-to-reveal"].asBool();
const bool start_expanded =
(drawer_config["start-expanded"].isBool() ? drawer_config["start-expanded"].asBool()
: false);
auto transition_type = getPreferredTransitionType(vertical);
revealer.set_transition_type(transition_type);
revealer.set_transition_duration(transition_duration);
revealer.set_reveal_child(false);
revealer.set_reveal_child(start_expanded);
if (start_expanded) {
box.set_state_flags(Gtk::StateFlags::STATE_FLAG_PRELIGHT);
}
revealer.get_style_context()->add_class("drawer");
@@ -124,6 +132,11 @@ auto Group::update() -> void {
// noop
}
bool Group::handleScroll(GdkEventScroll* e) {
// no scroll.
return true;
}
Gtk::Box& Group::getBox() { return is_drawer ? (is_first_widget ? box : revealer_box) : box; }
void Group::addWidget(Gtk::Widget& widget) {
+14 -6
View File
@@ -33,7 +33,10 @@ static void writeSignalToPipe(int signum) {
// to `signal_handler`.
static void catchSignals(waybar::SafeSignal<int>& signal_handler) {
int fd[2];
pipe(fd);
if (pipe(fd) != 0) {
spdlog::error("Failed to create signal pipe: {}", strerror(errno));
return;
}
int signal_pipe_read_fd = fd[0];
signal_pipe_write_fd = fd[1];
@@ -52,9 +55,11 @@ static void catchSignals(waybar::SafeSignal<int>& signal_handler) {
std::signal(SIGINT, writeSignalToPipe);
std::signal(SIGCHLD, writeSignalToPipe);
#ifdef SIGRTMIN
for (int sig = SIGRTMIN + 1; sig <= SIGRTMAX; ++sig) {
std::signal(sig, writeSignalToPipe);
}
#endif
while (true) {
int signum;
@@ -116,13 +121,15 @@ void handleUserSignal(int signal, bool& reload) {
// If this signal should restart or close the bar, this function will write
// `true` or `false`, respectively, into `reload`.
static void handleSignalMainThread(int signum, bool& reload) {
#ifdef SIGRTMIN
if (signum >= SIGRTMIN + 1 && signum <= SIGRTMAX) {
for (auto& bar : waybar::Client::inst()->bars) {
bar->handleSignal(signum);
}
return;
}
#endif
switch (signum) {
case SIGUSR1:
handleUserSignal(SIGUSR1, reload);
@@ -137,15 +144,16 @@ static void handleSignalMainThread(int signum, bool& reload) {
break;
case SIGCHLD:
spdlog::debug("Received SIGCHLD in signalThread");
if (!reap.empty()) {
reap_mtx.lock();
for (auto it = reap.begin(); it != reap.end(); ++it) {
{
std::lock_guard<std::mutex> lock(reap_mtx);
for (auto it = reap.begin(); it != reap.end();) {
if (waitpid(*it, nullptr, WNOHANG) == *it) {
spdlog::debug("Reaped child with PID: {}", *it);
it = reap.erase(it);
} else {
++it;
}
}
reap_mtx.unlock();
}
break;
default:
+6 -6
View File
@@ -13,7 +13,7 @@
#include "util/backend_common.hpp"
#include "util/backlight_backend.hpp"
waybar::modules::Backlight::Backlight(const std::string &id, const Json::Value &config)
waybar::modules::Backlight::Backlight(const std::string& id, const Json::Value& config)
: ALabel(config, "backlight", id, "{percent}%", 2),
preferred_device_(config["device"].isString() ? config["device"].asString() : ""),
backend(interval_, [this] { dp.emit(); }) {
@@ -58,11 +58,11 @@ auto waybar::modules::Backlight::update() -> void {
tooltip_format = config_["tooltip-format"].asString();
}
if (!tooltip_format.empty()) {
label_.set_tooltip_text(fmt::format(fmt::runtime(tooltip_format),
fmt::arg("percent", percent),
fmt::arg("icon", getIcon(percent))));
label_.set_tooltip_markup(fmt::format(fmt::runtime(tooltip_format),
fmt::arg("percent", percent),
fmt::arg("icon", getIcon(percent))));
} else {
label_.set_tooltip_text(desc);
label_.set_tooltip_markup(desc);
}
}
} else {
@@ -79,7 +79,7 @@ auto waybar::modules::Backlight::update() -> void {
ALabel::update();
}
bool waybar::modules::Backlight::handleScroll(GdkEventScroll *e) {
bool waybar::modules::Backlight::handleScroll(GdkEventScroll* e) {
// Check if the user has set a custom command for scrolling
if (config_["on-scroll-up"].isString() || config_["on-scroll-down"].isString()) {
return AModule::handleScroll(e);
+98 -72
View File
@@ -117,17 +117,16 @@ void waybar::modules::Battery::refreshBatteries() {
if (((bat_defined && dir_name == config_["bat"].asString()) || !bat_defined) &&
(fs::exists(node.path() / "capacity") || fs::exists(node.path() / "charge_now")) &&
fs::exists(node.path() / "uevent") &&
(fs::exists(node.path() / "status") || bat_compatibility) &&
fs::exists(node.path() / "type")) {
(fs::exists(node.path() / "status") || bat_compatibility)) {
std::string type;
std::ifstream(node.path() / "type") >> type;
if (!type.compare("Battery")) {
if (std::ifstream{node.path() / "type"} >> type && !type.compare("Battery")) {
// Ignore non-system power supplies unless explicitly requested
if (!bat_defined && fs::exists(node.path() / "scope")) {
if (!bat_defined) {
std::string scope;
std::ifstream(node.path() / "scope") >> scope;
if (g_ascii_strcasecmp(scope.data(), "device") == 0) {
// for hotplug-in device, access it is always unstable because you may remove the
// device anytime so just allow failure happen and do nothing
if (std::ifstream{node.path() / "scope"} >> scope &&
g_ascii_strcasecmp(scope.data(), "device") == 0) {
continue;
}
}
@@ -139,7 +138,9 @@ void waybar::modules::Battery::refreshBatteries() {
auto event_path = (node.path() / "uevent");
auto wd = inotify_add_watch(battery_watch_fd_, event_path.c_str(), IN_ACCESS);
if (wd < 0) {
throw std::runtime_error("Could not watch events for " + node.path().string());
spdlog::warn("Could not watch events for {} (device may have been removed)",
node.path().string());
continue;
}
batteries_[node.path()] = wd;
}
@@ -152,7 +153,7 @@ void waybar::modules::Battery::refreshBatteries() {
}
}
} catch (fs::filesystem_error& e) {
throw std::runtime_error(e.what());
spdlog::warn("Battery directory tracking failed: {}", e.what());
}
if (warnFirstTime_ && batteries_.empty()) {
if (config_["bat"].isString()) {
@@ -273,11 +274,11 @@ waybar::modules::Battery::getInfos() {
auto bat = item.first;
std::string _status;
/* Check for adapter status if battery is not available */
if (!std::ifstream(bat / "status")) {
std::getline(std::ifstream(adapter_ / "status"), _status);
} else {
std::getline(std::ifstream(bat / "status"), _status);
{
std::ifstream f{bat / "status"};
if (!std::getline(f, _status)) {
std::getline(std::ifstream(adapter_ / "status"), _status);
}
}
// Some battery will report current and charge in μA/μAh.
@@ -286,64 +287,74 @@ waybar::modules::Battery::getInfos() {
uint32_t current_now = 0;
int32_t _current_now_int = 0;
bool current_now_exists = false;
if (fs::exists(bat / "current_now")) {
current_now_exists = true;
std::ifstream(bat / "current_now") >> _current_now_int;
} else if (fs::exists(bat / "current_avg")) {
current_now_exists = true;
std::ifstream(bat / "current_avg") >> _current_now_int;
if (std::ifstream current_now_f{bat / "current_now"}) {
if (current_now_f >> _current_now_int) {
current_now_exists = true;
}
} else if (std::ifstream current_avg_f{bat / "current_avg"}) {
if (current_avg_f >> _current_now_int) {
current_now_exists = true;
}
}
// Documentation ABI allows a negative value when discharging, positive
// value when charging.
current_now = std::abs(_current_now_int);
if (fs::exists(bat / "time_to_empty_now")) {
time_to_empty_now_exists = true;
std::ifstream(bat / "time_to_empty_now") >> time_to_empty_now;
if (std::ifstream f{bat / "time_to_empty_now"}) {
if (f >> time_to_empty_now) {
time_to_empty_now_exists = true;
}
}
if (fs::exists(bat / "time_to_full_now")) {
time_to_full_now_exists = true;
std::ifstream(bat / "time_to_full_now") >> time_to_full_now;
if (std::ifstream f{bat / "time_to_full_now"}) {
if (f >> time_to_full_now) {
time_to_full_now_exists = true;
}
}
uint32_t voltage_now = 0;
bool voltage_now_exists = false;
if (fs::exists(bat / "voltage_now")) {
voltage_now_exists = true;
std::ifstream(bat / "voltage_now") >> voltage_now;
} else if (fs::exists(bat / "voltage_avg")) {
voltage_now_exists = true;
std::ifstream(bat / "voltage_avg") >> voltage_now;
if (std::ifstream voltage_now_f{bat / "voltage_now"}) {
if (voltage_now_f >> voltage_now) {
voltage_now_exists = true;
}
} else if (std::ifstream voltage_avg_f{bat / "voltage_avg"}) {
if (voltage_avg_f >> voltage_now) {
voltage_now_exists = true;
}
}
uint32_t charge_full = 0;
bool charge_full_exists = false;
if (fs::exists(bat / "charge_full")) {
charge_full_exists = true;
std::ifstream(bat / "charge_full") >> charge_full;
if (std::ifstream f{bat / "charge_full"}) {
if (f >> charge_full) {
charge_full_exists = true;
}
}
uint32_t charge_full_design = 0;
bool charge_full_design_exists = false;
if (fs::exists(bat / "charge_full_design")) {
charge_full_design_exists = true;
std::ifstream(bat / "charge_full_design") >> charge_full_design;
if (std::ifstream f{bat / "charge_full_design"}) {
if (f >> charge_full_design) {
charge_full_design_exists = true;
}
}
uint32_t charge_now = 0;
bool charge_now_exists = false;
if (fs::exists(bat / "charge_now")) {
charge_now_exists = true;
std::ifstream(bat / "charge_now") >> charge_now;
if (std::ifstream f{bat / "charge_now"}) {
if (f >> charge_now) {
charge_now_exists = true;
}
}
uint32_t power_now = 0;
int32_t _power_now_int = 0;
bool power_now_exists = false;
if (fs::exists(bat / "power_now")) {
power_now_exists = true;
std::ifstream(bat / "power_now") >> _power_now_int;
if (std::ifstream f{bat / "power_now"}) {
if (f >> _power_now_int) {
power_now_exists = true;
}
}
// Some drivers (example: Qualcomm) exposes use a negative value when
// discharging, positive value when charging.
@@ -351,28 +362,31 @@ waybar::modules::Battery::getInfos() {
uint32_t energy_now = 0;
bool energy_now_exists = false;
if (fs::exists(bat / "energy_now")) {
energy_now_exists = true;
std::ifstream(bat / "energy_now") >> energy_now;
if (std::ifstream f{bat / "energy_now"}) {
if (f >> energy_now) {
energy_now_exists = true;
}
}
uint32_t energy_full = 0;
bool energy_full_exists = false;
if (fs::exists(bat / "energy_full")) {
energy_full_exists = true;
std::ifstream(bat / "energy_full") >> energy_full;
if (std::ifstream f{bat / "energy_full"}) {
if (f >> energy_full) {
energy_full_exists = true;
}
}
uint32_t energy_full_design = 0;
bool energy_full_design_exists = false;
if (fs::exists(bat / "energy_full_design")) {
energy_full_design_exists = true;
std::ifstream(bat / "energy_full_design") >> energy_full_design;
if (std::ifstream f{bat / "energy_full_design"}) {
if (f >> energy_full_design) {
energy_full_design_exists = true;
}
}
uint16_t cycleCount = 0;
if (fs::exists(bat / "cycle_count")) {
std::ifstream(bat / "cycle_count") >> cycleCount;
if (std::ifstream f{bat / "cycle_count"}) {
f >> cycleCount;
}
if (charge_full_design >= largestDesignCapacity) {
largestDesignCapacity = charge_full_design;
@@ -402,9 +416,10 @@ waybar::modules::Battery::getInfos() {
} else if (energy_now_exists && energy_full_exists && energy_full != 0) {
capacity_exists = true;
capacity = 100 * (uint64_t)energy_now / (uint64_t)energy_full;
} else if (fs::exists(bat / "capacity")) {
capacity_exists = true;
std::ifstream(bat / "capacity") >> capacity;
} else if (std::ifstream f{bat / "capacity"}) {
if (f >> capacity) {
capacity_exists = true;
}
}
if (!voltage_now_exists) {
@@ -584,11 +599,12 @@ waybar::modules::Battery::getInfos() {
float calculated_capacity{0.0f};
if (total_capacity_exists) {
if (total_capacity > 0.0f)
if (total_capacity > 0.0f) {
calculated_capacity = (float)total_capacity / batteries_.size();
else if (total_energy_full_exists && total_energy_exists) {
if (total_energy_full > 0.0f)
} else if (total_energy_full_exists && total_energy_exists) {
if (total_energy_full > 0.0f) {
calculated_capacity = ((float)total_energy * 100.0f / (float)total_energy_full);
}
}
}
@@ -685,13 +701,20 @@ auto waybar::modules::Battery::update() -> void {
if (status == "Unknown") {
status = getAdapterStatus(capacity);
}
auto state = getState(capacity, true);
bool adapter_online = false;
if (!adapter_.empty()) {
std::ifstream(adapter_ / "online") >> adapter_online;
}
if (config_["full-at-plugged"].asBool() && status == "Full" && adapter_online) {
status = "Plugged";
}
auto status_pretty = status;
puts(status.c_str());
// Transform to lowercase and replace space with dash
std::ranges::transform(status.begin(), status.end(), status.begin(),
[](char ch) { return ch == ' ' ? '-' : std::tolower(ch); });
auto format = format_;
auto state = getState(capacity, true);
processEvents(state, status, capacity);
setBarClass(state);
auto time_remaining_formatted = formatTimeRemaining(time_remaining);
@@ -790,16 +813,19 @@ void waybar::modules::Battery::processEvents(std::string& state, std::string& st
if (!events.isObject() || events.empty()) {
return;
}
std::string event_name = fmt::format("on-{}-{}", status == "discharging" ? status : "charging",
state.empty() ? std::to_string(capacity) : state);
auto exec = [](Json::Value const& event) {
if (!event.isString()) return;
if (auto command = event.asString(); !command.empty()) {
util::command::exec(command, "");
}
};
std::string status_name = status == "discharging" ? "on-discharging" : "on-charging";
std::string event_name = status_name + '-' + (state.empty() ? std::to_string(capacity) : state);
if (last_event_ != event_name) {
spdlog::debug("battery: triggering event {}", event_name);
if (events[event_name].isString()) {
std::string exec = events[event_name].asString();
// Execute the command if it is not empty
if (!exec.empty()) {
util::command::exec(exec, "");
}
exec(events[event_name]);
if (!last_event_.empty() && last_event_[3] != event_name[3]) {
exec(events[status_name]);
}
last_event_ = event_name;
}
+18 -8
View File
@@ -111,13 +111,16 @@ waybar::modules::Bluetooth::Bluetooth(const std::string& id, const Json::Value&
findConnectedDevices(cur_controller_->path, connected_devices_);
}
g_signal_connect(manager_.get(), "object-added", G_CALLBACK(onObjectAdded), this);
g_signal_connect(manager_.get(), "object-removed", G_CALLBACK(onObjectRemoved), this);
g_signal_connect(manager_.get(), "interface-proxy-properties-changed",
G_CALLBACK(onInterfaceProxyPropertiesChanged), this);
g_signal_connect(manager_.get(), "interface-added", G_CALLBACK(onInterfaceAddedOrRemoved), this);
g_signal_connect(manager_.get(), "interface-removed", G_CALLBACK(onInterfaceAddedOrRemoved),
this);
if (manager_) {
g_signal_connect(manager_.get(), "object-added", G_CALLBACK(onObjectAdded), this);
g_signal_connect(manager_.get(), "object-removed", G_CALLBACK(onObjectRemoved), this);
g_signal_connect(manager_.get(), "interface-proxy-properties-changed",
G_CALLBACK(onInterfaceProxyPropertiesChanged), this);
g_signal_connect(manager_.get(), "interface-added", G_CALLBACK(onInterfaceAddedOrRemoved),
this);
g_signal_connect(manager_.get(), "interface-removed", G_CALLBACK(onInterfaceAddedOrRemoved),
this);
}
#ifdef WANT_RFKILL
rfkill_.on_update.connect(sigc::hide(sigc::mem_fun(*this, &Bluetooth::update)));
@@ -264,7 +267,7 @@ auto waybar::modules::Bluetooth::update() -> void {
device_enumerate_.erase(0, 1);
}
}
label_.set_tooltip_text(fmt::format(
label_.set_tooltip_markup(fmt::format(
fmt::runtime(tooltip_format), fmt::arg("status", state_),
fmt::arg("num_connections", connected_devices_.size()),
fmt::arg("controller_address", cur_controller_ ? cur_controller_->address : "null"),
@@ -446,6 +449,10 @@ auto waybar::modules::Bluetooth::getControllerProperties(GDBusObject* object,
auto waybar::modules::Bluetooth::findCurController() -> std::optional<ControllerInfo> {
std::optional<ControllerInfo> controller_info;
if (!manager_) {
return controller_info;
}
GList* objects = g_dbus_object_manager_get_objects(manager_.get());
for (GList* l = objects; l != NULL; l = l->next) {
GDBusObject* object = G_DBUS_OBJECT(l->data);
@@ -465,6 +472,9 @@ auto waybar::modules::Bluetooth::findCurController() -> std::optional<Controller
auto waybar::modules::Bluetooth::findConnectedDevices(const std::string& cur_controller_path,
std::vector<DeviceInfo>& connected_devices)
-> void {
if (!manager_) {
return;
}
GList* objects = g_dbus_object_manager_get_objects(manager_.get());
for (GList* l = objects; l != NULL; l = l->next) {
GDBusObject* object = G_DBUS_OBJECT(l->data);
+5 -3
View File
@@ -26,6 +26,7 @@ void waybar::modules::cava::Cava::pause_resume() { backend_->doPauseResume(); }
auto waybar::modules::cava::Cava::onUpdate(const std::string& input) -> void {
Glib::signal_idle().connect_once([this, input]() {
if (silence_) {
silence_ = false;
label_.get_style_context()->remove_class("silent");
if (!label_.get_style_context()->has_class("updated"))
label_.get_style_context()->add_class("updated");
@@ -38,7 +39,6 @@ auto waybar::modules::cava::Cava::onUpdate(const std::string& input) -> void {
label_.show();
ALabel::update();
});
silence_ = false;
}
auto waybar::modules::cava::Cava::onSilence() -> void {
@@ -47,9 +47,11 @@ auto waybar::modules::cava::Cava::onSilence() -> void {
if (label_.get_style_context()->has_class("updated"))
label_.get_style_context()->remove_class("updated");
if (hide_on_silence_)
if (hide_on_silence_) {
// Clear the label markup before hiding to prevent GTK from rendering a NULL Pango layout
label_.set_markup("");
label_.hide();
else if (config_["format_silent"].isString())
} else if (config_["format_silent"].isString())
label_.set_markup(format_silent_);
silence_ = true;
label_.get_style_context()->add_class("silent");
+5 -5
View File
@@ -183,10 +183,10 @@ void waybar::modules::cava::CavaBackend::loadConfig() {
prm_.inAtty = 0;
auto const output{prm_.output};
// prm_.output = ::cava::output_method::OUTPUT_RAW;
if (config_["data_format"].isString()) {
if (prm_.data_format) free(prm_.data_format);
prm_.data_format = strdup(config_["data_format"].asString().c_str());
}
if (prm_.data_format) free(prm_.data_format);
// Default to ascii for format-icons output; allow user override
prm_.data_format = strdup(
config_["data_format"].isString() ? config_["data_format"].asString().c_str() : "ascii");
if (config_["raw_target"].isString()) {
if (prm_.raw_target) free(prm_.raw_target);
prm_.raw_target = strdup(config_["raw_target"].asString().c_str());
@@ -218,7 +218,7 @@ void waybar::modules::cava::CavaBackend::loadConfig() {
prm_.input = ::cava::input_method_by_name(config_["method"].asString().c_str());
if (config_["source"].isString()) {
if (prm_.audio_source) free(prm_.audio_source);
prm_.audio_source = config_["source"].asString().data();
prm_.audio_source = strdup(config_["source"].asString().c_str());
}
if (config_["sample_rate"].isNumeric()) prm_.samplerate = config_["sample_rate"].asLargestInt();
if (config_["sample_bits"].isInt()) prm_.samplebits = config_["sample_bits"].asInt();
+2 -1
View File
@@ -35,7 +35,7 @@ CFFI::CFFI(const std::string& name, const std::string& id, const Json::Value& co
throw std::runtime_error{std::string{"Missing wbcffi_init function: "} + dlerror()};
}
hooks_.deinit = reinterpret_cast<DenitFn*>(dlsym(handle, "wbcffi_deinit"));
if (!hooks_.init) {
if (!hooks_.deinit) {
throw std::runtime_error{std::string{"Missing wbcffi_deinit function: "} + dlerror()};
}
// Optional functions
@@ -71,6 +71,7 @@ CFFI::CFFI(const std::string& name, const std::string& id, const Json::Value& co
// Prepare config_entries array
std::vector<ffi::wbcffi_config_entry> config_entries;
config_entries.reserve(keys.size());
for (size_t i = 0; i < keys.size(); i++) {
config_entries.push_back({keys[i].c_str(), config_entries_stringstor[i].c_str()});
}
+6 -1
View File
@@ -402,8 +402,13 @@ auto waybar::modules::Clock::get_calendar(const year_month_day& today, const yea
data = g_utf8_find_next_char(data, end);
}
}
// Note: the stream's default fill character is already a space (L' ' on
// libstdc++'s wide FormatStream, ' ' on libc++'s narrow one), so no
// std::setfill is needed. Passing std::setfill(' ')/std::setfill(L' ')
// here is not portable because the fill char type must match the
// FormatStream's char type, which differs between standard libraries.
os << Glib::ustring::format(
(cldWPos_ != WS::LEFT || line == 0) ? std::left : std::right, std::setfill(L' '),
(cldWPos_ != WS::LEFT || line == 0) ? std::left : std::right,
std::setw(cldMonColLen_ + ((line < 2) ? cldWnLen_ - wideCharCount : 0)),
calendarLine);
+21 -7
View File
@@ -26,9 +26,7 @@ auto waybar::modules::Cpu::update() -> void {
auto [load1, load5, load15] = Load::getLoad();
auto [cpu_usage, tooltip] = CpuUsage::getCpuUsage(prev_times_);
auto [max_frequency, min_frequency, avg_frequency] = CpuFrequency::getCpuFrequency();
if (tooltipEnabled()) {
label_.set_tooltip_text(tooltip);
}
auto format = format_;
auto total_usage = cpu_usage.empty() ? 0 : cpu_usage[0];
auto state = getState(total_usage);
@@ -48,14 +46,30 @@ auto waybar::modules::Cpu::update() -> void {
store.push_back(fmt::arg("max_frequency", max_frequency));
store.push_back(fmt::arg("min_frequency", min_frequency));
store.push_back(fmt::arg("avg_frequency", avg_frequency));
std::vector<std::string> arg_names;
arg_names.reserve(cpu_usage.size() * 2);
for (size_t i = 1; i < cpu_usage.size(); ++i) {
auto core_i = i - 1;
auto core_format = fmt::format("usage{}", core_i);
store.push_back(fmt::arg(core_format.c_str(), cpu_usage[i]));
auto icon_format = fmt::format("icon{}", core_i);
store.push_back(fmt::arg(icon_format.c_str(), getIcon(cpu_usage[i], icons)));
arg_names.push_back(fmt::format("usage{}", core_i));
store.push_back(fmt::arg(arg_names.back().c_str(), cpu_usage[i]));
arg_names.push_back(fmt::format("icon{}", core_i));
store.push_back(fmt::arg(arg_names.back().c_str(), getIcon(cpu_usage[i], icons)));
}
label_.set_markup(fmt::vformat(format, store));
if (tooltipEnabled()) {
std::string tooltip_format;
if (!state.empty() && config_["tooltip-format-" + state].isString()) {
tooltip_format = config_["tooltip-format-" + state].asString();
} else if (config_["tooltip-format"].isString()) {
tooltip_format = config_["tooltip-format"].asString();
}
if (!tooltip_format.empty()) {
label_.set_tooltip_markup(fmt::vformat(tooltip_format, store));
} else {
label_.set_tooltip_markup(tooltip);
}
}
}
// Call parent update
+13 -6
View File
@@ -20,12 +20,7 @@ waybar::modules::CpuFrequency::CpuFrequency(const std::string& id, const Json::V
auto waybar::modules::CpuFrequency::update() -> void {
// TODO: as creating dynamic fmt::arg arrays is buggy we have to calc both
auto [max_frequency, min_frequency, avg_frequency] = CpuFrequency::getCpuFrequency();
if (tooltipEnabled()) {
auto tooltip =
fmt::format("Minimum frequency: {}\nAverage frequency: {}\nMaximum frequency: {}\n",
min_frequency, avg_frequency, max_frequency);
label_.set_tooltip_text(tooltip);
}
auto format = format_;
auto state = getState(avg_frequency);
if (!state.empty() && config_["format-" + state].isString()) {
@@ -43,6 +38,18 @@ auto waybar::modules::CpuFrequency::update() -> void {
store.push_back(fmt::arg("min_frequency", min_frequency));
store.push_back(fmt::arg("avg_frequency", avg_frequency));
label_.set_markup(fmt::vformat(format, store));
if (tooltipEnabled()) {
std::string tooltip;
if (config_["tooltip-format"].isString()) {
tooltip = config_["tooltip-format"].asString();
label_.set_tooltip_markup(fmt::vformat(tooltip, store));
} else {
tooltip = "Minimum frequency: {}\nAverage frequency: {}\nMaximum frequency: {}\n";
label_.set_tooltip_markup(
fmt::format(fmt::runtime(tooltip), min_frequency, avg_frequency, max_frequency));
}
}
}
// Call parent update
+9 -11
View File
@@ -23,23 +23,21 @@ std::vector<float> waybar::modules::CpuFrequency::parseCpuFrequencies() {
if (frequencies.size() <= 0) {
std::string cpufreq_dir = "/sys/devices/system/cpu/cpufreq";
if (std::filesystem::exists(cpufreq_dir)) {
try {
std::vector<std::string> frequency_files = {"/cpuinfo_min_freq", "/cpuinfo_max_freq"};
for (auto& p : std::filesystem::directory_iterator(cpufreq_dir)) {
for (auto freq_file : frequency_files) {
for (const auto& freq_file : frequency_files) {
std::string freq_file_path = p.path().string() + freq_file;
if (std::filesystem::exists(freq_file_path)) {
std::string freq_value;
std::ifstream freq(freq_file_path);
if (freq.is_open()) {
getline(freq, freq_value);
float frequency = std::strtol(freq_value.c_str(), nullptr, 10);
frequencies.push_back(frequency / 1000);
freq.close();
}
std::string freq_value;
std::ifstream freq(freq_file_path);
if (freq.is_open()) {
getline(freq, freq_value);
float frequency = std::strtol(freq_value.c_str(), nullptr, 10);
frequencies.push_back(frequency / 1000);
}
}
}
} catch (const std::filesystem::filesystem_error&) {
}
}
+1 -1
View File
@@ -33,7 +33,7 @@ std::vector<std::tuple<size_t, size_t>> waybar::modules::CpuUsage::parseCpuinfo(
size_t sum_sz = sizeof(sum_cp_time);
int ncpu = sysconf(_SC_NPROCESSORS_CONF);
size_t sz = CPUSTATES * (ncpu + 1) * sizeof(pcp_time_t);
pcp_time_t *cp_time = static_cast<pcp_time_t *>(malloc(sz)), *pcp_time = cp_time;
pcp_time_t *cp_time = static_cast<pcp_time_t*>(malloc(sz)), *pcp_time = cp_time;
waybar::util::ScopeGuard cp_time_deleter([cp_time]() {
if (cp_time) {
free(cp_time);
+20 -9
View File
@@ -20,9 +20,7 @@ waybar::modules::CpuUsage::CpuUsage(const std::string& id, const Json::Value& co
auto waybar::modules::CpuUsage::update() -> void {
// TODO: as creating dynamic fmt::arg arrays is buggy we have to calc both
auto [cpu_usage, tooltip] = CpuUsage::getCpuUsage(prev_times_);
if (tooltipEnabled()) {
label_.set_tooltip_text(tooltip);
}
auto format = format_;
auto total_usage = cpu_usage.empty() ? 0 : cpu_usage[0];
auto state = getState(total_usage);
@@ -38,14 +36,25 @@ auto waybar::modules::CpuUsage::update() -> void {
fmt::dynamic_format_arg_store<fmt::format_context> store;
store.push_back(fmt::arg("usage", total_usage));
store.push_back(fmt::arg("icon", getIcon(total_usage, icons)));
std::vector<std::string> arg_names;
arg_names.reserve(cpu_usage.size() * 2);
for (size_t i = 1; i < cpu_usage.size(); ++i) {
auto core_i = i - 1;
auto core_format = fmt::format("usage{}", core_i);
store.push_back(fmt::arg(core_format.c_str(), cpu_usage[i]));
auto icon_format = fmt::format("icon{}", core_i);
store.push_back(fmt::arg(icon_format.c_str(), getIcon(cpu_usage[i], icons)));
arg_names.push_back(fmt::format("usage{}", core_i));
store.push_back(fmt::arg(arg_names.back().c_str(), cpu_usage[i]));
arg_names.push_back(fmt::format("icon{}", core_i));
store.push_back(fmt::arg(arg_names.back().c_str(), getIcon(cpu_usage[i], icons)));
}
label_.set_markup(fmt::vformat(format, store));
if (tooltipEnabled()) {
if (config_["tooltip-format"].isString()) {
tooltip = config_["tooltip-format"].asString();
label_.set_tooltip_markup(fmt::vformat(tooltip, store));
} else {
label_.set_tooltip_markup(tooltip);
}
}
}
// Call parent update
@@ -71,7 +80,8 @@ std::tuple<std::vector<uint16_t>, std::string> waybar::modules::CpuUsage::getCpu
auto [prev_idle, prev_total] = prev_times[0];
const float delta_idle = curr_idle - prev_idle;
const float delta_total = curr_total - prev_total;
uint16_t tmp = 100 * (1 - delta_idle / delta_total);
uint16_t tmp =
(delta_total > 0) ? static_cast<uint16_t>(100 * (1 - delta_idle / delta_total)) : 0;
tooltip = fmt::format("Total: {}%\nCores: (pending)", tmp);
usage.push_back(tmp);
} else {
@@ -93,7 +103,8 @@ std::tuple<std::vector<uint16_t>, std::string> waybar::modules::CpuUsage::getCpu
}
const float delta_idle = curr_idle - prev_idle;
const float delta_total = curr_total - prev_total;
uint16_t tmp = 100 * (1 - delta_idle / delta_total);
uint16_t tmp =
(delta_total > 0) ? static_cast<uint16_t>(100 * (1 - delta_idle / delta_total)) : 0;
if (i == 0) {
tooltip = fmt::format("Total: {}%", tmp);
} else {
+22 -11
View File
@@ -2,6 +2,8 @@
#include <spdlog/spdlog.h>
#include <utility>
#include "util/scope_guard.hpp"
waybar::modules::Custom::Custom(const std::string& name, const std::string& id,
@@ -37,6 +39,11 @@ waybar::modules::Custom::~Custom() {
}
void waybar::modules::Custom::delayWorker() {
if (!config_["exec"].isString() && !config_["exec-if"].isString()) {
dp.emit();
return;
}
thread_ = [this] {
for (int i : this->pid_children_) {
int status;
@@ -136,9 +143,11 @@ void waybar::modules::Custom::waitingWorker() {
}
void waybar::modules::Custom::refresh(int sig) {
if (sig == SIGRTMIN + config_["signal"].asInt()) {
#ifdef SIGRTMIN
if (config_["signal"].isInt() && sig == SIGRTMIN + config_["signal"].asInt()) {
thread_.wake_up();
}
#endif
}
void waybar::modules::Custom::handleEvent() {
@@ -180,20 +189,22 @@ auto waybar::modules::Custom::update() -> void {
} else {
label_.set_markup(str);
if (tooltipEnabled()) {
std::string tooltip_markup;
if (tooltip_format_enabled_) {
auto tooltip = config_["tooltip-format"].asString();
tooltip = fmt::format(
fmt::runtime(tooltip), fmt::arg("text", text_), fmt::arg("alt", alt_),
fmt::arg("icon", getIcon(percentage_, alt_)), fmt::arg("percentage", percentage_));
label_.set_tooltip_markup(tooltip);
tooltip_markup = fmt::format(fmt::runtime(tooltip), fmt::arg("text", text_),
fmt::arg("tooltip", tooltip_), fmt::arg("alt", alt_),
fmt::arg("icon", getIcon(percentage_, alt_)),
fmt::arg("percentage", percentage_));
} else if (text_ == tooltip_) {
if (label_.get_tooltip_markup() != str) {
label_.set_tooltip_markup(str);
}
tooltip_markup = str;
} else {
if (label_.get_tooltip_markup() != tooltip_) {
label_.set_tooltip_markup(tooltip_);
}
tooltip_markup = tooltip_;
}
if (last_tooltip_markup_ != tooltip_markup) {
label_.set_tooltip_markup(tooltip_markup);
last_tooltip_markup_ = std::move(tooltip_markup);
}
}
auto style = label_.get_style_context();
+4 -4
View File
@@ -41,7 +41,7 @@ auto waybar::modules::Disk::update() -> void {
fs_used - File system used space
*/
if (err != 0) {
if (err != 0 || stats.f_blocks == 0) {
event_box_.hide();
return;
}
@@ -81,7 +81,7 @@ auto waybar::modules::Disk::update() -> void {
if (config_["tooltip-format"].isString()) {
tooltip_format = config_["tooltip-format"].asString();
}
label_.set_tooltip_text(fmt::format(
label_.set_tooltip_markup(fmt::format(
fmt::runtime(tooltip_format), stats.f_bavail * 100 / stats.f_blocks, fmt::arg("free", free),
fmt::arg("percentage_free", stats.f_bavail * 100 / stats.f_blocks), fmt::arg("used", used),
fmt::arg("percentage_used", percentage_used), fmt::arg("total", total),
@@ -92,7 +92,7 @@ auto waybar::modules::Disk::update() -> void {
ALabel::update();
}
float waybar::modules::Disk::calc_specific_divisor(std::string divisor) {
float waybar::modules::Disk::calc_specific_divisor(const std::string& divisor) {
if (divisor == "kB") {
return 1000.0;
} else if (divisor == "kiB") {
@@ -112,4 +112,4 @@ float waybar::modules::Disk::calc_specific_divisor(std::string divisor) {
} else { // default to Bytes if it is anything that we don't recongnise
return 1.0;
}
}
}
+46 -29
View File
@@ -21,39 +21,39 @@ wl_array tags, layouts;
static uint num_tags = 0;
static void toggle_visibility(void *data, zdwl_ipc_output_v2 *zdwl_output_v2) {
static void toggle_visibility(void* data, zdwl_ipc_output_v2* zdwl_output_v2) {
// Intentionally empty
}
static void active(void *data, zdwl_ipc_output_v2 *zdwl_output_v2, uint32_t active) {
static void active(void* data, zdwl_ipc_output_v2* zdwl_output_v2, uint32_t active) {
// Intentionally empty
}
static void set_tag(void *data, zdwl_ipc_output_v2 *zdwl_output_v2, uint32_t tag, uint32_t state,
static void set_tag(void* data, zdwl_ipc_output_v2* zdwl_output_v2, uint32_t tag, uint32_t state,
uint32_t clients, uint32_t focused) {
static_cast<Tags *>(data)->handle_view_tags(tag, state, clients, focused);
static_cast<Tags*>(data)->handle_view_tags(tag, state, clients, focused);
num_tags = (state & ZDWL_IPC_OUTPUT_V2_TAG_STATE_ACTIVE) ? num_tags | (1 << tag)
: num_tags & ~(1 << tag);
}
static void set_layout_symbol(void *data, zdwl_ipc_output_v2 *zdwl_output_v2, const char *layout) {
static void set_layout_symbol(void* data, zdwl_ipc_output_v2* zdwl_output_v2, const char* layout) {
// Intentionally empty
}
static void title(void *data, zdwl_ipc_output_v2 *zdwl_output_v2, const char *title) {
static void title(void* data, zdwl_ipc_output_v2* zdwl_output_v2, const char* title) {
// Intentionally empty
}
static void dwl_frame(void *data, zdwl_ipc_output_v2 *zdwl_output_v2) {
static void dwl_frame(void* data, zdwl_ipc_output_v2* zdwl_output_v2) {
// Intentionally empty
}
static void set_layout(void *data, zdwl_ipc_output_v2 *zdwl_output_v2, uint32_t layout) {
static void set_layout(void* data, zdwl_ipc_output_v2* zdwl_output_v2, uint32_t layout) {
// Intentionally empty
}
static void appid(void *data, zdwl_ipc_output_v2 *zdwl_output_v2, const char *appid) {
static void appid(void* data, zdwl_ipc_output_v2* zdwl_output_v2, const char* appid) {
// Intentionally empty
};
@@ -68,35 +68,51 @@ static const zdwl_ipc_output_v2_listener output_status_listener_impl{
.frame = dwl_frame,
};
static void handle_global(void *data, struct wl_registry *registry, uint32_t name,
const char *interface, uint32_t version) {
if (std::strcmp(interface, zdwl_ipc_manager_v2_interface.name) == 0) {
static_cast<Tags *>(data)->status_manager_ = static_cast<struct zdwl_ipc_manager_v2 *>(
(zdwl_ipc_manager_v2 *)wl_registry_bind(registry, name, &zdwl_ipc_manager_v2_interface, 1));
}
if (std::strcmp(interface, wl_seat_interface.name) == 0) {
version = std::min<uint32_t>(version, 1);
static_cast<Tags *>(data)->seat_ = static_cast<struct wl_seat *>(
wl_registry_bind(registry, name, &wl_seat_interface, version));
}
static void handle_global(void* data, struct wl_registry* registry, uint32_t name,
const char* interface, uint32_t version) {
if (std::strcmp(interface, zdwl_ipc_manager_v2_interface.name) == 0) {
auto* self = static_cast<Tags*>(data);
if (self->status_manager_) {
zdwl_ipc_manager_v2_destroy(self->status_manager_);
self->status_manager_ = nullptr;
}
static void handle_global_remove(void *data, struct wl_registry *registry, uint32_t name) {
self->status_manager_ = static_cast<struct zdwl_ipc_manager_v2*>(
wl_registry_bind(registry, name, &zdwl_ipc_manager_v2_interface, 1));
}
if (std::strcmp(interface, wl_seat_interface.name) == 0) {
auto* self = static_cast<Tags*>(data);
if (self->seat_) {
wl_seat_destroy(self->seat_);
self->seat_ = nullptr;
}
version = std::min<uint32_t>(version, 1);
self->seat_ = static_cast<struct wl_seat*>(
wl_registry_bind(registry, name, &wl_seat_interface, version));
}
}
static void handle_global_remove(void* data, struct wl_registry* registry, uint32_t name) {
/* Ignore event */
}
static const wl_registry_listener registry_listener_impl = {.global = handle_global,
.global_remove = handle_global_remove};
Tags::Tags(const std::string &id, const waybar::Bar &bar, const Json::Value &config)
Tags::Tags(const std::string& id, const waybar::Bar& bar, const Json::Value& config)
: waybar::AModule(config, "tags", id, false, false),
status_manager_{nullptr},
seat_{nullptr},
bar_(bar),
box_{bar.orientation, 0},
output_status_{nullptr} {
struct wl_display *display = Client::inst()->wl_display;
struct wl_registry *registry = wl_display_get_registry(display);
struct wl_display* display = Client::inst()->wl_display;
struct wl_registry* registry = wl_display_get_registry(display);
wl_registry_add_listener(registry, &registry_listener_impl, this);
wl_display_roundtrip(display);
@@ -133,8 +149,8 @@ Tags::Tags(const std::string &id, const waybar::Bar &bar, const Json::Value &con
}
uint32_t i = 1;
for (const auto &tag_label : tag_labels) {
Gtk::Button &button = buttons_.emplace_back(tag_label);
for (const auto& tag_label : tag_labels) {
Gtk::Button& button = buttons_.emplace_back(tag_label);
button.set_relief(Gtk::RELIEF_NONE);
box_.pack_start(button, false, false, 0);
if (!config_["disable-click"].asBool()) {
@@ -147,7 +163,7 @@ Tags::Tags(const std::string &id, const waybar::Bar &bar, const Json::Value &con
i <<= 1;
}
struct wl_output *output = gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj());
struct wl_output* output = gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj());
output_status_ = zdwl_ipc_manager_v2_get_output(status_manager_, output);
zdwl_ipc_output_v2_add_listener(output_status_, &output_status_listener_impl, this);
@@ -170,7 +186,7 @@ void Tags::handle_primary_clicked(uint32_t tag) {
zdwl_ipc_output_v2_set_tags(output_status_, tag, 1);
}
bool Tags::handle_button_press(GdkEventButton *event_button, uint32_t tag) {
bool Tags::handle_button_press(GdkEventButton* event_button, uint32_t tag) {
if (event_button->type == GDK_BUTTON_PRESS && event_button->button == 3) {
if (!output_status_) return true;
zdwl_ipc_output_v2_set_tags(output_status_, num_tags ^ tag, 0);
@@ -179,8 +195,9 @@ bool Tags::handle_button_press(GdkEventButton *event_button, uint32_t tag) {
}
void Tags::handle_view_tags(uint32_t tag, uint32_t state, uint32_t clients, uint32_t focused) {
if (tag >= buttons_.size()) return;
// First clear all occupied state
auto &button = buttons_[tag];
auto& button = buttons_[tag];
if (clients) {
button.get_style_context()->add_class("occupied");
} else {
+26 -26
View File
@@ -14,37 +14,37 @@
namespace waybar::modules::dwl {
static void toggle_visibility(void *data, zdwl_ipc_output_v2 *zdwl_output_v2) {
static void toggle_visibility(void* data, zdwl_ipc_output_v2* zdwl_output_v2) {
// Intentionally empty
}
static void active(void *data, zdwl_ipc_output_v2 *zdwl_output_v2, uint32_t active) {
static void active(void* data, zdwl_ipc_output_v2* zdwl_output_v2, uint32_t active) {
// Intentionally empty
}
static void set_tag(void *data, zdwl_ipc_output_v2 *zdwl_output_v2, uint32_t tag, uint32_t state,
static void set_tag(void* data, zdwl_ipc_output_v2* zdwl_output_v2, uint32_t tag, uint32_t state,
uint32_t clients, uint32_t focused) {
// Intentionally empty
}
static void set_layout_symbol(void *data, zdwl_ipc_output_v2 *zdwl_output_v2, const char *layout) {
static_cast<Window *>(data)->handle_layout_symbol(layout);
static void set_layout_symbol(void* data, zdwl_ipc_output_v2* zdwl_output_v2, const char* layout) {
static_cast<Window*>(data)->handle_layout_symbol(layout);
}
static void title(void *data, zdwl_ipc_output_v2 *zdwl_output_v2, const char *title) {
static_cast<Window *>(data)->handle_title(title);
static void title(void* data, zdwl_ipc_output_v2* zdwl_output_v2, const char* title) {
static_cast<Window*>(data)->handle_title(title);
}
static void dwl_frame(void *data, zdwl_ipc_output_v2 *zdwl_output_v2) {
static_cast<Window *>(data)->handle_frame();
static void dwl_frame(void* data, zdwl_ipc_output_v2* zdwl_output_v2) {
static_cast<Window*>(data)->handle_frame();
}
static void set_layout(void *data, zdwl_ipc_output_v2 *zdwl_output_v2, uint32_t layout) {
static_cast<Window *>(data)->handle_layout(layout);
static void set_layout(void* data, zdwl_ipc_output_v2* zdwl_output_v2, uint32_t layout) {
static_cast<Window*>(data)->handle_layout(layout);
}
static void appid(void *data, zdwl_ipc_output_v2 *zdwl_output_v2, const char *appid) {
static_cast<Window *>(data)->handle_appid(appid);
static void appid(void* data, zdwl_ipc_output_v2* zdwl_output_v2, const char* appid) {
static_cast<Window*>(data)->handle_appid(appid);
};
static const zdwl_ipc_output_v2_listener output_status_listener_impl{
@@ -58,25 +58,25 @@ static const zdwl_ipc_output_v2_listener output_status_listener_impl{
.frame = dwl_frame,
};
static void handle_global(void *data, struct wl_registry *registry, uint32_t name,
const char *interface, uint32_t version) {
static void handle_global(void* data, struct wl_registry* registry, uint32_t name,
const char* interface, uint32_t version) {
if (std::strcmp(interface, zdwl_ipc_manager_v2_interface.name) == 0) {
static_cast<Window *>(data)->status_manager_ = static_cast<struct zdwl_ipc_manager_v2 *>(
(zdwl_ipc_manager_v2 *)wl_registry_bind(registry, name, &zdwl_ipc_manager_v2_interface, 1));
static_cast<Window*>(data)->status_manager_ = static_cast<struct zdwl_ipc_manager_v2*>(
(zdwl_ipc_manager_v2*)wl_registry_bind(registry, name, &zdwl_ipc_manager_v2_interface, 1));
}
}
static void handle_global_remove(void *data, struct wl_registry *registry, uint32_t name) {
static void handle_global_remove(void* data, struct wl_registry* registry, uint32_t name) {
/* Ignore event */
}
static const wl_registry_listener registry_listener_impl = {.global = handle_global,
.global_remove = handle_global_remove};
Window::Window(const std::string &id, const Bar &bar, const Json::Value &config)
Window::Window(const std::string& id, const Bar& bar, const Json::Value& config)
: AAppIconLabel(config, "window", id, "{}", 0, true), bar_(bar) {
struct wl_display *display = Client::inst()->wl_display;
struct wl_registry *registry = wl_display_get_registry(display);
struct wl_display* display = Client::inst()->wl_display;
struct wl_registry* registry = wl_display_get_registry(display);
wl_registry_add_listener(registry, &registry_listener_impl, this);
wl_display_roundtrip(display);
@@ -86,7 +86,7 @@ Window::Window(const std::string &id, const Bar &bar, const Json::Value &config)
return;
}
struct wl_output *output = gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj());
struct wl_output* output = gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj());
output_status_ = zdwl_ipc_manager_v2_get_output(status_manager_, output);
zdwl_ipc_output_v2_add_listener(output_status_, &output_status_listener_impl, this);
zdwl_ipc_manager_v2_destroy(status_manager_);
@@ -98,11 +98,11 @@ Window::~Window() {
}
}
void Window::handle_title(const char *title) { title_ = Glib::Markup::escape_text(title); }
void Window::handle_title(const char* title) { title_ = Glib::Markup::escape_text(title); }
void Window::handle_appid(const char *appid) { appid_ = Glib::Markup::escape_text(appid); }
void Window::handle_appid(const char* appid) { appid_ = Glib::Markup::escape_text(appid); }
void Window::handle_layout_symbol(const char *layout_symbol) {
void Window::handle_layout_symbol(const char* layout_symbol) {
layout_symbol_ = Glib::Markup::escape_text(layout_symbol);
}
@@ -116,7 +116,7 @@ void Window::handle_frame() {
updateAppIconName(appid_, "");
updateAppIcon();
if (tooltipEnabled()) {
label_.set_tooltip_text(title_);
label_.set_tooltip_markup(title_);
}
}
+38 -36
View File
@@ -20,8 +20,8 @@ uint32_t WorkspaceManager::group_global_id = 0;
uint32_t WorkspaceManager::workspace_global_id = 0;
std::map<std::string, std::string> Workspace::icon_map_;
WorkspaceManager::WorkspaceManager(const std::string &id, const waybar::Bar &bar,
const Json::Value &config)
WorkspaceManager::WorkspaceManager(const std::string& id, const waybar::Bar& bar,
const Json::Value& config)
: waybar::AModule(config, "workspaces", id, false, false), bar_(bar), box_(bar.orientation, 0) {
add_registry_listener(this);
@@ -70,7 +70,7 @@ WorkspaceManager::~WorkspaceManager() {
groups_.clear();
if (ext_manager_ != nullptr) {
auto *display = Client::inst()->wl_display;
auto* display = Client::inst()->wl_display;
// Send `stop` request and wait for one roundtrip.
ext_workspace_manager_v1_stop(ext_manager_);
wl_display_roundtrip(display);
@@ -84,7 +84,7 @@ WorkspaceManager::~WorkspaceManager() {
spdlog::debug("[ext/workspaces]: Workspace manager destroyed");
}
void WorkspaceManager::register_manager(wl_registry *registry, uint32_t name, uint32_t version) {
void WorkspaceManager::register_manager(wl_registry* registry, uint32_t name, uint32_t version) {
if (ext_manager_ != nullptr) {
spdlog::warn("[ext/workspaces]: Register workspace manager again although already registered!");
return;
@@ -99,7 +99,7 @@ void WorkspaceManager::register_manager(wl_registry *registry, uint32_t name, ui
void WorkspaceManager::remove_workspace_group(uint32_t id) {
const auto it =
std::find_if(groups_.begin(), groups_.end(), [id](const auto &g) { return g->id() == id; });
std::find_if(groups_.begin(), groups_.end(), [id](const auto& g) { return g->id() == id; });
if (it == groups_.end()) {
spdlog::warn("[ext/workspaces]: Can't find workspace group with id {}", id);
@@ -111,7 +111,7 @@ void WorkspaceManager::remove_workspace_group(uint32_t id) {
void WorkspaceManager::remove_workspace(uint32_t id) {
const auto it = std::find_if(workspaces_.begin(), workspaces_.end(),
[id](const auto &w) { return w->id() == id; });
[id](const auto& w) { return w->id() == id; });
if (it == workspaces_.end()) {
spdlog::warn("[ext/workspaces]: Can't find workspace with id {}", id);
@@ -121,13 +121,13 @@ void WorkspaceManager::remove_workspace(uint32_t id) {
workspaces_.erase(it);
}
void WorkspaceManager::handle_workspace_group(ext_workspace_group_handle_v1 *handle) {
void WorkspaceManager::handle_workspace_group(ext_workspace_group_handle_v1* handle) {
const auto new_id = ++group_global_id;
groups_.push_back(std::make_unique<WorkspaceGroup>(*this, handle, new_id));
spdlog::debug("[ext/workspaces]: Workspace group {} created", new_id);
}
void WorkspaceManager::handle_workspace(ext_workspace_handle_v1 *handle) {
void WorkspaceManager::handle_workspace(ext_workspace_handle_v1* handle) {
const auto new_id = ++workspace_global_id;
const auto new_name = std::to_string(++workspace_name);
workspaces_.push_back(std::make_unique<Workspace>(config_, *this, handle, new_id, new_name));
@@ -143,7 +143,9 @@ void WorkspaceManager::handle_finished() {
ext_manager_ = nullptr;
}
void WorkspaceManager::commit() const { ext_workspace_manager_v1_commit(ext_manager_); }
void WorkspaceManager::commit() const {
if (ext_manager_) ext_workspace_manager_v1_commit(ext_manager_);
}
void WorkspaceManager::update() {
spdlog::debug("[ext/workspaces]: Updating state");
@@ -158,7 +160,7 @@ void WorkspaceManager::update() {
AModule::update();
}
bool WorkspaceManager::has_button(const Gtk::Button *button) {
bool WorkspaceManager::has_button(const Gtk::Button* button) {
const auto buttons = box_.get_children();
return std::find(buttons.begin(), buttons.end(), button) != buttons.end();
}
@@ -166,20 +168,20 @@ bool WorkspaceManager::has_button(const Gtk::Button *button) {
void WorkspaceManager::sort_workspaces() {
// determine if workspace ID's and names can be sort numerically or literally
auto is_numeric = [](const std::string &s) {
auto is_numeric = [](const std::string& s) {
return !s.empty() && std::all_of(s.begin(), s.end(), ::isdigit);
};
auto sort_by_workspace_id_numerically =
std::all_of(workspaces_.begin(), workspaces_.end(),
[&](const auto &w) { return is_numeric(w->workspace_id()); });
[&](const auto& w) { return is_numeric(w->workspace_id()); });
auto sort_by_name_numerically = std::all_of(workspaces_.begin(), workspaces_.end(),
[&](const auto &w) { return is_numeric(w->name()); });
[&](const auto& w) { return is_numeric(w->name()); });
// sort based on configuration setting with sort-by-id as fallback
std::sort(workspaces_.begin(), workspaces_.end(), [&](const auto &w1, const auto &w2) {
std::sort(workspaces_.begin(), workspaces_.end(), [&](const auto& w1, const auto& w2) {
if (sort_by_id_ || (!sort_by_name_ && !sort_by_coordinates_)) {
if (w1->workspace_id() == w2->workspace_id()) {
return w1->id() < w2->id();
@@ -218,7 +220,7 @@ void WorkspaceManager::sort_workspaces() {
}
void WorkspaceManager::clear_buttons() {
for (const auto &workspace : workspaces_) {
for (const auto& workspace : workspaces_) {
if (has_button(&workspace->button())) {
box_.remove(workspace->button());
}
@@ -226,13 +228,13 @@ void WorkspaceManager::clear_buttons() {
}
void WorkspaceManager::update_buttons() {
const auto *output = gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj());
const auto* output = gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj());
// go through all workspace
for (const auto &workspace : workspaces_) {
for (const auto& workspace : workspaces_) {
const bool workspace_on_any_group_for_output =
std::any_of(groups_.begin(), groups_.end(), [&](const auto &group) {
std::any_of(groups_.begin(), groups_.end(), [&](const auto& group) {
const bool group_on_output = group->has_output(output) || all_outputs_;
const bool workspace_on_group = group->has_workspace(workspace->handle());
return group_on_output && workspace_on_group;
@@ -259,7 +261,7 @@ void WorkspaceManager::update_buttons() {
// WorkspaceGroup
WorkspaceGroup::WorkspaceGroup(WorkspaceManager &manager, ext_workspace_group_handle_v1 *handle,
WorkspaceGroup::WorkspaceGroup(WorkspaceManager& manager, ext_workspace_group_handle_v1* handle,
uint32_t id)
: workspaces_manager_(manager), ext_handle_(handle), id_(id) {
add_workspace_group_listener(ext_handle_, this);
@@ -272,11 +274,11 @@ WorkspaceGroup::~WorkspaceGroup() {
spdlog::debug("[ext/workspaces]: Workspace group {} destroyed", id_);
}
bool WorkspaceGroup::has_output(const wl_output *output) {
bool WorkspaceGroup::has_output(const wl_output* output) {
return std::find(outputs_.begin(), outputs_.end(), output) != outputs_.end();
}
bool WorkspaceGroup::has_workspace(const ext_workspace_handle_v1 *workspace) {
bool WorkspaceGroup::has_workspace(const ext_workspace_handle_v1* workspace) {
return std::find(workspaces_.begin(), workspaces_.end(), workspace) != workspaces_.end();
}
@@ -288,20 +290,20 @@ void WorkspaceGroup::handle_capabilities(uint32_t capabilities) {
}
}
void WorkspaceGroup::handle_output_enter(wl_output *output) { outputs_.push_back(output); }
void WorkspaceGroup::handle_output_enter(wl_output* output) { outputs_.push_back(output); }
void WorkspaceGroup::handle_output_leave(wl_output *output) {
void WorkspaceGroup::handle_output_leave(wl_output* output) {
const auto it = std::find(outputs_.begin(), outputs_.end(), output);
if (it != outputs_.end()) {
outputs_.erase(it);
}
}
void WorkspaceGroup::handle_workspace_enter(ext_workspace_handle_v1 *handle) {
void WorkspaceGroup::handle_workspace_enter(ext_workspace_handle_v1* handle) {
workspaces_.push_back(handle);
}
void WorkspaceGroup::handle_workspace_leave(ext_workspace_handle_v1 *handle) {
void WorkspaceGroup::handle_workspace_leave(ext_workspace_handle_v1* handle) {
const auto it = std::find(workspaces_.begin(), workspaces_.end(), handle);
if (it != workspaces_.end()) {
workspaces_.erase(it);
@@ -315,30 +317,30 @@ void WorkspaceGroup::handle_removed() {
// Workspace
Workspace::Workspace(const Json::Value &config, WorkspaceManager &manager,
ext_workspace_handle_v1 *handle, uint32_t id, const std::string &name)
Workspace::Workspace(const Json::Value& config, WorkspaceManager& manager,
ext_workspace_handle_v1* handle, uint32_t id, const std::string& name)
: workspace_manager_(manager), ext_handle_(handle), id_(id), workspace_id_(name), name_(name) {
add_workspace_listener(ext_handle_, this);
// parse configuration
const auto &config_active_only = config["active-only"];
const auto& config_active_only = config["active-only"];
if (config_active_only.isBool()) {
active_only_ = config_active_only.asBool();
}
const auto &config_ignore_hidden = config["ignore-hidden"];
const auto& config_ignore_hidden = config["ignore-hidden"];
if (config_ignore_hidden.isBool()) {
ignore_hidden_ = config_ignore_hidden.asBool();
}
const auto &config_format = config["format"];
const auto& config_format = config["format"];
format_ = config_format.isString() ? config_format.asString() : "{name}";
with_icon_ = format_.find("{icon}") != std::string::npos;
if (with_icon_ && icon_map_.empty()) {
const auto &format_icons = config["format-icons"];
for (auto &n : format_icons.getMemberNames()) {
const auto& format_icons = config["format-icons"];
for (auto& n : format_icons.getMemberNames()) {
icon_map_.emplace(n, format_icons[n].asString());
}
}
@@ -413,19 +415,19 @@ void Workspace::update() {
fmt::arg("icon", with_icon_ ? icon() : "")));
}
void Workspace::handle_id(const std::string &id) {
void Workspace::handle_id(const std::string& id) {
spdlog::debug("[ext/workspaces]: ID for workspace {}: {}", id_, id);
workspace_id_ = id;
workspace_manager_.set_needs_sorting();
}
void Workspace::handle_name(const std::string &name) {
void Workspace::handle_name(const std::string& name) {
spdlog::debug("[ext/workspaces]: Name for workspace {}: {}", id_, name);
name_ = name;
workspace_manager_.set_needs_sorting();
}
void Workspace::handle_coordinates(const std::vector<uint32_t> &coordinates) {
void Workspace::handle_coordinates(const std::vector<uint32_t>& coordinates) {
coordinates_ = coordinates;
workspace_manager_.set_needs_sorting();
}
@@ -453,7 +455,7 @@ void Workspace::handle_removed() {
workspace_manager_.remove_workspace(id_);
}
bool Workspace::handle_clicked(const GdkEventButton *button) const {
bool Workspace::handle_clicked(const GdkEventButton* button) const {
std::string action;
if (button->button == GDK_BUTTON_PRIMARY) {
action = on_click_action_;
+52 -52
View File
@@ -9,44 +9,44 @@
namespace waybar::modules::ext {
static void handle_global(void *data, wl_registry *registry, uint32_t name, const char *interface,
static void handle_global(void* data, wl_registry* registry, uint32_t name, const char* interface,
uint32_t version) {
if (std::strcmp(interface, ext_workspace_manager_v1_interface.name) == 0) {
static_cast<WorkspaceManager *>(data)->register_manager(registry, name, version);
static_cast<WorkspaceManager*>(data)->register_manager(registry, name, version);
}
}
static void handle_global_remove(void *data, wl_registry *registry, uint32_t name) {
static void handle_global_remove(void* data, wl_registry* registry, uint32_t name) {
/* Nothing to do here */
}
static const wl_registry_listener registry_listener_impl = {.global = handle_global,
.global_remove = handle_global_remove};
void add_registry_listener(void *data) {
wl_display *display = Client::inst()->wl_display;
wl_registry *registry = wl_display_get_registry(display);
void add_registry_listener(void* data) {
wl_display* display = Client::inst()->wl_display;
wl_registry* registry = wl_display_get_registry(display);
wl_registry_add_listener(registry, &registry_listener_impl, data);
wl_display_roundtrip(display);
}
static void workspace_manager_handle_workspace_group(
void *data, ext_workspace_manager_v1 *_, ext_workspace_group_handle_v1 *workspace_group) {
static_cast<WorkspaceManager *>(data)->handle_workspace_group(workspace_group);
void* data, ext_workspace_manager_v1* _, ext_workspace_group_handle_v1* workspace_group) {
static_cast<WorkspaceManager*>(data)->handle_workspace_group(workspace_group);
}
static void workspace_manager_handle_workspace(void *data, ext_workspace_manager_v1 *_,
ext_workspace_handle_v1 *workspace) {
static_cast<WorkspaceManager *>(data)->handle_workspace(workspace);
static void workspace_manager_handle_workspace(void* data, ext_workspace_manager_v1* _,
ext_workspace_handle_v1* workspace) {
static_cast<WorkspaceManager*>(data)->handle_workspace(workspace);
}
static void workspace_manager_handle_done(void *data, ext_workspace_manager_v1 *_) {
static_cast<WorkspaceManager *>(data)->handle_done();
static void workspace_manager_handle_done(void* data, ext_workspace_manager_v1* _) {
static_cast<WorkspaceManager*>(data)->handle_done();
}
static void workspace_manager_handle_finished(void *data, ext_workspace_manager_v1 *_) {
static_cast<WorkspaceManager *>(data)->handle_finished();
static void workspace_manager_handle_finished(void* data, ext_workspace_manager_v1* _) {
static_cast<WorkspaceManager*>(data)->handle_finished();
}
static const ext_workspace_manager_v1_listener workspace_manager_impl = {
@@ -56,9 +56,9 @@ static const ext_workspace_manager_v1_listener workspace_manager_impl = {
.finished = workspace_manager_handle_finished,
};
ext_workspace_manager_v1 *workspace_manager_bind(wl_registry *registry, uint32_t name,
uint32_t version, void *data) {
auto *workspace_manager = static_cast<ext_workspace_manager_v1 *>(
ext_workspace_manager_v1* workspace_manager_bind(wl_registry* registry, uint32_t name,
uint32_t version, void* data) {
auto* workspace_manager = static_cast<ext_workspace_manager_v1*>(
wl_registry_bind(registry, name, &ext_workspace_manager_v1_interface, version));
if (workspace_manager)
@@ -69,33 +69,33 @@ ext_workspace_manager_v1 *workspace_manager_bind(wl_registry *registry, uint32_t
return workspace_manager;
}
static void workspace_group_handle_capabilities(void *data, ext_workspace_group_handle_v1 *_,
static void workspace_group_handle_capabilities(void* data, ext_workspace_group_handle_v1* _,
uint32_t capabilities) {
static_cast<WorkspaceGroup *>(data)->handle_capabilities(capabilities);
static_cast<WorkspaceGroup*>(data)->handle_capabilities(capabilities);
}
static void workspace_group_handle_output_enter(void *data, ext_workspace_group_handle_v1 *_,
wl_output *output) {
static_cast<WorkspaceGroup *>(data)->handle_output_enter(output);
static void workspace_group_handle_output_enter(void* data, ext_workspace_group_handle_v1* _,
wl_output* output) {
static_cast<WorkspaceGroup*>(data)->handle_output_enter(output);
}
static void workspace_group_handle_output_leave(void *data, ext_workspace_group_handle_v1 *_,
wl_output *output) {
static_cast<WorkspaceGroup *>(data)->handle_output_leave(output);
static void workspace_group_handle_output_leave(void* data, ext_workspace_group_handle_v1* _,
wl_output* output) {
static_cast<WorkspaceGroup*>(data)->handle_output_leave(output);
}
static void workspace_group_handle_workspace_enter(void *data, ext_workspace_group_handle_v1 *_,
ext_workspace_handle_v1 *workspace) {
static_cast<WorkspaceGroup *>(data)->handle_workspace_enter(workspace);
static void workspace_group_handle_workspace_enter(void* data, ext_workspace_group_handle_v1* _,
ext_workspace_handle_v1* workspace) {
static_cast<WorkspaceGroup*>(data)->handle_workspace_enter(workspace);
}
static void workspace_group_handle_workspace_leave(void *data, ext_workspace_group_handle_v1 *_,
ext_workspace_handle_v1 *workspace) {
static_cast<WorkspaceGroup *>(data)->handle_workspace_leave(workspace);
static void workspace_group_handle_workspace_leave(void* data, ext_workspace_group_handle_v1* _,
ext_workspace_handle_v1* workspace) {
static_cast<WorkspaceGroup*>(data)->handle_workspace_leave(workspace);
}
static void workspace_group_handle_removed(void *data, ext_workspace_group_handle_v1 *_) {
static_cast<WorkspaceGroup *>(data)->handle_removed();
static void workspace_group_handle_removed(void* data, ext_workspace_group_handle_v1* _) {
static_cast<WorkspaceGroup*>(data)->handle_removed();
}
static const ext_workspace_group_handle_v1_listener workspace_group_impl = {
@@ -106,43 +106,43 @@ static const ext_workspace_group_handle_v1_listener workspace_group_impl = {
.workspace_leave = workspace_group_handle_workspace_leave,
.removed = workspace_group_handle_removed};
void add_workspace_group_listener(ext_workspace_group_handle_v1 *workspace_group_handle,
void *data) {
void add_workspace_group_listener(ext_workspace_group_handle_v1* workspace_group_handle,
void* data) {
ext_workspace_group_handle_v1_add_listener(workspace_group_handle, &workspace_group_impl, data);
}
void workspace_handle_name(void *data, struct ext_workspace_handle_v1 *_, const char *name) {
static_cast<Workspace *>(data)->handle_name(name);
void workspace_handle_name(void* data, struct ext_workspace_handle_v1* _, const char* name) {
static_cast<Workspace*>(data)->handle_name(name);
}
void workspace_handle_id(void *data, struct ext_workspace_handle_v1 *_, const char *id) {
static_cast<Workspace *>(data)->handle_id(id);
void workspace_handle_id(void* data, struct ext_workspace_handle_v1* _, const char* id) {
static_cast<Workspace*>(data)->handle_id(id);
}
void workspace_handle_coordinates(void *data, struct ext_workspace_handle_v1 *_,
struct wl_array *coordinates) {
void workspace_handle_coordinates(void* data, struct ext_workspace_handle_v1* _,
struct wl_array* coordinates) {
std::vector<uint32_t> coords_vec;
auto coords = static_cast<uint32_t *>(coordinates->data);
auto coords = static_cast<uint32_t*>(coordinates->data);
for (size_t i = 0; i < coordinates->size / sizeof(uint32_t); ++i) {
coords_vec.push_back(coords[i]);
}
static_cast<Workspace *>(data)->handle_coordinates(coords_vec);
static_cast<Workspace*>(data)->handle_coordinates(coords_vec);
}
void workspace_handle_state(void *data, struct ext_workspace_handle_v1 *workspace_handle,
void workspace_handle_state(void* data, struct ext_workspace_handle_v1* workspace_handle,
uint32_t state) {
static_cast<Workspace *>(data)->handle_state(state);
static_cast<Workspace*>(data)->handle_state(state);
}
static void workspace_handle_capabilities(void *data,
struct ext_workspace_handle_v1 *workspace_handle,
static void workspace_handle_capabilities(void* data,
struct ext_workspace_handle_v1* workspace_handle,
uint32_t capabilities) {
static_cast<Workspace *>(data)->handle_capabilities(capabilities);
static_cast<Workspace*>(data)->handle_capabilities(capabilities);
}
void workspace_handle_removed(void *data, struct ext_workspace_handle_v1 *workspace_handle) {
static_cast<Workspace *>(data)->handle_removed();
void workspace_handle_removed(void* data, struct ext_workspace_handle_v1* workspace_handle) {
static_cast<Workspace*>(data)->handle_removed();
}
static const ext_workspace_handle_v1_listener workspace_impl = {
@@ -153,7 +153,7 @@ static const ext_workspace_handle_v1_listener workspace_impl = {
.capabilities = workspace_handle_capabilities,
.removed = workspace_handle_removed};
void add_workspace_listener(ext_workspace_handle_v1 *workspace_handle, void *data) {
void add_workspace_listener(ext_workspace_handle_v1* workspace_handle, void* data) {
ext_workspace_handle_v1_add_listener(workspace_handle, &workspace_impl, data);
}
} // namespace waybar::modules::ext
+4 -4
View File
@@ -128,9 +128,9 @@ void Gamemode::getData() {
Glib::VariantContainerBase data = gamemode_proxy->call_sync("Get", parameters);
if (data && data.is_of_type(Glib::VariantType("(v)"))) {
Glib::VariantBase variant;
g_variant_get(data.gobj_copy(), "(v)", &variant);
g_variant_get(const_cast<GVariant*>(data.gobj()), "(v)", &variant);
if (variant && variant.is_of_type(Glib::VARIANT_TYPE_INT32)) {
g_variant_get(variant.gobj_copy(), "i", &gameCount);
g_variant_get(const_cast<GVariant*>(variant.gobj()), "i", &gameCount);
return;
}
}
@@ -158,7 +158,7 @@ void Gamemode::prepareForSleep_cb(const Glib::RefPtr<Gio::DBus::Connection>& con
const Glib::VariantContainerBase& parameters) {
if (parameters.is_of_type(Glib::VariantType("(b)"))) {
gboolean sleeping;
g_variant_get(parameters.gobj_copy(), "(b)", &sleeping);
g_variant_get(const_cast<GVariant*>(parameters.gobj()), "(b)", &sleeping);
if (!sleeping) {
getData();
dp.emit();
@@ -212,7 +212,7 @@ auto Gamemode::update() -> void {
// Tooltip
if (tooltip) {
std::string text = fmt::format(fmt::runtime(tooltip_format), fmt::arg("count", gameCount));
box_.set_tooltip_text(text);
box_.set_tooltip_markup(text);
}
// Label format
+181 -67
View File
@@ -9,44 +9,47 @@
#include <sys/un.h>
#include <unistd.h>
#include <array>
#include <cerrno>
#include <cstring>
#include <filesystem>
#include <optional>
#include <string>
#include "util/scoped_fd.hpp"
namespace waybar::modules::hyprland {
std::filesystem::path IPC::socketFolder_;
std::optional<bool> IPC::s_luaProtocolDetected_;
std::filesystem::path IPC::getSocketFolder(const char* instanceSig) {
static std::mutex folderMutex;
std::unique_lock lock(folderMutex);
// socket path, specified by EventManager of Hyprland
if (!socketFolder_.empty()) {
return socketFolder_;
if (socketFolder_.empty()) {
const char* xdgRuntimeDirEnv = std::getenv("XDG_RUNTIME_DIR");
std::filesystem::path xdgRuntimeDir;
// Only set path if env variable is set
if (xdgRuntimeDirEnv != nullptr) {
xdgRuntimeDir = std::filesystem::path(xdgRuntimeDirEnv);
}
if (!xdgRuntimeDir.empty() && std::filesystem::exists(xdgRuntimeDir / "hypr")) {
socketFolder_ = xdgRuntimeDir / "hypr";
} else {
spdlog::warn("$XDG_RUNTIME_DIR/hypr does not exist, falling back to /tmp/hypr");
socketFolder_ = std::filesystem::path("/tmp") / "hypr";
}
}
const char* xdgRuntimeDirEnv = std::getenv("XDG_RUNTIME_DIR");
std::filesystem::path xdgRuntimeDir;
// Only set path if env variable is set
if (xdgRuntimeDirEnv != nullptr) {
xdgRuntimeDir = std::filesystem::path(xdgRuntimeDirEnv);
}
if (!xdgRuntimeDir.empty() && std::filesystem::exists(xdgRuntimeDir / "hypr")) {
socketFolder_ = xdgRuntimeDir / "hypr";
} else {
spdlog::warn("$XDG_RUNTIME_DIR/hypr does not exist, falling back to /tmp/hypr");
socketFolder_ = std::filesystem::path("/tmp") / "hypr";
}
socketFolder_ = socketFolder_ / instanceSig;
return socketFolder_;
return socketFolder_ / instanceSig;
}
IPC::IPC() {
// will start IPC and relay events to parseIPC
ipcThread_ = std::thread([this]() { socketListener(); });
socketOwnerPid_ = getpid();
ipcThread_ = std::thread([this]() { socketListener(); });
}
IPC::~IPC() {
@@ -54,19 +57,20 @@ IPC::~IPC() {
// failed exec()) exits.
if (getpid() != socketOwnerPid_) return;
running_ = false;
running_.store(false, std::memory_order_relaxed);
spdlog::info("Hyprland IPC stopping...");
if (socketfd_ != -1) {
spdlog::trace("Shutting down socket");
if (shutdown(socketfd_, SHUT_RDWR) == -1) {
spdlog::error("Hyprland IPC: Couldn't shutdown socket");
}
spdlog::trace("Closing socket");
if (close(socketfd_) == -1) {
spdlog::error("Hyprland IPC: Couldn't close socket");
{
std::lock_guard<std::mutex> lock(socketMutex_);
if (socketfd_ != -1) {
spdlog::trace("Shutting down socket");
if (shutdown(socketfd_, SHUT_RDWR) == -1 && errno != ENOTCONN) {
spdlog::error("Hyprland IPC: Couldn't shutdown socket");
}
}
}
ipcThread_.join();
if (ipcThread_.joinable()) {
ipcThread_.join();
}
}
IPC& IPC::inst() {
@@ -85,10 +89,10 @@ void IPC::socketListener() {
spdlog::info("Hyprland IPC starting");
struct sockaddr_un addr;
socketfd_ = socket(AF_UNIX, SOCK_STREAM, 0);
struct sockaddr_un addr = {};
const int socketfd = socket(AF_UNIX, SOCK_STREAM, 0);
if (socketfd_ == -1) {
if (socketfd == -1) {
spdlog::error("Hyprland IPC: socketfd failed");
return;
}
@@ -96,44 +100,76 @@ void IPC::socketListener() {
addr.sun_family = AF_UNIX;
auto socketPath = IPC::getSocketFolder(his) / ".socket2.sock";
if (socketPath.native().size() >= sizeof(addr.sun_path)) {
spdlog::error("Hyprland IPC: Socket path is too long: {}", socketPath.string());
close(socketfd);
return;
}
strncpy(addr.sun_path, socketPath.c_str(), sizeof(addr.sun_path) - 1);
addr.sun_path[sizeof(addr.sun_path) - 1] = 0;
int l = sizeof(struct sockaddr_un);
if (connect(socketfd_, (struct sockaddr*)&addr, l) == -1) {
spdlog::error("Hyprland IPC: Unable to connect?");
if (connect(socketfd, (struct sockaddr*)&addr, l) == -1) {
spdlog::error("Hyprland IPC: Unable to connect? {}", std::strerror(errno));
close(socketfd);
return;
}
auto* file = fdopen(socketfd_, "r");
if (file == nullptr) {
spdlog::error("Hyprland IPC: Couldn't open file descriptor");
return;
{
std::lock_guard<std::mutex> lock(socketMutex_);
socketfd_ = socketfd;
}
while (running_) {
std::string pending;
while (running_.load(std::memory_order_relaxed)) {
std::array<char, 1024> buffer; // Hyprland socket2 events are max 1024 bytes
const ssize_t bytes_read = read(socketfd, buffer.data(), buffer.size());
auto* receivedCharPtr = fgets(buffer.data(), buffer.size(), file);
if (receivedCharPtr == nullptr) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
continue;
if (bytes_read == 0) {
if (running_.load(std::memory_order_relaxed)) {
spdlog::warn("Hyprland IPC: Socket closed by peer");
}
break;
}
std::string messageReceived(buffer.data());
messageReceived = messageReceived.substr(0, messageReceived.find_first_of('\n'));
spdlog::debug("hyprland IPC received {}", messageReceived);
try {
parseIPC(messageReceived);
} catch (std::exception& e) {
spdlog::warn("Failed to parse IPC message: {}, reason: {}", messageReceived, e.what());
} catch (...) {
throw;
if (bytes_read < 0) {
if (errno == EINTR) {
continue;
}
if (!running_.load(std::memory_order_relaxed)) {
break;
}
spdlog::error("Hyprland IPC: read failed: {}", std::strerror(errno));
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
pending.append(buffer.data(), static_cast<std::size_t>(bytes_read));
for (auto newline_pos = pending.find('\n'); newline_pos != std::string::npos;
newline_pos = pending.find('\n')) {
std::string messageReceived = pending.substr(0, newline_pos);
pending.erase(0, newline_pos + 1);
if (messageReceived.empty()) {
continue;
}
spdlog::debug("hyprland IPC received {}", messageReceived);
try {
parseIPC(messageReceived);
} catch (std::exception& e) {
spdlog::warn("Failed to parse IPC message: {}, reason: {}", messageReceived, e.what());
} catch (...) {
throw;
}
}
}
{
std::lock_guard<std::mutex> lock(socketMutex_);
if (socketfd_ != -1) {
if (close(socketfd_) == -1) {
spdlog::error("Hyprland IPC: Couldn't close socket");
}
socketfd_ = -1;
}
}
spdlog::debug("Hyprland IPC stopped");
}
@@ -178,7 +214,7 @@ void IPC::unregisterForIPC(EventHandler* ev_handler) {
std::string IPC::getSocket1Reply(const std::string& rq) {
// basically hyprctl
const auto serverSocket = socket(AF_UNIX, SOCK_STREAM, 0);
util::ScopedFd serverSocket(socket(AF_UNIX, SOCK_STREAM, 0));
if (serverSocket < 0) {
throw std::runtime_error("Hyprland IPC: Couldn't open a socket (1)");
@@ -198,8 +234,10 @@ std::string IPC::getSocket1Reply(const std::string& rq) {
std::string socketPath = IPC::getSocketFolder(instanceSig) / ".socket.sock";
// Use snprintf to copy the socketPath string into serverAddress.sun_path
if (snprintf(serverAddress.sun_path, sizeof(serverAddress.sun_path), "%s", socketPath.c_str()) <
0) {
const auto socketPathLength =
snprintf(serverAddress.sun_path, sizeof(serverAddress.sun_path), "%s", socketPath.c_str());
if (socketPathLength < 0 ||
socketPathLength >= static_cast<int>(sizeof(serverAddress.sun_path))) {
throw std::runtime_error("Hyprland IPC: Couldn't copy socket path (6)");
}
@@ -208,28 +246,39 @@ std::string IPC::getSocket1Reply(const std::string& rq) {
throw std::runtime_error("Hyprland IPC: Couldn't connect to " + socketPath + ". (3)");
}
auto sizeWritten = write(serverSocket, rq.c_str(), rq.length());
std::size_t totalWritten = 0;
while (totalWritten < rq.length()) {
const auto sizeWritten =
write(serverSocket, rq.c_str() + totalWritten, rq.length() - totalWritten);
if (sizeWritten < 0) {
spdlog::error("Hyprland IPC: Couldn't write (4)");
return "";
if (sizeWritten < 0) {
if (errno == EINTR) {
continue;
}
spdlog::error("Hyprland IPC: Couldn't write (4)");
return "";
}
if (sizeWritten == 0) {
spdlog::error("Hyprland IPC: Socket write made no progress");
return "";
}
totalWritten += static_cast<std::size_t>(sizeWritten);
}
std::array<char, 8192> buffer = {0};
std::string response;
ssize_t sizeWritten = 0;
do {
sizeWritten = read(serverSocket, buffer.data(), 8192);
if (sizeWritten < 0) {
spdlog::error("Hyprland IPC: Couldn't read (5)");
close(serverSocket);
return "";
}
response.append(buffer.data(), sizeWritten);
} while (sizeWritten > 0);
close(serverSocket);
return response;
}
@@ -243,4 +292,69 @@ Json::Value IPC::getSocket1JsonReply(const std::string& rq) {
return parser_.parse(reply);
}
bool IPC::isLuaProtocol() {
if (s_luaProtocolDetected_.has_value()) {
return *s_luaProtocolDetected_;
}
// Probe: send a harmless old-style dispatch and check the error.
// In Lua-based Hyprland (>= 0.54) the error contains "hl.dispatch".
// In older versions it returns "ok" or a different error.
auto reply = getSocket1Reply("dispatch workspace __waybar_probe__");
bool luaProto = reply.find("hl.dispatch") != std::string::npos;
if (luaProto) {
spdlog::info("Hyprland IPC: detected Lua-based dispatch protocol (Hyprland >= 0.54)");
} else {
spdlog::info("Hyprland IPC: detected legacy dispatch protocol");
}
s_luaProtocolDetected_ = luaProto;
return luaProto;
}
std::string IPC::buildLuaDispatch(const std::string& dispatcher, const std::string& arg) {
// Map old-style dispatchers to the new Lua hl.dsp API.
//
// Old format: dispatch workspace 1
// New format: /dispatch hl.dsp.focus({ workspace = "1" })
//
// Old format: dispatch focusworkspaceoncurrentmonitor 2
// New format: /dispatch hl.dsp.focus({ workspace = "2", on_current_monitor = true })
//
// Old format: dispatch togglespecialworkspace name
// New format: /dispatch hl.dsp.workspace.toggle_special("name")
if (dispatcher == "workspace") {
return "/dispatch hl.dsp.focus({ workspace = \"" + arg + "\" })";
}
if (dispatcher == "focusworkspaceoncurrentmonitor") {
return "/dispatch hl.dsp.focus({ workspace = \"" + arg + "\", on_current_monitor = true })";
}
if (dispatcher == "togglespecialworkspace") {
if (arg.empty()) {
return "/dispatch hl.dsp.workspace.toggle_special()";
}
return "/dispatch hl.dsp.workspace.toggle_special(\"" + arg + "\")";
}
// Fallback for any other dispatcher: try the old format wrapped in dispatch().
// This may not work for all dispatchers, but it's a reasonable default.
spdlog::warn("Hyprland IPC: unknown dispatcher '{}' in Lua mode, attempting generic format",
dispatcher);
return "/dispatch hl.dsp." + dispatcher + "(\"" + arg + "\")";
}
std::string IPC::dispatch(const std::string& dispatcher, const std::string& arg) {
if (isLuaProtocol()) {
return getSocket1Reply(buildLuaDispatch(dispatcher, arg));
}
// Legacy format: "dispatch <dispatcher> <arg>"
std::string cmd = "dispatch " + dispatcher;
if (!arg.empty()) {
cmd += " " + arg;
}
return getSocket1Reply(cmd);
}
} // namespace waybar::modules::hyprland
+57 -9
View File
@@ -48,12 +48,39 @@ auto Language::update() -> void {
fmt::arg("shortDescription", layout_.short_description),
fmt::arg("variant", layout_.variant)));
}
spdlog::debug("hyprland language formatted layout name {}", layoutName);
std::string tooltipContent = std::string{};
bool tooltip_enabled = tooltipEnabled();
if (tooltip_enabled) {
if (config_.isMember("tooltip-format")) {
auto tooltip_format = config_["tooltip-format"].asString();
if (config_.isMember("tooltip-format-" + layout_.short_description + "-" + layout_.variant)) {
const auto propName = "tooltip-format-" + layout_.short_description + "-" + layout_.variant;
tooltipContent = fmt::format(fmt::runtime(tooltip_format), config_[propName].asString());
} else if (config_.isMember("tooltip-format-" + layout_.short_description)) {
const auto propName = "tooltip-format-" + layout_.short_description;
tooltipContent = fmt::format(fmt::runtime(tooltip_format), config_[propName].asString());
} else {
tooltipContent =
trim(fmt::format(fmt::runtime(tooltip_format), fmt::arg("long", layout_.full_name),
fmt::arg("short", layout_.short_name),
fmt::arg("shortDescription", layout_.short_description),
fmt::arg("variant", layout_.variant)));
}
} else {
// if no tooltip format is provided, use the same text as the module
tooltipContent = layoutName;
}
spdlog::debug("hyprland language formatted tooltip content {}", tooltipContent);
}
if (!format_.empty()) {
label_.show();
label_.set_markup(layoutName);
if (tooltip_enabled) {
label_.set_tooltip_markup(tooltipContent);
}
} else {
label_.hide();
}
@@ -63,22 +90,43 @@ auto Language::update() -> void {
void Language::onEvent(const std::string& ev) {
std::lock_guard<std::mutex> lg(mutex_);
std::string kbName(begin(ev) + ev.find_last_of('>') + 1, begin(ev) + ev.find_first_of(','));
const auto payloadStart = ev.find(">>");
if (payloadStart == std::string::npos) {
spdlog::warn("hyprland language received malformed event: {}", ev);
return;
}
const auto payload = ev.substr(payloadStart + 2);
const auto kbSeparator = payload.find(',');
if (kbSeparator == std::string::npos) {
spdlog::warn("hyprland language received malformed event payload: {}", ev);
return;
}
// Last comma before variants parenthesis, eg:
// activelayout>>micro-star-int'l-co.,-ltd.-msi-gk50-elite-gaming-keyboard,English (US, intl.,
// with dead keys)
std::string beforeParenthesis;
auto parenthesisPos = ev.find_last_of('(');
auto parenthesisPos = payload.find_last_of('(');
if (parenthesisPos == std::string::npos) {
beforeParenthesis = ev;
beforeParenthesis = payload;
} else {
beforeParenthesis = std::string(begin(ev), begin(ev) + parenthesisPos);
beforeParenthesis = payload.substr(0, parenthesisPos);
}
auto layoutName = ev.substr(beforeParenthesis.find_last_of(',') + 1);
const auto layoutSeparator = beforeParenthesis.find_last_of(',');
if (layoutSeparator == std::string::npos) {
spdlog::warn("hyprland language received malformed layout payload: {}", ev);
return;
}
auto layoutName = payload.substr(layoutSeparator + 1);
if (config_.isMember("keyboard-name") && kbName != config_["keyboard-name"].asString())
return; // ignore
if (config_.isMember("keyboard-name")) {
const auto keyboardName = config_["keyboard-name"].asString();
// The keyboard name itself can contain commas, so match it as a full prefix
// (followed by the ',' separator) rather than comparing against the substring
// before the first comma, which would truncate such names and drop the event.
if (payload.size() <= keyboardName.size() || payload[keyboardName.size()] != ',' ||
payload.compare(0, keyboardName.size(), keyboardName) != 0)
return; // ignore
}
layoutName = waybar::util::sanitize_string(layoutName);
+17 -7
View File
@@ -44,12 +44,23 @@ auto Submap::parseConfig(const Json::Value& config) -> void {
auto Submap::update() -> void {
std::lock_guard<std::mutex> lg(mutex_);
// Handle style class changes
if (!prev_submap_.empty()) {
label_.get_style_context()->remove_class(prev_submap_);
}
if (!submap_.empty()) {
label_.get_style_context()->add_class(submap_);
}
prev_submap_ = submap_;
if (submap_.empty()) {
event_box_.hide();
} else {
label_.set_markup(fmt::format(fmt::runtime(format_), submap_));
if (tooltipEnabled()) {
label_.set_tooltip_text(submap_);
label_.set_tooltip_markup(submap_);
}
event_box_.show();
}
@@ -64,11 +75,12 @@ void Submap::onEvent(const std::string& ev) {
return;
}
auto submapName = ev.substr(ev.find_first_of('>') + 2);
if (!submap_.empty()) {
label_.get_style_context()->remove_class(submap_);
const auto separator = ev.find(">>");
if (separator == std::string::npos) {
spdlog::warn("hyprland submap received malformed event: {}", ev);
return;
}
auto submapName = ev.substr(separator + 2);
submap_ = submapName;
@@ -76,8 +88,6 @@ void Submap::onEvent(const std::string& ev) {
submap_ = default_submap_;
}
label_.get_style_context()->add_class(submap_);
spdlog::debug("hyprland submap onevent with {}", submap_);
dp.emit();
+72 -72
View File
@@ -1,5 +1,6 @@
#include "modules/hyprland/window.hpp"
#include <fmt/format.h>
#include <glibmm/fileutils.h>
#include <glibmm/keyfile.h>
#include <glibmm/miscutils.h>
@@ -19,21 +20,19 @@ std::shared_mutex windowIpcSmtx;
Window::Window(const std::string& id, const Bar& bar, const Json::Value& config)
: AAppIconLabel(config, "window", id, "{title}", 0, true), bar_(bar), m_ipc(IPC::inst()) {
std::unique_lock<std::shared_mutex> windowIpcUniqueLock(windowIpcSmtx);
separateOutputs_ = config["separate-outputs"].asBool();
update();
// register for hyprland ipc
std::unique_lock<std::shared_mutex> windowIpcUniqueLock(windowIpcSmtx);
m_ipc.registerForIPC("activewindow", this);
m_ipc.registerForIPC("closewindow", this);
m_ipc.registerForIPC("movewindow", this);
m_ipc.registerForIPC("changefloatingmode", this);
m_ipc.registerForIPC("fullscreen", this);
windowIpcUniqueLock.unlock();
queryActiveWorkspace();
update();
dp.emit();
}
@@ -45,6 +44,8 @@ Window::~Window() {
auto Window::update() -> void {
std::shared_lock<std::shared_mutex> windowIpcShareLock(windowIpcSmtx);
queryActiveWorkspace();
std::string windowName = waybar::util::sanitize_string(workspace_.last_window_title);
std::string windowAddress = workspace_.last_window;
@@ -53,8 +54,15 @@ auto Window::update() -> void {
std::string label_text;
if (!format_.empty()) {
label_.show();
// If the focused window name is empty and fallback is configured, use fallback text
std::string displayTitle = windowName;
if (displayTitle.empty() && config_["fallback"].isString()) {
displayTitle = config_["fallback"].asString();
}
label_text = waybar::util::rewriteString(
fmt::format(fmt::runtime(format_), fmt::arg("title", windowName),
fmt::format(fmt::runtime(format_), fmt::arg("title", displayTitle),
fmt::arg("initialTitle", windowData_.initial_title),
fmt::arg("class", windowData_.class_name),
fmt::arg("initialClass", windowData_.initial_class_name)),
@@ -70,13 +78,13 @@ auto Window::update() -> void {
tooltip_format = config_["tooltip-format"].asString();
}
if (!tooltip_format.empty()) {
label_.set_tooltip_text(
label_.set_tooltip_markup(
fmt::format(fmt::runtime(tooltip_format), fmt::arg("title", windowName),
fmt::arg("initialTitle", windowData_.initial_title),
fmt::arg("class", windowData_.class_name),
fmt::arg("initialClass", windowData_.initial_class_name)));
} else if (!label_text.empty()) {
label_.set_tooltip_text(label_text);
label_.set_tooltip_markup(label_text);
}
}
@@ -108,21 +116,14 @@ auto Window::update() -> void {
AAppIconLabel::update();
}
auto Window::getActiveWorkspace() -> Workspace {
const auto workspace = IPC::inst().getSocket1JsonReply("activeworkspace");
if (workspace.isObject()) {
return Workspace::parse(workspace);
}
return {};
}
auto Window::getActiveWorkspace() -> Workspace { return getActiveWorkspace(""); }
auto Window::getActiveWorkspace(const std::string& monitorName) -> Workspace {
const auto monitors = IPC::inst().getSocket1JsonReply("monitors");
if (monitors.isArray()) {
auto monitor = std::ranges::find_if(
monitors, [&](Json::Value monitor) { return monitor["name"] == monitorName; });
auto monitor = std::ranges::find_if(monitors, [&](const Json::Value& monitor) {
return monitorName.empty() ? monitor["focused"].asBool() : monitor["name"] == monitorName;
});
if (monitor == std::end(monitors)) {
spdlog::warn("Monitor not found: {}", monitorName);
return Workspace{
@@ -132,12 +133,13 @@ auto Window::getActiveWorkspace(const std::string& monitorName) -> Workspace {
.last_window_title = "",
};
}
const int id = (*monitor)["activeWorkspace"]["id"].asInt();
const int special_id = (*monitor)["specialWorkspace"]["id"].asInt();
const int id = special_id != 0 ? special_id : (*monitor)["activeWorkspace"]["id"].asInt();
const auto workspaces = IPC::inst().getSocket1JsonReply("workspaces");
if (workspaces.isArray()) {
auto workspace = std::ranges::find_if(
workspaces, [&](Json::Value workspace) { return workspace["id"] == id; });
workspaces, [&](const Json::Value& workspace) { return workspace["id"] == id; });
if (workspace == std::end(workspaces)) {
spdlog::warn("No workspace with id {}", id);
return Workspace{
@@ -175,71 +177,69 @@ auto Window::WindowData::parse(const Json::Value& value) -> Window::WindowData {
}
void Window::queryActiveWorkspace() {
std::shared_lock<std::shared_mutex> windowIpcShareLock(windowIpcSmtx);
if (separateOutputs_) {
workspace_ = getActiveWorkspace(this->bar_.output->name);
} else {
workspace_ = getActiveWorkspace();
}
focused_ = false;
windowData_ = WindowData{};
allFloating_ = false;
swallowing_ = false;
fullscreen_ = false;
solo_ = false;
soloClass_.clear();
if (workspace_.windows <= 0) {
return;
}
const auto clients = m_ipc.getSocket1JsonReply("clients");
if (!clients.isArray()) {
return;
}
auto activeWindow = std::ranges::find_if(clients, [&](const Json::Value& window) {
return window["address"] == workspace_.last_window;
});
if (activeWindow == std::end(clients)) {
return;
}
focused_ = true;
if (workspace_.windows > 0) {
const auto clients = m_ipc.getSocket1JsonReply("clients");
if (clients.isArray()) {
auto activeWindow = std::ranges::find_if(
clients, [&](Json::Value window) { return window["address"] == workspace_.last_window; });
if (activeWindow == std::end(clients)) {
focused_ = false;
return;
}
windowData_ = WindowData::parse(*activeWindow);
updateAppIconName(windowData_.class_name, windowData_.initial_class_name);
std::vector<Json::Value> workspaceWindows;
std::ranges::copy_if(clients, std::back_inserter(workspaceWindows), [&](Json::Value window) {
windowData_ = WindowData::parse(*activeWindow);
updateAppIconName(windowData_.class_name, windowData_.initial_class_name);
std::vector<Json::Value> workspaceWindows;
std::ranges::copy_if(
clients, std::back_inserter(workspaceWindows), [&](const Json::Value& window) {
return window["workspace"]["id"] == workspace_.id && window["mapped"].asBool();
});
swallowing_ = std::ranges::any_of(workspaceWindows, [&](Json::Value window) {
return !window["swallowing"].isNull() && window["swallowing"].asString() != "0x0";
});
std::vector<Json::Value> visibleWindows;
std::ranges::copy_if(workspaceWindows, std::back_inserter(visibleWindows),
[&](Json::Value window) { return !window["hidden"].asBool(); });
solo_ = 1 == std::count_if(visibleWindows.begin(), visibleWindows.end(),
[&](Json::Value window) { return !window["floating"].asBool(); });
allFloating_ = std::ranges::all_of(
visibleWindows, [&](Json::Value window) { return window["floating"].asBool(); });
fullscreen_ = windowData_.fullscreen;
swallowing_ = std::ranges::any_of(workspaceWindows, [&](const Json::Value& window) {
return !window["swallowing"].isNull() && window["swallowing"].asString() != "0x0";
});
std::vector<Json::Value> visibleWindows;
std::ranges::copy_if(workspaceWindows, std::back_inserter(visibleWindows),
[&](const Json::Value& window) { return !window["hidden"].asBool(); });
solo_ = 1 == std::count_if(
visibleWindows.begin(), visibleWindows.end(),
[&](const Json::Value& window) { return !window["floating"].asBool(); });
allFloating_ = std::ranges::all_of(
visibleWindows, [&](const Json::Value& window) { return window["floating"].asBool(); });
fullscreen_ = windowData_.fullscreen;
// Fullscreen windows look like they are solo
if (fullscreen_) {
solo_ = true;
}
// Fullscreen windows look like they are solo
if (fullscreen_) {
solo_ = true;
}
if (solo_) {
soloClass_ = windowData_.class_name;
} else {
soloClass_ = "";
}
}
} else {
focused_ = false;
windowData_ = WindowData{};
allFloating_ = false;
swallowing_ = false;
fullscreen_ = false;
solo_ = false;
soloClass_ = "";
if (solo_) {
soloClass_ = windowData_.class_name;
}
}
void Window::onEvent(const std::string& ev) {
queryActiveWorkspace();
dp.emit();
}
void Window::onEvent(const std::string& ev) { dp.emit(); }
void Window::setClass(const std::string& classname, bool enable) {
if (enable) {
+6 -9
View File
@@ -39,6 +39,8 @@ WindowCount::~WindowCount() {
auto WindowCount::update() -> void {
std::lock_guard<std::mutex> lg(mutex_);
queryActiveWorkspace();
std::string format = config_["format"].asString();
std::string formatEmpty = config_["format-empty"].asString();
std::string formatWindowed = config_["format-windowed"].asString();
@@ -56,7 +58,7 @@ auto WindowCount::update() -> void {
} else if (!format.empty()) {
label_.set_markup(fmt::format(fmt::runtime(format), workspace_.windows));
} else {
label_.set_text(fmt::format("{}", workspace_.windows));
label_.set_markup(fmt::format("{}", workspace_.windows));
}
label_.show();
@@ -77,7 +79,7 @@ auto WindowCount::getActiveWorkspace(const std::string& monitorName) -> Workspac
const auto monitors = m_ipc.getSocket1JsonReply("monitors");
if (monitors.isArray()) {
auto monitor = std::ranges::find_if(
monitors, [&](Json::Value monitor) { return monitor["name"] == monitorName; });
monitors, [&](const Json::Value& monitor) { return monitor["name"] == monitorName; });
if (monitor == std::end(monitors)) {
spdlog::warn("Monitor not found: {}", monitorName);
return Workspace{
@@ -91,7 +93,7 @@ auto WindowCount::getActiveWorkspace(const std::string& monitorName) -> Workspac
const auto workspaces = m_ipc.getSocket1JsonReply("workspaces");
if (workspaces.isArray()) {
auto workspace = std::ranges::find_if(
workspaces, [&](Json::Value workspace) { return workspace["id"] == id; });
workspaces, [&](const Json::Value& workspace) { return workspace["id"] == id; });
if (workspace == std::end(workspaces)) {
spdlog::warn("No workspace with id {}", id);
return Workspace{
@@ -116,8 +118,6 @@ auto WindowCount::Workspace::parse(const Json::Value& value) -> WindowCount::Wor
}
void WindowCount::queryActiveWorkspace() {
std::lock_guard<std::mutex> lg(mutex_);
if (separateOutputs_) {
workspace_ = getActiveWorkspace(this->bar_.output->name);
} else {
@@ -125,10 +125,7 @@ void WindowCount::queryActiveWorkspace() {
}
}
void WindowCount::onEvent(const std::string& ev) {
queryActiveWorkspace();
dp.emit();
}
void WindowCount::onEvent(const std::string& ev) { dp.emit(); }
void WindowCount::setClass(const std::string& classname, bool enable) {
if (enable) {
+10 -9
View File
@@ -11,7 +11,7 @@
namespace waybar::modules::hyprland {
WindowCreationPayload::WindowCreationPayload(Json::Value const &client_data)
WindowCreationPayload::WindowCreationPayload(Json::Value const& client_data)
: m_window(std::make_pair(client_data["class"].asString(), client_data["title"].asString())),
m_windowAddress(client_data["address"].asString()),
m_workspaceName(client_data["workspace"]["name"].asString()) {
@@ -19,7 +19,7 @@ WindowCreationPayload::WindowCreationPayload(Json::Value const &client_data)
clearWorkspaceName();
}
WindowCreationPayload::WindowCreationPayload(std::string workspace_name,
WindowCreationPayload::WindowCreationPayload(const std::string& workspace_name,
WindowAddress window_address, WindowRepr window_repr)
: m_window(std::move(window_repr)),
m_windowAddress(std::move(window_address)),
@@ -28,9 +28,10 @@ WindowCreationPayload::WindowCreationPayload(std::string workspace_name,
clearWorkspaceName();
}
WindowCreationPayload::WindowCreationPayload(std::string workspace_name,
WindowAddress window_address, std::string window_class,
std::string window_title, bool is_active)
WindowCreationPayload::WindowCreationPayload(const std::string& workspace_name,
WindowAddress window_address,
const std::string& window_class,
const std::string& window_title, bool is_active)
: m_window(std::make_pair(std::move(window_class), std::move(window_title))),
m_windowAddress(std::move(window_address)),
m_workspaceName(std::move(workspace_name)),
@@ -73,7 +74,7 @@ void WindowCreationPayload::clearWorkspaceName() {
}
}
bool WindowCreationPayload::isEmpty(Workspaces &workspace_manager) {
bool WindowCreationPayload::isEmpty(Workspaces& workspace_manager) {
if (std::holds_alternative<Repr>(m_window)) {
return std::get<Repr>(m_window).empty();
}
@@ -89,16 +90,16 @@ bool WindowCreationPayload::isEmpty(Workspaces &workspace_manager) {
int WindowCreationPayload::incrementTimeSpentUncreated() { return m_timeSpentUncreated++; }
void WindowCreationPayload::moveToWorkspace(std::string &new_workspace_name) {
void WindowCreationPayload::moveToWorkspace(std::string& new_workspace_name) {
m_workspaceName = new_workspace_name;
}
WindowRepr WindowCreationPayload::repr(Workspaces &workspace_manager) {
WindowRepr WindowCreationPayload::repr(Workspaces& workspace_manager) {
if (std::holds_alternative<Repr>(m_window)) {
return std::get<Repr>(m_window);
}
if (std::holds_alternative<ClassAndTitle>(m_window)) {
auto const &[window_class, window_title] = std::get<ClassAndTitle>(m_window);
auto const& [window_class, window_title] = std::get<ClassAndTitle>(m_window);
return {m_windowAddress, window_class, window_title,
workspace_manager.getRewrite(window_class, window_title), m_isActive};
}
+178 -44
View File
@@ -1,5 +1,6 @@
#include <json/value.h>
#include <spdlog/spdlog.h>
#include <glibmm/main.h>
#include <memory>
#include <string>
@@ -11,8 +12,8 @@
namespace waybar::modules::hyprland {
Workspace::Workspace(const Json::Value &workspace_data, Workspaces &workspace_manager,
const Json::Value &clients_data)
Workspace::Workspace(const Json::Value& workspace_data, Workspaces& workspace_manager,
const Json::Value& clients_data)
: m_workspaceManager(workspace_manager),
m_id(workspace_data["id"].asInt()),
m_name(workspace_data["name"].asString()),
@@ -30,6 +31,11 @@ Workspace::Workspace(const Json::Value &workspace_data, Workspaces &workspace_ma
}
m_button.add_events(Gdk::BUTTON_PRESS_MASK);
m_button.add_events(Gdk::ENTER_NOTIFY_MASK | Gdk::LEAVE_NOTIFY_MASK);
m_button.signal_enter_notify_event().connect(sigc::mem_fun(*this, &Workspace::handleEnter));
m_button.signal_leave_notify_event().connect(sigc::mem_fun(*this, &Workspace::handleLeave));
m_button.signal_button_press_event().connect(sigc::mem_fun(*this, &Workspace::handleClicked),
false);
@@ -45,8 +51,14 @@ Workspace::Workspace(const Json::Value &workspace_data, Workspaces &workspace_ma
initializeWindowMap(clients_data);
}
void addOrRemoveClass(const Glib::RefPtr<Gtk::StyleContext> &context, bool condition,
const std::string &class_name) {
Workspace::~Workspace() {
// Disconnect the hover-check timeout so it can't fire on this destroyed
// instance (Workspaces are removed at runtime while a check may be armed).
stopHoverCheck();
}
void addOrRemoveClass(const Glib::RefPtr<Gtk::StyleContext>& context, bool condition,
const std::string& class_name) {
if (condition) {
context->add_class(class_name);
} else {
@@ -54,9 +66,9 @@ void addOrRemoveClass(const Glib::RefPtr<Gtk::StyleContext> &context, bool condi
}
}
std::optional<WindowRepr> Workspace::closeWindow(WindowAddress const &addr) {
std::optional<WindowRepr> Workspace::closeWindow(WindowAddress const& addr) {
auto it = std::ranges::find_if(m_windowMap,
[&addr](const auto &window) { return window.address == addr; });
[&addr](const auto& window) { return window.address == addr; });
// If the vector contains the address, remove it and return the window representation
if (it != m_windowMap.end()) {
WindowRepr windowRepr = *it;
@@ -66,47 +78,143 @@ std::optional<WindowRepr> Workspace::closeWindow(WindowAddress const &addr) {
return std::nullopt;
}
bool Workspace::handleClicked(GdkEventButton *bt) const {
bool Workspace::pointerInsideButton() {
auto display = Gdk::Display::get_default();
if (!display) {
return false;
}
auto seat = display->get_default_seat();
if (!seat) {
return false;
}
auto pointer = seat->get_pointer();
if (!pointer) {
return false;
}
Glib::RefPtr<Gdk::Screen> screen;
int pointerRootX = 0;
int pointerRootY = 0;
pointer->get_position(screen, pointerRootX, pointerRootY);
Gtk::Widget* toplevel = m_button.get_toplevel();
if (toplevel == nullptr || !toplevel->get_window()) {
return false;
}
int buttonX = 0;
int buttonY = 0;
if (!m_button.translate_coordinates(*toplevel, 0, 0, buttonX, buttonY)) {
return false;
}
int windowRootX = 0;
int windowRootY = 0;
toplevel->get_window()->get_root_origin(windowRootX, windowRootY);
const auto allocation = m_button.get_allocation();
const int buttonRootX = windowRootX + buttonX;
const int buttonRootY = windowRootY + buttonY;
const int buttonWidth = allocation.get_width();
const int buttonHeight = allocation.get_height();
return pointerRootX >= buttonRootX && pointerRootY >= buttonRootY &&
pointerRootX < buttonRootX + buttonWidth &&
pointerRootY < buttonRootY + buttonHeight;
}
bool Workspace::syncHoverClass() {
auto styleContext = m_button.get_style_context();
if (pointerInsideButton()) {
styleContext->add_class("workspace-hover");
return true;
}
styleContext->remove_class("workspace-hover");
stopHoverCheck();
return false;
}
void Workspace::startHoverCheck() {
if (m_hoverCheckConnection.connected()) {
return;
}
m_hoverCheckConnection = Glib::signal_timeout().connect(
sigc::mem_fun(*this, &Workspace::syncHoverClass),
50);
}
void Workspace::stopHoverCheck() {
if (m_hoverCheckConnection.connected()) {
m_hoverCheckConnection.disconnect();
}
}
bool Workspace::handleEnter(GdkEventCrossing* /*event*/) {
m_button.get_style_context()->add_class("workspace-hover");
startHoverCheck();
return false;
}
bool Workspace::handleLeave(GdkEventCrossing* /*event*/) {
/*
* Do not remove immediately.
* Workspace taskbar children can fire misleading leave events while the
* pointer is still visually inside the workspace button.
*
* The polling check will remove the class once the pointer really leaves.
*/
startHoverCheck();
return false;
}
bool Workspace::handleClicked(GdkEventButton* bt) const {
if (bt->type == GDK_BUTTON_PRESS) {
try {
if (id() > 0) { // normal
if (m_workspaceManager.moveToMonitor()) {
m_ipc.getSocket1Reply("dispatch focusworkspaceoncurrentmonitor " + std::to_string(id()));
IPC::dispatch("focusworkspaceoncurrentmonitor", std::to_string(id()));
} else {
m_ipc.getSocket1Reply("dispatch workspace " + std::to_string(id()));
IPC::dispatch("workspace", std::to_string(id()));
}
} else if (!isSpecial()) { // named (this includes persistent)
if (m_workspaceManager.moveToMonitor()) {
m_ipc.getSocket1Reply("dispatch focusworkspaceoncurrentmonitor name:" + name());
IPC::dispatch("focusworkspaceoncurrentmonitor", "name:" + name());
} else {
m_ipc.getSocket1Reply("dispatch workspace name:" + name());
IPC::dispatch("workspace", "name:" + name());
}
} else if (id() != -99) { // named special
m_ipc.getSocket1Reply("dispatch togglespecialworkspace " + name());
IPC::dispatch("togglespecialworkspace", name());
} else { // special
m_ipc.getSocket1Reply("dispatch togglespecialworkspace");
IPC::dispatch("togglespecialworkspace", "");
}
return true;
} catch (const std::exception &e) {
} catch (const std::exception& e) {
spdlog::error("Failed to dispatch workspace: {}", e.what());
}
}
return false;
}
void Workspace::initializeWindowMap(const Json::Value &clients_data) {
void Workspace::initializeWindowMap(const Json::Value& clients_data) {
m_windowMap.clear();
for (auto client : clients_data) {
for (const auto& client : clients_data) {
if (client["workspace"]["id"].asInt() == id()) {
insertWindow({client});
}
}
}
void Workspace::setActiveWindow(WindowAddress const &addr) {
void Workspace::setActiveWindow(WindowAddress const& addr) {
std::optional<long> activeIdx;
for (size_t i = 0; i < m_windowMap.size(); ++i) {
auto &window = m_windowMap[i];
auto& window = m_windowMap[i];
bool isActive = (window.address == addr);
window.setActive(isActive);
if (isActive) {
@@ -115,7 +223,11 @@ void Workspace::setActiveWindow(WindowAddress const &addr) {
}
auto activeWindowPos = m_workspaceManager.activeWindowPosition();
if (activeIdx.has_value() && activeWindowPos != Workspaces::ActiveWindowPosition::NONE) {
const bool has_active_window =
activeIdx.has_value() &&
activeWindowPos != Workspaces::ActiveWindowPosition::NONE;
if (has_active_window) {
auto window = std::move(m_windowMap[*activeIdx]);
m_windowMap.erase(m_windowMap.begin() + *activeIdx);
if (activeWindowPos == Workspaces::ActiveWindowPosition::FIRST) {
@@ -130,10 +242,13 @@ void Workspace::insertWindow(WindowCreationPayload create_window_payload) {
if (!create_window_payload.isEmpty(m_workspaceManager)) {
auto repr = create_window_payload.repr(m_workspaceManager);
if (!repr.empty() || m_workspaceManager.enableTaskbar()) {
const bool should_display =
!repr.empty() || m_workspaceManager.enableTaskbar();
if (should_display) {
auto addr = create_window_payload.getAddress();
auto it = std::ranges::find_if(
m_windowMap, [&addr](const auto &window) { return window.address == addr; });
m_windowMap, [&addr](const auto& window) { return window.address == addr; });
// If the vector contains the address, update the window representation, otherwise insert it
if (it != m_windowMap.end()) {
*it = repr;
@@ -142,9 +257,9 @@ void Workspace::insertWindow(WindowCreationPayload create_window_payload) {
}
}
}
};
}
bool Workspace::onWindowOpened(WindowCreationPayload const &create_window_payload) {
bool Workspace::onWindowOpened(WindowCreationPayload const& create_window_payload) {
if (create_window_payload.getWorkspaceName() == name()) {
insertWindow(create_window_payload);
return true;
@@ -152,7 +267,7 @@ bool Workspace::onWindowOpened(WindowCreationPayload const &create_window_payloa
return false;
}
std::string &Workspace::selectIcon(std::map<std::string, std::string> &icons_map) {
std::string& Workspace::selectIcon(std::map<std::string, std::string>& icons_map) {
spdlog::trace("Selecting icon for workspace {}", name());
if (isUrgent()) {
auto urgentIconIt = icons_map.find("urgent");
@@ -161,6 +276,17 @@ std::string &Workspace::selectIcon(std::map<std::string, std::string> &icons_map
}
}
if (isActive() && isSpecial()) {
auto activeIconIt = icons_map.find("active:" + name());
if (activeIconIt != icons_map.end()) {
return activeIconIt->second;
}
auto namedIconIt = icons_map.find(name());
if (namedIconIt != icons_map.end()) {
return namedIconIt->second;
}
}
if (isActive()) {
auto activeIconIt = icons_map.find("active");
if (activeIconIt != icons_map.end()) {
@@ -209,7 +335,7 @@ std::string &Workspace::selectIcon(std::map<std::string, std::string> &icons_map
return m_name;
}
void Workspace::update(const std::string &workspace_icon) {
void Workspace::update(const std::string& workspace_icon) {
if (this->m_workspaceManager.persistentOnly() && !this->isPersistent()) {
m_button.hide();
return;
@@ -234,6 +360,7 @@ void Workspace::update(const std::string &workspace_icon) {
auto styleContext = m_button.get_style_context();
addOrRemoveClass(styleContext, isActive(), "active");
addOrRemoveClass(styleContext, isSpecial(), "special");
addOrRemoveClass(styleContext, isSpecial(), name());
addOrRemoveClass(styleContext, isEmpty(), "empty");
addOrRemoveClass(styleContext, isPersistent(), "persistent");
addOrRemoveClass(styleContext, isUrgent(), "urgent");
@@ -248,7 +375,7 @@ void Workspace::update(const std::string &workspace_icon) {
bool isNotFirst = false;
for (const auto &window_repr : m_windowMap) {
for (const auto& window_repr : m_windowMap) {
if (isNotFirst) {
windows.append(windowSeparator);
}
@@ -270,16 +397,18 @@ void Workspace::update(const std::string &workspace_icon) {
bool Workspace::isEmpty() const {
auto ignore_list = m_workspaceManager.getIgnoredWindows();
if (ignore_list.empty()) {
const bool no_ignore_rules = ignore_list.empty();
if (no_ignore_rules) {
return m_windows == 0;
}
// If there are windows but they are all ignored, consider the workspace empty
return std::all_of(
m_windowMap.begin(), m_windowMap.end(),
[this, &ignore_list](const auto &window_repr) { return shouldSkipWindow(window_repr); });
[this, &ignore_list](const auto& window_repr) { return shouldSkipWindow(window_repr); });
}
void Workspace::updateTaskbar(const std::string &workspace_icon) {
void Workspace::updateTaskbar(const std::string& workspace_icon) {
for (auto child : m_content.get_children()) {
if (child != &m_labelBefore) {
m_content.remove(*child);
@@ -287,7 +416,7 @@ void Workspace::updateTaskbar(const std::string &workspace_icon) {
}
bool isFirst = true;
auto processWindow = [&](const WindowRepr &window_repr) {
auto processWindow = [&](const WindowRepr& window_repr) {
if (shouldSkipWindow(window_repr)) {
return; // skip
}
@@ -300,16 +429,19 @@ void Workspace::updateTaskbar(const std::string &workspace_icon) {
}
auto window_box = Gtk::make_managed<Gtk::Box>(Gtk::ORIENTATION_HORIZONTAL);
window_box->set_tooltip_text(window_repr.window_title);
window_box->get_style_context()->add_class("taskbar-window");
window_box->set_tooltip_markup(window_repr.window_title);
auto button = Gtk::manage(new Gtk::Button());
button->set_relief(Gtk::RELIEF_NONE);
button->add(*window_box);
button->get_style_context()->add_class("taskbar-window");
if (window_repr.isActive) {
window_box->get_style_context()->add_class("active");
button->get_style_context()->add_class("active");
}
auto event_box = Gtk::manage(new Gtk::EventBox());
event_box->add(*window_box);
if (m_workspaceManager.onClickWindow() != "") {
event_box->signal_button_press_event().connect(
sigc::bind(sigc::mem_fun(*this, &Workspace::handleClick), window_repr.address));
button->signal_button_press_event().connect(
sigc::bind(sigc::mem_fun(*this, &Workspace::handleClick), window_repr.address),
false);
}
auto text_before = fmt::format(fmt::runtime(m_workspaceManager.taskbarFormatBefore()),
@@ -334,8 +466,8 @@ void Workspace::updateTaskbar(const std::string &workspace_icon) {
window_box->pack_start(*window_label_after, true, true);
}
m_content.pack_start(*event_box, true, false);
event_box->show_all();
m_content.pack_start(*button, true, false);
button->show_all();
};
if (m_workspaceManager.taskbarReverseDirection()) {
@@ -343,13 +475,15 @@ void Workspace::updateTaskbar(const std::string &workspace_icon) {
processWindow(*it);
}
} else {
for (const auto &window_repr : m_windowMap) {
for (const auto& window_repr : m_windowMap) {
processWindow(window_repr);
}
}
auto formatAfter = m_workspaceManager.formatAfter();
if (!formatAfter.empty()) {
const bool has_format_after = !formatAfter.empty();
if (has_format_after) {
m_labelAfter.set_markup(fmt::format(fmt::runtime(formatAfter), fmt::arg("id", id()),
fmt::arg("name", name()),
fmt::arg("icon", workspace_icon)));
@@ -358,7 +492,7 @@ void Workspace::updateTaskbar(const std::string &workspace_icon) {
}
}
bool Workspace::handleClick(const GdkEventButton *event_button, WindowAddress const &addr) const {
bool Workspace::handleClick(const GdkEventButton* event_button, WindowAddress const& addr) const {
if (event_button->type == GDK_BUTTON_PRESS) {
std::string command = std::regex_replace(m_workspaceManager.onClickWindow(),
std::regex("\\{address\\}"), "0x" + addr);
@@ -372,9 +506,9 @@ bool Workspace::handleClick(const GdkEventButton *event_button, WindowAddress co
return true;
}
bool Workspace::shouldSkipWindow(const WindowRepr &window_repr) const {
bool Workspace::shouldSkipWindow(const WindowRepr& window_repr) const {
auto ignore_list = m_workspaceManager.getIgnoredWindows();
auto it = std::ranges::find_if(ignore_list, [&window_repr](const auto &ignoreItem) {
auto it = std::ranges::find_if(ignore_list, [&window_repr](const auto& ignoreItem) {
return std::regex_match(window_repr.window_class, ignoreItem) ||
std::regex_match(window_repr.window_title, ignoreItem);
});
+188 -118
View File
@@ -14,7 +14,7 @@
namespace waybar::modules::hyprland {
Workspaces::Workspaces(const std::string &id, const Bar &bar, const Json::Value &config)
Workspaces::Workspaces(const std::string& id, const Bar& bar, const Json::Value& config)
: AModule(config, "workspaces", id, false, false),
m_bar(bar),
m_box(bar.orientation, 0),
@@ -34,6 +34,9 @@ Workspaces::Workspaces(const std::string &id, const Bar &bar, const Json::Value
}
Workspaces::~Workspaces() {
if (m_scrollEventConnection_.connected()) {
m_scrollEventConnection_.disconnect();
}
m_ipc.unregisterForIPC(this);
// wait for possible event handler to finish
std::lock_guard<std::mutex> lg(m_mutex);
@@ -43,11 +46,23 @@ void Workspaces::init() {
m_activeWorkspaceId = m_ipc.getSocket1JsonReply("activeworkspace")["id"].asInt();
initializeWorkspaces();
if (m_scrollEventConnection_.connected()) {
m_scrollEventConnection_.disconnect();
}
bool hasScrollConfig = config_["on-scroll-up"].isString() || config_["on-scroll-down"].isString();
if (barScroll() || hasScrollConfig) {
auto& window = const_cast<Bar&>(m_bar).window;
window.add_events(Gdk::SCROLL_MASK | Gdk::SMOOTH_SCROLL_MASK);
m_scrollEventConnection_ =
window.signal_scroll_event().connect(sigc::mem_fun(*this, &Workspaces::handleScroll));
}
dp.emit();
}
Json::Value Workspaces::createMonitorWorkspaceData(std::string const &name,
std::string const &monitor) {
Json::Value Workspaces::createMonitorWorkspaceData(std::string const& name,
std::string const& monitor) {
spdlog::trace("Creating persistent workspace: {} on monitor {}", name, monitor);
Json::Value workspaceData;
@@ -62,14 +77,14 @@ Json::Value Workspaces::createMonitorWorkspaceData(std::string const &name,
return workspaceData;
}
void Workspaces::createWorkspace(Json::Value const &workspace_data,
Json::Value const &clients_data) {
void Workspaces::createWorkspace(Json::Value const& workspace_data,
Json::Value const& clients_data) {
auto workspaceName = workspace_data["name"].asString();
auto workspaceId = workspace_data["id"].asInt();
spdlog::debug("Creating workspace {}", workspaceName);
// avoid recreating existing workspaces
auto workspace = std::ranges::find_if(m_workspaces, [&](std::unique_ptr<Workspace> const &w) {
auto workspace = std::ranges::find_if(m_workspaces, [&](std::unique_ptr<Workspace> const& w) {
if (workspaceId > 0) {
return w->id() == workspaceId;
}
@@ -81,7 +96,7 @@ void Workspaces::createWorkspace(Json::Value const &workspace_data,
// don't recreate workspace, but update persistency if necessary
const auto keys = workspace_data.getMemberNames();
const auto *k = "persistent-rule";
const auto* k = "persistent-rule";
if (std::ranges::find(keys, k) != keys.end()) {
spdlog::debug("Set dynamic persistency of workspace {} to: {}", workspaceName,
workspace_data[k].asBool() ? "true" : "false");
@@ -100,14 +115,14 @@ void Workspaces::createWorkspace(Json::Value const &workspace_data,
// create new workspace
m_workspaces.emplace_back(std::make_unique<Workspace>(workspace_data, *this, clients_data));
Gtk::Button &newWorkspaceButton = m_workspaces.back()->button();
Gtk::Button& newWorkspaceButton = m_workspaces.back()->button();
m_box.pack_start(newWorkspaceButton, false, false);
sortWorkspaces();
newWorkspaceButton.show_all();
}
void Workspaces::createWorkspacesToCreate() {
for (const auto &[workspaceData, clientsData] : m_workspacesToCreate) {
for (const auto& [workspaceData, clientsData] : m_workspacesToCreate) {
createWorkspace(workspaceData, clientsData);
}
if (!m_workspacesToCreate.empty()) {
@@ -139,16 +154,17 @@ void Workspaces::doUpdate() {
}
}
void Workspaces::extendOrphans(int workspaceId, Json::Value const &clientsJson) {
void Workspaces::extendOrphans(int workspaceId, Json::Value const& clientsJson) {
spdlog::trace("Extending orphans with workspace {}", workspaceId);
for (const auto &client : clientsJson) {
for (const auto& client : clientsJson) {
if (client["workspace"]["id"].asInt() == workspaceId) {
registerOrphanWindow({client});
}
}
}
std::string Workspaces::getRewrite(std::string window_class, std::string window_title) {
std::string Workspaces::getRewrite(const std::string& window_class,
const std::string& window_title) {
std::string windowReprKey;
if (windowRewriteConfigUsesTitle()) {
windowReprKey = fmt::format("class<{}> title<{}>", window_class, window_title);
@@ -163,7 +179,7 @@ std::string Workspaces::getRewrite(std::string window_class, std::string window_
std::vector<int> Workspaces::getVisibleWorkspaces() {
std::vector<int> visibleWorkspaces;
auto monitors = IPC::inst().getSocket1JsonReply("monitors");
for (const auto &monitor : monitors) {
for (const auto& monitor : monitors) {
auto ws = monitor["activeWorkspace"];
if (ws.isObject() && ws["id"].isInt()) {
visibleWorkspaces.push_back(ws["id"].asInt());
@@ -181,7 +197,7 @@ void Workspaces::initializeWorkspaces() {
spdlog::debug("Initializing workspaces");
// if the workspace rules changed since last initialization, make sure we reset everything:
for (auto &workspace : m_workspaces) {
for (auto& workspace : m_workspaces) {
m_workspacesToRemove.push_back(std::to_string(workspace->id()));
}
@@ -189,7 +205,7 @@ void Workspaces::initializeWorkspaces() {
auto const workspacesJson = m_ipc.getSocket1JsonReply("workspaces");
auto const clientsJson = m_ipc.getSocket1JsonReply("clients");
for (Json::Value workspaceJson : workspacesJson) {
for (const auto& workspaceJson : workspacesJson) {
std::string workspaceName = workspaceJson["name"].asString();
if ((allOutputs() || m_bar.output->name == workspaceJson["monitor"].asString()) &&
(!workspaceName.starts_with("special") || showSpecial()) &&
@@ -209,7 +225,7 @@ void Workspaces::initializeWorkspaces() {
loadPersistentWorkspacesFromWorkspaceRules(clientsJson);
}
bool isDoubleSpecial(std::string const &workspace_name) {
bool isDoubleSpecial(std::string const& workspace_name) {
// Hyprland's IPC sometimes reports the creation of workspaces strangely named
// `special:special:<some_name>`. This function checks for that and is used
// to avoid creating (and then removing) such workspaces.
@@ -217,8 +233,8 @@ bool isDoubleSpecial(std::string const &workspace_name) {
return workspace_name.find("special:special:") != std::string::npos;
}
bool Workspaces::isWorkspaceIgnored(std::string const &name) {
for (auto &rule : m_ignoreWorkspaces) {
bool Workspaces::isWorkspaceIgnored(std::string const& name) {
for (auto& rule : m_ignoreWorkspaces) {
if (std::regex_match(name, rule)) {
return true;
break;
@@ -228,19 +244,19 @@ bool Workspaces::isWorkspaceIgnored(std::string const &name) {
return false;
}
void Workspaces::loadPersistentWorkspacesFromConfig(Json::Value const &clientsJson) {
void Workspaces::loadPersistentWorkspacesFromConfig(Json::Value const& clientsJson) {
spdlog::info("Loading persistent workspaces from Waybar config");
const std::vector<std::string> keys = m_persistentWorkspaceConfig.getMemberNames();
std::vector<std::string> persistentWorkspacesToCreate;
const std::string currentMonitor = m_bar.output->name;
const bool monitorInConfig = std::ranges::find(keys, currentMonitor) != keys.end();
for (const std::string &key : keys) {
for (const std::string& key : keys) {
// only add if either:
// 1. key is the current monitor name
// 2. key is "*" and this monitor is not already defined in the config
bool canCreate = key == currentMonitor || (key == "*" && !monitorInConfig);
const Json::Value &value = m_persistentWorkspaceConfig[key];
const Json::Value& value = m_persistentWorkspaceConfig[key];
spdlog::trace("Parsing persistent workspace config: {} => {}", key, value.toStyledString());
if (value.isInt()) {
@@ -255,15 +271,15 @@ void Workspaces::loadPersistentWorkspacesFromConfig(Json::Value const &clientsJs
} else if (value.isArray() && !value.empty()) {
// value is an array => create defined workspaces for this monitor
if (canCreate) {
for (const Json::Value &workspace : value) {
for (const Json::Value& workspace : value) {
spdlog::debug("Creating workspace {} on monitor {}", workspace, currentMonitor);
persistentWorkspacesToCreate.emplace_back(workspace.asString());
}
} else {
// key is the workspace and value is array of monitors to create on
for (const Json::Value &monitor : value) {
for (const Json::Value& monitor : value) {
if (monitor.isString() && monitor.asString() == currentMonitor) {
persistentWorkspacesToCreate.emplace_back(currentMonitor);
persistentWorkspacesToCreate.emplace_back(key);
break;
}
}
@@ -274,18 +290,18 @@ void Workspaces::loadPersistentWorkspacesFromConfig(Json::Value const &clientsJs
}
}
for (auto const &workspace : persistentWorkspacesToCreate) {
for (auto const& workspace : persistentWorkspacesToCreate) {
auto workspaceData = createMonitorWorkspaceData(workspace, m_bar.output->name);
workspaceData["persistent-config"] = true;
m_workspacesToCreate.emplace_back(workspaceData, clientsJson);
}
}
void Workspaces::loadPersistentWorkspacesFromWorkspaceRules(const Json::Value &clientsJson) {
void Workspaces::loadPersistentWorkspacesFromWorkspaceRules(const Json::Value& clientsJson) {
spdlog::info("Loading persistent workspaces from Hyprland workspace rules");
auto const workspaceRules = m_ipc.getSocket1JsonReply("workspacerules");
for (Json::Value const &rule : workspaceRules) {
for (Json::Value const& rule : workspaceRules) {
if (!rule["workspaceString"].isString()) {
spdlog::warn("Workspace rules: invalid workspaceString, skipping: {}", rule);
continue;
@@ -305,12 +321,16 @@ void Workspaces::loadPersistentWorkspacesFromWorkspaceRules(const Json::Value &c
if (workspace.starts_with("name:")) {
workspace = workspace.substr(5);
}
auto const &monitor = rule["monitor"].asString();
auto const& monitor = rule["monitor"].asString();
// create this workspace persistently if:
// 1. the allOutputs config option is enabled
// 2. the rule's monitor is the current monitor
// 3. no monitor is specified in the rule => assume it needs to be persistent on every monitor
if (allOutputs() || m_bar.output->name == monitor || monitor.empty()) {
// => skip ignore-workspaces even if its a persistent
if(isWorkspaceIgnored(workspace)) {
continue;
}
// => persistent workspace should be shown on this monitor
auto workspaceData = createMonitorWorkspaceData(workspace, m_bar.output->name);
workspaceData["persistent-rule"] = true;
@@ -322,10 +342,15 @@ void Workspaces::loadPersistentWorkspacesFromWorkspaceRules(const Json::Value &c
}
}
void Workspaces::onEvent(const std::string &ev) {
void Workspaces::onEvent(const std::string& ev) {
std::lock_guard<std::mutex> lock(m_mutex);
std::string eventName(begin(ev), begin(ev) + ev.find_first_of('>'));
std::string payload = ev.substr(eventName.size() + 2);
const auto separator = ev.find(">>");
if (separator == std::string::npos) {
spdlog::warn("Malformed Hyprland workspace event: {}", ev);
return;
}
std::string eventName = ev.substr(0, separator);
std::string payload = ev.substr(separator + 2);
if (eventName == "workspacev2") {
onWorkspaceActivated(payload);
@@ -360,7 +385,7 @@ void Workspaces::onEvent(const std::string &ev) {
dp.emit();
}
void Workspaces::onWorkspaceActivated(std::string const &payload) {
void Workspaces::onWorkspaceActivated(std::string const& payload) {
const auto [workspaceIdStr, workspaceName] = splitDoublePayload(payload);
const auto workspaceId = parseWorkspaceId(workspaceIdStr);
if (workspaceId.has_value()) {
@@ -368,19 +393,19 @@ void Workspaces::onWorkspaceActivated(std::string const &payload) {
}
}
void Workspaces::onSpecialWorkspaceActivated(std::string const &payload) {
void Workspaces::onSpecialWorkspaceActivated(std::string const& payload) {
std::string name(begin(payload), begin(payload) + payload.find_first_of(','));
m_activeSpecialWorkspaceName = (!name.starts_with("special:") ? name : name.substr(8));
}
void Workspaces::onWorkspaceDestroyed(std::string const &payload) {
void Workspaces::onWorkspaceDestroyed(std::string const& payload) {
const auto [workspaceId, workspaceName] = splitDoublePayload(payload);
if (!isDoubleSpecial(workspaceName)) {
m_workspacesToRemove.push_back(workspaceId);
}
}
void Workspaces::onWorkspaceCreated(std::string const &payload, Json::Value const &clientsData) {
void Workspaces::onWorkspaceCreated(std::string const& payload, Json::Value const& clientsData) {
spdlog::debug("Workspace created: {}", payload);
const auto [workspaceIdStr, _] = splitDoublePayload(payload);
@@ -393,7 +418,7 @@ void Workspaces::onWorkspaceCreated(std::string const &payload, Json::Value cons
auto const workspaceRules = m_ipc.getSocket1JsonReply("workspacerules");
auto const workspacesJson = m_ipc.getSocket1JsonReply("workspaces");
for (Json::Value workspaceJson : workspacesJson) {
for (auto workspaceJson : workspacesJson) {
const auto currentId = workspaceJson["id"].asInt();
if (currentId == *workspaceId) {
std::string workspaceName = workspaceJson["name"].asString();
@@ -407,7 +432,7 @@ void Workspaces::onWorkspaceCreated(std::string const &payload, Json::Value cons
if ((allOutputs() || m_bar.output->name == workspaceJson["monitor"].asString()) &&
(showSpecial() || !workspaceName.starts_with("special")) &&
!isDoubleSpecial(workspaceName)) {
for (Json::Value const &rule : workspaceRules) {
for (Json::Value const& rule : workspaceRules) {
auto ruleWorkspaceName = rule.isMember("defaultName")
? rule["defaultName"].asString()
: rule["workspaceString"].asString();
@@ -426,7 +451,7 @@ void Workspaces::onWorkspaceCreated(std::string const &payload, Json::Value cons
}
}
void Workspaces::onWorkspaceMoved(std::string const &payload) {
void Workspaces::onWorkspaceMoved(std::string const& payload) {
spdlog::debug("Workspace moved: {}", payload);
// Update active workspace
@@ -447,7 +472,7 @@ void Workspaces::onWorkspaceMoved(std::string const &payload) {
}
}
void Workspaces::onWorkspaceRenamed(std::string const &payload) {
void Workspaces::onWorkspaceRenamed(std::string const& payload) {
spdlog::debug("Workspace renamed: {}", payload);
const auto [workspaceIdStr, newName] = splitDoublePayload(payload);
@@ -456,7 +481,7 @@ void Workspaces::onWorkspaceRenamed(std::string const &payload) {
return;
}
for (auto &workspace : m_workspaces) {
for (auto& workspace : m_workspaces) {
if (workspace->id() == *workspaceId) {
workspace->setName(newName);
break;
@@ -465,7 +490,7 @@ void Workspaces::onWorkspaceRenamed(std::string const &payload) {
sortWorkspaces();
}
void Workspaces::onMonitorFocused(std::string const &payload) {
void Workspaces::onMonitorFocused(std::string const& payload) {
spdlog::trace("Monitor focused: {}", payload);
const auto [monitorName, workspaceIdStr] = splitDoublePayload(payload);
@@ -477,7 +502,7 @@ void Workspaces::onMonitorFocused(std::string const &payload) {
m_activeWorkspaceId = *workspaceId;
for (Json::Value &monitor : m_ipc.getSocket1JsonReply("monitors")) {
for (Json::Value& monitor : m_ipc.getSocket1JsonReply("monitors")) {
if (monitor["name"].asString() == monitorName) {
const auto name = monitor["specialWorkspace"]["name"].asString();
m_activeSpecialWorkspaceName = !name.starts_with("special:") ? name : name.substr(8);
@@ -485,39 +510,41 @@ void Workspaces::onMonitorFocused(std::string const &payload) {
}
}
void Workspaces::onWindowOpened(std::string const &payload) {
void Workspaces::onWindowOpened(std::string const& payload) {
spdlog::trace("Window opened: {}", payload);
updateWindowCount();
size_t lastCommaIdx = 0;
size_t nextCommaIdx = payload.find(',');
std::string windowAddress = payload.substr(lastCommaIdx, nextCommaIdx - lastCommaIdx);
const auto firstComma = payload.find(',');
const auto secondComma =
firstComma == std::string::npos ? std::string::npos : payload.find(',', firstComma + 1);
const auto thirdComma =
secondComma == std::string::npos ? std::string::npos : payload.find(',', secondComma + 1);
if (firstComma == std::string::npos || secondComma == std::string::npos ||
thirdComma == std::string::npos) {
spdlog::warn("Malformed Hyprland openwindow payload: {}", payload);
return;
}
lastCommaIdx = nextCommaIdx;
nextCommaIdx = payload.find(',', nextCommaIdx + 1);
std::string workspaceName = payload.substr(lastCommaIdx + 1, nextCommaIdx - lastCommaIdx - 1);
lastCommaIdx = nextCommaIdx;
nextCommaIdx = payload.find(',', nextCommaIdx + 1);
std::string windowClass = payload.substr(lastCommaIdx + 1, nextCommaIdx - lastCommaIdx - 1);
std::string windowTitle = payload.substr(nextCommaIdx + 1, payload.length() - nextCommaIdx);
std::string windowAddress = payload.substr(0, firstComma);
std::string workspaceName = payload.substr(firstComma + 1, secondComma - firstComma - 1);
std::string windowClass = payload.substr(secondComma + 1, thirdComma - secondComma - 1);
std::string windowTitle = payload.substr(thirdComma + 1);
bool isActive = m_currentActiveWindowAddress == windowAddress;
m_windowsToCreate.emplace_back(workspaceName, windowAddress, windowClass, windowTitle, isActive);
}
void Workspaces::onWindowClosed(std::string const &addr) {
void Workspaces::onWindowClosed(std::string const& addr) {
spdlog::trace("Window closed: {}", addr);
updateWindowCount();
m_orphanWindowMap.erase(addr);
for (auto &workspace : m_workspaces) {
for (auto& workspace : m_workspaces) {
if (workspace->closeWindow(addr)) {
break;
}
}
}
void Workspaces::onWindowMoved(std::string const &payload) {
void Workspaces::onWindowMoved(std::string const& payload) {
spdlog::trace("Window moved: {}", payload);
updateWindowCount();
auto [windowAddress, _, workspaceName] = splitTriplePayload(payload);
@@ -526,7 +553,7 @@ void Workspaces::onWindowMoved(std::string const &payload) {
// If the window was still queued to be created, just change its destination
// and exit
for (auto &window : m_windowsToCreate) {
for (auto& window : m_windowsToCreate) {
if (window.getAddress() == windowAddress) {
window.moveToWorkspace(workspaceName);
return;
@@ -534,7 +561,7 @@ void Workspaces::onWindowMoved(std::string const &payload) {
}
// Take the window's representation from the old workspace...
for (auto &workspace : m_workspaces) {
for (auto& workspace : m_workspaces) {
if (auto windowAddr = workspace->closeWindow(windowAddress); windowAddr != std::nullopt) {
windowRepr = windowAddr.value();
break;
@@ -553,7 +580,7 @@ void Workspaces::onWindowMoved(std::string const &payload) {
}
}
void Workspaces::onWindowTitleEvent(std::string const &payload) {
void Workspaces::onWindowTitleEvent(std::string const& payload) {
spdlog::trace("Window title changed: {}", payload);
std::optional<std::function<void(WindowCreationPayload)>> inserter;
@@ -563,7 +590,7 @@ void Workspaces::onWindowTitleEvent(std::string const &payload) {
if (m_orphanWindowMap.contains(windowAddress)) {
inserter = [this](WindowCreationPayload wcp) { this->registerOrphanWindow(std::move(wcp)); };
} else {
auto windowWorkspace = std::ranges::find_if(m_workspaces, [windowAddress](auto &workspace) {
auto windowWorkspace = std::ranges::find_if(m_workspaces, [windowAddress](auto& workspace) {
return workspace->containsWindow(windowAddress);
});
@@ -575,7 +602,7 @@ void Workspaces::onWindowTitleEvent(std::string const &payload) {
};
} else {
auto queuedWindow =
std::ranges::find_if(m_windowsToCreate, [&windowAddress](auto &windowPayload) {
std::ranges::find_if(m_windowsToCreate, [&windowAddress](auto& windowPayload) {
return windowPayload.getAddress() == windowAddress;
});
@@ -590,7 +617,7 @@ void Workspaces::onWindowTitleEvent(std::string const &payload) {
Json::Value clientsData = m_ipc.getSocket1JsonReply("clients");
std::string jsonWindowAddress = fmt::format("0x{}", windowAddress);
auto client = std::ranges::find_if(clientsData, [jsonWindowAddress](auto &client) {
auto client = std::ranges::find_if(clientsData, [jsonWindowAddress](auto& client) {
return client["address"].asString() == jsonWindowAddress;
});
@@ -600,17 +627,17 @@ void Workspaces::onWindowTitleEvent(std::string const &payload) {
}
}
void Workspaces::onActiveWindowChanged(WindowAddress const &activeWindowAddress) {
void Workspaces::onActiveWindowChanged(WindowAddress const& activeWindowAddress) {
spdlog::trace("Active window changed: {}", activeWindowAddress);
m_currentActiveWindowAddress = activeWindowAddress;
for (auto &[address, window] : m_orphanWindowMap) {
for (auto& [address, window] : m_orphanWindowMap) {
window.setActive(address == activeWindowAddress);
}
for (auto const &workspace : m_workspaces) {
for (auto const& workspace : m_workspaces) {
workspace->setActiveWindow(activeWindowAddress);
}
for (auto &window : m_windowsToCreate) {
for (auto& window : m_windowsToCreate) {
window.setActive(window.getAddress() == activeWindowAddress);
}
}
@@ -620,8 +647,8 @@ void Workspaces::onConfigReloaded() {
init();
}
auto Workspaces::parseConfig(const Json::Value &config) -> void {
const auto &configFormat = config["format"];
auto Workspaces::parseConfig(const Json::Value& config) -> void {
const auto& configFormat = config["format"];
m_formatBefore = configFormat.isString() ? configFormat.asString() : "{name}";
m_withIcon = m_formatBefore.find("{icon}") != std::string::npos;
auto withWindows = m_formatBefore.find("{windows}") != std::string::npos;
@@ -636,6 +663,7 @@ auto Workspaces::parseConfig(const Json::Value &config) -> void {
populateBoolConfig(config, "persistent-only", m_persistentOnly);
populateBoolConfig(config, "active-only", m_activeOnly);
populateBoolConfig(config, "move-to-monitor", m_moveToMonitor);
populateBoolConfig(config, "enable-bar-scroll", m_barScroll);
m_persistentWorkspaceConfig = config.get("persistent-workspaces", Json::Value());
populateSortByConfig(config);
@@ -653,28 +681,28 @@ auto Workspaces::parseConfig(const Json::Value &config) -> void {
}
}
auto Workspaces::populateIconsMap(const Json::Value &formatIcons) -> void {
for (const auto &name : formatIcons.getMemberNames()) {
auto Workspaces::populateIconsMap(const Json::Value& formatIcons) -> void {
for (const auto& name : formatIcons.getMemberNames()) {
m_iconsMap.emplace(name, formatIcons[name].asString());
}
m_iconsMap.emplace("", "");
}
auto Workspaces::populateBoolConfig(const Json::Value &config, const std::string &key, bool &member)
auto Workspaces::populateBoolConfig(const Json::Value& config, const std::string& key, bool& member)
-> void {
const auto &configValue = config[key];
const auto& configValue = config[key];
if (configValue.isBool()) {
member = configValue.asBool();
}
}
auto Workspaces::populateSortByConfig(const Json::Value &config) -> void {
const auto &configSortBy = config["sort-by"];
auto Workspaces::populateSortByConfig(const Json::Value& config) -> void {
const auto& configSortBy = config["sort-by"];
if (configSortBy.isString()) {
auto sortByStr = configSortBy.asString();
try {
m_sortBy = m_enumParser.parseStringToEnum(sortByStr, m_sortMap);
} catch (const std::invalid_argument &e) {
} catch (const std::invalid_argument& e) {
m_sortBy = SortMethod::DEFAULT;
spdlog::warn(
"Invalid string representation for sort-by. Falling back to default sort method.");
@@ -682,16 +710,16 @@ auto Workspaces::populateSortByConfig(const Json::Value &config) -> void {
}
}
auto Workspaces::populateIgnoreWorkspacesConfig(const Json::Value &config) -> void {
auto Workspaces::populateIgnoreWorkspacesConfig(const Json::Value& config) -> void {
auto ignoreWorkspaces = config["ignore-workspaces"];
if (ignoreWorkspaces.isArray()) {
for (const auto &workspaceRegex : ignoreWorkspaces) {
for (const auto& workspaceRegex : ignoreWorkspaces) {
if (workspaceRegex.isString()) {
std::string ruleString = workspaceRegex.asString();
try {
const std::regex rule{ruleString, std::regex_constants::icase};
m_ignoreWorkspaces.emplace_back(rule);
} catch (const std::regex_error &e) {
} catch (const std::regex_error& e) {
spdlog::error("Invalid rule {}: {}", ruleString, e.what());
}
} else {
@@ -701,30 +729,30 @@ auto Workspaces::populateIgnoreWorkspacesConfig(const Json::Value &config) -> vo
}
}
auto Workspaces::populateFormatWindowSeparatorConfig(const Json::Value &config) -> void {
const auto &formatWindowSeparator = config["format-window-separator"];
auto Workspaces::populateFormatWindowSeparatorConfig(const Json::Value& config) -> void {
const auto& formatWindowSeparator = config["format-window-separator"];
m_formatWindowSeparator =
formatWindowSeparator.isString() ? formatWindowSeparator.asString() : " ";
}
auto Workspaces::populateWindowRewriteConfig(const Json::Value &config) -> void {
const auto &windowRewrite = config["window-rewrite"];
auto Workspaces::populateWindowRewriteConfig(const Json::Value& config) -> void {
const auto& windowRewrite = config["window-rewrite"];
if (!windowRewrite.isObject()) {
spdlog::debug("window-rewrite is not defined or is not an object, using default rules.");
return;
}
const auto &windowRewriteDefaultConfig = config["window-rewrite-default"];
const auto& windowRewriteDefaultConfig = config["window-rewrite-default"];
std::string windowRewriteDefault =
windowRewriteDefaultConfig.isString() ? windowRewriteDefaultConfig.asString() : "?";
m_windowRewriteRules = util::RegexCollection(
windowRewrite, windowRewriteDefault,
[this](std::string &window_rule) { return windowRewritePriorityFunction(window_rule); });
[this](std::string& window_rule) { return windowRewritePriorityFunction(window_rule); });
}
auto Workspaces::populateWorkspaceTaskbarConfig(const Json::Value &config) -> void {
const auto &workspaceTaskbar = config["workspace-taskbar"];
auto Workspaces::populateWorkspaceTaskbarConfig(const Json::Value& config) -> void {
const auto& workspaceTaskbar = config["workspace-taskbar"];
if (!workspaceTaskbar.isObject()) {
spdlog::debug("workspace-taskbar is not defined or is not an object, using default rules.");
return;
@@ -751,7 +779,7 @@ auto Workspaces::populateWorkspaceTaskbarConfig(const Json::Value &config) -> vo
auto iconTheme = workspaceTaskbar["icon-theme"];
if (iconTheme.isArray()) {
for (auto &c : iconTheme) {
for (auto& c : iconTheme) {
m_iconLoader.add_custom_icon_theme(c.asString());
}
} else if (iconTheme.isString()) {
@@ -771,11 +799,11 @@ auto Workspaces::populateWorkspaceTaskbarConfig(const Json::Value &config) -> vo
}
if (workspaceTaskbar["ignore-list"].isArray()) {
for (auto &windowRegex : workspaceTaskbar["ignore-list"]) {
for (auto& windowRegex : workspaceTaskbar["ignore-list"]) {
std::string ruleString = windowRegex.asString();
try {
m_ignoreWindows.emplace_back(ruleString, std::regex_constants::icase);
} catch (const std::regex_error &e) {
} catch (const std::regex_error& e) {
spdlog::error("Invalid rule {}: {}", ruleString, e.what());
}
}
@@ -786,7 +814,7 @@ auto Workspaces::populateWorkspaceTaskbarConfig(const Json::Value &config) -> vo
try {
m_activeWindowPosition =
m_activeWindowEnumParser.parseStringToEnum(posStr, m_activeWindowPositionMap);
} catch (const std::invalid_argument &e) {
} catch (const std::invalid_argument& e) {
spdlog::warn(
"Invalid string representation for active-window-position. Falling back to 'none'.");
m_activeWindowPosition = ActiveWindowPosition::NONE;
@@ -829,13 +857,13 @@ auto Workspaces::registerIpc() -> void {
}
void Workspaces::removeWorkspacesToRemove() {
for (const auto &workspaceString : m_workspacesToRemove) {
for (const auto& workspaceString : m_workspacesToRemove) {
removeWorkspace(workspaceString);
}
m_workspacesToRemove.clear();
}
void Workspaces::removeWorkspace(std::string const &workspaceString) {
void Workspaces::removeWorkspace(std::string const& workspaceString) {
spdlog::debug("Removing workspace {}", workspaceString);
// If this succeeds, we have a workspace ID.
@@ -853,7 +881,7 @@ void Workspaces::removeWorkspace(std::string const &workspaceString) {
name = workspaceString;
}
const auto workspace = std::ranges::find_if(m_workspaces, [&](std::unique_ptr<Workspace> &x) {
const auto workspace = std::ranges::find_if(m_workspaces, [&](std::unique_ptr<Workspace>& x) {
if (workspaceId.has_value()) {
return *workspaceId == x->id();
}
@@ -879,7 +907,7 @@ void Workspaces::setCurrentMonitorId() {
// get monitor ID from name (used by persistent workspaces)
m_monitorId = 0;
auto monitors = m_ipc.getSocket1JsonReply("monitors");
auto currentMonitor = std::ranges::find_if(monitors, [this](const Json::Value &m) {
auto currentMonitor = std::ranges::find_if(monitors, [this](const Json::Value& m) {
return m["name"].asString() == m_bar.output->name;
});
if (currentMonitor == monitors.end()) {
@@ -895,7 +923,7 @@ void Workspaces::sortSpecialCentered() {
std::vector<std::unique_ptr<Workspace>> hiddenWorkspaces;
std::vector<std::unique_ptr<Workspace>> normalWorkspaces;
for (auto &workspace : m_workspaces) {
for (auto& workspace : m_workspaces) {
if (workspace->isSpecial()) {
specialWorkspaces.push_back(std::move(workspace));
} else {
@@ -926,7 +954,7 @@ void Workspaces::sortSpecialCentered() {
void Workspaces::sortWorkspaces() {
std::ranges::sort( //
m_workspaces, [&](std::unique_ptr<Workspace> &a, std::unique_ptr<Workspace> &b) {
m_workspaces, [&](std::unique_ptr<Workspace>& a, std::unique_ptr<Workspace>& b) {
// Helper comparisons
auto isIdLess = a->id() < b->id();
auto isNameLess = a->name() < b->name();
@@ -939,7 +967,7 @@ void Workspaces::sortWorkspaces() {
case SortMethod::NUMBER:
try {
return std::stoi(a->name()) < std::stoi(b->name());
} catch (const std::invalid_argument &) {
} catch (const std::exception& e) {
// Handle the exception if necessary.
break;
}
@@ -991,18 +1019,20 @@ void Workspaces::sortWorkspaces() {
}
}
void Workspaces::setUrgentWorkspace(std::string const &windowaddress) {
void Workspaces::setUrgentWorkspace(std::string const& windowaddress) {
const Json::Value clientsJson = m_ipc.getSocket1JsonReply("clients");
const std::string normalizedAddress =
windowaddress.starts_with("0x") ? windowaddress : fmt::format("0x{}", windowaddress);
int workspaceId = -1;
for (Json::Value clientJson : clientsJson) {
if (clientJson["address"].asString().ends_with(windowaddress)) {
for (const auto& clientJson : clientsJson) {
if (clientJson["address"].asString() == normalizedAddress) {
workspaceId = clientJson["workspace"]["id"].asInt();
break;
}
}
auto workspace = std::ranges::find_if(m_workspaces, [workspaceId](std::unique_ptr<Workspace> &x) {
auto workspace = std::ranges::find_if(m_workspaces, [workspaceId](std::unique_ptr<Workspace>& x) {
return x->id() == workspaceId;
});
if (workspace != m_workspaces.end()) {
@@ -1017,8 +1047,8 @@ auto Workspaces::update() -> void {
void Workspaces::updateWindowCount() {
const Json::Value workspacesJson = m_ipc.getSocket1JsonReply("workspaces");
for (auto const &workspace : m_workspaces) {
auto workspaceJson = std::ranges::find_if(workspacesJson, [&](Json::Value const &x) {
for (auto const& workspace : m_workspaces) {
auto workspaceJson = std::ranges::find_if(workspacesJson, [&](Json::Value const& x) {
return x["name"].asString() == workspace->name() ||
(workspace->isSpecial() && x["name"].asString() == "special:" + workspace->name());
});
@@ -1026,7 +1056,7 @@ void Workspaces::updateWindowCount() {
if (workspaceJson != workspacesJson.end()) {
try {
count = (*workspaceJson)["windows"].asUInt();
} catch (const std::exception &e) {
} catch (const std::exception& e) {
spdlog::error("Failed to update window count: {}", e.what());
}
}
@@ -1037,9 +1067,9 @@ void Workspaces::updateWindowCount() {
bool Workspaces::updateWindowsToCreate() {
bool anyWindowCreated = false;
std::vector<WindowCreationPayload> notCreated;
for (auto &windowPayload : m_windowsToCreate) {
for (auto& windowPayload : m_windowsToCreate) {
bool created = false;
for (auto &workspace : m_workspaces) {
for (auto& workspace : m_workspaces) {
if (workspace->onWindowOpened(windowPayload)) {
created = true;
anyWindowCreated = true;
@@ -1068,7 +1098,7 @@ void Workspaces::updateWorkspaceStates() {
std::string currentWorkspaceName =
currentWorkspace.isMember("name") ? currentWorkspace["name"].asString() : "";
for (auto &workspace : m_workspaces) {
for (auto& workspace : m_workspaces) {
bool isActiveByName =
!currentWorkspaceName.empty() && workspace->name() == currentWorkspaceName;
@@ -1080,11 +1110,11 @@ void Workspaces::updateWorkspaceStates() {
}
workspace->setVisible(std::ranges::find(visibleWorkspaces, workspace->id()) !=
visibleWorkspaces.end());
std::string &workspaceIcon = m_iconsMap[""];
std::string& workspaceIcon = m_iconsMap[""];
if (m_withIcon) {
workspaceIcon = workspace->selectIcon(m_iconsMap);
}
auto updatedWorkspace = std::ranges::find_if(updatedWorkspaces, [&workspace](const auto &w) {
auto updatedWorkspace = std::ranges::find_if(updatedWorkspaces, [&workspace](const auto& w) {
auto wNameRaw = w["name"].asString();
auto wName = wNameRaw.starts_with("special:") ? wNameRaw.substr(8) : wNameRaw;
return wName == workspace->name();
@@ -1096,7 +1126,7 @@ void Workspaces::updateWorkspaceStates() {
}
}
int Workspaces::windowRewritePriorityFunction(std::string const &window_rule) {
int Workspaces::windowRewritePriorityFunction(std::string const& window_rule) {
// Rules that match against title are prioritized
// Rules that don't specify if they're matching against either title or class are deprioritized
bool const hasTitle = window_rule.find("title") != std::string::npos;
@@ -1117,23 +1147,30 @@ int Workspaces::windowRewritePriorityFunction(std::string const &window_rule) {
}
template <typename... Args>
std::string Workspaces::makePayload(Args const &...args) {
std::string Workspaces::makePayload(Args const&... args) {
std::ostringstream result;
bool first = true;
((result << (first ? "" : ",") << args, first = false), ...);
return result.str();
}
std::pair<std::string, std::string> Workspaces::splitDoublePayload(std::string const &payload) {
const std::string part1 = payload.substr(0, payload.find(','));
std::pair<std::string, std::string> Workspaces::splitDoublePayload(std::string const& payload) {
const auto separator = payload.find(',');
if (separator == std::string::npos) {
throw std::invalid_argument("Expected a two-part Hyprland payload");
}
const std::string part1 = payload.substr(0, separator);
const std::string part2 = payload.substr(part1.size() + 1);
return {part1, part2};
}
std::tuple<std::string, std::string, std::string> Workspaces::splitTriplePayload(
std::string const &payload) {
std::string const& payload) {
const size_t firstComma = payload.find(',');
const size_t secondComma = payload.find(',', firstComma + 1);
if (firstComma == std::string::npos || secondComma == std::string::npos) {
throw std::invalid_argument("Expected a three-part Hyprland payload");
}
const std::string part1 = payload.substr(0, firstComma);
const std::string part2 = payload.substr(firstComma + 1, secondComma - (firstComma + 1));
@@ -1142,13 +1179,46 @@ std::tuple<std::string, std::string, std::string> Workspaces::splitTriplePayload
return {part1, part2, part3};
}
std::optional<int> Workspaces::parseWorkspaceId(std::string const &workspaceIdStr) {
std::optional<int> Workspaces::parseWorkspaceId(std::string const& workspaceIdStr) {
try {
return workspaceIdStr == "special" ? -99 : std::stoi(workspaceIdStr);
} catch (std::exception const &e) {
} catch (std::exception const& e) {
spdlog::debug("Workspace \"{}\" is not bound to an id: {}", workspaceIdStr, e.what());
return std::nullopt;
}
}
bool Workspaces::handleScroll(GdkEventScroll* e) {
// Ignore emulated scroll events on window
if (gdk_event_get_pointer_emulated((GdkEvent*)e)) {
return false;
}
// Check for custom scroll commands first; delegate to base class
if (config_["on-scroll-up"].isString() || config_["on-scroll-down"].isString()) {
return AModule::handleScroll(e);
}
auto dir = AModule::getScrollDir(e);
if (dir == SCROLL_DIR::NONE) {
return true;
}
if (dir == SCROLL_DIR::DOWN || dir == SCROLL_DIR::RIGHT) {
if (allOutputs()) {
IPC::dispatch("workspace", "e+1");
} else {
IPC::dispatch("workspace", "m+1");
}
} else if (dir == SCROLL_DIR::UP || dir == SCROLL_DIR::LEFT) {
if (allOutputs()) {
IPC::dispatch("workspace", "e-1");
} else {
IPC::dispatch("workspace", "m-1");
}
}
return true;
}
} // namespace waybar::modules::hyprland
+19 -12
View File
@@ -14,22 +14,27 @@ waybar::modules::Image::Image(const std::string& id, const Json::Value& config)
size_ = config["size"].asInt();
interval_ = config_["interval"] == "once"
? std::chrono::milliseconds::max()
: std::chrono::milliseconds(std::max(
1L, // Minimum 1ms due to millisecond precision
static_cast<long>(
(config_["interval"].isNumeric() ? config_["interval"].asDouble() : 0) *
1000)));
const auto once = std::chrono::milliseconds::max();
if (!config_.isMember("interval") || config_["interval"].isNull() ||
config_["interval"] == "once") {
interval_ = once;
} else if (config_["interval"].isNumeric()) {
const auto interval_seconds = config_["interval"].asDouble();
if (interval_seconds <= 0) {
interval_ = once;
} else {
interval_ =
std::chrono::milliseconds(std::max(1L, // Minimum 1ms due to millisecond precision
static_cast<long>(interval_seconds * 1000)));
}
} else {
interval_ = once;
}
if (size_ == 0) {
size_ = 16;
}
if (interval_.count() == 0) {
interval_ = std::chrono::milliseconds::max();
}
delayWorker();
}
@@ -41,9 +46,11 @@ void waybar::modules::Image::delayWorker() {
}
void waybar::modules::Image::refresh(int sig) {
if (sig == SIGRTMIN + config_["signal"].asInt()) {
#ifdef SIGRTMIN
if (config_["signal"].isInt() && sig == SIGRTMIN + config_["signal"].asInt()) {
thread_.wake_up();
}
#endif
}
auto waybar::modules::Image::update() -> void {
+3 -2
View File
@@ -85,7 +85,8 @@ auto getInhibitors(const Json::Value& config) -> std::string {
if (config["what"].isArray()) {
inhibitors = checkInhibitor(config["what"][0].asString());
for (decltype(config["what"].size()) i = 1; i < config["what"].size(); ++i) {
inhibitors += ":" + checkInhibitor(config["what"][i].asString());
inhibitors.append(":");
inhibitors.append(checkInhibitor(config["what"][i].asString()));
}
return inhibitors;
}
@@ -123,7 +124,7 @@ auto Inhibitor::update() -> void {
label_.get_style_context()->add_class(status_text);
if (tooltipEnabled()) {
label_.set_tooltip_text(status_text);
label_.set_tooltip_markup(status_text);
}
return ALabel::update();
+12 -9
View File
@@ -2,7 +2,7 @@
namespace waybar::modules {
JACK::JACK(const std::string &id, const Json::Value &config)
JACK::JACK(const std::string& id, const Json::Value& config)
: ALabel(config, "jack", id, "{load}%", 1) {
running_ = false;
client_ = NULL;
@@ -53,7 +53,7 @@ std::string JACK::JACKState() {
auto JACK::update() -> void {
std::string format;
std::string state = JACKState();
float latency = 1000 * (float)bufsize_ / (float)samplerate_;
float latency = samplerate_ > 0 ? 1000.0f * (float)bufsize_ / (float)samplerate_ : 0.0f;
if (label_.get_style_context()->has_class("xrun")) {
label_.get_style_context()->remove_class("xrun");
@@ -80,7 +80,7 @@ auto JACK::update() -> void {
if (tooltipEnabled()) {
std::string tooltip_format = "{bufsize}/{samplerate} {latency}ms";
if (config_["tooltip-format"].isString()) tooltip_format = config_["tooltip-format"].asString();
label_.set_tooltip_text(fmt::format(
label_.set_tooltip_markup(fmt::format(
fmt::runtime(tooltip_format), fmt::arg("load", std::round(load_)),
fmt::arg("bufsize", bufsize_), fmt::arg("samplerate", samplerate_),
fmt::arg("latency", fmt::format("{:.2f}", latency)), fmt::arg("xruns", xruns_)));
@@ -91,16 +91,19 @@ auto JACK::update() -> void {
}
int JACK::bufSize(jack_nframes_t size) {
std::lock_guard<std::mutex> lock(mutex_);
bufsize_ = size;
return 0;
}
int JACK::sampleRate(jack_nframes_t rate) {
std::lock_guard<std::mutex> lock(mutex_);
samplerate_ = rate;
return 0;
}
int JACK::xrun() {
std::lock_guard<std::mutex> lock(mutex_);
xruns_ += 1;
state_ = "xrun";
return 0;
@@ -113,14 +116,14 @@ void JACK::shutdown() {
} // namespace waybar::modules
int bufSizeCallback(jack_nframes_t size, void *obj) {
return static_cast<waybar::modules::JACK *>(obj)->bufSize(size);
int bufSizeCallback(jack_nframes_t size, void* obj) {
return static_cast<waybar::modules::JACK*>(obj)->bufSize(size);
}
int sampleRateCallback(jack_nframes_t rate, void *obj) {
return static_cast<waybar::modules::JACK *>(obj)->sampleRate(rate);
int sampleRateCallback(jack_nframes_t rate, void* obj) {
return static_cast<waybar::modules::JACK*>(obj)->sampleRate(rate);
}
int xrunCallback(void *obj) { return static_cast<waybar::modules::JACK *>(obj)->xrun(); }
int xrunCallback(void* obj) { return static_cast<waybar::modules::JACK*>(obj)->xrun(); }
void shutdownCallback(void *obj) { return static_cast<waybar::modules::JACK *>(obj)->shutdown(); }
void shutdownCallback(void* obj) { return static_cast<waybar::modules::JACK*>(obj)->shutdown(); }
+22 -7
View File
@@ -232,9 +232,12 @@ waybar::modules::KeyboardState::KeyboardState(const std::string& id, const Bar&
}
tryAddDevice(dev_path);
} else if (event->mask & IN_DELETE) {
std::lock_guard<std::mutex> lock(devices_mutex_);
auto it = libinput_devices_.find(dev_path);
if (it != libinput_devices_.end()) {
spdlog::info("Keyboard {} has been removed.", dev_path);
libinput_path_remove_device(it->second);
libinput_device_unref(it->second);
libinput_devices_.erase(it);
}
}
@@ -245,6 +248,7 @@ waybar::modules::KeyboardState::KeyboardState(const std::string& id, const Bar&
}
waybar::modules::KeyboardState::~KeyboardState() {
std::lock_guard<std::mutex> lock(devices_mutex_);
for (const auto& [_, dev_ptr] : libinput_devices_) {
libinput_path_remove_device(dev_ptr);
}
@@ -256,11 +260,17 @@ auto waybar::modules::KeyboardState::update() -> void {
try {
std::string dev_path;
if (config_["device-path"].isString() &&
libinput_devices_.find(config_["device-path"].asString()) != libinput_devices_.end()) {
dev_path = config_["device-path"].asString();
} else {
dev_path = libinput_devices_.begin()->first;
{
std::lock_guard<std::mutex> lock(devices_mutex_);
if (libinput_devices_.empty()) {
return;
}
if (config_["device-path"].isString() &&
libinput_devices_.find(config_["device-path"].asString()) != libinput_devices_.end()) {
dev_path = config_["device-path"].asString();
} else {
dev_path = libinput_devices_.begin()->first;
}
}
int fd = openFile(dev_path, O_NONBLOCK | O_CLOEXEC | O_RDONLY);
auto dev = openDevice(fd);
@@ -308,10 +318,15 @@ auto waybar::modules ::KeyboardState::tryAddDevice(const std::string& dev_path)
auto dev = openDevice(fd);
if (supportsLockStates(dev)) {
spdlog::info("Found device {} at '{}'", libevdev_get_name(dev), dev_path);
std::lock_guard<std::mutex> lock(devices_mutex_);
if (libinput_devices_.find(dev_path) == libinput_devices_.end()) {
auto device = libinput_path_add_device(libinput_, dev_path.c_str());
libinput_device_ref(device);
libinput_devices_[dev_path] = device;
if (device) {
libinput_device_ref(device);
libinput_devices_[dev_path] = device;
} else {
spdlog::warn("keyboard-state: Failed to add device to libinput: {}", dev_path);
}
}
}
libevdev_free(dev);
+1 -1
View File
@@ -22,7 +22,7 @@ auto waybar::modules::Load::update() -> void {
auto [load1, load5, load15] = Load::getLoad();
if (tooltipEnabled()) {
auto tooltip = fmt::format("Load 1: {}\nLoad 5: {}\nLoad 15: {}", load1, load5, load15);
label_.set_tooltip_text(tooltip);
label_.set_tooltip_markup(tooltip);
}
auto format = format_;
auto state = getState(load1);
+43 -21
View File
@@ -1,11 +1,32 @@
#include "modules/memory.hpp"
namespace {
const std::unordered_map<std::string, float> kUnits = {
{"kB", 1.000},
{"kiB", 1.024},
{"MB", 1.000 * 1000.0},
{"MiB", 1.024 * 1024.0},
{"GB", 1.000 * 1000.0 * 1000.0},
{"GiB", 1.024 * 1024.0 * 1024.0},
{"TB", 1.000 * 1000.0 * 1000.0 * 1000.0},
{"TiB", 1.024 * 1024.0 * 1024.0 * 1024.0}
};
}
waybar::modules::Memory::Memory(const std::string& id, const Json::Value& config)
: ALabel(config, "memory", id, "{}%", 30) {
thread_ = [this] {
dp.emit();
thread_.sleep_for(interval_);
};
if (config["unit"].isString()) {
unit_ = config["unit"].asString();
if (!kUnits.contains(unit_)) {
unit_ = "GiB";
}
} else {
unit_ = "GiB";
}
}
auto waybar::modules::Memory::update() -> void {
@@ -13,15 +34,15 @@ auto waybar::modules::Memory::update() -> void {
unsigned long memtotal = meminfo_["MemTotal"];
unsigned long swaptotal = 0;
if (meminfo_.count("SwapTotal")) {
if (meminfo_.contains("SwapTotal")) {
swaptotal = meminfo_["SwapTotal"];
}
unsigned long memfree;
unsigned long swapfree = 0;
if (meminfo_.count("SwapFree")) {
if (meminfo_.contains("SwapFree")) {
swapfree = meminfo_["SwapFree"];
}
if (meminfo_.count("MemAvailable")) {
if (meminfo_.contains("MemAvailable")) {
// New kernels (3.4+) have an accurate available memory field.
memfree = meminfo_["MemAvailable"] + meminfo_["zfs_size"];
} else {
@@ -31,18 +52,19 @@ auto waybar::modules::Memory::update() -> void {
}
if (memtotal > 0 && memfree >= 0) {
float total_ram_gigabytes =
0.01 * round(memtotal / 10485.76); // 100*10485.76 = 2^20 = 1024^2 = GiB/KiB
float total_swap_gigabytes = 0.01 * round(swaptotal / 10485.76);
int used_ram_percentage = 100 * (memtotal - memfree) / memtotal;
int used_swap_percentage = 0;
if (swaptotal) {
if ((bool) swaptotal) {
used_swap_percentage = 100 * (swaptotal - swapfree) / swaptotal;
}
float used_ram_gigabytes = 0.01 * round((memtotal - memfree) / 10485.76);
float used_swap_gigabytes = 0.01 * round((swaptotal - swapfree) / 10485.76);
float available_ram_gigabytes = 0.01 * round(memfree / 10485.76);
float available_swap_gigabytes = 0.01 * round(swapfree / 10485.76);
float divisor = kUnits.at(unit_);
float total_ram = memtotal / divisor;
float total_swap = swaptotal / divisor;
float used_ram = (memtotal - memfree) / divisor;
float used_swap = (swaptotal - swapfree) / divisor;
float available_ram = memfree / divisor;
float available_swap = swapfree / divisor;
auto format = format_;
auto state = getState(used_ram_percentage);
@@ -58,27 +80,27 @@ auto waybar::modules::Memory::update() -> void {
label_.set_markup(fmt::format(
fmt::runtime(format), used_ram_percentage,
fmt::arg("icon", getIcon(used_ram_percentage, icons)),
fmt::arg("total", total_ram_gigabytes), fmt::arg("swapTotal", total_swap_gigabytes),
fmt::arg("total", total_ram), fmt::arg("swapTotal", total_swap),
fmt::arg("percentage", used_ram_percentage),
fmt::arg("swapState", swaptotal == 0 ? "Off" : "On"),
fmt::arg("swapPercentage", used_swap_percentage), fmt::arg("used", used_ram_gigabytes),
fmt::arg("swapUsed", used_swap_gigabytes), fmt::arg("avail", available_ram_gigabytes),
fmt::arg("swapAvail", available_swap_gigabytes)));
fmt::arg("swapPercentage", used_swap_percentage), fmt::arg("used", used_ram),
fmt::arg("swapUsed", used_swap), fmt::arg("avail", available_ram),
fmt::arg("swapAvail", available_swap)));
}
if (tooltipEnabled()) {
if (config_["tooltip-format"].isString()) {
auto tooltip_format = config_["tooltip-format"].asString();
label_.set_tooltip_text(fmt::format(
label_.set_tooltip_markup(fmt::format(
fmt::runtime(tooltip_format), used_ram_percentage,
fmt::arg("total", total_ram_gigabytes), fmt::arg("swapTotal", total_swap_gigabytes),
fmt::arg("total", total_ram), fmt::arg("swapTotal", total_swap),
fmt::arg("percentage", used_ram_percentage),
fmt::arg("swapState", swaptotal == 0 ? "Off" : "On"),
fmt::arg("swapPercentage", used_swap_percentage), fmt::arg("used", used_ram_gigabytes),
fmt::arg("swapUsed", used_swap_gigabytes), fmt::arg("avail", available_ram_gigabytes),
fmt::arg("swapAvail", available_swap_gigabytes)));
fmt::arg("swapPercentage", used_swap_percentage), fmt::arg("used", used_ram),
fmt::arg("swapUsed", used_swap), fmt::arg("avail", available_ram),
fmt::arg("swapAvail", available_swap)));
} else {
label_.set_tooltip_text(fmt::format("{:.{}f}GiB used", used_ram_gigabytes, 1));
label_.set_tooltip_markup(fmt::format("{:.{}f}{} used", used_ram, 1, unit_));
}
}
} else {
+54 -41
View File
@@ -6,6 +6,7 @@
#include <system_error>
#include <util/sanitize_str.hpp>
#include <util/utf8_string.hpp>
using namespace waybar::util;
#include "modules/mpd/state.hpp"
@@ -24,7 +25,8 @@ waybar::modules::MPD::MPD(const std::string& id, const Json::Value& config)
timeout_(config_["timeout"].isUInt() ? config_["timeout"].asUInt() * 1'000 : 30'000),
connection_(nullptr, &mpd_connection_free),
status_(nullptr, &mpd_status_free),
song_(nullptr, &mpd_song_free) {
song_(nullptr, &mpd_song_free),
ellipsis_(config_["ellipsis"].isString() ? config_["ellipsis"].asString() : "\u2026") {
if (!config_["port"].isNull() && !config_["port"].isUInt()) {
spdlog::warn("{}: `port` configuration should be an unsigned int", module_name_);
}
@@ -51,21 +53,6 @@ auto waybar::modules::MPD::update() -> void {
ALabel::update();
}
void waybar::modules::MPD::queryMPD() {
if (connection_ != nullptr) {
spdlog::trace("{}: fetching state information", module_name_);
try {
fetchState();
spdlog::trace("{}: fetch complete", module_name_);
} catch (std::exception const& e) {
spdlog::error("{}: {}", module_name_, e.what());
state_ = MPD_STATE_UNKNOWN;
}
dp.emit();
}
}
std::string waybar::modules::MPD::getTag(mpd_tag_type type, unsigned idx) const {
std::string result =
config_["unknown-tag"].isString() ? config_["unknown-tag"].asString() : "N/A";
@@ -98,7 +85,7 @@ void waybar::modules::MPD::setLabel() {
? config_["format-disconnected"].asString()
: "disconnected";
if (format.empty()) {
label_.set_markup(format);
setLabelMarkup(format);
label_.show();
} else {
label_.hide();
@@ -110,22 +97,22 @@ void waybar::modules::MPD::setLabel() {
? config_["tooltip-format-disconnected"].asString()
: "MPD (disconnected)";
// Nothing to format
label_.set_tooltip_text(tooltip_format);
setTooltipMarkup(tooltip_format);
}
return;
}
label_.get_style_context()->remove_class("disconnected");
auto format = format_;
Glib::ustring artist, album_artist, album, title;
std::string date, filename, uri;
int song_pos = 0, queue_length = 0, volume = 0;
std::chrono::seconds elapsedTime, totalTime;
std::string stateIcon = "";
bool no_song = song_.get() == nullptr;
if (stopped() || no_song) {
if (no_song) spdlog::warn("Bug in mpd: no current song but state is not stopped.");
bool is_stopped = stopped();
if (is_stopped || no_song) {
if (no_song && !is_stopped) spdlog::warn("mpd: no current song while state is not stopped");
format =
config_["format-stopped"].isString() ? config_["format-stopped"].asString() : "stopped";
label_.get_style_context()->add_class("stopped");
@@ -137,18 +124,15 @@ void waybar::modules::MPD::setLabel() {
label_.get_style_context()->add_class("playing");
label_.get_style_context()->remove_class("paused");
} else if (paused()) {
format = config_["format-paused"].isString() ? config_["format-paused"].asString()
: config_["format"].asString();
if (config_["format-paused"].isString()) {
format = config_["format-paused"].asString();
}
label_.get_style_context()->add_class("paused");
label_.get_style_context()->remove_class("playing");
}
stateIcon = getStateIcon();
artist = sanitize_string(getTag(MPD_TAG_ARTIST));
album_artist = sanitize_string(getTag(MPD_TAG_ALBUM_ARTIST));
album = sanitize_string(getTag(MPD_TAG_ALBUM));
title = sanitize_string(getTag(MPD_TAG_TITLE));
date = sanitize_string(getTag(MPD_TAG_DATE));
filename = sanitize_string(getFilename());
uri = mpd_song_get_uri(song_.get());
@@ -170,17 +154,12 @@ void waybar::modules::MPD::setLabel() {
std::string repeatIcon = getOptionIcon("repeat", repeatActivated);
bool singleActivated = mpd_status_get_single(status_.get());
std::string singleIcon = getOptionIcon("single", singleActivated);
if (config_["artist-len"].isInt()) artist = artist.substr(0, config_["artist-len"].asInt());
if (config_["album-artist-len"].isInt())
album_artist = album_artist.substr(0, config_["album-artist-len"].asInt());
if (config_["album-len"].isInt()) album = album.substr(0, config_["album-len"].asInt());
if (config_["title-len"].isInt()) title = title.substr(0, config_["title-len"].asInt());
try {
auto text = fmt::format(
fmt::runtime(format), fmt::arg("artist", artist.raw()),
fmt::arg("albumArtist", album_artist.raw()), fmt::arg("album", album.raw()),
fmt::arg("title", title.raw()), fmt::arg("date", date), fmt::arg("volume", volume),
fmt::runtime(format), fmt::arg("artist", getArtistStr(true)),
fmt::arg("albumArtist", getAlbumArtistStr(true)), fmt::arg("album", getAlbumStr(true)),
fmt::arg("title", getTitleStr(true)), fmt::arg("date", date), fmt::arg("volume", volume),
fmt::arg("elapsedTime", elapsedTime), fmt::arg("totalTime", totalTime),
fmt::arg("songPosition", song_pos), fmt::arg("queueLength", queue_length),
fmt::arg("stateIcon", stateIcon), fmt::arg("consumeIcon", consumeIcon),
@@ -190,7 +169,7 @@ void waybar::modules::MPD::setLabel() {
label_.hide();
} else {
label_.show();
label_.set_markup(text);
setLabelMarkup(text);
}
} catch (fmt::format_error const& e) {
spdlog::warn("mpd: format error: {}", e.what());
@@ -202,15 +181,15 @@ void waybar::modules::MPD::setLabel() {
: "MPD (connected)";
try {
auto tooltip_text = fmt::format(
fmt::runtime(tooltip_format), fmt::arg("artist", artist.raw()),
fmt::arg("albumArtist", album_artist.raw()), fmt::arg("album", album.raw()),
fmt::arg("title", title.raw()), fmt::arg("date", date), fmt::arg("volume", volume),
fmt::runtime(tooltip_format), fmt::arg("artist", getArtistStr(false)),
fmt::arg("albumArtist", getAlbumArtistStr(false)), fmt::arg("album", getAlbumStr(false)),
fmt::arg("title", getTitleStr(false)), fmt::arg("date", date), fmt::arg("volume", volume),
fmt::arg("elapsedTime", elapsedTime), fmt::arg("totalTime", totalTime),
fmt::arg("songPosition", song_pos), fmt::arg("queueLength", queue_length),
fmt::arg("stateIcon", stateIcon), fmt::arg("consumeIcon", consumeIcon),
fmt::arg("randomIcon", randomIcon), fmt::arg("repeatIcon", repeatIcon),
fmt::arg("singleIcon", singleIcon), fmt::arg("filename", filename), fmt::arg("uri", uri));
label_.set_tooltip_text(tooltip_text);
setTooltipMarkup(tooltip_text);
} catch (fmt::format_error const& e) {
spdlog::warn("mpd: format error (tooltip): {}", e.what());
}
@@ -239,7 +218,8 @@ std::string waybar::modules::MPD::getStateIcon() const {
}
}
std::string waybar::modules::MPD::getOptionIcon(std::string optionName, bool activated) const {
std::string waybar::modules::MPD::getOptionIcon(const std::string& optionName,
bool activated) const {
if (!config_[optionName + "-icons"].isObject()) {
return "";
}
@@ -256,6 +236,38 @@ std::string waybar::modules::MPD::getOptionIcon(std::string optionName, bool act
}
}
std::string waybar::modules::MPD::getArtistStr(bool truncated) const {
std::string artist = getTag(MPD_TAG_ARTIST);
if (truncated && config_["artist-len"].isInt()) {
waybar::util::utf8_truncate(artist, ellipsis_, config_["artist-len"].asInt());
}
return sanitize_string(artist);
}
std::string waybar::modules::MPD::getAlbumArtistStr(bool truncated) const {
std::string album_artist = getTag(MPD_TAG_ALBUM_ARTIST);
if (truncated && config_["album-artist-len"].isInt()) {
waybar::util::utf8_truncate(album_artist, ellipsis_, config_["album-artist-len"].asInt());
}
return sanitize_string(album_artist);
}
std::string waybar::modules::MPD::getAlbumStr(bool truncated) const {
std::string album = getTag(MPD_TAG_ALBUM);
if (truncated && config_["album-len"].isInt()) {
waybar::util::utf8_truncate(album, ellipsis_, config_["album-len"].asInt());
}
return sanitize_string(album);
}
std::string waybar::modules::MPD::getTitleStr(bool truncated) const {
std::string title = getTag(MPD_TAG_TITLE);
if (truncated && config_["title-len"].isInt()) {
waybar::util::utf8_truncate(title, ellipsis_, config_["title-len"].asInt());
}
return sanitize_string(title);
}
static bool isServerUnavailable(const std::error_code& ec) {
if (ec.category() == std::system_category()) {
switch (ec.value()) {
@@ -323,6 +335,7 @@ void waybar::modules::MPD::checkErrors(mpd_connection* conn) {
case MPD_ERROR_SYSTEM:
if (auto ec = mpd_connection_get_system_error(conn); ec != 0) {
mpd_connection_clear_error(conn);
connection_.reset();
throw std::system_error(ec, std::system_category());
}
G_GNUC_FALLTHROUGH;
-1
View File
@@ -152,7 +152,6 @@ bool Playing::on_timer() {
return false;
}
ctx_->queryMPD();
ctx_->emit();
} catch (std::exception const& e) {
spdlog::warn("mpd: Playing: error: {}", e.what());
+96 -90
View File
@@ -7,6 +7,7 @@
#include <string>
#include "util/scope_guard.hpp"
#include "util/utf8_string.hpp"
extern "C" {
#include <playerctl/playerctl.h>
@@ -109,6 +110,7 @@ Mpris::Mpris(const std::string& id, const Json::Value& config)
player_ = config_["player"].asString();
}
if (config_["ignored-players"].isArray()) {
ignored_players_.reserve(config_["ignored-players"].size());
for (const auto& item : config_["ignored-players"]) {
if (item.isString()) {
ignored_players_.push_back(item.asString());
@@ -117,7 +119,7 @@ Mpris::Mpris(const std::string& id, const Json::Value& config)
}
GError* error = nullptr;
waybar::util::ScopeGuard error_deleter([error]() {
waybar::util::ScopeGuard error_deleter([&error]() {
if (error) {
g_error_free(error);
}
@@ -161,8 +163,7 @@ Mpris::Mpris(const std::string& id, const Json::Value& config)
if (player) {
g_object_connect(player, "signal::play", G_CALLBACK(onPlayerPlay), this, "signal::pause",
G_CALLBACK(onPlayerPause), this, "signal::stop", G_CALLBACK(onPlayerStop),
this, "signal::stop", G_CALLBACK(onPlayerStop), this, "signal::metadata",
G_CALLBACK(onPlayerMetadata), this, NULL);
this, "signal::metadata", G_CALLBACK(onPlayerMetadata), this, NULL);
}
// allow setting an interval count that triggers periodic refreshes
@@ -178,8 +179,17 @@ Mpris::Mpris(const std::string& id, const Json::Value& config)
}
Mpris::~Mpris() {
if (manager != nullptr) g_object_unref(manager);
if (player != nullptr) g_object_unref(player);
if (manager != nullptr) {
g_signal_handlers_disconnect_by_data(manager, this);
}
if (player != nullptr) {
g_signal_handlers_disconnect_by_data(player, this);
}
if (last_active_player_ != nullptr && last_active_player_ != player) {
g_object_unref(last_active_player_);
}
g_clear_object(&manager);
g_clear_object(&player);
}
auto Mpris::getIconFromJson(const Json::Value& icons, const std::string& key) -> std::string {
@@ -193,69 +203,22 @@ auto Mpris::getIconFromJson(const Json::Value& icons, const std::string& key) ->
// Wide characters count as two, zero-width characters count as zero
// Modifies str in-place (unless width = std::string::npos)
// Returns the total width of the string pre-truncating
size_t utf8_truncate(std::string& str, size_t width = std::string::npos) {
if (str.length() == 0) return 0;
const gchar* trunc_end = nullptr;
size_t total_width = 0;
for (gchar *data = str.data(), *end = data + str.size(); data != nullptr;) {
gunichar c = g_utf8_get_char_validated(data, end - data);
if (c == -1U || c == -2U) {
// invalid unicode, treat string as ascii
if (width != std::string::npos && str.length() > width) str.resize(width);
return str.length();
} else if (g_unichar_iswide(c)) {
total_width += 2;
} else if (!g_unichar_iszerowidth(c) && c != 0xAD) { // neither zero-width nor soft hyphen
total_width += 1;
}
data = g_utf8_find_next_char(data, end);
if (width != std::string::npos && total_width <= width && !g_unichar_isspace(c))
trunc_end = data;
}
if (trunc_end) str.resize(trunc_end - str.data());
return total_width;
}
size_t utf8_width(const std::string& str) { return utf8_truncate(const_cast<std::string&>(str)); }
void truncate(std::string& s, const std::string& ellipsis, size_t max_len) {
if (max_len == 0) {
s.resize(0);
return;
}
size_t len = utf8_truncate(s, max_len);
if (len > max_len) {
size_t ellipsis_len = utf8_width(ellipsis);
if (max_len >= ellipsis_len) {
if (ellipsis_len) utf8_truncate(s, max_len - ellipsis_len);
s += ellipsis;
} else {
s.resize(0);
}
}
}
auto Mpris::getArtistStr(const PlayerInfo& info, bool truncated) -> std::string {
auto artist = info.artist.value_or(std::string());
if (truncated && artist_len_ >= 0) truncate(artist, ellipsis_, artist_len_);
if (truncated && artist_len_ >= 0) waybar::util::utf8_truncate(artist, ellipsis_, artist_len_);
return artist;
}
auto Mpris::getAlbumStr(const PlayerInfo& info, bool truncated) -> std::string {
auto album = info.album.value_or(std::string());
if (truncated && album_len_ >= 0) truncate(album, ellipsis_, album_len_);
if (truncated && album_len_ >= 0) waybar::util::utf8_truncate(album, ellipsis_, album_len_);
return album;
}
auto Mpris::getTitleStr(const PlayerInfo& info, bool truncated) -> std::string {
auto title = info.title.value_or(std::string());
if (truncated && title_len_ >= 0) truncate(title, ellipsis_, title_len_);
if (truncated && title_len_ >= 0) waybar::util::utf8_truncate(title, ellipsis_, title_len_);
return title;
}
@@ -283,9 +246,9 @@ auto Mpris::getDynamicStr(const PlayerInfo& info, bool truncated, bool html) ->
// keep position format same as length format
auto position = getPositionStr(info, truncated && truncate_hours_ && length.length() < 6);
size_t artistLen = utf8_width(artist);
size_t albumLen = utf8_width(album);
size_t titleLen = utf8_width(title);
size_t artistLen = waybar::util::utf8_width(artist);
size_t albumLen = waybar::util::utf8_width(album);
size_t titleLen = waybar::util::utf8_width(title);
size_t lengthLen = length.length();
size_t posLen = position.length();
@@ -304,7 +267,7 @@ auto Mpris::getDynamicStr(const PlayerInfo& info, bool truncated, bool html) ->
// Since the first element doesn't present a separator and we don't know a priori which one
// it will be, we add a "virtual separatorLen" to the dynamicLen, since we are adding the
// separatorLen to all the other lengths.
size_t separatorLen = utf8_width(dynamic_separator_);
size_t separatorLen = waybar::util::utf8_width(dynamic_separator_);
size_t dynamicLen = dynamic_len_ + separatorLen;
if (showArtist) artistLen += separatorLen;
if (showAlbum) albumLen += separatorLen;
@@ -410,11 +373,14 @@ auto Mpris::onPlayerNameAppeared(PlayerctlPlayerManager* manager, PlayerctlPlaye
return;
}
if (mpris->player != nullptr) {
g_signal_handlers_disconnect_by_data(mpris->player, mpris);
g_clear_object(&mpris->player);
}
mpris->player = playerctl_player_new_from_name(player_name, nullptr);
g_object_connect(mpris->player, "signal::play", G_CALLBACK(onPlayerPlay), mpris, "signal::pause",
G_CALLBACK(onPlayerPause), mpris, "signal::stop", G_CALLBACK(onPlayerStop),
mpris, "signal::stop", G_CALLBACK(onPlayerStop), mpris, "signal::metadata",
G_CALLBACK(onPlayerMetadata), mpris, NULL);
mpris, "signal::metadata", G_CALLBACK(onPlayerMetadata), mpris, NULL);
mpris->dp.emit();
}
@@ -458,10 +424,7 @@ auto Mpris::onPlayerStop(PlayerctlPlayer* player, gpointer data) -> void {
if (!mpris) return;
spdlog::debug("mpris: player-stop callback");
// hide widget
mpris->event_box_.set_visible(false);
// update widget
// update widget (update() handles visibility)
mpris->dp.emit();
}
@@ -480,7 +443,7 @@ auto Mpris::getPlayerInfo() -> std::optional<PlayerInfo> {
}
GError* error = nullptr;
waybar::util::ScopeGuard error_deleter([error]() {
waybar::util::ScopeGuard error_deleter([&error]() {
if (error) {
g_error_free(error);
}
@@ -488,7 +451,12 @@ auto Mpris::getPlayerInfo() -> std::optional<PlayerInfo> {
char* player_status = nullptr;
auto player_playback_status = PLAYERCTL_PLAYBACK_STATUS_STOPPED;
g_object_get(player, "status", &player_status, "playback-status", &player_playback_status, NULL);
// Clean up previous fallback player
if (last_active_player_ && last_active_player_ != player) {
g_object_unref(last_active_player_);
last_active_player_ = nullptr;
}
std::string player_name = player_;
if (player_name == "playerctld") {
@@ -498,19 +466,52 @@ auto Mpris::getPlayerInfo() -> std::optional<PlayerInfo> {
}
// > get the list of players [..] in order of activity
// https://github.com/altdesktop/playerctl/blob/b19a71cb9dba635df68d271bd2b3f6a99336a223/playerctl/playerctl-common.c#L248-L249
players = g_list_first(players);
if (players)
player_name = static_cast<PlayerctlPlayerName*>(players->data)->name;
else
return std::nullopt; // no players found, hide the widget
}
if (std::any_of(ignored_players_.begin(), ignored_players_.end(),
[&](const std::string& pn) { return player_name == pn; })) {
PlayerctlPlayer* first_valid_player = nullptr;
std::string first_valid_name;
for (auto* p = g_list_first(players); p != nullptr; p = p->next) {
auto* pn = static_cast<PlayerctlPlayerName*>(p->data);
std::string name = pn->name;
if (std::any_of(ignored_players_.begin(), ignored_players_.end(),
[&](const std::string& ignored) { return name == ignored; })) {
spdlog::warn("mpris[{}]: ignoring player update", name);
continue;
}
auto* tmp = playerctl_player_new_from_name(pn, &error);
if (error || !tmp) continue;
if (!first_valid_player) {
first_valid_player = tmp;
first_valid_name = name;
}
PlayerctlPlaybackStatus status;
g_object_get(tmp, "playback-status", &status, NULL);
if (status == PLAYERCTL_PLAYBACK_STATUS_PLAYING) {
if (tmp != first_valid_player) g_object_unref(first_valid_player);
last_active_player_ = tmp;
player_name = name;
break;
}
if (tmp != first_valid_player) g_object_unref(tmp);
}
if (!last_active_player_) {
if (!first_valid_player) return std::nullopt;
last_active_player_ = first_valid_player;
player_name = first_valid_name;
}
} else if (std::any_of(ignored_players_.begin(), ignored_players_.end(),
[&](const std::string& pn) { return player_name == pn; })) {
spdlog::warn("mpris[{}]: ignoring player update", player_name);
return std::nullopt;
} else {
last_active_player_ = player;
}
g_object_get(last_active_player_, "status", &player_status, "playback-status",
&player_playback_status, NULL);
if (!player_status) {
spdlog::error("mpris: failed to get player status");
return std::nullopt;
}
// make status lowercase
player_status[0] = std::tolower(player_status[0]);
@@ -524,28 +525,29 @@ auto Mpris::getPlayerInfo() -> std::optional<PlayerInfo> {
.length = std::nullopt,
};
if (auto* artist_ = playerctl_player_get_artist(player, &error)) {
if (auto* artist_ = playerctl_player_get_artist(last_active_player_, &error)) {
spdlog::debug("mpris[{}]: artist = {}", info.name, artist_);
info.artist = artist_;
g_free(artist_);
}
if (error) goto errorexit;
if (auto* album_ = playerctl_player_get_album(player, &error)) {
if (auto* album_ = playerctl_player_get_album(last_active_player_, &error)) {
spdlog::debug("mpris[{}]: album = {}", info.name, album_);
info.album = album_;
g_free(album_);
}
if (error) goto errorexit;
if (auto* title_ = playerctl_player_get_title(player, &error)) {
if (auto* title_ = playerctl_player_get_title(last_active_player_, &error)) {
spdlog::debug("mpris[{}]: title = {}", info.name, title_);
info.title = title_;
g_free(title_);
}
if (error) goto errorexit;
if (auto* length_ = playerctl_player_print_metadata_prop(player, "mpris:length", &error)) {
if (auto* length_ =
playerctl_player_print_metadata_prop(last_active_player_, "mpris:length", &error)) {
spdlog::debug("mpris[{}]: mpris:length = {}", info.name, length_);
auto len = std::chrono::microseconds(std::strtol(length_, nullptr, 10));
auto len_h = std::chrono::duration_cast<std::chrono::hours>(len);
@@ -557,7 +559,7 @@ auto Mpris::getPlayerInfo() -> std::optional<PlayerInfo> {
if (error) goto errorexit;
{
auto position_ = playerctl_player_get_position(player, &error);
auto position_ = playerctl_player_get_position(last_active_player_, &error);
if (error) {
// it's fine to have an error here because not all players report a position
g_error_free(error);
@@ -609,12 +611,13 @@ bool Mpris::handleToggle(GdkEventButton* const& e) {
});
// Command pattern: encapsulate each button's action
auto* target = last_active_player_ ? last_active_player_ : player;
const ButtonAction actions[] = {
{1, "on-click", [&]() { playerctl_player_play_pause(player, &error); }},
{2, "on-click-middle", [&]() { playerctl_player_previous(player, &error); }},
{3, "on-click-right", [&]() { playerctl_player_next(player, &error); }},
{8, "on-click-backward", [&]() { playerctl_player_previous(player, &error); }},
{9, "on-click-forward", [&]() { playerctl_player_next(player, &error); }},
{1, "on-click", [&]() { playerctl_player_play_pause(target, &error); }},
{2, "on-click-middle", [&]() { playerctl_player_previous(target, &error); }},
{3, "on-click-right", [&]() { playerctl_player_next(target, &error); }},
{8, "on-click-backward", [&]() { playerctl_player_previous(target, &error); }},
{9, "on-click-forward", [&]() { playerctl_player_next(target, &error); }},
};
for (const auto& action : actions) {
@@ -726,15 +729,18 @@ auto Mpris::update() -> void {
auto tooltip_text = fmt::format(
fmt::runtime(tooltipstr), fmt::arg("player", info.name),
fmt::arg("status", info.status_string),
fmt::arg("artist", getArtistStr(info, tooltip_len_limits_)),
fmt::arg("title", getTitleStr(info, tooltip_len_limits_)),
fmt::arg("album", getAlbumStr(info, tooltip_len_limits_)),
fmt::arg("artist",
std::string(Glib::Markup::escape_text(getArtistStr(info, tooltip_len_limits_)))),
fmt::arg("title",
std::string(Glib::Markup::escape_text(getTitleStr(info, tooltip_len_limits_)))),
fmt::arg("album",
std::string(Glib::Markup::escape_text(getAlbumStr(info, tooltip_len_limits_)))),
fmt::arg("length", tooltipLength), fmt::arg("position", tooltipPosition),
fmt::arg("dynamic", getDynamicStr(info, tooltip_len_limits_, false)),
fmt::arg("player_icon", getIconFromJson(config_["player-icons"], info.name)),
fmt::arg("status_icon", getIconFromJson(config_["status-icons"], info.status_string)));
label_.set_tooltip_text(tooltip_text);
label_.set_tooltip_markup(tooltip_text);
} catch (fmt::format_error const& e) {
spdlog::warn("mpris: format error (tooltip): {}", e.what());
}
+134 -92
View File
@@ -21,10 +21,10 @@
namespace {
using namespace waybar::util;
constexpr const char *DEFAULT_FORMAT = "{ifname}";
constexpr const char* DEFAULT_FORMAT = "{ifname}";
} // namespace
constexpr const char *NETDEV_FILE =
constexpr const char* NETDEV_FILE =
"/proc/net/dev"; // std::ifstream does not take std::string_view as param
std::optional<std::pair<unsigned long long, unsigned long long>>
waybar::modules::Network::readBandwidthUsage() {
@@ -45,7 +45,8 @@ waybar::modules::Network::readBandwidthUsage() {
std::istringstream iss(line);
std::string ifacename;
iss >> ifacename; // ifacename contains "eth0:"
iss >> ifacename; // ifacename contains "eth0:"
if (ifacename.empty()) continue;
ifacename.pop_back(); // remove trailing ':'
if (ifacename != ifname_) {
continue;
@@ -82,7 +83,7 @@ waybar::modules::Network::readBandwidthUsage() {
return {{receivedBytes, transmittedBytes}};
}
waybar::modules::Network::Network(const std::string &id, const Json::Value &config)
waybar::modules::Network::Network(const std::string& id, const Json::Value& config)
: ALabel(config, "network", id, DEFAULT_FORMAT, 60) {
// Start with some "text" in the module's label_. update() will then
// update it. Since the text should be different, update() will be able
@@ -104,6 +105,7 @@ waybar::modules::Network::Network(const std::string &id, const Json::Value &conf
bandwidth_down_total_ = 0;
bandwidth_up_total_ = 0;
}
bandwidth_last_sample_time_ = std::chrono::steady_clock::now();
if (!config_["interface"].isString()) {
// "interface" isn't configured, then try to guess the external
@@ -216,7 +218,7 @@ void waybar::modules::Network::worker() {
thread_timer_.sleep_for(interval_);
};
#ifdef WANT_RFKILL
rfkill_.on_update.connect([this](auto &) {
rfkill_.on_update.connect([this](auto&) {
/* If we are here, it's likely that the network thread already holds the mutex and will be
* holding it for a next few seconds.
* Let's delegate the update to the timer thread instead of blocking the main thread.
@@ -276,19 +278,41 @@ const std::string waybar::modules::Network::getNetworkState() const {
auto waybar::modules::Network::update() -> void {
std::lock_guard<std::mutex> lock(mutex_);
std::string tooltip_format;
auto now = std::chrono::steady_clock::now();
auto elapsed_seconds = std::chrono::duration<double>(now - bandwidth_last_sample_time_).count();
auto bandwidth = readBandwidthUsage();
auto bandwidth_down = 0ull;
auto bandwidth_up = 0ull;
if (bandwidth.has_value()) {
auto down_octets = (*bandwidth).first;
auto up_octets = (*bandwidth).second;
bandwidth_down = down_octets - bandwidth_down_total_;
bandwidth_down_total_ = down_octets;
// Only recalculate bandwidth when enough time has elapsed since the last
// sample. Event-driven dp.emit() calls (link/addr/route changes) can
// trigger update() between timer intervals, which would consume the byte
// delta prematurely and show near-zero bandwidth.
auto min_elapsed = std::chrono::duration<double>(interval_).count() * 0.5;
if (elapsed_seconds >= min_elapsed) {
if (elapsed_seconds <= 0.0) {
elapsed_seconds = std::chrono::duration<double>(interval_).count();
}
bandwidth_last_sample_time_ = now;
bandwidth_up = up_octets - bandwidth_up_total_;
bandwidth_up_total_ = up_octets;
auto bandwidth = readBandwidthUsage();
if (bandwidth.has_value()) {
auto down_octets = (*bandwidth).first;
auto up_octets = (*bandwidth).second;
bandwidth_down = down_octets - bandwidth_down_total_;
bandwidth_down_total_ = down_octets;
bandwidth_up = up_octets - bandwidth_up_total_;
bandwidth_up_total_ = up_octets;
bandwidth_down_prev_ = bandwidth_down;
bandwidth_up_prev_ = bandwidth_up;
}
} else {
bandwidth_down = bandwidth_down_prev_;
bandwidth_up = bandwidth_up_prev_;
elapsed_seconds = std::chrono::duration<double>(interval_).count();
}
if (!alt_) {
@@ -320,6 +344,7 @@ auto waybar::modules::Network::update() -> void {
} else if (addr_pref_ == ip_addr_pref::IPV6) {
final_ipaddr_ = ipaddr6_;
} else if (addr_pref_ == ip_addr_pref::IPV4_6) {
final_ipaddr_.reserve(ipaddr_.length() + ipaddr6_.length() + 1);
final_ipaddr_ = ipaddr_;
final_ipaddr_ += '\n';
final_ipaddr_ += ipaddr6_;
@@ -333,23 +358,18 @@ auto waybar::modules::Network::update() -> void {
fmt::arg("ipaddr", final_ipaddr_), fmt::arg("gwaddr", gwaddr_), fmt::arg("cidr", cidr_),
fmt::arg("cidr6", cidr6_), fmt::arg("frequency", fmt::format("{:.1f}", frequency_)),
fmt::arg("icon", getIcon(signal_strength_, state_)),
fmt::arg("bandwidthDownBits",
pow_format(bandwidth_down * 8ull / (interval_.count() / 1000.0), "b/s")),
fmt::arg("bandwidthUpBits",
pow_format(bandwidth_up * 8ull / (interval_.count() / 1000.0), "b/s")),
fmt::arg(
"bandwidthTotalBits",
pow_format((bandwidth_up + bandwidth_down) * 8ull / (interval_.count() / 1000.0), "b/s")),
fmt::arg("bandwidthDownOctets",
pow_format(bandwidth_down / (interval_.count() / 1000.0), "o/s")),
fmt::arg("bandwidthUpOctets", pow_format(bandwidth_up / (interval_.count() / 1000.0), "o/s")),
fmt::arg("bandwidthDownBits", pow_format(bandwidth_down * 8ull / elapsed_seconds, "b/s")),
fmt::arg("bandwidthUpBits", pow_format(bandwidth_up * 8ull / elapsed_seconds, "b/s")),
fmt::arg("bandwidthTotalBits",
pow_format((bandwidth_up + bandwidth_down) * 8ull / elapsed_seconds, "b/s")),
fmt::arg("bandwidthDownOctets", pow_format(bandwidth_down / elapsed_seconds, "o/s")),
fmt::arg("bandwidthUpOctets", pow_format(bandwidth_up / elapsed_seconds, "o/s")),
fmt::arg("bandwidthTotalOctets",
pow_format((bandwidth_up + bandwidth_down) / (interval_.count() / 1000.0), "o/s")),
fmt::arg("bandwidthDownBytes",
pow_format(bandwidth_down / (interval_.count() / 1000.0), "B/s")),
fmt::arg("bandwidthUpBytes", pow_format(bandwidth_up / (interval_.count() / 1000.0), "B/s")),
pow_format((bandwidth_up + bandwidth_down) / elapsed_seconds, "o/s")),
fmt::arg("bandwidthDownBytes", pow_format(bandwidth_down / elapsed_seconds, "B/s")),
fmt::arg("bandwidthUpBytes", pow_format(bandwidth_up / elapsed_seconds, "B/s")),
fmt::arg("bandwidthTotalBytes",
pow_format((bandwidth_up + bandwidth_down) / (interval_.count() / 1000.0), "B/s")));
pow_format((bandwidth_up + bandwidth_down) / elapsed_seconds, "B/s")));
if (text.compare(label_.get_label()) != 0) {
label_.set_markup(text);
if (text.empty()) {
@@ -371,19 +391,18 @@ auto waybar::modules::Network::update() -> void {
fmt::arg("ipaddr", final_ipaddr_), fmt::arg("gwaddr", gwaddr_), fmt::arg("cidr", cidr_),
fmt::arg("cidr6", cidr6_), fmt::arg("frequency", fmt::format("{:.1f}", frequency_)),
fmt::arg("icon", getIcon(signal_strength_, state_)),
fmt::arg("bandwidthDownBits",
pow_format(bandwidth_down * 8ull / interval_.count(), "b/s")),
fmt::arg("bandwidthUpBits", pow_format(bandwidth_up * 8ull / interval_.count(), "b/s")),
fmt::arg("bandwidthDownBits", pow_format(bandwidth_down * 8ull / elapsed_seconds, "b/s")),
fmt::arg("bandwidthUpBits", pow_format(bandwidth_up * 8ull / elapsed_seconds, "b/s")),
fmt::arg("bandwidthTotalBits",
pow_format((bandwidth_up + bandwidth_down) * 8ull / interval_.count(), "b/s")),
fmt::arg("bandwidthDownOctets", pow_format(bandwidth_down / interval_.count(), "o/s")),
fmt::arg("bandwidthUpOctets", pow_format(bandwidth_up / interval_.count(), "o/s")),
pow_format((bandwidth_up + bandwidth_down) * 8ull / elapsed_seconds, "b/s")),
fmt::arg("bandwidthDownOctets", pow_format(bandwidth_down / elapsed_seconds, "o/s")),
fmt::arg("bandwidthUpOctets", pow_format(bandwidth_up / elapsed_seconds, "o/s")),
fmt::arg("bandwidthTotalOctets",
pow_format((bandwidth_up + bandwidth_down) / interval_.count(), "o/s")),
fmt::arg("bandwidthDownBytes", pow_format(bandwidth_down / interval_.count(), "B/s")),
fmt::arg("bandwidthUpBytes", pow_format(bandwidth_up / interval_.count(), "B/s")),
pow_format((bandwidth_up + bandwidth_down) / elapsed_seconds, "o/s")),
fmt::arg("bandwidthDownBytes", pow_format(bandwidth_down / elapsed_seconds, "B/s")),
fmt::arg("bandwidthUpBytes", pow_format(bandwidth_up / elapsed_seconds, "B/s")),
fmt::arg("bandwidthTotalBytes",
pow_format((bandwidth_up + bandwidth_down) / interval_.count(), "B/s")));
pow_format((bandwidth_up + bandwidth_down) / elapsed_seconds, "B/s")));
if (label_.get_tooltip_text() != tooltip_text) {
label_.set_tooltip_markup(tooltip_text);
}
@@ -397,7 +416,7 @@ auto waybar::modules::Network::update() -> void {
}
// https://gist.github.com/rressi/92af77630faf055934c723ce93ae2495
static bool wildcardMatch(const std::string &pattern, const std::string &text) {
static bool wildcardMatch(const std::string& pattern, const std::string& text) {
auto P = int(pattern.size());
auto T = int(text.size());
@@ -435,9 +454,9 @@ static bool wildcardMatch(const std::string &pattern, const std::string &text) {
return p == P;
}
bool waybar::modules::Network::matchInterface(const std::string &ifname,
const std::vector<std::string> &altnames,
std::string &matched) const {
bool waybar::modules::Network::matchInterface(const std::string& ifname,
const std::vector<std::string>& altnames,
std::string& matched) const {
if (!config_["interface"].isString()) {
return false;
}
@@ -448,7 +467,7 @@ bool waybar::modules::Network::matchInterface(const std::string &ifname,
return true;
}
for (const auto &altname : altnames) {
for (const auto& altname : altnames) {
if (config_ifname == altname || wildcardMatch(config_ifname, altname)) {
matched = altname;
return true;
@@ -478,8 +497,8 @@ void waybar::modules::Network::clearIface() {
frequency_ = 0.0;
}
int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
auto net = static_cast<waybar::modules::Network *>(data);
int waybar::modules::Network::handleEvents(struct nl_msg* msg, void* data) {
auto net = static_cast<waybar::modules::Network*>(data);
std::lock_guard<std::mutex> lock(net->mutex_);
auto nh = nlmsg_hdr(msg);
bool is_del_event = false;
@@ -488,8 +507,8 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
case RTM_DELLINK:
is_del_event = true;
case RTM_NEWLINK: {
struct ifinfomsg *ifi = static_cast<struct ifinfomsg *>(NLMSG_DATA(nh));
struct nlattr *attrs[IFLA_MAX + 1];
struct ifinfomsg* ifi = static_cast<struct ifinfomsg*>(NLMSG_DATA(nh));
struct nlattr* attrs[IFLA_MAX + 1];
std::string ifname;
std::vector<std::string> altnames;
std::optional<bool> carrier;
@@ -517,7 +536,7 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
}
if (attrs[IFLA_IFNAME] != nullptr) {
const char *ifname_ptr = nla_get_string(attrs[IFLA_IFNAME]);
const char* ifname_ptr = nla_get_string(attrs[IFLA_IFNAME]);
size_t ifname_len = nla_len(attrs[IFLA_IFNAME]) - 1; // minus \0
ifname = std::string(ifname_ptr, ifname_len);
}
@@ -527,12 +546,12 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
}
if (attrs[IFLA_PROP_LIST] != nullptr) {
struct nlattr *prop;
struct nlattr* prop;
int rem;
nla_for_each_nested(prop, attrs[IFLA_PROP_LIST], rem) {
if (nla_type(prop) == IFLA_ALT_IFNAME) {
const char *altname_ptr = nla_get_string(prop);
const char* altname_ptr = nla_get_string(prop);
size_t altname_len = nla_len(prop) - 1; // minus \0
altnames.emplace_back(altname_ptr, altname_len);
}
@@ -605,9 +624,9 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
case RTM_DELADDR:
is_del_event = true;
case RTM_NEWADDR: {
struct ifaddrmsg *ifa = static_cast<struct ifaddrmsg *>(NLMSG_DATA(nh));
struct ifaddrmsg* ifa = static_cast<struct ifaddrmsg*>(NLMSG_DATA(nh));
ssize_t attrlen = IFA_PAYLOAD(nh);
struct rtattr *ifa_rta = IFA_RTA(ifa);
struct rtattr* ifa_rta = IFA_RTA(ifa);
if ((int)ifa->ifa_index != net->ifid_) {
return NL_OK;
@@ -625,18 +644,31 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
case IFA_LOCAL:
char ipaddr[INET6_ADDRSTRLEN];
if (!is_del_event) {
bool addr_changed = false;
std::string changed_ipaddr;
int changed_cidr = 0;
if ((net->addr_pref_ == ip_addr_pref::IPV4 ||
net->addr_pref_ == ip_addr_pref::IPV4_6) &&
net->cidr_ == 0 && ifa->ifa_family == AF_INET) {
net->ipaddr_ =
inet_ntop(ifa->ifa_family, RTA_DATA(ifa_rta), ipaddr, sizeof(ipaddr));
net->cidr_ = ifa->ifa_prefixlen;
if (inet_ntop(ifa->ifa_family, RTA_DATA(ifa_rta), ipaddr, sizeof(ipaddr)) !=
nullptr) {
net->ipaddr_ = ipaddr;
net->cidr_ = ifa->ifa_prefixlen;
addr_changed = true;
changed_ipaddr = net->ipaddr_;
changed_cidr = net->cidr_;
}
} else if ((net->addr_pref_ == ip_addr_pref::IPV6 ||
net->addr_pref_ == ip_addr_pref::IPV4_6) &&
net->cidr6_ == 0 && ifa->ifa_family == AF_INET6) {
net->ipaddr6_ =
inet_ntop(ifa->ifa_family, RTA_DATA(ifa_rta), ipaddr, sizeof(ipaddr));
net->cidr6_ = ifa->ifa_prefixlen;
if (inet_ntop(ifa->ifa_family, RTA_DATA(ifa_rta), ipaddr, sizeof(ipaddr)) !=
nullptr) {
net->ipaddr6_ = ipaddr;
net->cidr6_ = ifa->ifa_prefixlen;
addr_changed = true;
changed_ipaddr = net->ipaddr6_;
changed_cidr = net->cidr6_;
}
}
switch (ifa->ifa_family) {
@@ -656,14 +688,20 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
net->netmask6_ = inet_ntop(ifa->ifa_family, &netmask6, ipaddr, sizeof(ipaddr));
}
}
spdlog::debug("network: {}, new addr {}/{}", net->ifname_, net->ipaddr_, net->cidr_);
if (addr_changed) {
spdlog::debug("network: {}, new addr {}/{}", net->ifname_, changed_ipaddr,
changed_cidr);
}
} else {
net->ipaddr_.clear();
net->ipaddr6_.clear();
net->cidr_ = 0;
net->cidr6_ = 0;
net->netmask_.clear();
net->netmask6_.clear();
if (ifa->ifa_family == AF_INET) {
net->ipaddr_.clear();
net->cidr_ = 0;
net->netmask_.clear();
} else if (ifa->ifa_family == AF_INET6) {
net->ipaddr6_.clear();
net->cidr6_ = 0;
net->netmask6_.clear();
}
spdlog::debug("network: {} addr deleted {}/{}", net->ifname_,
inet_ntop(ifa->ifa_family, RTA_DATA(ifa_rta), ipaddr, sizeof(ipaddr)),
ifa->ifa_prefixlen);
@@ -681,10 +719,10 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
// Based on https://gist.github.com/Yawning/c70d804d4b8ae78cc698
// to find the interface used to reach the outside world
struct rtmsg *rtm = static_cast<struct rtmsg *>(NLMSG_DATA(nh));
struct rtmsg* rtm = static_cast<struct rtmsg*>(NLMSG_DATA(nh));
int family = rtm->rtm_family;
ssize_t attrlen = RTM_PAYLOAD(nh);
struct rtattr *attr = RTM_RTA(rtm);
struct rtattr* attr = RTM_RTA(rtm);
char gateway_addr[INET6_ADDRSTRLEN];
bool has_gateway = false;
bool has_destination = false;
@@ -718,24 +756,28 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
/* The destination address.
* Should be either missing, or maybe all 0s. Accept both.
*/
const uint32_t nr_zeroes = (family == AF_INET) ? 4 : 16;
unsigned char c = 0;
size_t dstlen = RTA_PAYLOAD(attr);
if (dstlen != nr_zeroes) {
break;
auto* dest = (const unsigned char*)RTA_DATA(attr);
size_t dest_size = RTA_PAYLOAD(attr);
for (size_t i = 0; i < dest_size; ++i) {
if (dest[i] != 0) {
has_destination = true;
break;
}
}
for (uint32_t i = 0; i < dstlen; i += 1) {
c |= *((unsigned char *)RTA_DATA(attr) + i);
if (rtm->rtm_dst_len != 0) {
// We have found a destination like 0.0.0.0/24, this is not a
// default gateway route.
has_destination = true;
}
has_destination = (c == 0);
break;
}
case RTA_OIF:
/* The output interface index. */
temp_idx = *static_cast<int *>(RTA_DATA(attr));
temp_idx = *static_cast<int*>(RTA_DATA(attr));
break;
case RTA_PRIORITY:
priority = *(uint32_t *)RTA_DATA(attr);
priority = *(uint32_t*)RTA_DATA(attr);
break;
default:
break;
@@ -826,18 +868,18 @@ void waybar::modules::Network::askForStateDump(void) {
}
}
int waybar::modules::Network::handleEventsDone(struct nl_msg *msg, void *data) {
auto net = static_cast<waybar::modules::Network *>(data);
int waybar::modules::Network::handleEventsDone(struct nl_msg* msg, void* data) {
auto net = static_cast<waybar::modules::Network*>(data);
net->dump_in_progress_ = false;
net->askForStateDump();
return NL_OK;
}
int waybar::modules::Network::handleScan(struct nl_msg *msg, void *data) {
auto net = static_cast<waybar::modules::Network *>(data);
auto gnlh = static_cast<genlmsghdr *>(nlmsg_data(nlmsg_hdr(msg)));
struct nlattr *tb[NL80211_ATTR_MAX + 1];
struct nlattr *bss[NL80211_BSS_MAX + 1];
int waybar::modules::Network::handleScan(struct nl_msg* msg, void* data) {
auto net = static_cast<waybar::modules::Network*>(data);
auto gnlh = static_cast<genlmsghdr*>(nlmsg_data(nlmsg_hdr(msg)));
struct nlattr* tb[NL80211_ATTR_MAX + 1];
struct nlattr* bss[NL80211_BSS_MAX + 1];
struct nla_policy bss_policy[NL80211_BSS_MAX + 1]{};
bss_policy[NL80211_BSS_TSF].type = NLA_U64;
bss_policy[NL80211_BSS_FREQUENCY].type = NLA_U32;
@@ -869,9 +911,9 @@ int waybar::modules::Network::handleScan(struct nl_msg *msg, void *data) {
return NL_OK;
}
void waybar::modules::Network::parseEssid(struct nlattr **bss) {
void waybar::modules::Network::parseEssid(struct nlattr** bss) {
if (bss[NL80211_BSS_INFORMATION_ELEMENTS] != nullptr) {
auto ies = static_cast<char *>(nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS]));
auto ies = static_cast<char*>(nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS]));
auto ies_len = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
const auto hdr_len = 2;
while (ies_len > hdr_len && ies[0] != 0) {
@@ -888,7 +930,7 @@ void waybar::modules::Network::parseEssid(struct nlattr **bss) {
}
}
void waybar::modules::Network::parseSignal(struct nlattr **bss) {
void waybar::modules::Network::parseSignal(struct nlattr** bss) {
if (bss[NL80211_BSS_SIGNAL_MBM] != nullptr) {
// signalstrength in dBm from mBm
signal_strength_dbm_ = nla_get_s32(bss[NL80211_BSS_SIGNAL_MBM]) / 100;
@@ -924,16 +966,16 @@ void waybar::modules::Network::parseSignal(struct nlattr **bss) {
}
}
void waybar::modules::Network::parseFreq(struct nlattr **bss) {
void waybar::modules::Network::parseFreq(struct nlattr** bss) {
if (bss[NL80211_BSS_FREQUENCY] != nullptr) {
// in GHz
frequency_ = (double)nla_get_u32(bss[NL80211_BSS_FREQUENCY]) / 1000;
}
}
void waybar::modules::Network::parseBssid(struct nlattr **bss) {
void waybar::modules::Network::parseBssid(struct nlattr** bss) {
if (bss[NL80211_BSS_BSSID] != nullptr) {
auto bssid = static_cast<uint8_t *>(nla_data(bss[NL80211_BSS_BSSID]));
auto bssid = static_cast<uint8_t*>(nla_data(bss[NL80211_BSS_BSSID]));
auto bssid_len = nla_len(bss[NL80211_BSS_BSSID]);
if (bssid_len == 6) {
bssid_ = fmt::format("{:x}:{:x}:{:x}:{:x}:{:x}:{:x}", bssid[0], bssid[1], bssid[2], bssid[3],
@@ -942,7 +984,7 @@ void waybar::modules::Network::parseBssid(struct nlattr **bss) {
}
}
bool waybar::modules::Network::associatedOrJoined(struct nlattr **bss) {
bool waybar::modules::Network::associatedOrJoined(struct nlattr** bss) {
if (bss[NL80211_BSS_STATUS] == nullptr) {
return false;
}
@@ -958,7 +1000,7 @@ bool waybar::modules::Network::associatedOrJoined(struct nlattr **bss) {
}
auto waybar::modules::Network::getInfo() -> void {
struct nl_msg *nl_msg = nlmsg_alloc();
struct nl_msg* nl_msg = nlmsg_alloc();
if (nl_msg == nullptr) {
return;
}
+49 -56
View File
@@ -17,19 +17,21 @@
#include "giomm/dataoutputstream.h"
#include "giomm/unixinputstream.h"
#include "giomm/unixoutputstream.h"
#include "util/scoped_fd.hpp"
namespace waybar::modules::niri {
IPC::IPC() { startIPC(); }
int IPC::connectToSocket() {
const char *socket_path = getenv("NIRI_SOCKET");
const char* socket_path = getenv("NIRI_SOCKET");
if (socket_path == nullptr) {
spdlog::warn("Niri is not running, niri IPC will not be available.");
return -1;
throw std::runtime_error("Niri IPC: NIRI_SOCKET was not set! (Is Niri running?)");
}
struct sockaddr_un addr;
int socketfd = socket(AF_UNIX, SOCK_STREAM, 0);
util::ScopedFd socketfd(socket(AF_UNIX, SOCK_STREAM, 0));
if (socketfd == -1) {
throw std::runtime_error("socketfd failed");
@@ -43,27 +45,19 @@ int IPC::connectToSocket() {
int l = sizeof(struct sockaddr_un);
if (connect(socketfd, (struct sockaddr *)&addr, l) == -1) {
close(socketfd);
if (connect(socketfd, (struct sockaddr*)&addr, l) == -1) {
throw std::runtime_error("unable to connect");
}
return socketfd;
return socketfd.release();
}
void IPC::startIPC() {
// will start IPC and relay events to parseIPC
std::thread([&]() {
int socketfd;
try {
socketfd = connectToSocket();
} catch (std::exception &e) {
spdlog::error("Niri IPC: failed to start, reason: {}", e.what());
return;
}
if (socketfd == -1) return;
int socketfd = connectToSocket();
std::thread([this, socketfd]() {
spdlog::info("Niri IPC starting");
auto unix_istream = Gio::UnixInputStream::create(socketfd, true);
@@ -87,7 +81,7 @@ void IPC::startIPC() {
try {
parseIPC(line);
} catch (std::exception &e) {
} catch (std::exception& e) {
spdlog::warn("Failed to parse IPC message: {}, reason: {}", line, e.what());
} catch (...) {
throw;
@@ -98,7 +92,7 @@ void IPC::startIPC() {
}).detach();
}
void IPC::parseIPC(const std::string &line) {
void IPC::parseIPC(const std::string& line) {
const auto ev = parser_.parse(line);
const auto members = ev.getMemberNames();
if (members.size() != 1) throw std::runtime_error("Event must have a single member");
@@ -106,28 +100,28 @@ void IPC::parseIPC(const std::string &line) {
{
auto lock = lockData();
if (const auto &payload = ev["WorkspacesChanged"]) {
if (const auto& payload = ev["WorkspacesChanged"]) {
workspaces_.clear();
const auto &values = payload["workspaces"];
const auto& values = payload["workspaces"];
std::copy(values.begin(), values.end(), std::back_inserter(workspaces_));
std::sort(workspaces_.begin(), workspaces_.end(), [](const auto &a, const auto &b) {
const auto &aOutput = a["output"].asString();
const auto &bOutput = b["output"].asString();
std::sort(workspaces_.begin(), workspaces_.end(), [](const auto& a, const auto& b) {
const auto& aOutput = a["output"].asString();
const auto& bOutput = b["output"].asString();
const auto aIdx = a["idx"].asUInt();
const auto bIdx = b["idx"].asUInt();
if (aOutput == bOutput) return aIdx < bIdx;
return aOutput < bOutput;
});
} else if (const auto &payload = ev["WorkspaceActivated"]) {
} else if (const auto& payload = ev["WorkspaceActivated"]) {
const auto id = payload["id"].asUInt64();
const auto focused = payload["focused"].asBool();
auto it = std::find_if(workspaces_.begin(), workspaces_.end(),
[id](const auto &ws) { return ws["id"].asUInt64() == id; });
[id](const auto& ws) { return ws["id"].asUInt64() == id; });
if (it != workspaces_.end()) {
const auto &ws = *it;
const auto &output = ws["output"].asString();
for (auto &ws : workspaces_) {
const auto& ws = *it;
const auto& output = ws["output"].asString();
for (auto& ws : workspaces_) {
const auto got_activated = (ws["id"].asUInt64() == id);
if (ws["output"] == output) ws["is_active"] = got_activated;
@@ -136,70 +130,70 @@ void IPC::parseIPC(const std::string &line) {
} else {
spdlog::error("Activated unknown workspace");
}
} else if (const auto &payload = ev["WorkspaceActiveWindowChanged"]) {
} else if (const auto& payload = ev["WorkspaceActiveWindowChanged"]) {
const auto workspaceId = payload["workspace_id"].asUInt64();
auto it = std::find_if(workspaces_.begin(), workspaces_.end(), [workspaceId](const auto &ws) {
auto it = std::find_if(workspaces_.begin(), workspaces_.end(), [workspaceId](const auto& ws) {
return ws["id"].asUInt64() == workspaceId;
});
if (it != workspaces_.end()) {
auto &ws = *it;
auto& ws = *it;
ws["active_window_id"] = payload["active_window_id"];
} else {
spdlog::error("Active window changed on unknown workspace");
}
} else if (const auto &payload = ev["WorkspaceUrgencyChanged"]) {
} else if (const auto& payload = ev["WorkspaceUrgencyChanged"]) {
const auto id = payload["id"].asUInt64();
const auto urgent = payload["urgent"].asBool();
auto it = std::find_if(workspaces_.begin(), workspaces_.end(),
[id](const auto &ws) { return ws["id"].asUInt64() == id; });
[id](const auto& ws) { return ws["id"].asUInt64() == id; });
if (it != workspaces_.end()) {
auto &ws = *it;
auto& ws = *it;
ws["is_urgent"] = urgent;
} else {
spdlog::error("Urgency changed for unknown workspace");
}
} else if (const auto &payload = ev["KeyboardLayoutsChanged"]) {
const auto &layouts = payload["keyboard_layouts"];
const auto &names = layouts["names"];
} else if (const auto& payload = ev["KeyboardLayoutsChanged"]) {
const auto& layouts = payload["keyboard_layouts"];
const auto& names = layouts["names"];
keyboardLayoutCurrent_ = layouts["current_idx"].asUInt();
keyboardLayoutNames_.clear();
for (const auto &fullName : names) keyboardLayoutNames_.push_back(fullName.asString());
} else if (const auto &payload = ev["KeyboardLayoutSwitched"]) {
for (const auto& fullName : names) keyboardLayoutNames_.push_back(fullName.asString());
} else if (const auto& payload = ev["KeyboardLayoutSwitched"]) {
keyboardLayoutCurrent_ = payload["idx"].asUInt();
} else if (const auto &payload = ev["WindowsChanged"]) {
} else if (const auto& payload = ev["WindowsChanged"]) {
windows_.clear();
const auto &values = payload["windows"];
const auto& values = payload["windows"];
std::copy(values.begin(), values.end(), std::back_inserter(windows_));
} else if (const auto &payload = ev["WindowOpenedOrChanged"]) {
const auto &window = payload["window"];
} else if (const auto& payload = ev["WindowOpenedOrChanged"]) {
const auto& window = payload["window"];
const auto id = window["id"].asUInt64();
auto it = std::find_if(windows_.begin(), windows_.end(),
[id](const auto &win) { return win["id"].asUInt64() == id; });
[id](const auto& win) { return win["id"].asUInt64() == id; });
if (it == windows_.end()) {
windows_.push_back(window);
if (window["is_focused"].asBool()) {
for (auto &win : windows_) {
for (auto& win : windows_) {
win["is_focused"] = win["id"].asUInt64() == id;
}
}
} else {
*it = window;
}
} else if (const auto &payload = ev["WindowClosed"]) {
} else if (const auto& payload = ev["WindowClosed"]) {
const auto id = payload["id"].asUInt64();
auto it = std::find_if(windows_.begin(), windows_.end(),
[id](const auto &win) { return win["id"].asUInt64() == id; });
[id](const auto& win) { return win["id"].asUInt64() == id; });
if (it != windows_.end()) {
windows_.erase(it);
} else {
spdlog::error("Unknown window closed");
}
} else if (const auto &payload = ev["WindowFocusChanged"]) {
} else if (const auto& payload = ev["WindowFocusChanged"]) {
const auto focused = !payload["id"].isNull();
const auto id = payload["id"].asUInt64();
for (auto &win : windows_) {
for (auto& win : windows_) {
win["is_focused"] = focused && win["id"].asUInt64() == id;
}
}
@@ -207,14 +201,14 @@ void IPC::parseIPC(const std::string &line) {
std::unique_lock lock(callbackMutex_);
for (auto &[eventname, handler] : callbacks_) {
for (auto& [eventname, handler] : callbacks_) {
if (eventname == members[0]) {
handler->onEvent(ev);
}
}
}
void IPC::registerForIPC(const std::string &ev, EventHandler *ev_handler) {
void IPC::registerForIPC(const std::string& ev, EventHandler* ev_handler) {
if (ev_handler == nullptr) {
return;
}
@@ -223,7 +217,7 @@ void IPC::registerForIPC(const std::string &ev, EventHandler *ev_handler) {
callbacks_.emplace_back(ev, ev_handler);
}
void IPC::unregisterForIPC(EventHandler *ev_handler) {
void IPC::unregisterForIPC(EventHandler* ev_handler) {
if (ev_handler == nullptr) {
return;
}
@@ -231,7 +225,7 @@ void IPC::unregisterForIPC(EventHandler *ev_handler) {
std::unique_lock lock(callbackMutex_);
for (auto it = callbacks_.begin(); it != callbacks_.end();) {
auto &[eventname, handler] = *it;
auto& [eventname, handler] = *it;
if (handler == ev_handler) {
it = callbacks_.erase(it);
} else {
@@ -240,9 +234,8 @@ void IPC::unregisterForIPC(EventHandler *ev_handler) {
}
}
Json::Value IPC::send(const Json::Value &request) {
int socketfd = connectToSocket();
if (socketfd == -1) throw std::runtime_error("Niri is not running");
Json::Value IPC::send(const Json::Value& request) {
util::ScopedFd socketfd(connectToSocket());
auto unix_istream = Gio::UnixInputStream::create(socketfd, true);
auto unix_ostream = Gio::UnixOutputStream::create(socketfd, false);
+11 -10
View File
@@ -8,7 +8,7 @@
namespace waybar::modules::niri {
Language::Language(const std::string &id, const Bar &bar, const Json::Value &config)
Language::Language(const std::string& id, const Bar& bar, const Json::Value& config)
: ALabel(config, "language", id, "{}", 0, false), bar_(bar) {
label_.hide();
@@ -32,7 +32,8 @@ void Language::updateFromIPC() {
auto ipcLock = gIPC->lockData();
layouts_.clear();
for (const auto &fullName : gIPC->keyboardLayoutNames()) layouts_.push_back(getLayout(fullName));
layouts_.reserve(gIPC->keyboardLayoutNames().size());
for (const auto& fullName : gIPC->keyboardLayoutNames()) layouts_.push_back(getLayout(fullName));
current_idx_ = gIPC->keyboardLayoutCurrent();
}
@@ -51,7 +52,7 @@ void Language::doUpdate() {
label_.hide();
return;
}
const auto &layout = layouts_[current_idx_];
const auto& layout = layouts_[current_idx_];
spdlog::debug("niri language update with full name {}", layout.full_name);
spdlog::debug("niri language update with short name {}", layout.short_name);
@@ -84,7 +85,7 @@ void Language::doUpdate() {
spdlog::debug("niri language formatted layout name {}", layoutName);
if (!format_.empty()) {
if (!layoutName.empty()) {
label_.show();
label_.set_markup(layoutName);
} else {
@@ -97,7 +98,7 @@ void Language::update() {
ALabel::update();
}
void Language::onEvent(const Json::Value &ev) {
void Language::onEvent(const Json::Value& ev) {
if (ev["KeyboardLayoutsChanged"]) {
updateFromIPC();
} else if (ev["KeyboardLayoutSwitched"]) {
@@ -109,11 +110,11 @@ void Language::onEvent(const Json::Value &ev) {
dp.emit();
}
Language::Layout Language::getLayout(const std::string &fullName) {
auto *const context = rxkb_context_new(RXKB_CONTEXT_LOAD_EXOTIC_RULES);
Language::Layout Language::getLayout(const std::string& fullName) {
auto* const context = rxkb_context_new(RXKB_CONTEXT_LOAD_EXOTIC_RULES);
rxkb_context_parse_default_ruleset(context);
rxkb_layout *layout = rxkb_layout_first(context);
rxkb_layout* layout = rxkb_layout_first(context);
while (layout != nullptr) {
std::string nameOfLayout = rxkb_layout_get_description(layout);
@@ -123,10 +124,10 @@ Language::Layout Language::getLayout(const std::string &fullName) {
}
auto name = std::string(rxkb_layout_get_name(layout));
const auto *variantPtr = rxkb_layout_get_variant(layout);
const auto* variantPtr = rxkb_layout_get_variant(layout);
std::string variant = variantPtr == nullptr ? "" : std::string(variantPtr);
const auto *descriptionPtr = rxkb_layout_get_brief(layout);
const auto* descriptionPtr = rxkb_layout_get_brief(layout);
std::string description = descriptionPtr == nullptr ? "" : std::string(descriptionPtr);
Layout info = Layout{nameOfLayout, name, variant, description};
+10 -10
View File
@@ -9,7 +9,7 @@
namespace waybar::modules::niri {
Window::Window(const std::string &id, const Bar &bar, const Json::Value &config)
Window::Window(const std::string& id, const Bar& bar, const Json::Value& config)
: AAppIconLabel(config, "window", id, "{title}", 0, true), bar_(bar) {
if (!gIPC) gIPC = std::make_unique<IPC>();
@@ -23,16 +23,16 @@ Window::Window(const std::string &id, const Bar &bar, const Json::Value &config)
Window::~Window() { gIPC->unregisterForIPC(this); }
void Window::onEvent(const Json::Value &ev) { dp.emit(); }
void Window::onEvent(const Json::Value& ev) { dp.emit(); }
void Window::doUpdate() {
auto ipcLock = gIPC->lockData();
const auto &windows = gIPC->windows();
const auto &workspaces = gIPC->workspaces();
const auto& windows = gIPC->windows();
const auto& workspaces = gIPC->workspaces();
const auto separateOutputs = config_["separate-outputs"].asBool();
const auto ws_it = std::find_if(workspaces.cbegin(), workspaces.cend(), [&](const auto &ws) {
const auto ws_it = std::find_if(workspaces.cbegin(), workspaces.cend(), [&](const auto& ws) {
if (separateOutputs) {
return ws["is_active"].asBool() && ws["output"].asString() == bar_.output->name;
}
@@ -46,13 +46,13 @@ void Window::doUpdate() {
} else {
const auto id = (*ws_it)["active_window_id"].asUInt64();
it = std::find_if(windows.cbegin(), windows.cend(),
[id](const auto &win) { return win["id"].asUInt64() == id; });
[id](const auto& win) { return win["id"].asUInt64() == id; });
}
setClass("empty", ws_it == workspaces.cend() || (*ws_it)["active_window_id"].isNull());
if (it != windows.cend()) {
const auto &window = *it;
const auto& window = *it;
const auto title = window["title"].asString();
const auto appId = window["app_id"].asString();
@@ -67,11 +67,11 @@ void Window::doUpdate() {
updateAppIconName(appId, "");
if (tooltipEnabled()) label_.set_tooltip_text(title);
if (tooltipEnabled()) label_.set_tooltip_markup(title);
const auto id = window["id"].asUInt64();
const auto workspaceId = window["workspace_id"].asUInt64();
const auto isSolo = std::none_of(windows.cbegin(), windows.cend(), [&](const auto &win) {
const auto isSolo = std::none_of(windows.cbegin(), windows.cend(), [&](const auto& win) {
return win["id"].asUInt64() != id && win["workspace_id"].asUInt64() == workspaceId;
});
setClass("solo", isSolo);
@@ -95,7 +95,7 @@ void Window::update() {
AAppIconLabel::update();
}
void Window::setClass(const std::string &className, bool enable) {
void Window::setClass(const std::string& className, bool enable) {
auto styleContext = bar_.window.get_style_context();
if (enable) {
if (!styleContext->has_class(className)) {
+29 -22
View File
@@ -6,7 +6,7 @@
namespace waybar::modules::niri {
Workspaces::Workspaces(const std::string &id, const Bar &bar, const Json::Value &config)
Workspaces::Workspaces(const std::string& id, const Bar& bar, const Json::Value& config)
: AModule(config, "workspaces", id, false, false), bar_(bar), box_(bar.orientation, 0) {
box_.set_name("workspaces");
if (!id.empty()) {
@@ -27,16 +27,16 @@ Workspaces::Workspaces(const std::string &id, const Bar &bar, const Json::Value
Workspaces::~Workspaces() { gIPC->unregisterForIPC(this); }
void Workspaces::onEvent(const Json::Value &ev) { dp.emit(); }
void Workspaces::onEvent(const Json::Value& ev) { dp.emit(); }
void Workspaces::doUpdate() {
auto ipcLock = gIPC->lockData();
const auto alloutputs = config_["all-outputs"].asBool();
std::vector<Json::Value> my_workspaces;
const auto &workspaces = gIPC->workspaces();
const auto& workspaces = gIPC->workspaces();
std::copy_if(workspaces.cbegin(), workspaces.cend(), std::back_inserter(my_workspaces),
[&](const auto &ws) {
[&](const auto& ws) {
if (alloutputs) return true;
return ws["output"].asString() == bar_.output->name;
});
@@ -44,7 +44,7 @@ void Workspaces::doUpdate() {
// Remove buttons for removed workspaces.
for (auto it = buttons_.begin(); it != buttons_.end();) {
auto ws = std::find_if(my_workspaces.begin(), my_workspaces.end(),
[it](const auto &ws) { return ws["id"].asUInt64() == it->first; });
[it](const auto& ws) { return ws["id"].asUInt64() == it->first; });
if (ws == my_workspaces.end()) {
it = buttons_.erase(it);
} else {
@@ -53,9 +53,9 @@ void Workspaces::doUpdate() {
}
// Add buttons for new workspaces, update existing ones.
for (const auto &ws : my_workspaces) {
for (const auto& ws : my_workspaces) {
auto bit = buttons_.find(ws["id"].asUInt64());
auto &button = bit == buttons_.end() ? addButton(ws) : bit->second;
auto& button = bit == buttons_.end() ? addButton(ws) : bit->second;
auto style_context = button.get_style_context();
if (ws["is_focused"].asBool())
@@ -103,17 +103,24 @@ void Workspaces::doUpdate() {
fmt::arg("output", ws["output"].asString()));
}
if (!config_["disable-markup"].asBool()) {
static_cast<Gtk::Label *>(button.get_children()[0])->set_markup(name);
auto* child = gtk_bin_get_child(GTK_BIN(button.gobj()));
if (child != nullptr && GTK_IS_LABEL(child))
gtk_label_set_markup(GTK_LABEL(child), name.c_str());
} else {
button.set_label(name);
}
if (config_["current-only"].asBool()) {
const auto *property = alloutputs ? "is_focused" : "is_active";
const auto* property = alloutputs ? "is_focused" : "is_active";
if (ws[property].asBool())
button.show();
else
button.hide();
} else if (config_["hide-empty"].asBool()) {
if (ws["active_window_id"].isNull() && !ws["is_focused"].asBool())
button.hide();
else
button.show();
} else {
button.show();
}
@@ -121,12 +128,12 @@ void Workspaces::doUpdate() {
// Refresh the button order.
for (auto it = my_workspaces.cbegin(); it != my_workspaces.cend(); ++it) {
const auto &ws = *it;
const auto& ws = *it;
auto pos = ws["idx"].asUInt() - 1;
if (alloutputs) pos = it - my_workspaces.cbegin();
auto &button = buttons_[ws["id"].asUInt64()];
auto& button = buttons_[ws["id"].asUInt64()];
box_.reorder_child(button, pos);
}
}
@@ -136,7 +143,7 @@ void Workspaces::update() {
AModule::update();
}
Gtk::Button &Workspaces::addButton(const Json::Value &ws) {
Gtk::Button& Workspaces::addButton(const Json::Value& ws) {
std::string name;
if (ws["name"]) {
name = ws["name"].asString();
@@ -145,7 +152,7 @@ Gtk::Button &Workspaces::addButton(const Json::Value &ws) {
}
auto pair = buttons_.emplace(ws["id"].asUInt64(), name);
auto &&button = pair.first->second;
auto&& button = pair.first->second;
box_.pack_start(button, false, false, 0);
button.set_relief(Gtk::RELIEF_NONE);
if (!config_["disable-click"].asBool()) {
@@ -154,13 +161,13 @@ Gtk::Button &Workspaces::addButton(const Json::Value &ws) {
try {
// {"Action":{"FocusWorkspace":{"reference":{"Id":1}}}}
Json::Value request(Json::objectValue);
auto &action = (request["Action"] = Json::Value(Json::objectValue));
auto &focusWorkspace = (action["FocusWorkspace"] = Json::Value(Json::objectValue));
auto &reference = (focusWorkspace["reference"] = Json::Value(Json::objectValue));
auto& action = (request["Action"] = Json::Value(Json::objectValue));
auto& focusWorkspace = (action["FocusWorkspace"] = Json::Value(Json::objectValue));
auto& reference = (focusWorkspace["reference"] = Json::Value(Json::objectValue));
reference["Id"] = id;
IPC::send(request);
} catch (const std::exception &e) {
} catch (const std::exception& e) {
spdlog::error("Error switching workspace: {}", e.what());
}
});
@@ -168,20 +175,20 @@ Gtk::Button &Workspaces::addButton(const Json::Value &ws) {
return button;
}
std::string Workspaces::getIcon(const std::string &value, const Json::Value &ws) {
const auto &icons = config_["format-icons"];
std::string Workspaces::getIcon(const std::string& value, const Json::Value& ws) {
const auto& icons = config_["format-icons"];
if (!icons) return value;
if (ws["is_urgent"].asBool() && icons["urgent"]) return icons["urgent"].asString();
if (ws["active_window_id"].isNull() && icons["empty"]) return icons["empty"].asString();
if (ws["is_active"].asBool() && icons["active"]) return icons["active"].asString();
if (ws["is_focused"].asBool() && icons["focused"]) return icons["focused"].asString();
if (ws["is_active"].asBool() && icons["active"]) return icons["active"].asString();
if (ws["active_window_id"].isNull() && icons["empty"]) return icons["empty"].asString();
if (ws["name"]) {
const auto &name = ws["name"].asString();
const auto& name = ws["name"].asString();
if (icons[name]) return icons[name].asString();
}
+5 -1
View File
@@ -157,7 +157,7 @@ auto PowerProfilesDaemon::update() -> void {
store.push_back(fmt::arg("icon", getIcon(0, profile.name)));
label_.set_markup(fmt::vformat(format_, store));
if (tooltipEnabled()) {
label_.set_tooltip_text(fmt::vformat(tooltipFormat_, store));
label_.set_tooltip_markup(fmt::vformat(tooltipFormat_, store));
}
// Set CSS class
@@ -176,6 +176,10 @@ auto PowerProfilesDaemon::update() -> void {
bool PowerProfilesDaemon::handleToggle(GdkEventButton* const& e) {
if (e->type == GdkEventType::GDK_BUTTON_PRESS && connected_) {
if (availableProfiles_.empty()) return true;
if (activeProfile_ == availableProfiles_.end()) {
activeProfile_ = availableProfiles_.begin();
}
if (e->button == 1) /* left click */ {
activeProfile_++;
if (activeProfile_ == availableProfiles_.end()) {
+2 -3
View File
@@ -71,6 +71,7 @@ Privacy::Privacy(const std::string& id, const Json::Value& config, Gtk::Orientat
auto* item = Gtk::make_managed<PrivacyItem>(module, nodeType, nodePtr, orientation, pos,
iconSize, transition_duration);
box_.add(*item);
modules_.push_back(item);
}
}
@@ -148,9 +149,7 @@ auto Privacy::update() -> void {
bool useAudioOut = false;
mutex_.lock();
for (Gtk::Widget* widget : box_.get_children()) {
auto* module = dynamic_cast<PrivacyItem*>(widget);
if (module == nullptr) continue;
for (PrivacyItem* module : modules_) {
switch (module->privacy_type) {
case util::PipewireBackend::PRIVACY_NODE_TYPE_VIDEO_INPUT:
setScreenshare = true;
+9 -9
View File
@@ -12,9 +12,9 @@
namespace waybar::modules::privacy {
PrivacyItem::PrivacyItem(const Json::Value &config_, enum PrivacyNodeType privacy_type_,
std::list<PrivacyNodeInfo *> *nodes_, Gtk::Orientation orientation,
const std::string &pos, const uint icon_size,
PrivacyItem::PrivacyItem(const Json::Value& config_, enum PrivacyNodeType privacy_type_,
std::list<PrivacyNodeInfo*>* nodes_, Gtk::Orientation orientation,
const std::string& pos, const uint icon_size,
const uint transition_duration)
: Gtk::Revealer(),
privacy_type(privacy_type_),
@@ -83,7 +83,7 @@ PrivacyItem::PrivacyItem(const Json::Value &config_, enum PrivacyNodeType privac
// Sets the window to use when showing the tooltip
update_tooltip();
this->signal_query_tooltip().connect(sigc::track_obj(
[this](int x, int y, bool keyboard_tooltip, const Glib::RefPtr<Gtk::Tooltip> &tooltip) {
[this](int x, int y, bool keyboard_tooltip, const Glib::RefPtr<Gtk::Tooltip>& tooltip) {
tooltip->set_custom(tooltip_window);
return true;
},
@@ -97,23 +97,23 @@ PrivacyItem::PrivacyItem(const Json::Value &config_, enum PrivacyNodeType privac
void PrivacyItem::update_tooltip() {
// Removes all old nodes
for (auto *child : tooltip_window.get_children()) {
for (auto* child : tooltip_window.get_children()) {
tooltip_window.remove(*child);
// despite the remove, still needs a delete to prevent memory leak. Speculating that this might
// work differently in GTK4.
delete child;
}
for (auto *node : *nodes) {
auto *box = Gtk::make_managed<Gtk::Box>(Gtk::ORIENTATION_HORIZONTAL, 4);
for (auto* node : *nodes) {
auto* box = Gtk::make_managed<Gtk::Box>(Gtk::ORIENTATION_HORIZONTAL, 4);
// Set device icon
auto *node_icon = Gtk::make_managed<Gtk::Image>();
auto* node_icon = Gtk::make_managed<Gtk::Image>();
node_icon->set_pixel_size(tooltipIconSize);
node_icon->set_from_icon_name(node->getIconName(), Gtk::ICON_SIZE_INVALID);
box->add(*node_icon);
// Set model
auto *nodeName = Gtk::make_managed<Gtk::Label>(node->getName());
auto* nodeName = Gtk::make_managed<Gtk::Label>(node->getName());
box->add(*nodeName);
tooltip_window.add(*box);
+4 -4
View File
@@ -1,6 +1,6 @@
#include "modules/pulseaudio.hpp"
waybar::modules::Pulseaudio::Pulseaudio(const std::string &id, const Json::Value &config)
waybar::modules::Pulseaudio::Pulseaudio(const std::string& id, const Json::Value& config)
: ALabel(config, "pulseaudio", id, "{volume}%") {
event_box_.add_events(Gdk::SCROLL_MASK | Gdk::SMOOTH_SCROLL_MASK);
event_box_.signal_scroll_event().connect(sigc::mem_fun(*this, &Pulseaudio::handleScroll));
@@ -9,7 +9,7 @@ waybar::modules::Pulseaudio::Pulseaudio(const std::string &id, const Json::Value
backend->setIgnoredSinks(config_["ignored-sinks"]);
}
bool waybar::modules::Pulseaudio::handleScroll(GdkEventScroll *e) {
bool waybar::modules::Pulseaudio::handleScroll(GdkEventScroll* e) {
// change the pulse volume only when no user provided
// events are configured
if (config_["on-scroll-up"].isString() || config_["on-scroll-down"].isString()) {
@@ -51,7 +51,7 @@ const std::vector<std::string> waybar::modules::Pulseaudio::getPulseIcon() const
res.push_back(backend->getDefaultSourceName());
std::string nameLC = backend->getSinkPortName() + backend->getFormFactor();
std::transform(nameLC.begin(), nameLC.end(), nameLC.begin(), ::tolower);
for (auto const &port : ports) {
for (auto const& port : ports) {
if (nameLC.find(port) != std::string::npos) {
if (sink_muted) {
res.emplace_back(port + "-muted");
@@ -138,7 +138,7 @@ auto waybar::modules::Pulseaudio::update() -> void {
fmt::arg("source_volume", source_volume), fmt::arg("source_desc", source_desc),
fmt::arg("icon", getIcon(sink_volume, getPulseIcon()))));
} else {
label_.set_tooltip_text(sink_desc);
label_.set_tooltip_markup(sink_desc);
}
}
+32 -54
View File
@@ -10,73 +10,51 @@ PulseaudioSlider::PulseaudioSlider(const std::string& id, const Json::Value& con
if (config_["target"].isString()) {
std::string target = config_["target"].asString();
if (target == "sink") {
this->target = PulseaudioSliderTarget::Sink;
this->target = util::PulseaudioTarget::Sink;
} else if (target == "source") {
this->target = PulseaudioSliderTarget::Source;
this->target = util::PulseaudioTarget::Source;
}
}
if (config_["zero-on-mute"].isBool()) {
zero_on_mute = config_["zero-on-mute"].asBool();
}
if (config_["unmute-on-volume-change"].isBool()) {
unmute_on_volume_change = config_["unmute-on-volume-change"].asBool();
}
}
void PulseaudioSlider::update() {
switch (target) {
case PulseaudioSliderTarget::Sink:
if (backend->getSinkMuted()) {
scale_.set_value(min_);
} else {
scale_.set_value(backend->getSinkVolume());
}
break;
uint16_t display_value = backend->getVolume(target);
bool is_muted = backend->getMuted(target);
case PulseaudioSliderTarget::Source:
if (backend->getSourceMuted()) {
scale_.set_value(min_);
} else {
scale_.set_value(backend->getSourceVolume());
}
break;
if (is_muted) {
if (zero_on_mute) {
display_value = min_;
}
if (!previously_muted) {
scale_.get_style_context()->add_class("muted");
}
} else if (previously_muted) {
scale_.get_style_context()->remove_class("muted");
}
scale_.set_value(display_value);
previously_muted = is_muted;
}
void PulseaudioSlider::onValueChanged() {
bool is_mute = false;
uint16_t slider_value = scale_.get_value();
switch (target) {
case PulseaudioSliderTarget::Sink:
if (backend->getSinkMuted()) {
is_mute = true;
}
break;
case PulseaudioSliderTarget::Source:
if (backend->getSourceMuted()) {
is_mute = true;
}
break;
}
uint16_t volume = scale_.get_value();
if (is_mute) {
// Avoid setting sink/source to volume 0 if the user muted if via another mean.
if (volume == 0) {
return;
}
// If the sink/source is mute, but the user clicked the slider, unmute it!
else {
switch (target) {
case PulseaudioSliderTarget::Sink:
backend->toggleSinkMute(false);
break;
case PulseaudioSliderTarget::Source:
backend->toggleSourceMute(false);
break;
}
// Avoid setting sink/source to volume 0 if the user muted it via other means.
if (!backend->getMuted(target) || slider_value != 0) {
if (unmute_on_volume_change) {
backend->unmute(target);
}
backend->changeVolume(slider_value, min_, max_);
}
backend->changeVolume(volume, min_, max_);
}
} // namespace waybar::modules
} // namespace waybar::modules
+33 -32
View File
@@ -7,48 +7,48 @@
namespace waybar::modules::river {
static void listen_focused_tags(void *data, struct zriver_output_status_v1 *zriver_output_status_v1,
static void listen_focused_tags(void* data, struct zriver_output_status_v1* zriver_output_status_v1,
uint32_t tags) {
// Intentionally empty
}
static void listen_view_tags(void *data, struct zriver_output_status_v1 *zriver_output_status_v1,
struct wl_array *tags) {
static void listen_view_tags(void* data, struct zriver_output_status_v1* zriver_output_status_v1,
struct wl_array* tags) {
// Intentionally empty
}
static void listen_urgent_tags(void *data, struct zriver_output_status_v1 *zriver_output_status_v1,
static void listen_urgent_tags(void* data, struct zriver_output_status_v1* zriver_output_status_v1,
uint32_t tags) {
// Intentionally empty
}
static void listen_layout_name(void *data, struct zriver_output_status_v1 *zriver_output_status_v1,
const char *layout) {
static_cast<Layout *>(data)->handle_name(layout);
static void listen_layout_name(void* data, struct zriver_output_status_v1* zriver_output_status_v1,
const char* layout) {
static_cast<Layout*>(data)->handle_name(layout);
}
static void listen_layout_name_clear(void *data,
struct zriver_output_status_v1 *zriver_output_status_v1) {
static_cast<Layout *>(data)->handle_clear();
static void listen_layout_name_clear(void* data,
struct zriver_output_status_v1* zriver_output_status_v1) {
static_cast<Layout*>(data)->handle_clear();
}
static void listen_focused_output(void *data, struct zriver_seat_status_v1 *zriver_seat_status_v1,
struct wl_output *output) {
static_cast<Layout *>(data)->handle_focused_output(output);
static void listen_focused_output(void* data, struct zriver_seat_status_v1* zriver_seat_status_v1,
struct wl_output* output) {
static_cast<Layout*>(data)->handle_focused_output(output);
}
static void listen_unfocused_output(void *data, struct zriver_seat_status_v1 *zriver_seat_status_v1,
struct wl_output *output) {
static_cast<Layout *>(data)->handle_unfocused_output(output);
static void listen_unfocused_output(void* data, struct zriver_seat_status_v1* zriver_seat_status_v1,
struct wl_output* output) {
static_cast<Layout*>(data)->handle_unfocused_output(output);
}
static void listen_focused_view(void *data, struct zriver_seat_status_v1 *zriver_seat_status_v1,
const char *title) {
static void listen_focused_view(void* data, struct zriver_seat_status_v1* zriver_seat_status_v1,
const char* title) {
// Intentionally empty
}
static void listen_mode(void *data, struct zriver_seat_status_v1 *zriver_seat_status_v1,
const char *mode) {
static void listen_mode(void* data, struct zriver_seat_status_v1* zriver_seat_status_v1,
const char* mode) {
// Intentionally empty
}
@@ -67,8 +67,8 @@ static const zriver_seat_status_v1_listener seat_status_listener_impl{
.mode = listen_mode,
};
static void handle_global(void *data, struct wl_registry *registry, uint32_t name,
const char *interface, uint32_t version) {
static void handle_global(void* data, struct wl_registry* registry, uint32_t name,
const char* interface, uint32_t version) {
if (std::strcmp(interface, zriver_status_manager_v1_interface.name) == 0) {
version = std::min<uint32_t>(version, 4);
@@ -80,32 +80,32 @@ static void handle_global(void *data, struct wl_registry *registry, uint32_t nam
std::to_string(version));
return;
}
static_cast<Layout *>(data)->status_manager_ = static_cast<struct zriver_status_manager_v1 *>(
static_cast<Layout*>(data)->status_manager_ = static_cast<struct zriver_status_manager_v1*>(
wl_registry_bind(registry, name, &zriver_status_manager_v1_interface, version));
}
if (std::strcmp(interface, wl_seat_interface.name) == 0) {
version = std::min<uint32_t>(version, 1);
static_cast<Layout *>(data)->seat_ = static_cast<struct wl_seat *>(
wl_registry_bind(registry, name, &wl_seat_interface, version));
static_cast<Layout*>(data)->seat_ =
static_cast<struct wl_seat*>(wl_registry_bind(registry, name, &wl_seat_interface, version));
}
}
static void handle_global_remove(void *data, struct wl_registry *registry, uint32_t name) {
static void handle_global_remove(void* data, struct wl_registry* registry, uint32_t name) {
// Nobody cares
}
static const wl_registry_listener registry_listener_impl = {.global = handle_global,
.global_remove = handle_global_remove};
Layout::Layout(const std::string &id, const waybar::Bar &bar, const Json::Value &config)
Layout::Layout(const std::string& id, const waybar::Bar& bar, const Json::Value& config)
: waybar::ALabel(config, "layout", id, "{}"),
status_manager_{nullptr},
seat_{nullptr},
bar_(bar),
output_status_{nullptr} {
struct wl_display *display = Client::inst()->wl_display;
struct wl_registry *registry = wl_display_get_registry(display);
struct wl_display* display = Client::inst()->wl_display;
struct wl_registry* registry = wl_display_get_registry(display);
wl_registry_add_listener(registry, &registry_listener_impl, this);
wl_display_roundtrip(display);
@@ -118,6 +118,7 @@ Layout::Layout(const std::string &id, const waybar::Bar &bar, const Json::Value
if (!seat_) {
spdlog::error("wl_seat not advertised");
return;
}
label_.hide();
@@ -141,7 +142,7 @@ Layout::~Layout() {
}
}
void Layout::handle_name(const char *name) {
void Layout::handle_name(const char* name) {
if (std::strcmp(name, "") == 0 || format_.empty()) {
label_.hide(); // hide empty labels or labels with empty format
} else {
@@ -162,7 +163,7 @@ void Layout::handle_clear() {
ALabel::update();
}
void Layout::handle_focused_output(struct wl_output *output) {
void Layout::handle_focused_output(struct wl_output* output) {
if (output_ == output) { // if we focused the output this bar belongs to
label_.get_style_context()->add_class("focused");
ALabel::update();
@@ -170,7 +171,7 @@ void Layout::handle_focused_output(struct wl_output *output) {
focused_output_ = output;
}
void Layout::handle_unfocused_output(struct wl_output *output) {
void Layout::handle_unfocused_output(struct wl_output* output) {
if (output_ == output) { // if we unfocused the output this bar belongs to
label_.get_style_context()->remove_class("focused");
ALabel::update();
+19 -18
View File
@@ -7,23 +7,23 @@
namespace waybar::modules::river {
static void listen_focused_output(void *data, struct zriver_seat_status_v1 *seat_status,
struct wl_output *output) {
static void listen_focused_output(void* data, struct zriver_seat_status_v1* seat_status,
struct wl_output* output) {
// Intentionally empty
}
static void listen_unfocused_output(void *data, struct zriver_seat_status_v1 *seat_status,
struct wl_output *output) {
static void listen_unfocused_output(void* data, struct zriver_seat_status_v1* seat_status,
struct wl_output* output) {
// Intentionally empty
}
static void listen_focused_view(void *data, struct zriver_seat_status_v1 *seat_status,
const char *title) {
static void listen_focused_view(void* data, struct zriver_seat_status_v1* seat_status,
const char* title) {
// Intentionally empty
}
static void listen_mode(void *data, struct zriver_seat_status_v1 *seat_status, const char *mode) {
static_cast<Mode *>(data)->handle_mode(mode);
static void listen_mode(void* data, struct zriver_seat_status_v1* seat_status, const char* mode) {
static_cast<Mode*>(data)->handle_mode(mode);
}
static const zriver_seat_status_v1_listener seat_status_listener_impl = {
@@ -33,8 +33,8 @@ static const zriver_seat_status_v1_listener seat_status_listener_impl = {
.mode = listen_mode,
};
static void handle_global(void *data, struct wl_registry *registry, uint32_t name,
const char *interface, uint32_t version) {
static void handle_global(void* data, struct wl_registry* registry, uint32_t name,
const char* interface, uint32_t version) {
if (std::strcmp(interface, zriver_status_manager_v1_interface.name) == 0) {
version = std::min<uint32_t>(version, 3);
if (version < ZRIVER_SEAT_STATUS_V1_MODE_SINCE_VERSION) {
@@ -42,31 +42,31 @@ static void handle_global(void *data, struct wl_registry *registry, uint32_t nam
"river server does not support the \"mode\" event; the module will be disabled");
return;
}
static_cast<Mode *>(data)->status_manager_ = static_cast<struct zriver_status_manager_v1 *>(
static_cast<Mode*>(data)->status_manager_ = static_cast<struct zriver_status_manager_v1*>(
wl_registry_bind(registry, name, &zriver_status_manager_v1_interface, version));
} else if (std::strcmp(interface, wl_seat_interface.name) == 0) {
version = std::min<uint32_t>(version, 1);
static_cast<Mode *>(data)->seat_ = static_cast<struct wl_seat *>(
wl_registry_bind(registry, name, &wl_seat_interface, version));
static_cast<Mode*>(data)->seat_ =
static_cast<struct wl_seat*>(wl_registry_bind(registry, name, &wl_seat_interface, version));
}
}
static void handle_global_remove(void *data, struct wl_registry *registry, uint32_t name) {
static void handle_global_remove(void* data, struct wl_registry* registry, uint32_t name) {
// Nobody cares
}
static const wl_registry_listener registry_listener_impl = {.global = handle_global,
.global_remove = handle_global_remove};
Mode::Mode(const std::string &id, const waybar::Bar &bar, const Json::Value &config)
Mode::Mode(const std::string& id, const waybar::Bar& bar, const Json::Value& config)
: waybar::ALabel(config, "mode", id, "{}"),
status_manager_{nullptr},
seat_{nullptr},
bar_(bar),
mode_{""},
seat_status_{nullptr} {
struct wl_display *display = Client::inst()->wl_display;
struct wl_registry *registry = wl_display_get_registry(display);
struct wl_display* display = Client::inst()->wl_display;
struct wl_registry* registry = wl_display_get_registry(display);
wl_registry_add_listener(registry, &registry_listener_impl, this);
wl_display_roundtrip(display);
@@ -77,6 +77,7 @@ Mode::Mode(const std::string &id, const waybar::Bar &bar, const Json::Value &con
if (!seat_) {
spdlog::error("wl_seat not advertised");
return;
}
label_.hide();
@@ -94,7 +95,7 @@ Mode::~Mode() {
}
}
void Mode::handle_mode(const char *mode) {
void Mode::handle_mode(const char* mode) {
if (format_.empty()) {
label_.hide();
} else {
+33 -30
View File
@@ -12,19 +12,19 @@
namespace waybar::modules::river {
static void listen_focused_tags(void *data, struct zriver_output_status_v1 *zriver_output_status_v1,
static void listen_focused_tags(void* data, struct zriver_output_status_v1* zriver_output_status_v1,
uint32_t tags) {
static_cast<Tags *>(data)->handle_focused_tags(tags);
static_cast<Tags*>(data)->handle_focused_tags(tags);
}
static void listen_view_tags(void *data, struct zriver_output_status_v1 *zriver_output_status_v1,
struct wl_array *tags) {
static_cast<Tags *>(data)->handle_view_tags(tags);
static void listen_view_tags(void* data, struct zriver_output_status_v1* zriver_output_status_v1,
struct wl_array* tags) {
static_cast<Tags*>(data)->handle_view_tags(tags);
}
static void listen_urgent_tags(void *data, struct zriver_output_status_v1 *zriver_output_status_v1,
static void listen_urgent_tags(void* data, struct zriver_output_status_v1* zriver_output_status_v1,
uint32_t tags) {
static_cast<Tags *>(data)->handle_urgent_tags(tags);
static_cast<Tags*>(data)->handle_urgent_tags(tags);
}
static const zriver_output_status_v1_listener output_status_listener_impl{
@@ -33,15 +33,15 @@ static const zriver_output_status_v1_listener output_status_listener_impl{
.urgent_tags = listen_urgent_tags,
};
static void listen_command_success(void *data,
struct zriver_command_callback_v1 *zriver_command_callback_v1,
const char *output) {
static void listen_command_success(void* data,
struct zriver_command_callback_v1* zriver_command_callback_v1,
const char* output) {
// Do nothing but keep listener to avoid crashing when command was successful
}
static void listen_command_failure(void *data,
struct zriver_command_callback_v1 *zriver_command_callback_v1,
const char *output) {
static void listen_command_failure(void* data,
struct zriver_command_callback_v1* zriver_command_callback_v1,
const char* output) {
spdlog::error("failure when selecting/toggling tags {}", output);
}
@@ -50,38 +50,38 @@ static const zriver_command_callback_v1_listener command_callback_listener_impl{
.failure = listen_command_failure,
};
static void handle_global(void *data, struct wl_registry *registry, uint32_t name,
const char *interface, uint32_t version) {
static void handle_global(void* data, struct wl_registry* registry, uint32_t name,
const char* interface, uint32_t version) {
if (std::strcmp(interface, zriver_status_manager_v1_interface.name) == 0) {
version = std::min(version, 2u);
if (version < ZRIVER_OUTPUT_STATUS_V1_URGENT_TAGS_SINCE_VERSION) {
spdlog::warn("river server does not support urgent tags");
}
static_cast<Tags *>(data)->status_manager_ = static_cast<struct zriver_status_manager_v1 *>(
static_cast<Tags*>(data)->status_manager_ = static_cast<struct zriver_status_manager_v1*>(
wl_registry_bind(registry, name, &zriver_status_manager_v1_interface, version));
}
if (std::strcmp(interface, zriver_control_v1_interface.name) == 0) {
version = std::min(version, 1u);
static_cast<Tags *>(data)->control_ = static_cast<struct zriver_control_v1 *>(
static_cast<Tags*>(data)->control_ = static_cast<struct zriver_control_v1*>(
wl_registry_bind(registry, name, &zriver_control_v1_interface, version));
}
if (std::strcmp(interface, wl_seat_interface.name) == 0) {
version = std::min(version, 1u);
static_cast<Tags *>(data)->seat_ = static_cast<struct wl_seat *>(
wl_registry_bind(registry, name, &wl_seat_interface, version));
static_cast<Tags*>(data)->seat_ =
static_cast<struct wl_seat*>(wl_registry_bind(registry, name, &wl_seat_interface, version));
}
}
static void handle_global_remove(void *data, struct wl_registry *registry, uint32_t name) {
static void handle_global_remove(void* data, struct wl_registry* registry, uint32_t name) {
/* Ignore event */
}
static const wl_registry_listener registry_listener_impl = {.global = handle_global,
.global_remove = handle_global_remove};
Tags::Tags(const std::string &id, const waybar::Bar &bar, const Json::Value &config)
Tags::Tags(const std::string& id, const waybar::Bar& bar, const Json::Value& config)
: waybar::AModule(config, "tags", id, false, false),
status_manager_{nullptr},
control_{nullptr},
@@ -89,8 +89,8 @@ Tags::Tags(const std::string &id, const waybar::Bar &bar, const Json::Value &con
bar_(bar),
box_{bar.orientation, 0},
output_status_{nullptr} {
struct wl_display *display = Client::inst()->wl_display;
struct wl_registry *registry = wl_display_get_registry(display);
struct wl_display* display = Client::inst()->wl_display;
struct wl_registry* registry = wl_display_get_registry(display);
wl_registry_add_listener(registry, &registry_listener_impl, this);
wl_display_roundtrip(display);
@@ -101,10 +101,12 @@ Tags::Tags(const std::string &id, const waybar::Bar &bar, const Json::Value &con
if (!control_) {
spdlog::error("river_control_v1 not advertised");
return;
}
if (!seat_) {
spdlog::error("wl_seat not advertised");
return;
}
box_.set_name("tags");
@@ -129,7 +131,7 @@ Tags::Tags(const std::string &id, const waybar::Bar &bar, const Json::Value &con
buttons_.emplace_back(std::to_string(tag + 1));
}
auto &button = buttons_[tag];
auto& button = buttons_[tag];
button.set_relief(Gtk::RELIEF_NONE);
box_.pack_start(button, false, false, 0);
@@ -168,7 +170,8 @@ Tags::~Tags() {
}
void Tags::handle_show() {
struct wl_output *output = gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj());
if (!status_manager_) return;
struct wl_output* output = gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj());
output_status_ = zriver_status_manager_v1_get_river_output_status(status_manager_, output);
zriver_output_status_v1_add_listener(output_status_, &output_status_listener_impl, this);
@@ -178,17 +181,17 @@ void Tags::handle_show() {
void Tags::handle_primary_clicked(uint32_t tag) {
// Send river command to select tag on left mouse click
zriver_command_callback_v1 *callback;
zriver_command_callback_v1* callback;
zriver_control_v1_add_argument(control_, "set-focused-tags");
zriver_control_v1_add_argument(control_, std::to_string(tag).c_str());
callback = zriver_control_v1_run_command(control_, seat_);
zriver_command_callback_v1_add_listener(callback, &command_callback_listener_impl, nullptr);
}
bool Tags::handle_button_press(GdkEventButton *event_button, uint32_t tag) {
bool Tags::handle_button_press(GdkEventButton* event_button, uint32_t tag) {
if (event_button->type == GDK_BUTTON_PRESS && event_button->button == 3) {
// Send river command to toggle tag on right mouse click
zriver_command_callback_v1 *callback;
zriver_command_callback_v1* callback;
zriver_control_v1_add_argument(control_, "toggle-focused-tags");
zriver_control_v1_add_argument(control_, std::to_string(tag).c_str());
callback = zriver_control_v1_run_command(control_, seat_);
@@ -217,9 +220,9 @@ void Tags::handle_focused_tags(uint32_t tags) {
}
}
void Tags::handle_view_tags(struct wl_array *view_tags) {
void Tags::handle_view_tags(struct wl_array* view_tags) {
uint32_t tags = 0;
auto view_tag = reinterpret_cast<uint32_t *>(view_tags->data);
auto view_tag = reinterpret_cast<uint32_t*>(view_tags->data);
auto end = view_tag + (view_tags->size / sizeof(uint32_t));
for (; view_tag < end; ++view_tag) {
tags |= *view_tag;
+24 -23
View File
@@ -9,23 +9,23 @@
namespace waybar::modules::river {
static void listen_focused_view(void *data, struct zriver_seat_status_v1 *zriver_seat_status_v1,
const char *title) {
static_cast<Window *>(data)->handle_focused_view(title);
static void listen_focused_view(void* data, struct zriver_seat_status_v1* zriver_seat_status_v1,
const char* title) {
static_cast<Window*>(data)->handle_focused_view(title);
}
static void listen_focused_output(void *data, struct zriver_seat_status_v1 *zriver_seat_status_v1,
struct wl_output *output) {
static_cast<Window *>(data)->handle_focused_output(output);
static void listen_focused_output(void* data, struct zriver_seat_status_v1* zriver_seat_status_v1,
struct wl_output* output) {
static_cast<Window*>(data)->handle_focused_output(output);
}
static void listen_unfocused_output(void *data, struct zriver_seat_status_v1 *zriver_seat_status_v1,
struct wl_output *output) {
static_cast<Window *>(data)->handle_unfocused_output(output);
static void listen_unfocused_output(void* data, struct zriver_seat_status_v1* zriver_seat_status_v1,
struct wl_output* output) {
static_cast<Window*>(data)->handle_unfocused_output(output);
}
static void listen_mode(void *data, struct zriver_seat_status_v1 *zriver_seat_status_v1,
const char *mode) {
static void listen_mode(void* data, struct zriver_seat_status_v1* zriver_seat_status_v1,
const char* mode) {
// This module doesn't care
}
@@ -36,36 +36,36 @@ static const zriver_seat_status_v1_listener seat_status_listener_impl{
.mode = listen_mode,
};
static void handle_global(void *data, struct wl_registry *registry, uint32_t name,
const char *interface, uint32_t version) {
static void handle_global(void* data, struct wl_registry* registry, uint32_t name,
const char* interface, uint32_t version) {
if (std::strcmp(interface, zriver_status_manager_v1_interface.name) == 0) {
version = std::min<uint32_t>(version, 2);
static_cast<Window *>(data)->status_manager_ = static_cast<struct zriver_status_manager_v1 *>(
static_cast<Window*>(data)->status_manager_ = static_cast<struct zriver_status_manager_v1*>(
wl_registry_bind(registry, name, &zriver_status_manager_v1_interface, version));
}
if (std::strcmp(interface, wl_seat_interface.name) == 0) {
version = std::min<uint32_t>(version, 1);
static_cast<Window *>(data)->seat_ = static_cast<struct wl_seat *>(
wl_registry_bind(registry, name, &wl_seat_interface, version));
static_cast<Window*>(data)->seat_ =
static_cast<struct wl_seat*>(wl_registry_bind(registry, name, &wl_seat_interface, version));
}
}
static void handle_global_remove(void *data, struct wl_registry *registry, uint32_t name) {
static void handle_global_remove(void* data, struct wl_registry* registry, uint32_t name) {
/* Ignore event */
}
static const wl_registry_listener registry_listener_impl = {.global = handle_global,
.global_remove = handle_global_remove};
Window::Window(const std::string &id, const waybar::Bar &bar, const Json::Value &config)
Window::Window(const std::string& id, const waybar::Bar& bar, const Json::Value& config)
: waybar::ALabel(config, "window", id, "{}", 30),
status_manager_{nullptr},
seat_{nullptr},
bar_(bar),
seat_status_{nullptr} {
struct wl_display *display = Client::inst()->wl_display;
struct wl_registry *registry = wl_display_get_registry(display);
struct wl_display* display = Client::inst()->wl_display;
struct wl_registry* registry = wl_display_get_registry(display);
wl_registry_add_listener(registry, &registry_listener_impl, this);
wl_display_roundtrip(display);
@@ -78,6 +78,7 @@ Window::Window(const std::string &id, const waybar::Bar &bar, const Json::Value
if (!seat_) {
spdlog::error("wl_seat not advertised");
return;
}
label_.hide(); // hide the label until populated
@@ -95,7 +96,7 @@ Window::~Window() {
}
}
void Window::handle_focused_view(const char *title) {
void Window::handle_focused_view(const char* title) {
// don't change the label on unfocused outputs.
// this makes the current output report its currently focused view, and unfocused outputs will
// report their last focused views. when freshly starting the bar, unfocused outputs don't have a
@@ -116,7 +117,7 @@ void Window::handle_focused_view(const char *title) {
ALabel::update();
}
void Window::handle_focused_output(struct wl_output *output) {
void Window::handle_focused_output(struct wl_output* output) {
if (output_ == output) { // if we focused the output this bar belongs to
label_.get_style_context()->add_class("focused");
ALabel::update();
@@ -124,7 +125,7 @@ void Window::handle_focused_output(struct wl_output *output) {
focused_output_ = output;
}
void Window::handle_unfocused_output(struct wl_output *output) {
void Window::handle_unfocused_output(struct wl_output* output) {
if (output_ == output) { // if we unfocused the output this bar belongs to
label_.get_style_context()->remove_class("focused");
ALabel::update();
+2 -2
View File
@@ -25,9 +25,9 @@ auto waybar::modules::Clock::update() -> void {
if (config_["tooltip-format"].isString()) {
auto tooltip_format = config_["tooltip-format"].asString();
auto tooltip_text = fmt::format(fmt::runtime(tooltip_format), localtime);
label_.set_tooltip_text(tooltip_text);
label_.set_tooltip_markup(tooltip_text);
} else {
label_.set_tooltip_text(text);
label_.set_tooltip_markup(text);
}
}
// Call parent update
+12 -10
View File
@@ -9,8 +9,8 @@
namespace waybar::modules {
void ondesc(void *arg, struct sioctl_desc *d, int curval) {
auto self = static_cast<Sndio *>(arg);
void ondesc(void* arg, struct sioctl_desc* d, int curval) {
auto self = static_cast<Sndio*>(arg);
if (d == NULL) {
// d is NULL when the list is done
return;
@@ -18,8 +18,8 @@ void ondesc(void *arg, struct sioctl_desc *d, int curval) {
self->set_desc(d, curval);
}
void onval(void *arg, unsigned int addr, unsigned int val) {
auto self = static_cast<Sndio *>(arg);
void onval(void* arg, unsigned int addr, unsigned int val) {
auto self = static_cast<Sndio*>(arg);
self->put_val(addr, val);
}
@@ -40,7 +40,7 @@ auto Sndio::connect_to_sndio() -> void {
pfds_.reserve(sioctl_nfds(hdl_));
}
Sndio::Sndio(const std::string &id, const Json::Value &config)
Sndio::Sndio(const std::string& id, const Json::Value& config)
: ALabel(config, "sndio", id, "{volume}%", 1, false, true),
hdl_(nullptr),
pfds_(0),
@@ -80,7 +80,7 @@ Sndio::Sndio(const std::string &id, const Json::Value &config)
while (thread_.isRunning()) {
try {
connect_to_sndio();
} catch (std::runtime_error const &e) {
} catch (std::runtime_error const& e) {
// avoid leaking hdl_
if (hdl_) {
sioctl_close(hdl_);
@@ -102,7 +102,9 @@ Sndio::~Sndio() { sioctl_close(hdl_); }
auto Sndio::update() -> void {
auto format = format_;
unsigned int vol = 100. * static_cast<double>(volume_) / static_cast<double>(maxval_);
unsigned int vol = (maxval_ > 0) ? static_cast<unsigned int>(100. * static_cast<double>(volume_) /
static_cast<double>(maxval_))
: 0;
if (volume_ == 0) {
label_.get_style_context()->add_class("muted");
@@ -122,7 +124,7 @@ auto Sndio::update() -> void {
ALabel::update();
}
auto Sndio::set_desc(struct sioctl_desc *d, unsigned int val) -> void {
auto Sndio::set_desc(struct sioctl_desc* d, unsigned int val) -> void {
std::string name{d->func};
std::string node_name{d->node0.name};
@@ -140,7 +142,7 @@ auto Sndio::put_val(unsigned int addr, unsigned int val) -> void {
}
}
bool Sndio::handleScroll(GdkEventScroll *e) {
bool Sndio::handleScroll(GdkEventScroll* e) {
// change the volume only when no user provided
// events are configured
if (config_["on-scroll-up"].isString() || config_["on-scroll-down"].isString()) {
@@ -180,7 +182,7 @@ bool Sndio::handleScroll(GdkEventScroll *e) {
return true;
}
bool Sndio::handleToggle(GdkEventButton *const &e) {
bool Sndio::handleToggle(GdkEventButton* const& e) {
// toggle mute only when no user provided events are configured
if (config_["on-click"].isString()) {
return AModule::handleToggle(e);
+78 -11
View File
@@ -6,9 +6,13 @@
namespace waybar::modules::SNI {
static const unsigned RETRY_DELAY_MS = 200;
static const unsigned MAX_RETRIES = 10;
Host::Host(const std::size_t id, const Json::Value& config, const Bar& bar,
const std::function<void(std::unique_ptr<Item>&)>& on_add,
const std::function<void(std::unique_ptr<Item>&)>& on_remove)
const std::function<void(std::unique_ptr<Item>&)>& on_remove,
const std::function<void()>& on_update)
: bus_name_("org.kde.StatusNotifierHost-" + std::to_string(getpid()) + "-" +
std::to_string(id)),
object_path_("/StatusNotifierHost/" + std::to_string(id)),
@@ -17,9 +21,11 @@ Host::Host(const std::size_t id, const Json::Value& config, const Bar& bar,
config_(config),
bar_(bar),
on_add_(on_add),
on_remove_(on_remove) {}
on_remove_(on_remove),
on_update_(on_update) {}
Host::~Host() {
retry_connection_.disconnect();
if (bus_name_id_ > 0) {
Gio::DBus::unown_name(bus_name_id_);
bus_name_id_ = 0;
@@ -51,15 +57,17 @@ void Host::nameAppeared(const Glib::RefPtr<Gio::DBus::Connection>& conn, const G
}
void Host::nameVanished(const Glib::RefPtr<Gio::DBus::Connection>& conn, const Glib::ustring name) {
retry_connection_.disconnect();
retry_count_ = 0;
g_cancellable_cancel(cancellable_);
g_clear_object(&cancellable_);
g_clear_object(&watcher_);
items_.clear();
clearItems();
}
void Host::proxyReady(GObject* src, GAsyncResult* res, gpointer data) {
GError* error = nullptr;
waybar::util::ScopeGuard error_deleter([error]() {
waybar::util::ScopeGuard error_deleter([&error]() {
if (error != nullptr) {
g_error_free(error);
}
@@ -70,18 +78,37 @@ void Host::proxyReady(GObject* src, GAsyncResult* res, gpointer data) {
return;
}
auto host = static_cast<SNI::Host*>(data);
host->watcher_ = watcher;
if (error != nullptr) {
spdlog::error("Host: {}", error->message);
g_clear_object(&host->cancellable_);
if (host->retry_count_ >= MAX_RETRIES) {
spdlog::warn("Host: giving up on watcher proxy creation after {} retries", host->retry_count_);
return;
}
host->retry_count_ += 1;
// Store the timeout connection so it is disconnected in ~Host, avoiding a
// use-after-free if the Host is destroyed before the retry fires.
host->retry_connection_ = Glib::signal_timeout().connect(
[host]() {
if (host->watcher_ != nullptr) {
return false;
}
auto conn = Gio::DBus::Connection::get_sync(Gio::DBus::BusType::BUS_TYPE_SESSION);
host->nameAppeared(conn, "org.kde.StatusNotifierWatcher", "");
return false;
},
RETRY_DELAY_MS);
return;
}
host->retry_count_ = 0;
host->watcher_ = watcher;
sn_watcher_call_register_host(host->watcher_, host->object_path_.c_str(), host->cancellable_,
&Host::registerHost, data);
}
void Host::registerHost(GObject* src, GAsyncResult* res, gpointer data) {
GError* error = nullptr;
waybar::util::ScopeGuard error_deleter([error]() {
waybar::util::ScopeGuard error_deleter([&error]() {
if (error != nullptr) {
g_error_free(error);
}
@@ -117,13 +144,50 @@ void Host::itemUnregistered(SnWatcher* watcher, const gchar* service, gpointer d
auto [bus_name, object_path] = host->getBusNameAndObjectPath(service);
for (auto it = host->items_.begin(); it != host->items_.end(); ++it) {
if ((*it)->bus_name == bus_name && (*it)->object_path == object_path) {
host->on_remove_(*it);
host->items_.erase(it);
host->removeItem(it);
break;
}
}
}
void Host::itemReady(Item& item) {
auto it = std::find_if(items_.begin(), items_.end(),
[&item](const auto& candidate) { return candidate.get() == &item; });
if (it != items_.end() && (*it)->isReady()) {
on_add_(*it);
}
}
void Host::itemInvalidated(Item& item) {
auto it = std::find_if(items_.begin(), items_.end(),
[&item](const auto& candidate) { return candidate.get() == &item; });
if (it != items_.end()) {
removeItem(it);
}
}
void Host::removeItem(std::vector<std::unique_ptr<Item>>::iterator it) {
if ((*it)->isReady()) {
on_remove_(*it);
}
items_.erase(it);
}
void Host::clearItems() {
bool removed_ready_item = false;
for (auto& item : items_) {
if (item->isReady()) {
on_remove_(item);
removed_ready_item = true;
}
}
bool had_items = !items_.empty();
items_.clear();
if (had_items && !removed_ready_item) {
on_update_();
}
}
std::tuple<std::string, std::string> Host::getBusNameAndObjectPath(const std::string service) {
auto it = service.find('/');
if (it != std::string::npos) {
@@ -132,15 +196,18 @@ std::tuple<std::string, std::string> Host::getBusNameAndObjectPath(const std::st
return {service, "/StatusNotifierItem"};
}
void Host::addRegisteredItem(std::string service) {
void Host::addRegisteredItem(const std::string& service) {
std::string bus_name, object_path;
std::tie(bus_name, object_path) = getBusNameAndObjectPath(service);
auto it = std::find_if(items_.begin(), items_.end(), [&bus_name, &object_path](const auto& item) {
return bus_name == item->bus_name && object_path == item->object_path;
});
if (it == items_.end()) {
items_.emplace_back(new Item(bus_name, object_path, config_, bar_));
on_add_(items_.back());
items_.emplace_back(std::make_unique<Item>(
bus_name, object_path, config_, bar_,
[this](Item& item) { itemReady(item); },
[this](Item& item) { itemInvalidated(item); },
on_update_));
}
}
+165 -53
View File
@@ -5,6 +5,7 @@
#include <gtkmm/tooltip.h>
#include <spdlog/spdlog.h>
#include <algorithm>
#include <filesystem>
#include <fstream>
#include <map>
@@ -37,13 +38,18 @@ namespace waybar::modules::SNI {
static const Glib::ustring SNI_INTERFACE_NAME = sn_item_interface_info()->name;
static const unsigned UPDATE_DEBOUNCE_TIME = 10;
Item::Item(const std::string& bn, const std::string& op, const Json::Value& config, const Bar& bar)
Item::Item(const std::string& bn, const std::string& op, const Json::Value& config, const Bar& bar,
const std::function<void(Item&)>& on_ready,
const std::function<void(Item&)>& on_invalidate, const std::function<void()>& on_updated)
: bus_name(bn),
object_path(op),
icon_size(16),
effective_icon_size(0),
icon_theme(Gtk::IconTheme::create()),
bar_(bar) {
bar_(bar),
on_ready_(on_ready),
on_invalidate_(on_invalidate),
on_updated_(on_updated) {
if (config["icon-size"].isUInt()) {
icon_size = config["icon-size"].asUInt();
}
@@ -79,8 +85,14 @@ Item::~Item() {
this->gtk_menu->popdown();
this->gtk_menu->detach();
}
if (this->dbus_menu != nullptr) {
g_object_weak_unref(G_OBJECT(this->dbus_menu), (GWeakNotify)onMenuDestroyed, this);
this->dbus_menu = nullptr;
}
}
bool Item::isReady() const { return ready_; }
bool Item::handleMouseEnter(GdkEventCrossing* const& e) {
event_box.set_state_flags(Gtk::StateFlags::STATE_FLAG_PRELIGHT);
return false;
@@ -108,14 +120,18 @@ void Item::proxyReady(Glib::RefPtr<Gio::AsyncResult>& result) {
if (this->id.empty() || this->category.empty()) {
spdlog::error("Invalid Status Notifier Item: {}, {}", bus_name, object_path);
invalidate();
return;
}
this->updateImage();
setReady();
} catch (const Glib::Error& err) {
spdlog::error("Failed to create DBus Proxy for {} {}: {}", bus_name, object_path, err.what());
invalidate();
} catch (const std::exception& err) {
spdlog::error("Failed to create DBus Proxy for {} {}: {}", bus_name, object_path, err.what());
invalidate();
}
}
@@ -174,17 +190,25 @@ void Item::setProperty(const Glib::ustring& name, Glib::VariantBase& value) {
} else if (name == "Status") {
setStatus(get_variant<Glib::ustring>(value));
} else if (name == "IconName") {
icon_name = get_variant<std::string>(value);
if (has_custom_icon_) {
spdlog::trace("Item '{}': ignoring IconName update, custom icon is set", id);
} else {
icon_name = get_variant<std::string>(value);
}
} else if (name == "IconPixmap") {
icon_pixmap = this->extractPixBuf(value.gobj());
if (has_custom_icon_) {
spdlog::trace("Item '{}': ignoring IconPixmap update, custom icon is set", id);
} else {
icon_pixmap = this->extractPixBuf(value.gobj());
}
} else if (name == "OverlayIconName") {
overlay_icon_name = get_variant<std::string>(value);
} else if (name == "OverlayIconPixmap") {
// TODO: overlay_icon_pixmap
overlay_icon_pixmap = extractPixBuf(value.gobj());
} else if (name == "AttentionIconName") {
attention_icon_name = get_variant<std::string>(value);
} else if (name == "AttentionIconPixmap") {
// TODO: attention_icon_pixmap
attention_icon_pixmap = extractPixBuf(value.gobj());
} else if (name == "AttentionMovieName") {
attention_movie_name = get_variant<std::string>(value);
} else if (name == "ToolTip") {
@@ -213,18 +237,35 @@ void Item::setProperty(const Glib::ustring& name, Glib::VariantBase& value) {
}
void Item::setStatus(const Glib::ustring& value) {
Glib::ustring lower = value.lowercase();
event_box.set_visible(show_passive_ || lower.compare("passive") != 0);
status_ = value.lowercase();
event_box.set_visible(show_passive_ || status_.compare("passive") != 0);
auto style = event_box.get_style_context();
for (const auto& class_name : style->list_classes()) {
style->remove_class(class_name);
}
if (lower.compare("needsattention") == 0) {
auto css_class = status_;
if (css_class.compare("needsattention") == 0) {
// convert status to dash-case for CSS
lower = "needs-attention";
css_class = "needs-attention";
}
style->add_class(lower);
style->add_class(css_class);
on_updated_();
}
void Item::setReady() {
if (ready_) {
return;
}
ready_ = true;
on_ready_(*this);
}
void Item::invalidate() {
if (ready_) {
ready_ = false;
}
on_invalidate_(*this);
}
void Item::setCustomIcon(const std::string& id) {
@@ -233,11 +274,17 @@ void Item::setCustomIcon(const std::string& id) {
std::string custom_icon = IconManager::instance().getIconForApp(id);
if (!custom_icon.empty()) {
if (std::filesystem::exists(custom_icon)) {
Glib::RefPtr<Gdk::Pixbuf> custom_pixbuf = Gdk::Pixbuf::create_from_file(custom_icon);
icon_name = ""; // icon_name has priority over pixmap
icon_pixmap = custom_pixbuf;
try {
Glib::RefPtr<Gdk::Pixbuf> custom_pixbuf = Gdk::Pixbuf::create_from_file(custom_icon);
icon_name = ""; // icon_name has priority over pixmap
icon_pixmap = custom_pixbuf;
has_custom_icon_ = true;
} catch (const Glib::Error& e) {
spdlog::error("Failed to load custom icon {}: {}", custom_icon, e.what());
}
} else { // if file doesn't exist it's most likely an icon_name
icon_name = custom_icon;
has_custom_icon_ = true;
}
}
}
@@ -279,8 +326,8 @@ void Item::processUpdatedProperties(Glib::RefPtr<Gio::AsyncResult>& _result) {
static const std::map<std::string_view, std::set<std::string_view>> signal2props = {
{"NewTitle", {"Title"}},
{"NewIcon", {"IconName", "IconPixmap"}},
// {"NewAttentionIcon", {"AttentionIconName", "AttentionIconPixmap", "AttentionMovieName"}},
// {"NewOverlayIcon", {"OverlayIconName", "OverlayIconPixmap"}},
{"NewAttentionIcon", {"AttentionIconName", "AttentionIconPixmap", "AttentionMovieName"}},
{"NewOverlayIcon", {"OverlayIconName", "OverlayIconPixmap"}},
{"NewIconThemePath", {"IconThemePath"}},
{"NewToolTip", {"ToolTip"}},
{"NewStatus", {"Status"}},
@@ -328,11 +375,20 @@ Glib::RefPtr<Gdk::Pixbuf> Item::extractPixBuf(GVariant* variant) {
if (array != nullptr) {
g_free(array);
}
#if GLIB_MAJOR_VERSION >= 2 && GLIB_MINOR_VERSION >= 68
array = static_cast<guchar*>(g_memdup2(data, size));
#else
array = static_cast<guchar*>(g_memdup(data, size));
#endif
// We must allocate our own array because the data from GVariant is read-only
// and we need to modify it to convert ARGB to RGBA.
array = static_cast<guchar*>(g_malloc(size));
// Copy and convert ARGB to RGBA in one pass to avoid g_memdup2 overhead
const guchar* src = static_cast<const guchar*>(data);
for (gsize i = 0; i < size; i += 4) {
guchar alpha = src[i];
array[i] = src[i + 1];
array[i + 1] = src[i + 2];
array[i + 2] = src[i + 3];
array[i + 3] = alpha;
}
lwidth = width;
lheight = height;
}
@@ -341,14 +397,6 @@ Glib::RefPtr<Gdk::Pixbuf> Item::extractPixBuf(GVariant* variant) {
}
g_variant_iter_free(it);
if (array != nullptr) {
/* argb to rgba */
for (uint32_t i = 0; i < 4U * lwidth * lheight; i += 4) {
guchar alpha = array[i];
array[i] = array[i + 1];
array[i + 1] = array[i + 2];
array[i + 2] = array[i + 3];
array[i + 3] = alpha;
}
return Gdk::Pixbuf::create_from_data(array, Gdk::Colorspace::COLORSPACE_RGB, true, 8, lwidth,
lheight, 4 * lwidth, &pixbuf_data_deleter);
}
@@ -357,47 +405,36 @@ Glib::RefPtr<Gdk::Pixbuf> Item::extractPixBuf(GVariant* variant) {
void Item::updateImage() {
auto pixbuf = getIconPixbuf();
if (!pixbuf) return;
auto scaled_icon_size = getScaledIconSize();
// If the loaded icon is not square, assume that the icon height should match the
// requested icon size, but the width is allowed to be different. As such, if the
// height of the image does not match the requested icon size, resize the icon such that
// the aspect ratio is maintained, but the height matches the requested icon size.
if (pixbuf->get_height() != scaled_icon_size) {
if (pixbuf->get_height() > 0 && pixbuf->get_height() != scaled_icon_size) {
int width = scaled_icon_size * pixbuf->get_width() / pixbuf->get_height();
pixbuf = pixbuf->scale_simple(width, scaled_icon_size, Gdk::InterpType::INTERP_BILINEAR);
}
pixbuf = overlayPixbufs(pixbuf, getOverlayIconPixbuf());
auto surface =
Gdk::Cairo::create_surface_from_pixbuf(pixbuf, image.get_scale_factor(), image.get_window());
image.set(surface);
}
Glib::RefPtr<Gdk::Pixbuf> Item::getIconPixbuf() {
if (!icon_name.empty()) {
try {
std::ifstream temp(icon_name);
if (temp.is_open()) {
return Gdk::Pixbuf::create_from_file(icon_name);
}
} catch (Glib::Error& e) {
// Ignore because we want to also try different methods of getting an icon.
//
// But a warning is logged, as the file apparently exists, but there was
// a failure in creating a pixbuf out of it.
spdlog::warn("Item '{}': {}", id, static_cast<std::string>(e.what()));
}
try {
// Will throw if it can not find an icon.
return getIconByName(icon_name, getScaledIconSize());
} catch (Glib::Error& e) {
spdlog::trace("Item '{}': {}", id, static_cast<std::string>(e.what()));
if (status_ == "needsattention") {
if (auto attention_pixbuf = getAttentionIconPixbuf()) {
return attention_pixbuf;
}
}
// Return the pixmap only if an icon for the given name could not be found.
if (auto pixbuf = loadIconFromNameOrFile(icon_name, true)) {
return pixbuf;
}
if (icon_pixmap) {
return icon_pixmap;
}
@@ -412,9 +449,78 @@ Glib::RefPtr<Gdk::Pixbuf> Item::getIconPixbuf() {
return getIconByName("image-missing", getScaledIconSize());
}
Glib::RefPtr<Gdk::Pixbuf> Item::getIconByName(const std::string& name, int request_size) {
icon_theme->rescan_if_needed();
Glib::RefPtr<Gdk::Pixbuf> Item::getAttentionIconPixbuf() {
if (auto pixbuf = loadIconFromNameOrFile(attention_icon_name, false)) {
return pixbuf;
}
if (auto pixbuf = loadIconFromNameOrFile(attention_movie_name, false)) {
return pixbuf;
}
return attention_icon_pixmap;
}
Glib::RefPtr<Gdk::Pixbuf> Item::getOverlayIconPixbuf() {
if (auto pixbuf = loadIconFromNameOrFile(overlay_icon_name, false)) {
return pixbuf;
}
return overlay_icon_pixmap;
}
Glib::RefPtr<Gdk::Pixbuf> Item::loadIconFromNameOrFile(const std::string& name, bool log_failure) {
if (name.empty()) {
return {};
}
try {
std::ifstream temp(name);
if (temp.is_open()) {
return Gdk::Pixbuf::create_from_file(name);
}
} catch (const Glib::Error& e) {
if (log_failure) {
spdlog::warn("Item '{}': {}", id, static_cast<std::string>(e.what()));
}
}
try {
return getIconByName(name, getScaledIconSize());
} catch (const Glib::Error& e) {
if (log_failure) {
spdlog::trace("Item '{}': {}", id, static_cast<std::string>(e.what()));
}
}
return {};
}
Glib::RefPtr<Gdk::Pixbuf> Item::overlayPixbufs(const Glib::RefPtr<Gdk::Pixbuf>& base,
const Glib::RefPtr<Gdk::Pixbuf>& overlay) {
if (!base || !overlay) {
return base;
}
auto composed = base->copy();
if (!composed) {
return base;
}
int overlay_target_size =
std::max(1, std::min(composed->get_width(), composed->get_height()) / 2);
auto scaled_overlay = overlay->scale_simple(overlay_target_size, overlay_target_size,
Gdk::InterpType::INTERP_BILINEAR);
if (!scaled_overlay) {
return composed;
}
int dest_x = std::max(0, composed->get_width() - scaled_overlay->get_width());
int dest_y = std::max(0, composed->get_height() - scaled_overlay->get_height());
scaled_overlay->composite(composed, dest_x, dest_y, scaled_overlay->get_width(),
scaled_overlay->get_height(), dest_x, dest_y, 1.0, 1.0,
Gdk::InterpType::INTERP_BILINEAR, 255);
return composed;
}
Glib::RefPtr<Gdk::Pixbuf> Item::getIconByName(const std::string& name, int request_size) {
if (!icon_theme_path.empty()) {
auto icon_info = icon_theme->lookup_icon(name.c_str(), request_size,
Gtk::IconLookupFlags::ICON_LOOKUP_FORCE_SIZE);
@@ -456,6 +562,9 @@ void Item::makeMenu() {
}
bool Item::handleClick(GdkEventButton* const& ev) {
if (!proxy_) {
return false;
}
auto parameters = Glib::VariantContainerBase::create_tuple(
{Glib::Variant<int>::create(ev->x_root + bar_.x_global),
Glib::Variant<int>::create(ev->y_root + bar_.y_global)});
@@ -483,6 +592,9 @@ bool Item::handleClick(GdkEventButton* const& ev) {
}
bool Item::handleScroll(GdkEventScroll* const& ev) {
if (!proxy_) {
return false;
}
int dx = 0, dy = 0;
switch (ev->direction) {
case GDK_SCROLL_UP:
+8 -14
View File
@@ -13,7 +13,8 @@ Tray::Tray(const std::string& id, const Bar& bar, const Json::Value& config)
box_(bar.orientation, 0),
watcher_(SNI::Watcher::getInstance()),
host_(nb_hosts_, config, bar, std::bind(&Tray::onAdd, this, std::placeholders::_1),
std::bind(&Tray::onRemove, this, std::placeholders::_1)) {
std::bind(&Tray::onRemove, this, std::placeholders::_1),
std::bind(&Tray::queueUpdate, this)) {
box_.set_name("tray");
event_box_.add(box_);
if (!id.empty()) {
@@ -23,9 +24,6 @@ Tray::Tray(const std::string& id, const Bar& bar, const Json::Value& config)
if (config_["spacing"].isUInt()) {
box_.set_spacing(config_["spacing"].asUInt());
}
if (config["show-passive-items"].isBool()) {
show_passive_ = config["show-passive-items"].asBool();
}
nb_hosts_ += 1;
if (config_["icons"].isObject()) {
IconManager::instance().setIconsConfig(config_["icons"]);
@@ -33,12 +31,16 @@ Tray::Tray(const std::string& id, const Bar& bar, const Json::Value& config)
dp.emit();
}
void Tray::queueUpdate() { dp.emit(); }
void Tray::onAdd(std::unique_ptr<Item>& item) {
if (config_["reverse-direction"].isBool() && config_["reverse-direction"].asBool()) {
box_.pack_end(item->event_box);
} else {
box_.pack_start(item->event_box);
}
item->event_box.signal_show().connect([this] { dp.emit(); });
item->event_box.signal_hide().connect([this] { dp.emit(); });
dp.emit();
}
@@ -48,17 +50,9 @@ void Tray::onRemove(std::unique_ptr<Item>& item) {
}
auto Tray::update() -> void {
// Show tray only when items are available
std::vector<Gtk::Widget*> children = box_.get_children();
if (show_passive_) {
event_box_.set_visible(!children.empty());
} else {
event_box_.set_visible(!std::all_of(children.begin(), children.end(), [](Gtk::Widget* child) {
return child->get_style_context()->has_class("passive");
}));
}
// Call parent update
event_box_.set_visible(std::any_of(children.begin(), children.end(),
[](Gtk::Widget* child) { return child->get_visible(); }));
AModule::update();
}
+6 -5
View File
@@ -31,7 +31,7 @@ Watcher::~Watcher() {
void Watcher::busAcquired(const Glib::RefPtr<Gio::DBus::Connection>& conn, Glib::ustring name) {
GError* error = nullptr;
waybar::util::ScopeGuard error_deleter([error]() {
waybar::util::ScopeGuard error_deleter([&error]() {
if (error) {
g_error_free(error);
}
@@ -69,7 +69,7 @@ gboolean Watcher::handleRegisterHost(Watcher* obj, GDBusMethodInvocation* invoca
if (watch != nullptr) {
g_warning("Status Notifier Host with bus name '%s' and object path '%s' is already registered",
bus_name, object_path);
sn_watcher_complete_register_item(obj->watcher_, invocation);
sn_watcher_complete_register_host(obj->watcher_, invocation);
return TRUE;
}
watch = gfWatchNew(GF_WATCH_TYPE_HOST, service, bus_name, object_path, obj);
@@ -98,8 +98,8 @@ gboolean Watcher::handleRegisterItem(Watcher* obj, GDBusMethodInvocation* invoca
}
auto watch = gfWatchFind(obj->items_, bus_name, object_path);
if (watch != nullptr) {
g_warning("Status Notifier Item with bus name '%s' and object path '%s' is already registered",
bus_name, object_path);
spdlog::debug("Ignoring duplicate Status Notifier Item registration for '{}' at '{}'", bus_name,
object_path);
sn_watcher_complete_register_item(obj->watcher_, invocation);
return TRUE;
}
@@ -158,7 +158,7 @@ void Watcher::nameVanished(GDBusConnection* connection, const char* name, gpoint
watch->watcher->hosts_ = g_slist_remove(watch->watcher->hosts_, watch);
if (watch->watcher->hosts_ == nullptr) {
sn_watcher_set_is_host_registered(watch->watcher->watcher_, FALSE);
sn_watcher_emit_host_registered(watch->watcher->watcher_);
sn_watcher_emit_host_unregistered(watch->watcher->watcher_);
}
} else if (watch->type == GF_WATCH_TYPE_ITEM) {
watch->watcher->items_ = g_slist_remove(watch->watcher->items_, watch);
@@ -167,6 +167,7 @@ void Watcher::nameVanished(GDBusConnection* connection, const char* name, gpoint
sn_watcher_emit_item_unregistered(watch->watcher->watcher_, tmp);
g_free(tmp);
}
gfWatchFree(watch);
}
void Watcher::updateRegisteredItems(SnWatcher* obj) {
+1 -1
View File
@@ -60,7 +60,7 @@ BarIpcClient::BarIpcClient(waybar::Bar& bar) : bar_{bar} {
});
}
bool BarIpcClient::isModuleEnabled(std::string name) {
bool BarIpcClient::isModuleEnabled(const std::string& name) {
for (const auto& section : {"modules-left", "modules-center", "modules-right"}) {
if (const auto& modules = bar_.config.get(section, {}); modules.isArray()) {
for (const auto& module : modules) {
+4 -8
View File
@@ -9,8 +9,8 @@ namespace waybar::modules::sway {
Ipc::Ipc() {
const std::string& socketPath = getSocketPath();
fd_ = open(socketPath);
fd_event_ = open(socketPath);
fd_ = util::ScopedFd(open(socketPath));
fd_event_ = util::ScopedFd(open(socketPath));
}
Ipc::~Ipc() {
@@ -21,15 +21,11 @@ Ipc::~Ipc() {
if (write(fd_, "close-sway-ipc", 14) == -1) {
spdlog::error("Failed to close sway IPC");
}
close(fd_);
fd_ = -1;
}
if (fd_event_ > 0) {
if (write(fd_event_, "close-sway-ipc", 14) == -1) {
spdlog::error("Failed to close sway IPC event handler");
}
close(fd_event_);
fd_event_ = -1;
}
}
@@ -64,7 +60,7 @@ const std::string Ipc::getSocketPath() const {
}
int Ipc::open(const std::string& socketPath) const {
int32_t fd = socket(AF_UNIX, SOCK_STREAM, 0);
util::ScopedFd fd(socket(AF_UNIX, SOCK_STREAM, 0));
if (fd == -1) {
throw std::runtime_error("Unable to open Unix socket");
}
@@ -78,7 +74,7 @@ int Ipc::open(const std::string& socketPath) const {
if (::connect(fd, reinterpret_cast<struct sockaddr*>(&addr), l) == -1) {
throw std::runtime_error("Unable to connect to Sway");
}
return fd;
return fd.release();
}
struct Ipc::ipc_response Ipc::recv(int fd) {
+43 -16
View File
@@ -54,21 +54,28 @@ void Language::onCmd(const struct Ipc::ipc_response& res) {
std::lock_guard<std::mutex> lock(mutex_);
auto payload = parser_.parse(res.payload);
std::vector<std::string> used_layouts;
// Display current layout of a device with a maximum count of layouts, expecting that all will
// be OK
// Union layout names across every keyboard input so hot-plugged devices contribute their
// layouts to the map. Track the device with the most layouts to seed the initially displayed
// layout, matching the previous behaviour at startup.
Json::ArrayIndex max_id = 0, max = 0;
for (Json::ArrayIndex i = 0; i < payload.size(); i++) {
auto size = payload[i][XKB_LAYOUT_NAMES_KEY].size();
if (size > max) {
max = size;
if (payload[i]["type"].asString() != "keyboard") continue;
const auto& names = payload[i][XKB_LAYOUT_NAMES_KEY];
if (names.size() > max) {
max = names.size();
max_id = i;
}
for (const auto& layout : names) {
const auto name = layout.asString();
if (std::find(used_layouts.begin(), used_layouts.end(), name) == used_layouts.end()) {
used_layouts.push_back(name);
}
}
}
for (const auto& layout : payload[max_id][XKB_LAYOUT_NAMES_KEY]) {
used_layouts.push_back(layout.asString());
}
// Rebuild from scratch so init_layouts_map's duplicate-suffix pass doesn't compound across
// refreshes (e.g. "us" -> "us1" -> "us11").
layouts_map_.clear();
init_layouts_map(used_layouts);
set_current_layout(payload[max_id][XKB_ACTIVE_LAYOUT_NAME_KEY].asString());
dp.emit();
@@ -82,13 +89,26 @@ void Language::onEvent(const struct Ipc::ipc_response& res) {
return;
}
bool refresh_inputs = false;
try {
std::lock_guard<std::mutex> lock(mutex_);
auto payload = parser_.parse(res.payload)["input"];
if (payload["type"].asString() == "keyboard") {
set_current_layout(payload[XKB_ACTIVE_LAYOUT_NAME_KEY].asString());
{
std::lock_guard<std::mutex> lock(mutex_);
auto root = parser_.parse(res.payload);
auto change = root["change"].asString();
auto payload = root["input"];
if (payload["type"].asString() == "keyboard") {
// A device was added or its keymap changed - the layout set may have grown, so refresh
// layouts_map_ via IPC_GET_INPUTS once we've released mutex_.
refresh_inputs = (change == "added" || change == "xkb_keymap");
set_current_layout(payload[XKB_ACTIVE_LAYOUT_NAME_KEY].asString());
}
dp.emit();
}
// sendCmd is synchronous: it blocks on the IPC reply and then emits signal_cmd on this same
// thread, which lands in onCmd and re-locks mutex_. Must call it with mutex_ released.
if (refresh_inputs) {
ipc_.sendCmd(IPC_GET_INPUTS);
}
dp.emit();
} catch (const std::exception& e) {
spdlog::error("Language: {}", e.what());
}
@@ -124,9 +144,16 @@ auto Language::update() -> void {
ALabel::update();
}
auto Language::set_current_layout(std::string current_layout) -> void {
auto Language::set_current_layout(const std::string& current_layout) -> void {
// Guard against unknown / empty layout names: transient virtual keyboards (e.g. wtype) and
// hot-plugged devices whose layouts haven't made it into the map yet would otherwise blank out
// layout_ via map::operator[]'s default-construct-on-miss.
auto it = layouts_map_.find(current_layout);
if (it == layouts_map_.end()) {
return;
}
label_.get_style_context()->remove_class(layout_.short_name);
layout_ = layouts_map_[current_layout];
layout_ = it->second;
label_.get_style_context()->add_class(layout_.short_name);
}
+1 -1
View File
@@ -44,7 +44,7 @@ auto Mode::update() -> void {
} else {
label_.set_markup(fmt::format(fmt::runtime(format_), mode_));
if (tooltipEnabled()) {
label_.set_tooltip_text(mode_);
label_.set_tooltip_markup(mode_);
}
event_box_.show();
}
+4 -4
View File
@@ -94,12 +94,12 @@ auto Window::update() -> void {
old_app_id_ = app_id_;
}
label_.set_markup(waybar::util::rewriteString(
setLabelMarkup(waybar::util::rewriteString(
fmt::format(fmt::runtime(format_), fmt::arg("title", window_), fmt::arg("app_id", app_id_),
fmt::arg("shell", shell_), fmt::arg("marks", marks_)),
config_["rewrite"]));
if (tooltipEnabled()) {
label_.set_tooltip_text(window_);
setTooltipMarkup(window_);
}
updateAppIcon();
@@ -184,9 +184,9 @@ std::tuple<std::string, std::string, std::string, std::string> getWindowInfo(
continue;
}
if (!marks.empty()) {
marks += ',';
marks.append(",");
}
marks += m.asString();
marks.append(m.asString());
}
}
return {app_id, app_class, shell, marks};
+66 -55
View File
@@ -10,10 +10,10 @@ namespace waybar::modules::sway {
// Helper function to assign a number to a workspace, just like sway. In fact
// this is taken quite verbatim from `sway/ipc-json.c`.
int Workspaces::convertWorkspaceNameToNum(std::string name) {
int Workspaces::convertWorkspaceNameToNum(const std::string& name) {
if (isdigit(name[0]) != 0) {
errno = 0;
char *endptr = nullptr;
char* endptr = nullptr;
long long parsed_num = strtoll(name.c_str(), &endptr, 10);
if (errno != 0 || parsed_num > INT32_MAX || parsed_num < 0 || endptr == name.c_str()) {
return -1;
@@ -23,7 +23,7 @@ int Workspaces::convertWorkspaceNameToNum(std::string name) {
return -1;
}
int Workspaces::windowRewritePriorityFunction(std::string const &window_rule) {
int Workspaces::windowRewritePriorityFunction(std::string const& window_rule) {
// Rules that match against title are prioritized
// Rules that don't specify if they're matching against either title or class are deprioritized
bool const hasTitle = window_rule.find("title") != std::string::npos;
@@ -41,12 +41,12 @@ int Workspaces::windowRewritePriorityFunction(std::string const &window_rule) {
return 0;
}
Workspaces::Workspaces(const std::string &id, const Bar &bar, const Json::Value &config)
Workspaces::Workspaces(const std::string& id, const Bar& bar, const Json::Value& config)
: AModule(config, "workspaces", id, false, !config["disable-scroll"].asBool()),
bar_(bar),
box_(bar.orientation, 0) {
if (config["format-icons"]["high-priority-named"].isArray()) {
for (const auto &it : config["format-icons"]["high-priority-named"]) {
for (const auto& it : config["format-icons"]["high-priority-named"]) {
high_priority_named_.push_back(it.asString());
}
}
@@ -61,9 +61,9 @@ Workspaces::Workspaces(const std::string &id, const Bar &bar, const Json::Value
} else {
m_formatWindowSeparator = " ";
}
const Json::Value &windowRewrite = config["window-rewrite"];
const Json::Value& windowRewrite = config["window-rewrite"];
if (windowRewrite.isObject()) {
const Json::Value &windowRewriteDefaultConfig = config["window-rewrite-default"];
const Json::Value& windowRewriteDefaultConfig = config["window-rewrite-default"];
std::string windowRewriteDefault =
windowRewriteDefaultConfig.isString() ? windowRewriteDefaultConfig.asString() : "?";
m_windowRewriteRules = waybar::util::RegexCollection(
@@ -75,7 +75,7 @@ Workspaces::Workspaces(const std::string &id, const Bar &bar, const Json::Value
ipc_.signal_cmd.connect(sigc::mem_fun(*this, &Workspaces::onCmd));
ipc_.sendCmd(IPC_GET_TREE);
if (config["enable-bar-scroll"].asBool()) {
auto &window = const_cast<Bar &>(bar_).window;
auto& window = const_cast<Bar&>(bar_).window;
window.add_events(Gdk::SCROLL_MASK | Gdk::SMOOTH_SCROLL_MASK);
window.signal_scroll_event().connect(sigc::mem_fun(*this, &Workspaces::handleScroll));
}
@@ -83,21 +83,21 @@ Workspaces::Workspaces(const std::string &id, const Bar &bar, const Json::Value
ipc_.setWorker([this] {
try {
ipc_.handleEvent();
} catch (const std::exception &e) {
} catch (const std::exception& e) {
spdlog::error("Workspaces: {}", e.what());
}
});
}
void Workspaces::onEvent(const struct Ipc::ipc_response &res) {
void Workspaces::onEvent(const struct Ipc::ipc_response& res) {
try {
ipc_.sendCmd(IPC_GET_TREE);
} catch (const std::exception &e) {
} catch (const std::exception& e) {
spdlog::error("Workspaces: {}", e.what());
}
}
void Workspaces::onCmd(const struct Ipc::ipc_response &res) {
void Workspaces::onCmd(const struct Ipc::ipc_response& res) {
if (res.type == IPC_GET_TREE) {
try {
{
@@ -107,7 +107,7 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) {
std::vector<Json::Value> outputs;
bool alloutputs = config_["all-outputs"].asBool();
std::copy_if(payload["nodes"].begin(), payload["nodes"].end(), std::back_inserter(outputs),
[&](const auto &output) {
[&](const auto& output) {
if (alloutputs && output["name"].asString() != "__i3") {
return true;
}
@@ -117,7 +117,7 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) {
return false;
});
for (auto &output : outputs) {
for (auto& output : outputs) {
std::copy(output["nodes"].begin(), output["nodes"].end(),
std::back_inserter(workspaces_));
std::copy(output["floating_nodes"].begin(), output["floating_nodes"].end(),
@@ -126,13 +126,13 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) {
// adding persistent workspaces (as per the config file)
if (config_["persistent-workspaces"].isObject()) {
const Json::Value &p_workspaces = config_["persistent-workspaces"];
const Json::Value& p_workspaces = config_["persistent-workspaces"];
const std::vector<std::string> p_workspaces_names = p_workspaces.getMemberNames();
for (const std::string &p_w_name : p_workspaces_names) {
const Json::Value &p_w = p_workspaces[p_w_name];
for (const std::string& p_w_name : p_workspaces_names) {
const Json::Value& p_w = p_workspaces[p_w_name];
auto it = std::find_if(workspaces_.begin(), workspaces_.end(),
[&p_w_name](const Json::Value &node) {
[&p_w_name](const Json::Value& node) {
return node["name"].asString() == p_w_name;
});
@@ -142,7 +142,7 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) {
if (p_w.isArray() && !p_w.empty()) {
// Adding to target outputs
for (const Json::Value &output : p_w) {
for (const Json::Value& output : p_w) {
if (output.asString() == bar_.output->name) {
Json::Value v;
v["name"] = p_w_name;
@@ -185,10 +185,10 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) {
// agreement that the "workspace prev/next" commands may not follow
// the order displayed in Waybar.
int max_num = -1;
for (auto &workspace : workspaces_) {
for (auto& workspace : workspaces_) {
max_num = std::max(workspace["num"].asInt(), max_num);
}
for (auto &workspace : workspaces_) {
for (auto& workspace : workspaces_) {
auto workspace_num = workspace["num"].asInt();
if (workspace_num > -1) {
workspace["sort"] = workspace_num;
@@ -197,7 +197,7 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) {
}
}
std::sort(workspaces_.begin(), workspaces_.end(),
[this](const Json::Value &lhs, const Json::Value &rhs) {
[this](const Json::Value& lhs, const Json::Value& rhs) {
auto lname = lhs["name"].asString();
auto rname = rhs["name"].asString();
int l = lhs["sort"].asInt();
@@ -217,7 +217,7 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) {
});
}
dp.emit();
} catch (const std::exception &e) {
} catch (const std::exception& e) {
spdlog::error("Workspaces: {}", e.what());
}
}
@@ -227,9 +227,12 @@ bool Workspaces::filterButtons() {
bool needReorder = false;
for (auto it = buttons_.begin(); it != buttons_.end();) {
auto ws = std::find_if(workspaces_.begin(), workspaces_.end(),
[it](const auto &node) { return node["name"].asString() == it->first; });
[it](const auto& node) { return node["name"].asString() == it->first; });
if (ws == workspaces_.end() ||
(!config_["all-outputs"].asBool() && (*ws)["output"].asString() != bar_.output->name)) {
((*ws).isMember("target_output") ? (*ws)["target_output"].asString() != bar_.output->name &&
(*ws)["target_output"].asString() != ""
: !config_["all-outputs"].asBool() &&
(*ws)["output"].asString() != bar_.output->name)) {
it = buttons_.erase(it);
needReorder = true;
} else {
@@ -239,23 +242,23 @@ bool Workspaces::filterButtons() {
return needReorder;
}
bool Workspaces::hasFlag(const Json::Value &node, const std::string &flag) {
bool Workspaces::hasFlag(const Json::Value& node, const std::string& flag) {
if (node[flag].asBool()) {
return true;
}
if (std::any_of(node["nodes"].begin(), node["nodes"].end(),
[&](auto const &e) { return hasFlag(e, flag); })) {
[&](auto const& e) { return hasFlag(e, flag); })) {
return true;
}
if (std::any_of(node["floating_nodes"].begin(), node["floating_nodes"].end(),
[&](auto const &e) { return hasFlag(e, flag); })) {
[&](auto const& e) { return hasFlag(e, flag); })) {
return true;
}
return false;
}
void Workspaces::updateWindows(const Json::Value &node, std::string &windows) {
void Workspaces::updateWindows(const Json::Value& node, std::string& windows) {
if ((node["type"].asString() == "con" || node["type"].asString() == "floating_con") &&
node["name"].isString()) {
std::string title = g_markup_escape_text(node["name"].asString().c_str(), -1);
@@ -274,10 +277,10 @@ void Workspaces::updateWindows(const Json::Value &node, std::string &windows) {
windows.append(m_formatWindowSeparator);
}
}
for (const Json::Value &child : node["nodes"]) {
for (const Json::Value& child : node["nodes"]) {
updateWindows(child, windows);
}
for (const Json::Value &child : node["floating_nodes"]) {
for (const Json::Value& child : node["floating_nodes"]) {
updateWindows(child, windows);
}
}
@@ -290,7 +293,7 @@ auto Workspaces::update() -> void {
if (bit == buttons_.end()) {
needReorder = true;
}
auto &button = bit == buttons_.end() ? addButton(*it) : bit->second;
auto& button = bit == buttons_.end() ? addButton(*it) : bit->second;
if (needReorder) {
box_.reorder_child(button, it - workspaces_.begin());
}
@@ -329,7 +332,12 @@ auto Workspaces::update() -> void {
} else {
button.get_style_context()->remove_class("current_output");
}
std::string output = (*it)["name"].asString();
std::string output;
if (!config_["disable-markup"].asBool()) {
output = g_markup_escape_text((*it)["name"].asString().c_str(), -1);
} else {
output = (*it)["name"].asString();
}
std::string windows = "";
if (config_["window-rewrite"].isObject()) {
updateWindows((*it), windows);
@@ -344,7 +352,7 @@ auto Workspaces::update() -> void {
fmt::arg("output", (*it)["output"].asString()));
}
if (!config_["disable-markup"].asBool()) {
static_cast<Gtk::Label *>(button.get_children()[0])->set_markup(output);
static_cast<Gtk::Label*>(button.get_children()[0])->set_markup(output);
} else {
button.set_label(output);
}
@@ -354,9 +362,9 @@ auto Workspaces::update() -> void {
AModule::update();
}
Gtk::Button &Workspaces::addButton(const Json::Value &node) {
Gtk::Button& Workspaces::addButton(const Json::Value& node) {
auto pair = buttons_.emplace(node["name"].asString(), node["name"].asString());
auto &&button = pair.first->second;
auto&& button = pair.first->second;
box_.pack_start(button, false, false, 0);
button.set_name("sway-workspace-" + node["name"].asString());
button.set_relief(Gtk::RELIEF_NONE);
@@ -369,13 +377,16 @@ Gtk::Button &Workspaces::addButton(const Json::Value &node) {
node["name"].asString(), node["target_output"].asString(),
"--no-auto-back-and-forth", node["name"].asString()));
} else {
ipc_.sendCmd(IPC_COMMAND, fmt::format("workspace {} \"{}\"",
config_["disable-auto-back-and-forth"].asBool()
? "--no-auto-back-and-forth"
: "",
node["name"].asString()));
std::string flag = config_["disable-auto-back-and-forth"].asBool()
? "--no-auto-back-and-forth"
: "";
if (node["num"].asInt() >= 0) {
ipc_.sendCmd(IPC_COMMAND, fmt::format(workspace_switch_number_cmd_, flag, node["num"].asInt()));
} else {
ipc_.sendCmd(IPC_COMMAND, fmt::format(workspace_switch_cmd_, flag, node["name"].asString()));
}
}
} catch (const std::exception &e) {
} catch (const std::exception& e) {
spdlog::error("Workspaces: {}", e.what());
}
});
@@ -383,18 +394,18 @@ Gtk::Button &Workspaces::addButton(const Json::Value &node) {
return button;
}
std::string Workspaces::getIcon(const std::string &name, const Json::Value &node) {
std::string Workspaces::getIcon(const std::string& name, const Json::Value& node) {
std::vector<std::string> keys = {"high-priority-named", "urgent", "focused", name, "default"};
for (auto const &key : keys) {
for (auto const& key : keys) {
if (key == "high-priority-named") {
auto it = std::find_if(high_priority_named_.begin(), high_priority_named_.end(),
[&](const std::string &member) { return member == name; });
[&](const std::string& member) { return member == name; });
if (it != high_priority_named_.end()) {
return config_["format-icons"][name].asString();
}
it = std::find_if(high_priority_named_.begin(), high_priority_named_.end(),
[&](const std::string &member) {
[&](const std::string& member) {
return trimWorkspaceName(member) == trimWorkspaceName(name);
});
if (it != high_priority_named_.end()) {
@@ -417,8 +428,8 @@ std::string Workspaces::getIcon(const std::string &name, const Json::Value &node
return name;
}
bool Workspaces::handleScroll(GdkEventScroll *e) {
if (gdk_event_get_pointer_emulated((GdkEvent *)e) != 0) {
bool Workspaces::handleScroll(GdkEventScroll* e) {
if (gdk_event_get_pointer_emulated((GdkEvent*)e) != 0) {
/**
* Ignore emulated scroll events on window
*/
@@ -433,7 +444,7 @@ bool Workspaces::handleScroll(GdkEventScroll *e) {
bool alloutputs = config_["all-outputs"].asBool();
std::lock_guard<std::mutex> lock(mutex_);
auto it =
std::find_if(workspaces_.begin(), workspaces_.end(), [alloutputs](const auto &workspace) {
std::find_if(workspaces_.begin(), workspaces_.end(), [alloutputs](const auto& workspace) {
if (alloutputs) {
return hasFlag(workspace, "focused");
}
@@ -460,7 +471,7 @@ bool Workspaces::handleScroll(GdkEventScroll *e) {
}
try {
ipc_.sendCmd(IPC_COMMAND, fmt::format(workspace_switch_cmd_, "--no-auto-back-and-forth", name));
} catch (const std::exception &e) {
} catch (const std::exception& e) {
spdlog::error("Workspaces: {}", e.what());
}
if (!config_["warp-on-scroll"].isNull() && !config_["warp-on-scroll"].asBool()) {
@@ -487,7 +498,7 @@ std::string Workspaces::getCycleWorkspace(std::vector<Json::Value>::iterator it,
return (*it)["name"].asString();
}
std::string Workspaces::trimWorkspaceName(std::string name) {
std::string Workspaces::trimWorkspaceName(const std::string& name) {
std::size_t found = name.find(':');
if (found != std::string::npos) {
return name.substr(found + 1);
@@ -495,7 +506,7 @@ std::string Workspaces::trimWorkspaceName(std::string name) {
return name;
}
bool is_focused_recursive(const Json::Value &node) {
bool is_focused_recursive(const Json::Value& node) {
// If a workspace has a focused container then get_tree will say
// that the workspace itself isn't focused. Therefore we need to
// check if any of its nodes are focused as well.
@@ -505,13 +516,13 @@ bool is_focused_recursive(const Json::Value &node) {
return true;
}
for (const auto &child : node["nodes"]) {
for (const auto& child : node["nodes"]) {
if (is_focused_recursive(child)) {
return true;
}
}
for (const auto &child : node["floating_nodes"]) {
for (const auto& child : node["floating_nodes"]) {
if (is_focused_recursive(child)) {
return true;
}
@@ -520,7 +531,7 @@ bool is_focused_recursive(const Json::Value &node) {
return false;
}
void Workspaces::onButtonReady(const Json::Value &node, Gtk::Button &button) {
void Workspaces::onButtonReady(const Json::Value& node, Gtk::Button& button) {
if (config_["current-only"].asBool()) {
if (is_focused_recursive(node)) {
button.show();
+193 -49
View File
@@ -1,10 +1,15 @@
#include "modules/systemd_failed_units.hpp"
#include <fmt/format.h>
#include <giomm/dbusproxy.h>
#include <glibmm/markup.h>
#include <glibmm/variant.h>
#include <spdlog/spdlog.h>
#include <cstdint>
#include <exception>
#include <stdexcept>
#include <tuple>
static const unsigned UPDATE_DEBOUNCE_TIME_MS = 1000;
@@ -12,56 +17,86 @@ namespace waybar::modules {
SystemdFailedUnits::SystemdFailedUnits(const std::string& id, const Json::Value& config)
: ALabel(config, "systemd-failed-units", id, "{nr_failed} failed", 1),
hide_on_ok(true),
update_pending(false),
nr_failed_system(0),
nr_failed_user(0),
nr_failed(0),
last_status() {
hide_on_ok_(true),
tooltip_format_(
"System: {system_state}\nUser: {user_state}\nFailed units ({nr_failed}):\n"
"{failed_units_list}"),
tooltip_format_ok_("System: {system_state}\nUser: {user_state}"),
tooltip_unit_format_("{name}: {description}"),
update_pending_(false),
nr_failed_system_(0),
nr_failed_user_(0),
nr_failed_(0),
last_status_() {
if (config["hide-on-ok"].isBool()) {
hide_on_ok = config["hide-on-ok"].asBool();
hide_on_ok_ = config["hide-on-ok"].asBool();
}
if (config["format-ok"].isString()) {
format_ok = config["format-ok"].asString();
format_ok_ = config["format-ok"].asString();
} else {
format_ok = format_;
format_ok_ = format_;
}
if (config["tooltip-format"].isString()) {
tooltip_format_ = config["tooltip-format"].asString();
}
if (config["tooltip-format-ok"].isString()) {
tooltip_format_ok_ = config["tooltip-format-ok"].asString();
}
if (config["tooltip-unit-format"].isString()) {
tooltip_unit_format_ = config["tooltip-unit-format"].asString();
}
/* Default to enable both "system" and "user". */
if (!config["system"].isBool() || config["system"].asBool()) {
system_proxy = Gio::DBus::Proxy::create_for_bus_sync(
system_props_proxy_ = Gio::DBus::Proxy::create_for_bus_sync(
Gio::DBus::BusType::BUS_TYPE_SYSTEM, "org.freedesktop.systemd1",
"/org/freedesktop/systemd1", "org.freedesktop.DBus.Properties");
if (!system_proxy) {
if (!system_props_proxy_) {
throw std::runtime_error("Unable to connect to systemwide systemd DBus!");
}
system_proxy->signal_signal().connect(sigc::mem_fun(*this, &SystemdFailedUnits::notify_cb));
system_props_proxy_->signal_signal().connect(
sigc::mem_fun(*this, &SystemdFailedUnits::notify_cb));
try {
system_manager_proxy_ = Gio::DBus::Proxy::create_for_bus_sync(
Gio::DBus::BusType::BUS_TYPE_SYSTEM, "org.freedesktop.systemd1",
"/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager");
} catch (const Glib::Error& e) {
spdlog::warn("Unable to connect to systemwide systemd Manager interface: {}",
e.what().c_str());
}
}
if (!config["user"].isBool() || config["user"].asBool()) {
user_proxy = Gio::DBus::Proxy::create_for_bus_sync(
user_props_proxy_ = Gio::DBus::Proxy::create_for_bus_sync(
Gio::DBus::BusType::BUS_TYPE_SESSION, "org.freedesktop.systemd1",
"/org/freedesktop/systemd1", "org.freedesktop.DBus.Properties");
if (!user_proxy) {
if (!user_props_proxy_) {
throw std::runtime_error("Unable to connect to user systemd DBus!");
}
user_proxy->signal_signal().connect(sigc::mem_fun(*this, &SystemdFailedUnits::notify_cb));
user_props_proxy_->signal_signal().connect(
sigc::mem_fun(*this, &SystemdFailedUnits::notify_cb));
try {
user_manager_proxy_ = Gio::DBus::Proxy::create_for_bus_sync(
Gio::DBus::BusType::BUS_TYPE_SESSION, "org.freedesktop.systemd1",
"/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager");
} catch (const Glib::Error& e) {
spdlog::warn("Unable to connect to user systemd Manager interface: {}", e.what().c_str());
}
}
if (!user_props_proxy_ && !system_props_proxy_)
throw std::runtime_error("Neither system nor user status is requested.");
updateData();
/* Always update for the first time. */
dp.emit();
}
SystemdFailedUnits::~SystemdFailedUnits() {
if (system_proxy) system_proxy.reset();
if (user_proxy) user_proxy.reset();
}
auto SystemdFailedUnits::notify_cb(const Glib::ustring& sender_name,
const Glib::ustring& signal_name,
const Glib::VariantContainerBase& arguments) -> void {
if (signal_name == "PropertiesChanged" && !update_pending) {
update_pending = true;
if (signal_name == "PropertiesChanged" && !update_pending_) {
update_pending_ = true;
/* The fail count may fluctuate due to restarting. */
Glib::signal_timeout().connect_once(sigc::mem_fun(*this, &SystemdFailedUnits::updateData),
UPDATE_DEBOUNCE_TIME_MS);
@@ -71,15 +106,15 @@ auto SystemdFailedUnits::notify_cb(const Glib::ustring& sender_name,
void SystemdFailedUnits::RequestSystemState() {
auto load = [](const char* kind, Glib::RefPtr<Gio::DBus::Proxy>& proxy) -> std::string {
try {
if (!proxy) return "unknown";
if (!proxy) return "ignored";
auto parameters = Glib::VariantContainerBase(
g_variant_new("(ss)", "org.freedesktop.systemd1.Manager", "SystemState"));
Glib::VariantContainerBase data = proxy->call_sync("Get", parameters);
if (data && data.is_of_type(Glib::VariantType("(v)"))) {
Glib::VariantBase variant;
g_variant_get(data.gobj_copy(), "(v)", &variant);
g_variant_get(const_cast<GVariant*>(data.gobj()), "(v)", &variant);
if (variant && variant.is_of_type(Glib::VARIANT_TYPE_STRING)) {
return g_variant_get_string(variant.gobj_copy(), NULL);
return g_variant_get_string(const_cast<GVariant*>(variant.gobj()), NULL);
}
}
} catch (Glib::Error& e) {
@@ -88,12 +123,14 @@ void SystemdFailedUnits::RequestSystemState() {
return "unknown";
};
system_state = load("systemwide", system_proxy);
user_state = load("user", user_proxy);
if (system_state == "running" && user_state == "running")
overall_state = "ok";
system_state_ = load("systemwide", system_props_proxy_);
user_state_ = load("user", user_props_proxy_);
if ((system_state_ == "running" || system_state_ == "ignored") &&
(user_state_ == "running" || user_state_ == "ignored"))
overall_state_ = "ok";
else
overall_state = "degraded";
overall_state_ = "degraded";
}
void SystemdFailedUnits::RequestFailedUnits() {
@@ -105,9 +142,9 @@ void SystemdFailedUnits::RequestFailedUnits() {
Glib::VariantContainerBase data = proxy->call_sync("Get", parameters);
if (data && data.is_of_type(Glib::VariantType("(v)"))) {
Glib::VariantBase variant;
g_variant_get(data.gobj_copy(), "(v)", &variant);
g_variant_get(const_cast<GVariant*>(data.gobj()), "(v)", &variant);
if (variant && variant.is_of_type(Glib::VARIANT_TYPE_UINT32)) {
return g_variant_get_uint32(variant.gobj_copy());
return g_variant_get_uint32(const_cast<GVariant*>(variant.gobj()));
}
}
} catch (Glib::Error& e) {
@@ -116,46 +153,153 @@ void SystemdFailedUnits::RequestFailedUnits() {
return 0;
};
nr_failed_system = load("systemwide", system_proxy);
nr_failed_user = load("user", user_proxy);
nr_failed = nr_failed_system + nr_failed_user;
nr_failed_system_ = load("systemwide", system_props_proxy_);
nr_failed_user_ = load("user", user_props_proxy_);
nr_failed_ = nr_failed_system_ + nr_failed_user_;
}
void SystemdFailedUnits::RequestFailedUnitsList() {
failed_units_.clear();
if (!tooltipEnabled() || nr_failed_ == 0) {
return;
}
if (system_manager_proxy_) {
auto units = LoadFailedUnitsList("systemwide", system_manager_proxy_, "system");
failed_units_.insert(failed_units_.end(), units.begin(), units.end());
}
if (user_manager_proxy_) {
auto units = LoadFailedUnitsList("user", user_manager_proxy_, "user");
failed_units_.insert(failed_units_.end(), units.begin(), units.end());
}
}
auto SystemdFailedUnits::LoadFailedUnitsList(const char* kind,
Glib::RefPtr<Gio::DBus::Proxy>& proxy,
const std::string& scope) -> std::vector<FailedUnit> {
// org.freedesktop.systemd1.Manager.ListUnits returns
// (name, description, load_state, active_state, sub_state, followed, unit_path, job_id,
// job_type, job_path).
using UnitRow = std::tuple<Glib::ustring, Glib::ustring, Glib::ustring, Glib::ustring,
Glib::ustring, Glib::ustring, Glib::DBusObjectPathString, guint32,
Glib::ustring, Glib::DBusObjectPathString>;
using ListUnitsReply = Glib::Variant<std::tuple<std::vector<UnitRow>>>;
std::vector<FailedUnit> units;
if (!proxy) {
return units;
}
try {
auto data = proxy->call_sync("ListUnits");
if (!data) return units;
if (!data.is_of_type(ListUnitsReply::variant_type())) {
spdlog::warn("Unexpected DBus signature for ListUnits: {}", data.get_type_string());
return units;
}
auto [rows] = Glib::VariantBase::cast_dynamic<ListUnitsReply>(data).get();
for (const auto& row : rows) {
const auto& name = std::get<0>(row);
const auto& description = std::get<1>(row);
const auto& load_state = std::get<2>(row);
const auto& active_state = std::get<3>(row);
const auto& sub_state = std::get<4>(row);
if (active_state == "failed" || sub_state == "failed") {
units.push_back({name, description, load_state, active_state, sub_state, scope});
}
}
} catch (const Glib::Error& e) {
spdlog::error("Failed to list {} units: {}", kind, e.what().c_str());
}
return units;
}
std::string SystemdFailedUnits::BuildTooltipFailedList() const {
if (failed_units_.empty()) {
return "";
}
std::string list;
list.reserve(failed_units_.size() * 16);
bool first = true;
for (const auto& unit : failed_units_) {
try {
auto line = fmt::format(
fmt::runtime(tooltip_unit_format_),
fmt::arg("name", Glib::Markup::escape_text(unit.name).raw()),
fmt::arg("description", Glib::Markup::escape_text(unit.description).raw()),
fmt::arg("load_state", unit.load_state), fmt::arg("active_state", unit.active_state),
fmt::arg("sub_state", unit.sub_state), fmt::arg("scope", unit.scope));
if (!first) {
list += "\n";
}
first = false;
list += "- ";
list += line;
} catch (const std::exception& e) {
spdlog::warn("Failed to format tooltip for unit {}: {}", unit.name, e.what());
}
}
return list;
}
void SystemdFailedUnits::updateData() {
update_pending = false;
update_pending_ = false;
RequestSystemState();
if (overall_state == "degraded") RequestFailedUnits();
if (overall_state_ == "degraded") {
RequestFailedUnits();
RequestFailedUnitsList();
} else {
nr_failed_system_ = nr_failed_user_ = nr_failed_ = 0;
failed_units_.clear();
}
dp.emit();
}
auto SystemdFailedUnits::update() -> void {
if (last_status == overall_state) return;
// Hide if needed.
if (overall_state == "ok" && hide_on_ok) {
if (overall_state_ == "ok" && hide_on_ok_) {
event_box_.set_visible(false);
last_status_ = overall_state_;
return;
}
event_box_.set_visible(true);
// Set state class.
if (!last_status.empty() && label_.get_style_context()->has_class(last_status)) {
label_.get_style_context()->remove_class(last_status);
if (!last_status_.empty() && label_.get_style_context()->has_class(last_status_)) {
label_.get_style_context()->remove_class(last_status_);
}
if (!label_.get_style_context()->has_class(overall_state)) {
label_.get_style_context()->add_class(overall_state);
if (!label_.get_style_context()->has_class(overall_state_)) {
label_.get_style_context()->add_class(overall_state_);
}
last_status = overall_state;
last_status_ = overall_state_;
label_.set_markup(fmt::format(
fmt::runtime(nr_failed == 0 ? format_ok : format_), fmt::arg("nr_failed", nr_failed),
fmt::arg("nr_failed_system", nr_failed_system), fmt::arg("nr_failed_user", nr_failed_user),
fmt::arg("system_state", system_state), fmt::arg("user_state", user_state),
fmt::arg("overall_state", overall_state)));
fmt::runtime(nr_failed_ == 0 ? format_ok_ : format_), fmt::arg("nr_failed", nr_failed_),
fmt::arg("nr_failed_system", nr_failed_system_), fmt::arg("nr_failed_user", nr_failed_user_),
fmt::arg("system_state", system_state_), fmt::arg("user_state", user_state_),
fmt::arg("overall_state", overall_state_)));
if (tooltipEnabled()) {
std::string failed_list = BuildTooltipFailedList();
auto tooltip_template = overall_state_ == "ok" ? tooltip_format_ok_ : tooltip_format_;
if (!tooltip_template.empty()) {
label_.set_tooltip_markup(fmt::format(
fmt::runtime(tooltip_template), fmt::arg("nr_failed", nr_failed_),
fmt::arg("nr_failed_system", nr_failed_system_),
fmt::arg("nr_failed_user", nr_failed_user_), fmt::arg("system_state", system_state_),
fmt::arg("user_state", user_state_), fmt::arg("overall_state", overall_state_),
fmt::arg("failed_units_list", failed_list)));
} else {
label_.set_tooltip_text("");
}
}
ALabel::update();
}
+5 -1
View File
@@ -133,7 +133,7 @@ auto waybar::modules::Temperature::update() -> void {
if (config_["tooltip-format"].isString()) {
tooltip_format = config_["tooltip-format"].asString();
}
label_.set_tooltip_text(fmt::format(
label_.set_tooltip_markup(fmt::format(
fmt::runtime(tooltip_format), fmt::arg("temperatureC", temperature_c),
fmt::arg("temperatureF", temperature_f), fmt::arg("temperatureK", temperature_k)));
}
@@ -187,3 +187,7 @@ bool waybar::modules::Temperature::isCritical(uint16_t temperature_c) {
return config_["critical-threshold"].isInt() &&
temperature_c >= config_["critical-threshold"].asInt();
}
void waybar::modules::Temperature::suspend() { thread_.pause(); }
void waybar::modules::Temperature::resume() { thread_.resume(); }
+50 -46
View File
@@ -6,7 +6,7 @@
namespace waybar::modules {
UPower::UPower(const std::string &id, const Json::Value &config)
UPower::UPower(const std::string& id, const Json::Value& config)
: AIconLabel(config, "upower", id, "{percentage}", 0, true, true, true), sleeping_{false} {
box_.set_name(name_);
box_.set_spacing(0);
@@ -59,10 +59,13 @@ UPower::UPower(const std::string &id, const Json::Value &config)
sigc::mem_fun(*this, &UPower::getConn_cb));
// Make UPower client
GError **gErr = NULL;
upClient_ = up_client_new_full(NULL, gErr);
if (upClient_ == NULL)
spdlog::error("Upower. UPower client connection error. {}", (*gErr)->message);
GError* gErr = NULL;
upClient_ = up_client_new_full(NULL, &gErr);
if (upClient_ == NULL) {
spdlog::error("Upower. UPower client connection error. {}",
gErr ? gErr->message : "unknown error");
if (gErr) g_error_free(gErr);
}
// Subscribe UPower events
g_signal_connect(upClient_, "device-added", G_CALLBACK(deviceAdded_cb), this);
@@ -92,7 +95,7 @@ UPower::~UPower() {
removeDevices();
}
static const std::string getDeviceStatus(UpDeviceState &state) {
static std::string_view getDeviceStatus(UpDeviceState& state) {
switch (state) {
case UP_DEVICE_STATE_CHARGING:
case UP_DEVICE_STATE_PENDING_CHARGE:
@@ -109,7 +112,7 @@ static const std::string getDeviceStatus(UpDeviceState &state) {
}
}
static const std::string getDeviceIcon(UpDeviceKind &kind) {
static std::string_view getDeviceIcon(UpDeviceKind& kind) {
switch (kind) {
case UP_DEVICE_KIND_LINE_POWER:
return "ac-adapter-symbolic";
@@ -209,7 +212,8 @@ auto UPower::update() -> void {
// Remove last status if it exists
if (!lastStatus_.empty() && box_.get_style_context()->has_class(lastStatus_))
box_.get_style_context()->remove_class(lastStatus_);
if (!box_.get_style_context()->has_class(status)) box_.get_style_context()->add_class(status);
if (!box_.get_style_context()->has_class(std::string(status)))
box_.get_style_context()->add_class(std::string(status));
lastStatus_ = status;
if (devices_.size() == 0 && !upDeviceValid && hideIfEmpty_) {
@@ -222,7 +226,7 @@ auto UPower::update() -> void {
label_.set_markup(getText(upDevice_, format_));
// Set icon
if (upDevice_.icon_name == NULL || !gtkTheme_->has_icon(upDevice_.icon_name))
upDevice_.icon_name = (char *)NO_BATTERY.c_str();
upDevice_.icon_name = (char*)NO_BATTERY.c_str();
image_.set_from_icon_name(upDevice_.icon_name, Gtk::ICON_SIZE_INVALID);
box_.show();
@@ -231,7 +235,7 @@ auto UPower::update() -> void {
ALabel::update();
}
void UPower::getConn_cb(Glib::RefPtr<Gio::AsyncResult> &result) {
void UPower::getConn_cb(Glib::RefPtr<Gio::AsyncResult>& result) {
try {
conn_ = Gio::DBus::Connection::get_finish(result);
// Subscribe DBUs events
@@ -239,26 +243,26 @@ void UPower::getConn_cb(Glib::RefPtr<Gio::AsyncResult> &result) {
"org.freedesktop.login1", "org.freedesktop.login1.Manager",
"PrepareForSleep", "/org/freedesktop/login1");
} catch (const Glib::Error &e) {
} catch (const Glib::Error& e) {
spdlog::error("Upower. DBus connection error. {}", e.what().c_str());
}
}
void UPower::onAppear(const Glib::RefPtr<Gio::DBus::Connection> &conn, const Glib::ustring &name,
const Glib::ustring &name_owner) {
void UPower::onAppear(const Glib::RefPtr<Gio::DBus::Connection>& conn, const Glib::ustring& name,
const Glib::ustring& name_owner) {
upRunning_ = true;
}
void UPower::onVanished(const Glib::RefPtr<Gio::DBus::Connection> &conn,
const Glib::ustring &name) {
void UPower::onVanished(const Glib::RefPtr<Gio::DBus::Connection>& conn,
const Glib::ustring& name) {
upRunning_ = false;
}
void UPower::prepareForSleep_cb(const Glib::RefPtr<Gio::DBus::Connection> &connection,
const Glib::ustring &sender_name, const Glib::ustring &object_path,
const Glib::ustring &interface_name,
const Glib::ustring &signal_name,
const Glib::VariantContainerBase &parameters) {
void UPower::prepareForSleep_cb(const Glib::RefPtr<Gio::DBus::Connection>& connection,
const Glib::ustring& sender_name, const Glib::ustring& object_path,
const Glib::ustring& interface_name,
const Glib::ustring& signal_name,
const Glib::VariantContainerBase& parameters) {
if (parameters.is_of_type(Glib::VariantType("(b)"))) {
Glib::Variant<bool> sleeping;
parameters.get_child(sleeping, 0);
@@ -273,33 +277,33 @@ void UPower::prepareForSleep_cb(const Glib::RefPtr<Gio::DBus::Connection> &conne
}
}
void UPower::deviceAdded_cb(UpClient *client, UpDevice *device, gpointer data) {
UPower *up{static_cast<UPower *>(data)};
void UPower::deviceAdded_cb(UpClient* client, UpDevice* device, gpointer data) {
UPower* up{static_cast<UPower*>(data)};
up->addDevice(device);
up->setDisplayDevice();
// Update the widget
up->dp.emit();
}
void UPower::deviceRemoved_cb(UpClient *client, const gchar *objectPath, gpointer data) {
UPower *up{static_cast<UPower *>(data)};
void UPower::deviceRemoved_cb(UpClient* client, const gchar* objectPath, gpointer data) {
UPower* up{static_cast<UPower*>(data)};
up->removeDevice(objectPath);
up->setDisplayDevice();
// Update the widget
up->dp.emit();
}
void UPower::deviceNotify_cb(UpDevice *device, GParamSpec *pspec, gpointer data) {
UPower *up{static_cast<UPower *>(data)};
void UPower::deviceNotify_cb(UpDevice* device, GParamSpec* pspec, gpointer data) {
UPower* up{static_cast<UPower*>(data)};
// Update the widget
up->dp.emit();
}
void UPower::addDevice(UpDevice *device) {
void UPower::addDevice(UpDevice* device) {
std::lock_guard<std::mutex> guard{mutex_};
if (G_IS_OBJECT(device)) {
const gchar *objectPath{up_device_get_object_path(device)};
const gchar* objectPath{up_device_get_object_path(device)};
// Due to the device getting cleared after this event is fired, we
// create a new object pointing to its objectPath
@@ -322,7 +326,7 @@ void UPower::addDevice(UpDevice *device) {
}
}
void UPower::removeDevice(const gchar *objectPath) {
void UPower::removeDevice(const gchar* objectPath) {
std::lock_guard<std::mutex> guard{mutex_};
if (devices_.find(objectPath) != devices_.cend()) {
auto upDevice{devices_[objectPath]};
@@ -348,10 +352,10 @@ void UPower::resetDevices() {
removeDevices();
// Adds all devices
GPtrArray *newDevices = up_client_get_devices2(upClient_);
GPtrArray* newDevices = up_client_get_devices2(upClient_);
if (newDevices != NULL)
for (guint i{0}; i < newDevices->len; ++i) {
UpDevice *device{(UpDevice *)g_ptr_array_index(newDevices, i)};
UpDevice* device{(UpDevice*)g_ptr_array_index(newDevices, i)};
if (device && G_IS_OBJECT(device)) addDevice(device);
}
}
@@ -372,8 +376,8 @@ void UPower::setDisplayDevice() {
up_client_get_devices2(upClient_),
[](gpointer data, gpointer user_data) {
upDevice_output upDevice;
auto thisPtr{static_cast<UPower *>(user_data)};
upDevice.upDevice = static_cast<UpDevice *>(data);
auto thisPtr{static_cast<UPower*>(user_data)};
upDevice.upDevice = static_cast<UpDevice*>(data);
thisPtr->getUpDeviceInfo(upDevice);
upDevice_output displayDevice{NULL};
if (!thisPtr->nativePath_.empty()) {
@@ -399,7 +403,7 @@ void UPower::setDisplayDevice() {
g_signal_connect(upDevice_.upDevice, "notify", G_CALLBACK(deviceNotify_cb), this);
}
void UPower::getUpDeviceInfo(upDevice_output &upDevice_) {
void UPower::getUpDeviceInfo(upDevice_output& upDevice_) {
if (upDevice_.upDevice != NULL && G_IS_OBJECT(upDevice_.upDevice)) {
g_object_get(upDevice_.upDevice, "kind", &upDevice_.kind, "state", &upDevice_.state,
"percentage", &upDevice_.percentage, "icon-name", &upDevice_.icon_name,
@@ -416,7 +420,7 @@ native_path: \"{7}\". model: \"{8}\"",
}
}
const Glib::ustring UPower::getText(const upDevice_output &upDevice_, const std::string &format) {
const Glib::ustring UPower::getText(const upDevice_output& upDevice_, const std::string& format) {
Glib::ustring ret{""};
if (upDevice_.upDevice != NULL) {
std::string timeStr{""};
@@ -445,11 +449,11 @@ const Glib::ustring UPower::getText(const upDevice_output &upDevice_, const std:
}
bool UPower::queryTooltipCb(int x, int y, bool keyboard_tooltip,
const Glib::RefPtr<Gtk::Tooltip> &tooltip) {
const Glib::RefPtr<Gtk::Tooltip>& tooltip) {
std::lock_guard<std::mutex> guard{mutex_};
// Clear content box
contentBox_.forall([this](Gtk::Widget &wg) { contentBox_.remove(wg); });
contentBox_.forall([this](Gtk::Widget& wg) { contentBox_.remove(wg); });
// Fill content box with the content
for (auto pairDev : devices_) {
@@ -459,33 +463,33 @@ bool UPower::queryTooltipCb(int x, int y, bool keyboard_tooltip,
if (pairDev.second.kind != UpDeviceKind::UP_DEVICE_KIND_UNKNOWN &&
pairDev.second.kind != UpDeviceKind::UP_DEVICE_KIND_LINE_POWER) {
// Make box record
Gtk::Box *boxRec{new Gtk::Box{box_.get_orientation(), tooltip_spacing_}};
Gtk::Box* boxRec{new Gtk::Box{box_.get_orientation(), tooltip_spacing_}};
contentBox_.add(*boxRec);
Gtk::Box *boxDev{new Gtk::Box{box_.get_orientation()}};
Gtk::Box *boxUsr{new Gtk::Box{box_.get_orientation()}};
Gtk::Box* boxDev{new Gtk::Box{box_.get_orientation()}};
Gtk::Box* boxUsr{new Gtk::Box{box_.get_orientation()}};
boxRec->add(*boxDev);
boxRec->add(*boxUsr);
// Construct device box
// Set icon from kind
std::string iconNameDev{getDeviceIcon(pairDev.second.kind)};
if (!gtkTheme_->has_icon(iconNameDev)) iconNameDev = (char *)NO_BATTERY.c_str();
Gtk::Image *iconDev{new Gtk::Image{}};
if (!gtkTheme_->has_icon(iconNameDev)) iconNameDev = (char*)NO_BATTERY.c_str();
Gtk::Image* iconDev{new Gtk::Image{}};
iconDev->set_from_icon_name(iconNameDev, Gtk::ICON_SIZE_INVALID);
iconDev->set_pixel_size(iconSize_);
boxDev->add(*iconDev);
// Set label from model
Gtk::Label *labelDev{new Gtk::Label{pairDev.second.model}};
Gtk::Label* labelDev{new Gtk::Label{pairDev.second.model}};
boxDev->add(*labelDev);
// Construct user box
// Set icon from icon state
if (pairDev.second.icon_name == NULL || !gtkTheme_->has_icon(pairDev.second.icon_name))
pairDev.second.icon_name = (char *)NO_BATTERY.c_str();
Gtk::Image *iconTooltip{new Gtk::Image{}};
pairDev.second.icon_name = (char*)NO_BATTERY.c_str();
Gtk::Image* iconTooltip{new Gtk::Image{}};
iconTooltip->set_from_icon_name(pairDev.second.icon_name, Gtk::ICON_SIZE_INVALID);
iconTooltip->set_pixel_size(iconSize_);
boxUsr->add(*iconTooltip);
// Set markup text
Gtk::Label *labelTooltip{new Gtk::Label{}};
Gtk::Label* labelTooltip{new Gtk::Label{}};
labelTooltip->set_markup(getText(pairDev.second, tooltipFormat_));
boxUsr->add(*labelTooltip);
}
+34 -17
View File
@@ -9,6 +9,7 @@
#include <bit>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <ranges>
#include <thread>
@@ -26,13 +27,19 @@ inline auto byteswap(uint32_t x) -> uint32_t {
auto pack_and_write(Sock& sock, std::string&& buf) -> void {
uint32_t len = buf.size();
if constexpr (std::endian::native != std::endian::little) len = byteswap(len);
(void)write(sock.fd, &len, 4);
(void)write(sock.fd, buf.data(), buf.size());
(void)write(sock, &len, 4);
(void)write(sock, buf.data(), buf.size());
}
auto read_exact(Sock& sock, size_t n) -> std::string {
auto buf = std::string(n, 0);
for (size_t i = 0; i < n;) i += read(sock.fd, &buf[i], n - i);
for (size_t i = 0; i < n;) {
auto r = read(sock, &buf[i], n - i);
if (r <= 0) {
throw std::runtime_error("Wayfire IPC: read failed");
}
i += static_cast<size_t>(r);
}
return buf;
}
@@ -53,6 +60,9 @@ auto State::Wset::locate_ws(const Json::Value& geo) -> Workspace& {
}
auto State::Wset::locate_ws(const Json::Value& geo) const -> const Workspace& {
if (!output.has_value()) {
throw std::runtime_error("Wayfire IPC: wset has no output assigned");
}
const auto& out = output.value().get();
auto [qx, rx] = std::div(geo["x"].asInt(), out.w);
auto [qy, ry] = std::div(geo["y"].asInt(), out.h);
@@ -88,7 +98,10 @@ auto State::update_view(const Json::Value& view) -> void {
auto IPC::get_instance() -> std::shared_ptr<IPC> {
auto p = instance.lock();
if (!p) instance = p = std::shared_ptr<IPC>(new IPC);
if (!p) {
instance = p = std::shared_ptr<IPC>(new IPC);
p->start();
}
return p;
}
@@ -98,7 +111,7 @@ auto IPC::connect() -> Sock {
throw std::runtime_error{"Wayfire IPC: ipc not available"};
}
auto sock = socket(AF_UNIX, SOCK_STREAM, 0);
util::ScopedFd sock(socket(AF_UNIX, SOCK_STREAM, 0));
if (sock == -1) {
throw std::runtime_error{"Wayfire IPC: socket() failed"};
}
@@ -108,15 +121,16 @@ auto IPC::connect() -> Sock {
addr.sun_path[sizeof(addr.sun_path) - 1] = 0;
if (::connect(sock, (const sockaddr*)&addr, sizeof(addr)) == -1) {
close(sock);
throw std::runtime_error{"Wayfire IPC: connect() failed"};
}
return {sock};
return sock;
}
auto IPC::receive(Sock& sock) -> Json::Value {
auto len = *reinterpret_cast<uint32_t*>(read_exact(sock, 4).data());
auto len_buf = read_exact(sock, 4);
uint32_t len;
std::memcpy(&len, len_buf.data(), sizeof(len));
if constexpr (std::endian::native != std::endian::little) len = byteswap(len);
auto buf = read_exact(sock, len);
@@ -153,15 +167,15 @@ auto IPC::start() -> void {
send("window-rules/get-focused-view", {});
send("window-rules/get-focused-output", {});
std::thread([&] {
std::thread([self = shared_from_this()] {
auto sock = connect();
{
Json::Value json;
json["method"] = "window-rules/events/watch";
pack_and_write(sock, Json::writeString(writer_builder, json));
if (receive(sock)["result"] != "ok") {
pack_and_write(sock, Json::writeString(self->writer_builder, json));
if (self->receive(sock)["result"] != "ok") {
spdlog::error(
"Wayfire IPC: method \"window-rules/events/watch\""
" have failed");
@@ -169,10 +183,10 @@ auto IPC::start() -> void {
}
}
while (auto json = receive(sock)) {
while (auto json = self->receive(sock)) {
auto ev = json["event"].asString();
spdlog::debug("Wayfire IPC: received event \"{}\"", ev);
root_event_handler(ev, json);
self->root_event_handler(ev, json);
}
}).detach();
}
@@ -333,10 +347,13 @@ auto IPC::update_state_handler(const std::string& event, const Json::Value& data
if (event == "output-wset-changed") {
// data: { event, new-wset: wset.name, output: id, new-wset-data: wset, output-data: output }
auto& output = state.outputs.at(data["output-data"]["name"].asString());
auto wset_idx = data["new-wset-data"]["index"].asUInt();
state.wsets.at(wset_idx).output = output;
output.wset_idx = wset_idx;
try {
auto& output = state.outputs.at(data["output-data"]["name"].asString());
auto wset_idx = data["new-wset-data"]["index"].asUInt();
state.wsets.at(wset_idx).output = output;
output.wset_idx = wset_idx;
} catch (const std::exception&) {
}
return;
}
+6 -2
View File
@@ -34,8 +34,12 @@ auto Window::update() -> void {
auto Window::update_icon_label() -> void {
auto _ = ipc->lock_state();
const auto& output = ipc->get_outputs().at(bar_.output->name);
const auto& wset = ipc->get_wsets().at(output.wset_idx);
auto out_it = ipc->get_outputs().find(bar_.output->name);
if (out_it == ipc->get_outputs().end()) return;
const auto& output = out_it->second;
auto wset_it = ipc->get_wsets().find(output.wset_idx);
if (wset_it == ipc->get_wsets().end()) return;
const auto& wset = wset_it->second;
const auto& views = ipc->get_views();
auto ctx = bar_.window.get_style_context();
+12 -4
View File
@@ -70,8 +70,12 @@ auto Workspaces::handleScroll(GdkEventScroll* e) -> bool {
Json::Value data;
{
auto _ = ipc->lock_state();
const auto& output = ipc->get_outputs().at(bar_.output->name);
const auto& wset = ipc->get_wsets().at(output.wset_idx);
auto out_it = ipc->get_outputs().find(bar_.output->name);
if (out_it == ipc->get_outputs().end()) return true;
const auto& output = out_it->second;
auto wset_it = ipc->get_wsets().find(output.wset_idx);
if (wset_it == ipc->get_wsets().end()) return true;
const auto& wset = wset_it->second;
auto n = wset.ws_w * wset.ws_h;
auto i = (wset.ws_idx() + delta + n) % n;
data["x"] = Json::Value((uint64_t)i % wset.ws_w);
@@ -92,8 +96,12 @@ auto Workspaces::update_box() -> void {
auto _ = ipc->lock_state();
const auto& output_name = bar_.output->name;
const auto& output = ipc->get_outputs().at(output_name);
const auto& wset = ipc->get_wsets().at(output.wset_idx);
auto out_it = ipc->get_outputs().find(output_name);
if (out_it == ipc->get_outputs().end()) return;
const auto& output = out_it->second;
auto wset_it = ipc->get_wsets().find(output.wset_idx);
if (wset_it == ipc->get_wsets().end()) return;
const auto& wset = wset_it->second;
auto output_focused = ipc->get_focused_output_name() == output_name;
auto ws_w = wset.ws_w;
+21 -9
View File
@@ -54,6 +54,15 @@ waybar::modules::Wireplumber::Wireplumber(const std::string& id, const Json::Val
waybar::modules::Wireplumber::~Wireplumber() {
waybar::modules::Wireplumber::modules.remove(this);
if (mixer_api_ != nullptr) {
g_signal_handlers_disconnect_by_data(mixer_api_, this);
}
if (def_nodes_api_ != nullptr) {
g_signal_handlers_disconnect_by_data(def_nodes_api_, this);
}
if (om_ != nullptr) {
g_signal_handlers_disconnect_by_data(om_, this);
}
wp_core_disconnect(wp_core_);
g_clear_pointer(&apis_, g_ptr_array_unref);
g_clear_object(&om_);
@@ -81,7 +90,7 @@ void waybar::modules::Wireplumber::updateNodeName(waybar::modules::Wireplumber*
if (proxy == nullptr) {
auto err = fmt::format("Object '{}' not found\n", id);
spdlog::error("[{}]: {}", self->name_, err);
throw std::runtime_error(err);
return;
}
g_autoptr(WpProperties) properties =
@@ -153,7 +162,7 @@ void waybar::modules::Wireplumber::updateVolume(waybar::modules::Wireplumber* se
if (variant == nullptr) {
auto err = fmt::format("Node {} does not support volume\n", id);
spdlog::error("[{}]: {}", self->name_, err);
throw std::runtime_error(err);
return;
}
g_variant_lookup(variant, "volume", "d", &self->volume_);
@@ -202,6 +211,7 @@ void waybar::modules::Wireplumber::onMixerChanged(waybar::modules::Wireplumber*
return;
}
}
return;
}
spdlog::warn("[{}]: (onMixerChanged: {}) - Object with id {} not found", self->name_,
@@ -287,14 +297,14 @@ void waybar::modules::Wireplumber::onObjectManagerInstalled(waybar::modules::Wir
if (self->def_nodes_api_ == nullptr) {
spdlog::error("[{}]: default nodes api is not loaded.", self->name_);
throw std::runtime_error("Default nodes API is not loaded\n");
return;
}
self->mixer_api_ = wp_plugin_find(self->wp_core_, "mixer-api");
if (self->mixer_api_ == nullptr) {
spdlog::error("[{}]: mixer api is not loaded.", self->name_);
throw std::runtime_error("Mixer api is not loaded\n");
return;
}
// Get default sink
@@ -336,7 +346,7 @@ void waybar::modules::Wireplumber::onPluginActivated(WpObject* p, GAsyncResult*
if (wp_object_activate_finish(p, res, &error) == 0) {
spdlog::error("[{}]: error activating plugin: {}", self->name_, error->message);
throw std::runtime_error(error->message);
return;
}
if (--self->pending_plugins_ == 0) {
@@ -373,7 +383,7 @@ void waybar::modules::Wireplumber::onDefaultNodesApiLoaded(WpObject* p, GAsyncRe
if (success == FALSE) {
spdlog::error("[{}]: default nodes API load failed", self->name_);
throw std::runtime_error(error->message);
return;
}
spdlog::debug("[{}]: loaded default nodes api", self->name_);
g_ptr_array_add(self->apis_, wp_plugin_find(self->wp_core_, "default-nodes-api"));
@@ -392,7 +402,7 @@ void waybar::modules::Wireplumber::onMixerApiLoaded(WpObject* p, GAsyncResult* r
if (success == FALSE) {
spdlog::error("[{}]: mixer API load failed", self->name_);
throw std::runtime_error(error->message);
return;
}
spdlog::debug("[{}]: loaded mixer API", self->name_);
@@ -479,12 +489,12 @@ auto waybar::modules::Wireplumber::update() -> void {
}
if (!tooltipFormat.empty()) {
label_.set_tooltip_text(fmt::format(
label_.set_tooltip_markup(fmt::format(
fmt::runtime(tooltipFormat), fmt::arg("node_name", node_name_), fmt::arg("volume", vol),
fmt::arg("icon", getIcon(vol)), fmt::arg("format_source", formatted_source),
fmt::arg("source_volume", source_vol), fmt::arg("source_desc", source_name_)));
} else {
label_.set_tooltip_text(node_name_);
label_.set_tooltip_markup(node_name_);
}
}
@@ -524,9 +534,11 @@ bool waybar::modules::Wireplumber::handleScroll(GdkEventScroll* e) {
}
}
if (newVol != volume_) {
if (mixer_api_ == nullptr) return true;
GVariant* variant = g_variant_new_double(newVol);
gboolean ret;
g_signal_emit_by_name(mixer_api_, "set-volume", node_id_, variant, &ret);
g_variant_unref(variant);
}
return true;
}
+121 -85
View File
@@ -29,42 +29,42 @@ namespace waybar::modules::wlr {
/* Task class implementation */
uint32_t Task::global_id = 0;
static void tl_handle_title(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle,
const char *title) {
return static_cast<Task *>(data)->handle_title(title);
static void tl_handle_title(void* data, struct zwlr_foreign_toplevel_handle_v1* handle,
const char* title) {
return static_cast<Task*>(data)->handle_title(title);
}
static void tl_handle_app_id(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle,
const char *app_id) {
return static_cast<Task *>(data)->handle_app_id(app_id);
static void tl_handle_app_id(void* data, struct zwlr_foreign_toplevel_handle_v1* handle,
const char* app_id) {
return static_cast<Task*>(data)->handle_app_id(app_id);
}
static void tl_handle_output_enter(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle,
struct wl_output *output) {
return static_cast<Task *>(data)->handle_output_enter(output);
static void tl_handle_output_enter(void* data, struct zwlr_foreign_toplevel_handle_v1* handle,
struct wl_output* output) {
return static_cast<Task*>(data)->handle_output_enter(output);
}
static void tl_handle_output_leave(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle,
struct wl_output *output) {
return static_cast<Task *>(data)->handle_output_leave(output);
static void tl_handle_output_leave(void* data, struct zwlr_foreign_toplevel_handle_v1* handle,
struct wl_output* output) {
return static_cast<Task*>(data)->handle_output_leave(output);
}
static void tl_handle_state(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle,
struct wl_array *state) {
return static_cast<Task *>(data)->handle_state(state);
static void tl_handle_state(void* data, struct zwlr_foreign_toplevel_handle_v1* handle,
struct wl_array* state) {
return static_cast<Task*>(data)->handle_state(state);
}
static void tl_handle_done(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle) {
return static_cast<Task *>(data)->handle_done();
static void tl_handle_done(void* data, struct zwlr_foreign_toplevel_handle_v1* handle) {
return static_cast<Task*>(data)->handle_done();
}
static void tl_handle_parent(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle,
struct zwlr_foreign_toplevel_handle_v1 *parent) {
static void tl_handle_parent(void* data, struct zwlr_foreign_toplevel_handle_v1* handle,
struct zwlr_foreign_toplevel_handle_v1* parent) {
/* This is explicitly left blank */
}
static void tl_handle_closed(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle) {
return static_cast<Task *>(data)->handle_closed();
static void tl_handle_closed(void* data, struct zwlr_foreign_toplevel_handle_v1* handle) {
return static_cast<Task*>(data)->handle_closed();
}
static const struct zwlr_foreign_toplevel_handle_v1_listener toplevel_handle_impl = {
@@ -81,8 +81,8 @@ static const struct zwlr_foreign_toplevel_handle_v1_listener toplevel_handle_imp
static const std::vector<Gtk::TargetEntry> target_entries = {
Gtk::TargetEntry("WAYBAR_TOPLEVEL", Gtk::TARGET_SAME_APP, 0)};
Task::Task(const waybar::Bar &bar, const Json::Value &config, Taskbar *tbar,
struct zwlr_foreign_toplevel_handle_v1 *tl_handle, struct wl_seat *seat)
Task::Task(const waybar::Bar& bar, const Json::Value& config, Taskbar* tbar,
struct zwlr_foreign_toplevel_handle_v1* tl_handle, struct wl_seat* seat)
: bar_{bar},
config_{config},
tbar_{tbar},
@@ -94,9 +94,35 @@ Task::Task(const waybar::Bar &bar, const Json::Value &config, Taskbar *tbar,
button.set_relief(Gtk::RELIEF_NONE);
content_.add(text_before_);
content_.add(icon_);
content_.add(text_after_);
/* When "expand" is enabled the buttons stretch to fill the taskbar and the
* titles ellipsize to fit within the available space. This only makes sense
* on a horizontal bar; on a vertical bar the box grows along the vertical
* axis, so ellipsizing/forcing width_chars(1) would truncate every title to
* "". Keep the historical behavior (buttons sized to their content) as the
* default and when the bar is vertical. */
bool expand = config_["expand"].isBool() && config_["expand"].asBool();
bool horizontal = bar.orientation == Gtk::ORIENTATION_HORIZONTAL;
if (expand && horizontal) {
button.set_hexpand(true);
content_.set_hexpand(true);
text_before_.set_ellipsize(Pango::ELLIPSIZE_END);
text_before_.set_single_line_mode(true);
text_before_.set_width_chars(1);
text_before_.set_xalign(0.0);
text_after_.set_ellipsize(Pango::ELLIPSIZE_END);
text_after_.set_single_line_mode(true);
text_after_.set_width_chars(1);
text_after_.set_xalign(0.0);
content_.pack_start(text_before_, true, true, 0);
content_.pack_start(icon_, false, false, 0);
content_.pack_start(text_after_, true, true, 0);
} else {
content_.add(text_before_);
content_.add(icon_);
content_.add(text_after_);
}
content_.show();
button.add(content_);
@@ -189,7 +215,7 @@ std::string Task::state_string(bool shortened) const {
return res.substr(0, res.size() - 1);
}
void Task::handle_title(const char *title) {
void Task::handle_title(const char* title) {
if (title_.empty()) {
spdlog::debug(fmt::format("Task ({}) setting title to {}", id_, title_));
} else {
@@ -198,7 +224,7 @@ void Task::handle_title(const char *title) {
title_ = title;
hide_if_ignored();
if (!with_icon_ && !with_name_ || app_info_) {
if ((!with_icon_ && !with_name_) || app_info_) {
return;
}
@@ -238,7 +264,7 @@ void Task::hide_if_ignored() {
}
}
void Task::handle_app_id(const char *app_id) {
void Task::handle_app_id(const char* app_id) {
if (app_id_.empty()) {
spdlog::debug(fmt::format("Task ({}) setting app_id to {}", id_, app_id));
} else {
@@ -273,20 +299,20 @@ void Task::handle_app_id(const char *app_id) {
spdlog::debug("Couldn't find icon for {}", app_id_);
}
void Task::on_button_size_allocated(Gtk::Allocation &alloc) {
void Task::on_button_size_allocated(Gtk::Allocation& alloc) {
gtk_widget_translate_coordinates(GTK_WIDGET(button.gobj()), GTK_WIDGET(bar_.window.gobj()), 0, 0,
&minimize_hint.x, &minimize_hint.y);
minimize_hint.w = button.get_width();
minimize_hint.h = button.get_height();
}
void Task::handle_output_enter(struct wl_output *output) {
void Task::handle_output_enter(struct wl_output* output) {
if (ignored_) {
spdlog::debug("{} is ignored", repr());
return;
}
spdlog::debug("{} entered output {}", repr(), (void *)output);
spdlog::debug("{} entered output {}", repr(), (void*)output);
if (!button_visible_ && (tbar_->all_outputs() || tbar_->show_output(output))) {
/* The task entered the output of the current bar make the button visible */
@@ -299,8 +325,8 @@ void Task::handle_output_enter(struct wl_output *output) {
}
}
void Task::handle_output_leave(struct wl_output *output) {
spdlog::debug("{} left output {}", repr(), (void *)output);
void Task::handle_output_leave(struct wl_output* output) {
spdlog::debug("{} left output {}", repr(), (void*)output);
if (button_visible_ && !tbar_->all_outputs() && tbar_->show_output(output)) {
/* The task left the output of the current bar, make the button invisible */
@@ -311,11 +337,11 @@ void Task::handle_output_leave(struct wl_output *output) {
}
}
void Task::handle_state(struct wl_array *state) {
void Task::handle_state(struct wl_array* state) {
state_ = 0;
size_t size = state->size / sizeof(uint32_t);
for (size_t i = 0; i < size; ++i) {
auto entry = static_cast<uint32_t *>(state->data)[i];
auto entry = static_cast<uint32_t*>(state->data)[i];
if (entry == ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_MAXIMIZED) state_ |= MAXIMIZED;
if (entry == ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_MINIMIZED) state_ |= MINIMIZED;
if (entry == ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_ACTIVATED) state_ |= ACTIVE;
@@ -367,7 +393,7 @@ void Task::handle_closed() {
tbar_->remove_task(id_);
}
bool Task::handle_clicked(GdkEventButton *bt) {
bool Task::handle_clicked(GdkEventButton* bt) {
/* filter out additional events for double/triple clicks */
if (bt->type == GDK_BUTTON_PRESS) {
/* save where the button press occurred in case it becomes a drag */
@@ -412,7 +438,7 @@ bool Task::handle_clicked(GdkEventButton *bt) {
return true;
}
bool Task::handle_motion_notify(GdkEventMotion *mn) {
bool Task::handle_motion_notify(GdkEventMotion* mn) {
if (drag_start_button == -1) return false;
if (button.drag_check_threshold(drag_start_x, drag_start_y, mn->x, mn->y)) {
@@ -420,25 +446,27 @@ bool Task::handle_motion_notify(GdkEventMotion *mn) {
auto target_list = Gtk::TargetList::create(target_entries);
auto refptr = Glib::RefPtr<Gtk::TargetList>(target_list);
auto drag_context =
button.drag_begin(refptr, Gdk::DragAction::ACTION_MOVE, drag_start_button, (GdkEvent *)mn);
button.drag_begin(refptr, Gdk::DragAction::ACTION_MOVE, drag_start_button, (GdkEvent*)mn);
}
return false;
}
void Task::handle_drag_data_get(const Glib::RefPtr<Gdk::DragContext> &context,
Gtk::SelectionData &selection_data, guint info, guint time) {
void Task::handle_drag_data_get(const Glib::RefPtr<Gdk::DragContext>& context,
Gtk::SelectionData& selection_data, guint info, guint time) {
spdlog::debug("drag_data_get");
void *button_addr = (void *)&this->button;
void* button_addr = (void*)&this->button;
selection_data.set("WAYBAR_TOPLEVEL", 32, (const guchar *)&button_addr, sizeof(gpointer));
selection_data.set("WAYBAR_TOPLEVEL", 32, (const guchar*)&button_addr, sizeof(gpointer));
}
void Task::handle_drag_data_received(const Glib::RefPtr<Gdk::DragContext> &context, int x, int y,
void Task::handle_drag_data_received(const Glib::RefPtr<Gdk::DragContext>& context, int x, int y,
Gtk::SelectionData selection_data, guint info, guint time) {
spdlog::debug("drag_data_received");
gpointer handle = *(gpointer *)selection_data.get_data();
auto dragged_button = (Gtk::Button *)handle;
auto* raw = selection_data.get_data();
if (!raw || selection_data.get_length() < static_cast<int>(sizeof(gpointer))) return;
gpointer handle = *(gpointer*)raw;
auto dragged_button = (Gtk::Button*)handle;
if (dragged_button == &this->button) return;
@@ -447,7 +475,7 @@ void Task::handle_drag_data_received(const Glib::RefPtr<Gdk::DragContext> &conte
if (parent_of_dragged != parent_of_dest) return;
auto box = (Gtk::Box *)parent_of_dragged;
auto box = (Gtk::Box*)parent_of_dragged;
auto position_prop = box->child_property_position(this->button);
auto position = position_prop.get_value();
@@ -455,9 +483,9 @@ void Task::handle_drag_data_received(const Glib::RefPtr<Gdk::DragContext> &conte
box->reorder_child(*dragged_button, position);
}
bool Task::operator==(const Task &o) const { return o.id_ == id_; }
bool Task::operator==(const Task& o) const { return o.id_ == id_; }
bool Task::operator!=(const Task &o) const { return o.id_ != id_; }
bool Task::operator!=(const Task& o) const { return o.id_ != id_; }
void Task::update() {
bool markup = config_["markup"].isBool() ? config_["markup"].asBool() : false;
@@ -509,7 +537,7 @@ void Task::update() {
if (markup)
button.set_tooltip_markup(txt);
else
button.set_tooltip_text(txt);
button.set_tooltip_markup(txt);
}
}
@@ -545,23 +573,23 @@ void Task::fullscreen(bool set) {
void Task::close() { zwlr_foreign_toplevel_handle_v1_close(handle_); }
/* Taskbar class implementation */
static void handle_global(void *data, struct wl_registry *registry, uint32_t name,
const char *interface, uint32_t version) {
static void handle_global(void* data, struct wl_registry* registry, uint32_t name,
const char* interface, uint32_t version) {
if (std::strcmp(interface, zwlr_foreign_toplevel_manager_v1_interface.name) == 0) {
static_cast<Taskbar *>(data)->register_manager(registry, name, version);
static_cast<Taskbar*>(data)->register_manager(registry, name, version);
} else if (std::strcmp(interface, wl_seat_interface.name) == 0) {
static_cast<Taskbar *>(data)->register_seat(registry, name, version);
static_cast<Taskbar*>(data)->register_seat(registry, name, version);
}
}
static void handle_global_remove(void *data, struct wl_registry *registry, uint32_t name) {
static void handle_global_remove(void* data, struct wl_registry* registry, uint32_t name) {
/* Nothing to do here */
}
static const wl_registry_listener registry_listener_impl = {.global = handle_global,
.global_remove = handle_global_remove};
Taskbar::Taskbar(const std::string &id, const waybar::Bar &bar, const Json::Value &config)
Taskbar::Taskbar(const std::string& id, const waybar::Bar& bar, const Json::Value& config)
: waybar::AModule(config, "taskbar", id, false, false),
bar_(bar),
box_{bar.orientation, 0},
@@ -575,8 +603,8 @@ Taskbar::Taskbar(const std::string &id, const waybar::Bar &bar, const Json::Valu
box_.get_style_context()->add_class("empty");
event_box_.add(box_);
struct wl_display *display = Client::inst()->wl_display;
struct wl_registry *registry = wl_display_get_registry(display);
struct wl_display* display = Client::inst()->wl_display;
struct wl_registry* registry = wl_display_get_registry(display);
wl_registry_add_listener(registry, &registry_listener_impl, this);
wl_display_roundtrip(display);
@@ -592,7 +620,7 @@ Taskbar::Taskbar(const std::string &id, const waybar::Bar &bar, const Json::Valu
/* Get the configured icon theme if specified */
if (config_["icon-theme"].isArray()) {
for (auto &c : config_["icon-theme"]) {
for (auto& c : config_["icon-theme"]) {
icon_loader_.add_custom_icon_theme(c.asString());
}
} else if (config_["icon-theme"].isString()) {
@@ -601,28 +629,28 @@ Taskbar::Taskbar(const std::string &id, const waybar::Bar &bar, const Json::Valu
// Load ignore-list
if (config_["ignore-list"].isArray()) {
for (auto &app_name : config_["ignore-list"]) {
for (auto& app_name : config_["ignore-list"]) {
ignore_list_.emplace(app_name.asString());
}
}
// Load app_id remappings
if (config_["app_ids-mapping"].isObject()) {
const Json::Value &mapping = config_["app_ids-mapping"];
const Json::Value& mapping = config_["app_ids-mapping"];
const std::vector<std::string> app_ids = config_["app_ids-mapping"].getMemberNames();
for (auto &app_id : app_ids) {
for (auto& app_id : app_ids) {
app_ids_replace_map_.emplace(app_id, mapping[app_id].asString());
}
}
for (auto &t : tasks_) {
for (auto& t : tasks_) {
t->handle_app_id(t->app_id().c_str());
}
}
Taskbar::~Taskbar() {
if (manager_) {
struct wl_display *display = Client::inst()->wl_display;
struct wl_display* display = Client::inst()->wl_display;
/*
* Send `stop` request and wait for one roundtrip.
* This is not quite correct as the protocol encourages us to wait for the .finished event,
@@ -640,13 +668,13 @@ Taskbar::~Taskbar() {
}
void Taskbar::update() {
for (auto &t : tasks_) {
for (auto& t : tasks_) {
t->update();
}
if (config_["sort-by-app-id"].asBool()) {
std::stable_sort(tasks_.begin(), tasks_.end(),
[](const std::unique_ptr<Task> &a, const std::unique_ptr<Task> &b) {
[](const std::unique_ptr<Task>& a, const std::unique_ptr<Task>& b) {
return a->app_id() < b->app_id();
});
@@ -658,13 +686,13 @@ void Taskbar::update() {
AModule::update();
}
static void tm_handle_toplevel(void *data, struct zwlr_foreign_toplevel_manager_v1 *manager,
struct zwlr_foreign_toplevel_handle_v1 *tl_handle) {
return static_cast<Taskbar *>(data)->handle_toplevel_create(tl_handle);
static void tm_handle_toplevel(void* data, struct zwlr_foreign_toplevel_manager_v1* manager,
struct zwlr_foreign_toplevel_handle_v1* tl_handle) {
return static_cast<Taskbar*>(data)->handle_toplevel_create(tl_handle);
}
static void tm_handle_finished(void *data, struct zwlr_foreign_toplevel_manager_v1 *manager) {
return static_cast<Taskbar *>(data)->handle_finished();
static void tm_handle_finished(void* data, struct zwlr_foreign_toplevel_manager_v1* manager) {
return static_cast<Taskbar*>(data)->handle_finished();
}
static const struct zwlr_foreign_toplevel_manager_v1_listener toplevel_manager_impl = {
@@ -672,7 +700,7 @@ static const struct zwlr_foreign_toplevel_manager_v1_listener toplevel_manager_i
.finished = tm_handle_finished,
};
void Taskbar::register_manager(struct wl_registry *registry, uint32_t name, uint32_t version) {
void Taskbar::register_manager(struct wl_registry* registry, uint32_t name, uint32_t version) {
if (manager_) {
spdlog::warn("Register foreign toplevel manager again although already existing!");
return;
@@ -687,7 +715,7 @@ void Taskbar::register_manager(struct wl_registry *registry, uint32_t name, uint
// limit version to a highest supported by the client protocol file
version = std::min<uint32_t>(version, zwlr_foreign_toplevel_manager_v1_interface.version);
manager_ = static_cast<struct zwlr_foreign_toplevel_manager_v1 *>(
manager_ = static_cast<struct zwlr_foreign_toplevel_manager_v1*>(
wl_registry_bind(registry, name, &zwlr_foreign_toplevel_manager_v1_interface, version));
if (manager_)
@@ -696,17 +724,17 @@ void Taskbar::register_manager(struct wl_registry *registry, uint32_t name, uint
spdlog::debug("Failed to register manager");
}
void Taskbar::register_seat(struct wl_registry *registry, uint32_t name, uint32_t version) {
void Taskbar::register_seat(struct wl_registry* registry, uint32_t name, uint32_t version) {
if (seat_) {
spdlog::warn("Register seat again although already existing!");
return;
}
version = std::min<uint32_t>(version, wl_seat_interface.version);
seat_ = static_cast<wl_seat *>(wl_registry_bind(registry, name, &wl_seat_interface, version));
seat_ = static_cast<wl_seat*>(wl_registry_bind(registry, name, &wl_seat_interface, version));
}
void Taskbar::handle_toplevel_create(struct zwlr_foreign_toplevel_handle_v1 *tl_handle) {
void Taskbar::handle_toplevel_create(struct zwlr_foreign_toplevel_handle_v1* tl_handle) {
tasks_.push_back(std::make_unique<Task>(bar_, config_, this, tl_handle, seat_));
}
@@ -715,14 +743,22 @@ void Taskbar::handle_finished() {
manager_ = nullptr;
}
void Taskbar::add_button(Gtk::Button &bt) {
box_.pack_start(bt, false, false);
void Taskbar::add_button(Gtk::Button& bt) {
/* Only let the buttons expand to fill the taskbar when "expand" is enabled
* and the bar is horizontal (see the Task constructor for details). */
bool expand = config_["expand"].isBool() && config_["expand"].asBool();
bool horizontal = bar_.orientation == Gtk::ORIENTATION_HORIZONTAL;
if (expand && horizontal) {
box_.pack_start(bt, true, true);
} else {
box_.pack_start(bt, false, false);
}
box_.get_style_context()->remove_class("empty");
}
void Taskbar::move_button(Gtk::Button &bt, int pos) { box_.reorder_child(bt, pos); }
void Taskbar::move_button(Gtk::Button& bt, int pos) { box_.reorder_child(bt, pos); }
void Taskbar::remove_button(Gtk::Button &bt) {
void Taskbar::remove_button(Gtk::Button& bt) {
box_.remove(bt);
if (box_.get_children().empty()) {
box_.get_style_context()->add_class("empty");
@@ -731,7 +767,7 @@ void Taskbar::remove_button(Gtk::Button &bt) {
void Taskbar::remove_task(uint32_t id) {
auto it = std::find_if(std::begin(tasks_), std::end(tasks_),
[id](const TaskPtr &p) { return p->id() == id; });
[id](const TaskPtr& p) { return p->id() == id; });
if (it == std::end(tasks_)) {
spdlog::warn("Can't find task with id {}", id);
@@ -741,7 +777,7 @@ void Taskbar::remove_task(uint32_t id) {
tasks_.erase(it);
}
bool Taskbar::show_output(struct wl_output *output) const {
bool Taskbar::show_output(struct wl_output* output) const {
return output == gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj());
}
@@ -749,11 +785,11 @@ bool Taskbar::all_outputs() const {
return config_["all-outputs"].isBool() && config_["all-outputs"].asBool();
}
const IconLoader &Taskbar::icon_loader() const { return icon_loader_; }
const IconLoader& Taskbar::icon_loader() const { return icon_loader_; }
const std::unordered_set<std::string> &Taskbar::ignore_list() const { return ignore_list_; }
const std::unordered_set<std::string>& Taskbar::ignore_list() const { return ignore_list_; }
const std::map<std::string, std::string> &Taskbar::app_ids_replace_map() const {
const std::map<std::string, std::string>& Taskbar::app_ids_replace_map() const {
return app_ids_replace_map_;
}
+78 -34
View File
@@ -40,12 +40,16 @@ AudioBackend::AudioBackend(std::function<void()> on_updated_cb, private_construc
}
AudioBackend::~AudioBackend() {
if (context_ != nullptr) {
pa_context_disconnect(context_);
}
if (mainloop_ != nullptr) {
mainloop_api_->quit(mainloop_api_, 0);
// Lock the mainloop so we can safely disconnect the context.
// This must be done before stopping the thread.
pa_threaded_mainloop_lock(mainloop_);
if (context_ != nullptr) {
pa_context_disconnect(context_);
pa_context_unref(context_);
context_ = nullptr;
}
pa_threaded_mainloop_unlock(mainloop_);
pa_threaded_mainloop_stop(mainloop_);
pa_threaded_mainloop_free(mainloop_);
}
@@ -69,11 +73,18 @@ void AudioBackend::connectContext() {
}
}
void AudioBackend::contextStateCb(pa_context *c, void *data) {
auto *backend = static_cast<AudioBackend *>(data);
void AudioBackend::contextStateCb(pa_context* c, void* data) {
auto* backend = static_cast<AudioBackend*>(data);
switch (pa_context_get_state(c)) {
case PA_CONTEXT_TERMINATED:
backend->mainloop_api_->quit(backend->mainloop_api_, 0);
// Only quit the mainloop if this is still the active context.
// During reconnection, the old context fires TERMINATED after the new one
// has already been created; quitting in that case would kill the new context.
// Note: context_ is only written from PA callbacks (while the mainloop lock is
// held), so this comparison is safe within any PA callback.
if (backend->context_ == nullptr || backend->context_ == c) {
backend->mainloop_api_->quit(backend->mainloop_api_, 0);
}
break;
case PA_CONTEXT_READY:
pa_context_get_server_info(c, serverInfoCb, data);
@@ -88,13 +99,17 @@ void AudioBackend::contextStateCb(pa_context *c, void *data) {
nullptr, nullptr);
break;
case PA_CONTEXT_FAILED:
// When pulseaudio server restarts, the connection is "failed". Try to reconnect.
// pa_threaded_mainloop_lock is already acquired in callback threads.
// So there is no need to lock it again.
if (backend->context_ != nullptr) {
pa_context_disconnect(backend->context_);
if (pa_context_errno(c) != PA_ERR_CONNECTIONREFUSED) {
// When pulseaudio server restarts, the connection is "failed". Try to reconnect.
// pa_threaded_mainloop_lock is already acquired in callback threads.
// So there is no need to lock it again.
if (backend->context_ != nullptr) {
pa_context_disconnect(backend->context_);
pa_context_unref(backend->context_);
backend->context_ = nullptr;
}
backend->connectContext();
}
backend->connectContext();
break;
case PA_CONTEXT_CONNECTING:
case PA_CONTEXT_AUTHORIZING:
@@ -107,8 +122,8 @@ void AudioBackend::contextStateCb(pa_context *c, void *data) {
/*
* Called when an event we subscribed to occurs.
*/
void AudioBackend::subscribeCb(pa_context *context, pa_subscription_event_type_t type, uint32_t idx,
void *data) {
void AudioBackend::subscribeCb(pa_context* context, pa_subscription_event_type_t type, uint32_t idx,
void* data) {
unsigned facility = type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK;
unsigned operation = type & PA_SUBSCRIPTION_EVENT_TYPE_MASK;
if (operation != PA_SUBSCRIPTION_EVENT_CHANGE) {
@@ -130,8 +145,8 @@ void AudioBackend::subscribeCb(pa_context *context, pa_subscription_event_type_t
/*
* Called in response to a volume change request
*/
void AudioBackend::volumeModifyCb(pa_context *c, int success, void *data) {
auto *backend = static_cast<AudioBackend *>(data);
void AudioBackend::volumeModifyCb(pa_context* c, int success, void* data) {
auto* backend = static_cast<AudioBackend*>(data);
if (success != 0) {
if ((backend->context_ != nullptr) &&
pa_context_get_state(backend->context_) == PA_CONTEXT_READY) {
@@ -145,18 +160,18 @@ void AudioBackend::volumeModifyCb(pa_context *c, int success, void *data) {
/*
* Called when the requested sink information is ready.
*/
void AudioBackend::sinkInfoCb(pa_context * /*context*/, const pa_sink_info *i, int /*eol*/,
void *data) {
void AudioBackend::sinkInfoCb(pa_context* /*context*/, const pa_sink_info* i, int /*eol*/,
void* data) {
if (i == nullptr) return;
auto running = i->state == PA_SINK_RUNNING;
auto idle = i->state == PA_SINK_IDLE;
spdlog::trace("Sink name {} Running:[{}] Idle:[{}]", i->name, running, idle);
auto *backend = static_cast<AudioBackend *>(data);
auto* backend = static_cast<AudioBackend*>(data);
if (!backend->ignored_sinks_.empty()) {
for (const auto &ignored_sink : backend->ignored_sinks_) {
for (const auto& ignored_sink : backend->ignored_sinks_) {
if (ignored_sink == i->description) {
if (i->name == backend->current_sink_name_) {
// If the current sink happens to be ignored it is never considered running
@@ -205,7 +220,7 @@ void AudioBackend::sinkInfoCb(pa_context * /*context*/, const pa_sink_info *i, i
backend->desc_ = i->description;
backend->monitor_ = i->monitor_source_name;
backend->port_name_ = i->active_port != nullptr ? i->active_port->name : "Unknown";
if (const auto *ff = pa_proplist_gets(i->proplist, PA_PROP_DEVICE_FORM_FACTOR)) {
if (const auto* ff = pa_proplist_gets(i->proplist, PA_PROP_DEVICE_FORM_FACTOR)) {
backend->form_factor_ = ff;
} else {
backend->form_factor_ = "";
@@ -217,9 +232,9 @@ void AudioBackend::sinkInfoCb(pa_context * /*context*/, const pa_sink_info *i, i
/*
* Called when the requested source information is ready.
*/
void AudioBackend::sourceInfoCb(pa_context * /*context*/, const pa_source_info *i, int /*eol*/,
void *data) {
auto *backend = static_cast<AudioBackend *>(data);
void AudioBackend::sourceInfoCb(pa_context* /*context*/, const pa_source_info* i, int /*eol*/,
void* data) {
auto* backend = static_cast<AudioBackend*>(data);
if (i != nullptr && backend->default_source_name_ == i->name) {
auto source_volume = static_cast<float>(pa_cvolume_avg(&(i->volume))) / float{PA_VOLUME_NORM};
backend->source_volume_ = std::round(source_volume * 100.0F);
@@ -235,16 +250,25 @@ void AudioBackend::sourceInfoCb(pa_context * /*context*/, const pa_source_info *
* Called when the requested information on the server is ready. This is
* used to find the default PulseAudio sink.
*/
void AudioBackend::serverInfoCb(pa_context *context, const pa_server_info *i, void *data) {
auto *backend = static_cast<AudioBackend *>(data);
backend->current_sink_name_ = i->default_sink_name;
backend->default_sink_name = i->default_sink_name;
backend->default_source_name_ = i->default_source_name;
void AudioBackend::serverInfoCb(pa_context* context, const pa_server_info* i, void* data) {
auto* backend = static_cast<AudioBackend*>(data);
if (i == nullptr) return;
backend->current_sink_name_ = i->default_sink_name ? i->default_sink_name : "";
backend->default_sink_name = i->default_sink_name ? i->default_sink_name : "";
backend->default_source_name_ = i->default_source_name ? i->default_source_name : "";
pa_context_get_sink_info_list(context, sinkInfoCb, data);
pa_context_get_source_info_list(context, sourceInfoCb, data);
}
uint16_t AudioBackend::getVolume(PulseaudioTarget target) const {
if (target == PulseaudioTarget::Source) {
return source_volume_;
} else {
return volume_;
}
}
void AudioBackend::changeVolume(uint16_t volume, uint16_t min_volume, uint16_t max_volume) {
// Early return if context is not ready
if ((context_ == nullptr) || pa_context_get_state(context_) != PA_CONTEXT_READY) {
@@ -354,7 +378,16 @@ void AudioBackend::changeVolume(ChangeType change_type, double step, uint16_t ma
pa_threaded_mainloop_unlock(mainloop_);
}
bool AudioBackend::getMuted(PulseaudioTarget target) const {
if (target == PulseaudioTarget::Source) {
return source_muted_;
} else {
return muted_;
}
}
void AudioBackend::toggleSinkMute() {
if (context_ == nullptr || pa_context_get_state(context_) != PA_CONTEXT_READY) return;
muted_ = !muted_;
pa_threaded_mainloop_lock(mainloop_);
pa_context_set_sink_mute_by_index(context_, sink_idx_, static_cast<int>(muted_), nullptr,
@@ -363,6 +396,7 @@ void AudioBackend::toggleSinkMute() {
}
void AudioBackend::toggleSinkMute(bool mute) {
if (context_ == nullptr || pa_context_get_state(context_) != PA_CONTEXT_READY) return;
muted_ = mute;
pa_threaded_mainloop_lock(mainloop_);
pa_context_set_sink_mute_by_index(context_, sink_idx_, static_cast<int>(muted_), nullptr,
@@ -371,7 +405,8 @@ void AudioBackend::toggleSinkMute(bool mute) {
}
void AudioBackend::toggleSourceMute() {
source_muted_ = !muted_;
if (context_ == nullptr || pa_context_get_state(context_) != PA_CONTEXT_READY) return;
source_muted_ = !source_muted_;
pa_threaded_mainloop_lock(mainloop_);
pa_context_set_source_mute_by_index(context_, source_idx_, static_cast<int>(source_muted_),
nullptr, nullptr);
@@ -379,6 +414,7 @@ void AudioBackend::toggleSourceMute() {
}
void AudioBackend::toggleSourceMute(bool mute) {
if (context_ == nullptr || pa_context_get_state(context_) != PA_CONTEXT_READY) return;
source_muted_ = mute;
pa_threaded_mainloop_lock(mainloop_);
pa_context_set_source_mute_by_index(context_, source_idx_, static_cast<int>(source_muted_),
@@ -386,15 +422,23 @@ void AudioBackend::toggleSourceMute(bool mute) {
pa_threaded_mainloop_unlock(mainloop_);
}
void AudioBackend::unmute(PulseaudioTarget target) {
if (target == PulseaudioTarget::Source) {
toggleSourceMute(false);
} else {
toggleSinkMute(false);
}
}
bool AudioBackend::isBluetooth() {
return monitor_.find("a2dp_sink") != std::string::npos || // PulseAudio
monitor_.find("a2dp-sink") != std::string::npos || // PipeWire
monitor_.find("bluez") != std::string::npos;
}
void AudioBackend::setIgnoredSinks(const Json::Value &config) {
void AudioBackend::setIgnoredSinks(const Json::Value& config) {
if (config.isArray()) {
for (const auto &ignored_sink : config) {
for (const auto& ignored_sink : config) {
if (ignored_sink.isString()) {
ignored_sinks_.push_back(ignored_sink.asString());
}
+63 -37
View File
@@ -14,10 +14,10 @@ namespace {
class FileDescriptor {
public:
explicit FileDescriptor(int fd) : fd_(fd) {}
FileDescriptor(const FileDescriptor &other) = delete;
FileDescriptor(FileDescriptor &&other) noexcept = delete;
FileDescriptor &operator=(const FileDescriptor &other) = delete;
FileDescriptor &operator=(FileDescriptor &&other) noexcept = delete;
FileDescriptor(const FileDescriptor& other) = delete;
FileDescriptor(FileDescriptor&& other) noexcept = delete;
FileDescriptor& operator=(const FileDescriptor& other) = delete;
FileDescriptor& operator=(FileDescriptor&& other) noexcept = delete;
~FileDescriptor() {
if (fd_ != -1) {
if (close(fd_) != 0) {
@@ -31,27 +31,27 @@ class FileDescriptor {
int fd_;
};
void check_eq(int rc, int expected, const char *message = "eq, rc was: ") {
void check_eq(int rc, int expected, const char* message = "eq, rc was: ") {
if (rc != expected) {
throw std::runtime_error(fmt::format(fmt::runtime(message), rc));
}
}
void check_neq(int rc, int bad_rc, const char *message = "neq, rc was: ") {
void check_neq(int rc, int bad_rc, const char* message = "neq, rc was: ") {
if (rc == bad_rc) {
throw std::runtime_error(fmt::format(fmt::runtime(message), rc));
}
}
void check0(int rc, const char *message = "rc wasn't 0") { check_eq(rc, 0, message); }
void check0(int rc, const char* message = "rc wasn't 0") { check_eq(rc, 0, message); }
void check_gte(int rc, int gte, const char *message = "rc was: ") {
void check_gte(int rc, int gte, const char* message = "rc was: ") {
if (rc < gte) {
throw std::runtime_error(fmt::format(fmt::runtime(message), rc));
}
}
void check_nn(const void *ptr, const char *message = "ptr was null") {
void check_nn(const void* ptr, const char* message = "ptr was null") {
if (ptr == nullptr) {
throw std::runtime_error(message);
}
@@ -61,48 +61,68 @@ void check_nn(const void *ptr, const char *message = "ptr was null") {
namespace waybar::util {
static void upsert_device(std::vector<BacklightDevice> &devices, udev_device *dev) {
const char *name = udev_device_get_sysname(dev);
static void upsert_device(std::vector<BacklightDevice>& devices, udev_device* dev) {
const char* name = udev_device_get_sysname(dev);
check_nn(name);
const char *actual_brightness_attr =
const char* actual_brightness_attr =
strncmp(name, "amdgpu_bl", 9) == 0 || strcmp(name, "apple-panel-bl") == 0
? "brightness"
: "actual_brightness";
const char *actual = udev_device_get_sysattr_value(dev, actual_brightness_attr);
const char *max = udev_device_get_sysattr_value(dev, "max_brightness");
const char *power = udev_device_get_sysattr_value(dev, "bl_power");
const char* actual = udev_device_get_sysattr_value(dev, actual_brightness_attr);
const char* max = udev_device_get_sysattr_value(dev, "max_brightness");
const char* power = udev_device_get_sysattr_value(dev, "bl_power");
auto found = std::find_if(devices.begin(), devices.end(), [name](const BacklightDevice &device) {
auto found = std::find_if(devices.begin(), devices.end(), [name](const BacklightDevice& device) {
return device.name() == name;
});
if (found != devices.end()) {
if (actual != nullptr) {
found->set_actual(std::stoi(actual));
try {
found->set_actual(std::stoi(actual));
} catch (const std::exception&) {
}
}
if (max != nullptr) {
found->set_max(std::stoi(max));
try {
found->set_max(std::stoi(max));
} catch (const std::exception&) {
}
}
if (power != nullptr) {
found->set_powered(std::stoi(power) == 0);
try {
found->set_powered(std::stoi(power) == 0);
} catch (const std::exception&) {
}
}
} else {
const int actual_int = actual == nullptr ? 0 : std::stoi(actual);
const int max_int = max == nullptr ? 0 : std::stoi(max);
const bool power_bool = power == nullptr ? true : std::stoi(power) == 0;
int actual_int = 0, max_int = 0;
bool power_bool = true;
try {
if (actual != nullptr) actual_int = std::stoi(actual);
} catch (const std::exception&) {
}
try {
if (max != nullptr) max_int = std::stoi(max);
} catch (const std::exception&) {
}
try {
if (power != nullptr) power_bool = std::stoi(power) == 0;
} catch (const std::exception&) {
}
devices.emplace_back(name, actual_int, max_int, power_bool);
}
}
static void enumerate_devices(std::vector<BacklightDevice> &devices, udev *udev) {
static void enumerate_devices(std::vector<BacklightDevice>& devices, udev* udev) {
std::unique_ptr<udev_enumerate, UdevEnumerateDeleter> enumerate{udev_enumerate_new(udev)};
udev_enumerate_add_match_subsystem(enumerate.get(), "backlight");
udev_enumerate_scan_devices(enumerate.get());
udev_list_entry *enum_devices = udev_enumerate_get_list_entry(enumerate.get());
udev_list_entry *dev_list_entry;
udev_list_entry* enum_devices = udev_enumerate_get_list_entry(enumerate.get());
udev_list_entry* dev_list_entry;
udev_list_entry_foreach(dev_list_entry, enum_devices) {
const char *path = udev_list_entry_get_name(dev_list_entry);
const char* path = udev_list_entry_get_name(dev_list_entry);
std::unique_ptr<udev_device, UdevDeviceDeleter> dev{udev_device_new_from_syspath(udev, path)};
check_nn(dev.get(), "dev new failed");
upsert_device(devices, dev.get());
@@ -184,7 +204,7 @@ BacklightBackend::BacklightBackend(std::chrono::milliseconds interval,
devices = devices_;
}
for (int i = 0; i < event_count; ++i) {
const auto &event = events[i];
const auto& event = events[i];
check_eq(event.data.fd, udev_fd, "unexpected udev fd");
std::unique_ptr<udev_device, UdevDeviceDeleter> dev{udev_monitor_receive_device(mon.get())};
if (!dev) {
@@ -206,27 +226,27 @@ BacklightBackend::BacklightBackend(std::chrono::milliseconds interval,
};
}
const BacklightDevice *BacklightBackend::best_device(const std::vector<BacklightDevice> &devices,
const BacklightDevice* BacklightBackend::best_device(const std::vector<BacklightDevice>& devices,
std::string_view preferred_device) {
const auto found = std::find_if(
devices.begin(), devices.end(),
[preferred_device](const BacklightDevice &dev) { return dev.name() == preferred_device; });
[preferred_device](const BacklightDevice& dev) { return dev.name() == preferred_device; });
if (found != devices.end()) {
return &(*found);
}
const auto max = std::max_element(
devices.begin(), devices.end(),
[](const BacklightDevice &l, const BacklightDevice &r) { return l.get_max() < r.get_max(); });
[](const BacklightDevice& l, const BacklightDevice& r) { return l.get_max() < r.get_max(); });
return max == devices.end() ? nullptr : &(*max);
}
const BacklightDevice *BacklightBackend::get_previous_best_device() {
const BacklightDevice* BacklightBackend::get_previous_best_device() {
return previous_best_.has_value() ? &(*previous_best_) : nullptr;
}
void BacklightBackend::set_previous_best_device(const BacklightDevice *device) {
void BacklightBackend::set_previous_best_device(const BacklightDevice* device) {
if (device == nullptr) {
previous_best_ = std::nullopt;
} else {
@@ -234,7 +254,7 @@ void BacklightBackend::set_previous_best_device(const BacklightDevice *device) {
}
}
void BacklightBackend::set_scaled_brightness(const std::string &preferred_device, int brightness) {
void BacklightBackend::set_scaled_brightness(const std::string& preferred_device, int brightness) {
GET_BEST_DEVICE(best, (*this), preferred_device);
if (best != nullptr) {
@@ -244,7 +264,7 @@ void BacklightBackend::set_scaled_brightness(const std::string &preferred_device
}
}
void BacklightBackend::set_brightness(const std::string &preferred_device, ChangeType change_type,
void BacklightBackend::set_brightness(const std::string& preferred_device, ChangeType change_type,
double step) {
GET_BEST_DEVICE(best, (*this), preferred_device);
@@ -259,8 +279,13 @@ void BacklightBackend::set_brightness(const std::string &preferred_device, Chang
}
}
void BacklightBackend::set_brightness_internal(const std::string &device_name, int brightness,
void BacklightBackend::set_brightness_internal(const std::string& device_name, int brightness,
int max_brightness) {
if (!login_proxy_) {
spdlog::error("Login proxy not available, cannot set brightness");
return;
}
brightness = std::clamp(brightness, 0, max_brightness);
auto call_args = Glib::VariantContainerBase(
@@ -269,11 +294,12 @@ void BacklightBackend::set_brightness_internal(const std::string &device_name, i
login_proxy_->call_sync("SetBrightness", call_args);
}
int BacklightBackend::get_scaled_brightness(const std::string &preferred_device) {
int BacklightBackend::get_scaled_brightness(const std::string& preferred_device) {
GET_BEST_DEVICE(best, (*this), preferred_device);
if (best != nullptr) {
return best->get_actual() * 100 / best->get_max();
if (best->get_max() == 0) return 0;
return static_cast<int>(std::round(best->get_actual() * 100.0F / best->get_max()));
}
return 0;
+14 -3
View File
@@ -23,7 +23,8 @@ namespace {
const std::regex IMPORT_REGEX(R"(@import\s+(?:url\()?(?:"|')([^"')]+)(?:"|')\)?;)");
}
waybar::CssReloadHelper::CssReloadHelper(std::string cssFile, std::function<void()> callback)
waybar::CssReloadHelper::CssReloadHelper(std::string cssFile,
std::function<void(const std::string&)> callback)
: m_cssFile(std::move(cssFile)), m_callback(std::move(callback)) {}
std::string waybar::CssReloadHelper::getFileContents(const std::string& filename) {
@@ -88,6 +89,12 @@ void waybar::CssReloadHelper::monitorChanges() {
}
}
void waybar::CssReloadHelper::changeCssFile(const std::string& newCssFile) {
m_fileMonitors.clear();
m_cssFile = newCssFile;
monitorChanges();
}
void waybar::CssReloadHelper::handleFileChange(Glib::RefPtr<Gio::File> const& file,
Glib::RefPtr<Gio::File> const& other_type,
Gio::FileMonitorEvent event_type) {
@@ -95,7 +102,7 @@ void waybar::CssReloadHelper::handleFileChange(Glib::RefPtr<Gio::File> const& fi
// fire for one
if (event_type == Gio::FileMonitorEvent::FILE_MONITOR_EVENT_CHANGES_DONE_HINT) {
spdlog::debug("Reloading style, file changed: {}", file->get_path());
m_callback();
m_callback(m_cssFile);
}
}
@@ -115,11 +122,15 @@ std::vector<std::string> waybar::CssReloadHelper::parseImports(const std::string
auto maxIterations = 100U;
do {
previousSize = imports.size();
std::vector<std::string> to_parse;
for (const auto& [file, parsed] : imports) {
if (!parsed) {
parseImports(file, imports);
to_parse.push_back(file);
}
}
for (const auto& file : to_parse) {
parseImports(file, imports);
}
} while (imports.size() > previousSize && maxIterations-- > 0);
-1
View File
@@ -21,7 +21,6 @@ Glib::RefPtr<Gdk::Pixbuf> DefaultGtkIconThemeWrapper::load_icon(
const std::lock_guard<std::mutex> lock(default_theme_mutex);
auto default_theme = Gtk::IconTheme::get_default();
default_theme->rescan_if_needed();
auto icon_info = default_theme->lookup_icon(name, tmp_size, flags);
+20 -17
View File
@@ -5,8 +5,11 @@
std::vector<std::string> IconLoader::search_prefix() {
std::vector<std::string> prefixes = {""};
std::string home_dir = std::getenv("HOME");
prefixes.push_back(home_dir + "/.local/share/");
const char* home_env = std::getenv("HOME");
std::string home_dir = home_env ? home_env : "";
if (!home_dir.empty()) {
prefixes.push_back(home_dir + "/.local/share/");
}
auto xdg_data_dirs = std::getenv("XDG_DATA_DIRS");
if (!xdg_data_dirs) {
@@ -26,12 +29,12 @@ std::vector<std::string> IconLoader::search_prefix() {
} while (end != std::string::npos);
}
for (auto &p : prefixes) spdlog::debug("Using 'desktop' search path prefix: {}", p);
for (auto& p : prefixes) spdlog::debug("Using 'desktop' search path prefix: {}", p);
return prefixes;
}
Glib::RefPtr<Gio::DesktopAppInfo> IconLoader::get_app_info_by_name(const std::string &app_id) {
Glib::RefPtr<Gio::DesktopAppInfo> IconLoader::get_app_info_by_name(const std::string& app_id) {
static std::vector<std::string> prefixes = search_prefix();
std::vector<std::string> app_folders = {"", "applications/", "applications/kde/",
@@ -39,9 +42,9 @@ Glib::RefPtr<Gio::DesktopAppInfo> IconLoader::get_app_info_by_name(const std::st
std::vector<std::string> suffixes = {"", ".desktop"};
for (auto const &prefix : prefixes) {
for (auto const &folder : app_folders) {
for (auto const &suffix : suffixes) {
for (auto const& prefix : prefixes) {
for (auto const& folder : app_folders) {
for (auto const& suffix : suffixes) {
auto app_info_ =
Gio::DesktopAppInfo::create_from_filename(prefix + folder + app_id + suffix);
if (!app_info_) {
@@ -56,7 +59,7 @@ Glib::RefPtr<Gio::DesktopAppInfo> IconLoader::get_app_info_by_name(const std::st
return {};
}
Glib::RefPtr<Gio::DesktopAppInfo> IconLoader::get_desktop_app_info(const std::string &app_id) {
Glib::RefPtr<Gio::DesktopAppInfo> IconLoader::get_desktop_app_info(const std::string& app_id) {
auto app_info = get_app_info_by_name(app_id);
if (app_info) {
return app_info;
@@ -64,7 +67,7 @@ Glib::RefPtr<Gio::DesktopAppInfo> IconLoader::get_desktop_app_info(const std::st
std::string desktop_file = "";
gchar ***desktop_list = g_desktop_app_info_search(app_id.c_str());
gchar*** desktop_list = g_desktop_app_info_search(app_id.c_str());
if (desktop_list != nullptr && desktop_list[0] != nullptr) {
for (size_t i = 0; desktop_list[0][i]; i++) {
if (desktop_file == "") {
@@ -89,7 +92,7 @@ Glib::RefPtr<Gio::DesktopAppInfo> IconLoader::get_desktop_app_info(const std::st
return get_app_info_by_name(desktop_file);
}
Glib::RefPtr<Gdk::Pixbuf> IconLoader::load_icon_from_file(std::string const &icon_path, int size) {
Glib::RefPtr<Gdk::Pixbuf> IconLoader::load_icon_from_file(std::string const& icon_path, int size) {
try {
auto pb = Gdk::Pixbuf::create_from_file(icon_path, size, size);
return pb;
@@ -99,13 +102,13 @@ Glib::RefPtr<Gdk::Pixbuf> IconLoader::load_icon_from_file(std::string const &ico
}
std::string IconLoader::get_icon_name_from_icon_theme(
const Glib::RefPtr<Gtk::IconTheme> &icon_theme, const std::string &app_id) {
const Glib::RefPtr<Gtk::IconTheme>& icon_theme, const std::string& app_id) {
if (icon_theme->lookup_icon(app_id, 24)) return app_id;
return "";
}
bool IconLoader::image_load_icon(Gtk::Image &image, const Glib::RefPtr<Gtk::IconTheme> &icon_theme,
bool IconLoader::image_load_icon(Gtk::Image& image, const Glib::RefPtr<Gtk::IconTheme>& icon_theme,
Glib::RefPtr<Gio::DesktopAppInfo> app_info, int size) {
std::string ret_icon_name = "unknown";
if (app_info) {
@@ -139,7 +142,7 @@ bool IconLoader::image_load_icon(Gtk::Image &image, const Glib::RefPtr<Gtk::Icon
}
if (pixbuf) {
if (pixbuf->get_width() != scaled_icon_size) {
if (pixbuf->get_width() != scaled_icon_size && pixbuf->get_height() > 0) {
int width = scaled_icon_size * pixbuf->get_width() / pixbuf->get_height();
pixbuf = pixbuf->scale_simple(width, scaled_icon_size, Gdk::InterpType::INTERP_BILINEAR);
}
@@ -152,16 +155,16 @@ bool IconLoader::image_load_icon(Gtk::Image &image, const Glib::RefPtr<Gtk::Icon
return false;
}
void IconLoader::add_custom_icon_theme(const std::string &theme_name) {
void IconLoader::add_custom_icon_theme(const std::string& theme_name) {
auto icon_theme = Gtk::IconTheme::create();
icon_theme->set_custom_theme(theme_name);
custom_icon_themes_.push_back(icon_theme);
spdlog::debug("Use custom icon theme: {}", theme_name);
}
bool IconLoader::image_load_icon(Gtk::Image &image, Glib::RefPtr<Gio::DesktopAppInfo> app_info,
bool IconLoader::image_load_icon(Gtk::Image& image, Glib::RefPtr<Gio::DesktopAppInfo> app_info,
int size) const {
for (auto &icon_theme : custom_icon_themes_) {
for (auto& icon_theme : custom_icon_themes_) {
if (image_load_icon(image, icon_theme, app_info, size)) {
return true;
}
@@ -170,7 +173,7 @@ bool IconLoader::image_load_icon(Gtk::Image &image, Glib::RefPtr<Gio::DesktopApp
}
Glib::RefPtr<Gio::DesktopAppInfo> IconLoader::get_app_info_from_app_id_list(
const std::string &app_id_list) {
const std::string& app_id_list) {
std::string app_id;
std::istringstream stream(app_id_list);
Glib::RefPtr<Gio::DesktopAppInfo> app_info_;
+27 -18
View File
@@ -4,11 +4,11 @@
namespace waybar::util::PipewireBackend {
static void getNodeInfo(void *data_, const struct pw_node_info *info) {
auto *pNodeInfo = static_cast<PrivacyNodeInfo *>(data_);
static void getNodeInfo(void* data_, const struct pw_node_info* info) {
auto* pNodeInfo = static_cast<PrivacyNodeInfo*>(data_);
pNodeInfo->handleNodeEventInfo(info);
static_cast<PipewireBackend *>(pNodeInfo->data)->privacy_nodes_changed_signal_event.emit();
static_cast<PipewireBackend*>(pNodeInfo->data)->privacy_nodes_changed_signal_event.emit();
}
static const struct pw_node_events NODE_EVENTS = {
@@ -16,8 +16,8 @@ static const struct pw_node_events NODE_EVENTS = {
.info = getNodeInfo,
};
static void proxyDestroy(void *data) {
static_cast<PrivacyNodeInfo *>(data)->handleProxyEventDestroy();
static void proxyDestroy(void* data) {
static_cast<PrivacyNodeInfo*>(data)->handleProxyEventDestroy();
}
static const struct pw_proxy_events PROXY_EVENTS = {
@@ -25,14 +25,14 @@ static const struct pw_proxy_events PROXY_EVENTS = {
.destroy = proxyDestroy,
};
static void registryEventGlobal(void *_data, uint32_t id, uint32_t permissions, const char *type,
uint32_t version, const struct spa_dict *props) {
static_cast<PipewireBackend *>(_data)->handleRegistryEventGlobal(id, permissions, type, version,
props);
static void registryEventGlobal(void* _data, uint32_t id, uint32_t permissions, const char* type,
uint32_t version, const struct spa_dict* props) {
static_cast<PipewireBackend*>(_data)->handleRegistryEventGlobal(id, permissions, type, version,
props);
}
static void registryEventGlobalRemove(void *_data, uint32_t id) {
static_cast<PipewireBackend *>(_data)->handleRegistryEventGlobalRemove(id);
static void registryEventGlobalRemove(void* _data, uint32_t id) {
static_cast<PipewireBackend*>(_data)->handleRegistryEventGlobalRemove(id);
}
static const struct pw_registry_events REGISTRY_EVENTS = {
@@ -54,11 +54,17 @@ PipewireBackend::PipewireBackend(PrivateConstructorTag tag)
context_ = pw_context_new(pw_thread_loop_get_loop(mainloop_), nullptr, 0);
if (context_ == nullptr) {
pw_thread_loop_unlock(mainloop_);
pw_thread_loop_destroy(mainloop_);
mainloop_ = nullptr;
throw std::runtime_error("pa_context_new() failed.");
}
core_ = pw_context_connect(context_, nullptr, 0);
if (core_ == nullptr) {
pw_thread_loop_unlock(mainloop_);
pw_context_destroy(context_);
context_ = nullptr;
pw_thread_loop_destroy(mainloop_);
mainloop_ = nullptr;
throw std::runtime_error("pw_context_connect() failed");
}
registry_ = pw_core_get_registry(core_, PW_VERSION_REGISTRY, 0);
@@ -78,7 +84,7 @@ PipewireBackend::~PipewireBackend() {
}
if (registry_ != nullptr) {
pw_proxy_destroy((struct pw_proxy *)registry_);
pw_proxy_destroy((struct pw_proxy*)registry_);
}
spa_zero(registryListener_);
@@ -103,11 +109,11 @@ std::shared_ptr<PipewireBackend> PipewireBackend::getInstance() {
return std::make_shared<PipewireBackend>(tag);
}
void PipewireBackend::handleRegistryEventGlobal(uint32_t id, uint32_t permissions, const char *type,
uint32_t version, const struct spa_dict *props) {
void PipewireBackend::handleRegistryEventGlobal(uint32_t id, uint32_t permissions, const char* type,
uint32_t version, const struct spa_dict* props) {
if (props == nullptr || strcmp(type, PW_TYPE_INTERFACE_Node) != 0) return;
const char *lookupStr = spa_dict_lookup(props, PW_KEY_MEDIA_CLASS);
const char* lookupStr = spa_dict_lookup(props, PW_KEY_MEDIA_CLASS);
if (lookupStr == nullptr) return;
std::string mediaClass = lookupStr;
enum PrivacyNodeType mediaType = PRIVACY_NODE_TYPE_NONE;
@@ -121,11 +127,11 @@ void PipewireBackend::handleRegistryEventGlobal(uint32_t id, uint32_t permission
return;
}
auto *proxy = (pw_proxy *)pw_registry_bind(registry_, id, type, version, sizeof(PrivacyNodeInfo));
auto* proxy = (pw_proxy*)pw_registry_bind(registry_, id, type, version, sizeof(PrivacyNodeInfo));
if (proxy == nullptr) return;
auto *pNodeInfo = (PrivacyNodeInfo *)pw_proxy_get_user_data(proxy);
auto* pNodeInfo = (PrivacyNodeInfo*)pw_proxy_get_user_data(proxy);
new (pNodeInfo) PrivacyNodeInfo{};
pNodeInfo->id = id;
pNodeInfo->data = this;
@@ -136,7 +142,10 @@ void PipewireBackend::handleRegistryEventGlobal(uint32_t id, uint32_t permission
pw_proxy_add_object_listener(proxy, &pNodeInfo->object_listener, &NODE_EVENTS, pNodeInfo);
privacy_nodes.insert_or_assign(id, pNodeInfo);
{
std::lock_guard<std::mutex> lock(mutex_);
privacy_nodes.insert_or_assign(id, pNodeInfo);
}
}
void PipewireBackend::handleRegistryEventGlobalRemove(uint32_t id) {
+7 -7
View File
@@ -3,9 +3,9 @@
namespace waybar::util::PipewireBackend {
std::string PrivacyNodeInfo::getName() {
const std::vector<std::string *> names{&application_name, &node_name};
const std::vector<std::string*> names{&application_name, &node_name};
std::string name = "Unknown Application";
for (const auto &item : names) {
for (const auto& item : names) {
if (item != nullptr && !item->empty()) {
name = *item;
name[0] = toupper(name[0]);
@@ -16,10 +16,10 @@ std::string PrivacyNodeInfo::getName() {
}
std::string PrivacyNodeInfo::getIconName() {
const std::vector<std::string *> names{&application_icon_name, &pipewire_access_portal_app_id,
&application_name, &node_name};
const std::vector<std::string*> names{&application_icon_name, &pipewire_access_portal_app_id,
&application_name, &node_name};
std::string name = "application-x-executable-symbolic";
for (const auto &item : names) {
for (const auto& item : names) {
if (item != nullptr && !item->empty() && DefaultGtkIconThemeWrapper::has_icon(*item)) {
return *item;
}
@@ -32,10 +32,10 @@ void PrivacyNodeInfo::handleProxyEventDestroy() {
spa_hook_remove(&object_listener);
}
void PrivacyNodeInfo::handleNodeEventInfo(const struct pw_node_info *info) {
void PrivacyNodeInfo::handleNodeEventInfo(const struct pw_node_info* info) {
state = info->state;
const struct spa_dict_item *item;
const struct spa_dict_item* item;
spa_dict_for_each(item, info->props) {
if (strcmp(item->key, PW_KEY_CLIENT_ID) == 0) {
client_id = strtoul(item->value, nullptr, 10);
+19 -13
View File
@@ -58,21 +58,27 @@ void waybar::Portal::refreshAppearance() {
// xdg-desktop-portal 1.17 will fix this issue with a new `ReadOne` method,
// but this version is not yet released.
// TODO(xdg-desktop-portal v1.17): switch to ReadOne
auto container = Glib::VariantBase::cast_dynamic<Glib::VariantContainerBase>(response);
Glib::VariantBase modev;
container.get_child(modev, 0);
auto mode =
Glib::VariantBase::cast_dynamic<Glib::Variant<Glib::Variant<Glib::Variant<uint32_t>>>>(modev)
.get()
.get()
.get();
auto newMode = Appearance(mode);
if (newMode == currentMode) {
try {
auto container = Glib::VariantBase::cast_dynamic<Glib::VariantContainerBase>(response);
Glib::VariantBase modev;
container.get_child(modev, 0);
auto mode =
Glib::VariantBase::cast_dynamic<Glib::Variant<Glib::Variant<Glib::Variant<uint32_t>>>>(
modev)
.get()
.get()
.get();
auto newMode = Appearance(mode);
if (newMode == currentMode) {
return;
}
spdlog::info("Discovered appearance '{}'", newMode);
currentMode = newMode;
m_signal_appearance_changed.emit(currentMode);
} catch (const std::bad_cast& e) {
spdlog::error("Unexpected appearance variant format: {}", e.what());
return;
}
spdlog::info("Discovered appearance '{}'", newMode);
currentMode = newMode;
m_signal_appearance_changed.emit(currentMode);
}
waybar::Appearance waybar::Portal::getAppearance() { return currentMode; };
+7 -7
View File
@@ -18,21 +18,21 @@ class PrepareForSleep {
}
}
static void prepareForSleep_cb(GDBusConnection *system_bus, const gchar *sender_name,
const gchar *object_path, const gchar *interface_name,
const gchar *signal_name, GVariant *parameters,
static void prepareForSleep_cb(GDBusConnection* system_bus, const gchar* sender_name,
const gchar* object_path, const gchar* interface_name,
const gchar* signal_name, GVariant* parameters,
gpointer user_data) {
if (g_variant_is_of_type(parameters, G_VARIANT_TYPE("(b)")) != 0) {
gboolean sleeping;
g_variant_get(parameters, "(b)", &sleeping);
auto *self = static_cast<PrepareForSleep *>(user_data);
auto* self = static_cast<PrepareForSleep*>(user_data);
self->signal.emit(sleeping);
}
}
public:
static PrepareForSleep &GetInstance() {
static PrepareForSleep& GetInstance() {
static PrepareForSleep instance;
return instance;
}
@@ -40,10 +40,10 @@ class PrepareForSleep {
private:
guint login1_id;
GDBusConnection *login1_connection;
GDBusConnection* login1_connection;
};
} // namespace
waybar::SafeSignal<bool> &waybar::util::prepare_for_sleep() {
waybar::SafeSignal<bool>& waybar::util::prepare_for_sleep() {
return PrepareForSleep::GetInstance().signal;
}
+1 -1
View File
@@ -18,7 +18,7 @@ std::string rewriteString(const std::string& value, const Json::Value& rules) {
// malformated regexes will cause an exception.
// in this case, log error and try the next rule.
const std::regex rule{it.key().asString(), std::regex_constants::icase};
if (std::regex_match(value, rule)) {
if (std::regex_match(res, rule)) {
res = std::regex_replace(res, rule, it->asString());
}
} catch (const std::regex_error& e) {
+60
View File
@@ -0,0 +1,60 @@
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <regex>
#include <sstream>
namespace fs = std::filesystem;
struct TransformResult {
std::string css;
bool was_transformed;
};
TransformResult transform_8bit_to_hex(const std::string& file_path) {
std::ifstream f(file_path, std::ios::in | std::ios::binary);
const auto size = fs::file_size(file_path);
std::string result(size, '\0');
if (!f.is_open() || !f.good()) {
throw std::runtime_error("Cannot open file: " + file_path);
}
if (size == 0) {
return {.css = result, .was_transformed = false};
}
f.read(result.data(), size);
static std::regex pattern(
R"(\#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2}))");
std::string final_output;
auto it = std::sregex_iterator(result.begin(), result.end(), pattern);
auto eof = std::sregex_iterator();
if (it == eof) {
return {.css = result, .was_transformed = false};
}
std::smatch match;
while (it != eof) {
match = *it;
final_output += match.prefix().str();
int r = stoi(match[1].str(), nullptr, 16);
int g = stoi(match[2].str(), nullptr, 16);
int b = stoi(match[3].str(), nullptr, 16);
double a = (stoi(match[4].str(), nullptr, 16) / 255.0);
std::stringstream ss;
ss << "rgba(" << r << "," << g << "," << b << "," << std::fixed << std::setprecision(2) << a
<< ")";
final_output += ss.str();
++it;
}
final_output += match.suffix().str();
return {.css = final_output, .was_transformed = true};
}
+1 -1
View File
@@ -1,6 +1,6 @@
#include "util/ustring_clen.hpp"
int ustring_clen(const Glib::ustring &str) {
int ustring_clen(const Glib::ustring& str) {
int total = 0;
for (unsigned int i : str) {
total += g_unichar_iswide(i) + 1;
+62
View File
@@ -0,0 +1,62 @@
#include <glib.h>
#include <string>
#include <util/utf8_string.hpp>
namespace waybar::util {
namespace {
// Wide characters count as two, zero-width characters count as zero
// Modifies str in-place (unless width = std::string::npos)
// Returns the total width of the string pre-truncating
size_t measure_and_truncate(std::string& str, size_t width = std::string::npos) {
if (str.length() == 0) return 0;
const gchar* trunc_end = nullptr;
size_t total_width = 0;
for (gchar *data = str.data(), *end = data + str.size(); data != nullptr;) {
gunichar c = g_utf8_get_char_validated(data, end - data);
if (c == -1U || c == -2U) {
// invalid unicode, treat string as ascii
if (width != std::string::npos && str.length() > width) str.resize(width);
return str.length();
} else if (g_unichar_iswide(c)) {
total_width += 2;
} else if (!g_unichar_iszerowidth(c) && c != 0xAD) { // neither zero-width nor soft hyphen
total_width += 1;
}
data = g_utf8_find_next_char(data, end);
if (width != std::string::npos && total_width <= width && !g_unichar_isspace(c))
trunc_end = data;
}
if (trunc_end) str.resize(trunc_end - str.data());
return total_width;
}
} // namespace
size_t utf8_width(const std::string& str) {
return measure_and_truncate(const_cast<std::string&>(str));
}
void utf8_truncate(std::string& s, const std::string& ellipsis, size_t max_len) {
if (max_len == 0) {
s.resize(0);
return;
}
size_t len = measure_and_truncate(s, max_len);
if (len > max_len) {
size_t ellipsis_len = utf8_width(ellipsis);
if (max_len >= ellipsis_len) {
if (ellipsis_len) measure_and_truncate(s, max_len - ellipsis_len);
s += ellipsis;
} else {
s.resize(0);
}
}
}
} // namespace waybar::util