pax_global_header00006660000000000000000000000064147560316530014524gustar00rootroot0000000000000052 comment=8490a1d9b9a5c8770dd63e9faca0a5e01acedcae waybar-0.12.0/000077500000000000000000000000001475603165300130715ustar00rootroot00000000000000waybar-0.12.0/.clang-format000066400000000000000000000001221475603165300154370ustar00rootroot00000000000000--- BasedOnStyle: Google AlignConsecutiveDeclarations: false ColumnLimit: 100 ... waybar-0.12.0/.clang-tidy000066400000000000000000000025651475603165300151350ustar00rootroot00000000000000Checks: > -*, bugprone-* misc-*, modernize-*, performance-*, portability-*, readability-*, -fuchsia-trailing-return, -readability-magic-numbers, -modernize-use-nodiscard, -modernize-use-trailing-return-type, -readability-braces-around-statements, -readability-redundant-access-specifiers, -readability-redundant-member-init, -readability-redundant-string-init, -readability-identifier-length # CheckOptions: # - { key: readability-identifier-naming.NamespaceCase, value: lower_case } # - { key: readability-identifier-naming.ClassCase, value: CamelCase } # - { key: readability-identifier-naming.StructCase, value: CamelCase } # - { key: readability-identifier-naming.FunctionCase, value: camelBack } # - { key: readability-identifier-naming.VariableCase, value: camelBack } # - { key: readability-identifier-naming.PrivateMemberCase, value: camelBack } # - { key: readability-identifier-naming.PrivateMemberSuffix, value: _ } # - { key: readability-identifier-naming.EnumCase, value: CamelCase } # - { key: readability-identifier-naming.EnumConstantCase, value: UPPER_CASE } # - { key: readability-identifier-naming.GlobalConstantCase, value: UPPER_CASE } # - { key: readability-identifier-naming.StaticConstantCase, value: UPPER_CASE } waybar-0.12.0/.editorconfig000066400000000000000000000004701475603165300155470ustar00rootroot00000000000000# EditorConfig configuration for Waybar # http://EditorConfig.org # Top-most EditorConfig file root = true [*] end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true charset = utf-8 [*.{build,css}] indent_style = space indent_size = 4 [*.{hpp,cpp}] indent_style = space indent_size = 2 waybar-0.12.0/.envrc000066400000000000000000000000121475603165300142000ustar00rootroot00000000000000use flake waybar-0.12.0/.github/000077500000000000000000000000001475603165300144315ustar00rootroot00000000000000waybar-0.12.0/.github/FUNDING.yml000066400000000000000000000001441475603165300162450ustar00rootroot00000000000000# These are supported funding model platforms github: Alexays custom: https://paypal.me/ARouillard waybar-0.12.0/.github/labeler.yml000066400000000000000000000015461475603165300165700ustar00rootroot00000000000000bug: - "(crash|bug|error|coredump|freeze|segfault|issue|problem)" enhancement: - "(feature|enhancement|improvement|request|suggestion)" hyprland: - "(hyprland)" network: - "(network|wifi|ethernet)" bluetooth: - "(bluetooth|bluez)" sway: - "(sway)" cpu: - "(cpu)" memory: - "(memory|ram)" disk: - "(disk|storage)" battery: - "(upower|battery)" sni: - "(sni|tray)" dwl: - "(dwl)" custom: - "(custom|module|extension|plugin|script)" mpd: - "(mpd|music)" audio: - "(pulseaudio|alsa|jack|audio|pirewire|wireplumber)" temperature: - "(temperature|thermal|hwmon)" clock: - "(clock|time|date)" gamemode: - "(gamemode|game|gaming)" inhibitor: - "(inhibitor|idle|lock|suspend|hibernate|logout)" cava: - "(cava|audio-visualizer)" backlight: - "(backlight|brightness)" keyboard: - "(keyboard|keymap|layout|shortcut)" waybar-0.12.0/.github/workflows/000077500000000000000000000000001475603165300164665ustar00rootroot00000000000000waybar-0.12.0/.github/workflows/clang-format.yml000066400000000000000000000007531475603165300215700ustar00rootroot00000000000000name: clang-format on: [push, pull_request] concurrency: group: ${{ github.workflow }}-format-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: DoozyX/clang-format-lint-action@v0.16.2 name: clang-format with: source: "." extensions: "hpp,h,cpp,c" style: "file:.clang-format" clangFormatVersion: 19 waybar-0.12.0/.github/workflows/clang-tidy.yml.bak000066400000000000000000000031041475603165300217760ustar00rootroot00000000000000name: clang-tidy on: [push, pull_request] concurrency: group: ${{ github.workflow }}-tidy-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true jobs: build: runs-on: ubuntu-latest container: image: alexays/waybar:debian steps: - uses: actions/checkout@v3 - name: configure run: | meson -Dcpp_std=c++20 build # necessary to generate compile_commands.json ninja -C build # necessary to find certain .h files (xdg, wayland, etc.) - uses: actions/setup-python@v5 with: python-version: '3.10' # to be kept in sync with cpp-linter-action update-environment: true # the python dist installed by the action needs LD_LIBRARY_PATH to work - uses: cpp-linter/cpp-linter-action@v2.9.1 name: clang-tidy id: clang-tidy-check env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} PIP_NO_CACHE_DIR: false with: style: "" # empty string => don't do clang-format checks here, we do them in clang-format.yml files-changed-only: true # only check files that have changed lines-changed-only: true # only check lines that have changed tidy-checks: "" # empty string => use the .clang-tidy file version: "17" # clang-tools version database: "build" # path to the compile_commands.json file - name: Check if clang-tidy failed on any files if: steps.clang-tidy-check.outputs.checks-failed > 0 run: echo "Some files failed the linting checks!" && exit 1 waybar-0.12.0/.github/workflows/docker.yml000066400000000000000000000016131475603165300204610ustar00rootroot00000000000000name: Build and Push Docker Image on: schedule: # run every night at midnight - cron: '0 0 * * *' jobs: build-and-push: runs-on: ubuntu-latest if: github.repository == 'Alexays/Waybar' strategy: fail-fast: false # don't fail the other jobs if one of the images fails to build matrix: os: [ 'alpine', 'archlinux', 'debian', 'fedora', 'gentoo', 'opensuse' ] steps: - name: Checkout repository uses: actions/checkout@v4 - name: Login to Docker Hub uses: docker/login-action@v3 with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} - name: Build and push Docker image uses: docker/build-push-action@v5 with: context: . file: Dockerfiles/${{ matrix.os }} push: true tags: alexays/waybar:${{ matrix.os }} waybar-0.12.0/.github/workflows/freebsd.yml000066400000000000000000000023731475603165300206300ustar00rootroot00000000000000name: freebsd on: [push, pull_request] concurrency: group: ${{ github.workflow }}-freebsd-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true jobs: clang: # Run actions in a FreeBSD VM on the ubuntu runner # https://github.com/actions/runner/issues/385 - for FreeBSD runner support runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Test in FreeBSD VM uses: cross-platform-actions/action@v0.25.0 timeout-minutes: 180 env: CPPFLAGS: '-isystem/usr/local/include' LDFLAGS: '-L/usr/local/lib' with: operating_system: freebsd version: "14.1" environment_variables: CPPFLAGS LDFLAGS sync_files: runner-to-vm run: | sudo pkg install -y git # subprojects/date sudo pkg install -y catch evdev-proto gtk-layer-shell gtkmm30 jsoncpp \ libdbusmenu libevdev libfmt libmpdclient libudev-devd meson \ pkgconf pipewire pulseaudio scdoc sndio spdlog wayland-protocols upower \ libinotify meson setup build -Dman-pages=enabled ninja -C build meson test -C build --no-rebuild --print-errorlogs --suite waybar waybar-0.12.0/.github/workflows/labeler.yml000066400000000000000000000005771475603165300206300ustar00rootroot00000000000000name: "Issue Labeler" on: issues: types: [opened, edited] permissions: issues: write contents: read jobs: triage: runs-on: ubuntu-latest steps: - uses: github/issue-labeler@v3.4 with: configuration-path: .github/labeler.yml enable-versioned-regex: 0 include-title: 1 repo-token: ${{ secrets.GITHUB_TOKEN }} waybar-0.12.0/.github/workflows/linux.yml000066400000000000000000000013331475603165300203500ustar00rootroot00000000000000name: linux on: [push, pull_request] concurrency: group: ${{ github.workflow }}-linux-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true jobs: build: strategy: fail-fast: false matrix: distro: - alpine - archlinux - debian - fedora - opensuse - gentoo cpp_std: [c++20] runs-on: ubuntu-latest container: image: alexays/waybar:${{ matrix.distro }} steps: - uses: actions/checkout@v3 - name: configure run: meson setup -Dman-pages=enabled -Dcpp_std=${{matrix.cpp_std}} build - name: build run: ninja -C build - name: test run: make test waybar-0.12.0/.github/workflows/nix-tests.yml000066400000000000000000000007051475603165300211510ustar00rootroot00000000000000name: "Nix-Tests" on: pull_request: push: 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 waybar-0.12.0/.github/workflows/nix-update-flake-lock.yml000066400000000000000000000012021475603165300232700ustar00rootroot00000000000000name: update-flake-lock on: workflow_dispatch: # allows manual triggering schedule: - cron: '0 0 1 * *' # Run monthly push: 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 - name: Install Nix uses: cachix/install-nix-action@v27 with: extra_nix_config: | access-tokens = github.com=${{ secrets.GITHUB_TOKEN }} - name: Update flake.lock uses: DeterminateSystems/update-flake-lock@v21 waybar-0.12.0/.gitignore000066400000000000000000000006551475603165300150670ustar00rootroot00000000000000.DS_Store *~ vgcore.* /.vscode /.idea /.cache *.swp packagecache /subprojects/**/ /build* /dist /meson.egg-info # Prerequisites *.d # Compiled Object files *.slo *.lo *.o *.obj # Precompiled Headers *.gch *.pch # Compiled Dynamic libraries *.so *.dylib *.dll # Fortran module files *.mod *.smod # Compiled Static libraries *.lai *.la *.a *.lib # Executables *.exe *.out *.app /.direnv/ # Nix result result-* .ccls-cache waybar-0.12.0/.gitmodules000066400000000000000000000001521475603165300152440ustar00rootroot00000000000000[submodule "package/archlinux"] path = package/archlinux url = https://aur.archlinux.org/waybar-git.git waybar-0.12.0/Dockerfiles/000077500000000000000000000000001475603165300153235ustar00rootroot00000000000000waybar-0.12.0/Dockerfiles/alpine000066400000000000000000000004601475603165300165160ustar00rootroot00000000000000# vim: ft=Dockerfile FROM alpine:latest RUN apk add --no-cache git meson alpine-sdk libinput-dev wayland-dev wayland-protocols mesa-dev libxkbcommon-dev eudev-dev pixman-dev gtkmm3-dev jsoncpp-dev pugixml-dev libnl3-dev pulseaudio-dev libmpdclient-dev sndio-dev scdoc libxkbcommon tzdata playerctl-dev waybar-0.12.0/Dockerfiles/archlinux000066400000000000000000000006231475603165300172440ustar00rootroot00000000000000# vim: ft=Dockerfile FROM archlinux:base-devel RUN pacman -Syu --noconfirm && \ pacman -S --noconfirm git meson base-devel libinput wayland wayland-protocols glib2-devel pixman libxkbcommon mesa gtkmm3 jsoncpp pugixml scdoc libpulse libdbusmenu-gtk3 libmpdclient gobject-introspection libxkbcommon playerctl iniparser fftw && \ sed -Ei 's/#(en_(US|GB)\.UTF)/\1/' /etc/locale.gen && locale-gen waybar-0.12.0/Dockerfiles/debian000066400000000000000000000022401475603165300164660ustar00rootroot00000000000000# vim: ft=Dockerfile FROM debian:sid RUN apt update && \ apt install --no-install-recommends --no-install-suggests -y \ build-essential \ catch2 \ cmake \ git \ gobject-introspection \ libdbusmenu-gtk3-dev \ libegl1-mesa-dev \ libfmt-dev \ libgbm-dev \ libgirepository1.0-dev \ libgles2-mesa-dev \ libgtk-layer-shell-dev \ libgtkmm-3.0-dev \ libhowardhinnant-date-dev \ libiniparser-dev \ libinput-dev \ libjack-jackd2-dev \ libjsoncpp-dev \ libmpdclient-dev \ libnl-3-dev \ libnl-genl-3-dev \ libpixman-1-dev \ libplayerctl-dev \ libpugixml-dev \ libpulse-dev \ libsndio-dev \ libspdlog-dev \ libudev-dev \ libupower-glib-dev \ libwayland-dev \ libwireplumber-0.5-dev \ libxkbcommon-dev \ libxkbregistry-dev \ locales \ meson \ ninja-build \ pkg-config \ python3-pip \ python3-venv \ scdoc \ sudo \ wayland-protocols \ && apt clean waybar-0.12.0/Dockerfiles/fedora000066400000000000000000000017001475603165300165040ustar00rootroot00000000000000# vim: ft=Dockerfile FROM fedora:latest RUN dnf install -y @c-development \ git-core glibc-langpack-en meson scdoc \ 'pkgconfig(catch2)' \ 'pkgconfig(date)' \ 'pkgconfig(dbusmenu-gtk3-0.4)' \ 'pkgconfig(fmt)' \ 'pkgconfig(gdk-pixbuf-2.0)' \ 'pkgconfig(gio-unix-2.0)' \ 'pkgconfig(gtk-layer-shell-0)' \ 'pkgconfig(gtkmm-3.0)' \ 'pkgconfig(jack)' \ 'pkgconfig(jsoncpp)' \ 'pkgconfig(libevdev)' \ 'pkgconfig(libinput)' \ 'pkgconfig(libmpdclient)' \ 'pkgconfig(libnl-3.0)' \ 'pkgconfig(libnl-genl-3.0)' \ 'pkgconfig(libpulse)' \ 'pkgconfig(libudev)' \ 'pkgconfig(playerctl)' \ 'pkgconfig(pugixml)' \ 'pkgconfig(sigc++-2.0)' \ 'pkgconfig(spdlog)' \ 'pkgconfig(upower-glib)' \ 'pkgconfig(wayland-client)' \ 'pkgconfig(wayland-cursor)' \ 'pkgconfig(wayland-protocols)' \ 'pkgconfig(wireplumber-0.5)' \ 'pkgconfig(xkbregistry)' && \ dnf clean all -y waybar-0.12.0/Dockerfiles/gentoo000066400000000000000000000013101475603165300165340ustar00rootroot00000000000000# vim: ft=Dockerfile FROM gentoo/stage3:latest RUN export FEATURES="-ipc-sandbox -network-sandbox -pid-sandbox -sandbox -usersandbox" && \ 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 \ 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 waybar-0.12.0/Dockerfiles/opensuse000066400000000000000000000011641475603165300171110ustar00rootroot00000000000000# vim: ft=Dockerfile FROM opensuse/tumbleweed:latest RUN zypper -n up && \ zypper addrepo https://download.opensuse.org/repositories/X11:Wayland/openSUSE_Tumbleweed/X11:Wayland.repo | echo 'a' && \ zypper -n refresh && \ zypper -n install -t pattern devel_C_C++ && \ zypper -n install git meson clang libinput10 libinput-devel pugixml-devel libwayland-client0 libwayland-cursor0 wayland-protocols-devel wayland-devel Mesa-libEGL-devel Mesa-libGLESv2-devel libgbm-devel libxkbcommon-devel libudev-devel libpixman-1-0-devel gtkmm3-devel jsoncpp-devel libxkbregistry-devel scdoc playerctl-devel python3-packaging waybar-0.12.0/LICENSE000066400000000000000000000020451475603165300140770ustar00rootroot00000000000000MIT License Copyright (c) 2025 Alex Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. waybar-0.12.0/Makefile000066400000000000000000000006251475603165300145340ustar00rootroot00000000000000.PHONY: build build-debug run clean default install default: build build: meson setup build ninja -C build build-debug: meson setup build --buildtype=debug ninja -C build install: build ninja -C build install run: build ./build/waybar debug-run: build-debug ./build/waybar --log-level debug test: meson test -C build --no-rebuild --verbose --suite waybar .PHONY: test clean: rm -rf build waybar-0.12.0/README.md000066400000000000000000000061751475603165300143610ustar00rootroot00000000000000# Waybar [![Licence](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE) [![Paypal Donate](https://img.shields.io/badge/Donate-Paypal-2244dd.svg)](https://paypal.me/ARouillard)
![Waybar](https://raw.githubusercontent.com/alexays/waybar/master/preview-2.png) > Highly customizable Wayland bar for Sway and Wlroots based compositors.
> Available in [all major distributions](https://github.com/Alexays/Waybar/wiki/Installation)
> *Waybar [examples](https://github.com/Alexays/Waybar/wiki/Examples)* #### Current features - Sway (Workspaces, Binding mode, Focused window name) - River (Mapping mode, Tags, Focused window name) - Hyprland (Window Icons, Workspaces, Focused window name) - Niri (Workspaces, Focused window name, Language) - DWL (Tags, Focused window name) [requires dwl ipc patch](https://codeberg.org/dwl/dwl-patches/src/branch/main/patches/ipc) - Tray [#21](https://github.com/Alexays/Waybar/issues/21) - Local time - Battery - UPower - Power profiles daemon - Network - Bluetooth - Pulseaudio - Privacy Info - Wireplumber - Disk - Memory - Cpu load average - Temperature - MPD - Custom scripts - Custom image - Multiple output configuration - And many more customizations #### Configuration and Styling [See the wiki for more details](https://github.com/Alexays/Waybar/wiki). ### Installation Waybar is available from a number of Linux distributions: [![Packaging status](https://repology.org/badge/vertical-allrepos/waybar.svg?columns=3&header=Waybar%20Downstream%20Packaging)](https://repology.org/project/waybar/versions) An Ubuntu PPA with more recent versions is available [here](https://launchpad.net/~nschloe/+archive/ubuntu/waybar). #### Building from source ```bash $ git clone https://github.com/Alexays/Waybar $ cd Waybar $ meson setup build $ ninja -C build $ ./build/waybar # If you want to install it $ ninja -C build install $ waybar ``` **Dependencies** ``` gtkmm3 jsoncpp libsigc++ fmt wayland chrono-date spdlog libgtk-3-dev [gtk-layer-shell] gobject-introspection [gtk-layer-shell] libgirepository1.0-dev [gtk-layer-shell] libpulse [Pulseaudio module] libnl [Network module] libappindicator-gtk3 [Tray module] libdbusmenu-gtk3 [Tray module] libmpdclient [MPD module] libsndio [sndio module] libevdev [KeyboardState module] xkbregistry upower [UPower battery module] ``` **Build dependencies** ``` cmake meson scdoc wayland-protocols ``` On Ubuntu, you can install all the relevant dependencies using this command (tested with 19.10 and 20.04): ``` sudo apt install \ clang-tidy \ gobject-introspection \ libdbusmenu-gtk3-dev \ libevdev-dev \ libfmt-dev \ libgirepository1.0-dev \ libgtk-3-dev \ libgtkmm-3.0-dev \ libinput-dev \ libjsoncpp-dev \ libmpdclient-dev \ libnl-3-dev \ libnl-genl-3-dev \ libpulse-dev \ libsigc++-2.0-dev \ libspdlog-dev \ libwayland-dev \ scdoc \ upower \ libxkbregistry-dev ``` Contributions welcome!
Have fun :)
The style guidelines are [Google's](https://google.github.io/styleguide/cppguide.html) ## License Waybar is licensed under the MIT license. [See LICENSE for more information](https://github.com/Alexays/Waybar/blob/master/LICENSE). waybar-0.12.0/default.nix000066400000000000000000000004611475603165300152360ustar00rootroot00000000000000(import ( let lock = builtins.fromJSON (builtins.readFile ./flake.lock); in fetchTarball { url = "https://github.com/edolstra/flake-compat/archive/${lock.nodes.flake-compat.locked.rev}.tar.gz"; sha256 = lock.nodes.flake-compat.locked.narHash; } ) { src = ./.; } ).defaultNix waybar-0.12.0/flake.lock000066400000000000000000000020361475603165300150260ustar00rootroot00000000000000{ "nodes": { "flake-compat": { "flake": false, "locked": { "lastModified": 1733328505, "narHash": "sha256-NeCCThCEP3eCl2l/+27kNNK7QrwZB1IJCrXfrbv5oqU=", "owner": "edolstra", "repo": "flake-compat", "rev": "ff81ac966bb2cae68946d5ed5fc4994f96d0ffec", "type": "github" }, "original": { "owner": "edolstra", "repo": "flake-compat", "type": "github" } }, "nixpkgs": { "locked": { "lastModified": 1738142207, "narHash": "sha256-NGqpVVxNAHwIicXpgaVqJEJWeyqzoQJ9oc8lnK9+WC4=", "owner": "NixOS", "repo": "nixpkgs", "rev": "9d3ae807ebd2981d593cddd0080856873139aa40", "type": "github" }, "original": { "owner": "NixOS", "ref": "nixos-unstable", "repo": "nixpkgs", "type": "github" } }, "root": { "inputs": { "flake-compat": "flake-compat", "nixpkgs": "nixpkgs" } } }, "root": "root", "version": 7 } waybar-0.12.0/flake.nix000066400000000000000000000044571475603165300147050ustar00rootroot00000000000000{ description = "Highly customizable Wayland bar for Sway and Wlroots based compositors"; inputs = { nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; flake-compat = { url = "github:edolstra/flake-compat"; flake = false; }; }; outputs = { self, nixpkgs, ... }: let inherit (nixpkgs) lib; genSystems = func: lib.genAttrs [ "x86_64-linux" "aarch64-linux" ] (system: func (import nixpkgs { inherit system; overlays = with self.overlays; [ waybar ]; })); mkDate = longDate: (lib.concatStringsSep "-" [ (builtins.substring 0 4 longDate) (builtins.substring 4 2 longDate) (builtins.substring 6 2 longDate) ]); in { devShells = genSystems (pkgs: { default = pkgs.mkShell { name = "waybar-shell"; # inherit attributes from upstream nixpkgs derivation inherit (pkgs.waybar) buildInputs depsBuildBuild depsBuildBuildPropagated depsBuildTarget depsBuildTargetPropagated depsHostHost depsHostHostPropagated depsTargetTarget depsTargetTargetPropagated propagatedBuildInputs propagatedNativeBuildInputs strictDeps; # overrides for local development nativeBuildInputs = pkgs.waybar.nativeBuildInputs ++ (with pkgs; [ clang-tools gdb ]); }; }); overlays = { default = self.overlays.waybar; waybar = final: prev: { waybar = final.callPackage ./nix/default.nix { waybar = prev.waybar; # take the first "version: '...'" from meson.build version = (builtins.head (builtins.split "'" (builtins.elemAt (builtins.split " version: '" (builtins.readFile ./meson.build)) 2))) + "+date=" + (mkDate (self.lastModifiedDate or "19700101")) + "_" + (self.shortRev or "dirty"); }; }; }; packages = genSystems (pkgs: { default = self.packages.${pkgs.stdenv.hostPlatform.system}.waybar; inherit (pkgs) waybar; }); }; } waybar-0.12.0/include/000077500000000000000000000000001475603165300145145ustar00rootroot00000000000000waybar-0.12.0/include/AAppIconLabel.hpp000066400000000000000000000014071475603165300176210ustar00rootroot00000000000000#pragma once #include #include #include "AIconLabel.hpp" 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, 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 updateAppIcon(); unsigned app_icon_size_{24}; bool update_app_icon_{true}; std::string app_icon_name_; }; } // namespace waybar waybar-0.12.0/include/AIconLabel.hpp000066400000000000000000000010721475603165300171560ustar00rootroot00000000000000#pragma once #include #include #include "ALabel.hpp" 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, bool enable_click = false, bool enable_scroll = false); virtual ~AIconLabel() = default; auto update() -> void override; protected: Gtk::Image image_; Gtk::Box box_; bool iconEnabled() const; }; } // namespace waybar waybar-0.12.0/include/ALabel.hpp000066400000000000000000000021431475603165300163450ustar00rootroot00000000000000#pragma once #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, 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); protected: Gtk::Label label_; std::string format_; const std::chrono::seconds interval_; bool alt_ = false; std::string default_format_; bool handleToggle(GdkEventButton *const &e) override; virtual std::string getState(uint8_t value, bool lesser = false); std::map submenus_; std::map menuActionsMap_; static void handleGtkMenuEvent(GtkMenuItem *menuitem, gpointer data); }; } // namespace waybar waybar-0.12.0/include/AModule.hpp000066400000000000000000000066211475603165300165600ustar00rootroot00000000000000#pragma once #include #include #include #include #include #include "IModule.hpp" namespace waybar { class AModule : public IModule { public: 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; /// Emitting on this dispatcher triggers a update() call Glib::Dispatcher dp; bool expandEnabled() const; 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, bool enable_scroll = false); enum SCROLL_DIR { NONE, UP, DOWN, LEFT, RIGHT }; SCROLL_DIR getScrollDir(GdkEventScroll *e); bool tooltipEnabled() const; const std::string name_; const Json::Value &config_; Gtk::EventBox event_box_; 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_; private: bool handleUserEvent(GdkEventButton *const &ev); const bool isTooltip; const bool isExpand; bool hasUserEvents_; std::vector pid_; gdouble distance_scrolled_y_; gdouble distance_scrolled_x_; std::map eventActionMap_; static const inline std::map, std::string> eventMap_{ {std::make_pair(1, GdkEventType::GDK_BUTTON_PRESS), "on-click"}, {std::make_pair(1, GdkEventType::GDK_BUTTON_RELEASE), "on-click-release"}, {std::make_pair(1, GdkEventType::GDK_2BUTTON_PRESS), "on-double-click"}, {std::make_pair(1, GdkEventType::GDK_3BUTTON_PRESS), "on-triple-click"}, {std::make_pair(2, GdkEventType::GDK_BUTTON_PRESS), "on-click-middle"}, {std::make_pair(2, GdkEventType::GDK_BUTTON_RELEASE), "on-click-middle-release"}, {std::make_pair(2, GdkEventType::GDK_2BUTTON_PRESS), "on-double-click-middle"}, {std::make_pair(2, GdkEventType::GDK_3BUTTON_PRESS), "on-triple-click-middle"}, {std::make_pair(3, GdkEventType::GDK_BUTTON_PRESS), "on-click-right"}, {std::make_pair(3, GdkEventType::GDK_BUTTON_RELEASE), "on-click-right-release"}, {std::make_pair(3, GdkEventType::GDK_2BUTTON_PRESS), "on-double-click-right"}, {std::make_pair(3, GdkEventType::GDK_3BUTTON_PRESS), "on-triple-click-right"}, {std::make_pair(8, GdkEventType::GDK_BUTTON_PRESS), "on-click-backward"}, {std::make_pair(8, GdkEventType::GDK_BUTTON_RELEASE), "on-click-backward-release"}, {std::make_pair(8, GdkEventType::GDK_2BUTTON_PRESS), "on-double-click-backward"}, {std::make_pair(8, GdkEventType::GDK_3BUTTON_PRESS), "on-triple-click-backward"}, {std::make_pair(9, GdkEventType::GDK_BUTTON_PRESS), "on-click-forward"}, {std::make_pair(9, GdkEventType::GDK_BUTTON_RELEASE), "on-click-forward-release"}, {std::make_pair(9, GdkEventType::GDK_2BUTTON_PRESS), "on-double-click-forward"}, {std::make_pair(9, GdkEventType::GDK_3BUTTON_PRESS), "on-triple-click-forward"}}; }; } // namespace waybar waybar-0.12.0/include/ASlider.hpp000066400000000000000000000005621475603165300165530ustar00rootroot00000000000000#pragma once #include "AModule.hpp" #include "gtkmm/scale.h" namespace waybar { class ASlider : public AModule { public: ASlider(const Json::Value& config, const std::string& name, const std::string& id); virtual void onValueChanged(); protected: bool vertical_ = false; int min_ = 0, max_ = 100, curr_ = 50; Gtk::Scale scale_; }; } // namespace waybarwaybar-0.12.0/include/IModule.hpp000066400000000000000000000004331475603165300165630ustar00rootroot00000000000000#pragma once #include namespace waybar { class IModule { public: virtual ~IModule() = default; virtual auto update() -> void = 0; virtual operator Gtk::Widget&() = 0; virtual auto doAction(const std::string& name) -> void = 0; }; } // namespace waybar waybar-0.12.0/include/bar.hpp000066400000000000000000000056351475603165300160020ustar00rootroot00000000000000#pragma once #include #include #include #include #include #include #include #include #include #include #include "AModule.hpp" #include "group.hpp" #include "xdg-output-unstable-v1-client-protocol.h" namespace waybar { class Factory; struct waybar_output { Glib::RefPtr monitor; std::string name; std::string identifier; std::unique_ptr xdg_output = { nullptr, &zxdg_output_v1_destroy}; }; enum class bar_layer : uint8_t { BOTTOM, TOP, OVERLAY, }; struct bar_margins { int top = 0; int right = 0; int bottom = 0; int left = 0; }; struct bar_mode { bar_layer layer; bool exclusive; bool passthrough; bool visible; }; #ifdef HAVE_SWAY namespace modules::sway { class BarIpcClient; } #endif // HAVE_SWAY class Bar : public sigc::trackable { public: using bar_mode_map = std::map; static const bar_mode_map PRESET_MODES; 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(); void setMode(const std::string &mode); void setVisible(bool value); void toggle(); void handleSignal(int); struct waybar_output *output; Json::Value config; struct wl_surface *surface; bool visible = true; Gtk::Window window; Gtk::Orientation orientation = Gtk::ORIENTATION_HORIZONTAL; Gtk::PositionType position = Gtk::POS_TOP; int x_global; int y_global; #ifdef HAVE_SWAY std::string bar_id; #endif private: 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 setPassThrough(bool passthrough); void setPosition(Gtk::PositionType position); void onConfigure(GdkEventConfigure *ev); void configureGlobalOffset(int width, int height); void onOutputGeometryChanged(); /* Copy initial set of modes to allow customization */ bar_mode_map configured_modes = PRESET_MODES; std::string last_mode_{MODE_DEFAULT}; struct bar_margins margins_; uint32_t width_, height_; bool passthrough_; Gtk::Box left_; Gtk::Box center_; Gtk::Box right_; Gtk::Box box_; std::vector> modules_left_; std::vector> modules_center_; std::vector> modules_right_; #ifdef HAVE_SWAY using BarIpcClient = modules::sway::BarIpcClient; std::unique_ptr _ipc_client; #endif std::vector> modules_all_; }; } // namespace waybar waybar-0.12.0/include/client.hpp000066400000000000000000000041211475603165300165010ustar00rootroot00000000000000#pragma once #include #include #include #include #include "bar.hpp" #include "config.hpp" #include "util/css_reload_helper.hpp" #include "util/portal.hpp" struct zwp_idle_inhibitor_v1; struct zwp_idle_inhibit_manager_v1; namespace waybar { class Client { public: 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; std::vector> bars; Config config; std::string bar_id; private: Client() = default; 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); 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 *); void handleMonitorAdded(Glib::RefPtr monitor); void handleMonitorRemoved(Glib::RefPtr monitor); void handleDeferredMonitorRemoval(Glib::RefPtr monitor); Glib::RefPtr style_context_; Glib::RefPtr css_provider_; std::unique_ptr portal; std::list outputs_; std::unique_ptr m_cssReloadHelper; std::string m_cssFile; }; } // namespace waybar waybar-0.12.0/include/config.hpp000066400000000000000000000022201475603165300164660ustar00rootroot00000000000000#pragma once #include #include #include #ifndef SYSCONFDIR #define SYSCONFDIR "/etc" #endif namespace waybar { class Config { public: static const std::vector CONFIG_DIRS; 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); static std::vector tryExpandPath(const std::string &base, const std::string &filename); Config() = default; void load(const std::string &config); Json::Value &getConfig() { return config_; } 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_); std::string config_file_; Json::Value config_; }; } // namespace waybar waybar-0.12.0/include/factory.hpp000066400000000000000000000005221475603165300166730ustar00rootroot00000000000000#pragma once #include #include namespace waybar { class Bar; class Factory { public: Factory(const Bar& bar, const Json::Value& config); AModule* makeModule(const std::string& name, const std::string& pos) const; private: const Bar& bar_; const Json::Value& config_; }; } // namespace waybar waybar-0.12.0/include/group.hpp000066400000000000000000000016221475603165300163620ustar00rootroot00000000000000#pragma once #include #include #include #include "AModule.hpp" #include "gtkmm/revealer.h" namespace waybar { class Group : public AModule { public: Group(const std::string &, const std::string &, const Json::Value &, bool); ~Group() override = default; auto update() -> void override; operator Gtk::Widget &() override; virtual Gtk::Box &getBox(); void addWidget(Gtk::Widget &widget); protected: Gtk::Box box; Gtk::Box revealer_box; Gtk::Revealer revealer; bool is_first_widget = true; 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; void show_group(); void hide_group(); }; } // namespace waybar waybar-0.12.0/include/modules/000077500000000000000000000000001475603165300161645ustar00rootroot00000000000000waybar-0.12.0/include/modules/backlight.hpp000066400000000000000000000011541475603165300206260ustar00rootroot00000000000000#pragma once #include #include #include #include #include #include "ALabel.hpp" #include "util/backlight_backend.hpp" #include "util/json.hpp" struct udev; struct udev_device; namespace waybar::modules { class Backlight : public ALabel { public: Backlight(const std::string &, const Json::Value &); virtual ~Backlight() = default; auto update() -> void override; bool handleScroll(GdkEventScroll *e) override; const std::string preferred_device_; std::string previous_format_; util::BacklightBackend backend; }; } // namespace waybar::modules waybar-0.12.0/include/modules/backlight_slider.hpp000066400000000000000000000007461475603165300221760ustar00rootroot00000000000000#pragma once #include #include "ASlider.hpp" #include "util/backlight_backend.hpp" namespace waybar::modules { class BacklightSlider : public ASlider { public: BacklightSlider(const std::string&, const Json::Value&); virtual ~BacklightSlider() = default; void update() override; void onValueChanged() override; private: std::chrono::milliseconds interval_; std::string preferred_device_; util::BacklightBackend backend; }; } // namespace waybar::moduleswaybar-0.12.0/include/modules/battery.hpp000066400000000000000000000023461475603165300203540ustar00rootroot00000000000000#pragma once #include #include #if defined(__linux__) #include #endif #include #include #include #include #include "ALabel.hpp" #include "bar.hpp" #include "util/sleeper_thread.hpp" namespace waybar::modules { namespace fs = std::filesystem; class Battery : public ALabel { public: Battery(const std::string&, const waybar::Bar&, const Json::Value&); virtual ~Battery(); auto update() -> void override; private: static inline const fs::path data_dir_ = "/sys/class/power_supply/"; void refreshBatteries(); void worker(); const std::string getAdapterStatus(uint8_t capacity) const; std::tuple getInfos(); const std::string formatTimeRemaining(float hoursRemaining); void setBarClass(std::string&); int global_watch; std::map batteries_; fs::path adapter_; int battery_watch_fd_; int global_watch_fd_; std::mutex battery_list_mutex_; std::string old_status_; bool warnFirstTime_{true}; const Bar& bar_; util::SleeperThread thread_; util::SleeperThread thread_battery_update_; util::SleeperThread thread_timer_; }; } // namespace waybar::modules waybar-0.12.0/include/modules/bluetooth.hpp000066400000000000000000000050031475603165300207000ustar00rootroot00000000000000#pragma once #include "ALabel.hpp" #ifdef WANT_RFKILL #include "util/rfkill.hpp" #endif #include #include #include #include namespace waybar::modules { class Bluetooth : public ALabel { struct ControllerInfo { std::string path; std::string address; std::string address_type; // std::string name; // just use alias instead std::string alias; bool powered; bool discoverable; bool pairable; bool discovering; }; // NOTE: there are some properties that not all devices provide struct DeviceInfo { std::string path; std::string paired_controller; std::string address; std::string address_type; // std::optional name; // just use alias instead std::string alias; std::optional icon; bool paired; bool trusted; bool blocked; bool connected; bool services_resolved; // NOTE: experimental feature in bluez std::optional battery_percentage; }; public: Bluetooth(const std::string&, const Json::Value&); virtual ~Bluetooth() = default; auto update() -> void override; private: static auto onObjectAdded(GDBusObjectManager*, GDBusObject*, gpointer) -> void; static auto onObjectRemoved(GDBusObjectManager*, GDBusObject*, gpointer) -> void; static auto onInterfaceAddedOrRemoved(GDBusObjectManager*, GDBusObject*, GDBusInterface*, gpointer) -> void; static auto onInterfaceProxyPropertiesChanged(GDBusObjectManagerClient*, GDBusObjectProxy*, GDBusProxy*, GVariant*, const gchar* const*, gpointer) -> void; auto getDeviceBatteryPercentage(GDBusObject*) -> std::optional; auto getDeviceProperties(GDBusObject*, DeviceInfo&) -> bool; auto getControllerProperties(GDBusObject*, ControllerInfo&) -> bool; // Returns std::nullopt if no controller could be found auto findCurController() -> std::optional; auto findConnectedDevices(const std::string&, std::vector&) -> void; #ifdef WANT_RFKILL util::Rfkill rfkill_; #endif const std::unique_ptr manager_; std::string state_; std::optional cur_controller_; std::vector connected_devices_; DeviceInfo cur_focussed_device_; std::string device_enumerate_; std::vector device_preference_; }; } // namespace waybar::modules waybar-0.12.0/include/modules/cava.hpp000066400000000000000000000027711475603165300176160ustar00rootroot00000000000000#pragma once #include "ALabel.hpp" #include "util/sleeper_thread.hpp" namespace cava { extern "C" { #include } } // 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 waybar-0.12.0/include/modules/cffi.hpp000066400000000000000000000030411475603165300176020ustar00rootroot00000000000000#pragma once #include #include "AModule.hpp" #include "util/command.hpp" #include "util/json.hpp" #include "util/sleeper_thread.hpp" namespace waybar::modules { namespace ffi { extern "C" { typedef struct wbcffi_module wbcffi_module; typedef struct { wbcffi_module* obj; const char* waybar_version; GtkContainer* (*get_root_widget)(wbcffi_module*); void (*queue_update)(wbcffi_module*); } wbcffi_init_info; struct wbcffi_config_entry { const char* key; const char* value; }; } } // namespace ffi class CFFI : public AModule { public: CFFI(const std::string&, const std::string&, const Json::Value&); virtual ~CFFI(); virtual auto refresh(int signal) -> void override; virtual auto doAction(const std::string& name) -> void override; virtual auto update() -> void override; private: /// void* cffi_instance_ = nullptr; typedef void*(InitFn)(const ffi::wbcffi_init_info* init_info, const ffi::wbcffi_config_entry* config_entries, size_t config_entries_len); typedef void(DenitFn)(void* instance); typedef void(RefreshFn)(void* instance, int signal); typedef void(DoActionFn)(void* instance, const char* name); typedef void(UpdateFn)(void* instance); // FFI hooks struct { std::function init = nullptr; std::function deinit = nullptr; std::function refresh = [](void*, int) {}; std::function doAction = [](void*, const char*) {}; std::function update = [](void*) {}; } hooks_; }; } // namespace waybar::modules waybar-0.12.0/include/modules/clock.hpp000066400000000000000000000066131475603165300177760ustar00rootroot00000000000000#pragma once #include "ALabel.hpp" #include "util/date.hpp" #include "util/sleeper_thread.hpp" namespace waybar::modules { const std::string kCldPlaceholder{"calendar"}; const std::string kTZPlaceholder{"tz_list"}; const std::string kOrdPlaceholder{"ordinal_date"}; enum class CldMode { MONTH, YEAR }; enum class WS { LEFT, RIGHT, HIDDEN }; class Clock final : public ALabel { public: Clock(const std::string&, const Json::Value&); virtual ~Clock() = default; auto update() -> void override; auto doAction(const std::string&) -> void override; private: const std::locale m_locale_; // tooltip const std::string m_tlpFmt_; std::string m_tlpText_{""}; // tooltip text to print const Glib::RefPtr m_tooltip_; // tooltip as a separate Gtk::Label bool query_tlp_cb(int, int, bool, const Glib::RefPtr& tooltip); // Calendar const bool cldInTooltip_; // calendar in tooltip /* 0 - calendar.format.months 1 - calendar.format.weekdays 2 - calendar.format.days 3 - calendar.format.today 4 - calendar.format.weeks 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) std::string cldText_{""}; // calendar text to print CldMode cldMode_{CldMode::MONTH}; auto get_calendar(const year_month_day& today, const year_month_day& ymd, const time_zone* tz) -> const std::string; // get local time zone auto local_zone() -> const 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 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 getTZtext(sys_seconds now) -> std::string; auto first_day_of_week() -> weekday; // Module actions void cldModeSwitch(); void cldShift_up(); void cldShift_down(); void cldShift_reset(); void tz_up(); void tz_down(); // Module Action Map static inline std::map actionMap_{ {"mode", &waybar::modules::Clock::cldModeSwitch}, {"shift_up", &waybar::modules::Clock::cldShift_up}, {"shift_down", &waybar::modules::Clock::cldShift_down}, {"shift_reset", &waybar::modules::Clock::cldShift_reset}, {"tz_up", &waybar::modules::Clock::tz_up}, {"tz_down", &waybar::modules::Clock::tz_down}}; }; } // namespace waybar::modules waybar-0.12.0/include/modules/cpu.hpp000066400000000000000000000010071475603165300174620ustar00rootroot00000000000000#pragma once #include #include #include #include #include #include #include #include "ALabel.hpp" #include "util/sleeper_thread.hpp" namespace waybar::modules { class Cpu : public ALabel { public: Cpu(const std::string&, const Json::Value&); virtual ~Cpu() = default; auto update() -> void override; private: std::vector> prev_times_; util::SleeperThread thread_; }; } // namespace waybar::modules waybar-0.12.0/include/modules/cpu_frequency.hpp000066400000000000000000000012431475603165300215450ustar00rootroot00000000000000#pragma once #include #include #include #include #include #include #include #include "ALabel.hpp" #include "util/sleeper_thread.hpp" namespace waybar::modules { class CpuFrequency : public ALabel { public: CpuFrequency(const std::string&, const Json::Value&); virtual ~CpuFrequency() = default; auto update() -> void override; // This is a static member because it is also used by the cpu module. static std::tuple getCpuFrequency(); private: static std::vector parseCpuFrequencies(); util::SleeperThread thread_; }; } // namespace waybar::modules waybar-0.12.0/include/modules/cpu_usage.hpp000066400000000000000000000014271475603165300206540ustar00rootroot00000000000000#pragma once #include #include #include #include #include #include #include #include "ALabel.hpp" #include "util/sleeper_thread.hpp" namespace waybar::modules { class CpuUsage : public ALabel { public: CpuUsage(const std::string&, const Json::Value&); virtual ~CpuUsage() = default; auto update() -> void override; // This is a static member because it is also used by the cpu module. static std::tuple, std::string> getCpuUsage( std::vector>&); private: static std::vector> parseCpuinfo(); std::vector> prev_times_; util::SleeperThread thread_; }; } // namespace waybar::modules waybar-0.12.0/include/modules/custom.hpp000066400000000000000000000021061475603165300202060ustar00rootroot00000000000000#pragma once #include #include #include #include "ALabel.hpp" #include "util/command.hpp" #include "util/json.hpp" #include "util/sleeper_thread.hpp" namespace waybar::modules { class Custom : public ALabel { public: Custom(const std::string&, const std::string&, const Json::Value&, const std::string&); virtual ~Custom(); auto update() -> void override; void refresh(int /*signal*/) override; private: void delayWorker(); void continuousWorker(); void waitingWorker(); void parseOutputRaw(); void parseOutputJson(); void handleEvent(); bool handleScroll(GdkEventScroll* e) override; bool handleToggle(GdkEventButton* const& e) override; const std::string name_; const std::string output_name_; std::string text_; std::string id_; std::string alt_; std::string tooltip_; const bool tooltip_format_enabled_; std::vector class_; int percentage_; FILE* fp_; int pid_; util::command::res output_; util::JsonParser parser_; util::SleeperThread thread_; }; } // namespace waybar::modules waybar-0.12.0/include/modules/disk.hpp000066400000000000000000000010161475603165300176250ustar00rootroot00000000000000#pragma once #include #include #include #include "ALabel.hpp" #include "util/format.hpp" #include "util/sleeper_thread.hpp" namespace waybar::modules { class Disk : public ALabel { public: Disk(const std::string&, const Json::Value&); virtual ~Disk() = default; auto update() -> void override; private: util::SleeperThread thread_; std::string path_; std::string unit_; float calc_specific_divisor(const std::string divisor); }; } // namespace waybar::modules waybar-0.12.0/include/modules/dwl/000077500000000000000000000000001475603165300167525ustar00rootroot00000000000000waybar-0.12.0/include/modules/dwl/tags.hpp000066400000000000000000000015601475603165300204230ustar00rootroot00000000000000#pragma once #include #include #include "AModule.hpp" #include "bar.hpp" #include "dwl-ipc-unstable-v2-client-protocol.h" #include "xdg-output-unstable-v1-client-protocol.h" namespace waybar::modules::dwl { class Tags : public waybar::AModule { public: 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); struct zdwl_ipc_manager_v2 *status_manager_; struct wl_seat *seat_; private: const waybar::Bar &bar_; Gtk::Box box_; std::vector buttons_; struct zdwl_ipc_output_v2 *output_status_; }; } /* namespace waybar::modules::dwl */ waybar-0.12.0/include/modules/dwl/window.hpp000066400000000000000000000015041475603165300207720ustar00rootroot00000000000000#pragma once #include #include #include "AAppIconLabel.hpp" #include "bar.hpp" #include "dwl-ipc-unstable-v2-client-protocol.h" #include "util/json.hpp" namespace waybar::modules::dwl { class Window : public AAppIconLabel, public sigc::trackable { public: 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_frame(); struct zdwl_ipc_manager_v2 *status_manager_; private: const Bar &bar_; std::string title_; std::string appid_; std::string layout_symbol_; uint32_t layout_; struct zdwl_ipc_output_v2 *output_status_; }; } // namespace waybar::modules::dwl waybar-0.12.0/include/modules/gamemode.hpp000066400000000000000000000050011475603165300204470ustar00rootroot00000000000000#pragma once #include #include #include #include "ALabel.hpp" #include "giomm/dbusconnection.h" #include "giomm/dbusproxy.h" #include "glibconfig.h" #include "gtkmm/box.h" #include "gtkmm/image.h" #include "gtkmm/label.h" #include "gtkmm/overlay.h" namespace waybar::modules { class Gamemode : public AModule { public: Gamemode(const std::string &, const Json::Value &); virtual ~Gamemode(); auto update() -> void override; private: const std::string DEFAULT_ICON_NAME = "input-gaming-symbolic"; 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 = ""; 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 getData(); bool handleToggle(GdkEventButton *const &) override; // Config std::string format = DEFAULT_FORMAT; std::string format_alt = DEFAULT_FORMAT_ALT; std::string tooltip_format = DEFAULT_TOOLTIP_FORMAT; std::string glyph = DEFAULT_GLYPH; bool tooltip = true; bool hideNotRunning = true; bool useIcon = true; uint iconSize = 20; uint iconSpacing = 4; std::string iconName = DEFAULT_ICON_NAME; Gtk::Box box_; Gtk::Image icon_; Gtk::Label label_; const std::string dbus_name = "com.feralinteractive.GameMode"; const std::string dbus_obj_path = "/com/feralinteractive/GameMode"; const std::string dbus_interface = "org.freedesktop.DBus.Properties"; const std::string dbus_get_interface = "com.feralinteractive.GameMode"; uint gameCount = 0; std::string lastStatus; bool showAltText = false; guint login1_id; Glib::RefPtr gamemode_proxy; Glib::RefPtr system_connection; bool gamemodeRunning; guint gamemodeWatcher_id; }; } // namespace waybar::modules waybar-0.12.0/include/modules/hyprland/000077500000000000000000000000001475603165300200055ustar00rootroot00000000000000waybar-0.12.0/include/modules/hyprland/backend.hpp000066400000000000000000000021511475603165300221040ustar00rootroot00000000000000#pragma once #include #include #include #include #include #include #include "util/json.hpp" namespace waybar::modules::hyprland { class EventHandler { public: virtual void onEvent(const std::string& ev) = 0; virtual ~EventHandler() = default; }; class IPC { public: IPC(); ~IPC(); static IPC& inst(); void registerForIPC(const std::string& ev, EventHandler* ev_handler); void unregisterForIPC(EventHandler* handler); static std::string getSocket1Reply(const std::string& rq); Json::Value getSocket1JsonReply(const std::string& rq); static std::filesystem::path getSocketFolder(const char* instanceSig); protected: static std::filesystem::path socketFolder_; private: void socketListener(); void parseIPC(const std::string&); std::thread ipcThread_; std::mutex callbackMutex_; util::JsonParser parser_; std::list> callbacks_; int socketfd_; // the hyprland socket file descriptor bool running_ = true; }; inline bool modulesReady = false; }; // namespace waybar::modules::hyprland waybar-0.12.0/include/modules/hyprland/language.hpp000066400000000000000000000014751475603165300223100ustar00rootroot00000000000000#pragma once #include #include #include "ALabel.hpp" #include "bar.hpp" #include "modules/hyprland/backend.hpp" #include "util/json.hpp" namespace waybar::modules::hyprland { class Language : public waybar::ALabel, public EventHandler { public: Language(const std::string&, const waybar::Bar&, const Json::Value&); virtual ~Language(); auto update() -> void override; private: void onEvent(const std::string&) override; void initLanguage(); struct Layout { std::string full_name; std::string short_name; std::string variant; std::string short_description; }; static auto getLayout(const std::string&) -> Layout; std::mutex mutex_; const Bar& bar_; util::JsonParser parser_; Layout layout_; IPC& m_ipc; }; } // namespace waybar::modules::hyprland waybar-0.12.0/include/modules/hyprland/submap.hpp000066400000000000000000000013321475603165300220040ustar00rootroot00000000000000#pragma once #include #include #include "ALabel.hpp" #include "bar.hpp" #include "modules/hyprland/backend.hpp" #include "util/json.hpp" namespace waybar::modules::hyprland { class Submap : public waybar::ALabel, public EventHandler { public: Submap(const std::string&, const waybar::Bar&, const Json::Value&); ~Submap() override; auto update() -> void override; private: auto parseConfig(const Json::Value&) -> void; void onEvent(const std::string& ev) override; std::mutex mutex_; const Bar& bar_; util::JsonParser parser_; std::string submap_; bool always_on_ = false; std::string default_submap_ = "Default"; IPC& m_ipc; }; } // namespace waybar::modules::hyprland waybar-0.12.0/include/modules/hyprland/window.hpp000066400000000000000000000027221475603165300220300ustar00rootroot00000000000000#pragma once #include #include #include "AAppIconLabel.hpp" #include "bar.hpp" #include "modules/hyprland/backend.hpp" #include "util/json.hpp" namespace waybar::modules::hyprland { class Window : public waybar::AAppIconLabel, public EventHandler { public: Window(const std::string&, const waybar::Bar&, const Json::Value&); ~Window() override; auto update() -> void override; private: struct Workspace { int id; int windows; std::string last_window; std::string last_window_title; static auto parse(const Json::Value& value) -> Workspace; }; struct WindowData { bool floating; int monitor = -1; std::string class_name; std::string initial_class_name; std::string title; std::string initial_title; bool fullscreen; bool grouped; static auto parse(const Json::Value&) -> WindowData; }; static auto getActiveWorkspace(const std::string&) -> Workspace; static 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_; util::JsonParser parser_; WindowData windowData_; Workspace workspace_; std::string soloClass_; std::string lastSoloClass_; bool solo_; bool allFloating_; bool swallowing_; bool fullscreen_; bool focused_; IPC& m_ipc; }; } // namespace waybar::modules::hyprland waybar-0.12.0/include/modules/hyprland/windowcreationpayload.hpp000066400000000000000000000031261475603165300251260ustar00rootroot00000000000000#pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include "AModule.hpp" #include "bar.hpp" #include "modules/hyprland/backend.hpp" #include "util/enum.hpp" #include "util/regex_collection.hpp" using WindowAddress = std::string; namespace waybar::modules::hyprland { class Workspaces; 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(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); std::string getWorkspaceName() const { return m_workspaceName; } WindowAddress getAddress() const { return m_windowAddress; } void moveToWorksace(std::string& new_workspace_name); private: void clearAddr(); void clearWorkspaceName(); using Repr = std::string; using ClassAndTitle = std::pair; std::variant m_window; WindowAddress m_windowAddress; std::string m_workspaceName; int m_timeSpentUncreated = 0; }; } // namespace waybar::modules::hyprland waybar-0.12.0/include/modules/hyprland/workspace.hpp000066400000000000000000000060451475603165300225210ustar00rootroot00000000000000#pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include "AModule.hpp" #include "bar.hpp" #include "modules/hyprland/backend.hpp" #include "modules/hyprland/windowcreationpayload.hpp" #include "util/enum.hpp" #include "util/regex_collection.hpp" using WindowAddress = std::string; namespace waybar::modules::hyprland { class Workspaces; class Workspace { public: explicit Workspace(const Json::Value& workspace_data, Workspaces& workspace_manager, const Json::Value& clients_data = Json::Value::nullRef); std::string& selectIcon(std::map& icons_map); Gtk::Button& button() { return m_button; }; int id() const { return m_id; }; std::string name() const { return m_name; }; std::string output() const { return m_output; }; bool isActive() const { return m_isActive; }; bool isSpecial() const { return m_isSpecial; }; bool isPersistent() const { return m_isPersistentRule || m_isPersistentConfig; }; 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; void setActive(bool value = true) { m_isActive = value; }; void setPersistentRule(bool value = true) { m_isPersistentRule = value; }; void setPersistentConfig(bool value = true) { m_isPersistentConfig = value; }; void setUrgent(bool value = true) { m_isUrgent = value; }; void setVisible(bool value = true) { m_isVisible = value; }; 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); void initializeWindowMap(const Json::Value& clients_data); bool onWindowOpened(WindowCreationPayload const& create_window_paylod); std::optional closeWindow(WindowAddress const& addr); void update(const std::string& format, const std::string& icon); private: Workspaces& m_workspaceManager; int m_id; std::string m_name; std::string m_output; uint m_windows; bool m_isActive = false; bool m_isSpecial = false; bool m_isPersistentRule = false; // represents the persistent state in hyprland bool m_isPersistentConfig = false; // represents the persistent state in the Waybar config bool m_isUrgent = false; bool m_isVisible = false; std::map m_windowMap; Gtk::Button m_button; Gtk::Box m_content; Gtk::Label m_label; IPC& m_ipc; }; } // namespace waybar::modules::hyprland waybar-0.12.0/include/modules/hyprland/workspaces.hpp000066400000000000000000000127651475603165300227120ustar00rootroot00000000000000#pragma once #include #include #include #include #include #include #include #include #include #include "AModule.hpp" #include "bar.hpp" #include "modules/hyprland/backend.hpp" #include "modules/hyprland/windowcreationpayload.hpp" #include "modules/hyprland/workspace.hpp" #include "util/enum.hpp" #include "util/regex_collection.hpp" using WindowAddress = std::string; namespace waybar::modules::hyprland { class Workspaces; class Workspaces : public AModule, public EventHandler { public: Workspaces(const std::string&, const waybar::Bar&, const Json::Value&); ~Workspaces() override; void update() override; void init(); auto allOutputs() const -> bool { return m_allOutputs; } auto showSpecial() const -> bool { return m_showSpecial; } auto activeOnly() const -> bool { return m_activeOnly; } auto specialVisibleOnly() const -> bool { return m_specialVisibleOnly; } auto moveToMonitor() const -> bool { return m_moveToMonitor; } auto getBarOutput() const -> std::string { return m_bar.output->name; } std::string getRewrite(std::string window_class, std::string window_title); std::string& getWindowSeparator() { return m_formatWindowSeparator; } bool isWorkspaceIgnored(std::string const& workspace_name); bool windowRewriteConfigUsesTitle() const { return m_anyWindowRewriteRuleUsesTitle; } private: void onEvent(const std::string& e) override; void updateWindowCount(); void sortWorkspaces(); void createWorkspace(Json::Value const& workspace_data, Json::Value const& clients_data = Json::Value::nullRef); static Json::Value createMonitorWorkspaceData(std::string const& name, std::string const& monitor); void removeWorkspace(std::string const& name); void setUrgentWorkspace(std::string const& windowaddress); // Config void parseConfig(const Json::Value& config); auto populateIconsMap(const Json::Value& formatIcons) -> void; static auto populateBoolConfig(const Json::Value& config, const std::string& key, bool& member) -> void; auto populateSortByConfig(const Json::Value& config) -> void; auto populateIgnoreWorkspacesConfig(const Json::Value& config) -> void; auto populateFormatWindowSeparatorConfig(const Json::Value& config) -> void; auto populateWindowRewriteConfig(const Json::Value& config) -> void; void registerIpc(); // workspace events void onWorkspaceActivated(std::string const& payload); void onSpecialWorkspaceActivated(std::string const& payload); void onWorkspaceDestroyed(std::string const& payload); void onWorkspaceCreated(std::string const& workspaceName, Json::Value const& clientsData = Json::Value::nullRef); void onWorkspaceMoved(std::string const& payload); void onWorkspaceRenamed(std::string const& payload); // monitor events void onMonitorFocused(std::string const& payload); // window events void onWindowOpened(std::string const& payload); void onWindowClosed(std::string const& addr); void onWindowMoved(std::string const& payload); void onWindowTitleEvent(std::string const& payload); void onConfigReloaded(); int windowRewritePriorityFunction(std::string const& window_rule); // Update methods void doUpdate(); void removeWorkspacesToRemove(); void createWorkspacesToCreate(); static std::vector getVisibleWorkspaces(); void updateWorkspaceStates(); bool updateWindowsToCreate(); void extendOrphans(int workspaceId, Json::Value const& clientsJson); void registerOrphanWindow(WindowCreationPayload create_window_payload); void initializeWorkspaces(); void setCurrentMonitorId(); void loadPersistentWorkspacesFromConfig(Json::Value const& clientsJson); void loadPersistentWorkspacesFromWorkspaceRules(const Json::Value& clientsJson); bool m_allOutputs = false; bool m_showSpecial = false; bool m_activeOnly = false; bool m_specialVisibleOnly = false; bool m_moveToMonitor = 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; enum class SortMethod { ID, NAME, NUMBER, DEFAULT }; util::EnumParser m_enumParser; SortMethod m_sortBy = SortMethod::DEFAULT; std::map m_sortMap = {{"ID", SortMethod::ID}, {"NAME", SortMethod::NAME}, {"NUMBER", SortMethod::NUMBER}, {"DEFAULT", SortMethod::DEFAULT}}; std::string m_format; std::map m_iconsMap; util::RegexCollection m_windowRewriteRules; bool m_anyWindowRewriteRuleUsesTitle = false; std::string m_formatWindowSeparator; bool m_withIcon; uint64_t m_monitorId; std::string m_activeWorkspaceName; std::string m_activeSpecialWorkspaceName; std::vector> m_workspaces; std::vector> m_workspacesToCreate; std::vector m_workspacesToRemove; std::vector m_windowsToCreate; std::vector m_ignoreWorkspaces; std::mutex m_mutex; const Bar& m_bar; Gtk::Box m_box; IPC& m_ipc; }; } // namespace waybar::modules::hyprland waybar-0.12.0/include/modules/idle_inhibitor.hpp000066400000000000000000000011571475603165300216650ustar00rootroot00000000000000#pragma once #include #include "ALabel.hpp" #include "bar.hpp" #include "client.hpp" namespace waybar::modules { class IdleInhibitor : public ALabel { sigc::connection timeout_; public: IdleInhibitor(const std::string&, const waybar::Bar&, const Json::Value&); virtual ~IdleInhibitor(); auto update() -> void override; static std::list modules; static bool status; private: bool handleToggle(GdkEventButton* const& e) override; void toggleStatus(); const Bar& bar_; struct zwp_idle_inhibitor_v1* idle_inhibitor_; int pid_; }; } // namespace waybar::modules waybar-0.12.0/include/modules/image.hpp000066400000000000000000000013571475603165300177650ustar00rootroot00000000000000#pragma once #include #include #include #include #include "ALabel.hpp" #include "gtkmm/box.h" #include "util/command.hpp" #include "util/json.hpp" #include "util/sleeper_thread.hpp" namespace waybar::modules { class Image : public AModule { public: Image(const std::string&, const Json::Value&); virtual ~Image() = default; auto update() -> void override; void refresh(int /*signal*/) override; private: void delayWorker(); void handleEvent(); void parseOutputRaw(); Gtk::Box box_; Gtk::Image image_; std::string path_; std::string tooltip_; int size_; int interval_; util::command::res output_; util::SleeperThread thread_; }; } // namespace waybar::modules waybar-0.12.0/include/modules/inhibitor.hpp000066400000000000000000000010771475603165300206710ustar00rootroot00000000000000#pragma once #include #include #include "ALabel.hpp" #include "bar.hpp" namespace waybar::modules { class Inhibitor : public ALabel { public: Inhibitor(const std::string&, const waybar::Bar&, const Json::Value&); virtual ~Inhibitor(); auto update() -> void override; auto activated() -> bool; private: auto handleToggle(::GdkEventButton* const& e) -> bool override; const std::unique_ptr<::GDBusConnection, void (*)(::GDBusConnection*)> dbus_; const std::string inhibitors_; int handle_ = -1; }; } // namespace waybar::modules waybar-0.12.0/include/modules/jack.hpp000066400000000000000000000016221475603165300176060ustar00rootroot00000000000000#pragma once #include #include #include #include #include "ALabel.hpp" #include "util/sleeper_thread.hpp" namespace waybar::modules { class JACK : public ALabel { public: JACK(const std::string &, const Json::Value &); virtual ~JACK() = default; auto update() -> void override; int bufSize(jack_nframes_t size); int sampleRate(jack_nframes_t rate); int xrun(); void shutdown(); private: std::string JACKState(); jack_client_t *client_; jack_nframes_t bufsize_; jack_nframes_t samplerate_; unsigned int xruns_; float load_; bool running_; std::mutex mutex_; std::string state_; util::SleeperThread thread_; }; } // 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); waybar-0.12.0/include/modules/keyboard_state.hpp000066400000000000000000000021071475603165300216750ustar00rootroot00000000000000#pragma once #include #include #include #include #include "AModule.hpp" #include "bar.hpp" #include "util/sleeper_thread.hpp" extern "C" { #include #include } namespace waybar::modules { class KeyboardState : public AModule { public: KeyboardState(const std::string&, const waybar::Bar&, const Json::Value&); virtual ~KeyboardState(); auto update() -> void override; private: auto tryAddDevice(const std::string&) -> void; Gtk::Box box_; Gtk::Label numlock_label_; Gtk::Label capslock_label_; Gtk::Label scrolllock_label_; std::string numlock_format_; std::string capslock_format_; std::string scrolllock_format_; const std::chrono::seconds interval_; std::string icon_locked_; std::string icon_unlocked_; std::string devices_path_; struct libinput* libinput_; std::unordered_map libinput_devices_; std::set binding_keys; util::SleeperThread libinput_thread_, hotplug_thread_; }; } // namespace waybar::modules waybar-0.12.0/include/modules/load.hpp000066400000000000000000000011221475603165300176100ustar00rootroot00000000000000#pragma once #include #include #include #include #include #include #include #include "ALabel.hpp" #include "util/sleeper_thread.hpp" namespace waybar::modules { class Load : public ALabel { public: Load(const std::string&, const Json::Value&); virtual ~Load() = default; auto update() -> void override; // This is a static member because it is also used by the cpu module. static std::tuple getLoad(); private: util::SleeperThread thread_; }; } // namespace waybar::modules waybar-0.12.0/include/modules/memory.hpp000066400000000000000000000007501475603165300202070ustar00rootroot00000000000000#pragma once #include #include #include #include "ALabel.hpp" #include "util/sleeper_thread.hpp" namespace waybar::modules { class Memory : public ALabel { public: Memory(const std::string&, const Json::Value&); virtual ~Memory() = default; auto update() -> void override; private: void parseMeminfo(); std::unordered_map meminfo_; util::SleeperThread thread_; }; } // namespace waybar::modules waybar-0.12.0/include/modules/mpd/000077500000000000000000000000001475603165300167445ustar00rootroot00000000000000waybar-0.12.0/include/modules/mpd/mpd.hpp000066400000000000000000000032021475603165300202320ustar00rootroot00000000000000#pragma once #include #include #include #include #include #include "ALabel.hpp" #include "modules/mpd/state.hpp" namespace waybar::modules { class MPD : public ALabel { friend class detail::Context; // State machine detail::Context context_{this}; const std::string module_name_; // Not using unique_ptr since we don't manage the pointer // (It's either nullptr, or from the config) const char* server_; const unsigned port_; const std::string password_; unsigned timeout_; detail::unique_connection connection_; detail::unique_status status_; mpd_state state_; detail::unique_song song_; public: MPD(const std::string&, const Json::Value&); virtual ~MPD() noexcept = default; auto update() -> void override; private: std::string getTag(mpd_tag_type type, unsigned idx = 0) const; std::string getFilename() const; void setLabel(); std::string getStateIcon() const; std::string getOptionIcon(std::string optionName, bool activated) const; // GUI-side methods bool handlePlayPause(GdkEventButton* const&); void emit() { dp.emit(); } // MPD-side, Non-GUI methods. 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; } inline bool paused() const { return connection_ && state_ == MPD_STATE_PAUSE; } }; #if !defined(MPD_NOINLINE) #include "modules/mpd/state.inl.hpp" #endif } // namespace waybar::modules waybar-0.12.0/include/modules/mpd/state.hpp000066400000000000000000000127521475603165300206040ustar00rootroot00000000000000#pragma once #include #include #include #include #include #include "ALabel.hpp" namespace waybar::modules { class MPD; } // namespace waybar::modules namespace waybar::modules::detail { using unique_connection = std::unique_ptr; using unique_status = std::unique_ptr; using unique_song = std::unique_ptr; class Context; /// This state machine loosely follows a non-hierarchical, statechart /// pattern, and includes ENTRY and EXIT actions. /// /// The State class is the base class for all other states. The /// entry and exit methods are automatically called when entering /// into a new state and exiting from the current state. This /// includes initially entering (Disconnected class) and exiting /// Waybar. /// /// The following nested "top-level" states are represented: /// 1. Idle - await notification of MPD activity. /// 2. All Non-Idle states: /// 1. Playing - An active song is producing audio output. /// 2. Paused - The current song is paused. /// 3. Stopped - No song is actively playing. /// 3. Disconnected - periodically attempt MPD (re-)connection. /// /// NOTE: Since this statechart is non-hierarchical, the above /// states are flattened into a set. class State { public: virtual ~State() noexcept = default; virtual void entry() noexcept { spdlog::debug("mpd: ignore entry action"); } virtual void exit() noexcept { spdlog::debug("mpd: ignore exit action"); } virtual void play() { spdlog::debug("mpd: ignore play state transition"); } virtual void stop() { spdlog::debug("mpd: ignore stop state transition"); } virtual void pause() { spdlog::debug("mpd: ignore pause state transition"); } /// Request state update the GUI. virtual void update() noexcept { spdlog::debug("mpd: ignoring update method request"); } }; class Idle : public State { Context* const ctx_; sigc::connection idle_connection_; public: Idle(Context* const ctx) : ctx_{ctx} {} virtual ~Idle() noexcept { this->exit(); }; void entry() noexcept override; void exit() noexcept override; void play() override; void stop() override; void pause() override; void update() noexcept override; private: Idle(const Idle&) = delete; Idle& operator=(const Idle&) = delete; bool on_io(Glib::IOCondition const&); }; class Playing : public State { Context* const ctx_; sigc::connection timer_connection_; public: Playing(Context* const ctx) : ctx_{ctx} {} virtual ~Playing() noexcept { this->exit(); } void entry() noexcept override; void exit() noexcept override; void pause() override; void stop() override; void update() noexcept override; private: Playing(Playing const&) = delete; Playing& operator=(Playing const&) = delete; bool on_timer(); }; class Paused : public State { Context* const ctx_; sigc::connection timer_connection_; public: Paused(Context* const ctx) : ctx_{ctx} {} virtual ~Paused() noexcept { this->exit(); } void entry() noexcept override; void exit() noexcept override; void play() override; void stop() override; void update() noexcept override; private: Paused(Paused const&) = delete; Paused& operator=(Paused const&) = delete; bool on_timer(); }; class Stopped : public State { Context* const ctx_; sigc::connection timer_connection_; public: Stopped(Context* const ctx) : ctx_{ctx} {} virtual ~Stopped() noexcept { this->exit(); } void entry() noexcept override; void exit() noexcept override; void play() override; void pause() override; void update() noexcept override; private: Stopped(Stopped const&) = delete; Stopped& operator=(Stopped const&) = delete; bool on_timer(); }; class Disconnected : public State { Context* const ctx_; sigc::connection timer_connection_; int last_interval_; public: Disconnected(Context* const ctx) : ctx_{ctx} {} virtual ~Disconnected() noexcept { this->exit(); } void entry() noexcept override; void exit() noexcept override; void update() noexcept override; private: Disconnected(Disconnected const&) = delete; Disconnected& operator=(Disconnected const&) = delete; bool arm_timer(int interval) noexcept; void disarm_timer() noexcept; bool on_timer(); }; class Context { std::unique_ptr state_; waybar::modules::MPD* mpd_module_; friend class State; friend class Playing; friend class Paused; friend class Stopped; friend class Disconnected; friend class Idle; protected: void setState(std::unique_ptr&& new_state) noexcept { if (state_.get() != nullptr) { state_->exit(); } state_ = std::move(new_state); state_->entry(); } bool is_connected() const; bool is_playing() const; bool is_paused() const; bool is_stopped() const; constexpr std::size_t interval() const; void tryConnect() const; void checkErrors(mpd_connection*) const; void do_update(); void queryMPD() const; void fetchState() const; constexpr mpd_state state() const; void emit() const; [[nodiscard]] unique_connection& connection(); public: explicit Context(waybar::modules::MPD* const mpd_module) : state_{std::make_unique(this)}, mpd_module_{mpd_module} { state_->entry(); } void play() { state_->play(); } void stop() { state_->stop(); } void pause() { state_->pause(); } void update() noexcept { state_->update(); } }; } // namespace waybar::modules::detail waybar-0.12.0/include/modules/mpd/state.inl.hpp000066400000000000000000000020521475603165300213550ustar00rootroot00000000000000#pragma once namespace detail { 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(); } inline void Context::tryConnect() const { mpd_module_->tryConnect(); } inline unique_connection& Context::connection() { return mpd_module_->connection_; } constexpr inline mpd_state Context::state() const { return mpd_module_->state_; } inline void Context::do_update() { mpd_module_->setLabel(); } inline void Context::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(); } } // namespace detail waybar-0.12.0/include/modules/mpris/000077500000000000000000000000001475603165300173165ustar00rootroot00000000000000waybar-0.12.0/include/modules/mpris/mpris.hpp000066400000000000000000000050761475603165300211710ustar00rootroot00000000000000#pragma once #include #include #include #include "gtkmm/box.h" #include "gtkmm/label.h" extern "C" { #include } #include "ALabel.hpp" #include "util/sleeper_thread.hpp" namespace waybar::modules::mpris { class Mpris : public ALabel { public: Mpris(const std::string&, const Json::Value&); virtual ~Mpris(); auto update() -> void override; bool handleToggle(GdkEventButton* const&) override; private: static auto onPlayerNameAppeared(PlayerctlPlayerManager*, PlayerctlPlayerName*, gpointer) -> void; static auto onPlayerNameVanished(PlayerctlPlayerManager*, PlayerctlPlayerName*, gpointer) -> void; static auto onPlayerPlay(PlayerctlPlayer*, gpointer) -> void; static auto onPlayerPause(PlayerctlPlayer*, gpointer) -> void; static auto onPlayerStop(PlayerctlPlayer*, gpointer) -> void; static auto onPlayerMetadata(PlayerctlPlayer*, GVariant*, gpointer) -> void; struct PlayerInfo { std::string name; PlayerctlPlaybackStatus status; std::string status_string; std::optional artist; std::optional album; std::optional title; std::optional length; // as HH:MM:SS std::optional position; // same format }; auto getPlayerInfo() -> std::optional; auto getIconFromJson(const Json::Value&, const std::string&) -> std::string; auto getArtistStr(const PlayerInfo&, bool) -> std::string; auto getAlbumStr(const PlayerInfo&, bool) -> std::string; auto getTitleStr(const PlayerInfo&, bool) -> std::string; auto getLengthStr(const PlayerInfo&, bool) -> std::string; auto getPositionStr(const PlayerInfo&, bool) -> std::string; auto getDynamicStr(const PlayerInfo&, bool, bool) -> std::string; // config std::string format_playing_; std::string format_paused_; std::string format_stopped_; std::string tooltip_; std::string tooltip_playing_; std::string tooltip_paused_; std::string tooltip_stopped_; int artist_len_; int album_len_; int title_len_; int dynamic_len_; std::vector dynamic_prio_; std::vector dynamic_order_; std::string dynamic_separator_; bool truncate_hours_; bool tooltip_len_limits_; std::string ellipsis_; std::string player_; std::vector ignored_players_; PlayerctlPlayerManager* manager; PlayerctlPlayer* player; std::string lastStatus; std::string lastPlayer; util::SleeperThread thread_; std::chrono::time_point last_update_; }; } // namespace waybar::modules::mpris waybar-0.12.0/include/modules/network.hpp000066400000000000000000000042651475603165300203750ustar00rootroot00000000000000#pragma once #include #include #include #include #include #include #include #include #include "ALabel.hpp" #include "util/sleeper_thread.hpp" #ifdef WANT_RFKILL #include "util/rfkill.hpp" #endif namespace waybar::modules { class Network : public ALabel { public: Network(const std::string&, const Json::Value&); virtual ~Network(); auto update() -> void override; private: 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*); static int handleScan(struct nl_msg*, void*); void askForStateDump(void); void worker(); void createInfoSocket(); void createEventSocket(); void parseEssid(struct nlattr**); void parseSignal(struct nlattr**); void parseFreq(struct nlattr**); void parseBssid(struct nlattr**); bool associatedOrJoined(struct nlattr**); bool checkInterface(std::string name); auto getInfo() -> void; const std::string getNetworkState() const; void clearIface(); bool wildcardMatch(const std::string& pattern, const std::string& text) const; std::optional> readBandwidthUsage(); int ifid_; struct sockaddr_nl nladdr_ = {0}; struct nl_sock* sock_ = nullptr; struct nl_sock* ev_sock_ = nullptr; int efd_; int ev_fd_; int nl80211_id_; std::mutex mutex_; bool want_route_dump_; bool want_link_dump_; bool want_addr_dump_; bool dump_in_progress_; bool is_p2p_; unsigned long long bandwidth_down_total_; unsigned long long bandwidth_up_total_; std::string state_; std::string essid_; std::string bssid_; bool carrier_; std::string ifname_; std::string ipaddr_; std::string gwaddr_; std::string netmask_; int cidr_; int32_t signal_strength_dbm_; uint8_t signal_strength_; std::string signal_strength_app_; uint32_t route_priority; util::SleeperThread thread_; util::SleeperThread thread_timer_; #ifdef WANT_RFKILL util::Rfkill rfkill_; #endif float frequency_; }; } // namespace waybar::modules waybar-0.12.0/include/modules/niri/000077500000000000000000000000001475603165300171255ustar00rootroot00000000000000waybar-0.12.0/include/modules/niri/backend.hpp000066400000000000000000000026521475603165300212320ustar00rootroot00000000000000#pragma once #include #include #include #include #include "util/json.hpp" namespace waybar::modules::niri { class EventHandler { public: virtual void onEvent(const Json::Value& ev) = 0; virtual ~EventHandler() = default; }; class IPC { public: IPC() { startIPC(); } void registerForIPC(const std::string& ev, EventHandler* ev_handler); void unregisterForIPC(EventHandler* handler); static Json::Value send(const Json::Value& request); // The data members are only safe to access while dataMutex_ is locked. std::lock_guard lockData() { return std::lock_guard(dataMutex_); } const std::vector& workspaces() const { return workspaces_; } const std::vector& windows() const { return windows_; } const std::vector& keyboardLayoutNames() const { return keyboardLayoutNames_; } unsigned keyboardLayoutCurrent() const { return keyboardLayoutCurrent_; } private: void startIPC(); static int connectToSocket(); void parseIPC(const std::string&); std::mutex dataMutex_; std::vector workspaces_; std::vector windows_; std::vector keyboardLayoutNames_; unsigned keyboardLayoutCurrent_; util::JsonParser parser_; std::mutex callbackMutex_; std::list> callbacks_; }; inline std::unique_ptr gIPC; }; // namespace waybar::modules::niri waybar-0.12.0/include/modules/niri/language.hpp000066400000000000000000000013751475603165300214270ustar00rootroot00000000000000#pragma once #include #include "ALabel.hpp" #include "bar.hpp" #include "modules/niri/backend.hpp" namespace waybar::modules::niri { class Language : public ALabel, public EventHandler { public: 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 doUpdate(); struct Layout { std::string full_name; std::string short_name; std::string variant; std::string short_description; }; static Layout getLayout(const std::string &fullName); std::mutex mutex_; const Bar &bar_; std::vector layouts_; unsigned current_idx_; }; } // namespace waybar::modules::niri waybar-0.12.0/include/modules/niri/window.hpp000066400000000000000000000011201475603165300211370ustar00rootroot00000000000000#pragma once #include #include #include "AAppIconLabel.hpp" #include "bar.hpp" #include "modules/niri/backend.hpp" namespace waybar::modules::niri { class Window : public AAppIconLabel, public EventHandler { public: Window(const std::string &, const Bar &, const Json::Value &); ~Window() override; void update() override; private: void onEvent(const Json::Value &ev) override; void doUpdate(); void setClass(const std::string &className, bool enable); const Bar &bar_; std::string oldAppId_; }; } // namespace waybar::modules::niri waybar-0.12.0/include/modules/niri/workspaces.hpp000066400000000000000000000013451475603165300220220ustar00rootroot00000000000000#pragma once #include #include #include "AModule.hpp" #include "bar.hpp" #include "modules/niri/backend.hpp" namespace waybar::modules::niri { class Workspaces : public AModule, public EventHandler { public: Workspaces(const std::string &, const Bar &, const Json::Value &); ~Workspaces() override; void update() override; private: 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); const Bar &bar_; Gtk::Box box_; // Map from niri workspace id to button. std::unordered_map buttons_; }; } // namespace waybar::modules::niri waybar-0.12.0/include/modules/power_profiles_daemon.hpp000066400000000000000000000027551475603165300232700ustar00rootroot00000000000000#pragma once #include #include "ALabel.hpp" #include "giomm/dbusproxy.h" namespace waybar::modules { struct Profile { std::string name; std::string driver; Profile(std::string n, std::string d) : name(std::move(n)), driver(std::move(d)) {} }; class PowerProfilesDaemon : public ALabel { public: 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 populateInitState(); bool handleToggle(GdkEventButton *const &e) override; private: // True if we're connected to the dbug interface. False if we're // not. bool connected_; // Look for a profile name in the list of available profiles and // switch activeProfile_ to it. void switchToProfile(std::string const &); // Used to toggle/display the profiles std::vector availableProfiles_; // Points to the active profile in the profiles list std::vector::iterator activeProfile_; // Current CSS class applied to the label std::string currentStyle_; // Format string std::string tooltipFormat_; // DBus Proxy used to track the current active profile Glib::RefPtr powerProfilesProxy_; }; } // namespace waybar::modules waybar-0.12.0/include/modules/privacy/000077500000000000000000000000001475603165300176415ustar00rootroot00000000000000waybar-0.12.0/include/modules/privacy/privacy.hpp000066400000000000000000000020041475603165300220230ustar00rootroot00000000000000#pragma once #include #include "gtkmm/box.h" #include "modules/privacy/privacy_item.hpp" #include "util/pipewire/pipewire_backend.hpp" #include "util/pipewire/privacy_node_info.hpp" using waybar::util::PipewireBackend::PrivacyNodeInfo; namespace waybar::modules::privacy { class Privacy : public AModule { public: Privacy(const std::string &, const Json::Value &, 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::mutex mutex_; sigc::connection visibility_conn; // Config Gtk::Box box_; uint iconSpacing = 4; uint iconSize = 20; uint transition_duration = 250; std::shared_ptr backend = nullptr; }; } // namespace waybar::modules::privacy waybar-0.12.0/include/modules/privacy/privacy_item.hpp000066400000000000000000000020371475603165300230470ustar00rootroot00000000000000#pragma once #include #include #include "gtkmm/box.h" #include "gtkmm/image.h" #include "gtkmm/revealer.h" #include "util/pipewire/privacy_node_info.hpp" using waybar::util::PipewireBackend::PrivacyNodeInfo; using waybar::util::PipewireBackend::PrivacyNodeType; namespace waybar::modules::privacy { class PrivacyItem : public Gtk::Revealer { public: PrivacyItem(const Json::Value &config_, enum PrivacyNodeType privacy_type_, std::list *nodes, 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; sigc::connection signal_conn; Gtk::Box tooltip_window; bool init = false; bool in_use = false; // Config std::string iconName = "image-missing-symbolic"; bool tooltip = true; uint tooltipIconSize = 24; Gtk::Box box_; Gtk::Image icon_; void update_tooltip(); }; } // namespace waybar::modules::privacy waybar-0.12.0/include/modules/pulseaudio.hpp000066400000000000000000000010561475603165300210510ustar00rootroot00000000000000#pragma once #include #include #include #include #include "ALabel.hpp" #include "util/audio_backend.hpp" namespace waybar::modules { class Pulseaudio : public ALabel { public: Pulseaudio(const std::string&, const Json::Value&); virtual ~Pulseaudio() = default; auto update() -> void override; private: bool handleScroll(GdkEventScroll* e) override; const std::vector getPulseIcon() const; std::shared_ptr backend = nullptr; }; } // namespace waybar::modules waybar-0.12.0/include/modules/pulseaudio_slider.hpp000066400000000000000000000010551475603165300224120ustar00rootroot00000000000000#pragma once #include #include "ASlider.hpp" #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&); virtual ~PulseaudioSlider() = default; void update() override; void onValueChanged() override; private: std::shared_ptr backend = nullptr; PulseaudioSliderTarget target = PulseaudioSliderTarget::Sink; }; } // namespace waybar::moduleswaybar-0.12.0/include/modules/river/000077500000000000000000000000001475603165300173135ustar00rootroot00000000000000waybar-0.12.0/include/modules/river/layout.hpp000066400000000000000000000016561475603165300213510ustar00rootroot00000000000000#pragma once #include #include "ALabel.hpp" #include "bar.hpp" #include "river-status-unstable-v1-client-protocol.h" namespace waybar::modules::river { class Layout : public waybar::ALabel { public: Layout(const std::string &, const waybar::Bar &, const Json::Value &); virtual ~Layout(); // Handlers for wayland events 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); 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_; }; } /* namespace waybar::modules::river */ waybar-0.12.0/include/modules/river/mode.hpp000066400000000000000000000011431475603165300207470ustar00rootroot00000000000000#pragma once #include #include "ALabel.hpp" #include "bar.hpp" #include "river-status-unstable-v1-client-protocol.h" namespace waybar::modules::river { class Mode : public waybar::ALabel { public: Mode(const std::string &, const waybar::Bar &, const Json::Value &); virtual ~Mode(); // Handlers for wayland events void handle_mode(const char *mode); struct zriver_status_manager_v1 *status_manager_; struct wl_seat *seat_; private: const waybar::Bar &bar_; std::string mode_; struct zriver_seat_status_v1 *seat_status_; }; } /* namespace waybar::modules::river */ waybar-0.12.0/include/modules/river/tags.hpp000066400000000000000000000020121475603165300207550ustar00rootroot00000000000000#pragma once #include #include #include "AModule.hpp" #include "bar.hpp" #include "river-control-unstable-v1-client-protocol.h" #include "river-status-unstable-v1-client-protocol.h" #include "xdg-output-unstable-v1-client-protocol.h" namespace waybar::modules::river { class Tags : public waybar::AModule { public: 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_urgent_tags(uint32_t tags); void handle_primary_clicked(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_; private: const waybar::Bar &bar_; Gtk::Box box_; std::vector buttons_; struct zriver_output_status_v1 *output_status_; }; } /* namespace waybar::modules::river */ waybar-0.12.0/include/modules/river/window.hpp000066400000000000000000000016741475603165300213430ustar00rootroot00000000000000#pragma once #include #include #include "ALabel.hpp" #include "bar.hpp" #include "river-status-unstable-v1-client-protocol.h" #include "xdg-output-unstable-v1-client-protocol.h" namespace waybar::modules::river { class Window : public waybar::ALabel { public: 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); 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_; }; } /* namespace waybar::modules::river */ waybar-0.12.0/include/modules/simpleclock.hpp000066400000000000000000000005441475603165300212050ustar00rootroot00000000000000#pragma once #include #include "ALabel.hpp" #include "util/sleeper_thread.hpp" namespace waybar::modules { class Clock : public ALabel { public: Clock(const std::string&, const Json::Value&); virtual ~Clock() = default; auto update() -> void override; private: util::SleeperThread thread_; }; } // namespace waybar::modules waybar-0.12.0/include/modules/sndio.hpp000066400000000000000000000013671475603165300200200ustar00rootroot00000000000000#pragma once #include #include #include "ALabel.hpp" #include "util/sleeper_thread.hpp" namespace waybar::modules { class Sndio : public ALabel { public: Sndio(const std::string &, const Json::Value &); virtual ~Sndio(); auto update() -> void override; 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; private: auto connect_to_sndio() -> void; util::SleeperThread thread_; struct sioctl_hdl *hdl_; std::vector pfds_; unsigned int addr_; unsigned int volume_, old_volume_, maxval_; bool muted_; }; } // namespace waybar::modules waybar-0.12.0/include/modules/sni/000077500000000000000000000000001475603165300167555ustar00rootroot00000000000000waybar-0.12.0/include/modules/sni/host.hpp000066400000000000000000000030521475603165300204430ustar00rootroot00000000000000#pragma once #include #include #include #include #include #include "bar.hpp" #include "modules/sni/item.hpp" namespace waybar::modules::SNI { class Host { public: Host(const std::size_t id, const Json::Value&, const Bar&, const std::function&)>&, const std::function&)>&); ~Host(); private: void busAcquired(const Glib::RefPtr&, Glib::ustring); void nameAppeared(const Glib::RefPtr&, Glib::ustring, const Glib::ustring&); void nameVanished(const Glib::RefPtr&, Glib::ustring); static void proxyReady(GObject*, GAsyncResult*, gpointer); static void registerHost(GObject*, GAsyncResult*, gpointer); static void itemRegistered(SnWatcher*, const gchar*, gpointer); static void itemUnregistered(SnWatcher*, const gchar*, gpointer); std::tuple getBusNameAndObjectPath(const std::string); void addRegisteredItem(std::string service); std::vector> items_; const std::string bus_name_; const std::string object_path_; std::size_t bus_name_id_; std::size_t watcher_id_; GCancellable* cancellable_ = nullptr; SnWatcher* watcher_ = nullptr; const Json::Value& config_; const Bar& bar_; const std::function&)> on_add_; const std::function&)> on_remove_; }; } // namespace waybar::modules::SNI waybar-0.12.0/include/modules/sni/item.hpp000066400000000000000000000055271475603165300204350ustar00rootroot00000000000000#pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include "bar.hpp" namespace waybar::modules::SNI { struct ToolTip { Glib::ustring icon_name; Glib::ustring text; }; class Item : public sigc::trackable { public: Item(const std::string&, const std::string&, const Json::Value&, const Bar&); ~Item() = default; std::string bus_name; std::string object_path; int icon_size; int effective_icon_size; Gtk::Image image; Gtk::EventBox event_box; std::string category; std::string id; std::string title; std::string icon_name; Glib::RefPtr icon_pixmap; Glib::RefPtr icon_theme; std::string overlay_icon_name; std::string attention_icon_name; std::string attention_movie_name; std::string icon_theme_path; std::string menu; ToolTip tooltip; DbusmenuGtkMenu* dbus_menu = nullptr; Gtk::Menu* gtk_menu = nullptr; /** * ItemIsMenu flag means that the item only supports the context menu. * Default value is true because libappindicator supports neither ItemIsMenu nor Activate method * while compliant SNI implementation would always reset the flag to desired value. */ bool item_is_menu = true; private: void onConfigure(GdkEventConfigure* ev); void proxyReady(Glib::RefPtr& result); void setProperty(const Glib::ustring& name, Glib::VariantBase& value); void setStatus(const Glib::ustring& value); void getUpdatedProperties(); void processUpdatedProperties(Glib::RefPtr& result); void onSignal(const Glib::ustring& sender_name, const Glib::ustring& signal_name, const Glib::VariantContainerBase& arguments); void updateImage(); Glib::RefPtr extractPixBuf(GVariant* variant); Glib::RefPtr getIconPixbuf(); Glib::RefPtr getIconByName(const std::string& name, int size); double getScaledIconSize(); static void onMenuDestroyed(Item* self, GObject* old_menu_pointer); void makeMenu(); bool handleClick(GdkEventButton* const& /*ev*/); bool handleScroll(GdkEventScroll* const&); bool handleMouseEnter(GdkEventCrossing* const&); bool handleMouseLeave(GdkEventCrossing* const&); // smooth scrolling threshold gdouble scroll_threshold_ = 0; gdouble distance_scrolled_x_ = 0; gdouble distance_scrolled_y_ = 0; // visibility of items with Status == Passive bool show_passive_ = false; const Bar& bar_; Glib::RefPtr proxy_; Glib::RefPtr cancellable_; std::set update_pending_; }; } // namespace waybar::modules::SNI waybar-0.12.0/include/modules/sni/tray.hpp000066400000000000000000000011631475603165300204460ustar00rootroot00000000000000#pragma once #include #include "AModule.hpp" #include "bar.hpp" #include "modules/sni/host.hpp" #include "modules/sni/watcher.hpp" #include "util/json.hpp" namespace waybar::modules::SNI { class Tray : public AModule { public: Tray(const std::string&, const Bar&, const Json::Value&); virtual ~Tray() = default; auto update() -> void override; private: void onAdd(std::unique_ptr& item); void onRemove(std::unique_ptr& item); static inline std::size_t nb_hosts_ = 0; Gtk::Box box_; SNI::Watcher::singleton watcher_; SNI::Host host_; }; } // namespace waybar::modules::SNI waybar-0.12.0/include/modules/sni/watcher.hpp000066400000000000000000000027721475603165300211330ustar00rootroot00000000000000#pragma once #include #include #include namespace waybar::modules::SNI { class Watcher { private: Watcher(); public: ~Watcher(); using singleton = std::shared_ptr; static singleton getInstance() { static std::weak_ptr weak; std::shared_ptr strong = weak.lock(); if (!strong) { strong = std::shared_ptr(new Watcher()); weak = strong; } return strong; } private: typedef enum { GF_WATCH_TYPE_HOST, GF_WATCH_TYPE_ITEM } GfWatchType; typedef struct { GfWatchType type; 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); static void gfWatchFree(gpointer data); void updateRegisteredItems(SnWatcher *obj); uint32_t bus_name_id_; GSList *hosts_ = nullptr; GSList *items_ = nullptr; SnWatcher *watcher_ = nullptr; }; } // namespace waybar::modules::SNI waybar-0.12.0/include/modules/sway/000077500000000000000000000000001475603165300171475ustar00rootroot00000000000000waybar-0.12.0/include/modules/sway/bar.hpp000066400000000000000000000025231475603165300204260ustar00rootroot00000000000000#pragma once #include #include #include "modules/sway/ipc/client.hpp" #include "util/SafeSignal.hpp" #include "util/json.hpp" namespace waybar { class Bar; namespace modules::sway { /* * Supported subset of i3/sway IPC barconfig object */ struct swaybar_config { std::string id; std::string mode; std::string hidden_state; }; /** * swaybar IPC client */ class BarIpcClient { public: BarIpcClient(waybar::Bar& bar); private: void onInitialConfig(const struct Ipc::ipc_response& res); void onIpcEvent(const struct Ipc::ipc_response&); void onCmd(const struct Ipc::ipc_response&); void onConfigUpdate(const swaybar_config& config); void onVisibilityUpdate(bool visible_by_modifier); void onModeUpdate(bool visible_by_modifier); void onUrgencyUpdate(bool visible_by_urgency); void update(); bool isModuleEnabled(std::string name); Bar& bar_; util::JsonParser parser_; Ipc ipc_; swaybar_config bar_config_; std::string modifier_reset_; bool visible_by_mode_ = false; bool visible_by_modifier_ = false; bool visible_by_urgency_ = false; std::atomic modifier_no_action_ = false; SafeSignal signal_mode_; SafeSignal signal_visible_; SafeSignal signal_urgency_; SafeSignal signal_config_; }; } // namespace modules::sway } // namespace waybar waybar-0.12.0/include/modules/sway/ipc/000077500000000000000000000000001475603165300177225ustar00rootroot00000000000000waybar-0.12.0/include/modules/sway/ipc/client.hpp000066400000000000000000000022561475603165300217160ustar00rootroot00000000000000#pragma once #include #include #include #include #include #include #include #include #include #include "ipc.hpp" #include "util/sleeper_thread.hpp" namespace waybar::modules::sway { class Ipc { public: Ipc(); ~Ipc(); struct ipc_response { uint32_t size; uint32_t type; std::string payload; }; sigc::signal signal_event; sigc::signal signal_cmd; void sendCmd(uint32_t type, const std::string &payload = ""); void subscribe(const std::string &payload); void handleEvent(); 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 = ""); struct ipc_response recv(int fd); int fd_; int fd_event_; std::mutex mutex_; util::SleeperThread thread_; }; } // namespace waybar::modules::sway waybar-0.12.0/include/modules/sway/ipc/ipc.hpp000066400000000000000000000020011475603165300211770ustar00rootroot00000000000000#pragma once #include #define event_mask(ev) (1u << (ev & 0x7F)) enum ipc_command_type : uint32_t { // i3 command types - see i3's I3_REPLY_TYPE constants IPC_COMMAND = 0, IPC_GET_WORKSPACES = 1, IPC_SUBSCRIBE = 2, IPC_GET_OUTPUTS = 3, IPC_GET_TREE = 4, IPC_GET_MARKS = 5, IPC_GET_BAR_CONFIG = 6, IPC_GET_VERSION = 7, IPC_GET_BINDING_MODES = 8, IPC_GET_CONFIG = 9, IPC_SEND_TICK = 10, // sway-specific command types IPC_GET_INPUTS = 100, IPC_GET_SEATS = 101, // Events sent from sway to clients. Events have the highest bits set. IPC_EVENT_WORKSPACE = ((1U << 31) | 0), IPC_EVENT_OUTPUT = ((1U << 31) | 1), IPC_EVENT_MODE = ((1U << 31) | 2), IPC_EVENT_WINDOW = ((1U << 31) | 3), IPC_EVENT_BARCONFIG_UPDATE = ((1U << 31) | 4), IPC_EVENT_BINDING = ((1U << 31) | 5), IPC_EVENT_SHUTDOWN = ((1U << 31) | 6), IPC_EVENT_TICK = ((1U << 31) | 7), // sway-specific event types IPC_EVENT_BAR_STATE_UPDATE = ((1U << 31) | 20), IPC_EVENT_INPUT = ((1U << 31) | 21), }; waybar-0.12.0/include/modules/sway/language.hpp000066400000000000000000000032701475603165300214450ustar00rootroot00000000000000#pragma once #include #include #include #include #include "ALabel.hpp" #include "bar.hpp" #include "client.hpp" #include "modules/sway/ipc/client.hpp" #include "util/json.hpp" namespace waybar::modules::sway { class Language : public ALabel, public sigc::trackable { public: Language(const std::string& id, const Json::Value& config); virtual ~Language() = default; auto update() -> void override; private: enum class DispayedShortFlag { None = 0, ShortName = 1, ShortDescription = 1 << 1 }; struct Layout { std::string full_name; std::string short_name; std::string variant; std::string short_description; std::string country_flag() const; }; class XKBContext { public: XKBContext(); ~XKBContext(); auto next_layout() -> Layout*; private: rxkb_context* context_ = nullptr; rxkb_layout* xkb_layout_ = nullptr; Layout* layout_ = nullptr; std::map base_layouts_by_name_; }; void onEvent(const struct Ipc::ipc_response&); void onCmd(const struct Ipc::ipc_response&); auto set_current_layout(std::string current_layout) -> void; auto init_layouts_map(const std::vector& used_layouts) -> void; const static std::string XKB_LAYOUT_NAMES_KEY; const static std::string XKB_ACTIVE_LAYOUT_NAME_KEY; Layout layout_; std::string tooltip_format_ = ""; std::map layouts_map_; bool hide_single_; bool is_variant_displayed; std::byte displayed_short_flag = static_cast(DispayedShortFlag::None); util::JsonParser parser_; std::mutex mutex_; Ipc ipc_; }; } // namespace waybar::modules::sway waybar-0.12.0/include/modules/sway/mode.hpp000066400000000000000000000010601475603165300206010ustar00rootroot00000000000000#pragma once #include #include "ALabel.hpp" #include "bar.hpp" #include "client.hpp" #include "modules/sway/ipc/client.hpp" #include "util/json.hpp" namespace waybar::modules::sway { class Mode : public ALabel, public sigc::trackable { public: Mode(const std::string&, const Json::Value&); virtual ~Mode() = default; auto update() -> void override; private: void onEvent(const struct Ipc::ipc_response&); std::string mode_; util::JsonParser parser_; std::mutex mutex_; Ipc ipc_; }; } // namespace waybar::modules::sway waybar-0.12.0/include/modules/sway/scratchpad.hpp000066400000000000000000000014101475603165300217700ustar00rootroot00000000000000#pragma once #include #include #include #include "ALabel.hpp" #include "bar.hpp" #include "client.hpp" #include "modules/sway/ipc/client.hpp" #include "util/json.hpp" namespace waybar::modules::sway { class Scratchpad : public ALabel { public: Scratchpad(const std::string&, const Json::Value&); virtual ~Scratchpad() = default; auto update() -> void override; private: auto getTree() -> void; auto onCmd(const struct Ipc::ipc_response&) -> void; auto onEvent(const struct Ipc::ipc_response&) -> void; std::string tooltip_format_; bool show_empty_; bool tooltip_enabled_; std::string tooltip_text_; int count_; std::mutex mutex_; Ipc ipc_; util::JsonParser parser_; }; } // namespace waybar::modules::sway waybar-0.12.0/include/modules/sway/window.hpp000066400000000000000000000021231475603165300211650ustar00rootroot00000000000000#pragma once #include #include #include "AAppIconLabel.hpp" #include "bar.hpp" #include "client.hpp" #include "modules/sway/ipc/client.hpp" #include "util/json.hpp" namespace waybar::modules::sway { class Window : public AAppIconLabel, public sigc::trackable { public: Window(const std::string&, const waybar::Bar&, const Json::Value&); virtual ~Window() = default; auto update() -> void override; private: void setClass(std::string classname, bool enable); void onEvent(const struct Ipc::ipc_response&); void onCmd(const struct Ipc::ipc_response&); std::tuple getFocusedNode(const Json::Value& nodes, std::string& output); void getTree(); const Bar& bar_; std::string window_; int windowId_; std::string app_id_; std::string app_class_; std::string layout_; std::string old_app_id_; std::size_t app_nb_; std::string shell_; int floating_count_; util::JsonParser parser_; std::mutex mutex_; Ipc ipc_; }; } // namespace waybar::modules::sway waybar-0.12.0/include/modules/sway/workspaces.hpp000066400000000000000000000037351475603165300220510ustar00rootroot00000000000000#pragma once #include #include #include #include #include #include "AModule.hpp" #include "bar.hpp" #include "client.hpp" #include "modules/sway/ipc/client.hpp" #include "util/json.hpp" #include "util/regex_collection.hpp" namespace waybar::modules::sway { class Workspaces : public AModule, public sigc::trackable { public: Workspaces(const std::string&, const waybar::Bar&, const Json::Value&); ~Workspaces() override = default; auto update() -> void override; private: static constexpr std::string_view workspace_switch_cmd_ = "workspace {} \"{}\""; static constexpr std::string_view persistent_workspace_switch_cmd_ = R"(workspace {} "{}"; move workspace to output "{}"; workspace {} "{}")"; static int convertWorkspaceNameToNum(std::string name); static int windowRewritePriorityFunction(std::string const& window_rule); void onCmd(const struct Ipc::ipc_response&); void onEvent(const struct Ipc::ipc_response&); bool filterButtons(); static bool hasFlag(const Json::Value&, const std::string&); void updateWindows(const Json::Value&, std::string&); Gtk::Button& addButton(const Json::Value&); void onButtonReady(const Json::Value&, Gtk::Button&); 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); bool handleScroll(GdkEventScroll* /*unused*/) override; const Bar& bar_; std::vector workspaces_; std::vector high_priority_named_; std::vector workspaces_order_; Gtk::Box box_; std::string m_formatWindowSeperator; util::RegexCollection m_windowRewriteRules; util::JsonParser parser_; std::unordered_map buttons_; std::mutex mutex_; Ipc ipc_; }; } // namespace waybar::modules::sway waybar-0.12.0/include/modules/systemd_failed_units.hpp000066400000000000000000000013121475603165300231100ustar00rootroot00000000000000#pragma once #include #include #include "ALabel.hpp" namespace waybar::modules { class SystemdFailedUnits : public ALabel { public: SystemdFailedUnits(const std::string &, const Json::Value &); virtual ~SystemdFailedUnits(); auto update() -> void override; private: bool hide_on_ok; std::string format_ok; bool update_pending; uint32_t nr_failed_system, nr_failed_user; std::string last_status; Glib::RefPtr system_proxy, user_proxy; void notify_cb(const Glib::ustring &sender_name, const Glib::ustring &signal_name, const Glib::VariantContainerBase &arguments); void updateData(); }; } // namespace waybar::modules waybar-0.12.0/include/modules/temperature.hpp000066400000000000000000000007701475603165300212360ustar00rootroot00000000000000#pragma once #include #include #include "ALabel.hpp" #include "util/sleeper_thread.hpp" namespace waybar::modules { class Temperature : public ALabel { public: Temperature(const std::string&, const Json::Value&); virtual ~Temperature() = default; auto update() -> void override; private: float getTemperature(); bool isCritical(uint16_t); bool isWarning(uint16_t); std::string file_path_; util::SleeperThread thread_; }; } // namespace waybar::modules waybar-0.12.0/include/modules/upower.hpp000066400000000000000000000055451475603165300202270ustar00rootroot00000000000000#pragma once #include #include #include #include #include "AIconLabel.hpp" namespace waybar::modules { class UPower final : public AIconLabel { public: UPower(const std::string &, const Json::Value &); virtual ~UPower(); auto update() -> void override; private: const std::string NO_BATTERY{"battery-missing-symbolic"}; // Config bool showIcon_{true}; bool hideIfEmpty_{true}; int iconSize_{20}; int tooltip_spacing_{4}; int tooltip_padding_{4}; Gtk::Box contentBox_; // tooltip box std::string tooltipFormat_; // UPower device info struct upDevice_output { UpDevice *upDevice{NULL}; double percentage{0.0}; double temperature{0.0}; guint64 time_full{0u}; guint64 time_empty{0u}; gchar *icon_name{(char *)'\0'}; bool upDeviceValid{false}; UpDeviceState state; UpDeviceKind kind; char *nativePath{(char *)'\0'}; char *model{(char *)'\0'}; }; // Technical variables std::string nativePath_; std::string model_; std::string lastStatus_; Glib::ustring label_markup_; std::mutex mutex_; Glib::RefPtr gtkTheme_; bool sleeping_; // Technical functions 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 &); // DBUS variables guint watcherID_; Glib::RefPtr conn_; guint subscrID_{0u}; // UPower variables 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); // 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); // UPower secondary functions void getUpDeviceInfo(upDevice_output &upDevice_); }; } // namespace waybar::modules waybar-0.12.0/include/modules/user.hpp000066400000000000000000000016721475603165300176610ustar00rootroot00000000000000#pragma once #include #include #include #include "AIconLabel.hpp" #include "util/sleeper_thread.hpp" namespace waybar::modules { class User : public AIconLabel { public: User(const std::string&, const Json::Value&); virtual ~User() = default; auto update() -> void override; bool handleToggle(GdkEventButton* const& e) override; private: util::SleeperThread thread_; static constexpr inline int defaultUserImageWidth_ = 20; static constexpr inline int defaultUserImageHeight_ = 20; long uptime_as_seconds(); std::string get_user_login() const; std::string get_user_home_dir() const; std::string get_default_user_avatar_path() const; void init_default_user_avatar(int width, int height); void init_user_avatar(const std::string& path, int width, int height); void init_avatar(const Json::Value& config); void init_update_worker(); }; } // namespace waybar::modules waybar-0.12.0/include/modules/wireplumber.hpp000066400000000000000000000027331475603165300212370ustar00rootroot00000000000000#pragma once #include #include #include #include #include "ALabel.hpp" namespace waybar::modules { class Wireplumber : public ALabel { public: Wireplumber(const std::string&, const Json::Value&); virtual ~Wireplumber(); auto update() -> void override; private: void asyncLoadRequiredApiModules(); void prepare(); void activatePlugins(); static void updateVolume(waybar::modules::Wireplumber* self, uint32_t id); static void updateNodeName(waybar::modules::Wireplumber* self, uint32_t id); static void onPluginActivated(WpObject* p, GAsyncResult* res, waybar::modules::Wireplumber* self); static void onDefaultNodesApiLoaded(WpObject* p, GAsyncResult* res, waybar::modules::Wireplumber* self); static void onMixerApiLoaded(WpObject* p, GAsyncResult* res, waybar::modules::Wireplumber* self); static void onObjectManagerInstalled(waybar::modules::Wireplumber* self); static void onMixerChanged(waybar::modules::Wireplumber* self, uint32_t id); static void onDefaultNodesApiChanged(waybar::modules::Wireplumber* self); bool handleScroll(GdkEventScroll* e) override; WpCore* wp_core_; GPtrArray* apis_; WpObjectManager* om_; WpPlugin* mixer_api_; WpPlugin* def_nodes_api_; gchar* default_node_name_; uint32_t pending_plugins_; bool muted_; double volume_; double min_step_; uint32_t node_id_{0}; std::string node_name_; }; } // namespace waybar::modules waybar-0.12.0/include/modules/wlr/000077500000000000000000000000001475603165300167705ustar00rootroot00000000000000waybar-0.12.0/include/modules/wlr/taskbar.hpp000066400000000000000000000117541475603165300211400ustar00rootroot00000000000000#pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include #include "AModule.hpp" #include "bar.hpp" #include "client.hpp" #include "giomm/desktopappinfo.h" #include "util/json.hpp" #include "wlr-foreign-toplevel-management-unstable-v1-client-protocol.h" namespace waybar::modules::wlr { struct widget_geometry { int x, y, w, h; }; class Taskbar; class Task { public: Task(const waybar::Bar &, const Json::Value &, Taskbar *, struct zwlr_foreign_toplevel_handle_v1 *, struct wl_seat *); ~Task(); public: enum State { MAXIMIZED = (1 << 0), MINIMIZED = (1 << 1), ACTIVE = (1 << 2), FULLSCREEN = (1 << 3), INVALID = (1 << 4) }; // made public so TaskBar can reorder based on configuration. Gtk::Button button; struct widget_geometry minimize_hint; private: static uint32_t global_id; private: const waybar::Bar &bar_; const Json::Value &config_; Taskbar *tbar_; struct zwlr_foreign_toplevel_handle_v1 *handle_; struct wl_seat *seat_; uint32_t id_; Gtk::Box content_; Gtk::Image icon_; Gtk::Label text_before_; Gtk::Label text_after_; Glib::RefPtr app_info_; bool button_visible_ = false; bool ignored_ = false; bool with_icon_ = false; bool with_name_ = false; std::string format_before_; std::string format_after_; std::string format_tooltip_; std::string name_; std::string title_; std::string app_id_; uint32_t state_ = 0; int32_t drag_start_x; int32_t drag_start_y; int32_t drag_start_button = -1; private: 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 hide_if_ignored(); public: /* Getter functions */ uint32_t id() const { return id_; } std::string title() const { return title_; } std::string app_id() const { return app_id_; } uint32_t state() const { return state_; } bool maximized() const { return state_ & MAXIMIZED; } bool minimized() const { return state_ & MINIMIZED; } bool active() const { return state_ & ACTIVE; } bool fullscreen() const { return state_ & FULLSCREEN; } public: /* Callbacks for the wlr protocol */ void handle_title(const char *); void handle_app_id(const char *); void handle_output_enter(struct wl_output *); void handle_output_leave(struct wl_output *); void handle_state(struct wl_array *); void handle_done(); void handle_closed(); /* Callbacks for Gtk events */ bool handle_clicked(GdkEventButton *); 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; public: void update(); public: /* Interaction with the tasks */ void maximize(bool); void minimize(bool); void activate(); void fullscreen(bool); void close(); }; using TaskPtr = std::unique_ptr; class Taskbar : public waybar::AModule { public: Taskbar(const std::string &, const waybar::Bar &, const Json::Value &); ~Taskbar(); void update(); private: const waybar::Bar &bar_; Gtk::Box box_; std::vector tasks_; std::vector> icon_themes_; std::unordered_set ignore_list_; std::map app_ids_replace_map_; 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); /* Callbacks for the wlr protocol */ void handle_toplevel_create(struct zwlr_foreign_toplevel_handle_v1 *); void handle_finished(); public: void add_button(Gtk::Button &); void move_button(Gtk::Button &, int); void remove_button(Gtk::Button &); void remove_task(uint32_t); 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; }; } /* namespace waybar::modules::wlr */ waybar-0.12.0/include/modules/wlr/workspace_manager.hpp000066400000000000000000000124361475603165300231770ustar00rootroot00000000000000#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 waybar-0.12.0/include/modules/wlr/workspace_manager_binding.hpp000066400000000000000000000010551475603165300246640ustar00rootroot00000000000000#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 waybar-0.12.0/include/util/000077500000000000000000000000001475603165300154715ustar00rootroot00000000000000waybar-0.12.0/include/util/SafeSignal.hpp000066400000000000000000000042051475603165300202170ustar00rootroot00000000000000#pragma once #include #include #include #include #include #include #include #include #include namespace waybar { /** * Thread-safe signal wrapper. * Uses Glib::Dispatcher to pass events to another thread and locked queue to pass the arguments. */ template struct SafeSignal : sigc::signal...)> { public: SafeSignal() { dp_.connect(sigc::mem_fun(*this, &SafeSignal::handle_event)); } template void emit(EmitArgs&&... args) { if (main_tid_ == std::this_thread::get_id()) { /* * Bypass the queue if the method is called the main thread. * Ensures that events emitted from the main thread are processed synchronously and saves a * few CPU cycles on locking/queuing. * As a downside, this makes main thread events prioritized over the other threads and * disrupts chronological order. */ signal_t::emit(std::forward(args)...); } else { { std::unique_lock lock(mutex_); queue_.emplace(std::forward(args)...); } dp_.emit(); } } template inline void operator()(EmitArgs&&... args) { emit(std::forward(args)...); } protected: using signal_t = sigc::signal...)>; using slot_t = decltype(std::declval().make_slot()); using arg_tuple_t = std::tuple...>; // ensure that unwrapped methods are not accessible using signal_t::emit_reverse; using signal_t::make_slot; void handle_event() { for (std::unique_lock lock(mutex_); !queue_.empty(); lock.lock()) { auto args = queue_.front(); queue_.pop(); lock.unlock(); std::apply(cached_fn_, args); } } Glib::Dispatcher dp_; std::mutex mutex_; std::queue queue_; 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(); }; } // namespace waybar waybar-0.12.0/include/util/audio_backend.hpp000066400000000000000000000062341475603165300207570ustar00rootroot00000000000000#pragma once #include #include #include #include #include #include #include #include #include "util/backend_common.hpp" namespace waybar::util { class AudioBackend { private: static void subscribeCb(pa_context*, pa_subscription_event_type_t, uint32_t, void*); static void contextStateCb(pa_context*, void*); static void sinkInfoCb(pa_context*, const pa_sink_info*, int, void*); static void sourceInfoCb(pa_context*, const pa_source_info* i, int, void* data); static void serverInfoCb(pa_context*, const pa_server_info*, void*); static void volumeModifyCb(pa_context*, int, void*); void connectContext(); pa_threaded_mainloop* mainloop_; pa_mainloop_api* mainloop_api_; pa_context* context_; pa_cvolume pa_volume_; // SINK uint32_t sink_idx_{0}; uint16_t volume_; bool muted_; std::string port_name_; std::string form_factor_; std::string desc_; std::string monitor_; std::string current_sink_name_; std::string default_sink_name; bool default_sink_running_; bool current_sink_running_; // SOURCE uint32_t source_idx_{0}; uint16_t source_volume_; bool source_muted_; std::string source_port_name_; std::string source_desc_; std::string default_source_name_; std::vector ignored_sinks_; std::function on_updated_cb_ = NOOP; /* Hack to keep constructor inaccessible but still public. * This is required to be able to use std::make_shared. * It is important to keep this class only accessible via a reference-counted * pointer because the destructor will manually free memory, and this could be * a problem with C++20's copy and move semantics. */ struct private_constructor_tag {}; public: static std::shared_ptr getInstance(std::function on_updated_cb = NOOP); AudioBackend(std::function on_updated_cb, private_constructor_tag tag); ~AudioBackend(); void changeVolume(uint16_t volume, uint16_t min_volume = 0, uint16_t max_volume = 100); void changeVolume(ChangeType change_type, double step = 1, uint16_t max_volume = 100); void setIgnoredSinks(const Json::Value& config); std::string getSinkPortName() const { return port_name_; } std::string getFormFactor() const { return form_factor_; } std::string getSinkDesc() const { return desc_; } std::string getMonitor() const { return monitor_; } std::string getCurrentSinkName() const { return current_sink_name_; } bool getCurrentSinkRunning() const { return current_sink_running_; } uint16_t getSinkVolume() const { return volume_; } bool getSinkMuted() const { return muted_; } uint16_t getSourceVolume() const { return source_volume_; } bool getSourceMuted() const { return source_muted_; } std::string getSourcePortName() const { return source_port_name_; } std::string getSourceDesc() const { return source_desc_; } std::string getDefaultSourceName() const { return default_source_name_; } void toggleSinkMute(); void toggleSinkMute(bool); void toggleSourceMute(); void toggleSourceMute(bool); bool isBluetooth(); }; } // namespace waybar::utilwaybar-0.12.0/include/util/backend_common.hpp000066400000000000000000000002641475603165300211430ustar00rootroot00000000000000#pragma once #include "AModule.hpp" namespace waybar::util { const static auto NOOP = []() {}; enum class ChangeType : char { Increase, Decrease }; } // namespace waybar::utilwaybar-0.12.0/include/util/backlight_backend.hpp000066400000000000000000000053231475603165300216040ustar00rootroot00000000000000#pragma once #include #include #include #include #include #include #include #include #include "giomm/dbusproxy.h" #include "util/backend_common.hpp" #include "util/sleeper_thread.hpp" #define GET_BEST_DEVICE(varname, backend, preferred_device) \ decltype((backend).devices_) __devices; \ { \ std::scoped_lock lock((backend).udev_thread_mutex_); \ __devices = (backend).devices_; \ } \ auto varname = (backend).best_device(__devices, preferred_device); namespace waybar::util { class BacklightDevice { public: BacklightDevice() = default; BacklightDevice(std::string name, int actual, int max, bool powered); std::string name() const; int get_actual() const; void set_actual(int actual); int get_max() const; void set_max(int max); bool get_powered() const; void set_powered(bool powered); friend inline bool operator==(const BacklightDevice &lhs, const BacklightDevice &rhs) { return lhs.name_ == rhs.name_ && lhs.actual_ == rhs.actual_ && lhs.max_ == rhs.max_; } private: std::string name_; int actual_ = 1; int max_ = 1; bool powered_ = true; }; class BacklightBackend { public: 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(); void set_previous_best_device(const BacklightDevice *device); 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); bool is_login_proxy_initialized() const { return static_cast(login_proxy_); } 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); std::function on_updated_cb_; std::chrono::milliseconds polling_interval_; std::optional previous_best_; // thread must destruct before shared data util::SleeperThread udev_thread_; Glib::RefPtr login_proxy_; static constexpr int EPOLL_MAX_EVENTS = 16; }; } // namespace waybar::util waybar-0.12.0/include/util/clara.hpp000066400000000000000000001047111475603165300172700ustar00rootroot00000000000000// Copyright 2017 Two Blue Cubes Ltd. All rights reserved. // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // See https://github.com/philsquared/Clara for more details // Clara v1.1.5 #ifndef CLARA_HPP_INCLUDED #define CLARA_HPP_INCLUDED #ifndef CLARA_CONFIG_CONSOLE_WIDTH #define CLARA_CONFIG_CONSOLE_WIDTH 80 #endif #ifndef CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH #define CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CLARA_CONFIG_CONSOLE_WIDTH #endif #ifndef CLARA_CONFIG_OPTIONAL_TYPE #ifdef __has_include #if __has_include() && __cplusplus >= 201703L #include #define CLARA_CONFIG_OPTIONAL_TYPE std::optional #endif #endif #endif // ----------- #included from clara_textflow.hpp ----------- // TextFlowCpp // // A single-header library for wrapping and laying out basic text, by Phil Nash // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // This project is hosted at https://github.com/philsquared/textflowcpp #ifndef CLARA_TEXTFLOW_HPP_INCLUDED #define CLARA_TEXTFLOW_HPP_INCLUDED #include #include #include #include #ifndef CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH #define CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80 #endif namespace clara { namespace TextFlow { inline auto isWhitespace(char c) -> bool { static std::string chars = " \t\n\r"; return chars.find(c) != std::string::npos; } inline auto isBreakableBefore(char c) -> bool { static std::string chars = "[({<|"; return chars.find(c) != std::string::npos; } inline auto isBreakableAfter(char c) -> bool { static std::string chars = "])}>.,:;*+-=&/\\"; return chars.find(c) != std::string::npos; } class Columns; class Column { std::vector m_strings; size_t m_width = CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH; size_t m_indent = 0; size_t m_initialIndent = std::string::npos; public: class iterator { friend Column; Column const &m_column; size_t m_stringIndex = 0; size_t m_pos = 0; size_t m_len = 0; size_t m_end = 0; bool m_suffix = false; iterator(Column const &column, size_t stringIndex) : m_column(column), m_stringIndex(stringIndex) {} auto line() const -> std::string const & { return m_column.m_strings[m_stringIndex]; } auto isBoundary(size_t at) const -> bool { assert(at > 0); assert(at <= line().size()); return at == line().size() || (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) || isBreakableBefore(line()[at]) || isBreakableAfter(line()[at - 1]); } void calcLength() { assert(m_stringIndex < m_column.m_strings.size()); m_suffix = false; auto width = m_column.m_width - indent(); m_end = m_pos; while (m_end < line().size() && line()[m_end] != '\n') ++m_end; if (m_end < m_pos + width) { m_len = m_end - m_pos; } else { size_t len = width; while (len > 0 && !isBoundary(m_pos + len)) --len; while (len > 0 && isWhitespace(line()[m_pos + len - 1])) --len; if (len > 0) { m_len = len; } else { m_suffix = true; m_len = width - 1; } } } auto indent() const -> size_t { auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos; return initial == std::string::npos ? m_column.m_indent : initial; } auto addIndentAndSuffix(std::string const &plain) const -> std::string { return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain); } public: using difference_type = std::ptrdiff_t; using value_type = std::string; using pointer = value_type *; using reference = value_type &; using iterator_category = std::forward_iterator_tag; explicit iterator(Column const &column) : m_column(column) { assert(m_column.m_width > m_column.m_indent); assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent); calcLength(); if (m_len == 0) m_stringIndex++; // Empty string } auto operator*() const -> std::string { assert(m_stringIndex < m_column.m_strings.size()); assert(m_pos <= m_end); return addIndentAndSuffix(line().substr(m_pos, m_len)); } auto operator++() -> iterator & { m_pos += m_len; if (m_pos < line().size() && line()[m_pos] == '\n') m_pos += 1; else while (m_pos < line().size() && isWhitespace(line()[m_pos])) ++m_pos; if (m_pos == line().size()) { m_pos = 0; ++m_stringIndex; } if (m_stringIndex < m_column.m_strings.size()) calcLength(); return *this; } auto operator++(int) -> iterator { iterator prev(*this); operator++(); return prev; } auto operator==(iterator const &other) const -> bool { return m_pos == other.m_pos && m_stringIndex == other.m_stringIndex && &m_column == &other.m_column; } auto operator!=(iterator const &other) const -> bool { return !operator==(other); } }; using const_iterator = iterator; explicit Column(std::string const &text) { m_strings.push_back(text); } auto width(size_t newWidth) -> Column & { assert(newWidth > 0); m_width = newWidth; return *this; } auto indent(size_t newIndent) -> Column & { m_indent = newIndent; return *this; } auto initialIndent(size_t newIndent) -> Column & { m_initialIndent = newIndent; return *this; } auto width() const -> size_t { return m_width; } auto begin() const -> iterator { return iterator(*this); } auto end() const -> iterator { return {*this, m_strings.size()}; } inline friend std::ostream &operator<<(std::ostream &os, Column const &col) { bool first = true; for (auto line : col) { if (first) first = false; else os << "\n"; os << line; } return os; } auto operator+(Column const &other) -> Columns; auto toString() const -> std::string { std::ostringstream oss; oss << *this; return oss.str(); } }; class Spacer : public Column { public: explicit Spacer(size_t spaceWidth) : Column("") { width(spaceWidth); } }; class Columns { std::vector m_columns; public: class iterator { friend Columns; struct EndTag {}; std::vector const &m_columns; std::vector m_iterators; size_t m_activeIterators; iterator(Columns const &columns, EndTag) : m_columns(columns.m_columns), m_activeIterators(0) { m_iterators.reserve(m_columns.size()); for (auto const &col : m_columns) m_iterators.push_back(col.end()); } public: using difference_type = std::ptrdiff_t; using value_type = std::string; using pointer = value_type *; using reference = value_type &; using iterator_category = std::forward_iterator_tag; explicit iterator(Columns const &columns) : m_columns(columns.m_columns), m_activeIterators(m_columns.size()) { m_iterators.reserve(m_columns.size()); for (auto const &col : m_columns) m_iterators.push_back(col.begin()); } auto operator==(iterator const &other) const -> bool { return m_iterators == other.m_iterators; } auto operator!=(iterator const &other) const -> bool { return m_iterators != other.m_iterators; } auto operator*() const -> std::string { std::string row, padding; for (size_t i = 0; i < m_columns.size(); ++i) { auto width = m_columns[i].width(); if (m_iterators[i] != m_columns[i].end()) { std::string col = *m_iterators[i]; row += padding + col; if (col.size() < width) padding = std::string(width - col.size(), ' '); else padding = ""; } else { padding += std::string(width, ' '); } } return row; } auto operator++() -> iterator & { for (size_t i = 0; i < m_columns.size(); ++i) { if (m_iterators[i] != m_columns[i].end()) ++m_iterators[i]; } return *this; } auto operator++(int) -> iterator { iterator prev(*this); operator++(); return prev; } }; using const_iterator = iterator; auto begin() const -> iterator { return iterator(*this); } auto end() const -> iterator { return {*this, iterator::EndTag()}; } auto operator+=(Column const &col) -> Columns & { m_columns.push_back(col); return *this; } auto operator+(Column const &col) -> Columns { Columns combined = *this; combined += col; return combined; } inline friend std::ostream &operator<<(std::ostream &os, Columns const &cols) { bool first = true; for (auto line : cols) { if (first) first = false; else os << "\n"; os << line; } return os; } auto toString() const -> std::string { std::ostringstream oss; oss << *this; return oss.str(); } }; inline auto Column::operator+(Column const &other) -> Columns { Columns cols; cols += *this; cols += other; return cols; } } // namespace TextFlow } // namespace clara #endif // CLARA_TEXTFLOW_HPP_INCLUDED // ----------- end of #include from clara_textflow.hpp ----------- // ........... back in clara.hpp #include #include #include #if !defined(CLARA_PLATFORM_WINDOWS) && \ (defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER)) #define CLARA_PLATFORM_WINDOWS #endif namespace clara { namespace detail { // Traits for extracting arg and return type of lambdas (for single argument lambdas) template struct UnaryLambdaTraits : UnaryLambdaTraits {}; template struct UnaryLambdaTraits { static const bool isValid = false; }; template struct UnaryLambdaTraits { static const bool isValid = true; using ArgType = typename std::remove_const::type>::type; using ReturnType = ReturnT; }; class TokenStream; // Transport for raw args (copied from main args, or supplied via init list for testing) class Args { friend TokenStream; std::string m_exeName; std::vector m_args; public: Args(int argc, char const *const *argv) : m_exeName(argv[0]), m_args(argv + 1, argv + argc) {} Args(std::initializer_list args) : m_exeName(*args.begin()), m_args(args.begin() + 1, args.end()) {} auto exeName() const -> std::string { return m_exeName; } }; // Wraps a token coming from a token stream. These may not directly correspond to strings as a // single string may encode an option + its argument if the : or = form is used enum class TokenType { Option, Argument }; struct Token { TokenType type; std::string token; }; inline auto isOptPrefix(char c) -> bool { return c == '-' #ifdef CLARA_PLATFORM_WINDOWS || c == '/' #endif ; } // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled class TokenStream { using Iterator = std::vector::const_iterator; Iterator it; Iterator itEnd; std::vector m_tokenBuffer; void loadBuffer() { m_tokenBuffer.resize(0); // Skip any empty strings while (it != itEnd && it->empty()) ++it; if (it != itEnd) { auto const &next = *it; if (isOptPrefix(next[0])) { auto delimiterPos = next.find_first_of(" :="); if (delimiterPos != std::string::npos) { m_tokenBuffer.push_back({TokenType::Option, next.substr(0, delimiterPos)}); m_tokenBuffer.push_back({TokenType::Argument, next.substr(delimiterPos + 1)}); } else { if (next[1] != '-' && next.size() > 2) { std::string opt = "- "; for (size_t i = 1; i < next.size(); ++i) { opt[1] = next[i]; m_tokenBuffer.push_back({TokenType::Option, opt}); } } else { m_tokenBuffer.push_back({TokenType::Option, next}); } } } else { m_tokenBuffer.push_back({TokenType::Argument, next}); } } } public: explicit TokenStream(Args const &args) : TokenStream(args.m_args.begin(), args.m_args.end()) {} TokenStream(Iterator it, Iterator itEnd) : it(it), itEnd(itEnd) { loadBuffer(); } explicit operator bool() const { return !m_tokenBuffer.empty() || it != itEnd; } auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); } auto operator*() const -> Token { assert(!m_tokenBuffer.empty()); return m_tokenBuffer.front(); } auto operator->() const -> Token const * { assert(!m_tokenBuffer.empty()); return &m_tokenBuffer.front(); } auto operator++() -> TokenStream & { if (m_tokenBuffer.size() >= 2) { m_tokenBuffer.erase(m_tokenBuffer.begin()); } else { if (it != itEnd) ++it; loadBuffer(); } return *this; } }; class ResultBase { public: enum Type { Ok, LogicError, RuntimeError }; protected: ResultBase(Type type) : m_type(type) {} virtual ~ResultBase() = default; virtual void enforceOk() const = 0; Type m_type; }; template class ResultValueBase : public ResultBase { public: auto value() const -> T const & { enforceOk(); return m_value; } protected: ResultValueBase(Type type) : ResultBase(type) {} ResultValueBase(ResultValueBase const &other) : ResultBase(other) { if (m_type == ResultBase::Ok) new (&m_value) T(other.m_value); } ResultValueBase(Type, T const &value) : ResultBase(Ok) { new (&m_value) T(value); } auto operator=(ResultValueBase const &other) -> ResultValueBase & { if (m_type == ResultBase::Ok) m_value.~T(); ResultBase::operator=(other); if (m_type == ResultBase::Ok) new (&m_value) T(other.m_value); return *this; } ~ResultValueBase() override { if (m_type == Ok) m_value.~T(); } union { T m_value; }; }; template <> class ResultValueBase : public ResultBase { protected: using ResultBase::ResultBase; }; template class BasicResult : public ResultValueBase { public: template explicit BasicResult(BasicResult const &other) : ResultValueBase(other.type()), m_errorMessage(other.errorMessage()) { assert(type() != ResultBase::Ok); } template static auto ok(U const &value) -> BasicResult { return {ResultBase::Ok, value}; } static auto ok() -> BasicResult { return {ResultBase::Ok}; } static auto logicError(std::string const &message) -> BasicResult { return {ResultBase::LogicError, message}; } static auto runtimeError(std::string const &message) -> BasicResult { return {ResultBase::RuntimeError, message}; } explicit operator bool() const { return m_type == ResultBase::Ok; } auto type() const -> ResultBase::Type { return m_type; } auto errorMessage() const -> std::string { return m_errorMessage; } protected: void enforceOk() const override { // Errors shouldn't reach this point, but if they do // the actual error message will be in m_errorMessage assert(m_type != ResultBase::LogicError); assert(m_type != ResultBase::RuntimeError); if (m_type != ResultBase::Ok) std::abort(); } std::string m_errorMessage; // Only populated if resultType is an error BasicResult(ResultBase::Type type, std::string const &message) : ResultValueBase(type), m_errorMessage(message) { assert(m_type != ResultBase::Ok); } using ResultValueBase::ResultValueBase; using ResultBase::m_type; }; enum class ParseResultType { Matched, NoMatch, ShortCircuitAll, ShortCircuitSame }; class ParseState { public: ParseState(ParseResultType type, TokenStream const &remainingTokens) : m_type(type), m_remainingTokens(remainingTokens) {} auto type() const -> ParseResultType { return m_type; } auto remainingTokens() const -> TokenStream { return m_remainingTokens; } private: ParseResultType m_type; TokenStream m_remainingTokens; }; using Result = BasicResult; using ParserResult = BasicResult; using InternalParseResult = BasicResult; struct HelpColumns { std::string left; std::string right; }; template inline auto convertInto(std::string const &source, T &target) -> ParserResult { std::stringstream ss; ss << source; ss >> target; if (ss.fail()) return ParserResult::runtimeError("Unable to convert '" + source + "' to destination type"); else return ParserResult::ok(ParseResultType::Matched); } inline auto convertInto(std::string const &source, std::string &target) -> ParserResult { target = source; return ParserResult::ok(ParseResultType::Matched); } inline auto convertInto(std::string const &source, bool &target) -> ParserResult { std::string srcLC = source; std::transform(srcLC.begin(), srcLC.end(), srcLC.begin(), [](char c) { return static_cast(::tolower(c)); }); if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on") target = true; else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off") target = false; else return ParserResult::runtimeError("Expected a boolean value but did not recognise: '" + source + "'"); return ParserResult::ok(ParseResultType::Matched); } #ifdef CLARA_CONFIG_OPTIONAL_TYPE template inline auto convertInto(std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE &target) -> ParserResult { T temp; auto result = convertInto(source, temp); if (result) target = std::move(temp); return result; } #endif // CLARA_CONFIG_OPTIONAL_TYPE struct NonCopyable { NonCopyable() = default; NonCopyable(NonCopyable const &) = delete; NonCopyable(NonCopyable &&) = delete; NonCopyable &operator=(NonCopyable const &) = delete; NonCopyable &operator=(NonCopyable &&) = delete; }; struct BoundRef : NonCopyable { virtual ~BoundRef() = default; virtual auto isContainer() const -> bool { return false; } virtual auto isFlag() const -> bool { return false; } }; struct BoundValueRefBase : BoundRef { virtual auto setValue(std::string const &arg) -> ParserResult = 0; }; struct BoundFlagRefBase : BoundRef { virtual auto setFlag(bool flag) -> ParserResult = 0; virtual auto isFlag() const -> bool { return true; } }; template struct BoundValueRef : BoundValueRefBase { T &m_ref; explicit BoundValueRef(T &ref) : m_ref(ref) {} auto setValue(std::string const &arg) -> ParserResult override { return convertInto(arg, m_ref); } }; template struct BoundValueRef> : BoundValueRefBase { std::vector &m_ref; explicit BoundValueRef(std::vector &ref) : m_ref(ref) {} auto isContainer() const -> bool override { return true; } auto setValue(std::string const &arg) -> ParserResult override { T temp; auto result = convertInto(arg, temp); if (result) m_ref.push_back(temp); return result; } }; struct BoundFlagRef : BoundFlagRefBase { bool &m_ref; explicit BoundFlagRef(bool &ref) : m_ref(ref) {} auto setFlag(bool flag) -> ParserResult override { m_ref = flag; return ParserResult::ok(ParseResultType::Matched); } }; template struct LambdaInvoker { static_assert(std::is_same::value, "Lambda must return void or clara::ParserResult"); template static auto invoke(L const &lambda, ArgType const &arg) -> ParserResult { return lambda(arg); } }; template <> struct LambdaInvoker { template static auto invoke(L const &lambda, ArgType const &arg) -> ParserResult { lambda(arg); return ParserResult::ok(ParseResultType::Matched); } }; template inline auto invokeLambda(L const &lambda, std::string const &arg) -> ParserResult { ArgType temp{}; auto result = convertInto(arg, temp); return !result ? result : LambdaInvoker::ReturnType>::invoke(lambda, temp); } template struct BoundLambda : BoundValueRefBase { L m_lambda; static_assert(UnaryLambdaTraits::isValid, "Supplied lambda must take exactly one argument"); explicit BoundLambda(L const &lambda) : m_lambda(lambda) {} auto setValue(std::string const &arg) -> ParserResult override { return invokeLambda::ArgType>(m_lambda, arg); } }; template struct BoundFlagLambda : BoundFlagRefBase { L m_lambda; static_assert(UnaryLambdaTraits::isValid, "Supplied lambda must take exactly one argument"); static_assert(std::is_same::ArgType, bool>::value, "flags must be boolean"); explicit BoundFlagLambda(L const &lambda) : m_lambda(lambda) {} auto setFlag(bool flag) -> ParserResult override { return LambdaInvoker::ReturnType>::invoke(m_lambda, flag); } }; enum class Optionality { Optional, Required }; struct Parser; class ParserBase { public: virtual ~ParserBase() = default; virtual auto validate() const -> Result { return Result::ok(); } virtual auto parse(std::string const &exeName, TokenStream const &tokens) const -> InternalParseResult = 0; virtual auto cardinality() const -> size_t { return 1; } auto parse(Args const &args) const -> InternalParseResult { return parse(args.exeName(), TokenStream(args)); } }; template class ComposableParserImpl : public ParserBase { public: template auto operator|(T const &other) const -> Parser; template auto operator+(T const &other) const -> Parser; }; // Common code and state for Args and Opts template class ParserRefImpl : public ComposableParserImpl { protected: Optionality m_optionality = Optionality::Optional; std::shared_ptr m_ref; std::string m_hint; std::string m_description; explicit ParserRefImpl(std::shared_ptr const &ref) : m_ref(ref) {} public: template ParserRefImpl(T &ref, std::string const &hint) : m_ref(std::make_shared>(ref)), m_hint(hint) {} template ParserRefImpl(LambdaT const &ref, std::string const &hint) : m_ref(std::make_shared>(ref)), m_hint(hint) {} auto operator()(std::string const &description) -> DerivedT & { m_description = description; return static_cast(*this); } auto optional() -> DerivedT & { m_optionality = Optionality::Optional; return static_cast(*this); }; auto required() -> DerivedT & { m_optionality = Optionality::Required; return static_cast(*this); }; auto isOptional() const -> bool { return m_optionality == Optionality::Optional; } auto cardinality() const -> size_t override { if (m_ref->isContainer()) return 0; else return 1; } auto hint() const -> std::string { return m_hint; } }; class ExeName : public ComposableParserImpl { std::shared_ptr m_name; std::shared_ptr m_ref; template static auto makeRef(LambdaT const &lambda) -> std::shared_ptr { return std::make_shared>(lambda); } public: ExeName() : m_name(std::make_shared("")) {} explicit ExeName(std::string &ref) : ExeName() { m_ref = std::make_shared>(ref); } template explicit ExeName(LambdaT const &lambda) : ExeName() { m_ref = std::make_shared>(lambda); } // The exe name is not parsed out of the normal tokens, but is handled specially auto parse(std::string const &, TokenStream const &tokens) const -> InternalParseResult override { return InternalParseResult::ok(ParseState(ParseResultType::NoMatch, tokens)); } auto name() const -> std::string { return *m_name; } auto set(std::string const &newName) -> ParserResult { auto lastSlash = newName.find_last_of("\\/"); auto filename = (lastSlash == std::string::npos) ? newName : newName.substr(lastSlash + 1); *m_name = filename; if (m_ref) return m_ref->setValue(filename); else return ParserResult::ok(ParseResultType::Matched); } }; class Arg : public ParserRefImpl { public: using ParserRefImpl::ParserRefImpl; 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; if (token.type != TokenType::Argument) return InternalParseResult::ok(ParseState(ParseResultType::NoMatch, remainingTokens)); assert(!m_ref->isFlag()); auto valueRef = static_cast(m_ref.get()); auto result = valueRef->setValue(remainingTokens->token); if (!result) return InternalParseResult(result); else return InternalParseResult::ok(ParseState(ParseResultType::Matched, ++remainingTokens)); } }; inline auto normaliseOpt(std::string const &optName) -> std::string { #ifdef CLARA_PLATFORM_WINDOWS if (optName[0] == '/') return "-" + optName.substr(1); else #endif return optName; } class Opt : public ParserRefImpl { protected: std::vector m_optNames; public: template explicit Opt(LambdaT const &ref) : ParserRefImpl(std::make_shared>(ref)) {} explicit Opt(bool &ref) : ParserRefImpl(std::make_shared(ref)) {} template Opt(LambdaT const &ref, std::string const &hint) : ParserRefImpl(ref, hint) {} template Opt(T &ref, std::string const &hint) : ParserRefImpl(ref, hint) {} auto operator[](std::string const &optName) -> Opt & { m_optNames.push_back(optName); return *this; } auto getHelpColumns() const -> std::vector { std::ostringstream oss; bool first = true; for (auto const &opt : m_optNames) { if (first) first = false; else oss << ", "; oss << opt; } if (!m_hint.empty()) oss << " <" << m_hint << ">"; return {{oss.str(), m_description}}; } auto isMatch(std::string const &optToken) const -> bool { auto normalisedToken = normaliseOpt(optToken); for (auto const &name : m_optNames) { if (normaliseOpt(name) == normalisedToken) return true; } return false; } using ParserBase::parse; auto parse(std::string const &, TokenStream const &tokens) const -> InternalParseResult override { auto validationResult = validate(); if (!validationResult) return InternalParseResult(validationResult); auto remainingTokens = tokens; if (remainingTokens && remainingTokens->type == TokenType::Option) { auto const &token = *remainingTokens; if (isMatch(token.token)) { if (m_ref->isFlag()) { auto flagRef = static_cast(m_ref.get()); auto result = flagRef->setFlag(true); if (!result) return InternalParseResult(result); if (result.value() == ParseResultType::ShortCircuitAll) return InternalParseResult::ok(ParseState(result.value(), remainingTokens)); } else { auto valueRef = static_cast(m_ref.get()); ++remainingTokens; if (!remainingTokens) return InternalParseResult::runtimeError("Expected argument following " + token.token); auto const &argToken = *remainingTokens; if (argToken.type != TokenType::Argument) return InternalParseResult::runtimeError("Expected argument following " + token.token); auto result = valueRef->setValue(argToken.token); if (!result) return InternalParseResult(result); if (result.value() == ParseResultType::ShortCircuitAll) return InternalParseResult::ok(ParseState(result.value(), remainingTokens)); } return InternalParseResult::ok(ParseState(ParseResultType::Matched, ++remainingTokens)); } } return InternalParseResult::ok(ParseState(ParseResultType::NoMatch, remainingTokens)); } auto validate() const -> Result override { if (m_optNames.empty()) return Result::logicError("No options supplied to Opt"); for (auto const &name : m_optNames) { if (name.empty()) return Result::logicError("Option name cannot be empty"); #ifdef CLARA_PLATFORM_WINDOWS if (name[0] != '-' && name[0] != '/') return Result::logicError("Option name must begin with '-' or '/'"); #else if (name[0] != '-') return Result::logicError("Option name must begin with '-'"); #endif } return ParserRefImpl::validate(); } }; struct Help : Opt { Help(bool &showHelpFlag) : Opt([&](bool flag) { showHelpFlag = flag; return ParserResult::ok(ParseResultType::ShortCircuitAll); }) { static_cast(*this)("display usage information")["-?"]["-h"]["--help"].optional(); } }; struct Parser : ParserBase { mutable ExeName m_exeName; std::vector m_options; std::vector m_args; auto operator|=(ExeName const &exeName) -> Parser & { m_exeName = exeName; return *this; } auto operator|=(Arg const &arg) -> Parser & { m_args.push_back(arg); return *this; } auto operator|=(Opt const &opt) -> Parser & { m_options.push_back(opt); return *this; } auto operator|=(Parser const &other) -> Parser & { m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end()); m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end()); return *this; } template auto operator|(T const &other) const -> Parser { return Parser(*this) |= other; } // Forward deprecated interface with '+' instead of '|' template auto operator+=(T const &other) -> Parser & { return operator|=(other); } template auto operator+(T const &other) const -> Parser { return operator|(other); } auto getHelpColumns() const -> std::vector { std::vector cols; for (auto const &o : m_options) { auto childCols = o.getHelpColumns(); cols.insert(cols.end(), childCols.begin(), childCols.end()); } return cols; } void writeToStream(std::ostream &os) const { if (!m_exeName.name().empty()) { os << "usage:\n" << " " << m_exeName.name() << " "; bool required = true, first = true; for (auto const &arg : m_args) { if (first) first = false; else os << " "; if (arg.isOptional() && required) { os << "["; required = false; } os << "<" << arg.hint() << ">"; if (arg.cardinality() == 0) os << " ... "; } if (!required) os << "]"; if (!m_options.empty()) os << " options"; os << "\n\nwhere options are:" << std::endl; } auto rows = getHelpColumns(); size_t consoleWidth = CLARA_CONFIG_CONSOLE_WIDTH; size_t optWidth = 0; for (auto const &cols : rows) optWidth = (std::max)(optWidth, cols.left.size() + 2); optWidth = (std::min)(optWidth, consoleWidth / 2); for (auto const &cols : rows) { auto row = TextFlow::Column(cols.left).width(optWidth).indent(2) + TextFlow::Spacer(4) + TextFlow::Column(cols.right).width(consoleWidth - 7 - optWidth); os << row << std::endl; } } friend auto operator<<(std::ostream &os, Parser const &parser) -> std::ostream & { parser.writeToStream(os); return os; } auto validate() const -> Result override { for (auto const &opt : m_options) { auto result = opt.validate(); if (!result) return result; } for (auto const &arg : m_args) { auto result = arg.validate(); if (!result) return result; } return Result::ok(); } using ParserBase::parse; auto parse(std::string const &exeName, TokenStream const &tokens) const -> InternalParseResult override { struct ParserInfo { ParserBase const *parser = nullptr; size_t count = 0; }; const size_t totalParsers = m_options.size() + m_args.size(); assert(totalParsers < 512); // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do ParserInfo parseInfos[512]; { size_t i = 0; for (auto const &opt : m_options) parseInfos[i++].parser = &opt; for (auto const &arg : m_args) parseInfos[i++].parser = &arg; } m_exeName.set(exeName); auto result = InternalParseResult::ok(ParseState(ParseResultType::NoMatch, tokens)); while (result.value().remainingTokens()) { bool tokenParsed = false; for (size_t i = 0; i < totalParsers; ++i) { auto &parseInfo = parseInfos[i]; if (parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality()) { result = parseInfo.parser->parse(exeName, result.value().remainingTokens()); if (!result) return result; if (result.value().type() != ParseResultType::NoMatch) { tokenParsed = true; ++parseInfo.count; break; } } } if (result.value().type() == ParseResultType::ShortCircuitAll) return result; if (!tokenParsed) return InternalParseResult::runtimeError("Unrecognised token: " + result.value().remainingTokens()->token); } // !TBD Check missing required options return result; } }; template template auto ComposableParserImpl::operator|(T const &other) const -> Parser { return Parser() | static_cast(*this) | other; } } // namespace detail // A Combined parser using detail::Parser; // A parser for options using detail::Opt; // A parser for arguments using detail::Arg; // Wrapper for argc, argv from main() using detail::Args; // Specifies the name of the executable using detail::ExeName; // Convenience wrapper for option parser that specifies the help option using detail::Help; // enum of result types from a parse using detail::ParseResultType; // Result type for parser operation using detail::ParserResult; } // namespace clara #endif // CLARA_HPP_INCLUDED waybar-0.12.0/include/util/command.hpp000066400000000000000000000105061475603165300176220ustar00rootroot00000000000000#pragma once #include #include #include #include #include #ifdef __linux__ #include #endif #ifdef __FreeBSD__ #include #endif #include extern std::mutex reap_mtx; extern std::list reap; namespace waybar::util::command { struct res { int exit_code; std::string out; }; inline std::string read(FILE* fp) { std::array buffer = {0}; std::string output; while (feof(fp) == 0) { if (fgets(buffer.data(), 128, fp) != nullptr) { output += buffer.data(); } } // Remove last newline if (!output.empty() && output[output.length() - 1] == '\n') { output.erase(output.length() - 1); } return output; } inline int close(FILE* fp, pid_t pid) { int stat = -1; pid_t ret; fclose(fp); do { ret = waitpid(pid, &stat, WCONTINUED | WUNTRACED); if (WIFEXITED(stat)) { spdlog::debug("Cmd exited with code {}", WEXITSTATUS(stat)); } else if (WIFSIGNALED(stat)) { spdlog::debug("Cmd killed by {}", WTERMSIG(stat)); } else if (WIFSTOPPED(stat)) { spdlog::debug("Cmd stopped by {}", WSTOPSIG(stat)); } else if (WIFCONTINUED(stat)) { spdlog::debug("Cmd continued"); } else if (ret == -1) { spdlog::debug("waitpid failed: {}", strerror(errno)); } else { break; } } while (!WIFEXITED(stat) && !WIFSIGNALED(stat)); return stat; } inline FILE* open(const std::string& cmd, int& pid, const std::string& output_name) { if (cmd == "") return nullptr; int fd[2]; // Open the pipe with the close-on-exec flag set, so it will not be inherited // by any other subprocesses launched by other threads (which could result in // the pipe staying open after this child dies, causing us to hang when trying // to read from it) if (pipe2(fd, O_CLOEXEC) != 0) { spdlog::error("Unable to pipe fd"); return nullptr; } pid_t child_pid = fork(); if (child_pid < 0) { spdlog::error("Unable to exec cmd {}, error {}", cmd.c_str(), strerror(errno)); ::close(fd[0]); ::close(fd[1]); return nullptr; } if (!child_pid) { int err; sigset_t mask; sigfillset(&mask); // Reset sigmask err = pthread_sigmask(SIG_UNBLOCK, &mask, nullptr); if (err != 0) spdlog::error("pthread_sigmask in open failed: {}", strerror(err)); // Kill child if Waybar exits int deathsig = SIGTERM; #ifdef __linux__ if (prctl(PR_SET_PDEATHSIG, deathsig) != 0) { spdlog::error("prctl(PR_SET_PDEATHSIG) in open failed: {}", strerror(errno)); } #endif #ifdef __FreeBSD__ if (procctl(P_PID, 0, PROC_PDEATHSIG_CTL, reinterpret_cast(&deathsig)) == -1) { spdlog::error("procctl(PROC_PDEATHSIG_CTL) in open failed: {}", strerror(errno)); } #endif ::close(fd[0]); dup2(fd[1], 1); setpgid(child_pid, child_pid); if (output_name != "") { setenv("WAYBAR_OUTPUT_NAME", output_name.c_str(), 1); } execlp("/bin/sh", "sh", "-c", cmd.c_str(), (char*)0); exit(0); } else { ::close(fd[1]); } pid = child_pid; return fdopen(fd[0], "r"); } inline struct res exec(const std::string& cmd, const std::string& output_name) { int pid; auto fp = command::open(cmd, pid, output_name); if (!fp) return {-1, ""}; auto output = command::read(fp); auto stat = command::close(fp, pid); return {WEXITSTATUS(stat), output}; } inline struct res execNoRead(const std::string& cmd) { int pid; auto fp = command::open(cmd, pid, ""); if (!fp) return {-1, ""}; auto stat = command::close(fp, pid); return {WEXITSTATUS(stat), ""}; } inline int32_t forkExec(const std::string& cmd) { if (cmd == "") return -1; pid_t pid = fork(); if (pid < 0) { spdlog::error("Unable to exec cmd {}, error {}", cmd.c_str(), strerror(errno)); return pid; } // Child executes the command if (!pid) { int err; sigset_t mask; sigfillset(&mask); // Reset sigmask err = pthread_sigmask(SIG_UNBLOCK, &mask, nullptr); if (err != 0) spdlog::error("pthread_sigmask in forkExec failed: {}", strerror(err)); setpgid(pid, pid); execl("/bin/sh", "sh", "-c", cmd.c_str(), (char*)0); exit(0); } else { reap_mtx.lock(); reap.push_back(pid); reap_mtx.unlock(); spdlog::debug("Added child to reap list: {}", pid); } return pid; } } // namespace waybar::util::command waybar-0.12.0/include/util/css_reload_helper.hpp000066400000000000000000000022731475603165300216630ustar00rootroot00000000000000#pragma once #include #include #include #include #include "giomm/file.h" #include "giomm/filemonitor.h" #include "glibmm/refptr.h" struct pollfd; namespace waybar { class CssReloadHelper { public: CssReloadHelper(std::string cssFile, std::function callback); virtual ~CssReloadHelper() = default; virtual void monitorChanges(); protected: std::vector parseImports(const std::string& cssFile); void parseImports(const std::string& cssFile, std::unordered_map& imports); void watchFiles(const std::vector& files); bool handleInotifyEvents(int fd); bool watch(int inotifyFd, pollfd* pollFd); virtual std::string getFileContents(const std::string& filename); virtual std::string findPath(const std::string& filename); void handleFileChange(Glib::RefPtr const& file, Glib::RefPtr const& other_type, Gio::FileMonitorEvent event_type); private: std::string m_cssFile; std::function m_callback; std::vector>> m_fileMonitors; }; } // namespace waybar waybar-0.12.0/include/util/date.hpp000066400000000000000000000035571475603165300171310ustar00rootroot00000000000000#pragma once #include #if HAVE_CHRONO_TIMEZONES #include #else #include #include #include #endif // Date namespace date { #if HAVE_CHRONO_TIMEZONES using namespace std::chrono; using namespace std; #else using system_clock = std::chrono::system_clock; using seconds = std::chrono::seconds; template inline auto format(const char* spec, const T& arg) { return date::format(std::regex_replace(spec, std::regex("\\{:L|\\}"), ""), arg); } template inline auto format(const std::locale& loc, const char* spec, const T& arg) { return date::format(loc, std::regex_replace(spec, std::regex("\\{:L|\\}"), ""), arg); } #endif } // namespace date // Format namespace waybar::util::date::format { #if HAVE_CHRONO_TIMEZONES using namespace std; #else using namespace fmt; #endif } // namespace waybar::util::date::format #if not HAVE_CHRONO_TIMEZONES template struct fmt::formatter> { std::string_view specs; template constexpr auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { auto it = ctx.begin(); if (it != ctx.end() && *it == ':') { ++it; } auto end = it; while (end != ctx.end() && *end != '}') { ++end; } if (end != it) { specs = {it, std::string_view::size_type(end - it)}; } return end; } template auto format(const date::zoned_time& ztime, FormatContext& ctx) const { if (ctx.locale()) { const auto loc = ctx.locale().template get(); return fmt::format_to(ctx.out(), "{}", date::format(loc, fmt::to_string(specs), ztime)); } return fmt::format_to(ctx.out(), "{}", date::format(fmt::to_string(specs), ztime)); } }; #endif using namespace date; waybar-0.12.0/include/util/enum.hpp000066400000000000000000000005371475603165300171530ustar00rootroot00000000000000#pragma once #include #include #include namespace waybar::util { template struct EnumParser { public: EnumParser(); ~EnumParser(); EnumType parseStringToEnum(const std::string& str, const std::map& enumMap); }; } // namespace waybar::util waybar-0.12.0/include/util/format.hpp000066400000000000000000000062261475603165300175000ustar00rootroot00000000000000#pragma once #include #include class pow_format { public: pow_format(long long val, std::string&& unit, bool binary = false) : val_(val), unit_(unit), binary_(binary) {}; long long val_; std::string unit_; bool binary_; }; namespace fmt { template <> struct formatter { char spec = 0; int width = 0; template constexpr auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { auto it = ctx.begin(), end = ctx.end(); if (it != end && *it == ':') ++it; if (it && (*it == '>' || *it == '<' || *it == '=')) { spec = *it; ++it; } if (it == end || *it == '}') return it; if ('0' <= *it && *it <= '9') { // We ignore it for now, but keep it for compatibility with // existing configs where the format for pow_format'ed numbers was // 'string' and specifications such as {:>9} were valid. // The rationale for ignoring it is that the only reason to specify // an alignment and a with is to get a fixed width bar, and ">" is // sufficient in this implementation. #if FMT_VERSION < 80000 width = parse_nonnegative_int(it, end, ctx); #else width = detail::parse_nonnegative_int(it, end, -1); #endif } return it; } template auto format(const pow_format& s, FormatContext& ctx) const -> decltype(ctx.out()) { const char* units[] = {"", "k", "M", "G", "T", "P", nullptr}; auto base = s.binary_ ? 1024ull : 1000ll; auto fraction = (double)s.val_; int pow; for (pow = 0; units[pow + 1] != nullptr && fraction / base >= 1; ++pow) { fraction /= base; } auto number_width = 5 // coeff in {:.1f} format + s.binary_; // potential 4th digit before the decimal point auto max_width = number_width + 1 // prefix from units array + s.binary_ // for the 'i' in GiB. + s.unit_.length(); const char* format; std::string string; switch (spec) { case '>': return fmt::format_to(ctx.out(), "{:>{}}", fmt::format("{}", s), max_width); case '<': return fmt::format_to(ctx.out(), "{:<{}}", fmt::format("{}", s), max_width); case '=': format = "{coefficient:<{number_width}.1f}{padding}{prefix}{unit}"; break; case 0: default: format = "{coefficient:.1f}{prefix}{unit}"; break; } return fmt::format_to( ctx.out(), fmt::runtime(format), fmt::arg("coefficient", fraction), fmt::arg("number_width", number_width), fmt::arg("prefix", std::string() + units[pow] + ((s.binary_ && pow) ? "i" : "")), fmt::arg("unit", s.unit_), fmt::arg("padding", pow ? "" : s.binary_ ? " " : " ")); } }; // Glib ustirng support template <> struct formatter : formatter { template auto format(const Glib::ustring& value, FormatContext& ctx) const { return formatter::format(static_cast(value), ctx); } }; } // namespace fmt waybar-0.12.0/include/util/gtk_icon.hpp000066400000000000000000000004641475603165300200030ustar00rootroot00000000000000#pragma once #include #include #include class DefaultGtkIconThemeWrapper { private: static std::mutex default_theme_mutex; public: static bool has_icon(const std::string&); static Glib::RefPtr load_icon(const char*, int, Gtk::IconLookupFlags); }; waybar-0.12.0/include/util/json.hpp000066400000000000000000000020701475603165300171520ustar00rootroot00000000000000#pragma once #include #include #include #include #include #include #include #if (FMT_VERSION >= 90000) template <> struct fmt::formatter : ostream_formatter {}; #endif namespace waybar::util { class JsonParser { public: JsonParser() = default; Json::Value parse(const std::string& jsonStr) { Json::Value root; // replace all occurrences of "\x" with "\u00", because JSON doesn't allow "\x" escape sequences std::string modifiedJsonStr = replaceHexadecimalEscape(jsonStr); std::istringstream jsonStream(modifiedJsonStr); std::string errs; if (!Json::parseFromStream(m_readerBuilder, jsonStream, &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"); } }; } // namespace waybar::util waybar-0.12.0/include/util/pipewire/000077500000000000000000000000001475603165300173155ustar00rootroot00000000000000waybar-0.12.0/include/util/pipewire/pipewire_backend.hpp000066400000000000000000000024501475603165300233220ustar00rootroot00000000000000#pragma once #include #include #include "util/backend_common.hpp" #include "util/pipewire/privacy_node_info.hpp" namespace waybar::util::PipewireBackend { class PipewireBackend { private: pw_thread_loop* mainloop_; pw_context* context_; pw_core* core_; pw_registry* registry_; spa_hook registryListener_; /* Hack to keep constructor inaccessible but still public. * This is required to be able to use std::make_shared. * It is important to keep this class only accessible via a reference-counted * pointer because the destructor will manually free memory, and this could be * a problem with C++20's copy and move semantics. */ struct PrivateConstructorTag {}; public: sigc::signal privacy_nodes_changed_signal_event; std::unordered_map privacy_nodes; std::mutex mutex_; static std::shared_ptr getInstance(); // Handlers for PipeWire events void handleRegistryEventGlobal(uint32_t id, uint32_t permissions, const char* type, uint32_t version, const struct spa_dict* props); void handleRegistryEventGlobalRemove(uint32_t id); PipewireBackend(PrivateConstructorTag tag); ~PipewireBackend(); }; } // namespace waybar::util::PipewireBackend waybar-0.12.0/include/util/pipewire/privacy_node_info.hpp000066400000000000000000000017131475603165300235250ustar00rootroot00000000000000#pragma once #include #include #include "util/gtk_icon.hpp" namespace waybar::util::PipewireBackend { enum PrivacyNodeType { PRIVACY_NODE_TYPE_NONE, PRIVACY_NODE_TYPE_VIDEO_INPUT, PRIVACY_NODE_TYPE_AUDIO_INPUT, PRIVACY_NODE_TYPE_AUDIO_OUTPUT }; class PrivacyNodeInfo { public: PrivacyNodeType type = PRIVACY_NODE_TYPE_NONE; uint32_t id; uint32_t client_id; enum pw_node_state state = PW_NODE_STATE_IDLE; std::string media_class; std::string media_name; std::string node_name; std::string application_name; std::string pipewire_access_portal_app_id; std::string application_icon_name; struct spa_hook object_listener; struct spa_hook proxy_listener; void *data; std::string getName(); std::string getIconName(); // Handlers for PipeWire events void handleProxyEventDestroy(); void handleNodeEventInfo(const struct pw_node_info *info); }; } // namespace waybar::util::PipewireBackend waybar-0.12.0/include/util/portal.hpp000066400000000000000000000016741475603165300175130ustar00rootroot00000000000000#include #include #include "fmt/format.h" namespace waybar { using namespace Gio; enum class Appearance { UNKNOWN = 0, DARK = 1, LIGHT = 2, }; class Portal : private DBus::Proxy { public: Portal(); void refreshAppearance(); Appearance getAppearance(); typedef sigc::signal type_signal_appearance_changed; type_signal_appearance_changed signal_appearance_changed() { return m_signal_appearance_changed; } private: type_signal_appearance_changed m_signal_appearance_changed; Appearance currentMode; void on_signal(const Glib::ustring& sender_name, const Glib::ustring& signal_name, const Glib::VariantContainerBase& parameters); }; } // namespace waybar template <> struct fmt::formatter : formatter { // parse is inherited from formatter. auto format(waybar::Appearance c, format_context& ctx) const; }; waybar-0.12.0/include/util/prepare_for_sleep.h000066400000000000000000000003321475603165300213340ustar00rootroot00000000000000#pragma once #include "SafeSignal.hpp" namespace waybar::util { // Get a signal emited with value true when entering sleep, and false when exiting SafeSignal& prepare_for_sleep(); } // namespace waybar::util waybar-0.12.0/include/util/regex_collection.hpp000066400000000000000000000030741475603165300215330ustar00rootroot00000000000000#pragma once #include #include #include #include #include namespace waybar::util { struct Rule { std::regex rule; std::string repr; int priority; // Fix for Clang < 16 // See https://en.cppreference.com/w/cpp/compiler_support/20 "Parenthesized initialization of // aggregates" Rule(std::regex rule, std::string repr, int priority) : rule(std::move(rule)), repr(std::move(repr)), priority(priority) {} }; int default_priority_function(std::string& key); /* A collection of regexes and strings, with a default string to return if no regexes. * When a regex is matched, the corresponding string is returned. * All regexes that are matched are cached, so that the regexes are only * evaluated once against a given string. * Regexes may be given a higher priority than others, so that they are matched * first. The priority function is given the regex string, and should return a * higher number for higher priority regexes. */ class RegexCollection { private: std::vector rules; std::map regex_cache; std::string default_repr; std::string find_match(std::string& value, bool& matched_any); public: RegexCollection() = default; RegexCollection( const Json::Value& map, std::string default_repr = "", const std::function& priority_function = default_priority_function); ~RegexCollection() = default; std::string& get(std::string& value, bool& matched_any); std::string& get(std::string& value); }; } // namespace waybar::util waybar-0.12.0/include/util/rewrite_string.hpp000066400000000000000000000004651475603165300212560ustar00rootroot00000000000000#pragma once #include #include namespace waybar::util { std::string rewriteString(const std::string&, const Json::Value&); std::string rewriteStringOnce(const std::string& value, const Json::Value& rules, bool& matched_any); } // namespace waybar::util waybar-0.12.0/include/util/rfkill.hpp000066400000000000000000000007561475603165300174750ustar00rootroot00000000000000#pragma once #include #include #include #include namespace waybar::util { class Rfkill : public sigc::trackable { public: Rfkill(enum rfkill_type rfkill_type); ~Rfkill(); bool getState() const; sigc::signal on_update; private: enum rfkill_type rfkill_type_; bool state_ = false; int fd_ = -1; bool on_event(Glib::IOCondition cond); }; } // namespace waybar::util waybar-0.12.0/include/util/sanitize_str.hpp000066400000000000000000000002041475603165300207140ustar00rootroot00000000000000#pragma once #include namespace waybar::util { std::string sanitize_string(std::string str); } // namespace waybar::util waybar-0.12.0/include/util/scope_guard.hpp000066400000000000000000000007141475603165300204770ustar00rootroot00000000000000#pragma once #include namespace waybar::util { template class ScopeGuard { public: explicit ScopeGuard(Func&& exit_function) : f{std::forward(exit_function)} {} ScopeGuard(const ScopeGuard&) = delete; ScopeGuard(ScopeGuard&&) = default; ScopeGuard& operator=(const ScopeGuard&) = delete; ScopeGuard& operator=(ScopeGuard&&) = default; ~ScopeGuard() { f(); } private: Func f; }; } // namespace waybar::util waybar-0.12.0/include/util/sleeper_thread.hpp000066400000000000000000000060751475603165300212000ustar00rootroot00000000000000#pragma once #include #include #include #include #include #include "prepare_for_sleep.h" namespace waybar::util { /** * Defer pthread_cancel until the end of a current scope. * * Required to protect a scope where it's unsafe to raise `__forced_unwind` exception. * An example of these is a call of a method marked as `noexcept`; an attempt to cancel within such * a method may result in a `std::terminate` call. */ class CancellationGuard { int oldstate; public: CancellationGuard() { pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate); } ~CancellationGuard() { pthread_setcancelstate(oldstate, &oldstate); } }; class SleeperThread { public: SleeperThread() = default; SleeperThread(std::function func) : thread_{[this, func] { while (do_run_) { signal_ = false; func(); } }} { connection_ = prepare_for_sleep().connect([this](bool sleep) { if (not sleep) wake_up(); }); } SleeperThread& operator=(std::function func) { thread_ = std::thread([this, func] { while (do_run_) { signal_ = false; func(); } }); if (connection_.empty()) { connection_ = prepare_for_sleep().connect([this](bool sleep) { if (not sleep) wake_up(); }); } return *this; } bool isRunning() const { return do_run_; } auto sleep() { std::unique_lock lk(mutex_); CancellationGuard cancel_lock; return condvar_.wait(lk, [this] { return signal_ || !do_run_; }); } auto sleep_for(std::chrono::system_clock::duration dur) { std::unique_lock lk(mutex_); CancellationGuard cancel_lock; 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_; }); } auto sleep_until( std::chrono::time_point time_point) { std::unique_lock lk(mutex_); CancellationGuard cancel_lock; return condvar_.wait_until(lk, time_point, [this] { return signal_ || !do_run_; }); } void wake_up() { { std::lock_guard lck(mutex_); signal_ = true; } condvar_.notify_all(); } auto stop() { { std::lock_guard lck(mutex_); signal_ = true; do_run_ = false; } condvar_.notify_all(); auto handle = thread_.native_handle(); if (handle != 0) { // TODO: find a proper way to terminate thread... pthread_cancel(handle); } } ~SleeperThread() { connection_.disconnect(); stop(); if (thread_.joinable()) { thread_.join(); } } private: std::thread thread_; std::condition_variable condvar_; std::mutex mutex_; bool do_run_ = true; bool signal_ = false; sigc::connection connection_; }; } // namespace waybar::util waybar-0.12.0/include/util/string.hpp000066400000000000000000000013401475603165300175060ustar00rootroot00000000000000#pragma once #include #include const std::string WHITESPACE = " \n\r\t\f\v"; inline std::string ltrim(const std::string& s) { size_t begin = s.find_first_not_of(WHITESPACE); return (begin == std::string::npos) ? "" : s.substr(begin); } inline std::string rtrim(const std::string& s) { size_t end = s.find_last_not_of(WHITESPACE); return (end == std::string::npos) ? "" : s.substr(0, end + 1); } inline std::string trim(const std::string& s) { return rtrim(ltrim(s)); } inline std::string capitalize(const std::string& str) { std::string result = str; std::transform(result.begin(), result.end(), result.begin(), [](unsigned char c) { return std::toupper(c); }); return result; } waybar-0.12.0/include/util/ustring_clen.hpp000066400000000000000000000001721475603165300206760ustar00rootroot00000000000000#pragma once #include // calculate column width of ustring int ustring_clen(const Glib::ustring &str);waybar-0.12.0/man/000077500000000000000000000000001475603165300136445ustar00rootroot00000000000000waybar-0.12.0/man/waybar-backlight-slider.5.scd000066400000000000000000000037351475603165300212050ustar00rootroot00000000000000waybar-backlight-slider(5) # NAME waybar - backlight slider module # DESCRIPTION The *backlight slider* module displays and controls the current brightness of the default or preferred device. The brightness can be controlled by dragging the slider across the bar or clicking on a specific position. # CONFIGURATION *min*: ++ typeof: int ++ default: 0 ++ The minimum volume value the slider should display and set. *max*: ++ typeof: int ++ default: 100 ++ The maximum volume value the slider should display and set. *orientation*: ++ typeof: string ++ default: horizontal ++ The orientation of the slider. Can be either `horizontal` or `vertical`. *device*: ++ typeof: string ++ The name of the preferred device to control. If left empty, a device will be chosen automatically. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # EXAMPLES ``` "modules-right": [ "backlight-slider", ], "backlight/slider": { "min": 0, "max": 100, "orientation": "horizontal", "device": "intel_backlight" } ``` # STYLE The slider is a component with multiple CSS Nodes, of which the following are exposed: *#backlight-slider*: ++ Controls the style of the box *around* the slider and bar. *#backlight-slider slider*: ++ Controls the style of the slider handle. *#backlight-slider trough*: ++ Controls the style of the part of the bar that has not been filled. *#backlight-slider highlight*: ++ Controls the style of the part of the bar that has been filled. ## STYLE EXAMPLE ``` #backlight-slider slider { min-height: 0px; min-width: 0px; opacity: 0; background-image: none; border: none; box-shadow: none; } #backlight-slider trough { min-height: 80px; min-width: 10px; border-radius: 5px; background-color: black; } #backlight-slider highlight { min-width: 10px; border-radius: 5px; background-color: red; } ``` waybar-0.12.0/man/waybar-backlight.5.scd000066400000000000000000000054051475603165300177210ustar00rootroot00000000000000waybar-backlight(5) # NAME waybar - backlight module # DESCRIPTION The *backlight* module displays the current backlight level. # CONFIGURATION *interval*: ++ typeof: integer ++ default: 2 ++ The interval in which information gets polled. *format*: ++ typeof: string ++ default: {percent}% ++ The format, how information should be displayed. On {} data gets inserted. *max-length*: ++ typeof: integer ++ The maximum length in characters the module should display. *min-length*: ++ typeof: integer ++ The minimum length in characters the module should accept. *align*: ++ typeof: float ++ The alignment of the label within the module, where 0 is left-aligned and 1 is right-aligned. If the module is rotated, it will follow the flow of the text. *justify*: ++ typeof: string ++ The alignment of the text within the module's label, allowing options 'left', 'right', or 'center' to define the positioning. *rotate*: ++ typeof: integer ++ Positive value to rotate the text label (in 90 degree increments). *states*: ++ typeof: object ++ A number of backlight states which get activated on certain brightness levels. See *waybar-states(5)*. *on-click*: ++ typeof: string ++ Command to execute when the module is clicked. *on-click-middle*: ++ typeof: string ++ Command to execute when middle-clicked on the module using mouse scroll wheel. *on-click-right*: ++ typeof: string ++ Command to execute when the module is right-clicked. *on-update*: ++ typeof: string ++ Command to execute when the module is updated. *on-scroll-up*: ++ typeof: string ++ Command to execute when performing a scroll up on the module. This replaces the default behaviour of brightness control. *on-scroll-down*: ++ typeof: string Command to execute when performing a scroll down on the module. This replaces the default behaviour of brightness control. *smooth-scrolling-threshold*: ++ typeof: double Threshold to be used when scrolling. *reverse-scrolling*: ++ typeof: bool ++ Option to reverse the scroll direction. *scroll-step*: ++ typeof: float ++ default: 1.0 ++ The speed at which to change the brightness when scrolling. *min-brightness*: ++ typeof: double ++ default: 0.0 ++ The minimum brightness of the backlight. *menu*: ++ typeof: string ++ Action that popups the menu. *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # EXAMPLE: ``` "backlight": { "device": "intel_backlight", "format": "{percent}% {icon}", "format-icons": ["", ""] } ``` # STYLE - *#backlight* waybar-0.12.0/man/waybar-battery.5.scd000066400000000000000000000131631475603165300174430ustar00rootroot00000000000000waybar-battery(5) # NAME waybar - battery module # DESCRIPTION The *battery* module displays the current capacity and state (eg. charging) of your battery. # CONFIGURATION *bat*: ++ typeof: string ++ The battery to monitor, as in /sys/class/power_supply/ instead of auto detect. *adapter*: ++ typeof: string ++ The adapter to monitor, as in /sys/class/power_supply/ instead of auto detect. *full-at*: ++ typeof: integer ++ Define the max percentage of the battery, for when you've set the battery to stop charging at a lower level to save it. For example, if you've set the battery to stop at 80% that will become the new 100%. *design-capacity*: ++ typeof: bool ++ default: false ++ Option to use the battery design capacity instead of its current maximal capacity. *interval*: ++ typeof: integer ++ default: 60 ++ The interval in which the information gets polled. *states*: ++ typeof: object ++ A number of battery states which get activated on certain capacity levels. See *waybar-states(5)*. *format*: ++ typeof: string ++ default: {capacity}% ++ The format, how information should be displayed. *format-time*: ++ typeof: string ++ default: {H} h {M} min ++ The format, how the time should be displayed. *format-icons*: ++ typeof: array/object ++ Based on the current capacity, the corresponding icon gets selected. ++ The order is *low* to *high*. Or by the state if it is an object. *max-length*: ++ typeof: integer++ The maximum length in character the module should display. *min-length*: ++ typeof: integer ++ The minimum length in characters the module should accept. *align*: ++ typeof: float ++ The alignment of the label within the module, where 0 is left-aligned and 1 is right-aligned. If the module is rotated, it will follow the flow of the text. *justify*: ++ typeof: string ++ The alignment of the text within the module's label, allowing options 'left', 'right', or 'center' to define the positioning. *rotate*: ++ typeof: integer++ Positive value to rotate the text label (in 90 degree increments). *on-click*: ++ typeof: string ++ Command to execute when clicked on the module. *on-click-middle*: ++ typeof: string ++ Command to execute when middle-clicked on the module using mousewheel. *on-click-right*: ++ typeof: string ++ Command to execute when you right-click on the module. *on-update*: ++ typeof: string ++ Command to execute when the module is updated. *on-scroll-up*: ++ typeof: string ++ Command to execute when scrolling up on the module. *on-scroll-down*: ++ typeof: string ++ Command to execute when scrolling down on the module. *smooth-scrolling-threshold*: ++ typeof: double ++ Threshold to be used when scrolling. *tooltip*: ++ typeof: bool ++ default: true ++ Option to disable tooltip on hover. *bat-compatibility*: ++ typeof: bool ++ default: false ++ Option to enable battery compatibility if not detected. *menu*: ++ typeof: string ++ Action that popups the menu. *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # FORMAT REPLACEMENTS *{capacity}*: Capacity in percentage *{power}*: Power in watts *{icon}*: Icon, as defined in *format-icons*. *{time}*: Estimate of time until full or empty. Note that this is based on the power draw at the last refresh time, not an average. *{cycles}*: Amount of charge cycles the highest-capacity battery has seen. *(Linux only)* *{health}*: The percentage of the highest-capacity battery's original maximum charge it can still hold. # TIME FORMAT The *battery* module allows you to define how time should be formatted via *format-time*. The three arguments are: *{H}*: Hours *{M}*: Minutes *{m}*: Zero-padded minutes # CUSTOM FORMATS The *battery* module allows one to define custom formats based on up to two factors. The best-fitting format will be selected. *format-*: With *states*, a custom format can be set depending on the capacity of your battery. *format-*: With the status, a custom format can be set depending on the status in /sys/class/power_supply//status (in lowercase). *format--*: You can also set a custom format depending on both values. # STATES - Every entry (*state*) consists of a ** (typeof: *string*) and a ** (typeof: *integer*). - 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*. # EXAMPLES ``` "battery": { "bat": "BAT2", "interval": 60, "states": { "warning": 30, "critical": 15 }, "format": "{capacity}% {icon}", "format-icons": ["", "", "", "", ""], "max-length": 25 } ``` # STYLE - *#battery* - *#battery.* - ** is the value of /sys/class/power_supply//status in lowercase. - *#battery.* - ** can be defined in the *config*. For more information see *states*. - *#battery..* - Combination of both ** and **. The following classes are applied to the entire Waybar rather than just the battery widget: - *window#waybar.battery-* - ** can be defined in the *config*, as previously mentioned. waybar-0.12.0/man/waybar-bluetooth.5.scd000066400000000000000000000172521475603165300200010ustar00rootroot00000000000000waybar-bluetooth(5) # NAME waybar - bluetooth module # DESCRIPTION The *bluetooth* module displays information about a bluetooth controller and its connections. # CONFIGURATION Addressed by *bluetooth* *controller*: ++ typeof: string ++ Use the controller with the defined alias. Otherwise, a random controller is used. Recommended to define when there is more than 1 controller available to the system. *format-device-preference*: ++ typeof: array ++ A ranking of bluetooth devices, addressed by their alias. The order is from *first displayed* to *last displayed*. ++ If this config option is not defined or none of the devices in the list are connected, it will fall back to showing the last connected device. *format*: ++ typeof: string ++ default: * {status}* ++ The format, how information should be displayed. This format is used when other formats aren't specified. *format-disabled*: ++ typeof: string ++ This format is used when the displayed controller is disabled. *format-off*: ++ typeof: string ++ This format is used when the displayed controller is turned off. *format-on*: ++ typeof: string ++ This format is used when the displayed controller is turned on with no devices connected. *format-connected*: ++ typeof: string ++ This format is used when the displayed controller is connected to at least 1 device. *format-no-controller*: ++ typeof: string ++ This format is used when no bluetooth controller can be found *format-icons*: ++ typeof: array/object ++ Based on the current battery percentage (see section *EXPERIMENTAL BATTERY PERCENTAGE FEATURE*), the corresponding icon gets selected. ++ The order is *low* to *high*. Will only show the current battery percentage icon in the *\*-connected-battery* config options. ++ Or by the state if it is an object. It will fall back to the enabled state if its derivatives are not defined (on, off, connected). *rotate*: ++ typeof: integer ++ Positive value to rotate the text label (in 90 degree increments). *max-length*: ++ typeof: integer ++ The maximum length in character the module should display. *min-length*: ++ typeof: integer ++ The minimum length in characters the module should accept. *align*: ++ typeof: float ++ The alignment of the label within the module, where 0 is left-aligned and 1 is right-aligned. If the module is rotated, it will follow the flow of the text. *justify*: ++ typeof: string ++ The alignment of the text within the module's label, allowing options 'left', 'right', or 'center' to define the positioning. *on-click*: ++ typeof: string ++ Command to execute when clicked on the module. *on-click-middle*: ++ typeof: string ++ Command to execute when middle-clicked on the module using mousewheel. *on-click-right*: ++ typeof: string ++ Command to execute when you right-click on the module. *on-scroll-up*: ++ typeof: string ++ Command to execute when scrolling up on the module. *on-scroll-down*: ++ typeof: string ++ Command to execute when scrolling down on the module. *smooth-scrolling-threshold*: ++ typeof: double ++ Threshold to be used when scrolling. *tooltip*: ++ typeof: bool ++ default: *true* ++ Option to disable tooltip on hover. *tooltip-format*: ++ typeof: string ++ The format, how information should be displayed in the tooltip. This format is used when other formats aren't specified. *tooltip-format-disabled*: ++ typeof: string ++ This format is used when the displayed controller is disabled. *tooltip-format-off*: ++ typeof: string ++ This format is used when the displayed controller is turned off. *tooltip-format-on*: ++ typeof: string ++ This format is used when the displayed controller is turned on with no devices connected. *tooltip-format-connected*: ++ typeof: string ++ This format is used when the displayed controller is connected to at least 1 device. *tooltip-format-no-controller*: ++ typeof: string ++ This format is used when no bluetooth controller can be found *tooltip-format-enumerate-connected*: ++ typeof: string ++ This format is used to define how each connected device should be displayed within the *device_enumerate* format replacement in the tooltip menu. *menu*: ++ typeof: string ++ Action that popups the menu. *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # FORMAT REPLACEMENTS *{status}*: Status of the bluetooth device. *{icon}*: Icon, as defined in *format-icons*. *{num_connections}*: Number of connections the displayed controller has. *{controller_address}*: Address of the displayed controller. *{controller_address_type}*: Address type of the displayed controller. *{controller_alias}*: Alias of the displayed controller. *{device_address}*: Address of the displayed device. *{device_address_type}*: Address type of the displayed device. *{device_alias}*: Alias of the displayed device. *{device_enumerate}*: Show a list of all connected devices, each on a separate line. Define the format of each device with the *tooltip-format-enumerate-connected* ++ and/or *tooltip-format-enumerate-connected-battery* config options. Can only be used in the tooltip-related format options. # EXPERIMENTAL BATTERY PERCENTAGE FEATURE At the time of writing, the experimental features of BlueZ need to be turned on, for the battery percentage options listed below to work. ## FORMAT REPLACEMENT *{device_battery_percentage}*: Battery percentage of the displayed device if available. Use only in the config options defined below. ## CONFIGURATION *format-connected-battery*: ++ typeof: string ++ This format is used when the displayed device provides its battery percentage. *tooltip-format-connected-battery*: ++ typeof: string ++ This format is used when the displayed device provides its battery percentage. *tooltip-format-enumerate-connected-battery*: ++ typeof: string ++ This format is used to define how each connected device with a battery should be displayed within the *device_enumerate* format replacement option. ++ When this config option is not defined, it will fall back on the *tooltip-format-enumerate-connected* config option. # EXAMPLES ``` "bluetooth": { // "controller": "controller1", // specify the alias of the controller if there are more than 1 on the system "format": " {status}", "format-disabled": "", // an empty format will hide the module "format-connected": " {num_connections} connected", "tooltip-format": "{controller_alias}\\t{controller_address}", "tooltip-format-connected": "{controller_alias}\\t{controller_address}\\n\\n{device_enumerate}", "tooltip-format-enumerate-connected": "{device_alias}\\t{device_address}" } ``` ``` "bluetooth": { "format": " {status}", "format-connected": " {device_alias}", "format-connected-battery": " {device_alias} {device_battery_percentage}%", // "format-device-preference": [ "device1", "device2" ], // preference list deciding the displayed device "tooltip-format": "{controller_alias}\\t{controller_address}\\n\\n{num_connections} connected", "tooltip-format-connected": "{controller_alias}\\t{controller_address}\\n\\n{num_connections} connected\\n\\n{device_enumerate}", "tooltip-format-enumerate-connected": "{device_alias}\\t{device_address}", "tooltip-format-enumerate-connected-battery": "{device_alias}\\t{device_address}\\t{device_battery_percentage}%" } ``` # STYLE - *#bluetooth* - *#bluetooth.disabled* - *#bluetooth.off* - *#bluetooth.on* - *#bluetooth.connected* - *#bluetooth.discoverable* - *#bluetooth.discovering* - *#bluetooth.pairable* waybar-0.12.0/man/waybar-cava.5.scd000066400000000000000000000140121475603165300166750ustar00rootroot00000000000000waybar-cava(5) "waybar-cava" "User Manual" # NAME waybar - cava module # DESCRIPTION *cava* module for karlstav/cava project. See it on github: https://github.com/karlstav/cava. # FILES $XDG_CONFIG_HOME/waybar/config ++ Per user configuration file # ADDITIONAL FILES libcava lives in: . /usr/lib/libcava.so or /usr/lib64/libcava.so . /usr/lib/pkgconfig/cava.pc or /usr/lib64/pkgconfig/cava.pc . /usr/include/cava # CONFIGURATION [- *Option* :- *Typeof* :- *Default* :- *Description* |[ *cava_config* :[ string :[ :< Path where cava configuration file is placed to |[ *framerate* :[ integer :[ 30 :[ Frames per second. Is used as a replacement for *interval* |[ *autosens* :[ integer :[ 1 :[ Will attempt to decrease sensitivity if the bars peak |[ *sensitivity* :[ integer :[ 100 :[ Manual sensitivity in %. It's recommended to be omitted when *autosens* = 1 |[ *bars* :[ integer :[ 12 :[ The number of bars |[ *lower_cutoff_freq* :[ long integer :[ 50 :[ Lower cutoff frequencies for lowest bars the bandwidth of the visualizer |[ *higher_cutoff_freq* :[ long integer :[ 10000 :[ Higher cutoff frequencies for highest bars the bandwidth of the visualizer |[ *sleep_timer* :[ integer :[ 5 :[ Seconds with no input before cava main thread goes to sleep mode |[ *hide_on_silence* :[ bool :[ false :[ Hides the widget if no input (after sleep_timer elapsed) |[ *format_silent* :[ string :[ :[ Widget's text after sleep_timer elapsed (hide_on_silence has to be false) |[ *method* :[ string :[ pulse :[ Audio capturing method. Possible methods are: pipewire, pulse, alsa, fifo, sndio or shmem |[ *source* :[ string :[ auto :[ See cava configuration |[ *sample_rate* :[ long integer :[ 44100 :[ See cava configuration |[ *sample_bits* :[ integer :[ 16 :[ See cava configuration |[ *stereo* :[ bool :[ true :[ Visual channels |[ *reverse* :[ bool :[ false :[ Displays frequencies the other way around |[ *bar_delimiter* :[ integer :[ 0 :[ Each bar is separated by a delimiter. Use decimal value in ascii table(i.e. 59 = ";"). 0 means no delimiter |[ *monstercat* :[ bool :[ false :[ Disables or enables the so-called "Monstercat smoothing" with or without "waves" |[ *waves* :[ bool :[ 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 |[ *input_delay* :[ integer :[ 2 :[ Sets the delay before fetching audio source thread start working. On author's machine, Waybar starts much faster than pipewire audio server, and without a little delay cava module fails because pipewire is not ready |[ *ascii_max_range* :[ integer :[ 7 :[ It's impossible to set it directly. The value is dictated by the number of icons in the array *format-icons* |[ *data_format* :[ string :[ asci :[ It's impossible to set it. Waybar sets it to = asci for internal needs |[ *raw_target* :[ string :[ /dev/stdout :[ It's impossible to set it. Waybar sets it to = /dev/stdout for internal needs |[ *menu* :[ string :[ :[ Action that popups the menu. |[ *menu-file* :[ string :[ :[ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* |[ *menu-actions* :[ array :[ :[ The actions corresponding to the buttons of the menu. Configuration can be provided as: - The only cava configuration file which is provided through *cava_config*. The rest configuration can be skipped - Without cava configuration file. In such case cava should be configured through provided list of the configuration option - Mix. When provided both And cava configuration file And configuration options. In such case, waybar applies configuration file first and then overrides particular options by the provided list of configuration options # ACTIONS [- *String* :- *Action* |[ *mode* :< Switch main cava thread and fetch audio source thread from/to pause/resume # DEPENDENCIES - iniparser - fftw3 # 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 # RISING ISSUES For clear understanding: this module is a cava API's consumer. So for any bugs related to cava engine you should contact Cava upstream(https://github.com/karlstav/cava) ++ with the one Exception. Cava upstream doesn't provide cava as a shared library. For that, this module author made a fork libcava(https://github.com/LukashonakV/cava). ++ So the order is: . cava upstream . libcava upstream. In case when cava releases new version and you're wanna get it, it should be raised an issue to libcava(https://github.com/LukashonakV/cava) with title ++ \[Bump\]x.x.x where x.x.x is cava release version. # EXAMPLES ``` "cava": { //"cava_config": "$XDG_CONFIG_HOME/cava/cava.conf", "framerate": 30, "autosens": 1, //"sensitivity": 100, "bars": 14, "lower_cutoff_freq": 50, "higher_cutoff_freq": 10000, "method": "pulse", "source": "auto", "stereo": true, "reverse": false, "bar_delimiter": 0, "monstercat": false, "waves": false, "noise_reduction": 0.77, "input_delay": 2, "format-icons" : ["▁", "▂", "▃", "▄", "▅", "▆", "▇", "█" ], "actions": { "on-click-right": "mode" } }, ``` # STYLE - *#cava* - *#cava.silent* Applied after no sound has been detected for sleep_timer seconds - *#cava.updated* Applied when a new frame is shown waybar-0.12.0/man/waybar-cffi.5.scd000066400000000000000000000016311475603165300166750ustar00rootroot00000000000000waybar-cffi(5) # NAME waybar - cffi module # DESCRIPTION The *cffi* module gives full control of a GTK widget to a third-party dynamic library, to create more complex modules using different programming languages. # CONFIGURATION Addressed by *cffi/* *module_path*: ++ typeof: string ++ The path to the dynamic library to load to control the widget. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. Some additional configuration may be required depending on the cffi dynamic library being used. # EXAMPLES ## C example: An example module written in C can be found at https://github.com/Alexays/Waybar/resources/custom_modules/cffi_example/ Waybar config to enable the module: ``` "cffi/c_example": { "module_path": ".config/waybar/cffi/wb_cffi_example.so" } ``` # STYLE The classes and IDs are managed by the cffi dynamic library. waybar-0.12.0/man/waybar-clock.5.scd000066400000000000000000000153231475603165300170640ustar00rootroot00000000000000waybar-clock(5) "waybar-clock" "User Manual" # NAME waybar - clock module # DESCRIPTION *clock* module displays current date and time # FILES $XDG_CONFIG_HOME/waybar/config ++ Per user configuration file # CONFIGURATION 1. Addressed by *clock* [- *Option* :- *Typeof* :- *Default* :- *Description* |[ *interval* :[ integer :[ 60 :[ The interval in which the information gets polled |[ *format* :[ string :[ *{:%H:%M}* :[ The format, how the date and time should be displayed. See format options below |[ *timezone* :[ string :[ :[ The timezone to display the time in, e.g. America/New_York. "" represents the system's local timezone. See Wikipedia's unofficial list of timezones |[ *timezones* :[ list of strings :[ :[ 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 |[ *locale* :[ string :[ :[ A locale to be used to display the time. Intended to render times in custom timezones with the proper language and format |[ *max-length* :[ integer :[ :[ The maximum length in character the module should display |[ *rotate* :[ integer :[ :[ Positive value to rotate the text label (in 90 degree increments) |[ *on-click* :[ string :[ :[ Command to execute when clicked on the module |[ *on-click-middle* :[ string :[ :[ Command to execute when you middle clicked on the module using mousewheel |[ *on-click-right* :[ string :[ :[ Command to execute when you right-click on the module |[ *on-scroll-up* :[ string :[ :[ Command to execute when scrolling up on the module |[ *on-scroll-down* :[ string :[ :[ Command to execute when scrolling down on the module |[ *smooth-scrolling-threshold* :[ double :[ :[ Threshold to be used when scrolling |[ *tooltip* :[ bool :[ true :[ Option to enable tooltip on hover |[ *tooltip-format* :[ string :[ same as format :[ Tooltip on hover |[ *menu* :[ string :[ :[ Action that popups the menu. |[ *menu-file* :[ string :[ :[ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* |[ *menu-actions* :[ array :[ :[ The actions corresponding to the buttons of the menu. |[ *expand*: :[ bool :[ false :[ Enables this module to consume all left over space dynamically. View all valid format options in *strftime(3)* or have a look https://en.cppreference.com/w/cpp/chrono/duration/formatter 2. Addressed by *clock: calendar* [- *Option* :- *Typeof* :- *Default* :- *Description* |[ *mode* :[ string :[ month :[ Calendar view mode. Possible values: year|month |[ *mode-mon-col* :[ integer :[ 3 :[ Relevant for *mode=year*. Count of months per row |[ *weeks-pos* :[ integer :[ :[ The position where week numbers should be displayed. Disabled when is empty. Possible values: left|right |[ *on-scroll* :[ integer :[ 1 :[ Value to scroll months/years forward/backward. Can be negative. Is configured under *on-scroll* option 3. Addressed by *clock: calendar: format* [- *Option* :- *Typeof* :- *Default* :- *Description* |[ *months* :[ string :[ :[ Format is applied to months header(January, February,...etc.) |[ *days* :[ string :[ :[ Format is applied to days |[ *weeks* :[ string :[ *{:%U}* :[ Format is applied to week numbers. When weekday format is not provided then is used default format: '{:%W}' when week starts with Monday, '{:%U}' otherwise |[ *weekdays* :[ string :[ :[ Format is applied to weeks header(Su,Mo,...etc.) |[ *today* :[ string :[ *{}* :[ Format is applied to Today ## Actions [- *String* :- *Action* |[ *mode* :[ Switch calendar mode between year/month |[ *tz_up* :[ Switch to the next provided time zone |[ *tz_down* :[ Switch to the previously provided time zone |[ *shift_up* :[ Switch to the next calendar month/year |[ *shift_down* :[ Switch to the previous calendar month/year # FORMAT REPLACEMENTS - *{calendar}*: Current month calendar - *{tz_list}*: List of time in the rest timezones, if more than one timezone is set in the config - *{ordinal_date}*: The current day in (English) ordinal form, e.g. 21st # EXAMPLES 1. General ``` "clock": { "interval": 60, "format": "{:%H:%M}", "max-length": 25 } ``` 2. Calendar ``` "clock": { "format": "{:%H:%M}  ", "format-alt": "{:%A, %B %d, %Y (%R)}  ", "tooltip-format": "{calendar}", "calendar": { "mode" : "year", "mode-mon-col" : 3, "weeks-pos" : "right", "on-scroll" : 1, "on-click-right": "mode", "format": { "months": "{}", "days": "{}", "weeks": "W{}", "weekdays": "{}", "today": "{}" } }, "actions": { "on-click-right": "mode", "on-click-forward": "tz_up", "on-click-backward": "tz_down", "on-scroll-up": "shift_up", "on-scroll-down": "shift_down" } }, ``` 3. Full date on hover ``` "clock": { "interval": 60, "tooltip": true, "format": "{:%H.%M}", "tooltip-format": "{:%Y-%m-%d}", } ``` # STYLE - *#clock* # Troubleshooting If clock module is disabled at startup with locale::facet::\_S\_create\_c\_locale ++ name not valid error message try one of the following: - check if LC_TIME is set properly (glibc) - set locale to C in the config file (musl) The locale option must be set for {calendar} to use the correct start-of-week, regardless of system locale. ## Calendar in Chinese. Alignment In order to have aligned Chinese calendar there are some useful recommendations: . Use "WenQuanYi Zen Hei Mono" which is provided in most Linux distributions . Try different font sizes and find best for you. size = 9pt should be fine . In case when "WenQuanYi Zen Hei Mono" font is used disable monospace font pango tag Example of working config ``` "clock": { "format": "{:%H:%M}  ", "format-alt": "{:%A, %B %d, %Y (%R)}  ", "tooltip-format": "\n{calendar}", "calendar": { "mode" : "year", "mode-mon-col" : 3, "weeks-pos" : "right", "on-scroll" : 1, "on-click-right": "mode", "format": { "months": "{}", "days": "{}", "weeks": "W{}", "weekdays": "{}", "today": "{}" } }, "actions": { "on-click-right": "mode", "on-click-forward": "tz_up", "on-click-backward": "tz_down", "on-scroll-up": "shift_up", "on-scroll-down": "shift_down" } }, ``` # AUTHOR Alexis Rouillard waybar-0.12.0/man/waybar-cpu.5.scd000066400000000000000000000060721475603165300165610ustar00rootroot00000000000000waybar-cpu(5) # NAME waybar - cpu module # DESCRIPTION The *cpu* module displays the current CPU utilization. # CONFIGURATION *interval*: ++ typeof: integer ++ default: 10 ++ The interval in which the information gets polled. *format*: ++ typeof: string ++ default: {usage}% ++ The format, how information should be displayed. On {} data gets inserted. *format-icons*: ++ typeof: array/object ++ Based on the current usage, the corresponding icon gets selected. ++ The order is *low* to *high*. Or by the state if it is an object. *max-length*: ++ typeof: integer ++ The maximum length in character the module should display. *min-length*: ++ typeof: integer ++ The minimum length in characters the module should accept. *align*: ++ typeof: float ++ The alignment of the label within the module, where 0 is left-aligned and 1 is right-aligned. If the module is rotated, it will follow the flow of the text. *justify*: ++ typeof: string ++ The alignment of the text within the module's label, allowing options 'left', 'right', or 'center' to define the positioning. *rotate*: ++ typeof: integer ++ Positive value to rotate the text label (in 90 degree increments). *states*: ++ typeof: object ++ A number of CPU usage states which get activated on certain usage levels. See *waybar-states(5)*. *on-click*: ++ typeof: string ++ Command to execute when clicked on the module. *on-click-middle*: ++ typeof: string ++ Command to execute when middle-clicked on the module using mousewheel. *on-click-right*: ++ typeof: string ++ Command to execute when you right-click on the module. *on-update*: ++ typeof: string ++ Command to execute when the module is updated. *on-scroll-up*: ++ typeof: string ++ Command to execute when scrolling up on the module. *on-scroll-down*: ++ typeof: string ++ Command to execute when scrolling down on the module. *smooth-scrolling-threshold*: ++ typeof: double ++ Threshold to be used when scrolling. *tooltip*: ++ typeof: bool ++ default: true ++ Option to disable tooltip on hover. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # FORMAT REPLACEMENTS *{load}*: Current CPU load. *{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}. *{avg_frequency}*: Current CPU average frequency (based on all cores) in GHz. *{max_frequency}*: Current CPU max frequency (based on the core with the highest frequency) in GHz. *{min_frequency}*: Current CPU min frequency (based on the core with the lowest frequency) in GHz. *{icon}*: Icon for overall CPU usage. *{icon*{n}*}*: Icon for CPU core n usage. Use like {icon0}. # EXAMPLES Basic configuration: ``` "cpu": { "interval": 10, "format": "{}% ", "max-length": 10 } ``` CPU usage per core rendered as icons: ``` "cpu": { "interval": 1, "format": "{icon0}{icon1}{icon2}{icon3} {usage:>2}% ", "format-icons": ["▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"], }, ``` # STYLE - *#cpu* waybar-0.12.0/man/waybar-custom.5.scd000066400000000000000000000145271475603165300173100ustar00rootroot00000000000000waybar-custom(5) # NAME waybar - custom module # DESCRIPTION The *custom* module displays either the output of a script or static text. To display static text, specify only the *format* field. # CONFIGURATION Addressed by *custom/* *exec*: ++ typeof: string ++ The path to the script, which should be executed. *exec-if*: ++ typeof: string ++ The path to a script, which determines if the script in *exec* should be executed. ++ *exec* will be executed if the exit code of *exec-if* equals 0. *hide-empty-text*: ++ typeof: bool ++ Disables the module when output is empty, but format might contain additional static content. *exec-on-event*: ++ typeof: bool ++ default: true ++ If an event command is set (e.g. *on-click* or *on-scroll-up*) then re-execute the script after executing the event command. *return-type*: ++ typeof: string ++ See *return-type* *interval*: ++ typeof: integer ++ The interval (in seconds) in which the information gets polled. ++ 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 ++ The restart interval (in seconds). ++ 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*. *signal*: ++ typeof: integer ++ The signal number used to update the module. ++ The number is valid between 1 and N, where *SIGRTMIN+N* = *SIGRTMAX*. ++ If no interval is defined then a signal will be the only way to update the module. *format*: ++ typeof: string ++ default: {text} ++ The format, how information should be displayed. On {text} data gets inserted. *format-icons*: ++ typeof: array ++ Based on the set percentage, the corresponding icon gets selected. The order is *low* to *high*. *rotate*: ++ typeof: integer ++ Positive value to rotate the text label (in 90 degree increments). *max-length*: ++ typeof: integer ++ The maximum length in character the module should display. *min-length*: ++ typeof: integer ++ The minimum length in characters the module should accept. *align*: ++ typeof: float ++ The alignment of the label within the module, where 0 is left-aligned and 1 is right-aligned. If the module is rotated, it will follow the flow of the text. *justify*: ++ typeof: string ++ The alignment of the text within the module's label, allowing options 'left', 'right', or 'center' to define the positioning. *on-click*: ++ typeof: string ++ Command to execute when clicked on the module. *on-click-middle*: ++ typeof: string ++ Command to execute when middle-clicked on the module using mousewheel. *on-click-right*: ++ typeof: string ++ Command to execute when you right-click on the module. *on-update*: ++ typeof: string ++ Command to execute when the module is updated. *on-scroll-up*: ++ typeof: string ++ Command to execute when scrolling up on the module. *on-scroll-down*: ++ typeof: string ++ Command to execute when scrolling down on the module. *smooth-scrolling-threshold*: ++ typeof: double ++ Threshold to be used when scrolling. *tooltip*: ++ typeof: bool ++ default: true ++ Option to disable tooltip on hover. *tooltip-format*: ++ typeof: string ++ The tooltip format. If specified, overrides any tooltip output from the script in *exec*. ++ Uses the same format replacements as *format*. *escape*: ++ typeof: bool ++ default: false ++ Option to enable escaping of script output. *menu*: ++ typeof: string ++ Action that popups the menu. *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # RETURN-TYPE When *return-type* is set to *json*, Waybar expects the *exec*-script to output its data in JSON format. This should look like this: ``` {"text": "$text", "tooltip": "$tooltip", "class": "$class", "percentage": $percentage } ``` The *class* parameter also accepts an array of strings. If nothing or an invalid option is specified, Waybar expects i3blocks style output. Values are *newline* separated. This should look like this: ``` $text\\n$tooltip\\n$class* ``` *class* is a CSS class, to apply different styles in *style.css* # FORMAT REPLACEMENTS *{text}*: Output of the script. *{percentage}* Percentage which can be set via a json return type. *{icon}*: An icon from 'format-icons' according to percentage. # EXAMPLES ## Spotify: ``` "custom/spotify": { "format": " {text}", "max-length": 40, "interval": 30, // Remove this if your script is endless and write in loop "exec": "$HOME/.config/waybar/mediaplayer.sh 2> /dev/null", // Script in resources folder "exec-if": "pgrep spotify", "return-type": "json" } ``` ## mpd: ``` "custom/mpd": { "format": "♪ {text}", //"max-length": 15, "interval": 10, "exec": "mpc current", "exec-if": "pgrep mpd", "on-click": "mpc toggle", "on-click-right": "sonata" } ``` ## cmus: ``` "custom/cmus": { "format": "♪ {text}", //"max-length": 15, "interval": 10, "exec": "cmus-remote -C \"format_print '%a - %t'\"", // artist - title "exec-if": "pgrep cmus", "on-click": "cmus-remote -u", //toggle pause "escape": true //handle markup entities } ``` ## Pacman ``` "custom/pacman": { "format": "{text} ", "interval": "once", "exec": "pacman_packages", "on-click": "update-system", "signal": 8 } ``` ## Alternate Pacman ``` "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 "signal": 8 } ``` You can use the signal and update the number of available packages with *pkill -RTMIN+8 waybar*. # STYLE - *#custom-* - *#custom-.* - ** can be set by the script. For more information see *return-type* waybar-0.12.0/man/waybar-disk.5.scd000066400000000000000000000077001475603165300167230ustar00rootroot00000000000000waybar-disk(5) # NAME waybar - disk module # DESCRIPTION The *disk* module displays the current disk space used. # CONFIGURATION Addressed by *disk* *path*: ++ typeof: string ++ default: "/" ++ Any path residing in the filesystem or mountpoint for which the information should be displayed. *interval*: ++ typeof: integer++ default: 30 ++ The interval in which the information gets polled. *format*: ++ typeof: string ++ default: "{percentage_used}%" ++ The format, how information should be displayed. *rotate*: ++ typeof: integer ++ Positive value to rotate the text label (in 90 degree increments). *states*: ++ typeof: object ++ A number of disk utilization states that get activated on certain percentage thresholds (percentage_used). See *waybar-states(5)*. *max-length*: ++ typeof: integer ++ The maximum length in character the module should display. *min-length*: ++ typeof: integer ++ The minimum length in characters the module should accept. *align*: ++ typeof: float ++ The alignment of the label within the module, where 0 is left-aligned and 1 is right-aligned. If the module is rotated, it will follow the flow of the text. *justify*: ++ typeof: string ++ The alignment of the text within the module's label, allowing options 'left', 'right', or 'center' to define the positioning. *on-click*: ++ typeof: string ++ Command to execute when clicked on the module. *on-click-middle*: ++ typeof: string ++ Command to execute when middle-clicked on the module using mousewheel. *on-click-right*: ++ typeof: string ++ Command to execute when you right-click on the module. *on-update*: ++ typeof: string ++ Command to execute when the module is updated. *on-scroll-up*: ++ typeof: string ++ Command to execute when scrolling up on the module. *on-scroll-down*: ++ typeof: string ++ Command to execute when scrolling down on the module. *smooth-scrolling-threshold*: ++ typeof: double ++ Threshold to be used when scrolling. *tooltip*: ++ typeof: bool ++ default: true ++ Option to disable tooltip on hover. *tooltip-format*: ++ typeof: string ++ default: "{used} out of {total} used ({percentage_used}%)" ++ The format of the information displayed in the tooltip. *unit*: ++ typeof: string ++ Use with specific_free, specific_used, and specific_total to force calculation to always be in a certain unit. Accepts kB, kiB, MB, Mib, GB, GiB, TB, TiB. *menu*: ++ typeof: string ++ Action that popups the menu. *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # FORMAT REPLACEMENTS *{percentage_used}*: Percentage of disk in use. *{percentage_free}*: Percentage of free disk space *{total}*: Total amount of space on the disk, partition, or mountpoint. Automatically selects unit based on size remaining. *{used}*: Amount of used disk space. Automatically selects unit based on size remaining. *{free}*: Amount of available disk space for normal users. Automatically selects unit based on size remaining. *{path}*: The path specified in the configuration. *{specific_total}*: Total amount of space on the disk, partition, or mountpoint in a specific unit. Defaults to bytes. *{specific_used}*: Amount of used disk space in a specific unit. Defaults to bytes. *{specific_free}*: Amount of available disk space for normal users in a specific unit. Defaults to bytes. # EXAMPLES ``` "disk": { "interval": 30, "format": "{percentage_free}% free on {path}", } ``` ``` "disk": { "interval": 30, "format": "{specific_free:0.2f} GB out of {specific_total:0.2f} GB available. Alternatively {free} out of {total} available", "unit": "GB" // 1434.25 GB out of 2000.00 GB available. Alternatively 1.4TiB out of 1.9TiB available. } ``` # STYLE - *#disk* waybar-0.12.0/man/waybar-dwl-tags.5.scd000066400000000000000000000016741475603165300175170ustar00rootroot00000000000000waybar-dwl-tags(5) # NAME waybar - dwl tags module # DESCRIPTION The *tags* module displays the current state of tags in dwl. # CONFIGURATION Addressed by *dwl/tags* *num-tags*: ++ typeof: uint ++ default: 9 ++ The number of tags that should be displayed. Max 32. *tag-labels*: ++ typeof: array ++ The label to display for each tag. *disable-click*: ++ typeof: bool ++ default: false ++ If set to false, you can left-click to set focused tag. Right-click to toggle tag focus. If set to true this behaviour is disabled. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # EXAMPLE ``` "dwl/tags": { "num-tags": 5 } ``` # STYLE - *#tags button* - *#tags button.occupied* - *#tags button.focused* - *#tags button.urgent* Note that occupied/focused/urgent status may overlap. That is, a tag may be both occupied and focused at the same time. # SEE ALSO waybar(5), dwl(1) waybar-0.12.0/man/waybar-dwl-window.5.scd000066400000000000000000000053551475603165300200700ustar00rootroot00000000000000waybar-dwl-window(5) # NAME waybar - dwl window module # DESCRIPTION The *window* module displays the title of the currently focused window in DWL # CONFIGURATION Addressed by *dwl/window* *format*: ++ typeof: string ++ default: {title} ++ The format, how information should be displayed. *rotate*: ++ typeof: integer ++ Positive value to rotate the text label (in 90 degree increments). *max-length*: ++ typeof: integer ++ The maximum length in character the module should display. *min-length*: ++ typeof: integer ++ The minimum length in characters the module should accept. *align*: ++ typeof: float ++ The alignment of the label within the module, where 0 is left-aligned and 1 is right-aligned. If the module is rotated, it will follow the flow of the text. *justify*: ++ typeof: string ++ The alignment of the text within the module's label, allowing options 'left', 'right', or 'center' to define the positioning. *on-click*: ++ typeof: string ++ Command to execute when clicked on the module. *on-click-middle*: ++ typeof: string ++ Command to execute when middle-clicked on the module using mousewheel. *on-click-right*: ++ typeof: string ++ Command to execute when you right-click on the module. *on-update*: ++ typeof: string ++ Command to execute when the module is updated. *on-scroll-up*: ++ typeof: string ++ Command to execute when scrolling up on the module. *on-scroll-down*: ++ typeof: string ++ Command to execute when scrolling down on the module. *smooth-scrolling-threshold*: ++ typeof: double ++ Threshold to be used when scrolling. *tooltip*: ++ typeof: bool ++ default: true ++ Option to disable tooltip on hover. *rewrite*: ++ typeof: object ++ Rules to rewrite the module format output. 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 *{title}*: The title of the focused window. *{app_id}*: The app_id of the focused window. *{layout}*: The layout 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 format output is left unchanged. Invalid expressions (e.g., mismatched parentheses) are skipped. # EXAMPLES ``` "dwl/window": { "format": "{}", "max-length": 50, "rewrite": { "(.*) - Mozilla Firefox": "🌎 $1", "(.*) - zsh": "> [$1]" } } ``` waybar-0.12.0/man/waybar-gamemode.5.scd000066400000000000000000000037031475603165300175460ustar00rootroot00000000000000waybar-gamemode(5) # NAME waybar - gamemode module # DESCRIPTION The *gamemode* module displays if any game or application is running with ++ Feral Gamemode optimizations. # CONFIGURATION *format*: ++ typeof: string ++ default: {glyph} ++ The text format. *format-alt*: ++ typeof: string ++ default: {glyph} {count} ++ The text format when toggled. *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. *hide-not-running*: ++ typeof: bool ++ default: true ++ Defines if the module should be hidden if no games are running. *use-icon*: ++ typeof: bool ++ default: true ++ Defines if the module should display a GTK icon instead of the specified *glyph* *glyph*: ++ typeof: string ++ default:  ++ The string icon to display. Only visible if *use-icon* is set to false. *icon-name*: ++ typeof: string ++ default: input-gaming-symbolic ++ The GTK icon to display. Only visible if *use-icon* is set to true. *icon-size*: ++ typeof: unsigned integer ++ default: 20 ++ Defines the size of the icons. *icon-spacing*: ++ typeof: unsigned integer ++ default: 4 ++ Defines the spacing between the icon and the text. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # FORMAT REPLACEMENTS *{glyph}*: The string icon glyph to use instead. *{count}*: The number of games running with gamemode optimizations. # TOOLTIP FORMAT REPLACEMENTS *{count}*: The number of games running with gamemode optimizations. # EXAMPLES ``` "gamemode": { "format": "{glyph}", "format-alt": "{glyph} {count}", "glyph": "", "hide-not-running": true, "use-icon": true, "icon-name": "input-gaming-symbolic", "icon-spacing": 4, "icon-size": 20, "tooltip": true, "tooltip-format": "Games running: {count}" } ``` # STYLE - *#gamemode* - *#gamemode.running* waybar-0.12.0/man/waybar-hyprland-language.5.scd000066400000000000000000000030451475603165300213710ustar00rootroot00000000000000waybar-hyprland-language(5) # NAME waybar - hyprland language module # DESCRIPTION The *language* module displays the currently selected language. # CONFIGURATION Addressed by *hyprland/language* *format*: ++ typeof: string ++ default: {} ++ The format, how information should be displayed. *format-* ++ typeof: string++ Provide an alternative name to display per language where is the language of your choosing. Can be passed multiple times with multiple languages as shown by the example below. *keyboard-name*: ++ typeof: string ++ Specifies which keyboard to use from hyprctl devices output. Using the option that begins with "at-translated-set..." is recommended. *menu*: ++ typeof: string ++ Action that popups the menu. *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # FORMAT REPLACEMENTS *{short}*: Short name of layout (e.g. "us"). Equals to {}. *{shortDescription}*: Short description of layout (e.g. "en"). *{long}*: Long name of layout (e.g. "English (Dvorak)"). *{variant}*: Variant of layout (e.g. "dvorak"). # EXAMPLES ``` "hyprland/language": { "format": "Lang: {long}", "format-en": "AMERICA, HELL YEAH!", "format-tr": "As bayrakları", "keyboard-name": "at-translated-set-2-keyboard" } ``` # STYLE - *#language* waybar-0.12.0/man/waybar-hyprland-submap.5.scd000066400000000000000000000047721475603165300211050ustar00rootroot00000000000000waybar-hyprland-submap(5) # NAME waybar - hyprland submap module # DESCRIPTION The *submap* module displays the currently active submap similar to *sway/mode*. # CONFIGURATION Addressed by *hyprland/submap* *format*: ++ typeof: string ++ default: {} ++ The format, how information should be displayed. On {} the currently active submap is displayed. *rotate*: ++ typeof: integer ++ Positive value to rotate the text label (in 90 degree increments). *max-length*: ++ typeof: integer ++ The maximum length in character the module should display. *min-length*: ++ typeof: integer ++ The minimum length in characters the module should accept. *align*: ++ typeof: float ++ The alignment of the label within the module, where 0 is left-aligned and 1 is right-aligned. If the module is rotated, it will follow the flow of the text. *justify*: ++ typeof: string ++ The alignment of the text within the module's label, allowing options 'left', 'right', or 'center' to define the positioning. *on-click*: ++ typeof: string ++ Command to execute when clicked on the module. *on-click-middle*: ++ typeof: string ++ Command to execute when middle-clicked on the module using mousewheel. *on-click-right*: ++ typeof: string ++ Command to execute when you right-click on the module. *on-update*: ++ typeof: string ++ Command to execute when the module is updated. *on-scroll-up*: ++ typeof: string ++ Command to execute when scrolling up on the module. *on-scroll-down*: ++ typeof: string ++ Command to execute when scrolling down on the module. *smooth-scrolling-threshold*: ++ typeof: double ++ Threshold to be used when scrolling. *tooltip*: ++ typeof: bool ++ default: true ++ Option to disable tooltip on hover. *always-on*: ++ typeof: bool ++ default: false ++ Option to display the widget even when there's no active submap. *default-submap* ++ typeof: string ++ default: Default ++ Option to set the submap name to display when not in an active submap. *menu*: ++ typeof: string ++ Action that popups the menu. *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # EXAMPLES ``` "hyprland/submap": { "format": "✌️ {}", "max-length": 8, "tooltip": false } ``` # STYLE - *#submap* - *#submap.* waybar-0.12.0/man/waybar-hyprland-window.5.scd000066400000000000000000000047111475603165300211160ustar00rootroot00000000000000waybar-hyprland-window(5) # NAME waybar - hyprland window module # DESCRIPTION The *window* module displays the title of the currently focused window in Hyprland. # CONFIGURATION Addressed by *hyprland/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*. *separate-outputs*: ++ typeof: bool ++ Show the active window of the monitor the bar belongs to, instead of the focused window. *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 "hyprctl clients" for examples *{title}*: The current title of the focused window. *{initialTitle}*: The initial title of the focused window. *{class}*: The current class of the focused window. *{initialClass}*: The initial class 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 ``` "hyprland/window": { "format": "{}", "rewrite": { "(.*) - Mozilla Firefox": "🌎 $1", "(.*) - zsh": "> [$1]" } } ``` # STYLE - *#window* - *window#waybar.empty #window* When no windows are in 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 one tiled window is visible in the workspace (floating windows may be present) - *window#waybar.* Where ** is the *class* (e.g. *chromium*) of the solo tiled window in the workspace (use *hyprctl clients* to see classes) - *window#waybar.floating* When there are only floating windows in the workspace - *window#waybar.fullscreen* When there is a fullscreen window in the workspace; useful with Hyprland's *fullscreen, 1* mode - *window#waybar.swallowing* When there is a swallowed window in the workspace waybar-0.12.0/man/waybar-hyprland-workspaces.5.scd000066400000000000000000000126621475603165300217740ustar00rootroot00000000000000waybar-hyprland-workspaces(5) # NAME waybar - hyprland workspaces module # DESCRIPTION The *workspaces* module displays the currently used workspaces in hyprland compositor. # CONFIGURATION Addressed by *hyprland/workspaces* *format*: ++ typeof: string ++ default: {id} ++ The format, how information should be displayed. *format-icons*: ++ typeof: array ++ Based on the workspace ID and state, the corresponding icon gets selected. See *icons*. *window-rewrite*: ++ typeof: object ++ 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. *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*. *format-window-separator*: ++ typeof: string ++ default: " " ++ The separator to be used between windows in a workspace. *show-special*: ++ typeof: bool ++ default: false ++ If set to true, special workspaces will be shown. *special-visible-only*: ++ typeof: bool ++ default: false ++ If this and show-special are to true, special workspaces will be shown only if visible. *all-outputs*: ++ typeof: bool ++ default: false ++ If set to false workspaces group will be shown only in assigned output. Otherwise, all workspace groups are shown. *active-only*: ++ typeof: bool ++ default: false ++ If set to true, only the active workspace will be shown. *move-to-monitor*: ++ typeof: bool ++ default: false ++ If set to true, open the workspace on the current monitor when clicking on a workspace button. Otherwise, the workspace will open on the monitor where it was previously assigned. Analog to using `focusworkspaceoncurrentmonitor` dispatcher instead of `workspace` in Hyprland. *ignore-workspaces*: ++ typeof: array ++ default: [] ++ Regexes to match against workspaces names. If there's a match, the workspace will not be shown. This takes precedence over *show-special*, *all-outputs*, and *active-only*. *sort-by*: ++ typeof: string ++ default: "default" ++ 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 none of those, workspaces will sort with default behavior. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # FORMAT REPLACEMENTS *{id}*: id of workspace assigned by compositor *{name}*: workspace name assigned by compositor *{icon}*: Icon, as defined in *format-icons*. # ICONS Additional to workspace name matching, the following *format-icons* can be set. - *default*: Will be shown, when no string match is found and none of the below conditions have defined icons. - *active*: Will be shown, when workspace is active - *special*: Will be shown on non-active special workspaces - *empty*: Will be shown on non-active, non-special empty persistent workspaces - *visible*: Will be shown on workspaces that are visible but not active. For example: this is useful if you want your visible workspaces on other monitors to have the same look as active. - *persistent*: Will be shown on non-empty persistent workspaces # EXAMPLES ``` "hyprland/workspaces": { "format": "{name}: {icon}", "format-icons": { "1": "", "2": "", "3": "", "4": "", "5": "", "active": "", "default": "" }, "persistent-workspaces": { "*": 5, // 5 workspaces by default on every monitor "HDMI-A-1": 3 // but only three on HDMI-A-1 } } ``` ``` "hyprland/workspaces": { "format": "{name}: {icon}", "format-icons": { "1": "", "2": "", "3": "", "4": "", "5": "", "active": "", "default": "" }, "persistent-workspaces": { "*": [ 2,3,4,5 ], // 2-5 on every monitor "HDMI-A-1": [ 1 ] // but only workspace 1 on HDMI-A-1 } } ``` ``` "hyprland/workspaces": { "format": "{name}\n{windows}", "format-window-separator": "\n", "window-rewrite-default": "", "window-rewrite": { "title<.*youtube.*>": "", // Windows whose titles contain "youtube" "class": "", // Windows whose classes are "firefox" "class title<.*github.*>": "", // Windows whose class is "firefox" and title contains "github". Note that "class" always comes first. "foot": "", // Windows that contain "foot" in either class or title. For optimization reasons, it will only match against a title if at least one other window explicitly matches against a title. "code": "󰨞", "title<.* - (.*) - VSCodium>": "codium $1" // captures part of the window title and formats it into output } } ``` ``` "hyprland/workspaces": { // Formatting omitted for brevity "ignore-workspaces": [ "(special:)?chrome-sharing-indicator" ] } ``` # Style - *#workspaces* - *#workspaces button* - *#workspaces button.active* - *#workspaces button.empty* - *#workspaces button.visible* - *#workspaces button.persistent* - *#workspaces button.special* - *#workspaces button.urgent* - *#workspaces button.hosting-monitor* (gets applied if workspace-monitor == waybar-monitor) waybar-0.12.0/man/waybar-idle-inhibitor.5.scd000066400000000000000000000056251475603165300206770ustar00rootroot00000000000000waybar-idle-inhibitor(5) # NAME waybar - idle_inhibitor module # DESCRIPTION The *idle_inhibitor* module can inhibit the idle behavior such as screen blanking, locking, and screensaver, also known as "presentation mode". # CONFIGURATION *format*: ++ typeof: string ++ The format, how the state should be displayed. *format-icons*: ++ typeof: array ++ Based on the current state, the corresponding icon gets selected. *rotate*: ++ typeof: integer ++ Positive value to rotate the text label (in 90 degree increments). *max-length*: ++ typeof: integer ++ The maximum length in character the module should display. *min-length*: ++ typeof: integer ++ The minimum length in characters the module should accept. *align*: ++ typeof: float ++ The alignment of the label within the module, where 0 is left-aligned and 1 is right-aligned. If the module is rotated, it will follow the flow of the text. *justify*: ++ typeof: string ++ The alignment of the text within the module's label, allowing options 'left', 'right', or 'center' to define the positioning. *on-click*: ++ typeof: string ++ Command to execute when clicked on the module. A click also toggles the state *on-click-middle*: ++ typeof: string ++ Command to execute when middle-clicked on the module using mousewheel. *on-click-right*: ++ typeof: string ++ Command to execute when you right-click on the module. *on-update*: ++ typeof: string ++ Command to execute when the module is updated. *on-scroll-up*: ++ typeof: string ++ Command to execute when scrolling up on the module. *on-scroll-down*: ++ typeof: string ++ Command to execute when scrolling down on the module. *smooth-scrolling-threshold*: ++ typeof: double ++ Threshold to be used when scrolling. *start-activated*: ++ typeof: bool ++ default: *false* ++ Whether the inhibit should be activated when starting waybar. *timeout*: ++ typeof: double ++ The number of minutes the inhibition should last. *tooltip*: ++ typeof: bool ++ default: true ++ Option to disable tooltip on hover. *tooltip-format-activated*: ++ typeof: string ++ This format is used when the inhibit is activated. *tooltip-format-deactivated*: ++ typeof: string ++ This format is used when the inhibit is deactivated. *menu*: ++ typeof: string ++ Action that popups the menu. Cannot be "on-click". *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # FORMAT REPLACEMENTS *{status}*: status (*activated* or *deactivated*) *{icon}*: Icon, as defined in *format-icons* # EXAMPLES ``` "idle_inhibitor": { "format": "{icon}", "format-icons": { "activated": "", "deactivated": "" }, "timeout": 30.5 } ``` waybar-0.12.0/man/waybar-image.5.scd000066400000000000000000000036071475603165300170550ustar00rootroot00000000000000waybar-image(5) # NAME waybar - image module # DESCRIPTION The *image* module displays an image from a path. # CONFIGURATION *path*: ++ typeof: string ++ The path to the image. *exec*: ++ typeof: string ++ The path to the script, which should return image path file. ++ It will only execute if the path is not set *size*: ++ typeof: integer ++ The width/height to render the image. *interval*: ++ typeof: integer ++ The interval (in seconds) to re-render the image. ++ This is useful if the contents of *path* changes. ++ If no *interval* is defined, the image will only be rendered once. *signal*: ++ typeof: integer ++ The signal number used to update the module. ++ This can be used instead of *interval* if the file changes irregularly. ++ The number is valid between 1 and N, where *SIGRTMIN+N* = *SIGRTMAX*. *on-click*: ++ typeof: string ++ Command to execute when clicked on the module. *on-click-middle*: ++ typeof: string ++ Command to execute when middle-clicked on the module using mousewheel. *on-update*: ++ typeof: string ++ Command to execute when the module is updated. *on-scroll-up*: ++ typeof: string ++ Command to execute when scrolling up on the module. *on-scroll-down*: ++ typeof: string ++ Command to execute when scrolling down on the module. *smooth-scrolling-threshold*: ++ typeof: double ++ Threshold to be used when scrolling. *tooltip*: ++ typeof: bool ++ default: true ++ Option to enable tooltip on hover. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # SCRIPT OUTPUT Similar to the *custom* module, output values of the script are *newline* separated. The following is the output format: ``` $path\\n$tooltip ``` # EXAMPLES ``` "image#album-art": { "path": "/tmp/mpd_art", "size": 32, "interval": 5, "on-click": "mpc toggle" } ``` # STYLE - *#image* - *#image.empty* waybar-0.12.0/man/waybar-inhibitor.5.scd000066400000000000000000000053401475603165300177560ustar00rootroot00000000000000waybar-inhibitor(5) # NAME waybar - inhibitor module # DESCRIPTION The *inhibitor* module allows one to take an inhibitor lock that logind provides. See *systemd-inhibit*(1) for more information. # CONFIGURATION *what*: ++ typeof: string or array ++ The inhibitor lock or locks that should be taken when active. The available inhibitor locks are *idle*, *shutdown*, *sleep*, *handle-power-key*, *handle-suspend-key*, *handle-hibernate-key* and *handle-lid-switch*. *format*: ++ typeof: string ++ The format, how the state should be displayed. *format-icons*: ++ typeof: array ++ Based on the current state, the corresponding icon gets selected. *rotate*: ++ typeof: integer ++ Positive value to rotate the text label (in 90 degree increments). *max-length*: ++ typeof: integer ++ The maximum length in character the module should display. *min-length*: ++ typeof: integer ++ The minimum length in characters the module should accept. *align*: ++ typeof: float ++ The alignment of the label within the module, where 0 is left-aligned and 1 is right-aligned. If the module is rotated, it will follow the flow of the text. *justify*: ++ typeof: string ++ The alignment of the text within the module's label, allowing options 'left', 'right', or 'center' to define the positioning. *on-click*: ++ typeof: string ++ Command to execute when clicked on the module. A click also toggles the state *on-click-middle*: ++ typeof: string ++ Command to execute when middle-clicked on the module using mousewheel. *on-click-right*: ++ typeof: string ++ Command to execute when you right-click on the module. *on-update*: ++ typeof: string ++ Command to execute when the module is updated. *on-scroll-up*: ++ typeof: string ++ Command to execute when scrolling up on the module. *on-scroll-down*: ++ typeof: string ++ Command to execute when scrolling down on the module. *smooth-scrolling-threshold*: ++ typeof: double ++ Threshold to be used when scrolling. *tooltip*: ++ typeof: bool ++ default: true ++ Option to disable tooltip on hover. *menu*: ++ typeof: string ++ Action that popups the menu. Cannot be "on-click". *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # FORMAT REPLACEMENTS *{status}*: status (*activated* or *deactivated*) *{icon}*: Icon, as defined in *format-icons* # EXAMPLES ``` "inhibitor": { "what": "handle-lid-switch", "format": "{icon}", "format-icons": { "activated": "", "deactivated": "" } } ``` waybar-0.12.0/man/waybar-jack.5.scd000066400000000000000000000060701475603165300167000ustar00rootroot00000000000000waybar-jack(5) # NAME waybar - JACK module # DESCRIPTION The *jack* module displays the current state of the JACK server. # CONFIGURATION Addressed by *jack* *format*: ++ typeof: string ++ default: *{load}%* ++ The format, how information should be displayed. This format is used when other formats aren't specified. *format-connected*: ++ typeof: string ++ This format is used when the module is connected to the JACK server. *format-disconnected*: ++ typeof: string ++ This format is used when the module is not connected to the JACK server. *format-xrun*: ++ typeof: string ++ This format is used for one polling interval when the JACK server reports an xrun. *realtime*: ++ typeof: bool ++ default: *true* ++ Option to drop real-time privileges for the JACK client opened by Waybar. *tooltip*: ++ typeof: bool ++ default: *true* ++ Option to disable tooltip on hover. *tooltip-format*: ++ typeof: string ++ default: *{bufsize}/{samplerate} {latency}ms* ++ The format of information displayed in the tooltip. *interval*: ++ typeof: integer ++ default: 1 ++ The interval in which the information gets polled. *rotate*: ++ typeof: integer ++ Positive value to rotate the text label (in 90 degree increments). *max-length*: ++ typeof: integer ++ The maximum length in character the module should display. *min-length*: ++ typeof: integer ++ The minimum length in characters the module should accept. *align*: ++ typeof: float ++ The alignment of the label within the module, where 0 is left-aligned and 1 is right-aligned. If the module is rotated, it will follow the flow of the text. *justify*: ++ typeof: string ++ The alignment of the text within the module's label, allowing options 'left', 'right', or 'center' to define the positioning. *on-click*: ++ typeof: string ++ Command to execute when clicked on the module. *on-click-middle*: ++ typeof: string ++ Command to execute when middle-clicked on the module using mousewheel. *on-click-right*: ++ typeof: string ++ Command to execute when you right-click on the module. *on-update*: ++ typeof: string ++ Command to execute when the module is updated. *menu*: ++ typeof: string ++ Action that popups the menu. *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # FORMAT REPLACEMENTS *{load}*: The current CPU load estimated by JACK. *{bufsize}*: The size of the JACK buffer. *{samplerate}*: The sample rate at which the JACK server is running. *{latency}*: The duration, in ms, of the current buffer size. *{xruns}*: The number of xruns reported by the JACK server since starting Waybar. # EXAMPLES ``` "jack": { "format": "DSP {}%", "format-xrun": "{xruns} xruns", "format-disconnected": "DSP off", "realtime": true } ``` # STYLE - *#jack* - *#jack.connected* - *#jack.disconnected* - *#jack.xrun* waybar-0.12.0/man/waybar-keyboard-state.5.scd000066400000000000000000000052661475603165300207140ustar00rootroot00000000000000waybar-keyboard-state(5) # NAME waybar - keyboard-state module # DESCRIPTION The *keyboard-state* module displays the state of number lock, caps lock, and scroll lock. You must be a member of the input group to use this module. # CONFIGURATION *interval*: ++ Deprecated, this module uses event loop now, the interval has no effect. typeof: integer ++ default: 1 ++ The interval, in seconds, to poll the keyboard state. *format*: ++ typeof: string|object ++ default: {name} {icon} ++ The format, how information should be displayed. If a string, the same format is used for all keyboard states. If an object, the fields "numlock", "capslock", and "scrolllock" each specify the format for the corresponding state. Any unspecified states use the default format. *format-icons*: ++ typeof: object ++ default: {"locked": "locked", "unlocked": "unlocked"} ++ Based on the keyboard state, the corresponding icon gets selected. The same set of icons is used for number, caps, and scroll lock, but the icon is selected from the set independently for each. See *icons*. *numlock*: ++ typeof: bool ++ default: false ++ Display the number lock state. *capslock*: ++ typeof: bool ++ default: false ++ Display the caps lock state. *scrolllock*: ++ typeof: bool ++ default: false ++ Display the scroll lock state. *device-path*: ++ typeof: string ++ default: chooses first valid input device ++ Which libevdev input device to show the state of. Libevdev devices can be found in /dev/input. The device should support number lock, caps lock, and scroll lock events. *binding-keys*: ++ typeof: array ++ default: [58, 69, 70] ++ Customize the key to trigger this module, the key number can be found in /usr/include/linux/input-event-codes.h or running sudo libinput debug-events --show-keycodes. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # FORMAT REPLACEMENTS *{name}*: Caps, Num, or Scroll. *{icon}*: Icon, as defined in *format-icons*. # ICONS The following *format-icons* can be set. - *locked*: Will be shown when the keyboard state is locked. Default "locked". - *unlocked*: Will be shown when the keyboard state is not locked. Default "unlocked" # EXAMPLE: ``` "keyboard-state": { "numlock": true, "capslock": true, "format": "{name} {icon}", "format-icons": { "locked": "", "unlocked": "" } } ``` # STYLE - *#keyboard-state* - *#keyboard-state label* - *#keyboard-state label.locked* - *#keyboard-state label.numlock* - *#keyboard-state label.numlock.locked* - *#keyboard-state label.capslock* - *#keyboard-state label.capslock.locked* - *#keyboard-state label.scrolllock* - *#keyboard-state label.scrolllock.locked* waybar-0.12.0/man/waybar-memory.5.scd000066400000000000000000000061071475603165300173010ustar00rootroot00000000000000waybar-memory(5) # NAME waybar - memory module # DESCRIPTION The *memory* module displays the current memory utilization. # CONFIGURATION Addressed by *memory* *interval*: ++ typeof: integer++ default: 30 ++ The interval in which the information gets polled. *format*: ++ typeof: string ++ default: {percentage}% ++ The format, how information should be displayed. *format-icons*: ++ typeof: array/object ++ Based on the current percentage, the corresponding icon gets selected. ++ The order is *low* to *high*. Or by the state if it is an object. *rotate*: ++ typeof: integer ++ Positive value to rotate the text label (in 90 degree increments). *states*: ++ typeof: object ++ A number of memory utilization states which get activated on certain percentage thresholds. See *waybar-states(5)*. *max-length*: ++ typeof: integer ++ The maximum length in character the module should display. *min-length*: ++ typeof: integer ++ The minimum length in characters the module should accept. *align*: ++ typeof: float ++ The alignment of the label within the module, where 0 is left-aligned and 1 is right-aligned. If the module is rotated, it will follow the flow of the text. *justify*: ++ typeof: string ++ The alignment of the text within the module's label, allowing options 'left', 'right', or 'center' to define the positioning. *on-click*: ++ typeof: string ++ Command to execute when clicked on the module. *on-click-middle*: ++ typeof: string ++ Command to execute when middle-clicked on the module using mousewheel. *on-click-right*: ++ typeof: string ++ Command to execute when you right-click on the module. *on-update*: ++ typeof: string ++ Command to execute when the module is updated. *on-scroll-up*: ++ typeof: string ++ Command to execute when scrolling up on the module. *on-scroll-down*: ++ typeof: string ++ Command to execute when scrolling down on the module. *smooth-scrolling-threshold*: ++ typeof: double ++ Threshold to be used when scrolling. *tooltip*: ++ typeof: bool ++ default: true ++ Option to disable tooltip on hover. *menu*: ++ typeof: string ++ Action that popups the menu. *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # FORMAT REPLACEMENTS *{percentage}*: Percentage of memory in use. *{swapPercentage}*: Percentage of swap in use. *{total}*: Amount of total memory available in GiB. *{swapTotal}*: Amount of total swap available in GiB. *{used}*: Amount of used memory in GiB. *{swapUsed}*: Amount of used swap in GiB. *{avail}*: Amount of available memory in GiB. *{swapAvail}*: Amount of available swap in GiB. # EXAMPLES ``` "memory": { "interval": 30, "format": "{}% ", "max-length": 10 } ``` ## FORMATTED MEMORY VALUES ``` "memory": { "interval": 30, "format": "{used:0.1f}G/{total:0.1f}G " } ``` # STYLE - *#memory* waybar-0.12.0/man/waybar-menu.5.scd000066400000000000000000000075141475603165300167400ustar00rootroot00000000000000waybar-menu(5) # NAME waybar - menu property # OVERVIEW Some modules support a 'menu', which allows to have a popup menu whan a defined click is done over the module. # PROPERTIES A module that implements a 'menu' needs 3 properties defined in its config : *menu*: ++ typeof: string ++ Action that popups the menu. The possibles actions are : [- *Option* :- *Description* |[ *on-click* :< When you left-click on the module |[ *on-click-release* :< When you release left button on the module |[ *on-double-click* :< When you double left click on the module |[ *on-triple-click* :< When you triple left click on the module |[ *on-click-middle* :< When you middle click on the module using mousewheel |[ *on-click-middle-release* :< When you release mousewheel button on the module |[ *on-double-click-middle* :< When you double middle click on the module |[ *on-triple-click-middle* :< When you triple middle click on the module |[ *on-click-right* :< When you right click on the module using |[ *on-click-right-release* :< When you release right button on the module |[ *on-double-click-right* :< When you double right click on the module |[ *on-triple-click-right* :< When you triple middle click on the module |[ *on-click-backward* :< When you click on the module using mouse backward button |[ *on-click-backward-release* :< When you release mouse backward button on the module |[ *on-double-click-backward* :< When you double click on the module using mouse backward button |[ *on-triple-click-backward* :< When you triple click on the module using mouse backawrd button |[ *on-click-forward* :< When you click on the module using mouse forward button |[ *on-click-forward-release* :< When you release mouse forward button on the module |[ *on-double-click-forward* :< When you double click on the module using mouse forward button |[ *on-triple-click-forward* :< When you triple click on the module using mouse forward button *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu*. *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. The identifiers of each actions needs to exists as an id in the 'menu-file' for it to be linked properly. # MENU-FILE The menu-file is an `.xml` file representing a GtkBuilder. Documentation for it can be found here : https://docs.gtk.org/gtk4/class.Builder.html Here, it needs to have an element of type GtkMenu with id "menu". Eeach actions in *menu-actions* are linked to elements in the *menu-file* file by the id of the elements. # EXAMPLE 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", }, }, ``` ~/.config/waybar/power_menu.xml : ``` Suspend Hibernate Shutdown Reboot ``` # STYLING MENUS - *menu* Style for the menu - *menuitem* Style for items in the menu # EXAMPLE: ``` menu { border-radius: 15px; background: #161320; color: #B5E8E0; } menuitem { border-radius: 15px; } ``` waybar-0.12.0/man/waybar-mpd.5.scd000066400000000000000000000153341475603165300165530ustar00rootroot00000000000000waybar-mpd(5) # NAME waybar - mpd module # DESCRIPTION The *mpd* module displays information about a running "Music Player Daemon" instance. # CONFIGURATION Addressed by *mpd* *server*: ++ typeof: string ++ The network address or Unix socket path of the MPD server. If empty, connect to the default host. *port*: ++ typeof: integer ++ The port MPD listens to. If empty, use the default port. *password*: ++ typeof: string ++ The password required to connect to the MPD server. If empty, no password is sent to MPD. *interval*: ++ typeof: integer++ default: 5 ++ The interval in which the connection to the MPD server is retried *timeout*: ++ typeof: integer++ default: 30 ++ The timeout for the connection. Change this if your MPD server has a low `connection_timeout` setting *unknown-tag*: ++ typeof: string ++ default: "N/A" ++ The text to display when a tag is not present in the current song, but used in `format` *format*: ++ typeof: string ++ default: "{album} - {artist} - {title}" ++ Information displayed when a song is playing. *format-stopped*: ++ typeof: string ++ default: "stopped" ++ Information displayed when the player is stopped. *format-paused*: ++ typeof: string ++ This format is used when a song is paused. *format-disconnected*: ++ typeof: string ++ default: "disconnected" ++ Information displayed when the MPD server can't be reached. *tooltip*: ++ typeof: bool ++ default: true ++ Option to disable tooltip on hover. *tooltip-format*: ++ typeof: string ++ default: "MPD (connected)" ++ Tooltip information displayed when connected to MPD. *tooltip-format-disconnected*: ++ typeof: string ++ default: "MPD (disconnected)" ++ Tooltip information displayed when the MPD server can't be reached. *artist-len*: ++ typeof: integer ++ Maximum length of the Artist tag. *album-len*: ++ typeof: integer ++ Maximum length of the Album tag. *album-artist-len*: ++ typeof: integer ++ Maximum length of the Album Artist tag. *title-len*: ++ typeof: integer ++ Maximum length of the Title tag. *rotate*: ++ typeof: integer ++ Positive value to rotate the text label (in 90 degree increments). *max-length*: ++ typeof: integer ++ The maximum length in character the module should display. *min-length*: ++ typeof: integer ++ The minimum length in characters the module should accept. *align*: ++ typeof: float ++ The alignment of the label within the module, where 0 is left-aligned and 1 is right-aligned. If the module is rotated, it will follow the flow of the text. *justify*: ++ typeof: string ++ The alignment of the text within the module's label, allowing options 'left', 'right', or 'center' to define the positioning. *on-click*: ++ typeof: string ++ Command to execute when clicked on the module. *on-click-middle*: ++ typeof: string ++ Command to execute when middle-clicked on the module using mousewheel. *on-click-right*: ++ typeof: string ++ Command to execute when you right-click on the module. *on-update*: ++ typeof: string ++ Command to execute when the module is updated. *on-scroll-up*: ++ typeof: string ++ Command to execute when scrolling up on the module. *on-scroll-down*: ++ typeof: string ++ Command to execute when scrolling down on the module. *smooth-scrolling-threshold*: ++ typeof: double ++ Threshold to be used when scrolling. *state-icons*: ++ typeof: object ++ default: {} ++ Icon to show depending on the play/pause state of the player (*{ "playing": "...", "paused": "..." }*) *consume-icons*: ++ typeof: object ++ default: {} ++ Icon to show depending on the "consume" option (*{ "on": "...", "off": "..." }*) *random-icons*: ++ typeof: object ++ default: {} ++ Icon to show depending on the "random" option (*{ "on": "...", "off": "..." }*) *repeat-icons*: ++ typeof: object ++ default: {} ++ Icon to show depending on the "repeat" option (*{ "on": "...", "off": "..." }*) *single-icons*: ++ typeof: object ++ default: {} ++ Icon to show depending on the "single" option (*{ "on": "...", "off": "..." }*) *menu*: ++ typeof: string ++ Action that popups the menu. *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # FORMAT REPLACEMENTS ## WHEN PLAYING/PAUSED *{artist}*: The artist of the current song *{albumArtist}*: The artist of the current album *{album}*: The album of the current song *{title}*: The title of the current song *{date}*: The date of the current song *{volume}*: The current volume in percent *{elapsedTime}*: The current position of the current song. To format as a date/time (see example configuration) *{totalTime}*: The length of the current song. To format as a date/time (see example configuration) *{songPosition}*: The position of the current song. *{queueLength}*: The length of the current queue. *{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) *{randomIcon}*: The icon corresponding the "random" option (see *random-icons* option) *{repeatIcon}*: The icon corresponding the "repeat" option (see *repeat-icons* option) *{singleIcon}*: The icon corresponding the "single" option (see *single-icons* option) ## WHEN STOPPED *{consumeIcon}*: The icon corresponding the "consume" option (see *consume-icons* option) *{randomIcon}*: The icon corresponding the "random" option (see *random-icons* option) *{repeatIcon}*: The icon corresponding the "repeat" option (see *repeat-icons* option) *{singleIcon}*: The icon corresponding the "single" option (see *single-icons* option) ## WHEN DISCONNECTED Currently, no format replacements when disconnected. # EXAMPLES ``` "mpd": { "format": "{stateIcon} {consumeIcon}{randomIcon}{repeatIcon}{singleIcon}{artist} - {album} - {title} ({elapsedTime:%M:%S}/{totalTime:%M:%S}) ", "format-disconnected": "Disconnected ", "format-stopped": "{consumeIcon}{randomIcon}{repeatIcon}{singleIcon}Stopped ", "interval": 2, "consume-icons": { "on": " " // Icon shows only when "consume" is on }, "random-icons": { "off": " ", // Icon grayed out when "random" is off "on": " " }, "repeat-icons": { "on": " " }, "single-icons": { "on": "1 " }, "state-icons": { "paused": "", "playing": "" }, "tooltip-format": "MPD (connected)", "tooltip-format-disconnected": "MPD (disconnected)" } ``` # STYLE - *#mpd* - *#mpd.disconnected* - *#mpd.stopped* - *#mpd.playing* - *#mpd.paused* waybar-0.12.0/man/waybar-mpris.5.scd000066400000000000000000000125571475603165300171310ustar00rootroot00000000000000waybar-mpris(5) # NAME waybar - MPRIS module # DESCRIPTION The *mpris* module displays currently playing media via libplayerctl. # CONFIGURATION *player*: ++ typeof: string ++ default: playerctld ++ Name of the MPRIS player to attach to. Using the default value always follows the currently active player. *ignored-players*: ++ typeof: []string ++ Ignore updates of the listed players, when using playerctld. *interval*: ++ typeof: integer ++ default: 0 ++ Refresh MPRIS information on a timer. *format*: ++ typeof: string ++ default: {player} ({status}) {dynamic} ++ The text format. *format-[status]*: ++ typeof: string ++ The status-specific text format. *tooltip*: ++ typeof: bool ++ default: true ++ Option to disable tooltip on hover. *tooltip-format*: ++ typeof: string ++ default: {player} ({status}) {dynamic} ++ The tooltip text format. *tooltip-format-[status]*: ++ typeof: string ++ The status-specific tooltip format. *artist-len*: ++ typeof: integer ++ Maximum length of the Artist tag (Wide/Fullwidth Unicode characters count as two). Set to zero to hide the artist in `{dynamic}` tag. *album-len*: ++ typeof: integer ++ Maximum length of the Album tag (Wide/Fullwidth Unicode characters count as two). Set to zero to hide the album in `{dynamic}` tag. *title-len*: ++ typeof: integer ++ Maximum length of the Title tag (Wide/Fullwidth Unicode characters count as two). Set to zero to hide the title in `{dynamic}` tag. *dynamic-len*: ++ typeof: integer ++ Maximum length of the Dynamic tag (Wide/Fullwidth Unicode characters ++ count as two). The dynamic tag will not truncate any tags beyond their ++ set length limits, instead, it will attempt to fit as much of the ++ available tags as possible. It is recommended you set title-len to ++ something less than or equal to this value, so the title will always be ++ displayed. *dynamic-order*: ++ typeof: []string ++ default: ["title", "artist", "album", "position", "length"] ++ Order of the tags shown by Dynamic tag. The position and length tags ++ will always be combined in the format [{position}/{length}]. The order ++ of these tags in relation to other tags will be determined based on the ++ declaration of the first among the two tags. Absence in this list means ++ force exclusion. *dynamic-importance-order*: ++ typeof: []string ++ default: ["title", "artist", "album", "position", "length"] ++ Priority of the tags when truncating the Dynamic tag. The final ones ++ will be the first to be truncated. Absence in this list means force ++ inclusion. *dynamic-separator*: ++ typeof: string ++ default: " - " ++ These characters will be used to separate two different tags, except ++ when one of these tags is position and length. *truncate-hours*: ++ typeof: bool ++ default: true ++ Whether to hide hours when media duration is less than an hour long. *enable-tooltip-len-limits*: ++ typeof: bool ++ default: false ++ Option to enable the length limits for the tooltip as well. By default, the tooltip ignores all length limits. *ellipsis*: ++ typeof: string ++ default: "…" ++ This character will be used when any of the tags exceed their maximum length. If you don't want to use an ellipsis, set this to empty string. *rotate*: ++ typeof: integer ++ Positive value to rotate the text label (in 90 degree increments). *max-length*: ++ typeof: integer ++ The maximum length in character the module should display. *min-length*: ++ typeof: integer ++ The minimum length in characters the module should accept. *align*: ++ typeof: float ++ The alignment of the label within the module, where 0 is left-aligned and 1 is right-aligned. If the module is rotated, it will follow the flow of the text. *justify*: ++ typeof: string ++ The alignment of the text within the module's label, allowing options 'left', 'right', or 'center' to define the positioning. *on-click*: ++ typeof: string ++ default: play-pause ++ Overwrite default action toggles. *on-click-middle*: ++ typeof: string ++ default: previous track ++ Overwrite default action toggles. *on-click-right*: ++ typeof: string ++ default: next track ++ Overwrite default action toggles. *player-icons*: ++ typeof: map[string]string ++ Allows setting _{player_icon}_ based on player-name property. *status-icons*: ++ typeof: map[string]string ++ Allows setting _{status_icon}_ based on player status (playing, paused, stopped). *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # FORMAT REPLACEMENTS *{player}*: The name of the current media player *{status}*: The current status (playing, paused, stopped) *{artist}*: The artist of the current track *{album}*: The album title of the current track *{title}*: The title of the current track *{length}*: Length of the track, formatted as HH:MM:SS *{dynamic}*: Use _{artist}_, _{album}_, _{title}_ and _{length}_, automatically omit++ empty values *{player_icon}*: Chooses an icon from _player-icons_ based on _{player}_ *{status_icon}*: Chooses an icon from _status-icons_ based on _{status}_ # EXAMPLES ``` "mpris": { "format": "{player_icon} {dynamic}", "format-paused": "{status_icon} {dynamic}", "player-icons": { "default": "▶", "mpv": "🎵" }, "status-icons": { "paused": "⏸" }, // "ignored-players": ["firefox"] } ``` # STYLE - *#mpris* - *#mpris.${status}* - *#mpris.${player}* waybar-0.12.0/man/waybar-network.5.scd000066400000000000000000000130771475603165300174660ustar00rootroot00000000000000waybar-network(5) # NAME waybar - network module # DESCRIPTION The *network* module displays information about the current network connections. # CONFIGURATION Addressed by *network* *interface*: ++ typeof: string ++ Use the defined interface instead of auto-detection. Accepts wildcard. *interval*: ++ typeof: integer ++ default: 60 ++ The interval in which the network information gets polled (e.g. signal strength). *family*: ++ typeof: string ++ default: *ipv4* ++ The address family that is used for the format replacement {ipaddr} and to determine if a network connection is present. *format*: ++ typeof: string ++ default: *{ifname}* ++ The format, how information should be displayed. This format is used when other formats aren't specified. *format-ethernet*: ++ typeof: string ++ This format is used when an ethernet interface is displayed. *format-wifi*: ++ typeof: string ++ This format is used when a wireless interface is displayed. *format-linked*: ++ typeof: string ++ This format is used when a linked interface with no IP address is displayed. *format-disconnected*: ++ typeof: string ++ This format is used when the displayed interface is disconnected. *format-disabled*: ++ typeof: string ++ This format is used when the displayed interface is disabled. *format-icons*: ++ typeof: array/object ++ Based on the current signal strength, the corresponding icon gets selected. ++ The order is *low* to *high*. Or by the state if it is an object. *rotate*: ++ typeof: integer ++ Positive value to rotate the text label (in 90 degree increments). *max-length*: ++ typeof: integer ++ The maximum length in character the module should display. *min-length*: ++ typeof: integer ++ The minimum length in characters the module should accept. *align*: ++ typeof: float ++ The alignment of the label within the module, where 0 is left-aligned and 1 is right-aligned. If the module is rotated, it will follow the flow of the text. *justify*: ++ typeof: string ++ The alignment of the text within the module's label, allowing options 'left', 'right', or 'center' to define the positioning. *on-click*: ++ typeof: string ++ Command to execute when clicked on the module. *on-click-middle*: ++ typeof: string ++ Command to execute when middle-clicked on the module using mousewheel. *on-click-right*: ++ typeof: string ++ Command to execute when you right-click on the module. *on-update*: ++ typeof: string ++ Command to execute when the module is updated. *on-scroll-up*: ++ typeof: string ++ Command to execute when scrolling up on the module. *on-scroll-down*: ++ typeof: string ++ Command to execute when scrolling down on the module. *smooth-scrolling-threshold*: ++ typeof: double ++ Threshold to be used when scrolling. *tooltip*: ++ typeof: bool ++ default: *true* ++ Option to disable tooltip on hover. *tooltip-format*: ++ typeof: string ++ The format, how information should be displayed in the tooltip. This format is used when other formats aren't specified. *tooltip-format-ethernet*: ++ typeof: string ++ This format is used when an ethernet interface is displayed. *tooltip-format-wifi*: ++ typeof: string ++ This format is used when a wireless interface is displayed. *tooltip-format-disconnected*: ++ typeof: string ++ This format is used when the displayed interface is disconnected. *tooltip-format-disabled*: ++ typeof: string ++ This format is used when the displayed interface is disabled. *menu*: ++ typeof: string ++ Action that popups the menu. *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # FORMAT REPLACEMENTS *{ifname}*: Name of the network interface. *{ipaddr}*: The first IP of the interface. *{gwaddr}*: The default gateway for the interface *{netmask}*: The subnetmask corresponding to the IP. *{cidr}*: The subnetmask corresponding to the IP in CIDR notation. *{essid}*: Name (SSID) of the wireless network. *{bssid}*: MAC address (BSSID) of the wireless access point. *{signalStrength}*: Signal strength of the wireless network. *{signaldBm}*: Signal strength of the wireless network in dBm. *{frequency}*: Frequency of the wireless network in MHz. *{bandwidthUpBits}*: Instant up speed in bits/seconds. *{bandwidthDownBits}*: Instant down speed in bits/seconds. *{bandwidthTotalBits}*: Instant total speed in bits/seconds. *{bandwidthUpOctets}*: Instant up speed in octets/seconds. *{bandwidthDownOctets}*: Instant down speed in octets/seconds. *{bandwidthTotalOctets}*: Instant total speed in octets/seconds. *{bandwidthUpBytes}*: Instant up speed in bytes/seconds. *{bandwidthDownBytes}*: Instant down speed in bytes/seconds. *{bandwidthTotalBytes}*: Instant total speed in bytes/seconds. *{icon}*: Icon, as defined in *format-icons*. # EXAMPLES ``` "network": { "interface": "wlp2s0", "format": "{ifname}", "format-wifi": "{essid} ({signalStrength}%) ", "format-ethernet": "{ifname} ", "format-disconnected": "", //An empty format will hide the module. "format-disconnected": "", "tooltip-format": "{ifname}", "tooltip-format-wifi": "{essid} ({signalStrength}%) ", "tooltip-format-ethernet": "{ifname} ", "tooltip-format-disconnected": "Disconnected", "max-length": 50 } ``` # STYLE - *#network* - *#network.disconnected* - *#network.disabled* - *#network.linked* - *#network.ethernet* - *#network.wifi* waybar-0.12.0/man/waybar-niri-language.5.scd000066400000000000000000000024671475603165300205200ustar00rootroot00000000000000waybar-niri-language(5) # NAME waybar - niri language module # DESCRIPTION The *language* module displays the currently selected language in niri. # CONFIGURATION Addressed by *niri/language* *format*: ++ typeof: string ++ default: {} ++ The format, how information should be displayed. *format-* ++ typeof: string++ Provide an alternative name to display per language where is the language of your choosing. Can be passed multiple times with multiple languages as shown by the example below. *menu*: ++ typeof: string ++ Action that popups the menu. *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # FORMAT REPLACEMENTS *{short}*: Short name of layout (e.g. "us"). Equals to {}. *{shortDescription}*: Short description of layout (e.g. "en"). *{long}*: Long name of layout (e.g. "English (Dvorak)"). *{variant}*: Variant of layout (e.g. "dvorak"). # EXAMPLES ``` "niri/language": { "format": "Lang: {long}" "format-en": "AMERICA, HELL YEAH!" "format-tr": "As bayrakları" } ``` # STYLE - *#language* waybar-0.12.0/man/waybar-niri-window.5.scd000066400000000000000000000036631475603165300202430ustar00rootroot00000000000000waybar-niri-window(5) # NAME waybar - niri window module # DESCRIPTION The *window* module displays the title of the currently focused window in niri. # CONFIGURATION Addressed by *niri/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*. *separate-outputs*: ++ typeof: bool ++ Show the active window of the monitor the bar belongs to, instead of the focused window. *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 "niri 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 ``` "niri/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 waybar-0.12.0/man/waybar-niri-workspaces.5.scd000066400000000000000000000047521475603165300211150ustar00rootroot00000000000000waybar-niri-workspaces(5) # NAME waybar - niri workspaces module # DESCRIPTION The *workspaces* module displays the currently used workspaces in niri. # CONFIGURATION Addressed by *niri/workspaces* *all-outputs*: ++ typeof: bool ++ default: false ++ If set to false, workspaces will only be shown on the output they are on. If set to true all workspaces will be shown on every output. *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 *{value}*: Name of the workspace, or index for unnamed workspaces, as defined by niri. *{name}*: Name of the workspace for named workspaces. *{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. - *active*: Will be shown, when workspace is active on its output. # EXAMPLES ``` "niri/workspaces": { "format": "{icon}", "format-icons": { // Named workspaces // (you need to configure them in niri) "browser": "", "discord": "", "chat": "", // Icons by state "active": "", "default": "" } } ``` # Style - *#workspaces button* - *#workspaces button.focused*: The single focused workspace. - *#workspaces button.active*: The workspace is active (visible) on its output. - *#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. - *#workspaces button#niri-workspace-*: Workspaces named this, or index for unnamed workspaces. waybar-0.12.0/man/waybar-power-profiles-daemon.5.scd000066400000000000000000000034411475603165300222050ustar00rootroot00000000000000waybar-power-profiles-daemon(5) # NAME waybar - power-profiles-daemon module # DESCRIPTION The *power-profiles-daemon* module displays the active power-profiles-daemon profile and cycle through the available profiles on click. # FILES $XDG_CONFIG_HOME/waybar/config # CONFIGURATION [- *Option* :- *Typeof* :- *Default* := *Description* |[ *format* :[ string :[ "{icon}" :[ Message displayed on the bar. {icon} and {profile} are respectively substituted with the icon representing the active profile and its full name. |[ *tooltip-format* :[ string :[ "Power profile: {profile}\\nDriver: {driver}" :[ Messaged displayed in the module tooltip. {icon} and {profile} are respectively substituted with the icon representing the active profile and its full name. |[ *tooltip* :[ bool :[ true :[ Display the tooltip. |[ *format-icons* :[ object :[ See default value in the example below. :[ Icons used to represent the various power-profile. *Note*: the default configuration uses the font-awesome icons. You may want to override it if you don't have this font installed on your system. |[ *expand*: :[ bool :[ false :[ Enables this module to consume all left over space dynamically. # CONFIGURATION EXAMPLES Compact display (default config): ``` "power-profiles-daemon": { "format": "{icon}", "tooltip-format": "Power profile: {profile}\nDriver: {driver}", "tooltip": true, "format-icons": { "default": "", "performance": "", "balanced": "", "power-saver": "" } } ``` Display the full profile name: ``` "power-profiles-daemon": { "format": "{icon} {profile}", "tooltip-format": "Power profile: {profile}\nDriver: {driver}", "tooltip": true, "format-icons": { "default": "", "performance": "", "balanced": "", "power-saver": "" } } ``` waybar-0.12.0/man/waybar-privacy.5.scd000066400000000000000000000031101475603165300174350ustar00rootroot00000000000000waybar-privacy(5) # NAME waybar - privacy module # DESCRIPTION The *privacy* module displays if any application is capturing audio, sharing ++ the screen or playing audio. # CONFIGURATION *icon-spacing*: ++ typeof: integer ++ default: 4 ++ The spacing between each privacy icon. *icon-size*: ++ typeof: integer ++ default: 20 ++ The size of each privacy icon. *transition-duration*: ++ typeof: integer ++ default: 250 ++ Option to disable tooltip on hover. *modules* ++ typeof: array of objects ++ default: [{"type": "screenshare"}, {"type": "audio-in"}] ++ Which privacy modules to monitor. See *MODULES CONFIGURATION* for++ more information. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # MODULES CONFIGURATION *type*: ++ typeof: string ++ values: "screenshare", "audio-in", "audio-out" ++ Specifies which module to use and configure. *tooltip*: ++ typeof: bool ++ default: true ++ Option to disable tooltip on hover. *tooltip-icon-size*: ++ typeof: integer ++ default: 24 ++ The size of each icon in the tooltip. # EXAMPLES ``` "privacy": { "icon-spacing": 4, "icon-size": 18, "transition-duration": 250, "modules": [ { "type": "screenshare", "tooltip": true, "tooltip-icon-size": 24 }, { "type": "audio-out", "tooltip": true, "tooltip-icon-size": 24 }, { "type": "audio-in", "tooltip": true, "tooltip-icon-size": 24 } ] }, ``` # STYLE - *#privacy* - *#privacy-item* - *#privacy-item.screenshare* - *#privacy-item.audio-in* - *#privacy-item.audio-out* waybar-0.12.0/man/waybar-pulseaudio-slider.5.scd000066400000000000000000000034731475603165300214260ustar00rootroot00000000000000waybar-pulseaudio-slider(5) # NAME waybar - pulseaudio slider module # DESCRIPTION The *pulseaudio slider* module displays and controls the current volume of the default sink or source as a bar. The volume can be controlled by dragging the slider across the bar or clicking on a specific position. # CONFIGURATION *min*: ++ typeof: int ++ default: 0 ++ The minimum volume value the slider should display and set. *max*: ++ typeof: int ++ default: 100 ++ The maximum volume value the slider should display and set. *orientation*: ++ typeof: string ++ default: horizontal ++ 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. # EXAMPLES ``` "modules-right": [ "pulseaudio/slider", ], "pulseaudio/slider": { "min": 0, "max": 100, "orientation": "horizontal" } ``` # STYLE The slider is a component with multiple CSS Nodes, of which the following are exposed: *#pulseaudio-slider*: ++ Controls the style of the box *around* the slider and bar. *#pulseaudio-slider slider*: ++ Controls the style of the slider handle. *#pulseaudio-slider trough*: ++ Controls the style of the part of the bar that has not been filled. *#pulseaudio-slider highlight*: ++ Controls the style of the part of the bar that has been filled. ## STYLE EXAMPLE ``` #pulseaudio-slider slider { min-height: 0px; min-width: 0px; opacity: 0; background-image: none; border: none; box-shadow: none; } #pulseaudio-slider trough { min-height: 80px; min-width: 10px; border-radius: 5px; background-color: black; } #pulseaudio-slider highlight { min-width: 10px; border-radius: 5px; background-color: green; } ``` waybar-0.12.0/man/waybar-pulseaudio.5.scd000066400000000000000000000113051475603165300201370ustar00rootroot00000000000000waybar-pulseaudio(5) # NAME waybar - pulseaudio module # DESCRIPTION The *pulseaudio* module displays the current volume reported by PulseAudio. Additionally, you can control the volume by scrolling *up* or *down* while the cursor is over the module. # CONFIGURATION *format*: ++ typeof: string ++ default: {volume}% ++ The format, how information should be displayed. This format is used when other formats aren't specified. *format-bluetooth*: ++ typeof: string ++ This format is used when using bluetooth speakers. *format-muted*: ++ typeof: string ++ This format is used when the sound is muted. *format-source*: ++ typeof: string ++ default: {volume}% ++ This format used for the source. *format-source-muted*: ++ typeof: string ++ This format is used when the source is muted. *format-icons*: ++ typeof: array ++ Based on the current port name and volume, the corresponding icon gets selected. The order is *low* to *high*. See *Icons*. *rotate*: ++ typeof: integer ++ Positive value to rotate the text label (in 90 degree increments). *states*: ++ typeof: object ++ A number of volume states which get activated on certain volume levels. See *waybar-states(5)*. *max-length*: ++ typeof: integer ++ The maximum length in character the module should display. *min-length*: ++ typeof: integer ++ The minimum length in characters the module should accept. *align*: ++ typeof: float ++ The alignment of the label within the module, where 0 is left-aligned and 1 is right-aligned. If the module is rotated, it will follow the flow of the text. *justify*: ++ typeof: string ++ The alignment of the text within the module's label, allowing options 'left', 'right', or 'center' to define the positioning. *scroll-step*: ++ typeof: float ++ default: 1.0 ++ The speed at which to change the volume when scrolling. *on-click*: ++ typeof: string ++ Command to execute when clicked on the module. *on-click-middle*: ++ typeof: string ++ Command to execute when middle-clicked on the module using mousewheel. *on-click-right*: ++ typeof: string ++ Command to execute when you right-click on the module. *on-update*: ++ typeof: string ++ Command to execute when the module is updated. *on-scroll-up*: ++ typeof: string ++ Command to execute when scrolling up on the module. This replaces the default behaviour of volume control. *on-scroll-down*: ++ typeof: string ++ Command to execute when scrolling down on the module. This replaces the default behaviour of volume control. *smooth-scrolling-threshold*: ++ typeof: double ++ Threshold to be used when scrolling. *reverse-scrolling*: ++ typeof: bool ++ Option to reverse the scroll direction. *tooltip*: ++ typeof: bool ++ default: true ++ Option to disable tooltip on hover. *max-volume*: ++ typeof: integer ++ default: 100 ++ The maximum volume that can be set, in percentage. *ignored-sinks*: ++ typeof: array ++ Sinks in this list will not be shown as active sink by Waybar. Entries should be the sink's description field. *menu*: ++ typeof: string ++ Action that popups the menu. *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # FORMAT REPLACEMENTS *{desc}*: Pulseaudio port's description, for bluetooth it'll be the device name. *{volume}*: Volume in percentage. *{icon}*: Icon, as defined in *format-icons*. *{format_source}*: Source format, *format-source*, *format-source-muted*. # ICONS: The following strings for *format-icons* are supported. - the device name If they are found in the current PulseAudio port name, the corresponding icons will be selected. - *default* (Shown, when no other port is found) - *headphone* - *speaker* - *hdmi* - *headset* - *hands-free* - *portable* - *car* - *hifi* - *phone* Additionally, suffixing a device name or port with *-muted* will cause the icon to be selected when the corresponding audio device is muted. This applies to *default* as well. # EXAMPLES ``` "pulseaudio": { "format": "{volume}% {icon}", "format-bluetooth": "{volume}% {icon}", "format-muted": "", "format-icons": { "alsa_output.pci-0000_00_1f.3.analog-stereo": "", "alsa_output.pci-0000_00_1f.3.analog-stereo-muted": "", "headphones": "", "handsfree": "", "headset": "", "phone": "", "phone-muted": "", "portable": "", "car": "", "default": ["", ""] }, "scroll-step": 1, "on-click": "pavucontrol" } ``` # STYLE - *#pulseaudio* - *#pulseaudio.bluetooth* - *#pulseaudio.muted* waybar-0.12.0/man/waybar-river-layout.5.scd000066400000000000000000000036211475603165300204310ustar00rootroot00000000000000waybar-river-layout(5) # NAME waybar - river layout module # DESCRIPTION The *layout* module displays the current layout in river. It may not be set until a layout is first applied. # CONFIGURATION Addressed by *river/layout* *format*: ++ typeof: string ++ default: {} ++ The format, how information should be displayed. On {} data gets inserted. *rotate*: ++ typeof: integer ++ Positive value to rotate the text label (in 90 degree increments). *max-length*: ++ typeof: integer ++ The maximum length in character the module should display. *min-length*: ++ typeof: integer ++ The minimum length in characters the module should accept. *align*: ++ typeof: float ++ The alignment of the label within the module, where 0 is left-aligned and 1 is right-aligned. If the module is rotated, it will follow the flow of the text. *justify*: ++ typeof: string ++ The alignment of the text within the module's label, allowing options 'left', 'right', or 'center' to define the positioning. *on-click*: ++ typeof: string ++ Command to execute when clicked on the module. *on-click-middle*: ++ typeof: string ++ Command to execute when middle-clicked on the module using mousewheel. *on-click-right*: ++ typeof: string ++ Command to execute when you right-click on the module. *menu*: ++ typeof: string ++ Action that popups the menu. *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # EXAMPLE ``` "river/layout": { "format": "{}", "min-length": 4, "align": "right" } ``` # STYLE - *#layout* - *#layout.focused* Applied when the output this module's bar belongs to is focused. # SEE ALSO waybar(5), river(1) waybar-0.12.0/man/waybar-river-mode.5.scd000066400000000000000000000040761475603165300200450ustar00rootroot00000000000000waybar-river-mode(5) # NAME waybar - river mode module # DESCRIPTION The *mode* module displays the current mapping mode of river. # CONFIGURATION Addressed by *river/mode* *format*: ++ typeof: string ++ default: {} ++ The format, how information should be displayed. On {} data gets inserted. *rotate*: ++ typeof: integer ++ Positive value to rotate the text label (in 90 degree increments). *max-length*: ++ typeof: integer ++ The maximum length in character the module should display. *min-length*: ++ typeof: integer ++ The minimum length in characters the module should accept. *align*: ++ typeof: float ++ The alignment of the label within the module, where 0 is left-aligned and 1 is right-aligned. If the module is rotated, it will follow the flow of the text. *justify*: ++ typeof: string ++ The alignment of the text within the module's label, allowing options 'left', 'right', or 'center' to define the positioning. *on-click*: ++ typeof: string ++ Command to execute when clicked on the module. *on-click-middle*: ++ typeof: string ++ Command to execute when middle-clicked on the module using mousewheel. *on-click-right*: ++ typeof: string ++ Command to execute when you right-click on the module. *on-update*: ++ typeof: string ++ Command to execute when the module is updated. *on-scroll-up*: ++ typeof: string ++ Command to execute when scrolling up on the module. *on-scroll-down*: ++ typeof: string ++ Command to execute when scrolling down on the module. *smooth-scrolling-threshold*: ++ typeof: double ++ Threshold to be used when scrolling. *menu*: ++ typeof: string ++ Action that popups the menu. *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # EXAMPLES ``` "river/mode": { "format": " {}" } ``` # STYLE - *#mode* - *#mode.* waybar-0.12.0/man/waybar-river-tags.5.scd000066400000000000000000000021201475603165300200430ustar00rootroot00000000000000waybar-river-tags(5) # NAME waybar - river tags module # DESCRIPTION The *tags* module displays the current state of tags in river. # CONFIGURATION Addressed by *river/tags* *num-tags*: ++ typeof: uint ++ default: 9 ++ The number of tags that should be displayed. Max 32. *tag-labels*: ++ typeof: array ++ The label to display for each tag. *disable-click*: ++ typeof: bool ++ default: false ++ If set to false, you can left-click to set focused tag. Right-click to toggle tag focus. If set to true this behaviour is disabled. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. *hide-vacant*: ++ typeof: bool ++ default: false ++ Only show relevant tags: tags that are either focused or have a window on them. # EXAMPLE ``` "river/tags": { "num-tags": 5 } ``` # STYLE - *#tags button* - *#tags button.occupied* - *#tags button.focused* - *#tags button.urgent* Note that occupied/focused/urgent status may overlap. That is, a tag may be both occupied and focused at the same time. # SEE ALSO waybar(5), river(1) waybar-0.12.0/man/waybar-river-window.5.scd000066400000000000000000000034561475603165300204310ustar00rootroot00000000000000waybar-river-window(5) # NAME waybar - river window module # DESCRIPTION The *window* module displays the title of the currently focused window in river # CONFIGURATION Addressed by *river/window* *format*: ++ typeof: string ++ default: {} ++ The format, how information should be displayed. On {} data gets inserted. *rotate*: ++ typeof: integer ++ Positive value to rotate the text label (in 90 degree increments). *max-length*: ++ typeof: integer ++ The maximum length in character the module should display. *min-length*: ++ typeof: integer ++ The minimum length in characters the module should accept. *align*: ++ typeof: float ++ The alignment of the label within the module, where 0 is left-aligned and 1 is right-aligned. If the module is rotated, it will follow the flow of the text. *justify*: ++ typeof: string ++ The alignment of the text within the module's label, allowing options 'left', 'right', or 'center' to define the positioning. *on-click*: ++ typeof: string ++ Command to execute when clicked on the module. *on-click-middle*: ++ typeof: string ++ Command to execute when middle-clicked on the module using mousewheel. *on-click-right*: ++ typeof: string ++ Command to execute when you right-click on the module. *menu*: ++ typeof: string ++ Action that popups the menu. *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # EXAMPLES ``` "river/window": { "format": "{}" } ``` # STYLE - *#window* - *#window.focused* Applied when the output this module's bar belongs to is focused. waybar-0.12.0/man/waybar-sndio.5.scd000066400000000000000000000051021475603165300170770ustar00rootroot00000000000000waybar-sndio(5) # NAME waybar - sndio module # DESCRIPTION The *sndio* module displays the current volume reported by sndio(7). Additionally, you can control the volume by scrolling *up* or *down* while the cursor is over the module, and clicking on the module toggles mute. # CONFIGURATION *format*: ++ typeof: string ++ default: {volume}% ++ The format for how information should be displayed. *rotate*: ++ typeof: integer ++ Positive value to rotate the text label (in 90 degree increments). *max-length*: ++ typeof: integer ++ The maximum length in character the module should display. *min-length*: ++ typeof: integer ++ The minimum length in characters the module should accept. *align*: ++ typeof: float ++ The alignment of the label within the module, where 0 is left-aligned and 1 is right-aligned. If the module is rotated, it will follow the flow of the text. *justify*: ++ typeof: string ++ The alignment of the text within the module's label, allowing options 'left', 'right', or 'center' to define the positioning. *scroll-step*: ++ typeof: int ++ default: 5 ++ The speed at which to change the volume when scrolling. *on-click*: ++ typeof: string ++ Command to execute when clicked on the module. This replaces the default behaviour of toggling mute. *on-click-middle*: ++ typeof: string ++ Command to execute when middle-clicked on the module using mousewheel. *on-click-right*: ++ typeof: string ++ Command to execute when you right-click on the module. *on-update*: ++ typeof: string ++ Command to execute when the module is updated. *on-scroll-up*: ++ typeof: string ++ Command to execute when scrolling up on the module. ++ This replaces the default behaviour of volume control. *on-scroll-down*: ++ typeof: string ++ Command to execute when scrolling down on the module. ++ This replaces the default behaviour of volume control. *smooth-scrolling-threshold*: ++ typeof: double ++ Threshold to be used when scrolling. *menu*: ++ typeof: string ++ Action that popups the menu. *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # FORMAT REPLACEMENTS *{volume}*: Volume in percentage. *{raw_value}*: Volume as value reported by sndio. # EXAMPLES ``` "sndio": { "format": "{raw_value} 🎜", "scroll-step": 3 } ``` # STYLE - *#sndio* - *#sndio.muted* waybar-0.12.0/man/waybar-states.5.scd000066400000000000000000000023271475603165300172740ustar00rootroot00000000000000waybar-states(5) # NAME waybar - states property # OVERVIEW Some modules support 'states' which allows percentage values to be used as styling triggers to apply a class when the value matches the declared state value. # STATES Every entry (*state*) consists of a ** (typeof: *string*) and a ** (typeof: *integer*). - 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 value is equal to or less than the configured ** for the *battery* module, or equal to or greater than the configured ** for all other modules. - Also, each state can have its own *format*. Those can be configured via *format-*, or if you want to differentiate a bit more, as *format--*. # EXAMPLE ``` "battery": { "bat": "BAT2", "interval": 60, "states": { "warning": 30, "critical": 15 }, "format": "{capacity}% {icon}", "format-icons": ["", "", "", "", ""], "max-length": 25 } ``` # STYLING STATES - *#battery.* - ** can be defined in the *config*. # EXAMPLE: - *#battery.warning: { background: orange; }* - *#battery.critical: { background: red; }* waybar-0.12.0/man/waybar-styles.5.scd.in000066400000000000000000000035041475603165300177170ustar00rootroot00000000000000waybar-styles(5) # NAME waybar-styles - using stylesheets for waybar # DESCRIPTION Waybar uses Cascading Style Sheets (CSS) to configure its appearance. It uses the first file found in this search order: - *$XDG_CONFIG_HOME/waybar/style.css* - *~/.config/waybar/style.css* - *~/waybar/style.css* - */etc/xdg/waybar/style.css* - *@sysconfdir@/xdg/waybar/style.css* # EXAMPLE An example user-controlled stylesheet that just changes the color of the clock to be green on black, while keeping the rest of the system config the same would be: ``` @import url("file:///etc/xdg/waybar/style.css") #clock { background: #000000; color: #00ff00; } ``` ## Hover-effect You can apply special styling to any module for when the cursor hovers it. ``` #clock:hover { background-color: #ffffff; } ``` ## Setting cursor style Most, if not all, module types support setting the `cursor` option. This is configured in your `config.jsonc`. If set to `false`, when hovering the module a "pointer"(as commonly known from web CSS styling `cursor: pointer`) style cursor will not be shown. Default behavior is to indicate an interaction event is available. There are more cursor types to choose from by setting the `cursor` option to a number, see Gdk3 official docs for all possible cursor types: https://docs.gtk.org/gdk3/enum.CursorType.html. However, note that not all cursor options listed may be available on your system. If you attempt to use a cursor which is not available, the application will crash. Example of disabling pointer(`Gdk::Hand2`) cursor type on a custom module: ``` "custom/my-custom-module": { ... "cursor": false, } ``` Example of setting cursor type to `Gdk::Boat`(according to https://docs.gtk.org/gdk3/enum.CursorType.html#boat): ``` "custom/my-custom-module": { ... "cursor": 8, } ``` # SEE ALSO - *waybar(5)* waybar-0.12.0/man/waybar-sway-language.5.scd000066400000000000000000000026471475603165300205420ustar00rootroot00000000000000waybar-sway-language(5) # NAME waybar - sway language module # DESCRIPTION The *language* module displays the current keyboard layout in Sway # CONFIGURATION Addressed by *sway/language* *format*: ++ typeof: string ++ default: {} ++ The format, how layout should be displayed. *hide-single-layout*: ++ typeof: bool ++ default: false ++ Defines visibility of the module if a single layout is configured *tooltip-format*: ++ typeof: string ++ default: {} ++ The format, how layout should be displayed in tooltip. *tooltip*: ++ typeof: bool ++ default: true ++ Option to disable tooltip on hover. *menu*: ++ typeof: string ++ Action that popups the menu. *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # FORMAT REPLACEMENTS *{short}*: Short name of layout (e.g. "us"). Equals to {}. *{shortDescription}*: Short description of layout (e.g. "en"). *{long}*: Long name of layout (e.g. "English (Dvorak)"). *{variant}*: Variant of layout (e.g. "dvorak"). *{flag}*: Country flag of layout. # EXAMPLES ``` "sway/language": { "format": "{}", }, "sway/language": { "format": "{short} {variant}", } ``` # STYLE - *#language* waybar-0.12.0/man/waybar-sway-mode.5.scd000066400000000000000000000042211475603165300176710ustar00rootroot00000000000000waybar-sway-mode(5) # NAME waybar - sway mode module # DESCRIPTION The *mode* module displays the current binding mode of Sway # CONFIGURATION Addressed by *sway/mode* *format*: ++ typeof: string ++ default: {} ++ The format, how information should be displayed. On {} data gets inserted. *rotate*: ++ typeof: integer ++ Positive value to rotate the text label (in 90 degree increments). *max-length*: ++ typeof: integer ++ The maximum length in character the module should display. *min-length*: ++ typeof: integer ++ The minimum length in characters the module should accept. *align*: ++ typeof: float ++ The alignment of the label within the module, where 0 is left-aligned and 1 is right-aligned. If the module is rotated, it will follow the flow of the text. *justify*: ++ typeof: string ++ The alignment of the text within the module's label, allowing options 'left', 'right', or 'center' to define the positioning. *on-click*: ++ typeof: string ++ Command to execute when clicked on the module. *on-click-middle*: ++ typeof: string ++ Command to execute when middle-clicked on the module using mousewheel. *on-click-right*: ++ typeof: string ++ Command to execute when you right-click on the module. *on-update*: ++ typeof: string ++ Command to execute when the module is updated. *on-scroll-up*: ++ typeof: string ++ Command to execute when scrolling up on the module. *on-scroll-down*: ++ typeof: string ++ Command to execute when scrolling down on the module. *smooth-scrolling-threshold*: ++ typeof: double ++ Threshold to be used when scrolling. *tooltip*: ++ typeof: bool ++ default: true ++ Option to disable tooltip on hover. *menu*: ++ typeof: string ++ Action that popups the menu. *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # EXAMPLES ``` "sway/mode": { "format": " {}", "max-length": 50 } ``` # STYLE - *#mode* waybar-0.12.0/man/waybar-sway-scratchpad.5.scd000066400000000000000000000031241475603165300210620ustar00rootroot00000000000000waybar-sway-scratchpad(5) # NAME waybar - sway scratchpad module # DESCRIPTION The *scratchpad* module displays the scratchpad status in Sway # CONFIGURATION Addressed by *sway/scratchpad* *format*: ++ typeof: string ++ default: {icon} {count} ++ The format, how information should be displayed. *show-empty*: ++ typeof: bool ++ default: false ++ Option to show module when scratchpad is empty. *format-icons*: ++ typeof: array/object ++ Based on the current scratchpad window counts, the corresponding icon gets selected. *tooltip*: ++ typeof: bool ++ default: true ++ Option to disable tooltip on hover. *tooltip-format*: ++ typeof: string ++ default: {app}: {title} ++ The format, how information in the tooltip should be displayed. *menu*: ++ typeof: string ++ Action that popups the menu. *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # FORMAT REPLACEMENTS *{icon}*: Icon, as defined in *format-icons*. *{count}*: Number of windows in the scratchpad. *{app}*: Name of the application in the scratchpad. *{title}*: Title of the application in the scratchpad. # EXAMPLES ``` "sway/scratchpad": { "format": "{icon} {count}", "show-empty": false, "format-icons": ["", ""], "tooltip": true, "tooltip-format": "{app}: {title}" } ``` # STYLE - *#scratchpad* - *#scratchpad.empty* waybar-0.12.0/man/waybar-sway-window.5.scd000066400000000000000000000107431475603165300202620ustar00rootroot00000000000000waybar-sway-window(5) # NAME waybar - sway window module # DESCRIPTION The *window* module displays the title of the currently focused window in Sway # CONFIGURATION Addressed by *sway/window* *format*: ++ typeof: string ++ default: {title} ++ The format, how information should be displayed. *rotate*: ++ typeof: integer ++ Positive value to rotate the text label (in 90 degree increments). *max-length*: ++ typeof: integer ++ The maximum length in character the module should display. *min-length*: ++ typeof: integer ++ The minimum length in characters the module should accept. *align*: ++ typeof: float ++ The alignment of the label within the module, where 0 is left-aligned and 1 is right-aligned. If the module is rotated, it will follow the flow of the text. *justify*: ++ typeof: string ++ The alignment of the text within the module's label, allowing options 'left', 'right', or 'center' to define the positioning. *on-click*: ++ typeof: string ++ Command to execute when clicked on the module. *on-click-middle*: ++ typeof: string ++ Command to execute when middle-clicked on the module using mousewheel. *on-click-right*: ++ typeof: string ++ Command to execute when you right-click on the module. *on-update*: ++ typeof: string ++ Command to execute when the module is updated. *on-scroll-up*: ++ typeof: string ++ Command to execute when scrolling up on the module. *on-scroll-down*: ++ typeof: string ++ Command to execute when scrolling down on the module. *smooth-scrolling-threshold*: ++ typeof: double ++ Threshold to be used when scrolling. *tooltip*: ++ typeof: bool ++ default: true ++ Option to disable tooltip on hover. *all-outputs*: ++ typeof: bool ++ default: false ++ Option to show the focused window along with its workspace styles on all outputs. *offscreen-css*: ++ typeof: bool ++ default: false ++ Only effective when all-outputs is true. Adds style according to present windows on unfocused outputs instead of showing the focused window and style. *offscreen-css-text*: ++ typeof: string ++ Only effective when both all-outputs and offscreen-style are true. On screens currently not focused, show the given text along with that workspace styles. *show-focused-workspace-name*: ++ typeof: bool ++ 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. *rewrite*: ++ typeof: object ++ Rules to rewrite the module format output. 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 *{title}*: The title of the focused window. *{app_id}*: The app_id of the focused window. *{shell}*: The shell of the focused window. It's 'xwayland' when the window is running through xwayland, otherwise, it's 'xdg-shell'. # 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 format output is left unchanged. Invalid expressions (e.g., mismatched parentheses) are skipped. # EXAMPLES ``` "sway/window": { "format": "{}", "max-length": 50, "rewrite": { "(.*) - Mozilla Firefox": "🌎 $1", "(.*) - zsh": "> [$1]" } } ``` # STYLE - *#window* 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, or screen is not focused and offscreen-css option is not set - *window#waybar.solo* When one tiled window is in the workspace - *window#waybar.floating* When there are only floating windows in the workspace - *window#waybar.stacked* When there is more than one window in the workspace and the workspace layout is stacked - *window#waybar.tabbed* When there is more than one window in the workspace and the workspace layout is tabbed - *window#waybar.tiled* When there is more than one window in the workspace and the workspace layout is splith or splitv - *window#waybar.* Where *app_id* is the app_id or *instance* name like (*chromium*) of the only window in the workspace waybar-0.12.0/man/waybar-sway-workspaces.5.scd000066400000000000000000000136611475603165300211360ustar00rootroot00000000000000waybar-sway-workspaces(5) # NAME waybar - sway workspaces module # DESCRIPTION The *workspaces* module displays the currently used workspaces in Sway. # CONFIGURATION Addressed by *sway/workspaces* *all-outputs*: ++ typeof: bool ++ default: false ++ If set to false, workspaces will only be shown on the output they are on. If set to true all workspaces will be shown on every output. *format*: ++ typeof: string ++ default: {value} ++ The format, how information should be displayed. *format-icons*: ++ typeof: array ++ Based on the workspace name and state, the corresponding icon gets selected. See *icons*. *disable-scroll*: ++ typeof: bool ++ default: false ++ If set to false, you can scroll to cycle through workspaces. If set to true this behaviour is disabled. *disable-click*: ++ typeof: bool ++ default: false ++ If set to false, you can click to change workspace. If set to true this behaviour is disabled. *smooth-scrolling-threshold*: ++ typeof: double ++ Threshold to be used when scrolling. *disable-scroll-wraparound*: ++ typeof: bool ++ default: false ++ If set to false, scrolling on the workspace indicator will wrap around to the first workspace when reading the end, and vice versa. If set to true this behavior is disabled. *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. *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 focused workspaces will be shown. *persistent-workspaces*: ++ typeof: json (see below) ++ default: empty ++ Lists workspaces that should always be shown, even when non-existent *on-update*: ++ typeof: string ++ Command to execute when the module is updated. *disable-auto-back-and-forth*: ++ typeof: bool ++ Whether to disable *workspace_auto_back_and_forth* when clicking on workspaces. If this is set to *true*, clicking on a workspace you are already on won't do anything, even if *workspace_auto_back_and_forth* is enabled in the Sway configuration. *alphabetical_sort*: ++ typeof: bool ++ Whether to sort workspaces alphabetically. Please note this can make "swaymsg workspace prev/next" move to workspaces inconsistent with the ordering shown in Waybar. warp-on-scroll: ++ typeof: bool ++ default: true ++ If set to false, you can scroll to cycle through workspaces without mouse warping being enabled. If set to true this behaviour is disabled. *window-rewrite*: ++ typeof: object ++ 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. 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. For Wayland windows `class` is matched against the `app_id`, and for X11 windows against the `class` property. *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*. *format-window-separator*: ++ typeof: string ++ default: " " ++ The separator to be used between windows in a workspace. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # FORMAT REPLACEMENTS *{value}*: Name of the workspace, as defined by sway. *{name}*: Number stripped from workspace value. *{icon}*: Icon, as defined in *format-icons*. *{index}*: Index of the workspace. *{output}*: Output where the workspace is located. *{windows}*: Result from window-rewrite # ICONS Additional to workspace name matching, the following *format-icons* can be set. - *default*: Will be shown, when no string matches are found. - *urgent*: Will be shown, when workspace is flagged as urgent - *focused*: Will be shown, when workspace is focused - *persistent*: Will be shown, when workspace is persistent. - *high-priority-named*: Icons by names will be shown always for those workspaces, independent by state. # PERSISTENT WORKSPACES Each entry of *persistent_workspace* names a workspace that should always be shown. Associated with that value is a list of outputs indicating *where* the workspace should be shown, an empty list denoting all outputs. ``` "sway/workspaces": { "persistent-workspaces": { "3": [], // Always show a workspace with name '3', on all outputs if it does not exist "4": ["eDP-1"], // Always show a workspace with name '4', on output 'eDP-1' if it does not exist "5": ["eDP-1", "DP-2"] // Always show a workspace with name '5', on outputs 'eDP-1' and 'DP-2' if it does not exist } } ``` n.b.: the list of outputs can be obtained from command line using *swaymsg -t get_outputs* # EXAMPLES ``` "sway/workspaces": { "disable-scroll": true, "all-outputs": true, "format": "{name}: {icon}", "format-icons": { "1": "", "2": "", "3": "", "4": "", "5": "", "high-priority-named": [ "1", "2" ], "urgent": "", "focused": "", "default": "" } } ``` ``` "sway/workspaces": { "format": "{name} {windows}", "format-window-separator": " | ", "window-rewrite-default": "{name}", "window-format": "{name}", "window-rewrite": { "class": "", "class": "k", "title<.* - (.*) - VSCodium>": "codium $1" // captures part of the window title and formats it into output } } ``` # Style - *#workspaces button* - *#workspaces button.visible* - *#workspaces button.focused* - *#workspaces button.urgent* - *#workspaces button.persistent* - *#workspaces button.empty* - *#workspaces button.current_output* - *#workspaces button#sway-workspace-${name}* waybar-0.12.0/man/waybar-systemd-failed-units.5.scd000066400000000000000000000032071475603165300220410ustar00rootroot00000000000000waybar-systemd-failed-units(5) # NAME waybar - systemd failed units monitor module # DESCRIPTION The *systemd-failed-units* module displays the number of failed systemd units. # CONFIGURATION Addressed by *systemd-failed-units* *format*: ++ typeof: string ++ default: *{nr_failed} failed* ++ The format, how information should be displayed. This format is used when other formats aren't specified. *format-ok*: ++ typeof: string ++ This format is used when there is no failing units. *user*: ++ typeof: bool ++ default: *true* ++ Option to count user systemd units. *system*: ++ typeof: bool ++ default: *true* ++ Option to count systemwide (PID=1) systemd units. *hide-on-ok*: ++ typeof: bool ++ default: *true* ++ Option to hide this module when there is no failing units. *menu*: ++ typeof: string ++ Action that popups the menu. *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # FORMAT REPLACEMENTS *{nr_failed_system}*: Number of failed units from systemwide (PID=1) systemd. *{nr_failed_user}*: Number of failed units from user systemd. *{nr_failed}*: Number of total failed units. # EXAMPLES ``` "systemd-failed-units": { "hide-on-ok": false, "format": "✗ {nr_failed}", "format-ok": "✓", "system": true, "user": false, } ``` # STYLE - *#systemd-failed-units* - *#systemd-failed-units.ok* - *#systemd-failed-units.degraded* waybar-0.12.0/man/waybar-temperature.5.scd000066400000000000000000000104631475603165300203260ustar00rootroot00000000000000waybar-temperature(5) # NAME waybar - temperature module # DESCRIPTION The *temperature* module displays the current temperature from a thermal zone. # CONFIGURATION Addressed by *temperature* *thermal-zone*: ++ typeof: integer ++ The thermal zone, as in */sys/class/thermal/*. *hwmon-path*: ++ typeof: string ++ The temperature path to use, e.g. */sys/class/hwmon/hwmon2/temp1_input* instead of one in */sys/class/thermal/*. This can also be an array of strings. In this case, waybar will check each item in the array and use the first valid one. This is suitable if you want to share the same configuration file among different machines with different hardware configurations. *hwmon-path-abs*: ++ typeof: string ++ 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*. *input-filename*: ++ typeof: string ++ The temperature filename of your *hwmon-path-abs*, e.g. *temp1_input* *warning-threshold*: ++ typeof: integer ++ The threshold before it is considered warning (Celsius). *critical-threshold*: ++ typeof: integer ++ The threshold before it is considered critical (Celsius). *interval*: ++ typeof: integer ++ default: 10 ++ The interval in which the information gets polled. *format-warning*: ++ typeof: string ++ The format to use when temperature is considered warning *format-critical*: ++ typeof: string ++ The format to use when temperature is considered critical *format*: ++ typeof: string ++ default: {temperatureC}°C ++ The format (Celsius/Fahrenheit/Kelvin) in which the temperature should be displayed. *format-icons*: ++ typeof: array ++ Based on the current temperature (Celsius) and *critical-threshold* if available, the corresponding icon gets selected. The order is *low* to *high*. *tooltip-format*: ++ typeof: string ++ default: {temperatureC}°C ++ The format for the tooltip *rotate*: ++ typeof: integer ++ Positive value to rotate the text label (in 90 degree increments). *max-length*: ++ typeof: integer ++ The maximum length in characters the module should display. *min-length*: ++ typeof: integer ++ The minimum length in characters the module should accept. *align*: ++ typeof: float ++ The alignment of the label within the module, where 0 is left-aligned and 1 is right-aligned. If the module is rotated, it will follow the flow of the text. *justify*: ++ typeof: string ++ The alignment of the text within the module's label, allowing options 'left', 'right', or 'center' to define the positioning. *on-click*: ++ typeof: string ++ Command to execute when you click on the module. *on-click-middle*: ++ typeof: string ++ Command to execute when middle-clicked on the module using mousewheel. *on-click-right*: ++ typeof: string ++ Command to execute when you right-click on the module. *on-update*: ++ typeof: string ++ Command to execute when the module is updated. *on-scroll-up*: ++ typeof: string ++ Command to execute when scrolling up on the module. *on-scroll-down*: ++ typeof: string ++ Command to execute when scrolling down on the module. *smooth-scrolling-threshold*: ++ typeof: double ++ Threshold to be used when scrolling. *tooltip*: ++ typeof: bool ++ default: true ++ Option to disable tooltip on hover. *menu*: ++ typeof: string ++ Action that popups the menu. *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. *expand*: ++ typeof: bool ++ default: false ++ Enables this module to consume all left over space dynamically. # FORMAT REPLACEMENTS *{temperatureC}*: Temperature in Celsius. *{temperatureF}*: Temperature in Fahrenheit. *{temperatureK}*: Temperature in Kelvin. # EXAMPLES ``` "temperature": { // "thermal-zone": 2, // "hwmon-path": ["/sys/class/hwmon/hwmon2/temp1_input", "/sys/class/thermal/thermal_zone0/temp"], // "critical-threshold": 80, // "format-critical": "{temperatureC}°C ", "format": "{temperatureC}°C " } ``` # STYLE - *#temperature* - *#temperature.critical* waybar-0.12.0/man/waybar-tray.5.scd000066400000000000000000000017601475603165300167500ustar00rootroot00000000000000waybar-tray(5) # NAME waybar - tray module # DESCRIPTION _WARNING_ *tray* is still in beta. There may be bugs. Breaking changes may occur. # CONFIGURATION Addressed by *tray* *icon-size*: ++ typeof: integer ++ Defines the size of the tray icons. *show-passive-items*: ++ typeof: bool ++ default: false ++ Defines visibility of the tray icons with *Passive* status. *smooth-scrolling-threshold*: ++ typeof: double ++ Threshold to be used when scrolling. *spacing*: ++ typeof: integer ++ Defines the spacing between the tray icons. *reverse-direction*: ++ typeof: bool ++ Defines if new app icons should be added in a reverse order *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. # EXAMPLES ``` "tray": { "icon-size": 21, "spacing": 10 } ``` # STYLE - *#tray* - *#tray > .passive* - *#tray > .active* - *#tray > .needs-attention* waybar-0.12.0/man/waybar-upower.5.scd000066400000000000000000000051441475603165300173120ustar00rootroot00000000000000waybar-upower(5) # NAME waybar - upower module # DESCRIPTION The *upower* module displays the main battery capacity with all other upower compatible devices in the tooltip. # CONFIGURATION *native-path*: ++ typeof: string ++ default: ++ The battery to monitor. Refer to the https://upower.freedesktop.org/docs/UpDevice.html#UpDevice--native-path ++ Can be obtained using `upower --dump` *model*: ++ typeof: string ++ default: ++ The battery to monitor, based on the model. (this option is ignored if *native-path* is given). ++ Can be obtained using `upower --dump` *icon-size*: ++ typeof: integer ++ default: 20 ++ Defines the size of the icons. *format*: ++ typeof: string ++ default: {percentage} ++ The text format. *format-alt*: ++ typeof: string ++ default: {percentage} {time} ++ The text format when toggled. *hide-if-empty*: ++ typeof: bool ++ default: true ++ Defines visibility of the module if no devices can be found. *tooltip*: ++ typeof: bool ++ default: true ++ Option to disable tooltip on hover. *tooltip-spacing*: ++ typeof: integer ++ default: 4 ++ Defines the spacing between the tooltip device name and device battery ++ status. *tooltip-padding*: ++ typeof: integer ++ default: 4 ++ Defines the spacing between the tooltip window edge and the tooltip content. *on-click*: ++ typeof: string ++ Command to execute when clicked on the module. *show-icon*: ++ typeof: bool ++ default: true ++ Option to disable battery icon. *menu*: ++ typeof: string ++ Action that popups the menu. *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. # FORMAT REPLACEMENTS *{percentage}*: The battery capacity in percentage *{time}*: An estimated time either until empty or until fully charged ++ depending on the charging state. # EXAMPLES ``` "upower": { "icon-size": 20, "hide-if-empty": true, "tooltip": true, "tooltip-spacing": 20 } ``` ``` "upower": { "native-path": "/org/bluez/hci0/dev_D4_AE_41_38_D0_EF", "icon-size": 20, "hide-if-empty": true, "tooltip": true, "tooltip-spacing": 20 } ``` ``` "upower": { "native-path": "battery_sony_controller_battery_d0o27o88o32ofcoee", "icon-size": 20, "hide-if-empty": true, "tooltip": true, "tooltip-spacing": 20 } ``` ``` "upower": { "show-icon": false, "hide-if-empty": true, "tooltip": true, "tooltip-spacing": 20 } ``` # STYLE - *#upower* - *#upower.charging* - *#upower.discharging* - *#upower.full* - *#upower.empty* - *#upower.unknown-status* waybar-0.12.0/man/waybar-wireplumber.5.scd000066400000000000000000000055151475603165300203300ustar00rootroot00000000000000waybar-wireplumber(5) # NAME waybar - WirePlumber module # DESCRIPTION The *wireplumber* module displays the current volume reported by WirePlumber. # CONFIGURATION *format*: ++ typeof: string ++ default: *{volume}%* ++ The format, how information should be displayed. This format is used when other formats aren't specified. *format-muted*: ++ typeof: string ++ This format is used when the sound is muted. *tooltip*: ++ typeof: bool ++ default: *true* ++ Option to disable tooltip on hover. *tooltip-format*: ++ typeof: string ++ default: *{node_name}* ++ The format of information displayed in the tooltip. *rotate*: ++ typeof: integer ++ Positive value to rotate the text label (in 90 degree increments). *states*: ++ typeof: object ++ A number of volume states which get activated on certain volume levels. See *waybar-states(5)*. *max-length*: ++ typeof: integer ++ The maximum length in character the module should display. *min-length*: ++ typeof: integer ++ The minimum length in characters the module should accept. *align*: ++ typeof: float ++ The alignment of the label within the module, where 0 is left-aligned and 1 is right-aligned. If the module is rotated, it will follow the flow of the text. *justify*: ++ typeof: string ++ The alignment of the text within the module's label, allowing options 'left', 'right', or 'center' to define the positioning. *scroll-step*: ++ typeof: float ++ default: 1.0 ++ The speed at which to change the volume when scrolling. *on-click*: ++ typeof: string ++ Command to execute when clicked on the module. *on-click-middle*: ++ typeof: string ++ Command to execute when middle-clicked on the module using mousewheel. *on-click-right*: ++ typeof: string ++ Command to execute when you right-click on the module. *on-update*: ++ typeof: string ++ Command to execute when the module is updated. *on-scroll-up*: ++ typeof: string ++ Command to execute when scrolling up on the module. This replaces the default behaviour of volume control. *on-scroll-down*: ++ typeof: string ++ Command to execute when scrolling down on the module. This replaces the default behaviour of volume control. *max-volume*: ++ typeof: float ++ default: 100 ++ The maximum volume that can be set, in percentage. *menu*: ++ typeof: string ++ Action that popups the menu. *menu-file*: ++ typeof: string ++ Location of the menu descriptor file. There need to be an element of type GtkMenu with id *menu* *menu-actions*: ++ typeof: array ++ The actions corresponding to the buttons of the menu. # FORMAT REPLACEMENTS *{volume}*: Volume in percentage. *{node_name}*: The node's nickname as reported by WirePlumber (*node.nick* property) # EXAMPLES ``` "wireplumber": { "format": "{volume}%", "format-muted": "", "on-click": "helvum" } ``` # STYLE - *#wireplumber* - *#wireplumber.muted* waybar-0.12.0/man/waybar-wlr-taskbar.5.scd000066400000000000000000000077531475603165300202320ustar00rootroot00000000000000waybar-wlr-taskbar(5) # NAME waybar - wlr taskbar module # DESCRIPTION The *taskbar* module displays the currently open applications. This module requires a compositor that implements the foreign-toplevel-manager interface. # CONFIGURATION Addressed by *wlr/taskbar* *all-outputs*: ++ typeof: bool ++ default: false ++ If set to false applications on the waybar's current output will be shown. Otherwise, all applications are shown. *format*: ++ typeof: string ++ default: {icon} ++ The format, how information should be displayed. *icon-theme*: ++ typeof: array|string ++ The names of the icon-themes that should be used to find an icon. The list will be traversed from left to right. If omitted, the system default will be used. *icon-size*: ++ typeof: integer ++ default: 16 ++ The size of the icon. *markup*: ++ typeof: bool ++ default: false ++ If set to true, pango markup will be accepted in format and tooltip-format. *tooltip*: ++ typeof: bool ++ default: true ++ If set to false no tooltip will be shown. *tooltip-format*: ++ typeof: string ++ default: {title} ++ The format, how information in the tooltip should be displayed. *active-first*: ++ typeof: bool ++ default: false ++ If set to true, always reorder the tasks in the taskbar so that the currently active one is first. Otherwise don't reorder. *sort-by-app-id*: ++ typeof: bool ++ default: false ++ If set to true, group tasks by their app_id. Cannot be used with 'active-first'. *on-click*: ++ typeof: string ++ The action which should be triggered when clicking on the application button with the left mouse button. *on-click-middle*: ++ typeof: string ++ The action which should be triggered when clicking on the application button with the middle mouse button. *on-click-right*: ++ typeof: string ++ The action which should be triggered when clicking on the application button with the right mouse button. *on-update*: ++ typeof: string ++ Command to execute when the module is updated. *ignore-list*: ++ typeof: array ++ List of app_id/titles to be invisible. *app_ids-mapping*: ++ typeof: object ++ Dictionary of app_id to be replaced with *rewrite*: ++ typeof: object ++ Rules to rewrite the module format output. See *rewrite rules*. # FORMAT REPLACEMENTS *{icon}*: The icon of the application. *{name}*: The application name as in desktop file if appropriate desktop files are found, otherwise same as {app_id} *{title}*: The title of the application. *{app_id}*: The app_id (== application name) of the application. *{state}*: The state (minimized, maximized, active, fullscreen) of the application. *{short_state}*: The state (minimize == m, maximized == M, active == A, fullscreen == F) represented as one character of the application. # CLICK ACTIONS *activate*: Bring the application into foreground. *minimize*: Toggle application's minimized state. *minimize-raise*: Bring the application into foreground or toggle its minimized state. *maximize*: Toggle application's maximized state. *fullscreen*: Toggle application's fullscreen state. *close*: Close the application. # 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 format output is left unchanged. Invalid expressions (e.g., mismatched parentheses) are skipped. # EXAMPLES ``` "wlr/taskbar": { "format": "{icon}", "icon-size": 14, "icon-theme": "Numix-Circle", "tooltip-format": "{title}", "on-click": "activate", "on-click-middle": "close", "ignore-list": [ "Alacritty" ], "app_ids-mapping": { "firefoxdeveloperedition": "firefox-developer-edition" }, "rewrite": { "Firefox Web Browser": "Firefox", "Foot Server": "Terminal" } } ``` # Style - *#taskbar* - *#taskbar button* - *#taskbar button.maximized* - *#taskbar button.minimized* - *#taskbar button.active* - *#taskbar button.fullscreen* waybar-0.12.0/man/waybar-wlr-workspaces.5.scd000066400000000000000000000037541475603165300207610ustar00rootroot00000000000000waybar-wlr-workspaces(5) # NAME waybar - wlr workspaces module # DESCRIPTION The *workspaces* module displays the currently used workspaces in wayland compositor. # CONFIGURATION Addressed by *wlr/workspaces* *format*: ++ typeof: string ++ default: {name} ++ The format, how information should be displayed. *format-icons*: ++ typeof: array ++ Based on the workspace name and state, the corresponding icon gets selected. See *icons*. *sort-by-name*: ++ typeof: bool ++ default: true ++ Should workspaces be sorted by name. *sort-by-coordinates*: ++ typeof: bool ++ default: true ++ 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*: ++ typeof: bool ++ default: false ++ If set to true, workspace names will be sorted numerically. Takes precedence over any other sort-by option. *all-outputs*: ++ typeof: bool ++ default: false ++ If set to false workspaces group will be shown only in assigned output. Otherwise, all workspace groups are shown. *active-only*: ++ typeof: bool ++ default: false ++ If set to true only active or urgent workspaces will be shown. # FORMAT REPLACEMENTS *{name}*: Name of workspace assigned by compositor *{icon}*: Icon, as defined in *format-icons*. # CLICK ACTIONS *activate*: Switch to workspace. *close*: Close the workspace. # ICONS In addition to workspace name matching, the following *format-icons* can be set. - *default*: Will be shown, when no string match is found. - *active*: Will be shown, when workspace is active # EXAMPLES ``` "wlr/workspaces": { "format": "{name}: {icon}", "format-icons": { "1": "", "2": "", "3": "", "4": "", "5": "", "active": "", "default": "" }, "sort-by-number": true } ``` # Style - *#workspaces* - *#workspaces button* - *#workspaces button.active* - *#workspaces button.urgent* - *#workspaces button.hidden* waybar-0.12.0/man/waybar.5.scd.in000066400000000000000000000255251475603165300164050ustar00rootroot00000000000000waybar(5) # NAME waybar - configuration file # DESCRIPTION The configuration uses the JSONC file format and is named *config* or *config.jsonc*. Valid locations for this file are: - *$XDG_CONFIG_HOME/waybar/* - *~/.config/waybar/* - *~/waybar/* - */etc/xdg/waybar/* - *@sysconfdir@/xdg/waybar/* 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. # BAR CONFIGURATION *expand-center* ++ typeof: bool ++ default: false ++ Enables the modules-center to consume all left over space dynamically. *expand-left* ++ typeof: bool ++ default: false ++ Enables the modules-left to consume all left over space dynamically. *expand-right* ++ typeof: bool ++ default: false ++ Enables the modules-left to consume all left over space dynamically. *layer* ++ typeof: string ++ default: bottom ++ Decide if the bar is displayed in front (*top*) of the windows or behind (*bottom*) them. *output* ++ typeof: string|array ++ Specifies on which screen this bar will be displayed. Exclamation mark(*!*) can be used to exclude specific output. Output specification follows sway's and can either be the output port such as "HDMI-A-1" or a string consisting of the make, model, and serial such as "Some Company ABC123 0x00000000". See *sway-output(5)* for details. In an array, star '*\**' can be used at the end to accept all outputs, in case all previous entries are exclusions. *position* ++ typeof: string ++ default: top ++ Bar position, can be *top*, *bottom*, *left*, *right*. *height* ++ typeof: integer ++ Height to be used by the bar if possible. Leave blank for a dynamic value. *width* ++ typeof: integer ++ Width to be used by the bar if possible. Leave blank for a dynamic value. *modules-left* ++ typeof: array ++ Modules that will be displayed on the left. *modules-center* ++ typeof: array ++ Modules that will be displayed in the center. *modules-right* ++ typeof: array Modules that will be displayed on the right. *margin* ++ typeof: string ++ Margins value using the CSS format without units. *margin-* ++ typeof: integer ++ Margins value without units. *no-center* ++ typeof: bool ++ default: false ++ Option to disable the center modules fully usefull together with expand-\*. *spacing* ++ typeof: integer ++ Size of gaps in between the different modules. *name* ++ typeof: string ++ Optional name added as a CSS class, for styling multiple waybars. *mode* ++ typeof: string ++ Selects one of the preconfigured display modes. This is an equivalent of the sway-bar(5) *mode* command and supports the same values: *dock*, *hide*, *invisible*, *overlay*. ++ Note: *hide* and *invisible* modes may be not as useful without Sway IPC. *start_hidden* ++ typeof: bool ++ default: *false* ++ Option to start the bar hidden. *modifier-reset* ++ typeof: string ++ default: *press* Defines the timing of modifier key to reset the bar visibility. To reset the visibility of the bar with the press of the modifier key use *press*. Use *release* to reset the visibility upon the release of the modifier key and only if no other action happened while the key was pressed. This prevents hiding the bar when the modifier is used to switch a workspace, change binding mode, or start a keybinding. *exclusive* ++ typeof: bool ++ default: *true* ++ Option to request an exclusive zone from the compositor. Disable this to allow drawing application windows underneath or on top of the bar. *fixed-center* ++ typeof: bool ++ default: *true* Prefer fixed center position for the `modules-center` block. The center block will stay in the middle of the bar whenever possible. It can still be pushed around if other blocks need more space. When false, the center block is centered in the space between the left and right block. *passthrough* ++ typeof: bool ++ default: *false* ++ Option to pass any pointer events to the window under the bar. Intended to be used with either *top* or *overlay* layers and without exclusive zone. *ipc* ++ typeof: bool ++ default: false ++ Option to subscribe to the Sway IPC bar configuration and visibility events and control waybar with *swaymsg bar* commands. ++ Requires *bar_id* value from sway configuration to be either passed with the *-b* command line argument or specified with the *id* option. *id* ++ typeof: string ++ *bar_id* for the Sway IPC. Use this if you need to override the value passed with the *-b bar_id* command line argument for the specific bar instance. *include* ++ typeof: string|array ++ Paths to additional configuration files. Each file can contain a single object with any of the bar configuration options. In case of duplicate options, the first defined value takes precedence, i.e. including file -> first included file -> etc. Nested includes are permitted, but make sure to avoid circular imports. For a multi-bar config, the include directive affects only current bar configuration object. *reload_style_on_change* ++ typeof: bool ++ default: *false* ++ Option to enable reloading the css style if a modification is detected on the style sheet file or any imported css files. # MODULE FORMAT You can use PangoMarkupFormat (See https://developer.gnome.org/pango/stable/PangoMarkupFormat.html#PangoMarkupFormat). e.g. ``` "format": "{}" ``` # MULTIPLE INSTANCES OF A MODULE If you want to have a second instance of a module, you can suffix it by a '#' and a custom name. For example, if you want a second battery module, you can add *"battery#bat2"* to your modules. To configure the newly added module, you then also add a module configuration with the same name. This could then look something like this *(this is an incomplete example)*: ``` "modules-right": ["battery", "battery#bat2"], "battery": { "bat": "BAT1" }, "battery#bat2": { "bat": "BAT2" } ``` # MINIMAL CONFIGURATION A minimal *config* file could look like this: ``` { "layer": "top", "modules-left": ["sway/workspaces", "sway/mode"], "modules-center": ["sway/window"], "modules-right": ["battery", "clock"], "sway/window": { "max-length": 50 }, "battery": { "format": "{capacity}% {icon}", "format-icons": ["", "", "", "", ""] }, "clock": { "format-alt": "{:%a, %d. %b %H:%M}" } } ``` # SIGNALS Waybar accepts the following signals: *SIGUSR1* Toggles the bar visibility (hides if shown, shows if hidden) *SIGUSR2* Reloads (resets) the bar *SIGINT* Quits the bar For example, to toggle the bar programmatically, you can invoke `killall -SIGUSR1 waybar`. # MULTI OUTPUT CONFIGURATION ## Limit a configuration to some outputs ``` { "layer": "top", "output": "eDP-1", "modules-left": ["sway/workspaces", "sway/mode"], ... } ``` ``` { "layer": "top", "output": ["eDP-1", "VGA"], "modules-left": ["sway/workspaces", "sway/mode"], ... } ``` ## Configuration of multiple outputs Don't specify an output to create multiple bars on the same screen. ``` [{ "layer": "top", "output": "eDP-1", "modules-left": ["sway/workspaces", "sway/mode"], ... }, { "layer": "top", "output": "VGA", "modules-right": ["clock"], ... }] ``` ## Rotating modules When positioning Waybar on the left or right side of the screen, sometimes it's useful to be able to rotate the contents of a module so the text runs vertically. This can be done using the "rotate" property of the module. Example: ``` { "clock": { "rotate": 90 } } ``` Valid options for the "rotate" property are: 0, 90, 180, and 270. ## 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. A module group is defined by specifying a module named "group/some-group-name". The group must also be configured with a list of contained modules. Example: ``` { "modules-right": ["group/hardware", "clock"], "group/hardware": { "orientation": "vertical", "modules": [ "cpu", "memory", "battery" ] }, ... } ``` Valid options for the (optional) "orientation" property are: "horizontal", "vertical", "inherit", and "orthogonal" (default). ## Group Drawers A group may hide all but one element, showing them only on mouse hover. In order to configure this, you can use the `drawer` property, whose value is an object with the following properties: *transition-duration*: ++ typeof: integer ++ default: 500 ++ Defines the duration of the transition animation in milliseconds. *children-class*: ++ typeof: string ++ default: "hidden" ++ Defines the CSS class to be applied to the hidden elements. *click-to-reveal*: ++ typeof: bool ++ 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. *transition-left-to-right*: ++ typeof: bool ++ default: true ++ Defines the direction of the transition animation. If true, the hidden elements will slide from left to right. If false, they will slide from right to left. When the bar is vertical, it reads as top-to-bottom. ``` "group/power": { "orientation": "inherit", "drawer": { "transition-duration": 500, "children-class": "not-power", "transition-left-to-right": false, }, "modules": [ "custom/power", // First element is the "group leader" and won't ever be hidden "custom/quit", "custom/lock", "custom/reboot", ] }, ``` # SUPPORTED MODULES - *waybar-backlight(5)* - *waybar-battery(5)* - *waybar-bluetooth(5)* - *waybar-cava(5)* - *waybar-clock(5)* - *waybar-cpu(5)* - *waybar-custom(5)* - *waybar-disk(5)* - *waybar-dwl-tags(5)* - *waybar-dwl-window(5)* - *waybar-gamemode(5)* - *waybar-hyprland-language(5)* - *waybar-hyprland-submap(5)* - *waybar-hyprland-window(5)* - *waybar-hyprland-workspaces(5)* - *waybar-niri-language(5)* - *waybar-niri-window(5)* - *waybar-niri-workspaces(5)* - *waybar-idle-inhibitor(5)* - *waybar-image(5)* - *waybar-inhibitor(5)* - *waybar-jack(5)* - *waybar-keyboard-state(5)* - *waybar-memory(5)* - *waybar-mpd(5)* - *waybar-mpris(5)* - *waybar-network(5)* - *waybar-pulseaudio(5)* - *waybar-river-layout(5)* - *waybar-river-mode(5)* - *waybar-river-tags(5)* - *waybar-river-window(5)* - *waybar-sndio(5)* - *waybar-states(5)* - *waybar-sway-language(5)* - *waybar-sway-mode(5)* - *waybar-sway-scratchpad(5)* - *waybar-sway-window(5)* - *waybar-sway-workspaces(5)* - *waybar-temperature(5)* - *waybar-tray(5)* - *waybar-upower(5)* - *waybar-wireplumber(5)* - *waybar-wlr-taskbar(5)* - *waybar-wlr-workspaces(5)* # SEE ALSO *sway-output(5)* *waybar-styles(5)" waybar-0.12.0/meson.build000066400000000000000000000445551475603165300152500ustar00rootroot00000000000000project( 'waybar', 'cpp', 'c', version: '0.12.0', license: 'MIT', meson_version: '>= 0.59.0', default_options : [ 'cpp_std=c++20', 'buildtype=release', 'default_library=static' ], ) compiler = meson.get_compiler('cpp') cpp_args = [] cpp_link_args = [] if get_option('libcxx') cpp_args += ['-stdlib=libc++'] cpp_link_args += ['-stdlib=libc++', '-lc++abi'] endif if compiler.has_link_argument('-lc++fs') cpp_link_args += ['-lc++fs'] elif compiler.has_link_argument('-lstdc++fs') cpp_link_args += ['-lstdc++fs'] endif git = find_program('git', native: true, required: false) if not git.found() add_project_arguments('-DVERSION="@0@"'.format(meson.project_version()), language: 'cpp') else git_path = run_command(git, 'rev-parse', '--show-toplevel', check: false).stdout().strip() if meson.project_source_root() == git_path git_commit_hash = run_command(git, 'describe', '--always', '--tags', check: false).stdout().strip() git_branch = run_command(git, 'rev-parse', '--abbrev-ref', 'HEAD', check: false).stdout().strip() version = '"@0@ (branch \'@1@\')"'.format(git_commit_hash, git_branch) add_project_arguments('-DVERSION=@0@'.format(version), language: 'cpp') else add_project_arguments('-DVERSION="@0@"'.format(meson.project_version()), language: 'cpp') endif endif code = ''' #include #include int main(int argc, char** argv) { locale_t locale = newlocale(LC_ALL, "en_US.UTF-8", nullptr); char* str; str = nl_langinfo_l(_NL_TIME_WEEK_1STDAY, locale); str = nl_langinfo_l(_NL_TIME_FIRST_WEEKDAY, locale); freelocale(locale); return 0; } ''' if compiler.links(code, name : 'nl_langinfo with _NL_TIME_WEEK_1STDAY, _NL_TIME_FIRST_WEEKDAY') add_project_arguments('-DHAVE_LANGINFO_1STDAY', language: 'cpp') endif add_global_arguments(cpp_args, language : 'cpp') add_global_link_arguments(cpp_link_args, language : 'cpp') is_linux = host_machine.system() == 'linux' is_dragonfly = host_machine.system() == 'dragonfly' is_freebsd = host_machine.system() == 'freebsd' is_netbsd = host_machine.system() == 'netbsd' 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']) wayland_client = dependency('wayland-client') wayland_cursor = dependency('wayland-cursor') wayland_protos = dependency('wayland-protocols') gtkmm = dependency('gtkmm-3.0', version : ['>=3.22.0']) dbusmenu_gtk = dependency('dbusmenu-gtk3-0.4', required: get_option('dbusmenu-gtk')) giounix = dependency('gio-unix-2.0') jsoncpp = dependency('jsoncpp', version : ['>=1.9.2'], fallback : ['jsoncpp', 'jsoncpp_dep']) sigcpp = dependency('sigc++-2.0') libinotify = dependency('libinotify', required: false) libepoll = dependency('epoll-shim', required: false) libinput = dependency('libinput', required: get_option('libinput')) libnl = dependency('libnl-3.0', required: get_option('libnl')) libnlgen = dependency('libnl-genl-3.0', required: get_option('libnl')) upower_glib = dependency('upower-glib', required: get_option('upower_glib')) pipewire = dependency('libpipewire-0.3', required: get_option('pipewire')) playerctl = dependency('playerctl', version : ['>=2.0.0'], required: get_option('mpris')) libpulse = dependency('libpulse', required: get_option('pulseaudio')) libudev = dependency('libudev', required: get_option('libudev')) libevdev = dependency('libevdev', required: get_option('libevdev')) 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')) libsndio = compiler.find_library('sndio', required: get_option('sndio')) if libsndio.found() if not compiler.has_function('sioctl_open', prefix: '#include ', dependencies: libsndio) if get_option('sndio').enabled() error('libsndio is too old, required >=1.7.0') else warning('libsndio is too old, required >=1.7.0') libsndio = dependency('', required: false) endif endif endif gtk_layer_shell = dependency('gtk-layer-shell-0', version: ['>=0.9.0'], default_options: ['introspection=false', 'vapi=false'], fallback: ['gtk-layer-shell', 'gtk_layer_shell']) systemd = dependency('systemd', required: get_option('systemd')) cpp_lib_chrono = compiler.compute_int('__cpp_lib_chrono', prefix : '#include ') have_chrono_timezones = cpp_lib_chrono >= 201611 if have_chrono_timezones code = ''' #include using namespace std::chrono; int main(int argc, char** argv) { const time_zone* tz; return 0; } ''' if not compiler.links(code) have_chrono_timezones = false endif endif if have_chrono_timezones tz_dep = declare_dependency() else tz_dep = dependency('date', required: false, default_options : [ 'use_system_tzdb=true' ], modules : [ 'date::date', 'date::date-tz' ], fallback: [ 'date', 'tz_dep' ]) endif prefix = get_option('prefix') sysconfdir = get_option('sysconfdir') conf_data = configuration_data() conf_data.set('prefix', prefix) add_project_arguments('-DSYSCONFDIR="@0@"'.format(prefix / sysconfdir), language : 'cpp') if systemd.found() user_units_dir = systemd.get_variable(pkgconfig: 'systemduserunitdir') configure_file( configuration: conf_data, input: './resources/waybar.service.in', output: '@BASENAME@', install_dir: user_units_dir ) endif src_files = files( 'src/factory.cpp', 'src/AModule.cpp', 'src/ALabel.cpp', 'src/AIconLabel.cpp', 'src/AAppIconLabel.cpp', 'src/modules/custom.cpp', 'src/modules/disk.cpp', 'src/modules/idle_inhibitor.cpp', 'src/modules/image.cpp', 'src/modules/load.cpp', 'src/modules/temperature.cpp', 'src/modules/user.cpp', 'src/ASlider.cpp', 'src/main.cpp', 'src/bar.cpp', 'src/client.cpp', 'src/config.cpp', 'src/group.cpp', 'src/util/portal.cpp', 'src/util/enum.cpp', 'src/util/prepare_for_sleep.cpp', 'src/util/ustring_clen.cpp', 'src/util/sanitize_str.cpp', 'src/util/rewrite_string.cpp', 'src/util/gtk_icon.cpp', 'src/util/regex_collection.cpp', 'src/util/css_reload_helper.cpp' ) man_files = files( 'man/waybar-custom.5.scd', 'man/waybar-disk.5.scd', 'man/waybar-idle-inhibitor.5.scd', 'man/waybar-image.5.scd', 'man/waybar-states.5.scd', 'man/waybar-menu.5.scd', 'man/waybar-temperature.5.scd', ) inc_dirs = ['include'] if is_linux add_project_arguments('-DHAVE_CPU_LINUX', language: 'cpp') add_project_arguments('-DHAVE_MEMORY_LINUX', language: 'cpp') add_project_arguments('-DHAVE_SYSTEMD_MONITOR', language: 'cpp') src_files += files( 'src/modules/battery.cpp', 'src/modules/bluetooth.cpp', 'src/modules/cffi.cpp', 'src/modules/cpu.cpp', 'src/modules/cpu_frequency/common.cpp', 'src/modules/cpu_frequency/linux.cpp', 'src/modules/cpu_usage/common.cpp', 'src/modules/cpu_usage/linux.cpp', 'src/modules/memory/common.cpp', 'src/modules/memory/linux.cpp', 'src/modules/power_profiles_daemon.cpp', 'src/modules/systemd_failed_units.cpp', ) man_files += files( 'man/waybar-battery.5.scd', 'man/waybar-bluetooth.5.scd', 'man/waybar-cffi.5.scd', 'man/waybar-cpu.5.scd', 'man/waybar-memory.5.scd', 'man/waybar-systemd-failed-units.5.scd', 'man/waybar-power-profiles-daemon.5.scd', ) elif is_dragonfly or is_freebsd or is_netbsd or is_openbsd add_project_arguments('-DHAVE_CPU_BSD', language: 'cpp') add_project_arguments('-DHAVE_MEMORY_BSD', language: 'cpp') src_files += files( 'src/modules/cffi.cpp', 'src/modules/cpu.cpp', 'src/modules/cpu_frequency/bsd.cpp', 'src/modules/cpu_frequency/common.cpp', 'src/modules/cpu_usage/bsd.cpp', 'src/modules/cpu_usage/common.cpp', 'src/modules/memory/bsd.cpp', 'src/modules/memory/common.cpp', ) man_files += files( 'man/waybar-cffi.5.scd', 'man/waybar-cpu.5.scd', 'man/waybar-memory.5.scd', ) if is_freebsd src_files += files('src/modules/battery.cpp') man_files += files('man/waybar-battery.5.scd') endif endif if true add_project_arguments('-DHAVE_SWAY', language: 'cpp') src_files += files( 'src/modules/sway/ipc/client.cpp', 'src/modules/sway/bar.cpp', 'src/modules/sway/mode.cpp', 'src/modules/sway/language.cpp', 'src/modules/sway/window.cpp', 'src/modules/sway/workspaces.cpp', 'src/modules/sway/scratchpad.cpp' ) man_files += files( 'man/waybar-sway-language.5.scd', 'man/waybar-sway-mode.5.scd', 'man/waybar-sway-scratchpad.5.scd', 'man/waybar-sway-window.5.scd', 'man/waybar-sway-workspaces.5.scd', ) endif if true add_project_arguments('-DHAVE_WLR_TASKBAR', language: 'cpp') src_files += files('src/modules/wlr/taskbar.cpp') man_files += files('man/waybar-wlr-taskbar.5.scd') endif if true add_project_arguments('-DHAVE_RIVER', language: 'cpp') src_files += files( 'src/modules/river/layout.cpp', 'src/modules/river/mode.cpp', 'src/modules/river/tags.cpp', 'src/modules/river/window.cpp', ) man_files += files( 'man/waybar-river-layout.5.scd', 'man/waybar-river-mode.5.scd', 'man/waybar-river-tags.5.scd', 'man/waybar-river-window.5.scd', ) endif if true add_project_arguments('-DHAVE_DWL', language: 'cpp') src_files += files('src/modules/dwl/tags.cpp') src_files += files('src/modules/dwl/window.cpp') man_files += files('man/waybar-dwl-tags.5.scd') man_files += files('man/waybar-dwl-window.5.scd') endif if true add_project_arguments('-DHAVE_HYPRLAND', language: 'cpp') src_files += files( 'src/modules/hyprland/backend.cpp', 'src/modules/hyprland/language.cpp', 'src/modules/hyprland/submap.cpp', 'src/modules/hyprland/window.cpp', 'src/modules/hyprland/workspace.cpp', 'src/modules/hyprland/workspaces.cpp', 'src/modules/hyprland/windowcreationpayload.cpp', ) man_files += files( 'man/waybar-hyprland-language.5.scd', 'man/waybar-hyprland-submap.5.scd', 'man/waybar-hyprland-window.5.scd', 'man/waybar-hyprland-workspaces.5.scd', ) endif if get_option('niri') add_project_arguments('-DHAVE_NIRI', language: 'cpp') src_files += files( 'src/modules/niri/backend.cpp', 'src/modules/niri/language.cpp', 'src/modules/niri/window.cpp', 'src/modules/niri/workspaces.cpp', ) man_files += files( 'man/waybar-niri-language.5.scd', 'man/waybar-niri-window.5.scd', 'man/waybar-niri-workspaces.5.scd', ) endif if libnl.found() and libnlgen.found() add_project_arguments('-DHAVE_LIBNL', language: 'cpp') src_files += files('src/modules/network.cpp') man_files += files('man/waybar-network.5.scd') endif if not get_option('logind').disabled() add_project_arguments('-DHAVE_GAMEMODE', '-DHAVE_LOGIND_INHIBITOR', language: 'cpp') src_files += files( 'src/modules/gamemode.cpp', 'src/modules/inhibitor.cpp', ) man_files += files( 'man/waybar-gamemode.5.scd', 'man/waybar-inhibitor.5.scd', ) endif if (upower_glib.found() and not get_option('logind').disabled()) add_project_arguments('-DHAVE_UPOWER', language: 'cpp') src_files += files('src/modules/upower.cpp') man_files += files('man/waybar-upower.5.scd') endif if pipewire.found() add_project_arguments('-DHAVE_PIPEWIRE', language: 'cpp') src_files += files( 'src/modules/privacy/privacy.cpp', 'src/modules/privacy/privacy_item.cpp', 'src/util/pipewire/pipewire_backend.cpp', 'src/util/pipewire/privacy_node_info.cpp', ) man_files += files('man/waybar-privacy.5.scd') endif if playerctl.found() add_project_arguments('-DHAVE_MPRIS', language: 'cpp') src_files += files('src/modules/mpris/mpris.cpp') man_files += files('man/waybar-mpris.5.scd') endif if libpulse.found() add_project_arguments('-DHAVE_LIBPULSE', language: 'cpp') src_files += files( 'src/modules/pulseaudio.cpp', 'src/modules/pulseaudio_slider.cpp', 'src/util/audio_backend.cpp', ) man_files += files( 'man/waybar-pulseaudio.5.scd', 'man/waybar-pulseaudio-slider.5.scd', ) endif if libjack.found() add_project_arguments('-DHAVE_LIBJACK', language: 'cpp') src_files += files('src/modules/jack.cpp') man_files += files('man/waybar-jack.5.scd') endif if libwireplumber.found() add_project_arguments('-DHAVE_LIBWIREPLUMBER', language: 'cpp') src_files += files('src/modules/wireplumber.cpp') man_files += files('man/waybar-wireplumber.5.scd') endif if dbusmenu_gtk.found() add_project_arguments('-DHAVE_DBUSMENU', language: 'cpp') src_files += files( 'src/modules/sni/tray.cpp', 'src/modules/sni/watcher.cpp', 'src/modules/sni/host.cpp', 'src/modules/sni/item.cpp' ) man_files += files( 'man/waybar-tray.5.scd', ) endif if libudev.found() and (is_linux or libepoll.found()) add_project_arguments('-DHAVE_LIBUDEV', language: 'cpp') src_files += files( 'src/modules/backlight.cpp', 'src/modules/backlight_slider.cpp', 'src/util/backlight_backend.cpp', ) man_files += files( 'man/waybar-backlight.5.scd', 'man/waybar-backlight-slider.5.scd', ) endif if libevdev.found() and (is_linux or libepoll.found()) and libinput.found() and (is_linux or libinotify.found()) add_project_arguments('-DHAVE_LIBEVDEV', language: 'cpp') add_project_arguments('-DHAVE_LIBINPUT', language: 'cpp') src_files += files('src/modules/keyboard_state.cpp') man_files += files('man/waybar-keyboard-state.5.scd') endif if libmpdclient.found() add_project_arguments('-DHAVE_LIBMPDCLIENT', language: 'cpp') src_files += files( 'src/modules/mpd/mpd.cpp', 'src/modules/mpd/state.cpp', ) man_files += files( 'man/waybar-mpd.5.scd', ) endif if libsndio.found() add_project_arguments('-DHAVE_LIBSNDIO', language: 'cpp') src_files += files('src/modules/sndio.cpp') man_files += files('man/waybar-sndio.5.scd') endif if get_option('rfkill').enabled() and is_linux add_project_arguments('-DWANT_RFKILL', language: 'cpp') src_files += files( 'src/util/rfkill.cpp' ) endif if have_chrono_timezones add_project_arguments('-DHAVE_CHRONO_TIMEZONES', language: 'cpp') src_files += files('src/modules/clock.cpp') man_files += files('man/waybar-clock.5.scd') elif tz_dep.found() add_project_arguments('-DHAVE_LIBDATE', language: 'cpp') src_files += files('src/modules/clock.cpp') man_files += files('man/waybar-clock.5.scd') else src_files += files('src/modules/simpleclock.cpp') 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.3', required: get_option('cava'), fallback : ['cava', 'cava_dep'], not_found_message: 'cava is not found. Building waybar without cava') if cava.found() add_project_arguments('-DHAVE_LIBCAVA', language: 'cpp') src_files += files('src/modules/cava.cpp') man_files += files('man/waybar-cava.5.scd') endif subdir('protocol') app_resources = [] subdir('resources/icons') executable( 'waybar', [src_files, app_resources], dependencies: [ thread_dep, client_protos, wayland_client, fmt, spdlog, sigcpp, jsoncpp, wayland_cursor, gtkmm, dbusmenu_gtk, giounix, libinput, libnl, libnlgen, upower_glib, pipewire, playerctl, libpulse, libjack, libwireplumber, libudev, libinotify, libepoll, libmpdclient, libevdev, gtk_layer_shell, libsndio, tz_dep, xkbregistry, cava ], include_directories: inc_dirs, install: true, ) install_data( 'resources/config.jsonc', 'resources/style.css', install_dir: sysconfdir / 'xdg/waybar' ) scdoc = dependency('scdoc', version: '>=1.9.2', native: true, required: get_option('man-pages')) if scdoc.found() man_files += configure_file( input: 'man/waybar.5.scd.in', output: 'waybar.5.scd', configuration: { 'sysconfdir': prefix / sysconfdir } ) man_files += configure_file( input: 'man/waybar-styles.5.scd.in', output: 'waybar-styles.5.scd', configuration: { 'sysconfdir': prefix / sysconfdir } ) fs = import('fs') mandir = get_option('mandir') foreach file : man_files basename = fs.name(file) topic = basename.split('.')[-3] section = basename.split('.')[-2] output = '@0@.@1@'.format(topic, section) custom_target( output, input: file, output: output, command: scdoc.get_variable('scdoc'), feed: true, capture: true, install: true, install_dir: '@0@/man@1@'.format(mandir, section) ) endforeach endif catch2 = dependency( 'catch2', default_options: [ 'tests=false' ], fallback: ['catch2', 'catch2_dep'], required: get_option('tests'), ) if catch2.found() subdir('test') endif clangtidy = find_program('clang-tidy', required: false) if clangtidy.found() run_target( 'tidy', command: [ clangtidy, '-checks=*,-fuchsia-default-arguments', '-p', meson.project_build_root() ] + src_files) endif waybar-0.12.0/meson_options.txt000066400000000000000000000041671475603165300165360ustar00rootroot00000000000000option('libcxx', type : 'boolean', value : false, description : 'Build with Clang\'s libc++ instead of libstdc++ on Linux.') option('libinput', type: 'feature', value: 'auto', description: 'Enable libinput support for libinput related features') option('libnl', type: 'feature', value: 'auto', description: 'Enable libnl support for network related features') option('libudev', type: 'feature', value: 'auto', description: 'Enable libudev support for udev related features') option('libevdev', type: 'feature', value: 'auto', description: 'Enable libevdev support for evdev related features') option('pulseaudio', type: 'feature', value: 'auto', description: 'Enable support for pulseaudio') option('upower_glib', type: 'feature', value: 'auto', description: 'Enable support for upower') option('pipewire', type: 'feature', value: 'auto', description: 'Enable support for pipewire') option('mpris', type: 'feature', value: 'auto', description: 'Enable support for mpris') option('systemd', type: 'feature', value: 'auto', description: 'Install systemd user service unit') option('dbusmenu-gtk', type: 'feature', value: 'auto', description: 'Enable support for tray') 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('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') option('jack', type: 'feature', value: 'auto', description: 'Enable support for JACK') option('wireplumber', type: 'feature', value: 'auto', description: 'Enable support for WirePlumber') option('cava', type: 'feature', value: 'auto', description: 'Enable support for Cava') option('niri', type: 'boolean', description: 'Enable support for niri') waybar-0.12.0/nix/000077500000000000000000000000001475603165300136675ustar00rootroot00000000000000waybar-0.12.0/nix/default.nix000066400000000000000000000016501475603165300160350ustar00rootroot00000000000000{ lib , pkgs , waybar , version }: let libcava = rec { version = "0.10.3"; src = pkgs.fetchFromGitHub { owner = "LukashonakV"; repo = "cava"; rev = version; hash = "sha256-ZDFbI69ECsUTjbhlw2kHRufZbQMu+FQSMmncCJ5pagg="; }; }; in (waybar.overrideAttrs ( oldAttrs: { inherit version; src = lib.cleanSourceWith { filter = name: type: type != "regular" || !lib.hasSuffix ".nix" name; src = lib.cleanSource ../.; }; mesonFlags = lib.remove "-Dgtk-layer-shell=enabled" oldAttrs.mesonFlags; # downstream patch should not affect upstream patches = []; buildInputs = (builtins.filter (p: p.pname != "wireplumber") oldAttrs.buildInputs) ++ [ pkgs.wireplumber ]; postUnpack = '' pushd "$sourceRoot" cp -R --no-preserve=mode,ownership ${libcava.src} subprojects/cava-${libcava.version} patchShebangs . popd ''; } )) waybar-0.12.0/package/000077500000000000000000000000001475603165300144645ustar00rootroot00000000000000waybar-0.12.0/package/archlinux/000077500000000000000000000000001475603165300164615ustar00rootroot00000000000000waybar-0.12.0/preview-2.png000066400000000000000000000124731475603165300154260ustar00rootroot00000000000000PNG  IHDRI\PLTE$<#:%=$: %<%< &=f̙)$;dr}BL\#;$:Y.q%;$="9AK\ &>#<!:!=$<";BL]@K]#<8;9AK[9!'> ;>GZ*\E/fLbœ<~^U_7dɖt@Di3nSIq  /OyYoB___~ppp 3#69FkWc-bI*iݴ ϰܙ<1쐽Ϩ +_Go{ */CXG'`%=KmlV0xM[ɻ PTaTǡc#W]cx̢ IDATx [p@DvY rG*ZmW[Z>睙IfͱJ9W:bD1V9C,$1J eTCVs c‚9Cu)&)=C9ޱ{X)BO-M@x<|h~d0mqp7bD{,58hFWml΄ Z㬃hv뀽MqO``^mU砳v`; `S-j{iQ7Xq`@}p'ޚЫDM_N3>)58lVH1jd+gXN~ 6l&{ wfsO3z:FKFJI[nE6Np =$pNv6-a9Dzu8󋷼C~gixwwyY{ /$D7F_Oѣ;?`4}%v+< ucA1Ԉ}ϊmM^'a(rzקS#O}_+jR@Jg.PR0V-$-G`v`6Io+Z0%L0%#!]]XWtލzMdv_Cع˹`ky|>痚p/N /k#u[!-oG]eYf2 w.`܎톮Eϼ/ /g޻\WQ+-U~N|0wB^/QX@f1"]+>'sH! "`d: /tcY0SI*軀hū} >Jk ]ka-iS9zj`C0~^_^Ǿ|;???wB0 2=1pY>^kˮhEȂRT[ =!3b i-Ί3"g{jt2 )0DAYHUSsCj5ITÍep$N"\*Fn&sxe(;U?Ocd ,i.,T)A+Aϐ6*vw``cR˺|YL1oT z|^r8v1~FEC| ł|h ]ZLlG(F 7\JDײp &JP|n T/={n.@{?|韫7Wb}j[!%3]qm^ٖ2xʊlYP^z%-pFhWDq+bjT#@Y5%:!_eGO%s@*\ C$⍇q d2>)p..GR`Ox* څ ؏qA\efLR2^lfw:"]R(SomWV5]D ¼gcQ/`Z̔QӞN\Nx N<~xP>_x?x)7Kl8[cF]Zk,͢8:-BQFq m݃:# pvv'[oVo>G3 3 !ho0R˕0,>[6O] |tQpp /g>+Y}IHˁ,nW,C|kޑp:N9?)֝H7Jp2Jt@w.s'(P Sa076H+=N.><d{XBCܚat :NhܜBpmp/{MJӐ;A V|-]Tߦ`xB,T9 -Z?lb?uP|=ّ ]oXjhi^;J, oX,Q䳰Rb4&9] uR^A&6E]]XQ7-]GPKqyxt3ifu[BWBϕBLx{4^c12 P lRY]עE!>!^|Q8$p%P ωmW^Ꞇ`ZXšHOaucFQ5-v k9N&2*cDQ#֏?B?@VH[rP-T)F:Dw],4UX!^$ po:rvӯ^)  4*B4JN":I9q0<sx.hg!p ^pK(_܃a*hc$ I D2ҠYn MWתT@5)dp?%20`Pm4N|v gk{ ]d94u=( o16eu+ b Zԧ3X`+ ܽK$K8`F|-p;WD]g0Ţs~@ ?f2<+ ?!aW6F, cg,߳ZeEׅ8ߊ<ѷ8-`$|8`% C~sq4$6~I+l5/lޯƌdWc`ʪsWqZ3sJar,Qԙr.޴!Uuή?#Q۰Oc٠٩߀u`m;;،C `)bB8: TΒdrqckGҔj ?5a|Cm]r)Jл50< Khr(2둿4HYFiSZ_n9cشA h ?Lpw `5Emf43g x@{`q 4US>p ?>>)< .ܗ%ha0ᵘ‚a&s0poE?`NL>e o{~PPW{0< `ƳxYF CFV'0spܠn-[<,Ħ- =$<066-_R ,z3'Vr5_<6qk-Uǫ!`@0*CP0 CP0s:C0 CpL߇!`@0]\4IJߴ2']fM+QϟXE>8ݾL|Ms;4?9g.QƷY+$XB1ˎW x_ e_G{JR$)lj' \RP?Z}Ar1MvjH==LQ痖%JbI cMϨ"Nn*'Z9Vg+{~[|IDEmZ)-TB/$`>;Mo*lDz" w|u,K.&7C!14l XvْZUz. ɶ/4tUY?JEM}؜{& VANb^To߈~I꼛,.*\椥Dyf)ޔY V^?D*\LvꄦlWt*}N-І /?~7F*x*zXT'}z!j%7Zxo>: 0zr讵{*jd4uT[.5ֈEGҥ >],B3E1AOPi *έhEҬ^kw]:L?O4+=+GiU]:YO6\O.!`8K Oݾ#6o3j5z ӪNu61~=o?lr\+9w 3jڍ)2ZLݾn? `J"B_KXbO}6wQx?Lo3jGfWZޣ&`hBCIuM?iLki3 q#i8?;sMohʻYPR9?GǣXʊ=b O֠{ҮfrdO&p:g9SB]s=Mk9HA,`xAz<.%J8A{y`N]8Tq3< e`fvpkWxjI7nmkr5ӹlTcaLuj)mxA뉧n %79_ >}E]t| [w}{0 -xaCMV'JIcq9r?dHz(lynS$XKj-'~7*Z^d/1O M/l;5t DzJfTKXtvޣ%_{$Tt|{J,_Wh6fx{RUXUxۈ Xb T ֩+* Fժ2ƀPj,?Qc *:Csp~4y<^p [dj a%(6I_~u_eҦόD/ȷAu0Ͷ-K |\Y\Vb0Yj/zD}^T8W8J%( ë_^䊦I*\uPL㧱>/D8ק־ERgORV{{g&`r>}?]` j[Dg@]jW4Y`Fh^)gRZ%X 8AEmjs]" Xm|JI `Ue,TTKzj(ˆ4R-ٰkȮPQ_n5vsO}z_o_q4T"W㧱>/WI% XlL}0wTh1%-Wi4W*0/@ׯYxQ^iT4TV:+b o3Im֫$5 `Ҥјۧ XHbPQ[TjI?Tp-kjFiOu"T%%@+_(Cω^B}&1huN/^tUue%'Q5m 7ɞ/cHHƠ\U*mx|>4yުgxp*5Ҷ(YB6 N`bCANܧO0!` q0"xSa0tj7H8!`I 0HuQ?$%"U `,N~c!vP[y Xt d sZUtJ_0: n! Zļ `+00b9C $&7 q<YcrԼ Sakvv *eȢ[;y;p.9$3dN]|}m2@v3fOF/แR͌ t x&\Bs2&%V5c d\3dmxG^>]F1en_g>Rlwy%~QM[+uכ_K;貧F#=<n? _]{>_>>:6: '`㯩{?ϡR/ u# e߾>\-g~y7?/?kI]x 6tIg߿>wC_~,z}3v cwbܽ^rp$'/aK/N|6rlC'mo$ixAFM@-MYs ΙJlɥ=#8oDPvDD% ԜαHK/ iW׏|9"NQd<׍)r;څ|`s. iw;:E`UKCZTjUPCJ#1,$'֛Yg Ҕ.AUUr+ jKonumVmt> G-OLf-[ MK'lJ2x|SԨaԘ^06$`OAw4h7֧& E"b|+H ^NyQb EjVX>Z6v7 ƠIu#fwF]EqӶ+aez##$\U{Thf+u[f3`\kU'vqܻD'`kVȦmy٭f b݆^Ӣ/KnTmEҊV7L,ʱASK{M [\c8͊u ӠLE QIg QoL߳U-k`jRxz?-< /+WV~{x8FDbi 9:We3ێ>)M4g V3ÝDrTĎoQ]xK7EZ(h̓ZdTt;GDsNn|tӷX׹Vac0pլLbuǒF"FF[&OvuNJ=[ [ɕjTsU-ʤO[ly8`\+40[2qlDƾː,%33:VHKGRKjES:bvwE#>)ꖊ[蔀}n usٳQ"Tm)2{Z&dV͋ujٌs=b&a6WYU,d:̤p_.76[f|+vcЫ݈x4;bLeRk 8KjGp-Y5ERӶ][rIM xҍ_\15L#pSK3A] , II_IYWefD5d&L,ݺi*QF]4| 7-熬[upoE=X?7qgQ6}"B['ݻ*Q3\ǡWxC{0?г0Q4aY JaBBpNWū x>rJH,-U!`x z*7(H?3in>FU^k ~j^GȺNt-@mzxuc8`pb 뗀!  ``D`TK3TW*y z l"Wy)8`X# _UB=/B v/ `$`k `0{5= 8LpcHܳWA?qV#l?WT~{O#s 1czb[֥ߡ޹-8$v0 ` <kכA#ϡs0 Oʳͷ5] =;~?_$\2B#BvGlYllU\j?7 ر/%PU5{{h2ʪ(!Lkӷ3Oboƻ~;\M_7{ :>>Y .8'błoߟ#Q~2$w.’.nf0,=hwv?3 ߄& Wzӭ. ɡo mb /GS0%(lP]܅禸Pkg:A^'8`8bWg]Wͫf &- ZelY' 꾵׬xlݱl2)jH="F(T&Z,h:!мJWՂ-mGj%jUqB.VuŚYKk'HVV#9S}YM{j6sm2RO䴌u[j -fN"JΔe8(oTGp11|>>~QbX~;\·Iïכy7#pȘcyMZ}*-JZ-NK]*L{0-qZM"5-]"b&Fî: KTcV=m+$6fU+Dh(6FR'LfQ!d,U4Q2f]L$;ĈZ#IUK5Uλ./~Lx䛃wAe_IesSWj `q\s>=ӄ+R0]4`>ZuD Xdj3gW$RGJQ[H!RtH4ƪoZe}) |U)-1BKp\$bge()_#$SqStvd/E4`͈(rF$DJ#oӛ mh;_J¢|8.wAFtn% x9 \KhȀ@:%6z ,B {oDu-U2A*_7۰lۖhn{Ӗm m2* iæe<efto?H%"A=\7K!`a25oD6 ߸'$,/&NI~f`fwaaXi&$ Xp!$`.`;:cZ}ţ6|H8^YD[dhʷ0YHQ 캲P8U eOHĬdnjk_ ֎MI|a3~{,أf*^x!"nC!MSz҄l5~wA_Yb _,r6f+u_ƙ13Kkynff7Bߨv[gM~ zh9Q<9ZDE+؄]e5h(ۃ J3 RX>I+CX$* T̯0FqjY_ rP}c[;S|ojs 3>,?s',M9=Q 㣠2]$nl!WZ8~'r'p02>B*lu6퓘B "م ,}͂lAXժBwӤ˹-0o,4F_sij994żemmBhRv|-Sf3#j7/FB:ՐܟoGxBz .<  ؞-茩(Tb`ëƟ98T40~pSp~/8ڋϐAc %&+:!ҟ k}z^{.||xLX(`"0 ,Ro`$``Y%AX0>W]-Uvo. Pl U) 5- `t|R.@y׀#L)00 ̿5a"њylvTL9^}#M]@`Adqp( N:1af!` 』(Jcʮ_Xx6բXHiTxsq X@s[a``YW0l,F ES*x# N\&ٕ <6noKߕ- ׀WZ_M胆q_SA Dž_uB, kVi-{?ZO0/W4i#6يd˪fҴik$awrl_4 k%R"IvY7r!^, $h̴gA,Zςb; o°N!՜ dϳ6V-fj@s-iZI+;}pw|?)n3rBiC4W~)̒;/8.H>?葆}r*rfo&Ia˜%C7=c]OY 9Q8b Yh}:#w,`9vcbs%ۯSL=mYc;hPᲚ$]??]Ћ$` [a[]{̒7tAdxZJޠW]ХfOw\z<~nlRӈ{ 4f*JCE2pv-D*詀*9{j/wAJX-u[TAaźJ 8d̯$3*|4aM[F+:"3LҵB6Iq;h[Af xy;6U,zy"]9Ka]^E!N2Gf!_.N5F8^uAak_1H| 6-|*!Uӈ/&vĉ8^wA `VG&슀R,UJ x2^i{W]z+TEXq;Ly|`luvZ#>[X_EEU!Yć!2b/ IT:M`km, A,2pfj_8%"qQ-\? n^n;\ '-?ڤ4<<NE'c_N&!Ǘ !Qǘ?Kw.`WӗO+`!`~_q|Qo-v4ml[8%X BiiQ޵b 0 NGDBhcq9i&@ax:ᐩ[x8B y5,"% ~8?Wf0xl_OG ~^I! ¿[858-. X[50 s闉W~t1'p8NiBiA5XĚp!_n̼; $>f2wxNbN%i\Z{d8Y~>IÙ82+ޡNNP+e5* !vA sul_A"V:J::궠*sk_B O oyfoW0F>>fvN7̾o&c!_ obC[&c$` `DW@ `@.&00 c^_K_ F`@>L0vn% o"G7JL0n27| 82)00gNOC"o.06 0N kLƅ&B/ Ƅ7nYݚm]B 1@|ik}<|Ls̄D"`cSD"HOX'$D"})k0D"HgpLD"HOWb $D"}IXI$D4OE&H$?I$D|'D"VvjUtϒ^|r9L`0D"=E{i^S^?ճ4sћVws I'I$҉T4י|YiYw./x R&H zS=K3W&}R^%$,D>5(7r\8h3L/οtsCT#\n$\ nZPl|z`ǹ/j{:w lg",|ۛTUb&L.OsՏچգyېsƞqbT9=o8M#O@ꢪ,.+q*8KWl]@oA=fBuO`%FB.+gr%w>:Эn`urW+ZpZhyc!apE[dqŊƺ̫h*"h·;repbjY2k! ls z`h\hK\T}ZȃmGzчP[r|׊4\p߇[UG#* y(.䴆xSǝ"uﱱo-sxe[ ⷭYŒ>kmXUfFLvb뗓;r4f۳cq6A.NL0XCƪQ6r sWZFP=$n%7acd*Ȝ8pXu`(Zxx1qn'zuetfĮ5f3Q?௑z极הJqh?FuC"s} BpWF*iTc˳lq$ p\L7`"y[n=G|JTz[wq8knV>1 mn ipy Gn݉HpK5c[ᄱdb,8WIXX_X|q%vӿxXmMkUܬ[Z@Yw;ssc?ðe5p۲Qw1EyzSeI3JZMpG㨵y 09` kMhh06p]UfB1dwJ"szMI7d/2p c+AÐ2 %!Dͨ~3=pm6k]\M q0MFv`qψYժe,zs cO(?tq(Z<8fA# u &vJO^ưM`r2SpCW5$ܪ@+q7ʽ6pF;=};gÙx"48|8O3ae1\7?>3`)*{Nh&{ E1x#M;<%cH7w3ŏIyd33](,\.K`\*BydrIY7ep>Ǜp-V>gp-uO 8 K2LRN Y$%@ϿǞGEK$`a`*uQ00d>C%c/0 xG~YY  lC|yGC R0 +{f7+Oo| WNoЩpec];t*DB0 Q0  X~H0  _!`200 >?#C0 [ C0 %.C0 H>[ `+`\񪴿H[]^?oEE1Xl`_#X/:N+dzpBX~ t䢢a; u"of0j*jsAhfѨ_֛lR+d_p\Pb.MJ=TgXN)5׮,)D>awގ*-%i[v-5/cd \-0By7+`{3~㍭Ȟץ_W+1"*uuaxJq|tgqM%͔ie ЫMU-7O/R~ӼME_'DaV5y| CC(`?WQy<'yl:v& m#?|&g\ΌNƬ\GGnפ=e[&Xo<8GV%rtϵy'hu#^4tQYNN6xjUE1)="ac#JԦDZ4vCB?a4fT{J5ɾ+-dloh^*5EYLv#%S{^l쏂^ov>/ nr 8IIj:/^؞z5T&co\ HMU&. `omQJ8CmB֮(,}cYAH4T}$Dvh6ܖ;}K&chyXFhƕRvD"ĸaw0ToXK_ih)9ÊurT5#آTibqׯ,dL ftX rù-B,QUM&=z)I dKqFK^6Ohᙚmd۲]+ƌ1bՍXPB+ pX3Y!#aiHJX!*"V|UK^lzjZ1()O8VdD|j=uhsvb[jk"iۃ~ ܒҦJmi|r!5n ν}fɏ VOXAy;Ơ!]űoKQo5T^tGW:m/ҾZۢܩ۷(ę\]yǕM5s)Slh 'aA1c.?(c1#{(qDH N4DДJ{#v}RWqoC|k Cgy;n{\.w"G_"g>'MoG}=Ia\$`}|{{se_0  NH? C0|lݑ}LOO0 '`0nC0|5hNߧ/0 '`/ Cp^P  Cp,(>!`] l?"|8/pp84l7 ZnM`e>{|0UÏ?YQ_pi߅񖀿Vyfw1$$`,W7p"~IR!A2Ub *E_LH6,/^~e,GW\2E6^q seĦ0l-єN&rR`%.< 8E\'cMy,(SL@8i6J3XA y@'ٱ~f ƅ0džze̕Fjgt0f.HHk\~$ɹ,6Z^A2qP )W]zA= ӽ͚%Vs~9ɈU yd[۬\1sN,otfd]v܄U BĺjuC7g )B< OU x9@ojC=\jvlȄk[ yJ"Yl(js,JZckTTن5BRi X2lbp!ȌeD)y1Q'Z1@7,W'`=y>ܼ$+?.yo~iD5DWS y,=hJbZ:SK9߰ӆXx>yܯ>o(J9[)z {-Jk|xqW. -ᚍ+web,/_[Z.Ե/Z`9{Oࢣyww\h}'9/ON,Lo_dY-zsl#.&@o4pj8~#I_5Ǩ,&o3jL17h]r8o~N^enWj'r‚;[WqZ ժ 8'8yy `8r?,y~yy9`%9֏# u6H`8M?':հL@qWV<W"p?hfq%}`8E[i߄O@0df 3p_Xhp p_U)'Caq患so϶{dQ@prЫ?oߞPdY@ft6b#}<>fx<{2ȻNME:qb$vB<>mw˴T}يG\yDI['ud}y9'%p߰ :Q6" 1 :hx^;& :c/hc!I6qp"s/k5T_9>V&|e 0Wo0<瀙8Y3p C_ 05f @ @ `0~ 1F<`||`|T`e@Y"XA U`V `m*M 0k+Vi(_ 0k+Vi04k+Vi%X VW ULm-etOS~4tY/ok 85<o0ࣥ}]9*9,Nw~|ʝ;^aYW;{__B,o__`ћu ԣ6Ն93!8wԇ76<6S@,p>u/ן#>ͨÁηeT=p93z_tɄf wx_ Yk SAKg0"Dh [Dg9=pPWwNKRtž ;jGʖ.S ]ڷ_ 0ݯ/Y;Li{K_,yFٱu0hMO qELף9XU{;{\de4q;RsҲ;51w-k y{Oݢf፰ Y\Н[!Ҏ.:eֱ~Ip3xN >XN9 po[Ô3v/b&B3kcYj U0Wa$*0{Rgyjm5wV,'$IENDB`waybar-0.12.0/protocol/000077500000000000000000000000001475603165300147325ustar00rootroot00000000000000waybar-0.12.0/protocol/dbus-menu.xml000066400000000000000000000050701475603165300173550ustar00rootroot00000000000000 waybar-0.12.0/protocol/dbus-status-notifier-item.xml000066400000000000000000000040431475603165300225040ustar00rootroot00000000000000 waybar-0.12.0/protocol/dbus-status-notifier-watcher.xml000066400000000000000000000035141475603165300232050ustar00rootroot00000000000000 waybar-0.12.0/protocol/dwl-ipc-unstable-v2.xml000066400000000000000000000150111475603165300211510ustar00rootroot00000000000000 This protocol allows clients to update and get updates from dwl. Warning! The protocol described in this file is experimental and backward incompatible changes may be made. Backward compatible changes may be added together with the corresponding interface version bump. Backward incompatible changes are done by bumping the version number in the protocol and interface names and resetting the interface version. Once the protocol is to be declared stable, the 'z' prefix and the version number in the protocol and interface names are removed and the interface version number is reset. This interface is exposed as a global in wl_registry. Clients can use this interface to get a dwl_ipc_output. After binding the client will recieve the dwl_ipc_manager.tags and dwl_ipc_manager.layout events. The dwl_ipc_manager.tags and dwl_ipc_manager.layout events expose tags and layouts to the client. Indicates that the client will not the dwl_ipc_manager object anymore. Objects created through this instance are not affected. Get a dwl_ipc_outout for the specified wl_output. This event is sent after binding. A roundtrip after binding guarantees the client recieved all tags. This event is sent after binding. A roundtrip after binding guarantees the client recieved all layouts. Observe and control a dwl output. Events are double-buffered: Clients should cache events and redraw when a dwl_ipc_output.frame event is sent. Request are not double-buffered: The compositor will update immediately upon request. Indicates to that the client no longer needs this dwl_ipc_output. Indicates the client should hide or show themselves. If the client is visible then hide, if hidden then show. Indicates if the output is active. Zero is invalid, nonzero is valid. Indicates that a tag has been updated. Indicates a new layout is selected. Indicates the title has changed. Indicates the appid has changed. Indicates the layout has changed. Since layout symbols are dynamic. As opposed to the zdwl_ipc_manager.layout event, this should take precendence when displaying. You can ignore the zdwl_ipc_output.layout event. Indicates that a sequence of status updates have finished and the client should redraw. The tags are updated as follows: new_tags = (current_tags AND and_tags) XOR xor_tags waybar-0.12.0/protocol/ext-workspace-unstable-v1.xml000066400000000000000000000332701475603165300224140ustar00rootroot00000000000000 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. waybar-0.12.0/protocol/meson.build000066400000000000000000000070311475603165300170750ustar00rootroot00000000000000wl_protocol_dir = wayland_protos.get_variable(pkgconfig: 'pkgdatadir') wayland_scanner = find_program('wayland-scanner') # should check wayland_scanner's version, but it is hard to get if wayland_client.version().version_compare('>=1.14.91') code_type = 'private-code' else code_type = 'code' endif wayland_scanner_code = generator( wayland_scanner, output: '@BASENAME@-protocol.c', arguments: [code_type, '@INPUT@', '@OUTPUT@'], ) wayland_scanner_client = generator( wayland_scanner, output: '@BASENAME@-client-protocol.h', arguments: ['client-header', '@INPUT@', '@OUTPUT@'], ) client_protocols = [ [wl_protocol_dir, 'stable/xdg-shell/xdg-shell.xml'], [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'], ] client_protos_src = [] client_protos_headers = [] foreach p : client_protocols xml = join_paths(p) client_protos_src += wayland_scanner_code.process(xml) client_protos_headers += wayland_scanner_client.process(xml) endforeach gdbus_codegen = find_program('gdbus-codegen') r = run_command(gdbus_codegen, '--body', '--output', '/dev/null', check: false) if r.returncode() != 0 gdbus_code_dsnw = custom_target( 'dbus-status-notifier-watcher.[ch]', output: ['@BASENAME@.c','@BASENAME@.h'], input: './dbus-status-notifier-watcher.xml', command: [gdbus_codegen,'--c-namespace', 'Sn', '--generate-c-code', 'protocol/@BASENAME@', '@INPUT@'], ) gdbus_code_dsni = custom_target( 'dbus-status-notifier-item.[ch]', output: ['@BASENAME@.c','@BASENAME@.h'], input: './dbus-status-notifier-item.xml', command: [gdbus_codegen,'--c-namespace', 'Sn', '--generate-c-code', 'protocol/@BASENAME@', '@INPUT@'], ) gdbus_code_dm = custom_target( 'dbus-menu.[ch]', output: ['@BASENAME@.c','@BASENAME@.h'], input: './dbus-menu.xml', command: [gdbus_codegen,'--c-namespace', 'Sn', '--generate-c-code', 'protocol/@BASENAME@', '@INPUT@'], ) client_protos_src += gdbus_code_dsnw[0] client_protos_headers += gdbus_code_dsnw[1] client_protos_src += gdbus_code_dsni[0] client_protos_headers += gdbus_code_dsni[1] client_protos_src += gdbus_code_dm[0] client_protos_headers += gdbus_code_dm[1] else gdbus_code = generator( gdbus_codegen, output: '@BASENAME@.c', arguments: ['--c-namespace', 'Sn', '--body', '--output', '@OUTPUT@', '@INPUT@'] ) gdbus_header = generator( gdbus_codegen, output: '@BASENAME@.h', arguments: ['--c-namespace', 'Sn', '--header', '--output', '@OUTPUT@', '@INPUT@'] ) client_protos_src += gdbus_code.process('./dbus-status-notifier-watcher.xml') client_protos_headers += gdbus_header.process('./dbus-status-notifier-watcher.xml') client_protos_src += gdbus_code.process('./dbus-status-notifier-item.xml') client_protos_headers += gdbus_header.process('./dbus-status-notifier-item.xml') client_protos_src += gdbus_code.process('./dbus-menu.xml') client_protos_headers += gdbus_header.process('./dbus-menu.xml') endif lib_client_protos = static_library( 'client_protos', client_protos_src + client_protos_headers, dependencies: [wayland_client, gtkmm, giounix], include_directories: include_directories('..'), ) # for the include directory client_protos = declare_dependency( link_with: lib_client_protos, sources: client_protos_headers, ) waybar-0.12.0/protocol/river-control-unstable-v1.xml000066400000000000000000000071371475603165300224300ustar00rootroot00000000000000 Copyright 2020 The River Developers Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, 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. This interface allows clients to run compositor commands and receive a success/failure response with output or a failure message respectively. Each command is built up in a series of add_argument requests and executed with a run_command request. The first argument is the command to be run. A complete list of commands should be made available in the man page of the compositor. This request indicates that the client will not use the river_control object any more. Objects that have been created through this instance are not affected. Arguments are stored by the server in the order they were sent until the run_command request is made. Execute the command built up using the add_argument request for the given seat. This object is created by the run_command request. Exactly one of the success or failure events will be sent. This object will be destroyed by the compositor after one of the events is sent. Sent when the command has been successfully received and executed by the compositor. Some commands may produce output, in which case the output argument will be a non-empty string. Sent when the command could not be carried out. This could be due to sending a non-existent command, no command, not enough arguments, too many arguments, invalid arguments, etc. waybar-0.12.0/protocol/river-status-unstable-v1.xml000066400000000000000000000140031475603165300222610ustar00rootroot00000000000000 Copyright 2020 The River Developers Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, 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. A global factory for objects that receive status information specific to river. It could be used to implement, for example, a status bar. This request indicates that the client will not use the river_status_manager object any more. Objects that have been created through this instance are not affected. This creates a new river_output_status object for the given wl_output. This creates a new river_seat_status object for the given wl_seat. This interface allows clients to receive information about the current windowing state of an output. This request indicates that the client will not use the river_output_status object any more. Sent once binding the interface and again whenever the tag focus of the output changes. Sent once on binding the interface and again whenever the tag state of the output changes. Sent once on binding the interface and again whenever the set of tags with at least one urgent view changes. Sent once on binding the interface should a layout name exist and again whenever the name changes. Sent when the current layout name has been removed without a new one being set, for example when the active layout generator disconnects. This interface allows clients to receive information about the current focus of a seat. Note that (un)focused_output events will only be sent if the client has bound the relevant wl_output globals. This request indicates that the client will not use the river_seat_status object any more. Sent on binding the interface and again whenever an output gains focus. Sent whenever an output loses focus. Sent once on binding the interface and again whenever the focused view or a property thereof changes. The title may be an empty string if no view is focused or the focused view did not set a title. Sent once on binding the interface and again whenever a new mode is entered (e.g. with riverctl enter-mode foobar). waybar-0.12.0/protocol/wlr-foreign-toplevel-management-unstable-v1.xml000066400000000000000000000264221475603165300260160ustar00rootroot00000000000000 Copyright © 2018 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. The purpose of this protocol is to enable the creation of taskbars and docks by providing them with a list of opened applications and letting them request certain actions on them, like maximizing, etc. After a client binds the zwlr_foreign_toplevel_manager_v1, each opened toplevel window will be sent via the toplevel event This event is emitted whenever a new toplevel window is created. It is emitted for all toplevels, regardless of the app that has created them. All initial details of the toplevel(title, app_id, states, etc.) will be sent immediately after this event via the corresponding events in zwlr_foreign_toplevel_handle_v1. Indicates the client no longer wishes to receive events for new toplevels. However the compositor may emit further toplevel_created events, until the finished event is emitted. The client must not send any more requests after this one. This event indicates that the compositor is done sending events to the zwlr_foreign_toplevel_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. A zwlr_foreign_toplevel_handle_v1 object represents an opened toplevel window. Each app may have multiple opened toplevels. Each toplevel has a list of outputs it is visible on, conveyed to the client with the output_enter and output_leave events. This event is emitted whenever the title of the toplevel changes. This event is emitted whenever the app-id of the toplevel changes. This event is emitted whenever the toplevel becomes visible on the given output. A toplevel may be visible on multiple outputs. This event is emitted whenever the toplevel stops being visible on the given output. It is guaranteed that an entered-output event with the same output has been emitted before this event. Requests that the toplevel be maximized. If the maximized state actually changes, this will be indicated by the state event. Requests that the toplevel be unmaximized. If the maximized state actually changes, this will be indicated by the state event. Requests that the toplevel be minimized. If the minimized state actually changes, this will be indicated by the state event. Requests that the toplevel be unminimized. If the minimized state actually changes, this will be indicated by the state event. Request that this toplevel be activated on the given seat. There is no guarantee the toplevel will be actually activated. The different states that a toplevel can have. These have the same meaning as the states with the same names defined in xdg-toplevel This event is emitted immediately after the zlw_foreign_toplevel_handle_v1 is created and each time the toplevel state changes, either because of a compositor action or because of a request in this protocol. This event is sent after all changes in the toplevel state have been sent. This allows changes to the zwlr_foreign_toplevel_handle_v1 properties to be seen as atomic, even if they happen via multiple events. Send a request to the toplevel to close itself. The compositor would typically use a shell-specific method to carry out this request, for example by sending the xdg_toplevel.close event. However, this gives no guarantees the toplevel will actually be destroyed. If and when this happens, the zwlr_foreign_toplevel_handle_v1.closed event will be emitted. The rectangle of the surface specified in this request corresponds to the place where the app using this protocol represents the given toplevel. It can be used by the compositor as a hint for some operations, e.g minimizing. The client is however not required to set this, in which case the compositor is free to decide some default value. If the client specifies more than one rectangle, only the last one is considered. The dimensions are given in surface-local coordinates. Setting width=height=0 removes the already-set rectangle. This event means the toplevel has been destroyed. It is guaranteed there won't be any more events for this zwlr_foreign_toplevel_handle_v1. The toplevel itself becomes inert so any requests will be ignored except the destroy request. Destroys the zwlr_foreign_toplevel_handle_v1 object. This request should be called either when the client does not want to use the toplevel anymore or after the closed event to finalize the destruction of the object. Requests that the toplevel be fullscreened on the given output. If the fullscreen state and/or the outputs the toplevel is visible on actually change, this will be indicated by the state and output_enter/leave events. The output parameter is only a hint to the compositor. Also, if output is NULL, the compositor should decide which output the toplevel will be fullscreened on, if at all. Requests that the toplevel be unfullscreened. If the fullscreen state actually changes, this will be indicated by the state event. This event is emitted whenever the parent of the toplevel changes. No event is emitted when the parent handle is destroyed by the client. waybar-0.12.0/resources/000077500000000000000000000000001475603165300151035ustar00rootroot00000000000000waybar-0.12.0/resources/config.jsonc000066400000000000000000000146721475603165300174200ustar00rootroot00000000000000// -*- mode: jsonc -*- { // "layer": "top", // Waybar at top layer // "position": "bottom", // Waybar position (top|bottom|left|right) "height": 30, // Waybar height (to be removed for auto height) // "width": 1280, // Waybar width "spacing": 4, // Gaps between modules (4px) // Choose the order of the modules "modules-left": [ "sway/workspaces", "sway/mode", "sway/scratchpad", "custom/media" ], "modules-center": [ "sway/window" ], "modules-right": [ "mpd", "idle_inhibitor", "pulseaudio", "network", "power-profiles-daemon", "cpu", "memory", "temperature", "backlight", "keyboard-state", "sway/language", "battery", "battery#bat2", "clock", "tray", "custom/power" ], // Modules configuration // "sway/workspaces": { // "disable-scroll": true, // "all-outputs": true, // "warp-on-scroll": false, // "format": "{name}: {icon}", // "format-icons": { // "1": "", // "2": "", // "3": "", // "4": "", // "5": "", // "urgent": "", // "focused": "", // "default": "" // } // }, "keyboard-state": { "numlock": true, "capslock": true, "format": "{name} {icon}", "format-icons": { "locked": "", "unlocked": "" } }, "sway/mode": { "format": "{}" }, "sway/scratchpad": { "format": "{icon} {count}", "show-empty": false, "format-icons": ["", ""], "tooltip": true, "tooltip-format": "{app}: {title}" }, "mpd": { "format": "{stateIcon} {consumeIcon}{randomIcon}{repeatIcon}{singleIcon}{artist} - {album} - {title} ({elapsedTime:%M:%S}/{totalTime:%M:%S}) ⸨{songPosition}|{queueLength}⸩ {volume}% ", "format-disconnected": "Disconnected ", "format-stopped": "{consumeIcon}{randomIcon}{repeatIcon}{singleIcon}Stopped ", "unknown-tag": "N/A", "interval": 5, "consume-icons": { "on": " " }, "random-icons": { "off": " ", "on": " " }, "repeat-icons": { "on": " " }, "single-icons": { "on": "1 " }, "state-icons": { "paused": "", "playing": "" }, "tooltip-format": "MPD (connected)", "tooltip-format-disconnected": "MPD (disconnected)" }, "idle_inhibitor": { "format": "{icon}", "format-icons": { "activated": "", "deactivated": "" } }, "tray": { // "icon-size": 21, "spacing": 10 }, "clock": { // "timezone": "America/New_York", "tooltip-format": "{:%Y %B}\n{calendar}", "format-alt": "{:%Y-%m-%d}" }, "cpu": { "format": "{usage}% ", "tooltip": false }, "memory": { "format": "{}% " }, "temperature": { // "thermal-zone": 2, // "hwmon-path": "/sys/class/hwmon/hwmon2/temp1_input", "critical-threshold": 80, // "format-critical": "{temperatureC}°C {icon}", "format": "{temperatureC}°C {icon}", "format-icons": ["", "", ""] }, "backlight": { // "device": "acpi_video1", "format": "{percent}% {icon}", "format-icons": ["", "", "", "", "", "", "", "", ""] }, "battery": { "states": { // "good": 95, "warning": 30, "critical": 15 }, "format": "{capacity}% {icon}", "format-full": "{capacity}% {icon}", "format-charging": "{capacity}% ", "format-plugged": "{capacity}% ", "format-alt": "{time} {icon}", // "format-good": "", // An empty format will hide the module // "format-full": "", "format-icons": ["", "", "", "", ""] }, "battery#bat2": { "bat": "BAT2" }, "power-profiles-daemon": { "format": "{icon}", "tooltip-format": "Power profile: {profile}\nDriver: {driver}", "tooltip": true, "format-icons": { "default": "", "performance": "", "balanced": "", "power-saver": "" } }, "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-disconnected": "Disconnected ⚠", "format-alt": "{ifname}: {ipaddr}/{cidr}" }, "pulseaudio": { // "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-source": "{volume}% ", "format-source-muted": "", "format-icons": { "headphone": "", "hands-free": "", "headset": "", "phone": "", "portable": "", "car": "", "default": ["", "", ""] }, "on-click": "pavucontrol" }, "custom/media": { "format": "{icon} {text}", "return-type": "json", "max-length": 40, "format-icons": { "spotify": "", "default": "🎜" }, "escape": true, "exec": "$HOME/.config/waybar/mediaplayer.py 2> /dev/null" // Script in resources folder // "exec": "$HOME/.config/waybar/mediaplayer.py --player spotify 2> /dev/null" // Filter player based on name }, "custom/power": { "format" : "⏻ ", "tooltip": false, "menu": "on-click", "menu-file": "$HOME/.config/waybar/power_menu.xml", // Menu file in resources folder "menu-actions": { "shutdown": "shutdown", "reboot": "reboot", "suspend": "systemctl suspend", "hibernate": "systemctl hibernate" } } } waybar-0.12.0/resources/custom_modules/000077500000000000000000000000001475603165300201455ustar00rootroot00000000000000waybar-0.12.0/resources/custom_modules/cffi_example/000077500000000000000000000000001475603165300225675ustar00rootroot00000000000000waybar-0.12.0/resources/custom_modules/cffi_example/.gitignore000066400000000000000000000000071475603165300245540ustar00rootroot00000000000000.cache/waybar-0.12.0/resources/custom_modules/cffi_example/README.md000066400000000000000000000015061475603165300240500ustar00rootroot00000000000000# C FFI module A C FFI module is a dynamic library that exposes standard C functions and constants, that Waybar can load and execute to create custom advanced widgets. Most language can implement the required functions and constants (C, C++, Rust, Go, Python, ...), meaning you can develop custom modules using your language of choice, as long as there's GTK bindings. Symbols to implement are documented in the [waybar_cffi_module.h](waybar_cffi_module.h) file. # Usage ## Building this module ```bash meson setup build meson compile -C build ``` ## Load the module Edit your waybar config: ```json { // ... "modules-center": [ // ... "cffi/c_example" ], // ... "cffi/c_example": { // Path to the compiled dynamic library file "module_path": "resources/custom_modules/cffi_example/build/wb_cffi_example.so" } } ``` waybar-0.12.0/resources/custom_modules/cffi_example/main.c000066400000000000000000000044051475603165300236620ustar00rootroot00000000000000 #include "waybar_cffi_module.h" typedef struct { wbcffi_module* waybar_module; GtkBox* container; GtkButton* button; } ExampleMod; // This static variable is shared between all instances of this module static int instance_count = 0; void onclicked(GtkButton* button) { char text[256]; snprintf(text, 256, "Dice throw result: %d", rand() % 6 + 1); gtk_button_set_label(button, text); } // You must const size_t wbcffi_version = 1; void* wbcffi_init(const wbcffi_init_info* init_info, const wbcffi_config_entry* config_entries, size_t config_entries_len) { printf("cffi_example: init config:\n"); for (size_t i = 0; i < config_entries_len; i++) { printf(" %s = %s\n", config_entries[i].key, config_entries[i].value); } // Allocate the instance object ExampleMod* inst = malloc(sizeof(ExampleMod)); inst->waybar_module = init_info->obj; GtkContainer* root = init_info->get_root_widget(init_info->obj); // Add a container for displaying the next widgets inst->container = GTK_BOX(gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5)); gtk_container_add(GTK_CONTAINER(root), GTK_WIDGET(inst->container)); // Add a label GtkLabel* label = GTK_LABEL(gtk_label_new("[Example C FFI Module:")); gtk_container_add(GTK_CONTAINER(inst->container), GTK_WIDGET(label)); // Add a button inst->button = GTK_BUTTON(gtk_button_new_with_label("click me !")); g_signal_connect(inst->button, "clicked", G_CALLBACK(onclicked), NULL); gtk_container_add(GTK_CONTAINER(inst->container), GTK_WIDGET(inst->button)); // Add a label label = GTK_LABEL(gtk_label_new("]")); gtk_container_add(GTK_CONTAINER(inst->container), GTK_WIDGET(label)); // Return instance object printf("cffi_example inst=%p: init success ! (%d total instances)\n", inst, ++instance_count); return inst; } void wbcffi_deinit(void* instance) { printf("cffi_example inst=%p: free memory\n", instance); free(instance); } void wbcffi_update(void* instance) { printf("cffi_example inst=%p: Update request\n", instance); } void wbcffi_refresh(void* instance, int signal) { printf("cffi_example inst=%p: Received refresh signal %d\n", instance, signal); } void wbcffi_doaction(void* instance, const char* name) { printf("cffi_example inst=%p: doAction(%s)\n", instance, name); }waybar-0.12.0/resources/custom_modules/cffi_example/meson.build000066400000000000000000000003601475603165300247300ustar00rootroot00000000000000project( 'waybar_cffi_example', 'c', version: '0.1.0', license: 'MIT', ) shared_library('wb_cffi_example', ['main.c'], dependencies: [ dependency('gtk+-3.0', version : ['>=3.22.0']) ], name_prefix: '' ) waybar-0.12.0/resources/custom_modules/cffi_example/waybar_cffi_module.h000066400000000000000000000051501475603165300265620ustar00rootroot00000000000000#pragma once #include #include #ifdef __cplusplus extern "C" { #endif /// Waybar ABI version. 1 is the latest version extern const size_t wbcffi_version; /// Private Waybar CFFI module typedef struct wbcffi_module wbcffi_module; /// Waybar module information typedef struct { /// Waybar CFFI object pointer wbcffi_module* obj; /// Waybar version string const char* waybar_version; /// Returns the waybar widget allocated for this module /// @param obj Waybar CFFI object pointer GtkContainer* (*get_root_widget)(wbcffi_module* obj); /// Queues a request for calling wbcffi_update() on the next GTK main event /// loop iteration /// @param obj Waybar CFFI object pointer void (*queue_update)(wbcffi_module*); } wbcffi_init_info; /// Config key-value pair typedef struct { /// Entry key const char* key; /// Entry value as string. JSON object and arrays are serialized. const char* value; } wbcffi_config_entry; /// Module init/new function, called on module instantiation /// /// MANDATORY CFFI function /// /// @param init_info Waybar module information /// @param config_entries Flat representation of the module JSON config. The data only available /// during wbcffi_init call. /// @param config_entries_len Number of entries in `config_entries` /// /// @return A untyped pointer to module data, NULL if the module failed to load. void* wbcffi_init(const wbcffi_init_info* init_info, const wbcffi_config_entry* config_entries, size_t config_entries_len); /// Module deinit/delete function, called when Waybar is closed or when the module is removed /// /// MANDATORY CFFI function /// /// @param instance Module instance data (as returned by `wbcffi_init`) void wbcffi_deinit(void* instance); /// Called from the GTK main event loop, to update the UI /// /// Optional CFFI function /// /// @param instance Module instance data (as returned by `wbcffi_init`) /// @param action_name Action name void wbcffi_update(void* instance); /// Called when Waybar receives a POSIX signal and forwards it to each module /// /// Optional CFFI function /// /// @param instance Module instance data (as returned by `wbcffi_init`) /// @param signal Signal ID void wbcffi_refresh(void* instance, int signal); /// Called on module action (see /// https://github.com/Alexays/Waybar/wiki/Configuration#module-actions-config) /// /// Optional CFFI function /// /// @param instance Module instance data (as returned by `wbcffi_init`) /// @param action_name Action name void wbcffi_doaction(void* instance, const char* action_name); #ifdef __cplusplus } #endif waybar-0.12.0/resources/custom_modules/mediaplayer.py000077500000000000000000000157761475603165300230360ustar00rootroot00000000000000#!/usr/bin/env python3 import gi gi.require_version("Playerctl", "2.0") from gi.repository import Playerctl, GLib from gi.repository.Playerctl import Player import argparse import logging import sys import signal import gi import json import os from typing import List logger = logging.getLogger(__name__) def signal_handler(sig, frame): logger.info("Received signal to stop, exiting") sys.stdout.write("\n") sys.stdout.flush() # loop.quit() sys.exit(0) class PlayerManager: def __init__(self, selected_player=None, excluded_player=[]): self.manager = Playerctl.PlayerManager() self.loop = GLib.MainLoop() self.manager.connect( "name-appeared", lambda *args: self.on_player_appeared(*args)) self.manager.connect( "player-vanished", lambda *args: self.on_player_vanished(*args)) signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) signal.signal(signal.SIGPIPE, signal.SIG_DFL) self.selected_player = selected_player self.excluded_player = excluded_player.split(',') if excluded_player else [] self.init_players() def init_players(self): for player in self.manager.props.player_names: if player.name in self.excluded_player: continue if self.selected_player is not None and self.selected_player != player.name: logger.debug(f"{player.name} is not the filtered player, skipping it") continue self.init_player(player) def run(self): logger.info("Starting main loop") self.loop.run() def init_player(self, player): logger.info(f"Initialize new player: {player.name}") player = Playerctl.Player.new_from_name(player) player.connect("playback-status", self.on_playback_status_changed, None) player.connect("metadata", self.on_metadata_changed, None) self.manager.manage_player(player) self.on_metadata_changed(player, player.props.metadata) def get_players(self) -> List[Player]: return self.manager.props.players def write_output(self, text, player): logger.debug(f"Writing output: {text}") output = {"text": text, "class": "custom-" + player.props.player_name, "alt": player.props.player_name} sys.stdout.write(json.dumps(output) + "\n") sys.stdout.flush() def clear_output(self): sys.stdout.write("\n") sys.stdout.flush() def on_playback_status_changed(self, player, status, _=None): logger.debug(f"Playback status changed for player {player.props.player_name}: {status}") self.on_metadata_changed(player, player.props.metadata) def get_first_playing_player(self): players = self.get_players() logger.debug(f"Getting first playing player from {len(players)} players") if len(players) > 0: # if any are playing, show the first one that is playing # reverse order, so that the most recently added ones are preferred for player in players[::-1]: if player.props.status == "Playing": return player # if none are playing, show the first one return players[0] else: logger.debug("No players found") return None def show_most_important_player(self): logger.debug("Showing most important player") # show the currently playing player # or else show the first paused player # or else show nothing current_player = self.get_first_playing_player() if current_player is not None: self.on_metadata_changed(current_player, current_player.props.metadata) 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() title = player.get_title() title = 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: track_info = title if track_info: if player.props.status == "Playing": track_info = " " + track_info else: track_info = " " + track_info # only print output if no other player is playing current_playing = self.get_first_playing_player() if current_playing is None or current_playing.props.player_name == player.props.player_name: self.write_output(track_info, player) else: logger.debug(f"Other player {current_playing.props.player_name} is playing, skipping") def on_player_appeared(self, _, player): logger.info(f"Player has appeared: {player.name}") if player.name in self.excluded_player: logger.debug( "New player appeared, but it's in exclude player list, skipping") return if player is not None and (self.selected_player is None or player.name == self.selected_player): self.init_player(player) else: logger.debug( "New player appeared, but it's not the selected player, skipping") def on_player_vanished(self, _, player): logger.info(f"Player {player.props.player_name} has vanished") self.show_most_important_player() def parse_arguments(): parser = argparse.ArgumentParser() # Increase verbosity with every occurrence of -v parser.add_argument("-v", "--verbose", action="count", default=0) parser.add_argument("-x", "--exclude", "- Comma-separated list of excluded player") # Define for which player we"re listening parser.add_argument("--player") parser.add_argument("--enable-logging", action="store_true") return parser.parse_args() def main(): arguments = parse_arguments() # Initialize logging if arguments.enable_logging: logfile = os.path.join(os.path.dirname( os.path.realpath(__file__)), "media-player.log") logging.basicConfig(filename=logfile, level=logging.DEBUG, format="%(asctime)s %(name)s %(levelname)s:%(lineno)d %(message)s") # Logging is set by default to WARN and higher. # With every occurrence of -v it's lowered by one logger.setLevel(max((3 - arguments.verbose) * 10, 0)) logger.info("Creating player manager") if arguments.player: logger.info(f"Filtering for player: {arguments.player}") if arguments.exclude: logger.info(f"Exclude player {arguments.exclude}") player = PlayerManager(arguments.player, arguments.exclude) player.run() if __name__ == "__main__": main() waybar-0.12.0/resources/custom_modules/power_menu.xml000066400000000000000000000013301475603165300230440ustar00rootroot00000000000000 Suspend Hibernate Shutdown Reboot waybar-0.12.0/resources/icons/000077500000000000000000000000001475603165300162165ustar00rootroot00000000000000waybar-0.12.0/resources/icons/meson.build000066400000000000000000000002171475603165300203600ustar00rootroot00000000000000gnome = import('gnome') app_resources += gnome.compile_resources('icon-resources', 'waybar_icons.gresource.xml', c_name: 'waybar_icons' ) waybar-0.12.0/resources/icons/waybar-privacy-audio-input-symbolic.svg000066400000000000000000000010421475603165300257470ustar00rootroot00000000000000 waybar-0.12.0/resources/icons/waybar-privacy-audio-output-symbolic.svg000066400000000000000000000102351475603165300261540ustar00rootroot00000000000000 waybar-0.12.0/resources/icons/waybar-privacy-screen-share-symbolic.svg000066400000000000000000000032641475603165300261000ustar00rootroot00000000000000 waybar-0.12.0/resources/icons/waybar_icons.gresource.xml000066400000000000000000000006311475603165300234150ustar00rootroot00000000000000 waybar-privacy-audio-input-symbolic.svg waybar-privacy-audio-output-symbolic.svg waybar-privacy-screen-share-symbolic.svg waybar-0.12.0/resources/style.css000066400000000000000000000123071475603165300167600ustar00rootroot00000000000000* { /* `otf-font-awesome` is required to be installed for icons */ font-family: FontAwesome, Roboto, Helvetica, Arial, sans-serif; font-size: 13px; } window#waybar { background-color: rgba(43, 48, 59, 0.5); border-bottom: 3px solid rgba(100, 114, 125, 0.5); color: #ffffff; transition-property: background-color; transition-duration: .5s; } window#waybar.hidden { opacity: 0.2; } /* window#waybar.empty { background-color: transparent; } window#waybar.solo { background-color: #FFFFFF; } */ window#waybar.termite { background-color: #3F3F3F; } window#waybar.chromium { background-color: #000000; border: none; } button { /* Use box-shadow instead of border so the text isn't offset */ box-shadow: inset 0 -3px transparent; /* Avoid rounded borders under each button name */ border: none; border-radius: 0; } /* https://github.com/Alexays/Waybar/wiki/FAQ#the-workspace-buttons-have-a-strange-hover-effect */ button:hover { background: inherit; box-shadow: inset 0 -3px #ffffff; } /* you can set a style on hover for any module like this */ #pulseaudio:hover { background-color: #a37800; } #workspaces button { padding: 0 5px; background-color: transparent; color: #ffffff; } #workspaces button:hover { background: rgba(0, 0, 0, 0.2); } #workspaces button.focused { background-color: #64727D; box-shadow: inset 0 -3px #ffffff; } #workspaces button.urgent { background-color: #eb4d4b; } #mode { background-color: #64727D; box-shadow: inset 0 -3px #ffffff; } #clock, #battery, #cpu, #memory, #disk, #temperature, #backlight, #network, #pulseaudio, #wireplumber, #custom-media, #tray, #mode, #idle_inhibitor, #scratchpad, #power-profiles-daemon, #mpd { padding: 0 10px; color: #ffffff; } #window, #workspaces { margin: 0 4px; } /* If workspaces is the leftmost module, omit left margin */ .modules-left > widget:first-child > #workspaces { margin-left: 0; } /* If workspaces is the rightmost module, omit right margin */ .modules-right > widget:last-child > #workspaces { margin-right: 0; } #clock { background-color: #64727D; } #battery { background-color: #ffffff; color: #000000; } #battery.charging, #battery.plugged { color: #ffffff; background-color: #26A65B; } @keyframes blink { to { background-color: #ffffff; color: #000000; } } /* Using steps() instead of linear as a timing function to limit cpu usage */ #battery.critical:not(.charging) { background-color: #f53c3c; color: #ffffff; animation-name: blink; animation-duration: 0.5s; animation-timing-function: steps(12); animation-iteration-count: infinite; animation-direction: alternate; } #power-profiles-daemon { padding-right: 15px; } #power-profiles-daemon.performance { background-color: #f53c3c; color: #ffffff; } #power-profiles-daemon.balanced { background-color: #2980b9; color: #ffffff; } #power-profiles-daemon.power-saver { background-color: #2ecc71; color: #000000; } label:focus { background-color: #000000; } #cpu { background-color: #2ecc71; color: #000000; } #memory { background-color: #9b59b6; } #disk { background-color: #964B00; } #backlight { background-color: #90b1b1; } #network { background-color: #2980b9; } #network.disconnected { background-color: #f53c3c; } #pulseaudio { background-color: #f1c40f; color: #000000; } #pulseaudio.muted { background-color: #90b1b1; color: #2a5c45; } #wireplumber { background-color: #fff0f5; color: #000000; } #wireplumber.muted { background-color: #f53c3c; } #custom-media { background-color: #66cc99; color: #2a5c45; min-width: 100px; } #custom-media.custom-spotify { background-color: #66cc99; } #custom-media.custom-vlc { background-color: #ffa000; } #temperature { background-color: #f0932b; } #temperature.critical { background-color: #eb4d4b; } #tray { background-color: #2980b9; } #tray > .passive { -gtk-icon-effect: dim; } #tray > .needs-attention { -gtk-icon-effect: highlight; background-color: #eb4d4b; } #idle_inhibitor { background-color: #2d3436; } #idle_inhibitor.activated { background-color: #ecf0f1; color: #2d3436; } #mpd { background-color: #66cc99; color: #2a5c45; } #mpd.disconnected { background-color: #f53c3c; } #mpd.stopped { background-color: #90b1b1; } #mpd.paused { background-color: #51a37a; } #language { background: #00b093; color: #740864; padding: 0 5px; margin: 0 5px; min-width: 16px; } #keyboard-state { background: #97e1ad; color: #000000; padding: 0 0px; margin: 0 5px; min-width: 16px; } #keyboard-state > label { padding: 0 5px; } #keyboard-state > label.locked { background: rgba(0, 0, 0, 0.2); } #scratchpad { background: rgba(0, 0, 0, 0.2); } #scratchpad.empty { background-color: transparent; } #privacy { padding: 0; } #privacy-item { padding: 0 5px; color: white; } #privacy-item.screenshare { background-color: #cf5700; } #privacy-item.audio-in { background-color: #1ca000; } #privacy-item.audio-out { background-color: #0069d4; } waybar-0.12.0/resources/waybar.service.in000066400000000000000000000005761475603165300203670ustar00rootroot00000000000000[Unit] 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 Requisite=graphical-session.target [Service] ExecStart=@prefix@/bin/waybar ExecReload=kill -SIGUSR2 $MAINPID Restart=on-failure [Install] WantedBy=graphical-session.target waybar-0.12.0/src/000077500000000000000000000000001475603165300136605ustar00rootroot00000000000000waybar-0.12.0/src/AAppIconLabel.cpp000066400000000000000000000142371475603165300167650ustar00rootroot00000000000000#include "AAppIconLabel.hpp" #include #include #include #include #include #include #include #include "util/gtk_icon.hpp" namespace waybar { AAppIconLabel::AAppIconLabel(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) : AIconLabel(config, name, id, format, interval, ellipsize, enable_click, enable_scroll) { // Icon size if (config["icon-size"].isUInt()) { app_icon_size_ = config["icon-size"].asUInt(); } image_.set_pixel_size(app_icon_size_); } std::string toLowerCase(const std::string& input) { std::string result = input; std::transform(result.begin(), result.end(), result.begin(), [](unsigned char c) { return std::tolower(c); }); return result; } 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(); } } } return {}; } std::optional getFileBySuffix(const std::string& dir, const std::string& suffix) { return getFileBySuffix(dir, suffix, false); } std::optional getDesktopFilePath(const std::string& app_identifier, const std::string& alternative_app_identifier) { if (app_identifier.empty()) { return {}; } const auto data_dirs = Glib::get_system_data_dirs(); for (const auto& data_dir : data_dirs) { const auto data_app_dir = data_dir + "/applications/"; auto desktop_file_suffix = app_identifier + ".desktop"; // searching for file by suffix catches cases like terminal emulator "foot" where class is // "footclient" and desktop file is named "org.codeberg.dnkl.footclient.desktop" auto desktop_file_path = getFileBySuffix(data_app_dir, desktop_file_suffix, true); // "true" argument allows checking for lowercase - this catches cases where class name is // "LibreWolf" and desktop file is named "librewolf.desktop" if (desktop_file_path.has_value()) { return desktop_file_path; } if (!alternative_app_identifier.empty()) { desktop_file_suffix = alternative_app_identifier + ".desktop"; desktop_file_path = getFileBySuffix(data_app_dir, desktop_file_suffix, true); if (desktop_file_path.has_value()) { return desktop_file_path; } } } return {}; } std::optional getIconName(const std::string& app_identifier, const std::string& alternative_app_identifier) { const auto desktop_file_path = getDesktopFilePath(app_identifier, alternative_app_identifier); if (!desktop_file_path.has_value()) { // Try some heuristics to find a matching icon if (DefaultGtkIconThemeWrapper::has_icon(app_identifier)) { return app_identifier; } auto app_identifier_desktop = app_identifier + "-desktop"; if (DefaultGtkIconThemeWrapper::has_icon(app_identifier_desktop)) { return app_identifier_desktop; } auto first_space = app_identifier.find_first_of(' '); if (first_space != std::string::npos) { auto first_word = toLowerCase(app_identifier.substr(0, first_space)); if (DefaultGtkIconThemeWrapper::has_icon(first_word)) { return first_word; } } const auto first_dash = app_identifier.find_first_of('-'); if (first_dash != std::string::npos) { auto first_word = toLowerCase(app_identifier.substr(0, first_dash)); if (DefaultGtkIconThemeWrapper::has_icon(first_word)) { return first_word; } } return {}; } try { Glib::KeyFile desktop_file; desktop_file.load_from_file(desktop_file_path.value()); return desktop_file.get_string("Desktop Entry", "Icon"); } catch (Glib::FileError& error) { spdlog::warn("Error while loading desktop file {}: {}", desktop_file_path.value(), error.what().c_str()); } catch (Glib::KeyFileError& error) { spdlog::warn("Error while loading desktop file {}: {}", desktop_file_path.value(), error.what().c_str()); } return {}; } void AAppIconLabel::updateAppIconName(const std::string& app_identifier, const std::string& alternative_app_identifier) { if (!iconEnabled()) { return; } const auto icon_name = getIconName(app_identifier, alternative_app_identifier); if (icon_name.has_value()) { app_icon_name_ = icon_name.value(); } else { app_icon_name_ = ""; } update_app_icon_ = true; } void AAppIconLabel::updateAppIcon() { if (update_app_icon_) { 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); auto surface = Gdk::Cairo::create_surface_from_pixbuf(pixbuf, image_.get_scale_factor(), image_.get_window()); image_.set(surface); image_.set_visible(true); } else { image_.set_from_icon_name(app_icon_name_, Gtk::ICON_SIZE_INVALID); image_.set_visible(true); } } } auto AAppIconLabel::update() -> void { updateAppIcon(); AIconLabel::update(); } } // namespace waybar waybar-0.12.0/src/AIconLabel.cpp000066400000000000000000000023021475603165300163120ustar00rootroot00000000000000#include "AIconLabel.hpp" #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, bool enable_click, bool enable_scroll) : ALabel(config, name, id, format, interval, ellipsize, enable_click, enable_scroll) { event_box_.remove(); label_.unset_name(); label_.get_style_context()->remove_class(MODULE_CLASS); box_.get_style_context()->add_class(MODULE_CLASS); if (!id.empty()) { label_.get_style_context()->remove_class(id); box_.get_style_context()->add_class(id); } box_.set_orientation(Gtk::Orientation::ORIENTATION_HORIZONTAL); 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_); event_box_.add(box_); } auto AIconLabel::update() -> void { image_.set_visible(image_.get_visible() && iconEnabled()); ALabel::update(); } bool AIconLabel::iconEnabled() const { return config_["icon"].isBool() ? config_["icon"].asBool() : false; } } // namespace waybar waybar-0.12.0/src/ALabel.cpp000066400000000000000000000165431475603165300155150ustar00rootroot00000000000000#include "ALabel.hpp" #include #include #include #include #include "config.hpp" namespace waybar { ALabel::ALabel(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) : AModule(config, name, id, config["format-alt"].isString() || config["menu"].isString() || enable_click, enable_scroll), format_(config_["format"].isString() ? config_["format"].asString() : format), interval_(config_["interval"] == "once" ? std::chrono::seconds::max() : std::chrono::seconds( config_["interval"].isUInt() ? config_["interval"].asUInt() : interval)), default_format_(format_) { label_.set_name(name); if (!id.empty()) { label_.get_style_context()->add_class(id); } label_.get_style_context()->add_class(MODULE_CLASS); event_box_.add(label_); if (config_["max-length"].isUInt()) { label_.set_max_width_chars(config_["max-length"].asInt()); label_.set_ellipsize(Pango::EllipsizeMode::ELLIPSIZE_END); label_.set_single_line_mode(true); } else if (ellipsize && label_.get_max_width_chars() == -1) { label_.set_ellipsize(Pango::EllipsizeMode::ELLIPSIZE_END); label_.set_single_line_mode(true); } if (config_["min-length"].isUInt()) { label_.set_width_chars(config_["min-length"].asUInt()); } uint rotate = 0; if (config_["rotate"].isUInt()) { rotate = config["rotate"].asUInt(); if (not(rotate == 0 || rotate == 90 || rotate == 180 || rotate == 270)) spdlog::warn("'rotate' is only supported in 90 degree increments {} is not valid.", rotate); label_.set_angle(rotate); } if (config_["align"].isDouble()) { auto align = config_["align"].asFloat(); if (rotate == 90 || rotate == 270) { label_.set_yalign(align); } else { label_.set_xalign(align); } } // If a GTKMenu is requested in the config if (config_["menu"].isString()) { // Create the GTKMenu widget try { // Check that the file exists std::string menuFile = config_["menu-file"].asString(); // there might be "~" or "$HOME" in original path, try to expand it. auto result = Config::tryExpandPath(menuFile, ""); if (result.empty()) { throw std::runtime_error("Failed to expand file: " + menuFile); } menuFile = result.front(); // Read the menu descriptor file std::ifstream file(menuFile); if (!file.is_open()) { throw std::runtime_error("Failed to open file: " + menuFile); } std::stringstream fileContent; fileContent << file.rdbuf(); GtkBuilder* builder = gtk_builder_new(); // Make the GtkBuilder and check for errors in his parsing if (gtk_builder_add_from_string(builder, fileContent.str().c_str(), -1, nullptr) == 0U) { throw std::runtime_error("Error found in the file " + menuFile); } menu_ = gtk_builder_get_object(builder, "menu"); if (menu_ == nullptr) { throw std::runtime_error("Failed to get 'menu' object from GtkBuilder"); } submenus_ = std::map(); menuActionsMap_ = std::map(); // Linking actions to the GTKMenu based on 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())); menuActionsMap_[key] = it->asString(); g_signal_connect(submenus_[key], "activate", G_CALLBACK(handleGtkMenuEvent), (gpointer)menuActionsMap_[key].c_str()); } } catch (std::runtime_error& e) { spdlog::warn("Error while creating the menu : {}. Menu popup not activated.", e.what()); } } if (config_["justify"].isString()) { auto justify_str = config_["justify"].asString(); if (justify_str == "left") { label_.set_justify(Gtk::Justification::JUSTIFY_LEFT); } else if (justify_str == "right") { label_.set_justify(Gtk::Justification::JUSTIFY_RIGHT); } else if (justify_str == "center") { label_.set_justify(Gtk::Justification::JUSTIFY_CENTER); } } } auto ALabel::update() -> void { AModule::update(); } std::string ALabel::getIcon(uint16_t percentage, const std::string& alt, uint16_t max) { auto format_icons = config_["format-icons"]; if (format_icons.isObject()) { if (!alt.empty() && (format_icons[alt].isString() || format_icons[alt].isArray())) { format_icons = format_icons[alt]; } else { format_icons = format_icons["default"]; } } 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); format_icons = format_icons[idx]; } } if (format_icons.isString()) { return format_icons.asString(); } return ""; } std::string ALabel::getIcon(uint16_t percentage, const std::vector& alts, uint16_t max) { auto format_icons = config_["format-icons"]; if (format_icons.isObject()) { std::string _alt = "default"; for (const auto& alt : alts) { if (!alt.empty() && (format_icons[alt].isString() || format_icons[alt].isArray())) { _alt = alt; break; } } format_icons = format_icons[_alt]; } 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); format_icons = format_icons[idx]; } } if (format_icons.isString()) { return format_icons.asString(); } return ""; } bool waybar::ALabel::handleToggle(GdkEventButton* const& e) { if (config_["format-alt-click"].isUInt() && e->button == config_["format-alt-click"].asUInt()) { alt_ = !alt_; if (alt_ && config_["format-alt"].isString()) { format_ = config_["format-alt"].asString(); } else { format_ = default_format_; } } return AModule::handleToggle(e); } void ALabel::handleGtkMenuEvent(GtkMenuItem* /*menuitem*/, gpointer data) { waybar::util::command::res res = waybar::util::command::exec((char*)data, "GtkMenu"); } std::string ALabel::getState(uint8_t value, bool lesser) { if (!config_["states"].isObject()) { return ""; } // Get current state std::vector> states; if (config_["states"].isObject()) { for (auto it = config_["states"].begin(); it != config_["states"].end(); ++it) { if (it->isUInt() && it.key().isString()) { states.emplace_back(it.key().asString(), it->asUInt()); } } } // Sort states std::sort(states.begin(), states.end(), [&lesser](auto& a, auto& b) { return lesser ? a.second < b.second : a.second > b.second; }); std::string valid_state; for (auto const& state : states) { if ((lesser ? value <= state.second : value >= state.second) && valid_state.empty()) { label_.get_style_context()->add_class(state.first); valid_state = state.first; } else { label_.get_style_context()->remove_class(state.first); } } return valid_state; } } // namespace waybar waybar-0.12.0/src/AModule.cpp000066400000000000000000000220751475603165300157200ustar00rootroot00000000000000#include "AModule.hpp" #include #include #include #include "gdk/gdk.h" #include "gdkmm/cursor.h" namespace waybar { AModule::AModule(const Json::Value& config, const std::string& name, const std::string& id, bool enable_click, bool enable_scroll) : name_(name), config_(config), 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) { // Configure module action Map const Json::Value actions{config_["actions"]}; for (Json::Value::const_iterator it = actions.begin(); it != actions.end(); ++it) { if (it.key().isString() && it->isString()) if (!eventActionMap_.contains(it.key().asString())) { eventActionMap_.insert({it.key().asString(), it->asString()}); enable_click = true; enable_scroll = true; } else spdlog::warn("Duplicate action is ignored: {0}", it.key().asString()); else spdlog::warn("Wrong actions section configuration. See config by index: {}", it.index()); } event_box_.signal_enter_notify_event().connect(sigc::mem_fun(*this, &AModule::handleMouseEnter)); event_box_.signal_leave_notify_event().connect(sigc::mem_fun(*this, &AModule::handleMouseLeave)); // configure events' user commands // hasUserEvents is true if any element from eventMap_ is satisfying the condition in the lambda bool hasUserEvents = std::find_if(eventMap_.cbegin(), eventMap_.cend(), [&config](const auto& eventEntry) { // True if there is any non-release type event return eventEntry.first.second != GdkEventType::GDK_BUTTON_RELEASE && config[eventEntry.second].isString(); }) != eventMap_.cend(); if (enable_click || hasUserEvents) { hasUserEvents_ = true; event_box_.add_events(Gdk::BUTTON_PRESS_MASK); event_box_.signal_button_press_event().connect(sigc::mem_fun(*this, &AModule::handleToggle)); } else { hasUserEvents_ = false; } bool hasReleaseEvent = std::find_if(eventMap_.cbegin(), eventMap_.cend(), [&config](const auto& eventEntry) { // True if there is any non-release type event return eventEntry.first.second == GdkEventType::GDK_BUTTON_RELEASE && config[eventEntry.second].isString(); }) != eventMap_.cend(); if (hasReleaseEvent) { event_box_.add_events(Gdk::BUTTON_RELEASE_MASK); event_box_.signal_button_release_event().connect(sigc::mem_fun(*this, &AModule::handleRelease)); } if (config_["on-scroll-up"].isString() || config_["on-scroll-down"].isString() || config_["on-scroll-left"].isString() || config_["on-scroll-right"].isString() || enable_scroll) { event_box_.add_events(Gdk::SCROLL_MASK | Gdk::SMOOTH_SCROLL_MASK); event_box_.signal_scroll_event().connect(sigc::mem_fun(*this, &AModule::handleScroll)); } // Respect user configuration of cursor if (config_.isMember("cursor")) { if (config_["cursor"].isBool() && config_["cursor"].asBool()) { setCursor(Gdk::HAND2); } else if (config_["cursor"].isInt()) { setCursor(Gdk::CursorType(config_["cursor"].asInt())); } else { spdlog::warn("unknown cursor option configured on module {}", name_); } } } AModule::~AModule() { for (const auto& pid : pid_) { if (pid != -1) { killpg(pid, SIGTERM); } } } 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())); } } // Get mapping between event name and module action name // Then call overrided 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 if (recA != eventActionMap_.cend() && name != recA->second) this->doAction(recA->second); } } void AModule::setCursor(Gdk::CursorType const& c) { auto gdk_window = event_box_.get_window(); if (gdk_window) { auto cursor = Gdk::Cursor::create(c); gdk_window->set_cursor(cursor); } 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( [this, c]() { setCursor(c); return false; }, 1); } } bool AModule::handleMouseEnter(GdkEventCrossing* const& e) { if (auto* module = event_box_.get_child(); module != nullptr) { module->set_state_flags(Gtk::StateFlags::STATE_FLAG_PRELIGHT); } // Default behavior indicating event availability if (hasUserEvents_ && !config_.isMember("cursor")) { setCursor(Gdk::HAND2); } return false; } bool AModule::handleMouseLeave(GdkEventCrossing* const& e) { if (auto* module = event_box_.get_child(); module != nullptr) { module->unset_state_flags(Gtk::StateFlags::STATE_FLAG_PRELIGHT); } // Default behavior indicating event availability if (hasUserEvents_ && !config_.isMember("cursor")) { setCursor(Gdk::ARROW); } return false; } bool AModule::handleToggle(GdkEventButton* const& e) { return handleUserEvent(e); } bool AModule::handleRelease(GdkEventButton* const& e) { return handleUserEvent(e); } bool AModule::handleUserEvent(GdkEventButton* const& e) { std::string format{}; const std::map, std::string>::const_iterator& rec{ eventMap_.find(std::pair(e->button, e->type))}; if (rec != eventMap_.cend()) { // First call module actions this->AModule::doAction(rec->second); format = rec->second; } // Check that a menu has been configured if (config_["menu"].isString()) { // Check if the event is the one specified for the "menu" option if (rec->second == config_["menu"].asString()) { // Popup the menu gtk_widget_show_all(GTK_WIDGET(menu_)); gtk_menu_popup_at_pointer(GTK_MENU(menu_), reinterpret_cast(e)); } } // Second call user scripts if (!format.empty()) { if (config_[format].isString()) format = config_[format].asString(); else format.clear(); } if (!format.empty()) { pid_.push_back(util::command::forkExec(format)); } dp.emit(); return true; } AModule::SCROLL_DIR AModule::getScrollDir(GdkEventScroll* e) { // only affects up/down bool reverse = config_["reverse-scrolling"].asBool(); bool reverse_mouse = config_["reverse-mouse-scrolling"].asBool(); // ignore reverse-scrolling if event comes from a mouse wheel GdkDevice* device = gdk_event_get_source_device((GdkEvent*)e); if (device != nullptr && gdk_device_get_source(device) == GDK_SOURCE_MOUSE) { reverse = reverse_mouse; } switch (e->direction) { case GDK_SCROLL_UP: return reverse ? SCROLL_DIR::DOWN : SCROLL_DIR::UP; case GDK_SCROLL_DOWN: return reverse ? SCROLL_DIR::UP : SCROLL_DIR::DOWN; case GDK_SCROLL_LEFT: return SCROLL_DIR::LEFT; case GDK_SCROLL_RIGHT: return SCROLL_DIR::RIGHT; case GDK_SCROLL_SMOOTH: { SCROLL_DIR dir{SCROLL_DIR::NONE}; distance_scrolled_y_ += e->delta_y; distance_scrolled_x_ += e->delta_x; gdouble threshold = 0; if (config_["smooth-scrolling-threshold"].isNumeric()) { threshold = config_["smooth-scrolling-threshold"].asDouble(); } if (distance_scrolled_y_ < -threshold) { dir = reverse ? SCROLL_DIR::DOWN : SCROLL_DIR::UP; } else if (distance_scrolled_y_ > threshold) { dir = reverse ? SCROLL_DIR::UP : SCROLL_DIR::DOWN; } else if (distance_scrolled_x_ > threshold) { dir = SCROLL_DIR::RIGHT; } else if (distance_scrolled_x_ < -threshold) { dir = SCROLL_DIR::LEFT; } switch (dir) { case SCROLL_DIR::UP: case SCROLL_DIR::DOWN: distance_scrolled_y_ = 0; break; case SCROLL_DIR::LEFT: case SCROLL_DIR::RIGHT: distance_scrolled_x_ = 0; break; case SCROLL_DIR::NONE: break; } return dir; } // Silence -Wreturn-type: default: return SCROLL_DIR::NONE; } } bool AModule::handleScroll(GdkEventScroll* e) { auto dir = getScrollDir(e); std::string eventName{}; if (dir == SCROLL_DIR::UP) eventName = "on-scroll-up"; else if (dir == SCROLL_DIR::DOWN) eventName = "on-scroll-down"; else if (dir == SCROLL_DIR::LEFT) eventName = "on-scroll-left"; else if (dir == SCROLL_DIR::RIGHT) eventName = "on-scroll-right"; // First call module actions this->AModule::doAction(eventName); // Second call user scripts if (config_[eventName].isString()) pid_.push_back(util::command::forkExec(config_[eventName].asString())); dp.emit(); return true; } bool AModule::tooltipEnabled() const { return isTooltip; } bool AModule::expandEnabled() const { return isExpand; } AModule::operator Gtk::Widget&() { return event_box_; } } // namespace waybar waybar-0.12.0/src/ASlider.cpp000066400000000000000000000017651475603165300157200ustar00rootroot00000000000000#include "ASlider.hpp" #include "gtkmm/adjustment.h" #include "gtkmm/enums.h" namespace waybar { ASlider::ASlider(const Json::Value& config, const std::string& name, const std::string& id) : AModule(config, name, id, false, false), vertical_(config_["orientation"].asString() == "vertical"), scale_(vertical_ ? Gtk::ORIENTATION_VERTICAL : Gtk::ORIENTATION_HORIZONTAL) { scale_.set_name(name); if (!id.empty()) { scale_.get_style_context()->add_class(id); } scale_.get_style_context()->add_class(MODULE_CLASS); event_box_.add(scale_); scale_.signal_value_changed().connect(sigc::mem_fun(*this, &ASlider::onValueChanged)); if (config_["min"].isUInt()) { min_ = config_["min"].asUInt(); } if (config_["max"].isUInt()) { max_ = config_["max"].asUInt(); } scale_.set_inverted(vertical_); scale_.set_draw_value(false); scale_.set_adjustment(Gtk::Adjustment::create(curr_, min_, max_ + 1, 1, 1, 1)); } void ASlider::onValueChanged() {} } // namespace waybarwaybar-0.12.0/src/bar.cpp000066400000000000000000000526041475603165300151370ustar00rootroot00000000000000#include "bar.hpp" #include #include #include #include "client.hpp" #include "factory.hpp" #include "group.hpp" #ifdef HAVE_SWAY #include "modules/sway/bar.hpp" #endif namespace waybar { static constexpr const char* MIN_HEIGHT_MSG = "Requested height: {} is less than the minimum height: {} required by the modules"; static constexpr const char* MIN_WIDTH_MSG = "Requested width: {} is less than the minimum width: {} required by the modules"; static constexpr const char* BAR_SIZE_MSG = "Bar configured (width: {}, height: {}) for output: {}"; const Bar::bar_mode_map Bar::PRESET_MODES = { // {"default", {// Special mode to hold the global bar configuration .layer = bar_layer::BOTTOM, .exclusive = true, .passthrough = false, .visible = true}}, {"dock", {// Modes supported by the sway config; see man sway-bar(5) .layer = bar_layer::BOTTOM, .exclusive = true, .passthrough = false, .visible = true}}, {"hide", {// .layer = bar_layer::OVERLAY, .exclusive = false, .passthrough = false, .visible = true}}, {"invisible", {// .layer = bar_layer::BOTTOM, .exclusive = false, .passthrough = true, .visible = false}}, {"overlay", {// .layer = bar_layer::OVERLAY, .exclusive = false, .passthrough = true, .visible = true}}}; const std::string Bar::MODE_DEFAULT = "default"; const std::string Bar::MODE_INVISIBLE = "invisible"; const std::string_view DEFAULT_BAR_ID = "bar-0"; /* Deserializer for enum bar_layer */ void from_json(const Json::Value& j, bar_layer& l) { if (j == "bottom") { l = bar_layer::BOTTOM; } else if (j == "top") { l = bar_layer::TOP; } else if (j == "overlay") { l = bar_layer::OVERLAY; } } /* Deserializer for struct bar_mode */ void from_json(const Json::Value& j, bar_mode& m) { if (j.isObject()) { if (const auto& v = j["layer"]; v.isString()) { from_json(v, m.layer); } if (const auto& v = j["exclusive"]; v.isBool()) { m.exclusive = v.asBool(); } if (const auto& v = j["passthrough"]; v.isBool()) { m.passthrough = v.asBool(); } if (const auto& v = j["visible"]; v.isBool()) { m.visible = v.asBool(); } } } /* Deserializer for enum Gtk::PositionType */ void from_json(const Json::Value& j, Gtk::PositionType& pos) { if (j == "left") { pos = Gtk::POS_LEFT; } else if (j == "right") { pos = Gtk::POS_RIGHT; } else if (j == "top") { pos = Gtk::POS_TOP; } else if (j == "bottom") { pos = Gtk::POS_BOTTOM; } } Glib::ustring to_string(Gtk::PositionType pos) { switch (pos) { case Gtk::POS_LEFT: return "left"; case Gtk::POS_RIGHT: return "right"; case Gtk::POS_TOP: return "top"; case Gtk::POS_BOTTOM: return "bottom"; } throw std::runtime_error("Invalid Gtk::PositionType"); } /* Deserializer for JSON Object -> map * Assumes that all the values in the object are deserializable to the same type. */ template >> void from_json(const Json::Value& j, std::map& m) { if (j.isObject()) { for (auto it = j.begin(); it != j.end(); ++it) { from_json(*it, m[it.key().asString()]); } } } }; // namespace waybar waybar::Bar::Bar(struct waybar_output* w_output, const Json::Value& w_config) : output(w_output), config(w_config), surface(nullptr), window{Gtk::WindowType::WINDOW_TOPLEVEL}, x_global(0), y_global(0), margins_{.top = 0, .right = 0, .bottom = 0, .left = 0}, left_(Gtk::ORIENTATION_HORIZONTAL, 0), center_(Gtk::ORIENTATION_HORIZONTAL, 0), right_(Gtk::ORIENTATION_HORIZONTAL, 0), box_(Gtk::ORIENTATION_HORIZONTAL, 0) { window.set_title("waybar"); window.set_name("waybar"); window.set_decorated(false); window.get_style_context()->add_class(output->name); window.get_style_context()->add_class(config["name"].asString()); from_json(config["position"], position); orientation = (position == Gtk::POS_LEFT || position == Gtk::POS_RIGHT) ? Gtk::ORIENTATION_VERTICAL : Gtk::ORIENTATION_HORIZONTAL; window.get_style_context()->add_class(to_string(position)); left_ = Gtk::Box(orientation, 0); center_ = Gtk::Box(orientation, 0); right_ = Gtk::Box(orientation, 0); box_ = Gtk::Box(orientation, 0); left_.get_style_context()->add_class("modules-left"); center_.get_style_context()->add_class("modules-center"); right_.get_style_context()->add_class("modules-right"); if (config["spacing"].isInt()) { int spacing = config["spacing"].asInt(); left_.set_spacing(spacing); center_.set_spacing(spacing); right_.set_spacing(spacing); } height_ = config["height"].isUInt() ? config["height"].asUInt() : 0; width_ = config["width"].isUInt() ? config["width"].asUInt() : 0; if (config["margin-top"].isInt() || config["margin-right"].isInt() || config["margin-bottom"].isInt() || config["margin-left"].isInt()) { margins_ = { config["margin-top"].isInt() ? config["margin-top"].asInt() : 0, config["margin-right"].isInt() ? config["margin-right"].asInt() : 0, config["margin-bottom"].isInt() ? config["margin-bottom"].asInt() : 0, config["margin-left"].isInt() ? config["margin-left"].asInt() : 0, }; } else if (config["margin"].isString()) { std::istringstream iss(config["margin"].asString()); std::vector margins{std::istream_iterator(iss), {}}; try { if (margins.size() == 1) { auto gaps = std::stoi(margins[0], nullptr, 10); margins_ = {.top = gaps, .right = gaps, .bottom = gaps, .left = gaps}; } if (margins.size() == 2) { auto vertical_margins = std::stoi(margins[0], nullptr, 10); auto horizontal_margins = std::stoi(margins[1], nullptr, 10); margins_ = {.top = vertical_margins, .right = horizontal_margins, .bottom = vertical_margins, .left = horizontal_margins}; } if (margins.size() == 3) { auto horizontal_margins = std::stoi(margins[1], nullptr, 10); margins_ = {.top = std::stoi(margins[0], nullptr, 10), .right = horizontal_margins, .bottom = std::stoi(margins[2], nullptr, 10), .left = horizontal_margins}; } if (margins.size() == 4) { margins_ = {.top = std::stoi(margins[0], nullptr, 10), .right = std::stoi(margins[1], nullptr, 10), .bottom = std::stoi(margins[2], nullptr, 10), .left = std::stoi(margins[3], nullptr, 10)}; } } catch (...) { spdlog::warn("Invalid margins: {}", config["margin"].asString()); } } else if (config["margin"].isInt()) { auto gaps = config["margin"].asInt(); margins_ = {.top = gaps, .right = gaps, .bottom = gaps, .left = gaps}; } window.signal_configure_event().connect_notify(sigc::mem_fun(*this, &Bar::onConfigure)); output->monitor->property_geometry().signal_changed().connect( sigc::mem_fun(*this, &Bar::onOutputGeometryChanged)); // this has to be executed before GtkWindow.realize auto* gtk_window = window.gobj(); 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_margin(gtk_window, GTK_LAYER_SHELL_EDGE_LEFT, margins_.left); gtk_layer_set_margin(gtk_window, GTK_LAYER_SHELL_EDGE_RIGHT, margins_.right); gtk_layer_set_margin(gtk_window, GTK_LAYER_SHELL_EDGE_TOP, margins_.top); gtk_layer_set_margin(gtk_window, GTK_LAYER_SHELL_EDGE_BOTTOM, margins_.bottom); window.set_size_request(width_, height_); // Position needs to be set after calculating the height due to the // GTK layer shell anchors logic relying on the dimensions of the bar. setPosition(position); /* Read custom modes if available */ if (auto modes = config.get("modes", {}); modes.isObject()) { from_json(modes, configured_modes); } /* Update "default" mode with the global bar options */ from_json(config, configured_modes[MODE_DEFAULT]); if (auto mode = config.get("mode", {}); mode.isString()) { setMode(config["mode"].asString()); } else { setMode(MODE_DEFAULT); } if (config["start_hidden"].asBool()) { setVisible(false); } window.signal_map_event().connect_notify(sigc::mem_fun(*this, &Bar::onMap)); #if HAVE_SWAY if (auto ipc = config["ipc"]; ipc.isBool() && ipc.asBool()) { bar_id = Client::inst()->bar_id; if (auto id = config["id"]; id.isString()) { bar_id = id.asString(); } if (bar_id.empty()) { bar_id = DEFAULT_BAR_ID; } try { _ipc_client = std::make_unique(*this); } catch (const std::exception& exc) { spdlog::warn("Failed to open bar ipc connection: {}", exc.what()); } } #endif setupWidgets(); window.show_all(); 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( window.get_style_context()->gobj(), (GtkStyleContextPrintFlags)(GTK_STYLE_CONTEXT_PRINT_RECURSE | GTK_STYLE_CONTEXT_PRINT_SHOW_STYLE)); spdlog::debug("GTK widget tree:\n{}", gtk_tree); g_free(gtk_tree); } } /* Need to define it here because of forward declared members */ waybar::Bar::~Bar() = default; void waybar::Bar::setMode(const std::string& mode) { using namespace std::literals::string_literals; auto style = window.get_style_context(); /* remove styles added by previous setMode calls */ style->remove_class("mode-"s + last_mode_); auto it = configured_modes.find(mode); if (it != configured_modes.end()) { last_mode_ = mode; style->add_class("mode-"s + last_mode_); setMode(it->second); } else { spdlog::warn("Unknown mode \"{}\" requested", mode); last_mode_ = MODE_DEFAULT; style->add_class("mode-"s + last_mode_); setMode(configured_modes.at(MODE_DEFAULT)); } } void waybar::Bar::setMode(const struct bar_mode& mode) { auto* gtk_window = window.gobj(); auto layer = GTK_LAYER_SHELL_LAYER_BOTTOM; if (mode.layer == bar_layer::TOP) { layer = GTK_LAYER_SHELL_LAYER_TOP; } else if (mode.layer == bar_layer::OVERLAY) { layer = GTK_LAYER_SHELL_LAYER_OVERLAY; } gtk_layer_set_layer(gtk_window, layer); if (mode.exclusive) { gtk_layer_auto_exclusive_zone_enable(gtk_window); } else { gtk_layer_set_exclusive_zone(gtk_window, 0); } setPassThrough(passthrough_ = mode.passthrough); if (mode.visible) { window.get_style_context()->remove_class("hidden"); window.set_opacity(1); } else { window.get_style_context()->add_class("hidden"); window.set_opacity(0); } /* * All the changes above require `wl_surface_commit`. * 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); wl_display_flush(Client::inst()->wl_display); } void waybar::Bar::setPassThrough(bool passthrough) { auto gdk_window = window.get_window(); if (gdk_window) { Cairo::RefPtr region; if (passthrough) { region = Cairo::Region::create(); } gdk_window->input_shape_combine_region(region, 0, 0); } } void waybar::Bar::setPosition(Gtk::PositionType position) { std::array anchors; anchors.fill(TRUE); auto orientation = (position == Gtk::POS_LEFT || position == Gtk::POS_RIGHT) ? Gtk::ORIENTATION_VERTICAL : Gtk::ORIENTATION_HORIZONTAL; switch (position) { case Gtk::POS_LEFT: anchors[GTK_LAYER_SHELL_EDGE_RIGHT] = FALSE; break; case Gtk::POS_RIGHT: anchors[GTK_LAYER_SHELL_EDGE_LEFT] = FALSE; break; case Gtk::POS_BOTTOM: anchors[GTK_LAYER_SHELL_EDGE_TOP] = FALSE; break; default: /* Gtk::POS_TOP */ anchors[GTK_LAYER_SHELL_EDGE_BOTTOM] = FALSE; break; }; // Disable anchoring for other edges too if the width // or the height has been set to a value other than 'auto' // otherwise the bar will use all space uint32_t configured_width = config["width"].isUInt() ? config["width"].asUInt() : 0; uint32_t configured_height = config["height"].isUInt() ? config["height"].asUInt() : 0; if (orientation == Gtk::ORIENTATION_VERTICAL && configured_height > 1) { anchors[GTK_LAYER_SHELL_EDGE_TOP] = FALSE; anchors[GTK_LAYER_SHELL_EDGE_BOTTOM] = FALSE; } else if (orientation == Gtk::ORIENTATION_HORIZONTAL && configured_width > 1) { anchors[GTK_LAYER_SHELL_EDGE_LEFT] = FALSE; anchors[GTK_LAYER_SHELL_EDGE_RIGHT] = FALSE; } for (auto edge : {GTK_LAYER_SHELL_EDGE_LEFT, GTK_LAYER_SHELL_EDGE_RIGHT, GTK_LAYER_SHELL_EDGE_TOP, GTK_LAYER_SHELL_EDGE_BOTTOM}) { gtk_layer_set_anchor(window.gobj(), edge, anchors[edge]); } } 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(); surface = gdk_wayland_window_get_wl_surface(gdk_window); configureGlobalOffset(gdk_window_get_width(gdk_window), gdk_window_get_height(gdk_window)); setPassThrough(passthrough_); } void waybar::Bar::setVisible(bool value) { visible = value; if (auto mode = config.get("mode", {}); mode.isString()) { setMode(visible ? config["mode"].asString() : MODE_INVISIBLE); } else { setMode(visible ? MODE_DEFAULT : MODE_INVISIBLE); } } void waybar::Bar::toggle() { setVisible(!visible); } // Converting string to button code rn as to avoid doing it later void waybar::Bar::setupAltFormatKeyForModule(const std::string& module_name) { if (config.isMember(module_name)) { Json::Value& module = config[module_name]; if (module.isMember("format-alt")) { if (module.isMember("format-alt-click")) { Json::Value& click = module["format-alt-click"]; if (click.isString()) { if (click == "click-right") { module["format-alt-click"] = 3U; } else if (click == "click-middle") { module["format-alt-click"] = 2U; } else if (click == "click-backward") { module["format-alt-click"] = 8U; } else if (click == "click-forward") { module["format-alt-click"] = 9U; } else { module["format-alt-click"] = 1U; // default click-left } } else { module["format-alt-click"] = 1U; } } else { module["format-alt-click"] = 1U; } } } } void waybar::Bar::setupAltFormatKeyForModuleList(const char* module_list_name) { if (config.isMember(module_list_name)) { Json::Value& modules = config[module_list_name]; for (const Json::Value& module_name : modules) { if (module_name.isString()) { auto ref = module_name.asString(); if (ref.compare(0, 6, "group/") == 0 && ref.size() > 6) { Json::Value& group_modules = config[ref]["modules"]; for (const Json::Value& module_name : group_modules) { if (module_name.isString()) { setupAltFormatKeyForModule(module_name.asString()); } } } else { setupAltFormatKeyForModule(ref); } } } } } void waybar::Bar::handleSignal(int signal) { for (auto& module : modules_all_) { module->refresh(signal); } } 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]; if (module_list.isArray()) { for (const auto& name : module_list) { try { auto ref = name.asString(); AModule* module; if (ref.compare(0, 6, "group/") == 0 && ref.size() > 6) { auto hash_pos = ref.find('#'); auto id_name = ref.substr(6, hash_pos - 6); auto class_name = hash_pos != std::string::npos ? ref.substr(hash_pos + 1) : ""; 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; } else { module = factory.makeModule(ref, pos); } std::shared_ptr module_sp(module); modules_all_.emplace_back(module_sp); if (group != nullptr) { group->addWidget(*module); } else { if (pos == "modules-left") { modules_left_.emplace_back(module_sp); } if (pos == "modules-center") { modules_center_.emplace_back(module_sp); } if (pos == "modules-right") { modules_right_.emplace_back(module_sp); } } module->dp.connect([module, ref] { try { module->update(); } catch (const std::exception& e) { spdlog::error("{}: {}", ref, e.what()); } }); } catch (const std::exception& e) { spdlog::warn("module {}: {}", name.asString(), e.what()); } } } } auto waybar::Bar::setupWidgets() -> void { window.add(box_); bool expand_left = config["expand-left"].isBool() ? config["expand-left"].asBool() : false; bool expand_center = config["expand-center"].isBool() ? config["expand-center"].asBool() : false; bool expand_right = config["expand-right"].isBool() ? config["expand-right"].asBool() : false; bool no_center = config["no-center"].isBool() ? config["no-center"].asBool() : false; box_.pack_start(left_, expand_left, expand_left); if (!no_center) { 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); } } box_.pack_end(right_, expand_right, expand_right); // Convert to button code for every module that is used. setupAltFormatKeyForModuleList("modules-left"); setupAltFormatKeyForModuleList("modules-right"); setupAltFormatKeyForModuleList("modules-center"); Factory factory(*this, config); getModules(factory, "modules-left"); if (!no_center) { getModules(factory, "modules-center"); } getModules(factory, "modules-right"); for (auto const& module : modules_left_) { left_.pack_start(*module, module->expandEnabled(), module->expandEnabled()); } if (!no_center) { for (auto const& module : modules_center_) { center_.pack_start(*module, false, false); } } std::reverse(modules_right_.begin(), modules_right_.end()); for (auto const& module : modules_right_) { right_.pack_end(*module, false, false); } } void waybar::Bar::onConfigure(GdkEventConfigure* ev) { /* * GTK wants new size for the window. * Actual resizing and management of the exclusve zone is handled within the gtk-layer-shell * code. This event handler only updates stored size of the window and prints some warnings. * * Note: forced resizing to a window smaller than required by GTK would not work with * gtk-layer-shell. */ if (orientation == Gtk::ORIENTATION_VERTICAL) { if (width_ > 1 && ev->width > static_cast(width_)) { spdlog::warn(MIN_WIDTH_MSG, width_, ev->width); } } else { if (height_ > 1 && ev->height > static_cast(height_)) { spdlog::warn(MIN_HEIGHT_MSG, height_, ev->height); } } width_ = ev->width; height_ = ev->height; configureGlobalOffset(ev->width, ev->height); spdlog::info(BAR_SIZE_MSG, ev->width, ev->height, output->name); } void waybar::Bar::configureGlobalOffset(int width, int height) { auto monitor_geometry = *output->monitor->property_geometry().get_value().gobj(); int x; int y; switch (position) { case Gtk::POS_BOTTOM: if (width + margins_.left + margins_.right >= monitor_geometry.width) x = margins_.left; else x = (monitor_geometry.width - width) / 2; y = monitor_geometry.height - height - margins_.bottom; break; case Gtk::POS_LEFT: x = margins_.left; if (height + margins_.top + margins_.bottom >= monitor_geometry.height) y = margins_.top; else y = (monitor_geometry.height - height) / 2; break; case Gtk::POS_RIGHT: x = monitor_geometry.width - width - margins_.right; if (height + margins_.top + margins_.bottom >= monitor_geometry.height) y = margins_.top; else y = (monitor_geometry.height - height) / 2; break; default: /* Gtk::POS_TOP */ if (width + margins_.left + margins_.right >= monitor_geometry.width) x = margins_.left; else x = (monitor_geometry.width - width) / 2; y = margins_.top; break; } x_global = x + monitor_geometry.x; y_global = y + monitor_geometry.y; } void waybar::Bar::onOutputGeometryChanged() { configureGlobalOffset(window.get_width(), window.get_height()); } waybar-0.12.0/src/client.cpp000066400000000000000000000257571475603165300156620ustar00rootroot00000000000000#include "client.hpp" #include #include #include #include #include "gtkmm/icontheme.h" #include "idle-inhibit-unstable-v1-client-protocol.h" #include "util/clara.hpp" #include "util/format.hpp" 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); 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( 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( wl_registry_bind(registry, name, &zwp_idle_inhibit_manager_v1_interface, 1)); } } void waybar::Client::handleGlobalRemove(void *data, struct wl_registry * /*registry*/, uint32_t name) { // Nothing here } 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) {}, .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()); 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) { auto it = std::find_if(outputs_.begin(), outputs_.end(), [&addr](const auto &output) { return &output == addr; }); if (it == outputs_.end()) { throw std::runtime_error("Unable to find valid output"); } return *it; } 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(); try { 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 * for the same output. .done events can also arrive after that for a scale or position changes. * We wouldn't want to draw a duplicate bar for each such event either. * * All the properties we care about are immutable so it's safe to delete the xdg_output object * on the first event and use the ptr value to check that the callback was already invoked. */ if (output.xdg_output) { 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)); } } } } catch (const std::exception &e) { std::cerr << e.what() << '\n'; } } 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); output.name = name; } catch (const std::exception &e) { std::cerr << e.what() << '\n'; } } 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, '('); // 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'; } } void waybar::Client::handleMonitorAdded(Glib::RefPtr monitor) { auto &output = outputs_.emplace_back(); output.monitor = std::move(monitor); handleOutput(output); } void waybar::Client::handleMonitorRemoved(Glib::RefPtr monitor) { spdlog::debug("Output removed: {} {}", monitor->get_manufacturer().c_str(), monitor->get_model().c_str()); /* This event can be triggered from wl_display_roundtrip called by GTK or our code. * Defer destruction of bars for the output to the next iteration of the event loop to avoid * deleting objects referenced by currently executed code. */ Glib::signal_idle().connect_once( sigc::bind(sigc::mem_fun(*this, &Client::handleDeferredMonitorRemoval), monitor), Glib::PRIORITY_HIGH_IDLE); } void waybar::Client::handleDeferredMonitorRemoval(Glib::RefPtr monitor) { for (auto it = bars.begin(); it != bars.end();) { if ((*it)->output->monitor == monitor) { auto output_name = (*it)->output->name; (*it)->window.hide(); gtk_app->remove_window((*it)->window); it = bars.erase(it); spdlog::info("Bar removed from output: {}", output_name); } else { ++it; } } outputs_.remove_if([&monitor](const auto &output) { return output.monitor == monitor; }); } const std::string waybar::Client::getStyle(const std::string &style, std::optional appearance = std::nullopt) { 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"); break; case waybar::Appearance::DARK: search_files.emplace_back("style-dark.css"); break; case waybar::Appearance::UNKNOWN: break; } search_files.emplace_back("style.css"); css_file = Config::findConfigPath(search_files); } 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"); } // there's always only one screen style_context_->add_provider_for_screen(Gdk::Screen::get_default(), css_provider_, GTK_STYLE_PROVIDER_PRIORITY_USER); } void waybar::Client::bindInterfaces() { registry = wl_display_get_registry(wl_display); static const struct wl_registry_listener registry_listener = { .global = handleGlobal, .global_remove = handleGlobalRemove, }; wl_registry_add_listener(registry, ®istry_listener, this); wl_display_roundtrip(wl_display); if (gtk_layer_is_supported() == 0) { throw std::runtime_error("The Wayland compositor does not support wlr-layer-shell protocol"); } if (xdg_output_manager == nullptr) { throw std::runtime_error("Failed to acquire required resources."); } // 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( sigc::mem_fun(*this, &Client::handleMonitorRemoved)); } int waybar::Client::main(int argc, char *argv[]) { bool show_help = false; bool show_version = false; std::string config_opt; std::string style_opt; std::string log_level; auto cli = clara::detail::Help(show_help) | clara::detail::Opt(show_version)["-v"]["--version"]("Show version") | clara::detail::Opt(config_opt, "config")["-c"]["--config"]("Config path") | clara::detail::Opt(style_opt, "style")["-s"]["--style"]("Style path") | clara::detail::Opt( log_level, "trace|debug|info|warning|error|critical|off")["-l"]["--log-level"]("Log level") | clara::detail::Opt(bar_id, "id")["-b"]["--bar"]("Bar id"); auto res = cli.parse(clara::detail::Args(argc, argv)); if (!res) { spdlog::error("Error in command line: {}", res.errorMessage()); return 1; } if (show_help) { std::cout << cli << '\n'; return 0; } if (show_version) { std::cout << "Waybar v" << VERSION << '\n'; return 0; } if (!log_level.empty()) { spdlog::set_level(spdlog::level::from_str(log_level)); } gtk_app = Gtk::Application::create(argc, argv, "fr.arouillard.waybar", Gio::APPLICATION_HANDLES_COMMAND_LINE); // Initialize Waybars GTK resources with our custom icons auto theme = Gtk::IconTheme::get_default(); theme->add_resource_path("/fr/arouillard/waybar/icons"); gdk_display = Gdk::Display::get_default(); if (!gdk_display) { throw std::runtime_error("Can't find display"); } if (!GDK_IS_WAYLAND_DISPLAY(gdk_display->gobj())) { throw std::runtime_error("Bar need to run under Wayland"); } wl_display = gdk_wayland_display_get_wl_display(gdk_display->gobj()); config.load(config_opt); if (!portal) { portal = std::make_unique(); } m_cssFile = getStyle(style_opt); setupCss(m_cssFile); m_cssReloadHelper = std::make_unique(m_cssFile, [&]() { setupCss(m_cssFile); }); portal->signal_appearance_changed().connect([&](waybar::Appearance appearance) { auto css_file = getStyle(style_opt, appearance); setupCss(css_file); }); auto m_config = config.getConfig(); 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) { if (conf["reload_style_on_change"].asBool()) { m_cssReloadHelper->monitorChanges(); break; } } } bindInterfaces(); gtk_app->hold(); gtk_app->run(); m_cssReloadHelper.reset(); // stop watching css file bars.clear(); return 0; } void waybar::Client::reset() { gtk_app->quit(); // delete signal handler for css changes portal->signal_appearance_changed().clear(); } waybar-0.12.0/src/config.cpp000066400000000000000000000135671475603165300156450ustar00rootroot00000000000000#include "config.hpp" #include #include #include #include #include #include #include "util/json.hpp" namespace fs = std::filesystem; namespace waybar { const std::vector Config::CONFIG_DIRS = { "$XDG_CONFIG_HOME/waybar/", "$HOME/.config/waybar/", "$HOME/waybar/", "/etc/xdg/waybar/", SYSCONFDIR "/xdg/waybar/", "./resources/", }; const char *Config::CONFIG_PATH_ENV = "WAYBAR_CONFIG_DIR"; std::vector Config::tryExpandPath(const std::string &base, const std::string &filename) { fs::path path; if (!filename.empty()) { path = fs::path(base) / fs::path(filename); } else { path = fs::path(base); } spdlog::debug("Try expanding: {}", path.string()); std::vector results; wordexp_t p; if (wordexp(path.c_str(), &p, 0) == 0) { for (size_t i = 0; i < p.we_wordc; i++) { if (access(p.we_wordv[i], F_OK) == 0) { results.emplace_back(p.we_wordv[i]); spdlog::debug("Found config file: {}", p.we_wordv[i]); } } wordfree(&p); } 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) { if (auto res = tryExpandPath(dir, name); !res.empty()) { return res.front(); } } } for (const auto &dir : dirs) { for (const auto &name : names) { if (auto res = tryExpandPath(dir, name); !res.empty()) { return res.front(); } } } return std::nullopt; } 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"); } std::ifstream file(config_file); if (!file.is_open()) { throw std::runtime_error("Can't open config file"); } std::string str((std::istreambuf_iterator(file)), std::istreambuf_iterator()); util::JsonParser parser; Json::Value tmp_config = parser.parse(str); if (tmp_config.isArray()) { for (auto &config_part : tmp_config) { resolveConfigIncludes(config_part, depth); } } else { resolveConfigIncludes(tmp_config, depth); } mergeConfig(dst, tmp_config); } void Config::resolveConfigIncludes(Json::Value &config, int depth) { Json::Value includes = config["include"]; if (includes.isArray()) { for (const auto &include : includes) { spdlog::info("Including resource file: {}", include.asString()); for (const auto &match : tryExpandPath(include.asString(), "")) { setupConfig(config, match, depth + 1); } } } else if (includes.isString()) { spdlog::info("Including resource file: {}", includes.asString()); for (const auto &match : tryExpandPath(includes.asString(), "")) { setupConfig(config, match, depth + 1); } } } 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()) { // [] creates key with default value. Use `get` to avoid that. if (a_config_.get(key, Json::Value::nullSingleton()).isObject() && b_config_[key].isObject()) { mergeConfig(a_config_[key], b_config_[key]); } else if (!a_config_.isMember(key)) { // do not allow overriding value set by top or previously included config a_config_[key] = b_config_[key]; } else { spdlog::trace("Option {} is already set; ignoring value {}", key, b_config_[key]); } } } else { spdlog::error("Cannot merge config, conflicting or invalid JSON types"); } } 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"]) { if (output_conf.isString()) { auto config_output = output_conf.asString(); if (config_output.substr(0, 1) == "!") { if (config_output.substr(1) == name || config_output.substr(1) == identifier) { return false; } continue; } if (config_output == name || config_output == identifier) { return true; } if (config_output.substr(0, 1) == "*") { return true; } } } return false; } if (config["output"].isString()) { auto config_output = config["output"].asString(); if (!config_output.empty()) { if (config_output.substr(0, 1) == "!") { return config_output.substr(1) != name && config_output.substr(1) != identifier; } return config_output == name || config_output == identifier; } } return true; } 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"); } config_file_ = file.value(); spdlog::info("Using configuration file {}", config_file_); config_ = Json::Value(); setupConfig(config_, config_file_, 0); } std::vector Config::getOutputConfigs(const std::string &name, const std::string &identifier) { std::vector configs; if (config_.isArray()) { for (auto const &config : config_) { if (config.isObject() && isValidOutput(config, name, identifier)) { configs.push_back(config); } } } else if (isValidOutput(config_, name, identifier)) { configs.push_back(config_); } return configs; } } // namespace waybar waybar-0.12.0/src/factory.cpp000066400000000000000000000241251475603165300160370ustar00rootroot00000000000000#include "factory.hpp" #include "bar.hpp" #if defined(HAVE_CHRONO_TIMEZONES) || defined(HAVE_LIBDATE) #include "modules/clock.hpp" #else #include "modules/simpleclock.hpp" #endif #ifdef HAVE_SWAY #include "modules/sway/language.hpp" #include "modules/sway/mode.hpp" #include "modules/sway/scratchpad.hpp" #include "modules/sway/window.hpp" #include "modules/sway/workspaces.hpp" #endif #ifdef HAVE_WLR_TASKBAR #include "modules/wlr/taskbar.hpp" #endif #ifdef HAVE_WLR_WORKSPACES #include "modules/wlr/workspace_manager.hpp" #endif #ifdef HAVE_RIVER #include "modules/river/layout.hpp" #include "modules/river/mode.hpp" #include "modules/river/tags.hpp" #include "modules/river/window.hpp" #endif #ifdef HAVE_DWL #include "modules/dwl/tags.hpp" #include "modules/dwl/window.hpp" #endif #ifdef HAVE_HYPRLAND #include "modules/hyprland/language.hpp" #include "modules/hyprland/submap.hpp" #include "modules/hyprland/window.hpp" #include "modules/hyprland/workspaces.hpp" #endif #ifdef HAVE_NIRI #include "modules/niri/language.hpp" #include "modules/niri/window.hpp" #include "modules/niri/workspaces.hpp" #endif #if defined(__FreeBSD__) || defined(__linux__) #include "modules/battery.hpp" #endif #if defined(HAVE_CPU_LINUX) || defined(HAVE_CPU_BSD) #include "modules/cpu.hpp" #include "modules/cpu_frequency.hpp" #include "modules/cpu_usage.hpp" #include "modules/load.hpp" #endif #include "modules/idle_inhibitor.hpp" #if defined(HAVE_MEMORY_LINUX) || defined(HAVE_MEMORY_BSD) #include "modules/memory.hpp" #endif #include "modules/disk.hpp" #ifdef HAVE_DBUSMENU #include "modules/sni/tray.hpp" #endif #ifdef HAVE_MPRIS #include "modules/mpris/mpris.hpp" #endif #ifdef HAVE_LIBNL #include "modules/network.hpp" #endif #ifdef HAVE_LIBUDEV #include "modules/backlight.hpp" #include "modules/backlight_slider.hpp" #endif #ifdef HAVE_LIBEVDEV #include "modules/keyboard_state.hpp" #endif #ifdef HAVE_GAMEMODE #include "modules/gamemode.hpp" #endif #ifdef HAVE_UPOWER #include "modules/upower.hpp" #endif #ifdef HAVE_PIPEWIRE #include "modules/privacy/privacy.hpp" #endif #ifdef HAVE_LIBPULSE #include "modules/pulseaudio.hpp" #include "modules/pulseaudio_slider.hpp" #endif #ifdef HAVE_LIBMPDCLIENT #include "modules/mpd/mpd.hpp" #endif #ifdef HAVE_LIBSNDIO #include "modules/sndio.hpp" #endif #if defined(__linux__) #include "modules/bluetooth.hpp" #include "modules/power_profiles_daemon.hpp" #endif #ifdef HAVE_LOGIND_INHIBITOR #include "modules/inhibitor.hpp" #endif #ifdef HAVE_LIBJACK #include "modules/jack.hpp" #endif #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 #include "modules/cffi.hpp" #include "modules/custom.hpp" #include "modules/image.hpp" #include "modules/temperature.hpp" #include "modules/user.hpp" waybar::Factory::Factory(const Bar& bar, const Json::Value& config) : bar_(bar), config_(config) {} waybar::AModule* waybar::Factory::makeModule(const std::string& name, const std::string& pos) const { try { auto hash_pos = name.find('#'); auto ref = name.substr(0, hash_pos); auto id = hash_pos != std::string::npos ? name.substr(hash_pos + 1) : ""; #if defined(__FreeBSD__) || defined(__linux__) if (ref == "battery") { return new waybar::modules::Battery(id, bar_, config_[name]); } #endif #ifdef HAVE_GAMEMODE if (ref == "gamemode") { return new waybar::modules::Gamemode(id, config_[name]); } #endif #ifdef HAVE_UPOWER if (ref == "upower") { return new waybar::modules::UPower(id, config_[name]); } #endif #ifdef HAVE_PIPEWIRE if (ref == "privacy") { return new waybar::modules::privacy::Privacy(id, config_[name], pos); } #endif #ifdef HAVE_MPRIS if (ref == "mpris") { return new waybar::modules::mpris::Mpris(id, config_[name]); } #endif #ifdef HAVE_SWAY if (ref == "sway/mode") { return new waybar::modules::sway::Mode(id, config_[name]); } if (ref == "sway/workspaces") { return new waybar::modules::sway::Workspaces(id, bar_, config_[name]); } if (ref == "sway/window") { return new waybar::modules::sway::Window(id, bar_, config_[name]); } if (ref == "sway/language") { return new waybar::modules::sway::Language(id, config_[name]); } if (ref == "sway/scratchpad") { return new waybar::modules::sway::Scratchpad(id, config_[name]); } #endif #ifdef HAVE_WLR_TASKBAR if (ref == "wlr/taskbar") { 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]); } #endif #ifdef HAVE_RIVER if (ref == "river/mode") { return new waybar::modules::river::Mode(id, bar_, config_[name]); } if (ref == "river/tags") { return new waybar::modules::river::Tags(id, bar_, config_[name]); } if (ref == "river/window") { return new waybar::modules::river::Window(id, bar_, config_[name]); } if (ref == "river/layout") { return new waybar::modules::river::Layout(id, bar_, config_[name]); } #endif #ifdef HAVE_DWL if (ref == "dwl/tags") { return new waybar::modules::dwl::Tags(id, bar_, config_[name]); } if (ref == "dwl/window") { return new waybar::modules::dwl::Window(id, bar_, config_[name]); } #endif #ifdef HAVE_HYPRLAND if (ref == "hyprland/window") { return new waybar::modules::hyprland::Window(id, bar_, config_[name]); } if (ref == "hyprland/language") { return new waybar::modules::hyprland::Language(id, bar_, config_[name]); } if (ref == "hyprland/submap") { return new waybar::modules::hyprland::Submap(id, bar_, config_[name]); } if (ref == "hyprland/workspaces") { return new waybar::modules::hyprland::Workspaces(id, bar_, config_[name]); } #endif #ifdef HAVE_NIRI if (ref == "niri/language") { return new waybar::modules::niri::Language(id, bar_, config_[name]); } if (ref == "niri/window") { return new waybar::modules::niri::Window(id, bar_, config_[name]); } if (ref == "niri/workspaces") { return new waybar::modules::niri::Workspaces(id, bar_, config_[name]); } #endif if (ref == "idle_inhibitor") { return new waybar::modules::IdleInhibitor(id, bar_, config_[name]); } #if defined(HAVE_MEMORY_LINUX) || defined(HAVE_MEMORY_BSD) if (ref == "memory") { return new waybar::modules::Memory(id, config_[name]); } #endif #if defined(HAVE_CPU_LINUX) || defined(HAVE_CPU_BSD) if (ref == "cpu") { return new waybar::modules::Cpu(id, config_[name]); } #if defined(HAVE_CPU_LINUX) if (ref == "cpu_frequency") { return new waybar::modules::CpuFrequency(id, config_[name]); } #endif if (ref == "cpu_usage") { return new waybar::modules::CpuUsage(id, config_[name]); } if (ref == "load") { return new waybar::modules::Load(id, config_[name]); } #endif if (ref == "clock") { return new waybar::modules::Clock(id, config_[name]); } if (ref == "user") { return new waybar::modules::User(id, config_[name]); } if (ref == "disk") { return new waybar::modules::Disk(id, config_[name]); } if (ref == "image") { return new waybar::modules::Image(id, config_[name]); } #ifdef HAVE_DBUSMENU if (ref == "tray") { return new waybar::modules::SNI::Tray(id, bar_, config_[name]); } #endif #ifdef HAVE_LIBNL if (ref == "network") { return new waybar::modules::Network(id, config_[name]); } #endif #ifdef HAVE_LIBUDEV if (ref == "backlight") { return new waybar::modules::Backlight(id, config_[name]); } if (ref == "backlight/slider") { return new waybar::modules::BacklightSlider(id, config_[name]); } #endif #ifdef HAVE_LIBEVDEV if (ref == "keyboard-state") { return new waybar::modules::KeyboardState(id, bar_, config_[name]); } #endif #ifdef HAVE_LIBPULSE if (ref == "pulseaudio") { return new waybar::modules::Pulseaudio(id, config_[name]); } if (ref == "pulseaudio/slider") { return new waybar::modules::PulseaudioSlider(id, config_[name]); } #endif #ifdef HAVE_LIBMPDCLIENT if (ref == "mpd") { return new waybar::modules::MPD(id, config_[name]); } #endif #ifdef HAVE_LIBSNDIO if (ref == "sndio") { return new waybar::modules::Sndio(id, config_[name]); } #endif #if defined(__linux__) if (ref == "bluetooth") { return new waybar::modules::Bluetooth(id, config_[name]); } if (ref == "power-profiles-daemon") { return new waybar::modules::PowerProfilesDaemon(id, config_[name]); } #endif #ifdef HAVE_LOGIND_INHIBITOR if (ref == "inhibitor") { return new waybar::modules::Inhibitor(id, bar_, config_[name]); } #endif #ifdef HAVE_LIBJACK if (ref == "jack") { return new waybar::modules::JACK(id, config_[name]); } #endif #ifdef HAVE_LIBWIREPLUMBER if (ref == "wireplumber") { return new waybar::modules::Wireplumber(id, config_[name]); } #endif #ifdef HAVE_LIBCAVA if (ref == "cava") { return new waybar::modules::Cava(id, config_[name]); } #endif #ifdef HAVE_SYSTEMD_MONITOR if (ref == "systemd-failed-units") { return new waybar::modules::SystemdFailedUnits(id, config_[name]); } #endif if (ref == "temperature") { return new waybar::modules::Temperature(id, config_[name]); } if (ref.compare(0, 7, "custom/") == 0 && ref.size() > 7) { return new waybar::modules::Custom(ref.substr(7), id, config_[name], bar_.output->name); } if (ref.compare(0, 5, "cffi/") == 0 && ref.size() > 5) { return new waybar::modules::CFFI(ref.substr(5), id, config_[name]); } } catch (const std::exception& e) { auto err = fmt::format("Disabling module \"{}\", {}", name, e.what()); throw std::runtime_error(err); } catch (...) { auto err = fmt::format("Disabling module \"{}\", Unknown reason", name); throw std::runtime_error(err); } throw std::runtime_error("Unknown module: " + name); } waybar-0.12.0/src/group.cpp000066400000000000000000000104021475603165300155150ustar00rootroot00000000000000#include "group.hpp" #include #include #include "gtkmm/enums.h" #include "gtkmm/widget.h" namespace waybar { Gtk::RevealerTransitionType getPreferredTransitionType(bool is_vertical) { /* The transition direction of a drawer is not actually determined by the transition type, * but rather by the order of 'box' and 'revealer_box': * 'REVEALER_TRANSITION_TYPE_SLIDE_LEFT' and 'REVEALER_TRANSITION_TYPE_SLIDE_RIGHT' * will result in the same thing. * However: we still need to differentiate between vertical and horizontal transition types. */ if (is_vertical) { return Gtk::RevealerTransitionType::REVEALER_TRANSITION_TYPE_SLIDE_UP; } return Gtk::RevealerTransitionType::REVEALER_TRANSITION_TYPE_SLIDE_LEFT; } Group::Group(const std::string& name, const std::string& id, const Json::Value& config, bool vertical) : AModule(config, name, id, true, true), box{vertical ? Gtk::ORIENTATION_VERTICAL : Gtk::ORIENTATION_HORIZONTAL, 0}, revealer_box{vertical ? Gtk::ORIENTATION_VERTICAL : Gtk::ORIENTATION_HORIZONTAL, 0} { box.set_name(name_); if (!id.empty()) { box.get_style_context()->add_class(id); } // default orientation: orthogonal to parent auto orientation = config_["orientation"].empty() ? "orthogonal" : config_["orientation"].asString(); if (orientation == "inherit") { // keep orientation passed } else if (orientation == "orthogonal") { box.set_orientation(vertical ? Gtk::ORIENTATION_HORIZONTAL : Gtk::ORIENTATION_VERTICAL); } else if (orientation == "vertical") { box.set_orientation(Gtk::ORIENTATION_VERTICAL); } else if (orientation == "horizontal") { box.set_orientation(Gtk::ORIENTATION_HORIZONTAL); } else { throw std::runtime_error("Invalid orientation value: " + orientation); } if (config_["drawer"].isObject()) { is_drawer = true; const auto& drawer_config = config_["drawer"]; const int transition_duration = (drawer_config["transition-duration"].isInt() ? drawer_config["transition-duration"].asInt() : 500); add_class_to_drawer_children = (drawer_config["children-class"].isString() ? drawer_config["children-class"].asString() : "drawer-child"); const bool left_to_right = (drawer_config["transition-left-to-right"].isBool() ? drawer_config["transition-left-to-right"].asBool() : true); click_to_reveal = drawer_config["click-to-reveal"].asBool(); auto transition_type = getPreferredTransitionType(vertical); revealer.set_transition_type(transition_type); revealer.set_transition_duration(transition_duration); revealer.set_reveal_child(false); revealer.get_style_context()->add_class("drawer"); revealer.add(revealer_box); if (left_to_right) { box.pack_end(revealer); } else { box.pack_start(revealer); } } event_box_.add(box); } void Group::show_group() { box.set_state_flags(Gtk::StateFlags::STATE_FLAG_PRELIGHT); revealer.set_reveal_child(true); } void Group::hide_group() { box.unset_state_flags(Gtk::StateFlags::STATE_FLAG_PRELIGHT); revealer.set_reveal_child(false); } bool Group::handleMouseEnter(GdkEventCrossing* const& e) { if (!click_to_reveal) { show_group(); } return false; } bool Group::handleMouseLeave(GdkEventCrossing* const& e) { if (!click_to_reveal && e->detail != GDK_NOTIFY_INFERIOR) { hide_group(); } return false; } bool Group::handleToggle(GdkEventButton* const& e) { if (!click_to_reveal || e->button != 1) { return false; } if ((box.get_state_flags() & Gtk::StateFlags::STATE_FLAG_PRELIGHT) != 0U) { hide_group(); } else { show_group(); } return true; } auto Group::update() -> void { // noop } Gtk::Box& Group::getBox() { return is_drawer ? (is_first_widget ? box : revealer_box) : box; } void Group::addWidget(Gtk::Widget& widget) { getBox().pack_start(widget, false, false); if (is_drawer && !is_first_widget) { widget.get_style_context()->add_class(add_class_to_drawer_children); } is_first_widget = false; } Group::operator Gtk::Widget&() { return event_box_; } } // namespace waybar waybar-0.12.0/src/main.cpp000066400000000000000000000056351475603165300153210ustar00rootroot00000000000000#include #include #include #include #include #include #include "client.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); while (true) { err = sigwait(&mask, &signum); if (err != 0) { spdlog::error("sigwait failed: {}", strerror(errno)); 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; } } } 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); } 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); } } 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(); } }); std::signal(SIGUSR2, [](int /*signal*/) { spdlog::info("Reloading..."); reload = true; waybar::Client::inst()->reset(); }); std::signal(SIGINT, [](int /*signal*/) { spdlog::info("Quitting."); reload = false; waybar::Client::inst()->reset(); }); for (int sig = SIGRTMIN + 1; sig <= SIGRTMAX; ++sig) { std::signal(sig, [](int sig) { for (auto& bar : waybar::Client::inst()->bars) { bar->handleSignal(sig); } }); } startSignalThread(); auto ret = 0; do { reload = false; ret = client->main(argc, argv); } while (reload); std::signal(SIGUSR1, SIG_IGN); std::signal(SIGUSR2, SIG_IGN); std::signal(SIGINT, SIG_IGN); delete client; return ret; } catch (const std::exception& e) { spdlog::error("{}", e.what()); return 1; } catch (const Glib::Exception& e) { spdlog::error("{}", static_cast(e.what())); return 1; } } waybar-0.12.0/src/modules/000077500000000000000000000000001475603165300153305ustar00rootroot00000000000000waybar-0.12.0/src/modules/backlight.cpp000066400000000000000000000072571475603165300177770ustar00rootroot00000000000000#include "modules/backlight.hpp" #include #include #include #include #include #include #include #include #include "util/backend_common.hpp" #include "util/backlight_backend.hpp" 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(); }) { dp.emit(); // Set up scroll handler event_box_.add_events(Gdk::SCROLL_MASK | Gdk::SMOOTH_SCROLL_MASK); event_box_.signal_scroll_event().connect(sigc::mem_fun(*this, &Backlight::handleScroll)); } auto waybar::modules::Backlight::update() -> void { GET_BEST_DEVICE(best, backend, preferred_device_); const auto previous_best_device = backend.get_previous_best_device(); if (best != nullptr) { if (previous_best_device != nullptr && *previous_best_device == *best && !previous_format_.empty() && previous_format_ == format_) { return; } if (best->get_powered()) { event_box_.show(); const uint8_t percent = best->get_max() == 0 ? 100 : round(best->get_actual() * 100.0f / best->get_max()); std::string desc = fmt::format(fmt::runtime(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)))); } else { label_.set_tooltip_text(desc); } } } else { event_box_.hide(); } } else { if (previous_best_device == nullptr) { return; } label_.set_markup(""); } backend.set_previous_best_device(best); previous_format_ = format_; ALabel::update(); } 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); } // Fail fast if the proxy could not be initialized if (!backend.is_login_proxy_initialized()) { return true; } // Check scroll direction auto dir = AModule::getScrollDir(e); // No worries, it will always be set because of the switch below. This is purely to suppress a // warning util::ChangeType ct = util::ChangeType::Increase; switch (dir) { case SCROLL_DIR::UP: [[fallthrough]]; case SCROLL_DIR::RIGHT: ct = util::ChangeType::Increase; break; case SCROLL_DIR::DOWN: [[fallthrough]]; case SCROLL_DIR::LEFT: ct = util::ChangeType::Decrease; break; case SCROLL_DIR::NONE: return true; break; } // Get scroll step double step = 1; if (config_["scroll-step"].isDouble()) { step = config_["scroll-step"].asDouble(); } double min_brightness = 0; if (config_["min-brightness"].isDouble()) { min_brightness = config_["min-brightness"].asDouble(); } if (backend.get_scaled_brightness(preferred_device_) <= min_brightness && ct == util::ChangeType::Decrease) { return true; } backend.set_brightness(preferred_device_, ct, step); return true; } waybar-0.12.0/src/modules/backlight_slider.cpp000066400000000000000000000014111475603165300213230ustar00rootroot00000000000000#include "modules/backlight_slider.hpp" #include "ASlider.hpp" namespace waybar::modules { BacklightSlider::BacklightSlider(const std::string& id, const Json::Value& config) : ASlider(config, "backlight-slider", id), interval_(config_["interval"].isUInt() ? config_["interval"].asUInt() : 1000), preferred_device_(config["device"].isString() ? config["device"].asString() : ""), backend(interval_, [this] { this->dp.emit(); }) {} void BacklightSlider::update() { uint16_t brightness = backend.get_scaled_brightness(preferred_device_); scale_.set_value(brightness); } void BacklightSlider::onValueChanged() { auto brightness = scale_.get_value(); backend.set_scaled_brightness(preferred_device_, brightness); } } // namespace waybar::moduleswaybar-0.12.0/src/modules/battery.cpp000066400000000000000000000704051475603165300175140ustar00rootroot00000000000000#include "modules/battery.hpp" #include #if defined(__FreeBSD__) #include #endif #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) { #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."); } // 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"); } #endif worker(); } 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; if (watch_id >= 0) { inotify_rm_watch(battery_watch_fd_, watch_id); } batteries_.erase(it); } close(battery_watch_fd_); #endif } void waybar::modules::Battery::worker() { #if defined(__FreeBSD__) thread_timer_ = [this] { dp.emit(); thread_timer_.sleep_for(interval_); }; #else thread_timer_ = [this] { // Make sure we eventually update the list of batteries even if we miss an // inotify event for some reason refreshBatteries(); dp.emit(); thread_timer_.sleep_for(interval_); }; thread_ = [this] { struct inotify_event event = {0}; int nbytes = read(battery_watch_fd_, &event, sizeof(event)); if (nbytes != sizeof(event) || event.mask & IN_IGNORED) { thread_.stop(); return; } 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) { thread_.stop(); return; } refreshBatteries(); dp.emit(); }; #endif } void waybar::modules::Battery::refreshBatteries() { #if defined(__linux__) std::lock_guard guard(battery_list_mutex_); // Mark existing list of batteries as not necessarily found std::map check_map; for (auto const& bat : batteries_) { check_map[bat.first] = false; } try { for (auto& node : fs::directory_iterator(data_dir_)) { if (!fs::is_directory(node)) { continue; } auto dir_name = node.path().filename(); auto bat_defined = config_["bat"].isString(); bool bat_compatibility = config_["bat-compatibility"].asBool(); 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")) { std::string type; std::ifstream(node.path() / "type") >> type; if (!type.compare("Battery")) { // Ignore non-system power supplies unless explicitly requested if (!bat_defined && fs::exists(node.path() / "scope")) { std::string scope; std::ifstream(node.path() / "scope") >> scope; if (g_ascii_strcasecmp(scope.data(), "device") == 0) { continue; } } check_map[node.path()] = true; auto search = batteries_.find(node.path()); if (search == batteries_.end()) { // We've found a new battery save it and start listening for events 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()); } batteries_[node.path()] = wd; } } } auto adap_defined = config_["adapter"].isString(); if (((adap_defined && dir_name == config_["adapter"].asString()) || !adap_defined) && (fs::exists(node.path() / "online") || fs::exists(node.path() / "status"))) { adapter_ = node.path(); } } } catch (fs::filesystem_error& e) { throw std::runtime_error(e.what()); } if (warnFirstTime_ && batteries_.empty()) { if (config_["bat"].isString()) { spdlog::warn("No battery named {0}", config_["bat"].asString()); } else { spdlog::warn("No batteries."); } warnFirstTime_ = false; } // Remove any batteries that are no longer present and unwatch them for (auto const& check : check_map) { if (!check.second) { auto watch_id = batteries_[check.first]; if (watch_id >= 0) { inotify_rm_watch(battery_watch_fd_, watch_id); } batteries_.erase(check.first); } } #endif } // Unknown > Full > Not charging > Discharging > Charging static bool status_gt(const std::string& a, const std::string& b) { if (a == b) return false; else if (a == "Unknown") return true; else if (a == "Full" && b != "Unknown") return true; else if (a == "Not charging" && b != "Unknown" && b != "Full") return true; else if (a == "Discharging" && b != "Unknown" && b != "Full" && b != "Not charging") return true; return false; } std::tuple waybar::modules::Battery::getInfos() { std::lock_guard guard(battery_list_mutex_); try { #if defined(__FreeBSD__) /* Allocate state of battery units reported via ACPI. */ int battery_units = 0; size_t battery_units_size = sizeof battery_units; if (sysctlbyname("hw.acpi.battery.units", &battery_units, &battery_units_size, NULL, 0) != 0) { throw std::runtime_error("sysctl hw.acpi.battery.units failed"); } if (battery_units < 0) { throw std::runtime_error("No battery units"); } int capacity; size_t size_capacity = sizeof capacity; if (sysctlbyname("hw.acpi.battery.life", &capacity, &size_capacity, NULL, 0) != 0) { throw std::runtime_error("sysctl hw.acpi.battery.life failed"); } int time; size_t size_time = sizeof time; if (sysctlbyname("hw.acpi.battery.time", &time, &size_time, NULL, 0) != 0) { throw std::runtime_error("sysctl hw.acpi.battery.time failed"); } int rate; size_t size_rate = sizeof rate; if (sysctlbyname("hw.acpi.battery.rate", &rate, &size_rate, NULL, 0) != 0) { throw std::runtime_error("sysctl hw.acpi.battery.rate failed"); } auto status = getAdapterStatus(capacity); // Handle full-at if (config_["full-at"].isUInt()) { auto full_at = config_["full-at"].asUInt(); if (full_at < 100) { capacity = 100.f * capacity / full_at; } } if (capacity > 100.f) { // This can happen when the battery is calibrating and goes above 100% // Handle it gracefully by clamping at 100% capacity = 100.f; } uint8_t cap = round(capacity); if (cap == 100 && status == "Plugged") { // If we've reached 100% just mark as full as some batteries can stay // stuck reporting they're still charging but not yet done status = "Full"; } // spdlog::info("{} {} {} {}", capacity,time,status,rate); return {capacity, time / 60.0, status, rate, 0, 0.0F}; #elif defined(__linux__) uint32_t total_power = 0; // μW bool total_power_exists = false; uint32_t total_energy = 0; // μWh bool total_energy_exists = false; uint32_t total_energy_full = 0; bool total_energy_full_exists = false; uint32_t total_energy_full_design = 0; bool total_energy_full_design_exists = false; uint32_t total_capacity = 0; bool total_capacity_exists = false; uint32_t time_to_empty_now = 0; bool time_to_empty_now_exists = false; uint32_t time_to_full_now = 0; bool time_to_full_now_exists = false; uint32_t largestDesignCapacity = 0; uint16_t mainBatCycleCount = 0; float mainBatHealthPercent = 0.0F; std::string status = "Unknown"; for (auto const& item : batteries_) { 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); } // Some battery will report current and charge in μA/μAh. // Scale these by the voltage to get μW/μWh. 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; } // 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 (fs::exists(bat / "time_to_full_now")) { time_to_full_now_exists = true; std::ifstream(bat / "time_to_full_now") >> time_to_full_now; } 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; } 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; } 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; } 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; } 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; } // Some drivers (example: Qualcomm) exposes use a negative value when // discharging, positive value when charging. power_now = std::abs(_power_now_int); 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; } 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; } 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; } uint16_t cycleCount = 0; if (fs::exists(bat / "cycle_count")) { std::ifstream(bat / "cycle_count") >> cycleCount; } if (charge_full_design >= largestDesignCapacity) { largestDesignCapacity = charge_full_design; if (cycleCount > mainBatCycleCount) { mainBatCycleCount = cycleCount; } if (charge_full_exists && charge_full_design_exists) { float batHealthPercent = ((float)charge_full / charge_full_design) * 100; if (mainBatHealthPercent == 0.0F || batHealthPercent < mainBatHealthPercent) { mainBatHealthPercent = batHealthPercent; } } else if (energy_full_exists && energy_full_design_exists) { float batHealthPercent = ((float)energy_full / energy_full_design) * 100; if (mainBatHealthPercent == 0.0F || batHealthPercent < mainBatHealthPercent) { mainBatHealthPercent = batHealthPercent; } } } uint32_t capacity = 0; bool capacity_exists = false; if (charge_now_exists && charge_full_exists && charge_full != 0) { capacity_exists = true; capacity = 100 * (uint64_t)charge_now / (uint64_t)charge_full; } 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; } if (!voltage_now_exists) { if (power_now_exists && current_now_exists && current_now != 0) { voltage_now_exists = true; voltage_now = 1000000 * (uint64_t)power_now / (uint64_t)current_now; } else if (energy_full_design_exists && charge_full_design_exists && charge_full_design != 0) { voltage_now_exists = true; voltage_now = 1000000 * (uint64_t)energy_full_design / (uint64_t)charge_full_design; } else if (energy_now_exists) { if (charge_now_exists && charge_now != 0) { voltage_now_exists = true; voltage_now = 1000000 * (uint64_t)energy_now / (uint64_t)charge_now; } else if (capacity_exists && charge_full_exists) { charge_now_exists = true; charge_now = (uint64_t)charge_full * (uint64_t)capacity / 100; if (charge_full != 0 && capacity != 0) { voltage_now_exists = true; voltage_now = 1000000 * (uint64_t)energy_now * 100 / (uint64_t)charge_full / (uint64_t)capacity; } } } else if (energy_full_exists) { if (charge_full_exists && charge_full != 0) { voltage_now_exists = true; voltage_now = 1000000 * (uint64_t)energy_full / (uint64_t)charge_full; } else if (charge_now_exists && capacity_exists) { if (capacity != 0) { charge_full_exists = true; charge_full = 100 * (uint64_t)charge_now / (uint64_t)capacity; } if (charge_now != 0) { voltage_now_exists = true; voltage_now = 10000 * (uint64_t)energy_full * (uint64_t)capacity / (uint64_t)charge_now; } } } } if (!capacity_exists) { if (charge_now_exists && energy_full_exists && voltage_now_exists) { if (!charge_full_exists && voltage_now != 0) { charge_full_exists = true; charge_full = 1000000 * (uint64_t)energy_full / (uint64_t)voltage_now; } if (energy_full != 0) { capacity_exists = true; capacity = (uint64_t)charge_now * (uint64_t)voltage_now / 10000 / (uint64_t)energy_full; } } else if (charge_full_exists && energy_now_exists && voltage_now_exists) { if (!charge_now_exists && voltage_now != 0) { charge_now_exists = true; charge_now = 1000000 * (uint64_t)energy_now / (uint64_t)voltage_now; } if (voltage_now != 0 && charge_full != 0) { capacity_exists = true; capacity = 100 * 1000000 * (uint64_t)energy_now / (uint64_t)voltage_now / (uint64_t)charge_full; } } } if (!energy_now_exists && voltage_now_exists) { if (charge_now_exists) { energy_now_exists = true; energy_now = (uint64_t)charge_now * (uint64_t)voltage_now / 1000000; } else if (capacity_exists && charge_full_exists) { charge_now_exists = true; charge_now = (uint64_t)capacity * (uint64_t)charge_full / 100; energy_now_exists = true; energy_now = (uint64_t)voltage_now * (uint64_t)capacity * (uint64_t)charge_full / 1000000 / 100; } else if (capacity_exists && energy_full) { if (voltage_now != 0) { charge_full_exists = true; charge_full = 1000000 * (uint64_t)energy_full / (uint64_t)voltage_now; charge_now_exists = true; charge_now = (uint64_t)capacity * 10000 * (uint64_t)energy_full / (uint64_t)voltage_now; } energy_now_exists = true; energy_now = (uint64_t)capacity * (uint64_t)energy_full / 100; } } if (!energy_full_exists && voltage_now_exists) { if (charge_full_exists) { energy_full_exists = true; energy_full = (uint64_t)charge_full * (uint64_t)voltage_now / 1000000; } else if (charge_now_exists && capacity_exists && capacity != 0) { charge_full_exists = true; charge_full = 100 * (uint64_t)charge_now / (uint64_t)capacity; energy_full_exists = true; energy_full = (uint64_t)charge_now * (uint64_t)voltage_now / (uint64_t)capacity / 10000; } else if (capacity_exists && energy_now) { if (voltage_now != 0) { charge_now_exists = true; charge_now = 1000000 * (uint64_t)energy_now / (uint64_t)voltage_now; } if (capacity != 0) { energy_full_exists = true; energy_full = 100 * (uint64_t)energy_now / (uint64_t)capacity; if (voltage_now != 0) { charge_full_exists = true; charge_full = 100 * 1000000 * (uint64_t)energy_now / (uint64_t)voltage_now / (uint64_t)capacity; } } } } if (!power_now_exists && voltage_now_exists && current_now_exists) { power_now_exists = true; power_now = (uint64_t)voltage_now * (uint64_t)current_now / 1000000; } if (!energy_full_design_exists && voltage_now_exists && charge_full_design_exists) { energy_full_design_exists = true; energy_full_design = (uint64_t)voltage_now * (uint64_t)charge_full_design / 1000000; } // Show the "smallest" status among all batteries if (status_gt(status, _status)) status = _status; if (power_now_exists) { total_power_exists = true; total_power += power_now; } if (energy_now_exists) { total_energy_exists = true; total_energy += energy_now; } if (energy_full_exists) { total_energy_full_exists = true; total_energy_full += energy_full; } if (energy_full_design_exists) { total_energy_full_design_exists = true; total_energy_full_design += energy_full_design; } if (capacity_exists) { total_capacity_exists = true; total_capacity += capacity; } } // Give `Plugged` higher priority over `Not charging`. // So in a setting where TLP is used, `Plugged` is shown when the threshold is reached if (!adapter_.empty() && (status == "Discharging" || status == "Not charging")) { bool online; std::string current_status; std::ifstream(adapter_ / "online") >> online; std::getline(std::ifstream(adapter_ / "status"), current_status); if (online && current_status != "Discharging") status = "Plugged"; } float time_remaining{0.0f}; if (status == "Discharging" && time_to_empty_now_exists) { if (time_to_empty_now != 0) time_remaining = (float)time_to_empty_now / 3600.0f; } else if (status == "Discharging" && total_power_exists && total_energy_exists) { if (total_power != 0) time_remaining = (float)total_energy / total_power; } else if (status == "Charging" && time_to_full_now_exists) { if (time_to_full_now_exists && (time_to_full_now != 0)) time_remaining = -(float)time_to_full_now / 3600.0f; // If we've turned positive it means the battery is past 100% and so just report that as no // time remaining if (time_remaining > 0.0f) time_remaining = 0.0f; } else if (status == "Charging" && total_energy_exists && total_energy_full_exists && total_power_exists) { if (total_power != 0) time_remaining = -(float)(total_energy_full - total_energy) / total_power; // If we've turned positive it means the battery is past 100% and so just report that as no // time remaining if (time_remaining > 0.0f) time_remaining = 0.0f; } float calculated_capacity{0.0f}; if (total_capacity_exists) { 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) 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 (total_energy_full > 0.0f) calculated_capacity = ((float)total_energy * 100.0f / (float)total_energy_full); } // Handle design-capacity if ((config_["design-capacity"].isBool() ? config_["design-capacity"].asBool() : false) && total_energy_exists && total_energy_full_design_exists) { if (total_energy_full_design > 0.0f) calculated_capacity = ((float)total_energy * 100.0f / (float)total_energy_full_design); } // Handle full-at if (config_["full-at"].isUInt()) { auto full_at = config_["full-at"].asUInt(); if (full_at < 100) calculated_capacity = 100.f * calculated_capacity / full_at; } // Handle it gracefully by clamping at 100% // This can happen when the battery is calibrating and goes above 100% if (calculated_capacity > 100.f) calculated_capacity = 100.f; uint8_t cap = round(calculated_capacity); // If we've reached 100% just mark as full as some batteries can stay stuck reporting they're // still charging but not yet done if (cap == 100 && status == "Charging") status = "Full"; return { cap, time_remaining, status, total_power / 1e6, mainBatCycleCount, mainBatHealthPercent}; #endif } catch (const std::exception& e) { spdlog::error("Battery: {}", e.what()); return {0, 0, "Unknown", 0, 0, 0.0f}; } } const std::string waybar::modules::Battery::getAdapterStatus(uint8_t capacity) const { #if defined(__FreeBSD__) int state; size_t size_state = sizeof state; if (sysctlbyname("hw.acpi.battery.state", &state, &size_state, NULL, 0) != 0) { throw std::runtime_error("sysctl hw.acpi.battery.state failed"); } bool online = state == 2; std::string status{"Unknown"}; // TODO: add status in FreeBSD { #else if (!adapter_.empty()) { bool online; std::string status; std::ifstream(adapter_ / "online") >> online; std::getline(std::ifstream(adapter_ / "status"), status); #endif if (capacity == 100) { return "Full"; } if (online && status != "Discharging") { return "Plugged"; } return "Discharging"; } return "Unknown"; } const std::string waybar::modules::Battery::formatTimeRemaining(float hoursRemaining) { hoursRemaining = std::fabs(hoursRemaining); uint16_t full_hours = static_cast(hoursRemaining); uint16_t minutes = static_cast(60 * (hoursRemaining - full_hours)); auto format = std::string("{H} h {M} min"); if (full_hours == 0 && minutes == 0) { // Migh as well not show "0h 0min" return ""; } if (config_["format-time"].isString()) { format = config_["format-time"].asString(); } std::string zero_pad_minutes = fmt::format("{:02d}", minutes); return fmt::format(fmt::runtime(format), fmt::arg("H", full_hours), fmt::arg("M", minutes), fmt::arg("m", zero_pad_minutes)); } auto waybar::modules::Battery::update() -> void { #if defined(__linux__) if (batteries_.empty()) { event_box_.hide(); return; } #endif auto [capacity, time_remaining, status, power, cycles, health] = getInfos(); 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); 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; } else { tooltip_text_default = status_pretty; } if (!state.empty() && config_["tooltip-format-" + status + "-" + state].isString()) { tooltip_format = config_["tooltip-format-" + status + "-" + state].asString(); } else if (config_["tooltip-format-" + status].isString()) { tooltip_format = config_["tooltip-format-" + status].asString(); } else 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(); } label_.set_tooltip_text( 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), fmt::arg("health", fmt::format("{:.3}", health)))); } if (!old_status_.empty()) { label_.get_style_context()->remove_class(old_status_); } label_.get_style_context()->add_class(status); old_status_ = status; if (!state.empty() && config_["format-" + status + "-" + state].isString()) { format = config_["format-" + status + "-" + state].asString(); } else if (config_["format-" + status].isString()) { format = config_["format-" + status].asString(); } else if (!state.empty() && config_["format-" + state].isString()) { format = config_["format-" + state].asString(); } if (format.empty()) { event_box_.hide(); } else { event_box_.show(); auto icons = std::vector{status + "-" + state, status, state}; label_.set_markup(fmt::format( fmt::runtime(format), fmt::arg("capacity", capacity), fmt::arg("power", power), fmt::arg("icon", getIcon(capacity, icons)), fmt::arg("time", time_remaining_formatted), fmt::arg("cycles", cycles), fmt::arg("health", fmt::format("{:.3}", health)))); } // Call parent update ALabel::update(); } void waybar::modules::Battery::setBarClass(std::string& state) { auto classes = bar_.window.get_style_context()->list_classes(); const std::string prefix = "battery-"; auto old_class_it = std::find_if(classes.begin(), classes.end(), [&prefix](auto classname) { return classname.rfind(prefix, 0) == 0; }); auto new_class = prefix + state; // If the bar doesn't have any `battery-` class if (old_class_it == classes.end()) { if (!state.empty()) { bar_.window.get_style_context()->add_class(new_class); } return; } auto old_class = *old_class_it; // If the bar has a `battery-` class, // but `state` is empty if (state.empty()) { bar_.window.get_style_context()->remove_class(old_class); return; } // If the bar has a `battery-` class, // and `state` is NOT empty if (old_class != new_class) { bar_.window.get_style_context()->remove_class(old_class); bar_.window.get_style_context()->add_class(new_class); } } waybar-0.12.0/src/modules/bluetooth.cpp000066400000000000000000000452241475603165300200500ustar00rootroot00000000000000#include "modules/bluetooth.hpp" #include #include #include #include #include "util/scope_guard.hpp" namespace { using GDBusManager = std::unique_ptr; auto generateManager() -> GDBusManager { GError* error = nullptr; waybar::util::ScopeGuard error_deleter([error]() { if (error) { g_error_free(error); } }); GDBusObjectManager* manager = g_dbus_object_manager_client_new_for_bus_sync( G_BUS_TYPE_SYSTEM, GDBusObjectManagerClientFlags::G_DBUS_OBJECT_MANAGER_CLIENT_FLAGS_DO_NOT_AUTO_START, "org.bluez", "/", NULL, NULL, NULL, NULL, &error); if (error) { spdlog::error("g_dbus_object_manager_client_new_for_bus_sync() failed: {}", error->message); } auto destructor = [](GDBusObjectManager* manager) { if (manager) { g_object_unref(manager); } }; return GDBusManager{manager, destructor}; } auto getBoolProperty(GDBusProxy* proxy, const char* property_name) -> bool { auto gvar = g_dbus_proxy_get_cached_property(proxy, property_name); if (gvar) { bool property_value = g_variant_get_boolean(gvar); g_variant_unref(gvar); return property_value; } spdlog::error("getBoolProperty() failed: doesn't have property {}", property_name); return false; } auto getOptionalStringProperty(GDBusProxy* proxy, const char* property_name) -> std::optional { auto gvar = g_dbus_proxy_get_cached_property(proxy, property_name); if (gvar) { std::string property_value = g_variant_get_string(gvar, NULL); g_variant_unref(gvar); return property_value; } return std::nullopt; } auto getStringProperty(GDBusProxy* proxy, const char* property_name) -> std::string { auto property_value = getOptionalStringProperty(proxy, property_name); if (!property_value.has_value()) { spdlog::error("getStringProperty() failed: doesn't have property {}", property_name); } return property_value.value_or(""); } auto getUcharProperty(GDBusProxy* proxy, const char* property_name) -> unsigned char { auto gvar = g_dbus_proxy_get_cached_property(proxy, property_name); if (gvar) { unsigned char property_value; g_variant_get(gvar, "y", &property_value); g_variant_unref(gvar); return property_value; } spdlog::error("getUcharProperty() failed: doesn't have property {}", property_name); return 0; } } // namespace waybar::modules::Bluetooth::Bluetooth(const std::string& id, const Json::Value& config) : ALabel(config, "bluetooth", id, " {status}", 10), #ifdef WANT_RFKILL rfkill_{RFKILL_TYPE_BLUETOOTH}, #endif manager_(generateManager()) { if (config_["format-device-preference"].isArray()) { std::transform(config_["format-device-preference"].begin(), config_["format-device-preference"].end(), std::back_inserter(device_preference_), [](auto x) { return x.asString(); }); } if (cur_controller_ = findCurController(); !cur_controller_) { if (config_["controller-alias"].isString()) { spdlog::warn("no bluetooth controller found with alias '{}'", config_["controller-alias"].asString()); } else { spdlog::warn("no bluetooth controller found"); } update(); } else { // This call only make sense if a controller could be found 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); #ifdef WANT_RFKILL rfkill_.on_update.connect(sigc::hide(sigc::mem_fun(*this, &Bluetooth::update))); #endif dp.emit(); } auto waybar::modules::Bluetooth::update() -> void { // focussed device is either: // - the first device in the device_preference_ list that is connected to the // current controller (if none fallback to last connected device) // - it is the last device that connected to the current controller if (!connected_devices_.empty()) { bool preferred_device_connected = false; if (!device_preference_.empty()) { for (const std::string& device_alias : device_preference_) { auto it = std::find_if(connected_devices_.begin(), connected_devices_.end(), [device_alias](auto device) { return device_alias == device.alias; }); if (it != connected_devices_.end()) { preferred_device_connected = true; cur_focussed_device_ = *it; break; } } } if (!preferred_device_connected) { cur_focussed_device_ = connected_devices_.back(); } } std::string state; std::string tooltip_format; if (cur_controller_) { if (!cur_controller_->powered) state = "off"; else if (!connected_devices_.empty()) state = "connected"; else state = "on"; } else { state = "no-controller"; } #ifdef WANT_RFKILL if (rfkill_.getState()) state = "disabled"; #endif bool battery_available = state == "connected" && cur_focussed_device_.battery_percentage.has_value(); #ifdef WANT_RFKILL // also adds enabled icon if icon for state is not defined std::vector states = {state, rfkill_.getState() ? "disabled" : "enabled"}; std::string icon = getIcon(0, states); #else std::string icon = getIcon(0, state); #endif std::string icon_label = icon; std::string icon_tooltip = icon; if (!alt_) { if (battery_available && config_["format-connected-battery"].isString()) { format_ = config_["format-connected-battery"].asString(); icon_label = getIcon(cur_focussed_device_.battery_percentage.value_or(0)); } else if (config_["format-" + state].isString()) { format_ = config_["format-" + state].asString(); } else if (config_["format"].isString()) { format_ = config_["format"].asString(); } else { format_ = default_format_; } } if (battery_available && config_["tooltip-format-connected-battery"].isString()) { tooltip_format = config_["tooltip-format-connected-battery"].asString(); icon_tooltip = getIcon(cur_focussed_device_.battery_percentage.value_or(0)); } else if (config_["tooltip-format-" + state].isString()) { tooltip_format = config_["tooltip-format-" + state].asString(); } else if (config_["tooltip-format"].isString()) { tooltip_format = config_["tooltip-format"].asString(); } auto update_style_context = [this](const std::string& style_class, bool in_next_state) { if (in_next_state && !label_.get_style_context()->has_class(style_class)) { label_.get_style_context()->add_class(style_class); } else if (!in_next_state && label_.get_style_context()->has_class(style_class)) { label_.get_style_context()->remove_class(style_class); } }; update_style_context("discoverable", cur_controller_ ? cur_controller_->discoverable : false); update_style_context("discovering", cur_controller_ ? cur_controller_->discovering : false); update_style_context("pairable", cur_controller_ ? cur_controller_->pairable : false); if (!state_.empty()) { update_style_context(state_, false); } update_style_context(state, true); state_ = state; if (format_.empty()) { event_box_.hide(); } else { event_box_.show(); label_.set_markup(fmt::format( fmt::runtime(format_), fmt::arg("status", state_), fmt::arg("num_connections", connected_devices_.size()), fmt::arg("controller_address", cur_controller_ ? cur_controller_->address : "null"), fmt::arg("controller_address_type", cur_controller_ ? cur_controller_->address_type : "null"), fmt::arg("controller_alias", cur_controller_ ? cur_controller_->alias : "null"), fmt::arg("device_address", cur_focussed_device_.address), fmt::arg("device_address_type", cur_focussed_device_.address_type), fmt::arg("device_alias", cur_focussed_device_.alias), fmt::arg("icon", icon_label), fmt::arg("device_battery_percentage", cur_focussed_device_.battery_percentage.value_or(0)))); } if (tooltipEnabled()) { bool tooltip_enumerate_connections_ = config_["tooltip-format-enumerate-connected"].isString(); bool tooltip_enumerate_connections_battery_ = config_["tooltip-format-enumerate-connected-battery"].isString(); if (tooltip_enumerate_connections_ || tooltip_enumerate_connections_battery_) { std::stringstream ss; for (DeviceInfo dev : connected_devices_) { if ((tooltip_enumerate_connections_battery_ && dev.battery_percentage.has_value()) || tooltip_enumerate_connections_) { ss << "\n"; std::string enumerate_format; std::string enumerate_icon; if (tooltip_enumerate_connections_battery_ && dev.battery_percentage.has_value()) { enumerate_format = config_["tooltip-format-enumerate-connected-battery"].asString(); enumerate_icon = getIcon(dev.battery_percentage.value_or(0)); } else { enumerate_format = config_["tooltip-format-enumerate-connected"].asString(); } ss << fmt::format( fmt::runtime(enumerate_format), fmt::arg("device_address", dev.address), fmt::arg("device_address_type", dev.address_type), fmt::arg("device_alias", dev.alias), fmt::arg("icon", enumerate_icon), fmt::arg("device_battery_percentage", dev.battery_percentage.value_or(0))); } } device_enumerate_ = ss.str(); // don't start the connected devices text with a new line if (!device_enumerate_.empty()) { device_enumerate_.erase(0, 1); } } label_.set_tooltip_text(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"), fmt::arg("controller_address_type", cur_controller_ ? cur_controller_->address_type : "null"), fmt::arg("controller_alias", cur_controller_ ? cur_controller_->alias : "null"), fmt::arg("device_address", cur_focussed_device_.address), fmt::arg("device_address_type", cur_focussed_device_.address_type), fmt::arg("device_alias", cur_focussed_device_.alias), fmt::arg("icon", icon_tooltip), fmt::arg("device_battery_percentage", cur_focussed_device_.battery_percentage.value_or(0)), fmt::arg("device_enumerate", device_enumerate_))); } // Call parent update ALabel::update(); } auto waybar::modules::Bluetooth::onObjectAdded(GDBusObjectManager* manager, GDBusObject* object, gpointer user_data) -> void { ControllerInfo info; Bluetooth* bt = static_cast(user_data); if (!bt->cur_controller_.has_value() && bt->getControllerProperties(object, info) && (!bt->config_["controller-alias"].isString() || bt->config_["controller-alias"].asString() == info.alias)) { bt->cur_controller_ = std::move(info); bt->dp.emit(); } } auto waybar::modules::Bluetooth::onObjectRemoved(GDBusObjectManager* manager, GDBusObject* object, gpointer user_data) -> void { Bluetooth* bt = static_cast(user_data); GDBusProxy* proxy_controller; if (!bt->cur_controller_.has_value()) { return; } proxy_controller = G_DBUS_PROXY(g_dbus_object_get_interface(object, "org.bluez.Adapter1")); if (proxy_controller != NULL) { std::string object_path = g_dbus_object_get_object_path(object); if (object_path == bt->cur_controller_->path) { bt->cur_controller_ = bt->findCurController(); if (bt->cur_controller_.has_value()) { bt->connected_devices_.clear(); bt->findConnectedDevices(bt->cur_controller_->path, bt->connected_devices_); } bt->dp.emit(); } g_object_unref(proxy_controller); } } // NOTE: only for when the org.bluez.Battery1 interface is added/removed after/before a device is // connected/disconnected auto waybar::modules::Bluetooth::onInterfaceAddedOrRemoved(GDBusObjectManager* manager, GDBusObject* object, GDBusInterface* interface, gpointer user_data) -> void { std::string interface_name = g_dbus_proxy_get_interface_name(G_DBUS_PROXY(interface)); std::string object_path = g_dbus_proxy_get_object_path(G_DBUS_PROXY(interface)); if (interface_name == "org.bluez.Battery1") { Bluetooth* bt = static_cast(user_data); if (bt->cur_controller_.has_value()) { auto device = std::find_if(bt->connected_devices_.begin(), bt->connected_devices_.end(), [object_path](auto d) { return d.path == object_path; }); if (device != bt->connected_devices_.end()) { device->battery_percentage = bt->getDeviceBatteryPercentage(object); bt->dp.emit(); } } } } auto waybar::modules::Bluetooth::onInterfaceProxyPropertiesChanged( GDBusObjectManagerClient* manager, GDBusObjectProxy* object_proxy, GDBusProxy* interface_proxy, GVariant* changed_properties, const gchar* const* invalidated_properties, gpointer user_data) -> void { std::string interface_name = g_dbus_proxy_get_interface_name(interface_proxy); std::string object_path = g_dbus_object_get_object_path(G_DBUS_OBJECT(object_proxy)); Bluetooth* bt = static_cast(user_data); if (!bt->cur_controller_.has_value()) { return; } if (interface_name == "org.bluez.Adapter1") { if (object_path == bt->cur_controller_->path) { bt->getControllerProperties(G_DBUS_OBJECT(object_proxy), *bt->cur_controller_); bt->dp.emit(); } } else if (interface_name == "org.bluez.Device1" || interface_name == "org.bluez.Battery1") { DeviceInfo device; bt->getDeviceProperties(G_DBUS_OBJECT(object_proxy), device); auto cur_device = std::find_if(bt->connected_devices_.begin(), bt->connected_devices_.end(), [device](auto d) { return d.path == device.path; }); if (cur_device == bt->connected_devices_.end()) { if (device.connected) { bt->connected_devices_.push_back(device); bt->dp.emit(); } } else { if (!device.connected) { bt->connected_devices_.erase(cur_device); } else { *cur_device = device; } bt->dp.emit(); } } } auto waybar::modules::Bluetooth::getDeviceBatteryPercentage(GDBusObject* object) -> std::optional { GDBusProxy* proxy_device_bat = G_DBUS_PROXY(g_dbus_object_get_interface(object, "org.bluez.Battery1")); if (proxy_device_bat != NULL) { unsigned char battery_percentage = getUcharProperty(proxy_device_bat, "Percentage"); g_object_unref(proxy_device_bat); return battery_percentage; } return std::nullopt; } auto waybar::modules::Bluetooth::getDeviceProperties(GDBusObject* object, DeviceInfo& device_info) -> bool { GDBusProxy* proxy_device = G_DBUS_PROXY(g_dbus_object_get_interface(object, "org.bluez.Device1")); if (proxy_device != NULL) { device_info.path = g_dbus_object_get_object_path(object); device_info.paired_controller = getStringProperty(proxy_device, "Adapter"); device_info.address = getStringProperty(proxy_device, "Address"); device_info.address_type = getStringProperty(proxy_device, "AddressType"); device_info.alias = getStringProperty(proxy_device, "Alias"); device_info.icon = getOptionalStringProperty(proxy_device, "Icon"); device_info.paired = getBoolProperty(proxy_device, "Paired"); device_info.trusted = getBoolProperty(proxy_device, "Trusted"); device_info.blocked = getBoolProperty(proxy_device, "Blocked"); device_info.connected = getBoolProperty(proxy_device, "Connected"); device_info.services_resolved = getBoolProperty(proxy_device, "ServicesResolved"); g_object_unref(proxy_device); device_info.battery_percentage = getDeviceBatteryPercentage(object); return true; } return false; } auto waybar::modules::Bluetooth::getControllerProperties(GDBusObject* object, ControllerInfo& controller_info) -> bool { GDBusProxy* proxy_controller = G_DBUS_PROXY(g_dbus_object_get_interface(object, "org.bluez.Adapter1")); if (proxy_controller != NULL) { controller_info.path = g_dbus_object_get_object_path(object); controller_info.address = getStringProperty(proxy_controller, "Address"); controller_info.address_type = getStringProperty(proxy_controller, "AddressType"); controller_info.alias = getStringProperty(proxy_controller, "Alias"); controller_info.powered = getBoolProperty(proxy_controller, "Powered"); controller_info.discoverable = getBoolProperty(proxy_controller, "Discoverable"); controller_info.pairable = getBoolProperty(proxy_controller, "Pairable"); controller_info.discovering = getBoolProperty(proxy_controller, "Discovering"); g_object_unref(proxy_controller); return true; } return false; } auto waybar::modules::Bluetooth::findCurController() -> std::optional { std::optional 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); ControllerInfo info; if (getControllerProperties(object, info) && (!config_["controller-alias"].isString() || config_["controller-alias"].asString() == info.alias)) { controller_info = std::move(info); break; } } g_list_free_full(objects, g_object_unref); return controller_info; } auto waybar::modules::Bluetooth::findConnectedDevices(const std::string& cur_controller_path, std::vector& connected_devices) -> void { 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); DeviceInfo device; if (getDeviceProperties(object, device) && device.connected && device.paired_controller == cur_controller_->path) { connected_devices.push_back(device); } } g_list_free_full(objects, g_object_unref); } waybar-0.12.0/src/modules/cava.cpp000066400000000000000000000166641475603165300167630ustar00rootroot00000000000000#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); } waybar-0.12.0/src/modules/cffi.cpp000066400000000000000000000072561475603165300167550ustar00rootroot00000000000000#include "modules/cffi.hpp" #include #include #include #include #include namespace waybar::modules { CFFI::CFFI(const std::string& name, const std::string& id, const Json::Value& config) : AModule(config, name, id, true, true) { const auto dynlib_path = config_["module_path"].asString(); if (dynlib_path.empty()) { throw std::runtime_error{"Missing or empty 'module_path' in module config"}; } void* handle = dlopen(dynlib_path.c_str(), RTLD_LAZY); if (handle == nullptr) { throw std::runtime_error{std::string{"Failed to load CFFI module: "} + dlerror()}; } // Fetch ABI version auto wbcffi_version = reinterpret_cast(dlsym(handle, "wbcffi_version")); if (wbcffi_version == nullptr) { throw std::runtime_error{std::string{"Missing wbcffi_version function: "} + dlerror()}; } // Fetch functions if (*wbcffi_version == 1) { // Mandatory functions hooks_.init = reinterpret_cast(dlsym(handle, "wbcffi_init")); if (!hooks_.init) { throw std::runtime_error{std::string{"Missing wbcffi_init function: "} + dlerror()}; } hooks_.deinit = reinterpret_cast(dlsym(handle, "wbcffi_deinit")); if (!hooks_.init) { throw std::runtime_error{std::string{"Missing wbcffi_deinit function: "} + dlerror()}; } // Optional functions if (auto fn = reinterpret_cast(dlsym(handle, "wbcffi_update"))) { hooks_.update = fn; } if (auto fn = reinterpret_cast(dlsym(handle, "wbcffi_refresh"))) { hooks_.refresh = fn; } if (auto fn = reinterpret_cast(dlsym(handle, "wbcffi_doaction"))) { hooks_.doAction = fn; } } else { throw std::runtime_error{"Unknown wbcffi_version " + std::to_string(*wbcffi_version)}; } // Prepare init() arguments // Convert JSON values to string std::vector config_entries_stringstor; const auto& keys = config.getMemberNames(); for (size_t i = 0; i < keys.size(); i++) { const auto& value = config[keys[i]]; if (value.isConvertibleTo(Json::ValueType::stringValue)) { config_entries_stringstor.push_back(config[keys[i]].asString()); } else { config_entries_stringstor.push_back(config[keys[i]].toStyledString()); } } // Prepare config_entries array std::vector config_entries; for (size_t i = 0; i < keys.size(); i++) { config_entries.push_back({keys[i].c_str(), config_entries_stringstor[i].c_str()}); } ffi::wbcffi_init_info init_info = { .obj = (ffi::wbcffi_module*)this, .waybar_version = VERSION, .get_root_widget = [](ffi::wbcffi_module* obj) { return dynamic_cast(&((CFFI*)obj)->event_box_)->gobj(); }, .queue_update = [](ffi::wbcffi_module* obj) { ((CFFI*)obj)->dp.emit(); }, }; // Call init cffi_instance_ = hooks_.init(&init_info, config_entries.data(), config_entries.size()); // Handle init failures if (cffi_instance_ == nullptr) { throw std::runtime_error{"Failed to initialize C ABI module"}; } } CFFI::~CFFI() { if (cffi_instance_ != nullptr) { hooks_.deinit(cffi_instance_); } } auto CFFI::update() -> void { assert(cffi_instance_ != nullptr); hooks_.update(cffi_instance_); // Execute the on-update command set in config AModule::update(); } auto CFFI::refresh(int signal) -> void { assert(cffi_instance_ != nullptr); hooks_.refresh(cffi_instance_, signal); } auto CFFI::doAction(const std::string& name) -> void { assert(cffi_instance_ != nullptr); if (!name.empty()) { hooks_.doAction(cffi_instance_, name.c_str()); } } } // namespace waybar::modules waybar-0.12.0/src/modules/clock.cpp000066400000000000000000000431351475603165300171350ustar00rootroot00000000000000#include "modules/clock.hpp" #include #include #include #include #include #include #include "util/ustring_clen.hpp" #ifdef HAVE_LANGINFO_1STDAY #include #include #endif namespace fmt_lib = waybar::util::date::format; waybar::modules::Clock::Clock(const std::string& id, const Json::Value& config) : ALabel(config, "clock", id, "{:%H:%M}", 60, false, false, true), m_locale_{std::locale(config_["locale"].isString() ? config_["locale"].asString() : "")}, m_tlpFmt_{(config_["tooltip-format"].isString()) ? config_["tooltip-format"].asString() : ""}, m_tooltip_{new Gtk::Label()}, cldInTooltip_{m_tlpFmt_.find("{" + kCldPlaceholder + "}") != std::string::npos}, cldYearShift_{January / 1 / 1900}, tzInTooltip_{m_tlpFmt_.find("{" + kTZPlaceholder + "}") != std::string::npos}, tzCurrIdx_{0}, ordInTooltip_{m_tlpFmt_.find("{" + kOrdPlaceholder + "}") != std::string::npos} { m_tlpText_ = m_tlpFmt_; if (config_["timezones"].isArray() && !config_["timezones"].empty()) { for (const auto& zone_name : config_["timezones"]) { if (!zone_name.isString()) continue; if (zone_name.asString().empty()) // local time should be shown tzList_.push_back(nullptr); else try { tzList_.push_back(locate_zone(zone_name.asString())); } catch (const std::exception& e) { spdlog::warn("Timezone: {0}. {1}", zone_name.asString(), e.what()); } } } else if (config_["timezone"].isString()) { if (config_["timezone"].asString().empty()) // local time should be shown tzList_.push_back(nullptr); else try { tzList_.push_back(locate_zone(config_["timezone"].asString())); } catch (const std::exception& e) { spdlog::warn("Timezone: {0}. {1}", config_["timezone"].asString(), e.what()); } } if (!tzList_.size()) tzList_.push_back(nullptr); // Calendar properties 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}}; if (monthModes.find(cfgMode) != monthModes.end()) cldMode_ = monthModes.at(cfgMode); else spdlog::warn( "Clock calendar configuration mode \"{0}\" is not recognized. Mode = \"month\" is " "using instead", cfgMode); } 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; } if (config_[kCldPlaceholder]["format"]["months"].isString()) fmtMap_.insert({0, config_[kCldPlaceholder]["format"]["months"].asString()}); else fmtMap_.insert({0, "{}"}); if (config_[kCldPlaceholder]["format"]["weekdays"].isString()) fmtMap_.insert({1, config_[kCldPlaceholder]["format"]["weekdays"].asString()}); else fmtMap_.insert({1, "{}"}); if (config_[kCldPlaceholder]["format"]["days"].isString()) fmtMap_.insert({2, config_[kCldPlaceholder]["format"]["days"].asString()}); else 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(); } else fmtMap_.insert({3, "{}"}); if (config_[kCldPlaceholder]["format"]["weeks"].isString() && cldWPos_ != WS::HIDDEN) { fmtMap_.insert({4, std::regex_replace(config_[kCldPlaceholder]["format"]["weeks"].asString(), std::regex("\\{\\}"), (first_day_of_week() == Monday) ? "{:%W}" : "{:%U}")}); 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 cldWnLen_ = 0; } if (config_[kCldPlaceholder]["mode-mon-col"].isInt()) { cldMonCols_ = config_[kCldPlaceholder]["mode-mon-col"].asInt(); if (cldMonCols_ == 0u || (12 % cldMonCols_) != 0u) { spdlog::warn( "Clock calendar configuration mode-mon-col = {0} must be one of [1, 2, 3, 4, 6, 12]. " "Value 3 is using instead", cldMonCols_); cldMonCols_ = 3u; } } else cldMonCols_ = 1; if (config_[kCldPlaceholder]["on-scroll"].isInt()) { cldShift_ = config_[kCldPlaceholder]["on-scroll"].asInt(); event_box_.add_events(Gdk::LEAVE_NOTIFY_MASK); event_box_.signal_leave_notify_event().connect([this](GdkEventCrossing*) { cldCurrShift_ = months{0}; return false; }); } } if (tooltipEnabled()) { label_.set_has_tooltip(true); label_.signal_query_tooltip().connect(sigc::mem_fun(*this, &Clock::query_tlp_cb)); } thread_ = [this] { dp.emit(); thread_.sleep_for(interval_ - system_clock::now().time_since_epoch() % interval_); }; } bool waybar::modules::Clock::query_tlp_cb(int, int, bool, const Glib::RefPtr& tooltip) { tooltip->set_custom(*m_tooltip_.get()); return true; } auto waybar::modules::Clock::update() -> void { const auto* tz = tzList_[tzCurrIdx_] != nullptr ? tzList_[tzCurrIdx_] : local_zone(); const zoned_time now{tz, floor(system_clock::now())}; label_.set_markup(fmt_lib::vformat(m_locale_, format_, fmt_lib::make_format_args(now))); if (tooltipEnabled()) { const year_month_day today{floor(now.get_local_time())}; const auto shiftedDay{today + cldCurrShift_}; const zoned_time shiftedNow{ tz, local_days(shiftedDay) + (now.get_local_time() - floor(now.get_local_time()))}; if (tzInTooltip_) tzText_ = getTZtext(now.get_sys_time()); if (cldInTooltip_) cldText_ = get_calendar(today, shiftedDay, tz); if (ordInTooltip_) ordText_ = get_ordinal_date(shiftedDay); if (tzInTooltip_ || cldInTooltip_ || ordInTooltip_) { // std::vformat doesn't support named arguments. m_tlpText_ = std::regex_replace(m_tlpFmt_, std::regex("\\{" + kTZPlaceholder + "\\}"), tzText_); m_tlpText_ = std::regex_replace( m_tlpText_, std::regex("\\{" + kCldPlaceholder + "\\}"), fmt_lib::vformat(m_locale_, cldText_, fmt_lib::make_format_args(shiftedNow))); m_tlpText_ = std::regex_replace(m_tlpText_, std::regex("\\{" + kOrdPlaceholder + "\\}"), ordText_); } else { m_tlpText_ = m_tlpFmt_; } m_tlpText_ = fmt_lib::vformat(m_locale_, m_tlpText_, fmt_lib::make_format_args(now)); m_tooltip_->set_markup(m_tlpText_); label_.trigger_tooltip_query(); } ALabel::update(); } auto waybar::modules::Clock::getTZtext(sys_seconds now) -> std::string { if (tzList_.size() == 1) return ""; std::stringstream os; 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(); auto zt{zoned_time{tz, now}}; os << fmt_lib::vformat(m_locale_, format_, fmt_lib::make_format_args(zt)) << '\n'; } return os.str(); } const unsigned cldRowsInMonth(const year_month& ym, const weekday& firstdow) { return 2u + ceil((weekday{ym / 1} - firstdow) + ((ym / last).day() - day{0})).count(); } 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]; } auto getCalendarLine(const year_month_day& currDate, const year_month ym, const unsigned line, const weekday& firstdow, const std::locale* const m_locale_) -> std::string { std::ostringstream os; switch (line) { // Print month and year title case 0: { os << date::format(*m_locale_, "{:L%B %Y}", ym); break; } // Print weekday names title case 1: { auto wd{firstdow}; Glib::ustring wdStr; Glib::ustring::size_type wdLen{0}; int clen{0}; do { wdStr = date::format(*m_locale_, "{:L%a}", wd); clen = ustring_clen(wdStr); wdLen = wdStr.length(); while (clen > 2) { wdStr = wdStr.substr(0, wdLen - 1); --wdLen; clen = ustring_clen(wdStr); } const std::string pad(2 - clen, ' '); if (wd != firstdow) os << ' '; os << pad << wdStr; } while (++wd != firstdow); break; } // Print first week prefixed with spaces if necessary case 2: { auto d{day{1}}; auto wd{weekday{ym / 1}}; os << std::string((wd - firstdow).count() * 3, ' '); if (currDate != ym / d) os << date::format(*m_locale_, "{:L%e}", d); else os << "{today}"; while (++wd != firstdow) { ++d; if (currDate != ym / d) os << date::format(*m_locale_, " {:L%e}", d); else os << " {today}"; } break; } // Print non-first week default: { auto ymdTmp{cldGetWeekForLine(ym, firstdow, line)}; if (ymdTmp.ok()) { auto d{year_month_day{ymdTmp}.day()}; const auto dlast{(ym / last).day()}; auto wd{firstdow}; if (currDate != ym / d) os << date::format(*m_locale_, "{:L%e}", d); else os << "{today}"; while (++wd != firstdow && ++d <= dlast) { if (currDate != ym / d) os << date::format(*m_locale_, " {:L%e}", d); else os << " {today}"; } // Append row with spaces if the week was not completed os << std::string((firstdow - wd).count() * 3, ' '); } break; } } return os.str(); } auto waybar::modules::Clock::get_calendar(const year_month_day& today, const year_month_day& ymd, const time_zone* tz) -> const std::string { const auto firstdow{first_day_of_week()}; const auto maxRows{12 / cldMonCols_}; const auto ym{ymd.year() / ymd.month()}; const auto y{ymd.year()}; const auto d{ymd.day()}; std::ostringstream os; std::ostringstream tmp; if (cldMode_ == CldMode::YEAR) { if (y / month{1} / 1 == cldYearShift_) if (d == cldBaseDay_ || (uint)cldBaseDay_ == 0u) return cldYearCached_; else cldBaseDay_ = d; else cldYearShift_ = y / month{1} / 1; } if (cldMode_ == CldMode::MONTH) { if (ym == cldMonShift_) if (d == cldBaseDay_ || (uint)cldBaseDay_ == 0u) return cldMonCached_; else cldBaseDay_ = d; else cldMonShift_ = ym; } // Pad object const std::string pads(cldWnLen_, ' '); // Compute number of lines needed for each calendar month unsigned ml[12]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; for (auto& m : ml) { if (cldMode_ == CldMode::YEAR || m == static_cast(ymd.month())) m = cldRowsInMonth(y / month{m}, firstdow); else m = 0u; } for (auto row{0u}; row < maxRows; ++row) { const auto lines{*std::max_element(std::begin(ml) + (row * cldMonCols_), std::begin(ml) + ((row + 1) * cldMonCols_))}; for (auto line{0u}; line < lines; ++line) { for (auto col{0u}; col < cldMonCols_; ++col) { const auto mon{month{row * cldMonCols_ + col + 1}}; if (cldMode_ == CldMode::YEAR || y / mon == ym) { const year_month ymTmp{y / mon}; if (col != 0 && cldMode_ == CldMode::YEAR) os << std::string(3, ' '); // Week numbers on the left if (cldWPos_ == WS::LEFT && line > 0) { if (line > 1) { if (line < ml[(unsigned)ymTmp.month() - 1u]) { os << fmt_lib::vformat( m_locale_, fmtMap_[4], fmt_lib::make_format_args( (line == 2) ? static_cast( zoned_seconds{tz, local_days{ymTmp / 1}}) : static_cast(zoned_seconds{ tz, local_days{cldGetWeekForLine(ymTmp, firstdow, line)}}))) << ' '; } 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_)); // Week numbers on the right if (cldWPos_ == WS::RIGHT && line > 0) { if (line > 1) { if (line < ml[(unsigned)ymTmp.month() - 1u]) os << ' ' << fmt_lib::vformat( m_locale_, fmtMap_[4], fmt_lib::make_format_args( (line == 2) ? static_cast( zoned_seconds{tz, local_days{ymTmp / 1}}) : static_cast( zoned_seconds{tz, local_days{cldGetWeekForLine( ymTmp, firstdow, line)}}))); else os << pads; } } } } // Apply user's formats if (line < 2) tmp << fmt_lib::vformat( m_locale_, fmtMap_[line], fmt_lib::make_format_args(static_cast(os.str()))); else tmp << os.str(); // Clear ostringstream std::ostringstream().swap(os); if (line + 1u != lines || (row + 1u != maxRows && cldMode_ == CldMode::YEAR)) tmp << '\n'; } if (row + 1u != maxRows && cldMode_ == CldMode::YEAR) tmp << '\n'; } os << std::regex_replace( fmt_lib::vformat(m_locale_, fmtMap_[2], fmt_lib::make_format_args(static_cast(tmp.str()))), std::regex("\\{today\\}"), fmt_lib::vformat(m_locale_, fmtMap_[3], fmt_lib::make_format_args( static_cast(date::format("{:L%e}", d))))); if (cldMode_ == CldMode::YEAR) cldYearCached_ = os.str(); else cldMonCached_ = os.str(); return os.str(); } auto waybar::modules::Clock::local_zone() -> const time_zone* { const char* tz_name = getenv("TZ"); if (tz_name) { try { return locate_zone(tz_name); } catch (const std::runtime_error& e) { spdlog::warn("Timezone: {0}. {1}", tz_name, e.what()); } } return current_zone(); } // Actions handler auto waybar::modules::Clock::doAction(const std::string& name) -> void { if (actionMap_[name]) { (this->*actionMap_[name])(); } else spdlog::error("Clock. Unsupported action \"{0}\"", name); } // Module actions void waybar::modules::Clock::cldModeSwitch() { cldMode_ = (cldMode_ == CldMode::YEAR) ? CldMode::MONTH : CldMode::YEAR; } void waybar::modules::Clock::cldShift_up() { cldCurrShift_ += (months)((cldMode_ == CldMode::YEAR) ? 12 : 1) * cldShift_; } void waybar::modules::Clock::cldShift_down() { cldCurrShift_ -= (months)((cldMode_ == CldMode::YEAR) ? 12 : 1) * cldShift_; } void waybar::modules::Clock::cldShift_reset() { cldCurrShift_ = (months)0; } void waybar::modules::Clock::tz_up() { const auto tzSize{tzList_.size()}; if (tzSize == 1) return; size_t newIdx{tzCurrIdx_ + 1lu}; tzCurrIdx_ = (newIdx == tzSize) ? 0 : newIdx; } void waybar::modules::Clock::tz_down() { const auto tzSize{tzList_.size()}; if (tzSize == 1) return; tzCurrIdx_ = (tzCurrIdx_ == 0) ? tzSize - 1 : tzCurrIdx_ - 1; } #ifdef HAVE_LANGINFO_1STDAY template using deleter_from_fn = std::integral_constant; template using deleting_unique_ptr = std::unique_ptr>; #endif // Computations done similarly to Linux cal utility. auto waybar::modules::Clock::first_day_of_week() -> weekday { #ifdef HAVE_LANGINFO_1STDAY deleting_unique_ptr::type, freelocale> posix_locale{ newlocale(LC_ALL, m_locale_.name().c_str(), nullptr)}; if (posix_locale) { const auto i{(int)((std::intptr_t)nl_langinfo_l(_NL_TIME_WEEK_1STDAY, posix_locale.get()))}; const weekday wd{year_month_day{year(i / 10000) / month(i / 100 % 100) / day(i % 100)}}; const auto j{(uint8_t)*nl_langinfo_l(_NL_TIME_FIRST_WEEKDAY, posix_locale.get())}; return wd + days{j - 1}; } #endif return Sunday; } auto waybar::modules::Clock::get_ordinal_date(const year_month_day& today) -> std::string { auto day = static_cast(today.day()); std::stringstream res; res << day; if (day >= 11 && day <= 13) { res << "th"; return res.str(); } switch (day % 10) { case 1: res << "st"; break; case 2: res << "nd"; break; case 3: res << "rd"; break; default: res << "th"; } return res.str(); } waybar-0.12.0/src/modules/cpu.cpp000066400000000000000000000042641475603165300166310ustar00rootroot00000000000000#include "modules/cpu.hpp" #include "modules/cpu_frequency.hpp" #include "modules/cpu_usage.hpp" #include "modules/load.hpp" // 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 waybar::modules::Cpu::Cpu(const std::string& id, const Json::Value& config) : ALabel(config, "cpu", id, "{usage}%", 10) { thread_ = [this] { dp.emit(); thread_.sleep_for(interval_); }; } auto waybar::modules::Cpu::update() -> void { // TODO: as creating dynamic fmt::arg arrays is buggy we have to calc both 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); if (!state.empty() && config_["format-" + state].isString()) { format = config_["format-" + state].asString(); } if (format.empty()) { event_box_.hide(); } else { event_box_.show(); auto icons = std::vector{state}; fmt::dynamic_format_arg_store store; store.push_back(fmt::arg("load", load1)); 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)); 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))); } label_.set_markup(fmt::vformat(format, store)); } // Call parent update ALabel::update(); } waybar-0.12.0/src/modules/cpu_frequency/000077500000000000000000000000001475603165300202005ustar00rootroot00000000000000waybar-0.12.0/src/modules/cpu_frequency/bsd.cpp000066400000000000000000000011761475603165300214610ustar00rootroot00000000000000#include #include #include "modules/cpu_frequency.hpp" std::vector waybar::modules::CpuFrequency::parseCpuFrequencies() { std::vector frequencies; char buffer[256]; size_t len; int32_t freq; uint32_t i = 0; while (true) { len = 4; snprintf(buffer, 256, "dev.cpu.%u.freq", i); if (sysctlbyname(buffer, &freq, &len, NULL, 0) == -1 || len <= 0) break; frequencies.push_back(freq); ++i; } if (frequencies.empty()) { spdlog::warn("cpu/bsd: parseCpuFrequencies failed, not found in sysctl"); frequencies.push_back(NAN); } return frequencies; } waybar-0.12.0/src/modules/cpu_frequency/common.cpp000066400000000000000000000046401475603165300222000ustar00rootroot00000000000000#include "modules/cpu_frequency.hpp" // 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 waybar::modules::CpuFrequency::CpuFrequency(const std::string& id, const Json::Value& config) : ALabel(config, "cpu_frequency", id, "{avg_frequency}", 10) { thread_ = [this] { dp.emit(); thread_.sleep_for(interval_); }; } 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()) { format = config_["format-" + state].asString(); } if (format.empty()) { event_box_.hide(); } else { event_box_.show(); auto icons = std::vector{state}; fmt::dynamic_format_arg_store store; store.push_back(fmt::arg("icon", getIcon(avg_frequency, 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)); label_.set_markup(fmt::vformat(format, store)); } // Call parent update ALabel::update(); } std::tuple waybar::modules::CpuFrequency::getCpuFrequency() { std::vector frequencies = CpuFrequency::parseCpuFrequencies(); if (frequencies.empty()) { return {0.f, 0.f, 0.f}; } auto [min, max] = std::minmax_element(std::begin(frequencies), std::end(frequencies)); float avg_frequency = std::accumulate(std::begin(frequencies), std::end(frequencies), 0.0) / frequencies.size(); // Round frequencies with double decimal precision to get GHz float max_frequency = std::ceil(*max / 10.0) / 100.0; float min_frequency = std::ceil(*min / 10.0) / 100.0; avg_frequency = std::ceil(avg_frequency / 10.0) / 100.0; return {max_frequency, min_frequency, avg_frequency}; } waybar-0.12.0/src/modules/cpu_frequency/linux.cpp000066400000000000000000000030161475603165300220430ustar00rootroot00000000000000#include #include "modules/cpu_frequency.hpp" std::vector waybar::modules::CpuFrequency::parseCpuFrequencies() { const std::string file_path_ = "/proc/cpuinfo"; std::ifstream info(file_path_); if (!info.is_open()) { throw std::runtime_error("Can't open " + file_path_); } std::vector frequencies; std::string line; while (getline(info, line)) { if (line.substr(0, 7).compare("cpu MHz") != 0) { continue; } std::string frequency_str = line.substr(line.find(":") + 2); float frequency = std::strtol(frequency_str.c_str(), nullptr, 10); frequencies.push_back(frequency); } info.close(); if (frequencies.size() <= 0) { std::string cpufreq_dir = "/sys/devices/system/cpu/cpufreq"; if (std::filesystem::exists(cpufreq_dir)) { std::vector frequency_files = {"/cpuinfo_min_freq", "/cpuinfo_max_freq"}; for (auto& p : std::filesystem::directory_iterator(cpufreq_dir)) { for (auto freq_file : frequency_files) { std::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(); } } } } } } return frequencies; } waybar-0.12.0/src/modules/cpu_usage/000077500000000000000000000000001475603165300173035ustar00rootroot00000000000000waybar-0.12.0/src/modules/cpu_usage/bsd.cpp000066400000000000000000000056621475603165300205700ustar00rootroot00000000000000#include // clang-format off #include #include // clang-format on #include // sysconf #include // NAN #include // malloc #include "modules/cpu_usage.hpp" #include "util/scope_guard.hpp" #if defined(__NetBSD__) || defined(__OpenBSD__) #include #else #include #endif #if defined(__NetBSD__) typedef uint64_t cp_time_t; #else typedef long cp_time_t; #endif #if defined(__NetBSD__) || defined(__OpenBSD__) typedef uint64_t pcp_time_t; #else typedef long pcp_time_t; #endif std::vector> waybar::modules::CpuUsage::parseCpuinfo() { cp_time_t sum_cp_time[CPUSTATES]; 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; waybar::util::ScopeGuard cp_time_deleter([cp_time]() { if (cp_time) { free(cp_time); } }); #if defined(__NetBSD__) int mib[] = { CTL_KERN, KERN_CP_TIME, }; if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), sum_cp_time, &sum_sz, NULL, 0)) { throw std::runtime_error("sysctl kern.cp_time failed"); } for (int state = 0; state < CPUSTATES; state++) { cp_time[state] = sum_cp_time[state]; } pcp_time += CPUSTATES; if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), pcp_time, &sz, NULL, 0)) { throw std::runtime_error("sysctl kern.cp_time failed"); } #elif defined(__OpenBSD__) { int mib[] = { CTL_KERN, KERN_CPTIME, }; if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), sum_cp_time, &sum_sz, NULL, 0)) { throw std::runtime_error("sysctl kern.cp_time failed"); } } for (int state = 0; state < CPUSTATES; state++) { cp_time[state] = sum_cp_time[state]; } pcp_time = cp_time; sz /= ncpu + 1; { int mib[] = { CTL_KERN, KERN_CPTIME2, 0, }; for (int cpu = 0; cpu < ncpu; cpu++) { mib[2] = cpu; pcp_time += CPUSTATES; if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), pcp_time, &sz, NULL, 0)) { throw std::runtime_error("sysctl kern.cp_time2 failed"); } } } #else if (sysctlbyname("kern.cp_time", sum_cp_time, &sum_sz, NULL, 0)) { throw std::runtime_error("sysctl kern.cp_time failed"); } for (int state = 0; state < CPUSTATES; state++) { cp_time[state] = sum_cp_time[state]; } pcp_time += CPUSTATES; if (sysctlbyname("kern.cp_times", pcp_time, &sz, NULL, 0)) { throw std::runtime_error("sysctl kern.cp_times failed"); } #endif std::vector> cpuinfo; for (int cpu = 0; cpu < ncpu + 1; cpu++) { pcp_time_t total = 0, *single_cp_time = &cp_time[cpu * CPUSTATES]; for (int state = 0; state < CPUSTATES; state++) { total += single_cp_time[state]; } cpuinfo.emplace_back(single_cp_time[CP_IDLE], total); } return cpuinfo; } waybar-0.12.0/src/modules/cpu_usage/common.cpp000066400000000000000000000072171475603165300213060ustar00rootroot00000000000000#include "modules/cpu_usage.hpp" // 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 waybar::modules::CpuUsage::CpuUsage(const std::string& id, const Json::Value& config) : ALabel(config, "cpu_usage", id, "{usage}%", 10) { thread_ = [this] { dp.emit(); thread_.sleep_for(interval_); }; } 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); if (!state.empty() && config_["format-" + state].isString()) { format = config_["format-" + state].asString(); } if (format.empty()) { event_box_.hide(); } else { event_box_.show(); auto icons = std::vector{state}; fmt::dynamic_format_arg_store store; store.push_back(fmt::arg("usage", total_usage)); store.push_back(fmt::arg("icon", getIcon(total_usage, icons))); 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))); } label_.set_markup(fmt::vformat(format, store)); } // Call parent update ALabel::update(); } std::tuple, std::string> waybar::modules::CpuUsage::getCpuUsage( std::vector>& prev_times) { if (prev_times.empty()) { prev_times = CpuUsage::parseCpuinfo(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } std::vector> curr_times = CpuUsage::parseCpuinfo(); std::string tooltip; std::vector usage; if (curr_times.size() != prev_times.size()) { // The number of CPUs has changed, eg. due to CPU hotplug // We don't know which CPU came up or went down // so only give total usage (if we can) if (!curr_times.empty() && !prev_times.empty()) { auto [curr_idle, curr_total] = curr_times[0]; 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); tooltip = fmt::format("Total: {}%\nCores: (pending)", tmp); usage.push_back(tmp); } else { tooltip = "(pending)"; usage.push_back(0); } prev_times = curr_times; return {usage, tooltip}; } for (size_t i = 0; i < curr_times.size(); ++i) { auto [curr_idle, curr_total] = curr_times[i]; auto [prev_idle, prev_total] = prev_times[i]; if (i > 0 && (curr_total == 0 || prev_total == 0)) { // This CPU is offline tooltip = tooltip + fmt::format("\nCore{}: offline", i - 1); usage.push_back(0); continue; } 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); if (i == 0) { tooltip = fmt::format("Total: {}%", tmp); } else { tooltip = tooltip + fmt::format("\nCore{}: {}%", i - 1, tmp); } usage.push_back(tmp); } prev_times = curr_times; return {usage, tooltip}; } waybar-0.12.0/src/modules/cpu_usage/linux.cpp000066400000000000000000000044451475603165300211550ustar00rootroot00000000000000#include #include "modules/cpu_usage.hpp" std::vector> waybar::modules::CpuUsage::parseCpuinfo() { // Get the "existing CPU count" from /sys/devices/system/cpu/present // Probably this is what the user wants the offline CPUs accounted from // For further details see: // https://www.kernel.org/doc/html/latest/core-api/cpu_hotplug.html const std::string sys_cpu_present_path = "/sys/devices/system/cpu/present"; size_t cpu_present_last = 0; std::ifstream cpu_present_file(sys_cpu_present_path); std::string cpu_present_text; if (cpu_present_file.is_open()) { getline(cpu_present_file, cpu_present_text); // This is a comma-separated list of ranges, eg. 0,2-4,7 size_t last_separator = cpu_present_text.find_last_of("-,"); if (last_separator < cpu_present_text.size()) { std::stringstream(cpu_present_text.substr(last_separator + 1)) >> cpu_present_last; } } const std::string data_dir_ = "/proc/stat"; std::ifstream info(data_dir_); if (!info.is_open()) { throw std::runtime_error("Can't open " + data_dir_); } std::vector> cpuinfo; std::string line; size_t current_cpu_number = -1; // First line is total, second line is cpu 0 while (getline(info, line)) { if (line.substr(0, 3).compare("cpu") != 0) { break; } size_t line_cpu_number; if (current_cpu_number >= 0) { std::stringstream(line.substr(3)) >> line_cpu_number; while (line_cpu_number > current_cpu_number) { // Fill in 0 for offline CPUs missing inside the lines of /proc/stat cpuinfo.emplace_back(0, 0); current_cpu_number++; } } std::stringstream sline(line.substr(5)); std::vector times; for (size_t time = 0; sline >> time; times.push_back(time)); size_t idle_time = 0; size_t total_time = 0; if (times.size() >= 5) { // idle + iowait idle_time = times[3] + times[4]; total_time = std::accumulate(times.begin(), times.end(), 0); } cpuinfo.emplace_back(idle_time, total_time); current_cpu_number++; } while (cpu_present_last >= current_cpu_number) { // Fill in 0 for offline CPUs missing after the lines of /proc/stat cpuinfo.emplace_back(0, 0); current_cpu_number++; } return cpuinfo; } waybar-0.12.0/src/modules/custom.cpp000066400000000000000000000204411475603165300173470ustar00rootroot00000000000000#include "modules/custom.hpp" #include #include "util/scope_guard.hpp" waybar::modules::Custom::Custom(const std::string& name, const std::string& id, const Json::Value& config, const std::string& output_name) : ALabel(config, "custom-" + name, id, "{}"), name_(name), output_name_(output_name), id_(id), tooltip_format_enabled_{config_["tooltip-format"].isString()}, percentage_(0), fp_(nullptr), pid_(-1) { dp.emit(); if (!config_["signal"].empty() && config_["interval"].empty() && config_["restart-interval"].empty()) { waitingWorker(); } else if (interval_.count() > 0) { delayWorker(); } else if (config_["exec"].isString()) { continuousWorker(); } } waybar::modules::Custom::~Custom() { if (pid_ != -1) { killpg(pid_, SIGTERM); waitpid(pid_, NULL, 0); pid_ = -1; } } void waybar::modules::Custom::delayWorker() { thread_ = [this] { bool can_update = true; if (config_["exec-if"].isString()) { output_ = util::command::execNoRead(config_["exec-if"].asString()); if (output_.exit_code != 0) { can_update = false; dp.emit(); } } if (can_update) { if (config_["exec"].isString()) { output_ = util::command::exec(config_["exec"].asString(), output_name_); } dp.emit(); } thread_.sleep_for(interval_); }; } void waybar::modules::Custom::continuousWorker() { auto cmd = config_["exec"].asString(); pid_ = -1; fp_ = util::command::open(cmd, pid_, output_name_); if (!fp_) { throw std::runtime_error("Unable to open " + cmd); } thread_ = [this, cmd] { char* buff = nullptr; waybar::util::ScopeGuard buff_deleter([buff]() { if (buff) { free(buff); } }); size_t len = 0; if (getline(&buff, &len, fp_) == -1) { int exit_code = 1; if (fp_) { exit_code = WEXITSTATUS(util::command::close(fp_, pid_)); fp_ = nullptr; } if (exit_code != 0) { output_ = {exit_code, ""}; dp.emit(); spdlog::error("{} stopped unexpectedly, is it endless?", name_); } if (config_["restart-interval"].isUInt()) { pid_ = -1; thread_.sleep_for(std::chrono::seconds(config_["restart-interval"].asUInt())); fp_ = util::command::open(cmd, pid_, output_name_); if (!fp_) { throw std::runtime_error("Unable to open " + cmd); } } else { thread_.stop(); return; } } else { std::string output = buff; // Remove last newline if (!output.empty() && output[output.length() - 1] == '\n') { output.erase(output.length() - 1); } output_ = {0, output}; dp.emit(); } }; } void waybar::modules::Custom::waitingWorker() { thread_ = [this] { bool can_update = true; if (config_["exec-if"].isString()) { output_ = util::command::execNoRead(config_["exec-if"].asString()); if (output_.exit_code != 0) { can_update = false; dp.emit(); } } if (can_update) { if (config_["exec"].isString()) { output_ = util::command::exec(config_["exec"].asString(), output_name_); } dp.emit(); } thread_.sleep(); }; } void waybar::modules::Custom::refresh(int sig) { if (sig == SIGRTMIN + config_["signal"].asInt()) { thread_.wake_up(); } } void waybar::modules::Custom::handleEvent() { if (!config_["exec-on-event"].isBool() || config_["exec-on-event"].asBool()) { thread_.wake_up(); } } bool waybar::modules::Custom::handleScroll(GdkEventScroll* e) { auto ret = ALabel::handleScroll(e); handleEvent(); return ret; } bool waybar::modules::Custom::handleToggle(GdkEventButton* const& e) { auto ret = ALabel::handleToggle(e); handleEvent(); return ret; } auto waybar::modules::Custom::update() -> void { // Hide label if output is empty if ((config_["exec"].isString() || config_["exec-if"].isString()) && (output_.out.empty() || output_.exit_code != 0)) { event_box_.hide(); } else { if (config_["return-type"].asString() == "json") { parseOutputJson(); } else { parseOutputRaw(); } try { auto str = fmt::format(fmt::runtime(format_), fmt::arg("text", text_), fmt::arg("alt", alt_), fmt::arg("icon", getIcon(percentage_, alt_)), fmt::arg("percentage", percentage_)); if ((config_["hide-empty-text"].asBool() && text_.empty()) || str.empty()) { event_box_.hide(); } else { label_.set_markup(str); if (tooltipEnabled()) { 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); } else if (text_ == tooltip_) { if (label_.get_tooltip_markup() != str) { label_.set_tooltip_markup(str); } } else { if (label_.get_tooltip_markup() != tooltip_) { label_.set_tooltip_markup(tooltip_); } } } auto style = label_.get_style_context(); auto classes = style->list_classes(); for (auto const& c : classes) { if (c == id_) continue; style->remove_class(c); } for (auto const& c : class_) { style->add_class(c); } style->add_class("flat"); style->add_class("text-button"); style->add_class(MODULE_CLASS); event_box_.show(); } } catch (const fmt::format_error& e) { if (std::strcmp(e.what(), "cannot switch from manual to automatic argument indexing") != 0) throw; throw fmt::format_error( "mixing manual and automatic argument indexing is no longer supported; " "try replacing \"{}\" with \"{text}\" in your format specifier"); } } // Call parent update ALabel::update(); } void waybar::modules::Custom::parseOutputRaw() { std::istringstream output(output_.out); std::string line; int i = 0; while (getline(output, line)) { Glib::ustring validated_line = line; if (!validated_line.validate()) { validated_line = validated_line.make_valid(); } if (i == 0) { if (config_["escape"].isBool() && config_["escape"].asBool()) { text_ = Glib::Markup::escape_text(validated_line); tooltip_ = Glib::Markup::escape_text(validated_line); } else { text_ = validated_line; tooltip_ = validated_line; } tooltip_ = validated_line; class_.clear(); } else if (i == 1) { if (config_["escape"].isBool() && config_["escape"].asBool()) { tooltip_ = Glib::Markup::escape_text(validated_line); } else { tooltip_ = validated_line; } } else if (i == 2) { class_.push_back(validated_line); } else { break; } i++; } } void waybar::modules::Custom::parseOutputJson() { std::istringstream output(output_.out); std::string line; class_.clear(); while (getline(output, line)) { auto parsed = parser_.parse(line); if (config_["escape"].isBool() && config_["escape"].asBool()) { text_ = Glib::Markup::escape_text(parsed["text"].asString()); } else { text_ = parsed["text"].asString(); } if (config_["escape"].isBool() && config_["escape"].asBool()) { alt_ = Glib::Markup::escape_text(parsed["alt"].asString()); } else { alt_ = parsed["alt"].asString(); } if (config_["escape"].isBool() && config_["escape"].asBool()) { tooltip_ = Glib::Markup::escape_text(parsed["tooltip"].asString()); } else { tooltip_ = parsed["tooltip"].asString(); } if (parsed["class"].isString()) { class_.push_back(parsed["class"].asString()); } else if (parsed["class"].isArray()) { for (auto const& c : parsed["class"]) { class_.push_back(c.asString()); } } if (!parsed["percentage"].asString().empty() && parsed["percentage"].isNumeric()) { percentage_ = (int)lround(parsed["percentage"].asFloat()); } else { percentage_ = 0; } break; } } waybar-0.12.0/src/modules/disk.cpp000066400000000000000000000103361475603165300167710ustar00rootroot00000000000000#include "modules/disk.hpp" using namespace waybar::util; waybar::modules::Disk::Disk(const std::string& id, const Json::Value& config) : ALabel(config, "disk", id, "{}%", 30), path_("/") { thread_ = [this] { dp.emit(); thread_.sleep_for(interval_); }; if (config["path"].isString()) { path_ = config["path"].asString(); } if (config["unit"].isString()) { unit_ = config["unit"].asString(); } } auto waybar::modules::Disk::update() -> void { struct statvfs /* { unsigned long f_bsize; // filesystem block size unsigned long f_frsize; // fragment size fsblkcnt_t f_blocks; // size of fs in f_frsize units fsblkcnt_t f_bfree; // # free blocks fsblkcnt_t f_bavail; // # free blocks for unprivileged users fsfilcnt_t f_files; // # inodes fsfilcnt_t f_ffree; // # free inodes fsfilcnt_t f_favail; // # free inodes for unprivileged users unsigned long f_fsid; // filesystem ID unsigned long f_flag; // mount flags unsigned long f_namemax; // maximum filename length }; */ stats; int err = statvfs(path_.c_str(), &stats); /* Conky options fs_bar - Bar that shows how much space is used fs_free - Free space on a file system fs_free_perc - Free percentage of space fs_size - File system size fs_used - File system used space */ if (err != 0) { event_box_.hide(); return; } float specific_free, specific_used, specific_total, divisor; divisor = calc_specific_divisor(unit_); specific_free = (stats.f_bavail * stats.f_frsize) / divisor; specific_used = ((stats.f_blocks - stats.f_bfree) * stats.f_frsize) / divisor; specific_total = (stats.f_blocks * stats.f_frsize) / divisor; auto free = pow_format(stats.f_bavail * stats.f_frsize, "B", true); auto used = pow_format((stats.f_blocks - stats.f_bfree) * stats.f_frsize, "B", true); auto total = pow_format(stats.f_blocks * stats.f_frsize, "B", true); auto percentage_used = (stats.f_blocks - stats.f_bfree) * 100 / stats.f_blocks; auto format = format_; auto state = getState(percentage_used); if (!state.empty() && config_["format-" + state].isString()) { format = config_["format-" + state].asString(); } if (format.empty()) { event_box_.hide(); } else { event_box_.show(); label_.set_markup(fmt::format( fmt::runtime(format), stats.f_bavail * 100 / stats.f_blocks, fmt::arg("free", free), fmt::arg("percentage_free", stats.f_bavail * 100 / stats.f_blocks), fmt::arg("used", used), fmt::arg("percentage_used", percentage_used), fmt::arg("total", total), fmt::arg("path", path_), fmt::arg("specific_free", specific_free), fmt::arg("specific_used", specific_used), fmt::arg("specific_total", specific_total))); } if (tooltipEnabled()) { std::string tooltip_format = "{used} used out of {total} on {path} ({percentage_used}%)"; if (config_["tooltip-format"].isString()) { tooltip_format = config_["tooltip-format"].asString(); } label_.set_tooltip_text(fmt::format( fmt::runtime(tooltip_format), stats.f_bavail * 100 / stats.f_blocks, fmt::arg("free", free), fmt::arg("percentage_free", stats.f_bavail * 100 / stats.f_blocks), fmt::arg("used", used), fmt::arg("percentage_used", percentage_used), fmt::arg("total", total), fmt::arg("path", path_), fmt::arg("specific_free", specific_free), fmt::arg("specific_used", specific_used), fmt::arg("specific_total", specific_total))); } // Call parent update ALabel::update(); } float waybar::modules::Disk::calc_specific_divisor(std::string divisor) { if (divisor == "kB") { return 1000.0; } else if (divisor == "kiB") { return 1024.0; } else if (divisor == "MB") { return 1000.0 * 1000.0; } else if (divisor == "MiB") { return 1024.0 * 1024.0; } else if (divisor == "GB") { return 1000.0 * 1000.0 * 1000.0; } else if (divisor == "GiB") { return 1024.0 * 1024.0 * 1024.0; } else if (divisor == "TB") { return 1000.0 * 1000.0 * 1000.0 * 1000.0; } else if (divisor == "TiB") { return 1024.0 * 1024.0 * 1024.0 * 1024.0; } else { // default to Bytes if it is anything that we don't recongnise return 1.0; } }waybar-0.12.0/src/modules/dwl/000077500000000000000000000000001475603165300161165ustar00rootroot00000000000000waybar-0.12.0/src/modules/dwl/tags.cpp000066400000000000000000000144421475603165300175650ustar00rootroot00000000000000#include "modules/dwl/tags.hpp" #include #include #include #include #include #include "client.hpp" #include "dwl-ipc-unstable-v2-client-protocol.h" #define TAG_INACTIVE 0 #define TAG_ACTIVE 1 #define TAG_URGENT 2 namespace waybar::modules::dwl { /* dwl stuff */ wl_array tags, layouts; static uint num_tags = 0; 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) { // Intentionally empty } 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); 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) { // Intentionally empty } 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) { // Intentionally empty } 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) { // Intentionally empty }; static const zdwl_ipc_output_v2_listener output_status_listener_impl{ .toggle_visibility = toggle_visibility, .active = active, .tag = set_tag, .layout = set_layout, .title = title, .appid = appid, .layout_symbol = set_layout_symbol, .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_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) : 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); wl_registry_add_listener(registry, ®istry_listener_impl, this); wl_display_roundtrip(display); if (!status_manager_) { spdlog::error("dwl_status_manager_v2 not advertised"); return; } if (!seat_) { spdlog::error("wl_seat not advertised"); } box_.set_name("tags"); if (!id.empty()) { box_.get_style_context()->add_class(id); } box_.get_style_context()->add_class(MODULE_CLASS); event_box_.add(box_); // Default to 9 tags, cap at 32 const uint32_t num_tags = config["num-tags"].isUInt() ? std::min(32, config_["num-tags"].asUInt()) : 9; std::vector tag_labels(num_tags); for (uint32_t tag = 0; tag < num_tags; ++tag) { tag_labels[tag] = std::to_string(tag + 1); } const Json::Value custom_labels = config["tag-labels"]; if (custom_labels.isArray() && !custom_labels.empty()) { for (uint32_t tag = 0; tag < std::min(num_tags, custom_labels.size()); ++tag) { tag_labels[tag] = custom_labels[tag].asString(); } } uint32_t i = 1; 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()) { button.signal_clicked().connect( sigc::bind(sigc::mem_fun(*this, &Tags::handle_primary_clicked), i)); button.signal_button_press_event().connect( sigc::bind(sigc::mem_fun(*this, &Tags::handle_button_press), i)); } button.show(); i <<= 1; } 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_); status_manager_ = nullptr; } Tags::~Tags() { if (output_status_) { zdwl_ipc_output_v2_destroy(output_status_); } if (status_manager_) { zdwl_ipc_manager_v2_destroy(status_manager_); } } void Tags::handle_primary_clicked(uint32_t tag) { if (!output_status_) return; zdwl_ipc_output_v2_set_tags(output_status_, tag, 1); } 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); } return true; } void Tags::handle_view_tags(uint32_t tag, uint32_t state, uint32_t clients, uint32_t focused) { // First clear all occupied state auto &button = buttons_[tag]; if (clients) { button.get_style_context()->add_class("occupied"); } else { button.get_style_context()->remove_class("occupied"); } if (state & TAG_ACTIVE) { button.get_style_context()->add_class("focused"); } else { button.get_style_context()->remove_class("focused"); } if (state & TAG_URGENT) { button.get_style_context()->add_class("urgent"); } else { button.get_style_context()->remove_class("urgent"); } } } /* namespace waybar::modules::dwl */ waybar-0.12.0/src/modules/dwl/window.cpp000066400000000000000000000102031475603165300201250ustar00rootroot00000000000000#include "modules/dwl/window.hpp" #include #include #include #include #include #include #include "client.hpp" #include "dwl-ipc-unstable-v2-client-protocol.h" #include "glibmm/markup.h" #include "util/rewrite_string.hpp" namespace waybar::modules::dwl { 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) { // Intentionally empty } 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 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 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 const zdwl_ipc_output_v2_listener output_status_listener_impl{ .toggle_visibility = toggle_visibility, .active = active, .tag = set_tag, .layout = set_layout, .title = title, .appid = appid, .layout_symbol = set_layout_symbol, .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)); } } 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) : 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); wl_registry_add_listener(registry, ®istry_listener_impl, this); wl_display_roundtrip(display); if (status_manager_ == nullptr) { spdlog::error("dwl_status_manager_v2 not advertised"); return; } 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_); } Window::~Window() { if (output_status_ != nullptr) { zdwl_ipc_output_v2_destroy(output_status_); } } 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_layout_symbol(const char *layout_symbol) { layout_symbol_ = Glib::Markup::escape_text(layout_symbol); } void Window::handle_layout(const uint32_t layout) { layout_ = layout; } void Window::handle_frame() { label_.set_markup(waybar::util::rewriteString( fmt::format(fmt::runtime(format_), fmt::arg("title", title_), fmt::arg("layout", layout_symbol_), fmt::arg("app_id", appid_)), config_["rewrite"])); updateAppIconName(appid_, ""); updateAppIcon(); if (tooltipEnabled()) { label_.set_tooltip_text(title_); } } } // namespace waybar::modules::dwl waybar-0.12.0/src/modules/gamemode.cpp000066400000000000000000000164051475603165300176200ustar00rootroot00000000000000#include "modules/gamemode.hpp" #include #include #include #include #include #include "AModule.hpp" #include "giomm/dbusconnection.h" #include "giomm/dbusinterface.h" #include "giomm/dbusproxy.h" #include "giomm/dbuswatchname.h" #include "glibmm/error.h" #include "glibmm/ustring.h" #include "glibmm/variant.h" #include "glibmm/varianttype.h" #include "gtkmm/label.h" #include "gtkmm/tooltip.h" #include "util/gtk_icon.hpp" namespace waybar::modules { Gamemode::Gamemode(const std::string& id, const Json::Value& config) : AModule(config, "gamemode", id), box_(Gtk::ORIENTATION_HORIZONTAL, 0), icon_(), label_() { box_.pack_start(icon_); box_.pack_start(label_); box_.set_name(name_); event_box_.add(box_); // Tooltip if (config_["tooltip"].isBool()) { tooltip = config_["tooltip"].asBool(); } box_.set_has_tooltip(tooltip); // Tooltip Format if (config_["tooltip-format"].isString()) { tooltip_format = config_["tooltip-format"].asString(); } // Hide when game count is 0 if (config_["hide-not-running"].isBool()) { hideNotRunning = config_["hide-not-running"].asBool(); } // Icon Name if (config_["icon-name"].isString()) { iconName = config_["icon-name"].asString(); } // Icon Spacing 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()) { useIcon = config_["use-icon"].asBool(); } // Icon Size if (config_["icon-size"].isUInt()) { iconSize = config_["icon-size"].asUInt(); } icon_.set_pixel_size(iconSize); // Format if (config_["format"].isString()) { format = config_["format"].asString(); } // Format Alt if (config_["format-alt"].isString()) { format_alt = config_["format-alt"].asString(); } // Glyph if (config_["glyph"].isString()) { glyph = config_["glyph"].asString(); } gamemodeWatcher_id = Gio::DBus::watch_name( Gio::DBus::BUS_TYPE_SESSION, dbus_name, sigc::mem_fun(*this, &Gamemode::appear), sigc::mem_fun(*this, &Gamemode::disappear), Gio::DBus::BusNameWatcherFlags::BUS_NAME_WATCHER_FLAGS_AUTO_START); // Connect to gamemode gamemode_proxy = Gio::DBus::Proxy::create_for_bus_sync(Gio::DBus::BusType::BUS_TYPE_SESSION, dbus_name, dbus_obj_path, dbus_interface); if (!gamemode_proxy) { throw std::runtime_error("Unable to connect to gamemode DBus!..."); } else { gamemode_proxy->signal_signal().connect(sigc::mem_fun(*this, &Gamemode::notify_cb)); } // Connect to Login1 PrepareForSleep signal system_connection = Gio::DBus::Connection::get_sync(Gio::DBus::BusType::BUS_TYPE_SYSTEM); if (!system_connection) { throw std::runtime_error("Unable to connect to the SYSTEM Bus!..."); } else { login1_id = system_connection->signal_subscribe( sigc::mem_fun(*this, &Gamemode::prepareForSleep_cb), "org.freedesktop.login1", "org.freedesktop.login1.Manager", "PrepareForSleep", "/org/freedesktop/login1"); } event_box_.signal_button_press_event().connect(sigc::mem_fun(*this, &Gamemode::handleToggle)); } Gamemode::~Gamemode() { if (gamemode_proxy) gamemode_proxy.reset(); if (gamemodeWatcher_id > 0) { Gio::DBus::unwatch_name(gamemodeWatcher_id); gamemodeWatcher_id = 0; } if (login1_id > 0) { system_connection->signal_unsubscribe(login1_id); login1_id = 0; } } // Gets the DBus ClientCount void Gamemode::getData() { if (gamemodeRunning && gamemode_proxy) { try { // Get game count auto parameters = Glib::VariantContainerBase( g_variant_new("(ss)", dbus_get_interface.c_str(), "ClientCount")); 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); if (variant && variant.is_of_type(Glib::VARIANT_TYPE_INT32)) { g_variant_get(variant.gobj_copy(), "i", &gameCount); return; } } } catch (Glib::Error& e) { spdlog::error("Gamemode Error {}", e.what().c_str()); } } gameCount = 0; } // Whenever the DBus ClientCount changes void Gamemode::notify_cb(const Glib::ustring& sender_name, const Glib::ustring& signal_name, const Glib::VariantContainerBase& arguments) { if (signal_name == "PropertiesChanged") { getData(); dp.emit(); } } void Gamemode::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)"))) { gboolean sleeping; g_variant_get(parameters.gobj_copy(), "(b)", &sleeping); if (!sleeping) { getData(); dp.emit(); } } } // When the gamemode name appears void Gamemode::appear(const Glib::RefPtr& connection, const Glib::ustring& name, const Glib::ustring& name_owner) { gamemodeRunning = true; event_box_.set_visible(true); getData(); dp.emit(); } // When the gamemode name disappears void Gamemode::disappear(const Glib::RefPtr& connection, const Glib::ustring& name) { gamemodeRunning = false; event_box_.set_visible(false); } bool Gamemode::handleToggle(GdkEventButton* const& event) { showAltText = !showAltText; dp.emit(); return true; } auto Gamemode::update() -> void { // Don't update widget if the Gamemode service isn't running if (!gamemodeRunning || (gameCount <= 0 && hideNotRunning)) { event_box_.set_visible(false); return; } // Show the module if (!event_box_.get_visible()) event_box_.set_visible(true); // CSS status class const std::string status = gamemodeRunning && gameCount > 0 ? "running" : ""; // Remove last status if it exists if (!lastStatus.empty() && box_.get_style_context()->has_class(lastStatus)) { box_.get_style_context()->remove_class(lastStatus); } // Add the new status class to the Box if (!status.empty() && !box_.get_style_context()->has_class(status)) { box_.get_style_context()->add_class(status); } lastStatus = status; // Tooltip if (tooltip) { std::string text = fmt::format(fmt::runtime(tooltip_format), fmt::arg("count", gameCount)); box_.set_tooltip_text(text); } // Label format std::string str = fmt::format(fmt::runtime(showAltText ? format_alt : format), fmt::arg("glyph", useIcon ? "" : glyph), fmt::arg("count", gameCount > 0 ? std::to_string(gameCount) : "")); label_.set_markup(str); if (useIcon) { if (!DefaultGtkIconThemeWrapper::has_icon(iconName)) { iconName = DEFAULT_ICON_NAME; } icon_.set_from_icon_name(iconName, Gtk::ICON_SIZE_INVALID); } // Call parent update AModule::update(); } } // namespace waybar::modules waybar-0.12.0/src/modules/hyprland/000077500000000000000000000000001475603165300171515ustar00rootroot00000000000000waybar-0.12.0/src/modules/hyprland/backend.cpp000066400000000000000000000144031475603165300212460ustar00rootroot00000000000000#include "modules/hyprland/backend.hpp" #include #include #include #include #include #include #include #include #include #include namespace waybar::modules::hyprland { std::filesystem::path IPC::socketFolder_; 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_; } 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_; } IPC::IPC() { // will start IPC and relay events to parseIPC ipcThread_ = std::thread([this]() { socketListener(); }); } IPC::~IPC() { running_ = false; 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"); } } ipcThread_.join(); } IPC& IPC::inst() { static IPC ipc; return ipc; } void IPC::socketListener() { // check for hyprland const char* his = getenv("HYPRLAND_INSTANCE_SIGNATURE"); if (his == nullptr) { spdlog::warn("Hyprland is not running, Hyprland IPC will not be available."); return; } if (!modulesReady) return; spdlog::info("Hyprland IPC starting"); struct sockaddr_un addr; socketfd_ = socket(AF_UNIX, SOCK_STREAM, 0); if (socketfd_ == -1) { spdlog::error("Hyprland IPC: socketfd failed"); return; } addr.sun_family = AF_UNIX; auto socketPath = IPC::getSocketFolder(his) / ".socket2.sock"; 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?"); return; } auto* file = fdopen(socketfd_, "r"); if (file == nullptr) { spdlog::error("Hyprland IPC: Couldn't open file descriptor"); return; } while (running_) { std::array buffer; // Hyprland socket2 events are max 1024 bytes auto* receivedCharPtr = fgets(buffer.data(), buffer.size(), file); if (receivedCharPtr == nullptr) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); continue; } 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; } std::this_thread::sleep_for(std::chrono::milliseconds(1)); } spdlog::debug("Hyprland IPC stopped"); } void IPC::parseIPC(const std::string& ev) { std::string request = ev.substr(0, ev.find_first_of('>')); std::unique_lock lock(callbackMutex_); for (auto& [eventname, handler] : callbacks_) { if (eventname == request) { handler->onEvent(ev); } } } void IPC::registerForIPC(const std::string& ev, EventHandler* ev_handler) { if (ev_handler == nullptr) { return; } std::unique_lock lock(callbackMutex_); callbacks_.emplace_back(ev, ev_handler); } void IPC::unregisterForIPC(EventHandler* ev_handler) { if (ev_handler == nullptr) { return; } std::unique_lock lock(callbackMutex_); for (auto it = callbacks_.begin(); it != callbacks_.end();) { auto& [eventname, handler] = *it; if (handler == ev_handler) { callbacks_.erase(it++); } else { ++it; } } } std::string IPC::getSocket1Reply(const std::string& rq) { // basically hyprctl const auto serverSocket = socket(AF_UNIX, SOCK_STREAM, 0); if (serverSocket < 0) { throw std::runtime_error("Hyprland IPC: Couldn't open a socket (1)"); } // get the instance signature auto* instanceSig = getenv("HYPRLAND_INSTANCE_SIGNATURE"); if (instanceSig == nullptr) { throw std::runtime_error( "Hyprland IPC: HYPRLAND_INSTANCE_SIGNATURE was not set! (Is Hyprland running?)"); } sockaddr_un serverAddress = {0}; serverAddress.sun_family = AF_UNIX; 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) { throw std::runtime_error("Hyprland IPC: Couldn't copy socket path (6)"); } if (connect(serverSocket, reinterpret_cast(&serverAddress), sizeof(serverAddress)) < 0) { throw std::runtime_error("Hyprland IPC: Couldn't connect to " + socketPath + ". (3)"); } auto sizeWritten = write(serverSocket, rq.c_str(), rq.length()); if (sizeWritten < 0) { spdlog::error("Hyprland IPC: Couldn't write (4)"); return ""; } std::array buffer = {0}; std::string response; 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; } Json::Value IPC::getSocket1JsonReply(const std::string& rq) { std::string reply = getSocket1Reply("j/" + rq); if (reply.empty()) { return {}; } return parser_.parse(reply); } } // namespace waybar::modules::hyprland waybar-0.12.0/src/modules/hyprland/language.cpp000066400000000000000000000110541475603165300214410ustar00rootroot00000000000000#include "modules/hyprland/language.hpp" #include #include #include #include "util/sanitize_str.hpp" #include "util/string.hpp" 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(); label_.hide(); update(); // register for hyprland ipc m_ipc.registerForIPC("activelayout", this); } Language::~Language() { m_ipc.unregisterForIPC(this); // wait for possible event handler to finish std::lock_guard lg(mutex_); } auto Language::update() -> void { std::lock_guard lg(mutex_); spdlog::debug("hyprland language update with full name {}", layout_.full_name); spdlog::debug("hyprland language update with short name {}", layout_.short_name); spdlog::debug("hyprland language update with short description {}", layout_.short_description); spdlog::debug("hyprland language update with variant {}", layout_.variant); std::string layoutName = std::string{}; if (config_.isMember("format-" + layout_.short_description + "-" + layout_.variant)) { const auto propName = "format-" + layout_.short_description + "-" + layout_.variant; layoutName = fmt::format(fmt::runtime(format_), config_[propName].asString()); } else if (config_.isMember("format-" + layout_.short_description)) { const auto propName = "format-" + layout_.short_description; layoutName = fmt::format(fmt::runtime(format_), config_[propName].asString()); } else { layoutName = trim(fmt::format(fmt::runtime(format_), fmt::arg("long", layout_.full_name), fmt::arg("short", layout_.short_name), fmt::arg("shortDescription", layout_.short_description), fmt::arg("variant", layout_.variant))); } spdlog::debug("hyprland language formatted layout name {}", layoutName); if (!format_.empty()) { label_.show(); label_.set_markup(layoutName); } else { label_.hide(); } ALabel::update(); } 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); if (config_.isMember("keyboard-name") && kbName != config_["keyboard-name"].asString()) return; // ignore layoutName = waybar::util::sanitize_string(layoutName); layout_ = getLayout(layoutName); spdlog::debug("hyprland language onevent with {}", layoutName); dp.emit(); } void Language::initLanguage() { const auto inputDevices = m_ipc.getSocket1Reply("devices"); const auto kbName = config_["keyboard-name"].asString(); try { auto searcher = kbName.empty() ? inputDevices : inputDevices.substr(inputDevices.find(kbName) + kbName.length()); searcher = searcher.substr(searcher.find("keymap:") + 8); searcher = searcher.substr(0, searcher.find_first_of("\n\t")); searcher = waybar::util::sanitize_string(searcher); layout_ = getLayout(searcher); spdlog::debug("hyprland language initLanguage found {}", layout_.full_name); dp.emit(); } catch (std::exception& e) { spdlog::error("hyprland language initLanguage failed with {}", e.what()); } } auto Language::getLayout(const std::string& fullName) -> Layout { auto* const context = rxkb_context_new(RXKB_CONTEXT_LOAD_EXOTIC_RULES); rxkb_context_parse_default_ruleset(context); rxkb_layout* layout = rxkb_layout_first(context); while (layout != nullptr) { std::string nameOfLayout = rxkb_layout_get_description(layout); if (nameOfLayout != fullName) { layout = rxkb_layout_next(layout); continue; } auto name = std::string(rxkb_layout_get_name(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); std::string description = descriptionPtr == nullptr ? "" : std::string(descriptionPtr); Layout info = Layout{nameOfLayout, name, variant, description}; rxkb_context_unref(context); return info; } rxkb_context_unref(context); spdlog::debug("hyprland language didn't find matching layout"); return Layout{"", "", "", ""}; } } // namespace waybar::modules::hyprland waybar-0.12.0/src/modules/hyprland/submap.cpp000066400000000000000000000041601475603165300211450ustar00rootroot00000000000000#include "modules/hyprland/submap.hpp" #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 if (always_on_) { submap_ = default_submap_; label_.get_style_context()->add_class(submap_); } // register for hyprland ipc m_ipc.registerForIPC("submap", this); dp.emit(); } Submap::~Submap() { m_ipc.unregisterForIPC(this); // wait for possible event handler to finish std::lock_guard lg(mutex_); } auto Submap::parseConfig(const Json::Value& config) -> void { auto const& alwaysOn = config["always-on"]; if (alwaysOn.isBool()) { always_on_ = alwaysOn.asBool(); } auto const& defaultSubmap = config["default-submap"]; if (defaultSubmap.isString()) { default_submap_ = defaultSubmap.asString(); } } auto Submap::update() -> void { std::lock_guard lg(mutex_); if (submap_.empty()) { event_box_.hide(); } else { label_.set_markup(fmt::format(fmt::runtime(format_), submap_)); if (tooltipEnabled()) { label_.set_tooltip_text(submap_); } event_box_.show(); } // Call parent update ALabel::update(); } void Submap::onEvent(const std::string& ev) { std::lock_guard lg(mutex_); if (ev.find("submap") == std::string::npos) { 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_); } submap_ = submapName; if (submap_.empty() && always_on_) { submap_ = default_submap_; } label_.get_style_context()->add_class(submap_); spdlog::debug("hyprland submap onevent with {}", submap_); dp.emit(); } } // namespace waybar::modules::hyprland waybar-0.12.0/src/modules/hyprland/window.cpp000066400000000000000000000202331475603165300211640ustar00rootroot00000000000000#include "modules/hyprland/window.hpp" #include #include #include #include #include #include #include #include "modules/hyprland/backend.hpp" #include "util/rewrite_string.hpp" #include "util/sanitize_str.hpp" namespace waybar::modules::hyprland { 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(); // register for hyprland ipc 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(); } Window::~Window() { std::unique_lock windowIpcUniqueLock(windowIpcSmtx); m_ipc.unregisterForIPC(this); } auto Window::update() -> void { std::shared_lock windowIpcShareLock(windowIpcSmtx); std::string windowName = waybar::util::sanitize_string(workspace_.last_window_title); std::string windowAddress = workspace_.last_window; windowData_.title = windowName; std::string label_text; if (!format_.empty()) { label_.show(); label_text = waybar::util::rewriteString( fmt::format(fmt::runtime(format_), fmt::arg("title", windowName), fmt::arg("initialTitle", windowData_.initial_title), fmt::arg("class", windowData_.class_name), fmt::arg("initialClass", windowData_.initial_class_name)), config_["rewrite"]); label_.set_markup(label_text); } else { label_.hide(); } 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("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); } } if (focused_) { image_.show(); } else { image_.hide(); } setClass("empty", workspace_.windows == 0); setClass("solo", solo_); setClass("floating", allFloating_); setClass("swallowing", swallowing_); setClass("fullscreen", fullscreen_); if (!lastSoloClass_.empty() && soloClass_ != lastSoloClass_) { if (bar_.window.get_style_context()->has_class(lastSoloClass_)) { bar_.window.get_style_context()->remove_class(lastSoloClass_); spdlog::trace("Removing solo class: {}", lastSoloClass_); } } if (!soloClass_.empty() && soloClass_ != lastSoloClass_) { bar_.window.get_style_context()->add_class(soloClass_); spdlog::trace("Adding solo class: {}", soloClass_); } lastSoloClass_ = soloClass_; AAppIconLabel::update(); } auto Window::getActiveWorkspace() -> Workspace { const auto workspace = IPC::inst().getSocket1JsonReply("activeworkspace"); if (workspace.isObject()) { return Workspace::parse(workspace); } return {}; } 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; }); if (monitor == std::end(monitors)) { spdlog::warn("Monitor not found: {}", monitorName); return Workspace{ .id = -1, .windows = 0, .last_window = "", .last_window_title = "", }; } const int 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; }); if (workspace == std::end(workspaces)) { spdlog::warn("No workspace with id {}", id); return Workspace{ .id = -1, .windows = 0, .last_window = "", .last_window_title = "", }; } return Workspace::parse(*workspace); }; }; return {}; } auto Window::Workspace::parse(const Json::Value& value) -> Window::Workspace { return Workspace{ .id = value["id"].asInt(), .windows = value["windows"].asInt(), .last_window = value["lastwindow"].asString(), .last_window_title = value["lastwindowtitle"].asString(), }; } auto Window::WindowData::parse(const Json::Value& value) -> Window::WindowData { return WindowData{.floating = value["floating"].asBool(), .monitor = value["monitor"].asInt(), .class_name = value["class"].asString(), .initial_class_name = value["initialClass"].asString(), .title = value["title"].asString(), .initial_title = value["initialTitle"].asString(), .fullscreen = value["fullscreen"].asBool(), .grouped = !value["grouped"].empty()}; } void Window::queryActiveWorkspace() { std::shared_lock windowIpcShareLock(windowIpcSmtx); if (separateOutputs_) { workspace_ = getActiveWorkspace(this->bar_.output->name); } else { workspace_ = getActiveWorkspace(); } 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) { 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; // 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_ = ""; } } void Window::onEvent(const std::string& ev) { queryActiveWorkspace(); dp.emit(); } 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); } } else { bar_.window.get_style_context()->remove_class(classname); } } } // namespace waybar::modules::hyprland waybar-0.12.0/src/modules/hyprland/windowcreationpayload.cpp000066400000000000000000000100501475603165300242570ustar00rootroot00000000000000#include "modules/hyprland/windowcreationpayload.hpp" #include #include #include #include #include #include "modules/hyprland/workspaces.hpp" namespace waybar::modules::hyprland { 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()) { clearAddr(); clearWorkspaceName(); } WindowCreationPayload::WindowCreationPayload(std::string workspace_name, WindowAddress window_address, std::string window_repr) : m_window(std::move(window_repr)), m_windowAddress(std::move(window_address)), m_workspaceName(std::move(workspace_name)) { clearAddr(); clearWorkspaceName(); } WindowCreationPayload::WindowCreationPayload(std::string workspace_name, WindowAddress window_address, std::string window_class, std::string window_title) : 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)) { clearAddr(); clearWorkspaceName(); } void WindowCreationPayload::clearAddr() { // substr(2, ...) is necessary because Hyprland's JSON follows this format: // 0x{ADDR} // While Hyprland's IPC follows this format: // {ADDR} static const std::string ADDR_PREFIX = "0x"; static const int ADDR_PREFIX_LEN = ADDR_PREFIX.length(); if (m_windowAddress.starts_with(ADDR_PREFIX)) { m_windowAddress = m_windowAddress.substr(ADDR_PREFIX_LEN, m_windowAddress.length() - ADDR_PREFIX_LEN); } } void WindowCreationPayload::clearWorkspaceName() { // The workspace name may optionally feature "special:" at the beginning. // If so, we need to remove it because the workspace is saved WITHOUT the // special qualifier. The reasoning is that not all of Hyprland's IPC events // use this qualifier, so it's better to be consistent about our uses. static const std::string SPECIAL_QUALIFIER_PREFIX = "special:"; static const int SPECIAL_QUALIFIER_PREFIX_LEN = SPECIAL_QUALIFIER_PREFIX.length(); if (m_workspaceName.starts_with(SPECIAL_QUALIFIER_PREFIX)) { m_workspaceName = m_workspaceName.substr( SPECIAL_QUALIFIER_PREFIX_LEN, m_workspaceName.length() - SPECIAL_QUALIFIER_PREFIX_LEN); } std::size_t spaceFound = m_workspaceName.find(' '); if (spaceFound != std::string::npos) { m_workspaceName.erase(m_workspaceName.begin() + spaceFound, m_workspaceName.end()); } } bool WindowCreationPayload::isEmpty(Workspaces &workspace_manager) { if (std::holds_alternative(m_window)) { return std::get(m_window).empty(); } if (std::holds_alternative(m_window)) { auto [window_class, window_title] = std::get(m_window); return (window_class.empty() && (!workspace_manager.windowRewriteConfigUsesTitle() || window_title.empty())); } // Unreachable spdlog::error("WorkspaceWindow::isEmpty: Unreachable"); throw std::runtime_error("WorkspaceWindow::isEmpty: Unreachable"); } int WindowCreationPayload::incrementTimeSpentUncreated() { return m_timeSpentUncreated++; } void WindowCreationPayload::moveToWorksace(std::string &new_workspace_name) { m_workspaceName = new_workspace_name; } std::string 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); } // Unreachable spdlog::error("WorkspaceWindow::repr: Unreachable"); throw std::runtime_error("WorkspaceWindow::repr: Unreachable"); } } // namespace waybar::modules::hyprland waybar-0.12.0/src/modules/hyprland/workspace.cpp000066400000000000000000000152111475603165300216530ustar00rootroot00000000000000#include #include #include #include #include #include "modules/hyprland/workspaces.hpp" namespace waybar::modules::hyprland { 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()), m_output(workspace_data["monitor"].asString()), // TODO:allow using monitor desc m_windows(workspace_data["windows"].asInt()), m_isActive(true), m_isPersistentRule(workspace_data["persistent-rule"].asBool()), m_isPersistentConfig(workspace_data["persistent-config"].asBool()), m_ipc(IPC::inst()) { if (m_name.starts_with("name:")) { m_name = m_name.substr(5); } else if (m_name.starts_with("special")) { m_name = m_id == -99 ? m_name : m_name.substr(8); m_isSpecial = true; } m_button.add_events(Gdk::BUTTON_PRESS_MASK); 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); m_button.add(m_content); initializeWindowMap(clients_data); } void addOrRemoveClass(const Glib::RefPtr &context, bool condition, const std::string &class_name) { if (condition) { context->add_class(class_name); } else { context->remove_class(class_name); } } std::optional Workspace::closeWindow(WindowAddress const &addr) { if (m_windowMap.contains(addr)) { return removeWindow(addr); } return std::nullopt; } 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())); } else { m_ipc.getSocket1Reply("dispatch workspace " + std::to_string(id())); } } else if (!isSpecial()) { // named (this includes persistent) if (m_workspaceManager.moveToMonitor()) { m_ipc.getSocket1Reply("dispatch focusworkspaceoncurrentmonitor name:" + name()); } else { m_ipc.getSocket1Reply("dispatch workspace name:" + name()); } } else if (id() != -99) { // named special m_ipc.getSocket1Reply("dispatch togglespecialworkspace " + name()); } else { // special m_ipc.getSocket1Reply("dispatch togglespecialworkspace"); } return true; } catch (const std::exception &e) { spdlog::error("Failed to dispatch workspace: {}", e.what()); } } return false; } void Workspace::initializeWindowMap(const Json::Value &clients_data) { m_windowMap.clear(); for (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; } } }; bool Workspace::onWindowOpened(WindowCreationPayload const &create_window_paylod) { if (create_window_paylod.getWorkspaceName() == name()) { insertWindow(create_window_paylod); 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) { spdlog::trace("Selecting icon for workspace {}", name()); if (isUrgent()) { auto urgentIconIt = icons_map.find("urgent"); if (urgentIconIt != icons_map.end()) { return urgentIconIt->second; } } if (isActive()) { auto activeIconIt = icons_map.find("active"); if (activeIconIt != icons_map.end()) { return activeIconIt->second; } } if (isSpecial()) { auto specialIconIt = icons_map.find("special"); if (specialIconIt != icons_map.end()) { return specialIconIt->second; } } auto namedIconIt = icons_map.find(name()); if (namedIconIt != icons_map.end()) { return namedIconIt->second; } if (isVisible()) { auto visibleIconIt = icons_map.find("visible"); if (visibleIconIt != icons_map.end()) { return visibleIconIt->second; } } if (isEmpty()) { auto emptyIconIt = icons_map.find("empty"); if (emptyIconIt != icons_map.end()) { return emptyIconIt->second; } } if (isPersistent()) { auto persistentIconIt = icons_map.find("persistent"); if (persistentIconIt != icons_map.end()) { return persistentIconIt->second; } } auto defaultIconIt = icons_map.find("default"); if (defaultIconIt != icons_map.end()) { return defaultIconIt->second; } return m_name; } void Workspace::update(const std::string &format, const std::string &icon) { // clang-format off if (this->m_workspaceManager.activeOnly() && \ !this->isActive() && \ !this->isPersistent() && \ !this->isVisible() && \ !this->isSpecial()) { // clang-format on // if activeOnly is true, hide if not active, persistent, visible or special m_button.hide(); return; } if (this->m_workspaceManager.specialVisibleOnly() && this->isSpecial() && !this->isVisible()) { m_button.hide(); return; } m_button.show(); auto styleContext = m_button.get_style_context(); addOrRemoveClass(styleContext, isActive(), "active"); addOrRemoveClass(styleContext, isSpecial(), "special"); addOrRemoveClass(styleContext, isEmpty(), "empty"); addOrRemoveClass(styleContext, isPersistent(), "persistent"); addOrRemoveClass(styleContext, isUrgent(), "urgent"); addOrRemoveClass(styleContext, isVisible(), "visible"); addOrRemoveClass(styleContext, m_workspaceManager.getBarOutput() == output(), "hosting-monitor"); std::string windows; auto windowSeparator = m_workspaceManager.getWindowSeparator(); bool isNotFirst = false; for (auto &[_pid, window_repr] : m_windowMap) { if (isNotFirst) { windows.append(windowSeparator); } 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))); } } // namespace waybar::modules::hyprland waybar-0.12.0/src/modules/hyprland/workspaces.cpp000066400000000000000000001012331475603165300220360ustar00rootroot00000000000000#include "modules/hyprland/workspaces.hpp" #include #include #include #include #include #include #include "util/regex_collection.hpp" namespace waybar::modules::hyprland { 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"); if (!id.empty()) { m_box.get_style_context()->add_class(id); } m_box.get_style_context()->add_class(MODULE_CLASS); event_box_.add(m_box); setCurrentMonitorId(); init(); registerIpc(); } Workspaces::~Workspaces() { m_ipc.unregisterForIPC(this); // wait for possible event handler to finish std::lock_guard lg(m_mutex); } void Workspaces::init() { m_activeWorkspaceName = (m_ipc.getSocket1JsonReply("activeworkspace"))["name"].asString(); initializeWorkspaces(); dp.emit(); } Json::Value Workspaces::createMonitorWorkspaceData(std::string const &name, std::string const &monitor) { spdlog::trace("Creating persistent workspace: {} on monitor {}", name, monitor); Json::Value workspaceData; try { // numbered persistent workspaces get the name as ID workspaceData["id"] = name == "special" ? -99 : std::stoi(name); } catch (const std::exception &e) { // named persistent workspaces start with ID=0 workspaceData["id"] = 0; } workspaceData["name"] = name; workspaceData["monitor"] = monitor; workspaceData["windows"] = 0; return workspaceData; } void Workspaces::createWorkspace(Json::Value const &workspace_data, Json::Value const &clients_data) { auto workspaceName = workspace_data["name"].asString(); spdlog::debug("Creating workspace {}", workspaceName); // avoid recreating existing workspaces auto workspace = std::find_if( m_workspaces.begin(), m_workspaces.end(), [workspaceName](std::unique_ptr const &w) { 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"; if (std::find(keys.begin(), keys.end(), k) != keys.end()) { spdlog::debug("Set dynamic persistency of workspace {} to: {}", workspaceName, workspace_data[k].asBool() ? "true" : "false"); (*workspace)->setPersistentRule(workspace_data[k].asBool()); } k = "persistent-config"; if (std::find(keys.begin(), keys.end(), k) != keys.end()) { spdlog::debug("Set config persistency of workspace {} to: {}", workspaceName, workspace_data[k].asBool() ? "true" : "false"); (*workspace)->setPersistentConfig(workspace_data[k].asBool()); } return; } // create new workspace m_workspaces.emplace_back(std::make_unique(workspace_data, *this, clients_data)); 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) { createWorkspace(workspaceData, clientsData); } if (!m_workspacesToCreate.empty()) { updateWindowCount(); sortWorkspaces(); } m_workspacesToCreate.clear(); } /** * Workspaces::doUpdate - update workspaces in UI thread. * * Note: some memberfields are modified by both UI thread and event listener thread, use m_mutex to * protect these member fields, and lock should released before calling AModule::update(). */ void Workspaces::doUpdate() { std::unique_lock lock(m_mutex); removeWorkspacesToRemove(); createWorkspacesToCreate(); updateWorkspaceStates(); updateWindowCount(); sortWorkspaces(); bool anyWindowCreated = updateWindowsToCreate(); if (anyWindowCreated) { dp.emit(); } } void Workspaces::extendOrphans(int workspaceId, Json::Value const &clientsJson) { spdlog::trace("Extending orphans with workspace {}", workspaceId); 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 windowReprKey; if (windowRewriteConfigUsesTitle()) { windowReprKey = fmt::format("class<{}> title<{}>", window_class, window_title); } else { windowReprKey = fmt::format("class<{}>", window_class); } auto const rewriteRule = m_windowRewriteRules.get(windowReprKey); return fmt::format(fmt::runtime(rewriteRule), fmt::arg("class", window_class), fmt::arg("title", window_title)); } std::vector Workspaces::getVisibleWorkspaces() { std::vector visibleWorkspaces; auto monitors = IPC::inst().getSocket1JsonReply("monitors"); for (const auto &monitor : monitors) { auto ws = monitor["activeWorkspace"]; if (ws.isObject() && ws["name"].isString()) { visibleWorkspaces.push_back(ws["name"].asString()); } auto sws = monitor["specialWorkspace"]; auto name = sws["name"].asString(); if (sws.isObject() && sws["name"].isString() && !name.empty()) { visibleWorkspaces.push_back(!name.starts_with("special:") ? name : name.substr(8)); } } return visibleWorkspaces; } 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) { m_workspacesToRemove.push_back(workspace->name()); } // get all current workspaces auto const workspacesJson = m_ipc.getSocket1JsonReply("workspaces"); auto const clientsJson = m_ipc.getSocket1JsonReply("clients"); for (Json::Value workspaceJson : workspacesJson) { std::string workspaceName = workspaceJson["name"].asString(); if ((allOutputs() || m_bar.output->name == workspaceJson["monitor"].asString()) && (!workspaceName.starts_with("special") || showSpecial()) && !isWorkspaceIgnored(workspaceName)) { m_workspacesToCreate.emplace_back(workspaceJson, clientsJson); } else { extendOrphans(workspaceJson["id"].asInt(), clientsJson); } } spdlog::debug("Initializing persistent workspaces"); if (m_persistentWorkspaceConfig.isObject()) { // a persistent workspace config is defined, so use that instead of workspace rules loadPersistentWorkspacesFromConfig(clientsJson); } // load Hyprland's workspace rules loadPersistentWorkspacesFromWorkspaceRules(clientsJson); } 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. // See hyprwm/Hyprland#3424 for more info. return workspace_name.find("special:special:") != std::string::npos; } bool Workspaces::isWorkspaceIgnored(std::string const &name) { for (auto &rule : m_ignoreWorkspaces) { if (std::regex_match(name, rule)) { return true; break; } } return false; } void Workspaces::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::find(keys.begin(), keys.end(), currentMonitor) != keys.end(); 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]; spdlog::trace("Parsing persistent workspace config: {} => {}", key, value.toStyledString()); if (value.isInt()) { // value is a number => create that many workspaces for this monitor if (canCreate) { int amount = value.asInt(); spdlog::debug("Creating {} persistent workspaces for monitor {}", amount, currentMonitor); for (int i = 0; i < amount; i++) { persistentWorkspacesToCreate.emplace_back(std::to_string(m_monitorId * amount + i + 1)); } } } 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())); } } } else { // key is the workspace and value is array of monitors to create on for (const Json::Value &monitor : value) { if (monitor.isString() && monitor.asString() == currentMonitor) { persistentWorkspacesToCreate.emplace_back(currentMonitor); break; } } } } else { // this workspace should be displayed on all monitors persistentWorkspacesToCreate.emplace_back(key); } } 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) { spdlog::info("Loading persistent workspaces from Hyprland workspace rules"); auto const workspaceRules = m_ipc.getSocket1JsonReply("workspacerules"); for (Json::Value const &rule : workspaceRules) { if (!rule["workspaceString"].isString()) { spdlog::warn("Workspace rules: invalid workspaceString, skipping: {}", rule); continue; } if (!rule["persistent"].asBool()) { continue; } auto const &workspace = rule.isMember("defaultName") ? rule["defaultName"].asString() : rule["workspaceString"].asString(); auto const &monitor = rule["monitor"].asString(); // create this workspace persistently if: // 1. the allOutputs config option is enabled // 2. the rule's monitor is the current monitor // 3. no monitor is specified in the rule => assume it needs to be persistent on every monitor if (allOutputs() || m_bar.output->name == monitor || monitor.empty()) { // => persistent workspace should be shown on this monitor auto workspaceData = createMonitorWorkspaceData(workspace, m_bar.output->name); workspaceData["persistent-rule"] = true; m_workspacesToCreate.emplace_back(workspaceData, clientsJson); } else { m_workspacesToRemove.emplace_back(workspace); } } } 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); if (eventName == "workspace") { onWorkspaceActivated(payload); } else if (eventName == "activespecial") { onSpecialWorkspaceActivated(payload); } else if (eventName == "destroyworkspace") { onWorkspaceDestroyed(payload); } else if (eventName == "createworkspace") { onWorkspaceCreated(payload); } else if (eventName == "focusedmon") { onMonitorFocused(payload); } else if (eventName == "moveworkspace") { onWorkspaceMoved(payload); } else if (eventName == "openwindow") { onWindowOpened(payload); } else if (eventName == "closewindow") { onWindowClosed(payload); } else if (eventName == "movewindow") { onWindowMoved(payload); } else if (eventName == "urgent") { setUrgentWorkspace(payload); } else if (eventName == "renameworkspace") { onWorkspaceRenamed(payload); } else if (eventName == "windowtitle") { onWindowTitleEvent(payload); } else if (eventName == "configreloaded") { onConfigReloaded(); } dp.emit(); } void Workspaces::onWorkspaceActivated(std::string const &payload) { m_activeWorkspaceName = 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) { if (!isDoubleSpecial(payload)) { m_workspacesToRemove.push_back(payload); } } void Workspaces::onWorkspaceCreated(std::string const &workspaceName, Json::Value const &clientsData) { spdlog::debug("Workspace created: {}", workspaceName); auto const workspacesJson = m_ipc.getSocket1JsonReply("workspaces"); if (!isWorkspaceIgnored(workspaceName)) { auto const workspaceRules = m_ipc.getSocket1JsonReply("workspacerules"); for (Json::Value workspaceJson : workspacesJson) { std::string name = workspaceJson["name"].asString(); if (name == workspaceName) { if ((allOutputs() || m_bar.output->name == workspaceJson["monitor"].asString()) && (showSpecial() || !name.starts_with("special")) && !isDoubleSpecial(workspaceName)) { for (Json::Value const &rule : workspaceRules) { auto ruleWorkspaceName = rule.isMember("defaultName") ? rule["defaultName"].asString() : rule["workspaceString"].asString(); if (ruleWorkspaceName == workspaceName) { workspaceJson["persistent-rule"] = rule["persistent"].asBool(); break; } } m_workspacesToCreate.emplace_back(workspaceJson, clientsData); break; } } else { extendOrphans(workspaceJson["id"].asInt(), clientsData); } } } else { spdlog::trace("Not creating workspace because it is ignored: {}", workspaceName); } } void Workspaces::onWorkspaceMoved(std::string const &payload) { spdlog::debug("Workspace moved: {}", payload); // Update active workspace m_activeWorkspaceName = (m_ipc.getSocket1JsonReply("activeworkspace"))["name"].asString(); if (allOutputs()) return; std::string workspaceName = payload.substr(0, payload.find(',')); std::string monitorName = payload.substr(payload.find(',') + 1); if (m_bar.output->name == monitorName) { Json::Value clientsData = m_ipc.getSocket1JsonReply("clients"); onWorkspaceCreated(workspaceName, clientsData); } else { spdlog::debug("Removing workspace because it was moved to another monitor: {}"); onWorkspaceDestroyed(workspaceName); } } void Workspaces::onWorkspaceRenamed(std::string const &payload) { spdlog::debug("Workspace renamed: {}", payload); std::string workspaceIdStr = payload.substr(0, payload.find(',')); int workspaceId = workspaceIdStr == "special" ? -99 : std::stoi(workspaceIdStr); std::string newName = payload.substr(payload.find(',') + 1); for (auto &workspace : m_workspaces) { if (workspace->id() == workspaceId) { if (workspace->name() == m_activeWorkspaceName) { m_activeWorkspaceName = newName; } workspace->setName(newName); break; } } sortWorkspaces(); } void Workspaces::onMonitorFocused(std::string const &payload) { spdlog::trace("Monitor focused: {}", payload); m_activeWorkspaceName = payload.substr(payload.find(',') + 1); for (Json::Value &monitor : m_ipc.getSocket1JsonReply("monitors")) { if (monitor["name"].asString() == payload.substr(0, payload.find(','))) { auto name = monitor["specialWorkspace"]["name"].asString(); m_activeSpecialWorkspaceName = !name.starts_with("special:") ? name : name.substr(8); } } } 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); lastCommaIdx = nextCommaIdx; nextCommaIdx = payload.find(',', nextCommaIdx + 1); std::string workspaceName = payload.substr(lastCommaIdx + 1, nextCommaIdx - lastCommaIdx - 1); lastCommaIdx = nextCommaIdx; nextCommaIdx = payload.find(',', nextCommaIdx + 1); std::string windowClass = payload.substr(lastCommaIdx + 1, nextCommaIdx - lastCommaIdx - 1); std::string windowTitle = payload.substr(nextCommaIdx + 1, payload.length() - nextCommaIdx); m_windowsToCreate.emplace_back(workspaceName, windowAddress, windowClass, windowTitle); } void Workspaces::onWindowClosed(std::string const &addr) { spdlog::trace("Window closed: {}", addr); updateWindowCount(); for (auto &workspace : m_workspaces) { if (workspace->closeWindow(addr)) { break; } } } void Workspaces::onWindowMoved(std::string const &payload) { spdlog::trace("Window moved: {}", payload); updateWindowCount(); size_t lastCommaIdx = 0; size_t nextCommaIdx = payload.find(','); std::string windowAddress = payload.substr(lastCommaIdx, nextCommaIdx - lastCommaIdx); std::string workspaceName = payload.substr(nextCommaIdx + 1, payload.length() - nextCommaIdx); std::string windowRepr; // If the window was still queued to be created, just change its destination // and exit for (auto &window : m_windowsToCreate) { if (window.getAddress() == windowAddress) { window.moveToWorksace(workspaceName); return; } } // Take the window's representation from the old workspace... for (auto &workspace : m_workspaces) { if (auto windowAddr = workspace->closeWindow(windowAddress); windowAddr != std::nullopt) { windowRepr = windowAddr.value(); break; } } // ...if it was empty, check if the window is an orphan... if (windowRepr.empty() && m_orphanWindowMap.contains(windowAddress)) { windowRepr = m_orphanWindowMap[windowAddress]; } // ...and then add it to the new workspace if (!windowRepr.empty()) { m_windowsToCreate.emplace_back(workspaceName, windowAddress, windowRepr); } } void Workspaces::onWindowTitleEvent(std::string const &payload) { spdlog::trace("Window title changed: {}", payload); std::optional> inserter; // If the window was an orphan, rename it at the orphan's vector if (m_orphanWindowMap.contains(payload)) { inserter = [this](WindowCreationPayload wcp) { this->registerOrphanWindow(std::move(wcp)); }; } else { auto windowWorkspace = std::find_if(m_workspaces.begin(), m_workspaces.end(), [payload](auto &workspace) { return workspace->containsWindow(payload); }); // If the window exists on a workspace, rename it at the workspace's window // map if (windowWorkspace != m_workspaces.end()) { inserter = [windowWorkspace](WindowCreationPayload wcp) { (*windowWorkspace)->insertWindow(std::move(wcp)); }; } else { auto queuedWindow = std::find_if( m_windowsToCreate.begin(), m_windowsToCreate.end(), [payload](auto &windowPayload) { return windowPayload.getAddress() == payload; }); // If the window was queued, rename it in the queue if (queuedWindow != m_windowsToCreate.end()) { inserter = [queuedWindow](WindowCreationPayload wcp) { *queuedWindow = std::move(wcp); }; } } } if (inserter.has_value()) { Json::Value clientsData = m_ipc.getSocket1JsonReply("clients"); std::string jsonWindowAddress = fmt::format("0x{}", payload); auto client = std::find_if(clientsData.begin(), clientsData.end(), [jsonWindowAddress](auto &client) { return client["address"].asString() == jsonWindowAddress; }); if (!client->empty()) { (*inserter)({*client}); } } } 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; if (m_withIcon && m_iconsMap.empty()) { populateIconsMap(config["format-icons"]); } populateBoolConfig(config, "all-outputs", m_allOutputs); populateBoolConfig(config, "show-special", m_showSpecial); populateBoolConfig(config, "special-visible-only", m_specialVisibleOnly); populateBoolConfig(config, "active-only", m_activeOnly); populateBoolConfig(config, "move-to-monitor", m_moveToMonitor); m_persistentWorkspaceConfig = config.get("persistent-workspaces", Json::Value()); populateSortByConfig(config); populateIgnoreWorkspacesConfig(config); populateFormatWindowSeparatorConfig(config); populateWindowRewriteConfig(config); } 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) -> void { 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"]; if (configSortBy.isString()) { auto sortByStr = configSortBy.asString(); try { m_sortBy = m_enumParser.parseStringToEnum(sortByStr, m_sortMap); } catch (const std::invalid_argument &e) { m_sortBy = SortMethod::DEFAULT; spdlog::warn( "Invalid string representation for sort-by. Falling back to default sort method."); } } } auto Workspaces::populateIgnoreWorkspacesConfig(const Json::Value &config) -> void { auto ignoreWorkspaces = config["ignore-workspaces"]; if (ignoreWorkspaces.isArray()) { for (const auto &workspaceRegex : ignoreWorkspaces) { if (workspaceRegex.isString()) { std::string ruleString = workspaceRegex.asString(); try { const std::regex rule{ruleString, std::regex_constants::icase}; m_ignoreWorkspaces.emplace_back(rule); } catch (const std::regex_error &e) { spdlog::error("Invalid rule {}: {}", ruleString, e.what()); } } else { spdlog::error("Not a string: '{}'", workspaceRegex); } } } } 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"]; 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"]; std::string windowRewriteDefault = windowRewriteDefaultConfig.isString() ? windowRewriteDefaultConfig.asString() : "?"; m_windowRewriteRules = util::RegexCollection( windowRewrite, windowRewriteDefault, [this](std::string &window_rule) { return windowRewritePriorityFunction(window_rule); }); } void Workspaces::registerOrphanWindow(WindowCreationPayload create_window_payload) { if (!create_window_payload.isEmpty(*this)) { m_orphanWindowMap[create_window_payload.getAddress()] = create_window_payload.repr(*this); } } auto Workspaces::registerIpc() -> void { m_ipc.registerForIPC("workspace", this); m_ipc.registerForIPC("activespecial", this); m_ipc.registerForIPC("createworkspace", this); m_ipc.registerForIPC("destroyworkspace", this); m_ipc.registerForIPC("focusedmon", this); m_ipc.registerForIPC("moveworkspace", this); m_ipc.registerForIPC("renameworkspace", this); m_ipc.registerForIPC("openwindow", this); m_ipc.registerForIPC("closewindow", this); m_ipc.registerForIPC("movewindow", this); m_ipc.registerForIPC("urgent", this); m_ipc.registerForIPC("configreloaded", this); if (windowRewriteConfigUsesTitle()) { spdlog::info( "Registering for Hyprland's 'windowtitle' events because a user-defined window " "rewrite rule uses the 'title' field."); m_ipc.registerForIPC("windowtitle", this); } } void Workspaces::removeWorkspacesToRemove() { for (const auto &workspaceName : m_workspacesToRemove) { removeWorkspace(workspaceName); } m_workspacesToRemove.clear(); } void Workspaces::removeWorkspace(std::string const &name) { spdlog::debug("Removing workspace {}", name); auto workspace = std::find_if(m_workspaces.begin(), m_workspaces.end(), [&](std::unique_ptr &x) { return (name.starts_with("special:") && name.substr(8) == x->name()) || name == x->name(); }); if (workspace == m_workspaces.end()) { // happens when a workspace on another monitor is destroyed return; } if ((*workspace)->isPersistentConfig()) { spdlog::trace("Not removing config persistent workspace {}", name); return; } m_box.remove(workspace->get()->button()); m_workspaces.erase(workspace); } void Workspaces::setCurrentMonitorId() { // get monitor ID from name (used by persistent workspaces) m_monitorId = 0; auto monitors = m_ipc.getSocket1JsonReply("monitors"); auto currentMonitor = std::find_if( monitors.begin(), monitors.end(), [this](const Json::Value &m) { return m["name"].asString() == m_bar.output->name; }); if (currentMonitor == monitors.end()) { spdlog::error("Monitor '{}' does not have an ID? Using 0", m_bar.output->name); } else { m_monitorId = (*currentMonitor)["id"].asInt(); spdlog::trace("Current monitor ID: {}", m_monitorId); } } void Workspaces::sortWorkspaces() { std::sort(m_workspaces.begin(), m_workspaces.end(), [&](std::unique_ptr &a, std::unique_ptr &b) { // Helper comparisons auto isIdLess = a->id() < b->id(); auto isNameLess = a->name() < b->name(); switch (m_sortBy) { case SortMethod::ID: return isIdLess; case SortMethod::NAME: return isNameLess; case SortMethod::NUMBER: try { return std::stoi(a->name()) < std::stoi(b->name()); } catch (const std::invalid_argument &) { // Handle the exception if necessary. break; } case SortMethod::DEFAULT: default: // Handle the default case here. // normal -> named persistent -> named -> special -> named special // both normal (includes numbered persistent) => sort by ID if (a->id() > 0 && b->id() > 0) { return isIdLess; } // one normal, one special => normal first if ((a->isSpecial()) ^ (b->isSpecial())) { return b->isSpecial(); } // only one normal, one named if ((a->id() > 0) ^ (b->id() > 0)) { return a->id() > 0; } // both special if (a->isSpecial() && b->isSpecial()) { // if one is -99 => put it last if (a->id() == -99 || b->id() == -99) { return b->id() == -99; } // both are 0 (not yet named persistents) / named specials (-98 <= ID <= -1) return isNameLess; } // sort non-special named workspaces by name (ID <= -1377) return isNameLess; break; } // Return a default value if none of the cases match. return isNameLess; // You can adjust this to your specific needs. }); 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) { const Json::Value clientsJson = m_ipc.getSocket1JsonReply("clients"); int workspaceId = -1; for (Json::Value clientJson : clientsJson) { if (clientJson["address"].asString().ends_with(windowaddress)) { workspaceId = clientJson["workspace"]["id"].asInt(); break; } } auto workspace = std::find_if(m_workspaces.begin(), m_workspaces.end(), [workspaceId](std::unique_ptr &x) { return x->id() == workspaceId; }); if (workspace != m_workspaces.end()) { workspace->get()->setUrgent(); } } auto Workspaces::update() -> void { doUpdate(); AModule::update(); } void Workspaces::updateWindowCount() { const Json::Value workspacesJson = m_ipc.getSocket1JsonReply("workspaces"); for (auto &workspace : m_workspaces) { auto workspaceJson = std::find_if(workspacesJson.begin(), workspacesJson.end(), [&](Json::Value const &x) { return x["name"].asString() == workspace->name() || (workspace->isSpecial() && x["name"].asString() == "special:" + workspace->name()); }); uint32_t count = 0; if (workspaceJson != workspacesJson.end()) { try { count = (*workspaceJson)["windows"].asUInt(); } catch (const std::exception &e) { spdlog::error("Failed to update window count: {}", e.what()); } } workspace->setWindows(count); } } bool Workspaces::updateWindowsToCreate() { bool anyWindowCreated = false; std::vector notCreated; for (auto &windowPayload : m_windowsToCreate) { bool created = false; for (auto &workspace : m_workspaces) { if (workspace->onWindowOpened(windowPayload)) { created = true; anyWindowCreated = true; break; } } if (!created) { static auto const WINDOW_CREATION_TIMEOUT = 2; if (windowPayload.incrementTimeSpentUncreated() < WINDOW_CREATION_TIMEOUT) { notCreated.push_back(windowPayload); } else { registerOrphanWindow(windowPayload); } } } m_windowsToCreate.clear(); m_windowsToCreate = notCreated; return anyWindowCreated; } void Workspaces::updateWorkspaceStates() { const std::vector visibleWorkspaces = getVisibleWorkspaces(); auto updatedWorkspaces = m_ipc.getSocket1JsonReply("workspaces"); for (auto &workspace : m_workspaces) { workspace->setActive(workspace->name() == m_activeWorkspaceName || workspace->name() == m_activeSpecialWorkspaceName); if (workspace->isActive() && workspace->isUrgent()) { workspace->setUrgent(false); } workspace->setVisible(std::find(visibleWorkspaces.begin(), visibleWorkspaces.end(), workspace->name()) != visibleWorkspaces.end()); std::string &workspaceIcon = m_iconsMap[""]; if (m_withIcon) { workspaceIcon = workspace->selectIcon(m_iconsMap); } auto updatedWorkspace = std::find_if( updatedWorkspaces.begin(), updatedWorkspaces.end(), [&workspace](const auto &w) { auto wNameRaw = w["name"].asString(); auto wName = wNameRaw.starts_with("special:") ? wNameRaw.substr(8) : wNameRaw; return wName == workspace->name(); }); if (updatedWorkspace != updatedWorkspaces.end()) { workspace->setOutput((*updatedWorkspace)["monitor"].asString()); } workspace->update(m_format, workspaceIcon); } } 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; bool const hasClass = window_rule.find("class") != std::string::npos; if (hasTitle && hasClass) { m_anyWindowRewriteRuleUsesTitle = true; return 3; } if (hasTitle) { m_anyWindowRewriteRuleUsesTitle = true; return 2; } if (hasClass) { return 1; } return 0; } } // namespace waybar::modules::hyprland waybar-0.12.0/src/modules/idle_inhibitor.cpp000066400000000000000000000076041475603165300210270ustar00rootroot00000000000000#include "modules/idle_inhibitor.hpp" #include "idle-inhibit-unstable-v1-client-protocol.h" #include "util/command.hpp" std::list waybar::modules::IdleInhibitor::modules; bool waybar::modules::IdleInhibitor::status = false; waybar::modules::IdleInhibitor::IdleInhibitor(const std::string& id, const Bar& bar, const Json::Value& config) : ALabel(config, "idle_inhibitor", id, "{status}", 0, false, true), bar_(bar), idle_inhibitor_(nullptr), pid_(-1) { if (waybar::Client::inst()->idle_inhibit_manager == nullptr) { throw std::runtime_error("idle-inhibit not available"); } if (waybar::modules::IdleInhibitor::modules.empty() && config_["start-activated"].isBool() && config_["start-activated"].asBool() != status) { toggleStatus(); } event_box_.add_events(Gdk::BUTTON_PRESS_MASK); event_box_.signal_button_press_event().connect( sigc::mem_fun(*this, &IdleInhibitor::handleToggle)); // Add this to the modules list waybar::modules::IdleInhibitor::modules.push_back(this); dp.emit(); } waybar::modules::IdleInhibitor::~IdleInhibitor() { if (idle_inhibitor_ != nullptr) { zwp_idle_inhibitor_v1_destroy(idle_inhibitor_); idle_inhibitor_ = nullptr; } // Remove this from the modules list waybar::modules::IdleInhibitor::modules.remove(this); if (pid_ != -1) { kill(-pid_, 9); pid_ = -1; } } auto waybar::modules::IdleInhibitor::update() -> void { // Check status if (status) { label_.get_style_context()->remove_class("deactivated"); if (idle_inhibitor_ == nullptr) { idle_inhibitor_ = zwp_idle_inhibit_manager_v1_create_inhibitor( waybar::Client::inst()->idle_inhibit_manager, bar_.surface); } } else { label_.get_style_context()->remove_class("activated"); if (idle_inhibitor_ != nullptr) { zwp_idle_inhibitor_v1_destroy(idle_inhibitor_); idle_inhibitor_ = nullptr; } } std::string status_text = status ? "activated" : "deactivated"; label_.set_markup(fmt::format(fmt::runtime(format_), fmt::arg("status", status_text), fmt::arg("icon", getIcon(0, status_text)))); label_.get_style_context()->add_class(status_text); if (tooltipEnabled()) { auto config = config_[status ? "tooltip-format-activated" : "tooltip-format-deactivated"]; auto tooltip_format = config.isString() ? config.asString() : "{status}"; label_.set_tooltip_markup(fmt::format(fmt::runtime(tooltip_format), fmt::arg("status", status_text), fmt::arg("icon", getIcon(0, status_text)))); } // Call parent update ALabel::update(); } void waybar::modules::IdleInhibitor::toggleStatus() { status = !status; if (timeout_.connected()) { /* cancel any already active timeout handler */ timeout_.disconnect(); } if (status && config_["timeout"].isNumeric()) { auto timeoutMins = config_["timeout"].asDouble(); int timeoutSecs = timeoutMins * 60; timeout_ = Glib::signal_timeout().connect_seconds( []() { /* intentionally not tied to a module instance lifetime * as the output with `this` can be disconnected */ spdlog::info("deactivating idle_inhibitor by timeout"); status = false; for (auto const& module : waybar::modules::IdleInhibitor::modules) { module->update(); } /* disconnect */ return false; }, timeoutSecs); } } bool waybar::modules::IdleInhibitor::handleToggle(GdkEventButton* const& e) { if (e->button == 1) { toggleStatus(); // Make all other idle inhibitor modules update for (auto const& module : waybar::modules::IdleInhibitor::modules) { if (module != this) { module->update(); } } } ALabel::handleToggle(e); return true; } waybar-0.12.0/src/modules/image.cpp000066400000000000000000000043511475603165300171210ustar00rootroot00000000000000#include "modules/image.hpp" waybar::modules::Image::Image(const std::string& id, const Json::Value& config) : AModule(config, "image", id), box_(Gtk::ORIENTATION_HORIZONTAL, 0) { box_.pack_start(image_); box_.set_name("image"); if (!id.empty()) { box_.get_style_context()->add_class(id); } box_.get_style_context()->add_class(MODULE_CLASS); event_box_.add(box_); dp.emit(); size_ = config["size"].asInt(); interval_ = config_["interval"].asInt(); 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); }; } void waybar::modules::Image::refresh(int sig) { if (sig == SIGRTMIN + config_["signal"].asInt()) { thread_.wake_up(); } } auto waybar::modules::Image::update() -> void { if (config_["path"].isString()) { path_ = config_["path"].asString(); } else if (config_["exec"].isString()) { output_ = util::command::exec(config_["exec"].asString(), ""); parseOutputRaw(); } else { path_ = ""; } if (Glib::file_test(path_, Glib::FILE_TEST_EXISTS)) { Glib::RefPtr pixbuf; int scaled_icon_size = size_ * image_.get_scale_factor(); pixbuf = Gdk::Pixbuf::create_from_file(path_, 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_.show(); if (tooltipEnabled() && !tooltip_.empty()) { if (box_.get_tooltip_markup() != tooltip_) { box_.set_tooltip_markup(tooltip_); } } box_.get_style_context()->remove_class("empty"); } else { image_.clear(); image_.hide(); box_.get_style_context()->add_class("empty"); } AModule::update(); } void waybar::modules::Image::parseOutputRaw() { std::istringstream output(output_.out); std::string line; int i = 0; while (getline(output, line)) { if (i == 0) { path_ = line; } else if (i == 1) { tooltip_ = line; } else { break; } i++; } } waybar-0.12.0/src/modules/inhibitor.cpp000066400000000000000000000104221475603165300200220ustar00rootroot00000000000000#include "modules/inhibitor.hpp" #include #include #include namespace { using DBus = std::unique_ptr; auto dbus() -> DBus { GError* error = nullptr; GDBusConnection* connection = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error); if (error) { spdlog::error("g_bus_get_sync() failed: {}", error->message); g_error_free(error); connection = nullptr; } auto destructor = [](GDBusConnection* connection) { GError* error = nullptr; g_dbus_connection_close_sync(connection, nullptr, &error); if (error) { spdlog::error("g_bus_connection_close_sync failed(): {}", error->message); g_error_free(error); } }; return DBus{connection, destructor}; } auto getLocks(const DBus& bus, const std::string& inhibitors) -> int { GError* error = nullptr; GUnixFDList* fd_list; int handle; auto reply = g_dbus_connection_call_with_unix_fd_list_sync( bus.get(), "org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", "Inhibit", g_variant_new("(ssss)", inhibitors.c_str(), "waybar", "Asked by user", "block"), G_VARIANT_TYPE("(h)"), G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &fd_list, nullptr, &error); if (error) { spdlog::error("g_dbus_connection_call_with_unix_fd_list_sync() failed: {}", error->message); g_error_free(error); handle = -1; } else { gint index; g_variant_get(reply, "(h)", &index); g_variant_unref(reply); handle = g_unix_fd_list_get(fd_list, index, nullptr); g_object_unref(fd_list); } return handle; } auto checkInhibitor(const std::string& inhibitor) -> const std::string& { static const auto inhibitors = std::array{"idle", "shutdown", "sleep", "handle-power-key", "handle-suspend-key", "handle-hibernate-key", "handle-lid-switch"}; if (std::find(inhibitors.begin(), inhibitors.end(), inhibitor) == inhibitors.end()) { throw std::runtime_error("invalid logind inhibitor " + inhibitor); } return inhibitor; } auto getInhibitors(const Json::Value& config) -> std::string { std::string inhibitors = "idle"; if (config["what"].empty()) { return inhibitors; } if (config["what"].isString()) { return checkInhibitor(config["what"].asString()); } 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()); } return inhibitors; } return inhibitors; } } // namespace namespace waybar::modules { Inhibitor::Inhibitor(const std::string& id, const Bar& bar, const Json::Value& config) : ALabel(config, "inhibitor", id, "{status}", true), dbus_(::dbus()), inhibitors_(::getInhibitors(config)) { event_box_.add_events(Gdk::BUTTON_PRESS_MASK); event_box_.signal_button_press_event().connect(sigc::mem_fun(*this, &Inhibitor::handleToggle)); dp.emit(); } Inhibitor::~Inhibitor() { if (handle_ != -1) { ::close(handle_); } } auto Inhibitor::activated() -> bool { return handle_ != -1; } auto Inhibitor::update() -> void { std::string status_text = activated() ? "activated" : "deactivated"; label_.get_style_context()->remove_class(activated() ? "deactivated" : "activated"); label_.set_markup(fmt::format(fmt::runtime(format_), fmt::arg("status", status_text), fmt::arg("icon", getIcon(0, status_text)))); label_.get_style_context()->add_class(status_text); if (tooltipEnabled()) { label_.set_tooltip_text(status_text); } return ALabel::update(); } auto Inhibitor::handleToggle(GdkEventButton* const& e) -> bool { if (e->button == 1) { if (activated()) { ::close(handle_); handle_ = -1; } else { handle_ = ::getLocks(dbus_, inhibitors_); if (handle_ == -1) { spdlog::error("cannot get inhibitor locks"); } } } return ALabel::handleToggle(e); } } // namespace waybar::modules waybar-0.12.0/src/modules/jack.cpp000066400000000000000000000070731475603165300167530ustar00rootroot00000000000000#include "modules/jack.hpp" namespace waybar::modules { JACK::JACK(const std::string &id, const Json::Value &config) : ALabel(config, "jack", id, "{load}%", 1) { running_ = false; client_ = NULL; thread_ = [this] { dp.emit(); thread_.sleep_for(interval_); }; } std::string JACK::JACKState() { std::lock_guard lock(mutex_); if (running_) { load_ = jack_cpu_load(client_); return state_; } xruns_ = 0; load_ = 0; bufsize_ = 0; samplerate_ = 0; if (client_) { jack_client_close(client_); client_ = NULL; } client_ = jack_client_open("waybar", JackNoStartServer, NULL); if (!client_) return "disconnected"; if (config_["realtime"].isBool() && !config_["realtime"].asBool()) { pthread_t jack_thread = jack_client_thread_id(client_); jack_drop_real_time_scheduling(jack_thread); } bufsize_ = jack_get_buffer_size(client_); samplerate_ = jack_get_sample_rate(client_); jack_set_sample_rate_callback(client_, sampleRateCallback, this); jack_set_buffer_size_callback(client_, bufSizeCallback, this); jack_set_xrun_callback(client_, xrunCallback, this); jack_on_shutdown(client_, shutdownCallback, this); if (jack_activate(client_)) return "disconnected"; running_ = true; return "connected"; } auto JACK::update() -> void { std::string format; std::string state = JACKState(); float latency = 1000 * (float)bufsize_ / (float)samplerate_; if (label_.get_style_context()->has_class("xrun")) { label_.get_style_context()->remove_class("xrun"); state = "connected"; } if (label_.get_style_context()->has_class(state_)) label_.get_style_context()->remove_class(state_); label_.get_style_context()->add_class(state); state_ = state; if (config_["format-" + state].isString()) { format = config_["format-" + state].asString(); } else if (config_["format"].isString()) { format = config_["format"].asString(); } else format = "{load}%"; label_.set_markup(fmt::format(fmt::runtime(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_))); 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( 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_))); } // Call parent update ALabel::update(); } int JACK::bufSize(jack_nframes_t size) { bufsize_ = size; return 0; } int JACK::sampleRate(jack_nframes_t rate) { samplerate_ = rate; return 0; } int JACK::xrun() { xruns_ += 1; state_ = "xrun"; return 0; } void JACK::shutdown() { std::lock_guard lock(mutex_); running_ = false; } } // namespace waybar::modules 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 xrunCallback(void *obj) { return static_cast(obj)->xrun(); } void shutdownCallback(void *obj) { return static_cast(obj)->shutdown(); } waybar-0.12.0/src/modules/keyboard_state.cpp000066400000000000000000000252321475603165300210400ustar00rootroot00000000000000#include "modules/keyboard_state.hpp" #include #include #include #include extern "C" { #include #include #include #include #include #include #include #include } class errno_error : public std::runtime_error { public: int code; errno_error(int code, const std::string& msg) : std::runtime_error(getErrorMsg(code, msg.c_str())), code(code) {} errno_error(int code, const char* msg) : std::runtime_error(getErrorMsg(code, msg)), code(code) {} private: static auto getErrorMsg(int err, const char* msg) -> std::string { std::string error_msg{msg}; error_msg += ": "; #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 32) // strerrorname_np gets the error code's name; it's nice to have, but it's a recent GNU // extension const auto errno_name = strerrorname_np(err); error_msg += errno_name; error_msg += " "; #endif const auto errno_str = strerror(err); error_msg += errno_str; return error_msg; } }; auto openFile(const std::string& path, int flags) -> int { int fd = open(path.c_str(), flags); if (fd < 0) { if (errno == EACCES) { throw errno_error(errno, "Can't open " + path + " (are you in the input group?)"); } else { throw errno_error(errno, "Can't open " + path); } } return fd; } auto closeFile(int fd) -> void { int res = close(fd); if (res < 0) { throw errno_error(errno, "Can't close file"); } } auto openDevice(int fd) -> libevdev* { libevdev* dev; int err = libevdev_new_from_fd(fd, &dev); if (err < 0) { throw errno_error(-err, "Can't create libevdev device"); } return dev; } auto supportsLockStates(const libevdev* dev) -> bool { return libevdev_has_event_type(dev, EV_LED) && libevdev_has_event_code(dev, EV_LED, LED_NUML) && libevdev_has_event_code(dev, EV_LED, LED_CAPSL) && libevdev_has_event_code(dev, EV_LED, LED_SCROLLL); } waybar::modules::KeyboardState::KeyboardState(const std::string& id, const Bar& bar, const Json::Value& config) : AModule(config, "keyboard-state", id, false, !config["disable-scroll"].asBool()), box_(bar.orientation, 0), numlock_label_(""), capslock_label_(""), numlock_format_(config_["format"].isString() ? config_["format"].asString() : config_["format"]["numlock"].isString() ? config_["format"]["numlock"].asString() : "{name} {icon}"), capslock_format_(config_["format"].isString() ? config_["format"].asString() : config_["format"]["capslock"].isString() ? config_["format"]["capslock"].asString() : "{name} {icon}"), scrolllock_format_(config_["format"].isString() ? config_["format"].asString() : config_["format"]["scrolllock"].isString() ? config_["format"]["scrolllock"].asString() : "{name} {icon}"), interval_( std::chrono::seconds(config_["interval"].isUInt() ? config_["interval"].asUInt() : 1)), icon_locked_(config_["format-icons"]["locked"].isString() ? config_["format-icons"]["locked"].asString() : "locked"), icon_unlocked_(config_["format-icons"]["unlocked"].isString() ? config_["format-icons"]["unlocked"].asString() : "unlocked"), devices_path_("/dev/input/"), libinput_(nullptr), libinput_devices_({}) { static struct libinput_interface interface = { [](const char* path, int flags, void* user_data) { return open(path, flags); }, [](int fd, void* user_data) { close(fd); }}; if (config_["interval"].isUInt()) { spdlog::warn("keyboard-state: interval is deprecated"); } libinput_ = libinput_path_create_context(&interface, NULL); box_.set_name("keyboard-state"); if (config_["numlock"].asBool()) { numlock_label_.get_style_context()->add_class("numlock"); box_.pack_end(numlock_label_, false, false, 0); } if (config_["capslock"].asBool()) { capslock_label_.get_style_context()->add_class("capslock"); box_.pack_end(capslock_label_, false, false, 0); } if (config_["scrolllock"].asBool()) { scrolllock_label_.get_style_context()->add_class("scrolllock"); box_.pack_end(scrolllock_label_, false, false, 0); } if (!id.empty()) { box_.get_style_context()->add_class(id); } box_.get_style_context()->add_class(MODULE_CLASS); event_box_.add(box_); if (config_["device-path"].isString()) { std::string dev_path = config_["device-path"].asString(); tryAddDevice(dev_path); if (libinput_devices_.empty()) { spdlog::error("keyboard-state: Cannot find device {}", dev_path); } } auto keys = config_["binding-keys"]; if (keys.isArray()) { for (const auto& key : keys) { if (key.isInt()) { binding_keys.insert(key.asInt()); } else { spdlog::warn("Cannot read key binding {} as int.", key.asString()); } } } else { binding_keys.insert(KEY_CAPSLOCK); binding_keys.insert(KEY_NUMLOCK); binding_keys.insert(KEY_SCROLLLOCK); } DIR* dev_dir = opendir(devices_path_.c_str()); if (dev_dir == nullptr) { throw errno_error(errno, "Failed to open " + devices_path_); } dirent* ep; while ((ep = readdir(dev_dir))) { if (ep->d_type == DT_DIR) continue; std::string dev_path = devices_path_ + ep->d_name; tryAddDevice(dev_path); } if (libinput_devices_.empty()) { throw errno_error(errno, "Failed to find keyboard device"); } libinput_thread_ = [this] { dp.emit(); while (1) { struct pollfd fd = {libinput_get_fd(libinput_), POLLIN, 0}; poll(&fd, 1, -1); libinput_dispatch(libinput_); struct libinput_event* event; while ((event = libinput_get_event(libinput_))) { auto type = libinput_event_get_type(event); if (type == LIBINPUT_EVENT_KEYBOARD_KEY) { auto keyboard_event = libinput_event_get_keyboard_event(event); auto state = libinput_event_keyboard_get_key_state(keyboard_event); if (state == LIBINPUT_KEY_STATE_RELEASED) { uint32_t key = libinput_event_keyboard_get_key(keyboard_event); if (binding_keys.contains(key)) { dp.emit(); } } } libinput_event_destroy(event); } } }; hotplug_thread_ = [this] { int fd; fd = inotify_init(); if (fd < 0) { spdlog::error("Failed to initialize inotify: {}", strerror(errno)); return; } inotify_add_watch(fd, devices_path_.c_str(), IN_CREATE | IN_DELETE); while (1) { int BUF_LEN = 1024 * (sizeof(struct inotify_event) + 16); char buf[BUF_LEN]; int length = read(fd, buf, 1024); if (length < 0) { spdlog::error("Failed to read inotify: {}", strerror(errno)); return; } for (int i = 0; i < length;) { struct inotify_event* event = (struct inotify_event*)&buf[i]; std::string dev_path = devices_path_ + event->name; if (event->mask & IN_CREATE) { // Wait for device setup int timeout = 10; while (timeout--) { try { int fd = openFile(dev_path, O_NONBLOCK | O_CLOEXEC | O_RDONLY); closeFile(fd); break; } catch (const errno_error& e) { if (e.code == EACCES) { sleep(1); } } } tryAddDevice(dev_path); } else if (event->mask & IN_DELETE) { auto it = libinput_devices_.find(dev_path); if (it != libinput_devices_.end()) { spdlog::info("Keyboard {} has been removed.", dev_path); libinput_devices_.erase(it); } } i += sizeof(struct inotify_event) + event->len; } } }; } waybar::modules::KeyboardState::~KeyboardState() { for (const auto& [_, dev_ptr] : libinput_devices_) { libinput_path_remove_device(dev_ptr); } } auto waybar::modules::KeyboardState::update() -> void { sleep(0); // Wait for keyboard status change int numl = 0, capsl = 0, scrolll = 0; 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; } int fd = openFile(dev_path, O_NONBLOCK | O_CLOEXEC | O_RDONLY); auto dev = openDevice(fd); numl = libevdev_get_event_value(dev, EV_LED, LED_NUML); capsl = libevdev_get_event_value(dev, EV_LED, LED_CAPSL); scrolll = libevdev_get_event_value(dev, EV_LED, LED_SCROLLL); libevdev_free(dev); closeFile(fd); } catch (const errno_error& e) { // ENOTTY just means the device isn't an evdev device, skip it if (e.code != ENOTTY) { spdlog::warn(e.what()); } } struct { bool state; Gtk::Label& label; const std::string& format; const char* name; } label_states[] = { {(bool)numl, numlock_label_, numlock_format_, "Num"}, {(bool)capsl, capslock_label_, capslock_format_, "Caps"}, {(bool)scrolll, scrolllock_label_, scrolllock_format_, "Scroll"}, }; for (auto& label_state : label_states) { std::string text; text = fmt::format(fmt::runtime(label_state.format), fmt::arg("icon", label_state.state ? icon_locked_ : icon_unlocked_), fmt::arg("name", label_state.name)); label_state.label.set_markup(text); if (label_state.state) { label_state.label.get_style_context()->add_class("locked"); } else { label_state.label.get_style_context()->remove_class("locked"); } } AModule::update(); } auto waybar::modules ::KeyboardState::tryAddDevice(const std::string& dev_path) -> void { try { int fd = openFile(dev_path, O_NONBLOCK | O_CLOEXEC | O_RDONLY); auto dev = openDevice(fd); if (supportsLockStates(dev)) { spdlog::info("Found device {} at '{}'", libevdev_get_name(dev), dev_path); 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; } } libevdev_free(dev); closeFile(fd); } catch (const errno_error& e) { // ENOTTY just means the device isn't an evdev device, skip it if (e.code != ENOTTY) { spdlog::warn(e.what()); } } } waybar-0.12.0/src/modules/load.cpp000066400000000000000000000037431475603165300167620ustar00rootroot00000000000000#include "modules/load.hpp" // 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 waybar::modules::Load::Load(const std::string& id, const Json::Value& config) : ALabel(config, "load", id, "{load1}", 10) { thread_ = [this] { dp.emit(); thread_.sleep_for(interval_); }; } auto waybar::modules::Load::update() -> void { // TODO: as creating dynamic fmt::arg arrays is buggy we have to calc both 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); } auto format = format_; auto state = getState(load1); if (!state.empty() && config_["format-" + state].isString()) { format = config_["format-" + state].asString(); } if (format.empty()) { event_box_.hide(); } else { event_box_.show(); auto icons = std::vector{state}; fmt::dynamic_format_arg_store store; 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("icon1", getIcon(load1, icons))); store.push_back(fmt::arg("icon5", getIcon(load5, icons))); store.push_back(fmt::arg("icon15", getIcon(load15, icons))); label_.set_markup(fmt::vformat(format, store)); } // Call parent update ALabel::update(); } std::tuple waybar::modules::Load::getLoad() { double load[3]; if (getloadavg(load, 3) != -1) { double load1 = std::ceil(load[0] * 100.0) / 100.0; double load5 = std::ceil(load[1] * 100.0) / 100.0; double load15 = std::ceil(load[2] * 100.0) / 100.0; return {load1, load5, load15}; } throw std::runtime_error("Can't get system load"); } waybar-0.12.0/src/modules/memory/000077500000000000000000000000001475603165300166405ustar00rootroot00000000000000waybar-0.12.0/src/modules/memory/bsd.cpp000066400000000000000000000047311475603165300201210ustar00rootroot00000000000000// clang-format off #include #include // clang-format on #include // getpagesize #include "modules/memory.hpp" #if defined(__DragonFly__) #include // struct vmstats #elif defined(__NetBSD__) #include // struct uvmexp_sysctl #elif defined(__OpenBSD__) #include // struct uvmexp #endif static uint64_t get_total_memory() { #if defined(HW_MEMSIZE) || defined(HW_PHYSMEM64) uint64_t physmem; #else u_long physmem; #endif int mib[] = { CTL_HW, #if defined(HW_MEMSIZE) HW_MEMSIZE, #elif defined(HW_PHYSMEM64) HW_PHYSMEM64, #else HW_PHYSMEM, #endif }; u_int miblen = sizeof(mib) / sizeof(mib[0]); size_t sz = sizeof(physmem); if (sysctl(mib, miblen, &physmem, &sz, NULL, 0)) { throw std::runtime_error("sysctl hw.physmem failed"); } return physmem; } static uint64_t get_free_memory() { #if defined(__DragonFly__) struct vmstats vms; size_t sz = sizeof(vms); if (sysctlbyname("vm.vmstats", &vms, &sz, NULL, 0)) { throw std::runtime_error("sysctl vm.vmstats failed"); } return static_cast(vms.v_free_count + vms.v_inactive_count + vms.v_cache_count) * getpagesize(); #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) u_int v_free_count = 0, v_inactive_count = 0, v_cache_count = 0; size_t sz = sizeof(u_int); sysctlbyname("vm.stats.vm.v_free_count", &v_free_count, &sz, NULL, 0); sysctlbyname("vm.stats.vm.v_inactive_count", &v_inactive_count, &sz, NULL, 0); sysctlbyname("vm.stats.vm.v_cache_count", &v_cache_count, &sz, NULL, 0); return static_cast(v_free_count + v_inactive_count + v_cache_count) * getpagesize(); #elif defined(__NetBSD__) || defined(__OpenBSD__) #ifdef VM_UVMEXP2 #undef VM_UVMEXP #define VM_UVMEXP VM_UVMEXP2 #define uvmexp uvmexp_sysctl #else #define filepages vnodepages #define execpages vtextpages #endif int mib[] = { CTL_VM, VM_UVMEXP, }; u_int miblen = sizeof(mib) / sizeof(mib[0]); struct uvmexp uvmexp; size_t sz = sizeof(uvmexp); if (sysctl(mib, miblen, &uvmexp, &sz, NULL, 0)) { throw std::runtime_error("sysctl vm.uvmexp failed"); } return static_cast(uvmexp.free + uvmexp.inactive + uvmexp.filepages + uvmexp.execpages) * uvmexp.pagesize; #endif } void waybar::modules::Memory::parseMeminfo() { meminfo_["MemTotal"] = get_total_memory() / 1024; meminfo_["MemAvailable"] = get_free_memory() / 1024; } waybar-0.12.0/src/modules/memory/common.cpp000066400000000000000000000067271475603165300206500ustar00rootroot00000000000000#include "modules/memory.hpp" 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_); }; } auto waybar::modules::Memory::update() -> void { parseMeminfo(); unsigned long memtotal = meminfo_["MemTotal"]; unsigned long swaptotal = 0; if (meminfo_.count("SwapTotal")) { swaptotal = meminfo_["SwapTotal"]; } unsigned long memfree; unsigned long swapfree = 0; if (meminfo_.count("SwapFree")) { swapfree = meminfo_["SwapFree"]; } if (meminfo_.count("MemAvailable")) { // New kernels (3.4+) have an accurate available memory field. memfree = meminfo_["MemAvailable"] + meminfo_["zfs_size"]; } else { // Old kernel; give a best-effort approximation of available memory. memfree = meminfo_["MemFree"] + meminfo_["Buffers"] + meminfo_["Cached"] + meminfo_["SReclaimable"] - meminfo_["Shmem"] + meminfo_["zfs_size"]; } 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) { 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); auto format = format_; auto state = getState(used_ram_percentage); if (!state.empty() && config_["format-" + state].isString()) { format = config_["format-" + state].asString(); } if (format.empty()) { event_box_.hide(); } else { event_box_.show(); auto icons = std::vector{state}; 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("percentage", used_ram_percentage), fmt::arg("swapPercentage", used_swap_percentage), fmt::arg("used", used_ram_gigabytes), fmt::arg("swapUsed", used_swap_gigabytes), fmt::arg("avail", available_ram_gigabytes), fmt::arg("swapAvail", available_swap_gigabytes))); } if (tooltipEnabled()) { if (config_["tooltip-format"].isString()) { auto tooltip_format = config_["tooltip-format"].asString(); label_.set_tooltip_text(fmt::format( fmt::runtime(tooltip_format), used_ram_percentage, fmt::arg("total", total_ram_gigabytes), fmt::arg("swapTotal", total_swap_gigabytes), fmt::arg("percentage", used_ram_percentage), fmt::arg("swapPercentage", used_swap_percentage), fmt::arg("used", used_ram_gigabytes), fmt::arg("swapUsed", used_swap_gigabytes), fmt::arg("avail", available_ram_gigabytes), fmt::arg("swapAvail", available_swap_gigabytes))); } else { label_.set_tooltip_text(fmt::format("{:.{}f}GiB used", used_ram_gigabytes, 1)); } } } else { event_box_.hide(); } // Call parent update ALabel::update(); } waybar-0.12.0/src/modules/memory/linux.cpp000066400000000000000000000017651475603165300205140ustar00rootroot00000000000000#include "modules/memory.hpp" static unsigned zfsArcSize() { std::ifstream zfs_arc_stats{"/proc/spl/kstat/zfs/arcstats"}; if (zfs_arc_stats.is_open()) { std::string name; std::string type; unsigned long data{0}; std::string line; while (std::getline(zfs_arc_stats, line)) { std::stringstream(line) >> name >> type >> data; if (name == "size") { return data / 1024; // convert to kB } } } return 0; } void waybar::modules::Memory::parseMeminfo() { const std::string data_dir_ = "/proc/meminfo"; std::ifstream info(data_dir_); if (!info.is_open()) { throw std::runtime_error("Can't open " + data_dir_); } std::string line; while (getline(info, line)) { auto posDelim = line.find(':'); if (posDelim == std::string::npos) { continue; } std::string name = line.substr(0, posDelim); int64_t value = std::stol(line.substr(posDelim + 1)); meminfo_[name] = value; } meminfo_["zfs_size"] = zfsArcSize(); } waybar-0.12.0/src/modules/mpd/000077500000000000000000000000001475603165300161105ustar00rootroot00000000000000waybar-0.12.0/src/modules/mpd/mpd.cpp000066400000000000000000000313051475603165300173760ustar00rootroot00000000000000#include "modules/mpd/mpd.hpp" #include #include #include #include #include using namespace waybar::util; #include "modules/mpd/state.hpp" #if defined(MPD_NOINLINE) namespace waybar::modules { #include "modules/mpd/state.inl.hpp" } // namespace waybar::modules #endif waybar::modules::MPD::MPD(const std::string& id, const Json::Value& config) : ALabel(config, "mpd", id, "{album} - {artist} - {title}", 5, false, true), module_name_(id.empty() ? "mpd" : "mpd#" + id), server_(nullptr), port_(config_["port"].isUInt() ? config["port"].asUInt() : 0), password_(config_["password"].empty() ? "" : config_["password"].asString()), 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) { if (!config_["port"].isNull() && !config_["port"].isUInt()) { spdlog::warn("{}: `port` configuration should be an unsigned int", module_name_); } if (!config_["timeout"].isNull() && !config_["timeout"].isUInt()) { spdlog::warn("{}: `timeout` configuration should be an unsigned int", module_name_); } if (!config["server"].isNull()) { if (!config_["server"].isString()) { spdlog::warn("{}:`server` configuration should be a string", module_name_); } server_ = config["server"].asCString(); } event_box_.add_events(Gdk::BUTTON_PRESS_MASK); event_box_.signal_button_press_event().connect(sigc::mem_fun(*this, &MPD::handlePlayPause)); } auto waybar::modules::MPD::update() -> void { context_.update(); // Call parent update 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"; const char* tag = mpd_song_get_tag(song_.get(), type, idx); // mpd_song_get_tag can return NULL, so make sure it's valid before setting if (tag) result = tag; return result; } std::string waybar::modules::MPD::getFilename() const { std::string path = mpd_song_get_uri(song_.get()); size_t position = path.find_last_of("/"); if (position == std::string::npos) { return path; } else { return path.substr(position + 1); } } void waybar::modules::MPD::setLabel() { if (connection_ == nullptr) { label_.get_style_context()->add_class("disconnected"); label_.get_style_context()->remove_class("stopped"); label_.get_style_context()->remove_class("playing"); label_.get_style_context()->remove_class("paused"); auto format = config_["format-disconnected"].isString() ? config_["format-disconnected"].asString() : "disconnected"; if (format.empty()) { label_.set_markup(format); label_.show(); } else { label_.hide(); } if (tooltipEnabled()) { std::string tooltip_format; tooltip_format = config_["tooltip-format-disconnected"].isString() ? config_["tooltip-format-disconnected"].asString() : "MPD (disconnected)"; // Nothing to format label_.set_tooltip_text(tooltip_format); } return; } label_.get_style_context()->remove_class("disconnected"); auto format = format_; Glib::ustring artist, album_artist, album, title; std::string date, filename; 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."); format = config_["format-stopped"].isString() ? config_["format-stopped"].asString() : "stopped"; label_.get_style_context()->add_class("stopped"); label_.get_style_context()->remove_class("playing"); label_.get_style_context()->remove_class("paused"); } else { label_.get_style_context()->remove_class("stopped"); if (playing()) { 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(); 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()); song_pos = mpd_status_get_song_pos(status_.get()) + 1; volume = mpd_status_get_volume(status_.get()); if (volume < 0) { volume = 0; } queue_length = mpd_status_get_queue_length(status_.get()); elapsedTime = std::chrono::seconds(mpd_status_get_elapsed_time(status_.get())); totalTime = std::chrono::seconds(mpd_status_get_total_time(status_.get())); } bool consumeActivated = mpd_status_get_consume(status_.get()); std::string consumeIcon = getOptionIcon("consume", consumeActivated); bool randomActivated = mpd_status_get_random(status_.get()); std::string randomIcon = getOptionIcon("random", randomActivated); bool repeatActivated = mpd_status_get_repeat(status_.get()); 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::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)); if (text.empty()) { label_.hide(); } else { label_.show(); label_.set_markup(text); } } catch (fmt::format_error const& e) { spdlog::warn("mpd: format error: {}", e.what()); } if (tooltipEnabled()) { std::string tooltip_format; 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); } catch (fmt::format_error const& e) { spdlog::warn("mpd: format error (tooltip): {}", e.what()); } } } std::string waybar::modules::MPD::getStateIcon() const { if (!config_["state-icons"].isObject()) { return ""; } if (connection_ == nullptr) { spdlog::warn("{}: Trying to fetch state icon while disconnected", module_name_); return ""; } if (stopped()) { spdlog::warn("{}: Trying to fetch state icon while stopped", module_name_); return ""; } if (playing()) { return config_["state-icons"]["playing"].asString(); } else { return config_["state-icons"]["paused"].asString(); } } std::string waybar::modules::MPD::getOptionIcon(std::string optionName, bool activated) const { if (!config_[optionName + "-icons"].isObject()) { return ""; } if (connection_ == nullptr) { spdlog::warn("{}: Trying to fetch option icon while disconnected", module_name_); return ""; } if (activated) { return config_[optionName + "-icons"]["on"].asString(); } else { return config_[optionName + "-icons"]["off"].asString(); } } static bool isServerUnavailable(const std::error_code& ec) { if (ec.category() == std::system_category()) { switch (ec.value()) { case ECONNREFUSED: case ECONNRESET: case ENETDOWN: case ENETUNREACH: case EHOSTDOWN: case ENOENT: return true; } } return false; } void waybar::modules::MPD::tryConnect() { if (connection_ != nullptr) { return; } connection_ = detail::unique_connection(mpd_connection_new(server_, port_, timeout_), &mpd_connection_free); if (connection_ == nullptr) { spdlog::error("{}: Failed to connect to MPD", module_name_); connection_.reset(); return; } try { checkErrors(connection_.get()); spdlog::debug("{}: Connected to MPD", module_name_); if (!password_.empty()) { bool res = mpd_run_password(connection_.get(), password_.c_str()); if (!res) { spdlog::error("{}: Wrong MPD password", module_name_); connection_.reset(); return; } checkErrors(connection_.get()); } } catch (std::system_error& e) { /* Tone down logs if it's likely that the mpd server is not running */ auto level = isServerUnavailable(e.code()) ? spdlog::level::debug : spdlog::level::err; spdlog::log(level, "{}: Failed to connect to MPD: {}", module_name_, e.what()); connection_.reset(); } catch (std::runtime_error& e) { spdlog::error("{}: Failed to connect to MPD: {}", module_name_, e.what()); connection_.reset(); } } void waybar::modules::MPD::checkErrors(mpd_connection* conn) { switch (mpd_connection_get_error(conn)) { case MPD_ERROR_SUCCESS: mpd_connection_clear_error(conn); return; case MPD_ERROR_TIMEOUT: case MPD_ERROR_CLOSED: mpd_connection_clear_error(conn); connection_.reset(); state_ = MPD_STATE_UNKNOWN; throw std::runtime_error("Connection to MPD closed"); case MPD_ERROR_SYSTEM: if (auto ec = mpd_connection_get_system_error(conn); ec != 0) { mpd_connection_clear_error(conn); throw std::system_error(ec, std::system_category()); } G_GNUC_FALLTHROUGH; default: if (conn) { auto error_message = mpd_connection_get_error_message(conn); std::string error(error_message); mpd_connection_clear_error(conn); throw std::runtime_error(error); } throw std::runtime_error("Invalid connection"); } } void waybar::modules::MPD::fetchState() { if (connection_ == nullptr) { spdlog::error("{}: Not connected to MPD", module_name_); return; } auto conn = connection_.get(); status_ = detail::unique_status(mpd_run_status(conn), &mpd_status_free); checkErrors(conn); state_ = mpd_status_get_state(status_.get()); checkErrors(conn); song_ = detail::unique_song(mpd_run_current_song(conn), &mpd_song_free); checkErrors(conn); } bool waybar::modules::MPD::handlePlayPause(GdkEventButton* const& e) { if (e->type == GDK_2BUTTON_PRESS || e->type == GDK_3BUTTON_PRESS || connection_ == nullptr) { return false; } if (e->button == 1) { if (state_ == MPD_STATE_PLAY) context_.pause(); else context_.play(); } else if (e->button == 3) { context_.stop(); } return true; } waybar-0.12.0/src/modules/mpd/state.cpp000066400000000000000000000241361475603165300177420ustar00rootroot00000000000000#include "modules/mpd/state.hpp" #include #include #include "modules/mpd/mpd.hpp" #if defined(MPD_NOINLINE) namespace waybar::modules { #include "modules/mpd/state.inl.hpp" } // namespace waybar::modules #endif #if FMT_VERSION >= 90000 /* Satisfy fmt 9.x deprecation of implicit conversion of enums to int */ auto format_as(enum mpd_idle val) { return static_cast>(val); } #endif namespace waybar::modules::detail { #define IDLE_RUN_NOIDLE_AND_CMD(...) \ if (idle_connection_.connected()) { \ idle_connection_.disconnect(); \ auto conn = ctx_->connection().get(); \ if (!mpd_run_noidle(conn)) { \ if (mpd_connection_get_error(conn) != MPD_ERROR_SUCCESS) { \ spdlog::error("mpd: Idle: failed to unregister for IDLE events"); \ ctx_->checkErrors(conn); \ } \ } \ __VA_ARGS__; \ } void Idle::play() { IDLE_RUN_NOIDLE_AND_CMD(mpd_run_play(conn)); ctx_->setState(std::make_unique(ctx_)); } void Idle::pause() { IDLE_RUN_NOIDLE_AND_CMD(mpd_run_pause(conn, true)); ctx_->setState(std::make_unique(ctx_)); } void Idle::stop() { IDLE_RUN_NOIDLE_AND_CMD(mpd_run_stop(conn)); ctx_->setState(std::make_unique(ctx_)); } #undef IDLE_RUN_NOIDLE_AND_CMD void Idle::update() noexcept { // This is intentionally blank. } void Idle::entry() noexcept { auto conn = ctx_->connection().get(); assert(conn != nullptr); if (!mpd_send_idle_mask( conn, static_cast(MPD_IDLE_PLAYER | MPD_IDLE_OPTIONS | MPD_IDLE_QUEUE))) { ctx_->checkErrors(conn); spdlog::error("mpd: Idle: failed to register for IDLE events"); } else { spdlog::debug("mpd: Idle: watching FD"); sigc::slot idle_slot = sigc::mem_fun(*this, &Idle::on_io); idle_connection_ = Glib::signal_io().connect(idle_slot, mpd_connection_get_fd(conn), Glib::IO_IN | Glib::IO_PRI | Glib::IO_ERR | Glib::IO_HUP); } } void Idle::exit() noexcept { if (idle_connection_.connected()) { idle_connection_.disconnect(); spdlog::debug("mpd: Idle: unwatching FD"); } } bool Idle::on_io(Glib::IOCondition const&) { auto conn = ctx_->connection().get(); // callback should do this: enum mpd_idle events = mpd_recv_idle(conn, /* ignore_timeout?= */ false); spdlog::debug("mpd: Idle: recv_idle events -> {}", events); mpd_response_finish(conn); try { ctx_->checkErrors(conn); } catch (std::exception const& e) { spdlog::warn("mpd: Idle: error: {}", e.what()); ctx_->setState(std::make_unique(ctx_)); return false; } ctx_->fetchState(); mpd_state state = ctx_->state(); if (state == MPD_STATE_STOP) { ctx_->emit(); ctx_->setState(std::make_unique(ctx_)); } else if (state == MPD_STATE_PLAY) { ctx_->emit(); ctx_->setState(std::make_unique(ctx_)); } else if (state == MPD_STATE_PAUSE) { ctx_->emit(); ctx_->setState(std::make_unique(ctx_)); } else { ctx_->emit(); // self transition ctx_->setState(std::make_unique(ctx_)); } return false; } void Playing::entry() noexcept { sigc::slot timer_slot = sigc::mem_fun(*this, &Playing::on_timer); timer_connection_ = Glib::signal_timeout().connect_seconds(timer_slot, 1); spdlog::debug("mpd: Playing: enabled 1 second periodic timer."); } void Playing::exit() noexcept { if (timer_connection_.connected()) { timer_connection_.disconnect(); spdlog::debug("mpd: Playing: disabled 1 second periodic timer."); } } bool Playing::on_timer() { // Attempt to connect with MPD. try { ctx_->tryConnect(); // Success? if (!ctx_->is_connected()) { ctx_->setState(std::make_unique(ctx_)); return false; } ctx_->fetchState(); if (!ctx_->is_playing()) { if (ctx_->is_paused()) { ctx_->setState(std::make_unique(ctx_)); } else { ctx_->setState(std::make_unique(ctx_)); } return false; } ctx_->queryMPD(); ctx_->emit(); } catch (std::exception const& e) { spdlog::warn("mpd: Playing: error: {}", e.what()); ctx_->setState(std::make_unique(ctx_)); return false; } return true; } void Playing::stop() { if (timer_connection_.connected()) { timer_connection_.disconnect(); mpd_run_stop(ctx_->connection().get()); } ctx_->setState(std::make_unique(ctx_)); } void Playing::pause() { if (timer_connection_.connected()) { timer_connection_.disconnect(); mpd_run_pause(ctx_->connection().get(), true); } ctx_->setState(std::make_unique(ctx_)); } void Playing::update() noexcept { ctx_->do_update(); } void Paused::entry() noexcept { sigc::slot timer_slot = sigc::mem_fun(*this, &Paused::on_timer); timer_connection_ = Glib::signal_timeout().connect(timer_slot, /* milliseconds */ 200); spdlog::debug("mpd: Paused: enabled 200 ms periodic timer."); } void Paused::exit() noexcept { if (timer_connection_.connected()) { timer_connection_.disconnect(); spdlog::debug("mpd: Paused: disabled 200 ms periodic timer."); } } bool Paused::on_timer() { bool rc = true; // Attempt to connect with MPD. try { ctx_->tryConnect(); // Success? if (!ctx_->is_connected()) { ctx_->setState(std::make_unique(ctx_)); return false; } ctx_->fetchState(); ctx_->emit(); if (ctx_->is_paused()) { ctx_->setState(std::make_unique(ctx_)); rc = false; } else if (ctx_->is_playing()) { ctx_->setState(std::make_unique(ctx_)); rc = false; } else if (ctx_->is_stopped()) { ctx_->setState(std::make_unique(ctx_)); rc = false; } } catch (std::exception const& e) { spdlog::warn("mpd: Paused: error: {}", e.what()); ctx_->setState(std::make_unique(ctx_)); rc = false; } return rc; } void Paused::play() { if (timer_connection_.connected()) { timer_connection_.disconnect(); mpd_run_play(ctx_->connection().get()); } ctx_->setState(std::make_unique(ctx_)); } void Paused::stop() { if (timer_connection_.connected()) { timer_connection_.disconnect(); mpd_run_stop(ctx_->connection().get()); } ctx_->setState(std::make_unique(ctx_)); } void Paused::update() noexcept { ctx_->do_update(); } void Stopped::entry() noexcept { sigc::slot timer_slot = sigc::mem_fun(*this, &Stopped::on_timer); timer_connection_ = Glib::signal_timeout().connect(timer_slot, /* milliseconds */ 200); spdlog::debug("mpd: Stopped: enabled 200 ms periodic timer."); } void Stopped::exit() noexcept { if (timer_connection_.connected()) { timer_connection_.disconnect(); spdlog::debug("mpd: Stopped: disabled 200 ms periodic timer."); } } bool Stopped::on_timer() { bool rc = true; // Attempt to connect with MPD. try { ctx_->tryConnect(); // Success? if (!ctx_->is_connected()) { ctx_->setState(std::make_unique(ctx_)); return false; } ctx_->fetchState(); ctx_->emit(); if (ctx_->is_stopped()) { ctx_->setState(std::make_unique(ctx_)); rc = false; } else if (ctx_->is_playing()) { ctx_->setState(std::make_unique(ctx_)); rc = false; } else if (ctx_->is_paused()) { ctx_->setState(std::make_unique(ctx_)); rc = false; } } catch (std::exception const& e) { spdlog::warn("mpd: Stopped: error: {}", e.what()); ctx_->setState(std::make_unique(ctx_)); rc = false; } return rc; } void Stopped::play() { if (timer_connection_.connected()) { timer_connection_.disconnect(); mpd_run_play(ctx_->connection().get()); } ctx_->setState(std::make_unique(ctx_)); } void Stopped::pause() { if (timer_connection_.connected()) { timer_connection_.disconnect(); mpd_run_pause(ctx_->connection().get(), true); } ctx_->setState(std::make_unique(ctx_)); } void Stopped::update() noexcept { ctx_->do_update(); } bool Disconnected::arm_timer(int interval) noexcept { // check if it's necessary to modify the timer if (timer_connection_ && last_interval_ == interval) { return true; } // unregister timer, if present disarm_timer(); // register timer last_interval_ = interval; sigc::slot timer_slot = sigc::mem_fun(*this, &Disconnected::on_timer); timer_connection_ = Glib::signal_timeout().connect_seconds(timer_slot, interval); spdlog::debug("mpd: Disconnected: enabled {}s interval timer.", interval); return false; } void Disconnected::disarm_timer() noexcept { // unregister timer, if present if (timer_connection_.connected()) { timer_connection_.disconnect(); spdlog::debug("mpd: Disconnected: disabled interval timer."); } } void Disconnected::entry() noexcept { ctx_->emit(); arm_timer(1 /* second */); } void Disconnected::exit() noexcept { disarm_timer(); } bool Disconnected::on_timer() { // Attempt to connect with MPD. try { ctx_->tryConnect(); // Success? if (ctx_->is_connected()) { ctx_->fetchState(); ctx_->emit(); if (ctx_->is_playing()) { ctx_->setState(std::make_unique(ctx_)); } else if (ctx_->is_paused()) { ctx_->setState(std::make_unique(ctx_)); } else { ctx_->setState(std::make_unique(ctx_)); } return false; // do not rearm timer } } catch (std::exception const& e) { spdlog::warn("mpd: Disconnected: error: {}", e.what()); } return arm_timer(ctx_->interval()); } void Disconnected::update() noexcept { ctx_->do_update(); } } // namespace waybar::modules::detail waybar-0.12.0/src/modules/mpris/000077500000000000000000000000001475603165300164625ustar00rootroot00000000000000waybar-0.12.0/src/modules/mpris/mpris.cpp000066400000000000000000000620021475603165300203200ustar00rootroot00000000000000#include "modules/mpris/mpris.hpp" #include #include #include #include #include "util/scope_guard.hpp" extern "C" { #include } #include #include namespace waybar::modules::mpris { const std::string DEFAULT_FORMAT = "{player} ({status}): {dynamic}"; Mpris::Mpris(const std::string& id, const Json::Value& config) : ALabel(config, "mpris", id, DEFAULT_FORMAT, 0, false, true), tooltip_(DEFAULT_FORMAT), artist_len_(-1), album_len_(-1), title_len_(-1), dynamic_len_(-1), dynamic_prio_({"title", "artist", "album", "position", "length"}), dynamic_order_({"title", "artist", "album", "position", "length"}), dynamic_separator_(" - "), truncate_hours_(true), tooltip_len_limits_(false), // this character is used in Gnome so it's fine to use it here ellipsis_("\u2026"), player_("playerctld"), manager(), player(), last_update_(std::chrono::system_clock::now() - interval_) { if (config_["format-playing"].isString()) { format_playing_ = config_["format-playing"].asString(); } if (config_["format-paused"].isString()) { format_paused_ = config_["format-paused"].asString(); } if (config_["format-stopped"].isString()) { format_stopped_ = config_["format-stopped"].asString(); } if (config_["ellipsis"].isString()) { ellipsis_ = config_["ellipsis"].asString(); } if (config_["dynamic-separator"].isString()) { dynamic_separator_ = config_["dynamic-separator"].asString(); } if (tooltipEnabled()) { if (config_["tooltip-format"].isString()) { tooltip_ = config_["tooltip-format"].asString(); } if (config_["tooltip-format-playing"].isString()) { tooltip_playing_ = config_["tooltip-format-playing"].asString(); } if (config_["tooltip-format-paused"].isString()) { tooltip_paused_ = config_["tooltip-format-paused"].asString(); } if (config_["tooltip-format-stopped"].isString()) { tooltip_stopped_ = config_["tooltip-format-stopped"].asString(); } if (config_["enable-tooltip-len-limits"].isBool()) { tooltip_len_limits_ = config["enable-tooltip-len-limits"].asBool(); } } if (config["artist-len"].isUInt()) { artist_len_ = config["artist-len"].asUInt(); } if (config["album-len"].isUInt()) { album_len_ = config["album-len"].asUInt(); } if (config["title-len"].isUInt()) { title_len_ = config["title-len"].asUInt(); } if (config["dynamic-len"].isUInt()) { dynamic_len_ = config["dynamic-len"].asUInt(); } // "dynamic-priority" has been kept for backward compatibility if (config_["dynamic-importance-order"].isArray() || config_["dynamic-priority"].isArray()) { dynamic_prio_.clear(); const auto& dynamic_priority = config_["dynamic-importance-order"].isArray() ? config_["dynamic-importance-order"] : config_["dynamic-priority"]; for (const auto& value : dynamic_priority) { if (value.isString()) { dynamic_prio_.push_back(value.asString()); } } } if (config_["dynamic-order"].isArray()) { dynamic_order_.clear(); for (const auto& item : config_["dynamic-order"]) { if (item.isString()) { dynamic_order_.push_back(item.asString()); } } } if (config_["truncate-hours"].isBool()) { truncate_hours_ = config["truncate-hours"].asBool(); } if (config_["player"].isString()) { player_ = config_["player"].asString(); } if (config_["ignored-players"].isArray()) { for (const auto& item : config_["ignored-players"]) { if (item.isString()) { ignored_players_.push_back(item.asString()); } } } GError* error = nullptr; waybar::util::ScopeGuard error_deleter([error]() { if (error) { g_error_free(error); } }); manager = playerctl_player_manager_new(&error); if (error) { throw std::runtime_error(fmt::format("unable to create MPRIS client: {}", error->message)); } g_object_connect(manager, "signal::name-appeared", G_CALLBACK(onPlayerNameAppeared), this, NULL); g_object_connect(manager, "signal::name-vanished", G_CALLBACK(onPlayerNameVanished), this, NULL); if (player_ == "playerctld") { // use playerctld proxy PlayerctlPlayerName name = { .instance = (gchar*)player_.c_str(), .source = PLAYERCTL_SOURCE_DBUS_SESSION, }; player = playerctl_player_new_from_name(&name, &error); } else { GList* players = playerctl_list_players(&error); if (error) { throw std::runtime_error(fmt::format("unable to list players: {}", error->message)); } for (auto* p = players; p != nullptr; p = p->next) { auto* pn = static_cast(p->data); if (strcmp(pn->name, player_.c_str()) == 0) { player = playerctl_player_new_from_name(pn, &error); break; } } } if (error) { throw std::runtime_error( fmt::format("unable to connect to player {}: {}", player_, error->message)); } 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); } // allow setting an interval count that triggers periodic refreshes if (interval_.count() > 0) { thread_ = [this] { dp.emit(); thread_.sleep_for(interval_); }; } // trigger initial update dp.emit(); } Mpris::~Mpris() { if (manager != nullptr) g_object_unref(manager); if (player != nullptr) g_object_unref(player); } auto Mpris::getIconFromJson(const Json::Value& icons, const std::string& key) -> std::string { if (icons.isObject()) { if (icons[key].isString()) return icons[key].asString(); if (icons["default"].isString()) return icons["default"].asString(); } return ""; } // 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_); 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_); 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_); return title; } auto Mpris::getLengthStr(const PlayerInfo& info, bool truncated) -> std::string { if (info.length.has_value()) { auto length = info.length.value(); return (truncated && length.substr(0, 3) == "00:") ? length.substr(3) : length; } return {}; } auto Mpris::getPositionStr(const PlayerInfo& info, bool truncated) -> std::string { if (info.position.has_value()) { auto position = info.position.value(); return (truncated && position.substr(0, 3) == "00:") ? position.substr(3) : position; } return {}; } auto Mpris::getDynamicStr(const PlayerInfo& info, bool truncated, bool html) -> std::string { auto artist = getArtistStr(info, truncated); auto album = getAlbumStr(info, truncated); auto title = getTitleStr(info, truncated); auto length = getLengthStr(info, truncated && truncate_hours_); // 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 lengthLen = length.length(); size_t posLen = position.length(); bool showArtist = (artistLen != 0) && (std::find(dynamic_order_.begin(), dynamic_order_.end(), "artist") != dynamic_order_.end()); bool showAlbum = (albumLen != 0) && (std::find(dynamic_order_.begin(), dynamic_order_.end(), "album") != dynamic_order_.end()); bool showTitle = (titleLen != 0) && (std::find(dynamic_order_.begin(), dynamic_order_.end(), "title") != dynamic_order_.end()); bool showLength = (lengthLen != 0) && (std::find(dynamic_order_.begin(), dynamic_order_.end(), "length") != dynamic_order_.end()); bool showPos = (posLen != 0) && (std::find(dynamic_order_.begin(), dynamic_order_.end(), "position") != dynamic_order_.end()); if (truncated && dynamic_len_ >= 0) { // 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 dynamicLen = dynamic_len_ + separatorLen; if (showArtist) artistLen += separatorLen; if (showAlbum) albumLen += separatorLen; if (showTitle) albumLen += separatorLen; if (showLength) lengthLen += separatorLen; if (showPos) posLen += separatorLen; size_t totalLen = 0; for (const auto& item : dynamic_prio_) { if (item == "artist") { if (totalLen + artistLen > dynamicLen) { showArtist = false; } else if (showArtist) { totalLen += artistLen; } } else if (item == "album") { if (totalLen + albumLen > dynamicLen) { showAlbum = false; } else if (showAlbum) { totalLen += albumLen; } } else if (item == "title") { if (totalLen + titleLen > dynamicLen) { showTitle = false; } else if (showTitle) { totalLen += titleLen; } } else if (item == "length") { if (totalLen + lengthLen > dynamicLen) { showLength = false; } else if (showLength) { totalLen += lengthLen; posLen = std::max((size_t)2, posLen) - 2; } } else if (item == "position") { if (totalLen + posLen > dynamicLen) { showPos = false; } else if (showPos) { totalLen += posLen; lengthLen = std::max((size_t)2, lengthLen) - 2; } } } } std::stringstream dynamic; if (html) { artist = Glib::Markup::escape_text(artist); album = Glib::Markup::escape_text(album); title = Glib::Markup::escape_text(title); } bool lengthOrPositionShown = false; bool previousShown = false; std::string previousOrder = ""; for (const std::string& order : dynamic_order_) { if ((order == "artist" && showArtist) || (order == "album" && showAlbum) || (order == "title" && showTitle)) { if (previousShown && previousOrder != "length" && previousOrder != "position") { dynamic << dynamic_separator_; } if (order == "artist") { dynamic << artist; } else if (order == "album") { dynamic << album; } else if (order == "title") { dynamic << title; } previousShown = true; } else if (order == "length" || order == "position") { if (!lengthOrPositionShown && (showLength || showPos)) { if (html) dynamic << ""; if (previousShown) dynamic << ' '; dynamic << '['; if (showPos) { dynamic << position; if (showLength) dynamic << '/'; } if (showLength) dynamic << length; dynamic << ']'; if (!dynamic.str().empty()) dynamic << ' '; if (html) dynamic << ""; lengthOrPositionShown = true; } } previousOrder = order; } return dynamic.str(); } auto Mpris::onPlayerNameAppeared(PlayerctlPlayerManager* manager, PlayerctlPlayerName* player_name, gpointer data) -> void { auto* mpris = static_cast(data); if (!mpris) return; spdlog::debug("mpris: name-appeared callback: {}", player_name->name); if (std::string(player_name->name) != mpris->player_) { return; } 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->dp.emit(); } auto Mpris::onPlayerNameVanished(PlayerctlPlayerManager* manager, PlayerctlPlayerName* player_name, gpointer data) -> void { auto* mpris = static_cast(data); if (!mpris) return; spdlog::debug("mpris: player-vanished callback: {}", player_name->name); if (std::string(player_name->name) == mpris->player_) { mpris->player = nullptr; mpris->event_box_.set_visible(false); mpris->dp.emit(); } } auto Mpris::onPlayerPlay(PlayerctlPlayer* player, gpointer data) -> void { auto* mpris = static_cast(data); if (!mpris) return; spdlog::debug("mpris: player-play callback"); // update widget mpris->dp.emit(); } auto Mpris::onPlayerPause(PlayerctlPlayer* player, gpointer data) -> void { auto* mpris = static_cast(data); if (!mpris) return; spdlog::debug("mpris: player-pause callback"); // update widget mpris->dp.emit(); } auto Mpris::onPlayerStop(PlayerctlPlayer* player, gpointer data) -> void { auto* mpris = static_cast(data); if (!mpris) return; spdlog::debug("mpris: player-stop callback"); // hide widget mpris->event_box_.set_visible(false); // update widget mpris->dp.emit(); } auto Mpris::onPlayerMetadata(PlayerctlPlayer* player, GVariant* metadata, gpointer data) -> void { auto* mpris = static_cast(data); if (!mpris) return; spdlog::debug("mpris: player-metadata callback"); // update widget mpris->dp.emit(); } auto Mpris::getPlayerInfo() -> std::optional { if (!player) { return std::nullopt; } GError* error = nullptr; waybar::util::ScopeGuard error_deleter([error]() { if (error) { g_error_free(error); } }); 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); std::string player_name = player_; if (player_name == "playerctld") { GList* players = playerctl_list_players(&error); if (error) { throw std::runtime_error(fmt::format("unable to list players: {}", error->message)); } // > 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; })) { spdlog::warn("mpris[{}]: ignoring player update", player_name); return std::nullopt; } // make status lowercase player_status[0] = std::tolower(player_status[0]); PlayerInfo info = { .name = player_name, .status = player_playback_status, .status_string = player_status, .artist = std::nullopt, .album = std::nullopt, .title = std::nullopt, .length = std::nullopt, }; if (auto* artist_ = playerctl_player_get_artist(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)) { 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)) { 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)) { 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); auto len_m = std::chrono::duration_cast(len - len_h); auto len_s = std::chrono::duration_cast(len - len_h - len_m); info.length = fmt::format("{:02}:{:02}:{:02}", len_h.count(), len_m.count(), len_s.count()); g_free(length_); } if (error) goto errorexit; { auto position_ = playerctl_player_get_position(player, &error); if (error) { // it's fine to have an error here because not all players report a position g_error_free(error); error = nullptr; } else { spdlog::debug("mpris[{}]: position = {}", info.name, position_); auto len = std::chrono::microseconds(position_); auto len_h = std::chrono::duration_cast(len); auto len_m = std::chrono::duration_cast(len - len_h); auto len_s = std::chrono::duration_cast(len - len_h - len_m); info.position = fmt::format("{:02}:{:02}:{:02}", len_h.count(), len_m.count(), len_s.count()); } } return info; errorexit: std::string errorMsg = error->message; // When mpris checks for active player sessions periodically(5 secs), NoActivePlayer error // message is // thrown when there are no active sessions. This error message is spamming logs without having // any value addition. Log the error only if the error we recceived is not NoActivePlayer. if (errorMsg.rfind("GDBus.Error:com.github.altdesktop.playerctld.NoActivePlayer") == std::string::npos) { spdlog::error("mpris[{}]: {}", info.name, error->message); } return std::nullopt; } bool Mpris::handleToggle(GdkEventButton* const& e) { GError* error = nullptr; waybar::util::ScopeGuard error_deleter([error]() { if (error) { g_error_free(error); } }); auto info = getPlayerInfo(); if (!info) return false; 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; } } if (error) { spdlog::error("mpris[{}]: error running builtin on-click action: {}", (*info).name, error->message); return false; } return true; } auto Mpris::update() -> void { const auto now = std::chrono::system_clock::now(); if (now - last_update_ < interval_) return; last_update_ = now; auto opt = getPlayerInfo(); if (!opt) { event_box_.set_visible(false); ALabel::update(); return; } auto info = *opt; if (info.status == PLAYERCTL_PLAYBACK_STATUS_STOPPED) { spdlog::debug("mpris[{}]: player stopped, skipping update", info.name); return; } spdlog::debug("mpris[{}]: running update", info.name); // set css class for player status if (!lastStatus.empty() && label_.get_style_context()->has_class(lastStatus)) { label_.get_style_context()->remove_class(lastStatus); } if (!label_.get_style_context()->has_class(info.status_string)) { label_.get_style_context()->add_class(info.status_string); } lastStatus = info.status_string; // set css class for player name if (!lastPlayer.empty() && label_.get_style_context()->has_class(lastPlayer)) { label_.get_style_context()->remove_class(lastPlayer); } if (!label_.get_style_context()->has_class(info.name)) { label_.get_style_context()->add_class(info.name); } lastPlayer = info.name; auto formatstr = format_; auto tooltipstr = tooltip_; switch (info.status) { case PLAYERCTL_PLAYBACK_STATUS_PLAYING: if (!format_playing_.empty()) formatstr = format_playing_; if (!tooltip_playing_.empty()) tooltipstr = tooltip_playing_; break; case PLAYERCTL_PLAYBACK_STATUS_PAUSED: if (!format_paused_.empty()) formatstr = format_paused_; if (!tooltip_paused_.empty()) tooltipstr = tooltip_paused_; break; case PLAYERCTL_PLAYBACK_STATUS_STOPPED: if (!format_stopped_.empty()) formatstr = format_stopped_; if (!tooltip_stopped_.empty()) tooltipstr = tooltip_stopped_; break; } std::string length = getLengthStr(info, truncate_hours_); std::string tooltipLength = (tooltip_len_limits_ || length.length() > 5) ? length : getLengthStr(info, false); // keep position format same as length format std::string position = getPositionStr(info, truncate_hours_ && length.length() < 6); std::string tooltipPosition = (tooltip_len_limits_ || position.length() > 5) ? position : getPositionStr(info, false); try { auto label_format = fmt::format( fmt::runtime(formatstr), fmt::arg("player", std::string(Glib::Markup::escape_text(info.name))), fmt::arg("status", info.status_string), fmt::arg("artist", std::string(Glib::Markup::escape_text(getArtistStr(info, true)))), fmt::arg("title", std::string(Glib::Markup::escape_text(getTitleStr(info, true)))), fmt::arg("album", std::string(Glib::Markup::escape_text(getAlbumStr(info, true)))), fmt::arg("length", length), fmt::arg("position", position), fmt::arg("dynamic", getDynamicStr(info, true, true)), fmt::arg("player_icon", getIconFromJson(config_["player-icons"], info.name)), fmt::arg("status_icon", getIconFromJson(config_["status-icons"], info.status_string))); if (label_format.empty()) { label_.hide(); } else { label_.set_markup(label_format); label_.show(); } } catch (fmt::format_error const& e) { spdlog::warn("mpris: format error: {}", e.what()); } if (tooltipEnabled()) { try { 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("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); } catch (fmt::format_error const& e) { spdlog::warn("mpris: format error (tooltip): {}", e.what()); } } event_box_.set_visible(true); // call parent update ALabel::update(); } } // namespace waybar::modules::mpris waybar-0.12.0/src/modules/network.cpp000066400000000000000000000761031475603165300175340ustar00rootroot00000000000000#include "modules/network.hpp" #include #include #include #include #include #include #include #include "util/format.hpp" #ifdef WANT_RFKILL #include "util/rfkill.hpp" #endif namespace { using namespace waybar::util; constexpr const char *DEFAULT_FORMAT = "{ifname}"; } // namespace constexpr const char *NETDEV_FILE = "/proc/net/dev"; // std::ifstream does not take std::string_view as param std::optional> waybar::modules::Network::readBandwidthUsage() { std::ifstream netdev(NETDEV_FILE); if (!netdev) { spdlog::warn("Failed to open netdev file {}", NETDEV_FILE); return {}; } std::string line; // skip the headers (first two lines) std::getline(netdev, line); std::getline(netdev, line); unsigned long long receivedBytes = 0ull; unsigned long long transmittedBytes = 0ull; while (std::getline(netdev, line)) { std::istringstream iss(line); std::string ifacename; iss >> ifacename; // ifacename contains "eth0:" ifacename.pop_back(); // remove trailing ':' if (ifacename != ifname_) { continue; } // The rest of the line consists of whitespace separated counts divided // into two groups (receive and transmit). Each group has the following // columns: bytes, packets, errs, drop, fifo, frame, compressed, multicast // // We only care about the bytes count, so we'll just ignore the 7 other // columns. unsigned long long r = 0ull; unsigned long long t = 0ull; // Read received bytes iss >> r; // Skip all the other columns in the received group for (int colsToSkip = 7; colsToSkip > 0; colsToSkip--) { // skip whitespace between columns while (iss.peek() == ' ') { iss.ignore(); } // skip the irrelevant column while (iss.peek() != ' ') { iss.ignore(); } } // Read transmit bytes iss >> t; receivedBytes += r; transmittedBytes += t; } return {{receivedBytes, transmittedBytes}}; } waybar::modules::Network::Network(const std::string &id, const Json::Value &config) : ALabel(config, "network", id, DEFAULT_FORMAT, 60), ifid_(-1), 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), signal_strength_dbm_(0), signal_strength_(0), #ifdef WANT_RFKILL rfkill_{RFKILL_TYPE_WLAN}, #endif frequency_(0.0) { // 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 // the module start with no text, but the event_box_ is shown. label_.set_markup(""); auto bandwidth = readBandwidthUsage(); if (bandwidth.has_value()) { bandwidth_down_total_ = (*bandwidth).first; bandwidth_up_total_ = (*bandwidth).second; } else { bandwidth_down_total_ = 0; bandwidth_up_total_ = 0; } if (!config_["interface"].isString()) { // "interface" isn't configured, then try to guess the external // interface currently used for internet. want_route_dump_ = true; } else { // Look for an interface that match "interface" // and then find the address associated with it. want_link_dump_ = true; want_addr_dump_ = true; } createEventSocket(); createInfoSocket(); dp.emit(); // Ask for a dump of interfaces and then addresses to populate our // information. First the interface dump, and once done, the callback // will be called again which will ask for addresses dump. askForStateDump(); worker(); } waybar::modules::Network::~Network() { if (ev_fd_ > -1) { close(ev_fd_); } if (efd_ > -1) { close(efd_); } if (ev_sock_ != nullptr) { nl_socket_drop_memberships(ev_sock_, RTNLGRP_LINK, RTNLGRP_IPV4_IFADDR, RTNLGRP_IPV6_IFADDR); nl_close(ev_sock_); nl_socket_free(ev_sock_); } if (sock_ != nullptr) { nl_close(sock_); nl_socket_free(sock_); } } void waybar::modules::Network::createEventSocket() { ev_sock_ = nl_socket_alloc(); nl_socket_disable_seq_check(ev_sock_); nl_socket_modify_cb(ev_sock_, NL_CB_VALID, NL_CB_CUSTOM, handleEvents, this); nl_socket_modify_cb(ev_sock_, NL_CB_FINISH, NL_CB_CUSTOM, handleEventsDone, this); auto groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR; nl_join_groups(ev_sock_, groups); // Deprecated if (nl_connect(ev_sock_, NETLINK_ROUTE) != 0) { throw std::runtime_error("Can't connect network socket"); } if (nl_socket_set_nonblocking(ev_sock_)) { throw std::runtime_error("Can't set non-blocking on network socket"); } nl_socket_add_memberships(ev_sock_, RTNLGRP_LINK, RTNLGRP_IPV4_IFADDR, RTNLGRP_IPV6_IFADDR, 0); if (!config_["interface"].isString()) { nl_socket_add_memberships(ev_sock_, RTNLGRP_IPV4_ROUTE, RTNLGRP_IPV6_ROUTE, 0); } efd_ = epoll_create1(EPOLL_CLOEXEC); if (efd_ < 0) { throw std::runtime_error("Can't create epoll"); } { ev_fd_ = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); struct epoll_event event; memset(&event, 0, sizeof(event)); event.events = EPOLLIN | EPOLLET; event.data.fd = ev_fd_; if (epoll_ctl(efd_, EPOLL_CTL_ADD, ev_fd_, &event) == -1) { throw std::runtime_error("Can't add epoll event"); } } { auto fd = nl_socket_get_fd(ev_sock_); struct epoll_event event; memset(&event, 0, sizeof(event)); event.events = EPOLLIN | EPOLLET | EPOLLRDHUP; event.data.fd = fd; if (epoll_ctl(efd_, EPOLL_CTL_ADD, fd, &event) == -1) { throw std::runtime_error("Can't add epoll event"); } } } void waybar::modules::Network::createInfoSocket() { sock_ = nl_socket_alloc(); if (genl_connect(sock_) != 0) { throw std::runtime_error("Can't connect to netlink socket"); } if (nl_socket_modify_cb(sock_, NL_CB_VALID, NL_CB_CUSTOM, handleScan, this) < 0) { throw std::runtime_error("Can't set callback"); } nl80211_id_ = genl_ctrl_resolve(sock_, "nl80211"); if (nl80211_id_ < 0) { spdlog::warn("Can't resolve nl80211 interface"); } } void waybar::modules::Network::worker() { // update via here not working thread_timer_ = [this] { { std::lock_guard lock(mutex_); if (ifid_ > 0) { getInfo(); dp.emit(); } } thread_timer_.sleep_for(interval_); }; #ifdef WANT_RFKILL 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. */ thread_timer_.wake_up(); }); #else spdlog::warn("Waybar has been built without rfkill support."); #endif thread_ = [this] { std::array events{}; int ec = epoll_wait(efd_, events.data(), EPOLL_MAX, -1); if (ec > 0) { for (auto i = 0; i < ec; i++) { if (events[i].data.fd == nl_socket_get_fd(ev_sock_)) { int rc = 0; // Read as many message as possible, until the socket blocks while (true) { errno = 0; rc = nl_recvmsgs_default(ev_sock_); if (rc == -NLE_AGAIN || errno == EAGAIN) { rc = 0; break; } } if (rc < 0) { spdlog::error("nl_recvmsgs_default error: {}", nl_geterror(-rc)); thread_.stop(); break; } } else { thread_.stop(); break; } } } }; } const std::string waybar::modules::Network::getNetworkState() const { if (ifid_ == -1) { #ifdef WANT_RFKILL if (rfkill_.getState()) return "disabled"; #endif return "disconnected"; } if (!carrier_) return "disconnected"; if (ipaddr_.empty()) return "linked"; if (essid_.empty()) return "ethernet"; return "wifi"; } auto waybar::modules::Network::update() -> void { std::lock_guard lock(mutex_); std::string tooltip_format; 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; bandwidth_up = up_octets - bandwidth_up_total_; bandwidth_up_total_ = up_octets; } if (!alt_) { auto state = getNetworkState(); 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; } getState(signal_strength_); auto text = fmt::format( fmt::runtime(format_), fmt::arg("essid", essid_), fmt::arg("bssid", bssid_), fmt::arg("signaldBm", signal_strength_dbm_), fmt::arg("signalStrength", signal_strength_), fmt::arg("signalStrengthApp", signal_strength_app_), fmt::arg("ifname", ifname_), fmt::arg("netmask", netmask_), fmt::arg("ipaddr", ipaddr_), fmt::arg("gwaddr", gwaddr_), fmt::arg("cidr", cidr_), fmt::arg("frequency", fmt::format("{:.1f}", frequency_)), fmt::arg("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("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")), 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")), fmt::arg("bandwidthTotalBytes", pow_format((bandwidth_up + bandwidth_down) / interval_.count(), "B/s"))); if (text.compare(label_.get_label()) != 0) { label_.set_markup(text); if (text.empty()) { event_box_.hide(); } else { event_box_.show(); } } if (tooltipEnabled()) { if (tooltip_format.empty() && config_["tooltip-format"].isString()) { tooltip_format = config_["tooltip-format"].asString(); } if (!tooltip_format.empty()) { auto tooltip_text = fmt::format( fmt::runtime(tooltip_format), fmt::arg("essid", essid_), fmt::arg("bssid", bssid_), fmt::arg("signaldBm", signal_strength_dbm_), fmt::arg("signalStrength", signal_strength_), fmt::arg("signalStrengthApp", signal_strength_app_), fmt::arg("ifname", ifname_), fmt::arg("netmask", netmask_), fmt::arg("ipaddr", ipaddr_), fmt::arg("gwaddr", gwaddr_), fmt::arg("cidr", cidr_), fmt::arg("frequency", fmt::format("{:.1f}", frequency_)), fmt::arg("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("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")), 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")), fmt::arg("bandwidthTotalBytes", pow_format((bandwidth_up + bandwidth_down) / interval_.count(), "B/s"))); 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); } } // Call parent update ALabel::update(); } bool waybar::modules::Network::checkInterface(std::string name) { if (config_["interface"].isString()) { return config_["interface"].asString() == name || wildcardMatch(config_["interface"].asString(), name); } return false; } void waybar::modules::Network::clearIface() { ifid_ = -1; ifname_.clear(); essid_.clear(); bssid_.clear(); ipaddr_.clear(); gwaddr_.clear(); netmask_.clear(); carrier_ = false; cidr_ = 0; signal_strength_dbm_ = 0; signal_strength_ = 0; signal_strength_app_.clear(); frequency_ = 0.0; } 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; switch (nh->nlmsg_type) { case RTM_DELLINK: is_del_event = true; case RTM_NEWLINK: { struct ifinfomsg *ifi = static_cast(NLMSG_DATA(nh)); ssize_t attrlen = IFLA_PAYLOAD(nh); struct rtattr *ifla = IFLA_RTA(ifi); const char *ifname = NULL; size_t ifname_len = 0; std::optional carrier; if (net->ifid_ != -1 && ifi->ifi_index != net->ifid_) { return NL_OK; } // Check if the interface goes "down" and if we want to detect the // external interface. if (net->ifid_ != -1 && !(ifi->ifi_flags & IFF_UP) && !net->config_["interface"].isString()) { // The current interface is now down, all the routes associated with // it have been deleted, so start looking for a new default route. spdlog::debug("network: if{} down", net->ifid_); net->clearIface(); net->dp.emit(); net->want_route_dump_ = true; net->askForStateDump(); return NL_OK; } for (; RTA_OK(ifla, attrlen); ifla = RTA_NEXT(ifla, attrlen)) { switch (ifla->rta_type) { case IFLA_IFNAME: ifname = static_cast(RTA_DATA(ifla)); ifname_len = RTA_PAYLOAD(ifla) - 1; // minus \0 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 (!is_del_event && ifi->ifi_index == net->ifid_) { // Update interface information if (net->ifname_.empty() && ifname != NULL) { std::string new_ifname(ifname, ifname_len); net->ifname_ = new_ifname; } if (carrier.has_value()) { if (net->carrier_ != *carrier) { if (*carrier) { // Ask for WiFi information net->thread_timer_.wake_up(); } else { // clear state related to WiFi connection net->essid_.clear(); net->bssid_.clear(); net->signal_strength_dbm_ = 0; net->signal_strength_ = 0; net->signal_strength_app_.clear(); net->frequency_ = 0.0; } } net->carrier_ = carrier.value(); } } else if (!is_del_event && net->ifid_ == -1) { // Checking if it's an interface we care about. std::string new_ifname(ifname, ifname_len); if (net->checkInterface(new_ifname)) { spdlog::debug("network: selecting new interface {}/{}", new_ifname, ifi->ifi_index); net->ifname_ = new_ifname; net->ifid_ = ifi->ifi_index; if (ifi->ifi_flags & IFF_POINTOPOINT) net->is_p2p_ = true; if (carrier.has_value()) { net->carrier_ = carrier.value(); } net->thread_timer_.wake_up(); /* An address for this new interface should be received via an * RTM_NEWADDR event either because we ask for a dump of both links * and addrs, or because this interface has just been created and * the addr will be sent after the RTM_NEWLINK event. * So we don't need to do anything. */ } } else if (is_del_event && net->ifid_ >= 0) { // Our interface has been deleted, start looking/waiting for one we care. spdlog::debug("network: interface {}/{} deleted", net->ifname_, net->ifid_); net->clearIface(); net->dp.emit(); } break; } case RTM_DELADDR: is_del_event = true; case RTM_NEWADDR: { struct ifaddrmsg *ifa = static_cast(NLMSG_DATA(nh)); ssize_t attrlen = IFA_PAYLOAD(nh); struct rtattr *ifa_rta = IFA_RTA(ifa); if ((int)ifa->ifa_index != net->ifid_) { return NL_OK; } // We ignore address mark as scope for the link or host, // which should leave scope global addresses. if (ifa->ifa_scope >= RT_SCOPE_LINK) { return NL_OK; } for (; RTA_OK(ifa_rta, attrlen); ifa_rta = RTA_NEXT(ifa_rta, attrlen)) { switch (ifa_rta->rta_type) { case IFA_ADDRESS: if (net->is_p2p_) continue; case IFA_LOCAL: char ipaddr[INET6_ADDRSTRLEN]; if (!is_del_event) { net->ipaddr_ = inet_ntop(ifa->ifa_family, RTA_DATA(ifa_rta), ipaddr, sizeof(ipaddr)); net->cidr_ = ifa->ifa_prefixlen; switch (ifa->ifa_family) { case AF_INET: { struct in_addr netmask; netmask.s_addr = htonl(~0 << (32 - ifa->ifa_prefixlen)); net->netmask_ = inet_ntop(ifa->ifa_family, &netmask, ipaddr, sizeof(ipaddr)); } case AF_INET6: { struct in6_addr netmask; for (int i = 0; i < 16; i++) { int v = (i + 1) * 8 - ifa->ifa_prefixlen; if (v < 0) v = 0; if (v > 8) v = 8; netmask.s6_addr[i] = ~0 << v; } net->netmask_ = inet_ntop(ifa->ifa_family, &netmask, ipaddr, sizeof(ipaddr)); } } spdlog::debug("network: {}, new addr {}/{}", net->ifname_, net->ipaddr_, net->cidr_); } else { net->ipaddr_.clear(); net->cidr_ = 0; net->netmask_.clear(); spdlog::debug("network: {} addr deleted {}/{}", net->ifname_, inet_ntop(ifa->ifa_family, RTA_DATA(ifa_rta), ipaddr, sizeof(ipaddr)), ifa->ifa_prefixlen); } net->dp.emit(); break; } } break; } char temp_gw_addr[INET6_ADDRSTRLEN]; case RTM_DELROUTE: is_del_event = true; case RTM_NEWROUTE: { // Based on https://gist.github.com/Yawning/c70d804d4b8ae78cc698 // to find the interface used to reach the outside world struct rtmsg *rtm = static_cast(NLMSG_DATA(nh)); int family = rtm->rtm_family; ssize_t attrlen = RTM_PAYLOAD(nh); struct rtattr *attr = RTM_RTA(rtm); bool has_gateway = false; bool has_destination = false; int temp_idx = -1; uint32_t priority = 0; /* Find the message(s) concerting the main routing table, each message * corresponds to a single routing table entry. */ if (rtm->rtm_table != RT_TABLE_MAIN) { return NL_OK; } /* Parse all the attributes for a single routing table entry. */ for (; RTA_OK(attr, attrlen); attr = RTA_NEXT(attr, attrlen)) { /* Determine if this routing table entry corresponds to the default * route by seeing if it has a gateway, and if a destination addr is * set, that it is all 0s. */ switch (attr->rta_type) { case RTA_GATEWAY: /* The gateway of the route. * * If someone ever needs to figure out the gateway address as well, * it's here as the attribute payload. */ inet_ntop(family, RTA_DATA(attr), temp_gw_addr, sizeof(temp_gw_addr)); has_gateway = true; break; case RTA_DST: { /* The destination address. * Should be either missing, or maybe all 0s. Accept both. */ const uint32_t nr_zeroes = (family == AF_INET) ? 4 : 16; unsigned char c = 0; size_t dstlen = RTA_PAYLOAD(attr); if (dstlen != nr_zeroes) { break; } for (uint32_t i = 0; i < dstlen; i += 1) { c |= *((unsigned char *)RTA_DATA(attr) + i); } has_destination = (c == 0); break; } case RTA_OIF: /* The output interface index. */ temp_idx = *static_cast(RTA_DATA(attr)); break; case RTA_PRIORITY: priority = *(uint32_t *)RTA_DATA(attr); break; default: break; } } // Check if we have a default route. if (has_gateway && !has_destination && temp_idx != -1) { // Check if this is the first default route we see, or if this new // route have a higher priority. /** Module doesn`t update state, because RTA_GATEWAY call before enable new router and set higher priority. Disable router -> RTA_GATEWAY -> up new router -> set higher priority added checking route id **/ if (!is_del_event && ((net->ifid_ == -1) || (priority < net->route_priority))) { // Clear if's state for the case were there is a higher priority // route on a different interface. net->clearIface(); net->ifid_ = temp_idx; net->route_priority = priority; net->gwaddr_ = temp_gw_addr; spdlog::debug("network: new default route via {} on if{} metric {}", temp_gw_addr, temp_idx, priority); /* Ask ifname associated with temp_idx as well as carrier status */ struct ifinfomsg ifinfo_hdr = { .ifi_family = AF_UNSPEC, .ifi_index = temp_idx, }; int err; err = nl_send_simple(net->ev_sock_, RTM_GETLINK, NLM_F_REQUEST, &ifinfo_hdr, sizeof(ifinfo_hdr)); if (err < 0) { spdlog::error("network: failed to ask link info: {}", err); /* Ask for a dump of all links instead */ net->want_link_dump_ = true; } /* Also ask for the address. Asking for a addresses of a specific * interface doesn't seems to work so ask for a dump of all * addresses. */ net->want_addr_dump_ = true; net->askForStateDump(); net->thread_timer_.wake_up(); } else if (is_del_event && temp_idx == net->ifid_ && net->route_priority == priority) { spdlog::debug("network: default route deleted {}/if{} metric {}", net->ifname_, temp_idx, priority); net->clearIface(); net->dp.emit(); /* Ask for a dump of all routes in case another one is already * setup. If there's none, there'll be an event with new one * later. */ net->want_route_dump_ = true; net->askForStateDump(); } } break; } } return NL_OK; } void waybar::modules::Network::askForStateDump(void) { /* We need to wait until the current dump is done before sending new * messages. handleEventsDone() is called when a dump is done. */ if (dump_in_progress_) return; struct rtgenmsg rt_hdr = { .rtgen_family = AF_UNSPEC, }; if (want_route_dump_) { nl_send_simple(ev_sock_, RTM_GETROUTE, NLM_F_DUMP, &rt_hdr, sizeof(rt_hdr)); want_route_dump_ = false; dump_in_progress_ = true; } else if (want_link_dump_) { nl_send_simple(ev_sock_, RTM_GETLINK, NLM_F_DUMP, &rt_hdr, sizeof(rt_hdr)); want_link_dump_ = false; dump_in_progress_ = true; } else if (want_addr_dump_) { nl_send_simple(ev_sock_, RTM_GETADDR, NLM_F_DUMP, &rt_hdr, sizeof(rt_hdr)); want_addr_dump_ = false; dump_in_progress_ = true; } } 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]; 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; bss_policy[NL80211_BSS_BSSID].type = NLA_UNSPEC; bss_policy[NL80211_BSS_BEACON_INTERVAL].type = NLA_U16; bss_policy[NL80211_BSS_CAPABILITY].type = NLA_U16; bss_policy[NL80211_BSS_INFORMATION_ELEMENTS].type = NLA_UNSPEC; bss_policy[NL80211_BSS_SIGNAL_MBM].type = NLA_U32; bss_policy[NL80211_BSS_SIGNAL_UNSPEC].type = NLA_U8; bss_policy[NL80211_BSS_STATUS].type = NLA_U32; if (nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_attrlen(gnlh, 0), nullptr) < 0) { return NL_SKIP; } if (tb[NL80211_ATTR_BSS] == nullptr) { return NL_SKIP; } if (nla_parse_nested(bss, NL80211_BSS_MAX, tb[NL80211_ATTR_BSS], bss_policy) != 0) { return NL_SKIP; } if (!net->associatedOrJoined(bss)) { return NL_SKIP; } net->parseEssid(bss); net->parseSignal(bss); net->parseFreq(bss); net->parseBssid(bss); return NL_OK; } void waybar::modules::Network::parseEssid(struct nlattr **bss) { if (bss[NL80211_BSS_INFORMATION_ELEMENTS] != nullptr) { auto ies = static_cast(nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS])); auto ies_len = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]); const auto hdr_len = 2; while (ies_len > hdr_len && ies[0] != 0) { ies_len -= ies[1] + hdr_len; ies += ies[1] + hdr_len; } if (ies_len > hdr_len && ies_len > ies[1] + hdr_len) { auto essid_begin = ies + hdr_len; auto essid_end = essid_begin + ies[1]; std::string essid_raw; std::copy(essid_begin, essid_end, std::back_inserter(essid_raw)); essid_ = Glib::Markup::escape_text(essid_raw); } } } 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; // WiFi-hardware usually operates in the range -90 to -30dBm. // If a signal is too strong, it can overwhelm receiving circuity that is designed // to pick up and process a certain signal level. The following percentage is scaled to // punish signals that are too strong (>= -45dBm) or too weak (<= -45 dBm). const int hardwareOptimum = -45; const int hardwareMin = -90; const int strength = 100 - ((abs(signal_strength_dbm_ - hardwareOptimum) / double{hardwareOptimum - hardwareMin}) * 100); signal_strength_ = std::clamp(strength, 0, 100); if (signal_strength_dbm_ >= -50) { signal_strength_app_ = "Great Connectivity"; } else if (signal_strength_dbm_ >= -60) { signal_strength_app_ = "Good Connectivity"; } else if (signal_strength_dbm_ >= -67) { signal_strength_app_ = "Streaming"; } else if (signal_strength_dbm_ >= -70) { signal_strength_app_ = "Web Surfing"; } else if (signal_strength_dbm_ >= -80) { signal_strength_app_ = "Basic Connectivity"; } else { signal_strength_app_ = "Poor Connectivity"; } } if (bss[NL80211_BSS_SIGNAL_UNSPEC] != nullptr) { signal_strength_ = nla_get_u8(bss[NL80211_BSS_SIGNAL_UNSPEC]); } } 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) { if (bss[NL80211_BSS_BSSID] != nullptr) { 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], bssid[4], bssid[5]); } } } bool waybar::modules::Network::associatedOrJoined(struct nlattr **bss) { if (bss[NL80211_BSS_STATUS] == nullptr) { return false; } auto status = nla_get_u32(bss[NL80211_BSS_STATUS]); switch (status) { case NL80211_BSS_STATUS_ASSOCIATED: case NL80211_BSS_STATUS_IBSS_JOINED: case NL80211_BSS_STATUS_AUTHENTICATED: return true; default: return false; } } auto waybar::modules::Network::getInfo() -> void { struct nl_msg *nl_msg = nlmsg_alloc(); if (nl_msg == nullptr) { return; } if (genlmsg_put(nl_msg, NL_AUTO_PORT, NL_AUTO_SEQ, nl80211_id_, 0, NLM_F_DUMP, NL80211_CMD_GET_SCAN, 0) == nullptr || nla_put_u32(nl_msg, NL80211_ATTR_IFINDEX, ifid_) < 0) { nlmsg_free(nl_msg); return; } 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; } waybar-0.12.0/src/modules/niri/000077500000000000000000000000001475603165300162715ustar00rootroot00000000000000waybar-0.12.0/src/modules/niri/backend.cpp000066400000000000000000000203451475603165300203700ustar00rootroot00000000000000#include "modules/niri/backend.hpp" #include #include #include #include #include #include #include #include #include #include #include #include "giomm/datainputstream.h" #include "giomm/dataoutputstream.h" #include "giomm/unixinputstream.h" #include "giomm/unixoutputstream.h" namespace waybar::modules::niri { int IPC::connectToSocket() { 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; } struct sockaddr_un addr; int socketfd = socket(AF_UNIX, SOCK_STREAM, 0); if (socketfd == -1) { throw std::runtime_error("socketfd failed"); } addr.sun_family = AF_UNIX; strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path) - 1); addr.sun_path[sizeof(addr.sun_path) - 1] = 0; int l = sizeof(struct sockaddr_un); if (connect(socketfd, (struct sockaddr *)&addr, l) == -1) { close(socketfd); throw std::runtime_error("unable to connect"); } return socketfd; } 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; spdlog::info("Niri IPC starting"); auto unix_istream = Gio::UnixInputStream::create(socketfd, true); auto unix_ostream = Gio::UnixOutputStream::create(socketfd, false); auto istream = Gio::DataInputStream::create(unix_istream); auto ostream = Gio::DataOutputStream::create(unix_ostream); if (!ostream->put_string("\"EventStream\"\n") || !ostream->flush()) { spdlog::error("Niri IPC: failed to start event stream"); return; } std::string line; if (!istream->read_line(line) || line != R"({"Ok":"Handled"})") { spdlog::error("Niri IPC: failed to start event stream"); return; } while (istream->read_line(line)) { spdlog::debug("Niri IPC: received {}", line); try { parseIPC(line); } catch (std::exception &e) { spdlog::warn("Failed to parse IPC message: {}, reason: {}", line, e.what()); } catch (...) { throw; } std::this_thread::sleep_for(std::chrono::milliseconds(1)); } }).detach(); } 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"); { auto lock = lockData(); if (const auto &payload = ev["WorkspacesChanged"]) { workspaces_.clear(); 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(); 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"]) { 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; }); if (it != workspaces_.end()) { 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; if (focused) ws["is_focused"] = got_activated; } } else { spdlog::error("Activated unknown workspace"); } } 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) { return ws["id"].asUInt64() == workspaceId; }); if (it != workspaces_.end()) { 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"]; keyboardLayoutCurrent_ = layouts["current_idx"].asUInt(); keyboardLayoutNames_.clear(); 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"]) { windows_.clear(); 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"]; const auto id = window["id"].asUInt64(); auto it = std::find_if(windows_.begin(), windows_.end(), [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_) { win["is_focused"] = win["id"].asUInt64() == id; } } } else { *it = window; } } 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; }); if (it != windows_.end()) { windows_.erase(it); } else { spdlog::error("Unknown window closed"); } } else if (const auto &payload = ev["WindowFocusChanged"]) { const auto focused = !payload["id"].isNull(); const auto id = payload["id"].asUInt64(); for (auto &win : windows_) { win["is_focused"] = focused && win["id"].asUInt64() == id; } } } std::unique_lock lock(callbackMutex_); for (auto &[eventname, handler] : callbacks_) { if (eventname == members[0]) { handler->onEvent(ev); } } } void IPC::registerForIPC(const std::string &ev, EventHandler *ev_handler) { if (ev_handler == nullptr) { return; } std::unique_lock lock(callbackMutex_); callbacks_.emplace_back(ev, ev_handler); } void IPC::unregisterForIPC(EventHandler *ev_handler) { if (ev_handler == nullptr) { return; } std::unique_lock lock(callbackMutex_); for (auto it = callbacks_.begin(); it != callbacks_.end();) { auto &[eventname, handler] = *it; if (handler == ev_handler) { it = callbacks_.erase(it); } else { ++it; } } } Json::Value IPC::send(const Json::Value &request) { int socketfd = connectToSocket(); if (socketfd == -1) throw std::runtime_error("Niri is not running"); auto unix_istream = Gio::UnixInputStream::create(socketfd, true); auto unix_ostream = Gio::UnixOutputStream::create(socketfd, false); auto istream = Gio::DataInputStream::create(unix_istream); auto ostream = Gio::DataOutputStream::create(unix_ostream); // Niri needs the request on a single line. Json::StreamWriterBuilder builder; builder["indentation"] = ""; std::unique_ptr writer(builder.newStreamWriter()); std::ostringstream oss; writer->write(request, &oss); oss << '\n'; if (!ostream->put_string(oss.str()) || !ostream->flush()) throw std::runtime_error("error writing to niri socket"); std::string line; if (!istream->read_line(line)) throw std::runtime_error("error reading from niri socket"); std::istringstream iss(std::move(line)); Json::Value response; iss >> response; return response; } } // namespace waybar::modules::niri waybar-0.12.0/src/modules/niri/language.cpp000066400000000000000000000104241475603165300205610ustar00rootroot00000000000000#include "modules/niri/language.hpp" #include #include #include #include "util/string.hpp" namespace waybar::modules::niri { Language::Language(const std::string &id, const Bar &bar, const Json::Value &config) : ALabel(config, "language", id, "{}", 0, false), bar_(bar) { label_.hide(); if (!gIPC) gIPC = std::make_unique(); gIPC->registerForIPC("KeyboardLayoutsChanged", this); gIPC->registerForIPC("KeyboardLayoutSwitched", this); updateFromIPC(); dp.emit(); } Language::~Language() { gIPC->unregisterForIPC(this); // wait for possible event handler to finish std::lock_guard lock(mutex_); } void Language::updateFromIPC() { std::lock_guard lock(mutex_); auto ipcLock = gIPC->lockData(); layouts_.clear(); for (const auto &fullName : gIPC->keyboardLayoutNames()) layouts_.push_back(getLayout(fullName)); current_idx_ = gIPC->keyboardLayoutCurrent(); } /** * Language::doUpdate - update workspaces in UI thread. * * Note: some member fields are modified by both UI thread and event listener thread, use mutex_ to * protect these member fields, and lock should released before calling ALabel::update(). */ void Language::doUpdate() { std::lock_guard lock(mutex_); if (layouts_.size() <= current_idx_) { spdlog::error("niri language layout index out of bounds"); label_.hide(); return; } 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); std::string layoutName = std::string{}; if (config_.isMember("format-" + layout.short_description + "-" + layout.variant)) { const auto propName = "format-" + layout.short_description + "-" + layout.variant; layoutName = fmt::format(fmt::runtime(format_), config_[propName].asString()); } else if (config_.isMember("format-" + layout.short_description)) { const auto propName = "format-" + layout.short_description; layoutName = fmt::format(fmt::runtime(format_), config_[propName].asString()); } else { layoutName = trim(fmt::format(fmt::runtime(format_), fmt::arg("long", layout.full_name), fmt::arg("short", layout.short_name), fmt::arg("shortDescription", layout.short_description), fmt::arg("variant", layout.variant))); } spdlog::debug("niri language formatted layout name {}", layoutName); if (!format_.empty()) { label_.show(); label_.set_markup(layoutName); } else { label_.hide(); } } void Language::update() { doUpdate(); ALabel::update(); } void Language::onEvent(const Json::Value &ev) { if (ev["KeyboardLayoutsChanged"]) { updateFromIPC(); } else if (ev["KeyboardLayoutSwitched"]) { std::lock_guard lock(mutex_); auto ipcLock = gIPC->lockData(); current_idx_ = gIPC->keyboardLayoutCurrent(); } dp.emit(); } 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); while (layout != nullptr) { std::string nameOfLayout = rxkb_layout_get_description(layout); if (nameOfLayout != fullName) { layout = rxkb_layout_next(layout); continue; } auto name = std::string(rxkb_layout_get_name(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); std::string description = descriptionPtr == nullptr ? "" : std::string(descriptionPtr); Layout info = Layout{nameOfLayout, name, variant, description}; rxkb_context_unref(context); return info; } rxkb_context_unref(context); spdlog::debug("niri language didn't find matching layout for {}", fullName); return Layout{"", "", "", ""}; } } // namespace waybar::modules::niri waybar-0.12.0/src/modules/niri/window.cpp000066400000000000000000000065131475603165300203110ustar00rootroot00000000000000#include "modules/niri/window.hpp" #include #include #include #include "util/rewrite_string.hpp" #include "util/sanitize_str.hpp" namespace waybar::modules::niri { 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(); gIPC->registerForIPC("WindowsChanged", this); gIPC->registerForIPC("WindowOpenedOrChanged", this); gIPC->registerForIPC("WindowClosed", this); gIPC->registerForIPC("WindowFocusChanged", this); dp.emit(); } Window::~Window() { gIPC->unregisterForIPC(this); } 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 separateOutputs = config_["separate-outputs"].asBool(); 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; } return ws["is_focused"].asBool(); }); std::vector::const_iterator it; if (ws_it == workspaces.cend() || (*ws_it)["active_window_id"].isNull()) { it = windows.cend(); } 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; }); } setClass("empty", ws_it == workspaces.cend() || (*ws_it)["active_window_id"].isNull()); if (it != windows.cend()) { const auto &window = *it; const auto title = window["title"].asString(); const auto appId = window["app_id"].asString(); const auto sanitizedTitle = waybar::util::sanitize_string(title); const auto sanitizedAppId = waybar::util::sanitize_string(appId); label_.show(); label_.set_markup(waybar::util::rewriteString( fmt::format(fmt::runtime(format_), fmt::arg("title", sanitizedTitle), fmt::arg("app_id", sanitizedAppId)), config_["rewrite"])); updateAppIconName(appId, ""); if (tooltipEnabled()) label_.set_tooltip_text(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) { return win["id"].asUInt64() != id && win["workspace_id"].asUInt64() == workspaceId; }); setClass("solo", isSolo); if (!appId.empty()) setClass(appId, isSolo); if (oldAppId_ != appId) { if (!oldAppId_.empty()) setClass(oldAppId_, false); oldAppId_ = appId; } } else { label_.hide(); updateAppIconName("", ""); setClass("solo", false); if (!oldAppId_.empty()) setClass(oldAppId_, false); oldAppId_.clear(); } } void Window::update() { doUpdate(); AAppIconLabel::update(); } void Window::setClass(const std::string &className, bool enable) { auto styleContext = bar_.window.get_style_context(); if (enable) { if (!styleContext->has_class(className)) { styleContext->add_class(className); } } else { styleContext->remove_class(className); } } } // namespace waybar::modules::niri waybar-0.12.0/src/modules/niri/workspaces.cpp000066400000000000000000000133241475603165300211610ustar00rootroot00000000000000#include "modules/niri/workspaces.hpp" #include #include #include namespace waybar::modules::niri { Workspaces::Workspaces(const std::string &id, const Bar &bar, const Json::Value &config) : AModule(config, "workspaces", id, false, false), bar_(bar), box_(bar.orientation, 0) { box_.set_name("workspaces"); if (!id.empty()) { box_.get_style_context()->add_class(id); } box_.get_style_context()->add_class(MODULE_CLASS); event_box_.add(box_); if (!gIPC) gIPC = std::make_unique(); gIPC->registerForIPC("WorkspacesChanged", this); gIPC->registerForIPC("WorkspaceActivated", this); gIPC->registerForIPC("WorkspaceActiveWindowChanged", this); dp.emit(); } Workspaces::~Workspaces() { gIPC->unregisterForIPC(this); } 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(); std::copy_if(workspaces.cbegin(), workspaces.cend(), std::back_inserter(my_workspaces), [&](const auto &ws) { if (alloutputs) return true; return ws["output"].asString() == bar_.output->name; }); // 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; }); if (ws == my_workspaces.end()) { it = buttons_.erase(it); } else { ++it; } } // Add buttons for new workspaces, update existing ones. for (const auto &ws : my_workspaces) { auto bit = buttons_.find(ws["id"].asUInt64()); auto &button = bit == buttons_.end() ? addButton(ws) : bit->second; auto style_context = button.get_style_context(); if (ws["is_focused"].asBool()) style_context->add_class("focused"); else style_context->remove_class("focused"); if (ws["is_active"].asBool()) style_context->add_class("active"); else style_context->remove_class("active"); if (ws["output"]) { if (ws["output"].asString() == bar_.output->name) style_context->add_class("current_output"); else style_context->remove_class("current_output"); } else { style_context->remove_class("current_output"); } if (ws["active_window_id"].isNull()) style_context->add_class("empty"); else style_context->remove_class("empty"); std::string name; if (ws["name"]) { name = ws["name"].asString(); } else { name = std::to_string(ws["idx"].asUInt()); } button.set_name("niri-workspace-" + name); if (config_["format"].isString()) { auto format = config_["format"].asString(); name = fmt::format(fmt::runtime(format), fmt::arg("icon", getIcon(name, ws)), fmt::arg("value", name), fmt::arg("name", ws["name"].asString()), fmt::arg("index", ws["idx"].asUInt()), fmt::arg("output", ws["output"].asString())); } if (!config_["disable-markup"].asBool()) { static_cast(button.get_children()[0])->set_markup(name); } else { button.set_label(name); } if (config_["current-only"].asBool()) { const auto *property = alloutputs ? "is_focused" : "is_active"; if (ws[property].asBool()) button.show(); else button.hide(); } else { button.show(); } } // Refresh the button order. for (auto it = my_workspaces.cbegin(); it != my_workspaces.cend(); ++it) { const auto &ws = *it; auto pos = ws["idx"].asUInt() - 1; if (alloutputs) pos = it - my_workspaces.cbegin(); auto &button = buttons_[ws["id"].asUInt64()]; box_.reorder_child(button, pos); } } void Workspaces::update() { doUpdate(); AModule::update(); } Gtk::Button &Workspaces::addButton(const Json::Value &ws) { std::string name; if (ws["name"]) { name = ws["name"].asString(); } else { name = std::to_string(ws["idx"].asUInt()); } auto pair = buttons_.emplace(ws["id"].asUInt64(), name); auto &&button = pair.first->second; box_.pack_start(button, false, false, 0); button.set_relief(Gtk::RELIEF_NONE); if (!config_["disable-click"].asBool()) { const auto id = ws["id"].asUInt64(); button.signal_pressed().connect([=] { 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)); reference["Id"] = id; IPC::send(request); } catch (const std::exception &e) { spdlog::error("Error switching workspace: {}", e.what()); } }); } return button; } 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_active"].asBool() && icons["active"]) return icons["active"].asString(); if (ws["name"]) { const auto &name = ws["name"].asString(); if (icons[name]) return icons[name].asString(); } const auto idx = ws["idx"].asString(); if (icons[idx]) return icons[idx].asString(); if (icons["default"]) return icons["default"].asString(); return value; } } // namespace waybar::modules::niri waybar-0.12.0/src/modules/power_profiles_daemon.cpp000066400000000000000000000205251475603165300224220ustar00rootroot00000000000000#include "modules/power_profiles_daemon.hpp" #include #include #include #include namespace waybar::modules { PowerProfilesDaemon::PowerProfilesDaemon(const std::string& id, const Json::Value& config) : ALabel(config, "power-profiles-daemon", id, "{icon}", 0, false, true), connected_(false) { if (config_["tooltip-format"].isString()) { tooltipFormat_ = config_["tooltip-format"].asString(); } else { tooltipFormat_ = "Power profile: {profile}\nDriver: {driver}"; } // Fasten your seatbelt, we're up for quite a ride. The rest of the // init is performed asynchronously. There's 2 callbacks involved. // Here's the overall idea: // 1. Async connect to the system bus. // 2. In the system bus connect callback, try to call // org.freedesktop.DBus.Properties.GetAll to see if // power-profiles-daemon is able to respond. // 3. In the GetAll callback, connect the activeProfile monitoring // callback, consider the init to be successful. Meaning start // drawing the module. // // There's sadly no other way around that, we have to try to call a // 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 // 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. // // Revisit this in 2026, systems should be updated by then. Gio::DBus::Proxy::create_for_bus(Gio::DBus::BusType::BUS_TYPE_SYSTEM, "net.hadess.PowerProfiles", "/net/hadess/PowerProfiles", "net.hadess.PowerProfiles", sigc::mem_fun(*this, &PowerProfilesDaemon::busConnectedCb)); // Schedule update to set the initial visibility dp.emit(); } void PowerProfilesDaemon::busConnectedCb(Glib::RefPtr& r) { try { powerProfilesProxy_ = Gio::DBus::Proxy::create_for_bus_finish(r); using GetAllProfilesVar = Glib::Variant>; auto callArgs = GetAllProfilesVar::create(std::make_tuple("net.hadess.PowerProfiles")); powerProfilesProxy_->call("org.freedesktop.DBus.Properties.GetAll", sigc::mem_fun(*this, &PowerProfilesDaemon::getAllPropsCb), callArgs); // Connect active profile callback } catch (const std::exception& e) { spdlog::error("Failed to create the power profiles daemon DBus proxy: {}", e.what()); } catch (const Glib::Error& e) { spdlog::error("Failed to create the power profiles daemon DBus proxy: {}", std::string(e.what())); } } // Callback for the GetAll call. // // We're abusing this call to make sure power-profiles-daemon is // available on the host. We're not really using void PowerProfilesDaemon::getAllPropsCb(Glib::RefPtr& r) { try { auto _ = powerProfilesProxy_->call_finish(r); // Power-profiles-daemon responded something, we can assume it's // available, we can safely attach the activeProfile monitoring // now. connected_ = true; powerProfilesProxy_->signal_properties_changed().connect( sigc::mem_fun(*this, &PowerProfilesDaemon::profileChangedCb)); populateInitState(); } catch (const std::exception& err) { spdlog::error("Failed to query power-profiles-daemon via dbus: {}", err.what()); } catch (const Glib::Error& err) { spdlog::error("Failed to query power-profiles-daemon via dbus: {}", std::string(err.what())); } } void PowerProfilesDaemon::populateInitState() { // Retrieve current active profile Glib::Variant profileStr; powerProfilesProxy_->get_cached_property(profileStr, "ActiveProfile"); // Retrieve profiles list, it's aa{sv}. using ProfilesType = std::vector>>; Glib::Variant profilesVariant; powerProfilesProxy_->get_cached_property(profilesVariant, "Profiles"); for (auto& variantDict : profilesVariant.get()) { Glib::ustring name; Glib::ustring driver; if (auto p = variantDict.find("Profile"); p != variantDict.end()) { name = p->second.get(); } if (auto d = variantDict.find("Driver"); d != variantDict.end()) { driver = d->second.get(); } if (!name.empty()) { availableProfiles_.emplace_back(std::move(name), std::move(driver)); } else { spdlog::error( "Power profiles daemon: power-profiles-daemon sent us an empty power profile name. " "Something is wrong."); } } // Find the index of the current activated mode (to toggle) std::string str = profileStr.get(); switchToProfile(str); } void PowerProfilesDaemon::profileChangedCb( const Gio::DBus::Proxy::MapChangedProperties& changedProperties, const std::vector& invalidatedProperties) { // We're likely connected if this callback gets triggered. // But better be safe than sorry. if (connected_) { if (auto activeProfileVariant = changedProperties.find("ActiveProfile"); activeProfileVariant != changedProperties.end()) { std::string activeProfile = Glib::VariantBase::cast_dynamic>(activeProfileVariant->second) .get(); switchToProfile(activeProfile); } } } // Look for the profile str in our internal profiles list. Using a // vector to store the profiles ain't the smartest move // complexity-wise, but it makes toggling between the mode easy. This // vector is 3 elements max, we'll be fine :P void PowerProfilesDaemon::switchToProfile(std::string const& str) { auto pred = [str](Profile const& p) { return p.name == str; }; this->activeProfile_ = std::find_if(availableProfiles_.begin(), availableProfiles_.end(), pred); if (activeProfile_ == availableProfiles_.end()) { spdlog::error( "Power profile daemon: can't find the active profile {} in the available profiles list", str); } dp.emit(); } auto PowerProfilesDaemon::update() -> void { if (connected_ && activeProfile_ != availableProfiles_.end()) { auto profile = (*activeProfile_); // Set label fmt::dynamic_format_arg_store store; store.push_back(fmt::arg("profile", profile.name)); store.push_back(fmt::arg("driver", profile.driver)); 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)); } // Set CSS class if (!currentStyle_.empty()) { label_.get_style_context()->remove_class(currentStyle_); } label_.get_style_context()->add_class(profile.name); currentStyle_ = profile.name; event_box_.set_visible(true); } else { event_box_.set_visible(false); } ALabel::update(); } bool PowerProfilesDaemon::handleToggle(GdkEventButton* const& e) { if (e->type == GdkEventType::GDK_BUTTON_PRESS && connected_) { if (e->button == 1) /* left click */ { activeProfile_++; if (activeProfile_ == availableProfiles_.end()) { activeProfile_ = availableProfiles_.begin(); } } else { if (activeProfile_ == availableProfiles_.begin()) { activeProfile_ = availableProfiles_.end(); } activeProfile_--; } using VarStr = Glib::Variant; using SetPowerProfileVar = Glib::Variant>; VarStr activeProfileVariant = VarStr::create(activeProfile_->name); auto callArgs = SetPowerProfileVar::create( std::make_tuple("net.hadess.PowerProfiles", "ActiveProfile", activeProfileVariant)); powerProfilesProxy_->call("org.freedesktop.DBus.Properties.Set", sigc::mem_fun(*this, &PowerProfilesDaemon::setPropCb), callArgs); } return true; } void PowerProfilesDaemon::setPropCb(Glib::RefPtr& r) { try { auto _ = powerProfilesProxy_->call_finish(r); dp.emit(); } catch (const std::exception& e) { spdlog::error("Failed to set the active power profile: {}", e.what()); } catch (const Glib::Error& e) { spdlog::error("Failed to set the active power profile: {}", std::string(e.what())); } } } // namespace waybar::modules waybar-0.12.0/src/modules/privacy/000077500000000000000000000000001475603165300170055ustar00rootroot00000000000000waybar-0.12.0/src/modules/privacy/privacy.cpp000066400000000000000000000133331475603165300211710ustar00rootroot00000000000000#include "modules/privacy/privacy.hpp" #include #include #include #include "AModule.hpp" #include "modules/privacy/privacy_item.hpp" namespace waybar::modules::privacy { using util::PipewireBackend::PRIVACY_NODE_TYPE_AUDIO_INPUT; using util::PipewireBackend::PRIVACY_NODE_TYPE_AUDIO_OUTPUT; using util::PipewireBackend::PRIVACY_NODE_TYPE_NONE; using util::PipewireBackend::PRIVACY_NODE_TYPE_VIDEO_INPUT; Privacy::Privacy(const std::string& id, const Json::Value& config, const std::string& pos) : AModule(config, "privacy", id), nodes_screenshare(), nodes_audio_in(), nodes_audio_out(), visibility_conn(), box_(Gtk::ORIENTATION_HORIZONTAL, 0) { box_.set_name(name_); event_box_.add(box_); // Icon Spacing if (config_["icon-spacing"].isUInt()) { iconSpacing = config_["icon-spacing"].asUInt(); } box_.set_spacing(iconSpacing); // Icon Size if (config_["icon-size"].isUInt()) { iconSize = config_["icon-size"].asUInt(); } // Transition Duration if (config_["transition-duration"].isUInt()) { transition_duration = config_["transition-duration"].asUInt(); } // Initialize each privacy module Json::Value modules = config_["modules"]; // Add Screenshare and Mic usage as default modules if none are specified if (!modules.isArray() || modules.empty()) { modules = Json::Value(Json::arrayValue); for (const auto& type : {"screenshare", "audio-in"}) { Json::Value obj = Json::Value(Json::objectValue); obj["type"] = type; modules.append(obj); } } std::map > typeMap = { {"screenshare", {&nodes_screenshare, PRIVACY_NODE_TYPE_VIDEO_INPUT}}, {"audio-in", {&nodes_audio_in, PRIVACY_NODE_TYPE_AUDIO_INPUT}}, {"audio-out", {&nodes_audio_out, PRIVACY_NODE_TYPE_AUDIO_OUTPUT}}, }; for (const auto& module : modules) { if (!module.isObject() || !module["type"].isString()) continue; const std::string type = module["type"].asString(); auto iter = typeMap.find(type); if (iter != typeMap.end()) { auto& [nodePtr, nodeType] = iter->second; auto* item = Gtk::make_managed(module, nodeType, nodePtr, pos, iconSize, transition_duration); box_.add(*item); } } backend = util::PipewireBackend::PipewireBackend::getInstance(); backend->privacy_nodes_changed_signal_event.connect( sigc::mem_fun(*this, &Privacy::onPrivacyNodesChanged)); dp.emit(); } void Privacy::onPrivacyNodesChanged() { mutex_.lock(); nodes_audio_out.clear(); nodes_audio_in.clear(); nodes_screenshare.clear(); for (auto& node : backend->privacy_nodes) { switch (node.second->state) { case PW_NODE_STATE_RUNNING: switch (node.second->type) { case PRIVACY_NODE_TYPE_VIDEO_INPUT: nodes_screenshare.push_back(node.second); break; case PRIVACY_NODE_TYPE_AUDIO_INPUT: nodes_audio_in.push_back(node.second); break; case PRIVACY_NODE_TYPE_AUDIO_OUTPUT: nodes_audio_out.push_back(node.second); break; case PRIVACY_NODE_TYPE_NONE: continue; } break; default: break; } } mutex_.unlock(); dp.emit(); } auto Privacy::update() -> void { // set in modules or not bool setScreenshare = false; bool setAudioIn = false; bool setAudioOut = false; // used or not bool useScreenshare = false; bool useAudioIn = false; bool useAudioOut = false; mutex_.lock(); for (Gtk::Widget* widget : box_.get_children()) { auto* module = dynamic_cast(widget); if (module == nullptr) continue; switch (module->privacy_type) { case util::PipewireBackend::PRIVACY_NODE_TYPE_VIDEO_INPUT: setScreenshare = true; useScreenshare = !nodes_screenshare.empty(); module->set_in_use(useScreenshare); break; case util::PipewireBackend::PRIVACY_NODE_TYPE_AUDIO_INPUT: setAudioIn = true; useAudioIn = !nodes_audio_in.empty(); module->set_in_use(useAudioIn); break; case util::PipewireBackend::PRIVACY_NODE_TYPE_AUDIO_OUTPUT: setAudioOut = true; useAudioOut = !nodes_audio_out.empty(); module->set_in_use(useAudioOut); break; case util::PipewireBackend::PRIVACY_NODE_TYPE_NONE: break; } } mutex_.unlock(); // Hide the whole widget if none are in use bool isVisible = (setScreenshare && useScreenshare) || (setAudioIn && useAudioIn) || (setAudioOut && useAudioOut); if (isVisible != event_box_.get_visible()) { // Disconnect any previous connection so that it doesn't get activated in // the future, hiding the module when it should be visible visibility_conn.disconnect(); if (isVisible) { event_box_.set_visible(true); } else { // Hides the widget when all of the privacy_item revealers animations // have finished animating visibility_conn = Glib::signal_timeout().connect( sigc::track_obj( [this, setScreenshare, setAudioOut, setAudioIn]() { mutex_.lock(); bool visible = false; visible |= setScreenshare && !nodes_screenshare.empty(); visible |= setAudioIn && !nodes_audio_in.empty(); visible |= setAudioOut && !nodes_audio_out.empty(); mutex_.unlock(); event_box_.set_visible(visible); return false; }, *this), transition_duration); } } // Call parent update AModule::update(); } } // namespace waybar::modules::privacy waybar-0.12.0/src/modules/privacy/privacy_item.cpp000066400000000000000000000112771475603165300222140ustar00rootroot00000000000000#include "modules/privacy/privacy_item.hpp" #include #include "glibmm/main.h" #include "gtkmm/label.h" #include "gtkmm/revealer.h" #include "gtkmm/tooltip.h" #include "util/pipewire/privacy_node_info.hpp" namespace waybar::modules::privacy { PrivacyItem::PrivacyItem(const Json::Value &config_, enum PrivacyNodeType privacy_type_, std::list *nodes_, const std::string &pos, const uint icon_size, const uint transition_duration) : Gtk::Revealer(), privacy_type(privacy_type_), nodes(nodes_), signal_conn(), tooltip_window(Gtk::ORIENTATION_VERTICAL, 0), box_(Gtk::ORIENTATION_HORIZONTAL, 0), icon_() { switch (privacy_type) { case util::PipewireBackend::PRIVACY_NODE_TYPE_AUDIO_INPUT: box_.get_style_context()->add_class("audio-in"); iconName = "waybar-privacy-audio-input-symbolic"; break; case util::PipewireBackend::PRIVACY_NODE_TYPE_AUDIO_OUTPUT: box_.get_style_context()->add_class("audio-out"); iconName = "waybar-privacy-audio-output-symbolic"; break; case util::PipewireBackend::PRIVACY_NODE_TYPE_VIDEO_INPUT: box_.get_style_context()->add_class("screenshare"); iconName = "waybar-privacy-screen-share-symbolic"; break; default: case util::PipewireBackend::PRIVACY_NODE_TYPE_NONE: return; } // Set the reveal transition to not look weird when sliding in if (pos == "modules-left") { set_transition_type(Gtk::REVEALER_TRANSITION_TYPE_SLIDE_RIGHT); } else if (pos == "modules-center") { set_transition_type(Gtk::REVEALER_TRANSITION_TYPE_CROSSFADE); } else if (pos == "modules-right") { set_transition_type(Gtk::REVEALER_TRANSITION_TYPE_SLIDE_LEFT); } set_transition_duration(transition_duration); box_.set_name("privacy-item"); box_.add(icon_); icon_.set_pixel_size(icon_size); add(box_); // Icon Name if (config_["icon-name"].isString()) { iconName = config_["icon-name"].asString(); } icon_.set_from_icon_name(iconName, Gtk::ICON_SIZE_INVALID); // Tooltip Icon Size if (config_["tooltip-icon-size"].isUInt()) { tooltipIconSize = config_["tooltip-icon-size"].asUInt(); } // Tooltip if (config_["tooltip"].isString()) { tooltip = config_["tooltip"].asBool(); } set_has_tooltip(tooltip); if (tooltip) { // 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) { tooltip->set_custom(tooltip_window); return true; }, *this)); } // Don't show by default set_reveal_child(true); set_visible(false); } void PrivacyItem::update_tooltip() { // Removes all old nodes for (auto *child : tooltip_window.get_children()) { delete child; } for (auto *node : *nodes) { Gtk::Box *box = new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 4); // Set device icon Gtk::Image *node_icon = new Gtk::Image(); node_icon->set_pixel_size(tooltipIconSize); node_icon->set_from_icon_name(node->getIconName(), Gtk::ICON_SIZE_INVALID); box->add(*node_icon); // Set model auto *nodeName = new Gtk::Label(node->getName()); box->add(*nodeName); tooltip_window.add(*box); } tooltip_window.show_all(); } void PrivacyItem::set_in_use(bool in_use) { if (in_use) { update_tooltip(); } if (this->in_use == in_use && init) return; if (init) { // Disconnect any previous connection so that it doesn't get activated in // the future, hiding the module when it should be visible signal_conn.disconnect(); this->in_use = in_use; guint duration = 0; if (this->in_use) { set_visible(true); } else { set_reveal_child(false); duration = get_transition_duration(); } signal_conn = Glib::signal_timeout().connect(sigc::track_obj( [this] { if (this->in_use) { set_reveal_child(true); } else { set_visible(false); } return false; }, *this), duration); } else { set_visible(false); set_reveal_child(false); } this->init = true; } } // namespace waybar::modules::privacy waybar-0.12.0/src/modules/pulseaudio.cpp000066400000000000000000000124441475603165300202130ustar00rootroot00000000000000#include "modules/pulseaudio.hpp" 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)); backend = util::AudioBackend::getInstance([this] { this->dp.emit(); }); backend->setIgnoredSinks(config_["ignored-sinks"]); } 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()) { return AModule::handleScroll(e); } auto dir = AModule::getScrollDir(e); if (dir == SCROLL_DIR::NONE) { return true; } int max_volume = 100; double step = 1; // isDouble returns true for integers as well, just in case if (config_["scroll-step"].isDouble()) { step = config_["scroll-step"].asDouble(); } if (config_["max-volume"].isInt()) { max_volume = config_["max-volume"].asInt(); } auto change_type = (dir == SCROLL_DIR::UP || dir == SCROLL_DIR::RIGHT) ? util::ChangeType::Increase : util::ChangeType::Decrease; backend->changeVolume(change_type, step, max_volume); return true; } static const std::array ports = { "headphone", "speaker", "hdmi", "headset", "hands-free", "portable", "car", "hifi", "phone", }; const std::vector waybar::modules::Pulseaudio::getPulseIcon() const { std::vector res; auto sink_muted = backend->getSinkMuted(); if (sink_muted) { res.emplace_back(backend->getCurrentSinkName() + "-muted"); } res.push_back(backend->getCurrentSinkName()); 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) { if (nameLC.find(port) != std::string::npos) { if (sink_muted) { res.emplace_back(port + "-muted"); } res.push_back(port); break; } } if (sink_muted) { res.emplace_back("default-muted"); } return res; } auto waybar::modules::Pulseaudio::update() -> void { auto format = format_; std::string tooltip_format; auto sink_volume = backend->getSinkVolume(); if (!alt_) { std::string format_name = "format"; if (backend->isBluetooth()) { format_name = format_name + "-bluetooth"; label_.get_style_context()->add_class("bluetooth"); } else { label_.get_style_context()->remove_class("bluetooth"); } if (backend->getSinkMuted()) { // Check muted bluetooth format exist, otherwise fallback to default muted format if (format_name != "format" && !config_[format_name + "-muted"].isString()) { format_name = "format"; } format_name = format_name + "-muted"; 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"); } auto state = getState(sink_volume, true); if (!state.empty() && config_[format_name + "-" + state].isString()) { format = config_[format_name + "-" + state].asString(); } else if (config_[format_name].isString()) { format = config_[format_name].asString(); } } // TODO: find a better way to split source/sink std::string format_source = "{volume}%"; if (backend->getSourceMuted()) { label_.get_style_context()->add_class("source-muted"); if (config_["format-source-muted"].isString()) { format_source = config_["format-source-muted"].asString(); } } else { label_.get_style_context()->remove_class("source-muted"); if (config_["format-source"].isString()) { format_source = config_["format-source"].asString(); } } auto source_volume = backend->getSourceVolume(); auto sink_desc = backend->getSinkDesc(); auto source_desc = backend->getSourceDesc(); format_source = fmt::format(fmt::runtime(format_source), fmt::arg("volume", source_volume)); auto text = fmt::format( fmt::runtime(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()))); if (text.empty()) { label_.hide(); } else { label_.set_markup(text); label_.show(); } if (tooltipEnabled()) { if (tooltip_format.empty() && 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("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); } } // Call parent update ALabel::update(); } waybar-0.12.0/src/modules/pulseaudio_slider.cpp000066400000000000000000000037371475603165300215620ustar00rootroot00000000000000#include "modules/pulseaudio_slider.hpp" namespace waybar::modules { PulseaudioSlider::PulseaudioSlider(const std::string& id, const Json::Value& config) : ASlider(config, "pulseaudio-slider", id) { backend = util::AudioBackend::getInstance([this] { this->dp.emit(); }); backend->setIgnoredSinks(config_["ignored-sinks"]); if (config_["target"].isString()) { std::string target = config_["target"].asString(); if (target == "sink") { this->target = PulseaudioSliderTarget::Sink; } else if (target == "source") { this->target = PulseaudioSliderTarget::Source; } } } void PulseaudioSlider::update() { switch (target) { case PulseaudioSliderTarget::Sink: if (backend->getSinkMuted()) { scale_.set_value(min_); } else { scale_.set_value(backend->getSinkVolume()); } break; case PulseaudioSliderTarget::Source: if (backend->getSourceMuted()) { scale_.set_value(min_); } else { scale_.set_value(backend->getSourceVolume()); } break; } } void PulseaudioSlider::onValueChanged() { bool is_mute = false; 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; } } } backend->changeVolume(volume, min_, max_); } } // namespace waybar::moduleswaybar-0.12.0/src/modules/river/000077500000000000000000000000001475603165300164575ustar00rootroot00000000000000waybar-0.12.0/src/modules/river/layout.cpp000066400000000000000000000136471475603165300205130ustar00rootroot00000000000000#include "modules/river/layout.hpp" #include #include #include "client.hpp" namespace waybar::modules::river { 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) { // Intentionally empty } 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_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_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) { // Intentionally empty } static void listen_mode(void *data, struct zriver_seat_status_v1 *zriver_seat_status_v1, const char *mode) { // Intentionally empty } static const zriver_output_status_v1_listener output_status_listener_impl{ .focused_tags = listen_focused_tags, .view_tags = listen_view_tags, .urgent_tags = listen_urgent_tags, .layout_name = listen_layout_name, .layout_name_clear = listen_layout_name_clear, }; static const zriver_seat_status_v1_listener seat_status_listener_impl{ .focused_output = listen_focused_output, .unfocused_output = listen_unfocused_output, .focused_view = listen_focused_view, .mode = listen_mode, }; static void 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); // implies ZRIVER_OUTPUT_STATUS_V1_LAYOUT_NAME_CLEAR_SINCE_VERSION if (version < ZRIVER_OUTPUT_STATUS_V1_LAYOUT_NAME_SINCE_VERSION) { spdlog::error( "river server does not support the \"layout_name\" and \"layout_clear\" events; the " "module will be disabled" + std::to_string(version)); return; } 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 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) : 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); wl_registry_add_listener(registry, ®istry_listener_impl, this); wl_display_roundtrip(display); output_ = gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj()); if (!status_manager_) { spdlog::error("river_status_manager_v1 not advertised"); return; } if (!seat_) { spdlog::error("wl_seat not advertised"); } label_.hide(); ALabel::update(); seat_status_ = zriver_status_manager_v1_get_river_seat_status(status_manager_, seat_); zriver_seat_status_v1_add_listener(seat_status_, &seat_status_listener_impl, this); 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_); } Layout::~Layout() { if (output_status_) { zriver_output_status_v1_destroy(output_status_); } if (seat_status_) { zriver_seat_status_v1_destroy(seat_status_); } } 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(); label_.set_markup(fmt::format(fmt::runtime(format_), Glib::Markup::escape_text(name).raw())); } ALabel::update(); } void Layout::handle_clear() { label_.hide(); ALabel::update(); } 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(); } focused_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(); } } } /* namespace waybar::modules::river */ waybar-0.12.0/src/modules/river/mode.cpp000066400000000000000000000072321475603165300201130ustar00rootroot00000000000000#include "modules/river/mode.hpp" #include #include #include "client.hpp" namespace waybar::modules::river { 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) { // Intentionally empty } 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 const zriver_seat_status_v1_listener seat_status_listener_impl = { .focused_output = listen_focused_output, .unfocused_output = listen_unfocused_output, .focused_view = listen_focused_view, .mode = listen_mode, }; static void 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) { spdlog::error( "river server does not support the \"mode\" event; the module will be disabled"); return; } 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 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) : 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); wl_registry_add_listener(registry, ®istry_listener_impl, this); wl_display_roundtrip(display); if (!status_manager_) { spdlog::error("river_status_manager_v1 not advertised"); return; } if (!seat_) { spdlog::error("wl_seat not advertised"); } label_.hide(); ALabel::update(); seat_status_ = zriver_status_manager_v1_get_river_seat_status(status_manager_, seat_); zriver_seat_status_v1_add_listener(seat_status_, &seat_status_listener_impl, this); zriver_status_manager_v1_destroy(status_manager_); } Mode::~Mode() { if (seat_status_) { zriver_seat_status_v1_destroy(seat_status_); } } void Mode::handle_mode(const char *mode) { if (format_.empty()) { label_.hide(); } else { if (!mode_.empty()) { label_.get_style_context()->remove_class(mode_); } label_.get_style_context()->add_class(mode); label_.set_markup(fmt::format(fmt::runtime(format_), Glib::Markup::escape_text(mode).raw())); label_.show(); } mode_ = mode; ALabel::update(); } } /* namespace waybar::modules::river */ waybar-0.12.0/src/modules/river/tags.cpp000066400000000000000000000225161475603165300201270ustar00rootroot00000000000000#include "modules/river/tags.hpp" #include #include #include #include #include #include "client.hpp" #include "xdg-output-unstable-v1-client-protocol.h" namespace waybar::modules::river { 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 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, uint32_t tags) { static_cast(data)->handle_urgent_tags(tags); } static const zriver_output_status_v1_listener output_status_listener_impl{ .focused_tags = listen_focused_tags, .view_tags = listen_view_tags, .urgent_tags = listen_urgent_tags, }; 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) { spdlog::error("failure when selecting/toggling tags {}", output); } static const zriver_command_callback_v1_listener command_callback_listener_impl{ .success = listen_command_success, .failure = listen_command_failure, }; 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( 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( 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 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) : waybar::AModule(config, "tags", id, false, false), status_manager_{nullptr}, control_{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); wl_registry_add_listener(registry, ®istry_listener_impl, this); wl_display_roundtrip(display); if (!status_manager_) { spdlog::error("river_status_manager_v1 not advertised"); return; } if (!control_) { spdlog::error("river_control_v1 not advertised"); } if (!seat_) { spdlog::error("wl_seat not advertised"); } box_.set_name("tags"); if (!id.empty()) { box_.get_style_context()->add_class(id); } box_.get_style_context()->add_class(MODULE_CLASS); event_box_.add(box_); // Default to 9 tags, cap at 32 const int num_tags = config["num-tags"].isUInt() ? std::min(32, config_["num-tags"].asUInt()) : 9; const auto tag_labels = config["tag-labels"]; const auto set_tags = config["set-tags"]; const auto toggle_tags = config["toggle-tags"]; for (int tag = 0; tag < num_tags; ++tag) { if (tag_labels.isArray() && !tag_labels.empty()) { buttons_.emplace_back(tag_labels[tag].asString()); } else { // default name is the tag value buttons_.emplace_back(std::to_string(tag + 1)); } auto &button = buttons_[tag]; button.set_relief(Gtk::RELIEF_NONE); box_.pack_start(button, false, false, 0); if (!config_["disable-click"].asBool()) { if (set_tags.isArray() && !set_tags.empty()) button.signal_clicked().connect(sigc::bind( sigc::mem_fun(*this, &Tags::handle_primary_clicked), set_tags[tag].asUInt())); else button.signal_clicked().connect( sigc::bind(sigc::mem_fun(*this, &Tags::handle_primary_clicked), (1 << tag))); if (toggle_tags.isArray() && !toggle_tags.empty()) button.signal_button_press_event().connect(sigc::bind( sigc::mem_fun(*this, &Tags::handle_button_press), toggle_tags[tag].asUInt())); else button.signal_button_press_event().connect( sigc::bind(sigc::mem_fun(*this, &Tags::handle_button_press), (1 << tag))); } 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_); } Tags::~Tags() { if (output_status_) { zriver_output_status_v1_destroy(output_status_); } if (control_) { zriver_control_v1_destroy(control_); } } void Tags::handle_primary_clicked(uint32_t tag) { // Send river command to select tag on left mouse click 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) { 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_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_); zriver_command_callback_v1_add_listener(callback, &command_callback_listener_impl, nullptr); } return true; } void Tags::handle_focused_tags(uint32_t tags) { auto hide_vacant = config_["hide-vacant"].asBool(); for (size_t i = 0; i < buttons_.size(); ++i) { bool visible = buttons_[i].is_visible(); bool occupied = buttons_[i].get_style_context()->has_class("occupied"); bool urgent = buttons_[i].get_style_context()->has_class("urgent"); if ((1 << i) & tags) { if (hide_vacant && !visible) { buttons_[i].set_visible(true); } buttons_[i].get_style_context()->add_class("focused"); } else { if (hide_vacant && !(occupied || urgent)) { buttons_[i].set_visible(false); } buttons_[i].get_style_context()->remove_class("focused"); } } } void Tags::handle_view_tags(struct wl_array *view_tags) { uint32_t tags = 0; 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; } auto hide_vacant = config_["hide-vacant"].asBool(); for (size_t i = 0; i < buttons_.size(); ++i) { bool visible = buttons_[i].is_visible(); bool focused = buttons_[i].get_style_context()->has_class("focused"); bool urgent = buttons_[i].get_style_context()->has_class("urgent"); if ((1 << i) & tags) { if (hide_vacant && !visible) { buttons_[i].set_visible(true); } buttons_[i].get_style_context()->add_class("occupied"); } else { if (hide_vacant && !(focused || urgent)) { buttons_[i].set_visible(false); } buttons_[i].get_style_context()->remove_class("occupied"); } } } void Tags::handle_urgent_tags(uint32_t tags) { auto hide_vacant = config_["hide-vacant"].asBool(); for (size_t i = 0; i < buttons_.size(); ++i) { bool visible = buttons_[i].is_visible(); bool occupied = buttons_[i].get_style_context()->has_class("occupied"); bool focused = buttons_[i].get_style_context()->has_class("focused"); if ((1 << i) & tags) { if (hide_vacant && !visible) { buttons_[i].set_visible(true); } buttons_[i].get_style_context()->add_class("urgent"); } else { if (hide_vacant && !(occupied || focused)) { buttons_[i].set_visible(false); } buttons_[i].get_style_context()->remove_class("urgent"); } } } } /* namespace waybar::modules::river */ waybar-0.12.0/src/modules/river/window.cpp000066400000000000000000000112021475603165300204660ustar00rootroot00000000000000#include "modules/river/window.hpp" #include #include #include #include "client.hpp" 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_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_mode(void *data, struct zriver_seat_status_v1 *zriver_seat_status_v1, const char *mode) { // This module doesn't care } static const zriver_seat_status_v1_listener seat_status_listener_impl{ .focused_output = listen_focused_output, .unfocused_output = listen_unfocused_output, .focused_view = listen_focused_view, .mode = listen_mode, }; static void 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( 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 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) : 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); wl_registry_add_listener(registry, ®istry_listener_impl, this); wl_display_roundtrip(display); output_ = gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj()); if (!status_manager_) { spdlog::error("river_status_manager_v1 not advertised"); return; } if (!seat_) { spdlog::error("wl_seat not advertised"); } label_.hide(); // hide the label until populated ALabel::update(); seat_status_ = zriver_status_manager_v1_get_river_seat_status(status_manager_, seat_); zriver_seat_status_v1_add_listener(seat_status_, &seat_status_listener_impl, this); zriver_status_manager_v1_destroy(status_manager_); } Window::~Window() { if (seat_status_) { zriver_seat_status_v1_destroy(seat_status_); } } 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 // last focused view, and will get blank labels until they are brought into focus at least once. if (focused_output_ != output_) return; if (std::strcmp(title, "") == 0 || format_.empty()) { label_.hide(); // hide empty labels or labels with empty format } else { label_.show(); auto text = fmt::format(fmt::runtime(format_), Glib::Markup::escape_text(title).raw()); label_.set_markup(text); if (tooltipEnabled()) { label_.set_tooltip_markup(text); } } ALabel::update(); } 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(); } focused_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(); } } } /* namespace waybar::modules::river */ waybar-0.12.0/src/modules/simpleclock.cpp000066400000000000000000000021671475603165300203470ustar00rootroot00000000000000#include "modules/simpleclock.hpp" #include waybar::modules::Clock::Clock(const std::string& id, const Json::Value& config) : ALabel(config, "clock", id, "{:%H:%M}", 60) { thread_ = [this] { dp.emit(); auto now = std::chrono::system_clock::now(); /* difference with projected wakeup time */ auto diff = now.time_since_epoch() % interval_; /* sleep until the next projected time */ thread_.sleep_for(interval_ - diff); }; } auto waybar::modules::Clock::update() -> void { tzset(); // Update timezone information auto now = std::chrono::system_clock::now(); auto localtime = fmt::localtime(std::chrono::system_clock::to_time_t(now)); auto text = fmt::format(fmt::runtime(format_), localtime); label_.set_markup(text); if (tooltipEnabled()) { 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); } else { label_.set_tooltip_text(text); } } // Call parent update ALabel::update(); } waybar-0.12.0/src/modules/sndio.cpp000066400000000000000000000116301475603165300171510ustar00rootroot00000000000000#include "modules/sndio.hpp" #include #include #include #include #include namespace waybar::modules { 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; } self->set_desc(d, curval); } void onval(void *arg, unsigned int addr, unsigned int val) { auto self = static_cast(arg); self->put_val(addr, val); } auto Sndio::connect_to_sndio() -> void { hdl_ = sioctl_open(SIO_DEVANY, SIOCTL_READ | SIOCTL_WRITE, 0); if (hdl_ == nullptr) { throw std::runtime_error("sioctl_open() failed."); } if (sioctl_ondesc(hdl_, ondesc, this) == 0) { throw std::runtime_error("sioctl_ondesc() failed."); } if (sioctl_onval(hdl_, onval, this) == 0) { throw std::runtime_error("sioctl_onval() failed."); } pfds_.reserve(sioctl_nfds(hdl_)); } Sndio::Sndio(const std::string &id, const Json::Value &config) : ALabel(config, "sndio", id, "{volume}%", 1, false, true), hdl_(nullptr), pfds_(0), addr_(0), volume_(0), old_volume_(0), maxval_(0), muted_(false) { connect_to_sndio(); event_box_.show(); event_box_.add_events(Gdk::SCROLL_MASK | Gdk::SMOOTH_SCROLL_MASK | Gdk::BUTTON_PRESS_MASK); event_box_.signal_scroll_event().connect(sigc::mem_fun(*this, &Sndio::handleScroll)); event_box_.signal_button_press_event().connect(sigc::mem_fun(*this, &Sndio::handleToggle)); thread_ = [this] { dp.emit(); int nfds = sioctl_pollfd(hdl_, pfds_.data(), POLLIN); if (nfds == 0) { throw std::runtime_error("sioctl_pollfd() failed."); } while (poll(pfds_.data(), nfds, -1) < 0) { if (errno != EINTR) { throw std::runtime_error("poll() failed."); } } int revents = sioctl_revents(hdl_, pfds_.data()); if (revents & POLLHUP) { spdlog::warn("sndio disconnected!"); sioctl_close(hdl_); hdl_ = nullptr; // reconnection loop while (thread_.isRunning()) { try { connect_to_sndio(); } catch (std::runtime_error const &e) { // avoid leaking hdl_ if (hdl_) { sioctl_close(hdl_); hdl_ = nullptr; } // rate limiting for the retries thread_.sleep_for(interval_); continue; } spdlog::warn("sndio reconnected!"); break; } } }; } Sndio::~Sndio() { sioctl_close(hdl_); } auto Sndio::update() -> void { auto format = format_; unsigned int vol = 100. * static_cast(volume_) / static_cast(maxval_); if (volume_ == 0) { label_.get_style_context()->add_class("muted"); } else { label_.get_style_context()->remove_class("muted"); } auto text = fmt::format(fmt::runtime(format), fmt::arg("volume", vol), fmt::arg("raw_value", volume_)); if (text.empty()) { label_.hide(); } else { label_.set_markup(text); label_.show(); } ALabel::update(); } auto Sndio::set_desc(struct sioctl_desc *d, unsigned int val) -> void { std::string name{d->func}; std::string node_name{d->node0.name}; if (name == "level" && node_name == "output" && d->type == SIOCTL_NUM) { // store addr for output.level value, used in put_val addr_ = d->addr; maxval_ = d->maxval; volume_ = val; } } auto Sndio::put_val(unsigned int addr, unsigned int val) -> void { if (addr == addr_) { volume_ = val; } } 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()) { return AModule::handleScroll(e); } // only try to talk to sndio if connected if (hdl_ == nullptr) return true; auto dir = AModule::getScrollDir(e); if (dir == SCROLL_DIR::NONE) { return true; } int step = 5; if (config_["scroll-step"].isInt()) { step = config_["scroll-step"].asInt(); } int new_volume = volume_; if (muted_) { new_volume = old_volume_; } if (dir == SCROLL_DIR::UP) { new_volume += step; } else if (dir == SCROLL_DIR::DOWN) { new_volume -= step; } new_volume = std::clamp(new_volume, 0, static_cast(maxval_)); // quits muted mode if volume changes muted_ = false; sioctl_setval(hdl_, addr_, new_volume); return true; } 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); } // only try to talk to sndio if connected if (hdl_ == nullptr) return true; muted_ = !muted_; if (muted_) { // store old volume to be able to restore it later old_volume_ = volume_; sioctl_setval(hdl_, addr_, 0); } else { sioctl_setval(hdl_, addr_, old_volume_); } return true; } } /* namespace waybar::modules */ waybar-0.12.0/src/modules/sni/000077500000000000000000000000001475603165300161215ustar00rootroot00000000000000waybar-0.12.0/src/modules/sni/host.cpp000066400000000000000000000121141475603165300176010ustar00rootroot00000000000000#include "modules/sni/host.hpp" #include #include "util/scope_guard.hpp" namespace waybar::modules::SNI { Host::Host(const std::size_t id, const Json::Value& config, const Bar& bar, const std::function&)>& on_add, const std::function&)>& on_remove) : bus_name_("org.kde.StatusNotifierHost-" + std::to_string(getpid()) + "-" + std::to_string(id)), object_path_("/StatusNotifierHost/" + std::to_string(id)), bus_name_id_(Gio::DBus::own_name(Gio::DBus::BusType::BUS_TYPE_SESSION, bus_name_, sigc::mem_fun(*this, &Host::busAcquired))), config_(config), bar_(bar), on_add_(on_add), on_remove_(on_remove) {} Host::~Host() { if (bus_name_id_ > 0) { Gio::DBus::unown_name(bus_name_id_); bus_name_id_ = 0; } if (watcher_id_ > 0) { Gio::DBus::unwatch_name(watcher_id_); watcher_id_ = 0; } g_cancellable_cancel(cancellable_); g_clear_object(&cancellable_); g_clear_object(&watcher_); } void Host::busAcquired(const Glib::RefPtr& conn, Glib::ustring name) { watcher_id_ = Gio::DBus::watch_name(conn, "org.kde.StatusNotifierWatcher", sigc::mem_fun(*this, &Host::nameAppeared), sigc::mem_fun(*this, &Host::nameVanished)); } void Host::nameAppeared(const Glib::RefPtr& conn, const Glib::ustring name, const Glib::ustring& name_owner) { if (cancellable_ != nullptr) { // TODO return; } cancellable_ = g_cancellable_new(); sn_watcher_proxy_new(conn->gobj(), G_DBUS_PROXY_FLAGS_NONE, "org.kde.StatusNotifierWatcher", "/StatusNotifierWatcher", cancellable_, &Host::proxyReady, this); } void Host::nameVanished(const Glib::RefPtr& conn, const Glib::ustring name) { g_cancellable_cancel(cancellable_); g_clear_object(&cancellable_); g_clear_object(&watcher_); items_.clear(); } void Host::proxyReady(GObject* src, GAsyncResult* res, gpointer data) { GError* error = nullptr; waybar::util::ScopeGuard error_deleter([error]() { if (error != nullptr) { g_error_free(error); } }); SnWatcher* watcher = sn_watcher_proxy_new_finish(res, &error); if (g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) { spdlog::error("Host: {}", error->message); return; } auto host = static_cast(data); host->watcher_ = watcher; if (error != nullptr) { spdlog::error("Host: {}", error->message); return; } 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]() { if (error != nullptr) { g_error_free(error); } }); sn_watcher_call_register_host_finish(SN_WATCHER(src), res, &error); if (g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) { spdlog::error("Host: {}", error->message); return; } auto host = static_cast(data); if (error != nullptr) { spdlog::error("Host: {}", error->message); return; } g_signal_connect(host->watcher_, "item-registered", G_CALLBACK(&Host::itemRegistered), data); g_signal_connect(host->watcher_, "item-unregistered", G_CALLBACK(&Host::itemUnregistered), data); auto items = sn_watcher_dup_registered_items(host->watcher_); if (items != nullptr) { for (uint32_t i = 0; items[i] != nullptr; i += 1) { host->addRegisteredItem(items[i]); } } g_strfreev(items); } void Host::itemRegistered(SnWatcher* watcher, const gchar* service, gpointer data) { auto host = static_cast(data); host->addRegisteredItem(service); } void Host::itemUnregistered(SnWatcher* watcher, const gchar* service, gpointer data) { auto host = static_cast(data); 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); break; } } } std::tuple Host::getBusNameAndObjectPath(const std::string service) { auto it = service.find('/'); if (it != std::string::npos) { return {service.substr(0, it), service.substr(it)}; } return {service, "/StatusNotifierItem"}; } void Host::addRegisteredItem(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()); } } } // namespace waybar::modules::SNI waybar-0.12.0/src/modules/sni/item.cpp000066400000000000000000000423631475603165300175730ustar00rootroot00000000000000#include "modules/sni/item.hpp" #include #include #include #include #include #include #include "gdk/gdk.h" #include "util/format.hpp" #include "util/gtk_icon.hpp" template <> struct fmt::formatter : formatter { bool is_printable(const Glib::VariantBase& value) const { auto type = value.get_type_string(); /* Print only primitive (single character excluding 'v') and short complex types */ return (type.length() == 1 && islower(type[0]) && type[0] != 'v') || value.get_size() <= 32; } template auto format(const Glib::VariantBase& value, FormatContext& ctx) const { if (is_printable(value)) { return formatter::format(static_cast(value.print()), ctx); } else { return formatter::format(value.get_type_string(), ctx); } } }; 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) : bus_name(bn), object_path(op), icon_size(16), effective_icon_size(0), icon_theme(Gtk::IconTheme::create()), bar_(bar) { if (config["icon-size"].isUInt()) { icon_size = config["icon-size"].asUInt(); } if (config["smooth-scrolling-threshold"].isNumeric()) { scroll_threshold_ = config["smooth-scrolling-threshold"].asDouble(); } if (config["show-passive-items"].isBool()) { show_passive_ = config["show-passive-items"].asBool(); } auto& window = const_cast(bar).window; window.signal_configure_event().connect_notify(sigc::mem_fun(*this, &Item::onConfigure)); event_box.add(image); event_box.add_events(Gdk::BUTTON_PRESS_MASK | Gdk::SCROLL_MASK | Gdk::SMOOTH_SCROLL_MASK); event_box.signal_button_press_event().connect(sigc::mem_fun(*this, &Item::handleClick)); event_box.signal_scroll_event().connect(sigc::mem_fun(*this, &Item::handleScroll)); event_box.signal_enter_notify_event().connect(sigc::mem_fun(*this, &Item::handleMouseEnter)); event_box.signal_leave_notify_event().connect(sigc::mem_fun(*this, &Item::handleMouseLeave)); // initial visibility event_box.show_all(); event_box.set_visible(show_passive_); cancellable_ = Gio::Cancellable::create(); auto interface = Glib::wrap(sn_item_interface_info(), true); Gio::DBus::Proxy::create_for_bus(Gio::DBus::BusType::BUS_TYPE_SESSION, bus_name, object_path, SNI_INTERFACE_NAME, sigc::mem_fun(*this, &Item::proxyReady), cancellable_, interface); } bool Item::handleMouseEnter(GdkEventCrossing* const& e) { event_box.set_state_flags(Gtk::StateFlags::STATE_FLAG_PRELIGHT); return false; } bool Item::handleMouseLeave(GdkEventCrossing* const& e) { event_box.unset_state_flags(Gtk::StateFlags::STATE_FLAG_PRELIGHT); return false; } void Item::onConfigure(GdkEventConfigure* ev) { this->updateImage(); } void Item::proxyReady(Glib::RefPtr& result) { try { this->proxy_ = Gio::DBus::Proxy::create_for_bus_finish(result); /* Properties are already cached during object creation */ auto cached_properties = this->proxy_->get_cached_property_names(); for (const auto& name : cached_properties) { Glib::VariantBase value; this->proxy_->get_cached_property(value, name); setProperty(name, value); } this->proxy_->signal_signal().connect(sigc::mem_fun(*this, &Item::onSignal)); if (this->id.empty() || this->category.empty()) { spdlog::error("Invalid Status Notifier Item: {}, {}", bus_name, object_path); return; } this->updateImage(); } catch (const Glib::Error& err) { spdlog::error("Failed to create DBus Proxy for {} {}: {}", bus_name, object_path, err.what()); } catch (const std::exception& err) { spdlog::error("Failed to create DBus Proxy for {} {}: {}", bus_name, object_path, err.what()); } } template T get_variant(const Glib::VariantBase& value) { return Glib::VariantBase::cast_dynamic>(value).get(); } template <> ToolTip get_variant(const Glib::VariantBase& value) { ToolTip result; // Unwrap (sa(iiay)ss) auto container = value.cast_dynamic(value); result.icon_name = get_variant(container.get_child(0)); result.text = get_variant(container.get_child(2)); auto description = get_variant(container.get_child(3)); if (!description.empty()) { auto escapedDescription = Glib::Markup::escape_text(description); result.text = fmt::format("{}\n{}", result.text, escapedDescription); } return result; } void Item::setProperty(const Glib::ustring& name, Glib::VariantBase& value) { try { spdlog::trace("Set tray item property: {}.{} = {}", id.empty() ? bus_name : id, name, value); if (name == "Category") { category = get_variant(value); } else if (name == "Id") { id = get_variant(value); } else if (name == "Title") { title = get_variant(value); if (tooltip.text.empty()) { event_box.set_tooltip_markup(title); } } else if (name == "Status") { setStatus(get_variant(value)); } else if (name == "IconName") { icon_name = get_variant(value); } else if (name == "IconPixmap") { icon_pixmap = this->extractPixBuf(value.gobj()); } else if (name == "OverlayIconName") { overlay_icon_name = get_variant(value); } else if (name == "OverlayIconPixmap") { // TODO: overlay_icon_pixmap } else if (name == "AttentionIconName") { attention_icon_name = get_variant(value); } else if (name == "AttentionIconPixmap") { // TODO: attention_icon_pixmap } else if (name == "AttentionMovieName") { attention_movie_name = get_variant(value); } else if (name == "ToolTip") { tooltip = get_variant(value); if (!tooltip.text.empty()) { event_box.set_tooltip_markup(tooltip.text); } } else if (name == "IconThemePath") { icon_theme_path = get_variant(value); if (!icon_theme_path.empty()) { icon_theme->set_search_path({icon_theme_path}); } } else if (name == "Menu") { menu = get_variant(value); makeMenu(); } else if (name == "ItemIsMenu") { item_is_menu = get_variant(value); } } catch (const Glib::Error& err) { spdlog::warn("Failed to set tray item property: {}.{}, value = {}, err = {}", id.empty() ? bus_name : id, name, value, err.what()); } catch (const std::exception& err) { spdlog::warn("Failed to set tray item property: {}.{}, value = {}, err = {}", id.empty() ? bus_name : id, name, value, err.what()); } } void Item::setStatus(const Glib::ustring& value) { Glib::ustring lower = value.lowercase(); event_box.set_visible(show_passive_ || lower.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) { // convert status to dash-case for CSS lower = "needs-attention"; } style->add_class(lower); } void Item::getUpdatedProperties() { auto params = Glib::VariantContainerBase::create_tuple( {Glib::Variant::create(SNI_INTERFACE_NAME)}); proxy_->call("org.freedesktop.DBus.Properties.GetAll", sigc::mem_fun(*this, &Item::processUpdatedProperties), params); }; void Item::processUpdatedProperties(Glib::RefPtr& _result) { try { auto result = proxy_->call_finish(_result); // extract "a{sv}" from VariantContainerBase Glib::Variant> properties_variant; result.get_child(properties_variant); auto properties = properties_variant.get(); for (const auto& [name, value] : properties) { if (update_pending_.count(name.raw())) { setProperty(name, const_cast(value)); } } this->updateImage(); } catch (const Glib::Error& err) { spdlog::warn("Failed to update properties: {}", err.what()); } catch (const std::exception& err) { spdlog::warn("Failed to update properties: {}", err.what()); } update_pending_.clear(); } /** * Mapping from a signal name to a set of possibly changed properties. * Commented signals are not handled by the tray module at the moment. */ static const std::map> signal2props = { {"NewTitle", {"Title"}}, {"NewIcon", {"IconName", "IconPixmap"}}, // {"NewAttentionIcon", {"AttentionIconName", "AttentionIconPixmap", "AttentionMovieName"}}, // {"NewOverlayIcon", {"OverlayIconName", "OverlayIconPixmap"}}, {"NewIconThemePath", {"IconThemePath"}}, {"NewToolTip", {"ToolTip"}}, {"NewStatus", {"Status"}}, // {"XAyatanaNewLabel", {"XAyatanaLabel"}}, }; void Item::onSignal(const Glib::ustring& sender_name, const Glib::ustring& signal_name, const Glib::VariantContainerBase& arguments) { spdlog::trace("Tray item '{}' got signal {}", id, signal_name); auto changed = signal2props.find(signal_name.raw()); if (changed != signal2props.end()) { if (update_pending_.empty()) { /* Debounce signals and schedule update of all properties. * Based on behavior of Plasma dataengine for StatusNotifierItem. */ Glib::signal_timeout().connect_once(sigc::mem_fun(*this, &Item::getUpdatedProperties), UPDATE_DEBOUNCE_TIME); } update_pending_.insert(changed->second.begin(), changed->second.end()); } } static void pixbuf_data_deleter(const guint8* data) { g_free((void*)data); } Glib::RefPtr Item::extractPixBuf(GVariant* variant) { GVariantIter* it; g_variant_get(variant, "a(iiay)", &it); if (it == nullptr) { return Glib::RefPtr{}; } GVariant* val; gint lwidth = 0; gint lheight = 0; gint width; gint height; guchar* array = nullptr; while (g_variant_iter_loop(it, "(ii@ay)", &width, &height, &val)) { if (width > 0 && height > 0 && val != nullptr && width * height > lwidth * lheight) { auto size = g_variant_get_size(val); /* Sanity check */ if (size == 4U * width * height) { /* Find the largest image */ gconstpointer data = g_variant_get_data(val); if (data != nullptr) { 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 lwidth = width; lheight = height; } } } } 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); } return Glib::RefPtr{}; } void Item::updateImage() { auto pixbuf = getIconPixbuf(); 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) { 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); } 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())); } } // Return the pixmap only if an icon for the given name could not be found. if (icon_pixmap) { return icon_pixmap; } if (icon_name.empty()) { spdlog::error("Item '{}': No icon name or pixmap given.", id); } else { spdlog::error("Item '{}': Could not find an icon named '{}' and no pixmap given.", id, icon_name); } return getIconByName("image-missing", getScaledIconSize()); } Glib::RefPtr Item::getIconByName(const std::string& name, int request_size) { icon_theme->rescan_if_needed(); 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); } return DefaultGtkIconThemeWrapper::load_icon(name.c_str(), request_size, Gtk::IconLookupFlags::ICON_LOOKUP_FORCE_SIZE); } double Item::getScaledIconSize() { // apply the scale factor from the Gtk window to the requested icon size return icon_size * image.get_scale_factor(); } void Item::onMenuDestroyed(Item* self, GObject* old_menu_pointer) { if (old_menu_pointer == reinterpret_cast(self->dbus_menu)) { self->gtk_menu = nullptr; self->dbus_menu = nullptr; } } void Item::makeMenu() { if (gtk_menu == nullptr && !menu.empty()) { dbus_menu = dbusmenu_gtkmenu_new(bus_name.data(), menu.data()); if (dbus_menu != nullptr) { g_object_ref_sink(G_OBJECT(dbus_menu)); g_object_weak_ref(G_OBJECT(dbus_menu), (GWeakNotify)onMenuDestroyed, this); gtk_menu = Glib::wrap(GTK_MENU(dbus_menu)); gtk_menu->attach_to_widget(event_box); } } } bool Item::handleClick(GdkEventButton* const& ev) { auto parameters = Glib::VariantContainerBase::create_tuple( {Glib::Variant::create(ev->x_root + bar_.x_global), Glib::Variant::create(ev->y_root + bar_.y_global)}); if ((ev->button == 1 && item_is_menu) || ev->button == 3) { makeMenu(); if (gtk_menu != nullptr) { #if GTK_CHECK_VERSION(3, 22, 0) gtk_menu->popup_at_pointer(reinterpret_cast(ev)); #else gtk_menu->popup(ev->button, ev->time); #endif return true; } else { proxy_->call("ContextMenu", parameters); return true; } } else if (ev->button == 1) { proxy_->call("Activate", parameters); return true; } else if (ev->button == 2) { proxy_->call("SecondaryActivate", parameters); return true; } return false; } bool Item::handleScroll(GdkEventScroll* const& ev) { int dx = 0, dy = 0; switch (ev->direction) { case GDK_SCROLL_UP: dy = -1; break; case GDK_SCROLL_DOWN: dy = 1; break; case GDK_SCROLL_LEFT: dx = -1; break; case GDK_SCROLL_RIGHT: dx = 1; break; case GDK_SCROLL_SMOOTH: distance_scrolled_x_ += ev->delta_x; distance_scrolled_y_ += ev->delta_y; // check against the configured threshold and ensure that the absolute value >= 1 if (distance_scrolled_x_ > scroll_threshold_) { dx = (int)lround(std::max(distance_scrolled_x_, 1.0)); distance_scrolled_x_ = 0; } else if (distance_scrolled_x_ < -scroll_threshold_) { dx = (int)lround(std::min(distance_scrolled_x_, -1.0)); distance_scrolled_x_ = 0; } if (distance_scrolled_y_ > scroll_threshold_) { dy = (int)lround(std::max(distance_scrolled_y_, 1.0)); distance_scrolled_y_ = 0; } else if (distance_scrolled_y_ < -scroll_threshold_) { dy = (int)lround(std::min(distance_scrolled_y_, -1.0)); distance_scrolled_y_ = 0; } break; } if (dx != 0) { auto parameters = Glib::VariantContainerBase::create_tuple( {Glib::Variant::create(dx), Glib::Variant::create("horizontal")}); proxy_->call("Scroll", parameters); } if (dy != 0) { auto parameters = Glib::VariantContainerBase::create_tuple( {Glib::Variant::create(dy), Glib::Variant::create("vertical")}); proxy_->call("Scroll", parameters); } return true; } } // namespace waybar::modules::SNI waybar-0.12.0/src/modules/sni/tray.cpp000066400000000000000000000024231475603165300176050ustar00rootroot00000000000000#include "modules/sni/tray.hpp" #include namespace waybar::modules::SNI { Tray::Tray(const std::string& id, const Bar& bar, const Json::Value& config) : AModule(config, "tray", id), box_(bar.orientation, 0), watcher_(SNI::Watcher::getInstance()), host_(nb_hosts_, config, bar, std::bind(&Tray::onAdd, this, std::placeholders::_1), std::bind(&Tray::onRemove, this, std::placeholders::_1)) { box_.set_name("tray"); event_box_.add(box_); if (!id.empty()) { box_.get_style_context()->add_class(id); } box_.get_style_context()->add_class(MODULE_CLASS); if (config_["spacing"].isUInt()) { box_.set_spacing(config_["spacing"].asUInt()); } nb_hosts_ += 1; 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); } dp.emit(); } void Tray::onRemove(std::unique_ptr& item) { box_.remove(item->event_box); dp.emit(); } auto Tray::update() -> void { // Show tray only when items are available event_box_.set_visible(!box_.get_children().empty()); // Call parent update AModule::update(); } } // namespace waybar::modules::SNI waybar-0.12.0/src/modules/sni/watcher.cpp000066400000000000000000000161171475603165300202700ustar00rootroot00000000000000#include "modules/sni/watcher.hpp" #include #include "util/scope_guard.hpp" using namespace waybar::modules::SNI; Watcher::Watcher() : bus_name_id_(Gio::DBus::own_name(Gio::DBus::BusType::BUS_TYPE_SESSION, "org.kde.StatusNotifierWatcher", sigc::mem_fun(*this, &Watcher::busAcquired), Gio::DBus::SlotNameAcquired(), Gio::DBus::SlotNameLost(), Gio::DBus::BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT | Gio::DBus::BUS_NAME_OWNER_FLAGS_REPLACE)), watcher_(sn_watcher_skeleton_new()) {} Watcher::~Watcher() { if (hosts_ != nullptr) { g_slist_free_full(hosts_, gfWatchFree); hosts_ = nullptr; } if (items_ != nullptr) { g_slist_free_full(items_, gfWatchFree); items_ = nullptr; } Gio::DBus::unown_name(bus_name_id_); auto iface = G_DBUS_INTERFACE_SKELETON(watcher_); g_dbus_interface_skeleton_unexport(iface); } void Watcher::busAcquired(const Glib::RefPtr& conn, Glib::ustring name) { GError* error = nullptr; waybar::util::ScopeGuard error_deleter([error]() { if (error) { g_error_free(error); } }); g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(watcher_), conn->gobj(), "/StatusNotifierWatcher", &error); if (error != nullptr) { // Don't print an error when a watcher is already present if (error->code != 2) { spdlog::error("Watcher: {}", error->message); } return; } g_signal_connect_swapped(watcher_, "handle-register-item", G_CALLBACK(&Watcher::handleRegisterItem), this); g_signal_connect_swapped(watcher_, "handle-register-host", G_CALLBACK(&Watcher::handleRegisterHost), this); } gboolean Watcher::handleRegisterHost(Watcher* obj, GDBusMethodInvocation* invocation, const gchar* service) { const gchar* bus_name = service; const gchar* object_path = "/StatusNotifierHost"; if (*service == '/') { bus_name = g_dbus_method_invocation_get_sender(invocation); object_path = service; } if (g_dbus_is_name(bus_name) == FALSE) { g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "D-Bus bus name '%s' is not valid", bus_name); return TRUE; } auto watch = gfWatchFind(obj->hosts_, bus_name, object_path); 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); return TRUE; } watch = gfWatchNew(GF_WATCH_TYPE_HOST, service, bus_name, object_path, obj); obj->hosts_ = g_slist_prepend(obj->hosts_, watch); if (!sn_watcher_get_is_host_registered(obj->watcher_)) { sn_watcher_set_is_host_registered(obj->watcher_, TRUE); sn_watcher_emit_host_registered(obj->watcher_); } sn_watcher_complete_register_host(obj->watcher_, invocation); return TRUE; } gboolean Watcher::handleRegisterItem(Watcher* obj, GDBusMethodInvocation* invocation, const gchar* service) { const gchar* bus_name = service; const gchar* object_path = "/StatusNotifierItem"; if (*service == '/') { bus_name = g_dbus_method_invocation_get_sender(invocation); object_path = service; } if (g_dbus_is_name(bus_name) == FALSE) { g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "D-Bus bus name '%s' is not valid", bus_name); return TRUE; } auto watch = gfWatchFind(obj->items_, bus_name, object_path); if (watch != nullptr) { g_warning("Status Notifier Item with bus name '%s' and object path '%s' is already registered", bus_name, object_path); sn_watcher_complete_register_item(obj->watcher_, invocation); return TRUE; } watch = gfWatchNew(GF_WATCH_TYPE_ITEM, service, bus_name, object_path, obj); obj->items_ = g_slist_prepend(obj->items_, watch); obj->updateRegisteredItems(obj->watcher_); gchar* tmp = g_strdup_printf("%s%s", bus_name, object_path); sn_watcher_emit_item_registered(obj->watcher_, tmp); g_free(tmp); sn_watcher_complete_register_item(obj->watcher_, invocation); return TRUE; } Watcher::GfWatch* Watcher::gfWatchFind(GSList* list, const gchar* bus_name, const gchar* object_path) { for (GSList* l = list; l != nullptr; l = g_slist_next(l)) { auto watch = static_cast(l->data); if (g_strcmp0(watch->bus_name, bus_name) == 0 && g_strcmp0(watch->object_path, object_path) == 0) { return watch; } } return nullptr; } void Watcher::gfWatchFree(gpointer data) { auto watch = static_cast(data); if (watch->watch_id > 0) { g_bus_unwatch_name(watch->watch_id); } g_free(watch->service); g_free(watch->bus_name); g_free(watch->object_path); g_free(watch); } Watcher::GfWatch* Watcher::gfWatchNew(GfWatchType type, const gchar* service, const gchar* bus_name, const gchar* object_path, Watcher* watcher) { GfWatch* watch = g_new0(GfWatch, 1); watch->type = type; watch->watcher = watcher; watch->service = g_strdup(service); watch->bus_name = g_strdup(bus_name); watch->object_path = g_strdup(object_path); watch->watch_id = g_bus_watch_name(G_BUS_TYPE_SESSION, bus_name, G_BUS_NAME_WATCHER_FLAGS_NONE, nullptr, &Watcher::nameVanished, watch, nullptr); return watch; } void Watcher::nameVanished(GDBusConnection* connection, const char* name, gpointer data) { auto watch = static_cast(data); if (watch->type == GF_WATCH_TYPE_HOST) { 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_); } } else if (watch->type == GF_WATCH_TYPE_ITEM) { watch->watcher->items_ = g_slist_remove(watch->watcher->items_, watch); watch->watcher->updateRegisteredItems(watch->watcher->watcher_); gchar* tmp = g_strdup_printf("%s%s", watch->bus_name, watch->object_path); sn_watcher_emit_item_unregistered(watch->watcher->watcher_, tmp); g_free(tmp); } } void Watcher::updateRegisteredItems(SnWatcher* obj) { GVariantBuilder builder; g_variant_builder_init(&builder, G_VARIANT_TYPE("as")); for (GSList* l = items_; l != nullptr; l = g_slist_next(l)) { auto watch = static_cast(l->data); gchar* item = g_strdup_printf("%s%s", watch->bus_name, watch->object_path); g_variant_builder_add(&builder, "s", item); g_free(item); } GVariant* variant = g_variant_builder_end(&builder); const gchar** items = g_variant_get_strv(variant, nullptr); sn_watcher_set_registered_items(obj, items); g_variant_unref(variant); g_free(items); } waybar-0.12.0/src/modules/sway/000077500000000000000000000000001475603165300163135ustar00rootroot00000000000000waybar-0.12.0/src/modules/sway/bar.cpp000066400000000000000000000163451475603165300175740ustar00rootroot00000000000000#include "modules/sway/bar.hpp" #include #include #include #include "bar.hpp" #include "modules/sway/ipc/ipc.hpp" namespace waybar::modules::sway { BarIpcClient::BarIpcClient(waybar::Bar& bar) : bar_{bar} { { sigc::connection handle = ipc_.signal_cmd.connect(sigc::mem_fun(*this, &BarIpcClient::onInitialConfig)); ipc_.sendCmd(IPC_GET_BAR_CONFIG, bar_.bar_id); handle.disconnect(); } Json::Value subscribe_events{Json::arrayValue}; subscribe_events.append("bar_state_update"); subscribe_events.append("barconfig_update"); bool has_mode = isModuleEnabled("sway/mode"); bool has_workspaces = isModuleEnabled("sway/workspaces"); if (has_mode) { subscribe_events.append("mode"); } if (has_workspaces) { subscribe_events.append("workspace"); } if (has_mode || has_workspaces) { subscribe_events.append("binding"); } modifier_reset_ = bar.config.get("modifier-reset", "press").asString(); signal_config_.connect(sigc::mem_fun(*this, &BarIpcClient::onConfigUpdate)); signal_visible_.connect(sigc::mem_fun(*this, &BarIpcClient::onVisibilityUpdate)); signal_urgency_.connect(sigc::mem_fun(*this, &BarIpcClient::onUrgencyUpdate)); signal_mode_.connect(sigc::mem_fun(*this, &BarIpcClient::onModeUpdate)); // Subscribe to non bar events to determine if the modifier key press is followed by another // action. std::ostringstream oss_events; oss_events << subscribe_events; ipc_.subscribe(oss_events.str()); ipc_.signal_event.connect(sigc::mem_fun(*this, &BarIpcClient::onIpcEvent)); ipc_.signal_cmd.connect(sigc::mem_fun(*this, &BarIpcClient::onCmd)); // Launch worker ipc_.setWorker([this] { try { ipc_.handleEvent(); } catch (const std::exception& e) { spdlog::error("BarIpcClient::handleEvent {}", e.what()); } }); } bool BarIpcClient::isModuleEnabled(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) { if (module.asString().rfind(name, 0) == 0) { return true; } } } } return false; } struct swaybar_config parseConfig(const Json::Value& payload) { swaybar_config conf; if (auto id = payload["id"]; id.isString()) { conf.id = id.asString(); } if (auto mode = payload["mode"]; mode.isString()) { conf.mode = mode.asString(); } if (auto hs = payload["hidden_state"]; hs.isString()) { conf.hidden_state = hs.asString(); } return conf; } void BarIpcClient::onInitialConfig(const struct Ipc::ipc_response& res) { auto payload = parser_.parse(res.payload); if (auto success = payload.get("success", true); !success.asBool()) { auto err = payload.get("error", "Unknown error"); throw std::runtime_error(err.asString()); } auto config = parseConfig(payload); onConfigUpdate(config); } void BarIpcClient::onIpcEvent(const struct Ipc::ipc_response& res) { try { auto payload = parser_.parse(res.payload); switch (res.type) { case IPC_EVENT_WORKSPACE: if (payload.isMember("change")) { // only check and send signal if the workspace update reason was because of a urgent // change if (payload["change"] == "urgent") { auto urgent = payload["current"]["urgent"]; if (urgent.asBool()) { // Event for a new urgency, update the visibly signal_urgency_(true); } else if (!urgent.asBool() && visible_by_urgency_) { // Event clearing an urgency, bar is visible, check if another workspace still has // the urgency hint set ipc_.sendCmd(IPC_GET_WORKSPACES); } } modifier_no_action_ = false; } break; case IPC_EVENT_MODE: if (payload.isMember("change")) { signal_mode_(payload["change"] != "default"); modifier_no_action_ = false; } break; case IPC_EVENT_BINDING: modifier_no_action_ = false; break; case IPC_EVENT_BAR_STATE_UPDATE: case IPC_EVENT_BARCONFIG_UPDATE: if (auto id = payload["id"]; id.isString() && id.asString() != bar_.bar_id) { spdlog::trace("swaybar ipc: ignore event for {}", id.asString()); return; } if (payload.isMember("visible_by_modifier")) { // visibility change for hidden bar signal_visible_(payload["visible_by_modifier"].asBool()); } else { // configuration update auto config = parseConfig(payload); signal_config_(std::move(config)); } break; } } catch (const std::exception& e) { spdlog::error("BarIpcClient::onEvent {}", e.what()); } } void BarIpcClient::onCmd(const struct Ipc::ipc_response& res) { if (res.type == IPC_GET_WORKSPACES) { try { auto payload = parser_.parse(res.payload); for (auto& ws : payload) { if (ws["urgent"].asBool()) { spdlog::debug("Found workspace {} with urgency set. Stopping search.", ws["name"]); // Found one workspace with urgency set, signal bar visibility signal_urgency_(true); return; } } // Command to get workspaces was sent after a change in workspaces was based on "urgent", // if no workspace has this flag set to true, all flags must be cleared. signal_urgency_(false); } catch (const std::exception& e) { spdlog::error("Bar: {}", e.what()); } } } void BarIpcClient::onConfigUpdate(const swaybar_config& config) { spdlog::info("config update for {}: id {}, mode {}, hidden_state {}", bar_.bar_id, config.id, config.mode, config.hidden_state); bar_config_ = config; update(); } void BarIpcClient::onModeUpdate(bool visible_by_mode) { spdlog::debug("mode update for {}: {}", bar_.bar_id, visible_by_mode); visible_by_mode_ = visible_by_mode; update(); } void BarIpcClient::onVisibilityUpdate(bool visible_by_modifier) { spdlog::debug("visibility update for {}: {}", bar_.bar_id, visible_by_modifier); visible_by_modifier_ = visible_by_modifier; if (visible_by_modifier) { modifier_no_action_ = true; } // Clear on either press or release depending on bar_.bar_config_.action value. // For the check on release, make sure that the modifier key was not used for another action. if (((modifier_reset_ == "press" && visible_by_modifier_) || (modifier_reset_ == "release" && !visible_by_modifier_ && modifier_no_action_))) { // Clear the flags to hide the bar. visible_by_urgency_ = false; visible_by_mode_ = false; } update(); } void BarIpcClient::onUrgencyUpdate(bool visible_by_urgency) { spdlog::debug("urgency update for {}: {}", bar_.bar_id, visible_by_urgency); visible_by_urgency_ = visible_by_urgency; update(); } void BarIpcClient::update() { bool visible = visible_by_modifier_ || visible_by_mode_ || visible_by_urgency_; if (bar_config_.mode == "invisible") { visible = false; } else if (bar_config_.mode != "hide" || bar_config_.hidden_state != "hide") { visible = true; } bar_.setMode(visible ? bar_config_.mode : Bar::MODE_INVISIBLE); } } // namespace waybar::modules::sway waybar-0.12.0/src/modules/sway/ipc/000077500000000000000000000000001475603165300170665ustar00rootroot00000000000000waybar-0.12.0/src/modules/sway/ipc/client.cpp000066400000000000000000000104001475603165300210430ustar00rootroot00000000000000#include "modules/sway/ipc/client.hpp" #include #include #include namespace waybar::modules::sway { Ipc::Ipc() { const std::string& socketPath = getSocketPath(); fd_ = open(socketPath); fd_event_ = open(socketPath); } Ipc::~Ipc() { thread_.stop(); if (fd_ > 0) { // To fail the IPC header 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; } } void Ipc::setWorker(std::function&& func) { thread_ = func; } const std::string Ipc::getSocketPath() const { const char* env = getenv("SWAYSOCK"); if (env != nullptr) { return std::string(env); } std::string str; { std::string str_buf; FILE* in; char buf[512] = {0}; if ((in = popen("sway --get-socketpath 2>/dev/null", "r")) == nullptr) { throw std::runtime_error("Failed to get socket path"); } while (fgets(buf, sizeof(buf), in) != nullptr) { str_buf.append(buf, sizeof(buf)); } pclose(in); str = str_buf; if (str.empty()) { throw std::runtime_error("Socket path is empty"); } } if (str.back() == '\n') { str.pop_back(); } return str; } int Ipc::open(const std::string& socketPath) const { int32_t fd = socket(AF_UNIX, SOCK_STREAM, 0); if (fd == -1) { throw std::runtime_error("Unable to open Unix socket"); } (void)fcntl(fd, F_SETFD, FD_CLOEXEC); struct sockaddr_un addr; memset(&addr, 0, sizeof(struct sockaddr_un)); addr.sun_family = AF_UNIX; 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(fd, reinterpret_cast(&addr), l) == -1) { throw std::runtime_error("Unable to connect to Sway"); } return fd; } struct Ipc::ipc_response Ipc::recv(int fd) { std::string header; header.resize(ipc_header_size_); auto data32 = reinterpret_cast(header.data() + ipc_magic_.size()); size_t total = 0; while (total < ipc_header_size_) { auto res = ::recv(fd, header.data() + total, ipc_header_size_ - total, 0); if (fd_event_ == -1 || fd_ == -1) { // IPC is closed so just return an empty response return {0, 0, ""}; } if (res <= 0) { throw std::runtime_error("Unable to receive IPC header"); } total += res; } auto magic = std::string(header.data(), header.data() + ipc_magic_.size()); if (magic != ipc_magic_) { throw std::runtime_error("Invalid IPC magic"); } total = 0; std::string payload; payload.resize(data32[0]); while (total < data32[0]) { auto res = ::recv(fd, payload.data() + total, data32[0] - total, 0); if (res < 0) { if (errno == EINTR || errno == EAGAIN) { continue; } throw std::runtime_error("Unable to receive IPC payload"); } total += res; } return {data32[0], data32[1], &payload.front()}; } struct Ipc::ipc_response Ipc::send(int fd, uint32_t type, const std::string& payload) { std::string header; header.resize(ipc_header_size_); auto data32 = reinterpret_cast(header.data() + ipc_magic_.size()); memcpy(header.data(), ipc_magic_.c_str(), ipc_magic_.size()); data32[0] = payload.size(); data32[1] = type; if (::send(fd, header.data(), ipc_header_size_, 0) == -1) { throw std::runtime_error("Unable to send IPC header"); } if (::send(fd, payload.c_str(), payload.size(), 0) == -1) { throw std::runtime_error("Unable to send IPC payload"); } return Ipc::recv(fd); } void Ipc::sendCmd(uint32_t type, const std::string& payload) { std::lock_guard lock(mutex_); const auto res = Ipc::send(fd_, type, payload); signal_cmd.emit(res); } void Ipc::subscribe(const std::string& payload) { auto res = Ipc::send(fd_event_, IPC_SUBSCRIBE, payload); if (res.payload != "{\"success\": true}") { throw std::runtime_error("Unable to subscribe ipc event"); } } void Ipc::handleEvent() { const auto res = Ipc::recv(fd_event_); signal_event.emit(res); } } // namespace waybar::modules::sway waybar-0.12.0/src/modules/sway/language.cpp000066400000000000000000000173461475603165300206150ustar00rootroot00000000000000#include "modules/sway/language.hpp" #include #include #include #include #include #include #include #include "modules/sway/ipc/ipc.hpp" #include "util/string.hpp" namespace waybar::modules::sway { const std::string Language::XKB_LAYOUT_NAMES_KEY = "xkb_layout_names"; const std::string Language::XKB_ACTIVE_LAYOUT_NAME_KEY = "xkb_active_layout_name"; Language::Language(const std::string& id, const Json::Value& config) : ALabel(config, "language", id, "{}", 0, true) { 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); } if (format_.find("{shortDescription}") != std::string::npos) { displayed_short_flag |= static_cast(DispayedShortFlag::ShortDescription); } if (config.isMember("tooltip-format")) { tooltip_format_ = config["tooltip-format"].asString(); } ipc_.subscribe(R"(["input"])"); ipc_.signal_event.connect(sigc::mem_fun(*this, &Language::onEvent)); ipc_.signal_cmd.connect(sigc::mem_fun(*this, &Language::onCmd)); ipc_.sendCmd(IPC_GET_INPUTS); // Launch worker ipc_.setWorker([this] { try { ipc_.handleEvent(); } catch (const std::exception& e) { spdlog::error("Language: {}", e.what()); } }); dp.emit(); } void Language::onCmd(const struct Ipc::ipc_response& res) { if (res.type != IPC_GET_INPUTS) { return; } try { 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 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; max_id = i; } } for (const auto& layout : payload[max_id][XKB_LAYOUT_NAMES_KEY]) { used_layouts.push_back(layout.asString()); } init_layouts_map(used_layouts); set_current_layout(payload[max_id][XKB_ACTIVE_LAYOUT_NAME_KEY].asString()); dp.emit(); } catch (const std::exception& e) { spdlog::error("Language: {}", e.what()); } } void Language::onEvent(const struct Ipc::ipc_response& res) { if (res.type != IPC_EVENT_INPUT) { return; } 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()); } dp.emit(); } catch (const std::exception& e) { spdlog::error("Language: {}", e.what()); } } auto Language::update() -> void { std::lock_guard lock(mutex_); if (hide_single_ && layouts_map_.size() <= 1) { event_box_.hide(); return; } auto display_layout = trim(fmt::format( fmt::runtime(format_), fmt::arg("short", layout_.short_name), fmt::arg("shortDescription", layout_.short_description), fmt::arg("long", layout_.full_name), fmt::arg("variant", layout_.variant), fmt::arg("flag", layout_.country_flag()))); label_.set_markup(display_layout); if (tooltipEnabled()) { if (tooltip_format_ != "") { auto tooltip_display_layout = trim( fmt::format(fmt::runtime(tooltip_format_), fmt::arg("short", layout_.short_name), fmt::arg("shortDescription", layout_.short_description), fmt::arg("long", layout_.full_name), fmt::arg("variant", layout_.variant), fmt::arg("flag", layout_.country_flag()))); label_.set_tooltip_markup(tooltip_display_layout); } else { label_.set_tooltip_markup(display_layout); } } event_box_.show(); // Call parent update ALabel::update(); } auto Language::set_current_layout(std::string current_layout) -> void { label_.get_style_context()->remove_class(layout_.short_name); layout_ = layouts_map_[current_layout]; label_.get_style_context()->add_class(layout_.short_name); } auto Language::init_layouts_map(const std::vector& used_layouts) -> void { std::map> found_by_short_names; XKBContext xkb_context; auto layout = xkb_context.next_layout(); for (; layout != nullptr; layout = xkb_context.next_layout()) { if (std::find(used_layouts.begin(), used_layouts.end(), layout->full_name) == used_layouts.end()) { continue; } if (!is_variant_displayed) { auto short_name = layout->short_name; if (found_by_short_names.count(short_name) > 0) { found_by_short_names[short_name].push_back(layout); } else { found_by_short_names[short_name] = {layout}; } } layouts_map_.emplace(layout->full_name, *layout); } if (is_variant_displayed || found_by_short_names.size() == 0) { return; } std::map short_name_to_number_map; for (const auto& used_layout_name : used_layouts) { auto found = layouts_map_.find(used_layout_name); if (found == layouts_map_.end()) continue; auto used_layout = &found->second; auto layouts_with_same_name_list = found_by_short_names[used_layout->short_name]; if (layouts_with_same_name_list.size() < 2) { continue; } if (short_name_to_number_map.count(used_layout->short_name) == 0) { short_name_to_number_map[used_layout->short_name] = 1; } if (displayed_short_flag != static_cast(0)) { int& number = short_name_to_number_map[used_layout->short_name]; used_layout->short_name = used_layout->short_name + std::to_string(number); used_layout->short_description = used_layout->short_description + std::to_string(number); ++number; } } } Language::XKBContext::XKBContext() { context_ = rxkb_context_new(RXKB_CONTEXT_LOAD_EXOTIC_RULES); rxkb_context_parse_default_ruleset(context_); } auto Language::XKBContext::next_layout() -> Layout* { if (xkb_layout_ == nullptr) { xkb_layout_ = rxkb_layout_first(context_); } else { xkb_layout_ = rxkb_layout_next(xkb_layout_); } if (xkb_layout_ == nullptr) { return nullptr; } auto description = std::string(rxkb_layout_get_description(xkb_layout_)); auto name = std::string(rxkb_layout_get_name(xkb_layout_)); auto variant_ = rxkb_layout_get_variant(xkb_layout_); std::string variant = variant_ == nullptr ? "" : std::string(variant_); auto short_description_ = rxkb_layout_get_brief(xkb_layout_); std::string short_description; if (short_description_ != nullptr) { short_description = std::string(short_description_); base_layouts_by_name_.emplace(name, xkb_layout_); } else { auto base_layout = base_layouts_by_name_[name]; short_description = base_layout == nullptr ? "" : std::string(rxkb_layout_get_brief(base_layout)); } delete layout_; layout_ = new Layout{description, name, variant, short_description}; return layout_; } Language::XKBContext::~XKBContext() { rxkb_context_unref(context_); delete layout_; } std::string Language::Layout::country_flag() const { if (short_name.size() != 2) return ""; unsigned char result[] = "\xf0\x9f\x87\x00\xf0\x9f\x87\x00"; result[3] = short_name[0] + 0x45; result[7] = short_name[1] + 0x45; // Check if both emojis are in A-Z symbol bounds if (result[3] < 0xa6 || result[3] > 0xbf) return ""; if (result[7] < 0xa6 || result[7] > 0xbf) return ""; return std::string{reinterpret_cast(result)}; } } // namespace waybar::modules::sway waybar-0.12.0/src/modules/sway/mode.cpp000066400000000000000000000025271475603165300177510ustar00rootroot00000000000000#include "modules/sway/mode.hpp" #include namespace waybar::modules::sway { Mode::Mode(const std::string& id, const Json::Value& config) : ALabel(config, "mode", id, "{}", 0, true) { ipc_.subscribe(R"(["mode"])"); ipc_.signal_event.connect(sigc::mem_fun(*this, &Mode::onEvent)); // Launch worker ipc_.setWorker([this] { try { ipc_.handleEvent(); } catch (const std::exception& e) { spdlog::error("Mode: {}", e.what()); } }); dp.emit(); } void Mode::onEvent(const struct Ipc::ipc_response& res) { try { std::lock_guard lock(mutex_); auto payload = parser_.parse(res.payload); if (payload["change"] != "default") { if (payload["pango_markup"].asBool()) { mode_ = payload["change"].asString(); } else { mode_ = Glib::Markup::escape_text(payload["change"].asString()); } } else { mode_.clear(); } dp.emit(); } catch (const std::exception& e) { spdlog::error("Mode: {}", e.what()); } } auto Mode::update() -> void { if (mode_.empty()) { event_box_.hide(); } else { label_.set_markup(fmt::format(fmt::runtime(format_), mode_)); if (tooltipEnabled()) { label_.set_tooltip_text(mode_); } event_box_.show(); } // Call parent update ALabel::update(); } } // namespace waybar::modules::sway waybar-0.12.0/src/modules/sway/scratchpad.cpp000066400000000000000000000053361475603165300211420ustar00rootroot00000000000000#include "modules/sway/scratchpad.hpp" #include #include namespace waybar::modules::sway { Scratchpad::Scratchpad(const std::string& id, const Json::Value& config) : ALabel(config, "scratchpad", id, config["format"].isString() ? config["format"].asString() : "{icon} {count}"), tooltip_format_(config_["tooltip-format"].isString() ? config_["tooltip-format"].asString() : "{app}: {title}"), show_empty_(config_["show-empty"].isBool() ? config_["show-empty"].asBool() : false), tooltip_enabled_(config_["tooltip"].isBool() ? config_["tooltip"].asBool() : true), tooltip_text_(""), count_(0) { ipc_.subscribe(R"(["window"])"); ipc_.signal_event.connect(sigc::mem_fun(*this, &Scratchpad::onEvent)); ipc_.signal_cmd.connect(sigc::mem_fun(*this, &Scratchpad::onCmd)); getTree(); ipc_.setWorker([this] { try { ipc_.handleEvent(); } catch (const std::exception& e) { spdlog::error("Scratchpad: {}", e.what()); } }); } auto Scratchpad::update() -> void { if (count_ || show_empty_) { event_box_.show(); label_.set_markup( fmt::format(fmt::runtime(format_), fmt::arg("icon", getIcon(count_, "", config_["format-icons"].size())), fmt::arg("count", count_))); if (tooltip_enabled_) { label_.set_tooltip_markup(tooltip_text_); } } else { event_box_.hide(); } if (count_) { label_.get_style_context()->remove_class("empty"); } else { label_.get_style_context()->add_class("empty"); } ALabel::update(); } auto Scratchpad::getTree() -> void { try { ipc_.sendCmd(IPC_GET_TREE); } catch (const std::exception& e) { spdlog::error("Scratchpad: {}", e.what()); } } auto Scratchpad::onCmd(const struct Ipc::ipc_response& res) -> void { try { std::lock_guard lock(mutex_); auto tree = parser_.parse(res.payload); count_ = tree["nodes"][0]["nodes"][0]["floating_nodes"].size(); if (tooltip_enabled_) { tooltip_text_.clear(); for (const auto& window : tree["nodes"][0]["nodes"][0]["floating_nodes"]) { tooltip_text_.append(fmt::format(fmt::runtime(tooltip_format_ + '\n'), fmt::arg("app", window["app_id"].asString()), fmt::arg("title", window["name"].asString()))); } if (!tooltip_text_.empty()) { tooltip_text_.pop_back(); } } dp.emit(); } catch (const std::exception& e) { spdlog::error("Scratchpad: {}", e.what()); } } auto Scratchpad::onEvent(const struct Ipc::ipc_response& res) -> void { getTree(); } } // namespace waybar::modules::swaywaybar-0.12.0/src/modules/sway/window.cpp000066400000000000000000000242301475603165300203270ustar00rootroot00000000000000#include "modules/sway/window.hpp" #include #include #include #include #include #include #include #include #include #include "util/gtk_icon.hpp" #include "util/rewrite_string.hpp" namespace waybar::modules::sway { Window::Window(const std::string& id, const Bar& bar, const Json::Value& config) : AAppIconLabel(config, "window", id, "{}", 0, true), bar_(bar), windowId_(-1) { ipc_.subscribe(R"(["window","workspace"])"); ipc_.signal_event.connect(sigc::mem_fun(*this, &Window::onEvent)); ipc_.signal_cmd.connect(sigc::mem_fun(*this, &Window::onCmd)); // Get Initial focused window getTree(); // Launch worker ipc_.setWorker([this] { try { ipc_.handleEvent(); } catch (const std::exception& e) { spdlog::error("Window: {}", e.what()); spdlog::trace("Window::Window exception"); } }); } void Window::onEvent(const struct Ipc::ipc_response& res) { getTree(); } void Window::onCmd(const struct Ipc::ipc_response& res) { try { 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); updateAppIconName(app_id_, app_class_); dp.emit(); } catch (const std::exception& e) { spdlog::error("Window: {}", e.what()); spdlog::trace("Window::onCmd exception"); } } auto Window::update() -> void { spdlog::trace("workspace layout {}, tiled count {}, floating count {}", layout_, app_nb_, floating_count_); int mode = 0; if (app_nb_ == 0) { if (floating_count_ == 0) { mode += 1; } else { mode += 4; } } else if (app_nb_ == 1) { mode += 2; } else { if (layout_ == "tabbed") { mode += 8; } else if (layout_ == "stacked") { mode += 16; } else { mode += 32; } } if (!old_app_id_.empty() && ((mode & 2) == 0 || old_app_id_ != app_id_) && bar_.window.get_style_context()->has_class(old_app_id_)) { spdlog::trace("Removing app_id class: {}", old_app_id_); bar_.window.get_style_context()->remove_class(old_app_id_); old_app_id_ = ""; } setClass("empty", ((mode & 1) > 0)); setClass("solo", ((mode & 2) > 0)); setClass("floating", ((mode & 4) > 0)); setClass("tabbed", ((mode & 8) > 0)); setClass("stacked", ((mode & 16) > 0)); setClass("tiled", ((mode & 32) > 0)); if ((mode & 2) > 0 && !app_id_.empty() && !bar_.window.get_style_context()->has_class(app_id_)) { spdlog::trace("Adding app_id class: {}", app_id_); bar_.window.get_style_context()->add_class(app_id_); old_app_id_ = app_id_; } label_.set_markup(waybar::util::rewriteString( fmt::format(fmt::runtime(format_), fmt::arg("title", window_), fmt::arg("app_id", app_id_), fmt::arg("shell", shell_)), config_["rewrite"])); if (tooltipEnabled()) { label_.set_tooltip_text(window_); } updateAppIcon(); // Call parent update AAppIconLabel::update(); } void Window::setClass(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); } } std::pair leafNodesInWorkspace(const Json::Value& node) { auto const& nodes = node["nodes"]; auto const& floating_nodes = node["floating_nodes"]; if (nodes.empty() && floating_nodes.empty()) { if (node["type"].asString() == "workspace") return {0, 0}; else if (node["type"].asString() == "floating_con") { return {0, 1}; } else { return {1, 0}; } } int sum = 0; int floating_sum = 0; for (auto const& node : nodes) { std::pair all_leaf_nodes = leafNodesInWorkspace(node); sum += all_leaf_nodes.first; floating_sum += all_leaf_nodes.second; } for (auto const& node : floating_nodes) { std::pair all_leaf_nodes = leafNodesInWorkspace(node); sum += all_leaf_nodes.first; floating_sum += all_leaf_nodes.second; } return {sum, floating_sum}; } std::optional> getSingleChildNode( const Json::Value& node) { auto const& nodes = node["nodes"]; if (nodes.empty()) { if (node["type"].asString() == "workspace") return {}; else if (node["type"].asString() == "floating_con") { return {}; } else { return {std::cref(node)}; } } auto it = std::cbegin(nodes); if (it == std::cend(nodes)) { return {}; } auto const& child = *it; ++it; if (it != std::cend(nodes)) { return {}; } return {getSingleChildNode(child)}; } std::tuple getWindowInfo(const Json::Value& node) { 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::tuple gfnWithWorkspace(const Json::Value& nodes, std::string& output, const Json::Value& config_, const Bar& bar_, Json::Value& parentWorkspace, const Json::Value& immediateParent) { for (auto const& node : nodes) { if (node["type"].asString() == "output") { if ((!config_["all-outputs"].asBool() || config_["offscreen-css"].asBool()) && (node["name"].asString() != bar_.output->name)) { continue; } output = node["name"].asString(); } else if (node["type"].asString() == "workspace") { // needs to be a string comparison, because filterWorkspace is the current_workspace if (node["name"].asString() != immediateParent["current_workspace"].asString()) { continue; } if (node["focused"].asBool()) { std::pair all_leaf_nodes = leafNodesInWorkspace(node); return {all_leaf_nodes.first, all_leaf_nodes.second, node["id"].asInt(), (((all_leaf_nodes.first > 0) || (all_leaf_nodes.second > 0)) && (config_["show-focused-workspace-name"].asBool())) ? node["name"].asString() : "", "", "", "", node["layout"].asString()}; } parentWorkspace = node; } else if ((node["type"].asString() == "con" || node["type"].asString() == "floating_con") && (node["focused"].asBool())) { // 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); int nb = node.size(); int floating_count = 0; std::string workspace_layout = ""; if (!parentWorkspace.isNull()) { std::pair all_leaf_nodes = leafNodesInWorkspace(parentWorkspace); nb = all_leaf_nodes.first; floating_count = all_leaf_nodes.second; workspace_layout = parentWorkspace["layout"].asString(); } return {nb, floating_count, node["id"].asInt(), Glib::Markup::escape_text(node["name"].asString()), app_id, app_class, shell, workspace_layout}; } // iterate auto [nb, f, id, name, app_id, app_class, shell, workspace_layout] = gfnWithWorkspace(node["nodes"], output, config_, bar_, parentWorkspace, node); auto [nb2, f2, id2, name2, app_id2, app_class2, shell2, workspace_layout2] = 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}; } else if (id2 > 0 && !name2.empty()) { return {nb2, f2, id2, name2, app_id2, app_class, shell2, workspace_layout2}; } } // this only comes into effect when no focused children are present if (config_["all-outputs"].asBool() && config_["offscreen-css"].asBool() && immediateParent["type"].asString() == "workspace") { std::pair all_leaf_nodes = leafNodesInWorkspace(immediateParent); // using an empty string as default ensures that no window depending styles are set due to the // checks above for !name.empty() std::string app_id = ""; std::string app_class = ""; std::string workspace_layout = ""; 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()); } } return {all_leaf_nodes.first, all_leaf_nodes.second, 0, (all_leaf_nodes.first > 0 || all_leaf_nodes.second > 0) ? config_["offscreen-css-text"].asString() : "", app_id, app_class, workspace_layout, immediateParent["layout"].asString()}; } return {0, 0, -1, "", "", "", "", ""}; } 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); } void Window::getTree() { try { ipc_.sendCmd(IPC_GET_TREE); } catch (const std::exception& e) { spdlog::error("Window: {}", e.what()); spdlog::trace("Window::getTree exception"); } } } // namespace waybar::modules::sway waybar-0.12.0/src/modules/sway/workspaces.cpp000066400000000000000000000467061475603165300212150ustar00rootroot00000000000000#include "modules/sway/workspaces.hpp" #include #include #include #include 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) { if (isdigit(name[0]) != 0) { errno = 0; 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; } return (int)parsed_num; } return -1; } 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; bool const hasClass = window_rule.find("class") != std::string::npos; if (hasTitle && hasClass) { return 3; } if (hasTitle) { return 2; } if (hasClass) { return 1; } return 0; } 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"]) { high_priority_named_.push_back(it.asString()); } } box_.set_name("workspaces"); if (!id.empty()) { box_.get_style_context()->add_class(id); } box_.get_style_context()->add_class(MODULE_CLASS); event_box_.add(box_); if (config_["format-window-separator"].isString()) { m_formatWindowSeperator = config_["format-window-separator"].asString(); } else { m_formatWindowSeperator = " "; } const Json::Value &windowRewrite = config["window-rewrite"]; if (windowRewrite.isObject()) { const Json::Value &windowRewriteDefaultConfig = config["window-rewrite-default"]; std::string windowRewriteDefault = windowRewriteDefaultConfig.isString() ? windowRewriteDefaultConfig.asString() : "?"; m_windowRewriteRules = waybar::util::RegexCollection( windowRewrite, std::move(windowRewriteDefault), windowRewritePriorityFunction); } ipc_.subscribe(R"(["workspace"])"); ipc_.subscribe(R"(["window"])"); ipc_.signal_event.connect(sigc::mem_fun(*this, &Workspaces::onEvent)); 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; window.add_events(Gdk::SCROLL_MASK | Gdk::SMOOTH_SCROLL_MASK); window.signal_scroll_event().connect(sigc::mem_fun(*this, &Workspaces::handleScroll)); } // Launch worker ipc_.setWorker([this] { try { ipc_.handleEvent(); } catch (const std::exception &e) { spdlog::error("Workspaces: {}", e.what()); } }); } void Workspaces::onEvent(const struct Ipc::ipc_response &res) { try { ipc_.sendCmd(IPC_GET_TREE); } catch (const std::exception &e) { spdlog::error("Workspaces: {}", e.what()); } } void Workspaces::onCmd(const struct Ipc::ipc_response &res) { if (res.type == IPC_GET_TREE) { try { { std::lock_guard lock(mutex_); auto payload = parser_.parse(res.payload); workspaces_.clear(); 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) { if (alloutputs && output["name"].asString() != "__i3") { return true; } if (output["name"].asString() == bar_.output->name) { return true; } return false; }); 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(), std::back_inserter(workspaces_)); } // adding persistent workspaces (as per the config file) if (config_["persistent-workspaces"].isObject()) { const Json::Value &p_workspaces = config_["persistent-workspaces"]; const std::vector p_workspaces_names = p_workspaces.getMemberNames(); for (const std::string &p_w_name : p_workspaces_names) { const Json::Value &p_w = p_workspaces[p_w_name]; auto it = std::find_if(workspaces_.begin(), workspaces_.end(), [&p_w_name](const Json::Value &node) { return node["name"].asString() == p_w_name; }); if (it != workspaces_.end()) { continue; // already displayed by some bar } if (p_w.isArray() && !p_w.empty()) { // Adding to target outputs for (const Json::Value &output : p_w) { if (output.asString() == bar_.output->name) { Json::Value v; v["name"] = p_w_name; v["target_output"] = bar_.output->name; v["num"] = convertWorkspaceNameToNum(p_w_name); workspaces_.emplace_back(std::move(v)); break; } } } else { // Adding to all outputs Json::Value v; v["name"] = p_w_name; v["target_output"] = ""; v["num"] = convertWorkspaceNameToNum(p_w_name); workspaces_.emplace_back(std::move(v)); } } } // sway has a defined ordering of workspaces that should be preserved in // the representation displayed by waybar to ensure that commands such // as "workspace prev" or "workspace next" make sense when looking at // the workspace representation in the bar. // Due to waybar's own feature of persistent workspaces unknown to sway, // custom sorting logic is necessary to make these workspaces appear // naturally in the list of workspaces without messing up sway's // sorting. For this purpose, a custom numbering property is created // that preserves the order provided by sway while inserting numbered // persistent workspaces at their natural positions. // // All of this code assumes that sway provides numbered workspaces first // and other workspaces are sorted by their creation time. // // In a first pass, the maximum "num" value is computed to enqueue // unnumbered workspaces behind numbered ones when computing the sort // attribute. // // Note: if the 'alphabetical_sort' option is true, the user is in // agreement that the "workspace prev/next" commands may not follow // the order displayed in Waybar. int max_num = -1; for (auto &workspace : workspaces_) { max_num = std::max(workspace["num"].asInt(), max_num); } for (auto &workspace : workspaces_) { auto workspace_num = workspace["num"].asInt(); if (workspace_num > -1) { workspace["sort"] = workspace_num; } else { workspace["sort"] = ++max_num; } } std::sort(workspaces_.begin(), workspaces_.end(), [this](const Json::Value &lhs, const Json::Value &rhs) { auto lname = lhs["name"].asString(); auto rname = rhs["name"].asString(); int l = lhs["sort"].asInt(); int r = rhs["sort"].asInt(); if (l == r || config_["alphabetical_sort"].asBool()) { // In case both integers are the same, lexicographical // sort. The code above already ensure that this will only // happened in case of explicitly numbered workspaces. // // Additionally, if the config specifies to sort workspaces // alphabetically do this here. return lname < rname; } return l < r; }); } dp.emit(); } catch (const std::exception &e) { spdlog::error("Workspaces: {}", e.what()); } } } 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; }); if (ws == workspaces_.end() || (!config_["all-outputs"].asBool() && (*ws)["output"].asString() != bar_.output->name)) { it = buttons_.erase(it); needReorder = true; } else { ++it; } } return needReorder; } 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); })) { return true; } if (std::any_of(node["floating_nodes"].begin(), node["floating_nodes"].end(), [&](auto const &e) { return hasFlag(e, flag); })) { return true; } return false; } 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); std::string windowClass = node["app_id"].isString() ? node["app_id"].asString() : node["window_properties"]["class"].asString(); // Only add window rewrites that can be looked up if (!windowClass.empty()) { std::string windowReprKey = fmt::format("class<{}> title<{}>", windowClass, title); std::string window = m_windowRewriteRules.get(windowReprKey); // allow result to have formatting window = fmt::format(fmt::runtime(window), fmt::arg("name", title), fmt::arg("class", windowClass)); windows.append(window); windows.append(m_formatWindowSeperator); } } for (const Json::Value &child : node["nodes"]) { updateWindows(child, windows); } for (const Json::Value &child : node["floating_nodes"]) { updateWindows(child, windows); } } auto Workspaces::update() -> void { std::lock_guard lock(mutex_); bool needReorder = filterButtons(); for (auto it = workspaces_.begin(); it != workspaces_.end(); ++it) { auto bit = buttons_.find((*it)["name"].asString()); if (bit == buttons_.end()) { needReorder = true; } auto &button = bit == buttons_.end() ? addButton(*it) : bit->second; if (needReorder) { box_.reorder_child(button, it - workspaces_.begin()); } bool noNodes = (*it)["nodes"].empty() && (*it)["floating_nodes"].empty(); if (hasFlag((*it), "focused")) { button.get_style_context()->add_class("focused"); } else { button.get_style_context()->remove_class("focused"); } if (hasFlag((*it), "visible") || ((*it)["output"].isString() && noNodes)) { button.get_style_context()->add_class("visible"); } else { button.get_style_context()->remove_class("visible"); } if (hasFlag((*it), "urgent")) { button.get_style_context()->add_class("urgent"); } else { button.get_style_context()->remove_class("urgent"); } if ((*it)["target_output"].isString()) { button.get_style_context()->add_class("persistent"); } else { button.get_style_context()->remove_class("persistent"); } if (noNodes) { button.get_style_context()->add_class("empty"); } else { button.get_style_context()->remove_class("empty"); } if ((*it)["output"].isString()) { if (((*it)["output"].asString()) == bar_.output->name) { button.get_style_context()->add_class("current_output"); } else { button.get_style_context()->remove_class("current_output"); } } else { button.get_style_context()->remove_class("current_output"); } std::string output = (*it)["name"].asString(); std::string windows = ""; if (config_["window-format"].isString()) { updateWindows((*it), windows); } if (config_["format"].isString()) { auto format = config_["format"].asString(); output = fmt::format( fmt::runtime(format), fmt::arg("icon", getIcon(output, *it)), fmt::arg("value", output), fmt::arg("name", trimWorkspaceName(output)), fmt::arg("index", (*it)["num"].asString()), fmt::arg("windows", windows.substr(0, windows.length() - m_formatWindowSeperator.length())), fmt::arg("output", (*it)["output"].asString())); } if (!config_["disable-markup"].asBool()) { static_cast(button.get_children()[0])->set_markup(output); } else { button.set_label(output); } onButtonReady(*it, button); } // Call parent update AModule::update(); } Gtk::Button &Workspaces::addButton(const Json::Value &node) { auto pair = buttons_.emplace(node["name"].asString(), node["name"].asString()); auto &&button = pair.first->second; box_.pack_start(button, false, false, 0); button.set_name("sway-workspace-" + node["name"].asString()); button.set_relief(Gtk::RELIEF_NONE); if (!config_["disable-click"].asBool()) { button.signal_pressed().connect([this, node] { try { if (node["target_output"].isString()) { ipc_.sendCmd(IPC_COMMAND, fmt::format(persistent_workspace_switch_cmd_, "--no-auto-back-and-forth", node["name"].asString(), node["target_output"].asString(), "--no-auto-back-and-forth", node["name"].asString())); } else { ipc_.sendCmd(IPC_COMMAND, fmt::format("workspace {} \"{}\"", config_["disable-auto-back-and-forth"].asBool() ? "--no-auto-back-and-forth" : "", node["name"].asString())); } } catch (const std::exception &e) { spdlog::error("Workspaces: {}", e.what()); } }); } return button; } 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) { 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; }); 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) { return trimWorkspaceName(member) == trimWorkspaceName(name); }); if (it != high_priority_named_.end()) { return config_["format-icons"][trimWorkspaceName(name)].asString(); } } if (key == "focused" || key == "urgent") { if (config_["format-icons"][key].isString() && hasFlag(node, key)) { return config_["format-icons"][key].asString(); } } else if (config_["format-icons"]["persistent"].isString() && node["target_output"].isString()) { return config_["format-icons"]["persistent"].asString(); } else if (config_["format-icons"][key].isString()) { return config_["format-icons"][key].asString(); } else if (config_["format-icons"][trimWorkspaceName(key)].isString()) { return config_["format-icons"][trimWorkspaceName(key)].asString(); } } return name; } bool Workspaces::handleScroll(GdkEventScroll *e) { if (gdk_event_get_pointer_emulated((GdkEvent *)e) != 0) { /** * Ignore emulated scroll events on window */ return false; } auto dir = AModule::getScrollDir(e); if (dir == SCROLL_DIR::NONE) { return true; } std::string name; { bool alloutputs = config_["all-outputs"].asBool(); std::lock_guard lock(mutex_); auto it = std::find_if(workspaces_.begin(), workspaces_.end(), [alloutputs](const auto &workspace) { if (alloutputs) { return hasFlag(workspace, "focused"); } bool noNodes = workspace["nodes"].empty() && workspace["floating_nodes"].empty(); return hasFlag(workspace, "visible") || (workspace["output"].isString() && noNodes); }); if (it == workspaces_.end()) { return true; } if (dir == SCROLL_DIR::DOWN || dir == SCROLL_DIR::RIGHT) { name = getCycleWorkspace(it, false); } else if (dir == SCROLL_DIR::UP || dir == SCROLL_DIR::LEFT) { name = getCycleWorkspace(it, true); } else { return true; } if (name == (*it)["name"].asString()) { return true; } } if (!config_["warp-on-scroll"].isNull() && !config_["warp-on-scroll"].asBool()) { ipc_.sendCmd(IPC_COMMAND, fmt::format("mouse_warping none")); } try { ipc_.sendCmd(IPC_COMMAND, fmt::format(workspace_switch_cmd_, "--no-auto-back-and-forth", name)); } catch (const std::exception &e) { spdlog::error("Workspaces: {}", e.what()); } if (!config_["warp-on-scroll"].isNull() && !config_["warp-on-scroll"].asBool()) { ipc_.sendCmd(IPC_COMMAND, fmt::format("mouse_warping container")); } return true; } std::string Workspaces::getCycleWorkspace(std::vector::iterator it, bool prev) const { if (prev && it == workspaces_.begin() && !config_["disable-scroll-wraparound"].asBool()) { return (*(--workspaces_.end()))["name"].asString(); } if (prev && it != workspaces_.begin()) --it; else if (!prev && it != workspaces_.end()) ++it; if (!prev && it == workspaces_.end()) { if (config_["disable-scroll-wraparound"].asBool()) { --it; } else { return (*(workspaces_.begin()))["name"].asString(); } } return (*it)["name"].asString(); } std::string Workspaces::trimWorkspaceName(std::string name) { std::size_t found = name.find(':'); if (found != std::string::npos) { return name.substr(found + 1); } return name; } void Workspaces::onButtonReady(const Json::Value &node, Gtk::Button &button) { if (config_["current-only"].asBool()) { // If a workspace has a focused container then get_tree will say // that the workspace itself isn't focused. Therefore we need to // check if any of its nodes are focused as well. bool focused = node["focused"].asBool() || std::any_of(node["nodes"].begin(), node["nodes"].end(), [](const auto &child) { return child["focused"].asBool(); }); if (focused) { button.show(); } else { button.hide(); } } else { button.show(); } } } // namespace waybar::modules::sway waybar-0.12.0/src/modules/systemd_failed_units.cpp000066400000000000000000000105751475603165300222620ustar00rootroot00000000000000#include "modules/systemd_failed_units.hpp" #include #include #include #include static const unsigned UPDATE_DEBOUNCE_TIME_MS = 1000; 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() { if (config["hide-on-ok"].isBool()) { hide_on_ok = config["hide-on-ok"].asBool(); } if (config["format-ok"].isString()) { format_ok = config["format-ok"].asString(); } else { format_ok = format_; } /* Default to enable both "system" and "user". */ if (!config["system"].isBool() || config["system"].asBool()) { system_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) { throw std::runtime_error("Unable to connect to systemwide systemd DBus!"); } system_proxy->signal_signal().connect(sigc::mem_fun(*this, &SystemdFailedUnits::notify_cb)); } if (!config["user"].isBool() || config["user"].asBool()) { user_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) { throw std::runtime_error("Unable to connect to user systemd DBus!"); } user_proxy->signal_signal().connect(sigc::mem_fun(*this, &SystemdFailedUnits::notify_cb)); } 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; /* 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; auto load = [](const char* kind, Glib::RefPtr& proxy) -> uint32_t { try { 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); if (variant && variant.is_of_type(Glib::VARIANT_TYPE_UINT32)) { uint32_t value = 0; g_variant_get(variant.gobj_copy(), "u", &value); return value; } } } catch (Glib::Error& e) { spdlog::error("Failed to get {} failed units: {}", kind, e.what().c_str()); } return 0; }; if (system_proxy) { nr_failed_system = load("systemwide", system_proxy); } if (user_proxy) { nr_failed_user = load("user", user_proxy); } 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) { event_box_.set_visible(false); return; } if (!event_box_.get_visible()) { 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 (!label_.get_style_context()->has_class(status)) { label_.get_style_context()->add_class(status); } last_status = status; 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))); ALabel::update(); } } // namespace waybar::modules waybar-0.12.0/src/modules/temperature.cpp000066400000000000000000000122241475603165300203720ustar00rootroot00000000000000#include "modules/temperature.hpp" #include #include #if defined(__FreeBSD__) #include #endif waybar::modules::Temperature::Temperature(const std::string& id, const Json::Value& config) : ALabel(config, "temperature", id, "{temperatureC}°C", 10) { #if defined(__FreeBSD__) // FreeBSD uses sysctlbyname instead of read from a file #else auto traverseAsArray = [](const Json::Value& value, auto&& check_set_path) { if (value.isString()) check_set_path(value.asString()); else if (value.isArray()) for (const auto& item : value) if (check_set_path(item.asString())) break; }; // if hwmon_path is an array, loop to find first valid item traverseAsArray(config_["hwmon-path"], [this](const std::string& path) { if (!std::filesystem::exists(path)) return false; file_path_ = path; return true; }); if (file_path_.empty() && config_["input-filename"].isString()) { // fallback to hwmon_paths-abs traverseAsArray(config_["hwmon-path-abs"], [this](const std::string& path) { if (!std::filesystem::is_directory(path)) return false; return std::ranges::any_of( std::filesystem::directory_iterator(path), [this](const auto& hwmon) { if (!hwmon.path().filename().string().starts_with("hwmon")) return false; file_path_ = hwmon.path().string() + "/" + config_["input-filename"].asString(); return true; }); }); } 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 std::ifstream temp(file_path_); if (!temp.is_open()) { throw std::runtime_error("Can't open " + file_path_); } if (!temp.good()) { temp.close(); throw std::runtime_error("Can't read from " + file_path_); } temp.close(); #endif thread_ = [this] { dp.emit(); thread_.sleep_for(interval_); }; } auto waybar::modules::Temperature::update() -> void { auto temperature = getTemperature(); uint16_t temperature_c = std::round(temperature); uint16_t temperature_f = std::round(temperature * 1.8 + 32); uint16_t temperature_k = std::round(temperature + 273.15); auto critical = isCritical(temperature_c); auto warning = isWarning(temperature_c); auto format = format_; 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 (format.empty()) { event_box_.hide(); return; } event_box_.show(); auto max_temp = config_["critical-threshold"].isInt() ? config_["critical-threshold"].asInt() : 0; label_.set_markup(fmt::format(fmt::runtime(format), fmt::arg("temperatureC", temperature_c), fmt::arg("temperatureF", temperature_f), fmt::arg("temperatureK", temperature_k), fmt::arg("icon", getIcon(temperature_c, "", max_temp)))); if (tooltipEnabled()) { std::string tooltip_format = "{temperatureC}°C"; if (config_["tooltip-format"].isString()) { tooltip_format = config_["tooltip-format"].asString(); } label_.set_tooltip_text(fmt::format( fmt::runtime(tooltip_format), fmt::arg("temperatureC", temperature_c), fmt::arg("temperatureF", temperature_f), fmt::arg("temperatureK", temperature_k))); } // Call parent update ALabel::update(); } float waybar::modules::Temperature::getTemperature() { #if defined(__FreeBSD__) int temp; size_t size = sizeof temp; auto zone = config_["thermal-zone"].isInt() ? config_["thermal-zone"].asInt() : 0; if (sysctlbyname(fmt::format("hw.acpi.thermal.tz{}.temperature", zone).c_str(), &temp, &size, NULL, 0) != 0) { throw std::runtime_error(fmt::format( "sysctl hw.acpi.thermal.tz{}.temperature or dev.cpu.{}.temperature failed", zone, zone)); } auto temperature_c = ((float)temp - 2732) / 10; return temperature_c; #else // Linux std::ifstream temp(file_path_); if (!temp.is_open()) { throw std::runtime_error("Can't open " + file_path_); } std::string line; if (temp.good()) { getline(temp, line); } else { temp.close(); throw std::runtime_error("Can't read from " + file_path_); } temp.close(); auto temperature_c = std::strtol(line.c_str(), nullptr, 10) / 1000.0; return temperature_c; #endif } bool waybar::modules::Temperature::isWarning(uint16_t temperature_c) { return config_["warning-threshold"].isInt() && temperature_c >= config_["warning-threshold"].asInt(); } bool waybar::modules::Temperature::isCritical(uint16_t temperature_c) { return config_["critical-threshold"].isInt() && temperature_c >= config_["critical-threshold"].asInt(); }waybar-0.12.0/src/modules/upower.cpp000066400000000000000000000431471475603165300173660ustar00rootroot00000000000000#include "modules/upower.hpp" #include #include #include namespace waybar::modules { 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 : Gtk::ORIENTATION_HORIZONTAL); // Get current theme gtkTheme_ = Gtk::IconTheme::get_default(); // Icon Size if (config_["icon-size"].isInt()) { iconSize_ = config_["icon-size"].asInt(); } image_.set_pixel_size(iconSize_); // Show icon only when "show-icon" isn't set to false if (config_["show-icon"].isBool()) showIcon_ = config_["show-icon"].asBool(); if (!showIcon_) box_.remove(image_); // Device user wants if (config_["native-path"].isString()) nativePath_ = config_["native-path"].asString(); // Device model user wants if (config_["model"].isString()) model_ = config_["model"].asString(); // Hide If Empty if (config_["hide-if-empty"].isBool()) hideIfEmpty_ = config_["hide-if-empty"].asBool(); // Tooltip Spacing if (config_["tooltip-spacing"].isInt()) tooltip_spacing_ = config_["tooltip-spacing"].asInt(); // Tooltip Padding if (config_["tooltip-padding"].isInt()) { tooltip_padding_ = config_["tooltip-padding"].asInt(); contentBox_.set_margin_top(tooltip_padding_); contentBox_.set_margin_bottom(tooltip_padding_); contentBox_.set_margin_left(tooltip_padding_); contentBox_.set_margin_right(tooltip_padding_); } // Tooltip Format if (config_["tooltip-format"].isString()) tooltipFormat_ = config_["tooltip-format"].asString(); // Start watching DBUS watcherID_ = Gio::DBus::watch_name( Gio::DBus::BusType::BUS_TYPE_SYSTEM, "org.freedesktop.UPower", sigc::mem_fun(*this, &UPower::onAppear), sigc::mem_fun(*this, &UPower::onVanished), Gio::DBus::BusNameWatcherFlags::BUS_NAME_WATCHER_FLAGS_AUTO_START); // Get DBus async connect Gio::DBus::Connection::get(Gio::DBus::BusType::BUS_TYPE_SYSTEM, 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); // 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); resetDevices(); setDisplayDevice(); // Update the widget dp.emit(); } UPower::~UPower() { if (upDevice_.upDevice != NULL) g_object_unref(upDevice_.upDevice); if (upClient_ != NULL) g_object_unref(upClient_); if (subscrID_ > 0u) { conn_->signal_unsubscribe(subscrID_); subscrID_ = 0u; } Gio::DBus::unwatch_name(watcherID_); watcherID_ = 0u; removeDevices(); } static const std::string getDeviceStatus(UpDeviceState &state) { switch (state) { case UP_DEVICE_STATE_CHARGING: case UP_DEVICE_STATE_PENDING_CHARGE: return "charging"; case UP_DEVICE_STATE_DISCHARGING: case UP_DEVICE_STATE_PENDING_DISCHARGE: return "discharging"; case UP_DEVICE_STATE_FULLY_CHARGED: return "full"; case UP_DEVICE_STATE_EMPTY: return "empty"; default: return "unknown-status"; } } static const std::string getDeviceIcon(UpDeviceKind &kind) { switch (kind) { case UP_DEVICE_KIND_LINE_POWER: return "ac-adapter-symbolic"; case UP_DEVICE_KIND_BATTERY: return "battery-symbolic"; case UP_DEVICE_KIND_UPS: return "uninterruptible-power-supply-symbolic"; case UP_DEVICE_KIND_MONITOR: return "video-display-symbolic"; case UP_DEVICE_KIND_MOUSE: return "input-mouse-symbolic"; case UP_DEVICE_KIND_KEYBOARD: return "input-keyboard-symbolic"; case UP_DEVICE_KIND_PDA: return "pda-symbolic"; case UP_DEVICE_KIND_PHONE: return "phone-symbolic"; case UP_DEVICE_KIND_MEDIA_PLAYER: return "multimedia-player-symbolic"; case UP_DEVICE_KIND_TABLET: return "computer-apple-ipad-symbolic"; case UP_DEVICE_KIND_COMPUTER: return "computer-symbolic"; case UP_DEVICE_KIND_GAMING_INPUT: return "input-gaming-symbolic"; case UP_DEVICE_KIND_PEN: return "input-tablet-symbolic"; case UP_DEVICE_KIND_TOUCHPAD: return "input-touchpad-symbolic"; case UP_DEVICE_KIND_MODEM: return "modem-symbolic"; case UP_DEVICE_KIND_NETWORK: return "network-wired-symbolic"; case UP_DEVICE_KIND_HEADSET: return "audio-headset-symbolic"; case UP_DEVICE_KIND_HEADPHONES: return "audio-headphones-symbolic"; case UP_DEVICE_KIND_OTHER_AUDIO: case UP_DEVICE_KIND_SPEAKERS: return "audio-speakers-symbolic"; case UP_DEVICE_KIND_VIDEO: return "camera-web-symbolic"; case UP_DEVICE_KIND_PRINTER: return "printer-symbolic"; case UP_DEVICE_KIND_SCANNER: return "scanner-symbolic"; case UP_DEVICE_KIND_CAMERA: return "camera-photo-symbolic"; case UP_DEVICE_KIND_BLUETOOTH_GENERIC: return "bluetooth-active-symbolic"; case UP_DEVICE_KIND_TOY: case UP_DEVICE_KIND_REMOTE_CONTROL: case UP_DEVICE_KIND_WEARABLE: case UP_DEVICE_KIND_LAST: default: return "battery-symbolic"; } } static std::string secondsToString(const std::chrono::seconds sec) { const auto ds{std::chrono::duration_cast(sec)}; const auto hrs{std::chrono::duration_cast(sec - ds)}; const auto min{std::chrono::duration_cast(sec - ds - hrs)}; std::string_view strRet{(ds.count() > 0) ? "{D}d {H}h {M}min" : (hrs.count() > 0) ? "{H}h {M}min" : (min.count() > 0) ? "{M}min" : ""}; spdlog::debug( "UPower::secondsToString(). seconds: \"{0}\", minutes: \"{1}\", hours: \"{2}\", \ days: \"{3}\", strRet: \"{4}\"", sec.count(), min.count(), hrs.count(), ds.count(), strRet); return fmt::format(fmt::runtime(strRet), fmt::arg("D", ds.count()), fmt::arg("H", hrs.count()), fmt::arg("M", min.count())); } auto UPower::update() -> void { std::lock_guard guard{mutex_}; // Don't update widget if the UPower service isn't running if (!upRunning_ || sleeping_) { if (hideIfEmpty_) box_.hide(); return; } getUpDeviceInfo(upDevice_); if (upDevice_.upDevice == NULL && hideIfEmpty_) { box_.hide(); return; } /* Every Device which is handled by Upower and which is not * UP_DEVICE_KIND_UNKNOWN (0) or UP_DEVICE_KIND_LINE_POWER (1) is a Battery */ const bool upDeviceValid{upDevice_.kind != UpDeviceKind::UP_DEVICE_KIND_UNKNOWN && upDevice_.kind != UpDeviceKind::UP_DEVICE_KIND_LINE_POWER}; // Get CSS status const auto status{getDeviceStatus(upDevice_.state)}; // 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); lastStatus_ = status; if (devices_.size() == 0 && !upDeviceValid && hideIfEmpty_) { box_.hide(); // Call parent update AModule::update(); return; } 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(); image_.set_from_icon_name(upDevice_.icon_name, Gtk::ICON_SIZE_INVALID); box_.show(); // Call parent update ALabel::update(); } void UPower::getConn_cb(Glib::RefPtr &result) { try { conn_ = Gio::DBus::Connection::get_finish(result); // Subscribe DBUs events subscrID_ = conn_->signal_subscribe(sigc::mem_fun(*this, &UPower::prepareForSleep_cb), "org.freedesktop.login1", "org.freedesktop.login1.Manager", "PrepareForSleep", "/org/freedesktop/login1"); } 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) { upRunning_ = true; } 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) { if (parameters.is_of_type(Glib::VariantType("(b)"))) { Glib::Variant sleeping; parameters.get_child(sleeping, 0); if (!sleeping.get()) { resetDevices(); setDisplayDevice(); sleeping_ = false; // Update the widget dp.emit(); } else sleeping_ = true; } } 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)}; 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)}; // Update the widget up->dp.emit(); } void UPower::addDevice(UpDevice *device) { std::lock_guard guard{mutex_}; if (G_IS_OBJECT(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 device = up_device_new(); upDevice_output upDevice{.upDevice = device}; gboolean ret{up_device_set_object_path_sync(device, objectPath, NULL, NULL)}; if (!ret) { g_object_unref(G_OBJECT(device)); return; } if (devices_.find(objectPath) != devices_.cend()) { auto upDevice{devices_[objectPath]}; if (G_IS_OBJECT(upDevice.upDevice)) g_object_unref(upDevice.upDevice); devices_.erase(objectPath); } g_signal_connect(device, "notify", G_CALLBACK(deviceNotify_cb), this); devices_.emplace(Devices::value_type(objectPath, upDevice)); } } void UPower::removeDevice(const gchar *objectPath) { std::lock_guard guard{mutex_}; if (devices_.find(objectPath) != devices_.cend()) { auto upDevice{devices_[objectPath]}; if (G_IS_OBJECT(upDevice.upDevice)) g_object_unref(upDevice.upDevice); devices_.erase(objectPath); } } void UPower::removeDevices() { std::lock_guard guard{mutex_}; if (!devices_.empty()) { auto it{devices_.cbegin()}; while (it != devices_.cend()) { if (G_IS_OBJECT(it->second.upDevice)) g_object_unref(it->second.upDevice); devices_.erase(it++); } } } // Removes all devices and adds the current devices void UPower::resetDevices() { // Remove all devices removeDevices(); // Adds all devices 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)}; if (device && G_IS_OBJECT(device)) addDevice(device); } } void UPower::setDisplayDevice() { std::lock_guard guard{mutex_}; if (upDevice_.upDevice != NULL) { g_object_unref(upDevice_.upDevice); upDevice_.upDevice = NULL; } if (nativePath_.empty() && model_.empty()) { upDevice_.upDevice = up_client_get_display_device(upClient_); getUpDeviceInfo(upDevice_); } else { g_ptr_array_foreach( up_client_get_devices2(upClient_), [](gpointer data, gpointer user_data) { upDevice_output upDevice; auto thisPtr{static_cast(user_data)}; upDevice.upDevice = static_cast(data); thisPtr->getUpDeviceInfo(upDevice); upDevice_output displayDevice{NULL}; if (!thisPtr->nativePath_.empty()) { if (upDevice.nativePath == nullptr) return; if (0 == std::strcmp(upDevice.nativePath, thisPtr->nativePath_.c_str())) { displayDevice = upDevice; } } else { if (upDevice.model == nullptr) return; if (0 == std::strcmp(upDevice.model, thisPtr->model_.c_str())) { displayDevice = upDevice; } } // Unref current upDevice if it exists if (displayDevice.upDevice != NULL) { thisPtr->upDevice_ = displayDevice; } }, this); } if (upDevice_.upDevice != NULL) g_signal_connect(upDevice_.upDevice, "notify", G_CALLBACK(deviceNotify_cb), this); } 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, "time-to-empty", &upDevice_.time_empty, "time-to-full", &upDevice_.time_full, "temperature", &upDevice_.temperature, "native-path", &upDevice_.nativePath, "model", &upDevice_.model, NULL); spdlog::debug( "UPower. getUpDeviceInfo. kind: \"{0}\". state: \"{1}\". percentage: \"{2}\". \ icon_name: \"{3}\". time-to-empty: \"{4}\". time-to-full: \"{5}\". temperature: \"{6}\". \ native_path: \"{7}\". model: \"{8}\"", fmt::format_int(upDevice_.kind).str(), fmt::format_int(upDevice_.state).str(), upDevice_.percentage, upDevice_.icon_name, upDevice_.time_empty, upDevice_.time_full, upDevice_.temperature, upDevice_.nativePath, upDevice_.model); } } const Glib::ustring UPower::getText(const upDevice_output &upDevice_, const std::string &format) { Glib::ustring ret{""}; if (upDevice_.upDevice != NULL) { std::string timeStr{""}; switch (upDevice_.state) { case UP_DEVICE_STATE_CHARGING: case UP_DEVICE_STATE_PENDING_CHARGE: timeStr = secondsToString(std::chrono::seconds(upDevice_.time_full)); break; case UP_DEVICE_STATE_DISCHARGING: case UP_DEVICE_STATE_PENDING_DISCHARGE: timeStr = secondsToString(std::chrono::seconds(upDevice_.time_empty)); break; default: break; } ret = fmt::format( fmt::runtime(format), fmt::arg("percentage", std::to_string((int)std::round(upDevice_.percentage)) + '%'), fmt::arg("time", timeStr), fmt::arg("temperature", fmt::format("{:-.2g}C", upDevice_.temperature)), fmt::arg("model", upDevice_.model), fmt::arg("native-path", upDevice_.nativePath)); } return ret; } bool UPower::queryTooltipCb(int x, int y, bool keyboard_tooltip, const Glib::RefPtr &tooltip) { std::lock_guard guard{mutex_}; // Clear content box contentBox_.forall([this](Gtk::Widget &wg) { contentBox_.remove(wg); }); // Fill content box with the content for (auto pairDev : devices_) { // Get device info getUpDeviceInfo(pairDev.second); 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_}}; contentBox_.add(*boxRec); 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{}}; 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}}; 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{}}; 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{}}; labelTooltip->set_markup(getText(pairDev.second, tooltipFormat_)); boxUsr->add(*labelTooltip); } } tooltip->set_custom(contentBox_); contentBox_.show_all(); return true; } } // namespace waybar::modules waybar-0.12.0/src/modules/user.cpp000066400000000000000000000105751475603165300170220ustar00rootroot00000000000000#include "modules/user.hpp" #include #include #include #include #include #include "gdkmm/cursor.h" #include "gdkmm/event.h" #include "gdkmm/types.h" #include "glibmm/fileutils.h" #include "sigc++/functors/mem_fun.h" #include "sigc++/functors/ptr_fun.h" #if HAVE_CPU_LINUX #include #endif #if HAVE_CPU_BSD #include #endif const static int LEFT_MOUSE_BUTTON_CODE = 1; namespace waybar::modules { User::User(const std::string& id, const Json::Value& config) : AIconLabel(config, "user", id, "{user} {work_H}:{work_M}", 60, false, true, true) { AIconLabel::box_.set_spacing(0); if (AIconLabel::iconEnabled()) { this->init_avatar(AIconLabel::config_); } this->init_update_worker(); } bool User::handleToggle(GdkEventButton* const& e) { if (AIconLabel::config_["open-on-click"].isBool() && AIconLabel::config_["open-on-click"].asBool() && e->button == LEFT_MOUSE_BUTTON_CODE) { std::string openPath = this->get_user_home_dir(); if (AIconLabel::config_["open-path"].isString()) { std::string customPath = AIconLabel::config_["open-path"].asString(); if (!customPath.empty()) { openPath = std::move(customPath); } } Gio::AppInfo::launch_default_for_uri("file:///" + openPath); } return true; } long User::uptime_as_seconds() { long uptime = 0; #if HAVE_CPU_LINUX struct sysinfo s_info; if (0 == sysinfo(&s_info)) { uptime = s_info.uptime; } #endif #if HAVE_CPU_BSD struct timespec s_info; if (0 == clock_gettime(CLOCK_UPTIME_PRECISE, &s_info)) { uptime = s_info.tv_sec; } #endif return uptime; } std::string User::get_user_login() const { return Glib::get_user_name(); } std::string User::get_user_home_dir() const { return Glib::get_home_dir(); } void User::init_update_worker() { this->thread_ = [this] { ALabel::dp.emit(); auto now = std::chrono::system_clock::now(); auto diff = now.time_since_epoch() % ALabel::interval_; this->thread_.sleep_for(ALabel::interval_ - diff); }; } void User::init_avatar(const Json::Value& config) { int height = config["height"].isUInt() ? config["height"].asUInt() : this->defaultUserImageHeight_; int width = config["width"].isUInt() ? config["width"].asUInt() : this->defaultUserImageWidth_; if (config["avatar"].isString()) { std::string userAvatar = config["avatar"].asString(); if (!userAvatar.empty()) { this->init_user_avatar(userAvatar, width, height); return; } } this->init_default_user_avatar(width, width); } std::string User::get_default_user_avatar_path() const { return this->get_user_home_dir() + "/" + ".face"; } void User::init_default_user_avatar(int width, int height) { this->init_user_avatar(this->get_default_user_avatar_path(), width, height); } void User::init_user_avatar(const std::string& path, int width, int height) { if (Glib::file_test(path, Glib::FILE_TEST_EXISTS)) { Glib::RefPtr pixbuf_ = Gdk::Pixbuf::create_from_file(path, width, height); AIconLabel::image_.set(pixbuf_); } else { AIconLabel::box_.remove(AIconLabel::image_); } } auto User::update() -> void { std::string systemUser = this->get_user_login(); std::transform(systemUser.cbegin(), systemUser.cend(), systemUser.begin(), [](unsigned char c) { return std::toupper(c); }); long uptimeSeconds = this->uptime_as_seconds(); auto workSystemTimeSeconds = std::chrono::seconds(uptimeSeconds); auto currentSystemTime = std::chrono::system_clock::now(); auto startSystemTime = currentSystemTime - workSystemTimeSeconds; long workSystemDays = uptimeSeconds / 86400; auto label = fmt::format( fmt::runtime(ALabel::format_), fmt::arg("up_H", fmt::format("{:%H}", startSystemTime)), fmt::arg("up_M", fmt::format("{:%M}", startSystemTime)), fmt::arg("up_d", fmt::format("{:%d}", startSystemTime)), fmt::arg("up_m", fmt::format("{:%m}", startSystemTime)), fmt::arg("up_Y", fmt::format("{:%Y}", startSystemTime)), fmt::arg("work_d", workSystemDays), fmt::arg("work_H", fmt::format("{:%H}", workSystemTimeSeconds)), fmt::arg("work_M", fmt::format("{:%M}", workSystemTimeSeconds)), fmt::arg("work_S", fmt::format("{:%S}", workSystemTimeSeconds)), fmt::arg("user", systemUser)); ALabel::label_.set_markup(label); AIconLabel::update(); } }; // namespace waybar::modules waybar-0.12.0/src/modules/wireplumber.cpp000066400000000000000000000334151475603165300203770ustar00rootroot00000000000000#include "modules/wireplumber.hpp" #include bool isValidNodeId(uint32_t id) { return id > 0 && id < G_MAXUINT32; } waybar::modules::Wireplumber::Wireplumber(const std::string& id, const Json::Value& config) : ALabel(config, "wireplumber", id, "{volume}%"), wp_core_(nullptr), apis_(nullptr), om_(nullptr), mixer_api_(nullptr), def_nodes_api_(nullptr), default_node_name_(nullptr), pending_plugins_(0), muted_(false), volume_(0.0), min_step_(0.0), node_id_(0) { wp_init(WP_INIT_PIPEWIRE); wp_core_ = wp_core_new(nullptr, nullptr, nullptr); apis_ = g_ptr_array_new_with_free_func(g_object_unref); om_ = wp_object_manager_new(); prepare(); spdlog::debug("[{}]: connecting to pipewire...", name_); if (wp_core_connect(wp_core_) == 0) { spdlog::error("[{}]: Could not connect to PipeWire", name_); throw std::runtime_error("Could not connect to PipeWire\n"); } spdlog::debug("[{}]: connected!", name_); g_signal_connect_swapped(om_, "installed", (GCallback)onObjectManagerInstalled, this); asyncLoadRequiredApiModules(); } waybar::modules::Wireplumber::~Wireplumber() { wp_core_disconnect(wp_core_); g_clear_pointer(&apis_, g_ptr_array_unref); g_clear_object(&om_); g_clear_object(&wp_core_); g_clear_object(&mixer_api_); g_clear_object(&def_nodes_api_); g_free(default_node_name_); } void waybar::modules::Wireplumber::updateNodeName(waybar::modules::Wireplumber* self, uint32_t id) { spdlog::debug("[{}]: updating node name with node.id {}", self->name_, id); if (!isValidNodeId(id)) { spdlog::warn("[{}]: '{}' is not a valid node ID. Ignoring node 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("Object '{}' not found\n", id); spdlog::error("[{}]: {}", self->name_, err); throw std::runtime_error(err); } 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->node_name_ = nick != nullptr ? nick : description != nullptr ? description : "Unknown node name"; spdlog::debug("[{}]: Updating node name to: {}", self->name_, self->node_name_); } void waybar::modules::Wireplumber::updateVolume(waybar::modules::Wireplumber* self, uint32_t id) { spdlog::debug("[{}]: updating volume", self->name_); GVariant* variant = nullptr; if (!isValidNodeId(id)) { spdlog::error("[{}]: '{}' is not a valid node ID. Ignoring volume update.", self->name_, id); return; } g_signal_emit_by_name(self->mixer_api_, "get-volume", id, &variant); if (variant == nullptr) { auto err = fmt::format("Node {} does not support volume\n", id); spdlog::error("[{}]: {}", self->name_, err); throw std::runtime_error(err); } g_variant_lookup(variant, "volume", "d", &self->volume_); g_variant_lookup(variant, "step", "d", &self->min_step_); g_variant_lookup(variant, "mute", "b", &self->muted_); g_clear_pointer(&variant, g_variant_unref); self->dp.emit(); } void waybar::modules::Wireplumber::onMixerChanged(waybar::modules::Wireplumber* self, uint32_t id) { spdlog::debug("[{}]: (onMixerChanged) - id: {}", self->name_, 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)); if (node == nullptr) { spdlog::warn("[{}]: (onMixerChanged) - Object with id {} not found", self->name_, id); return; } 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_, id, name, self->default_node_name_, self->node_id_); return; } spdlog::debug("[{}]: (onMixerChanged) - Need to update volume for node with id {} and name {}", self->name_, id, name); updateVolume(self, id); } void waybar::modules::Wireplumber::onDefaultNodesApiChanged(waybar::modules::Wireplumber* self) { spdlog::debug("[{}]: (onDefaultNodesApiChanged)", self->name_); uint32_t defaultNodeId; g_signal_emit_by_name(self->def_nodes_api_, "get-default-node", "Audio/Sink", &defaultNodeId); if (!isValidNodeId(defaultNodeId)) { spdlog::warn("[{}]: '{}' is not a valid node ID. Ignoring node change.", self->name_, defaultNodeId); return; } 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) { spdlog::warn("[{}]: (onDefaultNodesApiChanged) - Object with id {} not found", self->name_, defaultNodeId); return; } 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_, 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->default_node_name_, defaultNodeId); return; } spdlog::debug( "[{}]: (onDefaultNodesApiChanged) - Default node 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); } void waybar::modules::Wireplumber::onObjectManagerInstalled(waybar::modules::Wireplumber* self) { spdlog::debug("[{}]: onObjectManagerInstalled", self->name_); self->def_nodes_api_ = wp_plugin_find(self->wp_core_, "default-nodes-api"); 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"); } 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"); } g_signal_emit_by_name(self->def_nodes_api_, "get-default-configured-node-name", "Audio/Sink", &self->default_node_name_); g_signal_emit_by_name(self->def_nodes_api_, "get-default-node", "Audio/Sink", &self->node_id_); if (self->default_node_name_ != nullptr) { spdlog::debug("[{}]: (onObjectManagerInstalled) - default configured node name: {} and id: {}", self->name_, self->default_node_name_, self->node_id_); } updateVolume(self, self->node_id_); updateNodeName(self, self->node_id_); g_signal_connect_swapped(self->mixer_api_, "changed", (GCallback)onMixerChanged, self); g_signal_connect_swapped(self->def_nodes_api_, "changed", (GCallback)onDefaultNodesApiChanged, self); } void waybar::modules::Wireplumber::onPluginActivated(WpObject* p, GAsyncResult* res, waybar::modules::Wireplumber* self) { const auto* pluginName = wp_plugin_get_name(WP_PLUGIN(p)); spdlog::debug("[{}]: onPluginActivated: {}", self->name_, pluginName); g_autoptr(GError) error = nullptr; if (wp_object_activate_finish(p, res, &error) == 0) { spdlog::error("[{}]: error activating plugin: {}", self->name_, error->message); throw std::runtime_error(error->message); } if (--self->pending_plugins_ == 0) { wp_core_install_object_manager(self->wp_core_, self->om_); } } void waybar::modules::Wireplumber::activatePlugins() { spdlog::debug("[{}]: activating plugins", name_); for (uint16_t i = 0; i < apis_->len; i++) { WpPlugin* plugin = static_cast(g_ptr_array_index(apis_, i)); pending_plugins_++; wp_object_activate(WP_OBJECT(plugin), WP_PLUGIN_FEATURE_ENABLED, nullptr, (GAsyncReadyCallback)onPluginActivated, this); } } void waybar::modules::Wireplumber::prepare() { spdlog::debug("[{}]: preparing object manager", name_); wp_object_manager_add_interest(om_, WP_TYPE_NODE, WP_CONSTRAINT_TYPE_PW_PROPERTY, "media.class", "=s", "Audio/Sink", nullptr); } void waybar::modules::Wireplumber::onDefaultNodesApiLoaded(WpObject* p, GAsyncResult* res, waybar::modules::Wireplumber* self) { gboolean success = FALSE; g_autoptr(GError) error = nullptr; spdlog::debug("[{}]: callback loading default node api module", self->name_); success = wp_core_load_component_finish(self->wp_core_, res, &error); if (success == FALSE) { spdlog::error("[{}]: default nodes API load failed", self->name_); throw std::runtime_error(error->message); } spdlog::debug("[{}]: loaded default nodes api", self->name_); g_ptr_array_add(self->apis_, wp_plugin_find(self->wp_core_, "default-nodes-api")); spdlog::debug("[{}]: loading mixer api module", self->name_); wp_core_load_component(self->wp_core_, "libwireplumber-module-mixer-api", "module", nullptr, "mixer-api", nullptr, (GAsyncReadyCallback)onMixerApiLoaded, self); } void waybar::modules::Wireplumber::onMixerApiLoaded(WpObject* p, GAsyncResult* res, waybar::modules::Wireplumber* self) { gboolean success = FALSE; g_autoptr(GError) error = nullptr; success = wp_core_load_component_finish(self->wp_core_, res, nullptr); if (success == FALSE) { spdlog::error("[{}]: mixer API load failed", self->name_); throw std::runtime_error(error->message); } spdlog::debug("[{}]: loaded mixer API", self->name_); g_ptr_array_add(self->apis_, ({ WpPlugin* p = wp_plugin_find(self->wp_core_, "mixer-api"); g_object_set(G_OBJECT(p), "scale", 1 /* cubic */, nullptr); p; })); self->activatePlugins(); self->dp.emit(); self->event_box_.add_events(Gdk::SCROLL_MASK | Gdk::SMOOTH_SCROLL_MASK); self->event_box_.signal_scroll_event().connect(sigc::mem_fun(*self, &Wireplumber::handleScroll)); } void waybar::modules::Wireplumber::asyncLoadRequiredApiModules() { spdlog::debug("[{}]: loading default nodes api module", name_); wp_core_load_component(wp_core_, "libwireplumber-module-default-nodes-api", "module", nullptr, "default-nodes-api", nullptr, (GAsyncReadyCallback)onDefaultNodesApiLoaded, this); } auto waybar::modules::Wireplumber::update() -> void { auto format = format_; std::string tooltipFormat; if (muted_) { format = config_["format-muted"].isString() ? config_["format-muted"].asString() : format; label_.get_style_context()->add_class("muted"); } else { label_.get_style_context()->remove_class("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); getState(vol); if (tooltipEnabled()) { if (tooltipFormat.empty() && config_["tooltip-format"].isString()) { tooltipFormat = config_["tooltip-format"].asString(); } 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)))); } else { label_.set_tooltip_text(node_name_); } } // Call parent update ALabel::update(); } bool waybar::modules::Wireplumber::handleScroll(GdkEventScroll* e) { 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; } double maxVolume = 1; double step = 1.0 / 100.0; if (config_["scroll-step"].isDouble()) { step = config_["scroll-step"].asDouble() / 100.0; } if (config_["max-volume"].isDouble()) { maxVolume = config_["max-volume"].asDouble() / 100.0; } if (step < min_step_) step = min_step_; double newVol = volume_; if (dir == SCROLL_DIR::UP) { if (volume_ < maxVolume) { newVol = volume_ + step; if (newVol > maxVolume) newVol = maxVolume; } } else if (dir == SCROLL_DIR::DOWN) { if (volume_ > 0) { newVol = volume_ - step; if (newVol < 0) newVol = 0; } } if (newVol != volume_) { GVariant* variant = g_variant_new_double(newVol); gboolean ret; g_signal_emit_by_name(mixer_api_, "set-volume", node_id_, variant, &ret); } return true; } waybar-0.12.0/src/modules/wlr/000077500000000000000000000000001475603165300161345ustar00rootroot00000000000000waybar-0.12.0/src/modules/wlr/taskbar.cpp000066400000000000000000000737511475603165300203040ustar00rootroot00000000000000#include "modules/wlr/taskbar.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include "gdkmm/general.h" #include "glibmm/error.h" #include "glibmm/fileutils.h" #include "glibmm/refptr.h" #include "util/format.hpp" #include "util/gtk_icon.hpp" #include "util/rewrite_string.hpp" #include "util/string.hpp" 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_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_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_done(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle) { return static_cast(data)->handle_done(); } static void tl_handle_parent(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle, struct zwlr_foreign_toplevel_handle_v1 *parent) { /* This is explicitly left blank */ } 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 = { .title = tl_handle_title, .app_id = tl_handle_app_id, .output_enter = tl_handle_output_enter, .output_leave = tl_handle_output_leave, .state = tl_handle_state, .done = tl_handle_done, .closed = tl_handle_closed, .parent = tl_handle_parent, }; 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) : bar_{bar}, config_{config}, tbar_{tbar}, handle_{tl_handle}, seat_{seat}, id_{global_id++}, content_{bar.orientation, 0} { zwlr_foreign_toplevel_handle_v1_add_listener(handle_, &toplevel_handle_impl, this); button.set_relief(Gtk::RELIEF_NONE); content_.add(text_before_); content_.add(icon_); content_.add(text_after_); content_.show(); button.add(content_); format_before_.clear(); format_after_.clear(); if (config_["format"].isString()) { /* The user defined a format string, use it */ auto format = config_["format"].asString(); if (format.find("{name}") != std::string::npos) { with_name_ = true; } auto icon_pos = format.find("{icon}"); if (icon_pos == 0) { with_icon_ = true; format_after_ = format.substr(6); } else if (icon_pos == std::string::npos) { format_before_ = format; } else { with_icon_ = true; format_before_ = format.substr(0, icon_pos); format_after_ = format.substr(icon_pos + 6); } } else { /* The default is to only show the icon */ with_icon_ = true; } if (app_id_.empty()) { handle_app_id("unknown"); } /* Strip spaces at the beginning and end of the format strings */ format_tooltip_.clear(); if (!config_["tooltip"].isBool() || config_["tooltip"].asBool()) { if (config_["tooltip-format"].isString()) format_tooltip_ = config_["tooltip-format"].asString(); else format_tooltip_ = "{title}"; } /* Handle click events if configured */ if (config_["on-click"].isString() || config_["on-click-middle"].isString() || config_["on-click-right"].isString()) { } button.add_events(Gdk::BUTTON_PRESS_MASK); button.signal_button_release_event().connect(sigc::mem_fun(*this, &Task::handle_clicked), false); button.signal_motion_notify_event().connect(sigc::mem_fun(*this, &Task::handle_motion_notify), false); button.drag_source_set(target_entries, Gdk::BUTTON1_MASK, Gdk::ACTION_MOVE); button.drag_dest_set(target_entries, Gtk::DEST_DEFAULT_ALL, Gdk::ACTION_MOVE); button.signal_drag_data_get().connect(sigc::mem_fun(*this, &Task::handle_drag_data_get), false); button.signal_drag_data_received().connect(sigc::mem_fun(*this, &Task::handle_drag_data_received), false); } Task::~Task() { if (handle_) { zwlr_foreign_toplevel_handle_v1_destroy(handle_); handle_ = nullptr; } if (button_visible_) { tbar_->remove_button(button); button_visible_ = false; } } std::string Task::repr() const { std::stringstream ss; ss << "Task (" << id_ << ") " << title_ << " [" << app_id_ << "] <" << (active() ? "A" : "a") << (maximized() ? "M" : "m") << (minimized() ? "I" : "i") << (fullscreen() ? "F" : "f") << ">"; return ss.str(); } std::string Task::state_string(bool shortened) const { std::stringstream ss; if (shortened) ss << (minimized() ? "m" : "") << (maximized() ? "M" : "") << (active() ? "A" : "") << (fullscreen() ? "F" : ""); else ss << (minimized() ? "minimized " : "") << (maximized() ? "maximized " : "") << (active() ? "active " : "") << (fullscreen() ? "fullscreen " : ""); std::string res = ss.str(); if (shortened || res.empty()) return res; else return res.substr(0, res.size() - 1); } void Task::handle_title(const char *title) { title_ = title; hide_if_ignored(); } void Task::set_minimize_hint() { zwlr_foreign_toplevel_handle_v1_set_rectangle(handle_, bar_.surface, minimize_hint.x, minimize_hint.y, minimize_hint.w, minimize_hint.h); } void Task::hide_if_ignored() { if (tbar_->ignore_list().count(app_id_) || tbar_->ignore_list().count(title_)) { ignored_ = true; if (button_visible_) { auto output = gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj()); handle_output_leave(output); } } else { bool is_was_ignored = ignored_; ignored_ = false; if (is_was_ignored) { auto output = gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj()); handle_output_enter(output); } } } void Task::handle_app_id(const char *app_id) { if (app_id_.empty()) { spdlog::debug(fmt::format("Task ({}) setting app_id to {}", id_, app_id)); } else { spdlog::debug(fmt::format("Task ({}) overwriting app_id '{}' with '{}'", id_, app_id_, app_id)); } app_id_ = app_id; hide_if_ignored(); auto ids_replace_map = tbar_->app_ids_replace_map(); if (ids_replace_map.count(app_id_)) { auto replaced_id = ids_replace_map[app_id_]; spdlog::debug( fmt::format("Task ({}) [{}] app_id was replaced with {}", id_, app_id_, replaced_id)); app_id_ = replaced_id; } if (!with_icon_ && !with_name_) { return; } set_app_info_from_app_id_list(app_id_); name_ = app_info_ ? app_info_->get_display_name() : app_id; if (!with_icon_) { return; } int icon_size = config_["icon-size"].isInt() ? config_["icon-size"].asInt() : 16; bool found = false; for (auto &icon_theme : tbar_->icon_themes()) { if (image_load_icon(icon_, icon_theme, app_info_, icon_size)) { found = true; break; } } if (found) icon_.show(); else spdlog::debug("Couldn't find icon for {}", app_id_); } void Task::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) { if (ignored_) { spdlog::debug("{} is ignored", repr()); return; } spdlog::debug("{} entered output {}", repr(), (void *)output); if (!button_visible_ && (tbar_->all_outputs() || tbar_->show_output(output))) { /* The task entered the output of the current bar make the button visible */ button.signal_size_allocate().connect_notify( sigc::mem_fun(this, &Task::on_button_size_allocated)); tbar_->add_button(button); button.show(); button_visible_ = true; spdlog::debug("{} now visible on {}", repr(), bar_.output->name); } } void Task::handle_output_leave(struct wl_output *output) { spdlog::debug("{} left output {}", repr(), (void *)output); if (button_visible_ && !tbar_->all_outputs() && tbar_->show_output(output)) { /* The task left the output of the current bar, make the button invisible */ tbar_->remove_button(button); button.hide(); button_visible_ = false; spdlog::debug("{} now invisible on {}", repr(), bar_.output->name); } } void Task::handle_state(struct wl_array *state) { state_ = 0; size_t size = state->size / sizeof(uint32_t); for (size_t i = 0; i < size; ++i) { auto entry = static_cast(state->data)[i]; if (entry == ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_MAXIMIZED) state_ |= MAXIMIZED; if (entry == ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_MINIMIZED) state_ |= MINIMIZED; if (entry == ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_ACTIVATED) state_ |= ACTIVE; if (entry == ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_FULLSCREEN) state_ |= FULLSCREEN; } } void Task::handle_done() { spdlog::debug("{} changed", repr()); if (state_ & MAXIMIZED) { button.get_style_context()->add_class("maximized"); } else if (!(state_ & MAXIMIZED)) { button.get_style_context()->remove_class("maximized"); } if (state_ & MINIMIZED) { button.get_style_context()->add_class("minimized"); } else if (!(state_ & MINIMIZED)) { button.get_style_context()->remove_class("minimized"); } if (state_ & ACTIVE) { button.get_style_context()->add_class("active"); } else if (!(state_ & ACTIVE)) { button.get_style_context()->remove_class("active"); } if (state_ & FULLSCREEN) { button.get_style_context()->add_class("fullscreen"); } else if (!(state_ & FULLSCREEN)) { button.get_style_context()->remove_class("fullscreen"); } if (config_["active-first"].isBool() && config_["active-first"].asBool() && active()) tbar_->move_button(button, 0); tbar_->dp.emit(); } void Task::handle_closed() { spdlog::debug("{} closed", repr()); zwlr_foreign_toplevel_handle_v1_destroy(handle_); handle_ = nullptr; if (button_visible_) { tbar_->remove_button(button); button_visible_ = false; } tbar_->remove_task(id_); } bool Task::handle_clicked(GdkEventButton *bt) { /* 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 */ drag_start_button = bt->button; drag_start_x = bt->x; drag_start_y = bt->y; } 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") activate(); else if (action == "minimize") { set_minimize_hint(); minimize(!minimized()); } else if (action == "minimize-raise") { set_minimize_hint(); if (minimized()) minimize(false); else if (active()) minimize(true); else activate(); } else if (action == "maximize") maximize(!maximized()); else if (action == "fullscreen") fullscreen(!fullscreen()); else if (action == "close") close(); else spdlog::warn("Unknown action {}", action); drag_start_button = -1; return true; } 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)) { /* start drag in addition to other assigned action */ 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); } return false; } 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; 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, 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; if (dragged_button == &this->button) return; auto parent_of_dragged = dragged_button->get_parent(); auto parent_of_dest = this->button.get_parent(); if (parent_of_dragged != parent_of_dest) return; auto box = (Gtk::Box *)parent_of_dragged; auto position_prop = box->child_property_position(this->button); auto position = position_prop.get_value(); 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_; } void Task::update() { bool markup = config_["markup"].isBool() ? config_["markup"].asBool() : false; std::string title = title_; std::string name = name_; std::string app_id = app_id_; if (markup) { title = Glib::Markup::escape_text(title); name = Glib::Markup::escape_text(name); app_id = Glib::Markup::escape_text(app_id); } if (!format_before_.empty()) { auto txt = fmt::format(fmt::runtime(format_before_), fmt::arg("title", title), fmt::arg("name", name), fmt::arg("app_id", app_id), fmt::arg("state", state_string()), fmt::arg("short_state", state_string(true))); txt = waybar::util::rewriteString(txt, config_["rewrite"]); if (markup) text_before_.set_markup(txt); else text_before_.set_label(txt); text_before_.show(); } if (!format_after_.empty()) { auto txt = fmt::format(fmt::runtime(format_after_), fmt::arg("title", title), fmt::arg("name", name), fmt::arg("app_id", app_id), fmt::arg("state", state_string()), fmt::arg("short_state", state_string(true))); txt = waybar::util::rewriteString(txt, config_["rewrite"]); if (markup) text_after_.set_markup(txt); else text_after_.set_label(txt); text_after_.show(); } if (!format_tooltip_.empty()) { auto txt = 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))); if (markup) button.set_tooltip_markup(txt); else button.set_tooltip_text(txt); } } void Task::maximize(bool set) { if (set) zwlr_foreign_toplevel_handle_v1_set_maximized(handle_); else zwlr_foreign_toplevel_handle_v1_unset_maximized(handle_); } void Task::minimize(bool set) { if (set) zwlr_foreign_toplevel_handle_v1_set_minimized(handle_); else zwlr_foreign_toplevel_handle_v1_unset_minimized(handle_); } void Task::activate() { zwlr_foreign_toplevel_handle_v1_activate(handle_, seat_); } void Task::fullscreen(bool set) { if (zwlr_foreign_toplevel_handle_v1_get_version(handle_) < ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_SET_FULLSCREEN_SINCE_VERSION) { spdlog::warn("Foreign toplevel manager server does not support for set/unset fullscreen."); return; } if (set) zwlr_foreign_toplevel_handle_v1_set_fullscreen(handle_, nullptr); else zwlr_foreign_toplevel_handle_v1_unset_fullscreen(handle_); } void Task::close() { zwlr_foreign_toplevel_handle_v1_close(handle_); } /* Taskbar class implementation */ static void handle_global(void *data, struct wl_registry *registry, uint32_t name, const char *interface, uint32_t version) { if (std::strcmp(interface, zwlr_foreign_toplevel_manager_v1_interface.name) == 0) { static_cast(data)->register_manager(registry, name, version); } else if (std::strcmp(interface, wl_seat_interface.name) == 0) { static_cast(data)->register_seat(registry, name, version); } } 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) : waybar::AModule(config, "taskbar", id, false, false), bar_(bar), box_{bar.orientation, 0}, manager_{nullptr}, seat_{nullptr} { box_.set_name("taskbar"); if (!id.empty()) { box_.get_style_context()->add_class(id); } box_.get_style_context()->add_class(MODULE_CLASS); 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); wl_registry_add_listener(registry, ®istry_listener_impl, this); wl_display_roundtrip(display); if (!manager_) { spdlog::error("Failed to register as toplevel manager"); return; } if (!seat_) { spdlog::error("Failed to get wayland seat"); return; } /* Get the configured icon theme if specified */ if (config_["icon-theme"].isArray()) { for (auto &c : config_["icon-theme"]) { auto it_name = c.asString(); auto it = Gtk::IconTheme::create(); it->set_custom_theme(it_name); spdlog::debug("Use custom icon theme: {}", it_name); icon_themes_.push_back(it); } } else if (config_["icon-theme"].isString()) { auto it_name = config_["icon-theme"].asString(); auto it = Gtk::IconTheme::create(); it->set_custom_theme(it_name); spdlog::debug("Use custom icon theme: {}", it_name); icon_themes_.push_back(it); } // Load ignore-list if (config_["ignore-list"].isArray()) { for (auto &app_name : config_["ignore-list"]) { ignore_list_.emplace(app_name.asString()); } } // Load app_id remappings if (config_["app_ids-mapping"].isObject()) { const Json::Value &mapping = config_["app_ids-mapping"]; const std::vector app_ids = config_["app_ids-mapping"].getMemberNames(); for (auto &app_id : app_ids) { app_ids_replace_map_.emplace(app_id, mapping[app_id].asString()); } } icon_themes_.push_back(Gtk::IconTheme::get_default()); 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; /* * Send `stop` request and wait for one roundtrip. * This is not quite correct as the protocol encourages us to wait for the .finished event, * but it should work with wlroots foreign toplevel manager implementation. */ zwlr_foreign_toplevel_manager_v1_stop(manager_); wl_display_roundtrip(display); if (manager_) { spdlog::warn("Foreign toplevel manager destroyed before .finished event"); zwlr_foreign_toplevel_manager_v1_destroy(manager_); manager_ = nullptr; } } } void Taskbar::update() { 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) { return a->app_id() < b->app_id(); }); for (unsigned long i = 0; i < tasks_.size(); i++) { move_button(tasks_[i]->button, i); } } 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_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 = { .toplevel = tm_handle_toplevel, .finished = tm_handle_finished, }; void Taskbar::register_manager(struct wl_registry *registry, uint32_t name, uint32_t version) { if (manager_) { spdlog::warn("Register foreign toplevel manager again although already existing!"); return; } if (version < ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_SET_FULLSCREEN_SINCE_VERSION) { spdlog::warn( "Foreign toplevel manager server does not have the appropriate version." " To be able to use all features, you need at least version 2, but server is version {}", version); } // limit version to a highest supported by the client protocol file version = std::min(version, zwlr_foreign_toplevel_manager_v1_interface.version); manager_ = static_cast( wl_registry_bind(registry, name, &zwlr_foreign_toplevel_manager_v1_interface, version)); if (manager_) zwlr_foreign_toplevel_manager_v1_add_listener(manager_, &toplevel_manager_impl, this); else spdlog::debug("Failed to register manager"); } void Taskbar::register_seat(struct wl_registry *registry, uint32_t name, uint32_t version) { if (seat_) { spdlog::warn("Register seat again although already existing!"); return; } version = std::min(version, wl_seat_interface.version); seat_ = static_cast(wl_registry_bind(registry, name, &wl_seat_interface, version)); } void Taskbar::handle_toplevel_create(struct zwlr_foreign_toplevel_handle_v1 *tl_handle) { tasks_.push_back(std::make_unique(bar_, config_, this, tl_handle, seat_)); } void Taskbar::handle_finished() { zwlr_foreign_toplevel_manager_v1_destroy(manager_); manager_ = nullptr; } void Taskbar::add_button(Gtk::Button &bt) { 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::remove_button(Gtk::Button &bt) { box_.remove(bt); if (box_.get_children().empty()) { box_.get_style_context()->add_class("empty"); } } void Taskbar::remove_task(uint32_t id) { auto it = std::find_if(std::begin(tasks_), std::end(tasks_), [id](const TaskPtr &p) { return p->id() == id; }); if (it == std::end(tasks_)) { spdlog::warn("Can't find task with id {}", id); return; } tasks_.erase(it); } bool Taskbar::show_output(struct wl_output *output) const { return output == gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj()); } bool Taskbar::all_outputs() const { return config_["all-outputs"].isBool() && config_["all-outputs"].asBool(); } const std::vector> &Taskbar::icon_themes() const { return icon_themes_; } const std::unordered_set &Taskbar::ignore_list() const { return ignore_list_; } const std::map &Taskbar::app_ids_replace_map() const { return app_ids_replace_map_; } } /* namespace waybar::modules::wlr */ waybar-0.12.0/src/modules/wlr/workspace_manager.cpp000066400000000000000000000427301475603165300223360ustar00rootroot00000000000000#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 waybar-0.12.0/src/modules/wlr/workspace_manager_binding.cpp000066400000000000000000000123751475603165300240320ustar00rootroot00000000000000#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 waybar-0.12.0/src/util/000077500000000000000000000000001475603165300146355ustar00rootroot00000000000000waybar-0.12.0/src/util/audio_backend.cpp000066400000000000000000000265151475603165300201220ustar00rootroot00000000000000#include "util/audio_backend.hpp" #include #include #include #include #include #include #include #include #include #include #include namespace waybar::util { AudioBackend::AudioBackend(std::function on_updated_cb, private_constructor_tag tag) : mainloop_(nullptr), mainloop_api_(nullptr), context_(nullptr), volume_(0), muted_(false), source_volume_(0), source_muted_(false), on_updated_cb_(std::move(on_updated_cb)) { mainloop_ = pa_threaded_mainloop_new(); if (mainloop_ == nullptr) { throw std::runtime_error("pa_mainloop_new() failed."); } pa_threaded_mainloop_lock(mainloop_); mainloop_api_ = pa_threaded_mainloop_get_api(mainloop_); connectContext(); if (pa_threaded_mainloop_start(mainloop_) < 0) { throw std::runtime_error("pa_mainloop_run() failed."); } pa_threaded_mainloop_unlock(mainloop_); } AudioBackend::~AudioBackend() { if (context_ != nullptr) { pa_context_disconnect(context_); } if (mainloop_ != nullptr) { mainloop_api_->quit(mainloop_api_, 0); pa_threaded_mainloop_stop(mainloop_); pa_threaded_mainloop_free(mainloop_); } } std::shared_ptr AudioBackend::getInstance(std::function on_updated_cb) { private_constructor_tag tag; return std::make_shared(on_updated_cb, tag); } void AudioBackend::connectContext() { context_ = pa_context_new(mainloop_api_, "waybar"); if (context_ == nullptr) { throw std::runtime_error("pa_context_new() failed."); } pa_context_set_state_callback(context_, contextStateCb, this); if (pa_context_connect(context_, nullptr, PA_CONTEXT_NOFAIL, nullptr) < 0) { auto err = fmt::format("pa_context_connect() failed: {}", pa_strerror(pa_context_errno(context_))); throw std::runtime_error(err); } } 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); break; case PA_CONTEXT_READY: pa_context_get_server_info(c, serverInfoCb, data); pa_context_set_subscribe_callback(c, subscribeCb, data); pa_context_subscribe(c, static_cast( static_cast(PA_SUBSCRIPTION_MASK_SERVER) | static_cast(PA_SUBSCRIPTION_MASK_SINK) | static_cast(PA_SUBSCRIPTION_MASK_SINK_INPUT) | static_cast(PA_SUBSCRIPTION_MASK_SOURCE) | static_cast(PA_SUBSCRIPTION_MASK_SOURCE_OUTPUT)), nullptr, nullptr); 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_); } backend->connectContext(); break; case PA_CONTEXT_CONNECTING: case PA_CONTEXT_AUTHORIZING: case PA_CONTEXT_SETTING_NAME: default: break; } } /* * 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) { unsigned facility = type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK; unsigned operation = type & PA_SUBSCRIPTION_EVENT_TYPE_MASK; if (operation != PA_SUBSCRIPTION_EVENT_CHANGE) { return; } if (facility == PA_SUBSCRIPTION_EVENT_SERVER) { pa_context_get_server_info(context, serverInfoCb, data); } else if (facility == PA_SUBSCRIPTION_EVENT_SINK) { pa_context_get_sink_info_by_index(context, idx, sinkInfoCb, data); } else if (facility == PA_SUBSCRIPTION_EVENT_SINK_INPUT) { pa_context_get_sink_info_list(context, sinkInfoCb, data); } else if (facility == PA_SUBSCRIPTION_EVENT_SOURCE) { pa_context_get_source_info_by_index(context, idx, sourceInfoCb, data); } else if (facility == PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT) { pa_context_get_source_info_list(context, sourceInfoCb, data); } } /* * Called in response to a volume change request */ void AudioBackend::volumeModifyCb(pa_context *c, int success, void *data) { auto *backend = static_cast(data); if (success != 0) { pa_context_get_sink_info_by_index(backend->context_, backend->sink_idx_, sinkInfoCb, data); } } /* * Called when the requested sink information is ready. */ 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); if (!backend->ignored_sinks_.empty()) { 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 // so it will be replaced with another sink. backend->current_sink_running_ = false; } return; } } } backend->default_sink_running_ = backend->default_sink_name == i->name && (i->state == PA_SINK_RUNNING || i->state == PA_SINK_IDLE); if (i->name != backend->default_sink_name && !backend->default_sink_running_) { return; } if (backend->current_sink_name_ == i->name) { backend->current_sink_running_ = (i->state == PA_SINK_RUNNING || i->state == PA_SINK_IDLE); } if (!backend->current_sink_running_ && (i->state == PA_SINK_RUNNING || i->state == PA_SINK_IDLE)) { backend->current_sink_name_ = i->name; backend->current_sink_running_ = true; } if (backend->current_sink_name_ == i->name) { backend->pa_volume_ = i->volume; float volume = static_cast(pa_cvolume_avg(&(backend->pa_volume_))) / float{PA_VOLUME_NORM}; backend->sink_idx_ = i->index; backend->volume_ = std::round(volume * 100.0F); backend->muted_ = i->mute != 0; 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)) { backend->form_factor_ = ff; } else { backend->form_factor_ = ""; } backend->on_updated_cb_(); } } /* * 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); 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); backend->source_idx_ = i->index; backend->source_muted_ = i->mute != 0; backend->source_desc_ = i->description; backend->source_port_name_ = i->active_port != nullptr ? i->active_port->name : "Unknown"; backend->on_updated_cb_(); } } /* * 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; pa_context_get_sink_info_list(context, sinkInfoCb, data); pa_context_get_source_info_list(context, sourceInfoCb, data); } void AudioBackend::changeVolume(uint16_t volume, uint16_t min_volume, uint16_t max_volume) { double volume_tick = static_cast(PA_VOLUME_NORM) / 100; pa_cvolume pa_volume = pa_volume_; volume = std::clamp(volume, min_volume, max_volume); pa_cvolume_set(&pa_volume, pa_volume_.channels, volume * volume_tick); pa_threaded_mainloop_lock(mainloop_); pa_context_set_sink_volume_by_index(context_, sink_idx_, &pa_volume, volumeModifyCb, this); pa_threaded_mainloop_unlock(mainloop_); } void AudioBackend::changeVolume(ChangeType change_type, double step, uint16_t max_volume) { double volume_tick = static_cast(PA_VOLUME_NORM) / 100; pa_volume_t change = volume_tick; pa_cvolume pa_volume = pa_volume_; max_volume = std::min(max_volume, static_cast(PA_VOLUME_UI_MAX)); if (change_type == ChangeType::Increase) { if (volume_ < max_volume) { if (volume_ + step > max_volume) { change = round((max_volume - volume_) * volume_tick); } else { change = round(step * volume_tick); } pa_cvolume_inc(&pa_volume, change); } } else if (change_type == ChangeType::Decrease) { if (volume_ > 0) { if (volume_ - step < 0) { change = round(volume_ * volume_tick); } else { change = round(step * volume_tick); } pa_cvolume_dec(&pa_volume, change); } } pa_threaded_mainloop_lock(mainloop_); pa_context_set_sink_volume_by_index(context_, sink_idx_, &pa_volume, volumeModifyCb, this); pa_threaded_mainloop_unlock(mainloop_); } void AudioBackend::toggleSinkMute() { muted_ = !muted_; pa_threaded_mainloop_lock(mainloop_); pa_context_set_sink_mute_by_index(context_, sink_idx_, static_cast(muted_), nullptr, nullptr); pa_threaded_mainloop_unlock(mainloop_); } void AudioBackend::toggleSinkMute(bool mute) { muted_ = mute; pa_threaded_mainloop_lock(mainloop_); pa_context_set_sink_mute_by_index(context_, sink_idx_, static_cast(muted_), nullptr, nullptr); pa_threaded_mainloop_unlock(mainloop_); } void AudioBackend::toggleSourceMute() { source_muted_ = !muted_; pa_threaded_mainloop_lock(mainloop_); pa_context_set_source_mute_by_index(context_, source_idx_, static_cast(source_muted_), nullptr, nullptr); pa_threaded_mainloop_unlock(mainloop_); } void AudioBackend::toggleSourceMute(bool mute) { source_muted_ = mute; pa_threaded_mainloop_lock(mainloop_); pa_context_set_source_mute_by_index(context_, source_idx_, static_cast(source_muted_), nullptr, nullptr); pa_threaded_mainloop_unlock(mainloop_); } 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) { if (config.isArray()) { for (const auto &ignored_sink : config) { if (ignored_sink.isString()) { ignored_sinks_.push_back(ignored_sink.asString()); } } } } } // namespace waybar::util waybar-0.12.0/src/util/backlight_backend.cpp000066400000000000000000000234441475603165300207470ustar00rootroot00000000000000#include "util/backlight_backend.hpp" #include #include #include #include #include #include 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() { if (fd_ != -1) { if (close(fd_) != 0) { fmt::print(stderr, "Failed to close fd: {}\n", errno); } } } int get() const { return fd_; } private: 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: ") { 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: ") { 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 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") { if (ptr == nullptr) { throw std::runtime_error(message); } } } // namespace namespace waybar::util { 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 = 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"); 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)); } if (max != nullptr) { found->set_max(std::stoi(max)); } if (power != nullptr) { found->set_powered(std::stoi(power) == 0); } } 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; devices.emplace_back(name, actual_int, max_int, power_bool); } } 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_foreach(dev_list_entry, enum_devices) { 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()); } } BacklightDevice::BacklightDevice(std::string name, int actual, int max, bool powered) : name_(std::move(name)), actual_(actual), max_(max), powered_(powered) {} std::string BacklightDevice::name() const { return name_; } int BacklightDevice::get_actual() const { return actual_; } void BacklightDevice::set_actual(int actual) { actual_ = actual; } int BacklightDevice::get_max() const { return max_; } void BacklightDevice::set_max(int max) { max_ = max; } bool BacklightDevice::get_powered() const { return powered_; } void BacklightDevice::set_powered(bool powered) { powered_ = powered; } BacklightBackend::BacklightBackend(std::chrono::milliseconds interval, std::function on_updated_cb) : on_updated_cb_(std::move(on_updated_cb)), polling_interval_(interval), previous_best_({}) { std::unique_ptr udev_check{udev_new()}; check_nn(udev_check.get(), "Udev check new failed"); enumerate_devices(devices_, udev_check.get()); if (devices_.empty()) { throw std::runtime_error("No backlight found"); } // Connect to the login interface login_proxy_ = Gio::DBus::Proxy::create_for_bus_sync( Gio::DBus::BusType::BUS_TYPE_SYSTEM, "org.freedesktop.login1", "/org/freedesktop/login1/session/auto", "org.freedesktop.login1.Session"); if (!login_proxy_) { login_proxy_ = Gio::DBus::Proxy::create_for_bus_sync( Gio::DBus::BusType::BUS_TYPE_SYSTEM, "org.freedesktop.login1", "/org/freedesktop/login1/session/self", "org.freedesktop.login1.Session"); } udev_thread_ = [this] { std::unique_ptr udev{udev_new()}; check_nn(udev.get(), "Udev new failed"); std::unique_ptr mon{ udev_monitor_new_from_netlink(udev.get(), "udev")}; check_nn(mon.get(), "udev monitor new failed"); check_gte(udev_monitor_filter_add_match_subsystem_devtype(mon.get(), "backlight", nullptr), 0, "udev failed to add monitor filter: "); udev_monitor_enable_receiving(mon.get()); auto udev_fd = udev_monitor_get_fd(mon.get()); auto epoll_fd = FileDescriptor{epoll_create1(EPOLL_CLOEXEC)}; check_neq(epoll_fd.get(), -1, "epoll init failed: "); epoll_event ctl_event{}; ctl_event.events = EPOLLIN; ctl_event.data.fd = udev_fd; check0(epoll_ctl(epoll_fd.get(), EPOLL_CTL_ADD, ctl_event.data.fd, &ctl_event), "epoll_ctl failed: {}"); epoll_event events[EPOLL_MAX_EVENTS]; while (udev_thread_.isRunning()) { const int event_count = epoll_wait(epoll_fd.get(), events, EPOLL_MAX_EVENTS, this->polling_interval_.count()); if (!udev_thread_.isRunning()) { break; } decltype(devices_) devices; { std::scoped_lock lock(udev_thread_mutex_); devices = devices_; } for (int i = 0; i < event_count; ++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"); upsert_device(devices, dev.get()); } // Refresh state if timed out if (event_count == 0) { enumerate_devices(devices, udev.get()); } { std::scoped_lock lock(udev_thread_mutex_); devices_ = devices; } this->on_updated_cb_(); } }; } 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; }); 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(); }); return max == devices.end() ? nullptr : &(*max); } const BacklightDevice *BacklightBackend::get_previous_best_device() { return previous_best_.has_value() ? &(*previous_best_) : nullptr; } void BacklightBackend::set_previous_best_device(const BacklightDevice *device) { if (device == nullptr) { previous_best_ = std::nullopt; } else { previous_best_ = std::optional{*device}; } } void BacklightBackend::set_scaled_brightness(const std::string &preferred_device, int brightness) { GET_BEST_DEVICE(best, (*this), preferred_device); if (best != nullptr) { const auto max = best->get_max(); const auto abs_val = static_cast(std::round(brightness * max / 100.0F)); set_brightness_internal(best->name(), abs_val, best->get_max()); } } void BacklightBackend::set_brightness(const std::string &preferred_device, ChangeType change_type, double step) { GET_BEST_DEVICE(best, (*this), preferred_device); if (best != nullptr) { const auto max = best->get_max(); const auto abs_step = static_cast(round(step * max / 100.0F)); const int new_brightness = change_type == ChangeType::Increase ? best->get_actual() + abs_step : best->get_actual() - abs_step; set_brightness_internal(best->name(), new_brightness, max); } } void BacklightBackend::set_brightness_internal(const std::string &device_name, int brightness, int max_brightness) { brightness = std::clamp(brightness, 0, max_brightness); auto call_args = Glib::VariantContainerBase( g_variant_new("(ssu)", "backlight", device_name.c_str(), brightness)); login_proxy_->call_sync("SetBrightness", call_args); } 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(); } return 0; } } // namespace waybar::util waybar-0.12.0/src/util/css_reload_helper.cpp000066400000000000000000000103551475603165300210220ustar00rootroot00000000000000#include "util/css_reload_helper.hpp" #include #include #include #include #include #include #include #include "config.hpp" #include "giomm/file.h" #include "glibmm/refptr.h" namespace { const std::regex IMPORT_REGEX(R"(@import\s+(?:url\()?(?:"|')([^"')]+)(?:"|')\)?;)"); } 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) { if (filename.empty()) { return {}; } std::ifstream file(filename); if (!file.is_open()) { return {}; } return {(std::istreambuf_iterator(file)), std::istreambuf_iterator()}; } std::string waybar::CssReloadHelper::findPath(const std::string& filename) { // try path and fallback to looking relative to the config std::string result; if (std::filesystem::exists(filename)) { result = filename; } else { result = Config::findConfigPath({filename}).value_or(""); } // File monitor does not work with symlinks, so resolve them std::string original = result; while (std::filesystem::is_symlink(result)) { result = std::filesystem::read_symlink(result); // prevent infinite cycle if (result == original) { break; } } return result; } void waybar::CssReloadHelper::monitorChanges() { auto files = parseImports(m_cssFile); for (const auto& file : files) { auto gioFile = Gio::File::create_for_path(file); if (!gioFile) { spdlog::error("Failed to create file for path: {}", file); continue; } auto fileMonitor = gioFile->monitor_file(); if (!fileMonitor) { spdlog::error("Failed to create file monitor for path: {}", file); continue; } auto connection = fileMonitor->signal_changed().connect( sigc::mem_fun(*this, &CssReloadHelper::handleFileChange)); if (!connection.connected()) { spdlog::error("Failed to connect to file monitor for path: {}", file); continue; } m_fileMonitors.emplace_back(std::move(fileMonitor)); } } void waybar::CssReloadHelper::handleFileChange(Glib::RefPtr const& file, Glib::RefPtr const& other_type, Gio::FileMonitorEvent event_type) { // Multiple events are fired on file changed (attributes, write, changes done hint, etc.), only // 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(); } } std::vector waybar::CssReloadHelper::parseImports(const std::string& cssFile) { std::unordered_map imports; auto cssFullPath = findPath(cssFile); if (cssFullPath.empty()) { spdlog::error("Failed to find css file: {}", cssFile); return {}; } spdlog::debug("Parsing imports for file: {}", cssFullPath); imports[cssFullPath] = false; auto previousSize = 0UL; auto maxIterations = 100U; do { previousSize = imports.size(); for (const auto& [file, parsed] : imports) { if (!parsed) { parseImports(file, imports); } } } while (imports.size() > previousSize && maxIterations-- > 0); std::vector result; for (const auto& [file, parsed] : imports) { if (parsed) { spdlog::debug("Adding file to watch list: {}", file); result.push_back(file); } } return result; } void waybar::CssReloadHelper::parseImports(const std::string& cssFile, std::unordered_map& imports) { // if the file has already been parsed, skip if (imports.find(cssFile) != imports.end() && imports[cssFile]) { return; } auto contents = getFileContents(cssFile); std::smatch matches; while (std::regex_search(contents, matches, IMPORT_REGEX)) { auto importFile = findPath({matches[1].str()}); if (!importFile.empty() && imports.find(importFile) == imports.end()) { imports[importFile] = false; } contents = matches.suffix().str(); } imports[cssFile] = true; } waybar-0.12.0/src/util/enum.cpp000066400000000000000000000027741475603165300163170ustar00rootroot00000000000000#include "util/enum.hpp" #include // for std::transform #include // for std::toupper #include #include #include #include #include "modules/hyprland/workspaces.hpp" #include "util/string.hpp" namespace waybar::util { template EnumParser::EnumParser() = default; template EnumParser::~EnumParser() = default; template EnumType EnumParser::parseStringToEnum(const std::string& str, const std::map& enumMap) { // Convert the input string to uppercase std::string uppercaseStr = capitalize(str); // Capitalize the map keys before searching std::map capitalizedEnumMap; std::transform( enumMap.begin(), enumMap.end(), std::inserter(capitalizedEnumMap, capitalizedEnumMap.end()), [](const auto& pair) { return std::make_pair(capitalize(pair.first), pair.second); }); // Return enum match of string auto it = capitalizedEnumMap.find(uppercaseStr); if (it != capitalizedEnumMap.end()) return it->second; // Throw error if it doesn't return throw std::invalid_argument("Invalid string representation for enum"); } // Explicit instantiations for specific EnumType types you intend to use // Add explicit instantiations for all relevant EnumType types template struct EnumParser; } // namespace waybar::util waybar-0.12.0/src/util/gtk_icon.cpp000066400000000000000000000021251475603165300171360ustar00rootroot00000000000000#include "util/gtk_icon.hpp" /* We need a global mutex for accessing the object returned by Gtk::IconTheme::get_default() * because it always returns the same object across different threads, and concurrent * access can cause data corruption and lead to invalid memory access and crashes. * Even concurrent calls that seem read only such as has_icon can cause issues because * the GTK lib may update the internal icon cache on this calls. */ std::mutex DefaultGtkIconThemeWrapper::default_theme_mutex; bool DefaultGtkIconThemeWrapper::has_icon(const std::string& value) { const std::lock_guard lock(default_theme_mutex); return Gtk::IconTheme::get_default()->has_icon(value); } Glib::RefPtr DefaultGtkIconThemeWrapper::load_icon(const char* name, int tmp_size, Gtk::IconLookupFlags flags) { 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); } waybar-0.12.0/src/util/pipewire/000077500000000000000000000000001475603165300164615ustar00rootroot00000000000000waybar-0.12.0/src/util/pipewire/pipewire_backend.cpp000066400000000000000000000115221475603165300224610ustar00rootroot00000000000000#include "util/pipewire/pipewire_backend.hpp" #include "util/pipewire/privacy_node_info.hpp" namespace waybar::util::PipewireBackend { 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 const struct pw_node_events NODE_EVENTS = { .version = PW_VERSION_NODE_EVENTS, .info = getNodeInfo, }; static void proxyDestroy(void *data) { static_cast(data)->handleProxyEventDestroy(); } static const struct pw_proxy_events PROXY_EVENTS = { .version = PW_VERSION_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 registryEventGlobalRemove(void *_data, uint32_t id) { static_cast(_data)->handleRegistryEventGlobalRemove(id); } static const struct pw_registry_events REGISTRY_EVENTS = { .version = PW_VERSION_REGISTRY_EVENTS, .global = registryEventGlobal, .global_remove = registryEventGlobalRemove, }; PipewireBackend::PipewireBackend(PrivateConstructorTag tag) : mainloop_(nullptr), context_(nullptr), core_(nullptr) { pw_init(nullptr, nullptr); mainloop_ = pw_thread_loop_new("waybar", nullptr); if (mainloop_ == nullptr) { throw std::runtime_error("pw_thread_loop_new() failed."); } pw_thread_loop_lock(mainloop_); context_ = pw_context_new(pw_thread_loop_get_loop(mainloop_), nullptr, 0); if (context_ == nullptr) { pw_thread_loop_unlock(mainloop_); throw std::runtime_error("pa_context_new() failed."); } core_ = pw_context_connect(context_, nullptr, 0); if (core_ == nullptr) { pw_thread_loop_unlock(mainloop_); throw std::runtime_error("pw_context_connect() failed"); } registry_ = pw_core_get_registry(core_, PW_VERSION_REGISTRY, 0); spa_zero(registryListener_); pw_registry_add_listener(registry_, ®istryListener_, ®ISTRY_EVENTS, this); if (pw_thread_loop_start(mainloop_) < 0) { pw_thread_loop_unlock(mainloop_); throw std::runtime_error("pw_thread_loop_start() failed."); } pw_thread_loop_unlock(mainloop_); } PipewireBackend::~PipewireBackend() { if (mainloop_ != nullptr) { pw_thread_loop_lock(mainloop_); } if (registry_ != nullptr) { pw_proxy_destroy((struct pw_proxy *)registry_); } spa_zero(registryListener_); if (core_ != nullptr) { pw_core_disconnect(core_); } if (context_ != nullptr) { pw_context_destroy(context_); } if (mainloop_ != nullptr) { pw_thread_loop_unlock(mainloop_); pw_thread_loop_stop(mainloop_); pw_thread_loop_destroy(mainloop_); } } std::shared_ptr PipewireBackend::getInstance() { PrivateConstructorTag tag; 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) { if (props == nullptr || strcmp(type, PW_TYPE_INTERFACE_Node) != 0) return; 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; if (mediaClass == "Stream/Input/Video") { mediaType = PRIVACY_NODE_TYPE_VIDEO_INPUT; } else if (mediaClass == "Stream/Input/Audio") { mediaType = PRIVACY_NODE_TYPE_AUDIO_INPUT; } else if (mediaClass == "Stream/Output/Audio") { mediaType = PRIVACY_NODE_TYPE_AUDIO_OUTPUT; } else { return; } 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); new (pNodeInfo) PrivacyNodeInfo{}; pNodeInfo->id = id; pNodeInfo->data = this; pNodeInfo->type = mediaType; pNodeInfo->media_class = mediaClass; pw_proxy_add_listener(proxy, &pNodeInfo->proxy_listener, &PROXY_EVENTS, pNodeInfo); pw_proxy_add_object_listener(proxy, &pNodeInfo->object_listener, &NODE_EVENTS, pNodeInfo); privacy_nodes.insert_or_assign(id, pNodeInfo); } void PipewireBackend::handleRegistryEventGlobalRemove(uint32_t id) { mutex_.lock(); auto iter = privacy_nodes.find(id); if (iter != privacy_nodes.end()) { privacy_nodes[id]->~PrivacyNodeInfo(); privacy_nodes.erase(id); } mutex_.unlock(); privacy_nodes_changed_signal_event.emit(); } } // namespace waybar::util::PipewireBackend waybar-0.12.0/src/util/pipewire/privacy_node_info.cpp000066400000000000000000000034711475603165300226670ustar00rootroot00000000000000#include "util/pipewire/privacy_node_info.hpp" namespace waybar::util::PipewireBackend { std::string PrivacyNodeInfo::getName() { const std::vector names{&application_name, &node_name}; std::string name = "Unknown Application"; for (const auto &item : names) { if (item != nullptr && !item->empty()) { name = *item; name[0] = toupper(name[0]); break; } } return name; } std::string PrivacyNodeInfo::getIconName() { 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) { if (item != nullptr && !item->empty() && DefaultGtkIconThemeWrapper::has_icon(*item)) { return *item; } } return name; } void PrivacyNodeInfo::handleProxyEventDestroy() { spa_hook_remove(&proxy_listener); spa_hook_remove(&object_listener); } void PrivacyNodeInfo::handleNodeEventInfo(const struct pw_node_info *info) { state = info->state; 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); } else if (strcmp(item->key, PW_KEY_MEDIA_NAME) == 0) { media_name = item->value; } else if (strcmp(item->key, PW_KEY_NODE_NAME) == 0) { node_name = item->value; } else if (strcmp(item->key, PW_KEY_APP_NAME) == 0) { application_name = item->value; } else if (strcmp(item->key, "pipewire.access.portal.app_id") == 0) { pipewire_access_portal_app_id = item->value; } else if (strcmp(item->key, PW_KEY_APP_ICON_NAME) == 0) { application_icon_name = item->value; } } } } // namespace waybar::util::PipewireBackend waybar-0.12.0/src/util/portal.cpp000066400000000000000000000073111475603165300166440ustar00rootroot00000000000000#include "util/portal.hpp" #include #include #include #include #include #include "fmt/format.h" namespace waybar { static constexpr const char* PORTAL_BUS_NAME = "org.freedesktop.portal.Desktop"; static constexpr const char* PORTAL_OBJ_PATH = "/org/freedesktop/portal/desktop"; static constexpr const char* PORTAL_INTERFACE = "org.freedesktop.portal.Settings"; 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) { case waybar::Appearance::LIGHT: name = "light"; break; case waybar::Appearance::DARK: name = "dark"; break; default: name = "unknown"; break; } return formatter::format(name, ctx); } waybar::Portal::Portal() : DBus::Proxy(DBus::Connection::get_sync(DBus::BusType::BUS_TYPE_SESSION), PORTAL_BUS_NAME, PORTAL_OBJ_PATH, PORTAL_INTERFACE), currentMode(Appearance::UNKNOWN) { refreshAppearance(); }; void waybar::Portal::refreshAppearance() { auto params = Glib::Variant>::create( {PORTAL_NAMESPACE, PORTAL_KEY}); Glib::VariantBase response; try { response = call_sync(std::string(PORTAL_INTERFACE) + ".Read", params); } catch (const Glib::Error& e) { spdlog::info("Unable to receive desktop appearance: {}", std::string(e.what())); return; } // unfortunately, the response is triple-nested, with type (v>), // so we have cast thrice. This is a variation from the freedesktop standard // (it should only be doubly nested) but all implementations appear to do so. // // 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) { return; } spdlog::info("Discovered appearance '{}'", newMode); currentMode = newMode; m_signal_appearance_changed.emit(currentMode); } waybar::Appearance waybar::Portal::getAppearance() { return currentMode; }; void waybar::Portal::on_signal(const Glib::ustring& sender_name, const Glib::ustring& signal_name, const Glib::VariantContainerBase& parameters) { spdlog::debug("Received signal {}", (std::string)signal_name); if (signal_name != "SettingChanged" || parameters.get_n_children() != 3) { return; } Glib::VariantBase nspcv; Glib::VariantBase keyv; Glib::VariantBase valuev; parameters.get_child(nspcv, 0); parameters.get_child(keyv, 1); parameters.get_child(valuev, 2); auto nspc = Glib::VariantBase::cast_dynamic>(nspcv).get(); auto key = Glib::VariantBase::cast_dynamic>(keyv).get(); if (nspc != PORTAL_NAMESPACE || key != PORTAL_KEY) { return; } auto value = Glib::VariantBase::cast_dynamic>>(valuev).get().get(); auto newMode = Appearance(value); if (newMode == currentMode) { return; } spdlog::info("Received new appearance '{}'", newMode); currentMode = newMode; m_signal_appearance_changed.emit(currentMode); } waybar-0.12.0/src/util/prepare_for_sleep.cpp000066400000000000000000000030231475603165300210330ustar00rootroot00000000000000#include "util/prepare_for_sleep.h" #include #include namespace { class PrepareForSleep { private: PrepareForSleep() { login1_connection = g_bus_get_sync(G_BUS_TYPE_SYSTEM, nullptr, nullptr); if (login1_connection == nullptr) { spdlog::warn("Unable to connect to the SYSTEM Bus!..."); } else { login1_id = g_dbus_connection_signal_subscribe( login1_connection, "org.freedesktop.login1", "org.freedesktop.login1.Manager", "PrepareForSleep", "/org/freedesktop/login1", nullptr, G_DBUS_SIGNAL_FLAGS_NONE, prepareForSleep_cb, this, nullptr); } } 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); self->signal.emit(sleeping); } } public: static PrepareForSleep &GetInstance() { static PrepareForSleep instance; return instance; } waybar::SafeSignal signal; private: guint login1_id; GDBusConnection *login1_connection; }; } // namespace waybar::SafeSignal &waybar::util::prepare_for_sleep() { return PrepareForSleep::GetInstance().signal; } waybar-0.12.0/src/util/regex_collection.cpp000066400000000000000000000037251475603165300206750ustar00rootroot00000000000000#include "util/regex_collection.hpp" #include #include #include #include namespace waybar::util { int default_priority_function(std::string& key) { return 0; } RegexCollection::RegexCollection(const Json::Value& map, std::string default_repr, const std::function& priority_function) : default_repr(std::move(default_repr)) { if (!map.isObject()) { spdlog::warn("Mapping is not an object"); return; } for (auto it = map.begin(); it != map.end(); ++it) { if (it.key().isString() && it->isString()) { std::string key = it.key().asString(); int priority = priority_function(key); try { const std::regex rule{key, std::regex_constants::icase}; rules.emplace_back(rule, it->asString(), priority); } catch (const std::regex_error& e) { spdlog::error("Invalid rule '{}': {}", key, e.what()); } } } std::sort(rules.begin(), rules.end(), [](Rule& a, Rule& b) { return a.priority > b.priority; }); } std::string RegexCollection::find_match(std::string& value, bool& matched_any) { for (auto& rule : rules) { std::smatch match; if (std::regex_search(value, match, rule.rule)) { matched_any = true; return match.format(rule.repr.data()); } } return value; } std::string& RegexCollection::get(std::string& value, bool& matched_any) { if (regex_cache.contains(value)) { return regex_cache[value]; } // std::string repr = // waybar::util::find_match(value, window_rewrite_rules_, matched_any); std::string repr = find_match(value, matched_any); if (!matched_any) { repr = default_repr; } regex_cache.emplace(value, repr); return regex_cache[value]; // Necessary in order to return a reference to the heap } std::string& RegexCollection::get(std::string& value) { bool matched_any = false; return get(value, matched_any); } } // namespace waybar::util waybar-0.12.0/src/util/rewrite_string.cpp000066400000000000000000000015631475603165300204150ustar00rootroot00000000000000#include "util/rewrite_string.hpp" #include #include namespace waybar::util { std::string rewriteString(const std::string& value, const Json::Value& rules) { if (!rules.isObject()) { return value; } std::string res = value; for (auto it = rules.begin(); it != rules.end(); ++it) { if (it.key().isString() && it->isString()) { try { // 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)) { res = std::regex_replace(res, rule, it->asString()); } } catch (const std::regex_error& e) { spdlog::error("Invalid rule {}: {}", it.key().asString(), e.what()); } } } return res; } } // namespace waybar::util waybar-0.12.0/src/util/rfkill.cpp000066400000000000000000000051231475603165300166250ustar00rootroot00000000000000/* https://git.kernel.org/pub/scm/linux/kernel/git/jberg/rfkill.git/ * * Copyright 2009 Johannes Berg * Copyright 2009 Marcel Holtmann * Copyright 2009 Tim Gardner * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, 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. */ #include "util/rfkill.hpp" #include #include #include #include #include #include waybar::util::Rfkill::Rfkill(const enum rfkill_type rfkill_type) : rfkill_type_(rfkill_type) { fd_ = open("/dev/rfkill", O_RDONLY); if (fd_ < 0) { spdlog::error("Can't open RFKILL control device"); return; } int rc = fcntl(fd_, F_SETFL, O_NONBLOCK); if (rc < 0) { spdlog::error("Can't set RFKILL control device to non-blocking: {}", errno); close(fd_); fd_ = -1; return; } Glib::signal_io().connect(sigc::mem_fun(*this, &Rfkill::on_event), fd_, Glib::IO_IN | Glib::IO_ERR | Glib::IO_HUP); } waybar::util::Rfkill::~Rfkill() { if (fd_ >= 0) { close(fd_); } } bool waybar::util::Rfkill::on_event(Glib::IOCondition cond) { if (cond & Glib::IO_IN) { struct rfkill_event event; ssize_t len; len = read(fd_, &event, sizeof(event)); if (len < 0) { if (errno == EAGAIN) { return true; } spdlog::error("Reading of RFKILL events failed: {}", errno); return false; } if (static_cast(len) < RFKILL_EVENT_SIZE_V1) { spdlog::error("Wrong size of RFKILL event: {} < {}", len, RFKILL_EVENT_SIZE_V1); return true; } if (event.type == rfkill_type_ && (event.op == RFKILL_OP_ADD || event.op == RFKILL_OP_CHANGE)) { state_ = event.soft || event.hard; on_update.emit(event); } return true; } spdlog::error("Failed to poll RFKILL control device"); return false; } bool waybar::util::Rfkill::getState() const { return state_; } waybar-0.12.0/src/util/sanitize_str.cpp000066400000000000000000000013771475603165300200670ustar00rootroot00000000000000#include #include #include #include namespace waybar::util { // replaces ``<>&"'`` with their encoded counterparts std::string sanitize_string(std::string str) { // note: it's important that '&' is replaced first; therefore we *can't* use std::map const std::pair replacement_table[] = { {'&', "&"}, {'<', "<"}, {'>', ">"}, {'"', """}, {'\'', "'"}}; size_t startpoint; for (const auto& pair : replacement_table) { startpoint = 0; while ((startpoint = str.find(pair.first, startpoint)) != std::string::npos) { str.replace(startpoint, 1, pair.second); startpoint += pair.second.length(); } } return str; } } // namespace waybar::util waybar-0.12.0/src/util/ustring_clen.cpp000066400000000000000000000002731475603165300200370ustar00rootroot00000000000000#include "util/ustring_clen.hpp" int ustring_clen(const Glib::ustring &str) { int total = 0; for (unsigned int i : str) { total += g_unichar_iswide(i) + 1; } return total; } waybar-0.12.0/subprojects/000077500000000000000000000000001475603165300154345ustar00rootroot00000000000000waybar-0.12.0/subprojects/catch2.wrap000066400000000000000000000006601475603165300174750ustar00rootroot00000000000000[wrap-file] directory = Catch2-3.7.0 source_url = https://github.com/catchorg/Catch2/archive/v3.7.0.tar.gz source_filename = Catch2-3.7.0.tar.gz source_hash = 5b10cd536fa3818112a82820ce0787bd9f2a906c618429e7c4dea639983c8e88 source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/catch2_3.7.0-1/Catch2-3.7.0.tar.gz wrapdb_version = 3.7.0-1 [provide] catch2 = catch2_dep catch2-with-main = catch2_with_main_dep waybar-0.12.0/subprojects/cava.wrap000066400000000000000000000003711475603165300172420ustar00rootroot00000000000000[wrap-file] directory = cava-0.10.3 source_url = https://github.com/LukashonakV/cava/archive/0.10.3.tar.gz source_filename = cava-0.10.3.tar.gz source_hash = aab0a4ed3f999e8461ad9de63ef8a77f28b6b2011f7dd0c69ba81819d442f6f9 [provide] cava = cava_dep waybar-0.12.0/subprojects/date.wrap000066400000000000000000000007521475603165300172500ustar00rootroot00000000000000[wrap-file] source_url = https://github.com/HowardHinnant/date/archive/v3.0.1.tar.gz source_filename = date-3.0.1.tar.gz source_hash = 7a390f200f0ccd207e8cff6757e04817c1a0aec3e327b006b7eb451c57ee3538 directory = date-3.0.1 patch_filename = hinnant-date_3.0.1-2_patch.zip patch_url = https://wrapdb.mesonbuild.com/v2/hinnant-date_3.0.1-2/get_patch patch_hash = 11b715b792609117a63310eeefc2939cc2ca26ecd4e996108335e504db58a41d wrapdb_version = 3.0.1-2 [provide] tz = tz_dep date = date_dep waybar-0.12.0/subprojects/fmt.wrap000066400000000000000000000010601475603165300171120ustar00rootroot00000000000000[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 [provide] fmt = fmt_dep waybar-0.12.0/subprojects/gtk-layer-shell.wrap000066400000000000000000000004151475603165300213330ustar00rootroot00000000000000[wrap-file] directory = gtk-layer-shell-0.9.0 source_filename = gtk-layer-shell-0.9.0.tar.gz source_hash = 3809e5565d9ed02e44bb73787ff218523e8760fef65830afe60ea7322e22da1c source_url = https://github.com/wmww/gtk-layer-shell/archive/v0.9.0/gtk-layer-shell-0.9.0.tar.gz waybar-0.12.0/subprojects/jsoncpp.wrap000066400000000000000000000004171475603165300200050ustar00rootroot00000000000000[wrap-file] directory = jsoncpp-1.9.5 source_url = https://github.com/open-source-parsers/jsoncpp/archive/1.9.5.tar.gz source_filename = jsoncpp-1.9.5.tar.gz source_hash = f409856e5920c18d0c2fb85276e24ee607d2a09b5e7d5f0a371368903c275da2 [provide] jsoncpp = jsoncpp_dep waybar-0.12.0/subprojects/spdlog.wrap000066400000000000000000000011261475603165300176170ustar00rootroot00000000000000[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 [provide] spdlog = spdlog_dep waybar-0.12.0/test/000077500000000000000000000000001475603165300140505ustar00rootroot00000000000000waybar-0.12.0/test/config.cpp000066400000000000000000000141571475603165300160310ustar00rootroot00000000000000#include "config.hpp" #if __has_include() #include #else #include #endif TEST_CASE("Load simple config", "[config]") { waybar::Config conf; conf.load("test/config/simple.json"); SECTION("validate the config data") { auto& data = conf.getConfig(); REQUIRE(data["layer"].asString() == "top"); REQUIRE(data["height"].asInt() == 30); } SECTION("select configs for configured output") { auto configs = conf.getOutputConfigs("HDMI-0", "Fake HDMI output #0"); REQUIRE(configs.size() == 1); } SECTION("select configs for missing output") { auto configs = conf.getOutputConfigs("HDMI-1", "Fake HDMI output #1"); REQUIRE(configs.empty()); } } TEST_CASE("Load config with multiple bars", "[config]") { waybar::Config conf; conf.load("test/config/multi.json"); SECTION("select multiple configs #1") { auto data = conf.getOutputConfigs("DP-0", "Fake DisplayPort output #0"); REQUIRE(data.size() == 4); REQUIRE(data[0]["layer"].asString() == "bottom"); REQUIRE(data[0]["height"].asInt() == 20); REQUIRE(data[1]["layer"].asString() == "top"); REQUIRE(data[1]["position"].asString() == "bottom"); REQUIRE(data[1]["height"].asInt() == 21); REQUIRE(data[2]["layer"].asString() == "overlay"); REQUIRE(data[2]["position"].asString() == "right"); REQUIRE(data[2]["height"].asInt() == 23); REQUIRE(data[3]["height"].asInt() == 24); } SECTION("select multiple configs #2") { auto data = conf.getOutputConfigs("HDMI-0", "Fake HDMI output #0"); REQUIRE(data.size() == 2); REQUIRE(data[0]["layer"].asString() == "bottom"); REQUIRE(data[0]["height"].asInt() == 20); REQUIRE(data[1]["layer"].asString() == "overlay"); REQUIRE(data[1]["position"].asString() == "right"); REQUIRE(data[1]["height"].asInt() == 23); } SECTION("select single config by output description") { auto data = conf.getOutputConfigs("HDMI-1", "Fake HDMI output #1"); REQUIRE(data.size() == 1); REQUIRE(data[0]["layer"].asString() == "overlay"); REQUIRE(data[0]["position"].asString() == "left"); REQUIRE(data[0]["height"].asInt() == 22); } } TEST_CASE("Load simple config with include", "[config]") { waybar::Config conf; conf.load("test/config/include.json"); SECTION("validate the config data") { auto& data = conf.getConfig(); // config override behavior: preserve first included value REQUIRE(data["layer"].asString() == "top"); REQUIRE(data["height"].asInt() == 30); // config override behavior: preserve value from the top config REQUIRE(data["position"].asString() == "top"); // config override behavior: explicit null is still a value and should be preserved REQUIRE((data.isMember("nullOption") && data["nullOption"].isNull())); } SECTION("select configs for configured output") { auto configs = conf.getOutputConfigs("HDMI-0", "Fake HDMI output #0"); REQUIRE(configs.size() == 1); } SECTION("select configs for missing output") { auto configs = conf.getOutputConfigs("HDMI-1", "Fake HDMI output #1"); REQUIRE(configs.empty()); } } TEST_CASE("Load multiple bar config with include", "[config]") { waybar::Config conf; conf.load("test/config/include-multi.json"); SECTION("bar config with sole include") { auto data = conf.getOutputConfigs("OUT-0", "Fake output #0"); REQUIRE(data.size() == 1); REQUIRE(data[0]["height"].asInt() == 20); } SECTION("bar config with output and include") { auto data = conf.getOutputConfigs("OUT-1", "Fake output #1"); REQUIRE(data.size() == 1); REQUIRE(data[0]["height"].asInt() == 21); } SECTION("bar config with output override") { auto data = conf.getOutputConfigs("OUT-2", "Fake output #2"); REQUIRE(data.size() == 1); REQUIRE(data[0]["height"].asInt() == 22); } SECTION("multiple levels of include") { auto data = conf.getOutputConfigs("OUT-3", "Fake output #3"); REQUIRE(data.size() == 1); REQUIRE(data[0]["height"].asInt() == 23); } auto& data = conf.getConfig(); REQUIRE(data.isArray()); REQUIRE(data.size() == 4); REQUIRE(data[0]["output"].asString() == "OUT-0"); } TEST_CASE("Load Hyprland Workspaces bar config", "[config]") { waybar::Config conf; conf.load("test/config/hyprland-workspaces.json"); auto& data = conf.getConfig(); auto hyprland = data[0]["hyprland/workspaces"]; auto hyprland_window_rewrite = data[0]["hyprland/workspaces"]["window-rewrite"]; auto hyprland_format_icons = data[0]["hyprland/workspaces"]["format-icons"]; auto hyprland_persistent_workspaces = data[0]["hyprland/workspaces"]["persistent-workspaces"]; REQUIRE(data.isArray()); REQUIRE(data.size() == 1); REQUIRE(data[0]["height"].asInt() == 20); REQUIRE(data[0]["layer"].asString() == "bottom"); REQUIRE(data[0]["output"].isArray()); REQUIRE(data[0]["output"][0].asString() == "HDMI-0"); REQUIRE(data[0]["output"][1].asString() == "DP-0"); REQUIRE(hyprland["active-only"].asBool() == true); REQUIRE(hyprland["all-outputs"].asBool() == false); REQUIRE(hyprland["move-to-monitor"].asBool() == true); REQUIRE(hyprland["format"].asString() == "{icon} {windows}"); REQUIRE(hyprland["format-window-separator"].asString() == " "); REQUIRE(hyprland["on-scroll-down"].asString() == "hyprctl dispatch workspace e-1"); REQUIRE(hyprland["on-scroll-up"].asString() == "hyprctl dispatch workspace e+1"); REQUIRE(hyprland["show-special"].asBool() == true); REQUIRE(hyprland["window-rewrite-default"].asString() == ""); REQUIRE(hyprland["window-rewrite-separator"].asString() == " "); REQUIRE(hyprland_format_icons["1"].asString() == "󰎤"); REQUIRE(hyprland_format_icons["2"].asString() == "󰎧"); REQUIRE(hyprland_format_icons["3"].asString() == "󰎪"); REQUIRE(hyprland_format_icons["default"].asString() == ""); REQUIRE(hyprland_format_icons["empty"].asString() == "󱓼"); REQUIRE(hyprland_format_icons["urgent"].asString() == "󱨇"); REQUIRE(hyprland_persistent_workspaces["1"].asString() == "HDMI-0"); REQUIRE(hyprland_window_rewrite["title"].asString() == ""); REQUIRE(hyprland["sort-by"].asString() == "number"); } waybar-0.12.0/test/config/000077500000000000000000000000001475603165300153155ustar00rootroot00000000000000waybar-0.12.0/test/config/hyprland-workspaces.json000066400000000000000000000015171475603165300222140ustar00rootroot00000000000000[ { "height": 20, "layer": "bottom", "output": [ "HDMI-0", "DP-0" ], "hyprland/workspaces": { "active-only": true, "all-outputs": false, "show-special": true, "move-to-monitor": true, "format": "{icon} {windows}", "format-window-separator": " ", "format-icons": { "1": "󰎤", "2": "󰎧", "3": "󰎪", "default": "", "empty": "󱓼", "urgent": "󱨇" }, "persistent-workspaces": { "1": "HDMI-0" }, "on-scroll-down": "hyprctl dispatch workspace e-1", "on-scroll-up": "hyprctl dispatch workspace e+1", "window-rewrite": { "title": "" }, "window-rewrite-default": "", "window-rewrite-separator": " ", "sort-by": "number" } } ] waybar-0.12.0/test/config/include-1.json000066400000000000000000000001711475603165300177700ustar00rootroot00000000000000{ "layer": "top", "position": "bottom", "height": 30, "output": ["HDMI-0", "DP-0"], "nullOption": "not null" } waybar-0.12.0/test/config/include-2.json000066400000000000000000000000301475603165300177630ustar00rootroot00000000000000{ "layer": "bottom" } waybar-0.12.0/test/config/include-multi-0.json000066400000000000000000000000501475603165300211130ustar00rootroot00000000000000{ "output": "OUT-0", "height": 20 } waybar-0.12.0/test/config/include-multi-1.json000066400000000000000000000000231475603165300211140ustar00rootroot00000000000000{ "height": 21 } waybar-0.12.0/test/config/include-multi-2.json000066400000000000000000000000501475603165300211150ustar00rootroot00000000000000{ "output": "OUT-1", "height": 22 } waybar-0.12.0/test/config/include-multi-3-0.json000066400000000000000000000000231475603165300212530ustar00rootroot00000000000000{ "height": 23 } waybar-0.12.0/test/config/include-multi-3.json000066400000000000000000000001131475603165300211160ustar00rootroot00000000000000{ "output": "OUT-3", "include": "test/config/include-multi-3-0.json" } waybar-0.12.0/test/config/include-multi.json000066400000000000000000000004351475603165300207650ustar00rootroot00000000000000[ { "include": "test/config/include-multi-0.json" }, { "output": "OUT-1", "include": "test/config/include-multi-1.json" }, { "output": "OUT-2", "include": "test/config/include-multi-2.json" }, { "include": "test/config/include-multi-3.json" } ] waybar-0.12.0/test/config/include.json000066400000000000000000000001711475603165300176320ustar00rootroot00000000000000{ "include": ["test/config/include-1.json", "test/config/include-2.json"], "position": "top", "nullOption": null } waybar-0.12.0/test/config/multi.json000066400000000000000000000007161475603165300173460ustar00rootroot00000000000000[ { "layer": "bottom", "height": 20, "output": ["HDMI-0", "DP-0"] }, { "position": "bottom", "layer": "top", "height": 21, "output": ["DP-0"] }, { "position": "left", "layer": "overlay", "height": 22, "output": "Fake HDMI output #1" }, { "position": "right", "layer": "overlay", "height": 23, "output": "!HDMI-1" }, { "height": 24, "output": ["!HDMI-0", "!HDMI-1", "*"] } ] waybar-0.12.0/test/config/simple.json000066400000000000000000000001051475603165300174750ustar00rootroot00000000000000{ "layer": "top", "height": 30, "output": ["HDMI-0", "DP-0"] } waybar-0.12.0/test/hyprland/000077500000000000000000000000001475603165300156715ustar00rootroot00000000000000waybar-0.12.0/test/hyprland/backend.cpp000066400000000000000000000035271475603165300177730ustar00rootroot00000000000000#if __has_include() #include #else #include #endif #include "fixtures/IPCTestFixture.hpp" namespace fs = std::filesystem; namespace hyprland = waybar::modules::hyprland; TEST_CASE_METHOD(IPCTestFixture, "XDGRuntimeDirExists", "[getSocketFolder]") { // Test case: XDG_RUNTIME_DIR exists and contains "hypr" directory // Arrange tempDir = fs::temp_directory_path() / "hypr_test/run/user/1000"; fs::path expectedPath = tempDir / "hypr" / instanceSig; fs::create_directories(tempDir / "hypr" / instanceSig); setenv("XDG_RUNTIME_DIR", tempDir.c_str(), 1); // Act fs::path actualPath = getSocketFolder(instanceSig); // Assert expected result REQUIRE(actualPath == expectedPath); } TEST_CASE_METHOD(IPCTestFixture, "XDGRuntimeDirDoesNotExist", "[getSocketFolder]") { // Test case: XDG_RUNTIME_DIR does not exist // Arrange unsetenv("XDG_RUNTIME_DIR"); fs::path expectedPath = fs::path("/tmp") / "hypr" / instanceSig; // Act fs::path actualPath = getSocketFolder(instanceSig); // Assert expected result REQUIRE(actualPath == expectedPath); } TEST_CASE_METHOD(IPCTestFixture, "XDGRuntimeDirExistsNoHyprDir", "[getSocketFolder]") { // Test case: XDG_RUNTIME_DIR exists but does not contain "hypr" directory // Arrange fs::path tempDir = fs::temp_directory_path() / "hypr_test/run/user/1000"; fs::create_directories(tempDir); setenv("XDG_RUNTIME_DIR", tempDir.c_str(), 1); fs::path expectedPath = fs::path("/tmp") / "hypr" / instanceSig; // Act fs::path actualPath = getSocketFolder(instanceSig); // Assert expected result REQUIRE(actualPath == expectedPath); } TEST_CASE_METHOD(IPCTestFixture, "getSocket1Reply throws on no socket", "[getSocket1Reply]") { std::string request = "test_request"; CHECK_THROWS(getSocket1Reply(request)); } waybar-0.12.0/test/hyprland/fixtures/000077500000000000000000000000001475603165300175425ustar00rootroot00000000000000waybar-0.12.0/test/hyprland/fixtures/IPCTestFixture.hpp000066400000000000000000000012141475603165300230730ustar00rootroot00000000000000#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"; }; waybar-0.12.0/test/hyprland/meson.build000066400000000000000000000006701475603165300200360ustar00rootroot00000000000000test_inc = include_directories('../../include') test_dep = [ catch2, fmt, gtkmm, jsoncpp, spdlog, ] test_src = files( '../main.cpp', 'backend.cpp', '../../src/modules/hyprland/backend.cpp' ) hyprland_test = executable( 'hyprland_test', test_src, dependencies: test_dep, include_directories: test_inc, ) test( 'hyprland', hyprland_test, workdir: meson.project_source_root(), ) waybar-0.12.0/test/main.cpp000066400000000000000000000020511475603165300154760ustar00rootroot00000000000000#define CATCH_CONFIG_RUNNER #include #include #include #if __has_include() #include #include #include #else #include #include #endif #include int main(int argc, char* argv[]) { Catch::Session session; Glib::init(); session.applyCommandLine(argc, argv); const auto logger = spdlog::default_logger(); #if CATCH_VERSION_MAJOR >= 3 for (const auto& spec : session.config().getReporterSpecs()) { const auto& reporter_name = spec.name(); #else { const auto& reporter_name = session.config().getReporterName(); #endif if (reporter_name == "tap") { spdlog::set_pattern("# [%l] %v"); } else if (reporter_name == "compact") { logger->sinks().clear(); } else { logger->sinks().assign({std::make_shared()}); } } return session.run(); } waybar-0.12.0/test/meson.build000066400000000000000000000006711475603165300162160ustar00rootroot00000000000000test_inc = include_directories('../include') test_dep = [ catch2, fmt, gtkmm, jsoncpp, spdlog, ] test_src = files( 'main.cpp', 'config.cpp', '../src/config.cpp', ) waybar_test = executable( 'waybar_test', test_src, dependencies: test_dep, include_directories: test_inc, ) test( 'waybar', waybar_test, workdir: meson.project_source_root(), ) subdir('utils') subdir('hyprland') waybar-0.12.0/test/utils/000077500000000000000000000000001475603165300152105ustar00rootroot00000000000000waybar-0.12.0/test/utils/JsonParser.cpp000066400000000000000000000027001475603165300200010ustar00rootroot00000000000000#include "util/json.hpp" #if __has_include() #include #else #include #endif TEST_CASE("Simple json", "[json]") { SECTION("Parse simple json") { std::string stringToTest = R"({"number": 5, "string": "test"})"; waybar::util::JsonParser parser; Json::Value jsonValue = parser.parse(stringToTest); REQUIRE(jsonValue["number"].asInt() == 5); REQUIRE(jsonValue["string"].asString() == "test"); } } TEST_CASE("Json with unicode", "[json]") { SECTION("Parse json with unicode") { std::string stringToTest = R"({"test": "\xab"})"; waybar::util::JsonParser parser; Json::Value jsonValue = parser.parse(stringToTest); // compare with "\u00ab" because "\xab" is replaced with "\u00ab" in the parser REQUIRE(jsonValue["test"].asString() == "\u00ab"); } } TEST_CASE("Json with emoji", "[json]") { SECTION("Parse json with emoji") { std::string stringToTest = R"({"test": "😊"})"; waybar::util::JsonParser parser; Json::Value jsonValue = parser.parse(stringToTest); REQUIRE(jsonValue["test"].asString() == "😊"); } } TEST_CASE("Json with chinese characters", "[json]") { SECTION("Parse json with chinese characters") { std::string stringToTest = R"({"test": "你好"})"; waybar::util::JsonParser parser; Json::Value jsonValue = parser.parse(stringToTest); REQUIRE(jsonValue["test"].asString() == "你好"); } }waybar-0.12.0/test/utils/SafeSignal.cpp000066400000000000000000000072541475603165300177400ustar00rootroot00000000000000#include "util/SafeSignal.hpp" #include #if __has_include() #include #else #include #endif #include #include #include "fixtures/GlibTestsFixture.hpp" using namespace waybar; template using remove_cvref_t = typename std::remove_cv::type>::type; /** * Basic sanity test for SafeSignal: * check that type deduction works, events are delivered and the order is right * Running this with -fsanitize=thread should not fail */ TEST_CASE_METHOD(GlibTestsFixture, "SafeSignal basic functionality", "[signal][thread][util]") { const int NUM_EVENTS = 100; int count = 0; int last_value = 0; SafeSignal test_signal; const auto main_tid = std::this_thread::get_id(); std::thread producer; // timeout the test in 500ms setTimeout(500); test_signal.connect([&](auto val, auto str) { static_assert(std::is_same::value); static_assert(std::is_same::value); // check that we're in the same thread as the main loop REQUIRE(std::this_thread::get_id() == main_tid); // check event order REQUIRE(val == last_value + 1); last_value = val; if (++count >= NUM_EVENTS) { this->quit(); }; }); run([&]() { // check that events from the same thread are delivered and processed synchronously test_signal.emit(1, "test"); REQUIRE(count == 1); // start another thread and generate events producer = std::thread([&]() { for (auto i = 2; i <= NUM_EVENTS; ++i) { test_signal.emit(i, "test"); } }); }); producer.join(); REQUIRE(count == NUM_EVENTS); } template struct TestObject { T value; unsigned copied = 0; unsigned moved = 0; TestObject(const T& v) : value(v) {}; ~TestObject() = default; TestObject(const TestObject& other) : value(other.value), copied(other.copied + 1), moved(other.moved) {} TestObject(TestObject&& other) noexcept : value(std::move(other.value)), copied(std::exchange(other.copied, 0)), moved(std::exchange(other.moved, 0) + 1) {} TestObject& operator=(const TestObject& other) { value = other.value; copied = other.copied + 1; moved = other.moved; return *this; } TestObject& operator=(TestObject&& other) noexcept { value = std::move(other.value); copied = std::exchange(other.copied, 0); moved = std::exchange(other.moved, 0) + 1; return *this; } bool operator==(T other) const { return value == other; } operator T() const { return value; } }; /* * Check the number of copies/moves performed on the object passed through SafeSignal */ TEST_CASE_METHOD(GlibTestsFixture, "SafeSignal copy/move counter", "[signal][thread][util]") { const int NUM_EVENTS = 3; int count = 0; SafeSignal> test_signal; std::thread producer; // timeout the test in 500ms setTimeout(500); test_signal.connect([&](auto& val) { static_assert(std::is_same, remove_cvref_t>::value); /* explicit move in the producer thread */ REQUIRE(val.moved <= 1); /* copy within the SafeSignal queuing code */ REQUIRE(val.copied <= 1); if (++count >= NUM_EVENTS) { this->quit(); }; }); run([&]() { test_signal.emit(1); REQUIRE(count == 1); producer = std::thread([&]() { for (auto i = 2; i <= NUM_EVENTS; ++i) { TestObject t{i}; // check that signal.emit accepts moved objects test_signal.emit(std::move(t)); } }); }); producer.join(); REQUIRE(count == NUM_EVENTS); } waybar-0.12.0/test/utils/css_reload_helper.cpp000066400000000000000000000063551475603165300214020ustar00rootroot00000000000000#include "util/css_reload_helper.hpp" #include #if __has_include() #include #else #include #endif class CssReloadHelperTest : public waybar::CssReloadHelper { public: CssReloadHelperTest() : CssReloadHelper("/tmp/waybar_test.css", [this]() { callback(); }) {} void callback() { m_callbackCounter++; } protected: std::string getFileContents(const std::string& filename) override { return m_fileContents[filename]; } std::string findPath(const std::string& filename) override { return filename; } void setFileContents(const std::string& filename, const std::string& contents) { m_fileContents[filename] = contents; } int getCallbackCounter() const { return m_callbackCounter; } private: int m_callbackCounter{}; std::map m_fileContents; }; TEST_CASE_METHOD(CssReloadHelperTest, "parse_imports", "[util][css_reload_helper]") { SECTION("no imports") { setFileContents("/tmp/waybar_test.css", "body { color: red; }"); auto files = parseImports("/tmp/waybar_test.css"); REQUIRE(files.size() == 1); CHECK(files[0] == "/tmp/waybar_test.css"); } SECTION("single import") { setFileContents("/tmp/waybar_test.css", "@import 'test.css';"); setFileContents("test.css", "body { color: red; }"); auto files = parseImports("/tmp/waybar_test.css"); std::sort(files.begin(), files.end()); REQUIRE(files.size() == 2); CHECK(files[0] == "/tmp/waybar_test.css"); CHECK(files[1] == "test.css"); } SECTION("multiple imports") { setFileContents("/tmp/waybar_test.css", "@import 'test.css'; @import 'test2.css';"); setFileContents("test.css", "body { color: red; }"); setFileContents("test2.css", "body { color: blue; }"); auto files = parseImports("/tmp/waybar_test.css"); std::sort(files.begin(), files.end()); REQUIRE(files.size() == 3); CHECK(files[0] == "/tmp/waybar_test.css"); CHECK(files[1] == "test.css"); CHECK(files[2] == "test2.css"); } SECTION("nested imports") { setFileContents("/tmp/waybar_test.css", "@import 'test.css';"); setFileContents("test.css", "@import 'test2.css';"); setFileContents("test2.css", "body { color: red; }"); auto files = parseImports("/tmp/waybar_test.css"); std::sort(files.begin(), files.end()); REQUIRE(files.size() == 3); CHECK(files[0] == "/tmp/waybar_test.css"); CHECK(files[1] == "test.css"); CHECK(files[2] == "test2.css"); } SECTION("circular imports") { setFileContents("/tmp/waybar_test.css", "@import 'test.css';"); setFileContents("test.css", "@import 'test2.css';"); setFileContents("test2.css", "@import 'test.css';"); auto files = parseImports("/tmp/waybar_test.css"); std::sort(files.begin(), files.end()); REQUIRE(files.size() == 3); CHECK(files[0] == "/tmp/waybar_test.css"); CHECK(files[1] == "test.css"); CHECK(files[2] == "test2.css"); } SECTION("empty") { setFileContents("/tmp/waybar_test.css", ""); auto files = parseImports("/tmp/waybar_test.css"); REQUIRE(files.size() == 1); CHECK(files[0] == "/tmp/waybar_test.css"); } SECTION("empty name") { auto files = parseImports(""); REQUIRE(files.empty()); } } waybar-0.12.0/test/utils/date.cpp000066400000000000000000000146701475603165300166410ustar00rootroot00000000000000#include "util/date.hpp" #include #include #include #include #if __has_include() #include #include #else #include #endif #ifndef SKIP #define SKIP(...) \ WARN(__VA_ARGS__); \ return #endif 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. */ const zoned_time TEST_TIME{ "UTC", local_days{Monday[1] / January / 2022} + 13h + 4min + 5s}; /* * Check if the date formatted with LC_TIME=en_US is within expectations. * * The check expects Glibc output style and will fail with FreeBSD (different implementation) * or musl (no implementation). */ static const bool LC_TIME_is_sane = []() { try { std::stringstream ss; ss.imbue(std::locale("en_US.UTF-8")); time_t t = 1641211200; std::tm tm = *std::gmtime(&t); ss << std::put_time(&tm, "%x %X"); return ss.str() == "01/03/2022 12:00:00 PM"; } catch (std::exception &) { return false; } }(); TEST_CASE("Format UTC time", "[clock][util]") { const auto loc = std::locale("C"); const auto tm = TEST_TIME; #if not HAVE_CHRONO_TIMEZONES CHECK(fmt_lib::format(loc, "{}", tm).empty()); // no format specified #endif CHECK(fmt_lib::format(loc, "{:%c %Z}", tm) == "Mon Jan 3 13:04:05 2022 UTC"); CHECK(fmt_lib::format(loc, "{:%Y%m%d%H%M%S}", tm) == "20220103130405"); if (!LC_TIME_is_sane) { SKIP("Locale support check failed, skip tests"); } /* Test a few locales that are most likely to be present */ SECTION("US locale") { try { const auto loc = std::locale("en_US.UTF-8"); #if not HAVE_CHRONO_TIMEZONES CHECK(fmt_lib::format(loc, "{}", tm).empty()); // no format specified CHECK_THAT(fmt_lib::format(loc, "{:%c}", tm), // HowardHinnant/date#704 Catch::Matchers::StartsWith("Mon 03 Jan 2022 01:04:05 PM")); CHECK(fmt_lib::format(loc, "{:%x %X}", tm) == "01/03/2022 01:04:05 PM"); #else 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 &) { WARN("Locale en_US not found, skip tests"); } } SECTION("GB locale") { try { const auto loc = std::locale("en_GB.UTF-8"); #if not HAVE_CHRONO_TIMEZONES CHECK(fmt_lib::format(loc, "{}", tm).empty()); // no format specified CHECK_THAT(fmt_lib::format(loc, "{:%c}", tm), // HowardHinnant/date#704 Catch::Matchers::StartsWith("Mon 03 Jan 2022 13:04:05")); CHECK(fmt_lib::format(loc, "{:%x %X}", tm) == "03/01/22 13:04:05"); #else 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 &) { WARN("Locale en_GB not found, skip tests"); } } SECTION("Global locale") { try { const auto loc = std::locale::global(std::locale("en_US.UTF-8")); #if not HAVE_CHRONO_TIMEZONES CHECK(fmt_lib::format("{}", tm).empty()); // no format specified CHECK_THAT(fmt_lib::format("{:%c}", tm), // HowardHinnant/date#704 Catch::Matchers::StartsWith("Mon 03 Jan 2022 01:04:05 PM")); CHECK(fmt_lib::format("{:%x %X}", tm) == "01/03/2022 01:04:05 PM"); #else CHECK(fmt_lib::format("{:%F %r}", tm) == "2022-01-03 01:04:05 PM"); #endif CHECK(fmt_lib::format("{:%Y%m%d%H%M%S}", tm) == "20220103130405"); std::locale::global(loc); } catch (const std::runtime_error &) { WARN("Locale en_US not found, skip tests"); } } } TEST_CASE("Format zoned time", "[clock][util]") { const auto loc = std::locale("C"); const auto tm = zoned_time{"America/New_York", TEST_TIME}; #if not HAVE_CHRONO_TIMEZONES CHECK(fmt_lib::format(loc, "{}", tm).empty()); // no format specified #endif CHECK(fmt_lib::format(loc, "{:%c %Z}", tm) == "Mon Jan 3 08:04:05 2022 EST"); CHECK(fmt_lib::format(loc, "{:%Y%m%d%H%M%S}", tm) == "20220103080405"); if (!LC_TIME_is_sane) { SKIP("Locale support check failed, skip tests"); } /* Test a few locales that are most likely to be present */ SECTION("US locale") { try { const auto loc = std::locale("en_US.UTF-8"); #if not HAVE_CHRONO_TIMEZONES CHECK(fmt_lib::format(loc, "{}", tm).empty()); // no format specified CHECK_THAT(fmt_lib::format(loc, "{:%c}", tm), // HowardHinnant/date#704 Catch::Matchers::StartsWith("Mon 03 Jan 2022 08:04:05 AM")); CHECK(fmt_lib::format(loc, "{:%x %X}", tm) == "01/03/2022 08:04:05 AM"); #else 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 &) { WARN("Locale en_US not found, skip tests"); } } SECTION("GB locale") { try { const auto loc = std::locale("en_GB.UTF-8"); #if not HAVE_CHRONO_TIMEZONES CHECK(fmt_lib::format(loc, "{}", tm).empty()); // no format specified CHECK_THAT(fmt_lib::format(loc, "{:%c}", tm), // HowardHinnant/date#704 Catch::Matchers::StartsWith("Mon 03 Jan 2022 08:04:05")); CHECK(fmt_lib::format(loc, "{:%x %X}", tm) == "03/01/22 08:04:05"); #else 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 &) { WARN("Locale en_GB not found, skip tests"); } } SECTION("Global locale") { try { const auto loc = std::locale::global(std::locale("en_US.UTF-8")); #if not HAVE_CHRONO_TIMEZONES CHECK(fmt_lib::format("{}", tm).empty()); // no format specified CHECK_THAT(fmt_lib::format("{:%c}", tm), // HowardHinnant/date#704 Catch::Matchers::StartsWith("Mon 03 Jan 2022 08:04:05 AM")); CHECK(fmt_lib::format("{:%x %X}", tm) == "01/03/2022 08:04:05 AM"); #else CHECK(fmt_lib::format("{:%F %r}", tm) == "2022-01-03 08:04:05 AM"); #endif CHECK(fmt_lib::format("{:%Y%m%d%H%M%S}", tm) == "20220103080405"); std::locale::global(loc); } catch (const std::runtime_error &) { WARN("Locale en_US not found, skip tests"); } } } waybar-0.12.0/test/utils/fixtures/000077500000000000000000000000001475603165300170615ustar00rootroot00000000000000waybar-0.12.0/test/utils/fixtures/GlibTestsFixture.hpp000066400000000000000000000011721475603165300230420ustar00rootroot00000000000000#pragma once #include /** * Minimal Glib application to be used for tests that require Glib main loop */ class GlibTestsFixture : public sigc::trackable { public: GlibTestsFixture() : main_loop_{Glib::MainLoop::create()} {} void setTimeout(int timeout) { Glib::signal_timeout().connect_once([]() { throw std::runtime_error("Test timed out"); }, timeout); } void run(std::function fn) { Glib::signal_idle().connect_once(fn); main_loop_->run(); } void quit() { main_loop_->quit(); } protected: Glib::RefPtr main_loop_; }; waybar-0.12.0/test/utils/meson.build000066400000000000000000000011371475603165300173540ustar00rootroot00000000000000test_inc = include_directories('../../include') test_dep = [ catch2, fmt, gtkmm, jsoncpp, spdlog, ] test_src = files( '../main.cpp', '../config.cpp', '../../src/config.cpp', 'JsonParser.cpp', 'SafeSignal.cpp', 'css_reload_helper.cpp', '../../src/util/css_reload_helper.cpp', ) if tz_dep.found() test_dep += tz_dep test_src += files('date.cpp') endif utils_test = executable( 'utils_test', test_src, dependencies: test_dep, include_directories: test_inc, ) test( 'utils', utils_test, workdir: meson.project_source_root(), )