refactor: lint

This commit is contained in:
Alex 2022-04-06 08:37:19 +02:00
parent 168ba2ca5b
commit f2fcadbf62
99 changed files with 3173 additions and 3512 deletions

View File

@ -1,6 +1,5 @@
--- ---
BasedOnStyle: Google BasedOnStyle: Google
AlignConsecutiveDeclarations: true AlignConsecutiveDeclarations: false
BinPackArguments: false
ColumnLimit: 100 ColumnLimit: 100
... ...

View File

@ -3,6 +3,7 @@
#include <glibmm/markup.h> #include <glibmm/markup.h>
#include <gtkmm/label.h> #include <gtkmm/label.h>
#include <json/json.h> #include <json/json.h>
#include "AModule.hpp" #include "AModule.hpp"
namespace waybar { namespace waybar {
@ -10,7 +11,8 @@ namespace waybar {
class ALabel : public AModule { class ALabel : public AModule {
public: public:
ALabel(const Json::Value &, const std::string &, const std::string &, const std::string &format, ALabel(const Json::Value &, const std::string &, const std::string &, const std::string &format,
uint16_t interval = 0, bool ellipsize = false, bool enable_click = false, bool enable_scroll = false); uint16_t interval = 0, bool ellipsize = false, bool enable_click = false,
bool enable_scroll = false);
virtual ~ALabel() = default; virtual ~ALabel() = default;
virtual auto update() -> void; virtual auto update() -> void;
virtual std::string getIcon(uint16_t, const std::string &alt = "", uint16_t max = 0); virtual std::string getIcon(uint16_t, const std::string &alt = "", uint16_t max = 0);

View File

@ -51,8 +51,7 @@ class AModule : public IModule {
{std::make_pair(8, GdkEventType::GDK_2BUTTON_PRESS), "on-triple-click-backward"}, {std::make_pair(8, GdkEventType::GDK_2BUTTON_PRESS), "on-triple-click-backward"},
{std::make_pair(9, GdkEventType::GDK_BUTTON_PRESS), "on-click-forward"}, {std::make_pair(9, GdkEventType::GDK_BUTTON_PRESS), "on-click-forward"},
{std::make_pair(9, GdkEventType::GDK_2BUTTON_PRESS), "on-double-click-forward"}, {std::make_pair(9, GdkEventType::GDK_2BUTTON_PRESS), "on-double-click-forward"},
{std::make_pair(9, GdkEventType::GDK_2BUTTON_PRESS), "on-triple-click-forward"} {std::make_pair(9, GdkEventType::GDK_2BUTTON_PRESS), "on-triple-click-forward"}};
};
}; };
} // namespace waybar } // namespace waybar

View File

@ -8,7 +8,7 @@ class IModule {
public: public:
virtual ~IModule() = default; virtual ~IModule() = default;
virtual auto update() -> void = 0; virtual auto update() -> void = 0;
virtual operator Gtk::Widget &() = 0; virtual operator Gtk::Widget&() = 0;
}; };
} // namespace waybar } // namespace waybar

View File

@ -98,7 +98,7 @@ class Bar {
private: private:
void onMap(GdkEventAny *); void onMap(GdkEventAny *);
auto setupWidgets() -> void; auto setupWidgets() -> void;
void getModules(const Factory &, const std::string &, Gtk::Box*); void getModules(const Factory &, const std::string &, Gtk::Box *);
void setupAltFormatKeyForModule(const std::string &module_name); void setupAltFormatKeyForModule(const std::string &module_name);
void setupAltFormatKeyForModuleList(const char *module_list_name); void setupAltFormatKeyForModuleList(const char *module_list_name);
void setMode(const bar_mode &); void setMode(const bar_mode &);

View File

@ -22,10 +22,10 @@ class Client {
Glib::RefPtr<Gtk::Application> gtk_app; Glib::RefPtr<Gtk::Application> gtk_app;
Glib::RefPtr<Gdk::Display> gdk_display; Glib::RefPtr<Gdk::Display> gdk_display;
struct wl_display * wl_display = nullptr; struct wl_display *wl_display = nullptr;
struct wl_registry * registry = nullptr; struct wl_registry *registry = nullptr;
struct zwlr_layer_shell_v1 * layer_shell = nullptr; struct zwlr_layer_shell_v1 *layer_shell = nullptr;
struct zxdg_output_manager_v1 * xdg_output_manager = nullptr; struct zxdg_output_manager_v1 *xdg_output_manager = nullptr;
struct zwp_idle_inhibit_manager_v1 *idle_inhibit_manager = nullptr; struct zwp_idle_inhibit_manager_v1 *idle_inhibit_manager = nullptr;
std::vector<std::unique_ptr<Bar>> bars; std::vector<std::unique_ptr<Bar>> bars;
Config config; Config config;
@ -37,7 +37,7 @@ class Client {
void bindInterfaces(); void bindInterfaces();
void handleOutput(struct waybar_output &output); void handleOutput(struct waybar_output &output);
auto setupCss(const std::string &css_file) -> void; auto setupCss(const std::string &css_file) -> void;
struct waybar_output & getOutput(void *); struct waybar_output &getOutput(void *);
std::vector<Json::Value> getOutputConfigs(struct waybar_output &output); std::vector<Json::Value> getOutputConfigs(struct waybar_output &output);
static void handleGlobal(void *data, struct wl_registry *registry, uint32_t name, static void handleGlobal(void *data, struct wl_registry *registry, uint32_t name,

View File

@ -7,10 +7,10 @@
#include "modules/simpleclock.hpp" #include "modules/simpleclock.hpp"
#endif #endif
#ifdef HAVE_SWAY #ifdef HAVE_SWAY
#include "modules/sway/language.hpp"
#include "modules/sway/mode.hpp" #include "modules/sway/mode.hpp"
#include "modules/sway/window.hpp" #include "modules/sway/window.hpp"
#include "modules/sway/workspaces.hpp" #include "modules/sway/workspaces.hpp"
#include "modules/sway/language.hpp"
#endif #endif
#ifdef HAVE_WLR #ifdef HAVE_WLR
#include "modules/wlr/taskbar.hpp" #include "modules/wlr/taskbar.hpp"
@ -61,9 +61,9 @@
#include "modules/custom.hpp" #include "modules/custom.hpp"
#include "modules/temperature.hpp" #include "modules/temperature.hpp"
#if defined(__linux__) #if defined(__linux__)
# ifdef WANT_RFKILL #ifdef WANT_RFKILL
# include "modules/bluetooth.hpp" #include "modules/bluetooth.hpp"
# endif #endif
#endif #endif
namespace waybar { namespace waybar {

View File

@ -1,8 +1,9 @@
#pragma once #pragma once
#include <gtkmm/widget.h>
#include <gtkmm/box.h> #include <gtkmm/box.h>
#include <gtkmm/widget.h>
#include <json/json.h> #include <json/json.h>
#include "AModule.hpp" #include "AModule.hpp"
#include "bar.hpp" #include "bar.hpp"
#include "factory.hpp" #include "factory.hpp"
@ -14,7 +15,7 @@ class Group : public AModule {
Group(const std::string&, const Bar&, const Json::Value&); Group(const std::string&, const Bar&, const Json::Value&);
~Group() = default; ~Group() = default;
auto update() -> void; auto update() -> void;
operator Gtk::Widget &(); operator Gtk::Widget&();
Gtk::Box box; Gtk::Box box;
}; };

View File

@ -7,10 +7,12 @@
#endif #endif
#include <fmt/format.h> #include <fmt/format.h>
#include <sys/inotify.h> #include <sys/inotify.h>
#include <algorithm> #include <algorithm>
#include <fstream> #include <fstream>
#include <string> #include <string>
#include <vector> #include <vector>
#include "ALabel.hpp" #include "ALabel.hpp"
#include "util/sleeper_thread.hpp" #include "util/sleeper_thread.hpp"
@ -38,7 +40,7 @@ class Battery : public ALabel {
const std::string formatTimeRemaining(float hoursRemaining); const std::string formatTimeRemaining(float hoursRemaining);
int global_watch; int global_watch;
std::map<fs::path,int> batteries_; std::map<fs::path, int> batteries_;
fs::path adapter_; fs::path adapter_;
int battery_watch_fd_; int battery_watch_fd_;
int global_watch_fd_; int global_watch_fd_;

View File

@ -1,6 +1,7 @@
#pragma once #pragma once
#include <date/tz.h> #include <date/tz.h>
#include "ALabel.hpp" #include "ALabel.hpp"
#include "util/sleeper_thread.hpp" #include "util/sleeper_thread.hpp"
@ -24,7 +25,7 @@ class Clock : public ALabel {
std::locale locale_; std::locale locale_;
std::vector<const date::time_zone*> time_zones_; std::vector<const date::time_zone*> time_zones_;
int current_time_zone_idx_; int current_time_zone_idx_;
date::year_month_day cached_calendar_ymd_ = date::January/1/0; date::year_month_day cached_calendar_ymd_ = date::January / 1 / 0;
std::string cached_calendar_text_; std::string cached_calendar_text_;
bool is_calendar_in_tooltip_; bool is_calendar_in_tooltip_;
bool is_timezoned_list_in_tooltip_; bool is_timezoned_list_in_tooltip_;
@ -36,7 +37,7 @@ class Clock : public ALabel {
auto first_day_of_week() -> date::weekday; auto first_day_of_week() -> date::weekday;
const date::time_zone* current_timezone(); const date::time_zone* current_timezone();
bool is_timezone_fixed(); bool is_timezone_fixed();
auto timezones_text(std::chrono::system_clock::time_point *now) -> std::string; auto timezones_text(std::chrono::system_clock::time_point* now) -> std::string;
}; };
} // namespace modules } // namespace modules

View File

@ -1,12 +1,14 @@
#pragma once #pragma once
#include <fmt/format.h> #include <fmt/format.h>
#include <cstdint> #include <cstdint>
#include <fstream> #include <fstream>
#include <numeric> #include <numeric>
#include <string> #include <string>
#include <utility> #include <utility>
#include <vector> #include <vector>
#include "ALabel.hpp" #include "ALabel.hpp"
#include "util/sleeper_thread.hpp" #include "util/sleeper_thread.hpp"

View File

@ -1,8 +1,10 @@
#pragma once #pragma once
#include <fmt/format.h> #include <fmt/format.h>
#include <csignal> #include <csignal>
#include <string> #include <string>
#include "ALabel.hpp" #include "ALabel.hpp"
#include "util/command.hpp" #include "util/command.hpp"
#include "util/json.hpp" #include "util/json.hpp"

View File

@ -1,11 +1,13 @@
#pragma once #pragma once
#include <fmt/format.h> #include <fmt/format.h>
#include <fstream>
#include <sys/statvfs.h> #include <sys/statvfs.h>
#include <fstream>
#include "ALabel.hpp" #include "ALabel.hpp"
#include "util/sleeper_thread.hpp"
#include "util/format.hpp" #include "util/format.hpp"
#include "util/sleeper_thread.hpp"
namespace waybar::modules { namespace waybar::modules {

View File

@ -1,6 +1,7 @@
#pragma once #pragma once
#include <fmt/format.h> #include <fmt/format.h>
#include "ALabel.hpp" #include "ALabel.hpp"
#include "bar.hpp" #include "bar.hpp"
#include "client.hpp" #include "client.hpp"

View File

@ -1,9 +1,9 @@
#pragma once #pragma once
#include <memory>
#include <gio/gio.h> #include <gio/gio.h>
#include <memory>
#include "ALabel.hpp" #include "ALabel.hpp"
#include "bar.hpp" #include "bar.hpp"
@ -19,7 +19,7 @@ class Inhibitor : public ALabel {
private: private:
auto handleToggle(::GdkEventButton* const& e) -> bool; auto handleToggle(::GdkEventButton* const& e) -> bool;
const std::unique_ptr<::GDBusConnection, void(*)(::GDBusConnection*)> dbus_; const std::unique_ptr<::GDBusConnection, void (*)(::GDBusConnection*)> dbus_;
const std::string inhibitors_; const std::string inhibitors_;
int handle_ = -1; int handle_ = -1;
}; };

View File

@ -6,10 +6,11 @@
#else #else
#include <fmt/chrono.h> #include <fmt/chrono.h>
#endif #endif
#include <gtkmm/label.h>
#include "AModule.hpp" #include "AModule.hpp"
#include "bar.hpp" #include "bar.hpp"
#include "util/sleeper_thread.hpp" #include "util/sleeper_thread.hpp"
#include <gtkmm/label.h>
extern "C" { extern "C" {
#include <libevdev/libevdev.h> #include <libevdev/libevdev.h>

View File

@ -1,8 +1,10 @@
#pragma once #pragma once
#include <fmt/format.h> #include <fmt/format.h>
#include <fstream> #include <fstream>
#include <unordered_map> #include <unordered_map>
#include "ALabel.hpp" #include "ALabel.hpp"
#include "util/sleeper_thread.hpp" #include "util/sleeper_thread.hpp"

View File

@ -1,7 +1,7 @@
#pragma once #pragma once
#include <mpd/client.h>
#include <fmt/format.h> #include <fmt/format.h>
#include <mpd/client.h>
#include <spdlog/spdlog.h> #include <spdlog/spdlog.h>
#include <condition_variable> #include <condition_variable>

View File

@ -12,9 +12,7 @@ inline void Context::tryConnect() const { mpd_module_->tryConne
inline unique_connection& Context::connection() { return mpd_module_->connection_; } inline unique_connection& Context::connection() { return mpd_module_->connection_; }
constexpr inline mpd_state Context::state() const { return mpd_module_->state_; } constexpr inline mpd_state Context::state() const { return mpd_module_->state_; }
inline void Context::do_update() { inline void Context::do_update() { mpd_module_->setLabel(); }
mpd_module_->setLabel();
}
inline void Context::checkErrors(mpd_connection* conn) const { mpd_module_->checkErrors(conn); } inline void Context::checkErrors(mpd_connection* conn) const { mpd_module_->checkErrors(conn); }
inline void Context::queryMPD() const { mpd_module_->queryMPD(); } inline void Context::queryMPD() const { mpd_module_->queryMPD(); }

View File

@ -7,6 +7,7 @@
#include <netlink/genl/genl.h> #include <netlink/genl/genl.h>
#include <netlink/netlink.h> #include <netlink/netlink.h>
#include <sys/epoll.h> #include <sys/epoll.h>
#include "ALabel.hpp" #include "ALabel.hpp"
#include "util/sleeper_thread.hpp" #include "util/sleeper_thread.hpp"
#ifdef WANT_RFKILL #ifdef WANT_RFKILL

View File

@ -3,8 +3,10 @@
#include <fmt/format.h> #include <fmt/format.h>
#include <pulse/pulseaudio.h> #include <pulse/pulseaudio.h>
#include <pulse/volume.h> #include <pulse/volume.h>
#include <algorithm> #include <algorithm>
#include <array> #include <array>
#include "ALabel.hpp" #include "ALabel.hpp"
namespace waybar::modules { namespace waybar::modules {

View File

@ -5,8 +5,8 @@
#include "AModule.hpp" #include "AModule.hpp"
#include "bar.hpp" #include "bar.hpp"
#include "river-status-unstable-v1-client-protocol.h"
#include "river-control-unstable-v1-client-protocol.h" #include "river-control-unstable-v1-client-protocol.h"
#include "river-status-unstable-v1-client-protocol.h"
#include "xdg-output-unstable-v1-client-protocol.h" #include "xdg-output-unstable-v1-client-protocol.h"
namespace waybar::modules::river { namespace waybar::modules::river {
@ -29,7 +29,7 @@ class Tags : public waybar::AModule {
struct wl_seat *seat_; struct wl_seat *seat_;
private: private:
const waybar::Bar & bar_; const waybar::Bar &bar_;
Gtk::Box box_; Gtk::Box box_;
std::vector<Gtk::Button> buttons_; std::vector<Gtk::Button> buttons_;
struct zriver_output_status_v1 *output_status_; struct zriver_output_status_v1 *output_status_;

View File

@ -1,7 +1,9 @@
#pragma once #pragma once
#include <sndio.h> #include <sndio.h>
#include <vector> #include <vector>
#include "ALabel.hpp" #include "ALabel.hpp"
#include "util/sleeper_thread.hpp" #include "util/sleeper_thread.hpp"
@ -9,13 +11,13 @@ namespace waybar::modules {
class Sndio : public ALabel { class Sndio : public ALabel {
public: public:
Sndio(const std::string&, const Json::Value&); Sndio(const std::string &, const Json::Value &);
~Sndio(); ~Sndio();
auto update() -> void; auto update() -> void;
auto set_desc(struct sioctl_desc *, unsigned int) -> void; auto set_desc(struct sioctl_desc *, unsigned int) -> void;
auto put_val(unsigned int, unsigned int) -> void; auto put_val(unsigned int, unsigned int) -> void;
bool handleScroll(GdkEventScroll *); bool handleScroll(GdkEventScroll *);
bool handleToggle(GdkEventButton* const&); bool handleToggle(GdkEventButton *const &);
private: private:
auto connect_to_sndio() -> void; auto connect_to_sndio() -> void;

View File

@ -4,7 +4,9 @@
#include <giomm.h> #include <giomm.h>
#include <glibmm/refptr.h> #include <glibmm/refptr.h>
#include <json/json.h> #include <json/json.h>
#include <tuple> #include <tuple>
#include "bar.hpp" #include "bar.hpp"
#include "modules/sni/item.hpp" #include "modules/sni/item.hpp"

View File

@ -1,6 +1,7 @@
#pragma once #pragma once
#include <fmt/format.h> #include <fmt/format.h>
#include "AModule.hpp" #include "AModule.hpp"
#include "bar.hpp" #include "bar.hpp"
#include "modules/sni/host.hpp" #include "modules/sni/host.hpp"

View File

@ -30,10 +30,10 @@ class Watcher {
typedef struct { typedef struct {
GfWatchType type; GfWatchType type;
Watcher * watcher; Watcher *watcher;
gchar * service; gchar *service;
gchar * bus_name; gchar *bus_name;
gchar * object_path; gchar *object_path;
guint watch_id; guint watch_id;
} GfWatch; } GfWatch;
@ -48,8 +48,8 @@ class Watcher {
void updateRegisteredItems(SnWatcher *obj); void updateRegisteredItems(SnWatcher *obj);
uint32_t bus_name_id_; uint32_t bus_name_id_;
GSList * hosts_ = nullptr; GSList *hosts_ = nullptr;
GSList * items_ = nullptr; GSList *items_ = nullptr;
SnWatcher *watcher_ = nullptr; SnWatcher *watcher_ = nullptr;
}; };

View File

@ -4,9 +4,11 @@
#include <sys/socket.h> #include <sys/socket.h>
#include <sys/un.h> #include <sys/un.h>
#include <unistd.h> #include <unistd.h>
#include <cstring> #include <cstring>
#include <memory> #include <memory>
#include <mutex> #include <mutex>
#include "ipc.hpp" #include "ipc.hpp"
#include "util/sleeper_thread.hpp" #include "util/sleeper_thread.hpp"

View File

@ -31,6 +31,6 @@ enum ipc_command_type {
IPC_EVENT_TICK = ((1 << 31) | 7), IPC_EVENT_TICK = ((1 << 31) | 7),
// sway-specific event types // sway-specific event types
IPC_EVENT_BAR_STATE_UPDATE = ((1<<31) | 20), IPC_EVENT_BAR_STATE_UPDATE = ((1 << 31) | 20),
IPC_EVENT_INPUT = ((1<<31) | 21), IPC_EVENT_INPUT = ((1 << 31) | 21),
}; };

View File

@ -21,11 +21,7 @@ class Language : public ALabel, public sigc::trackable {
auto update() -> void; auto update() -> void;
private: private:
enum class DispayedShortFlag { enum class DispayedShortFlag { None = 0, ShortName = 1, ShortDescription = 1 << 1 };
None = 0,
ShortName = 1,
ShortDescription = 1 << 1
};
struct Layout { struct Layout {
std::string full_name; std::string full_name;
@ -40,6 +36,7 @@ class Language : public ALabel, public sigc::trackable {
XKBContext(); XKBContext();
~XKBContext(); ~XKBContext();
auto next_layout() -> Layout*; auto next_layout() -> Layout*;
private: private:
rxkb_context* context_ = nullptr; rxkb_context* context_ = nullptr;
rxkb_layout* xkb_layout_ = nullptr; rxkb_layout* xkb_layout_ = nullptr;

View File

@ -1,6 +1,7 @@
#pragma once #pragma once
#include <fmt/format.h> #include <fmt/format.h>
#include "ALabel.hpp" #include "ALabel.hpp"
#include "bar.hpp" #include "bar.hpp"
#include "client.hpp" #include "client.hpp"

View File

@ -1,6 +1,7 @@
#pragma once #pragma once
#include <fmt/format.h> #include <fmt/format.h>
#include <tuple> #include <tuple>
#include "AIconLabel.hpp" #include "AIconLabel.hpp"

View File

@ -1,10 +1,11 @@
#pragma once #pragma once
#include <unordered_map>
#include <fmt/format.h> #include <fmt/format.h>
#include <gtkmm/button.h> #include <gtkmm/button.h>
#include <gtkmm/label.h> #include <gtkmm/label.h>
#include <unordered_map> #include <unordered_map>
#include "AModule.hpp" #include "AModule.hpp"
#include "bar.hpp" #include "bar.hpp"
#include "client.hpp" #include "client.hpp"

View File

@ -1,7 +1,9 @@
#pragma once #pragma once
#include <fmt/format.h> #include <fmt/format.h>
#include <fstream> #include <fstream>
#include "ALabel.hpp" #include "ALabel.hpp"
#include "util/sleeper_thread.hpp" #include "util/sleeper_thread.hpp"

View File

@ -1,40 +1,35 @@
#pragma once #pragma once
#include <gdk/gdk.h>
#include <glibmm/refptr.h>
#include <gtkmm/box.h>
#include <gtkmm/button.h>
#include <gtkmm/icontheme.h>
#include <gtkmm/image.h>
#include <gtkmm/label.h>
#include <wayland-client.h>
#include <map>
#include <memory>
#include <string>
#include <unordered_set>
#include <vector>
#include "AModule.hpp" #include "AModule.hpp"
#include "bar.hpp" #include "bar.hpp"
#include "client.hpp" #include "client.hpp"
#include "giomm/desktopappinfo.h" #include "giomm/desktopappinfo.h"
#include "util/json.hpp" #include "util/json.hpp"
#include <memory>
#include <string>
#include <vector>
#include <map>
#include <unordered_set>
#include <gdk/gdk.h>
#include <glibmm/refptr.h>
#include <gtkmm/box.h>
#include <gtkmm/button.h>
#include <gtkmm/image.h>
#include <gtkmm/label.h>
#include <gtkmm/icontheme.h>
#include <wayland-client.h>
#include "wlr-foreign-toplevel-management-unstable-v1-client-protocol.h" #include "wlr-foreign-toplevel-management-unstable-v1-client-protocol.h"
namespace waybar::modules::wlr { namespace waybar::modules::wlr {
class Taskbar; class Taskbar;
class Task class Task {
{
public: public:
Task(const waybar::Bar&, const Json::Value&, Taskbar*, Task(const waybar::Bar &, const Json::Value &, Taskbar *,
struct zwlr_foreign_toplevel_handle_v1 *, struct wl_seat*); struct zwlr_foreign_toplevel_handle_v1 *, struct wl_seat *);
~Task(); ~Task();
public: public:
@ -82,8 +77,9 @@ class Task
private: private:
std::string repr() const; std::string repr() const;
std::string state_string(bool = false) const; std::string state_string(bool = false) const;
void set_app_info_from_app_id_list(const std::string& app_id_list); void set_app_info_from_app_id_list(const std::string &app_id_list);
bool image_load_icon(Gtk::Image& image, const Glib::RefPtr<Gtk::IconTheme>& icon_theme, Glib::RefPtr<Gio::DesktopAppInfo> app_info, int size); bool image_load_icon(Gtk::Image &image, const Glib::RefPtr<Gtk::IconTheme> &icon_theme,
Glib::RefPtr<Gio::DesktopAppInfo> app_info, int size);
void hide_if_ignored(); void hide_if_ignored();
public: public:
@ -111,8 +107,8 @@ class Task
bool handle_clicked(GdkEventButton *); bool handle_clicked(GdkEventButton *);
public: public:
bool operator==(const Task&) const; bool operator==(const Task &) const;
bool operator!=(const Task&) const; bool operator!=(const Task &) const;
public: public:
void update(); void update();
@ -128,11 +124,9 @@ class Task
using TaskPtr = std::unique_ptr<Task>; using TaskPtr = std::unique_ptr<Task>;
class Taskbar : public waybar::AModule {
class Taskbar : public waybar::AModule
{
public: public:
Taskbar(const std::string&, const waybar::Bar&, const Json::Value&); Taskbar(const std::string &, const waybar::Bar &, const Json::Value &);
~Taskbar(); ~Taskbar();
void update(); void update();
@ -150,8 +144,8 @@ class Taskbar : public waybar::AModule
public: public:
/* Callbacks for global registration */ /* Callbacks for global registration */
void register_manager(struct wl_registry*, uint32_t name, uint32_t version); void register_manager(struct wl_registry *, uint32_t name, uint32_t version);
void register_seat(struct wl_registry*, uint32_t name, uint32_t version); void register_seat(struct wl_registry *, uint32_t name, uint32_t version);
/* Callbacks for the wlr protocol */ /* Callbacks for the wlr protocol */
void handle_toplevel_create(struct zwlr_foreign_toplevel_handle_v1 *); void handle_toplevel_create(struct zwlr_foreign_toplevel_handle_v1 *);
@ -166,9 +160,9 @@ class Taskbar : public waybar::AModule
bool show_output(struct wl_output *) const; bool show_output(struct wl_output *) const;
bool all_outputs() const; bool all_outputs() const;
const std::vector<Glib::RefPtr<Gtk::IconTheme>>& icon_themes() const; const std::vector<Glib::RefPtr<Gtk::IconTheme>> &icon_themes() const;
const std::unordered_set<std::string>& ignore_list() const; const std::unordered_set<std::string> &ignore_list() const;
const std::map<std::string, std::string>& app_ids_replace_map() const; const std::map<std::string, std::string> &app_ids_replace_map() const;
}; };
} /* namespace waybar::modules::wlr */ } /* namespace waybar::modules::wlr */

View File

@ -1,8 +1,10 @@
#include "ext-workspace-unstable-v1-client-protocol.h" #include "ext-workspace-unstable-v1-client-protocol.h"
namespace waybar::modules::wlr { namespace waybar::modules::wlr {
void add_registry_listener(void *data); void add_registry_listener(void *data);
void add_workspace_listener(zext_workspace_handle_v1 *workspace_handle, void *data); void add_workspace_listener(zext_workspace_handle_v1 *workspace_handle, void *data);
void add_workspace_group_listener(zext_workspace_group_handle_v1 *workspace_group_handle, void *data); void add_workspace_group_listener(zext_workspace_group_handle_v1 *workspace_group_handle,
zext_workspace_manager_v1* workspace_manager_bind(wl_registry *registry, uint32_t name, uint32_t version, void *data); void *data);
} zext_workspace_manager_v1 *workspace_manager_bind(wl_registry *registry, uint32_t name,
uint32_t version, void *data);
} // namespace waybar::modules::wlr

File diff suppressed because it is too large Load Diff

View File

@ -68,7 +68,7 @@ inline int close(FILE* fp, pid_t pid) {
inline FILE* open(const std::string& cmd, int& pid) { inline FILE* open(const std::string& cmd, int& pid) {
if (cmd == "") return nullptr; if (cmd == "") return nullptr;
int fd[2]; int fd[2];
if (pipe(fd) != 0){ if (pipe(fd) != 0) {
spdlog::error("Unable to pipe fd"); spdlog::error("Unable to pipe fd");
return nullptr; return nullptr;
} }

View File

@ -5,23 +5,22 @@
class pow_format { class pow_format {
public: public:
pow_format(long long val, std::string&& unit, bool binary = false): pow_format(long long val, std::string&& unit, bool binary = false)
val_(val), unit_(unit), binary_(binary) { }; : val_(val), unit_(unit), binary_(binary){};
long long val_; long long val_;
std::string unit_; std::string unit_;
bool binary_; bool binary_;
}; };
namespace fmt { namespace fmt {
template <> template <>
struct formatter<pow_format> { struct formatter<pow_format> {
char spec = 0; char spec = 0;
int width = 0; int width = 0;
template <typename ParseContext> template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) -> decltype (ctx.begin()) { constexpr auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
auto it = ctx.begin(), end = ctx.end(); auto it = ctx.begin(), end = ctx.end();
if (it != end && *it == ':') ++it; if (it != end && *it == ':') ++it;
if (it && (*it == '>' || *it == '<' || *it == '=')) { if (it && (*it == '>' || *it == '<' || *it == '=')) {
@ -45,15 +44,15 @@ namespace fmt {
return it; return it;
} }
template<class FormatContext> template <class FormatContext>
auto format(const pow_format& s, FormatContext &ctx) -> decltype (ctx.out()) { auto format(const pow_format& s, FormatContext& ctx) -> decltype(ctx.out()) {
const char* units[] = { "", "k", "M", "G", "T", "P", nullptr}; const char* units[] = {"", "k", "M", "G", "T", "P", nullptr};
auto base = s.binary_ ? 1024ull : 1000ll; auto base = s.binary_ ? 1024ull : 1000ll;
auto fraction = (double) s.val_; auto fraction = (double)s.val_;
int pow; int pow;
for (pow = 0; units[pow+1] != nullptr && fraction / base >= 1; ++pow) { for (pow = 0; units[pow + 1] != nullptr && fraction / base >= 1; ++pow) {
fraction /= base; fraction /= base;
} }
@ -62,7 +61,7 @@ namespace fmt {
+ s.binary_ // for the 'i' in GiB. + s.binary_ // for the 'i' in GiB.
+ s.unit_.length(); + s.unit_.length();
const char * format; const char* format;
std::string string; std::string string;
switch (spec) { switch (spec) {
case '>': case '>':
@ -77,23 +76,22 @@ namespace fmt {
format = "{coefficient:.3g}{prefix}{unit}"; format = "{coefficient:.3g}{prefix}{unit}";
break; break;
} }
return format_to(ctx.out(), format return format_to(
, fmt::arg("coefficient", fraction) ctx.out(), format, fmt::arg("coefficient", fraction),
, fmt::arg("prefix", std::string() + units[pow] + ((s.binary_ && pow) ? "i" : "")) fmt::arg("prefix", std::string() + units[pow] + ((s.binary_ && pow) ? "i" : "")),
, fmt::arg("unit", s.unit_) fmt::arg("unit", s.unit_),
, fmt::arg("padding", pow ? "" : s.binary_ ? " " : " ") fmt::arg("padding", pow ? ""
); : s.binary_ ? " "
: " "));
} }
}; };
// Glib ustirng support
// Glib ustirng support template <>
template <> struct formatter<Glib::ustring> : formatter<std::string> {
struct formatter<Glib::ustring> : formatter<std::string> {
template <typename FormatContext> template <typename FormatContext>
auto format(const Glib::ustring& value, FormatContext& ctx) { auto format(const Glib::ustring& value, FormatContext& ctx) {
return formatter<std::string>::format(value, ctx); return formatter<std::string>::format(value, ctx);
} }
}; };
} } // namespace fmt

View File

@ -17,7 +17,8 @@ namespace waybar::util {
*/ */
class CancellationGuard { class CancellationGuard {
int oldstate; int oldstate;
public:
public:
CancellationGuard() { pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate); } CancellationGuard() { pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate); }
~CancellationGuard() { pthread_setcancelstate(oldstate, &oldstate); } ~CancellationGuard() { pthread_setcancelstate(oldstate, &oldstate); }
}; };

View File

@ -1,5 +1,7 @@
#include "ALabel.hpp" #include "ALabel.hpp"
#include <fmt/format.h> #include <fmt/format.h>
#include <util/command.hpp> #include <util/command.hpp>
namespace waybar { namespace waybar {
@ -46,15 +48,10 @@ ALabel::ALabel(const Json::Value& config, const std::string& name, const std::st
} else { } else {
label_.set_xalign(align); label_.set_xalign(align);
} }
} }
} }
auto ALabel::update() -> void { auto ALabel::update() -> void { AModule::update(); }
AModule::update();
}
std::string ALabel::getIcon(uint16_t percentage, const std::string& alt, uint16_t max) { std::string ALabel::getIcon(uint16_t percentage, const std::string& alt, uint16_t max) {
auto format_icons = config_["format-icons"]; auto format_icons = config_["format-icons"];
@ -78,7 +75,8 @@ std::string ALabel::getIcon(uint16_t percentage, const std::string& alt, uint16_
return ""; return "";
} }
std::string ALabel::getIcon(uint16_t percentage, const std::vector<std::string>& alts, uint16_t max) { std::string ALabel::getIcon(uint16_t percentage, const std::vector<std::string>& alts,
uint16_t max) {
auto format_icons = config_["format-icons"]; auto format_icons = config_["format-icons"];
if (format_icons.isObject()) { if (format_icons.isObject()) {
std::string _alt = "default"; std::string _alt = "default";

View File

@ -1,24 +1,28 @@
#include "AModule.hpp" #include "AModule.hpp"
#include <fmt/format.h> #include <fmt/format.h>
#include <util/command.hpp> #include <util/command.hpp>
namespace waybar { namespace waybar {
AModule::AModule(const Json::Value& config, const std::string& name, const std::string& id, AModule::AModule(const Json::Value& config, const std::string& name, const std::string& id,
bool enable_click, bool enable_scroll) bool enable_click, bool enable_scroll)
: name_(std::move(name)), config_(std::move(config)) : name_(std::move(name)),
, distance_scrolled_y_(0.0) config_(std::move(config)),
, distance_scrolled_x_(0.0) { distance_scrolled_y_(0.0),
distance_scrolled_x_(0.0) {
// configure events' user commands // configure events' user commands
if (enable_click) { if (enable_click) {
event_box_.add_events(Gdk::BUTTON_PRESS_MASK); event_box_.add_events(Gdk::BUTTON_PRESS_MASK);
event_box_.signal_button_press_event().connect(sigc::mem_fun(*this, &AModule::handleToggle)); event_box_.signal_button_press_event().connect(sigc::mem_fun(*this, &AModule::handleToggle));
} else { } else {
std::map<std::pair<uint, GdkEventType>, std::string>::const_iterator it{eventMap_.cbegin()}; std::map<std::pair<uint, GdkEventType>, std::string>::const_iterator it{eventMap_.cbegin()};
while(it != eventMap_.cend()) { while (it != eventMap_.cend()) {
if (config_[it->second].isString()) { if (config_[it->second].isString()) {
event_box_.add_events(Gdk::BUTTON_PRESS_MASK); event_box_.add_events(Gdk::BUTTON_PRESS_MASK);
event_box_.signal_button_press_event().connect(sigc::mem_fun(*this, &AModule::handleToggle)); event_box_.signal_button_press_event().connect(
sigc::mem_fun(*this, &AModule::handleToggle));
break; break;
} }
++it; ++it;
@ -46,12 +50,15 @@ auto AModule::update() -> void {
} }
bool AModule::handleToggle(GdkEventButton* const& e) { bool AModule::handleToggle(GdkEventButton* const& e) {
const std::map<std::pair<uint, GdkEventType>, std::string>::const_iterator& rec{eventMap_.find(std::pair(e->button, e->type))}; const std::map<std::pair<uint, GdkEventType>, std::string>::const_iterator& rec{
std::string format{ (rec != eventMap_.cend()) ? rec->second : std::string{""}}; eventMap_.find(std::pair(e->button, e->type))};
std::string format{(rec != eventMap_.cend()) ? rec->second : std::string{""}};
if (!format.empty()) { if (!format.empty()) {
if (config_[format].isString()) format = config_[format].asString(); if (config_[format].isString())
else format.clear(); format = config_[format].asString();
else
format.clear();
} }
if (!format.empty()) { if (!format.empty()) {
@ -62,11 +69,15 @@ bool AModule::handleToggle(GdkEventButton* const& e) {
} }
AModule::SCROLL_DIR AModule::getScrollDir(GdkEventScroll* e) { AModule::SCROLL_DIR AModule::getScrollDir(GdkEventScroll* e) {
switch (e -> direction) { switch (e->direction) {
case GDK_SCROLL_UP: return SCROLL_DIR::UP; case GDK_SCROLL_UP:
case GDK_SCROLL_DOWN: return SCROLL_DIR::DOWN; return SCROLL_DIR::UP;
case GDK_SCROLL_LEFT: return SCROLL_DIR::LEFT; case GDK_SCROLL_DOWN:
case GDK_SCROLL_RIGHT: return SCROLL_DIR::RIGHT; return SCROLL_DIR::DOWN;
case GDK_SCROLL_LEFT:
return SCROLL_DIR::LEFT;
case GDK_SCROLL_RIGHT:
return SCROLL_DIR::RIGHT;
case GDK_SCROLL_SMOOTH: { case GDK_SCROLL_SMOOTH: {
SCROLL_DIR dir{SCROLL_DIR::NONE}; SCROLL_DIR dir{SCROLL_DIR::NONE};
@ -104,7 +115,8 @@ AModule::SCROLL_DIR AModule::getScrollDir(GdkEventScroll* e) {
return dir; return dir;
} }
// Silence -Wreturn-type: // Silence -Wreturn-type:
default: return SCROLL_DIR::NONE; default:
return SCROLL_DIR::NONE;
} }
} }

View File

@ -170,10 +170,8 @@ struct GLSSurfaceImpl : public BarSurface, public sigc::trackable {
vertical_ = true; vertical_ = true;
unanchored = GTK_LAYER_SHELL_EDGE_LEFT; unanchored = GTK_LAYER_SHELL_EDGE_LEFT;
} }
for (auto edge : {GTK_LAYER_SHELL_EDGE_LEFT, for (auto edge : {GTK_LAYER_SHELL_EDGE_LEFT, GTK_LAYER_SHELL_EDGE_RIGHT,
GTK_LAYER_SHELL_EDGE_RIGHT, GTK_LAYER_SHELL_EDGE_TOP, GTK_LAYER_SHELL_EDGE_BOTTOM}) {
GTK_LAYER_SHELL_EDGE_TOP,
GTK_LAYER_SHELL_EDGE_BOTTOM}) {
gtk_layer_set_anchor(window_.gobj(), edge, unanchored != edge); gtk_layer_set_anchor(window_.gobj(), edge, unanchored != edge);
} }
} }
@ -276,8 +274,8 @@ struct RawSurfaceImpl : public BarSurface, public sigc::trackable {
margins_ = margins; margins_ = margins;
// updating already mapped window // updating already mapped window
if (layer_surface_) { if (layer_surface_) {
zwlr_layer_surface_v1_set_margin( zwlr_layer_surface_v1_set_margin(layer_surface_.get(), margins_.top, margins_.right,
layer_surface_.get(), margins_.top, margins_.right, margins_.bottom, margins_.left); margins_.bottom, margins_.left);
} }
} }
@ -365,14 +363,14 @@ struct RawSurfaceImpl : public BarSurface, public sigc::trackable {
auto gdk_window = window_.get_window()->gobj(); auto gdk_window = window_.get_window()->gobj();
surface_ = gdk_wayland_window_get_wl_surface(gdk_window); surface_ = gdk_wayland_window_get_wl_surface(gdk_window);
layer_surface_.reset(zwlr_layer_shell_v1_get_layer_surface( layer_surface_.reset(zwlr_layer_shell_v1_get_layer_surface(client->layer_shell, surface_,
client->layer_shell, surface_, output_, layer_, "waybar")); output_, layer_, "waybar"));
zwlr_layer_surface_v1_add_listener(layer_surface_.get(), &layer_surface_listener, this); zwlr_layer_surface_v1_add_listener(layer_surface_.get(), &layer_surface_listener, this);
zwlr_layer_surface_v1_set_keyboard_interactivity(layer_surface_.get(), false); zwlr_layer_surface_v1_set_keyboard_interactivity(layer_surface_.get(), false);
zwlr_layer_surface_v1_set_anchor(layer_surface_.get(), anchor_); zwlr_layer_surface_v1_set_anchor(layer_surface_.get(), anchor_);
zwlr_layer_surface_v1_set_margin( zwlr_layer_surface_v1_set_margin(layer_surface_.get(), margins_.top, margins_.right,
layer_surface_.get(), margins_.top, margins_.right, margins_.bottom, margins_.left); margins_.bottom, margins_.left);
setSurfaceSize(width_, height_); setSurfaceSize(width_, height_);
setExclusiveZone(exclusive_zone_); setExclusiveZone(exclusive_zone_);
@ -453,10 +451,8 @@ struct RawSurfaceImpl : public BarSurface, public sigc::trackable {
o->window_.set_size_request(o->width_, o->height_); o->window_.set_size_request(o->width_, o->height_);
o->window_.resize(o->width_, o->height_); o->window_.resize(o->width_, o->height_);
o->setExclusiveZone(o->exclusive_zone_); o->setExclusiveZone(o->exclusive_zone_);
spdlog::info(BAR_SIZE_MSG, spdlog::info(BAR_SIZE_MSG, o->width_ == 1 ? "auto" : std::to_string(o->width_),
o->width_ == 1 ? "auto" : std::to_string(o->width_), o->height_ == 1 ? "auto" : std::to_string(o->height_), o->output_name_);
o->height_ == 1 ? "auto" : std::to_string(o->height_),
o->output_name_);
o->commit(); o->commit();
} }
zwlr_layer_surface_v1_ack_configure(surface, serial); zwlr_layer_surface_v1_ack_configure(surface, serial);
@ -723,7 +719,8 @@ void waybar::Bar::handleSignal(int signal) {
} }
} }
void waybar::Bar::getModules(const Factory& factory, const std::string& pos, Gtk::Box* group = nullptr) { void waybar::Bar::getModules(const Factory& factory, const std::string& pos,
Gtk::Box* group = nullptr) {
auto module_list = group ? config[pos]["modules"] : config[pos]; auto module_list = group ? config[pos]["modules"] : config[pos];
if (module_list.isArray()) { if (module_list.isArray()) {
for (const auto& name : module_list) { for (const auto& name : module_list) {

View File

@ -32,7 +32,7 @@ void waybar::Client::handleGlobal(void *data, struct wl_registry *registry, uint
} }
} }
void waybar::Client::handleGlobalRemove(void * data, struct wl_registry * /*registry*/, void waybar::Client::handleGlobalRemove(void *data, struct wl_registry * /*registry*/,
uint32_t name) { uint32_t name) {
// Nothing here // Nothing here
} }
@ -52,8 +52,8 @@ void waybar::Client::handleOutput(struct waybar_output &output) {
} }
struct waybar::waybar_output &waybar::Client::getOutput(void *addr) { struct waybar::waybar_output &waybar::Client::getOutput(void *addr) {
auto it = std::find_if( auto it = std::find_if(outputs_.begin(), outputs_.end(),
outputs_.begin(), outputs_.end(), [&addr](const auto &output) { return &output == addr; }); [&addr](const auto &output) { return &output == addr; });
if (it == outputs_.end()) { if (it == outputs_.end()) {
throw std::runtime_error("Unable to find valid output"); throw std::runtime_error("Unable to find valid output");
} }
@ -93,7 +93,7 @@ void waybar::Client::handleOutputDone(void *data, struct zxdg_output_v1 * /*xdg_
} }
} }
void waybar::Client::handleOutputName(void * data, struct zxdg_output_v1 * /*xdg_output*/, void waybar::Client::handleOutputName(void *data, struct zxdg_output_v1 * /*xdg_output*/,
const char *name) { const char *name) {
auto client = waybar::Client::inst(); auto client = waybar::Client::inst();
try { try {
@ -108,7 +108,7 @@ void waybar::Client::handleOutputDescription(void *data, struct zxdg_output_v1 *
const char *description) { const char *description) {
auto client = waybar::Client::inst(); auto client = waybar::Client::inst();
try { try {
auto & output = client->getOutput(data); auto &output = client->getOutput(data);
const char *open_paren = strrchr(description, '('); const char *open_paren = strrchr(description, '(');
// Description format: "identifier (name)" // Description format: "identifier (name)"
@ -169,8 +169,8 @@ auto waybar::Client::setupCss(const std::string &css_file) -> void {
throw std::runtime_error("Can't open style file"); throw std::runtime_error("Can't open style file");
} }
// there's always only one screen // there's always only one screen
style_context_->add_provider_for_screen( style_context_->add_provider_for_screen(Gdk::Screen::get_default(), css_provider_,
Gdk::Screen::get_default(), css_provider_, GTK_STYLE_PROVIDER_PRIORITY_USER); GTK_STYLE_PROVIDER_PRIORITY_USER);
} }
void waybar::Client::bindInterfaces() { void waybar::Client::bindInterfaces() {
@ -224,8 +224,8 @@ int waybar::Client::main(int argc, char *argv[]) {
if (!log_level.empty()) { if (!log_level.empty()) {
spdlog::set_level(spdlog::level::from_str(log_level)); spdlog::set_level(spdlog::level::from_str(log_level));
} }
gtk_app = Gtk::Application::create( gtk_app = Gtk::Application::create(argc, argv, "fr.arouillard.waybar",
argc, argv, "fr.arouillard.waybar", Gio::APPLICATION_HANDLES_COMMAND_LINE); Gio::APPLICATION_HANDLES_COMMAND_LINE);
gdk_display = Gdk::Display::get_default(); gdk_display = Gdk::Display::get_default();
if (!gdk_display) { if (!gdk_display) {
throw std::runtime_error("Can't find display"); throw std::runtime_error("Can't find display");
@ -244,6 +244,4 @@ int waybar::Client::main(int argc, char *argv[]) {
return 0; return 0;
} }
void waybar::Client::reset() { void waybar::Client::reset() { gtk_app->quit(); }
gtk_app->quit();
}

View File

@ -13,12 +13,8 @@
namespace waybar { namespace waybar {
const std::vector<std::string> Config::CONFIG_DIRS = { const std::vector<std::string> Config::CONFIG_DIRS = {
"$XDG_CONFIG_HOME/waybar/", "$XDG_CONFIG_HOME/waybar/", "$HOME/.config/waybar/", "$HOME/waybar/",
"$HOME/.config/waybar/", "/etc/xdg/waybar/", SYSCONFDIR "/xdg/waybar/", "./resources/",
"$HOME/waybar/",
"/etc/xdg/waybar/",
SYSCONFDIR "/xdg/waybar/",
"./resources/",
}; };
std::optional<std::string> tryExpandPath(const std::string &path) { std::optional<std::string> tryExpandPath(const std::string &path) {

View File

@ -109,11 +109,11 @@ waybar::AModule* waybar::Factory::makeModule(const std::string& name) const {
return new waybar::modules::Temperature(id, config_[name]); return new waybar::modules::Temperature(id, config_[name]);
} }
#if defined(__linux__) #if defined(__linux__)
# ifdef WANT_RFKILL #ifdef WANT_RFKILL
if (ref == "bluetooth") { if (ref == "bluetooth") {
return new waybar::modules::Bluetooth(id, config_[name]); return new waybar::modules::Bluetooth(id, config_[name]);
} }
# endif #endif
#endif #endif
if (ref.compare(0, 7, "custom/") == 0 && ref.size() > 7) { if (ref.compare(0, 7, "custom/") == 0 && ref.size() > 7) {
return new waybar::modules::Custom(ref.substr(7), id, config_[name]); return new waybar::modules::Custom(ref.substr(7), id, config_[name]);

View File

@ -1,14 +1,14 @@
#include "group.hpp" #include "group.hpp"
#include <fmt/format.h> #include <fmt/format.h>
#include <util/command.hpp> #include <util/command.hpp>
namespace waybar { namespace waybar {
Group::Group(const std::string& name, const Bar& bar, const Json::Value& config) Group::Group(const std::string& name, const Bar& bar, const Json::Value& config)
: AModule(config, name, "", false, false), : AModule(config, name, "", false, false),
box{bar.vertical ? Gtk::ORIENTATION_HORIZONTAL : Gtk::ORIENTATION_VERTICAL, 0} box{bar.vertical ? Gtk::ORIENTATION_HORIZONTAL : Gtk::ORIENTATION_VERTICAL, 0} {}
{
}
auto Group::update() -> void { auto Group::update() -> void {
// noop // noop

View File

@ -1,9 +1,11 @@
#include <spdlog/spdlog.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <csignal> #include <csignal>
#include <list> #include <list>
#include <mutex> #include <mutex>
#include <sys/types.h>
#include <sys/wait.h>
#include <spdlog/spdlog.h>
#include "client.hpp" #include "client.hpp"
std::mutex reap_mtx; std::mutex reap_mtx;
@ -38,8 +40,7 @@ void* signalThread(void* args) {
} }
break; break;
default: default:
spdlog::debug("Received signal with number {}, but not handling", spdlog::debug("Received signal with number {}, but not handling", signum);
signum);
break; break;
} }
} }

View File

@ -93,8 +93,8 @@ waybar::modules::Backlight::Backlight(const std::string &id, const Json::Value &
{ {
std::unique_ptr<udev, UdevDeleter> udev_check{udev_new()}; std::unique_ptr<udev, UdevDeleter> udev_check{udev_new()};
check_nn(udev_check.get(), "Udev check new failed"); check_nn(udev_check.get(), "Udev check new failed");
enumerate_devices( enumerate_devices(devices_.begin(), devices_.end(), std::back_inserter(devices_),
devices_.begin(), devices_.end(), std::back_inserter(devices_), udev_check.get()); udev_check.get());
if (devices_.empty()) { if (devices_.empty()) {
throw std::runtime_error("No backlight found"); throw std::runtime_error("No backlight found");
} }
@ -108,8 +108,7 @@ waybar::modules::Backlight::Backlight(const std::string &id, const Json::Value &
std::unique_ptr<udev_monitor, UdevMonitorDeleter> mon{ std::unique_ptr<udev_monitor, UdevMonitorDeleter> mon{
udev_monitor_new_from_netlink(udev.get(), "udev")}; udev_monitor_new_from_netlink(udev.get(), "udev")};
check_nn(mon.get(), "udev monitor new failed"); check_nn(mon.get(), "udev monitor new failed");
check_gte(udev_monitor_filter_add_match_subsystem_devtype(mon.get(), "backlight", nullptr), check_gte(udev_monitor_filter_add_match_subsystem_devtype(mon.get(), "backlight", nullptr), 0,
0,
"udev failed to add monitor filter: "); "udev failed to add monitor filter: ");
udev_monitor_enable_receiving(mon.get()); udev_monitor_enable_receiving(mon.get());
@ -126,8 +125,8 @@ waybar::modules::Backlight::Backlight(const std::string &id, const Json::Value &
epoll_event events[EPOLL_MAX_EVENTS]; epoll_event events[EPOLL_MAX_EVENTS];
while (udev_thread_.isRunning()) { while (udev_thread_.isRunning()) {
const int event_count = epoll_wait( const int event_count = epoll_wait(epoll_fd.get(), events, EPOLL_MAX_EVENTS,
epoll_fd.get(), events, EPOLL_MAX_EVENTS, std::chrono::milliseconds{interval_}.count()); std::chrono::milliseconds{interval_}.count());
if (!udev_thread_.isRunning()) { if (!udev_thread_.isRunning()) {
break; break;
} }
@ -173,9 +172,10 @@ auto waybar::modules::Backlight::update() -> void {
return; return;
} }
const uint8_t percent = best->get_max() == 0 ? 100 : round(best->get_actual() * 100.0f / best->get_max()); const uint8_t percent =
label_.set_markup(fmt::format( best->get_max() == 0 ? 100 : round(best->get_actual() * 100.0f / best->get_max());
format_, fmt::arg("percent", std::to_string(percent)), fmt::arg("icon", getIcon(percent)))); label_.set_markup(fmt::format(format_, fmt::arg("percent", std::to_string(percent)),
fmt::arg("icon", getIcon(percent))));
getState(percent); getState(percent);
} else { } else {
if (!previous_best_.has_value()) { if (!previous_best_.has_value()) {
@ -241,7 +241,7 @@ void waybar::modules::Backlight::enumerate_devices(ForwardIt first, ForwardIt la
udev_list_entry *enum_devices = udev_enumerate_get_list_entry(enumerate.get()); udev_list_entry *enum_devices = udev_enumerate_get_list_entry(enumerate.get());
udev_list_entry *dev_list_entry; udev_list_entry *dev_list_entry;
udev_list_entry_foreach(dev_list_entry, enum_devices) { udev_list_entry_foreach(dev_list_entry, enum_devices) {
const char * path = udev_list_entry_get_name(dev_list_entry); const char *path = udev_list_entry_get_name(dev_list_entry);
std::unique_ptr<udev_device, UdevDeviceDeleter> dev{udev_device_new_from_syspath(udev, path)}; std::unique_ptr<udev_device, UdevDeviceDeleter> dev{udev_device_new_from_syspath(udev, path)};
check_nn(dev.get(), "dev new failed"); check_nn(dev.get(), "dev new failed");
upsert_device(first, last, inserter, dev.get()); upsert_device(first, last, inserter, dev.get());

View File

@ -94,7 +94,7 @@ void waybar::modules::Battery::refreshBatteries() {
std::string type; std::string type;
std::ifstream(node.path() / "type") >> type; std::ifstream(node.path() / "type") >> type;
if (!type.compare("Battery")){ if (!type.compare("Battery")) {
check_map[node.path()] = true; check_map[node.path()] = true;
auto search = batteries_.find(node.path()); auto search = batteries_.find(node.path());
if (search == batteries_.end()) { if (search == batteries_.end()) {
@ -139,11 +139,16 @@ void waybar::modules::Battery::refreshBatteries() {
// Unknown > Full > Not charging > Discharging > Charging // Unknown > Full > Not charging > Discharging > Charging
static bool status_gt(const std::string& a, const std::string& b) { static bool status_gt(const std::string& a, const std::string& b) {
if (a == b) return false; if (a == b)
else if (a == "Unknown") return true; return false;
else if (a == "Full" && b != "Unknown") return true; else if (a == "Unknown")
else if (a == "Not charging" && b != "Unknown" && b != "Full") return true; return true;
else if (a == "Discharging" && b != "Unknown" && b != "Full" && b != "Not charging") return true; else if (a == "Full" && b != "Unknown")
return true;
else if (a == "Not charging" && b != "Unknown" && b != "Full")
return true;
else if (a == "Discharging" && b != "Unknown" && b != "Full" && b != "Not charging")
return true;
return false; return false;
} }
@ -241,14 +246,14 @@ const std::tuple<uint8_t, float, std::string, float> waybar::modules::Battery::g
} }
} }
float capacity{0.0f}; float capacity{0.0f};
if(total_energy_full > 0.0f) { if (total_energy_full > 0.0f) {
capacity = ((float)total_energy * 100.0f / (float) total_energy_full); capacity = ((float)total_energy * 100.0f / (float)total_energy_full);
} else { } else {
capacity = (float)total_capacity; capacity = (float)total_capacity;
} }
// Handle design-capacity // Handle design-capacity
if (config_["design-capacity"].isBool() ? config_["design-capacity"].asBool() : false) { if (config_["design-capacity"].isBool() ? config_["design-capacity"].asBool() : false) {
capacity = ((float)total_energy * 100.0f / (float) total_energy_full_design); capacity = ((float)total_energy * 100.0f / (float)total_energy_full_design);
} }
// Handle full-at // Handle full-at
if (config_["full-at"].isUInt()) { if (config_["full-at"].isUInt()) {
@ -317,9 +322,8 @@ auto waybar::modules::Battery::update() -> void {
} }
auto status_pretty = status; auto status_pretty = status;
// Transform to lowercase and replace space with dash // Transform to lowercase and replace space with dash
std::transform(status.begin(), status.end(), status.begin(), [](char ch) { std::transform(status.begin(), status.end(), status.begin(),
return ch == ' ' ? '-' : std::tolower(ch); [](char ch) { return ch == ' ' ? '-' : std::tolower(ch); });
});
auto format = format_; auto format = format_;
auto state = getState(capacity, true); auto state = getState(capacity, true);
auto time_remaining_formatted = formatTimeRemaining(time_remaining); auto time_remaining_formatted = formatTimeRemaining(time_remaining);
@ -341,8 +345,7 @@ auto waybar::modules::Battery::update() -> void {
} else if (config_["tooltip-format"].isString()) { } else if (config_["tooltip-format"].isString()) {
tooltip_format = config_["tooltip-format"].asString(); tooltip_format = config_["tooltip-format"].asString();
} }
label_.set_tooltip_text(fmt::format(tooltip_format, label_.set_tooltip_text(fmt::format(tooltip_format, fmt::arg("timeTo", tooltip_text_default),
fmt::arg("timeTo", tooltip_text_default),
fmt::arg("capacity", capacity), fmt::arg("capacity", capacity),
fmt::arg("time", time_remaining_formatted))); fmt::arg("time", time_remaining_formatted)));
} }
@ -363,9 +366,7 @@ auto waybar::modules::Battery::update() -> void {
} else { } else {
event_box_.show(); event_box_.show();
auto icons = std::vector<std::string>{status + "-" + state, status, state}; auto icons = std::vector<std::string>{status + "-" + state, status, state};
label_.set_markup(fmt::format(format, label_.set_markup(fmt::format(format, fmt::arg("capacity", capacity), fmt::arg("power", power),
fmt::arg("capacity", capacity),
fmt::arg("power", power),
fmt::arg("icon", getIcon(capacity, icons)), fmt::arg("icon", getIcon(capacity, icons)),
fmt::arg("time", time_remaining_formatted))); fmt::arg("time", time_remaining_formatted)));
} }

View File

@ -24,43 +24,37 @@ waybar::modules::Clock::Clock(const std::string& id, const Json::Value& config)
: ALabel(config, "clock", id, "{:%H:%M}", 60, false, false, true), : ALabel(config, "clock", id, "{:%H:%M}", 60, false, false, true),
current_time_zone_idx_(0), current_time_zone_idx_(0),
is_calendar_in_tooltip_(false), is_calendar_in_tooltip_(false),
is_timezoned_list_in_tooltip_(false) is_timezoned_list_in_tooltip_(false) {
{
if (config_["timezones"].isArray() && !config_["timezones"].empty()) { if (config_["timezones"].isArray() && !config_["timezones"].empty()) {
for (const auto& zone_name: config_["timezones"]) { for (const auto& zone_name : config_["timezones"]) {
if (!zone_name.isString() || zone_name.asString().empty()) { if (!zone_name.isString() || zone_name.asString().empty()) {
time_zones_.push_back(nullptr); time_zones_.push_back(nullptr);
continue; continue;
} }
time_zones_.push_back( time_zones_.push_back(date::locate_zone(zone_name.asString()));
date::locate_zone(
zone_name.asString()
)
);
} }
} else if (config_["timezone"].isString() && !config_["timezone"].asString().empty()) { } else if (config_["timezone"].isString() && !config_["timezone"].asString().empty()) {
time_zones_.push_back( time_zones_.push_back(date::locate_zone(config_["timezone"].asString()));
date::locate_zone(
config_["timezone"].asString()
)
);
} }
// If all timezones are parsed and no one is good, add nullptr to the timezones vector, to mark that local time should be shown. // If all timezones are parsed and no one is good, add nullptr to the timezones vector, to mark
// that local time should be shown.
if (!time_zones_.size()) { if (!time_zones_.size()) {
time_zones_.push_back(nullptr); time_zones_.push_back(nullptr);
} }
if (!is_timezone_fixed()) { if (!is_timezone_fixed()) {
spdlog::warn("As using a timezone, some format args may be missing as the date library haven't got a release since 2018."); spdlog::warn(
"As using a timezone, some format args may be missing as the date library haven't got a "
"release since 2018.");
} }
// Check if a particular placeholder is present in the tooltip format, to know what to calculate on update. // Check if a particular placeholder is present in the tooltip format, to know what to calculate
// on update.
if (config_["tooltip-format"].isString()) { if (config_["tooltip-format"].isString()) {
std::string trimmed_format = config_["tooltip-format"].asString(); std::string trimmed_format = config_["tooltip-format"].asString();
trimmed_format.erase(std::remove_if(trimmed_format.begin(), trimmed_format.erase(std::remove_if(trimmed_format.begin(), trimmed_format.end(),
trimmed_format.end(), [](unsigned char x) { return std::isspace(x); }),
[](unsigned char x){return std::isspace(x);}),
trimmed_format.end()); trimmed_format.end());
if (trimmed_format.find("{" + kCalendarPlaceholder + "}") != std::string::npos) { if (trimmed_format.find("{" + kCalendarPlaceholder + "}") != std::string::npos) {
is_calendar_in_tooltip_ = true; is_calendar_in_tooltip_ = true;
@ -86,7 +80,8 @@ waybar::modules::Clock::Clock(const std::string& id, const Json::Value& config)
} }
const date::time_zone* waybar::modules::Clock::current_timezone() { const date::time_zone* waybar::modules::Clock::current_timezone() {
return time_zones_[current_time_zone_idx_] ? time_zones_[current_time_zone_idx_] : date::current_zone(); return time_zones_[current_time_zone_idx_] ? time_zones_[current_time_zone_idx_]
: date::current_zone();
} }
bool waybar::modules::Clock::is_timezone_fixed() { bool waybar::modules::Clock::is_timezone_fixed() {
@ -120,7 +115,9 @@ auto waybar::modules::Clock::update() -> void {
timezoned_time_lines = timezones_text(&now); timezoned_time_lines = timezones_text(&now);
} }
auto tooltip_format = config_["tooltip-format"].asString(); auto tooltip_format = config_["tooltip-format"].asString();
text = fmt::format(tooltip_format, wtime, fmt::arg(kCalendarPlaceholder.c_str(), calendar_lines), fmt::arg(KTimezonedTimeListPlaceholder.c_str(), timezoned_time_lines)); text =
fmt::format(tooltip_format, wtime, fmt::arg(kCalendarPlaceholder.c_str(), calendar_lines),
fmt::arg(KTimezonedTimeListPlaceholder.c_str(), timezoned_time_lines));
label_.set_tooltip_markup(text); label_.set_tooltip_markup(text);
} }
} }
@ -129,7 +126,7 @@ auto waybar::modules::Clock::update() -> void {
ALabel::update(); ALabel::update();
} }
bool waybar::modules::Clock::handleScroll(GdkEventScroll *e) { bool waybar::modules::Clock::handleScroll(GdkEventScroll* e) {
// defer to user commands if set // defer to user commands if set
if (config_["on-scroll-up"].isString() || config_["on-scroll-down"].isString()) { if (config_["on-scroll-up"].isString() || config_["on-scroll-down"].isString()) {
return AModule::handleScroll(e); return AModule::handleScroll(e);
@ -148,7 +145,8 @@ bool waybar::modules::Clock::handleScroll(GdkEventScroll *e) {
size_t new_idx = current_time_zone_idx_ + 1; size_t new_idx = current_time_zone_idx_ + 1;
current_time_zone_idx_ = new_idx == nr_zones ? 0 : new_idx; current_time_zone_idx_ = new_idx == nr_zones ? 0 : new_idx;
} else { } else {
current_time_zone_idx_ = current_time_zone_idx_ == 0 ? nr_zones - 1 : current_time_zone_idx_ - 1; current_time_zone_idx_ =
current_time_zone_idx_ == 0 ? nr_zones - 1 : current_time_zone_idx_ - 1;
} }
update(); update();
@ -209,7 +207,7 @@ auto waybar::modules::Clock::weekdays_header(const date::weekday& first_dow, std
auto clen = ustring_clen(wd_ustring); auto clen = ustring_clen(wd_ustring);
auto wd_len = wd_ustring.length(); auto wd_len = wd_ustring.length();
while (clen > 2) { while (clen > 2) {
wd_ustring = wd_ustring.substr(0, wd_len-1); wd_ustring = wd_ustring.substr(0, wd_len - 1);
wd_len--; wd_len--;
clen = ustring_clen(wd_ustring); clen = ustring_clen(wd_ustring);
} }
@ -219,7 +217,8 @@ auto waybar::modules::Clock::weekdays_header(const date::weekday& first_dow, std
os << "\n"; os << "\n";
} }
auto waybar::modules::Clock::timezones_text(std::chrono::system_clock::time_point *now) -> std::string { auto waybar::modules::Clock::timezones_text(std::chrono::system_clock::time_point* now)
-> std::string {
if (time_zones_.size() == 1) { if (time_zones_.size() == 1) {
return ""; return "";
} }

View File

@ -1,16 +1,17 @@
#include <spdlog/spdlog.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <unistd.h> // sysconf
#include <cmath> // NAN
#include <cstdlib> // malloc
#include "modules/cpu.hpp" #include "modules/cpu.hpp"
#include <sys/types.h>
#include <sys/sysctl.h>
#include <spdlog/spdlog.h>
#include <cstdlib> // malloc
#include <unistd.h> // sysconf
#include <cmath> // NAN
#if defined(__NetBSD__) || defined(__OpenBSD__) #if defined(__NetBSD__) || defined(__OpenBSD__)
# include <sys/sched.h> #include <sys/sched.h>
#else #else
# include <sys/resource.h> #include <sys/resource.h>
#endif #endif
#if defined(__NetBSD__) #if defined(__NetBSD__)
@ -35,14 +36,14 @@ std::vector<std::tuple<size_t, size_t>> waybar::modules::Cpu::parseCpuinfo() {
CTL_KERN, CTL_KERN,
KERN_CP_TIME, KERN_CP_TIME,
}; };
if (sysctl(mib, sizeof(mib)/sizeof(mib[0]), sum_cp_time, &sum_sz, NULL, 0)) { if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), sum_cp_time, &sum_sz, NULL, 0)) {
throw std::runtime_error("sysctl kern.cp_time failed"); throw std::runtime_error("sysctl kern.cp_time failed");
} }
for (int state = 0; state < CPUSTATES; state++) { for (int state = 0; state < CPUSTATES; state++) {
cp_time[state] = sum_cp_time[state]; cp_time[state] = sum_cp_time[state];
} }
pcp_time += CPUSTATES; pcp_time += CPUSTATES;
if (sysctl(mib, sizeof(mib)/sizeof(mib[0]), pcp_time, &sz, NULL, 0)) { if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), pcp_time, &sz, NULL, 0)) {
throw std::runtime_error("sysctl kern.cp_time failed"); throw std::runtime_error("sysctl kern.cp_time failed");
} }
#elif defined(__OpenBSD__) #elif defined(__OpenBSD__)
@ -51,7 +52,7 @@ std::vector<std::tuple<size_t, size_t>> waybar::modules::Cpu::parseCpuinfo() {
CTL_KERN, CTL_KERN,
KERN_CPTIME, KERN_CPTIME,
}; };
if (sysctl(mib, sizeof(mib)/sizeof(mib[0]), sum_cp_time, &sum_sz, NULL, 0)) { if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), sum_cp_time, &sum_sz, NULL, 0)) {
throw std::runtime_error("sysctl kern.cp_time failed"); throw std::runtime_error("sysctl kern.cp_time failed");
} }
} }
@ -69,7 +70,7 @@ std::vector<std::tuple<size_t, size_t>> waybar::modules::Cpu::parseCpuinfo() {
for (int cpu = 0; cpu < ncpu; cpu++) { for (int cpu = 0; cpu < ncpu; cpu++) {
mib[2] = cpu; mib[2] = cpu;
pcp_time += CPUSTATES; pcp_time += CPUSTATES;
if (sysctl(mib, sizeof(mib)/sizeof(mib[0]), pcp_time, &sz, NULL, 0)) { if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), pcp_time, &sz, NULL, 0)) {
throw std::runtime_error("sysctl kern.cp_time2 failed"); throw std::runtime_error("sysctl kern.cp_time2 failed");
} }
} }
@ -101,7 +102,8 @@ std::vector<std::tuple<size_t, size_t>> waybar::modules::Cpu::parseCpuinfo() {
std::vector<float> waybar::modules::Cpu::parseCpuFrequencies() { std::vector<float> waybar::modules::Cpu::parseCpuFrequencies() {
static std::vector<float> frequencies; static std::vector<float> frequencies;
if (frequencies.empty()) { if (frequencies.empty()) {
spdlog::warn("cpu/bsd: parseCpuFrequencies is not implemented, expect garbage in {*_frequency}"); spdlog::warn(
"cpu/bsd: parseCpuFrequencies is not implemented, expect garbage in {*_frequency}");
frequencies.push_back(NAN); frequencies.push_back(NAN);
} }
return frequencies; return frequencies;

View File

@ -95,12 +95,13 @@ std::tuple<std::vector<uint16_t>, std::string> waybar::modules::Cpu::getCpuUsage
std::tuple<float, float, float> waybar::modules::Cpu::getCpuFrequency() { std::tuple<float, float, float> waybar::modules::Cpu::getCpuFrequency() {
std::vector<float> frequencies = parseCpuFrequencies(); std::vector<float> frequencies = parseCpuFrequencies();
auto [min, max] = std::minmax_element(std::begin(frequencies), std::end(frequencies)); auto [min, max] = std::minmax_element(std::begin(frequencies), std::end(frequencies));
float avg_frequency = std::accumulate(std::begin(frequencies), std::end(frequencies), 0.0) / frequencies.size(); float avg_frequency =
std::accumulate(std::begin(frequencies), std::end(frequencies), 0.0) / frequencies.size();
// Round frequencies with double decimal precision to get GHz // Round frequencies with double decimal precision to get GHz
float max_frequency = std::ceil(*max / 10.0) / 100.0; float max_frequency = std::ceil(*max / 10.0) / 100.0;
float min_frequency = std::ceil(*min / 10.0) / 100.0; float min_frequency = std::ceil(*min / 10.0) / 100.0;
avg_frequency = std::ceil(avg_frequency / 10.0) / 100.0; avg_frequency = std::ceil(avg_frequency / 10.0) / 100.0;
return { max_frequency, min_frequency, avg_frequency }; return {max_frequency, min_frequency, avg_frequency};
} }

View File

@ -1,4 +1,5 @@
#include <filesystem> #include <filesystem>
#include "modules/cpu.hpp" #include "modules/cpu.hpp"
std::vector<std::tuple<size_t, size_t>> waybar::modules::Cpu::parseCpuinfo() { std::vector<std::tuple<size_t, size_t>> waybar::modules::Cpu::parseCpuinfo() {
@ -51,12 +52,9 @@ std::vector<float> waybar::modules::Cpu::parseCpuFrequencies() {
if (frequencies.size() <= 0) { if (frequencies.size() <= 0) {
std::string cpufreq_dir = "/sys/devices/system/cpu/cpufreq"; std::string cpufreq_dir = "/sys/devices/system/cpu/cpufreq";
if (std::filesystem::exists(cpufreq_dir)) { if (std::filesystem::exists(cpufreq_dir)) {
std::vector<std::string> frequency_files = { std::vector<std::string> frequency_files = {"/cpuinfo_min_freq", "/cpuinfo_max_freq"};
"/cpuinfo_min_freq", for (auto& p : std::filesystem::directory_iterator(cpufreq_dir)) {
"/cpuinfo_max_freq" for (auto freq_file : frequency_files) {
};
for (auto& p: std::filesystem::directory_iterator(cpufreq_dir)) {
for (auto freq_file: frequency_files) {
std::string freq_file_path = p.path().string() + freq_file; std::string freq_file_path = p.path().string() + freq_file;
if (std::filesystem::exists(freq_file_path)) { if (std::filesystem::exists(freq_file_path)) {
std::string freq_value; std::string freq_value;

View File

@ -120,9 +120,7 @@ auto waybar::modules::Custom::update() -> void {
} else { } else {
parseOutputRaw(); parseOutputRaw();
} }
auto str = fmt::format(format_, auto str = fmt::format(format_, text_, fmt::arg("alt", alt_),
text_,
fmt::arg("alt", alt_),
fmt::arg("icon", getIcon(percentage_, alt_)), fmt::arg("icon", getIcon(percentage_, alt_)),
fmt::arg("percentage", percentage_)); fmt::arg("percentage", percentage_));
if (str.empty()) { if (str.empty()) {

View File

@ -3,9 +3,7 @@
using namespace waybar::util; using namespace waybar::util;
waybar::modules::Disk::Disk(const std::string& id, const Json::Value& config) waybar::modules::Disk::Disk(const std::string& id, const Json::Value& config)
: ALabel(config, "disk", id, "{}%", 30) : ALabel(config, "disk", id, "{}%", 30), path_("/") {
, path_("/")
{
thread_ = [this] { thread_ = [this] {
dp.emit(); dp.emit();
thread_.sleep_for(interval_); thread_.sleep_for(interval_);
@ -28,7 +26,8 @@ auto waybar::modules::Disk::update() -> void {
unsigned long f_fsid; // filesystem ID unsigned long f_fsid; // filesystem ID
unsigned long f_flag; // mount flags unsigned long f_flag; // mount flags
unsigned long f_namemax; // maximum filename length unsigned long f_namemax; // maximum filename length
}; */ stats; }; */
stats;
int err = statvfs(path_.c_str(), &stats); int err = statvfs(path_.c_str(), &stats);
/* Conky options /* Conky options
@ -59,15 +58,11 @@ auto waybar::modules::Disk::update() -> void {
event_box_.hide(); event_box_.hide();
} else { } else {
event_box_.show(); event_box_.show();
label_.set_markup(fmt::format(format label_.set_markup(
, stats.f_bavail * 100 / stats.f_blocks fmt::format(format, stats.f_bavail * 100 / stats.f_blocks, fmt::arg("free", free),
, fmt::arg("free", free) fmt::arg("percentage_free", stats.f_bavail * 100 / stats.f_blocks),
, fmt::arg("percentage_free", stats.f_bavail * 100 / stats.f_blocks) fmt::arg("used", used), fmt::arg("percentage_used", percentage_used),
, fmt::arg("used", used) fmt::arg("total", total), fmt::arg("path", path_)));
, fmt::arg("percentage_used", percentage_used)
, fmt::arg("total", total)
, fmt::arg("path", path_)
));
} }
if (tooltipEnabled()) { if (tooltipEnabled()) {
@ -75,15 +70,11 @@ auto waybar::modules::Disk::update() -> void {
if (config_["tooltip-format"].isString()) { if (config_["tooltip-format"].isString()) {
tooltip_format = config_["tooltip-format"].asString(); tooltip_format = config_["tooltip-format"].asString();
} }
label_.set_tooltip_text(fmt::format(tooltip_format label_.set_tooltip_text(
, stats.f_bavail * 100 / stats.f_blocks fmt::format(tooltip_format, stats.f_bavail * 100 / stats.f_blocks, fmt::arg("free", free),
, fmt::arg("free", free) fmt::arg("percentage_free", stats.f_bavail * 100 / stats.f_blocks),
, fmt::arg("percentage_free", stats.f_bavail * 100 / stats.f_blocks) fmt::arg("used", used), fmt::arg("percentage_used", percentage_used),
, fmt::arg("used", used) fmt::arg("total", total), fmt::arg("path", path_)));
, fmt::arg("percentage_used", percentage_used)
, fmt::arg("total", total)
, fmt::arg("path", path_)
));
} }
// Call parent update // Call parent update
ALabel::update(); ALabel::update();

View File

@ -58,8 +58,8 @@ auto waybar::modules::IdleInhibitor::update() -> void {
} }
std::string status_text = status ? "activated" : "deactivated"; std::string status_text = status ? "activated" : "deactivated";
label_.set_markup( label_.set_markup(fmt::format(format_, fmt::arg("status", status_text),
fmt::format(format_, fmt::arg("status", status_text), fmt::arg("icon", getIcon(0, status_text)))); fmt::arg("icon", getIcon(0, status_text))));
label_.get_style_context()->add_class(status_text); label_.get_style_context()->add_class(status_text);
if (tooltipEnabled()) { if (tooltipEnabled()) {
label_.set_tooltip_text(status_text); label_.set_tooltip_text(status_text);

View File

@ -6,12 +6,11 @@
namespace { namespace {
using DBus = std::unique_ptr<GDBusConnection, void(*)(GDBusConnection*)>; using DBus = std::unique_ptr<GDBusConnection, void (*)(GDBusConnection*)>;
auto dbus() -> DBus { auto dbus() -> DBus {
GError *error = nullptr; GError* error = nullptr;
GDBusConnection* connection = GDBusConnection* connection = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error);
g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error);
if (error) { if (error) {
spdlog::error("g_bus_get_sync() failed: {}", error->message); spdlog::error("g_bus_get_sync() failed: {}", error->message);
@ -20,12 +19,10 @@ auto dbus() -> DBus {
} }
auto destructor = [](GDBusConnection* connection) { auto destructor = [](GDBusConnection* connection) {
GError *error = nullptr; GError* error = nullptr;
g_dbus_connection_close_sync(connection, nullptr, &error); g_dbus_connection_close_sync(connection, nullptr, &error);
if (error) { if (error) {
spdlog::error( spdlog::error("g_bus_connection_close_sync failed(): {}", error->message);
"g_bus_connection_close_sync failed(): {}",
error->message);
g_error_free(error); g_error_free(error);
} }
}; };
@ -34,32 +31,17 @@ auto dbus() -> DBus {
} }
auto getLocks(const DBus& bus, const std::string& inhibitors) -> int { auto getLocks(const DBus& bus, const std::string& inhibitors) -> int {
GError *error = nullptr; GError* error = nullptr;
GUnixFDList* fd_list; GUnixFDList* fd_list;
int handle; int handle;
auto reply = g_dbus_connection_call_with_unix_fd_list_sync(bus.get(), auto reply = g_dbus_connection_call_with_unix_fd_list_sync(
"org.freedesktop.login1", bus.get(), "org.freedesktop.login1", "/org/freedesktop/login1",
"/org/freedesktop/login1", "org.freedesktop.login1.Manager", "Inhibit",
"org.freedesktop.login1.Manager", g_variant_new("(ssss)", inhibitors.c_str(), "waybar", "Asked by user", "block"),
"Inhibit", G_VARIANT_TYPE("(h)"), G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &fd_list, nullptr, &error);
g_variant_new(
"(ssss)",
inhibitors.c_str(),
"waybar",
"Asked by user",
"block"),
G_VARIANT_TYPE("(h)"),
G_DBUS_CALL_FLAGS_NONE,
-1,
nullptr,
&fd_list,
nullptr,
&error);
if (error) { if (error) {
spdlog::error( spdlog::error("g_dbus_connection_call_with_unix_fd_list_sync() failed: {}", error->message);
"g_dbus_connection_call_with_unix_fd_list_sync() failed: {}",
error->message);
g_error_free(error); g_error_free(error);
handle = -1; handle = -1;
} else { } else {
@ -74,18 +56,15 @@ auto getLocks(const DBus& bus, const std::string& inhibitors) -> int {
} }
auto checkInhibitor(const std::string& inhibitor) -> const std::string& { auto checkInhibitor(const std::string& inhibitor) -> const std::string& {
static const auto inhibitors = std::array{ static const auto inhibitors = std::array{"idle",
"idle",
"shutdown", "shutdown",
"sleep", "sleep",
"handle-power-key", "handle-power-key",
"handle-suspend-key", "handle-suspend-key",
"handle-hibernate-key", "handle-hibernate-key",
"handle-lid-switch" "handle-lid-switch"};
};
if (std::find(inhibitors.begin(), inhibitors.end(), inhibitor) if (std::find(inhibitors.begin(), inhibitors.end(), inhibitor) == inhibitors.end()) {
== inhibitors.end()) {
throw std::runtime_error("invalid logind inhibitor " + inhibitor); throw std::runtime_error("invalid logind inhibitor " + inhibitor);
} }
@ -114,18 +93,16 @@ auto getInhibitors(const Json::Value& config) -> std::string {
return inhibitors; return inhibitors;
} }
} } // namespace
namespace waybar::modules { namespace waybar::modules {
Inhibitor::Inhibitor(const std::string& id, const Bar& bar, Inhibitor::Inhibitor(const std::string& id, const Bar& bar, const Json::Value& config)
const Json::Value& config)
: ALabel(config, "inhibitor", id, "{status}", true), : ALabel(config, "inhibitor", id, "{status}", true),
dbus_(::dbus()), dbus_(::dbus()),
inhibitors_(::getInhibitors(config)) { inhibitors_(::getInhibitors(config)) {
event_box_.add_events(Gdk::BUTTON_PRESS_MASK); event_box_.add_events(Gdk::BUTTON_PRESS_MASK);
event_box_.signal_button_press_event().connect( event_box_.signal_button_press_event().connect(sigc::mem_fun(*this, &Inhibitor::handleToggle));
sigc::mem_fun(*this, &Inhibitor::handleToggle));
dp.emit(); dp.emit();
} }
@ -135,17 +112,13 @@ Inhibitor::~Inhibitor() {
} }
} }
auto Inhibitor::activated() -> bool { auto Inhibitor::activated() -> bool { return handle_ != -1; }
return handle_ != -1;
}
auto Inhibitor::update() -> void { auto Inhibitor::update() -> void {
std::string status_text = activated() ? "activated" : "deactivated"; std::string status_text = activated() ? "activated" : "deactivated";
label_.get_style_context()->remove_class( label_.get_style_context()->remove_class(activated() ? "deactivated" : "activated");
activated() ? "deactivated" : "activated"); label_.set_markup(fmt::format(format_, fmt::arg("status", status_text),
label_.set_markup(
fmt::format(format_, fmt::arg("status", status_text),
fmt::arg("icon", getIcon(0, status_text)))); fmt::arg("icon", getIcon(0, status_text))));
label_.get_style_context()->add_class(status_text); label_.get_style_context()->add_class(status_text);
@ -172,4 +145,4 @@ auto Inhibitor::handleToggle(GdkEventButton* const& e) -> bool {
return ALabel::handleToggle(e); return ALabel::handleToggle(e);
} }
} // waybar::modules } // namespace waybar::modules

View File

@ -1,31 +1,32 @@
#include "modules/keyboard_state.hpp" #include "modules/keyboard_state.hpp"
#include <errno.h> #include <errno.h>
#include <filesystem>
#include <spdlog/spdlog.h> #include <spdlog/spdlog.h>
#include <string.h> #include <string.h>
#include <filesystem>
extern "C" { extern "C" {
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h> #include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
} }
class errno_error : public std::runtime_error { class errno_error : public std::runtime_error {
public: public:
int code; int code;
errno_error(int code, const std::string& msg) errno_error(int code, const std::string& msg)
: std::runtime_error(getErrorMsg(code, msg.c_str())), : std::runtime_error(getErrorMsg(code, msg.c_str())), code(code) {}
code(code) {} errno_error(int code, const char* msg) : std::runtime_error(getErrorMsg(code, msg)), code(code) {}
errno_error(int code, const char* msg)
: std::runtime_error(getErrorMsg(code, msg)),
code(code) {}
private: private:
static auto getErrorMsg(int err, const char* msg) -> std::string { static auto getErrorMsg(int err, const char* msg) -> std::string {
std::string error_msg{msg}; std::string error_msg{msg};
error_msg += ": "; error_msg += ": ";
#if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 32) #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 32)
// strerrorname_np gets the error code's name; it's nice to have, but it's a recent GNU extension // strerrorname_np gets the error code's name; it's nice to have, but it's a recent GNU
// extension
const auto errno_name = strerrorname_np(err); const auto errno_name = strerrorname_np(err);
error_msg += errno_name; error_msg += errno_name;
error_msg += " "; error_msg += " ";
@ -67,27 +68,31 @@ auto openDevice(int fd) -> libevdev* {
} }
auto supportsLockStates(const libevdev* dev) -> bool { auto supportsLockStates(const libevdev* dev) -> bool {
return libevdev_has_event_type(dev, EV_LED) return libevdev_has_event_type(dev, EV_LED) && libevdev_has_event_code(dev, EV_LED, LED_NUML) &&
&& libevdev_has_event_code(dev, EV_LED, LED_NUML) libevdev_has_event_code(dev, EV_LED, LED_CAPSL) &&
&& libevdev_has_event_code(dev, EV_LED, LED_CAPSL) libevdev_has_event_code(dev, EV_LED, LED_SCROLLL);
&& libevdev_has_event_code(dev, EV_LED, LED_SCROLLL);
} }
waybar::modules::KeyboardState::KeyboardState(const std::string& id, const Bar& bar, const Json::Value& config) 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()), : AModule(config, "keyboard-state", id, false, !config["disable-scroll"].asBool()),
box_(bar.vertical ? Gtk::ORIENTATION_VERTICAL : Gtk::ORIENTATION_HORIZONTAL, 0), box_(bar.vertical ? Gtk::ORIENTATION_VERTICAL : Gtk::ORIENTATION_HORIZONTAL, 0),
numlock_label_(""), numlock_label_(""),
capslock_label_(""), capslock_label_(""),
numlock_format_(config_["format"].isString() ? config_["format"].asString() numlock_format_(config_["format"].isString() ? config_["format"].asString()
: config_["format"]["numlock"].isString() ? config_["format"]["numlock"].asString() : config_["format"]["numlock"].isString()
? config_["format"]["numlock"].asString()
: "{name} {icon}"), : "{name} {icon}"),
capslock_format_(config_["format"].isString() ? config_["format"].asString() capslock_format_(config_["format"].isString() ? config_["format"].asString()
: config_["format"]["capslock"].isString() ? config_["format"]["capslock"].asString() : config_["format"]["capslock"].isString()
? config_["format"]["capslock"].asString()
: "{name} {icon}"), : "{name} {icon}"),
scrolllock_format_(config_["format"].isString() ? config_["format"].asString() scrolllock_format_(config_["format"].isString() ? config_["format"].asString()
: config_["format"]["scrolllock"].isString() ? config_["format"]["scrolllock"].asString() : config_["format"]["scrolllock"].isString()
? config_["format"]["scrolllock"].asString()
: "{name} {icon}"), : "{name} {icon}"),
interval_(std::chrono::seconds(config_["interval"].isUInt() ? config_["interval"].asUInt() : 1)), interval_(
std::chrono::seconds(config_["interval"].isUInt() ? config_["interval"].asUInt() : 1)),
icon_locked_(config_["format-icons"]["locked"].isString() icon_locked_(config_["format-icons"]["locked"].isString()
? config_["format-icons"]["locked"].asString() ? config_["format-icons"]["locked"].asString()
: "locked"), : "locked"),
@ -120,7 +125,7 @@ waybar::modules::KeyboardState::KeyboardState(const std::string& id, const Bar&
if (dev_dir == nullptr) { if (dev_dir == nullptr) {
throw errno_error(errno, "Failed to open /dev/input"); throw errno_error(errno, "Failed to open /dev/input");
} }
dirent *ep; dirent* ep;
while ((ep = readdir(dev_dir))) { while ((ep = readdir(dev_dir))) {
if (ep->d_type != DT_CHR) continue; if (ep->d_type != DT_CHR) continue;
std::string dev_path = std::string("/dev/input/") + ep->d_name; std::string dev_path = std::string("/dev/input/") + ep->d_name;
@ -184,9 +189,9 @@ auto waybar::modules::KeyboardState::update() -> void {
const std::string& format; const std::string& format;
const char* name; const char* name;
} label_states[] = { } label_states[] = {
{(bool) numl, numlock_label_, numlock_format_, "Num"}, {(bool)numl, numlock_label_, numlock_format_, "Num"},
{(bool) capsl, capslock_label_, capslock_format_, "Caps"}, {(bool)capsl, capslock_label_, capslock_format_, "Caps"},
{(bool) scrolll, scrolllock_label_, scrolllock_format_, "Scroll"}, {(bool)scrolll, scrolllock_label_, scrolllock_format_, "Scroll"},
}; };
for (auto& label_state : label_states) { for (auto& label_state : label_states) {
std::string text; std::string text;

View File

@ -1,15 +1,15 @@
#include "modules/memory.hpp"
#include <sys/types.h>
#include <sys/sysctl.h> #include <sys/sysctl.h>
#include <sys/types.h>
#include <unistd.h> // getpagesize #include <unistd.h> // getpagesize
#include "modules/memory.hpp"
#if defined(__DragonFly__) #if defined(__DragonFly__)
# include <sys/vmmeter.h> // struct vmstats #include <sys/vmmeter.h> // struct vmstats
#elif defined(__NetBSD__) #elif defined(__NetBSD__)
# include <uvm/uvm_extern.h> // struct uvmexp_sysctl #include <uvm/uvm_extern.h> // struct uvmexp_sysctl
#elif defined(__OpenBSD__) #elif defined(__OpenBSD__)
# include <uvm/uvmexp.h> // struct uvmexp #include <uvm/uvmexp.h> // struct uvmexp
#endif #endif
static uint64_t get_total_memory() { static uint64_t get_total_memory() {
@ -43,29 +43,23 @@ static uint64_t get_free_memory() {
if (sysctlbyname("vm.vmstats", &vms, &sz, NULL, 0)) { if (sysctlbyname("vm.vmstats", &vms, &sz, NULL, 0)) {
throw std::runtime_error("sysctl vm.vmstats failed"); throw std::runtime_error("sysctl vm.vmstats failed");
} }
return static_cast<uint64_t> return static_cast<uint64_t>(vms.v_free_count + vms.v_inactive_count + vms.v_cache_count) *
(vms.v_free_count + vms.v_inactive_count + vms.v_cache_count) getpagesize();
* getpagesize();
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
u_int v_free_count = 0, v_inactive_count = 0, v_cache_count = 0; u_int v_free_count = 0, v_inactive_count = 0, v_cache_count = 0;
size_t sz = sizeof(u_int); size_t sz = sizeof(u_int);
sysctlbyname("vm.stats.vm.v_free_count", sysctlbyname("vm.stats.vm.v_free_count", &v_free_count, &sz, NULL, 0);
&v_free_count, &sz, NULL, 0); sysctlbyname("vm.stats.vm.v_inactive_count", &v_inactive_count, &sz, NULL, 0);
sysctlbyname("vm.stats.vm.v_inactive_count", sysctlbyname("vm.stats.vm.v_cache_count", &v_cache_count, &sz, NULL, 0);
&v_inactive_count, &sz, NULL, 0); return static_cast<uint64_t>(v_free_count + v_inactive_count + v_cache_count) * getpagesize();
sysctlbyname("vm.stats.vm.v_cache_count",
&v_cache_count, &sz, NULL, 0);
return static_cast<uint64_t>
(v_free_count + v_inactive_count + v_cache_count)
* getpagesize();
#elif defined(__NetBSD__) || defined(__OpenBSD__) #elif defined(__NetBSD__) || defined(__OpenBSD__)
#ifdef VM_UVMEXP2 #ifdef VM_UVMEXP2
# undef VM_UVMEXP #undef VM_UVMEXP
# define VM_UVMEXP VM_UVMEXP2 #define VM_UVMEXP VM_UVMEXP2
# define uvmexp uvmexp_sysctl #define uvmexp uvmexp_sysctl
#else #else
# define filepages vnodepages #define filepages vnodepages
# define execpages vtextpages #define execpages vtextpages
#endif #endif
int mib[] = { int mib[] = {
CTL_VM, CTL_VM,
@ -77,9 +71,9 @@ static uint64_t get_free_memory() {
if (sysctl(mib, miblen, &uvmexp, &sz, NULL, 0)) { if (sysctl(mib, miblen, &uvmexp, &sz, NULL, 0)) {
throw std::runtime_error("sysctl vm.uvmexp failed"); throw std::runtime_error("sysctl vm.uvmexp failed");
} }
return static_cast<uint64_t> return static_cast<uint64_t>(uvmexp.free + uvmexp.inactive + uvmexp.filepages +
(uvmexp.free + uvmexp.inactive + uvmexp.filepages + uvmexp.execpages) uvmexp.execpages) *
* uvmexp.pagesize; uvmexp.pagesize;
#endif #endif
} }

View File

@ -54,31 +54,24 @@ auto waybar::modules::Memory::update() -> void {
} else { } else {
event_box_.show(); event_box_.show();
auto icons = std::vector<std::string>{state}; auto icons = std::vector<std::string>{state};
label_.set_markup(fmt::format(format, label_.set_markup(fmt::format(
used_ram_percentage, format, used_ram_percentage, fmt::arg("icon", getIcon(used_ram_percentage, icons)),
fmt::arg("icon", getIcon(used_ram_percentage, icons)), fmt::arg("total", total_ram_gigabytes), fmt::arg("swapTotal", total_swap_gigabytes),
fmt::arg("total", total_ram_gigabytes),
fmt::arg("swapTotal", total_swap_gigabytes),
fmt::arg("percentage", used_ram_percentage), fmt::arg("percentage", used_ram_percentage),
fmt::arg("swapPercentage", used_swap_percentage), fmt::arg("swapPercentage", used_swap_percentage), fmt::arg("used", used_ram_gigabytes),
fmt::arg("used", used_ram_gigabytes), fmt::arg("swapUsed", used_swap_gigabytes), fmt::arg("avail", available_ram_gigabytes),
fmt::arg("swapUsed", used_swap_gigabytes),
fmt::arg("avail", available_ram_gigabytes),
fmt::arg("swapAvail", available_swap_gigabytes))); fmt::arg("swapAvail", available_swap_gigabytes)));
} }
if (tooltipEnabled()) { if (tooltipEnabled()) {
if (config_["tooltip-format"].isString()) { if (config_["tooltip-format"].isString()) {
auto tooltip_format = config_["tooltip-format"].asString(); auto tooltip_format = config_["tooltip-format"].asString();
label_.set_tooltip_text(fmt::format(tooltip_format, label_.set_tooltip_text(fmt::format(
used_ram_percentage, tooltip_format, used_ram_percentage, fmt::arg("total", total_ram_gigabytes),
fmt::arg("total", total_ram_gigabytes),
fmt::arg("swapTotal", total_swap_gigabytes), fmt::arg("swapTotal", total_swap_gigabytes),
fmt::arg("percentage", used_ram_percentage), fmt::arg("percentage", used_ram_percentage),
fmt::arg("swapPercentage", used_swap_percentage), fmt::arg("swapPercentage", used_swap_percentage), fmt::arg("used", used_ram_gigabytes),
fmt::arg("used", used_ram_gigabytes), fmt::arg("swapUsed", used_swap_gigabytes), fmt::arg("avail", available_ram_gigabytes),
fmt::arg("swapUsed", used_swap_gigabytes),
fmt::arg("avail", available_ram_gigabytes),
fmt::arg("swapAvail", available_swap_gigabytes))); fmt::arg("swapAvail", available_swap_gigabytes)));
} else { } else {
label_.set_tooltip_text(fmt::format("{:.{}f}GiB used", used_ram_gigabytes, 1)); label_.set_tooltip_text(fmt::format("{:.{}f}GiB used", used_ram_gigabytes, 1));

View File

@ -1,8 +1,9 @@
#include "modules/mpd/mpd.hpp" #include "modules/mpd/mpd.hpp"
#include <fmt/chrono.h> #include <fmt/chrono.h>
#include <spdlog/spdlog.h>
#include <glibmm/ustring.h> #include <glibmm/ustring.h>
#include <spdlog/spdlog.h>
#include "modules/mpd/state.hpp" #include "modules/mpd/state.hpp"
#if defined(MPD_NOINLINE) #if defined(MPD_NOINLINE)
namespace waybar::modules { namespace waybar::modules {
@ -148,28 +149,23 @@ void waybar::modules::MPD::setLabel() {
bool singleActivated = mpd_status_get_single(status_.get()); bool singleActivated = mpd_status_get_single(status_.get());
std::string singleIcon = getOptionIcon("single", singleActivated); std::string singleIcon = getOptionIcon("single", singleActivated);
if (config_["artist-len"].isInt()) artist = artist.substr(0, config_["artist-len"].asInt()); if (config_["artist-len"].isInt()) artist = artist.substr(0, config_["artist-len"].asInt());
if (config_["album-artist-len"].isInt()) album_artist = album_artist.substr(0, config_["album-artist-len"].asInt()); if (config_["album-artist-len"].isInt())
album_artist = album_artist.substr(0, config_["album-artist-len"].asInt());
if (config_["album-len"].isInt()) album = album.substr(0, config_["album-len"].asInt()); if (config_["album-len"].isInt()) album = album.substr(0, config_["album-len"].asInt());
if (config_["title-len"].isInt()) title = title.substr(0,config_["title-len"].asInt()); if (config_["title-len"].isInt()) title = title.substr(0, config_["title-len"].asInt());
try { try {
label_.set_markup( label_.set_markup(
fmt::format(format, fmt::format(format, fmt::arg("artist", Glib::Markup::escape_text(artist).raw()),
fmt::arg("artist", Glib::Markup::escape_text(artist).raw()),
fmt::arg("albumArtist", Glib::Markup::escape_text(album_artist).raw()), fmt::arg("albumArtist", Glib::Markup::escape_text(album_artist).raw()),
fmt::arg("album", Glib::Markup::escape_text(album).raw()), fmt::arg("album", Glib::Markup::escape_text(album).raw()),
fmt::arg("title", Glib::Markup::escape_text(title).raw()), fmt::arg("title", Glib::Markup::escape_text(title).raw()),
fmt::arg("date", Glib::Markup::escape_text(date).raw()), fmt::arg("date", Glib::Markup::escape_text(date).raw()),
fmt::arg("volume", volume), fmt::arg("volume", volume), fmt::arg("elapsedTime", elapsedTime),
fmt::arg("elapsedTime", elapsedTime), fmt::arg("totalTime", totalTime), fmt::arg("songPosition", song_pos),
fmt::arg("totalTime", totalTime), fmt::arg("queueLength", queue_length), fmt::arg("stateIcon", stateIcon),
fmt::arg("songPosition", song_pos), fmt::arg("consumeIcon", consumeIcon), fmt::arg("randomIcon", randomIcon),
fmt::arg("queueLength", queue_length), fmt::arg("repeatIcon", repeatIcon), fmt::arg("singleIcon", singleIcon)));
fmt::arg("stateIcon", stateIcon),
fmt::arg("consumeIcon", consumeIcon),
fmt::arg("randomIcon", randomIcon),
fmt::arg("repeatIcon", repeatIcon),
fmt::arg("singleIcon", singleIcon)));
} catch (fmt::format_error const& e) { } catch (fmt::format_error const& e) {
spdlog::warn("mpd: format error: {}", e.what()); spdlog::warn("mpd: format error: {}", e.what());
} }
@ -179,22 +175,15 @@ void waybar::modules::MPD::setLabel() {
tooltip_format = config_["tooltip-format"].isString() ? config_["tooltip-format"].asString() tooltip_format = config_["tooltip-format"].isString() ? config_["tooltip-format"].asString()
: "MPD (connected)"; : "MPD (connected)";
try { try {
auto tooltip_text = fmt::format(tooltip_format, auto tooltip_text =
fmt::arg("artist", artist.raw()), fmt::format(tooltip_format, fmt::arg("artist", artist.raw()),
fmt::arg("albumArtist", album_artist.raw()), fmt::arg("albumArtist", album_artist.raw()), fmt::arg("album", album.raw()),
fmt::arg("album", album.raw()), fmt::arg("title", title.raw()), fmt::arg("date", date),
fmt::arg("title", title.raw()), fmt::arg("volume", volume), fmt::arg("elapsedTime", elapsedTime),
fmt::arg("date", date), fmt::arg("totalTime", totalTime), fmt::arg("songPosition", song_pos),
fmt::arg("volume", volume), fmt::arg("queueLength", queue_length), fmt::arg("stateIcon", stateIcon),
fmt::arg("elapsedTime", elapsedTime), fmt::arg("consumeIcon", consumeIcon), fmt::arg("randomIcon", randomIcon),
fmt::arg("totalTime", totalTime), fmt::arg("repeatIcon", repeatIcon), fmt::arg("singleIcon", singleIcon));
fmt::arg("songPosition", song_pos),
fmt::arg("queueLength", queue_length),
fmt::arg("stateIcon", stateIcon),
fmt::arg("consumeIcon", consumeIcon),
fmt::arg("randomIcon", randomIcon),
fmt::arg("repeatIcon", repeatIcon),
fmt::arg("singleIcon", singleIcon));
label_.set_tooltip_text(tooltip_text); label_.set_tooltip_text(tooltip_text);
} catch (fmt::format_error const& e) { } catch (fmt::format_error const& e) {
spdlog::warn("mpd: format error (tooltip): {}", e.what()); spdlog::warn("mpd: format error (tooltip): {}", e.what());

View File

@ -61,8 +61,7 @@ void Idle::entry() noexcept {
spdlog::debug("mpd: Idle: watching FD"); spdlog::debug("mpd: Idle: watching FD");
sigc::slot<bool, Glib::IOCondition const&> idle_slot = sigc::mem_fun(*this, &Idle::on_io); sigc::slot<bool, Glib::IOCondition const&> idle_slot = sigc::mem_fun(*this, &Idle::on_io);
idle_connection_ = idle_connection_ =
Glib::signal_io().connect(idle_slot, Glib::signal_io().connect(idle_slot, mpd_connection_get_fd(conn),
mpd_connection_get_fd(conn),
Glib::IO_IN | Glib::IO_PRI | Glib::IO_ERR | Glib::IO_HUP); Glib::IO_IN | Glib::IO_PRI | Glib::IO_ERR | Glib::IO_HUP);
} }
} }
@ -327,8 +326,7 @@ void Disconnected::arm_timer(int interval) noexcept {
// register timer // register timer
sigc::slot<bool> timer_slot = sigc::mem_fun(*this, &Disconnected::on_timer); sigc::slot<bool> timer_slot = sigc::mem_fun(*this, &Disconnected::on_timer);
timer_connection_ = timer_connection_ = Glib::signal_timeout().connect(timer_slot, interval);
Glib::signal_timeout().connect(timer_slot, interval);
spdlog::debug("mpd: Disconnected: enabled interval timer."); spdlog::debug("mpd: Disconnected: enabled interval timer.");
} }
@ -345,9 +343,7 @@ void Disconnected::entry() noexcept {
arm_timer(1'000); arm_timer(1'000);
} }
void Disconnected::exit() noexcept { void Disconnected::exit() noexcept { disarm_timer(); }
disarm_timer();
}
bool Disconnected::on_timer() { bool Disconnected::on_timer() {
// Attempt to connect with MPD. // Attempt to connect with MPD.

View File

@ -1,13 +1,14 @@
#include "modules/network.hpp"
#include <linux/if.h> #include <linux/if.h>
#include <spdlog/spdlog.h> #include <spdlog/spdlog.h>
#include <sys/eventfd.h> #include <sys/eventfd.h>
#include <cassert> #include <cassert>
#include <fstream> #include <fstream>
#include <sstream>
#include <optional> #include <optional>
#include <sstream>
#include "modules/network.hpp"
#include "util/format.hpp" #include "util/format.hpp"
#ifdef WANT_RFKILL #ifdef WANT_RFKILL
#include "util/rfkill.hpp" #include "util/rfkill.hpp"
@ -58,9 +59,13 @@ waybar::modules::Network::readBandwidthUsage() {
// Skip all the other columns in the received group // Skip all the other columns in the received group
for (int colsToSkip = 7; colsToSkip > 0; colsToSkip--) { for (int colsToSkip = 7; colsToSkip > 0; colsToSkip--) {
// skip whitespace between columns // skip whitespace between columns
while (iss.peek() == ' ') { iss.ignore(); } while (iss.peek() == ' ') {
iss.ignore();
}
// skip the irrelevant column // skip the irrelevant column
while (iss.peek() != ' ') { iss.ignore(); } while (iss.peek() != ' ') {
iss.ignore();
}
} }
// Read transmit bytes // Read transmit bytes
iss >> t; iss >> t;
@ -274,8 +279,7 @@ void waybar::modules::Network::worker() {
const std::string waybar::modules::Network::getNetworkState() const { const std::string waybar::modules::Network::getNetworkState() const {
if (ifid_ == -1) { if (ifid_ == -1) {
#ifdef WANT_RFKILL #ifdef WANT_RFKILL
if (rfkill_.getState()) if (rfkill_.getState()) return "disabled";
return "disabled";
#endif #endif
return "disconnected"; return "disconnected";
} }
@ -327,17 +331,11 @@ auto waybar::modules::Network::update() -> void {
getState(signal_strength_); getState(signal_strength_);
auto text = fmt::format( auto text = fmt::format(
format_, format_, fmt::arg("essid", essid_), fmt::arg("signaldBm", signal_strength_dbm_),
fmt::arg("essid", essid_),
fmt::arg("signaldBm", signal_strength_dbm_),
fmt::arg("signalStrength", signal_strength_), fmt::arg("signalStrength", signal_strength_),
fmt::arg("signalStrengthApp", signal_strength_app_), fmt::arg("signalStrengthApp", signal_strength_app_), fmt::arg("ifname", ifname_),
fmt::arg("ifname", ifname_), fmt::arg("netmask", netmask_), fmt::arg("ipaddr", ipaddr_), fmt::arg("gwaddr", gwaddr_),
fmt::arg("netmask", netmask_), fmt::arg("cidr", cidr_), fmt::arg("frequency", fmt::format("{:.1f}", frequency_)),
fmt::arg("ipaddr", ipaddr_),
fmt::arg("gwaddr", gwaddr_),
fmt::arg("cidr", cidr_),
fmt::arg("frequency", fmt::format("{:.1f}", frequency_)),
fmt::arg("icon", getIcon(signal_strength_, state_)), fmt::arg("icon", getIcon(signal_strength_, state_)),
fmt::arg("bandwidthDownBits", pow_format(bandwidth_down * 8ull / interval_.count(), "b/s")), fmt::arg("bandwidthDownBits", pow_format(bandwidth_down * 8ull / interval_.count(), "b/s")),
fmt::arg("bandwidthUpBits", pow_format(bandwidth_up * 8ull / interval_.count(), "b/s")), fmt::arg("bandwidthUpBits", pow_format(bandwidth_up * 8ull / interval_.count(), "b/s")),
@ -359,17 +357,11 @@ auto waybar::modules::Network::update() -> void {
} }
if (!tooltip_format.empty()) { if (!tooltip_format.empty()) {
auto tooltip_text = fmt::format( auto tooltip_text = fmt::format(
tooltip_format, tooltip_format, fmt::arg("essid", essid_), fmt::arg("signaldBm", signal_strength_dbm_),
fmt::arg("essid", essid_),
fmt::arg("signaldBm", signal_strength_dbm_),
fmt::arg("signalStrength", signal_strength_), fmt::arg("signalStrength", signal_strength_),
fmt::arg("signalStrengthApp", signal_strength_app_), fmt::arg("signalStrengthApp", signal_strength_app_), fmt::arg("ifname", ifname_),
fmt::arg("ifname", ifname_), fmt::arg("netmask", netmask_), fmt::arg("ipaddr", ipaddr_), fmt::arg("gwaddr", gwaddr_),
fmt::arg("netmask", netmask_), fmt::arg("cidr", cidr_), fmt::arg("frequency", fmt::format("{:.1f}", frequency_)),
fmt::arg("ipaddr", ipaddr_),
fmt::arg("gwaddr", gwaddr_),
fmt::arg("cidr", cidr_),
fmt::arg("frequency", fmt::format("{:.1f}", frequency_)),
fmt::arg("icon", getIcon(signal_strength_, state_)), fmt::arg("icon", getIcon(signal_strength_, state_)),
fmt::arg("bandwidthDownBits", fmt::arg("bandwidthDownBits",
pow_format(bandwidth_down * 8ull / interval_.count(), "b/s")), pow_format(bandwidth_down * 8ull / interval_.count(), "b/s")),
@ -436,8 +428,7 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
// Check if the interface goes "down" and if we want to detect the // Check if the interface goes "down" and if we want to detect the
// external interface. // external interface.
if (net->ifid_ != -1 && !(ifi->ifi_flags & IFF_UP) if (net->ifid_ != -1 && !(ifi->ifi_flags & IFF_UP) && !net->config_["interface"].isString()) {
&& !net->config_["interface"].isString()) {
// The current interface is now down, all the routes associated with // The current interface is now down, all the routes associated with
// it have been deleted, so start looking for a new default route. // it have been deleted, so start looking for a new default route.
spdlog::debug("network: if{} down", net->ifid_); spdlog::debug("network: if{} down", net->ifid_);
@ -455,7 +446,7 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
ifname_len = RTA_PAYLOAD(ifla) - 1; // minus \0 ifname_len = RTA_PAYLOAD(ifla) - 1; // minus \0
break; break;
case IFLA_CARRIER: { case IFLA_CARRIER: {
carrier = *(char*)RTA_DATA(ifla) == 1; carrier = *(char *)RTA_DATA(ifla) == 1;
break; break;
} }
} }
@ -464,7 +455,7 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
if (!is_del_event && ifi->ifi_index == net->ifid_) { if (!is_del_event && ifi->ifi_index == net->ifid_) {
// Update interface information // Update interface information
if (net->ifname_.empty() && ifname != NULL) { if (net->ifname_.empty() && ifname != NULL) {
std::string new_ifname (ifname, ifname_len); std::string new_ifname(ifname, ifname_len);
net->ifname_ = new_ifname; net->ifname_ = new_ifname;
} }
if (carrier.has_value()) { if (carrier.has_value()) {
@ -485,7 +476,7 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
} }
} else if (!is_del_event && net->ifid_ == -1) { } else if (!is_del_event && net->ifid_ == -1) {
// Checking if it's an interface we care about. // Checking if it's an interface we care about.
std::string new_ifname (ifname, ifname_len); std::string new_ifname(ifname, ifname_len);
if (net->checkInterface(new_ifname)) { if (net->checkInterface(new_ifname)) {
spdlog::debug("network: selecting new interface {}/{}", new_ifname, ifi->ifi_index); spdlog::debug("network: selecting new interface {}/{}", new_ifname, ifi->ifi_index);
@ -537,15 +528,13 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
case IFA_ADDRESS: { case IFA_ADDRESS: {
char ipaddr[INET6_ADDRSTRLEN]; char ipaddr[INET6_ADDRSTRLEN];
if (!is_del_event) { if (!is_del_event) {
net->ipaddr_ = inet_ntop(ifa->ifa_family, RTA_DATA(ifa_rta), net->ipaddr_ = inet_ntop(ifa->ifa_family, RTA_DATA(ifa_rta), ipaddr, sizeof(ipaddr));
ipaddr, sizeof (ipaddr));
net->cidr_ = ifa->ifa_prefixlen; net->cidr_ = ifa->ifa_prefixlen;
switch (ifa->ifa_family) { switch (ifa->ifa_family) {
case AF_INET: { case AF_INET: {
struct in_addr netmask; struct in_addr netmask;
netmask.s_addr = htonl(~0 << (32 - ifa->ifa_prefixlen)); netmask.s_addr = htonl(~0 << (32 - ifa->ifa_prefixlen));
net->netmask_ = inet_ntop(ifa->ifa_family, &netmask, net->netmask_ = inet_ntop(ifa->ifa_family, &netmask, ipaddr, sizeof(ipaddr));
ipaddr, sizeof (ipaddr));
} }
case AF_INET6: { case AF_INET6: {
struct in6_addr netmask; struct in6_addr netmask;
@ -555,8 +544,7 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
if (v > 8) v = 8; if (v > 8) v = 8;
netmask.s6_addr[i] = ~0 << v; netmask.s6_addr[i] = ~0 << v;
} }
net->netmask_ = inet_ntop(ifa->ifa_family, &netmask, net->netmask_ = inet_ntop(ifa->ifa_family, &netmask, ipaddr, sizeof(ipaddr));
ipaddr, sizeof (ipaddr));
} }
} }
spdlog::debug("network: {}, new addr {}/{}", net->ifname_, net->ipaddr_, net->cidr_); spdlog::debug("network: {}, new addr {}/{}", net->ifname_, net->ipaddr_, net->cidr_);
@ -564,10 +552,8 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
net->ipaddr_.clear(); net->ipaddr_.clear();
net->cidr_ = 0; net->cidr_ = 0;
net->netmask_.clear(); net->netmask_.clear();
spdlog::debug("network: {} addr deleted {}/{}", spdlog::debug("network: {} addr deleted {}/{}", net->ifname_,
net->ifname_, inet_ntop(ifa->ifa_family, RTA_DATA(ifa_rta), ipaddr, sizeof(ipaddr)),
inet_ntop(ifa->ifa_family, RTA_DATA(ifa_rta),
ipaddr, sizeof (ipaddr)),
ifa->ifa_prefixlen); ifa->ifa_prefixlen);
} }
net->dp.emit(); net->dp.emit();
@ -593,7 +579,6 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
int temp_idx = -1; int temp_idx = -1;
uint32_t priority = 0; uint32_t priority = 0;
/* Find the message(s) concerting the main routing table, each message /* Find the message(s) concerting the main routing table, each message
* corresponds to a single routing table entry. * corresponds to a single routing table entry.
*/ */
@ -607,7 +592,7 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
* route by seeing if it has a gateway, and if a destination addr is * route by seeing if it has a gateway, and if a destination addr is
* set, that it is all 0s. * set, that it is all 0s.
*/ */
switch(attr->rta_type) { switch (attr->rta_type) {
case RTA_GATEWAY: case RTA_GATEWAY:
/* The gateway of the route. /* The gateway of the route.
* *
@ -638,7 +623,7 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
temp_idx = *static_cast<int *>(RTA_DATA(attr)); temp_idx = *static_cast<int *>(RTA_DATA(attr));
break; break;
case RTA_PRIORITY: case RTA_PRIORITY:
priority = *(uint32_t*)RTA_DATA(attr); priority = *(uint32_t *)RTA_DATA(attr);
break; break;
default: default:
break; break;
@ -656,7 +641,8 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
net->ifid_ = temp_idx; net->ifid_ = temp_idx;
net->route_priority = priority; net->route_priority = priority;
net->gwaddr_ = temp_gw_addr; net->gwaddr_ = temp_gw_addr;
spdlog::debug("network: new default route via {} on if{} metric {}", temp_gw_addr, temp_idx, priority); spdlog::debug("network: new default route via {} on if{} metric {}", temp_gw_addr,
temp_idx, priority);
/* Ask ifname associated with temp_idx as well as carrier status */ /* Ask ifname associated with temp_idx as well as carrier status */
struct ifinfomsg ifinfo_hdr = { struct ifinfomsg ifinfo_hdr = {
@ -664,8 +650,8 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
.ifi_index = temp_idx, .ifi_index = temp_idx,
}; };
int err; int err;
err = nl_send_simple(net->ev_sock_, RTM_GETLINK, NLM_F_REQUEST, err = nl_send_simple(net->ev_sock_, RTM_GETLINK, NLM_F_REQUEST, &ifinfo_hdr,
&ifinfo_hdr, sizeof (ifinfo_hdr)); sizeof(ifinfo_hdr));
if (err < 0) { if (err < 0) {
spdlog::error("network: failed to ask link info: {}", err); spdlog::error("network: failed to ask link info: {}", err);
/* Ask for a dump of all links instead */ /* Ask for a dump of all links instead */
@ -678,10 +664,9 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
net->want_addr_dump_ = true; net->want_addr_dump_ = true;
net->askForStateDump(); net->askForStateDump();
net->thread_timer_.wake_up(); net->thread_timer_.wake_up();
} else if (is_del_event && temp_idx == net->ifid_ } else if (is_del_event && temp_idx == net->ifid_ && net->route_priority == priority) {
&& net->route_priority == priority) { spdlog::debug("network: default route deleted {}/if{} metric {}", net->ifname_, temp_idx,
spdlog::debug("network: default route deleted {}/if{} metric {}", priority);
net->ifname_, temp_idx, priority);
net->clearIface(); net->clearIface();
net->dp.emit(); net->dp.emit();
@ -702,8 +687,7 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
void waybar::modules::Network::askForStateDump(void) { void waybar::modules::Network::askForStateDump(void) {
/* We need to wait until the current dump is done before sending new /* We need to wait until the current dump is done before sending new
* messages. handleEventsDone() is called when a dump is done. */ * messages. handleEventsDone() is called when a dump is done. */
if (dump_in_progress_) if (dump_in_progress_) return;
return;
struct rtgenmsg rt_hdr = { struct rtgenmsg rt_hdr = {
.rtgen_family = AF_UNSPEC, .rtgen_family = AF_UNSPEC,
@ -711,21 +695,18 @@ void waybar::modules::Network::askForStateDump(void) {
if (want_route_dump_) { if (want_route_dump_) {
rt_hdr.rtgen_family = family_; rt_hdr.rtgen_family = family_;
nl_send_simple(ev_sock_, RTM_GETROUTE, NLM_F_DUMP, nl_send_simple(ev_sock_, RTM_GETROUTE, NLM_F_DUMP, &rt_hdr, sizeof(rt_hdr));
&rt_hdr, sizeof (rt_hdr));
want_route_dump_ = false; want_route_dump_ = false;
dump_in_progress_ = true; dump_in_progress_ = true;
} else if (want_link_dump_) { } else if (want_link_dump_) {
nl_send_simple(ev_sock_, RTM_GETLINK, NLM_F_DUMP, nl_send_simple(ev_sock_, RTM_GETLINK, NLM_F_DUMP, &rt_hdr, sizeof(rt_hdr));
&rt_hdr, sizeof (rt_hdr));
want_link_dump_ = false; want_link_dump_ = false;
dump_in_progress_ = true; dump_in_progress_ = true;
} else if (want_addr_dump_) { } else if (want_addr_dump_) {
rt_hdr.rtgen_family = family_; rt_hdr.rtgen_family = family_;
nl_send_simple(ev_sock_, RTM_GETADDR, NLM_F_DUMP, nl_send_simple(ev_sock_, RTM_GETADDR, NLM_F_DUMP, &rt_hdr, sizeof(rt_hdr));
&rt_hdr, sizeof (rt_hdr));
want_addr_dump_ = false; want_addr_dump_ = false;
dump_in_progress_ = true; dump_in_progress_ = true;
} }
@ -741,8 +722,8 @@ int waybar::modules::Network::handleEventsDone(struct nl_msg *msg, void *data) {
int waybar::modules::Network::handleScan(struct nl_msg *msg, void *data) { int waybar::modules::Network::handleScan(struct nl_msg *msg, void *data) {
auto net = static_cast<waybar::modules::Network *>(data); auto net = static_cast<waybar::modules::Network *>(data);
auto gnlh = static_cast<genlmsghdr *>(nlmsg_data(nlmsg_hdr(msg))); auto gnlh = static_cast<genlmsghdr *>(nlmsg_data(nlmsg_hdr(msg)));
struct nlattr * tb[NL80211_ATTR_MAX + 1]; struct nlattr *tb[NL80211_ATTR_MAX + 1];
struct nlattr * bss[NL80211_BSS_MAX + 1]; struct nlattr *bss[NL80211_BSS_MAX + 1];
struct nla_policy bss_policy[NL80211_BSS_MAX + 1]{}; struct nla_policy bss_policy[NL80211_BSS_MAX + 1]{};
bss_policy[NL80211_BSS_TSF].type = NLA_U64; bss_policy[NL80211_BSS_TSF].type = NLA_U64;
bss_policy[NL80211_BSS_FREQUENCY].type = NLA_U32; bss_policy[NL80211_BSS_FREQUENCY].type = NLA_U32;
@ -754,8 +735,8 @@ int waybar::modules::Network::handleScan(struct nl_msg *msg, void *data) {
bss_policy[NL80211_BSS_SIGNAL_UNSPEC].type = NLA_U8; bss_policy[NL80211_BSS_SIGNAL_UNSPEC].type = NLA_U8;
bss_policy[NL80211_BSS_STATUS].type = NLA_U32; bss_policy[NL80211_BSS_STATUS].type = NLA_U32;
if (nla_parse( if (nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_attrlen(gnlh, 0),
tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_attrlen(gnlh, 0), nullptr) < 0) { nullptr) < 0) {
return NL_SKIP; return NL_SKIP;
} }
if (tb[NL80211_ATTR_BSS] == nullptr) { if (tb[NL80211_ATTR_BSS] == nullptr) {
@ -804,7 +785,9 @@ void waybar::modules::Network::parseSignal(struct nlattr **bss) {
const int hardwareOptimum = -45; const int hardwareOptimum = -45;
const int hardwareMin = -90; const int hardwareMin = -90;
const int strength = const int strength =
100 - ((abs(signal_strength_dbm_ - hardwareOptimum) / double{hardwareOptimum - hardwareMin}) * 100); 100 -
((abs(signal_strength_dbm_ - hardwareOptimum) / double{hardwareOptimum - hardwareMin}) *
100);
signal_strength_ = std::clamp(strength, 0, 100); signal_strength_ = std::clamp(strength, 0, 100);
if (signal_strength_dbm_ >= -50) { if (signal_strength_dbm_ >= -50) {
@ -829,7 +812,7 @@ void waybar::modules::Network::parseSignal(struct nlattr **bss) {
void waybar::modules::Network::parseFreq(struct nlattr **bss) { void waybar::modules::Network::parseFreq(struct nlattr **bss) {
if (bss[NL80211_BSS_FREQUENCY] != nullptr) { if (bss[NL80211_BSS_FREQUENCY] != nullptr) {
// in GHz // in GHz
frequency_ = (double) nla_get_u32(bss[NL80211_BSS_FREQUENCY]) / 1000; frequency_ = (double)nla_get_u32(bss[NL80211_BSS_FREQUENCY]) / 1000;
} }
} }
@ -853,9 +836,8 @@ auto waybar::modules::Network::getInfo() -> void {
if (nl_msg == nullptr) { if (nl_msg == nullptr) {
return; return;
} }
if (genlmsg_put( if (genlmsg_put(nl_msg, NL_AUTO_PORT, NL_AUTO_SEQ, nl80211_id_, 0, NLM_F_DUMP,
nl_msg, NL_AUTO_PORT, NL_AUTO_SEQ, nl80211_id_, 0, NLM_F_DUMP, NL80211_CMD_GET_SCAN, 0) == NL80211_CMD_GET_SCAN, 0) == nullptr ||
nullptr ||
nla_put_u32(nl_msg, NL80211_ATTR_IFINDEX, ifid_) < 0) { nla_put_u32(nl_msg, NL80211_ATTR_IFINDEX, ifid_) < 0) {
nlmsg_free(nl_msg); nlmsg_free(nl_msg);
return; return;

View File

@ -50,15 +50,14 @@ void waybar::modules::Pulseaudio::contextStateCb(pa_context *c, void *data) {
case PA_CONTEXT_READY: case PA_CONTEXT_READY:
pa_context_get_server_info(c, serverInfoCb, data); pa_context_get_server_info(c, serverInfoCb, data);
pa_context_set_subscribe_callback(c, subscribeCb, data); pa_context_set_subscribe_callback(c, subscribeCb, data);
pa_context_subscribe( pa_context_subscribe(c,
c, static_cast<enum pa_subscription_mask>(
static_cast<enum pa_subscription_mask>(static_cast<int>(PA_SUBSCRIPTION_MASK_SERVER) | static_cast<int>(PA_SUBSCRIPTION_MASK_SERVER) |
static_cast<int>(PA_SUBSCRIPTION_MASK_SINK) | static_cast<int>(PA_SUBSCRIPTION_MASK_SINK) |
static_cast<int>(PA_SUBSCRIPTION_MASK_SINK_INPUT) | static_cast<int>(PA_SUBSCRIPTION_MASK_SINK_INPUT) |
static_cast<int>(PA_SUBSCRIPTION_MASK_SOURCE) | static_cast<int>(PA_SUBSCRIPTION_MASK_SOURCE) |
static_cast<int>(PA_SUBSCRIPTION_MASK_SOURCE_OUTPUT)), static_cast<int>(PA_SUBSCRIPTION_MASK_SOURCE_OUTPUT)),
nullptr, nullptr, nullptr);
nullptr);
break; break;
case PA_CONTEXT_FAILED: case PA_CONTEXT_FAILED:
pa->mainloop_api_->quit(pa->mainloop_api_, 1); pa->mainloop_api_->quit(pa->mainloop_api_, 1);
@ -81,7 +80,7 @@ bool waybar::modules::Pulseaudio::handleScroll(GdkEventScroll *e) {
if (dir == SCROLL_DIR::NONE) { if (dir == SCROLL_DIR::NONE) {
return true; return true;
} }
if (config_["reverse-scrolling"].asInt() == 1){ if (config_["reverse-scrolling"].asInt() == 1) {
if (dir == SCROLL_DIR::UP) { if (dir == SCROLL_DIR::UP) {
dir = SCROLL_DIR::DOWN; dir = SCROLL_DIR::DOWN;
} else if (dir == SCROLL_DIR::DOWN) { } else if (dir == SCROLL_DIR::DOWN) {
@ -111,7 +110,7 @@ bool waybar::modules::Pulseaudio::handleScroll(GdkEventScroll *e) {
/* /*
* Called when an event we subscribed to occurs. * Called when an event we subscribed to occurs.
*/ */
void waybar::modules::Pulseaudio::subscribeCb(pa_context * context, void waybar::modules::Pulseaudio::subscribeCb(pa_context *context,
pa_subscription_event_type_t type, uint32_t idx, pa_subscription_event_type_t type, uint32_t idx,
void *data) { void *data) {
unsigned facility = type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK; unsigned facility = type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK;
@ -164,8 +163,7 @@ void waybar::modules::Pulseaudio::sourceInfoCb(pa_context * /*context*/, const p
*/ */
void waybar::modules::Pulseaudio::sinkInfoCb(pa_context * /*context*/, const pa_sink_info *i, void waybar::modules::Pulseaudio::sinkInfoCb(pa_context * /*context*/, const pa_sink_info *i,
int /*eol*/, void *data) { int /*eol*/, void *data) {
if (i == nullptr) if (i == nullptr) return;
return;
auto pa = static_cast<waybar::modules::Pulseaudio *>(data); auto pa = static_cast<waybar::modules::Pulseaudio *>(data);
if (pa->current_sink_name_ == i->name) { if (pa->current_sink_name_ == i->name) {
@ -212,15 +210,7 @@ void waybar::modules::Pulseaudio::serverInfoCb(pa_context *context, const pa_ser
} }
static const std::array<std::string, 9> ports = { static const std::array<std::string, 9> ports = {
"headphone", "headphone", "speaker", "hdmi", "headset", "hands-free", "portable", "car", "hifi", "phone",
"speaker",
"hdmi",
"headset",
"hands-free",
"portable",
"car",
"hifi",
"phone",
}; };
const std::vector<std::string> waybar::modules::Pulseaudio::getPulseIcon() const { const std::vector<std::string> waybar::modules::Pulseaudio::getPulseIcon() const {
@ -260,8 +250,7 @@ auto waybar::modules::Pulseaudio::update() -> void {
label_.get_style_context()->remove_class("muted"); label_.get_style_context()->remove_class("muted");
label_.get_style_context()->remove_class("sink-muted"); label_.get_style_context()->remove_class("sink-muted");
} }
format = format = config_[format_name].isString() ? config_[format_name].asString() : format;
config_[format_name].isString() ? config_[format_name].asString() : format;
} }
// TODO: find a better way to split source/sink // TODO: find a better way to split source/sink
std::string format_source = "{volume}%"; std::string format_source = "{volume}%";
@ -277,13 +266,10 @@ auto waybar::modules::Pulseaudio::update() -> void {
} }
} }
format_source = fmt::format(format_source, fmt::arg("volume", source_volume_)); format_source = fmt::format(format_source, fmt::arg("volume", source_volume_));
label_.set_markup(fmt::format(format, label_.set_markup(fmt::format(
fmt::arg("desc", desc_), format, fmt::arg("desc", desc_), fmt::arg("volume", volume_),
fmt::arg("volume", volume_), fmt::arg("format_source", format_source), fmt::arg("source_volume", source_volume_),
fmt::arg("format_source", format_source), fmt::arg("source_desc", source_desc_), fmt::arg("icon", getIcon(volume_, getPulseIcon()))));
fmt::arg("source_volume", source_volume_),
fmt::arg("source_desc", source_desc_),
fmt::arg("icon", getIcon(volume_, getPulseIcon()))));
getState(volume_); getState(volume_);
if (tooltipEnabled()) { if (tooltipEnabled()) {
@ -292,11 +278,8 @@ auto waybar::modules::Pulseaudio::update() -> void {
} }
if (!tooltip_format.empty()) { if (!tooltip_format.empty()) {
label_.set_tooltip_text(fmt::format( label_.set_tooltip_text(fmt::format(
tooltip_format, tooltip_format, fmt::arg("desc", desc_), fmt::arg("volume", volume_),
fmt::arg("desc", desc_), fmt::arg("format_source", format_source), fmt::arg("source_volume", source_volume_),
fmt::arg("volume", volume_),
fmt::arg("format_source", format_source),
fmt::arg("source_volume", source_volume_),
fmt::arg("source_desc", source_desc_), fmt::arg("source_desc", source_desc_),
fmt::arg("icon", getIcon(volume_, getPulseIcon())))); fmt::arg("icon", getIcon(volume_, getPulseIcon()))));
} else { } else {

View File

@ -1,3 +1,5 @@
#include "modules/river/tags.hpp"
#include <gtkmm/button.h> #include <gtkmm/button.h>
#include <gtkmm/label.h> #include <gtkmm/label.h>
#include <spdlog/spdlog.h> #include <spdlog/spdlog.h>
@ -6,7 +8,6 @@
#include <algorithm> #include <algorithm>
#include "client.hpp" #include "client.hpp"
#include "modules/river/tags.hpp"
#include "xdg-output-unstable-v1-client-protocol.h" #include "xdg-output-unstable-v1-client-protocol.h"
namespace waybar::modules::river { namespace waybar::modules::river {
@ -44,7 +45,7 @@ static void listen_command_failure(void *data,
spdlog::error("failure when selecting/toggling tags {}", output); spdlog::error("failure when selecting/toggling tags {}", output);
} }
static const zriver_command_callback_v1_listener command_callback_listener_impl { static const zriver_command_callback_v1_listener command_callback_listener_impl{
.success = listen_command_success, .success = listen_command_success,
.failure = listen_command_failure, .failure = listen_command_failure,
}; };
@ -77,7 +78,6 @@ static void handle_global_remove(void *data, struct wl_registry *registry, uint3
/* Ignore event */ /* Ignore event */
} }
static const wl_registry_listener registry_listener_impl = {.global = handle_global, static const wl_registry_listener registry_listener_impl = {.global = handle_global,
.global_remove = handle_global_remove}; .global_remove = handle_global_remove};
@ -89,7 +89,7 @@ Tags::Tags(const std::string &id, const waybar::Bar &bar, const Json::Value &con
bar_(bar), bar_(bar),
box_{bar.vertical ? Gtk::ORIENTATION_VERTICAL : Gtk::ORIENTATION_HORIZONTAL, 0}, box_{bar.vertical ? Gtk::ORIENTATION_VERTICAL : Gtk::ORIENTATION_HORIZONTAL, 0},
output_status_{nullptr} { output_status_{nullptr} {
struct wl_display * display = Client::inst()->wl_display; struct wl_display *display = Client::inst()->wl_display;
struct wl_registry *registry = wl_display_get_registry(display); struct wl_registry *registry = wl_display_get_registry(display);
wl_registry_add_listener(registry, &registry_listener_impl, this); wl_registry_add_listener(registry, &registry_listener_impl, this);
wl_display_roundtrip(display); wl_display_roundtrip(display);
@ -119,7 +119,7 @@ Tags::Tags(const std::string &id, const waybar::Bar &bar, const Json::Value &con
std::vector<std::string> tag_labels(num_tags); std::vector<std::string> tag_labels(num_tags);
for (uint32_t tag = 0; tag < num_tags; ++tag) { for (uint32_t tag = 0; tag < num_tags; ++tag) {
tag_labels[tag] = std::to_string(tag+1); tag_labels[tag] = std::to_string(tag + 1);
} }
const Json::Value custom_labels = config["tag-labels"]; const Json::Value custom_labels = config["tag-labels"];
if (custom_labels.isArray() && !custom_labels.empty()) { if (custom_labels.isArray() && !custom_labels.empty()) {
@ -134,8 +134,10 @@ Tags::Tags(const std::string &id, const waybar::Bar &bar, const Json::Value &con
button.set_relief(Gtk::RELIEF_NONE); button.set_relief(Gtk::RELIEF_NONE);
box_.pack_start(button, false, false, 0); box_.pack_start(button, false, false, 0);
if (!config_["disable-click"].asBool()) { if (!config_["disable-click"].asBool()) {
button.signal_clicked().connect(sigc::bind(sigc::mem_fun(*this, &Tags::handle_primary_clicked), i)); button.signal_clicked().connect(
button.signal_button_press_event().connect(sigc::bind(sigc::mem_fun(*this, &Tags::handle_button_press), i)); sigc::bind(sigc::mem_fun(*this, &Tags::handle_primary_clicked), i));
button.signal_button_press_event().connect(
sigc::bind(sigc::mem_fun(*this, &Tags::handle_button_press), i));
} }
button.show(); button.show();
i <<= 1; i <<= 1;

View File

@ -1,4 +1,5 @@
#include "modules/simpleclock.hpp" #include "modules/simpleclock.hpp"
#include <time.h> #include <time.h>
waybar::modules::Clock::Clock(const std::string& id, const Json::Value& config) waybar::modules::Clock::Clock(const std::string& id, const Json::Value& config)

View File

@ -1,14 +1,16 @@
#include "modules/sndio.hpp" #include "modules/sndio.hpp"
#include <fmt/format.h>
#include <poll.h>
#include <spdlog/spdlog.h>
#include <algorithm> #include <algorithm>
#include <cstdlib> #include <cstdlib>
#include <poll.h>
#include <fmt/format.h>
#include <spdlog/spdlog.h>
namespace waybar::modules { namespace waybar::modules {
void ondesc(void *arg, struct sioctl_desc *d, int curval) { void ondesc(void *arg, struct sioctl_desc *d, int curval) {
auto self = static_cast<Sndio*>(arg); auto self = static_cast<Sndio *>(arg);
if (d == NULL) { if (d == NULL) {
// d is NULL when the list is done // d is NULL when the list is done
return; return;
@ -17,7 +19,7 @@ void ondesc(void *arg, struct sioctl_desc *d, int curval) {
} }
void onval(void *arg, unsigned int addr, unsigned int val) { void onval(void *arg, unsigned int addr, unsigned int val) {
auto self = static_cast<Sndio*>(arg); auto self = static_cast<Sndio *>(arg);
self->put_val(addr, val); self->put_val(addr, val);
} }
@ -52,10 +54,8 @@ Sndio::Sndio(const std::string &id, const Json::Value &config)
event_box_.show(); event_box_.show();
event_box_.add_events(Gdk::SCROLL_MASK | Gdk::SMOOTH_SCROLL_MASK | Gdk::BUTTON_PRESS_MASK); event_box_.add_events(Gdk::SCROLL_MASK | Gdk::SMOOTH_SCROLL_MASK | Gdk::BUTTON_PRESS_MASK);
event_box_.signal_scroll_event().connect( event_box_.signal_scroll_event().connect(sigc::mem_fun(*this, &Sndio::handleScroll));
sigc::mem_fun(*this, &Sndio::handleScroll)); event_box_.signal_button_press_event().connect(sigc::mem_fun(*this, &Sndio::handleToggle));
event_box_.signal_button_press_event().connect(
sigc::mem_fun(*this, &Sndio::handleToggle));
thread_ = [this] { thread_ = [this] {
dp.emit(); dp.emit();
@ -80,7 +80,7 @@ Sndio::Sndio(const std::string &id, const Json::Value &config)
while (thread_.isRunning()) { while (thread_.isRunning()) {
try { try {
connect_to_sndio(); connect_to_sndio();
} catch(std::runtime_error const& e) { } catch (std::runtime_error const &e) {
// avoid leaking hdl_ // avoid leaking hdl_
if (hdl_) { if (hdl_) {
sioctl_close(hdl_); sioctl_close(hdl_);
@ -98,9 +98,7 @@ Sndio::Sndio(const std::string &id, const Json::Value &config)
}; };
} }
Sndio::~Sndio() { Sndio::~Sndio() { sioctl_close(hdl_); }
sioctl_close(hdl_);
}
auto Sndio::update() -> void { auto Sndio::update() -> void {
auto format = format_; auto format = format_;
@ -112,9 +110,7 @@ auto Sndio::update() -> void {
label_.get_style_context()->remove_class("muted"); label_.get_style_context()->remove_class("muted");
} }
label_.set_markup(fmt::format(format, label_.set_markup(fmt::format(format, fmt::arg("volume", vol), fmt::arg("raw_value", volume_)));
fmt::arg("volume", vol),
fmt::arg("raw_value", volume_)));
ALabel::update(); ALabel::update();
} }
@ -177,7 +173,7 @@ bool Sndio::handleScroll(GdkEventScroll *e) {
return true; return true;
} }
bool Sndio::handleToggle(GdkEventButton* const& e) { bool Sndio::handleToggle(GdkEventButton *const &e) {
// toggle mute only when no user provided events are configured // toggle mute only when no user provided events are configured
if (config_["on-click"].isString()) { if (config_["on-click"].isString()) {
return AModule::handleToggle(e); return AModule::handleToggle(e);

View File

@ -1,4 +1,5 @@
#include "modules/sni/host.hpp" #include "modules/sni/host.hpp"
#include <fmt/ostream.h> #include <fmt/ostream.h>
#include <spdlog/spdlog.h> #include <spdlog/spdlog.h>
@ -32,8 +33,7 @@ Host::~Host() {
} }
void Host::busAcquired(const Glib::RefPtr<Gio::DBus::Connection>& conn, Glib::ustring name) { void Host::busAcquired(const Glib::RefPtr<Gio::DBus::Connection>& conn, Glib::ustring name) {
watcher_id_ = Gio::DBus::watch_name(conn, watcher_id_ = Gio::DBus::watch_name(conn, "org.kde.StatusNotifierWatcher",
"org.kde.StatusNotifierWatcher",
sigc::mem_fun(*this, &Host::nameAppeared), sigc::mem_fun(*this, &Host::nameAppeared),
sigc::mem_fun(*this, &Host::nameVanished)); sigc::mem_fun(*this, &Host::nameVanished));
} }
@ -45,13 +45,8 @@ void Host::nameAppeared(const Glib::RefPtr<Gio::DBus::Connection>& conn, const G
return; return;
} }
cancellable_ = g_cancellable_new(); cancellable_ = g_cancellable_new();
sn_watcher_proxy_new(conn->gobj(), sn_watcher_proxy_new(conn->gobj(), G_DBUS_PROXY_FLAGS_NONE, "org.kde.StatusNotifierWatcher",
G_DBUS_PROXY_FLAGS_NONE, "/StatusNotifierWatcher", cancellable_, &Host::proxyReady, this);
"org.kde.StatusNotifierWatcher",
"/StatusNotifierWatcher",
cancellable_,
&Host::proxyReady,
this);
} }
void Host::nameVanished(const Glib::RefPtr<Gio::DBus::Connection>& conn, const Glib::ustring name) { void Host::nameVanished(const Glib::RefPtr<Gio::DBus::Connection>& conn, const Glib::ustring name) {
@ -76,8 +71,8 @@ void Host::proxyReady(GObject* src, GAsyncResult* res, gpointer data) {
g_error_free(error); g_error_free(error);
return; return;
} }
sn_watcher_call_register_host( sn_watcher_call_register_host(host->watcher_, host->object_path_.c_str(), host->cancellable_,
host->watcher_, host->object_path_.c_str(), host->cancellable_, &Host::registerHost, data); &Host::registerHost, data);
} }
void Host::registerHost(GObject* src, GAsyncResult* res, gpointer data) { void Host::registerHost(GObject* src, GAsyncResult* res, gpointer data) {

View File

@ -49,7 +49,7 @@ Item::Item(const std::string& bn, const std::string& op, const Json::Value& conf
show_passive_ = config["show-passive-items"].asBool(); show_passive_ = config["show-passive-items"].asBool();
} }
auto &window = const_cast<Bar &>(bar).window; auto& window = const_cast<Bar&>(bar).window;
window.signal_configure_event().connect_notify(sigc::mem_fun(*this, &Item::onConfigure)); window.signal_configure_event().connect_notify(sigc::mem_fun(*this, &Item::onConfigure));
event_box.add(image); event_box.add(image);
event_box.add_events(Gdk::BUTTON_PRESS_MASK | Gdk::SCROLL_MASK | Gdk::SMOOTH_SCROLL_MASK); event_box.add_events(Gdk::BUTTON_PRESS_MASK | Gdk::SCROLL_MASK | Gdk::SMOOTH_SCROLL_MASK);
@ -62,18 +62,12 @@ Item::Item(const std::string& bn, const std::string& op, const Json::Value& conf
cancellable_ = Gio::Cancellable::create(); cancellable_ = Gio::Cancellable::create();
auto interface = Glib::wrap(sn_item_interface_info(), true); auto interface = Glib::wrap(sn_item_interface_info(), true);
Gio::DBus::Proxy::create_for_bus(Gio::DBus::BusType::BUS_TYPE_SESSION, Gio::DBus::Proxy::create_for_bus(Gio::DBus::BusType::BUS_TYPE_SESSION, bus_name, object_path,
bus_name, SNI_INTERFACE_NAME, sigc::mem_fun(*this, &Item::proxyReady),
object_path, cancellable_, interface);
SNI_INTERFACE_NAME,
sigc::mem_fun(*this, &Item::proxyReady),
cancellable_,
interface);
} }
void Item::onConfigure(GdkEventConfigure* ev) { void Item::onConfigure(GdkEventConfigure* ev) { this->updateImage(); }
this->updateImage();
}
void Item::proxyReady(Glib::RefPtr<Gio::AsyncResult>& result) { void Item::proxyReady(Glib::RefPtr<Gio::AsyncResult>& result) {
try { try {
@ -167,16 +161,10 @@ void Item::setProperty(const Glib::ustring& name, Glib::VariantBase& value) {
} }
} catch (const Glib::Error& err) { } catch (const Glib::Error& err) {
spdlog::warn("Failed to set tray item property: {}.{}, value = {}, err = {}", spdlog::warn("Failed to set tray item property: {}.{}, value = {}, err = {}",
id.empty() ? bus_name : id, id.empty() ? bus_name : id, name, value, err.what());
name,
value,
err.what());
} catch (const std::exception& err) { } catch (const std::exception& err) {
spdlog::warn("Failed to set tray item property: {}.{}, value = {}, err = {}", spdlog::warn("Failed to set tray item property: {}.{}, value = {}, err = {}",
id.empty() ? bus_name : id, id.empty() ? bus_name : id, name, value, err.what());
name,
value,
err.what());
} }
} }
@ -199,8 +187,7 @@ void Item::getUpdatedProperties() {
auto params = Glib::VariantContainerBase::create_tuple( auto params = Glib::VariantContainerBase::create_tuple(
{Glib::Variant<Glib::ustring>::create(SNI_INTERFACE_NAME)}); {Glib::Variant<Glib::ustring>::create(SNI_INTERFACE_NAME)});
proxy_->call("org.freedesktop.DBus.Properties.GetAll", proxy_->call("org.freedesktop.DBus.Properties.GetAll",
sigc::mem_fun(*this, &Item::processUpdatedProperties), sigc::mem_fun(*this, &Item::processUpdatedProperties), params);
params);
}; };
void Item::processUpdatedProperties(Glib::RefPtr<Gio::AsyncResult>& _result) { void Item::processUpdatedProperties(Glib::RefPtr<Gio::AsyncResult>& _result) {
@ -303,14 +290,8 @@ Glib::RefPtr<Gdk::Pixbuf> Item::extractPixBuf(GVariant* variant) {
array[i + 2] = array[i + 3]; array[i + 2] = array[i + 3];
array[i + 3] = alpha; array[i + 3] = alpha;
} }
return Gdk::Pixbuf::create_from_data(array, return Gdk::Pixbuf::create_from_data(array, Gdk::Colorspace::COLORSPACE_RGB, true, 8, lwidth,
Gdk::Colorspace::COLORSPACE_RGB, lheight, 4 * lwidth, &pixbuf_data_deleter);
true,
8,
lwidth,
lheight,
4 * lwidth,
&pixbuf_data_deleter);
} }
return Glib::RefPtr<Gdk::Pixbuf>{}; return Glib::RefPtr<Gdk::Pixbuf>{};
} }
@ -374,15 +355,15 @@ Glib::RefPtr<Gdk::Pixbuf> Item::getIconByName(const std::string& name, int reque
tmp_size = request_size; tmp_size = request_size;
} }
if (!icon_theme_path.empty() && if (!icon_theme_path.empty() &&
icon_theme->lookup_icon( icon_theme->lookup_icon(name.c_str(), tmp_size,
name.c_str(), tmp_size, Gtk::IconLookupFlags::ICON_LOOKUP_FORCE_SIZE)) { Gtk::IconLookupFlags::ICON_LOOKUP_FORCE_SIZE)) {
return icon_theme->load_icon( return icon_theme->load_icon(name.c_str(), tmp_size,
name.c_str(), tmp_size, Gtk::IconLookupFlags::ICON_LOOKUP_FORCE_SIZE); Gtk::IconLookupFlags::ICON_LOOKUP_FORCE_SIZE);
} }
Glib::RefPtr<Gtk::IconTheme> default_theme = Gtk::IconTheme::get_default(); Glib::RefPtr<Gtk::IconTheme> default_theme = Gtk::IconTheme::get_default();
default_theme->rescan_if_needed(); default_theme->rescan_if_needed();
return default_theme->load_icon( return default_theme->load_icon(name.c_str(), tmp_size,
name.c_str(), tmp_size, Gtk::IconLookupFlags::ICON_LOOKUP_FORCE_SIZE); Gtk::IconLookupFlags::ICON_LOOKUP_FORCE_SIZE);
} }
double Item::getScaledIconSize() { double Item::getScaledIconSize() {

View File

@ -1,4 +1,5 @@
#include "modules/sni/tray.hpp" #include "modules/sni/tray.hpp"
#include <spdlog/spdlog.h> #include <spdlog/spdlog.h>
namespace waybar::modules::SNI { namespace waybar::modules::SNI {

View File

@ -1,4 +1,5 @@
#include "modules/sni/watcher.hpp" #include "modules/sni/watcher.hpp"
#include <spdlog/spdlog.h> #include <spdlog/spdlog.h>
using namespace waybar::modules::SNI; using namespace waybar::modules::SNI;
@ -29,8 +30,8 @@ Watcher::~Watcher() {
void Watcher::busAcquired(const Glib::RefPtr<Gio::DBus::Connection>& conn, Glib::ustring name) { void Watcher::busAcquired(const Glib::RefPtr<Gio::DBus::Connection>& conn, Glib::ustring name) {
GError* error = nullptr; GError* error = nullptr;
g_dbus_interface_skeleton_export( g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(watcher_), conn->gobj(),
G_DBUS_INTERFACE_SKELETON(watcher_), conn->gobj(), "/StatusNotifierWatcher", &error); "/StatusNotifierWatcher", &error);
if (error != nullptr) { if (error != nullptr) {
// Don't print an error when a watcher is already present // Don't print an error when a watcher is already present
if (error->code != 2) { if (error->code != 2) {
@ -39,10 +40,10 @@ void Watcher::busAcquired(const Glib::RefPtr<Gio::DBus::Connection>& conn, Glib:
g_error_free(error); g_error_free(error);
return; return;
} }
g_signal_connect_swapped( g_signal_connect_swapped(watcher_, "handle-register-item",
watcher_, "handle-register-item", G_CALLBACK(&Watcher::handleRegisterItem), this); G_CALLBACK(&Watcher::handleRegisterItem), this);
g_signal_connect_swapped( g_signal_connect_swapped(watcher_, "handle-register-host",
watcher_, "handle-register-host", G_CALLBACK(&Watcher::handleRegisterHost), this); G_CALLBACK(&Watcher::handleRegisterHost), this);
} }
gboolean Watcher::handleRegisterHost(Watcher* obj, GDBusMethodInvocation* invocation, gboolean Watcher::handleRegisterHost(Watcher* obj, GDBusMethodInvocation* invocation,
@ -55,22 +56,16 @@ gboolean Watcher::handleRegisterHost(Watcher* obj, GDBusMethodInvocation* invoca
object_path = service; object_path = service;
} }
if (g_dbus_is_name(bus_name) == FALSE) { if (g_dbus_is_name(bus_name) == FALSE) {
g_dbus_method_invocation_return_error(invocation, g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
G_DBUS_ERROR, "D-Bus bus name '%s' is not valid", bus_name);
G_DBUS_ERROR_INVALID_ARGS,
"D-Bus bus name '%s' is not valid",
bus_name);
return TRUE; return TRUE;
} }
auto watch = gfWatchFind(obj->hosts_, bus_name, object_path); auto watch = gfWatchFind(obj->hosts_, bus_name, object_path);
if (watch != nullptr) { if (watch != nullptr) {
g_dbus_method_invocation_return_error( g_dbus_method_invocation_return_error(
invocation, invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"Status Notifier Host with bus name '%s' and object path '%s' is already registered", "Status Notifier Host with bus name '%s' and object path '%s' is already registered",
bus_name, bus_name, object_path);
object_path);
return TRUE; return TRUE;
} }
watch = gfWatchNew(GF_WATCH_TYPE_HOST, service, bus_name, object_path, obj); watch = gfWatchNew(GF_WATCH_TYPE_HOST, service, bus_name, object_path, obj);
@ -93,18 +88,14 @@ gboolean Watcher::handleRegisterItem(Watcher* obj, GDBusMethodInvocation* invoca
object_path = service; object_path = service;
} }
if (g_dbus_is_name(bus_name) == FALSE) { if (g_dbus_is_name(bus_name) == FALSE) {
g_dbus_method_invocation_return_error(invocation, g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
G_DBUS_ERROR, "D-Bus bus name '%s' is not valid", bus_name);
G_DBUS_ERROR_INVALID_ARGS,
"D-Bus bus name '%s' is not valid",
bus_name);
return TRUE; return TRUE;
} }
auto watch = gfWatchFind(obj->items_, bus_name, object_path); auto watch = gfWatchFind(obj->items_, bus_name, object_path);
if (watch != nullptr) { if (watch != nullptr) {
g_warning("Status Notifier Item with bus name '%s' and object path '%s' is already registered", g_warning("Status Notifier Item with bus name '%s' and object path '%s' is already registered",
bus_name, bus_name, object_path);
object_path);
sn_watcher_complete_register_item(obj->watcher_, invocation); sn_watcher_complete_register_item(obj->watcher_, invocation);
return TRUE; return TRUE;
} }
@ -152,13 +143,8 @@ Watcher::GfWatch* Watcher::gfWatchNew(GfWatchType type, const gchar* service, co
watch->service = g_strdup(service); watch->service = g_strdup(service);
watch->bus_name = g_strdup(bus_name); watch->bus_name = g_strdup(bus_name);
watch->object_path = g_strdup(object_path); watch->object_path = g_strdup(object_path);
watch->watch_id = g_bus_watch_name(G_BUS_TYPE_SESSION, watch->watch_id = g_bus_watch_name(G_BUS_TYPE_SESSION, bus_name, G_BUS_NAME_WATCHER_FLAGS_NONE,
bus_name, nullptr, &Watcher::nameVanished, watch, nullptr);
G_BUS_NAME_WATCHER_FLAGS_NONE,
nullptr,
&Watcher::nameVanished,
watch,
nullptr);
return watch; return watch;
} }

View File

@ -79,11 +79,8 @@ void BarIpcClient::onIpcEvent(const struct Ipc::ipc_response& res) {
} }
void BarIpcClient::onConfigUpdate(const swaybar_config& config) { void BarIpcClient::onConfigUpdate(const swaybar_config& config) {
spdlog::info("config update for {}: id {}, mode {}, hidden_state {}", spdlog::info("config update for {}: id {}, mode {}, hidden_state {}", bar_.bar_id, config.id,
bar_.bar_id, config.mode, config.hidden_state);
config.id,
config.mode,
config.hidden_state);
bar_config_ = config; bar_config_ = config;
update(); update();
} }

View File

@ -1,4 +1,5 @@
#include "modules/sway/ipc/client.hpp" #include "modules/sway/ipc/client.hpp"
#include <fcntl.h> #include <fcntl.h>
namespace waybar::modules::sway { namespace waybar::modules::sway {

View File

@ -95,20 +95,17 @@ void Language::onEvent(const struct Ipc::ipc_response& res) {
auto Language::update() -> void { auto Language::update() -> void {
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
auto display_layout = trim(fmt::format(format_, auto display_layout = trim(fmt::format(
fmt::arg("short", layout_.short_name), format_, fmt::arg("short", layout_.short_name),
fmt::arg("shortDescription", layout_.short_description), fmt::arg("shortDescription", layout_.short_description), fmt::arg("long", layout_.full_name),
fmt::arg("long", layout_.full_name), fmt::arg("variant", layout_.variant), fmt::arg("flag", layout_.country_flag())));
fmt::arg("variant", layout_.variant),
fmt::arg("flag", layout_.country_flag())));
label_.set_markup(display_layout); label_.set_markup(display_layout);
if (tooltipEnabled()) { if (tooltipEnabled()) {
if (tooltip_format_ != "") { if (tooltip_format_ != "") {
auto tooltip_display_layout = trim(fmt::format(tooltip_format_, auto tooltip_display_layout = trim(
fmt::arg("short", layout_.short_name), fmt::format(tooltip_format_, fmt::arg("short", layout_.short_name),
fmt::arg("shortDescription", layout_.short_description), fmt::arg("shortDescription", layout_.short_description),
fmt::arg("long", layout_.full_name), fmt::arg("long", layout_.full_name), fmt::arg("variant", layout_.variant),
fmt::arg("variant", layout_.variant),
fmt::arg("flag", layout_.country_flag()))); fmt::arg("flag", layout_.country_flag())));
label_.set_tooltip_markup(tooltip_display_layout); label_.set_tooltip_markup(tooltip_display_layout);
} else { } else {
@ -155,8 +152,7 @@ auto Language::init_layouts_map(const std::vector<std::string>& used_layouts) ->
std::map<std::string, int> short_name_to_number_map; std::map<std::string, int> short_name_to_number_map;
for (const auto& used_layout_name : used_layouts) { for (const auto& used_layout_name : used_layouts) {
auto found = layouts_map_.find(used_layout_name); auto found = layouts_map_.find(used_layout_name);
if (found == layouts_map_.end()) if (found == layouts_map_.end()) continue;
continue;
auto used_layout = &found->second; auto used_layout = &found->second;
auto layouts_with_same_name_list = found_by_short_names[used_layout->short_name]; auto layouts_with_same_name_list = found_by_short_names[used_layout->short_name];
if (layouts_with_same_name_list.size() < 2) { if (layouts_with_same_name_list.size() < 2) {
@ -169,10 +165,8 @@ auto Language::init_layouts_map(const std::vector<std::string>& used_layouts) ->
if (displayed_short_flag != static_cast<std::byte>(0)) { if (displayed_short_flag != static_cast<std::byte>(0)) {
int& number = short_name_to_number_map[used_layout->short_name]; int& number = short_name_to_number_map[used_layout->short_name];
used_layout->short_name = used_layout->short_name = used_layout->short_name + std::to_string(number);
used_layout->short_name + std::to_string(number); used_layout->short_description = used_layout->short_description + std::to_string(number);
used_layout->short_description =
used_layout->short_description + std::to_string(number);
++number; ++number;
} }
} }
@ -205,7 +199,8 @@ auto Language::XKBContext::next_layout() -> Layout* {
base_layouts_by_name_.emplace(name, xkb_layout_); base_layouts_by_name_.emplace(name, xkb_layout_);
} else { } else {
auto base_layout = base_layouts_by_name_[name]; auto base_layout = base_layouts_by_name_[name];
short_description = base_layout == nullptr ? "" : std::string(rxkb_layout_get_brief(base_layout)); short_description =
base_layout == nullptr ? "" : std::string(rxkb_layout_get_brief(base_layout));
} }
delete layout_; delete layout_;
layout_ = new Layout{description, name, variant, short_description}; layout_ = new Layout{description, name, variant, short_description};

View File

@ -1,4 +1,5 @@
#include "modules/sway/mode.hpp" #include "modules/sway/mode.hpp"
#include <spdlog/spdlog.h> #include <spdlog/spdlog.h>
namespace waybar::modules::sway { namespace waybar::modules::sway {

View File

@ -70,11 +70,11 @@ std::optional<Glib::ustring> getIconName(const std::string& app_id) {
} }
return icon_name; return icon_name;
} catch (Glib::FileError& error) { } catch (Glib::FileError& error) {
spdlog::warn( spdlog::warn("Error while loading desktop file {}: {}", desktop_file_path.value(),
"Error while loading desktop file {}: {}", desktop_file_path.value(), error.what().c_str()); error.what().c_str());
} catch (Glib::KeyFileError& error) { } catch (Glib::KeyFileError& error) {
spdlog::warn( spdlog::warn("Error while loading desktop file {}: {}", desktop_file_path.value(),
"Error while loading desktop file {}: {}", desktop_file_path.value(), error.what().c_str()); error.what().c_str());
} }
return {}; return {};
} }
@ -114,8 +114,8 @@ auto Window::update() -> void {
bar_.window.get_style_context()->remove_class("solo"); bar_.window.get_style_context()->remove_class("solo");
bar_.window.get_style_context()->remove_class("empty"); bar_.window.get_style_context()->remove_class("empty");
} }
label_.set_markup(fmt::format(format_, fmt::arg("title", rewriteTitle(window_)), label_.set_markup(
fmt::arg("app_id", app_id_))); fmt::format(format_, fmt::arg("title", rewriteTitle(window_)), fmt::arg("app_id", app_id_)));
if (tooltipEnabled()) { if (tooltipEnabled()) {
label_.set_tooltip_text(window_); label_.set_tooltip_text(window_);
} }
@ -126,28 +126,26 @@ auto Window::update() -> void {
int leafNodesInWorkspace(const Json::Value& node) { int leafNodesInWorkspace(const Json::Value& node) {
auto const& nodes = node["nodes"]; auto const& nodes = node["nodes"];
auto const& floating_nodes = node["floating_nodes"]; auto const& floating_nodes = node["floating_nodes"];
if(nodes.empty() && floating_nodes.empty()) { if (nodes.empty() && floating_nodes.empty()) {
if(node["type"] == "workspace") if (node["type"] == "workspace")
return 0; return 0;
else else
return 1; return 1;
} }
int sum = 0; int sum = 0;
if (!nodes.empty()) { if (!nodes.empty()) {
for(auto const& node : nodes) for (auto const& node : nodes) sum += leafNodesInWorkspace(node);
sum += leafNodesInWorkspace(node);
} }
if (!floating_nodes.empty()) { if (!floating_nodes.empty()) {
for(auto const& node : floating_nodes) for (auto const& node : floating_nodes) sum += leafNodesInWorkspace(node);
sum += leafNodesInWorkspace(node);
} }
return sum; return sum;
} }
std::tuple<std::size_t, int, std::string, std::string> gfnWithWorkspace( std::tuple<std::size_t, int, std::string, std::string> gfnWithWorkspace(
const Json::Value& nodes, std::string& output, const Json::Value& config_, const Json::Value& nodes, std::string& output, const Json::Value& config_, const Bar& bar_,
const Bar& bar_, Json::Value& parentWorkspace) { Json::Value& parentWorkspace) {
for(auto const& node : nodes) { for (auto const& node : nodes) {
if (node["output"].isString()) { if (node["output"].isString()) {
output = node["output"].asString(); output = node["output"].asString();
} }
@ -158,23 +156,20 @@ std::tuple<std::size_t, int, std::string, std::string> gfnWithWorkspace(
auto app_id = node["app_id"].isString() ? node["app_id"].asString() auto app_id = node["app_id"].isString() ? node["app_id"].asString()
: node["window_properties"]["instance"].asString(); : node["window_properties"]["instance"].asString();
int nb = node.size(); int nb = node.size();
if(parentWorkspace != 0) if (parentWorkspace != 0) nb = leafNodesInWorkspace(parentWorkspace);
nb = leafNodesInWorkspace(parentWorkspace); return {nb, node["id"].asInt(), Glib::Markup::escape_text(node["name"].asString()), app_id};
return {nb,
node["id"].asInt(),
Glib::Markup::escape_text(node["name"].asString()),
app_id};
} }
} }
// iterate // iterate
if(node["type"] == "workspace") if (node["type"] == "workspace") parentWorkspace = node;
parentWorkspace = node; auto [nb, id, name, app_id] =
auto [nb, id, name, app_id] = gfnWithWorkspace(node["nodes"], output, config_, bar_, parentWorkspace); gfnWithWorkspace(node["nodes"], output, config_, bar_, parentWorkspace);
if (id > -1 && !name.empty()) { if (id > -1 && !name.empty()) {
return {nb, id, name, app_id}; return {nb, id, name, app_id};
} }
// Search for floating node // Search for floating node
std::tie(nb, id, name, app_id) = gfnWithWorkspace(node["floating_nodes"], output, config_, bar_, parentWorkspace); std::tie(nb, id, name, app_id) =
gfnWithWorkspace(node["floating_nodes"], output, config_, bar_, parentWorkspace);
if (id > -1 && !name.empty()) { if (id > -1 && !name.empty()) {
return {nb, id, name, app_id}; return {nb, id, name, app_id};
} }

View File

@ -13,7 +13,7 @@ namespace waybar::modules::sway {
int Workspaces::convertWorkspaceNameToNum(std::string name) { int Workspaces::convertWorkspaceNameToNum(std::string name) {
if (isdigit(name[0])) { if (isdigit(name[0])) {
errno = 0; errno = 0;
char * endptr = NULL; char *endptr = NULL;
long long parsed_num = strtoll(name.c_str(), &endptr, 10); long long parsed_num = strtoll(name.c_str(), &endptr, 10);
if (errno != 0 || parsed_num > INT32_MAX || parsed_num < 0 || endptr == name.c_str()) { if (errno != 0 || parsed_num > INT32_MAX || parsed_num < 0 || endptr == name.c_str()) {
return -1; return -1;
@ -67,9 +67,7 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) {
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
auto payload = parser_.parse(res.payload); auto payload = parser_.parse(res.payload);
workspaces_.clear(); workspaces_.clear();
std::copy_if(payload.begin(), std::copy_if(payload.begin(), payload.end(), std::back_inserter(workspaces_),
payload.end(),
std::back_inserter(workspaces_),
[&](const auto &workspace) { [&](const auto &workspace) {
return !config_["all-outputs"].asBool() return !config_["all-outputs"].asBool()
? workspace["output"].asString() == bar_.output->name ? workspace["output"].asString() == bar_.output->name
@ -78,7 +76,7 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) {
// adding persistent workspaces (as per the config file) // adding persistent workspaces (as per the config file)
if (config_["persistent_workspaces"].isObject()) { if (config_["persistent_workspaces"].isObject()) {
const Json::Value & p_workspaces = config_["persistent_workspaces"]; const Json::Value &p_workspaces = config_["persistent_workspaces"];
const std::vector<std::string> p_workspaces_names = p_workspaces.getMemberNames(); const std::vector<std::string> p_workspaces_names = p_workspaces.getMemberNames();
for (const std::string &p_w_name : p_workspaces_names) { for (const std::string &p_w_name : p_workspaces_names) {
@ -133,10 +131,10 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) {
// unnumbered workspaces behind numbered ones when computing the sort // unnumbered workspaces behind numbered ones when computing the sort
// attribute. // attribute.
int max_num = -1; int max_num = -1;
for (auto & workspace : workspaces_) { for (auto &workspace : workspaces_) {
max_num = std::max(workspace["num"].asInt(), max_num); max_num = std::max(workspace["num"].asInt(), max_num);
} }
for (auto & workspace : workspaces_) { for (auto &workspace : workspaces_) {
auto workspace_num = workspace["num"].asInt(); auto workspace_num = workspace["num"].asInt();
if (workspace_num > -1) { if (workspace_num > -1) {
workspace["sort"] = workspace_num; workspace["sort"] = workspace_num;
@ -144,8 +142,7 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) {
workspace["sort"] = ++max_num; workspace["sort"] = ++max_num;
} }
} }
std::sort(workspaces_.begin(), std::sort(workspaces_.begin(), workspaces_.end(),
workspaces_.end(),
[](const Json::Value &lhs, const Json::Value &rhs) { [](const Json::Value &lhs, const Json::Value &rhs) {
auto lname = lhs["name"].asString(); auto lname = lhs["name"].asString();
auto rname = rhs["name"].asString(); auto rname = rhs["name"].asString();
@ -161,7 +158,6 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) {
return l < r; return l < r;
}); });
} }
dp.emit(); dp.emit();
} catch (const std::exception &e) { } catch (const std::exception &e) {
@ -173,9 +169,8 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) {
bool Workspaces::filterButtons() { bool Workspaces::filterButtons() {
bool needReorder = false; bool needReorder = false;
for (auto it = buttons_.begin(); it != buttons_.end();) { for (auto it = buttons_.begin(); it != buttons_.end();) {
auto ws = std::find_if(workspaces_.begin(), workspaces_.end(), [it](const auto &node) { auto ws = std::find_if(workspaces_.begin(), workspaces_.end(),
return node["name"].asString() == it->first; [it](const auto &node) { return node["name"].asString() == it->first; });
});
if (ws == workspaces_.end() || if (ws == workspaces_.end() ||
(!config_["all-outputs"].asBool() && (*ws)["output"].asString() != bar_.output->name)) { (!config_["all-outputs"].asBool() && (*ws)["output"].asString() != bar_.output->name)) {
it = buttons_.erase(it); it = buttons_.erase(it);
@ -231,10 +226,8 @@ auto Workspaces::update() -> void {
std::string output = (*it)["name"].asString(); std::string output = (*it)["name"].asString();
if (config_["format"].isString()) { if (config_["format"].isString()) {
auto format = config_["format"].asString(); auto format = config_["format"].asString();
output = fmt::format(format, output = fmt::format(format, fmt::arg("icon", getIcon(output, *it)),
fmt::arg("icon", getIcon(output, *it)), fmt::arg("value", output), fmt::arg("name", trimWorkspaceName(output)),
fmt::arg("value", output),
fmt::arg("name", trimWorkspaceName(output)),
fmt::arg("index", (*it)["num"].asString())); fmt::arg("index", (*it)["num"].asString()));
} }
if (!config_["disable-markup"].asBool()) { if (!config_["disable-markup"].asBool()) {
@ -258,18 +251,14 @@ Gtk::Button &Workspaces::addButton(const Json::Value &node) {
button.signal_pressed().connect([this, node] { button.signal_pressed().connect([this, node] {
try { try {
if (node["target_output"].isString()) { if (node["target_output"].isString()) {
ipc_.sendCmd( ipc_.sendCmd(IPC_COMMAND,
IPC_COMMAND, fmt::format(workspace_switch_cmd_ + "; move workspace to output \"{}\"; " +
fmt::format(workspace_switch_cmd_ + "; move workspace to output \"{}\"; " + workspace_switch_cmd_, workspace_switch_cmd_,
"--no-auto-back-and-forth", "--no-auto-back-and-forth", node["name"].asString(),
node["name"].asString(), node["target_output"].asString(), "--no-auto-back-and-forth",
node["target_output"].asString(),
"--no-auto-back-and-forth",
node["name"].asString())); node["name"].asString()));
} else { } else {
ipc_.sendCmd( ipc_.sendCmd(IPC_COMMAND, fmt::format("workspace {} \"{}\"",
IPC_COMMAND,
fmt::format("workspace {} \"{}\"",
config_["disable-auto-back-and-forth"].asBool() config_["disable-auto-back-and-forth"].asBool()
? "--no-auto-back-and-forth" ? "--no-auto-back-and-forth"
: "", : "",
@ -316,9 +305,8 @@ bool Workspaces::handleScroll(GdkEventScroll *e) {
std::string name; std::string name;
{ {
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
auto it = std::find_if(workspaces_.begin(), workspaces_.end(), [](const auto &workspace) { auto it = std::find_if(workspaces_.begin(), workspaces_.end(),
return workspace["focused"].asBool(); [](const auto &workspace) { return workspace["focused"].asBool(); });
});
if (it == workspaces_.end()) { if (it == workspaces_.end()) {
return true; return true;
} }
@ -334,9 +322,7 @@ bool Workspaces::handleScroll(GdkEventScroll *e) {
} }
} }
try { try {
ipc_.sendCmd( ipc_.sendCmd(IPC_COMMAND, fmt::format(workspace_switch_cmd_, "--no-auto-back-and-forth", name));
IPC_COMMAND,
fmt::format(workspace_switch_cmd_, "--no-auto-back-and-forth", name));
} catch (const std::exception &e) { } catch (const std::exception &e) {
spdlog::error("Workspaces: {}", e.what()); spdlog::error("Workspaces: {}", e.what());
} }

View File

@ -1,4 +1,5 @@
#include "modules/temperature.hpp" #include "modules/temperature.hpp"
#include <filesystem> #include <filesystem>
waybar::modules::Temperature::Temperature(const std::string& id, const Json::Value& config) waybar::modules::Temperature::Temperature(const std::string& id, const Json::Value& config)
@ -6,7 +7,10 @@ waybar::modules::Temperature::Temperature(const std::string& id, const Json::Val
if (config_["hwmon-path"].isString()) { if (config_["hwmon-path"].isString()) {
file_path_ = config_["hwmon-path"].asString(); file_path_ = config_["hwmon-path"].asString();
} else if (config_["hwmon-path-abs"].isString() && config_["input-filename"].isString()) { } else if (config_["hwmon-path-abs"].isString() && config_["input-filename"].isString()) {
file_path_ = (*std::filesystem::directory_iterator(config_["hwmon-path-abs"].asString())).path().string() + "/" + config_["input-filename"].asString(); file_path_ = (*std::filesystem::directory_iterator(config_["hwmon-path-abs"].asString()))
.path()
.string() +
"/" + config_["input-filename"].asString();
} else { } else {
auto zone = config_["thermal-zone"].isInt() ? config_["thermal-zone"].asInt() : 0; auto zone = config_["thermal-zone"].isInt() ? config_["thermal-zone"].asInt() : 0;
file_path_ = fmt::format("/sys/class/thermal/thermal_zone{}/temp", zone); file_path_ = fmt::format("/sys/class/thermal/thermal_zone{}/temp", zone);
@ -35,7 +39,7 @@ auto waybar::modules::Temperature::update() -> void {
label_.get_style_context()->remove_class("critical"); label_.get_style_context()->remove_class("critical");
} }
if(format.empty()) { if (format.empty()) {
event_box_.hide(); event_box_.hide();
return; return;
} else { } else {
@ -43,8 +47,7 @@ auto waybar::modules::Temperature::update() -> void {
} }
auto max_temp = config_["critical-threshold"].isInt() ? config_["critical-threshold"].asInt() : 0; auto max_temp = config_["critical-threshold"].isInt() ? config_["critical-threshold"].asInt() : 0;
label_.set_markup(fmt::format(format, label_.set_markup(fmt::format(format, fmt::arg("temperatureC", temperature_c),
fmt::arg("temperatureC", temperature_c),
fmt::arg("temperatureF", temperature_f), fmt::arg("temperatureF", temperature_f),
fmt::arg("temperatureK", temperature_k), fmt::arg("temperatureK", temperature_k),
fmt::arg("icon", getIcon(temperature_c, "", max_temp)))); fmt::arg("icon", getIcon(temperature_c, "", max_temp))));
@ -53,8 +56,7 @@ auto waybar::modules::Temperature::update() -> void {
if (config_["tooltip-format"].isString()) { if (config_["tooltip-format"].isString()) {
tooltip_format = config_["tooltip-format"].asString(); tooltip_format = config_["tooltip-format"].asString();
} }
label_.set_tooltip_text(fmt::format(tooltip_format, label_.set_tooltip_text(fmt::format(tooltip_format, fmt::arg("temperatureC", temperature_c),
fmt::arg("temperatureC", temperature_c),
fmt::arg("temperatureF", temperature_f), fmt::arg("temperatureF", temperature_f),
fmt::arg("temperatureK", temperature_k))); fmt::arg("temperatureK", temperature_k)));
} }

View File

@ -68,13 +68,9 @@ UPower::UPower(const std::string& id, const Json::Value& config)
box_.signal_query_tooltip().connect(sigc::mem_fun(*this, &UPower::show_tooltip_callback)); box_.signal_query_tooltip().connect(sigc::mem_fun(*this, &UPower::show_tooltip_callback));
} }
upowerWatcher_id = g_bus_watch_name(G_BUS_TYPE_SYSTEM, upowerWatcher_id = g_bus_watch_name(G_BUS_TYPE_SYSTEM, "org.freedesktop.UPower",
"org.freedesktop.UPower", G_BUS_NAME_WATCHER_FLAGS_AUTO_START, upowerAppear,
G_BUS_NAME_WATCHER_FLAGS_AUTO_START, upowerDisappear, this, NULL);
upowerAppear,
upowerDisappear,
this,
NULL);
GError* error = NULL; GError* error = NULL;
client = up_client_new_full(NULL, &error); client = up_client_new_full(NULL, &error);
@ -87,16 +83,10 @@ UPower::UPower(const std::string& id, const Json::Value& config)
if (!login1_connection) { if (!login1_connection) {
throw std::runtime_error("Unable to connect to the SYSTEM Bus!..."); throw std::runtime_error("Unable to connect to the SYSTEM Bus!...");
} else { } else {
login1_id = g_dbus_connection_signal_subscribe(login1_connection, login1_id = g_dbus_connection_signal_subscribe(
"org.freedesktop.login1", login1_connection, "org.freedesktop.login1", "org.freedesktop.login1.Manager",
"org.freedesktop.login1.Manager", "PrepareForSleep", "/org/freedesktop/login1", NULL, G_DBUS_SIGNAL_FLAGS_NONE,
"PrepareForSleep", prepareForSleep_cb, this, NULL);
"/org/freedesktop/login1",
NULL,
G_DBUS_SIGNAL_FLAGS_NONE,
prepareForSleep_cb,
this,
NULL);
} }
event_box_.signal_button_press_event().connect(sigc::mem_fun(*this, &UPower::handleToggle)); event_box_.signal_button_press_event().connect(sigc::mem_fun(*this, &UPower::handleToggle));
@ -291,19 +281,8 @@ auto UPower::update() -> void {
gint64 time_full; gint64 time_full;
gchar* icon_name; gchar* icon_name;
g_object_get(displayDevice, g_object_get(displayDevice, "kind", &kind, "state", &state, "percentage", &percentage,
"kind", "icon-name", &icon_name, "time-to-empty", &time_empty, "time-to-full", &time_full,
&kind,
"state",
&state,
"percentage",
&percentage,
"icon-name",
&icon_name,
"time-to-empty",
&time_empty,
"time-to-full",
&time_full,
NULL); NULL);
bool displayDeviceValid = bool displayDeviceValid =
@ -357,8 +336,8 @@ auto UPower::update() -> void {
default: default:
break; break;
} }
std::string label_format = fmt::format(showAltText ? format_alt : format, std::string label_format =
fmt::arg("percentage", percentString), fmt::format(showAltText ? format_alt : format, fmt::arg("percentage", percentString),
fmt::arg("time", time_format)); fmt::arg("time", time_format));
// Only set the label text if it doesn't only contain spaces // Only set the label text if it doesn't only contain spaces
bool onlySpaces = true; bool onlySpaces = true;

View File

@ -48,18 +48,8 @@ uint UPowerTooltip::updateTooltip(Devices& devices) {
gchar* model; gchar* model;
gchar* icon_name; gchar* icon_name;
g_object_get(device, g_object_get(device, "kind", &kind, "percentage", &percentage, "native-path", &native_path,
"kind", "model", &model, "icon-name", &icon_name, NULL);
&kind,
"percentage",
&percentage,
"native-path",
&native_path,
"model",
&model,
"icon-name",
&icon_name,
NULL);
// Skip Line_Power and BAT0 devices // Skip Line_Power and BAT0 devices
if (kind == UP_DEVICE_KIND_LINE_POWER || native_path == NULL || strlen(native_path) == 0 || if (kind == UP_DEVICE_KIND_LINE_POWER || native_path == NULL || strlen(native_path) == 0 ||

View File

@ -1,10 +1,11 @@
#include "modules/wlr/taskbar.hpp" #include "modules/wlr/taskbar.hpp"
#include "glibmm/error.h" #include <fmt/core.h>
#include "glibmm/fileutils.h" #include <gdkmm/monitor.h>
#include "glibmm/refptr.h" #include <gio/gdesktopappinfo.h>
#include "util/format.hpp" #include <giomm/desktopappinfo.h>
#include "util/string.hpp" #include <gtkmm/icontheme.h>
#include <spdlog/spdlog.h>
#include <algorithm> #include <algorithm>
#include <cctype> #include <cctype>
@ -14,22 +15,16 @@
#include <sstream> #include <sstream>
#include <utility> #include <utility>
#include <fmt/core.h> #include "glibmm/error.h"
#include <gdkmm/monitor.h> #include "glibmm/fileutils.h"
#include "glibmm/refptr.h"
#include <gtkmm/icontheme.h> #include "util/format.hpp"
#include "util/string.hpp"
#include <giomm/desktopappinfo.h>
#include <gio/gdesktopappinfo.h>
#include <spdlog/spdlog.h>
namespace waybar::modules::wlr { namespace waybar::modules::wlr {
/* Icon loading functions */ /* Icon loading functions */
static std::vector<std::string> search_prefix() static std::vector<std::string> search_prefix() {
{
std::vector<std::string> prefixes = {""}; std::vector<std::string> prefixes = {""};
auto xdg_data_dirs = std::getenv("XDG_DATA_DIRS"); auto xdg_data_dirs = std::getenv("XDG_DATA_DIRS");
@ -42,52 +37,43 @@ static std::vector<std::string> search_prefix()
do { do {
end = xdg_data_dirs_str.find(':', start); end = xdg_data_dirs_str.find(':', start);
auto p = xdg_data_dirs_str.substr(start, end-start); auto p = xdg_data_dirs_str.substr(start, end - start);
prefixes.push_back(trim(p) + "/"); prefixes.push_back(trim(p) + "/");
start = end == std::string::npos ? end : end + 1; start = end == std::string::npos ? end : end + 1;
} while(end != std::string::npos); } while (end != std::string::npos);
} }
std::string home_dir = std::getenv("HOME"); std::string home_dir = std::getenv("HOME");
prefixes.push_back(home_dir + "/.local/share/"); prefixes.push_back(home_dir + "/.local/share/");
for (auto& p : prefixes) for (auto &p : prefixes) spdlog::debug("Using 'desktop' search path prefix: {}", p);
spdlog::debug("Using 'desktop' search path prefix: {}", p);
return prefixes; return prefixes;
} }
static Glib::RefPtr<Gdk::Pixbuf> load_icon_from_file(std::string icon_path, int size) static Glib::RefPtr<Gdk::Pixbuf> load_icon_from_file(std::string icon_path, int size) {
{
try { try {
auto pb = Gdk::Pixbuf::create_from_file(icon_path, size, size); auto pb = Gdk::Pixbuf::create_from_file(icon_path, size, size);
return pb; return pb;
} catch(...) { } catch (...) {
return {}; return {};
} }
} }
static Glib::RefPtr<Gio::DesktopAppInfo> get_app_info_by_name(const std::string& app_id) static Glib::RefPtr<Gio::DesktopAppInfo> get_app_info_by_name(const std::string &app_id) {
{
static std::vector<std::string> prefixes = search_prefix(); static std::vector<std::string> prefixes = search_prefix();
std::vector<std::string> app_folders = { std::vector<std::string> app_folders = {"", "applications/", "applications/kde/",
"", "applications/org.kde."};
"applications/",
"applications/kde/",
"applications/org.kde."
};
std::vector<std::string> suffixes = { std::vector<std::string> suffixes = {"", ".desktop"};
"",
".desktop"
};
for (auto& prefix : prefixes) { for (auto &prefix : prefixes) {
for (auto& folder : app_folders) { for (auto &folder : app_folders) {
for (auto& suffix : suffixes) { for (auto &suffix : suffixes) {
auto app_info_ = Gio::DesktopAppInfo::create_from_filename(prefix + folder + app_id + suffix); auto app_info_ =
Gio::DesktopAppInfo::create_from_filename(prefix + folder + app_id + suffix);
if (!app_info_) { if (!app_info_) {
continue; continue;
} }
@ -100,8 +86,7 @@ static Glib::RefPtr<Gio::DesktopAppInfo> get_app_info_by_name(const std::string&
return {}; return {};
} }
Glib::RefPtr<Gio::DesktopAppInfo> get_desktop_app_info(const std::string &app_id) Glib::RefPtr<Gio::DesktopAppInfo> get_desktop_app_info(const std::string &app_id) {
{
auto app_info = get_app_info_by_name(app_id); auto app_info = get_app_info_by_name(app_id);
if (app_info) { if (app_info) {
return app_info; return app_info;
@ -109,9 +94,9 @@ Glib::RefPtr<Gio::DesktopAppInfo> get_desktop_app_info(const std::string &app_id
std::string desktop_file = ""; std::string desktop_file = "";
gchar*** desktop_list = g_desktop_app_info_search(app_id.c_str()); gchar ***desktop_list = g_desktop_app_info_search(app_id.c_str());
if (desktop_list != nullptr && desktop_list[0] != nullptr) { if (desktop_list != nullptr && desktop_list[0] != nullptr) {
for (size_t i=0; desktop_list[0][i]; i++) { for (size_t i = 0; desktop_list[0][i]; i++) {
if (desktop_file == "") { if (desktop_file == "") {
desktop_file = desktop_list[0][i]; desktop_file = desktop_list[0][i];
} else { } else {
@ -131,14 +116,13 @@ Glib::RefPtr<Gio::DesktopAppInfo> get_desktop_app_info(const std::string &app_id
return get_app_info_by_name(desktop_file); return get_app_info_by_name(desktop_file);
} }
void Task::set_app_info_from_app_id_list(const std::string& app_id_list) { void Task::set_app_info_from_app_id_list(const std::string &app_id_list) {
std::string app_id; std::string app_id;
std::istringstream stream(app_id_list); std::istringstream stream(app_id_list);
/* Wayfire sends a list of app-id's in space separated format, other compositors /* Wayfire sends a list of app-id's in space separated format, other compositors
* send a single app-id, but in any case this works fine */ * send a single app-id, but in any case this works fine */
while (stream >> app_id) while (stream >> app_id) {
{
app_info_ = get_desktop_app_info(app_id); app_info_ = get_desktop_app_info(app_id);
if (app_info_) { if (app_info_) {
return; return;
@ -146,7 +130,7 @@ void Task::set_app_info_from_app_id_list(const std::string& app_id_list) {
auto lower_app_id = app_id; auto lower_app_id = app_id;
std::transform(lower_app_id.begin(), lower_app_id.end(), lower_app_id.begin(), std::transform(lower_app_id.begin(), lower_app_id.end(), lower_app_id.begin(),
[](char c){ return std::tolower(c); }); [](char c) { return std::tolower(c); });
app_info_ = get_desktop_app_info(lower_app_id); app_info_ = get_desktop_app_info(lower_app_id);
if (app_info_) { if (app_info_) {
return; return;
@ -154,7 +138,7 @@ void Task::set_app_info_from_app_id_list(const std::string& app_id_list) {
size_t start = 0, end = app_id.size(); size_t start = 0, end = app_id.size();
start = app_id.rfind(".", end); start = app_id.rfind(".", end);
std::string app_name = app_id.substr(start+1, app_id.size()); std::string app_name = app_id.substr(start + 1, app_id.size());
app_info_ = get_desktop_app_info(app_name); app_info_ = get_desktop_app_info(app_name);
if (app_info_) { if (app_info_) {
return; return;
@ -166,20 +150,19 @@ void Task::set_app_info_from_app_id_list(const std::string& app_id_list) {
} }
} }
static std::string get_icon_name_from_icon_theme(const Glib::RefPtr<Gtk::IconTheme>& icon_theme, static std::string get_icon_name_from_icon_theme(const Glib::RefPtr<Gtk::IconTheme> &icon_theme,
const std::string &app_id) const std::string &app_id) {
{ if (icon_theme->lookup_icon(app_id, 24)) return app_id;
if (icon_theme->lookup_icon(app_id, 24))
return app_id;
return ""; return "";
} }
bool Task::image_load_icon(Gtk::Image& image, const Glib::RefPtr<Gtk::IconTheme>& icon_theme, Glib::RefPtr<Gio::DesktopAppInfo> app_info, int size) bool Task::image_load_icon(Gtk::Image &image, const Glib::RefPtr<Gtk::IconTheme> &icon_theme,
{ Glib::RefPtr<Gio::DesktopAppInfo> app_info, int size) {
std::string ret_icon_name = "unknown"; std::string ret_icon_name = "unknown";
if (app_info) { if (app_info) {
std::string icon_name = get_icon_name_from_icon_theme(icon_theme, app_info->get_startup_wm_class()); std::string icon_name =
get_icon_name_from_icon_theme(icon_theme, app_info->get_startup_wm_class());
if (!icon_name.empty()) { if (!icon_name.empty()) {
ret_icon_name = icon_name; ret_icon_name = icon_name;
} else { } else {
@ -193,7 +176,7 @@ bool Task::image_load_icon(Gtk::Image& image, const Glib::RefPtr<Gtk::IconTheme>
try { try {
pixbuf = icon_theme->load_icon(ret_icon_name, size, Gtk::ICON_LOOKUP_FORCE_SIZE); pixbuf = icon_theme->load_icon(ret_icon_name, size, Gtk::ICON_LOOKUP_FORCE_SIZE);
} catch(...) { } catch (...) {
if (Glib::file_test(ret_icon_name, Glib::FILE_TEST_EXISTS)) if (Glib::file_test(ret_icon_name, Glib::FILE_TEST_EXISTS))
pixbuf = load_icon_from_file(ret_icon_name, size); pixbuf = load_icon_from_file(ret_icon_name, size);
else else
@ -212,49 +195,41 @@ bool Task::image_load_icon(Gtk::Image& image, const Glib::RefPtr<Gtk::IconTheme>
uint32_t Task::global_id = 0; uint32_t Task::global_id = 0;
static void tl_handle_title(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle, static void tl_handle_title(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle,
const char *title) const char *title) {
{ return static_cast<Task *>(data)->handle_title(title);
return static_cast<Task*>(data)->handle_title(title);
} }
static void tl_handle_app_id(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle, static void tl_handle_app_id(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle,
const char *app_id) const char *app_id) {
{ return static_cast<Task *>(data)->handle_app_id(app_id);
return static_cast<Task*>(data)->handle_app_id(app_id);
} }
static void tl_handle_output_enter(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle, static void tl_handle_output_enter(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle,
struct wl_output *output) struct wl_output *output) {
{ return static_cast<Task *>(data)->handle_output_enter(output);
return static_cast<Task*>(data)->handle_output_enter(output);
} }
static void tl_handle_output_leave(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle, static void tl_handle_output_leave(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle,
struct wl_output *output) struct wl_output *output) {
{ return static_cast<Task *>(data)->handle_output_leave(output);
return static_cast<Task*>(data)->handle_output_leave(output);
} }
static void tl_handle_state(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle, static void tl_handle_state(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle,
struct wl_array *state) struct wl_array *state) {
{ return static_cast<Task *>(data)->handle_state(state);
return static_cast<Task*>(data)->handle_state(state);
} }
static void tl_handle_done(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle) static void tl_handle_done(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle) {
{ return static_cast<Task *>(data)->handle_done();
return static_cast<Task*>(data)->handle_done();
} }
static void tl_handle_parent(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle, static void tl_handle_parent(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle,
struct zwlr_foreign_toplevel_handle_v1 *parent) struct zwlr_foreign_toplevel_handle_v1 *parent) {
{
/* This is explicitly left blank */ /* This is explicitly left blank */
} }
static void tl_handle_closed(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle) static void tl_handle_closed(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle) {
{ return static_cast<Task *>(data)->handle_closed();
return static_cast<Task*>(data)->handle_closed();
} }
static const struct zwlr_foreign_toplevel_handle_v1_listener toplevel_handle_impl = { static const struct zwlr_foreign_toplevel_handle_v1_listener toplevel_handle_impl = {
@ -269,11 +244,14 @@ static const struct zwlr_foreign_toplevel_handle_v1_listener toplevel_handle_imp
}; };
Task::Task(const waybar::Bar &bar, const Json::Value &config, Taskbar *tbar, Task::Task(const waybar::Bar &bar, const Json::Value &config, Taskbar *tbar,
struct zwlr_foreign_toplevel_handle_v1 *tl_handle, struct wl_seat *seat) : struct zwlr_foreign_toplevel_handle_v1 *tl_handle, struct wl_seat *seat)
bar_{bar}, config_{config}, tbar_{tbar}, handle_{tl_handle}, seat_{seat}, : bar_{bar},
config_{config},
tbar_{tbar},
handle_{tl_handle},
seat_{seat},
id_{global_id++}, id_{global_id++},
content_{bar.vertical ? Gtk::ORIENTATION_VERTICAL : Gtk::ORIENTATION_HORIZONTAL, 0} content_{bar.vertical ? Gtk::ORIENTATION_VERTICAL : Gtk::ORIENTATION_HORIZONTAL, 0} {
{
zwlr_foreign_toplevel_handle_v1_add_listener(handle_, &toplevel_handle_impl, this); zwlr_foreign_toplevel_handle_v1_add_listener(handle_, &toplevel_handle_impl, this);
button_.set_relief(Gtk::RELIEF_NONE); button_.set_relief(Gtk::RELIEF_NONE);
@ -321,16 +299,14 @@ Task::Task(const waybar::Bar &bar, const Json::Value &config, Taskbar *tbar,
} }
/* Handle click events if configured */ /* Handle click events if configured */
if (config_["on-click"].isString() || config_["on-click-middle"].isString() if (config_["on-click"].isString() || config_["on-click-middle"].isString() ||
|| config_["on-click-right"].isString()) { config_["on-click-right"].isString()) {
button_.add_events(Gdk::BUTTON_PRESS_MASK); button_.add_events(Gdk::BUTTON_PRESS_MASK);
button_.signal_button_press_event().connect( button_.signal_button_press_event().connect(sigc::mem_fun(*this, &Task::handle_clicked), false);
sigc::mem_fun(*this, &Task::handle_clicked), false);
} }
} }
Task::~Task() Task::~Task() {
{
if (handle_) { if (handle_) {
zwlr_foreign_toplevel_handle_v1_destroy(handle_); zwlr_foreign_toplevel_handle_v1_destroy(handle_);
handle_ = nullptr; handle_ = nullptr;
@ -341,25 +317,19 @@ Task::~Task()
} }
} }
std::string Task::repr() const std::string Task::repr() const {
{
std::stringstream ss; std::stringstream ss;
ss << "Task (" << id_ << ") " << title_ << " [" << app_id_ << "] <" ss << "Task (" << id_ << ") " << title_ << " [" << app_id_ << "] <" << (active() ? "A" : "a")
<< (active() ? "A" : "a") << (maximized() ? "M" : "m") << (minimized() ? "I" : "i") << (fullscreen() ? "F" : "f") << ">";
<< (maximized() ? "M" : "m")
<< (minimized() ? "I" : "i")
<< (fullscreen() ? "F" : "f")
<< ">";
return ss.str(); return ss.str();
} }
std::string Task::state_string(bool shortened) const std::string Task::state_string(bool shortened) const {
{
std::stringstream ss; std::stringstream ss;
if (shortened) if (shortened)
ss << (minimized() ? "m" : "") << (maximized() ? "M" : "") ss << (minimized() ? "m" : "") << (maximized() ? "M" : "") << (active() ? "A" : "")
<< (active() ? "A" : "") << (fullscreen() ? "F" : ""); << (fullscreen() ? "F" : "");
else else
ss << (minimized() ? "minimized " : "") << (maximized() ? "maximized " : "") ss << (minimized() ? "minimized " : "") << (maximized() ? "maximized " : "")
<< (active() ? "active " : "") << (fullscreen() ? "fullscreen " : ""); << (active() ? "active " : "") << (fullscreen() ? "fullscreen " : "");
@ -371,14 +341,12 @@ std::string Task::state_string(bool shortened) const
return res.substr(0, res.size() - 1); return res.substr(0, res.size() - 1);
} }
void Task::handle_title(const char *title) void Task::handle_title(const char *title) {
{
title_ = title; title_ = title;
hide_if_ignored(); hide_if_ignored();
} }
void Task::hide_if_ignored() void Task::hide_if_ignored() {
{
if (tbar_->ignore_list().count(app_id_) || tbar_->ignore_list().count(title_)) { if (tbar_->ignore_list().count(app_id_) || tbar_->ignore_list().count(title_)) {
ignored_ = true; ignored_ = true;
if (button_visible_) { if (button_visible_) {
@ -395,15 +363,15 @@ void Task::hide_if_ignored()
} }
} }
void Task::handle_app_id(const char *app_id) void Task::handle_app_id(const char *app_id) {
{
app_id_ = app_id; app_id_ = app_id;
hide_if_ignored(); hide_if_ignored();
auto ids_replace_map = tbar_->app_ids_replace_map(); auto ids_replace_map = tbar_->app_ids_replace_map();
if (ids_replace_map.count(app_id_)) { if (ids_replace_map.count(app_id_)) {
auto replaced_id = ids_replace_map[app_id_]; auto replaced_id = ids_replace_map[app_id_];
spdlog::debug(fmt::format("Task ({}) [{}] app_id was replaced with {}", id_, app_id_, replaced_id)); spdlog::debug(
fmt::format("Task ({}) [{}] app_id was replaced with {}", id_, app_id_, replaced_id));
app_id_ = replaced_id; app_id_ = replaced_id;
} }
@ -420,7 +388,7 @@ void Task::handle_app_id(const char *app_id)
int icon_size = config_["icon-size"].isInt() ? config_["icon-size"].asInt() : 16; int icon_size = config_["icon-size"].isInt() ? config_["icon-size"].asInt() : 16;
bool found = false; bool found = false;
for (auto& icon_theme : tbar_->icon_themes()) { for (auto &icon_theme : tbar_->icon_themes()) {
if (image_load_icon(icon_, icon_theme, app_info_, icon_size)) { if (image_load_icon(icon_, icon_theme, app_info_, icon_size)) {
found = true; found = true;
break; break;
@ -433,14 +401,13 @@ void Task::handle_app_id(const char *app_id)
spdlog::debug("Couldn't find icon for {}", app_id_); spdlog::debug("Couldn't find icon for {}", app_id_);
} }
void Task::handle_output_enter(struct wl_output *output) void Task::handle_output_enter(struct wl_output *output) {
{
if (ignored_) { if (ignored_) {
spdlog::debug("{} is ignored", repr()); spdlog::debug("{} is ignored", repr());
return; return;
} }
spdlog::debug("{} entered output {}", repr(), (void*)output); spdlog::debug("{} entered output {}", repr(), (void *)output);
if (!button_visible_ && (tbar_->all_outputs() || tbar_->show_output(output))) { if (!button_visible_ && (tbar_->all_outputs() || tbar_->show_output(output))) {
/* The task entered the output of the current bar make the button visible */ /* The task entered the output of the current bar make the button visible */
@ -451,9 +418,8 @@ void Task::handle_output_enter(struct wl_output *output)
} }
} }
void Task::handle_output_leave(struct wl_output *output) void Task::handle_output_leave(struct wl_output *output) {
{ spdlog::debug("{} left output {}", repr(), (void *)output);
spdlog::debug("{} left output {}", repr(), (void*)output);
if (button_visible_ && !tbar_->all_outputs() && tbar_->show_output(output)) { if (button_visible_ && !tbar_->all_outputs() && tbar_->show_output(output)) {
/* The task left the output of the current bar, make the button invisible */ /* The task left the output of the current bar, make the button invisible */
@ -464,25 +430,19 @@ void Task::handle_output_leave(struct wl_output *output)
} }
} }
void Task::handle_state(struct wl_array *state) void Task::handle_state(struct wl_array *state) {
{
state_ = 0; state_ = 0;
size_t size = state->size / sizeof(uint32_t); size_t size = state->size / sizeof(uint32_t);
for (size_t i = 0; i < size; ++i) { for (size_t i = 0; i < size; ++i) {
auto entry = static_cast<uint32_t*>(state->data)[i]; auto entry = static_cast<uint32_t *>(state->data)[i];
if (entry == ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_MAXIMIZED) if (entry == ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_MAXIMIZED) state_ |= MAXIMIZED;
state_ |= MAXIMIZED; if (entry == ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_MINIMIZED) state_ |= MINIMIZED;
if (entry == ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_MINIMIZED) if (entry == ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_ACTIVATED) state_ |= ACTIVE;
state_ |= MINIMIZED; if (entry == ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_FULLSCREEN) state_ |= FULLSCREEN;
if (entry == ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_ACTIVATED)
state_ |= ACTIVE;
if (entry == ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_FULLSCREEN)
state_ |= FULLSCREEN;
} }
} }
void Task::handle_done() void Task::handle_done() {
{
spdlog::debug("{} changed", repr()); spdlog::debug("{} changed", repr());
if (state_ & MAXIMIZED) { if (state_ & MAXIMIZED) {
@ -515,8 +475,7 @@ void Task::handle_done()
tbar_->dp.emit(); tbar_->dp.emit();
} }
void Task::handle_closed() void Task::handle_closed() {
{
spdlog::debug("{} closed", repr()); spdlog::debug("{} closed", repr());
zwlr_foreign_toplevel_handle_v1_destroy(handle_); zwlr_foreign_toplevel_handle_v1_destroy(handle_);
handle_ = nullptr; handle_ = nullptr;
@ -527,8 +486,7 @@ void Task::handle_closed()
tbar_->remove_task(id_); tbar_->remove_task(id_);
} }
bool Task::handle_clicked(GdkEventButton *bt) bool Task::handle_clicked(GdkEventButton *bt) {
{
std::string action; std::string action;
if (config_["on-click"].isString() && bt->button == 1) if (config_["on-click"].isString() && bt->button == 1)
action = config_["on-click"].asString(); action = config_["on-click"].asString();
@ -543,15 +501,14 @@ bool Task::handle_clicked(GdkEventButton *bt)
activate(); activate();
else if (action == "minimize") else if (action == "minimize")
minimize(!minimized()); minimize(!minimized());
else if (action == "minimize-raise"){ else if (action == "minimize-raise") {
if (minimized()) if (minimized())
minimize(false); minimize(false);
else if (active()) else if (active())
minimize(true); minimize(true);
else else
activate(); activate();
} } else if (action == "maximize")
else if (action == "maximize")
maximize(!maximized()); maximize(!maximized());
else if (action == "fullscreen") else if (action == "fullscreen")
fullscreen(!fullscreen()); fullscreen(!fullscreen());
@ -563,18 +520,11 @@ bool Task::handle_clicked(GdkEventButton *bt)
return true; return true;
} }
bool Task::operator==(const Task &o) const bool Task::operator==(const Task &o) const { return o.id_ == id_; }
{
return o.id_ == id_;
}
bool Task::operator!=(const Task &o) const bool Task::operator!=(const Task &o) const { return o.id_ != id_; }
{
return o.id_ != id_;
}
void Task::update() void Task::update() {
{
bool markup = config_["markup"].isBool() ? config_["markup"].asBool() : false; bool markup = config_["markup"].isBool() ? config_["markup"].asBool() : false;
std::string title = title_; std::string title = title_;
std::string name = name_; std::string name = name_;
@ -585,13 +535,9 @@ void Task::update()
app_id = Glib::Markup::escape_text(app_id); app_id = Glib::Markup::escape_text(app_id);
} }
if (!format_before_.empty()) { if (!format_before_.empty()) {
auto txt = fmt::format(format_before_, auto txt = fmt::format(format_before_, fmt::arg("title", title), fmt::arg("name", name),
fmt::arg("title", title), fmt::arg("app_id", app_id), fmt::arg("state", state_string()),
fmt::arg("name", name), fmt::arg("short_state", state_string(true)));
fmt::arg("app_id", app_id),
fmt::arg("state", state_string()),
fmt::arg("short_state", state_string(true))
);
if (markup) if (markup)
text_before_.set_markup(txt); text_before_.set_markup(txt);
else else
@ -599,13 +545,9 @@ void Task::update()
text_before_.show(); text_before_.show();
} }
if (!format_after_.empty()) { if (!format_after_.empty()) {
auto txt = fmt::format(format_after_, auto txt = fmt::format(format_after_, fmt::arg("title", title), fmt::arg("name", name),
fmt::arg("title", title), fmt::arg("app_id", app_id), fmt::arg("state", state_string()),
fmt::arg("name", name), fmt::arg("short_state", state_string(true)));
fmt::arg("app_id", app_id),
fmt::arg("state", state_string()),
fmt::arg("short_state", state_string(true))
);
if (markup) if (markup)
text_after_.set_markup(txt); text_after_.set_markup(txt);
else else
@ -614,13 +556,9 @@ void Task::update()
} }
if (!format_tooltip_.empty()) { if (!format_tooltip_.empty()) {
auto txt = fmt::format(format_tooltip_, auto txt = fmt::format(format_tooltip_, fmt::arg("title", title), fmt::arg("name", name),
fmt::arg("title", title), fmt::arg("app_id", app_id), fmt::arg("state", state_string()),
fmt::arg("name", name), fmt::arg("short_state", state_string(true)));
fmt::arg("app_id", app_id),
fmt::arg("state", state_string()),
fmt::arg("short_state", state_string(true))
);
if (markup) if (markup)
button_.set_tooltip_markup(txt); button_.set_tooltip_markup(txt);
else else
@ -628,30 +566,25 @@ void Task::update()
} }
} }
void Task::maximize(bool set) void Task::maximize(bool set) {
{
if (set) if (set)
zwlr_foreign_toplevel_handle_v1_set_maximized(handle_); zwlr_foreign_toplevel_handle_v1_set_maximized(handle_);
else else
zwlr_foreign_toplevel_handle_v1_unset_maximized(handle_); zwlr_foreign_toplevel_handle_v1_unset_maximized(handle_);
} }
void Task::minimize(bool set) void Task::minimize(bool set) {
{
if (set) if (set)
zwlr_foreign_toplevel_handle_v1_set_minimized(handle_); zwlr_foreign_toplevel_handle_v1_set_minimized(handle_);
else else
zwlr_foreign_toplevel_handle_v1_unset_minimized(handle_); zwlr_foreign_toplevel_handle_v1_unset_minimized(handle_);
} }
void Task::activate() void Task::activate() { zwlr_foreign_toplevel_handle_v1_activate(handle_, seat_); }
{
zwlr_foreign_toplevel_handle_v1_activate(handle_, seat_);
}
void Task::fullscreen(bool set) void Task::fullscreen(bool set) {
{ if (zwlr_foreign_toplevel_handle_v1_get_version(handle_) <
if (zwlr_foreign_toplevel_handle_v1_get_version(handle_) < ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_SET_FULLSCREEN_SINCE_VERSION) { ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_SET_FULLSCREEN_SINCE_VERSION) {
spdlog::warn("Foreign toplevel manager server does not support for set/unset fullscreen."); spdlog::warn("Foreign toplevel manager server does not support for set/unset fullscreen.");
return; return;
} }
@ -662,39 +595,31 @@ void Task::fullscreen(bool set)
zwlr_foreign_toplevel_handle_v1_unset_fullscreen(handle_); zwlr_foreign_toplevel_handle_v1_unset_fullscreen(handle_);
} }
void Task::close() void Task::close() { zwlr_foreign_toplevel_handle_v1_close(handle_); }
{
zwlr_foreign_toplevel_handle_v1_close(handle_);
}
/* Taskbar class implementation */ /* Taskbar class implementation */
static void handle_global(void *data, struct wl_registry *registry, uint32_t name, static void handle_global(void *data, struct wl_registry *registry, uint32_t name,
const char *interface, uint32_t version) const char *interface, uint32_t version) {
{
if (std::strcmp(interface, zwlr_foreign_toplevel_manager_v1_interface.name) == 0) { if (std::strcmp(interface, zwlr_foreign_toplevel_manager_v1_interface.name) == 0) {
static_cast<Taskbar*>(data)->register_manager(registry, name, version); static_cast<Taskbar *>(data)->register_manager(registry, name, version);
} else if (std::strcmp(interface, wl_seat_interface.name) == 0) { } else if (std::strcmp(interface, wl_seat_interface.name) == 0) {
static_cast<Taskbar*>(data)->register_seat(registry, name, version); static_cast<Taskbar *>(data)->register_seat(registry, name, version);
} }
} }
static void handle_global_remove(void *data, struct wl_registry *registry, uint32_t name) static void handle_global_remove(void *data, struct wl_registry *registry, uint32_t name) {
{
/* Nothing to do here */ /* Nothing to do here */
} }
static const wl_registry_listener registry_listener_impl = { static const wl_registry_listener registry_listener_impl = {.global = handle_global,
.global = handle_global, .global_remove = handle_global_remove};
.global_remove = handle_global_remove
};
Taskbar::Taskbar(const std::string &id, const waybar::Bar &bar, const Json::Value &config) Taskbar::Taskbar(const std::string &id, const waybar::Bar &bar, const Json::Value &config)
: waybar::AModule(config, "taskbar", id, false, false), : waybar::AModule(config, "taskbar", id, false, false),
bar_(bar), bar_(bar),
box_{bar.vertical ? Gtk::ORIENTATION_VERTICAL : Gtk::ORIENTATION_HORIZONTAL, 0}, box_{bar.vertical ? Gtk::ORIENTATION_VERTICAL : Gtk::ORIENTATION_HORIZONTAL, 0},
manager_{nullptr}, seat_{nullptr} manager_{nullptr},
{ seat_{nullptr} {
box_.set_name("taskbar"); box_.set_name("taskbar");
if (!id.empty()) { if (!id.empty()) {
box_.get_style_context()->add_class(id); box_.get_style_context()->add_class(id);
@ -718,7 +643,7 @@ Taskbar::Taskbar(const std::string &id, const waybar::Bar &bar, const Json::Valu
/* Get the configured icon theme if specified */ /* Get the configured icon theme if specified */
if (config_["icon-theme"].isArray()) { if (config_["icon-theme"].isArray()) {
for (auto& c : config_["icon-theme"]) { for (auto &c : config_["icon-theme"]) {
auto it_name = c.asString(); auto it_name = c.asString();
auto it = Gtk::IconTheme::create(); auto it = Gtk::IconTheme::create();
@ -739,16 +664,16 @@ Taskbar::Taskbar(const std::string &id, const waybar::Bar &bar, const Json::Valu
// Load ignore-list // Load ignore-list
if (config_["ignore-list"].isArray()) { if (config_["ignore-list"].isArray()) {
for (auto& app_name : config_["ignore-list"]) { for (auto &app_name : config_["ignore-list"]) {
ignore_list_.emplace(app_name.asString()); ignore_list_.emplace(app_name.asString());
} }
} }
// Load app_id remappings // Load app_id remappings
if (config_["app_ids-mapping"].isObject()) { if (config_["app_ids-mapping"].isObject()) {
const Json::Value& mapping = config_["app_ids-mapping"]; const Json::Value &mapping = config_["app_ids-mapping"];
const std::vector<std::string> app_ids = config_["app_ids-mapping"].getMemberNames(); const std::vector<std::string> app_ids = config_["app_ids-mapping"].getMemberNames();
for (auto& app_id : app_ids) { for (auto &app_id : app_ids) {
app_ids_replace_map_.emplace(app_id, mapping[app_id].asString()); app_ids_replace_map_.emplace(app_id, mapping[app_id].asString());
} }
} }
@ -756,8 +681,7 @@ Taskbar::Taskbar(const std::string &id, const waybar::Bar &bar, const Json::Valu
icon_themes_.push_back(Gtk::IconTheme::get_default()); icon_themes_.push_back(Gtk::IconTheme::get_default());
} }
Taskbar::~Taskbar() Taskbar::~Taskbar() {
{
if (manager_) { if (manager_) {
struct wl_display *display = Client::inst()->wl_display; struct wl_display *display = Client::inst()->wl_display;
/* /*
@ -776,9 +700,8 @@ Taskbar::~Taskbar()
} }
} }
void Taskbar::update() void Taskbar::update() {
{ for (auto &t : tasks_) {
for (auto& t : tasks_) {
t->update(); t->update();
} }
@ -786,14 +709,12 @@ void Taskbar::update()
} }
static void tm_handle_toplevel(void *data, struct zwlr_foreign_toplevel_manager_v1 *manager, static void tm_handle_toplevel(void *data, struct zwlr_foreign_toplevel_manager_v1 *manager,
struct zwlr_foreign_toplevel_handle_v1 *tl_handle) struct zwlr_foreign_toplevel_handle_v1 *tl_handle) {
{ return static_cast<Taskbar *>(data)->handle_toplevel_create(tl_handle);
return static_cast<Taskbar*>(data)->handle_toplevel_create(tl_handle);
} }
static void tm_handle_finished(void *data, struct zwlr_foreign_toplevel_manager_v1 *manager) static void tm_handle_finished(void *data, struct zwlr_foreign_toplevel_manager_v1 *manager) {
{ return static_cast<Taskbar *>(data)->handle_finished();
return static_cast<Taskbar*>(data)->handle_finished();
} }
static const struct zwlr_foreign_toplevel_manager_v1_listener toplevel_manager_impl = { static const struct zwlr_foreign_toplevel_manager_v1_listener toplevel_manager_impl = {
@ -801,22 +722,23 @@ static const struct zwlr_foreign_toplevel_manager_v1_listener toplevel_manager_i
.finished = tm_handle_finished, .finished = tm_handle_finished,
}; };
void Taskbar::register_manager(struct wl_registry *registry, uint32_t name, uint32_t version) void Taskbar::register_manager(struct wl_registry *registry, uint32_t name, uint32_t version) {
{
if (manager_) { if (manager_) {
spdlog::warn("Register foreign toplevel manager again although already existing!"); spdlog::warn("Register foreign toplevel manager again although already existing!");
return; return;
} }
if (version < ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_SET_FULLSCREEN_SINCE_VERSION) { if (version < ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_SET_FULLSCREEN_SINCE_VERSION) {
spdlog::warn("Foreign toplevel manager server does not have the appropriate version." spdlog::warn(
" To be able to use all features, you need at least version 2, but server is version {}", version); "Foreign toplevel manager server does not have the appropriate version."
" To be able to use all features, you need at least version 2, but server is version {}",
version);
} }
// limit version to a highest supported by the client protocol file // limit version to a highest supported by the client protocol file
version = std::min<uint32_t>(version, zwlr_foreign_toplevel_manager_v1_interface.version); version = std::min<uint32_t>(version, zwlr_foreign_toplevel_manager_v1_interface.version);
manager_ = static_cast<struct zwlr_foreign_toplevel_manager_v1 *>(wl_registry_bind(registry, name, manager_ = static_cast<struct zwlr_foreign_toplevel_manager_v1 *>(
&zwlr_foreign_toplevel_manager_v1_interface, version)); wl_registry_bind(registry, name, &zwlr_foreign_toplevel_manager_v1_interface, version));
if (manager_) if (manager_)
zwlr_foreign_toplevel_manager_v1_add_listener(manager_, &toplevel_manager_impl, this); zwlr_foreign_toplevel_manager_v1_add_listener(manager_, &toplevel_manager_impl, this);
@ -824,45 +746,32 @@ void Taskbar::register_manager(struct wl_registry *registry, uint32_t name, uint
spdlog::debug("Failed to register manager"); spdlog::debug("Failed to register manager");
} }
void Taskbar::register_seat(struct wl_registry *registry, uint32_t name, uint32_t version) void Taskbar::register_seat(struct wl_registry *registry, uint32_t name, uint32_t version) {
{
if (seat_) { if (seat_) {
spdlog::warn("Register seat again although already existing!"); spdlog::warn("Register seat again although already existing!");
return; return;
} }
version = std::min<uint32_t>(version, wl_seat_interface.version); version = std::min<uint32_t>(version, wl_seat_interface.version);
seat_ = static_cast<wl_seat*>(wl_registry_bind(registry, name, &wl_seat_interface, version)); seat_ = static_cast<wl_seat *>(wl_registry_bind(registry, name, &wl_seat_interface, version));
} }
void Taskbar::handle_toplevel_create(struct zwlr_foreign_toplevel_handle_v1 *tl_handle) void Taskbar::handle_toplevel_create(struct zwlr_foreign_toplevel_handle_v1 *tl_handle) {
{
tasks_.push_back(std::make_unique<Task>(bar_, config_, this, tl_handle, seat_)); tasks_.push_back(std::make_unique<Task>(bar_, config_, this, tl_handle, seat_));
} }
void Taskbar::handle_finished() void Taskbar::handle_finished() {
{
zwlr_foreign_toplevel_manager_v1_destroy(manager_); zwlr_foreign_toplevel_manager_v1_destroy(manager_);
manager_ = nullptr; manager_ = nullptr;
} }
void Taskbar::add_button(Gtk::Button &bt) void Taskbar::add_button(Gtk::Button &bt) { box_.pack_start(bt, false, false); }
{
box_.pack_start(bt, false, false);
}
void Taskbar::move_button(Gtk::Button &bt, int pos) void Taskbar::move_button(Gtk::Button &bt, int pos) { box_.reorder_child(bt, pos); }
{
box_.reorder_child(bt, pos);
}
void Taskbar::remove_button(Gtk::Button &bt) void Taskbar::remove_button(Gtk::Button &bt) { box_.remove(bt); }
{
box_.remove(bt);
}
void Taskbar::remove_task(uint32_t id) void Taskbar::remove_task(uint32_t id) {
{
auto it = std::find_if(std::begin(tasks_), std::end(tasks_), auto it = std::find_if(std::begin(tasks_), std::end(tasks_),
[id](const TaskPtr &p) { return p->id() == id; }); [id](const TaskPtr &p) { return p->id() == id; });
@ -874,20 +783,22 @@ void Taskbar::remove_task(uint32_t id)
tasks_.erase(it); tasks_.erase(it);
} }
bool Taskbar::show_output(struct wl_output *output) const bool Taskbar::show_output(struct wl_output *output) const {
{
return output == gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj()); return output == gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj());
} }
bool Taskbar::all_outputs() const bool Taskbar::all_outputs() const {
{
return config_["all-outputs"].isBool() && config_["all-outputs"].asBool(); return config_["all-outputs"].isBool() && config_["all-outputs"].asBool();
} }
const std::vector<Glib::RefPtr<Gtk::IconTheme>>& Taskbar::icon_themes() const { return icon_themes_; } const std::vector<Glib::RefPtr<Gtk::IconTheme>> &Taskbar::icon_themes() const {
return icon_themes_;
}
const std::unordered_set<std::string>& Taskbar::ignore_list() const { return ignore_list_; } const std::unordered_set<std::string> &Taskbar::ignore_list() const { return ignore_list_; }
const std::map<std::string, std::string>& Taskbar::app_ids_replace_map() const { return app_ids_replace_map_; } const std::map<std::string, std::string> &Taskbar::app_ids_replace_map() const {
return app_ids_replace_map_;
}
} /* namespace waybar::modules::wlr */ } /* namespace waybar::modules::wlr */

View File

@ -156,8 +156,7 @@ WorkspaceManager::~WorkspaceManager() {
} }
auto WorkspaceManager::remove_workspace_group(uint32_t id) -> void { auto WorkspaceManager::remove_workspace_group(uint32_t id) -> void {
auto it = std::find_if(groups_.begin(), auto it = std::find_if(groups_.begin(), groups_.end(),
groups_.end(),
[id](const std::unique_ptr<WorkspaceGroup> &g) { return g->id() == id; }); [id](const std::unique_ptr<WorkspaceGroup> &g) { return g->id() == id; });
if (it == groups_.end()) { if (it == groups_.end()) {
@ -257,8 +256,7 @@ auto WorkspaceGroup::update() -> void {
} }
auto WorkspaceGroup::remove_workspace(uint32_t id) -> void { auto WorkspaceGroup::remove_workspace(uint32_t id) -> void {
auto it = std::find_if(workspaces_.begin(), auto it = std::find_if(workspaces_.begin(), workspaces_.end(),
workspaces_.end(),
[id](const std::unique_ptr<Workspace> &w) { return w->id() == id; }); [id](const std::unique_ptr<Workspace> &w) { return w->id() == id; });
if (it == workspaces_.end()) { if (it == workspaces_.end()) {
@ -353,8 +351,8 @@ Workspace::~Workspace() {
} }
auto Workspace::update() -> void { auto Workspace::update() -> void {
label_.set_markup(fmt::format( label_.set_markup(fmt::format(format_, fmt::arg("name", name_),
format_, fmt::arg("name", name_), fmt::arg("icon", with_icon_ ? get_icon() : ""))); fmt::arg("icon", with_icon_ ? get_icon() : "")));
} }
auto Workspace::handle_state(const std::vector<uint32_t> &state) -> void { auto Workspace::handle_state(const std::vector<uint32_t> &state) -> void {

View File

@ -1,6 +1,7 @@
#include "modules/wlr/workspace_manager_binding.hpp" #include "modules/wlr/workspace_manager_binding.hpp"
#include <spdlog/spdlog.h> #include <spdlog/spdlog.h>
#include <cstdint> #include <cstdint>
#include "client.hpp" #include "client.hpp"
@ -23,7 +24,7 @@ static const wl_registry_listener registry_listener_impl = {.global = handle_glo
.global_remove = handle_global_remove}; .global_remove = handle_global_remove};
void add_registry_listener(void *data) { void add_registry_listener(void *data) {
wl_display * display = Client::inst()->wl_display; wl_display *display = Client::inst()->wl_display;
wl_registry *registry = wl_display_get_registry(display); wl_registry *registry = wl_display_get_registry(display);
wl_registry_add_listener(registry, &registry_listener_impl, data); wl_registry_add_listener(registry, &registry_listener_impl, data);
@ -89,7 +90,7 @@ static const zext_workspace_group_handle_v1_listener workspace_group_impl = {
.remove = workspace_group_handle_remove}; .remove = workspace_group_handle_remove};
void add_workspace_group_listener(zext_workspace_group_handle_v1 *workspace_group_handle, void add_workspace_group_listener(zext_workspace_group_handle_v1 *workspace_group_handle,
void * data) { void *data) {
zext_workspace_group_handle_v1_add_listener(workspace_group_handle, &workspace_group_impl, data); zext_workspace_group_handle_v1_add_listener(workspace_group_handle, &workspace_group_impl, data);
} }

View File

@ -39,8 +39,8 @@ waybar::util::Rfkill::Rfkill(const enum rfkill_type rfkill_type) : rfkill_type_(
fd_ = -1; fd_ = -1;
return; return;
} }
Glib::signal_io().connect( Glib::signal_io().connect(sigc::mem_fun(*this, &Rfkill::on_event), fd_,
sigc::mem_fun(*this, &Rfkill::on_event), fd_, Glib::IO_IN | Glib::IO_ERR | Glib::IO_HUP); Glib::IO_IN | Glib::IO_ERR | Glib::IO_HUP);
} }
waybar::util::Rfkill::~Rfkill() { waybar::util::Rfkill::~Rfkill() {

View File

@ -1,6 +1,6 @@
#include "util/ustring_clen.hpp" #include "util/ustring_clen.hpp"
int ustring_clen(const Glib::ustring &str){ int ustring_clen(const Glib::ustring &str) {
int total = 0; int total = 0;
for (auto i = str.begin(); i != str.end(); ++i) { for (auto i = str.begin(); i != str.end(); ++i) {
total += g_unichar_iswide(*i) + 1; total += g_unichar_iswide(*i) + 1;