diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 0fad47c4..25f62c8e 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -10,13 +10,9 @@ jobs: lint: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 - # TODO: bump to clang 19 release - # - uses: DoozyX/clang-format-lint-action@v0.18.2 - - uses: DoozyX/clang-format-lint-action@558090054b3f39e3d6af24f0cd73b319535da809 + - uses: actions/checkout@v6 + - uses: RafikFarhad/clang-format-github-action@v6 name: clang-format with: - source: "." - extensions: "hpp,h,cpp,c" - style: "file:.clang-format" - clangFormatVersion: 19 + sources: "src/**/*.hpp,src/**/*.cpp" + style: "file" diff --git a/.github/workflows/clang-tidy.yml.bak b/.github/workflows/clang-tidy.yml.bak index ec67fb7e..9e9da80c 100644 --- a/.github/workflows/clang-tidy.yml.bak +++ b/.github/workflows/clang-tidy.yml.bak @@ -12,7 +12,7 @@ jobs: container: image: alexays/waybar:debian steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v6 - name: configure run: | meson -Dcpp_std=c++20 build # necessary to generate compile_commands.json diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 66c465ba..ea8eb08b 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -1,14 +1,15 @@ name: Build and Push Docker Image on: + workflow_dispatch: schedule: - # run every night at midnight - - cron: '0 0 * * *' + # run monthly + - cron: '0 0 1 * *' jobs: build-and-push: runs-on: ubuntu-latest - if: github.repository == 'Alexays/Waybar' + if: github.event_name != 'schedule' || github.repository == 'Alexays/Waybar' strategy: fail-fast: false # don't fail the other jobs if one of the images fails to build matrix: @@ -16,7 +17,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Login to Docker Hub uses: docker/login-action@v3 diff --git a/.github/workflows/freebsd.yml b/.github/workflows/freebsd.yml index ca0dcbc8..f6c96f95 100644 --- a/.github/workflows/freebsd.yml +++ b/.github/workflows/freebsd.yml @@ -12,16 +12,16 @@ jobs: # https://github.com/actions/runner/issues/385 - for FreeBSD runner support runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v6 - name: Test in FreeBSD VM - uses: cross-platform-actions/action@v0.25.0 + uses: cross-platform-actions/action@v0.28.0 timeout-minutes: 180 env: CPPFLAGS: '-isystem/usr/local/include' - LDFLAGS: '-L/usr/local/lib' + LDFLAGS: '-L/usr/local/lib' with: operating_system: freebsd - version: "14.1" + version: "14.2" environment_variables: CPPFLAGS LDFLAGS sync_files: runner-to-vm run: | diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index c36f68e2..12a995d7 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -25,7 +25,7 @@ jobs: image: alexays/waybar:${{ matrix.distro }} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v6 - name: configure run: meson setup -Dman-pages=enabled -Dcpp_std=${{matrix.cpp_std}} build - name: build diff --git a/.github/workflows/nix-tests.yml b/.github/workflows/nix-tests.yml index 8859ecb5..c2193b99 100644 --- a/.github/workflows/nix-tests.yml +++ b/.github/workflows/nix-tests.yml @@ -2,16 +2,19 @@ name: "Nix-Tests" on: pull_request: push: +concurrency: + group: ${{ github.workflow }}-nix-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true jobs: nix-flake-check: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: cachix/install-nix-action@v27 - with: - extra_nix_config: | - experimental-features = nix-command flakes - access-tokens = github.com=${{ secrets.GITHUB_TOKEN }} - - run: nix flake show - - run: nix flake check --print-build-logs - - run: nix build --print-build-logs + - uses: actions/checkout@v6 + - uses: cachix/install-nix-action@v31 + with: + extra_nix_config: | + experimental-features = nix-command flakes + access-tokens = github.com=${{ secrets.GITHUB_TOKEN }} + - run: nix flake show + - run: nix flake check --print-build-logs + - run: nix build --print-build-logs diff --git a/.github/workflows/nix-update-flake-lock.yml b/.github/workflows/nix-update-flake-lock.yml index a1679ead..de8a0ea1 100644 --- a/.github/workflows/nix-update-flake-lock.yml +++ b/.github/workflows/nix-update-flake-lock.yml @@ -4,19 +4,19 @@ on: schedule: - cron: '0 0 1 * *' # Run monthly push: - paths: - - 'flake.nix' + paths: + - 'flake.nix' jobs: lockfile: runs-on: ubuntu-latest if: github.event_name != 'schedule' || github.repository == 'Alexays/Waybar' steps: - name: Checkout repository - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Install Nix - uses: cachix/install-nix-action@v27 + uses: cachix/install-nix-action@v31 with: extra_nix_config: | access-tokens = github.com=${{ secrets.GITHUB_TOKEN }} - name: Update flake.lock - uses: DeterminateSystems/update-flake-lock@v21 + uses: DeterminateSystems/update-flake-lock@v28 diff --git a/.gitignore b/.gitignore index b486237e..f21700d6 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ vgcore.* *.swp packagecache /subprojects/**/ +/subprojects/.wraplock /build* /dist /meson.egg-info @@ -50,3 +51,5 @@ result result-* .ccls-cache +_codeql_detected_source_root +heaptrack* diff --git a/Dockerfiles/debian b/Dockerfiles/debian index f479062d..c2584ccf 100644 --- a/Dockerfiles/debian +++ b/Dockerfiles/debian @@ -1,6 +1,6 @@ # vim: ft=Dockerfile -FROM debian:sid +FROM debian:sid-slim RUN apt update && \ apt install --no-install-recommends --no-install-suggests -y \ diff --git a/Dockerfiles/gentoo b/Dockerfiles/gentoo index f2ec0dc9..f7023825 100644 --- a/Dockerfiles/gentoo +++ b/Dockerfiles/gentoo @@ -6,6 +6,6 @@ RUN export FEATURES="-ipc-sandbox -network-sandbox -pid-sandbox -sandbox -usersa emerge --sync && \ eselect news read --quiet new 1>/dev/null 2>&1 && \ emerge --verbose --update --deep --with-bdeps=y --backtrack=30 --newuse @world && \ - USE="wayland gtk3 gtk -doc X pulseaudio minimal" emerge dev-vcs/git dev-libs/wayland dev-libs/wayland-protocols =dev-cpp/gtkmm-3.24.6 x11-libs/libxkbcommon \ + USE="wayland gtk3 gtk -doc X pulseaudio minimal" emerge dev-vcs/git dev-libs/wayland dev-libs/wayland-protocols dev-cpp/gtkmm:3.0 x11-libs/libxkbcommon \ x11-libs/gtk+:3 dev-libs/libdbusmenu dev-libs/libnl sys-power/upower media-libs/libpulse dev-libs/libevdev media-libs/libmpdclient \ media-sound/sndio gui-libs/gtk-layer-shell app-text/scdoc media-sound/playerctl dev-libs/iniparser sci-libs/fftw diff --git a/Makefile b/Makefile index 3bb11199..12af8e0e 100644 --- a/Makefile +++ b/Makefile @@ -20,8 +20,12 @@ debug-run: build-debug ./build/waybar --log-level debug test: - meson test -C build --no-rebuild --verbose --suite waybar + meson test -C build --verbose --suite waybar .PHONY: test +test-detailed: + meson test -C build --verbose --print-errorlogs --test-args='--reporter console -s' +.PHONY: test-detailed + clean: rm -rf build diff --git a/README.md b/README.md index 5266e916..9ca041d1 100644 --- a/README.md +++ b/README.md @@ -116,11 +116,45 @@ sudo apt install \ libxkbregistry-dev ``` +On Arch, you can use this command: + +``` +pacman -S --asdeps \ + gtkmm3 \ + jsoncpp \ + libsigc++ \ + fmt \ + wayland \ + chrono-date \ + spdlog \ + gtk3 \ + gobject-introspection \ + libgirepository \ + libpulse \ + libnl \ + libappindicator-gtk3 \ + libdbusmenu-gtk3 \ + libmpdclient \ + sndio \ + libevdev \ + libxkbcommon \ + upower \ + meson \ + cmake \ + scdoc \ + wayland-protocols \ + glib2-devel +``` + Contributions welcome!
Have fun :)
The style guidelines are [Google's](https://google.github.io/styleguide/cppguide.html) +> [!CAUTION] +> Distributions of Waybar are only released on the [official GitHub page](https://github.com/Alexays/Waybar).
+> Waybar does **not** have an official website. Do not trust any sites that claim to be official. + ## License Waybar is licensed under the MIT license. [See LICENSE for more information](https://github.com/Alexays/Waybar/blob/master/LICENSE). diff --git a/_codeql_detected_source_root b/_codeql_detected_source_root new file mode 120000 index 00000000..945c9b46 --- /dev/null +++ b/_codeql_detected_source_root @@ -0,0 +1 @@ +. \ No newline at end of file diff --git a/asan.supp b/asan.supp new file mode 100644 index 00000000..3633b361 --- /dev/null +++ b/asan.supp @@ -0,0 +1,5 @@ +# Suppress common address sanitizer issues in dependencies, these are often non-fixable or not an issue. +# Use it like this (when in repo root): ASAN_OPTIONS="suppressions=./asan.supp" ./build/waybar +leak:libpangoft2-1.0.so.0 +leak:libgtk-3.so.0 +leak:libfontconfig.so.1 \ No newline at end of file diff --git a/flake.lock b/flake.lock index 480f004f..e3e70a02 100644 --- a/flake.lock +++ b/flake.lock @@ -3,11 +3,11 @@ "flake-compat": { "flake": false, "locked": { - "lastModified": 1733328505, - "narHash": "sha256-NeCCThCEP3eCl2l/+27kNNK7QrwZB1IJCrXfrbv5oqU=", + "lastModified": 1767039857, + "narHash": "sha256-vNpUSpF5Nuw8xvDLj2KCwwksIbjua2LZCqhV1LNRDns=", "owner": "edolstra", "repo": "flake-compat", - "rev": "ff81ac966bb2cae68946d5ed5fc4994f96d0ffec", + "rev": "5edf11c44bc78a0d334f6334cdaf7d60d732daab", "type": "github" }, "original": { @@ -18,11 +18,11 @@ }, "nixpkgs": { "locked": { - "lastModified": 1745391562, - "narHash": "sha256-sPwcCYuiEopaafePqlG826tBhctuJsLx/mhKKM5Fmjo=", + "lastModified": 1769461804, + "narHash": "sha256-msG8SU5WsBUfVVa/9RPLaymvi5bI8edTavbIq3vRlhI=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "8a2f738d9d1f1d986b5a4cd2fd2061a7127237d7", + "rev": "bfc1b8a4574108ceef22f02bafcf6611380c100d", "type": "github" }, "original": { diff --git a/flake.nix b/flake.nix index 7c7a2281..b2f96731 100644 --- a/flake.nix +++ b/flake.nix @@ -65,7 +65,7 @@ nativeBuildInputs = pkgs.waybar.nativeBuildInputs ++ (with pkgs; [ - nixfmt-rfc-style + nixfmt clang-tools gdb ]); @@ -75,28 +75,26 @@ formatter = genSystems ( pkgs: pkgs.treefmt.withConfig { - settings = [ - { - formatter = { - clang-format = { - options = [ "-i" ]; - command = lib.getExe' pkgs.clang-tools "clang-format"; - excludes = [ ]; - includes = [ - "*.c" - "*.cpp" - "*.h" - "*.hpp" - ]; - }; - nixfmt = { - command = lib.getExe pkgs.nixfmt-rfc-style; - includes = [ "*.nix" ]; - }; + settings = { + formatter = { + clang-format = { + options = [ "-i" ]; + command = lib.getExe' pkgs.clang-tools "clang-format"; + excludes = [ ]; + includes = [ + "*.c" + "*.cpp" + "*.h" + "*.hpp" + ]; }; - tree-root-file = ".git/index"; - } - ]; + nixfmt = { + command = lib.getExe pkgs.nixfmt; + includes = [ "*.nix" ]; + }; + }; + tree-root-file = ".git/index"; + }; } ); diff --git a/include/AAppIconLabel.hpp b/include/AAppIconLabel.hpp index d09ab14a..e8532e18 100644 --- a/include/AAppIconLabel.hpp +++ b/include/AAppIconLabel.hpp @@ -9,15 +9,15 @@ namespace waybar { class AAppIconLabel : public AIconLabel { public: - AAppIconLabel(const Json::Value &config, const std::string &name, const std::string &id, - const std::string &format, uint16_t interval = 0, bool ellipsize = false, + AAppIconLabel(const Json::Value& config, const std::string& name, const std::string& id, + const std::string& format, uint16_t interval = 0, bool ellipsize = false, bool enable_click = false, bool enable_scroll = false); virtual ~AAppIconLabel() = default; auto update() -> void override; protected: - void updateAppIconName(const std::string &app_identifier, - const std::string &alternative_app_identifier); + void updateAppIconName(const std::string& app_identifier, + const std::string& alternative_app_identifier); void updateAppIcon(); unsigned app_icon_size_{24}; bool update_app_icon_{true}; diff --git a/include/AIconLabel.hpp b/include/AIconLabel.hpp index 054d031a..f0fb8614 100644 --- a/include/AIconLabel.hpp +++ b/include/AIconLabel.hpp @@ -9,8 +9,8 @@ namespace waybar { class AIconLabel : public ALabel { public: - AIconLabel(const Json::Value &config, const std::string &name, const std::string &id, - const std::string &format, uint16_t interval = 0, bool ellipsize = false, + AIconLabel(const Json::Value& config, const std::string& name, const std::string& id, + const std::string& format, uint16_t interval = 0, bool ellipsize = false, bool enable_click = false, bool enable_scroll = false); virtual ~AIconLabel() = default; auto update() -> void override; diff --git a/include/ALabel.hpp b/include/ALabel.hpp index a1aae9da..7c5150a0 100644 --- a/include/ALabel.hpp +++ b/include/ALabel.hpp @@ -4,33 +4,42 @@ #include #include +#include + #include "AModule.hpp" namespace waybar { class ALabel : public AModule { public: - ALabel(const Json::Value &, const std::string &, const std::string &, const std::string &format, + ALabel(const Json::Value&, const std::string&, const std::string&, const std::string& format, uint16_t interval = 0, bool ellipsize = false, bool enable_click = false, bool enable_scroll = false); virtual ~ALabel() = default; auto update() -> void override; - 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); + 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_; - const std::chrono::seconds interval_; + const std::chrono::milliseconds interval_; bool alt_ = false; std::string default_format_; - bool handleToggle(GdkEventButton *const &e) override; + bool setLabelMarkup(const Glib::ustring& markup); + bool setTooltipMarkup(const Glib::ustring& markup); + + bool handleToggle(GdkEventButton* const& e) override; virtual std::string getState(uint8_t value, bool lesser = false); - std::map submenus_; + std::map submenus_; std::map menuActionsMap_; - static void handleGtkMenuEvent(GtkMenuItem *menuitem, gpointer data); + static void handleGtkMenuEvent(GtkMenuItem* menuitem, gpointer data); + + private: + std::optional last_label_markup_; + std::optional last_tooltip_markup_; }; } // namespace waybar diff --git a/include/AModule.hpp b/include/AModule.hpp index 2ffc429c..f697c012 100644 --- a/include/AModule.hpp +++ b/include/AModule.hpp @@ -12,51 +12,58 @@ namespace waybar { class AModule : public IModule { public: - static constexpr const char *MODULE_CLASS = "module"; + static constexpr const char* MODULE_CLASS = "module"; ~AModule() override; auto update() -> void override; virtual auto refresh(int shouldRefresh) -> void {}; - operator Gtk::Widget &() override; - auto doAction(const std::string &name) -> void override; + operator Gtk::Widget&() override; + auto doAction(const std::string& name) -> void override; /// Emitting on this dispatcher triggers a update() call Glib::Dispatcher dp; bool expandEnabled() const; + virtual void suspend() {}; + virtual void resume() {}; + bool shouldSuspend() const { return disable_on_sleep_; } + protected: // Don't need to make an object directly // Derived classes are able to use it - AModule(const Json::Value &, const std::string &, const std::string &, bool enable_click = false, + AModule(const Json::Value&, const std::string&, const std::string&, bool enable_click = false, bool enable_scroll = false); enum SCROLL_DIR { NONE, UP, DOWN, LEFT, RIGHT }; - SCROLL_DIR getScrollDir(GdkEventScroll *e); + SCROLL_DIR getScrollDir(GdkEventScroll* e); bool tooltipEnabled() const; + std::vector pid_children_; const std::string name_; - const Json::Value &config_; + const Json::Value& config_; Gtk::EventBox event_box_; - virtual void setCursor(Gdk::CursorType const &c); + virtual void setCursor(Gdk::CursorType const& c); - virtual bool handleToggle(GdkEventButton *const &ev); - virtual bool handleMouseEnter(GdkEventCrossing *const &ev); - virtual bool handleMouseLeave(GdkEventCrossing *const &ev); - virtual bool handleScroll(GdkEventScroll *); - virtual bool handleRelease(GdkEventButton *const &ev); - GObject *menu_; + virtual bool handleToggle(GdkEventButton* const& ev); + virtual bool handleMouseEnter(GdkEventCrossing* const& ev); + virtual bool handleMouseLeave(GdkEventCrossing* const& ev); + virtual bool handleScroll(GdkEventScroll*); + virtual bool handleRelease(GdkEventButton* const& ev); + + bool disable_on_sleep_{false}; + GObject* menu_ = nullptr; private: - bool handleUserEvent(GdkEventButton *const &ev); + bool handleUserEvent(GdkEventButton* const& ev); const bool isTooltip; const bool isExpand; bool hasUserEvents_; - std::vector pid_; gdouble distance_scrolled_y_; gdouble distance_scrolled_x_; + sigc::connection cursor_timeout_conn_; std::map eventActionMap_; static const inline std::map, std::string> eventMap_{ {std::make_pair(1, GdkEventType::GDK_BUTTON_PRESS), "on-click"}, diff --git a/include/bar.hpp b/include/bar.hpp index 9b407abf..783dd282 100644 --- a/include/bar.hpp +++ b/include/bar.hpp @@ -14,6 +14,7 @@ #include "AModule.hpp" #include "group.hpp" +#include "util/kill_signal.hpp" #include "xdg-output-unstable-v1-client-protocol.h" namespace waybar { @@ -61,18 +62,24 @@ class Bar : public sigc::trackable { static const std::string MODE_DEFAULT; static const std::string MODE_INVISIBLE; - Bar(struct waybar_output *w_output, const Json::Value &); - Bar(const Bar &) = delete; + Bar(struct waybar_output* w_output, const Json::Value&); + Bar(const Bar&) = delete; ~Bar(); - void setMode(const std::string &mode); + void setMode(const std::string& mode); void setVisible(bool value); void toggle(); + void show(); + void hide(); void handleSignal(int); + util::KillSignalAction getOnSigusr1Action(); + util::KillSignalAction getOnSigusr2Action(); - struct waybar_output *output; + void toggleSuspend(bool suspend); + + struct waybar_output* output; Json::Value config; - struct wl_surface *surface; + struct wl_surface* surface; bool visible = true; Gtk::Window window; Gtk::Orientation orientation = Gtk::ORIENTATION_HORIZONTAL; @@ -86,15 +93,16 @@ class Bar : public sigc::trackable { #endif private: - void onMap(GdkEventAny *); + void onMap(GdkEventAny*); auto setupWidgets() -> void; - void getModules(const Factory &, const std::string &, waybar::Group *); - void setupAltFormatKeyForModule(const std::string &module_name); - void setupAltFormatKeyForModuleList(const char *module_list_name); - void setMode(const bar_mode &); + void getModules(const Factory&, const std::string&, waybar::Group*); + void setupAltFormatKeyForModule(const std::string& module_name); + void setupAltFormatKeyForModuleList(const char* module_list_name); + void setMode(const bar_mode&); void setPassThrough(bool passthrough); void setPosition(Gtk::PositionType position); - void onConfigure(GdkEventConfigure *ev); + void forceLayerCommit(); + void onConfigure(GdkEventConfigure* ev); void configureGlobalOffset(int width, int height); void onOutputGeometryChanged(); @@ -118,6 +126,9 @@ class Bar : public sigc::trackable { std::unique_ptr _ipc_client; #endif std::vector> modules_all_; + + waybar::util::KillSignalAction onSigusr1 = util::SIGNALACTION_DEFAULT_SIGUSR1; + waybar::util::KillSignalAction onSigusr2 = util::SIGNALACTION_DEFAULT_SIGUSR2; }; } // namespace waybar diff --git a/include/client.hpp b/include/client.hpp index 0e68f002..10a634fc 100644 --- a/include/client.hpp +++ b/include/client.hpp @@ -17,35 +17,36 @@ namespace waybar { class Client { public: - static Client *inst(); - int main(int argc, char *argv[]); + static Client* inst(); + 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 zxdg_output_manager_v1 *xdg_output_manager = nullptr; - struct zwp_idle_inhibit_manager_v1 *idle_inhibit_manager = nullptr; + struct wl_display* wl_display = nullptr; + struct wl_registry* registry = 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; private: Client() = default; - const std::string getStyle(const std::string &style, std::optional appearance); + const std::string getStyle(const std::string& style, std::optional appearance); 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); + 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, - const char *interface, uint32_t version); - static void handleGlobalRemove(void *data, struct wl_registry *registry, uint32_t name); - 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 *); + static void handleGlobal(void* data, struct wl_registry* registry, uint32_t name, + const char* interface, uint32_t version); + static void handleGlobalRemove(void* data, struct wl_registry* registry, uint32_t name); + static void handleOutputDone(void*, struct zxdg_output_v1*); + void createBarsBatch(); + 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); @@ -56,6 +57,10 @@ class Client { std::list outputs_; std::unique_ptr m_cssReloadHelper; std::string m_cssFile; + sigc::connection monitor_added_connection_; + sigc::connection monitor_removed_connection_; + std::list pending_outputs_; + bool bars_scheduled_ = false; }; } // namespace waybar diff --git a/include/config.hpp b/include/config.hpp index 5256bb46..1ef9ef5f 100644 --- a/include/config.hpp +++ b/include/config.hpp @@ -14,27 +14,29 @@ namespace waybar { class Config { public: static const std::vector CONFIG_DIRS; - static const char *CONFIG_PATH_ENV; + static const char* CONFIG_PATH_ENV; /* Try to find any of provided names in the supported set of config directories */ static std::optional findConfigPath( - const std::vector &names, const std::vector &dirs = CONFIG_DIRS); + const std::vector& names, const std::vector& dirs = CONFIG_DIRS); - static std::vector tryExpandPath(const std::string &base, - const std::string &filename); + static std::vector tryExpandPath(const std::string& base, + const std::string& filename); Config() = default; - void load(const std::string &config); + void load(const std::string& config); - Json::Value &getConfig() { return config_; } + Json::Value& getConfig() { return config_; } - std::vector getOutputConfigs(const std::string &name, const std::string &identifier); + std::vector getOutputConfigs(const std::string& name, const std::string& identifier); private: - void setupConfig(Json::Value &dst, const std::string &config_file, int depth); - void resolveConfigIncludes(Json::Value &config, int depth); - void mergeConfig(Json::Value &a_config_, Json::Value &b_config_); + void setupConfig(Json::Value& dst, const std::string& config_file, int depth); + void resolveConfigIncludes(Json::Value& config, int depth); + void mergeConfig(Json::Value& a_config_, Json::Value& b_config_); + static std::vector findIncludePath( + const std::string& name, const std::vector& dirs = CONFIG_DIRS); std::string config_file_; diff --git a/include/group.hpp b/include/group.hpp index 5ce331a8..d5cbb289 100644 --- a/include/group.hpp +++ b/include/group.hpp @@ -11,13 +11,13 @@ namespace waybar { class Group : public AModule { public: - Group(const std::string &, const std::string &, const Json::Value &, bool); + Group(const std::string&, const std::string&, const Json::Value&, bool); ~Group() override = default; auto update() -> void override; - operator Gtk::Widget &() override; + operator Gtk::Widget&() override; - virtual Gtk::Box &getBox(); - void addWidget(Gtk::Widget &widget); + virtual Gtk::Box& getBox(); + void addWidget(Gtk::Widget& widget); protected: Gtk::Box box; @@ -27,9 +27,10 @@ class Group : public AModule { bool is_drawer = false; bool click_to_reveal = false; std::string add_class_to_drawer_children; - bool handleMouseEnter(GdkEventCrossing *const &ev) override; - bool handleMouseLeave(GdkEventCrossing *const &ev) override; - bool handleToggle(GdkEventButton *const &ev) override; + bool handleMouseEnter(GdkEventCrossing* const& ev) override; + bool handleMouseLeave(GdkEventCrossing* const& ev) override; + bool handleToggle(GdkEventButton* const& ev) override; + bool handleScroll(GdkEventScroll* e) override; void show_group(); void hide_group(); }; diff --git a/include/modules/backlight.hpp b/include/modules/backlight.hpp index 110cd434..46b38972 100644 --- a/include/modules/backlight.hpp +++ b/include/modules/backlight.hpp @@ -17,11 +17,11 @@ namespace waybar::modules { class Backlight : public ALabel { public: - Backlight(const std::string &, const Json::Value &); + Backlight(const std::string&, const Json::Value&); virtual ~Backlight() = default; auto update() -> void override; - bool handleScroll(GdkEventScroll *e) override; + bool handleScroll(GdkEventScroll* e) override; const std::string preferred_device_; diff --git a/include/modules/battery.hpp b/include/modules/battery.hpp index 8e1a2ad2..09c172b0 100644 --- a/include/modules/battery.hpp +++ b/include/modules/battery.hpp @@ -6,6 +6,7 @@ #if defined(__linux__) #include #endif +#include #include #include @@ -15,6 +16,7 @@ #include "ALabel.hpp" #include "bar.hpp" #include "util/sleeper_thread.hpp" +#include "util/udev_deleter.hpp" namespace waybar::modules { @@ -35,15 +37,19 @@ class Battery : public ALabel { std::tuple getInfos(); const std::string formatTimeRemaining(float hoursRemaining); void setBarClass(std::string&); + void processEvents(std::string& state, std::string& status, uint8_t capacity); - int global_watch; std::map batteries_; + std::unique_ptr udev_; + std::array poll_fds_; + std::unique_ptr mon_; fs::path adapter_; int battery_watch_fd_; - int global_watch_fd_; std::mutex battery_list_mutex_; std::string old_status_; + std::string last_event_; bool warnFirstTime_{true}; + bool weightedAverage_{true}; const Bar& bar_; util::SleeperThread thread_; diff --git a/include/modules/cava.hpp b/include/modules/cava.hpp deleted file mode 100644 index 1a88c7b7..00000000 --- a/include/modules/cava.hpp +++ /dev/null @@ -1,59 +0,0 @@ -#pragma once - -#include "ALabel.hpp" -#include "util/sleeper_thread.hpp" - -namespace cava { -extern "C" { -// Need sdl_glsl output feature to be enabled on libcava -#ifndef SDL_GLSL -#define SDL_GLSL -#endif - -#include - -#ifdef SDL_GLSL -#undef SDL_GLSL -#endif -} -} // namespace cava - -namespace waybar::modules { -using namespace std::literals::chrono_literals; - -class Cava final : public ALabel { - public: - Cava(const std::string&, const Json::Value&); - virtual ~Cava(); - auto update() -> void override; - auto doAction(const std::string& name) -> void override; - - private: - util::SleeperThread thread_; - util::SleeperThread thread_fetch_input_; - - struct cava::error_s error_{}; // cava errors - struct cava::config_params prm_{}; // cava parameters - struct cava::audio_raw audio_raw_{}; // cava handled raw audio data(is based on audio_data) - struct cava::audio_data audio_data_{}; // cava audio data - struct cava::cava_plan* plan_; //{new cava_plan{}}; - // Cava API to read audio source - cava::ptr input_source_; - // Delay to handle audio source - std::chrono::milliseconds frame_time_milsec_{1s}; - // Text to display - std::string text_{""}; - int rePaint_{1}; - std::chrono::seconds fetch_input_delay_{4}; - std::chrono::seconds suspend_silence_delay_{0}; - bool silence_{false}; - bool hide_on_silence_{false}; - std::string format_silent_{""}; - int sleep_counter_{0}; - // Cava method - void pause_resume(); - // ModuleActionMap - static inline std::map actionMap_{ - {"mode", &waybar::modules::Cava::pause_resume}}; -}; -} // namespace waybar::modules diff --git a/include/modules/cava/cavaGLSL.hpp b/include/modules/cava/cavaGLSL.hpp new file mode 100644 index 00000000..d2632aff --- /dev/null +++ b/include/modules/cava/cavaGLSL.hpp @@ -0,0 +1,43 @@ +#pragma once + +#include + +#include "AModule.hpp" +#include "cava_backend.hpp" + +namespace waybar::modules::cava { + +class CavaGLSL final : public AModule, public Gtk::GLArea { + public: + CavaGLSL(const std::string&, const Json::Value&); + ~CavaGLSL() = default; + + private: + std::shared_ptr backend_; + struct ::cava::config_params prm_; + int frame_counter{0}; + bool silence_{false}; + bool hide_on_silence_{false}; + // Cava method + auto onUpdate(const ::cava::audio_raw& input) -> void; + auto onSilence() -> void; + // Member variable to store the shared pointer + std::shared_ptr<::cava::audio_raw> m_data_; + GLuint shaderProgram_; + // OpenGL variables + GLuint fbo_; + GLuint texture_; + GLint uniform_bars_; + GLint uniform_previous_bars_; + GLint uniform_bars_count_; + GLint uniform_time_; + // Methods + void onRealize(); + bool onRender(const Glib::RefPtr& context); + + void initShaders(); + void initSurface(); + void initGLSL(); + GLuint loadShader(const std::string& fileName, GLenum type); +}; +} // namespace waybar::modules::cava diff --git a/include/modules/cava/cavaRaw.hpp b/include/modules/cava/cavaRaw.hpp new file mode 100644 index 00000000..f4ceb603 --- /dev/null +++ b/include/modules/cava/cavaRaw.hpp @@ -0,0 +1,30 @@ +#pragma once + +#include "ALabel.hpp" +#include "cava_backend.hpp" + +namespace waybar::modules::cava { + +class Cava final : public ALabel, public sigc::trackable { + public: + Cava(const std::string&, const Json::Value&); + ~Cava() = default; + auto doAction(const std::string& name) -> void override; + + private: + std::shared_ptr backend_; + // Text to display + Glib::ustring label_text_{""}; + bool silence_{false}; + bool hide_on_silence_{false}; + std::string format_silent_{""}; + int ascii_range_{0}; + // Cava method + void pause_resume(); + auto onUpdate(const std::string& input) -> void; + auto onSilence() -> void; + // ModuleActionMap + static inline std::map + actionMap_{{"mode", &waybar::modules::cava::Cava::pause_resume}}; +}; +} // namespace waybar::modules::cava diff --git a/include/modules/cava/cava_backend.hpp b/include/modules/cava/cava_backend.hpp new file mode 100644 index 00000000..4022a2ff --- /dev/null +++ b/include/modules/cava/cava_backend.hpp @@ -0,0 +1,84 @@ +#pragma once + +#include +#include + +#include "util/sleeper_thread.hpp" + +namespace cava { +extern "C" { +// Need sdl_glsl output feature to be enabled on libcava +#ifndef SDL_GLSL +#define SDL_GLSL +#endif + +#include + +#ifdef SDL_GLSL +#undef SDL_GLSL +#endif +} +} // namespace cava + +namespace waybar::modules::cava { +using namespace std::literals::chrono_literals; + +class CavaBackend final { + public: + static std::shared_ptr inst(const Json::Value& config); + + virtual ~CavaBackend(); + // Methods + int getAsciiRange(); + void doPauseResume(); + void Update(); + const struct ::cava::config_params* getPrm(); + std::chrono::milliseconds getFrameTimeMilsec(); + + // Signal accessor + using type_signal_update = sigc::signal; + type_signal_update signal_update(); + using type_signal_audio_raw_update = sigc::signal; + type_signal_audio_raw_update signal_audio_raw_update(); + using type_signal_silence = sigc::signal; + type_signal_silence signal_silence(); + + private: + CavaBackend(const Json::Value& config); + util::SleeperThread read_thread_; + util::SleeperThread out_thread_; + + // Cava API to read audio source + ::cava::ptr input_source_{NULL}; + + struct ::cava::error_s error_{}; // cava errors + struct ::cava::config_params prm_{}; // cava parameters + struct ::cava::audio_raw audio_raw_{}; // cava handled raw audio data(is based on audio_data) + struct ::cava::audio_data audio_data_{}; // cava audio data + struct ::cava::cava_plan* plan_{NULL}; //{new cava_plan{}}; + + std::chrono::seconds fetch_input_delay_{4}; + // Delay to handle audio source + std::chrono::milliseconds frame_time_milsec_{1s}; + + const Json::Value& config_; + int re_paint_{0}; + bool silence_{false}; + bool silence_prev_{false}; + std::chrono::seconds suspend_silence_delay_{0}; + int sleep_counter_{0}; + std::string output_{}; + // Methods + void invoke(); + void execute(); + bool isSilence(); + void doUpdate(bool force = false); + void loadConfig(); + void freeBackend(); + + // Signal + type_signal_update m_signal_update_; + type_signal_audio_raw_update m_signal_audio_raw_; + type_signal_silence m_signal_silence_; +}; +} // namespace waybar::modules::cava diff --git a/include/modules/cava/cava_frontend.hpp b/include/modules/cava/cava_frontend.hpp new file mode 100644 index 00000000..402a9bad --- /dev/null +++ b/include/modules/cava/cava_frontend.hpp @@ -0,0 +1,27 @@ +#pragma once + +#ifdef HAVE_LIBCAVA +#include "cavaRaw.hpp" +#include "cava_backend.hpp" +#ifdef HAVE_LIBCAVAGLSL +#include "cavaGLSL.hpp" +#endif +#endif + +namespace waybar::modules::cava { +AModule* getModule(const std::string& id, const Json::Value& config) { +#ifdef HAVE_LIBCAVA + const std::shared_ptr backend_{waybar::modules::cava::CavaBackend::inst(config)}; + switch (backend_->getPrm()->output) { +#ifdef HAVE_LIBCAVAGLSL + case ::cava::output_method::OUTPUT_SDL_GLSL: + return new waybar::modules::cava::CavaGLSL(id, config); +#endif + default: + return new waybar::modules::cava::Cava(id, config); + } +#else + throw std::runtime_error("Unknown module"); +#endif +}; +} // namespace waybar::modules::cava diff --git a/include/modules/clock.hpp b/include/modules/clock.hpp index 40b4f80e..c3548063 100644 --- a/include/modules/clock.hpp +++ b/include/modules/clock.hpp @@ -38,39 +38,41 @@ class Clock final : public ALabel { 5 - tooltip-format */ std::map fmtMap_; - uint cldMonCols_{3}; // calendar count month columns - int cldWnLen_{3}; // calendar week number length - const int cldMonColLen_{20}; // calendar month column length - WS cldWPos_{WS::HIDDEN}; // calendar week side to print - months cldCurrShift_{0}; // calendar months shift - int cldShift_{1}; // calendar months shift factor - year_month_day cldYearShift_; // calendar Year mode. Cached ymd - std::string cldYearCached_; // calendar Year mode. Cached calendar - year_month cldMonShift_; // calendar Month mode. Cached ym - std::string cldMonCached_; // calendar Month mode. Cached calendar - day cldBaseDay_{0}; // calendar Cached day. Is used when today is changing(midnight) + uint cldMonCols_{3}; // calendar count month columns + int cldWnLen_{3}; // calendar week number length + const int cldMonColLen_{20}; // calendar month column length + WS cldWPos_{WS::HIDDEN}; // calendar week side to print + date::months cldCurrShift_{0}; // calendar months shift + int cldShift_{1}; // calendar months shift factor + date::year_month_day cldYearShift_; // calendar Year mode. Cached ymd + std::string cldYearCached_; // calendar Year mode. Cached calendar + date::year_month cldMonShift_; // calendar Month mode. Cached ym + std::string cldMonCached_; // calendar Month mode. Cached calendar + date::day cldBaseDay_{0}; // calendar Cached day. Is used when today is changing(midnight) std::string cldText_{""}; // calendar text to print + bool iso8601Calendar_{false}; // whether the calendar is in ISO8601 CldMode cldMode_{CldMode::MONTH}; - auto get_calendar(const year_month_day& today, const year_month_day& ymd, const time_zone* tz) - -> const std::string; + auto get_calendar(const date::year_month_day& today, const date::year_month_day& ymd, + const date::time_zone* tz) -> const std::string; // get local time zone - auto local_zone() -> const time_zone*; + auto local_zone() -> const date::time_zone*; // time zoned time in tooltip - const bool tzInTooltip_; // if need to print time zones text - std::vector tzList_; // time zones list - int tzCurrIdx_; // current time zone index for tzList_ - std::string tzText_{""}; // time zones text to print + const bool tzInTooltip_; // if need to print time zones text + std::vector tzList_; // time zones list + int tzCurrIdx_; // current time zone index for tzList_ + std::string tzText_{""}; // time zones text to print + std::string tzTooltipFormat_{""}; // optional timezone tooltip format util::SleeperThread thread_; // ordinal date in tooltip const bool ordInTooltip_; std::string ordText_{""}; - auto get_ordinal_date(const year_month_day& today) -> std::string; + auto get_ordinal_date(const date::year_month_day& today) -> std::string; - auto getTZtext(sys_seconds now) -> std::string; - auto first_day_of_week() -> weekday; + auto getTZtext(date::sys_seconds now) -> std::string; + auto first_day_of_week() -> date::weekday; // Module actions void cldModeSwitch(); void cldShift_up(); diff --git a/include/modules/custom.hpp b/include/modules/custom.hpp index 6c17c6e4..a345a33b 100644 --- a/include/modules/custom.hpp +++ b/include/modules/custom.hpp @@ -35,6 +35,7 @@ class Custom : public ALabel { std::string id_; std::string alt_; std::string tooltip_; + std::string last_tooltip_markup_; const bool tooltip_format_enabled_; std::vector class_; int percentage_; diff --git a/include/modules/disk.hpp b/include/modules/disk.hpp index 1b4f3176..b576e19f 100644 --- a/include/modules/disk.hpp +++ b/include/modules/disk.hpp @@ -22,7 +22,7 @@ class Disk : public ALabel { std::string path_; std::string unit_; - float calc_specific_divisor(const std::string divisor); + float calc_specific_divisor(const std::string& divisor); }; } // namespace waybar::modules diff --git a/include/modules/dwl/tags.hpp b/include/modules/dwl/tags.hpp index 53dff989..856a35dd 100644 --- a/include/modules/dwl/tags.hpp +++ b/include/modules/dwl/tags.hpp @@ -12,23 +12,23 @@ namespace waybar::modules::dwl { class Tags : public waybar::AModule { public: - Tags(const std::string &, const waybar::Bar &, const Json::Value &); + Tags(const std::string&, const waybar::Bar&, const Json::Value&); virtual ~Tags(); // Handlers for wayland events void handle_view_tags(uint32_t tag, uint32_t state, uint32_t clients, uint32_t focused); void handle_primary_clicked(uint32_t tag); - bool handle_button_press(GdkEventButton *event_button, uint32_t tag); + bool handle_button_press(GdkEventButton* event_button, uint32_t tag); - struct zdwl_ipc_manager_v2 *status_manager_; - struct wl_seat *seat_; + struct zdwl_ipc_manager_v2* status_manager_; + struct wl_seat* seat_; private: - const waybar::Bar &bar_; + const waybar::Bar& bar_; Gtk::Box box_; std::vector buttons_; - struct zdwl_ipc_output_v2 *output_status_; + struct zdwl_ipc_output_v2* output_status_; }; } /* namespace waybar::modules::dwl */ diff --git a/include/modules/dwl/window.hpp b/include/modules/dwl/window.hpp index 43586399..5efd0abb 100644 --- a/include/modules/dwl/window.hpp +++ b/include/modules/dwl/window.hpp @@ -13,26 +13,26 @@ namespace waybar::modules::dwl { class Window : public AAppIconLabel, public sigc::trackable { public: - Window(const std::string &, const waybar::Bar &, const Json::Value &); + Window(const std::string&, const waybar::Bar&, const Json::Value&); ~Window(); void handle_layout(const uint32_t layout); - void handle_title(const char *title); - void handle_appid(const char *ppid); - void handle_layout_symbol(const char *layout_symbol); + void handle_title(const char* title); + void handle_appid(const char* ppid); + void handle_layout_symbol(const char* layout_symbol); void handle_frame(); - struct zdwl_ipc_manager_v2 *status_manager_; + struct zdwl_ipc_manager_v2* status_manager_; private: - const Bar &bar_; + const Bar& bar_; std::string title_; std::string appid_; std::string layout_symbol_; uint32_t layout_; - struct zdwl_ipc_output_v2 *output_status_; + struct zdwl_ipc_output_v2* output_status_; }; } // namespace waybar::modules::dwl diff --git a/include/modules/ext/workspace_manager.hpp b/include/modules/ext/workspace_manager.hpp new file mode 100644 index 00000000..f21ff26e --- /dev/null +++ b/include/modules/ext/workspace_manager.hpp @@ -0,0 +1,141 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include + +#include "AModule.hpp" +#include "bar.hpp" +#include "ext-workspace-v1-client-protocol.h" + +namespace waybar::modules::ext { + +class WorkspaceGroup; +class Workspace; + +class WorkspaceManager final : public AModule { + public: + WorkspaceManager(const std::string& id, const waybar::Bar& bar, const Json::Value& config); + ~WorkspaceManager() override; + void register_manager(wl_registry* registry, uint32_t name, uint32_t version); + void remove_workspace_group(uint32_t id); + void remove_workspace(uint32_t id); + void set_needs_sorting() { needs_sorting_ = true; } + + // wl events + void handle_workspace_group(ext_workspace_group_handle_v1* handle); + void handle_workspace(ext_workspace_handle_v1* handle); + void handle_done(); + void handle_finished(); + + // wl requests + void commit() const; + + private: + void update() override; + bool has_button(const Gtk::Button* button); + void sort_workspaces(); + void clear_buttons(); + void update_buttons(); + + static uint32_t group_global_id; + static uint32_t workspace_global_id; + uint32_t workspace_name = 0; + + bool sort_by_id_ = false; + bool sort_by_name_ = true; + bool sort_by_coordinates_ = false; + bool all_outputs_ = false; + + const waybar::Bar& bar_; + Gtk::Box box_; + + ext_workspace_manager_v1* ext_manager_ = nullptr; + std::vector> groups_; + std::vector> workspaces_; + + bool needs_sorting_ = false; +}; + +class WorkspaceGroup { + public: + WorkspaceGroup(WorkspaceManager& manager, ext_workspace_group_handle_v1* handle, uint32_t id); + ~WorkspaceGroup(); + + u_int32_t id() const { return id_; } + bool has_output(const wl_output* output); + bool has_workspace(const ext_workspace_handle_v1* workspace); + + // wl events + void handle_capabilities(uint32_t capabilities); + void handle_output_enter(wl_output* output); + void handle_output_leave(wl_output* output); + void handle_workspace_enter(ext_workspace_handle_v1* handle); + void handle_workspace_leave(ext_workspace_handle_v1* handle); + void handle_removed(); + + private: + WorkspaceManager& workspaces_manager_; + ext_workspace_group_handle_v1* ext_handle_; + uint32_t id_; + std::vector outputs_; + std::vector workspaces_; +}; + +class Workspace { + public: + Workspace(const Json::Value& config, WorkspaceManager& manager, ext_workspace_handle_v1* handle, + uint32_t id, const std::string& name); + ~Workspace(); + + ext_workspace_handle_v1* handle() const { return ext_handle_; } + u_int32_t id() const { return id_; } + std::string& workspace_id() { return workspace_id_; } + std::string& name() { return name_; } + std::vector& coordinates() { return coordinates_; } + Gtk::Button& button() { return button_; } + void update(); + + // wl events + void handle_id(const std::string& id); + void handle_name(const std::string& name); + void handle_coordinates(const std::vector& coordinates); + void handle_state(uint32_t state); + void handle_capabilities(uint32_t capabilities); + void handle_removed(); + + // gdk events + bool handle_clicked(const GdkEventButton* button) const; + + private: + bool has_state(uint32_t state) const { return (state_ & state) == state; } + std::string icon(); + + WorkspaceManager& workspace_manager_; + ext_workspace_handle_v1* ext_handle_ = nullptr; + uint32_t id_; + uint32_t state_ = 0; + std::string workspace_id_; + std::string name_; + std::vector coordinates_; + + bool active_only_ = false; + bool ignore_hidden_ = true; + std::string format_; + bool with_icon_ = false; + static std::map icon_map_; + std::string on_click_action_; + std::string on_click_middle_action_; + std::string on_click_right_action_; + + Gtk::Button button_; + Gtk::Box content_; + Gtk::Label label_; +}; + +} // namespace waybar::modules::ext diff --git a/include/modules/ext/workspace_manager_binding.hpp b/include/modules/ext/workspace_manager_binding.hpp new file mode 100644 index 00000000..20232970 --- /dev/null +++ b/include/modules/ext/workspace_manager_binding.hpp @@ -0,0 +1,10 @@ +#include "ext-workspace-v1-client-protocol.h" + +namespace waybar::modules::ext { +void add_registry_listener(void* data); +void add_workspace_listener(ext_workspace_handle_v1* workspace_handle, void* data); +void add_workspace_group_listener(ext_workspace_group_handle_v1* workspace_group_handle, + void* data); +ext_workspace_manager_v1* workspace_manager_bind(wl_registry* registry, uint32_t name, + uint32_t version, void* data); +} // namespace waybar::modules::ext diff --git a/include/modules/gamemode.hpp b/include/modules/gamemode.hpp index 69c0c3ae..89f66272 100644 --- a/include/modules/gamemode.hpp +++ b/include/modules/gamemode.hpp @@ -17,7 +17,7 @@ namespace waybar::modules { class Gamemode : public AModule { public: - Gamemode(const std::string &, const Json::Value &); + Gamemode(const std::string&, const Json::Value&); virtual ~Gamemode(); auto update() -> void override; @@ -26,20 +26,20 @@ class Gamemode : public AModule { const std::string DEFAULT_FORMAT = "{glyph}"; const std::string DEFAULT_FORMAT_ALT = "{glyph} {count}"; const std::string DEFAULT_TOOLTIP_FORMAT = "Games running: {count}"; - const std::string DEFAULT_GLYPH = ""; + const std::string DEFAULT_GLYPH = "󰊴"; - void appear(const Glib::RefPtr &connection, const Glib::ustring &name, - const Glib::ustring &name_owner); - void disappear(const Glib::RefPtr &connection, const Glib::ustring &name); - void prepareForSleep_cb(const Glib::RefPtr &connection, - const Glib::ustring &sender_name, const Glib::ustring &object_path, - const Glib::ustring &interface_name, const Glib::ustring &signal_name, - const Glib::VariantContainerBase ¶meters); - void notify_cb(const Glib::ustring &sender_name, const Glib::ustring &signal_name, - const Glib::VariantContainerBase &arguments); + void appear(const Glib::RefPtr& connection, const Glib::ustring& name, + const Glib::ustring& name_owner); + void disappear(const Glib::RefPtr& connection, const Glib::ustring& name); + void prepareForSleep_cb(const Glib::RefPtr& connection, + const Glib::ustring& sender_name, const Glib::ustring& object_path, + const Glib::ustring& interface_name, const Glib::ustring& signal_name, + const Glib::VariantContainerBase& parameters); + void notify_cb(const Glib::ustring& sender_name, const Glib::ustring& signal_name, + const Glib::VariantContainerBase& arguments); void getData(); - bool handleToggle(GdkEventButton *const &) override; + bool handleToggle(GdkEventButton* const&) override; // Config std::string format = DEFAULT_FORMAT; diff --git a/include/modules/gps.hpp b/include/modules/gps.hpp new file mode 100644 index 00000000..80df12ba --- /dev/null +++ b/include/modules/gps.hpp @@ -0,0 +1,40 @@ +#pragma once + +#include +#include + +#ifdef WANT_RFKILL +#include "util/rfkill.hpp" +#endif + +#include + +#include "ALabel.hpp" +#include "util/sleeper_thread.hpp" + +namespace waybar::modules { + +class Gps : public ALabel { + public: + Gps(const std::string&, const Json::Value&); + virtual ~Gps(); + auto update() -> void override; + + private: +#ifdef WANT_RFKILL + util::Rfkill rfkill_; +#endif + const std::string getFixModeName() const; + const std::string getFixModeString() const; + + const std::string getFixStatusString() const; + + util::SleeperThread thread_, gps_thread_; + gps_data_t gps_data_; + std::string state_; + + bool hideDisconnected = true; + bool hideNoFix = false; +}; + +} // namespace waybar::modules diff --git a/include/modules/hyprland/backend.hpp b/include/modules/hyprland/backend.hpp index cfd0b258..7c6369da 100644 --- a/include/modules/hyprland/backend.hpp +++ b/include/modules/hyprland/backend.hpp @@ -1,8 +1,10 @@ #pragma once +#include #include #include #include +#include #include #include #include @@ -17,9 +19,13 @@ class EventHandler { virtual ~EventHandler() = default; }; +/// If you want to use the Hyprland IPC, simply use IPC::inst() to get the singleton instance. +/// Do not create multiple instances. class IPC { + protected: + IPC(); // use IPC::inst() instead. + public: - IPC(); ~IPC(); static IPC& inst(); @@ -30,20 +36,33 @@ class IPC { Json::Value getSocket1JsonReply(const std::string& rq); static std::filesystem::path getSocketFolder(const char* instanceSig); + /// Dispatch a Hyprland command. Automatically uses the correct protocol + /// (legacy text or Lua-based) depending on the running Hyprland version. + static std::string dispatch(const std::string& dispatcher, const std::string& arg); + + /// Build a Lua-format dispatch command string. + static std::string buildLuaDispatch(const std::string& dispatcher, const std::string& arg); + protected: static std::filesystem::path socketFolder_; + /// Detect whether the running Hyprland uses the Lua-based IPC protocol. + /// Returns true for Hyprland >= 0.54 (Lua config), false for older versions. + static bool isLuaProtocol(); + + static std::optional s_luaProtocolDetected_; // cached detection result + private: void socketListener(); void parseIPC(const std::string&); std::thread ipcThread_; std::mutex callbackMutex_; + std::mutex socketMutex_; util::JsonParser parser_; std::list> callbacks_; - int socketfd_; // the hyprland socket file descriptor - bool running_ = true; + int socketfd_ = -1; // the hyprland socket file descriptor + pid_t socketOwnerPid_ = -1; + std::atomic running_ = true; // the ipcThread will stop running when this is false }; - -inline bool modulesReady = false; }; // namespace waybar::modules::hyprland diff --git a/include/modules/hyprland/submap.hpp b/include/modules/hyprland/submap.hpp index 7e3425ef..0dcb5d5a 100644 --- a/include/modules/hyprland/submap.hpp +++ b/include/modules/hyprland/submap.hpp @@ -26,6 +26,7 @@ class Submap : public waybar::ALabel, public EventHandler { const Bar& bar_; util::JsonParser parser_; std::string submap_; + std::string prev_submap_; bool always_on_ = false; std::string default_submap_ = "Default"; diff --git a/include/modules/hyprland/window.hpp b/include/modules/hyprland/window.hpp index 2be64594..9725d33a 100644 --- a/include/modules/hyprland/window.hpp +++ b/include/modules/hyprland/window.hpp @@ -20,8 +20,8 @@ class Window : public waybar::AAppIconLabel, public EventHandler { private: struct Workspace { - int id; - int windows; + int id = 0; + int windows = 0; std::string last_window; std::string last_window_title; @@ -29,14 +29,14 @@ class Window : public waybar::AAppIconLabel, public EventHandler { }; struct WindowData { - bool floating; + bool floating = false; int monitor = -1; std::string class_name; std::string initial_class_name; std::string title; std::string initial_title; - bool fullscreen; - bool grouped; + bool fullscreen = false; + bool grouped = false; static auto parse(const Json::Value&) -> WindowData; }; @@ -47,7 +47,7 @@ class Window : public waybar::AAppIconLabel, public EventHandler { void queryActiveWorkspace(); void setClass(const std::string&, bool enable); - bool separateOutputs_; + bool separateOutputs_ = false; std::mutex mutex_; const Bar& bar_; util::JsonParser parser_; @@ -55,11 +55,11 @@ class Window : public waybar::AAppIconLabel, public EventHandler { Workspace workspace_; std::string soloClass_; std::string lastSoloClass_; - bool solo_; - bool allFloating_; - bool swallowing_; - bool fullscreen_; - bool focused_; + bool solo_ = false; + bool allFloating_ = false; + bool swallowing_ = false; + bool fullscreen_ = false; + bool focused_ = false; IPC& m_ipc; }; diff --git a/include/modules/hyprland/windowcount.hpp b/include/modules/hyprland/windowcount.hpp new file mode 100644 index 00000000..7c86fb3e --- /dev/null +++ b/include/modules/hyprland/windowcount.hpp @@ -0,0 +1,41 @@ +#pragma once + +#include + +#include + +#include "AAppIconLabel.hpp" +#include "bar.hpp" +#include "modules/hyprland/backend.hpp" + +namespace waybar::modules::hyprland { + +class WindowCount : public waybar::AAppIconLabel, public EventHandler { + public: + WindowCount(const std::string&, const waybar::Bar&, const Json::Value&); + ~WindowCount() override; + + auto update() -> void override; + + private: + struct Workspace { + int id; + int windows; + bool hasfullscreen; + static auto parse(const Json::Value& value) -> Workspace; + }; + + auto getActiveWorkspace(const std::string&) -> Workspace; + auto getActiveWorkspace() -> Workspace; + void onEvent(const std::string& ev) override; + void queryActiveWorkspace(); + void setClass(const std::string&, bool enable); + + bool separateOutputs_; + std::mutex mutex_; + const Bar& bar_; + Workspace workspace_; + IPC& m_ipc; +}; + +} // namespace waybar::modules::hyprland diff --git a/include/modules/hyprland/windowcreationpayload.hpp b/include/modules/hyprland/windowcreationpayload.hpp index 45229ed4..906be805 100644 --- a/include/modules/hyprland/windowcreationpayload.hpp +++ b/include/modules/hyprland/windowcreationpayload.hpp @@ -26,34 +26,49 @@ namespace waybar::modules::hyprland { class Workspaces; +struct WindowRepr { + std::string address; + std::string window_class; + std::string window_title; + std::string repr_rewrite; + bool isActive = false; + + public: + bool empty() const { return address.empty(); } + void setActive(bool value) { isActive = value; } +}; + class WindowCreationPayload { public: - WindowCreationPayload(std::string workspace_name, WindowAddress window_address, - std::string window_repr); - WindowCreationPayload(std::string workspace_name, WindowAddress window_address, - std::string window_class, std::string window_title); + WindowCreationPayload(const std::string& workspace_name, WindowAddress window_address, + WindowRepr window_repr); + WindowCreationPayload(const std::string& workspace_name, WindowAddress window_address, + const std::string& window_class, const std::string& window_title, + bool is_active); WindowCreationPayload(Json::Value const& client_data); int incrementTimeSpentUncreated(); bool isEmpty(Workspaces& workspace_manager); bool reprIsReady() const { return std::holds_alternative(m_window); } - std::string repr(Workspaces& workspace_manager); + WindowRepr repr(Workspaces& workspace_manager); + void setActive(bool value) { m_isActive = value; } std::string getWorkspaceName() const { return m_workspaceName; } WindowAddress getAddress() const { return m_windowAddress; } - void moveToWorksace(std::string& new_workspace_name); + void moveToWorkspace(std::string& new_workspace_name); private: void clearAddr(); void clearWorkspaceName(); - using Repr = std::string; + using Repr = WindowRepr; using ClassAndTitle = std::pair; std::variant m_window; WindowAddress m_windowAddress; std::string m_workspaceName; + bool m_isActive = false; int m_timeSpentUncreated = 0; }; diff --git a/include/modules/hyprland/workspace.hpp b/include/modules/hyprland/workspace.hpp index 3dedba4c..a4cccee6 100644 --- a/include/modules/hyprland/workspace.hpp +++ b/include/modules/hyprland/workspace.hpp @@ -30,6 +30,7 @@ class Workspace { public: explicit Workspace(const Json::Value& workspace_data, Workspaces& workspace_manager, const Json::Value& clients_data = Json::Value::nullRef); + ~Workspace(); std::string& selectIcon(std::map& icons_map); Gtk::Button& button() { return m_button; }; @@ -42,10 +43,18 @@ class Workspace { bool isPersistentConfig() const { return m_isPersistentConfig; }; bool isPersistentRule() const { return m_isPersistentRule; }; bool isVisible() const { return m_isVisible; }; - bool isEmpty() const { return m_windows == 0; }; bool isUrgent() const { return m_isUrgent; }; bool handleClicked(GdkEventButton* bt) const; + + bool handleEnter(GdkEventCrossing* event); + bool handleLeave(GdkEventCrossing* event); + + void startHoverCheck(); + void stopHoverCheck(); + bool syncHoverClass(); + bool pointerInsideButton(); + void setActive(bool value = true) { m_isActive = value; }; void setPersistentRule(bool value = true) { m_isPersistentRule = value; }; void setPersistentConfig(bool value = true) { m_isPersistentConfig = value; }; @@ -54,15 +63,18 @@ class Workspace { void setWindows(uint value) { m_windows = value; }; void setName(std::string const& value) { m_name = value; }; void setOutput(std::string const& value) { m_output = value; }; - bool containsWindow(WindowAddress const& addr) const { return m_windowMap.contains(addr); } - void insertWindow(WindowCreationPayload create_window_paylod); - std::string removeWindow(WindowAddress const& addr); + bool containsWindow(WindowAddress const& addr) const { + return std::ranges::any_of(m_windowMap, + [&addr](const auto& window) { return window.address == addr; }); + }; + void insertWindow(WindowCreationPayload create_window_payload); void initializeWindowMap(const Json::Value& clients_data); + void setActiveWindow(WindowAddress const& addr); - bool onWindowOpened(WindowCreationPayload const& create_window_paylod); - std::optional closeWindow(WindowAddress const& addr); + bool onWindowOpened(WindowCreationPayload const& create_window_payload); + std::optional closeWindow(WindowAddress const& addr); - void update(const std::string& format, const std::string& icon); + void update(const std::string& workspace_icon); private: Workspaces& m_workspaceManager; @@ -78,11 +90,19 @@ class Workspace { bool m_isUrgent = false; bool m_isVisible = false; - std::map m_windowMap; + sigc::connection m_hoverCheckConnection; + + std::vector m_windowMap; Gtk::Button m_button; Gtk::Box m_content; - Gtk::Label m_label; + Gtk::Label m_labelBefore; + Gtk::Label m_labelAfter; + + bool isEmpty() const; + void updateTaskbar(const std::string& workspace_icon); + bool handleClick(const GdkEventButton* event_button, WindowAddress const& addr) const; + bool shouldSkipWindow(const WindowRepr& window_repr) const; IPC& m_ipc; }; diff --git a/include/modules/hyprland/workspaces.hpp b/include/modules/hyprland/workspaces.hpp index 7618f35c..ffcbd38e 100644 --- a/include/modules/hyprland/workspaces.hpp +++ b/include/modules/hyprland/workspaces.hpp @@ -1,8 +1,10 @@ #pragma once #include +#include #include #include +#include #include #include @@ -18,6 +20,7 @@ #include "modules/hyprland/windowcreationpayload.hpp" #include "modules/hyprland/workspace.hpp" #include "util/enum.hpp" +#include "util/icon_loader.hpp" #include "util/regex_collection.hpp" using WindowAddress = std::string; @@ -38,19 +41,37 @@ class Workspaces : public AModule, public EventHandler { auto activeOnly() const -> bool { return m_activeOnly; } auto hideActive() const -> bool { return m_hideActive; } auto specialVisibleOnly() const -> bool { return m_specialVisibleOnly; } + auto persistentOnly() const -> bool { return m_persistentOnly; } auto moveToMonitor() const -> bool { return m_moveToMonitor; } + auto enableTaskbar() const -> bool { return m_enableTaskbar; } + auto taskbarWithIcon() const -> bool { return m_taskbarWithIcon; } + auto barScroll() const -> bool { return m_barScroll; } auto getBarOutput() const -> std::string { return m_bar.output->name; } + auto formatBefore() const -> std::string { return m_formatBefore; } + auto formatAfter() const -> std::string { return m_formatAfter; } + auto taskbarFormatBefore() const -> std::string { return m_taskbarFormatBefore; } + auto taskbarFormatAfter() const -> std::string { return m_taskbarFormatAfter; } + auto taskbarIconSize() const -> int { return m_taskbarIconSize; } + auto taskbarOrientation() const -> Gtk::Orientation { return m_taskbarOrientation; } + auto taskbarReverseDirection() const -> bool { return m_taskbarReverseDirection; } + auto onClickWindow() const -> std::string { return m_onClickWindow; } + auto getIgnoredWindows() const -> std::vector { return m_ignoreWindows; } - std::string getRewrite(std::string window_class, std::string window_title); + enum class ActiveWindowPosition { NONE, FIRST, LAST }; + auto activeWindowPosition() const -> ActiveWindowPosition { return m_activeWindowPosition; } + + std::string getRewrite(const std::string& window_class, const std::string& window_title); std::string& getWindowSeparator() { return m_formatWindowSeparator; } bool isWorkspaceIgnored(std::string const& workspace_name); bool windowRewriteConfigUsesTitle() const { return m_anyWindowRewriteRuleUsesTitle; } + const IconLoader& iconLoader() const { return m_iconLoader; } private: void onEvent(const std::string& e) override; void updateWindowCount(); + void sortSpecialCentered(); void sortWorkspaces(); void createWorkspace(Json::Value const& workspace_data, Json::Value const& clients_data = Json::Value::nullRef); @@ -69,6 +90,7 @@ class Workspaces : public AModule, public EventHandler { auto populateIgnoreWorkspacesConfig(const Json::Value& config) -> void; auto populateFormatWindowSeparatorConfig(const Json::Value& config) -> void; auto populateWindowRewriteConfig(const Json::Value& config) -> void; + auto populateWorkspaceTaskbarConfig(const Json::Value& config) -> void; void registerIpc(); @@ -91,6 +113,7 @@ class Workspaces : public AModule, public EventHandler { void onWindowMoved(std::string const& payload); void onWindowTitleEvent(std::string const& payload); + void onActiveWindowChanged(WindowAddress const& payload); void onConfigReloaded(); @@ -102,6 +125,8 @@ class Workspaces : public AModule, public EventHandler { static std::pair splitDoublePayload(std::string const& payload); static std::tuple splitTriplePayload( std::string const& payload); + // scroll events + bool handleScroll(GdkEventScroll* e) override; // Update methods void doUpdate(); @@ -124,23 +149,27 @@ class Workspaces : public AModule, public EventHandler { bool m_activeOnly = false; bool m_hideActive = false; bool m_specialVisibleOnly = false; + bool m_persistentOnly = false; bool m_moveToMonitor = false; + bool m_barScroll = false; Json::Value m_persistentWorkspaceConfig; // Map for windows stored in workspaces not present in the current bar. // This happens when the user has multiple monitors (hence, multiple bars) - // and doesn't share windows accross bars (a.k.a `all-outputs` = false) - std::map m_orphanWindowMap; + // and doesn't share windows across bars (a.k.a `all-outputs` = false) + std::map> m_orphanWindowMap; - enum class SortMethod { ID, NAME, NUMBER, DEFAULT }; + enum class SortMethod { ID, NAME, NUMBER, SPECIAL_CENTERED, DEFAULT }; util::EnumParser m_enumParser; SortMethod m_sortBy = SortMethod::DEFAULT; std::map m_sortMap = {{"ID", SortMethod::ID}, {"NAME", SortMethod::NAME}, {"NUMBER", SortMethod::NUMBER}, + {"SPECIAL-CENTERED", SortMethod::SPECIAL_CENTERED}, {"DEFAULT", SortMethod::DEFAULT}}; - std::string m_format; + std::string m_formatBefore; + std::string m_formatAfter; std::map m_iconsMap; util::RegexCollection m_windowRewriteRules; @@ -156,11 +185,33 @@ class Workspaces : public AModule, public EventHandler { std::vector m_workspacesToRemove; std::vector m_windowsToCreate; + IconLoader m_iconLoader; + bool m_enableTaskbar = false; + bool m_updateActiveWindow = false; + bool m_taskbarWithIcon = false; + bool m_taskbarWithTitle = false; + std::string m_taskbarFormatBefore; + std::string m_taskbarFormatAfter; + int m_taskbarIconSize = 16; + Gtk::Orientation m_taskbarOrientation = Gtk::ORIENTATION_HORIZONTAL; + bool m_taskbarReverseDirection = false; + util::EnumParser m_activeWindowEnumParser; + ActiveWindowPosition m_activeWindowPosition = ActiveWindowPosition::NONE; + std::map m_activeWindowPositionMap = { + {"NONE", ActiveWindowPosition::NONE}, + {"FIRST", ActiveWindowPosition::FIRST}, + {"LAST", ActiveWindowPosition::LAST}, + }; + std::string m_onClickWindow; + std::string m_currentActiveWindowAddress; + std::vector m_ignoreWorkspaces; + std::vector m_ignoreWindows; std::mutex m_mutex; const Bar& m_bar; Gtk::Box m_box; + sigc::connection m_scrollEventConnection_; IPC& m_ipc; }; diff --git a/include/modules/image.hpp b/include/modules/image.hpp index 7c0d014f..510dad94 100644 --- a/include/modules/image.hpp +++ b/include/modules/image.hpp @@ -31,7 +31,7 @@ class Image : public AModule { std::string path_; std::string tooltip_; int size_; - int interval_; + std::chrono::milliseconds interval_; util::command::res output_; util::SleeperThread thread_; diff --git a/include/modules/jack.hpp b/include/modules/jack.hpp index 452c43a3..5c30739e 100644 --- a/include/modules/jack.hpp +++ b/include/modules/jack.hpp @@ -13,7 +13,7 @@ namespace waybar::modules { class JACK : public ALabel { public: - JACK(const std::string &, const Json::Value &); + JACK(const std::string&, const Json::Value&); virtual ~JACK() = default; auto update() -> void override; @@ -25,7 +25,7 @@ class JACK : public ALabel { private: std::string JACKState(); - jack_client_t *client_; + jack_client_t* client_; jack_nframes_t bufsize_; jack_nframes_t samplerate_; unsigned int xruns_; @@ -38,7 +38,7 @@ class JACK : public ALabel { } // namespace waybar::modules -int bufSizeCallback(jack_nframes_t size, void *obj); -int sampleRateCallback(jack_nframes_t rate, void *obj); -int xrunCallback(void *obj); -void shutdownCallback(void *obj); +int bufSizeCallback(jack_nframes_t size, void* obj); +int sampleRateCallback(jack_nframes_t rate, void* obj); +int xrunCallback(void* obj); +void shutdownCallback(void* obj); diff --git a/include/modules/keyboard_state.hpp b/include/modules/keyboard_state.hpp index be90eee4..db7f2550 100644 --- a/include/modules/keyboard_state.hpp +++ b/include/modules/keyboard_state.hpp @@ -3,6 +3,7 @@ #include #include +#include #include #include @@ -41,6 +42,7 @@ class KeyboardState : public AModule { struct libinput* libinput_; std::unordered_map libinput_devices_; + std::mutex devices_mutex_; // protects libinput_devices_ std::set binding_keys; util::SleeperThread libinput_thread_, hotplug_thread_; diff --git a/include/modules/memory.hpp b/include/modules/memory.hpp index 3b6342b3..0e405187 100644 --- a/include/modules/memory.hpp +++ b/include/modules/memory.hpp @@ -22,6 +22,8 @@ class Memory : public ALabel { std::unordered_map meminfo_; util::SleeperThread thread_; + + std::string unit_; }; } // namespace waybar::modules diff --git a/include/modules/mpd/mpd.hpp b/include/modules/mpd/mpd.hpp index 32d526e9..554f2977 100644 --- a/include/modules/mpd/mpd.hpp +++ b/include/modules/mpd/mpd.hpp @@ -33,6 +33,7 @@ class MPD : public ALabel { detail::unique_status status_; mpd_state state_; detail::unique_song song_; + std::string ellipsis_; public: MPD(const std::string&, const Json::Value&); @@ -44,7 +45,11 @@ class MPD : public ALabel { std::string getFilename() const; void setLabel(); std::string getStateIcon() const; - std::string getOptionIcon(std::string optionName, bool activated) const; + std::string getOptionIcon(const std::string& optionName, bool activated) const; + std::string getArtistStr(bool truncated) const; + std::string getAlbumArtistStr(bool truncated) const; + std::string getAlbumStr(bool truncated) const; + std::string getTitleStr(bool truncated) const; // GUI-side methods bool handlePlayPause(GdkEventButton* const&); @@ -54,7 +59,6 @@ class MPD : public ALabel { void tryConnect(); void checkErrors(mpd_connection* conn); void fetchState(); - void queryMPD(); inline bool stopped() const { return connection_ && state_ == MPD_STATE_STOP; } inline bool playing() const { return connection_ && state_ == MPD_STATE_PLAY; } diff --git a/include/modules/mpd/state.hpp b/include/modules/mpd/state.hpp index 2c9071b4..0624c196 100644 --- a/include/modules/mpd/state.hpp +++ b/include/modules/mpd/state.hpp @@ -197,7 +197,6 @@ class Context { 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; diff --git a/include/modules/mpd/state.inl.hpp b/include/modules/mpd/state.inl.hpp index 895970e6..cf4a4beb 100644 --- a/include/modules/mpd/state.inl.hpp +++ b/include/modules/mpd/state.inl.hpp @@ -1,13 +1,14 @@ #pragma once namespace detail { +using namespace std::literals::chrono_literals; inline bool Context::is_connected() const { return mpd_module_->connection_ != nullptr; } inline bool Context::is_playing() const { return mpd_module_->playing(); } 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(); } +constexpr inline std::size_t Context::interval() const { return mpd_module_->interval_ / 1s; } 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_; } @@ -15,7 +16,6 @@ constexpr inline mpd_state Context::state() const { return mpd_module_->state_; 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(); } inline void Context::fetchState() const { mpd_module_->fetchState(); } inline void Context::emit() const { mpd_module_->emit(); } diff --git a/include/modules/mpris/mpris.hpp b/include/modules/mpris/mpris.hpp index ad4dac1e..a33db4d2 100644 --- a/include/modules/mpris/mpris.hpp +++ b/include/modules/mpris/mpris.hpp @@ -78,6 +78,7 @@ class Mpris : public ALabel { PlayerctlPlayerManager* manager; PlayerctlPlayer* player; + PlayerctlPlayer* last_active_player_ = nullptr; std::string lastStatus; std::string lastPlayer; diff --git a/include/modules/network.hpp b/include/modules/network.hpp index 5fd0c180..66fc6d04 100644 --- a/include/modules/network.hpp +++ b/include/modules/network.hpp @@ -9,6 +9,7 @@ #include #include +#include #include "ALabel.hpp" #include "util/sleeper_thread.hpp" @@ -27,8 +28,8 @@ class Network : public ALabel { auto update() -> void override; private: - static const uint8_t MAX_RETRY = 5; - static const uint8_t EPOLL_MAX = 200; + static const uint8_t MAX_RETRY{5}; + static const uint8_t EPOLL_MAX{200}; static int handleEvents(struct nl_msg*, void*); static int handleEventsDone(struct nl_msg*, void*); @@ -44,44 +45,47 @@ class Network : public ALabel { void parseFreq(struct nlattr**); void parseBssid(struct nlattr**); bool associatedOrJoined(struct nlattr**); - bool checkInterface(std::string name); + bool matchInterface(const std::string& ifname, const std::vector& altnames, + std::string& matched) const; auto getInfo() -> void; const std::string getNetworkState() const; void clearIface(); - bool wildcardMatch(const std::string& pattern, const std::string& text) const; std::optional> readBandwidthUsage(); - int ifid_; - ip_addr_pref addr_pref_; - struct sockaddr_nl nladdr_ = {0}; - struct nl_sock* sock_ = nullptr; - struct nl_sock* ev_sock_ = nullptr; - int efd_; - int ev_fd_; - int nl80211_id_; + int ifid_{-1}; + ip_addr_pref addr_pref_{ip_addr_pref::IPV4}; + struct sockaddr_nl nladdr_{0}; + struct nl_sock* sock_{nullptr}; + struct nl_sock* ev_sock_{nullptr}; + int efd_{-1}; + int ev_fd_{-1}; + int nl80211_id_{-1}; std::mutex mutex_; - bool want_route_dump_; - bool want_link_dump_; - bool want_addr_dump_; - bool dump_in_progress_; - bool is_p2p_; + bool want_route_dump_{false}; + bool want_link_dump_{false}; + bool want_addr_dump_{false}; + bool dump_in_progress_{false}; + bool is_p2p_{false}; - unsigned long long bandwidth_down_total_; - unsigned long long bandwidth_up_total_; + unsigned long long bandwidth_down_total_{0}; + unsigned long long bandwidth_up_total_{0}; + unsigned long long bandwidth_down_prev_{0}; + unsigned long long bandwidth_up_prev_{0}; + std::chrono::steady_clock::time_point bandwidth_last_sample_time_; std::string state_; std::string essid_; std::string bssid_; - bool carrier_; + bool carrier_{false}; std::string ifname_; std::string ipaddr_; std::string ipaddr6_; std::string gwaddr_; std::string netmask_; std::string netmask6_; - int cidr_; - int cidr6_; + int cidr_{0}; + int cidr6_{0}; int32_t signal_strength_dbm_; uint8_t signal_strength_; std::string signal_strength_app_; @@ -90,9 +94,9 @@ class Network : public ALabel { util::SleeperThread thread_; util::SleeperThread thread_timer_; #ifdef WANT_RFKILL - util::Rfkill rfkill_; + util::Rfkill rfkill_{RFKILL_TYPE_WLAN}; #endif - float frequency_; + float frequency_{0}; }; } // namespace waybar::modules diff --git a/include/modules/niri/backend.hpp b/include/modules/niri/backend.hpp index 42b9ff7f..07be039a 100644 --- a/include/modules/niri/backend.hpp +++ b/include/modules/niri/backend.hpp @@ -17,7 +17,7 @@ class EventHandler { class IPC { public: - IPC() { startIPC(); } + IPC(); void registerForIPC(const std::string& ev, EventHandler* ev_handler); void unregisterForIPC(EventHandler* handler); diff --git a/include/modules/niri/language.hpp b/include/modules/niri/language.hpp index 42b90ac4..cff2b352 100644 --- a/include/modules/niri/language.hpp +++ b/include/modules/niri/language.hpp @@ -10,13 +10,13 @@ namespace waybar::modules::niri { class Language : public ALabel, public EventHandler { public: - Language(const std::string &, const Bar &, const Json::Value &); + Language(const std::string&, const Bar&, const Json::Value&); ~Language() override; void update() override; private: void updateFromIPC(); - void onEvent(const Json::Value &ev) override; + void onEvent(const Json::Value& ev) override; void doUpdate(); struct Layout { @@ -26,13 +26,14 @@ class Language : public ALabel, public EventHandler { std::string short_description; }; - static Layout getLayout(const std::string &fullName); + static Layout getLayout(const std::string& fullName); std::mutex mutex_; - const Bar &bar_; + const Bar& bar_; std::vector layouts_; unsigned current_idx_; + std::string last_short_name_; }; } // namespace waybar::modules::niri diff --git a/include/modules/niri/window.hpp b/include/modules/niri/window.hpp index 909ae6f0..6be4686e 100644 --- a/include/modules/niri/window.hpp +++ b/include/modules/niri/window.hpp @@ -11,16 +11,16 @@ namespace waybar::modules::niri { class Window : public AAppIconLabel, public EventHandler { public: - Window(const std::string &, const Bar &, const Json::Value &); + Window(const std::string&, const Bar&, const Json::Value&); ~Window() override; void update() override; private: - void onEvent(const Json::Value &ev) override; + void onEvent(const Json::Value& ev) override; void doUpdate(); - void setClass(const std::string &className, bool enable); + void setClass(const std::string& className, bool enable); - const Bar &bar_; + const Bar& bar_; std::string oldAppId_; }; diff --git a/include/modules/niri/workspaces.hpp b/include/modules/niri/workspaces.hpp index a6850ed1..08986412 100644 --- a/include/modules/niri/workspaces.hpp +++ b/include/modules/niri/workspaces.hpp @@ -11,17 +11,17 @@ namespace waybar::modules::niri { class Workspaces : public AModule, public EventHandler { public: - Workspaces(const std::string &, const Bar &, const Json::Value &); + Workspaces(const std::string&, const Bar&, const Json::Value&); ~Workspaces() override; void update() override; private: - void onEvent(const Json::Value &ev) override; + void onEvent(const Json::Value& ev) override; void doUpdate(); - Gtk::Button &addButton(const Json::Value &ws); - std::string getIcon(const std::string &value, const Json::Value &ws); + Gtk::Button& addButton(const Json::Value& ws); + std::string getIcon(const std::string& value, const Json::Value& ws); - const Bar &bar_; + const Bar& bar_; Gtk::Box box_; // Map from niri workspace id to button. std::unordered_map buttons_; diff --git a/include/modules/power_profiles_daemon.hpp b/include/modules/power_profiles_daemon.hpp index a2bd3858..b2436171 100644 --- a/include/modules/power_profiles_daemon.hpp +++ b/include/modules/power_profiles_daemon.hpp @@ -16,15 +16,15 @@ struct Profile { class PowerProfilesDaemon : public ALabel { public: - PowerProfilesDaemon(const std::string &, const Json::Value &); + PowerProfilesDaemon(const std::string&, const Json::Value&); auto update() -> void override; - void profileChangedCb(const Gio::DBus::Proxy::MapChangedProperties &, - const std::vector &); - void busConnectedCb(Glib::RefPtr &r); - void getAllPropsCb(Glib::RefPtr &r); - void setPropCb(Glib::RefPtr &r); + void profileChangedCb(const Gio::DBus::Proxy::MapChangedProperties&, + const std::vector&); + void busConnectedCb(Glib::RefPtr& r); + void getAllPropsCb(Glib::RefPtr& r); + void setPropCb(Glib::RefPtr& r); void populateInitState(); - bool handleToggle(GdkEventButton *const &e) override; + bool handleToggle(GdkEventButton* const& e) override; private: // True if we're connected to the dbug interface. False if we're @@ -32,7 +32,7 @@ class PowerProfilesDaemon : public ALabel { bool connected_; // Look for a profile name in the list of available profiles and // switch activeProfile_ to it. - void switchToProfile(std::string const &); + void switchToProfile(std::string const&); // Used to toggle/display the profiles std::vector availableProfiles_; // Points to the active profile in the profiles list diff --git a/include/modules/privacy/privacy.hpp b/include/modules/privacy/privacy.hpp index 6179098c..729fcc6a 100644 --- a/include/modules/privacy/privacy.hpp +++ b/include/modules/privacy/privacy.hpp @@ -13,24 +13,27 @@ namespace waybar::modules::privacy { class Privacy : public AModule { public: - Privacy(const std::string &, const Json::Value &, Gtk::Orientation, const std::string &pos); + Privacy(const std::string&, const Json::Value&, Gtk::Orientation, const std::string& pos); auto update() -> void override; void onPrivacyNodesChanged(); private: - std::list nodes_screenshare; // Screen is being shared - std::list nodes_audio_in; // Application is using the microphone - std::list nodes_audio_out; // Application is outputting audio + std::list nodes_screenshare; // Screen is being shared + std::list nodes_audio_in; // Application is using the microphone + std::list nodes_audio_out; // Application is outputting audio std::mutex mutex_; sigc::connection visibility_conn; // Config Gtk::Box box_; + std::vector modules_; uint iconSpacing = 4; uint iconSize = 20; uint transition_duration = 250; + std::set> ignore; + bool ignore_monitor = true; std::shared_ptr backend = nullptr; }; diff --git a/include/modules/privacy/privacy_item.hpp b/include/modules/privacy/privacy_item.hpp index f5f572c0..31e200e3 100644 --- a/include/modules/privacy/privacy_item.hpp +++ b/include/modules/privacy/privacy_item.hpp @@ -16,16 +16,16 @@ namespace waybar::modules::privacy { class PrivacyItem : public Gtk::Revealer { public: - PrivacyItem(const Json::Value &config_, enum PrivacyNodeType privacy_type_, - std::list *nodes, Gtk::Orientation orientation, - const std::string &pos, const uint icon_size, const uint transition_duration); + PrivacyItem(const Json::Value& config_, enum PrivacyNodeType privacy_type_, + std::list* nodes, Gtk::Orientation orientation, + const std::string& pos, const uint icon_size, const uint transition_duration); enum PrivacyNodeType privacy_type; void set_in_use(bool in_use); private: - std::list *nodes; + std::list* nodes; sigc::connection signal_conn; diff --git a/include/modules/pulseaudio_slider.hpp b/include/modules/pulseaudio_slider.hpp index 3ef44684..597b3cc8 100644 --- a/include/modules/pulseaudio_slider.hpp +++ b/include/modules/pulseaudio_slider.hpp @@ -6,11 +6,6 @@ #include "util/audio_backend.hpp" namespace waybar::modules { -enum class PulseaudioSliderTarget { - Sink, - Source, -}; - class PulseaudioSlider : public ASlider { public: PulseaudioSlider(const std::string&, const Json::Value&); @@ -21,7 +16,15 @@ class PulseaudioSlider : public ASlider { private: std::shared_ptr backend = nullptr; - PulseaudioSliderTarget target = PulseaudioSliderTarget::Sink; + util::PulseaudioTarget target = util::PulseaudioTarget::Sink; + + bool zero_on_mute = true; + bool unmute_on_volume_change = true; + // zero_on_mute and unmute_on_volume_change default to true + // in order to maintain previous behaviour when using a + // config in which these values are undefined + + bool previously_muted = false; }; -} // namespace waybar::modules \ No newline at end of file +} // namespace waybar::modules diff --git a/include/modules/river/layout.hpp b/include/modules/river/layout.hpp index dc78ee20..3486472e 100644 --- a/include/modules/river/layout.hpp +++ b/include/modules/river/layout.hpp @@ -10,24 +10,25 @@ namespace waybar::modules::river { class Layout : public waybar::ALabel { public: - Layout(const std::string &, const waybar::Bar &, const Json::Value &); + Layout(const std::string&, const waybar::Bar&, const Json::Value&); virtual ~Layout(); // Handlers for wayland events - void handle_name(const char *name); + void handle_name(const char* name); void handle_clear(); - void handle_focused_output(struct wl_output *output); - void handle_unfocused_output(struct wl_output *output); + void handle_focused_output(struct wl_output* output); + void handle_unfocused_output(struct wl_output* output); - struct zriver_status_manager_v1 *status_manager_; - struct wl_seat *seat_; + struct zriver_status_manager_v1* status_manager_; + struct wl_seat* seat_; private: - const waybar::Bar &bar_; - struct wl_output *output_; // stores the output this module belongs to - struct wl_output *focused_output_; // stores the currently focused output - struct zriver_output_status_v1 *output_status_; - struct zriver_seat_status_v1 *seat_status_; + const waybar::Bar& bar_; + std::string name_; + struct wl_output* output_; // stores the output this module belongs to + struct wl_output* focused_output_; // stores the currently focused output + struct zriver_output_status_v1* output_status_; + struct zriver_seat_status_v1* seat_status_; }; } /* namespace waybar::modules::river */ diff --git a/include/modules/river/mode.hpp b/include/modules/river/mode.hpp index 246cecae..91585309 100644 --- a/include/modules/river/mode.hpp +++ b/include/modules/river/mode.hpp @@ -10,19 +10,19 @@ namespace waybar::modules::river { class Mode : public waybar::ALabel { public: - Mode(const std::string &, const waybar::Bar &, const Json::Value &); + Mode(const std::string&, const waybar::Bar&, const Json::Value&); virtual ~Mode(); // Handlers for wayland events - void handle_mode(const char *mode); + void handle_mode(const char* mode); - struct zriver_status_manager_v1 *status_manager_; - struct wl_seat *seat_; + struct zriver_status_manager_v1* status_manager_; + struct wl_seat* seat_; private: - const waybar::Bar &bar_; + const waybar::Bar& bar_; std::string mode_; - struct zriver_seat_status_v1 *seat_status_; + struct zriver_seat_status_v1* seat_status_; }; } /* namespace waybar::modules::river */ diff --git a/include/modules/river/tags.hpp b/include/modules/river/tags.hpp index fb3eefaa..386ddecf 100644 --- a/include/modules/river/tags.hpp +++ b/include/modules/river/tags.hpp @@ -13,26 +13,27 @@ namespace waybar::modules::river { class Tags : public waybar::AModule { public: - Tags(const std::string &, const waybar::Bar &, const Json::Value &); + Tags(const std::string&, const waybar::Bar&, const Json::Value&); virtual ~Tags(); // Handlers for wayland events void handle_focused_tags(uint32_t tags); - void handle_view_tags(struct wl_array *tags); + void handle_view_tags(struct wl_array* tags); void handle_urgent_tags(uint32_t tags); + void handle_show(); void handle_primary_clicked(uint32_t tag); - bool handle_button_press(GdkEventButton *event_button, uint32_t tag); + bool handle_button_press(GdkEventButton* event_button, uint32_t tag); - struct zriver_status_manager_v1 *status_manager_; - struct zriver_control_v1 *control_; - struct wl_seat *seat_; + struct zriver_status_manager_v1* status_manager_; + struct zriver_control_v1* control_; + struct wl_seat* seat_; private: - const waybar::Bar &bar_; + const waybar::Bar& bar_; Gtk::Box box_; std::vector buttons_; - struct zriver_output_status_v1 *output_status_; + struct zriver_output_status_v1* output_status_; }; } /* namespace waybar::modules::river */ diff --git a/include/modules/river/window.hpp b/include/modules/river/window.hpp index bf29ebbf..0d759bb2 100644 --- a/include/modules/river/window.hpp +++ b/include/modules/river/window.hpp @@ -12,22 +12,22 @@ namespace waybar::modules::river { class Window : public waybar::ALabel { public: - Window(const std::string &, const waybar::Bar &, const Json::Value &); + Window(const std::string&, const waybar::Bar&, const Json::Value&); virtual ~Window(); // Handlers for wayland events - void handle_focused_view(const char *title); - void handle_focused_output(struct wl_output *output); - void handle_unfocused_output(struct wl_output *output); + void handle_focused_view(const char* title); + void handle_focused_output(struct wl_output* output); + void handle_unfocused_output(struct wl_output* output); - struct zriver_status_manager_v1 *status_manager_; - struct wl_seat *seat_; + struct zriver_status_manager_v1* status_manager_; + struct wl_seat* seat_; private: - const waybar::Bar &bar_; - struct wl_output *output_; // stores the output this module belongs to - struct wl_output *focused_output_; // stores the currently focused output - struct zriver_seat_status_v1 *seat_status_; + const waybar::Bar& bar_; + struct wl_output* output_; // stores the output this module belongs to + struct wl_output* focused_output_; // stores the currently focused output + struct zriver_seat_status_v1* seat_status_; }; } /* namespace waybar::modules::river */ diff --git a/include/modules/sndio.hpp b/include/modules/sndio.hpp index 3fe36fad..43c84f9e 100644 --- a/include/modules/sndio.hpp +++ b/include/modules/sndio.hpp @@ -11,18 +11,18 @@ namespace waybar::modules { class Sndio : public ALabel { public: - Sndio(const std::string &, const Json::Value &); + Sndio(const std::string&, const Json::Value&); virtual ~Sndio(); auto update() -> void override; - auto set_desc(struct sioctl_desc *, unsigned int) -> void; + auto set_desc(struct sioctl_desc*, unsigned int) -> void; auto put_val(unsigned int, unsigned int) -> void; - bool handleScroll(GdkEventScroll *) override; - bool handleToggle(GdkEventButton *const &) override; + bool handleScroll(GdkEventScroll*) override; + bool handleToggle(GdkEventButton* const&) override; private: auto connect_to_sndio() -> void; util::SleeperThread thread_; - struct sioctl_hdl *hdl_; + struct sioctl_hdl* hdl_; std::vector pfds_; unsigned int addr_; unsigned int volume_, old_volume_, maxval_; diff --git a/include/modules/sni/host.hpp b/include/modules/sni/host.hpp index 6c62ac31..f18cf414 100644 --- a/include/modules/sni/host.hpp +++ b/include/modules/sni/host.hpp @@ -16,7 +16,7 @@ class Host { public: Host(const std::size_t id, const Json::Value&, const Bar&, const std::function&)>&, - const std::function&)>&); + const std::function&)>&, const std::function&); ~Host(); private: @@ -28,9 +28,13 @@ class Host { static void registerHost(GObject*, GAsyncResult*, gpointer); static void itemRegistered(SnWatcher*, const gchar*, gpointer); static void itemUnregistered(SnWatcher*, const gchar*, gpointer); + void itemReady(Item&); + void itemInvalidated(Item&); + void removeItem(std::vector>::iterator); + void clearItems(); std::tuple getBusNameAndObjectPath(const std::string); - void addRegisteredItem(std::string service); + void addRegisteredItem(const std::string& service); std::vector> items_; const std::string bus_name_; @@ -39,10 +43,13 @@ class Host { std::size_t watcher_id_; GCancellable* cancellable_ = nullptr; SnWatcher* watcher_ = nullptr; + sigc::connection retry_connection_; + unsigned retry_count_ = 0; const Json::Value& config_; const Bar& bar_; const std::function&)> on_add_; const std::function&)> on_remove_; + const std::function on_update_; }; } // namespace waybar::modules::SNI diff --git a/include/modules/sni/item.hpp b/include/modules/sni/item.hpp index c5e86d37..df87bfb7 100644 --- a/include/modules/sni/item.hpp +++ b/include/modules/sni/item.hpp @@ -11,6 +11,7 @@ #include #include +#include #include #include @@ -25,8 +26,12 @@ struct ToolTip { class Item : public sigc::trackable { public: - Item(const std::string&, const std::string&, const Json::Value&, const Bar&); - ~Item() = default; + Item(const std::string&, const std::string&, const Json::Value&, const Bar&, + const std::function&, const std::function&, + const std::function&); + ~Item(); + + bool isReady() const; std::string bus_name; std::string object_path; @@ -41,9 +46,12 @@ class Item : public sigc::trackable { std::string title; std::string icon_name; Glib::RefPtr icon_pixmap; + bool has_custom_icon_ = false; Glib::RefPtr icon_theme; std::string overlay_icon_name; + Glib::RefPtr overlay_icon_pixmap; std::string attention_icon_name; + Glib::RefPtr attention_icon_pixmap; std::string attention_movie_name; std::string icon_theme_path; std::string menu; @@ -62,6 +70,8 @@ class Item : public sigc::trackable { void proxyReady(Glib::RefPtr& result); void setProperty(const Glib::ustring& name, Glib::VariantBase& value); void setStatus(const Glib::ustring& value); + void setReady(); + void invalidate(); void setCustomIcon(const std::string& id); void getUpdatedProperties(); void processUpdatedProperties(Glib::RefPtr& result); @@ -69,8 +79,13 @@ class Item : public sigc::trackable { const Glib::VariantContainerBase& arguments); void updateImage(); - Glib::RefPtr extractPixBuf(GVariant* variant); + static Glib::RefPtr extractPixBuf(GVariant* variant); Glib::RefPtr getIconPixbuf(); + Glib::RefPtr getAttentionIconPixbuf(); + Glib::RefPtr getOverlayIconPixbuf(); + Glib::RefPtr loadIconFromNameOrFile(const std::string& name, bool log_failure); + static Glib::RefPtr overlayPixbufs(const Glib::RefPtr&, + const Glib::RefPtr&); Glib::RefPtr getIconByName(const std::string& name, int size); double getScaledIconSize(); static void onMenuDestroyed(Item* self, GObject* old_menu_pointer); @@ -86,8 +101,13 @@ class Item : public sigc::trackable { gdouble distance_scrolled_y_ = 0; // visibility of items with Status == Passive bool show_passive_ = false; + bool ready_ = false; + Glib::ustring status_ = "active"; const Bar& bar_; + const std::function on_ready_; + const std::function on_invalidate_; + const std::function on_updated_; Glib::RefPtr proxy_; Glib::RefPtr cancellable_; diff --git a/include/modules/sni/tray.hpp b/include/modules/sni/tray.hpp index 6cda35d7..755aa7b3 100644 --- a/include/modules/sni/tray.hpp +++ b/include/modules/sni/tray.hpp @@ -19,6 +19,7 @@ class Tray : public AModule { private: void onAdd(std::unique_ptr& item); void onRemove(std::unique_ptr& item); + void queueUpdate(); static inline std::size_t nb_hosts_ = 0; Gtk::Box box_; diff --git a/include/modules/sni/watcher.hpp b/include/modules/sni/watcher.hpp index 5cb0f19e..49d2dae5 100644 --- a/include/modules/sni/watcher.hpp +++ b/include/modules/sni/watcher.hpp @@ -30,27 +30,27 @@ class Watcher { typedef struct { GfWatchType type; - Watcher *watcher; - gchar *service; - gchar *bus_name; - gchar *object_path; + Watcher* watcher; + gchar* service; + gchar* bus_name; + gchar* object_path; guint watch_id; } GfWatch; - 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); + 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); - void updateRegisteredItems(SnWatcher *obj); + void updateRegisteredItems(SnWatcher* obj); uint32_t bus_name_id_; - GSList *hosts_ = nullptr; - GSList *items_ = nullptr; - SnWatcher *watcher_ = nullptr; + GSList* hosts_ = nullptr; + GSList* items_ = nullptr; + SnWatcher* watcher_ = nullptr; }; } // namespace waybar::modules::SNI diff --git a/include/modules/sway/bar.hpp b/include/modules/sway/bar.hpp index fd48e5a3..381c6c37 100644 --- a/include/modules/sway/bar.hpp +++ b/include/modules/sway/bar.hpp @@ -37,7 +37,7 @@ class BarIpcClient { void onModeUpdate(bool visible_by_modifier); void onUrgencyUpdate(bool visible_by_urgency); void update(); - bool isModuleEnabled(std::string name); + bool isModuleEnabled(const std::string& name); Bar& bar_; util::JsonParser parser_; diff --git a/include/modules/sway/ipc/client.hpp b/include/modules/sway/ipc/client.hpp index a9a3e4e9..f6eb7c40 100644 --- a/include/modules/sway/ipc/client.hpp +++ b/include/modules/sway/ipc/client.hpp @@ -12,6 +12,8 @@ #include #include "ipc.hpp" +#include "util/SafeSignal.hpp" +#include "util/scoped_fd.hpp" #include "util/sleeper_thread.hpp" namespace waybar::modules::sway { @@ -27,25 +29,25 @@ class Ipc { std::string payload; }; - sigc::signal signal_event; - sigc::signal signal_cmd; + ::waybar::SafeSignal signal_event; + ::waybar::SafeSignal signal_cmd; - void sendCmd(uint32_t type, const std::string &payload = ""); - void subscribe(const std::string &payload); + void sendCmd(uint32_t type, const std::string& payload = ""); + void subscribe(const std::string& payload); void handleEvent(); - void setWorker(std::function &&func); + void setWorker(std::function&& func); protected: static inline const std::string ipc_magic_ = "i3-ipc"; static inline const size_t ipc_header_size_ = ipc_magic_.size() + 8; const std::string getSocketPath() const; - int open(const std::string &) const; - struct ipc_response send(int fd, uint32_t type, const std::string &payload = ""); + 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_; + util::ScopedFd fd_; + util::ScopedFd fd_event_; std::mutex mutex_; util::SleeperThread thread_; }; diff --git a/include/modules/sway/language.hpp b/include/modules/sway/language.hpp index ea58c4f0..470b9879 100644 --- a/include/modules/sway/language.hpp +++ b/include/modules/sway/language.hpp @@ -21,7 +21,7 @@ class Language : public ALabel, public sigc::trackable { auto update() -> void override; private: - enum class DispayedShortFlag { None = 0, ShortName = 1, ShortDescription = 1 << 1 }; + enum class DisplayedShortFlag { None = 0, ShortName = 1, ShortDescription = 1 << 1 }; struct Layout { std::string full_name; @@ -47,7 +47,7 @@ class Language : public ALabel, public sigc::trackable { void onEvent(const struct Ipc::ipc_response&); void onCmd(const struct Ipc::ipc_response&); - auto set_current_layout(std::string current_layout) -> void; + auto set_current_layout(const std::string& current_layout) -> void; auto init_layouts_map(const std::vector& used_layouts) -> void; const static std::string XKB_LAYOUT_NAMES_KEY; @@ -58,7 +58,7 @@ class Language : public ALabel, public sigc::trackable { std::map layouts_map_; bool hide_single_; bool is_variant_displayed; - std::byte displayed_short_flag = static_cast(DispayedShortFlag::None); + std::byte displayed_short_flag = static_cast(DisplayedShortFlag::None); util::JsonParser parser_; std::mutex mutex_; diff --git a/include/modules/sway/window.hpp b/include/modules/sway/window.hpp index 427c2e81..60cd2679 100644 --- a/include/modules/sway/window.hpp +++ b/include/modules/sway/window.hpp @@ -19,10 +19,11 @@ class Window : public AAppIconLabel, public sigc::trackable { auto update() -> void override; private: - void setClass(std::string classname, bool enable); + void setClass(const std::string& classname, bool enable); void onEvent(const struct Ipc::ipc_response&); void onCmd(const struct Ipc::ipc_response&); - std::tuple + std::tuple getFocusedNode(const Json::Value& nodes, std::string& output); void getTree(); @@ -35,6 +36,7 @@ class Window : public AAppIconLabel, public sigc::trackable { std::string old_app_id_; std::size_t app_nb_; std::string shell_; + std::string marks_; int floating_count_; util::JsonParser parser_; std::mutex mutex_; diff --git a/include/modules/sway/workspaces.hpp b/include/modules/sway/workspaces.hpp index 58c173ec..1f8d8ed0 100644 --- a/include/modules/sway/workspaces.hpp +++ b/include/modules/sway/workspaces.hpp @@ -24,10 +24,11 @@ class Workspaces : public AModule, public sigc::trackable { private: static constexpr std::string_view workspace_switch_cmd_ = "workspace {} \"{}\""; + static constexpr std::string_view workspace_switch_number_cmd_ = "workspace {} number {}"; static constexpr std::string_view persistent_workspace_switch_cmd_ = R"(workspace {} "{}"; move workspace to output "{}"; workspace {} "{}")"; - static int convertWorkspaceNameToNum(std::string name); + static int convertWorkspaceNameToNum(const std::string& name); static int windowRewritePriorityFunction(std::string const& window_rule); void onCmd(const struct Ipc::ipc_response&); @@ -40,7 +41,7 @@ class Workspaces : public AModule, public sigc::trackable { std::string getIcon(const std::string&, const Json::Value&); std::string getCycleWorkspace(std::vector::iterator, bool prev) const; uint16_t getWorkspaceIndex(const std::string& name) const; - static std::string trimWorkspaceName(std::string); + static std::string trimWorkspaceName(const std::string&); bool handleScroll(GdkEventScroll* /*unused*/) override; const Bar& bar_; @@ -48,7 +49,7 @@ class Workspaces : public AModule, public sigc::trackable { std::vector high_priority_named_; std::vector workspaces_order_; Gtk::Box box_; - std::string m_formatWindowSeperator; + std::string m_formatWindowSeparator; util::RegexCollection m_windowRewriteRules; util::JsonParser parser_; std::unordered_map buttons_; diff --git a/include/modules/systemd_failed_units.hpp b/include/modules/systemd_failed_units.hpp index 9c3fbcee..3eda799a 100644 --- a/include/modules/systemd_failed_units.hpp +++ b/include/modules/systemd_failed_units.hpp @@ -3,6 +3,7 @@ #include #include +#include #include "ALabel.hpp" @@ -10,21 +11,43 @@ namespace waybar::modules { class SystemdFailedUnits : public ALabel { public: - SystemdFailedUnits(const std::string &, const Json::Value &); - virtual ~SystemdFailedUnits(); + SystemdFailedUnits(const std::string&, const Json::Value&); + virtual ~SystemdFailedUnits() = default; auto update() -> void override; private: - bool hide_on_ok; - std::string format_ok; + struct FailedUnit { + std::string name; + std::string description; + std::string load_state; + std::string active_state; + std::string sub_state; + std::string scope; + }; - bool update_pending; - uint32_t nr_failed_system, nr_failed_user; - std::string last_status; - Glib::RefPtr system_proxy, user_proxy; + bool hide_on_ok_; + std::string format_ok_; + std::string tooltip_format_; + std::string tooltip_format_ok_; + std::string tooltip_unit_format_; - void notify_cb(const Glib::ustring &sender_name, const Glib::ustring &signal_name, - const Glib::VariantContainerBase &arguments); + bool update_pending_; + std::string system_state_, user_state_, overall_state_; + uint32_t nr_failed_system_, nr_failed_user_, nr_failed_; + std::string last_status_; + Glib::RefPtr system_props_proxy_, user_props_proxy_; + Glib::RefPtr system_manager_proxy_, user_manager_proxy_; + std::vector failed_units_; + + void notify_cb(const Glib::ustring& sender_name, const Glib::ustring& signal_name, + const Glib::VariantContainerBase& arguments); + void RequestFailedUnits(); + void RequestFailedUnitsList(); + void RequestSystemState(); + std::vector LoadFailedUnitsList(const char* kind, + Glib::RefPtr& proxy, + const std::string& scope); + std::string BuildTooltipFailedList() const; void updateData(); }; diff --git a/include/modules/temperature.hpp b/include/modules/temperature.hpp index 918281be..d65ef84d 100644 --- a/include/modules/temperature.hpp +++ b/include/modules/temperature.hpp @@ -14,6 +14,8 @@ class Temperature : public ALabel { Temperature(const std::string&, const Json::Value&); virtual ~Temperature() = default; auto update() -> void override; + void suspend() override; + void resume() override; private: float getTemperature(); diff --git a/include/modules/upower.hpp b/include/modules/upower.hpp index 60a276db..0d445047 100644 --- a/include/modules/upower.hpp +++ b/include/modules/upower.hpp @@ -12,7 +12,7 @@ namespace waybar::modules { class UPower final : public AIconLabel { public: - UPower(const std::string &, const Json::Value &); + UPower(const std::string&, const Json::Value&); virtual ~UPower(); auto update() -> void override; @@ -30,17 +30,17 @@ class UPower final : public AIconLabel { // UPower device info struct upDevice_output { - UpDevice *upDevice{NULL}; + UpDevice* upDevice{NULL}; double percentage{0.0}; double temperature{0.0}; guint64 time_full{0u}; guint64 time_empty{0u}; - gchar *icon_name{(char *)'\0'}; + gchar* icon_name{(char*)'\0'}; bool upDeviceValid{false}; UpDeviceState state; UpDeviceKind kind; - char *nativePath{(char *)'\0'}; - char *model{(char *)'\0'}; + char* nativePath{(char*)'\0'}; + char* model{(char*)'\0'}; }; // Technical variables @@ -53,13 +53,13 @@ class UPower final : public AIconLabel { bool sleeping_; // Technical functions - void addDevice(UpDevice *); - void removeDevice(const gchar *); + void addDevice(UpDevice*); + void removeDevice(const gchar*); void removeDevices(); void resetDevices(); void setDisplayDevice(); - const Glib::ustring getText(const upDevice_output &upDevice_, const std::string &format); - bool queryTooltipCb(int, int, bool, const Glib::RefPtr &); + const Glib::ustring getText(const upDevice_output& upDevice_, const std::string& format); + bool queryTooltipCb(int, int, bool, const Glib::RefPtr&); // DBUS variables guint watcherID_; @@ -67,28 +67,28 @@ class UPower final : public AIconLabel { guint subscrID_{0u}; // UPower variables - UpClient *upClient_; + UpClient* upClient_; upDevice_output upDevice_; // Device to display typedef std::unordered_map Devices; Devices devices_; bool upRunning_{true}; // DBus callbacks - void getConn_cb(Glib::RefPtr &result); - void onAppear(const Glib::RefPtr &, const Glib::ustring &, - const Glib::ustring &); - void onVanished(const Glib::RefPtr &, const Glib::ustring &); - void prepareForSleep_cb(const Glib::RefPtr &connection, - const Glib::ustring &sender_name, const Glib::ustring &object_path, - const Glib::ustring &interface_name, const Glib::ustring &signal_name, - const Glib::VariantContainerBase ¶meters); + void getConn_cb(Glib::RefPtr& result); + void onAppear(const Glib::RefPtr&, const Glib::ustring&, + const Glib::ustring&); + void onVanished(const Glib::RefPtr&, const Glib::ustring&); + void prepareForSleep_cb(const Glib::RefPtr& connection, + const Glib::ustring& sender_name, const Glib::ustring& object_path, + const Glib::ustring& interface_name, const Glib::ustring& signal_name, + const Glib::VariantContainerBase& parameters); // UPower callbacks - static void deviceAdded_cb(UpClient *client, UpDevice *device, gpointer data); - static void deviceRemoved_cb(UpClient *client, const gchar *objectPath, gpointer data); - static void deviceNotify_cb(UpDevice *device, GParamSpec *pspec, gpointer user_data); + static void deviceAdded_cb(UpClient* client, UpDevice* device, gpointer data); + static void deviceRemoved_cb(UpClient* client, const gchar* objectPath, gpointer data); + static void deviceNotify_cb(UpDevice* device, GParamSpec* pspec, gpointer user_data); // UPower secondary functions - void getUpDeviceInfo(upDevice_output &upDevice_); + void getUpDeviceInfo(upDevice_output& upDevice_); }; } // namespace waybar::modules diff --git a/include/modules/wayfire/backend.hpp b/include/modules/wayfire/backend.hpp new file mode 100644 index 00000000..e1f259cc --- /dev/null +++ b/include/modules/wayfire/backend.hpp @@ -0,0 +1,108 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "util/scoped_fd.hpp" + +namespace waybar::modules::wayfire { + +using EventHandler = std::function; + +struct State { + /* + ┌───────────┐ ┌───────────┐ + │ output #1 │ │ output #2 │ + └─────┬─────┘ └─────┬─────┘ + └─┐ └─────┐─ ─ ─ ─ ─ ─ ─ ─ ┐ + ┌───────┴───────┐ ┌───────┴──────┐ ┌───────┴───────┐ + │ wset #1 │ │ wset #2 │ │ wset #3 │ + │┌────────────┐ │ │┌────────────┐│ │┌────────────┐ │ + ││ workspaces │ │ ││ workspaces ││ ││ workspaces │ │ + │└─┬──────────┘ │ │└────────────┘│ │└─┬──────────┘ │ + │ │ ┌─────────┐│ └──────────────┘ │ │ ┌─────────┐│ + │ ├─┤ view #1 ││ │ └─┤ view #3 ││ + │ │ └─────────┘│ │ └─────────┘│ + │ │ ┌─────────┐│ └───────────────┘ + │ └─┤ view #2 ││ + │ └─────────┘│ + └───────────────┘ + */ + + struct Output { + size_t id; + size_t w, h; + size_t wset_idx; + }; + + struct Workspace { + size_t num_views; + size_t num_sticky_views; + }; + + struct Wset { + std::optional> output; + std::vector wss; + size_t ws_w, ws_h, ws_x, ws_y; + size_t focused_view_id; + + auto ws_idx() const { return ws_w * ws_y + ws_x; } + auto count_ws(const Json::Value& pos) -> Workspace&; + auto locate_ws(const Json::Value& geo) -> Workspace&; + auto locate_ws(const Json::Value& geo) const -> const Workspace&; + }; + + std::unordered_map outputs; + std::unordered_map wsets; + std::unordered_map views; + std::string focused_output_name; + size_t maybe_empty_focus_wset_idx = {}; + size_t vswitch_sticky_view_id = {}; + bool new_output_detected = {}; + bool vswitching = {}; + + auto update_view(const Json::Value& view) -> void; +}; + +using Sock = util::ScopedFd; + +class IPC : public std::enable_shared_from_this { + static std::weak_ptr instance; + Json::CharReaderBuilder reader_builder; + Json::StreamWriterBuilder writer_builder; + std::list>> handlers; + std::mutex handlers_mutex; + State state; + std::mutex state_mutex; + + IPC() = default; + + static auto connect() -> Sock; + auto receive(Sock& sock) -> Json::Value; + auto start() -> void; + auto root_event_handler(const std::string& event, const Json::Value& data) -> void; + auto update_state_handler(const std::string& event, const Json::Value& data) -> void; + + public: + static auto get_instance() -> std::shared_ptr; + auto send(const std::string& method, Json::Value&& data) -> Json::Value; + auto register_handler(const std::string& event, const EventHandler& handler) -> void; + auto unregister_handler(EventHandler& handler) -> void; + + auto lock_state() -> std::lock_guard { return std::lock_guard{state_mutex}; } + auto& get_outputs() const { return state.outputs; } + auto& get_wsets() const { return state.wsets; } + auto& get_views() const { return state.views; } + auto& get_focused_output_name() const { return state.focused_output_name; } +}; + +} // namespace waybar::modules::wayfire diff --git a/include/modules/wayfire/window.hpp b/include/modules/wayfire/window.hpp new file mode 100644 index 00000000..3e8cb291 --- /dev/null +++ b/include/modules/wayfire/window.hpp @@ -0,0 +1,24 @@ +#pragma once + +#include "AAppIconLabel.hpp" +#include "bar.hpp" +#include "modules/wayfire/backend.hpp" + +namespace waybar::modules::wayfire { + +class Window : public AAppIconLabel { + std::shared_ptr ipc; + EventHandler handler; + + const Bar& bar_; + std::string old_app_id_; + + public: + Window(const std::string& id, const Bar& bar, const Json::Value& config); + ~Window() override; + + auto update() -> void override; + auto update_icon_label() -> void; +}; + +} // namespace waybar::modules::wayfire diff --git a/include/modules/wayfire/workspaces.hpp b/include/modules/wayfire/workspaces.hpp new file mode 100644 index 00000000..ab7cac44 --- /dev/null +++ b/include/modules/wayfire/workspaces.hpp @@ -0,0 +1,32 @@ +#pragma once + +#include +#include + +#include +#include + +#include "AModule.hpp" +#include "bar.hpp" +#include "modules/wayfire/backend.hpp" + +namespace waybar::modules::wayfire { + +class Workspaces : public AModule { + std::shared_ptr ipc; + EventHandler handler; + + const Bar& bar_; + Gtk::Box box_; + std::vector buttons_; + + auto handleScroll(GdkEventScroll* e) -> bool override; + auto update() -> void override; + auto update_box() -> void; + + public: + Workspaces(const std::string& id, const Bar& bar, const Json::Value& config); + ~Workspaces() override; +}; + +} // namespace waybar::modules::wayfire diff --git a/include/modules/wireplumber.hpp b/include/modules/wireplumber.hpp index e0033e8a..0565704f 100644 --- a/include/modules/wireplumber.hpp +++ b/include/modules/wireplumber.hpp @@ -22,6 +22,8 @@ class Wireplumber : public ALabel { void activatePlugins(); static void updateVolume(waybar::modules::Wireplumber* self, uint32_t id); static void updateNodeName(waybar::modules::Wireplumber* self, uint32_t id); + static void updateSourceVolume(waybar::modules::Wireplumber* self, uint32_t id); + static void updateSourceName(waybar::modules::Wireplumber* self, uint32_t id); // NEW static void onPluginActivated(WpObject* p, GAsyncResult* res, waybar::modules::Wireplumber* self); static void onDefaultNodesApiLoaded(WpObject* p, GAsyncResult* res, waybar::modules::Wireplumber* self); @@ -46,7 +48,12 @@ class Wireplumber : public ALabel { double min_step_; uint32_t node_id_{0}; std::string node_name_; + std::string source_name_; gchar* type_; + uint32_t source_node_id_; + bool source_muted_; + double source_volume_; + gchar* default_source_name_; }; } // namespace waybar::modules diff --git a/include/modules/wlr/taskbar.hpp b/include/modules/wlr/taskbar.hpp index 07110dde..413eae85 100644 --- a/include/modules/wlr/taskbar.hpp +++ b/include/modules/wlr/taskbar.hpp @@ -19,6 +19,7 @@ #include "bar.hpp" #include "client.hpp" #include "giomm/desktopappinfo.h" +#include "util/icon_loader.hpp" #include "util/json.hpp" #include "wlr-foreign-toplevel-management-unstable-v1-client-protocol.h" @@ -32,8 +33,8 @@ class Taskbar; class Task { public: - Task(const waybar::Bar &, const Json::Value &, Taskbar *, - struct zwlr_foreign_toplevel_handle_v1 *, struct wl_seat *); + Task(const waybar::Bar&, const Json::Value&, Taskbar*, struct zwlr_foreign_toplevel_handle_v1*, + struct wl_seat*); ~Task(); public: @@ -52,11 +53,11 @@ class Task { 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_; + const waybar::Bar& bar_; + const Json::Value& config_; + Taskbar* tbar_; + struct zwlr_foreign_toplevel_handle_v1* handle_; + struct wl_seat* seat_; uint32_t id_; @@ -88,10 +89,7 @@ class Task { std::string repr() const; std::string state_string(bool = false) const; void set_minimize_hint(); - void on_button_size_allocated(Gtk::Allocation &alloc); - 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 on_button_size_allocated(Gtk::Allocation& alloc); void hide_if_ignored(); public: @@ -107,26 +105,26 @@ class Task { 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_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 *); - bool handle_button_release(GdkEventButton *); - bool handle_motion_notify(GdkEventMotion *); - void handle_drag_data_get(const Glib::RefPtr &context, - Gtk::SelectionData &selection_data, guint info, guint time); - void handle_drag_data_received(const Glib::RefPtr &context, int x, int y, + bool handle_clicked(GdkEventButton*); + bool handle_button_release(GdkEventButton*); + bool handle_motion_notify(GdkEventMotion*); + void handle_drag_data_get(const Glib::RefPtr& context, + Gtk::SelectionData& selection_data, guint info, guint time); + void handle_drag_data_received(const Glib::RefPtr& context, int x, int y, Gtk::SelectionData selection_data, guint info, guint time); public: - bool operator==(const Task &) const; - bool operator!=(const Task &) const; + bool operator==(const Task&) const; + bool operator!=(const Task&) const; public: void update(); @@ -144,43 +142,43 @@ using TaskPtr = std::unique_ptr; class Taskbar : public waybar::AModule { public: - Taskbar(const std::string &, const waybar::Bar &, const Json::Value &); + Taskbar(const std::string&, const waybar::Bar&, const Json::Value&); ~Taskbar(); void update(); private: - const waybar::Bar &bar_; + const waybar::Bar& bar_; Gtk::Box box_; std::vector tasks_; - std::vector> icon_themes_; + IconLoader icon_loader_; 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); + 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_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 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 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 IconLoader& icon_loader() 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 deleted file mode 100644 index f7cc759e..00000000 --- a/include/modules/wlr/workspace_manager.hpp +++ /dev/null @@ -1,172 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include -#include -#include -#include - -#include "AModule.hpp" -#include "bar.hpp" -#include "ext-workspace-unstable-v1-client-protocol.h" - -namespace waybar::modules::wlr { - -class WorkspaceManager; -class WorkspaceGroup; - -class Workspace { - public: - Workspace(const waybar::Bar &bar, const Json::Value &config, WorkspaceGroup &workspace_group, - zext_workspace_handle_v1 *workspace, uint32_t id, std::string name); - ~Workspace(); - auto update() -> void; - - auto id() const -> uint32_t { return id_; } - auto is_active() const -> bool { return state_ & static_cast(State::ACTIVE); } - auto is_urgent() const -> bool { return state_ & static_cast(State::URGENT); } - auto is_hidden() const -> bool { return state_ & static_cast(State::HIDDEN); } - auto is_empty() const -> bool { return state_ & static_cast(State::EMPTY); } - auto is_persistent() const -> bool { return persistent_; } - // wlr stuff - auto handle_name(const std::string &name) -> void; - auto handle_coordinates(const std::vector &coordinates) -> void; - auto handle_state(const std::vector &state) -> void; - auto handle_remove() -> void; - auto make_persistent() -> void; - auto handle_duplicate() -> void; - - auto handle_done() -> void; - auto handle_clicked(GdkEventButton *bt) -> bool; - auto show() -> void; - auto hide() -> void; - auto get_button_ref() -> Gtk::Button & { return button_; } - auto get_name() -> std::string & { return name_; } - auto get_coords() -> std::vector & { return coordinates_; } - - enum class State { - ACTIVE = (1 << 0), - URGENT = (1 << 1), - HIDDEN = (1 << 2), - EMPTY = (1 << 3), - }; - - private: - auto get_icon() -> std::string; - - const Bar &bar_; - const Json::Value &config_; - WorkspaceGroup &workspace_group_; - - // wlr stuff - zext_workspace_handle_v1 *workspace_handle_; - uint32_t state_ = 0; - - uint32_t id_; - std::string name_; - std::vector coordinates_; - static std::map icons_map_; - std::string format_; - bool with_icon_ = false; - bool persistent_ = false; - - Gtk::Button button_; - Gtk::Box content_; - Gtk::Label label_; -}; - -class WorkspaceGroup { - public: - WorkspaceGroup(const waybar::Bar &bar, Gtk::Box &box, const Json::Value &config, - WorkspaceManager &manager, zext_workspace_group_handle_v1 *workspace_group_handle, - uint32_t id); - ~WorkspaceGroup(); - auto update() -> void; - - auto id() const -> uint32_t { return id_; } - auto is_visible() const -> bool; - auto remove_workspace(uint32_t id_) -> void; - auto active_only() const -> bool; - auto creation_delayed() const -> bool; - auto workspaces() -> std::vector> & { return workspaces_; } - auto persistent_workspaces() -> std::vector & { return persistent_workspaces_; } - - auto sort_workspaces() -> void; - auto set_need_to_sort() -> void { need_to_sort = true; } - auto add_button(Gtk::Button &button) -> void; - auto remove_button(Gtk::Button &button) -> void; - auto fill_persistent_workspaces() -> void; - auto create_persistent_workspaces() -> void; - - // wlr stuff - auto handle_workspace_create(zext_workspace_handle_v1 *workspace_handle) -> void; - auto handle_remove() -> void; - auto handle_output_enter(wl_output *output) -> void; - auto handle_output_leave() -> void; - auto handle_done() -> void; - auto commit() -> void; - - private: - static uint32_t workspace_global_id; - const waybar::Bar &bar_; - Gtk::Box &box_; - const Json::Value &config_; - WorkspaceManager &workspace_manager_; - - // wlr stuff - zext_workspace_group_handle_v1 *workspace_group_handle_; - wl_output *output_ = nullptr; - - uint32_t id_; - std::vector> workspaces_; - bool need_to_sort = false; - std::vector persistent_workspaces_; - bool persistent_created_ = false; -}; - -class WorkspaceManager : public AModule { - public: - WorkspaceManager(const std::string &id, const waybar::Bar &bar, const Json::Value &config); - ~WorkspaceManager() override; - auto update() -> void override; - - auto all_outputs() const -> bool { return all_outputs_; } - auto active_only() const -> bool { return active_only_; } - auto workspace_comparator() const - -> std::function &, std::unique_ptr &)>; - auto creation_delayed() const -> bool { return creation_delayed_; } - - auto sort_workspaces() -> void; - auto remove_workspace_group(uint32_t id_) -> void; - - // wlr stuff - auto register_manager(wl_registry *registry, uint32_t name, uint32_t version) -> void; - auto handle_workspace_group_create(zext_workspace_group_handle_v1 *workspace_group_handle) - -> void; - auto handle_done() -> void; - auto handle_finished() -> void; - auto commit() -> void; - - private: - const waybar::Bar &bar_; - Gtk::Box box_; - std::vector> groups_; - - // wlr stuff - zext_workspace_manager_v1 *workspace_manager_ = nullptr; - - static uint32_t group_global_id; - - bool sort_by_name_ = true; - bool sort_by_coordinates_ = true; - bool sort_by_number_ = false; - bool all_outputs_ = false; - bool active_only_ = false; - bool creation_delayed_ = false; -}; - -} // namespace waybar::modules::wlr diff --git a/include/modules/wlr/workspace_manager_binding.hpp b/include/modules/wlr/workspace_manager_binding.hpp deleted file mode 100644 index cc242c94..00000000 --- a/include/modules/wlr/workspace_manager_binding.hpp +++ /dev/null @@ -1,10 +0,0 @@ -#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); -} // namespace waybar::modules::wlr diff --git a/include/util/SafeSignal.hpp b/include/util/SafeSignal.hpp index 458bc57e..b1e3a91a 100644 --- a/include/util/SafeSignal.hpp +++ b/include/util/SafeSignal.hpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -22,6 +23,12 @@ struct SafeSignal : sigc::signal...)> { public: SafeSignal() { dp_.connect(sigc::mem_fun(*this, &SafeSignal::handle_event)); } + void set_max_queued_events(std::size_t max_queued_events) { + std::unique_lock lock(mutex_); + max_queued_events_ = max_queued_events; + trim_queue_locked(); + } + template void emit(EmitArgs&&... args) { if (main_tid_ == std::this_thread::get_id()) { @@ -36,6 +43,9 @@ struct SafeSignal : sigc::signal...)> { } else { { std::unique_lock lock(mutex_); + if (max_queued_events_ != 0 && queue_.size() >= max_queued_events_) { + queue_.pop(); + } queue_.emplace(std::forward(args)...); } dp_.emit(); @@ -55,6 +65,15 @@ struct SafeSignal : sigc::signal...)> { using signal_t::emit_reverse; using signal_t::make_slot; + void trim_queue_locked() { + if (max_queued_events_ == 0) { + return; + } + while (queue_.size() > max_queued_events_) { + queue_.pop(); + } + } + void handle_event() { for (std::unique_lock lock(mutex_); !queue_.empty(); lock.lock()) { auto args = queue_.front(); @@ -67,6 +86,7 @@ struct SafeSignal : sigc::signal...)> { Glib::Dispatcher dp_; std::mutex mutex_; std::queue queue_; + std::size_t max_queued_events_ = 4096; 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/audio_backend.hpp b/include/util/audio_backend.hpp index 3737ae26..f5904b43 100644 --- a/include/util/audio_backend.hpp +++ b/include/util/audio_backend.hpp @@ -14,6 +14,11 @@ namespace waybar::util { +enum class PulseaudioTarget { + Sink, + Source, +}; + class AudioBackend { private: static void subscribeCb(pa_context*, pa_subscription_event_type_t, uint32_t, void*); @@ -92,7 +97,11 @@ class AudioBackend { void toggleSourceMute(); void toggleSourceMute(bool); + uint16_t getVolume(PulseaudioTarget) const; + bool getMuted(PulseaudioTarget) const; + void unmute(PulseaudioTarget); + bool isBluetooth(); }; -} // namespace waybar::util \ No newline at end of file +} // namespace waybar::util diff --git a/include/util/backlight_backend.hpp b/include/util/backlight_backend.hpp index eb42d3cc..ba3ccca7 100644 --- a/include/util/backlight_backend.hpp +++ b/include/util/backlight_backend.hpp @@ -36,7 +36,7 @@ class BacklightDevice { void set_max(int max); bool get_powered() const; void set_powered(bool powered); - friend inline bool operator==(const BacklightDevice &lhs, const BacklightDevice &rhs) { + friend inline bool operator==(const BacklightDevice& lhs, const BacklightDevice& rhs) { return lhs.name_ == rhs.name_ && lhs.actual_ == rhs.actual_ && lhs.max_ == rhs.max_; } @@ -52,25 +52,25 @@ class BacklightBackend { BacklightBackend(std::chrono::milliseconds interval, std::function on_updated_cb = NOOP); // const inline BacklightDevice *get_best_device(std::string_view preferred_device); - const BacklightDevice *get_previous_best_device(); + const BacklightDevice* get_previous_best_device(); - void set_previous_best_device(const BacklightDevice *device); + void set_previous_best_device(const BacklightDevice* device); - void set_brightness(const std::string &preferred_device, ChangeType change_type, double step); + void set_brightness(const std::string& preferred_device, ChangeType change_type, double step); - void set_scaled_brightness(const std::string &preferred_device, int brightness); - int get_scaled_brightness(const std::string &preferred_device); + void set_scaled_brightness(const std::string& preferred_device, int brightness); + int get_scaled_brightness(const std::string& preferred_device); bool is_login_proxy_initialized() const { return static_cast(login_proxy_); } - static const BacklightDevice *best_device(const std::vector &devices, + static const BacklightDevice* best_device(const std::vector& devices, std::string_view); std::vector devices_; std::mutex udev_thread_mutex_; private: - void set_brightness_internal(const std::string &device_name, int brightness, int max_brightness); + void set_brightness_internal(const std::string& device_name, int brightness, int max_brightness); std::function on_updated_cb_; std::chrono::milliseconds polling_interval_; diff --git a/include/util/clara.hpp b/include/util/clara.hpp index 73fa5415..48123549 100644 --- a/include/util/clara.hpp +++ b/include/util/clara.hpp @@ -78,7 +78,7 @@ class Column { class iterator { friend Column; - Column const &m_column; + Column const& m_column; size_t m_stringIndex = 0; size_t m_pos = 0; @@ -86,10 +86,10 @@ class Column { size_t m_end = 0; bool m_suffix = false; - iterator(Column const &column, size_t stringIndex) + 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 line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; } auto isBoundary(size_t at) const -> bool { assert(at > 0); @@ -129,18 +129,18 @@ class Column { return initial == std::string::npos ? m_column.m_indent : initial; } - auto addIndentAndSuffix(std::string const &plain) const -> std::string { + 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 pointer = value_type*; + using reference = value_type&; using iterator_category = std::forward_iterator_tag; - explicit iterator(Column const &column) : m_column(column) { + 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); @@ -154,7 +154,7 @@ class Column { return addIndentAndSuffix(line().substr(m_pos, m_len)); } - auto operator++() -> iterator & { + auto operator++() -> iterator& { m_pos += m_len; if (m_pos < line().size() && line()[m_pos] == '\n') m_pos += 1; @@ -174,26 +174,26 @@ class Column { return prev; } - auto operator==(iterator const &other) const -> bool { + 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); } + 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); } + explicit Column(std::string const& text) { m_strings.push_back(text); } - auto width(size_t newWidth) -> Column & { + auto width(size_t newWidth) -> Column& { assert(newWidth > 0); m_width = newWidth; return *this; } - auto indent(size_t newIndent) -> Column & { + auto indent(size_t newIndent) -> Column& { m_indent = newIndent; return *this; } - auto initialIndent(size_t newIndent) -> Column & { + auto initialIndent(size_t newIndent) -> Column& { m_initialIndent = newIndent; return *this; } @@ -202,7 +202,7 @@ class Column { 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) { + inline friend std::ostream& operator<<(std::ostream& os, Column const& col) { bool first = true; for (auto line : col) { if (first) @@ -214,7 +214,7 @@ class Column { return os; } - auto operator+(Column const &other) -> Columns; + auto operator+(Column const& other) -> Columns; auto toString() const -> std::string { std::ostringstream oss; @@ -236,34 +236,34 @@ class Columns { friend Columns; struct EndTag {}; - std::vector const &m_columns; + 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) { + 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()); + 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 pointer = value_type*; + using reference = value_type&; using iterator_category = std::forward_iterator_tag; - explicit iterator(Columns const &columns) + 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()); + for (auto const& col : m_columns) m_iterators.push_back(col.begin()); } - auto operator==(iterator const &other) const -> bool { + auto operator==(iterator const& other) const -> bool { return m_iterators == other.m_iterators; } - auto operator!=(iterator const &other) const -> bool { + auto operator!=(iterator const& other) const -> bool { return m_iterators != other.m_iterators; } auto operator*() const -> std::string { @@ -284,7 +284,7 @@ class Columns { } return row; } - auto operator++() -> iterator & { + auto operator++() -> iterator& { for (size_t i = 0; i < m_columns.size(); ++i) { if (m_iterators[i] != m_columns[i].end()) ++m_iterators[i]; } @@ -301,17 +301,17 @@ class Columns { auto begin() const -> iterator { return iterator(*this); } auto end() const -> iterator { return {*this, iterator::EndTag()}; } - auto operator+=(Column const &col) -> Columns & { + auto operator+=(Column const& col) -> Columns& { m_columns.push_back(col); return *this; } - auto operator+(Column const &col) -> Columns { + auto operator+(Column const& col) -> Columns { Columns combined = *this; combined += col; return combined; } - inline friend std::ostream &operator<<(std::ostream &os, Columns const &cols) { + inline friend std::ostream& operator<<(std::ostream& os, Columns const& cols) { bool first = true; for (auto line : cols) { if (first) @@ -330,7 +330,7 @@ class Columns { } }; -inline auto Column::operator+(Column const &other) -> Columns { +inline auto Column::operator+(Column const& other) -> Columns { Columns cols; cols += *this; cols += other; @@ -381,7 +381,7 @@ class Args { std::vector m_args; public: - Args(int argc, char const *const *argv) : m_exeName(argv[0]), m_args(argv + 1, argv + argc) {} + 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()) {} @@ -419,7 +419,7 @@ class TokenStream { while (it != itEnd && it->empty()) ++it; if (it != itEnd) { - auto const &next = *it; + auto const& next = *it; if (isOptPrefix(next[0])) { auto delimiterPos = next.find_first_of(" :="); if (delimiterPos != std::string::npos) { @@ -443,7 +443,7 @@ class TokenStream { } public: - explicit TokenStream(Args const &args) : TokenStream(args.m_args.begin(), args.m_args.end()) {} + explicit TokenStream(Args const& args) : TokenStream(args.m_args.begin(), args.m_args.end()) {} TokenStream(Iterator it, Iterator itEnd) : it(it), itEnd(itEnd) { loadBuffer(); } @@ -456,12 +456,12 @@ class TokenStream { return m_tokenBuffer.front(); } - auto operator->() const -> Token const * { + auto operator->() const -> Token const* { assert(!m_tokenBuffer.empty()); return &m_tokenBuffer.front(); } - auto operator++() -> TokenStream & { + auto operator++() -> TokenStream& { if (m_tokenBuffer.size() >= 2) { m_tokenBuffer.erase(m_tokenBuffer.begin()); } else { @@ -488,7 +488,7 @@ class ResultBase { template class ResultValueBase : public ResultBase { public: - auto value() const -> T const & { + auto value() const -> T const& { enforceOk(); return m_value; } @@ -496,13 +496,13 @@ class ResultValueBase : public ResultBase { protected: ResultValueBase(Type type) : ResultBase(type) {} - ResultValueBase(ResultValueBase const &other) : ResultBase(other) { + 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); } + ResultValueBase(Type, T const& value) : ResultBase(Ok) { new (&m_value) T(value); } - auto operator=(ResultValueBase const &other) -> ResultValueBase & { + 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); @@ -528,20 +528,20 @@ template class BasicResult : public ResultValueBase { public: template - explicit BasicResult(BasicResult const &other) + explicit BasicResult(BasicResult const& other) : ResultValueBase(other.type()), m_errorMessage(other.errorMessage()) { assert(type() != ResultBase::Ok); } template - static auto ok(U const &value) -> BasicResult { + 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 { + static auto logicError(std::string const& message) -> BasicResult { return {ResultBase::LogicError, message}; } - static auto runtimeError(std::string const &message) -> BasicResult { + static auto runtimeError(std::string const& message) -> BasicResult { return {ResultBase::RuntimeError, message}; } @@ -560,7 +560,7 @@ class BasicResult : public ResultValueBase { std::string m_errorMessage; // Only populated if resultType is an error - BasicResult(ResultBase::Type type, std::string const &message) + BasicResult(ResultBase::Type type, std::string const& message) : ResultValueBase(type), m_errorMessage(message) { assert(m_type != ResultBase::Ok); } @@ -573,7 +573,7 @@ enum class ParseResultType { Matched, NoMatch, ShortCircuitAll, ShortCircuitSame class ParseState { public: - ParseState(ParseResultType type, TokenStream const &remainingTokens) + ParseState(ParseResultType type, TokenStream const& remainingTokens) : m_type(type), m_remainingTokens(remainingTokens) {} auto type() const -> ParseResultType { return m_type; } @@ -594,7 +594,7 @@ struct HelpColumns { }; template -inline auto convertInto(std::string const &source, T &target) -> ParserResult { +inline auto convertInto(std::string const& source, T& target) -> ParserResult { std::stringstream ss; ss << source; ss >> target; @@ -603,11 +603,11 @@ inline auto convertInto(std::string const &source, T &target) -> ParserResult { else return ParserResult::ok(ParseResultType::Matched); } -inline auto convertInto(std::string const &source, std::string &target) -> ParserResult { +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 { +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)); }); @@ -622,7 +622,7 @@ inline auto convertInto(std::string const &source, bool &target) -> ParserResult } #ifdef CLARA_CONFIG_OPTIONAL_TYPE template -inline auto convertInto(std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE &target) +inline auto convertInto(std::string const& source, CLARA_CONFIG_OPTIONAL_TYPE& target) -> ParserResult { T temp; auto result = convertInto(source, temp); @@ -633,10 +633,10 @@ inline auto convertInto(std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE struct NonCopyable { NonCopyable() = default; - NonCopyable(NonCopyable const &) = delete; - NonCopyable(NonCopyable &&) = delete; - NonCopyable &operator=(NonCopyable const &) = delete; - NonCopyable &operator=(NonCopyable &&) = delete; + NonCopyable(NonCopyable const&) = delete; + NonCopyable(NonCopyable&&) = delete; + NonCopyable& operator=(NonCopyable const&) = delete; + NonCopyable& operator=(NonCopyable&&) = delete; }; struct BoundRef : NonCopyable { @@ -645,7 +645,7 @@ struct BoundRef : NonCopyable { virtual auto isFlag() const -> bool { return false; } }; struct BoundValueRefBase : BoundRef { - virtual auto setValue(std::string const &arg) -> ParserResult = 0; + virtual auto setValue(std::string const& arg) -> ParserResult = 0; }; struct BoundFlagRefBase : BoundRef { virtual auto setFlag(bool flag) -> ParserResult = 0; @@ -654,22 +654,22 @@ struct BoundFlagRefBase : BoundRef { template struct BoundValueRef : BoundValueRefBase { - T &m_ref; + 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; + 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 setValue(std::string const &arg) -> ParserResult override { + auto setValue(std::string const& arg) -> ParserResult override { T temp; auto result = convertInto(arg, temp); if (result) m_ref.push_back(temp); @@ -678,9 +678,9 @@ struct BoundValueRef> : BoundValueRefBase { }; struct BoundFlagRef : BoundFlagRefBase { - bool &m_ref; + 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; @@ -694,7 +694,7 @@ struct LambdaInvoker { "Lambda must return void or clara::ParserResult"); template - static auto invoke(L const &lambda, ArgType const &arg) -> ParserResult { + static auto invoke(L const& lambda, ArgType const& arg) -> ParserResult { return lambda(arg); } }; @@ -702,14 +702,14 @@ struct LambdaInvoker { template <> struct LambdaInvoker { template - static auto invoke(L const &lambda, ArgType const &arg) -> ParserResult { + 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 { +inline auto invokeLambda(L const& lambda, std::string const& arg) -> ParserResult { ArgType temp{}; auto result = convertInto(arg, temp); return !result ? result @@ -721,9 +721,9 @@ 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) {} + explicit BoundLambda(L const& lambda) : m_lambda(lambda) {} - auto setValue(std::string const &arg) -> ParserResult override { + auto setValue(std::string const& arg) -> ParserResult override { return invokeLambda::ArgType>(m_lambda, arg); } }; @@ -736,7 +736,7 @@ struct BoundFlagLambda : BoundFlagRefBase { 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); @@ -751,11 +751,11 @@ 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 + 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 { + auto parse(Args const& args) const -> InternalParseResult { return parse(args.exeName(), TokenStream(args)); } }; @@ -764,10 +764,10 @@ template class ComposableParserImpl : public ParserBase { public: template - auto operator|(T const &other) const -> Parser; + auto operator|(T const& other) const -> Parser; template - auto operator+(T const &other) const -> Parser; + auto operator+(T const& other) const -> Parser; }; // Common code and state for Args and Opts @@ -779,30 +779,30 @@ class ParserRefImpl : public ComposableParserImpl { 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) + 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) + ParserRefImpl(LambdaT const& ref, std::string const& hint) : m_ref(std::make_shared>(ref)), m_hint(hint) {} - auto operator()(std::string const &description) -> DerivedT & { + auto operator()(std::string const& description) -> DerivedT& { m_description = description; - return static_cast(*this); + return static_cast(*this); } - auto optional() -> DerivedT & { + auto optional() -> DerivedT& { m_optionality = Optionality::Optional; - return static_cast(*this); + return static_cast(*this); }; - auto required() -> DerivedT & { + auto required() -> DerivedT& { m_optionality = Optionality::Required; - return static_cast(*this); + return static_cast(*this); }; auto isOptional() const -> bool { return m_optionality == Optionality::Optional; } @@ -822,29 +822,29 @@ class ExeName : public ComposableParserImpl { std::shared_ptr m_ref; template - static auto makeRef(LambdaT const &lambda) -> std::shared_ptr { + static auto makeRef(LambdaT const& lambda) -> std::shared_ptr { return std::make_shared>(lambda); } public: ExeName() : m_name(std::make_shared("")) {} - explicit ExeName(std::string &ref) : ExeName() { + explicit ExeName(std::string& ref) : ExeName() { m_ref = std::make_shared>(ref); } template - explicit ExeName(LambdaT const &lambda) : ExeName() { + 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 { + 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 set(std::string const& newName) -> ParserResult { auto lastSlash = newName.find_last_of("\\/"); auto filename = (lastSlash == std::string::npos) ? newName : newName.substr(lastSlash + 1); @@ -860,17 +860,17 @@ class Arg : public ParserRefImpl { public: using ParserRefImpl::ParserRefImpl; - auto parse(std::string const &, TokenStream const &tokens) const -> InternalParseResult override { + auto parse(std::string const&, TokenStream const& tokens) const -> InternalParseResult override { auto validationResult = validate(); if (!validationResult) return InternalParseResult(validationResult); auto remainingTokens = tokens; - auto const &token = *remainingTokens; + auto const& token = *remainingTokens; if (token.type != TokenType::Argument) return InternalParseResult::ok(ParseState(ParseResultType::NoMatch, remainingTokens)); assert(!m_ref->isFlag()); - auto valueRef = static_cast(m_ref.get()); + auto valueRef = static_cast(m_ref.get()); auto result = valueRef->setValue(remainingTokens->token); if (!result) @@ -880,7 +880,7 @@ class Arg : public ParserRefImpl { } }; -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); @@ -895,18 +895,18 @@ class Opt : public ParserRefImpl { public: template - explicit Opt(LambdaT const &ref) + explicit Opt(LambdaT const& ref) : ParserRefImpl(std::make_shared>(ref)) {} - explicit Opt(bool &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) {} + Opt(LambdaT const& ref, std::string const& hint) : ParserRefImpl(ref, hint) {} template - Opt(T &ref, std::string const &hint) : ParserRefImpl(ref, hint) {} + Opt(T& ref, std::string const& hint) : ParserRefImpl(ref, hint) {} - auto operator[](std::string const &optName) -> Opt & { + auto operator[](std::string const& optName) -> Opt& { m_optNames.push_back(optName); return *this; } @@ -914,7 +914,7 @@ class Opt : public ParserRefImpl { auto getHelpColumns() const -> std::vector { std::ostringstream oss; bool first = true; - for (auto const &opt : m_optNames) { + for (auto const& opt : m_optNames) { if (first) first = false; else @@ -925,9 +925,9 @@ class Opt : public ParserRefImpl { return {{oss.str(), m_description}}; } - auto isMatch(std::string const &optToken) const -> bool { + auto isMatch(std::string const& optToken) const -> bool { auto normalisedToken = normaliseOpt(optToken); - for (auto const &name : m_optNames) { + for (auto const& name : m_optNames) { if (normaliseOpt(name) == normalisedToken) return true; } return false; @@ -935,26 +935,26 @@ class Opt : public ParserRefImpl { using ParserBase::parse; - auto parse(std::string const &, TokenStream const &tokens) const -> InternalParseResult override { + 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; + auto const& token = *remainingTokens; if (isMatch(token.token)) { if (m_ref->isFlag()) { - auto flagRef = static_cast(m_ref.get()); + 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()); + auto valueRef = static_cast(m_ref.get()); ++remainingTokens; if (!remainingTokens) return InternalParseResult::runtimeError("Expected argument following " + token.token); - auto const &argToken = *remainingTokens; + auto const& argToken = *remainingTokens; if (argToken.type != TokenType::Argument) return InternalParseResult::runtimeError("Expected argument following " + token.token); auto result = valueRef->setValue(argToken.token); @@ -970,7 +970,7 @@ class Opt : public ParserRefImpl { auto validate() const -> Result override { if (m_optNames.empty()) return Result::logicError("No options supplied to Opt"); - for (auto const &name : m_optNames) { + 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] != '/') @@ -984,12 +984,12 @@ class Opt : public ParserRefImpl { }; struct Help : Opt { - Help(bool &showHelpFlag) + Help(bool& showHelpFlag) : Opt([&](bool flag) { showHelpFlag = flag; return ParserResult::ok(ParseResultType::ShortCircuitAll); }) { - static_cast(*this)("display usage information")["-?"]["-h"]["--help"].optional(); + static_cast(*this)("display usage information")["-?"]["-h"]["--help"].optional(); } }; @@ -998,57 +998,57 @@ struct Parser : ParserBase { std::vector m_options; std::vector m_args; - auto operator|=(ExeName const &exeName) -> Parser & { + auto operator|=(ExeName const& exeName) -> Parser& { m_exeName = exeName; return *this; } - auto operator|=(Arg const &arg) -> Parser & { + auto operator|=(Arg const& arg) -> Parser& { m_args.push_back(arg); return *this; } - auto operator|=(Opt const &opt) -> Parser & { + auto operator|=(Opt const& opt) -> Parser& { m_options.push_back(opt); return *this; } - auto operator|=(Parser const &other) -> Parser & { + 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 { + auto operator|(T const& other) const -> Parser { return Parser(*this) |= other; } // Forward deprecated interface with '+' instead of '|' template - auto operator+=(T const &other) -> Parser & { + auto operator+=(T const& other) -> Parser& { return operator|=(other); } template - auto operator+(T const &other) const -> Parser { + auto operator+(T const& other) const -> Parser { return operator|(other); } auto getHelpColumns() const -> std::vector { std::vector cols; - for (auto const &o : m_options) { + 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 { + 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) { + for (auto const& arg : m_args) { if (first) first = false; else @@ -1068,28 +1068,28 @@ struct Parser : ParserBase { 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); + for (auto const& cols : rows) optWidth = (std::max)(optWidth, cols.left.size() + 2); optWidth = (std::min)(optWidth, consoleWidth / 2); - for (auto const &cols : rows) { + 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 & { + 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) { + for (auto const& opt : m_options) { auto result = opt.validate(); if (!result) return result; } - for (auto const &arg : m_args) { + for (auto const& arg : m_args) { auto result = arg.validate(); if (!result) return result; } @@ -1098,10 +1098,10 @@ struct Parser : ParserBase { using ParserBase::parse; - auto parse(std::string const &exeName, TokenStream const &tokens) const + auto parse(std::string const& exeName, TokenStream const& tokens) const -> InternalParseResult override { struct ParserInfo { - ParserBase const *parser = nullptr; + ParserBase const* parser = nullptr; size_t count = 0; }; const size_t totalParsers = m_options.size() + m_args.size(); @@ -1111,8 +1111,8 @@ struct Parser : ParserBase { { size_t i = 0; - for (auto const &opt : m_options) parseInfos[i++].parser = &opt; - for (auto const &arg : m_args) parseInfos[i++].parser = &arg; + for (auto const& opt : m_options) parseInfos[i++].parser = &opt; + for (auto const& arg : m_args) parseInfos[i++].parser = &arg; } m_exeName.set(exeName); @@ -1122,7 +1122,7 @@ struct Parser : ParserBase { bool tokenParsed = false; for (size_t i = 0; i < totalParsers; ++i) { - auto &parseInfo = parseInfos[i]; + auto& parseInfo = parseInfos[i]; if (parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality()) { result = parseInfo.parser->parse(exeName, result.value().remainingTokens()); @@ -1147,8 +1147,8 @@ struct Parser : ParserBase { template template -auto ComposableParserImpl::operator|(T const &other) const -> Parser { - return Parser() | static_cast(*this) | other; +auto ComposableParserImpl::operator|(T const& other) const -> Parser { + return Parser() | static_cast(*this) | other; } } // namespace detail diff --git a/include/util/command.hpp b/include/util/command.hpp index 4b9decaa..f6d2cabf 100644 --- a/include/util/command.hpp +++ b/include/util/command.hpp @@ -20,6 +20,8 @@ extern std::list reap; namespace waybar::util::command { +constexpr int kExecFailureExitCode = 127; + struct res { int exit_code; std::string out; @@ -59,6 +61,7 @@ inline int close(FILE* fp, pid_t pid) { spdlog::debug("Cmd continued"); } else if (ret == -1) { spdlog::debug("waitpid failed: {}", strerror(errno)); + break; } else { break; } @@ -109,11 +112,13 @@ inline FILE* open(const std::string& cmd, int& pid, const std::string& output_na ::close(fd[0]); dup2(fd[1], 1); setpgid(child_pid, child_pid); - if (output_name != "") { + if (!output_name.empty()) { setenv("WAYBAR_OUTPUT_NAME", output_name.c_str(), 1); } execlp("/bin/sh", "sh", "-c", cmd.c_str(), (char*)0); - exit(0); + const int saved_errno = errno; + spdlog::error("execlp(/bin/sh) failed in open: {}", strerror(saved_errno)); + _exit(kExecFailureExitCode); } else { ::close(fd[1]); } @@ -138,7 +143,7 @@ inline struct res execNoRead(const std::string& cmd) { return {WEXITSTATUS(stat), ""}; } -inline int32_t forkExec(const std::string& cmd) { +inline int32_t forkExec(const std::string& cmd, const std::string& output_name) { if (cmd == "") return -1; pid_t pid = fork(); @@ -157,8 +162,13 @@ inline int32_t forkExec(const std::string& cmd) { err = pthread_sigmask(SIG_UNBLOCK, &mask, nullptr); if (err != 0) spdlog::error("pthread_sigmask in forkExec failed: {}", strerror(err)); setpgid(pid, pid); + if (!output_name.empty()) { + setenv("WAYBAR_OUTPUT_NAME", output_name.c_str(), 1); + } execl("/bin/sh", "sh", "-c", cmd.c_str(), (char*)0); - exit(0); + const int saved_errno = errno; + spdlog::error("execl(/bin/sh) failed in forkExec: {}", strerror(saved_errno)); + _exit(kExecFailureExitCode); } else { reap_mtx.lock(); reap.push_back(pid); @@ -169,4 +179,6 @@ inline int32_t forkExec(const std::string& cmd) { return pid; } +inline int32_t forkExec(const std::string& cmd) { return forkExec(cmd, ""); } + } // namespace waybar::util::command diff --git a/include/util/css_reload_helper.hpp b/include/util/css_reload_helper.hpp index 032b2382..e198a5b0 100644 --- a/include/util/css_reload_helper.hpp +++ b/include/util/css_reload_helper.hpp @@ -14,12 +14,14 @@ struct pollfd; namespace waybar { class CssReloadHelper { public: - CssReloadHelper(std::string cssFile, std::function callback); + CssReloadHelper(std::string cssFile, std::function callback); virtual ~CssReloadHelper() = default; virtual void monitorChanges(); + virtual void changeCssFile(const std::string& newCssFile); + protected: std::vector parseImports(const std::string& cssFile); @@ -42,7 +44,7 @@ class CssReloadHelper { private: std::string m_cssFile; - std::function m_callback; + std::function m_callback; std::vector>> m_fileMonitors; }; diff --git a/include/util/date.hpp b/include/util/date.hpp index a467cc56..d8653faf 100644 --- a/include/util/date.hpp +++ b/include/util/date.hpp @@ -15,7 +15,7 @@ namespace date { #if HAVE_CHRONO_TIMEZONES using namespace std::chrono; -using namespace std; +using std::format; #else using system_clock = std::chrono::system_clock; @@ -73,5 +73,3 @@ struct fmt::formatter> { } }; #endif - -using namespace date; diff --git a/include/util/gtk_icon.hpp b/include/util/gtk_icon.hpp index 44555f65..06f15abe 100644 --- a/include/util/gtk_icon.hpp +++ b/include/util/gtk_icon.hpp @@ -10,5 +10,7 @@ class DefaultGtkIconThemeWrapper { public: static bool has_icon(const std::string&); - static Glib::RefPtr load_icon(const char*, int, Gtk::IconLookupFlags); + static Glib::RefPtr load_icon( + const char*, int, Gtk::IconLookupFlags, + Glib::RefPtr style = Glib::RefPtr()); }; diff --git a/include/util/hex_checker.hpp b/include/util/hex_checker.hpp new file mode 100644 index 00000000..27a84d1f --- /dev/null +++ b/include/util/hex_checker.hpp @@ -0,0 +1,17 @@ +#pragma once + +#include + +/** + * Result of transforming 8-bit hex codes to rgba(). + */ +struct TransformResult { + std::string css; + bool was_transformed; +}; + +/** + * Reads a CSS file, searches for 8-bit hex codes (#RRGGBBAA), + * and transforms them into GTK-compatible rgba() syntax. + */ +TransformResult transform_8bit_to_hex(const std::string& file_path); diff --git a/include/util/icon_loader.hpp b/include/util/icon_loader.hpp new file mode 100644 index 00000000..f9256eb5 --- /dev/null +++ b/include/util/icon_loader.hpp @@ -0,0 +1,34 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "util/gtk_icon.hpp" + +class IconLoader { + private: + std::vector> custom_icon_themes_; + Glib::RefPtr default_icon_theme_ = Gtk::IconTheme::get_default(); + static std::vector search_prefix(); + static Glib::RefPtr get_app_info_by_name(const std::string& app_id); + static Glib::RefPtr get_desktop_app_info(const std::string& app_id); + static Glib::RefPtr load_icon_from_file(std::string const& icon_path, int size); + static std::string get_icon_name_from_icon_theme(const Glib::RefPtr& icon_theme, + const std::string& app_id); + static bool image_load_icon(Gtk::Image& image, const Glib::RefPtr& icon_theme, + Glib::RefPtr app_info, int size); + + public: + void add_custom_icon_theme(const std::string& theme_name); + bool image_load_icon(Gtk::Image& image, Glib::RefPtr app_info, + int size) const; + static Glib::RefPtr get_app_info_from_app_id_list( + const std::string& app_id_list); +}; diff --git a/include/util/json.hpp b/include/util/json.hpp index f0736f9b..5f45ae92 100644 --- a/include/util/json.hpp +++ b/include/util/json.hpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #if (FMT_VERSION >= 90000) @@ -26,19 +27,25 @@ class JsonParser { Json::Value root; // replace all occurrences of "\x" with "\u00", because JSON doesn't allow "\x" escape sequences - std::string modifiedJsonStr = replaceHexadecimalEscape(jsonStr); + std::string modifiedJsonStr; + const std::string* json = &jsonStr; + if (jsonStr.find("\\x") != std::string::npos) { + modifiedJsonStr = replaceHexadecimalEscape(jsonStr); + json = &modifiedJsonStr; + } - std::istringstream jsonStream(modifiedJsonStr); std::string errs; - if (!Json::parseFromStream(m_readerBuilder, jsonStream, &root, &errs)) { + // Use local CharReaderBuilder for thread safety - the IPC singleton's + // parser can be called concurrently from multiple module threads + Json::CharReaderBuilder readerBuilder; + auto reader = std::unique_ptr(readerBuilder.newCharReader()); + if (!reader->parse(json->data(), json->data() + json->size(), &root, &errs)) { throw std::runtime_error("Error parsing JSON: " + errs); } return root; } private: - Json::CharReaderBuilder m_readerBuilder; - static std::string replaceHexadecimalEscape(const std::string& str) { static std::regex re("\\\\x"); return std::regex_replace(str, re, "\\u00"); diff --git a/include/util/kill_signal.hpp b/include/util/kill_signal.hpp new file mode 100644 index 00000000..26d156e9 --- /dev/null +++ b/include/util/kill_signal.hpp @@ -0,0 +1,26 @@ +#pragma once + +#include + +#include + +namespace waybar::util { + +enum class KillSignalAction : std::uint8_t { + TOGGLE, + RELOAD, + SHOW, + HIDE, + NOOP, +}; +const std::map userKillSignalActions = { + {"TOGGLE", KillSignalAction::TOGGLE}, + {"RELOAD", KillSignalAction::RELOAD}, + {"SHOW", KillSignalAction::SHOW}, + {"HIDE", KillSignalAction::HIDE}, + {"NOOP", KillSignalAction::NOOP}}; + +const KillSignalAction SIGNALACTION_DEFAULT_SIGUSR1 = KillSignalAction::TOGGLE; +const KillSignalAction SIGNALACTION_DEFAULT_SIGUSR2 = KillSignalAction::RELOAD; + +}; // namespace waybar::util diff --git a/include/util/pipewire/privacy_node_info.hpp b/include/util/pipewire/privacy_node_info.hpp index 7b8df018..54acad42 100644 --- a/include/util/pipewire/privacy_node_info.hpp +++ b/include/util/pipewire/privacy_node_info.hpp @@ -25,6 +25,7 @@ class PrivacyNodeInfo { std::string media_name; std::string node_name; std::string application_name; + bool is_monitor = false; std::string pipewire_access_portal_app_id; std::string application_icon_name; @@ -32,14 +33,14 @@ class PrivacyNodeInfo { struct spa_hook object_listener; struct spa_hook proxy_listener; - void *data; + void* data; std::string getName(); std::string getIconName(); // Handlers for PipeWire events void handleProxyEventDestroy(); - void handleNodeEventInfo(const struct pw_node_info *info); + void handleNodeEventInfo(const struct pw_node_info* info); }; } // namespace waybar::util::PipewireBackend diff --git a/include/util/portal.hpp b/include/util/portal.hpp index 23619169..bff74b11 100644 --- a/include/util/portal.hpp +++ b/include/util/portal.hpp @@ -6,14 +6,12 @@ namespace waybar { -using namespace Gio; - enum class Appearance { UNKNOWN = 0, DARK = 1, LIGHT = 2, }; -class Portal : private DBus::Proxy { +class Portal : private Gio::DBus::Proxy { public: Portal(); void refreshAppearance(); diff --git a/include/util/prepare_for_sleep.h b/include/util/prepare_for_sleep.h index 68db8d8e..82f3b627 100644 --- a/include/util/prepare_for_sleep.h +++ b/include/util/prepare_for_sleep.h @@ -4,6 +4,6 @@ namespace waybar::util { -// Get a signal emited with value true when entering sleep, and false when exiting +// Get a signal emitted with value true when entering sleep, and false when exiting SafeSignal& prepare_for_sleep(); } // namespace waybar::util diff --git a/include/util/rfkill.hpp b/include/util/rfkill.hpp index f620db53..47ab729b 100644 --- a/include/util/rfkill.hpp +++ b/include/util/rfkill.hpp @@ -5,6 +5,8 @@ #include #include +#include + namespace waybar::util { class Rfkill : public sigc::trackable { @@ -17,7 +19,7 @@ class Rfkill : public sigc::trackable { private: enum rfkill_type rfkill_type_; - bool state_ = false; + std::atomic_bool state_ = false; int fd_ = -1; bool on_event(Glib::IOCondition cond); diff --git a/include/util/scoped_fd.hpp b/include/util/scoped_fd.hpp new file mode 100644 index 00000000..e970109e --- /dev/null +++ b/include/util/scoped_fd.hpp @@ -0,0 +1,54 @@ +#pragma once + +#include + +namespace waybar::util { + +class ScopedFd { + public: + explicit ScopedFd(int fd = -1) : fd_(fd) {} + ~ScopedFd() { + if (fd_ != -1) { + close(fd_); + } + } + + // ScopedFd is non-copyable + ScopedFd(const ScopedFd&) = delete; + ScopedFd& operator=(const ScopedFd&) = delete; + + // ScopedFd is moveable + ScopedFd(ScopedFd&& other) noexcept : fd_(other.fd_) { other.fd_ = -1; } + ScopedFd& operator=(ScopedFd&& other) noexcept { + if (this != &other) { + if (fd_ != -1) { + close(fd_); + } + fd_ = other.fd_; + other.fd_ = -1; + } + return *this; + } + + int get() const { return fd_; } + + operator int() const { return fd_; } + + void reset(int fd = -1) { + if (fd_ != -1) { + close(fd_); + } + fd_ = fd; + } + + int release() { + int fd = fd_; + fd_ = -1; + return fd; + } + + private: + int fd_; +}; + +} // namespace waybar::util diff --git a/include/util/sleeper_thread.hpp b/include/util/sleeper_thread.hpp index 62d12931..9d20f252 100644 --- a/include/util/sleeper_thread.hpp +++ b/include/util/sleeper_thread.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -31,8 +32,8 @@ class SleeperThread { SleeperThread(std::function func) : thread_{[this, func] { - while (do_run_) { - signal_ = false; + while (do_run_.load(std::memory_order_relaxed)) { + signal_.store(false, std::memory_order_relaxed); func(); } }} { @@ -42,9 +43,18 @@ class SleeperThread { } SleeperThread& operator=(std::function func) { + if (thread_.joinable()) { + stop(); + thread_.join(); + } + { + std::lock_guard lck(mutex_); + do_run_.store(true, std::memory_order_relaxed); + signal_.store(false, std::memory_order_relaxed); + } thread_ = std::thread([this, func] { - while (do_run_) { - signal_ = false; + while (do_run_.load(std::memory_order_relaxed)) { + signal_.store(false, std::memory_order_relaxed); func(); } }); @@ -56,24 +66,34 @@ class SleeperThread { return *this; } - bool isRunning() const { return do_run_; } + bool isRunning() const { return do_run_.load(std::memory_order_relaxed); } auto sleep() { std::unique_lock lk(mutex_); CancellationGuard cancel_lock; - return condvar_.wait(lk, [this] { return signal_ || !do_run_; }); + return condvar_.wait(lk, [this] { + return signal_.load(std::memory_order_relaxed) || !do_run_.load(std::memory_order_relaxed); + }); } auto sleep_for(std::chrono::system_clock::duration dur) { std::unique_lock lk(mutex_); CancellationGuard cancel_lock; + + condvar_.wait(lk, [this] { + return !is_paused_ || signal_.load(std::memory_order_relaxed) || + !do_run_.load(std::memory_order_relaxed); + }); + constexpr auto max_time_point = std::chrono::steady_clock::time_point::max(); auto wait_end = max_time_point; auto now = std::chrono::steady_clock::now(); if (now < max_time_point - dur) { wait_end = now + dur; } - return condvar_.wait_until(lk, wait_end, [this] { return signal_ || !do_run_; }); + return condvar_.wait_until(lk, wait_end, [this] { + return signal_.load(std::memory_order_relaxed) || !do_run_.load(std::memory_order_relaxed); + }); } auto sleep_until( @@ -81,22 +101,30 @@ class SleeperThread { time_point) { std::unique_lock lk(mutex_); CancellationGuard cancel_lock; - return condvar_.wait_until(lk, time_point, [this] { return signal_ || !do_run_; }); + + condvar_.wait(lk, [this] { + return !is_paused_ || signal_.load(std::memory_order_relaxed) || + !do_run_.load(std::memory_order_relaxed); + }); + + return condvar_.wait_until(lk, time_point, [this] { + return signal_.load(std::memory_order_relaxed) || !do_run_.load(std::memory_order_relaxed); + }); } void wake_up() { { std::lock_guard lck(mutex_); - signal_ = true; + signal_.store(true, std::memory_order_relaxed); } condvar_.notify_all(); } - auto stop() { + void stop() { { std::lock_guard lck(mutex_); - signal_ = true; - do_run_ = false; + signal_.store(true, std::memory_order_relaxed); + do_run_.store(false, std::memory_order_relaxed); } condvar_.notify_all(); auto handle = thread_.native_handle(); @@ -106,6 +134,17 @@ class SleeperThread { } } + void pause() { + std::lock_guard lock(mutex_); + is_paused_ = true; + } + + void resume() { + std::lock_guard lock(mutex_); + is_paused_ = false; + condvar_.notify_all(); + } + ~SleeperThread() { connection_.disconnect(); stop(); @@ -118,9 +157,10 @@ class SleeperThread { std::thread thread_; std::condition_variable condvar_; std::mutex mutex_; - bool do_run_ = true; - bool signal_ = false; + std::atomic do_run_ = true; + std::atomic signal_ = false; sigc::connection connection_; + bool is_paused_{false}; }; } // namespace waybar::util diff --git a/include/util/string.hpp b/include/util/string.hpp index d06557c1..cb8a6892 100644 --- a/include/util/string.hpp +++ b/include/util/string.hpp @@ -23,3 +23,26 @@ inline std::string capitalize(const std::string& str) { [](unsigned char c) { return std::toupper(c); }); return result; } + +inline std::string toLower(const std::string& str) { + std::string result = str; + std::transform(result.begin(), result.end(), result.begin(), + [](unsigned char c) { return std::tolower(c); }); + return result; +} + +inline std::vector split(std::string_view s, std::string_view delimiter, + int max_splits = -1) { + std::vector result; + size_t pos = 0; + size_t next_pos = 0; + while ((next_pos = s.find(delimiter, pos)) != std::string::npos) { + result.push_back(std::string(s.substr(pos, next_pos - pos))); + pos = next_pos + delimiter.size(); + if (max_splits > 0 && result.size() == static_cast(max_splits)) { + break; + } + } + result.push_back(std::string(s.substr(pos))); + return result; +} diff --git a/include/util/udev_deleter.hpp b/include/util/udev_deleter.hpp new file mode 100644 index 00000000..77493c4a --- /dev/null +++ b/include/util/udev_deleter.hpp @@ -0,0 +1,21 @@ +#pragma once + +#include + +namespace waybar::util { +struct UdevDeleter { + void operator()(udev* ptr) const { udev_unref(ptr); } +}; + +struct UdevDeviceDeleter { + void operator()(udev_device* ptr) const { udev_device_unref(ptr); } +}; + +struct UdevEnumerateDeleter { + void operator()(udev_enumerate* ptr) const { udev_enumerate_unref(ptr); } +}; + +struct UdevMonitorDeleter { + void operator()(udev_monitor* ptr) const { udev_monitor_unref(ptr); } +}; +} // namespace waybar::util \ No newline at end of file diff --git a/include/util/ustring_clen.hpp b/include/util/ustring_clen.hpp index cddd2e1a..63311d53 100644 --- a/include/util/ustring_clen.hpp +++ b/include/util/ustring_clen.hpp @@ -2,4 +2,4 @@ #include // calculate column width of ustring -int ustring_clen(const Glib::ustring &str); \ No newline at end of file +int ustring_clen(const Glib::ustring& str); \ No newline at end of file diff --git a/include/util/utf8_string.hpp b/include/util/utf8_string.hpp new file mode 100644 index 00000000..07a04466 --- /dev/null +++ b/include/util/utf8_string.hpp @@ -0,0 +1,7 @@ +#pragma once +#include + +namespace waybar::util { +size_t utf8_width(const std::string& str); +void utf8_truncate(std::string& s, const std::string& ellipsis, size_t max_len); +} // namespace waybar::util diff --git a/man/waybar-battery.5.scd b/man/waybar-battery.5.scd index a3c21a20..0c71518c 100644 --- a/man/waybar-battery.5.scd +++ b/man/waybar-battery.5.scd @@ -27,6 +27,11 @@ The *battery* module displays the current capacity and state (eg. charging) of y default: false ++ Option to use the battery design capacity instead of its current maximal capacity. +*full-at-plugged*: ++ + typeof: bool ++ + default: false ++ + When enabled, a battery that is *Full* while the adapter is online is reported with the *Plugged* status instead of *Full* (so you can style/format it separately). Disabled by default to preserve the existing *Full* behaviour. + *interval*: ++ typeof: integer ++ default: 60 ++ @@ -91,6 +96,11 @@ The *battery* module displays the current capacity and state (eg. charging) of y typeof: string ++ Command to execute when scrolling up on the module. +*weighted-average*: ++ + typeof: bool ++ + default: true ++ + Option to combine multiple batteries with different capacities. + *on-scroll-down*: ++ typeof: string ++ Command to execute when scrolling down on the module. @@ -116,7 +126,7 @@ The *battery* module displays the current capacity and state (eg. charging) of y *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type - GtkMenu with id *menu* + GtkMenu with id *menu*. *menu-actions*: ++ typeof: array ++ @@ -127,6 +137,10 @@ The *battery* module displays the current capacity and state (eg. charging) of y default: false ++ Enables this module to consume all left over space dynamically. +*events*: ++ + typeof: object ++ + Specifies commands to be executed on specific battery states. See *EVENTS* section below. + # FORMAT REPLACEMENTS *{capacity}*: Capacity in percentage @@ -166,6 +180,20 @@ The *battery* module allows one to define custom formats based on up to two fact - The state can be addressed as a CSS class in the *style.css*. The name of the CSS class is the ** of the state. Each class gets activated when the current capacity is equal to or below the configured **. - Also each state can have its own *format*. Those can be configured via *format-*. Or if you want to differentiate a bit more even as *format--*. For more information see *custom-formats*. +# EVENTS + +Every entry in the *events* object consists of a ** (typeof: *string*) and a ** (typeof: *string*). ++ +** can be in one of the following formats: + +- *on--* +- *on--* +- *on-* + +Where: + +- ** is either *charging* or *discharging*, +- ** is the name of one of the states specified in the *states* object, +- ** is a battery level value (between *0-100*). # EXAMPLES @@ -178,6 +206,13 @@ The *battery* module allows one to define custom formats based on up to two fact "warning": 30, "critical": 15 }, + "events": { + "on-discharging-warning": "notify-send -u normal 'Low Battery'", + "on-discharging-critical": "notify-send -u critical 'Very Low Battery'", + "on-charging-100": "notify-send -u normal 'Battery Full!'", + "on-discharging": "notify-send -u normal 'Power Switch' Discharging", + "on-charging": "notify-send -u normal 'Power Switch' Charging'" + }, "format": "{capacity}% {icon}", "format-icons": ["", "", "", "", ""], "max-length": 25 diff --git a/man/waybar-cava.5.scd b/man/waybar-cava.5.scd index 7825c38a..95336e24 100644 --- a/man/waybar-cava.5.scd +++ b/man/waybar-cava.5.scd @@ -8,6 +8,8 @@ waybar - cava module *cava* module for karlstav/cava project. See it on github: https://github.com/karlstav/cava. +Module supports two different frontends starting from the 0.15.0 release. The frontend that +will be used is managed by the method parameter in the [output] section of the cava configuration file. # FILES @@ -32,6 +34,10 @@ libcava lives in: :[ string :[ :< Path where cava configuration file is placed to +|[ *method* \[output\] +:[ string +:[ +:< Manages which frontend Waybar cava module should use. Values: raw, sdl_glsl |[ *framerate* :[ integer :[ 30 @@ -43,7 +49,7 @@ libcava lives in: |[ *sensitivity* :[ integer :[ 100 -:[ Manual sensitivity in %. It's recommended to be omitted when *autosens* = 1 +:[ Manual sensitivity in %. If autosens is enabled, this will only be the initial value. 200 means double height. Accepts only non-negative values |[ *bars* :[ integer :[ 12 @@ -68,7 +74,7 @@ libcava lives in: :[ string :[ :[ Widget's text after sleep_timer elapsed (hide_on_silence has to be false) -|[ *method* +|[ *method* \[input\] :[ string :[ pulse :[ Audio capturing method. Possible methods are: pipewire, pulse, alsa, fifo, sndio or shmem @@ -105,9 +111,9 @@ libcava lives in: :[ false :[ Disables or enables the so-called "Monstercat smoothing" with or without "waves" |[ *noise_reduction* -:[ double -:[ 0.77 -:[ Range between 0 - 1. The raw visualization is very noisy, this factor adjusts the integral and gravity filters to keep the signal smooth. 1 - will be very slow and smooth, 0 - will be fast but noisy +:[ integer +:[ 77 +:[ Range between 0 - 100. The raw visualization is very noisy, this factor adjusts the integral and gravity filters to keep the signal smooth. 100 will be very slow and smooth, 0 will be fast but noisy |[ *input_delay* :[ integer :[ 2 @@ -119,11 +125,11 @@ libcava lives in: |[ *data_format* :[ string :[ asci -:[ It's impossible to set it. Waybar sets it to = asci for internal needs +:[ Raw data format. Can be 'binary' or 'ascii' |[ *raw_target* :[ string :[ /dev/stdout -:[ It's impossible to set it. Waybar sets it to = /dev/stdout for internal needs +:[ Raw output target. A fifo will be created if target does not exist |[ *menu* :[ string :[ @@ -136,6 +142,50 @@ libcava lives in: :[ array :[ :[ The actions corresponding to the buttons of the menu. +|[ *bar_spacing* +:[ integer +:[ +:[ Bars' space between bars in number of characters +|[ *bar_width* +:[ integer +:[ +:[ Bars' width between bars in number of characters +|[ *bar_height* +:[ integer +:[ +:[ Useless. bar_height is only used for output in "noritake" format +|[ *background* +:[ string +:[ +:[ GLSL actual. Support hex code colors only. Must be within '' +|[ *foreground* +:[ string +:[ +:[ GLSL actual. Support hex code colors only. Must be within '' +|[ *gradient* +:[ integer +:[ 0 +:[ GLSL actual. Gradient mode(0/1 - on/off) +|[ *gradient_count* +:[ integer +:[ 0 +:[ GLSL actual. The count of colors for the gradient +|[ *gradient_color_N* +:[ string +:[ +:[ GLSL actual. N - the number of the gradient color between 1 and 8. Only hex defined colors are supported. Must be within '' +|[ *sdl_width* +:[ integer +:[ +:[ GLSL actual. Manages the width of the waybar cava GLSL frontend module +|[ *sdl_height* +:[ integer +:[ +:[ GLSL actual. Manages the height of the waybar cava GLSL frontend module +|[ *continuous_rendering* +:[ integer +:[ 0 +:[ GLSL actual. Keep rendering even if no audio. Recommended to set to 1 Configuration can be provided as: - The only cava configuration file which is provided through *cava_config*. The rest configuration can be skipped @@ -153,16 +203,17 @@ Configuration can be provided as: - iniparser - fftw3 +- epoxy (GLSL frontend only) # SOLVING ISSUES . On start Waybar throws an exception "error while loading shared libraries: libcava.so: cannot open shared object file: No such file or directory". It might happen when libcava for some reason hasn't been registered in the system. sudo ldconfig should help . Waybar is starting but cava module doesn't react to the music - 1. In such cases at first need to make sure usual cava application is working as well - 2. If so, need to comment all configuration options. Uncomment cava_config and provide the path to the working cava config - 3. You might set too huge or too small input_delay. Try to setup to 4 seconds, restart waybar, and check again 4 seconds past. Usual even on weak machines it should be enough - 4. You might accidentally switch action mode to pause mode + 1. In such cases at first need to make sure usual cava application is working as well + 2. If so, need to comment all configuration options. Uncomment cava_config and provide the path to the working cava config + 3. You might set too huge or too small input_delay. Try to setup to 4 seconds, restart waybar, and check again 4 seconds past. Usual even on weak machines it should be enough + 4. You might accidentally switch action mode to pause mode # RISING ISSUES @@ -205,3 +256,453 @@ In case when cava releases new version and you're wanna get it, it should be rai - *#cava* - *#cava.silent* Applied after no sound has been detected for sleep_timer seconds - *#cava.updated* Applied when a new frame is shown +# FRONTENDS + +## RAW +The cava raw frontend uses ASCII characters to visualize incoming audio data. Each ASCII symbol position corresponds to the value of the audio power pulse. + +Under the hood: +``` +. Incoming audio power pulse list is : 12684 +. Configured array of ASCII codes is: ["▁", "▂", "▃", "▄", "▅", "▆", "▇", "█" ]. See `format-icons` https://github.com/Alexays/Waybar/wiki/Module:-Cava#example +``` +As a result cava frontend will give ▁▂▆█▄ + +Examples: + +waybar config +``` +"cava": { + "cava_config": "$XDG_CONFIG_HOME/cava/waybar_raw.conf", + "input_delay": 2, + "format-icons" : ["▁", "▂", "▃", "▄", "▅", "▆", "▇", "█" ], + "actions": { + "on-click-right": "mode" + } + }, +``` + +waybar_raw.conf +``` +## Configuration file for CAVA. +# Remove the ; to change parameters. + + +[general] + +# Smoothing mode. Can be 'normal', 'scientific' or 'waves'. DEPRECATED as of 0.6.0 + +# Accepts only non-negative values. + +# 'autosens' will attempt to decrease sensitivity if the bars peak. 1 = on, 0 = off +# new as of 0.6.0 autosens of low values (dynamic range) +# 'overshoot' allows bars to overshoot (in % of terminal height) without initiating autosens. DEPRECATED as of 0.6.0 + +# Manual sensitivity in %. If autosens is enabled, this will only be the initial value. +# 200 means double height. Accepts only non-negative values. + +# The number of bars (0-512). 0 sets it to auto (fill up console). +# Bars' width and space between bars in number of characters. +bars = 12 +# bar_height is only used for output in "noritake" format + +# For SDL width and space between bars is in pixels, defaults are: + +# sdl_glsl have these default values, they are only used to calculate max number of bars. + + +# Lower and higher cutoff frequencies for lowest and highest bars +# the bandwidth of the visualizer. +# Note: there is a minimum total bandwidth of 43Mhz x number of bars. +# Cava will automatically increase the higher cutoff if a too low band is specified. + +# Seconds with no input before cava goes to sleep mode. Cava will not perform FFT or drawing and +# only check for input once per second. Cava will wake up once input is detected. 0 = disable. +sleep_timer = 5 + + +[input] + +# Audio capturing method. Possible methods are: 'fifo', 'portaudio', 'pipewire', 'alsa', 'pulse', 'sndio', 'oss', 'jack' or 'shmem' +# Defaults to 'oss', 'pipewire', 'sndio', 'jack', 'pulse', 'alsa', 'portaudio' or 'fifo', in that order, dependent on what support cava was built with. +# On Mac it defaults to 'portaudio' or 'fifo' +# On windows this is automatic and no input settings are needed. +# +# All input methods uses the same config variable 'source' +# to define where it should get the audio. +# +# For pulseaudio and pipewire 'source' will be the source. Default: 'auto', which uses the monitor source of the default sink +# (all pulseaudio sinks(outputs) have 'monitor' sources(inputs) associated with them). +# +# For pipewire 'source' will be the object name or object.serial of the device to capture from. +# Both input and output devices are supported. +# +# For alsa 'source' will be the capture device. +# For fifo 'source' will be the path to fifo-file. +# For shmem 'source' will be /squeezelite-AA:BB:CC:DD:EE:FF where 'AA:BB:CC:DD:EE:FF' will be squeezelite's MAC address +# +# For sndio 'source' will be a raw recording audio descriptor or a monitoring sub-device, e.g. 'rsnd/2' or 'snd/1'. Default: 'default'. +# README.md contains further information on how to setup CAVA for sndio. +# +# For oss 'source' will be the path to a audio device, e.g. '/dev/dsp2'. Default: '/dev/dsp', i.e. the default audio device. +# README.md contains further information on how to setup CAVA for OSS on FreeBSD. +# +# For jack 'source' will be the name of the JACK server to connect to, e.g. 'foobar'. Default: 'default'. +# README.md contains further information on how to setup CAVA for JACK. +# + +# The options 'sample_rate', 'sample_bits', 'channels' and 'autoconnect' can be configured for some input methods: +# sample_rate: fifo, pipewire, sndio, oss +# sample_bits: fifo, pipewire, sndio, oss +# channels: sndio, oss, jack +# autoconnect: jack +# Other methods ignore these settings. +# +# For 'sndio' and 'oss' they are only preferred values, i.e. if the values are not supported +# by the chosen audio device, the device will use other supported values instead. +# Example: 48000, 32 and 2, but the device only supports 44100, 16 and 1, then it +# will use 44100, 16 and 1. +# + + +[output] + +# Output method. Can be 'ncurses', 'noncurses', 'raw', 'noritake', 'sdl' +# or 'sdl_glsl'. +# 'noncurses' (default) uses a buffer and cursor movements to only print +# changes from frame to frame in the terminal. Uses less resources and is less +# prone to tearing (vsync issues) than 'ncurses'. +# +# 'raw' is an 8 or 16 bit (configurable via the 'bit_format' option) data +# stream of the bar heights that can be used to send to other applications. +# 'raw' defaults to 200 bars, which can be adjusted in the 'bars' option above. +# +# 'noritake' outputs a bitmap in the format expected by a Noritake VFD display +# in graphic mode. It only support the 3000 series graphical VFDs for now. +# +# 'sdl' uses the Simple DirectMedia Layer to render in a graphical context. +# 'sdl_glsl' uses SDL to create an OpenGL context. Write your own shaders or +# use one of the predefined ones. +method = raw + +# Orientation of the visualization. Can be 'bottom', 'top', 'left', 'right' or +# 'horizontal'. Default is 'bottom'. 'left and 'right' are only supported on sdl +# and ncruses output. 'horizontal' (bars go up and down from center) is only supported +# on noncurses output. +# Note: many fonts have weird or missing glyphs for characters used in orientations +# other than 'bottom', which can make output not look right. + +# Visual channels. Can be 'stereo' or 'mono'. +# 'stereo' mirrors both channels with low frequencies in center. +# 'mono' outputs left to right lowest to highest frequencies. +# 'mono_option' set mono to either take input from 'left', 'right' or 'average'. +# set 'reverse' to 1 to display frequencies the other way around. + +# Raw output target. A fifo will be created if target does not exist. +raw_target = /dev/stdout + +# Raw data format. Can be 'binary' or 'ascii'. +data_format = ascii + +# Binary bit format, can be '8bit' (0-255) or '16bit' (0-65530). + +# Ascii max value. In 'ascii' mode range will run from 0 to value specified here + +# Ascii delimiters. In ascii format each bar and frame is separated by a delimiters. +# Use decimal value in ascii table (i.e. 59 = ';' and 10 = '\n' (line feed)). +bar_delimiter = 0 + +# sdl window size and position. -1,-1 is centered. + +# set label on bars on the x-axis. Can be 'frequency' or 'none'. Default: 'none' +# 'frequency' displays the lower cut off frequency of the bar above. +# Only supported on ncurses and noncurses output. + +# enable synchronized sync. 1 = on, 0 = off +# removes flickering in alacritty terminal emulator. +# defaults to off since the behaviour in other terminal emulators is unknown + +# Shaders for sdl_glsl, located in $HOME/.config/cava/shaders + +; for glsl output mode, keep rendering even if no audio + +# disable console blank (screen saver) in tty +# (Not supported on FreeBSD) + +# show a flat bar at the bottom of the screen when idle, 1 = on, 0 = off + +# show waveform instead of frequency spectrum, 1 = on, 0 = off + +[color] + +# Colors can be one of seven predefined: black, blue, cyan, green, magenta, red, white, yellow. +# Or defined by hex code '#xxxxxx' (hex code must be within ''). User defined colors requires +# a terminal that can change color definitions such as Gnome-terminal or rxvt. +# default is to keep current terminal color + +# SDL and sdl_glsl only support hex code colors, these are the default: + +# Gradient mode, only hex defined colors are supported, +# background must also be defined in hex or remain commented out. 1 = on, 0 = off. +# You can define as many as 8 different colors. They range from bottom to top of screen + +[smoothing] + +# Disables or enables the so-called "Monstercat smoothing" with or without "waves". Set to 0 to disable. + +# Noise reduction, int 0 - 100. default 77 +# the raw visualization is very noisy, this factor adjusts the integral and gravity filters to keep the signal smooth +# 100 will be very slow and smooth, 0 will be fast but noisy. + + +[eq] + +# This one is tricky. You can have as much keys as you want. +# Remember to uncomment more than one key! More keys = more precision. +# Look at readme.md on github for further explanations and examples. +``` +## GLSL +The Cava GLSL frontend delegates the visualization of incoming audio data to the GPU via OpenGL. + +There are some mandatory dependencies that need to be satisfied in order for Cava GLSL to be built and function properly: + +. epoxy library must be installed on the system +. Vertex and fragment shaders from the original project must be used. They should be downloaded, and the file paths must be configured correctly in the Waybar Cava configuration: + 1. cava shaders [cava shaders](https://github.com/karlstav/cava/tree/master/output/shaders) + 2. libcava shaders [libcava shaders](https://github.com/LukashonakV/cava/tree/master/output/shaders) +. It is highly recommended to have a separate cava configuration for the Waybar Cava GLSL module and to use this as the cava_config in the Waybar configuration. +. It is common for cava configurations to be placed in the XDG_CONFIG_HOME directory, including shaders as well. Consider keeping them in the $XDG_CONFIG_HOME/cava/shaders folder. + +Key configuration options: + +. bars. The more values the parameter has, the more interesting the visualization becomes. +. method in output section must be set to sdl_glsl +. sdl_width and sdl_height manage the size of the module. Adjust them according to your needs. +. Shaders for sdl_glsl, located in $HOME/.config/cava/shaders. Example: "vertex_shader" = "pass_through.vert" "fragment_shader" = "spectrogram.frag" +. Set continuous_rendering to 1 to enable smooth rendering; set it to 0 otherwise. It is recommended to keep it set to 1. +. background, foreground, and gradient_color_N (where N is a number between 1 and 8) must be defined using hex code + +Example: + +waybar config +``` +"cava": { + "cava_config": "$XDG_CONFIG_HOME/cava/waybar_cava#3.conf", + "input_delay": 2, + "actions": { + "on-click-right": "mode" + } + }, +``` + +waybar_raw.conf +``` +## Configuration file for CAVA. +# Remove the ; to change parameters. + + +[general] + +# Smoothing mode. Can be 'normal', 'scientific' or 'waves'. DEPRECATED as of 0.6.0 + +# Accepts only non-negative values. + +# 'autosens' will attempt to decrease sensitivity if the bars peak. 1 = on, 0 = off +# new as of 0.6.0 autosens of low values (dynamic range) +# 'overshoot' allows bars to overshoot (in % of terminal height) without initiating autosens. DEPRECATED as of 0.6.0 + +# Manual sensitivity in %. If autosens is enabled, this will only be the initial value. +# 200 means double height. Accepts only non-negative values. + +# The number of bars (0-512). 0 sets it to auto (fill up console). +# Bars' width and space between bars in number of characters. +bars = 50 + +# bar_height is only used for output in "noritake" format + +# For SDL width and space between bars is in pixels, defaults are: + +# sdl_glsl have these default values, they are only used to calculate max number of bars. + +# Lower and higher cutoff frequencies for lowest and highest bars +# the bandwidth of the visualizer. +# Note: there is a minimum total bandwidth of 43Mhz x number of bars. +# Cava will automatically increase the higher cutoff if a too low band is specified. + +# Seconds with no input before cava goes to sleep mode. Cava will not perform FFT or drawing and +# only check for input once per second. Cava will wake up once input is detected. 0 = disable. +sleep_timer = 5 + + +[input] + +# Audio capturing method. Possible methods are: 'fifo', 'portaudio', 'pipewire', 'alsa', 'pulse', 'sndio', 'oss', 'jack' or 'shmem' +# Defaults to 'oss', 'pipewire', 'sndio', 'jack', 'pulse', 'alsa', 'portaudio' or 'fifo', in that order, dependent on what support cava was built with. +# On Mac it defaults to 'portaudio' or 'fifo' +# On windows this is automatic and no input settings are needed. +# +# All input methods uses the same config variable 'source' +# to define where it should get the audio. +# +# For pulseaudio and pipewire 'source' will be the source. Default: 'auto', which uses the monitor source of the default sink +# (all pulseaudio sinks(outputs) have 'monitor' sources(inputs) associated with them). +# +# For pipewire 'source' will be the object name or object.serial of the device to capture from. +# Both input and output devices are supported. +# +# For alsa 'source' will be the capture device. +# For fifo 'source' will be the path to fifo-file. +# For shmem 'source' will be /squeezelite-AA:BB:CC:DD:EE:FF where 'AA:BB:CC:DD:EE:FF' will be squeezelite's MAC address +# +# For sndio 'source' will be a raw recording audio descriptor or a monitoring sub-device, e.g. 'rsnd/2' or 'snd/1'. Default: 'default'. +# README.md contains further information on how to setup CAVA for sndio. +# +# For oss 'source' will be the path to a audio device, e.g. '/dev/dsp2'. Default: '/dev/dsp', i.e. the default audio device. +# README.md contains further information on how to setup CAVA for OSS on FreeBSD. +# +# For jack 'source' will be the name of the JACK server to connect to, e.g. 'foobar'. Default: 'default'. +# README.md contains further information on how to setup CAVA for JACK. +# + + +# The options 'sample_rate', 'sample_bits', 'channels' and 'autoconnect' can be configured for some input methods: +# sample_rate: fifo, pipewire, sndio, oss +# sample_bits: fifo, pipewire, sndio, oss +# channels: sndio, oss, jack +# autoconnect: jack +# Other methods ignore these settings. +# +# For 'sndio' and 'oss' they are only preferred values, i.e. if the values are not supported +# by the chosen audio device, the device will use other supported values instead. +# Example: 48000, 32 and 2, but the device only supports 44100, 16 and 1, then it +# will use 44100, 16 and 1. +# + + +[output] + +# Output method. Can be 'ncurses', 'noncurses', 'raw', 'noritake', 'sdl' +# or 'sdl_glsl'. +# 'noncurses' (default) uses a buffer and cursor movements to only print +# changes from frame to frame in the terminal. Uses less resources and is less +# prone to tearing (vsync issues) than 'ncurses'. +# +# 'raw' is an 8 or 16 bit (configurable via the 'bit_format' option) data +# stream of the bar heights that can be used to send to other applications. +# 'raw' defaults to 200 bars, which can be adjusted in the 'bars' option above. +# +# 'noritake' outputs a bitmap in the format expected by a Noritake VFD display +# in graphic mode. It only support the 3000 series graphical VFDs for now. +# +# 'sdl' uses the Simple DirectMedia Layer to render in a graphical context. +# 'sdl_glsl' uses SDL to create an OpenGL context. Write your own shaders or +# use one of the predefined ones. +method = sdl_glsl + +# Orientation of the visualization. Can be 'bottom', 'top', 'left', 'right' or +# 'horizontal'. Default is 'bottom'. 'left and 'right' are only supported on sdl +# and ncruses output. 'horizontal' (bars go up and down from center) is only supported +# on noncurses output. +# Note: many fonts have weird or missing glyphs for characters used in orientations +# other than 'bottom', which can make output not look right. + +# Visual channels. Can be 'stereo' or 'mono'. +# 'stereo' mirrors both channels with low frequencies in center. +# 'mono' outputs left to right lowest to highest frequencies. +# 'mono_option' set mono to either take input from 'left', 'right' or 'average'. +# set 'reverse' to 1 to display frequencies the other way around. + +# Raw output target. A fifo will be created if target does not exist. + +# Raw data format. Can be 'binary' or 'ascii'. + +# Binary bit format, can be '8bit' (0-255) or '16bit' (0-65530). + +# Ascii max value. In 'ascii' mode range will run from 0 to value specified here + +# Ascii delimiters. In ascii format each bar and frame is separated by a delimiters. +# Use decimal value in ascii table (i.e. 59 = ';' and 10 = '\n' (line feed)). +bar_delimiter = 0 + +# sdl window size and position. -1,-1 is centered. +sdl_width = 150 +sdl_height = 39 + +# set label on bars on the x-axis. Can be 'frequency' or 'none'. Default: 'none' +# 'frequency' displays the lower cut off frequency of the bar above. +# Only supported on ncurses and noncurses output. + +# enable synchronized sync. 1 = on, 0 = off +# removes flickering in alacritty terminal emulator. +# defaults to off since the behaviour in other terminal emulators is unknown + +# Shaders for sdl_glsl, located in $HOME/.config/cava/shaders +vertex_shader = pass_through.vert +fragment_shader = bar_spectrum.frag + +; for glsl output mode, keep rendering even if no audio +continuous_rendering = 1; + +# disable console blank (screen saver) in tty +# (Not supported on FreeBSD) + +# show a flat bar at the bottom of the screen when idle, 1 = on, 0 = off + +# show waveform instead of frequency spectrum, 1 = on, 0 = off + +[color] + + +# Colors can be one of seven predefined: black, blue, cyan, green, magenta, red, white, yellow. +# Or defined by hex code '#xxxxxx' (hex code must be within ''). User defined colors requires +# a terminal that can change color definitions such as Gnome-terminal or rxvt. +# default is to keep current terminal color + +# SDL and sdl_glsl only support hex code colors, these are the default: +background = '#282C34' + +# Gradient mode, only hex defined colors are supported, +# background must also be defined in hex or remain commented out. 1 = on, 0 = off. +# You can define as many as 8 different colors. They range from bottom to top of screen +gradient = 1 +gradient_count = 2 +gradient_color_1 = '#282C34' +gradient_color_2 = '#45475A' + +; gradient_color_1 = '#59cc33' +; gradient_color_2 = '#80cc33' + gradient_color_3 = '#a6cc33' + gradient_color_4 = '#cccc33' + gradient_color_5 = '#cca633' + gradient_color_6 = '#cc8033' + gradient_color_7 = '#cc5933' + gradient_color_8 = '#cc3333' + +[smoothing] + +# Percentage value for integral smoothing. Takes values from 0 - 100. +# Higher values means smoother, but less precise. 0 to disable. +# DEPRECATED as of 0.8.0, use noise_reduction instead + +# Disables or enables the so-called "Monstercat smoothing" with or without "waves". Set to 0 to disable. + +# Set gravity percentage for "drop off". Higher values means bars will drop faster. +# Accepts only non-negative values. 50 means half gravity, 200 means double. Set to 0 to disable "drop off". +# DEPRECATED as of 0.8.0, use noise_reduction instead + + +# In bar height, bars that would have been lower that this will not be drawn. +# DEPRECATED as of 0.8.0 + +# Noise reduction, int 0 - 100. default 77 +# the raw visualization is very noisy, this factor adjusts the integral and gravity filters to keep the signal smooth +# 100 will be very slow and smooth, 0 will be fast but noisy. + +[eq] + +# This one is tricky. You can have as much keys as you want. +# Remember to uncomment more than one key! More keys = more precision. +# Look at readme.md on github for further explanations and examples. +``` + +Different waybar_cava#N.conf see at [cava GLSL](https://github.com/Alexays/Waybar/wiki/Module:-Cava:-GLSL) diff --git a/man/waybar-clock.5.scd b/man/waybar-clock.5.scd index 50a5fc07..1b13dcb7 100644 --- a/man/waybar-clock.5.scd +++ b/man/waybar-clock.5.scd @@ -39,6 +39,12 @@ $XDG_CONFIG_HOME/waybar/config ++ :[ A list of timezones (as in *timezone*) to use for time display, changed using the scroll wheel. Do not specify *timezone* option when *timezones* is specified. "" represents the system's local timezone +|[ *timezone-tooltip-format* +:[ string +:[ +:[ Format to use for displaying timezones in the tooltip. When set, this allows showing + timezone information (like timezone abbreviations) in the tooltip while keeping the + main display clean. Uses the same format options as *format* |[ *locale* :[ string :[ @@ -126,6 +132,12 @@ View all valid format options in *strftime(3)* or have a look https://en.cpprefe :[ 1 :[ Value to scroll months/years forward/backward. Can be negative. Is configured under *on-scroll* option +|[ *iso8601* +:[ bool +:[ false +:[ When enabled, the calendar follows the ISO 8601 standard: weeks begin on + Monday, and the first week of the year is numbered 1. The default week format is + '{:%V}'. 3. Addressed by *clock: calendar: format* [- *Option* @@ -192,7 +204,7 @@ View all valid format options in *strftime(3)* or have a look https://en.cpprefe ``` "clock": { "format": "{:%H:%M}  ", - "format-alt": "{:%A, %B %d, %Y (%R)}  ", + "format-alt": "{:%A, %B %d, %Y (%R)} 󰃰 ", "tooltip-format": "{calendar}", "calendar": { "mode" : "year", @@ -229,6 +241,37 @@ View all valid format options in *strftime(3)* or have a look https://en.cpprefe } ``` +4. Show timezone in tooltip only + +``` +"clock": { + "interval": 60, + "format": "{:%H:%M}", + "timezone-tooltip-format": "{:%H:%M %Z}", + "timezones": [ + "", + "America/Chicago", + "America/Los_Angeles", + "Europe/Paris", + "UTC" + ], + "tooltip": true, + "tooltip-format": "{tz_list}" +} +``` +5. Simple calendar tooltip + +``` +"clock": { +"format": "{:%H:%M}", +"tooltip-format": "{calendar}", +"calendar": { +"format": { +"today": "{}" +} +} +} +``` # STYLE - *#clock* @@ -256,7 +299,7 @@ Example of working config ``` "clock": { "format": "{:%H:%M}  ", - "format-alt": "{:%A, %B %d, %Y (%R)}  ", + "format-alt": "{:%A, %B %d, %Y (%R)} 󰃰 ", "tooltip-format": "\n{calendar}", "calendar": { "mode" : "year", diff --git a/man/waybar-cpu.5.scd b/man/waybar-cpu.5.scd index 287bf123..3df38216 100644 --- a/man/waybar-cpu.5.scd +++ b/man/waybar-cpu.5.scd @@ -11,9 +11,10 @@ The *cpu* module displays the current CPU utilization. # CONFIGURATION *interval*: ++ - typeof: integer ++ + typeof: integer or float ++ default: 10 ++ - The interval in which the information gets polled. + The interval in which the information gets polled. ++ + Minimum value is 0.001 (1ms). Values smaller than 1ms will be set to 1ms. *format*: ++ typeof: string ++ @@ -91,6 +92,12 @@ The *cpu* module displays the current CPU utilization. *{load}*: Current CPU load. +*{load1}*: CPU load average over the last minute. + +*{load5}*: CPU load average over the last 5 minutes. + +*{load15}*: CPU load average over the last 15 minutes. + *{usage}*: Current overall CPU usage. *{usage*{n}*}*: Current CPU core n usage. Cores are numbered from zero, so first core will be {usage0} and 4th will be {usage3}. diff --git a/man/waybar-custom.5.scd b/man/waybar-custom.5.scd index 309fc184..88b79151 100644 --- a/man/waybar-custom.5.scd +++ b/man/waybar-custom.5.scd @@ -35,15 +35,17 @@ Addressed by *custom/* See *return-type* *interval*: ++ - typeof: integer ++ + typeof: integer or float ++ The interval (in seconds) in which the information gets polled. ++ + Minimum value is 0.001 (1ms). Values smaller than 1ms will be set to 1ms. ++ Use *once* if you want to execute the module only on startup. ++ You can update it manually with a signal. If no *interval* or *signal* is defined, it is assumed that the out script loops itself. ++ If a *signal* is defined then the script will run once on startup and will only update with a signal. *restart-interval*: ++ - typeof: integer ++ + typeof: integer or float ++ The restart interval (in seconds). ++ + Minimum value is 0.001 (1ms). Values smaller than 1ms will be set to 1ms. ++ Can't be used with the *interval* option, so only with continuous scripts. ++ Once the script exits, it'll be re-executed after the *restart-interval*. @@ -232,7 +234,6 @@ $text\\n$tooltip\\n$class* ``` "custom/pacman": { "format": "{text} ", - "interval": 3600, // every hour "exec": "checkupdates | wc -l", // # of updates "exec-if": "exit 0", // always run; consider advanced run conditions "on-click": "termite -e 'sudo pacman -Syu'; pkill -SIGRTMIN+8 waybar", // update system @@ -240,7 +241,7 @@ $text\\n$tooltip\\n$class* } ``` -You can use the signal and update the number of available packages with *pkill -RTMIN+8 waybar*. +Under the premise that interval is not defined, you can use the signal and update the number of available packages with *pkill -RTMIN+8 waybar*. # STYLE diff --git a/man/waybar-dwl-tags.5.scd b/man/waybar-dwl-tags.5.scd index a2146dfd..39d15b7a 100644 --- a/man/waybar-dwl-tags.5.scd +++ b/man/waybar-dwl-tags.5.scd @@ -43,6 +43,7 @@ Addressed by *dwl/tags* - *#tags button* - *#tags button.occupied* +- *#tags button.empty* - *#tags button.focused* - *#tags button.urgent* diff --git a/man/waybar-wlr-workspaces.5.scd b/man/waybar-ext-workspaces.5.scd similarity index 69% rename from man/waybar-wlr-workspaces.5.scd rename to man/waybar-ext-workspaces.5.scd index 62d3f636..3fdae606 100644 --- a/man/waybar-wlr-workspaces.5.scd +++ b/man/waybar-ext-workspaces.5.scd @@ -10,7 +10,7 @@ The *workspaces* module displays the currently used workspaces in wayland compos # CONFIGURATION -Addressed by *wlr/workspaces* +Addressed by *ext/workspaces* *format*: ++ typeof: string ++ @@ -24,18 +24,18 @@ Addressed by *wlr/workspaces* *sort-by-name*: ++ typeof: bool ++ default: true ++ - Should workspaces be sorted by name. + Should workspaces be sorted by name. Workspace names will be sorted numerically when all names are numbers. *sort-by-coordinates*: ++ typeof: bool ++ - default: true ++ + default: false ++ Should workspaces be sorted by coordinates. ++ Note that if both *sort-by-name* and *sort-by-coordinates* are true sort-by name will be first. If both are false - sort by id will be performed. -*sort-by-number*: ++ +*sort-by-id*: ++ typeof: bool ++ default: false ++ - If set to true, workspace names will be sorted numerically. Takes precedence over any other sort-by option. + Should workspaces be sorted by ID. Workspace ID will be sorted numerically when all ID are numbers. Takes precedence over any other sort-by option. *all-outputs*: ++ typeof: bool ++ @@ -47,9 +47,16 @@ Addressed by *wlr/workspaces* default: false ++ If set to true only active or urgent workspaces will be shown. +*ignore-hidden*: ++ + typeof: bool ++ + default: true ++ + If set to false hidden workspaces will be shown. + # FORMAT REPLACEMENTS -*{name}*: Name of workspace assigned by compositor +*{name}*: Name of workspace assigned by compositor. + +*{id}*: ID of workspace assigned by compositor. *{icon}*: Icon, as defined in *format-icons*. @@ -57,6 +64,8 @@ Addressed by *wlr/workspaces* *activate*: Switch to workspace. +*deactivate*: Deactivate the workspace. + *close*: Close the workspace. # ICONS @@ -69,18 +78,18 @@ In addition to workspace name matching, the following *format-icons* can be set. # EXAMPLES ``` -"wlr/workspaces": { +"ext/workspaces": { "format": "{name}: {icon}", + "on-click": "activate", "format-icons": { - "1": "", - "2": "", - "3": "", - "4": "", - "5": "", + "Workspace 1": "", + "Workspace 2": "", + "Workspace 3": "", + "Workspace 4": "", "active": "", "default": "" }, - "sort-by-number": true + "sort-by-id": true } ``` diff --git a/man/waybar-gamemode.5.scd b/man/waybar-gamemode.5.scd index a6ca9af0..bb82e0aa 100644 --- a/man/waybar-gamemode.5.scd +++ b/man/waybar-gamemode.5.scd @@ -43,7 +43,7 @@ Feral Gamemode optimizations. *glyph*: ++ typeof: string ++ - default:  ++ + default: 󰊴 ++ The string icon to display. Only visible if *use-icon* is set to false. *icon-name*: ++ @@ -82,7 +82,7 @@ Feral Gamemode optimizations. "gamemode": { "format": "{glyph}", "format-alt": "{glyph} {count}", - "glyph": "", + "glyph": "󰊴", "hide-not-running": true, "use-icon": true, "icon-name": "input-gaming-symbolic", diff --git a/man/waybar-gps.5.scd b/man/waybar-gps.5.scd new file mode 100644 index 00000000..e7473601 --- /dev/null +++ b/man/waybar-gps.5.scd @@ -0,0 +1,111 @@ +waybar-gps(5) "waybar-gps" "User Manual" + +# NAME + +waybar - gps module + +# DESCRIPTION + +*gps* module for gpsd. + + +# FILES + +$XDG_CONFIG_HOME/waybar/config ++ + Per user configuration file + +# ADDITIONAL FILES + +libgps lives in: + +. /usr/lib/libgps.so or /usr/lib64/libgps.so +. /usr/lib/pkgconfig/libgps.pc or /usr/lib64/pkgconfig/libgps.pc +. /usr/include/gps + +# CONFIGURATION + +*format*: ++ + typeof: string ++ + default: {glyph} ++ + The text format. + +*tooltip*: ++ + typeof: bool ++ + default: true ++ + Option to disable tooltip on hover. + +*tooltip-format*: ++ + typeof: string ++ + default: Games running: {glyph} ++ + The text format of the tooltip. + +*interval*: ++ + typeof: integer ++ + default: 5 ++ + The interval in which the GPS information gets polled (e.g. current speed). + Significant updates (e.g. the current fix mode) are updated immediately. + +*hide-disconnected*: ++ + typeof: bool ++ + default: true ++ + Defines if the module should be hidden if there is no GPS receiver. + +*hide-no-fix*: ++ + typeof: bool ++ + default: false ++ + Defines if the module should be hidden if there is no GPS fix. + +# FORMAT REPLACEMENTS + +*{mode}*: Fix mode + +*{status}*: Technology used for GPS fix. Not all GPS receivers report this. + +*{latitude}*: Latitude, decimal degrees. Can be NaN. + +*{latitude_error}*: Latitude uncertainty, meters. Can be NaN. + +*{longitude}*: Longitude, decimal degrees. Can be NaN. + +*{longitude_error}*: Longitude uncertainty, meters. Can be NaN. + +*{altitude_hae}*: Altitude, height above ellipsoid, meters. Can be NaN. + +*{altitude_msl}*: Longitude, MSL, meters. Can be NaN. + +*{altitude_error}*: Altitude uncertainty, meters. Can be NaN. + +*{speed}*: Speed over ground, meters/sec. Can be NaN. + +*{speed_error}*: Speed uncertainty, meters/sec. Can be NaN. + +*{climb}*: Vertical speed, meters/sec. Can be NaN. + +*{climb_error}*: Vertical speed uncertainty, meters/sec. Can be NaN. + +*{satellites_visible}*: Number of satellites visible from the GPS receiver. + +*{satellites_used}*: Number of satellites used for the GPS fix. + +# EXAMPLES + +``` +"gps": { + "format": "{mode}", + "format-disabled": "", // an empty format will hide the module + "format-no-fix": "No fix", + "format-fix-3d": "{status}", + "tooltip-format": "{mode}", + "tooltip-format-no-fix": "{satellites_visible} satellites visible", + "tooltip-format-fix-2d": "{satellites_used}/{satellites_visible} satellites used", + "tooltip-format-fix-3d": "Altitude: {altitude_hae}m", + "hide-disconnected": false +} +``` +# STYLE + +- *#gps* +- *#gps.disabled* Applied when GPS is disabled. +- *#gps.fix-none* Applied when GPS is present, but there is no fix. +- *#gps.fix-2d* Applied when there is a 2D fix. +- *#gps.fix-3d* Applied when there is a 3D fix. diff --git a/man/waybar-hyprland-language.5.scd b/man/waybar-hyprland-language.5.scd index 5a7ba941..b5ce80aa 100644 --- a/man/waybar-hyprland-language.5.scd +++ b/man/waybar-hyprland-language.5.scd @@ -38,6 +38,20 @@ Addressed by *hyprland/language* typeof: array ++ The actions corresponding to the buttons of the menu. +*tooltip*: ++ + typeof: boolean ++ + default: true ++ + Enables or disables the tooltip for the language module. By default, the tooltip is enabled. Set to *false* to disable. + +*tooltip-format*: ++ + typeof: string ++ + default: {long} ++ + Specifies the format of the tooltip when it is enabled. It follows the same format replacement rules as the *format* key. + +*tooltip-format-*: ++ + typeof: string ++ + Allows specifying a different tooltip format for each language. The ** should be replaced with the language code. This can be used to provide a custom tooltip for each language. + *expand*: ++ typeof: bool ++ default: false ++ @@ -66,6 +80,28 @@ Addressed by *hyprland/language* } ``` +``` +"hyprland/language": { + "format": "{}", + "format-en": "US", + "format-es": "ES", + "tooltip": true, + "tooltip-format": "{long}" +} +``` + +``` +"hyprland/language": { + "format": "{}", + "format-en": "US", + "format-es": "ES", + "tooltip": true, + "tooltip-format": "{}", + "tooltip-format-es": "{Español}", + "tooltip-format-en": "{English (american)}" +} +``` + # STYLE - *#language* diff --git a/man/waybar-hyprland-windowcount.5.scd b/man/waybar-hyprland-windowcount.5.scd new file mode 100644 index 00000000..6a4f87d1 --- /dev/null +++ b/man/waybar-hyprland-windowcount.5.scd @@ -0,0 +1,46 @@ +waybar-hyprland-windowcount(5) + +# NAME + +waybar - hyprland window count module + +# DESCRIPTION + +The *windowcount* module displays the number of windows in the current Hyprland workspace. + +# CONFIGURATION + +Addressed by *hyprland/windowcount* + +*format*: ++ + typeof: string ++ + default: {} ++ + The format for how information should be displayed. On {} the current workspace window count is displayed. + +*format-empty*: ++ + typeof: string ++ + Override the format when the workspace contains no windows window + +*format-windowed*: ++ + typeof: string ++ + Override the format when the workspace contains no fullscreen windows + +*format-fullscreen*: ++ + typeof: string ++ + Override the format when the workspace contains a fullscreen window + +*separate-outputs*: ++ + typeof: bool ++ + default: true ++ + Show the active workspace window count of the monitor the bar belongs to, instead of the focused workspace. + +# STYLE + +- *#windowcount* + +The following classes are applied to the entire Waybar rather than just the +windowcount widget: + +- *window#waybar.empty* When no windows are in the workspace +- *window#waybar.fullscreen* When there is a fullscreen window in the workspace; + useful with Hyprland's *fullscreen, 1* mode diff --git a/man/waybar-hyprland-workspaces.5.scd b/man/waybar-hyprland-workspaces.5.scd index 73ccd9f3..bee7f0be 100644 --- a/man/waybar-hyprland-workspaces.5.scd +++ b/man/waybar-hyprland-workspaces.5.scd @@ -26,17 +26,77 @@ Addressed by *hyprland/workspaces* Regex rules to map window class to an icon or preferred method of representation for a workspace's window. Keys are the rules, while the values are the methods of representation. Values may use the placeholders {class} and {title} to use the window's original class and/or title respectively. Rules may specify `class<...>`, `title<...>`, or both in order to fine-tune the matching. - You may assign an empty value to a rule to have it ignored from generating any representation in workspaces. + You may assign an empty value to a rule to have it ignored from generating any representation in workspaces. ++ +This setting is ignored if *workspace-taskbar.enable* is set to true. -*window-rewrite-default*: +*window-rewrite-default*: ++ typeof: string ++ default: "?" ++ - The default method of representation for a workspace's window. This will be used for windows whose classes do not match any of the rules in *window-rewrite*. + The default method of representation for a workspace's window. This will be used for windows whose classes do not match any of the rules in *window-rewrite*. ++ + This setting is ignored if *workspace-taskbar.enable* is set to true. *format-window-separator*: ++ typeof: string ++ default: " " ++ - The separator to be used between windows in a workspace. + The separator to be used between windows in a workspace. ++ + This setting is ignored if *workspace-taskbar.enable* is set to true. + +*workspace-taskbar*: ++ + typeof: object ++ + Contains settings for the workspace taskbar, an alternative mode for the workspaces module which displays the window icons as images instead of text. + + *enable*: ++ + typeof: bool ++ + default: false ++ + Enables the workspace taskbar mode. + + *update-active-window*: ++ + typeof: bool ++ + default: false ++ + If true, the active/focused window will have an 'active' class. Could cause higher CPU usage due to more frequent redraws. + + *reverse-direction*: ++ + typeof: bool ++ + default: false ++ + If true, the taskbar windows will be added in reverse order (right to left if orientation is horizontal, bottom to top if vertical). + + *active-window-position*: ++ + typeof: "none" | "first" | "last" ++ + default: "none" ++ + If set to "first", the active window will be moved at the beginning of the taskbar. If set to "last", it will be moved at the end. It will only work if *update-active-window* is set to true. + + *format*: ++ + typeof: string ++ + default: {icon} ++ + Format to use for each window in the workspace taskbar. Available placeholders are {icon} and {title}. + + *icon-size*: ++ + typeof: int ++ + default: 16 ++ + Size of the icons in the workspace taskbar. + + *icon-theme*: ++ + typeof: string | array ++ + default: [] ++ + Icon theme to use for the workspace taskbar. If an array is provided, the first theme that is found for a given icon will be used. If no theme is found (or the array is empty), the default icon theme is used. + + *orientation*: ++ + typeof: "horizontal" | "vertical" ++ + default: horizontal ++ + Direction in which the workspace taskbar is displayed. + + *ignore-list*: ++ + typeof: array ++ + default: [] ++ + Regex patterns to match against window class or window title. If a window's class OR title matches any of the patterns, it will not be shown. + + *on-click-window*: ++ + typeof: string ++ + default: "" ++ + Command to run when a window is clicked. Available placeholders are: ++ + - {address} Hyprland address of the clicked window. ++ + - {button} Pressed button number, see https://api.gtkd.org/gdk.c.types.GdkEventButton.button.html. ++ + See https://github.com/Alexays/Waybar/wiki/Module:-Hyprland#workspace-taskbars-example for a full example. *show-special*: ++ typeof: bool ++ @@ -48,6 +108,11 @@ Addressed by *hyprland/workspaces* default: false ++ If this and show-special are to true, special workspaces will be shown only if visible. +*persistent-only*: ++ + typeof: bool ++ + default: false ++ + If set to true, only persistent workspaces will be shown on bar. + *all-outputs*: ++ typeof: bool ++ default: false ++ @@ -70,6 +135,19 @@ Addressed by *hyprland/workspaces* Otherwise, the workspace will open on the monitor where it was previously assigned. Analog to using `focusworkspaceoncurrentmonitor` dispatcher instead of `workspace` in Hyprland. +*enable-bar-scroll*: ++ + typeof: bool ++ + default: false ++ + If set to false, you can't scroll to cycle throughout workspaces from the entire bar. If set to true this behaviour is enabled. + +*on-scroll-up*: ++ + typeof: string ++ + Command to execute when scrolling up on the module. This replaces the default behaviour of workspace cycling. + +*on-scroll-down*: ++ + typeof: string ++ + Command to execute when scrolling down on the module. This replaces the default behaviour of workspace cycling. + *ignore-workspaces*: ++ typeof: array ++ default: [] ++ @@ -81,6 +159,7 @@ Addressed by *hyprland/workspaces* If set to number, workspaces will sort by number. If set to name, workspaces will sort by name. If set to id, workspaces will sort by id. + If set to special-centered, workspaces will sort by default with special workspaces in the center. If none of those, workspaces will sort with default behavior. *expand*: ++ @@ -183,3 +262,6 @@ Additional to workspace name matching, the following *format-icons* can be set. - *#workspaces button.special* - *#workspaces button.urgent* - *#workspaces button.hosting-monitor* (gets applied if workspace-monitor == waybar-monitor) +- *#workspaces .workspace-label* +- *#workspaces .taskbar-window* (each window in the taskbar, only if 'workspace-taskbar.enable' is true) +- *#workspaces .taskbar-window.active* (applied to the focused window, only if 'workspace-taskbar.update-active-window' is true) diff --git a/man/waybar-idle-inhibitor.5.scd b/man/waybar-idle-inhibitor.5.scd index 6d5a2170..405c8fc5 100644 --- a/man/waybar-idle-inhibitor.5.scd +++ b/man/waybar-idle-inhibitor.5.scd @@ -125,3 +125,9 @@ screensaver, also known as "presentation mode". "timeout": 30.5 } ``` + +# STYLE + +- *#idle_inhibitor* +- *#idle_inhibitor.activated* +- *#idle_inhibitor.deactivated* diff --git a/man/waybar-image.5.scd b/man/waybar-image.5.scd index a2dcc938..8be182a6 100644 --- a/man/waybar-image.5.scd +++ b/man/waybar-image.5.scd @@ -24,8 +24,10 @@ The *image* module displays an image from a path. The width/height to render the image. *interval*: ++ - typeof: integer ++ + typeof: integer or float ++ The interval (in seconds) to re-render the image. ++ + If set to a positive value, the minimum is 0.001 (1ms). Values smaller than 1ms will be set to 1ms. ++ + Zero or negative values are treated as "once". ++ This is useful if the contents of *path* changes. ++ If no *interval* is defined, the image will only be rendered once. diff --git a/man/waybar-jack.5.scd b/man/waybar-jack.5.scd index 85ce7180..98adc8db 100644 --- a/man/waybar-jack.5.scd +++ b/man/waybar-jack.5.scd @@ -45,7 +45,7 @@ Addressed by *jack* The format of information displayed in the tooltip. *interval*: ++ - typeof: integer ++ + typeof: integer or float ++ default: 1 ++ The interval in which the information gets polled. diff --git a/man/waybar-memory.5.scd b/man/waybar-memory.5.scd index cc42d5a3..99f57299 100644 --- a/man/waybar-memory.5.scd +++ b/man/waybar-memory.5.scd @@ -102,23 +102,31 @@ Addressed by *memory* default: false ++ Enables this module to consume all left over space dynamically. +*unit*: ++ + typeof: string ++ + default: GiB ++ + Used to specify unit for total, swapTotal, used, swapUsed, avail, swapAvail, + and swapState. Accepts B, kB, kiB, MB, MiB, GB, GiB, TB, and TiB. + # FORMAT REPLACEMENTS *{percentage}*: Percentage of memory in use. *{swapPercentage}*: Percentage of swap in use. -*{total}*: Amount of total memory available in GiB. +*{total}*: Amount of total memory available. Defaults to GiB. -*{swapTotal}*: Amount of total swap available in GiB. +*{swapTotal}*: Amount of total swap available. Defaults to GiB. -*{used}*: Amount of used memory in GiB. +*{used}*: Amount of used memory. Defaults to GiB. -*{swapUsed}*: Amount of used swap in GiB. +*{swapUsed}*: Amount of used swap. Defaults to GiB. -*{avail}*: Amount of available memory in GiB. +*{avail}*: Amount of available memory. Defaults to GiB. -*{swapAvail}*: Amount of available swap in GiB. +*{swapAvail}*: Amount of available swap. Defaults to GiB. + +*{swapState}*: Signals if swap is activated or not # EXAMPLES diff --git a/man/waybar-menu.5.scd b/man/waybar-menu.5.scd index 19790ed4..798917f0 100644 --- a/man/waybar-menu.5.scd +++ b/man/waybar-menu.5.scd @@ -7,7 +7,7 @@ waybar - menu property # OVERVIEW -Some modules support a 'menu', which allows to have a popup menu whan a defined +Some modules support a 'menu', which allows to have a popup menu when a defined click is done over the module. # PROPERTIES @@ -87,15 +87,15 @@ Module config : ``` "custom/power": { "format" : "⏻ ", - "tooltip": false, - "menu": "on-click", - "menu-file": "~/.config/waybar/power_menu.xml", - "menu-actions": { - "shutdown": "shutdown", - "reboot": "reboot", - "suspend": "systemctl suspend", - "hibernate": "systemctl hibernate", - }, + "tooltip": false, + "menu": "on-click", + "menu-file": "~/.config/waybar/power_menu.xml", + "menu-actions": { + "shutdown": "shutdown", + "reboot": "reboot", + "suspend": "systemctl suspend", + "hibernate": "systemctl hibernate", + }, }, ``` @@ -104,28 +104,28 @@ Module config : - - - Suspend - - - - - Hibernate - - + + + Suspend + + + + + Hibernate + + - - Shutdown - + + Shutdown + - - Reboot - + + Reboot + diff --git a/man/waybar-mpd.5.scd b/man/waybar-mpd.5.scd index 84abc2e8..d310efd4 100644 --- a/man/waybar-mpd.5.scd +++ b/man/waybar-mpd.5.scd @@ -204,6 +204,10 @@ Addressed by *mpd* *{queueLength}*: The length of the current queue. +*{uri}*: The URI of the song relative to the MPD music directory. + +*{filename}* The last part of the URI. + *{stateIcon}*: The icon corresponding to the playing or paused status of the player (see *state-icons* option) *{consumeIcon}*: The icon corresponding the "consume" option (see *consume-icons* option) diff --git a/man/waybar-network.5.scd b/man/waybar-network.5.scd index 15f15395..9e146ac0 100644 --- a/man/waybar-network.5.scd +++ b/man/waybar-network.5.scd @@ -16,6 +16,11 @@ Addressed by *network* typeof: string ++ Use the defined interface instead of auto-detection. Accepts wildcard. +*rfkill*: ++ + typeof: bool ++ + default: true ++ + If enabled, the *disabled* format will be used when rfkill is blocking wlan interfaces. + *interval*: ++ typeof: integer ++ default: 60 ++ @@ -49,7 +54,7 @@ Addressed by *network* *format-disabled*: ++ typeof: string ++ - This format is used when the displayed interface is disabled. + This format is used when rfkill is blocking wlan interfaces. *format-icons*: ++ typeof: array/object ++ @@ -127,7 +132,7 @@ Addressed by *network* *tooltip-format-disabled*: ++ typeof: string ++ - This format is used when the displayed interface is disabled. + This format is used when rfkill is blocking wlan interfaces. *menu*: ++ typeof: string ++ @@ -157,7 +162,7 @@ Addressed by *network* *{netmask}*: The subnetmask corresponding to the IP(V4). -*{netmask6}*: The subnetmask corresponding to the IP(V6). +*{netmask6}*: The subnetmask corresponding to the IP(V6). *{cidr}*: The subnetmask corresponding to the IP(V4) in CIDR notation. @@ -171,7 +176,7 @@ Addressed by *network* *{signaldBm}*: Signal strength of the wireless network in dBm. -*{frequency}*: Frequency of the wireless network in MHz. +*{frequency}*: Frequency of the wireless network in GHz. *{bandwidthUpBits}*: Instant up speed in bits/seconds. diff --git a/man/waybar-niri-language.5.scd b/man/waybar-niri-language.5.scd index 44876fd9..78cf14f8 100644 --- a/man/waybar-niri-language.5.scd +++ b/man/waybar-niri-language.5.scd @@ -52,8 +52,8 @@ Addressed by *niri/language* ``` "niri/language": { - "format": "Lang: {long}" - "format-en": "AMERICA, HELL YEAH!" + "format": "Lang: {long}", + "format-en": "AMERICA, HELL YEAH!", "format-tr": "As bayrakları" } ``` @@ -61,3 +61,12 @@ Addressed by *niri/language* # STYLE - *#language* + +Additionally, a CSS class matching the current layout's short name is added to the widget. This +allows per-language styling, for example: + +``` +#language.us { color: #00ff00; } +#language.de { color: #ff0000; } +#language.fr { color: #0000ff; } +``` diff --git a/man/waybar-niri-workspaces.5.scd b/man/waybar-niri-workspaces.5.scd index 0c0249ca..4be85eb3 100644 --- a/man/waybar-niri-workspaces.5.scd +++ b/man/waybar-niri-workspaces.5.scd @@ -70,6 +70,8 @@ Additional to workspace name matching, the following *format-icons* can be set. - *default*: Will be shown, when no string matches are found. - *focused*: Will be shown, when workspace is focused. - *active*: Will be shown, when workspace is active on its output. +- *urgent*: Will be shown, when workspace has urgent windows. +- *empty*: Will be shown, when workspace is empty. # EXAMPLES @@ -95,6 +97,7 @@ Additional to workspace name matching, the following *format-icons* can be set. - *#workspaces button* - *#workspaces button.focused*: The single focused workspace. - *#workspaces button.active*: The workspace is active (visible) on its output. +- *#workspaces button.urgent*: The workspace has one or more urgent windows. - *#workspaces button.empty*: The workspace is empty. - *#workspaces button.current_output*: The workspace is from the same output as the bar that it is displayed on. diff --git a/man/waybar-privacy.5.scd b/man/waybar-privacy.5.scd index 946fe136..1c4ef59d 100644 --- a/man/waybar-privacy.5.scd +++ b/man/waybar-privacy.5.scd @@ -37,6 +37,17 @@ the screen or playing audio. default: false ++ Enables this module to consume all left over space dynamically. +*ignore-monitor* ++ + typeof: bool ++ + default: true ++ + Ignore streams with *stream.monitor* property. + +*ignore* ++ + typeof: array of objects ++ + default: [] ++ + Additional streams to be ignored. See *IGNORE CONFIGURATION* for++ + more information. + # MODULES CONFIGURATION *type*: ++ @@ -54,6 +65,14 @@ the screen or playing audio. default: 24 ++ The size of each icon in the tooltip. +# IGNORE CONFIGURATION + +*type*: ++ + typeof: string + +*name*: ++ + typeof: string + # EXAMPLES ``` @@ -77,6 +96,17 @@ the screen or playing audio. "tooltip": true, "tooltip-icon-size": 24 } + ], + "ignore-monitor": true, + "ignore": [ + { + "type": "audio-in", + "name": "cava" + }, + { + "type": "screenshare", + "name": "obs" + } ] }, ``` diff --git a/man/waybar-pulseaudio-slider.5.scd b/man/waybar-pulseaudio-slider.5.scd index cb274826..3f56a80c 100644 --- a/man/waybar-pulseaudio-slider.5.scd +++ b/man/waybar-pulseaudio-slider.5.scd @@ -28,9 +28,20 @@ The volume can be controlled by dragging the slider across the bar or clicking o The orientation of the slider. Can be either `horizontal` or `vertical`. *expand*: ++ - typeof: bool ++ - default: false ++ - Enables this module to consume all left over space dynamically. + typeof: bool ++ + default: false ++ + Enables this module to consume all left over space dynamically. + +*zero-on-mute*: ++ + typeof: bool ++ + default: true ++ + `true` = The slider will be set to `min` when the source/sink is muted. ++ + `false` = The slider will continue to show the unmuted volume level when the source/sink is muted. + +*unmute-on-volume-change*: ++ + typeof: bool ++ + default: true ++ + Specifies whether to unmute a muted souce/sink when its volume is changed by the user moving the slider. # EXAMPLES @@ -41,7 +52,9 @@ The volume can be controlled by dragging the slider across the bar or clicking o "pulseaudio/slider": { "min": 0, "max": 100, - "orientation": "horizontal" + "orientation": "horizontal", + "zero-on-mute": false, + "unmute-on-volume-change": false } ``` @@ -52,6 +65,9 @@ The slider is a component with multiple CSS Nodes, of which the following are ex *#pulseaudio-slider*: ++ Controls the style of the box *around* the slider and bar. +*#pulseaudio-slider.muted*: ++ + Controls the style when the audio source/sink is muted. + *#pulseaudio-slider slider*: ++ Controls the style of the slider handle. @@ -77,12 +93,16 @@ The slider is a component with multiple CSS Nodes, of which the following are ex min-height: 80px; min-width: 10px; border-radius: 5px; - background-color: black; + background: black; } #pulseaudio-slider highlight { min-width: 10px; border-radius: 5px; - background-color: green; + background: green; +} + +#pulseaudio-slider.muted highlight { + background-color: orange; } ``` diff --git a/man/waybar-pulseaudio.5.scd b/man/waybar-pulseaudio.5.scd index d47fc744..a52d5b3e 100644 --- a/man/waybar-pulseaudio.5.scd +++ b/man/waybar-pulseaudio.5.scd @@ -97,7 +97,11 @@ Additionally, you can control the volume by scrolling *up* or *down* while the c *reverse-scrolling*: ++ typeof: bool ++ - Option to reverse the scroll direction. + Option to reverse the scroll direction for touchpads. + +*reverse-mouse-scrolling*: ++ + typeof: bool ++ + Option to reverse the scroll direction for mice. *tooltip*: ++ typeof: bool ++ @@ -173,9 +177,9 @@ to be selected when the corresponding audio device is muted. This applies to *de "format-icons": { "alsa_output.pci-0000_00_1f.3.analog-stereo": "", "alsa_output.pci-0000_00_1f.3.analog-stereo-muted": "", - "headphones": "", - "handsfree": "", - "headset": "", + "headphone": "", + "hands-free": "󰂑", + "headset": "󰂑", "phone": "", "phone-muted": "", "portable": "", diff --git a/man/waybar-river-layout.5.scd b/man/waybar-river-layout.5.scd index 78e03634..a259b9ca 100644 --- a/man/waybar-river-layout.5.scd +++ b/man/waybar-river-layout.5.scd @@ -83,6 +83,7 @@ Addressed by *river/layout* - *#layout* - *#layout.focused* Applied when the output this module's bar belongs to is focused. +- *#layout.* Applied when the output this module's bar belongs uses this layout. # SEE ALSO diff --git a/man/waybar-river-mode.5.scd b/man/waybar-river-mode.5.scd index 5837411d..ac209f2c 100644 --- a/man/waybar-river-mode.5.scd +++ b/man/waybar-river-mode.5.scd @@ -87,7 +87,7 @@ Addressed by *river/mode* ``` "river/mode": { - "format": " {}" + "format": " {}" } ``` diff --git a/man/waybar-styles.5.scd.in b/man/waybar-styles.5.scd.in index b11e15bd..130e5db3 100644 --- a/man/waybar-styles.5.scd.in +++ b/man/waybar-styles.5.scd.in @@ -8,13 +8,27 @@ waybar-styles - using stylesheets for waybar Waybar uses Cascading Style Sheets (CSS) to configure its appearance. -It uses the first file found in this search order: +When the system appearance is light, Waybar first looks for *style-light.css*. +When the system appearance is dark, Waybar first looks for *style-dark.css*. +If no appearance-specific stylesheet is found, it falls back to *style.css*. -- *$XDG_CONFIG_HOME/waybar/style.css* -- *~/.config/waybar/style.css* -- *~/waybar/style.css* -- */etc/xdg/waybar/style.css* -- *@sysconfdir@/xdg/waybar/style.css* +Waybar uses the first file found in this search order for each stylesheet name: + +- *$XDG_CONFIG_HOME/waybar/* +- *~/.config/waybar/* +- *~/waybar/* +- */etc/xdg/waybar/* +- *@sysconfdir@/xdg/waybar/* + +For example, a light theme is loaded from the first available file among: + +- *$XDG_CONFIG_HOME/waybar/style-light.css* +- *~/.config/waybar/style-light.css* +- *~/waybar/style-light.css* +- */etc/xdg/waybar/style-light.css* +- *@sysconfdir@/xdg/waybar/style-light.css* + +If no file is found there, Waybar repeats the same search using *style.css*. # EXAMPLE diff --git a/man/waybar-sway-mode.5.scd b/man/waybar-sway-mode.5.scd index 52827376..2c5ba7e6 100644 --- a/man/waybar-sway-mode.5.scd +++ b/man/waybar-sway-mode.5.scd @@ -92,7 +92,7 @@ Addressed by *sway/mode* ``` "sway/mode": { - "format": " {}", + "format": " {}", "max-length": 50 } ``` diff --git a/man/waybar-sway-window.5.scd b/man/waybar-sway-window.5.scd index a7eb4f05..6fa9170b 100644 --- a/man/waybar-sway-window.5.scd +++ b/man/waybar-sway-window.5.scd @@ -89,6 +89,11 @@ Addressed by *sway/window* default: false ++ If the workspace itself is focused and the workspace contains nodes or floating_nodes, show the workspace name. If not set, text remains empty but styles according to nodes in the workspace are still applied. +*show-hidden-marks*: ++ + typeof: bool ++ + default: false ++ + For the *{marks}* format replacement, include hidden marks that start with an underscore. + *rewrite*: ++ typeof: object ++ Rules to rewrite the module format output. See *rewrite rules*. @@ -117,6 +122,8 @@ Addressed by *sway/window* *{shell}*: The shell of the focused window. It's 'xwayland' when the window is running through xwayland, otherwise, it's 'xdg-shell'. +*{marks}*: Marks of the window. + # REWRITE RULES *rewrite* is an object where keys are regular expressions and values are diff --git a/man/waybar-sway-workspaces.5.scd b/man/waybar-sway-workspaces.5.scd index 1c4360e9..3d4e3ad0 100644 --- a/man/waybar-sway-workspaces.5.scd +++ b/man/waybar-sway-workspaces.5.scd @@ -31,6 +31,11 @@ Addressed by *sway/workspaces* default: false ++ If set to false, you can scroll to cycle through workspaces. If set to true this behaviour is disabled. +*reverse-scroll*: ++ + typeof: bool ++ + default: false ++ + If set to false, scrolling up will switch to the previous workspace and scrolling down will switch to the next workspace. If set to true, the behavior will be reversed. + *disable-click*: ++ typeof: bool ++ default: false ++ @@ -174,7 +179,6 @@ n.b.: the list of outputs can be obtained from command line using *swaymsg -t ge "format": "{name} {windows}", "format-window-separator": " | ", "window-rewrite-default": "{name}", - "window-format": "{name}", "window-rewrite": { "class": "", "class": "k", diff --git a/man/waybar-systemd-failed-units.5.scd b/man/waybar-systemd-failed-units.5.scd index 92e74e9d..aaeee2d1 100644 --- a/man/waybar-systemd-failed-units.5.scd +++ b/man/waybar-systemd-failed-units.5.scd @@ -19,7 +19,7 @@ Addressed by *systemd-failed-units* *format-ok*: ++ typeof: string ++ - This format is used when there is no failing units. + This format is used when there are no failing units. *user*: ++ typeof: bool ++ @@ -34,15 +34,30 @@ Addressed by *systemd-failed-units* *hide-on-ok*: ++ typeof: bool ++ default: *true* ++ - Option to hide this module when there is no failing units. + Option to hide this module when there are no failed units. + +*tooltip-format*: ++ + typeof: string ++ + default: *System: {system_state}\nUser: {user_state}\nFailed units ({nr_failed}):\n{failed_units_list}* ++ + Tooltip format shown when there are failed units. + +*tooltip-format-ok*: ++ + typeof: string ++ + default: *System: {system_state}\nUser: {user_state}* ++ + Tooltip format used when there are no failed units. + +*tooltip-unit-format*: ++ + typeof: string ++ + default: *{name}: {description}* ++ + Format used to render each failed unit inside the tooltip. Each item is prefixed with a bullet. *menu*: ++ typeof: string ++ - Action that popups the menu. + Action that pops up the menu. *menu-file*: ++ typeof: string ++ - Location of the menu descriptor file. There need to be an element of type + Location of the menu descriptor file. There needs to be an element of type GtkMenu with id *menu* *menu-actions*: ++ @@ -52,7 +67,7 @@ Addressed by *systemd-failed-units* *expand*: ++ typeof: bool ++ default: false ++ - Enables this module to consume all left over space dynamically. + Enables this module to consume all leftover space dynamically. # FORMAT REPLACEMENTS @@ -62,6 +77,24 @@ Addressed by *systemd-failed-units* *{nr_failed}*: Number of total failed units. +*{system_state}:* State of the systemd system session. + +*{user_state}:* State of the systemd user session. + +*{overall_state}:* Overall state of the systemd and user session. ("ok" or "degraded") + +*{failed_units_list}:* Bulleted list of failed units using *tooltip-unit-format*. Empty when +there are no failed units. + +The *tooltip-unit-format* string supports the following replacements: + +*{name}*: Unit name ++ +*{description}*: Unit description ++ +*{load_state}*: Unit load state ++ +*{active_state}*: Unit active state ++ +*{sub_state}*: Unit sub state ++ +*{scope}*: Either *system* or *user* depending on where the unit originated + # EXAMPLES ``` @@ -71,6 +104,8 @@ Addressed by *systemd-failed-units* "format-ok": "✓", "system": true, "user": false, + "tooltip-format": "{nr_failed} failed units:\n{failed_units_list}", + "tooltip-unit-format": "{scope}: {name} ({active_state})", } ``` diff --git a/man/waybar-temperature.5.scd b/man/waybar-temperature.5.scd index 923d643d..0783331e 100644 --- a/man/waybar-temperature.5.scd +++ b/man/waybar-temperature.5.scd @@ -27,6 +27,12 @@ Addressed by *temperature* The path of the hwmon-directory of the device, e.g. */sys/devices/pci0000:00/0000:00:18.3/hwmon*. (Note that the subdirectory *hwmon/hwmon#*, where *#* is a number is not part of the path!) Has to be used together with *input-filename*. This can also be an array of strings, for which, it just works like *hwmon-path*. +*hwmon-name*: ++ + typeof: string ++ + Select a hwmon device by its name (from /sys/class/hwmon/\*/name), e.g. *amdgpu*. + Requires *input-filename* to be set. + Cannot be used together with *hwmon-path* or *hwmon-path-abs*. + *input-filename*: ++ typeof: string ++ The temperature filename of your *hwmon-path-abs*, e.g. *temp1_input* @@ -40,7 +46,7 @@ Addressed by *temperature* The threshold before it is considered critical (Celsius). *interval*: ++ - typeof: integer ++ + typeof: integer or float ++ default: 10 ++ The interval in which the information gets polled. @@ -160,4 +166,5 @@ Addressed by *temperature* # STYLE - *#temperature* +- *#temperature.warning* - *#temperature.critical* diff --git a/man/waybar-wayfire-window.5.scd b/man/waybar-wayfire-window.5.scd new file mode 100644 index 00000000..290b0c65 --- /dev/null +++ b/man/waybar-wayfire-window.5.scd @@ -0,0 +1,82 @@ +waybar-wayfire-window(5) + +# NAME + +waybar - wayfire window module + +# DESCRIPTION + +The *window* module displays the title of the currently focused window in wayfire. + +# CONFIGURATION + +Addressed by *wayfire/window* + +*format*: ++ + typeof: string ++ + default: {title} ++ + The format, how information should be displayed. On {} the current window title is displayed. + +*rewrite*: ++ + typeof: object ++ + Rules to rewrite window title. See *rewrite rules*. + +*icon*: ++ + typeof: bool ++ + default: false ++ + Option to hide the application icon. + +*icon-size*: ++ + typeof: integer ++ + default: 24 ++ + Option to change the size of the application icon. + +*expand*: ++ + typeof: bool ++ + default: false ++ + Enables this module to consume all left over space dynamically. + +# FORMAT REPLACEMENTS + +See the output of "wayfire msg windows" for examples + +*{title}*: The current title of the focused window. + +*{app_id}*: The current app ID of the focused window. + +# REWRITE RULES + +*rewrite* is an object where keys are regular expressions and values are +rewrite rules if the expression matches. Rules may contain references to +captures of the expression. + +Regular expression and replacement follow ECMA-script rules. + +If no expression matches, the title is left unchanged. + +Invalid expressions (e.g., mismatched parentheses) are skipped. + +# EXAMPLES + +``` +"wayfire/window": { + "format": "{}", + "rewrite": { + "(.*) - Mozilla Firefox": "🌎 $1", + "(.*) - zsh": "> [$1]" + } +} +``` + +# STYLE + +- *#window* +- *window#waybar.empty #window* When no windows are on the workspace + +The following classes are applied to the entire Waybar rather than just the +window widget: + +- *window#waybar.empty* When no windows are in the workspace +- *window#waybar.solo* When only one window is on the workspace +- *window#waybar.* Where *app-id* is the app ID of the only window on + the workspace diff --git a/man/waybar-wayfire-workspaces.5.scd b/man/waybar-wayfire-workspaces.5.scd new file mode 100644 index 00000000..53a179e8 --- /dev/null +++ b/man/waybar-wayfire-workspaces.5.scd @@ -0,0 +1,86 @@ +waybar-wayfire-workspaces(5) + +# NAME + +waybar - wayfire workspaces module + +# DESCRIPTION + +The *workspaces* module displays the currently used workspaces in wayfire. + +# CONFIGURATION + +Addressed by *wayfire/workspaces* + +*format*: ++ + typeof: string ++ + default: {value} ++ + The format, how information should be displayed. + +*format-icons*: ++ + typeof: array ++ + Based on the workspace name, index and state, the corresponding icon gets selected. See *icons*. + +*disable-click*: ++ + typeof: bool ++ + default: false ++ + If set to false, you can click to change workspace. If set to true this behaviour is disabled. + +*disable-markup*: ++ + typeof: bool ++ + default: false ++ + If set to true, button label will escape pango markup. + +*current-only*: ++ + typeof: bool ++ + default: false ++ + If set to true, only the active or focused workspace will be shown. + +*on-update*: ++ + typeof: string ++ + Command to execute when the module is updated. + +*expand*: ++ + typeof: bool ++ + default: false ++ + Enables this module to consume all left over space dynamically. + +# FORMAT REPLACEMENTS + +*{icon}*: Icon, as defined in *format-icons*. + +*{index}*: Index of the workspace on its output. + +*{output}*: Output where the workspace is located. + +# ICONS + +Additional to workspace name matching, the following *format-icons* can be set. + +- *default*: Will be shown, when no string matches are found. +- *focused*: Will be shown, when workspace is focused. + +# EXAMPLES + +``` +"wayfire/workspaces": { + "format": "{icon}", + "format-icons": { + "1": "", + "2": "", + "3": "", + "4": "", + "5": "", + "focused": "", + "default": "" + } +} +``` + +# Style + +- *#workspaces button* +- *#workspaces button.focused*: The single focused workspace. +- *#workspaces button.empty*: The workspace is empty. +- *#workspaces button.current_output*: The workspace is from the same output as + the bar that it is displayed on. diff --git a/man/waybar-wireplumber.5.scd b/man/waybar-wireplumber.5.scd index ae78f184..8d97d7af 100644 --- a/man/waybar-wireplumber.5.scd +++ b/man/waybar-wireplumber.5.scd @@ -128,7 +128,7 @@ The *wireplumber* module displays the current volume reported by WirePlumber. ``` "wireplumber#sink": { "format": "{volume}% {icon}", - "format-muted": "", + "format-muted": "󰅶", "format-icons": ["", "", ""], "on-click": "helvum", "on-click-right": "wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle", diff --git a/man/waybar-wlr-taskbar.5.scd b/man/waybar-wlr-taskbar.5.scd index af1ba97f..2aa26f3f 100644 --- a/man/waybar-wlr-taskbar.5.scd +++ b/man/waybar-wlr-taskbar.5.scd @@ -57,6 +57,11 @@ Addressed by *wlr/taskbar* default: false ++ If set to true, group tasks by their app_id. Cannot be used with 'active-first'. +*expand*: ++ + typeof: bool ++ + default: false ++ + If set to true, task buttons stretch to fill the available space in the taskbar and long titles are ellipsized to fit. Only takes effect on a horizontal bar; on a vertical bar the buttons keep their content-based size. If set to false, buttons are sized to their content. + *on-click*: ++ typeof: string ++ The action which should be triggered when clicking on the application button with the left mouse button. diff --git a/man/waybar.5.scd.in b/man/waybar.5.scd.in index 5bb62724..d7766c90 100644 --- a/man/waybar.5.scd.in +++ b/man/waybar.5.scd.in @@ -19,7 +19,7 @@ Valid locations for this file are: A good starting point is the default configuration found at https://github.com/Alexays/Waybar/blob/master/resources/config.jsonc Also, a minimal example configuration can be found at the bottom of this man page. -The visual display elements for waybar use a CSS stylesheet, see *waybar-styles(5)* for details. +The visual display elements for waybar use a CSS stylesheet. Waybar supports *style.css* and the appearance-specific *style-light.css* and *style-dark.css* files; see *waybar-styles(5)* for details. # BAR CONFIGURATION @@ -36,7 +36,7 @@ The visual display elements for waybar use a CSS stylesheet, see *waybar-styles( *expand-right* ++ typeof: bool ++ default: false ++ - Enables the modules-left to consume all left over space dynamically. + Enables the modules-right to consume all left over space dynamically. *layer* ++ typeof: string ++ @@ -86,7 +86,7 @@ The visual display elements for waybar use a CSS stylesheet, see *waybar-styles( *no-center* ++ typeof: bool ++ default: false ++ - Option to disable the center modules fully usefull together with expand-\*. + Option to disable the center modules fully useful together with expand-\*. *spacing* ++ typeof: integer ++ @@ -151,9 +151,24 @@ The visual display elements for waybar use a CSS stylesheet, see *waybar-styles( default: *false* ++ Option to enable reloading the css style if a modification is detected on the style sheet file or any imported css files. +*on-sigusr1* ++ + typeof: string ++ + default: *toggle* ++ + Action that is performed when receiving SIGUSR1 kill signal. ++ + Possible values: *show*, *hide*, *toggle*, *reload*, *noop*. ++ + Default value: *toggle*. + +*on-sigusr2* ++ + typeof: string ++ + default: *reload* ++ + Action that is performed when receiving SIGUSR2 kill signal. ++ + Possible values: *show*, *hide*, *toggle*, *reload*, *noop*. ++ + Default value: *reload*. + # MODULE FORMAT You can use PangoMarkupFormat (See https://developer.gnome.org/pango/stable/PangoMarkupFormat.html#PangoMarkupFormat). +Tooltip appearance is generally controlled globally via CSS and cannot be truly scoped per module. Some modules (such as the clock) provide limited workarounds for customization. e.g. @@ -206,14 +221,36 @@ A minimal *config* file could look like this: Waybar accepts the following signals: *SIGUSR1* - Toggles the bar visibility (hides if shown, shows if hidden) + By default toggles the bar visibility (hides if shown, shows if hidden) *SIGUSR2* - Reloads (resets) the bar + By default reloads (resets) the bar *SIGINT* Quits the bar For example, to toggle the bar programmatically, you can invoke `killall -SIGUSR1 waybar`. +## User signal configuration + +Config parameters *on-sigusr1* and *on-sigusr2* change what happens when bars receive +*SIGUSR1* and *SIGUSR2* signals. + +This means that commands `killall -SIGUSR1 waybar` and `killall -SIGUSR2 waybar` +can perform user-configured action. + +It also means that if an external script has the PID of the bar then it can +perform more complex `show`/`hide`/`reload` logic for each instance of Waybar. +One can find the PID e.g. by doing `pgrep -a waybar` which could then match +by config name or other parameters. + +## Kill parameter meanings + +*show* Switches state to visible (per bar). +*hide* Switches state to hidden (per bar). +*toggle* Switches state between visible and hidden (per bar). +*reload* Reloads all waybars of current waybar process (basically equivalent to +restarting with updated config which sets initial visibility values). +*noop* Does nothing when the kill signal is received. + # MULTI OUTPUT CONFIGURATION ## Limit a configuration to some outputs @@ -272,6 +309,17 @@ When positioning Waybar on the left or right side of the screen, sometimes it's Valid options for the "rotate" property are: 0, 90, 180, and 270. +## Swapping icon and label + +If a module displays both a label and an icon, it might be desirable to swap them (for instance, for panels on the left or right of the screen, or for user adopting a right-to-left script). This can be achieved with the "swap-icon-label" property, taking a boolean. Example: +``` +{ + "sway/window": { + "swap-icon-label": true + } +} +``` + ## Grouping modules Module groups allow stacking modules in any direction. By default, when the bar is positioned on the top or bottom of the screen, modules in a group are stacked vertically. Likewise, when positioned on the left or right, modules in a group are stacked horizontally. This can be changed with the "orientation" property. @@ -316,6 +364,11 @@ A group may hide all but one element, showing them only on mouse hover. In order default: false ++ Whether left click should reveal the content rather than mouse over. Note that grouped modules may still process their own on-click events. +*start-expanded*: ++ + typeof: bool ++ + default: false ++ + Defines whether the drawer should initialize in an expanded state. + *transition-left-to-right*: ++ typeof: bool ++ default: true ++ @@ -390,4 +443,4 @@ A group may hide all but one element, showing them only on mouse hover. In order # SEE ALSO *sway-output(5)* -*waybar-styles(5)" +*waybar-styles(5)* diff --git a/meson.build b/meson.build index 7f9854d5..e528a6da 100644 --- a/meson.build +++ b/meson.build @@ -1,6 +1,6 @@ project( 'waybar', 'cpp', 'c', - version: '0.12.0', + version: '0.15.0', license: 'MIT', meson_version: '>= 0.59.0', default_options : [ @@ -69,7 +69,7 @@ is_openbsd = host_machine.system() == 'openbsd' thread_dep = dependency('threads') fmt = dependency('fmt', version : ['>=8.1.1'], fallback : ['fmt', 'fmt_dep']) -spdlog = dependency('spdlog', version : ['>=1.10.0'], fallback : ['spdlog', 'spdlog_dep'], default_options : ['external_fmt=enabled', 'std_format=disabled', 'tests=disabled']) +spdlog = dependency('spdlog', version : ['>=1.15.2'], fallback : ['spdlog', 'spdlog_dep'], default_options : ['std_format=disabled', 'tests=disabled']) wayland_client = dependency('wayland-client') wayland_cursor = dependency('wayland-cursor') wayland_protos = dependency('wayland-protocols') @@ -93,6 +93,7 @@ libmpdclient = dependency('libmpdclient', required: get_option('mpd')) xkbregistry = dependency('xkbregistry') libjack = dependency('jack', required: get_option('jack')) libwireplumber = dependency('wireplumber-0.5', required: get_option('wireplumber')) +libgps = dependency('libgps', required: get_option('gps')) libsndio = compiler.find_library('sndio', required: get_option('sndio')) if libsndio.found() @@ -182,8 +183,11 @@ src_files = files( 'src/util/sanitize_str.cpp', 'src/util/rewrite_string.cpp', 'src/util/gtk_icon.cpp', + 'src/util/icon_loader.cpp', 'src/util/regex_collection.cpp', - 'src/util/css_reload_helper.cpp' + 'src/util/css_reload_helper.cpp', + 'src/util/transform_8bit_to_rgba.cpp', + 'src/util/utf8_string.cpp' ) man_files = files( @@ -275,6 +279,17 @@ if true man_files += files('man/waybar-wlr-taskbar.5.scd') endif +if wayland_protos.version().version_compare('>=1.39') + add_project_arguments('-DHAVE_EXT_WORKSPACES', language: 'cpp') + src_files += files( + 'src/modules/ext/workspace_manager.cpp', + 'src/modules/ext/workspace_manager_binding.cpp', + ) + man_files += files( + 'man/waybar-ext-workspaces.5.scd', + ) +endif + if true add_project_arguments('-DHAVE_RIVER', language: 'cpp') src_files += files( @@ -306,6 +321,7 @@ if true 'src/modules/hyprland/language.cpp', 'src/modules/hyprland/submap.cpp', 'src/modules/hyprland/window.cpp', + 'src/modules/hyprland/windowcount.cpp', 'src/modules/hyprland/workspace.cpp', 'src/modules/hyprland/workspaces.cpp', 'src/modules/hyprland/windowcreationpayload.cpp', @@ -333,6 +349,15 @@ if get_option('niri') ) endif +if true + add_project_arguments('-DHAVE_WAYFIRE', language: 'cpp') + src_files += files( + 'src/modules/wayfire/backend.cpp', + 'src/modules/wayfire/window.cpp', + 'src/modules/wayfire/workspaces.cpp', + ) +endif + if get_option('login-proxy') add_project_arguments('-DHAVE_LOGIN_PROXY', language: 'cpp') endif @@ -474,27 +499,30 @@ else man_files += files('man/waybar-clock.5.scd') endif -if get_option('experimental') - add_project_arguments('-DHAVE_WLR_WORKSPACES', language: 'cpp') - src_files += files( - 'src/modules/wlr/workspace_manager.cpp', - 'src/modules/wlr/workspace_manager_binding.cpp', - ) - man_files += files( - 'man/waybar-wlr-workspaces.5.scd', - ) -endif - -cava = dependency('cava', - version : '>=0.10.4', +cava = dependency('libcava', + version : '>=0.10.7', required: get_option('cava'), - fallback : ['cava', 'cava_dep'], + fallback : ['libcava', 'cava_dep'], not_found_message: 'cava is not found. Building waybar without cava') +eproxy = dependency('epoxy', required: false) + if cava.found() add_project_arguments('-DHAVE_LIBCAVA', language: 'cpp') - src_files += files('src/modules/cava.cpp') + src_files += files('src/modules/cava/cavaRaw.cpp', + 'src/modules/cava/cava_backend.cpp') man_files += files('man/waybar-cava.5.scd') + + if eproxy.found() + add_project_arguments('-DHAVE_LIBCAVAGLSL', language: 'cpp') + src_files += files('src/modules/cava/cavaGLSL.cpp') + endif +endif + +if libgps.found() + add_project_arguments('-DHAVE_LIBGPS', language: 'cpp') + src_files += files('src/modules/gps.cpp') + man_files += files('man/waybar-gps.5.scd') endif subdir('protocol') @@ -535,7 +563,9 @@ executable( libsndio, tz_dep, xkbregistry, - cava + cava, + eproxy, + libgps ], include_directories: inc_dirs, install: true, diff --git a/meson_options.txt b/meson_options.txt index d83fe01f..eac4e324 100644 --- a/meson_options.txt +++ b/meson_options.txt @@ -12,7 +12,7 @@ option('dbusmenu-gtk', type: 'feature', value: 'auto', description: 'Enable supp option('man-pages', type: 'feature', value: 'auto', description: 'Generate and install man pages') option('mpd', type: 'feature', value: 'auto', description: 'Enable support for the Music Player Daemon') option('rfkill', type: 'feature', value: 'auto', description: 'Enable support for RFKILL') -option('sndio', type: 'feature', value: 'auto', description: 'Enable support for sndio') +option('sndio', type: 'feature', value: 'auto', description: 'Enable support for volume control via sndio') option('logind', type: 'feature', value: 'auto', description: 'Enable support for logind') option('tests', type: 'feature', value: 'auto', description: 'Enable tests') option('experimental', type : 'boolean', value : false, description: 'Enable experimental features') @@ -21,3 +21,4 @@ option('wireplumber', type: 'feature', value: 'auto', description: 'Enable suppo option('cava', type: 'feature', value: 'auto', description: 'Enable support for Cava') option('niri', type: 'boolean', description: 'Enable support for niri') option('login-proxy', type: 'boolean', description: 'Enable interfacing with dbus login interface') +option('gps', type: 'feature', value: 'auto', description: 'Enable support for gps') diff --git a/nix/default.nix b/nix/default.nix index 4cfd75c0..1850a414 100644 --- a/nix/default.nix +++ b/nix/default.nix @@ -6,16 +6,17 @@ }: let libcava = rec { - version = "0.10.4"; + version = "0.10.7"; src = pkgs.fetchFromGitHub { owner = "LukashonakV"; repo = "cava"; - tag = version; - hash = "sha256-9eTDqM+O1tA/3bEfd1apm8LbEcR9CVgELTIspSVPMKM="; + # NOTE: Needs to match the cava.wrap + tag = "${version}"; + hash = "sha256-zkyj1vBzHtoypX4Bxdh1Vmwh967DKKxN751v79hzmgQ="; }; }; in -(waybar.overrideAttrs (oldAttrs: { +waybar.overrideAttrs (oldAttrs: { inherit version; src = lib.cleanSourceWith { @@ -30,9 +31,12 @@ in # nixpkgs checks version, no need when building locally nativeInstallCheckInputs = [ ]; - buildInputs = (builtins.filter (p: p.pname != "wireplumber") oldAttrs.buildInputs) ++ [ - pkgs.wireplumber - ]; + buildInputs = + (builtins.filter (p: p.pname != "wireplumber" && p.pname != "gps") oldAttrs.buildInputs) + ++ [ + pkgs.wireplumber + pkgs.gpsd + ]; postUnpack = '' pushd "$sourceRoot" @@ -40,4 +44,4 @@ in patchShebangs . popd ''; -})) +}) diff --git a/protocol/ext-workspace-unstable-v1.xml b/protocol/ext-workspace-unstable-v1.xml deleted file mode 100644 index 24410b62..00000000 --- a/protocol/ext-workspace-unstable-v1.xml +++ /dev/null @@ -1,306 +0,0 @@ - - - - Copyright © 2019 Christopher Billington - Copyright © 2020 Ilia Bozhinov - - Permission to use, copy, modify, distribute, and sell this - software and its documentation for any purpose is hereby granted - without fee, provided that the above copyright notice appear in - all copies and that both that copyright notice and this permission - notice appear in supporting documentation, and that the name of - the copyright holders not be used in advertising or publicity - pertaining to distribution of the software without specific, - written prior permission. The copyright holders make no - representations about the suitability of this software for any - purpose. It is provided "as is" without express or implied - warranty. - - THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS - SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY - SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN - AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, - ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF - THIS SOFTWARE. - - - - - Workspaces, also called virtual desktops, are groups of surfaces. A - compositor with a concept of workspaces may only show some such groups of - surfaces (those of 'active' workspaces) at a time. 'Activating' a - workspace is a request for the compositor to display that workspace's - surfaces as normal, whereas the compositor may hide or otherwise - de-emphasise surfaces that are associated only with 'inactive' workspaces. - Workspaces are grouped by which sets of outputs they correspond to, and - may contain surfaces only from those outputs. In this way, it is possible - for each output to have its own set of workspaces, or for all outputs (or - any other arbitrary grouping) to share workspaces. Compositors may - optionally conceptually arrange each group of workspaces in an - N-dimensional grid. - - The purpose of this protocol is to enable the creation of taskbars and - docks by providing them with a list of workspaces and their properties, - and allowing them to activate and deactivate workspaces. - - After a client binds the zext_workspace_manager_v1, each workspace will be - sent via the workspace event. - - - - - This event is emitted whenever a new workspace group has been created. - - All initial details of the workspace group (workspaces, outputs) will be - sent immediately after this event via the corresponding events in - zext_workspace_group_handle_v1. - - - - - - - The client must send this request after it has finished sending other - requests. The compositor must process a series of requests preceding a - commit request atomically. - - This allows changes to the workspace properties to be seen as atomic, - even if they happen via multiple events, and even if they involve - multiple zext_workspace_handle_v1 objects, for example, deactivating one - workspace and activating another. - - - - - - This event is sent after all changes in all workspace groups have been - sent. - - This allows changes to one or more zext_workspace_group_handle_v1 - properties to be seen as atomic, even if they happen via multiple - events. In particular, an output moving from one workspace group to - another sends an output_enter event and an output_leave event to the two - zext_workspace_group_handle_v1 objects in question. The compositor sends - the done event only after updating the output information in both - workspace groups. - - - - - - This event indicates that the compositor is done sending events to the - zext_workspace_manager_v1. The server will destroy the object - immediately after sending this request, so it will become invalid and - the client should free any resources associated with it. - - - - - - Indicates the client no longer wishes to receive events for new - workspace groups. However the compositor may emit further workspace - events, until the finished event is emitted. - - The client must not send any more requests after this one. - - - - - - - A zext_workspace_group_handle_v1 object represents a a workspace group - that is assigned a set of outputs and contains a number of workspaces. - - The set of outputs assigned to the workspace group is conveyed to the client via - output_enter and output_leave events, and its workspaces are conveyed with - workspace events. - - For example, a compositor which has a set of workspaces for each output may - advertise a workspace group (and its workspaces) per output, whereas a compositor - where a workspace spans all outputs may advertise a single workspace group for all - outputs. - - - - - This event is emitted whenever an output is assigned to the workspace - group. - - - - - - - This event is emitted whenever an output is removed from the workspace - group. - - - - - - - This event is emitted whenever a new workspace has been created. - - All initial details of the workspace (name, coordinates, state) will - be sent immediately after this event via the corresponding events in - zext_workspace_handle_v1. - - - - - - - This event means the zext_workspace_group_handle_v1 has been destroyed. - It is guaranteed there won't be any more events for this - zext_workspace_group_handle_v1. The zext_workspace_group_handle_v1 becomes - inert so any requests will be ignored except the destroy request. - - The compositor must remove all workspaces belonging to a workspace group - before removing the workspace group. - - - - - - Request that the compositor create a new workspace with the given name. - - There is no guarantee that the compositor will create a new workspace, - or that the created workspace will have the provided name. - - - - - - - Destroys the zext_workspace_handle_v1 object. - - This request should be called either when the client does not want to - use the workspace object any more or after the remove event to finalize - the destruction of the object. - - - - - - - A zext_workspace_handle_v1 object represents a a workspace that handles a - group of surfaces. - - Each workspace has a name, conveyed to the client with the name event; a - list of states, conveyed to the client with the state event; and - optionally a set of coordinates, conveyed to the client with the - coordinates event. The client may request that the compositor activate or - deactivate the workspace. - - Each workspace can belong to only a single workspace group. - Depepending on the compositor policy, there might be workspaces with - the same name in different workspace groups, but these workspaces are still - separate (e.g. one of them might be active while the other is not). - - - - - This event is emitted immediately after the zext_workspace_handle_v1 is - created and whenever the name of the workspace changes. - - - - - - - This event is used to organize workspaces into an N-dimensional grid - within a workspace group, and if supported, is emitted immediately after - the zext_workspace_handle_v1 is created and whenever the coordinates of - the workspace change. Compositors may not send this event if they do not - conceptually arrange workspaces in this way. If compositors simply - number workspaces, without any geometric interpretation, they may send - 1D coordinates, which clients should not interpret as implying any - geometry. Sending an empty array means that the compositor no longer - orders the workspace geometrically. - - Coordinates have an arbitrary number of dimensions N with an uint32 - position along each dimension. By convention if N > 1, the first - dimension is X, the second Y, the third Z, and so on. The compositor may - chose to utilize these events for a more novel workspace layout - convention, however. No guarantee is made about the grid being filled or - bounded; there may be a workspace at coordinate 1 and another at - coordinate 1000 and none in between. Within a workspace group, however, - workspaces must have unique coordinates of equal dimensionality. - - - - - - - This event is emitted immediately after the zext_workspace_handle_v1 is - created and each time the workspace state changes, either because of a - compositor action or because of a request in this protocol. - - - - - - - The different states that a workspace can have. - - - - - - - The workspace is not visible in its workspace group, and clients - attempting to visualize the compositor workspace state should not - display such workspaces. - - - - - - - This event means the zext_workspace_handle_v1 has been destroyed. It is - guaranteed there won't be any more events for this - zext_workspace_handle_v1. The zext_workspace_handle_v1 becomes inert so - any requests will be ignored except the destroy request. - - - - - - Destroys the zext_workspace_handle_v1 object. - - This request should be called either when the client does not want to - use the workspace object any more or after the remove event to finalize - the destruction of the object. - - - - - - Request that this workspace be activated. - - There is no guarantee the workspace will be actually activated, and - behaviour may be compositor-dependent. For example, activating a - workspace may or may not deactivate all other workspaces in the same - group. - - - - - - Request that this workspace be deactivated. - - There is no guarantee the workspace will be actually deactivated. - - - - - - Request that this workspace be removed. - - There is no guarantee the workspace will be actually removed. - - - - diff --git a/protocol/meson.build b/protocol/meson.build index cd9a77b1..b16113b2 100644 --- a/protocol/meson.build +++ b/protocol/meson.build @@ -26,12 +26,17 @@ client_protocols = [ [wl_protocol_dir, 'unstable/xdg-output/xdg-output-unstable-v1.xml'], [wl_protocol_dir, 'unstable/idle-inhibit/idle-inhibit-unstable-v1.xml'], ['wlr-foreign-toplevel-management-unstable-v1.xml'], - ['ext-workspace-unstable-v1.xml'], ['river-status-unstable-v1.xml'], ['river-control-unstable-v1.xml'], ['dwl-ipc-unstable-v2.xml'], ] +if wayland_protos.version().version_compare('>=1.39') + client_protocols += [ + [wl_protocol_dir, 'staging/ext-workspace/ext-workspace-v1.xml'] + ] +endif + client_protos_src = [] client_protos_headers = [] diff --git a/resources/config.jsonc b/resources/config.jsonc index 67d5ff5b..9ba8b97a 100644 --- a/resources/config.jsonc +++ b/resources/config.jsonc @@ -128,7 +128,7 @@ "critical-threshold": 80, // "format-critical": "{temperatureC}°C {icon}", "format": "{temperatureC}°C {icon}", - "format-icons": ["", "", ""] + "format-icons": ["󰉬", "", "󰉪"] }, "backlight": { // "device": "acpi_video1", @@ -143,7 +143,7 @@ }, "format": "{capacity}% {icon}", "format-full": "{capacity}% {icon}", - "format-charging": "{capacity}% ", + "format-charging": "{capacity}% 󰃨", "format-plugged": "{capacity}% ", "format-alt": "{time} {icon}", // "format-good": "", // An empty format will hide the module @@ -167,9 +167,9 @@ "network": { // "interface": "wlp2*", // (Optional) To force the use of this interface "format-wifi": "{essid} ({signalStrength}%) ", - "format-ethernet": "{ipaddr}/{cidr} ", - "tooltip-format": "{ifname} via {gwaddr} ", - "format-linked": "{ifname} (No IP) ", + "format-ethernet": "{ipaddr}/{cidr} 󰊗", + "tooltip-format": "{ifname} via {gwaddr} 󰊗", + "format-linked": "{ifname} (No IP) 󰊗", "format-disconnected": "Disconnected ⚠", "format-alt": "{ifname}: {ipaddr}/{cidr}" }, @@ -177,14 +177,14 @@ // "scroll-step": 1, // %, can be a float "format": "{volume}% {icon} {format_source}", "format-bluetooth": "{volume}% {icon} {format_source}", - "format-bluetooth-muted": " {icon} {format_source}", - "format-muted": " {format_source}", + "format-bluetooth-muted": "󰅶 {icon} {format_source}", + "format-muted": "󰅶 {format_source}", "format-source": "{volume}% ", "format-source-muted": "", "format-icons": { "headphone": "", - "hands-free": "", - "headset": "", + "hands-free": "󰂑", + "headset": "󰂑", "phone": "", "portable": "", "car": "", diff --git a/resources/custom_modules/mediaplayer.py b/resources/custom_modules/mediaplayer.py index d1bb72b4..4de1edf8 100755 --- a/resources/custom_modules/mediaplayer.py +++ b/resources/custom_modules/mediaplayer.py @@ -105,23 +105,26 @@ class PlayerManager: current_player = self.get_first_playing_player() if current_player is not None: self.on_metadata_changed(current_player, current_player.props.metadata) - else: + else: self.clear_output() def on_metadata_changed(self, player, metadata, _=None): logger.debug(f"Metadata changed for player {player.props.player_name}") player_name = player.props.player_name artist = player.get_artist() + artist = artist and artist.replace("&", "&") title = player.get_title() - title = title.replace("&", "&") + title = title and title.replace("&", "&") track_info = "" if player_name == "spotify" and "mpris:trackid" in metadata.keys() and ":ad:" in player.props.metadata["mpris:trackid"]: track_info = "Advertisement" elif artist is not None and title is not None: track_info = f"{artist} - {title}" - else: + elif title is not None: track_info = title + elif artist is not None: + track_info = artist if track_info: if player.props.status == "Playing": diff --git a/resources/custom_modules/power_menu.xml b/resources/custom_modules/power_menu.xml index aa2a42ca..972499d7 100644 --- a/resources/custom_modules/power_menu.xml +++ b/resources/custom_modules/power_menu.xml @@ -2,27 +2,27 @@ - - Suspend - - - - - Hibernate - - + + Suspend + + - - Shutdown - + + Hibernate + + + + + Shutdown + - - Reboot - + + Reboot + diff --git a/resources/style.css b/resources/style.css index 7e830285..bcfcb5c8 100644 --- a/resources/style.css +++ b/resources/style.css @@ -63,7 +63,7 @@ button:hover { background: rgba(0, 0, 0, 0.2); } -#workspaces button.focused { +#workspaces button.focused, #workspaces button.active { background-color: #64727D; box-shadow: inset 0 -3px #ffffff; } diff --git a/resources/waybar.service.in b/resources/waybar.service.in index 81ac6779..18bac54c 100644 --- a/resources/waybar.service.in +++ b/resources/waybar.service.in @@ -1,5 +1,5 @@ [Unit] -Description=Highly customizable Wayland bar for Sway and Wlroots based compositors. +Description=Highly customizable Wayland bar for Sway and Wlroots based compositors Documentation=https://github.com/Alexays/Waybar/wiki/ PartOf=graphical-session.target After=graphical-session.target diff --git a/src/AAppIconLabel.cpp b/src/AAppIconLabel.cpp index 3f47eff1..784f30c2 100644 --- a/src/AAppIconLabel.cpp +++ b/src/AAppIconLabel.cpp @@ -33,21 +33,21 @@ std::string toLowerCase(const std::string& input) { std::optional getFileBySuffix(const std::string& dir, const std::string& suffix, bool check_lower_case) { - if (!std::filesystem::exists(dir)) { - return {}; - } - for (const auto& entry : std::filesystem::recursive_directory_iterator(dir)) { - if (entry.is_regular_file()) { - std::string filename = entry.path().filename().string(); - if (filename.size() < suffix.size()) { - continue; - } - if ((filename.compare(filename.size() - suffix.size(), suffix.size(), suffix) == 0) || - (check_lower_case && filename.compare(filename.size() - suffix.size(), suffix.size(), - toLowerCase(suffix)) == 0)) { - return entry.path().string(); + try { + for (const auto& entry : std::filesystem::recursive_directory_iterator(dir)) { + if (entry.is_regular_file()) { + std::string filename = entry.path().filename().string(); + if (filename.size() < suffix.size()) { + continue; + } + if ((filename.compare(filename.size() - suffix.size(), suffix.size(), suffix) == 0) || + (check_lower_case && filename.compare(filename.size() - suffix.size(), suffix.size(), + toLowerCase(suffix)) == 0)) { + return entry.path().string(); + } } } + } catch (const std::filesystem::filesystem_error&) { } return {}; @@ -63,7 +63,8 @@ std::optional getDesktopFilePath(const std::string& app_identifier, return {}; } - const auto data_dirs = Glib::get_system_data_dirs(); + auto data_dirs = Glib::get_system_data_dirs(); + data_dirs.insert(data_dirs.begin(), Glib::get_user_data_dir()); for (const auto& data_dir : data_dirs) { const auto data_app_dir = data_dir + "/applications/"; auto desktop_file_suffix = app_identifier + ".desktop"; @@ -150,19 +151,24 @@ void AAppIconLabel::updateAppIconName(const std::string& app_identifier, } void AAppIconLabel::updateAppIcon() { - if (update_app_icon_) { + if (update_app_icon_ || (!iconEnabled() && image_.get_visible())) { update_app_icon_ = false; if (app_icon_name_.empty()) { image_.set_visible(false); } else if (app_icon_name_.front() == '/') { - auto pixbuf = Gdk::Pixbuf::create_from_file(app_icon_name_); - int scaled_icon_size = app_icon_size_ * image_.get_scale_factor(); - pixbuf = Gdk::Pixbuf::create_from_file(app_icon_name_, scaled_icon_size, scaled_icon_size); + try { + int scaled_icon_size = app_icon_size_ * image_.get_scale_factor(); + auto pixbuf = + Gdk::Pixbuf::create_from_file(app_icon_name_, scaled_icon_size, scaled_icon_size); - auto surface = Gdk::Cairo::create_surface_from_pixbuf(pixbuf, image_.get_scale_factor(), - image_.get_window()); - image_.set(surface); - image_.set_visible(true); + auto surface = Gdk::Cairo::create_surface_from_pixbuf(pixbuf, image_.get_scale_factor(), + image_.get_window()); + image_.set(surface); + image_.set_visible(true); + } catch (const Glib::Exception& e) { + spdlog::warn("Failed to load app icon {}: {}", app_icon_name_, std::string(e.what())); + image_.set_visible(false); + } } else { image_.set_from_icon_name(app_icon_name_, Gtk::ICON_SIZE_INVALID); image_.set_visible(true); diff --git a/src/AIconLabel.cpp b/src/AIconLabel.cpp index d7ee666e..5c7df0ed 100644 --- a/src/AIconLabel.cpp +++ b/src/AIconLabel.cpp @@ -1,11 +1,12 @@ #include "AIconLabel.hpp" #include +#include namespace waybar { -AIconLabel::AIconLabel(const Json::Value &config, const std::string &name, const std::string &id, - const std::string &format, uint16_t interval, bool ellipsize, +AIconLabel::AIconLabel(const Json::Value& config, const std::string& name, const std::string& id, + const std::string& format, uint16_t interval, bool ellipsize, bool enable_click, bool enable_scroll) : ALabel(config, name, id, format, interval, ellipsize, enable_click, enable_scroll) { event_box_.remove(); @@ -17,14 +18,39 @@ AIconLabel::AIconLabel(const Json::Value &config, const std::string &name, const box_.get_style_context()->add_class(id); } - box_.set_orientation(Gtk::Orientation::ORIENTATION_HORIZONTAL); + int rot = 0; + + if (config_["rotate"].isUInt()) { + rot = config["rotate"].asUInt() % 360; + if ((rot % 90) != 00) rot = 0; + rot /= 90; + } + + if ((rot % 2) == 0) + box_.set_orientation(Gtk::Orientation::ORIENTATION_HORIZONTAL); + else + box_.set_orientation(Gtk::Orientation::ORIENTATION_VERTICAL); box_.set_name(name); int spacing = config_["icon-spacing"].isInt() ? config_["icon-spacing"].asInt() : 8; box_.set_spacing(spacing); - box_.add(image_); - box_.add(label_); + bool swap_icon_label = false; + if (config_["swap-icon-label"].isNull()) { + } else if (config_["swap-icon-label"].isBool()) { + swap_icon_label = config_["swap-icon-label"].asBool(); + } else { + spdlog::warn("'swap-icon-label' must be a bool, found '{}'. Using default value (false).", + config_["swap-icon-label"].asString()); + } + + if ((rot == 0 || rot == 3) ^ swap_icon_label) { + box_.add(image_); + box_.add(label_); + } else { + box_.add(label_); + box_.add(image_); + } event_box_.add(box_); } diff --git a/src/ALabel.cpp b/src/ALabel.cpp index c218e402..f2a585fe 100644 --- a/src/ALabel.cpp +++ b/src/ALabel.cpp @@ -17,10 +17,17 @@ ALabel::ALabel(const Json::Value& config, const std::string& name, const std::st config["format-alt"].isString() || config["menu"].isString() || enable_click, enable_scroll), format_(config_["format"].isString() ? config_["format"].asString() : format), + + // Leave the default option outside of the std::max(1L, ...), because the zero value + // (default) is used in modules/custom.cpp to make the difference between + // two types of custom scripts. Fixes #4521. interval_(config_["interval"] == "once" - ? std::chrono::seconds::max() - : std::chrono::seconds( - config_["interval"].isUInt() ? config_["interval"].asUInt() : interval)), + ? std::chrono::milliseconds::max() + : std::chrono::milliseconds( + (config_["interval"].isNumeric() + ? std::max(1L, // Minimum 1ms due to millisecond precision + static_cast(config_["interval"].asDouble() * 1000)) + : 1000 * (long)interval))), default_format_(format_) { label_.set_name(name); if (!id.empty()) { @@ -84,13 +91,17 @@ ALabel::ALabel(const Json::Value& config, const std::string& name, const std::st // Make the GtkBuilder and check for errors in his parsing if (gtk_builder_add_from_string(builder, fileContent.str().c_str(), -1, nullptr) == 0U) { + g_object_unref(builder); throw std::runtime_error("Error found in the file " + menuFile); } menu_ = gtk_builder_get_object(builder, "menu"); if (menu_ == nullptr) { + g_object_unref(builder); throw std::runtime_error("Failed to get 'menu' object from GtkBuilder"); } + // Keep the menu alive after dropping the transient GtkBuilder. + g_object_ref(menu_); submenus_ = std::map(); menuActionsMap_ = std::map(); @@ -98,11 +109,17 @@ ALabel::ALabel(const Json::Value& config, const std::string& name, const std::st for (Json::Value::const_iterator it = config_["menu-actions"].begin(); it != config_["menu-actions"].end(); ++it) { std::string key = it.key().asString(); - submenus_[key] = GTK_MENU_ITEM(gtk_builder_get_object(builder, key.c_str())); + auto* item = gtk_builder_get_object(builder, key.c_str()); + if (item == nullptr) { + spdlog::warn("Menu item '{}' not found in builder file", key); + continue; + } + submenus_[key] = GTK_MENU_ITEM(item); menuActionsMap_[key] = it->asString(); g_signal_connect(submenus_[key], "activate", G_CALLBACK(handleGtkMenuEvent), (gpointer)menuActionsMap_[key].c_str()); } + g_object_unref(builder); } catch (std::runtime_error& e) { spdlog::warn("Error while creating the menu : {}. Menu popup not activated.", e.what()); } @@ -122,6 +139,26 @@ ALabel::ALabel(const Json::Value& config, const std::string& name, const std::st auto ALabel::update() -> void { AModule::update(); } +bool ALabel::setLabelMarkup(const Glib::ustring& markup) { + if (last_label_markup_ == markup) { + return false; + } + + label_.set_markup(markup); + last_label_markup_ = markup; + return true; +} + +bool ALabel::setTooltipMarkup(const Glib::ustring& markup) { + if (last_tooltip_markup_ == markup) { + return false; + } + + label_.set_tooltip_markup(markup); + last_tooltip_markup_ = markup; + return true; +} + std::string ALabel::getIcon(uint16_t percentage, const std::string& alt, uint16_t max) { auto format_icons = config_["format-icons"]; if (format_icons.isObject()) { @@ -134,7 +171,8 @@ std::string ALabel::getIcon(uint16_t percentage, const std::string& alt, uint16_ if (format_icons.isArray()) { auto size = format_icons.size(); if (size != 0U) { - auto idx = std::clamp(percentage / ((max == 0 ? 100 : max) / size), 0U, size - 1); + auto divisor = std::max(1U, (max == 0 ? 100U : static_cast(max)) / size); + auto idx = std::clamp(percentage / divisor, 0U, size - 1); format_icons = format_icons[idx]; } } @@ -160,7 +198,8 @@ std::string ALabel::getIcon(uint16_t percentage, const std::vector& if (format_icons.isArray()) { auto size = format_icons.size(); if (size != 0U) { - auto idx = std::clamp(percentage / ((max == 0 ? 100 : max) / size), 0U, size - 1); + auto divisor = std::max(1U, (max == 0 ? 100U : static_cast(max)) / size); + auto idx = std::clamp(percentage / divisor, 0U, size - 1); format_icons = format_icons[idx]; } } @@ -183,7 +222,7 @@ bool waybar::ALabel::handleToggle(GdkEventButton* const& e) { } void ALabel::handleGtkMenuEvent(GtkMenuItem* /*menuitem*/, gpointer data) { - waybar::util::command::res res = waybar::util::command::exec((char*)data, "GtkMenu"); + waybar::util::command::forkExec((char*)data, "GtkMenu"); } std::string ALabel::getState(uint8_t value, bool lesser) { @@ -200,7 +239,7 @@ std::string ALabel::getState(uint8_t value, bool lesser) { } } // Sort states - std::sort(states.begin(), states.end(), [&lesser](auto& a, auto& b) { + std::ranges::sort(states.begin(), states.end(), [&lesser](auto& a, auto& b) { return lesser ? a.second < b.second : a.second > b.second; }); std::string valid_state; diff --git a/src/AModule.cpp b/src/AModule.cpp index 5abb779a..353d0dea 100644 --- a/src/AModule.cpp +++ b/src/AModule.cpp @@ -17,10 +17,14 @@ AModule::AModule(const Json::Value& config, const std::string& name, const std:: isTooltip{config_["tooltip"].isBool() ? config_["tooltip"].asBool() : true}, isExpand{config_["expand"].isBool() ? config_["expand"].asBool() : false}, distance_scrolled_y_(0.0), - distance_scrolled_x_(0.0) { + distance_scrolled_x_(0.0), + cursor_timeout_conn_() { // Configure module action Map const Json::Value actions{config_["actions"]}; + disable_on_sleep_ = + config_["disable-on-sleep"].isBool() ? config_["disable-on-sleep"].asBool() : false; + for (Json::Value::const_iterator it = actions.begin(); it != actions.end(); ++it) { if (it.key().isString() && it->isString()) if (!eventActionMap_.contains(it.key().asString())) { @@ -72,8 +76,12 @@ AModule::AModule(const Json::Value& config, const std::string& name, const std:: // Respect user configuration of cursor if (config_.isMember("cursor")) { - if (config_["cursor"].isBool() && config_["cursor"].asBool()) { - setCursor(Gdk::HAND2); + if (config_["cursor"].isBool()) { + if (config_["cursor"].asBool()) { + setCursor(Gdk::HAND2); + } else { + setCursor(Gdk::ARROW); + } } else if (config_["cursor"].isInt()) { setCursor(Gdk::CursorType(config_["cursor"].asInt())); } else { @@ -83,25 +91,32 @@ AModule::AModule(const Json::Value& config, const std::string& name, const std:: } AModule::~AModule() { - for (const auto& pid : pid_) { + if (cursor_timeout_conn_.connected()) { + cursor_timeout_conn_.disconnect(); + } + for (const auto& pid : pid_children_) { if (pid != -1) { killpg(pid, SIGTERM); } } + if (menu_ != nullptr) { + g_object_unref(menu_); + menu_ = nullptr; + } } auto AModule::update() -> void { // Run user-provided update handler if configured if (config_["on-update"].isString()) { - pid_.push_back(util::command::forkExec(config_["on-update"].asString())); + pid_children_.push_back(util::command::forkExec(config_["on-update"].asString())); } } // Get mapping between event name and module action name -// Then call overrided doAction in order to call appropriate module action +// Then call overridden doAction in order to call appropriate module action auto AModule::doAction(const std::string& name) -> void { if (!name.empty()) { const std::map::const_iterator& recA{eventActionMap_.find(name)}; - // Call overrided action if derrived class has implemented it + // Call overridden action if derived class has implemented it if (recA != eventActionMap_.cend() && name != recA->second) this->doAction(recA->second); } } @@ -114,7 +129,7 @@ void AModule::setCursor(Gdk::CursorType const& c) { } else { // window may not be accessible yet, in this case, // schedule another call for setting the cursor in 1 sec - Glib::signal_timeout().connect_seconds( + cursor_timeout_conn_ = Glib::signal_timeout().connect_seconds( [this, c]() { setCursor(c); return false; @@ -166,12 +181,16 @@ bool AModule::handleUserEvent(GdkEventButton* const& e) { } // Check that a menu has been configured - if (config_["menu"].isString()) { + if (rec != eventMap_.cend() && config_["menu"].isString()) { // Check if the event is the one specified for the "menu" option - if (rec->second == config_["menu"].asString()) { + if (rec->second == config_["menu"].asString() && menu_ != nullptr) { // Popup the menu gtk_widget_show_all(GTK_WIDGET(menu_)); gtk_menu_popup_at_pointer(GTK_MENU(menu_), reinterpret_cast(e)); + // Manually reset prelight to make sure the module doesn't stay in a hover state + if (auto* module = event_box_.get_child(); module != nullptr) { + module->unset_state_flags(Gtk::StateFlags::STATE_FLAG_PRELIGHT); + } } } // Second call user scripts @@ -182,7 +201,7 @@ bool AModule::handleUserEvent(GdkEventButton* const& e) { format.clear(); } if (!format.empty()) { - pid_.push_back(util::command::forkExec(format)); + pid_children_.push_back(util::command::forkExec(format)); } dp.emit(); return true; @@ -267,7 +286,7 @@ bool AModule::handleScroll(GdkEventScroll* e) { this->AModule::doAction(eventName); // Second call user scripts if (config_[eventName].isString()) - pid_.push_back(util::command::forkExec(config_[eventName].asString())); + pid_children_.push_back(util::command::forkExec(config_[eventName].asString())); dp.emit(); return true; diff --git a/src/bar.cpp b/src/bar.cpp index b7737d36..4bf247b4 100644 --- a/src/bar.cpp +++ b/src/bar.cpp @@ -8,6 +8,8 @@ #include "client.hpp" #include "factory.hpp" #include "group.hpp" +#include "util/enum.hpp" +#include "util/kill_signal.hpp" #ifdef HAVE_SWAY #include "modules/sway/bar.hpp" @@ -170,6 +172,10 @@ waybar::Bar::Bar(struct waybar_output* w_output, const Json::Value& w_config) right_.set_spacing(spacing); } + if (config.isMember("height") && !config["height"].isUInt()) { + spdlog::warn("Invalid type for 'height', expected unsigned integer"); + } + height_ = config["height"].isUInt() ? config["height"].asUInt() : 0; width_ = config["width"].isUInt() ? config["width"].asUInt() : 0; @@ -227,7 +233,8 @@ waybar::Bar::Bar(struct waybar_output* w_output, const Json::Value& w_config) gtk_layer_init_for_window(gtk_window); gtk_layer_set_keyboard_mode(gtk_window, GTK_LAYER_SHELL_KEYBOARD_MODE_NONE); gtk_layer_set_monitor(gtk_window, output->monitor->gobj()); - gtk_layer_set_namespace(gtk_window, "waybar"); + gtk_layer_set_namespace(gtk_window, + config["name"].isString() ? config["name"].asCString() : "waybar"); gtk_layer_set_margin(gtk_window, GTK_LAYER_SHELL_EDGE_LEFT, margins_.left); gtk_layer_set_margin(gtk_window, GTK_LAYER_SHELL_EDGE_RIGHT, margins_.right); @@ -260,6 +267,16 @@ waybar::Bar::Bar(struct waybar_output* w_output, const Json::Value& w_config) window.signal_map_event().connect_notify(sigc::mem_fun(*this, &Bar::onMap)); + window.signal_unmap().connect([this]() { + spdlog::debug("Output {} unmapped (DPMS off), suspending modules", output->name); + toggleSuspend(true); + }); + + window.signal_map().connect([this]() { + spdlog::debug("Output {} mapped (DPMS on), resuming modules", output->name); + toggleSuspend(false); + }); + #if HAVE_SWAY if (auto ipc = config["ipc"]; ipc.isBool() && ipc.asBool()) { bar_id = Client::inst()->bar_id; @@ -277,9 +294,48 @@ waybar::Bar::Bar(struct waybar_output* w_output, const Json::Value& w_config) } #endif + waybar::util::EnumParser m_signalActionEnumParser; + const auto& configSigusr1 = config["on-sigusr1"]; + if (configSigusr1.isString()) { + auto strSigusr1 = configSigusr1.asString(); + try { + onSigusr1 = + m_signalActionEnumParser.parseStringToEnum(strSigusr1, util::userKillSignalActions); + } catch (const std::invalid_argument& e) { + onSigusr1 = util::SIGNALACTION_DEFAULT_SIGUSR1; + spdlog::warn( + "Invalid string representation for on-sigusr1. Falling back to default mode (toggle)."); + } + } + const auto& configSigusr2 = config["on-sigusr2"]; + if (configSigusr2.isString()) { + auto strSigusr2 = configSigusr2.asString(); + try { + onSigusr2 = + m_signalActionEnumParser.parseStringToEnum(strSigusr2, util::userKillSignalActions); + } catch (const std::invalid_argument& e) { + onSigusr2 = util::SIGNALACTION_DEFAULT_SIGUSR2; + spdlog::warn( + "Invalid string representation for on-sigusr2. Falling back to default mode (reload)."); + } + } + setupWidgets(); window.show_all(); + /* + * If gtk-layer-shell's synchronous wait for the initial configure timed out, show_all() can + * return with a configured but not-yet-presented surface. Kick GTK/layer-shell once control has + * returned to the main loop, when any late initial configure has been dispatched and widgets have + * had a chance to allocate/draw. + */ + Glib::signal_idle().connect(sigc::track_obj([this] { + window.queue_resize(); + window.queue_draw(); + forceLayerCommit(); + return false; + }, *this)); + if (spdlog::should_log(spdlog::level::debug)) { // Unfortunately, this function isn't in the C++ bindings, so we have to call the C version. char* gtk_tree = gtk_style_context_to_string( @@ -345,7 +401,14 @@ void waybar::Bar::setMode(const struct bar_mode& mode) { * gtk-layer-shell schedules a commit on the next frame event in GTK, but this could fail in * certain scenarios, such as fully occluded bar. */ - gtk_layer_try_force_commit(gtk_window); + forceLayerCommit(); +} + +void waybar::Bar::forceLayerCommit() { + auto* gtk_window = window.gobj(); + if (gtk_window != nullptr && gtk_widget_get_realized(GTK_WIDGET(gtk_window))) { + gtk_layer_try_force_commit(gtk_window); + } wl_display_flush(Client::inst()->wl_display); } @@ -405,7 +468,18 @@ void waybar::Bar::onMap(GdkEventAny* /*unused*/) { /* * Obtain a pointer to the custom layer surface for modules that require it (idle_inhibitor). */ - auto* gdk_window = window.get_window()->gobj(); + auto gdk_window_ref = window.get_window(); + if (!gdk_window_ref) { + spdlog::warn("Failed to get GDK window during onMap, deferring surface initialization"); + return; + } + + auto* gdk_window = gdk_window_ref->gobj(); + if (!gdk_window) { + spdlog::warn("GDK window object is null during onMap, deferring surface initialization"); + return; + } + surface = gdk_wayland_window_get_wl_surface(gdk_window); configureGlobalOffset(gdk_window_get_width(gdk_window), gdk_window_get_height(gdk_window)); @@ -422,6 +496,8 @@ void waybar::Bar::setVisible(bool value) { } void waybar::Bar::toggle() { setVisible(!visible); } +void waybar::Bar::show() { setVisible(true); } +void waybar::Bar::hide() { setVisible(false); } // Converting string to button code rn as to avoid doing it later void waybar::Bar::setupAltFormatKeyForModule(const std::string& module_name) { @@ -479,6 +555,9 @@ void waybar::Bar::handleSignal(int signal) { } } +waybar::util::KillSignalAction waybar::Bar::getOnSigusr1Action() { return this->onSigusr1; } +waybar::util::KillSignalAction waybar::Bar::getOnSigusr2Action() { return this->onSigusr2; } + void waybar::Bar::getModules(const Factory& factory, const std::string& pos, waybar::Group* group = nullptr) { auto module_list = group != nullptr ? config[pos]["modules"] : config[pos]; @@ -496,9 +575,15 @@ void waybar::Bar::getModules(const Factory& factory, const std::string& pos, auto vertical = (group != nullptr ? group->getBox().get_orientation() : box_.get_orientation()) == Gtk::ORIENTATION_VERTICAL; - auto* group_module = new waybar::Group(id_name, class_name, config[ref], vertical); - getModules(factory, ref, group_module); - module = group_module; + const Json::Value& group_config = config[ref]; + if (group_config["modules"].isNull()) { + spdlog::warn("Group definition '{}' has not been found, group will be hidden", ref); + } + auto group_module = + std::make_unique(id_name, class_name, group_config, vertical); + + getModules(factory, ref, group_module.get()); + module = group_module.release(); } else { module = factory.makeModule(ref, pos); } @@ -545,7 +630,6 @@ auto waybar::Bar::setupWidgets() -> void { if (config["fixed-center"].isBool() ? config["fixed-center"].asBool() : true) { box_.set_center_widget(center_); } else { - spdlog::error("No fixed center_"); box_.pack_start(center_, true, expand_center); } } @@ -569,13 +653,13 @@ auto waybar::Bar::setupWidgets() -> void { if (!no_center) { for (auto const& module : modules_center_) { - center_.pack_start(*module, false, false); + center_.pack_start(*module, module->expandEnabled(), module->expandEnabled()); } } std::reverse(modules_right_.begin(), modules_right_.end()); for (auto const& module : modules_right_) { - right_.pack_end(*module, false, false); + right_.pack_end(*module, module->expandEnabled(), module->expandEnabled()); } } @@ -602,6 +686,17 @@ void waybar::Bar::onConfigure(GdkEventConfigure* ev) { configureGlobalOffset(ev->width, ev->height); spdlog::info(BAR_SIZE_MSG, ev->width, ev->height, output->name); + + /* + * gtk-layer-shell waits for the compositor's initial configure while realizing the window. On a + * busy compositor (common during session startup) that wait can time out even though the initial + * configure arrives shortly afterwards. In that case GTK may not schedule the frame commit that + * presents the first layer-surface buffer, leaving an otherwise configured bar invisible. Force a + * commit after every configure so late initial configures, and later compositor-driven resizes, + * always result in a submitted surface state. + */ + window.queue_draw(); + forceLayerCommit(); } void waybar::Bar::configureGlobalOffset(int width, int height) { @@ -646,3 +741,22 @@ void waybar::Bar::configureGlobalOffset(int width, int height) { void waybar::Bar::onOutputGeometryChanged() { configureGlobalOffset(window.get_width(), window.get_height()); } + +void waybar::Bar::toggleSuspend(bool suspend) { + auto process_modules = [suspend](Gtk::Box& module_box) { + for (auto* widget : module_box.get_children()) { + auto* module = dynamic_cast(widget); + if (module && module->shouldSuspend()) { + if (suspend) { + module->suspend(); + } else { + module->resume(); + } + } + } + }; + + process_modules(left_); + process_modules(center_); + process_modules(right_); +} diff --git a/src/client.cpp b/src/client.cpp index 63a9276a..14d2cf6f 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -10,61 +10,74 @@ #include "idle-inhibit-unstable-v1-client-protocol.h" #include "util/clara.hpp" #include "util/format.hpp" +#include "util/hex_checker.hpp" -waybar::Client *waybar::Client::inst() { - static auto *c = new Client(); +waybar::Client* waybar::Client::inst() { + static auto* c = new Client(); return c; } -void waybar::Client::handleGlobal(void *data, struct wl_registry *registry, uint32_t name, - const char *interface, uint32_t version) { - auto *client = static_cast(data); +void waybar::Client::handleGlobal(void* data, struct wl_registry* registry, uint32_t name, + const char* interface, uint32_t version) { + auto* client = static_cast(data); + if (strcmp(interface, zxdg_output_manager_v1_interface.name) == 0 && version >= ZXDG_OUTPUT_V1_NAME_SINCE_VERSION) { - client->xdg_output_manager = static_cast(wl_registry_bind( + if (client->xdg_output_manager != nullptr) { + zxdg_output_manager_v1_destroy(client->xdg_output_manager); + client->xdg_output_manager = nullptr; + } + + client->xdg_output_manager = static_cast(wl_registry_bind( registry, name, &zxdg_output_manager_v1_interface, ZXDG_OUTPUT_V1_NAME_SINCE_VERSION)); + } else if (strcmp(interface, zwp_idle_inhibit_manager_v1_interface.name) == 0) { - client->idle_inhibit_manager = static_cast( + if (client->idle_inhibit_manager != nullptr) { + zwp_idle_inhibit_manager_v1_destroy(client->idle_inhibit_manager); + client->idle_inhibit_manager = nullptr; + } + + client->idle_inhibit_manager = static_cast( wl_registry_bind(registry, name, &zwp_idle_inhibit_manager_v1_interface, 1)); } } -void waybar::Client::handleGlobalRemove(void *data, struct wl_registry * /*registry*/, +void waybar::Client::handleGlobalRemove(void* data, struct wl_registry* /*registry*/, uint32_t name) { // Nothing here } -void waybar::Client::handleOutput(struct waybar_output &output) { +void waybar::Client::handleOutput(struct waybar_output& output) { static const struct zxdg_output_v1_listener xdgOutputListener = { - .logical_position = [](void *, struct zxdg_output_v1 *, int32_t, int32_t) {}, - .logical_size = [](void *, struct zxdg_output_v1 *, int32_t, int32_t) {}, + .logical_position = [](void*, struct zxdg_output_v1*, int32_t, int32_t) {}, + .logical_size = [](void*, struct zxdg_output_v1*, int32_t, int32_t) {}, .done = &handleOutputDone, .name = &handleOutputName, .description = &handleOutputDescription, }; // owned by output->monitor; no need to destroy - auto *wl_output = gdk_wayland_monitor_get_wl_output(output.monitor->gobj()); + auto* wl_output = gdk_wayland_monitor_get_wl_output(output.monitor->gobj()); output.xdg_output.reset(zxdg_output_manager_v1_get_xdg_output(xdg_output_manager, wl_output)); zxdg_output_v1_add_listener(output.xdg_output.get(), &xdgOutputListener, &output); } -struct waybar::waybar_output &waybar::Client::getOutput(void *addr) { +struct waybar::waybar_output& waybar::Client::getOutput(void* addr) { auto it = std::find_if(outputs_.begin(), outputs_.end(), - [&addr](const auto &output) { return &output == addr; }); + [&addr](const auto& output) { return &output == addr; }); if (it == outputs_.end()) { throw std::runtime_error("Unable to find valid output"); } return *it; } -std::vector waybar::Client::getOutputConfigs(struct waybar_output &output) { +std::vector waybar::Client::getOutputConfigs(struct waybar_output& output) { return config.getOutputConfigs(output.name, output.identifier); } -void waybar::Client::handleOutputDone(void *data, struct zxdg_output_v1 * /*xdg_output*/) { - auto *client = waybar::Client::inst(); +void waybar::Client::handleOutputDone(void* data, struct zxdg_output_v1* /*xdg_output*/) { + auto* client = waybar::Client::inst(); try { - auto &output = client->getOutput(data); + auto& output = client->getOutput(data); /** * Multiple .done events may arrive in batch. In this case libwayland would queue * xdg_output.destroy and dispatch all pending events, triggering this callback several times @@ -78,46 +91,68 @@ void waybar::Client::handleOutputDone(void *data, struct zxdg_output_v1 * /*xdg_ output.xdg_output.reset(); spdlog::debug("Output detection done: {} ({})", output.name, output.identifier); - auto configs = client->getOutputConfigs(output); - if (!configs.empty()) { - for (const auto &config : configs) { - client->bars.emplace_back(std::make_unique(&output, config)); - } + client->pending_outputs_.push_back(&output); + + if (!client->bars_scheduled_) { + client->bars_scheduled_ = true; + + Glib::signal_idle().connect_once([client]() { + client->createBarsBatch(); + }, Glib::PRIORITY_HIGH_IDLE); } } - } catch (const std::exception &e) { - std::cerr << e.what() << '\n'; + } catch (const std::exception& e) { + spdlog::warn("caught exception in zxdg_output_v1_listener::done: {}", e.what()); } } -void waybar::Client::handleOutputName(void *data, struct zxdg_output_v1 * /*xdg_output*/, - const char *name) { - auto *client = waybar::Client::inst(); +void waybar::Client::createBarsBatch() { + pending_outputs_.remove_if([this](auto* output) { return std::none_of(outputs_.begin(), outputs_.end(), [&output](const auto& o) { return &o == output; }); }); + for (auto* output : pending_outputs_) { + try { + auto configs = getOutputConfigs(*output); + if (!configs.empty()) { + for (const auto& config : configs) { + bars.emplace_back(std::make_unique(output, config)); + } + } + } catch (const std::exception& e) { + spdlog::warn("Error creating bar: {}", e.what()); + } + } + + pending_outputs_.clear(); + bars_scheduled_ = false; +} + +void waybar::Client::handleOutputName(void* data, struct zxdg_output_v1* /*xdg_output*/, + const char* name) { + auto* client = waybar::Client::inst(); try { - auto &output = client->getOutput(data); + auto& output = client->getOutput(data); output.name = name; - } catch (const std::exception &e) { - std::cerr << e.what() << '\n'; + } catch (const std::exception& e) { + spdlog::warn("caught exception in zxdg_output_v1_listener::name: {}", e.what()); } } -void waybar::Client::handleOutputDescription(void *data, struct zxdg_output_v1 * /*xdg_output*/, - const char *description) { - auto *client = waybar::Client::inst(); +void waybar::Client::handleOutputDescription(void* data, struct zxdg_output_v1* /*xdg_output*/, + const char* description) { + auto* client = waybar::Client::inst(); try { - auto &output = client->getOutput(data); - const char *open_paren = strrchr(description, '('); + auto& output = client->getOutput(data); // Description format: "identifier (name)" - size_t identifier_length = open_paren - description; - output.identifier = std::string(description, identifier_length - 1); - } catch (const std::exception &e) { - std::cerr << e.what() << '\n'; + auto s = std::string(description); + auto pos = s.find(" ("); + output.identifier = pos != std::string::npos ? s.substr(0, pos) : s; + } catch (const std::exception& e) { + spdlog::warn("caught exception in zxdg_output_v1_listener::description: {}", e.what()); } } void waybar::Client::handleMonitorAdded(Glib::RefPtr monitor) { - auto &output = outputs_.emplace_back(); + auto& output = outputs_.emplace_back(); output.monitor = std::move(monitor); handleOutput(output); } @@ -146,20 +181,24 @@ void waybar::Client::handleDeferredMonitorRemoval(Glib::RefPtr mon ++it; } } - outputs_.remove_if([&monitor](const auto &output) { return output.monitor == monitor; }); + outputs_.remove_if([&monitor](const auto& output) { return output.monitor == monitor; }); } -const std::string waybar::Client::getStyle(const std::string &style, +const std::string waybar::Client::getStyle(const std::string& style, std::optional appearance = std::nullopt) { + auto gtk_settings = Gtk::Settings::get_default(); std::optional css_file; + if (style.empty()) { std::vector search_files; switch (appearance.value_or(portal->getAppearance())) { case waybar::Appearance::LIGHT: search_files.emplace_back("style-light.css"); + gtk_settings->property_gtk_application_prefer_dark_theme() = false; break; case waybar::Appearance::DARK: search_files.emplace_back("style-dark.css"); + gtk_settings->property_gtk_application_prefer_dark_theme() = true; break; case waybar::Appearance::UNKNOWN: break; @@ -169,24 +208,38 @@ const std::string waybar::Client::getStyle(const std::string &style, } else { css_file = style; } + if (!css_file) { throw std::runtime_error("Missing required resource files"); } + spdlog::info("Using CSS file {}", css_file.value()); return css_file.value(); }; -auto waybar::Client::setupCss(const std::string &css_file) -> void { - css_provider_ = Gtk::CssProvider::create(); - style_context_ = Gtk::StyleContext::create(); - - // Load our css file, wherever that may be hiding - if (!css_provider_->load_from_path(css_file)) { - throw std::runtime_error("Can't open style file"); +auto waybar::Client::setupCss(const std::string& css_file) -> void { + auto screen = Gdk::Screen::get_default(); + if (!screen) { + throw std::runtime_error("No default screen"); } - // there's always only one screen - style_context_->add_provider_for_screen(Gdk::Screen::get_default(), css_provider_, - GTK_STYLE_PROVIDER_PRIORITY_USER); + + if (css_provider_) { + Gtk::StyleContext::remove_provider_for_screen(screen, css_provider_); + css_provider_.reset(); + } + + css_provider_ = Gtk::CssProvider::create(); + auto [modified_css, was_transformed] = transform_8bit_to_hex(css_file); + if (was_transformed) { + css_provider_->load_from_data(modified_css); + } else { + if (!css_provider_->load_from_path(css_file)) { + css_provider_.reset(); + throw std::runtime_error("Can't open style file"); + } + } + Gtk::StyleContext::add_provider_for_screen(screen, css_provider_, + GTK_STYLE_PROVIDER_PRIORITY_USER); } void waybar::Client::bindInterfaces() { @@ -205,17 +258,26 @@ void waybar::Client::bindInterfaces() { if (xdg_output_manager == nullptr) { throw std::runtime_error("Failed to acquire required resources."); } + + // Disconnect previous signal handlers to prevent duplicate handlers on reload + monitor_added_connection_.disconnect(); + monitor_removed_connection_.disconnect(); + + // Clear stale outputs from previous run + outputs_.clear(); + // add existing outputs and subscribe to updates for (auto i = 0; i < gdk_display->get_n_monitors(); ++i) { auto monitor = gdk_display->get_monitor(i); handleMonitorAdded(monitor); } - gdk_display->signal_monitor_added().connect(sigc::mem_fun(*this, &Client::handleMonitorAdded)); - gdk_display->signal_monitor_removed().connect( + monitor_added_connection_ = gdk_display->signal_monitor_added().connect( + sigc::mem_fun(*this, &Client::handleMonitorAdded)); + monitor_removed_connection_ = gdk_display->signal_monitor_removed().connect( sigc::mem_fun(*this, &Client::handleMonitorRemoved)); } -int waybar::Client::main(int argc, char *argv[]) { +int waybar::Client::main(int argc, char* argv[]) { bool show_help = false; bool show_version = false; std::string config_opt; @@ -266,9 +328,10 @@ int waybar::Client::main(int argc, char *argv[]) { } m_cssFile = getStyle(style_opt); setupCss(m_cssFile); - m_cssReloadHelper = std::make_unique(m_cssFile, [&]() { setupCss(m_cssFile); }); + m_cssReloadHelper = std::make_unique(m_cssFile, [&](const std::string& css_file) { setupCss(css_file); }); portal->signal_appearance_changed().connect([&](waybar::Appearance appearance) { auto css_file = getStyle(style_opt, appearance); + m_cssReloadHelper->changeCssFile(css_file); setupCss(css_file); }); @@ -276,7 +339,7 @@ int waybar::Client::main(int argc, char *argv[]) { if (m_config.isObject() && m_config["reload_style_on_change"].asBool()) { m_cssReloadHelper->monitorChanges(); } else if (m_config.isArray()) { - for (const auto &conf : m_config) { + for (const auto& conf : m_config) { if (conf["reload_style_on_change"].asBool()) { m_cssReloadHelper->monitorChanges(); break; diff --git a/src/config.cpp b/src/config.cpp index 7096ba89..266342ae 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -2,7 +2,11 @@ #include #include +#ifndef __OpenBSD__ #include +#else +#include +#endif #include #include @@ -19,10 +23,10 @@ const std::vector Config::CONFIG_DIRS = { "/etc/xdg/waybar/", SYSCONFDIR "/xdg/waybar/", "./resources/", }; -const char *Config::CONFIG_PATH_ENV = "WAYBAR_CONFIG_DIR"; +const char* Config::CONFIG_PATH_ENV = "WAYBAR_CONFIG_DIR"; -std::vector Config::tryExpandPath(const std::string &base, - const std::string &filename) { +std::vector Config::tryExpandPath(const std::string& base, + const std::string& filename) { fs::path path; if (!filename.empty()) { @@ -34,6 +38,7 @@ std::vector Config::tryExpandPath(const std::string &base, spdlog::debug("Try expanding: {}", path.string()); std::vector results; +#ifndef __OpenBSD__ wordexp_t p; if (wordexp(path.c_str(), &p, 0) == 0) { for (size_t i = 0; i < p.we_wordc; i++) { @@ -44,22 +49,34 @@ std::vector Config::tryExpandPath(const std::string &base, } wordfree(&p); } +#else + glob_t p; + if (glob(path.c_str(), 0, NULL, &p) == 0) { + for (size_t i = 0; i < p.gl_pathc; i++) { + if (access(p.gl_pathv[i], F_OK) == 0) { + results.emplace_back(p.gl_pathv[i]); + spdlog::debug("Found config file: {}", p.gl_pathv[i]); + } + } + globfree(&p); + } +#endif return results; } -std::optional Config::findConfigPath(const std::vector &names, - const std::vector &dirs) { - if (const char *dir = std::getenv(Config::CONFIG_PATH_ENV)) { - for (const auto &name : names) { +std::optional Config::findConfigPath(const std::vector& names, + const std::vector& dirs) { + if (const char* dir = std::getenv(Config::CONFIG_PATH_ENV)) { + for (const auto& name : names) { if (auto res = tryExpandPath(dir, name); !res.empty()) { return res.front(); } } } - for (const auto &dir : dirs) { - for (const auto &name : names) { + for (const auto& dir : dirs) { + for (const auto& name : names) { if (auto res = tryExpandPath(dir, name); !res.empty()) { return res.front(); } @@ -68,7 +85,7 @@ std::optional Config::findConfigPath(const std::vector return std::nullopt; } -void Config::setupConfig(Json::Value &dst, const std::string &config_file, int depth) { +void Config::setupConfig(Json::Value& dst, const std::string& config_file, int depth) { if (depth > 100) { throw std::runtime_error("Aborting due to likely recursive include in config files"); } @@ -80,7 +97,7 @@ void Config::setupConfig(Json::Value &dst, const std::string &config_file, int d util::JsonParser parser; Json::Value tmp_config = parser.parse(str); if (tmp_config.isArray()) { - for (auto &config_part : tmp_config) { + for (auto& config_part : tmp_config) { resolveConfigIncludes(config_part, depth); } } else { @@ -89,29 +106,59 @@ void Config::setupConfig(Json::Value &dst, const std::string &config_file, int d mergeConfig(dst, tmp_config); } -void Config::resolveConfigIncludes(Json::Value &config, int depth) { +std::vector Config::findIncludePath(const std::string& name, + const std::vector& dirs) { + auto match1 = tryExpandPath(name, ""); + if (!match1.empty()) { + return match1; + } + if (const char* dir = std::getenv(Config::CONFIG_PATH_ENV)) { + if (auto res = tryExpandPath(dir, name); !res.empty()) { + return res; + } + } + for (const auto& dir : dirs) { + if (auto res = tryExpandPath(dir, name); !res.empty()) { + return res; + } + } + + return {}; +} + +void Config::resolveConfigIncludes(Json::Value& config, int depth) { Json::Value includes = config["include"]; if (includes.isArray()) { - for (const auto &include : includes) { + for (const auto& include : includes) { spdlog::info("Including resource file: {}", include.asString()); - for (const auto &match : tryExpandPath(include.asString(), "")) { - setupConfig(config, match, depth + 1); + auto matches = findIncludePath(include.asString()); + if (!matches.empty()) { + for (const auto& match : matches) { + setupConfig(config, match, depth + 1); + } + } else { + spdlog::warn("Unable to find resource file: {}", include.asString()); } } } else if (includes.isString()) { spdlog::info("Including resource file: {}", includes.asString()); - for (const auto &match : tryExpandPath(includes.asString(), "")) { - setupConfig(config, match, depth + 1); + auto matches = findIncludePath(includes.asString()); + if (!matches.empty()) { + for (const auto& match : matches) { + setupConfig(config, match, depth + 1); + } + } else { + spdlog::warn("Unable to find resource file: {}", includes.asString()); } } } -void Config::mergeConfig(Json::Value &a_config_, Json::Value &b_config_) { +void Config::mergeConfig(Json::Value& a_config_, Json::Value& b_config_) { if (!a_config_) { // For the first config a_config_ = b_config_; } else if (a_config_.isObject() && b_config_.isObject()) { - for (const auto &key : b_config_.getMemberNames()) { + for (const auto& key : b_config_.getMemberNames()) { // [] creates key with default value. Use `get` to avoid that. if (a_config_.get(key, Json::Value::nullSingleton()).isObject() && b_config_[key].isObject()) { @@ -127,10 +174,10 @@ void Config::mergeConfig(Json::Value &a_config_, Json::Value &b_config_) { spdlog::error("Cannot merge config, conflicting or invalid JSON types"); } } -bool isValidOutput(const Json::Value &config, const std::string &name, - const std::string &identifier) { +bool isValidOutput(const Json::Value& config, const std::string& name, + const std::string& identifier) { if (config["output"].isArray()) { - for (auto const &output_conf : config["output"]) { + for (auto const& output_conf : config["output"]) { if (output_conf.isString()) { auto config_output = output_conf.asString(); if (config_output.substr(0, 1) == "!") { @@ -164,7 +211,7 @@ bool isValidOutput(const Json::Value &config, const std::string &name, return true; } -void Config::load(const std::string &config) { +void Config::load(const std::string& config) { auto file = config.empty() ? findConfigPath({"config", "config.jsonc"}) : config; if (!file) { throw std::runtime_error("Missing required resource files"); @@ -175,11 +222,11 @@ void Config::load(const std::string &config) { setupConfig(config_, config_file_, 0); } -std::vector Config::getOutputConfigs(const std::string &name, - const std::string &identifier) { +std::vector Config::getOutputConfigs(const std::string& name, + const std::string& identifier) { std::vector configs; if (config_.isArray()) { - for (auto const &config : config_) { + for (auto const& config : config_) { if (config.isObject() && isValidOutput(config, name, identifier)) { configs.push_back(config); } diff --git a/src/factory.cpp b/src/factory.cpp index 1483397d..2fd3e3b8 100644 --- a/src/factory.cpp +++ b/src/factory.cpp @@ -17,8 +17,8 @@ #ifdef HAVE_WLR_TASKBAR #include "modules/wlr/taskbar.hpp" #endif -#ifdef HAVE_WLR_WORKSPACES -#include "modules/wlr/workspace_manager.hpp" +#ifdef HAVE_EXT_WORKSPACES +#include "modules/ext/workspace_manager.hpp" #endif #ifdef HAVE_RIVER #include "modules/river/layout.hpp" @@ -34,6 +34,7 @@ #include "modules/hyprland/language.hpp" #include "modules/hyprland/submap.hpp" #include "modules/hyprland/window.hpp" +#include "modules/hyprland/windowcount.hpp" #include "modules/hyprland/workspaces.hpp" #endif #ifdef HAVE_NIRI @@ -41,6 +42,10 @@ #include "modules/niri/window.hpp" #include "modules/niri/workspaces.hpp" #endif +#ifdef HAVE_WAYFIRE +#include "modules/wayfire/window.hpp" +#include "modules/wayfire/workspaces.hpp" +#endif #if defined(__FreeBSD__) || defined(__linux__) #include "modules/battery.hpp" #endif @@ -103,12 +108,13 @@ #ifdef HAVE_LIBWIREPLUMBER #include "modules/wireplumber.hpp" #endif -#ifdef HAVE_LIBCAVA -#include "modules/cava.hpp" -#endif #ifdef HAVE_SYSTEMD_MONITOR #include "modules/systemd_failed_units.hpp" #endif +#ifdef HAVE_LIBGPS +#include "modules/gps.hpp" +#endif +#include "modules/cava/cava_frontend.hpp" #include "modules/cffi.hpp" #include "modules/custom.hpp" #include "modules/image.hpp" @@ -170,9 +176,9 @@ waybar::AModule* waybar::Factory::makeModule(const std::string& name, return new waybar::modules::wlr::Taskbar(id, bar_, config_[name]); } #endif -#ifdef HAVE_WLR_WORKSPACES - if (ref == "wlr/workspaces") { - return new waybar::modules::wlr::WorkspaceManager(id, bar_, config_[name]); +#ifdef HAVE_EXT_WORKSPACES + if (ref == "ext/workspaces") { + return new waybar::modules::ext::WorkspaceManager(id, bar_, config_[name]); } #endif #ifdef HAVE_RIVER @@ -201,6 +207,9 @@ waybar::AModule* waybar::Factory::makeModule(const std::string& name, if (ref == "hyprland/window") { return new waybar::modules::hyprland::Window(id, bar_, config_[name]); } + if (ref == "hyprland/windowcount") { + return new waybar::modules::hyprland::WindowCount(id, bar_, config_[name]); + } if (ref == "hyprland/language") { return new waybar::modules::hyprland::Language(id, bar_, config_[name]); } @@ -221,6 +230,14 @@ waybar::AModule* waybar::Factory::makeModule(const std::string& name, if (ref == "niri/workspaces") { return new waybar::modules::niri::Workspaces(id, bar_, config_[name]); } +#endif +#ifdef HAVE_WAYFIRE + if (ref == "wayfire/window") { + return new waybar::modules::wayfire::Window(id, bar_, config_[name]); + } + if (ref == "wayfire/workspaces") { + return new waybar::modules::wayfire::Workspaces(id, bar_, config_[name]); + } #endif if (ref == "idle_inhibitor") { return new waybar::modules::IdleInhibitor(id, bar_, config_[name]); @@ -322,15 +339,18 @@ waybar::AModule* waybar::Factory::makeModule(const std::string& name, return new waybar::modules::Wireplumber(id, config_[name]); } #endif -#ifdef HAVE_LIBCAVA if (ref == "cava") { - return new waybar::modules::Cava(id, config_[name]); + return waybar::modules::cava::getModule(id, config_[name]); } -#endif #ifdef HAVE_SYSTEMD_MONITOR if (ref == "systemd-failed-units") { return new waybar::modules::SystemdFailedUnits(id, config_[name]); } +#endif +#ifdef HAVE_LIBGPS + if (ref == "gps") { + return new waybar::modules::Gps(id, config_[name]); + } #endif if (ref == "temperature") { return new waybar::modules::Temperature(id, config_[name]); diff --git a/src/group.cpp b/src/group.cpp index 50841efd..acd7bd42 100644 --- a/src/group.cpp +++ b/src/group.cpp @@ -26,7 +26,7 @@ Gtk::RevealerTransitionType getPreferredTransitionType(bool is_vertical) { Group::Group(const std::string& name, const std::string& id, const Json::Value& config, bool vertical) - : AModule(config, name, id, true, true), + : AModule(config, name, id, true, false), box{vertical ? Gtk::ORIENTATION_VERTICAL : Gtk::ORIENTATION_HORIZONTAL, 0}, revealer_box{vertical ? Gtk::ORIENTATION_VERTICAL : Gtk::ORIENTATION_HORIZONTAL, 0} { box.set_name(name_); @@ -64,11 +64,19 @@ Group::Group(const std::string& name, const std::string& id, const Json::Value& : true); click_to_reveal = drawer_config["click-to-reveal"].asBool(); + const bool start_expanded = + (drawer_config["start-expanded"].isBool() ? drawer_config["start-expanded"].asBool() + : false); + auto transition_type = getPreferredTransitionType(vertical); revealer.set_transition_type(transition_type); revealer.set_transition_duration(transition_duration); - revealer.set_reveal_child(false); + revealer.set_reveal_child(start_expanded); + + if (start_expanded) { + box.set_state_flags(Gtk::StateFlags::STATE_FLAG_PRELIGHT); + } revealer.get_style_context()->add_class("drawer"); @@ -124,6 +132,11 @@ auto Group::update() -> void { // noop } +bool Group::handleScroll(GdkEventScroll* e) { + // no scroll. + return true; +} + Gtk::Box& Group::getBox() { return is_drawer ? (is_first_widget ? box : revealer_box) : box; } void Group::addWidget(Gtk::Widget& widget) { diff --git a/src/main.cpp b/src/main.cpp index 045b2cd4..0866a9b7 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -6,67 +7,158 @@ #include #include +#include "bar.hpp" #include "client.hpp" +#include "util/SafeSignal.hpp" std::mutex reap_mtx; std::list reap; -volatile bool reload; -void* signalThread(void* args) { - int err; - int signum; - sigset_t mask; - sigemptyset(&mask); - sigaddset(&mask, SIGCHLD); +static int signal_pipe_write_fd; + +// Write a single signal to `signal_pipe_write_fd`. +// This function is set as a signal handler, so it must be async-signal-safe. +static void writeSignalToPipe(int signum) { + ssize_t amt = write(signal_pipe_write_fd, &signum, sizeof(int)); + + // There's not much we can safely do inside of a signal handler. + // Let's just ignore any errors. + (void)amt; +} + +// This initializes `signal_pipe_write_fd`, and sets up signal handlers. +// +// This function will run forever, emitting every `SIGUSR1`, `SIGUSR2`, +// `SIGINT`, `SIGCHLD`, and `SIGRTMIN + 1`...`SIGRTMAX` signal received +// to `signal_handler`. +static void catchSignals(waybar::SafeSignal& signal_handler) { + int fd[2]; + if (pipe(fd) != 0) { + spdlog::error("Failed to create signal pipe: {}", strerror(errno)); + return; + } + + int signal_pipe_read_fd = fd[0]; + signal_pipe_write_fd = fd[1]; + + // This pipe should be able to buffer ~thousands of signals. If it fills up, + // we'll drop signals instead of blocking. + + // We can't allow the write end to block because we'll be writing to it in a + // signal handler, which could interrupt the loop that's reading from it and + // deadlock. + + fcntl(signal_pipe_write_fd, F_SETFL, O_NONBLOCK); + + std::signal(SIGUSR1, writeSignalToPipe); + std::signal(SIGUSR2, writeSignalToPipe); + std::signal(SIGINT, writeSignalToPipe); + std::signal(SIGCHLD, writeSignalToPipe); + +#ifdef SIGRTMIN + for (int sig = SIGRTMIN + 1; sig <= SIGRTMAX; ++sig) { + std::signal(sig, writeSignalToPipe); + } +#endif while (true) { - err = sigwait(&mask, &signum); - if (err != 0) { - spdlog::error("sigwait failed: {}", strerror(errno)); + int signum; + ssize_t amt = read(signal_pipe_read_fd, &signum, sizeof(int)); + if (amt < 0) { + spdlog::error("read from signal pipe failed with error {}, closing thread", strerror(errno)); + break; + } + + if (amt != sizeof(int)) { continue; } - switch (signum) { - case SIGCHLD: - spdlog::debug("Received SIGCHLD in signalThread"); - if (!reap.empty()) { - reap_mtx.lock(); - for (auto it = reap.begin(); it != reap.end(); ++it) { - if (waitpid(*it, nullptr, WNOHANG) == *it) { - spdlog::debug("Reaped child with PID: {}", *it); - it = reap.erase(it); - } - } - reap_mtx.unlock(); - } - break; - default: - spdlog::debug("Received signal with number {}, but not handling", signum); - break; - } + signal_handler.emit(signum); } } -void startSignalThread() { - int err; - sigset_t mask; - sigemptyset(&mask); - sigaddset(&mask, SIGCHLD); - - // Block SIGCHLD so it can be handled by the signal thread - // Any threads created by this one (the main thread) should not - // modify their signal mask to unblock SIGCHLD - err = pthread_sigmask(SIG_BLOCK, &mask, nullptr); - if (err != 0) { - spdlog::error("pthread_sigmask failed in startSignalThread: {}", strerror(err)); - exit(1); +waybar::util::KillSignalAction getActionForBar(waybar::Bar* bar, int signal) { + switch (signal) { + case SIGUSR1: + return bar->getOnSigusr1Action(); + case SIGUSR2: + return bar->getOnSigusr2Action(); + default: + return waybar::util::KillSignalAction::NOOP; } +} - pthread_t thread_id; - err = pthread_create(&thread_id, nullptr, signalThread, nullptr); - if (err != 0) { - spdlog::error("pthread_create failed in startSignalThread: {}", strerror(err)); - exit(1); +void handleUserSignal(int signal, bool& reload) { + int i = 0; + for (auto& bar : waybar::Client::inst()->bars) { + switch (getActionForBar(bar.get(), signal)) { + case waybar::util::KillSignalAction::HIDE: + spdlog::debug("Visibility 'hide' for bar ", i); + bar->hide(); + break; + case waybar::util::KillSignalAction::SHOW: + spdlog::debug("Visibility 'show' for bar ", i); + bar->show(); + break; + case waybar::util::KillSignalAction::TOGGLE: + spdlog::debug("Visibility 'toggle' for bar ", i); + bar->toggle(); + break; + case waybar::util::KillSignalAction::RELOAD: + spdlog::info("Reloading..."); + reload = true; + waybar::Client::inst()->reset(); + return; + case waybar::util::KillSignalAction::NOOP: + break; + } + i++; + } +} + +// Must be called on the main thread. +// +// If this signal should restart or close the bar, this function will write +// `true` or `false`, respectively, into `reload`. +static void handleSignalMainThread(int signum, bool& reload) { +#ifdef SIGRTMIN + if (signum >= SIGRTMIN + 1 && signum <= SIGRTMAX) { + for (auto& bar : waybar::Client::inst()->bars) { + bar->handleSignal(signum); + } + return; + } +#endif + + switch (signum) { + case SIGUSR1: + handleUserSignal(SIGUSR1, reload); + break; + case SIGUSR2: + handleUserSignal(SIGUSR2, reload); + break; + case SIGINT: + spdlog::info("Quitting."); + reload = false; + waybar::Client::inst()->reset(); + break; + case SIGCHLD: + spdlog::debug("Received SIGCHLD in signalThread"); + { + std::lock_guard lock(reap_mtx); + for (auto it = reap.begin(); it != reap.end();) { + if (waitpid(*it, nullptr, WNOHANG) == *it) { + spdlog::debug("Reaped child with PID: {}", *it); + it = reap.erase(it); + } else { + ++it; + } + } + } + break; + default: + spdlog::debug("Received signal with number {}, but not handling", signum); + break; } } @@ -74,32 +166,16 @@ int main(int argc, char* argv[]) { try { auto* client = waybar::Client::inst(); - std::signal(SIGUSR1, [](int /*signal*/) { - for (auto& bar : waybar::Client::inst()->bars) { - bar->toggle(); - } - }); + bool reload; - std::signal(SIGUSR2, [](int /*signal*/) { - spdlog::info("Reloading..."); - reload = true; - waybar::Client::inst()->reset(); - }); + waybar::SafeSignal posix_signal_received; + posix_signal_received.connect([&](int signum) { handleSignalMainThread(signum, reload); }); - std::signal(SIGINT, [](int /*signal*/) { - spdlog::info("Quitting."); - reload = false; - waybar::Client::inst()->reset(); - }); + std::thread signal_thread([&]() { catchSignals(posix_signal_received); }); - for (int sig = SIGRTMIN + 1; sig <= SIGRTMAX; ++sig) { - std::signal(sig, [](int sig) { - for (auto& bar : waybar::Client::inst()->bars) { - bar->handleSignal(sig); - } - }); - } - startSignalThread(); + // Every `std::thread` must be joined or detached. + // This thread should run forever, so detach it. + signal_thread.detach(); auto ret = 0; do { diff --git a/src/modules/backlight.cpp b/src/modules/backlight.cpp index ff58951c..8f0d583f 100644 --- a/src/modules/backlight.cpp +++ b/src/modules/backlight.cpp @@ -13,7 +13,7 @@ #include "util/backend_common.hpp" #include "util/backlight_backend.hpp" -waybar::modules::Backlight::Backlight(const std::string &id, const Json::Value &config) +waybar::modules::Backlight::Backlight(const std::string& id, const Json::Value& config) : ALabel(config, "backlight", id, "{percent}%", 2), preferred_device_(config["device"].isString() ? config["device"].asString() : ""), backend(interval_, [this] { dp.emit(); }) { @@ -38,21 +38,31 @@ auto waybar::modules::Backlight::update() -> void { event_box_.show(); const uint8_t percent = best->get_max() == 0 ? 100 : round(best->get_actual() * 100.0f / best->get_max()); - std::string desc = fmt::format(fmt::runtime(format_), fmt::arg("percent", percent), + + // Get the state and apply state-specific format if available + auto state = getState(percent); + std::string current_format = format_; + if (!state.empty()) { + std::string state_format_name = "format-" + state; + if (config_[state_format_name].isString()) { + current_format = config_[state_format_name].asString(); + } + } + + std::string desc = fmt::format(fmt::runtime(current_format), fmt::arg("percent", percent), fmt::arg("icon", getIcon(percent))); label_.set_markup(desc); - getState(percent); if (tooltipEnabled()) { std::string tooltip_format; if (config_["tooltip-format"].isString()) { tooltip_format = config_["tooltip-format"].asString(); } if (!tooltip_format.empty()) { - label_.set_tooltip_text(fmt::format(fmt::runtime(tooltip_format), - fmt::arg("percent", percent), - fmt::arg("icon", getIcon(percent)))); + label_.set_tooltip_markup(fmt::format(fmt::runtime(tooltip_format), + fmt::arg("percent", percent), + fmt::arg("icon", getIcon(percent)))); } else { - label_.set_tooltip_text(desc); + label_.set_tooltip_markup(desc); } } } else { @@ -69,7 +79,7 @@ auto waybar::modules::Backlight::update() -> void { ALabel::update(); } -bool waybar::modules::Backlight::handleScroll(GdkEventScroll *e) { +bool waybar::modules::Backlight::handleScroll(GdkEventScroll* e) { // Check if the user has set a custom command for scrolling if (config_["on-scroll-up"].isString() || config_["on-scroll-down"].isString()) { return AModule::handleScroll(e); diff --git a/src/modules/battery.cpp b/src/modules/battery.cpp index 44481448..2581ef9a 100644 --- a/src/modules/battery.cpp +++ b/src/modules/battery.cpp @@ -1,31 +1,41 @@ #include "modules/battery.hpp" #include +#include + +#include "util/command.hpp" #if defined(__FreeBSD__) #include #endif +#include +#include #include +#include -#include waybar::modules::Battery::Battery(const std::string& id, const Bar& bar, const Json::Value& config) - : ALabel(config, "battery", id, "{capacity}%", 60), bar_(bar) { + : ALabel(config, "battery", id, "{capacity}%", 60), last_event_(""), bar_(bar) { #if defined(__linux__) battery_watch_fd_ = inotify_init1(IN_CLOEXEC); if (battery_watch_fd_ == -1) { throw std::runtime_error("Unable to listen batteries."); } - - global_watch_fd_ = inotify_init1(IN_CLOEXEC); - if (global_watch_fd_ == -1) { - throw std::runtime_error("Unable to listen batteries."); + udev_ = std::unique_ptr(udev_new()); + if (udev_ == nullptr) { + throw std::runtime_error("udev_new failed"); } - - // Watch the directory for any added or removed batteries - global_watch = inotify_add_watch(global_watch_fd_, data_dir_.c_str(), IN_CREATE | IN_DELETE); - if (global_watch < 0) { - throw std::runtime_error("Could not watch for battery plug/unplug"); + mon_ = std::unique_ptr( + udev_monitor_new_from_netlink(udev_.get(), "kernel")); + if (mon_ == nullptr) { + throw std::runtime_error("udev monitor new failed"); } + if (udev_monitor_filter_add_match_subsystem_devtype(mon_.get(), "power_supply", nullptr) < 0) { + throw std::runtime_error("udev failed to add monitor filter"); + } + udev_monitor_enable_receiving(mon_.get()); + + if (config_["weighted-average"].isBool()) weightedAverage_ = config_["weighted-average"].asBool(); #endif + spdlog::debug("battery: worker interval is {}", interval_.count()); worker(); } @@ -33,11 +43,6 @@ waybar::modules::Battery::~Battery() { #if defined(__linux__) std::lock_guard guard(battery_list_mutex_); - if (global_watch >= 0) { - inotify_rm_watch(global_watch_fd_, global_watch); - } - close(global_watch_fd_); - for (auto it = batteries_.cbegin(), next_it = it; it != batteries_.cend(); it = next_it) { ++next_it; auto watch_id = (*it).second; @@ -74,12 +79,18 @@ void waybar::modules::Battery::worker() { dp.emit(); }; thread_battery_update_ = [this] { - struct inotify_event event = {0}; - int nbytes = read(global_watch_fd_, &event, sizeof(event)); - if (nbytes != sizeof(event) || event.mask & IN_IGNORED) { + poll_fds_[0].revents = 0; + poll_fds_[0].events = POLLIN; + poll_fds_[0].fd = udev_monitor_get_fd(mon_.get()); + int ret = poll(poll_fds_.data(), poll_fds_.size(), -1); + if (ret < 0) { thread_.stop(); return; } + if ((poll_fds_[0].revents & POLLIN) != 0) { + signalfd_siginfo signal_info; + read(poll_fds_[0].fd, &signal_info, sizeof(signal_info)); + } refreshBatteries(); dp.emit(); }; @@ -106,17 +117,16 @@ void waybar::modules::Battery::refreshBatteries() { if (((bat_defined && dir_name == config_["bat"].asString()) || !bat_defined) && (fs::exists(node.path() / "capacity") || fs::exists(node.path() / "charge_now")) && fs::exists(node.path() / "uevent") && - (fs::exists(node.path() / "status") || bat_compatibility) && - fs::exists(node.path() / "type")) { + (fs::exists(node.path() / "status") || bat_compatibility)) { std::string type; - std::ifstream(node.path() / "type") >> type; - - if (!type.compare("Battery")) { + if (std::ifstream{node.path() / "type"} >> type && !type.compare("Battery")) { // Ignore non-system power supplies unless explicitly requested - if (!bat_defined && fs::exists(node.path() / "scope")) { + if (!bat_defined) { std::string scope; - std::ifstream(node.path() / "scope") >> scope; - if (g_ascii_strcasecmp(scope.data(), "device") == 0) { + // for hotplug-in device, access it is always unstable because you may remove the + // device anytime so just allow failure happen and do nothing + if (std::ifstream{node.path() / "scope"} >> scope && + g_ascii_strcasecmp(scope.data(), "device") == 0) { continue; } } @@ -128,7 +138,9 @@ void waybar::modules::Battery::refreshBatteries() { auto event_path = (node.path() / "uevent"); auto wd = inotify_add_watch(battery_watch_fd_, event_path.c_str(), IN_ACCESS); if (wd < 0) { - throw std::runtime_error("Could not watch events for " + node.path().string()); + spdlog::warn("Could not watch events for {} (device may have been removed)", + node.path().string()); + continue; } batteries_[node.path()] = wd; } @@ -141,7 +153,7 @@ void waybar::modules::Battery::refreshBatteries() { } } } catch (fs::filesystem_error& e) { - throw std::runtime_error(e.what()); + spdlog::warn("Battery directory tracking failed: {}", e.what()); } if (warnFirstTime_ && batteries_.empty()) { if (config_["bat"].isString()) { @@ -262,11 +274,11 @@ waybar::modules::Battery::getInfos() { auto bat = item.first; std::string _status; - /* Check for adapter status if battery is not available */ - if (!std::ifstream(bat / "status")) { - std::getline(std::ifstream(adapter_ / "status"), _status); - } else { - std::getline(std::ifstream(bat / "status"), _status); + { + std::ifstream f{bat / "status"}; + if (!std::getline(f, _status)) { + std::getline(std::ifstream(adapter_ / "status"), _status); + } } // Some battery will report current and charge in μA/μAh. @@ -275,64 +287,74 @@ waybar::modules::Battery::getInfos() { uint32_t current_now = 0; int32_t _current_now_int = 0; bool current_now_exists = false; - if (fs::exists(bat / "current_now")) { - current_now_exists = true; - std::ifstream(bat / "current_now") >> _current_now_int; - } else if (fs::exists(bat / "current_avg")) { - current_now_exists = true; - std::ifstream(bat / "current_avg") >> _current_now_int; + if (std::ifstream current_now_f{bat / "current_now"}) { + if (current_now_f >> _current_now_int) { + current_now_exists = true; + } + } else if (std::ifstream current_avg_f{bat / "current_avg"}) { + if (current_avg_f >> _current_now_int) { + current_now_exists = true; + } } // Documentation ABI allows a negative value when discharging, positive // value when charging. current_now = std::abs(_current_now_int); - if (fs::exists(bat / "time_to_empty_now")) { - time_to_empty_now_exists = true; - std::ifstream(bat / "time_to_empty_now") >> time_to_empty_now; + if (std::ifstream f{bat / "time_to_empty_now"}) { + if (f >> time_to_empty_now) { + time_to_empty_now_exists = true; + } } - if (fs::exists(bat / "time_to_full_now")) { - time_to_full_now_exists = true; - std::ifstream(bat / "time_to_full_now") >> time_to_full_now; + if (std::ifstream f{bat / "time_to_full_now"}) { + if (f >> time_to_full_now) { + time_to_full_now_exists = true; + } } uint32_t voltage_now = 0; bool voltage_now_exists = false; - if (fs::exists(bat / "voltage_now")) { - voltage_now_exists = true; - std::ifstream(bat / "voltage_now") >> voltage_now; - } else if (fs::exists(bat / "voltage_avg")) { - voltage_now_exists = true; - std::ifstream(bat / "voltage_avg") >> voltage_now; + if (std::ifstream voltage_now_f{bat / "voltage_now"}) { + if (voltage_now_f >> voltage_now) { + voltage_now_exists = true; + } + } else if (std::ifstream voltage_avg_f{bat / "voltage_avg"}) { + if (voltage_avg_f >> voltage_now) { + voltage_now_exists = true; + } } uint32_t charge_full = 0; bool charge_full_exists = false; - if (fs::exists(bat / "charge_full")) { - charge_full_exists = true; - std::ifstream(bat / "charge_full") >> charge_full; + if (std::ifstream f{bat / "charge_full"}) { + if (f >> charge_full) { + charge_full_exists = true; + } } uint32_t charge_full_design = 0; bool charge_full_design_exists = false; - if (fs::exists(bat / "charge_full_design")) { - charge_full_design_exists = true; - std::ifstream(bat / "charge_full_design") >> charge_full_design; + if (std::ifstream f{bat / "charge_full_design"}) { + if (f >> charge_full_design) { + charge_full_design_exists = true; + } } uint32_t charge_now = 0; bool charge_now_exists = false; - if (fs::exists(bat / "charge_now")) { - charge_now_exists = true; - std::ifstream(bat / "charge_now") >> charge_now; + if (std::ifstream f{bat / "charge_now"}) { + if (f >> charge_now) { + charge_now_exists = true; + } } uint32_t power_now = 0; int32_t _power_now_int = 0; bool power_now_exists = false; - if (fs::exists(bat / "power_now")) { - power_now_exists = true; - std::ifstream(bat / "power_now") >> _power_now_int; + if (std::ifstream f{bat / "power_now"}) { + if (f >> _power_now_int) { + power_now_exists = true; + } } // Some drivers (example: Qualcomm) exposes use a negative value when // discharging, positive value when charging. @@ -340,28 +362,31 @@ waybar::modules::Battery::getInfos() { uint32_t energy_now = 0; bool energy_now_exists = false; - if (fs::exists(bat / "energy_now")) { - energy_now_exists = true; - std::ifstream(bat / "energy_now") >> energy_now; + if (std::ifstream f{bat / "energy_now"}) { + if (f >> energy_now) { + energy_now_exists = true; + } } uint32_t energy_full = 0; bool energy_full_exists = false; - if (fs::exists(bat / "energy_full")) { - energy_full_exists = true; - std::ifstream(bat / "energy_full") >> energy_full; + if (std::ifstream f{bat / "energy_full"}) { + if (f >> energy_full) { + energy_full_exists = true; + } } uint32_t energy_full_design = 0; bool energy_full_design_exists = false; - if (fs::exists(bat / "energy_full_design")) { - energy_full_design_exists = true; - std::ifstream(bat / "energy_full_design") >> energy_full_design; + if (std::ifstream f{bat / "energy_full_design"}) { + if (f >> energy_full_design) { + energy_full_design_exists = true; + } } uint16_t cycleCount = 0; - if (fs::exists(bat / "cycle_count")) { - std::ifstream(bat / "cycle_count") >> cycleCount; + if (std::ifstream f{bat / "cycle_count"}) { + f >> cycleCount; } if (charge_full_design >= largestDesignCapacity) { largestDesignCapacity = charge_full_design; @@ -391,9 +416,10 @@ waybar::modules::Battery::getInfos() { } else if (energy_now_exists && energy_full_exists && energy_full != 0) { capacity_exists = true; capacity = 100 * (uint64_t)energy_now / (uint64_t)energy_full; - } else if (fs::exists(bat / "capacity")) { - capacity_exists = true; - std::ifstream(bat / "capacity") >> capacity; + } else if (std::ifstream f{bat / "capacity"}) { + if (f >> capacity) { + capacity_exists = true; + } } if (!voltage_now_exists) { @@ -573,17 +599,17 @@ waybar::modules::Battery::getInfos() { float calculated_capacity{0.0f}; if (total_capacity_exists) { - if (total_capacity > 0.0f) + if (total_capacity > 0.0f) { calculated_capacity = (float)total_capacity / batteries_.size(); - else if (total_energy_full_exists && total_energy_exists) { - if (total_energy_full > 0.0f) + } else if (total_energy_full_exists && total_energy_exists) { + if (total_energy_full > 0.0f) { calculated_capacity = ((float)total_energy * 100.0f / (float)total_energy_full); + } } } // Handle weighted-average - if ((config_["weighted-average"].isBool() ? config_["weighted-average"].asBool() : false) && - total_energy_exists && total_energy_full_exists) { + if (weightedAverage_ && total_energy_exists && total_energy_full_exists) { if (total_energy_full > 0.0f) calculated_capacity = ((float)total_energy * 100.0f / (float)total_energy_full); } @@ -675,20 +701,32 @@ auto waybar::modules::Battery::update() -> void { if (status == "Unknown") { status = getAdapterStatus(capacity); } - 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); }); - auto format = format_; auto state = getState(capacity, true); + bool adapter_online = false; + if (!adapter_.empty()) { + std::ifstream(adapter_ / "online") >> adapter_online; + } + if (config_["full-at-plugged"].asBool() && status == "Full" && adapter_online) { + status = "Plugged"; + } + auto status_pretty = status; + + // Transform to lowercase and replace space with dash + std::ranges::transform(status.begin(), status.end(), status.begin(), + [](char ch) { return ch == ' ' ? '-' : std::tolower(ch); }); + auto format = format_; + processEvents(state, status, capacity); setBarClass(state); auto time_remaining_formatted = formatTimeRemaining(time_remaining); if (tooltipEnabled()) { std::string tooltip_text_default; std::string tooltip_format = "{timeTo}"; if (time_remaining != 0) { - std::string time_to = std::string("Time to ") + ((time_remaining > 0) ? "empty" : "full"); - tooltip_text_default = time_to + ": " + time_remaining_formatted; + if (time_remaining > 0) { + tooltip_text_default = std::string("Empty in ") + time_remaining_formatted; + } else { + tooltip_text_default = std::string("Full in ") + time_remaining_formatted; + } } else { tooltip_text_default = status_pretty; } @@ -701,7 +739,7 @@ auto waybar::modules::Battery::update() -> void { } else if (config_["tooltip-format"].isString()) { tooltip_format = config_["tooltip-format"].asString(); } - label_.set_tooltip_text( + label_.set_tooltip_markup( fmt::format(fmt::runtime(tooltip_format), fmt::arg("timeTo", tooltip_text_default), fmt::arg("power", power), fmt::arg("capacity", capacity), fmt::arg("time", time_remaining_formatted), fmt::arg("cycles", cycles), @@ -767,3 +805,28 @@ void waybar::modules::Battery::setBarClass(std::string& state) { bar_.window.get_style_context()->add_class(new_class); } } + +void waybar::modules::Battery::processEvents(std::string& state, std::string& status, + uint8_t capacity) { + // There are no events specified, skip + auto events = config_["events"]; + if (!events.isObject() || events.empty()) { + return; + } + auto exec = [](Json::Value const& event) { + if (!event.isString()) return; + if (auto command = event.asString(); !command.empty()) { + util::command::exec(command, ""); + } + }; + std::string status_name = status == "discharging" ? "on-discharging" : "on-charging"; + std::string event_name = status_name + '-' + (state.empty() ? std::to_string(capacity) : state); + if (last_event_ != event_name) { + spdlog::debug("battery: triggering event {}", event_name); + exec(events[event_name]); + if (!last_event_.empty() && last_event_[3] != event_name[3]) { + exec(events[status_name]); + } + last_event_ = event_name; + } +} diff --git a/src/modules/bluetooth.cpp b/src/modules/bluetooth.cpp index 06475a2e..c59af3b5 100644 --- a/src/modules/bluetooth.cpp +++ b/src/modules/bluetooth.cpp @@ -111,13 +111,16 @@ waybar::modules::Bluetooth::Bluetooth(const std::string& id, const Json::Value& findConnectedDevices(cur_controller_->path, connected_devices_); } - g_signal_connect(manager_.get(), "object-added", G_CALLBACK(onObjectAdded), this); - g_signal_connect(manager_.get(), "object-removed", G_CALLBACK(onObjectRemoved), this); - g_signal_connect(manager_.get(), "interface-proxy-properties-changed", - G_CALLBACK(onInterfaceProxyPropertiesChanged), this); - g_signal_connect(manager_.get(), "interface-added", G_CALLBACK(onInterfaceAddedOrRemoved), this); - g_signal_connect(manager_.get(), "interface-removed", G_CALLBACK(onInterfaceAddedOrRemoved), - this); + if (manager_) { + g_signal_connect(manager_.get(), "object-added", G_CALLBACK(onObjectAdded), this); + g_signal_connect(manager_.get(), "object-removed", G_CALLBACK(onObjectRemoved), this); + g_signal_connect(manager_.get(), "interface-proxy-properties-changed", + G_CALLBACK(onInterfaceProxyPropertiesChanged), this); + g_signal_connect(manager_.get(), "interface-added", G_CALLBACK(onInterfaceAddedOrRemoved), + this); + g_signal_connect(manager_.get(), "interface-removed", G_CALLBACK(onInterfaceAddedOrRemoved), + this); + } #ifdef WANT_RFKILL rfkill_.on_update.connect(sigc::hide(sigc::mem_fun(*this, &Bluetooth::update))); @@ -264,7 +267,7 @@ auto waybar::modules::Bluetooth::update() -> void { device_enumerate_.erase(0, 1); } } - label_.set_tooltip_text(fmt::format( + label_.set_tooltip_markup(fmt::format( fmt::runtime(tooltip_format), fmt::arg("status", state_), fmt::arg("num_connections", connected_devices_.size()), fmt::arg("controller_address", cur_controller_ ? cur_controller_->address : "null"), @@ -446,6 +449,10 @@ auto waybar::modules::Bluetooth::getControllerProperties(GDBusObject* object, auto waybar::modules::Bluetooth::findCurController() -> std::optional { std::optional controller_info; + if (!manager_) { + return controller_info; + } + GList* objects = g_dbus_object_manager_get_objects(manager_.get()); for (GList* l = objects; l != NULL; l = l->next) { GDBusObject* object = G_DBUS_OBJECT(l->data); @@ -465,6 +472,9 @@ auto waybar::modules::Bluetooth::findCurController() -> std::optional& connected_devices) -> void { + if (!manager_) { + return; + } GList* objects = g_dbus_object_manager_get_objects(manager_.get()); for (GList* l = objects; l != NULL; l = l->next) { GDBusObject* object = G_DBUS_OBJECT(l->data); diff --git a/src/modules/cava.cpp b/src/modules/cava.cpp deleted file mode 100644 index 405a351a..00000000 --- a/src/modules/cava.cpp +++ /dev/null @@ -1,211 +0,0 @@ -#include "modules/cava.hpp" - -#include - -waybar::modules::Cava::Cava(const std::string& id, const Json::Value& config) - : ALabel(config, "cava", id, "{}", 60, false, false, false) { - // Load waybar module config - char cfgPath[PATH_MAX]; - cfgPath[0] = '\0'; - - if (config_["cava_config"].isString()) strcpy(cfgPath, config_["cava_config"].asString().data()); - // Load cava config - error_.length = 0; - - if (!load_config(cfgPath, &prm_, false, &error_)) { - spdlog::error("Error loading config. {0}", error_.message); - exit(EXIT_FAILURE); - } - - // Override cava parameters by the user config - prm_.inAtty = 0; - prm_.output = cava::output_method::OUTPUT_RAW; - strcpy(prm_.data_format, "ascii"); - strcpy(prm_.raw_target, "/dev/stdout"); - prm_.ascii_range = config_["format-icons"].size() - 1; - - prm_.bar_width = 2; - prm_.bar_spacing = 0; - prm_.bar_height = 32; - prm_.bar_width = 1; - prm_.orientation = cava::ORIENT_TOP; - prm_.xaxis = cava::xaxis_scale::NONE; - prm_.mono_opt = cava::AVERAGE; - prm_.autobars = 0; - prm_.gravity = 0; - prm_.integral = 1; - - if (config_["framerate"].isInt()) prm_.framerate = config_["framerate"].asInt(); - if (config_["autosens"].isInt()) prm_.autosens = config_["autosens"].asInt(); - if (config_["sensitivity"].isInt()) prm_.sens = config_["sensitivity"].asInt(); - if (config_["bars"].isInt()) prm_.fixedbars = config_["bars"].asInt(); - if (config_["lower_cutoff_freq"].isNumeric()) - prm_.lower_cut_off = config_["lower_cutoff_freq"].asLargestInt(); - if (config_["higher_cutoff_freq"].isNumeric()) - prm_.upper_cut_off = config_["higher_cutoff_freq"].asLargestInt(); - if (config_["sleep_timer"].isInt()) prm_.sleep_timer = config_["sleep_timer"].asInt(); - if (config_["method"].isString()) - prm_.input = cava::input_method_by_name(config_["method"].asString().c_str()); - if (config_["source"].isString()) prm_.audio_source = config_["source"].asString().data(); - if (config_["sample_rate"].isNumeric()) prm_.samplerate = config_["sample_rate"].asLargestInt(); - if (config_["sample_bits"].isInt()) prm_.samplebits = config_["sample_bits"].asInt(); - if (config_["stereo"].isBool()) prm_.stereo = config_["stereo"].asBool(); - if (config_["reverse"].isBool()) prm_.reverse = config_["reverse"].asBool(); - if (config_["bar_delimiter"].isInt()) prm_.bar_delim = config_["bar_delimiter"].asInt(); - if (config_["monstercat"].isBool()) prm_.monstercat = config_["monstercat"].asBool(); - if (config_["waves"].isBool()) prm_.waves = config_["waves"].asBool(); - if (config_["noise_reduction"].isDouble()) - prm_.noise_reduction = config_["noise_reduction"].asDouble(); - if (config_["input_delay"].isInt()) - fetch_input_delay_ = std::chrono::seconds(config_["input_delay"].asInt()); - if (config_["hide_on_silence"].isBool()) hide_on_silence_ = config_["hide_on_silence"].asBool(); - if (config_["format_silent"].isString()) format_silent_ = config_["format_silent"].asString(); - // Make cava parameters configuration - plan_ = new cava::cava_plan{}; - - audio_raw_.height = prm_.ascii_range; - audio_data_.format = -1; - audio_data_.source = new char[1 + strlen(prm_.audio_source)]; - audio_data_.source[0] = '\0'; - strcpy(audio_data_.source, prm_.audio_source); - - audio_data_.rate = 0; - audio_data_.samples_counter = 0; - audio_data_.channels = 2; - audio_data_.IEEE_FLOAT = 0; - - audio_data_.input_buffer_size = BUFFER_SIZE * audio_data_.channels; - audio_data_.cava_buffer_size = audio_data_.input_buffer_size * 8; - - audio_data_.cava_in = new double[audio_data_.cava_buffer_size]{0.0}; - - audio_data_.terminate = 0; - audio_data_.suspendFlag = false; - input_source_ = get_input(&audio_data_, &prm_); - - if (!input_source_) { - spdlog::error("cava API didn't provide input audio source method"); - exit(EXIT_FAILURE); - } - // Calculate delay for Update() thread - frame_time_milsec_ = std::chrono::milliseconds((int)(1e3 / prm_.framerate)); - - // Init cava plan, audio_raw structure - audio_raw_init(&audio_data_, &audio_raw_, &prm_, plan_); - if (!plan_) spdlog::error("cava plan is not provided"); - audio_raw_.previous_frame[0] = -1; // For first Update() call need to rePaint text message - // Read audio source trough cava API. Cava orginizes this process via infinity loop - thread_fetch_input_ = [this] { - thread_fetch_input_.sleep_for(fetch_input_delay_); - input_source_(&audio_data_); - }; - - thread_ = [this] { - dp.emit(); - thread_.sleep_for(frame_time_milsec_); - }; -} - -waybar::modules::Cava::~Cava() { - thread_fetch_input_.stop(); - thread_.stop(); - delete plan_; - plan_ = nullptr; -} - -void upThreadDelay(std::chrono::milliseconds& delay, std::chrono::seconds& delta) { - if (delta == std::chrono::seconds{0}) { - delta += std::chrono::seconds{1}; - delay += delta; - } -} - -void downThreadDelay(std::chrono::milliseconds& delay, std::chrono::seconds& delta) { - if (delta > std::chrono::seconds{0}) { - delay -= delta; - delta -= std::chrono::seconds{1}; - } -} - -auto waybar::modules::Cava::update() -> void { - if (audio_data_.suspendFlag) return; - silence_ = true; - - for (int i{0}; i < audio_data_.input_buffer_size; ++i) { - if (audio_data_.cava_in[i]) { - silence_ = false; - sleep_counter_ = 0; - break; - } - } - - if (silence_ && prm_.sleep_timer != 0) { - if (sleep_counter_ <= - (int)(std::chrono::milliseconds(prm_.sleep_timer * 1s) / frame_time_milsec_)) { - ++sleep_counter_; - silence_ = false; - } - } - - if (!silence_ || prm_.sleep_timer == 0) { - downThreadDelay(frame_time_milsec_, suspend_silence_delay_); - // Process: execute cava - pthread_mutex_lock(&audio_data_.lock); - cava::cava_execute(audio_data_.cava_in, audio_data_.samples_counter, audio_raw_.cava_out, - plan_); - if (audio_data_.samples_counter > 0) audio_data_.samples_counter = 0; - pthread_mutex_unlock(&audio_data_.lock); - - // Do transformation under raw data - audio_raw_fetch(&audio_raw_, &prm_, &rePaint_, plan_); - - if (rePaint_ == 1) { - text_.clear(); - - for (int i{0}; i < audio_raw_.number_of_bars; ++i) { - audio_raw_.previous_frame[i] = audio_raw_.bars[i]; - text_.append( - getIcon((audio_raw_.bars[i] > prm_.ascii_range) ? prm_.ascii_range : audio_raw_.bars[i], - "", prm_.ascii_range + 1)); - if (prm_.bar_delim != 0) text_.push_back(prm_.bar_delim); - } - - label_.set_markup(text_); - label_.show(); - ALabel::update(); - label_.get_style_context()->add_class("updated"); - } - - label_.get_style_context()->remove_class("silent"); - } else { - upThreadDelay(frame_time_milsec_, suspend_silence_delay_); - if (hide_on_silence_) - label_.hide(); - else if (config_["format_silent"].isString()) - label_.set_markup(format_silent_); - - label_.get_style_context()->add_class("silent"); - label_.get_style_context()->remove_class("updated"); - } -} - -auto waybar::modules::Cava::doAction(const std::string& name) -> void { - if ((actionMap_[name])) { - (this->*actionMap_[name])(); - } else - spdlog::error("Cava. Unsupported action \"{0}\"", name); -} - -// Cava actions -void waybar::modules::Cava::pause_resume() { - pthread_mutex_lock(&audio_data_.lock); - if (audio_data_.suspendFlag) { - audio_data_.suspendFlag = false; - pthread_cond_broadcast(&audio_data_.resumeCond); - downThreadDelay(frame_time_milsec_, suspend_silence_delay_); - } else { - audio_data_.suspendFlag = true; - upThreadDelay(frame_time_milsec_, suspend_silence_delay_); - } - pthread_mutex_unlock(&audio_data_.lock); -} diff --git a/src/modules/cava/cavaGLSL.cpp b/src/modules/cava/cavaGLSL.cpp new file mode 100644 index 00000000..4ab03bcd --- /dev/null +++ b/src/modules/cava/cavaGLSL.cpp @@ -0,0 +1,271 @@ +#include "modules/cava/cavaGLSL.hpp" + +#include + +#include + +waybar::modules::cava::CavaGLSL::CavaGLSL(const std::string& id, const Json::Value& config) + : AModule(config, "cavaGLSL", id, false, false), + backend_{waybar::modules::cava::CavaBackend::inst(config)} { + set_name(name_); + if (config_["hide_on_silence"].isBool()) hide_on_silence_ = config_["hide_on_silence"].asBool(); + if (!id.empty()) { + get_style_context()->add_class(id); + } + get_style_context()->add_class(MODULE_CLASS); + + set_use_es(true); + // set_auto_render(true); + signal_realize().connect(sigc::mem_fun(*this, &CavaGLSL::onRealize)); + signal_render().connect(sigc::mem_fun(*this, &CavaGLSL::onRender), false); + + // Get parameters_config struct from the backend + prm_ = *backend_->getPrm(); + + // Set widget length + int length{0}; + if (config_["min-length"].isUInt()) + length = config_["min-length"].asUInt(); + else if (config_["max-length"].isUInt()) + length = config_["max-length"].asUInt(); + else + length = prm_.sdl_width; + + set_size_request(length, prm_.sdl_height); + + // Subscribe for changes + backend_->signal_audio_raw_update().connect(sigc::mem_fun(*this, &CavaGLSL::onUpdate)); + // Subscribe for silence + backend_->signal_silence().connect(sigc::mem_fun(*this, &CavaGLSL::onSilence)); + event_box_.add(*this); +} + +auto waybar::modules::cava::CavaGLSL::onUpdate(const ::cava::audio_raw& input) -> void { + Glib::signal_idle().connect_once([this, input]() { + m_data_ = std::make_shared<::cava::audio_raw>(input); + if (silence_) { + get_style_context()->remove_class("silent"); + if (!get_style_context()->has_class("updated")) get_style_context()->add_class("updated"); + show(); + silence_ = false; + } + + queue_render(); + }); +} + +auto waybar::modules::cava::CavaGLSL::onSilence() -> void { + Glib::signal_idle().connect_once([this]() { + if (!silence_) { + if (get_style_context()->has_class("updated")) get_style_context()->remove_class("updated"); + + if (hide_on_silence_) hide(); + silence_ = true; + get_style_context()->add_class("silent"); + // Set clear color to black + glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + queue_render(); + } + }); +} + +bool waybar::modules::cava::CavaGLSL::onRender(const Glib::RefPtr& context) { + if (!m_data_) return true; + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, texture_); + glUniform1i(glGetUniformLocation(shaderProgram_, "inputTexture"), 0); + + glUniform1fv(uniform_bars_, m_data_->number_of_bars, m_data_->bars_raw); + glUniform1fv(uniform_previous_bars_, m_data_->number_of_bars, m_data_->previous_bars_raw); + glUniform1i(uniform_bars_count_, m_data_->number_of_bars); + ++frame_counter; + glUniform1f(uniform_time_, (frame_counter / backend_->getFrameTimeMilsec().count()) / 1e3); + + // glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glDrawElements(GL_TRIANGLE_FAN, 4, GL_UNSIGNED_INT, nullptr); + + glBindFramebuffer(GL_FRAMEBUFFER, fbo_); + glDrawElements(GL_TRIANGLE_FAN, 4, GL_UNSIGNED_INT, nullptr); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + + return true; +} + +void waybar::modules::cava::CavaGLSL::onRealize() { + make_current(); + initShaders(); + initGLSL(); + initSurface(); +} + +struct colors { + uint16_t R; + uint16_t G; + uint16_t B; +}; + +static void parse_color(char* color_string, struct colors* color) { + if (color_string[0] == '#') { + sscanf(++color_string, "%02hx%02hx%02hx", &color->R, &color->G, &color->B); + } +} + +void waybar::modules::cava::CavaGLSL::initGLSL() { + GLint gVertexPos2DLocation{glGetAttribLocation(shaderProgram_, "vertexPosition_modelspace")}; + if (gVertexPos2DLocation == -1) { + spdlog::error("{0}. Could not find vertex position shader variable", name_); + } + + glClearColor(0.f, 0.f, 0.f, 1.f); + + GLfloat vertexData[]{-1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f}; + GLint indexData[]{0, 1, 2, 3}; + + GLuint gVBO{0}; + glGenBuffers(1, &gVBO); + glBindBuffer(GL_ARRAY_BUFFER, gVBO); + glBufferData(GL_ARRAY_BUFFER, 2 * 4 * sizeof(GLfloat), vertexData, GL_STATIC_DRAW); + + GLuint gIBO{0}; + glGenBuffers(1, &gIBO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gIBO); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, 4 * sizeof(GLuint), indexData, GL_STATIC_DRAW); + + GLuint gVAO{0}; + glGenVertexArrays(1, &gVAO); + glBindVertexArray(gVAO); + glEnableVertexAttribArray(gVertexPos2DLocation); + + glBindBuffer(GL_ARRAY_BUFFER, gVBO); + glVertexAttribPointer(gVertexPos2DLocation, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), nullptr); + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gIBO); + + glGenFramebuffers(1, &fbo_); + glBindFramebuffer(GL_FRAMEBUFFER, fbo_); + + // Create a texture to attach the framebuffer + glGenTextures(1, &texture_); + glBindTexture(GL_TEXTURE_2D, texture_); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, prm_.sdl_width, prm_.sdl_height, 0, GL_RGBA, + GL_UNSIGNED_BYTE, nullptr); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture_, 0); + + // Check is framebuffer is complete + if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { + spdlog::error("{0}. Framebuffer not complete", name_); + } + + // Unbind the framebuffer + glBindFramebuffer(GL_FRAMEBUFFER, 0); + uniform_bars_ = glGetUniformLocation(shaderProgram_, "bars"); + uniform_previous_bars_ = glGetUniformLocation(shaderProgram_, "previous_bars"); + uniform_bars_count_ = glGetUniformLocation(shaderProgram_, "bars_count"); + uniform_time_ = glGetUniformLocation(shaderProgram_, "shader_time"); + + GLuint err{glGetError()}; + if (err != 0) { + spdlog::error("{0}. Error on initGLSL: {1}", name_, err); + } +} + +void waybar::modules::cava::CavaGLSL::initSurface() { + colors color = {0}; + GLint uniform_bg_col{glGetUniformLocation(shaderProgram_, "bg_color")}; + parse_color(prm_.bcolor, &color); + glUniform3f(uniform_bg_col, (float)color.R / 255.0, (float)color.G / 255.0, + (float)color.B / 255.0); + GLint uniform_fg_col{glGetUniformLocation(shaderProgram_, "fg_color")}; + parse_color(prm_.color, &color); + glUniform3f(uniform_fg_col, (float)color.R / 255.0, (float)color.G / 255.0, + (float)color.B / 255.0); + GLint uniform_res{glGetUniformLocation(shaderProgram_, "u_resolution")}; + glUniform3f(uniform_res, (float)prm_.sdl_width, (float)prm_.sdl_height, 0.0f); + GLint uniform_bar_width{glGetUniformLocation(shaderProgram_, "bar_width")}; + glUniform1i(uniform_bar_width, prm_.bar_width); + GLint uniform_bar_spacing{glGetUniformLocation(shaderProgram_, "bar_spacing")}; + glUniform1i(uniform_bar_spacing, prm_.bar_spacing); + GLint uniform_gradient_count{glGetUniformLocation(shaderProgram_, "gradient_count")}; + glUniform1i(uniform_gradient_count, prm_.gradient_count); + GLint uniform_gradient_colors{glGetUniformLocation(shaderProgram_, "gradient_colors")}; + GLfloat gradient_colors[8][3]; + for (int i{0}; i < prm_.gradient_count; ++i) { + parse_color(prm_.gradient_colors[i], &color); + gradient_colors[i][0] = (float)color.R / 255.0; + gradient_colors[i][1] = (float)color.G / 255.0; + gradient_colors[i][2] = (float)color.B / 255.0; + } + glUniform3fv(uniform_gradient_colors, 8, (const GLfloat*)gradient_colors); + + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glDrawElements(GL_TRIANGLE_FAN, 4, GL_UNSIGNED_INT, nullptr); +} + +void waybar::modules::cava::CavaGLSL::initShaders() { + shaderProgram_ = glCreateProgram(); + + GLuint vertexShader{loadShader(prm_.vertex_shader, GL_VERTEX_SHADER)}; + GLuint fragmentShader{loadShader(prm_.fragment_shader, GL_FRAGMENT_SHADER)}; + + glAttachShader(shaderProgram_, vertexShader); + glAttachShader(shaderProgram_, fragmentShader); + + glLinkProgram(shaderProgram_); + + glDeleteShader(vertexShader); + glDeleteShader(fragmentShader); + + // Check for linking errors + GLint success, len; + glGetProgramiv(shaderProgram_, GL_LINK_STATUS, &success); + if (!success) { + glGetProgramiv(shaderProgram_, GL_INFO_LOG_LENGTH, &len); + GLchar* infoLog{(char*)'\0'}; + glGetProgramInfoLog(shaderProgram_, len, &len, infoLog); + spdlog::error("{0}. Shader linking error: {1}", name_, infoLog); + } + + glReleaseShaderCompiler(); + glUseProgram(shaderProgram_); +} + +GLuint waybar::modules::cava::CavaGLSL::loadShader(const std::string& fileName, GLenum type) { + spdlog::debug("{0}. loadShader: {1}", name_, fileName); + + // Read shader source code from the file + std::ifstream shaderFile{fileName}; + + if (!shaderFile.is_open()) { + spdlog::error("{0}. Could not open shader file: {1}", name_, fileName); + } + + std::ostringstream buffer; + buffer << shaderFile.rdbuf(); // read file content into stringstream + std::string str{buffer.str()}; + const char* shaderSource = str.c_str(); + shaderFile.close(); + + GLuint shaderID{glCreateShader(type)}; + if (shaderID == 0) spdlog::error("{0}. Error creating shader type: {0}", type); + glShaderSource(shaderID, 1, &shaderSource, nullptr); + glCompileShader(shaderID); + + // Check for compilation errors + GLint success, len; + + glGetShaderiv(shaderID, GL_COMPILE_STATUS, &success); + + if (!success) { + glGetShaderiv(shaderID, GL_INFO_LOG_LENGTH, &len); + + GLchar* infoLog{(char*)'\0'}; + glGetShaderInfoLog(shaderID, len, nullptr, infoLog); + spdlog::error("{0}. Shader compilation error in {1}: {2}", name_, fileName, infoLog); + } + + return shaderID; +} diff --git a/src/modules/cava/cavaRaw.cpp b/src/modules/cava/cavaRaw.cpp new file mode 100644 index 00000000..2b0aca72 --- /dev/null +++ b/src/modules/cava/cavaRaw.cpp @@ -0,0 +1,60 @@ +#include "modules/cava/cavaRaw.hpp" + +#include + +waybar::modules::cava::Cava::Cava(const std::string& id, const Json::Value& config) + : ALabel(config, "cava", id, "{}", 60, false, false, false), + backend_{waybar::modules::cava::CavaBackend::inst(config)} { + if (config_["hide_on_silence"].isBool()) hide_on_silence_ = config_["hide_on_silence"].asBool(); + if (config_["format_silent"].isString()) format_silent_ = config_["format_silent"].asString(); + + ascii_range_ = backend_->getAsciiRange(); + backend_->signal_update().connect(sigc::mem_fun(*this, &Cava::onUpdate)); + backend_->signal_silence().connect(sigc::mem_fun(*this, &Cava::onSilence)); + backend_->Update(); +} + +auto waybar::modules::cava::Cava::doAction(const std::string& name) -> void { + if ((actionMap_[name])) { + (this->*actionMap_[name])(); + } else + spdlog::error("Cava. Unsupported action \"{0}\"", name); +} + +// Cava actions +void waybar::modules::cava::Cava::pause_resume() { backend_->doPauseResume(); } +auto waybar::modules::cava::Cava::onUpdate(const std::string& input) -> void { + Glib::signal_idle().connect_once([this, input]() { + if (silence_) { + silence_ = false; + label_.get_style_context()->remove_class("silent"); + if (!label_.get_style_context()->has_class("updated")) + label_.get_style_context()->add_class("updated"); + } + label_text_.clear(); + for (auto& ch : input) + label_text_.append(getIcon((ch > ascii_range_) ? ascii_range_ : ch, "", ascii_range_ + 1)); + + label_.set_markup(label_text_); + label_.show(); + ALabel::update(); + }); +} + +auto waybar::modules::cava::Cava::onSilence() -> void { + Glib::signal_idle().connect_once([this]() { + if (!silence_) { + if (label_.get_style_context()->has_class("updated")) + label_.get_style_context()->remove_class("updated"); + + if (hide_on_silence_) { + // Clear the label markup before hiding to prevent GTK from rendering a NULL Pango layout + label_.set_markup(""); + label_.hide(); + } else if (config_["format_silent"].isString()) + label_.set_markup(format_silent_); + silence_ = true; + label_.get_style_context()->add_class("silent"); + } + }); +} diff --git a/src/modules/cava/cava_backend.cpp b/src/modules/cava/cava_backend.cpp new file mode 100644 index 00000000..6eb540c9 --- /dev/null +++ b/src/modules/cava/cava_backend.cpp @@ -0,0 +1,273 @@ +#include "modules/cava/cava_backend.hpp" + +#include + +std::shared_ptr waybar::modules::cava::CavaBackend::inst( + const Json::Value& config) { + static auto* backend = new CavaBackend(config); + static std::shared_ptr backend_ptr{backend}; + return backend_ptr; +} + +waybar::modules::cava::CavaBackend::CavaBackend(const Json::Value& config) : config_(config) { + // Load waybar module config + loadConfig(); + // Read audio source trough cava API. Cava orginizes this process via infinity loop + read_thread_ = [this] { + try { + input_source_(&audio_data_); + } catch (const std::runtime_error& e) { + spdlog::warn("Cava backend. Read source error: {0}", e.what()); + } + read_thread_.sleep_for(fetch_input_delay_); + loadConfig(); + }; + // Write outcoming data. Emit signals + out_thread_ = [this] { + doUpdate(false); + out_thread_.sleep_for(frame_time_milsec_); + }; +} + +waybar::modules::cava::CavaBackend::~CavaBackend() { + out_thread_.stop(); + read_thread_.stop(); + + freeBackend(); +} + +static bool upThreadDelay(std::chrono::milliseconds& delay, std::chrono::seconds& delta) { + if (delta == std::chrono::seconds{0}) { + delta += std::chrono::seconds{1}; + delay += delta; + return true; + } + return false; +} + +static bool downThreadDelay(std::chrono::milliseconds& delay, std::chrono::seconds& delta) { + if (delta > std::chrono::seconds{0}) { + delay -= delta; + delta -= std::chrono::seconds{1}; + return true; + } + return false; +} + +bool waybar::modules::cava::CavaBackend::isSilence() { + for (int i{0}; i < audio_data_.input_buffer_size; ++i) { + if (audio_data_.cava_in[i]) { + return false; + } + } + + return true; +} + +int waybar::modules::cava::CavaBackend::getAsciiRange() { return prm_.ascii_range; } + +// Process: execute cava +void waybar::modules::cava::CavaBackend::invoke() { + pthread_mutex_lock(&audio_data_.lock); + ::cava::cava_execute(audio_data_.cava_in, audio_data_.samples_counter, audio_raw_.cava_out, + plan_); + if (audio_data_.samples_counter > 0) audio_data_.samples_counter = 0; + pthread_mutex_unlock(&audio_data_.lock); +} + +// Do transformation under raw data +void waybar::modules::cava::CavaBackend::execute() { + invoke(); + audio_raw_fetch(&audio_raw_, &prm_, &re_paint_, plan_); + + if (re_paint_ == 1) { + output_.clear(); + for (int i{0}; i < audio_raw_.number_of_bars; ++i) { + audio_raw_.previous_frame[i] = audio_raw_.bars[i]; + output_.push_back(audio_raw_.bars[i]); + if (prm_.bar_delim != 0) output_.push_back(prm_.bar_delim); + } + } +} + +void waybar::modules::cava::CavaBackend::doPauseResume() { + pthread_mutex_lock(&audio_data_.lock); + if (audio_data_.suspendFlag) { + audio_data_.suspendFlag = false; + pthread_cond_broadcast(&audio_data_.resumeCond); + downThreadDelay(frame_time_milsec_, suspend_silence_delay_); + } else { + audio_data_.suspendFlag = true; + upThreadDelay(frame_time_milsec_, suspend_silence_delay_); + } + pthread_mutex_unlock(&audio_data_.lock); + Update(); +} + +waybar::modules::cava::CavaBackend::type_signal_update +waybar::modules::cava::CavaBackend::signal_update() { + return m_signal_update_; +} + +waybar::modules::cava::CavaBackend::type_signal_audio_raw_update +waybar::modules::cava::CavaBackend::signal_audio_raw_update() { + return m_signal_audio_raw_; +} + +waybar::modules::cava::CavaBackend::type_signal_silence +waybar::modules::cava::CavaBackend::signal_silence() { + return m_signal_silence_; +} + +void waybar::modules::cava::CavaBackend::Update() { doUpdate(true); } + +void waybar::modules::cava::CavaBackend::doUpdate(bool force) { + if (audio_data_.suspendFlag && !force) return; + + silence_ = isSilence(); + if (!silence_) sleep_counter_ = 0; + + if (silence_ && prm_.sleep_timer != 0) { + if (sleep_counter_ <= + (int)(std::chrono::milliseconds(prm_.sleep_timer * 1s) / frame_time_milsec_)) { + ++sleep_counter_; + silence_ = false; + } + } + + if (!silence_ || prm_.sleep_timer == 0) { + if (downThreadDelay(frame_time_milsec_, suspend_silence_delay_)) Update(); + execute(); + if (re_paint_ == 1 || force || prm_.continuous_rendering) { + m_signal_update_.emit(output_); + m_signal_audio_raw_.emit(audio_raw_); + } + } else { + if (upThreadDelay(frame_time_milsec_, suspend_silence_delay_)) Update(); + if (silence_ != silence_prev_ || force) m_signal_silence_.emit(); + } + silence_prev_ = silence_; +} + +void waybar::modules::cava::CavaBackend::freeBackend() { + if (plan_ != NULL) { + cava_destroy(plan_); + plan_ = NULL; + } + + audio_raw_clean(&audio_raw_); + pthread_mutex_lock(&audio_data_.lock); + audio_data_.terminate = 1; + pthread_mutex_unlock(&audio_data_.lock); + free_config(&prm_); + free(audio_data_.source); + free(audio_data_.cava_in); +} + +void waybar::modules::cava::CavaBackend::loadConfig() { + freeBackend(); + // Load waybar module config + char cfgPath[PATH_MAX]; + cfgPath[0] = '\0'; + + if (config_["cava_config"].isString()) strcpy(cfgPath, config_["cava_config"].asString().data()); + // Load cava config + error_.length = 0; + + if (!load_config(cfgPath, &prm_, &error_)) { + spdlog::error("cava backend. Error loading config. {0}", error_.message); + exit(EXIT_FAILURE); + } + + // Override cava parameters by the user config + prm_.inAtty = 0; + auto const output{prm_.output}; + // prm_.output = ::cava::output_method::OUTPUT_RAW; + if (prm_.data_format) free(prm_.data_format); + // Default to ascii for format-icons output; allow user override + prm_.data_format = strdup( + config_["data_format"].isString() ? config_["data_format"].asString().c_str() : "ascii"); + if (config_["raw_target"].isString()) { + if (prm_.raw_target) free(prm_.raw_target); + prm_.raw_target = strdup(config_["raw_target"].asString().c_str()); + } + prm_.ascii_range = config_["format-icons"].size() - 1; + + if (config_["bar_spacing"].isInt()) prm_.bar_spacing = config_["bar_spacing"].asInt(); + if (config_["bar_width"].isInt()) prm_.bar_width = config_["bar_width"].asInt(); + if (config_["bar_height"].isInt()) prm_.bar_height = config_["bar_height"].asInt(); + prm_.orientation = ::cava::ORIENT_TOP; + prm_.xaxis = ::cava::xaxis_scale::NONE; + prm_.mono_opt = ::cava::AVERAGE; + prm_.autobars = 0; + if (config_["gravity"].isInt()) prm_.gravity = config_["gravity"].asInt(); + if (config_["integral"].isInt()) prm_.integral = config_["integral"].asInt(); + + if (config_["framerate"].isInt()) prm_.framerate = config_["framerate"].asInt(); + // Calculate delay for Update() thread + frame_time_milsec_ = std::chrono::milliseconds((int)(1e3 / prm_.framerate)); + if (config_["autosens"].isInt()) prm_.autosens = config_["autosens"].asInt(); + if (config_["sensitivity"].isInt()) prm_.sens = config_["sensitivity"].asInt(); + if (config_["bars"].isInt()) prm_.fixedbars = config_["bars"].asInt(); + if (config_["lower_cutoff_freq"].isNumeric()) + prm_.lower_cut_off = config_["lower_cutoff_freq"].asLargestInt(); + if (config_["higher_cutoff_freq"].isNumeric()) + prm_.upper_cut_off = config_["higher_cutoff_freq"].asLargestInt(); + if (config_["sleep_timer"].isInt()) prm_.sleep_timer = config_["sleep_timer"].asInt(); + if (config_["method"].isString()) + prm_.input = ::cava::input_method_by_name(config_["method"].asString().c_str()); + if (config_["source"].isString()) { + if (prm_.audio_source) free(prm_.audio_source); + prm_.audio_source = strdup(config_["source"].asString().c_str()); + } + if (config_["sample_rate"].isNumeric()) prm_.samplerate = config_["sample_rate"].asLargestInt(); + if (config_["sample_bits"].isInt()) prm_.samplebits = config_["sample_bits"].asInt(); + if (config_["stereo"].isBool()) prm_.stereo = config_["stereo"].asBool(); + if (config_["reverse"].isBool()) prm_.reverse = config_["reverse"].asBool(); + if (config_["bar_delimiter"].isInt()) prm_.bar_delim = config_["bar_delimiter"].asInt(); + if (config_["monstercat"].isBool()) prm_.monstercat = config_["monstercat"].asBool(); + if (config_["waves"].isBool()) prm_.waves = config_["waves"].asBool(); + if (config_["noise_reduction"].isDouble()) + prm_.noise_reduction = config_["noise_reduction"].asDouble(); + if (config_["input_delay"].isInt()) + fetch_input_delay_ = std::chrono::seconds(config_["input_delay"].asInt()); + if (config_["gradient"].isInt()) prm_.gradient = config_["gradient"].asInt(); + if (prm_.gradient == 0) + prm_.gradient_count = 0; + else if (config_["gradient_count"].isInt()) + prm_.gradient_count = config_["gradient_count"].asInt(); + if (config_["sdl_width"].isInt()) prm_.sdl_width = config_["sdl_width"].asInt(); + if (config_["sdl_height"].isInt()) prm_.sdl_height = config_["sdl_height"].asInt(); + + audio_raw_.height = prm_.ascii_range; + audio_data_.format = -1; + audio_data_.rate = 0; + audio_data_.samples_counter = 0; + audio_data_.channels = 2; + audio_data_.IEEE_FLOAT = 0; + audio_data_.input_buffer_size = BUFFER_SIZE * audio_data_.channels; + audio_data_.cava_buffer_size = audio_data_.input_buffer_size * 8; + audio_data_.terminate = 0; + audio_data_.suspendFlag = false; + input_source_ = get_input(&audio_data_, &prm_); + + if (!input_source_) { + spdlog::error("cava backend API didn't provide input audio source method"); + exit(EXIT_FAILURE); + } + + prm_.output = ::cava::output_method::OUTPUT_RAW; + + // Make cava parameters configuration + // Init cava plan, audio_raw structure + audio_raw_init(&audio_data_, &audio_raw_, &prm_, &plan_); + if (!plan_) spdlog::error("cava backend plan is not provided"); + audio_raw_.previous_frame[0] = -1; // For first Update() call need to rePaint text message + + prm_.output = output; +} + +const struct ::cava::config_params* waybar::modules::cava::CavaBackend::getPrm() { return &prm_; } +std::chrono::milliseconds waybar::modules::cava::CavaBackend::getFrameTimeMilsec() { + return frame_time_milsec_; +}; diff --git a/src/modules/cffi.cpp b/src/modules/cffi.cpp index 5c095f46..c3f1398f 100644 --- a/src/modules/cffi.cpp +++ b/src/modules/cffi.cpp @@ -35,7 +35,7 @@ CFFI::CFFI(const std::string& name, const std::string& id, const Json::Value& co throw std::runtime_error{std::string{"Missing wbcffi_init function: "} + dlerror()}; } hooks_.deinit = reinterpret_cast(dlsym(handle, "wbcffi_deinit")); - if (!hooks_.init) { + if (!hooks_.deinit) { throw std::runtime_error{std::string{"Missing wbcffi_deinit function: "} + dlerror()}; } // Optional functions @@ -71,6 +71,7 @@ CFFI::CFFI(const std::string& name, const std::string& id, const Json::Value& co // Prepare config_entries array std::vector config_entries; + config_entries.reserve(keys.size()); for (size_t i = 0; i < keys.size(); i++) { config_entries.push_back({keys[i].c_str(), config_entries_stringstor[i].c_str()}); } diff --git a/src/modules/clock.cpp b/src/modules/clock.cpp index 269fa765..97777667 100644 --- a/src/modules/clock.cpp +++ b/src/modules/clock.cpp @@ -1,5 +1,6 @@ #include "modules/clock.hpp" +#include #include #include @@ -16,6 +17,7 @@ #include #endif +using namespace date; namespace fmt_lib = waybar::util::date::format; waybar::modules::Clock::Clock(const std::string& id, const Json::Value& config) @@ -25,8 +27,12 @@ waybar::modules::Clock::Clock(const std::string& id, const Json::Value& config) m_tooltip_{new Gtk::Label()}, cldInTooltip_{m_tlpFmt_.find("{" + kCldPlaceholder + "}") != std::string::npos}, cldYearShift_{January / 1 / 1900}, + cldMonShift_{year(1900) / January}, tzInTooltip_{m_tlpFmt_.find("{" + kTZPlaceholder + "}") != std::string::npos}, tzCurrIdx_{0}, + tzTooltipFormat_{config_["timezone-tooltip-format"].isString() + ? config_["timezone-tooltip-format"].asString() + : ""}, ordInTooltip_{m_tlpFmt_.find("{" + kOrdPlaceholder + "}") != std::string::npos} { m_tlpText_ = m_tlpFmt_; @@ -60,8 +66,8 @@ waybar::modules::Clock::Clock(const std::string& id, const Json::Value& config) if (cldInTooltip_) { if (config_[kCldPlaceholder]["mode"].isString()) { const std::string cfgMode{config_[kCldPlaceholder]["mode"].asString()}; - const std::map monthModes{{"month", CldMode::MONTH}, - {"year", CldMode::YEAR}}; + const std::map monthModes{{"month", CldMode::MONTH}, + {"year", CldMode::YEAR}}; if (monthModes.find(cfgMode) != monthModes.end()) cldMode_ = monthModes.at(cfgMode); else @@ -70,6 +76,11 @@ waybar::modules::Clock::Clock(const std::string& id, const Json::Value& config) "using instead", cfgMode); } + + if (config_[kCldPlaceholder]["iso8601"].isBool()) { + iso8601Calendar_ = config_[kCldPlaceholder]["iso8601"].asBool(); + } + if (config_[kCldPlaceholder]["weeks-pos"].isString()) { if (config_[kCldPlaceholder]["weeks-pos"].asString() == "left") cldWPos_ = WS::LEFT; if (config_[kCldPlaceholder]["weeks-pos"].asString() == "right") cldWPos_ = WS::RIGHT; @@ -89,23 +100,25 @@ waybar::modules::Clock::Clock(const std::string& id, const Json::Value& config) fmtMap_.insert({2, "{}"}); if (config_[kCldPlaceholder]["format"]["today"].isString()) { fmtMap_.insert({3, config_[kCldPlaceholder]["format"]["today"].asString()}); - cldBaseDay_ = - year_month_day{ - floor(zoned_time{local_zone(), system_clock::now()}.get_local_time())} - .day(); + auto local_time = zoned_time{local_zone(), system_clock::now()}.get_local_time(); + cldBaseDay_ = year_month_day{floor(local_time)}.day(); } else fmtMap_.insert({3, "{}"}); if (config_[kCldPlaceholder]["format"]["weeks"].isString() && cldWPos_ != WS::HIDDEN) { + const auto defaultFmt = + iso8601Calendar_ ? "{:%V}" : ((first_day_of_week() == Monday) ? "{:%W}" : "{:%U}"); fmtMap_.insert({4, std::regex_replace(config_[kCldPlaceholder]["format"]["weeks"].asString(), - std::regex("\\{\\}"), - (first_day_of_week() == Monday) ? "{:%W}" : "{:%U}")}); + std::regex("\\{\\}"), defaultFmt)}); Glib::ustring tmp{std::regex_replace(fmtMap_[4], std::regex("]+>|\\{.*\\}"), "")}; cldWnLen_ += tmp.size(); } else { - if (cldWPos_ != WS::HIDDEN) - fmtMap_.insert({4, (first_day_of_week() == Monday) ? "{:%W}" : "{:%U}"}); - else + if (cldWPos_ != WS::HIDDEN) { + const auto defaultFmt = + iso8601Calendar_ ? "{:%V}" : ((first_day_of_week() == Monday) ? "{:%W}" : "{:%U}"); + fmtMap_.insert({4, defaultFmt}); + } else { cldWnLen_ = 0; + } } if (config_[kCldPlaceholder]["mode-mon-col"].isInt()) { cldMonCols_ = config_[kCldPlaceholder]["mode-mon-col"].asInt(); @@ -185,11 +198,26 @@ auto waybar::modules::Clock::getTZtext(sys_seconds now) -> std::string { if (tzList_.size() == 1) return ""; std::stringstream os; + bool first = true; for (size_t tz_idx{0}; tz_idx < tzList_.size(); ++tz_idx) { - if (static_cast(tz_idx) == tzCurrIdx_) continue; - const auto* tz = tzList_[tz_idx] != nullptr ? tzList_[tz_idx] : local_zone(); + // Skip local timezone (nullptr) - never show it in tooltip + if (tzList_[tz_idx] == nullptr) continue; + + // Skip current timezone unless timezone-tooltip-format is specified + if (static_cast(tz_idx) == tzCurrIdx_ && tzTooltipFormat_.empty()) continue; + + const auto* tz = tzList_[tz_idx]; auto zt{zoned_time{tz, now}}; - os << fmt_lib::vformat(m_locale_, format_, fmt_lib::make_format_args(zt)) << '\n'; + + // Add newline before each entry except the first + if (!first) { + os << '\n'; + } + first = false; + + // Use timezone-tooltip-format if specified, otherwise use format_ + const std::string& fmt = tzTooltipFormat_.empty() ? format_ : tzTooltipFormat_; + os << fmt_lib::vformat(m_locale_, fmt, fmt_lib::make_format_args(zt)); } return os.str(); @@ -201,9 +229,11 @@ const unsigned cldRowsInMonth(const year_month& ym, const weekday& firstdow) { auto cldGetWeekForLine(const year_month& ym, const weekday& firstdow, const unsigned line) -> const year_month_weekday { - unsigned index{line - 2}; - if (weekday{ym / 1} == firstdow) ++index; - return ym / firstdow[index]; + const unsigned idx = line - 2; + const auto indexed_first_day_of_week = + weekday{ym / 1} == firstdow ? firstdow[idx + 1] : firstdow[idx]; + + return ym / indexed_first_day_of_week; } auto getCalendarLine(const year_month_day& currDate, const year_month ym, const unsigned line, @@ -262,7 +292,7 @@ auto getCalendarLine(const year_month_day& currDate, const year_month ym, const } // Print non-first week default: { - auto ymdTmp{cldGetWeekForLine(ym, firstdow, line)}; + const auto ymdTmp{cldGetWeekForLine(ym, firstdow, line)}; if (ymdTmp.ok()) { auto d{year_month_day{ymdTmp}.day()}; const auto dlast{(ym / last).day()}; @@ -348,20 +378,39 @@ auto waybar::modules::Clock::get_calendar(const year_month_day& today, const yea m_locale_, fmtMap_[4], fmt_lib::make_format_args( (line == 2) - ? static_cast( + ? static_cast( zoned_seconds{tz, local_days{ymTmp / 1}}) - : static_cast(zoned_seconds{ + : static_cast(zoned_seconds{ tz, local_days{cldGetWeekForLine(ymTmp, firstdow, line)}}))) << ' '; - } else + } else { os << pads; + } } } - os << Glib::ustring::format((cldWPos_ != WS::LEFT || line == 0) ? std::left : std::right, - std::setfill(L' '), - std::setw(cldMonColLen_ + ((line < 2) ? cldWnLen_ : 0)), - getCalendarLine(today, ymTmp, line, firstdow, &m_locale_)); + // Count wide characters to avoid extra padding + size_t wideCharCount = 0; + std::string calendarLine = getCalendarLine(today, ymTmp, line, firstdow, &m_locale_); + if (line < 2) { + for (gchar *data = calendarLine.data(), *end = data + calendarLine.size(); + data != nullptr;) { + gunichar c = g_utf8_get_char_validated(data, end - data); + if (g_unichar_iswide(c)) { + wideCharCount++; + } + data = g_utf8_find_next_char(data, end); + } + } + // Note: the stream's default fill character is already a space (L' ' on + // libstdc++'s wide FormatStream, ' ' on libc++'s narrow one), so no + // std::setfill is needed. Passing std::setfill(' ')/std::setfill(L' ') + // here is not portable because the fill char type must match the + // FormatStream's char type, which differs between standard libraries. + os << Glib::ustring::format( + (cldWPos_ != WS::LEFT || line == 0) ? std::left : std::right, + std::setw(cldMonColLen_ + ((line < 2) ? cldWnLen_ - wideCharCount : 0)), + calendarLine); // Week numbers on the right if (cldWPos_ == WS::RIGHT && line > 0) { @@ -371,9 +420,9 @@ auto waybar::modules::Clock::get_calendar(const year_month_day& today, const yea << fmt_lib::vformat( m_locale_, fmtMap_[4], fmt_lib::make_format_args( - (line == 2) ? static_cast( + (line == 2) ? static_cast( zoned_seconds{tz, local_days{ymTmp / 1}}) - : static_cast( + : static_cast( zoned_seconds{tz, local_days{cldGetWeekForLine( ymTmp, firstdow, line)}}))); else @@ -465,6 +514,9 @@ using deleting_unique_ptr = std::unique_ptr>; // Computations done similarly to Linux cal utility. auto waybar::modules::Clock::first_day_of_week() -> weekday { + if (iso8601Calendar_) { + return Monday; + } #ifdef HAVE_LANGINFO_1STDAY deleting_unique_ptr::type, freelocale> posix_locale{ newlocale(LC_ALL, m_locale_.name().c_str(), nullptr)}; diff --git a/src/modules/cpu.cpp b/src/modules/cpu.cpp index 0703eaf7..faeb5696 100644 --- a/src/modules/cpu.cpp +++ b/src/modules/cpu.cpp @@ -26,9 +26,7 @@ auto waybar::modules::Cpu::update() -> void { auto [load1, load5, load15] = Load::getLoad(); auto [cpu_usage, tooltip] = CpuUsage::getCpuUsage(prev_times_); auto [max_frequency, min_frequency, avg_frequency] = CpuFrequency::getCpuFrequency(); - if (tooltipEnabled()) { - label_.set_tooltip_text(tooltip); - } + auto format = format_; auto total_usage = cpu_usage.empty() ? 0 : cpu_usage[0]; auto state = getState(total_usage); @@ -43,19 +41,38 @@ auto waybar::modules::Cpu::update() -> void { auto icons = std::vector{state}; fmt::dynamic_format_arg_store store; store.push_back(fmt::arg("load", load1)); + store.push_back(fmt::arg("load1", load1)); + store.push_back(fmt::arg("load5", load5)); + store.push_back(fmt::arg("load15", load15)); store.push_back(fmt::arg("usage", total_usage)); store.push_back(fmt::arg("icon", getIcon(total_usage, icons))); store.push_back(fmt::arg("max_frequency", max_frequency)); store.push_back(fmt::arg("min_frequency", min_frequency)); store.push_back(fmt::arg("avg_frequency", avg_frequency)); + std::vector arg_names; + arg_names.reserve(cpu_usage.size() * 2); for (size_t i = 1; i < cpu_usage.size(); ++i) { auto core_i = i - 1; - auto core_format = fmt::format("usage{}", core_i); - store.push_back(fmt::arg(core_format.c_str(), cpu_usage[i])); - auto icon_format = fmt::format("icon{}", core_i); - store.push_back(fmt::arg(icon_format.c_str(), getIcon(cpu_usage[i], icons))); + arg_names.push_back(fmt::format("usage{}", core_i)); + store.push_back(fmt::arg(arg_names.back().c_str(), cpu_usage[i])); + arg_names.push_back(fmt::format("icon{}", core_i)); + store.push_back(fmt::arg(arg_names.back().c_str(), getIcon(cpu_usage[i], icons))); } label_.set_markup(fmt::vformat(format, store)); + + if (tooltipEnabled()) { + std::string tooltip_format; + if (!state.empty() && config_["tooltip-format-" + state].isString()) { + tooltip_format = config_["tooltip-format-" + state].asString(); + } else if (config_["tooltip-format"].isString()) { + tooltip_format = config_["tooltip-format"].asString(); + } + if (!tooltip_format.empty()) { + label_.set_tooltip_markup(fmt::vformat(tooltip_format, store)); + } else { + label_.set_tooltip_markup(tooltip); + } + } } // Call parent update diff --git a/src/modules/cpu_frequency/bsd.cpp b/src/modules/cpu_frequency/bsd.cpp index 743fb288..eb5ae98a 100644 --- a/src/modules/cpu_frequency/bsd.cpp +++ b/src/modules/cpu_frequency/bsd.cpp @@ -5,11 +5,12 @@ std::vector waybar::modules::CpuFrequency::parseCpuFrequencies() { std::vector frequencies; - char buffer[256]; size_t len; int32_t freq; - uint32_t i = 0; +#ifndef __OpenBSD__ + char buffer[256]; + uint32_t i = 0; while (true) { len = 4; snprintf(buffer, 256, "dev.cpu.%u.freq", i); @@ -17,6 +18,12 @@ std::vector waybar::modules::CpuFrequency::parseCpuFrequencies() { frequencies.push_back(freq); ++i; } +#else + int getMhz[] = {CTL_HW, HW_CPUSPEED}; + len = sizeof(freq); + sysctl(getMhz, 2, &freq, &len, NULL, 0); + frequencies.push_back((float)freq); +#endif if (frequencies.empty()) { spdlog::warn("cpu/bsd: parseCpuFrequencies failed, not found in sysctl"); diff --git a/src/modules/cpu_frequency/common.cpp b/src/modules/cpu_frequency/common.cpp index e47364ba..05adc2b3 100644 --- a/src/modules/cpu_frequency/common.cpp +++ b/src/modules/cpu_frequency/common.cpp @@ -20,12 +20,7 @@ waybar::modules::CpuFrequency::CpuFrequency(const std::string& id, const Json::V auto waybar::modules::CpuFrequency::update() -> void { // TODO: as creating dynamic fmt::arg arrays is buggy we have to calc both auto [max_frequency, min_frequency, avg_frequency] = CpuFrequency::getCpuFrequency(); - if (tooltipEnabled()) { - auto tooltip = - fmt::format("Minimum frequency: {}\nAverage frequency: {}\nMaximum frequency: {}\n", - min_frequency, avg_frequency, max_frequency); - label_.set_tooltip_text(tooltip); - } + auto format = format_; auto state = getState(avg_frequency); if (!state.empty() && config_["format-" + state].isString()) { @@ -43,6 +38,18 @@ auto waybar::modules::CpuFrequency::update() -> void { store.push_back(fmt::arg("min_frequency", min_frequency)); store.push_back(fmt::arg("avg_frequency", avg_frequency)); label_.set_markup(fmt::vformat(format, store)); + + if (tooltipEnabled()) { + std::string tooltip; + if (config_["tooltip-format"].isString()) { + tooltip = config_["tooltip-format"].asString(); + label_.set_tooltip_markup(fmt::vformat(tooltip, store)); + } else { + tooltip = "Minimum frequency: {}\nAverage frequency: {}\nMaximum frequency: {}\n"; + label_.set_tooltip_markup( + fmt::format(fmt::runtime(tooltip), min_frequency, avg_frequency, max_frequency)); + } + } } // Call parent update diff --git a/src/modules/cpu_frequency/linux.cpp b/src/modules/cpu_frequency/linux.cpp index 1f368789..7b927cdc 100644 --- a/src/modules/cpu_frequency/linux.cpp +++ b/src/modules/cpu_frequency/linux.cpp @@ -23,23 +23,21 @@ std::vector waybar::modules::CpuFrequency::parseCpuFrequencies() { if (frequencies.size() <= 0) { std::string cpufreq_dir = "/sys/devices/system/cpu/cpufreq"; - if (std::filesystem::exists(cpufreq_dir)) { + try { std::vector frequency_files = {"/cpuinfo_min_freq", "/cpuinfo_max_freq"}; for (auto& p : std::filesystem::directory_iterator(cpufreq_dir)) { - for (auto freq_file : frequency_files) { + for (const auto& freq_file : frequency_files) { std::string freq_file_path = p.path().string() + freq_file; - if (std::filesystem::exists(freq_file_path)) { - std::string freq_value; - std::ifstream freq(freq_file_path); - if (freq.is_open()) { - getline(freq, freq_value); - float frequency = std::strtol(freq_value.c_str(), nullptr, 10); - frequencies.push_back(frequency / 1000); - freq.close(); - } + std::string freq_value; + std::ifstream freq(freq_file_path); + if (freq.is_open()) { + getline(freq, freq_value); + float frequency = std::strtol(freq_value.c_str(), nullptr, 10); + frequencies.push_back(frequency / 1000); } } } + } catch (const std::filesystem::filesystem_error&) { } } diff --git a/src/modules/cpu_usage/bsd.cpp b/src/modules/cpu_usage/bsd.cpp index d795a817..e49498e4 100644 --- a/src/modules/cpu_usage/bsd.cpp +++ b/src/modules/cpu_usage/bsd.cpp @@ -33,7 +33,7 @@ std::vector> waybar::modules::CpuUsage::parseCpuinfo( size_t sum_sz = sizeof(sum_cp_time); int ncpu = sysconf(_SC_NPROCESSORS_CONF); size_t sz = CPUSTATES * (ncpu + 1) * sizeof(pcp_time_t); - pcp_time_t *cp_time = static_cast(malloc(sz)), *pcp_time = cp_time; + pcp_time_t *cp_time = static_cast(malloc(sz)), *pcp_time = cp_time; waybar::util::ScopeGuard cp_time_deleter([cp_time]() { if (cp_time) { free(cp_time); diff --git a/src/modules/cpu_usage/common.cpp b/src/modules/cpu_usage/common.cpp index e3947967..1571cb74 100644 --- a/src/modules/cpu_usage/common.cpp +++ b/src/modules/cpu_usage/common.cpp @@ -20,9 +20,7 @@ waybar::modules::CpuUsage::CpuUsage(const std::string& id, const Json::Value& co auto waybar::modules::CpuUsage::update() -> void { // TODO: as creating dynamic fmt::arg arrays is buggy we have to calc both auto [cpu_usage, tooltip] = CpuUsage::getCpuUsage(prev_times_); - if (tooltipEnabled()) { - label_.set_tooltip_text(tooltip); - } + auto format = format_; auto total_usage = cpu_usage.empty() ? 0 : cpu_usage[0]; auto state = getState(total_usage); @@ -38,14 +36,25 @@ auto waybar::modules::CpuUsage::update() -> void { fmt::dynamic_format_arg_store store; store.push_back(fmt::arg("usage", total_usage)); store.push_back(fmt::arg("icon", getIcon(total_usage, icons))); + std::vector arg_names; + arg_names.reserve(cpu_usage.size() * 2); for (size_t i = 1; i < cpu_usage.size(); ++i) { auto core_i = i - 1; - auto core_format = fmt::format("usage{}", core_i); - store.push_back(fmt::arg(core_format.c_str(), cpu_usage[i])); - auto icon_format = fmt::format("icon{}", core_i); - store.push_back(fmt::arg(icon_format.c_str(), getIcon(cpu_usage[i], icons))); + arg_names.push_back(fmt::format("usage{}", core_i)); + store.push_back(fmt::arg(arg_names.back().c_str(), cpu_usage[i])); + arg_names.push_back(fmt::format("icon{}", core_i)); + store.push_back(fmt::arg(arg_names.back().c_str(), getIcon(cpu_usage[i], icons))); } label_.set_markup(fmt::vformat(format, store)); + + if (tooltipEnabled()) { + if (config_["tooltip-format"].isString()) { + tooltip = config_["tooltip-format"].asString(); + label_.set_tooltip_markup(fmt::vformat(tooltip, store)); + } else { + label_.set_tooltip_markup(tooltip); + } + } } // Call parent update @@ -71,7 +80,8 @@ std::tuple, std::string> waybar::modules::CpuUsage::getCpu auto [prev_idle, prev_total] = prev_times[0]; const float delta_idle = curr_idle - prev_idle; const float delta_total = curr_total - prev_total; - uint16_t tmp = 100 * (1 - delta_idle / delta_total); + uint16_t tmp = + (delta_total > 0) ? static_cast(100 * (1 - delta_idle / delta_total)) : 0; tooltip = fmt::format("Total: {}%\nCores: (pending)", tmp); usage.push_back(tmp); } else { @@ -93,7 +103,8 @@ std::tuple, std::string> waybar::modules::CpuUsage::getCpu } const float delta_idle = curr_idle - prev_idle; const float delta_total = curr_total - prev_total; - uint16_t tmp = 100 * (1 - delta_idle / delta_total); + uint16_t tmp = + (delta_total > 0) ? static_cast(100 * (1 - delta_idle / delta_total)) : 0; if (i == 0) { tooltip = fmt::format("Total: {}%", tmp); } else { diff --git a/src/modules/custom.cpp b/src/modules/custom.cpp index e023aaf6..e4a4eb37 100644 --- a/src/modules/custom.cpp +++ b/src/modules/custom.cpp @@ -2,6 +2,8 @@ #include +#include + #include "util/scope_guard.hpp" waybar::modules::Custom::Custom(const std::string& name, const std::string& id, @@ -14,6 +16,9 @@ waybar::modules::Custom::Custom(const std::string& name, const std::string& id, percentage_(0), fp_(nullptr), pid_(-1) { + if (config.isNull()) { + spdlog::warn("There is no configuration for 'custom/{}', element will be hidden", name); + } dp.emit(); if (!config_["signal"].empty() && config_["interval"].empty() && config_["restart-interval"].empty()) { @@ -34,7 +39,19 @@ waybar::modules::Custom::~Custom() { } void waybar::modules::Custom::delayWorker() { + if (!config_["exec"].isString() && !config_["exec-if"].isString()) { + dp.emit(); + return; + } + thread_ = [this] { + for (int i : this->pid_children_) { + int status; + waitpid(i, &status, 0); + } + + this->pid_children_.clear(); + bool can_update = true; if (config_["exec-if"].isString()) { output_ = util::command::execNoRead(config_["exec-if"].asString()); @@ -62,7 +79,7 @@ void waybar::modules::Custom::continuousWorker() { } thread_ = [this, cmd] { char* buff = nullptr; - waybar::util::ScopeGuard buff_deleter([buff]() { + waybar::util::ScopeGuard buff_deleter([&buff]() { if (buff) { free(buff); } @@ -79,9 +96,11 @@ void waybar::modules::Custom::continuousWorker() { dp.emit(); spdlog::error("{} stopped unexpectedly, is it endless?", name_); } - if (config_["restart-interval"].isUInt()) { + if (config_["restart-interval"].isNumeric()) { pid_ = -1; - thread_.sleep_for(std::chrono::seconds(config_["restart-interval"].asUInt())); + thread_.sleep_for(std::chrono::milliseconds( + std::max(1L, // Minimum 1ms due to millisecond precision + static_cast(config_["restart-interval"].asDouble() * 1000)))); fp_ = util::command::open(cmd, pid_, output_name_); if (!fp_) { throw std::runtime_error("Unable to open " + cmd); @@ -124,9 +143,11 @@ void waybar::modules::Custom::waitingWorker() { } void waybar::modules::Custom::refresh(int sig) { - if (sig == SIGRTMIN + config_["signal"].asInt()) { +#ifdef SIGRTMIN + if (config_["signal"].isInt() && sig == SIGRTMIN + config_["signal"].asInt()) { thread_.wake_up(); } +#endif } void waybar::modules::Custom::handleEvent() { @@ -168,20 +189,22 @@ auto waybar::modules::Custom::update() -> void { } else { label_.set_markup(str); if (tooltipEnabled()) { + std::string tooltip_markup; if (tooltip_format_enabled_) { auto tooltip = config_["tooltip-format"].asString(); - tooltip = fmt::format( - fmt::runtime(tooltip), fmt::arg("text", text_), fmt::arg("alt", alt_), - fmt::arg("icon", getIcon(percentage_, alt_)), fmt::arg("percentage", percentage_)); - label_.set_tooltip_markup(tooltip); + tooltip_markup = fmt::format(fmt::runtime(tooltip), fmt::arg("text", text_), + fmt::arg("tooltip", tooltip_), fmt::arg("alt", alt_), + fmt::arg("icon", getIcon(percentage_, alt_)), + fmt::arg("percentage", percentage_)); } else if (text_ == tooltip_) { - if (label_.get_tooltip_markup() != str) { - label_.set_tooltip_markup(str); - } + tooltip_markup = str; } else { - if (label_.get_tooltip_markup() != tooltip_) { - label_.set_tooltip_markup(tooltip_); - } + tooltip_markup = tooltip_; + } + + if (last_tooltip_markup_ != tooltip_markup) { + label_.set_tooltip_markup(tooltip_markup); + last_tooltip_markup_ = std::move(tooltip_markup); } } auto style = label_.get_style_context(); diff --git a/src/modules/disk.cpp b/src/modules/disk.cpp index ef257b72..462940b2 100644 --- a/src/modules/disk.cpp +++ b/src/modules/disk.cpp @@ -41,7 +41,7 @@ auto waybar::modules::Disk::update() -> void { fs_used - File system used space */ - if (err != 0) { + if (err != 0 || stats.f_blocks == 0) { event_box_.hide(); return; } @@ -81,7 +81,7 @@ auto waybar::modules::Disk::update() -> void { if (config_["tooltip-format"].isString()) { tooltip_format = config_["tooltip-format"].asString(); } - label_.set_tooltip_text(fmt::format( + label_.set_tooltip_markup(fmt::format( fmt::runtime(tooltip_format), stats.f_bavail * 100 / stats.f_blocks, fmt::arg("free", free), fmt::arg("percentage_free", stats.f_bavail * 100 / stats.f_blocks), fmt::arg("used", used), fmt::arg("percentage_used", percentage_used), fmt::arg("total", total), @@ -92,7 +92,7 @@ auto waybar::modules::Disk::update() -> void { ALabel::update(); } -float waybar::modules::Disk::calc_specific_divisor(std::string divisor) { +float waybar::modules::Disk::calc_specific_divisor(const std::string& divisor) { if (divisor == "kB") { return 1000.0; } else if (divisor == "kiB") { @@ -112,4 +112,4 @@ float waybar::modules::Disk::calc_specific_divisor(std::string divisor) { } else { // default to Bytes if it is anything that we don't recongnise return 1.0; } -} \ No newline at end of file +} diff --git a/src/modules/dwl/tags.cpp b/src/modules/dwl/tags.cpp index f8b250c8..243aaa92 100644 --- a/src/modules/dwl/tags.cpp +++ b/src/modules/dwl/tags.cpp @@ -21,39 +21,39 @@ wl_array tags, layouts; static uint num_tags = 0; -static void toggle_visibility(void *data, zdwl_ipc_output_v2 *zdwl_output_v2) { +static void toggle_visibility(void* data, zdwl_ipc_output_v2* zdwl_output_v2) { // Intentionally empty } -static void active(void *data, zdwl_ipc_output_v2 *zdwl_output_v2, uint32_t active) { +static void active(void* data, zdwl_ipc_output_v2* zdwl_output_v2, uint32_t active) { // Intentionally empty } -static void set_tag(void *data, zdwl_ipc_output_v2 *zdwl_output_v2, uint32_t tag, uint32_t state, +static void set_tag(void* data, zdwl_ipc_output_v2* zdwl_output_v2, uint32_t tag, uint32_t state, uint32_t clients, uint32_t focused) { - static_cast(data)->handle_view_tags(tag, state, clients, focused); + static_cast(data)->handle_view_tags(tag, state, clients, focused); num_tags = (state & ZDWL_IPC_OUTPUT_V2_TAG_STATE_ACTIVE) ? num_tags | (1 << tag) : num_tags & ~(1 << tag); } -static void set_layout_symbol(void *data, zdwl_ipc_output_v2 *zdwl_output_v2, const char *layout) { +static void set_layout_symbol(void* data, zdwl_ipc_output_v2* zdwl_output_v2, const char* layout) { // Intentionally empty } -static void title(void *data, zdwl_ipc_output_v2 *zdwl_output_v2, const char *title) { +static void title(void* data, zdwl_ipc_output_v2* zdwl_output_v2, const char* title) { // Intentionally empty } -static void dwl_frame(void *data, zdwl_ipc_output_v2 *zdwl_output_v2) { +static void dwl_frame(void* data, zdwl_ipc_output_v2* zdwl_output_v2) { // Intentionally empty } -static void set_layout(void *data, zdwl_ipc_output_v2 *zdwl_output_v2, uint32_t layout) { +static void set_layout(void* data, zdwl_ipc_output_v2* zdwl_output_v2, uint32_t layout) { // Intentionally empty } -static void appid(void *data, zdwl_ipc_output_v2 *zdwl_output_v2, const char *appid) { +static void appid(void* data, zdwl_ipc_output_v2* zdwl_output_v2, const char* appid) { // Intentionally empty }; @@ -68,35 +68,51 @@ static const zdwl_ipc_output_v2_listener output_status_listener_impl{ .frame = dwl_frame, }; -static void handle_global(void *data, struct wl_registry *registry, uint32_t name, - const char *interface, uint32_t version) { - if (std::strcmp(interface, zdwl_ipc_manager_v2_interface.name) == 0) { - static_cast(data)->status_manager_ = static_cast( - (zdwl_ipc_manager_v2 *)wl_registry_bind(registry, name, &zdwl_ipc_manager_v2_interface, 1)); - } - if (std::strcmp(interface, wl_seat_interface.name) == 0) { - version = std::min(version, 1); - static_cast(data)->seat_ = static_cast( - wl_registry_bind(registry, name, &wl_seat_interface, version)); - } +static void handle_global(void* data, struct wl_registry* registry, uint32_t name, + const char* interface, uint32_t version) { + +if (std::strcmp(interface, zdwl_ipc_manager_v2_interface.name) == 0) { + auto* self = static_cast(data); + + if (self->status_manager_) { + zdwl_ipc_manager_v2_destroy(self->status_manager_); + self->status_manager_ = nullptr; } -static void handle_global_remove(void *data, struct wl_registry *registry, uint32_t name) { + self->status_manager_ = static_cast( + wl_registry_bind(registry, name, &zdwl_ipc_manager_v2_interface, 1)); +} + +if (std::strcmp(interface, wl_seat_interface.name) == 0) { + auto* self = static_cast(data); + + if (self->seat_) { + wl_seat_destroy(self->seat_); + self->seat_ = nullptr; + } + + version = std::min(version, 1); + + self->seat_ = static_cast( + wl_registry_bind(registry, name, &wl_seat_interface, version)); +} +} +static void handle_global_remove(void* data, struct wl_registry* registry, uint32_t name) { /* Ignore event */ } static const wl_registry_listener registry_listener_impl = {.global = handle_global, .global_remove = handle_global_remove}; -Tags::Tags(const std::string &id, const waybar::Bar &bar, const Json::Value &config) +Tags::Tags(const std::string& id, const waybar::Bar& bar, const Json::Value& config) : waybar::AModule(config, "tags", id, false, false), status_manager_{nullptr}, seat_{nullptr}, bar_(bar), box_{bar.orientation, 0}, output_status_{nullptr} { - struct wl_display *display = Client::inst()->wl_display; - struct wl_registry *registry = wl_display_get_registry(display); + struct wl_display* display = Client::inst()->wl_display; + struct wl_registry* registry = wl_display_get_registry(display); wl_registry_add_listener(registry, ®istry_listener_impl, this); wl_display_roundtrip(display); @@ -133,8 +149,8 @@ Tags::Tags(const std::string &id, const waybar::Bar &bar, const Json::Value &con } uint32_t i = 1; - for (const auto &tag_label : tag_labels) { - Gtk::Button &button = buttons_.emplace_back(tag_label); + for (const auto& tag_label : tag_labels) { + Gtk::Button& button = buttons_.emplace_back(tag_label); button.set_relief(Gtk::RELIEF_NONE); box_.pack_start(button, false, false, 0); if (!config_["disable-click"].asBool()) { @@ -147,7 +163,7 @@ Tags::Tags(const std::string &id, const waybar::Bar &bar, const Json::Value &con i <<= 1; } - struct wl_output *output = gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj()); + struct wl_output* output = gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj()); output_status_ = zdwl_ipc_manager_v2_get_output(status_manager_, output); zdwl_ipc_output_v2_add_listener(output_status_, &output_status_listener_impl, this); @@ -170,7 +186,7 @@ void Tags::handle_primary_clicked(uint32_t tag) { zdwl_ipc_output_v2_set_tags(output_status_, tag, 1); } -bool Tags::handle_button_press(GdkEventButton *event_button, uint32_t tag) { +bool Tags::handle_button_press(GdkEventButton* event_button, uint32_t tag) { if (event_button->type == GDK_BUTTON_PRESS && event_button->button == 3) { if (!output_status_) return true; zdwl_ipc_output_v2_set_tags(output_status_, num_tags ^ tag, 0); @@ -179,14 +195,21 @@ bool Tags::handle_button_press(GdkEventButton *event_button, uint32_t tag) { } void Tags::handle_view_tags(uint32_t tag, uint32_t state, uint32_t clients, uint32_t focused) { + if (tag >= buttons_.size()) return; // First clear all occupied state - auto &button = buttons_[tag]; + auto& button = buttons_[tag]; if (clients) { button.get_style_context()->add_class("occupied"); } else { button.get_style_context()->remove_class("occupied"); } + if (clients & TAG_INACTIVE) { + button.get_style_context()->remove_class("empty"); + } else { + button.get_style_context()->add_class("empty"); + } + if (state & TAG_ACTIVE) { button.get_style_context()->add_class("focused"); } else { diff --git a/src/modules/dwl/window.cpp b/src/modules/dwl/window.cpp index a960a1f0..56e67895 100644 --- a/src/modules/dwl/window.cpp +++ b/src/modules/dwl/window.cpp @@ -14,37 +14,37 @@ namespace waybar::modules::dwl { -static void toggle_visibility(void *data, zdwl_ipc_output_v2 *zdwl_output_v2) { +static void toggle_visibility(void* data, zdwl_ipc_output_v2* zdwl_output_v2) { // Intentionally empty } -static void active(void *data, zdwl_ipc_output_v2 *zdwl_output_v2, uint32_t active) { +static void active(void* data, zdwl_ipc_output_v2* zdwl_output_v2, uint32_t active) { // Intentionally empty } -static void set_tag(void *data, zdwl_ipc_output_v2 *zdwl_output_v2, uint32_t tag, uint32_t state, +static void set_tag(void* data, zdwl_ipc_output_v2* zdwl_output_v2, uint32_t tag, uint32_t state, uint32_t clients, uint32_t focused) { // Intentionally empty } -static void set_layout_symbol(void *data, zdwl_ipc_output_v2 *zdwl_output_v2, const char *layout) { - static_cast(data)->handle_layout_symbol(layout); +static void set_layout_symbol(void* data, zdwl_ipc_output_v2* zdwl_output_v2, const char* layout) { + static_cast(data)->handle_layout_symbol(layout); } -static void title(void *data, zdwl_ipc_output_v2 *zdwl_output_v2, const char *title) { - static_cast(data)->handle_title(title); +static void title(void* data, zdwl_ipc_output_v2* zdwl_output_v2, const char* title) { + static_cast(data)->handle_title(title); } -static void dwl_frame(void *data, zdwl_ipc_output_v2 *zdwl_output_v2) { - static_cast(data)->handle_frame(); +static void dwl_frame(void* data, zdwl_ipc_output_v2* zdwl_output_v2) { + static_cast(data)->handle_frame(); } -static void set_layout(void *data, zdwl_ipc_output_v2 *zdwl_output_v2, uint32_t layout) { - static_cast(data)->handle_layout(layout); +static void set_layout(void* data, zdwl_ipc_output_v2* zdwl_output_v2, uint32_t layout) { + static_cast(data)->handle_layout(layout); } -static void appid(void *data, zdwl_ipc_output_v2 *zdwl_output_v2, const char *appid) { - static_cast(data)->handle_appid(appid); +static void appid(void* data, zdwl_ipc_output_v2* zdwl_output_v2, const char* appid) { + static_cast(data)->handle_appid(appid); }; static const zdwl_ipc_output_v2_listener output_status_listener_impl{ @@ -58,25 +58,25 @@ static const zdwl_ipc_output_v2_listener output_status_listener_impl{ .frame = dwl_frame, }; -static void handle_global(void *data, struct wl_registry *registry, uint32_t name, - const char *interface, uint32_t version) { +static void handle_global(void* data, struct wl_registry* registry, uint32_t name, + const char* interface, uint32_t version) { if (std::strcmp(interface, zdwl_ipc_manager_v2_interface.name) == 0) { - static_cast(data)->status_manager_ = static_cast( - (zdwl_ipc_manager_v2 *)wl_registry_bind(registry, name, &zdwl_ipc_manager_v2_interface, 1)); + static_cast(data)->status_manager_ = static_cast( + (zdwl_ipc_manager_v2*)wl_registry_bind(registry, name, &zdwl_ipc_manager_v2_interface, 1)); } } -static void handle_global_remove(void *data, struct wl_registry *registry, uint32_t name) { +static void handle_global_remove(void* data, struct wl_registry* registry, uint32_t name) { /* Ignore event */ } static const wl_registry_listener registry_listener_impl = {.global = handle_global, .global_remove = handle_global_remove}; -Window::Window(const std::string &id, const Bar &bar, const Json::Value &config) +Window::Window(const std::string& id, const Bar& bar, const Json::Value& config) : AAppIconLabel(config, "window", id, "{}", 0, true), bar_(bar) { - struct wl_display *display = Client::inst()->wl_display; - struct wl_registry *registry = wl_display_get_registry(display); + struct wl_display* display = Client::inst()->wl_display; + struct wl_registry* registry = wl_display_get_registry(display); wl_registry_add_listener(registry, ®istry_listener_impl, this); wl_display_roundtrip(display); @@ -86,7 +86,7 @@ Window::Window(const std::string &id, const Bar &bar, const Json::Value &config) return; } - struct wl_output *output = gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj()); + struct wl_output* output = gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj()); output_status_ = zdwl_ipc_manager_v2_get_output(status_manager_, output); zdwl_ipc_output_v2_add_listener(output_status_, &output_status_listener_impl, this); zdwl_ipc_manager_v2_destroy(status_manager_); @@ -98,11 +98,11 @@ Window::~Window() { } } -void Window::handle_title(const char *title) { title_ = Glib::Markup::escape_text(title); } +void Window::handle_title(const char* title) { title_ = Glib::Markup::escape_text(title); } -void Window::handle_appid(const char *appid) { appid_ = Glib::Markup::escape_text(appid); } +void Window::handle_appid(const char* appid) { appid_ = Glib::Markup::escape_text(appid); } -void Window::handle_layout_symbol(const char *layout_symbol) { +void Window::handle_layout_symbol(const char* layout_symbol) { layout_symbol_ = Glib::Markup::escape_text(layout_symbol); } @@ -116,7 +116,7 @@ void Window::handle_frame() { updateAppIconName(appid_, ""); updateAppIcon(); if (tooltipEnabled()) { - label_.set_tooltip_text(title_); + label_.set_tooltip_markup(title_); } } diff --git a/src/modules/ext/workspace_manager.cpp b/src/modules/ext/workspace_manager.cpp new file mode 100644 index 00000000..b4471c14 --- /dev/null +++ b/src/modules/ext/workspace_manager.cpp @@ -0,0 +1,506 @@ +#include "modules/ext/workspace_manager.hpp" + +#include +#include +#include + +#include +#include +#include + +#include "client.hpp" +#include "gtkmm/widget.h" +#include "modules/ext/workspace_manager_binding.hpp" + +namespace waybar::modules::ext { + +// WorkspaceManager + +uint32_t WorkspaceManager::group_global_id = 0; +uint32_t WorkspaceManager::workspace_global_id = 0; +std::map Workspace::icon_map_; + +WorkspaceManager::WorkspaceManager(const std::string& id, const waybar::Bar& bar, + const Json::Value& config) + : waybar::AModule(config, "workspaces", id, false, false), bar_(bar), box_(bar.orientation, 0) { + add_registry_listener(this); + + // parse configuration + + const auto config_sort_by_number = config_["sort-by-number"]; + if (config_sort_by_number.isBool()) { + spdlog::warn("[ext/workspaces]: Prefer sort-by-id instead of sort-by-number"); + sort_by_id_ = config_sort_by_number.asBool(); + } + + const auto config_sort_by_id = config_["sort-by-id"]; + if (config_sort_by_id.isBool()) { + sort_by_id_ = config_sort_by_id.asBool(); + } + + const auto config_sort_by_name = config_["sort-by-name"]; + if (config_sort_by_name.isBool()) { + sort_by_name_ = config_sort_by_name.asBool(); + } + + const auto config_sort_by_coordinates = config_["sort-by-coordinates"]; + if (config_sort_by_coordinates.isBool()) { + sort_by_coordinates_ = config_sort_by_coordinates.asBool(); + } + + const auto config_all_outputs = config_["all-outputs"]; + if (config_all_outputs.isBool()) { + all_outputs_ = config_all_outputs.asBool(); + } + + // setup UI + + box_.set_name("workspaces"); + if (!id.empty()) { + box_.get_style_context()->add_class(id); + } + box_.get_style_context()->add_class(MODULE_CLASS); + event_box_.add(box_); + + spdlog::debug("[ext/workspaces]: Workspace manager created"); +} + +WorkspaceManager::~WorkspaceManager() { + workspaces_.clear(); + groups_.clear(); + + if (ext_manager_ != nullptr) { + auto* display = Client::inst()->wl_display; + // Send `stop` request and wait for one roundtrip. + ext_workspace_manager_v1_stop(ext_manager_); + wl_display_roundtrip(display); + } + + if (ext_manager_ != nullptr) { + spdlog::warn("[ext/workspaces]: Destroying workspace manager before .finished event"); + ext_workspace_manager_v1_destroy(ext_manager_); + } + + spdlog::debug("[ext/workspaces]: Workspace manager destroyed"); +} + +void WorkspaceManager::register_manager(wl_registry* registry, uint32_t name, uint32_t version) { + if (ext_manager_ != nullptr) { + spdlog::warn("[ext/workspaces]: Register workspace manager again although already registered!"); + return; + } + if (version != 1) { + spdlog::warn("[ext/workspaces]: Using different workspace manager protocol version: {}", + version); + } + + ext_manager_ = workspace_manager_bind(registry, name, version, this); +} + +void WorkspaceManager::remove_workspace_group(uint32_t id) { + const auto it = + std::find_if(groups_.begin(), groups_.end(), [id](const auto& g) { return g->id() == id; }); + + if (it == groups_.end()) { + spdlog::warn("[ext/workspaces]: Can't find workspace group with id {}", id); + return; + } + + groups_.erase(it); +} + +void WorkspaceManager::remove_workspace(uint32_t id) { + const auto it = std::find_if(workspaces_.begin(), workspaces_.end(), + [id](const auto& w) { return w->id() == id; }); + + if (it == workspaces_.end()) { + spdlog::warn("[ext/workspaces]: Can't find workspace with id {}", id); + return; + } + + workspaces_.erase(it); +} + +void WorkspaceManager::handle_workspace_group(ext_workspace_group_handle_v1* handle) { + const auto new_id = ++group_global_id; + groups_.push_back(std::make_unique(*this, handle, new_id)); + spdlog::debug("[ext/workspaces]: Workspace group {} created", new_id); +} + +void WorkspaceManager::handle_workspace(ext_workspace_handle_v1* handle) { + const auto new_id = ++workspace_global_id; + const auto new_name = std::to_string(++workspace_name); + workspaces_.push_back(std::make_unique(config_, *this, handle, new_id, new_name)); + set_needs_sorting(); + spdlog::debug("[ext/workspaces]: Workspace {} created", new_id); +} + +void WorkspaceManager::handle_done() { dp.emit(); } + +void WorkspaceManager::handle_finished() { + spdlog::debug("[ext/workspaces]: Finishing workspace manager"); + ext_workspace_manager_v1_destroy(ext_manager_); + ext_manager_ = nullptr; +} + +void WorkspaceManager::commit() const { + if (ext_manager_) ext_workspace_manager_v1_commit(ext_manager_); +} + +void WorkspaceManager::update() { + spdlog::debug("[ext/workspaces]: Updating state"); + + if (needs_sorting_) { + clear_buttons(); + sort_workspaces(); + needs_sorting_ = false; + } + + update_buttons(); + AModule::update(); +} + +bool WorkspaceManager::has_button(const Gtk::Button* button) { + const auto buttons = box_.get_children(); + return std::find(buttons.begin(), buttons.end(), button) != buttons.end(); +} + +void WorkspaceManager::sort_workspaces() { + // determine if workspace ID's and names can be sort numerically or literally + + auto is_numeric = [](const std::string& s) { + return !s.empty() && std::all_of(s.begin(), s.end(), ::isdigit); + }; + + auto sort_by_workspace_id_numerically = + std::all_of(workspaces_.begin(), workspaces_.end(), + [&](const auto& w) { return is_numeric(w->workspace_id()); }); + + auto sort_by_name_numerically = std::all_of(workspaces_.begin(), workspaces_.end(), + [&](const auto& w) { return is_numeric(w->name()); }); + + // sort based on configuration setting with sort-by-id as fallback + + std::sort(workspaces_.begin(), workspaces_.end(), [&](const auto& w1, const auto& w2) { + if (sort_by_id_ || (!sort_by_name_ && !sort_by_coordinates_)) { + if (w1->workspace_id() == w2->workspace_id()) { + return w1->id() < w2->id(); + } + if (sort_by_workspace_id_numerically) { + // the idea is that phonetic compare can be applied just to numbers + // with same number of digits + return w1->workspace_id().size() < w2->workspace_id().size() || + (w1->workspace_id().size() == w2->workspace_id().size() && + w1->workspace_id() < w2->workspace_id()); + } + return w1->workspace_id() < w2->workspace_id(); + } + + if (sort_by_name_) { + if (w1->name() == w2->name()) { + return w1->id() < w2->id(); + } + if (sort_by_name_numerically) { + // see above about numeric sorting + return w1->name().size() < w2->name().size() || + (w1->name().size() == w2->name().size() && w1->name() < w2->name()); + } + return w1->name() < w2->name(); + } + + if (sort_by_coordinates_) { + if (w1->coordinates() == w2->coordinates()) { + return w1->id() < w2->id(); + } + return w1->coordinates() < w2->coordinates(); + } + + return w1->id() < w2->id(); + }); +} + +void WorkspaceManager::clear_buttons() { + for (const auto& workspace : workspaces_) { + if (has_button(&workspace->button())) { + box_.remove(workspace->button()); + } + } +} + +void WorkspaceManager::update_buttons() { + const auto* output = gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj()); + + // go through all workspace + + for (const auto& workspace : workspaces_) { + const bool workspace_on_any_group_for_output = + std::any_of(groups_.begin(), groups_.end(), [&](const auto& group) { + const bool group_on_output = group->has_output(output) || all_outputs_; + const bool workspace_on_group = group->has_workspace(workspace->handle()); + return group_on_output && workspace_on_group; + }); + const bool bar_contains_button = has_button(&workspace->button()); + + // add or remove buttons if needed, update button state + + if (workspace_on_any_group_for_output) { + if (!bar_contains_button) { + // add button to bar + box_.pack_start(workspace->button(), false, false); + workspace->button().show_all(); + } + workspace->update(); + } else { + if (bar_contains_button) { + // remove button from bar + box_.remove(workspace->button()); + } + } + } +} + +// WorkspaceGroup + +WorkspaceGroup::WorkspaceGroup(WorkspaceManager& manager, ext_workspace_group_handle_v1* handle, + uint32_t id) + : workspaces_manager_(manager), ext_handle_(handle), id_(id) { + add_workspace_group_listener(ext_handle_, this); +} + +WorkspaceGroup::~WorkspaceGroup() { + if (ext_handle_ != nullptr) { + ext_workspace_group_handle_v1_destroy(ext_handle_); + } + spdlog::debug("[ext/workspaces]: Workspace group {} destroyed", id_); +} + +bool WorkspaceGroup::has_output(const wl_output* output) { + return std::find(outputs_.begin(), outputs_.end(), output) != outputs_.end(); +} + +bool WorkspaceGroup::has_workspace(const ext_workspace_handle_v1* workspace) { + return std::find(workspaces_.begin(), workspaces_.end(), workspace) != workspaces_.end(); +} + +void WorkspaceGroup::handle_capabilities(uint32_t capabilities) { + spdlog::debug("[ext/workspaces]: Capabilities for workspace group {}:", id_); + if ((capabilities & EXT_WORKSPACE_GROUP_HANDLE_V1_GROUP_CAPABILITIES_CREATE_WORKSPACE) == + capabilities) { + spdlog::debug("[ext/workspaces]: - create-workspace"); + } +} + +void WorkspaceGroup::handle_output_enter(wl_output* output) { outputs_.push_back(output); } + +void WorkspaceGroup::handle_output_leave(wl_output* output) { + const auto it = std::find(outputs_.begin(), outputs_.end(), output); + if (it != outputs_.end()) { + outputs_.erase(it); + } +} + +void WorkspaceGroup::handle_workspace_enter(ext_workspace_handle_v1* handle) { + workspaces_.push_back(handle); +} + +void WorkspaceGroup::handle_workspace_leave(ext_workspace_handle_v1* handle) { + const auto it = std::find(workspaces_.begin(), workspaces_.end(), handle); + if (it != workspaces_.end()) { + workspaces_.erase(it); + } +} + +void WorkspaceGroup::handle_removed() { + spdlog::debug("[ext/workspaces]: Removing workspace group {}", id_); + workspaces_manager_.remove_workspace_group(id_); +} + +// Workspace + +Workspace::Workspace(const Json::Value& config, WorkspaceManager& manager, + ext_workspace_handle_v1* handle, uint32_t id, const std::string& name) + : workspace_manager_(manager), ext_handle_(handle), id_(id), workspace_id_(name), name_(name) { + add_workspace_listener(ext_handle_, this); + + // parse configuration + + const auto& config_active_only = config["active-only"]; + if (config_active_only.isBool()) { + active_only_ = config_active_only.asBool(); + } + + const auto& config_ignore_hidden = config["ignore-hidden"]; + if (config_ignore_hidden.isBool()) { + ignore_hidden_ = config_ignore_hidden.asBool(); + } + + const auto& config_format = config["format"]; + format_ = config_format.isString() ? config_format.asString() : "{name}"; + with_icon_ = format_.find("{icon}") != std::string::npos; + + if (with_icon_ && icon_map_.empty()) { + const auto& format_icons = config["format-icons"]; + for (auto& n : format_icons.getMemberNames()) { + icon_map_.emplace(n, format_icons[n].asString()); + } + } + + const bool config_on_click = config["on-click"].isString(); + if (config_on_click) { + on_click_action_ = config["on-click"].asString(); + } + const bool config_on_click_middle = config["on-click-middle"].isString(); + if (config_on_click_middle) { + on_click_middle_action_ = config["on-click-middle"].asString(); + } + const bool config_on_click_right = config["on-click-right"].isString(); + if (config_on_click_right) { + on_click_right_action_ = config["on-click-right"].asString(); + } + + // setup UI + + if (config_on_click || config_on_click_middle || config_on_click_right) { + button_.add_events(Gdk::BUTTON_PRESS_MASK); + button_.signal_button_press_event().connect(sigc::mem_fun(*this, &Workspace::handle_clicked), + false); + } + + button_.set_relief(Gtk::RELIEF_NONE); + content_.set_center_widget(label_); + button_.add(content_); +} + +Workspace::~Workspace() { + if (ext_handle_ != nullptr) { + ext_workspace_handle_v1_destroy(ext_handle_); + } + spdlog::debug("[ext/workspaces]: Workspace {} destroyed", id_); +} + +void Workspace::update() { + const auto style_context = button_.get_style_context(); + + // update style and visibility + + if (!has_state(EXT_WORKSPACE_HANDLE_V1_STATE_ACTIVE)) { + style_context->remove_class("active"); + } + if (!has_state(EXT_WORKSPACE_HANDLE_V1_STATE_URGENT)) { + style_context->remove_class("urgent"); + } + if (!has_state(EXT_WORKSPACE_HANDLE_V1_STATE_HIDDEN)) { + style_context->remove_class("hidden"); + } + + if (has_state(EXT_WORKSPACE_HANDLE_V1_STATE_ACTIVE)) { + button_.set_visible(true); + style_context->add_class("active"); + } + if (has_state(EXT_WORKSPACE_HANDLE_V1_STATE_URGENT)) { + button_.set_visible(true); + style_context->add_class("urgent"); + } + if (has_state(EXT_WORKSPACE_HANDLE_V1_STATE_HIDDEN)) { + button_.set_visible(!active_only_ && !ignore_hidden_); + style_context->add_class("hidden"); + } + if (state_ == 0) { + button_.set_visible(!active_only_); + } + + // update label + label_.set_markup(fmt::format(fmt::runtime(format_), fmt::arg("name", name_), + fmt::arg("id", workspace_id_), + fmt::arg("icon", with_icon_ ? icon() : ""))); +} + +void Workspace::handle_id(const std::string& id) { + spdlog::debug("[ext/workspaces]: ID for workspace {}: {}", id_, id); + workspace_id_ = id; + workspace_manager_.set_needs_sorting(); +} + +void Workspace::handle_name(const std::string& name) { + spdlog::debug("[ext/workspaces]: Name for workspace {}: {}", id_, name); + name_ = name; + workspace_manager_.set_needs_sorting(); +} + +void Workspace::handle_coordinates(const std::vector& coordinates) { + coordinates_ = coordinates; + workspace_manager_.set_needs_sorting(); +} + +void Workspace::handle_state(uint32_t state) { state_ = state; } + +void Workspace::handle_capabilities(uint32_t capabilities) { + spdlog::debug("[ext/workspaces]: Capabilities for workspace {}:", id_); + if ((capabilities & EXT_WORKSPACE_HANDLE_V1_WORKSPACE_CAPABILITIES_ACTIVATE) == capabilities) { + spdlog::debug("[ext/workspaces]: - activate"); + } + if ((capabilities & EXT_WORKSPACE_HANDLE_V1_WORKSPACE_CAPABILITIES_DEACTIVATE) == capabilities) { + spdlog::debug("[ext/workspaces]: - deactivate"); + } + if ((capabilities & EXT_WORKSPACE_HANDLE_V1_WORKSPACE_CAPABILITIES_REMOVE) == capabilities) { + spdlog::debug("[ext/workspaces]: - remove"); + } + if ((capabilities & EXT_WORKSPACE_HANDLE_V1_WORKSPACE_CAPABILITIES_ASSIGN) == capabilities) { + spdlog::debug("[ext/workspaces]: - assign"); + } +} + +void Workspace::handle_removed() { + spdlog::debug("[ext/workspaces]: Removing workspace {}", id_); + workspace_manager_.remove_workspace(id_); +} + +bool Workspace::handle_clicked(const GdkEventButton* button) const { + std::string action; + if (button->button == GDK_BUTTON_PRIMARY) { + action = on_click_action_; + } else if (button->button == GDK_BUTTON_MIDDLE) { + action = on_click_middle_action_; + } else if (button->button == GDK_BUTTON_SECONDARY) { + action = on_click_right_action_; + } + + if (action.empty()) { + return true; + } + + if (action == "activate") { + ext_workspace_handle_v1_activate(ext_handle_); + } else if (action == "deactivate") { + ext_workspace_handle_v1_deactivate(ext_handle_); + } else if (action == "close") { + ext_workspace_handle_v1_remove(ext_handle_); + } else { + spdlog::warn("[ext/workspaces]: Unknown action {}", action); + } + workspace_manager_.commit(); + return true; +} + +std::string Workspace::icon() { + if (has_state(EXT_WORKSPACE_HANDLE_V1_STATE_ACTIVE)) { + const auto active_icon_it = icon_map_.find("active"); + if (active_icon_it != icon_map_.end()) { + return active_icon_it->second; + } + } + + const auto named_icon_it = icon_map_.find(name_); + if (named_icon_it != icon_map_.end()) { + return named_icon_it->second; + } + + const auto default_icon_it = icon_map_.find("default"); + if (default_icon_it != icon_map_.end()) { + return default_icon_it->second; + } + + return name_; +} + +} // namespace waybar::modules::ext diff --git a/src/modules/ext/workspace_manager_binding.cpp b/src/modules/ext/workspace_manager_binding.cpp new file mode 100644 index 00000000..91110faf --- /dev/null +++ b/src/modules/ext/workspace_manager_binding.cpp @@ -0,0 +1,159 @@ +#include "modules/ext/workspace_manager_binding.hpp" + +#include + +#include + +#include "client.hpp" +#include "modules/ext/workspace_manager.hpp" + +namespace waybar::modules::ext { + +static void handle_global(void* data, wl_registry* registry, uint32_t name, const char* interface, + uint32_t version) { + if (std::strcmp(interface, ext_workspace_manager_v1_interface.name) == 0) { + static_cast(data)->register_manager(registry, name, version); + } +} + +static void handle_global_remove(void* data, wl_registry* registry, uint32_t name) { + /* Nothing to do here */ +} + +static const wl_registry_listener registry_listener_impl = {.global = handle_global, + .global_remove = handle_global_remove}; + +void add_registry_listener(void* data) { + wl_display* display = Client::inst()->wl_display; + wl_registry* registry = wl_display_get_registry(display); + + wl_registry_add_listener(registry, ®istry_listener_impl, data); + wl_display_roundtrip(display); +} + +static void workspace_manager_handle_workspace_group( + void* data, ext_workspace_manager_v1* _, ext_workspace_group_handle_v1* workspace_group) { + static_cast(data)->handle_workspace_group(workspace_group); +} + +static void workspace_manager_handle_workspace(void* data, ext_workspace_manager_v1* _, + ext_workspace_handle_v1* workspace) { + static_cast(data)->handle_workspace(workspace); +} + +static void workspace_manager_handle_done(void* data, ext_workspace_manager_v1* _) { + static_cast(data)->handle_done(); +} + +static void workspace_manager_handle_finished(void* data, ext_workspace_manager_v1* _) { + static_cast(data)->handle_finished(); +} + +static const ext_workspace_manager_v1_listener workspace_manager_impl = { + .workspace_group = workspace_manager_handle_workspace_group, + .workspace = workspace_manager_handle_workspace, + .done = workspace_manager_handle_done, + .finished = workspace_manager_handle_finished, +}; + +ext_workspace_manager_v1* workspace_manager_bind(wl_registry* registry, uint32_t name, + uint32_t version, void* data) { + auto* workspace_manager = static_cast( + wl_registry_bind(registry, name, &ext_workspace_manager_v1_interface, version)); + + if (workspace_manager) + ext_workspace_manager_v1_add_listener(workspace_manager, &workspace_manager_impl, data); + else + spdlog::error("Failed to register manager"); + + return workspace_manager; +} + +static void workspace_group_handle_capabilities(void* data, ext_workspace_group_handle_v1* _, + uint32_t capabilities) { + static_cast(data)->handle_capabilities(capabilities); +} + +static void workspace_group_handle_output_enter(void* data, ext_workspace_group_handle_v1* _, + wl_output* output) { + static_cast(data)->handle_output_enter(output); +} + +static void workspace_group_handle_output_leave(void* data, ext_workspace_group_handle_v1* _, + wl_output* output) { + static_cast(data)->handle_output_leave(output); +} + +static void workspace_group_handle_workspace_enter(void* data, ext_workspace_group_handle_v1* _, + ext_workspace_handle_v1* workspace) { + static_cast(data)->handle_workspace_enter(workspace); +} + +static void workspace_group_handle_workspace_leave(void* data, ext_workspace_group_handle_v1* _, + ext_workspace_handle_v1* workspace) { + static_cast(data)->handle_workspace_leave(workspace); +} + +static void workspace_group_handle_removed(void* data, ext_workspace_group_handle_v1* _) { + static_cast(data)->handle_removed(); +} + +static const ext_workspace_group_handle_v1_listener workspace_group_impl = { + .capabilities = workspace_group_handle_capabilities, + .output_enter = workspace_group_handle_output_enter, + .output_leave = workspace_group_handle_output_leave, + .workspace_enter = workspace_group_handle_workspace_enter, + .workspace_leave = workspace_group_handle_workspace_leave, + .removed = workspace_group_handle_removed}; + +void add_workspace_group_listener(ext_workspace_group_handle_v1* workspace_group_handle, + void* data) { + ext_workspace_group_handle_v1_add_listener(workspace_group_handle, &workspace_group_impl, data); +} + +void workspace_handle_name(void* data, struct ext_workspace_handle_v1* _, const char* name) { + static_cast(data)->handle_name(name); +} + +void workspace_handle_id(void* data, struct ext_workspace_handle_v1* _, const char* id) { + static_cast(data)->handle_id(id); +} + +void workspace_handle_coordinates(void* data, struct ext_workspace_handle_v1* _, + struct wl_array* coordinates) { + std::vector coords_vec; + auto coords = static_cast(coordinates->data); + for (size_t i = 0; i < coordinates->size / sizeof(uint32_t); ++i) { + coords_vec.push_back(coords[i]); + } + + static_cast(data)->handle_coordinates(coords_vec); +} + +void workspace_handle_state(void* data, struct ext_workspace_handle_v1* workspace_handle, + uint32_t state) { + static_cast(data)->handle_state(state); +} + +static void workspace_handle_capabilities(void* data, + struct ext_workspace_handle_v1* workspace_handle, + uint32_t capabilities) { + static_cast(data)->handle_capabilities(capabilities); +} + +void workspace_handle_removed(void* data, struct ext_workspace_handle_v1* workspace_handle) { + static_cast(data)->handle_removed(); +} + +static const ext_workspace_handle_v1_listener workspace_impl = { + .id = workspace_handle_id, + .name = workspace_handle_name, + .coordinates = workspace_handle_coordinates, + .state = workspace_handle_state, + .capabilities = workspace_handle_capabilities, + .removed = workspace_handle_removed}; + +void add_workspace_listener(ext_workspace_handle_v1* workspace_handle, void* data) { + ext_workspace_handle_v1_add_listener(workspace_handle, &workspace_impl, data); +} +} // namespace waybar::modules::ext diff --git a/src/modules/gamemode.cpp b/src/modules/gamemode.cpp index 811f13ca..691a2844 100644 --- a/src/modules/gamemode.cpp +++ b/src/modules/gamemode.cpp @@ -53,7 +53,6 @@ Gamemode::Gamemode(const std::string& id, const Json::Value& config) if (config_["icon-spacing"].isUInt()) { iconSpacing = config_["icon-spacing"].asUInt(); } - box_.set_spacing(iconSpacing); // Whether to use icon or not if (config_["use-icon"].isBool()) { @@ -64,7 +63,6 @@ Gamemode::Gamemode(const std::string& id, const Json::Value& config) if (config_["icon-size"].isUInt()) { iconSize = config_["icon-size"].asUInt(); } - icon_.set_pixel_size(iconSize); // Format if (config_["format"].isString()) { @@ -130,9 +128,9 @@ void Gamemode::getData() { Glib::VariantContainerBase data = gamemode_proxy->call_sync("Get", parameters); if (data && data.is_of_type(Glib::VariantType("(v)"))) { Glib::VariantBase variant; - g_variant_get(data.gobj_copy(), "(v)", &variant); + g_variant_get(const_cast(data.gobj()), "(v)", &variant); if (variant && variant.is_of_type(Glib::VARIANT_TYPE_INT32)) { - g_variant_get(variant.gobj_copy(), "i", &gameCount); + g_variant_get(const_cast(variant.gobj()), "i", &gameCount); return; } } @@ -160,7 +158,7 @@ void Gamemode::prepareForSleep_cb(const Glib::RefPtr& con const Glib::VariantContainerBase& parameters) { if (parameters.is_of_type(Glib::VariantType("(b)"))) { gboolean sleeping; - g_variant_get(parameters.gobj_copy(), "(b)", &sleeping); + g_variant_get(const_cast(parameters.gobj()), "(b)", &sleeping); if (!sleeping) { getData(); dp.emit(); @@ -214,7 +212,7 @@ auto Gamemode::update() -> void { // Tooltip if (tooltip) { std::string text = fmt::format(fmt::runtime(tooltip_format), fmt::arg("count", gameCount)); - box_.set_tooltip_text(text); + box_.set_tooltip_markup(text); } // Label format @@ -228,6 +226,11 @@ auto Gamemode::update() -> void { iconName = DEFAULT_ICON_NAME; } icon_.set_from_icon_name(iconName, Gtk::ICON_SIZE_INVALID); + box_.set_spacing(iconSpacing); + icon_.set_pixel_size(iconSize); + } else { + box_.set_spacing(0); + icon_.set_pixel_size(0); } // Call parent update diff --git a/src/modules/gps.cpp b/src/modules/gps.cpp new file mode 100644 index 00000000..a7bab659 --- /dev/null +++ b/src/modules/gps.cpp @@ -0,0 +1,216 @@ +#include "modules/gps.hpp" + +#include +#include + +#include +#include + +// In the 80000 version of fmt library authors decided to optimize imports +// and moved declarations required for fmt::dynamic_format_arg_store in new +// header fmt/args.h +#if (FMT_VERSION >= 80000) +#include +#else +#include +#endif + +namespace { +using namespace waybar::util; +constexpr const char* DEFAULT_FORMAT = "{mode}"; +} // namespace + +waybar::modules::Gps::Gps(const std::string& id, const Json::Value& config) + : ALabel(config, "gps", id, "{}", 5) +#ifdef WANT_RFKILL + , + rfkill_{RFKILL_TYPE_GPS} +#endif +{ + thread_ = [this] { + dp.emit(); + thread_.sleep_for(interval_); + }; + + if (0 != gps_open("localhost", "2947", &gps_data_)) { + throw std::runtime_error("Can't open gpsd socket"); + } + + if (config_["hide-disconnected"].isBool()) { + hideDisconnected = config_["hide-disconnected"].asBool(); + } + + if (config_["hide-no-fix"].isBool()) { + hideNoFix = config_["hide-no-fix"].asBool(); + } + + gps_thread_ = [this] { + dp.emit(); + gps_stream(&gps_data_, WATCH_ENABLE, NULL); + int last_gps_mode = 0; + + while (gps_waiting(&gps_data_, 5000000)) { + if (gps_read(&gps_data_, NULL, 0) == -1) { + throw std::runtime_error("Can't read data from gpsd."); + } + + if (MODE_SET != (MODE_SET & gps_data_.set)) { + // did not even get mode, nothing to see here + continue; + } + + if (gps_data_.fix.mode != last_gps_mode) { + // significant update + dp.emit(); + } + last_gps_mode = gps_data_.fix.mode; + } + }; + +#ifdef WANT_RFKILL + rfkill_.on_update.connect(sigc::hide(sigc::mem_fun(*this, &Gps::update))); +#endif +} + +const std::string waybar::modules::Gps::getFixModeName() const { + switch (gps_data_.fix.mode) { + case MODE_NO_FIX: + return "fix-none"; + case MODE_2D: + return "fix-2d"; + case MODE_3D: + return "fix-3d"; + default: +#ifdef WANT_RFKILL + if (rfkill_.getState()) return "disabled"; +#endif + return "disconnected"; + } +} + +const std::string waybar::modules::Gps::getFixModeString() const { + switch (gps_data_.fix.mode) { + case MODE_NO_FIX: + return "No fix"; + case MODE_2D: + return "2D Fix"; + case MODE_3D: + return "3D Fix"; + default: + return "Disconnected"; + } +} + +const std::string waybar::modules::Gps::getFixStatusString() const { + switch (gps_data_.fix.status) { + case STATUS_GPS: + return "GPS"; + case STATUS_DGPS: + return "DGPS"; + case STATUS_RTK_FIX: + return "RTK Fixed"; + case STATUS_RTK_FLT: + return "RTK Float"; + case STATUS_DR: + return "Dead Reckoning"; + case STATUS_GNSSDR: + return "GNSS + Dead Reckoning"; + case STATUS_TIME: + return "Time Only"; + case STATUS_PPS_FIX: + return "PPS Fix"; + default: + +#ifdef WANT_RFKILL + if (rfkill_.getState()) return "Disabled"; +#endif + + return "Unknown"; + } +} + +auto waybar::modules::Gps::update() -> void { + sleep(0); // Wait for gps status change + + if ((gps_data_.fix.mode == MODE_NOT_SEEN && hideDisconnected) || + (gps_data_.fix.mode == MODE_NO_FIX && hideNoFix)) { + event_box_.set_visible(false); + return; + } + + // Show the module + if (!event_box_.get_visible()) event_box_.set_visible(true); + + std::string tooltip_format; + + if (!alt_) { + auto state = getFixModeName(); + if (!state_.empty() && label_.get_style_context()->has_class(state_)) { + label_.get_style_context()->remove_class(state_); + } + if (config_["format-" + state].isString()) { + default_format_ = config_["format-" + state].asString(); + } else if (config_["format"].isString()) { + default_format_ = config_["format"].asString(); + } else { + default_format_ = DEFAULT_FORMAT; + } + if (config_["tooltip-format-" + state].isString()) { + tooltip_format = config_["tooltip-format-" + state].asString(); + } + if (!label_.get_style_context()->has_class(state)) { + label_.get_style_context()->add_class(state); + } + format_ = default_format_; + state_ = state; + } + + auto format = format_; + + fmt::dynamic_format_arg_store store; + store.push_back(fmt::arg("mode", getFixModeString())); + store.push_back(fmt::arg("status", getFixStatusString())); + + store.push_back(fmt::arg("latitude", gps_data_.fix.latitude)); + store.push_back(fmt::arg("latitude_error", gps_data_.fix.epy)); + + store.push_back(fmt::arg("longitude", gps_data_.fix.longitude)); + store.push_back(fmt::arg("longitude_error", gps_data_.fix.epx)); + + store.push_back(fmt::arg("altitude_hae", gps_data_.fix.altHAE)); + store.push_back(fmt::arg("altitude_msl", gps_data_.fix.altMSL)); + store.push_back(fmt::arg("altitude_error", gps_data_.fix.epv)); + + store.push_back(fmt::arg("speed", gps_data_.fix.speed)); + store.push_back(fmt::arg("speed_error", gps_data_.fix.eps)); + + store.push_back(fmt::arg("climb", gps_data_.fix.climb)); + store.push_back(fmt::arg("climb_error", gps_data_.fix.epc)); + + store.push_back(fmt::arg("satellites_used", gps_data_.satellites_used)); + store.push_back(fmt::arg("satellites_visible", gps_data_.satellites_visible)); + + auto text = fmt::vformat(format, store); + + if (tooltipEnabled()) { + if (tooltip_format.empty() && config_["tooltip-format"].isString()) { + tooltip_format = config_["tooltip-format"].asString(); + } + if (!tooltip_format.empty()) { + auto tooltip_text = fmt::vformat(tooltip_format, store); + if (label_.get_tooltip_text() != tooltip_text) { + label_.set_tooltip_markup(tooltip_text); + } + } else if (label_.get_tooltip_text() != text) { + label_.set_tooltip_markup(text); + } + } + label_.set_markup(text); + // Call parent update + ALabel::update(); +} + +waybar::modules::Gps::~Gps() { + gps_stream(&gps_data_, WATCH_DISABLE, NULL); + gps_close(&gps_data_); +} diff --git a/src/modules/hyprland/backend.cpp b/src/modules/hyprland/backend.cpp index 2bd3b509..f38f8216 100644 --- a/src/modules/hyprland/backend.cpp +++ b/src/modules/hyprland/backend.cpp @@ -9,59 +9,68 @@ #include #include +#include +#include +#include #include +#include #include +#include "util/scoped_fd.hpp" + namespace waybar::modules::hyprland { std::filesystem::path IPC::socketFolder_; +std::optional IPC::s_luaProtocolDetected_; std::filesystem::path IPC::getSocketFolder(const char* instanceSig) { static std::mutex folderMutex; std::unique_lock lock(folderMutex); - // socket path, specified by EventManager of Hyprland - if (!socketFolder_.empty()) { - return socketFolder_; + if (socketFolder_.empty()) { + const char* xdgRuntimeDirEnv = std::getenv("XDG_RUNTIME_DIR"); + std::filesystem::path xdgRuntimeDir; + // Only set path if env variable is set + if (xdgRuntimeDirEnv != nullptr) { + xdgRuntimeDir = std::filesystem::path(xdgRuntimeDirEnv); + } + + if (!xdgRuntimeDir.empty() && std::filesystem::exists(xdgRuntimeDir / "hypr")) { + socketFolder_ = xdgRuntimeDir / "hypr"; + } else { + spdlog::warn("$XDG_RUNTIME_DIR/hypr does not exist, falling back to /tmp/hypr"); + socketFolder_ = std::filesystem::path("/tmp") / "hypr"; + } } - const char* xdgRuntimeDirEnv = std::getenv("XDG_RUNTIME_DIR"); - std::filesystem::path xdgRuntimeDir; - // Only set path if env variable is set - if (xdgRuntimeDirEnv != nullptr) { - xdgRuntimeDir = std::filesystem::path(xdgRuntimeDirEnv); - } - - if (!xdgRuntimeDir.empty() && std::filesystem::exists(xdgRuntimeDir / "hypr")) { - socketFolder_ = xdgRuntimeDir / "hypr"; - } else { - spdlog::warn("$XDG_RUNTIME_DIR/hypr does not exist, falling back to /tmp/hypr"); - socketFolder_ = std::filesystem::path("/tmp") / "hypr"; - } - - socketFolder_ = socketFolder_ / instanceSig; - return socketFolder_; + return socketFolder_ / instanceSig; } IPC::IPC() { // will start IPC and relay events to parseIPC + socketOwnerPid_ = getpid(); ipcThread_ = std::thread([this]() { socketListener(); }); } IPC::~IPC() { - running_ = false; + // Do no stop Hyprland IPC if a child process (with successful fork() but + // failed exec()) exits. + if (getpid() != socketOwnerPid_) return; + + running_.store(false, std::memory_order_relaxed); spdlog::info("Hyprland IPC stopping..."); - if (socketfd_ != -1) { - spdlog::trace("Shutting down socket"); - if (shutdown(socketfd_, SHUT_RDWR) == -1) { - spdlog::error("Hyprland IPC: Couldn't shutdown socket"); - } - spdlog::trace("Closing socket"); - if (close(socketfd_) == -1) { - spdlog::error("Hyprland IPC: Couldn't close socket"); + { + std::lock_guard lock(socketMutex_); + if (socketfd_ != -1) { + spdlog::trace("Shutting down socket"); + if (shutdown(socketfd_, SHUT_RDWR) == -1 && errno != ENOTCONN) { + spdlog::error("Hyprland IPC: Couldn't shutdown socket"); + } } } - ipcThread_.join(); + if (ipcThread_.joinable()) { + ipcThread_.join(); + } } IPC& IPC::inst() { @@ -78,14 +87,12 @@ void IPC::socketListener() { return; } - if (!modulesReady) return; - spdlog::info("Hyprland IPC starting"); - struct sockaddr_un addr; - socketfd_ = socket(AF_UNIX, SOCK_STREAM, 0); + struct sockaddr_un addr = {}; + const int socketfd = socket(AF_UNIX, SOCK_STREAM, 0); - if (socketfd_ == -1) { + if (socketfd == -1) { spdlog::error("Hyprland IPC: socketfd failed"); return; } @@ -93,44 +100,76 @@ void IPC::socketListener() { addr.sun_family = AF_UNIX; auto socketPath = IPC::getSocketFolder(his) / ".socket2.sock"; + if (socketPath.native().size() >= sizeof(addr.sun_path)) { + spdlog::error("Hyprland IPC: Socket path is too long: {}", socketPath.string()); + close(socketfd); + return; + } strncpy(addr.sun_path, socketPath.c_str(), sizeof(addr.sun_path) - 1); - addr.sun_path[sizeof(addr.sun_path) - 1] = 0; - int l = sizeof(struct sockaddr_un); - if (connect(socketfd_, (struct sockaddr*)&addr, l) == -1) { - spdlog::error("Hyprland IPC: Unable to connect?"); + if (connect(socketfd, (struct sockaddr*)&addr, l) == -1) { + spdlog::error("Hyprland IPC: Unable to connect? {}", std::strerror(errno)); + close(socketfd); return; } - auto* file = fdopen(socketfd_, "r"); - if (file == nullptr) { - spdlog::error("Hyprland IPC: Couldn't open file descriptor"); - return; + + { + std::lock_guard lock(socketMutex_); + socketfd_ = socketfd; } - while (running_) { + + std::string pending; + while (running_.load(std::memory_order_relaxed)) { std::array buffer; // Hyprland socket2 events are max 1024 bytes + const ssize_t bytes_read = read(socketfd, buffer.data(), buffer.size()); - auto* receivedCharPtr = fgets(buffer.data(), buffer.size(), file); - - if (receivedCharPtr == nullptr) { - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - continue; + if (bytes_read == 0) { + if (running_.load(std::memory_order_relaxed)) { + spdlog::warn("Hyprland IPC: Socket closed by peer"); + } + break; } - std::string messageReceived(buffer.data()); - messageReceived = messageReceived.substr(0, messageReceived.find_first_of('\n')); - spdlog::debug("hyprland IPC received {}", messageReceived); - - try { - parseIPC(messageReceived); - } catch (std::exception& e) { - spdlog::warn("Failed to parse IPC message: {}, reason: {}", messageReceived, e.what()); - } catch (...) { - throw; + if (bytes_read < 0) { + if (errno == EINTR) { + continue; + } + if (!running_.load(std::memory_order_relaxed)) { + break; + } + spdlog::error("Hyprland IPC: read failed: {}", std::strerror(errno)); + break; } - std::this_thread::sleep_for(std::chrono::milliseconds(1)); + pending.append(buffer.data(), static_cast(bytes_read)); + for (auto newline_pos = pending.find('\n'); newline_pos != std::string::npos; + newline_pos = pending.find('\n')) { + std::string messageReceived = pending.substr(0, newline_pos); + pending.erase(0, newline_pos + 1); + if (messageReceived.empty()) { + continue; + } + spdlog::debug("hyprland IPC received {}", messageReceived); + + try { + parseIPC(messageReceived); + } catch (std::exception& e) { + spdlog::warn("Failed to parse IPC message: {}, reason: {}", messageReceived, e.what()); + } catch (...) { + throw; + } + } + } + { + std::lock_guard lock(socketMutex_); + if (socketfd_ != -1) { + if (close(socketfd_) == -1) { + spdlog::error("Hyprland IPC: Couldn't close socket"); + } + socketfd_ = -1; + } } spdlog::debug("Hyprland IPC stopped"); } @@ -175,7 +214,7 @@ void IPC::unregisterForIPC(EventHandler* ev_handler) { std::string IPC::getSocket1Reply(const std::string& rq) { // basically hyprctl - const auto serverSocket = socket(AF_UNIX, SOCK_STREAM, 0); + util::ScopedFd serverSocket(socket(AF_UNIX, SOCK_STREAM, 0)); if (serverSocket < 0) { throw std::runtime_error("Hyprland IPC: Couldn't open a socket (1)"); @@ -195,8 +234,10 @@ std::string IPC::getSocket1Reply(const std::string& rq) { std::string socketPath = IPC::getSocketFolder(instanceSig) / ".socket.sock"; // Use snprintf to copy the socketPath string into serverAddress.sun_path - if (snprintf(serverAddress.sun_path, sizeof(serverAddress.sun_path), "%s", socketPath.c_str()) < - 0) { + const auto socketPathLength = + snprintf(serverAddress.sun_path, sizeof(serverAddress.sun_path), "%s", socketPath.c_str()); + if (socketPathLength < 0 || + socketPathLength >= static_cast(sizeof(serverAddress.sun_path))) { throw std::runtime_error("Hyprland IPC: Couldn't copy socket path (6)"); } @@ -205,28 +246,39 @@ std::string IPC::getSocket1Reply(const std::string& rq) { throw std::runtime_error("Hyprland IPC: Couldn't connect to " + socketPath + ". (3)"); } - auto sizeWritten = write(serverSocket, rq.c_str(), rq.length()); + std::size_t totalWritten = 0; + while (totalWritten < rq.length()) { + const auto sizeWritten = + write(serverSocket, rq.c_str() + totalWritten, rq.length() - totalWritten); - if (sizeWritten < 0) { - spdlog::error("Hyprland IPC: Couldn't write (4)"); - return ""; + if (sizeWritten < 0) { + if (errno == EINTR) { + continue; + } + spdlog::error("Hyprland IPC: Couldn't write (4)"); + return ""; + } + if (sizeWritten == 0) { + spdlog::error("Hyprland IPC: Socket write made no progress"); + return ""; + } + totalWritten += static_cast(sizeWritten); } std::array buffer = {0}; std::string response; + ssize_t sizeWritten = 0; do { sizeWritten = read(serverSocket, buffer.data(), 8192); if (sizeWritten < 0) { spdlog::error("Hyprland IPC: Couldn't read (5)"); - close(serverSocket); return ""; } response.append(buffer.data(), sizeWritten); } while (sizeWritten > 0); - close(serverSocket); return response; } @@ -240,4 +292,69 @@ Json::Value IPC::getSocket1JsonReply(const std::string& rq) { return parser_.parse(reply); } +bool IPC::isLuaProtocol() { + if (s_luaProtocolDetected_.has_value()) { + return *s_luaProtocolDetected_; + } + + // Probe: send a harmless old-style dispatch and check the error. + // In Lua-based Hyprland (>= 0.54) the error contains "hl.dispatch". + // In older versions it returns "ok" or a different error. + auto reply = getSocket1Reply("dispatch workspace __waybar_probe__"); + bool luaProto = reply.find("hl.dispatch") != std::string::npos; + + if (luaProto) { + spdlog::info("Hyprland IPC: detected Lua-based dispatch protocol (Hyprland >= 0.54)"); + } else { + spdlog::info("Hyprland IPC: detected legacy dispatch protocol"); + } + + s_luaProtocolDetected_ = luaProto; + return luaProto; +} + +std::string IPC::buildLuaDispatch(const std::string& dispatcher, const std::string& arg) { + // Map old-style dispatchers to the new Lua hl.dsp API. + // + // Old format: dispatch workspace 1 + // New format: /dispatch hl.dsp.focus({ workspace = "1" }) + // + // Old format: dispatch focusworkspaceoncurrentmonitor 2 + // New format: /dispatch hl.dsp.focus({ workspace = "2", on_current_monitor = true }) + // + // Old format: dispatch togglespecialworkspace name + // New format: /dispatch hl.dsp.workspace.toggle_special("name") + + if (dispatcher == "workspace") { + return "/dispatch hl.dsp.focus({ workspace = \"" + arg + "\" })"; + } + if (dispatcher == "focusworkspaceoncurrentmonitor") { + return "/dispatch hl.dsp.focus({ workspace = \"" + arg + "\", on_current_monitor = true })"; + } + if (dispatcher == "togglespecialworkspace") { + if (arg.empty()) { + return "/dispatch hl.dsp.workspace.toggle_special()"; + } + return "/dispatch hl.dsp.workspace.toggle_special(\"" + arg + "\")"; + } + + // Fallback for any other dispatcher: try the old format wrapped in dispatch(). + // This may not work for all dispatchers, but it's a reasonable default. + spdlog::warn("Hyprland IPC: unknown dispatcher '{}' in Lua mode, attempting generic format", + dispatcher); + return "/dispatch hl.dsp." + dispatcher + "(\"" + arg + "\")"; +} + +std::string IPC::dispatch(const std::string& dispatcher, const std::string& arg) { + if (isLuaProtocol()) { + return getSocket1Reply(buildLuaDispatch(dispatcher, arg)); + } + // Legacy format: "dispatch " + std::string cmd = "dispatch " + dispatcher; + if (!arg.empty()) { + cmd += " " + arg; + } + return getSocket1Reply(cmd); +} + } // namespace waybar::modules::hyprland diff --git a/src/modules/hyprland/language.cpp b/src/modules/hyprland/language.cpp index da56e578..e413f578 100644 --- a/src/modules/hyprland/language.cpp +++ b/src/modules/hyprland/language.cpp @@ -11,8 +11,6 @@ namespace waybar::modules::hyprland { Language::Language(const std::string& id, const Bar& bar, const Json::Value& config) : ALabel(config, "language", id, "{}", 0, true), bar_(bar), m_ipc(IPC::inst()) { - modulesReady = true; - // get the active layout when open initLanguage(); @@ -50,12 +48,39 @@ auto Language::update() -> void { fmt::arg("shortDescription", layout_.short_description), fmt::arg("variant", layout_.variant))); } - spdlog::debug("hyprland language formatted layout name {}", layoutName); + std::string tooltipContent = std::string{}; + bool tooltip_enabled = tooltipEnabled(); + if (tooltip_enabled) { + if (config_.isMember("tooltip-format")) { + auto tooltip_format = config_["tooltip-format"].asString(); + if (config_.isMember("tooltip-format-" + layout_.short_description + "-" + layout_.variant)) { + const auto propName = "tooltip-format-" + layout_.short_description + "-" + layout_.variant; + tooltipContent = fmt::format(fmt::runtime(tooltip_format), config_[propName].asString()); + } else if (config_.isMember("tooltip-format-" + layout_.short_description)) { + const auto propName = "tooltip-format-" + layout_.short_description; + tooltipContent = fmt::format(fmt::runtime(tooltip_format), config_[propName].asString()); + } else { + tooltipContent = + trim(fmt::format(fmt::runtime(tooltip_format), fmt::arg("long", layout_.full_name), + fmt::arg("short", layout_.short_name), + fmt::arg("shortDescription", layout_.short_description), + fmt::arg("variant", layout_.variant))); + } + } else { + // if no tooltip format is provided, use the same text as the module + tooltipContent = layoutName; + } + spdlog::debug("hyprland language formatted tooltip content {}", tooltipContent); + } + if (!format_.empty()) { label_.show(); label_.set_markup(layoutName); + if (tooltip_enabled) { + label_.set_tooltip_markup(tooltipContent); + } } else { label_.hide(); } @@ -65,11 +90,43 @@ auto Language::update() -> void { void Language::onEvent(const std::string& ev) { std::lock_guard lg(mutex_); - std::string kbName(begin(ev) + ev.find_last_of('>') + 1, begin(ev) + ev.find_first_of(',')); - auto layoutName = ev.substr(ev.find_last_of(',') + 1); + const auto payloadStart = ev.find(">>"); + if (payloadStart == std::string::npos) { + spdlog::warn("hyprland language received malformed event: {}", ev); + return; + } + const auto payload = ev.substr(payloadStart + 2); + const auto kbSeparator = payload.find(','); + if (kbSeparator == std::string::npos) { + spdlog::warn("hyprland language received malformed event payload: {}", ev); + return; + } + // Last comma before variants parenthesis, eg: + // activelayout>>micro-star-int'l-co.,-ltd.-msi-gk50-elite-gaming-keyboard,English (US, intl., + // with dead keys) + std::string beforeParenthesis; + auto parenthesisPos = payload.find_last_of('('); + if (parenthesisPos == std::string::npos) { + beforeParenthesis = payload; + } else { + beforeParenthesis = payload.substr(0, parenthesisPos); + } + const auto layoutSeparator = beforeParenthesis.find_last_of(','); + if (layoutSeparator == std::string::npos) { + spdlog::warn("hyprland language received malformed layout payload: {}", ev); + return; + } + auto layoutName = payload.substr(layoutSeparator + 1); - if (config_.isMember("keyboard-name") && kbName != config_["keyboard-name"].asString()) - return; // ignore + if (config_.isMember("keyboard-name")) { + const auto keyboardName = config_["keyboard-name"].asString(); + // The keyboard name itself can contain commas, so match it as a full prefix + // (followed by the ',' separator) rather than comparing against the substring + // before the first comma, which would truncate such names and drop the event. + if (payload.size() <= keyboardName.size() || payload[keyboardName.size()] != ',' || + payload.compare(0, keyboardName.size(), keyboardName) != 0) + return; // ignore + } layoutName = waybar::util::sanitize_string(layoutName); diff --git a/src/modules/hyprland/submap.cpp b/src/modules/hyprland/submap.cpp index 97c4bb62..36b9bf79 100644 --- a/src/modules/hyprland/submap.cpp +++ b/src/modules/hyprland/submap.cpp @@ -2,21 +2,17 @@ #include -#include "util/sanitize_str.hpp" - namespace waybar::modules::hyprland { Submap::Submap(const std::string& id, const Bar& bar, const Json::Value& config) : ALabel(config, "submap", id, "{}", 0, true), bar_(bar), m_ipc(IPC::inst()) { - modulesReady = true; - parseConfig(config); label_.hide(); ALabel::update(); // Displays widget immediately if always_on_ assuming default submap - // Needs an actual way to retrive current submap on startup + // Needs an actual way to retrieve current submap on startup if (always_on_) { submap_ = default_submap_; label_.get_style_context()->add_class(submap_); @@ -48,12 +44,23 @@ auto Submap::parseConfig(const Json::Value& config) -> void { auto Submap::update() -> void { std::lock_guard lg(mutex_); + // Handle style class changes + if (!prev_submap_.empty()) { + label_.get_style_context()->remove_class(prev_submap_); + } + + if (!submap_.empty()) { + label_.get_style_context()->add_class(submap_); + } + + prev_submap_ = submap_; + if (submap_.empty()) { event_box_.hide(); } else { label_.set_markup(fmt::format(fmt::runtime(format_), submap_)); if (tooltipEnabled()) { - label_.set_tooltip_text(submap_); + label_.set_tooltip_markup(submap_); } event_box_.show(); } @@ -68,12 +75,12 @@ void Submap::onEvent(const std::string& ev) { return; } - auto submapName = ev.substr(ev.find_last_of('>') + 1); - submapName = waybar::util::sanitize_string(submapName); - - if (!submap_.empty()) { - label_.get_style_context()->remove_class(submap_); + const auto separator = ev.find(">>"); + if (separator == std::string::npos) { + spdlog::warn("hyprland submap received malformed event: {}", ev); + return; } + auto submapName = ev.substr(separator + 2); submap_ = submapName; @@ -81,8 +88,6 @@ void Submap::onEvent(const std::string& ev) { submap_ = default_submap_; } - label_.get_style_context()->add_class(submap_); - spdlog::debug("hyprland submap onevent with {}", submap_); dp.emit(); diff --git a/src/modules/hyprland/window.cpp b/src/modules/hyprland/window.cpp index 815fbad8..029f9722 100644 --- a/src/modules/hyprland/window.cpp +++ b/src/modules/hyprland/window.cpp @@ -1,5 +1,6 @@ #include "modules/hyprland/window.hpp" +#include #include #include #include @@ -19,22 +20,19 @@ std::shared_mutex windowIpcSmtx; Window::Window(const std::string& id, const Bar& bar, const Json::Value& config) : AAppIconLabel(config, "window", id, "{title}", 0, true), bar_(bar), m_ipc(IPC::inst()) { - std::unique_lock windowIpcUniqueLock(windowIpcSmtx); - - modulesReady = true; separateOutputs_ = config["separate-outputs"].asBool(); + update(); + // register for hyprland ipc + std::unique_lock windowIpcUniqueLock(windowIpcSmtx); m_ipc.registerForIPC("activewindow", this); m_ipc.registerForIPC("closewindow", this); m_ipc.registerForIPC("movewindow", this); m_ipc.registerForIPC("changefloatingmode", this); m_ipc.registerForIPC("fullscreen", this); - windowIpcUniqueLock.unlock(); - queryActiveWorkspace(); - update(); dp.emit(); } @@ -46,6 +44,8 @@ Window::~Window() { auto Window::update() -> void { std::shared_lock windowIpcShareLock(windowIpcSmtx); + queryActiveWorkspace(); + std::string windowName = waybar::util::sanitize_string(workspace_.last_window_title); std::string windowAddress = workspace_.last_window; @@ -54,8 +54,15 @@ auto Window::update() -> void { std::string label_text; if (!format_.empty()) { label_.show(); + + // If the focused window name is empty and fallback is configured, use fallback text + std::string displayTitle = windowName; + if (displayTitle.empty() && config_["fallback"].isString()) { + displayTitle = config_["fallback"].asString(); + } + label_text = waybar::util::rewriteString( - fmt::format(fmt::runtime(format_), fmt::arg("title", windowName), + fmt::format(fmt::runtime(format_), fmt::arg("title", displayTitle), fmt::arg("initialTitle", windowData_.initial_title), fmt::arg("class", windowData_.class_name), fmt::arg("initialClass", windowData_.initial_class_name)), @@ -71,13 +78,13 @@ auto Window::update() -> void { tooltip_format = config_["tooltip-format"].asString(); } if (!tooltip_format.empty()) { - label_.set_tooltip_text( + label_.set_tooltip_markup( fmt::format(fmt::runtime(tooltip_format), fmt::arg("title", windowName), fmt::arg("initialTitle", windowData_.initial_title), fmt::arg("class", windowData_.class_name), fmt::arg("initialClass", windowData_.initial_class_name))); } else if (!label_text.empty()) { - label_.set_tooltip_text(label_text); + label_.set_tooltip_markup(label_text); } } @@ -109,21 +116,14 @@ auto Window::update() -> void { AAppIconLabel::update(); } -auto Window::getActiveWorkspace() -> Workspace { - const auto workspace = IPC::inst().getSocket1JsonReply("activeworkspace"); - - if (workspace.isObject()) { - return Workspace::parse(workspace); - } - - return {}; -} +auto Window::getActiveWorkspace() -> Workspace { return getActiveWorkspace(""); } auto Window::getActiveWorkspace(const std::string& monitorName) -> Workspace { const auto monitors = IPC::inst().getSocket1JsonReply("monitors"); if (monitors.isArray()) { - auto monitor = std::ranges::find_if( - monitors, [&](Json::Value monitor) { return monitor["name"] == monitorName; }); + auto monitor = std::ranges::find_if(monitors, [&](const Json::Value& monitor) { + return monitorName.empty() ? monitor["focused"].asBool() : monitor["name"] == monitorName; + }); if (monitor == std::end(monitors)) { spdlog::warn("Monitor not found: {}", monitorName); return Workspace{ @@ -133,12 +133,13 @@ auto Window::getActiveWorkspace(const std::string& monitorName) -> Workspace { .last_window_title = "", }; } - const int id = (*monitor)["activeWorkspace"]["id"].asInt(); + const int special_id = (*monitor)["specialWorkspace"]["id"].asInt(); + const int id = special_id != 0 ? special_id : (*monitor)["activeWorkspace"]["id"].asInt(); const auto workspaces = IPC::inst().getSocket1JsonReply("workspaces"); if (workspaces.isArray()) { auto workspace = std::ranges::find_if( - workspaces, [&](Json::Value workspace) { return workspace["id"] == id; }); + workspaces, [&](const Json::Value& workspace) { return workspace["id"] == id; }); if (workspace == std::end(workspaces)) { spdlog::warn("No workspace with id {}", id); return Workspace{ @@ -176,71 +177,69 @@ auto Window::WindowData::parse(const Json::Value& value) -> Window::WindowData { } void Window::queryActiveWorkspace() { - std::shared_lock windowIpcShareLock(windowIpcSmtx); - if (separateOutputs_) { workspace_ = getActiveWorkspace(this->bar_.output->name); } else { workspace_ = getActiveWorkspace(); } + focused_ = false; + windowData_ = WindowData{}; + allFloating_ = false; + swallowing_ = false; + fullscreen_ = false; + solo_ = false; + soloClass_.clear(); + + if (workspace_.windows <= 0) { + return; + } + + const auto clients = m_ipc.getSocket1JsonReply("clients"); + if (!clients.isArray()) { + return; + } + + auto activeWindow = std::ranges::find_if(clients, [&](const Json::Value& window) { + return window["address"] == workspace_.last_window; + }); + + if (activeWindow == std::end(clients)) { + return; + } + focused_ = true; - if (workspace_.windows > 0) { - const auto clients = m_ipc.getSocket1JsonReply("clients"); - if (clients.isArray()) { - auto activeWindow = std::ranges::find_if( - clients, [&](Json::Value window) { return window["address"] == workspace_.last_window; }); - - if (activeWindow == std::end(clients)) { - focused_ = false; - return; - } - - windowData_ = WindowData::parse(*activeWindow); - updateAppIconName(windowData_.class_name, windowData_.initial_class_name); - std::vector workspaceWindows; - std::ranges::copy_if(clients, std::back_inserter(workspaceWindows), [&](Json::Value window) { + windowData_ = WindowData::parse(*activeWindow); + updateAppIconName(windowData_.class_name, windowData_.initial_class_name); + std::vector workspaceWindows; + std::ranges::copy_if( + clients, std::back_inserter(workspaceWindows), [&](const Json::Value& window) { return window["workspace"]["id"] == workspace_.id && window["mapped"].asBool(); }); - swallowing_ = std::ranges::any_of(workspaceWindows, [&](Json::Value window) { - return !window["swallowing"].isNull() && window["swallowing"].asString() != "0x0"; - }); - std::vector visibleWindows; - std::ranges::copy_if(workspaceWindows, std::back_inserter(visibleWindows), - [&](Json::Value window) { return !window["hidden"].asBool(); }); - solo_ = 1 == std::count_if(visibleWindows.begin(), visibleWindows.end(), - [&](Json::Value window) { return !window["floating"].asBool(); }); - allFloating_ = std::ranges::all_of( - visibleWindows, [&](Json::Value window) { return window["floating"].asBool(); }); - fullscreen_ = windowData_.fullscreen; + swallowing_ = std::ranges::any_of(workspaceWindows, [&](const Json::Value& window) { + return !window["swallowing"].isNull() && window["swallowing"].asString() != "0x0"; + }); + std::vector visibleWindows; + std::ranges::copy_if(workspaceWindows, std::back_inserter(visibleWindows), + [&](const Json::Value& window) { return !window["hidden"].asBool(); }); + solo_ = 1 == std::count_if( + visibleWindows.begin(), visibleWindows.end(), + [&](const Json::Value& window) { return !window["floating"].asBool(); }); + allFloating_ = std::ranges::all_of( + visibleWindows, [&](const Json::Value& window) { return window["floating"].asBool(); }); + fullscreen_ = windowData_.fullscreen; - // Fullscreen windows look like they are solo - if (fullscreen_) { - solo_ = true; - } + // Fullscreen windows look like they are solo + if (fullscreen_) { + solo_ = true; + } - if (solo_) { - soloClass_ = windowData_.class_name; - } else { - soloClass_ = ""; - } - } - } else { - focused_ = false; - windowData_ = WindowData{}; - allFloating_ = false; - swallowing_ = false; - fullscreen_ = false; - solo_ = false; - soloClass_ = ""; + if (solo_) { + soloClass_ = windowData_.class_name; } } -void Window::onEvent(const std::string& ev) { - queryActiveWorkspace(); - - dp.emit(); -} +void Window::onEvent(const std::string& ev) { dp.emit(); } void Window::setClass(const std::string& classname, bool enable) { if (enable) { diff --git a/src/modules/hyprland/windowcount.cpp b/src/modules/hyprland/windowcount.cpp new file mode 100644 index 00000000..5f5db80c --- /dev/null +++ b/src/modules/hyprland/windowcount.cpp @@ -0,0 +1,140 @@ +#include "modules/hyprland/windowcount.hpp" + +#include +#include +#include +#include + +#include +#include + +#include "modules/hyprland/backend.hpp" + +namespace waybar::modules::hyprland { + +WindowCount::WindowCount(const std::string& id, const Bar& bar, const Json::Value& config) + : AAppIconLabel(config, "windowcount", id, "{count}", 0, true), bar_(bar), m_ipc(IPC::inst()) { + separateOutputs_ = + config.isMember("separate-outputs") ? config["separate-outputs"].asBool() : true; + + queryActiveWorkspace(); + update(); + dp.emit(); + + // register for hyprland ipc + m_ipc.registerForIPC("fullscreen", this); + m_ipc.registerForIPC("workspace", this); + m_ipc.registerForIPC("focusedmon", this); + m_ipc.registerForIPC("openwindow", this); + m_ipc.registerForIPC("closewindow", this); + m_ipc.registerForIPC("movewindow", this); +} + +WindowCount::~WindowCount() { + m_ipc.unregisterForIPC(this); + // wait for possible event handler to finish + std::lock_guard lg(mutex_); +} + +auto WindowCount::update() -> void { + std::lock_guard lg(mutex_); + + queryActiveWorkspace(); + + std::string format = config_["format"].asString(); + std::string formatEmpty = config_["format-empty"].asString(); + std::string formatWindowed = config_["format-windowed"].asString(); + std::string formatFullscreen = config_["format-fullscreen"].asString(); + + setClass("empty", workspace_.windows == 0); + setClass("fullscreen", workspace_.hasfullscreen); + + if (workspace_.windows == 0 && !formatEmpty.empty()) { + label_.set_markup(fmt::format(fmt::runtime(formatEmpty), workspace_.windows)); + } else if (!workspace_.hasfullscreen && !formatWindowed.empty()) { + label_.set_markup(fmt::format(fmt::runtime(formatWindowed), workspace_.windows)); + } else if (workspace_.hasfullscreen && !formatFullscreen.empty()) { + label_.set_markup(fmt::format(fmt::runtime(formatFullscreen), workspace_.windows)); + } else if (!format.empty()) { + label_.set_markup(fmt::format(fmt::runtime(format), workspace_.windows)); + } else { + label_.set_markup(fmt::format("{}", workspace_.windows)); + } + + label_.show(); + AAppIconLabel::update(); +} + +auto WindowCount::getActiveWorkspace() -> Workspace { + const auto workspace = m_ipc.getSocket1JsonReply("activeworkspace"); + + if (workspace.isObject()) { + return Workspace::parse(workspace); + } + + return {}; +} + +auto WindowCount::getActiveWorkspace(const std::string& monitorName) -> Workspace { + const auto monitors = m_ipc.getSocket1JsonReply("monitors"); + if (monitors.isArray()) { + auto monitor = std::ranges::find_if( + monitors, [&](const Json::Value& monitor) { return monitor["name"] == monitorName; }); + if (monitor == std::end(monitors)) { + spdlog::warn("Monitor not found: {}", monitorName); + return Workspace{ + .id = -1, + .windows = 0, + .hasfullscreen = false, + }; + } + const int id = (*monitor)["activeWorkspace"]["id"].asInt(); + + const auto workspaces = m_ipc.getSocket1JsonReply("workspaces"); + if (workspaces.isArray()) { + auto workspace = std::ranges::find_if( + workspaces, [&](const Json::Value& workspace) { return workspace["id"] == id; }); + if (workspace == std::end(workspaces)) { + spdlog::warn("No workspace with id {}", id); + return Workspace{ + .id = -1, + .windows = 0, + .hasfullscreen = false, + }; + } + return Workspace::parse(*workspace); + }; + }; + + return {}; +} + +auto WindowCount::Workspace::parse(const Json::Value& value) -> WindowCount::Workspace { + return Workspace{ + .id = value["id"].asInt(), + .windows = value["windows"].asInt(), + .hasfullscreen = value["hasfullscreen"].asBool(), + }; +} + +void WindowCount::queryActiveWorkspace() { + if (separateOutputs_) { + workspace_ = getActiveWorkspace(this->bar_.output->name); + } else { + workspace_ = getActiveWorkspace(); + } +} + +void WindowCount::onEvent(const std::string& ev) { dp.emit(); } + +void WindowCount::setClass(const std::string& classname, bool enable) { + if (enable) { + if (!bar_.window.get_style_context()->has_class(classname)) { + bar_.window.get_style_context()->add_class(classname); + } + } else { + bar_.window.get_style_context()->remove_class(classname); + } +} + +} // namespace waybar::modules::hyprland diff --git a/src/modules/hyprland/windowcreationpayload.cpp b/src/modules/hyprland/windowcreationpayload.cpp index df7fe784..5ace5b32 100644 --- a/src/modules/hyprland/windowcreationpayload.cpp +++ b/src/modules/hyprland/windowcreationpayload.cpp @@ -11,7 +11,7 @@ namespace waybar::modules::hyprland { -WindowCreationPayload::WindowCreationPayload(Json::Value const &client_data) +WindowCreationPayload::WindowCreationPayload(Json::Value const& client_data) : m_window(std::make_pair(client_data["class"].asString(), client_data["title"].asString())), m_windowAddress(client_data["address"].asString()), m_workspaceName(client_data["workspace"]["name"].asString()) { @@ -19,8 +19,8 @@ WindowCreationPayload::WindowCreationPayload(Json::Value const &client_data) clearWorkspaceName(); } -WindowCreationPayload::WindowCreationPayload(std::string workspace_name, - WindowAddress window_address, std::string window_repr) +WindowCreationPayload::WindowCreationPayload(const std::string& workspace_name, + WindowAddress window_address, WindowRepr window_repr) : m_window(std::move(window_repr)), m_windowAddress(std::move(window_address)), m_workspaceName(std::move(workspace_name)) { @@ -28,12 +28,14 @@ WindowCreationPayload::WindowCreationPayload(std::string workspace_name, clearWorkspaceName(); } -WindowCreationPayload::WindowCreationPayload(std::string workspace_name, - WindowAddress window_address, std::string window_class, - std::string window_title) +WindowCreationPayload::WindowCreationPayload(const std::string& workspace_name, + WindowAddress window_address, + const std::string& window_class, + const std::string& window_title, bool is_active) : m_window(std::make_pair(std::move(window_class), std::move(window_title))), m_windowAddress(std::move(window_address)), - m_workspaceName(std::move(workspace_name)) { + m_workspaceName(std::move(workspace_name)), + m_isActive(is_active) { clearAddr(); clearWorkspaceName(); } @@ -72,7 +74,7 @@ void WindowCreationPayload::clearWorkspaceName() { } } -bool WindowCreationPayload::isEmpty(Workspaces &workspace_manager) { +bool WindowCreationPayload::isEmpty(Workspaces& workspace_manager) { if (std::holds_alternative(m_window)) { return std::get(m_window).empty(); } @@ -88,17 +90,18 @@ bool WindowCreationPayload::isEmpty(Workspaces &workspace_manager) { int WindowCreationPayload::incrementTimeSpentUncreated() { return m_timeSpentUncreated++; } -void WindowCreationPayload::moveToWorksace(std::string &new_workspace_name) { +void WindowCreationPayload::moveToWorkspace(std::string& new_workspace_name) { m_workspaceName = new_workspace_name; } -std::string WindowCreationPayload::repr(Workspaces &workspace_manager) { +WindowRepr WindowCreationPayload::repr(Workspaces& workspace_manager) { if (std::holds_alternative(m_window)) { return std::get(m_window); } if (std::holds_alternative(m_window)) { - auto [window_class, window_title] = std::get(m_window); - return workspace_manager.getRewrite(window_class, window_title); + auto const& [window_class, window_title] = std::get(m_window); + return {m_windowAddress, window_class, window_title, + workspace_manager.getRewrite(window_class, window_title), m_isActive}; } // Unreachable spdlog::error("WorkspaceWindow::repr: Unreachable"); diff --git a/src/modules/hyprland/workspace.cpp b/src/modules/hyprland/workspace.cpp index e0fed6cc..9b2d0b32 100644 --- a/src/modules/hyprland/workspace.cpp +++ b/src/modules/hyprland/workspace.cpp @@ -1,16 +1,19 @@ #include #include +#include #include #include #include #include "modules/hyprland/workspaces.hpp" +#include "util/command.hpp" +#include "util/icon_loader.hpp" namespace waybar::modules::hyprland { -Workspace::Workspace(const Json::Value &workspace_data, Workspaces &workspace_manager, - const Json::Value &clients_data) +Workspace::Workspace(const Json::Value& workspace_data, Workspaces& workspace_manager, + const Json::Value& clients_data) : m_workspaceManager(workspace_manager), m_id(workspace_data["id"].asInt()), m_name(workspace_data["name"].asString()), @@ -28,18 +31,34 @@ Workspace::Workspace(const Json::Value &workspace_data, Workspaces &workspace_ma } m_button.add_events(Gdk::BUTTON_PRESS_MASK); + m_button.add_events(Gdk::ENTER_NOTIFY_MASK | Gdk::LEAVE_NOTIFY_MASK); + + m_button.signal_enter_notify_event().connect(sigc::mem_fun(*this, &Workspace::handleEnter)); + m_button.signal_leave_notify_event().connect(sigc::mem_fun(*this, &Workspace::handleLeave)); + m_button.signal_button_press_event().connect(sigc::mem_fun(*this, &Workspace::handleClicked), false); m_button.set_relief(Gtk::RELIEF_NONE); - m_content.set_center_widget(m_label); + if (m_workspaceManager.enableTaskbar()) { + m_content.set_orientation(m_workspaceManager.taskbarOrientation()); + m_content.pack_start(m_labelBefore, false, false); + } else { + m_content.set_center_widget(m_labelBefore); + } m_button.add(m_content); initializeWindowMap(clients_data); } -void addOrRemoveClass(const Glib::RefPtr &context, bool condition, - const std::string &class_name) { +Workspace::~Workspace() { + // Disconnect the hover-check timeout so it can't fire on this destroyed + // instance (Workspaces are removed at runtime while a check may be armed). + stopHoverCheck(); +} + +void addOrRemoveClass(const Glib::RefPtr& context, bool condition, + const std::string& class_name) { if (condition) { context->add_class(class_name); } else { @@ -47,75 +66,208 @@ void addOrRemoveClass(const Glib::RefPtr &context, bool condi } } -std::optional Workspace::closeWindow(WindowAddress const &addr) { - if (m_windowMap.contains(addr)) { - return removeWindow(addr); +std::optional Workspace::closeWindow(WindowAddress const& addr) { + auto it = std::ranges::find_if(m_windowMap, + [&addr](const auto& window) { return window.address == addr; }); + // If the vector contains the address, remove it and return the window representation + if (it != m_windowMap.end()) { + WindowRepr windowRepr = *it; + m_windowMap.erase(it); + return windowRepr; } return std::nullopt; } -bool Workspace::handleClicked(GdkEventButton *bt) const { +bool Workspace::pointerInsideButton() { + auto display = Gdk::Display::get_default(); + if (!display) { + return false; + } + + auto seat = display->get_default_seat(); + if (!seat) { + return false; + } + + auto pointer = seat->get_pointer(); + if (!pointer) { + return false; + } + + Glib::RefPtr screen; + int pointerRootX = 0; + int pointerRootY = 0; + + pointer->get_position(screen, pointerRootX, pointerRootY); + + Gtk::Widget* toplevel = m_button.get_toplevel(); + if (toplevel == nullptr || !toplevel->get_window()) { + return false; + } + + int buttonX = 0; + int buttonY = 0; + + if (!m_button.translate_coordinates(*toplevel, 0, 0, buttonX, buttonY)) { + return false; + } + + int windowRootX = 0; + int windowRootY = 0; + toplevel->get_window()->get_root_origin(windowRootX, windowRootY); + + const auto allocation = m_button.get_allocation(); + + const int buttonRootX = windowRootX + buttonX; + const int buttonRootY = windowRootY + buttonY; + const int buttonWidth = allocation.get_width(); + const int buttonHeight = allocation.get_height(); + + return pointerRootX >= buttonRootX && pointerRootY >= buttonRootY && + pointerRootX < buttonRootX + buttonWidth && + pointerRootY < buttonRootY + buttonHeight; +} + +bool Workspace::syncHoverClass() { + auto styleContext = m_button.get_style_context(); + + if (pointerInsideButton()) { + styleContext->add_class("workspace-hover"); + return true; + } + + styleContext->remove_class("workspace-hover"); + stopHoverCheck(); + return false; +} + +void Workspace::startHoverCheck() { + if (m_hoverCheckConnection.connected()) { + return; + } + + m_hoverCheckConnection = Glib::signal_timeout().connect( + sigc::mem_fun(*this, &Workspace::syncHoverClass), + 50); +} + +void Workspace::stopHoverCheck() { + if (m_hoverCheckConnection.connected()) { + m_hoverCheckConnection.disconnect(); + } +} + +bool Workspace::handleEnter(GdkEventCrossing* /*event*/) { + m_button.get_style_context()->add_class("workspace-hover"); + startHoverCheck(); + return false; +} + +bool Workspace::handleLeave(GdkEventCrossing* /*event*/) { + /* + * Do not remove immediately. + * Workspace taskbar children can fire misleading leave events while the + * pointer is still visually inside the workspace button. + * + * The polling check will remove the class once the pointer really leaves. + */ + startHoverCheck(); + return false; +} +bool Workspace::handleClicked(GdkEventButton* bt) const { if (bt->type == GDK_BUTTON_PRESS) { try { if (id() > 0) { // normal if (m_workspaceManager.moveToMonitor()) { - m_ipc.getSocket1Reply("dispatch focusworkspaceoncurrentmonitor " + std::to_string(id())); + IPC::dispatch("focusworkspaceoncurrentmonitor", std::to_string(id())); } else { - m_ipc.getSocket1Reply("dispatch workspace " + std::to_string(id())); + IPC::dispatch("workspace", std::to_string(id())); } } else if (!isSpecial()) { // named (this includes persistent) if (m_workspaceManager.moveToMonitor()) { - m_ipc.getSocket1Reply("dispatch focusworkspaceoncurrentmonitor name:" + name()); + IPC::dispatch("focusworkspaceoncurrentmonitor", "name:" + name()); } else { - m_ipc.getSocket1Reply("dispatch workspace name:" + name()); + IPC::dispatch("workspace", "name:" + name()); } } else if (id() != -99) { // named special - m_ipc.getSocket1Reply("dispatch togglespecialworkspace " + name()); + IPC::dispatch("togglespecialworkspace", name()); } else { // special - m_ipc.getSocket1Reply("dispatch togglespecialworkspace"); + IPC::dispatch("togglespecialworkspace", ""); } return true; - } catch (const std::exception &e) { + } catch (const std::exception& e) { spdlog::error("Failed to dispatch workspace: {}", e.what()); } } return false; } -void Workspace::initializeWindowMap(const Json::Value &clients_data) { +void Workspace::initializeWindowMap(const Json::Value& clients_data) { m_windowMap.clear(); - for (auto client : clients_data) { + for (const auto& client : clients_data) { if (client["workspace"]["id"].asInt() == id()) { insertWindow({client}); } } } -void Workspace::insertWindow(WindowCreationPayload create_window_paylod) { - if (!create_window_paylod.isEmpty(m_workspaceManager)) { - auto repr = create_window_paylod.repr(m_workspaceManager); - - if (!repr.empty()) { - m_windowMap[create_window_paylod.getAddress()] = repr; +void Workspace::setActiveWindow(WindowAddress const& addr) { + std::optional activeIdx; + for (size_t i = 0; i < m_windowMap.size(); ++i) { + auto& window = m_windowMap[i]; + bool isActive = (window.address == addr); + window.setActive(isActive); + if (isActive) { + activeIdx = i; } } -}; -bool Workspace::onWindowOpened(WindowCreationPayload const &create_window_paylod) { - if (create_window_paylod.getWorkspaceName() == name()) { - insertWindow(create_window_paylod); + auto activeWindowPos = m_workspaceManager.activeWindowPosition(); + const bool has_active_window = + activeIdx.has_value() && + activeWindowPos != Workspaces::ActiveWindowPosition::NONE; + + if (has_active_window) { + auto window = std::move(m_windowMap[*activeIdx]); + m_windowMap.erase(m_windowMap.begin() + *activeIdx); + if (activeWindowPos == Workspaces::ActiveWindowPosition::FIRST) { + m_windowMap.insert(m_windowMap.begin(), std::move(window)); + } else if (activeWindowPos == Workspaces::ActiveWindowPosition::LAST) { + m_windowMap.emplace_back(std::move(window)); + } + } +} + +void Workspace::insertWindow(WindowCreationPayload create_window_payload) { + if (!create_window_payload.isEmpty(m_workspaceManager)) { + auto repr = create_window_payload.repr(m_workspaceManager); + + const bool should_display = + !repr.empty() || m_workspaceManager.enableTaskbar(); + + if (should_display) { + auto addr = create_window_payload.getAddress(); + auto it = std::ranges::find_if( + m_windowMap, [&addr](const auto& window) { return window.address == addr; }); + // If the vector contains the address, update the window representation, otherwise insert it + if (it != m_windowMap.end()) { + *it = repr; + } else { + m_windowMap.emplace_back(repr); + } + } + } +} + +bool Workspace::onWindowOpened(WindowCreationPayload const& create_window_payload) { + if (create_window_payload.getWorkspaceName() == name()) { + insertWindow(create_window_payload); return true; } return false; } -std::string Workspace::removeWindow(WindowAddress const &addr) { - std::string windowRepr = m_windowMap[addr]; - m_windowMap.erase(addr); - return windowRepr; -} - -std::string &Workspace::selectIcon(std::map &icons_map) { +std::string& Workspace::selectIcon(std::map& icons_map) { spdlog::trace("Selecting icon for workspace {}", name()); if (isUrgent()) { auto urgentIconIt = icons_map.find("urgent"); @@ -124,6 +276,17 @@ std::string &Workspace::selectIcon(std::map &icons_map } } + if (isActive() && isSpecial()) { + auto activeIconIt = icons_map.find("active:" + name()); + if (activeIconIt != icons_map.end()) { + return activeIconIt->second; + } + auto namedIconIt = icons_map.find(name()); + if (namedIconIt != icons_map.end()) { + return namedIconIt->second; + } + } + if (isActive()) { auto activeIconIt = icons_map.find("active"); if (activeIconIt != icons_map.end()) { @@ -172,7 +335,11 @@ std::string &Workspace::selectIcon(std::map &icons_map return m_name; } -void Workspace::update(const std::string &format, const std::string &icon) { +void Workspace::update(const std::string& workspace_icon) { + if (this->m_workspaceManager.persistentOnly() && !this->isPersistent()) { + m_button.hide(); + return; + } // clang-format off if (this->m_workspaceManager.hideActive() && \ this->isActive() && \ @@ -202,6 +369,7 @@ void Workspace::update(const std::string &format, const std::string &icon) { auto styleContext = m_button.get_style_context(); addOrRemoveClass(styleContext, isActive(), "active"); addOrRemoveClass(styleContext, isSpecial(), "special"); + addOrRemoveClass(styleContext, isSpecial(), name()); addOrRemoveClass(styleContext, isEmpty(), "empty"); addOrRemoveClass(styleContext, isPersistent(), "persistent"); addOrRemoveClass(styleContext, isUrgent(), "urgent"); @@ -209,21 +377,151 @@ void Workspace::update(const std::string &format, const std::string &icon) { addOrRemoveClass(styleContext, m_workspaceManager.getBarOutput() == output(), "hosting-monitor"); std::string windows; - auto windowSeparator = m_workspaceManager.getWindowSeparator(); + // Optimization: The {windows} substitution string is only possible if the taskbar is disabled, no + // need to compute this if enableTaskbar() is true + if (!m_workspaceManager.enableTaskbar()) { + auto windowSeparator = m_workspaceManager.getWindowSeparator(); - bool isNotFirst = false; + bool isNotFirst = false; - for (auto &[_pid, window_repr] : m_windowMap) { - if (isNotFirst) { - windows.append(windowSeparator); + for (const auto& window_repr : m_windowMap) { + if (isNotFirst) { + windows.append(windowSeparator); + } + isNotFirst = true; + windows.append(window_repr.repr_rewrite); } - isNotFirst = true; - windows.append(window_repr); } - m_label.set_markup(fmt::format(fmt::runtime(format), fmt::arg("id", id()), - fmt::arg("name", name()), fmt::arg("icon", icon), - fmt::arg("windows", windows))); + auto formatBefore = m_workspaceManager.formatBefore(); + m_labelBefore.set_markup(fmt::format(fmt::runtime(formatBefore), fmt::arg("id", id()), + fmt::arg("name", name()), fmt::arg("icon", workspace_icon), + fmt::arg("windows", windows))); + m_labelBefore.get_style_context()->add_class("workspace-label"); + + if (m_workspaceManager.enableTaskbar()) { + updateTaskbar(workspace_icon); + } +} + +bool Workspace::isEmpty() const { + auto ignore_list = m_workspaceManager.getIgnoredWindows(); + const bool no_ignore_rules = ignore_list.empty(); + + if (no_ignore_rules) { + return m_windows == 0; + } + // If there are windows but they are all ignored, consider the workspace empty + return std::all_of( + m_windowMap.begin(), m_windowMap.end(), + [this, &ignore_list](const auto& window_repr) { return shouldSkipWindow(window_repr); }); +} + +void Workspace::updateTaskbar(const std::string& workspace_icon) { + for (auto child : m_content.get_children()) { + if (child != &m_labelBefore) { + m_content.remove(*child); + } + } + + bool isFirst = true; + auto processWindow = [&](const WindowRepr& window_repr) { + if (shouldSkipWindow(window_repr)) { + return; // skip + } + if (isFirst) { + isFirst = false; + } else if (m_workspaceManager.getWindowSeparator() != "") { + auto windowSeparator = Gtk::make_managed(m_workspaceManager.getWindowSeparator()); + m_content.pack_start(*windowSeparator, false, false); + windowSeparator->show(); + } + + auto window_box = Gtk::make_managed(Gtk::ORIENTATION_HORIZONTAL); + window_box->set_tooltip_markup(window_repr.window_title); + + auto button = Gtk::manage(new Gtk::Button()); + button->set_relief(Gtk::RELIEF_NONE); + button->add(*window_box); + button->get_style_context()->add_class("taskbar-window"); + if (window_repr.isActive) { + button->get_style_context()->add_class("active"); + } + if (m_workspaceManager.onClickWindow() != "") { + button->signal_button_press_event().connect( + sigc::bind(sigc::mem_fun(*this, &Workspace::handleClick), window_repr.address), + false); + } + + auto text_before = fmt::format(fmt::runtime(m_workspaceManager.taskbarFormatBefore()), + fmt::arg("title", window_repr.window_title)); + if (!text_before.empty()) { + auto window_label_before = Gtk::make_managed(text_before); + window_box->pack_start(*window_label_before, true, true); + } + + if (m_workspaceManager.taskbarWithIcon()) { + auto app_info_ = IconLoader::get_app_info_from_app_id_list(window_repr.window_class); + int icon_size = m_workspaceManager.taskbarIconSize(); + auto window_icon = Gtk::make_managed(); + m_workspaceManager.iconLoader().image_load_icon(*window_icon, app_info_, icon_size); + window_box->pack_start(*window_icon, false, false); + } + + auto text_after = fmt::format(fmt::runtime(m_workspaceManager.taskbarFormatAfter()), + fmt::arg("title", window_repr.window_title)); + if (!text_after.empty()) { + auto window_label_after = Gtk::make_managed(text_after); + window_box->pack_start(*window_label_after, true, true); + } + + m_content.pack_start(*button, true, false); + button->show_all(); + }; + + if (m_workspaceManager.taskbarReverseDirection()) { + for (auto it = m_windowMap.rbegin(); it != m_windowMap.rend(); ++it) { + processWindow(*it); + } + } else { + for (const auto& window_repr : m_windowMap) { + processWindow(window_repr); + } + } + + auto formatAfter = m_workspaceManager.formatAfter(); + const bool has_format_after = !formatAfter.empty(); + + if (has_format_after) { + m_labelAfter.set_markup(fmt::format(fmt::runtime(formatAfter), fmt::arg("id", id()), + fmt::arg("name", name()), + fmt::arg("icon", workspace_icon))); + m_content.pack_end(m_labelAfter, false, false); + m_labelAfter.show(); + } +} + +bool Workspace::handleClick(const GdkEventButton* event_button, WindowAddress const& addr) const { + if (event_button->type == GDK_BUTTON_PRESS) { + std::string command = std::regex_replace(m_workspaceManager.onClickWindow(), + std::regex("\\{address\\}"), "0x" + addr); + command = std::regex_replace(command, std::regex("\\{button\\}"), + std::to_string(event_button->button)); + auto res = util::command::execNoRead(command); + if (res.exit_code != 0) { + spdlog::error("Failed to execute {}: {}", command, res.out); + } + } + return true; +} + +bool Workspace::shouldSkipWindow(const WindowRepr& window_repr) const { + auto ignore_list = m_workspaceManager.getIgnoredWindows(); + auto it = std::ranges::find_if(ignore_list, [&window_repr](const auto& ignoreItem) { + return std::regex_match(window_repr.window_class, ignoreItem) || + std::regex_match(window_repr.window_title, ignoreItem); + }); + return it != ignore_list.end(); } } // namespace waybar::modules::hyprland diff --git a/src/modules/hyprland/workspaces.cpp b/src/modules/hyprland/workspaces.cpp index ebfc942b..c50022ea 100644 --- a/src/modules/hyprland/workspaces.cpp +++ b/src/modules/hyprland/workspaces.cpp @@ -10,15 +10,15 @@ #include #include "util/regex_collection.hpp" +#include "util/string.hpp" namespace waybar::modules::hyprland { -Workspaces::Workspaces(const std::string &id, const Bar &bar, const Json::Value &config) +Workspaces::Workspaces(const std::string& id, const Bar& bar, const Json::Value& config) : AModule(config, "workspaces", id, false, false), m_bar(bar), m_box(bar.orientation, 0), m_ipc(IPC::inst()) { - modulesReady = true; parseConfig(config); m_box.set_name("workspaces"); @@ -34,6 +34,9 @@ Workspaces::Workspaces(const std::string &id, const Bar &bar, const Json::Value } Workspaces::~Workspaces() { + if (m_scrollEventConnection_.connected()) { + m_scrollEventConnection_.disconnect(); + } m_ipc.unregisterForIPC(this); // wait for possible event handler to finish std::lock_guard lg(m_mutex); @@ -43,11 +46,23 @@ void Workspaces::init() { m_activeWorkspaceId = m_ipc.getSocket1JsonReply("activeworkspace")["id"].asInt(); initializeWorkspaces(); + + if (m_scrollEventConnection_.connected()) { + m_scrollEventConnection_.disconnect(); + } + bool hasScrollConfig = config_["on-scroll-up"].isString() || config_["on-scroll-down"].isString(); + if (barScroll() || hasScrollConfig) { + auto& window = const_cast(m_bar).window; + window.add_events(Gdk::SCROLL_MASK | Gdk::SMOOTH_SCROLL_MASK); + m_scrollEventConnection_ = + window.signal_scroll_event().connect(sigc::mem_fun(*this, &Workspaces::handleScroll)); + } + dp.emit(); } -Json::Value Workspaces::createMonitorWorkspaceData(std::string const &name, - std::string const &monitor) { +Json::Value Workspaces::createMonitorWorkspaceData(std::string const& name, + std::string const& monitor) { spdlog::trace("Creating persistent workspace: {} on monitor {}", name, monitor); Json::Value workspaceData; @@ -62,23 +77,26 @@ Json::Value Workspaces::createMonitorWorkspaceData(std::string const &name, return workspaceData; } -void Workspaces::createWorkspace(Json::Value const &workspace_data, - Json::Value const &clients_data) { +void Workspaces::createWorkspace(Json::Value const& workspace_data, + Json::Value const& clients_data) { auto workspaceName = workspace_data["name"].asString(); + auto workspaceId = workspace_data["id"].asInt(); spdlog::debug("Creating workspace {}", workspaceName); // avoid recreating existing workspaces - auto workspace = - std::ranges::find_if(m_workspaces, [workspaceName](std::unique_ptr const &w) { - return (workspaceName.starts_with("special:") && workspaceName.substr(8) == w->name()) || - workspaceName == w->name(); - }); + auto workspace = std::ranges::find_if(m_workspaces, [&](std::unique_ptr const& w) { + if (workspaceId > 0) { + return w->id() == workspaceId; + } + return (workspaceName.starts_with("special:") && workspaceName.substr(8) == w->name()) || + workspaceName == w->name(); + }); if (workspace != m_workspaces.end()) { // don't recreate workspace, but update persistency if necessary const auto keys = workspace_data.getMemberNames(); - const auto *k = "persistent-rule"; + const auto* k = "persistent-rule"; if (std::ranges::find(keys, k) != keys.end()) { spdlog::debug("Set dynamic persistency of workspace {} to: {}", workspaceName, workspace_data[k].asBool() ? "true" : "false"); @@ -97,14 +115,14 @@ void Workspaces::createWorkspace(Json::Value const &workspace_data, // create new workspace m_workspaces.emplace_back(std::make_unique(workspace_data, *this, clients_data)); - Gtk::Button &newWorkspaceButton = m_workspaces.back()->button(); + Gtk::Button& newWorkspaceButton = m_workspaces.back()->button(); m_box.pack_start(newWorkspaceButton, false, false); sortWorkspaces(); newWorkspaceButton.show_all(); } void Workspaces::createWorkspacesToCreate() { - for (const auto &[workspaceData, clientsData] : m_workspacesToCreate) { + for (const auto& [workspaceData, clientsData] : m_workspacesToCreate) { createWorkspace(workspaceData, clientsData); } if (!m_workspacesToCreate.empty()) { @@ -136,16 +154,17 @@ void Workspaces::doUpdate() { } } -void Workspaces::extendOrphans(int workspaceId, Json::Value const &clientsJson) { +void Workspaces::extendOrphans(int workspaceId, Json::Value const& clientsJson) { spdlog::trace("Extending orphans with workspace {}", workspaceId); - for (const auto &client : clientsJson) { + for (const auto& client : clientsJson) { if (client["workspace"]["id"].asInt() == workspaceId) { registerOrphanWindow({client}); } } } -std::string Workspaces::getRewrite(std::string window_class, std::string window_title) { +std::string Workspaces::getRewrite(const std::string& window_class, + const std::string& window_title) { std::string windowReprKey; if (windowRewriteConfigUsesTitle()) { windowReprKey = fmt::format("class<{}> title<{}>", window_class, window_title); @@ -160,7 +179,7 @@ std::string Workspaces::getRewrite(std::string window_class, std::string window_ std::vector Workspaces::getVisibleWorkspaces() { std::vector visibleWorkspaces; auto monitors = IPC::inst().getSocket1JsonReply("monitors"); - for (const auto &monitor : monitors) { + for (const auto& monitor : monitors) { auto ws = monitor["activeWorkspace"]; if (ws.isObject() && ws["id"].isInt()) { visibleWorkspaces.push_back(ws["id"].asInt()); @@ -178,7 +197,7 @@ void Workspaces::initializeWorkspaces() { spdlog::debug("Initializing workspaces"); // if the workspace rules changed since last initialization, make sure we reset everything: - for (auto &workspace : m_workspaces) { + for (auto& workspace : m_workspaces) { m_workspacesToRemove.push_back(std::to_string(workspace->id())); } @@ -186,7 +205,7 @@ void Workspaces::initializeWorkspaces() { auto const workspacesJson = m_ipc.getSocket1JsonReply("workspaces"); auto const clientsJson = m_ipc.getSocket1JsonReply("clients"); - for (Json::Value workspaceJson : workspacesJson) { + for (const auto& workspaceJson : workspacesJson) { std::string workspaceName = workspaceJson["name"].asString(); if ((allOutputs() || m_bar.output->name == workspaceJson["monitor"].asString()) && (!workspaceName.starts_with("special") || showSpecial()) && @@ -206,7 +225,7 @@ void Workspaces::initializeWorkspaces() { loadPersistentWorkspacesFromWorkspaceRules(clientsJson); } -bool isDoubleSpecial(std::string const &workspace_name) { +bool isDoubleSpecial(std::string const& workspace_name) { // Hyprland's IPC sometimes reports the creation of workspaces strangely named // `special:special:`. This function checks for that and is used // to avoid creating (and then removing) such workspaces. @@ -214,8 +233,8 @@ bool isDoubleSpecial(std::string const &workspace_name) { return workspace_name.find("special:special:") != std::string::npos; } -bool Workspaces::isWorkspaceIgnored(std::string const &name) { - for (auto &rule : m_ignoreWorkspaces) { +bool Workspaces::isWorkspaceIgnored(std::string const& name) { + for (auto& rule : m_ignoreWorkspaces) { if (std::regex_match(name, rule)) { return true; break; @@ -225,19 +244,19 @@ bool Workspaces::isWorkspaceIgnored(std::string const &name) { return false; } -void Workspaces::loadPersistentWorkspacesFromConfig(Json::Value const &clientsJson) { +void Workspaces::loadPersistentWorkspacesFromConfig(Json::Value const& clientsJson) { spdlog::info("Loading persistent workspaces from Waybar config"); const std::vector keys = m_persistentWorkspaceConfig.getMemberNames(); std::vector persistentWorkspacesToCreate; const std::string currentMonitor = m_bar.output->name; const bool monitorInConfig = std::ranges::find(keys, currentMonitor) != keys.end(); - for (const std::string &key : keys) { + for (const std::string& key : keys) { // only add if either: // 1. key is the current monitor name // 2. key is "*" and this monitor is not already defined in the config bool canCreate = key == currentMonitor || (key == "*" && !monitorInConfig); - const Json::Value &value = m_persistentWorkspaceConfig[key]; + const Json::Value& value = m_persistentWorkspaceConfig[key]; spdlog::trace("Parsing persistent workspace config: {} => {}", key, value.toStyledString()); if (value.isInt()) { @@ -252,17 +271,15 @@ void Workspaces::loadPersistentWorkspacesFromConfig(Json::Value const &clientsJs } else if (value.isArray() && !value.empty()) { // value is an array => create defined workspaces for this monitor if (canCreate) { - for (const Json::Value &workspace : value) { - if (workspace.isInt()) { - spdlog::debug("Creating workspace {} on monitor {}", workspace, currentMonitor); - persistentWorkspacesToCreate.emplace_back(std::to_string(workspace.asInt())); - } + for (const Json::Value& workspace : value) { + spdlog::debug("Creating workspace {} on monitor {}", workspace, currentMonitor); + persistentWorkspacesToCreate.emplace_back(workspace.asString()); } } else { // key is the workspace and value is array of monitors to create on - for (const Json::Value &monitor : value) { + for (const Json::Value& monitor : value) { if (monitor.isString() && monitor.asString() == currentMonitor) { - persistentWorkspacesToCreate.emplace_back(currentMonitor); + persistentWorkspacesToCreate.emplace_back(key); break; } } @@ -273,18 +290,18 @@ void Workspaces::loadPersistentWorkspacesFromConfig(Json::Value const &clientsJs } } - for (auto const &workspace : persistentWorkspacesToCreate) { + for (auto const& workspace : persistentWorkspacesToCreate) { auto workspaceData = createMonitorWorkspaceData(workspace, m_bar.output->name); workspaceData["persistent-config"] = true; m_workspacesToCreate.emplace_back(workspaceData, clientsJson); } } -void Workspaces::loadPersistentWorkspacesFromWorkspaceRules(const Json::Value &clientsJson) { +void Workspaces::loadPersistentWorkspacesFromWorkspaceRules(const Json::Value& clientsJson) { spdlog::info("Loading persistent workspaces from Hyprland workspace rules"); auto const workspaceRules = m_ipc.getSocket1JsonReply("workspacerules"); - for (Json::Value const &rule : workspaceRules) { + for (Json::Value const& rule : workspaceRules) { if (!rule["workspaceString"].isString()) { spdlog::warn("Workspace rules: invalid workspaceString, skipping: {}", rule); continue; @@ -292,14 +309,28 @@ void Workspaces::loadPersistentWorkspacesFromWorkspaceRules(const Json::Value &c if (!rule["persistent"].asBool()) { continue; } - auto const &workspace = rule.isMember("defaultName") ? rule["defaultName"].asString() - : rule["workspaceString"].asString(); - auto const &monitor = rule["monitor"].asString(); + auto workspace = rule.isMember("defaultName") ? rule["defaultName"].asString() + : rule["workspaceString"].asString(); + + // There could be persistent special workspaces, only show those when show-special is enabled. + if (workspace.starts_with("special:") && !showSpecial()) { + continue; + } + + // The prefix "name:" cause mismatches with workspace names taken anywhere else. + if (workspace.starts_with("name:")) { + workspace = workspace.substr(5); + } + auto const& monitor = rule["monitor"].asString(); // create this workspace persistently if: // 1. the allOutputs config option is enabled // 2. the rule's monitor is the current monitor // 3. no monitor is specified in the rule => assume it needs to be persistent on every monitor if (allOutputs() || m_bar.output->name == monitor || monitor.empty()) { + // => skip ignore-workspaces even if its a persistent + if(isWorkspaceIgnored(workspace)) { + continue; + } // => persistent workspace should be shown on this monitor auto workspaceData = createMonitorWorkspaceData(workspace, m_bar.output->name); workspaceData["persistent-rule"] = true; @@ -311,10 +342,15 @@ void Workspaces::loadPersistentWorkspacesFromWorkspaceRules(const Json::Value &c } } -void Workspaces::onEvent(const std::string &ev) { +void Workspaces::onEvent(const std::string& ev) { std::lock_guard lock(m_mutex); - std::string eventName(begin(ev), begin(ev) + ev.find_first_of('>')); - std::string payload = ev.substr(eventName.size() + 2); + const auto separator = ev.find(">>"); + if (separator == std::string::npos) { + spdlog::warn("Malformed Hyprland workspace event: {}", ev); + return; + } + std::string eventName = ev.substr(0, separator); + std::string payload = ev.substr(separator + 2); if (eventName == "workspacev2") { onWorkspaceActivated(payload); @@ -340,6 +376,8 @@ void Workspaces::onEvent(const std::string &ev) { onWorkspaceRenamed(payload); } else if (eventName == "windowtitlev2") { onWindowTitleEvent(payload); + } else if (eventName == "activewindowv2") { + onActiveWindowChanged(payload); } else if (eventName == "configreloaded") { onConfigReloaded(); } @@ -347,7 +385,7 @@ void Workspaces::onEvent(const std::string &ev) { dp.emit(); } -void Workspaces::onWorkspaceActivated(std::string const &payload) { +void Workspaces::onWorkspaceActivated(std::string const& payload) { const auto [workspaceIdStr, workspaceName] = splitDoublePayload(payload); const auto workspaceId = parseWorkspaceId(workspaceIdStr); if (workspaceId.has_value()) { @@ -355,19 +393,19 @@ void Workspaces::onWorkspaceActivated(std::string const &payload) { } } -void Workspaces::onSpecialWorkspaceActivated(std::string const &payload) { +void Workspaces::onSpecialWorkspaceActivated(std::string const& payload) { std::string name(begin(payload), begin(payload) + payload.find_first_of(',')); m_activeSpecialWorkspaceName = (!name.starts_with("special:") ? name : name.substr(8)); } -void Workspaces::onWorkspaceDestroyed(std::string const &payload) { +void Workspaces::onWorkspaceDestroyed(std::string const& payload) { const auto [workspaceId, workspaceName] = splitDoublePayload(payload); if (!isDoubleSpecial(workspaceName)) { m_workspacesToRemove.push_back(workspaceId); } } -void Workspaces::onWorkspaceCreated(std::string const &payload, Json::Value const &clientsData) { +void Workspaces::onWorkspaceCreated(std::string const& payload, Json::Value const& clientsData) { spdlog::debug("Workspace created: {}", payload); const auto [workspaceIdStr, _] = splitDoublePayload(payload); @@ -380,7 +418,7 @@ void Workspaces::onWorkspaceCreated(std::string const &payload, Json::Value cons auto const workspaceRules = m_ipc.getSocket1JsonReply("workspacerules"); auto const workspacesJson = m_ipc.getSocket1JsonReply("workspaces"); - for (Json::Value workspaceJson : workspacesJson) { + for (auto workspaceJson : workspacesJson) { const auto currentId = workspaceJson["id"].asInt(); if (currentId == *workspaceId) { std::string workspaceName = workspaceJson["name"].asString(); @@ -394,7 +432,7 @@ void Workspaces::onWorkspaceCreated(std::string const &payload, Json::Value cons if ((allOutputs() || m_bar.output->name == workspaceJson["monitor"].asString()) && (showSpecial() || !workspaceName.starts_with("special")) && !isDoubleSpecial(workspaceName)) { - for (Json::Value const &rule : workspaceRules) { + for (Json::Value const& rule : workspaceRules) { auto ruleWorkspaceName = rule.isMember("defaultName") ? rule["defaultName"].asString() : rule["workspaceString"].asString(); @@ -413,7 +451,7 @@ void Workspaces::onWorkspaceCreated(std::string const &payload, Json::Value cons } } -void Workspaces::onWorkspaceMoved(std::string const &payload) { +void Workspaces::onWorkspaceMoved(std::string const& payload) { spdlog::debug("Workspace moved: {}", payload); // Update active workspace @@ -434,7 +472,7 @@ void Workspaces::onWorkspaceMoved(std::string const &payload) { } } -void Workspaces::onWorkspaceRenamed(std::string const &payload) { +void Workspaces::onWorkspaceRenamed(std::string const& payload) { spdlog::debug("Workspace renamed: {}", payload); const auto [workspaceIdStr, newName] = splitDoublePayload(payload); @@ -443,7 +481,7 @@ void Workspaces::onWorkspaceRenamed(std::string const &payload) { return; } - for (auto &workspace : m_workspaces) { + for (auto& workspace : m_workspaces) { if (workspace->id() == *workspaceId) { workspace->setName(newName); break; @@ -452,7 +490,7 @@ void Workspaces::onWorkspaceRenamed(std::string const &payload) { sortWorkspaces(); } -void Workspaces::onMonitorFocused(std::string const &payload) { +void Workspaces::onMonitorFocused(std::string const& payload) { spdlog::trace("Monitor focused: {}", payload); const auto [monitorName, workspaceIdStr] = splitDoublePayload(payload); @@ -464,7 +502,7 @@ void Workspaces::onMonitorFocused(std::string const &payload) { m_activeWorkspaceId = *workspaceId; - for (Json::Value &monitor : m_ipc.getSocket1JsonReply("monitors")) { + for (Json::Value& monitor : m_ipc.getSocket1JsonReply("monitors")) { if (monitor["name"].asString() == monitorName) { const auto name = monitor["specialWorkspace"]["name"].asString(); m_activeSpecialWorkspaceName = !name.starts_with("special:") ? name : name.substr(8); @@ -472,54 +510,58 @@ void Workspaces::onMonitorFocused(std::string const &payload) { } } -void Workspaces::onWindowOpened(std::string const &payload) { +void Workspaces::onWindowOpened(std::string const& payload) { spdlog::trace("Window opened: {}", payload); updateWindowCount(); - size_t lastCommaIdx = 0; - size_t nextCommaIdx = payload.find(','); - std::string windowAddress = payload.substr(lastCommaIdx, nextCommaIdx - lastCommaIdx); + const auto firstComma = payload.find(','); + const auto secondComma = + firstComma == std::string::npos ? std::string::npos : payload.find(',', firstComma + 1); + const auto thirdComma = + secondComma == std::string::npos ? std::string::npos : payload.find(',', secondComma + 1); + if (firstComma == std::string::npos || secondComma == std::string::npos || + thirdComma == std::string::npos) { + spdlog::warn("Malformed Hyprland openwindow payload: {}", payload); + return; + } - lastCommaIdx = nextCommaIdx; - nextCommaIdx = payload.find(',', nextCommaIdx + 1); - std::string workspaceName = payload.substr(lastCommaIdx + 1, nextCommaIdx - lastCommaIdx - 1); + std::string windowAddress = payload.substr(0, firstComma); + std::string workspaceName = payload.substr(firstComma + 1, secondComma - firstComma - 1); + std::string windowClass = payload.substr(secondComma + 1, thirdComma - secondComma - 1); + std::string windowTitle = payload.substr(thirdComma + 1); - lastCommaIdx = nextCommaIdx; - nextCommaIdx = payload.find(',', nextCommaIdx + 1); - std::string windowClass = payload.substr(lastCommaIdx + 1, nextCommaIdx - lastCommaIdx - 1); - - std::string windowTitle = payload.substr(nextCommaIdx + 1, payload.length() - nextCommaIdx); - - m_windowsToCreate.emplace_back(workspaceName, windowAddress, windowClass, windowTitle); + bool isActive = m_currentActiveWindowAddress == windowAddress; + m_windowsToCreate.emplace_back(workspaceName, windowAddress, windowClass, windowTitle, isActive); } -void Workspaces::onWindowClosed(std::string const &addr) { +void Workspaces::onWindowClosed(std::string const& addr) { spdlog::trace("Window closed: {}", addr); updateWindowCount(); - for (auto &workspace : m_workspaces) { + m_orphanWindowMap.erase(addr); + for (auto& workspace : m_workspaces) { if (workspace->closeWindow(addr)) { break; } } } -void Workspaces::onWindowMoved(std::string const &payload) { +void Workspaces::onWindowMoved(std::string const& payload) { spdlog::trace("Window moved: {}", payload); updateWindowCount(); auto [windowAddress, _, workspaceName] = splitTriplePayload(payload); - std::string windowRepr; + WindowRepr windowRepr; // If the window was still queued to be created, just change its destination // and exit - for (auto &window : m_windowsToCreate) { + for (auto& window : m_windowsToCreate) { if (window.getAddress() == windowAddress) { - window.moveToWorksace(workspaceName); + window.moveToWorkspace(workspaceName); return; } } // Take the window's representation from the old workspace... - for (auto &workspace : m_workspaces) { + for (auto& workspace : m_workspaces) { if (auto windowAddr = workspace->closeWindow(windowAddress); windowAddr != std::nullopt) { windowRepr = windowAddr.value(); break; @@ -533,11 +575,12 @@ void Workspaces::onWindowMoved(std::string const &payload) { // ...and then add it to the new workspace if (!windowRepr.empty()) { + m_orphanWindowMap.erase(windowAddress); m_windowsToCreate.emplace_back(workspaceName, windowAddress, windowRepr); } } -void Workspaces::onWindowTitleEvent(std::string const &payload) { +void Workspaces::onWindowTitleEvent(std::string const& payload) { spdlog::trace("Window title changed: {}", payload); std::optional> inserter; @@ -547,7 +590,7 @@ void Workspaces::onWindowTitleEvent(std::string const &payload) { if (m_orphanWindowMap.contains(windowAddress)) { inserter = [this](WindowCreationPayload wcp) { this->registerOrphanWindow(std::move(wcp)); }; } else { - auto windowWorkspace = std::ranges::find_if(m_workspaces, [windowAddress](auto &workspace) { + auto windowWorkspace = std::ranges::find_if(m_workspaces, [windowAddress](auto& workspace) { return workspace->containsWindow(windowAddress); }); @@ -558,9 +601,10 @@ void Workspaces::onWindowTitleEvent(std::string const &payload) { (*windowWorkspace)->insertWindow(std::move(wcp)); }; } else { - auto queuedWindow = std::ranges::find_if(m_windowsToCreate, [payload](auto &windowPayload) { - return windowPayload.getAddress() == payload; - }); + auto queuedWindow = + std::ranges::find_if(m_windowsToCreate, [&windowAddress](auto& windowPayload) { + return windowPayload.getAddress() == windowAddress; + }); // If the window was queued, rename it in the queue if (queuedWindow != m_windowsToCreate.end()) { @@ -571,9 +615,9 @@ void Workspaces::onWindowTitleEvent(std::string const &payload) { if (inserter.has_value()) { Json::Value clientsData = m_ipc.getSocket1JsonReply("clients"); - std::string jsonWindowAddress = fmt::format("0x{}", payload); + std::string jsonWindowAddress = fmt::format("0x{}", windowAddress); - auto client = std::ranges::find_if(clientsData, [jsonWindowAddress](auto &client) { + auto client = std::ranges::find_if(clientsData, [jsonWindowAddress](auto& client) { return client["address"].asString() == jsonWindowAddress; }); @@ -583,15 +627,31 @@ void Workspaces::onWindowTitleEvent(std::string const &payload) { } } +void Workspaces::onActiveWindowChanged(WindowAddress const& activeWindowAddress) { + spdlog::trace("Active window changed: {}", activeWindowAddress); + m_currentActiveWindowAddress = activeWindowAddress; + + for (auto& [address, window] : m_orphanWindowMap) { + window.setActive(address == activeWindowAddress); + } + for (auto const& workspace : m_workspaces) { + workspace->setActiveWindow(activeWindowAddress); + } + for (auto& window : m_windowsToCreate) { + window.setActive(window.getAddress() == activeWindowAddress); + } +} + void Workspaces::onConfigReloaded() { spdlog::info("Hyprland config reloaded, reinitializing hyprland/workspaces module..."); init(); } -auto Workspaces::parseConfig(const Json::Value &config) -> void { - const auto &configFormat = config["format"]; - m_format = configFormat.isString() ? configFormat.asString() : "{name}"; - m_withIcon = m_format.find("{icon}") != std::string::npos; +auto Workspaces::parseConfig(const Json::Value& config) -> void { + const auto& configFormat = config["format"]; + m_formatBefore = configFormat.isString() ? configFormat.asString() : "{name}"; + m_withIcon = m_formatBefore.find("{icon}") != std::string::npos; + auto withWindows = m_formatBefore.find("{windows}") != std::string::npos; if (m_withIcon && m_iconsMap.empty()) { populateIconsMap(config["format-icons"]); @@ -600,39 +660,50 @@ auto Workspaces::parseConfig(const Json::Value &config) -> void { populateBoolConfig(config, "all-outputs", m_allOutputs); populateBoolConfig(config, "show-special", m_showSpecial); populateBoolConfig(config, "special-visible-only", m_specialVisibleOnly); + populateBoolConfig(config, "persistent-only", m_persistentOnly); populateBoolConfig(config, "active-only", m_activeOnly); populateBoolConfig(config, "hide-active", m_hideActive); populateBoolConfig(config, "move-to-monitor", m_moveToMonitor); + populateBoolConfig(config, "enable-bar-scroll", m_barScroll); m_persistentWorkspaceConfig = config.get("persistent-workspaces", Json::Value()); populateSortByConfig(config); populateIgnoreWorkspacesConfig(config); populateFormatWindowSeparatorConfig(config); populateWindowRewriteConfig(config); + + if (withWindows) { + populateWorkspaceTaskbarConfig(config); + } + if (m_enableTaskbar) { + auto parts = split(m_formatBefore, "{windows}", 1); + m_formatBefore = parts[0]; + m_formatAfter = parts.size() > 1 ? parts[1] : ""; + } } -auto Workspaces::populateIconsMap(const Json::Value &formatIcons) -> void { - for (const auto &name : formatIcons.getMemberNames()) { +auto Workspaces::populateIconsMap(const Json::Value& formatIcons) -> void { + for (const auto& name : formatIcons.getMemberNames()) { m_iconsMap.emplace(name, formatIcons[name].asString()); } m_iconsMap.emplace("", ""); } -auto Workspaces::populateBoolConfig(const Json::Value &config, const std::string &key, bool &member) +auto Workspaces::populateBoolConfig(const Json::Value& config, const std::string& key, bool& member) -> void { - const auto &configValue = config[key]; + const auto& configValue = config[key]; if (configValue.isBool()) { member = configValue.asBool(); } } -auto Workspaces::populateSortByConfig(const Json::Value &config) -> void { - const auto &configSortBy = config["sort-by"]; +auto Workspaces::populateSortByConfig(const Json::Value& config) -> void { + const auto& configSortBy = config["sort-by"]; if (configSortBy.isString()) { auto sortByStr = configSortBy.asString(); try { m_sortBy = m_enumParser.parseStringToEnum(sortByStr, m_sortMap); - } catch (const std::invalid_argument &e) { + } catch (const std::invalid_argument& e) { m_sortBy = SortMethod::DEFAULT; spdlog::warn( "Invalid string representation for sort-by. Falling back to default sort method."); @@ -640,16 +711,16 @@ auto Workspaces::populateSortByConfig(const Json::Value &config) -> void { } } -auto Workspaces::populateIgnoreWorkspacesConfig(const Json::Value &config) -> void { +auto Workspaces::populateIgnoreWorkspacesConfig(const Json::Value& config) -> void { auto ignoreWorkspaces = config["ignore-workspaces"]; if (ignoreWorkspaces.isArray()) { - for (const auto &workspaceRegex : ignoreWorkspaces) { + for (const auto& workspaceRegex : ignoreWorkspaces) { if (workspaceRegex.isString()) { std::string ruleString = workspaceRegex.asString(); try { const std::regex rule{ruleString, std::regex_constants::icase}; m_ignoreWorkspaces.emplace_back(rule); - } catch (const std::regex_error &e) { + } catch (const std::regex_error& e) { spdlog::error("Invalid rule {}: {}", ruleString, e.what()); } } else { @@ -659,26 +730,97 @@ auto Workspaces::populateIgnoreWorkspacesConfig(const Json::Value &config) -> vo } } -auto Workspaces::populateFormatWindowSeparatorConfig(const Json::Value &config) -> void { - const auto &formatWindowSeparator = config["format-window-separator"]; +auto Workspaces::populateFormatWindowSeparatorConfig(const Json::Value& config) -> void { + const auto& formatWindowSeparator = config["format-window-separator"]; m_formatWindowSeparator = formatWindowSeparator.isString() ? formatWindowSeparator.asString() : " "; } -auto Workspaces::populateWindowRewriteConfig(const Json::Value &config) -> void { - const auto &windowRewrite = config["window-rewrite"]; +auto Workspaces::populateWindowRewriteConfig(const Json::Value& config) -> void { + const auto& windowRewrite = config["window-rewrite"]; if (!windowRewrite.isObject()) { spdlog::debug("window-rewrite is not defined or is not an object, using default rules."); return; } - const auto &windowRewriteDefaultConfig = config["window-rewrite-default"]; + const auto& windowRewriteDefaultConfig = config["window-rewrite-default"]; std::string windowRewriteDefault = windowRewriteDefaultConfig.isString() ? windowRewriteDefaultConfig.asString() : "?"; m_windowRewriteRules = util::RegexCollection( windowRewrite, windowRewriteDefault, - [this](std::string &window_rule) { return windowRewritePriorityFunction(window_rule); }); + [this](std::string& window_rule) { return windowRewritePriorityFunction(window_rule); }); +} + +auto Workspaces::populateWorkspaceTaskbarConfig(const Json::Value& config) -> void { + const auto& workspaceTaskbar = config["workspace-taskbar"]; + if (!workspaceTaskbar.isObject()) { + spdlog::debug("workspace-taskbar is not defined or is not an object, using default rules."); + return; + } + + populateBoolConfig(workspaceTaskbar, "enable", m_enableTaskbar); + populateBoolConfig(workspaceTaskbar, "update-active-window", m_updateActiveWindow); + populateBoolConfig(workspaceTaskbar, "reverse-direction", m_taskbarReverseDirection); + + if (workspaceTaskbar["format"].isString()) { + /* The user defined a format string, use it */ + std::string format = workspaceTaskbar["format"].asString(); + m_taskbarWithTitle = format.find("{title") != std::string::npos; /* {title} or {title.length} */ + auto parts = split(format, "{icon}", 1); + m_taskbarFormatBefore = parts[0]; + if (parts.size() > 1) { + m_taskbarWithIcon = true; + m_taskbarFormatAfter = parts[1]; + } + } else { + /* The default is to only show the icon */ + m_taskbarWithIcon = true; + } + + auto iconTheme = workspaceTaskbar["icon-theme"]; + if (iconTheme.isArray()) { + for (auto& c : iconTheme) { + m_iconLoader.add_custom_icon_theme(c.asString()); + } + } else if (iconTheme.isString()) { + m_iconLoader.add_custom_icon_theme(iconTheme.asString()); + } + + if (workspaceTaskbar["icon-size"].isInt()) { + m_taskbarIconSize = workspaceTaskbar["icon-size"].asInt(); + } + if (workspaceTaskbar["orientation"].isString() && + toLower(workspaceTaskbar["orientation"].asString()) == "vertical") { + m_taskbarOrientation = Gtk::ORIENTATION_VERTICAL; + } + + if (workspaceTaskbar["on-click-window"].isString()) { + m_onClickWindow = workspaceTaskbar["on-click-window"].asString(); + } + + if (workspaceTaskbar["ignore-list"].isArray()) { + for (auto& windowRegex : workspaceTaskbar["ignore-list"]) { + std::string ruleString = windowRegex.asString(); + try { + m_ignoreWindows.emplace_back(ruleString, std::regex_constants::icase); + } catch (const std::regex_error& e) { + spdlog::error("Invalid rule {}: {}", ruleString, e.what()); + } + } + } + + if (workspaceTaskbar["active-window-position"].isString()) { + auto posStr = workspaceTaskbar["active-window-position"].asString(); + try { + m_activeWindowPosition = + m_activeWindowEnumParser.parseStringToEnum(posStr, m_activeWindowPositionMap); + } catch (const std::invalid_argument& e) { + spdlog::warn( + "Invalid string representation for active-window-position. Falling back to 'none'."); + m_activeWindowPosition = ActiveWindowPosition::NONE; + } + } } void Workspaces::registerOrphanWindow(WindowCreationPayload create_window_payload) { @@ -701,22 +843,28 @@ auto Workspaces::registerIpc() -> void { m_ipc.registerForIPC("urgent", this); m_ipc.registerForIPC("configreloaded", this); - if (windowRewriteConfigUsesTitle()) { + if (windowRewriteConfigUsesTitle() || m_taskbarWithTitle) { spdlog::info( "Registering for Hyprland's 'windowtitlev2' events because a user-defined window " "rewrite rule uses the 'title' field."); m_ipc.registerForIPC("windowtitlev2", this); } + if (m_updateActiveWindow) { + spdlog::info( + "Registering for Hyprland's 'activewindowv2' events because 'update-active-window' is set " + "to true."); + m_ipc.registerForIPC("activewindowv2", this); + } } void Workspaces::removeWorkspacesToRemove() { - for (const auto &workspaceString : m_workspacesToRemove) { + for (const auto& workspaceString : m_workspacesToRemove) { removeWorkspace(workspaceString); } m_workspacesToRemove.clear(); } -void Workspaces::removeWorkspace(std::string const &workspaceString) { +void Workspaces::removeWorkspace(std::string const& workspaceString) { spdlog::debug("Removing workspace {}", workspaceString); // If this succeeds, we have a workspace ID. @@ -734,7 +882,7 @@ void Workspaces::removeWorkspace(std::string const &workspaceString) { name = workspaceString; } - const auto workspace = std::ranges::find_if(m_workspaces, [&](std::unique_ptr &x) { + const auto workspace = std::ranges::find_if(m_workspaces, [&](std::unique_ptr& x) { if (workspaceId.has_value()) { return *workspaceId == x->id(); } @@ -760,7 +908,7 @@ void Workspaces::setCurrentMonitorId() { // get monitor ID from name (used by persistent workspaces) m_monitorId = 0; auto monitors = m_ipc.getSocket1JsonReply("monitors"); - auto currentMonitor = std::ranges::find_if(monitors, [this](const Json::Value &m) { + auto currentMonitor = std::ranges::find_if(monitors, [this](const Json::Value& m) { return m["name"].asString() == m_bar.output->name; }); if (currentMonitor == monitors.end()) { @@ -771,9 +919,43 @@ void Workspaces::setCurrentMonitorId() { } } +void Workspaces::sortSpecialCentered() { + std::vector> specialWorkspaces; + std::vector> hiddenWorkspaces; + std::vector> normalWorkspaces; + + for (auto& workspace : m_workspaces) { + if (workspace->isSpecial()) { + specialWorkspaces.push_back(std::move(workspace)); + } else { + if (workspace->button().is_visible()) { + normalWorkspaces.push_back(std::move(workspace)); + } else { + hiddenWorkspaces.push_back(std::move(workspace)); + } + } + } + m_workspaces.clear(); + + size_t center = normalWorkspaces.size() / 2; + + m_workspaces.insert(m_workspaces.end(), std::make_move_iterator(normalWorkspaces.begin()), + std::make_move_iterator(normalWorkspaces.begin() + center)); + + m_workspaces.insert(m_workspaces.end(), std::make_move_iterator(specialWorkspaces.begin()), + std::make_move_iterator(specialWorkspaces.end())); + + m_workspaces.insert(m_workspaces.end(), + std::make_move_iterator(normalWorkspaces.begin() + center), + std::make_move_iterator(normalWorkspaces.end())); + + m_workspaces.insert(m_workspaces.end(), std::make_move_iterator(hiddenWorkspaces.begin()), + std::make_move_iterator(hiddenWorkspaces.end())); +} + void Workspaces::sortWorkspaces() { std::ranges::sort( // - m_workspaces, [&](std::unique_ptr &a, std::unique_ptr &b) { + m_workspaces, [&](std::unique_ptr& a, std::unique_ptr& b) { // Helper comparisons auto isIdLess = a->id() < b->id(); auto isNameLess = a->name() < b->name(); @@ -786,7 +968,7 @@ void Workspaces::sortWorkspaces() { case SortMethod::NUMBER: try { return std::stoi(a->name()) < std::stoi(b->name()); - } catch (const std::invalid_argument &) { + } catch (const std::exception& e) { // Handle the exception if necessary. break; } @@ -829,24 +1011,29 @@ void Workspaces::sortWorkspaces() { // Return a default value if none of the cases match. return isNameLess; // You can adjust this to your specific needs. }); + if (m_sortBy == SortMethod::SPECIAL_CENTERED) { + this->sortSpecialCentered(); + } for (size_t i = 0; i < m_workspaces.size(); ++i) { m_box.reorder_child(m_workspaces[i]->button(), i); } } -void Workspaces::setUrgentWorkspace(std::string const &windowaddress) { +void Workspaces::setUrgentWorkspace(std::string const& windowaddress) { const Json::Value clientsJson = m_ipc.getSocket1JsonReply("clients"); + const std::string normalizedAddress = + windowaddress.starts_with("0x") ? windowaddress : fmt::format("0x{}", windowaddress); int workspaceId = -1; - for (Json::Value clientJson : clientsJson) { - if (clientJson["address"].asString().ends_with(windowaddress)) { + for (const auto& clientJson : clientsJson) { + if (clientJson["address"].asString() == normalizedAddress) { workspaceId = clientJson["workspace"]["id"].asInt(); break; } } - auto workspace = std::ranges::find_if(m_workspaces, [workspaceId](std::unique_ptr &x) { + auto workspace = std::ranges::find_if(m_workspaces, [workspaceId](std::unique_ptr& x) { return x->id() == workspaceId; }); if (workspace != m_workspaces.end()) { @@ -861,8 +1048,8 @@ auto Workspaces::update() -> void { void Workspaces::updateWindowCount() { const Json::Value workspacesJson = m_ipc.getSocket1JsonReply("workspaces"); - for (auto &workspace : m_workspaces) { - auto workspaceJson = std::ranges::find_if(workspacesJson, [&](Json::Value const &x) { + for (auto const& workspace : m_workspaces) { + auto workspaceJson = std::ranges::find_if(workspacesJson, [&](Json::Value const& x) { return x["name"].asString() == workspace->name() || (workspace->isSpecial() && x["name"].asString() == "special:" + workspace->name()); }); @@ -870,7 +1057,7 @@ void Workspaces::updateWindowCount() { if (workspaceJson != workspacesJson.end()) { try { count = (*workspaceJson)["windows"].asUInt(); - } catch (const std::exception &e) { + } catch (const std::exception& e) { spdlog::error("Failed to update window count: {}", e.what()); } } @@ -881,9 +1068,9 @@ void Workspaces::updateWindowCount() { bool Workspaces::updateWindowsToCreate() { bool anyWindowCreated = false; std::vector notCreated; - for (auto &windowPayload : m_windowsToCreate) { + for (auto& windowPayload : m_windowsToCreate) { bool created = false; - for (auto &workspace : m_workspaces) { + for (auto& workspace : m_workspaces) { if (workspace->onWindowOpened(windowPayload)) { created = true; anyWindowCreated = true; @@ -907,20 +1094,28 @@ bool Workspaces::updateWindowsToCreate() { void Workspaces::updateWorkspaceStates() { const std::vector visibleWorkspaces = getVisibleWorkspaces(); auto updatedWorkspaces = m_ipc.getSocket1JsonReply("workspaces"); - for (auto &workspace : m_workspaces) { + + auto currentWorkspace = m_ipc.getSocket1JsonReply("activeworkspace"); + std::string currentWorkspaceName = + currentWorkspace.isMember("name") ? currentWorkspace["name"].asString() : ""; + + for (auto& workspace : m_workspaces) { + bool isActiveByName = + !currentWorkspaceName.empty() && workspace->name() == currentWorkspaceName; + workspace->setActive( - workspace->id() == m_activeWorkspaceId || + workspace->id() == m_activeWorkspaceId || isActiveByName || (workspace->isSpecial() && workspace->name() == m_activeSpecialWorkspaceName)); if (workspace->isActive() && workspace->isUrgent()) { workspace->setUrgent(false); } workspace->setVisible(std::ranges::find(visibleWorkspaces, workspace->id()) != visibleWorkspaces.end()); - std::string &workspaceIcon = m_iconsMap[""]; + std::string& workspaceIcon = m_iconsMap[""]; if (m_withIcon) { workspaceIcon = workspace->selectIcon(m_iconsMap); } - auto updatedWorkspace = std::ranges::find_if(updatedWorkspaces, [&workspace](const auto &w) { + auto updatedWorkspace = std::ranges::find_if(updatedWorkspaces, [&workspace](const auto& w) { auto wNameRaw = w["name"].asString(); auto wName = wNameRaw.starts_with("special:") ? wNameRaw.substr(8) : wNameRaw; return wName == workspace->name(); @@ -928,11 +1123,11 @@ void Workspaces::updateWorkspaceStates() { if (updatedWorkspace != updatedWorkspaces.end()) { workspace->setOutput((*updatedWorkspace)["monitor"].asString()); } - workspace->update(m_format, workspaceIcon); + workspace->update(workspaceIcon); } } -int Workspaces::windowRewritePriorityFunction(std::string const &window_rule) { +int Workspaces::windowRewritePriorityFunction(std::string const& window_rule) { // Rules that match against title are prioritized // Rules that don't specify if they're matching against either title or class are deprioritized bool const hasTitle = window_rule.find("title") != std::string::npos; @@ -953,23 +1148,30 @@ int Workspaces::windowRewritePriorityFunction(std::string const &window_rule) { } template -std::string Workspaces::makePayload(Args const &...args) { +std::string Workspaces::makePayload(Args const&... args) { std::ostringstream result; bool first = true; ((result << (first ? "" : ",") << args, first = false), ...); return result.str(); } -std::pair Workspaces::splitDoublePayload(std::string const &payload) { - const std::string part1 = payload.substr(0, payload.find(',')); +std::pair Workspaces::splitDoublePayload(std::string const& payload) { + const auto separator = payload.find(','); + if (separator == std::string::npos) { + throw std::invalid_argument("Expected a two-part Hyprland payload"); + } + const std::string part1 = payload.substr(0, separator); const std::string part2 = payload.substr(part1.size() + 1); return {part1, part2}; } std::tuple Workspaces::splitTriplePayload( - std::string const &payload) { + std::string const& payload) { const size_t firstComma = payload.find(','); const size_t secondComma = payload.find(',', firstComma + 1); + if (firstComma == std::string::npos || secondComma == std::string::npos) { + throw std::invalid_argument("Expected a three-part Hyprland payload"); + } const std::string part1 = payload.substr(0, firstComma); const std::string part2 = payload.substr(firstComma + 1, secondComma - (firstComma + 1)); @@ -978,13 +1180,46 @@ std::tuple Workspaces::splitTriplePayload return {part1, part2, part3}; } -std::optional Workspaces::parseWorkspaceId(std::string const &workspaceIdStr) { +std::optional Workspaces::parseWorkspaceId(std::string const& workspaceIdStr) { try { return workspaceIdStr == "special" ? -99 : std::stoi(workspaceIdStr); - } catch (std::exception const &e) { - spdlog::error("Failed to parse workspace ID: {}", e.what()); + } catch (std::exception const& e) { + spdlog::debug("Workspace \"{}\" is not bound to an id: {}", workspaceIdStr, e.what()); return std::nullopt; } } +bool Workspaces::handleScroll(GdkEventScroll* e) { + // Ignore emulated scroll events on window + if (gdk_event_get_pointer_emulated((GdkEvent*)e)) { + return false; + } + + // Check for custom scroll commands first; delegate to base class + if (config_["on-scroll-up"].isString() || config_["on-scroll-down"].isString()) { + return AModule::handleScroll(e); + } + + auto dir = AModule::getScrollDir(e); + if (dir == SCROLL_DIR::NONE) { + return true; + } + + if (dir == SCROLL_DIR::DOWN || dir == SCROLL_DIR::RIGHT) { + if (allOutputs()) { + IPC::dispatch("workspace", "e+1"); + } else { + IPC::dispatch("workspace", "m+1"); + } + } else if (dir == SCROLL_DIR::UP || dir == SCROLL_DIR::LEFT) { + if (allOutputs()) { + IPC::dispatch("workspace", "e-1"); + } else { + IPC::dispatch("workspace", "m-1"); + } + } + + return true; +} + } // namespace waybar::modules::hyprland diff --git a/src/modules/image.cpp b/src/modules/image.cpp index 71e93b94..48729cc4 100644 --- a/src/modules/image.cpp +++ b/src/modules/image.cpp @@ -14,31 +14,43 @@ waybar::modules::Image::Image(const std::string& id, const Json::Value& config) size_ = config["size"].asInt(); - interval_ = config_["interval"].asInt(); + const auto once = std::chrono::milliseconds::max(); + if (!config_.isMember("interval") || config_["interval"].isNull() || + config_["interval"] == "once") { + interval_ = once; + } else if (config_["interval"].isNumeric()) { + const auto interval_seconds = config_["interval"].asDouble(); + if (interval_seconds <= 0) { + interval_ = once; + } else { + interval_ = + std::chrono::milliseconds(std::max(1L, // Minimum 1ms due to millisecond precision + static_cast(interval_seconds * 1000))); + } + } else { + interval_ = once; + } if (size_ == 0) { size_ = 16; } - if (interval_ == 0) { - interval_ = INT_MAX; - } - delayWorker(); } void waybar::modules::Image::delayWorker() { thread_ = [this] { dp.emit(); - auto interval = std::chrono::seconds(interval_); - thread_.sleep_for(interval); + thread_.sleep_for(interval_); }; } void waybar::modules::Image::refresh(int sig) { - if (sig == SIGRTMIN + config_["signal"].asInt()) { +#ifdef SIGRTMIN + if (config_["signal"].isInt() && sig == SIGRTMIN + config_["signal"].asInt()) { thread_.wake_up(); } +#endif } auto waybar::modules::Image::update() -> void { diff --git a/src/modules/inhibitor.cpp b/src/modules/inhibitor.cpp index fe2a4be4..43c1f83e 100644 --- a/src/modules/inhibitor.cpp +++ b/src/modules/inhibitor.cpp @@ -85,7 +85,8 @@ auto getInhibitors(const Json::Value& config) -> std::string { if (config["what"].isArray()) { inhibitors = checkInhibitor(config["what"][0].asString()); for (decltype(config["what"].size()) i = 1; i < config["what"].size(); ++i) { - inhibitors += ":" + checkInhibitor(config["what"][i].asString()); + inhibitors.append(":"); + inhibitors.append(checkInhibitor(config["what"][i].asString())); } return inhibitors; } @@ -123,7 +124,7 @@ auto Inhibitor::update() -> void { label_.get_style_context()->add_class(status_text); if (tooltipEnabled()) { - label_.set_tooltip_text(status_text); + label_.set_tooltip_markup(status_text); } return ALabel::update(); diff --git a/src/modules/jack.cpp b/src/modules/jack.cpp index 9bd6fcd6..578fb4e0 100644 --- a/src/modules/jack.cpp +++ b/src/modules/jack.cpp @@ -2,7 +2,7 @@ namespace waybar::modules { -JACK::JACK(const std::string &id, const Json::Value &config) +JACK::JACK(const std::string& id, const Json::Value& config) : ALabel(config, "jack", id, "{load}%", 1) { running_ = false; client_ = NULL; @@ -53,7 +53,7 @@ std::string JACK::JACKState() { auto JACK::update() -> void { std::string format; std::string state = JACKState(); - float latency = 1000 * (float)bufsize_ / (float)samplerate_; + float latency = samplerate_ > 0 ? 1000.0f * (float)bufsize_ / (float)samplerate_ : 0.0f; if (label_.get_style_context()->has_class("xrun")) { label_.get_style_context()->remove_class("xrun"); @@ -80,7 +80,7 @@ auto JACK::update() -> void { if (tooltipEnabled()) { std::string tooltip_format = "{bufsize}/{samplerate} {latency}ms"; if (config_["tooltip-format"].isString()) tooltip_format = config_["tooltip-format"].asString(); - label_.set_tooltip_text(fmt::format( + label_.set_tooltip_markup(fmt::format( fmt::runtime(tooltip_format), fmt::arg("load", std::round(load_)), fmt::arg("bufsize", bufsize_), fmt::arg("samplerate", samplerate_), fmt::arg("latency", fmt::format("{:.2f}", latency)), fmt::arg("xruns", xruns_))); @@ -91,16 +91,19 @@ auto JACK::update() -> void { } int JACK::bufSize(jack_nframes_t size) { + std::lock_guard lock(mutex_); bufsize_ = size; return 0; } int JACK::sampleRate(jack_nframes_t rate) { + std::lock_guard lock(mutex_); samplerate_ = rate; return 0; } int JACK::xrun() { + std::lock_guard lock(mutex_); xruns_ += 1; state_ = "xrun"; return 0; @@ -113,14 +116,14 @@ void JACK::shutdown() { } // namespace waybar::modules -int bufSizeCallback(jack_nframes_t size, void *obj) { - return static_cast(obj)->bufSize(size); +int bufSizeCallback(jack_nframes_t size, void* obj) { + return static_cast(obj)->bufSize(size); } -int sampleRateCallback(jack_nframes_t rate, void *obj) { - return static_cast(obj)->sampleRate(rate); +int sampleRateCallback(jack_nframes_t rate, void* obj) { + return static_cast(obj)->sampleRate(rate); } -int xrunCallback(void *obj) { return static_cast(obj)->xrun(); } +int xrunCallback(void* obj) { return static_cast(obj)->xrun(); } -void shutdownCallback(void *obj) { return static_cast(obj)->shutdown(); } +void shutdownCallback(void* obj) { return static_cast(obj)->shutdown(); } diff --git a/src/modules/keyboard_state.cpp b/src/modules/keyboard_state.cpp index 18ce0a7c..a2207fdd 100644 --- a/src/modules/keyboard_state.cpp +++ b/src/modules/keyboard_state.cpp @@ -232,9 +232,12 @@ waybar::modules::KeyboardState::KeyboardState(const std::string& id, const Bar& } tryAddDevice(dev_path); } else if (event->mask & IN_DELETE) { + std::lock_guard lock(devices_mutex_); auto it = libinput_devices_.find(dev_path); if (it != libinput_devices_.end()) { spdlog::info("Keyboard {} has been removed.", dev_path); + libinput_path_remove_device(it->second); + libinput_device_unref(it->second); libinput_devices_.erase(it); } } @@ -245,6 +248,7 @@ waybar::modules::KeyboardState::KeyboardState(const std::string& id, const Bar& } waybar::modules::KeyboardState::~KeyboardState() { + std::lock_guard lock(devices_mutex_); for (const auto& [_, dev_ptr] : libinput_devices_) { libinput_path_remove_device(dev_ptr); } @@ -256,11 +260,17 @@ auto waybar::modules::KeyboardState::update() -> void { try { std::string dev_path; - if (config_["device-path"].isString() && - libinput_devices_.find(config_["device-path"].asString()) != libinput_devices_.end()) { - dev_path = config_["device-path"].asString(); - } else { - dev_path = libinput_devices_.begin()->first; + { + std::lock_guard lock(devices_mutex_); + if (libinput_devices_.empty()) { + return; + } + if (config_["device-path"].isString() && + libinput_devices_.find(config_["device-path"].asString()) != libinput_devices_.end()) { + dev_path = config_["device-path"].asString(); + } else { + dev_path = libinput_devices_.begin()->first; + } } int fd = openFile(dev_path, O_NONBLOCK | O_CLOEXEC | O_RDONLY); auto dev = openDevice(fd); @@ -308,10 +318,15 @@ auto waybar::modules ::KeyboardState::tryAddDevice(const std::string& dev_path) auto dev = openDevice(fd); if (supportsLockStates(dev)) { spdlog::info("Found device {} at '{}'", libevdev_get_name(dev), dev_path); + std::lock_guard lock(devices_mutex_); if (libinput_devices_.find(dev_path) == libinput_devices_.end()) { auto device = libinput_path_add_device(libinput_, dev_path.c_str()); - libinput_device_ref(device); - libinput_devices_[dev_path] = device; + if (device) { + libinput_device_ref(device); + libinput_devices_[dev_path] = device; + } else { + spdlog::warn("keyboard-state: Failed to add device to libinput: {}", dev_path); + } } } libevdev_free(dev); diff --git a/src/modules/load.cpp b/src/modules/load.cpp index 69a37b4e..72627405 100644 --- a/src/modules/load.cpp +++ b/src/modules/load.cpp @@ -22,7 +22,7 @@ auto waybar::modules::Load::update() -> void { auto [load1, load5, load15] = Load::getLoad(); if (tooltipEnabled()) { auto tooltip = fmt::format("Load 1: {}\nLoad 5: {}\nLoad 15: {}", load1, load5, load15); - label_.set_tooltip_text(tooltip); + label_.set_tooltip_markup(tooltip); } auto format = format_; auto state = getState(load1); diff --git a/src/modules/memory/common.cpp b/src/modules/memory/common.cpp index 544d7814..d41b4fc2 100644 --- a/src/modules/memory/common.cpp +++ b/src/modules/memory/common.cpp @@ -1,11 +1,32 @@ #include "modules/memory.hpp" +namespace { +const std::unordered_map kUnits = { + {"kB", 1.000}, + {"kiB", 1.024}, + {"MB", 1.000 * 1000.0}, + {"MiB", 1.024 * 1024.0}, + {"GB", 1.000 * 1000.0 * 1000.0}, + {"GiB", 1.024 * 1024.0 * 1024.0}, + {"TB", 1.000 * 1000.0 * 1000.0 * 1000.0}, + {"TiB", 1.024 * 1024.0 * 1024.0 * 1024.0} +}; +} + waybar::modules::Memory::Memory(const std::string& id, const Json::Value& config) : ALabel(config, "memory", id, "{}%", 30) { thread_ = [this] { dp.emit(); thread_.sleep_for(interval_); }; + if (config["unit"].isString()) { + unit_ = config["unit"].asString(); + if (!kUnits.contains(unit_)) { + unit_ = "GiB"; + } + } else { + unit_ = "GiB"; + } } auto waybar::modules::Memory::update() -> void { @@ -13,15 +34,15 @@ auto waybar::modules::Memory::update() -> void { unsigned long memtotal = meminfo_["MemTotal"]; unsigned long swaptotal = 0; - if (meminfo_.count("SwapTotal")) { + if (meminfo_.contains("SwapTotal")) { swaptotal = meminfo_["SwapTotal"]; } unsigned long memfree; unsigned long swapfree = 0; - if (meminfo_.count("SwapFree")) { + if (meminfo_.contains("SwapFree")) { swapfree = meminfo_["SwapFree"]; } - if (meminfo_.count("MemAvailable")) { + if (meminfo_.contains("MemAvailable")) { // New kernels (3.4+) have an accurate available memory field. memfree = meminfo_["MemAvailable"] + meminfo_["zfs_size"]; } else { @@ -31,18 +52,19 @@ auto waybar::modules::Memory::update() -> void { } if (memtotal > 0 && memfree >= 0) { - float total_ram_gigabytes = - 0.01 * round(memtotal / 10485.76); // 100*10485.76 = 2^20 = 1024^2 = GiB/KiB - float total_swap_gigabytes = 0.01 * round(swaptotal / 10485.76); int used_ram_percentage = 100 * (memtotal - memfree) / memtotal; int used_swap_percentage = 0; - if (swaptotal && swapfree) { + if ((bool) swaptotal) { used_swap_percentage = 100 * (swaptotal - swapfree) / swaptotal; } - float used_ram_gigabytes = 0.01 * round((memtotal - memfree) / 10485.76); - float used_swap_gigabytes = 0.01 * round((swaptotal - swapfree) / 10485.76); - float available_ram_gigabytes = 0.01 * round(memfree / 10485.76); - float available_swap_gigabytes = 0.01 * round(swapfree / 10485.76); + + float divisor = kUnits.at(unit_); + float total_ram = memtotal / divisor; + float total_swap = swaptotal / divisor; + float used_ram = (memtotal - memfree) / divisor; + float used_swap = (swaptotal - swapfree) / divisor; + float available_ram = memfree / divisor; + float available_swap = swapfree / divisor; auto format = format_; auto state = getState(used_ram_percentage); @@ -58,25 +80,27 @@ auto waybar::modules::Memory::update() -> void { label_.set_markup(fmt::format( fmt::runtime(format), used_ram_percentage, fmt::arg("icon", getIcon(used_ram_percentage, icons)), - fmt::arg("total", total_ram_gigabytes), fmt::arg("swapTotal", total_swap_gigabytes), + fmt::arg("total", total_ram), fmt::arg("swapTotal", total_swap), fmt::arg("percentage", used_ram_percentage), - fmt::arg("swapPercentage", used_swap_percentage), fmt::arg("used", used_ram_gigabytes), - fmt::arg("swapUsed", used_swap_gigabytes), fmt::arg("avail", available_ram_gigabytes), - fmt::arg("swapAvail", available_swap_gigabytes))); + fmt::arg("swapState", swaptotal == 0 ? "Off" : "On"), + fmt::arg("swapPercentage", used_swap_percentage), fmt::arg("used", used_ram), + fmt::arg("swapUsed", used_swap), fmt::arg("avail", available_ram), + fmt::arg("swapAvail", available_swap))); } if (tooltipEnabled()) { if (config_["tooltip-format"].isString()) { auto tooltip_format = config_["tooltip-format"].asString(); - label_.set_tooltip_text(fmt::format( + label_.set_tooltip_markup(fmt::format( fmt::runtime(tooltip_format), used_ram_percentage, - fmt::arg("total", total_ram_gigabytes), fmt::arg("swapTotal", total_swap_gigabytes), + fmt::arg("total", total_ram), fmt::arg("swapTotal", total_swap), fmt::arg("percentage", used_ram_percentage), - fmt::arg("swapPercentage", used_swap_percentage), fmt::arg("used", used_ram_gigabytes), - fmt::arg("swapUsed", used_swap_gigabytes), fmt::arg("avail", available_ram_gigabytes), - fmt::arg("swapAvail", available_swap_gigabytes))); + fmt::arg("swapState", swaptotal == 0 ? "Off" : "On"), + fmt::arg("swapPercentage", used_swap_percentage), fmt::arg("used", used_ram), + fmt::arg("swapUsed", used_swap), fmt::arg("avail", available_ram), + fmt::arg("swapAvail", available_swap))); } else { - label_.set_tooltip_text(fmt::format("{:.{}f}GiB used", used_ram_gigabytes, 1)); + label_.set_tooltip_markup(fmt::format("{:.{}f}{} used", used_ram, 1, unit_)); } } } else { diff --git a/src/modules/mpd/mpd.cpp b/src/modules/mpd/mpd.cpp index 192e6c1a..fdf16f0e 100644 --- a/src/modules/mpd/mpd.cpp +++ b/src/modules/mpd/mpd.cpp @@ -6,6 +6,7 @@ #include #include +#include using namespace waybar::util; #include "modules/mpd/state.hpp" @@ -24,7 +25,8 @@ waybar::modules::MPD::MPD(const std::string& id, const Json::Value& config) timeout_(config_["timeout"].isUInt() ? config_["timeout"].asUInt() * 1'000 : 30'000), connection_(nullptr, &mpd_connection_free), status_(nullptr, &mpd_status_free), - song_(nullptr, &mpd_song_free) { + song_(nullptr, &mpd_song_free), + ellipsis_(config_["ellipsis"].isString() ? config_["ellipsis"].asString() : "\u2026") { if (!config_["port"].isNull() && !config_["port"].isUInt()) { spdlog::warn("{}: `port` configuration should be an unsigned int", module_name_); } @@ -51,21 +53,6 @@ auto waybar::modules::MPD::update() -> void { ALabel::update(); } -void waybar::modules::MPD::queryMPD() { - if (connection_ != nullptr) { - spdlog::trace("{}: fetching state information", module_name_); - try { - fetchState(); - spdlog::trace("{}: fetch complete", module_name_); - } catch (std::exception const& e) { - spdlog::error("{}: {}", module_name_, e.what()); - state_ = MPD_STATE_UNKNOWN; - } - - dp.emit(); - } -} - std::string waybar::modules::MPD::getTag(mpd_tag_type type, unsigned idx) const { std::string result = config_["unknown-tag"].isString() ? config_["unknown-tag"].asString() : "N/A"; @@ -98,7 +85,7 @@ void waybar::modules::MPD::setLabel() { ? config_["format-disconnected"].asString() : "disconnected"; if (format.empty()) { - label_.set_markup(format); + setLabelMarkup(format); label_.show(); } else { label_.hide(); @@ -110,22 +97,22 @@ void waybar::modules::MPD::setLabel() { ? config_["tooltip-format-disconnected"].asString() : "MPD (disconnected)"; // Nothing to format - label_.set_tooltip_text(tooltip_format); + setTooltipMarkup(tooltip_format); } return; } label_.get_style_context()->remove_class("disconnected"); auto format = format_; - Glib::ustring artist, album_artist, album, title; - std::string date, filename; + std::string date, filename, uri; int song_pos = 0, queue_length = 0, volume = 0; std::chrono::seconds elapsedTime, totalTime; std::string stateIcon = ""; bool no_song = song_.get() == nullptr; - if (stopped() || no_song) { - if (no_song) spdlog::warn("Bug in mpd: no current song but state is not stopped."); + bool is_stopped = stopped(); + if (is_stopped || no_song) { + if (no_song && !is_stopped) spdlog::warn("mpd: no current song while state is not stopped"); format = config_["format-stopped"].isString() ? config_["format-stopped"].asString() : "stopped"; label_.get_style_context()->add_class("stopped"); @@ -137,20 +124,18 @@ void waybar::modules::MPD::setLabel() { label_.get_style_context()->add_class("playing"); label_.get_style_context()->remove_class("paused"); } else if (paused()) { - format = config_["format-paused"].isString() ? config_["format-paused"].asString() - : config_["format"].asString(); + if (config_["format-paused"].isString()) { + format = config_["format-paused"].asString(); + } label_.get_style_context()->add_class("paused"); label_.get_style_context()->remove_class("playing"); } stateIcon = getStateIcon(); - artist = sanitize_string(getTag(MPD_TAG_ARTIST)); - album_artist = sanitize_string(getTag(MPD_TAG_ALBUM_ARTIST)); - album = sanitize_string(getTag(MPD_TAG_ALBUM)); - title = sanitize_string(getTag(MPD_TAG_TITLE)); date = sanitize_string(getTag(MPD_TAG_DATE)); filename = sanitize_string(getFilename()); + uri = mpd_song_get_uri(song_.get()); song_pos = mpd_status_get_song_pos(status_.get()) + 1; volume = mpd_status_get_volume(status_.get()); if (volume < 0) { @@ -169,27 +154,22 @@ void waybar::modules::MPD::setLabel() { std::string repeatIcon = getOptionIcon("repeat", repeatActivated); bool singleActivated = mpd_status_get_single(status_.get()); std::string singleIcon = getOptionIcon("single", singleActivated); - if (config_["artist-len"].isInt()) artist = artist.substr(0, config_["artist-len"].asInt()); - if (config_["album-artist-len"].isInt()) - album_artist = album_artist.substr(0, config_["album-artist-len"].asInt()); - if (config_["album-len"].isInt()) album = album.substr(0, config_["album-len"].asInt()); - if (config_["title-len"].isInt()) title = title.substr(0, config_["title-len"].asInt()); try { auto text = fmt::format( - fmt::runtime(format), fmt::arg("artist", artist.raw()), - fmt::arg("albumArtist", album_artist.raw()), fmt::arg("album", album.raw()), - fmt::arg("title", title.raw()), fmt::arg("date", date), fmt::arg("volume", volume), + fmt::runtime(format), fmt::arg("artist", getArtistStr(true)), + fmt::arg("albumArtist", getAlbumArtistStr(true)), fmt::arg("album", getAlbumStr(true)), + fmt::arg("title", getTitleStr(true)), fmt::arg("date", date), fmt::arg("volume", volume), fmt::arg("elapsedTime", elapsedTime), fmt::arg("totalTime", totalTime), fmt::arg("songPosition", song_pos), fmt::arg("queueLength", queue_length), fmt::arg("stateIcon", stateIcon), fmt::arg("consumeIcon", consumeIcon), fmt::arg("randomIcon", randomIcon), fmt::arg("repeatIcon", repeatIcon), - fmt::arg("singleIcon", singleIcon), fmt::arg("filename", filename)); + fmt::arg("singleIcon", singleIcon), fmt::arg("filename", filename), fmt::arg("uri", uri)); if (text.empty()) { label_.hide(); } else { label_.show(); - label_.set_markup(text); + setLabelMarkup(text); } } catch (fmt::format_error const& e) { spdlog::warn("mpd: format error: {}", e.what()); @@ -200,16 +180,16 @@ void waybar::modules::MPD::setLabel() { tooltip_format = config_["tooltip-format"].isString() ? config_["tooltip-format"].asString() : "MPD (connected)"; try { - auto tooltip_text = - fmt::format(fmt::runtime(tooltip_format), fmt::arg("artist", artist.raw()), - fmt::arg("albumArtist", album_artist.raw()), fmt::arg("album", album.raw()), - fmt::arg("title", title.raw()), fmt::arg("date", date), - fmt::arg("volume", volume), fmt::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); + auto tooltip_text = fmt::format( + fmt::runtime(tooltip_format), fmt::arg("artist", getArtistStr(false)), + fmt::arg("albumArtist", getAlbumArtistStr(false)), fmt::arg("album", getAlbumStr(false)), + fmt::arg("title", getTitleStr(false)), fmt::arg("date", date), fmt::arg("volume", volume), + fmt::arg("elapsedTime", elapsedTime), fmt::arg("totalTime", totalTime), + fmt::arg("songPosition", song_pos), fmt::arg("queueLength", queue_length), + fmt::arg("stateIcon", stateIcon), fmt::arg("consumeIcon", consumeIcon), + fmt::arg("randomIcon", randomIcon), fmt::arg("repeatIcon", repeatIcon), + fmt::arg("singleIcon", singleIcon), fmt::arg("filename", filename), fmt::arg("uri", uri)); + setTooltipMarkup(tooltip_text); } catch (fmt::format_error const& e) { spdlog::warn("mpd: format error (tooltip): {}", e.what()); } @@ -238,7 +218,8 @@ std::string waybar::modules::MPD::getStateIcon() const { } } -std::string waybar::modules::MPD::getOptionIcon(std::string optionName, bool activated) const { +std::string waybar::modules::MPD::getOptionIcon(const std::string& optionName, + bool activated) const { if (!config_[optionName + "-icons"].isObject()) { return ""; } @@ -255,6 +236,38 @@ std::string waybar::modules::MPD::getOptionIcon(std::string optionName, bool act } } +std::string waybar::modules::MPD::getArtistStr(bool truncated) const { + std::string artist = getTag(MPD_TAG_ARTIST); + if (truncated && config_["artist-len"].isInt()) { + waybar::util::utf8_truncate(artist, ellipsis_, config_["artist-len"].asInt()); + } + return sanitize_string(artist); +} + +std::string waybar::modules::MPD::getAlbumArtistStr(bool truncated) const { + std::string album_artist = getTag(MPD_TAG_ALBUM_ARTIST); + if (truncated && config_["album-artist-len"].isInt()) { + waybar::util::utf8_truncate(album_artist, ellipsis_, config_["album-artist-len"].asInt()); + } + return sanitize_string(album_artist); +} + +std::string waybar::modules::MPD::getAlbumStr(bool truncated) const { + std::string album = getTag(MPD_TAG_ALBUM); + if (truncated && config_["album-len"].isInt()) { + waybar::util::utf8_truncate(album, ellipsis_, config_["album-len"].asInt()); + } + return sanitize_string(album); +} + +std::string waybar::modules::MPD::getTitleStr(bool truncated) const { + std::string title = getTag(MPD_TAG_TITLE); + if (truncated && config_["title-len"].isInt()) { + waybar::util::utf8_truncate(title, ellipsis_, config_["title-len"].asInt()); + } + return sanitize_string(title); +} + static bool isServerUnavailable(const std::error_code& ec) { if (ec.category() == std::system_category()) { switch (ec.value()) { @@ -322,6 +335,7 @@ void waybar::modules::MPD::checkErrors(mpd_connection* conn) { case MPD_ERROR_SYSTEM: if (auto ec = mpd_connection_get_system_error(conn); ec != 0) { mpd_connection_clear_error(conn); + connection_.reset(); throw std::system_error(ec, std::system_category()); } G_GNUC_FALLTHROUGH; diff --git a/src/modules/mpd/state.cpp b/src/modules/mpd/state.cpp index 3d7c8561..eb95665f 100644 --- a/src/modules/mpd/state.cpp +++ b/src/modules/mpd/state.cpp @@ -152,7 +152,6 @@ bool Playing::on_timer() { return false; } - ctx_->queryMPD(); ctx_->emit(); } catch (std::exception const& e) { spdlog::warn("mpd: Playing: error: {}", e.what()); diff --git a/src/modules/mpris/mpris.cpp b/src/modules/mpris/mpris.cpp index ed383b0c..13ba836d 100644 --- a/src/modules/mpris/mpris.cpp +++ b/src/modules/mpris/mpris.cpp @@ -7,6 +7,7 @@ #include #include "util/scope_guard.hpp" +#include "util/utf8_string.hpp" extern "C" { #include @@ -14,7 +15,6 @@ extern "C" { #include #include - namespace waybar::modules::mpris { const std::string DEFAULT_FORMAT = "{player} ({status}): {dynamic}"; @@ -110,6 +110,7 @@ Mpris::Mpris(const std::string& id, const Json::Value& config) player_ = config_["player"].asString(); } if (config_["ignored-players"].isArray()) { + ignored_players_.reserve(config_["ignored-players"].size()); for (const auto& item : config_["ignored-players"]) { if (item.isString()) { ignored_players_.push_back(item.asString()); @@ -118,7 +119,7 @@ Mpris::Mpris(const std::string& id, const Json::Value& config) } GError* error = nullptr; - waybar::util::ScopeGuard error_deleter([error]() { + waybar::util::ScopeGuard error_deleter([&error]() { if (error) { g_error_free(error); } @@ -162,8 +163,7 @@ Mpris::Mpris(const std::string& id, const Json::Value& config) if (player) { g_object_connect(player, "signal::play", G_CALLBACK(onPlayerPlay), this, "signal::pause", G_CALLBACK(onPlayerPause), this, "signal::stop", G_CALLBACK(onPlayerStop), - this, "signal::stop", G_CALLBACK(onPlayerStop), this, "signal::metadata", - G_CALLBACK(onPlayerMetadata), this, NULL); + this, "signal::metadata", G_CALLBACK(onPlayerMetadata), this, NULL); } // allow setting an interval count that triggers periodic refreshes @@ -179,8 +179,17 @@ Mpris::Mpris(const std::string& id, const Json::Value& config) } Mpris::~Mpris() { - if (manager != nullptr) g_object_unref(manager); - if (player != nullptr) g_object_unref(player); + if (manager != nullptr) { + g_signal_handlers_disconnect_by_data(manager, this); + } + if (player != nullptr) { + g_signal_handlers_disconnect_by_data(player, this); + } + if (last_active_player_ != nullptr && last_active_player_ != player) { + g_object_unref(last_active_player_); + } + g_clear_object(&manager); + g_clear_object(&player); } auto Mpris::getIconFromJson(const Json::Value& icons, const std::string& key) -> std::string { @@ -194,69 +203,22 @@ auto Mpris::getIconFromJson(const Json::Value& icons, const std::string& key) -> // Wide characters count as two, zero-width characters count as zero // Modifies str in-place (unless width = std::string::npos) // Returns the total width of the string pre-truncating -size_t utf8_truncate(std::string& str, size_t width = std::string::npos) { - if (str.length() == 0) return 0; - - const gchar* trunc_end = nullptr; - - size_t total_width = 0; - - for (gchar *data = str.data(), *end = data + str.size(); data != nullptr;) { - gunichar c = g_utf8_get_char_validated(data, end - data); - if (c == -1U || c == -2U) { - // invalid unicode, treat string as ascii - if (width != std::string::npos && str.length() > width) str.resize(width); - return str.length(); - } else if (g_unichar_iswide(c)) { - total_width += 2; - } else if (!g_unichar_iszerowidth(c) && c != 0xAD) { // neither zero-width nor soft hyphen - total_width += 1; - } - - data = g_utf8_find_next_char(data, end); - if (width != std::string::npos && total_width <= width && !g_unichar_isspace(c)) - trunc_end = data; - } - - if (trunc_end) str.resize(trunc_end - str.data()); - - return total_width; -} - -size_t utf8_width(const std::string& str) { return utf8_truncate(const_cast(str)); } - -void truncate(std::string& s, const std::string& ellipsis, size_t max_len) { - if (max_len == 0) { - s.resize(0); - return; - } - size_t len = utf8_truncate(s, max_len); - if (len > max_len) { - size_t ellipsis_len = utf8_width(ellipsis); - if (max_len >= ellipsis_len) { - if (ellipsis_len) utf8_truncate(s, max_len - ellipsis_len); - s += ellipsis; - } else { - s.resize(0); - } - } -} auto Mpris::getArtistStr(const PlayerInfo& info, bool truncated) -> std::string { auto artist = info.artist.value_or(std::string()); - if (truncated && artist_len_ >= 0) truncate(artist, ellipsis_, artist_len_); + if (truncated && artist_len_ >= 0) waybar::util::utf8_truncate(artist, ellipsis_, artist_len_); return artist; } auto Mpris::getAlbumStr(const PlayerInfo& info, bool truncated) -> std::string { auto album = info.album.value_or(std::string()); - if (truncated && album_len_ >= 0) truncate(album, ellipsis_, album_len_); + if (truncated && album_len_ >= 0) waybar::util::utf8_truncate(album, ellipsis_, album_len_); return album; } auto Mpris::getTitleStr(const PlayerInfo& info, bool truncated) -> std::string { auto title = info.title.value_or(std::string()); - if (truncated && title_len_ >= 0) truncate(title, ellipsis_, title_len_); + if (truncated && title_len_ >= 0) waybar::util::utf8_truncate(title, ellipsis_, title_len_); return title; } @@ -284,9 +246,9 @@ auto Mpris::getDynamicStr(const PlayerInfo& info, bool truncated, bool html) -> // keep position format same as length format auto position = getPositionStr(info, truncated && truncate_hours_ && length.length() < 6); - size_t artistLen = utf8_width(artist); - size_t albumLen = utf8_width(album); - size_t titleLen = utf8_width(title); + size_t artistLen = waybar::util::utf8_width(artist); + size_t albumLen = waybar::util::utf8_width(album); + size_t titleLen = waybar::util::utf8_width(title); size_t lengthLen = length.length(); size_t posLen = position.length(); @@ -305,7 +267,7 @@ auto Mpris::getDynamicStr(const PlayerInfo& info, bool truncated, bool html) -> // Since the first element doesn't present a separator and we don't know a priori which one // it will be, we add a "virtual separatorLen" to the dynamicLen, since we are adding the // separatorLen to all the other lengths. - size_t separatorLen = utf8_width(dynamic_separator_); + size_t separatorLen = waybar::util::utf8_width(dynamic_separator_); size_t dynamicLen = dynamic_len_ + separatorLen; if (showArtist) artistLen += separatorLen; if (showAlbum) albumLen += separatorLen; @@ -411,11 +373,14 @@ auto Mpris::onPlayerNameAppeared(PlayerctlPlayerManager* manager, PlayerctlPlaye return; } + if (mpris->player != nullptr) { + g_signal_handlers_disconnect_by_data(mpris->player, mpris); + g_clear_object(&mpris->player); + } mpris->player = playerctl_player_new_from_name(player_name, nullptr); g_object_connect(mpris->player, "signal::play", G_CALLBACK(onPlayerPlay), mpris, "signal::pause", G_CALLBACK(onPlayerPause), mpris, "signal::stop", G_CALLBACK(onPlayerStop), - mpris, "signal::stop", G_CALLBACK(onPlayerStop), mpris, "signal::metadata", - G_CALLBACK(onPlayerMetadata), mpris, NULL); + mpris, "signal::metadata", G_CALLBACK(onPlayerMetadata), mpris, NULL); mpris->dp.emit(); } @@ -425,9 +390,11 @@ auto Mpris::onPlayerNameVanished(PlayerctlPlayerManager* manager, PlayerctlPlaye auto* mpris = static_cast(data); if (!mpris) return; - spdlog::debug("mpris: player-vanished callback: {}", player_name->name); + spdlog::debug("mpris: name-vanished callback: {}", player_name->name); - if (std::string(player_name->name) == mpris->player_) { + if (mpris->player_ == "playerctld") { + mpris->dp.emit(); + } else if (mpris->player_ == player_name->name) { mpris->player = nullptr; mpris->event_box_.set_visible(false); mpris->dp.emit(); @@ -457,10 +424,7 @@ auto Mpris::onPlayerStop(PlayerctlPlayer* player, gpointer data) -> void { if (!mpris) return; spdlog::debug("mpris: player-stop callback"); - - // hide widget - mpris->event_box_.set_visible(false); - // update widget + // update widget (update() handles visibility) mpris->dp.emit(); } @@ -479,7 +443,7 @@ auto Mpris::getPlayerInfo() -> std::optional { } GError* error = nullptr; - waybar::util::ScopeGuard error_deleter([error]() { + waybar::util::ScopeGuard error_deleter([&error]() { if (error) { g_error_free(error); } @@ -487,7 +451,12 @@ auto Mpris::getPlayerInfo() -> std::optional { char* player_status = nullptr; auto player_playback_status = PLAYERCTL_PLAYBACK_STATUS_STOPPED; - g_object_get(player, "status", &player_status, "playback-status", &player_playback_status, NULL); + + // Clean up previous fallback player + if (last_active_player_ && last_active_player_ != player) { + g_object_unref(last_active_player_); + last_active_player_ = nullptr; + } std::string player_name = player_; if (player_name == "playerctld") { @@ -497,16 +466,52 @@ auto Mpris::getPlayerInfo() -> std::optional { } // > get the list of players [..] in order of activity // https://github.com/altdesktop/playerctl/blob/b19a71cb9dba635df68d271bd2b3f6a99336a223/playerctl/playerctl-common.c#L248-L249 - players = g_list_first(players); - if (players) player_name = static_cast(players->data)->name; - } - - if (std::any_of(ignored_players_.begin(), ignored_players_.end(), - [&](const std::string& pn) { return player_name == pn; })) { + PlayerctlPlayer* first_valid_player = nullptr; + std::string first_valid_name; + for (auto* p = g_list_first(players); p != nullptr; p = p->next) { + auto* pn = static_cast(p->data); + std::string name = pn->name; + if (std::any_of(ignored_players_.begin(), ignored_players_.end(), + [&](const std::string& ignored) { return name == ignored; })) { + spdlog::warn("mpris[{}]: ignoring player update", name); + continue; + } + auto* tmp = playerctl_player_new_from_name(pn, &error); + if (error || !tmp) continue; + if (!first_valid_player) { + first_valid_player = tmp; + first_valid_name = name; + } + PlayerctlPlaybackStatus status; + g_object_get(tmp, "playback-status", &status, NULL); + if (status == PLAYERCTL_PLAYBACK_STATUS_PLAYING) { + if (tmp != first_valid_player) g_object_unref(first_valid_player); + last_active_player_ = tmp; + player_name = name; + break; + } + if (tmp != first_valid_player) g_object_unref(tmp); + } + if (!last_active_player_) { + if (!first_valid_player) return std::nullopt; + last_active_player_ = first_valid_player; + player_name = first_valid_name; + } + } else if (std::any_of(ignored_players_.begin(), ignored_players_.end(), + [&](const std::string& pn) { return player_name == pn; })) { spdlog::warn("mpris[{}]: ignoring player update", player_name); return std::nullopt; + } else { + last_active_player_ = player; } + g_object_get(last_active_player_, "status", &player_status, "playback-status", + &player_playback_status, NULL); + + if (!player_status) { + spdlog::error("mpris: failed to get player status"); + return std::nullopt; + } // make status lowercase player_status[0] = std::tolower(player_status[0]); @@ -520,28 +525,29 @@ auto Mpris::getPlayerInfo() -> std::optional { .length = std::nullopt, }; - if (auto* artist_ = playerctl_player_get_artist(player, &error)) { + if (auto* artist_ = playerctl_player_get_artist(last_active_player_, &error)) { spdlog::debug("mpris[{}]: artist = {}", info.name, artist_); info.artist = artist_; g_free(artist_); } if (error) goto errorexit; - if (auto* album_ = playerctl_player_get_album(player, &error)) { + if (auto* album_ = playerctl_player_get_album(last_active_player_, &error)) { spdlog::debug("mpris[{}]: album = {}", info.name, album_); info.album = album_; g_free(album_); } if (error) goto errorexit; - if (auto* title_ = playerctl_player_get_title(player, &error)) { + if (auto* title_ = playerctl_player_get_title(last_active_player_, &error)) { spdlog::debug("mpris[{}]: title = {}", info.name, title_); info.title = title_; g_free(title_); } if (error) goto errorexit; - if (auto* length_ = playerctl_player_print_metadata_prop(player, "mpris:length", &error)) { + if (auto* length_ = + playerctl_player_print_metadata_prop(last_active_player_, "mpris:length", &error)) { spdlog::debug("mpris[{}]: mpris:length = {}", info.name, length_); auto len = std::chrono::microseconds(std::strtol(length_, nullptr, 10)); auto len_h = std::chrono::duration_cast(len); @@ -553,7 +559,7 @@ auto Mpris::getPlayerInfo() -> std::optional { if (error) goto errorexit; { - auto position_ = playerctl_player_get_position(player, &error); + auto position_ = playerctl_player_get_position(last_active_player_, &error); if (error) { // it's fine to have an error here because not all players report a position g_error_free(error); @@ -584,38 +590,46 @@ errorexit: } bool Mpris::handleToggle(GdkEventButton* const& e) { + if (!e || e->type != GdkEventType::GDK_BUTTON_PRESS) { + return false; + } + + auto info = getPlayerInfo(); + if (!info) return false; + + struct ButtonAction { + guint button; + const char* config_key; + std::function builtin_action; + }; + GError* error = nullptr; - waybar::util::ScopeGuard error_deleter([error]() { + waybar::util::ScopeGuard error_deleter([&error]() { if (error) { g_error_free(error); } }); - auto info = getPlayerInfo(); - if (!info) return false; + // Command pattern: encapsulate each button's action + auto* target = last_active_player_ ? last_active_player_ : player; + const ButtonAction actions[] = { + {1, "on-click", [&]() { playerctl_player_play_pause(target, &error); }}, + {2, "on-click-middle", [&]() { playerctl_player_previous(target, &error); }}, + {3, "on-click-right", [&]() { playerctl_player_next(target, &error); }}, + {8, "on-click-backward", [&]() { playerctl_player_previous(target, &error); }}, + {9, "on-click-forward", [&]() { playerctl_player_next(target, &error); }}, + }; - if (e->type == GdkEventType::GDK_BUTTON_PRESS) { - switch (e->button) { - case 1: // left-click - if (config_["on-click"].isString()) { - return ALabel::handleToggle(e); - } - playerctl_player_play_pause(player, &error); - break; - case 2: // middle-click - if (config_["on-click-middle"].isString()) { - return ALabel::handleToggle(e); - } - playerctl_player_previous(player, &error); - break; - case 3: // right-click - if (config_["on-click-right"].isString()) { - return ALabel::handleToggle(e); - } - playerctl_player_next(player, &error); - break; + for (const auto& action : actions) { + if (e->button == action.button) { + if (config_[action.config_key].isString()) { + return ALabel::handleToggle(e); + } + action.builtin_action(); + break; } } + if (error) { spdlog::error("mpris[{}]: error running builtin on-click action: {}", (*info).name, error->message); @@ -715,15 +729,18 @@ auto Mpris::update() -> void { auto tooltip_text = fmt::format( fmt::runtime(tooltipstr), fmt::arg("player", info.name), fmt::arg("status", info.status_string), - fmt::arg("artist", getArtistStr(info, tooltip_len_limits_)), - fmt::arg("title", getTitleStr(info, tooltip_len_limits_)), - fmt::arg("album", getAlbumStr(info, tooltip_len_limits_)), + fmt::arg("artist", + std::string(Glib::Markup::escape_text(getArtistStr(info, tooltip_len_limits_)))), + fmt::arg("title", + std::string(Glib::Markup::escape_text(getTitleStr(info, tooltip_len_limits_)))), + fmt::arg("album", + std::string(Glib::Markup::escape_text(getAlbumStr(info, tooltip_len_limits_)))), fmt::arg("length", tooltipLength), fmt::arg("position", tooltipPosition), fmt::arg("dynamic", getDynamicStr(info, tooltip_len_limits_, false)), fmt::arg("player_icon", getIconFromJson(config_["player-icons"], info.name)), fmt::arg("status_icon", getIconFromJson(config_["status-icons"], info.status_string))); - label_.set_tooltip_text(tooltip_text); + label_.set_tooltip_markup(tooltip_text); } catch (fmt::format_error const& e) { spdlog::warn("mpris: format error (tooltip): {}", e.what()); } diff --git a/src/modules/network.cpp b/src/modules/network.cpp index 0a77c00e..f43893c5 100644 --- a/src/modules/network.cpp +++ b/src/modules/network.cpp @@ -1,13 +1,18 @@ #include "modules/network.hpp" #include +#include +#include #include #include #include +#include #include #include #include +#include +#include #include "util/format.hpp" #ifdef WANT_RFKILL @@ -16,10 +21,10 @@ namespace { using namespace waybar::util; -constexpr const char *DEFAULT_FORMAT = "{ifname}"; +constexpr const char* DEFAULT_FORMAT = "{ifname}"; } // namespace -constexpr const char *NETDEV_FILE = +constexpr const char* NETDEV_FILE = "/proc/net/dev"; // std::ifstream does not take std::string_view as param std::optional> waybar::modules::Network::readBandwidthUsage() { @@ -40,7 +45,8 @@ waybar::modules::Network::readBandwidthUsage() { std::istringstream iss(line); std::string ifacename; - iss >> ifacename; // ifacename contains "eth0:" + iss >> ifacename; // ifacename contains "eth0:" + if (ifacename.empty()) continue; ifacename.pop_back(); // remove trailing ':' if (ifacename != ifname_) { continue; @@ -77,26 +83,8 @@ waybar::modules::Network::readBandwidthUsage() { return {{receivedBytes, transmittedBytes}}; } -waybar::modules::Network::Network(const std::string &id, const Json::Value &config) - : ALabel(config, "network", id, DEFAULT_FORMAT, 60), - ifid_(-1), - addr_pref_(IPV4), - efd_(-1), - ev_fd_(-1), - want_route_dump_(false), - want_link_dump_(false), - want_addr_dump_(false), - dump_in_progress_(false), - is_p2p_(false), - cidr_(0), - cidr6_(0), - signal_strength_dbm_(0), - signal_strength_(0), -#ifdef WANT_RFKILL - rfkill_{RFKILL_TYPE_WLAN}, -#endif - frequency_(0.0) { - +waybar::modules::Network::Network(const std::string& id, const Json::Value& config) + : ALabel(config, "network", id, DEFAULT_FORMAT, 60) { // Start with some "text" in the module's label_. update() will then // update it. Since the text should be different, update() will be able // to show or hide the event_box_. This is to work around the case where @@ -117,6 +105,7 @@ waybar::modules::Network::Network(const std::string &id, const Json::Value &conf bandwidth_down_total_ = 0; bandwidth_up_total_ = 0; } + bandwidth_last_sample_time_ = std::chrono::steady_clock::now(); if (!config_["interface"].isString()) { // "interface" isn't configured, then try to guess the external @@ -223,13 +212,13 @@ void waybar::modules::Network::worker() { std::lock_guard lock(mutex_); if (ifid_ > 0) { getInfo(); - dp.emit(); } + dp.emit(); } thread_timer_.sleep_for(interval_); }; #ifdef WANT_RFKILL - rfkill_.on_update.connect([this](auto &) { + rfkill_.on_update.connect([this](auto&) { /* If we are here, it's likely that the network thread already holds the mutex and will be * holding it for a next few seconds. * Let's delegate the update to the timer thread instead of blocking the main thread. @@ -271,13 +260,16 @@ void waybar::modules::Network::worker() { } const std::string waybar::modules::Network::getNetworkState() const { - if (ifid_ == -1) { + if (ifid_ == -1 || !carrier_) { #ifdef WANT_RFKILL - if (rfkill_.getState()) return "disabled"; + bool display_rfkill = true; + if (config_["rfkill"].isBool()) { + display_rfkill = config_["rfkill"].asBool(); + } + if (rfkill_.getState() && display_rfkill) return "disabled"; #endif return "disconnected"; } - if (!carrier_) return "disconnected"; if (ipaddr_.empty() && ipaddr6_.empty()) return "linked"; if (essid_.empty()) return "ethernet"; return "wifi"; @@ -286,19 +278,41 @@ const std::string waybar::modules::Network::getNetworkState() const { auto waybar::modules::Network::update() -> void { std::lock_guard lock(mutex_); std::string tooltip_format; + auto now = std::chrono::steady_clock::now(); + auto elapsed_seconds = std::chrono::duration(now - bandwidth_last_sample_time_).count(); - auto bandwidth = readBandwidthUsage(); auto bandwidth_down = 0ull; auto bandwidth_up = 0ull; - if (bandwidth.has_value()) { - auto down_octets = (*bandwidth).first; - auto up_octets = (*bandwidth).second; - bandwidth_down = down_octets - bandwidth_down_total_; - bandwidth_down_total_ = down_octets; + // Only recalculate bandwidth when enough time has elapsed since the last + // sample. Event-driven dp.emit() calls (link/addr/route changes) can + // trigger update() between timer intervals, which would consume the byte + // delta prematurely and show near-zero bandwidth. + auto min_elapsed = std::chrono::duration(interval_).count() * 0.5; + if (elapsed_seconds >= min_elapsed) { + if (elapsed_seconds <= 0.0) { + elapsed_seconds = std::chrono::duration(interval_).count(); + } + bandwidth_last_sample_time_ = now; - bandwidth_up = up_octets - bandwidth_up_total_; - bandwidth_up_total_ = up_octets; + auto bandwidth = readBandwidthUsage(); + if (bandwidth.has_value()) { + auto down_octets = (*bandwidth).first; + auto up_octets = (*bandwidth).second; + + bandwidth_down = down_octets - bandwidth_down_total_; + bandwidth_down_total_ = down_octets; + + bandwidth_up = up_octets - bandwidth_up_total_; + bandwidth_up_total_ = up_octets; + + bandwidth_down_prev_ = bandwidth_down; + bandwidth_up_prev_ = bandwidth_up; + } + } else { + bandwidth_down = bandwidth_down_prev_; + bandwidth_up = bandwidth_up_prev_; + elapsed_seconds = std::chrono::duration(interval_).count(); } if (!alt_) { @@ -330,6 +344,7 @@ auto waybar::modules::Network::update() -> void { } else if (addr_pref_ == ip_addr_pref::IPV6) { final_ipaddr_ = ipaddr6_; } else if (addr_pref_ == ip_addr_pref::IPV4_6) { + final_ipaddr_.reserve(ipaddr_.length() + ipaddr6_.length() + 1); final_ipaddr_ = ipaddr_; final_ipaddr_ += '\n'; final_ipaddr_ += ipaddr6_; @@ -343,18 +358,18 @@ auto waybar::modules::Network::update() -> void { fmt::arg("ipaddr", final_ipaddr_), fmt::arg("gwaddr", gwaddr_), fmt::arg("cidr", cidr_), fmt::arg("cidr6", cidr6_), fmt::arg("frequency", fmt::format("{:.1f}", frequency_)), fmt::arg("icon", getIcon(signal_strength_, state_)), - fmt::arg("bandwidthDownBits", pow_format(bandwidth_down * 8ull / interval_.count(), "b/s")), - fmt::arg("bandwidthUpBits", pow_format(bandwidth_up * 8ull / interval_.count(), "b/s")), + fmt::arg("bandwidthDownBits", pow_format(bandwidth_down * 8ull / elapsed_seconds, "b/s")), + fmt::arg("bandwidthUpBits", pow_format(bandwidth_up * 8ull / elapsed_seconds, "b/s")), fmt::arg("bandwidthTotalBits", - pow_format((bandwidth_up + bandwidth_down) * 8ull / interval_.count(), "b/s")), - fmt::arg("bandwidthDownOctets", pow_format(bandwidth_down / interval_.count(), "o/s")), - fmt::arg("bandwidthUpOctets", pow_format(bandwidth_up / interval_.count(), "o/s")), + pow_format((bandwidth_up + bandwidth_down) * 8ull / elapsed_seconds, "b/s")), + fmt::arg("bandwidthDownOctets", pow_format(bandwidth_down / elapsed_seconds, "o/s")), + fmt::arg("bandwidthUpOctets", pow_format(bandwidth_up / elapsed_seconds, "o/s")), fmt::arg("bandwidthTotalOctets", - pow_format((bandwidth_up + bandwidth_down) / interval_.count(), "o/s")), - fmt::arg("bandwidthDownBytes", pow_format(bandwidth_down / interval_.count(), "B/s")), - fmt::arg("bandwidthUpBytes", pow_format(bandwidth_up / interval_.count(), "B/s")), + pow_format((bandwidth_up + bandwidth_down) / elapsed_seconds, "o/s")), + fmt::arg("bandwidthDownBytes", pow_format(bandwidth_down / elapsed_seconds, "B/s")), + fmt::arg("bandwidthUpBytes", pow_format(bandwidth_up / elapsed_seconds, "B/s")), fmt::arg("bandwidthTotalBytes", - pow_format((bandwidth_up + bandwidth_down) / interval_.count(), "B/s"))); + pow_format((bandwidth_up + bandwidth_down) / elapsed_seconds, "B/s"))); if (text.compare(label_.get_label()) != 0) { label_.set_markup(text); if (text.empty()) { @@ -376,19 +391,18 @@ auto waybar::modules::Network::update() -> void { fmt::arg("ipaddr", final_ipaddr_), fmt::arg("gwaddr", gwaddr_), fmt::arg("cidr", cidr_), fmt::arg("cidr6", cidr6_), fmt::arg("frequency", fmt::format("{:.1f}", frequency_)), fmt::arg("icon", getIcon(signal_strength_, state_)), - fmt::arg("bandwidthDownBits", - pow_format(bandwidth_down * 8ull / interval_.count(), "b/s")), - fmt::arg("bandwidthUpBits", pow_format(bandwidth_up * 8ull / interval_.count(), "b/s")), + fmt::arg("bandwidthDownBits", pow_format(bandwidth_down * 8ull / elapsed_seconds, "b/s")), + fmt::arg("bandwidthUpBits", pow_format(bandwidth_up * 8ull / elapsed_seconds, "b/s")), fmt::arg("bandwidthTotalBits", - pow_format((bandwidth_up + bandwidth_down) * 8ull / interval_.count(), "b/s")), - fmt::arg("bandwidthDownOctets", pow_format(bandwidth_down / interval_.count(), "o/s")), - fmt::arg("bandwidthUpOctets", pow_format(bandwidth_up / interval_.count(), "o/s")), + pow_format((bandwidth_up + bandwidth_down) * 8ull / elapsed_seconds, "b/s")), + fmt::arg("bandwidthDownOctets", pow_format(bandwidth_down / elapsed_seconds, "o/s")), + fmt::arg("bandwidthUpOctets", pow_format(bandwidth_up / elapsed_seconds, "o/s")), fmt::arg("bandwidthTotalOctets", - pow_format((bandwidth_up + bandwidth_down) / interval_.count(), "o/s")), - fmt::arg("bandwidthDownBytes", pow_format(bandwidth_down / interval_.count(), "B/s")), - fmt::arg("bandwidthUpBytes", pow_format(bandwidth_up / interval_.count(), "B/s")), + pow_format((bandwidth_up + bandwidth_down) / elapsed_seconds, "o/s")), + fmt::arg("bandwidthDownBytes", pow_format(bandwidth_down / elapsed_seconds, "B/s")), + fmt::arg("bandwidthUpBytes", pow_format(bandwidth_up / elapsed_seconds, "B/s")), fmt::arg("bandwidthTotalBytes", - pow_format((bandwidth_up + bandwidth_down) / interval_.count(), "B/s"))); + pow_format((bandwidth_up + bandwidth_down) / elapsed_seconds, "B/s"))); if (label_.get_tooltip_text() != tooltip_text) { label_.set_tooltip_markup(tooltip_text); } @@ -401,11 +415,65 @@ auto waybar::modules::Network::update() -> void { ALabel::update(); } -bool waybar::modules::Network::checkInterface(std::string name) { - if (config_["interface"].isString()) { - return config_["interface"].asString() == name || - wildcardMatch(config_["interface"].asString(), name); +// https://gist.github.com/rressi/92af77630faf055934c723ce93ae2495 +static bool wildcardMatch(const std::string& pattern, const std::string& text) { + auto P = int(pattern.size()); + auto T = int(text.size()); + + auto p = 0, fallback_p = -1; + auto t = 0, fallback_t = -1; + + while (t < T) { + // Wildcard match: + if (p < P && pattern[p] == '*') { + fallback_p = p++; // starting point after failures + fallback_t = t; // starting point after failures + } + + // Simple match: + else if (p < P && (pattern[p] == '?' || pattern[p] == text[t])) { + p++; + t++; + } + + // Failure, fall back just after last matched '*': + else if (fallback_p >= 0) { + p = fallback_p + 1; // position just after last matched '*" + t = ++fallback_t; // re-try to match text from here + } + + // There were no '*' before, so we fail here: + else { + return false; + } } + + // Consume all '*' at the end of pattern: + while (p < P && pattern[p] == '*') p++; + + return p == P; +} + +bool waybar::modules::Network::matchInterface(const std::string& ifname, + const std::vector& altnames, + std::string& matched) const { + if (!config_["interface"].isString()) { + return false; + } + + auto config_ifname = config_["interface"].asString(); + if (config_ifname == ifname || wildcardMatch(config_ifname, ifname)) { + matched = ifname; + return true; + } + + for (const auto& altname : altnames) { + if (config_ifname == altname || wildcardMatch(config_ifname, altname)) { + matched = altname; + return true; + } + } + return false; } @@ -420,6 +488,7 @@ void waybar::modules::Network::clearIface() { netmask_.clear(); netmask6_.clear(); carrier_ = false; + is_p2p_ = false; cidr_ = 0; cidr6_ = 0; signal_strength_dbm_ = 0; @@ -428,8 +497,8 @@ void waybar::modules::Network::clearIface() { frequency_ = 0.0; } -int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) { - auto net = static_cast(data); +int waybar::modules::Network::handleEvents(struct nl_msg* msg, void* data) { + auto net = static_cast(data); std::lock_guard lock(net->mutex_); auto nh = nlmsg_hdr(msg); bool is_del_event = false; @@ -438,13 +507,17 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) { case RTM_DELLINK: is_del_event = true; case RTM_NEWLINK: { - struct ifinfomsg *ifi = static_cast(NLMSG_DATA(nh)); - ssize_t attrlen = IFLA_PAYLOAD(nh); - struct rtattr *ifla = IFLA_RTA(ifi); - const char *ifname = NULL; - size_t ifname_len = 0; + struct ifinfomsg* ifi = static_cast(NLMSG_DATA(nh)); + struct nlattr* attrs[IFLA_MAX + 1]; + std::string ifname; + std::vector altnames; std::optional carrier; + if (nlmsg_parse(nh, sizeof(*ifi), attrs, IFLA_MAX, nullptr) < 0) { + spdlog::error("network: failed to parse netlink attributes"); + return NL_SKIP; + } + if (net->ifid_ != -1 && ifi->ifi_index != net->ifid_) { return NL_OK; } @@ -462,26 +535,33 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) { 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 - if (ifi->ifi_flags & IFF_POINTOPOINT && net->checkInterface(ifname)) - net->is_p2p_ = true; - break; - case IFLA_CARRIER: { - carrier = *(char *)RTA_DATA(ifla) == 1; - break; + if (attrs[IFLA_IFNAME] != nullptr) { + const char* ifname_ptr = nla_get_string(attrs[IFLA_IFNAME]); + size_t ifname_len = nla_len(attrs[IFLA_IFNAME]) - 1; // minus \0 + ifname = std::string(ifname_ptr, ifname_len); + } + + if (attrs[IFLA_CARRIER] != nullptr) { + carrier = nla_get_u8(attrs[IFLA_CARRIER]) == 1; + } + + if (attrs[IFLA_PROP_LIST] != nullptr) { + struct nlattr* prop; + int rem; + + nla_for_each_nested(prop, attrs[IFLA_PROP_LIST], rem) { + if (nla_type(prop) == IFLA_ALT_IFNAME) { + const char* altname_ptr = nla_get_string(prop); + size_t altname_len = nla_len(prop) - 1; // minus \0 + altnames.emplace_back(altname_ptr, altname_len); } } } 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 (net->ifname_.empty() && !ifname.empty()) { + net->ifname_ = ifname; } if (carrier.has_value()) { if (net->carrier_ != *carrier) { @@ -502,13 +582,25 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) { } } 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); + std::string matched; + if (net->matchInterface(ifname, altnames, matched)) { + if (ifname == matched) { + spdlog::debug("network: selecting new interface {}/{}", ifname, ifi->ifi_index); + } else { + spdlog::debug("network: selecting new interface {}/{} (matched altname {})", ifname, + ifi->ifi_index, matched); + } - net->ifname_ = new_ifname; + net->ifname_ = ifname; net->ifid_ = ifi->ifi_index; - if (ifi->ifi_flags & IFF_POINTOPOINT) net->is_p2p_ = true; + if ((ifi->ifi_flags & IFF_POINTOPOINT) != 0) { + net->is_p2p_ = true; + } + if ((ifi->ifi_flags & IFF_UP) == 0) { + // With some network drivers (e.g. mt7921e), the interface may + // report having a carrier even though interface is down. + carrier = false; + } if (carrier.has_value()) { net->carrier_ = carrier.value(); } @@ -532,9 +624,9 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) { case RTM_DELADDR: is_del_event = true; case RTM_NEWADDR: { - struct ifaddrmsg *ifa = static_cast(NLMSG_DATA(nh)); + struct ifaddrmsg* ifa = static_cast(NLMSG_DATA(nh)); ssize_t attrlen = IFA_PAYLOAD(nh); - struct rtattr *ifa_rta = IFA_RTA(ifa); + struct rtattr* ifa_rta = IFA_RTA(ifa); if ((int)ifa->ifa_index != net->ifid_) { return NL_OK; @@ -552,18 +644,31 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) { case IFA_LOCAL: char ipaddr[INET6_ADDRSTRLEN]; if (!is_del_event) { + bool addr_changed = false; + std::string changed_ipaddr; + int changed_cidr = 0; if ((net->addr_pref_ == ip_addr_pref::IPV4 || net->addr_pref_ == ip_addr_pref::IPV4_6) && net->cidr_ == 0 && ifa->ifa_family == AF_INET) { - net->ipaddr_ = - inet_ntop(ifa->ifa_family, RTA_DATA(ifa_rta), ipaddr, sizeof(ipaddr)); - net->cidr_ = ifa->ifa_prefixlen; + if (inet_ntop(ifa->ifa_family, RTA_DATA(ifa_rta), ipaddr, sizeof(ipaddr)) != + nullptr) { + net->ipaddr_ = ipaddr; + net->cidr_ = ifa->ifa_prefixlen; + addr_changed = true; + changed_ipaddr = net->ipaddr_; + changed_cidr = net->cidr_; + } } else if ((net->addr_pref_ == ip_addr_pref::IPV6 || net->addr_pref_ == ip_addr_pref::IPV4_6) && net->cidr6_ == 0 && ifa->ifa_family == AF_INET6) { - net->ipaddr6_ = - inet_ntop(ifa->ifa_family, RTA_DATA(ifa_rta), ipaddr, sizeof(ipaddr)); - net->cidr6_ = ifa->ifa_prefixlen; + if (inet_ntop(ifa->ifa_family, RTA_DATA(ifa_rta), ipaddr, sizeof(ipaddr)) != + nullptr) { + net->ipaddr6_ = ipaddr; + net->cidr6_ = ifa->ifa_prefixlen; + addr_changed = true; + changed_ipaddr = net->ipaddr6_; + changed_cidr = net->cidr6_; + } } switch (ifa->ifa_family) { @@ -583,14 +688,20 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) { net->netmask6_ = inet_ntop(ifa->ifa_family, &netmask6, ipaddr, sizeof(ipaddr)); } } - spdlog::debug("network: {}, new addr {}/{}", net->ifname_, net->ipaddr_, net->cidr_); + if (addr_changed) { + spdlog::debug("network: {}, new addr {}/{}", net->ifname_, changed_ipaddr, + changed_cidr); + } } else { - net->ipaddr_.clear(); - net->ipaddr6_.clear(); - net->cidr_ = 0; - net->cidr6_ = 0; - net->netmask_.clear(); - net->netmask6_.clear(); + if (ifa->ifa_family == AF_INET) { + net->ipaddr_.clear(); + net->cidr_ = 0; + net->netmask_.clear(); + } else if (ifa->ifa_family == AF_INET6) { + net->ipaddr6_.clear(); + net->cidr6_ = 0; + net->netmask6_.clear(); + } spdlog::debug("network: {} addr deleted {}/{}", net->ifname_, inet_ntop(ifa->ifa_family, RTA_DATA(ifa_rta), ipaddr, sizeof(ipaddr)), ifa->ifa_prefixlen); @@ -602,17 +713,17 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) { 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)); + struct rtmsg* rtm = static_cast(NLMSG_DATA(nh)); int family = rtm->rtm_family; ssize_t attrlen = RTM_PAYLOAD(nh); - struct rtattr *attr = RTM_RTA(rtm); + struct rtattr* attr = RTM_RTA(rtm); + char gateway_addr[INET6_ADDRSTRLEN]; bool has_gateway = false; bool has_destination = false; int temp_idx = -1; @@ -638,31 +749,35 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) { * If someone ever needs to figure out the gateway address as well, * it's here as the attribute payload. */ - inet_ntop(family, RTA_DATA(attr), temp_gw_addr, sizeof(temp_gw_addr)); + inet_ntop(family, RTA_DATA(attr), gateway_addr, sizeof(gateway_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 = (family == AF_INET) ? 4 : 16; - unsigned char c = 0; - size_t dstlen = RTA_PAYLOAD(attr); - if (dstlen != nr_zeroes) { - break; + auto* dest = (const unsigned char*)RTA_DATA(attr); + size_t dest_size = RTA_PAYLOAD(attr); + for (size_t i = 0; i < dest_size; ++i) { + if (dest[i] != 0) { + has_destination = true; + break; + } } - for (uint32_t i = 0; i < dstlen; i += 1) { - c |= *((unsigned char *)RTA_DATA(attr) + i); + + if (rtm->rtm_dst_len != 0) { + // We have found a destination like 0.0.0.0/24, this is not a + // default gateway route. + has_destination = true; } - has_destination = (c == 0); break; } case RTA_OIF: /* The output interface index. */ - temp_idx = *static_cast(RTA_DATA(attr)); + temp_idx = *static_cast(RTA_DATA(attr)); break; case RTA_PRIORITY: - priority = *(uint32_t *)RTA_DATA(attr); + priority = *(uint32_t*)RTA_DATA(attr); break; default: break; @@ -683,8 +798,8 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) { 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, + net->gwaddr_ = gateway_addr; + spdlog::debug("network: new default route via {} on if{} metric {}", gateway_addr, temp_idx, priority); /* Ask ifname associated with temp_idx as well as carrier status */ @@ -753,18 +868,18 @@ void waybar::modules::Network::askForStateDump(void) { } } -int waybar::modules::Network::handleEventsDone(struct nl_msg *msg, void *data) { - auto net = static_cast(data); +int waybar::modules::Network::handleEventsDone(struct nl_msg* msg, void* data) { + auto net = static_cast(data); net->dump_in_progress_ = false; net->askForStateDump(); return NL_OK; } -int waybar::modules::Network::handleScan(struct nl_msg *msg, void *data) { - auto net = static_cast(data); - auto gnlh = static_cast(nlmsg_data(nlmsg_hdr(msg))); - struct nlattr *tb[NL80211_ATTR_MAX + 1]; - struct nlattr *bss[NL80211_BSS_MAX + 1]; +int waybar::modules::Network::handleScan(struct nl_msg* msg, void* data) { + auto net = static_cast(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; @@ -796,9 +911,9 @@ int waybar::modules::Network::handleScan(struct nl_msg *msg, void *data) { return NL_OK; } -void waybar::modules::Network::parseEssid(struct nlattr **bss) { +void waybar::modules::Network::parseEssid(struct nlattr** bss) { if (bss[NL80211_BSS_INFORMATION_ELEMENTS] != nullptr) { - auto ies = static_cast(nla_data(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) { @@ -815,7 +930,7 @@ void waybar::modules::Network::parseEssid(struct nlattr **bss) { } } -void waybar::modules::Network::parseSignal(struct nlattr **bss) { +void waybar::modules::Network::parseSignal(struct nlattr** bss) { if (bss[NL80211_BSS_SIGNAL_MBM] != nullptr) { // signalstrength in dBm from mBm signal_strength_dbm_ = nla_get_s32(bss[NL80211_BSS_SIGNAL_MBM]) / 100; @@ -851,16 +966,16 @@ void waybar::modules::Network::parseSignal(struct nlattr **bss) { } } -void waybar::modules::Network::parseFreq(struct nlattr **bss) { +void waybar::modules::Network::parseFreq(struct nlattr** bss) { if (bss[NL80211_BSS_FREQUENCY] != nullptr) { // in GHz frequency_ = (double)nla_get_u32(bss[NL80211_BSS_FREQUENCY]) / 1000; } } -void waybar::modules::Network::parseBssid(struct nlattr **bss) { +void waybar::modules::Network::parseBssid(struct nlattr** bss) { if (bss[NL80211_BSS_BSSID] != nullptr) { - auto bssid = static_cast(nla_data(bss[NL80211_BSS_BSSID])); + auto bssid = static_cast(nla_data(bss[NL80211_BSS_BSSID])); auto bssid_len = nla_len(bss[NL80211_BSS_BSSID]); if (bssid_len == 6) { bssid_ = fmt::format("{:x}:{:x}:{:x}:{:x}:{:x}:{:x}", bssid[0], bssid[1], bssid[2], bssid[3], @@ -869,7 +984,7 @@ void waybar::modules::Network::parseBssid(struct nlattr **bss) { } } -bool waybar::modules::Network::associatedOrJoined(struct nlattr **bss) { +bool waybar::modules::Network::associatedOrJoined(struct nlattr** bss) { if (bss[NL80211_BSS_STATUS] == nullptr) { return false; } @@ -885,7 +1000,7 @@ bool waybar::modules::Network::associatedOrJoined(struct nlattr **bss) { } auto waybar::modules::Network::getInfo() -> void { - struct nl_msg *nl_msg = nlmsg_alloc(); + struct nl_msg* nl_msg = nlmsg_alloc(); if (nl_msg == nullptr) { return; } @@ -897,43 +1012,3 @@ auto waybar::modules::Network::getInfo() -> void { } nl_send_sync(sock_, nl_msg); } - -// https://gist.github.com/rressi/92af77630faf055934c723ce93ae2495 -bool waybar::modules::Network::wildcardMatch(const std::string &pattern, - const std::string &text) const { - auto P = int(pattern.size()); - auto T = int(text.size()); - - auto p = 0, fallback_p = -1; - auto t = 0, fallback_t = -1; - - while (t < T) { - // Wildcard match: - if (p < P && pattern[p] == '*') { - fallback_p = p++; // starting point after failures - fallback_t = t; // starting point after failures - } - - // Simple match: - else if (p < P && (pattern[p] == '?' || pattern[p] == text[t])) { - p++; - t++; - } - - // Failure, fall back just after last matched '*': - else if (fallback_p >= 0) { - p = fallback_p + 1; // position just after last matched '*" - t = ++fallback_t; // re-try to match text from here - } - - // There were no '*' before, so we fail here: - else { - return false; - } - } - - // Consume all '*' at the end of pattern: - while (p < P && pattern[p] == '*') p++; - - return p == P; -} diff --git a/src/modules/niri/backend.cpp b/src/modules/niri/backend.cpp index 383bf113..de3f8a9a 100644 --- a/src/modules/niri/backend.cpp +++ b/src/modules/niri/backend.cpp @@ -17,19 +17,21 @@ #include "giomm/dataoutputstream.h" #include "giomm/unixinputstream.h" #include "giomm/unixoutputstream.h" +#include "util/scoped_fd.hpp" namespace waybar::modules::niri { +IPC::IPC() { startIPC(); } + int IPC::connectToSocket() { - const char *socket_path = getenv("NIRI_SOCKET"); + const char* socket_path = getenv("NIRI_SOCKET"); if (socket_path == nullptr) { - spdlog::warn("Niri is not running, niri IPC will not be available."); - return -1; + throw std::runtime_error("Niri IPC: NIRI_SOCKET was not set! (Is Niri running?)"); } struct sockaddr_un addr; - int socketfd = socket(AF_UNIX, SOCK_STREAM, 0); + util::ScopedFd socketfd(socket(AF_UNIX, SOCK_STREAM, 0)); if (socketfd == -1) { throw std::runtime_error("socketfd failed"); @@ -43,27 +45,19 @@ int IPC::connectToSocket() { int l = sizeof(struct sockaddr_un); - if (connect(socketfd, (struct sockaddr *)&addr, l) == -1) { - close(socketfd); + if (connect(socketfd, (struct sockaddr*)&addr, l) == -1) { throw std::runtime_error("unable to connect"); } - return socketfd; + return socketfd.release(); } void IPC::startIPC() { // will start IPC and relay events to parseIPC - std::thread([&]() { - int socketfd; - try { - socketfd = connectToSocket(); - } catch (std::exception &e) { - spdlog::error("Niri IPC: failed to start, reason: {}", e.what()); - return; - } - if (socketfd == -1) return; + int socketfd = connectToSocket(); + std::thread([this, socketfd]() { spdlog::info("Niri IPC starting"); auto unix_istream = Gio::UnixInputStream::create(socketfd, true); @@ -87,7 +81,7 @@ void IPC::startIPC() { try { parseIPC(line); - } catch (std::exception &e) { + } catch (std::exception& e) { spdlog::warn("Failed to parse IPC message: {}, reason: {}", line, e.what()); } catch (...) { throw; @@ -98,7 +92,7 @@ void IPC::startIPC() { }).detach(); } -void IPC::parseIPC(const std::string &line) { +void IPC::parseIPC(const std::string& line) { const auto ev = parser_.parse(line); const auto members = ev.getMemberNames(); if (members.size() != 1) throw std::runtime_error("Event must have a single member"); @@ -106,28 +100,28 @@ void IPC::parseIPC(const std::string &line) { { auto lock = lockData(); - if (const auto &payload = ev["WorkspacesChanged"]) { + if (const auto& payload = ev["WorkspacesChanged"]) { workspaces_.clear(); - const auto &values = payload["workspaces"]; + const auto& values = payload["workspaces"]; std::copy(values.begin(), values.end(), std::back_inserter(workspaces_)); - std::sort(workspaces_.begin(), workspaces_.end(), [](const auto &a, const auto &b) { - const auto &aOutput = a["output"].asString(); - const auto &bOutput = b["output"].asString(); + std::sort(workspaces_.begin(), workspaces_.end(), [](const auto& a, const auto& b) { + const auto& aOutput = a["output"].asString(); + const auto& bOutput = b["output"].asString(); const auto aIdx = a["idx"].asUInt(); const auto bIdx = b["idx"].asUInt(); if (aOutput == bOutput) return aIdx < bIdx; return aOutput < bOutput; }); - } else if (const auto &payload = ev["WorkspaceActivated"]) { + } else if (const auto& payload = ev["WorkspaceActivated"]) { const auto id = payload["id"].asUInt64(); const auto focused = payload["focused"].asBool(); auto it = std::find_if(workspaces_.begin(), workspaces_.end(), - [id](const auto &ws) { return ws["id"].asUInt64() == id; }); + [id](const auto& ws) { return ws["id"].asUInt64() == id; }); if (it != workspaces_.end()) { - const auto &ws = *it; - const auto &output = ws["output"].asString(); - for (auto &ws : workspaces_) { + const auto& ws = *it; + const auto& output = ws["output"].asString(); + for (auto& ws : workspaces_) { const auto got_activated = (ws["id"].asUInt64() == id); if (ws["output"] == output) ws["is_active"] = got_activated; @@ -136,59 +130,70 @@ void IPC::parseIPC(const std::string &line) { } else { spdlog::error("Activated unknown workspace"); } - } else if (const auto &payload = ev["WorkspaceActiveWindowChanged"]) { + } else if (const auto& payload = ev["WorkspaceActiveWindowChanged"]) { const auto workspaceId = payload["workspace_id"].asUInt64(); - auto it = std::find_if(workspaces_.begin(), workspaces_.end(), [workspaceId](const auto &ws) { + auto it = std::find_if(workspaces_.begin(), workspaces_.end(), [workspaceId](const auto& ws) { return ws["id"].asUInt64() == workspaceId; }); if (it != workspaces_.end()) { - auto &ws = *it; + auto& ws = *it; ws["active_window_id"] = payload["active_window_id"]; } else { spdlog::error("Active window changed on unknown workspace"); } - } else if (const auto &payload = ev["KeyboardLayoutsChanged"]) { - const auto &layouts = payload["keyboard_layouts"]; - const auto &names = layouts["names"]; + } else if (const auto& payload = ev["WorkspaceUrgencyChanged"]) { + const auto id = payload["id"].asUInt64(); + const auto urgent = payload["urgent"].asBool(); + auto it = std::find_if(workspaces_.begin(), workspaces_.end(), + [id](const auto& ws) { return ws["id"].asUInt64() == id; }); + if (it != workspaces_.end()) { + auto& ws = *it; + ws["is_urgent"] = urgent; + } else { + spdlog::error("Urgency changed for unknown workspace"); + } + } else if (const auto& payload = ev["KeyboardLayoutsChanged"]) { + const auto& layouts = payload["keyboard_layouts"]; + const auto& names = layouts["names"]; keyboardLayoutCurrent_ = layouts["current_idx"].asUInt(); keyboardLayoutNames_.clear(); - for (const auto &fullName : names) keyboardLayoutNames_.push_back(fullName.asString()); - } else if (const auto &payload = ev["KeyboardLayoutSwitched"]) { + for (const auto& fullName : names) keyboardLayoutNames_.push_back(fullName.asString()); + } else if (const auto& payload = ev["KeyboardLayoutSwitched"]) { keyboardLayoutCurrent_ = payload["idx"].asUInt(); - } else if (const auto &payload = ev["WindowsChanged"]) { + } else if (const auto& payload = ev["WindowsChanged"]) { windows_.clear(); - const auto &values = payload["windows"]; + const auto& values = payload["windows"]; std::copy(values.begin(), values.end(), std::back_inserter(windows_)); - } else if (const auto &payload = ev["WindowOpenedOrChanged"]) { - const auto &window = payload["window"]; + } else if (const auto& payload = ev["WindowOpenedOrChanged"]) { + const auto& window = payload["window"]; const auto id = window["id"].asUInt64(); auto it = std::find_if(windows_.begin(), windows_.end(), - [id](const auto &win) { return win["id"].asUInt64() == id; }); + [id](const auto& win) { return win["id"].asUInt64() == id; }); if (it == windows_.end()) { windows_.push_back(window); if (window["is_focused"].asBool()) { - for (auto &win : windows_) { + for (auto& win : windows_) { win["is_focused"] = win["id"].asUInt64() == id; } } } else { *it = window; } - } else if (const auto &payload = ev["WindowClosed"]) { + } else if (const auto& payload = ev["WindowClosed"]) { const auto id = payload["id"].asUInt64(); auto it = std::find_if(windows_.begin(), windows_.end(), - [id](const auto &win) { return win["id"].asUInt64() == id; }); + [id](const auto& win) { return win["id"].asUInt64() == id; }); if (it != windows_.end()) { windows_.erase(it); } else { spdlog::error("Unknown window closed"); } - } else if (const auto &payload = ev["WindowFocusChanged"]) { + } else if (const auto& payload = ev["WindowFocusChanged"]) { const auto focused = !payload["id"].isNull(); const auto id = payload["id"].asUInt64(); - for (auto &win : windows_) { + for (auto& win : windows_) { win["is_focused"] = focused && win["id"].asUInt64() == id; } } @@ -196,14 +201,14 @@ void IPC::parseIPC(const std::string &line) { std::unique_lock lock(callbackMutex_); - for (auto &[eventname, handler] : callbacks_) { + for (auto& [eventname, handler] : callbacks_) { if (eventname == members[0]) { handler->onEvent(ev); } } } -void IPC::registerForIPC(const std::string &ev, EventHandler *ev_handler) { +void IPC::registerForIPC(const std::string& ev, EventHandler* ev_handler) { if (ev_handler == nullptr) { return; } @@ -212,7 +217,7 @@ void IPC::registerForIPC(const std::string &ev, EventHandler *ev_handler) { callbacks_.emplace_back(ev, ev_handler); } -void IPC::unregisterForIPC(EventHandler *ev_handler) { +void IPC::unregisterForIPC(EventHandler* ev_handler) { if (ev_handler == nullptr) { return; } @@ -220,7 +225,7 @@ void IPC::unregisterForIPC(EventHandler *ev_handler) { std::unique_lock lock(callbackMutex_); for (auto it = callbacks_.begin(); it != callbacks_.end();) { - auto &[eventname, handler] = *it; + auto& [eventname, handler] = *it; if (handler == ev_handler) { it = callbacks_.erase(it); } else { @@ -229,9 +234,8 @@ void IPC::unregisterForIPC(EventHandler *ev_handler) { } } -Json::Value IPC::send(const Json::Value &request) { - int socketfd = connectToSocket(); - if (socketfd == -1) throw std::runtime_error("Niri is not running"); +Json::Value IPC::send(const Json::Value& request) { + util::ScopedFd socketfd(connectToSocket()); auto unix_istream = Gio::UnixInputStream::create(socketfd, true); auto unix_ostream = Gio::UnixOutputStream::create(socketfd, false); diff --git a/src/modules/niri/language.cpp b/src/modules/niri/language.cpp index 3b55ff24..d739ce57 100644 --- a/src/modules/niri/language.cpp +++ b/src/modules/niri/language.cpp @@ -8,7 +8,7 @@ namespace waybar::modules::niri { -Language::Language(const std::string &id, const Bar &bar, const Json::Value &config) +Language::Language(const std::string& id, const Bar& bar, const Json::Value& config) : ALabel(config, "language", id, "{}", 0, false), bar_(bar) { label_.hide(); @@ -32,7 +32,8 @@ void Language::updateFromIPC() { auto ipcLock = gIPC->lockData(); layouts_.clear(); - for (const auto &fullName : gIPC->keyboardLayoutNames()) layouts_.push_back(getLayout(fullName)); + layouts_.reserve(gIPC->keyboardLayoutNames().size()); + for (const auto& fullName : gIPC->keyboardLayoutNames()) layouts_.push_back(getLayout(fullName)); current_idx_ = gIPC->keyboardLayoutCurrent(); } @@ -51,13 +52,23 @@ void Language::doUpdate() { label_.hide(); return; } - const auto &layout = layouts_[current_idx_]; + const auto& layout = layouts_[current_idx_]; spdlog::debug("niri language update with full name {}", layout.full_name); spdlog::debug("niri language update with short name {}", layout.short_name); spdlog::debug("niri language update with short description {}", layout.short_description); spdlog::debug("niri language update with variant {}", layout.variant); + if (!last_short_name_.empty()) { + label_.get_style_context()->remove_class(last_short_name_); + } + if (!layout.short_name.empty()) { + label_.get_style_context()->add_class(layout.short_name); + last_short_name_ = layout.short_name; + } else { + last_short_name_.clear(); + } + std::string layoutName = std::string{}; if (config_.isMember("format-" + layout.short_description + "-" + layout.variant)) { const auto propName = "format-" + layout.short_description + "-" + layout.variant; @@ -74,7 +85,7 @@ void Language::doUpdate() { spdlog::debug("niri language formatted layout name {}", layoutName); - if (!format_.empty()) { + if (!layoutName.empty()) { label_.show(); label_.set_markup(layoutName); } else { @@ -87,7 +98,7 @@ void Language::update() { ALabel::update(); } -void Language::onEvent(const Json::Value &ev) { +void Language::onEvent(const Json::Value& ev) { if (ev["KeyboardLayoutsChanged"]) { updateFromIPC(); } else if (ev["KeyboardLayoutSwitched"]) { @@ -99,11 +110,11 @@ void Language::onEvent(const Json::Value &ev) { dp.emit(); } -Language::Layout Language::getLayout(const std::string &fullName) { - auto *const context = rxkb_context_new(RXKB_CONTEXT_LOAD_EXOTIC_RULES); +Language::Layout Language::getLayout(const std::string& fullName) { + auto* const context = rxkb_context_new(RXKB_CONTEXT_LOAD_EXOTIC_RULES); rxkb_context_parse_default_ruleset(context); - rxkb_layout *layout = rxkb_layout_first(context); + rxkb_layout* layout = rxkb_layout_first(context); while (layout != nullptr) { std::string nameOfLayout = rxkb_layout_get_description(layout); @@ -113,10 +124,10 @@ Language::Layout Language::getLayout(const std::string &fullName) { } auto name = std::string(rxkb_layout_get_name(layout)); - const auto *variantPtr = rxkb_layout_get_variant(layout); + const auto* variantPtr = rxkb_layout_get_variant(layout); std::string variant = variantPtr == nullptr ? "" : std::string(variantPtr); - const auto *descriptionPtr = rxkb_layout_get_brief(layout); + const auto* descriptionPtr = rxkb_layout_get_brief(layout); std::string description = descriptionPtr == nullptr ? "" : std::string(descriptionPtr); Layout info = Layout{nameOfLayout, name, variant, description}; diff --git a/src/modules/niri/window.cpp b/src/modules/niri/window.cpp index 6e6fd36f..61b3a7dd 100644 --- a/src/modules/niri/window.cpp +++ b/src/modules/niri/window.cpp @@ -9,7 +9,7 @@ namespace waybar::modules::niri { -Window::Window(const std::string &id, const Bar &bar, const Json::Value &config) +Window::Window(const std::string& id, const Bar& bar, const Json::Value& config) : AAppIconLabel(config, "window", id, "{title}", 0, true), bar_(bar) { if (!gIPC) gIPC = std::make_unique(); @@ -23,16 +23,16 @@ Window::Window(const std::string &id, const Bar &bar, const Json::Value &config) Window::~Window() { gIPC->unregisterForIPC(this); } -void Window::onEvent(const Json::Value &ev) { dp.emit(); } +void Window::onEvent(const Json::Value& ev) { dp.emit(); } void Window::doUpdate() { auto ipcLock = gIPC->lockData(); - const auto &windows = gIPC->windows(); - const auto &workspaces = gIPC->workspaces(); + const auto& windows = gIPC->windows(); + const auto& workspaces = gIPC->workspaces(); const auto separateOutputs = config_["separate-outputs"].asBool(); - const auto ws_it = std::find_if(workspaces.cbegin(), workspaces.cend(), [&](const auto &ws) { + const auto ws_it = std::find_if(workspaces.cbegin(), workspaces.cend(), [&](const auto& ws) { if (separateOutputs) { return ws["is_active"].asBool() && ws["output"].asString() == bar_.output->name; } @@ -46,13 +46,13 @@ void Window::doUpdate() { } else { const auto id = (*ws_it)["active_window_id"].asUInt64(); it = std::find_if(windows.cbegin(), windows.cend(), - [id](const auto &win) { return win["id"].asUInt64() == id; }); + [id](const auto& win) { return win["id"].asUInt64() == id; }); } setClass("empty", ws_it == workspaces.cend() || (*ws_it)["active_window_id"].isNull()); if (it != windows.cend()) { - const auto &window = *it; + const auto& window = *it; const auto title = window["title"].asString(); const auto appId = window["app_id"].asString(); @@ -67,11 +67,11 @@ void Window::doUpdate() { updateAppIconName(appId, ""); - if (tooltipEnabled()) label_.set_tooltip_text(title); + if (tooltipEnabled()) label_.set_tooltip_markup(title); const auto id = window["id"].asUInt64(); const auto workspaceId = window["workspace_id"].asUInt64(); - const auto isSolo = std::none_of(windows.cbegin(), windows.cend(), [&](const auto &win) { + const auto isSolo = std::none_of(windows.cbegin(), windows.cend(), [&](const auto& win) { return win["id"].asUInt64() != id && win["workspace_id"].asUInt64() == workspaceId; }); setClass("solo", isSolo); @@ -95,7 +95,7 @@ void Window::update() { AAppIconLabel::update(); } -void Window::setClass(const std::string &className, bool enable) { +void Window::setClass(const std::string& className, bool enable) { auto styleContext = bar_.window.get_style_context(); if (enable) { if (!styleContext->has_class(className)) { diff --git a/src/modules/niri/workspaces.cpp b/src/modules/niri/workspaces.cpp index d2fcad5d..a817ab9c 100644 --- a/src/modules/niri/workspaces.cpp +++ b/src/modules/niri/workspaces.cpp @@ -6,7 +6,7 @@ namespace waybar::modules::niri { -Workspaces::Workspaces(const std::string &id, const Bar &bar, const Json::Value &config) +Workspaces::Workspaces(const std::string& id, const Bar& bar, const Json::Value& config) : AModule(config, "workspaces", id, false, false), bar_(bar), box_(bar.orientation, 0) { box_.set_name("workspaces"); if (!id.empty()) { @@ -20,22 +20,23 @@ Workspaces::Workspaces(const std::string &id, const Bar &bar, const Json::Value gIPC->registerForIPC("WorkspacesChanged", this); gIPC->registerForIPC("WorkspaceActivated", this); gIPC->registerForIPC("WorkspaceActiveWindowChanged", this); + gIPC->registerForIPC("WorkspaceUrgencyChanged", this); dp.emit(); } Workspaces::~Workspaces() { gIPC->unregisterForIPC(this); } -void Workspaces::onEvent(const Json::Value &ev) { dp.emit(); } +void Workspaces::onEvent(const Json::Value& ev) { dp.emit(); } void Workspaces::doUpdate() { auto ipcLock = gIPC->lockData(); const auto alloutputs = config_["all-outputs"].asBool(); std::vector my_workspaces; - const auto &workspaces = gIPC->workspaces(); + const auto& workspaces = gIPC->workspaces(); std::copy_if(workspaces.cbegin(), workspaces.cend(), std::back_inserter(my_workspaces), - [&](const auto &ws) { + [&](const auto& ws) { if (alloutputs) return true; return ws["output"].asString() == bar_.output->name; }); @@ -43,7 +44,7 @@ void Workspaces::doUpdate() { // Remove buttons for removed workspaces. for (auto it = buttons_.begin(); it != buttons_.end();) { auto ws = std::find_if(my_workspaces.begin(), my_workspaces.end(), - [it](const auto &ws) { return ws["id"].asUInt64() == it->first; }); + [it](const auto& ws) { return ws["id"].asUInt64() == it->first; }); if (ws == my_workspaces.end()) { it = buttons_.erase(it); } else { @@ -52,9 +53,9 @@ void Workspaces::doUpdate() { } // Add buttons for new workspaces, update existing ones. - for (const auto &ws : my_workspaces) { + for (const auto& ws : my_workspaces) { auto bit = buttons_.find(ws["id"].asUInt64()); - auto &button = bit == buttons_.end() ? addButton(ws) : bit->second; + auto& button = bit == buttons_.end() ? addButton(ws) : bit->second; auto style_context = button.get_style_context(); if (ws["is_focused"].asBool()) @@ -67,6 +68,11 @@ void Workspaces::doUpdate() { else style_context->remove_class("active"); + if (ws["is_urgent"].asBool()) + style_context->add_class("urgent"); + else + style_context->remove_class("urgent"); + if (ws["output"]) { if (ws["output"].asString() == bar_.output->name) style_context->add_class("current_output"); @@ -97,17 +103,24 @@ void Workspaces::doUpdate() { fmt::arg("output", ws["output"].asString())); } if (!config_["disable-markup"].asBool()) { - static_cast(button.get_children()[0])->set_markup(name); + auto* child = gtk_bin_get_child(GTK_BIN(button.gobj())); + if (child != nullptr && GTK_IS_LABEL(child)) + gtk_label_set_markup(GTK_LABEL(child), name.c_str()); } else { button.set_label(name); } if (config_["current-only"].asBool()) { - const auto *property = alloutputs ? "is_focused" : "is_active"; + const auto* property = alloutputs ? "is_focused" : "is_active"; if (ws[property].asBool()) button.show(); else button.hide(); + } else if (config_["hide-empty"].asBool()) { + if (ws["active_window_id"].isNull() && !ws["is_focused"].asBool()) + button.hide(); + else + button.show(); } else { button.show(); } @@ -115,12 +128,12 @@ void Workspaces::doUpdate() { // Refresh the button order. for (auto it = my_workspaces.cbegin(); it != my_workspaces.cend(); ++it) { - const auto &ws = *it; + const auto& ws = *it; auto pos = ws["idx"].asUInt() - 1; if (alloutputs) pos = it - my_workspaces.cbegin(); - auto &button = buttons_[ws["id"].asUInt64()]; + auto& button = buttons_[ws["id"].asUInt64()]; box_.reorder_child(button, pos); } } @@ -130,7 +143,7 @@ void Workspaces::update() { AModule::update(); } -Gtk::Button &Workspaces::addButton(const Json::Value &ws) { +Gtk::Button& Workspaces::addButton(const Json::Value& ws) { std::string name; if (ws["name"]) { name = ws["name"].asString(); @@ -139,7 +152,7 @@ Gtk::Button &Workspaces::addButton(const Json::Value &ws) { } auto pair = buttons_.emplace(ws["id"].asUInt64(), name); - auto &&button = pair.first->second; + auto&& button = pair.first->second; box_.pack_start(button, false, false, 0); button.set_relief(Gtk::RELIEF_NONE); if (!config_["disable-click"].asBool()) { @@ -148,13 +161,13 @@ Gtk::Button &Workspaces::addButton(const Json::Value &ws) { try { // {"Action":{"FocusWorkspace":{"reference":{"Id":1}}}} Json::Value request(Json::objectValue); - auto &action = (request["Action"] = Json::Value(Json::objectValue)); - auto &focusWorkspace = (action["FocusWorkspace"] = Json::Value(Json::objectValue)); - auto &reference = (focusWorkspace["reference"] = Json::Value(Json::objectValue)); + auto& action = (request["Action"] = Json::Value(Json::objectValue)); + auto& focusWorkspace = (action["FocusWorkspace"] = Json::Value(Json::objectValue)); + auto& reference = (focusWorkspace["reference"] = Json::Value(Json::objectValue)); reference["Id"] = id; IPC::send(request); - } catch (const std::exception &e) { + } catch (const std::exception& e) { spdlog::error("Error switching workspace: {}", e.what()); } }); @@ -162,16 +175,20 @@ Gtk::Button &Workspaces::addButton(const Json::Value &ws) { return button; } -std::string Workspaces::getIcon(const std::string &value, const Json::Value &ws) { - const auto &icons = config_["format-icons"]; +std::string Workspaces::getIcon(const std::string& value, const Json::Value& ws) { + const auto& icons = config_["format-icons"]; if (!icons) return value; - if (ws["is_focused"].asBool() && icons["focused"]) return icons["focused"].asString(); + if (ws["is_urgent"].asBool() && icons["urgent"]) return icons["urgent"].asString(); if (ws["is_active"].asBool() && icons["active"]) return icons["active"].asString(); + if (ws["is_focused"].asBool() && icons["focused"]) return icons["focused"].asString(); + + if (ws["active_window_id"].isNull() && icons["empty"]) return icons["empty"].asString(); + if (ws["name"]) { - const auto &name = ws["name"].asString(); + const auto& name = ws["name"].asString(); if (icons[name]) return icons[name].asString(); } diff --git a/src/modules/power_profiles_daemon.cpp b/src/modules/power_profiles_daemon.cpp index 3ae3ae83..566787f3 100644 --- a/src/modules/power_profiles_daemon.cpp +++ b/src/modules/power_profiles_daemon.cpp @@ -29,14 +29,14 @@ PowerProfilesDaemon::PowerProfilesDaemon(const std::string& id, const Json::Valu // method on the proxy to see whether or not something's responding // on the other side. - // NOTE: the DBus adresses are under migration. They should be + // NOTE: the DBus addresses are under migration. They should be // changed to org.freedesktop.UPower.PowerProfiles at some point. // // See // https://gitlab.freedesktop.org/upower/power-profiles-daemon/-/releases/0.20 // // The old name is still announced for now. Let's rather use the old - // adresses for compatibility sake. + // addresses for compatibility sake. // // Revisit this in 2026, systems should be updated by then. @@ -157,7 +157,7 @@ auto PowerProfilesDaemon::update() -> void { store.push_back(fmt::arg("icon", getIcon(0, profile.name))); label_.set_markup(fmt::vformat(format_, store)); if (tooltipEnabled()) { - label_.set_tooltip_text(fmt::vformat(tooltipFormat_, store)); + label_.set_tooltip_markup(fmt::vformat(tooltipFormat_, store)); } // Set CSS class @@ -176,6 +176,10 @@ auto PowerProfilesDaemon::update() -> void { bool PowerProfilesDaemon::handleToggle(GdkEventButton* const& e) { if (e->type == GdkEventType::GDK_BUTTON_PRESS && connected_) { + if (availableProfiles_.empty()) return true; + if (activeProfile_ == availableProfiles_.end()) { + activeProfile_ = availableProfiles_.begin(); + } if (e->button == 1) /* left click */ { activeProfile_++; if (activeProfile_ == availableProfiles_.end()) { diff --git a/src/modules/privacy/privacy.cpp b/src/modules/privacy/privacy.cpp index 48bba888..4e613971 100644 --- a/src/modules/privacy/privacy.cpp +++ b/src/modules/privacy/privacy.cpp @@ -71,9 +71,28 @@ Privacy::Privacy(const std::string& id, const Json::Value& config, Gtk::Orientat auto* item = Gtk::make_managed(module, nodeType, nodePtr, orientation, pos, iconSize, transition_duration); box_.add(*item); + modules_.push_back(item); } } + for (const auto& ignore_item : config_["ignore"]) { + if (!ignore_item.isObject() || !ignore_item["type"].isString() || + !ignore_item["name"].isString()) + continue; + const std::string type = ignore_item["type"].asString(); + const std::string name = ignore_item["name"].asString(); + + auto iter = typeMap.find(type); + if (iter != typeMap.end()) { + auto& [_, nodeType] = iter->second; + ignore.emplace(nodeType, std::move(name)); + } + } + + if (config_["ignore-monitor"].isBool()) { + ignore_monitor = config_["ignore-monitor"].asBool(); + } + backend = util::PipewireBackend::PipewireBackend::getInstance(); backend->privacy_nodes_changed_signal_event.connect( sigc::mem_fun(*this, &Privacy::onPrivacyNodesChanged)); @@ -88,6 +107,11 @@ void Privacy::onPrivacyNodesChanged() { nodes_screenshare.clear(); for (auto& node : backend->privacy_nodes) { + if (ignore_monitor && node.second->is_monitor) continue; + + auto iter = ignore.find(std::pair(node.second->type, node.second->node_name)); + if (iter != ignore.end()) continue; + switch (node.second->state) { case PW_NODE_STATE_RUNNING: switch (node.second->type) { @@ -125,9 +149,7 @@ auto Privacy::update() -> void { bool useAudioOut = false; mutex_.lock(); - for (Gtk::Widget* widget : box_.get_children()) { - auto* module = dynamic_cast(widget); - if (module == nullptr) continue; + for (PrivacyItem* module : modules_) { switch (module->privacy_type) { case util::PipewireBackend::PRIVACY_NODE_TYPE_VIDEO_INPUT: setScreenshare = true; diff --git a/src/modules/privacy/privacy_item.cpp b/src/modules/privacy/privacy_item.cpp index 54e61b43..3a55eee7 100644 --- a/src/modules/privacy/privacy_item.cpp +++ b/src/modules/privacy/privacy_item.cpp @@ -1,5 +1,7 @@ #include "modules/privacy/privacy_item.hpp" +#include + #include #include "glibmm/main.h" @@ -10,9 +12,9 @@ namespace waybar::modules::privacy { -PrivacyItem::PrivacyItem(const Json::Value &config_, enum PrivacyNodeType privacy_type_, - std::list *nodes_, Gtk::Orientation orientation, - const std::string &pos, const uint icon_size, +PrivacyItem::PrivacyItem(const Json::Value& config_, enum PrivacyNodeType privacy_type_, + std::list* nodes_, Gtk::Orientation orientation, + const std::string& pos, const uint icon_size, const uint transition_duration) : Gtk::Revealer(), privacy_type(privacy_type_), @@ -81,7 +83,7 @@ PrivacyItem::PrivacyItem(const Json::Value &config_, enum PrivacyNodeType privac // Sets the window to use when showing the tooltip update_tooltip(); this->signal_query_tooltip().connect(sigc::track_obj( - [this](int x, int y, bool keyboard_tooltip, const Glib::RefPtr &tooltip) { + [this](int x, int y, bool keyboard_tooltip, const Glib::RefPtr& tooltip) { tooltip->set_custom(tooltip_window); return true; }, @@ -95,21 +97,23 @@ PrivacyItem::PrivacyItem(const Json::Value &config_, enum PrivacyNodeType privac void PrivacyItem::update_tooltip() { // Removes all old nodes - for (auto *child : tooltip_window.get_children()) { + for (auto* child : tooltip_window.get_children()) { + tooltip_window.remove(*child); + // despite the remove, still needs a delete to prevent memory leak. Speculating that this might + // work differently in GTK4. delete child; } - - for (auto *node : *nodes) { - Gtk::Box *box = new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 4); + for (auto* node : *nodes) { + auto* box = Gtk::make_managed(Gtk::ORIENTATION_HORIZONTAL, 4); // Set device icon - Gtk::Image *node_icon = new Gtk::Image(); + auto* node_icon = Gtk::make_managed(); node_icon->set_pixel_size(tooltipIconSize); node_icon->set_from_icon_name(node->getIconName(), Gtk::ICON_SIZE_INVALID); box->add(*node_icon); // Set model - auto *nodeName = new Gtk::Label(node->getName()); + auto* nodeName = Gtk::make_managed(node->getName()); box->add(*nodeName); tooltip_window.add(*box); diff --git a/src/modules/pulseaudio.cpp b/src/modules/pulseaudio.cpp index 255ca571..4d63ff3c 100644 --- a/src/modules/pulseaudio.cpp +++ b/src/modules/pulseaudio.cpp @@ -1,6 +1,6 @@ #include "modules/pulseaudio.hpp" -waybar::modules::Pulseaudio::Pulseaudio(const std::string &id, const Json::Value &config) +waybar::modules::Pulseaudio::Pulseaudio(const std::string& id, const Json::Value& config) : ALabel(config, "pulseaudio", id, "{volume}%") { event_box_.add_events(Gdk::SCROLL_MASK | Gdk::SMOOTH_SCROLL_MASK); event_box_.signal_scroll_event().connect(sigc::mem_fun(*this, &Pulseaudio::handleScroll)); @@ -9,7 +9,7 @@ waybar::modules::Pulseaudio::Pulseaudio(const std::string &id, const Json::Value backend->setIgnoredSinks(config_["ignored-sinks"]); } -bool waybar::modules::Pulseaudio::handleScroll(GdkEventScroll *e) { +bool waybar::modules::Pulseaudio::handleScroll(GdkEventScroll* e) { // change the pulse volume only when no user provided // events are configured if (config_["on-scroll-up"].isString() || config_["on-scroll-down"].isString()) { @@ -51,7 +51,7 @@ const std::vector waybar::modules::Pulseaudio::getPulseIcon() const res.push_back(backend->getDefaultSourceName()); std::string nameLC = backend->getSinkPortName() + backend->getFormFactor(); std::transform(nameLC.begin(), nameLC.end(), nameLC.begin(), ::tolower); - for (auto const &port : ports) { + for (auto const& port : ports) { if (nameLC.find(port) != std::string::npos) { if (sink_muted) { res.emplace_back(port + "-muted"); @@ -132,13 +132,13 @@ auto waybar::modules::Pulseaudio::update() -> void { tooltip_format = config_["tooltip-format"].asString(); } if (!tooltip_format.empty()) { - label_.set_tooltip_text(fmt::format( + label_.set_tooltip_markup(fmt::format( fmt::runtime(tooltip_format), fmt::arg("desc", sink_desc), fmt::arg("volume", sink_volume), fmt::arg("format_source", format_source), fmt::arg("source_volume", source_volume), fmt::arg("source_desc", source_desc), fmt::arg("icon", getIcon(sink_volume, getPulseIcon())))); } else { - label_.set_tooltip_text(sink_desc); + label_.set_tooltip_markup(sink_desc); } } diff --git a/src/modules/pulseaudio_slider.cpp b/src/modules/pulseaudio_slider.cpp index bf85584e..d0e54459 100644 --- a/src/modules/pulseaudio_slider.cpp +++ b/src/modules/pulseaudio_slider.cpp @@ -10,73 +10,51 @@ PulseaudioSlider::PulseaudioSlider(const std::string& id, const Json::Value& con if (config_["target"].isString()) { std::string target = config_["target"].asString(); if (target == "sink") { - this->target = PulseaudioSliderTarget::Sink; + this->target = util::PulseaudioTarget::Sink; } else if (target == "source") { - this->target = PulseaudioSliderTarget::Source; + this->target = util::PulseaudioTarget::Source; } } + + if (config_["zero-on-mute"].isBool()) { + zero_on_mute = config_["zero-on-mute"].asBool(); + } + + if (config_["unmute-on-volume-change"].isBool()) { + unmute_on_volume_change = config_["unmute-on-volume-change"].asBool(); + } } void PulseaudioSlider::update() { - switch (target) { - case PulseaudioSliderTarget::Sink: - if (backend->getSinkMuted()) { - scale_.set_value(min_); - } else { - scale_.set_value(backend->getSinkVolume()); - } - break; + uint16_t display_value = backend->getVolume(target); + bool is_muted = backend->getMuted(target); - case PulseaudioSliderTarget::Source: - if (backend->getSourceMuted()) { - scale_.set_value(min_); - } else { - scale_.set_value(backend->getSourceVolume()); - } - break; + if (is_muted) { + if (zero_on_mute) { + display_value = min_; + } + if (!previously_muted) { + scale_.get_style_context()->add_class("muted"); + } + } else if (previously_muted) { + scale_.get_style_context()->remove_class("muted"); } + + scale_.set_value(display_value); + + previously_muted = is_muted; } void PulseaudioSlider::onValueChanged() { - bool is_mute = false; + uint16_t slider_value = scale_.get_value(); - switch (target) { - case PulseaudioSliderTarget::Sink: - if (backend->getSinkMuted()) { - is_mute = true; - } - break; - - case PulseaudioSliderTarget::Source: - if (backend->getSourceMuted()) { - is_mute = true; - } - break; - } - - uint16_t volume = scale_.get_value(); - - if (is_mute) { - // Avoid setting sink/source to volume 0 if the user muted if via another mean. - if (volume == 0) { - return; - } - - // If the sink/source is mute, but the user clicked the slider, unmute it! - else { - switch (target) { - case PulseaudioSliderTarget::Sink: - backend->toggleSinkMute(false); - break; - - case PulseaudioSliderTarget::Source: - backend->toggleSourceMute(false); - break; - } + // Avoid setting sink/source to volume 0 if the user muted it via other means. + if (!backend->getMuted(target) || slider_value != 0) { + if (unmute_on_volume_change) { + backend->unmute(target); } + backend->changeVolume(slider_value, min_, max_); } - - backend->changeVolume(volume, min_, max_); } -} // namespace waybar::modules \ No newline at end of file +} // namespace waybar::modules diff --git a/src/modules/river/layout.cpp b/src/modules/river/layout.cpp index e938400f..3f1745fe 100644 --- a/src/modules/river/layout.cpp +++ b/src/modules/river/layout.cpp @@ -7,48 +7,48 @@ namespace waybar::modules::river { -static void listen_focused_tags(void *data, struct zriver_output_status_v1 *zriver_output_status_v1, +static void listen_focused_tags(void* data, struct zriver_output_status_v1* zriver_output_status_v1, uint32_t tags) { // Intentionally empty } -static void listen_view_tags(void *data, struct zriver_output_status_v1 *zriver_output_status_v1, - struct wl_array *tags) { +static void listen_view_tags(void* data, struct zriver_output_status_v1* zriver_output_status_v1, + struct wl_array* tags) { // Intentionally empty } -static void listen_urgent_tags(void *data, struct zriver_output_status_v1 *zriver_output_status_v1, +static void listen_urgent_tags(void* data, struct zriver_output_status_v1* zriver_output_status_v1, uint32_t tags) { // Intentionally empty } -static void listen_layout_name(void *data, struct zriver_output_status_v1 *zriver_output_status_v1, - const char *layout) { - static_cast(data)->handle_name(layout); +static void listen_layout_name(void* data, struct zriver_output_status_v1* zriver_output_status_v1, + const char* layout) { + static_cast(data)->handle_name(layout); } -static void listen_layout_name_clear(void *data, - struct zriver_output_status_v1 *zriver_output_status_v1) { - static_cast(data)->handle_clear(); +static void listen_layout_name_clear(void* data, + struct zriver_output_status_v1* zriver_output_status_v1) { + static_cast(data)->handle_clear(); } -static void listen_focused_output(void *data, struct zriver_seat_status_v1 *zriver_seat_status_v1, - struct wl_output *output) { - static_cast(data)->handle_focused_output(output); +static void listen_focused_output(void* data, struct zriver_seat_status_v1* zriver_seat_status_v1, + struct wl_output* output) { + static_cast(data)->handle_focused_output(output); } -static void listen_unfocused_output(void *data, struct zriver_seat_status_v1 *zriver_seat_status_v1, - struct wl_output *output) { - static_cast(data)->handle_unfocused_output(output); +static void listen_unfocused_output(void* data, struct zriver_seat_status_v1* zriver_seat_status_v1, + struct wl_output* output) { + static_cast(data)->handle_unfocused_output(output); } -static void listen_focused_view(void *data, struct zriver_seat_status_v1 *zriver_seat_status_v1, - const char *title) { +static void listen_focused_view(void* data, struct zriver_seat_status_v1* zriver_seat_status_v1, + const char* title) { // Intentionally empty } -static void listen_mode(void *data, struct zriver_seat_status_v1 *zriver_seat_status_v1, - const char *mode) { +static void listen_mode(void* data, struct zriver_seat_status_v1* zriver_seat_status_v1, + const char* mode) { // Intentionally empty } @@ -67,8 +67,8 @@ static const zriver_seat_status_v1_listener seat_status_listener_impl{ .mode = listen_mode, }; -static void handle_global(void *data, struct wl_registry *registry, uint32_t name, - const char *interface, uint32_t version) { +static void handle_global(void* data, struct wl_registry* registry, uint32_t name, + const char* interface, uint32_t version) { if (std::strcmp(interface, zriver_status_manager_v1_interface.name) == 0) { version = std::min(version, 4); @@ -80,32 +80,32 @@ static void handle_global(void *data, struct wl_registry *registry, uint32_t nam std::to_string(version)); return; } - static_cast(data)->status_manager_ = static_cast( + static_cast(data)->status_manager_ = static_cast( wl_registry_bind(registry, name, &zriver_status_manager_v1_interface, version)); } if (std::strcmp(interface, wl_seat_interface.name) == 0) { version = std::min(version, 1); - static_cast(data)->seat_ = static_cast( - wl_registry_bind(registry, name, &wl_seat_interface, version)); + static_cast(data)->seat_ = + static_cast(wl_registry_bind(registry, name, &wl_seat_interface, version)); } } -static void handle_global_remove(void *data, struct wl_registry *registry, uint32_t name) { +static void handle_global_remove(void* data, struct wl_registry* registry, uint32_t name) { // Nobody cares } static const wl_registry_listener registry_listener_impl = {.global = handle_global, .global_remove = handle_global_remove}; -Layout::Layout(const std::string &id, const waybar::Bar &bar, const Json::Value &config) +Layout::Layout(const std::string& id, const waybar::Bar& bar, const Json::Value& config) : waybar::ALabel(config, "layout", id, "{}"), status_manager_{nullptr}, seat_{nullptr}, bar_(bar), output_status_{nullptr} { - struct wl_display *display = Client::inst()->wl_display; - struct wl_registry *registry = wl_display_get_registry(display); + struct wl_display* display = Client::inst()->wl_display; + struct wl_registry* registry = wl_display_get_registry(display); wl_registry_add_listener(registry, ®istry_listener_impl, this); wl_display_roundtrip(display); @@ -118,6 +118,7 @@ Layout::Layout(const std::string &id, const waybar::Bar &bar, const Json::Value if (!seat_) { spdlog::error("wl_seat not advertised"); + return; } label_.hide(); @@ -141,13 +142,19 @@ Layout::~Layout() { } } -void Layout::handle_name(const char *name) { +void Layout::handle_name(const char* name) { if (std::strcmp(name, "") == 0 || format_.empty()) { label_.hide(); // hide empty labels or labels with empty format } else { - label_.show(); + if (!name_.empty()) { + label_.get_style_context()->remove_class(name_); + } + + label_.get_style_context()->add_class(name); label_.set_markup(fmt::format(fmt::runtime(format_), Glib::Markup::escape_text(name).raw())); + label_.show(); } + name_ = name; ALabel::update(); } @@ -156,7 +163,7 @@ void Layout::handle_clear() { ALabel::update(); } -void Layout::handle_focused_output(struct wl_output *output) { +void Layout::handle_focused_output(struct wl_output* output) { if (output_ == output) { // if we focused the output this bar belongs to label_.get_style_context()->add_class("focused"); ALabel::update(); @@ -164,7 +171,7 @@ void Layout::handle_focused_output(struct wl_output *output) { focused_output_ = output; } -void Layout::handle_unfocused_output(struct wl_output *output) { +void Layout::handle_unfocused_output(struct wl_output* output) { if (output_ == output) { // if we unfocused the output this bar belongs to label_.get_style_context()->remove_class("focused"); ALabel::update(); diff --git a/src/modules/river/mode.cpp b/src/modules/river/mode.cpp index 1f788e09..13545030 100644 --- a/src/modules/river/mode.cpp +++ b/src/modules/river/mode.cpp @@ -7,23 +7,23 @@ namespace waybar::modules::river { -static void listen_focused_output(void *data, struct zriver_seat_status_v1 *seat_status, - struct wl_output *output) { +static void listen_focused_output(void* data, struct zriver_seat_status_v1* seat_status, + struct wl_output* output) { // Intentionally empty } -static void listen_unfocused_output(void *data, struct zriver_seat_status_v1 *seat_status, - struct wl_output *output) { +static void listen_unfocused_output(void* data, struct zriver_seat_status_v1* seat_status, + struct wl_output* output) { // Intentionally empty } -static void listen_focused_view(void *data, struct zriver_seat_status_v1 *seat_status, - const char *title) { +static void listen_focused_view(void* data, struct zriver_seat_status_v1* seat_status, + const char* title) { // Intentionally empty } -static void listen_mode(void *data, struct zriver_seat_status_v1 *seat_status, const char *mode) { - static_cast(data)->handle_mode(mode); +static void listen_mode(void* data, struct zriver_seat_status_v1* seat_status, const char* mode) { + static_cast(data)->handle_mode(mode); } static const zriver_seat_status_v1_listener seat_status_listener_impl = { @@ -33,8 +33,8 @@ static const zriver_seat_status_v1_listener seat_status_listener_impl = { .mode = listen_mode, }; -static void handle_global(void *data, struct wl_registry *registry, uint32_t name, - const char *interface, uint32_t version) { +static void handle_global(void* data, struct wl_registry* registry, uint32_t name, + const char* interface, uint32_t version) { if (std::strcmp(interface, zriver_status_manager_v1_interface.name) == 0) { version = std::min(version, 3); if (version < ZRIVER_SEAT_STATUS_V1_MODE_SINCE_VERSION) { @@ -42,31 +42,31 @@ static void handle_global(void *data, struct wl_registry *registry, uint32_t nam "river server does not support the \"mode\" event; the module will be disabled"); return; } - static_cast(data)->status_manager_ = static_cast( + static_cast(data)->status_manager_ = static_cast( wl_registry_bind(registry, name, &zriver_status_manager_v1_interface, version)); } else if (std::strcmp(interface, wl_seat_interface.name) == 0) { version = std::min(version, 1); - static_cast(data)->seat_ = static_cast( - wl_registry_bind(registry, name, &wl_seat_interface, version)); + static_cast(data)->seat_ = + static_cast(wl_registry_bind(registry, name, &wl_seat_interface, version)); } } -static void handle_global_remove(void *data, struct wl_registry *registry, uint32_t name) { +static void handle_global_remove(void* data, struct wl_registry* registry, uint32_t name) { // Nobody cares } static const wl_registry_listener registry_listener_impl = {.global = handle_global, .global_remove = handle_global_remove}; -Mode::Mode(const std::string &id, const waybar::Bar &bar, const Json::Value &config) +Mode::Mode(const std::string& id, const waybar::Bar& bar, const Json::Value& config) : waybar::ALabel(config, "mode", id, "{}"), status_manager_{nullptr}, seat_{nullptr}, bar_(bar), mode_{""}, seat_status_{nullptr} { - struct wl_display *display = Client::inst()->wl_display; - struct wl_registry *registry = wl_display_get_registry(display); + struct wl_display* display = Client::inst()->wl_display; + struct wl_registry* registry = wl_display_get_registry(display); wl_registry_add_listener(registry, ®istry_listener_impl, this); wl_display_roundtrip(display); @@ -77,6 +77,7 @@ Mode::Mode(const std::string &id, const waybar::Bar &bar, const Json::Value &con if (!seat_) { spdlog::error("wl_seat not advertised"); + return; } label_.hide(); @@ -94,7 +95,7 @@ Mode::~Mode() { } } -void Mode::handle_mode(const char *mode) { +void Mode::handle_mode(const char* mode) { if (format_.empty()) { label_.hide(); } else { diff --git a/src/modules/river/tags.cpp b/src/modules/river/tags.cpp index 359e5a23..f06565f6 100644 --- a/src/modules/river/tags.cpp +++ b/src/modules/river/tags.cpp @@ -12,19 +12,19 @@ namespace waybar::modules::river { -static void listen_focused_tags(void *data, struct zriver_output_status_v1 *zriver_output_status_v1, +static void listen_focused_tags(void* data, struct zriver_output_status_v1* zriver_output_status_v1, uint32_t tags) { - static_cast(data)->handle_focused_tags(tags); + static_cast(data)->handle_focused_tags(tags); } -static void listen_view_tags(void *data, struct zriver_output_status_v1 *zriver_output_status_v1, - struct wl_array *tags) { - static_cast(data)->handle_view_tags(tags); +static void listen_view_tags(void* data, struct zriver_output_status_v1* zriver_output_status_v1, + struct wl_array* tags) { + static_cast(data)->handle_view_tags(tags); } -static void listen_urgent_tags(void *data, struct zriver_output_status_v1 *zriver_output_status_v1, +static void listen_urgent_tags(void* data, struct zriver_output_status_v1* zriver_output_status_v1, uint32_t tags) { - static_cast(data)->handle_urgent_tags(tags); + static_cast(data)->handle_urgent_tags(tags); } static const zriver_output_status_v1_listener output_status_listener_impl{ @@ -33,15 +33,15 @@ static const zriver_output_status_v1_listener output_status_listener_impl{ .urgent_tags = listen_urgent_tags, }; -static void listen_command_success(void *data, - struct zriver_command_callback_v1 *zriver_command_callback_v1, - const char *output) { +static void listen_command_success(void* data, + struct zriver_command_callback_v1* zriver_command_callback_v1, + const char* output) { // Do nothing but keep listener to avoid crashing when command was successful } -static void listen_command_failure(void *data, - struct zriver_command_callback_v1 *zriver_command_callback_v1, - const char *output) { +static void listen_command_failure(void* data, + struct zriver_command_callback_v1* zriver_command_callback_v1, + const char* output) { spdlog::error("failure when selecting/toggling tags {}", output); } @@ -50,38 +50,38 @@ static const zriver_command_callback_v1_listener command_callback_listener_impl{ .failure = listen_command_failure, }; -static void handle_global(void *data, struct wl_registry *registry, uint32_t name, - const char *interface, uint32_t version) { +static void handle_global(void* data, struct wl_registry* registry, uint32_t name, + const char* interface, uint32_t version) { if (std::strcmp(interface, zriver_status_manager_v1_interface.name) == 0) { version = std::min(version, 2u); if (version < ZRIVER_OUTPUT_STATUS_V1_URGENT_TAGS_SINCE_VERSION) { spdlog::warn("river server does not support urgent tags"); } - static_cast(data)->status_manager_ = static_cast( + static_cast(data)->status_manager_ = static_cast( wl_registry_bind(registry, name, &zriver_status_manager_v1_interface, version)); } if (std::strcmp(interface, zriver_control_v1_interface.name) == 0) { version = std::min(version, 1u); - static_cast(data)->control_ = static_cast( + static_cast(data)->control_ = static_cast( wl_registry_bind(registry, name, &zriver_control_v1_interface, version)); } if (std::strcmp(interface, wl_seat_interface.name) == 0) { version = std::min(version, 1u); - static_cast(data)->seat_ = static_cast( - wl_registry_bind(registry, name, &wl_seat_interface, version)); + static_cast(data)->seat_ = + static_cast(wl_registry_bind(registry, name, &wl_seat_interface, version)); } } -static void handle_global_remove(void *data, struct wl_registry *registry, uint32_t name) { +static void handle_global_remove(void* data, struct wl_registry* registry, uint32_t name) { /* Ignore event */ } static const wl_registry_listener registry_listener_impl = {.global = handle_global, .global_remove = handle_global_remove}; -Tags::Tags(const std::string &id, const waybar::Bar &bar, const Json::Value &config) +Tags::Tags(const std::string& id, const waybar::Bar& bar, const Json::Value& config) : waybar::AModule(config, "tags", id, false, false), status_manager_{nullptr}, control_{nullptr}, @@ -89,8 +89,8 @@ Tags::Tags(const std::string &id, const waybar::Bar &bar, const Json::Value &con bar_(bar), box_{bar.orientation, 0}, output_status_{nullptr} { - struct wl_display *display = Client::inst()->wl_display; - struct wl_registry *registry = wl_display_get_registry(display); + struct wl_display* display = Client::inst()->wl_display; + struct wl_registry* registry = wl_display_get_registry(display); wl_registry_add_listener(registry, ®istry_listener_impl, this); wl_display_roundtrip(display); @@ -101,10 +101,12 @@ Tags::Tags(const std::string &id, const waybar::Bar &bar, const Json::Value &con if (!control_) { spdlog::error("river_control_v1 not advertised"); + return; } if (!seat_) { spdlog::error("wl_seat not advertised"); + return; } box_.set_name("tags"); @@ -129,7 +131,7 @@ Tags::Tags(const std::string &id, const waybar::Bar &bar, const Json::Value &con buttons_.emplace_back(std::to_string(tag + 1)); } - auto &button = buttons_[tag]; + auto& button = buttons_[tag]; button.set_relief(Gtk::RELIEF_NONE); box_.pack_start(button, false, false, 0); @@ -150,11 +152,7 @@ Tags::Tags(const std::string &id, const waybar::Bar &bar, const Json::Value &con button.show(); } - struct wl_output *output = gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj()); - output_status_ = zriver_status_manager_v1_get_river_output_status(status_manager_, output); - zriver_output_status_v1_add_listener(output_status_, &output_status_listener_impl, this); - - zriver_status_manager_v1_destroy(status_manager_); + box_.signal_show().connect(sigc::mem_fun(*this, &Tags::handle_show)); } Tags::~Tags() { @@ -165,21 +163,35 @@ Tags::~Tags() { if (control_) { zriver_control_v1_destroy(control_); } + + if (status_manager_) { + zriver_status_manager_v1_destroy(status_manager_); + } +} + +void Tags::handle_show() { + if (!status_manager_) return; + struct wl_output* output = gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj()); + output_status_ = zriver_status_manager_v1_get_river_output_status(status_manager_, output); + zriver_output_status_v1_add_listener(output_status_, &output_status_listener_impl, this); + + zriver_status_manager_v1_destroy(status_manager_); + status_manager_ = nullptr; } void Tags::handle_primary_clicked(uint32_t tag) { // Send river command to select tag on left mouse click - zriver_command_callback_v1 *callback; + zriver_command_callback_v1* callback; zriver_control_v1_add_argument(control_, "set-focused-tags"); zriver_control_v1_add_argument(control_, std::to_string(tag).c_str()); callback = zriver_control_v1_run_command(control_, seat_); zriver_command_callback_v1_add_listener(callback, &command_callback_listener_impl, nullptr); } -bool Tags::handle_button_press(GdkEventButton *event_button, uint32_t tag) { +bool Tags::handle_button_press(GdkEventButton* event_button, uint32_t tag) { if (event_button->type == GDK_BUTTON_PRESS && event_button->button == 3) { // Send river command to toggle tag on right mouse click - zriver_command_callback_v1 *callback; + zriver_command_callback_v1* callback; zriver_control_v1_add_argument(control_, "toggle-focused-tags"); zriver_control_v1_add_argument(control_, std::to_string(tag).c_str()); callback = zriver_control_v1_run_command(control_, seat_); @@ -208,9 +220,9 @@ void Tags::handle_focused_tags(uint32_t tags) { } } -void Tags::handle_view_tags(struct wl_array *view_tags) { +void Tags::handle_view_tags(struct wl_array* view_tags) { uint32_t tags = 0; - auto view_tag = reinterpret_cast(view_tags->data); + auto view_tag = reinterpret_cast(view_tags->data); auto end = view_tag + (view_tags->size / sizeof(uint32_t)); for (; view_tag < end; ++view_tag) { tags |= *view_tag; diff --git a/src/modules/river/window.cpp b/src/modules/river/window.cpp index dc7a6459..2daed002 100644 --- a/src/modules/river/window.cpp +++ b/src/modules/river/window.cpp @@ -9,23 +9,23 @@ namespace waybar::modules::river { -static void listen_focused_view(void *data, struct zriver_seat_status_v1 *zriver_seat_status_v1, - const char *title) { - static_cast(data)->handle_focused_view(title); +static void listen_focused_view(void* data, struct zriver_seat_status_v1* zriver_seat_status_v1, + const char* title) { + static_cast(data)->handle_focused_view(title); } -static void listen_focused_output(void *data, struct zriver_seat_status_v1 *zriver_seat_status_v1, - struct wl_output *output) { - static_cast(data)->handle_focused_output(output); +static void listen_focused_output(void* data, struct zriver_seat_status_v1* zriver_seat_status_v1, + struct wl_output* output) { + static_cast(data)->handle_focused_output(output); } -static void listen_unfocused_output(void *data, struct zriver_seat_status_v1 *zriver_seat_status_v1, - struct wl_output *output) { - static_cast(data)->handle_unfocused_output(output); +static void listen_unfocused_output(void* data, struct zriver_seat_status_v1* zriver_seat_status_v1, + struct wl_output* output) { + static_cast(data)->handle_unfocused_output(output); } -static void listen_mode(void *data, struct zriver_seat_status_v1 *zriver_seat_status_v1, - const char *mode) { +static void listen_mode(void* data, struct zriver_seat_status_v1* zriver_seat_status_v1, + const char* mode) { // This module doesn't care } @@ -36,36 +36,36 @@ static const zriver_seat_status_v1_listener seat_status_listener_impl{ .mode = listen_mode, }; -static void handle_global(void *data, struct wl_registry *registry, uint32_t name, - const char *interface, uint32_t version) { +static void handle_global(void* data, struct wl_registry* registry, uint32_t name, + const char* interface, uint32_t version) { if (std::strcmp(interface, zriver_status_manager_v1_interface.name) == 0) { version = std::min(version, 2); - static_cast(data)->status_manager_ = static_cast( + static_cast(data)->status_manager_ = static_cast( wl_registry_bind(registry, name, &zriver_status_manager_v1_interface, version)); } if (std::strcmp(interface, wl_seat_interface.name) == 0) { version = std::min(version, 1); - static_cast(data)->seat_ = static_cast( - wl_registry_bind(registry, name, &wl_seat_interface, version)); + static_cast(data)->seat_ = + static_cast(wl_registry_bind(registry, name, &wl_seat_interface, version)); } } -static void handle_global_remove(void *data, struct wl_registry *registry, uint32_t name) { +static void handle_global_remove(void* data, struct wl_registry* registry, uint32_t name) { /* Ignore event */ } static const wl_registry_listener registry_listener_impl = {.global = handle_global, .global_remove = handle_global_remove}; -Window::Window(const std::string &id, const waybar::Bar &bar, const Json::Value &config) +Window::Window(const std::string& id, const waybar::Bar& bar, const Json::Value& config) : waybar::ALabel(config, "window", id, "{}", 30), status_manager_{nullptr}, seat_{nullptr}, bar_(bar), seat_status_{nullptr} { - struct wl_display *display = Client::inst()->wl_display; - struct wl_registry *registry = wl_display_get_registry(display); + struct wl_display* display = Client::inst()->wl_display; + struct wl_registry* registry = wl_display_get_registry(display); wl_registry_add_listener(registry, ®istry_listener_impl, this); wl_display_roundtrip(display); @@ -78,6 +78,7 @@ Window::Window(const std::string &id, const waybar::Bar &bar, const Json::Value if (!seat_) { spdlog::error("wl_seat not advertised"); + return; } label_.hide(); // hide the label until populated @@ -95,7 +96,7 @@ Window::~Window() { } } -void Window::handle_focused_view(const char *title) { +void Window::handle_focused_view(const char* title) { // don't change the label on unfocused outputs. // this makes the current output report its currently focused view, and unfocused outputs will // report their last focused views. when freshly starting the bar, unfocused outputs don't have a @@ -116,7 +117,7 @@ void Window::handle_focused_view(const char *title) { ALabel::update(); } -void Window::handle_focused_output(struct wl_output *output) { +void Window::handle_focused_output(struct wl_output* output) { if (output_ == output) { // if we focused the output this bar belongs to label_.get_style_context()->add_class("focused"); ALabel::update(); @@ -124,7 +125,7 @@ void Window::handle_focused_output(struct wl_output *output) { focused_output_ = output; } -void Window::handle_unfocused_output(struct wl_output *output) { +void Window::handle_unfocused_output(struct wl_output* output) { if (output_ == output) { // if we unfocused the output this bar belongs to label_.get_style_context()->remove_class("focused"); ALabel::update(); diff --git a/src/modules/simpleclock.cpp b/src/modules/simpleclock.cpp index b6a96ecc..59a2b1c1 100644 --- a/src/modules/simpleclock.cpp +++ b/src/modules/simpleclock.cpp @@ -25,9 +25,9 @@ auto waybar::modules::Clock::update() -> void { if (config_["tooltip-format"].isString()) { auto tooltip_format = config_["tooltip-format"].asString(); auto tooltip_text = fmt::format(fmt::runtime(tooltip_format), localtime); - label_.set_tooltip_text(tooltip_text); + label_.set_tooltip_markup(tooltip_text); } else { - label_.set_tooltip_text(text); + label_.set_tooltip_markup(text); } } // Call parent update diff --git a/src/modules/sndio.cpp b/src/modules/sndio.cpp index 72e7207c..d878c4a4 100644 --- a/src/modules/sndio.cpp +++ b/src/modules/sndio.cpp @@ -9,8 +9,8 @@ namespace waybar::modules { -void ondesc(void *arg, struct sioctl_desc *d, int curval) { - auto self = static_cast(arg); +void ondesc(void* arg, struct sioctl_desc* d, int curval) { + auto self = static_cast(arg); if (d == NULL) { // d is NULL when the list is done return; @@ -18,8 +18,8 @@ void ondesc(void *arg, struct sioctl_desc *d, int curval) { self->set_desc(d, curval); } -void onval(void *arg, unsigned int addr, unsigned int val) { - auto self = static_cast(arg); +void onval(void* arg, unsigned int addr, unsigned int val) { + auto self = static_cast(arg); self->put_val(addr, val); } @@ -40,7 +40,7 @@ auto Sndio::connect_to_sndio() -> void { pfds_.reserve(sioctl_nfds(hdl_)); } -Sndio::Sndio(const std::string &id, const Json::Value &config) +Sndio::Sndio(const std::string& id, const Json::Value& config) : ALabel(config, "sndio", id, "{volume}%", 1, false, true), hdl_(nullptr), pfds_(0), @@ -80,7 +80,7 @@ Sndio::Sndio(const std::string &id, const Json::Value &config) while (thread_.isRunning()) { try { connect_to_sndio(); - } catch (std::runtime_error const &e) { + } catch (std::runtime_error const& e) { // avoid leaking hdl_ if (hdl_) { sioctl_close(hdl_); @@ -102,7 +102,9 @@ Sndio::~Sndio() { sioctl_close(hdl_); } auto Sndio::update() -> void { auto format = format_; - unsigned int vol = 100. * static_cast(volume_) / static_cast(maxval_); + unsigned int vol = (maxval_ > 0) ? static_cast(100. * static_cast(volume_) / + static_cast(maxval_)) + : 0; if (volume_ == 0) { label_.get_style_context()->add_class("muted"); @@ -122,7 +124,7 @@ auto Sndio::update() -> void { ALabel::update(); } -auto Sndio::set_desc(struct sioctl_desc *d, unsigned int val) -> void { +auto Sndio::set_desc(struct sioctl_desc* d, unsigned int val) -> void { std::string name{d->func}; std::string node_name{d->node0.name}; @@ -140,7 +142,7 @@ auto Sndio::put_val(unsigned int addr, unsigned int val) -> void { } } -bool Sndio::handleScroll(GdkEventScroll *e) { +bool Sndio::handleScroll(GdkEventScroll* e) { // change the volume only when no user provided // events are configured if (config_["on-scroll-up"].isString() || config_["on-scroll-down"].isString()) { @@ -180,7 +182,7 @@ bool Sndio::handleScroll(GdkEventScroll *e) { return true; } -bool Sndio::handleToggle(GdkEventButton *const &e) { +bool Sndio::handleToggle(GdkEventButton* const& e) { // toggle mute only when no user provided events are configured if (config_["on-click"].isString()) { return AModule::handleToggle(e); diff --git a/src/modules/sni/host.cpp b/src/modules/sni/host.cpp index 54faa16c..2c0c42c7 100644 --- a/src/modules/sni/host.cpp +++ b/src/modules/sni/host.cpp @@ -6,9 +6,13 @@ namespace waybar::modules::SNI { +static const unsigned RETRY_DELAY_MS = 200; +static const unsigned MAX_RETRIES = 10; + Host::Host(const std::size_t id, const Json::Value& config, const Bar& bar, const std::function&)>& on_add, - const std::function&)>& on_remove) + const std::function&)>& on_remove, + const std::function& on_update) : bus_name_("org.kde.StatusNotifierHost-" + std::to_string(getpid()) + "-" + std::to_string(id)), object_path_("/StatusNotifierHost/" + std::to_string(id)), @@ -17,9 +21,11 @@ Host::Host(const std::size_t id, const Json::Value& config, const Bar& bar, config_(config), bar_(bar), on_add_(on_add), - on_remove_(on_remove) {} + on_remove_(on_remove), + on_update_(on_update) {} Host::~Host() { + retry_connection_.disconnect(); if (bus_name_id_ > 0) { Gio::DBus::unown_name(bus_name_id_); bus_name_id_ = 0; @@ -51,15 +57,17 @@ void Host::nameAppeared(const Glib::RefPtr& conn, const G } void Host::nameVanished(const Glib::RefPtr& conn, const Glib::ustring name) { + retry_connection_.disconnect(); + retry_count_ = 0; g_cancellable_cancel(cancellable_); g_clear_object(&cancellable_); g_clear_object(&watcher_); - items_.clear(); + clearItems(); } void Host::proxyReady(GObject* src, GAsyncResult* res, gpointer data) { GError* error = nullptr; - waybar::util::ScopeGuard error_deleter([error]() { + waybar::util::ScopeGuard error_deleter([&error]() { if (error != nullptr) { g_error_free(error); } @@ -70,18 +78,37 @@ void Host::proxyReady(GObject* src, GAsyncResult* res, gpointer data) { return; } auto host = static_cast(data); - host->watcher_ = watcher; if (error != nullptr) { spdlog::error("Host: {}", error->message); + g_clear_object(&host->cancellable_); + if (host->retry_count_ >= MAX_RETRIES) { + spdlog::warn("Host: giving up on watcher proxy creation after {} retries", host->retry_count_); + return; + } + host->retry_count_ += 1; + // Store the timeout connection so it is disconnected in ~Host, avoiding a + // use-after-free if the Host is destroyed before the retry fires. + host->retry_connection_ = Glib::signal_timeout().connect( + [host]() { + if (host->watcher_ != nullptr) { + return false; + } + auto conn = Gio::DBus::Connection::get_sync(Gio::DBus::BusType::BUS_TYPE_SESSION); + host->nameAppeared(conn, "org.kde.StatusNotifierWatcher", ""); + return false; + }, + RETRY_DELAY_MS); return; } + host->retry_count_ = 0; + host->watcher_ = watcher; sn_watcher_call_register_host(host->watcher_, host->object_path_.c_str(), host->cancellable_, &Host::registerHost, data); } void Host::registerHost(GObject* src, GAsyncResult* res, gpointer data) { GError* error = nullptr; - waybar::util::ScopeGuard error_deleter([error]() { + waybar::util::ScopeGuard error_deleter([&error]() { if (error != nullptr) { g_error_free(error); } @@ -117,13 +144,50 @@ void Host::itemUnregistered(SnWatcher* watcher, const gchar* service, gpointer d auto [bus_name, object_path] = host->getBusNameAndObjectPath(service); for (auto it = host->items_.begin(); it != host->items_.end(); ++it) { if ((*it)->bus_name == bus_name && (*it)->object_path == object_path) { - host->on_remove_(*it); - host->items_.erase(it); + host->removeItem(it); break; } } } +void Host::itemReady(Item& item) { + auto it = std::find_if(items_.begin(), items_.end(), + [&item](const auto& candidate) { return candidate.get() == &item; }); + if (it != items_.end() && (*it)->isReady()) { + on_add_(*it); + } +} + +void Host::itemInvalidated(Item& item) { + auto it = std::find_if(items_.begin(), items_.end(), + [&item](const auto& candidate) { return candidate.get() == &item; }); + if (it != items_.end()) { + removeItem(it); + } +} + +void Host::removeItem(std::vector>::iterator it) { + if ((*it)->isReady()) { + on_remove_(*it); + } + items_.erase(it); +} + +void Host::clearItems() { + bool removed_ready_item = false; + for (auto& item : items_) { + if (item->isReady()) { + on_remove_(item); + removed_ready_item = true; + } + } + bool had_items = !items_.empty(); + items_.clear(); + if (had_items && !removed_ready_item) { + on_update_(); + } +} + std::tuple Host::getBusNameAndObjectPath(const std::string service) { auto it = service.find('/'); if (it != std::string::npos) { @@ -132,15 +196,18 @@ std::tuple Host::getBusNameAndObjectPath(const std::st return {service, "/StatusNotifierItem"}; } -void Host::addRegisteredItem(std::string service) { +void Host::addRegisteredItem(const std::string& service) { std::string bus_name, object_path; std::tie(bus_name, object_path) = getBusNameAndObjectPath(service); auto it = std::find_if(items_.begin(), items_.end(), [&bus_name, &object_path](const auto& item) { return bus_name == item->bus_name && object_path == item->object_path; }); if (it == items_.end()) { - items_.emplace_back(new Item(bus_name, object_path, config_, bar_)); - on_add_(items_.back()); + items_.emplace_back(std::make_unique( + bus_name, object_path, config_, bar_, + [this](Item& item) { itemReady(item); }, + [this](Item& item) { itemInvalidated(item); }, + on_update_)); } } diff --git a/src/modules/sni/item.cpp b/src/modules/sni/item.cpp index 9dc13158..8e2e2570 100644 --- a/src/modules/sni/item.cpp +++ b/src/modules/sni/item.cpp @@ -5,6 +5,7 @@ #include #include +#include #include #include #include @@ -37,13 +38,18 @@ namespace waybar::modules::SNI { static const Glib::ustring SNI_INTERFACE_NAME = sn_item_interface_info()->name; static const unsigned UPDATE_DEBOUNCE_TIME = 10; -Item::Item(const std::string& bn, const std::string& op, const Json::Value& config, const Bar& bar) +Item::Item(const std::string& bn, const std::string& op, const Json::Value& config, const Bar& bar, + const std::function& on_ready, + const std::function& on_invalidate, const std::function& on_updated) : bus_name(bn), object_path(op), icon_size(16), effective_icon_size(0), icon_theme(Gtk::IconTheme::create()), - bar_(bar) { + bar_(bar), + on_ready_(on_ready), + on_invalidate_(on_invalidate), + on_updated_(on_updated) { if (config["icon-size"].isUInt()) { icon_size = config["icon-size"].asUInt(); } @@ -74,6 +80,19 @@ Item::Item(const std::string& bn, const std::string& op, const Json::Value& conf cancellable_, interface); } +Item::~Item() { + if (this->gtk_menu != nullptr) { + this->gtk_menu->popdown(); + this->gtk_menu->detach(); + } + if (this->dbus_menu != nullptr) { + g_object_weak_unref(G_OBJECT(this->dbus_menu), (GWeakNotify)onMenuDestroyed, this); + this->dbus_menu = nullptr; + } +} + +bool Item::isReady() const { return ready_; } + bool Item::handleMouseEnter(GdkEventCrossing* const& e) { event_box.set_state_flags(Gtk::StateFlags::STATE_FLAG_PRELIGHT); return false; @@ -101,14 +120,18 @@ void Item::proxyReady(Glib::RefPtr& result) { if (this->id.empty() || this->category.empty()) { spdlog::error("Invalid Status Notifier Item: {}, {}", bus_name, object_path); + invalidate(); return; } this->updateImage(); + setReady(); } catch (const Glib::Error& err) { spdlog::error("Failed to create DBus Proxy for {} {}: {}", bus_name, object_path, err.what()); + invalidate(); } catch (const std::exception& err) { spdlog::error("Failed to create DBus Proxy for {} {}: {}", bus_name, object_path, err.what()); + invalidate(); } } @@ -140,7 +163,25 @@ void Item::setProperty(const Glib::ustring& name, Glib::VariantBase& value) { category = get_variant(value); } else if (name == "Id") { id = get_variant(value); - setCustomIcon(id); + + /* + * HACK: Electron apps seem to have the same ID, but tooltip seems correct, so use that as ID + * to pass as the custom icon option. I'm avoiding being disruptive and setting that to the ID + * itself as I've no idea what this would affect. + * The tooltip text is converted to lowercase since that's what (most?) themes expect? + * I still haven't found a way for it to pick from theme automatically, although + * it might be my theme. + */ + if (id == "chrome_status_icon_1") { + Glib::VariantBase value; + this->proxy_->get_cached_property(value, "ToolTip"); + tooltip = get_variant(value); + if (!tooltip.text.empty()) { + setCustomIcon(tooltip.text.lowercase()); + } + } else { + setCustomIcon(id); + } } else if (name == "Title") { title = get_variant(value); if (tooltip.text.empty()) { @@ -149,17 +190,25 @@ void Item::setProperty(const Glib::ustring& name, Glib::VariantBase& value) { } else if (name == "Status") { setStatus(get_variant(value)); } else if (name == "IconName") { - icon_name = get_variant(value); + if (has_custom_icon_) { + spdlog::trace("Item '{}': ignoring IconName update, custom icon is set", id); + } else { + icon_name = get_variant(value); + } } else if (name == "IconPixmap") { - icon_pixmap = this->extractPixBuf(value.gobj()); + if (has_custom_icon_) { + spdlog::trace("Item '{}': ignoring IconPixmap update, custom icon is set", id); + } else { + icon_pixmap = this->extractPixBuf(value.gobj()); + } } else if (name == "OverlayIconName") { overlay_icon_name = get_variant(value); } else if (name == "OverlayIconPixmap") { - // TODO: overlay_icon_pixmap + overlay_icon_pixmap = extractPixBuf(value.gobj()); } else if (name == "AttentionIconName") { attention_icon_name = get_variant(value); } else if (name == "AttentionIconPixmap") { - // TODO: attention_icon_pixmap + attention_icon_pixmap = extractPixBuf(value.gobj()); } else if (name == "AttentionMovieName") { attention_movie_name = get_variant(value); } else if (name == "ToolTip") { @@ -188,29 +237,54 @@ void Item::setProperty(const Glib::ustring& name, Glib::VariantBase& value) { } void Item::setStatus(const Glib::ustring& value) { - Glib::ustring lower = value.lowercase(); - event_box.set_visible(show_passive_ || lower.compare("passive") != 0); + status_ = value.lowercase(); + event_box.set_visible(show_passive_ || status_.compare("passive") != 0); auto style = event_box.get_style_context(); for (const auto& class_name : style->list_classes()) { style->remove_class(class_name); } - if (lower.compare("needsattention") == 0) { + auto css_class = status_; + if (css_class.compare("needsattention") == 0) { // convert status to dash-case for CSS - lower = "needs-attention"; + css_class = "needs-attention"; } - style->add_class(lower); + style->add_class(css_class); + on_updated_(); +} + +void Item::setReady() { + if (ready_) { + return; + } + ready_ = true; + on_ready_(*this); +} + +void Item::invalidate() { + if (ready_) { + ready_ = false; + } + on_invalidate_(*this); } void Item::setCustomIcon(const std::string& id) { + spdlog::debug("SNI tray id: {}", id); + std::string custom_icon = IconManager::instance().getIconForApp(id); if (!custom_icon.empty()) { if (std::filesystem::exists(custom_icon)) { - Glib::RefPtr custom_pixbuf = Gdk::Pixbuf::create_from_file(custom_icon); - icon_name = ""; // icon_name has priority over pixmap - icon_pixmap = custom_pixbuf; + try { + Glib::RefPtr custom_pixbuf = Gdk::Pixbuf::create_from_file(custom_icon); + icon_name = ""; // icon_name has priority over pixmap + icon_pixmap = custom_pixbuf; + has_custom_icon_ = true; + } catch (const Glib::Error& e) { + spdlog::error("Failed to load custom icon {}: {}", custom_icon, e.what()); + } } else { // if file doesn't exist it's most likely an icon_name icon_name = custom_icon; + has_custom_icon_ = true; } } } @@ -252,8 +326,8 @@ void Item::processUpdatedProperties(Glib::RefPtr& _result) { static const std::map> signal2props = { {"NewTitle", {"Title"}}, {"NewIcon", {"IconName", "IconPixmap"}}, - // {"NewAttentionIcon", {"AttentionIconName", "AttentionIconPixmap", "AttentionMovieName"}}, - // {"NewOverlayIcon", {"OverlayIconName", "OverlayIconPixmap"}}, + {"NewAttentionIcon", {"AttentionIconName", "AttentionIconPixmap", "AttentionMovieName"}}, + {"NewOverlayIcon", {"OverlayIconName", "OverlayIconPixmap"}}, {"NewIconThemePath", {"IconThemePath"}}, {"NewToolTip", {"ToolTip"}}, {"NewStatus", {"Status"}}, @@ -301,11 +375,20 @@ Glib::RefPtr Item::extractPixBuf(GVariant* variant) { if (array != nullptr) { g_free(array); } -#if GLIB_MAJOR_VERSION >= 2 && GLIB_MINOR_VERSION >= 68 - array = static_cast(g_memdup2(data, size)); -#else - array = static_cast(g_memdup(data, size)); -#endif + // We must allocate our own array because the data from GVariant is read-only + // and we need to modify it to convert ARGB to RGBA. + array = static_cast(g_malloc(size)); + + // Copy and convert ARGB to RGBA in one pass to avoid g_memdup2 overhead + const guchar* src = static_cast(data); + for (gsize i = 0; i < size; i += 4) { + guchar alpha = src[i]; + array[i] = src[i + 1]; + array[i + 1] = src[i + 2]; + array[i + 2] = src[i + 3]; + array[i + 3] = alpha; + } + lwidth = width; lheight = height; } @@ -314,14 +397,6 @@ Glib::RefPtr Item::extractPixBuf(GVariant* variant) { } g_variant_iter_free(it); if (array != nullptr) { - /* argb to rgba */ - for (uint32_t i = 0; i < 4U * lwidth * lheight; i += 4) { - guchar alpha = array[i]; - array[i] = array[i + 1]; - array[i + 1] = array[i + 2]; - array[i + 2] = array[i + 3]; - array[i + 3] = alpha; - } return Gdk::Pixbuf::create_from_data(array, Gdk::Colorspace::COLORSPACE_RGB, true, 8, lwidth, lheight, 4 * lwidth, &pixbuf_data_deleter); } @@ -330,47 +405,36 @@ Glib::RefPtr Item::extractPixBuf(GVariant* variant) { void Item::updateImage() { auto pixbuf = getIconPixbuf(); + if (!pixbuf) return; auto scaled_icon_size = getScaledIconSize(); // If the loaded icon is not square, assume that the icon height should match the // requested icon size, but the width is allowed to be different. As such, if the // height of the image does not match the requested icon size, resize the icon such that // the aspect ratio is maintained, but the height matches the requested icon size. - if (pixbuf->get_height() != scaled_icon_size) { + if (pixbuf->get_height() > 0 && pixbuf->get_height() != scaled_icon_size) { int width = scaled_icon_size * pixbuf->get_width() / pixbuf->get_height(); pixbuf = pixbuf->scale_simple(width, scaled_icon_size, Gdk::InterpType::INTERP_BILINEAR); } + pixbuf = overlayPixbufs(pixbuf, getOverlayIconPixbuf()); + auto surface = Gdk::Cairo::create_surface_from_pixbuf(pixbuf, image.get_scale_factor(), image.get_window()); image.set(surface); } Glib::RefPtr Item::getIconPixbuf() { - if (!icon_name.empty()) { - try { - std::ifstream temp(icon_name); - if (temp.is_open()) { - return Gdk::Pixbuf::create_from_file(icon_name); - } - } catch (Glib::Error& e) { - // Ignore because we want to also try different methods of getting an icon. - // - // But a warning is logged, as the file apparently exists, but there was - // a failure in creating a pixbuf out of it. - - spdlog::warn("Item '{}': {}", id, static_cast(e.what())); - } - - try { - // Will throw if it can not find an icon. - return getIconByName(icon_name, getScaledIconSize()); - } catch (Glib::Error& e) { - spdlog::trace("Item '{}': {}", id, static_cast(e.what())); + if (status_ == "needsattention") { + if (auto attention_pixbuf = getAttentionIconPixbuf()) { + return attention_pixbuf; } } - // Return the pixmap only if an icon for the given name could not be found. + if (auto pixbuf = loadIconFromNameOrFile(icon_name, true)) { + return pixbuf; + } + if (icon_pixmap) { return icon_pixmap; } @@ -385,17 +449,89 @@ Glib::RefPtr Item::getIconPixbuf() { return getIconByName("image-missing", getScaledIconSize()); } -Glib::RefPtr Item::getIconByName(const std::string& name, int request_size) { - icon_theme->rescan_if_needed(); +Glib::RefPtr Item::getAttentionIconPixbuf() { + if (auto pixbuf = loadIconFromNameOrFile(attention_icon_name, false)) { + return pixbuf; + } + if (auto pixbuf = loadIconFromNameOrFile(attention_movie_name, false)) { + return pixbuf; + } + return attention_icon_pixmap; +} - if (!icon_theme_path.empty() && - icon_theme->lookup_icon(name.c_str(), request_size, - Gtk::IconLookupFlags::ICON_LOOKUP_FORCE_SIZE)) { - return icon_theme->load_icon(name.c_str(), request_size, - Gtk::IconLookupFlags::ICON_LOOKUP_FORCE_SIZE); +Glib::RefPtr Item::getOverlayIconPixbuf() { + if (auto pixbuf = loadIconFromNameOrFile(overlay_icon_name, false)) { + return pixbuf; + } + return overlay_icon_pixmap; +} + +Glib::RefPtr Item::loadIconFromNameOrFile(const std::string& name, bool log_failure) { + if (name.empty()) { + return {}; + } + + try { + std::ifstream temp(name); + if (temp.is_open()) { + return Gdk::Pixbuf::create_from_file(name); + } + } catch (const Glib::Error& e) { + if (log_failure) { + spdlog::warn("Item '{}': {}", id, static_cast(e.what())); + } + } + + try { + return getIconByName(name, getScaledIconSize()); + } catch (const Glib::Error& e) { + if (log_failure) { + spdlog::trace("Item '{}': {}", id, static_cast(e.what())); + } + } + + return {}; +} + +Glib::RefPtr Item::overlayPixbufs(const Glib::RefPtr& base, + const Glib::RefPtr& overlay) { + if (!base || !overlay) { + return base; + } + + auto composed = base->copy(); + if (!composed) { + return base; + } + + int overlay_target_size = + std::max(1, std::min(composed->get_width(), composed->get_height()) / 2); + auto scaled_overlay = overlay->scale_simple(overlay_target_size, overlay_target_size, + Gdk::InterpType::INTERP_BILINEAR); + if (!scaled_overlay) { + return composed; + } + + int dest_x = std::max(0, composed->get_width() - scaled_overlay->get_width()); + int dest_y = std::max(0, composed->get_height() - scaled_overlay->get_height()); + scaled_overlay->composite(composed, dest_x, dest_y, scaled_overlay->get_width(), + scaled_overlay->get_height(), dest_x, dest_y, 1.0, 1.0, + Gdk::InterpType::INTERP_BILINEAR, 255); + return composed; +} + +Glib::RefPtr Item::getIconByName(const std::string& name, int request_size) { + if (!icon_theme_path.empty()) { + auto icon_info = icon_theme->lookup_icon(name.c_str(), request_size, + Gtk::IconLookupFlags::ICON_LOOKUP_FORCE_SIZE); + if (icon_info) { + bool is_sym = false; + return icon_info.load_symbolic(event_box.get_style_context(), is_sym); + } } return DefaultGtkIconThemeWrapper::load_icon(name.c_str(), request_size, - Gtk::IconLookupFlags::ICON_LOOKUP_FORCE_SIZE); + Gtk::IconLookupFlags::ICON_LOOKUP_FORCE_SIZE, + event_box.get_style_context()); } double Item::getScaledIconSize() { @@ -420,9 +556,15 @@ void Item::makeMenu() { gtk_menu->attach_to_widget(event_box); } } + // Manually reset prelight to make sure the tray item doesn't stay in a hover state even though + // the menu is focused + event_box.unset_state_flags(Gtk::StateFlags::STATE_FLAG_PRELIGHT); } bool Item::handleClick(GdkEventButton* const& ev) { + if (!proxy_) { + return false; + } auto parameters = Glib::VariantContainerBase::create_tuple( {Glib::Variant::create(ev->x_root + bar_.x_global), Glib::Variant::create(ev->y_root + bar_.y_global)}); @@ -450,6 +592,9 @@ bool Item::handleClick(GdkEventButton* const& ev) { } bool Item::handleScroll(GdkEventScroll* const& ev) { + if (!proxy_) { + return false; + } int dx = 0, dy = 0; switch (ev->direction) { case GDK_SCROLL_UP: diff --git a/src/modules/sni/tray.cpp b/src/modules/sni/tray.cpp index f657c855..19de5174 100644 --- a/src/modules/sni/tray.cpp +++ b/src/modules/sni/tray.cpp @@ -2,6 +2,8 @@ #include +#include + #include "modules/sni/icon_manager.hpp" namespace waybar::modules::SNI { @@ -11,7 +13,8 @@ Tray::Tray(const std::string& id, const Bar& bar, const Json::Value& config) box_(bar.orientation, 0), watcher_(SNI::Watcher::getInstance()), host_(nb_hosts_, config, bar, std::bind(&Tray::onAdd, this, std::placeholders::_1), - std::bind(&Tray::onRemove, this, std::placeholders::_1)) { + std::bind(&Tray::onRemove, this, std::placeholders::_1), + std::bind(&Tray::queueUpdate, this)) { box_.set_name("tray"); event_box_.add(box_); if (!id.empty()) { @@ -28,12 +31,16 @@ Tray::Tray(const std::string& id, const Bar& bar, const Json::Value& config) dp.emit(); } +void Tray::queueUpdate() { dp.emit(); } + void Tray::onAdd(std::unique_ptr& item) { if (config_["reverse-direction"].isBool() && config_["reverse-direction"].asBool()) { box_.pack_end(item->event_box); } else { box_.pack_start(item->event_box); } + item->event_box.signal_show().connect([this] { dp.emit(); }); + item->event_box.signal_hide().connect([this] { dp.emit(); }); dp.emit(); } @@ -43,9 +50,9 @@ void Tray::onRemove(std::unique_ptr& item) { } auto Tray::update() -> void { - // Show tray only when items are available - event_box_.set_visible(!box_.get_children().empty()); - // Call parent update + std::vector children = box_.get_children(); + event_box_.set_visible(std::any_of(children.begin(), children.end(), + [](Gtk::Widget* child) { return child->get_visible(); })); AModule::update(); } diff --git a/src/modules/sni/watcher.cpp b/src/modules/sni/watcher.cpp index 324bd9f5..969806cf 100644 --- a/src/modules/sni/watcher.cpp +++ b/src/modules/sni/watcher.cpp @@ -31,7 +31,7 @@ Watcher::~Watcher() { void Watcher::busAcquired(const Glib::RefPtr& conn, Glib::ustring name) { GError* error = nullptr; - waybar::util::ScopeGuard error_deleter([error]() { + waybar::util::ScopeGuard error_deleter([&error]() { if (error) { g_error_free(error); } @@ -69,7 +69,7 @@ gboolean Watcher::handleRegisterHost(Watcher* obj, GDBusMethodInvocation* invoca if (watch != nullptr) { g_warning("Status Notifier Host with bus name '%s' and object path '%s' is already registered", bus_name, object_path); - sn_watcher_complete_register_item(obj->watcher_, invocation); + sn_watcher_complete_register_host(obj->watcher_, invocation); return TRUE; } watch = gfWatchNew(GF_WATCH_TYPE_HOST, service, bus_name, object_path, obj); @@ -98,8 +98,8 @@ gboolean Watcher::handleRegisterItem(Watcher* obj, GDBusMethodInvocation* invoca } auto watch = gfWatchFind(obj->items_, bus_name, object_path); if (watch != nullptr) { - g_warning("Status Notifier Item with bus name '%s' and object path '%s' is already registered", - bus_name, object_path); + spdlog::debug("Ignoring duplicate Status Notifier Item registration for '{}' at '{}'", bus_name, + object_path); sn_watcher_complete_register_item(obj->watcher_, invocation); return TRUE; } @@ -158,7 +158,7 @@ void Watcher::nameVanished(GDBusConnection* connection, const char* name, gpoint watch->watcher->hosts_ = g_slist_remove(watch->watcher->hosts_, watch); if (watch->watcher->hosts_ == nullptr) { sn_watcher_set_is_host_registered(watch->watcher->watcher_, FALSE); - sn_watcher_emit_host_registered(watch->watcher->watcher_); + sn_watcher_emit_host_unregistered(watch->watcher->watcher_); } } else if (watch->type == GF_WATCH_TYPE_ITEM) { watch->watcher->items_ = g_slist_remove(watch->watcher->items_, watch); @@ -167,6 +167,7 @@ void Watcher::nameVanished(GDBusConnection* connection, const char* name, gpoint sn_watcher_emit_item_unregistered(watch->watcher->watcher_, tmp); g_free(tmp); } + gfWatchFree(watch); } void Watcher::updateRegisteredItems(SnWatcher* obj) { diff --git a/src/modules/sway/bar.cpp b/src/modules/sway/bar.cpp index f28b0502..f374f1c1 100644 --- a/src/modules/sway/bar.cpp +++ b/src/modules/sway/bar.cpp @@ -60,7 +60,7 @@ BarIpcClient::BarIpcClient(waybar::Bar& bar) : bar_{bar} { }); } -bool BarIpcClient::isModuleEnabled(std::string name) { +bool BarIpcClient::isModuleEnabled(const std::string& name) { for (const auto& section : {"modules-left", "modules-center", "modules-right"}) { if (const auto& modules = bar_.config.get(section, {}); modules.isArray()) { for (const auto& module : modules) { diff --git a/src/modules/sway/ipc/client.cpp b/src/modules/sway/ipc/client.cpp index 4139a53b..3ebccccd 100644 --- a/src/modules/sway/ipc/client.cpp +++ b/src/modules/sway/ipc/client.cpp @@ -9,8 +9,8 @@ namespace waybar::modules::sway { Ipc::Ipc() { const std::string& socketPath = getSocketPath(); - fd_ = open(socketPath); - fd_event_ = open(socketPath); + fd_ = util::ScopedFd(open(socketPath)); + fd_event_ = util::ScopedFd(open(socketPath)); } Ipc::~Ipc() { @@ -21,15 +21,11 @@ Ipc::~Ipc() { if (write(fd_, "close-sway-ipc", 14) == -1) { spdlog::error("Failed to close sway IPC"); } - close(fd_); - fd_ = -1; } if (fd_event_ > 0) { if (write(fd_event_, "close-sway-ipc", 14) == -1) { spdlog::error("Failed to close sway IPC event handler"); } - close(fd_event_); - fd_event_ = -1; } } @@ -64,7 +60,7 @@ const std::string Ipc::getSocketPath() const { } int Ipc::open(const std::string& socketPath) const { - int32_t fd = socket(AF_UNIX, SOCK_STREAM, 0); + util::ScopedFd fd(socket(AF_UNIX, SOCK_STREAM, 0)); if (fd == -1) { throw std::runtime_error("Unable to open Unix socket"); } @@ -78,7 +74,7 @@ int Ipc::open(const std::string& socketPath) const { if (::connect(fd, reinterpret_cast(&addr), l) == -1) { throw std::runtime_error("Unable to connect to Sway"); } - return fd; + return fd.release(); } struct Ipc::ipc_response Ipc::recv(int fd) { diff --git a/src/modules/sway/language.cpp b/src/modules/sway/language.cpp index a005df17..28f1ef24 100644 --- a/src/modules/sway/language.cpp +++ b/src/modules/sway/language.cpp @@ -22,10 +22,10 @@ Language::Language(const std::string& id, const Json::Value& config) hide_single_ = config["hide-single-layout"].isBool() && config["hide-single-layout"].asBool(); is_variant_displayed = format_.find("{variant}") != std::string::npos; if (format_.find("{}") != std::string::npos || format_.find("{short}") != std::string::npos) { - displayed_short_flag |= static_cast(DispayedShortFlag::ShortName); + displayed_short_flag |= static_cast(DisplayedShortFlag::ShortName); } if (format_.find("{shortDescription}") != std::string::npos) { - displayed_short_flag |= static_cast(DispayedShortFlag::ShortDescription); + displayed_short_flag |= static_cast(DisplayedShortFlag::ShortDescription); } if (config.isMember("tooltip-format")) { tooltip_format_ = config["tooltip-format"].asString(); @@ -54,21 +54,28 @@ void Language::onCmd(const struct Ipc::ipc_response& res) { std::lock_guard lock(mutex_); 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 + // Union layout names across every keyboard input so hot-plugged devices contribute their + // layouts to the map. Track the device with the most layouts to seed the initially displayed + // layout, matching the previous behaviour at startup. Json::ArrayIndex max_id = 0, max = 0; for (Json::ArrayIndex i = 0; i < payload.size(); i++) { - auto size = payload[i][XKB_LAYOUT_NAMES_KEY].size(); - if (size > max) { - max = size; + if (payload[i]["type"].asString() != "keyboard") continue; + const auto& names = payload[i][XKB_LAYOUT_NAMES_KEY]; + if (names.size() > max) { + max = names.size(); max_id = i; } + for (const auto& layout : names) { + const auto name = layout.asString(); + if (std::find(used_layouts.begin(), used_layouts.end(), name) == used_layouts.end()) { + used_layouts.push_back(name); + } + } } - for (const auto& layout : payload[max_id][XKB_LAYOUT_NAMES_KEY]) { - used_layouts.push_back(layout.asString()); - } - + // Rebuild from scratch so init_layouts_map's duplicate-suffix pass doesn't compound across + // refreshes (e.g. "us" -> "us1" -> "us11"). + layouts_map_.clear(); init_layouts_map(used_layouts); set_current_layout(payload[max_id][XKB_ACTIVE_LAYOUT_NAME_KEY].asString()); dp.emit(); @@ -82,13 +89,26 @@ void Language::onEvent(const struct Ipc::ipc_response& res) { return; } + bool refresh_inputs = false; try { - std::lock_guard lock(mutex_); - auto payload = parser_.parse(res.payload)["input"]; - if (payload["type"].asString() == "keyboard") { - set_current_layout(payload[XKB_ACTIVE_LAYOUT_NAME_KEY].asString()); + { + std::lock_guard lock(mutex_); + auto root = parser_.parse(res.payload); + auto change = root["change"].asString(); + auto payload = root["input"]; + if (payload["type"].asString() == "keyboard") { + // A device was added or its keymap changed - the layout set may have grown, so refresh + // layouts_map_ via IPC_GET_INPUTS once we've released mutex_. + refresh_inputs = (change == "added" || change == "xkb_keymap"); + set_current_layout(payload[XKB_ACTIVE_LAYOUT_NAME_KEY].asString()); + } + dp.emit(); + } + // sendCmd is synchronous: it blocks on the IPC reply and then emits signal_cmd on this same + // thread, which lands in onCmd and re-locks mutex_. Must call it with mutex_ released. + if (refresh_inputs) { + ipc_.sendCmd(IPC_GET_INPUTS); } - dp.emit(); } catch (const std::exception& e) { spdlog::error("Language: {}", e.what()); } @@ -124,9 +144,16 @@ auto Language::update() -> void { ALabel::update(); } -auto Language::set_current_layout(std::string current_layout) -> void { +auto Language::set_current_layout(const std::string& current_layout) -> void { + // Guard against unknown / empty layout names: transient virtual keyboards (e.g. wtype) and + // hot-plugged devices whose layouts haven't made it into the map yet would otherwise blank out + // layout_ via map::operator[]'s default-construct-on-miss. + auto it = layouts_map_.find(current_layout); + if (it == layouts_map_.end()) { + return; + } label_.get_style_context()->remove_class(layout_.short_name); - layout_ = layouts_map_[current_layout]; + layout_ = it->second; label_.get_style_context()->add_class(layout_.short_name); } diff --git a/src/modules/sway/mode.cpp b/src/modules/sway/mode.cpp index b81735e5..1f5f071a 100644 --- a/src/modules/sway/mode.cpp +++ b/src/modules/sway/mode.cpp @@ -44,7 +44,7 @@ auto Mode::update() -> void { } else { label_.set_markup(fmt::format(fmt::runtime(format_), mode_)); if (tooltipEnabled()) { - label_.set_tooltip_text(mode_); + label_.set_tooltip_markup(mode_); } event_box_.show(); } diff --git a/src/modules/sway/window.cpp b/src/modules/sway/window.cpp index 25e430a7..2b62da14 100644 --- a/src/modules/sway/window.cpp +++ b/src/modules/sway/window.cpp @@ -41,8 +41,8 @@ void Window::onCmd(const struct Ipc::ipc_response& res) { std::lock_guard lock(mutex_); auto payload = parser_.parse(res.payload); auto output = payload["output"].isString() ? payload["output"].asString() : ""; - std::tie(app_nb_, floating_count_, windowId_, window_, app_id_, app_class_, shell_, layout_) = - getFocusedNode(payload["nodes"], output); + std::tie(app_nb_, floating_count_, windowId_, window_, app_id_, app_class_, shell_, layout_, + marks_) = getFocusedNode(payload["nodes"], output); updateAppIconName(app_id_, app_class_); dp.emit(); } catch (const std::exception& e) { @@ -94,12 +94,12 @@ auto Window::update() -> void { old_app_id_ = app_id_; } - label_.set_markup(waybar::util::rewriteString( + setLabelMarkup(waybar::util::rewriteString( fmt::format(fmt::runtime(format_), fmt::arg("title", window_), fmt::arg("app_id", app_id_), - fmt::arg("shell", shell_)), + fmt::arg("shell", shell_), fmt::arg("marks", marks_)), config_["rewrite"])); if (tooltipEnabled()) { - label_.set_tooltip_text(window_); + setTooltipMarkup(window_); } updateAppIcon(); @@ -108,7 +108,7 @@ auto Window::update() -> void { AAppIconLabel::update(); } -void Window::setClass(std::string classname, bool enable) { +void Window::setClass(const std::string& classname, bool enable) { if (enable) { if (!bar_.window.get_style_context()->has_class(classname)) { bar_.window.get_style_context()->add_class(classname); @@ -169,17 +169,31 @@ std::optional> getSingleChildNode( return {getSingleChildNode(child)}; } -std::tuple getWindowInfo(const Json::Value& node) { +std::tuple getWindowInfo( + const Json::Value& node, bool showHidden) { const auto app_id = node["app_id"].isString() ? node["app_id"].asString() : node["window_properties"]["instance"].asString(); const auto app_class = node["window_properties"]["class"].isString() ? node["window_properties"]["class"].asString() : ""; const auto shell = node["shell"].isString() ? node["shell"].asString() : ""; - return {app_id, app_class, shell}; + std::string marks = ""; + if (node["marks"].isArray()) { + for (const auto& m : node["marks"]) { + if (!m.isString() || (!showHidden && m.asString().at(0) == '_')) { + continue; + } + if (!marks.empty()) { + marks.append(","); + } + marks.append(m.asString()); + } + } + return {app_id, app_class, shell, marks}; } -std::tuple +std::tuple gfnWithWorkspace(const Json::Value& nodes, std::string& output, const Json::Value& config_, const Bar& bar_, Json::Value& parentWorkspace, const Json::Value& immediateParent) { @@ -207,7 +221,8 @@ gfnWithWorkspace(const Json::Value& nodes, std::string& output, const Json::Valu "", "", "", - node["layout"].asString()}; + node["layout"].asString(), + ""}; } parentWorkspace = node; } else if ((node["type"].asString() == "con" || node["type"].asString() == "floating_con") && @@ -215,7 +230,8 @@ gfnWithWorkspace(const Json::Value& nodes, std::string& output, const Json::Valu // found node spdlog::trace("actual output {}, output found {}, node (focused) found {}", bar_.output->name, output, node["name"].asString()); - const auto [app_id, app_class, shell] = getWindowInfo(node); + const auto [app_id, app_class, shell, marks] = + getWindowInfo(node, config_["show-hidden-marks"].asBool()); int nb = node.size(); int floating_count = 0; std::string workspace_layout = ""; @@ -232,20 +248,21 @@ gfnWithWorkspace(const Json::Value& nodes, std::string& output, const Json::Valu app_id, app_class, shell, - workspace_layout}; + workspace_layout, + marks}; } // iterate - auto [nb, f, id, name, app_id, app_class, shell, workspace_layout] = + auto [nb, f, id, name, app_id, app_class, shell, workspace_layout, marks] = gfnWithWorkspace(node["nodes"], output, config_, bar_, parentWorkspace, node); - auto [nb2, f2, id2, name2, app_id2, app_class2, shell2, workspace_layout2] = + auto [nb2, f2, id2, name2, app_id2, app_class2, shell2, workspace_layout2, marks2] = gfnWithWorkspace(node["floating_nodes"], output, config_, bar_, parentWorkspace, node); // if ((id > 0 || ((id2 < 0 || name2.empty()) && id > -1)) && !name.empty()) { if ((id > 0) || (id2 < 0 && id > -1)) { - return {nb, f, id, name, app_id, app_class, shell, workspace_layout}; + return {nb, f, id, name, app_id, app_class, shell, workspace_layout, marks}; } else if (id2 > 0 && !name2.empty()) { - return {nb2, f2, id2, name2, app_id2, app_class, shell2, workspace_layout2}; + return {nb2, f2, id2, name2, app_id2, app_class, shell2, workspace_layout2, marks2}; } } @@ -258,10 +275,12 @@ gfnWithWorkspace(const Json::Value& nodes, std::string& output, const Json::Valu std::string app_id = ""; std::string app_class = ""; std::string workspace_layout = ""; + std::string marks = ""; if (all_leaf_nodes.first == 1) { const auto single_child = getSingleChildNode(immediateParent); if (single_child.has_value()) { - std::tie(app_id, app_class, workspace_layout) = getWindowInfo(single_child.value()); + std::tie(app_id, app_class, workspace_layout, marks) = + getWindowInfo(single_child.value(), config_["show-hidden-marks"].asBool()); } } return {all_leaf_nodes.first, @@ -273,13 +292,15 @@ gfnWithWorkspace(const Json::Value& nodes, std::string& output, const Json::Valu app_id, app_class, workspace_layout, - immediateParent["layout"].asString()}; + immediateParent["layout"].asString(), + marks}; } - return {0, 0, -1, "", "", "", "", ""}; + return {0, 0, -1, "", "", "", "", "", ""}; } -std::tuple +std::tuple Window::getFocusedNode(const Json::Value& nodes, std::string& output) { Json::Value placeholder = Json::Value::null; return gfnWithWorkspace(nodes, output, config_, bar_, placeholder, placeholder); diff --git a/src/modules/sway/workspaces.cpp b/src/modules/sway/workspaces.cpp index b8ed73d4..6cb3ee48 100644 --- a/src/modules/sway/workspaces.cpp +++ b/src/modules/sway/workspaces.cpp @@ -10,10 +10,10 @@ namespace waybar::modules::sway { // Helper function to assign a number to a workspace, just like sway. In fact // this is taken quite verbatim from `sway/ipc-json.c`. -int Workspaces::convertWorkspaceNameToNum(std::string name) { +int Workspaces::convertWorkspaceNameToNum(const std::string& name) { if (isdigit(name[0]) != 0) { errno = 0; - char *endptr = nullptr; + char* endptr = nullptr; long long parsed_num = strtoll(name.c_str(), &endptr, 10); if (errno != 0 || parsed_num > INT32_MAX || parsed_num < 0 || endptr == name.c_str()) { return -1; @@ -23,7 +23,7 @@ int Workspaces::convertWorkspaceNameToNum(std::string name) { return -1; } -int Workspaces::windowRewritePriorityFunction(std::string const &window_rule) { +int Workspaces::windowRewritePriorityFunction(std::string const& window_rule) { // Rules that match against title are prioritized // Rules that don't specify if they're matching against either title or class are deprioritized bool const hasTitle = window_rule.find("title") != std::string::npos; @@ -41,12 +41,12 @@ int Workspaces::windowRewritePriorityFunction(std::string const &window_rule) { return 0; } -Workspaces::Workspaces(const std::string &id, const Bar &bar, const Json::Value &config) +Workspaces::Workspaces(const std::string& id, const Bar& bar, const Json::Value& config) : AModule(config, "workspaces", id, false, !config["disable-scroll"].asBool()), bar_(bar), box_(bar.orientation, 0) { if (config["format-icons"]["high-priority-named"].isArray()) { - for (const auto &it : config["format-icons"]["high-priority-named"]) { + for (const auto& it : config["format-icons"]["high-priority-named"]) { high_priority_named_.push_back(it.asString()); } } @@ -57,13 +57,13 @@ Workspaces::Workspaces(const std::string &id, const Bar &bar, const Json::Value box_.get_style_context()->add_class(MODULE_CLASS); event_box_.add(box_); if (config_["format-window-separator"].isString()) { - m_formatWindowSeperator = config_["format-window-separator"].asString(); + m_formatWindowSeparator = config_["format-window-separator"].asString(); } else { - m_formatWindowSeperator = " "; + m_formatWindowSeparator = " "; } - const Json::Value &windowRewrite = config["window-rewrite"]; + const Json::Value& windowRewrite = config["window-rewrite"]; if (windowRewrite.isObject()) { - const Json::Value &windowRewriteDefaultConfig = config["window-rewrite-default"]; + const Json::Value& windowRewriteDefaultConfig = config["window-rewrite-default"]; std::string windowRewriteDefault = windowRewriteDefaultConfig.isString() ? windowRewriteDefaultConfig.asString() : "?"; m_windowRewriteRules = waybar::util::RegexCollection( @@ -75,7 +75,7 @@ Workspaces::Workspaces(const std::string &id, const Bar &bar, const Json::Value ipc_.signal_cmd.connect(sigc::mem_fun(*this, &Workspaces::onCmd)); ipc_.sendCmd(IPC_GET_TREE); if (config["enable-bar-scroll"].asBool()) { - auto &window = const_cast(bar_).window; + auto& window = const_cast(bar_).window; window.add_events(Gdk::SCROLL_MASK | Gdk::SMOOTH_SCROLL_MASK); window.signal_scroll_event().connect(sigc::mem_fun(*this, &Workspaces::handleScroll)); } @@ -83,21 +83,21 @@ Workspaces::Workspaces(const std::string &id, const Bar &bar, const Json::Value ipc_.setWorker([this] { try { ipc_.handleEvent(); - } catch (const std::exception &e) { + } catch (const std::exception& e) { spdlog::error("Workspaces: {}", e.what()); } }); } -void Workspaces::onEvent(const struct Ipc::ipc_response &res) { +void Workspaces::onEvent(const struct Ipc::ipc_response& res) { try { ipc_.sendCmd(IPC_GET_TREE); - } catch (const std::exception &e) { + } catch (const std::exception& e) { spdlog::error("Workspaces: {}", e.what()); } } -void Workspaces::onCmd(const struct Ipc::ipc_response &res) { +void Workspaces::onCmd(const struct Ipc::ipc_response& res) { if (res.type == IPC_GET_TREE) { try { { @@ -107,7 +107,7 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) { std::vector outputs; bool alloutputs = config_["all-outputs"].asBool(); std::copy_if(payload["nodes"].begin(), payload["nodes"].end(), std::back_inserter(outputs), - [&](const auto &output) { + [&](const auto& output) { if (alloutputs && output["name"].asString() != "__i3") { return true; } @@ -117,7 +117,7 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) { return false; }); - for (auto &output : outputs) { + for (auto& output : outputs) { std::copy(output["nodes"].begin(), output["nodes"].end(), std::back_inserter(workspaces_)); std::copy(output["floating_nodes"].begin(), output["floating_nodes"].end(), @@ -126,13 +126,13 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) { // adding persistent workspaces (as per the config file) if (config_["persistent-workspaces"].isObject()) { - const Json::Value &p_workspaces = config_["persistent-workspaces"]; + const Json::Value& p_workspaces = config_["persistent-workspaces"]; const std::vector p_workspaces_names = p_workspaces.getMemberNames(); - for (const std::string &p_w_name : p_workspaces_names) { - const Json::Value &p_w = p_workspaces[p_w_name]; + for (const std::string& p_w_name : p_workspaces_names) { + const Json::Value& p_w = p_workspaces[p_w_name]; auto it = std::find_if(workspaces_.begin(), workspaces_.end(), - [&p_w_name](const Json::Value &node) { + [&p_w_name](const Json::Value& node) { return node["name"].asString() == p_w_name; }); @@ -142,7 +142,7 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) { if (p_w.isArray() && !p_w.empty()) { // Adding to target outputs - for (const Json::Value &output : p_w) { + for (const Json::Value& output : p_w) { if (output.asString() == bar_.output->name) { Json::Value v; v["name"] = p_w_name; @@ -185,10 +185,10 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) { // agreement that the "workspace prev/next" commands may not follow // the order displayed in Waybar. int max_num = -1; - for (auto &workspace : workspaces_) { + for (auto& workspace : workspaces_) { max_num = std::max(workspace["num"].asInt(), max_num); } - for (auto &workspace : workspaces_) { + for (auto& workspace : workspaces_) { auto workspace_num = workspace["num"].asInt(); if (workspace_num > -1) { workspace["sort"] = workspace_num; @@ -197,7 +197,7 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) { } } std::sort(workspaces_.begin(), workspaces_.end(), - [this](const Json::Value &lhs, const Json::Value &rhs) { + [this](const Json::Value& lhs, const Json::Value& rhs) { auto lname = lhs["name"].asString(); auto rname = rhs["name"].asString(); int l = lhs["sort"].asInt(); @@ -217,7 +217,7 @@ void Workspaces::onCmd(const struct Ipc::ipc_response &res) { }); } dp.emit(); - } catch (const std::exception &e) { + } catch (const std::exception& e) { spdlog::error("Workspaces: {}", e.what()); } } @@ -227,9 +227,12 @@ bool Workspaces::filterButtons() { bool needReorder = false; for (auto it = buttons_.begin(); it != buttons_.end();) { auto ws = std::find_if(workspaces_.begin(), workspaces_.end(), - [it](const auto &node) { return node["name"].asString() == it->first; }); + [it](const auto& node) { return node["name"].asString() == it->first; }); if (ws == workspaces_.end() || - (!config_["all-outputs"].asBool() && (*ws)["output"].asString() != bar_.output->name)) { + ((*ws).isMember("target_output") ? (*ws)["target_output"].asString() != bar_.output->name && + (*ws)["target_output"].asString() != "" + : !config_["all-outputs"].asBool() && + (*ws)["output"].asString() != bar_.output->name)) { it = buttons_.erase(it); needReorder = true; } else { @@ -239,23 +242,23 @@ bool Workspaces::filterButtons() { return needReorder; } -bool Workspaces::hasFlag(const Json::Value &node, const std::string &flag) { +bool Workspaces::hasFlag(const Json::Value& node, const std::string& flag) { if (node[flag].asBool()) { return true; } if (std::any_of(node["nodes"].begin(), node["nodes"].end(), - [&](auto const &e) { return hasFlag(e, flag); })) { + [&](auto const& e) { return hasFlag(e, flag); })) { return true; } if (std::any_of(node["floating_nodes"].begin(), node["floating_nodes"].end(), - [&](auto const &e) { return hasFlag(e, flag); })) { + [&](auto const& e) { return hasFlag(e, flag); })) { return true; } return false; } -void Workspaces::updateWindows(const Json::Value &node, std::string &windows) { +void Workspaces::updateWindows(const Json::Value& node, std::string& windows) { if ((node["type"].asString() == "con" || node["type"].asString() == "floating_con") && node["name"].isString()) { std::string title = g_markup_escape_text(node["name"].asString().c_str(), -1); @@ -271,13 +274,13 @@ void Workspaces::updateWindows(const Json::Value &node, std::string &windows) { window = fmt::format(fmt::runtime(window), fmt::arg("name", title), fmt::arg("class", windowClass)); windows.append(window); - windows.append(m_formatWindowSeperator); + windows.append(m_formatWindowSeparator); } } - for (const Json::Value &child : node["nodes"]) { + for (const Json::Value& child : node["nodes"]) { updateWindows(child, windows); } - for (const Json::Value &child : node["floating_nodes"]) { + for (const Json::Value& child : node["floating_nodes"]) { updateWindows(child, windows); } } @@ -290,7 +293,7 @@ auto Workspaces::update() -> void { if (bit == buttons_.end()) { needReorder = true; } - auto &button = bit == buttons_.end() ? addButton(*it) : bit->second; + auto& button = bit == buttons_.end() ? addButton(*it) : bit->second; if (needReorder) { box_.reorder_child(button, it - workspaces_.begin()); } @@ -329,9 +332,14 @@ auto Workspaces::update() -> void { } else { button.get_style_context()->remove_class("current_output"); } - std::string output = (*it)["name"].asString(); + std::string output; + if (!config_["disable-markup"].asBool()) { + output = g_markup_escape_text((*it)["name"].asString().c_str(), -1); + } else { + output = (*it)["name"].asString(); + } std::string windows = ""; - if (config_["window-format"].isString()) { + if (config_["window-rewrite"].isObject()) { updateWindows((*it), windows); } if (config_["format"].isString()) { @@ -340,11 +348,11 @@ auto Workspaces::update() -> void { fmt::runtime(format), fmt::arg("icon", getIcon(output, *it)), fmt::arg("value", output), fmt::arg("name", trimWorkspaceName(output)), fmt::arg("index", (*it)["num"].asString()), fmt::arg("windows", - windows.substr(0, windows.length() - m_formatWindowSeperator.length())), + windows.substr(0, windows.length() - m_formatWindowSeparator.length())), fmt::arg("output", (*it)["output"].asString())); } if (!config_["disable-markup"].asBool()) { - static_cast(button.get_children()[0])->set_markup(output); + static_cast(button.get_children()[0])->set_markup(output); } else { button.set_label(output); } @@ -354,9 +362,9 @@ auto Workspaces::update() -> void { AModule::update(); } -Gtk::Button &Workspaces::addButton(const Json::Value &node) { +Gtk::Button& Workspaces::addButton(const Json::Value& node) { auto pair = buttons_.emplace(node["name"].asString(), node["name"].asString()); - auto &&button = pair.first->second; + auto&& button = pair.first->second; box_.pack_start(button, false, false, 0); button.set_name("sway-workspace-" + node["name"].asString()); button.set_relief(Gtk::RELIEF_NONE); @@ -369,13 +377,16 @@ Gtk::Button &Workspaces::addButton(const Json::Value &node) { node["name"].asString(), node["target_output"].asString(), "--no-auto-back-and-forth", node["name"].asString())); } else { - ipc_.sendCmd(IPC_COMMAND, fmt::format("workspace {} \"{}\"", - config_["disable-auto-back-and-forth"].asBool() - ? "--no-auto-back-and-forth" - : "", - node["name"].asString())); + std::string flag = config_["disable-auto-back-and-forth"].asBool() + ? "--no-auto-back-and-forth" + : ""; + if (node["num"].asInt() >= 0) { + ipc_.sendCmd(IPC_COMMAND, fmt::format(workspace_switch_number_cmd_, flag, node["num"].asInt())); + } else { + ipc_.sendCmd(IPC_COMMAND, fmt::format(workspace_switch_cmd_, flag, node["name"].asString())); + } } - } catch (const std::exception &e) { + } catch (const std::exception& e) { spdlog::error("Workspaces: {}", e.what()); } }); @@ -383,18 +394,18 @@ Gtk::Button &Workspaces::addButton(const Json::Value &node) { return button; } -std::string Workspaces::getIcon(const std::string &name, const Json::Value &node) { +std::string Workspaces::getIcon(const std::string& name, const Json::Value& node) { std::vector keys = {"high-priority-named", "urgent", "focused", name, "default"}; - for (auto const &key : keys) { + for (auto const& key : keys) { if (key == "high-priority-named") { auto it = std::find_if(high_priority_named_.begin(), high_priority_named_.end(), - [&](const std::string &member) { return member == name; }); + [&](const std::string& member) { return member == name; }); if (it != high_priority_named_.end()) { return config_["format-icons"][name].asString(); } it = std::find_if(high_priority_named_.begin(), high_priority_named_.end(), - [&](const std::string &member) { + [&](const std::string& member) { return trimWorkspaceName(member) == trimWorkspaceName(name); }); if (it != high_priority_named_.end()) { @@ -417,8 +428,8 @@ std::string Workspaces::getIcon(const std::string &name, const Json::Value &node return name; } -bool Workspaces::handleScroll(GdkEventScroll *e) { - if (gdk_event_get_pointer_emulated((GdkEvent *)e) != 0) { +bool Workspaces::handleScroll(GdkEventScroll* e) { + if (gdk_event_get_pointer_emulated((GdkEvent*)e) != 0) { /** * Ignore emulated scroll events on window */ @@ -433,7 +444,7 @@ bool Workspaces::handleScroll(GdkEventScroll *e) { bool alloutputs = config_["all-outputs"].asBool(); std::lock_guard lock(mutex_); auto it = - std::find_if(workspaces_.begin(), workspaces_.end(), [alloutputs](const auto &workspace) { + std::find_if(workspaces_.begin(), workspaces_.end(), [alloutputs](const auto& workspace) { if (alloutputs) { return hasFlag(workspace, "focused"); } @@ -443,10 +454,11 @@ bool Workspaces::handleScroll(GdkEventScroll *e) { if (it == workspaces_.end()) { return true; } + bool reverse_scroll = config_["reverse-scroll"].isBool() && config_["reverse-scroll"].asBool(); if (dir == SCROLL_DIR::DOWN || dir == SCROLL_DIR::RIGHT) { - name = getCycleWorkspace(it, false); + name = getCycleWorkspace(it, reverse_scroll ? true : false); } else if (dir == SCROLL_DIR::UP || dir == SCROLL_DIR::LEFT) { - name = getCycleWorkspace(it, true); + name = getCycleWorkspace(it, reverse_scroll ? false : true); } else { return true; } @@ -459,7 +471,7 @@ bool Workspaces::handleScroll(GdkEventScroll *e) { } try { ipc_.sendCmd(IPC_COMMAND, fmt::format(workspace_switch_cmd_, "--no-auto-back-and-forth", name)); - } catch (const std::exception &e) { + } catch (const std::exception& e) { spdlog::error("Workspaces: {}", e.what()); } if (!config_["warp-on-scroll"].isNull() && !config_["warp-on-scroll"].asBool()) { @@ -486,7 +498,7 @@ std::string Workspaces::getCycleWorkspace(std::vector::iterator it, return (*it)["name"].asString(); } -std::string Workspaces::trimWorkspaceName(std::string name) { +std::string Workspaces::trimWorkspaceName(const std::string& name) { std::size_t found = name.find(':'); if (found != std::string::npos) { return name.substr(found + 1); @@ -519,7 +531,7 @@ bool is_focused_recursive(const Json::Value& node) { return false; } -void Workspaces::onButtonReady(const Json::Value &node, Gtk::Button &button) { +void Workspaces::onButtonReady(const Json::Value& node, Gtk::Button& button) { if (config_["current-only"].asBool()) { if (is_focused_recursive(node)) { button.show(); diff --git a/src/modules/systemd_failed_units.cpp b/src/modules/systemd_failed_units.cpp index 56e624cf..829a7776 100644 --- a/src/modules/systemd_failed_units.cpp +++ b/src/modules/systemd_failed_units.cpp @@ -1,10 +1,15 @@ #include "modules/systemd_failed_units.hpp" +#include #include +#include #include #include #include +#include +#include +#include static const unsigned UPDATE_DEBOUNCE_TIME_MS = 1000; @@ -12,76 +17,134 @@ namespace waybar::modules { SystemdFailedUnits::SystemdFailedUnits(const std::string& id, const Json::Value& config) : ALabel(config, "systemd-failed-units", id, "{nr_failed} failed", 1), - hide_on_ok(true), - update_pending(false), - nr_failed_system(0), - nr_failed_user(0), - last_status() { + hide_on_ok_(true), + tooltip_format_( + "System: {system_state}\nUser: {user_state}\nFailed units ({nr_failed}):\n" + "{failed_units_list}"), + tooltip_format_ok_("System: {system_state}\nUser: {user_state}"), + tooltip_unit_format_("{name}: {description}"), + update_pending_(false), + nr_failed_system_(0), + nr_failed_user_(0), + nr_failed_(0), + last_status_() { if (config["hide-on-ok"].isBool()) { - hide_on_ok = config["hide-on-ok"].asBool(); + hide_on_ok_ = config["hide-on-ok"].asBool(); } if (config["format-ok"].isString()) { - format_ok = config["format-ok"].asString(); + format_ok_ = config["format-ok"].asString(); } else { - format_ok = format_; + format_ok_ = format_; + } + + if (config["tooltip-format"].isString()) { + tooltip_format_ = config["tooltip-format"].asString(); + } + if (config["tooltip-format-ok"].isString()) { + tooltip_format_ok_ = config["tooltip-format-ok"].asString(); + } + if (config["tooltip-unit-format"].isString()) { + tooltip_unit_format_ = config["tooltip-unit-format"].asString(); } /* Default to enable both "system" and "user". */ if (!config["system"].isBool() || config["system"].asBool()) { - system_proxy = Gio::DBus::Proxy::create_for_bus_sync( + system_props_proxy_ = Gio::DBus::Proxy::create_for_bus_sync( Gio::DBus::BusType::BUS_TYPE_SYSTEM, "org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.DBus.Properties"); - if (!system_proxy) { + if (!system_props_proxy_) { throw std::runtime_error("Unable to connect to systemwide systemd DBus!"); } - system_proxy->signal_signal().connect(sigc::mem_fun(*this, &SystemdFailedUnits::notify_cb)); + system_props_proxy_->signal_signal().connect( + sigc::mem_fun(*this, &SystemdFailedUnits::notify_cb)); + try { + system_manager_proxy_ = Gio::DBus::Proxy::create_for_bus_sync( + Gio::DBus::BusType::BUS_TYPE_SYSTEM, "org.freedesktop.systemd1", + "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager"); + } catch (const Glib::Error& e) { + spdlog::warn("Unable to connect to systemwide systemd Manager interface: {}", + e.what().c_str()); + } } if (!config["user"].isBool() || config["user"].asBool()) { - user_proxy = Gio::DBus::Proxy::create_for_bus_sync( + user_props_proxy_ = Gio::DBus::Proxy::create_for_bus_sync( Gio::DBus::BusType::BUS_TYPE_SESSION, "org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.DBus.Properties"); - if (!user_proxy) { + if (!user_props_proxy_) { throw std::runtime_error("Unable to connect to user systemd DBus!"); } - user_proxy->signal_signal().connect(sigc::mem_fun(*this, &SystemdFailedUnits::notify_cb)); + user_props_proxy_->signal_signal().connect( + sigc::mem_fun(*this, &SystemdFailedUnits::notify_cb)); + try { + user_manager_proxy_ = Gio::DBus::Proxy::create_for_bus_sync( + Gio::DBus::BusType::BUS_TYPE_SESSION, "org.freedesktop.systemd1", + "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager"); + } catch (const Glib::Error& e) { + spdlog::warn("Unable to connect to user systemd Manager interface: {}", e.what().c_str()); + } } + if (!user_props_proxy_ && !system_props_proxy_) + throw std::runtime_error("Neither system nor user status is requested."); + updateData(); /* Always update for the first time. */ dp.emit(); } -SystemdFailedUnits::~SystemdFailedUnits() { - if (system_proxy) system_proxy.reset(); - if (user_proxy) user_proxy.reset(); -} - auto SystemdFailedUnits::notify_cb(const Glib::ustring& sender_name, const Glib::ustring& signal_name, const Glib::VariantContainerBase& arguments) -> void { - if (signal_name == "PropertiesChanged" && !update_pending) { - update_pending = true; + if (signal_name == "PropertiesChanged" && !update_pending_) { + update_pending_ = true; /* The fail count may fluctuate due to restarting. */ Glib::signal_timeout().connect_once(sigc::mem_fun(*this, &SystemdFailedUnits::updateData), UPDATE_DEBOUNCE_TIME_MS); } } -void SystemdFailedUnits::updateData() { - update_pending = false; +void SystemdFailedUnits::RequestSystemState() { + auto load = [](const char* kind, Glib::RefPtr& proxy) -> std::string { + try { + if (!proxy) return "ignored"; + auto parameters = Glib::VariantContainerBase( + g_variant_new("(ss)", "org.freedesktop.systemd1.Manager", "SystemState")); + Glib::VariantContainerBase data = proxy->call_sync("Get", parameters); + if (data && data.is_of_type(Glib::VariantType("(v)"))) { + Glib::VariantBase variant; + g_variant_get(const_cast(data.gobj()), "(v)", &variant); + if (variant && variant.is_of_type(Glib::VARIANT_TYPE_STRING)) { + return g_variant_get_string(const_cast(variant.gobj()), NULL); + } + } + } catch (Glib::Error& e) { + spdlog::error("Failed to get {} state: {}", kind, e.what().c_str()); + } + return "unknown"; + }; + system_state_ = load("systemwide", system_props_proxy_); + user_state_ = load("user", user_props_proxy_); + + if ((system_state_ == "running" || system_state_ == "ignored") && + (user_state_ == "running" || user_state_ == "ignored")) + overall_state_ = "ok"; + else + overall_state_ = "degraded"; +} + +void SystemdFailedUnits::RequestFailedUnits() { auto load = [](const char* kind, Glib::RefPtr& proxy) -> uint32_t { try { + if (!proxy) return 0; auto parameters = Glib::VariantContainerBase( g_variant_new("(ss)", "org.freedesktop.systemd1.Manager", "NFailedUnits")); Glib::VariantContainerBase data = proxy->call_sync("Get", parameters); if (data && data.is_of_type(Glib::VariantType("(v)"))) { Glib::VariantBase variant; - g_variant_get(data.gobj_copy(), "(v)", &variant); + g_variant_get(const_cast(data.gobj()), "(v)", &variant); if (variant && variant.is_of_type(Glib::VARIANT_TYPE_UINT32)) { - uint32_t value = 0; - g_variant_get(variant.gobj_copy(), "u", &value); - return value; + return g_variant_get_uint32(const_cast(variant.gobj())); } } } catch (Glib::Error& e) { @@ -90,40 +153,153 @@ void SystemdFailedUnits::updateData() { return 0; }; - if (system_proxy) { - nr_failed_system = load("systemwide", system_proxy); + nr_failed_system_ = load("systemwide", system_props_proxy_); + nr_failed_user_ = load("user", user_props_proxy_); + nr_failed_ = nr_failed_system_ + nr_failed_user_; +} + +void SystemdFailedUnits::RequestFailedUnitsList() { + failed_units_.clear(); + if (!tooltipEnabled() || nr_failed_ == 0) { + return; } - if (user_proxy) { - nr_failed_user = load("user", user_proxy); + + if (system_manager_proxy_) { + auto units = LoadFailedUnitsList("systemwide", system_manager_proxy_, "system"); + failed_units_.insert(failed_units_.end(), units.begin(), units.end()); } + if (user_manager_proxy_) { + auto units = LoadFailedUnitsList("user", user_manager_proxy_, "user"); + failed_units_.insert(failed_units_.end(), units.begin(), units.end()); + } +} + +auto SystemdFailedUnits::LoadFailedUnitsList(const char* kind, + Glib::RefPtr& proxy, + const std::string& scope) -> std::vector { + // org.freedesktop.systemd1.Manager.ListUnits returns + // (name, description, load_state, active_state, sub_state, followed, unit_path, job_id, + // job_type, job_path). + using UnitRow = std::tuple; + using ListUnitsReply = Glib::Variant>>; + + std::vector units; + if (!proxy) { + return units; + } + + try { + auto data = proxy->call_sync("ListUnits"); + if (!data) return units; + if (!data.is_of_type(ListUnitsReply::variant_type())) { + spdlog::warn("Unexpected DBus signature for ListUnits: {}", data.get_type_string()); + return units; + } + + auto [rows] = Glib::VariantBase::cast_dynamic(data).get(); + for (const auto& row : rows) { + const auto& name = std::get<0>(row); + const auto& description = std::get<1>(row); + const auto& load_state = std::get<2>(row); + const auto& active_state = std::get<3>(row); + const auto& sub_state = std::get<4>(row); + if (active_state == "failed" || sub_state == "failed") { + units.push_back({name, description, load_state, active_state, sub_state, scope}); + } + } + } catch (const Glib::Error& e) { + spdlog::error("Failed to list {} units: {}", kind, e.what().c_str()); + } + + return units; +} + +std::string SystemdFailedUnits::BuildTooltipFailedList() const { + if (failed_units_.empty()) { + return ""; + } + + std::string list; + list.reserve(failed_units_.size() * 16); + bool first = true; + for (const auto& unit : failed_units_) { + try { + auto line = fmt::format( + fmt::runtime(tooltip_unit_format_), + fmt::arg("name", Glib::Markup::escape_text(unit.name).raw()), + fmt::arg("description", Glib::Markup::escape_text(unit.description).raw()), + fmt::arg("load_state", unit.load_state), fmt::arg("active_state", unit.active_state), + fmt::arg("sub_state", unit.sub_state), fmt::arg("scope", unit.scope)); + if (!first) { + list += "\n"; + } + first = false; + list += "- "; + list += line; + } catch (const std::exception& e) { + spdlog::warn("Failed to format tooltip for unit {}: {}", unit.name, e.what()); + } + } + + return list; +} + +void SystemdFailedUnits::updateData() { + update_pending_ = false; + + RequestSystemState(); + if (overall_state_ == "degraded") { + RequestFailedUnits(); + RequestFailedUnitsList(); + } else { + nr_failed_system_ = nr_failed_user_ = nr_failed_ = 0; + failed_units_.clear(); + } + dp.emit(); } auto SystemdFailedUnits::update() -> void { - uint32_t nr_failed = nr_failed_system + nr_failed_user; - // Hide if needed. - if (nr_failed == 0 && hide_on_ok) { + if (overall_state_ == "ok" && hide_on_ok_) { event_box_.set_visible(false); + last_status_ = overall_state_; return; } - if (!event_box_.get_visible()) { - event_box_.set_visible(true); - } + + event_box_.set_visible(true); // Set state class. - const std::string status = nr_failed == 0 ? "ok" : "degraded"; - if (!last_status.empty() && label_.get_style_context()->has_class(last_status)) { - label_.get_style_context()->remove_class(last_status); + if (!last_status_.empty() && label_.get_style_context()->has_class(last_status_)) { + label_.get_style_context()->remove_class(last_status_); } - if (!label_.get_style_context()->has_class(status)) { - label_.get_style_context()->add_class(status); + if (!label_.get_style_context()->has_class(overall_state_)) { + label_.get_style_context()->add_class(overall_state_); } - last_status = status; + + last_status_ = overall_state_; label_.set_markup(fmt::format( - fmt::runtime(nr_failed == 0 ? format_ok : format_), fmt::arg("nr_failed", nr_failed), - fmt::arg("nr_failed_system", nr_failed_system), fmt::arg("nr_failed_user", nr_failed_user))); + fmt::runtime(nr_failed_ == 0 ? format_ok_ : format_), fmt::arg("nr_failed", nr_failed_), + fmt::arg("nr_failed_system", nr_failed_system_), fmt::arg("nr_failed_user", nr_failed_user_), + fmt::arg("system_state", system_state_), fmt::arg("user_state", user_state_), + fmt::arg("overall_state", overall_state_))); + if (tooltipEnabled()) { + std::string failed_list = BuildTooltipFailedList(); + auto tooltip_template = overall_state_ == "ok" ? tooltip_format_ok_ : tooltip_format_; + if (!tooltip_template.empty()) { + label_.set_tooltip_markup(fmt::format( + fmt::runtime(tooltip_template), fmt::arg("nr_failed", nr_failed_), + fmt::arg("nr_failed_system", nr_failed_system_), + fmt::arg("nr_failed_user", nr_failed_user_), fmt::arg("system_state", system_state_), + fmt::arg("user_state", user_state_), fmt::arg("overall_state", overall_state_), + fmt::arg("failed_units_list", failed_list))); + } else { + label_.set_tooltip_text(""); + } + } ALabel::update(); } diff --git a/src/modules/temperature.cpp b/src/modules/temperature.cpp index a3e1c1ee..9aac8d99 100644 --- a/src/modules/temperature.cpp +++ b/src/modules/temperature.cpp @@ -20,6 +20,24 @@ waybar::modules::Temperature::Temperature(const std::string& id, const Json::Val if (check_set_path(item.asString())) break; }; + auto find_hwmon_by_name = [](const std::string& name) -> std::optional { + for (const auto& entry : std::filesystem::directory_iterator("/sys/class/hwmon")) { + std::ifstream f(entry.path() / "name"); + std::string hwname; + if (f >> hwname && hwname == name) { + return entry.path(); + } + } + return std::nullopt; + }; + + // ensure either hwmon-name OR old paths are used, not both + if (config_["hwmon-name"].isString() && + (!config_["hwmon-path"].isNull() || !config_["hwmon-path-abs"].isNull())) { + throw std::runtime_error( + "hwmon-name cannot be used together with hwmon-path or hwmon-path-abs"); + } + // if hwmon_path is an array, loop to find first valid item traverseAsArray(config_["hwmon-path"], [this](const std::string& path) { if (!std::filesystem::exists(path)) return false; @@ -40,12 +58,26 @@ waybar::modules::Temperature::Temperature(const std::string& id, const Json::Val }); } + if (file_path_.empty() && config_["hwmon-name"].isString()) { + if (!config_["input-filename"].isString()) { + throw std::runtime_error("hwmon-name requires input-filename to be set"); + } + + auto hwmon = find_hwmon_by_name(config_["hwmon-name"].asString()); + + if (!hwmon) { + throw std::runtime_error("hwmon-name '" + config_["hwmon-name"].asString() + "' not found"); + } + + file_path_ = hwmon->string() + "/" + config_["input-filename"].asString(); + } + if (file_path_.empty()) { auto zone = config_["thermal-zone"].isInt() ? config_["thermal-zone"].asInt() : 0; file_path_ = fmt::format("/sys/class/thermal/thermal_zone{}/temp", zone); } - // check if file_path_ can be used to retrive the temperature + // check if file_path_ can be used to retrieve the temperature std::ifstream temp(file_path_); if (!temp.is_open()) { throw std::runtime_error("Can't open " + file_path_); @@ -74,12 +106,14 @@ auto waybar::modules::Temperature::update() -> void { if (critical) { format = config_["format-critical"].isString() ? config_["format-critical"].asString() : format; label_.get_style_context()->add_class("critical"); - } else if (warning) { - format = config_["format-warning"].isString() ? config_["format-warning"].asString() : format; - label_.get_style_context()->add_class("warning"); } else { label_.get_style_context()->remove_class("critical"); - label_.get_style_context()->remove_class("warning"); + if (warning) { + format = config_["format-warning"].isString() ? config_["format-warning"].asString() : format; + label_.get_style_context()->add_class("warning"); + } else { + label_.get_style_context()->remove_class("warning"); + } } if (format.empty()) { @@ -99,7 +133,7 @@ auto waybar::modules::Temperature::update() -> void { if (config_["tooltip-format"].isString()) { tooltip_format = config_["tooltip-format"].asString(); } - label_.set_tooltip_text(fmt::format( + label_.set_tooltip_markup(fmt::format( fmt::runtime(tooltip_format), fmt::arg("temperatureC", temperature_c), fmt::arg("temperatureF", temperature_f), fmt::arg("temperatureK", temperature_k))); } @@ -153,3 +187,7 @@ bool waybar::modules::Temperature::isCritical(uint16_t temperature_c) { return config_["critical-threshold"].isInt() && temperature_c >= config_["critical-threshold"].asInt(); } + +void waybar::modules::Temperature::suspend() { thread_.pause(); } + +void waybar::modules::Temperature::resume() { thread_.resume(); } diff --git a/src/modules/upower.cpp b/src/modules/upower.cpp index 4b832b7e..d260ba83 100644 --- a/src/modules/upower.cpp +++ b/src/modules/upower.cpp @@ -6,11 +6,10 @@ namespace waybar::modules { -UPower::UPower(const std::string &id, const Json::Value &config) +UPower::UPower(const std::string& id, const Json::Value& config) : AIconLabel(config, "upower", id, "{percentage}", 0, true, true, true), sleeping_{false} { box_.set_name(name_); box_.set_spacing(0); - box_.set_has_tooltip(AModule::tooltipEnabled()); // Tooltip box contentBox_.set_orientation((box_.get_orientation() == Gtk::ORIENTATION_HORIZONTAL) ? Gtk::ORIENTATION_VERTICAL @@ -60,18 +59,23 @@ UPower::UPower(const std::string &id, const Json::Value &config) sigc::mem_fun(*this, &UPower::getConn_cb)); // Make UPower client - GError **gErr = NULL; - upClient_ = up_client_new_full(NULL, gErr); - if (upClient_ == NULL) - spdlog::error("Upower. UPower client connection error. {}", (*gErr)->message); + GError* gErr = NULL; + upClient_ = up_client_new_full(NULL, &gErr); + if (upClient_ == NULL) { + spdlog::error("Upower. UPower client connection error. {}", + gErr ? gErr->message : "unknown error"); + if (gErr) g_error_free(gErr); + } // Subscribe UPower events g_signal_connect(upClient_, "device-added", G_CALLBACK(deviceAdded_cb), this); g_signal_connect(upClient_, "device-removed", G_CALLBACK(deviceRemoved_cb), this); // Subscribe tooltip query events - box_.set_has_tooltip(); - box_.signal_query_tooltip().connect(sigc::mem_fun(*this, &UPower::queryTooltipCb), false); + box_.set_has_tooltip(AModule::tooltipEnabled()); + if (AModule::tooltipEnabled()) { + box_.signal_query_tooltip().connect(sigc::mem_fun(*this, &UPower::queryTooltipCb), false); + } resetDevices(); setDisplayDevice(); @@ -91,7 +95,7 @@ UPower::~UPower() { removeDevices(); } -static const std::string getDeviceStatus(UpDeviceState &state) { +static std::string_view getDeviceStatus(UpDeviceState& state) { switch (state) { case UP_DEVICE_STATE_CHARGING: case UP_DEVICE_STATE_PENDING_CHARGE: @@ -108,7 +112,7 @@ static const std::string getDeviceStatus(UpDeviceState &state) { } } -static const std::string getDeviceIcon(UpDeviceKind &kind) { +static std::string_view getDeviceIcon(UpDeviceKind& kind) { switch (kind) { case UP_DEVICE_KIND_LINE_POWER: return "ac-adapter-symbolic"; @@ -208,7 +212,8 @@ auto UPower::update() -> void { // Remove last status if it exists if (!lastStatus_.empty() && box_.get_style_context()->has_class(lastStatus_)) box_.get_style_context()->remove_class(lastStatus_); - if (!box_.get_style_context()->has_class(status)) box_.get_style_context()->add_class(status); + if (!box_.get_style_context()->has_class(std::string(status))) + box_.get_style_context()->add_class(std::string(status)); lastStatus_ = status; if (devices_.size() == 0 && !upDeviceValid && hideIfEmpty_) { @@ -221,7 +226,7 @@ auto UPower::update() -> void { label_.set_markup(getText(upDevice_, format_)); // Set icon if (upDevice_.icon_name == NULL || !gtkTheme_->has_icon(upDevice_.icon_name)) - upDevice_.icon_name = (char *)NO_BATTERY.c_str(); + upDevice_.icon_name = (char*)NO_BATTERY.c_str(); image_.set_from_icon_name(upDevice_.icon_name, Gtk::ICON_SIZE_INVALID); box_.show(); @@ -230,7 +235,7 @@ auto UPower::update() -> void { ALabel::update(); } -void UPower::getConn_cb(Glib::RefPtr &result) { +void UPower::getConn_cb(Glib::RefPtr& result) { try { conn_ = Gio::DBus::Connection::get_finish(result); // Subscribe DBUs events @@ -238,26 +243,26 @@ void UPower::getConn_cb(Glib::RefPtr &result) { "org.freedesktop.login1", "org.freedesktop.login1.Manager", "PrepareForSleep", "/org/freedesktop/login1"); - } catch (const Glib::Error &e) { + } catch (const Glib::Error& e) { spdlog::error("Upower. DBus connection error. {}", e.what().c_str()); } } -void UPower::onAppear(const Glib::RefPtr &conn, const Glib::ustring &name, - const Glib::ustring &name_owner) { +void UPower::onAppear(const Glib::RefPtr& conn, const Glib::ustring& name, + const Glib::ustring& name_owner) { upRunning_ = true; } -void UPower::onVanished(const Glib::RefPtr &conn, - const Glib::ustring &name) { +void UPower::onVanished(const Glib::RefPtr& conn, + const Glib::ustring& name) { upRunning_ = false; } -void UPower::prepareForSleep_cb(const Glib::RefPtr &connection, - const Glib::ustring &sender_name, const Glib::ustring &object_path, - const Glib::ustring &interface_name, - const Glib::ustring &signal_name, - const Glib::VariantContainerBase ¶meters) { +void UPower::prepareForSleep_cb(const Glib::RefPtr& connection, + const Glib::ustring& sender_name, const Glib::ustring& object_path, + const Glib::ustring& interface_name, + const Glib::ustring& signal_name, + const Glib::VariantContainerBase& parameters) { if (parameters.is_of_type(Glib::VariantType("(b)"))) { Glib::Variant sleeping; parameters.get_child(sleeping, 0); @@ -272,33 +277,33 @@ void UPower::prepareForSleep_cb(const Glib::RefPtr &conne } } -void UPower::deviceAdded_cb(UpClient *client, UpDevice *device, gpointer data) { - UPower *up{static_cast(data)}; +void UPower::deviceAdded_cb(UpClient* client, UpDevice* device, gpointer data) { + UPower* up{static_cast(data)}; up->addDevice(device); up->setDisplayDevice(); // Update the widget up->dp.emit(); } -void UPower::deviceRemoved_cb(UpClient *client, const gchar *objectPath, gpointer data) { - UPower *up{static_cast(data)}; +void UPower::deviceRemoved_cb(UpClient* client, const gchar* objectPath, gpointer data) { + UPower* up{static_cast(data)}; up->removeDevice(objectPath); up->setDisplayDevice(); // Update the widget up->dp.emit(); } -void UPower::deviceNotify_cb(UpDevice *device, GParamSpec *pspec, gpointer data) { - UPower *up{static_cast(data)}; +void UPower::deviceNotify_cb(UpDevice* device, GParamSpec* pspec, gpointer data) { + UPower* up{static_cast(data)}; // Update the widget up->dp.emit(); } -void UPower::addDevice(UpDevice *device) { +void UPower::addDevice(UpDevice* device) { std::lock_guard guard{mutex_}; if (G_IS_OBJECT(device)) { - const gchar *objectPath{up_device_get_object_path(device)}; + const gchar* objectPath{up_device_get_object_path(device)}; // Due to the device getting cleared after this event is fired, we // create a new object pointing to its objectPath @@ -321,7 +326,7 @@ void UPower::addDevice(UpDevice *device) { } } -void UPower::removeDevice(const gchar *objectPath) { +void UPower::removeDevice(const gchar* objectPath) { std::lock_guard guard{mutex_}; if (devices_.find(objectPath) != devices_.cend()) { auto upDevice{devices_[objectPath]}; @@ -347,10 +352,10 @@ void UPower::resetDevices() { removeDevices(); // Adds all devices - GPtrArray *newDevices = up_client_get_devices2(upClient_); + GPtrArray* newDevices = up_client_get_devices2(upClient_); if (newDevices != NULL) for (guint i{0}; i < newDevices->len; ++i) { - UpDevice *device{(UpDevice *)g_ptr_array_index(newDevices, i)}; + UpDevice* device{(UpDevice*)g_ptr_array_index(newDevices, i)}; if (device && G_IS_OBJECT(device)) addDevice(device); } } @@ -371,8 +376,8 @@ void UPower::setDisplayDevice() { up_client_get_devices2(upClient_), [](gpointer data, gpointer user_data) { upDevice_output upDevice; - auto thisPtr{static_cast(user_data)}; - upDevice.upDevice = static_cast(data); + auto thisPtr{static_cast(user_data)}; + upDevice.upDevice = static_cast(data); thisPtr->getUpDeviceInfo(upDevice); upDevice_output displayDevice{NULL}; if (!thisPtr->nativePath_.empty()) { @@ -398,7 +403,7 @@ void UPower::setDisplayDevice() { g_signal_connect(upDevice_.upDevice, "notify", G_CALLBACK(deviceNotify_cb), this); } -void UPower::getUpDeviceInfo(upDevice_output &upDevice_) { +void UPower::getUpDeviceInfo(upDevice_output& upDevice_) { if (upDevice_.upDevice != NULL && G_IS_OBJECT(upDevice_.upDevice)) { g_object_get(upDevice_.upDevice, "kind", &upDevice_.kind, "state", &upDevice_.state, "percentage", &upDevice_.percentage, "icon-name", &upDevice_.icon_name, @@ -415,7 +420,7 @@ native_path: \"{7}\". model: \"{8}\"", } } -const Glib::ustring UPower::getText(const upDevice_output &upDevice_, const std::string &format) { +const Glib::ustring UPower::getText(const upDevice_output& upDevice_, const std::string& format) { Glib::ustring ret{""}; if (upDevice_.upDevice != NULL) { std::string timeStr{""}; @@ -444,11 +449,11 @@ const Glib::ustring UPower::getText(const upDevice_output &upDevice_, const std: } bool UPower::queryTooltipCb(int x, int y, bool keyboard_tooltip, - const Glib::RefPtr &tooltip) { + const Glib::RefPtr& tooltip) { std::lock_guard guard{mutex_}; // Clear content box - contentBox_.forall([this](Gtk::Widget &wg) { contentBox_.remove(wg); }); + contentBox_.forall([this](Gtk::Widget& wg) { contentBox_.remove(wg); }); // Fill content box with the content for (auto pairDev : devices_) { @@ -458,33 +463,33 @@ bool UPower::queryTooltipCb(int x, int y, bool keyboard_tooltip, if (pairDev.second.kind != UpDeviceKind::UP_DEVICE_KIND_UNKNOWN && pairDev.second.kind != UpDeviceKind::UP_DEVICE_KIND_LINE_POWER) { // Make box record - Gtk::Box *boxRec{new Gtk::Box{box_.get_orientation(), tooltip_spacing_}}; + Gtk::Box* boxRec{new Gtk::Box{box_.get_orientation(), tooltip_spacing_}}; contentBox_.add(*boxRec); - Gtk::Box *boxDev{new Gtk::Box{box_.get_orientation()}}; - Gtk::Box *boxUsr{new Gtk::Box{box_.get_orientation()}}; + Gtk::Box* boxDev{new Gtk::Box{box_.get_orientation()}}; + Gtk::Box* boxUsr{new Gtk::Box{box_.get_orientation()}}; boxRec->add(*boxDev); boxRec->add(*boxUsr); // Construct device box // Set icon from kind std::string iconNameDev{getDeviceIcon(pairDev.second.kind)}; - if (!gtkTheme_->has_icon(iconNameDev)) iconNameDev = (char *)NO_BATTERY.c_str(); - Gtk::Image *iconDev{new Gtk::Image{}}; + if (!gtkTheme_->has_icon(iconNameDev)) iconNameDev = (char*)NO_BATTERY.c_str(); + Gtk::Image* iconDev{new Gtk::Image{}}; iconDev->set_from_icon_name(iconNameDev, Gtk::ICON_SIZE_INVALID); iconDev->set_pixel_size(iconSize_); boxDev->add(*iconDev); // Set label from model - Gtk::Label *labelDev{new Gtk::Label{pairDev.second.model}}; + Gtk::Label* labelDev{new Gtk::Label{pairDev.second.model}}; boxDev->add(*labelDev); // Construct user box // Set icon from icon state if (pairDev.second.icon_name == NULL || !gtkTheme_->has_icon(pairDev.second.icon_name)) - pairDev.second.icon_name = (char *)NO_BATTERY.c_str(); - Gtk::Image *iconTooltip{new Gtk::Image{}}; + pairDev.second.icon_name = (char*)NO_BATTERY.c_str(); + Gtk::Image* iconTooltip{new Gtk::Image{}}; iconTooltip->set_from_icon_name(pairDev.second.icon_name, Gtk::ICON_SIZE_INVALID); iconTooltip->set_pixel_size(iconSize_); boxUsr->add(*iconTooltip); // Set markup text - Gtk::Label *labelTooltip{new Gtk::Label{}}; + Gtk::Label* labelTooltip{new Gtk::Label{}}; labelTooltip->set_markup(getText(pairDev.second, tooltipFormat_)); boxUsr->add(*labelTooltip); } diff --git a/src/modules/user.cpp b/src/modules/user.cpp index 418fc585..3ca5e431 100644 --- a/src/modules/user.cpp +++ b/src/modules/user.cpp @@ -62,7 +62,13 @@ long User::uptime_as_seconds() { #if HAVE_CPU_BSD struct timespec s_info; - if (0 == clock_gettime(CLOCK_UPTIME_PRECISE, &s_info)) { + int flags = 0; +#ifndef __OpenBSD__ + flags = CLOCK_UPTIME_PRECISE; +#else + flags = CLOCK_UPTIME; +#endif + if (0 == clock_gettime(flags, &s_info)) { uptime = s_info.tv_sec; } #endif diff --git a/src/modules/wayfire/backend.cpp b/src/modules/wayfire/backend.cpp new file mode 100644 index 00000000..037a61e1 --- /dev/null +++ b/src/modules/wayfire/backend.cpp @@ -0,0 +1,462 @@ +#include "modules/wayfire/backend.hpp" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace waybar::modules::wayfire { + +std::weak_ptr IPC::instance; + +// C++23: std::byteswap +inline auto byteswap(uint32_t x) -> uint32_t { + return (x & 0xff000000) >> 24 | (x & 0x00ff0000) >> 8 | (x & 0x0000ff00) << 8 | + (x & 0x000000ff) << 24; +} + +auto pack_and_write(Sock& sock, std::string&& buf) -> void { + uint32_t len = buf.size(); + if constexpr (std::endian::native != std::endian::little) len = byteswap(len); + (void)write(sock, &len, 4); + (void)write(sock, buf.data(), buf.size()); +} + +auto read_exact(Sock& sock, size_t n) -> std::string { + auto buf = std::string(n, 0); + for (size_t i = 0; i < n;) { + auto r = read(sock, &buf[i], n - i); + if (r <= 0) { + throw std::runtime_error("Wayfire IPC: read failed"); + } + i += static_cast(r); + } + return buf; +} + +// https://github.com/WayfireWM/pywayfire/blob/69b7c21/wayfire/ipc.py#L438 +inline auto is_mapped_toplevel_view(const Json::Value& view) -> bool { + return view["mapped"].asBool() && view["role"] != "desktop-environment" && + view["pid"].asInt() != -1; +} + +auto State::Wset::count_ws(const Json::Value& pos) -> Workspace& { + auto x = pos["x"].asInt(); + auto y = pos["y"].asInt(); + return wss.at(ws_w * y + x); +} + +auto State::Wset::locate_ws(const Json::Value& geo) -> Workspace& { + return const_cast(std::as_const(*this).locate_ws(geo)); +} + +auto State::Wset::locate_ws(const Json::Value& geo) const -> const Workspace& { + if (!output.has_value()) { + throw std::runtime_error("Wayfire IPC: wset has no output assigned"); + } + const auto& out = output.value().get(); + auto [qx, rx] = std::div(geo["x"].asInt(), out.w); + auto [qy, ry] = std::div(geo["y"].asInt(), out.h); + auto x = std::max(0, (int)ws_x + qx - int{rx < 0}); + auto y = std::max(0, (int)ws_y + qy - int{ry < 0}); + return wss.at(ws_w * y + x); +} + +auto State::update_view(const Json::Value& view) -> void { + auto id = view["id"].asUInt(); + + // erase old view information + if (views.contains(id)) { + auto& old_view = views.at(id); + auto& ws = wsets.at(old_view["wset-index"].asUInt()).locate_ws(old_view["geometry"]); + ws.num_views--; + if (old_view["sticky"].asBool()) ws.num_sticky_views--; + views.erase(id); + } + + // insert or assign new view information + if (is_mapped_toplevel_view(view)) { + try { + // view["wset-index"] could be messed up + auto& ws = wsets.at(view["wset-index"].asUInt()).locate_ws(view["geometry"]); + ws.num_views++; + if (view["sticky"].asBool()) ws.num_sticky_views++; + views.emplace(id, view); + } catch (const std::exception&) { + } + } +} + +auto IPC::get_instance() -> std::shared_ptr { + auto p = instance.lock(); + if (!p) { + instance = p = std::shared_ptr(new IPC); + p->start(); + } + return p; +} + +auto IPC::connect() -> Sock { + auto* path = std::getenv("WAYFIRE_SOCKET"); + if (path == nullptr) { + throw std::runtime_error{"Wayfire IPC: ipc not available"}; + } + + util::ScopedFd sock(socket(AF_UNIX, SOCK_STREAM, 0)); + if (sock == -1) { + throw std::runtime_error{"Wayfire IPC: socket() failed"}; + } + + auto addr = sockaddr_un{.sun_family = AF_UNIX}; + std::strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1); + addr.sun_path[sizeof(addr.sun_path) - 1] = 0; + + if (::connect(sock, (const sockaddr*)&addr, sizeof(addr)) == -1) { + throw std::runtime_error{"Wayfire IPC: connect() failed"}; + } + + return sock; +} + +auto IPC::receive(Sock& sock) -> Json::Value { + auto len_buf = read_exact(sock, 4); + uint32_t len; + std::memcpy(&len, len_buf.data(), sizeof(len)); + if constexpr (std::endian::native != std::endian::little) len = byteswap(len); + auto buf = read_exact(sock, len); + + Json::Value json; + std::string err; + auto* reader = reader_builder.newCharReader(); + if (!reader->parse(&*buf.begin(), &*buf.end(), &json, &err)) { + throw std::runtime_error{"Wayfire IPC: parse json failed: " + err}; + } + return json; +} + +auto IPC::send(const std::string& method, Json::Value&& data) -> Json::Value { + spdlog::debug("Wayfire IPC: send method \"{}\"", method); + auto sock = connect(); + + Json::Value json; + json["method"] = method; + json["data"] = std::move(data); + + pack_and_write(sock, Json::writeString(writer_builder, json)); + auto res = receive(sock); + root_event_handler(method, res); + return res; +} + +auto IPC::start() -> void { + spdlog::info("Wayfire IPC: starting"); + + // init state + send("window-rules/list-outputs", {}); + send("window-rules/list-wsets", {}); + send("window-rules/list-views", {}); + send("window-rules/get-focused-view", {}); + send("window-rules/get-focused-output", {}); + + std::thread([self = shared_from_this()] { + auto sock = connect(); + + { + Json::Value json; + json["method"] = "window-rules/events/watch"; + + pack_and_write(sock, Json::writeString(self->writer_builder, json)); + if (self->receive(sock)["result"] != "ok") { + spdlog::error( + "Wayfire IPC: method \"window-rules/events/watch\"" + " have failed"); + return; + } + } + + while (auto json = self->receive(sock)) { + auto ev = json["event"].asString(); + spdlog::debug("Wayfire IPC: received event \"{}\"", ev); + self->root_event_handler(ev, json); + } + }).detach(); +} + +auto IPC::register_handler(const std::string& event, const EventHandler& handler) -> void { + auto _ = std::lock_guard{handlers_mutex}; + handlers.emplace_back(event, handler); +} + +auto IPC::unregister_handler(EventHandler& handler) -> void { + auto _ = std::lock_guard{handlers_mutex}; + handlers.remove_if([&](auto& e) { return &e.second.get() == &handler; }); +} + +auto IPC::root_event_handler(const std::string& event, const Json::Value& data) -> void { + bool new_output_detected; + { + auto _ = lock_state(); + update_state_handler(event, data); + new_output_detected = state.new_output_detected; + state.new_output_detected = false; + } + if (new_output_detected) { + send("window-rules/list-outputs", {}); + send("window-rules/list-wsets", {}); + } + { + auto _ = std::lock_guard{handlers_mutex}; + for (const auto& [_event, handler] : handlers) + if (_event == event) handler(event); + } +} + +auto IPC::update_state_handler(const std::string& event, const Json::Value& data) -> void { + // IPC events + // https://github.com/WayfireWM/wayfire/blob/053b222/plugins/ipc-rules/ipc-events.hpp#L108-L125 + /* + [x] view-mapped + [x] view-unmapped + [-] view-set-output // for detect new output + [ ] view-geometry-changed // -> view-workspace-changed + [x] view-wset-changed + [x] view-focused + [x] view-title-changed + [x] view-app-id-changed + [x] plugin-activation-state-changed + [x] output-gain-focus + + [ ] view-tiled + [ ] view-minimized + [ ] view-fullscreened + [x] view-sticky + [x] view-workspace-changed + [x] output-wset-changed + [x] wset-workspace-changed + */ + + if (event == "view-mapped") { + // data: { event, view } + state.update_view(data["view"]); + return; + } + + if (event == "view-unmapped") { + // data: { event, view } + try { + // data["view"]["wset-index"] could be messed up + state.update_view(data["view"]); + state.maybe_empty_focus_wset_idx = data["view"]["wset-index"].asUInt(); + } catch (const std::exception&) { + } + return; + } + + if (event == "view-set-output") { + // data: { event, output?, view } + // new output event + if (!state.outputs.contains(data["view"]["output-name"].asString())) { + state.new_output_detected = true; + } + return; + } + + if (event == "view-wset-changed") { + // data: { event, old-wset: wset, new-wset: wset, view } + state.maybe_empty_focus_wset_idx = data["old-wset"]["index"].asUInt(); + state.update_view(data["view"]); + return; + } + + if (event == "view-focused") { + // data: { event, view? } + if (const auto& view = data["view"]) { + try { + // view["wset-index"] could be messed up + auto& wset = state.wsets.at(view["wset-index"].asUInt()); + wset.focused_view_id = view["id"].asUInt(); + } catch (const std::exception&) { + } + } else { + // focused to null + if (state.wsets.contains(state.maybe_empty_focus_wset_idx)) + state.wsets.at(state.maybe_empty_focus_wset_idx).focused_view_id = {}; + } + return; + } + + if (event == "view-title-changed" || event == "view-app-id-changed" || event == "view-sticky") { + // data: { event, view } + state.update_view(data["view"]); + return; + } + + if (event == "plugin-activation-state-changed") { + // data: { event, plugin: name, state: bool, output: id, output-data: output } + auto plugin = data["plugin"].asString(); + auto plugin_state = data["state"].asBool(); + + if (plugin == "vswitch") { + state.vswitching = plugin_state; + if (plugin_state) { + state.maybe_empty_focus_wset_idx = data["output-data"]["wset-index"].asUInt(); + } + } + + return; + } + + if (event == "output-gain-focus") { + // data: { event, output } + state.focused_output_name = data["output"]["name"].asString(); + return; + } + + if (event == "view-workspace-changed") { + // data: { event, from: point, to: point, view } + if (state.vswitching) { + if (state.vswitch_sticky_view_id == 0) { + auto& wset = state.wsets.at(data["view"]["wset-index"].asUInt()); + auto& old_ws = wset.locate_ws(state.views.at(data["view"]["id"].asUInt())["geometry"]); + auto& new_ws = wset.count_ws(data["to"]); + old_ws.num_views--; + new_ws.num_views++; + if (data["view"]["sticky"].asBool()) { + old_ws.num_sticky_views--; + new_ws.num_sticky_views++; + } + state.update_view(data["view"]); + state.vswitch_sticky_view_id = data["view"]["id"].asUInt(); + } else { + state.vswitch_sticky_view_id = {}; + } + return; + } + state.update_view(data["view"]); + return; + } + + if (event == "output-wset-changed") { + // data: { event, new-wset: wset.name, output: id, new-wset-data: wset, output-data: output } + try { + auto& output = state.outputs.at(data["output-data"]["name"].asString()); + auto wset_idx = data["new-wset-data"]["index"].asUInt(); + state.wsets.at(wset_idx).output = output; + output.wset_idx = wset_idx; + } catch (const std::exception&) { + } + return; + } + + if (event == "wset-workspace-changed") { + // data: { event, previous-workspace: point, new-workspace: point, + // output: id, wset: wset.name, output-data: output, wset-data: wset } + auto wset_idx = data["wset-data"]["index"].asUInt(); + auto& wset = state.wsets.at(wset_idx); + wset.ws_x = data["new-workspace"]["x"].asUInt(); + wset.ws_y = data["new-workspace"]["y"].asUInt(); + + // correct existing views geometry + auto& out = wset.output.value().get(); + auto dx = (int)out.w * ((int)wset.ws_x - data["previous-workspace"]["x"].asInt()); + auto dy = (int)out.h * ((int)wset.ws_y - data["previous-workspace"]["y"].asInt()); + for (auto& [_, view] : state.views) { + if (view["wset-index"].asUInt() == wset_idx && + view["id"].asUInt() != state.vswitch_sticky_view_id) { + view["geometry"]["x"] = view["geometry"]["x"].asInt() - dx; + view["geometry"]["y"] = view["geometry"]["y"].asInt() - dy; + } + } + return; + } + + // IPC responses + // https://github.com/WayfireWM/wayfire/blob/053b222/plugins/ipc-rules/ipc-rules.cpp#L27-L37 + + if (event == "window-rules/list-views") { + // data: [ view ] + state.views.clear(); + for (auto& [_, wset] : state.wsets) std::ranges::fill(wset.wss, State::Workspace{}); + for (const auto& view : data | std::views::filter(is_mapped_toplevel_view)) { + state.update_view(view); + } + return; + } + + if (event == "window-rules/list-outputs") { + // data: [ output ] + state.outputs.clear(); + for (const auto& output_data : data) { + state.outputs.emplace(output_data["name"].asString(), + State::Output{ + .id = output_data["id"].asUInt(), + .w = output_data["geometry"]["width"].asUInt(), + .h = output_data["geometry"]["height"].asUInt(), + .wset_idx = output_data["wset-index"].asUInt(), + }); + } + return; + } + + if (event == "window-rules/list-wsets") { + // data: [ wset ] + std::unordered_map wsets; + for (const auto& wset_data : data) { + auto wset_idx = wset_data["index"].asUInt(); + + auto output_name = wset_data["output-name"].asString(); + auto output = state.outputs.contains(output_name) + ? std::optional{std::ref(state.outputs.at(output_name))} + : std::nullopt; + + const auto& ws_data = wset_data["workspace"]; + auto ws_w = ws_data["grid_width"].asUInt(); + auto ws_h = ws_data["grid_height"].asUInt(); + + wsets.emplace(wset_idx, State::Wset{ + .output = output, + .wss = std::vector(ws_w * ws_h), + .ws_w = ws_w, + .ws_h = ws_h, + .ws_x = ws_data["x"].asUInt(), + .ws_y = ws_data["y"].asUInt(), + }); + + if (state.wsets.contains(wset_idx)) { + auto& old_wset = state.wsets.at(wset_idx); + auto& new_wset = wsets.at(wset_idx); + new_wset.wss = std::move(old_wset.wss); + new_wset.focused_view_id = old_wset.focused_view_id; + } + } + state.wsets = std::move(wsets); + return; + } + + if (event == "window-rules/get-focused-view") { + // data: { ok, info: view? } + if (const auto& view = data["info"]) { + auto& wset = state.wsets.at(view["wset-index"].asUInt()); + wset.focused_view_id = view["id"].asUInt(); + state.update_view(view); + } + return; + } + + if (event == "window-rules/get-focused-output") { + // data: { ok, info: output } + state.focused_output_name = data["info"]["name"].asString(); + return; + } +} + +} // namespace waybar::modules::wayfire diff --git a/src/modules/wayfire/window.cpp b/src/modules/wayfire/window.cpp new file mode 100644 index 00000000..8634f090 --- /dev/null +++ b/src/modules/wayfire/window.cpp @@ -0,0 +1,81 @@ +#include "modules/wayfire/window.hpp" + +#include +#include +#include + +#include "util/rewrite_string.hpp" +#include "util/sanitize_str.hpp" + +namespace waybar::modules::wayfire { + +Window::Window(const std::string& id, const Bar& bar, const Json::Value& config) + : AAppIconLabel(config, "window", id, "{title}", 0, true), + ipc{IPC::get_instance()}, + handler{[this](const auto&) { dp.emit(); }}, + bar_{bar} { + ipc->register_handler("view-unmapped", handler); + ipc->register_handler("view-focused", handler); + ipc->register_handler("view-title-changed", handler); + ipc->register_handler("view-app-id-changed", handler); + + ipc->register_handler("window-rules/get-focused-view", handler); + + dp.emit(); +} + +Window::~Window() { ipc->unregister_handler(handler); } + +auto Window::update() -> void { + update_icon_label(); + AAppIconLabel::update(); +} + +auto Window::update_icon_label() -> void { + auto _ = ipc->lock_state(); + + auto out_it = ipc->get_outputs().find(bar_.output->name); + if (out_it == ipc->get_outputs().end()) return; + const auto& output = out_it->second; + auto wset_it = ipc->get_wsets().find(output.wset_idx); + if (wset_it == ipc->get_wsets().end()) return; + const auto& wset = wset_it->second; + const auto& views = ipc->get_views(); + auto ctx = bar_.window.get_style_context(); + + if (views.contains(wset.focused_view_id)) { + const auto& view = views.at(wset.focused_view_id); + auto title = view["title"].asString(); + auto app_id = view["app-id"].asString(); + + // update label + label_.set_markup(waybar::util::rewriteString( + fmt::format(fmt::runtime(format_), fmt::arg("title", waybar::util::sanitize_string(title)), + fmt::arg("app_id", waybar::util::sanitize_string(app_id))), + config_["rewrite"])); + + // update window#waybar.solo + if (wset.locate_ws(view["geometry"]).num_views > 1) + ctx->remove_class("solo"); + else + ctx->add_class("solo"); + + // update window#waybar. + ctx->remove_class(old_app_id_); + ctx->add_class(old_app_id_ = app_id); + + // update window#waybar.empty + ctx->remove_class("empty"); + + // + updateAppIconName(app_id, ""); + label_.show(); + } else { + ctx->add_class("empty"); + + updateAppIconName("", ""); + label_.hide(); + } +} + +} // namespace waybar::modules::wayfire diff --git a/src/modules/wayfire/workspaces.cpp b/src/modules/wayfire/workspaces.cpp new file mode 100644 index 00000000..724a19f8 --- /dev/null +++ b/src/modules/wayfire/workspaces.cpp @@ -0,0 +1,191 @@ +#include "modules/wayfire/workspaces.hpp" + +#include +#include +#include + +#include +#include + +#include "modules/wayfire/backend.hpp" + +namespace waybar::modules::wayfire { + +Workspaces::Workspaces(const std::string& id, const Bar& bar, const Json::Value& config) + : AModule{config, "workspaces", id, false, !config["disable-scroll"].asBool()}, + ipc{IPC::get_instance()}, + handler{[this](const auto&) { dp.emit(); }}, + bar_{bar} { + // init box_ + box_.set_name("workspaces"); + if (!id.empty()) box_.get_style_context()->add_class(id); + box_.get_style_context()->add_class(MODULE_CLASS); + event_box_.add(box_); + + // scroll events + if (!config_["disable-scroll"].asBool()) { + auto& target = config_["enable-bar-scroll"].asBool() ? const_cast(bar_).window + : dynamic_cast(box_); + target.add_events(Gdk::SCROLL_MASK | Gdk::SMOOTH_SCROLL_MASK); + target.signal_scroll_event().connect(sigc::mem_fun(*this, &Workspaces::handleScroll)); + } + + // listen events + ipc->register_handler("view-mapped", handler); + ipc->register_handler("view-unmapped", handler); + ipc->register_handler("view-wset-changed", handler); + ipc->register_handler("output-gain-focus", handler); + ipc->register_handler("view-sticky", handler); + ipc->register_handler("view-workspace-changed", handler); + ipc->register_handler("output-wset-changed", handler); + ipc->register_handler("wset-workspace-changed", handler); + + ipc->register_handler("window-rules/list-views", handler); + ipc->register_handler("window-rules/list-outputs", handler); + ipc->register_handler("window-rules/list-wsets", handler); + ipc->register_handler("window-rules/get-focused-output", handler); + + // initial render + dp.emit(); +} + +Workspaces::~Workspaces() { ipc->unregister_handler(handler); } + +auto Workspaces::handleScroll(GdkEventScroll* e) -> bool { + // Ignore emulated scroll events on window + if (gdk_event_get_pointer_emulated((GdkEvent*)e) != 0) return false; + + auto dir = AModule::getScrollDir(e); + if (dir == SCROLL_DIR::NONE) return true; + + int delta; + if (dir == SCROLL_DIR::DOWN || dir == SCROLL_DIR::RIGHT) + delta = 1; + else if (dir == SCROLL_DIR::UP || dir == SCROLL_DIR::LEFT) + delta = -1; + else + return true; + + // cycle workspace + Json::Value data; + { + auto _ = ipc->lock_state(); + auto out_it = ipc->get_outputs().find(bar_.output->name); + if (out_it == ipc->get_outputs().end()) return true; + const auto& output = out_it->second; + auto wset_it = ipc->get_wsets().find(output.wset_idx); + if (wset_it == ipc->get_wsets().end()) return true; + const auto& wset = wset_it->second; + auto n = wset.ws_w * wset.ws_h; + auto i = (wset.ws_idx() + delta + n) % n; + data["x"] = Json::Value((uint64_t)i % wset.ws_w); + data["y"] = Json::Value((uint64_t)i / wset.ws_h); + data["output-id"] = Json::Value((uint64_t)output.id); + } + ipc->send("vswitch/set-workspace", std::move(data)); + + return true; +} + +auto Workspaces::update() -> void { + update_box(); + AModule::update(); +} + +auto Workspaces::update_box() -> void { + auto _ = ipc->lock_state(); + + const auto& output_name = bar_.output->name; + auto out_it = ipc->get_outputs().find(output_name); + if (out_it == ipc->get_outputs().end()) return; + const auto& output = out_it->second; + auto wset_it = ipc->get_wsets().find(output.wset_idx); + if (wset_it == ipc->get_wsets().end()) return; + const auto& wset = wset_it->second; + + auto output_focused = ipc->get_focused_output_name() == output_name; + auto ws_w = wset.ws_w; + auto ws_h = wset.ws_h; + auto num_wss = ws_w * ws_h; + + // add buttons for new workspaces + for (auto i = buttons_.size(); i < num_wss; i++) { + auto& btn = buttons_.emplace_back(""); + box_.pack_start(btn, false, false, 0); + btn.set_relief(Gtk::RELIEF_NONE); + if (!config_["disable-click"].asBool()) { + btn.signal_pressed().connect([=, this] { + Json::Value data; + data["x"] = Json::Value((uint64_t)i % ws_w); + data["y"] = Json::Value((uint64_t)i / ws_h); + data["output-id"] = Json::Value((uint64_t)output.id); + ipc->send("vswitch/set-workspace", std::move(data)); + }); + } + } + + // remove buttons for removed workspaces + buttons_.resize(num_wss); + + // update buttons + for (size_t i = 0; i < num_wss; i++) { + const auto& ws = wset.wss[i]; + auto& btn = buttons_[i]; + auto ctx = btn.get_style_context(); + auto ws_focused = i == wset.ws_idx(); + auto ws_empty = ws.num_views == 0; + + // update #workspaces button.focused + if (ws_focused) + ctx->add_class("focused"); + else + ctx->remove_class("focused"); + + // update #workspaces button.empty + if (ws_empty) + ctx->add_class("empty"); + else + ctx->remove_class("empty"); + + // update #workspaces button.current_output + if (output_focused) + ctx->add_class("current_output"); + else + ctx->remove_class("current_output"); + + // update label + auto label = std::to_string(i + 1); + if (config_["format"].isString()) { + auto format = config_["format"].asString(); + auto ws_idx = std::to_string(i + 1); + + const auto& icons = config_["format-icons"]; + std::string icon; + if (!icons) + icon = ws_idx; + else if (ws_focused && icons["focused"]) + icon = icons["focused"].asString(); + else if (icons[ws_idx]) + icon = icons[ws_idx].asString(); + else if (icons["default"]) + icon = icons["default"].asString(); + else + icon = ws_idx; + + label = fmt::format(fmt::runtime(format), fmt::arg("icon", icon), fmt::arg("index", ws_idx), + fmt::arg("output", output_name)); + } + if (!config_["disable-markup"].asBool()) + static_cast(btn.get_children()[0])->set_markup(label); + else + btn.set_label(label); + + // + if (config_["current-only"].asBool() && i != wset.ws_idx()) + btn.hide(); + else + btn.show(); + } +} + +} // namespace waybar::modules::wayfire diff --git a/src/modules/wireplumber.cpp b/src/modules/wireplumber.cpp index 106ca403..7d9ac578 100644 --- a/src/modules/wireplumber.cpp +++ b/src/modules/wireplumber.cpp @@ -19,7 +19,13 @@ waybar::modules::Wireplumber::Wireplumber(const std::string& id, const Json::Val volume_(0.0), min_step_(0.0), node_id_(0), - type_(nullptr) { + node_name_(""), + source_name_(""), + type_(nullptr), + source_node_id_(0), + source_muted_(false), + source_volume_(0.0), + default_source_name_(nullptr) { waybar::modules::Wireplumber::modules.push_back(this); wp_init(WP_INIT_PIPEWIRE); @@ -48,6 +54,15 @@ waybar::modules::Wireplumber::Wireplumber(const std::string& id, const Json::Val waybar::modules::Wireplumber::~Wireplumber() { waybar::modules::Wireplumber::modules.remove(this); + if (mixer_api_ != nullptr) { + g_signal_handlers_disconnect_by_data(mixer_api_, this); + } + if (def_nodes_api_ != nullptr) { + g_signal_handlers_disconnect_by_data(def_nodes_api_, this); + } + if (om_ != nullptr) { + g_signal_handlers_disconnect_by_data(om_, this); + } wp_core_disconnect(wp_core_); g_clear_pointer(&apis_, g_ptr_array_unref); g_clear_object(&om_); @@ -55,6 +70,7 @@ waybar::modules::Wireplumber::~Wireplumber() { g_clear_object(&mixer_api_); g_clear_object(&def_nodes_api_); g_free(default_node_name_); + g_free(default_source_name_); g_free(type_); } @@ -74,7 +90,7 @@ void waybar::modules::Wireplumber::updateNodeName(waybar::modules::Wireplumber* if (proxy == nullptr) { auto err = fmt::format("Object '{}' not found\n", id); spdlog::error("[{}]: {}", self->name_, err); - throw std::runtime_error(err); + return; } g_autoptr(WpProperties) properties = @@ -94,6 +110,43 @@ void waybar::modules::Wireplumber::updateNodeName(waybar::modules::Wireplumber* spdlog::debug("[{}]: Updating '{}' node name to: {}", self->name_, self->type_, self->node_name_); } +void waybar::modules::Wireplumber::updateSourceName(waybar::modules::Wireplumber* self, + uint32_t id) { + spdlog::debug("[{}]: updating source name with node.id {}", self->name_, id); + + if (!isValidNodeId(id)) { + spdlog::warn("[{}]: '{}' is not a valid source node ID. Ignoring source name update.", + self->name_, id); + return; + } + + auto* proxy = static_cast(wp_object_manager_lookup(self->om_, WP_TYPE_GLOBAL_PROXY, + WP_CONSTRAINT_TYPE_G_PROPERTY, + "bound-id", "=u", id, nullptr)); + + if (proxy == nullptr) { + auto err = fmt::format("Source object '{}' not found\n", id); + spdlog::error("[{}]: {}", self->name_, err); + return; + } + + g_autoptr(WpProperties) properties = + WP_IS_PIPEWIRE_OBJECT(proxy) != 0 + ? wp_pipewire_object_get_properties(WP_PIPEWIRE_OBJECT(proxy)) + : wp_properties_new_empty(); + g_autoptr(WpProperties) globalP = wp_global_proxy_get_global_properties(WP_GLOBAL_PROXY(proxy)); + properties = wp_properties_ensure_unique_owner(properties); + wp_properties_add(properties, globalP); + wp_properties_set(properties, "object.id", nullptr); + const auto* nick = wp_properties_get(properties, "node.nick"); + const auto* description = wp_properties_get(properties, "node.description"); + + self->source_name_ = nick != nullptr ? nick + : description != nullptr ? description + : "Unknown source name"; + spdlog::debug("[{}]: Updating source name to: {}", self->name_, self->source_name_); +} + void waybar::modules::Wireplumber::updateVolume(waybar::modules::Wireplumber* self, uint32_t id) { spdlog::debug("[{}]: updating volume", self->name_); GVariant* variant = nullptr; @@ -109,7 +162,7 @@ void waybar::modules::Wireplumber::updateVolume(waybar::modules::Wireplumber* se if (variant == nullptr) { auto err = fmt::format("Node {} does not support volume\n", id); spdlog::error("[{}]: {}", self->name_, err); - throw std::runtime_error(err); + return; } g_variant_lookup(variant, "volume", "d", &self->volume_); @@ -120,6 +173,31 @@ void waybar::modules::Wireplumber::updateVolume(waybar::modules::Wireplumber* se self->dp.emit(); } +void waybar::modules::Wireplumber::updateSourceVolume(waybar::modules::Wireplumber* self, + uint32_t id) { + spdlog::debug("[{}]: updating source volume", self->name_); + GVariant* variant = nullptr; + + if (!isValidNodeId(id)) { + spdlog::error("[{}]: '{}' is not a valid source node ID. Ignoring source volume update.", + self->name_, id); + return; + } + + g_signal_emit_by_name(self->mixer_api_, "get-volume", id, &variant); + + if (variant == nullptr) { + spdlog::debug("[{}]: Source node {} does not support volume", self->name_, id); + return; + } + + g_variant_lookup(variant, "volume", "d", &self->source_volume_); + g_variant_lookup(variant, "mute", "b", &self->source_muted_); + g_clear_pointer(&variant, g_variant_unref); + + self->dp.emit(); +} + void waybar::modules::Wireplumber::onMixerChanged(waybar::modules::Wireplumber* self, uint32_t id) { g_autoptr(WpNode) node = static_cast(wp_object_manager_lookup( self->om_, WP_TYPE_NODE, WP_CONSTRAINT_TYPE_G_PROPERTY, "bound-id", "=u", id, nullptr)); @@ -127,12 +205,13 @@ void waybar::modules::Wireplumber::onMixerChanged(waybar::modules::Wireplumber* if (node == nullptr) { // log a warning only if no other widget is targeting the id. // this reduces log spam when multiple instances of the module are used on different node types. - if (id != self->node_id_) { + if (id != self->node_id_ && id != self->source_node_id_) { for (auto const& module : waybar::modules::Wireplumber::modules) { - if (module->node_id_ == id) { + if (module->node_id_ == id || module->source_node_id_ == id) { return; } } + return; } spdlog::warn("[{}]: (onMixerChanged: {}) - Object with id {} not found", self->name_, @@ -142,68 +221,73 @@ void waybar::modules::Wireplumber::onMixerChanged(waybar::modules::Wireplumber* const gchar* name = wp_pipewire_object_get_property(WP_PIPEWIRE_OBJECT(node), "node.name"); - if (self->node_id_ != id) { - spdlog::debug( - "[{}]: (onMixerChanged: {}) - ignoring mixer update for node: id: {}, name: {} as it is " - "not the default node: {} with id: {}", - self->name_, self->type_, id, name, self->default_node_name_, self->node_id_); - return; + if (self->node_id_ == id) { + spdlog::debug("[{}]: (onMixerChanged: {}) - updating sink volume for node: {}", self->name_, + self->type_, name); + updateVolume(self, id); + } else if (self->source_node_id_ == id) { + spdlog::debug("[{}]: (onMixerChanged: {}) - updating source volume for node: {}", self->name_, + self->type_, name); + updateSourceVolume(self, id); } - - spdlog::debug( - "[{}]: (onMixerChanged: {}) - Need to update volume for node with id {} and name {}", - self->name_, self->type_, id, name); - updateVolume(self, id); } void waybar::modules::Wireplumber::onDefaultNodesApiChanged(waybar::modules::Wireplumber* self) { spdlog::debug("[{}]: (onDefaultNodesApiChanged: {})", self->name_, self->type_); + // Handle sink uint32_t defaultNodeId; g_signal_emit_by_name(self->def_nodes_api_, "get-default-node", self->type_, &defaultNodeId); - if (!isValidNodeId(defaultNodeId)) { - spdlog::warn("[{}]: '{}' is not a valid node ID. Ignoring '{}' node change.", self->name_, - defaultNodeId, self->type_); - return; + if (isValidNodeId(defaultNodeId)) { + g_autoptr(WpNode) node = static_cast( + wp_object_manager_lookup(self->om_, WP_TYPE_NODE, WP_CONSTRAINT_TYPE_G_PROPERTY, "bound-id", + "=u", defaultNodeId, nullptr)); + + if (node != nullptr) { + const gchar* defaultNodeName = + wp_pipewire_object_get_property(WP_PIPEWIRE_OBJECT(node), "node.name"); + + if (g_strcmp0(self->default_node_name_, defaultNodeName) != 0 || + self->node_id_ != defaultNodeId) { + spdlog::debug("[{}]: Default sink changed to -> Node(name: {}, id: {})", self->name_, + defaultNodeName, defaultNodeId); + + g_free(self->default_node_name_); + self->default_node_name_ = g_strdup(defaultNodeName); + self->node_id_ = defaultNodeId; + updateVolume(self, defaultNodeId); + updateNodeName(self, defaultNodeId); + } + } } - g_autoptr(WpNode) node = static_cast( - wp_object_manager_lookup(self->om_, WP_TYPE_NODE, WP_CONSTRAINT_TYPE_G_PROPERTY, "bound-id", - "=u", defaultNodeId, nullptr)); + // Handle source + uint32_t defaultSourceId; + g_signal_emit_by_name(self->def_nodes_api_, "get-default-node", "Audio/Source", &defaultSourceId); - if (node == nullptr) { - spdlog::warn("[{}]: (onDefaultNodesApiChanged: {}) - Object with id {} not found", self->name_, - self->type_, defaultNodeId); - return; + if (isValidNodeId(defaultSourceId)) { + g_autoptr(WpNode) sourceNode = static_cast( + wp_object_manager_lookup(self->om_, WP_TYPE_NODE, WP_CONSTRAINT_TYPE_G_PROPERTY, "bound-id", + "=u", defaultSourceId, nullptr)); + + if (sourceNode != nullptr) { + const gchar* defaultSourceName = + wp_pipewire_object_get_property(WP_PIPEWIRE_OBJECT(sourceNode), "node.name"); + + if (g_strcmp0(self->default_source_name_, defaultSourceName) != 0 || + self->source_node_id_ != defaultSourceId) { + spdlog::debug("[{}]: Default source changed to -> Node(name: {}, id: {})", self->name_, + defaultSourceName, defaultSourceId); + + g_free(self->default_source_name_); + self->default_source_name_ = g_strdup(defaultSourceName); + self->source_node_id_ = defaultSourceId; + updateSourceVolume(self, defaultSourceId); + updateSourceName(self, defaultSourceId); + } + } } - - const gchar* defaultNodeName = - wp_pipewire_object_get_property(WP_PIPEWIRE_OBJECT(node), "node.name"); - - spdlog::debug( - "[{}]: (onDefaultNodesApiChanged: {}) - got the following default node: Node(name: {}, id: " - "{})", - self->name_, self->type_, defaultNodeName, defaultNodeId); - - if (g_strcmp0(self->default_node_name_, defaultNodeName) == 0 && - self->node_id_ == defaultNodeId) { - spdlog::debug( - "[{}]: (onDefaultNodesApiChanged: {}) - Default node has not changed. Node(name: {}, id: " - "{}). Ignoring.", - self->name_, self->type_, self->default_node_name_, defaultNodeId); - return; - } - - spdlog::debug( - "[{}]: (onDefaultNodesApiChanged: {}) - Default node changed to -> Node(name: {}, id: {})", - self->name_, self->type_, defaultNodeName, defaultNodeId); - - g_free(self->default_node_name_); - self->default_node_name_ = g_strdup(defaultNodeName); - self->node_id_ = defaultNodeId; - updateVolume(self, defaultNodeId); - updateNodeName(self, defaultNodeId); } void waybar::modules::Wireplumber::onObjectManagerInstalled(waybar::modules::Wireplumber* self) { @@ -213,28 +297,41 @@ void waybar::modules::Wireplumber::onObjectManagerInstalled(waybar::modules::Wir if (self->def_nodes_api_ == nullptr) { spdlog::error("[{}]: default nodes api is not loaded.", self->name_); - throw std::runtime_error("Default nodes API is not loaded\n"); + return; } self->mixer_api_ = wp_plugin_find(self->wp_core_, "mixer-api"); if (self->mixer_api_ == nullptr) { spdlog::error("[{}]: mixer api is not loaded.", self->name_); - throw std::runtime_error("Mixer api is not loaded\n"); + return; } + // Get default sink g_signal_emit_by_name(self->def_nodes_api_, "get-default-configured-node-name", self->type_, &self->default_node_name_); g_signal_emit_by_name(self->def_nodes_api_, "get-default-node", self->type_, &self->node_id_); + // Get default source + g_signal_emit_by_name(self->def_nodes_api_, "get-default-configured-node-name", "Audio/Source", + &self->default_source_name_); + g_signal_emit_by_name(self->def_nodes_api_, "get-default-node", "Audio/Source", + &self->source_node_id_); + if (self->default_node_name_ != nullptr) { spdlog::debug( "[{}]: (onObjectManagerInstalled: {}) - default configured node name: {} and id: {}", self->name_, self->type_, self->default_node_name_, self->node_id_); } + if (self->default_source_name_ != nullptr) { + spdlog::debug("[{}]: default source: {} (id: {})", self->name_, self->default_source_name_, + self->source_node_id_); + } updateVolume(self, self->node_id_); updateNodeName(self, self->node_id_); + updateSourceVolume(self, self->source_node_id_); + updateSourceName(self, self->source_node_id_); g_signal_connect_swapped(self->mixer_api_, "changed", (GCallback)onMixerChanged, self); g_signal_connect_swapped(self->def_nodes_api_, "changed", (GCallback)onDefaultNodesApiChanged, @@ -249,7 +346,7 @@ void waybar::modules::Wireplumber::onPluginActivated(WpObject* p, GAsyncResult* if (wp_object_activate_finish(p, res, &error) == 0) { spdlog::error("[{}]: error activating plugin: {}", self->name_, error->message); - throw std::runtime_error(error->message); + return; } if (--self->pending_plugins_ == 0) { @@ -271,6 +368,8 @@ void waybar::modules::Wireplumber::prepare(waybar::modules::Wireplumber* self) { spdlog::debug("[{}]: preparing object manager: '{}'", name_, self->type_); wp_object_manager_add_interest(om_, WP_TYPE_NODE, WP_CONSTRAINT_TYPE_PW_PROPERTY, "media.class", "=s", self->type_, nullptr); + wp_object_manager_add_interest(om_, WP_TYPE_NODE, WP_CONSTRAINT_TYPE_PW_PROPERTY, "media.class", + "=s", "Audio/Source", nullptr); } void waybar::modules::Wireplumber::onDefaultNodesApiLoaded(WpObject* p, GAsyncResult* res, @@ -284,7 +383,7 @@ void waybar::modules::Wireplumber::onDefaultNodesApiLoaded(WpObject* p, GAsyncRe if (success == FALSE) { spdlog::error("[{}]: default nodes API load failed", self->name_); - throw std::runtime_error(error->message); + return; } spdlog::debug("[{}]: loaded default nodes api", self->name_); g_ptr_array_add(self->apis_, wp_plugin_find(self->wp_core_, "default-nodes-api")); @@ -303,7 +402,7 @@ void waybar::modules::Wireplumber::onMixerApiLoaded(WpObject* p, GAsyncResult* r if (success == FALSE) { spdlog::error("[{}]: mixer API load failed", self->name_); - throw std::runtime_error(error->message); + return; } spdlog::debug("[{}]: loaded mixer API", self->name_); @@ -332,19 +431,57 @@ auto waybar::modules::Wireplumber::update() -> void { auto format = format_; std::string tooltipFormat; + // Handle sink mute state if (muted_) { format = config_["format-muted"].isString() ? config_["format-muted"].asString() : format; label_.get_style_context()->add_class("muted"); + label_.get_style_context()->add_class("sink-muted"); } else { label_.get_style_context()->remove_class("muted"); + label_.get_style_context()->remove_class("sink-muted"); + } + + // Handle source mute state + if (source_muted_) { + label_.get_style_context()->add_class("source-muted"); + } else { + label_.get_style_context()->remove_class("source-muted"); } int vol = round(volume_ * 100.0); - std::string markup = fmt::format(fmt::runtime(format), fmt::arg("node_name", node_name_), - fmt::arg("volume", vol), fmt::arg("icon", getIcon(vol))); - label_.set_markup(markup); + int source_vol = round(source_volume_ * 100.0); - getState(vol); + // Get the state and apply state-specific format if available + auto state = getState(vol); + if (!state.empty()) { + std::string format_name = muted_ ? "format-muted" : "format"; + std::string state_format_name = format_name + "-" + state; + if (config_[state_format_name].isString()) { + format = config_[state_format_name].asString(); + } + } + + // Prepare source format string (similar to PulseAudio) + std::string format_source = "{volume}%"; + if (source_muted_) { + if (config_["format-source-muted"].isString()) { + format_source = config_["format-source-muted"].asString(); + } + } else { + if (config_["format-source"].isString()) { + format_source = config_["format-source"].asString(); + } + } + + // Format the source string with actual volume + std::string formatted_source = + fmt::format(fmt::runtime(format_source), fmt::arg("volume", source_vol)); + + std::string markup = + fmt::format(fmt::runtime(format), fmt::arg("node_name", node_name_), fmt::arg("volume", vol), + fmt::arg("icon", getIcon(vol)), fmt::arg("format_source", formatted_source), + fmt::arg("source_volume", source_vol), fmt::arg("source_desc", source_name_)); + label_.set_markup(markup); if (tooltipEnabled()) { if (tooltipFormat.empty() && config_["tooltip-format"].isString()) { @@ -352,11 +489,12 @@ auto waybar::modules::Wireplumber::update() -> void { } if (!tooltipFormat.empty()) { - label_.set_tooltip_text(fmt::format(fmt::runtime(tooltipFormat), - fmt::arg("node_name", node_name_), - fmt::arg("volume", vol), fmt::arg("icon", getIcon(vol)))); + label_.set_tooltip_markup(fmt::format( + fmt::runtime(tooltipFormat), fmt::arg("node_name", node_name_), fmt::arg("volume", vol), + fmt::arg("icon", getIcon(vol)), fmt::arg("format_source", formatted_source), + fmt::arg("source_volume", source_vol), fmt::arg("source_desc", source_name_))); } else { - label_.set_tooltip_text(node_name_); + label_.set_tooltip_markup(node_name_); } } @@ -396,9 +534,11 @@ bool waybar::modules::Wireplumber::handleScroll(GdkEventScroll* e) { } } if (newVol != volume_) { + if (mixer_api_ == nullptr) return true; GVariant* variant = g_variant_new_double(newVol); gboolean ret; g_signal_emit_by_name(mixer_api_, "set-volume", node_id_, variant, &ret); + g_variant_unref(variant); } return true; } diff --git a/src/modules/wlr/taskbar.cpp b/src/modules/wlr/taskbar.cpp index 8e3b2542..f382e1fc 100644 --- a/src/modules/wlr/taskbar.cpp +++ b/src/modules/wlr/taskbar.cpp @@ -26,233 +26,45 @@ namespace waybar::modules::wlr { -/* Icon loading functions */ -static std::vector search_prefix() { - std::vector prefixes = {""}; - - std::string home_dir = std::getenv("HOME"); - prefixes.push_back(home_dir + "/.local/share/"); - - 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) + "/"); - - start = end == std::string::npos ? end : end + 1; - } while (end != std::string::npos); - } - - for (auto &p : prefixes) spdlog::debug("Using 'desktop' search path prefix: {}", p); - - 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 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 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]); - if (!tmp_info) - // see https://github.com/Alexays/Waybar/issues/1446 - continue; - - auto startup_class = tmp_info->get_startup_wm_class(); - 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); -} - -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); - - /* 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); - } -} - -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; - - return ""; -} - -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(); - } - } - } - - Glib::RefPtr pixbuf; - auto scaled_icon_size = size * image.get_scale_factor(); - - try { - pixbuf = icon_theme->load_icon(ret_icon_name, scaled_icon_size, Gtk::ICON_LOOKUP_FORCE_SIZE); - spdlog::debug("{} Loaded icon '{}'", repr(), ret_icon_name); - } catch (...) { - if (Glib::file_test(ret_icon_name, Glib::FILE_TEST_EXISTS)) { - pixbuf = load_icon_from_file(ret_icon_name, scaled_icon_size); - spdlog::debug("{} Loaded icon from file '{}'", repr(), ret_icon_name); - } else { - try { - pixbuf = DefaultGtkIconThemeWrapper::load_icon( - "image-missing", scaled_icon_size, Gtk::IconLookupFlags::ICON_LOOKUP_FORCE_SIZE); - spdlog::debug("{} Loaded icon from resource", repr()); - } catch (...) { - pixbuf = {}; - spdlog::debug("{} Unable to load icon.", repr()); - } - } - } - - if (pixbuf) { - if (pixbuf->get_width() != scaled_icon_size) { - int width = scaled_icon_size * pixbuf->get_width() / pixbuf->get_height(); - pixbuf = pixbuf->scale_simple(width, scaled_icon_size, Gdk::InterpType::INTERP_BILINEAR); - } - auto surface = Gdk::Cairo::create_surface_from_pixbuf(pixbuf, image.get_scale_factor(), - image.get_window()); - image.set(surface); - 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); +static void tl_handle_title(void* data, struct zwlr_foreign_toplevel_handle_v1* handle, + 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); +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); } -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); +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); } -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); +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); } -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); +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); } -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) { +static void tl_handle_parent(void* data, struct zwlr_foreign_toplevel_handle_v1* handle, + struct zwlr_foreign_toplevel_handle_v1* parent) { /* This is explicitly left blank */ } -static void tl_handle_closed(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle) { - return static_cast(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,8 +81,8 @@ static const struct zwlr_foreign_toplevel_handle_v1_listener toplevel_handle_imp static const std::vector target_entries = { Gtk::TargetEntry("WAYBAR_TOPLEVEL", Gtk::TARGET_SAME_APP, 0)}; -Task::Task(const waybar::Bar &bar, const Json::Value &config, Taskbar *tbar, - struct zwlr_foreign_toplevel_handle_v1 *tl_handle, struct wl_seat *seat) +Task::Task(const waybar::Bar& bar, const Json::Value& config, Taskbar* tbar, + struct zwlr_foreign_toplevel_handle_v1* tl_handle, struct wl_seat* seat) : bar_{bar}, config_{config}, tbar_{tbar}, @@ -282,9 +94,35 @@ Task::Task(const waybar::Bar &bar, const Json::Value &config, Taskbar *tbar, button.set_relief(Gtk::RELIEF_NONE); - content_.add(text_before_); - content_.add(icon_); - content_.add(text_after_); + /* When "expand" is enabled the buttons stretch to fill the taskbar and the + * titles ellipsize to fit within the available space. This only makes sense + * on a horizontal bar; on a vertical bar the box grows along the vertical + * axis, so ellipsizing/forcing width_chars(1) would truncate every title to + * "…". Keep the historical behavior (buttons sized to their content) as the + * default and when the bar is vertical. */ + bool expand = config_["expand"].isBool() && config_["expand"].asBool(); + bool horizontal = bar.orientation == Gtk::ORIENTATION_HORIZONTAL; + + if (expand && horizontal) { + button.set_hexpand(true); + content_.set_hexpand(true); + text_before_.set_ellipsize(Pango::ELLIPSIZE_END); + text_before_.set_single_line_mode(true); + text_before_.set_width_chars(1); + text_before_.set_xalign(0.0); + text_after_.set_ellipsize(Pango::ELLIPSIZE_END); + text_after_.set_single_line_mode(true); + text_after_.set_width_chars(1); + text_after_.set_xalign(0.0); + + content_.pack_start(text_before_, true, true, 0); + content_.pack_start(icon_, false, false, 0); + content_.pack_start(text_after_, true, true, 0); + } else { + content_.add(text_before_); + content_.add(icon_); + content_.add(text_after_); + } content_.show(); button.add(content_); @@ -299,16 +137,11 @@ Task::Task(const waybar::Bar &bar, const Json::Value &config, Taskbar *tbar, with_name_ = true; } - auto icon_pos = format.find("{icon}"); - if (icon_pos == 0) { + auto parts = split(format, "{icon}", 1); + format_before_ = parts[0]; + if (parts.size() > 1) { 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); + format_after_ = parts[1]; } } else { /* The default is to only show the icon */ @@ -382,7 +215,7 @@ std::string Task::state_string(bool shortened) const { return res.substr(0, res.size() - 1); } -void Task::handle_title(const char *title) { +void Task::handle_title(const char* title) { if (title_.empty()) { spdlog::debug(fmt::format("Task ({}) setting title to {}", id_, title_)); } else { @@ -391,11 +224,11 @@ void Task::handle_title(const char *title) { title_ = title; hide_if_ignored(); - if (!with_icon_ && !with_name_ || app_info_) { + if ((!with_icon_ && !with_name_) || app_info_) { return; } - set_app_info_from_app_id_list(title_); + app_info_ = IconLoader::get_app_info_from_app_id_list(title_); name_ = app_info_ ? app_info_->get_display_name() : title; if (!with_icon_) { @@ -403,15 +236,7 @@ void Task::handle_title(const char *title) { } 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) + if (tbar_->icon_loader().image_load_icon(icon_, app_info_, icon_size)) icon_.show(); else spdlog::debug("Couldn't find icon for {}", title_); @@ -439,7 +264,7 @@ void Task::hide_if_ignored() { } } -void Task::handle_app_id(const char *app_id) { +void Task::handle_app_id(const char* app_id) { if (app_id_.empty()) { spdlog::debug(fmt::format("Task ({}) setting app_id to {}", id_, app_id)); } else { @@ -460,7 +285,7 @@ void Task::handle_app_id(const char *app_id) { return; } - set_app_info_from_app_id_list(app_id_); + app_info_ = IconLoader::get_app_info_from_app_id_list(app_id_); name_ = app_info_ ? app_info_->get_display_name() : app_id; if (!with_icon_) { @@ -468,34 +293,26 @@ void Task::handle_app_id(const char *app_id) { } 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) + if (tbar_->icon_loader().image_load_icon(icon_, app_info_, icon_size)) icon_.show(); else spdlog::debug("Couldn't find icon for {}", app_id_); } -void Task::on_button_size_allocated(Gtk::Allocation &alloc) { +void Task::on_button_size_allocated(Gtk::Allocation& alloc) { gtk_widget_translate_coordinates(GTK_WIDGET(button.gobj()), GTK_WIDGET(bar_.window.gobj()), 0, 0, &minimize_hint.x, &minimize_hint.y); minimize_hint.w = button.get_width(); minimize_hint.h = button.get_height(); } -void Task::handle_output_enter(struct wl_output *output) { +void Task::handle_output_enter(struct wl_output* output) { if (ignored_) { spdlog::debug("{} is ignored", repr()); return; } - spdlog::debug("{} entered output {}", repr(), (void *)output); + spdlog::debug("{} entered output {}", repr(), (void*)output); if (!button_visible_ && (tbar_->all_outputs() || tbar_->show_output(output))) { /* The task entered the output of the current bar make the button visible */ @@ -508,8 +325,8 @@ void Task::handle_output_enter(struct wl_output *output) { } } -void Task::handle_output_leave(struct wl_output *output) { - spdlog::debug("{} left output {}", repr(), (void *)output); +void Task::handle_output_leave(struct wl_output* output) { + spdlog::debug("{} left output {}", repr(), (void*)output); if (button_visible_ && !tbar_->all_outputs() && tbar_->show_output(output)) { /* The task left the output of the current bar, make the button invisible */ @@ -520,11 +337,11 @@ void Task::handle_output_leave(struct wl_output *output) { } } -void Task::handle_state(struct wl_array *state) { +void Task::handle_state(struct wl_array* state) { state_ = 0; size_t size = state->size / sizeof(uint32_t); for (size_t i = 0; i < size; ++i) { - auto entry = static_cast(state->data)[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; @@ -576,7 +393,7 @@ void Task::handle_closed() { tbar_->remove_task(id_); } -bool Task::handle_clicked(GdkEventButton *bt) { +bool Task::handle_clicked(GdkEventButton* bt) { /* filter out additional events for double/triple clicks */ if (bt->type == GDK_BUTTON_PRESS) { /* save where the button press occurred in case it becomes a drag */ @@ -621,7 +438,7 @@ bool Task::handle_clicked(GdkEventButton *bt) { return true; } -bool Task::handle_motion_notify(GdkEventMotion *mn) { +bool Task::handle_motion_notify(GdkEventMotion* mn) { if (drag_start_button == -1) return false; if (button.drag_check_threshold(drag_start_x, drag_start_y, mn->x, mn->y)) { @@ -629,25 +446,27 @@ bool Task::handle_motion_notify(GdkEventMotion *mn) { auto target_list = Gtk::TargetList::create(target_entries); auto refptr = Glib::RefPtr(target_list); auto drag_context = - button.drag_begin(refptr, Gdk::DragAction::ACTION_MOVE, drag_start_button, (GdkEvent *)mn); + button.drag_begin(refptr, Gdk::DragAction::ACTION_MOVE, drag_start_button, (GdkEvent*)mn); } return false; } -void Task::handle_drag_data_get(const Glib::RefPtr &context, - Gtk::SelectionData &selection_data, guint info, guint time) { +void Task::handle_drag_data_get(const Glib::RefPtr& context, + Gtk::SelectionData& selection_data, guint info, guint time) { spdlog::debug("drag_data_get"); - void *button_addr = (void *)&this->button; + void* button_addr = (void*)&this->button; - selection_data.set("WAYBAR_TOPLEVEL", 32, (const guchar *)&button_addr, sizeof(gpointer)); + selection_data.set("WAYBAR_TOPLEVEL", 32, (const guchar*)&button_addr, sizeof(gpointer)); } -void Task::handle_drag_data_received(const Glib::RefPtr &context, int x, int y, +void Task::handle_drag_data_received(const Glib::RefPtr& context, int x, int y, Gtk::SelectionData selection_data, guint info, guint time) { spdlog::debug("drag_data_received"); - gpointer handle = *(gpointer *)selection_data.get_data(); - auto dragged_button = (Gtk::Button *)handle; + auto* raw = selection_data.get_data(); + if (!raw || selection_data.get_length() < static_cast(sizeof(gpointer))) return; + gpointer handle = *(gpointer*)raw; + auto dragged_button = (Gtk::Button*)handle; if (dragged_button == &this->button) return; @@ -656,7 +475,7 @@ void Task::handle_drag_data_received(const Glib::RefPtr &conte if (parent_of_dragged != parent_of_dest) return; - auto box = (Gtk::Box *)parent_of_dragged; + auto box = (Gtk::Box*)parent_of_dragged; auto position_prop = box->child_property_position(this->button); auto position = position_prop.get_value(); @@ -664,9 +483,9 @@ void Task::handle_drag_data_received(const Glib::RefPtr &conte box->reorder_child(*dragged_button, position); } -bool Task::operator==(const Task &o) const { return o.id_ == id_; } +bool Task::operator==(const Task& o) const { return o.id_ == id_; } -bool Task::operator!=(const Task &o) const { return o.id_ != id_; } +bool Task::operator!=(const Task& o) const { return o.id_ != id_; } void Task::update() { bool markup = config_["markup"].isBool() ? config_["markup"].asBool() : false; @@ -712,10 +531,13 @@ void Task::update() { fmt::format(fmt::runtime(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))); + + txt = waybar::util::rewriteString(txt, config_["rewrite"]); + if (markup) button.set_tooltip_markup(txt); else - button.set_tooltip_text(txt); + button.set_tooltip_markup(txt); } } @@ -751,23 +573,23 @@ void Task::fullscreen(bool set) { void Task::close() { zwlr_foreign_toplevel_handle_v1_close(handle_); } /* Taskbar class implementation */ -static void handle_global(void *data, struct wl_registry *registry, uint32_t name, - const char *interface, uint32_t version) { +static void handle_global(void* data, struct wl_registry* registry, uint32_t name, + const char* interface, uint32_t version) { if (std::strcmp(interface, zwlr_foreign_toplevel_manager_v1_interface.name) == 0) { - static_cast(data)->register_manager(registry, name, version); + 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_cast(data)->register_seat(registry, name, version); } } -static void handle_global_remove(void *data, struct wl_registry *registry, uint32_t name) { +static void handle_global_remove(void* data, struct wl_registry* registry, uint32_t name) { /* Nothing to do here */ } static const wl_registry_listener registry_listener_impl = {.global = handle_global, .global_remove = handle_global_remove}; -Taskbar::Taskbar(const std::string &id, const waybar::Bar &bar, const Json::Value &config) +Taskbar::Taskbar(const std::string& id, const waybar::Bar& bar, const Json::Value& config) : waybar::AModule(config, "taskbar", id, false, false), bar_(bar), box_{bar.orientation, 0}, @@ -781,8 +603,8 @@ Taskbar::Taskbar(const std::string &id, const waybar::Bar &bar, const Json::Valu box_.get_style_context()->add_class("empty"); event_box_.add(box_); - struct wl_display *display = Client::inst()->wl_display; - struct wl_registry *registry = wl_display_get_registry(display); + struct wl_display* display = Client::inst()->wl_display; + struct wl_registry* registry = wl_display_get_registry(display); wl_registry_add_listener(registry, ®istry_listener_impl, this); wl_display_roundtrip(display); @@ -798,51 +620,37 @@ Taskbar::Taskbar(const std::string &id, const waybar::Bar &bar, const Json::Valu /* Get the configured icon theme if specified */ if (config_["icon-theme"].isArray()) { - for (auto &c : config_["icon-theme"]) { - 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); + for (auto& c : config_["icon-theme"]) { + icon_loader_.add_custom_icon_theme(c.asString()); } } 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); + icon_loader_.add_custom_icon_theme(config_["icon-theme"].asString()); } // Load ignore-list if (config_["ignore-list"].isArray()) { - for (auto &app_name : config_["ignore-list"]) { + for (auto& app_name : config_["ignore-list"]) { ignore_list_.emplace(app_name.asString()); } } // Load app_id remappings if (config_["app_ids-mapping"].isObject()) { - const Json::Value &mapping = config_["app_ids-mapping"]; + const Json::Value& mapping = config_["app_ids-mapping"]; const std::vector app_ids = config_["app_ids-mapping"].getMemberNames(); - for (auto &app_id : app_ids) { + for (auto& app_id : app_ids) { app_ids_replace_map_.emplace(app_id, mapping[app_id].asString()); } } - icon_themes_.push_back(Gtk::IconTheme::get_default()); - - for (auto &t : tasks_) { + for (auto& t : tasks_) { t->handle_app_id(t->app_id().c_str()); } } Taskbar::~Taskbar() { if (manager_) { - struct wl_display *display = Client::inst()->wl_display; + struct wl_display* display = Client::inst()->wl_display; /* * Send `stop` request and wait for one roundtrip. * This is not quite correct as the protocol encourages us to wait for the .finished event, @@ -860,13 +668,13 @@ Taskbar::~Taskbar() { } void Taskbar::update() { - for (auto &t : tasks_) { + for (auto& t : tasks_) { t->update(); } if (config_["sort-by-app-id"].asBool()) { std::stable_sort(tasks_.begin(), tasks_.end(), - [](const std::unique_ptr &a, const std::unique_ptr &b) { + [](const std::unique_ptr& a, const std::unique_ptr& b) { return a->app_id() < b->app_id(); }); @@ -878,13 +686,13 @@ void Taskbar::update() { AModule::update(); } -static void tm_handle_toplevel(void *data, struct zwlr_foreign_toplevel_manager_v1 *manager, - struct zwlr_foreign_toplevel_handle_v1 *tl_handle) { - return static_cast(data)->handle_toplevel_create(tl_handle); +static void tm_handle_toplevel(void* data, struct zwlr_foreign_toplevel_manager_v1* manager, + struct zwlr_foreign_toplevel_handle_v1* tl_handle) { + return static_cast(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 = { @@ -892,7 +700,7 @@ static const struct zwlr_foreign_toplevel_manager_v1_listener toplevel_manager_i .finished = tm_handle_finished, }; -void Taskbar::register_manager(struct wl_registry *registry, uint32_t name, uint32_t version) { +void Taskbar::register_manager(struct wl_registry* registry, uint32_t name, uint32_t version) { if (manager_) { spdlog::warn("Register foreign toplevel manager again although already existing!"); return; @@ -907,7 +715,7 @@ void Taskbar::register_manager(struct wl_registry *registry, uint32_t name, uint // limit version to a highest supported by the client protocol file version = std::min(version, zwlr_foreign_toplevel_manager_v1_interface.version); - manager_ = static_cast( + manager_ = static_cast( wl_registry_bind(registry, name, &zwlr_foreign_toplevel_manager_v1_interface, version)); if (manager_) @@ -916,17 +724,17 @@ void Taskbar::register_manager(struct wl_registry *registry, uint32_t name, uint spdlog::debug("Failed to register manager"); } -void Taskbar::register_seat(struct wl_registry *registry, uint32_t name, uint32_t version) { +void Taskbar::register_seat(struct wl_registry* registry, uint32_t name, uint32_t version) { if (seat_) { spdlog::warn("Register seat again although already existing!"); return; } version = std::min(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) { +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_)); } @@ -935,14 +743,22 @@ void Taskbar::handle_finished() { manager_ = nullptr; } -void Taskbar::add_button(Gtk::Button &bt) { - box_.pack_start(bt, false, false); +void Taskbar::add_button(Gtk::Button& bt) { + /* Only let the buttons expand to fill the taskbar when "expand" is enabled + * and the bar is horizontal (see the Task constructor for details). */ + bool expand = config_["expand"].isBool() && config_["expand"].asBool(); + bool horizontal = bar_.orientation == Gtk::ORIENTATION_HORIZONTAL; + if (expand && horizontal) { + box_.pack_start(bt, true, true); + } else { + box_.pack_start(bt, false, false); + } box_.get_style_context()->remove_class("empty"); } -void Taskbar::move_button(Gtk::Button &bt, int pos) { box_.reorder_child(bt, pos); } +void Taskbar::move_button(Gtk::Button& bt, int pos) { box_.reorder_child(bt, pos); } -void Taskbar::remove_button(Gtk::Button &bt) { +void Taskbar::remove_button(Gtk::Button& bt) { box_.remove(bt); if (box_.get_children().empty()) { box_.get_style_context()->add_class("empty"); @@ -951,7 +767,7 @@ void Taskbar::remove_button(Gtk::Button &bt) { void Taskbar::remove_task(uint32_t id) { auto it = std::find_if(std::begin(tasks_), std::end(tasks_), - [id](const TaskPtr &p) { return p->id() == id; }); + [id](const TaskPtr& p) { return p->id() == id; }); if (it == std::end(tasks_)) { spdlog::warn("Can't find task with id {}", id); @@ -961,7 +777,7 @@ void Taskbar::remove_task(uint32_t id) { tasks_.erase(it); } -bool Taskbar::show_output(struct wl_output *output) const { +bool Taskbar::show_output(struct wl_output* output) const { return output == gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj()); } @@ -969,13 +785,11 @@ 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 IconLoader& Taskbar::icon_loader() const { return icon_loader_; } -const std::unordered_set &Taskbar::ignore_list() const { return ignore_list_; } +const std::unordered_set& Taskbar::ignore_list() const { return ignore_list_; } -const std::map &Taskbar::app_ids_replace_map() const { +const std::map& Taskbar::app_ids_replace_map() const { return app_ids_replace_map_; } diff --git a/src/modules/wlr/workspace_manager.cpp b/src/modules/wlr/workspace_manager.cpp deleted file mode 100644 index f556a161..00000000 --- a/src/modules/wlr/workspace_manager.cpp +++ /dev/null @@ -1,585 +0,0 @@ -#include "modules/wlr/workspace_manager.hpp" - -#include -#include -#include - -#include -#include -#include -#include - -#include "client.hpp" -#include "gtkmm/widget.h" -#include "modules/wlr/workspace_manager_binding.hpp" - -namespace waybar::modules::wlr { - -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, - const Json::Value &config) - : waybar::AModule(config, "workspaces", id, false, false), bar_(bar), box_(bar.orientation, 0) { - auto config_sort_by_name = config_["sort-by-name"]; - if (config_sort_by_name.isBool()) { - sort_by_name_ = config_sort_by_name.asBool(); - } - - auto config_sort_by_coordinates = config_["sort-by-coordinates"]; - if (config_sort_by_coordinates.isBool()) { - sort_by_coordinates_ = config_sort_by_coordinates.asBool(); - } - - auto config_sort_by_number = config_["sort-by-number"]; - if (config_sort_by_number.isBool()) { - sort_by_number_ = config_sort_by_number.asBool(); - } - - auto config_all_outputs = config_["all-outputs"]; - if (config_all_outputs.isBool()) { - all_outputs_ = config_all_outputs.asBool(); - } - - auto config_active_only = config_["active-only"]; - if (config_active_only.isBool()) { - active_only_ = config_active_only.asBool(); - creation_delayed_ = active_only_; - } - - box_.set_name("workspaces"); - if (!id.empty()) { - box_.get_style_context()->add_class(id); - } - box_.get_style_context()->add_class(MODULE_CLASS); - event_box_.add(box_); - - add_registry_listener(this); - if (!workspace_manager_) { - return; - } -} - -auto WorkspaceManager::workspace_comparator() const - -> std::function &, std::unique_ptr &)> { - return [=, this](std::unique_ptr &lhs, std::unique_ptr &rhs) { - auto is_name_less = lhs->get_name() < rhs->get_name(); - auto is_name_eq = lhs->get_name() == rhs->get_name(); - auto is_coords_less = lhs->get_coords() < rhs->get_coords(); - - if (sort_by_number_) { - try { - auto is_number_less = std::stoi(lhs->get_name()) < std::stoi(rhs->get_name()); - return is_number_less; - } catch (const std::invalid_argument &) { - } - } - - if (sort_by_name_) { - if (sort_by_coordinates_) { - return is_name_eq ? is_coords_less : is_name_less; - } else { - return is_name_less; - } - } - - if (sort_by_coordinates_) { - return is_coords_less; - } - - return lhs->id() < rhs->id(); - }; -} - -auto WorkspaceManager::sort_workspaces() -> void { - std::vector>> all_workspaces; - for (auto &group : groups_) { - auto &group_workspaces = group->workspaces(); - all_workspaces.reserve(all_workspaces.size() + - std::distance(group_workspaces.begin(), group_workspaces.end())); - if (!active_only()) { - all_workspaces.insert(all_workspaces.end(), group_workspaces.begin(), group_workspaces.end()); - continue; - } - - for (auto &workspace : group_workspaces) { - if (!workspace->is_active()) { - continue; - } - - all_workspaces.push_back(workspace); - } - } - - std::sort(all_workspaces.begin(), all_workspaces.end(), workspace_comparator()); - for (size_t i = 0; i < all_workspaces.size(); ++i) { - box_.reorder_child(all_workspaces[i].get()->get_button_ref(), i); - } -} - -auto WorkspaceManager::register_manager(wl_registry *registry, uint32_t name, uint32_t version) - -> void { - if (workspace_manager_) { - spdlog::warn("Register workspace manager again although already registered!"); - return; - } - if (version != 1) { - spdlog::warn("Using different workspace manager protocol version: {}", version); - } - workspace_manager_ = workspace_manager_bind(registry, name, version, this); -} - -auto WorkspaceManager::handle_workspace_group_create( - zext_workspace_group_handle_v1 *workspace_group_handle) -> void { - auto new_id = ++group_global_id; - groups_.push_back( - std::make_unique(bar_, box_, config_, *this, workspace_group_handle, new_id)); - spdlog::debug("Workspace group {} created", new_id); -} - -auto WorkspaceManager::handle_finished() -> void { - zext_workspace_manager_v1_destroy(workspace_manager_); - workspace_manager_ = nullptr; -} - -auto WorkspaceManager::handle_done() -> void { - for (auto &group : groups_) { - group->handle_done(); - } - dp.emit(); -} - -auto WorkspaceManager::update() -> void { - for (auto &group : groups_) { - group->update(); - } - if (creation_delayed()) { - creation_delayed_ = false; - sort_workspaces(); - } - AModule::update(); -} - -WorkspaceManager::~WorkspaceManager() { - if (!workspace_manager_) { - return; - } - - 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 workspace manager implementation. - zext_workspace_manager_v1_stop(workspace_manager_); - wl_display_roundtrip(display); - - // If the .finished handler is still not executed, destroy the workspace manager here. - if (workspace_manager_) { - spdlog::warn("Foreign toplevel manager destroyed before .finished event"); - zext_workspace_manager_v1_destroy(workspace_manager_); - workspace_manager_ = nullptr; - } -} - -auto WorkspaceManager::remove_workspace_group(uint32_t id) -> void { - auto it = std::find_if(groups_.begin(), groups_.end(), - [id](const std::unique_ptr &g) { return g->id() == id; }); - - if (it == groups_.end()) { - spdlog::warn("Can't find group with id {}", id); - return; - } - - groups_.erase(it); -} -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, - zext_workspace_group_handle_v1 *workspace_group_handle, uint32_t id) - : bar_(bar), - box_(box), - config_(config), - workspace_manager_(manager), - workspace_group_handle_(workspace_group_handle), - id_(id) { - add_workspace_group_listener(workspace_group_handle, this); -} - -auto WorkspaceGroup::fill_persistent_workspaces() -> void { - if (config_["persistent_workspaces"].isObject()) { - spdlog::warn( - "persistent_workspaces is deprecated. Please change config to use persistent-workspaces."); - } - - if ((config_["persistent-workspaces"].isObject() || - config_["persistent_workspaces"].isObject()) && - !workspace_manager_.all_outputs()) { - const Json::Value &p_workspaces = config_["persistent-workspaces"].isObject() - ? config_["persistent-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]; - if (p_w.isArray() && !p_w.empty()) { - // Adding to target outputs - for (const Json::Value &output : p_w) { - if (output.asString() == bar_.output->name) { - persistent_workspaces_.push_back(p_w_name); - break; - } - } - } else { - // Adding to all outputs - persistent_workspaces_.push_back(p_w_name); - } - } - } -} - -auto WorkspaceGroup::create_persistent_workspaces() -> void { - for (const std::string &p_w_name : persistent_workspaces_) { - auto new_id = ++workspace_global_id; - workspaces_.push_back( - std::make_unique(bar_, config_, *this, nullptr, new_id, p_w_name)); - spdlog::debug("Workspace {} created", new_id); - } -} - -auto WorkspaceGroup::active_only() const -> bool { return workspace_manager_.active_only(); } -auto WorkspaceGroup::creation_delayed() const -> bool { - return workspace_manager_.creation_delayed(); -} - -auto WorkspaceGroup::add_button(Gtk::Button &button) -> void { - box_.pack_start(button, false, false); -} - -WorkspaceGroup::~WorkspaceGroup() { - if (!workspace_group_handle_) { - return; - } - - zext_workspace_group_handle_v1_destroy(workspace_group_handle_); - workspace_group_handle_ = nullptr; -} - -auto WorkspaceGroup::handle_workspace_create(zext_workspace_handle_v1 *workspace) -> void { - auto new_id = ++workspace_global_id; - workspaces_.push_back(std::make_unique(bar_, config_, *this, workspace, new_id, "")); - spdlog::debug("Workspace {} created", new_id); - if (!persistent_created_) { - fill_persistent_workspaces(); - create_persistent_workspaces(); - persistent_created_ = true; - } -} - -auto WorkspaceGroup::handle_remove() -> void { - zext_workspace_group_handle_v1_destroy(workspace_group_handle_); - workspace_group_handle_ = nullptr; - workspace_manager_.remove_workspace_group(id_); -} - -auto WorkspaceGroup::handle_output_enter(wl_output *output) -> void { - spdlog::debug("Output {} assigned to {} group", (void *)output, id_); - output_ = output; - - if (!is_visible() || workspace_manager_.creation_delayed()) { - return; - } - - for (auto &workspace : workspaces_) { - add_button(workspace->get_button_ref()); - } -} - -auto WorkspaceGroup::is_visible() const -> bool { - return output_ != nullptr && - (workspace_manager_.all_outputs() || - output_ == gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj())); -} - -auto WorkspaceGroup::handle_output_leave() -> void { - spdlog::debug("Output {} remove from {} group", (void *)output_, id_); - output_ = nullptr; - - if (output_ != gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj())) { - return; - } - - for (auto &workspace : workspaces_) { - remove_button(workspace->get_button_ref()); - } -} - -auto WorkspaceGroup::update() -> void { - for (auto &workspace : workspaces_) { - if (workspace_manager_.creation_delayed()) { - add_button(workspace->get_button_ref()); - if (is_visible() && (workspace->is_active() || workspace->is_urgent())) { - workspace->show(); - } - } - - workspace->update(); - } -} - -auto WorkspaceGroup::remove_workspace(uint32_t id) -> void { - auto it = std::find_if(workspaces_.begin(), workspaces_.end(), - [id](const std::unique_ptr &w) { return w->id() == id; }); - - if (it == workspaces_.end()) { - spdlog::warn("Can't find workspace with id {}", id); - return; - } - - workspaces_.erase(it); -} - -auto WorkspaceGroup::handle_done() -> void { - need_to_sort = false; - if (!is_visible()) { - return; - } - - for (auto &workspace : workspaces_) { - workspace->handle_done(); - } - - if (creation_delayed()) { - return; - } - - if (!workspace_manager_.all_outputs()) { - sort_workspaces(); - } else { - workspace_manager_.sort_workspaces(); - } -} - -auto WorkspaceGroup::commit() -> void { workspace_manager_.commit(); } - -auto WorkspaceGroup::sort_workspaces() -> void { - std::sort(workspaces_.begin(), workspaces_.end(), workspace_manager_.workspace_comparator()); - for (size_t i = 0; i < workspaces_.size(); ++i) { - box_.reorder_child(workspaces_[i]->get_button_ref(), i); - } -} - -auto WorkspaceGroup::remove_button(Gtk::Button &button) -> void { box_.remove(button); } - -Workspace::Workspace(const Bar &bar, const Json::Value &config, WorkspaceGroup &workspace_group, - zext_workspace_handle_v1 *workspace, uint32_t id, std::string name) - : bar_(bar), - config_(config), - workspace_group_(workspace_group), - workspace_handle_(workspace), - id_(id), - name_(name) { - if (workspace) { - add_workspace_listener(workspace, this); - } else { - state_ = (uint32_t)State::EMPTY; - } - - auto config_format = config["format"]; - - format_ = config_format.isString() ? config_format.asString() : "{name}"; - with_icon_ = format_.find("{icon}") != std::string::npos; - - if (with_icon_ && icons_map_.empty()) { - auto format_icons = config["format-icons"]; - for (auto &name : format_icons.getMemberNames()) { - icons_map_.emplace(name, format_icons[name].asString()); - } - } - - /* 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, &Workspace::handle_clicked), - false); - } - - button_.set_relief(Gtk::RELIEF_NONE); - content_.set_center_widget(label_); - button_.add(content_); - - if (!workspace_group.is_visible()) { - return; - } - - workspace_group.add_button(button_); - button_.show_all(); -} - -Workspace::~Workspace() { - workspace_group_.remove_button(button_); - if (!workspace_handle_) { - return; - } - - zext_workspace_handle_v1_destroy(workspace_handle_); - workspace_handle_ = nullptr; -} - -auto Workspace::update() -> void { - label_.set_markup(fmt::format(fmt::runtime(format_), fmt::arg("name", name_), - fmt::arg("icon", with_icon_ ? get_icon() : ""))); -} - -auto Workspace::handle_state(const std::vector &state) -> void { - state_ = 0; - for (auto state_entry : state) { - switch (state_entry) { - case ZEXT_WORKSPACE_HANDLE_V1_STATE_ACTIVE: - state_ |= (uint32_t)State::ACTIVE; - break; - case ZEXT_WORKSPACE_HANDLE_V1_STATE_URGENT: - state_ |= (uint32_t)State::URGENT; - break; - case ZEXT_WORKSPACE_HANDLE_V1_STATE_HIDDEN: - state_ |= (uint32_t)State::HIDDEN; - break; - } - } -} - -auto Workspace::handle_remove() -> void { - if (workspace_handle_) { - zext_workspace_handle_v1_destroy(workspace_handle_); - workspace_handle_ = nullptr; - } - if (!persistent_) { - workspace_group_.remove_workspace(id_); - } else { - state_ = (uint32_t)State::EMPTY; - } -} - -auto add_or_remove_class(Glib::RefPtr context, bool condition, - const std::string &class_name) { - if (condition) { - context->add_class(class_name); - } else { - context->remove_class(class_name); - } -} - -auto Workspace::handle_done() -> void { - spdlog::debug("Workspace {} changed to state {}", id_, state_); - auto style_context = button_.get_style_context(); - add_or_remove_class(style_context, is_active(), "active"); - add_or_remove_class(style_context, is_urgent(), "urgent"); - add_or_remove_class(style_context, is_hidden(), "hidden"); - add_or_remove_class(style_context, is_empty(), "persistent"); - - if (workspace_group_.creation_delayed()) { - return; - } - - if (workspace_group_.active_only() && (is_active() || is_urgent())) { - button_.show_all(); - } else if (workspace_group_.active_only() && !(is_active() || is_urgent())) { - button_.hide(); - } -} - -auto Workspace::get_icon() -> std::string { - if (is_active()) { - auto active_icon_it = icons_map_.find("active"); - if (active_icon_it != icons_map_.end()) { - return active_icon_it->second; - } - } - - auto named_icon_it = icons_map_.find(name_); - if (named_icon_it != icons_map_.end()) { - return named_icon_it->second; - } - - if (is_empty()) { - auto persistent_icon_it = icons_map_.find("persistent"); - if (persistent_icon_it != icons_map_.end()) { - return persistent_icon_it->second; - } - } - - auto default_icon_it = icons_map_.find("default"); - if (default_icon_it != icons_map_.end()) { - return default_icon_it->second; - } - - return name_; -} - -auto Workspace::handle_clicked(GdkEventButton *bt) -> bool { - 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; - else if (action == "activate") { - zext_workspace_handle_v1_activate(workspace_handle_); - } else if (action == "close") { - zext_workspace_handle_v1_remove(workspace_handle_); - } else { - spdlog::warn("Unknown action {}", action); - } - - workspace_group_.commit(); - - return true; -} - -auto Workspace::show() -> void { button_.show_all(); } -auto Workspace::hide() -> void { button_.hide(); } - -auto Workspace::handle_name(const std::string &name) -> void { - if (name_ != name) { - workspace_group_.set_need_to_sort(); - } - name_ = name; - spdlog::debug("Workspace {} added to group {}", name, workspace_group_.id()); - - make_persistent(); - handle_duplicate(); -} - -auto Workspace::make_persistent() -> void { - auto p_workspaces = workspace_group_.persistent_workspaces(); - - if (std::find(p_workspaces.begin(), p_workspaces.end(), name_) != p_workspaces.end()) { - persistent_ = true; - } -} - -auto Workspace::handle_duplicate() -> void { - auto duplicate = - std::find_if(workspace_group_.workspaces().begin(), workspace_group_.workspaces().end(), - [this](const std::unique_ptr &g) { - return g->get_name() == name_ && g->id() != id_; - }); - if (duplicate != workspace_group_.workspaces().end()) { - workspace_group_.remove_workspace(duplicate->get()->id()); - } -} - -auto Workspace::handle_coordinates(const std::vector &coordinates) -> void { - if (coordinates_ != coordinates) { - workspace_group_.set_need_to_sort(); - } - coordinates_ = coordinates; -} -} // namespace waybar::modules::wlr diff --git a/src/modules/wlr/workspace_manager_binding.cpp b/src/modules/wlr/workspace_manager_binding.cpp deleted file mode 100644 index 22e68fbf..00000000 --- a/src/modules/wlr/workspace_manager_binding.cpp +++ /dev/null @@ -1,136 +0,0 @@ -#include "modules/wlr/workspace_manager_binding.hpp" - -#include - -#include - -#include "client.hpp" -#include "modules/wlr/workspace_manager.hpp" - -namespace waybar::modules::wlr { - -static void handle_global(void *data, wl_registry *registry, uint32_t name, const char *interface, - uint32_t version) { - if (std::strcmp(interface, zext_workspace_manager_v1_interface.name) == 0) { - static_cast(data)->register_manager(registry, name, version); - } -} - -static void handle_global_remove(void *data, wl_registry *registry, uint32_t name) { - /* Nothing to do here */ -} - -static const wl_registry_listener registry_listener_impl = {.global = handle_global, - .global_remove = handle_global_remove}; - -void add_registry_listener(void *data) { - wl_display *display = Client::inst()->wl_display; - wl_registry *registry = wl_display_get_registry(display); - - wl_registry_add_listener(registry, ®istry_listener_impl, data); - wl_display_roundtrip(display); - wl_display_roundtrip(display); -} - -static void workspace_manager_handle_workspace_group( - void *data, zext_workspace_manager_v1 *_, zext_workspace_group_handle_v1 *workspace_group) { - static_cast(data)->handle_workspace_group_create(workspace_group); -} - -static void workspace_manager_handle_done(void *data, zext_workspace_manager_v1 *_) { - static_cast(data)->handle_done(); -} - -static void workspace_manager_handle_finished(void *data, zext_workspace_manager_v1 *_) { - static_cast(data)->handle_finished(); -} - -static const zext_workspace_manager_v1_listener workspace_manager_impl = { - .workspace_group = workspace_manager_handle_workspace_group, - .done = workspace_manager_handle_done, - .finished = workspace_manager_handle_finished, -}; - -zext_workspace_manager_v1 *workspace_manager_bind(wl_registry *registry, uint32_t name, - uint32_t version, void *data) { - auto *workspace_manager = static_cast( - wl_registry_bind(registry, name, &zext_workspace_manager_v1_interface, version)); - - if (workspace_manager) - zext_workspace_manager_v1_add_listener(workspace_manager, &workspace_manager_impl, data); - else - spdlog::error("Failed to register manager"); - - return workspace_manager; -} - -static void workspace_group_handle_output_enter(void *data, zext_workspace_group_handle_v1 *_, - wl_output *output) { - static_cast(data)->handle_output_enter(output); -} - -static void workspace_group_handle_output_leave(void *data, zext_workspace_group_handle_v1 *_, - wl_output *output) { - static_cast(data)->handle_output_leave(); -} - -static void workspace_group_handle_workspace(void *data, zext_workspace_group_handle_v1 *_, - zext_workspace_handle_v1 *workspace) { - static_cast(data)->handle_workspace_create(workspace); -} - -static void workspace_group_handle_remove(void *data, zext_workspace_group_handle_v1 *_) { - static_cast(data)->handle_remove(); -} - -static const zext_workspace_group_handle_v1_listener workspace_group_impl = { - .output_enter = workspace_group_handle_output_enter, - .output_leave = workspace_group_handle_output_leave, - .workspace = workspace_group_handle_workspace, - .remove = workspace_group_handle_remove}; - -void add_workspace_group_listener(zext_workspace_group_handle_v1 *workspace_group_handle, - void *data) { - zext_workspace_group_handle_v1_add_listener(workspace_group_handle, &workspace_group_impl, data); -} - -void workspace_handle_name(void *data, struct zext_workspace_handle_v1 *_, const char *name) { - static_cast(data)->handle_name(name); -} - -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); - for (size_t i = 0; i < coordinates->size / sizeof(uint32_t); ++i) { - coords_vec.push_back(coords[i]); - } - - static_cast(data)->handle_coordinates(coords_vec); -} - -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); - for (size_t i = 0; i < state->size / sizeof(uint32_t); ++i) { - state_vec.push_back(states[i]); - } - - static_cast(data)->handle_state(state_vec); -} - -void workspace_handle_remove(void *data, struct zext_workspace_handle_v1 *_) { - static_cast(data)->handle_remove(); -} - -static const zext_workspace_handle_v1_listener workspace_impl = { - .name = workspace_handle_name, - .coordinates = workspace_handle_coordinates, - .state = workspace_handle_state, - .remove = workspace_handle_remove}; - -void add_workspace_listener(zext_workspace_handle_v1 *workspace_handle, void *data) { - zext_workspace_handle_v1_add_listener(workspace_handle, &workspace_impl, data); -} -} // namespace waybar::modules::wlr diff --git a/src/util/audio_backend.cpp b/src/util/audio_backend.cpp index 860168fd..96a5bdb4 100644 --- a/src/util/audio_backend.cpp +++ b/src/util/audio_backend.cpp @@ -40,12 +40,16 @@ AudioBackend::AudioBackend(std::function on_updated_cb, private_construc } AudioBackend::~AudioBackend() { - if (context_ != nullptr) { - pa_context_disconnect(context_); - } - if (mainloop_ != nullptr) { - mainloop_api_->quit(mainloop_api_, 0); + // Lock the mainloop so we can safely disconnect the context. + // This must be done before stopping the thread. + pa_threaded_mainloop_lock(mainloop_); + if (context_ != nullptr) { + pa_context_disconnect(context_); + pa_context_unref(context_); + context_ = nullptr; + } + pa_threaded_mainloop_unlock(mainloop_); pa_threaded_mainloop_stop(mainloop_); pa_threaded_mainloop_free(mainloop_); } @@ -69,11 +73,18 @@ void AudioBackend::connectContext() { } } -void AudioBackend::contextStateCb(pa_context *c, void *data) { - auto *backend = static_cast(data); +void AudioBackend::contextStateCb(pa_context* c, void* data) { + auto* backend = static_cast(data); switch (pa_context_get_state(c)) { case PA_CONTEXT_TERMINATED: - backend->mainloop_api_->quit(backend->mainloop_api_, 0); + // Only quit the mainloop if this is still the active context. + // During reconnection, the old context fires TERMINATED after the new one + // has already been created; quitting in that case would kill the new context. + // Note: context_ is only written from PA callbacks (while the mainloop lock is + // held), so this comparison is safe within any PA callback. + if (backend->context_ == nullptr || backend->context_ == c) { + backend->mainloop_api_->quit(backend->mainloop_api_, 0); + } break; case PA_CONTEXT_READY: pa_context_get_server_info(c, serverInfoCb, data); @@ -88,13 +99,17 @@ void AudioBackend::contextStateCb(pa_context *c, void *data) { nullptr, nullptr); break; case PA_CONTEXT_FAILED: - // When pulseaudio server restarts, the connection is "failed". Try to reconnect. - // pa_threaded_mainloop_lock is already acquired in callback threads. - // So there is no need to lock it again. - if (backend->context_ != nullptr) { - pa_context_disconnect(backend->context_); + if (pa_context_errno(c) != PA_ERR_CONNECTIONREFUSED) { + // When pulseaudio server restarts, the connection is "failed". Try to reconnect. + // pa_threaded_mainloop_lock is already acquired in callback threads. + // So there is no need to lock it again. + if (backend->context_ != nullptr) { + pa_context_disconnect(backend->context_); + pa_context_unref(backend->context_); + backend->context_ = nullptr; + } + backend->connectContext(); } - backend->connectContext(); break; case PA_CONTEXT_CONNECTING: case PA_CONTEXT_AUTHORIZING: @@ -107,8 +122,8 @@ void AudioBackend::contextStateCb(pa_context *c, void *data) { /* * Called when an event we subscribed to occurs. */ -void AudioBackend::subscribeCb(pa_context *context, pa_subscription_event_type_t type, uint32_t idx, - void *data) { +void AudioBackend::subscribeCb(pa_context* context, pa_subscription_event_type_t type, uint32_t idx, + void* data) { unsigned facility = type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK; unsigned operation = type & PA_SUBSCRIPTION_EVENT_TYPE_MASK; if (operation != PA_SUBSCRIPTION_EVENT_CHANGE) { @@ -130,8 +145,8 @@ void AudioBackend::subscribeCb(pa_context *context, pa_subscription_event_type_t /* * Called in response to a volume change request */ -void AudioBackend::volumeModifyCb(pa_context *c, int success, void *data) { - auto *backend = static_cast(data); +void AudioBackend::volumeModifyCb(pa_context* c, int success, void* data) { + auto* backend = static_cast(data); if (success != 0) { if ((backend->context_ != nullptr) && pa_context_get_state(backend->context_) == PA_CONTEXT_READY) { @@ -145,18 +160,18 @@ void AudioBackend::volumeModifyCb(pa_context *c, int success, void *data) { /* * Called when the requested sink information is ready. */ -void AudioBackend::sinkInfoCb(pa_context * /*context*/, const pa_sink_info *i, int /*eol*/, - void *data) { +void AudioBackend::sinkInfoCb(pa_context* /*context*/, const pa_sink_info* i, int /*eol*/, + void* data) { if (i == nullptr) return; auto running = i->state == PA_SINK_RUNNING; auto idle = i->state == PA_SINK_IDLE; spdlog::trace("Sink name {} Running:[{}] Idle:[{}]", i->name, running, idle); - auto *backend = static_cast(data); + auto* backend = static_cast(data); if (!backend->ignored_sinks_.empty()) { - for (const auto &ignored_sink : backend->ignored_sinks_) { + for (const auto& ignored_sink : backend->ignored_sinks_) { if (ignored_sink == i->description) { if (i->name == backend->current_sink_name_) { // If the current sink happens to be ignored it is never considered running @@ -205,7 +220,7 @@ void AudioBackend::sinkInfoCb(pa_context * /*context*/, const pa_sink_info *i, i backend->desc_ = i->description; backend->monitor_ = i->monitor_source_name; backend->port_name_ = i->active_port != nullptr ? i->active_port->name : "Unknown"; - if (const auto *ff = pa_proplist_gets(i->proplist, PA_PROP_DEVICE_FORM_FACTOR)) { + if (const auto* ff = pa_proplist_gets(i->proplist, PA_PROP_DEVICE_FORM_FACTOR)) { backend->form_factor_ = ff; } else { backend->form_factor_ = ""; @@ -217,9 +232,9 @@ void AudioBackend::sinkInfoCb(pa_context * /*context*/, const pa_sink_info *i, i /* * Called when the requested source information is ready. */ -void AudioBackend::sourceInfoCb(pa_context * /*context*/, const pa_source_info *i, int /*eol*/, - void *data) { - auto *backend = static_cast(data); +void AudioBackend::sourceInfoCb(pa_context* /*context*/, const pa_source_info* i, int /*eol*/, + void* data) { + auto* backend = static_cast(data); if (i != nullptr && backend->default_source_name_ == i->name) { auto source_volume = static_cast(pa_cvolume_avg(&(i->volume))) / float{PA_VOLUME_NORM}; backend->source_volume_ = std::round(source_volume * 100.0F); @@ -235,16 +250,25 @@ void AudioBackend::sourceInfoCb(pa_context * /*context*/, const pa_source_info * * Called when the requested information on the server is ready. This is * used to find the default PulseAudio sink. */ -void AudioBackend::serverInfoCb(pa_context *context, const pa_server_info *i, void *data) { - auto *backend = static_cast(data); - backend->current_sink_name_ = i->default_sink_name; - backend->default_sink_name = i->default_sink_name; - backend->default_source_name_ = i->default_source_name; +void AudioBackend::serverInfoCb(pa_context* context, const pa_server_info* i, void* data) { + auto* backend = static_cast(data); + if (i == nullptr) return; + backend->current_sink_name_ = i->default_sink_name ? i->default_sink_name : ""; + backend->default_sink_name = i->default_sink_name ? i->default_sink_name : ""; + backend->default_source_name_ = i->default_source_name ? i->default_source_name : ""; pa_context_get_sink_info_list(context, sinkInfoCb, data); pa_context_get_source_info_list(context, sourceInfoCb, data); } +uint16_t AudioBackend::getVolume(PulseaudioTarget target) const { + if (target == PulseaudioTarget::Source) { + return source_volume_; + } else { + return volume_; + } +} + void AudioBackend::changeVolume(uint16_t volume, uint16_t min_volume, uint16_t max_volume) { // Early return if context is not ready if ((context_ == nullptr) || pa_context_get_state(context_) != PA_CONTEXT_READY) { @@ -354,7 +378,16 @@ void AudioBackend::changeVolume(ChangeType change_type, double step, uint16_t ma pa_threaded_mainloop_unlock(mainloop_); } +bool AudioBackend::getMuted(PulseaudioTarget target) const { + if (target == PulseaudioTarget::Source) { + return source_muted_; + } else { + return muted_; + } +} + void AudioBackend::toggleSinkMute() { + if (context_ == nullptr || pa_context_get_state(context_) != PA_CONTEXT_READY) return; muted_ = !muted_; pa_threaded_mainloop_lock(mainloop_); pa_context_set_sink_mute_by_index(context_, sink_idx_, static_cast(muted_), nullptr, @@ -363,6 +396,7 @@ void AudioBackend::toggleSinkMute() { } void AudioBackend::toggleSinkMute(bool mute) { + if (context_ == nullptr || pa_context_get_state(context_) != PA_CONTEXT_READY) return; muted_ = mute; pa_threaded_mainloop_lock(mainloop_); pa_context_set_sink_mute_by_index(context_, sink_idx_, static_cast(muted_), nullptr, @@ -371,7 +405,8 @@ void AudioBackend::toggleSinkMute(bool mute) { } void AudioBackend::toggleSourceMute() { - source_muted_ = !muted_; + if (context_ == nullptr || pa_context_get_state(context_) != PA_CONTEXT_READY) return; + source_muted_ = !source_muted_; pa_threaded_mainloop_lock(mainloop_); pa_context_set_source_mute_by_index(context_, source_idx_, static_cast(source_muted_), nullptr, nullptr); @@ -379,6 +414,7 @@ void AudioBackend::toggleSourceMute() { } void AudioBackend::toggleSourceMute(bool mute) { + if (context_ == nullptr || pa_context_get_state(context_) != PA_CONTEXT_READY) return; source_muted_ = mute; pa_threaded_mainloop_lock(mainloop_); pa_context_set_source_mute_by_index(context_, source_idx_, static_cast(source_muted_), @@ -386,15 +422,23 @@ void AudioBackend::toggleSourceMute(bool mute) { pa_threaded_mainloop_unlock(mainloop_); } +void AudioBackend::unmute(PulseaudioTarget target) { + if (target == PulseaudioTarget::Source) { + toggleSourceMute(false); + } else { + toggleSinkMute(false); + } +} + bool AudioBackend::isBluetooth() { return monitor_.find("a2dp_sink") != std::string::npos || // PulseAudio monitor_.find("a2dp-sink") != std::string::npos || // PipeWire monitor_.find("bluez") != std::string::npos; } -void AudioBackend::setIgnoredSinks(const Json::Value &config) { +void AudioBackend::setIgnoredSinks(const Json::Value& config) { if (config.isArray()) { - for (const auto &ignored_sink : config) { + for (const auto& ignored_sink : config) { if (ignored_sink.isString()) { ignored_sinks_.push_back(ignored_sink.asString()); } diff --git a/src/util/backlight_backend.cpp b/src/util/backlight_backend.cpp index 863896d5..61eb9b43 100644 --- a/src/util/backlight_backend.cpp +++ b/src/util/backlight_backend.cpp @@ -8,14 +8,16 @@ #include #include +#include "util/udev_deleter.hpp" + namespace { class FileDescriptor { public: explicit FileDescriptor(int fd) : fd_(fd) {} - FileDescriptor(const FileDescriptor &other) = delete; - FileDescriptor(FileDescriptor &&other) noexcept = delete; - FileDescriptor &operator=(const FileDescriptor &other) = delete; - FileDescriptor &operator=(FileDescriptor &&other) noexcept = delete; + FileDescriptor(const FileDescriptor& other) = delete; + FileDescriptor(FileDescriptor&& other) noexcept = delete; + FileDescriptor& operator=(const FileDescriptor& other) = delete; + FileDescriptor& operator=(FileDescriptor&& other) noexcept = delete; ~FileDescriptor() { if (fd_ != -1) { if (close(fd_) != 0) { @@ -29,43 +31,27 @@ class FileDescriptor { int fd_; }; -struct UdevDeleter { - void operator()(udev *ptr) { udev_unref(ptr); } -}; - -struct UdevDeviceDeleter { - void operator()(udev_device *ptr) { udev_device_unref(ptr); } -}; - -struct UdevEnumerateDeleter { - void operator()(udev_enumerate *ptr) { udev_enumerate_unref(ptr); } -}; - -struct UdevMonitorDeleter { - void operator()(udev_monitor *ptr) { udev_monitor_unref(ptr); } -}; - -void check_eq(int rc, int expected, const char *message = "eq, rc was: ") { +void check_eq(int rc, int expected, const char* message = "eq, rc was: ") { if (rc != expected) { throw std::runtime_error(fmt::format(fmt::runtime(message), rc)); } } -void check_neq(int rc, int bad_rc, const char *message = "neq, rc was: ") { +void check_neq(int rc, int bad_rc, const char* message = "neq, rc was: ") { if (rc == bad_rc) { throw std::runtime_error(fmt::format(fmt::runtime(message), rc)); } } -void check0(int rc, const char *message = "rc wasn't 0") { check_eq(rc, 0, message); } +void check0(int rc, const char* message = "rc wasn't 0") { check_eq(rc, 0, message); } -void check_gte(int rc, int gte, const char *message = "rc was: ") { +void check_gte(int rc, int gte, const char* message = "rc was: ") { if (rc < gte) { throw std::runtime_error(fmt::format(fmt::runtime(message), rc)); } } -void check_nn(const void *ptr, const char *message = "ptr was null") { +void check_nn(const void* ptr, const char* message = "ptr was null") { if (ptr == nullptr) { throw std::runtime_error(message); } @@ -75,48 +61,68 @@ void check_nn(const void *ptr, const char *message = "ptr was null") { namespace waybar::util { -static void upsert_device(std::vector &devices, udev_device *dev) { - const char *name = udev_device_get_sysname(dev); +static void upsert_device(std::vector& devices, udev_device* dev) { + const char* name = udev_device_get_sysname(dev); check_nn(name); - const char *actual_brightness_attr = + const char* actual_brightness_attr = strncmp(name, "amdgpu_bl", 9) == 0 || strcmp(name, "apple-panel-bl") == 0 ? "brightness" : "actual_brightness"; - const char *actual = udev_device_get_sysattr_value(dev, actual_brightness_attr); - const char *max = udev_device_get_sysattr_value(dev, "max_brightness"); - const char *power = udev_device_get_sysattr_value(dev, "bl_power"); + const char* actual = udev_device_get_sysattr_value(dev, actual_brightness_attr); + const char* max = udev_device_get_sysattr_value(dev, "max_brightness"); + const char* power = udev_device_get_sysattr_value(dev, "bl_power"); - auto found = std::find_if(devices.begin(), devices.end(), [name](const BacklightDevice &device) { + auto found = std::find_if(devices.begin(), devices.end(), [name](const BacklightDevice& device) { return device.name() == name; }); if (found != devices.end()) { if (actual != nullptr) { - found->set_actual(std::stoi(actual)); + try { + found->set_actual(std::stoi(actual)); + } catch (const std::exception&) { + } } if (max != nullptr) { - found->set_max(std::stoi(max)); + try { + found->set_max(std::stoi(max)); + } catch (const std::exception&) { + } } if (power != nullptr) { - found->set_powered(std::stoi(power) == 0); + try { + found->set_powered(std::stoi(power) == 0); + } catch (const std::exception&) { + } } } else { - const int actual_int = actual == nullptr ? 0 : std::stoi(actual); - const int max_int = max == nullptr ? 0 : std::stoi(max); - const bool power_bool = power == nullptr ? true : std::stoi(power) == 0; + int actual_int = 0, max_int = 0; + bool power_bool = true; + try { + if (actual != nullptr) actual_int = std::stoi(actual); + } catch (const std::exception&) { + } + try { + if (max != nullptr) max_int = std::stoi(max); + } catch (const std::exception&) { + } + try { + if (power != nullptr) power_bool = std::stoi(power) == 0; + } catch (const std::exception&) { + } devices.emplace_back(name, actual_int, max_int, power_bool); } } -static void enumerate_devices(std::vector &devices, udev *udev) { +static void enumerate_devices(std::vector& devices, udev* udev) { std::unique_ptr enumerate{udev_enumerate_new(udev)}; udev_enumerate_add_match_subsystem(enumerate.get(), "backlight"); udev_enumerate_scan_devices(enumerate.get()); - udev_list_entry *enum_devices = udev_enumerate_get_list_entry(enumerate.get()); - udev_list_entry *dev_list_entry; + udev_list_entry* enum_devices = udev_enumerate_get_list_entry(enumerate.get()); + udev_list_entry* dev_list_entry; udev_list_entry_foreach(dev_list_entry, enum_devices) { - const char *path = udev_list_entry_get_name(dev_list_entry); + const char* path = udev_list_entry_get_name(dev_list_entry); std::unique_ptr dev{udev_device_new_from_syspath(udev, path)}; check_nn(dev.get(), "dev new failed"); upsert_device(devices, dev.get()); @@ -198,10 +204,12 @@ BacklightBackend::BacklightBackend(std::chrono::milliseconds interval, devices = devices_; } for (int i = 0; i < event_count; ++i) { - const auto &event = events[i]; + const auto& event = events[i]; check_eq(event.data.fd, udev_fd, "unexpected udev fd"); std::unique_ptr dev{udev_monitor_receive_device(mon.get())}; - check_nn(dev.get(), "epoll dev was null"); + if (!dev) { + continue; + } upsert_device(devices, dev.get()); } @@ -218,27 +226,27 @@ BacklightBackend::BacklightBackend(std::chrono::milliseconds interval, }; } -const BacklightDevice *BacklightBackend::best_device(const std::vector &devices, +const BacklightDevice* BacklightBackend::best_device(const std::vector& devices, std::string_view preferred_device) { const auto found = std::find_if( devices.begin(), devices.end(), - [preferred_device](const BacklightDevice &dev) { return dev.name() == preferred_device; }); + [preferred_device](const BacklightDevice& dev) { return dev.name() == preferred_device; }); if (found != devices.end()) { return &(*found); } const auto max = std::max_element( devices.begin(), devices.end(), - [](const BacklightDevice &l, const BacklightDevice &r) { return l.get_max() < r.get_max(); }); + [](const BacklightDevice& l, const BacklightDevice& r) { return l.get_max() < r.get_max(); }); return max == devices.end() ? nullptr : &(*max); } -const BacklightDevice *BacklightBackend::get_previous_best_device() { +const BacklightDevice* BacklightBackend::get_previous_best_device() { return previous_best_.has_value() ? &(*previous_best_) : nullptr; } -void BacklightBackend::set_previous_best_device(const BacklightDevice *device) { +void BacklightBackend::set_previous_best_device(const BacklightDevice* device) { if (device == nullptr) { previous_best_ = std::nullopt; } else { @@ -246,7 +254,7 @@ void BacklightBackend::set_previous_best_device(const BacklightDevice *device) { } } -void BacklightBackend::set_scaled_brightness(const std::string &preferred_device, int brightness) { +void BacklightBackend::set_scaled_brightness(const std::string& preferred_device, int brightness) { GET_BEST_DEVICE(best, (*this), preferred_device); if (best != nullptr) { @@ -256,7 +264,7 @@ void BacklightBackend::set_scaled_brightness(const std::string &preferred_device } } -void BacklightBackend::set_brightness(const std::string &preferred_device, ChangeType change_type, +void BacklightBackend::set_brightness(const std::string& preferred_device, ChangeType change_type, double step) { GET_BEST_DEVICE(best, (*this), preferred_device); @@ -271,8 +279,13 @@ void BacklightBackend::set_brightness(const std::string &preferred_device, Chang } } -void BacklightBackend::set_brightness_internal(const std::string &device_name, int brightness, +void BacklightBackend::set_brightness_internal(const std::string& device_name, int brightness, int max_brightness) { + if (!login_proxy_) { + spdlog::error("Login proxy not available, cannot set brightness"); + return; + } + brightness = std::clamp(brightness, 0, max_brightness); auto call_args = Glib::VariantContainerBase( @@ -281,11 +294,12 @@ void BacklightBackend::set_brightness_internal(const std::string &device_name, i login_proxy_->call_sync("SetBrightness", call_args); } -int BacklightBackend::get_scaled_brightness(const std::string &preferred_device) { +int BacklightBackend::get_scaled_brightness(const std::string& preferred_device) { GET_BEST_DEVICE(best, (*this), preferred_device); if (best != nullptr) { - return best->get_actual() * 100 / best->get_max(); + if (best->get_max() == 0) return 0; + return static_cast(std::round(best->get_actual() * 100.0F / best->get_max())); } return 0; diff --git a/src/util/css_reload_helper.cpp b/src/util/css_reload_helper.cpp index 274bdeed..9c7b8a1f 100644 --- a/src/util/css_reload_helper.cpp +++ b/src/util/css_reload_helper.cpp @@ -2,7 +2,13 @@ #include #include +#ifndef __OpenBSD__ #include +#else +#include +#include +#include +#endif #include #include @@ -17,7 +23,8 @@ namespace { const std::regex IMPORT_REGEX(R"(@import\s+(?:url\()?(?:"|')([^"')]+)(?:"|')\)?;)"); } -waybar::CssReloadHelper::CssReloadHelper(std::string cssFile, std::function callback) +waybar::CssReloadHelper::CssReloadHelper(std::string cssFile, + std::function callback) : m_cssFile(std::move(cssFile)), m_callback(std::move(callback)) {} std::string waybar::CssReloadHelper::getFileContents(const std::string& filename) { @@ -82,6 +89,12 @@ void waybar::CssReloadHelper::monitorChanges() { } } +void waybar::CssReloadHelper::changeCssFile(const std::string& newCssFile) { + m_fileMonitors.clear(); + m_cssFile = newCssFile; + monitorChanges(); +} + void waybar::CssReloadHelper::handleFileChange(Glib::RefPtr const& file, Glib::RefPtr const& other_type, Gio::FileMonitorEvent event_type) { @@ -89,7 +102,7 @@ void waybar::CssReloadHelper::handleFileChange(Glib::RefPtr const& fi // fire for one if (event_type == Gio::FileMonitorEvent::FILE_MONITOR_EVENT_CHANGES_DONE_HINT) { spdlog::debug("Reloading style, file changed: {}", file->get_path()); - m_callback(); + m_callback(m_cssFile); } } @@ -109,11 +122,15 @@ std::vector waybar::CssReloadHelper::parseImports(const std::string auto maxIterations = 100U; do { previousSize = imports.size(); + std::vector to_parse; for (const auto& [file, parsed] : imports) { if (!parsed) { - parseImports(file, imports); + to_parse.push_back(file); } } + for (const auto& file : to_parse) { + parseImports(file, imports); + } } while (imports.size() > previousSize && maxIterations-- > 0); diff --git a/src/util/enum.cpp b/src/util/enum.cpp index dc3eae0c..6b5d5562 100644 --- a/src/util/enum.cpp +++ b/src/util/enum.cpp @@ -41,5 +41,7 @@ EnumType EnumParser::parseStringToEnum(const std::string& str, // Explicit instantiations for specific EnumType types you intend to use // Add explicit instantiations for all relevant EnumType types template struct EnumParser; +template struct EnumParser; +template struct EnumParser; } // namespace waybar::util diff --git a/src/util/gtk_icon.cpp b/src/util/gtk_icon.cpp index 5dd741f9..1b2fca57 100644 --- a/src/util/gtk_icon.cpp +++ b/src/util/gtk_icon.cpp @@ -15,11 +15,23 @@ bool DefaultGtkIconThemeWrapper::has_icon(const std::string& value) { return Gtk::IconTheme::get_default()->has_icon(value); } -Glib::RefPtr DefaultGtkIconThemeWrapper::load_icon(const char* name, int tmp_size, - Gtk::IconLookupFlags flags) { +Glib::RefPtr DefaultGtkIconThemeWrapper::load_icon( + const char* name, int tmp_size, Gtk::IconLookupFlags flags, + Glib::RefPtr style) { const std::lock_guard lock(default_theme_mutex); auto default_theme = Gtk::IconTheme::get_default(); - default_theme->rescan_if_needed(); - return default_theme->load_icon(name, tmp_size, flags); + + auto icon_info = default_theme->lookup_icon(name, tmp_size, flags); + + if (icon_info == nullptr) { + return default_theme->load_icon(name, tmp_size, flags); + } + + if (style.get() == nullptr) { + return icon_info.load_icon(); + } + + bool is_sym = false; + return icon_info.load_symbolic(style, is_sym); } diff --git a/src/util/icon_loader.cpp b/src/util/icon_loader.cpp new file mode 100644 index 00000000..1d0bd067 --- /dev/null +++ b/src/util/icon_loader.cpp @@ -0,0 +1,210 @@ +#include "util/icon_loader.hpp" + +#include "util/string.hpp" + +std::vector IconLoader::search_prefix() { + std::vector prefixes = {""}; + + const char* home_env = std::getenv("HOME"); + std::string home_dir = home_env ? home_env : ""; + if (!home_dir.empty()) { + prefixes.push_back(home_dir + "/.local/share/"); + } + + auto xdg_data_dirs = std::getenv("XDG_DATA_DIRS"); + if (!xdg_data_dirs) { + 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; + size_t 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) + "/"); + + start = end == std::string::npos ? end : end + 1; + } while (end != std::string::npos); + } + + for (auto& p : prefixes) spdlog::debug("Using 'desktop' search path prefix: {}", p); + + return prefixes; +} + +Glib::RefPtr IconLoader::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 suffixes = {"", ".desktop"}; + + for (auto const& prefix : prefixes) { + for (auto const& folder : app_folders) { + for (auto const& suffix : suffixes) { + auto app_info_ = + Gio::DesktopAppInfo::create_from_filename(prefix + folder + app_id + suffix); + if (!app_info_) { + continue; + } + + return app_info_; + } + } + } + + return {}; +} + +Glib::RefPtr IconLoader::get_desktop_app_info(const std::string& app_id) { + auto app_info = get_app_info_by_name(app_id); + if (app_info) { + return app_info; + } + + 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]); + if (!tmp_info) + // see https://github.com/Alexays/Waybar/issues/1446 + continue; + + auto startup_class = tmp_info->get_startup_wm_class(); + 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); +} + +Glib::RefPtr IconLoader::load_icon_from_file(std::string const& icon_path, int size) { + try { + auto pb = Gdk::Pixbuf::create_from_file(icon_path, size, size); + return pb; + } catch (...) { + return {}; + } +} + +std::string IconLoader::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; + + return ""; +} + +bool IconLoader::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(); + } + } + } + + Glib::RefPtr pixbuf; + auto scaled_icon_size = size * image.get_scale_factor(); + + try { + pixbuf = icon_theme->load_icon(ret_icon_name, scaled_icon_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, scaled_icon_size); + } else { + try { + pixbuf = DefaultGtkIconThemeWrapper::load_icon( + "image-missing", scaled_icon_size, Gtk::IconLookupFlags::ICON_LOOKUP_FORCE_SIZE); + } catch (...) { + pixbuf = {}; + } + } + } + + if (pixbuf) { + if (pixbuf->get_width() != scaled_icon_size && pixbuf->get_height() > 0) { + int width = scaled_icon_size * pixbuf->get_width() / pixbuf->get_height(); + pixbuf = pixbuf->scale_simple(width, scaled_icon_size, Gdk::InterpType::INTERP_BILINEAR); + } + auto surface = Gdk::Cairo::create_surface_from_pixbuf(pixbuf, image.get_scale_factor(), + image.get_window()); + image.set(surface); + return true; + } + + return false; +} + +void IconLoader::add_custom_icon_theme(const std::string& theme_name) { + auto icon_theme = Gtk::IconTheme::create(); + icon_theme->set_custom_theme(theme_name); + custom_icon_themes_.push_back(icon_theme); + spdlog::debug("Use custom icon theme: {}", theme_name); +} + +bool IconLoader::image_load_icon(Gtk::Image& image, Glib::RefPtr app_info, + int size) const { + for (auto& icon_theme : custom_icon_themes_) { + if (image_load_icon(image, icon_theme, app_info, size)) { + return true; + } + } + return image_load_icon(image, default_icon_theme_, app_info, size); +} + +Glib::RefPtr IconLoader::get_app_info_from_app_id_list( + const std::string& app_id_list) { + std::string app_id; + std::istringstream stream(app_id_list); + Glib::RefPtr 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 app_info_; + } + + auto lower_app_id = app_id; + std::ranges::transform(lower_app_id, lower_app_id.begin(), + [](char c) { return std::tolower(c); }); + app_info_ = get_desktop_app_info(lower_app_id); + if (app_info_) { + return app_info_; + } + + 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 app_info_; + } + + start = app_id.find("-"); + app_name = app_id.substr(0, start); + app_info_ = get_desktop_app_info(app_name); + } + return app_info_; +} diff --git a/src/util/pipewire/pipewire_backend.cpp b/src/util/pipewire/pipewire_backend.cpp index 6d859a91..82ec0c0f 100644 --- a/src/util/pipewire/pipewire_backend.cpp +++ b/src/util/pipewire/pipewire_backend.cpp @@ -4,11 +4,11 @@ namespace waybar::util::PipewireBackend { -static void getNodeInfo(void *data_, const struct pw_node_info *info) { - auto *pNodeInfo = static_cast(data_); +static void getNodeInfo(void* data_, const struct pw_node_info* info) { + auto* pNodeInfo = static_cast(data_); pNodeInfo->handleNodeEventInfo(info); - static_cast(pNodeInfo->data)->privacy_nodes_changed_signal_event.emit(); + static_cast(pNodeInfo->data)->privacy_nodes_changed_signal_event.emit(); } static const struct pw_node_events NODE_EVENTS = { @@ -16,8 +16,8 @@ static const struct pw_node_events NODE_EVENTS = { .info = getNodeInfo, }; -static void proxyDestroy(void *data) { - static_cast(data)->handleProxyEventDestroy(); +static void proxyDestroy(void* data) { + static_cast(data)->handleProxyEventDestroy(); } static const struct pw_proxy_events PROXY_EVENTS = { @@ -25,14 +25,14 @@ static const struct pw_proxy_events PROXY_EVENTS = { .destroy = proxyDestroy, }; -static void registryEventGlobal(void *_data, uint32_t id, uint32_t permissions, const char *type, - uint32_t version, const struct spa_dict *props) { - static_cast(_data)->handleRegistryEventGlobal(id, permissions, type, version, - props); +static void registryEventGlobal(void* _data, uint32_t id, uint32_t permissions, const char* type, + uint32_t version, const struct spa_dict* props) { + static_cast(_data)->handleRegistryEventGlobal(id, permissions, type, version, + props); } -static void registryEventGlobalRemove(void *_data, uint32_t id) { - static_cast(_data)->handleRegistryEventGlobalRemove(id); +static void registryEventGlobalRemove(void* _data, uint32_t id) { + static_cast(_data)->handleRegistryEventGlobalRemove(id); } static const struct pw_registry_events REGISTRY_EVENTS = { @@ -54,11 +54,17 @@ PipewireBackend::PipewireBackend(PrivateConstructorTag tag) context_ = pw_context_new(pw_thread_loop_get_loop(mainloop_), nullptr, 0); if (context_ == nullptr) { pw_thread_loop_unlock(mainloop_); + pw_thread_loop_destroy(mainloop_); + mainloop_ = nullptr; throw std::runtime_error("pa_context_new() failed."); } core_ = pw_context_connect(context_, nullptr, 0); if (core_ == nullptr) { pw_thread_loop_unlock(mainloop_); + pw_context_destroy(context_); + context_ = nullptr; + pw_thread_loop_destroy(mainloop_); + mainloop_ = nullptr; throw std::runtime_error("pw_context_connect() failed"); } registry_ = pw_core_get_registry(core_, PW_VERSION_REGISTRY, 0); @@ -78,7 +84,7 @@ PipewireBackend::~PipewireBackend() { } if (registry_ != nullptr) { - pw_proxy_destroy((struct pw_proxy *)registry_); + pw_proxy_destroy((struct pw_proxy*)registry_); } spa_zero(registryListener_); @@ -103,11 +109,11 @@ std::shared_ptr PipewireBackend::getInstance() { return std::make_shared(tag); } -void PipewireBackend::handleRegistryEventGlobal(uint32_t id, uint32_t permissions, const char *type, - uint32_t version, const struct spa_dict *props) { +void PipewireBackend::handleRegistryEventGlobal(uint32_t id, uint32_t permissions, const char* type, + uint32_t version, const struct spa_dict* props) { if (props == nullptr || strcmp(type, PW_TYPE_INTERFACE_Node) != 0) return; - const char *lookupStr = spa_dict_lookup(props, PW_KEY_MEDIA_CLASS); + const char* lookupStr = spa_dict_lookup(props, PW_KEY_MEDIA_CLASS); if (lookupStr == nullptr) return; std::string mediaClass = lookupStr; enum PrivacyNodeType mediaType = PRIVACY_NODE_TYPE_NONE; @@ -121,11 +127,11 @@ void PipewireBackend::handleRegistryEventGlobal(uint32_t id, uint32_t permission return; } - auto *proxy = (pw_proxy *)pw_registry_bind(registry_, id, type, version, sizeof(PrivacyNodeInfo)); + auto* proxy = (pw_proxy*)pw_registry_bind(registry_, id, type, version, sizeof(PrivacyNodeInfo)); if (proxy == nullptr) return; - auto *pNodeInfo = (PrivacyNodeInfo *)pw_proxy_get_user_data(proxy); + auto* pNodeInfo = (PrivacyNodeInfo*)pw_proxy_get_user_data(proxy); new (pNodeInfo) PrivacyNodeInfo{}; pNodeInfo->id = id; pNodeInfo->data = this; @@ -136,7 +142,10 @@ void PipewireBackend::handleRegistryEventGlobal(uint32_t id, uint32_t permission pw_proxy_add_object_listener(proxy, &pNodeInfo->object_listener, &NODE_EVENTS, pNodeInfo); - privacy_nodes.insert_or_assign(id, pNodeInfo); + { + std::lock_guard lock(mutex_); + privacy_nodes.insert_or_assign(id, pNodeInfo); + } } void PipewireBackend::handleRegistryEventGlobalRemove(uint32_t id) { diff --git a/src/util/pipewire/privacy_node_info.cpp b/src/util/pipewire/privacy_node_info.cpp index 739dc528..dbd6ed85 100644 --- a/src/util/pipewire/privacy_node_info.cpp +++ b/src/util/pipewire/privacy_node_info.cpp @@ -3,9 +3,9 @@ namespace waybar::util::PipewireBackend { std::string PrivacyNodeInfo::getName() { - const std::vector names{&application_name, &node_name}; + const std::vector names{&application_name, &node_name}; std::string name = "Unknown Application"; - for (const auto &item : names) { + for (const auto& item : names) { if (item != nullptr && !item->empty()) { name = *item; name[0] = toupper(name[0]); @@ -16,10 +16,10 @@ std::string PrivacyNodeInfo::getName() { } std::string PrivacyNodeInfo::getIconName() { - const std::vector names{&application_icon_name, &pipewire_access_portal_app_id, - &application_name, &node_name}; + const std::vector names{&application_icon_name, &pipewire_access_portal_app_id, + &application_name, &node_name}; std::string name = "application-x-executable-symbolic"; - for (const auto &item : names) { + for (const auto& item : names) { if (item != nullptr && !item->empty() && DefaultGtkIconThemeWrapper::has_icon(*item)) { return *item; } @@ -32,10 +32,10 @@ void PrivacyNodeInfo::handleProxyEventDestroy() { spa_hook_remove(&object_listener); } -void PrivacyNodeInfo::handleNodeEventInfo(const struct pw_node_info *info) { +void PrivacyNodeInfo::handleNodeEventInfo(const struct pw_node_info* info) { state = info->state; - const struct spa_dict_item *item; + const struct spa_dict_item* item; spa_dict_for_each(item, info->props) { if (strcmp(item->key, PW_KEY_CLIENT_ID) == 0) { client_id = strtoul(item->value, nullptr, 10); @@ -49,6 +49,8 @@ void PrivacyNodeInfo::handleNodeEventInfo(const struct pw_node_info *info) { pipewire_access_portal_app_id = item->value; } else if (strcmp(item->key, PW_KEY_APP_ICON_NAME) == 0) { application_icon_name = item->value; + } else if (strcmp(item->key, "stream.monitor") == 0) { + is_monitor = strcmp(item->value, "true") == 0; } } } diff --git a/src/util/portal.cpp b/src/util/portal.cpp index 5874871b..e2be97c7 100644 --- a/src/util/portal.cpp +++ b/src/util/portal.cpp @@ -17,8 +17,6 @@ static constexpr const char* PORTAL_NAMESPACE = "org.freedesktop.appearance"; static constexpr const char* PORTAL_KEY = "color-scheme"; } // namespace waybar -using namespace Gio; - auto fmt::formatter::format(waybar::Appearance c, format_context& ctx) const { string_view name; switch (c) { @@ -36,8 +34,8 @@ auto fmt::formatter::format(waybar::Appearance c, format_con } waybar::Portal::Portal() - : DBus::Proxy(DBus::Connection::get_sync(DBus::BusType::BUS_TYPE_SESSION), PORTAL_BUS_NAME, - PORTAL_OBJ_PATH, PORTAL_INTERFACE), + : Gio::DBus::Proxy(Gio::DBus::Connection::get_sync(Gio::DBus::BusType::BUS_TYPE_SESSION), + PORTAL_BUS_NAME, PORTAL_OBJ_PATH, PORTAL_INTERFACE), currentMode(Appearance::UNKNOWN) { refreshAppearance(); }; @@ -60,21 +58,27 @@ void waybar::Portal::refreshAppearance() { // xdg-desktop-portal 1.17 will fix this issue with a new `ReadOne` method, // but this version is not yet released. // TODO(xdg-desktop-portal v1.17): switch to ReadOne - auto container = Glib::VariantBase::cast_dynamic(response); - Glib::VariantBase modev; - container.get_child(modev, 0); - auto mode = - Glib::VariantBase::cast_dynamic>>>(modev) - .get() - .get() - .get(); - auto newMode = Appearance(mode); - if (newMode == currentMode) { + try { + auto container = Glib::VariantBase::cast_dynamic(response); + Glib::VariantBase modev; + container.get_child(modev, 0); + auto mode = + Glib::VariantBase::cast_dynamic>>>( + modev) + .get() + .get() + .get(); + auto newMode = Appearance(mode); + if (newMode == currentMode) { + return; + } + spdlog::info("Discovered appearance '{}'", newMode); + currentMode = newMode; + m_signal_appearance_changed.emit(currentMode); + } catch (const std::bad_cast& e) { + spdlog::error("Unexpected appearance variant format: {}", e.what()); return; } - spdlog::info("Discovered appearance '{}'", newMode); - currentMode = newMode; - m_signal_appearance_changed.emit(currentMode); } waybar::Appearance waybar::Portal::getAppearance() { return currentMode; }; diff --git a/src/util/prepare_for_sleep.cpp b/src/util/prepare_for_sleep.cpp index 3adcdf67..ed4100be 100644 --- a/src/util/prepare_for_sleep.cpp +++ b/src/util/prepare_for_sleep.cpp @@ -18,21 +18,21 @@ class PrepareForSleep { } } - static void prepareForSleep_cb(GDBusConnection *system_bus, const gchar *sender_name, - const gchar *object_path, const gchar *interface_name, - const gchar *signal_name, GVariant *parameters, + static void prepareForSleep_cb(GDBusConnection* system_bus, const gchar* sender_name, + const gchar* object_path, const gchar* interface_name, + const gchar* signal_name, GVariant* parameters, gpointer user_data) { if (g_variant_is_of_type(parameters, G_VARIANT_TYPE("(b)")) != 0) { gboolean sleeping; g_variant_get(parameters, "(b)", &sleeping); - auto *self = static_cast(user_data); + auto* self = static_cast(user_data); self->signal.emit(sleeping); } } public: - static PrepareForSleep &GetInstance() { + static PrepareForSleep& GetInstance() { static PrepareForSleep instance; return instance; } @@ -40,10 +40,10 @@ class PrepareForSleep { private: guint login1_id; - GDBusConnection *login1_connection; + GDBusConnection* login1_connection; }; } // namespace -waybar::SafeSignal &waybar::util::prepare_for_sleep() { +waybar::SafeSignal& waybar::util::prepare_for_sleep() { return PrepareForSleep::GetInstance().signal; } diff --git a/src/util/rewrite_string.cpp b/src/util/rewrite_string.cpp index 3f6ae4ca..8c377d3f 100644 --- a/src/util/rewrite_string.cpp +++ b/src/util/rewrite_string.cpp @@ -18,7 +18,7 @@ std::string rewriteString(const std::string& value, const Json::Value& rules) { // malformated regexes will cause an exception. // in this case, log error and try the next rule. const std::regex rule{it.key().asString(), std::regex_constants::icase}; - if (std::regex_match(value, rule)) { + if (std::regex_match(res, rule)) { res = std::regex_replace(res, rule, it->asString()); } } catch (const std::regex_error& e) { diff --git a/src/util/transform_8bit_to_rgba.cpp b/src/util/transform_8bit_to_rgba.cpp new file mode 100644 index 00000000..dc87a88e --- /dev/null +++ b/src/util/transform_8bit_to_rgba.cpp @@ -0,0 +1,60 @@ +#include +#include +#include +#include +#include +namespace fs = std::filesystem; + +struct TransformResult { + std::string css; + bool was_transformed; +}; + +TransformResult transform_8bit_to_hex(const std::string& file_path) { + std::ifstream f(file_path, std::ios::in | std::ios::binary); + const auto size = fs::file_size(file_path); + std::string result(size, '\0'); + if (!f.is_open() || !f.good()) { + throw std::runtime_error("Cannot open file: " + file_path); + } + + if (size == 0) { + return {.css = result, .was_transformed = false}; + } + + f.read(result.data(), size); + + static std::regex pattern( + R"(\#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2}))"); + std::string final_output; + + auto it = std::sregex_iterator(result.begin(), result.end(), pattern); + auto eof = std::sregex_iterator(); + + if (it == eof) { + return {.css = result, .was_transformed = false}; + } + + std::smatch match; + while (it != eof) { + match = *it; + + final_output += match.prefix().str(); + + int r = stoi(match[1].str(), nullptr, 16); + int g = stoi(match[2].str(), nullptr, 16); + int b = stoi(match[3].str(), nullptr, 16); + double a = (stoi(match[4].str(), nullptr, 16) / 255.0); + + std::stringstream ss; + ss << "rgba(" << r << "," << g << "," << b << "," << std::fixed << std::setprecision(2) << a + << ")"; + final_output += ss.str(); + + ++it; + } + + final_output += match.suffix().str(); + + return {.css = final_output, .was_transformed = true}; +} diff --git a/src/util/ustring_clen.cpp b/src/util/ustring_clen.cpp index a8b9c9af..5a5b0028 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 (unsigned int i : str) { total += g_unichar_iswide(i) + 1; diff --git a/src/util/utf8_string.cpp b/src/util/utf8_string.cpp new file mode 100644 index 00000000..f96f2bd1 --- /dev/null +++ b/src/util/utf8_string.cpp @@ -0,0 +1,62 @@ +#include + +#include +#include + +namespace waybar::util { + +namespace { +// Wide characters count as two, zero-width characters count as zero +// Modifies str in-place (unless width = std::string::npos) +// Returns the total width of the string pre-truncating +size_t measure_and_truncate(std::string& str, size_t width = std::string::npos) { + if (str.length() == 0) return 0; + + const gchar* trunc_end = nullptr; + + size_t total_width = 0; + + for (gchar *data = str.data(), *end = data + str.size(); data != nullptr;) { + gunichar c = g_utf8_get_char_validated(data, end - data); + if (c == -1U || c == -2U) { + // invalid unicode, treat string as ascii + if (width != std::string::npos && str.length() > width) str.resize(width); + return str.length(); + } else if (g_unichar_iswide(c)) { + total_width += 2; + } else if (!g_unichar_iszerowidth(c) && c != 0xAD) { // neither zero-width nor soft hyphen + total_width += 1; + } + + data = g_utf8_find_next_char(data, end); + if (width != std::string::npos && total_width <= width && !g_unichar_isspace(c)) + trunc_end = data; + } + + if (trunc_end) str.resize(trunc_end - str.data()); + + return total_width; +} +} // namespace + +size_t utf8_width(const std::string& str) { + return measure_and_truncate(const_cast(str)); +} + +void utf8_truncate(std::string& s, const std::string& ellipsis, size_t max_len) { + if (max_len == 0) { + s.resize(0); + return; + } + size_t len = measure_and_truncate(s, max_len); + if (len > max_len) { + size_t ellipsis_len = utf8_width(ellipsis); + if (max_len >= ellipsis_len) { + if (ellipsis_len) measure_and_truncate(s, max_len - ellipsis_len); + s += ellipsis; + } else { + s.resize(0); + } + } +} +} // namespace waybar::util diff --git a/subprojects/cava.wrap b/subprojects/cava.wrap deleted file mode 100644 index f220207c..00000000 --- a/subprojects/cava.wrap +++ /dev/null @@ -1,7 +0,0 @@ -[wrap-file] -directory = cava-0.10.4 -source_url = https://github.com/LukashonakV/cava/archive/0.10.4.tar.gz -source_filename = cava-0.10.4.tar.gz -source_hash =7bc1c1f9535f2bcc5cd2ae8a2434a2e3a05f5670b1c96316df304137ffc65756 -[provide] -cava = cava_dep diff --git a/subprojects/fmt.wrap b/subprojects/fmt.wrap index fd508477..15a716ac 100644 --- a/subprojects/fmt.wrap +++ b/subprojects/fmt.wrap @@ -1,13 +1,13 @@ [wrap-file] -directory = fmt-11.0.2 -source_url = https://github.com/fmtlib/fmt/archive/11.0.2.tar.gz -source_filename = fmt-11.0.2.tar.gz -source_hash = 6cb1e6d37bdcb756dbbe59be438790db409cdb4868c66e888d5df9f13f7c027f -patch_filename = fmt_11.0.2-1_patch.zip -patch_url = https://wrapdb.mesonbuild.com/v2/fmt_11.0.2-1/get_patch -patch_hash = 90c9e3b8e8f29713d40ca949f6f93ad115d78d7fb921064112bc6179e6427c5e -source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/fmt_11.0.2-1/fmt-11.0.2.tar.gz -wrapdb_version = 11.0.2-1 +directory = fmt-12.0.0 +source_url = https://github.com/fmtlib/fmt/archive/12.0.0.tar.gz +source_filename = fmt-12.0.0.tar.gz +source_hash = aa3e8fbb6a0066c03454434add1f1fc23299e85758ceec0d7d2d974431481e40 +patch_filename = fmt_12.0.0-1_patch.zip +patch_url = https://wrapdb.mesonbuild.com/v2/fmt_12.0.0-1/get_patch +patch_hash = 307f288ebf3850abf2f0c50ac1fb07de97df9538d39146d802f3c0d6cada8998 +source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/fmt_12.0.0-1/fmt-12.0.0.tar.gz +wrapdb_version = 12.0.0-1 [provide] fmt = fmt_dep diff --git a/subprojects/libcava.wrap b/subprojects/libcava.wrap new file mode 100644 index 00000000..d66d657b --- /dev/null +++ b/subprojects/libcava.wrap @@ -0,0 +1,12 @@ +#[wrap-git] +#url = https://github.com/LukashonakV/cava.git +#revision = 866cfec40b7b9d38e97148d004d3134c1385b52f +#depth = 1 + +[wrap-file] +directory = cava-0.10.7 +source_url = https://github.com/LukashonakV/cava/archive/0.10.7.tar.gz +source_filename = cava-0.10.7.tar.gz +source_hash = 50cc6413e9c96c503657f814744a2baf429a24ff9fed31a8343e0ed285269eff +[provide] +libcava = cava_dep diff --git a/subprojects/spdlog.wrap b/subprojects/spdlog.wrap index af00d5a7..f7a43600 100644 --- a/subprojects/spdlog.wrap +++ b/subprojects/spdlog.wrap @@ -1,13 +1,13 @@ [wrap-file] -directory = spdlog-1.14.1 -source_url = https://github.com/gabime/spdlog/archive/refs/tags/v1.14.1.tar.gz -source_filename = spdlog-1.14.1.tar.gz -source_hash = 1586508029a7d0670dfcb2d97575dcdc242d3868a259742b69f100801ab4e16b -patch_filename = spdlog_1.14.1-1_patch.zip -patch_url = https://wrapdb.mesonbuild.com/v2/spdlog_1.14.1-1/get_patch -patch_hash = ae878e732330ea1048f90d7e117c40c0cd2a6fb8ae5492c7955818ce3aaade6c -source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/spdlog_1.14.1-1/spdlog-1.14.1.tar.gz -wrapdb_version = 1.14.1-1 +directory = spdlog-1.15.2 +source_url = https://github.com/gabime/spdlog/archive/refs/tags/v1.15.2.tar.gz +source_filename = spdlog-1.15.2.tar.gz +source_hash = 7a80896357f3e8e920e85e92633b14ba0f229c506e6f978578bdc35ba09e9a5d +patch_filename = spdlog_1.15.2-3_patch.zip +patch_url = https://wrapdb.mesonbuild.com/v2/spdlog_1.15.2-3/get_patch +patch_hash = d5ab078661f571ef5113a8e4bc5c4121e16c044e7772a24b44b1ca8f3ee7c6cb +source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/spdlog_1.15.2-3/spdlog-1.15.2.tar.gz +wrapdb_version = 1.15.2-3 [provide] spdlog = spdlog_dep diff --git a/test/config.cpp b/test/config.cpp index c60519ce..638d9663 100644 --- a/test/config.cpp +++ b/test/config.cpp @@ -84,6 +84,33 @@ TEST_CASE("Load simple config with include", "[config]") { } } +TEST_CASE("Load simple config with wildcard include", "[config]") { + waybar::Config conf; + conf.load("test/config/include-wildcard.json"); + + auto& data = conf.getConfig(); + SECTION("validate cpu include file") { REQUIRE(data["cpu"]["format"].asString() == "goo"); } + SECTION("validate memory include file") { REQUIRE(data["memory"]["format"].asString() == "foo"); } +} + +TEST_CASE("Load config using relative paths and wildcards", "[config]") { + waybar::Config conf; + + const char* old_config_path = std::getenv(waybar::Config::CONFIG_PATH_ENV); + setenv(waybar::Config::CONFIG_PATH_ENV, "test/config", 1); + + conf.load("test/config/include-relative-path.json"); + + auto& data = conf.getConfig(); + SECTION("validate cpu include file") { REQUIRE(data["cpu"]["format"].asString() == "goo"); } + SECTION("validate memory include file") { REQUIRE(data["memory"]["format"].asString() == "foo"); } + + if (old_config_path) + setenv(waybar::Config::CONFIG_PATH_ENV, old_config_path, 1); + else + unsetenv(waybar::Config::CONFIG_PATH_ENV); +} + TEST_CASE("Load multiple bar config with include", "[config]") { waybar::Config conf; conf.load("test/config/include-multi.json"); diff --git a/test/config/include-relative-path.json b/test/config/include-relative-path.json new file mode 100644 index 00000000..82214b37 --- /dev/null +++ b/test/config/include-relative-path.json @@ -0,0 +1,5 @@ +{ + "include": ["modules/*.jsonc"], + "position": "top", + "nullOption": null +} diff --git a/test/config/include-wildcard.json b/test/config/include-wildcard.json new file mode 100644 index 00000000..75c9f3a1 --- /dev/null +++ b/test/config/include-wildcard.json @@ -0,0 +1,5 @@ +{ + "include": ["test/config/modules/*.jsonc"], + "position": "top", + "nullOption": null +} diff --git a/test/config/modules/cpu.jsonc b/test/config/modules/cpu.jsonc new file mode 100644 index 00000000..393fd786 --- /dev/null +++ b/test/config/modules/cpu.jsonc @@ -0,0 +1,6 @@ +{ + "cpu": { + "interval": 2, + "format": "goo" + } +} diff --git a/test/config/modules/memory.jsonc b/test/config/modules/memory.jsonc new file mode 100644 index 00000000..6085d43a --- /dev/null +++ b/test/config/modules/memory.jsonc @@ -0,0 +1,6 @@ +{ + "memory": { + "interval": 2, + "format": "foo", + } +} diff --git a/test/hyprland/backend.cpp b/test/hyprland/backend.cpp index b83b839c..f2e10dae 100644 --- a/test/hyprland/backend.cpp +++ b/test/hyprland/backend.cpp @@ -4,56 +4,211 @@ #include #endif -#include "fixtures/IPCTestFixture.hpp" +#include + +#include "modules/hyprland/backend.hpp" namespace fs = std::filesystem; namespace hyprland = waybar::modules::hyprland; -TEST_CASE_METHOD(IPCTestFixture, "XDGRuntimeDirExists", "[getSocketFolder]") { +namespace { +class IPCTestHelper : public hyprland::IPC { + public: + static void resetSocketFolder() { socketFolder_.clear(); } + static void resetLuaProtocolDetection() { s_luaProtocolDetected_.reset(); } + static void setLuaProtocolDetected(bool value) { s_luaProtocolDetected_ = value; } + using hyprland::IPC::buildLuaDispatch; + using hyprland::IPC::isLuaProtocol; +}; + +std::size_t countOpenFds() { +#if defined(__linux__) + std::size_t count = 0; + for (const auto& _ : fs::directory_iterator("/proc/self/fd")) { + (void)_; + ++count; + } + return count; +#else + return 0; +#endif +} +} // namespace + +TEST_CASE("XDGRuntimeDirExists", "[getSocketFolder]") { // Test case: XDG_RUNTIME_DIR exists and contains "hypr" directory // Arrange - tempDir = fs::temp_directory_path() / "hypr_test/run/user/1000"; + constexpr auto instanceSig = "instance_sig"; + const fs::path tempDir = fs::temp_directory_path() / "hypr_test/run/user/1000"; + std::error_code ec; + fs::remove_all(tempDir, ec); fs::path expectedPath = tempDir / "hypr" / instanceSig; - fs::create_directories(tempDir / "hypr" / instanceSig); + fs::create_directories(expectedPath); setenv("XDG_RUNTIME_DIR", tempDir.c_str(), 1); + IPCTestHelper::resetSocketFolder(); // Act - fs::path actualPath = getSocketFolder(instanceSig); + fs::path actualPath = hyprland::IPC::getSocketFolder(instanceSig); // Assert expected result REQUIRE(actualPath == expectedPath); + fs::remove_all(tempDir, ec); } -TEST_CASE_METHOD(IPCTestFixture, "XDGRuntimeDirDoesNotExist", "[getSocketFolder]") { +TEST_CASE("XDGRuntimeDirDoesNotExist", "[getSocketFolder]") { // Test case: XDG_RUNTIME_DIR does not exist // Arrange + constexpr auto instanceSig = "instance_sig"; unsetenv("XDG_RUNTIME_DIR"); fs::path expectedPath = fs::path("/tmp") / "hypr" / instanceSig; + IPCTestHelper::resetSocketFolder(); // Act - fs::path actualPath = getSocketFolder(instanceSig); + fs::path actualPath = hyprland::IPC::getSocketFolder(instanceSig); // Assert expected result REQUIRE(actualPath == expectedPath); } -TEST_CASE_METHOD(IPCTestFixture, "XDGRuntimeDirExistsNoHyprDir", "[getSocketFolder]") { +TEST_CASE("XDGRuntimeDirExistsNoHyprDir", "[getSocketFolder]") { // Test case: XDG_RUNTIME_DIR exists but does not contain "hypr" directory // Arrange + constexpr auto instanceSig = "instance_sig"; fs::path tempDir = fs::temp_directory_path() / "hypr_test/run/user/1000"; + std::error_code ec; + fs::remove_all(tempDir, ec); fs::create_directories(tempDir); setenv("XDG_RUNTIME_DIR", tempDir.c_str(), 1); fs::path expectedPath = fs::path("/tmp") / "hypr" / instanceSig; + IPCTestHelper::resetSocketFolder(); // Act - fs::path actualPath = getSocketFolder(instanceSig); + fs::path actualPath = hyprland::IPC::getSocketFolder(instanceSig); // Assert expected result REQUIRE(actualPath == expectedPath); + fs::remove_all(tempDir, ec); } -TEST_CASE_METHOD(IPCTestFixture, "getSocket1Reply throws on no socket", "[getSocket1Reply]") { +TEST_CASE("Socket folder is resolved per instance signature", "[getSocketFolder]") { + const fs::path tempDir = fs::temp_directory_path() / "hypr_test/run/user/1000"; + std::error_code ec; + fs::remove_all(tempDir, ec); + fs::create_directories(tempDir / "hypr"); + setenv("XDG_RUNTIME_DIR", tempDir.c_str(), 1); + IPCTestHelper::resetSocketFolder(); + + const auto firstPath = hyprland::IPC::getSocketFolder("instance_a"); + const auto secondPath = hyprland::IPC::getSocketFolder("instance_b"); + + REQUIRE(firstPath == tempDir / "hypr" / "instance_a"); + REQUIRE(secondPath == tempDir / "hypr" / "instance_b"); + REQUIRE(firstPath != secondPath); + + fs::remove_all(tempDir, ec); +} + +TEST_CASE("getSocket1Reply throws on no socket", "[getSocket1Reply]") { + unsetenv("HYPRLAND_INSTANCE_SIGNATURE"); + IPCTestHelper::resetSocketFolder(); std::string request = "test_request"; - CHECK_THROWS(getSocket1Reply(request)); + CHECK_THROWS(hyprland::IPC::getSocket1Reply(request)); +} + +#if defined(__linux__) +TEST_CASE("getSocket1Reply failure paths do not leak fds", "[getSocket1Reply][fd-leak]") { + const auto baseline = countOpenFds(); + + unsetenv("HYPRLAND_INSTANCE_SIGNATURE"); + for (int i = 0; i < 16; ++i) { + IPCTestHelper::resetSocketFolder(); + CHECK_THROWS(hyprland::IPC::getSocket1Reply("test_request")); + } + const auto after_missing_signature = countOpenFds(); + REQUIRE(after_missing_signature == baseline); + + setenv("HYPRLAND_INSTANCE_SIGNATURE", "definitely-not-running", 1); + for (int i = 0; i < 16; ++i) { + IPCTestHelper::resetSocketFolder(); + CHECK_THROWS(hyprland::IPC::getSocket1Reply("test_request")); + } + const auto after_connect_failures = countOpenFds(); + REQUIRE(after_connect_failures == baseline); +} +#endif + +// --- Tests for new Lua IPC dispatch functions --- + +TEST_CASE("buildLuaDispatch workspace", "[buildLuaDispatch]") { + SECTION("numeric workspace") { + auto result = IPCTestHelper::buildLuaDispatch("workspace", "1"); + REQUIRE(result == "/dispatch hl.dsp.focus({ workspace = \"1\" })"); + } + SECTION("named workspace") { + auto result = IPCTestHelper::buildLuaDispatch("workspace", "name:term"); + REQUIRE(result == "/dispatch hl.dsp.focus({ workspace = \"name:term\" })"); + } + SECTION("relative workspace") { + auto result = IPCTestHelper::buildLuaDispatch("workspace", "e+1"); + REQUIRE(result == "/dispatch hl.dsp.focus({ workspace = \"e+1\" })"); + } +} + +TEST_CASE("buildLuaDispatch focusworkspaceoncurrentmonitor", "[buildLuaDispatch]") { + auto result = + IPCTestHelper::buildLuaDispatch("focusworkspaceoncurrentmonitor", "3"); + REQUIRE( + result == + "/dispatch hl.dsp.focus({ workspace = \"3\", on_current_monitor = true })"); +} + +TEST_CASE("buildLuaDispatch togglespecialworkspace", "[buildLuaDispatch]") { + SECTION("with name") { + auto result = + IPCTestHelper::buildLuaDispatch("togglespecialworkspace", "scratchpad"); + REQUIRE(result == + "/dispatch hl.dsp.workspace.toggle_special(\"scratchpad\")"); + } + SECTION("empty arg") { + auto result = + IPCTestHelper::buildLuaDispatch("togglespecialworkspace", ""); + REQUIRE(result == "/dispatch hl.dsp.workspace.toggle_special()"); + } +} + +TEST_CASE("buildLuaDispatch unknown dispatcher fallback", "[buildLuaDispatch]") { + auto result = + IPCTestHelper::buildLuaDispatch("unknown_dispatcher", "some_arg"); + REQUIRE(result == + "/dispatch hl.dsp.unknown_dispatcher(\"some_arg\")"); +} + +TEST_CASE("dispatch throws when Hyprland is not running", "[dispatch]") { + unsetenv("HYPRLAND_INSTANCE_SIGNATURE"); + IPCTestHelper::resetSocketFolder(); + IPCTestHelper::resetLuaProtocolDetection(); + + CHECK_THROWS(hyprland::IPC::dispatch("workspace", "1")); +} + +TEST_CASE("isLuaProtocol uses cached value and avoids socket call", + "[isLuaProtocol]") { + unsetenv("HYPRLAND_INSTANCE_SIGNATURE"); + IPCTestHelper::resetSocketFolder(); + + SECTION("cached false") { + IPCTestHelper::setLuaProtocolDetected(false); + // Should return false without throwing (no socket call needed) + REQUIRE(IPCTestHelper::isLuaProtocol() == false); + } + + SECTION("cached true") { + IPCTestHelper::setLuaProtocolDetected(true); + // Should return true without throwing (no socket call needed) + REQUIRE(IPCTestHelper::isLuaProtocol() == true); + } + + // Cleanup: reset detection so other tests aren't affected + IPCTestHelper::resetLuaProtocolDetection(); } diff --git a/test/hyprland/fixtures/IPCTestFixture.hpp b/test/hyprland/fixtures/IPCTestFixture.hpp deleted file mode 100644 index caa92975..00000000 --- a/test/hyprland/fixtures/IPCTestFixture.hpp +++ /dev/null @@ -1,25 +0,0 @@ -#include "modules/hyprland/backend.hpp" - -namespace fs = std::filesystem; -namespace hyprland = waybar::modules::hyprland; - -class IPCTestFixture : public hyprland::IPC { - public: - IPCTestFixture() : IPC() { IPC::socketFolder_ = ""; } - ~IPCTestFixture() { fs::remove_all(tempDir); } - - protected: - const char* instanceSig = "instance_sig"; - fs::path tempDir = fs::temp_directory_path() / "hypr_test"; - - private: -}; - -class IPCMock : public IPCTestFixture { - public: - // Mock getSocket1Reply to return an empty string - static std::string getSocket1Reply(const std::string& rq) { return ""; } - - protected: - const char* instanceSig = "instance_sig"; -}; diff --git a/test/utils/SafeSignal.cpp b/test/utils/SafeSignal.cpp index e7e096b0..1502b7d9 100644 --- a/test/utils/SafeSignal.cpp +++ b/test/utils/SafeSignal.cpp @@ -9,6 +9,7 @@ #endif #include #include +#include #include "fixtures/GlibTestsFixture.hpp" @@ -141,3 +142,33 @@ TEST_CASE_METHOD(GlibTestsFixture, "SafeSignal copy/move counter", "[signal][thr producer.join(); REQUIRE(count == NUM_EVENTS); } + +TEST_CASE_METHOD(GlibTestsFixture, "SafeSignal queue stays bounded under burst load", + "[signal][thread][util][perf]") { + constexpr int NUM_EVENTS = 200; + constexpr std::size_t MAX_QUEUED_EVENTS = 8; + std::vector received; + + SafeSignal test_signal; + test_signal.set_max_queued_events(MAX_QUEUED_EVENTS); + + setTimeout(500); + + test_signal.connect([&](auto value) { received.push_back(value); }); + + run([&]() { + std::thread producer([&]() { + for (int i = 1; i <= NUM_EVENTS; ++i) { + test_signal.emit(i); + } + }); + producer.join(); + + Glib::signal_timeout().connect_once([this]() { this->quit(); }, 50); + }); + + REQUIRE(received.size() <= MAX_QUEUED_EVENTS); + REQUIRE_FALSE(received.empty()); + REQUIRE(received.back() == NUM_EVENTS); + REQUIRE(received.front() == NUM_EVENTS - static_cast(received.size()) + 1); +} diff --git a/test/utils/command.cpp b/test/utils/command.cpp new file mode 100644 index 00000000..053a2b77 --- /dev/null +++ b/test/utils/command.cpp @@ -0,0 +1,57 @@ +#if __has_include() +#include +#else +#include +#endif + +#include +#include + +#include +#include +#include + +std::mutex reap_mtx; +std::list reap; + +extern "C" int waybar_test_execl(const char* path, const char* arg, ...); +extern "C" int waybar_test_execlp(const char* file, const char* arg, ...); + +#define execl waybar_test_execl +#define execlp waybar_test_execlp +#include "util/command.hpp" +#undef execl +#undef execlp + +extern "C" int waybar_test_execl(const char* path, const char* arg, ...) { + (void)path; + (void)arg; + errno = ENOENT; + return -1; +} + +extern "C" int waybar_test_execlp(const char* file, const char* arg, ...) { + (void)file; + (void)arg; + errno = ENOENT; + return -1; +} + +TEST_CASE("command::execNoRead returns 127 when shell exec fails", "[util][command]") { + const auto result = waybar::util::command::execNoRead("echo should-not-run"); + REQUIRE(result.exit_code == waybar::util::command::kExecFailureExitCode); + REQUIRE(result.out.empty()); +} + +TEST_CASE("command::forkExec child exits 127 when shell exec fails", "[util][command]") { + const auto pid = waybar::util::command::forkExec("echo should-not-run", "test-output"); + REQUIRE(pid > 0); + + int status = -1; + REQUIRE(waitpid(pid, &status, 0) == pid); + REQUIRE(WIFEXITED(status)); + REQUIRE(WEXITSTATUS(status) == waybar::util::command::kExecFailureExitCode); + + std::scoped_lock lock(reap_mtx); + reap.remove(pid); +} diff --git a/test/utils/css_reload_helper.cpp b/test/utils/css_reload_helper.cpp index f3888a83..0ba0bde4 100644 --- a/test/utils/css_reload_helper.cpp +++ b/test/utils/css_reload_helper.cpp @@ -10,7 +10,7 @@ class CssReloadHelperTest : public waybar::CssReloadHelper { public: - CssReloadHelperTest() : CssReloadHelper("/tmp/waybar_test.css", [this]() { callback(); }) {} + CssReloadHelperTest() : CssReloadHelper("/tmp/waybar_test.css", [this](const std::string&) { callback(); }) {} void callback() { m_callbackCounter++; } diff --git a/test/utils/date.cpp b/test/utils/date.cpp index d317f98a..14694e2f 100644 --- a/test/utils/date.cpp +++ b/test/utils/date.cpp @@ -18,8 +18,10 @@ return #endif +using namespace date; using namespace std::literals::chrono_literals; namespace fmt_lib = waybar::util::date::format; + /* * Check that the date/time formatter with locale and timezone support is working as expected. */ @@ -43,7 +45,7 @@ static const bool LC_TIME_is_sane = []() { ss << std::put_time(&tm, "%x %X"); return ss.str() == "01/03/2022 12:00:00 PM"; - } catch (std::exception &) { + } catch (std::exception&) { return false; } }(); @@ -75,7 +77,7 @@ TEST_CASE("Format UTC time", "[clock][util]") { CHECK(fmt_lib::format(loc, "{:%F %r}", tm) == "2022-01-03 01:04:05 PM"); #endif CHECK(fmt_lib::format(loc, "{:%Y%m%d%H%M%S}", tm) == "20220103130405"); - } catch (const std::runtime_error &) { + } catch (const std::runtime_error&) { WARN("Locale en_US not found, skip tests"); } } @@ -92,7 +94,7 @@ TEST_CASE("Format UTC time", "[clock][util]") { CHECK(fmt_lib::format(loc, "{:%F %T}", tm) == "2022-01-03 13:04:05"); #endif CHECK(fmt_lib::format(loc, "{:%Y%m%d%H%M%S}", tm) == "20220103130405"); - } catch (const std::runtime_error &) { + } catch (const std::runtime_error&) { WARN("Locale en_GB not found, skip tests"); } } @@ -111,7 +113,7 @@ TEST_CASE("Format UTC time", "[clock][util]") { CHECK(fmt_lib::format("{:%Y%m%d%H%M%S}", tm) == "20220103130405"); std::locale::global(loc); - } catch (const std::runtime_error &) { + } catch (const std::runtime_error&) { WARN("Locale en_US not found, skip tests"); } } @@ -145,7 +147,7 @@ TEST_CASE("Format zoned time", "[clock][util]") { CHECK(fmt_lib::format(loc, "{:%F %r}", tm) == "2022-01-03 08:04:05 AM"); #endif CHECK(fmt_lib::format(loc, "{:%Y%m%d%H%M%S}", tm) == "20220103080405"); - } catch (const std::runtime_error &) { + } catch (const std::runtime_error&) { WARN("Locale en_US not found, skip tests"); } } @@ -162,7 +164,7 @@ TEST_CASE("Format zoned time", "[clock][util]") { CHECK(fmt_lib::format(loc, "{:%F %T}", tm) == "2022-01-03 08:04:05"); #endif CHECK(fmt_lib::format(loc, "{:%Y%m%d%H%M%S}", tm) == "20220103080405"); - } catch (const std::runtime_error &) { + } catch (const std::runtime_error&) { WARN("Locale en_GB not found, skip tests"); } } @@ -181,7 +183,7 @@ TEST_CASE("Format zoned time", "[clock][util]") { CHECK(fmt_lib::format("{:%Y%m%d%H%M%S}", tm) == "20220103080405"); std::locale::global(loc); - } catch (const std::runtime_error &) { + } catch (const std::runtime_error&) { WARN("Locale en_US not found, skip tests"); } } diff --git a/test/utils/meson.build b/test/utils/meson.build index b7b3665a..e8dd37fa 100644 --- a/test/utils/meson.build +++ b/test/utils/meson.build @@ -13,6 +13,8 @@ test_src = files( '../../src/config.cpp', 'JsonParser.cpp', 'SafeSignal.cpp', + 'sleeper_thread.cpp', + 'command.cpp', 'css_reload_helper.cpp', '../../src/util/css_reload_helper.cpp', ) diff --git a/test/utils/sleeper_thread.cpp b/test/utils/sleeper_thread.cpp new file mode 100644 index 00000000..9e1a1ef3 --- /dev/null +++ b/test/utils/sleeper_thread.cpp @@ -0,0 +1,80 @@ +#if __has_include() +#include +#else +#include +#endif + +#include +#include + +#include +#include + +#include "util/sleeper_thread.hpp" + +namespace waybar::util { +SafeSignal& prepare_for_sleep() { + static SafeSignal signal; + return signal; +} +} // namespace waybar::util + +namespace { +int run_in_subprocess(int (*task)()) { + const auto pid = fork(); + if (pid < 0) { + return -1; + } + if (pid == 0) { + alarm(5); + _exit(task()); + } + + int status = -1; + if (waitpid(pid, &status, 0) != pid) { + return -1; + } + if (!WIFEXITED(status)) { + return -1; + } + return WEXITSTATUS(status); +} + +int run_reassignment_regression() { + waybar::util::SleeperThread thread; + thread = [] { std::this_thread::sleep_for(std::chrono::milliseconds(10)); }; + thread = [] { std::this_thread::sleep_for(std::chrono::milliseconds(1)); }; + return 0; +} + +int run_control_flag_stress() { + for (int i = 0; i < 200; ++i) { + waybar::util::SleeperThread thread; + thread = [&thread] { thread.sleep_for(std::chrono::milliseconds(1)); }; + + std::thread waker([&thread] { + for (int j = 0; j < 100; ++j) { + thread.wake_up(); + std::this_thread::yield(); + } + }); + + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + thread.stop(); + waker.join(); + if (thread.isRunning()) { + return 1; + } + } + return 0; +} +} // namespace + +TEST_CASE("SleeperThread reassignment does not terminate process", "[util][sleeper_thread]") { + REQUIRE(run_in_subprocess(run_reassignment_regression) == 0); +} + +TEST_CASE("SleeperThread control flags are stable under concurrent wake and stop", + "[util][sleeper_thread]") { + REQUIRE(run_in_subprocess(run_control_flag_stress) == 0); +} diff --git a/tsan.supp b/tsan.supp new file mode 100644 index 00000000..48a47611 --- /dev/null +++ b/tsan.supp @@ -0,0 +1,7 @@ +# Suppress common thread issues in dependencies, these are often non-fixable or not an issue. +# Use it like this (when in repo root): TSAN_OPTIONS="suppressions=./tsan.supp" ./build/waybar +race:libfontconfig.so +race:libglib-2.0.so +race:libpango-1.0.so +race:libc.so.6 +race:libgio-2.0.so