From 168ba2ca5b0236bdb22dbf9f9bd700b88f9fbd07 Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 6 Apr 2022 08:27:52 +0200 Subject: [PATCH 1/4] Create lint.yml --- .github/workflows/lint.yml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .github/workflows/lint.yml diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 00000000..b57dbead --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,14 @@ +name: Linter + +on: [push] + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: DoozyX/clang-format-lint-action@v0.13 + with: + source: '.' + extensions: 'h,cpp,c' + clangFormatVersion: 12 From f2fcadbf625344f9b952a80276cfb54c46253b8b Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 6 Apr 2022 08:37:19 +0200 Subject: [PATCH 2/4] refactor: lint --- .clang-format | 3 +- include/AIconLabel.hpp | 4 +- include/ALabel.hpp | 16 +- include/AModule.hpp | 43 +- include/IModule.hpp | 4 +- include/bar.hpp | 36 +- include/client.hpp | 40 +- include/factory.hpp | 10 +- include/group.hpp | 5 +- include/modules/backlight.hpp | 20 +- include/modules/battery.hpp | 30 +- include/modules/clock.hpp | 5 +- include/modules/cpu.hpp | 10 +- include/modules/custom.hpp | 20 +- include/modules/disk.hpp | 6 +- include/modules/idle_inhibitor.hpp | 7 +- include/modules/inhibitor.hpp | 8 +- include/modules/keyboard_state.hpp | 15 +- include/modules/memory.hpp | 4 +- include/modules/mpd/mpd.hpp | 10 +- include/modules/mpd/state.hpp | 38 +- include/modules/mpd/state.inl.hpp | 10 +- include/modules/network.hpp | 59 +- include/modules/pulseaudio.hpp | 24 +- include/modules/river/tags.hpp | 6 +- include/modules/sndio.hpp | 6 +- include/modules/sni/host.hpp | 30 +- include/modules/sni/item.hpp | 46 +- include/modules/sni/tray.hpp | 7 +- include/modules/sni/watcher.hpp | 22 +- include/modules/sway/bar.hpp | 8 +- include/modules/sway/ipc/client.hpp | 18 +- include/modules/sway/ipc/ipc.hpp | 6 +- include/modules/sway/language.hpp | 29 +- include/modules/sway/mode.hpp | 7 +- include/modules/sway/window.hpp | 29 +- include/modules/sway/workspaces.hpp | 35 +- include/modules/temperature.hpp | 8 +- include/modules/upower/upower.hpp | 46 +- include/modules/wlr/taskbar.hpp | 256 +- include/modules/wlr/workspace_manager.hpp | 36 +- .../modules/wlr/workspace_manager_binding.hpp | 12 +- include/util/SafeSignal.hpp | 6 +- include/util/clara.hpp | 2069 ++++++++--------- include/util/command.hpp | 10 +- include/util/format.hpp | 156 +- include/util/json.hpp | 2 +- include/util/rfkill.hpp | 4 +- include/util/sleeper_thread.hpp | 15 +- include/util/waybar_time.hpp | 2 +- src/ALabel.cpp | 12 +- src/AModule.cpp | 44 +- src/bar.cpp | 63 +- src/client.cpp | 28 +- src/config.cpp | 12 +- src/factory.cpp | 6 +- src/group.cpp | 6 +- src/main.cpp | 17 +- src/modules/backlight.cpp | 20 +- src/modules/battery.cpp | 79 +- src/modules/clock.cpp | 61 +- src/modules/cpu/bsd.cpp | 44 +- src/modules/cpu/common.cpp | 21 +- src/modules/cpu/linux.cpp | 14 +- src/modules/custom.cpp | 12 +- src/modules/disk.cpp | 35 +- src/modules/idle_inhibitor.cpp | 8 +- src/modules/inhibitor.cpp | 91 +- src/modules/keyboard_state.cpp | 65 +- src/modules/memory/bsd.cpp | 52 +- src/modules/memory/common.cpp | 39 +- src/modules/memory/linux.cpp | 8 +- src/modules/mpd/mpd.cpp | 65 +- src/modules/mpd/state.cpp | 18 +- src/modules/network.cpp | 626 +++-- src/modules/pulseaudio.cpp | 69 +- src/modules/river/tags.cpp | 16 +- src/modules/simpleclock.cpp | 3 +- src/modules/sndio.cpp | 30 +- src/modules/sni/host.cpp | 19 +- src/modules/sni/item.cpp | 67 +- src/modules/sni/tray.cpp | 1 + src/modules/sni/watcher.cpp | 50 +- src/modules/sway/bar.cpp | 7 +- src/modules/sway/ipc/client.cpp | 7 +- src/modules/sway/language.cpp | 49 +- src/modules/sway/mode.cpp | 3 +- src/modules/sway/window.cpp | 47 +- src/modules/sway/workspaces.cpp | 76 +- src/modules/temperature.cpp | 20 +- src/modules/upower/upower.cpp | 55 +- src/modules/upower/upower_tooltip.cpp | 24 +- src/modules/wlr/taskbar.cpp | 1351 +++++------ src/modules/wlr/workspace_manager.cpp | 16 +- src/modules/wlr/workspace_manager_binding.cpp | 9 +- src/util/rfkill.cpp | 6 +- src/util/ustring_clen.cpp | 2 +- test/SafeSignal.cpp | 12 +- test/main.cpp | 2 +- 99 files changed, 3173 insertions(+), 3512 deletions(-) diff --git a/.clang-format b/.clang-format index c428ccc8..c858a764 100644 --- a/.clang-format +++ b/.clang-format @@ -1,6 +1,5 @@ --- BasedOnStyle: Google -AlignConsecutiveDeclarations: true -BinPackArguments: false +AlignConsecutiveDeclarations: false ColumnLimit: 100 ... diff --git a/include/AIconLabel.hpp b/include/AIconLabel.hpp index 3eac7dd7..aeeba6cb 100644 --- a/include/AIconLabel.hpp +++ b/include/AIconLabel.hpp @@ -13,11 +13,11 @@ class AIconLabel : public ALabel { const std::string &format, uint16_t interval = 0, bool ellipsize = false, bool enable_click = false, bool enable_scroll = false); virtual ~AIconLabel() = default; - virtual auto update() -> void; + virtual auto update() -> void; protected: Gtk::Image image_; - Gtk::Box box_; + Gtk::Box box_; bool iconEnabled() const; }; diff --git a/include/ALabel.hpp b/include/ALabel.hpp index d8a5b504..14f82242 100644 --- a/include/ALabel.hpp +++ b/include/ALabel.hpp @@ -3,6 +3,7 @@ #include #include #include + #include "AModule.hpp" namespace waybar { @@ -10,20 +11,21 @@ namespace waybar { class ALabel : public AModule { public: 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 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::vector &alts, uint16_t max = 0); protected: - Gtk::Label label_; - std::string format_; + Gtk::Label label_; + std::string format_; const std::chrono::seconds interval_; - bool alt_ = false; - std::string default_format_; + bool alt_ = false; + std::string default_format_; - virtual bool handleToggle(GdkEventButton *const &e); + virtual bool handleToggle(GdkEventButton *const &e); virtual std::string getState(uint8_t value, bool lesser = false); }; diff --git a/include/AModule.hpp b/include/AModule.hpp index 91606f55..3f511f66 100644 --- a/include/AModule.hpp +++ b/include/AModule.hpp @@ -15,7 +15,7 @@ class AModule : public IModule { bool enable_scroll = false); virtual ~AModule(); virtual auto update() -> void; - virtual operator Gtk::Widget &(); + virtual operator Gtk::Widget &(); Glib::Dispatcher dp; @@ -23,36 +23,35 @@ class AModule : public IModule { enum SCROLL_DIR { NONE, UP, DOWN, LEFT, RIGHT }; SCROLL_DIR getScrollDir(GdkEventScroll *e); - bool tooltipEnabled(); + bool tooltipEnabled(); - const std::string name_; + const std::string name_; const Json::Value &config_; - Gtk::EventBox event_box_; + Gtk::EventBox event_box_; virtual bool handleToggle(GdkEventButton *const &ev); virtual bool handleScroll(GdkEventScroll *); private: std::vector pid_; - gdouble distance_scrolled_y_; - gdouble distance_scrolled_x_; + gdouble distance_scrolled_y_; + gdouble distance_scrolled_x_; static const inline std::map, std::string> eventMap_{ - {std::make_pair(1, GdkEventType::GDK_BUTTON_PRESS), "on-click"}, - {std::make_pair(1, GdkEventType::GDK_2BUTTON_PRESS), "on-double-click"}, - {std::make_pair(1, GdkEventType::GDK_3BUTTON_PRESS), "on-triple-click"}, - {std::make_pair(2, GdkEventType::GDK_BUTTON_PRESS), "on-click-middle"}, - {std::make_pair(2, GdkEventType::GDK_2BUTTON_PRESS), "on-double-click-middle"}, - {std::make_pair(2, GdkEventType::GDK_3BUTTON_PRESS), "on-triple-click-middle"}, - {std::make_pair(3, GdkEventType::GDK_BUTTON_PRESS), "on-click-right"}, - {std::make_pair(3, GdkEventType::GDK_2BUTTON_PRESS), "on-double-click-right"}, - {std::make_pair(3, GdkEventType::GDK_3BUTTON_PRESS), "on-triple-click-right"}, - {std::make_pair(8, GdkEventType::GDK_BUTTON_PRESS), "on-click-backward"}, - {std::make_pair(8, GdkEventType::GDK_2BUTTON_PRESS), "on-double-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_2BUTTON_PRESS), "on-double-click-forward"}, - {std::make_pair(9, GdkEventType::GDK_2BUTTON_PRESS), "on-triple-click-forward"} - }; + {std::make_pair(1, GdkEventType::GDK_BUTTON_PRESS), "on-click"}, + {std::make_pair(1, GdkEventType::GDK_2BUTTON_PRESS), "on-double-click"}, + {std::make_pair(1, GdkEventType::GDK_3BUTTON_PRESS), "on-triple-click"}, + {std::make_pair(2, GdkEventType::GDK_BUTTON_PRESS), "on-click-middle"}, + {std::make_pair(2, GdkEventType::GDK_2BUTTON_PRESS), "on-double-click-middle"}, + {std::make_pair(2, GdkEventType::GDK_3BUTTON_PRESS), "on-triple-click-middle"}, + {std::make_pair(3, GdkEventType::GDK_BUTTON_PRESS), "on-click-right"}, + {std::make_pair(3, GdkEventType::GDK_2BUTTON_PRESS), "on-double-click-right"}, + {std::make_pair(3, GdkEventType::GDK_3BUTTON_PRESS), "on-triple-click-right"}, + {std::make_pair(8, GdkEventType::GDK_BUTTON_PRESS), "on-click-backward"}, + {std::make_pair(8, GdkEventType::GDK_2BUTTON_PRESS), "on-double-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_2BUTTON_PRESS), "on-double-click-forward"}, + {std::make_pair(9, GdkEventType::GDK_2BUTTON_PRESS), "on-triple-click-forward"}}; }; } // namespace waybar diff --git a/include/IModule.hpp b/include/IModule.hpp index 69d55d8c..961a4612 100644 --- a/include/IModule.hpp +++ b/include/IModule.hpp @@ -7,8 +7,8 @@ namespace waybar { class IModule { public: virtual ~IModule() = default; - virtual auto update() -> void = 0; - virtual operator Gtk::Widget &() = 0; + virtual auto update() -> void = 0; + virtual operator Gtk::Widget&() = 0; }; } // namespace waybar diff --git a/include/bar.hpp b/include/bar.hpp index 01a9d034..7c5525f6 100644 --- a/include/bar.hpp +++ b/include/bar.hpp @@ -19,8 +19,8 @@ namespace waybar { class Factory; struct waybar_output { Glib::RefPtr monitor; - std::string name; - std::string identifier; + std::string name; + std::string identifier; std::unique_ptr xdg_output = { nullptr, &zxdg_output_v1_destroy}; @@ -41,9 +41,9 @@ struct bar_margins { struct bar_mode { bar_layer layer; - bool exclusive; - bool passthrough; - bool visible; + bool exclusive; + bool passthrough; + bool visible; }; #ifdef HAVE_SWAY @@ -71,7 +71,7 @@ class BarSurface { class Bar { public: using bar_mode_map = std::map; - static const bar_mode_map PRESET_MODES; + static const bar_mode_map PRESET_MODES; static const std::string_view MODE_DEFAULT; static const std::string_view MODE_INVISIBLE; @@ -85,11 +85,11 @@ class Bar { void handleSignal(int); struct waybar_output *output; - Json::Value config; - struct wl_surface *surface; - bool visible = true; - bool vertical = false; - Gtk::Window window; + Json::Value config; + struct wl_surface *surface; + bool visible = true; + bool vertical = false; + Gtk::Window window; #ifdef HAVE_SWAY std::string bar_id; @@ -98,20 +98,20 @@ class Bar { private: void onMap(GdkEventAny *); 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 setupAltFormatKeyForModuleList(const char *module_list_name); void setMode(const bar_mode &); /* Copy initial set of modes to allow customization */ bar_mode_map configured_modes = PRESET_MODES; - std::string last_mode_{MODE_DEFAULT}; + std::string last_mode_{MODE_DEFAULT}; - std::unique_ptr surface_impl_; - Gtk::Box left_; - Gtk::Box center_; - Gtk::Box right_; - Gtk::Box box_; + std::unique_ptr surface_impl_; + Gtk::Box left_; + Gtk::Box center_; + Gtk::Box right_; + Gtk::Box box_; std::vector> modules_left_; std::vector> modules_center_; std::vector> modules_right_; diff --git a/include/client.hpp b/include/client.hpp index 7fc3dce7..aaba3b6b 100644 --- a/include/client.hpp +++ b/include/client.hpp @@ -17,27 +17,27 @@ namespace waybar { class Client { public: static Client *inst(); - int main(int argc, char *argv[]); - void reset(); + int main(int argc, char *argv[]); + void reset(); - Glib::RefPtr gtk_app; - Glib::RefPtr gdk_display; - struct wl_display * wl_display = nullptr; - struct wl_registry * registry = nullptr; - struct zwlr_layer_shell_v1 * layer_shell = nullptr; - struct zxdg_output_manager_v1 * xdg_output_manager = nullptr; + Glib::RefPtr gtk_app; + Glib::RefPtr gdk_display; + struct wl_display *wl_display = nullptr; + struct wl_registry *registry = nullptr; + struct zwlr_layer_shell_v1 *layer_shell = nullptr; + struct zxdg_output_manager_v1 *xdg_output_manager = nullptr; struct zwp_idle_inhibit_manager_v1 *idle_inhibit_manager = nullptr; - std::vector> bars; - Config config; - std::string bar_id; + std::vector> bars; + Config config; + std::string bar_id; private: Client() = default; - const std::string getStyle(const std::string &style); - void bindInterfaces(); - void handleOutput(struct waybar_output &output); - auto setupCss(const std::string &css_file) -> void; - struct waybar_output & getOutput(void *); + const std::string getStyle(const std::string &style); + void bindInterfaces(); + void handleOutput(struct waybar_output &output); + auto setupCss(const std::string &css_file) -> void; + struct waybar_output &getOutput(void *); std::vector getOutputConfigs(struct waybar_output &output); static void handleGlobal(void *data, struct wl_registry *registry, uint32_t name, @@ -46,12 +46,12 @@ class Client { static void handleOutputDone(void *, struct zxdg_output_v1 *); static void handleOutputName(void *, struct zxdg_output_v1 *, const char *); static void handleOutputDescription(void *, struct zxdg_output_v1 *, const char *); - void handleMonitorAdded(Glib::RefPtr monitor); - void handleMonitorRemoved(Glib::RefPtr monitor); - void handleDeferredMonitorRemoval(Glib::RefPtr monitor); + void handleMonitorAdded(Glib::RefPtr monitor); + void handleMonitorRemoved(Glib::RefPtr monitor); + void handleDeferredMonitorRemoval(Glib::RefPtr monitor); Glib::RefPtr style_context_; - Glib::RefPtr css_provider_; + Glib::RefPtr css_provider_; std::list outputs_; }; diff --git a/include/factory.hpp b/include/factory.hpp index 3954dac4..b9666976 100644 --- a/include/factory.hpp +++ b/include/factory.hpp @@ -7,10 +7,10 @@ #include "modules/simpleclock.hpp" #endif #ifdef HAVE_SWAY +#include "modules/sway/language.hpp" #include "modules/sway/mode.hpp" #include "modules/sway/window.hpp" #include "modules/sway/workspaces.hpp" -#include "modules/sway/language.hpp" #endif #ifdef HAVE_WLR #include "modules/wlr/taskbar.hpp" @@ -61,9 +61,9 @@ #include "modules/custom.hpp" #include "modules/temperature.hpp" #if defined(__linux__) -# ifdef WANT_RFKILL -# include "modules/bluetooth.hpp" -# endif +#ifdef WANT_RFKILL +#include "modules/bluetooth.hpp" +#endif #endif namespace waybar { @@ -74,7 +74,7 @@ class Factory { AModule* makeModule(const std::string& name) const; private: - const Bar& bar_; + const Bar& bar_; const Json::Value& config_; }; diff --git a/include/group.hpp b/include/group.hpp index f282f9c5..5e828677 100644 --- a/include/group.hpp +++ b/include/group.hpp @@ -1,8 +1,9 @@ #pragma once -#include #include +#include #include + #include "AModule.hpp" #include "bar.hpp" #include "factory.hpp" @@ -14,7 +15,7 @@ class Group : public AModule { Group(const std::string&, const Bar&, const Json::Value&); ~Group() = default; auto update() -> void; - operator Gtk::Widget &(); + operator Gtk::Widget&(); Gtk::Box box; }; diff --git a/include/modules/backlight.hpp b/include/modules/backlight.hpp index c225aa04..b7499b8f 100644 --- a/include/modules/backlight.hpp +++ b/include/modules/backlight.hpp @@ -19,19 +19,19 @@ class Backlight : public ALabel { public: BacklightDev() = default; BacklightDev(std::string name, int actual, int max); - std::string_view name() const; - int get_actual() const; - void set_actual(int actual); - int get_max() const; - void set_max(int max); + std::string_view name() const; + int get_actual() const; + void set_actual(int actual); + int get_max() const; + void set_max(int max); friend inline bool operator==(const BacklightDev &lhs, const BacklightDev &rhs) { return lhs.name_ == rhs.name_ && lhs.actual_ == rhs.actual_ && lhs.max_ == rhs.max_; } private: std::string name_; - int actual_ = 1; - int max_ = 1; + int actual_ = 1; + int max_ = 1; }; public: @@ -47,13 +47,13 @@ class Backlight : public ALabel { template static void enumerate_devices(ForwardIt first, ForwardIt last, Inserter inserter, udev *udev); - const std::string preferred_device_; + const std::string preferred_device_; static constexpr int EPOLL_MAX_EVENTS = 16; std::optional previous_best_; - std::string previous_format_; + std::string previous_format_; - std::mutex udev_thread_mutex_; + std::mutex udev_thread_mutex_; std::vector devices_; // thread must destruct before shared data util::SleeperThread udev_thread_; diff --git a/include/modules/battery.hpp b/include/modules/battery.hpp index 41bc0ad3..11028cf6 100644 --- a/include/modules/battery.hpp +++ b/include/modules/battery.hpp @@ -7,10 +7,12 @@ #endif #include #include + #include #include #include #include + #include "ALabel.hpp" #include "util/sleeper_thread.hpp" @@ -31,23 +33,23 @@ class Battery : public ALabel { private: static inline const fs::path data_dir_ = "/sys/class/power_supply/"; - void refreshBatteries(); - void worker(); - const std::string getAdapterStatus(uint8_t capacity) const; + void refreshBatteries(); + void worker(); + const std::string getAdapterStatus(uint8_t capacity) const; const std::tuple getInfos(); - const std::string formatTimeRemaining(float hoursRemaining); + const std::string formatTimeRemaining(float hoursRemaining); - int global_watch; - std::map batteries_; - fs::path adapter_; - int battery_watch_fd_; - int global_watch_fd_; - std::mutex battery_list_mutex_; - std::string old_status_; + int global_watch; + std::map batteries_; + fs::path adapter_; + int battery_watch_fd_; + int global_watch_fd_; + std::mutex battery_list_mutex_; + std::string old_status_; - util::SleeperThread thread_; - util::SleeperThread thread_battery_update_; - util::SleeperThread thread_timer_; + util::SleeperThread thread_; + util::SleeperThread thread_battery_update_; + util::SleeperThread thread_timer_; }; } // namespace waybar::modules diff --git a/include/modules/clock.hpp b/include/modules/clock.hpp index 7c3eb8fc..efc71863 100644 --- a/include/modules/clock.hpp +++ b/include/modules/clock.hpp @@ -1,6 +1,7 @@ #pragma once #include + #include "ALabel.hpp" #include "util/sleeper_thread.hpp" @@ -24,7 +25,7 @@ class Clock : public ALabel { std::locale locale_; std::vector time_zones_; 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_; bool is_calendar_in_tooltip_; bool is_timezoned_list_in_tooltip_; @@ -36,7 +37,7 @@ class Clock : public ALabel { auto first_day_of_week() -> date::weekday; const date::time_zone* current_timezone(); 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 diff --git a/include/modules/cpu.hpp b/include/modules/cpu.hpp index 7e32a43f..539f926c 100644 --- a/include/modules/cpu.hpp +++ b/include/modules/cpu.hpp @@ -1,12 +1,14 @@ #pragma once #include + #include #include #include #include #include #include + #include "ALabel.hpp" #include "util/sleeper_thread.hpp" @@ -19,11 +21,11 @@ class Cpu : public ALabel { auto update() -> void; private: - double getCpuLoad(); + double getCpuLoad(); std::tuple, std::string> getCpuUsage(); - std::tuple getCpuFrequency(); - std::vector> parseCpuinfo(); - std::vector parseCpuFrequencies(); + std::tuple getCpuFrequency(); + std::vector> parseCpuinfo(); + std::vector parseCpuFrequencies(); std::vector> prev_times_; diff --git a/include/modules/custom.hpp b/include/modules/custom.hpp index 7c771450..f35ef9ba 100644 --- a/include/modules/custom.hpp +++ b/include/modules/custom.hpp @@ -1,8 +1,10 @@ #pragma once #include + #include #include + #include "ALabel.hpp" #include "util/command.hpp" #include "util/json.hpp" @@ -26,16 +28,16 @@ class Custom : public ALabel { bool handleScroll(GdkEventScroll* e); bool handleToggle(GdkEventButton* const& e); - const std::string name_; - std::string text_; - std::string alt_; - std::string tooltip_; + const std::string name_; + std::string text_; + std::string alt_; + std::string tooltip_; std::vector class_; - int percentage_; - FILE* fp_; - int pid_; - util::command::res output_; - util::JsonParser parser_; + int percentage_; + FILE* fp_; + int pid_; + util::command::res output_; + util::JsonParser parser_; util::SleeperThread thread_; }; diff --git a/include/modules/disk.hpp b/include/modules/disk.hpp index 5f5ce195..ec386b21 100644 --- a/include/modules/disk.hpp +++ b/include/modules/disk.hpp @@ -1,11 +1,13 @@ #pragma once #include -#include #include + +#include + #include "ALabel.hpp" -#include "util/sleeper_thread.hpp" #include "util/format.hpp" +#include "util/sleeper_thread.hpp" namespace waybar::modules { diff --git a/include/modules/idle_inhibitor.hpp b/include/modules/idle_inhibitor.hpp index 4b6c097f..c7ee6800 100644 --- a/include/modules/idle_inhibitor.hpp +++ b/include/modules/idle_inhibitor.hpp @@ -1,6 +1,7 @@ #pragma once #include + #include "ALabel.hpp" #include "bar.hpp" #include "client.hpp" @@ -13,14 +14,14 @@ class IdleInhibitor : public ALabel { ~IdleInhibitor(); auto update() -> void; static std::list modules; - static bool status; + static bool status; private: bool handleToggle(GdkEventButton* const& e); - const Bar& bar_; + const Bar& bar_; struct zwp_idle_inhibitor_v1* idle_inhibitor_; - int pid_; + int pid_; }; } // namespace waybar::modules diff --git a/include/modules/inhibitor.hpp b/include/modules/inhibitor.hpp index aa2f97d4..a5f300d6 100644 --- a/include/modules/inhibitor.hpp +++ b/include/modules/inhibitor.hpp @@ -1,9 +1,9 @@ #pragma once -#include - #include +#include + #include "ALabel.hpp" #include "bar.hpp" @@ -19,9 +19,9 @@ class Inhibitor : public ALabel { private: 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_; int handle_ = -1; }; -} // namespace waybar::modules +} // namespace waybar::modules diff --git a/include/modules/keyboard_state.hpp b/include/modules/keyboard_state.hpp index ed137c14..6af19d14 100644 --- a/include/modules/keyboard_state.hpp +++ b/include/modules/keyboard_state.hpp @@ -6,10 +6,11 @@ #else #include #endif +#include + #include "AModule.hpp" #include "bar.hpp" #include "util/sleeper_thread.hpp" -#include extern "C" { #include @@ -24,10 +25,10 @@ class KeyboardState : public AModule { auto update() -> void; private: - Gtk::Box box_; - Gtk::Label numlock_label_; - Gtk::Label capslock_label_; - Gtk::Label scrolllock_label_; + Gtk::Box box_; + Gtk::Label numlock_label_; + Gtk::Label capslock_label_; + Gtk::Label scrolllock_label_; std::string numlock_format_; std::string capslock_format_; @@ -36,8 +37,8 @@ class KeyboardState : public AModule { std::string icon_locked_; std::string icon_unlocked_; - int fd_; - libevdev* dev_; + int fd_; + libevdev* dev_; util::SleeperThread thread_; }; diff --git a/include/modules/memory.hpp b/include/modules/memory.hpp index abfe2872..e23ed841 100644 --- a/include/modules/memory.hpp +++ b/include/modules/memory.hpp @@ -1,8 +1,10 @@ #pragma once #include + #include #include + #include "ALabel.hpp" #include "util/sleeper_thread.hpp" @@ -15,7 +17,7 @@ class Memory : public ALabel { auto update() -> void; private: - void parseMeminfo(); + void parseMeminfo(); std::unordered_map meminfo_; diff --git a/include/modules/mpd/mpd.hpp b/include/modules/mpd/mpd.hpp index 0fc1ce99..01240d15 100644 --- a/include/modules/mpd/mpd.hpp +++ b/include/modules/mpd/mpd.hpp @@ -22,8 +22,8 @@ class MPD : public ALabel { // Not using unique_ptr since we don't manage the pointer // (It's either nullptr, or from the config) - const char* server_; - const unsigned port_; + const char* server_; + const unsigned port_; const std::string password_; unsigned timeout_; @@ -31,8 +31,8 @@ class MPD : public ALabel { detail::unique_connection connection_; detail::unique_status status_; - mpd_state state_; - detail::unique_song song_; + mpd_state state_; + detail::unique_song song_; public: MPD(const std::string&, const Json::Value&); @@ -41,7 +41,7 @@ class MPD : public ALabel { private: std::string getTag(mpd_tag_type type, unsigned idx = 0) const; - void setLabel(); + void setLabel(); std::string getStateIcon() const; std::string getOptionIcon(std::string optionName, bool activated) const; diff --git a/include/modules/mpd/state.hpp b/include/modules/mpd/state.hpp index 3b181598..1276e3c3 100644 --- a/include/modules/mpd/state.hpp +++ b/include/modules/mpd/state.hpp @@ -1,7 +1,7 @@ #pragma once -#include #include +#include #include #include @@ -57,7 +57,7 @@ class State { }; class Idle : public State { - Context* const ctx_; + Context* const ctx_; sigc::connection idle_connection_; public: @@ -80,7 +80,7 @@ class Idle : public State { }; class Playing : public State { - Context* const ctx_; + Context* const ctx_; sigc::connection timer_connection_; public: @@ -102,7 +102,7 @@ class Playing : public State { }; class Paused : public State { - Context* const ctx_; + Context* const ctx_; sigc::connection timer_connection_; public: @@ -124,7 +124,7 @@ class Paused : public State { }; class Stopped : public State { - Context* const ctx_; + Context* const ctx_; sigc::connection timer_connection_; public: @@ -146,7 +146,7 @@ class Stopped : public State { }; class Disconnected : public State { - Context* const ctx_; + Context* const ctx_; sigc::connection timer_connection_; public: @@ -170,7 +170,7 @@ class Disconnected : public State { class Context { std::unique_ptr state_; - waybar::modules::MPD* mpd_module_; + waybar::modules::MPD* mpd_module_; friend class State; friend class Playing; @@ -188,18 +188,18 @@ class Context { state_->entry(); } - bool is_connected() const; - bool is_playing() const; - bool is_paused() const; - bool is_stopped() const; - constexpr std::size_t interval() const; - void tryConnect() const; - void checkErrors(mpd_connection*) const; - void do_update(); - void queryMPD() const; - void fetchState() const; - constexpr mpd_state state() const; - void emit() const; + bool is_connected() const; + bool is_playing() const; + bool is_paused() const; + bool is_stopped() const; + constexpr std::size_t interval() const; + void tryConnect() const; + void checkErrors(mpd_connection*) const; + void do_update(); + void queryMPD() const; + void fetchState() const; + constexpr mpd_state state() const; + void emit() const; [[nodiscard]] unique_connection& connection(); public: diff --git a/include/modules/mpd/state.inl.hpp b/include/modules/mpd/state.inl.hpp index 0d83b0b3..895970e6 100644 --- a/include/modules/mpd/state.inl.hpp +++ b/include/modules/mpd/state.inl.hpp @@ -8,13 +8,11 @@ inline bool Context::is_paused() const { return mpd_module_->paused(); } inline bool Context::is_stopped() const { return mpd_module_->stopped(); } constexpr inline std::size_t Context::interval() const { return mpd_module_->interval_.count(); } -inline void Context::tryConnect() const { mpd_module_->tryConnect(); } -inline unique_connection& Context::connection() { return mpd_module_->connection_; } -constexpr inline mpd_state Context::state() const { return mpd_module_->state_; } +inline void Context::tryConnect() const { mpd_module_->tryConnect(); } +inline unique_connection& Context::connection() { return mpd_module_->connection_; } +constexpr inline mpd_state Context::state() const { return mpd_module_->state_; } -inline void Context::do_update() { - mpd_module_->setLabel(); -} +inline void Context::do_update() { mpd_module_->setLabel(); } inline void Context::checkErrors(mpd_connection* conn) const { mpd_module_->checkErrors(conn); } inline void Context::queryMPD() const { mpd_module_->queryMPD(); } diff --git a/include/modules/network.hpp b/include/modules/network.hpp index 7b8281b1..8e06aa65 100644 --- a/include/modules/network.hpp +++ b/include/modules/network.hpp @@ -7,6 +7,7 @@ #include #include #include + #include "ALabel.hpp" #include "util/sleeper_thread.hpp" #ifdef WANT_RFKILL @@ -31,51 +32,51 @@ class Network : public ALabel { void askForStateDump(void); - void worker(); - void createInfoSocket(); - void createEventSocket(); - void parseEssid(struct nlattr**); - void parseSignal(struct nlattr**); - void parseFreq(struct nlattr**); - bool associatedOrJoined(struct nlattr**); - bool checkInterface(std::string name); - auto getInfo() -> void; + void worker(); + void createInfoSocket(); + void createEventSocket(); + void parseEssid(struct nlattr**); + void parseSignal(struct nlattr**); + void parseFreq(struct nlattr**); + bool associatedOrJoined(struct nlattr**); + bool checkInterface(std::string name); + auto getInfo() -> void; const std::string getNetworkState() const; - void clearIface(); - bool wildcardMatch(const std::string& pattern, const std::string& text) const; + void clearIface(); + bool wildcardMatch(const std::string& pattern, const std::string& text) const; std::optional> readBandwidthUsage(); - int ifid_; - sa_family_t family_; + int ifid_; + sa_family_t family_; struct sockaddr_nl nladdr_ = {0}; - struct nl_sock* sock_ = nullptr; - struct nl_sock* ev_sock_ = nullptr; - int efd_; - int ev_fd_; - int nl80211_id_; - std::mutex mutex_; + struct nl_sock* sock_ = nullptr; + struct nl_sock* ev_sock_ = nullptr; + int efd_; + int ev_fd_; + int nl80211_id_; + std::mutex mutex_; - bool want_route_dump_; - bool want_link_dump_; - bool want_addr_dump_; - bool dump_in_progress_; + bool want_route_dump_; + bool want_link_dump_; + bool want_addr_dump_; + bool dump_in_progress_; unsigned long long bandwidth_down_total_; unsigned long long bandwidth_up_total_; std::string state_; std::string essid_; - bool carrier_; + bool carrier_; std::string ifname_; std::string ipaddr_; std::string gwaddr_; std::string netmask_; - int cidr_; - int32_t signal_strength_dbm_; - uint8_t signal_strength_; + int cidr_; + int32_t signal_strength_dbm_; + uint8_t signal_strength_; std::string signal_strength_app_; - float frequency_; - uint32_t route_priority; + float frequency_; + uint32_t route_priority; util::SleeperThread thread_; util::SleeperThread thread_timer_; diff --git a/include/modules/pulseaudio.hpp b/include/modules/pulseaudio.hpp index 99511b37..a8e4890a 100644 --- a/include/modules/pulseaudio.hpp +++ b/include/modules/pulseaudio.hpp @@ -3,8 +3,10 @@ #include #include #include + #include #include + #include "ALabel.hpp" namespace waybar::modules { @@ -23,27 +25,27 @@ class Pulseaudio : public ALabel { static void serverInfoCb(pa_context*, const pa_server_info*, void*); static void volumeModifyCb(pa_context*, int, void*); - bool handleScroll(GdkEventScroll* e); + bool handleScroll(GdkEventScroll* e); const std::vector getPulseIcon() const; pa_threaded_mainloop* mainloop_; - pa_mainloop_api* mainloop_api_; - pa_context* context_; + pa_mainloop_api* mainloop_api_; + pa_context* context_; // SINK - uint32_t sink_idx_{0}; - uint16_t volume_; - pa_cvolume pa_volume_; - bool muted_; + uint32_t sink_idx_{0}; + uint16_t volume_; + pa_cvolume pa_volume_; + bool muted_; std::string port_name_; std::string form_factor_; std::string desc_; std::string monitor_; std::string current_sink_name_; - bool current_sink_running_; + bool current_sink_running_; // SOURCE - uint32_t source_idx_{0}; - uint16_t source_volume_; - bool source_muted_; + uint32_t source_idx_{0}; + uint16_t source_volume_; + bool source_muted_; std::string source_port_name_; std::string source_desc_; std::string default_source_name_; diff --git a/include/modules/river/tags.hpp b/include/modules/river/tags.hpp index c49ec60d..c2b1a119 100644 --- a/include/modules/river/tags.hpp +++ b/include/modules/river/tags.hpp @@ -5,8 +5,8 @@ #include "AModule.hpp" #include "bar.hpp" -#include "river-status-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" namespace waybar::modules::river { @@ -29,8 +29,8 @@ class Tags : public waybar::AModule { struct wl_seat *seat_; private: - const waybar::Bar & bar_; - Gtk::Box box_; + const waybar::Bar &bar_; + Gtk::Box box_; std::vector buttons_; struct zriver_output_status_v1 *output_status_; }; diff --git a/include/modules/sndio.hpp b/include/modules/sndio.hpp index 32ed7066..eb9b218e 100644 --- a/include/modules/sndio.hpp +++ b/include/modules/sndio.hpp @@ -1,7 +1,9 @@ #pragma once #include + #include + #include "ALabel.hpp" #include "util/sleeper_thread.hpp" @@ -9,13 +11,13 @@ namespace waybar::modules { class Sndio : public ALabel { public: - Sndio(const std::string&, const Json::Value&); + Sndio(const std::string &, const Json::Value &); ~Sndio(); auto update() -> void; auto set_desc(struct sioctl_desc *, unsigned int) -> void; auto put_val(unsigned int, unsigned int) -> void; bool handleScroll(GdkEventScroll *); - bool handleToggle(GdkEventButton* const&); + bool handleToggle(GdkEventButton *const &); private: auto connect_to_sndio() -> void; diff --git a/include/modules/sni/host.hpp b/include/modules/sni/host.hpp index 8d321036..6c62ac31 100644 --- a/include/modules/sni/host.hpp +++ b/include/modules/sni/host.hpp @@ -4,7 +4,9 @@ #include #include #include + #include + #include "bar.hpp" #include "modules/sni/item.hpp" @@ -18,27 +20,27 @@ class Host { ~Host(); private: - void busAcquired(const Glib::RefPtr&, Glib::ustring); - void nameAppeared(const Glib::RefPtr&, Glib::ustring, - const Glib::ustring&); - void nameVanished(const Glib::RefPtr&, Glib::ustring); + void busAcquired(const Glib::RefPtr&, Glib::ustring); + void nameAppeared(const Glib::RefPtr&, Glib::ustring, + const Glib::ustring&); + void nameVanished(const Glib::RefPtr&, Glib::ustring); static void proxyReady(GObject*, GAsyncResult*, gpointer); static void registerHost(GObject*, GAsyncResult*, gpointer); static void itemRegistered(SnWatcher*, const gchar*, gpointer); static void itemUnregistered(SnWatcher*, const gchar*, gpointer); std::tuple getBusNameAndObjectPath(const std::string); - void addRegisteredItem(std::string service); + void addRegisteredItem(std::string service); - std::vector> items_; - const std::string bus_name_; - const std::string object_path_; - std::size_t bus_name_id_; - std::size_t watcher_id_; - GCancellable* cancellable_ = nullptr; - SnWatcher* watcher_ = nullptr; - const Json::Value& config_; - const Bar& bar_; + std::vector> items_; + const std::string bus_name_; + const std::string object_path_; + std::size_t bus_name_id_; + std::size_t watcher_id_; + GCancellable* cancellable_ = nullptr; + SnWatcher* watcher_ = nullptr; + const Json::Value& config_; + const Bar& bar_; const std::function&)> on_add_; const std::function&)> on_remove_; }; diff --git a/include/modules/sni/item.hpp b/include/modules/sni/item.hpp index 430c351c..423ec7c5 100644 --- a/include/modules/sni/item.hpp +++ b/include/modules/sni/item.hpp @@ -31,25 +31,25 @@ class Item : public sigc::trackable { std::string bus_name; std::string object_path; - int icon_size; - int effective_icon_size; - Gtk::Image image; + int icon_size; + int effective_icon_size; + Gtk::Image image; Gtk::EventBox event_box; - std::string category; - std::string id; + std::string category; + std::string id; - std::string title; - std::string icon_name; - Glib::RefPtr icon_pixmap; + std::string title; + std::string icon_name; + Glib::RefPtr icon_pixmap; Glib::RefPtr icon_theme; - std::string overlay_icon_name; - std::string attention_icon_name; - std::string attention_movie_name; - std::string icon_theme_path; - std::string menu; - ToolTip tooltip; - DbusmenuGtkMenu* dbus_menu = nullptr; - Gtk::Menu* gtk_menu = nullptr; + std::string overlay_icon_name; + std::string attention_icon_name; + std::string attention_movie_name; + std::string icon_theme_path; + std::string menu; + ToolTip tooltip; + DbusmenuGtkMenu* dbus_menu = nullptr; + Gtk::Menu* gtk_menu = nullptr; /** * ItemIsMenu flag means that the item only supports the context menu. * Default value is true because libappindicator supports neither ItemIsMenu nor Activate method @@ -67,15 +67,15 @@ class Item : public sigc::trackable { void onSignal(const Glib::ustring& sender_name, const Glib::ustring& signal_name, const Glib::VariantContainerBase& arguments); - void updateImage(); + void updateImage(); Glib::RefPtr extractPixBuf(GVariant* variant); Glib::RefPtr getIconPixbuf(); Glib::RefPtr getIconByName(const std::string& name, int size); - double getScaledIconSize(); - static void onMenuDestroyed(Item* self, GObject* old_menu_pointer); - void makeMenu(); - bool handleClick(GdkEventButton* const& /*ev*/); - bool handleScroll(GdkEventScroll* const&); + double getScaledIconSize(); + static void onMenuDestroyed(Item* self, GObject* old_menu_pointer); + void makeMenu(); + bool handleClick(GdkEventButton* const& /*ev*/); + bool handleScroll(GdkEventScroll* const&); // smooth scrolling threshold gdouble scroll_threshold_ = 0; @@ -86,7 +86,7 @@ class Item : public sigc::trackable { Glib::RefPtr proxy_; Glib::RefPtr cancellable_; - std::set update_pending_; + std::set update_pending_; }; } // namespace waybar::modules::SNI diff --git a/include/modules/sni/tray.hpp b/include/modules/sni/tray.hpp index aaa1e4f9..c1499b9e 100644 --- a/include/modules/sni/tray.hpp +++ b/include/modules/sni/tray.hpp @@ -1,6 +1,7 @@ #pragma once #include + #include "AModule.hpp" #include "bar.hpp" #include "modules/sni/host.hpp" @@ -20,9 +21,9 @@ class Tray : public AModule { void onRemove(std::unique_ptr& item); static inline std::size_t nb_hosts_ = 0; - Gtk::Box box_; - SNI::Watcher::singleton watcher_; - SNI::Host host_; + Gtk::Box box_; + SNI::Watcher::singleton watcher_; + SNI::Host host_; }; } // namespace waybar::modules::SNI diff --git a/include/modules/sni/watcher.hpp b/include/modules/sni/watcher.hpp index 5a55d2d3..5cb0f19e 100644 --- a/include/modules/sni/watcher.hpp +++ b/include/modules/sni/watcher.hpp @@ -30,26 +30,26 @@ class Watcher { typedef struct { GfWatchType type; - Watcher * watcher; - gchar * service; - gchar * bus_name; - gchar * object_path; - guint watch_id; + Watcher *watcher; + gchar *service; + gchar *bus_name; + gchar *object_path; + guint watch_id; } GfWatch; - void busAcquired(const Glib::RefPtr &, Glib::ustring); + void busAcquired(const Glib::RefPtr &, Glib::ustring); static gboolean handleRegisterHost(Watcher *, GDBusMethodInvocation *, const gchar *); static gboolean handleRegisterItem(Watcher *, GDBusMethodInvocation *, const gchar *); static GfWatch *gfWatchFind(GSList *list, const gchar *bus_name, const gchar *object_path); static GfWatch *gfWatchNew(GfWatchType, const gchar *, const gchar *, const gchar *, Watcher *); - static void nameVanished(GDBusConnection *connection, const char *name, gpointer data); - static void gfWatchFree(gpointer data); + static void nameVanished(GDBusConnection *connection, const char *name, gpointer data); + static void gfWatchFree(gpointer data); void updateRegisteredItems(SnWatcher *obj); - uint32_t bus_name_id_; - GSList * hosts_ = nullptr; - GSList * items_ = nullptr; + uint32_t bus_name_id_; + GSList *hosts_ = nullptr; + GSList *items_ = nullptr; SnWatcher *watcher_ = nullptr; }; diff --git a/include/modules/sway/bar.hpp b/include/modules/sway/bar.hpp index c4381a43..e54fc090 100644 --- a/include/modules/sway/bar.hpp +++ b/include/modules/sway/bar.hpp @@ -34,14 +34,14 @@ class BarIpcClient { void onVisibilityUpdate(bool visible_by_modifier); void update(); - Bar& bar_; + Bar& bar_; util::JsonParser parser_; - Ipc ipc_; + Ipc ipc_; swaybar_config bar_config_; - bool visible_by_modifier_ = false; + bool visible_by_modifier_ = false; - SafeSignal signal_visible_; + SafeSignal signal_visible_; SafeSignal signal_config_; }; diff --git a/include/modules/sway/ipc/client.hpp b/include/modules/sway/ipc/client.hpp index 7df53629..77dab083 100644 --- a/include/modules/sway/ipc/client.hpp +++ b/include/modules/sway/ipc/client.hpp @@ -4,9 +4,11 @@ #include #include #include + #include #include #include + #include "ipc.hpp" #include "util/sleeper_thread.hpp" @@ -18,8 +20,8 @@ class Ipc { ~Ipc(); struct ipc_response { - uint32_t size; - uint32_t type; + uint32_t size; + uint32_t type; std::string payload; }; @@ -33,16 +35,16 @@ class Ipc { protected: static inline const std::string ipc_magic_ = "i3-ipc"; - static inline const size_t ipc_header_size_ = ipc_magic_.size() + 8; + static inline const size_t ipc_header_size_ = ipc_magic_.size() + 8; - const std::string getSocketPath() const; - int open(const std::string &) const; + const std::string getSocketPath() const; + int open(const std::string &) const; struct ipc_response send(int fd, uint32_t type, const std::string &payload = ""); struct ipc_response recv(int fd); - int fd_; - int fd_event_; - std::mutex mutex_; + int fd_; + int fd_event_; + std::mutex mutex_; util::SleeperThread thread_; }; diff --git a/include/modules/sway/ipc/ipc.hpp b/include/modules/sway/ipc/ipc.hpp index 5f23d172..783a84d4 100644 --- a/include/modules/sway/ipc/ipc.hpp +++ b/include/modules/sway/ipc/ipc.hpp @@ -30,7 +30,7 @@ enum ipc_command_type { IPC_EVENT_SHUTDOWN = ((1 << 31) | 6), IPC_EVENT_TICK = ((1 << 31) | 7), - // sway-specific event types - IPC_EVENT_BAR_STATE_UPDATE = ((1<<31) | 20), - IPC_EVENT_INPUT = ((1<<31) | 21), + // sway-specific event types + IPC_EVENT_BAR_STATE_UPDATE = ((1 << 31) | 20), + IPC_EVENT_INPUT = ((1 << 31) | 21), }; diff --git a/include/modules/sway/language.hpp b/include/modules/sway/language.hpp index 92e2bbaa..f7602765 100644 --- a/include/modules/sway/language.hpp +++ b/include/modules/sway/language.hpp @@ -21,11 +21,7 @@ class Language : public ALabel, public sigc::trackable { auto update() -> void; private: - enum class DispayedShortFlag { - None = 0, - ShortName = 1, - ShortDescription = 1 << 1 - }; + enum class DispayedShortFlag { None = 0, ShortName = 1, ShortDescription = 1 << 1 }; struct Layout { std::string full_name; @@ -37,14 +33,15 @@ class Language : public ALabel, public sigc::trackable { class XKBContext { public: - XKBContext(); - ~XKBContext(); - auto next_layout() -> Layout*; + XKBContext(); + ~XKBContext(); + auto next_layout() -> Layout*; + private: - rxkb_context* context_ = nullptr; - rxkb_layout* xkb_layout_ = nullptr; - Layout* layout_ = nullptr; - std::map base_layouts_by_name_; + rxkb_context* context_ = nullptr; + rxkb_layout* xkb_layout_ = nullptr; + Layout* layout_ = nullptr; + std::map base_layouts_by_name_; }; void onEvent(const struct Ipc::ipc_response&); @@ -56,15 +53,15 @@ class Language : public ALabel, public sigc::trackable { const static std::string XKB_LAYOUT_NAMES_KEY; const static std::string XKB_ACTIVE_LAYOUT_NAME_KEY; - Layout layout_; + Layout layout_; std::string tooltip_format_ = ""; std::map layouts_map_; bool is_variant_displayed; std::byte displayed_short_flag = static_cast(DispayedShortFlag::None); - util::JsonParser parser_; - std::mutex mutex_; - Ipc ipc_; + util::JsonParser parser_; + std::mutex mutex_; + Ipc ipc_; }; } // namespace waybar::modules::sway diff --git a/include/modules/sway/mode.hpp b/include/modules/sway/mode.hpp index a1a88b02..5543c4eb 100644 --- a/include/modules/sway/mode.hpp +++ b/include/modules/sway/mode.hpp @@ -1,6 +1,7 @@ #pragma once #include + #include "ALabel.hpp" #include "bar.hpp" #include "client.hpp" @@ -18,10 +19,10 @@ class Mode : public ALabel, public sigc::trackable { private: void onEvent(const struct Ipc::ipc_response&); - std::string mode_; + std::string mode_; util::JsonParser parser_; - std::mutex mutex_; - Ipc ipc_; + std::mutex mutex_; + Ipc ipc_; }; } // namespace waybar::modules::sway diff --git a/include/modules/sway/window.hpp b/include/modules/sway/window.hpp index 0ab129e67..2b3f95a1 100644 --- a/include/modules/sway/window.hpp +++ b/include/modules/sway/window.hpp @@ -1,6 +1,7 @@ #pragma once #include + #include #include "AIconLabel.hpp" @@ -18,23 +19,23 @@ class Window : public AIconLabel, public sigc::trackable { auto update() -> void; private: - void onEvent(const struct Ipc::ipc_response&); - void onCmd(const struct Ipc::ipc_response&); + void onEvent(const struct Ipc::ipc_response&); + void onCmd(const struct Ipc::ipc_response&); std::tuple getFocusedNode(const Json::Value& nodes, - std::string& output); - void getTree(); - std::string rewriteTitle(const std::string& title); - void updateAppIcon(); + std::string& output); + void getTree(); + std::string rewriteTitle(const std::string& title); + void updateAppIcon(); - const Bar& bar_; - std::string window_; - int windowId_; - std::string app_id_; - std::string old_app_id_; - std::size_t app_nb_; + const Bar& bar_; + std::string window_; + int windowId_; + std::string app_id_; + std::string old_app_id_; + std::size_t app_nb_; util::JsonParser parser_; - std::mutex mutex_; - Ipc ipc_; + std::mutex mutex_; + Ipc ipc_; }; } // namespace waybar::modules::sway diff --git a/include/modules/sway/workspaces.hpp b/include/modules/sway/workspaces.hpp index c6443836..e6df067f 100644 --- a/include/modules/sway/workspaces.hpp +++ b/include/modules/sway/workspaces.hpp @@ -1,10 +1,11 @@ #pragma once -#include #include #include #include + #include + #include "AModule.hpp" #include "bar.hpp" #include "client.hpp" @@ -24,25 +25,25 @@ class Workspaces : public AModule, public sigc::trackable { static int convertWorkspaceNameToNum(std::string name); - void onCmd(const struct Ipc::ipc_response&); - void onEvent(const struct Ipc::ipc_response&); - bool filterButtons(); - Gtk::Button& addButton(const Json::Value&); - void onButtonReady(const Json::Value&, Gtk::Button&); - std::string getIcon(const std::string&, const Json::Value&); + void onCmd(const struct Ipc::ipc_response&); + void onEvent(const struct Ipc::ipc_response&); + bool filterButtons(); + Gtk::Button& addButton(const Json::Value&); + void onButtonReady(const Json::Value&, Gtk::Button&); + std::string getIcon(const std::string&, const Json::Value&); const std::string getCycleWorkspace(std::vector::iterator, bool prev) const; - uint16_t getWorkspaceIndex(const std::string& name) const; - std::string trimWorkspaceName(std::string); - bool handleScroll(GdkEventScroll*); + uint16_t getWorkspaceIndex(const std::string& name) const; + std::string trimWorkspaceName(std::string); + bool handleScroll(GdkEventScroll*); - const Bar& bar_; - std::vector workspaces_; - std::vector workspaces_order_; - Gtk::Box box_; - util::JsonParser parser_; + const Bar& bar_; + std::vector workspaces_; + std::vector workspaces_order_; + Gtk::Box box_; + util::JsonParser parser_; std::unordered_map buttons_; - std::mutex mutex_; - Ipc ipc_; + std::mutex mutex_; + Ipc ipc_; }; } // namespace waybar::modules::sway diff --git a/include/modules/temperature.hpp b/include/modules/temperature.hpp index 9f071a33..04caafc5 100644 --- a/include/modules/temperature.hpp +++ b/include/modules/temperature.hpp @@ -1,7 +1,9 @@ #pragma once #include + #include + #include "ALabel.hpp" #include "util/sleeper_thread.hpp" @@ -14,10 +16,10 @@ class Temperature : public ALabel { auto update() -> void; private: - float getTemperature(); - bool isCritical(uint16_t); + float getTemperature(); + bool isCritical(uint16_t); - std::string file_path_; + std::string file_path_; util::SleeperThread thread_; }; diff --git a/include/modules/upower/upower.hpp b/include/modules/upower/upower.hpp index ee70fbef..12889404 100644 --- a/include/modules/upower/upower.hpp +++ b/include/modules/upower/upower.hpp @@ -38,41 +38,41 @@ class UPower : public AModule { gpointer data); static void upowerDisappear(GDBusConnection *connection, const gchar *name, gpointer user_data); - void removeDevice(const gchar *objectPath); - void addDevice(UpDevice *device); - void setDisplayDevice(); - void resetDevices(); - void removeDevices(); - bool show_tooltip_callback(int, int, bool, const Glib::RefPtr &tooltip); - bool handleToggle(GdkEventButton *const &); + void removeDevice(const gchar *objectPath); + void addDevice(UpDevice *device); + void setDisplayDevice(); + void resetDevices(); + void removeDevices(); + bool show_tooltip_callback(int, int, bool, const Glib::RefPtr &tooltip); + bool handleToggle(GdkEventButton *const &); std::string timeToString(gint64 time); const std::string getDeviceStatus(UpDeviceState &state); - Gtk::Box box_; + Gtk::Box box_; Gtk::Image icon_; Gtk::Label label_; // Config - bool hideIfEmpty = true; - bool tooltip_enabled = true; - uint tooltip_spacing = 4; - uint tooltip_padding = 4; - uint iconSize = 20; + bool hideIfEmpty = true; + bool tooltip_enabled = true; + uint tooltip_spacing = 4; + uint tooltip_padding = 4; + uint iconSize = 20; std::string format = DEFAULT_FORMAT; std::string format_alt = DEFAULT_FORMAT_ALT; - Devices devices; - std::mutex m_Mutex; - UpClient *client; - UpDevice *displayDevice; - guint login1_id; + Devices devices; + std::mutex m_Mutex; + UpClient *client; + UpDevice *displayDevice; + guint login1_id; GDBusConnection *login1_connection; - UPowerTooltip *upower_tooltip; - std::string lastStatus; - bool showAltText; - bool upowerRunning; - guint upowerWatcher_id; + UPowerTooltip *upower_tooltip; + std::string lastStatus; + bool showAltText; + bool upowerRunning; + guint upowerWatcher_id; }; } // namespace waybar::modules::upower diff --git a/include/modules/wlr/taskbar.hpp b/include/modules/wlr/taskbar.hpp index 973d15db..74b0109d 100644 --- a/include/modules/wlr/taskbar.hpp +++ b/include/modules/wlr/taskbar.hpp @@ -1,174 +1,168 @@ #pragma once +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + #include "AModule.hpp" #include "bar.hpp" #include "client.hpp" #include "giomm/desktopappinfo.h" #include "util/json.hpp" - -#include -#include -#include -#include -#include - -#include - -#include - -#include -#include -#include -#include -#include - -#include #include "wlr-foreign-toplevel-management-unstable-v1-client-protocol.h" - namespace waybar::modules::wlr { class Taskbar; -class Task -{ - public: - Task(const waybar::Bar&, const Json::Value&, Taskbar*, - struct zwlr_foreign_toplevel_handle_v1 *, struct wl_seat*); - ~Task(); +class Task { + public: + Task(const waybar::Bar &, const Json::Value &, Taskbar *, + struct zwlr_foreign_toplevel_handle_v1 *, struct wl_seat *); + ~Task(); - public: - enum State { - MAXIMIZED = (1 << 0), - MINIMIZED = (1 << 1), - ACTIVE = (1 << 2), - FULLSCREEN = (1 << 3), - INVALID = (1 << 4) - }; + public: + enum State { + MAXIMIZED = (1 << 0), + MINIMIZED = (1 << 1), + ACTIVE = (1 << 2), + FULLSCREEN = (1 << 3), + INVALID = (1 << 4) + }; - private: - static uint32_t global_id; + private: + static uint32_t global_id; - private: - const waybar::Bar &bar_; - const Json::Value &config_; - Taskbar *tbar_; - struct zwlr_foreign_toplevel_handle_v1 *handle_; - struct wl_seat *seat_; + private: + const waybar::Bar &bar_; + const Json::Value &config_; + Taskbar *tbar_; + struct zwlr_foreign_toplevel_handle_v1 *handle_; + struct wl_seat *seat_; - uint32_t id_; + uint32_t id_; - Gtk::Button button_; - Gtk::Box content_; - Gtk::Image icon_; - Gtk::Label text_before_; - Gtk::Label text_after_; - Glib::RefPtr app_info_; - bool button_visible_ = false; - bool ignored_ = false; + Gtk::Button button_; + Gtk::Box content_; + Gtk::Image icon_; + Gtk::Label text_before_; + Gtk::Label text_after_; + Glib::RefPtr app_info_; + bool button_visible_ = false; + bool ignored_ = false; - bool with_icon_ = false; - bool with_name_ = false; - std::string format_before_; - std::string format_after_; + bool with_icon_ = false; + bool with_name_ = false; + std::string format_before_; + std::string format_after_; - std::string format_tooltip_; + std::string format_tooltip_; - std::string name_; - std::string title_; - std::string app_id_; - uint32_t state_ = 0; + std::string name_; + std::string title_; + std::string app_id_; + uint32_t state_ = 0; - private: - std::string repr() const; - std::string state_string(bool = false) const; - void set_app_info_from_app_id_list(const std::string& app_id_list); - bool image_load_icon(Gtk::Image& image, const Glib::RefPtr& icon_theme, Glib::RefPtr app_info, int size); - void hide_if_ignored(); + private: + std::string repr() const; + std::string state_string(bool = false) const; + void set_app_info_from_app_id_list(const std::string &app_id_list); + bool image_load_icon(Gtk::Image &image, const Glib::RefPtr &icon_theme, + Glib::RefPtr app_info, int size); + void hide_if_ignored(); - public: - /* Getter functions */ - uint32_t id() const { return id_; } - std::string title() const { return title_; } - std::string app_id() const { return app_id_; } - uint32_t state() const { return state_; } - bool maximized() const { return state_ & MAXIMIZED; } - bool minimized() const { return state_ & MINIMIZED; } - bool active() const { return state_ & ACTIVE; } - bool fullscreen() const { return state_ & FULLSCREEN; } + public: + /* Getter functions */ + uint32_t id() const { return id_; } + std::string title() const { return title_; } + std::string app_id() const { return app_id_; } + uint32_t state() const { return state_; } + bool maximized() const { return state_ & MAXIMIZED; } + bool minimized() const { return state_ & MINIMIZED; } + bool active() const { return state_ & ACTIVE; } + bool fullscreen() const { return state_ & FULLSCREEN; } - public: - /* Callbacks for the wlr protocol */ - void handle_title(const char *); - void handle_app_id(const char *); - void handle_output_enter(struct wl_output *); - void handle_output_leave(struct wl_output *); - void handle_state(struct wl_array *); - void handle_done(); - void handle_closed(); + public: + /* Callbacks for the wlr protocol */ + void handle_title(const char *); + void handle_app_id(const char *); + void handle_output_enter(struct wl_output *); + void handle_output_leave(struct wl_output *); + void handle_state(struct wl_array *); + void handle_done(); + void handle_closed(); - /* Callbacks for Gtk events */ - bool handle_clicked(GdkEventButton *); + /* Callbacks for Gtk events */ + bool handle_clicked(GdkEventButton *); - public: - bool operator==(const Task&) const; - bool operator!=(const Task&) const; + public: + bool operator==(const Task &) const; + bool operator!=(const Task &) const; - public: - void update(); + public: + void update(); - public: - /* Interaction with the tasks */ - void maximize(bool); - void minimize(bool); - void activate(); - void fullscreen(bool); - void close(); + public: + /* Interaction with the tasks */ + void maximize(bool); + void minimize(bool); + void activate(); + void fullscreen(bool); + void close(); }; using TaskPtr = std::unique_ptr; +class Taskbar : public waybar::AModule { + public: + Taskbar(const std::string &, const waybar::Bar &, const Json::Value &); + ~Taskbar(); + void update(); -class Taskbar : public waybar::AModule -{ - public: - Taskbar(const std::string&, const waybar::Bar&, const Json::Value&); - ~Taskbar(); - void update(); + private: + const waybar::Bar &bar_; + Gtk::Box box_; + std::vector tasks_; - private: - const waybar::Bar &bar_; - Gtk::Box box_; - std::vector tasks_; + std::vector> icon_themes_; + std::unordered_set ignore_list_; + std::map app_ids_replace_map_; - std::vector> icon_themes_; - std::unordered_set ignore_list_; - std::map app_ids_replace_map_; + struct zwlr_foreign_toplevel_manager_v1 *manager_; + struct wl_seat *seat_; - struct zwlr_foreign_toplevel_manager_v1 *manager_; - struct wl_seat *seat_; + public: + /* Callbacks for global registration */ + void register_manager(struct wl_registry *, uint32_t name, uint32_t version); + void register_seat(struct wl_registry *, uint32_t name, uint32_t version); - public: - /* Callbacks for global registration */ - void register_manager(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 */ + void handle_toplevel_create(struct zwlr_foreign_toplevel_handle_v1 *); + void handle_finished(); - /* Callbacks for the wlr protocol */ - void handle_toplevel_create(struct zwlr_foreign_toplevel_handle_v1 *); - void handle_finished(); + public: + void add_button(Gtk::Button &); + void move_button(Gtk::Button &, int); + void remove_button(Gtk::Button &); + void remove_task(uint32_t); - public: - void add_button(Gtk::Button &); - void move_button(Gtk::Button &, int); - void remove_button(Gtk::Button &); - void remove_task(uint32_t); + bool show_output(struct wl_output *) const; + bool all_outputs() const; - bool show_output(struct wl_output *) const; - bool all_outputs() const; - - const std::vector>& icon_themes() const; - const std::unordered_set& ignore_list() const; - const std::map& app_ids_replace_map() const; + const std::vector> &icon_themes() const; + const std::unordered_set &ignore_list() const; + const std::map &app_ids_replace_map() const; }; } /* namespace waybar::modules::wlr */ diff --git a/include/modules/wlr/workspace_manager.hpp b/include/modules/wlr/workspace_manager.hpp index e4cdb4da..e65594af 100644 --- a/include/modules/wlr/workspace_manager.hpp +++ b/include/modules/wlr/workspace_manager.hpp @@ -53,24 +53,24 @@ class Workspace { private: auto get_icon() -> std::string; - const Bar &bar_; + const Bar &bar_; const Json::Value &config_; - WorkspaceGroup &workspace_group_; + WorkspaceGroup &workspace_group_; // wlr stuff zext_workspace_handle_v1 *workspace_handle_; - uint32_t state_ = 0; + uint32_t state_ = 0; - uint32_t id_; - std::string name_; - std::vector coordinates_; + uint32_t id_; + std::string name_; + std::vector coordinates_; static std::map icons_map_; - std::string format_; - bool with_icon_ = false; + std::string format_; + bool with_icon_ = false; Gtk::Button button_; - Gtk::Box content_; - Gtk::Label label_; + Gtk::Box content_; + Gtk::Label label_; }; class WorkspaceGroup { @@ -102,19 +102,19 @@ class WorkspaceGroup { auto commit() -> void; private: - static uint32_t workspace_global_id; + static uint32_t workspace_global_id; const waybar::Bar &bar_; - Gtk::Box &box_; + Gtk::Box &box_; const Json::Value &config_; - WorkspaceManager &workspace_manager_; + WorkspaceManager &workspace_manager_; // wlr stuff zext_workspace_group_handle_v1 *workspace_group_handle_; - wl_output *output_ = nullptr; + wl_output *output_ = nullptr; - uint32_t id_; + uint32_t id_; std::vector> workspaces_; - bool need_to_sort = false; + bool need_to_sort = false; }; class WorkspaceManager : public AModule { @@ -141,8 +141,8 @@ class WorkspaceManager : public AModule { auto commit() -> void; private: - const waybar::Bar &bar_; - Gtk::Box box_; + const waybar::Bar &bar_; + Gtk::Box box_; std::vector> groups_; // wlr stuff diff --git a/include/modules/wlr/workspace_manager_binding.hpp b/include/modules/wlr/workspace_manager_binding.hpp index 0bfe663f..cc242c94 100644 --- a/include/modules/wlr/workspace_manager_binding.hpp +++ b/include/modules/wlr/workspace_manager_binding.hpp @@ -1,8 +1,10 @@ #include "ext-workspace-unstable-v1-client-protocol.h" namespace waybar::modules::wlr { - void add_registry_listener(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); - zext_workspace_manager_v1* workspace_manager_bind(wl_registry *registry, uint32_t name, uint32_t version, void *data); -} +void add_registry_listener(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); +zext_workspace_manager_v1 *workspace_manager_bind(wl_registry *registry, uint32_t name, + uint32_t version, void *data); +} // namespace waybar::modules::wlr diff --git a/include/util/SafeSignal.hpp b/include/util/SafeSignal.hpp index 3b68653c..458bc57e 100644 --- a/include/util/SafeSignal.hpp +++ b/include/util/SafeSignal.hpp @@ -64,10 +64,10 @@ struct SafeSignal : sigc::signal...)> { } } - Glib::Dispatcher dp_; - std::mutex mutex_; + Glib::Dispatcher dp_; + std::mutex mutex_; std::queue queue_; - const std::thread::id main_tid_ = std::this_thread::get_id(); + const std::thread::id main_tid_ = std::this_thread::get_id(); // cache functor for signal emission to avoid recreating it on each event const slot_t cached_fn_ = make_slot(); }; diff --git a/include/util/clara.hpp b/include/util/clara.hpp index 6be5a98b..4cc6f486 100644 --- a/include/util/clara.hpp +++ b/include/util/clara.hpp @@ -27,7 +27,6 @@ #endif #endif - // ----------- #included from clara_textflow.hpp ----------- // TextFlowCpp @@ -51,1188 +50,1107 @@ #define CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80 #endif +namespace clara { +namespace TextFlow { -namespace clara { namespace TextFlow { +inline auto isWhitespace(char c) -> bool { + static std::string chars = " \t\n\r"; + return chars.find(c) != std::string::npos; +} +inline auto isBreakableBefore(char c) -> bool { + static std::string chars = "[({<|"; + return chars.find(c) != std::string::npos; +} +inline auto isBreakableAfter(char c) -> bool { + static std::string chars = "])}>.,:;*+-=&/\\"; + return chars.find(c) != std::string::npos; +} - inline auto isWhitespace( char c ) -> bool { - static std::string chars = " \t\n\r"; - return chars.find( c ) != std::string::npos; - } - inline auto isBreakableBefore( char c ) -> bool { - static std::string chars = "[({<|"; - return chars.find( c ) != std::string::npos; - } - inline auto isBreakableAfter( char c ) -> bool { - static std::string chars = "])}>.,:;*+-=&/\\"; - return chars.find( c ) != std::string::npos; +class Columns; + +class Column { + std::vector m_strings; + size_t m_width = CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH; + size_t m_indent = 0; + size_t m_initialIndent = std::string::npos; + + public: + class iterator { + friend Column; + + Column const &m_column; + size_t m_stringIndex = 0; + size_t m_pos = 0; + + size_t m_len = 0; + size_t m_end = 0; + bool m_suffix = false; + + iterator(Column const &column, size_t stringIndex) + : m_column(column), m_stringIndex(stringIndex) {} + + auto line() const -> std::string const & { return m_column.m_strings[m_stringIndex]; } + + auto isBoundary(size_t at) const -> bool { + assert(at > 0); + assert(at <= line().size()); + + return at == line().size() || (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) || + isBreakableBefore(line()[at]) || isBreakableAfter(line()[at - 1]); } - class Columns; + void calcLength() { + assert(m_stringIndex < m_column.m_strings.size()); - class Column { - std::vector m_strings; - size_t m_width = CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH; - size_t m_indent = 0; - size_t m_initialIndent = std::string::npos; + m_suffix = false; + auto width = m_column.m_width - indent(); + m_end = m_pos; + while (m_end < line().size() && line()[m_end] != '\n') ++m_end; - public: - class iterator { - friend Column; + if (m_end < m_pos + width) { + m_len = m_end - m_pos; + } else { + size_t len = width; + while (len > 0 && !isBoundary(m_pos + len)) --len; + while (len > 0 && isWhitespace(line()[m_pos + len - 1])) --len; - Column const& m_column; - size_t m_stringIndex = 0; - size_t m_pos = 0; - - size_t m_len = 0; - size_t m_end = 0; - bool m_suffix = false; - - iterator( Column const& column, size_t stringIndex ) - : m_column( column ), - m_stringIndex( stringIndex ) - {} - - auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; } - - auto isBoundary( size_t at ) const -> bool { - assert( at > 0 ); - assert( at <= line().size() ); - - return at == line().size() || - ( isWhitespace( line()[at] ) && !isWhitespace( line()[at-1] ) ) || - isBreakableBefore( line()[at] ) || - isBreakableAfter( line()[at-1] ); - } - - void calcLength() { - assert( m_stringIndex < m_column.m_strings.size() ); - - m_suffix = false; - auto width = m_column.m_width-indent(); - m_end = m_pos; - while( m_end < line().size() && line()[m_end] != '\n' ) - ++m_end; - - if( m_end < m_pos + width ) { - m_len = m_end - m_pos; - } - else { - size_t len = width; - while (len > 0 && !isBoundary(m_pos + len)) - --len; - while (len > 0 && isWhitespace( line()[m_pos + len - 1] )) - --len; - - if (len > 0) { - m_len = len; - } else { - m_suffix = true; - m_len = width - 1; - } - } - } - - auto indent() const -> size_t { - auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos; - return initial == std::string::npos ? m_column.m_indent : initial; - } - - auto addIndentAndSuffix(std::string const &plain) const -> std::string { - return std::string( indent(), ' ' ) + (m_suffix ? plain + "-" : plain); - } - - public: - using difference_type = std::ptrdiff_t; - using value_type = std::string; - using pointer = value_type*; - using reference = value_type&; - using iterator_category = std::forward_iterator_tag; - - explicit iterator( Column const& column ) : m_column( column ) { - assert( m_column.m_width > m_column.m_indent ); - assert( m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent ); - calcLength(); - if( m_len == 0 ) - m_stringIndex++; // Empty string - } - - auto operator *() const -> std::string { - assert( m_stringIndex < m_column.m_strings.size() ); - assert( m_pos <= m_end ); - return addIndentAndSuffix(line().substr(m_pos, m_len)); - } - - auto operator ++() -> iterator& { - m_pos += m_len; - if( m_pos < line().size() && line()[m_pos] == '\n' ) - m_pos += 1; - else - while( m_pos < line().size() && isWhitespace( line()[m_pos] ) ) - ++m_pos; - - if( m_pos == line().size() ) { - m_pos = 0; - ++m_stringIndex; - } - if( m_stringIndex < m_column.m_strings.size() ) - calcLength(); - return *this; - } - auto operator ++(int) -> iterator { - iterator prev( *this ); - operator++(); - return prev; - } - - auto operator ==( iterator const& other ) const -> bool { - return - m_pos == other.m_pos && - m_stringIndex == other.m_stringIndex && - &m_column == &other.m_column; - } - auto operator !=( iterator const& other ) const -> bool { - return !operator==( other ); - } - }; - using const_iterator = iterator; - - explicit Column( std::string const& text ) { m_strings.push_back( text ); } - - auto width( size_t newWidth ) -> Column& { - assert( newWidth > 0 ); - m_width = newWidth; - return *this; + if (len > 0) { + m_len = len; + } else { + m_suffix = true; + m_len = width - 1; } - auto indent( size_t newIndent ) -> Column& { - m_indent = newIndent; - return *this; - } - auto initialIndent( size_t newIndent ) -> Column& { - m_initialIndent = newIndent; - return *this; - } - - auto width() const -> size_t { return m_width; } - auto begin() const -> iterator { return iterator( *this ); } - auto end() const -> iterator { return { *this, m_strings.size() }; } - - inline friend std::ostream& operator << ( std::ostream& os, Column const& col ) { - bool first = true; - for( auto line : col ) { - if( first ) - first = false; - else - os << "\n"; - os << line; - } - return os; - } - - auto operator + ( Column const& other ) -> Columns; - - auto toString() const -> std::string { - std::ostringstream oss; - oss << *this; - return oss.str(); - } - }; - - class Spacer : public Column { - - public: - explicit Spacer( size_t spaceWidth ) : Column( "" ) { - width( spaceWidth ); - } - }; - - class Columns { - std::vector m_columns; - - public: - - class iterator { - friend Columns; - struct EndTag {}; - - std::vector const& m_columns; - std::vector m_iterators; - size_t m_activeIterators; - - iterator( Columns const& columns, EndTag ) - : m_columns( columns.m_columns ), - m_activeIterators( 0 ) - { - m_iterators.reserve( m_columns.size() ); - - for( auto const& col : m_columns ) - m_iterators.push_back( col.end() ); - } - - public: - using difference_type = std::ptrdiff_t; - using value_type = std::string; - using pointer = value_type*; - using reference = value_type&; - using iterator_category = std::forward_iterator_tag; - - explicit iterator( Columns const& columns ) - : m_columns( columns.m_columns ), - m_activeIterators( m_columns.size() ) - { - m_iterators.reserve( m_columns.size() ); - - for( auto const& col : m_columns ) - m_iterators.push_back( col.begin() ); - } - - auto operator ==( iterator const& other ) const -> bool { - return m_iterators == other.m_iterators; - } - auto operator !=( iterator const& other ) const -> bool { - return m_iterators != other.m_iterators; - } - auto operator *() const -> std::string { - std::string row, padding; - - for( size_t i = 0; i < m_columns.size(); ++i ) { - auto width = m_columns[i].width(); - if( m_iterators[i] != m_columns[i].end() ) { - std::string col = *m_iterators[i]; - row += padding + col; - if( col.size() < width ) - padding = std::string( width - col.size(), ' ' ); - else - padding = ""; - } - else { - padding += std::string( width, ' ' ); - } - } - return row; - } - auto operator ++() -> iterator& { - for( size_t i = 0; i < m_columns.size(); ++i ) { - if (m_iterators[i] != m_columns[i].end()) - ++m_iterators[i]; - } - return *this; - } - auto operator ++(int) -> iterator { - iterator prev( *this ); - operator++(); - return prev; - } - }; - using const_iterator = iterator; - - auto begin() const -> iterator { return iterator( *this ); } - auto end() const -> iterator { return { *this, iterator::EndTag() }; } - - auto operator += ( Column const& col ) -> Columns& { - m_columns.push_back( col ); - return *this; - } - auto operator + ( Column const& col ) -> Columns { - Columns combined = *this; - combined += col; - return combined; - } - - inline friend std::ostream& operator << ( std::ostream& os, Columns const& cols ) { - - bool first = true; - for( auto line : cols ) { - if( first ) - first = false; - else - os << "\n"; - os << line; - } - return os; - } - - auto toString() const -> std::string { - std::ostringstream oss; - oss << *this; - return oss.str(); - } - }; - - inline auto Column::operator + ( Column const& other ) -> Columns { - Columns cols; - cols += *this; - cols += other; - return cols; + } } -}} -#endif // CLARA_TEXTFLOW_HPP_INCLUDED + auto indent() const -> size_t { + auto initial = + m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos; + return initial == std::string::npos ? m_column.m_indent : initial; + } + + auto addIndentAndSuffix(std::string const &plain) const -> std::string { + return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain); + } + + public: + using difference_type = std::ptrdiff_t; + using value_type = std::string; + using pointer = value_type *; + using reference = value_type &; + using iterator_category = std::forward_iterator_tag; + + explicit iterator(Column const &column) : m_column(column) { + assert(m_column.m_width > m_column.m_indent); + assert(m_column.m_initialIndent == std::string::npos || + m_column.m_width > m_column.m_initialIndent); + calcLength(); + if (m_len == 0) m_stringIndex++; // Empty string + } + + auto operator*() const -> std::string { + assert(m_stringIndex < m_column.m_strings.size()); + assert(m_pos <= m_end); + return addIndentAndSuffix(line().substr(m_pos, m_len)); + } + + auto operator++() -> iterator & { + m_pos += m_len; + if (m_pos < line().size() && line()[m_pos] == '\n') + m_pos += 1; + else + while (m_pos < line().size() && isWhitespace(line()[m_pos])) ++m_pos; + + if (m_pos == line().size()) { + m_pos = 0; + ++m_stringIndex; + } + if (m_stringIndex < m_column.m_strings.size()) calcLength(); + return *this; + } + auto operator++(int) -> iterator { + iterator prev(*this); + operator++(); + return prev; + } + + auto operator==(iterator const &other) const -> bool { + return m_pos == other.m_pos && m_stringIndex == other.m_stringIndex && + &m_column == &other.m_column; + } + auto operator!=(iterator const &other) const -> bool { return !operator==(other); } + }; + using const_iterator = iterator; + + explicit Column(std::string const &text) { m_strings.push_back(text); } + + auto width(size_t newWidth) -> Column & { + assert(newWidth > 0); + m_width = newWidth; + return *this; + } + auto indent(size_t newIndent) -> Column & { + m_indent = newIndent; + return *this; + } + auto initialIndent(size_t newIndent) -> Column & { + m_initialIndent = newIndent; + return *this; + } + + auto width() const -> size_t { return m_width; } + auto begin() const -> iterator { return iterator(*this); } + auto end() const -> iterator { return {*this, m_strings.size()}; } + + inline friend std::ostream &operator<<(std::ostream &os, Column const &col) { + bool first = true; + for (auto line : col) { + if (first) + first = false; + else + os << "\n"; + os << line; + } + return os; + } + + auto operator+(Column const &other) -> Columns; + + auto toString() const -> std::string { + std::ostringstream oss; + oss << *this; + return oss.str(); + } +}; + +class Spacer : public Column { + public: + explicit Spacer(size_t spaceWidth) : Column("") { width(spaceWidth); } +}; + +class Columns { + std::vector m_columns; + + public: + class iterator { + friend Columns; + struct EndTag {}; + + std::vector const &m_columns; + std::vector m_iterators; + size_t m_activeIterators; + + iterator(Columns const &columns, EndTag) : m_columns(columns.m_columns), m_activeIterators(0) { + m_iterators.reserve(m_columns.size()); + + for (auto const &col : m_columns) m_iterators.push_back(col.end()); + } + + public: + using difference_type = std::ptrdiff_t; + using value_type = std::string; + using pointer = value_type *; + using reference = value_type &; + using iterator_category = std::forward_iterator_tag; + + explicit iterator(Columns const &columns) + : m_columns(columns.m_columns), m_activeIterators(m_columns.size()) { + m_iterators.reserve(m_columns.size()); + + for (auto const &col : m_columns) m_iterators.push_back(col.begin()); + } + + auto operator==(iterator const &other) const -> bool { + return m_iterators == other.m_iterators; + } + auto operator!=(iterator const &other) const -> bool { + return m_iterators != other.m_iterators; + } + auto operator*() const -> std::string { + std::string row, padding; + + for (size_t i = 0; i < m_columns.size(); ++i) { + auto width = m_columns[i].width(); + if (m_iterators[i] != m_columns[i].end()) { + std::string col = *m_iterators[i]; + row += padding + col; + if (col.size() < width) + padding = std::string(width - col.size(), ' '); + else + padding = ""; + } else { + padding += std::string(width, ' '); + } + } + return row; + } + auto operator++() -> iterator & { + for (size_t i = 0; i < m_columns.size(); ++i) { + if (m_iterators[i] != m_columns[i].end()) ++m_iterators[i]; + } + return *this; + } + auto operator++(int) -> iterator { + iterator prev(*this); + operator++(); + return prev; + } + }; + using const_iterator = iterator; + + auto begin() const -> iterator { return iterator(*this); } + auto end() const -> iterator { return {*this, iterator::EndTag()}; } + + auto operator+=(Column const &col) -> Columns & { + m_columns.push_back(col); + return *this; + } + auto operator+(Column const &col) -> Columns { + Columns combined = *this; + combined += col; + return combined; + } + + inline friend std::ostream &operator<<(std::ostream &os, Columns const &cols) { + bool first = true; + for (auto line : cols) { + if (first) + first = false; + else + os << "\n"; + os << line; + } + return os; + } + + auto toString() const -> std::string { + std::ostringstream oss; + oss << *this; + return oss.str(); + } +}; + +inline auto Column::operator+(Column const &other) -> Columns { + Columns cols; + cols += *this; + cols += other; + return cols; +} +} // namespace TextFlow +} // namespace clara + +#endif // CLARA_TEXTFLOW_HPP_INCLUDED // ----------- end of #include from clara_textflow.hpp ----------- // ........... back in clara.hpp - +#include #include #include -#include -#if !defined(CLARA_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) ) +#if !defined(CLARA_PLATFORM_WINDOWS) && \ + (defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER)) #define CLARA_PLATFORM_WINDOWS #endif namespace clara { namespace detail { - // Traits for extracting arg and return type of lambdas (for single argument lambdas) - template - struct UnaryLambdaTraits : UnaryLambdaTraits {}; +// Traits for extracting arg and return type of lambdas (for single argument lambdas) +template +struct UnaryLambdaTraits : UnaryLambdaTraits {}; - template - struct UnaryLambdaTraits { - static const bool isValid = false; - }; +template +struct UnaryLambdaTraits { + static const bool isValid = false; +}; - template - struct UnaryLambdaTraits { - static const bool isValid = true; - using ArgType = typename std::remove_const::type>::type; - using ReturnType = ReturnT; - }; +template +struct UnaryLambdaTraits { + static const bool isValid = true; + using ArgType = typename std::remove_const::type>::type; + using ReturnType = ReturnT; +}; - class TokenStream; +class TokenStream; - // Transport for raw args (copied from main args, or supplied via init list for testing) - class Args { - friend TokenStream; - std::string m_exeName; - std::vector m_args; +// Transport for raw args (copied from main args, or supplied via init list for testing) +class Args { + friend TokenStream; + std::string m_exeName; + std::vector m_args; - public: - Args( int argc, char const* const* argv ) - : m_exeName(argv[0]), - m_args(argv + 1, argv + argc) {} + public: + Args(int argc, char const *const *argv) : m_exeName(argv[0]), m_args(argv + 1, argv + argc) {} - Args( std::initializer_list args ) - : m_exeName( *args.begin() ), - m_args( args.begin()+1, args.end() ) - {} + Args(std::initializer_list args) + : m_exeName(*args.begin()), m_args(args.begin() + 1, args.end()) {} - auto exeName() const -> std::string { - return m_exeName; - } - }; + auto exeName() const -> std::string { return m_exeName; } +}; - // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string - // may encode an option + its argument if the : or = form is used - enum class TokenType { - Option, Argument - }; - struct Token { - TokenType type; - std::string token; - }; +// Wraps a token coming from a token stream. These may not directly correspond to strings as a +// single string may encode an option + its argument if the : or = form is used +enum class TokenType { Option, Argument }; +struct Token { + TokenType type; + std::string token; +}; - inline auto isOptPrefix( char c ) -> bool { - return c == '-' +inline auto isOptPrefix(char c) -> bool { + return c == '-' #ifdef CLARA_PLATFORM_WINDOWS - || c == '/' + || c == '/' #endif - ; - } + ; +} - // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled - class TokenStream { - using Iterator = std::vector::const_iterator; - Iterator it; - Iterator itEnd; - std::vector m_tokenBuffer; +// Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled +class TokenStream { + using Iterator = std::vector::const_iterator; + Iterator it; + Iterator itEnd; + std::vector m_tokenBuffer; - void loadBuffer() { - m_tokenBuffer.resize( 0 ); + void loadBuffer() { + m_tokenBuffer.resize(0); - // Skip any empty strings - while( it != itEnd && it->empty() ) - ++it; + // Skip any empty strings + while (it != itEnd && it->empty()) ++it; - if( it != itEnd ) { - auto const &next = *it; - if( isOptPrefix( next[0] ) ) { - auto delimiterPos = next.find_first_of( " :=" ); - if( delimiterPos != std::string::npos ) { - m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } ); - m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } ); - } else { - if( next[1] != '-' && next.size() > 2 ) { - std::string opt = "- "; - for( size_t i = 1; i < next.size(); ++i ) { - opt[1] = next[i]; - m_tokenBuffer.push_back( { TokenType::Option, opt } ); - } - } else { - m_tokenBuffer.push_back( { TokenType::Option, next } ); - } - } - } else { - m_tokenBuffer.push_back( { TokenType::Argument, next } ); - } + if (it != itEnd) { + auto const &next = *it; + if (isOptPrefix(next[0])) { + auto delimiterPos = next.find_first_of(" :="); + if (delimiterPos != std::string::npos) { + m_tokenBuffer.push_back({TokenType::Option, next.substr(0, delimiterPos)}); + m_tokenBuffer.push_back({TokenType::Argument, next.substr(delimiterPos + 1)}); + } else { + if (next[1] != '-' && next.size() > 2) { + std::string opt = "- "; + for (size_t i = 1; i < next.size(); ++i) { + opt[1] = next[i]; + m_tokenBuffer.push_back({TokenType::Option, opt}); } + } else { + m_tokenBuffer.push_back({TokenType::Option, next}); + } } - - public: - explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {} - - TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) { - loadBuffer(); - } - - explicit operator bool() const { - return !m_tokenBuffer.empty() || it != itEnd; - } - - auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); } - - auto operator*() const -> Token { - assert( !m_tokenBuffer.empty() ); - return m_tokenBuffer.front(); - } - - auto operator->() const -> Token const * { - assert( !m_tokenBuffer.empty() ); - return &m_tokenBuffer.front(); - } - - auto operator++() -> TokenStream & { - if( m_tokenBuffer.size() >= 2 ) { - m_tokenBuffer.erase( m_tokenBuffer.begin() ); - } else { - if( it != itEnd ) - ++it; - loadBuffer(); - } - return *this; - } - }; - - - class ResultBase { - public: - enum Type { - Ok, LogicError, RuntimeError - }; - - protected: - ResultBase( Type type ) : m_type( type ) {} - virtual ~ResultBase() = default; - - virtual void enforceOk() const = 0; - - Type m_type; - }; - - template - class ResultValueBase : public ResultBase { - public: - auto value() const -> T const & { - enforceOk(); - return m_value; - } - - protected: - ResultValueBase( Type type ) : ResultBase( type ) {} - - ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) { - if( m_type == ResultBase::Ok ) - new( &m_value ) T( other.m_value ); - } - - ResultValueBase( Type, T const &value ) : ResultBase( Ok ) { - new( &m_value ) T( value ); - } - - auto operator=( ResultValueBase const &other ) -> ResultValueBase & { - if( m_type == ResultBase::Ok ) - m_value.~T(); - ResultBase::operator=(other); - if( m_type == ResultBase::Ok ) - new( &m_value ) T( other.m_value ); - return *this; - } - - ~ResultValueBase() override { - if( m_type == Ok ) - m_value.~T(); - } - - union { - T m_value; - }; - }; - - template<> - class ResultValueBase : public ResultBase { - protected: - using ResultBase::ResultBase; - }; - - template - class BasicResult : public ResultValueBase { - public: - template - explicit BasicResult( BasicResult const &other ) - : ResultValueBase( other.type() ), - m_errorMessage( other.errorMessage() ) - { - assert( type() != ResultBase::Ok ); - } - - template - static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; } - static auto ok() -> BasicResult { return { ResultBase::Ok }; } - static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; } - static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; } - - explicit operator bool() const { return m_type == ResultBase::Ok; } - auto type() const -> ResultBase::Type { return m_type; } - auto errorMessage() const -> std::string { return m_errorMessage; } - - protected: - void enforceOk() const override { - - // Errors shouldn't reach this point, but if they do - // the actual error message will be in m_errorMessage - assert( m_type != ResultBase::LogicError ); - assert( m_type != ResultBase::RuntimeError ); - if( m_type != ResultBase::Ok ) - std::abort(); - } - - std::string m_errorMessage; // Only populated if resultType is an error - - BasicResult( ResultBase::Type type, std::string const &message ) - : ResultValueBase(type), - m_errorMessage(message) - { - assert( m_type != ResultBase::Ok ); - } - - using ResultValueBase::ResultValueBase; - using ResultBase::m_type; - }; - - enum class ParseResultType { - Matched, NoMatch, ShortCircuitAll, ShortCircuitSame - }; - - class ParseState { - public: - - ParseState( ParseResultType type, TokenStream const &remainingTokens ) - : m_type(type), - m_remainingTokens( remainingTokens ) - {} - - auto type() const -> ParseResultType { return m_type; } - auto remainingTokens() const -> TokenStream { return m_remainingTokens; } - - private: - ParseResultType m_type; - TokenStream m_remainingTokens; - }; - - using Result = BasicResult; - using ParserResult = BasicResult; - using InternalParseResult = BasicResult; - - struct HelpColumns { - std::string left; - std::string right; - }; - - template - inline auto convertInto( std::string const &source, T& target ) -> ParserResult { - std::stringstream ss; - ss << source; - ss >> target; - if( ss.fail() ) - return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" ); - else - return ParserResult::ok( ParseResultType::Matched ); + } else { + m_tokenBuffer.push_back({TokenType::Argument, next}); + } } - inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult { - target = source; - return ParserResult::ok( ParseResultType::Matched ); - } - inline auto convertInto( std::string const &source, bool &target ) -> ParserResult { - std::string srcLC = source; - std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast( ::tolower(c) ); } ); - if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on") - target = true; - else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off") - target = false; - else - return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" ); - return ParserResult::ok( ParseResultType::Matched ); + } + + public: + explicit TokenStream(Args const &args) : TokenStream(args.m_args.begin(), args.m_args.end()) {} + + TokenStream(Iterator it, Iterator itEnd) : it(it), itEnd(itEnd) { loadBuffer(); } + + explicit operator bool() const { return !m_tokenBuffer.empty() || it != itEnd; } + + auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); } + + auto operator*() const -> Token { + assert(!m_tokenBuffer.empty()); + return m_tokenBuffer.front(); + } + + auto operator->() const -> Token const * { + assert(!m_tokenBuffer.empty()); + return &m_tokenBuffer.front(); + } + + auto operator++() -> TokenStream & { + if (m_tokenBuffer.size() >= 2) { + m_tokenBuffer.erase(m_tokenBuffer.begin()); + } else { + if (it != itEnd) ++it; + loadBuffer(); } + return *this; + } +}; + +class ResultBase { + public: + enum Type { Ok, LogicError, RuntimeError }; + + protected: + ResultBase(Type type) : m_type(type) {} + virtual ~ResultBase() = default; + + virtual void enforceOk() const = 0; + + Type m_type; +}; + +template +class ResultValueBase : public ResultBase { + public: + auto value() const -> T const & { + enforceOk(); + return m_value; + } + + protected: + ResultValueBase(Type type) : ResultBase(type) {} + + ResultValueBase(ResultValueBase const &other) : ResultBase(other) { + if (m_type == ResultBase::Ok) new (&m_value) T(other.m_value); + } + + ResultValueBase(Type, T const &value) : ResultBase(Ok) { new (&m_value) T(value); } + + auto operator=(ResultValueBase const &other) -> ResultValueBase & { + if (m_type == ResultBase::Ok) m_value.~T(); + ResultBase::operator=(other); + if (m_type == ResultBase::Ok) new (&m_value) T(other.m_value); + return *this; + } + + ~ResultValueBase() override { + if (m_type == Ok) m_value.~T(); + } + + union { + T m_value; + }; +}; + +template <> +class ResultValueBase : public ResultBase { + protected: + using ResultBase::ResultBase; +}; + +template +class BasicResult : public ResultValueBase { + public: + template + explicit BasicResult(BasicResult const &other) + : ResultValueBase(other.type()), m_errorMessage(other.errorMessage()) { + assert(type() != ResultBase::Ok); + } + + template + static auto ok(U const &value) -> BasicResult { + return {ResultBase::Ok, value}; + } + static auto ok() -> BasicResult { return {ResultBase::Ok}; } + static auto logicError(std::string const &message) -> BasicResult { + return {ResultBase::LogicError, message}; + } + static auto runtimeError(std::string const &message) -> BasicResult { + return {ResultBase::RuntimeError, message}; + } + + explicit operator bool() const { return m_type == ResultBase::Ok; } + auto type() const -> ResultBase::Type { return m_type; } + auto errorMessage() const -> std::string { return m_errorMessage; } + + protected: + void enforceOk() const override { + // Errors shouldn't reach this point, but if they do + // the actual error message will be in m_errorMessage + assert(m_type != ResultBase::LogicError); + assert(m_type != ResultBase::RuntimeError); + if (m_type != ResultBase::Ok) std::abort(); + } + + std::string m_errorMessage; // Only populated if resultType is an error + + BasicResult(ResultBase::Type type, std::string const &message) + : ResultValueBase(type), m_errorMessage(message) { + assert(m_type != ResultBase::Ok); + } + + using ResultValueBase::ResultValueBase; + using ResultBase::m_type; +}; + +enum class ParseResultType { Matched, NoMatch, ShortCircuitAll, ShortCircuitSame }; + +class ParseState { + public: + ParseState(ParseResultType type, TokenStream const &remainingTokens) + : m_type(type), m_remainingTokens(remainingTokens) {} + + auto type() const -> ParseResultType { return m_type; } + auto remainingTokens() const -> TokenStream { return m_remainingTokens; } + + private: + ParseResultType m_type; + TokenStream m_remainingTokens; +}; + +using Result = BasicResult; +using ParserResult = BasicResult; +using InternalParseResult = BasicResult; + +struct HelpColumns { + std::string left; + std::string right; +}; + +template +inline auto convertInto(std::string const &source, T &target) -> ParserResult { + std::stringstream ss; + ss << source; + ss >> target; + if (ss.fail()) + return ParserResult::runtimeError("Unable to convert '" + source + "' to destination type"); + else + return ParserResult::ok(ParseResultType::Matched); +} +inline auto convertInto(std::string const &source, std::string &target) -> ParserResult { + target = source; + return ParserResult::ok(ParseResultType::Matched); +} +inline auto convertInto(std::string const &source, bool &target) -> ParserResult { + std::string srcLC = source; + std::transform(srcLC.begin(), srcLC.end(), srcLC.begin(), + [](char c) { return static_cast(::tolower(c)); }); + if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on") + target = true; + else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off") + target = false; + else + return ParserResult::runtimeError("Expected a boolean value but did not recognise: '" + source + + "'"); + return ParserResult::ok(ParseResultType::Matched); +} #ifdef CLARA_CONFIG_OPTIONAL_TYPE - template - inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE& target ) -> ParserResult { - T temp; - auto result = convertInto( source, temp ); - if( result ) - target = std::move(temp); - return result; - } -#endif // CLARA_CONFIG_OPTIONAL_TYPE +template +inline auto convertInto(std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE &target) + -> ParserResult { + T temp; + auto result = convertInto(source, temp); + if (result) target = std::move(temp); + return result; +} +#endif // CLARA_CONFIG_OPTIONAL_TYPE - struct NonCopyable { - NonCopyable() = default; - NonCopyable( NonCopyable const & ) = delete; - NonCopyable( NonCopyable && ) = delete; - NonCopyable &operator=( NonCopyable const & ) = delete; - NonCopyable &operator=( NonCopyable && ) = delete; - }; +struct NonCopyable { + NonCopyable() = default; + NonCopyable(NonCopyable const &) = delete; + NonCopyable(NonCopyable &&) = delete; + NonCopyable &operator=(NonCopyable const &) = delete; + NonCopyable &operator=(NonCopyable &&) = delete; +}; - struct BoundRef : NonCopyable { - virtual ~BoundRef() = default; - virtual auto isContainer() const -> bool { return false; } - virtual auto isFlag() const -> bool { return false; } - }; - struct BoundValueRefBase : BoundRef { - virtual auto setValue( std::string const &arg ) -> ParserResult = 0; - }; - struct BoundFlagRefBase : BoundRef { - virtual auto setFlag( bool flag ) -> ParserResult = 0; - virtual auto isFlag() const -> bool { return true; } - }; +struct BoundRef : NonCopyable { + virtual ~BoundRef() = default; + virtual auto isContainer() const -> bool { return false; } + virtual auto isFlag() const -> bool { return false; } +}; +struct BoundValueRefBase : BoundRef { + virtual auto setValue(std::string const &arg) -> ParserResult = 0; +}; +struct BoundFlagRefBase : BoundRef { + virtual auto setFlag(bool flag) -> ParserResult = 0; + virtual auto isFlag() const -> bool { return true; } +}; - template - struct BoundValueRef : BoundValueRefBase { - T &m_ref; +template +struct BoundValueRef : BoundValueRefBase { + T &m_ref; - explicit BoundValueRef( T &ref ) : m_ref( ref ) {} + explicit BoundValueRef(T &ref) : m_ref(ref) {} - auto setValue( std::string const &arg ) -> ParserResult override { - return convertInto( arg, m_ref ); - } - }; + auto setValue(std::string const &arg) -> ParserResult override { return convertInto(arg, m_ref); } +}; - template - struct BoundValueRef> : BoundValueRefBase { - std::vector &m_ref; +template +struct BoundValueRef> : BoundValueRefBase { + std::vector &m_ref; - explicit BoundValueRef( std::vector &ref ) : m_ref( ref ) {} + explicit BoundValueRef(std::vector &ref) : m_ref(ref) {} - auto isContainer() const -> bool override { return true; } + auto isContainer() const -> bool override { return true; } - auto setValue( std::string const &arg ) -> ParserResult override { - T temp; - auto result = convertInto( arg, temp ); - if( result ) - m_ref.push_back( temp ); - return result; - } - }; + auto setValue(std::string const &arg) -> ParserResult override { + T temp; + auto result = convertInto(arg, temp); + if (result) m_ref.push_back(temp); + return result; + } +}; - struct BoundFlagRef : BoundFlagRefBase { - bool &m_ref; +struct BoundFlagRef : BoundFlagRefBase { + bool &m_ref; - explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {} + explicit BoundFlagRef(bool &ref) : m_ref(ref) {} - auto setFlag( bool flag ) -> ParserResult override { - m_ref = flag; - return ParserResult::ok( ParseResultType::Matched ); - } - }; + auto setFlag(bool flag) -> ParserResult override { + m_ref = flag; + return ParserResult::ok(ParseResultType::Matched); + } +}; - template - struct LambdaInvoker { - static_assert( std::is_same::value, "Lambda must return void or clara::ParserResult" ); +template +struct LambdaInvoker { + static_assert(std::is_same::value, + "Lambda must return void or clara::ParserResult"); - template - static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult { - return lambda( arg ); - } - }; + template + static auto invoke(L const &lambda, ArgType const &arg) -> ParserResult { + return lambda(arg); + } +}; - template<> - struct LambdaInvoker { - template - static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult { - lambda( arg ); - return ParserResult::ok( ParseResultType::Matched ); - } - }; +template <> +struct LambdaInvoker { + template + static auto invoke(L const &lambda, ArgType const &arg) -> ParserResult { + lambda(arg); + return ParserResult::ok(ParseResultType::Matched); + } +}; - template - inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult { - ArgType temp{}; - auto result = convertInto( arg, temp ); - return !result - ? result - : LambdaInvoker::ReturnType>::invoke( lambda, temp ); - } +template +inline auto invokeLambda(L const &lambda, std::string const &arg) -> ParserResult { + ArgType temp{}; + auto result = convertInto(arg, temp); + return !result ? result + : LambdaInvoker::ReturnType>::invoke(lambda, temp); +} +template +struct BoundLambda : BoundValueRefBase { + L m_lambda; - template - struct BoundLambda : BoundValueRefBase { - L m_lambda; + static_assert(UnaryLambdaTraits::isValid, "Supplied lambda must take exactly one argument"); + explicit BoundLambda(L const &lambda) : m_lambda(lambda) {} - static_assert( UnaryLambdaTraits::isValid, "Supplied lambda must take exactly one argument" ); - explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {} + auto setValue(std::string const &arg) -> ParserResult override { + return invokeLambda::ArgType>(m_lambda, arg); + } +}; - auto setValue( std::string const &arg ) -> ParserResult override { - return invokeLambda::ArgType>( m_lambda, arg ); - } - }; +template +struct BoundFlagLambda : BoundFlagRefBase { + L m_lambda; - template - struct BoundFlagLambda : BoundFlagRefBase { - L m_lambda; + static_assert(UnaryLambdaTraits::isValid, "Supplied lambda must take exactly one argument"); + static_assert(std::is_same::ArgType, bool>::value, + "flags must be boolean"); - static_assert( UnaryLambdaTraits::isValid, "Supplied lambda must take exactly one argument" ); - static_assert( std::is_same::ArgType, bool>::value, "flags must be boolean" ); + explicit BoundFlagLambda(L const &lambda) : m_lambda(lambda) {} - explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {} + auto setFlag(bool flag) -> ParserResult override { + return LambdaInvoker::ReturnType>::invoke(m_lambda, flag); + } +}; - auto setFlag( bool flag ) -> ParserResult override { - return LambdaInvoker::ReturnType>::invoke( m_lambda, flag ); - } - }; +enum class Optionality { Optional, Required }; - enum class Optionality { Optional, Required }; +struct Parser; - struct Parser; +class ParserBase { + public: + virtual ~ParserBase() = default; + virtual auto validate() const -> Result { return Result::ok(); } + virtual auto parse(std::string const &exeName, TokenStream const &tokens) const + -> InternalParseResult = 0; + virtual auto cardinality() const -> size_t { return 1; } - class ParserBase { - public: - virtual ~ParserBase() = default; - virtual auto validate() const -> Result { return Result::ok(); } - virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0; - virtual auto cardinality() const -> size_t { return 1; } + auto parse(Args const &args) const -> InternalParseResult { + return parse(args.exeName(), TokenStream(args)); + } +}; - auto parse( Args const &args ) const -> InternalParseResult { - return parse( args.exeName(), TokenStream( args ) ); - } - }; +template +class ComposableParserImpl : public ParserBase { + public: + template + auto operator|(T const &other) const -> Parser; - template - class ComposableParserImpl : public ParserBase { - public: - template - auto operator|( T const &other ) const -> Parser; + template + auto operator+(T const &other) const -> Parser; +}; - template - auto operator+( T const &other ) const -> Parser; - }; +// Common code and state for Args and Opts +template +class ParserRefImpl : public ComposableParserImpl { + protected: + Optionality m_optionality = Optionality::Optional; + std::shared_ptr m_ref; + std::string m_hint; + std::string m_description; - // Common code and state for Args and Opts - template - class ParserRefImpl : public ComposableParserImpl { - protected: - Optionality m_optionality = Optionality::Optional; - std::shared_ptr m_ref; - std::string m_hint; - std::string m_description; + explicit ParserRefImpl(std::shared_ptr const &ref) : m_ref(ref) {} - explicit ParserRefImpl( std::shared_ptr const &ref ) : m_ref( ref ) {} + public: + template + ParserRefImpl(T &ref, std::string const &hint) + : m_ref(std::make_shared>(ref)), m_hint(hint) {} - public: - template - ParserRefImpl( T &ref, std::string const &hint ) - : m_ref( std::make_shared>( ref ) ), - m_hint( hint ) - {} + template + ParserRefImpl(LambdaT const &ref, std::string const &hint) + : m_ref(std::make_shared>(ref)), m_hint(hint) {} - template - ParserRefImpl( LambdaT const &ref, std::string const &hint ) - : m_ref( std::make_shared>( ref ) ), - m_hint(hint) - {} + auto operator()(std::string const &description) -> DerivedT & { + m_description = description; + return static_cast(*this); + } - auto operator()( std::string const &description ) -> DerivedT & { - m_description = description; - return static_cast( *this ); - } + auto optional() -> DerivedT & { + m_optionality = Optionality::Optional; + return static_cast(*this); + }; - auto optional() -> DerivedT & { - m_optionality = Optionality::Optional; - return static_cast( *this ); - }; + auto required() -> DerivedT & { + m_optionality = Optionality::Required; + return static_cast(*this); + }; - auto required() -> DerivedT & { - m_optionality = Optionality::Required; - return static_cast( *this ); - }; + auto isOptional() const -> bool { return m_optionality == Optionality::Optional; } - auto isOptional() const -> bool { - return m_optionality == Optionality::Optional; - } + auto cardinality() const -> size_t override { + if (m_ref->isContainer()) + return 0; + else + return 1; + } - auto cardinality() const -> size_t override { - if( m_ref->isContainer() ) - return 0; - else - return 1; - } + auto hint() const -> std::string { return m_hint; } +}; - auto hint() const -> std::string { return m_hint; } - }; +class ExeName : public ComposableParserImpl { + std::shared_ptr m_name; + std::shared_ptr m_ref; - class ExeName : public ComposableParserImpl { - std::shared_ptr m_name; - std::shared_ptr m_ref; + template + static auto makeRef(LambdaT const &lambda) -> std::shared_ptr { + return std::make_shared>(lambda); + } - template - static auto makeRef(LambdaT const &lambda) -> std::shared_ptr { - return std::make_shared>( lambda) ; - } + public: + ExeName() : m_name(std::make_shared("")) {} - public: - ExeName() : m_name( std::make_shared( "" ) ) {} + explicit ExeName(std::string &ref) : ExeName() { + m_ref = std::make_shared>(ref); + } - explicit ExeName( std::string &ref ) : ExeName() { - m_ref = std::make_shared>( ref ); - } + template + explicit ExeName(LambdaT const &lambda) : ExeName() { + m_ref = std::make_shared>(lambda); + } - template - explicit ExeName( LambdaT const& lambda ) : ExeName() { - m_ref = std::make_shared>( lambda ); - } + // The exe name is not parsed out of the normal tokens, but is handled specially + auto parse(std::string const &, TokenStream const &tokens) const -> InternalParseResult override { + return InternalParseResult::ok(ParseState(ParseResultType::NoMatch, tokens)); + } - // The exe name is not parsed out of the normal tokens, but is handled specially - auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override { - return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) ); - } + auto name() const -> std::string { return *m_name; } + auto set(std::string const &newName) -> ParserResult { + auto lastSlash = newName.find_last_of("\\/"); + auto filename = (lastSlash == std::string::npos) ? newName : newName.substr(lastSlash + 1); - auto name() const -> std::string { return *m_name; } - auto set( std::string const& newName ) -> ParserResult { + *m_name = filename; + if (m_ref) + return m_ref->setValue(filename); + else + return ParserResult::ok(ParseResultType::Matched); + } +}; - auto lastSlash = newName.find_last_of( "\\/" ); - auto filename = ( lastSlash == std::string::npos ) - ? newName - : newName.substr( lastSlash+1 ); +class Arg : public ParserRefImpl { + public: + using ParserRefImpl::ParserRefImpl; - *m_name = filename; - if( m_ref ) - return m_ref->setValue( filename ); - else - return ParserResult::ok( ParseResultType::Matched ); - } - }; + auto parse(std::string const &, TokenStream const &tokens) const -> InternalParseResult override { + auto validationResult = validate(); + if (!validationResult) return InternalParseResult(validationResult); - class Arg : public ParserRefImpl { - public: - using ParserRefImpl::ParserRefImpl; + auto remainingTokens = tokens; + auto const &token = *remainingTokens; + if (token.type != TokenType::Argument) + return InternalParseResult::ok(ParseState(ParseResultType::NoMatch, remainingTokens)); - auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override { - auto validationResult = validate(); - if( !validationResult ) - return InternalParseResult( validationResult ); + assert(!m_ref->isFlag()); + auto valueRef = static_cast(m_ref.get()); - auto remainingTokens = tokens; - auto const &token = *remainingTokens; - if( token.type != TokenType::Argument ) - return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) ); + auto result = valueRef->setValue(remainingTokens->token); + if (!result) + return InternalParseResult(result); + else + return InternalParseResult::ok(ParseState(ParseResultType::Matched, ++remainingTokens)); + } +}; - assert( !m_ref->isFlag() ); - auto valueRef = static_cast( m_ref.get() ); - - auto result = valueRef->setValue( remainingTokens->token ); - if( !result ) - return InternalParseResult( result ); - else - return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) ); - } - }; - - inline auto normaliseOpt( std::string const &optName ) -> std::string { +inline auto normaliseOpt(std::string const &optName) -> std::string { #ifdef CLARA_PLATFORM_WINDOWS - if( optName[0] == '/' ) - return "-" + optName.substr( 1 ); - else + if (optName[0] == '/') + return "-" + optName.substr(1); + else #endif - return optName; + return optName; +} + +class Opt : public ParserRefImpl { + protected: + std::vector m_optNames; + + public: + template + explicit Opt(LambdaT const &ref) + : ParserRefImpl(std::make_shared>(ref)) {} + + explicit Opt(bool &ref) : ParserRefImpl(std::make_shared(ref)) {} + + template + Opt(LambdaT const &ref, std::string const &hint) : ParserRefImpl(ref, hint) {} + + template + Opt(T &ref, std::string const &hint) : ParserRefImpl(ref, hint) {} + + auto operator[](std::string const &optName) -> Opt & { + m_optNames.push_back(optName); + return *this; + } + + auto getHelpColumns() const -> std::vector { + std::ostringstream oss; + bool first = true; + for (auto const &opt : m_optNames) { + if (first) + first = false; + else + oss << ", "; + oss << opt; } + if (!m_hint.empty()) oss << " <" << m_hint << ">"; + return {{oss.str(), m_description}}; + } - class Opt : public ParserRefImpl { - protected: - std::vector m_optNames; + auto isMatch(std::string const &optToken) const -> bool { + auto normalisedToken = normaliseOpt(optToken); + for (auto const &name : m_optNames) { + if (normaliseOpt(name) == normalisedToken) return true; + } + return false; + } - public: - template - explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared>( ref ) ) {} + using ParserBase::parse; - explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared( ref ) ) {} + auto parse(std::string const &, TokenStream const &tokens) const -> InternalParseResult override { + auto validationResult = validate(); + if (!validationResult) return InternalParseResult(validationResult); - template - Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {} - - template - Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {} - - auto operator[]( std::string const &optName ) -> Opt & { - m_optNames.push_back( optName ); - return *this; + auto remainingTokens = tokens; + if (remainingTokens && remainingTokens->type == TokenType::Option) { + auto const &token = *remainingTokens; + if (isMatch(token.token)) { + if (m_ref->isFlag()) { + auto flagRef = static_cast(m_ref.get()); + auto result = flagRef->setFlag(true); + if (!result) return InternalParseResult(result); + if (result.value() == ParseResultType::ShortCircuitAll) + return InternalParseResult::ok(ParseState(result.value(), remainingTokens)); + } else { + auto valueRef = static_cast(m_ref.get()); + ++remainingTokens; + if (!remainingTokens) + return InternalParseResult::runtimeError("Expected argument following " + token.token); + auto const &argToken = *remainingTokens; + if (argToken.type != TokenType::Argument) + return InternalParseResult::runtimeError("Expected argument following " + token.token); + auto result = valueRef->setValue(argToken.token); + if (!result) return InternalParseResult(result); + if (result.value() == ParseResultType::ShortCircuitAll) + return InternalParseResult::ok(ParseState(result.value(), remainingTokens)); } + return InternalParseResult::ok(ParseState(ParseResultType::Matched, ++remainingTokens)); + } + } + return InternalParseResult::ok(ParseState(ParseResultType::NoMatch, remainingTokens)); + } - auto getHelpColumns() const -> std::vector { - std::ostringstream oss; - bool first = true; - for( auto const &opt : m_optNames ) { - if (first) - first = false; - else - oss << ", "; - oss << opt; - } - if( !m_hint.empty() ) - oss << " <" << m_hint << ">"; - return { { oss.str(), m_description } }; - } - - auto isMatch( std::string const &optToken ) const -> bool { - auto normalisedToken = normaliseOpt( optToken ); - for( auto const &name : m_optNames ) { - if( normaliseOpt( name ) == normalisedToken ) - return true; - } - return false; - } - - using ParserBase::parse; - - auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override { - auto validationResult = validate(); - if( !validationResult ) - return InternalParseResult( validationResult ); - - auto remainingTokens = tokens; - if( remainingTokens && remainingTokens->type == TokenType::Option ) { - auto const &token = *remainingTokens; - if( isMatch(token.token ) ) { - if( m_ref->isFlag() ) { - auto flagRef = static_cast( m_ref.get() ); - auto result = flagRef->setFlag( true ); - if( !result ) - return InternalParseResult( result ); - if( result.value() == ParseResultType::ShortCircuitAll ) - return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) ); - } else { - auto valueRef = static_cast( m_ref.get() ); - ++remainingTokens; - if( !remainingTokens ) - return InternalParseResult::runtimeError( "Expected argument following " + token.token ); - auto const &argToken = *remainingTokens; - if( argToken.type != TokenType::Argument ) - return InternalParseResult::runtimeError( "Expected argument following " + token.token ); - auto result = valueRef->setValue( argToken.token ); - if( !result ) - return InternalParseResult( result ); - if( result.value() == ParseResultType::ShortCircuitAll ) - return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) ); - } - return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) ); - } - } - return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) ); - } - - auto validate() const -> Result override { - if( m_optNames.empty() ) - return Result::logicError( "No options supplied to Opt" ); - for( auto const &name : m_optNames ) { - if( name.empty() ) - return Result::logicError( "Option name cannot be empty" ); + auto validate() const -> Result override { + if (m_optNames.empty()) return Result::logicError("No options supplied to Opt"); + for (auto const &name : m_optNames) { + if (name.empty()) return Result::logicError("Option name cannot be empty"); #ifdef CLARA_PLATFORM_WINDOWS - if( name[0] != '-' && name[0] != '/' ) - return Result::logicError( "Option name must begin with '-' or '/'" ); + if (name[0] != '-' && name[0] != '/') + return Result::logicError("Option name must begin with '-' or '/'"); #else - if( name[0] != '-' ) - return Result::logicError( "Option name must begin with '-'" ); + if (name[0] != '-') return Result::logicError("Option name must begin with '-'"); #endif - } - return ParserRefImpl::validate(); - } - }; - - struct Help : Opt { - Help( bool &showHelpFlag ) - : Opt([&]( bool flag ) { - showHelpFlag = flag; - return ParserResult::ok( ParseResultType::ShortCircuitAll ); - }) - { - static_cast( *this ) - ("display usage information") - ["-?"]["-h"]["--help"] - .optional(); - } - }; - - - struct Parser : ParserBase { - - mutable ExeName m_exeName; - std::vector m_options; - std::vector m_args; - - auto operator|=( ExeName const &exeName ) -> Parser & { - m_exeName = exeName; - return *this; - } - - auto operator|=( Arg const &arg ) -> Parser & { - m_args.push_back(arg); - return *this; - } - - auto operator|=( Opt const &opt ) -> Parser & { - m_options.push_back(opt); - return *this; - } - - auto operator|=( Parser const &other ) -> Parser & { - m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end()); - m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end()); - return *this; - } - - template - auto operator|( T const &other ) const -> Parser { - return Parser( *this ) |= other; - } - - // Forward deprecated interface with '+' instead of '|' - template - auto operator+=( T const &other ) -> Parser & { return operator|=( other ); } - template - auto operator+( T const &other ) const -> Parser { return operator|( other ); } - - auto getHelpColumns() const -> std::vector { - std::vector cols; - for (auto const &o : m_options) { - auto childCols = o.getHelpColumns(); - cols.insert( cols.end(), childCols.begin(), childCols.end() ); - } - return cols; - } - - void writeToStream( std::ostream &os ) const { - if (!m_exeName.name().empty()) { - os << "usage:\n" << " " << m_exeName.name() << " "; - bool required = true, first = true; - for( auto const &arg : m_args ) { - if (first) - first = false; - else - os << " "; - if( arg.isOptional() && required ) { - os << "["; - required = false; - } - os << "<" << arg.hint() << ">"; - if( arg.cardinality() == 0 ) - os << " ... "; - } - if( !required ) - os << "]"; - if( !m_options.empty() ) - os << " options"; - os << "\n\nwhere options are:" << std::endl; - } - - auto rows = getHelpColumns(); - size_t consoleWidth = CLARA_CONFIG_CONSOLE_WIDTH; - size_t optWidth = 0; - for( auto const &cols : rows ) - optWidth = (std::max)(optWidth, cols.left.size() + 2); - - optWidth = (std::min)(optWidth, consoleWidth/2); - - for( auto const &cols : rows ) { - auto row = - TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) + - TextFlow::Spacer(4) + - TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth ); - os << row << std::endl; - } - } - - friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& { - parser.writeToStream( os ); - return os; - } - - auto validate() const -> Result override { - for( auto const &opt : m_options ) { - auto result = opt.validate(); - if( !result ) - return result; - } - for( auto const &arg : m_args ) { - auto result = arg.validate(); - if( !result ) - return result; - } - return Result::ok(); - } - - using ParserBase::parse; - - auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override { - - struct ParserInfo { - ParserBase const* parser = nullptr; - size_t count = 0; - }; - const size_t totalParsers = m_options.size() + m_args.size(); - assert( totalParsers < 512 ); - // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do - ParserInfo parseInfos[512]; - - { - size_t i = 0; - for (auto const &opt : m_options) parseInfos[i++].parser = &opt; - for (auto const &arg : m_args) parseInfos[i++].parser = &arg; - } - - m_exeName.set( exeName ); - - auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) ); - while( result.value().remainingTokens() ) { - bool tokenParsed = false; - - for( size_t i = 0; i < totalParsers; ++i ) { - auto& parseInfo = parseInfos[i]; - if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) { - result = parseInfo.parser->parse(exeName, result.value().remainingTokens()); - if (!result) - return result; - if (result.value().type() != ParseResultType::NoMatch) { - tokenParsed = true; - ++parseInfo.count; - break; - } - } - } - - if( result.value().type() == ParseResultType::ShortCircuitAll ) - return result; - if( !tokenParsed ) - return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token ); - } - // !TBD Check missing required options - return result; - } - }; - - template - template - auto ComposableParserImpl::operator|( T const &other ) const -> Parser { - return Parser() | static_cast( *this ) | other; } -} // namespace detail + return ParserRefImpl::validate(); + } +}; +struct Help : Opt { + Help(bool &showHelpFlag) + : Opt([&](bool flag) { + showHelpFlag = flag; + return ParserResult::ok(ParseResultType::ShortCircuitAll); + }) { + static_cast (*this)("display usage information")["-?"]["-h"]["--help"].optional(); + } +}; + +struct Parser : ParserBase { + mutable ExeName m_exeName; + std::vector m_options; + std::vector m_args; + + auto operator|=(ExeName const &exeName) -> Parser & { + m_exeName = exeName; + return *this; + } + + auto operator|=(Arg const &arg) -> Parser & { + m_args.push_back(arg); + return *this; + } + + auto operator|=(Opt const &opt) -> Parser & { + m_options.push_back(opt); + return *this; + } + + auto operator|=(Parser const &other) -> Parser & { + m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end()); + m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end()); + return *this; + } + + template + auto operator|(T const &other) const -> Parser { + return Parser(*this) |= other; + } + + // Forward deprecated interface with '+' instead of '|' + template + auto operator+=(T const &other) -> Parser & { + return operator|=(other); + } + template + auto operator+(T const &other) const -> Parser { + return operator|(other); + } + + auto getHelpColumns() const -> std::vector { + std::vector cols; + for (auto const &o : m_options) { + auto childCols = o.getHelpColumns(); + cols.insert(cols.end(), childCols.begin(), childCols.end()); + } + return cols; + } + + void writeToStream(std::ostream &os) const { + if (!m_exeName.name().empty()) { + os << "usage:\n" + << " " << m_exeName.name() << " "; + bool required = true, first = true; + for (auto const &arg : m_args) { + if (first) + first = false; + else + os << " "; + if (arg.isOptional() && required) { + os << "["; + required = false; + } + os << "<" << arg.hint() << ">"; + if (arg.cardinality() == 0) os << " ... "; + } + if (!required) os << "]"; + if (!m_options.empty()) os << " options"; + os << "\n\nwhere options are:" << std::endl; + } + + auto rows = getHelpColumns(); + size_t consoleWidth = CLARA_CONFIG_CONSOLE_WIDTH; + size_t optWidth = 0; + for (auto const &cols : rows) optWidth = (std::max)(optWidth, cols.left.size() + 2); + + optWidth = (std::min)(optWidth, consoleWidth / 2); + + for (auto const &cols : rows) { + auto row = TextFlow::Column(cols.left).width(optWidth).indent(2) + TextFlow::Spacer(4) + + TextFlow::Column(cols.right).width(consoleWidth - 7 - optWidth); + os << row << std::endl; + } + } + + friend auto operator<<(std::ostream &os, Parser const &parser) -> std::ostream & { + parser.writeToStream(os); + return os; + } + + auto validate() const -> Result override { + for (auto const &opt : m_options) { + auto result = opt.validate(); + if (!result) return result; + } + for (auto const &arg : m_args) { + auto result = arg.validate(); + if (!result) return result; + } + return Result::ok(); + } + + using ParserBase::parse; + + auto parse(std::string const &exeName, TokenStream const &tokens) const + -> InternalParseResult override { + struct ParserInfo { + ParserBase const *parser = nullptr; + size_t count = 0; + }; + const size_t totalParsers = m_options.size() + m_args.size(); + assert(totalParsers < 512); + // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do + ParserInfo parseInfos[512]; + + { + size_t i = 0; + for (auto const &opt : m_options) parseInfos[i++].parser = &opt; + for (auto const &arg : m_args) parseInfos[i++].parser = &arg; + } + + m_exeName.set(exeName); + + auto result = InternalParseResult::ok(ParseState(ParseResultType::NoMatch, tokens)); + while (result.value().remainingTokens()) { + bool tokenParsed = false; + + for (size_t i = 0; i < totalParsers; ++i) { + auto &parseInfo = parseInfos[i]; + if (parseInfo.parser->cardinality() == 0 || + parseInfo.count < parseInfo.parser->cardinality()) { + result = parseInfo.parser->parse(exeName, result.value().remainingTokens()); + if (!result) return result; + if (result.value().type() != ParseResultType::NoMatch) { + tokenParsed = true; + ++parseInfo.count; + break; + } + } + } + + if (result.value().type() == ParseResultType::ShortCircuitAll) return result; + if (!tokenParsed) + return InternalParseResult::runtimeError("Unrecognised token: " + + result.value().remainingTokens()->token); + } + // !TBD Check missing required options + return result; + } +}; + +template +template +auto ComposableParserImpl::operator|(T const &other) const -> Parser { + return Parser() | static_cast(*this) | other; +} +} // namespace detail // A Combined parser using detail::Parser; @@ -1258,7 +1176,6 @@ using detail::ParseResultType; // Result type for parser operation using detail::ParserResult; +} // namespace clara -} // namespace clara - -#endif // CLARA_HPP_INCLUDED +#endif // CLARA_HPP_INCLUDED diff --git a/include/util/command.hpp b/include/util/command.hpp index 5f398e19..c9f238c1 100644 --- a/include/util/command.hpp +++ b/include/util/command.hpp @@ -20,13 +20,13 @@ extern std::list reap; namespace waybar::util::command { struct res { - int exit_code; + int exit_code; std::string out; }; inline std::string read(FILE* fp) { std::array buffer = {0}; - std::string output; + std::string output; while (feof(fp) == 0) { if (fgets(buffer.data(), 128, fp) != nullptr) { output += buffer.data(); @@ -68,7 +68,7 @@ inline int close(FILE* fp, pid_t pid) { inline FILE* open(const std::string& cmd, int& pid) { if (cmd == "") return nullptr; int fd[2]; - if (pipe(fd) != 0){ + if (pipe(fd) != 0) { spdlog::error("Unable to pipe fd"); return nullptr; } @@ -112,7 +112,7 @@ inline FILE* open(const std::string& cmd, int& pid) { } inline struct res exec(const std::string& cmd) { - int pid; + int pid; auto fp = command::open(cmd, pid); if (!fp) return {-1, ""}; auto output = command::read(fp); @@ -121,7 +121,7 @@ inline struct res exec(const std::string& cmd) { } inline struct res execNoRead(const std::string& cmd) { - int pid; + int pid; auto fp = command::open(cmd, pid); if (!fp) return {-1, ""}; auto stat = command::close(fp, pid); diff --git a/include/util/format.hpp b/include/util/format.hpp index 48f0f516..e9904210 100644 --- a/include/util/format.hpp +++ b/include/util/format.hpp @@ -4,96 +4,94 @@ #include class pow_format { - public: - pow_format(long long val, std::string&& unit, bool binary = false): - val_(val), unit_(unit), binary_(binary) { }; + public: + pow_format(long long val, std::string&& unit, bool binary = false) + : val_(val), unit_(unit), binary_(binary){}; - long long val_; - std::string unit_; - bool binary_; + long long val_; + std::string unit_; + bool binary_; }; - namespace fmt { - template <> - struct formatter { - char spec = 0; - int width = 0; +template <> +struct formatter { + char spec = 0; + int width = 0; - template - constexpr auto parse(ParseContext& ctx) -> decltype (ctx.begin()) { - auto it = ctx.begin(), end = ctx.end(); - if (it != end && *it == ':') ++it; - if (it && (*it == '>' || *it == '<' || *it == '=')) { - spec = *it; - ++it; - } - if (it == end || *it == '}') return it; - if ('0' <= *it && *it <= '9') { - // We ignore it for now, but keep it for compatibility with - // existing configs where the format for pow_format'ed numbers was - // 'string' and specifications such as {:>9} were valid. - // The rationale for ignoring it is that the only reason to specify - // an alignment and a with is to get a fixed width bar, and ">" is - // sufficient in this implementation. + template + constexpr auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + auto it = ctx.begin(), end = ctx.end(); + if (it != end && *it == ':') ++it; + if (it && (*it == '>' || *it == '<' || *it == '=')) { + spec = *it; + ++it; + } + if (it == end || *it == '}') return it; + if ('0' <= *it && *it <= '9') { + // We ignore it for now, but keep it for compatibility with + // existing configs where the format for pow_format'ed numbers was + // 'string' and specifications such as {:>9} were valid. + // The rationale for ignoring it is that the only reason to specify + // an alignment and a with is to get a fixed width bar, and ">" is + // sufficient in this implementation. #if FMT_VERSION < 80000 - width = parse_nonnegative_int(it, end, ctx); + width = parse_nonnegative_int(it, end, ctx); #else - width = detail::parse_nonnegative_int(it, end, -1); + width = detail::parse_nonnegative_int(it, end, -1); #endif - } - return it; - } + } + return it; + } - template - auto format(const pow_format& s, FormatContext &ctx) -> decltype (ctx.out()) { - const char* units[] = { "", "k", "M", "G", "T", "P", nullptr}; + template + auto format(const pow_format& s, FormatContext& ctx) -> decltype(ctx.out()) { + const char* units[] = {"", "k", "M", "G", "T", "P", nullptr}; - auto base = s.binary_ ? 1024ull : 1000ll; - auto fraction = (double) s.val_; + auto base = s.binary_ ? 1024ull : 1000ll; + auto fraction = (double)s.val_; - int pow; - for (pow = 0; units[pow+1] != nullptr && fraction / base >= 1; ++pow) { - fraction /= base; - } + int pow; + for (pow = 0; units[pow + 1] != nullptr && fraction / base >= 1; ++pow) { + fraction /= base; + } - auto max_width = 4 // coeff in {:.3g} format - + 1 // prefix from units array - + s.binary_ // for the 'i' in GiB. - + s.unit_.length(); + auto max_width = 4 // coeff in {:.3g} format + + 1 // prefix from units array + + s.binary_ // for the 'i' in GiB. + + s.unit_.length(); - const char * format; - std::string string; - switch (spec) { - case '>': - return format_to(ctx.out(), "{:>{}}", fmt::format("{}", s), max_width); - case '<': - return format_to(ctx.out(), "{:<{}}", fmt::format("{}", s), max_width); - case '=': - format = "{coefficient:<4.3g}{padding}{prefix}{unit}"; - break; - case 0: - default: - format = "{coefficient:.3g}{prefix}{unit}"; - break; - } - return format_to(ctx.out(), format - , fmt::arg("coefficient", fraction) - , fmt::arg("prefix", std::string() + units[pow] + ((s.binary_ && pow) ? "i" : "")) - , fmt::arg("unit", s.unit_) - , fmt::arg("padding", pow ? "" : s.binary_ ? " " : " ") - ); - } - }; - - - // Glib ustirng support - template <> - struct formatter : formatter { - template - auto format(const Glib::ustring& value, FormatContext& ctx) { - return formatter::format(value, ctx); - } - }; -} + const char* format; + std::string string; + switch (spec) { + case '>': + return format_to(ctx.out(), "{:>{}}", fmt::format("{}", s), max_width); + case '<': + return format_to(ctx.out(), "{:<{}}", fmt::format("{}", s), max_width); + case '=': + format = "{coefficient:<4.3g}{padding}{prefix}{unit}"; + break; + case 0: + default: + format = "{coefficient:.3g}{prefix}{unit}"; + break; + } + return format_to( + ctx.out(), format, fmt::arg("coefficient", fraction), + fmt::arg("prefix", std::string() + units[pow] + ((s.binary_ && pow) ? "i" : "")), + fmt::arg("unit", s.unit_), + fmt::arg("padding", pow ? "" + : s.binary_ ? " " + : " ")); + } +}; +// Glib ustirng support +template <> +struct formatter : formatter { + template + auto format(const Glib::ustring& value, FormatContext& ctx) { + return formatter::format(value, ctx); + } +}; +} // namespace fmt diff --git a/include/util/json.hpp b/include/util/json.hpp index 581ad9b4..cc514e13 100644 --- a/include/util/json.hpp +++ b/include/util/json.hpp @@ -13,7 +13,7 @@ struct JsonParser { return root; } std::unique_ptr const reader(builder_.newCharReader()); - std::string err; + std::string err; bool res = reader->parse(data.c_str(), data.c_str() + data.size(), &root, &err); if (!res) throw std::runtime_error(err); return root; diff --git a/include/util/rfkill.hpp b/include/util/rfkill.hpp index 5d519cae..f620db53 100644 --- a/include/util/rfkill.hpp +++ b/include/util/rfkill.hpp @@ -17,8 +17,8 @@ class Rfkill : public sigc::trackable { private: enum rfkill_type rfkill_type_; - bool state_ = false; - int fd_ = -1; + bool state_ = false; + int fd_ = -1; bool on_event(Glib::IOCondition cond); }; diff --git a/include/util/sleeper_thread.hpp b/include/util/sleeper_thread.hpp index d1c6ba0d..e12287a0 100644 --- a/include/util/sleeper_thread.hpp +++ b/include/util/sleeper_thread.hpp @@ -17,7 +17,8 @@ namespace waybar::util { */ class CancellationGuard { int oldstate; -public: + + public: CancellationGuard() { pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate); } ~CancellationGuard() { pthread_setcancelstate(oldstate, &oldstate); } }; @@ -47,7 +48,7 @@ class SleeperThread { bool isRunning() const { return do_run_; } auto sleep_for(std::chrono::system_clock::duration dur) { - std::unique_lock lk(mutex_); + std::unique_lock lk(mutex_); CancellationGuard cancel_lock; return condvar_.wait_for(lk, dur, [this] { return signal_ || !do_run_; }); } @@ -55,7 +56,7 @@ class SleeperThread { auto sleep_until( std::chrono::time_point time_point) { - std::unique_lock lk(mutex_); + std::unique_lock lk(mutex_); CancellationGuard cancel_lock; return condvar_.wait_until(lk, time_point, [this] { return signal_ || !do_run_; }); } @@ -90,11 +91,11 @@ class SleeperThread { } private: - std::thread thread_; + std::thread thread_; std::condition_variable condvar_; - std::mutex mutex_; - bool do_run_ = true; - bool signal_ = false; + std::mutex mutex_; + bool do_run_ = true; + bool signal_ = false; }; } // namespace waybar::util diff --git a/include/util/waybar_time.hpp b/include/util/waybar_time.hpp index c74e58c3..b9f9ea98 100644 --- a/include/util/waybar_time.hpp +++ b/include/util/waybar_time.hpp @@ -6,7 +6,7 @@ namespace waybar { struct waybar_time { - std::locale locale; + std::locale locale; date::zoned_seconds ztime; }; diff --git a/src/ALabel.cpp b/src/ALabel.cpp index b9b3d1d2..4d8b2218 100644 --- a/src/ALabel.cpp +++ b/src/ALabel.cpp @@ -1,5 +1,7 @@ #include "ALabel.hpp" + #include + #include namespace waybar { @@ -46,15 +48,10 @@ ALabel::ALabel(const Json::Value& config, const std::string& name, const std::st } else { label_.set_xalign(align); } - } - - } -auto ALabel::update() -> void { - AModule::update(); -} +auto ALabel::update() -> void { AModule::update(); } std::string ALabel::getIcon(uint16_t percentage, const std::string& alt, uint16_t max) { auto format_icons = config_["format-icons"]; @@ -78,7 +75,8 @@ std::string ALabel::getIcon(uint16_t percentage, const std::string& alt, uint16_ return ""; } -std::string ALabel::getIcon(uint16_t percentage, const std::vector& alts, uint16_t max) { +std::string ALabel::getIcon(uint16_t percentage, const std::vector& alts, + uint16_t max) { auto format_icons = config_["format-icons"]; if (format_icons.isObject()) { std::string _alt = "default"; diff --git a/src/AModule.cpp b/src/AModule.cpp index e65067e0..b19594a1 100644 --- a/src/AModule.cpp +++ b/src/AModule.cpp @@ -1,24 +1,28 @@ #include "AModule.hpp" + #include + #include namespace waybar { AModule::AModule(const Json::Value& config, const std::string& name, const std::string& id, bool enable_click, bool enable_scroll) - : name_(std::move(name)), config_(std::move(config)) - , distance_scrolled_y_(0.0) - , distance_scrolled_x_(0.0) { + : name_(std::move(name)), + config_(std::move(config)), + distance_scrolled_y_(0.0), + distance_scrolled_x_(0.0) { // configure events' user commands if (enable_click) { event_box_.add_events(Gdk::BUTTON_PRESS_MASK); event_box_.signal_button_press_event().connect(sigc::mem_fun(*this, &AModule::handleToggle)); } else { std::map, std::string>::const_iterator it{eventMap_.cbegin()}; - while(it != eventMap_.cend()) { + while (it != eventMap_.cend()) { if (config_[it->second].isString()) { 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; } ++it; @@ -27,7 +31,7 @@ AModule::AModule(const Json::Value& config, const std::string& name, const std:: if (config_["on-scroll-up"].isString() || config_["on-scroll-down"].isString() || enable_scroll) { event_box_.add_events(Gdk::SCROLL_MASK | Gdk::SMOOTH_SCROLL_MASK); event_box_.signal_scroll_event().connect(sigc::mem_fun(*this, &AModule::handleScroll)); - } + } } AModule::~AModule() { @@ -46,12 +50,15 @@ auto AModule::update() -> void { } bool AModule::handleToggle(GdkEventButton* const& e) { - const std::map, std::string>::const_iterator& rec{eventMap_.find(std::pair(e->button, e->type))}; - std::string format{ (rec != eventMap_.cend()) ? rec->second : std::string{""}}; + const std::map, std::string>::const_iterator& rec{ + eventMap_.find(std::pair(e->button, e->type))}; + std::string format{(rec != eventMap_.cend()) ? rec->second : std::string{""}}; if (!format.empty()) { - if (config_[format].isString()) format = config_[format].asString(); - else format.clear(); + if (config_[format].isString()) + format = config_[format].asString(); + else + format.clear(); } if (!format.empty()) { @@ -62,11 +69,15 @@ bool AModule::handleToggle(GdkEventButton* const& e) { } AModule::SCROLL_DIR AModule::getScrollDir(GdkEventScroll* e) { - switch (e -> direction) { - case GDK_SCROLL_UP: return SCROLL_DIR::UP; - case GDK_SCROLL_DOWN: return SCROLL_DIR::DOWN; - case GDK_SCROLL_LEFT: return SCROLL_DIR::LEFT; - case GDK_SCROLL_RIGHT: return SCROLL_DIR::RIGHT; + switch (e->direction) { + case GDK_SCROLL_UP: + return SCROLL_DIR::UP; + case GDK_SCROLL_DOWN: + return SCROLL_DIR::DOWN; + case GDK_SCROLL_LEFT: + return SCROLL_DIR::LEFT; + case GDK_SCROLL_RIGHT: + return SCROLL_DIR::RIGHT; case GDK_SCROLL_SMOOTH: { SCROLL_DIR dir{SCROLL_DIR::NONE}; @@ -104,7 +115,8 @@ AModule::SCROLL_DIR AModule::getScrollDir(GdkEventScroll* e) { return dir; } // Silence -Wreturn-type: - default: return SCROLL_DIR::NONE; + default: + return SCROLL_DIR::NONE; } } diff --git a/src/bar.cpp b/src/bar.cpp index d4319ff0..be10eed8 100644 --- a/src/bar.cpp +++ b/src/bar.cpp @@ -170,10 +170,8 @@ struct GLSSurfaceImpl : public BarSurface, public sigc::trackable { vertical_ = true; unanchored = GTK_LAYER_SHELL_EDGE_LEFT; } - for (auto edge : {GTK_LAYER_SHELL_EDGE_LEFT, - GTK_LAYER_SHELL_EDGE_RIGHT, - GTK_LAYER_SHELL_EDGE_TOP, - GTK_LAYER_SHELL_EDGE_BOTTOM}) { + for (auto edge : {GTK_LAYER_SHELL_EDGE_LEFT, GTK_LAYER_SHELL_EDGE_RIGHT, + GTK_LAYER_SHELL_EDGE_TOP, GTK_LAYER_SHELL_EDGE_BOTTOM}) { gtk_layer_set_anchor(window_.gobj(), edge, unanchored != edge); } } @@ -186,11 +184,11 @@ struct GLSSurfaceImpl : public BarSurface, public sigc::trackable { private: Gtk::Window& window_; - std::string output_name_; - uint32_t width_; - uint32_t height_; - bool passthrough_ = false; - bool vertical_ = false; + std::string output_name_; + uint32_t width_; + uint32_t height_; + bool passthrough_ = false; + bool vertical_ = false; void onMap(GdkEventAny* ev) { setPassThrough(passthrough_); } @@ -276,8 +274,8 @@ struct RawSurfaceImpl : public BarSurface, public sigc::trackable { margins_ = margins; // updating already mapped window if (layer_surface_) { - zwlr_layer_surface_v1_set_margin( - layer_surface_.get(), margins_.top, margins_.right, margins_.bottom, margins_.left); + zwlr_layer_surface_v1_set_margin(layer_surface_.get(), margins_.top, margins_.right, + margins_.bottom, margins_.left); } } @@ -335,21 +333,21 @@ struct RawSurfaceImpl : public BarSurface, public sigc::trackable { using layer_surface_ptr = std::unique_ptr>; - Gtk::Window& window_; - std::string output_name_; - uint32_t configured_width_ = 0; - uint32_t configured_height_ = 0; - uint32_t width_ = 0; - uint32_t height_ = 0; - uint8_t anchor_ = HORIZONTAL_ANCHOR | ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP; - bool exclusive_zone_ = true; - bool passthrough_ = false; + Gtk::Window& window_; + std::string output_name_; + uint32_t configured_width_ = 0; + uint32_t configured_height_ = 0; + uint32_t width_ = 0; + uint32_t height_ = 0; + uint8_t anchor_ = HORIZONTAL_ANCHOR | ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP; + bool exclusive_zone_ = true; + bool passthrough_ = false; struct bar_margins margins_; zwlr_layer_shell_v1_layer layer_ = ZWLR_LAYER_SHELL_V1_LAYER_BOTTOM; - struct wl_output* output_ = nullptr; // owned by GTK - struct wl_surface* surface_ = nullptr; // owned by GTK - layer_surface_ptr layer_surface_; + struct wl_output* output_ = nullptr; // owned by GTK + struct wl_surface* surface_ = nullptr; // owned by GTK + layer_surface_ptr layer_surface_; void onRealize() { auto gdk_window = window_.get_window()->gobj(); @@ -365,14 +363,14 @@ struct RawSurfaceImpl : public BarSurface, public sigc::trackable { auto gdk_window = window_.get_window()->gobj(); surface_ = gdk_wayland_window_get_wl_surface(gdk_window); - layer_surface_.reset(zwlr_layer_shell_v1_get_layer_surface( - client->layer_shell, surface_, output_, layer_, "waybar")); + layer_surface_.reset(zwlr_layer_shell_v1_get_layer_surface(client->layer_shell, surface_, + output_, layer_, "waybar")); 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_anchor(layer_surface_.get(), anchor_); - zwlr_layer_surface_v1_set_margin( - layer_surface_.get(), margins_.top, margins_.right, margins_.bottom, margins_.left); + zwlr_layer_surface_v1_set_margin(layer_surface_.get(), margins_.top, margins_.right, + margins_.bottom, margins_.left); setSurfaceSize(width_, height_); 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_.resize(o->width_, o->height_); o->setExclusiveZone(o->exclusive_zone_); - spdlog::info(BAR_SIZE_MSG, - o->width_ == 1 ? "auto" : std::to_string(o->width_), - o->height_ == 1 ? "auto" : std::to_string(o->height_), - o->output_name_); + spdlog::info(BAR_SIZE_MSG, o->width_ == 1 ? "auto" : std::to_string(o->width_), + o->height_ == 1 ? "auto" : std::to_string(o->height_), o->output_name_); o->commit(); } zwlr_layer_surface_v1_ack_configure(surface, serial); @@ -520,7 +516,7 @@ waybar::Bar::Bar(struct waybar_output* w_output, const Json::Value& w_config) config["margin-left"].isInt() ? config["margin-left"].asInt() : 0, }; } else if (config["margin"].isString()) { - std::istringstream iss(config["margin"].asString()); + std::istringstream iss(config["margin"].asString()); std::vector margins{std::istream_iterator(iss), {}}; try { if (margins.size() == 1) { @@ -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]; if (module_list.isArray()) { for (const auto& name : module_list) { diff --git a/src/client.cpp b/src/client.cpp index 8adbeac1..be2ec917 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -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) { // Nothing here } @@ -52,8 +52,8 @@ void waybar::Client::handleOutput(struct waybar_output &output) { } struct waybar::waybar_output &waybar::Client::getOutput(void *addr) { - auto it = std::find_if( - outputs_.begin(), outputs_.end(), [&addr](const auto &output) { return &output == addr; }); + auto it = std::find_if(outputs_.begin(), outputs_.end(), + [&addr](const auto &output) { return &output == addr; }); if (it == outputs_.end()) { 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) { auto client = waybar::Client::inst(); try { @@ -108,7 +108,7 @@ void waybar::Client::handleOutputDescription(void *data, struct zxdg_output_v1 * const char *description) { auto client = waybar::Client::inst(); try { - auto & output = client->getOutput(data); + auto &output = client->getOutput(data); const char *open_paren = strrchr(description, '('); // 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"); } // there's always only one screen - style_context_->add_provider_for_screen( - Gdk::Screen::get_default(), css_provider_, GTK_STYLE_PROVIDER_PRIORITY_USER); + style_context_->add_provider_for_screen(Gdk::Screen::get_default(), css_provider_, + GTK_STYLE_PROVIDER_PRIORITY_USER); } void waybar::Client::bindInterfaces() { @@ -195,12 +195,12 @@ void waybar::Client::bindInterfaces() { } int waybar::Client::main(int argc, char *argv[]) { - bool show_help = false; - bool show_version = false; + bool show_help = false; + bool show_version = false; std::string config_opt; std::string style_opt; std::string log_level; - auto cli = clara::detail::Help(show_help) | + auto cli = clara::detail::Help(show_help) | clara::detail::Opt(show_version)["-v"]["--version"]("Show version") | clara::detail::Opt(config_opt, "config")["-c"]["--config"]("Config path") | clara::detail::Opt(style_opt, "style")["-s"]["--style"]("Style path") | @@ -224,8 +224,8 @@ int waybar::Client::main(int argc, char *argv[]) { if (!log_level.empty()) { spdlog::set_level(spdlog::level::from_str(log_level)); } - gtk_app = Gtk::Application::create( - argc, argv, "fr.arouillard.waybar", Gio::APPLICATION_HANDLES_COMMAND_LINE); + gtk_app = Gtk::Application::create(argc, argv, "fr.arouillard.waybar", + Gio::APPLICATION_HANDLES_COMMAND_LINE); gdk_display = Gdk::Display::get_default(); if (!gdk_display) { throw std::runtime_error("Can't find display"); @@ -244,6 +244,4 @@ int waybar::Client::main(int argc, char *argv[]) { return 0; } -void waybar::Client::reset() { - gtk_app->quit(); -} +void waybar::Client::reset() { gtk_app->quit(); } diff --git a/src/config.cpp b/src/config.cpp index 63149cbd..5894cb6b 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -13,12 +13,8 @@ namespace waybar { const std::vector Config::CONFIG_DIRS = { - "$XDG_CONFIG_HOME/waybar/", - "$HOME/.config/waybar/", - "$HOME/waybar/", - "/etc/xdg/waybar/", - SYSCONFDIR "/xdg/waybar/", - "./resources/", + "$XDG_CONFIG_HOME/waybar/", "$HOME/.config/waybar/", "$HOME/waybar/", + "/etc/xdg/waybar/", SYSCONFDIR "/xdg/waybar/", "./resources/", }; std::optional tryExpandPath(const std::string &path) { @@ -55,9 +51,9 @@ void Config::setupConfig(Json::Value &dst, const std::string &config_file, int d if (!file.is_open()) { throw std::runtime_error("Can't open config file"); } - std::string str((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + std::string str((std::istreambuf_iterator(file)), std::istreambuf_iterator()); util::JsonParser parser; - Json::Value tmp_config = parser.parse(str); + Json::Value tmp_config = parser.parse(str); if (tmp_config.isArray()) { for (auto &config_part : tmp_config) { resolveConfigIncludes(config_part, depth); diff --git a/src/factory.cpp b/src/factory.cpp index ab0dc435..4aaa248e 100644 --- a/src/factory.cpp +++ b/src/factory.cpp @@ -28,7 +28,7 @@ waybar::AModule* waybar::Factory::makeModule(const std::string& name) const { return new waybar::modules::sway::Window(id, bar_, config_[name]); } if (ref == "sway/language") { - return new waybar::modules::sway::Language(id, config_[name]); + return new waybar::modules::sway::Language(id, config_[name]); } #endif #ifdef HAVE_WLR @@ -109,11 +109,11 @@ waybar::AModule* waybar::Factory::makeModule(const std::string& name) const { return new waybar::modules::Temperature(id, config_[name]); } #if defined(__linux__) -# ifdef WANT_RFKILL +#ifdef WANT_RFKILL if (ref == "bluetooth") { return new waybar::modules::Bluetooth(id, config_[name]); } -# endif +#endif #endif if (ref.compare(0, 7, "custom/") == 0 && ref.size() > 7) { return new waybar::modules::Custom(ref.substr(7), id, config_[name]); diff --git a/src/group.cpp b/src/group.cpp index 9d2188cc..83243654 100644 --- a/src/group.cpp +++ b/src/group.cpp @@ -1,14 +1,14 @@ #include "group.hpp" + #include + #include namespace waybar { Group::Group(const std::string& name, const Bar& bar, const Json::Value& config) : 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 { // noop diff --git a/src/main.cpp b/src/main.cpp index 13a25670..e06774b4 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,9 +1,11 @@ +#include +#include +#include + #include #include #include -#include -#include -#include + #include "client.hpp" std::mutex reap_mtx; @@ -38,8 +40,7 @@ void* signalThread(void* args) { } break; default: - spdlog::debug("Received signal with number {}, but not handling", - signum); + spdlog::debug("Received signal with number {}, but not handling", signum); break; } } @@ -79,9 +80,9 @@ int main(int argc, char* argv[]) { }); std::signal(SIGUSR2, [](int /*signal*/) { - spdlog::info("Reloading..."); - reload = true; - waybar::Client::inst()->reset(); + spdlog::info("Reloading..."); + reload = true; + waybar::Client::inst()->reset(); }); for (int sig = SIGRTMIN + 1; sig <= SIGRTMAX; ++sig) { diff --git a/src/modules/backlight.cpp b/src/modules/backlight.cpp index fcd668c5..a93934b4 100644 --- a/src/modules/backlight.cpp +++ b/src/modules/backlight.cpp @@ -93,8 +93,8 @@ waybar::modules::Backlight::Backlight(const std::string &id, const Json::Value & { std::unique_ptr udev_check{udev_new()}; check_nn(udev_check.get(), "Udev check new failed"); - enumerate_devices( - devices_.begin(), devices_.end(), std::back_inserter(devices_), udev_check.get()); + enumerate_devices(devices_.begin(), devices_.end(), std::back_inserter(devices_), + udev_check.get()); if (devices_.empty()) { 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 mon{ udev_monitor_new_from_netlink(udev.get(), "udev")}; check_nn(mon.get(), "udev monitor new failed"); - check_gte(udev_monitor_filter_add_match_subsystem_devtype(mon.get(), "backlight", nullptr), - 0, + check_gte(udev_monitor_filter_add_match_subsystem_devtype(mon.get(), "backlight", nullptr), 0, "udev failed to add monitor filter: "); 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]; while (udev_thread_.isRunning()) { - const int event_count = epoll_wait( - epoll_fd.get(), events, EPOLL_MAX_EVENTS, std::chrono::milliseconds{interval_}.count()); + const int event_count = epoll_wait(epoll_fd.get(), events, EPOLL_MAX_EVENTS, + std::chrono::milliseconds{interval_}.count()); if (!udev_thread_.isRunning()) { break; } @@ -173,9 +172,10 @@ auto waybar::modules::Backlight::update() -> void { return; } - const uint8_t percent = best->get_max() == 0 ? 100 : round(best->get_actual() * 100.0f / best->get_max()); - label_.set_markup(fmt::format( - format_, fmt::arg("percent", std::to_string(percent)), fmt::arg("icon", getIcon(percent)))); + const uint8_t percent = + best->get_max() == 0 ? 100 : round(best->get_actual() * 100.0f / best->get_max()); + label_.set_markup(fmt::format(format_, fmt::arg("percent", std::to_string(percent)), + fmt::arg("icon", getIcon(percent)))); getState(percent); } else { 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 *dev_list_entry; udev_list_entry_foreach(dev_list_entry, enum_devices) { - const char * path = udev_list_entry_get_name(dev_list_entry); + const char *path = udev_list_entry_get_name(dev_list_entry); std::unique_ptr dev{udev_device_new_from_syspath(udev, path)}; check_nn(dev.get(), "dev new failed"); upsert_device(first, last, inserter, dev.get()); diff --git a/src/modules/battery.cpp b/src/modules/battery.cpp index 59874f78..cb7237a3 100644 --- a/src/modules/battery.cpp +++ b/src/modules/battery.cpp @@ -52,7 +52,7 @@ void waybar::modules::Battery::worker() { }; thread_ = [this] { struct inotify_event event = {0}; - int nbytes = read(battery_watch_fd_, &event, sizeof(event)); + int nbytes = read(battery_watch_fd_, &event, sizeof(event)); if (nbytes != sizeof(event) || event.mask & IN_IGNORED) { thread_.stop(); return; @@ -61,7 +61,7 @@ void waybar::modules::Battery::worker() { }; thread_battery_update_ = [this] { struct inotify_event event = {0}; - int nbytes = read(global_watch_fd_, &event, sizeof(event)); + int nbytes = read(global_watch_fd_, &event, sizeof(event)); if (nbytes != sizeof(event) || event.mask & IN_IGNORED) { thread_.stop(); return; @@ -94,7 +94,7 @@ void waybar::modules::Battery::refreshBatteries() { std::string type; std::ifstream(node.path() / "type") >> type; - if (!type.compare("Battery")){ + if (!type.compare("Battery")) { check_map[node.path()] = true; auto search = batteries_.find(node.path()); if (search == batteries_.end()) { @@ -139,11 +139,16 @@ void waybar::modules::Battery::refreshBatteries() { // Unknown > Full > Not charging > Discharging > Charging static bool status_gt(const std::string& a, const std::string& b) { - if (a == b) return false; - else if (a == "Unknown") 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; + if (a == b) + return false; + else if (a == "Unknown") + 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; } @@ -151,19 +156,19 @@ const std::tuple waybar::modules::Battery::g std::lock_guard guard(battery_list_mutex_); try { - uint32_t total_power = 0; // μW - uint32_t total_energy = 0; // μWh - uint32_t total_energy_full = 0; - uint32_t total_energy_full_design = 0; - uint32_t total_capacity{0}; + uint32_t total_power = 0; // μW + uint32_t total_energy = 0; // μWh + uint32_t total_energy_full = 0; + uint32_t total_energy_full_design = 0; + uint32_t total_capacity{0}; std::string status = "Unknown"; for (auto const& item : batteries_) { auto bat = item.first; - uint32_t power_now; - uint32_t energy_full; - uint32_t energy_now; - uint32_t energy_full_design; - uint32_t capacity{0}; + uint32_t power_now; + uint32_t energy_full; + uint32_t energy_now; + uint32_t energy_full_design; + uint32_t capacity{0}; std::string _status; std::getline(std::ifstream(bat / "status"), _status); @@ -198,17 +203,17 @@ const std::tuple waybar::modules::Battery::g energy_now = ((uint64_t)charge_now * (uint64_t)voltage_now) / 1000000; energy_full = ((uint64_t)charge_full * (uint64_t)voltage_now) / 1000000; energy_full_design = ((uint64_t)charge_full_design * (uint64_t)voltage_now) / 1000000; - } // Gamepads such as PS Dualshock provide the only capacity - else if (fs::exists(bat / "energy_now") && fs::exists(bat / "energy_full")) { - std::ifstream(bat / "power_now") >> power_now; - std::ifstream(bat / "energy_now") >> energy_now; - std::ifstream(bat / "energy_full") >> energy_full; - std::ifstream(bat / "energy_full_design") >> energy_full_design; + } // Gamepads such as PS Dualshock provide the only capacity + else if (fs::exists(bat / "energy_now") && fs::exists(bat / "energy_full")) { + std::ifstream(bat / "power_now") >> power_now; + std::ifstream(bat / "energy_now") >> energy_now; + std::ifstream(bat / "energy_full") >> energy_full; + std::ifstream(bat / "energy_full_design") >> energy_full_design; } else { std::ifstream(bat / "capacity") >> capacity; - power_now = 0; - energy_now = 0; - energy_full = 0; + power_now = 0; + energy_now = 0; + energy_full = 0; energy_full_design = 0; } @@ -241,14 +246,14 @@ const std::tuple waybar::modules::Battery::g } } float capacity{0.0f}; - if(total_energy_full > 0.0f) { - capacity = ((float)total_energy * 100.0f / (float) total_energy_full); + if (total_energy_full > 0.0f) { + capacity = ((float)total_energy * 100.0f / (float)total_energy_full); } else { capacity = (float)total_capacity; } // Handle design-capacity 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 if (config_["full-at"].isUInt()) { @@ -295,7 +300,7 @@ const std::string waybar::modules::Battery::formatTimeRemaining(float hoursRemai hoursRemaining = std::fabs(hoursRemaining); uint16_t full_hours = static_cast(hoursRemaining); uint16_t minutes = static_cast(60 * (hoursRemaining - full_hours)); - auto format = std::string("{H} h {M} min"); + auto format = std::string("{H} h {M} min"); if (full_hours == 0 && minutes == 0) { // Migh as well not show "0h 0min" return ""; @@ -317,9 +322,8 @@ auto waybar::modules::Battery::update() -> void { } auto status_pretty = status; // Transform to lowercase and replace space with dash - std::transform(status.begin(), status.end(), status.begin(), [](char ch) { - return ch == ' ' ? '-' : std::tolower(ch); - }); + std::transform(status.begin(), status.end(), status.begin(), + [](char ch) { return ch == ' ' ? '-' : std::tolower(ch); }); auto format = format_; auto state = getState(capacity, true); auto time_remaining_formatted = formatTimeRemaining(time_remaining); @@ -341,8 +345,7 @@ auto waybar::modules::Battery::update() -> void { } else if (config_["tooltip-format"].isString()) { tooltip_format = config_["tooltip-format"].asString(); } - label_.set_tooltip_text(fmt::format(tooltip_format, - fmt::arg("timeTo", tooltip_text_default), + label_.set_tooltip_text(fmt::format(tooltip_format, fmt::arg("timeTo", tooltip_text_default), fmt::arg("capacity", capacity), fmt::arg("time", time_remaining_formatted))); } @@ -363,9 +366,7 @@ auto waybar::modules::Battery::update() -> void { } else { event_box_.show(); auto icons = std::vector{status + "-" + state, status, state}; - label_.set_markup(fmt::format(format, - fmt::arg("capacity", capacity), - fmt::arg("power", power), + label_.set_markup(fmt::format(format, fmt::arg("capacity", capacity), fmt::arg("power", power), fmt::arg("icon", getIcon(capacity, icons)), fmt::arg("time", time_remaining_formatted))); } diff --git a/src/modules/clock.cpp b/src/modules/clock.cpp index c80057c5..0aeb4d72 100644 --- a/src/modules/clock.cpp +++ b/src/modules/clock.cpp @@ -24,44 +24,38 @@ waybar::modules::Clock::Clock(const std::string& id, const Json::Value& config) : ALabel(config, "clock", id, "{:%H:%M}", 60, false, false, true), current_time_zone_idx_(0), is_calendar_in_tooltip_(false), - is_timezoned_list_in_tooltip_(false) -{ + is_timezoned_list_in_tooltip_(false) { 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()) { time_zones_.push_back(nullptr); continue; } - time_zones_.push_back( - date::locate_zone( - zone_name.asString() - ) - ); + time_zones_.push_back(date::locate_zone(zone_name.asString())); } } else if (config_["timezone"].isString() && !config_["timezone"].asString().empty()) { - time_zones_.push_back( - date::locate_zone( - config_["timezone"].asString() - ) - ); + time_zones_.push_back(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()) { time_zones_.push_back(nullptr); } 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()) { std::string trimmed_format = config_["tooltip-format"].asString(); - trimmed_format.erase(std::remove_if(trimmed_format.begin(), - trimmed_format.end(), - [](unsigned char x){return std::isspace(x);}), - trimmed_format.end()); + trimmed_format.erase(std::remove_if(trimmed_format.begin(), trimmed_format.end(), + [](unsigned char x) { return std::isspace(x); }), + trimmed_format.end()); if (trimmed_format.find("{" + kCalendarPlaceholder + "}") != std::string::npos) { 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() { - 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() { @@ -120,7 +115,9 @@ auto waybar::modules::Clock::update() -> void { timezoned_time_lines = timezones_text(&now); } 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); } } @@ -129,7 +126,7 @@ auto waybar::modules::Clock::update() -> void { ALabel::update(); } -bool waybar::modules::Clock::handleScroll(GdkEventScroll *e) { +bool waybar::modules::Clock::handleScroll(GdkEventScroll* e) { // defer to user commands if set if (config_["on-scroll-up"].isString() || config_["on-scroll-down"].isString()) { return AModule::handleScroll(e); @@ -148,7 +145,8 @@ bool waybar::modules::Clock::handleScroll(GdkEventScroll *e) { size_t new_idx = current_time_zone_idx_ + 1; current_time_zone_idx_ = new_idx == nr_zones ? 0 : new_idx; } 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(); @@ -163,10 +161,10 @@ auto waybar::modules::Clock::calendar_text(const waybar_time& wtime) -> std::str } const date::year_month ym(ymd.year(), ymd.month()); - const auto curr_day = ymd.day(); + const auto curr_day = ymd.day(); std::stringstream os; - const auto first_dow = first_day_of_week(); + const auto first_dow = first_day_of_week(); weekdays_header(first_dow, os); // First week prefixed with spaces if needed. @@ -209,7 +207,7 @@ auto waybar::modules::Clock::weekdays_header(const date::weekday& first_dow, std auto clen = ustring_clen(wd_ustring); auto wd_len = wd_ustring.length(); while (clen > 2) { - wd_ustring = wd_ustring.substr(0, wd_len-1); + wd_ustring = wd_ustring.substr(0, wd_len - 1); wd_len--; clen = ustring_clen(wd_ustring); } @@ -219,7 +217,8 @@ auto waybar::modules::Clock::weekdays_header(const date::weekday& first_dow, std 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) { return ""; } @@ -254,9 +253,9 @@ auto waybar::modules::Clock::first_day_of_week() -> date::weekday { newlocale(LC_ALL, locale_.name().c_str(), nullptr)}; if (posix_locale) { const int i = (std::intptr_t)nl_langinfo_l(_NL_TIME_WEEK_1STDAY, posix_locale.get()); - auto ymd = date::year(i / 10000) / (i / 100 % 100) / (i % 100); - auto wd = date::weekday(ymd); - uint8_t j = *nl_langinfo_l(_NL_TIME_FIRST_WEEKDAY, posix_locale.get()); + auto ymd = date::year(i / 10000) / (i / 100 % 100) / (i % 100); + auto wd = date::weekday(ymd); + uint8_t j = *nl_langinfo_l(_NL_TIME_FIRST_WEEKDAY, posix_locale.get()); return wd + date::days(j - 1); } #endif diff --git a/src/modules/cpu/bsd.cpp b/src/modules/cpu/bsd.cpp index a92252f1..748c3cd6 100644 --- a/src/modules/cpu/bsd.cpp +++ b/src/modules/cpu/bsd.cpp @@ -1,16 +1,17 @@ +#include +#include +#include +#include // sysconf + +#include // NAN +#include // malloc + #include "modules/cpu.hpp" -#include -#include -#include -#include // malloc -#include // sysconf -#include // NAN - #if defined(__NetBSD__) || defined(__OpenBSD__) -# include +#include #else -# include +#include #endif #if defined(__NetBSD__) @@ -32,26 +33,26 @@ std::vector> waybar::modules::Cpu::parseCpuinfo() { pcp_time_t *cp_time = static_cast(malloc(sz)), *pcp_time = cp_time; #if defined(__NetBSD__) int mib[] = { - CTL_KERN, - KERN_CP_TIME, + CTL_KERN, + 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"); } for (int state = 0; state < CPUSTATES; state++) { cp_time[state] = sum_cp_time[state]; } 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"); } #elif defined(__OpenBSD__) { int mib[] = { - CTL_KERN, - KERN_CPTIME, + CTL_KERN, + 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"); } } @@ -62,14 +63,14 @@ std::vector> waybar::modules::Cpu::parseCpuinfo() { sz /= ncpu + 1; { int mib[] = { - CTL_KERN, - KERN_CPTIME2, - 0, + CTL_KERN, + KERN_CPTIME2, + 0, }; for (int cpu = 0; cpu < ncpu; cpu++) { mib[2] = cpu; 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"); } } @@ -101,7 +102,8 @@ std::vector> waybar::modules::Cpu::parseCpuinfo() { std::vector waybar::modules::Cpu::parseCpuFrequencies() { static std::vector frequencies; 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); } return frequencies; diff --git a/src/modules/cpu/common.cpp b/src/modules/cpu/common.cpp index 903b3bdc..9fc58211 100644 --- a/src/modules/cpu/common.cpp +++ b/src/modules/cpu/common.cpp @@ -46,11 +46,11 @@ auto waybar::modules::Cpu::update() -> void { store.push_back(fmt::arg("min_frequency", min_frequency)); store.push_back(fmt::arg("avg_frequency", avg_frequency)); for (size_t i = 1; i < cpu_usage.size(); ++i) { - auto core_i = i - 1; - auto core_format = fmt::format("usage{}", core_i); - store.push_back(fmt::arg(core_format.c_str(), cpu_usage[i])); - auto icon_format = fmt::format("icon{}", core_i); - store.push_back(fmt::arg(icon_format.c_str(), getIcon(cpu_usage[i], icons))); + auto core_i = i - 1; + auto core_format = fmt::format("usage{}", core_i); + store.push_back(fmt::arg(core_format.c_str(), cpu_usage[i])); + auto icon_format = fmt::format("icon{}", core_i); + store.push_back(fmt::arg(icon_format.c_str(), getIcon(cpu_usage[i], icons))); } label_.set_markup(fmt::vformat(format, store)); } @@ -73,14 +73,14 @@ std::tuple, std::string> waybar::modules::Cpu::getCpuUsage std::this_thread::sleep_for(std::chrono::milliseconds(100)); } std::vector> curr_times = parseCpuinfo(); - std::string tooltip; - std::vector usage; + std::string tooltip; + std::vector usage; for (size_t i = 0; i < curr_times.size(); ++i) { auto [curr_idle, curr_total] = curr_times[i]; auto [prev_idle, prev_total] = prev_times_[i]; const float delta_idle = curr_idle - prev_idle; const float delta_total = curr_total - prev_total; - uint16_t tmp = 100 * (1 - delta_idle / delta_total); + uint16_t tmp = 100 * (1 - delta_idle / delta_total); if (i == 0) { tooltip = fmt::format("Total: {}%", tmp); } else { @@ -95,12 +95,13 @@ std::tuple, std::string> waybar::modules::Cpu::getCpuUsage std::tuple waybar::modules::Cpu::getCpuFrequency() { std::vector frequencies = parseCpuFrequencies(); 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 float max_frequency = std::ceil(*max / 10.0) / 100.0; float min_frequency = std::ceil(*min / 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}; } diff --git a/src/modules/cpu/linux.cpp b/src/modules/cpu/linux.cpp index 6d638a9f..e9b18d70 100644 --- a/src/modules/cpu/linux.cpp +++ b/src/modules/cpu/linux.cpp @@ -1,4 +1,5 @@ #include + #include "modules/cpu.hpp" std::vector> waybar::modules::Cpu::parseCpuinfo() { @@ -8,12 +9,12 @@ std::vector> waybar::modules::Cpu::parseCpuinfo() { throw std::runtime_error("Can't open " + data_dir_); } std::vector> cpuinfo; - std::string line; + std::string line; while (getline(info, line)) { if (line.substr(0, 3).compare("cpu") != 0) { break; } - std::stringstream sline(line.substr(5)); + std::stringstream sline(line.substr(5)); std::vector times; for (size_t time = 0; sline >> time; times.push_back(time)) ; @@ -51,12 +52,9 @@ std::vector waybar::modules::Cpu::parseCpuFrequencies() { if (frequencies.size() <= 0) { std::string cpufreq_dir = "/sys/devices/system/cpu/cpufreq"; if (std::filesystem::exists(cpufreq_dir)) { - std::vector frequency_files = { - "/cpuinfo_min_freq", - "/cpuinfo_max_freq" - }; - for (auto& p: std::filesystem::directory_iterator(cpufreq_dir)) { - for (auto freq_file: frequency_files) { + std::vector frequency_files = {"/cpuinfo_min_freq", "/cpuinfo_max_freq"}; + 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; if (std::filesystem::exists(freq_file_path)) { std::string freq_value; diff --git a/src/modules/custom.cpp b/src/modules/custom.cpp index ba55edd5..bbb7ce6b 100644 --- a/src/modules/custom.cpp +++ b/src/modules/custom.cpp @@ -48,7 +48,7 @@ void waybar::modules::Custom::continuousWorker() { throw std::runtime_error("Unable to open " + cmd); } thread_ = [this, cmd] { - char* buff = nullptr; + char* buff = nullptr; size_t len = 0; if (getline(&buff, &len, fp_) == -1) { int exit_code = 1; @@ -120,9 +120,7 @@ auto waybar::modules::Custom::update() -> void { } else { parseOutputRaw(); } - auto str = fmt::format(format_, - text_, - fmt::arg("alt", alt_), + auto str = fmt::format(format_, text_, fmt::arg("alt", alt_), fmt::arg("icon", getIcon(percentage_, alt_)), fmt::arg("percentage", percentage_)); if (str.empty()) { @@ -156,8 +154,8 @@ auto waybar::modules::Custom::update() -> void { void waybar::modules::Custom::parseOutputRaw() { std::istringstream output(output_.out); - std::string line; - int i = 0; + std::string line; + int i = 0; while (getline(output, line)) { if (i == 0) { if (config_["escape"].isBool() && config_["escape"].asBool()) { @@ -180,7 +178,7 @@ void waybar::modules::Custom::parseOutputRaw() { void waybar::modules::Custom::parseOutputJson() { std::istringstream output(output_.out); - std::string line; + std::string line; class_.clear(); while (getline(output, line)) { auto parsed = parser_.parse(line); diff --git a/src/modules/disk.cpp b/src/modules/disk.cpp index b4e50533..5578dc2f 100644 --- a/src/modules/disk.cpp +++ b/src/modules/disk.cpp @@ -3,9 +3,7 @@ using namespace waybar::util; waybar::modules::Disk::Disk(const std::string& id, const Json::Value& config) - : ALabel(config, "disk", id, "{}%", 30) - , path_("/") -{ + : ALabel(config, "disk", id, "{}%", 30), path_("/") { thread_ = [this] { dp.emit(); thread_.sleep_for(interval_); @@ -28,7 +26,8 @@ auto waybar::modules::Disk::update() -> void { unsigned long f_fsid; // filesystem ID unsigned long f_flag; // mount flags unsigned long f_namemax; // maximum filename length - }; */ stats; + }; */ + stats; int err = statvfs(path_.c_str(), &stats); /* Conky options @@ -59,15 +58,11 @@ auto waybar::modules::Disk::update() -> void { event_box_.hide(); } else { event_box_.show(); - label_.set_markup(fmt::format(format - , stats.f_bavail * 100 / stats.f_blocks - , fmt::arg("free", free) - , fmt::arg("percentage_free", stats.f_bavail * 100 / stats.f_blocks) - , fmt::arg("used", used) - , fmt::arg("percentage_used", percentage_used) - , fmt::arg("total", total) - , fmt::arg("path", path_) - )); + label_.set_markup( + fmt::format(format, stats.f_bavail * 100 / stats.f_blocks, fmt::arg("free", free), + fmt::arg("percentage_free", stats.f_bavail * 100 / stats.f_blocks), + fmt::arg("used", used), fmt::arg("percentage_used", percentage_used), + fmt::arg("total", total), fmt::arg("path", path_))); } if (tooltipEnabled()) { @@ -75,15 +70,11 @@ auto waybar::modules::Disk::update() -> void { if (config_["tooltip-format"].isString()) { tooltip_format = config_["tooltip-format"].asString(); } - label_.set_tooltip_text(fmt::format(tooltip_format - , stats.f_bavail * 100 / stats.f_blocks - , fmt::arg("free", free) - , fmt::arg("percentage_free", stats.f_bavail * 100 / stats.f_blocks) - , fmt::arg("used", used) - , fmt::arg("percentage_used", percentage_used) - , fmt::arg("total", total) - , fmt::arg("path", path_) - )); + label_.set_tooltip_text( + fmt::format(tooltip_format, stats.f_bavail * 100 / stats.f_blocks, fmt::arg("free", free), + fmt::arg("percentage_free", stats.f_bavail * 100 / stats.f_blocks), + fmt::arg("used", used), fmt::arg("percentage_used", percentage_used), + fmt::arg("total", total), fmt::arg("path", path_))); } // Call parent update ALabel::update(); diff --git a/src/modules/idle_inhibitor.cpp b/src/modules/idle_inhibitor.cpp index 26889c23..cf79565e 100644 --- a/src/modules/idle_inhibitor.cpp +++ b/src/modules/idle_inhibitor.cpp @@ -4,7 +4,7 @@ #include "util/command.hpp" std::list waybar::modules::IdleInhibitor::modules; -bool waybar::modules::IdleInhibitor::status = false; +bool waybar::modules::IdleInhibitor::status = false; waybar::modules::IdleInhibitor::IdleInhibitor(const std::string& id, const Bar& bar, const Json::Value& config) @@ -47,7 +47,7 @@ auto waybar::modules::IdleInhibitor::update() -> void { label_.get_style_context()->remove_class("deactivated"); if (idle_inhibitor_ == nullptr) { idle_inhibitor_ = zwp_idle_inhibit_manager_v1_create_inhibitor( - waybar::Client::inst()->idle_inhibit_manager, bar_.surface); + waybar::Client::inst()->idle_inhibit_manager, bar_.surface); } } else { label_.get_style_context()->remove_class("activated"); @@ -58,8 +58,8 @@ auto waybar::modules::IdleInhibitor::update() -> void { } std::string status_text = status ? "activated" : "deactivated"; - label_.set_markup( - fmt::format(format_, fmt::arg("status", status_text), fmt::arg("icon", getIcon(0, status_text)))); + label_.set_markup(fmt::format(format_, fmt::arg("status", status_text), + fmt::arg("icon", getIcon(0, status_text)))); label_.get_style_context()->add_class(status_text); if (tooltipEnabled()) { label_.set_tooltip_text(status_text); diff --git a/src/modules/inhibitor.cpp b/src/modules/inhibitor.cpp index 1e3f2d35..e4340b14 100644 --- a/src/modules/inhibitor.cpp +++ b/src/modules/inhibitor.cpp @@ -6,12 +6,11 @@ namespace { -using DBus = std::unique_ptr; +using DBus = std::unique_ptr; auto dbus() -> DBus { - GError *error = nullptr; - GDBusConnection* connection = - g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error); + GError* error = nullptr; + GDBusConnection* connection = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error); if (error) { spdlog::error("g_bus_get_sync() failed: {}", error->message); @@ -20,46 +19,29 @@ auto dbus() -> DBus { } auto destructor = [](GDBusConnection* connection) { - GError *error = nullptr; - g_dbus_connection_close_sync(connection, nullptr, &error); - if (error) { - spdlog::error( - "g_bus_connection_close_sync failed(): {}", - error->message); - g_error_free(error); - } + GError* error = nullptr; + g_dbus_connection_close_sync(connection, nullptr, &error); + if (error) { + spdlog::error("g_bus_connection_close_sync failed(): {}", error->message); + g_error_free(error); + } }; return DBus{connection, destructor}; } auto getLocks(const DBus& bus, const std::string& inhibitors) -> int { - GError *error = nullptr; + GError* error = nullptr; GUnixFDList* fd_list; int handle; - auto reply = g_dbus_connection_call_with_unix_fd_list_sync(bus.get(), - "org.freedesktop.login1", - "/org/freedesktop/login1", - "org.freedesktop.login1.Manager", - "Inhibit", - 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); + auto reply = g_dbus_connection_call_with_unix_fd_list_sync( + bus.get(), "org.freedesktop.login1", "/org/freedesktop/login1", + "org.freedesktop.login1.Manager", "Inhibit", + 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) { - spdlog::error( - "g_dbus_connection_call_with_unix_fd_list_sync() failed: {}", - error->message); + spdlog::error("g_dbus_connection_call_with_unix_fd_list_sync() failed: {}", error->message); g_error_free(error); handle = -1; } else { @@ -74,18 +56,15 @@ auto getLocks(const DBus& bus, const std::string& inhibitors) -> int { } auto checkInhibitor(const std::string& inhibitor) -> const std::string& { - static const auto inhibitors = std::array{ - "idle", - "shutdown", - "sleep", - "handle-power-key", - "handle-suspend-key", - "handle-hibernate-key", - "handle-lid-switch" - }; + static const auto inhibitors = std::array{"idle", + "shutdown", + "sleep", + "handle-power-key", + "handle-suspend-key", + "handle-hibernate-key", + "handle-lid-switch"}; - if (std::find(inhibitors.begin(), inhibitors.end(), inhibitor) - == inhibitors.end()) { + if (std::find(inhibitors.begin(), inhibitors.end(), inhibitor) == inhibitors.end()) { throw std::runtime_error("invalid logind inhibitor " + inhibitor); } @@ -114,18 +93,16 @@ auto getInhibitors(const Json::Value& config) -> std::string { return inhibitors; } -} +} // namespace namespace waybar::modules { -Inhibitor::Inhibitor(const std::string& id, const Bar& bar, - const Json::Value& config) +Inhibitor::Inhibitor(const std::string& id, const Bar& bar, const Json::Value& config) : ALabel(config, "inhibitor", id, "{status}", true), dbus_(::dbus()), inhibitors_(::getInhibitors(config)) { event_box_.add_events(Gdk::BUTTON_PRESS_MASK); - event_box_.signal_button_press_event().connect( - sigc::mem_fun(*this, &Inhibitor::handleToggle)); + event_box_.signal_button_press_event().connect(sigc::mem_fun(*this, &Inhibitor::handleToggle)); dp.emit(); } @@ -135,18 +112,14 @@ Inhibitor::~Inhibitor() { } } -auto Inhibitor::activated() -> bool { - return handle_ != -1; -} +auto Inhibitor::activated() -> bool { return handle_ != -1; } auto Inhibitor::update() -> void { std::string status_text = activated() ? "activated" : "deactivated"; - label_.get_style_context()->remove_class( - activated() ? "deactivated" : "activated"); - label_.set_markup( - fmt::format(format_, fmt::arg("status", status_text), - fmt::arg("icon", getIcon(0, status_text)))); + label_.get_style_context()->remove_class(activated() ? "deactivated" : "activated"); + label_.set_markup(fmt::format(format_, fmt::arg("status", status_text), + fmt::arg("icon", getIcon(0, status_text)))); label_.get_style_context()->add_class(status_text); if (tooltipEnabled()) { @@ -172,4 +145,4 @@ auto Inhibitor::handleToggle(GdkEventButton* const& e) -> bool { return ALabel::handleToggle(e); } -} // waybar::modules +} // namespace waybar::modules diff --git a/src/modules/keyboard_state.cpp b/src/modules/keyboard_state.cpp index 1ac075d6..734fd7f4 100644 --- a/src/modules/keyboard_state.cpp +++ b/src/modules/keyboard_state.cpp @@ -1,31 +1,32 @@ #include "modules/keyboard_state.hpp" + #include -#include #include #include +#include + extern "C" { -#include -#include #include +#include +#include } class errno_error : public std::runtime_error { public: int code; errno_error(int code, const std::string& msg) - : std::runtime_error(getErrorMsg(code, msg.c_str())), - code(code) {} - errno_error(int code, const char* msg) - : std::runtime_error(getErrorMsg(code, msg)), - code(code) {} + : std::runtime_error(getErrorMsg(code, msg.c_str())), code(code) {} + errno_error(int code, const char* msg) : std::runtime_error(getErrorMsg(code, msg)), code(code) {} + private: static auto getErrorMsg(int err, const char* msg) -> std::string { std::string error_msg{msg}; error_msg += ": "; #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); error_msg += errno_name; error_msg += " "; @@ -67,33 +68,37 @@ auto openDevice(int fd) -> libevdev* { } auto supportsLockStates(const libevdev* dev) -> bool { - 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_CAPSL) - && libevdev_has_event_code(dev, EV_LED, LED_SCROLLL); + 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_CAPSL) && + 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()), box_(bar.vertical ? Gtk::ORIENTATION_VERTICAL : Gtk::ORIENTATION_HORIZONTAL, 0), numlock_label_(""), capslock_label_(""), numlock_format_(config_["format"].isString() ? config_["format"].asString() - : config_["format"]["numlock"].isString() ? config_["format"]["numlock"].asString() - : "{name} {icon}"), + : config_["format"]["numlock"].isString() + ? config_["format"]["numlock"].asString() + : "{name} {icon}"), capslock_format_(config_["format"].isString() ? config_["format"].asString() - : config_["format"]["capslock"].isString() ? config_["format"]["capslock"].asString() - : "{name} {icon}"), + : config_["format"]["capslock"].isString() + ? config_["format"]["capslock"].asString() + : "{name} {icon}"), scrolllock_format_(config_["format"].isString() ? config_["format"].asString() - : config_["format"]["scrolllock"].isString() ? config_["format"]["scrolllock"].asString() - : "{name} {icon}"), - interval_(std::chrono::seconds(config_["interval"].isUInt() ? config_["interval"].asUInt() : 1)), + : config_["format"]["scrolllock"].isString() + ? config_["format"]["scrolllock"].asString() + : "{name} {icon}"), + interval_( + std::chrono::seconds(config_["interval"].isUInt() ? config_["interval"].asUInt() : 1)), icon_locked_(config_["format-icons"]["locked"].isString() - ? config_["format-icons"]["locked"].asString() - : "locked"), + ? config_["format-icons"]["locked"].asString() + : "locked"), icon_unlocked_(config_["format-icons"]["unlocked"].isString() - ? config_["format-icons"]["unlocked"].asString() - : "unlocked"), + ? config_["format-icons"]["unlocked"].asString() + : "unlocked"), fd_(0), dev_(nullptr) { box_.set_name("keyboard-state"); @@ -120,7 +125,7 @@ waybar::modules::KeyboardState::KeyboardState(const std::string& id, const Bar& if (dev_dir == nullptr) { throw errno_error(errno, "Failed to open /dev/input"); } - dirent *ep; + dirent* ep; while ((ep = readdir(dev_dir))) { if (ep->d_type != DT_CHR) continue; std::string dev_path = std::string("/dev/input/") + ep->d_name; @@ -128,7 +133,7 @@ waybar::modules::KeyboardState::KeyboardState(const std::string& id, const Bar& try { auto dev = openDevice(fd); if (supportsLockStates(dev)) { - spdlog::info("Found device {} at '{}'", libevdev_get_name(dev), dev_path); + spdlog::info("Found device {} at '{}'", libevdev_get_name(dev), dev_path); fd_ = fd; dev_ = dev; break; @@ -184,9 +189,9 @@ auto waybar::modules::KeyboardState::update() -> void { const std::string& format; const char* name; } label_states[] = { - {(bool) numl, numlock_label_, numlock_format_, "Num"}, - {(bool) capsl, capslock_label_, capslock_format_, "Caps"}, - {(bool) scrolll, scrolllock_label_, scrolllock_format_, "Scroll"}, + {(bool)numl, numlock_label_, numlock_format_, "Num"}, + {(bool)capsl, capslock_label_, capslock_format_, "Caps"}, + {(bool)scrolll, scrolllock_label_, scrolllock_format_, "Scroll"}, }; for (auto& label_state : label_states) { std::string text; diff --git a/src/modules/memory/bsd.cpp b/src/modules/memory/bsd.cpp index b3520d0c..d9098cee 100644 --- a/src/modules/memory/bsd.cpp +++ b/src/modules/memory/bsd.cpp @@ -1,15 +1,15 @@ +#include +#include +#include // getpagesize + #include "modules/memory.hpp" -#include -#include -#include // getpagesize - #if defined(__DragonFly__) -# include // struct vmstats +#include // struct vmstats #elif defined(__NetBSD__) -# include // struct uvmexp_sysctl +#include // struct uvmexp_sysctl #elif defined(__OpenBSD__) -# include // struct uvmexp +#include // struct uvmexp #endif static uint64_t get_total_memory() { @@ -43,33 +43,27 @@ static uint64_t get_free_memory() { if (sysctlbyname("vm.vmstats", &vms, &sz, NULL, 0)) { throw std::runtime_error("sysctl vm.vmstats failed"); } - return static_cast - (vms.v_free_count + vms.v_inactive_count + vms.v_cache_count) - * getpagesize(); + return static_cast(vms.v_free_count + vms.v_inactive_count + vms.v_cache_count) * + getpagesize(); #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) u_int v_free_count = 0, v_inactive_count = 0, v_cache_count = 0; size_t sz = sizeof(u_int); - sysctlbyname("vm.stats.vm.v_free_count", - &v_free_count, &sz, NULL, 0); - sysctlbyname("vm.stats.vm.v_inactive_count", - &v_inactive_count, &sz, NULL, 0); - sysctlbyname("vm.stats.vm.v_cache_count", - &v_cache_count, &sz, NULL, 0); - return static_cast - (v_free_count + v_inactive_count + v_cache_count) - * getpagesize(); + sysctlbyname("vm.stats.vm.v_free_count", &v_free_count, &sz, NULL, 0); + sysctlbyname("vm.stats.vm.v_inactive_count", &v_inactive_count, &sz, NULL, 0); + sysctlbyname("vm.stats.vm.v_cache_count", &v_cache_count, &sz, NULL, 0); + return static_cast(v_free_count + v_inactive_count + v_cache_count) * getpagesize(); #elif defined(__NetBSD__) || defined(__OpenBSD__) #ifdef VM_UVMEXP2 -# undef VM_UVMEXP -# define VM_UVMEXP VM_UVMEXP2 -# define uvmexp uvmexp_sysctl +#undef VM_UVMEXP +#define VM_UVMEXP VM_UVMEXP2 +#define uvmexp uvmexp_sysctl #else -# define filepages vnodepages -# define execpages vtextpages +#define filepages vnodepages +#define execpages vtextpages #endif int mib[] = { - CTL_VM, - VM_UVMEXP, + CTL_VM, + VM_UVMEXP, }; u_int miblen = sizeof(mib) / sizeof(mib[0]); struct uvmexp uvmexp; @@ -77,9 +71,9 @@ static uint64_t get_free_memory() { if (sysctl(mib, miblen, &uvmexp, &sz, NULL, 0)) { throw std::runtime_error("sysctl vm.uvmexp failed"); } - return static_cast - (uvmexp.free + uvmexp.inactive + uvmexp.filepages + uvmexp.execpages) - * uvmexp.pagesize; + return static_cast(uvmexp.free + uvmexp.inactive + uvmexp.filepages + + uvmexp.execpages) * + uvmexp.pagesize; #endif } diff --git a/src/modules/memory/common.cpp b/src/modules/memory/common.cpp index a0bf13fa..6bf84e86 100644 --- a/src/modules/memory/common.cpp +++ b/src/modules/memory/common.cpp @@ -33,8 +33,8 @@ auto waybar::modules::Memory::update() -> void { if (memtotal > 0 && memfree >= 0) { auto total_ram_gigabytes = memtotal / std::pow(1024, 2); auto total_swap_gigabytes = swaptotal / std::pow(1024, 2); - int used_ram_percentage = 100 * (memtotal - memfree) / memtotal; - int used_swap_percentage = 0; + int used_ram_percentage = 100 * (memtotal - memfree) / memtotal; + int used_swap_percentage = 0; if (swaptotal && swapfree) { used_swap_percentage = 100 * (swaptotal - swapfree) / swaptotal; } @@ -54,32 +54,25 @@ auto waybar::modules::Memory::update() -> void { } else { event_box_.show(); auto icons = std::vector{state}; - label_.set_markup(fmt::format(format, - used_ram_percentage, - fmt::arg("icon", getIcon(used_ram_percentage, icons)), - fmt::arg("total", total_ram_gigabytes), - fmt::arg("swapTotal", total_swap_gigabytes), - fmt::arg("percentage", used_ram_percentage), - fmt::arg("swapPercentage", used_swap_percentage), - fmt::arg("used", used_ram_gigabytes), - fmt::arg("swapUsed", used_swap_gigabytes), - fmt::arg("avail", available_ram_gigabytes), - fmt::arg("swapAvail", available_swap_gigabytes))); + label_.set_markup(fmt::format( + format, used_ram_percentage, fmt::arg("icon", getIcon(used_ram_percentage, icons)), + fmt::arg("total", total_ram_gigabytes), fmt::arg("swapTotal", total_swap_gigabytes), + fmt::arg("percentage", used_ram_percentage), + fmt::arg("swapPercentage", used_swap_percentage), fmt::arg("used", used_ram_gigabytes), + fmt::arg("swapUsed", used_swap_gigabytes), fmt::arg("avail", available_ram_gigabytes), + fmt::arg("swapAvail", available_swap_gigabytes))); } if (tooltipEnabled()) { if (config_["tooltip-format"].isString()) { auto tooltip_format = config_["tooltip-format"].asString(); - label_.set_tooltip_text(fmt::format(tooltip_format, - used_ram_percentage, - fmt::arg("total", total_ram_gigabytes), - fmt::arg("swapTotal", total_swap_gigabytes), - fmt::arg("percentage", used_ram_percentage), - fmt::arg("swapPercentage", used_swap_percentage), - fmt::arg("used", used_ram_gigabytes), - fmt::arg("swapUsed", used_swap_gigabytes), - fmt::arg("avail", available_ram_gigabytes), - fmt::arg("swapAvail", available_swap_gigabytes))); + label_.set_tooltip_text(fmt::format( + tooltip_format, used_ram_percentage, fmt::arg("total", total_ram_gigabytes), + fmt::arg("swapTotal", total_swap_gigabytes), + fmt::arg("percentage", used_ram_percentage), + fmt::arg("swapPercentage", used_swap_percentage), fmt::arg("used", used_ram_gigabytes), + fmt::arg("swapUsed", used_swap_gigabytes), fmt::arg("avail", available_ram_gigabytes), + fmt::arg("swapAvail", available_swap_gigabytes))); } else { label_.set_tooltip_text(fmt::format("{:.{}f}GiB used", used_ram_gigabytes, 1)); } diff --git a/src/modules/memory/linux.cpp b/src/modules/memory/linux.cpp index 34d55c93..50f50d6f 100644 --- a/src/modules/memory/linux.cpp +++ b/src/modules/memory/linux.cpp @@ -4,8 +4,8 @@ static unsigned zfsArcSize() { std::ifstream zfs_arc_stats{"/proc/spl/kstat/zfs/arcstats"}; if (zfs_arc_stats.is_open()) { - std::string name; - std::string type; + std::string name; + std::string type; unsigned long data{0}; std::string line; @@ -23,7 +23,7 @@ static unsigned zfsArcSize() { void waybar::modules::Memory::parseMeminfo() { const std::string data_dir_ = "/proc/meminfo"; - std::ifstream info(data_dir_); + std::ifstream info(data_dir_); if (!info.is_open()) { throw std::runtime_error("Can't open " + data_dir_); } @@ -35,7 +35,7 @@ void waybar::modules::Memory::parseMeminfo() { } std::string name = line.substr(0, posDelim); - int64_t value = std::stol(line.substr(posDelim + 1)); + int64_t value = std::stol(line.substr(posDelim + 1)); meminfo_[name] = value; } diff --git a/src/modules/mpd/mpd.cpp b/src/modules/mpd/mpd.cpp index e5cafc02..cfacb20c 100644 --- a/src/modules/mpd/mpd.cpp +++ b/src/modules/mpd/mpd.cpp @@ -1,8 +1,9 @@ #include "modules/mpd/mpd.hpp" #include -#include #include +#include + #include "modules/mpd/state.hpp" #if defined(MPD_NOINLINE) namespace waybar::modules { @@ -98,9 +99,9 @@ void waybar::modules::MPD::setLabel() { } auto format = format_; - Glib::ustring artist, album_artist, album, title; - std::string date; - int song_pos = 0, queue_length = 0, volume = 0; + Glib::ustring artist, album_artist, album, title; + std::string date; + int song_pos = 0, queue_length = 0, volume = 0; std::chrono::seconds elapsedTime, totalTime; std::string stateIcon = ""; @@ -139,37 +140,32 @@ void waybar::modules::MPD::setLabel() { totalTime = std::chrono::seconds(mpd_status_get_total_time(status_.get())); } - bool consumeActivated = mpd_status_get_consume(status_.get()); + bool consumeActivated = mpd_status_get_consume(status_.get()); std::string consumeIcon = getOptionIcon("consume", consumeActivated); - bool randomActivated = mpd_status_get_random(status_.get()); + bool randomActivated = mpd_status_get_random(status_.get()); std::string randomIcon = getOptionIcon("random", randomActivated); - bool repeatActivated = mpd_status_get_repeat(status_.get()); + bool repeatActivated = mpd_status_get_repeat(status_.get()); std::string repeatIcon = getOptionIcon("repeat", repeatActivated); - bool singleActivated = mpd_status_get_single(status_.get()); + bool singleActivated = mpd_status_get_single(status_.get()); std::string singleIcon = getOptionIcon("single", singleActivated); if (config_["artist-len"].isInt()) artist = artist.substr(0, config_["artist-len"].asInt()); - if (config_["album-artist-len"].isInt()) album_artist = album_artist.substr(0, config_["album-artist-len"].asInt()); + if (config_["album-artist-len"].isInt()) + album_artist = album_artist.substr(0, config_["album-artist-len"].asInt()); if (config_["album-len"].isInt()) album = album.substr(0, config_["album-len"].asInt()); - if (config_["title-len"].isInt()) title = title.substr(0,config_["title-len"].asInt()); + if (config_["title-len"].isInt()) title = title.substr(0, config_["title-len"].asInt()); try { label_.set_markup( - fmt::format(format, - fmt::arg("artist", Glib::Markup::escape_text(artist).raw()), + fmt::format(format, fmt::arg("artist", Glib::Markup::escape_text(artist).raw()), fmt::arg("albumArtist", Glib::Markup::escape_text(album_artist).raw()), fmt::arg("album", Glib::Markup::escape_text(album).raw()), fmt::arg("title", Glib::Markup::escape_text(title).raw()), fmt::arg("date", Glib::Markup::escape_text(date).raw()), - fmt::arg("volume", volume), - fmt::arg("elapsedTime", elapsedTime), - fmt::arg("totalTime", totalTime), - fmt::arg("songPosition", song_pos), - fmt::arg("queueLength", queue_length), - fmt::arg("stateIcon", stateIcon), - fmt::arg("consumeIcon", consumeIcon), - fmt::arg("randomIcon", randomIcon), - fmt::arg("repeatIcon", repeatIcon), - fmt::arg("singleIcon", singleIcon))); + fmt::arg("volume", volume), fmt::arg("elapsedTime", elapsedTime), + fmt::arg("totalTime", totalTime), fmt::arg("songPosition", song_pos), + fmt::arg("queueLength", queue_length), fmt::arg("stateIcon", stateIcon), + fmt::arg("consumeIcon", consumeIcon), fmt::arg("randomIcon", randomIcon), + fmt::arg("repeatIcon", repeatIcon), fmt::arg("singleIcon", singleIcon))); } catch (fmt::format_error const& e) { 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() : "MPD (connected)"; try { - auto tooltip_text = fmt::format(tooltip_format, - fmt::arg("artist", artist.raw()), - fmt::arg("albumArtist", album_artist.raw()), - fmt::arg("album", album.raw()), - fmt::arg("title", title.raw()), - fmt::arg("date", date), - fmt::arg("volume", volume), - fmt::arg("elapsedTime", elapsedTime), - fmt::arg("totalTime", totalTime), - fmt::arg("songPosition", song_pos), - fmt::arg("queueLength", queue_length), - fmt::arg("stateIcon", stateIcon), - fmt::arg("consumeIcon", consumeIcon), - fmt::arg("randomIcon", randomIcon), - fmt::arg("repeatIcon", repeatIcon), - fmt::arg("singleIcon", singleIcon)); + auto tooltip_text = + fmt::format(tooltip_format, fmt::arg("artist", artist.raw()), + fmt::arg("albumArtist", album_artist.raw()), fmt::arg("album", album.raw()), + fmt::arg("title", title.raw()), fmt::arg("date", date), + fmt::arg("volume", volume), fmt::arg("elapsedTime", elapsedTime), + fmt::arg("totalTime", totalTime), fmt::arg("songPosition", song_pos), + fmt::arg("queueLength", queue_length), fmt::arg("stateIcon", stateIcon), + fmt::arg("consumeIcon", consumeIcon), fmt::arg("randomIcon", randomIcon), + fmt::arg("repeatIcon", repeatIcon), fmt::arg("singleIcon", singleIcon)); label_.set_tooltip_text(tooltip_text); } catch (fmt::format_error const& e) { spdlog::warn("mpd: format error (tooltip): {}", e.what()); diff --git a/src/modules/mpd/state.cpp b/src/modules/mpd/state.cpp index ffe18e7c..4d1e8c91 100644 --- a/src/modules/mpd/state.cpp +++ b/src/modules/mpd/state.cpp @@ -50,7 +50,7 @@ void Idle::update() noexcept { } void Idle::entry() noexcept { - auto conn = ctx_->connection().get(); + auto conn = ctx_->connection().get(); assert(conn != nullptr); if (!mpd_send_idle_mask( @@ -61,8 +61,7 @@ void Idle::entry() noexcept { spdlog::debug("mpd: Idle: watching FD"); sigc::slot idle_slot = sigc::mem_fun(*this, &Idle::on_io); idle_connection_ = - Glib::signal_io().connect(idle_slot, - mpd_connection_get_fd(conn), + Glib::signal_io().connect(idle_slot, mpd_connection_get_fd(conn), Glib::IO_IN | Glib::IO_PRI | Glib::IO_ERR | Glib::IO_HUP); } } @@ -75,7 +74,7 @@ void Idle::exit() noexcept { } bool Idle::on_io(Glib::IOCondition const&) { - auto conn = ctx_->connection().get(); + auto conn = ctx_->connection().get(); // callback should do this: enum mpd_idle events = mpd_recv_idle(conn, /* ignore_timeout?= */ false); @@ -193,7 +192,7 @@ void Paused::exit() noexcept { } bool Paused::on_timer() { - bool rc = true; + bool rc = true; // Attempt to connect with MPD. try { @@ -264,7 +263,7 @@ void Stopped::exit() noexcept { } bool Stopped::on_timer() { - bool rc = true; + bool rc = true; // Attempt to connect with MPD. try { @@ -327,8 +326,7 @@ void Disconnected::arm_timer(int interval) noexcept { // register timer sigc::slot timer_slot = sigc::mem_fun(*this, &Disconnected::on_timer); - timer_connection_ = - Glib::signal_timeout().connect(timer_slot, interval); + timer_connection_ = Glib::signal_timeout().connect(timer_slot, interval); spdlog::debug("mpd: Disconnected: enabled interval timer."); } @@ -345,9 +343,7 @@ void Disconnected::entry() noexcept { arm_timer(1'000); } -void Disconnected::exit() noexcept { - disarm_timer(); -} +void Disconnected::exit() noexcept { disarm_timer(); } bool Disconnected::on_timer() { // Attempt to connect with MPD. diff --git a/src/modules/network.cpp b/src/modules/network.cpp index 74b54d91..eb71b6e2 100644 --- a/src/modules/network.cpp +++ b/src/modules/network.cpp @@ -1,13 +1,14 @@ +#include "modules/network.hpp" + #include #include #include #include #include -#include #include +#include -#include "modules/network.hpp" #include "util/format.hpp" #ifdef WANT_RFKILL #include "util/rfkill.hpp" @@ -39,7 +40,7 @@ waybar::modules::Network::readBandwidthUsage() { std::istringstream iss(line); std::string ifacename; - iss >> ifacename; // ifacename contains "eth0:" + iss >> ifacename; // ifacename contains "eth0:" ifacename.pop_back(); // remove trailing ':' if (!checkInterface(ifacename)) { continue; @@ -58,9 +59,13 @@ waybar::modules::Network::readBandwidthUsage() { // Skip all the other columns in the received group for (int colsToSkip = 7; colsToSkip > 0; colsToSkip--) { // skip whitespace between columns - while (iss.peek() == ' ') { iss.ignore(); } + while (iss.peek() == ' ') { + iss.ignore(); + } // skip the irrelevant column - while (iss.peek() != ' ') { iss.ignore(); } + while (iss.peek() != ' ') { + iss.ignore(); + } } // Read transmit bytes iss >> t; @@ -192,7 +197,7 @@ void waybar::modules::Network::createEventSocket() { } } { - auto fd = nl_socket_get_fd(ev_sock_); + auto fd = nl_socket_get_fd(ev_sock_); struct epoll_event event; memset(&event, 0, sizeof(event)); event.events = EPOLLIN | EPOLLET | EPOLLRDHUP; @@ -274,8 +279,7 @@ void waybar::modules::Network::worker() { const std::string waybar::modules::Network::getNetworkState() const { if (ifid_ == -1) { #ifdef WANT_RFKILL - if (rfkill_.getState()) - return "disabled"; + if (rfkill_.getState()) return "disabled"; #endif return "disconnected"; } @@ -287,7 +291,7 @@ const std::string waybar::modules::Network::getNetworkState() const { auto waybar::modules::Network::update() -> void { std::lock_guard lock(mutex_); - std::string tooltip_format; + std::string tooltip_format; auto bandwidth = readBandwidthUsage(); auto bandwidth_down = 0ull; @@ -327,17 +331,11 @@ auto waybar::modules::Network::update() -> void { getState(signal_strength_); auto text = fmt::format( - format_, - fmt::arg("essid", essid_), - fmt::arg("signaldBm", signal_strength_dbm_), + format_, fmt::arg("essid", essid_), fmt::arg("signaldBm", signal_strength_dbm_), fmt::arg("signalStrength", signal_strength_), - fmt::arg("signalStrengthApp", signal_strength_app_), - fmt::arg("ifname", ifname_), - fmt::arg("netmask", netmask_), - fmt::arg("ipaddr", ipaddr_), - fmt::arg("gwaddr", gwaddr_), - fmt::arg("cidr", cidr_), - fmt::arg("frequency", fmt::format("{:.1f}", frequency_)), + fmt::arg("signalStrengthApp", signal_strength_app_), fmt::arg("ifname", ifname_), + fmt::arg("netmask", netmask_), 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("bandwidthDownBits", pow_format(bandwidth_down * 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()) { auto tooltip_text = fmt::format( - tooltip_format, - fmt::arg("essid", essid_), - fmt::arg("signaldBm", signal_strength_dbm_), + tooltip_format, fmt::arg("essid", essid_), fmt::arg("signaldBm", signal_strength_dbm_), fmt::arg("signalStrength", signal_strength_), - fmt::arg("signalStrengthApp", signal_strength_app_), - fmt::arg("ifname", ifname_), - fmt::arg("netmask", netmask_), - fmt::arg("ipaddr", ipaddr_), - fmt::arg("gwaddr", gwaddr_), - fmt::arg("cidr", cidr_), - fmt::arg("frequency", fmt::format("{:.1f}", frequency_)), + fmt::arg("signalStrengthApp", signal_strength_app_), fmt::arg("ifname", ifname_), + fmt::arg("netmask", netmask_), 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("bandwidthDownBits", pow_format(bandwidth_down * 8ull / interval_.count(), "b/s")), @@ -414,286 +406,279 @@ void waybar::modules::Network::clearIface() { } int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) { - auto net = static_cast(data); + auto net = static_cast(data); std::lock_guard lock(net->mutex_); - auto nh = nlmsg_hdr(msg); - bool is_del_event = false; + auto nh = nlmsg_hdr(msg); + bool is_del_event = false; switch (nh->nlmsg_type) { - case RTM_DELLINK: - is_del_event = true; - case RTM_NEWLINK: { - struct ifinfomsg *ifi = static_cast(NLMSG_DATA(nh)); - ssize_t attrlen = IFLA_PAYLOAD(nh); - struct rtattr *ifla = IFLA_RTA(ifi); - const char *ifname = NULL; - size_t ifname_len = 0; - std::optional carrier; + case RTM_DELLINK: + is_del_event = true; + case RTM_NEWLINK: { + struct ifinfomsg *ifi = static_cast(NLMSG_DATA(nh)); + ssize_t attrlen = IFLA_PAYLOAD(nh); + struct rtattr *ifla = IFLA_RTA(ifi); + const char *ifname = NULL; + size_t ifname_len = 0; + std::optional carrier; - if (net->ifid_ != -1 && ifi->ifi_index != net->ifid_) { - return NL_OK; - } - - // Check if the interface goes "down" and if we want to detect the - // external interface. - if (net->ifid_ != -1 && !(ifi->ifi_flags & IFF_UP) - && !net->config_["interface"].isString()) { - // The current interface is now down, all the routes associated with - // it have been deleted, so start looking for a new default route. - spdlog::debug("network: if{} down", net->ifid_); - net->clearIface(); - net->dp.emit(); - net->want_route_dump_ = true; - net->askForStateDump(); - return NL_OK; - } - - for (; RTA_OK(ifla, attrlen); ifla = RTA_NEXT(ifla, attrlen)) { - switch (ifla->rta_type) { - case IFLA_IFNAME: - ifname = static_cast(RTA_DATA(ifla)); - ifname_len = RTA_PAYLOAD(ifla) - 1; // minus \0 - break; - case IFLA_CARRIER: { - carrier = *(char*)RTA_DATA(ifla) == 1; - break; + if (net->ifid_ != -1 && ifi->ifi_index != net->ifid_) { + return NL_OK; } - } - } - - if (!is_del_event && ifi->ifi_index == net->ifid_) { - // Update interface information - if (net->ifname_.empty() && ifname != NULL) { - std::string new_ifname (ifname, ifname_len); - net->ifname_ = new_ifname; - } - if (carrier.has_value()) { - if (net->carrier_ != *carrier) { - if (*carrier) { - // Ask for WiFi information - net->thread_timer_.wake_up(); - } else { - // clear state related to WiFi connection - net->essid_.clear(); - net->signal_strength_dbm_ = 0; - net->signal_strength_ = 0; - net->signal_strength_app_.clear(); - net->frequency_ = 0.0; - } - } - net->carrier_ = carrier.value(); - } - } else if (!is_del_event && net->ifid_ == -1) { - // Checking if it's an interface we care about. - std::string new_ifname (ifname, ifname_len); - if (net->checkInterface(new_ifname)) { - spdlog::debug("network: selecting new interface {}/{}", new_ifname, ifi->ifi_index); - - net->ifname_ = new_ifname; - net->ifid_ = ifi->ifi_index; - if (carrier.has_value()) { - net->carrier_ = carrier.value(); - } - net->thread_timer_.wake_up(); - /* An address for this new interface should be received via an - * RTM_NEWADDR event either because we ask for a dump of both links - * and addrs, or because this interface has just been created and - * the addr will be sent after the RTM_NEWLINK event. - * So we don't need to do anything. */ - } - } else if (is_del_event && net->ifid_ >= 0) { - // Our interface has been deleted, start looking/waiting for one we care. - spdlog::debug("network: interface {}/{} deleted", net->ifname_, net->ifid_); - - net->clearIface(); - net->dp.emit(); - } - break; - } - - case RTM_DELADDR: - is_del_event = true; - case RTM_NEWADDR: { - struct ifaddrmsg *ifa = static_cast(NLMSG_DATA(nh)); - ssize_t attrlen = IFA_PAYLOAD(nh); - struct rtattr *ifa_rta = IFA_RTA(ifa); - - if ((int)ifa->ifa_index != net->ifid_) { - return NL_OK; - } - - if (ifa->ifa_family != net->family_) { - return NL_OK; - } - - // We ignore address mark as scope for the link or host, - // which should leave scope global addresses. - if (ifa->ifa_scope >= RT_SCOPE_LINK) { - return NL_OK; - } - - for (; RTA_OK(ifa_rta, attrlen); ifa_rta = RTA_NEXT(ifa_rta, attrlen)) { - switch (ifa_rta->rta_type) { - case IFA_ADDRESS: { - char ipaddr[INET6_ADDRSTRLEN]; - if (!is_del_event) { - net->ipaddr_ = inet_ntop(ifa->ifa_family, RTA_DATA(ifa_rta), - ipaddr, sizeof (ipaddr)); - net->cidr_ = ifa->ifa_prefixlen; - switch (ifa->ifa_family) { - case AF_INET: { - struct in_addr netmask; - netmask.s_addr = htonl(~0 << (32 - ifa->ifa_prefixlen)); - net->netmask_ = inet_ntop(ifa->ifa_family, &netmask, - ipaddr, sizeof (ipaddr)); - } - case AF_INET6: { - struct in6_addr netmask; - for (int i = 0; i < 16; i++) { - int v = (i + 1) * 8 - ifa->ifa_prefixlen; - if (v < 0) v = 0; - if (v > 8) v = 8; - netmask.s6_addr[i] = ~0 << v; - } - net->netmask_ = inet_ntop(ifa->ifa_family, &netmask, - ipaddr, sizeof (ipaddr)); - } - } - spdlog::debug("network: {}, new addr {}/{}", net->ifname_, net->ipaddr_, net->cidr_); - } else { - net->ipaddr_.clear(); - net->cidr_ = 0; - net->netmask_.clear(); - spdlog::debug("network: {} addr deleted {}/{}", - net->ifname_, - inet_ntop(ifa->ifa_family, RTA_DATA(ifa_rta), - ipaddr, sizeof (ipaddr)), - ifa->ifa_prefixlen); - } - net->dp.emit(); - break; - } - } - } - break; - } - - char temp_gw_addr[INET6_ADDRSTRLEN]; - case RTM_DELROUTE: - is_del_event = true; - case RTM_NEWROUTE: { - // Based on https://gist.github.com/Yawning/c70d804d4b8ae78cc698 - // to find the interface used to reach the outside world - - struct rtmsg *rtm = static_cast(NLMSG_DATA(nh)); - ssize_t attrlen = RTM_PAYLOAD(nh); - struct rtattr *attr = RTM_RTA(rtm); - bool has_gateway = false; - bool has_destination = false; - int temp_idx = -1; - uint32_t priority = 0; - - - /* Find the message(s) concerting the main routing table, each message - * corresponds to a single routing table entry. - */ - if (rtm->rtm_table != RT_TABLE_MAIN) { - return NL_OK; - } - - /* Parse all the attributes for a single routing table entry. */ - for (; RTA_OK(attr, attrlen); attr = RTA_NEXT(attr, attrlen)) { - /* Determine if this routing table entry corresponds to the default - * route by seeing if it has a gateway, and if a destination addr is - * set, that it is all 0s. - */ - switch(attr->rta_type) { - case RTA_GATEWAY: - /* The gateway of the route. - * - * If someone ever needs to figure out the gateway address as well, - * it's here as the attribute payload. - */ - inet_ntop(net->family_, RTA_DATA(attr), temp_gw_addr, sizeof(temp_gw_addr)); - has_gateway = true; - break; - case RTA_DST: { - /* The destination address. - * Should be either missing, or maybe all 0s. Accept both. - */ - const uint32_t nr_zeroes = (net->family_ == AF_INET) ? 4 : 16; - unsigned char c = 0; - size_t dstlen = RTA_PAYLOAD(attr); - if (dstlen != nr_zeroes) { - break; - } - for (uint32_t i = 0; i < dstlen; i += 1) { - c |= *((unsigned char *)RTA_DATA(attr) + i); - } - has_destination = (c == 0); - break; - } - case RTA_OIF: - /* The output interface index. */ - temp_idx = *static_cast(RTA_DATA(attr)); - break; - case RTA_PRIORITY: - priority = *(uint32_t*)RTA_DATA(attr); - break; - default: - break; - } - } - - // Check if we have a default route. - if (has_gateway && !has_destination && temp_idx != -1) { - // Check if this is the first default route we see, or if this new - // route have a higher priority. - if (!is_del_event && ((net->ifid_ == -1) || (priority < net->route_priority))) { - // Clear if's state for the case were there is a higher priority - // route on a different interface. - net->clearIface(); - net->ifid_ = temp_idx; - net->route_priority = priority; - net->gwaddr_ = temp_gw_addr; - 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 */ - struct ifinfomsg ifinfo_hdr = { - .ifi_family = AF_UNSPEC, - .ifi_index = temp_idx, - }; - int err; - err = nl_send_simple(net->ev_sock_, RTM_GETLINK, NLM_F_REQUEST, - &ifinfo_hdr, sizeof (ifinfo_hdr)); - if (err < 0) { - spdlog::error("network: failed to ask link info: {}", err); - /* Ask for a dump of all links instead */ - net->want_link_dump_ = true; - } - - /* Also ask for the address. Asking for a addresses of a specific - * interface doesn't seems to work so ask for a dump of all - * addresses. */ - net->want_addr_dump_ = true; - net->askForStateDump(); - net->thread_timer_.wake_up(); - } else if (is_del_event && temp_idx == net->ifid_ - && net->route_priority == priority) { - spdlog::debug("network: default route deleted {}/if{} metric {}", - net->ifname_, temp_idx, priority); + // Check if the interface goes "down" and if we want to detect the + // external interface. + if (net->ifid_ != -1 && !(ifi->ifi_flags & IFF_UP) && !net->config_["interface"].isString()) { + // The current interface is now down, all the routes associated with + // it have been deleted, so start looking for a new default route. + spdlog::debug("network: if{} down", net->ifid_); net->clearIface(); net->dp.emit(); - /* Ask for a dump of all routes in case another one is already - * setup. If there's none, there'll be an event with new one - * later. */ net->want_route_dump_ = true; net->askForStateDump(); + return NL_OK; } + + for (; RTA_OK(ifla, attrlen); ifla = RTA_NEXT(ifla, attrlen)) { + switch (ifla->rta_type) { + case IFLA_IFNAME: + ifname = static_cast(RTA_DATA(ifla)); + ifname_len = RTA_PAYLOAD(ifla) - 1; // minus \0 + break; + case IFLA_CARRIER: { + carrier = *(char *)RTA_DATA(ifla) == 1; + break; + } + } + } + + if (!is_del_event && ifi->ifi_index == net->ifid_) { + // Update interface information + if (net->ifname_.empty() && ifname != NULL) { + std::string new_ifname(ifname, ifname_len); + net->ifname_ = new_ifname; + } + if (carrier.has_value()) { + if (net->carrier_ != *carrier) { + if (*carrier) { + // Ask for WiFi information + net->thread_timer_.wake_up(); + } else { + // clear state related to WiFi connection + net->essid_.clear(); + net->signal_strength_dbm_ = 0; + net->signal_strength_ = 0; + net->signal_strength_app_.clear(); + net->frequency_ = 0.0; + } + } + net->carrier_ = carrier.value(); + } + } else if (!is_del_event && net->ifid_ == -1) { + // Checking if it's an interface we care about. + std::string new_ifname(ifname, ifname_len); + if (net->checkInterface(new_ifname)) { + spdlog::debug("network: selecting new interface {}/{}", new_ifname, ifi->ifi_index); + + net->ifname_ = new_ifname; + net->ifid_ = ifi->ifi_index; + if (carrier.has_value()) { + net->carrier_ = carrier.value(); + } + net->thread_timer_.wake_up(); + /* An address for this new interface should be received via an + * RTM_NEWADDR event either because we ask for a dump of both links + * and addrs, or because this interface has just been created and + * the addr will be sent after the RTM_NEWLINK event. + * So we don't need to do anything. */ + } + } else if (is_del_event && net->ifid_ >= 0) { + // Our interface has been deleted, start looking/waiting for one we care. + spdlog::debug("network: interface {}/{} deleted", net->ifname_, net->ifid_); + + net->clearIface(); + net->dp.emit(); + } + break; + } + + case RTM_DELADDR: + is_del_event = true; + case RTM_NEWADDR: { + struct ifaddrmsg *ifa = static_cast(NLMSG_DATA(nh)); + ssize_t attrlen = IFA_PAYLOAD(nh); + struct rtattr *ifa_rta = IFA_RTA(ifa); + + if ((int)ifa->ifa_index != net->ifid_) { + return NL_OK; + } + + if (ifa->ifa_family != net->family_) { + return NL_OK; + } + + // We ignore address mark as scope for the link or host, + // which should leave scope global addresses. + if (ifa->ifa_scope >= RT_SCOPE_LINK) { + return NL_OK; + } + + for (; RTA_OK(ifa_rta, attrlen); ifa_rta = RTA_NEXT(ifa_rta, attrlen)) { + switch (ifa_rta->rta_type) { + case IFA_ADDRESS: { + char ipaddr[INET6_ADDRSTRLEN]; + if (!is_del_event) { + net->ipaddr_ = inet_ntop(ifa->ifa_family, RTA_DATA(ifa_rta), ipaddr, sizeof(ipaddr)); + net->cidr_ = ifa->ifa_prefixlen; + switch (ifa->ifa_family) { + case AF_INET: { + struct in_addr netmask; + netmask.s_addr = htonl(~0 << (32 - ifa->ifa_prefixlen)); + net->netmask_ = inet_ntop(ifa->ifa_family, &netmask, ipaddr, sizeof(ipaddr)); + } + case AF_INET6: { + struct in6_addr netmask; + for (int i = 0; i < 16; i++) { + int v = (i + 1) * 8 - ifa->ifa_prefixlen; + if (v < 0) v = 0; + if (v > 8) v = 8; + netmask.s6_addr[i] = ~0 << v; + } + net->netmask_ = inet_ntop(ifa->ifa_family, &netmask, ipaddr, sizeof(ipaddr)); + } + } + spdlog::debug("network: {}, new addr {}/{}", net->ifname_, net->ipaddr_, net->cidr_); + } else { + net->ipaddr_.clear(); + net->cidr_ = 0; + net->netmask_.clear(); + spdlog::debug("network: {} addr deleted {}/{}", net->ifname_, + inet_ntop(ifa->ifa_family, RTA_DATA(ifa_rta), ipaddr, sizeof(ipaddr)), + ifa->ifa_prefixlen); + } + net->dp.emit(); + break; + } + } + } + break; + } + + char temp_gw_addr[INET6_ADDRSTRLEN]; + case RTM_DELROUTE: + is_del_event = true; + case RTM_NEWROUTE: { + // Based on https://gist.github.com/Yawning/c70d804d4b8ae78cc698 + // to find the interface used to reach the outside world + + struct rtmsg *rtm = static_cast(NLMSG_DATA(nh)); + ssize_t attrlen = RTM_PAYLOAD(nh); + struct rtattr *attr = RTM_RTA(rtm); + bool has_gateway = false; + bool has_destination = false; + int temp_idx = -1; + uint32_t priority = 0; + + /* Find the message(s) concerting the main routing table, each message + * corresponds to a single routing table entry. + */ + if (rtm->rtm_table != RT_TABLE_MAIN) { + return NL_OK; + } + + /* Parse all the attributes for a single routing table entry. */ + for (; RTA_OK(attr, attrlen); attr = RTA_NEXT(attr, attrlen)) { + /* Determine if this routing table entry corresponds to the default + * route by seeing if it has a gateway, and if a destination addr is + * set, that it is all 0s. + */ + switch (attr->rta_type) { + case RTA_GATEWAY: + /* The gateway of the route. + * + * If someone ever needs to figure out the gateway address as well, + * it's here as the attribute payload. + */ + inet_ntop(net->family_, RTA_DATA(attr), temp_gw_addr, sizeof(temp_gw_addr)); + has_gateway = true; + break; + case RTA_DST: { + /* The destination address. + * Should be either missing, or maybe all 0s. Accept both. + */ + const uint32_t nr_zeroes = (net->family_ == AF_INET) ? 4 : 16; + unsigned char c = 0; + size_t dstlen = RTA_PAYLOAD(attr); + if (dstlen != nr_zeroes) { + break; + } + for (uint32_t i = 0; i < dstlen; i += 1) { + c |= *((unsigned char *)RTA_DATA(attr) + i); + } + has_destination = (c == 0); + break; + } + case RTA_OIF: + /* The output interface index. */ + temp_idx = *static_cast(RTA_DATA(attr)); + break; + case RTA_PRIORITY: + priority = *(uint32_t *)RTA_DATA(attr); + break; + default: + break; + } + } + + // Check if we have a default route. + if (has_gateway && !has_destination && temp_idx != -1) { + // Check if this is the first default route we see, or if this new + // route have a higher priority. + if (!is_del_event && ((net->ifid_ == -1) || (priority < net->route_priority))) { + // Clear if's state for the case were there is a higher priority + // route on a different interface. + net->clearIface(); + net->ifid_ = temp_idx; + net->route_priority = priority; + net->gwaddr_ = temp_gw_addr; + 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 */ + struct ifinfomsg ifinfo_hdr = { + .ifi_family = AF_UNSPEC, + .ifi_index = temp_idx, + }; + int err; + err = nl_send_simple(net->ev_sock_, RTM_GETLINK, NLM_F_REQUEST, &ifinfo_hdr, + sizeof(ifinfo_hdr)); + if (err < 0) { + spdlog::error("network: failed to ask link info: {}", err); + /* Ask for a dump of all links instead */ + net->want_link_dump_ = true; + } + + /* Also ask for the address. Asking for a addresses of a specific + * interface doesn't seems to work so ask for a dump of all + * addresses. */ + net->want_addr_dump_ = true; + net->askForStateDump(); + net->thread_timer_.wake_up(); + } else if (is_del_event && temp_idx == net->ifid_ && net->route_priority == priority) { + spdlog::debug("network: default route deleted {}/if{} metric {}", net->ifname_, temp_idx, + priority); + + net->clearIface(); + net->dp.emit(); + /* Ask for a dump of all routes in case another one is already + * setup. If there's none, there'll be an event with new one + * later. */ + net->want_route_dump_ = true; + net->askForStateDump(); + } + } + break; } - break; - } } return NL_OK; @@ -702,30 +687,26 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) { void waybar::modules::Network::askForStateDump(void) { /* We need to wait until the current dump is done before sending new * messages. handleEventsDone() is called when a dump is done. */ - if (dump_in_progress_) - return; + if (dump_in_progress_) return; struct rtgenmsg rt_hdr = { - .rtgen_family = AF_UNSPEC, + .rtgen_family = AF_UNSPEC, }; if (want_route_dump_) { rt_hdr.rtgen_family = family_; - nl_send_simple(ev_sock_, RTM_GETROUTE, NLM_F_DUMP, - &rt_hdr, sizeof (rt_hdr)); + nl_send_simple(ev_sock_, RTM_GETROUTE, NLM_F_DUMP, &rt_hdr, sizeof(rt_hdr)); want_route_dump_ = false; dump_in_progress_ = true; } else if (want_link_dump_) { - nl_send_simple(ev_sock_, RTM_GETLINK, NLM_F_DUMP, - &rt_hdr, sizeof (rt_hdr)); + nl_send_simple(ev_sock_, RTM_GETLINK, NLM_F_DUMP, &rt_hdr, sizeof(rt_hdr)); want_link_dump_ = false; dump_in_progress_ = true; } else if (want_addr_dump_) { rt_hdr.rtgen_family = family_; - nl_send_simple(ev_sock_, RTM_GETADDR, NLM_F_DUMP, - &rt_hdr, sizeof (rt_hdr)); + nl_send_simple(ev_sock_, RTM_GETADDR, NLM_F_DUMP, &rt_hdr, sizeof(rt_hdr)); want_addr_dump_ = false; dump_in_progress_ = true; } @@ -739,10 +720,10 @@ int waybar::modules::Network::handleEventsDone(struct nl_msg *msg, void *data) { } int waybar::modules::Network::handleScan(struct nl_msg *msg, void *data) { - auto net = static_cast(data); - auto gnlh = static_cast(nlmsg_data(nlmsg_hdr(msg))); - struct nlattr * tb[NL80211_ATTR_MAX + 1]; - struct nlattr * bss[NL80211_BSS_MAX + 1]; + auto net = static_cast(data); + auto gnlh = static_cast(nlmsg_data(nlmsg_hdr(msg))); + struct nlattr *tb[NL80211_ATTR_MAX + 1]; + struct nlattr *bss[NL80211_BSS_MAX + 1]; struct nla_policy bss_policy[NL80211_BSS_MAX + 1]{}; bss_policy[NL80211_BSS_TSF].type = NLA_U64; bss_policy[NL80211_BSS_FREQUENCY].type = NLA_U32; @@ -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_STATUS].type = NLA_U32; - if (nla_parse( - tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_attrlen(gnlh, 0), nullptr) < 0) { + if (nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_attrlen(gnlh, 0), + nullptr) < 0) { return NL_SKIP; } if (tb[NL80211_ATTR_BSS] == nullptr) { @@ -775,16 +756,16 @@ int waybar::modules::Network::handleScan(struct nl_msg *msg, void *data) { void waybar::modules::Network::parseEssid(struct nlattr **bss) { if (bss[NL80211_BSS_INFORMATION_ELEMENTS] != nullptr) { - auto ies = static_cast(nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS])); - auto ies_len = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]); + auto ies = static_cast(nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS])); + auto ies_len = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]); const auto hdr_len = 2; while (ies_len > hdr_len && ies[0] != 0) { ies_len -= ies[1] + hdr_len; ies += ies[1] + hdr_len; } if (ies_len > hdr_len && ies_len > ies[1] + hdr_len) { - auto essid_begin = ies + hdr_len; - auto essid_end = essid_begin + ies[1]; + auto essid_begin = ies + hdr_len; + auto essid_end = essid_begin + ies[1]; std::string essid_raw; std::copy(essid_begin, essid_end, std::back_inserter(essid_raw)); essid_ = Glib::Markup::escape_text(essid_raw); @@ -804,8 +785,10 @@ void waybar::modules::Network::parseSignal(struct nlattr **bss) { const int hardwareOptimum = -45; const int hardwareMin = -90; const int strength = - 100 - ((abs(signal_strength_dbm_ - hardwareOptimum) / double{hardwareOptimum - hardwareMin}) * 100); - signal_strength_ = std::clamp(strength, 0, 100); + 100 - + ((abs(signal_strength_dbm_ - hardwareOptimum) / double{hardwareOptimum - hardwareMin}) * + 100); + signal_strength_ = std::clamp(strength, 0, 100); if (signal_strength_dbm_ >= -50) { signal_strength_app_ = "Great Connectivity"; @@ -829,7 +812,7 @@ void waybar::modules::Network::parseSignal(struct nlattr **bss) { void waybar::modules::Network::parseFreq(struct nlattr **bss) { if (bss[NL80211_BSS_FREQUENCY] != nullptr) { // in GHz - frequency_ = (double) nla_get_u32(bss[NL80211_BSS_FREQUENCY]) / 1000; + frequency_ = (double)nla_get_u32(bss[NL80211_BSS_FREQUENCY]) / 1000; } } @@ -853,9 +836,8 @@ auto waybar::modules::Network::getInfo() -> void { if (nl_msg == nullptr) { return; } - if (genlmsg_put( - nl_msg, NL_AUTO_PORT, NL_AUTO_SEQ, nl80211_id_, 0, NLM_F_DUMP, NL80211_CMD_GET_SCAN, 0) == - nullptr || + if (genlmsg_put(nl_msg, NL_AUTO_PORT, NL_AUTO_SEQ, nl80211_id_, 0, NLM_F_DUMP, + NL80211_CMD_GET_SCAN, 0) == nullptr || nla_put_u32(nl_msg, NL80211_ATTR_IFINDEX, ifid_) < 0) { nlmsg_free(nl_msg); return; diff --git a/src/modules/pulseaudio.cpp b/src/modules/pulseaudio.cpp index b1f78302..03d09061 100644 --- a/src/modules/pulseaudio.cpp +++ b/src/modules/pulseaudio.cpp @@ -50,15 +50,14 @@ void waybar::modules::Pulseaudio::contextStateCb(pa_context *c, void *data) { case PA_CONTEXT_READY: pa_context_get_server_info(c, serverInfoCb, data); pa_context_set_subscribe_callback(c, subscribeCb, data); - pa_context_subscribe( - c, - static_cast(static_cast(PA_SUBSCRIPTION_MASK_SERVER) | - static_cast(PA_SUBSCRIPTION_MASK_SINK) | - static_cast(PA_SUBSCRIPTION_MASK_SINK_INPUT) | - static_cast(PA_SUBSCRIPTION_MASK_SOURCE) | - static_cast(PA_SUBSCRIPTION_MASK_SOURCE_OUTPUT)), - nullptr, - nullptr); + pa_context_subscribe(c, + static_cast( + static_cast(PA_SUBSCRIPTION_MASK_SERVER) | + static_cast(PA_SUBSCRIPTION_MASK_SINK) | + static_cast(PA_SUBSCRIPTION_MASK_SINK_INPUT) | + static_cast(PA_SUBSCRIPTION_MASK_SOURCE) | + static_cast(PA_SUBSCRIPTION_MASK_SOURCE_OUTPUT)), + nullptr, nullptr); break; case PA_CONTEXT_FAILED: pa->mainloop_api_->quit(pa->mainloop_api_, 1); @@ -81,16 +80,16 @@ bool waybar::modules::Pulseaudio::handleScroll(GdkEventScroll *e) { if (dir == SCROLL_DIR::NONE) { return true; } - if (config_["reverse-scrolling"].asInt() == 1){ + if (config_["reverse-scrolling"].asInt() == 1) { if (dir == SCROLL_DIR::UP) { dir = SCROLL_DIR::DOWN; } else if (dir == SCROLL_DIR::DOWN) { dir = SCROLL_DIR::UP; } } - double volume_tick = static_cast(PA_VOLUME_NORM) / 100; + double volume_tick = static_cast(PA_VOLUME_NORM) / 100; pa_volume_t change = volume_tick; - pa_cvolume pa_volume = pa_volume_; + pa_cvolume pa_volume = pa_volume_; // isDouble returns true for integers as well, just in case if (config_["scroll-step"].isDouble()) { change = round(config_["scroll-step"].asDouble() * volume_tick); @@ -111,7 +110,7 @@ bool waybar::modules::Pulseaudio::handleScroll(GdkEventScroll *e) { /* * 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, void *data) { 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, int /*eol*/, void *data) { - if (i == nullptr) - return; + if (i == nullptr) return; auto pa = static_cast(data); 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 ports = { - "headphone", - "speaker", - "hdmi", - "headset", - "hands-free", - "portable", - "car", - "hifi", - "phone", + "headphone", "speaker", "hdmi", "headset", "hands-free", "portable", "car", "hifi", "phone", }; const std::vector waybar::modules::Pulseaudio::getPulseIcon() const { @@ -238,11 +228,11 @@ const std::vector waybar::modules::Pulseaudio::getPulseIcon() const auto waybar::modules::Pulseaudio::update() -> void { auto format = format_; - std::string tooltip_format; + std::string tooltip_format; if (!alt_) { std::string format_name = "format"; - if (monitor_.find("a2dp_sink") != std::string::npos || // PulseAudio - monitor_.find("a2dp-sink") != std::string::npos) { // PipeWire + if (monitor_.find("a2dp_sink") != std::string::npos || // PulseAudio + monitor_.find("a2dp-sink") != std::string::npos) { // PipeWire format_name = format_name + "-bluetooth"; label_.get_style_context()->add_class("bluetooth"); } else { @@ -260,8 +250,7 @@ auto waybar::modules::Pulseaudio::update() -> void { label_.get_style_context()->remove_class("muted"); label_.get_style_context()->remove_class("sink-muted"); } - format = - config_[format_name].isString() ? config_[format_name].asString() : format; + format = config_[format_name].isString() ? config_[format_name].asString() : format; } // TODO: find a better way to split source/sink 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_)); - label_.set_markup(fmt::format(format, - fmt::arg("desc", desc_), - fmt::arg("volume", volume_), - fmt::arg("format_source", format_source), - fmt::arg("source_volume", source_volume_), - fmt::arg("source_desc", source_desc_), - fmt::arg("icon", getIcon(volume_, getPulseIcon())))); + label_.set_markup(fmt::format( + format, fmt::arg("desc", desc_), fmt::arg("volume", volume_), + fmt::arg("format_source", format_source), fmt::arg("source_volume", source_volume_), + fmt::arg("source_desc", source_desc_), fmt::arg("icon", getIcon(volume_, getPulseIcon())))); getState(volume_); if (tooltipEnabled()) { @@ -292,13 +278,10 @@ auto waybar::modules::Pulseaudio::update() -> void { } if (!tooltip_format.empty()) { label_.set_tooltip_text(fmt::format( - tooltip_format, - fmt::arg("desc", desc_), - fmt::arg("volume", volume_), - fmt::arg("format_source", format_source), - fmt::arg("source_volume", source_volume_), - fmt::arg("source_desc", source_desc_), - fmt::arg("icon", getIcon(volume_, getPulseIcon())))); + tooltip_format, fmt::arg("desc", desc_), fmt::arg("volume", volume_), + fmt::arg("format_source", format_source), fmt::arg("source_volume", source_volume_), + fmt::arg("source_desc", source_desc_), + fmt::arg("icon", getIcon(volume_, getPulseIcon())))); } else { label_.set_tooltip_text(desc_); } diff --git a/src/modules/river/tags.cpp b/src/modules/river/tags.cpp index 87655beb..ccafc167 100644 --- a/src/modules/river/tags.cpp +++ b/src/modules/river/tags.cpp @@ -1,3 +1,5 @@ +#include "modules/river/tags.hpp" + #include #include #include @@ -6,7 +8,6 @@ #include #include "client.hpp" -#include "modules/river/tags.hpp" #include "xdg-output-unstable-v1-client-protocol.h" namespace waybar::modules::river { @@ -44,7 +45,7 @@ static void listen_command_failure(void *data, 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, .failure = listen_command_failure, }; @@ -77,7 +78,6 @@ static void handle_global_remove(void *data, struct wl_registry *registry, uint3 /* Ignore event */ } - static const wl_registry_listener registry_listener_impl = {.global = handle_global, .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), box_{bar.vertical ? Gtk::ORIENTATION_VERTICAL : Gtk::ORIENTATION_HORIZONTAL, 0}, 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); wl_registry_add_listener(registry, ®istry_listener_impl, this); wl_display_roundtrip(display); @@ -119,7 +119,7 @@ Tags::Tags(const std::string &id, const waybar::Bar &bar, const Json::Value &con std::vector tag_labels(num_tags); 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"]; 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); box_.pack_start(button, false, false, 0); if (!config_["disable-click"].asBool()) { - button.signal_clicked().connect(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.signal_clicked().connect( + 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(); i <<= 1; diff --git a/src/modules/simpleclock.cpp b/src/modules/simpleclock.cpp index 3004fc2c..f4a4ec47 100644 --- a/src/modules/simpleclock.cpp +++ b/src/modules/simpleclock.cpp @@ -1,4 +1,5 @@ #include "modules/simpleclock.hpp" + #include waybar::modules::Clock::Clock(const std::string& id, const Json::Value& config) @@ -13,7 +14,7 @@ waybar::modules::Clock::Clock(const std::string& id, const Json::Value& config) } auto waybar::modules::Clock::update() -> void { - tzset(); // Update timezone information + tzset(); // Update timezone information auto now = std::chrono::system_clock::now(); auto localtime = fmt::localtime(std::chrono::system_clock::to_time_t(now)); auto text = fmt::format(format_, localtime); diff --git a/src/modules/sndio.cpp b/src/modules/sndio.cpp index 34c46bdd..63e9eac3 100644 --- a/src/modules/sndio.cpp +++ b/src/modules/sndio.cpp @@ -1,14 +1,16 @@ #include "modules/sndio.hpp" + +#include +#include +#include + #include #include -#include -#include -#include namespace waybar::modules { void ondesc(void *arg, struct sioctl_desc *d, int curval) { - auto self = static_cast(arg); + auto self = static_cast(arg); if (d == NULL) { // d is NULL when the list is done 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) { - auto self = static_cast(arg); + auto self = static_cast(arg); self->put_val(addr, val); } @@ -52,10 +54,8 @@ Sndio::Sndio(const std::string &id, const Json::Value &config) event_box_.show(); event_box_.add_events(Gdk::SCROLL_MASK | Gdk::SMOOTH_SCROLL_MASK | Gdk::BUTTON_PRESS_MASK); - event_box_.signal_scroll_event().connect( - sigc::mem_fun(*this, &Sndio::handleScroll)); - event_box_.signal_button_press_event().connect( - sigc::mem_fun(*this, &Sndio::handleToggle)); + event_box_.signal_scroll_event().connect(sigc::mem_fun(*this, &Sndio::handleScroll)); + event_box_.signal_button_press_event().connect(sigc::mem_fun(*this, &Sndio::handleToggle)); thread_ = [this] { dp.emit(); @@ -80,7 +80,7 @@ Sndio::Sndio(const std::string &id, const Json::Value &config) while (thread_.isRunning()) { try { connect_to_sndio(); - } catch(std::runtime_error const& e) { + } catch (std::runtime_error const &e) { // avoid leaking hdl_ if (hdl_) { sioctl_close(hdl_); @@ -98,9 +98,7 @@ Sndio::Sndio(const std::string &id, const Json::Value &config) }; } -Sndio::~Sndio() { - sioctl_close(hdl_); -} +Sndio::~Sndio() { sioctl_close(hdl_); } auto Sndio::update() -> void { auto format = format_; @@ -112,9 +110,7 @@ auto Sndio::update() -> void { label_.get_style_context()->remove_class("muted"); } - label_.set_markup(fmt::format(format, - fmt::arg("volume", vol), - fmt::arg("raw_value", volume_))); + label_.set_markup(fmt::format(format, fmt::arg("volume", vol), fmt::arg("raw_value", volume_))); ALabel::update(); } @@ -177,7 +173,7 @@ bool Sndio::handleScroll(GdkEventScroll *e) { return true; } -bool Sndio::handleToggle(GdkEventButton* const& e) { +bool Sndio::handleToggle(GdkEventButton *const &e) { // toggle mute only when no user provided events are configured if (config_["on-click"].isString()) { return AModule::handleToggle(e); diff --git a/src/modules/sni/host.cpp b/src/modules/sni/host.cpp index 414f1515..560d7368 100644 --- a/src/modules/sni/host.cpp +++ b/src/modules/sni/host.cpp @@ -1,4 +1,5 @@ #include "modules/sni/host.hpp" + #include #include @@ -32,8 +33,7 @@ Host::~Host() { } void Host::busAcquired(const Glib::RefPtr& conn, Glib::ustring name) { - watcher_id_ = Gio::DBus::watch_name(conn, - "org.kde.StatusNotifierWatcher", + watcher_id_ = Gio::DBus::watch_name(conn, "org.kde.StatusNotifierWatcher", sigc::mem_fun(*this, &Host::nameAppeared), sigc::mem_fun(*this, &Host::nameVanished)); } @@ -45,13 +45,8 @@ void Host::nameAppeared(const Glib::RefPtr& conn, const G return; } cancellable_ = g_cancellable_new(); - sn_watcher_proxy_new(conn->gobj(), - G_DBUS_PROXY_FLAGS_NONE, - "org.kde.StatusNotifierWatcher", - "/StatusNotifierWatcher", - cancellable_, - &Host::proxyReady, - this); + sn_watcher_proxy_new(conn->gobj(), G_DBUS_PROXY_FLAGS_NONE, "org.kde.StatusNotifierWatcher", + "/StatusNotifierWatcher", cancellable_, &Host::proxyReady, this); } void Host::nameVanished(const Glib::RefPtr& conn, const Glib::ustring name) { @@ -62,7 +57,7 @@ void Host::nameVanished(const Glib::RefPtr& conn, const G } void Host::proxyReady(GObject* src, GAsyncResult* res, gpointer data) { - GError* error = nullptr; + GError* error = nullptr; SnWatcher* watcher = sn_watcher_proxy_new_finish(res, &error); if (g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) { spdlog::error("Host: {}", error->message); @@ -76,8 +71,8 @@ void Host::proxyReady(GObject* src, GAsyncResult* res, gpointer data) { g_error_free(error); return; } - sn_watcher_call_register_host( - host->watcher_, host->object_path_.c_str(), host->cancellable_, &Host::registerHost, data); + sn_watcher_call_register_host(host->watcher_, host->object_path_.c_str(), host->cancellable_, + &Host::registerHost, data); } void Host::registerHost(GObject* src, GAsyncResult* res, gpointer data) { diff --git a/src/modules/sni/item.cpp b/src/modules/sni/item.cpp index 74987ca4..0295153e 100644 --- a/src/modules/sni/item.cpp +++ b/src/modules/sni/item.cpp @@ -31,7 +31,7 @@ struct fmt::formatter : formatter { namespace waybar::modules::SNI { static const Glib::ustring SNI_INTERFACE_NAME = sn_item_interface_info()->name; -static const unsigned UPDATE_DEBOUNCE_TIME = 10; +static const unsigned UPDATE_DEBOUNCE_TIME = 10; Item::Item(const std::string& bn, const std::string& op, const Json::Value& config, const Bar& bar) : bus_name(bn), @@ -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(); } - auto &window = const_cast(bar).window; + auto& window = const_cast(bar).window; window.signal_configure_event().connect_notify(sigc::mem_fun(*this, &Item::onConfigure)); event_box.add(image); 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(); auto interface = Glib::wrap(sn_item_interface_info(), true); - Gio::DBus::Proxy::create_for_bus(Gio::DBus::BusType::BUS_TYPE_SESSION, - bus_name, - object_path, - SNI_INTERFACE_NAME, - sigc::mem_fun(*this, &Item::proxyReady), - cancellable_, - interface); + Gio::DBus::Proxy::create_for_bus(Gio::DBus::BusType::BUS_TYPE_SESSION, bus_name, object_path, + SNI_INTERFACE_NAME, sigc::mem_fun(*this, &Item::proxyReady), + cancellable_, interface); } -void Item::onConfigure(GdkEventConfigure* ev) { - this->updateImage(); -} +void Item::onConfigure(GdkEventConfigure* ev) { this->updateImage(); } void Item::proxyReady(Glib::RefPtr& result) { try { @@ -167,16 +161,10 @@ void Item::setProperty(const Glib::ustring& name, Glib::VariantBase& value) { } } catch (const Glib::Error& err) { spdlog::warn("Failed to set tray item property: {}.{}, value = {}, err = {}", - id.empty() ? bus_name : id, - name, - value, - err.what()); + id.empty() ? bus_name : id, name, value, err.what()); } catch (const std::exception& err) { spdlog::warn("Failed to set tray item property: {}.{}, value = {}, err = {}", - id.empty() ? bus_name : id, - name, - value, - err.what()); + id.empty() ? bus_name : id, name, value, err.what()); } } @@ -199,8 +187,7 @@ void Item::getUpdatedProperties() { auto params = Glib::VariantContainerBase::create_tuple( {Glib::Variant::create(SNI_INTERFACE_NAME)}); proxy_->call("org.freedesktop.DBus.Properties.GetAll", - sigc::mem_fun(*this, &Item::processUpdatedProperties), - params); + sigc::mem_fun(*this, &Item::processUpdatedProperties), params); }; void Item::processUpdatedProperties(Glib::RefPtr& _result) { @@ -266,11 +253,11 @@ Glib::RefPtr Item::extractPixBuf(GVariant* variant) { return Glib::RefPtr{}; } GVariant* val; - gint lwidth = 0; - gint lheight = 0; - gint width; - gint height; - guchar* array = nullptr; + gint lwidth = 0; + gint lheight = 0; + gint width; + gint height; + guchar* array = nullptr; while (g_variant_iter_loop(it, "(ii@ay)", &width, &height, &val)) { if (width > 0 && height > 0 && val != nullptr && width * height > lwidth * lheight) { auto size = g_variant_get_size(val); @@ -303,14 +290,8 @@ Glib::RefPtr Item::extractPixBuf(GVariant* variant) { array[i + 2] = array[i + 3]; array[i + 3] = alpha; } - return Gdk::Pixbuf::create_from_data(array, - Gdk::Colorspace::COLORSPACE_RGB, - true, - 8, - lwidth, - lheight, - 4 * lwidth, - &pixbuf_data_deleter); + return Gdk::Pixbuf::create_from_data(array, Gdk::Colorspace::COLORSPACE_RGB, true, 8, lwidth, + lheight, 4 * lwidth, &pixbuf_data_deleter); } return Glib::RefPtr{}; } @@ -318,7 +299,7 @@ Glib::RefPtr Item::extractPixBuf(GVariant* variant) { void Item::updateImage() { auto pixbuf = getIconPixbuf(); auto scaled_icon_size = getScaledIconSize(); - + if (!pixbuf) { pixbuf = getIconByName("image-missing", getScaledIconSize()); } @@ -349,7 +330,7 @@ Glib::RefPtr Item::getIconPixbuf() { } } catch (Glib::Error& e) { spdlog::error("Item '{}': {}", id, static_cast(e.what())); - } + } return getIconByName("image-missing", getScaledIconSize()); } @@ -374,15 +355,15 @@ Glib::RefPtr Item::getIconByName(const std::string& name, int reque tmp_size = request_size; } if (!icon_theme_path.empty() && - icon_theme->lookup_icon( - name.c_str(), tmp_size, Gtk::IconLookupFlags::ICON_LOOKUP_FORCE_SIZE)) { - return icon_theme->load_icon( - name.c_str(), tmp_size, Gtk::IconLookupFlags::ICON_LOOKUP_FORCE_SIZE); + icon_theme->lookup_icon(name.c_str(), tmp_size, + Gtk::IconLookupFlags::ICON_LOOKUP_FORCE_SIZE)) { + return icon_theme->load_icon(name.c_str(), tmp_size, + Gtk::IconLookupFlags::ICON_LOOKUP_FORCE_SIZE); } Glib::RefPtr default_theme = Gtk::IconTheme::get_default(); default_theme->rescan_if_needed(); - return default_theme->load_icon( - name.c_str(), tmp_size, Gtk::IconLookupFlags::ICON_LOOKUP_FORCE_SIZE); + return default_theme->load_icon(name.c_str(), tmp_size, + Gtk::IconLookupFlags::ICON_LOOKUP_FORCE_SIZE); } double Item::getScaledIconSize() { diff --git a/src/modules/sni/tray.cpp b/src/modules/sni/tray.cpp index 94120be6..87e5577f 100644 --- a/src/modules/sni/tray.cpp +++ b/src/modules/sni/tray.cpp @@ -1,4 +1,5 @@ #include "modules/sni/tray.hpp" + #include namespace waybar::modules::SNI { diff --git a/src/modules/sni/watcher.cpp b/src/modules/sni/watcher.cpp index 73b3eaca..34bcef68 100644 --- a/src/modules/sni/watcher.cpp +++ b/src/modules/sni/watcher.cpp @@ -1,4 +1,5 @@ #include "modules/sni/watcher.hpp" + #include using namespace waybar::modules::SNI; @@ -29,8 +30,8 @@ Watcher::~Watcher() { void Watcher::busAcquired(const Glib::RefPtr& conn, Glib::ustring name) { GError* error = nullptr; - g_dbus_interface_skeleton_export( - G_DBUS_INTERFACE_SKELETON(watcher_), conn->gobj(), "/StatusNotifierWatcher", &error); + g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(watcher_), conn->gobj(), + "/StatusNotifierWatcher", &error); if (error != nullptr) { // Don't print an error when a watcher is already present if (error->code != 2) { @@ -39,10 +40,10 @@ void Watcher::busAcquired(const Glib::RefPtr& conn, Glib: g_error_free(error); return; } - g_signal_connect_swapped( - watcher_, "handle-register-item", G_CALLBACK(&Watcher::handleRegisterItem), this); - g_signal_connect_swapped( - watcher_, "handle-register-host", G_CALLBACK(&Watcher::handleRegisterHost), this); + g_signal_connect_swapped(watcher_, "handle-register-item", + G_CALLBACK(&Watcher::handleRegisterItem), this); + g_signal_connect_swapped(watcher_, "handle-register-host", + G_CALLBACK(&Watcher::handleRegisterHost), this); } gboolean Watcher::handleRegisterHost(Watcher* obj, GDBusMethodInvocation* invocation, @@ -55,22 +56,16 @@ gboolean Watcher::handleRegisterHost(Watcher* obj, GDBusMethodInvocation* invoca object_path = service; } if (g_dbus_is_name(bus_name) == FALSE) { - g_dbus_method_invocation_return_error(invocation, - G_DBUS_ERROR, - G_DBUS_ERROR_INVALID_ARGS, - "D-Bus bus name '%s' is not valid", - bus_name); + g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, + "D-Bus bus name '%s' is not valid", bus_name); return TRUE; } auto watch = gfWatchFind(obj->hosts_, bus_name, object_path); if (watch != nullptr) { g_dbus_method_invocation_return_error( - invocation, - G_DBUS_ERROR, - G_DBUS_ERROR_INVALID_ARGS, + invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Status Notifier Host with bus name '%s' and object path '%s' is already registered", - bus_name, - object_path); + bus_name, object_path); return TRUE; } 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; } if (g_dbus_is_name(bus_name) == FALSE) { - g_dbus_method_invocation_return_error(invocation, - G_DBUS_ERROR, - G_DBUS_ERROR_INVALID_ARGS, - "D-Bus bus name '%s' is not valid", - bus_name); + g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, + "D-Bus bus name '%s' is not valid", bus_name); return TRUE; } auto watch = gfWatchFind(obj->items_, bus_name, object_path); if (watch != nullptr) { g_warning("Status Notifier Item with bus name '%s' and object path '%s' is already registered", - bus_name, - object_path); + bus_name, object_path); sn_watcher_complete_register_item(obj->watcher_, invocation); return TRUE; } @@ -152,13 +143,8 @@ Watcher::GfWatch* Watcher::gfWatchNew(GfWatchType type, const gchar* service, co watch->service = g_strdup(service); watch->bus_name = g_strdup(bus_name); watch->object_path = g_strdup(object_path); - watch->watch_id = g_bus_watch_name(G_BUS_TYPE_SESSION, - bus_name, - G_BUS_NAME_WATCHER_FLAGS_NONE, - nullptr, - &Watcher::nameVanished, - watch, - nullptr); + watch->watch_id = g_bus_watch_name(G_BUS_TYPE_SESSION, bus_name, G_BUS_NAME_WATCHER_FLAGS_NONE, + nullptr, &Watcher::nameVanished, watch, nullptr); return watch; } @@ -183,12 +169,12 @@ void Watcher::updateRegisteredItems(SnWatcher* obj) { GVariantBuilder builder; g_variant_builder_init(&builder, G_VARIANT_TYPE("as")); for (GSList* l = items_; l != nullptr; l = g_slist_next(l)) { - auto watch = static_cast(l->data); + auto watch = static_cast(l->data); gchar* item = g_strdup_printf("%s%s", watch->bus_name, watch->object_path); g_variant_builder_add(&builder, "s", item); g_free(item); } - GVariant* variant = g_variant_builder_end(&builder); + GVariant* variant = g_variant_builder_end(&builder); const gchar** items = g_variant_get_strv(variant, nullptr); sn_watcher_set_registered_items(obj, items); g_variant_unref(variant); diff --git a/src/modules/sway/bar.cpp b/src/modules/sway/bar.cpp index 6ad74af1..7a235ae3 100644 --- a/src/modules/sway/bar.cpp +++ b/src/modules/sway/bar.cpp @@ -79,11 +79,8 @@ void BarIpcClient::onIpcEvent(const struct Ipc::ipc_response& res) { } void BarIpcClient::onConfigUpdate(const swaybar_config& config) { - spdlog::info("config update for {}: id {}, mode {}, hidden_state {}", - bar_.bar_id, - config.id, - config.mode, - config.hidden_state); + spdlog::info("config update for {}: id {}, mode {}, hidden_state {}", bar_.bar_id, config.id, + config.mode, config.hidden_state); bar_config_ = config; update(); } diff --git a/src/modules/sway/ipc/client.cpp b/src/modules/sway/ipc/client.cpp index 58aed60c..4d6495cb 100644 --- a/src/modules/sway/ipc/client.cpp +++ b/src/modules/sway/ipc/client.cpp @@ -1,4 +1,5 @@ #include "modules/sway/ipc/client.hpp" + #include namespace waybar::modules::sway { @@ -35,8 +36,8 @@ const std::string Ipc::getSocketPath() const { std::string str; { std::string str_buf; - FILE* in; - char buf[512] = {0}; + FILE* in; + char buf[512] = {0}; if ((in = popen("sway --get-socketpath 2>/dev/null", "r")) == nullptr) { throw std::runtime_error("Failed to get socket path"); } @@ -76,7 +77,7 @@ int Ipc::open(const std::string& socketPath) const { struct Ipc::ipc_response Ipc::recv(int fd) { std::string header; header.resize(ipc_header_size_); - auto data32 = reinterpret_cast(header.data() + ipc_magic_.size()); + auto data32 = reinterpret_cast(header.data() + ipc_magic_.size()); size_t total = 0; while (total < ipc_header_size_) { diff --git a/src/modules/sway/language.cpp b/src/modules/sway/language.cpp index 163a5fdf..68e31470 100644 --- a/src/modules/sway/language.cpp +++ b/src/modules/sway/language.cpp @@ -51,8 +51,8 @@ void Language::onCmd(const struct Ipc::ipc_response& res) { try { std::lock_guard lock(mutex_); - auto payload = parser_.parse(res.payload); - std::vector used_layouts; + auto payload = parser_.parse(res.payload); + std::vector used_layouts; // Display current layout of a device with a maximum count of layouts, expecting that all will // be OK Json::ArrayIndex max_id = 0, max = 0; @@ -83,7 +83,7 @@ void Language::onEvent(const struct Ipc::ipc_response& res) { try { std::lock_guard lock(mutex_); - auto payload = parser_.parse(res.payload)["input"]; + auto payload = parser_.parse(res.payload)["input"]; if (payload["type"].asString() == "keyboard") { set_current_layout(payload[XKB_ACTIVE_LAYOUT_NAME_KEY].asString()); } @@ -95,21 +95,18 @@ void Language::onEvent(const struct Ipc::ipc_response& res) { auto Language::update() -> void { std::lock_guard lock(mutex_); - auto display_layout = trim(fmt::format(format_, - fmt::arg("short", layout_.short_name), - fmt::arg("shortDescription", layout_.short_description), - fmt::arg("long", layout_.full_name), - fmt::arg("variant", layout_.variant), - fmt::arg("flag", layout_.country_flag()))); + auto display_layout = trim(fmt::format( + format_, fmt::arg("short", layout_.short_name), + fmt::arg("shortDescription", layout_.short_description), fmt::arg("long", layout_.full_name), + fmt::arg("variant", layout_.variant), fmt::arg("flag", layout_.country_flag()))); label_.set_markup(display_layout); if (tooltipEnabled()) { if (tooltip_format_ != "") { - auto tooltip_display_layout = trim(fmt::format(tooltip_format_, - fmt::arg("short", layout_.short_name), - fmt::arg("shortDescription", layout_.short_description), - fmt::arg("long", layout_.full_name), - fmt::arg("variant", layout_.variant), - fmt::arg("flag", layout_.country_flag()))); + auto tooltip_display_layout = trim( + fmt::format(tooltip_format_, fmt::arg("short", layout_.short_name), + fmt::arg("shortDescription", layout_.short_description), + fmt::arg("long", layout_.full_name), fmt::arg("variant", layout_.variant), + fmt::arg("flag", layout_.country_flag()))); label_.set_tooltip_markup(tooltip_display_layout); } else { label_.set_tooltip_markup(display_layout); @@ -129,7 +126,7 @@ auto Language::set_current_layout(std::string current_layout) -> void { auto Language::init_layouts_map(const std::vector& used_layouts) -> void { std::map> found_by_short_names; XKBContext xkb_context; - auto layout = xkb_context.next_layout(); + auto layout = xkb_context.next_layout(); for (; layout != nullptr; layout = xkb_context.next_layout()) { if (std::find(used_layouts.begin(), used_layouts.end(), layout->full_name) == used_layouts.end()) { @@ -155,8 +152,7 @@ auto Language::init_layouts_map(const std::vector& used_layouts) -> std::map short_name_to_number_map; for (const auto& used_layout_name : used_layouts) { auto found = layouts_map_.find(used_layout_name); - if (found == layouts_map_.end()) - continue; + if (found == layouts_map_.end()) continue; auto used_layout = &found->second; auto layouts_with_same_name_list = found_by_short_names[used_layout->short_name]; if (layouts_with_same_name_list.size() < 2) { @@ -169,10 +165,8 @@ auto Language::init_layouts_map(const std::vector& used_layouts) -> if (displayed_short_flag != static_cast(0)) { int& number = short_name_to_number_map[used_layout->short_name]; - used_layout->short_name = - used_layout->short_name + std::to_string(number); - used_layout->short_description = - used_layout->short_description + std::to_string(number); + used_layout->short_name = used_layout->short_name + std::to_string(number); + used_layout->short_description = used_layout->short_description + std::to_string(number); ++number; } } @@ -194,18 +188,19 @@ auto Language::XKBContext::next_layout() -> Layout* { return nullptr; } - auto description = std::string(rxkb_layout_get_description(xkb_layout_)); - auto name = std::string(rxkb_layout_get_name(xkb_layout_)); - auto variant_ = rxkb_layout_get_variant(xkb_layout_); + auto description = std::string(rxkb_layout_get_description(xkb_layout_)); + auto name = std::string(rxkb_layout_get_name(xkb_layout_)); + auto variant_ = rxkb_layout_get_variant(xkb_layout_); std::string variant = variant_ == nullptr ? "" : std::string(variant_); - auto short_description_ = rxkb_layout_get_brief(xkb_layout_); + auto short_description_ = rxkb_layout_get_brief(xkb_layout_); std::string short_description; if (short_description_ != nullptr) { short_description = std::string(short_description_); base_layouts_by_name_.emplace(name, xkb_layout_); } else { 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_; layout_ = new Layout{description, name, variant, short_description}; diff --git a/src/modules/sway/mode.cpp b/src/modules/sway/mode.cpp index 605271c3..7eaa523a 100644 --- a/src/modules/sway/mode.cpp +++ b/src/modules/sway/mode.cpp @@ -1,4 +1,5 @@ #include "modules/sway/mode.hpp" + #include namespace waybar::modules::sway { @@ -21,7 +22,7 @@ Mode::Mode(const std::string& id, const Json::Value& config) void Mode::onEvent(const struct Ipc::ipc_response& res) { try { std::lock_guard lock(mutex_); - auto payload = parser_.parse(res.payload); + auto payload = parser_.parse(res.payload); if (payload["change"] != "default") { if (payload["pango_markup"].asBool()) { mode_ = payload["change"].asString(); diff --git a/src/modules/sway/window.cpp b/src/modules/sway/window.cpp index 00418a16..b220de10 100644 --- a/src/modules/sway/window.cpp +++ b/src/modules/sway/window.cpp @@ -70,11 +70,11 @@ std::optional getIconName(const std::string& app_id) { } return icon_name; } catch (Glib::FileError& error) { - spdlog::warn( - "Error while loading desktop file {}: {}", desktop_file_path.value(), error.what().c_str()); + spdlog::warn("Error while loading desktop file {}: {}", desktop_file_path.value(), + error.what().c_str()); } catch (Glib::KeyFileError& error) { - spdlog::warn( - "Error while loading desktop file {}: {}", desktop_file_path.value(), error.what().c_str()); + spdlog::warn("Error while loading desktop file {}: {}", desktop_file_path.value(), + error.what().c_str()); } return {}; } @@ -114,8 +114,8 @@ auto Window::update() -> void { bar_.window.get_style_context()->remove_class("solo"); bar_.window.get_style_context()->remove_class("empty"); } - label_.set_markup(fmt::format(format_, fmt::arg("title", rewriteTitle(window_)), - fmt::arg("app_id", app_id_))); + label_.set_markup( + fmt::format(format_, fmt::arg("title", rewriteTitle(window_)), fmt::arg("app_id", app_id_))); if (tooltipEnabled()) { label_.set_tooltip_text(window_); } @@ -126,28 +126,26 @@ auto Window::update() -> void { int leafNodesInWorkspace(const Json::Value& node) { auto const& nodes = node["nodes"]; auto const& floating_nodes = node["floating_nodes"]; - if(nodes.empty() && floating_nodes.empty()) { - if(node["type"] == "workspace") + if (nodes.empty() && floating_nodes.empty()) { + if (node["type"] == "workspace") return 0; else return 1; } int sum = 0; if (!nodes.empty()) { - for(auto const& node : nodes) - sum += leafNodesInWorkspace(node); + for (auto const& node : nodes) sum += leafNodesInWorkspace(node); } if (!floating_nodes.empty()) { - for(auto const& node : floating_nodes) - sum += leafNodesInWorkspace(node); + for (auto const& node : floating_nodes) sum += leafNodesInWorkspace(node); } return sum; } std::tuple gfnWithWorkspace( - const Json::Value& nodes, std::string& output, const Json::Value& config_, - const Bar& bar_, Json::Value& parentWorkspace) { - for(auto const& node : nodes) { + const Json::Value& nodes, std::string& output, const Json::Value& config_, const Bar& bar_, + Json::Value& parentWorkspace) { + for (auto const& node : nodes) { if (node["output"].isString()) { output = node["output"].asString(); } @@ -156,25 +154,22 @@ std::tuple gfnWithWorkspace( if ((!config_["all-outputs"].asBool() && output == bar_.output->name) || config_["all-outputs"].asBool()) { 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(); - if(parentWorkspace != 0) - nb = leafNodesInWorkspace(parentWorkspace); - return {nb, - node["id"].asInt(), - Glib::Markup::escape_text(node["name"].asString()), - app_id}; + if (parentWorkspace != 0) nb = leafNodesInWorkspace(parentWorkspace); + return {nb, node["id"].asInt(), Glib::Markup::escape_text(node["name"].asString()), app_id}; } } // iterate - if(node["type"] == "workspace") - parentWorkspace = node; - auto [nb, id, name, app_id] = gfnWithWorkspace(node["nodes"], output, config_, bar_, parentWorkspace); + if (node["type"] == "workspace") parentWorkspace = node; + auto [nb, id, name, app_id] = + gfnWithWorkspace(node["nodes"], output, config_, bar_, parentWorkspace); if (id > -1 && !name.empty()) { return {nb, id, name, app_id}; } // 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()) { return {nb, id, name, app_id}; } diff --git a/src/modules/sway/workspaces.cpp b/src/modules/sway/workspaces.cpp index 074d145f..4866d869 100644 --- a/src/modules/sway/workspaces.cpp +++ b/src/modules/sway/workspaces.cpp @@ -13,7 +13,7 @@ namespace waybar::modules::sway { int Workspaces::convertWorkspaceNameToNum(std::string name) { if (isdigit(name[0])) { errno = 0; - char * endptr = NULL; + char *endptr = NULL; long long parsed_num = strtoll(name.c_str(), &endptr, 10); if (errno != 0 || parsed_num > INT32_MAX || parsed_num < 0 || endptr == name.c_str()) { return -1; @@ -65,11 +65,9 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) { try { { std::lock_guard lock(mutex_); - auto payload = parser_.parse(res.payload); + auto payload = parser_.parse(res.payload); workspaces_.clear(); - std::copy_if(payload.begin(), - payload.end(), - std::back_inserter(workspaces_), + std::copy_if(payload.begin(), payload.end(), std::back_inserter(workspaces_), [&](const auto &workspace) { return !config_["all-outputs"].asBool() ? workspace["output"].asString() == bar_.output->name @@ -78,12 +76,12 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) { // adding persistent workspaces (as per the config file) if (config_["persistent_workspaces"].isObject()) { - const Json::Value & p_workspaces = config_["persistent_workspaces"]; + const Json::Value &p_workspaces = config_["persistent_workspaces"]; const std::vector p_workspaces_names = p_workspaces.getMemberNames(); for (const std::string &p_w_name : p_workspaces_names) { const Json::Value &p_w = p_workspaces[p_w_name]; - auto it = + auto it = std::find_if(payload.begin(), payload.end(), [&p_w_name](const Json::Value &node) { return node["name"].asString() == p_w_name; }); @@ -133,10 +131,10 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) { // unnumbered workspaces behind numbered ones when computing the sort // attribute. int max_num = -1; - for (auto & workspace : workspaces_) { + for (auto &workspace : workspaces_) { max_num = std::max(workspace["num"].asInt(), max_num); } - for (auto & workspace : workspaces_) { + for (auto &workspace : workspaces_) { auto workspace_num = workspace["num"].asInt(); if (workspace_num > -1) { workspace["sort"] = workspace_num; @@ -144,13 +142,12 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) { workspace["sort"] = ++max_num; } } - std::sort(workspaces_.begin(), - workspaces_.end(), + std::sort(workspaces_.begin(), workspaces_.end(), [](const Json::Value &lhs, const Json::Value &rhs) { auto lname = lhs["name"].asString(); auto rname = rhs["name"].asString(); - int l = lhs["sort"].asInt(); - int r = rhs["sort"].asInt(); + int l = lhs["sort"].asInt(); + int r = rhs["sort"].asInt(); if (l == r) { // In case both integers are the same, lexicographical @@ -161,7 +158,6 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) { return l < r; }); - } dp.emit(); } catch (const std::exception &e) { @@ -173,9 +169,8 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) { bool Workspaces::filterButtons() { bool needReorder = false; for (auto it = buttons_.begin(); it != buttons_.end();) { - auto ws = std::find_if(workspaces_.begin(), workspaces_.end(), [it](const auto &node) { - return node["name"].asString() == it->first; - }); + auto ws = std::find_if(workspaces_.begin(), workspaces_.end(), + [it](const auto &node) { return node["name"].asString() == it->first; }); if (ws == workspaces_.end() || (!config_["all-outputs"].asBool() && (*ws)["output"].asString() != bar_.output->name)) { it = buttons_.erase(it); @@ -189,7 +184,7 @@ bool Workspaces::filterButtons() { auto Workspaces::update() -> void { std::lock_guard lock(mutex_); - bool needReorder = filterButtons(); + bool needReorder = filterButtons(); for (auto it = workspaces_.begin(); it != workspaces_.end(); ++it) { auto bit = buttons_.find((*it)["name"].asString()); if (bit == buttons_.end()) { @@ -231,10 +226,8 @@ auto Workspaces::update() -> void { std::string output = (*it)["name"].asString(); if (config_["format"].isString()) { auto format = config_["format"].asString(); - output = fmt::format(format, - fmt::arg("icon", getIcon(output, *it)), - fmt::arg("value", output), - fmt::arg("name", trimWorkspaceName(output)), + output = fmt::format(format, fmt::arg("icon", getIcon(output, *it)), + fmt::arg("value", output), fmt::arg("name", trimWorkspaceName(output)), fmt::arg("index", (*it)["num"].asString())); } if (!config_["disable-markup"].asBool()) { @@ -249,7 +242,7 @@ auto Workspaces::update() -> void { } Gtk::Button &Workspaces::addButton(const Json::Value &node) { - auto pair = buttons_.emplace(node["name"].asString(), node["name"].asString()); + auto pair = buttons_.emplace(node["name"].asString(), node["name"].asString()); auto &&button = pair.first->second; box_.pack_start(button, false, false, 0); button.set_name("sway-workspace-" + node["name"].asString()); @@ -258,22 +251,18 @@ Gtk::Button &Workspaces::addButton(const Json::Value &node) { button.signal_pressed().connect([this, node] { try { if (node["target_output"].isString()) { - ipc_.sendCmd( - IPC_COMMAND, - fmt::format(workspace_switch_cmd_ + "; move workspace to output \"{}\"; " + workspace_switch_cmd_, - "--no-auto-back-and-forth", - node["name"].asString(), - node["target_output"].asString(), - "--no-auto-back-and-forth", - node["name"].asString())); + ipc_.sendCmd(IPC_COMMAND, + fmt::format(workspace_switch_cmd_ + "; move workspace to output \"{}\"; " + + workspace_switch_cmd_, + "--no-auto-back-and-forth", node["name"].asString(), + node["target_output"].asString(), "--no-auto-back-and-forth", + node["name"].asString())); } else { - ipc_.sendCmd( - IPC_COMMAND, - fmt::format("workspace {} \"{}\"", - config_["disable-auto-back-and-forth"].asBool() - ? "--no-auto-back-and-forth" - : "", - node["name"].asString())); + ipc_.sendCmd(IPC_COMMAND, fmt::format("workspace {} \"{}\"", + config_["disable-auto-back-and-forth"].asBool() + ? "--no-auto-back-and-forth" + : "", + node["name"].asString())); } } catch (const std::exception &e) { spdlog::error("Workspaces: {}", e.what()); @@ -316,9 +305,8 @@ bool Workspaces::handleScroll(GdkEventScroll *e) { std::string name; { std::lock_guard lock(mutex_); - auto it = std::find_if(workspaces_.begin(), workspaces_.end(), [](const auto &workspace) { - return workspace["focused"].asBool(); - }); + auto it = std::find_if(workspaces_.begin(), workspaces_.end(), + [](const auto &workspace) { return workspace["focused"].asBool(); }); if (it == workspaces_.end()) { return true; } @@ -334,9 +322,7 @@ bool Workspaces::handleScroll(GdkEventScroll *e) { } } try { - ipc_.sendCmd( - IPC_COMMAND, - fmt::format(workspace_switch_cmd_, "--no-auto-back-and-forth", name)); + ipc_.sendCmd(IPC_COMMAND, fmt::format(workspace_switch_cmd_, "--no-auto-back-and-forth", name)); } catch (const std::exception &e) { spdlog::error("Workspaces: {}", e.what()); } @@ -344,7 +330,7 @@ bool Workspaces::handleScroll(GdkEventScroll *e) { } const std::string Workspaces::getCycleWorkspace(std::vector::iterator it, - bool prev) const { + bool prev) const { if (prev && it == workspaces_.begin() && !config_["disable-scroll-wraparound"].asBool()) { return (*(--workspaces_.end()))["name"].asString(); } diff --git a/src/modules/temperature.cpp b/src/modules/temperature.cpp index 627ece90..f2ba71ff 100644 --- a/src/modules/temperature.cpp +++ b/src/modules/temperature.cpp @@ -1,4 +1,5 @@ #include "modules/temperature.hpp" + #include 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()) { file_path_ = config_["hwmon-path"].asString(); } 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 { auto zone = config_["thermal-zone"].isInt() ? config_["thermal-zone"].asInt() : 0; 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"); } - if(format.empty()) { + if (format.empty()) { event_box_.hide(); return; } else { @@ -43,8 +47,7 @@ auto waybar::modules::Temperature::update() -> void { } auto max_temp = config_["critical-threshold"].isInt() ? config_["critical-threshold"].asInt() : 0; - label_.set_markup(fmt::format(format, - fmt::arg("temperatureC", temperature_c), + label_.set_markup(fmt::format(format, fmt::arg("temperatureC", temperature_c), fmt::arg("temperatureF", temperature_f), fmt::arg("temperatureK", temperature_k), fmt::arg("icon", getIcon(temperature_c, "", max_temp)))); @@ -53,10 +56,9 @@ auto waybar::modules::Temperature::update() -> void { if (config_["tooltip-format"].isString()) { tooltip_format = config_["tooltip-format"].asString(); } - label_.set_tooltip_text(fmt::format(tooltip_format, - fmt::arg("temperatureC", temperature_c), - fmt::arg("temperatureF", temperature_f), - fmt::arg("temperatureK", temperature_k))); + label_.set_tooltip_text(fmt::format(tooltip_format, fmt::arg("temperatureC", temperature_c), + fmt::arg("temperatureF", temperature_f), + fmt::arg("temperatureK", temperature_k))); } // Call parent update ALabel::update(); @@ -72,7 +74,7 @@ float waybar::modules::Temperature::getTemperature() { getline(temp, line); } temp.close(); - auto temperature_c = std::strtol(line.c_str(), nullptr, 10) / 1000.0; + auto temperature_c = std::strtol(line.c_str(), nullptr, 10) / 1000.0; return temperature_c; } diff --git a/src/modules/upower/upower.cpp b/src/modules/upower/upower.cpp index 83d3df26..41fc362b 100644 --- a/src/modules/upower/upower.cpp +++ b/src/modules/upower/upower.cpp @@ -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)); } - upowerWatcher_id = g_bus_watch_name(G_BUS_TYPE_SYSTEM, - "org.freedesktop.UPower", - G_BUS_NAME_WATCHER_FLAGS_AUTO_START, - upowerAppear, - upowerDisappear, - this, - NULL); + upowerWatcher_id = g_bus_watch_name(G_BUS_TYPE_SYSTEM, "org.freedesktop.UPower", + G_BUS_NAME_WATCHER_FLAGS_AUTO_START, upowerAppear, + upowerDisappear, this, NULL); GError* error = NULL; client = up_client_new_full(NULL, &error); @@ -87,16 +83,10 @@ UPower::UPower(const std::string& id, const Json::Value& config) if (!login1_connection) { throw std::runtime_error("Unable to connect to the SYSTEM Bus!..."); } else { - login1_id = g_dbus_connection_signal_subscribe(login1_connection, - "org.freedesktop.login1", - "org.freedesktop.login1.Manager", - "PrepareForSleep", - "/org/freedesktop/login1", - NULL, - G_DBUS_SIGNAL_FLAGS_NONE, - prepareForSleep_cb, - this, - NULL); + login1_id = g_dbus_connection_signal_subscribe( + login1_connection, "org.freedesktop.login1", "org.freedesktop.login1.Manager", + "PrepareForSleep", "/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)); @@ -284,26 +274,15 @@ auto UPower::update() -> void { // Don't update widget if the UPower service isn't running if (!upowerRunning) return; - UpDeviceKind kind; + UpDeviceKind kind; UpDeviceState state; - double percentage; - gint64 time_empty; - gint64 time_full; - gchar* icon_name; + double percentage; + gint64 time_empty; + gint64 time_full; + gchar* icon_name; - g_object_get(displayDevice, - "kind", - &kind, - "state", - &state, - "percentage", - &percentage, - "icon-name", - &icon_name, - "time-to-empty", - &time_empty, - "time-to-full", - &time_full, + g_object_get(displayDevice, "kind", &kind, "state", &state, "percentage", &percentage, + "icon-name", &icon_name, "time-to-empty", &time_empty, "time-to-full", &time_full, NULL); bool displayDeviceValid = @@ -357,9 +336,9 @@ auto UPower::update() -> void { default: break; } - std::string label_format = fmt::format(showAltText ? format_alt : format, - fmt::arg("percentage", percentString), - fmt::arg("time", time_format)); + std::string label_format = + fmt::format(showAltText ? format_alt : format, fmt::arg("percentage", percentString), + fmt::arg("time", time_format)); // Only set the label text if it doesn't only contain spaces bool onlySpaces = true; for (auto& character : label_format) { diff --git a/src/modules/upower/upower_tooltip.cpp b/src/modules/upower/upower_tooltip.cpp index 8aaba924..bec55c7e 100644 --- a/src/modules/upower/upower_tooltip.cpp +++ b/src/modules/upower/upower_tooltip.cpp @@ -35,7 +35,7 @@ uint UPowerTooltip::updateTooltip(Devices& devices) { uint deviceCount = 0; // Adds all valid devices for (auto pair : devices) { - UpDevice* device = pair.second; + UpDevice* device = pair.second; std::string objectPath = pair.first; if (!G_IS_OBJECT(device)) continue; @@ -43,23 +43,13 @@ uint UPowerTooltip::updateTooltip(Devices& devices) { Gtk::Box* box = new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, tooltipSpacing); UpDeviceKind kind; - double percentage; - gchar* native_path; - gchar* model; - gchar* icon_name; + double percentage; + gchar* native_path; + gchar* model; + gchar* icon_name; - g_object_get(device, - "kind", - &kind, - "percentage", - &percentage, - "native-path", - &native_path, - "model", - &model, - "icon-name", - &icon_name, - NULL); + g_object_get(device, "kind", &kind, "percentage", &percentage, "native-path", &native_path, + "model", &model, "icon-name", &icon_name, NULL); // Skip Line_Power and BAT0 devices if (kind == UP_DEVICE_KIND_LINE_POWER || native_path == NULL || strlen(native_path) == 0 || diff --git a/src/modules/wlr/taskbar.cpp b/src/modules/wlr/taskbar.cpp index 55c9431e..b74c44b2 100644 --- a/src/modules/wlr/taskbar.cpp +++ b/src/modules/wlr/taskbar.cpp @@ -1,10 +1,11 @@ #include "modules/wlr/taskbar.hpp" -#include "glibmm/error.h" -#include "glibmm/fileutils.h" -#include "glibmm/refptr.h" -#include "util/format.hpp" -#include "util/string.hpp" +#include +#include +#include +#include +#include +#include #include #include @@ -14,247 +15,221 @@ #include #include -#include -#include - -#include - -#include -#include - -#include - +#include "glibmm/error.h" +#include "glibmm/fileutils.h" +#include "glibmm/refptr.h" +#include "util/format.hpp" +#include "util/string.hpp" namespace waybar::modules::wlr { /* Icon loading functions */ -static std::vector search_prefix() -{ - std::vector prefixes = {""}; +static std::vector search_prefix() { + std::vector prefixes = {""}; - auto xdg_data_dirs = std::getenv("XDG_DATA_DIRS"); - if (!xdg_data_dirs) { - prefixes.emplace_back("/usr/share/"); - prefixes.emplace_back("/usr/local/share/"); - } else { - std::string xdg_data_dirs_str(xdg_data_dirs); - size_t start = 0, end = 0; + auto xdg_data_dirs = std::getenv("XDG_DATA_DIRS"); + if (!xdg_data_dirs) { + prefixes.emplace_back("/usr/share/"); + prefixes.emplace_back("/usr/local/share/"); + } else { + std::string xdg_data_dirs_str(xdg_data_dirs); + size_t start = 0, end = 0; - do { - end = xdg_data_dirs_str.find(':', start); - auto p = xdg_data_dirs_str.substr(start, end-start); - prefixes.push_back(trim(p) + "/"); + do { + end = xdg_data_dirs_str.find(':', start); + auto p = xdg_data_dirs_str.substr(start, end - start); + prefixes.push_back(trim(p) + "/"); - start = end == std::string::npos ? end : end + 1; - } while(end != std::string::npos); - } + start = end == std::string::npos ? end : end + 1; + } while (end != std::string::npos); + } - std::string home_dir = std::getenv("HOME"); - prefixes.push_back(home_dir + "/.local/share/"); + std::string home_dir = std::getenv("HOME"); + prefixes.push_back(home_dir + "/.local/share/"); - for (auto& p : prefixes) - spdlog::debug("Using 'desktop' search path prefix: {}", p); + for (auto &p : prefixes) spdlog::debug("Using 'desktop' search path prefix: {}", p); - return prefixes; + return prefixes; } -static Glib::RefPtr load_icon_from_file(std::string icon_path, int size) -{ - try { - auto pb = Gdk::Pixbuf::create_from_file(icon_path, size, size); - return pb; - } catch(...) { - return {}; - } +static Glib::RefPtr load_icon_from_file(std::string icon_path, int size) { + try { + auto pb = Gdk::Pixbuf::create_from_file(icon_path, size, size); + return pb; + } catch (...) { + return {}; + } } -static Glib::RefPtr get_app_info_by_name(const std::string& app_id) -{ - static std::vector prefixes = search_prefix(); +static Glib::RefPtr get_app_info_by_name(const std::string &app_id) { + static std::vector prefixes = search_prefix(); - std::vector app_folders = { - "", - "applications/", - "applications/kde/", - "applications/org.kde." - }; + std::vector app_folders = {"", "applications/", "applications/kde/", + "applications/org.kde."}; - std::vector suffixes = { - "", - ".desktop" - }; + std::vector suffixes = {"", ".desktop"}; - for (auto& prefix : prefixes) { - for (auto& folder : app_folders) { - for (auto& suffix : suffixes) { - auto app_info_ = Gio::DesktopAppInfo::create_from_filename(prefix + folder + app_id + suffix); - if (!app_info_) { - continue; - } - - return app_info_; - } - } - } - - return {}; -} - -Glib::RefPtr get_desktop_app_info(const std::string &app_id) -{ - auto app_info = get_app_info_by_name(app_id); - if (app_info) { - return app_info; - } - - std::string desktop_file = ""; - - gchar*** desktop_list = g_desktop_app_info_search(app_id.c_str()); - if (desktop_list != nullptr && desktop_list[0] != nullptr) { - for (size_t i=0; desktop_list[0][i]; i++) { - if (desktop_file == "") { - desktop_file = desktop_list[0][i]; - } else { - auto tmp_info = Gio::DesktopAppInfo::create(desktop_list[0][i]); - auto startup_class = tmp_info->get_startup_wm_class(); - - if (startup_class == app_id) { - desktop_file = desktop_list[0][i]; - break; - } - } + for (auto &prefix : prefixes) { + for (auto &folder : app_folders) { + for (auto &suffix : suffixes) { + auto app_info_ = + Gio::DesktopAppInfo::create_from_filename(prefix + folder + app_id + suffix); + if (!app_info_) { + continue; } - g_strfreev(desktop_list[0]); + + return app_info_; + } } - g_free(desktop_list); + } - return get_app_info_by_name(desktop_file); + return {}; } -void Task::set_app_info_from_app_id_list(const std::string& app_id_list) { - std::string app_id; - std::istringstream stream(app_id_list); +Glib::RefPtr get_desktop_app_info(const std::string &app_id) { + auto app_info = get_app_info_by_name(app_id); + if (app_info) { + return app_info; + } - /* 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 */ - while (stream >> app_id) - { - app_info_ = get_desktop_app_info(app_id); - if (app_info_) { - return; - } + std::string desktop_file = ""; - auto lower_app_id = app_id; - std::transform(lower_app_id.begin(), lower_app_id.end(), lower_app_id.begin(), - [](char c){ return std::tolower(c); }); - app_info_ = get_desktop_app_info(lower_app_id); - if (app_info_) { - return; - } - - size_t start = 0, end = app_id.size(); - start = app_id.rfind(".", end); - std::string app_name = app_id.substr(start+1, app_id.size()); - app_info_ = get_desktop_app_info(app_name); - if (app_info_) { - return; - } + gchar ***desktop_list = g_desktop_app_info_search(app_id.c_str()); + if (desktop_list != nullptr && desktop_list[0] != nullptr) { + for (size_t i = 0; desktop_list[0][i]; i++) { + if (desktop_file == "") { + desktop_file = desktop_list[0][i]; + } else { + auto tmp_info = Gio::DesktopAppInfo::create(desktop_list[0][i]); + auto startup_class = tmp_info->get_startup_wm_class(); - start = app_id.find("-"); - app_name = app_id.substr(0, start); - app_info_ = get_desktop_app_info(app_name); - } + if (startup_class == app_id) { + desktop_file = desktop_list[0][i]; + break; + } + } + } + g_strfreev(desktop_list[0]); + } + g_free(desktop_list); + + return get_app_info_by_name(desktop_file); } -static std::string get_icon_name_from_icon_theme(const Glib::RefPtr& icon_theme, - const std::string &app_id) -{ - if (icon_theme->lookup_icon(app_id, 24)) - return app_id; +void Task::set_app_info_from_app_id_list(const std::string &app_id_list) { + std::string app_id; + std::istringstream stream(app_id_list); - return ""; + /* 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 */ + while (stream >> app_id) { + app_info_ = get_desktop_app_info(app_id); + if (app_info_) { + return; + } + + auto lower_app_id = app_id; + std::transform(lower_app_id.begin(), lower_app_id.end(), lower_app_id.begin(), + [](char c) { return std::tolower(c); }); + app_info_ = get_desktop_app_info(lower_app_id); + if (app_info_) { + return; + } + + size_t start = 0, end = app_id.size(); + start = app_id.rfind(".", end); + std::string app_name = app_id.substr(start + 1, app_id.size()); + app_info_ = get_desktop_app_info(app_name); + if (app_info_) { + return; + } + + start = app_id.find("-"); + app_name = app_id.substr(0, start); + app_info_ = get_desktop_app_info(app_name); + } } -bool Task::image_load_icon(Gtk::Image& image, const Glib::RefPtr& icon_theme, Glib::RefPtr app_info, int size) -{ - std::string ret_icon_name = "unknown"; - if (app_info) { - std::string icon_name = get_icon_name_from_icon_theme(icon_theme, app_info->get_startup_wm_class()); - if (!icon_name.empty()) { - ret_icon_name = icon_name; - } else { - if (app_info->get_icon()) { - ret_icon_name = app_info->get_icon()->to_string(); - } - } - } +static std::string get_icon_name_from_icon_theme(const Glib::RefPtr &icon_theme, + const std::string &app_id) { + if (icon_theme->lookup_icon(app_id, 24)) return app_id; - Glib::RefPtr pixbuf; + return ""; +} - try { - pixbuf = icon_theme->load_icon(ret_icon_name, size, Gtk::ICON_LOOKUP_FORCE_SIZE); - } catch(...) { - if (Glib::file_test(ret_icon_name, Glib::FILE_TEST_EXISTS)) - pixbuf = load_icon_from_file(ret_icon_name, size); - else - pixbuf = {}; - } +bool Task::image_load_icon(Gtk::Image &image, const Glib::RefPtr &icon_theme, + Glib::RefPtr app_info, int size) { + std::string ret_icon_name = "unknown"; + if (app_info) { + std::string icon_name = + get_icon_name_from_icon_theme(icon_theme, app_info->get_startup_wm_class()); + if (!icon_name.empty()) { + ret_icon_name = icon_name; + } else { + if (app_info->get_icon()) { + ret_icon_name = app_info->get_icon()->to_string(); + } + } + } - if (pixbuf) { - image.set(pixbuf); - return true; - } + Glib::RefPtr pixbuf; - return false; + try { + pixbuf = icon_theme->load_icon(ret_icon_name, size, Gtk::ICON_LOOKUP_FORCE_SIZE); + } catch (...) { + if (Glib::file_test(ret_icon_name, Glib::FILE_TEST_EXISTS)) + pixbuf = load_icon_from_file(ret_icon_name, size); + else + pixbuf = {}; + } + + if (pixbuf) { + image.set(pixbuf); + return true; + } + + return false; } /* Task class implementation */ uint32_t Task::global_id = 0; static void tl_handle_title(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle, - const char *title) -{ - return static_cast(data)->handle_title(title); + const char *title) { + return static_cast(data)->handle_title(title); } static void tl_handle_app_id(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle, - const char *app_id) -{ - return static_cast(data)->handle_app_id(app_id); + const char *app_id) { + return static_cast(data)->handle_app_id(app_id); } static void tl_handle_output_enter(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle, - struct wl_output *output) -{ - return static_cast(data)->handle_output_enter(output); + struct wl_output *output) { + return static_cast(data)->handle_output_enter(output); } static void tl_handle_output_leave(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle, - struct wl_output *output) -{ - return static_cast(data)->handle_output_leave(output); + struct wl_output *output) { + return static_cast(data)->handle_output_leave(output); } static void tl_handle_state(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle, - struct wl_array *state) -{ - return static_cast(data)->handle_state(state); + struct wl_array *state) { + return static_cast(data)->handle_state(state); } -static void tl_handle_done(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle) -{ - return static_cast(data)->handle_done(); +static void tl_handle_done(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle) { + return static_cast(data)->handle_done(); } static void tl_handle_parent(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle, - struct zwlr_foreign_toplevel_handle_v1 *parent) -{ - /* This is explicitly left blank */ + struct zwlr_foreign_toplevel_handle_v1 *parent) { + /* This is explicitly left blank */ } -static void tl_handle_closed(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle) -{ - return static_cast(data)->handle_closed(); +static void tl_handle_closed(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle) { + return static_cast(data)->handle_closed(); } static const struct zwlr_foreign_toplevel_handle_v1_listener toplevel_handle_impl = { @@ -269,531 +244,477 @@ static const struct zwlr_foreign_toplevel_handle_v1_listener toplevel_handle_imp }; Task::Task(const waybar::Bar &bar, const Json::Value &config, Taskbar *tbar, - struct zwlr_foreign_toplevel_handle_v1 *tl_handle, struct wl_seat *seat) : - bar_{bar}, config_{config}, tbar_{tbar}, handle_{tl_handle}, seat_{seat}, - id_{global_id++}, - content_{bar.vertical ? Gtk::ORIENTATION_VERTICAL : Gtk::ORIENTATION_HORIZONTAL, 0} -{ - zwlr_foreign_toplevel_handle_v1_add_listener(handle_, &toplevel_handle_impl, this); + struct zwlr_foreign_toplevel_handle_v1 *tl_handle, struct wl_seat *seat) + : bar_{bar}, + config_{config}, + tbar_{tbar}, + handle_{tl_handle}, + seat_{seat}, + id_{global_id++}, + content_{bar.vertical ? Gtk::ORIENTATION_VERTICAL : Gtk::ORIENTATION_HORIZONTAL, 0} { + zwlr_foreign_toplevel_handle_v1_add_listener(handle_, &toplevel_handle_impl, this); - button_.set_relief(Gtk::RELIEF_NONE); + button_.set_relief(Gtk::RELIEF_NONE); - content_.add(text_before_); - content_.add(icon_); - content_.add(text_after_); + content_.add(text_before_); + content_.add(icon_); + content_.add(text_after_); - content_.show(); - button_.add(content_); + content_.show(); + button_.add(content_); - format_before_.clear(); - format_after_.clear(); + format_before_.clear(); + format_after_.clear(); - if (config_["format"].isString()) { - /* The user defined a format string, use it */ - auto format = config_["format"].asString(); - if (format.find("{name}") != std::string::npos) { - with_name_ = true; - } + if (config_["format"].isString()) { + /* The user defined a format string, use it */ + auto format = config_["format"].asString(); + if (format.find("{name}") != std::string::npos) { + with_name_ = true; + } - auto icon_pos = format.find("{icon}"); - if (icon_pos == 0) { - with_icon_ = true; - format_after_ = format.substr(6); - } else if (icon_pos == std::string::npos) { - format_before_ = format; - } else { - with_icon_ = true; - format_before_ = format.substr(0, icon_pos); - format_after_ = format.substr(icon_pos + 6); - } + auto icon_pos = format.find("{icon}"); + if (icon_pos == 0) { + with_icon_ = true; + format_after_ = format.substr(6); + } else if (icon_pos == std::string::npos) { + format_before_ = format; } else { - /* The default is to only show the icon */ - with_icon_ = true; + with_icon_ = true; + format_before_ = format.substr(0, icon_pos); + format_after_ = format.substr(icon_pos + 6); } + } else { + /* The default is to only show the icon */ + with_icon_ = true; + } - /* Strip spaces at the beginning and end of the format strings */ - format_tooltip_.clear(); - if (!config_["tooltip"].isBool() || config_["tooltip"].asBool()) { - if (config_["tooltip-format"].isString()) - format_tooltip_ = config_["tooltip-format"].asString(); - else - format_tooltip_ = "{title}"; - } - - /* Handle click events if configured */ - if (config_["on-click"].isString() || config_["on-click-middle"].isString() - || config_["on-click-right"].isString()) { - button_.add_events(Gdk::BUTTON_PRESS_MASK); - button_.signal_button_press_event().connect( - sigc::mem_fun(*this, &Task::handle_clicked), false); - } -} - -Task::~Task() -{ - if (handle_) { - zwlr_foreign_toplevel_handle_v1_destroy(handle_); - handle_ = nullptr; - } - if (button_visible_) { - tbar_->remove_button(button_); - button_visible_ = false; - } -} - -std::string Task::repr() const -{ - std::stringstream ss; - ss << "Task (" << id_ << ") " << title_ << " [" << app_id_ << "] <" - << (active() ? "A" : "a") - << (maximized() ? "M" : "m") - << (minimized() ? "I" : "i") - << (fullscreen() ? "F" : "f") - << ">"; - - return ss.str(); -} - -std::string Task::state_string(bool shortened) const -{ - std::stringstream ss; - if (shortened) - ss << (minimized() ? "m" : "") << (maximized() ? "M" : "") - << (active() ? "A" : "") << (fullscreen() ? "F" : ""); + /* Strip spaces at the beginning and end of the format strings */ + format_tooltip_.clear(); + if (!config_["tooltip"].isBool() || config_["tooltip"].asBool()) { + if (config_["tooltip-format"].isString()) + format_tooltip_ = config_["tooltip-format"].asString(); else - ss << (minimized() ? "minimized " : "") << (maximized() ? "maximized " : "") - << (active() ? "active " : "") << (fullscreen() ? "fullscreen " : ""); + format_tooltip_ = "{title}"; + } - std::string res = ss.str(); - if (shortened || res.empty()) - return res; - else - return res.substr(0, res.size() - 1); + /* Handle click events if configured */ + if (config_["on-click"].isString() || config_["on-click-middle"].isString() || + config_["on-click-right"].isString()) { + button_.add_events(Gdk::BUTTON_PRESS_MASK); + button_.signal_button_press_event().connect(sigc::mem_fun(*this, &Task::handle_clicked), false); + } } -void Task::handle_title(const char *title) -{ - title_ = title; - hide_if_ignored(); -} - -void Task::hide_if_ignored() -{ - if (tbar_->ignore_list().count(app_id_) || tbar_->ignore_list().count(title_)) { - ignored_ = true; - if (button_visible_) { - auto output = gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj()); - handle_output_leave(output); - } - } else { - bool is_was_ignored = ignored_; - ignored_ = false; - if (is_was_ignored) { - auto output = gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj()); - handle_output_enter(output); - } - } -} - -void Task::handle_app_id(const char *app_id) -{ - app_id_ = app_id; - hide_if_ignored(); - - auto ids_replace_map = tbar_->app_ids_replace_map(); - if (ids_replace_map.count(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)); - app_id_ = replaced_id; - } - - if (!with_icon_ && !with_name_) { - return; - } - - set_app_info_from_app_id_list(app_id_); - name_ = app_info_ ? app_info_->get_display_name() : app_id; - - if (!with_icon_) { - return; - } - - int icon_size = config_["icon-size"].isInt() ? config_["icon-size"].asInt() : 16; - bool found = false; - for (auto& icon_theme : tbar_->icon_themes()) { - if (image_load_icon(icon_, icon_theme, app_info_, icon_size)) { - found = true; - break; - } - } - - if (found) - icon_.show(); - else - spdlog::debug("Couldn't find icon for {}", app_id_); -} - -void Task::handle_output_enter(struct wl_output *output) -{ - if (ignored_) { - spdlog::debug("{} is ignored", repr()); - return; - } - - spdlog::debug("{} entered output {}", repr(), (void*)output); - - if (!button_visible_ && (tbar_->all_outputs() || tbar_->show_output(output))) { - /* The task entered the output of the current bar make the button visible */ - tbar_->add_button(button_); - button_.show(); - button_visible_ = true; - spdlog::debug("{} now visible on {}", repr(), bar_.output->name); - } -} - -void Task::handle_output_leave(struct wl_output *output) -{ - spdlog::debug("{} left output {}", repr(), (void*)output); - - if (button_visible_ && !tbar_->all_outputs() && tbar_->show_output(output)) { - /* The task left the output of the current bar, make the button invisible */ - tbar_->remove_button(button_); - button_.hide(); - button_visible_ = false; - spdlog::debug("{} now invisible on {}", repr(), bar_.output->name); - } -} - -void Task::handle_state(struct wl_array *state) -{ - state_ = 0; - size_t size = state->size / sizeof(uint32_t); - for (size_t i = 0; i < size; ++i) { - auto entry = static_cast(state->data)[i]; - if (entry == ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_MAXIMIZED) - state_ |= MAXIMIZED; - if (entry == ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_MINIMIZED) - state_ |= MINIMIZED; - if (entry == ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_ACTIVATED) - state_ |= ACTIVE; - if (entry == ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_FULLSCREEN) - state_ |= FULLSCREEN; - } -} - -void Task::handle_done() -{ - spdlog::debug("{} changed", repr()); - - if (state_ & MAXIMIZED) { - button_.get_style_context()->add_class("maximized"); - } else if (!(state_ & MAXIMIZED)) { - button_.get_style_context()->remove_class("maximized"); - } - - if (state_ & MINIMIZED) { - button_.get_style_context()->add_class("minimized"); - } else if (!(state_ & MINIMIZED)) { - button_.get_style_context()->remove_class("minimized"); - } - - if (state_ & ACTIVE) { - button_.get_style_context()->add_class("active"); - } else if (!(state_ & ACTIVE)) { - button_.get_style_context()->remove_class("active"); - } - - if (state_ & FULLSCREEN) { - button_.get_style_context()->add_class("fullscreen"); - } else if (!(state_ & FULLSCREEN)) { - button_.get_style_context()->remove_class("fullscreen"); - } - - if (config_["active-first"].isBool() && config_["active-first"].asBool() && active()) - tbar_->move_button(button_, 0); - - tbar_->dp.emit(); -} - -void Task::handle_closed() -{ - spdlog::debug("{} closed", repr()); +Task::~Task() { + if (handle_) { zwlr_foreign_toplevel_handle_v1_destroy(handle_); handle_ = nullptr; + } + if (button_visible_) { + tbar_->remove_button(button_); + button_visible_ = false; + } +} + +std::string Task::repr() const { + std::stringstream ss; + ss << "Task (" << id_ << ") " << title_ << " [" << app_id_ << "] <" << (active() ? "A" : "a") + << (maximized() ? "M" : "m") << (minimized() ? "I" : "i") << (fullscreen() ? "F" : "f") << ">"; + + return ss.str(); +} + +std::string Task::state_string(bool shortened) const { + std::stringstream ss; + if (shortened) + ss << (minimized() ? "m" : "") << (maximized() ? "M" : "") << (active() ? "A" : "") + << (fullscreen() ? "F" : ""); + else + ss << (minimized() ? "minimized " : "") << (maximized() ? "maximized " : "") + << (active() ? "active " : "") << (fullscreen() ? "fullscreen " : ""); + + std::string res = ss.str(); + if (shortened || res.empty()) + return res; + else + return res.substr(0, res.size() - 1); +} + +void Task::handle_title(const char *title) { + title_ = title; + hide_if_ignored(); +} + +void Task::hide_if_ignored() { + if (tbar_->ignore_list().count(app_id_) || tbar_->ignore_list().count(title_)) { + ignored_ = true; if (button_visible_) { - tbar_->remove_button(button_); - button_visible_ = false; + auto output = gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj()); + handle_output_leave(output); } - tbar_->remove_task(id_); + } else { + bool is_was_ignored = ignored_; + ignored_ = false; + if (is_was_ignored) { + auto output = gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj()); + handle_output_enter(output); + } + } } -bool Task::handle_clicked(GdkEventButton *bt) -{ - std::string action; - if (config_["on-click"].isString() && bt->button == 1) - action = config_["on-click"].asString(); - else if (config_["on-click-middle"].isString() && bt->button == 2) - action = config_["on-click-middle"].asString(); - else if (config_["on-click-right"].isString() && bt->button == 3) - action = config_["on-click-right"].asString(); +void Task::handle_app_id(const char *app_id) { + app_id_ = app_id; + hide_if_ignored(); - if (action.empty()) - return true; - else if (action == "activate") - activate(); - else if (action == "minimize") - minimize(!minimized()); - else if (action == "minimize-raise"){ - if (minimized()) - minimize(false); - else if (active()) - minimize(true); - else - activate(); + auto ids_replace_map = tbar_->app_ids_replace_map(); + if (ids_replace_map.count(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)); + app_id_ = replaced_id; + } + + if (!with_icon_ && !with_name_) { + return; + } + + set_app_info_from_app_id_list(app_id_); + name_ = app_info_ ? app_info_->get_display_name() : app_id; + + if (!with_icon_) { + return; + } + + int icon_size = config_["icon-size"].isInt() ? config_["icon-size"].asInt() : 16; + bool found = false; + for (auto &icon_theme : tbar_->icon_themes()) { + if (image_load_icon(icon_, icon_theme, app_info_, icon_size)) { + found = true; + break; } - else if (action == "maximize") - maximize(!maximized()); - else if (action == "fullscreen") - fullscreen(!fullscreen()); - else if (action == "close") - close(); - else - spdlog::warn("Unknown action {}", action); + } + if (found) + icon_.show(); + else + spdlog::debug("Couldn't find icon for {}", app_id_); +} + +void Task::handle_output_enter(struct wl_output *output) { + if (ignored_) { + spdlog::debug("{} is ignored", repr()); + return; + } + + spdlog::debug("{} entered output {}", repr(), (void *)output); + + if (!button_visible_ && (tbar_->all_outputs() || tbar_->show_output(output))) { + /* The task entered the output of the current bar make the button visible */ + tbar_->add_button(button_); + button_.show(); + button_visible_ = true; + spdlog::debug("{} now visible on {}", repr(), bar_.output->name); + } +} + +void Task::handle_output_leave(struct wl_output *output) { + spdlog::debug("{} left output {}", repr(), (void *)output); + + if (button_visible_ && !tbar_->all_outputs() && tbar_->show_output(output)) { + /* The task left the output of the current bar, make the button invisible */ + tbar_->remove_button(button_); + button_.hide(); + button_visible_ = false; + spdlog::debug("{} now invisible on {}", repr(), bar_.output->name); + } +} + +void Task::handle_state(struct wl_array *state) { + state_ = 0; + size_t size = state->size / sizeof(uint32_t); + for (size_t i = 0; i < size; ++i) { + auto entry = static_cast(state->data)[i]; + if (entry == ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_MAXIMIZED) state_ |= MAXIMIZED; + if (entry == ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_MINIMIZED) state_ |= MINIMIZED; + if (entry == ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_ACTIVATED) state_ |= ACTIVE; + if (entry == ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_FULLSCREEN) state_ |= FULLSCREEN; + } +} + +void Task::handle_done() { + spdlog::debug("{} changed", repr()); + + if (state_ & MAXIMIZED) { + button_.get_style_context()->add_class("maximized"); + } else if (!(state_ & MAXIMIZED)) { + button_.get_style_context()->remove_class("maximized"); + } + + if (state_ & MINIMIZED) { + button_.get_style_context()->add_class("minimized"); + } else if (!(state_ & MINIMIZED)) { + button_.get_style_context()->remove_class("minimized"); + } + + if (state_ & ACTIVE) { + button_.get_style_context()->add_class("active"); + } else if (!(state_ & ACTIVE)) { + button_.get_style_context()->remove_class("active"); + } + + if (state_ & FULLSCREEN) { + button_.get_style_context()->add_class("fullscreen"); + } else if (!(state_ & FULLSCREEN)) { + button_.get_style_context()->remove_class("fullscreen"); + } + + if (config_["active-first"].isBool() && config_["active-first"].asBool() && active()) + tbar_->move_button(button_, 0); + + tbar_->dp.emit(); +} + +void Task::handle_closed() { + spdlog::debug("{} closed", repr()); + zwlr_foreign_toplevel_handle_v1_destroy(handle_); + handle_ = nullptr; + if (button_visible_) { + tbar_->remove_button(button_); + button_visible_ = false; + } + tbar_->remove_task(id_); +} + +bool Task::handle_clicked(GdkEventButton *bt) { + std::string action; + if (config_["on-click"].isString() && bt->button == 1) + action = config_["on-click"].asString(); + else if (config_["on-click-middle"].isString() && bt->button == 2) + action = config_["on-click-middle"].asString(); + else if (config_["on-click-right"].isString() && bt->button == 3) + action = config_["on-click-right"].asString(); + + if (action.empty()) return true; -} - -bool Task::operator==(const Task &o) const -{ - return o.id_ == id_; -} - -bool Task::operator!=(const Task &o) const -{ - return o.id_ != id_; -} - -void Task::update() -{ - bool markup = config_["markup"].isBool() ? config_["markup"].asBool() : false; - std::string title = title_; - std::string name = name_; - std::string app_id = app_id_; - if (markup) { - title = Glib::Markup::escape_text(title); - name = Glib::Markup::escape_text(name); - app_id = Glib::Markup::escape_text(app_id); - } - if (!format_before_.empty()) { - auto txt = fmt::format(format_before_, - fmt::arg("title", title), - fmt::arg("name", name), - fmt::arg("app_id", app_id), - fmt::arg("state", state_string()), - fmt::arg("short_state", state_string(true)) - ); - if (markup) - text_before_.set_markup(txt); - else - text_before_.set_label(txt); - text_before_.show(); - } - if (!format_after_.empty()) { - auto txt = fmt::format(format_after_, - fmt::arg("title", title), - fmt::arg("name", name), - fmt::arg("app_id", app_id), - fmt::arg("state", state_string()), - fmt::arg("short_state", state_string(true)) - ); - if (markup) - text_after_.set_markup(txt); - else - text_after_.set_label(txt); - text_after_.show(); - } - - if (!format_tooltip_.empty()) { - auto txt = fmt::format(format_tooltip_, - fmt::arg("title", title), - fmt::arg("name", name), - fmt::arg("app_id", app_id), - fmt::arg("state", state_string()), - fmt::arg("short_state", state_string(true)) - ); - if (markup) - button_.set_tooltip_markup(txt); - else - button_.set_tooltip_text(txt); - } -} - -void Task::maximize(bool set) -{ - if (set) - zwlr_foreign_toplevel_handle_v1_set_maximized(handle_); + else if (action == "activate") + activate(); + else if (action == "minimize") + minimize(!minimized()); + else if (action == "minimize-raise") { + if (minimized()) + minimize(false); + else if (active()) + minimize(true); else - zwlr_foreign_toplevel_handle_v1_unset_maximized(handle_); + activate(); + } else if (action == "maximize") + maximize(!maximized()); + else if (action == "fullscreen") + fullscreen(!fullscreen()); + else if (action == "close") + close(); + else + spdlog::warn("Unknown action {}", action); + + return true; } -void Task::minimize(bool set) -{ - if (set) - zwlr_foreign_toplevel_handle_v1_set_minimized(handle_); +bool Task::operator==(const Task &o) const { return o.id_ == id_; } + +bool Task::operator!=(const Task &o) const { return o.id_ != id_; } + +void Task::update() { + bool markup = config_["markup"].isBool() ? config_["markup"].asBool() : false; + std::string title = title_; + std::string name = name_; + std::string app_id = app_id_; + if (markup) { + title = Glib::Markup::escape_text(title); + name = Glib::Markup::escape_text(name); + app_id = Glib::Markup::escape_text(app_id); + } + if (!format_before_.empty()) { + auto txt = fmt::format(format_before_, fmt::arg("title", title), fmt::arg("name", name), + fmt::arg("app_id", app_id), fmt::arg("state", state_string()), + fmt::arg("short_state", state_string(true))); + if (markup) + text_before_.set_markup(txt); else - zwlr_foreign_toplevel_handle_v1_unset_minimized(handle_); -} - -void Task::activate() -{ - zwlr_foreign_toplevel_handle_v1_activate(handle_, seat_); -} - -void Task::fullscreen(bool set) -{ - if (zwlr_foreign_toplevel_handle_v1_get_version(handle_) < ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_SET_FULLSCREEN_SINCE_VERSION) { - spdlog::warn("Foreign toplevel manager server does not support for set/unset fullscreen."); - return; - } - - if (set) - zwlr_foreign_toplevel_handle_v1_set_fullscreen(handle_, nullptr); + text_before_.set_label(txt); + text_before_.show(); + } + if (!format_after_.empty()) { + auto txt = fmt::format(format_after_, fmt::arg("title", title), fmt::arg("name", name), + fmt::arg("app_id", app_id), fmt::arg("state", state_string()), + fmt::arg("short_state", state_string(true))); + if (markup) + text_after_.set_markup(txt); else - zwlr_foreign_toplevel_handle_v1_unset_fullscreen(handle_); + text_after_.set_label(txt); + text_after_.show(); + } + + if (!format_tooltip_.empty()) { + auto txt = fmt::format(format_tooltip_, fmt::arg("title", title), fmt::arg("name", name), + fmt::arg("app_id", app_id), fmt::arg("state", state_string()), + fmt::arg("short_state", state_string(true))); + if (markup) + button_.set_tooltip_markup(txt); + else + button_.set_tooltip_text(txt); + } } -void Task::close() -{ - zwlr_foreign_toplevel_handle_v1_close(handle_); +void Task::maximize(bool set) { + if (set) + zwlr_foreign_toplevel_handle_v1_set_maximized(handle_); + else + zwlr_foreign_toplevel_handle_v1_unset_maximized(handle_); } +void Task::minimize(bool set) { + if (set) + zwlr_foreign_toplevel_handle_v1_set_minimized(handle_); + else + zwlr_foreign_toplevel_handle_v1_unset_minimized(handle_); +} + +void Task::activate() { zwlr_foreign_toplevel_handle_v1_activate(handle_, seat_); } + +void Task::fullscreen(bool set) { + if (zwlr_foreign_toplevel_handle_v1_get_version(handle_) < + ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_SET_FULLSCREEN_SINCE_VERSION) { + spdlog::warn("Foreign toplevel manager server does not support for set/unset fullscreen."); + return; + } + + if (set) + zwlr_foreign_toplevel_handle_v1_set_fullscreen(handle_, nullptr); + else + zwlr_foreign_toplevel_handle_v1_unset_fullscreen(handle_); +} + +void Task::close() { zwlr_foreign_toplevel_handle_v1_close(handle_); } /* Taskbar class implementation */ static void handle_global(void *data, struct wl_registry *registry, uint32_t name, - const char *interface, uint32_t version) -{ - if (std::strcmp(interface, zwlr_foreign_toplevel_manager_v1_interface.name) == 0) { - static_cast(data)->register_manager(registry, name, version); - } else if (std::strcmp(interface, wl_seat_interface.name) == 0) { - static_cast(data)->register_seat(registry, name, version); - } + const char *interface, uint32_t version) { + if (std::strcmp(interface, zwlr_foreign_toplevel_manager_v1_interface.name) == 0) { + static_cast(data)->register_manager(registry, name, version); + } else if (std::strcmp(interface, wl_seat_interface.name) == 0) { + static_cast(data)->register_seat(registry, name, version); + } } -static void handle_global_remove(void *data, struct wl_registry *registry, uint32_t name) -{ - /* Nothing to do here */ +static void handle_global_remove(void *data, struct wl_registry *registry, uint32_t name) { + /* Nothing to do here */ } -static const wl_registry_listener registry_listener_impl = { - .global = handle_global, - .global_remove = handle_global_remove -}; +static const wl_registry_listener registry_listener_impl = {.global = handle_global, + .global_remove = handle_global_remove}; Taskbar::Taskbar(const std::string &id, const waybar::Bar &bar, const Json::Value &config) : waybar::AModule(config, "taskbar", id, false, false), bar_(bar), box_{bar.vertical ? Gtk::ORIENTATION_VERTICAL : Gtk::ORIENTATION_HORIZONTAL, 0}, - manager_{nullptr}, seat_{nullptr} -{ - box_.set_name("taskbar"); - if (!id.empty()) { - box_.get_style_context()->add_class(id); + manager_{nullptr}, + seat_{nullptr} { + box_.set_name("taskbar"); + if (!id.empty()) { + box_.get_style_context()->add_class(id); + } + event_box_.add(box_); + + struct wl_display *display = Client::inst()->wl_display; + struct wl_registry *registry = wl_display_get_registry(display); + + wl_registry_add_listener(registry, ®istry_listener_impl, this); + wl_display_roundtrip(display); + + if (!manager_) { + spdlog::error("Failed to register as toplevel manager"); + return; + } + if (!seat_) { + spdlog::error("Failed to get wayland seat"); + return; + } + + /* Get the configured icon theme if specified */ + if (config_["icon-theme"].isArray()) { + for (auto &c : config_["icon-theme"]) { + auto it_name = c.asString(); + + auto it = Gtk::IconTheme::create(); + it->set_custom_theme(it_name); + spdlog::debug("Use custom icon theme: {}", it_name); + + icon_themes_.push_back(it); } - event_box_.add(box_); + } else if (config_["icon-theme"].isString()) { + auto it_name = config_["icon-theme"].asString(); + auto it = Gtk::IconTheme::create(); + it->set_custom_theme(it_name); + spdlog::debug("Use custom icon theme: {}", it_name); + + icon_themes_.push_back(it); + } + + // Load ignore-list + if (config_["ignore-list"].isArray()) { + for (auto &app_name : config_["ignore-list"]) { + ignore_list_.emplace(app_name.asString()); + } + } + + // Load app_id remappings + if (config_["app_ids-mapping"].isObject()) { + const Json::Value &mapping = config_["app_ids-mapping"]; + const std::vector app_ids = config_["app_ids-mapping"].getMemberNames(); + for (auto &app_id : app_ids) { + app_ids_replace_map_.emplace(app_id, mapping[app_id].asString()); + } + } + + icon_themes_.push_back(Gtk::IconTheme::get_default()); +} + +Taskbar::~Taskbar() { + if (manager_) { struct wl_display *display = Client::inst()->wl_display; - struct wl_registry *registry = wl_display_get_registry(display); - - wl_registry_add_listener(registry, ®istry_listener_impl, this); + /* + * Send `stop` request and wait for one roundtrip. + * This is not quite correct as the protocol encourages us to wait for the .finished event, + * but it should work with wlroots foreign toplevel manager implementation. + */ + zwlr_foreign_toplevel_manager_v1_stop(manager_); wl_display_roundtrip(display); - if (!manager_) { - spdlog::error("Failed to register as toplevel manager"); - return; - } - if (!seat_) { - spdlog::error("Failed to get wayland seat"); - return; - } - - /* Get the configured icon theme if specified */ - if (config_["icon-theme"].isArray()) { - for (auto& c : config_["icon-theme"]) { - auto it_name = c.asString(); - - auto it = Gtk::IconTheme::create(); - it->set_custom_theme(it_name); - spdlog::debug("Use custom icon theme: {}", it_name); - - icon_themes_.push_back(it); - } - } else if (config_["icon-theme"].isString()) { - auto it_name = config_["icon-theme"].asString(); - - auto it = Gtk::IconTheme::create(); - it->set_custom_theme(it_name); - spdlog::debug("Use custom icon theme: {}", it_name); - - icon_themes_.push_back(it); - } - - // Load ignore-list - if (config_["ignore-list"].isArray()) { - for (auto& app_name : config_["ignore-list"]) { - ignore_list_.emplace(app_name.asString()); - } - } - - // Load app_id remappings - if (config_["app_ids-mapping"].isObject()) { - const Json::Value& mapping = config_["app_ids-mapping"]; - const std::vector app_ids = config_["app_ids-mapping"].getMemberNames(); - for (auto& app_id : app_ids) { - app_ids_replace_map_.emplace(app_id, mapping[app_id].asString()); - } - } - - icon_themes_.push_back(Gtk::IconTheme::get_default()); -} - -Taskbar::~Taskbar() -{ if (manager_) { - struct wl_display *display = Client::inst()->wl_display; - /* - * Send `stop` request and wait for one roundtrip. - * This is not quite correct as the protocol encourages us to wait for the .finished event, - * but it should work with wlroots foreign toplevel manager implementation. - */ - zwlr_foreign_toplevel_manager_v1_stop(manager_); - wl_display_roundtrip(display); - - if (manager_) { - spdlog::warn("Foreign toplevel manager destroyed before .finished event"); - zwlr_foreign_toplevel_manager_v1_destroy(manager_); - manager_ = nullptr; - } + spdlog::warn("Foreign toplevel manager destroyed before .finished event"); + zwlr_foreign_toplevel_manager_v1_destroy(manager_); + manager_ = nullptr; } + } } -void Taskbar::update() -{ - for (auto& t : tasks_) { - t->update(); - } +void Taskbar::update() { + for (auto &t : tasks_) { + t->update(); + } - AModule::update(); + AModule::update(); } static void tm_handle_toplevel(void *data, struct zwlr_foreign_toplevel_manager_v1 *manager, - struct zwlr_foreign_toplevel_handle_v1 *tl_handle) -{ - return static_cast(data)->handle_toplevel_create(tl_handle); + struct zwlr_foreign_toplevel_handle_v1 *tl_handle) { + return static_cast(data)->handle_toplevel_create(tl_handle); } -static void tm_handle_finished(void *data, struct zwlr_foreign_toplevel_manager_v1 *manager) -{ - return static_cast(data)->handle_finished(); +static void tm_handle_finished(void *data, struct zwlr_foreign_toplevel_manager_v1 *manager) { + return static_cast(data)->handle_finished(); } static const struct zwlr_foreign_toplevel_manager_v1_listener toplevel_manager_impl = { @@ -801,93 +722,83 @@ static const struct zwlr_foreign_toplevel_manager_v1_listener toplevel_manager_i .finished = tm_handle_finished, }; -void Taskbar::register_manager(struct wl_registry *registry, uint32_t name, uint32_t version) -{ - if (manager_) { - spdlog::warn("Register foreign toplevel manager again although already existing!"); - return; - } - if (version < ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_SET_FULLSCREEN_SINCE_VERSION) { - spdlog::warn("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); - } +void Taskbar::register_manager(struct wl_registry *registry, uint32_t name, uint32_t version) { + if (manager_) { + spdlog::warn("Register foreign toplevel manager again although already existing!"); + return; + } + if (version < ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_SET_FULLSCREEN_SINCE_VERSION) { + spdlog::warn( + "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 - version = std::min(version, zwlr_foreign_toplevel_manager_v1_interface.version); + // limit version to a highest supported by the client protocol file + version = std::min(version, zwlr_foreign_toplevel_manager_v1_interface.version); - manager_ = static_cast(wl_registry_bind(registry, name, - &zwlr_foreign_toplevel_manager_v1_interface, version)); + manager_ = static_cast( + wl_registry_bind(registry, name, &zwlr_foreign_toplevel_manager_v1_interface, version)); - if (manager_) - zwlr_foreign_toplevel_manager_v1_add_listener(manager_, &toplevel_manager_impl, this); - else - spdlog::debug("Failed to register manager"); + if (manager_) + zwlr_foreign_toplevel_manager_v1_add_listener(manager_, &toplevel_manager_impl, this); + else + spdlog::debug("Failed to register manager"); } -void Taskbar::register_seat(struct wl_registry *registry, uint32_t name, uint32_t version) -{ - if (seat_) { - spdlog::warn("Register seat again although already existing!"); - return; - } - version = std::min(version, wl_seat_interface.version); +void Taskbar::register_seat(struct wl_registry *registry, uint32_t name, uint32_t version) { + if (seat_) { + spdlog::warn("Register seat again although already existing!"); + return; + } + version = std::min(version, wl_seat_interface.version); - seat_ = static_cast(wl_registry_bind(registry, name, &wl_seat_interface, version)); + seat_ = static_cast(wl_registry_bind(registry, name, &wl_seat_interface, version)); } -void Taskbar::handle_toplevel_create(struct zwlr_foreign_toplevel_handle_v1 *tl_handle) -{ - tasks_.push_back(std::make_unique(bar_, config_, this, tl_handle, seat_)); +void Taskbar::handle_toplevel_create(struct zwlr_foreign_toplevel_handle_v1 *tl_handle) { + tasks_.push_back(std::make_unique(bar_, config_, this, tl_handle, seat_)); } -void Taskbar::handle_finished() -{ - zwlr_foreign_toplevel_manager_v1_destroy(manager_); - manager_ = nullptr; +void Taskbar::handle_finished() { + zwlr_foreign_toplevel_manager_v1_destroy(manager_); + manager_ = nullptr; } -void Taskbar::add_button(Gtk::Button &bt) -{ - box_.pack_start(bt, false, false); +void Taskbar::add_button(Gtk::Button &bt) { box_.pack_start(bt, false, false); } + +void Taskbar::move_button(Gtk::Button &bt, int pos) { box_.reorder_child(bt, pos); } + +void Taskbar::remove_button(Gtk::Button &bt) { box_.remove(bt); } + +void Taskbar::remove_task(uint32_t id) { + auto it = std::find_if(std::begin(tasks_), std::end(tasks_), + [id](const TaskPtr &p) { return p->id() == id; }); + + if (it == std::end(tasks_)) { + spdlog::warn("Can't find task with id {}", id); + return; + } + + tasks_.erase(it); } -void Taskbar::move_button(Gtk::Button &bt, int pos) -{ - box_.reorder_child(bt, pos); +bool Taskbar::show_output(struct wl_output *output) const { + return output == gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj()); } -void Taskbar::remove_button(Gtk::Button &bt) -{ - box_.remove(bt); +bool Taskbar::all_outputs() const { + return config_["all-outputs"].isBool() && config_["all-outputs"].asBool(); } -void Taskbar::remove_task(uint32_t id) -{ - auto it = std::find_if(std::begin(tasks_), std::end(tasks_), - [id](const TaskPtr &p) { return p->id() == id; }); - - if (it == std::end(tasks_)) { - spdlog::warn("Can't find task with id {}", id); - return; - } - - tasks_.erase(it); +const std::vector> &Taskbar::icon_themes() const { + return icon_themes_; } -bool Taskbar::show_output(struct wl_output *output) const -{ - return output == gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj()); +const std::unordered_set &Taskbar::ignore_list() const { return ignore_list_; } + +const std::map &Taskbar::app_ids_replace_map() const { + return app_ids_replace_map_; } -bool Taskbar::all_outputs() const -{ - return config_["all-outputs"].isBool() && config_["all-outputs"].asBool(); -} - -const std::vector>& Taskbar::icon_themes() const { return icon_themes_; } - -const std::unordered_set& Taskbar::ignore_list() const { return ignore_list_; } - -const std::map& Taskbar::app_ids_replace_map() const { return app_ids_replace_map_; } - } /* namespace waybar::modules::wlr */ diff --git a/src/modules/wlr/workspace_manager.cpp b/src/modules/wlr/workspace_manager.cpp index bacef355..cc3c8151 100644 --- a/src/modules/wlr/workspace_manager.cpp +++ b/src/modules/wlr/workspace_manager.cpp @@ -13,8 +13,8 @@ namespace waybar::modules::wlr { -uint32_t WorkspaceGroup::workspace_global_id = 0; -uint32_t WorkspaceManager::group_global_id = 0; +uint32_t WorkspaceGroup::workspace_global_id = 0; +uint32_t WorkspaceManager::group_global_id = 0; std::map Workspace::icons_map_; WorkspaceManager::WorkspaceManager(const std::string &id, const waybar::Bar &bar, @@ -156,8 +156,7 @@ WorkspaceManager::~WorkspaceManager() { } auto WorkspaceManager::remove_workspace_group(uint32_t id) -> void { - auto it = std::find_if(groups_.begin(), - groups_.end(), + auto it = std::find_if(groups_.begin(), groups_.end(), [id](const std::unique_ptr &g) { return g->id() == id; }); if (it == groups_.end()) { @@ -170,7 +169,7 @@ auto WorkspaceManager::remove_workspace_group(uint32_t id) -> void { auto WorkspaceManager::commit() -> void { zext_workspace_manager_v1_commit(workspace_manager_); } WorkspaceGroup::WorkspaceGroup(const Bar &bar, Gtk::Box &box, const Json::Value &config, - WorkspaceManager &manager, + WorkspaceManager &manager, zext_workspace_group_handle_v1 *workspace_group_handle, uint32_t id) : bar_(bar), box_(box), @@ -257,8 +256,7 @@ auto WorkspaceGroup::update() -> void { } auto WorkspaceGroup::remove_workspace(uint32_t id) -> void { - auto it = std::find_if(workspaces_.begin(), - workspaces_.end(), + auto it = std::find_if(workspaces_.begin(), workspaces_.end(), [id](const std::unique_ptr &w) { return w->id() == id; }); if (it == workspaces_.end()) { @@ -353,8 +351,8 @@ Workspace::~Workspace() { } auto Workspace::update() -> void { - label_.set_markup(fmt::format( - format_, fmt::arg("name", name_), fmt::arg("icon", with_icon_ ? get_icon() : ""))); + label_.set_markup(fmt::format(format_, fmt::arg("name", name_), + fmt::arg("icon", with_icon_ ? get_icon() : ""))); } auto Workspace::handle_state(const std::vector &state) -> void { diff --git a/src/modules/wlr/workspace_manager_binding.cpp b/src/modules/wlr/workspace_manager_binding.cpp index 30c60413..22e68fbf 100644 --- a/src/modules/wlr/workspace_manager_binding.cpp +++ b/src/modules/wlr/workspace_manager_binding.cpp @@ -1,6 +1,7 @@ #include "modules/wlr/workspace_manager_binding.hpp" #include + #include #include "client.hpp" @@ -23,7 +24,7 @@ static const wl_registry_listener registry_listener_impl = {.global = handle_glo .global_remove = handle_global_remove}; 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_add_listener(registry, ®istry_listener_impl, data); @@ -89,7 +90,7 @@ static const zext_workspace_group_handle_v1_listener workspace_group_impl = { .remove = workspace_group_handle_remove}; 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); } @@ -100,7 +101,7 @@ void workspace_handle_name(void *data, struct zext_workspace_handle_v1 *_, const void workspace_handle_coordinates(void *data, struct zext_workspace_handle_v1 *_, struct wl_array *coordinates) { std::vector coords_vec; - auto coords = static_cast(coordinates->data); + auto coords = static_cast(coordinates->data); for (size_t i = 0; i < coordinates->size / sizeof(uint32_t); ++i) { coords_vec.push_back(coords[i]); } @@ -111,7 +112,7 @@ void workspace_handle_coordinates(void *data, struct zext_workspace_handle_v1 *_ void workspace_handle_state(void *data, struct zext_workspace_handle_v1 *workspace_handle, struct wl_array *state) { std::vector state_vec; - auto states = static_cast(state->data); + auto states = static_cast(state->data); for (size_t i = 0; i < state->size / sizeof(uint32_t); ++i) { state_vec.push_back(states[i]); } diff --git a/src/util/rfkill.cpp b/src/util/rfkill.cpp index 7400135e..47da3b52 100644 --- a/src/util/rfkill.cpp +++ b/src/util/rfkill.cpp @@ -39,8 +39,8 @@ waybar::util::Rfkill::Rfkill(const enum rfkill_type rfkill_type) : rfkill_type_( fd_ = -1; return; } - Glib::signal_io().connect( - sigc::mem_fun(*this, &Rfkill::on_event), fd_, Glib::IO_IN | Glib::IO_ERR | Glib::IO_HUP); + Glib::signal_io().connect(sigc::mem_fun(*this, &Rfkill::on_event), fd_, + Glib::IO_IN | Glib::IO_ERR | Glib::IO_HUP); } waybar::util::Rfkill::~Rfkill() { @@ -52,7 +52,7 @@ waybar::util::Rfkill::~Rfkill() { bool waybar::util::Rfkill::on_event(Glib::IOCondition cond) { if (cond & Glib::IO_IN) { struct rfkill_event event; - ssize_t len; + ssize_t len; len = read(fd_, &event, sizeof(event)); if (len < 0) { diff --git a/src/util/ustring_clen.cpp b/src/util/ustring_clen.cpp index cd7d9cf5..374df0d6 100644 --- a/src/util/ustring_clen.cpp +++ b/src/util/ustring_clen.cpp @@ -1,6 +1,6 @@ #include "util/ustring_clen.hpp" -int ustring_clen(const Glib::ustring &str){ +int ustring_clen(const Glib::ustring &str) { int total = 0; for (auto i = str.begin(); i != str.end(); ++i) { total += g_unichar_iswide(*i) + 1; diff --git a/test/SafeSignal.cpp b/test/SafeSignal.cpp index 244487f2..6a1e17a5 100644 --- a/test/SafeSignal.cpp +++ b/test/SafeSignal.cpp @@ -20,12 +20,12 @@ using remove_cvref_t = typename std::remove_cv */ TEST_CASE_METHOD(GlibTestsFixture, "SafeSignal basic functionality", "[signal][thread][util]") { const int NUM_EVENTS = 100; - int count = 0; - int last_value = 0; + int count = 0; + int last_value = 0; SafeSignal test_signal; - const auto main_tid = std::this_thread::get_id(); + const auto main_tid = std::this_thread::get_id(); std::thread producer; // timeout the test in 500ms @@ -63,7 +63,7 @@ TEST_CASE_METHOD(GlibTestsFixture, "SafeSignal basic functionality", "[signal][t template struct TestObject { - T value; + T value; unsigned copied = 0; unsigned moved = 0; @@ -93,7 +93,7 @@ struct TestObject { } bool operator==(T other) const { return value == other; } - operator T() const { return value; } + operator T() const { return value; } }; /* @@ -101,7 +101,7 @@ struct TestObject { */ TEST_CASE_METHOD(GlibTestsFixture, "SafeSignal copy/move counter", "[signal][thread][util]") { const int NUM_EVENTS = 3; - int count = 0; + int count = 0; SafeSignal> test_signal; diff --git a/test/main.cpp b/test/main.cpp index bbfcc9f2..5eb060d9 100644 --- a/test/main.cpp +++ b/test/main.cpp @@ -12,7 +12,7 @@ int main(int argc, char* argv[]) { Glib::init(); session.applyCommandLine(argc, argv); - const auto logger = spdlog::default_logger(); + const auto logger = spdlog::default_logger(); const auto& reporter_name = session.config().getReporterName(); if (reporter_name == "tap") { spdlog::set_pattern("# [%l] %v"); From 2e12ea6a810f3ec07193046ae45aef47e8465055 Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 6 Apr 2022 08:43:31 +0200 Subject: [PATCH 3/4] fix: add missing include --- include/modules/network.hpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/include/modules/network.hpp b/include/modules/network.hpp index 8e06aa65..8ec6b6df 100644 --- a/include/modules/network.hpp +++ b/include/modules/network.hpp @@ -8,6 +8,8 @@ #include #include +#include + #include "ALabel.hpp" #include "util/sleeper_thread.hpp" #ifdef WANT_RFKILL From a1129c4c87dd14beef771295aca911f3f9e799bc Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 6 Apr 2022 14:55:08 +0200 Subject: [PATCH 4/4] fix: bsd --- src/modules/cpu/bsd.cpp | 4 +++- src/modules/memory/bsd.cpp | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/modules/cpu/bsd.cpp b/src/modules/cpu/bsd.cpp index 748c3cd6..5eb767d9 100644 --- a/src/modules/cpu/bsd.cpp +++ b/src/modules/cpu/bsd.cpp @@ -1,6 +1,8 @@ #include -#include +// clang-format off #include +#include +// clang-format on #include // sysconf #include // NAN diff --git a/src/modules/memory/bsd.cpp b/src/modules/memory/bsd.cpp index d9098cee..67f9fed7 100644 --- a/src/modules/memory/bsd.cpp +++ b/src/modules/memory/bsd.cpp @@ -1,5 +1,7 @@ -#include +// clang-format off #include +#include +// clang-format on #include // getpagesize #include "modules/memory.hpp"