Merge remote-tracking branch 'origin/master' into pr-5069
This commit is contained in:
+48
-1
@@ -2,6 +2,8 @@
|
||||
|
||||
#include <gdkmm/pixbuf.h>
|
||||
#include <spdlog/spdlog.h>
|
||||
#include <regex>
|
||||
#include <string>
|
||||
|
||||
namespace waybar {
|
||||
|
||||
@@ -9,6 +11,10 @@ AIconLabel::AIconLabel(const Json::Value& config, const std::string& name, const
|
||||
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) {
|
||||
if (config["icon-size"].isUInt()) {
|
||||
app_icon_size_ = config["icon-size"].asUInt();
|
||||
}
|
||||
image_.set_pixel_size(app_icon_size_);
|
||||
event_box_.remove();
|
||||
label_.unset_name();
|
||||
label_.get_style_context()->remove_class(MODULE_CLASS);
|
||||
@@ -55,13 +61,54 @@ AIconLabel::AIconLabel(const Json::Value& config, const std::string& name, const
|
||||
event_box_.add(box_);
|
||||
}
|
||||
|
||||
std::tuple<std::string, std::string> AIconLabel::extractIcon(const std::string& input) {
|
||||
std::string icon_result = "";
|
||||
std::string label_result = input;
|
||||
try {
|
||||
static const std::regex icon_search(R"((?=\\0icon\\1f).+?(?=\\n))");
|
||||
std::smatch icon_match;
|
||||
if (std::regex_search(input, icon_match, icon_search)) {
|
||||
icon_result = icon_match[0].str().substr(9);
|
||||
|
||||
static const std::regex clean_label_pattern(R"(\\0icon\\1f.+?\\n)");
|
||||
label_result = std::regex_replace(input, clean_label_pattern, "");
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
spdlog::warn("Error while parsing icon from label. {}", e.what());
|
||||
}
|
||||
|
||||
return std::make_tuple(icon_result, label_result);
|
||||
}
|
||||
|
||||
auto AIconLabel::update() -> void {
|
||||
label_contains_icon = false;
|
||||
|
||||
auto [iconLabel, cleanLabel] = extractIcon(label_.get_label().c_str());
|
||||
label_contains_icon = iconLabel.length() > 0;
|
||||
|
||||
if (label_contains_icon) {
|
||||
label_.set_markup(cleanLabel);
|
||||
|
||||
if (iconLabel.front() == '/') {
|
||||
int scaled_icon_size = app_icon_size_ * image_.get_scale_factor();
|
||||
auto pixbuf = Gdk::Pixbuf::create_from_file(iconLabel, 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);
|
||||
} else {
|
||||
image_.set_from_icon_name(iconLabel, Gtk::ICON_SIZE_INVALID);
|
||||
image_.set_visible(true);
|
||||
}
|
||||
}
|
||||
|
||||
image_.set_visible(image_.get_visible() && iconEnabled());
|
||||
ALabel::update();
|
||||
}
|
||||
|
||||
bool AIconLabel::iconEnabled() const {
|
||||
return config_["icon"].isBool() ? config_["icon"].asBool() : false;
|
||||
return label_contains_icon || (config_["icon"].isBool() ? config_["icon"].asBool() : false);
|
||||
}
|
||||
|
||||
} // namespace waybar
|
||||
|
||||
+9
-1
@@ -117,7 +117,7 @@ ALabel::ALabel(const Json::Value& config, const std::string& name, const std::st
|
||||
submenus_[key] = GTK_MENU_ITEM(item);
|
||||
menuActionsMap_[key] = it->asString();
|
||||
g_signal_connect(submenus_[key], "activate", G_CALLBACK(handleGtkMenuEvent),
|
||||
(gpointer)menuActionsMap_[key].c_str());
|
||||
(gpointer)g_strdup(menuActionsMap_[key].c_str()));
|
||||
}
|
||||
g_object_unref(builder);
|
||||
} catch (std::runtime_error& e) {
|
||||
@@ -209,6 +209,10 @@ std::string ALabel::getIcon(uint16_t percentage, const std::vector<std::string>&
|
||||
return "";
|
||||
}
|
||||
|
||||
void ALabel::copyToClipboard(const std::string& literal) {
|
||||
Gtk::Clipboard::get()->set_text(literal);
|
||||
}
|
||||
|
||||
bool waybar::ALabel::handleToggle(GdkEventButton* const& e) {
|
||||
if (config_["format-alt-click"].isUInt() && e->button == config_["format-alt-click"].asUInt()) {
|
||||
alt_ = !alt_;
|
||||
@@ -218,6 +222,10 @@ bool waybar::ALabel::handleToggle(GdkEventButton* const& e) {
|
||||
format_ = default_format_;
|
||||
}
|
||||
}
|
||||
|
||||
if (config_["on-click-copy"].isBool() && config_["on-click-copy"].asBool()) {
|
||||
copyToClipboard(label_.get_text());
|
||||
}
|
||||
return AModule::handleToggle(e);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -46,7 +46,7 @@ AModule::AModule(const Json::Value& config, const std::string& name, const std::
|
||||
std::find_if(eventMap_.cbegin(), eventMap_.cend(), [&config](const auto& eventEntry) {
|
||||
// True if there is any non-release type event
|
||||
return eventEntry.first.second != GdkEventType::GDK_BUTTON_RELEASE &&
|
||||
config[eventEntry.second].isString();
|
||||
(config[eventEntry.second].isString() || config[eventEntry.second].isBool());
|
||||
}) != eventMap_.cend();
|
||||
|
||||
if (enable_click || hasUserEvents) {
|
||||
|
||||
@@ -3,12 +3,14 @@
|
||||
#include <gtk-layer-shell.h>
|
||||
#include <spdlog/spdlog.h>
|
||||
|
||||
#include <ostream>
|
||||
#include <type_traits>
|
||||
|
||||
#include "client.hpp"
|
||||
#include "factory.hpp"
|
||||
#include "group.hpp"
|
||||
#include "util/enum.hpp"
|
||||
#include "util/hosts_check.hpp"
|
||||
#include "util/kill_signal.hpp"
|
||||
|
||||
#ifdef HAVE_SWAY
|
||||
@@ -565,6 +567,11 @@ void waybar::Bar::getModules(const Factory& factory, const std::string& pos,
|
||||
for (const auto& name : module_list) {
|
||||
try {
|
||||
auto ref = name.asString();
|
||||
|
||||
if (config[ref].isMember("hosts") && !waybar::util::valid_host(config[ref])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
AModule* module;
|
||||
|
||||
if (ref.compare(0, 6, "group/") == 0 && ref.size() > 6) {
|
||||
|
||||
@@ -42,6 +42,13 @@
|
||||
#include "modules/niri/window.hpp"
|
||||
#include "modules/niri/workspaces.hpp"
|
||||
#endif
|
||||
#ifdef HAVE_MANGO
|
||||
#include "modules/mango/language.hpp"
|
||||
#include "modules/mango/keymode.hpp"
|
||||
#include "modules/mango/window.hpp"
|
||||
#include "modules/mango/workspaces.hpp"
|
||||
#include "modules/mango/layout.hpp"
|
||||
#endif
|
||||
#ifdef HAVE_WAYFIRE
|
||||
#include "modules/wayfire/window.hpp"
|
||||
#include "modules/wayfire/workspaces.hpp"
|
||||
@@ -231,6 +238,23 @@ waybar::AModule* waybar::Factory::makeModule(const std::string& name,
|
||||
return new waybar::modules::niri::Workspaces(id, bar_, config_[name]);
|
||||
}
|
||||
#endif
|
||||
#ifdef HAVE_MANGO
|
||||
if (ref == "mango/window") {
|
||||
return new waybar::modules::mango::Window(id, bar_, config_[name]);
|
||||
}
|
||||
if (ref == "mango/workspaces") {
|
||||
return new waybar::modules::mango::Workspaces(id, bar_, config_[name]);
|
||||
}
|
||||
if (ref == "mango/language") {
|
||||
return new waybar::modules::mango::Language(id, bar_, config_[name]);
|
||||
}
|
||||
if (ref == "mango/keymode") {
|
||||
return new waybar::modules::mango::Keymode(id, bar_, config_[name]);
|
||||
}
|
||||
if (ref == "mango/layout") {
|
||||
return new waybar::modules::mango::Layout(id, bar_, config_[name]);
|
||||
}
|
||||
#endif
|
||||
#ifdef HAVE_WAYFIRE
|
||||
if (ref == "wayfire/window") {
|
||||
return new waybar::modules::wayfire::Window(id, bar_, config_[name]);
|
||||
|
||||
+18
-1
@@ -63,6 +63,7 @@ Group::Group(const std::string& name, const std::string& id, const Json::Value&
|
||||
? drawer_config["transition-left-to-right"].asBool()
|
||||
: true);
|
||||
click_to_reveal = drawer_config["click-to-reveal"].asBool();
|
||||
reveal_delay = drawer_config["reveal-delay"].asInt();
|
||||
|
||||
const bool start_expanded =
|
||||
(drawer_config["start-expanded"].isBool() ? drawer_config["start-expanded"].asBool()
|
||||
@@ -95,22 +96,38 @@ Group::Group(const std::string& name, const std::string& id, const Json::Value&
|
||||
void Group::show_group() {
|
||||
box.set_state_flags(Gtk::StateFlags::STATE_FLAG_PRELIGHT);
|
||||
revealer.set_reveal_child(true);
|
||||
box.get_style_context()->add_class("expanded");
|
||||
}
|
||||
|
||||
void Group::hide_group() {
|
||||
box.unset_state_flags(Gtk::StateFlags::STATE_FLAG_PRELIGHT);
|
||||
revealer.set_reveal_child(false);
|
||||
box.get_style_context()->remove_class("expanded");
|
||||
}
|
||||
|
||||
bool Group::handleMouseEnter(GdkEventCrossing* const& e) {
|
||||
if (!click_to_reveal) {
|
||||
show_group();
|
||||
if (reveal_delay > 0) {
|
||||
if (reveal_timeout_.connected()) {
|
||||
reveal_timeout_.disconnect();
|
||||
}
|
||||
|
||||
reveal_timeout_ = Glib::signal_timeout().connect(
|
||||
[this]() { show_group(); return false; },
|
||||
reveal_delay);
|
||||
} else {
|
||||
show_group();
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool Group::handleMouseLeave(GdkEventCrossing* const& e) {
|
||||
if (!click_to_reveal && e->detail != GDK_NOTIFY_INFERIOR) {
|
||||
if (reveal_delay > 0 && reveal_timeout_.connected()) {
|
||||
reveal_timeout_.disconnect();
|
||||
}
|
||||
|
||||
hide_group();
|
||||
}
|
||||
return false;
|
||||
|
||||
@@ -36,9 +36,15 @@ auto waybar::modules::Backlight::update() -> void {
|
||||
|
||||
if (best->get_powered()) {
|
||||
event_box_.show();
|
||||
|
||||
const uint8_t percent =
|
||||
best->get_max() == 0 ? 100 : round(best->get_actual() * 100.0f / best->get_max());
|
||||
|
||||
const uint8_t percent_exp =
|
||||
best->get_max() == 0
|
||||
? 100
|
||||
: roundf(powf((float)best->get_actual() / best->get_max(), 1.0f / 2.718f) * 100);
|
||||
|
||||
// Get the state and apply state-specific format if available
|
||||
auto state = getState(percent);
|
||||
std::string current_format = format_;
|
||||
@@ -49,8 +55,10 @@ auto waybar::modules::Backlight::update() -> void {
|
||||
}
|
||||
}
|
||||
|
||||
std::string desc = fmt::format(fmt::runtime(current_format), fmt::arg("percent", percent),
|
||||
fmt::arg("icon", getIcon(percent)));
|
||||
std::string desc =
|
||||
fmt::format(fmt::runtime(current_format), fmt::arg("percent", percent),
|
||||
fmt::arg("percent_exp", percent_exp), fmt::arg("icon", getIcon(percent)),
|
||||
fmt::arg("icon_exp", getIcon(percent_exp)));
|
||||
label_.set_markup(desc);
|
||||
if (tooltipEnabled()) {
|
||||
std::string tooltip_format;
|
||||
|
||||
+29
-1
@@ -2,6 +2,9 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
|
||||
#include "util/command.hpp"
|
||||
#if defined(__FreeBSD__)
|
||||
@@ -33,6 +36,11 @@ waybar::modules::Battery::Battery(const std::string& id, const Bar& bar, const J
|
||||
}
|
||||
udev_monitor_enable_receiving(mon_.get());
|
||||
|
||||
if (config_["smooth-power"].isBool()) {
|
||||
smoothPowerEnable_ = config_["smooth-power"].asBool();
|
||||
if (smoothPowerEnable_ && config_["smooth-power-time-constant"].isNumeric())
|
||||
time_constant_s_ = std::max(1.0, config_["smooth-power-time-constant"].asDouble());
|
||||
}
|
||||
if (config_["weighted-average"].isBool()) weightedAverage_ = config_["weighted-average"].asBool();
|
||||
#endif
|
||||
spdlog::debug("battery: worker interval is {}", interval_.count());
|
||||
@@ -577,11 +585,31 @@ waybar::modules::Battery::getInfos() {
|
||||
if (online && current_status != "Discharging") status = "Plugged";
|
||||
}
|
||||
|
||||
if (total_energy_exists && total_power_exists && total_power != 0) {
|
||||
if (!smoothPowerEnable_) {
|
||||
smooth_power_ = total_power;
|
||||
} else {
|
||||
if (status != old_status_raw_) {
|
||||
smooth_power_ = total_power;
|
||||
last_t_ = std::chrono::steady_clock::now();
|
||||
} else {
|
||||
std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
|
||||
double dt_s =
|
||||
std::chrono::duration_cast<std::chrono::duration<double> >(now - last_t_).count();
|
||||
smooth_power_ = smooth_power_ + ((1 - std::exp(-dt_s / time_constant_s_)) *
|
||||
(total_power - smooth_power_));
|
||||
last_t_ = now;
|
||||
}
|
||||
|
||||
old_status_raw_ = status;
|
||||
}
|
||||
}
|
||||
|
||||
float time_remaining{0.0f};
|
||||
if (status == "Discharging" && time_to_empty_now_exists) {
|
||||
if (time_to_empty_now != 0) time_remaining = (float)time_to_empty_now / 3600.0f;
|
||||
} else if (status == "Discharging" && total_power_exists && total_energy_exists) {
|
||||
if (total_power != 0) time_remaining = (float)total_energy / total_power;
|
||||
if (smooth_power_ != 0) time_remaining = (float)total_energy / smooth_power_;
|
||||
} else if (status == "Charging" && time_to_full_now_exists) {
|
||||
if (time_to_full_now_exists && (time_to_full_now != 0))
|
||||
time_remaining = -(float)time_to_full_now / 3600.0f;
|
||||
|
||||
@@ -187,6 +187,45 @@ auto waybar::modules::Clock::update() -> void {
|
||||
}
|
||||
|
||||
m_tlpText_ = fmt_lib::vformat(m_locale_, m_tlpText_, fmt_lib::make_format_args(now));
|
||||
|
||||
// Pango doesn't support CSS classes but to continue using it while staying
|
||||
// backwards compatible this approach uses post-posting to replace fake
|
||||
// classes with attributes Pango does understand.
|
||||
//
|
||||
// The benefit of this approach is anyone using the original styling choices
|
||||
// can continue doing that and folks can optionally opt into using classes.
|
||||
//
|
||||
// It's also forwards compatible to where if this implemention ever changes
|
||||
// to support proper classes anyone using them will continue to work.
|
||||
auto context = label_.get_style_context();
|
||||
|
||||
static const std::vector<std::pair<std::string, std::string>> calendar_class_map = {
|
||||
{"calendar-today", "class='today'"},
|
||||
{"calendar-days", "class='days'"},
|
||||
{"calendar-weeks", "class='weeks'"},
|
||||
{"calendar-weekdays", "class='weekdays'"},
|
||||
{"calendar-months", "class='months'"}};
|
||||
|
||||
for (const auto& [css_class, search_str] : calendar_class_map) {
|
||||
try {
|
||||
context->add_class(css_class);
|
||||
const Gdk::RGBA color = context->get_color();
|
||||
context->remove_class(css_class);
|
||||
|
||||
const std::string replace_str = fmt::format(
|
||||
"color='#{:02x}{:02x}{:02x}'", static_cast<int>(color.get_red() * 255),
|
||||
static_cast<int>(color.get_green() * 255), static_cast<int>(color.get_blue() * 255));
|
||||
|
||||
m_tlpText_ = std::regex_replace(m_tlpText_, std::regex(search_str), replace_str);
|
||||
} catch (const Glib::Error& e) {
|
||||
spdlog::warn("Clock: Failed to fetch CSS color for {}: {}", css_class, e.what().raw());
|
||||
continue;
|
||||
} catch (...) {
|
||||
// Catch-all for any other weirdness.
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
m_tooltip_->set_markup(m_tlpText_);
|
||||
label_.trigger_tooltip_query();
|
||||
}
|
||||
@@ -514,6 +553,18 @@ using deleting_unique_ptr = std::unique_ptr<T, deleter_from_fn<fn>>;
|
||||
|
||||
// Computations done similarly to Linux cal utility.
|
||||
auto waybar::modules::Clock::first_day_of_week() -> weekday {
|
||||
const auto firstdow = config_[kCldPlaceholder]["first-day-of-week"];
|
||||
if (firstdow.isInt()) {
|
||||
const int firstDay = firstdow.asInt();
|
||||
if (!(firstDay >= 0 && firstDay <= 6)) {
|
||||
spdlog::warn(
|
||||
"Clock calender configuration first-day-of-week = {0} must be in range [0, 6]. Default "
|
||||
"value is used instead",
|
||||
firstDay);
|
||||
} else {
|
||||
return weekday{static_cast<unsigned>(firstDay)};
|
||||
}
|
||||
}
|
||||
if (iso8601Calendar_) {
|
||||
return Monday;
|
||||
}
|
||||
|
||||
+5
-1
@@ -51,13 +51,17 @@ auto waybar::modules::Cpu::update() -> void {
|
||||
store.push_back(fmt::arg("avg_frequency", avg_frequency));
|
||||
std::vector<std::string> arg_names;
|
||||
arg_names.reserve(cpu_usage.size() * 2);
|
||||
std::string all_icons;
|
||||
for (size_t i = 1; i < cpu_usage.size(); ++i) {
|
||||
auto core_i = i - 1;
|
||||
arg_names.push_back(fmt::format("usage{}", core_i));
|
||||
store.push_back(fmt::arg(arg_names.back().c_str(), cpu_usage[i]));
|
||||
auto core_icon = getIcon(cpu_usage[i], icons);
|
||||
all_icons += core_icon;
|
||||
arg_names.push_back(fmt::format("icon{}", core_i));
|
||||
store.push_back(fmt::arg(arg_names.back().c_str(), getIcon(cpu_usage[i], icons)));
|
||||
store.push_back(fmt::arg(arg_names.back().c_str(), core_icon));
|
||||
}
|
||||
store.push_back(fmt::arg("icons", all_icons));
|
||||
label_.set_markup(fmt::vformat(format, store));
|
||||
|
||||
if (tooltipEnabled()) {
|
||||
|
||||
@@ -38,13 +38,17 @@ auto waybar::modules::CpuUsage::update() -> void {
|
||||
store.push_back(fmt::arg("icon", getIcon(total_usage, icons)));
|
||||
std::vector<std::string> arg_names;
|
||||
arg_names.reserve(cpu_usage.size() * 2);
|
||||
std::string all_icons;
|
||||
for (size_t i = 1; i < cpu_usage.size(); ++i) {
|
||||
auto core_i = i - 1;
|
||||
arg_names.push_back(fmt::format("usage{}", core_i));
|
||||
store.push_back(fmt::arg(arg_names.back().c_str(), cpu_usage[i]));
|
||||
auto core_icon = getIcon(cpu_usage[i], icons);
|
||||
all_icons += core_icon;
|
||||
arg_names.push_back(fmt::format("icon{}", core_i));
|
||||
store.push_back(fmt::arg(arg_names.back().c_str(), getIcon(cpu_usage[i], icons)));
|
||||
store.push_back(fmt::arg(arg_names.back().c_str(), core_icon));
|
||||
}
|
||||
store.push_back(fmt::arg("icons", all_icons));
|
||||
label_.set_markup(fmt::vformat(format, store));
|
||||
|
||||
if (tooltipEnabled()) {
|
||||
|
||||
+111
-62
@@ -1,15 +1,32 @@
|
||||
#include "modules/disk.hpp"
|
||||
|
||||
#include <spdlog/spdlog.h>
|
||||
|
||||
using namespace waybar::util;
|
||||
|
||||
waybar::modules::Disk::Disk(const std::string& id, const Json::Value& config)
|
||||
: ALabel(config, "disk", id, "{}%", 30), path_("/") {
|
||||
: ALabel(config, "disk", id, "{}%", 30), header_(""), paths_(), separator_(" ") {
|
||||
thread_ = [this] {
|
||||
dp.emit();
|
||||
thread_.sleep_for(interval_);
|
||||
};
|
||||
if (config["path"].isString()) {
|
||||
path_ = config["path"].asString();
|
||||
if (config["header"].isString()) {
|
||||
header_ = config["header"].asString();
|
||||
}
|
||||
if (config["path"].isString() && !config["paths"].isArray()) {
|
||||
spdlog::warn("Disk: path is deprecated use paths instead!");
|
||||
paths_.push_back(config["path"].asString());
|
||||
}
|
||||
if (config["paths"].isArray()) {
|
||||
for (const auto& path : config["paths"]) {
|
||||
paths_.push_back(path.asString());
|
||||
}
|
||||
}
|
||||
if (!config["path"].isString() && !config["paths"].isArray()) {
|
||||
paths_.emplace_back("/");
|
||||
}
|
||||
if (config["separator"].isString()) {
|
||||
separator_ = config["separator"].asString();
|
||||
}
|
||||
if (config["unit"].isString()) {
|
||||
unit_ = config["unit"].asString();
|
||||
@@ -17,76 +34,108 @@ waybar::modules::Disk::Disk(const std::string& id, const Json::Value& config)
|
||||
}
|
||||
|
||||
auto waybar::modules::Disk::update() -> void {
|
||||
struct statvfs /* {
|
||||
unsigned long f_bsize; // filesystem block size
|
||||
unsigned long f_frsize; // fragment size
|
||||
fsblkcnt_t f_blocks; // size of fs in f_frsize units
|
||||
fsblkcnt_t f_bfree; // # free blocks
|
||||
fsblkcnt_t f_bavail; // # free blocks for unprivileged users
|
||||
fsfilcnt_t f_files; // # inodes
|
||||
fsfilcnt_t f_ffree; // # free inodes
|
||||
fsfilcnt_t f_favail; // # free inodes for unprivileged users
|
||||
unsigned long f_fsid; // filesystem ID
|
||||
unsigned long f_flag; // mount flags
|
||||
unsigned long f_namemax; // maximum filename length
|
||||
}; */
|
||||
stats;
|
||||
int err = statvfs(path_.c_str(), &stats);
|
||||
std::string tooltip_label;
|
||||
std::string label = header_;
|
||||
|
||||
/* Conky options
|
||||
fs_bar - Bar that shows how much space is used
|
||||
fs_free - Free space on a file system
|
||||
fs_free_perc - Free percentage of space
|
||||
fs_size - File system size
|
||||
fs_used - File system used space
|
||||
*/
|
||||
bool had_valid_disk = false;
|
||||
|
||||
if (err != 0 || stats.f_blocks == 0) {
|
||||
event_box_.hide();
|
||||
return;
|
||||
}
|
||||
for (size_t i = 0; i < paths_.size(); ++i) {
|
||||
const auto& path = paths_[i];
|
||||
|
||||
float specific_free, specific_used, specific_total, divisor;
|
||||
struct statvfs /* {
|
||||
unsigned long f_bsize; // filesystem block size
|
||||
unsigned long f_frsize; // fragment size
|
||||
fsblkcnt_t f_blocks; // size of fs in f_frsize units
|
||||
fsblkcnt_t f_bfree; // # free blocks
|
||||
fsblkcnt_t f_bavail; // # free blocks for unprivileged users
|
||||
fsfilcnt_t f_files; // # inodes
|
||||
fsfilcnt_t f_ffree; // # free inodes
|
||||
fsfilcnt_t f_favail; // # free inodes for unprivileged users
|
||||
unsigned long f_fsid; // filesystem ID
|
||||
unsigned long f_flag; // mount flags
|
||||
unsigned long f_namemax; // maximum filename length
|
||||
}; */
|
||||
stats;
|
||||
|
||||
divisor = calc_specific_divisor(unit_);
|
||||
specific_free = (stats.f_bavail * stats.f_frsize) / divisor;
|
||||
specific_used = ((stats.f_blocks - stats.f_bfree) * stats.f_frsize) / divisor;
|
||||
specific_total = (stats.f_blocks * stats.f_frsize) / divisor;
|
||||
int err = statvfs(path.c_str(), &stats);
|
||||
|
||||
auto free = pow_format(stats.f_bavail * stats.f_frsize, "B", true);
|
||||
auto used = pow_format((stats.f_blocks - stats.f_bfree) * stats.f_frsize, "B", true);
|
||||
auto total = pow_format(stats.f_blocks * stats.f_frsize, "B", true);
|
||||
auto percentage_used = (stats.f_blocks - stats.f_bfree) * 100 / stats.f_blocks;
|
||||
/* Conky options
|
||||
fs_bar - Bar that shows how much space is used
|
||||
fs_free - Free space on a file system
|
||||
fs_free_perc - Free percentage of space
|
||||
fs_size - File system size
|
||||
fs_used - File system used space
|
||||
*/
|
||||
|
||||
auto format = format_;
|
||||
auto state = getState(percentage_used);
|
||||
if (!state.empty() && config_["format-" + state].isString()) {
|
||||
format = config_["format-" + state].asString();
|
||||
}
|
||||
if (err != 0 || stats.f_blocks == 0) {
|
||||
spdlog::warn("Disk: statvfs failed for path '{}' (errno={})", path, errno);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (format.empty()) {
|
||||
event_box_.hide();
|
||||
} else {
|
||||
event_box_.show();
|
||||
label_.set_markup(fmt::format(
|
||||
fmt::runtime(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),
|
||||
fmt::arg("path", path_), fmt::arg("specific_free", specific_free),
|
||||
fmt::arg("specific_used", specific_used), fmt::arg("specific_total", specific_total)));
|
||||
}
|
||||
float specific_free, specific_used, specific_total, divisor;
|
||||
|
||||
divisor = calc_specific_divisor(unit_);
|
||||
specific_free = (stats.f_bavail * stats.f_frsize) / divisor;
|
||||
specific_used = ((stats.f_blocks - stats.f_bfree) * stats.f_frsize) / divisor;
|
||||
specific_total = (stats.f_blocks * stats.f_frsize) / divisor;
|
||||
|
||||
auto free = pow_format(stats.f_bavail * stats.f_frsize, "B", true);
|
||||
auto used = pow_format((stats.f_blocks - stats.f_bfree) * stats.f_frsize, "B", true);
|
||||
auto total = pow_format(stats.f_blocks * stats.f_frsize, "B", true);
|
||||
auto percentage_used = (stats.f_blocks - stats.f_bfree) * 100 / stats.f_blocks;
|
||||
|
||||
std::string disk_format = format_;
|
||||
auto state = getState(percentage_used);
|
||||
if (!state.empty() && config_["format-" + state].isString()) {
|
||||
disk_format = config_["format-" + state].asString();
|
||||
}
|
||||
|
||||
if (!disk_format.empty()) {
|
||||
if (had_valid_disk) {
|
||||
label += separator_;
|
||||
}
|
||||
|
||||
label += fmt::format(
|
||||
fmt::runtime(disk_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), fmt::arg("path", path),
|
||||
fmt::arg("specific_free", specific_free), fmt::arg("specific_used", specific_used),
|
||||
fmt::arg("specific_total", specific_total));
|
||||
}
|
||||
|
||||
if (tooltipEnabled()) {
|
||||
std::string tooltip_format = "{used} used out of {total} on {path} ({percentage_used}%)";
|
||||
if (config_["tooltip-format"].isString()) {
|
||||
tooltip_format = config_["tooltip-format"].asString();
|
||||
}
|
||||
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),
|
||||
fmt::arg("path", path_), fmt::arg("specific_free", specific_free),
|
||||
fmt::arg("specific_used", specific_used), fmt::arg("specific_total", specific_total)));
|
||||
|
||||
if (!tooltip_format.empty()) {
|
||||
if (had_valid_disk) {
|
||||
tooltip_label += "\n";
|
||||
}
|
||||
|
||||
tooltip_label += 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), fmt::arg("path", path),
|
||||
fmt::arg("specific_free", specific_free), fmt::arg("specific_used", specific_used),
|
||||
fmt::arg("specific_total", specific_total));
|
||||
}
|
||||
|
||||
had_valid_disk = true;
|
||||
}
|
||||
if (had_valid_disk) {
|
||||
event_box_.show();
|
||||
} else {
|
||||
event_box_.hide();
|
||||
}
|
||||
|
||||
label_.set_markup(label);
|
||||
|
||||
if (tooltipEnabled() && !tooltip_label.empty()) {
|
||||
label_.set_tooltip_markup(tooltip_label);
|
||||
}
|
||||
// Call parent update
|
||||
ALabel::update();
|
||||
@@ -109,7 +158,7 @@ float waybar::modules::Disk::calc_specific_divisor(const std::string& divisor) {
|
||||
return 1000.0 * 1000.0 * 1000.0 * 1000.0;
|
||||
} else if (divisor == "TiB") {
|
||||
return 1024.0 * 1024.0 * 1024.0 * 1024.0;
|
||||
} else { // default to Bytes if it is anything that we don't recongnise
|
||||
} else { // default to Bytes if it is anything that we don't recognise
|
||||
return 1.0;
|
||||
}
|
||||
}
|
||||
|
||||
+44
-23
@@ -26,7 +26,7 @@ static void toggle_visibility(void* data, zdwl_ipc_output_v2* zdwl_output_v2) {
|
||||
}
|
||||
|
||||
static void active(void* data, zdwl_ipc_output_v2* zdwl_output_v2, uint32_t active) {
|
||||
// Intentionally empty
|
||||
static_cast<Tags*>(data)->handle_active_output(zdwl_output_v2, active);
|
||||
}
|
||||
|
||||
static void set_tag(void* data, zdwl_ipc_output_v2* zdwl_output_v2, uint32_t tag, uint32_t state,
|
||||
@@ -70,32 +70,31 @@ static const zdwl_ipc_output_v2_listener output_status_listener_impl{
|
||||
|
||||
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 (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;
|
||||
}
|
||||
if (self->status_manager_) {
|
||||
zdwl_ipc_manager_v2_destroy(self->status_manager_);
|
||||
self->status_manager_ = nullptr;
|
||||
}
|
||||
|
||||
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;
|
||||
self->status_manager_ = static_cast<struct zdwl_ipc_manager_v2*>(
|
||||
wl_registry_bind(registry, name, &zdwl_ipc_manager_v2_interface, 1));
|
||||
}
|
||||
|
||||
version = std::min<uint32_t>(version, 1);
|
||||
if (std::strcmp(interface, wl_seat_interface.name) == 0) {
|
||||
auto* self = static_cast<Tags*>(data);
|
||||
|
||||
self->seat_ = static_cast<struct wl_seat*>(
|
||||
wl_registry_bind(registry, name, &wl_seat_interface, version));
|
||||
}
|
||||
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 */
|
||||
@@ -110,7 +109,11 @@ Tags::Tags(const std::string& id, const waybar::Bar& bar, const Json::Value& con
|
||||
seat_{nullptr},
|
||||
bar_(bar),
|
||||
box_{bar.orientation, 0},
|
||||
hide_vacant_(false),
|
||||
output_status_{nullptr} {
|
||||
if (config_["hide-vacant"].asBool()) {
|
||||
hide_vacant_ = config_["hide-vacant"].asBool();
|
||||
}
|
||||
struct wl_display* display = Client::inst()->wl_display;
|
||||
struct wl_registry* registry = wl_display_get_registry(display);
|
||||
|
||||
@@ -163,7 +166,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);
|
||||
|
||||
@@ -221,6 +224,24 @@ void Tags::handle_view_tags(uint32_t tag, uint32_t state, uint32_t clients, uint
|
||||
} else {
|
||||
button.get_style_context()->remove_class("urgent");
|
||||
}
|
||||
|
||||
if (hide_vacant_ && !clients && !(state & TAG_ACTIVE)) {
|
||||
button.set_visible(false);
|
||||
} else {
|
||||
button.set_visible(true);
|
||||
}
|
||||
}
|
||||
|
||||
void Tags::handle_active_output(zdwl_ipc_output_v2* zdwl_output_v2, uint32_t active) {
|
||||
if (output_status_ == zdwl_output_v2) {
|
||||
for (size_t i = 0; i < buttons_.size(); ++i) {
|
||||
if (active == 0) {
|
||||
buttons_[i].get_style_context()->remove_class("output");
|
||||
} else {
|
||||
buttons_[i].get_style_context()->add_class("output");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace waybar::modules::dwl */
|
||||
|
||||
@@ -19,7 +19,7 @@ static void toggle_visibility(void* data, zdwl_ipc_output_v2* zdwl_output_v2) {
|
||||
}
|
||||
|
||||
static void active(void* data, zdwl_ipc_output_v2* zdwl_output_v2, uint32_t active) {
|
||||
// Intentionally empty
|
||||
static_cast<Window*>(data)->handle_active(active);
|
||||
}
|
||||
|
||||
static void set_tag(void* data, zdwl_ipc_output_v2* zdwl_output_v2, uint32_t tag, uint32_t state,
|
||||
@@ -74,7 +74,17 @@ static const wl_registry_listener registry_listener_impl = {.global = handle_glo
|
||||
.global_remove = handle_global_remove};
|
||||
|
||||
Window::Window(const std::string& id, const Bar& bar, const Json::Value& config)
|
||||
: AAppIconLabel(config, "window", id, "{}", 0, true), bar_(bar) {
|
||||
: AAppIconLabel(config, "window", id, "{}", 0, true),
|
||||
bar_(bar),
|
||||
active_(false),
|
||||
hide_inactive_(false),
|
||||
hide_empty_(false) {
|
||||
if (config_["hide-inactive"].isBool()) {
|
||||
hide_inactive_ = config["hide-inactive"].asBool();
|
||||
}
|
||||
if (config_["hide-empty"].isBool()) {
|
||||
hide_empty_ = config["hide-empty"].asBool();
|
||||
}
|
||||
struct wl_display* display = Client::inst()->wl_display;
|
||||
struct wl_registry* registry = wl_display_get_registry(display);
|
||||
|
||||
@@ -102,6 +112,8 @@ void Window::handle_title(const char* title) { title_ = Glib::Markup::escape_tex
|
||||
|
||||
void Window::handle_appid(const char* appid) { appid_ = Glib::Markup::escape_text(appid); }
|
||||
|
||||
void Window::handle_active(const uint32_t active) { active_ = active != 0; }
|
||||
|
||||
void Window::handle_layout_symbol(const char* layout_symbol) {
|
||||
layout_symbol_ = Glib::Markup::escape_text(layout_symbol);
|
||||
}
|
||||
@@ -118,6 +130,19 @@ void Window::handle_frame() {
|
||||
if (tooltipEnabled()) {
|
||||
label_.set_tooltip_markup(title_);
|
||||
}
|
||||
if (hide_empty_ && title_.empty()) {
|
||||
box_.set_visible(false);
|
||||
} else {
|
||||
if (active_) {
|
||||
box_.get_style_context()->add_class("active");
|
||||
box_.set_visible(true);
|
||||
} else {
|
||||
box_.get_style_context()->remove_class("active");
|
||||
if (hide_inactive_) {
|
||||
box_.set_visible(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace waybar::modules::dwl
|
||||
|
||||
@@ -85,6 +85,25 @@ auto Language::update() -> void {
|
||||
label_.hide();
|
||||
}
|
||||
|
||||
// Tooltip support
|
||||
if (tooltipEnabled()) {
|
||||
std::string tooltipFormat;
|
||||
if (config_["tooltip-format"].isString()) {
|
||||
tooltipFormat = config_["tooltip-format"].asString();
|
||||
} else {
|
||||
tooltipFormat = "{long}";
|
||||
}
|
||||
auto tooltipText = trim(fmt::format(
|
||||
fmt::runtime(tooltipFormat),
|
||||
fmt::arg("long", layout_.full_name),
|
||||
fmt::arg("short", layout_.short_name),
|
||||
fmt::arg("shortDescription", layout_.short_description),
|
||||
fmt::arg("variant", layout_.variant)));
|
||||
label_.set_tooltip_text(tooltipText);
|
||||
} else {
|
||||
label_.set_tooltip_text("");
|
||||
}
|
||||
|
||||
ALabel::update();
|
||||
}
|
||||
|
||||
@@ -130,7 +149,9 @@ void Language::onEvent(const std::string& ev) {
|
||||
|
||||
layoutName = waybar::util::sanitize_string(layoutName);
|
||||
|
||||
removeXkbLayoutCssClass();
|
||||
layout_ = getLayout(layoutName);
|
||||
addXkbLayoutCssClass();
|
||||
|
||||
spdlog::debug("hyprland language onevent with {}", layoutName);
|
||||
|
||||
@@ -152,6 +173,7 @@ void Language::initLanguage() {
|
||||
searcher = waybar::util::sanitize_string(searcher);
|
||||
|
||||
layout_ = getLayout(searcher);
|
||||
addXkbLayoutCssClass();
|
||||
|
||||
spdlog::debug("hyprland language initLanguage found {}", layout_.full_name);
|
||||
|
||||
@@ -161,6 +183,15 @@ void Language::initLanguage() {
|
||||
}
|
||||
}
|
||||
|
||||
auto Language::removeXkbLayoutCssClass() -> void {
|
||||
label_.get_style_context()->remove_class(layout_.short_name);
|
||||
spdlog::debug("hyprland language try to remove currently short_name css class {}", layout_.short_name);
|
||||
}
|
||||
auto Language::addXkbLayoutCssClass() -> void {
|
||||
label_.get_style_context()->add_class(layout_.short_name);
|
||||
spdlog::debug("hyprland language add new short_name css class {}", layout_.short_name);
|
||||
}
|
||||
|
||||
auto Language::getLayout(const std::string& fullName) -> Layout {
|
||||
auto* const context = rxkb_context_new(RXKB_CONTEXT_LOAD_EXOTIC_RULES);
|
||||
rxkb_context_parse_default_ruleset(context);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#include <spdlog/spdlog.h>
|
||||
#include <glibmm/main.h>
|
||||
|
||||
#include <cctype>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
@@ -10,6 +11,33 @@
|
||||
#include "util/command.hpp"
|
||||
#include "util/icon_loader.hpp"
|
||||
|
||||
namespace {
|
||||
constexpr std::string_view kCssClassPrefix = "ws-";
|
||||
|
||||
// Convert a workspace name to a valid CSS class name.
|
||||
// Lowercases, replaces non-alphanumeric runs with single hyphens,
|
||||
// and prefixes digit-leading names (CSS classes can't start with a digit).
|
||||
std::string sanitizeCssClass(const std::string& name) {
|
||||
std::string result;
|
||||
result.reserve(name.size() + kCssClassPrefix.size());
|
||||
for (auto c : name) {
|
||||
auto uc = static_cast<unsigned char>(c);
|
||||
if (std::isalnum(uc)) {
|
||||
result += static_cast<char>(std::tolower(uc));
|
||||
} else if (!result.empty() && result.back() != '-') {
|
||||
result += '-';
|
||||
}
|
||||
}
|
||||
if (!result.empty() && result.back() == '-') {
|
||||
result.pop_back();
|
||||
}
|
||||
if (!result.empty() && std::isdigit(static_cast<unsigned char>(result.front()))) {
|
||||
result.insert(0, kCssClassPrefix);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
namespace waybar::modules::hyprland {
|
||||
|
||||
Workspace::Workspace(const Json::Value& workspace_data, Workspaces& workspace_manager,
|
||||
@@ -270,6 +298,11 @@ bool Workspace::onWindowOpened(WindowCreationPayload const& create_window_payloa
|
||||
std::string& Workspace::selectIcon(std::map<std::string, std::string>& icons_map) {
|
||||
spdlog::trace("Selecting icon for workspace {}", name());
|
||||
if (isUrgent()) {
|
||||
auto urgentNamedIconIt = icons_map.find("urgent:" + name());
|
||||
if (urgentNamedIconIt != icons_map.end()) {
|
||||
return urgentNamedIconIt->second;
|
||||
}
|
||||
|
||||
auto urgentIconIt = icons_map.find("urgent");
|
||||
if (urgentIconIt != icons_map.end()) {
|
||||
return urgentIconIt->second;
|
||||
@@ -288,6 +321,11 @@ std::string& Workspace::selectIcon(std::map<std::string, std::string>& icons_map
|
||||
}
|
||||
|
||||
if (isActive()) {
|
||||
auto activeNamedIconIt = icons_map.find("active:" + name());
|
||||
if (activeNamedIconIt != icons_map.end()) {
|
||||
return activeNamedIconIt->second;
|
||||
}
|
||||
|
||||
auto activeIconIt = icons_map.find("active");
|
||||
if (activeIconIt != icons_map.end()) {
|
||||
return activeIconIt->second;
|
||||
@@ -295,6 +333,11 @@ std::string& Workspace::selectIcon(std::map<std::string, std::string>& icons_map
|
||||
}
|
||||
|
||||
if (isSpecial()) {
|
||||
auto specialNamedIconIt = icons_map.find("special:" + name());
|
||||
if (specialNamedIconIt != icons_map.end()) {
|
||||
return specialNamedIconIt->second;
|
||||
}
|
||||
|
||||
auto specialIconIt = icons_map.find("special");
|
||||
if (specialIconIt != icons_map.end()) {
|
||||
return specialIconIt->second;
|
||||
@@ -335,12 +378,22 @@ std::string& Workspace::selectIcon(std::map<std::string, std::string>& icons_map
|
||||
return m_name;
|
||||
}
|
||||
|
||||
|
||||
void Workspace::update(const std::string& workspace_icon) {
|
||||
if (this->m_workspaceManager.persistentOnly() && !this->isPersistent()) {
|
||||
m_button.hide();
|
||||
return;
|
||||
}
|
||||
// clang-format off
|
||||
if (this->m_workspaceManager.hideActive() && \
|
||||
this->isActive() && \
|
||||
!this->isPersistent() && \
|
||||
!this->isSpecial()) {
|
||||
// clang-format on
|
||||
m_button.hide();
|
||||
return;
|
||||
}
|
||||
// clang-format off
|
||||
if (this->m_workspaceManager.activeOnly() && \
|
||||
!this->isActive() && \
|
||||
!this->isPersistent() && \
|
||||
@@ -367,6 +420,17 @@ void Workspace::update(const std::string& workspace_icon) {
|
||||
addOrRemoveClass(styleContext, isVisible(), "visible");
|
||||
addOrRemoveClass(styleContext, m_workspaceManager.getBarOutput() == output(), "hosting-monitor");
|
||||
|
||||
// Add workspace name as CSS class for per-workspace styling
|
||||
if (!m_prevNameClass.empty()) {
|
||||
styleContext->remove_class(m_prevNameClass);
|
||||
m_prevNameClass.clear();
|
||||
}
|
||||
auto nameClass = sanitizeCssClass(name());
|
||||
if (!nameClass.empty()) {
|
||||
styleContext->add_class(nameClass);
|
||||
m_prevNameClass = nameClass;
|
||||
}
|
||||
|
||||
std::string windows;
|
||||
// Optimization: The {windows} substitution string is only possible if the taskbar is disabled, no
|
||||
// need to compute this if enableTaskbar() is true
|
||||
@@ -374,13 +438,14 @@ void Workspace::update(const std::string& workspace_icon) {
|
||||
auto windowSeparator = m_workspaceManager.getWindowSeparator();
|
||||
|
||||
bool isNotFirst = false;
|
||||
auto end_it = m_workspaceManager.maxWindows() == 0 ? m_windowMap.end() : m_windowMap.begin() + m_workspaceManager.maxWindows();
|
||||
|
||||
for (const auto& window_repr : m_windowMap) {
|
||||
for (auto it = m_windowMap.begin(); it != end_it; ++it) {
|
||||
if (isNotFirst) {
|
||||
windows.append(windowSeparator);
|
||||
}
|
||||
isNotFirst = true;
|
||||
windows.append(window_repr.repr_rewrite);
|
||||
windows.append(it->repr_rewrite);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -471,12 +536,16 @@ void Workspace::updateTaskbar(const std::string& workspace_icon) {
|
||||
};
|
||||
|
||||
if (m_workspaceManager.taskbarReverseDirection()) {
|
||||
for (auto it = m_windowMap.rbegin(); it != m_windowMap.rend(); ++it) {
|
||||
auto rend_it = m_workspaceManager.maxWindows() == 0 ? m_windowMap.rend() : m_windowMap.rbegin() + m_workspaceManager.maxWindows();
|
||||
|
||||
for (auto it = m_windowMap.rbegin(); it != rend_it; ++it) {
|
||||
processWindow(*it);
|
||||
}
|
||||
} else {
|
||||
for (const auto& window_repr : m_windowMap) {
|
||||
processWindow(window_repr);
|
||||
auto end_it = m_workspaceManager.maxWindows() == 0 ? m_windowMap.end() : m_windowMap.begin() + m_workspaceManager.maxWindows();
|
||||
|
||||
for (auto it = m_windowMap.begin(); it != end_it; ++it) {
|
||||
processWindow(*it);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -662,6 +662,7 @@ auto Workspaces::parseConfig(const Json::Value& config) -> void {
|
||||
populateBoolConfig(config, "special-visible-only", m_specialVisibleOnly);
|
||||
populateBoolConfig(config, "persistent-only", m_persistentOnly);
|
||||
populateBoolConfig(config, "active-only", m_activeOnly);
|
||||
populateBoolConfig(config, "hide-active", m_hideActive);
|
||||
populateBoolConfig(config, "move-to-monitor", m_moveToMonitor);
|
||||
populateBoolConfig(config, "enable-bar-scroll", m_barScroll);
|
||||
|
||||
@@ -670,6 +671,7 @@ auto Workspaces::parseConfig(const Json::Value& config) -> void {
|
||||
populateIgnoreWorkspacesConfig(config);
|
||||
populateFormatWindowSeparatorConfig(config);
|
||||
populateWindowRewriteConfig(config);
|
||||
populateMaxWindowsConfig(config);
|
||||
|
||||
if (withWindows) {
|
||||
populateWorkspaceTaskbarConfig(config);
|
||||
@@ -751,6 +753,15 @@ auto Workspaces::populateWindowRewriteConfig(const Json::Value& config) -> void
|
||||
[this](std::string& window_rule) { return windowRewritePriorityFunction(window_rule); });
|
||||
}
|
||||
|
||||
auto Workspaces::populateMaxWindowsConfig(const Json::Value& config) -> void {
|
||||
if (config["max-windows"].isInt()) {
|
||||
m_maxWindows = config["max-windows"].asInt();
|
||||
if (m_maxWindows < 0) {
|
||||
m_maxWindows = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
auto Workspaces::populateWorkspaceTaskbarConfig(const Json::Value& config) -> void {
|
||||
const auto& workspaceTaskbar = config["workspace-taskbar"];
|
||||
if (!workspaceTaskbar.isObject()) {
|
||||
|
||||
+13
-5
@@ -1,5 +1,7 @@
|
||||
#include "modules/image.hpp"
|
||||
|
||||
#include <config.hpp>
|
||||
|
||||
waybar::modules::Image::Image(const std::string& id, const Json::Value& config)
|
||||
: AModule(config, "image", id), box_(Gtk::ORIENTATION_HORIZONTAL, 0) {
|
||||
box_.pack_start(image_);
|
||||
@@ -35,6 +37,13 @@ waybar::modules::Image::Image(const std::string& id, const Json::Value& config)
|
||||
size_ = 16;
|
||||
}
|
||||
|
||||
if (config_["path"].isString()) {
|
||||
auto result = Config::tryExpandPath(config_["path"].asString(), "");
|
||||
path_ = result.empty() ? "" : result.front();
|
||||
} else {
|
||||
path_.clear();
|
||||
}
|
||||
|
||||
delayWorker();
|
||||
}
|
||||
|
||||
@@ -54,13 +63,12 @@ void waybar::modules::Image::refresh(int sig) {
|
||||
}
|
||||
|
||||
auto waybar::modules::Image::update() -> void {
|
||||
if (config_["path"].isString()) {
|
||||
path_ = config_["path"].asString();
|
||||
} else if (config_["exec"].isString()) {
|
||||
if (config_["exec"].isString()) {
|
||||
output_ = util::command::exec(config_["exec"].asString(), "");
|
||||
parseOutputRaw();
|
||||
} else {
|
||||
path_ = "";
|
||||
// expand path if "~" or "$HOME" is present in original path
|
||||
auto result = Config::tryExpandPath(path_, "");
|
||||
path_ = result.empty() ? "" : result.front();
|
||||
}
|
||||
|
||||
if (Glib::file_test(path_, Glib::FILE_TEST_EXISTS)) {
|
||||
|
||||
@@ -78,6 +78,53 @@ auto supportsLockStates(const libevdev* dev) -> bool {
|
||||
libevdev_has_event_code(dev, EV_LED, LED_SCROLLL);
|
||||
}
|
||||
|
||||
auto isCommonFormatIcons(const Json::Value& config) -> bool {
|
||||
return config["format-icons"].isObject() && (config["format-icons"]["locked"].isString() ||
|
||||
config["format-icons"]["unlocked"].isString());
|
||||
}
|
||||
|
||||
auto keyStateToIcons(const Json::Value& config)
|
||||
-> std::unordered_map<std::string, std::vector<std::string>> {
|
||||
std::unordered_map<std::string, std::vector<std::string>> key_icon_states;
|
||||
std::vector<std::string> default_icons = {"unlocked", "locked"};
|
||||
|
||||
if (isCommonFormatIcons(config)) {
|
||||
std::vector<std::string> icons = {
|
||||
config["format-icons"]["unlocked"].isString()
|
||||
? config["format-icons"]["unlocked"].asString()
|
||||
: "unlocked",
|
||||
config["format-icons"]["locked"].isString() ? config["format-icons"]["locked"].asString()
|
||||
: "locked",
|
||||
};
|
||||
key_icon_states["Lock"] = icons;
|
||||
return key_icon_states;
|
||||
}
|
||||
|
||||
bool found_any = false;
|
||||
for (const auto& key : std::vector<std::string>{"numlock", "capslock", "scrolllock"}) {
|
||||
std::string map_key = key.substr(0, key.length() - 4);
|
||||
map_key[0] = std::toupper(map_key[0]);
|
||||
if (config["format-icons"].isObject() && config["format-icons"][key].isObject()) {
|
||||
std::string unlocked = config["format-icons"][key]["unlocked"].isString()
|
||||
? config["format-icons"][key]["unlocked"].asString()
|
||||
: "unlocked";
|
||||
std::string locked = config["format-icons"][key]["locked"].isString()
|
||||
? config["format-icons"][key]["locked"].asString()
|
||||
: "locked";
|
||||
key_icon_states[map_key] = {unlocked, locked};
|
||||
found_any = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!found_any) {
|
||||
key_icon_states["Num"] = default_icons;
|
||||
key_icon_states["Caps"] = default_icons;
|
||||
key_icon_states["Scroll"] = default_icons;
|
||||
}
|
||||
|
||||
return key_icon_states;
|
||||
}
|
||||
|
||||
waybar::modules::KeyboardState::KeyboardState(const std::string& id, const Bar& bar,
|
||||
const Json::Value& config)
|
||||
: AModule(config, "keyboard-state", id, false, !config["disable-scroll"].asBool()),
|
||||
@@ -98,12 +145,7 @@ waybar::modules::KeyboardState::KeyboardState(const std::string& id, const Bar&
|
||||
: "{name} {icon}"),
|
||||
interval_(
|
||||
std::chrono::seconds(config_["interval"].isUInt() ? config_["interval"].asUInt() : 1)),
|
||||
icon_locked_(config_["format-icons"]["locked"].isString()
|
||||
? config_["format-icons"]["locked"].asString()
|
||||
: "locked"),
|
||||
icon_unlocked_(config_["format-icons"]["unlocked"].isString()
|
||||
? config_["format-icons"]["unlocked"].asString()
|
||||
: "unlocked"),
|
||||
key_icon_states_(keyStateToIcons(config_)),
|
||||
devices_path_("/dev/input/"),
|
||||
libinput_(nullptr),
|
||||
libinput_devices_({}) {
|
||||
@@ -290,7 +332,7 @@ auto waybar::modules::KeyboardState::update() -> void {
|
||||
bool state;
|
||||
Gtk::Label& label;
|
||||
const std::string& format;
|
||||
const char* name;
|
||||
const std::string name;
|
||||
} label_states[] = {
|
||||
{(bool)numl, numlock_label_, numlock_format_, "Num"},
|
||||
{(bool)capsl, capslock_label_, capslock_format_, "Caps"},
|
||||
@@ -298,8 +340,21 @@ auto waybar::modules::KeyboardState::update() -> void {
|
||||
};
|
||||
for (auto& label_state : label_states) {
|
||||
std::string text;
|
||||
std::string map_key = isCommonFormatIcons(config_) ? "Lock" : label_state.name;
|
||||
|
||||
if (key_icon_states_.find(map_key) == key_icon_states_.end()) {
|
||||
spdlog::warn("keyboard-state: Missing icon configuration for '{}'", map_key);
|
||||
continue;
|
||||
}
|
||||
|
||||
auto& icons = key_icon_states_[map_key];
|
||||
if (icons.size() < 2) {
|
||||
spdlog::warn("keyboard-state: Invalid icon vector size for '{}'", map_key);
|
||||
continue;
|
||||
}
|
||||
|
||||
text = fmt::format(fmt::runtime(label_state.format),
|
||||
fmt::arg("icon", label_state.state ? icon_locked_ : icon_unlocked_),
|
||||
fmt::arg("icon", label_state.state ? icons[1] : icons[0]),
|
||||
fmt::arg("name", label_state.name));
|
||||
label_state.label.set_markup(text);
|
||||
if (label_state.state) {
|
||||
|
||||
@@ -0,0 +1,317 @@
|
||||
#include "modules/mango/backend.hpp"
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <poll.h>
|
||||
#include <spdlog/spdlog.h>
|
||||
#include <sys/poll.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/un.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <sstream>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "util/scoped_fd.hpp"
|
||||
|
||||
namespace waybar::modules::mango {
|
||||
|
||||
int IPC::connectToSocket() {
|
||||
const char* socket_path = getenv("MANGO_INSTANCE_SIGNATURE");
|
||||
if (!socket_path) {
|
||||
throw std::runtime_error("Mango IPC: MANGO_INSTANCE_SIGNATURE not set");
|
||||
}
|
||||
|
||||
struct sockaddr_un addr;
|
||||
util::ScopedFd fd(socket(AF_UNIX, SOCK_STREAM, 0));
|
||||
if (fd == -1) throw std::runtime_error("socket() failed");
|
||||
|
||||
addr.sun_family = AF_UNIX;
|
||||
strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path) - 1);
|
||||
addr.sun_path[sizeof(addr.sun_path) - 1] = 0;
|
||||
|
||||
if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
|
||||
throw std::runtime_error("connect() failed");
|
||||
}
|
||||
return fd.release();
|
||||
}
|
||||
|
||||
Json::Value IPC::sendCommand(const std::string& cmd) {
|
||||
util::ScopedFd fd(IPC::connectToSocket());
|
||||
std::string full_cmd = cmd + "\n";
|
||||
|
||||
ssize_t total_written = 0;
|
||||
while (total_written < (ssize_t)full_cmd.size()) {
|
||||
ssize_t res = write(fd, full_cmd.c_str() + total_written, full_cmd.size() - total_written);
|
||||
if (res < 0) {
|
||||
if (errno == EINTR) continue;
|
||||
throw std::runtime_error("Failed to write command");
|
||||
}
|
||||
total_written += res;
|
||||
}
|
||||
|
||||
char buf[4096];
|
||||
std::string response;
|
||||
while (true) {
|
||||
ssize_t n = read(fd, buf, sizeof(buf) - 1);
|
||||
if (n <= 0) {
|
||||
if (n == 0) break;
|
||||
if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) continue;
|
||||
throw std::runtime_error("Read error");
|
||||
}
|
||||
buf[n] = '\0';
|
||||
response += buf;
|
||||
if (response.find('\n') != std::string::npos) break;
|
||||
}
|
||||
|
||||
Json::Value root;
|
||||
std::istringstream iss(response);
|
||||
Json::CharReaderBuilder builder;
|
||||
std::string errors;
|
||||
if (!Json::parseFromStream(builder, iss, &root, &errors)) {
|
||||
throw std::runtime_error("JSON parse error: " + errors);
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
Json::Value IPC::send(const Json::Value& request) {
|
||||
if (!request.isMember("command")) {
|
||||
throw std::runtime_error("Mango IPC: request must have 'command' field");
|
||||
}
|
||||
return sendCommand(request["command"].asString());
|
||||
}
|
||||
|
||||
void IPC::sendAsync(const Json::Value& request) {
|
||||
if (!request.isMember("command")) {
|
||||
spdlog::error("Mango IPC: request must have 'command' field");
|
||||
return;
|
||||
}
|
||||
std::string cmd = request["command"].asString();
|
||||
|
||||
std::thread([cmd]() {
|
||||
try {
|
||||
IPC::sendCommand(cmd);
|
||||
} catch (const std::exception& e) {
|
||||
spdlog::error("IPC async send failed: {}", e.what());
|
||||
}
|
||||
}).detach();
|
||||
}
|
||||
|
||||
IPC::IPC() : sockfd_(-1), active_client_(Json::nullValue) { startIPC(); }
|
||||
|
||||
IPC::~IPC() {
|
||||
if (sockfd_ != -1) close(sockfd_);
|
||||
if (ipc_thread_.joinable()) ipc_thread_.join();
|
||||
}
|
||||
|
||||
void IPC::startIPC() {
|
||||
sockfd_ = IPC::connectToSocket();
|
||||
|
||||
ipc_thread_ = std::thread([this]() {
|
||||
spdlog::info("Mango IPC thread started");
|
||||
|
||||
struct pollfd pfd;
|
||||
pfd.fd = sockfd_;
|
||||
pfd.events = POLLIN;
|
||||
|
||||
const std::vector<std::string> subs = {"watch all-monitors"};
|
||||
for (const auto& cmd : subs) {
|
||||
if (write(sockfd_, cmd.c_str(), cmd.size()) != (ssize_t)cmd.size() ||
|
||||
write(sockfd_, "\n", 1) != 1) {
|
||||
spdlog::error("Failed to subscribe to {}", cmd);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
char buf[4096];
|
||||
std::string buffer;
|
||||
while (true) {
|
||||
int ret = poll(&pfd, 1, 1000);
|
||||
if (ret == 0) continue;
|
||||
if (ret < 0) {
|
||||
if (errno == EINTR) continue;
|
||||
spdlog::error("IPC poll error: {}", strerror(errno));
|
||||
break;
|
||||
}
|
||||
|
||||
if (pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) {
|
||||
spdlog::info("Mango IPC socket closed or invalid");
|
||||
break;
|
||||
}
|
||||
|
||||
if (pfd.revents & POLLIN) {
|
||||
ssize_t n = read(sockfd_, buf, sizeof(buf));
|
||||
if (n == 0) {
|
||||
spdlog::info("Mango IPC connection closed");
|
||||
break;
|
||||
}
|
||||
if (n < 0) {
|
||||
if (errno == EINTR) continue;
|
||||
spdlog::error("IPC read error: {}", strerror(errno));
|
||||
break;
|
||||
}
|
||||
buffer.append(buf, n);
|
||||
|
||||
size_t pos;
|
||||
while ((pos = buffer.find('\n')) != std::string::npos) {
|
||||
std::string line = buffer.substr(0, pos);
|
||||
buffer.erase(0, pos + 1);
|
||||
if (line.empty()) continue;
|
||||
try {
|
||||
parseIPC(line);
|
||||
} catch (const std::exception& e) {
|
||||
spdlog::warn("Failed to parse IPC line: {} - {}", line, e.what());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void IPC::parseIPC(const std::string& line) {
|
||||
Json::Value root;
|
||||
Json::CharReaderBuilder builder;
|
||||
std::string errors;
|
||||
std::istringstream iss(line);
|
||||
if (!Json::parseFromStream(builder, iss, &root, &errors)) {
|
||||
throw std::runtime_error("JSON parse error: " + errors);
|
||||
}
|
||||
|
||||
if (root.isMember("monitors") && root["monitors"].isArray()) {
|
||||
for (const auto& mon : root["monitors"]) {
|
||||
handleMonitorUpdate(mon);
|
||||
}
|
||||
|
||||
Json::Value active_monitor;
|
||||
for (const auto& mon : root["monitors"]) {
|
||||
if (mon["active"].asBool()) {
|
||||
active_monitor = mon;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!active_monitor.isNull()) {
|
||||
const auto& active_client = active_monitor["active_client"];
|
||||
updateFocusingClient(active_client);
|
||||
|
||||
if (active_monitor.isMember("keyboardlayout")) {
|
||||
updateKeyboardLayout(active_monitor["keyboardlayout"].asString());
|
||||
}
|
||||
|
||||
if (active_monitor.isMember("keymode")) {
|
||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||
keymode_ = active_monitor["keymode"].asString();
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<EventHandler*> handlers_to_notify;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(callback_mutex_);
|
||||
for (auto& [ev, handler] : callbacks_) {
|
||||
if (ev == "monitor") {
|
||||
handlers_to_notify.push_back(handler);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (auto* handler : handlers_to_notify) {
|
||||
handler->onEvent(root);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
spdlog::debug("Unhandled IPC message: {}", line);
|
||||
}
|
||||
|
||||
std::unordered_map<std::string, Json::Value> IPC::getMonitors() const {
|
||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||
return monitors_;
|
||||
}
|
||||
|
||||
IPC& IPC::getInstance() {
|
||||
static IPC instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
Json::Value IPC::getMonitor(const std::string& name) {
|
||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||
auto it = monitors_.find(name);
|
||||
if (it != monitors_.end()) {
|
||||
return it->second;
|
||||
}
|
||||
return Json::nullValue;
|
||||
}
|
||||
|
||||
std::string IPC::getKeyboardLayout() const {
|
||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||
return keyboard_layout_;
|
||||
}
|
||||
|
||||
std::string IPC::getKeymode() const {
|
||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||
return keymode_;
|
||||
}
|
||||
|
||||
Json::Value IPC::getActiveClientForMonitor(const std::string& name) const {
|
||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||
auto it = monitors_.find(name);
|
||||
if (it != monitors_.end() && it->second.isMember("active_client")) {
|
||||
return it->second["active_client"];
|
||||
}
|
||||
return Json::nullValue;
|
||||
}
|
||||
|
||||
std::string IPC::getLayoutSymbolForMonitor(const std::string& name) const {
|
||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||
auto it = monitors_.find(name);
|
||||
if (it != monitors_.end() && it->second.isMember("layout_symbol")) {
|
||||
return it->second["layout_symbol"].asString();
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
void IPC::handleMonitorUpdate(const Json::Value& mon) {
|
||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||
monitors_[mon["name"].asString()] = mon;
|
||||
}
|
||||
|
||||
void IPC::updateFocusingClient(const Json::Value& client) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||
active_client_ = client;
|
||||
|
||||
if (client.isNull() || !client.isObject() || client["id"].isNull()) {
|
||||
focusing_client_id_ = 0;
|
||||
} else {
|
||||
focusing_client_id_ = client["id"].asUInt64();
|
||||
clients_[focusing_client_id_] = client;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void IPC::updateKeyboardLayout(const std::string& layout) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||
keyboard_layout_ = layout;
|
||||
}
|
||||
}
|
||||
|
||||
void IPC::registerForIPC(const std::string& ev, EventHandler* handler) {
|
||||
if (!handler) return;
|
||||
std::lock_guard<std::mutex> lock(callback_mutex_);
|
||||
callbacks_.emplace_back(ev, handler);
|
||||
}
|
||||
|
||||
void IPC::unregisterForIPC(EventHandler* handler) {
|
||||
if (!handler) return;
|
||||
std::lock_guard<std::mutex> lock(callback_mutex_);
|
||||
for (auto it = callbacks_.begin(); it != callbacks_.end();) {
|
||||
if (it->second == handler)
|
||||
it = callbacks_.erase(it);
|
||||
else
|
||||
++it;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace waybar::modules::mango
|
||||
@@ -0,0 +1,58 @@
|
||||
#include "modules/mango/keymode.hpp"
|
||||
|
||||
#include <spdlog/spdlog.h>
|
||||
|
||||
namespace waybar::modules::mango {
|
||||
|
||||
Keymode::Keymode(const std::string& id, const Bar& bar, const Json::Value& config)
|
||||
: ALabel(config, "keymode", id, "{}", 0, false), bar_(bar) {
|
||||
IPC::getInstance().registerForIPC("monitor", this);
|
||||
dp.emit();
|
||||
}
|
||||
|
||||
Keymode::~Keymode() { IPC::getInstance().unregisterForIPC(this); }
|
||||
|
||||
void Keymode::onEvent(const Json::Value& ev) { dp.emit(); }
|
||||
|
||||
void Keymode::doUpdate() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
std::string current = IPC::getInstance().getKeymode();
|
||||
|
||||
// if keymode is empty, hide the label
|
||||
if (current.empty()) {
|
||||
label_.hide();
|
||||
last_keymode_.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
// if keymode is the same as last time, skip style changes
|
||||
if (current != last_keymode_) {
|
||||
if (!last_keymode_.empty()) label_.get_style_context()->remove_class(last_keymode_);
|
||||
label_.get_style_context()->add_class(current);
|
||||
last_keymode_ = current;
|
||||
}
|
||||
|
||||
// support config's format-keymode custom format (such as format-default, format-resize, etc.)
|
||||
std::string text;
|
||||
std::string format_key = "format-" + current;
|
||||
if (config_.isMember(format_key)) {
|
||||
text = fmt::format(fmt::runtime(config_[format_key].asString()), fmt::arg("mode", current));
|
||||
} else {
|
||||
text = fmt::format(fmt::runtime(format_), fmt::arg("mode", current));
|
||||
}
|
||||
|
||||
if (!text.empty()) {
|
||||
label_.show();
|
||||
label_.set_markup(text);
|
||||
} else {
|
||||
label_.hide();
|
||||
}
|
||||
}
|
||||
|
||||
void Keymode::update() {
|
||||
doUpdate();
|
||||
ALabel::update();
|
||||
}
|
||||
|
||||
} // namespace waybar::modules::mango
|
||||
@@ -0,0 +1,148 @@
|
||||
#include "modules/mango/language.hpp"
|
||||
|
||||
#include <spdlog/spdlog.h>
|
||||
#include <xkbcommon/xkbcommon.h>
|
||||
#include <xkbcommon/xkbregistry.h>
|
||||
|
||||
#include "util/string.hpp"
|
||||
|
||||
namespace waybar::modules::mango {
|
||||
|
||||
Language::Language(const std::string& id, const Bar& bar, const Json::Value& config)
|
||||
: ALabel(config, "language", id, "{}", 0, false), bar_(bar), rxkb_ctx_(nullptr) {
|
||||
rxkb_ctx_ = rxkb_context_new(RXKB_CONTEXT_LOAD_EXOTIC_RULES);
|
||||
if (rxkb_ctx_) {
|
||||
rxkb_context_parse_default_ruleset(rxkb_ctx_);
|
||||
}
|
||||
|
||||
IPC::getInstance().registerForIPC("monitor", this);
|
||||
updateFromIPC();
|
||||
dp.emit();
|
||||
}
|
||||
|
||||
Language::~Language() {
|
||||
IPC::getInstance().unregisterForIPC(this);
|
||||
if (rxkb_ctx_) rxkb_context_unref(rxkb_ctx_);
|
||||
}
|
||||
|
||||
void Language::updateFromIPC() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
std::string layout = IPC::getInstance().getKeyboardLayout();
|
||||
|
||||
layouts_.clear();
|
||||
if (!layout.empty()) {
|
||||
Layout l = getLayout(layout);
|
||||
layouts_.push_back(l);
|
||||
current_idx_ = 0;
|
||||
} else {
|
||||
current_idx_ = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void Language::doUpdate() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (layouts_.empty() || current_idx_ >= layouts_.size()) {
|
||||
label_.hide();
|
||||
return;
|
||||
}
|
||||
const auto& layout = layouts_[current_idx_];
|
||||
|
||||
if (!last_short_name_.empty()) label_.get_style_context()->remove_class(last_short_name_);
|
||||
if (!layout.short_name.empty()) {
|
||||
label_.get_style_context()->add_class(layout.short_name);
|
||||
last_short_name_ = layout.short_name;
|
||||
}
|
||||
|
||||
std::string layoutName;
|
||||
std::string variant_key = "format-" + layout.short_description + "-" + layout.variant;
|
||||
if (!layout.variant.empty() && config_.isMember(variant_key)) {
|
||||
layoutName =
|
||||
fmt::format(fmt::runtime(config_[variant_key].asString()),
|
||||
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 (config_.isMember("format-" + layout.short_description)) {
|
||||
std::string key = "format-" + layout.short_description;
|
||||
layoutName =
|
||||
fmt::format(fmt::runtime(config_[key].asString()), fmt::arg("long", layout.full_name),
|
||||
fmt::arg("short", layout.short_name),
|
||||
fmt::arg("shortDescription", layout.short_description),
|
||||
fmt::arg("variant", layout.variant));
|
||||
} else {
|
||||
layoutName = fmt::format(fmt::runtime(format_), fmt::arg("long", layout.full_name),
|
||||
fmt::arg("short", layout.short_name),
|
||||
fmt::arg("shortDescription", layout.short_description),
|
||||
fmt::arg("variant", layout.variant));
|
||||
}
|
||||
|
||||
if (!layoutName.empty()) {
|
||||
label_.show();
|
||||
label_.set_markup(layoutName);
|
||||
} else {
|
||||
label_.hide();
|
||||
}
|
||||
}
|
||||
|
||||
void Language::update() {
|
||||
updateFromIPC();
|
||||
doUpdate();
|
||||
ALabel::update();
|
||||
}
|
||||
|
||||
void Language::onEvent(const Json::Value& ev) {
|
||||
updateFromIPC();
|
||||
dp.emit();
|
||||
}
|
||||
|
||||
Language::Layout Language::getLayout(const std::string& fullName) {
|
||||
if (rxkb_ctx_) {
|
||||
rxkb_layout* layout = rxkb_layout_first(rxkb_ctx_);
|
||||
while (layout != nullptr) {
|
||||
std::string desc = rxkb_layout_get_description(layout);
|
||||
if (desc == fullName) {
|
||||
std::string short_name = rxkb_layout_get_name(layout);
|
||||
const char* variant_ptr = rxkb_layout_get_variant(layout);
|
||||
std::string variant = variant_ptr ? variant_ptr : "";
|
||||
const char* brief_ptr = rxkb_layout_get_brief(layout);
|
||||
std::string short_description = brief_ptr ? brief_ptr : "";
|
||||
|
||||
if (short_description.empty()) {
|
||||
short_description = short_name;
|
||||
}
|
||||
|
||||
short_description = short_name;
|
||||
|
||||
Layout info{desc, short_name, variant, short_description};
|
||||
return info;
|
||||
}
|
||||
layout = rxkb_layout_next(layout);
|
||||
}
|
||||
}
|
||||
|
||||
spdlog::warn("mango language: rxkb failed to find layout '{}', using string parsing fallback",
|
||||
fullName);
|
||||
|
||||
Layout l;
|
||||
l.full_name = fullName;
|
||||
l.variant = "";
|
||||
|
||||
size_t paren_start = fullName.find('(');
|
||||
size_t paren_end = fullName.find(')');
|
||||
if (paren_start != std::string::npos && paren_end != std::string::npos &&
|
||||
paren_end > paren_start) {
|
||||
l.short_name = fullName.substr(paren_start + 1, paren_end - paren_start - 1);
|
||||
} else if (fullName.length() >= 2) {
|
||||
l.short_name = fullName.substr(0, 2);
|
||||
} else {
|
||||
l.short_name = fullName;
|
||||
}
|
||||
|
||||
std::transform(l.short_name.begin(), l.short_name.end(), l.short_name.begin(),
|
||||
[](unsigned char c) { return std::tolower(c); });
|
||||
|
||||
l.short_description = l.short_name;
|
||||
|
||||
return l;
|
||||
}
|
||||
|
||||
} // namespace waybar::modules::mango
|
||||
@@ -0,0 +1,56 @@
|
||||
#include "modules/mango/layout.hpp"
|
||||
|
||||
#include <spdlog/spdlog.h>
|
||||
|
||||
namespace waybar::modules::mango {
|
||||
|
||||
Layout::Layout(const std::string& id, const Bar& bar, const Json::Value& config)
|
||||
: ALabel(config, "layout", id, "{}", 0, false), bar_(bar) {
|
||||
IPC::getInstance().registerForIPC("monitor", this);
|
||||
dp.emit();
|
||||
}
|
||||
|
||||
Layout::~Layout() { IPC::getInstance().unregisterForIPC(this); }
|
||||
|
||||
void Layout::onEvent(const Json::Value& ev) { dp.emit(); }
|
||||
|
||||
void Layout::doUpdate() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
std::string symbol = IPC::getInstance().getLayoutSymbolForMonitor(bar_.output->name);
|
||||
|
||||
if (symbol.empty()) {
|
||||
label_.hide();
|
||||
last_symbol_.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
if (symbol != last_symbol_) {
|
||||
if (!last_symbol_.empty()) label_.get_style_context()->remove_class(last_symbol_);
|
||||
label_.get_style_context()->add_class(symbol);
|
||||
last_symbol_ = symbol;
|
||||
}
|
||||
|
||||
std::string text;
|
||||
std::string format_key = "format-" + symbol;
|
||||
|
||||
if (config_.isMember(format_key)) {
|
||||
text = fmt::format(fmt::runtime(config_[format_key].asString()), fmt::arg("symbol", symbol));
|
||||
} else {
|
||||
text = fmt::format(fmt::runtime(format_), fmt::arg("symbol", symbol));
|
||||
}
|
||||
|
||||
if (!text.empty()) {
|
||||
label_.show();
|
||||
label_.set_markup(text);
|
||||
} else {
|
||||
label_.hide();
|
||||
}
|
||||
}
|
||||
|
||||
void Layout::update() {
|
||||
doUpdate();
|
||||
ALabel::update();
|
||||
}
|
||||
|
||||
} // namespace waybar::modules::mango
|
||||
@@ -0,0 +1,93 @@
|
||||
#include "modules/mango/window.hpp"
|
||||
|
||||
#include <spdlog/spdlog.h>
|
||||
|
||||
#include "util/rewrite_string.hpp"
|
||||
#include "util/sanitize_str.hpp"
|
||||
|
||||
namespace waybar::modules::mango {
|
||||
|
||||
Window::Window(const std::string& id, const Bar& bar, const Json::Value& config)
|
||||
: AAppIconLabel(config, "window", id, "{title}", 0, true), bar_(bar) {
|
||||
IPC::getInstance().registerForIPC("monitor", this);
|
||||
dp.emit();
|
||||
}
|
||||
|
||||
Window::~Window() { IPC::getInstance().unregisterForIPC(this); }
|
||||
|
||||
void Window::onEvent(const Json::Value& ev) { dp.emit(); }
|
||||
|
||||
void Window::doUpdate() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
const Json::Value& client = IPC::getInstance().getActiveClientForMonitor(bar_.output->name);
|
||||
|
||||
// judge whether to hide: active_client is null or title field is null
|
||||
if (client.isNull() || !client.isObject() || client["title"].isNull()) {
|
||||
event_box_.hide();
|
||||
label_.hide();
|
||||
updateAppIconName("", "");
|
||||
setClass("empty", true);
|
||||
if (!oldAppId_.empty()) setClass(oldAppId_, false);
|
||||
oldAppId_.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
// if we have a valid client, show the label and update content
|
||||
event_box_.show();
|
||||
label_.show();
|
||||
setClass("empty", false);
|
||||
|
||||
std::string title = client["title"].asString();
|
||||
std::string appid = client["appid"].asString();
|
||||
std::string sanitized_title = waybar::util::sanitize_string(title);
|
||||
std::string sanitized_appid = waybar::util::sanitize_string(appid);
|
||||
|
||||
label_.set_markup(waybar::util::rewriteString(
|
||||
fmt::format(fmt::runtime(format_), fmt::arg("title", sanitized_title),
|
||||
fmt::arg("app_id", sanitized_appid)),
|
||||
config_["rewrite"]));
|
||||
|
||||
updateAppIconName(appid, "");
|
||||
if (tooltipEnabled()) label_.set_tooltip_markup(title);
|
||||
|
||||
// Solo judgment
|
||||
bool solo = false;
|
||||
if (client.isMember("tags") && client["tags"].isArray() && client["tags"].size() == 1) {
|
||||
int tag_idx = client["tags"][0].asInt();
|
||||
const auto& monitors = IPC::getInstance().getMonitors();
|
||||
auto mon_it = monitors.find(client["monitor"].asString());
|
||||
if (mon_it != monitors.end()) {
|
||||
const auto& tags = mon_it->second["tags"];
|
||||
for (const auto& tag : tags) {
|
||||
if (tag["index"].asInt() == tag_idx) {
|
||||
solo = (tag["client_count"].asInt() == 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
setClass("solo", solo);
|
||||
if (!appid.empty()) setClass(appid, solo);
|
||||
|
||||
if (oldAppId_ != appid) {
|
||||
if (!oldAppId_.empty()) setClass(oldAppId_, false);
|
||||
oldAppId_ = appid;
|
||||
}
|
||||
}
|
||||
|
||||
void Window::update() {
|
||||
doUpdate();
|
||||
AAppIconLabel::update();
|
||||
}
|
||||
|
||||
void Window::setClass(const std::string& className, bool enable) {
|
||||
auto style_context = event_box_.get_style_context();
|
||||
if (enable) {
|
||||
if (!style_context->has_class(className)) style_context->add_class(className);
|
||||
} else {
|
||||
style_context->remove_class(className);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace waybar::modules::mango
|
||||
@@ -0,0 +1,252 @@
|
||||
#include "modules/mango/workspaces.hpp"
|
||||
|
||||
#include <spdlog/spdlog.h>
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace waybar::modules::mango {
|
||||
|
||||
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()) box_.get_style_context()->add_class(id);
|
||||
box_.get_style_context()->add_class(MODULE_CLASS);
|
||||
event_box_.add(box_);
|
||||
|
||||
if (config_["on-click"].isString()) on_click_left_ = config_["on-click"].asString();
|
||||
if (config_["on-click-middle"].isString())
|
||||
on_click_middle_ = config_["on-click-middle"].asString();
|
||||
if (config_["on-click-right"].isString()) on_click_right_ = config_["on-click-right"].asString();
|
||||
|
||||
overview_button_ = new Gtk::Button("OVERVIEW");
|
||||
overview_button_->set_relief(Gtk::RELIEF_NONE);
|
||||
box_.pack_start(*overview_button_, false, false, 0);
|
||||
|
||||
if (!on_click_left_.empty() || !on_click_middle_.empty() || !on_click_right_.empty()) {
|
||||
overview_button_->add_events(Gdk::BUTTON_PRESS_MASK);
|
||||
overview_button_->signal_button_press_event().connect(
|
||||
[this](GdkEventButton* event) -> bool { return handleButtonClick(event, 0, true); }, false);
|
||||
}
|
||||
|
||||
IPC::getInstance().registerForIPC("monitor", this);
|
||||
dp.emit();
|
||||
}
|
||||
|
||||
Workspaces::~Workspaces() {
|
||||
IPC::getInstance().unregisterForIPC(this);
|
||||
|
||||
if (overview_button_) {
|
||||
box_.remove(*overview_button_);
|
||||
delete overview_button_;
|
||||
overview_button_ = nullptr;
|
||||
}
|
||||
|
||||
for (auto& [idx, btn] : buttons_) {
|
||||
box_.remove(btn);
|
||||
}
|
||||
buttons_.clear();
|
||||
}
|
||||
|
||||
void Workspaces::onEvent(const Json::Value& ev) { dp.emit(); }
|
||||
|
||||
void Workspaces::doUpdate() {
|
||||
Json::Value monitor = IPC::getInstance().getMonitor(bar_.output->name);
|
||||
if (monitor.isNull()) return;
|
||||
|
||||
const auto& tags = monitor["tags"];
|
||||
|
||||
bool overview_mode = false;
|
||||
if (monitor.isMember("active_tags") && monitor["active_tags"].isArray()) {
|
||||
const auto& active_tags = monitor["active_tags"];
|
||||
if (active_tags.size() == 1 && active_tags[0].asInt() == 0) {
|
||||
overview_mode = true;
|
||||
}
|
||||
}
|
||||
|
||||
for (auto& [idx, btn] : buttons_) {
|
||||
btn.hide();
|
||||
}
|
||||
|
||||
if (overview_mode) {
|
||||
overview_button_->show();
|
||||
auto style = overview_button_->get_style_context();
|
||||
style->add_class("overview");
|
||||
if (monitor["active"].asBool())
|
||||
style->add_class("current_output");
|
||||
else
|
||||
style->remove_class("current_output");
|
||||
|
||||
std::string label =
|
||||
config_["overview-label"].isString() ? config_["overview-label"].asString() : "OVERVIEW";
|
||||
|
||||
if (!config_["disable-markup"].asBool()) {
|
||||
if (auto gtk_label = dynamic_cast<Gtk::Label*>(overview_button_->get_child())) {
|
||||
gtk_label->set_markup(label);
|
||||
}
|
||||
} else {
|
||||
overview_button_->set_label(label);
|
||||
}
|
||||
} else {
|
||||
overview_button_->hide();
|
||||
|
||||
for (auto btn_it = buttons_.begin(); btn_it != buttons_.end();) {
|
||||
uint64_t id = btn_it->first;
|
||||
bool found = std::any_of(tags.begin(), tags.end(), [id](const Json::Value& tag) {
|
||||
return tag["index"].asUInt64() == id;
|
||||
});
|
||||
|
||||
if (!found) {
|
||||
box_.remove(btn_it->second);
|
||||
btn_it = buttons_.erase(btn_it);
|
||||
} else {
|
||||
++btn_it;
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto& tag : tags) {
|
||||
uint64_t idx = tag["index"].asUInt64();
|
||||
auto btn_it = buttons_.find(idx);
|
||||
Gtk::Button& button = (btn_it == buttons_.end()) ? addButton(idx) : btn_it->second;
|
||||
updateButtonState(button, tag, monitor);
|
||||
}
|
||||
|
||||
std::vector<uint64_t> indices;
|
||||
for (const auto& tag : tags) indices.push_back(tag["index"].asUInt64());
|
||||
std::sort(indices.begin(), indices.end());
|
||||
int pos = 0;
|
||||
for (uint64_t idx : indices) {
|
||||
box_.reorder_child(buttons_[idx], pos + 1);
|
||||
pos++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Workspaces::update() {
|
||||
doUpdate();
|
||||
AModule::update();
|
||||
}
|
||||
|
||||
Gtk::Button& Workspaces::addButton(uint64_t idx) {
|
||||
auto [it, _] = buttons_.emplace(idx, std::to_string(idx));
|
||||
auto& button = it->second;
|
||||
box_.pack_start(button, false, false, 0);
|
||||
button.set_relief(Gtk::RELIEF_NONE);
|
||||
|
||||
if (!on_click_left_.empty() || !on_click_middle_.empty() || !on_click_right_.empty()) {
|
||||
button.add_events(Gdk::BUTTON_PRESS_MASK);
|
||||
button.signal_button_press_event().connect(
|
||||
[this, idx](GdkEventButton* event) -> bool { return handleButtonClick(event, idx, false); },
|
||||
false);
|
||||
}
|
||||
|
||||
button.show_all();
|
||||
return button;
|
||||
}
|
||||
|
||||
void Workspaces::updateButtonState(Gtk::Button& button, const Json::Value& tag,
|
||||
const Json::Value& monitor) {
|
||||
auto style = button.get_style_context();
|
||||
bool active = tag["is_active"].asBool();
|
||||
bool urgent = tag["is_urgent"].asBool();
|
||||
bool empty = (tag["client_count"].asInt() == 0);
|
||||
|
||||
if (active)
|
||||
style->add_class("active");
|
||||
else
|
||||
style->remove_class("active");
|
||||
|
||||
if (urgent)
|
||||
style->add_class("urgent");
|
||||
else
|
||||
style->remove_class("urgent");
|
||||
|
||||
if (empty)
|
||||
style->add_class("empty");
|
||||
else
|
||||
style->remove_class("empty");
|
||||
|
||||
if (monitor["active"].asBool())
|
||||
style->add_class("current_output");
|
||||
else
|
||||
style->remove_class("current_output");
|
||||
|
||||
uint64_t idx = tag["index"].asUInt64();
|
||||
std::string name = std::to_string(idx);
|
||||
if (config_["format"].isString()) {
|
||||
name = fmt::format(fmt::runtime(config_["format"].asString()),
|
||||
fmt::arg("icon", getIcon(name, tag)), fmt::arg("value", name),
|
||||
fmt::arg("index", idx), fmt::arg("output", monitor["name"].asString()));
|
||||
}
|
||||
|
||||
if (!config_["disable-markup"].asBool()) {
|
||||
if (auto gtk_label = dynamic_cast<Gtk::Label*>(button.get_child())) {
|
||||
gtk_label->set_markup(name);
|
||||
}
|
||||
} else {
|
||||
button.set_label(name);
|
||||
}
|
||||
|
||||
if (config_["current-only"].asBool()) {
|
||||
if (active)
|
||||
button.show();
|
||||
else
|
||||
button.hide();
|
||||
} else if (config_["hide-empty"].asBool() && empty && !active) {
|
||||
button.hide();
|
||||
} else {
|
||||
button.show();
|
||||
}
|
||||
}
|
||||
|
||||
std::string Workspaces::getIcon(const std::string& value, const Json::Value& tag) {
|
||||
const auto& icons = config_["format-icons"];
|
||||
if (!icons) return value;
|
||||
|
||||
if (tag["is_urgent"].asBool() && icons["urgent"]) return icons["urgent"].asString();
|
||||
if (tag["is_active"].asBool() && icons["active"]) return icons["active"].asString();
|
||||
if (tag["client_count"].asInt() == 0 && icons["empty"]) return icons["empty"].asString();
|
||||
|
||||
std::string idx = std::to_string(tag["index"].asUInt());
|
||||
if (icons[idx]) return icons[idx].asString();
|
||||
if (icons["default"]) return icons["default"].asString();
|
||||
return value;
|
||||
}
|
||||
|
||||
bool Workspaces::handleButtonClick(GdkEventButton* event, uint64_t idx, bool isOverview) {
|
||||
std::string action;
|
||||
if (event->button == 1)
|
||||
action = on_click_left_;
|
||||
else if (event->button == 2)
|
||||
action = on_click_middle_;
|
||||
else if (event->button == 3)
|
||||
action = on_click_right_;
|
||||
|
||||
if (action.empty()) return true;
|
||||
|
||||
try {
|
||||
std::string cmd;
|
||||
if (isOverview) {
|
||||
if (action == "activate")
|
||||
cmd = "dispatch overview";
|
||||
else if (action == "toggle")
|
||||
cmd = "dispatch toggleoverview";
|
||||
} else {
|
||||
if (action == "activate")
|
||||
cmd = "dispatch view," + std::to_string(idx);
|
||||
else if (action == "toggle")
|
||||
cmd = "dispatch toggleview," + std::to_string(idx);
|
||||
}
|
||||
|
||||
if (!cmd.empty()) {
|
||||
Json::Value req;
|
||||
req["command"] = cmd;
|
||||
IPC::sendAsync(req);
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
spdlog::error("Error sending IPC command: {}", e.what());
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace waybar::modules::mango
|
||||
+106
-32
@@ -19,39 +19,37 @@ auto format_as(enum mpd_idle val) {
|
||||
|
||||
namespace waybar::modules::detail {
|
||||
|
||||
#define IDLE_RUN_NOIDLE_AND_CMD(...) \
|
||||
if (idle_connection_.connected()) { \
|
||||
idle_connection_.disconnect(); \
|
||||
auto conn = ctx_->connection().get(); \
|
||||
if (!mpd_run_noidle(conn)) { \
|
||||
if (mpd_connection_get_error(conn) != MPD_ERROR_SUCCESS) { \
|
||||
spdlog::error("mpd: Idle: failed to unregister for IDLE events"); \
|
||||
ctx_->checkErrors(conn); \
|
||||
} \
|
||||
} \
|
||||
__VA_ARGS__; \
|
||||
#define RUN_NOIDLE_AND_CMD(STATE, ...) \
|
||||
if (idle_connection_.connected()) { \
|
||||
idle_connection_.disconnect(); \
|
||||
auto conn = ctx_->connection().get(); \
|
||||
if (!mpd_run_noidle(conn)) { \
|
||||
if (mpd_connection_get_error(conn) != MPD_ERROR_SUCCESS) { \
|
||||
spdlog::error("mpd: STATE: failed to unregister for IDLE events"); \
|
||||
ctx_->checkErrors(conn); \
|
||||
} \
|
||||
} \
|
||||
__VA_ARGS__; \
|
||||
}
|
||||
|
||||
void Idle::play() {
|
||||
IDLE_RUN_NOIDLE_AND_CMD(mpd_run_play(conn));
|
||||
RUN_NOIDLE_AND_CMD(Idle, mpd_run_play(conn));
|
||||
|
||||
ctx_->setState(std::make_unique<Playing>(ctx_));
|
||||
}
|
||||
|
||||
void Idle::pause() {
|
||||
IDLE_RUN_NOIDLE_AND_CMD(mpd_run_pause(conn, true));
|
||||
RUN_NOIDLE_AND_CMD(Idle, mpd_run_pause(conn, true));
|
||||
|
||||
ctx_->setState(std::make_unique<Paused>(ctx_));
|
||||
}
|
||||
|
||||
void Idle::stop() {
|
||||
IDLE_RUN_NOIDLE_AND_CMD(mpd_run_stop(conn));
|
||||
RUN_NOIDLE_AND_CMD(Idle, mpd_run_stop(conn));
|
||||
|
||||
ctx_->setState(std::make_unique<Stopped>(ctx_));
|
||||
}
|
||||
|
||||
#undef IDLE_RUN_NOIDLE_AND_CMD
|
||||
|
||||
void Idle::update() noexcept {
|
||||
// This is intentionally blank.
|
||||
}
|
||||
@@ -97,19 +95,16 @@ bool Idle::on_io(Glib::IOCondition const&) {
|
||||
}
|
||||
|
||||
ctx_->fetchState();
|
||||
ctx_->emit();
|
||||
mpd_state state = ctx_->state();
|
||||
|
||||
if (state == MPD_STATE_STOP) {
|
||||
ctx_->emit();
|
||||
ctx_->setState(std::make_unique<Stopped>(ctx_));
|
||||
} else if (state == MPD_STATE_PLAY) {
|
||||
ctx_->emit();
|
||||
ctx_->setState(std::make_unique<Playing>(ctx_));
|
||||
} else if (state == MPD_STATE_PAUSE) {
|
||||
ctx_->emit();
|
||||
ctx_->setState(std::make_unique<Paused>(ctx_));
|
||||
} else {
|
||||
ctx_->emit();
|
||||
// self transition
|
||||
ctx_->setState(std::make_unique<Idle>(ctx_));
|
||||
}
|
||||
@@ -118,18 +113,49 @@ bool Idle::on_io(Glib::IOCondition const&) {
|
||||
}
|
||||
|
||||
void Playing::entry() noexcept {
|
||||
sigc::slot<bool> timer_slot = sigc::mem_fun(*this, &Playing::on_timer);
|
||||
timer_connection_ = Glib::signal_timeout().connect_seconds(timer_slot, 1);
|
||||
timer();
|
||||
idle();
|
||||
spdlog::debug("mpd: Playing: enabled 1 second periodic timer.");
|
||||
}
|
||||
|
||||
void Playing::exit() noexcept {
|
||||
if (idle_connection_.connected()) {
|
||||
idle_connection_.disconnect();
|
||||
spdlog::debug("mpd: Playing: unwatching FD");
|
||||
}
|
||||
|
||||
if (timer_connection_.connected()) {
|
||||
timer_connection_.disconnect();
|
||||
spdlog::debug("mpd: Playing: disabled 1 second periodic timer.");
|
||||
}
|
||||
}
|
||||
|
||||
void Playing::timer() noexcept {
|
||||
if (timer_connection_.connected()) {
|
||||
timer_connection_.disconnect();
|
||||
}
|
||||
|
||||
sigc::slot<bool> timer_slot = sigc::mem_fun(*this, &Playing::on_timer);
|
||||
timer_connection_ = Glib::signal_timeout().connect_seconds(timer_slot, 1);
|
||||
}
|
||||
|
||||
void Playing::idle() noexcept {
|
||||
auto conn = ctx_->connection().get();
|
||||
assert(conn != nullptr);
|
||||
|
||||
if (!mpd_send_idle_mask(
|
||||
conn, static_cast<mpd_idle>(MPD_IDLE_PLAYER | MPD_IDLE_OPTIONS | MPD_IDLE_QUEUE))) {
|
||||
ctx_->checkErrors(conn);
|
||||
spdlog::error("mpd: Playing: failed to register for IDLE events");
|
||||
} else if (!idle_connection_.connected()) {
|
||||
spdlog::trace("mpd: Playing: watching FD");
|
||||
sigc::slot<bool, Glib::IOCondition const&> idle_slot = sigc::mem_fun(*this, &Playing::on_io);
|
||||
idle_connection_ =
|
||||
Glib::signal_io().connect(idle_slot, mpd_connection_get_fd(conn),
|
||||
Glib::IO_IN | Glib::IO_PRI | Glib::IO_ERR | Glib::IO_HUP);
|
||||
}
|
||||
}
|
||||
|
||||
bool Playing::on_timer() {
|
||||
// Attempt to connect with MPD.
|
||||
try {
|
||||
@@ -141,9 +167,12 @@ bool Playing::on_timer() {
|
||||
return false;
|
||||
}
|
||||
|
||||
RUN_NOIDLE_AND_CMD(Playing);
|
||||
|
||||
ctx_->fetchState();
|
||||
|
||||
if (!ctx_->is_playing()) {
|
||||
ctx_->emit();
|
||||
if (ctx_->is_paused()) {
|
||||
ctx_->setState(std::make_unique<Paused>(ctx_));
|
||||
} else {
|
||||
@@ -153,6 +182,50 @@ bool Playing::on_timer() {
|
||||
}
|
||||
|
||||
ctx_->emit();
|
||||
|
||||
idle();
|
||||
} catch (std::exception const& e) {
|
||||
spdlog::warn("mpd: Playing: error: {}", e.what());
|
||||
ctx_->setState(std::make_unique<Disconnected>(ctx_));
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Playing::on_io(Glib::IOCondition const&) {
|
||||
auto conn = ctx_->connection().get();
|
||||
|
||||
// callback should do this:
|
||||
enum mpd_idle events = mpd_recv_idle(conn, /* ignore_timeout?= */ false);
|
||||
spdlog::debug("mpd: Playing: recv_idle events -> {}", events);
|
||||
|
||||
mpd_response_finish(conn);
|
||||
try {
|
||||
ctx_->checkErrors(conn);
|
||||
|
||||
ctx_->fetchState();
|
||||
|
||||
if (!ctx_->is_playing()) {
|
||||
ctx_->emit();
|
||||
if (ctx_->is_paused()) {
|
||||
ctx_->setState(std::make_unique<Paused>(ctx_));
|
||||
} else {
|
||||
ctx_->setState(std::make_unique<Stopped>(ctx_));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
ctx_->emit();
|
||||
|
||||
if (!mpd_send_idle_mask(
|
||||
conn, static_cast<mpd_idle>(MPD_IDLE_PLAYER | MPD_IDLE_OPTIONS | MPD_IDLE_QUEUE))) {
|
||||
ctx_->checkErrors(conn);
|
||||
spdlog::error("mpd: Playing: failed to register for IDLE events");
|
||||
}
|
||||
|
||||
// Defer the next timer
|
||||
timer();
|
||||
} catch (std::exception const& e) {
|
||||
spdlog::warn("mpd: Playing: error: {}", e.what());
|
||||
ctx_->setState(std::make_unique<Disconnected>(ctx_));
|
||||
@@ -163,21 +236,23 @@ bool Playing::on_timer() {
|
||||
}
|
||||
|
||||
void Playing::stop() {
|
||||
if (timer_connection_.connected()) {
|
||||
timer_connection_.disconnect();
|
||||
RUN_NOIDLE_AND_CMD(
|
||||
Playing, if (timer_connection_.connected()) {
|
||||
timer_connection_.disconnect();
|
||||
|
||||
mpd_run_stop(ctx_->connection().get());
|
||||
}
|
||||
mpd_run_stop(ctx_->connection().get());
|
||||
});
|
||||
|
||||
ctx_->setState(std::make_unique<Stopped>(ctx_));
|
||||
}
|
||||
|
||||
void Playing::pause() {
|
||||
if (timer_connection_.connected()) {
|
||||
timer_connection_.disconnect();
|
||||
RUN_NOIDLE_AND_CMD(
|
||||
Playing, if (timer_connection_.connected()) {
|
||||
timer_connection_.disconnect();
|
||||
|
||||
mpd_run_pause(ctx_->connection().get(), true);
|
||||
}
|
||||
mpd_run_pause(ctx_->connection().get(), true);
|
||||
});
|
||||
|
||||
ctx_->setState(std::make_unique<Paused>(ctx_));
|
||||
}
|
||||
@@ -211,7 +286,6 @@ bool Paused::on_timer() {
|
||||
}
|
||||
|
||||
ctx_->fetchState();
|
||||
|
||||
ctx_->emit();
|
||||
|
||||
if (ctx_->is_paused()) {
|
||||
@@ -282,7 +356,6 @@ bool Stopped::on_timer() {
|
||||
}
|
||||
|
||||
ctx_->fetchState();
|
||||
|
||||
ctx_->emit();
|
||||
|
||||
if (ctx_->is_stopped()) {
|
||||
@@ -386,4 +459,5 @@ bool Disconnected::on_timer() {
|
||||
|
||||
void Disconnected::update() noexcept { ctx_->do_update(); }
|
||||
|
||||
#undef RUN_NOIDLE_AND_CMD
|
||||
} // namespace waybar::modules::detail
|
||||
|
||||
@@ -31,6 +31,7 @@ Mpris::Mpris(const std::string& id, const Json::Value& config)
|
||||
dynamic_separator_(" - "),
|
||||
truncate_hours_(true),
|
||||
tooltip_len_limits_(false),
|
||||
prefer_album_artist_(false),
|
||||
// this character is used in Gnome so it's fine to use it here
|
||||
ellipsis_("\u2026"),
|
||||
player_("playerctld"),
|
||||
@@ -68,6 +69,9 @@ Mpris::Mpris(const std::string& id, const Json::Value& config)
|
||||
if (config_["enable-tooltip-len-limits"].isBool()) {
|
||||
tooltip_len_limits_ = config["enable-tooltip-len-limits"].asBool();
|
||||
}
|
||||
if (config_["prefer-album-artist"].isBool()) {
|
||||
prefer_album_artist_ = config["prefer-album-artist"].asBool();
|
||||
}
|
||||
}
|
||||
|
||||
if (config["artist-len"].isUInt()) {
|
||||
@@ -206,6 +210,12 @@ auto Mpris::getIconFromJson(const Json::Value& icons, const std::string& key) ->
|
||||
|
||||
auto Mpris::getArtistStr(const PlayerInfo& info, bool truncated) -> std::string {
|
||||
auto artist = info.artist.value_or(std::string());
|
||||
if (prefer_album_artist_) {
|
||||
auto album_artist = info.album_artist.value_or(std::string());
|
||||
if (!album_artist.empty()) {
|
||||
artist = album_artist;
|
||||
}
|
||||
}
|
||||
if (truncated && artist_len_ >= 0) waybar::util::utf8_truncate(artist, ellipsis_, artist_len_);
|
||||
return artist;
|
||||
}
|
||||
@@ -521,6 +531,7 @@ auto Mpris::getPlayerInfo() -> std::optional<PlayerInfo> {
|
||||
.status_string = player_status,
|
||||
.artist = std::nullopt,
|
||||
.album = std::nullopt,
|
||||
.album_artist = std::nullopt,
|
||||
.title = std::nullopt,
|
||||
.length = std::nullopt,
|
||||
};
|
||||
@@ -532,6 +543,13 @@ auto Mpris::getPlayerInfo() -> std::optional<PlayerInfo> {
|
||||
}
|
||||
if (error) goto errorexit;
|
||||
|
||||
if (auto* album_artist_ =
|
||||
playerctl_player_print_metadata_prop(player, "xesam:albumArtist", &error)) {
|
||||
spdlog::debug("mpris[{}]: albumArtist = {}", info.name, album_artist_);
|
||||
info.album_artist = album_artist_;
|
||||
g_free(album_artist_);
|
||||
}
|
||||
|
||||
if (auto* album_ = playerctl_player_get_album(last_active_player_, &error)) {
|
||||
spdlog::debug("mpris[{}]: album = {}", info.name, album_);
|
||||
info.album = album_;
|
||||
|
||||
@@ -368,6 +368,10 @@ auto waybar::modules::Network::update() -> void {
|
||||
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("bandwidthDownBytesCompact",
|
||||
pow_format(bandwidth_down / elapsed_seconds, "B", false, 2)),
|
||||
fmt::arg("bandwidthUpBytesCompact",
|
||||
pow_format(bandwidth_up / elapsed_seconds, "B", false, 2)),
|
||||
fmt::arg("bandwidthTotalBytes",
|
||||
pow_format((bandwidth_up + bandwidth_down) / elapsed_seconds, "B/s")));
|
||||
if (text.compare(label_.get_label()) != 0) {
|
||||
@@ -401,6 +405,10 @@ auto waybar::modules::Network::update() -> void {
|
||||
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("bandwidthDownBytesCompact",
|
||||
pow_format(bandwidth_down / elapsed_seconds, "B", false, 2)),
|
||||
fmt::arg("bandwidthUpBytesCompact",
|
||||
pow_format(bandwidth_up / elapsed_seconds, "B", false, 2)),
|
||||
fmt::arg("bandwidthTotalBytes",
|
||||
pow_format((bandwidth_up + bandwidth_down) / elapsed_seconds, "B/s")));
|
||||
if (label_.get_tooltip_text() != tooltip_text) {
|
||||
|
||||
@@ -196,6 +196,18 @@ void IPC::parseIPC(const std::string& line) {
|
||||
for (auto& win : windows_) {
|
||||
win["is_focused"] = focused && win["id"].asUInt64() == id;
|
||||
}
|
||||
} else if (const auto &payload = ev["WindowLayoutsChanged"]) {
|
||||
const auto &values = payload["changes"];
|
||||
for (const auto &changed : values) {
|
||||
const auto id = changed[0].asUInt64();
|
||||
const auto &change = changed[1];
|
||||
for (auto &win : windows_) {
|
||||
if (win["id"].asUInt64() == id) {
|
||||
win["layout"] = change;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ Window::Window(const std::string& id, const Bar& bar, const Json::Value& config)
|
||||
gIPC->registerForIPC("WindowOpenedOrChanged", this);
|
||||
gIPC->registerForIPC("WindowClosed", this);
|
||||
gIPC->registerForIPC("WindowFocusChanged", this);
|
||||
gIPC->registerForIPC("WindowLayoutsChanged", this);
|
||||
|
||||
dp.emit();
|
||||
}
|
||||
@@ -54,15 +55,25 @@ void Window::doUpdate() {
|
||||
if (it != windows.cend()) {
|
||||
const auto& window = *it;
|
||||
|
||||
auto max_col = -1;
|
||||
for (const auto &win : windows) {
|
||||
if (win["workspace_id"].asUInt64() != window["workspace_id"].asUInt64()) {
|
||||
continue;
|
||||
}
|
||||
const auto col = win["layout"]["pos_in_scrolling_layout"][0].asInt64();
|
||||
if (col > max_col) max_col = col;
|
||||
}
|
||||
const auto title = window["title"].asString();
|
||||
const auto appId = window["app_id"].asString();
|
||||
const auto col = window["layout"]["pos_in_scrolling_layout"][0].asInt64();
|
||||
const auto sanitizedTitle = waybar::util::sanitize_string(title);
|
||||
const auto sanitizedAppId = waybar::util::sanitize_string(appId);
|
||||
|
||||
label_.show();
|
||||
label_.set_markup(waybar::util::rewriteString(
|
||||
fmt::format(fmt::runtime(format_), fmt::arg("title", sanitizedTitle),
|
||||
fmt::arg("app_id", sanitizedAppId)),
|
||||
fmt::arg("app_id", sanitizedAppId), fmt::arg("col", col),
|
||||
fmt::arg("max_col", max_col)),
|
||||
config_["rewrite"]));
|
||||
|
||||
updateAppIconName(appId, "");
|
||||
@@ -82,7 +93,12 @@ void Window::doUpdate() {
|
||||
oldAppId_ = appId;
|
||||
}
|
||||
} else {
|
||||
label_.hide();
|
||||
label_.show();
|
||||
label_.set_markup(waybar::util::rewriteString(
|
||||
fmt::format(fmt::runtime(format_), fmt::arg("title", ""),
|
||||
fmt::arg("app_id", "")),
|
||||
config_["rewrite"]));
|
||||
|
||||
updateAppIconName("", "");
|
||||
setClass("solo", false);
|
||||
if (!oldAppId_.empty()) setClass(oldAppId_, false);
|
||||
|
||||
@@ -4,10 +4,34 @@
|
||||
#include <gtkmm/label.h>
|
||||
#include <spdlog/spdlog.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
|
||||
namespace waybar::modules::niri {
|
||||
|
||||
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) {
|
||||
const auto config_sort_by_number = config_["sort-by-number"];
|
||||
if (config_sort_by_number.isBool()) {
|
||||
spdlog::warn("[niri/workspaces]: Prefer sort-by-id instead of sort-by-number");
|
||||
sort_by_id_ = config_sort_by_number.asBool();
|
||||
}
|
||||
|
||||
const auto config_sort_by_id = config_["sort-by-id"];
|
||||
if (config_sort_by_id.isBool()) {
|
||||
sort_by_id_ = config_sort_by_id.asBool();
|
||||
}
|
||||
|
||||
const auto config_sort_by_name = config_["sort-by-name"];
|
||||
if (config_sort_by_name.isBool()) {
|
||||
sort_by_name_ = config_sort_by_name.asBool();
|
||||
}
|
||||
|
||||
const auto config_sort_by_coordinates = config_["sort-by-coordinates"];
|
||||
if (config_sort_by_coordinates.isBool()) {
|
||||
sort_by_coordinates_ = config_sort_by_coordinates.asBool();
|
||||
}
|
||||
|
||||
box_.set_name("workspaces");
|
||||
if (!id.empty()) {
|
||||
box_.get_style_context()->add_class(id);
|
||||
@@ -41,6 +65,8 @@ void Workspaces::doUpdate() {
|
||||
return ws["output"].asString() == bar_.output->name;
|
||||
});
|
||||
|
||||
sortWorkspaces(my_workspaces);
|
||||
|
||||
// Remove buttons for removed workspaces.
|
||||
for (auto it = buttons_.begin(); it != buttons_.end();) {
|
||||
auto ws = std::find_if(my_workspaces.begin(), my_workspaces.end(),
|
||||
@@ -118,9 +144,9 @@ void Workspaces::doUpdate() {
|
||||
button.hide();
|
||||
} else if (config_["hide-empty"].asBool()) {
|
||||
if (ws["active_window_id"].isNull() && !ws["is_focused"].asBool())
|
||||
button.hide();
|
||||
button.hide();
|
||||
else
|
||||
button.show();
|
||||
button.show();
|
||||
} else {
|
||||
button.show();
|
||||
}
|
||||
@@ -130,8 +156,7 @@ void Workspaces::doUpdate() {
|
||||
for (auto it = my_workspaces.cbegin(); it != my_workspaces.cend(); ++it) {
|
||||
const auto& ws = *it;
|
||||
|
||||
auto pos = ws["idx"].asUInt() - 1;
|
||||
if (alloutputs) pos = it - my_workspaces.cbegin();
|
||||
const auto pos = static_cast<int>(std::distance(my_workspaces.cbegin(), it));
|
||||
|
||||
auto& button = buttons_[ws["id"].asUInt64()];
|
||||
box_.reorder_child(button, pos);
|
||||
@@ -200,4 +225,59 @@ std::string Workspaces::getIcon(const std::string& value, const Json::Value& ws)
|
||||
return value;
|
||||
}
|
||||
|
||||
void Workspaces::sortWorkspaces(std::vector<Json::Value>& workspaces) const {
|
||||
auto get_name = [](const Json::Value& ws) -> std::string {
|
||||
if (ws["name"]) return ws["name"].asString();
|
||||
return std::to_string(ws["idx"].asUInt());
|
||||
};
|
||||
|
||||
auto is_numeric = [](const std::string& value) {
|
||||
return !value.empty() &&
|
||||
std::all_of(value.begin(), value.end(), [](unsigned char c) { return std::isdigit(c); });
|
||||
};
|
||||
|
||||
const bool names_are_numeric =
|
||||
std::all_of(workspaces.begin(), workspaces.end(),
|
||||
[&](const auto& ws) { return is_numeric(get_name(ws)); });
|
||||
|
||||
auto compare_numeric_strings = [](const std::string& a, const std::string& b) {
|
||||
if (a.size() != b.size()) return a.size() < b.size();
|
||||
return a < b;
|
||||
};
|
||||
|
||||
std::sort(workspaces.begin(), workspaces.end(), [&](const auto& a, const auto& b) {
|
||||
if (sort_by_id_) {
|
||||
return a["id"].asUInt64() < b["id"].asUInt64();
|
||||
}
|
||||
|
||||
if (sort_by_name_) {
|
||||
const auto a_name = get_name(a);
|
||||
const auto b_name = get_name(b);
|
||||
if (a_name == b_name) return a["id"].asUInt64() < b["id"].asUInt64();
|
||||
if (names_are_numeric) return compare_numeric_strings(a_name, b_name);
|
||||
return a_name < b_name;
|
||||
}
|
||||
|
||||
if (sort_by_coordinates_) {
|
||||
const auto& a_output = a["output"].asString();
|
||||
const auto& b_output = b["output"].asString();
|
||||
if (a_output == b_output) {
|
||||
const auto a_idx = a["idx"].asUInt();
|
||||
const auto b_idx = b["idx"].asUInt();
|
||||
if (a_idx == b_idx) return a["id"].asUInt64() < b["id"].asUInt64();
|
||||
return a_idx < b_idx;
|
||||
}
|
||||
return a_output < b_output;
|
||||
}
|
||||
|
||||
// Default to sorting by workspace index on each output.
|
||||
const auto& a_output = a["output"].asString();
|
||||
const auto& b_output = b["output"].asString();
|
||||
const auto a_idx = a["idx"].asUInt();
|
||||
const auto b_idx = b["idx"].asUInt();
|
||||
if (a_output == b_output) return a_idx < b_idx;
|
||||
return a_output < b_output;
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace waybar::modules::niri
|
||||
|
||||
@@ -12,7 +12,8 @@ PowerProfilesDaemon::PowerProfilesDaemon(const std::string& id, const Json::Valu
|
||||
if (config_["tooltip-format"].isString()) {
|
||||
tooltipFormat_ = config_["tooltip-format"].asString();
|
||||
} else {
|
||||
tooltipFormat_ = "Power profile: {profile}\nDriver: {driver}";
|
||||
tooltipFormat_ =
|
||||
"Power profile: {profile}\nCPU driver: {cpu_driver}\nPlatform driver: {platform_driver}";
|
||||
}
|
||||
// Fasten your seatbelt, we're up for quite a ride. The rest of the
|
||||
// init is performed asynchronously. There's 2 callbacks involved.
|
||||
@@ -95,15 +96,51 @@ void PowerProfilesDaemon::populateInitState() {
|
||||
powerProfilesProxy_->get_cached_property(profilesVariant, "Profiles");
|
||||
for (auto& variantDict : profilesVariant.get()) {
|
||||
Glib::ustring name;
|
||||
// Legacy single `Driver` property, still exposed by older
|
||||
// power-profiles-daemon versions.
|
||||
Glib::ustring driver;
|
||||
Glib::ustring cpuDriver;
|
||||
Glib::ustring platformDriver;
|
||||
if (auto p = variantDict.find("Profile"); p != variantDict.end()) {
|
||||
name = p->second.get();
|
||||
}
|
||||
if (auto d = variantDict.find("Driver"); d != variantDict.end()) {
|
||||
driver = d->second.get();
|
||||
}
|
||||
if (auto cd = variantDict.find("CpuDriver"); cd != variantDict.end()) {
|
||||
cpuDriver = cd->second.get();
|
||||
}
|
||||
if (auto pd = variantDict.find("PlatformDriver"); pd != variantDict.end()) {
|
||||
platformDriver = pd->second.get();
|
||||
}
|
||||
|
||||
// Recent power-profiles-daemon versions split the single `Driver`
|
||||
// property into `CpuDriver` and `PlatformDriver`. When talking to an
|
||||
// older daemon that only exposes `Driver`, fall back to it so the new
|
||||
// {cpu_driver}/{platform_driver} placeholders still resolve.
|
||||
if (cpuDriver.empty()) {
|
||||
cpuDriver = driver;
|
||||
}
|
||||
if (platformDriver.empty()) {
|
||||
platformDriver = driver;
|
||||
}
|
||||
// Conversely, keep the legacy {driver} placeholder working against a
|
||||
// recent daemon that no longer exposes `Driver` by deriving it from
|
||||
// the CPU driver.
|
||||
if (driver.empty()) {
|
||||
driver = cpuDriver;
|
||||
}
|
||||
|
||||
if (driver.empty()) {
|
||||
driver = "Unavailable";
|
||||
cpuDriver = "Unavailable";
|
||||
platformDriver = "Unavailable";
|
||||
spdlog::warn("Cannot find power profiles daemon driver.");
|
||||
}
|
||||
|
||||
if (!name.empty()) {
|
||||
availableProfiles_.emplace_back(std::move(name), std::move(driver));
|
||||
availableProfiles_.emplace_back(std::move(name), std::move(driver), std::move(cpuDriver),
|
||||
std::move(platformDriver));
|
||||
} else {
|
||||
spdlog::error(
|
||||
"Power profiles daemon: power-profiles-daemon sent us an empty power profile name. "
|
||||
@@ -153,7 +190,10 @@ auto PowerProfilesDaemon::update() -> void {
|
||||
// Set label
|
||||
fmt::dynamic_format_arg_store<fmt::format_context> store;
|
||||
store.push_back(fmt::arg("profile", profile.name));
|
||||
// Legacy placeholder, kept for backward compatibility with existing configs.
|
||||
store.push_back(fmt::arg("driver", profile.driver));
|
||||
store.push_back(fmt::arg("cpu_driver", profile.cpuDriver));
|
||||
store.push_back(fmt::arg("platform_driver", profile.platformDriver));
|
||||
store.push_back(fmt::arg("icon", getIcon(0, profile.name)));
|
||||
label_.set_markup(fmt::vformat(format_, store));
|
||||
if (tooltipEnabled()) {
|
||||
|
||||
@@ -7,6 +7,10 @@ waybar::modules::Pulseaudio::Pulseaudio(const std::string& id, const Json::Value
|
||||
|
||||
backend = util::AudioBackend::getInstance([this] { this->dp.emit(); });
|
||||
backend->setIgnoredSinks(config_["ignored-sinks"]);
|
||||
|
||||
if (config_["target"].isString() && config_["target"].asString() == "source") {
|
||||
target = util::PulseaudioTarget::Source;
|
||||
}
|
||||
}
|
||||
|
||||
bool waybar::modules::Pulseaudio::handleScroll(GdkEventScroll* e) {
|
||||
@@ -33,7 +37,7 @@ bool waybar::modules::Pulseaudio::handleScroll(GdkEventScroll* e) {
|
||||
? util::ChangeType::Increase
|
||||
: util::ChangeType::Decrease;
|
||||
|
||||
backend->changeVolume(change_type, step, max_volume);
|
||||
backend->changeVolume(change_type, step, max_volume, target);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -53,7 +53,7 @@ void PulseaudioSlider::onValueChanged() {
|
||||
if (unmute_on_volume_change) {
|
||||
backend->unmute(target);
|
||||
}
|
||||
backend->changeVolume(slider_value, min_, max_);
|
||||
backend->changeVolume(slider_value, min_, max_, target);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -33,6 +33,33 @@ static const zriver_output_status_v1_listener output_status_listener_impl{
|
||||
.urgent_tags = listen_urgent_tags,
|
||||
};
|
||||
|
||||
static void listen_focused_output(void* data, struct zriver_seat_status_v1* zriver_seat_status_v1,
|
||||
struct wl_output* output) {
|
||||
static_cast<Tags *>(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<Tags *>(data)->handle_unfocused_output(output);
|
||||
}
|
||||
|
||||
static void listen_focused_view(void* data, struct zriver_seat_status_v1* zriver_seat_status_v1,
|
||||
const char* title) {
|
||||
// This module doesn't care
|
||||
}
|
||||
|
||||
static void listen_mode(void* data, struct zriver_seat_status_v1* zriver_seat_status_v1,
|
||||
const char* mode) {
|
||||
// This module doesn't care
|
||||
}
|
||||
|
||||
static const zriver_seat_status_v1_listener seat_status_listener_impl{
|
||||
.focused_output = listen_focused_output,
|
||||
.unfocused_output = listen_unfocused_output,
|
||||
.focused_view = listen_focused_view,
|
||||
.mode = listen_mode,
|
||||
};
|
||||
|
||||
static void listen_command_success(void* data,
|
||||
struct zriver_command_callback_v1* zriver_command_callback_v1,
|
||||
const char* output) {
|
||||
@@ -87,8 +114,10 @@ Tags::Tags(const std::string& id, const waybar::Bar& bar, const Json::Value& con
|
||||
control_{nullptr},
|
||||
seat_{nullptr},
|
||||
bar_(bar),
|
||||
output_{nullptr},
|
||||
box_{bar.orientation, 0},
|
||||
output_status_{nullptr} {
|
||||
output_status_{nullptr},
|
||||
seat_status_{nullptr} {
|
||||
struct wl_display* display = Client::inst()->wl_display;
|
||||
struct wl_registry* registry = wl_display_get_registry(display);
|
||||
wl_registry_add_listener(registry, ®istry_listener_impl, this);
|
||||
@@ -109,6 +138,11 @@ Tags::Tags(const std::string& id, const waybar::Bar& bar, const Json::Value& con
|
||||
return;
|
||||
}
|
||||
|
||||
// Store the output this module belongs to; the river_output_status and
|
||||
// river_seat_status objects (and their listeners) are created lazily in
|
||||
// handle_show() to avoid leaking objects without listeners here.
|
||||
output_ = gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj());
|
||||
|
||||
box_.set_name("tags");
|
||||
if (!id.empty()) {
|
||||
box_.get_style_context()->add_class(id);
|
||||
@@ -160,6 +194,10 @@ Tags::~Tags() {
|
||||
zriver_output_status_v1_destroy(output_status_);
|
||||
}
|
||||
|
||||
if (seat_status_) {
|
||||
zriver_seat_status_v1_destroy(seat_status_);
|
||||
}
|
||||
|
||||
if (control_) {
|
||||
zriver_control_v1_destroy(control_);
|
||||
}
|
||||
@@ -171,10 +209,12 @@ Tags::~Tags() {
|
||||
|
||||
void Tags::handle_show() {
|
||||
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);
|
||||
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);
|
||||
|
||||
seat_status_ = zriver_status_manager_v1_get_river_seat_status(status_manager_, seat_);
|
||||
zriver_seat_status_v1_add_listener(seat_status_, &seat_status_listener_impl, this);
|
||||
|
||||
zriver_status_manager_v1_destroy(status_manager_);
|
||||
status_manager_ = nullptr;
|
||||
}
|
||||
@@ -266,4 +306,20 @@ void Tags::handle_urgent_tags(uint32_t tags) {
|
||||
}
|
||||
}
|
||||
|
||||
void Tags::handle_focused_output(struct wl_output *output) {
|
||||
if (output_ == output) {
|
||||
for (size_t i = 0; i < buttons_.size(); ++i) {
|
||||
buttons_[i].get_style_context()->add_class("output");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Tags::handle_unfocused_output(struct wl_output *output) {
|
||||
if (output_ == output) {
|
||||
for (size_t i = 0; i < buttons_.size(); ++i) {
|
||||
buttons_[i].get_style_context()->remove_class("output");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace waybar::modules::river */
|
||||
|
||||
@@ -10,6 +10,7 @@ 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::vector<std::string>& ignore_list,
|
||||
const std::function<void(std::unique_ptr<Item>&)>& on_add,
|
||||
const std::function<void(std::unique_ptr<Item>&)>& on_remove,
|
||||
const std::function<void()>& on_update)
|
||||
@@ -20,6 +21,7 @@ Host::Host(const std::size_t id, const Json::Value& config, const Bar& bar,
|
||||
sigc::mem_fun(*this, &Host::busAcquired))),
|
||||
config_(config),
|
||||
bar_(bar),
|
||||
ignore_list_(ignore_list),
|
||||
on_add_(on_add),
|
||||
on_remove_(on_remove),
|
||||
on_update_(on_update) {}
|
||||
@@ -39,6 +41,42 @@ Host::~Host() {
|
||||
g_clear_object(&watcher_);
|
||||
}
|
||||
|
||||
void Host::checkIgnoreList(const std::vector<std::string>& ignore_list,
|
||||
const std::function<void(std::unique_ptr<Item>&)>& on_remove) {
|
||||
spdlog::debug("Host::checkIgnoreList - checking {} items against {} patterns", items_.size(),
|
||||
ignore_list.size());
|
||||
|
||||
for (auto it = items_.begin(); it != items_.end();) {
|
||||
auto& item = *it;
|
||||
spdlog::debug(" Checking item: bus_name='{}', category='{}', icon_name='{}', title='{}'",
|
||||
item->bus_name, item->category, item->icon_name, item->title);
|
||||
|
||||
bool should_remove = false;
|
||||
|
||||
for (const auto& ignored : ignore_list) {
|
||||
if (item->bus_name.find(ignored) != std::string::npos ||
|
||||
item->category.find(ignored) != std::string::npos ||
|
||||
item->icon_name.find(ignored) != std::string::npos ||
|
||||
item->id.find(ignored) != std::string::npos ||
|
||||
item->title.find(ignored) != std::string::npos) {
|
||||
spdlog::info(
|
||||
"Host: Ignoring item bus_name='{}', category='{}', icon_name='{}', title='{}' - "
|
||||
"matched pattern '{}'",
|
||||
item->bus_name, item->category, item->icon_name, item->title, ignored);
|
||||
on_remove(item);
|
||||
should_remove = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (should_remove) {
|
||||
it = items_.erase(it);
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Host::busAcquired(const Glib::RefPtr<Gio::DBus::Connection>& conn, Glib::ustring name) {
|
||||
watcher_id_ = Gio::DBus::watch_name(conn, "org.kde.StatusNotifierWatcher",
|
||||
sigc::mem_fun(*this, &Host::nameAppeared),
|
||||
@@ -82,7 +120,8 @@ void Host::proxyReady(GObject* src, GAsyncResult* res, gpointer data) {
|
||||
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_);
|
||||
spdlog::warn("Host: giving up on watcher proxy creation after {} retries",
|
||||
host->retry_count_);
|
||||
return;
|
||||
}
|
||||
host->retry_count_ += 1;
|
||||
@@ -127,7 +166,9 @@ void Host::registerHost(GObject* src, GAsyncResult* res, gpointer data) {
|
||||
g_signal_connect(host->watcher_, "item-unregistered", G_CALLBACK(&Host::itemUnregistered), data);
|
||||
auto items = sn_watcher_dup_registered_items(host->watcher_);
|
||||
if (items != nullptr) {
|
||||
spdlog::info("Host: Found {} pre-registered SNI items", g_strv_length(items));
|
||||
for (uint32_t i = 0; items[i] != nullptr; i += 1) {
|
||||
spdlog::info("Host: Processing pre-registered item: {}", items[i]);
|
||||
host->addRegisteredItem(items[i]);
|
||||
}
|
||||
}
|
||||
@@ -136,7 +177,10 @@ void Host::registerHost(GObject* src, GAsyncResult* res, gpointer data) {
|
||||
|
||||
void Host::itemRegistered(SnWatcher* watcher, const gchar* service, gpointer data) {
|
||||
auto host = static_cast<SNI::Host*>(data);
|
||||
spdlog::info("Host::itemRegistered called with service: {}", service);
|
||||
host->addRegisteredItem(service);
|
||||
// host->checkIgnoreList(host->ignore_list_, std::bind(&Host::itemUnregistered, host,
|
||||
// std::placeholders::_1, std::placeholders::_2, data));
|
||||
}
|
||||
|
||||
void Host::itemUnregistered(SnWatcher* watcher, const gchar* service, gpointer data) {
|
||||
@@ -197,17 +241,25 @@ std::tuple<std::string, std::string> Host::getBusNameAndObjectPath(const std::st
|
||||
}
|
||||
|
||||
void Host::addRegisteredItem(const std::string& service) {
|
||||
// Check service string directly before parsing
|
||||
for (const auto& ignored : ignore_list_) {
|
||||
if (service.find(ignored) != std::string::npos) {
|
||||
spdlog::info("Host: Ignoring service '{}' - matched pattern '{}'", service, ignored);
|
||||
return;
|
||||
}
|
||||
}
|
||||
std::string bus_name, object_path;
|
||||
std::tie(bus_name, object_path) = getBusNameAndObjectPath(service);
|
||||
spdlog::debug("SNI item registered: bus_name={}, object_path={}, full_service={}", bus_name,
|
||||
object_path, 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()) {
|
||||
spdlog::debug("Adding SNI item: {}", bus_name);
|
||||
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_));
|
||||
bus_name, object_path, config_, bar_, [this](Item& item) { itemReady(item); },
|
||||
[this](Item& item) { itemInvalidated(item); }, on_update_));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,11 +8,29 @@
|
||||
|
||||
namespace waybar::modules::SNI {
|
||||
|
||||
std::vector<std::string> Tray::parseIgnoreList(const Json::Value& config) {
|
||||
std::vector<std::string> ignore_list;
|
||||
if (config["ignore-list"].isArray()) {
|
||||
spdlog::info("Tray: Found ignore-list with {} items", config["ignore-list"].size());
|
||||
for (const auto& item : config["ignore-list"]) {
|
||||
if (item.isString()) {
|
||||
ignore_list.push_back(item.asString());
|
||||
spdlog::info("Tray: Adding to ignore list: {}", item.asString());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
spdlog::info("Tray: No ignore-list configured");
|
||||
}
|
||||
return ignore_list;
|
||||
}
|
||||
|
||||
Tray::Tray(const std::string& id, const Bar& bar, const Json::Value& config)
|
||||
: AModule(config, "tray", id),
|
||||
box_(bar.orientation, 0),
|
||||
watcher_(SNI::Watcher::getInstance()),
|
||||
host_(nb_hosts_, config, bar, std::bind(&Tray::onAdd, this, std::placeholders::_1),
|
||||
ignore_list_(parseIgnoreList(config)),
|
||||
host_(nb_hosts_, config, bar, ignore_list_,
|
||||
std::bind(&Tray::onAdd, this, std::placeholders::_1),
|
||||
std::bind(&Tray::onRemove, this, std::placeholders::_1),
|
||||
std::bind(&Tray::queueUpdate, this)) {
|
||||
box_.set_name("tray");
|
||||
@@ -31,14 +49,26 @@ Tray::Tray(const std::string& id, const Bar& bar, const Json::Value& config)
|
||||
dp.emit();
|
||||
}
|
||||
|
||||
void Tray::checkIgnoreList(std::unique_ptr<Item>* item_ptr) {
|
||||
// Delegate to Host's checkIgnoreList method
|
||||
host_.checkIgnoreList(ignore_list_, std::bind(&Tray::onRemove, this, std::placeholders::_1));
|
||||
}
|
||||
|
||||
void Tray::queueUpdate() { dp.emit(); }
|
||||
|
||||
void Tray::onAdd(std::unique_ptr<Item>& item) {
|
||||
spdlog::info("Tray::onAdd - item bus_name='{}', category='{}', icon_name='{}', title='{}'",
|
||||
item->bus_name, item->category, item->icon_name, item->title);
|
||||
|
||||
if (config_["reverse-direction"].isBool() && config_["reverse-direction"].asBool()) {
|
||||
box_.pack_end(item->event_box);
|
||||
} else {
|
||||
box_.pack_start(item->event_box);
|
||||
}
|
||||
|
||||
spdlog::debug("Tray::onAdd deferred check - checking ignore list");
|
||||
host_.checkIgnoreList(ignore_list_, std::bind(&Tray::onRemove, this, std::placeholders::_1));
|
||||
|
||||
item->event_box.signal_show().connect([this] { dp.emit(); });
|
||||
item->event_box.signal_hide().connect([this] { dp.emit(); });
|
||||
dp.emit();
|
||||
@@ -50,6 +80,12 @@ void Tray::onRemove(std::unique_ptr<Item>& item) {
|
||||
}
|
||||
|
||||
auto Tray::update() -> void {
|
||||
// Check if any items should be ignored now that properties have loaded
|
||||
if (!ignore_list_.empty()) {
|
||||
spdlog::debug("Tray::update() - checking ignore list");
|
||||
host_.checkIgnoreList(ignore_list_, std::bind(&Tray::onRemove, this, std::placeholders::_1));
|
||||
}
|
||||
|
||||
std::vector<Gtk::Widget*> children = box_.get_children();
|
||||
event_box_.set_visible(std::any_of(children.begin(), children.end(),
|
||||
[](Gtk::Widget* child) { return child->get_visible(); }));
|
||||
|
||||
@@ -69,6 +69,7 @@ Workspaces::Workspaces(const std::string& id, const Bar& bar, const Json::Value&
|
||||
m_windowRewriteRules = waybar::util::RegexCollection(
|
||||
windowRewrite, std::move(windowRewriteDefault), windowRewritePriorityFunction);
|
||||
}
|
||||
populateIgnoreWorkspacesConfig(config);
|
||||
ipc_.subscribe(R"(["workspace"])");
|
||||
ipc_.subscribe(R"(["window"])");
|
||||
ipc_.signal_event.connect(sigc::mem_fun(*this, &Workspaces::onEvent));
|
||||
@@ -97,6 +98,36 @@ void Workspaces::onEvent(const struct Ipc::ipc_response& res) {
|
||||
}
|
||||
}
|
||||
|
||||
auto Workspaces::populateIgnoreWorkspacesConfig(const Json::Value& config) -> void {
|
||||
auto ignoreWorkspaces = config["ignore-workspaces"];
|
||||
if (ignoreWorkspaces.isArray()) {
|
||||
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) {
|
||||
spdlog::error("Invalid rule {}: {}", ruleString, e.what());
|
||||
}
|
||||
} else {
|
||||
spdlog::error("Not a string: '{}'", workspaceRegex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool Workspaces::isWorkspaceIgnored(std::string const& name) {
|
||||
for (auto& rule : m_ignoreWorkspaces) {
|
||||
if (std::regex_match(name, rule)) {
|
||||
return true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void Workspaces::onCmd(const struct Ipc::ipc_response& res) {
|
||||
if (res.type == IPC_GET_TREE) {
|
||||
try {
|
||||
@@ -118,8 +149,9 @@ void Workspaces::onCmd(const struct Ipc::ipc_response& res) {
|
||||
});
|
||||
|
||||
for (auto& output : outputs) {
|
||||
std::copy(output["nodes"].begin(), output["nodes"].end(),
|
||||
std::back_inserter(workspaces_));
|
||||
std::copy_if(
|
||||
output["nodes"].begin(), output["nodes"].end(), std::back_inserter(workspaces_),
|
||||
[&](const auto& node) { return !(isWorkspaceIgnored(node["name"].asString())); });
|
||||
std::copy(output["floating_nodes"].begin(), output["floating_nodes"].end(),
|
||||
std::back_inserter(workspaces_));
|
||||
}
|
||||
@@ -143,7 +175,8 @@ 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) {
|
||||
if (output.asString() == bar_.output->name) {
|
||||
auto output_name = output.asString();
|
||||
if (output_name == bar_.output->name || output_name == bar_.output->identifier) {
|
||||
Json::Value v;
|
||||
v["name"] = p_w_name;
|
||||
v["target_output"] = bar_.output->name;
|
||||
@@ -324,6 +357,18 @@ auto Workspaces::update() -> void {
|
||||
button.get_style_context()->remove_class("empty");
|
||||
}
|
||||
if ((*it)["output"].isString()) {
|
||||
// Simply attempt to remove all output classes every time to reset output classes. This works
|
||||
// even if a class has not been previously added to the style context.
|
||||
for (const auto &oclass : config_["output-classes"]) {
|
||||
button.get_style_context()->remove_class(oclass.asString());
|
||||
}
|
||||
// If output-classes contains a class for output associated with current workspace button, add
|
||||
// the class to its style context.
|
||||
std::string output_name = (*it)["output"].asString();
|
||||
if (config_["output-classes"].isMember(output_name) &&
|
||||
config_["output-classes"][output_name].isString()) {
|
||||
button.get_style_context()->add_class(config_["output-classes"][output_name].asString());
|
||||
}
|
||||
if (((*it)["output"].asString()) == bar_.output->name) {
|
||||
button.get_style_context()->add_class("current_output");
|
||||
} else {
|
||||
@@ -332,29 +377,44 @@ auto Workspaces::update() -> void {
|
||||
} else {
|
||||
button.get_style_context()->remove_class("current_output");
|
||||
}
|
||||
std::string output;
|
||||
std::string full_name;
|
||||
if (!config_["disable-markup"].asBool()) {
|
||||
output = g_markup_escape_text((*it)["name"].asString().c_str(), -1);
|
||||
full_name = g_markup_escape_text((*it)["name"].asString().c_str(), -1);
|
||||
} else {
|
||||
output = (*it)["name"].asString();
|
||||
full_name = (*it)["name"].asString();
|
||||
}
|
||||
|
||||
std::string windows = "";
|
||||
if (config_["window-rewrite"].isObject()) {
|
||||
updateWindows((*it), windows);
|
||||
}
|
||||
|
||||
auto index = (*it)["num"].asInt();
|
||||
|
||||
if (config_["format"].isString()) {
|
||||
auto format = config_["format"].asString();
|
||||
output = fmt::format(
|
||||
fmt::runtime(format), fmt::arg("icon", getIcon(output, *it)), fmt::arg("value", output),
|
||||
fmt::arg("name", trimWorkspaceName(output)), fmt::arg("index", (*it)["num"].asString()),
|
||||
fmt::arg("windows",
|
||||
windows.substr(0, windows.length() - m_formatWindowSeparator.length())),
|
||||
fmt::arg("output", (*it)["output"].asString()));
|
||||
std::string format;
|
||||
if (config_["format-for-negative-index"].isString() && index < 0) {
|
||||
format = config_["format-for-negative-index"].asString();
|
||||
} else {
|
||||
format = config_["format"].asString();
|
||||
}
|
||||
|
||||
auto name = trimWorkspaceName(full_name);
|
||||
auto output = (*it)["output"].asString();
|
||||
auto icon = getIcon(full_name, *it);
|
||||
auto separated_windows =
|
||||
windows.substr(0, windows.length() - m_formatWindowSeparator.length());
|
||||
|
||||
full_name =
|
||||
fmt::format(fmt::runtime(format), fmt::arg("index", index), fmt::arg("name", name),
|
||||
fmt::arg("value", full_name), fmt::arg("output", output),
|
||||
fmt::arg("icon", icon), fmt::arg("windows", separated_windows));
|
||||
}
|
||||
|
||||
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(full_name);
|
||||
} else {
|
||||
button.set_label(output);
|
||||
button.set_label(full_name);
|
||||
}
|
||||
onButtonReady(*it, button);
|
||||
}
|
||||
|
||||
@@ -297,7 +297,7 @@ auto SystemdFailedUnits::update() -> void {
|
||||
fmt::arg("user_state", user_state_), fmt::arg("overall_state", overall_state_),
|
||||
fmt::arg("failed_units_list", failed_list)));
|
||||
} else {
|
||||
label_.set_tooltip_text("");
|
||||
label_.set_tooltip_markup("");
|
||||
}
|
||||
}
|
||||
ALabel::update();
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#include "modules/temperature.hpp"
|
||||
|
||||
#include <filesystem>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
#if defined(__FreeBSD__)
|
||||
@@ -20,6 +22,33 @@ waybar::modules::Temperature::Temperature(const std::string& id, const Json::Val
|
||||
if (check_set_path(item.asString())) break;
|
||||
};
|
||||
|
||||
if (config_["hwmon-by-name"].isString() && config_["input-filename"].isString()) {
|
||||
auto name = config_["hwmon-by-name"].asString();
|
||||
auto input_filename = config_["input-filename"].asString();
|
||||
for (const auto& entry : std::filesystem::directory_iterator("/sys/class/hwmon/")) {
|
||||
if (std::filesystem::is_directory(entry) && file_path_.empty()) {
|
||||
auto name_filepath = entry.path().string() + "/name";
|
||||
auto input_filepath = entry.path().string() + "/" + input_filename;
|
||||
|
||||
if (std::filesystem::exists(name_filepath) && std::filesystem::exists(input_filepath)) {
|
||||
std::ifstream name_file(name_filepath);
|
||||
if (!name_file.is_open()) {
|
||||
throw std::runtime_error("Error: Could not open file " + name_filepath);
|
||||
}
|
||||
|
||||
std::string line;
|
||||
while (std::getline(name_file, line)) {
|
||||
if (line.find(name) != std::string::npos) {
|
||||
file_path_ = input_filepath;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (file_path_.empty()) throw std::runtime_error("Could not find hwmon by name " + name);
|
||||
}
|
||||
|
||||
auto find_hwmon_by_name = [](const std::string& name) -> std::optional<std::filesystem::path> {
|
||||
for (const auto& entry : std::filesystem::directory_iterator("/sys/class/hwmon")) {
|
||||
std::ifstream f(entry.path() / "name");
|
||||
@@ -38,12 +67,14 @@ waybar::modules::Temperature::Temperature(const std::string& id, const Json::Val
|
||||
"hwmon-name cannot be used together with hwmon-path or hwmon-path-abs");
|
||||
}
|
||||
|
||||
// if hwmon_path is an array, loop to find first valid item
|
||||
traverseAsArray(config_["hwmon-path"], [this](const std::string& path) {
|
||||
if (!std::filesystem::exists(path)) return false;
|
||||
file_path_ = path;
|
||||
return true;
|
||||
});
|
||||
if (file_path_.empty()) {
|
||||
// if hwmon_path is an array, loop to find first valid item
|
||||
traverseAsArray(config_["hwmon-path"], [this](const std::string& path) {
|
||||
if (!std::filesystem::exists(path)) return false;
|
||||
file_path_ = path;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
if (file_path_.empty() && config_["input-filename"].isString()) {
|
||||
// fallback to hwmon_paths-abs
|
||||
|
||||
+63
-16
@@ -2,6 +2,9 @@
|
||||
|
||||
#include <spdlog/spdlog.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <string>
|
||||
|
||||
bool isValidNodeId(uint32_t id) { return id > 0 && id < G_MAXUINT32; }
|
||||
|
||||
std::list<waybar::modules::Wireplumber*> waybar::modules::Wireplumber::modules;
|
||||
@@ -408,7 +411,7 @@ void waybar::modules::Wireplumber::onMixerApiLoaded(WpObject* p, GAsyncResult* r
|
||||
spdlog::debug("[{}]: loaded mixer API", self->name_);
|
||||
g_ptr_array_add(self->apis_, ({
|
||||
WpPlugin* p = wp_plugin_find(self->wp_core_, "mixer-api");
|
||||
g_object_set(G_OBJECT(p), "scale", 1 /* cubic */, nullptr);
|
||||
g_object_set(G_OBJECT(p), "scale", 0 /* linear */, nullptr);
|
||||
p;
|
||||
}));
|
||||
|
||||
@@ -448,8 +451,14 @@ auto waybar::modules::Wireplumber::update() -> void {
|
||||
label_.get_style_context()->remove_class("source-muted");
|
||||
}
|
||||
|
||||
int vol = round(volume_ * 100.0);
|
||||
int source_vol = round(source_volume_ * 100.0);
|
||||
double vol_cube = pow(volume_, 3);
|
||||
double source_vol_cube = pow(source_volume_, 3);
|
||||
|
||||
int vol = round(vol_cube * 100.0);
|
||||
int source_vol = round(source_vol_cube * 100.0);
|
||||
|
||||
double vol_db = 20.0 * log10(volume_);
|
||||
double source_vol_db = 20.0 * log10(source_volume_);
|
||||
|
||||
// Get the state and apply state-specific format if available
|
||||
auto state = getState(vol);
|
||||
@@ -480,7 +489,11 @@ auto waybar::modules::Wireplumber::update() -> void {
|
||||
std::string markup =
|
||||
fmt::format(fmt::runtime(format), 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_));
|
||||
fmt::arg("source_volume", source_vol), fmt::arg("source_desc", source_name_),
|
||||
fmt::arg("volume_linear", volume_), fmt::arg("volume_cubic", vol_cube),
|
||||
fmt::arg("volume_db", vol_db), fmt::arg("source_volume_linear", source_volume_),
|
||||
fmt::arg("source_volume_cubic", source_vol_cube),
|
||||
fmt::arg("source_volume_db", source_vol_db));
|
||||
label_.set_markup(markup);
|
||||
|
||||
if (tooltipEnabled()) {
|
||||
@@ -492,7 +505,11 @@ auto waybar::modules::Wireplumber::update() -> void {
|
||||
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_)));
|
||||
fmt::arg("source_volume", source_vol), fmt::arg("source_desc", source_name_),
|
||||
fmt::arg("volume_linear", volume_), fmt::arg("volume_cubic", vol_cube),
|
||||
fmt::arg("volume_db", vol_db), fmt::arg("source_volume_linear", source_volume_),
|
||||
fmt::arg("source_volume_cubic", source_vol_cube),
|
||||
fmt::arg("source_volume_db", source_vol_db)));
|
||||
} else {
|
||||
label_.set_tooltip_markup(node_name_);
|
||||
}
|
||||
@@ -511,28 +528,58 @@ bool waybar::modules::Wireplumber::handleScroll(GdkEventScroll* e) {
|
||||
return true;
|
||||
}
|
||||
double maxVolume = 1;
|
||||
double step = 1.0 / 100.0;
|
||||
double step = 1.0;
|
||||
if (config_["scroll-step"].isDouble()) {
|
||||
step = config_["scroll-step"].asDouble() / 100.0;
|
||||
step = config_["scroll-step"].asDouble();
|
||||
}
|
||||
if (config_["max-volume"].isDouble()) {
|
||||
maxVolume = config_["max-volume"].asDouble() / 100.0;
|
||||
maxVolume = config_["max-volume"].asDouble();
|
||||
}
|
||||
|
||||
if (step < min_step_) step = min_step_;
|
||||
double vol = volume_;
|
||||
std::string scale = "cubic_percent";
|
||||
if (config_["scroll-scale"].isString()) {
|
||||
scale = config_["scroll-scale"].asString();
|
||||
}
|
||||
|
||||
double newVol = volume_;
|
||||
if (scale == "cubic") {
|
||||
vol = pow(vol, 3);
|
||||
} else if (scale == "db") {
|
||||
vol = log10(vol) * 20.0;
|
||||
} else if (scale == "cubic_percent") {
|
||||
vol = pow(vol, 3) * 100.0;
|
||||
}
|
||||
|
||||
double newVol = vol;
|
||||
if (dir == SCROLL_DIR::UP) {
|
||||
if (volume_ < maxVolume) {
|
||||
newVol = volume_ + step;
|
||||
if (newVol > maxVolume) newVol = maxVolume;
|
||||
newVol = vol + step;
|
||||
} else if (dir == SCROLL_DIR::DOWN) {
|
||||
newVol = vol - step;
|
||||
}
|
||||
|
||||
if (scale == "cubic") {
|
||||
newVol = cbrt(newVol);
|
||||
} else if (scale == "db") {
|
||||
newVol = exp10(newVol / 20.0);
|
||||
} else if (scale == "cubic_percent") {
|
||||
newVol = cbrt(newVol / 100.0);
|
||||
}
|
||||
|
||||
if (dir == SCROLL_DIR::UP) {
|
||||
if (volume_ + min_step_ > newVol) {
|
||||
newVol = volume_ + min_step_;
|
||||
}
|
||||
} else if (dir == SCROLL_DIR::DOWN) {
|
||||
if (volume_ > 0) {
|
||||
newVol = volume_ - step;
|
||||
if (newVol < 0) newVol = 0;
|
||||
if (volume_ - min_step_ < newVol) {
|
||||
newVol = volume_ - min_step_;
|
||||
}
|
||||
}
|
||||
|
||||
if (newVol < 0)
|
||||
newVol = 0;
|
||||
else if (newVol > maxVolume)
|
||||
newVol = maxVolume;
|
||||
|
||||
if (newVol != volume_) {
|
||||
if (mixer_api_ == nullptr) return true;
|
||||
GVariant* variant = g_variant_new_double(newVol);
|
||||
|
||||
+255
-1
@@ -124,6 +124,17 @@ Task::Task(const waybar::Bar& bar, const Json::Value& config, Taskbar* tbar,
|
||||
content_.add(text_after_);
|
||||
}
|
||||
|
||||
if (config_["justify"].isString()) {
|
||||
auto justify_str = config_["justify"].asString();
|
||||
if (justify_str == "left") {
|
||||
content_.set_halign(Gtk::ALIGN_START);
|
||||
} else if (justify_str == "right") {
|
||||
content_.set_halign(Gtk::ALIGN_END);
|
||||
} else if (justify_str == "center") {
|
||||
content_.set_halign(Gtk::ALIGN_CENTER);
|
||||
}
|
||||
}
|
||||
|
||||
content_.show();
|
||||
button.add(content_);
|
||||
|
||||
@@ -319,9 +330,12 @@ void Task::handle_output_enter(struct wl_output* output) {
|
||||
button.signal_size_allocate().connect_notify(
|
||||
sigc::mem_fun(this, &Task::on_button_size_allocated));
|
||||
tbar_->add_button(button);
|
||||
button.show();
|
||||
if (!config_["active-only"].asBool() || active()) {
|
||||
button.show();
|
||||
}
|
||||
button_visible_ = true;
|
||||
spdlog::debug("{} now visible on {}", repr(), bar_.output->name);
|
||||
tbar_->update_bar_css_classes();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -334,6 +348,7 @@ void Task::handle_output_leave(struct wl_output* output) {
|
||||
button.hide();
|
||||
button_visible_ = false;
|
||||
spdlog::debug("{} now invisible on {}", repr(), bar_.output->name);
|
||||
tbar_->update_bar_css_classes();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -376,6 +391,20 @@ void Task::handle_done() {
|
||||
button.get_style_context()->remove_class("fullscreen");
|
||||
}
|
||||
|
||||
if (button_visible_ && config_["active-only"].asBool()) {
|
||||
if (active()) {
|
||||
button.show();
|
||||
} else {
|
||||
button.hide();
|
||||
}
|
||||
}
|
||||
|
||||
if (active()) {
|
||||
tbar_->assign_current_workspace(*this);
|
||||
}
|
||||
|
||||
tbar_->update_bar_css_classes();
|
||||
|
||||
if (config_["active-first"].isBool() && config_["active-first"].asBool() && active())
|
||||
tbar_->move_button(button, 0);
|
||||
|
||||
@@ -577,6 +606,8 @@ static void handle_global(void* data, struct wl_registry* registry, uint32_t nam
|
||||
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);
|
||||
} else if (std::strcmp(interface, ext_workspace_manager_v1_interface.name) == 0) {
|
||||
static_cast<Taskbar*>(data)->register_workspace_manager(registry, name, version);
|
||||
} else if (std::strcmp(interface, wl_seat_interface.name) == 0) {
|
||||
static_cast<Taskbar*>(data)->register_seat(registry, name, version);
|
||||
}
|
||||
@@ -594,6 +625,7 @@ Taskbar::Taskbar(const std::string& id, const waybar::Bar& bar, const Json::Valu
|
||||
bar_(bar),
|
||||
box_{bar.orientation, 0},
|
||||
manager_{nullptr},
|
||||
workspace_manager_{nullptr},
|
||||
seat_{nullptr} {
|
||||
box_.set_name("taskbar");
|
||||
if (!id.empty()) {
|
||||
@@ -649,6 +681,27 @@ Taskbar::Taskbar(const std::string& id, const waybar::Bar& bar, const Json::Valu
|
||||
}
|
||||
|
||||
Taskbar::~Taskbar() {
|
||||
for (auto& workspace : workspaces_) {
|
||||
ext_workspace_handle_v1_destroy(workspace->handle);
|
||||
}
|
||||
workspaces_.clear();
|
||||
for (auto* group : workspace_groups_) {
|
||||
ext_workspace_group_handle_v1_destroy(group);
|
||||
}
|
||||
workspace_groups_.clear();
|
||||
|
||||
if (workspace_manager_) {
|
||||
struct wl_display* display = Client::inst()->wl_display;
|
||||
ext_workspace_manager_v1_stop(workspace_manager_);
|
||||
wl_display_roundtrip(display);
|
||||
|
||||
if (workspace_manager_) {
|
||||
spdlog::warn("Workspace manager destroyed before .finished event");
|
||||
ext_workspace_manager_v1_destroy(workspace_manager_);
|
||||
workspace_manager_ = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
if (manager_) {
|
||||
struct wl_display* display = Client::inst()->wl_display;
|
||||
/*
|
||||
@@ -665,6 +718,13 @@ Taskbar::~Taskbar() {
|
||||
manager_ = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
if (config_["bar-css-states"].asBool()) {
|
||||
set_bar_css_class("toplevel-active", false);
|
||||
set_bar_css_class("toplevel-maximized", false);
|
||||
set_bar_css_class("toplevel-minimized", false);
|
||||
set_bar_css_class("toplevel-fullscreen", false);
|
||||
}
|
||||
}
|
||||
|
||||
void Taskbar::update() {
|
||||
@@ -700,6 +760,80 @@ static const struct zwlr_foreign_toplevel_manager_v1_listener toplevel_manager_i
|
||||
.finished = tm_handle_finished,
|
||||
};
|
||||
|
||||
static void workspace_handle_id(void*, struct ext_workspace_handle_v1*, const char*) {}
|
||||
static void workspace_handle_name(void*, struct ext_workspace_handle_v1*, const char*) {}
|
||||
static void workspace_handle_coordinates(void*, struct ext_workspace_handle_v1*, struct wl_array*) {
|
||||
}
|
||||
|
||||
static void workspace_handle_state(void* data, struct ext_workspace_handle_v1*, uint32_t state) {
|
||||
static_cast<Taskbar::WorkspaceState*>(data)->state = state;
|
||||
}
|
||||
|
||||
static void workspace_handle_capabilities(void*, struct ext_workspace_handle_v1*, uint32_t) {}
|
||||
|
||||
static void workspace_handle_removed(void* data, struct ext_workspace_handle_v1* handle) {
|
||||
static_cast<Taskbar::WorkspaceState*>(data)->taskbar->handle_workspace_removed(handle);
|
||||
}
|
||||
|
||||
static const struct ext_workspace_handle_v1_listener workspace_handle_impl = {
|
||||
.id = workspace_handle_id,
|
||||
.name = workspace_handle_name,
|
||||
.coordinates = workspace_handle_coordinates,
|
||||
.state = workspace_handle_state,
|
||||
.capabilities = workspace_handle_capabilities,
|
||||
.removed = workspace_handle_removed,
|
||||
};
|
||||
|
||||
static void workspace_group_handle_capabilities(void*, struct ext_workspace_group_handle_v1*,
|
||||
uint32_t) {}
|
||||
static void workspace_group_handle_output_enter(void*, struct ext_workspace_group_handle_v1*,
|
||||
struct wl_output*) {}
|
||||
static void workspace_group_handle_output_leave(void*, struct ext_workspace_group_handle_v1*,
|
||||
struct wl_output*) {}
|
||||
static void workspace_group_handle_workspace_enter(void*, struct ext_workspace_group_handle_v1*,
|
||||
struct ext_workspace_handle_v1*) {}
|
||||
static void workspace_group_handle_workspace_leave(void*, struct ext_workspace_group_handle_v1*,
|
||||
struct ext_workspace_handle_v1*) {}
|
||||
|
||||
static void workspace_group_handle_removed(void* data,
|
||||
struct ext_workspace_group_handle_v1* group) {
|
||||
static_cast<Taskbar*>(data)->handle_workspace_group_removed(group);
|
||||
}
|
||||
|
||||
static const struct ext_workspace_group_handle_v1_listener workspace_group_impl = {
|
||||
.capabilities = workspace_group_handle_capabilities,
|
||||
.output_enter = workspace_group_handle_output_enter,
|
||||
.output_leave = workspace_group_handle_output_leave,
|
||||
.workspace_enter = workspace_group_handle_workspace_enter,
|
||||
.workspace_leave = workspace_group_handle_workspace_leave,
|
||||
.removed = workspace_group_handle_removed,
|
||||
};
|
||||
|
||||
static void workspace_manager_handle_group(void* data, struct ext_workspace_manager_v1*,
|
||||
struct ext_workspace_group_handle_v1* group) {
|
||||
static_cast<Taskbar*>(data)->handle_workspace_group_create(group);
|
||||
}
|
||||
|
||||
static void workspace_manager_handle_workspace(void* data, struct ext_workspace_manager_v1*,
|
||||
struct ext_workspace_handle_v1* workspace) {
|
||||
static_cast<Taskbar*>(data)->handle_workspace_create(workspace);
|
||||
}
|
||||
|
||||
static void workspace_manager_handle_done(void* data, struct ext_workspace_manager_v1*) {
|
||||
static_cast<Taskbar*>(data)->handle_workspace_done();
|
||||
}
|
||||
|
||||
static void workspace_manager_handle_finished(void* data, struct ext_workspace_manager_v1*) {
|
||||
static_cast<Taskbar*>(data)->handle_workspace_finished();
|
||||
}
|
||||
|
||||
static const struct ext_workspace_manager_v1_listener workspace_manager_impl = {
|
||||
.workspace_group = workspace_manager_handle_group,
|
||||
.workspace = workspace_manager_handle_workspace,
|
||||
.done = workspace_manager_handle_done,
|
||||
.finished = workspace_manager_handle_finished,
|
||||
};
|
||||
|
||||
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!");
|
||||
@@ -724,6 +858,18 @@ void Taskbar::register_manager(struct wl_registry* registry, uint32_t name, uint
|
||||
spdlog::debug("Failed to register manager");
|
||||
}
|
||||
|
||||
void Taskbar::register_workspace_manager(struct wl_registry* registry, uint32_t name,
|
||||
uint32_t version) {
|
||||
if (workspace_manager_) {
|
||||
return;
|
||||
}
|
||||
|
||||
version = std::min<uint32_t>(version, ext_workspace_manager_v1_interface.version);
|
||||
workspace_manager_ = static_cast<struct ext_workspace_manager_v1*>(
|
||||
wl_registry_bind(registry, name, &ext_workspace_manager_v1_interface, version));
|
||||
ext_workspace_manager_v1_add_listener(workspace_manager_, &workspace_manager_impl, this);
|
||||
}
|
||||
|
||||
void Taskbar::register_seat(struct wl_registry* registry, uint32_t name, uint32_t version) {
|
||||
if (seat_) {
|
||||
spdlog::warn("Register seat again although already existing!");
|
||||
@@ -743,6 +889,64 @@ void Taskbar::handle_finished() {
|
||||
manager_ = nullptr;
|
||||
}
|
||||
|
||||
void Taskbar::handle_workspace_group_create(struct ext_workspace_group_handle_v1* handle) {
|
||||
ext_workspace_group_handle_v1_add_listener(handle, &workspace_group_impl, this);
|
||||
workspace_groups_.push_back(handle);
|
||||
}
|
||||
|
||||
void Taskbar::handle_workspace_group_removed(struct ext_workspace_group_handle_v1* handle) {
|
||||
const auto group = std::find(workspace_groups_.begin(), workspace_groups_.end(), handle);
|
||||
if (group != workspace_groups_.end()) {
|
||||
ext_workspace_group_handle_v1_destroy(*group);
|
||||
workspace_groups_.erase(group);
|
||||
}
|
||||
}
|
||||
|
||||
void Taskbar::handle_workspace_create(struct ext_workspace_handle_v1* handle) {
|
||||
auto workspace = std::make_unique<WorkspaceState>(WorkspaceState{this, handle});
|
||||
ext_workspace_handle_v1_add_listener(handle, &workspace_handle_impl, workspace.get());
|
||||
workspaces_.push_back(std::move(workspace));
|
||||
}
|
||||
|
||||
void Taskbar::handle_workspace_done() {
|
||||
const auto active_workspace =
|
||||
std::find_if(workspaces_.begin(), workspaces_.end(), [](const auto& workspace) {
|
||||
return workspace->state & EXT_WORKSPACE_HANDLE_V1_STATE_ACTIVE;
|
||||
});
|
||||
current_workspace_ =
|
||||
active_workspace == workspaces_.end() ? nullptr : (*active_workspace)->handle;
|
||||
if (current_workspace_) {
|
||||
const auto active_task =
|
||||
std::find_if(tasks_.begin(), tasks_.end(), [](const auto& task) { return task->active(); });
|
||||
if (active_task != tasks_.end()) {
|
||||
(*active_task)->set_workspace(current_workspace_);
|
||||
}
|
||||
}
|
||||
update_bar_css_classes();
|
||||
}
|
||||
|
||||
void Taskbar::handle_workspace_finished() { workspace_manager_ = nullptr; }
|
||||
|
||||
void Taskbar::handle_workspace_removed(struct ext_workspace_handle_v1* handle) {
|
||||
if (current_workspace_ == handle) {
|
||||
current_workspace_ = nullptr;
|
||||
}
|
||||
for (auto& task : tasks_) {
|
||||
if (task->workspace() == handle) {
|
||||
task->set_workspace(nullptr);
|
||||
}
|
||||
}
|
||||
|
||||
const auto workspace =
|
||||
std::find_if(workspaces_.begin(), workspaces_.end(),
|
||||
[handle](const auto& workspace) { return workspace->handle == handle; });
|
||||
if (workspace != workspaces_.end()) {
|
||||
ext_workspace_handle_v1_destroy((*workspace)->handle);
|
||||
workspaces_.erase(workspace);
|
||||
}
|
||||
update_bar_css_classes();
|
||||
}
|
||||
|
||||
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). */
|
||||
@@ -775,6 +979,56 @@ void Taskbar::remove_task(uint32_t id) {
|
||||
}
|
||||
|
||||
tasks_.erase(it);
|
||||
update_bar_css_classes();
|
||||
}
|
||||
|
||||
void Taskbar::assign_current_workspace(Task& task) {
|
||||
if (current_workspace_) {
|
||||
task.set_workspace(current_workspace_);
|
||||
}
|
||||
}
|
||||
|
||||
void Taskbar::update_bar_css_classes() {
|
||||
if (!config_["bar-css-states"].asBool()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const auto active_task = std::find_if(tasks_.begin(), tasks_.end(), [](const TaskPtr& task) {
|
||||
return task->visible() && task->active();
|
||||
});
|
||||
|
||||
const bool has_active_task = active_task != tasks_.end();
|
||||
const auto on_current_workspace = [this](const TaskPtr& task) {
|
||||
if (!current_workspace_) {
|
||||
return task->active();
|
||||
}
|
||||
return task->workspace() == current_workspace_;
|
||||
};
|
||||
const bool has_maximized_task =
|
||||
std::any_of(tasks_.begin(), tasks_.end(), [&on_current_workspace](const TaskPtr& task) {
|
||||
return task->visible() && !task->minimized() && on_current_workspace(task) &&
|
||||
task->maximized();
|
||||
});
|
||||
const bool has_fullscreen_task =
|
||||
std::any_of(tasks_.begin(), tasks_.end(), [&on_current_workspace](const TaskPtr& task) {
|
||||
return task->visible() && !task->minimized() && on_current_workspace(task) &&
|
||||
task->fullscreen();
|
||||
});
|
||||
set_bar_css_class("toplevel-active", has_active_task);
|
||||
set_bar_css_class("toplevel-maximized", has_maximized_task);
|
||||
set_bar_css_class("toplevel-minimized", has_active_task && (*active_task)->minimized());
|
||||
set_bar_css_class("toplevel-fullscreen", has_fullscreen_task);
|
||||
}
|
||||
|
||||
void Taskbar::set_bar_css_class(const std::string& class_name, bool enabled) {
|
||||
const auto style = bar_.window.get_style_context();
|
||||
if (enabled && !style->has_class(class_name)) {
|
||||
spdlog::trace("Adding bar class: {}", class_name);
|
||||
style->add_class(class_name);
|
||||
} else if (!enabled && style->has_class(class_name)) {
|
||||
spdlog::trace("Removing bar class: {}", class_name);
|
||||
style->remove_class(class_name);
|
||||
}
|
||||
}
|
||||
|
||||
bool Taskbar::show_output(struct wl_output* output) const {
|
||||
|
||||
+70
-23
@@ -24,8 +24,9 @@ AudioBackend::AudioBackend(std::function<void()> on_updated_cb, private_construc
|
||||
source_volume_(0),
|
||||
source_muted_(false),
|
||||
on_updated_cb_(std::move(on_updated_cb)) {
|
||||
// Initialize pa_volume_ with safe defaults
|
||||
// Initialize pa_volume_ and pa_source_volume_ with safe defaults
|
||||
pa_cvolume_init(&pa_volume_);
|
||||
pa_cvolume_init(&pa_source_volume_);
|
||||
mainloop_ = pa_threaded_mainloop_new();
|
||||
if (mainloop_ == nullptr) {
|
||||
throw std::runtime_error("pa_mainloop_new() failed.");
|
||||
@@ -157,6 +158,19 @@ void AudioBackend::volumeModifyCb(pa_context* c, int success, void* data) {
|
||||
}
|
||||
}
|
||||
|
||||
void AudioBackend::sourceVolumeModifyCb(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) {
|
||||
pa_context_get_source_info_by_index(backend->context_, backend->source_idx_, sourceInfoCb,
|
||||
data);
|
||||
}
|
||||
} else {
|
||||
spdlog::debug("Source volume modification failed");
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Called when the requested sink information is ready.
|
||||
*/
|
||||
@@ -236,6 +250,11 @@ void AudioBackend::sourceInfoCb(pa_context* /*context*/, const pa_source_info* i
|
||||
void* data) {
|
||||
auto* backend = static_cast<AudioBackend*>(data);
|
||||
if (i != nullptr && backend->default_source_name_ == i->name) {
|
||||
if (pa_cvolume_valid(&i->volume) != 0) {
|
||||
backend->pa_source_volume_ = i->volume;
|
||||
} else {
|
||||
pa_cvolume_init(&backend->pa_source_volume_);
|
||||
}
|
||||
auto source_volume = static_cast<float>(pa_cvolume_avg(&(i->volume))) / float{PA_VOLUME_NORM};
|
||||
backend->source_volume_ = std::round(source_volume * 100.0F);
|
||||
backend->source_idx_ = i->index;
|
||||
@@ -269,25 +288,31 @@ uint16_t AudioBackend::getVolume(PulseaudioTarget target) const {
|
||||
}
|
||||
}
|
||||
|
||||
void AudioBackend::changeVolume(uint16_t volume, uint16_t min_volume, uint16_t max_volume) {
|
||||
void AudioBackend::changeVolume(uint16_t volume, uint16_t min_volume, uint16_t max_volume,
|
||||
PulseaudioTarget target) {
|
||||
// Early return if context is not ready
|
||||
if ((context_ == nullptr) || pa_context_get_state(context_) != PA_CONTEXT_READY) {
|
||||
spdlog::error("PulseAudio context not ready");
|
||||
return;
|
||||
}
|
||||
|
||||
bool is_source = target == PulseaudioTarget::Source;
|
||||
|
||||
// Select the appropriate stored volume structure
|
||||
auto& ref_volume = is_source ? pa_source_volume_ : pa_volume_;
|
||||
|
||||
// Prepare volume structure
|
||||
pa_cvolume pa_volume;
|
||||
|
||||
pa_cvolume_init(&pa_volume);
|
||||
|
||||
// Use existing volume structure if valid, otherwise create a safe default
|
||||
if ((pa_cvolume_valid(&pa_volume_) != 0) && (pa_channels_valid(pa_volume_.channels) != 0)) {
|
||||
pa_volume = pa_volume_;
|
||||
if ((pa_cvolume_valid(&ref_volume) != 0) && (pa_channels_valid(ref_volume.channels) != 0)) {
|
||||
pa_volume = ref_volume;
|
||||
} else {
|
||||
// Set stereo as a safe default
|
||||
pa_volume.channels = 2;
|
||||
spdlog::debug("Using default stereo volume structure");
|
||||
// Mono for sources (microphones), stereo for sinks
|
||||
pa_volume.channels = is_source ? 1 : 2;
|
||||
spdlog::debug("Using default volume structure ({} channels)", pa_volume.channels);
|
||||
}
|
||||
|
||||
// Set the volume safely
|
||||
@@ -301,39 +326,56 @@ void AudioBackend::changeVolume(uint16_t volume, uint16_t min_volume, uint16_t m
|
||||
|
||||
// Apply the volume change
|
||||
pa_threaded_mainloop_lock(mainloop_);
|
||||
pa_context_set_sink_volume_by_index(context_, sink_idx_, &pa_volume, volumeModifyCb, this);
|
||||
if (is_source) {
|
||||
pa_context_set_source_volume_by_index(context_, source_idx_, &pa_volume, sourceVolumeModifyCb,
|
||||
this);
|
||||
} else {
|
||||
pa_context_set_sink_volume_by_index(context_, sink_idx_, &pa_volume, volumeModifyCb, this);
|
||||
}
|
||||
pa_threaded_mainloop_unlock(mainloop_);
|
||||
}
|
||||
|
||||
void AudioBackend::changeVolume(ChangeType change_type, double step, uint16_t max_volume) {
|
||||
void AudioBackend::changeVolume(ChangeType change_type, double step, uint16_t max_volume,
|
||||
PulseaudioTarget target) {
|
||||
// Early return if context is not ready
|
||||
if ((context_ == nullptr) || pa_context_get_state(context_) != PA_CONTEXT_READY) {
|
||||
spdlog::error("PulseAudio context not ready");
|
||||
return;
|
||||
}
|
||||
|
||||
bool is_source = target == PulseaudioTarget::Source;
|
||||
|
||||
// Select the appropriate stored volume structure and current volume
|
||||
auto& ref_volume = is_source ? pa_source_volume_ : pa_volume_;
|
||||
auto current_volume = is_source ? source_volume_ : volume_;
|
||||
|
||||
// Prepare volume structure
|
||||
pa_cvolume pa_volume;
|
||||
pa_cvolume_init(&pa_volume);
|
||||
|
||||
// Use existing volume structure if valid, otherwise create a safe default
|
||||
if ((pa_cvolume_valid(&pa_volume_) != 0) && (pa_channels_valid(pa_volume_.channels) != 0)) {
|
||||
pa_volume = pa_volume_;
|
||||
if ((pa_cvolume_valid(&ref_volume) != 0) && (pa_channels_valid(ref_volume.channels) != 0)) {
|
||||
pa_volume = ref_volume;
|
||||
} else {
|
||||
// Set stereo as a safe default
|
||||
pa_volume.channels = 2;
|
||||
spdlog::debug("Using default stereo volume structure");
|
||||
// Mono for sources (microphones), stereo for sinks
|
||||
pa_volume.channels = is_source ? 1 : 2;
|
||||
spdlog::debug("Using default volume structure ({} channels)", pa_volume.channels);
|
||||
|
||||
// Initialize all channels to current volume level
|
||||
double volume_tick = static_cast<double>(PA_VOLUME_NORM) / 100;
|
||||
pa_volume_t vol = volume_ * volume_tick;
|
||||
pa_volume_t vol = current_volume * volume_tick;
|
||||
for (uint8_t i = 0; i < pa_volume.channels; i++) {
|
||||
pa_volume.values[i] = vol;
|
||||
}
|
||||
|
||||
// No need to continue with volume change if we had to create a new structure
|
||||
pa_threaded_mainloop_lock(mainloop_);
|
||||
pa_context_set_sink_volume_by_index(context_, sink_idx_, &pa_volume, volumeModifyCb, this);
|
||||
if (is_source) {
|
||||
pa_context_set_source_volume_by_index(context_, source_idx_, &pa_volume, sourceVolumeModifyCb,
|
||||
this);
|
||||
} else {
|
||||
pa_context_set_sink_volume_by_index(context_, sink_idx_, &pa_volume, volumeModifyCb, this);
|
||||
}
|
||||
pa_threaded_mainloop_unlock(mainloop_);
|
||||
return;
|
||||
}
|
||||
@@ -343,10 +385,10 @@ void AudioBackend::changeVolume(ChangeType change_type, double step, uint16_t ma
|
||||
pa_volume_t change;
|
||||
max_volume = std::min(max_volume, static_cast<uint16_t>(PA_VOLUME_UI_MAX));
|
||||
|
||||
if (change_type == ChangeType::Increase && volume_ < max_volume) {
|
||||
if (change_type == ChangeType::Increase && current_volume < max_volume) {
|
||||
// Calculate how much to increase
|
||||
if (volume_ + step > max_volume) {
|
||||
change = round((max_volume - volume_) * volume_tick);
|
||||
if (current_volume + step > max_volume) {
|
||||
change = round((max_volume - current_volume) * volume_tick);
|
||||
} else {
|
||||
change = round(step * volume_tick);
|
||||
}
|
||||
@@ -355,10 +397,10 @@ void AudioBackend::changeVolume(ChangeType change_type, double step, uint16_t ma
|
||||
for (uint8_t i = 0; i < pa_volume.channels; i++) {
|
||||
pa_volume.values[i] = std::min(pa_volume.values[i] + change, PA_VOLUME_MAX);
|
||||
}
|
||||
} else if (change_type == ChangeType::Decrease && volume_ > 0) {
|
||||
} else if (change_type == ChangeType::Decrease && current_volume > 0) {
|
||||
// Calculate how much to decrease
|
||||
if (volume_ - step < 0) {
|
||||
change = round(volume_ * volume_tick);
|
||||
if (current_volume - step < 0) {
|
||||
change = round(current_volume * volume_tick);
|
||||
} else {
|
||||
change = round(step * volume_tick);
|
||||
}
|
||||
@@ -374,7 +416,12 @@ void AudioBackend::changeVolume(ChangeType change_type, double step, uint16_t ma
|
||||
|
||||
// Apply the volume change
|
||||
pa_threaded_mainloop_lock(mainloop_);
|
||||
pa_context_set_sink_volume_by_index(context_, sink_idx_, &pa_volume, volumeModifyCb, this);
|
||||
if (is_source) {
|
||||
pa_context_set_source_volume_by_index(context_, source_idx_, &pa_volume, sourceVolumeModifyCb,
|
||||
this);
|
||||
} else {
|
||||
pa_context_set_sink_volume_by_index(context_, sink_idx_, &pa_volume, volumeModifyCb, this);
|
||||
}
|
||||
pa_threaded_mainloop_unlock(mainloop_);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
#include "util/hosts_check.hpp"
|
||||
|
||||
#include <glibmm/miscutils.h>
|
||||
#include <json/config.h>
|
||||
|
||||
namespace waybar::util {
|
||||
bool valid_host(const Json::Value& config) {
|
||||
if (config.isMember("hosts") && config["hosts"].isArray()) {
|
||||
const auto hostname = Glib::get_host_name();
|
||||
|
||||
if (!std::ranges::any_of(config["hosts"].begin(), config["hosts"].end(),
|
||||
[&](const auto& h) { return h.asString() == hostname; }))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
} // namespace waybar::util
|
||||
Reference in New Issue
Block a user