Merge branch 'master' into issue-1681

This commit is contained in:
Alexis Rouillard
2025-06-22 08:41:15 +01:00
committed by GitHub
276 changed files with 15334 additions and 5163 deletions

29
.clang-tidy Normal file
View File

@ -0,0 +1,29 @@
Checks: >
-*,
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 }

65
.github/labeler.yml vendored Normal file
View File

@ -0,0 +1,65 @@
bug:
- "(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)"

22
.github/workflows/clang-format.yml vendored Normal file
View File

@ -0,0 +1,22 @@
name: clang-format
on: [push, pull_request]
concurrency:
group: ${{ github.workflow }}-format-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
# TODO: bump to clang 19 release
# - uses: DoozyX/clang-format-lint-action@v0.18.2
- uses: DoozyX/clang-format-lint-action@558090054b3f39e3d6af24f0cd73b319535da809
name: clang-format
with:
source: "."
extensions: "hpp,h,cpp,c"
style: "file:.clang-format"
clangFormatVersion: 19

39
.github/workflows/clang-tidy.yml.bak vendored Normal file
View File

@ -0,0 +1,39 @@
name: clang-tidy
on: [push, pull_request]
concurrency:
group: ${{ github.workflow }}-tidy-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
lint:
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

34
.github/workflows/docker.yml vendored Normal file
View File

@ -0,0 +1,34 @@
name: Build and Push Docker Image
on:
workflow_dispatch:
schedule:
# run monthly
- cron: '0 0 1 * *'
jobs:
build-and-push:
runs-on: ubuntu-latest
if: github.event_name != 'schedule' || github.repository == 'Alexays/Waybar'
strategy:
fail-fast: false # don't fail the other jobs if one of the images fails to build
matrix:
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 }}

View File

@ -1,29 +1,35 @@
name: freebsd name: freebsd
on: [ push, pull_request ] on: [push, pull_request]
concurrency:
group: ${{ github.workflow }}-freebsd-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs: jobs:
clang: build:
# Run actions in a FreeBSD VM on the macos-12 runner # Run actions in a FreeBSD VM on the ubuntu runner
# https://github.com/actions/runner/issues/385 - for FreeBSD runner support # https://github.com/actions/runner/issues/385 - for FreeBSD runner support
# https://github.com/actions/virtual-environments/issues/4060 - for lack of VirtualBox on MacOS 11 runners runs-on: ubuntu-latest
runs-on: macos-12
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
- name: Test in FreeBSD VM - name: Test in FreeBSD VM
uses: vmactions/freebsd-vm@v0 uses: cross-platform-actions/action@v0.25.0
with: timeout-minutes: 180
mem: 2048 env:
usesh: true CPPFLAGS: '-isystem/usr/local/include'
prepare: | LDFLAGS: '-L/usr/local/lib'
export CPPFLAGS=-isystem/usr/local/include LDFLAGS=-L/usr/local/lib # sndio with:
sed -i '' 's/quarterly/latest/' /etc/pkg/FreeBSD.conf operating_system: freebsd
pkg install -y git # subprojects/date version: "14.3"
pkg install -y catch evdev-proto gtk-layer-shell gtkmm30 jsoncpp \ environment_variables: CPPFLAGS LDFLAGS
libdbusmenu libevdev libfmt libmpdclient libudev-devd meson \ sync_files: runner-to-vm
pkgconf pulseaudio scdoc sndio spdlog wayland-protocols upower \ run: |
libinotify sudo pkg install -y git # subprojects/date
run: | sudo pkg install -y catch evdev-proto gtk-layer-shell gtkmm30 jsoncpp \
meson build -Dman-pages=enabled libdbusmenu libevdev libfmt libmpdclient libudev-devd meson \
ninja -C build pkgconf pipewire pulseaudio scdoc sndio spdlog wayland-protocols upower \
meson test -C build --no-rebuild --print-errorlogs --suite waybar libinotify
meson setup build -Dman-pages=enabled
ninja -C build
meson test -C build --no-rebuild --print-errorlogs --suite waybar

19
.github/workflows/labeler.yml vendored Normal file
View File

@ -0,0 +1,19 @@
name: "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 }}

View File

@ -1,14 +0,0 @@
name: Linter
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: DoozyX/clang-format-lint-action@v0.13
with:
source: '.'
extensions: 'h,cpp,c'
clangFormatVersion: 12

View File

@ -2,9 +2,14 @@ name: linux
on: [push, pull_request] on: [push, pull_request]
concurrency:
group: ${{ github.workflow }}-linux-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs: jobs:
build: build:
strategy: strategy:
fail-fast: false
matrix: matrix:
distro: distro:
- alpine - alpine
@ -13,10 +18,7 @@ jobs:
- fedora - fedora
- opensuse - opensuse
- gentoo - gentoo
cpp_std: [c++17] cpp_std: [c++20]
include:
- distro: fedora
cpp_std: c++20
runs-on: ubuntu-latest runs-on: ubuntu-latest
container: container:
@ -25,7 +27,7 @@ jobs:
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
- name: configure - name: configure
run: meson -Dman-pages=enabled -Dcpp_std=${{matrix.cpp_std}} build run: meson setup -Dman-pages=enabled -Dcpp_std=${{matrix.cpp_std}} build
- name: build - name: build
run: ninja -C build run: ninja -C build
- name: test - name: test

17
.github/workflows/nix-tests.yml vendored Normal file
View File

@ -0,0 +1,17 @@
name: "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

View File

@ -0,0 +1,22 @@
name: 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

6
.gitignore vendored
View File

@ -44,3 +44,9 @@ packagecache
*.out *.out
*.app *.app
/.direnv/ /.direnv/
# Nix
result
result-*
.ccls-cache

View File

@ -3,5 +3,5 @@
FROM archlinux:base-devel FROM archlinux:base-devel
RUN pacman -Syu --noconfirm && \ RUN pacman -Syu --noconfirm && \
pacman -S --noconfirm git meson base-devel libinput wayland wayland-protocols pixman libxkbcommon mesa gtkmm3 jsoncpp pugixml scdoc libpulse libdbusmenu-gtk3 libmpdclient gobject-introspection libxkbcommon playerctl && \ 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 sed -Ei 's/#(en_(US|GB)\.UTF)/\1/' /etc/locale.gen && locale-gen

View File

@ -1,7 +1,49 @@
# vim: ft=Dockerfile # vim: ft=Dockerfile
FROM debian:sid FROM debian:sid-slim
RUN apt-get update && \ RUN apt update && \
apt-get install -y build-essential meson ninja-build git pkg-config libinput10 libpugixml-dev libinput-dev wayland-protocols libwayland-client0 libwayland-cursor0 libwayland-dev libegl1-mesa-dev libgles2-mesa-dev libgbm-dev libxkbcommon-dev libudev-dev libpixman-1-dev libgtkmm-3.0-dev libjsoncpp-dev scdoc libdbusmenu-gtk3-dev libnl-3-dev libnl-genl-3-dev libpulse-dev libmpdclient-dev gobject-introspection libgirepository1.0-dev libxkbcommon-dev libxkbregistry-dev libxkbregistry0 libplayerctl-dev && \ apt install --no-install-recommends --no-install-suggests -y \
apt-get clean 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

View File

@ -29,6 +29,6 @@ RUN dnf install -y @c-development \
'pkgconfig(wayland-client)' \ 'pkgconfig(wayland-client)' \
'pkgconfig(wayland-cursor)' \ 'pkgconfig(wayland-cursor)' \
'pkgconfig(wayland-protocols)' \ 'pkgconfig(wayland-protocols)' \
'pkgconfig(wireplumber-0.4)' \ 'pkgconfig(wireplumber-0.5)' \
'pkgconfig(xkbregistry)' && \ 'pkgconfig(xkbregistry)' && \
dnf clean all -y dnf clean all -y

View File

@ -6,6 +6,6 @@ RUN export FEATURES="-ipc-sandbox -network-sandbox -pid-sandbox -sandbox -usersa
emerge --sync && \ emerge --sync && \
eselect news read --quiet new 1>/dev/null 2>&1 && \ eselect news read --quiet new 1>/dev/null 2>&1 && \
emerge --verbose --update --deep --with-bdeps=y --backtrack=30 --newuse @world && \ emerge --verbose --update --deep --with-bdeps=y --backtrack=30 --newuse @world && \
USE="wayland gtk3 gtk -doc X pulseaudio minimal" emerge dev-vcs/git dev-libs/wayland dev-libs/wayland-protocols =dev-cpp/gtkmm-3.24.6 x11-libs/libxkbcommon \ USE="wayland gtk3 gtk -doc X pulseaudio minimal" emerge dev-vcs/git dev-libs/wayland dev-libs/wayland-protocols dev-cpp/gtkmm:3.0 x11-libs/libxkbcommon \
x11-libs/gtk+:3 dev-libs/libdbusmenu dev-libs/libnl sys-power/upower media-libs/libpulse dev-libs/libevdev media-libs/libmpdclient \ 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 media-sound/sndio gui-libs/gtk-layer-shell app-text/scdoc media-sound/playerctl dev-libs/iniparser sci-libs/fftw

View File

@ -6,4 +6,4 @@ RUN zypper -n up && \
zypper addrepo https://download.opensuse.org/repositories/X11:Wayland/openSUSE_Tumbleweed/X11:Wayland.repo | echo 'a' && \ zypper addrepo https://download.opensuse.org/repositories/X11:Wayland/openSUSE_Tumbleweed/X11:Wayland.repo | echo 'a' && \
zypper -n refresh && \ zypper -n refresh && \
zypper -n install -t pattern devel_C_C++ && \ 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 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

View File

@ -1,6 +1,6 @@
MIT License MIT License
Copyright (c) 2018 Alex Copyright (c) 2025 Alex
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@ -3,11 +3,11 @@
default: build default: build
build: build:
meson build meson setup build
ninja -C build ninja -C build
build-debug: build-debug:
meson build --buildtype=debug meson setup build --buildtype=debug
ninja -C build ninja -C build
install: build install: build

View File

@ -1,22 +1,24 @@
# 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)<br>![Waybar](https://raw.githubusercontent.com/alexays/waybar/master/preview-2.png) # 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)<br>![Waybar](https://raw.githubusercontent.com/alexays/waybar/master/preview-2.png)
> Highly customizable Wayland bar for Sway and Wlroots based compositors.<br> > Highly customizable Wayland bar for Sway and Wlroots based compositors.<br>
> Available in Arch [community](https://www.archlinux.org/packages/extra/x86_64/waybar/) or > Available in [all major distributions](https://github.com/Alexays/Waybar/wiki/Installation)<br>
[AUR](https://aur.archlinux.org/packages/waybar-git/), [Gentoo](https://packages.gentoo.org/packages/gui-apps/waybar), [openSUSE](https://build.opensuse.org/package/show/X11:Wayland/waybar), and [Alpine Linux](https://pkgs.alpinelinux.org/packages?name=waybar).<br>
> *Waybar [examples](https://github.com/Alexays/Waybar/wiki/Examples)* > *Waybar [examples](https://github.com/Alexays/Waybar/wiki/Examples)*
#### Current features #### Current features
- Sway (Workspaces, Binding mode, Focused window name) - Sway (Workspaces, Binding mode, Focused window name)
- River (Mapping mode, Tags, Focused window name) - River (Mapping mode, Tags, Focused window name)
- Hyprland (Focused window name) - Hyprland (Window Icons, Workspaces, Focused window name)
- DWL (Tags) [requires dwl ipc patch](https://github.com/djpohly/dwl/wiki/ipc) - 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) - Tray [#21](https://github.com/Alexays/Waybar/issues/21)
- Local time - Local time
- Battery - Battery
- UPower - UPower
- Power profiles daemon
- Network - Network
- Bluetooth - Bluetooth
- Pulseaudio - Pulseaudio
- Privacy Info
- Wireplumber - Wireplumber
- Disk - Disk
- Memory - Memory
@ -36,7 +38,7 @@
Waybar is available from a number of Linux distributions: Waybar is available from a number of Linux distributions:
[![Packaging status](https://repology.org/badge/vertical-allrepos/waybar.svg)](https://repology.org/project/waybar/versions) [![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 An Ubuntu PPA with more recent versions is available
[here](https://launchpad.net/~nschloe/+archive/ubuntu/waybar). [here](https://launchpad.net/~nschloe/+archive/ubuntu/waybar).
@ -47,7 +49,7 @@ An Ubuntu PPA with more recent versions is available
```bash ```bash
$ git clone https://github.com/Alexays/Waybar $ git clone https://github.com/Alexays/Waybar
$ cd Waybar $ cd Waybar
$ meson build $ meson setup build
$ ninja -C build $ ninja -C build
$ ./build/waybar $ ./build/waybar
# If you want to install it # If you want to install it

View File

@ -1,10 +1,9 @@
(import (import (
( let
let lock = builtins.fromJSON (builtins.readFile ./flake.lock); in lock = builtins.fromJSON (builtins.readFile ./flake.lock);
fetchTarball { in
url = "https://github.com/edolstra/flake-compat/archive/${lock.nodes.flake-compat.locked.rev}.tar.gz"; fetchTarball {
sha256 = lock.nodes.flake-compat.locked.narHash; url = "https://github.com/edolstra/flake-compat/archive/${lock.nodes.flake-compat.locked.rev}.tar.gz";
} sha256 = lock.nodes.flake-compat.locked.narHash;
) }
{ src = ./.; } ) { src = ./.; }).defaultNix
).defaultNix

81
flake.lock generated
View File

@ -1,32 +1,13 @@
{ {
"nodes": { "nodes": {
"devshell": {
"inputs": {
"flake-utils": "flake-utils",
"nixpkgs": "nixpkgs"
},
"locked": {
"lastModified": 1676293499,
"narHash": "sha256-uIOTlTxvrXxpKeTvwBI1JGDGtCxMXE3BI0LFwoQMhiQ=",
"owner": "numtide",
"repo": "devshell",
"rev": "71e3022e3ab20bbf1342640547ef5bc14fb43bf4",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "devshell",
"type": "github"
}
},
"flake-compat": { "flake-compat": {
"flake": false, "flake": false,
"locked": { "locked": {
"lastModified": 1673956053, "lastModified": 1747046372,
"narHash": "sha256-4gtG9iQuiKITOjNQQeQIpoIB6b16fm+504Ch3sNKLd8=", "narHash": "sha256-CIVLLkVgvHYbgI2UpXvIIBJ12HWgX+fjA8Xf8PUmqCY=",
"owner": "edolstra", "owner": "edolstra",
"repo": "flake-compat", "repo": "flake-compat",
"rev": "35bb57c0c8d8b62bbfd284272c928ceb64ddbde9", "rev": "9100a0f413b0c601e0533d1d94ffd501ce2e7885",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -35,59 +16,13 @@
"type": "github" "type": "github"
} }
}, },
"flake-utils": {
"locked": {
"lastModified": 1642700792,
"narHash": "sha256-XqHrk7hFb+zBvRg6Ghl+AZDq03ov6OshJLiSWOoX5es=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "846b2ae0fc4cc943637d3d1def4454213e203cba",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"flake-utils_2": {
"locked": {
"lastModified": 1676283394,
"narHash": "sha256-XX2f9c3iySLCw54rJ/CZs+ZK6IQy7GXNY4nSOyu2QG4=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "3db36a8b464d0c4532ba1c7dda728f4576d6d073",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nixpkgs": { "nixpkgs": {
"locked": { "locked": {
"lastModified": 1643381941, "lastModified": 1748460289,
"narHash": "sha256-pHTwvnN4tTsEKkWlXQ8JMY423epos8wUOhthpwJjtpc=", "narHash": "sha256-7doLyJBzCllvqX4gszYtmZUToxKvMUrg45EUWaUYmBg=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "5efc8ca954272c4376ac929f4c5ffefcc20551d5", "rev": "96ec055edbe5ee227f28cdbc3f1ddf1df5965102",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs_2": {
"locked": {
"lastModified": 1676300157,
"narHash": "sha256-1HjRzfp6LOLfcj/HJHdVKWAkX9QRAouoh6AjzJiIerU=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "545c7a31e5dedea4a6d372712a18e00ce097d462",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -99,10 +34,8 @@
}, },
"root": { "root": {
"inputs": { "inputs": {
"devshell": "devshell",
"flake-compat": "flake-compat", "flake-compat": "flake-compat",
"flake-utils": "flake-utils_2", "nixpkgs": "nixpkgs"
"nixpkgs": "nixpkgs_2"
} }
} }
}, },

175
flake.nix
View File

@ -1,93 +1,128 @@
{ {
description = "Highly customizable Wayland bar for Sway and Wlroots based compositors."; description = "Highly customizable Wayland bar for Sway and Wlroots based compositors";
inputs = { inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
devshell.url = "github:numtide/devshell";
flake-utils.url = "github:numtide/flake-utils";
flake-compat = { flake-compat = {
url = "github:edolstra/flake-compat"; url = "github:edolstra/flake-compat";
flake = false; flake = false;
}; };
}; };
outputs = { self, flake-utils, devshell, nixpkgs, flake-compat }: outputs =
{ self, nixpkgs, ... }:
let let
inherit (nixpkgs) lib; inherit (nixpkgs) lib;
genSystems = lib.genAttrs [ genSystems =
"x86_64-linux" func:
]; lib.genAttrs
[
"x86_64-linux"
"aarch64-linux"
]
(
system:
func (
import nixpkgs {
inherit system;
overlays = with self.overlays; [
waybar
];
}
)
);
pkgsFor = genSystems (system: mkDate =
import nixpkgs { longDate:
inherit system; (lib.concatStringsSep "-" [
}); (builtins.substring 0 4 longDate)
(builtins.substring 4 2 longDate)
mkDate = longDate: (lib.concatStringsSep "-" [ (builtins.substring 6 2 longDate)
(builtins.substring 0 4 longDate) ]);
(builtins.substring 4 2 longDate)
(builtins.substring 6 2 longDate)
]);
in in
{ {
overlays.default = _: prev: { devShells = genSystems (pkgs: {
waybar = prev.callPackage ./nix/default.nix { default = pkgs.mkShell {
version = prev.waybar.version + "+date=" + (mkDate (self.lastModifiedDate or "19700101")) + "_" + (self.shortRev or "dirty"); name = "waybar-shell";
};
};
packages = genSystems
(system:
(self.overlays.default null pkgsFor.${system})
// {
default = self.packages.${system}.waybar;
});
} //
flake-utils.lib.eachDefaultSystem (system: {
devShell =
let pkgs = import nixpkgs {
inherit system;
overlays = [ devshell.overlay ]; # 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; [
nixfmt-rfc-style
clang-tools
gdb
]);
}; };
in });
pkgs.devshell.mkShell {
imports = [ "${pkgs.devshell.extraModulesDir}/language/c.nix" ]; formatter = genSystems (
commands = [ pkgs:
pkgs.treefmt.withConfig {
settings = [
{ {
package = pkgs.devshell.cli; formatter = {
help = "Per project developer environments"; clang-format = {
options = [ "-i" ];
command = lib.getExe' pkgs.clang-tools "clang-format";
excludes = [ ];
includes = [
"*.c"
"*.cpp"
"*.h"
"*.hpp"
];
};
nixfmt = {
command = lib.getExe pkgs.nixfmt-rfc-style;
includes = [ "*.nix" ];
};
};
tree-root-file = ".git/index";
} }
]; ];
devshell.packages = with pkgs; [ }
clang-tools );
gdb
# from nativeBuildInputs
gnumake
meson
ninja
pkg-config
scdoc
] ++ (map lib.getDev [
# from buildInputs
wayland wlroots gtkmm3 libsigcxx jsoncpp spdlog gtk-layer-shell howard-hinnant-date libxkbcommon
# optional dependencies
gobject-introspection glib playerctl python3.pkgs.pygobject3
libevdev libinput libjack2 libmpdclient playerctl libnl
libpulseaudio sndio sway libdbusmenu-gtk3 udev upower wireplumber
# from propagated build inputs? overlays = {
at-spi2-atk atkmm cairo cairomm catch2 fmt_8 fontconfig default = self.overlays.waybar;
gdk-pixbuf glibmm gtk3 harfbuzz pango pangomm wayland-protocols waybar = final: prev: {
]); waybar = final.callPackage ./nix/default.nix {
env = with pkgs; [ waybar = prev.waybar;
{ name = "CPLUS_INCLUDE_PATH"; prefix = "$DEVSHELL_DIR/include"; } # take the first "version: '...'" from meson.build
{ name = "PKG_CONFIG_PATH"; prefix = "$DEVSHELL_DIR/lib/pkgconfig"; } version =
{ name = "PKG_CONFIG_PATH"; prefix = "$DEVSHELL_DIR/share/pkgconfig"; } (builtins.head (
{ name = "PATH"; prefix = "${wayland.bin}/bin"; } builtins.split "'" (
{ name = "LIBRARY_PATH"; prefix = "${lib.getLib sndio}/lib"; } builtins.elemAt (builtins.split " version: '" (builtins.readFile ./meson.build)) 2
{ name = "LIBRARY_PATH"; prefix = "${lib.getLib zlib}/lib"; } )
{ name = "LIBRARY_PATH"; prefix = "${lib.getLib howard-hinnant-date}/lib"; } ))
]; + "+date="
+ (mkDate (self.lastModifiedDate or "19700101"))
+ "_"
+ (self.shortRev or "dirty");
};
}; };
}); };
packages = genSystems (pkgs: {
default = self.packages.${pkgs.stdenv.hostPlatform.system}.waybar;
inherit (pkgs) waybar;
});
};
} }

27
include/AAppIconLabel.hpp Normal file
View File

@ -0,0 +1,27 @@
#pragma once
#include <gtkmm/box.h>
#include <gtkmm/image.h>
#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

View File

@ -27,6 +27,10 @@ class ALabel : public AModule {
bool handleToggle(GdkEventButton *const &e) override; bool handleToggle(GdkEventButton *const &e) override;
virtual std::string getState(uint8_t value, bool lesser = false); virtual std::string getState(uint8_t value, bool lesser = false);
std::map<std::string, GtkMenuItem *> submenus_;
std::map<std::string, std::string> menuActionsMap_;
static void handleGtkMenuEvent(GtkMenuItem *menuitem, gpointer data);
}; };
} // namespace waybar } // namespace waybar

View File

@ -2,6 +2,7 @@
#include <glibmm/dispatcher.h> #include <glibmm/dispatcher.h>
#include <glibmm/markup.h> #include <glibmm/markup.h>
#include <gtkmm.h>
#include <gtkmm/eventbox.h> #include <gtkmm/eventbox.h>
#include <json/json.h> #include <json/json.h>
@ -11,14 +12,19 @@ namespace waybar {
class AModule : public IModule { class AModule : public IModule {
public: public:
virtual ~AModule(); static constexpr const char *MODULE_CLASS = "module";
~AModule() override;
auto update() -> void override; auto update() -> void override;
virtual auto refresh(int) -> void{}; virtual auto refresh(int shouldRefresh) -> void {};
operator Gtk::Widget &() override; operator Gtk::Widget &() override;
auto doAction(const std::string &name) -> void override; auto doAction(const std::string &name) -> void override;
/// Emitting on this dispatcher triggers a update() call
Glib::Dispatcher dp; Glib::Dispatcher dp;
bool expandEnabled() const;
protected: protected:
// Don't need to make an object directly // Don't need to make an object directly
// Derived classes are able to use it // Derived classes are able to use it
@ -28,34 +34,49 @@ class AModule : public IModule {
enum SCROLL_DIR { NONE, UP, DOWN, LEFT, RIGHT }; enum SCROLL_DIR { NONE, UP, DOWN, LEFT, RIGHT };
SCROLL_DIR getScrollDir(GdkEventScroll *e); SCROLL_DIR getScrollDir(GdkEventScroll *e);
bool tooltipEnabled(); bool tooltipEnabled() const;
std::vector<int> pid_children_; std::vector<int> pid_children_;
const std::string name_; const std::string name_;
const Json::Value &config_; const Json::Value &config_;
Gtk::EventBox event_box_; Gtk::EventBox event_box_;
virtual void setCursor(Gdk::CursorType const &c);
virtual bool handleToggle(GdkEventButton *const &ev); virtual bool handleToggle(GdkEventButton *const &ev);
virtual bool handleMouseEnter(GdkEventCrossing *const &ev);
virtual bool handleMouseLeave(GdkEventCrossing *const &ev);
virtual bool handleScroll(GdkEventScroll *); virtual bool handleScroll(GdkEventScroll *);
virtual bool handleRelease(GdkEventButton *const &ev);
GObject *menu_;
private: private:
bool handleUserEvent(GdkEventButton *const &ev);
const bool isTooltip;
const bool isExpand;
bool hasUserEvents_;
gdouble distance_scrolled_y_; gdouble distance_scrolled_y_;
gdouble distance_scrolled_x_; gdouble distance_scrolled_x_;
std::map<std::string, std::string> eventActionMap_; std::map<std::string, std::string> eventActionMap_;
static const inline std::map<std::pair<uint, GdkEventType>, std::string> eventMap_{ static const inline std::map<std::pair<uint, GdkEventType>, std::string> eventMap_{
{std::make_pair(1, GdkEventType::GDK_BUTTON_PRESS), "on-click"}, {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_2BUTTON_PRESS), "on-double-click"},
{std::make_pair(1, GdkEventType::GDK_3BUTTON_PRESS), "on-triple-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_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_2BUTTON_PRESS), "on-double-click-middle"},
{std::make_pair(2, GdkEventType::GDK_3BUTTON_PRESS), "on-triple-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_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_2BUTTON_PRESS), "on-double-click-right"},
{std::make_pair(3, GdkEventType::GDK_3BUTTON_PRESS), "on-triple-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_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_2BUTTON_PRESS), "on-double-click-backward"},
{std::make_pair(8, GdkEventType::GDK_3BUTTON_PRESS), "on-triple-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_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_2BUTTON_PRESS), "on-double-click-forward"},
{std::make_pair(9, GdkEventType::GDK_3BUTTON_PRESS), "on-triple-click-forward"}}; {std::make_pair(9, GdkEventType::GDK_3BUTTON_PRESS), "on-triple-click-forward"}};
}; };

19
include/ASlider.hpp Normal file
View File

@ -0,0 +1,19 @@
#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 waybar

View File

@ -9,9 +9,11 @@
#include <json/json.h> #include <json/json.h>
#include <memory> #include <memory>
#include <optional>
#include <vector> #include <vector>
#include "AModule.hpp" #include "AModule.hpp"
#include "group.hpp"
#include "xdg-output-unstable-v1-client-protocol.h" #include "xdg-output-unstable-v1-client-protocol.h"
namespace waybar { namespace waybar {
@ -52,35 +54,19 @@ class BarIpcClient;
} }
#endif // HAVE_SWAY #endif // HAVE_SWAY
class BarSurface { class Bar : public sigc::trackable {
protected:
BarSurface() = default;
public: public:
virtual void setExclusiveZone(bool enable) = 0; using bar_mode_map = std::map<std::string, struct bar_mode>;
virtual void setLayer(bar_layer layer) = 0;
virtual void setMargins(const struct bar_margins &margins) = 0;
virtual void setPassThrough(bool enable) = 0;
virtual void setPosition(const std::string_view &position) = 0;
virtual void setSize(uint32_t width, uint32_t height) = 0;
virtual void commit(){};
virtual ~BarSurface() = default;
};
class Bar {
public:
using bar_mode_map = std::map<std::string_view, struct bar_mode>;
static const bar_mode_map PRESET_MODES; static const bar_mode_map PRESET_MODES;
static const std::string_view MODE_DEFAULT; static const std::string MODE_DEFAULT;
static const std::string_view MODE_INVISIBLE; static const std::string MODE_INVISIBLE;
Bar(struct waybar_output *w_output, const Json::Value &); Bar(struct waybar_output *w_output, const Json::Value &);
Bar(const Bar &) = delete; Bar(const Bar &) = delete;
~Bar(); ~Bar();
void setMode(const std::string_view &); void setMode(const std::string &mode);
void setVisible(bool visible); void setVisible(bool value);
void toggle(); void toggle();
void handleSignal(int); void handleSignal(int);
@ -88,8 +74,12 @@ class Bar {
Json::Value config; Json::Value config;
struct wl_surface *surface; struct wl_surface *surface;
bool visible = true; bool visible = true;
bool vertical = false;
Gtk::Window window; Gtk::Window window;
Gtk::Orientation orientation = Gtk::ORIENTATION_HORIZONTAL;
Gtk::PositionType position = Gtk::POS_TOP;
int x_global;
int y_global;
#ifdef HAVE_SWAY #ifdef HAVE_SWAY
std::string bar_id; std::string bar_id;
@ -98,16 +88,24 @@ class Bar {
private: private:
void onMap(GdkEventAny *); void onMap(GdkEventAny *);
auto setupWidgets() -> void; auto setupWidgets() -> void;
void getModules(const Factory &, const std::string &, Gtk::Box *); void getModules(const Factory &, const std::string &, waybar::Group *);
void setupAltFormatKeyForModule(const std::string &module_name); void setupAltFormatKeyForModule(const std::string &module_name);
void setupAltFormatKeyForModuleList(const char *module_list_name); void setupAltFormatKeyForModuleList(const char *module_list_name);
void setMode(const bar_mode &); void setMode(const bar_mode &);
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 */ /* Copy initial set of modes to allow customization */
bar_mode_map configured_modes = PRESET_MODES; bar_mode_map configured_modes = PRESET_MODES;
std::string last_mode_{MODE_DEFAULT}; std::string last_mode_{MODE_DEFAULT};
std::unique_ptr<BarSurface> surface_impl_; struct bar_margins margins_;
uint32_t width_, height_;
bool passthrough_;
Gtk::Box left_; Gtk::Box left_;
Gtk::Box center_; Gtk::Box center_;
Gtk::Box right_; Gtk::Box right_;

View File

@ -7,8 +7,9 @@
#include "bar.hpp" #include "bar.hpp"
#include "config.hpp" #include "config.hpp"
#include "util/css_reload_helper.hpp"
#include "util/portal.hpp"
struct zwlr_layer_shell_v1;
struct zwp_idle_inhibitor_v1; struct zwp_idle_inhibitor_v1;
struct zwp_idle_inhibit_manager_v1; struct zwp_idle_inhibit_manager_v1;
@ -24,7 +25,6 @@ class Client {
Glib::RefPtr<Gdk::Display> gdk_display; Glib::RefPtr<Gdk::Display> gdk_display;
struct wl_display *wl_display = nullptr; struct wl_display *wl_display = nullptr;
struct wl_registry *registry = nullptr; struct wl_registry *registry = nullptr;
struct zwlr_layer_shell_v1 *layer_shell = nullptr;
struct zxdg_output_manager_v1 *xdg_output_manager = nullptr; struct zxdg_output_manager_v1 *xdg_output_manager = nullptr;
struct zwp_idle_inhibit_manager_v1 *idle_inhibit_manager = nullptr; struct zwp_idle_inhibit_manager_v1 *idle_inhibit_manager = nullptr;
std::vector<std::unique_ptr<Bar>> bars; std::vector<std::unique_ptr<Bar>> bars;
@ -33,7 +33,7 @@ class Client {
private: private:
Client() = default; Client() = default;
const std::string getStyle(const std::string &style); const std::string getStyle(const std::string &style, std::optional<Appearance> appearance);
void bindInterfaces(); void bindInterfaces();
void handleOutput(struct waybar_output &output); void handleOutput(struct waybar_output &output);
auto setupCss(const std::string &css_file) -> void; auto setupCss(const std::string &css_file) -> void;
@ -52,7 +52,10 @@ class Client {
Glib::RefPtr<Gtk::StyleContext> style_context_; Glib::RefPtr<Gtk::StyleContext> style_context_;
Glib::RefPtr<Gtk::CssProvider> css_provider_; Glib::RefPtr<Gtk::CssProvider> css_provider_;
std::unique_ptr<Portal> portal;
std::list<struct waybar_output> outputs_; std::list<struct waybar_output> outputs_;
std::unique_ptr<CssReloadHelper> m_cssReloadHelper;
std::string m_cssFile;
}; };
} // namespace waybar } // namespace waybar

View File

@ -20,6 +20,9 @@ class Config {
static std::optional<std::string> findConfigPath( static std::optional<std::string> findConfigPath(
const std::vector<std::string> &names, const std::vector<std::string> &dirs = CONFIG_DIRS); const std::vector<std::string> &names, const std::vector<std::string> &dirs = CONFIG_DIRS);
static std::vector<std::string> tryExpandPath(const std::string &base,
const std::string &filename);
Config() = default; Config() = default;
void load(const std::string &config); void load(const std::string &config);

View File

@ -1,104 +1,17 @@
#pragma once #pragma once
#include <json/json.h> #include <json/json.h>
#if defined(HAVE_CHRONO_TIMEZONES) || defined(HAVE_LIBDATE)
#include "modules/clock.hpp" #include <AModule.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
#include "modules/wlr/taskbar.hpp"
#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"
#endif
#ifdef HAVE_HYPRLAND
#include "modules/hyprland/backend.hpp"
#include "modules/hyprland/language.hpp"
#include "modules/hyprland/submap.hpp"
#include "modules/hyprland/window.hpp"
#include "modules/hyprland/workspaces.hpp"
#endif
#if defined(__FreeBSD__) || (defined(__linux__) && !defined(NO_FILESYSTEM))
#include "modules/battery.hpp"
#endif
#if defined(HAVE_CPU_LINUX) || defined(HAVE_CPU_BSD)
#include "modules/cpu.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"
#endif
#ifdef HAVE_LIBEVDEV
#include "modules/keyboard_state.hpp"
#endif
#ifdef HAVE_GAMEMODE
#include "modules/gamemode.hpp"
#endif
#ifdef HAVE_UPOWER
#include "modules/upower/upower.hpp"
#endif
#ifdef HAVE_LIBPULSE
#include "modules/pulseaudio.hpp"
#endif
#ifdef HAVE_LIBMPDCLIENT
#include "modules/mpd/mpd.hpp"
#endif
#ifdef HAVE_LIBSNDIO
#include "modules/sndio.hpp"
#endif
#ifdef HAVE_GIO_UNIX
#include "modules/bluetooth.hpp"
#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
#include "bar.hpp"
#include "modules/custom.hpp"
#include "modules/image.hpp"
#include "modules/temperature.hpp"
#include "modules/user.hpp"
namespace waybar { namespace waybar {
class Bar;
class Factory { class Factory {
public: public:
Factory(const Bar& bar, const Json::Value& config); Factory(const Bar& bar, const Json::Value& config);
AModule* makeModule(const std::string& name) const; AModule* makeModule(const std::string& name, const std::string& pos) const;
private: private:
const Bar& bar_; const Bar& bar_;

View File

@ -5,18 +5,33 @@
#include <json/json.h> #include <json/json.h>
#include "AModule.hpp" #include "AModule.hpp"
#include "bar.hpp" #include "gtkmm/revealer.h"
#include "factory.hpp"
namespace waybar { namespace waybar {
class Group : public AModule { class Group : public AModule {
public: public:
Group(const std::string&, const std::string&, const Json::Value&, bool); Group(const std::string &, const std::string &, const Json::Value &, bool);
~Group() = default; ~Group() override = default;
auto update() -> void override; auto update() -> void override;
operator Gtk::Widget&() override; operator Gtk::Widget &() override;
virtual Gtk::Box &getBox();
void addWidget(Gtk::Widget &widget);
protected:
Gtk::Box box; 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 } // namespace waybar

View File

@ -1,14 +1,14 @@
#pragma once #pragma once
#include <memory>
#include <optional> #include <optional>
#include <string> #include <string>
#include <string_view> #include <string_view>
#include <vector> #include <vector>
#include "ALabel.hpp" #include "ALabel.hpp"
#include "giomm/dbusproxy.h" #include "util/backlight_backend.hpp"
#include "util/json.hpp" #include "util/json.hpp"
#include "util/sleeper_thread.hpp"
struct udev; struct udev;
struct udev_device; struct udev_device;
@ -16,54 +16,17 @@ struct udev_device;
namespace waybar::modules { namespace waybar::modules {
class Backlight : public ALabel { class Backlight : public ALabel {
class BacklightDev {
public:
BacklightDev() = default;
BacklightDev(std::string name, int actual, int max, bool powered);
std::string_view 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 BacklightDev &lhs, const BacklightDev &rhs) {
return lhs.name_ == rhs.name_ && lhs.actual_ == rhs.actual_ && lhs.max_ == rhs.max_;
}
private:
std::string name_;
int actual_ = 1;
int max_ = 1;
bool powered_ = true;
};
public: public:
Backlight(const std::string &, const Json::Value &); Backlight(const std::string &, const Json::Value &);
virtual ~Backlight(); virtual ~Backlight() = default;
auto update() -> void override; auto update() -> void override;
private:
template <class ForwardIt>
static const BacklightDev *best_device(ForwardIt first, ForwardIt last, std::string_view);
template <class ForwardIt, class Inserter>
static void upsert_device(ForwardIt first, ForwardIt last, Inserter inserter, udev_device *dev);
template <class ForwardIt, class Inserter>
static void enumerate_devices(ForwardIt first, ForwardIt last, Inserter inserter, udev *udev);
bool handleScroll(GdkEventScroll *e) override; bool handleScroll(GdkEventScroll *e) override;
const std::string preferred_device_; const std::string preferred_device_;
static constexpr int EPOLL_MAX_EVENTS = 16;
std::optional<BacklightDev> previous_best_;
std::string previous_format_; std::string previous_format_;
std::mutex udev_thread_mutex_; util::BacklightBackend backend;
std::vector<BacklightDev> devices_;
// thread must destruct before shared data
util::SleeperThread udev_thread_;
Glib::RefPtr<Gio::DBus::Proxy> login_proxy_;
}; };
} // namespace waybar::modules } // namespace waybar::modules

View File

@ -0,0 +1,24 @@
#pragma once
#include <chrono>
#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::modules

View File

@ -1,11 +1,8 @@
#pragma once #pragma once
#ifdef FILESYSTEM_EXPERIMENTAL
#include <experimental/filesystem>
#else
#include <filesystem>
#endif
#include <fmt/format.h> #include <fmt/format.h>
#include <filesystem>
#if defined(__linux__) #if defined(__linux__)
#include <sys/inotify.h> #include <sys/inotify.h>
#endif #endif
@ -16,19 +13,16 @@
#include <vector> #include <vector>
#include "ALabel.hpp" #include "ALabel.hpp"
#include "bar.hpp"
#include "util/sleeper_thread.hpp" #include "util/sleeper_thread.hpp"
namespace waybar::modules { namespace waybar::modules {
#ifdef FILESYSTEM_EXPERIMENTAL
namespace fs = std::experimental::filesystem;
#else
namespace fs = std::filesystem; namespace fs = std::filesystem;
#endif
class Battery : public ALabel { class Battery : public ALabel {
public: public:
Battery(const std::string&, const Json::Value&); Battery(const std::string&, const waybar::Bar&, const Json::Value&);
virtual ~Battery(); virtual ~Battery();
auto update() -> void override; auto update() -> void override;
@ -38,8 +32,9 @@ class Battery : public ALabel {
void refreshBatteries(); void refreshBatteries();
void worker(); void worker();
const std::string getAdapterStatus(uint8_t capacity) const; const std::string getAdapterStatus(uint8_t capacity) const;
const std::tuple<uint8_t, float, std::string, float> getInfos(); std::tuple<uint8_t, float, std::string, float, uint16_t, float> getInfos();
const std::string formatTimeRemaining(float hoursRemaining); const std::string formatTimeRemaining(float hoursRemaining);
void setBarClass(std::string&);
int global_watch; int global_watch;
std::map<fs::path, int> batteries_; std::map<fs::path, int> batteries_;
@ -49,6 +44,7 @@ class Battery : public ALabel {
std::mutex battery_list_mutex_; std::mutex battery_list_mutex_;
std::string old_status_; std::string old_status_;
bool warnFirstTime_{true}; bool warnFirstTime_{true};
const Bar& bar_;
util::SleeperThread thread_; util::SleeperThread thread_;
util::SleeperThread thread_battery_update_; util::SleeperThread thread_battery_update_;

View File

@ -49,6 +49,9 @@ class Bluetooth : public ALabel {
auto update() -> void override; auto update() -> void override;
private: private:
static auto onObjectAdded(GDBusObjectManager*, GDBusObject*, gpointer) -> void;
static auto onObjectRemoved(GDBusObjectManager*, GDBusObject*, gpointer) -> void;
static auto onInterfaceAddedOrRemoved(GDBusObjectManager*, GDBusObject*, GDBusInterface*, static auto onInterfaceAddedOrRemoved(GDBusObjectManager*, GDBusObject*, GDBusInterface*,
gpointer) -> void; gpointer) -> void;
static auto onInterfaceProxyPropertiesChanged(GDBusObjectManagerClient*, GDBusObjectProxy*, static auto onInterfaceProxyPropertiesChanged(GDBusObjectManagerClient*, GDBusObjectProxy*,
@ -59,7 +62,8 @@ class Bluetooth : public ALabel {
auto getDeviceProperties(GDBusObject*, DeviceInfo&) -> bool; auto getDeviceProperties(GDBusObject*, DeviceInfo&) -> bool;
auto getControllerProperties(GDBusObject*, ControllerInfo&) -> bool; auto getControllerProperties(GDBusObject*, ControllerInfo&) -> bool;
auto findCurController(ControllerInfo&) -> bool; // Returns std::nullopt if no controller could be found
auto findCurController() -> std::optional<ControllerInfo>;
auto findConnectedDevices(const std::string&, std::vector<DeviceInfo>&) -> void; auto findConnectedDevices(const std::string&, std::vector<DeviceInfo>&) -> void;
#ifdef WANT_RFKILL #ifdef WANT_RFKILL
@ -68,7 +72,7 @@ class Bluetooth : public ALabel {
const std::unique_ptr<GDBusObjectManager, void (*)(GDBusObjectManager*)> manager_; const std::unique_ptr<GDBusObjectManager, void (*)(GDBusObjectManager*)> manager_;
std::string state_; std::string state_;
ControllerInfo cur_controller_; std::optional<ControllerInfo> cur_controller_;
std::vector<DeviceInfo> connected_devices_; std::vector<DeviceInfo> connected_devices_;
DeviceInfo cur_focussed_device_; DeviceInfo cur_focussed_device_;
std::string device_enumerate_; std::string device_enumerate_;

View File

@ -3,9 +3,20 @@
#include "ALabel.hpp" #include "ALabel.hpp"
#include "util/sleeper_thread.hpp" #include "util/sleeper_thread.hpp"
namespace cava {
extern "C" { extern "C" {
// Need sdl_glsl output feature to be enabled on libcava
#ifndef SDL_GLSL
#define SDL_GLSL
#endif
#include <cava/common.h> #include <cava/common.h>
#ifdef SDL_GLSL
#undef SDL_GLSL
#endif
} }
} // namespace cava
namespace waybar::modules { namespace waybar::modules {
using namespace std::literals::chrono_literals; using namespace std::literals::chrono_literals;
@ -21,13 +32,13 @@ class Cava final : public ALabel {
util::SleeperThread thread_; util::SleeperThread thread_;
util::SleeperThread thread_fetch_input_; util::SleeperThread thread_fetch_input_;
struct error_s error_ {}; // cava errors struct cava::error_s error_{}; // cava errors
struct config_params prm_ {}; // cava parameters struct cava::config_params prm_{}; // cava parameters
struct audio_raw audio_raw_ {}; // cava handled raw audio data(is based on audio_data) struct cava::audio_raw audio_raw_{}; // cava handled raw audio data(is based on audio_data)
struct audio_data audio_data_ {}; // cava audio data struct cava::audio_data audio_data_{}; // cava audio data
struct cava_plan* plan_; //{new cava_plan{}}; struct cava::cava_plan* plan_; //{new cava_plan{}};
// Cava API to read audio source // Cava API to read audio source
ptr input_source_; cava::ptr input_source_;
// Delay to handle audio source // Delay to handle audio source
std::chrono::milliseconds frame_time_milsec_{1s}; std::chrono::milliseconds frame_time_milsec_{1s};
// Text to display // Text to display
@ -36,11 +47,13 @@ class Cava final : public ALabel {
std::chrono::seconds fetch_input_delay_{4}; std::chrono::seconds fetch_input_delay_{4};
std::chrono::seconds suspend_silence_delay_{0}; std::chrono::seconds suspend_silence_delay_{0};
bool silence_{false}; bool silence_{false};
bool hide_on_silence_{false};
std::string format_silent_{""};
int sleep_counter_{0}; int sleep_counter_{0};
// Cava method // Cava method
void pause_resume(); void pause_resume();
// ModuleActionMap // ModuleActionMap
static inline std::map<const std::string, void (waybar::modules::Cava::*const)()> actionMap_{ static inline std::map<const std::string, void (waybar::modules::Cava::* const)()> actionMap_{
{"mode", &waybar::modules::Cava::pause_resume}}; {"mode", &waybar::modules::Cava::pause_resume}};
}; };
} // namespace waybar::modules } // namespace waybar::modules

60
include/modules/cffi.hpp Normal file
View File

@ -0,0 +1,60 @@
#pragma once
#include <string>
#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<InitFn> init = nullptr;
std::function<DenitFn> deinit = nullptr;
std::function<RefreshFn> refresh = [](void*, int) {};
std::function<DoActionFn> doAction = [](void*, const char*) {};
std::function<UpdateFn> update = [](void*) {};
} hooks_;
};
} // namespace waybar::modules

View File

@ -6,67 +6,86 @@
namespace waybar::modules { namespace waybar::modules {
const std::string kCalendarPlaceholder = "calendar"; const std::string kCldPlaceholder{"calendar"};
const std::string KTimezonedTimeListPlaceholder = "timezoned_time_list"; const std::string kTZPlaceholder{"tz_list"};
const std::string kOrdPlaceholder{"ordinal_date"};
enum class WeeksSide {
LEFT,
RIGHT,
HIDDEN,
};
enum class CldMode { MONTH, YEAR }; enum class CldMode { MONTH, YEAR };
enum class WS { LEFT, RIGHT, HIDDEN };
class Clock final : public ALabel { class Clock final : public ALabel {
public: public:
Clock(const std::string&, const Json::Value&); Clock(const std::string&, const Json::Value&);
virtual ~Clock() = default; virtual ~Clock() = default;
auto update() -> void override; auto update() -> void override;
auto doAction(const std::string& name) -> void override; auto doAction(const std::string&) -> void override;
private: private:
util::SleeperThread thread_; const std::locale m_locale_;
std::locale locale_; // tooltip
std::vector<const date::time_zone*> time_zones_; const std::string m_tlpFmt_;
int current_time_zone_idx_; std::string m_tlpText_{""}; // tooltip text to print
bool is_calendar_in_tooltip_; const Glib::RefPtr<Gtk::Label> m_tooltip_; // tooltip as a separate Gtk::Label
bool is_timezoned_list_in_tooltip_; bool query_tlp_cb(int, int, bool, const Glib::RefPtr<Gtk::Tooltip>& tooltip);
// Calendar
auto first_day_of_week() -> date::weekday; const bool cldInTooltip_; // calendar in tooltip
const date::time_zone* current_timezone(); /*
bool is_timezone_fixed(); 0 - calendar.format.months
auto timezones_text(std::chrono::system_clock::time_point* now) -> std::string; 1 - calendar.format.weekdays
2 - calendar.format.days
/*Calendar properties*/ 3 - calendar.format.today
WeeksSide cldWPos_{WeeksSide::HIDDEN}; 4 - calendar.format.weeks
5 - tooltip-format
*/
std::map<int, std::string const> fmtMap_; std::map<int, std::string const> 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
date::months cldCurrShift_{0}; // calendar months shift
int cldShift_{1}; // calendar months shift factor
date::year_month_day cldYearShift_; // calendar Year mode. Cached ymd
std::string cldYearCached_; // calendar Year mode. Cached calendar
date::year_month cldMonShift_; // calendar Month mode. Cached ym
std::string cldMonCached_; // calendar Month mode. Cached calendar
date::day cldBaseDay_{0}; // calendar Cached day. Is used when today is changing(midnight)
std::string cldText_{""}; // calendar text to print
CldMode cldMode_{CldMode::MONTH}; CldMode cldMode_{CldMode::MONTH};
uint cldMonCols_{3}; // Count of the month in the row auto get_calendar(const date::year_month_day& today, const date::year_month_day& ymd,
int cldMonColLen_{20}; // Length of the month column const date::time_zone* tz) -> const std::string;
int cldWnLen_{3}; // Length of the week number
date::year_month_day cldYearShift_; // get local time zone
date::year_month cldMonShift_; auto local_zone() -> const date::time_zone*;
date::months cldCurrShift_{0};
date::months cldShift_{0}; // time zoned time in tooltip
std::string cldYearCached_{}; const bool tzInTooltip_; // if need to print time zones text
std::string cldMonCached_{}; std::vector<const date::time_zone*> tzList_; // time zones list
date::day cldBaseDay_{0}; int tzCurrIdx_; // current time zone index for tzList_
/*Calendar functions*/ std::string tzText_{""}; // time zones text to print
auto get_calendar(const date::zoned_seconds& now, const date::zoned_seconds& wtime) util::SleeperThread thread_;
-> std::string;
/*Clock actions*/ // ordinal date in tooltip
const bool ordInTooltip_;
std::string ordText_{""};
auto get_ordinal_date(const date::year_month_day& today) -> std::string;
auto getTZtext(date::sys_seconds now) -> std::string;
auto first_day_of_week() -> date::weekday;
// Module actions
void cldModeSwitch(); void cldModeSwitch();
void cldShift_up(); void cldShift_up();
void cldShift_down(); void cldShift_down();
void cldShift_reset();
void tz_up(); void tz_up();
void tz_down(); void tz_down();
// Module Action Map
// ModuleActionMap static inline std::map<const std::string, void (waybar::modules::Clock::* const)()> actionMap_{
static inline std::map<const std::string, void (waybar::modules::Clock::*const)()> actionMap_{
{"mode", &waybar::modules::Clock::cldModeSwitch}, {"mode", &waybar::modules::Clock::cldModeSwitch},
{"shift_up", &waybar::modules::Clock::cldShift_up}, {"shift_up", &waybar::modules::Clock::cldShift_up},
{"shift_down", &waybar::modules::Clock::cldShift_down}, {"shift_down", &waybar::modules::Clock::cldShift_down},
{"shift_reset", &waybar::modules::Clock::cldShift_reset},
{"tz_up", &waybar::modules::Clock::tz_up}, {"tz_up", &waybar::modules::Clock::tz_up},
{"tz_down", &waybar::modules::Clock::tz_down}}; {"tz_down", &waybar::modules::Clock::tz_down}};
}; };
} // namespace waybar::modules } // namespace waybar::modules

View File

@ -21,12 +21,6 @@ class Cpu : public ALabel {
auto update() -> void override; auto update() -> void override;
private: private:
double getCpuLoad();
std::tuple<std::vector<uint16_t>, std::string> getCpuUsage();
std::tuple<float, float, float> getCpuFrequency();
std::vector<std::tuple<size_t, size_t>> parseCpuinfo();
std::vector<float> parseCpuFrequencies();
std::vector<std::tuple<size_t, size_t>> prev_times_; std::vector<std::tuple<size_t, size_t>> prev_times_;
util::SleeperThread thread_; util::SleeperThread thread_;

View File

@ -0,0 +1,32 @@
#pragma once
#include <fmt/format.h>
#include <cstdint>
#include <fstream>
#include <numeric>
#include <string>
#include <utility>
#include <vector>
#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<float, float, float> getCpuFrequency();
private:
static std::vector<float> parseCpuFrequencies();
util::SleeperThread thread_;
};
} // namespace waybar::modules

View File

@ -0,0 +1,35 @@
#pragma once
#include <fmt/format.h>
#include <cstdint>
#include <fstream>
#include <numeric>
#include <string>
#include <utility>
#include <vector>
#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::vector<uint16_t>, std::string> getCpuUsage(
std::vector<std::tuple<size_t, size_t>>&);
private:
static std::vector<std::tuple<size_t, size_t>> parseCpuinfo();
std::vector<std::tuple<size_t, size_t>> prev_times_;
util::SleeperThread thread_;
};
} // namespace waybar::modules

View File

@ -14,7 +14,7 @@ namespace waybar::modules {
class Custom : public ALabel { class Custom : public ALabel {
public: public:
Custom(const std::string&, const std::string&, const Json::Value&); Custom(const std::string&, const std::string&, const Json::Value&, const std::string&);
virtual ~Custom(); virtual ~Custom();
auto update() -> void override; auto update() -> void override;
void refresh(int /*signal*/) override; void refresh(int /*signal*/) override;
@ -22,6 +22,7 @@ class Custom : public ALabel {
private: private:
void delayWorker(); void delayWorker();
void continuousWorker(); void continuousWorker();
void waitingWorker();
void parseOutputRaw(); void parseOutputRaw();
void parseOutputJson(); void parseOutputJson();
void handleEvent(); void handleEvent();
@ -29,10 +30,12 @@ class Custom : public ALabel {
bool handleToggle(GdkEventButton* const& e) override; bool handleToggle(GdkEventButton* const& e) override;
const std::string name_; const std::string name_;
const std::string output_name_;
std::string text_; std::string text_;
std::string id_; std::string id_;
std::string alt_; std::string alt_;
std::string tooltip_; std::string tooltip_;
const bool tooltip_format_enabled_;
std::vector<std::string> class_; std::vector<std::string> class_;
int percentage_; int percentage_;
FILE* fp_; FILE* fp_;

View File

@ -20,6 +20,9 @@ class Disk : public ALabel {
private: private:
util::SleeperThread thread_; util::SleeperThread thread_;
std::string path_; std::string path_;
std::string unit_;
float calc_specific_divisor(const std::string divisor);
}; };
} // namespace waybar::modules } // namespace waybar::modules

View File

@ -0,0 +1,38 @@
#pragma once
#include <fmt/format.h>
#include <string>
#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

View File

@ -1,10 +1,11 @@
#pragma once #pragma once
#include <functional>
#include <filesystem>
#include <list> #include <list>
#include <memory>
#include <mutex> #include <mutex>
#include <string> #include <string>
#include <thread> #include <thread>
#include <utility>
#include "util/json.hpp" #include "util/json.hpp"
@ -18,23 +19,31 @@ class EventHandler {
class IPC { class IPC {
public: public:
IPC() { startIPC(); } IPC();
~IPC();
static IPC& inst();
void registerForIPC(const std::string&, EventHandler*); void registerForIPC(const std::string& ev, EventHandler* ev_handler);
void unregisterForIPC(EventHandler*); void unregisterForIPC(EventHandler* handler);
std::string getSocket1Reply(const std::string& rq); static std::string getSocket1Reply(const std::string& rq);
Json::Value getSocket1JsonReply(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: private:
void startIPC(); void socketListener();
void parseIPC(const std::string&); void parseIPC(const std::string&);
std::mutex callbackMutex; std::thread ipcThread_;
std::mutex callbackMutex_;
util::JsonParser parser_; util::JsonParser parser_;
std::list<std::pair<std::string, EventHandler*>> callbacks; std::list<std::pair<std::string, EventHandler*>> callbacks_;
int socketfd_; // the hyprland socket file descriptor
bool running_ = true;
}; };
inline std::unique_ptr<IPC> gIPC;
inline bool modulesReady = false; inline bool modulesReady = false;
}; // namespace waybar::modules::hyprland }; // namespace waybar::modules::hyprland

View File

@ -1,5 +1,9 @@
#pragma once
#include <fmt/format.h> #include <fmt/format.h>
#include <string>
#include "ALabel.hpp" #include "ALabel.hpp"
#include "bar.hpp" #include "bar.hpp"
#include "modules/hyprland/backend.hpp" #include "modules/hyprland/backend.hpp"
@ -26,13 +30,15 @@ class Language : public waybar::ALabel, public EventHandler {
std::string short_description; std::string short_description;
}; };
auto getLayout(const std::string&) -> Layout; static auto getLayout(const std::string&) -> Layout;
std::mutex mutex_; std::mutex mutex_;
const Bar& bar_; const Bar& bar_;
util::JsonParser parser_; util::JsonParser parser_;
Layout layout_; Layout layout_;
IPC& m_ipc;
}; };
} // namespace waybar::modules::hyprland } // namespace waybar::modules::hyprland

View File

@ -1,5 +1,9 @@
#pragma once
#include <fmt/format.h> #include <fmt/format.h>
#include <string>
#include "ALabel.hpp" #include "ALabel.hpp"
#include "bar.hpp" #include "bar.hpp"
#include "modules/hyprland/backend.hpp" #include "modules/hyprland/backend.hpp"
@ -10,17 +14,22 @@ namespace waybar::modules::hyprland {
class Submap : public waybar::ALabel, public EventHandler { class Submap : public waybar::ALabel, public EventHandler {
public: public:
Submap(const std::string&, const waybar::Bar&, const Json::Value&); Submap(const std::string&, const waybar::Bar&, const Json::Value&);
virtual ~Submap(); ~Submap() override;
auto update() -> void override; auto update() -> void override;
private: private:
void onEvent(const std::string&) override; auto parseConfig(const Json::Value&) -> void;
void onEvent(const std::string& ev) override;
std::mutex mutex_; std::mutex mutex_;
const Bar& bar_; const Bar& bar_;
util::JsonParser parser_; util::JsonParser parser_;
std::string submap_; std::string submap_;
bool always_on_ = false;
std::string default_submap_ = "Default";
IPC& m_ipc;
}; };
} // namespace waybar::modules::hyprland } // namespace waybar::modules::hyprland

View File

@ -1,16 +1,20 @@
#pragma once
#include <fmt/format.h> #include <fmt/format.h>
#include "ALabel.hpp" #include <string>
#include "AAppIconLabel.hpp"
#include "bar.hpp" #include "bar.hpp"
#include "modules/hyprland/backend.hpp" #include "modules/hyprland/backend.hpp"
#include "util/json.hpp" #include "util/json.hpp"
namespace waybar::modules::hyprland { namespace waybar::modules::hyprland {
class Window : public waybar::ALabel, public EventHandler { class Window : public waybar::AAppIconLabel, public EventHandler {
public: public:
Window(const std::string&, const waybar::Bar&, const Json::Value&); Window(const std::string&, const waybar::Bar&, const Json::Value&);
virtual ~Window(); ~Window() override;
auto update() -> void override; auto update() -> void override;
@ -21,26 +25,43 @@ class Window : public waybar::ALabel, public EventHandler {
std::string last_window; std::string last_window;
std::string last_window_title; std::string last_window_title;
static auto parse(const Json::Value&) -> Workspace; static auto parse(const Json::Value& value) -> Workspace;
}; };
auto getActiveWorkspace(const std::string&) -> Workspace; struct WindowData {
auto getActiveWorkspace() -> Workspace; bool floating;
void onEvent(const std::string&) override; 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 queryActiveWorkspace();
void setClass(const std::string&, bool enable); void setClass(const std::string&, bool enable);
bool separate_outputs; bool separateOutputs_;
std::mutex mutex_; std::mutex mutex_;
const Bar& bar_; const Bar& bar_;
util::JsonParser parser_; util::JsonParser parser_;
std::string last_title_; WindowData windowData_;
Workspace workspace_; Workspace workspace_;
std::string solo_class_; std::string soloClass_;
std::string last_solo_class_; std::string lastSoloClass_;
bool solo_; bool solo_;
bool all_floating_; bool allFloating_;
bool swallowing_;
bool fullscreen_; bool fullscreen_;
bool focused_;
IPC& m_ipc;
}; };
} // namespace waybar::modules::hyprland } // namespace waybar::modules::hyprland

View File

@ -0,0 +1,61 @@
#pragma once
#include <gtkmm/button.h>
#include <gtkmm/label.h>
#include <json/value.h>
#include <cstddef>
#include <cstdint>
#include <map>
#include <memory>
#include <optional>
#include <regex>
#include <string>
#include <variant>
#include <vector>
#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<Repr>(m_window); }
std::string repr(Workspaces& workspace_manager);
std::string getWorkspaceName() const { return m_workspaceName; }
WindowAddress getAddress() const { return m_windowAddress; }
void moveToWorkspace(std::string& new_workspace_name);
private:
void clearAddr();
void clearWorkspaceName();
using Repr = std::string;
using ClassAndTitle = std::pair<std::string, std::string>;
std::variant<Repr, ClassAndTitle> m_window;
WindowAddress m_windowAddress;
std::string m_workspaceName;
int m_timeSpentUncreated = 0;
};
} // namespace waybar::modules::hyprland

View File

@ -0,0 +1,89 @@
#pragma once
#include <gtkmm/button.h>
#include <gtkmm/label.h>
#include <json/value.h>
#include <cstddef>
#include <cstdint>
#include <map>
#include <memory>
#include <optional>
#include <regex>
#include <string>
#include <variant>
#include <vector>
#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<std::string, std::string>& 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_payload);
std::string removeWindow(WindowAddress const& addr);
void initializeWindowMap(const Json::Value& clients_data);
bool onWindowOpened(WindowCreationPayload const& create_window_payload);
std::optional<std::string> 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<WindowAddress, std::string> m_windowMap;
Gtk::Button m_button;
Gtk::Box m_content;
Gtk::Label m_label;
IPC& m_ipc;
};
} // namespace waybar::modules::hyprland

View File

@ -1,64 +1,165 @@
#pragma once
#include <gtkmm/button.h> #include <gtkmm/button.h>
#include <gtkmm/label.h> #include <gtkmm/label.h>
#include <json/value.h>
#include <cstdint>
#include <map>
#include <memory> #include <memory>
#include <optional>
#include <regex>
#include <string>
#include <vector>
#include "AModule.hpp" #include "AModule.hpp"
#include "bar.hpp" #include "bar.hpp"
#include "modules/hyprland/backend.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 { namespace waybar::modules::hyprland {
struct WorkspaceDto { class Workspaces;
int id;
static WorkspaceDto parse(const Json::Value& value);
};
class Workspace {
public:
Workspace(int id);
Workspace(WorkspaceDto dto);
int id() const { return id_; };
int active() const { return active_; };
std::string& select_icon(std::map<std::string, std::string>& icons_map);
void set_active(bool value = true) { active_ = value; };
Gtk::Button& button() { return button_; };
void update(const std::string& format, const std::string& icon);
private:
int id_;
bool active_;
Gtk::Button button_;
Gtk::Box content_;
Gtk::Label label_;
};
class Workspaces : public AModule, public EventHandler { class Workspaces : public AModule, public EventHandler {
public: public:
Workspaces(const std::string&, const waybar::Bar&, const Json::Value&); Workspaces(const std::string&, const waybar::Bar&, const Json::Value&);
virtual ~Workspaces(); ~Workspaces() override;
void update() override; void update() override;
void init(); void init();
private: auto allOutputs() const -> bool { return m_allOutputs; }
void onEvent(const std::string&) override; auto showSpecial() const -> bool { return m_showSpecial; }
void sort_workspaces(); auto activeOnly() const -> bool { return m_activeOnly; }
void create_workspace(int id); auto specialVisibleOnly() const -> bool { return m_specialVisibleOnly; }
void remove_workspace(int id); auto moveToMonitor() const -> bool { return m_moveToMonitor; }
std::string format_; auto getBarOutput() const -> std::string { return m_bar.output->name; }
std::map<std::string, std::string> icons_map_;
bool with_icon_; std::string getRewrite(std::string window_class, std::string window_title);
int active_workspace_id; std::string& getWindowSeparator() { return m_formatWindowSeparator; }
std::vector<std::unique_ptr<Workspace>> workspaces_; bool isWorkspaceIgnored(std::string const& workspace_name);
std::vector<int> workspaces_to_create_;
std::vector<int> workspaces_to_remove_; bool windowRewriteConfigUsesTitle() const { return m_anyWindowRewriteRuleUsesTitle; }
std::mutex mutex_;
const Bar& bar_; private:
Gtk::Box box_; 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& workspaceString);
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& payload,
Json::Value const& clientsData = Json::Value::nullRef);
void onWorkspaceMoved(std::string const& payload);
void onWorkspaceRenamed(std::string const& payload);
static std::optional<int> parseWorkspaceId(std::string const& workspaceIdStr);
// 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);
// event payload management
template <typename... Args>
static std::string makePayload(Args const&... args);
static std::pair<std::string, std::string> splitDoublePayload(std::string const& payload);
static std::tuple<std::string, std::string, std::string> splitTriplePayload(
std::string const& payload);
// Update methods
void doUpdate();
void removeWorkspacesToRemove();
void createWorkspacesToCreate();
static std::vector<int> 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 across bars (a.k.a `all-outputs` = false)
std::map<WindowAddress, std::string> m_orphanWindowMap;
enum class SortMethod { ID, NAME, NUMBER, DEFAULT };
util::EnumParser<SortMethod> m_enumParser;
SortMethod m_sortBy = SortMethod::DEFAULT;
std::map<std::string, SortMethod> m_sortMap = {{"ID", SortMethod::ID},
{"NAME", SortMethod::NAME},
{"NUMBER", SortMethod::NUMBER},
{"DEFAULT", SortMethod::DEFAULT}};
std::string m_format;
std::map<std::string, std::string> m_iconsMap;
util::RegexCollection m_windowRewriteRules;
bool m_anyWindowRewriteRuleUsesTitle = false;
std::string m_formatWindowSeparator;
bool m_withIcon;
uint64_t m_monitorId;
int m_activeWorkspaceId;
std::string m_activeSpecialWorkspaceName;
std::vector<std::unique_ptr<Workspace>> m_workspaces;
std::vector<std::pair<Json::Value, Json::Value>> m_workspacesToCreate;
std::vector<std::string> m_workspacesToRemove;
std::vector<WindowCreationPayload> m_windowsToCreate;
std::vector<std::regex> m_ignoreWorkspaces;
std::mutex m_mutex;
const Bar& m_bar;
Gtk::Box m_box;
IPC& m_ipc;
}; };
} // namespace waybar::modules::hyprland } // namespace waybar::modules::hyprland

View File

@ -3,6 +3,7 @@
#include <fmt/chrono.h> #include <fmt/chrono.h>
#include <gtkmm/label.h> #include <gtkmm/label.h>
#include <set>
#include <unordered_map> #include <unordered_map>
#include "AModule.hpp" #include "AModule.hpp"
@ -40,6 +41,7 @@ class KeyboardState : public AModule {
struct libinput* libinput_; struct libinput* libinput_;
std::unordered_map<std::string, struct libinput_device*> libinput_devices_; std::unordered_map<std::string, struct libinput_device*> libinput_devices_;
std::set<int> binding_keys;
util::SleeperThread libinput_thread_, hotplug_thread_; util::SleeperThread libinput_thread_, hotplug_thread_;
}; };

30
include/modules/load.hpp Normal file
View File

@ -0,0 +1,30 @@
#pragma once
#include <fmt/format.h>
#include <cstdint>
#include <fstream>
#include <numeric>
#include <string>
#include <utility>
#include <vector>
#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<double, double, double> getLoad();
private:
util::SleeperThread thread_;
};
} // namespace waybar::modules

View File

@ -148,6 +148,7 @@ class Stopped : public State {
class Disconnected : public State { class Disconnected : public State {
Context* const ctx_; Context* const ctx_;
sigc::connection timer_connection_; sigc::connection timer_connection_;
int last_interval_;
public: public:
Disconnected(Context* const ctx) : ctx_{ctx} {} Disconnected(Context* const ctx) : ctx_{ctx} {}
@ -162,7 +163,7 @@ class Disconnected : public State {
Disconnected(Disconnected const&) = delete; Disconnected(Disconnected const&) = delete;
Disconnected& operator=(Disconnected const&) = delete; Disconnected& operator=(Disconnected const&) = delete;
void arm_timer(int interval) noexcept; bool arm_timer(int interval) noexcept;
void disarm_timer() noexcept; void disarm_timer() noexcept;
bool on_timer(); bool on_timer();

View File

@ -66,9 +66,9 @@ class Mpris : public ALabel {
int album_len_; int album_len_;
int title_len_; int title_len_;
int dynamic_len_; int dynamic_len_;
std::string dynamic_separator_;
std::vector<std::string> dynamic_order_;
std::vector<std::string> dynamic_prio_; std::vector<std::string> dynamic_prio_;
std::vector<std::string> dynamic_order_;
std::string dynamic_separator_;
bool truncate_hours_; bool truncate_hours_;
bool tooltip_len_limits_; bool tooltip_len_limits_;
std::string ellipsis_; std::string ellipsis_;

View File

@ -16,6 +16,8 @@
#include "util/rfkill.hpp" #include "util/rfkill.hpp"
#endif #endif
enum ip_addr_pref : uint8_t { IPV4, IPV6, IPV4_6 };
namespace waybar::modules { namespace waybar::modules {
class Network : public ALabel { class Network : public ALabel {
@ -40,6 +42,7 @@ class Network : public ALabel {
void parseEssid(struct nlattr**); void parseEssid(struct nlattr**);
void parseSignal(struct nlattr**); void parseSignal(struct nlattr**);
void parseFreq(struct nlattr**); void parseFreq(struct nlattr**);
void parseBssid(struct nlattr**);
bool associatedOrJoined(struct nlattr**); bool associatedOrJoined(struct nlattr**);
bool checkInterface(std::string name); bool checkInterface(std::string name);
auto getInfo() -> void; auto getInfo() -> void;
@ -49,7 +52,7 @@ class Network : public ALabel {
std::optional<std::pair<unsigned long long, unsigned long long>> readBandwidthUsage(); std::optional<std::pair<unsigned long long, unsigned long long>> readBandwidthUsage();
int ifid_; int ifid_;
sa_family_t family_; ip_addr_pref addr_pref_;
struct sockaddr_nl nladdr_ = {0}; struct sockaddr_nl nladdr_ = {0};
struct nl_sock* sock_ = nullptr; struct nl_sock* sock_ = nullptr;
struct nl_sock* ev_sock_ = nullptr; struct nl_sock* ev_sock_ = nullptr;
@ -69,12 +72,16 @@ class Network : public ALabel {
std::string state_; std::string state_;
std::string essid_; std::string essid_;
std::string bssid_;
bool carrier_; bool carrier_;
std::string ifname_; std::string ifname_;
std::string ipaddr_; std::string ipaddr_;
std::string ipaddr6_;
std::string gwaddr_; std::string gwaddr_;
std::string netmask_; std::string netmask_;
std::string netmask6_;
int cidr_; int cidr_;
int cidr6_;
int32_t signal_strength_dbm_; int32_t signal_strength_dbm_;
uint8_t signal_strength_; uint8_t signal_strength_;
std::string signal_strength_app_; std::string signal_strength_app_;

View File

@ -0,0 +1,52 @@
#pragma once
#include <list>
#include <mutex>
#include <string>
#include <utility>
#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<std::mutex> lockData() { return std::lock_guard(dataMutex_); }
const std::vector<Json::Value>& workspaces() const { return workspaces_; }
const std::vector<Json::Value>& windows() const { return windows_; }
const std::vector<std::string>& 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<Json::Value> workspaces_;
std::vector<Json::Value> windows_;
std::vector<std::string> keyboardLayoutNames_;
unsigned keyboardLayoutCurrent_;
util::JsonParser parser_;
std::mutex callbackMutex_;
std::list<std::pair<std::string, EventHandler*>> callbacks_;
};
inline std::unique_ptr<IPC> gIPC;
}; // namespace waybar::modules::niri

View File

@ -0,0 +1,38 @@
#pragma once
#include <string>
#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<Layout> layouts_;
unsigned current_idx_;
};
} // namespace waybar::modules::niri

View File

@ -0,0 +1,28 @@
#pragma once
#include <gtkmm/button.h>
#include <json/value.h>
#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

View File

@ -0,0 +1,30 @@
#pragma once
#include <gtkmm/button.h>
#include <json/value.h>
#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<uint64_t, Gtk::Button> buttons_;
};
} // namespace waybar::modules::niri

View File

@ -0,0 +1,48 @@
#pragma once
#include <fmt/format.h>
#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<Glib::ustring> &);
void busConnectedCb(Glib::RefPtr<Gio::AsyncResult> &r);
void getAllPropsCb(Glib::RefPtr<Gio::AsyncResult> &r);
void setPropCb(Glib::RefPtr<Gio::AsyncResult> &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<Profile> availableProfiles_;
// Points to the active profile in the profiles list
std::vector<Profile>::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<Gio::DBus::Proxy> powerProfilesProxy_;
};
} // namespace waybar::modules

View File

@ -0,0 +1,40 @@
#pragma once
#include <string>
#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 &, Gtk::Orientation, const std::string &pos);
auto update() -> void override;
void onPrivacyNodesChanged();
private:
std::list<PrivacyNodeInfo *> nodes_screenshare; // Screen is being shared
std::list<PrivacyNodeInfo *> nodes_audio_in; // Application is using the microphone
std::list<PrivacyNodeInfo *> 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::set<std::pair<PrivacyNodeType, std::string>> ignore;
bool ignore_monitor = true;
std::shared_ptr<util::PipewireBackend::PipewireBackend> backend = nullptr;
};
} // namespace waybar::modules::privacy

View File

@ -0,0 +1,48 @@
#pragma once
#include <json/value.h>
#include <string>
#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<PrivacyNodeInfo *> *nodes, Gtk::Orientation orientation,
const std::string &pos, const uint icon_size, const uint transition_duration);
enum PrivacyNodeType privacy_type;
void set_in_use(bool in_use);
private:
std::list<PrivacyNodeInfo *> *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

View File

@ -1,54 +1,27 @@
#pragma once #pragma once
#include <fmt/format.h> #include <fmt/format.h>
#include <pulse/pulseaudio.h>
#include <pulse/volume.h>
#include <algorithm> #include <algorithm>
#include <array> #include <array>
#include <memory>
#include "ALabel.hpp" #include "ALabel.hpp"
#include "util/audio_backend.hpp"
namespace waybar::modules { namespace waybar::modules {
class Pulseaudio : public ALabel { class Pulseaudio : public ALabel {
public: public:
Pulseaudio(const std::string&, const Json::Value&); Pulseaudio(const std::string&, const Json::Value&);
virtual ~Pulseaudio(); virtual ~Pulseaudio() = default;
auto update() -> void override; auto update() -> void override;
private: 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*);
bool handleScroll(GdkEventScroll* e) override; bool handleScroll(GdkEventScroll* e) override;
const std::vector<std::string> getPulseIcon() const; const std::vector<std::string> getPulseIcon() const;
pa_threaded_mainloop* mainloop_; std::shared_ptr<util::AudioBackend> backend = nullptr;
pa_mainloop_api* mainloop_api_;
pa_context* context_;
// SINK
uint32_t sink_idx_{0};
uint16_t volume_;
pa_cvolume pa_volume_;
bool muted_;
std::string port_name_;
std::string form_factor_;
std::string desc_;
std::string monitor_;
std::string current_sink_name_;
bool current_sink_running_;
// 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_;
}; };
} // namespace waybar::modules } // namespace waybar::modules

View File

@ -0,0 +1,27 @@
#pragma once
#include <memory>
#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<util::AudioBackend> backend = nullptr;
PulseaudioSliderTarget target = PulseaudioSliderTarget::Sink;
};
} // namespace waybar::modules

View File

@ -0,0 +1,43 @@
#pragma once
#include <json/json.h>
#include <spdlog/spdlog.h>
#include <string>
#include <unordered_map>
class IconManager {
public:
static IconManager& instance() {
static IconManager instance;
return instance;
}
void setIconsConfig(const Json::Value& icons_config) {
if (icons_config.isObject()) {
for (const auto& key : icons_config.getMemberNames()) {
std::string app_name = key;
const Json::Value& icon_value = icons_config[key];
if (icon_value.isString()) {
std::string icon_path = icon_value.asString();
icons_map_[app_name] = icon_path;
}
}
} else {
spdlog::warn("Invalid icon config format.");
}
}
std::string getIconForApp(const std::string& app_name) const {
auto it = icons_map_.find(app_name);
if (it != icons_map_.end()) {
return it->second;
}
return "";
}
private:
IconManager() = default;
std::unordered_map<std::string, std::string> icons_map_;
};

View File

@ -62,6 +62,7 @@ class Item : public sigc::trackable {
void proxyReady(Glib::RefPtr<Gio::AsyncResult>& result); void proxyReady(Glib::RefPtr<Gio::AsyncResult>& result);
void setProperty(const Glib::ustring& name, Glib::VariantBase& value); void setProperty(const Glib::ustring& name, Glib::VariantBase& value);
void setStatus(const Glib::ustring& value); void setStatus(const Glib::ustring& value);
void setCustomIcon(const std::string& id);
void getUpdatedProperties(); void getUpdatedProperties();
void processUpdatedProperties(Glib::RefPtr<Gio::AsyncResult>& result); void processUpdatedProperties(Glib::RefPtr<Gio::AsyncResult>& result);
void onSignal(const Glib::ustring& sender_name, const Glib::ustring& signal_name, void onSignal(const Glib::ustring& sender_name, const Glib::ustring& signal_name,
@ -76,6 +77,8 @@ class Item : public sigc::trackable {
void makeMenu(); void makeMenu();
bool handleClick(GdkEventButton* const& /*ev*/); bool handleClick(GdkEventButton* const& /*ev*/);
bool handleScroll(GdkEventScroll* const&); bool handleScroll(GdkEventScroll* const&);
bool handleMouseEnter(GdkEventCrossing* const&);
bool handleMouseLeave(GdkEventCrossing* const&);
// smooth scrolling threshold // smooth scrolling threshold
gdouble scroll_threshold_ = 0; gdouble scroll_threshold_ = 0;
@ -84,6 +87,8 @@ class Item : public sigc::trackable {
// visibility of items with Status == Passive // visibility of items with Status == Passive
bool show_passive_ = false; bool show_passive_ = false;
const Bar& bar_;
Glib::RefPtr<Gio::DBus::Proxy> proxy_; Glib::RefPtr<Gio::DBus::Proxy> proxy_;
Glib::RefPtr<Gio::Cancellable> cancellable_; Glib::RefPtr<Gio::Cancellable> cancellable_;
std::set<std::string_view> update_pending_; std::set<std::string_view> update_pending_;

View File

@ -21,7 +21,7 @@ class Language : public ALabel, public sigc::trackable {
auto update() -> void override; auto update() -> void override;
private: private:
enum class DispayedShortFlag { None = 0, ShortName = 1, ShortDescription = 1 << 1 }; enum class DisplayedShortFlag { None = 0, ShortName = 1, ShortDescription = 1 << 1 };
struct Layout { struct Layout {
std::string full_name; std::string full_name;
@ -56,8 +56,9 @@ class Language : public ALabel, public sigc::trackable {
Layout layout_; Layout layout_;
std::string tooltip_format_ = ""; std::string tooltip_format_ = "";
std::map<std::string, Layout> layouts_map_; std::map<std::string, Layout> layouts_map_;
bool hide_single_;
bool is_variant_displayed; bool is_variant_displayed;
std::byte displayed_short_flag = static_cast<std::byte>(DispayedShortFlag::None); std::byte displayed_short_flag = static_cast<std::byte>(DisplayedShortFlag::None);
util::JsonParser parser_; util::JsonParser parser_;
std::mutex mutex_; std::mutex mutex_;

View File

@ -4,7 +4,7 @@
#include <tuple> #include <tuple>
#include "AIconLabel.hpp" #include "AAppIconLabel.hpp"
#include "bar.hpp" #include "bar.hpp"
#include "client.hpp" #include "client.hpp"
#include "modules/sway/ipc/client.hpp" #include "modules/sway/ipc/client.hpp"
@ -12,7 +12,7 @@
namespace waybar::modules::sway { namespace waybar::modules::sway {
class Window : public AIconLabel, public sigc::trackable { class Window : public AAppIconLabel, public sigc::trackable {
public: public:
Window(const std::string&, const waybar::Bar&, const Json::Value&); Window(const std::string&, const waybar::Bar&, const Json::Value&);
virtual ~Window() = default; virtual ~Window() = default;
@ -25,8 +25,6 @@ class Window : public AIconLabel, public sigc::trackable {
std::tuple<std::size_t, int, int, std::string, std::string, std::string, std::string, std::string> std::tuple<std::size_t, int, int, std::string, std::string, std::string, std::string, std::string>
getFocusedNode(const Json::Value& nodes, std::string& output); getFocusedNode(const Json::Value& nodes, std::string& output);
void getTree(); void getTree();
void updateAppIconName();
void updateAppIcon();
const Bar& bar_; const Bar& bar_;
std::string window_; std::string window_;
@ -37,9 +35,6 @@ class Window : public AIconLabel, public sigc::trackable {
std::string old_app_id_; std::string old_app_id_;
std::size_t app_nb_; std::size_t app_nb_;
std::string shell_; std::string shell_;
unsigned app_icon_size_{24};
bool update_app_icon_{true};
std::string app_icon_name_;
int floating_count_; int floating_count_;
util::JsonParser parser_; util::JsonParser parser_;
std::mutex mutex_; std::mutex mutex_;

View File

@ -12,13 +12,14 @@
#include "client.hpp" #include "client.hpp"
#include "modules/sway/ipc/client.hpp" #include "modules/sway/ipc/client.hpp"
#include "util/json.hpp" #include "util/json.hpp"
#include "util/regex_collection.hpp"
namespace waybar::modules::sway { namespace waybar::modules::sway {
class Workspaces : public AModule, public sigc::trackable { class Workspaces : public AModule, public sigc::trackable {
public: public:
Workspaces(const std::string&, const waybar::Bar&, const Json::Value&); Workspaces(const std::string&, const waybar::Bar&, const Json::Value&);
virtual ~Workspaces() = default; ~Workspaces() override = default;
auto update() -> void override; auto update() -> void override;
private: private:
@ -27,22 +28,28 @@ class Workspaces : public AModule, public sigc::trackable {
R"(workspace {} "{}"; move workspace to output "{}"; workspace {} "{}")"; R"(workspace {} "{}"; move workspace to output "{}"; workspace {} "{}")";
static int convertWorkspaceNameToNum(std::string name); static int convertWorkspaceNameToNum(std::string name);
static int windowRewritePriorityFunction(std::string const& window_rule);
void onCmd(const struct Ipc::ipc_response&); void onCmd(const struct Ipc::ipc_response&);
void onEvent(const struct Ipc::ipc_response&); void onEvent(const struct Ipc::ipc_response&);
bool filterButtons(); bool filterButtons();
static bool hasFlag(const Json::Value&, const std::string&);
void updateWindows(const Json::Value&, std::string&);
Gtk::Button& addButton(const Json::Value&); Gtk::Button& addButton(const Json::Value&);
void onButtonReady(const Json::Value&, Gtk::Button&); void onButtonReady(const Json::Value&, Gtk::Button&);
std::string getIcon(const std::string&, const Json::Value&); std::string getIcon(const std::string&, const Json::Value&);
const std::string getCycleWorkspace(std::vector<Json::Value>::iterator, bool prev) const; std::string getCycleWorkspace(std::vector<Json::Value>::iterator, bool prev) const;
uint16_t getWorkspaceIndex(const std::string& name) const; uint16_t getWorkspaceIndex(const std::string& name) const;
std::string trimWorkspaceName(std::string); static std::string trimWorkspaceName(std::string);
bool handleScroll(GdkEventScroll*) override; bool handleScroll(GdkEventScroll* /*unused*/) override;
const Bar& bar_; const Bar& bar_;
std::vector<Json::Value> workspaces_; std::vector<Json::Value> workspaces_;
std::vector<std::string> high_priority_named_;
std::vector<std::string> workspaces_order_; std::vector<std::string> workspaces_order_;
Gtk::Box box_; Gtk::Box box_;
std::string m_formatWindowSeparator;
util::RegexCollection m_windowRewriteRules;
util::JsonParser parser_; util::JsonParser parser_;
std::unordered_map<std::string, Gtk::Button> buttons_; std::unordered_map<std::string, Gtk::Button> buttons_;
std::mutex mutex_; std::mutex mutex_;

View File

@ -0,0 +1,34 @@
#pragma once
#include <giomm/dbusproxy.h>
#include <string>
#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;
std::string system_state, user_state, overall_state;
uint32_t nr_failed_system, nr_failed_user, nr_failed;
std::string last_status;
Glib::RefPtr<Gio::DBus::Proxy> system_proxy, user_proxy;
void notify_cb(const Glib::ustring &sender_name, const Glib::ustring &signal_name,
const Glib::VariantContainerBase &arguments);
void RequestFailedUnits();
void RequestSystemState();
void updateData();
};
} // namespace waybar::modules

View File

@ -18,6 +18,7 @@ class Temperature : public ALabel {
private: private:
float getTemperature(); float getTemperature();
bool isCritical(uint16_t); bool isCritical(uint16_t);
bool isWarning(uint16_t);
std::string file_path_; std::string file_path_;
util::SleeperThread thread_; util::SleeperThread thread_;

View File

@ -0,0 +1,94 @@
#pragma once
#include <giomm/dbusconnection.h>
#include <gtkmm/icontheme.h>
#include <libupower-glib/upower.h>
#include <unordered_map>
#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<Gtk::IconTheme> 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<Gtk::Tooltip> &);
// DBUS variables
guint watcherID_;
Glib::RefPtr<Gio::DBus::Connection> conn_;
guint subscrID_{0u};
// UPower variables
UpClient *upClient_;
upDevice_output upDevice_; // Device to display
typedef std::unordered_map<std::string, upDevice_output> Devices;
Devices devices_;
bool upRunning_{true};
// DBus callbacks
void getConn_cb(Glib::RefPtr<Gio::AsyncResult> &result);
void onAppear(const Glib::RefPtr<Gio::DBus::Connection> &, const Glib::ustring &,
const Glib::ustring &);
void onVanished(const Glib::RefPtr<Gio::DBus::Connection> &, const Glib::ustring &);
void prepareForSleep_cb(const Glib::RefPtr<Gio::DBus::Connection> &connection,
const Glib::ustring &sender_name, const Glib::ustring &object_path,
const Glib::ustring &interface_name, const Glib::ustring &signal_name,
const Glib::VariantContainerBase &parameters);
// UPower callbacks
static void deviceAdded_cb(UpClient *client, UpDevice *device, gpointer data);
static void deviceRemoved_cb(UpClient *client, const gchar *objectPath, gpointer data);
static void deviceNotify_cb(UpDevice *device, GParamSpec *pspec, gpointer user_data);
// UPower secondary functions
void getUpDeviceInfo(upDevice_output &upDevice_);
};
} // namespace waybar::modules

View File

@ -1,80 +0,0 @@
#pragma once
#include <libupower-glib/upower.h>
#include <iostream>
#include <map>
#include <string>
#include <unordered_map>
#include "ALabel.hpp"
#include "glibconfig.h"
#include "gtkmm/box.h"
#include "gtkmm/image.h"
#include "gtkmm/label.h"
#include "modules/upower/upower_tooltip.hpp"
namespace waybar::modules::upower {
class UPower : public AModule {
public:
UPower(const std::string &, const Json::Value &);
virtual ~UPower();
auto update() -> void override;
private:
typedef std::unordered_map<std::string, UpDevice *> Devices;
const std::string DEFAULT_FORMAT = "{percentage}";
const std::string DEFAULT_FORMAT_ALT = "{percentage} {time}";
static void deviceAdded_cb(UpClient *client, UpDevice *device, gpointer data);
static void deviceRemoved_cb(UpClient *client, const gchar *objectPath, gpointer data);
static void deviceNotify_cb(UpDevice *device, GParamSpec *pspec, gpointer user_data);
static void 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);
static void upowerAppear(GDBusConnection *conn, const gchar *name, const gchar *name_owner,
gpointer data);
static void upowerDisappear(GDBusConnection *connection, const gchar *name, gpointer user_data);
void removeDevice(const gchar *objectPath);
void addDevice(UpDevice *device);
void setDisplayDevice();
void resetDevices();
void removeDevices();
bool show_tooltip_callback(int, int, bool, const Glib::RefPtr<Gtk::Tooltip> &tooltip);
bool handleToggle(GdkEventButton *const &) override;
std::string timeToString(gint64 time);
const std::string getDeviceStatus(UpDeviceState &state);
Gtk::Box box_;
Gtk::Image icon_;
Gtk::Label label_;
// Config
bool hideIfEmpty = true;
bool tooltip_enabled = true;
uint tooltip_spacing = 4;
uint tooltip_padding = 4;
uint iconSize = 20;
std::string format = DEFAULT_FORMAT;
std::string format_alt = DEFAULT_FORMAT_ALT;
Devices devices;
std::mutex m_Mutex;
UpClient *client;
UpDevice *displayDevice;
guint login1_id;
GDBusConnection *login1_connection;
UPowerTooltip *upower_tooltip;
std::string lastStatus;
bool showAltText;
bool upowerRunning;
guint upowerWatcher_id;
std::string nativePath_;
};
} // namespace waybar::modules::upower

View File

@ -1,32 +0,0 @@
#pragma once
#include <libupower-glib/upower.h>
#include <unordered_map>
#include "gtkmm/box.h"
#include "gtkmm/label.h"
#include "gtkmm/window.h"
namespace waybar::modules::upower {
class UPowerTooltip : public Gtk::Window {
private:
typedef std::unordered_map<std::string, UpDevice*> Devices;
const std::string getDeviceIcon(UpDeviceKind& kind);
Gtk::Box* contentBox;
uint iconSize;
uint tooltipSpacing;
uint tooltipPadding;
public:
UPowerTooltip(uint iconSize, uint tooltipSpacing, uint tooltipPadding);
virtual ~UPowerTooltip();
uint updateTooltip(Devices& devices);
};
} // namespace waybar::modules::upower

View File

@ -17,18 +17,23 @@ class Wireplumber : public ALabel {
auto update() -> void override; auto update() -> void override;
private: private:
void loadRequiredApiModules(); void asyncLoadRequiredApiModules();
void prepare(); void prepare(waybar::modules::Wireplumber* self);
void activatePlugins(); void activatePlugins();
static void updateVolume(waybar::modules::Wireplumber* self, uint32_t id); static void updateVolume(waybar::modules::Wireplumber* self, uint32_t id);
static void updateNodeName(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 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 onObjectManagerInstalled(waybar::modules::Wireplumber* self);
static void onMixerChanged(waybar::modules::Wireplumber* self, uint32_t id); static void onMixerChanged(waybar::modules::Wireplumber* self, uint32_t id);
static void onDefaultNodesApiChanged(waybar::modules::Wireplumber* self); static void onDefaultNodesApiChanged(waybar::modules::Wireplumber* self);
bool handleScroll(GdkEventScroll* e) override; bool handleScroll(GdkEventScroll* e) override;
static std::list<waybar::modules::Wireplumber*> modules;
WpCore* wp_core_; WpCore* wp_core_;
GPtrArray* apis_; GPtrArray* apis_;
WpObjectManager* om_; WpObjectManager* om_;
@ -41,6 +46,7 @@ class Wireplumber : public ALabel {
double min_step_; double min_step_;
uint32_t node_id_{0}; uint32_t node_id_{0};
std::string node_name_; std::string node_name_;
gchar* type_;
}; };
} // namespace waybar::modules } // namespace waybar::modules

View File

@ -24,6 +24,10 @@
namespace waybar::modules::wlr { namespace waybar::modules::wlr {
struct widget_geometry {
int x, y, w, h;
};
class Taskbar; class Taskbar;
class Task { class Task {
@ -42,6 +46,7 @@ class Task {
}; };
// made public so TaskBar can reorder based on configuration. // made public so TaskBar can reorder based on configuration.
Gtk::Button button; Gtk::Button button;
struct widget_geometry minimize_hint;
private: private:
static uint32_t global_id; static uint32_t global_id;
@ -82,6 +87,8 @@ class Task {
private: private:
std::string repr() const; std::string repr() const;
std::string state_string(bool = false) const; std::string state_string(bool = false) const;
void set_minimize_hint();
void on_button_size_allocated(Gtk::Allocation &alloc);
void set_app_info_from_app_id_list(const std::string &app_id_list); void set_app_info_from_app_id_list(const std::string &app_id_list);
bool image_load_icon(Gtk::Image &image, const Glib::RefPtr<Gtk::IconTheme> &icon_theme, bool image_load_icon(Gtk::Image &image, const Glib::RefPtr<Gtk::IconTheme> &icon_theme,
Glib::RefPtr<Gio::DesktopAppInfo> app_info, int size); Glib::RefPtr<Gio::DesktopAppInfo> app_info, int size);

View File

@ -0,0 +1,98 @@
#pragma once
#include <json/value.h>
#include <pulse/context.h>
#include <pulse/introspect.h>
#include <pulse/thread-mainloop.h>
#include <pulse/volume.h>
#include <functional>
#include <memory>
#include <string>
#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<std::string> ignored_sinks_;
std::function<void()> 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<AudioBackend> getInstance(std::function<void()> on_updated_cb = NOOP);
AudioBackend(std::function<void()> 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::util

View File

@ -0,0 +1,10 @@
#pragma once
#include "AModule.hpp"
namespace waybar::util {
const static auto NOOP = []() {};
enum class ChangeType : char { Increase, Decrease };
} // namespace waybar::util

View File

@ -0,0 +1,87 @@
#pragma once
#include <libudev.h>
#include <spdlog/spdlog.h>
#include <chrono>
#include <mutex>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
#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<std::mutex> 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<void()> 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<bool>(login_proxy_); }
static const BacklightDevice *best_device(const std::vector<BacklightDevice> &devices,
std::string_view);
std::vector<BacklightDevice> devices_;
std::mutex udev_thread_mutex_;
private:
void set_brightness_internal(const std::string &device_name, int brightness, int max_brightness);
std::function<void()> on_updated_cb_;
std::chrono::milliseconds polling_interval_;
std::optional<BacklightDevice> previous_best_;
// thread must destruct before shared data
util::SleeperThread udev_thread_;
Glib::RefPtr<Gio::DBus::Proxy> login_proxy_;
static constexpr int EPOLL_MAX_EVENTS = 16;
};
} // namespace waybar::util

View File

@ -66,7 +66,7 @@ inline int close(FILE* fp, pid_t pid) {
return stat; return stat;
} }
inline FILE* open(const std::string& cmd, int& pid) { inline FILE* open(const std::string& cmd, int& pid, const std::string& output_name) {
if (cmd == "") return nullptr; if (cmd == "") return nullptr;
int fd[2]; int fd[2];
// Open the pipe with the close-on-exec flag set, so it will not be inherited // Open the pipe with the close-on-exec flag set, so it will not be inherited
@ -109,6 +109,9 @@ inline FILE* open(const std::string& cmd, int& pid) {
::close(fd[0]); ::close(fd[0]);
dup2(fd[1], 1); dup2(fd[1], 1);
setpgid(child_pid, child_pid); 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); execlp("/bin/sh", "sh", "-c", cmd.c_str(), (char*)0);
exit(0); exit(0);
} else { } else {
@ -118,9 +121,9 @@ inline FILE* open(const std::string& cmd, int& pid) {
return fdopen(fd[0], "r"); return fdopen(fd[0], "r");
} }
inline struct res exec(const std::string& cmd) { inline struct res exec(const std::string& cmd, const std::string& output_name) {
int pid; int pid;
auto fp = command::open(cmd, pid); auto fp = command::open(cmd, pid, output_name);
if (!fp) return {-1, ""}; if (!fp) return {-1, ""};
auto output = command::read(fp); auto output = command::read(fp);
auto stat = command::close(fp, pid); auto stat = command::close(fp, pid);
@ -129,7 +132,7 @@ inline struct res exec(const std::string& cmd) {
inline struct res execNoRead(const std::string& cmd) { inline struct res execNoRead(const std::string& cmd) {
int pid; int pid;
auto fp = command::open(cmd, pid); auto fp = command::open(cmd, pid, "");
if (!fp) return {-1, ""}; if (!fp) return {-1, ""};
auto stat = command::close(fp, pid); auto stat = command::close(fp, pid);
return {WEXITSTATUS(stat), ""}; return {WEXITSTATUS(stat), ""};

View File

@ -0,0 +1,49 @@
#pragma once
#include <functional>
#include <string>
#include <unordered_map>
#include <vector>
#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<void()> callback);
virtual ~CssReloadHelper() = default;
virtual void monitorChanges();
protected:
std::vector<std::string> parseImports(const std::string& cssFile);
void parseImports(const std::string& cssFile, std::unordered_map<std::string, bool>& imports);
void watchFiles(const std::vector<std::string>& 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<Gio::File> const& file,
Glib::RefPtr<Gio::File> const& other_type,
Gio::FileMonitorEvent event_type);
private:
std::string m_cssFile;
std::function<void()> m_callback;
std::vector<std::tuple<Glib::RefPtr<Gio::FileMonitor>>> m_fileMonitors;
};
} // namespace waybar

View File

@ -1,34 +1,48 @@
#pragma once #pragma once
#include <fmt/format.h> #include <chrono>
#if HAVE_CHRONO_TIMEZONES #if HAVE_CHRONO_TIMEZONES
#include <chrono>
#include <format> #include <format>
/* Compatibility layer for <date/tz.h> on top of C++20 <chrono> */
namespace date {
using namespace std::chrono;
namespace literals {
using std::chrono::last;
}
inline auto format(const std::string& spec, const auto& ztime) {
return spec.empty() ? "" : std::vformat("{:L" + spec + "}", std::make_format_args(ztime));
}
inline auto format(const std::locale& loc, const std::string& spec, const auto& ztime) {
return spec.empty() ? "" : std::vformat(loc, "{:L" + spec + "}", std::make_format_args(ztime));
}
} // namespace date
#else #else
#include <date/tz.h> #include <date/tz.h>
#include <fmt/format.h>
#include <regex>
#endif #endif
// Date
namespace date {
#if HAVE_CHRONO_TIMEZONES
using namespace std::chrono;
using std::format;
#else
using system_clock = std::chrono::system_clock;
using seconds = std::chrono::seconds;
template <typename T>
inline auto format(const char* spec, const T& arg) {
return date::format(std::regex_replace(spec, std::regex("\\{:L|\\}"), ""), arg);
}
template <typename T>
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 <typename Duration, typename TimeZonePtr> template <typename Duration, typename TimeZonePtr>
struct fmt::formatter<date::zoned_time<Duration, TimeZonePtr>> { struct fmt::formatter<date::zoned_time<Duration, TimeZonePtr>> {
std::string_view specs; std::string_view specs;
@ -50,7 +64,7 @@ struct fmt::formatter<date::zoned_time<Duration, TimeZonePtr>> {
} }
template <typename FormatContext> template <typename FormatContext>
auto format(const date::zoned_time<Duration, TimeZonePtr>& ztime, FormatContext& ctx) { auto format(const date::zoned_time<Duration, TimeZonePtr>& ztime, FormatContext& ctx) const {
if (ctx.locale()) { if (ctx.locale()) {
const auto loc = ctx.locale().template get<std::locale>(); const auto loc = ctx.locale().template get<std::locale>();
return fmt::format_to(ctx.out(), "{}", date::format(loc, fmt::to_string(specs), ztime)); return fmt::format_to(ctx.out(), "{}", date::format(loc, fmt::to_string(specs), ztime));
@ -58,3 +72,4 @@ struct fmt::formatter<date::zoned_time<Duration, TimeZonePtr>> {
return fmt::format_to(ctx.out(), "{}", date::format(fmt::to_string(specs), ztime)); return fmt::format_to(ctx.out(), "{}", date::format(fmt::to_string(specs), ztime));
} }
}; };
#endif

19
include/util/enum.hpp Normal file
View File

@ -0,0 +1,19 @@
#pragma once
#include <map>
#include <stdexcept>
#include <string>
namespace waybar::util {
template <typename EnumType>
struct EnumParser {
public:
EnumParser();
~EnumParser();
EnumType parseStringToEnum(const std::string& str,
const std::map<std::string, EnumType>& enumMap);
};
} // namespace waybar::util

View File

@ -6,7 +6,7 @@
class pow_format { class pow_format {
public: public:
pow_format(long long val, std::string&& unit, bool binary = false) pow_format(long long val, std::string&& unit, bool binary = false)
: val_(val), unit_(unit), binary_(binary){}; : val_(val), unit_(unit), binary_(binary) {};
long long val_; long long val_;
std::string unit_; std::string unit_;
@ -45,7 +45,7 @@ struct formatter<pow_format> {
} }
template <class FormatContext> template <class FormatContext>
auto format(const pow_format& s, FormatContext& ctx) -> decltype(ctx.out()) { auto format(const pow_format& s, FormatContext& ctx) const -> decltype(ctx.out()) {
const char* units[] = {"", "k", "M", "G", "T", "P", nullptr}; const char* units[] = {"", "k", "M", "G", "T", "P", nullptr};
auto base = s.binary_ ? 1024ull : 1000ll; auto base = s.binary_ ? 1024ull : 1000ll;
@ -92,8 +92,8 @@ struct formatter<pow_format> {
template <> template <>
struct formatter<Glib::ustring> : formatter<std::string> { struct formatter<Glib::ustring> : formatter<std::string> {
template <typename FormatContext> template <typename FormatContext>
auto format(const Glib::ustring& value, FormatContext& ctx) { auto format(const Glib::ustring& value, FormatContext& ctx) const {
return formatter<std::string>::format(value, ctx); return formatter<std::string>::format(static_cast<std::string>(value), ctx);
} }
}; };
} // namespace fmt } // namespace fmt

View File

@ -10,5 +10,7 @@ class DefaultGtkIconThemeWrapper {
public: public:
static bool has_icon(const std::string&); static bool has_icon(const std::string&);
static Glib::RefPtr<Gdk::Pixbuf> load_icon(const char*, int, Gtk::IconLookupFlags); static Glib::RefPtr<Gdk::Pixbuf> load_icon(
const char*, int, Gtk::IconLookupFlags,
Glib::RefPtr<Gtk::StyleContext> style = Glib::RefPtr<Gtk::StyleContext>());
}; };

View File

@ -3,6 +3,12 @@
#include <fmt/ostream.h> #include <fmt/ostream.h>
#include <json/json.h> #include <json/json.h>
#include <algorithm>
#include <codecvt>
#include <iostream>
#include <locale>
#include <regex>
#if (FMT_VERSION >= 90000) #if (FMT_VERSION >= 90000)
template <> template <>
@ -12,25 +18,30 @@ struct fmt::formatter<Json::Value> : ostream_formatter {};
namespace waybar::util { namespace waybar::util {
struct JsonParser { class JsonParser {
JsonParser() {} public:
JsonParser() = default;
const Json::Value parse(const std::string& data) const { Json::Value parse(const std::string& jsonStr) {
Json::Value root(Json::objectValue); Json::Value root;
if (data.empty()) {
return 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);
} }
std::unique_ptr<Json::CharReader> const reader(builder_.newCharReader());
std::string err;
bool res = reader->parse(data.c_str(), data.c_str() + data.size(), &root, &err);
if (!res) throw std::runtime_error(err);
return root; return root;
} }
~JsonParser() = default;
private: private:
Json::CharReaderBuilder builder_; 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 } // namespace waybar::util

View File

@ -0,0 +1,45 @@
#pragma once
#include <pipewire/pipewire.h>
#include <unordered_map>
#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<void> privacy_nodes_changed_signal_event;
std::unordered_map<uint32_t, PrivacyNodeInfo*> privacy_nodes;
std::mutex mutex_;
static std::shared_ptr<PipewireBackend> 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

View File

@ -0,0 +1,46 @@
#pragma once
#include <pipewire/pipewire.h>
#include <string>
#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;
bool is_monitor = false;
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

36
include/util/portal.hpp Normal file
View File

@ -0,0 +1,36 @@
#include <giomm/dbusproxy.h>
#include <string>
#include "fmt/format.h"
namespace waybar {
enum class Appearance {
UNKNOWN = 0,
DARK = 1,
LIGHT = 2,
};
class Portal : private Gio::DBus::Proxy {
public:
Portal();
void refreshAppearance();
Appearance getAppearance();
typedef sigc::signal<void, Appearance> 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<waybar::Appearance> : formatter<fmt::string_view> {
// parse is inherited from formatter<string_view>.
auto format(waybar::Appearance c, format_context& ctx) const;
};

View File

@ -4,6 +4,6 @@
namespace waybar::util { namespace waybar::util {
// Get a signal emited with value true when entering sleep, and false when exiting // Get a signal emitted with value true when entering sleep, and false when exiting
SafeSignal<bool>& prepare_for_sleep(); SafeSignal<bool>& prepare_for_sleep();
} // namespace waybar::util } // namespace waybar::util

View File

@ -0,0 +1,53 @@
#pragma once
#include <json/json.h>
#include <functional>
#include <regex>
#include <string>
#include <utility>
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<Rule> rules;
std::map<std::string, std::string> 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<int(std::string&)>& 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

View File

@ -5,4 +5,6 @@
namespace waybar::util { namespace waybar::util {
std::string rewriteString(const std::string&, const Json::Value&); 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

View File

@ -0,0 +1,21 @@
#pragma once
#include <utility>
namespace waybar::util {
template <typename Func>
class ScopeGuard {
public:
explicit ScopeGuard(Func&& exit_function) : f{std::forward<Func>(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

View File

@ -58,10 +58,22 @@ class SleeperThread {
bool isRunning() const { return do_run_; } 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) { auto sleep_for(std::chrono::system_clock::duration dur) {
std::unique_lock lk(mutex_); std::unique_lock lk(mutex_);
CancellationGuard cancel_lock; CancellationGuard cancel_lock;
return condvar_.wait_for(lk, dur, [this] { return signal_ || !do_run_; }); 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( auto sleep_until(
@ -95,6 +107,7 @@ class SleeperThread {
} }
~SleeperThread() { ~SleeperThread() {
connection_.disconnect();
stop(); stop();
if (thread_.joinable()) { if (thread_.joinable()) {
thread_.join(); thread_.join();

View File

@ -1,5 +1,6 @@
#pragma once #pragma once
#include <iostream>
#include <string> #include <string>
const std::string WHITESPACE = " \n\r\t\f\v"; const std::string WHITESPACE = " \n\r\t\f\v";
@ -15,3 +16,10 @@ inline std::string rtrim(const std::string& s) {
} }
inline std::string trim(const std::string& s) { return rtrim(ltrim(s)); } 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;
}

View File

@ -0,0 +1,93 @@
waybar-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;
}
```

View File

@ -25,16 +25,20 @@ The *backlight* module displays the current backlight level.
The maximum length in characters the module should display. The maximum length in characters the module should display.
*min-length*: ++ *min-length*: ++
typeof: integer ++ typeof: integer ++
The minimum length in characters the module should take up. The minimum length in characters the module should accept.
*align*: ++ *align*: ++
typeof: float ++ typeof: float ++
The alignment of the text, where 0 is left-aligned and 1 is right-aligned. If the module is rotated, it will follow the flow of the text. 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*: ++ *rotate*: ++
typeof: integer ++ typeof: integer ++
Positive value to rotate the text label. Positive value to rotate the text label (in 90 degree increments).
*states*: ++ *states*: ++
typeof: object ++ typeof: object ++
@ -46,11 +50,11 @@ The *backlight* module displays the current backlight level.
*on-click-middle*: ++ *on-click-middle*: ++
typeof: string ++ typeof: string ++
Command to execute when middle-clicked on the module using mousewheel. Command to execute when middle-clicked on the module using mouse scroll wheel.
*on-click-right*: ++ *on-click-right*: ++
typeof: string ++ typeof: string ++
Command to execute when the module is right clicked. Command to execute when the module is right-clicked.
*on-update*: ++ *on-update*: ++
typeof: string ++ typeof: string ++
@ -75,15 +79,38 @@ The *backlight* module displays the current backlight level.
*scroll-step*: ++ *scroll-step*: ++
typeof: float ++ typeof: float ++
default: 1.0 ++ default: 1.0 ++
The speed in which to change the brightness when scrolling. 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: # EXAMPLE:
``` ```
"backlight": { "backlight": {
"device": "intel_backlight", "device": "intel_backlight",
"format": "{percent}% {icon}", "format": "{percent}% {icon}",
"format-icons": ["", ""] "format-icons": ["", ""]
} }
``` ```

Some files were not shown because too many files have changed in this diff Show More