Compare commits

...

265 Commits

Author SHA1 Message Date
Alexis Rouillard
2f94435014 Merge pull request #4789 from xander1421/fix/json-type-check-crash
fix(json): use local CharReaderBuilder for thread safety
2026-01-25 21:59:41 +01:00
xander1421
1639dec7d8 fix(json): use local CharReaderBuilder for thread safety 2026-01-24 23:40:07 +02:00
Alexis Rouillard
b4854f96a3 Merge pull request #4766 from zjeffer/fix/zjeffer/persistent-special-workspaces
hyprland/workspaces: don't show persistent special workspaces if show-special is disabled
2026-01-14 18:27:30 +01:00
zjeffer
8f5fc990a5 hyprland/workspaces: don't show persistent special workspaces if show-special is disabled 2026-01-10 13:29:40 +01:00
Alexis Rouillard
a02180a815 Merge pull request #4739 from LorenzBischof/man-reverse-mouse-scrolling
docs: add missing reverse-mouse-scrolling to pulseaudio module man page
2026-01-09 20:02:15 +01:00
Alexis Rouillard
af7eebba5e Merge pull request #4745 from cartok/docs/arch-update-readme
docs(arch): install build deps as deps to keep system clean
2026-01-09 20:01:17 +01:00
Alexis Rouillard
479ea9f3e8 Merge pull request #4746 from cartok/chore/maintainance
chore: update .gitingore
2026-01-09 20:01:02 +01:00
Alexis Rouillard
f990486a40 Merge pull request #4748 from Alexays/update_flake_lock_action
flake.lock: Update
2026-01-09 20:00:50 +01:00
github-actions[bot]
d0f5fab52b flake.lock: Update
Flake lock file updates:

• Updated input 'flake-compat':
    'github:edolstra/flake-compat/f387cd2afec9419c8ee37694406ca490c3f34ee5?narHash=sha256-XKUZz9zewJNUj46b4AJdiRZJAvSZ0Dqj2BNfXvFlJC4%3D' (2025-10-27)
  → 'github:edolstra/flake-compat/5edf11c44bc78a0d334f6334cdaf7d60d732daab?narHash=sha256-vNpUSpF5Nuw8xvDLj2KCwwksIbjua2LZCqhV1LNRDns%3D' (2025-12-29)
• Updated input 'nixpkgs':
    'github:NixOS/nixpkgs/2fad6eac6077f03fe109c4d4eb171cf96791faa4?narHash=sha256-sKoIWfnijJ0%2B9e4wRvIgm/HgE27bzwQxcEmo2J/gNpI%3D' (2025-11-27)
  → 'github:NixOS/nixpkgs/c0b0e0fddf73fd517c3471e546c0df87a42d53f4?narHash=sha256-coBu0ONtFzlwwVBzmjacUQwj3G%2BlybcZ1oeNSQkgC0M%3D' (2025-12-28)
2026-01-01 00:14:44 +00:00
Dennis Weiershaeuser
a05e6c6f74 chore: update .gitingore 2025-12-31 18:18:04 +01:00
Dennis Weiershaeuser
99867005a0 docs(arch): install build deps as deps to keep system clean 2025-12-31 13:43:21 +01:00
LorenzBischof
959f41ca9c docs: add missing reverse-mouse-scrolling to pulseaudio module man page 2025-12-30 12:30:30 +01:00
Alexis Rouillard
06484547d1 Merge pull request #4677 from mliszcz/remove-window-format
fix(sway/workspaces): window-rewrite: do not check for window-format
2025-12-28 23:12:44 +01:00
Alexis Rouillard
46a6f60138 Merge pull request #4728 from xav-ie/fix-cava-config
fix-cava-config
2025-12-28 23:11:05 +01:00
Alexis Rouillard
83a6998fcb Merge pull request #4708 from khaneliman/cava
nix: bump cava again
2025-12-28 21:50:21 +01:00
Alexis Rouillard
386036a67a Merge pull request #4710 from LukashonakV/cavaMan
cava man
2025-12-28 21:50:04 +01:00
Xavier Ruiz
e3186abdce fix(cava): handle all output methods in frontend
Default to raw Cava module for non-GLSL output methods.
Fixes "Unknown module" error when no cava_config is specified.
2025-12-27 14:52:28 -05:00
Viktar Lukashonak
c8c3287be3 cava man 2025-12-20 15:35:20 +03:00
Austin Horstman
601b5f0241 nix: bump cava again
Signed-off-by: Austin Horstman <khaneliman12@gmail.com>
2025-12-18 23:47:01 -06:00
Alexis Rouillard
97eb60677e Merge pull request #4616 from schmop/battery-plugging-instant-updates
2. Try: Make battery module update on plugging/unplugging again (refs #2519)
2025-12-18 19:11:18 +01:00
Alexis Rouillard
3d0b942956 Merge pull request #4689 from ospafford/feat-dwl_tag_state
feat(dwl/tags): add empty tag option
2025-12-18 19:09:39 +01:00
Alexis Rouillard
c3d29b1185 Merge branch 'master' into battery-plugging-instant-updates 2025-12-18 19:04:31 +01:00
Alexis Rouillard
c6844781ea Merge pull request #4671 from touero/dev
Fix example error about update moudle by signal in man page
2025-12-18 19:03:11 +01:00
Alexis Rouillard
c1218fa889 Merge pull request #4646 from gszy/swap-abused
modules: memory: fix fully utilized swap percentage calculation
2025-12-18 19:02:47 +01:00
Alexis Rouillard
11c4e55376 Merge pull request #4591 from rrrnld/fix/multiple-batteries
Improve multiple battery support
2025-12-18 19:02:31 +01:00
Alexis Rouillard
6b05d73a64 Merge pull request #4589 from cebem1nt/master
fix: crash on group scrolling #4510
2025-12-18 19:01:15 +01:00
Alexis Rouillard
374ccbb878 Merge pull request #4705 from rwwiv/fix/duplicate-layers-on-monitor-hotplug
fix: prevent duplicate layer surfaces on monitor hotplug
2025-12-18 19:00:48 +01:00
Alexis Rouillard
d012de3cde Merge pull request #4682 from LukashonakV/cavaGLSL
Cava GLSL
2025-12-18 18:59:27 +01:00
Alexis Rouillard
7ecad3229d Merge pull request #4650 from BartiX259/master
fix(docs): pulseaudio man page example
2025-12-18 18:59:01 +01:00
Alexis Rouillard
278e8822ff Merge pull request #4686 from marvelpokemaster/fix-wireplumber-init-order
fix(wireplumber): reorder initializer list to match header and fix -Wreorder
2025-12-18 18:58:10 +01:00
Alexis Rouillard
a23cef457f Merge pull request #4615 from Alexays/update_flake_lock_action
flake.lock: Update
2025-12-18 18:57:57 +01:00
Will Wernert
a9ef11a2b3 fix: prevent duplicate layer surfaces on monitor hotplug
The monitor signal handlers (signal_monitor_added, signal_monitor_removed)
were never disconnected during SIGUSR2 reload. Each reload accumulated
additional handlers, causing multiple layer surfaces to be created when
monitors were hotplugged.

This fix:
- Stores signal connections as class members
- Disconnects them before reconnecting in bindInterfaces()
- Clears stale outputs_ on reload
2025-12-17 22:17:35 -05:00
Owen Spafford
07cb2c02d2 feat(dwl/tags): add empty tag option
Added option in the `dwl/tags` to theme empty tags (i.e. tags without any clients) in `style.css` using
`#tags button.empty`.

Signed-off-by: ospafford <ospafford@gmail.com>
2025-12-09 07:28:18 -08:00
Viktar Lukashonak
e03119fe94 Factory. cava_frontend 2025-12-09 18:13:45 +03:00
marvelpokemaster
5ee3bd5325 fix(wireplumber): reorder initializer list to match header and fix -Wreorder warnings 2025-12-08 01:44:19 +05:30
Viktar Lukashonak
3773021546 cavaGLSL 2025-12-07 23:08:55 +03:00
Viktar Lukashonak
52f4db1154 Moving GTK dispatcher into frontend 2025-12-05 10:04:52 +03:00
mliszcz
e362550e27 fix(sway/workspaces): window-rewrite: do not check for window-format
Remove check for unused window-format option.

Fixes #3797.
2025-12-02 17:19:44 +01:00
github-actions[bot]
cb0ee665a3 flake.lock: Update
Flake lock file updates:

• Updated input 'flake-compat':
    'github:edolstra/flake-compat/9100a0f413b0c601e0533d1d94ffd501ce2e7885?narHash=sha256-CIVLLkVgvHYbgI2UpXvIIBJ12HWgX%2BfjA8Xf8PUmqCY%3D' (2025-05-12)
  → 'github:edolstra/flake-compat/f387cd2afec9419c8ee37694406ca490c3f34ee5?narHash=sha256-XKUZz9zewJNUj46b4AJdiRZJAvSZ0Dqj2BNfXvFlJC4%3D' (2025-10-27)
• Updated input 'nixpkgs':
    'github:NixOS/nixpkgs/5e2a59a5b1a82f89f2c7e598302a9cacebb72a67?narHash=sha256-K5Osef2qexezUfs0alLvZ7nQFTGS9DL2oTVsIXsqLgs%3D' (2025-10-19)
  → 'github:NixOS/nixpkgs/2fad6eac6077f03fe109c4d4eb171cf96791faa4?narHash=sha256-sKoIWfnijJ0%2B9e4wRvIgm/HgE27bzwQxcEmo2J/gNpI%3D' (2025-11-27)
2025-12-01 00:15:02 +00:00
touero
e189649c33 docs(custom): fix example error about update moudle by signal 2025-11-29 17:29:52 +08:00
Viktar Lukashonak
13519ca5bf cava. nonsafe thread.= & cava bump 2025-11-26 13:26:32 +03:00
BartiX259
097c00c7bd fix(docs): pulseaudio man page example
The example configuration in the man page used 'headphones' and 'handsfree' as keys for format-icons. The correct keys are 'headphone' and 'hands-free'.
2025-11-22 20:09:34 +01:00
Grzegorz Szymaszek
73808dfacc modules: memory: fix fully utilized swap percentage calculation
Do calculate used swap percentage even if swapfree is 0, otherwise
reported used_swap_percentage would be 0, even though it should be 100.

Signed-off-by: Grzegorz Szymaszek <gszymaszek@short.pl>
2025-11-18 11:50:04 +01:00
schmop
ce1da5a178 Make udev_deleter not linux-only and fix freebsd build 2025-11-01 10:57:18 +01:00
schmop
4e25871655 Reapply "Make battery module update on plugging/unplugging again (refs #2519)"
This reverts commit bb2c67ebad.
2025-10-31 13:43:36 +01:00
arne
ca62481dc9 fix: default weighted average to true 2025-10-26 06:44:53 +01:00
arne
b701d7f70b docs: add information about weighted-average config option 2025-10-26 06:34:04 +01:00
cebem1nt
68cbb507d9 fixing crash on group scrolling 2025-10-24 21:57:58 -03:00
Alexis Rouillard
161367d961 Merge pull request #4579 from khaneliman/freebsd
fix(clock): fix freebsd compatibility
2025-10-23 09:36:19 +02:00
Alexis Rouillard
a62455e1b9 Merge pull request #4578 from khaneliman/fmt
fix(subprojects): fmt hash mismatch
2025-10-23 09:35:49 +02:00
Alexis Rouillard
588c344c8a Merge pull request #4577 from khaneliman/cava
fix(nix): bump cava and fix nix build
2025-10-23 09:35:39 +02:00
Austin Horstman
bf0ccfd90c fix(clock): fix freebsd compatibility
Recently introduced for ISO 8601 calendar compatibility. But, lib
differences causing the explicit type to break freebsd.

Signed-off-by: Austin Horstman <khaneliman12@gmail.com>
2025-10-21 23:07:04 -05:00
Austin Horstman
8b0a82ad34 fix(subprojects): fmt hash mismatch
Failing ci for multiple runners

Signed-off-by: Austin Horstman <khaneliman12@gmail.com>
2025-10-21 22:56:33 -05:00
Austin Horstman
37ac2daac8 flake.lock: update
Signed-off-by: Austin Horstman <khaneliman12@gmail.com>
2025-10-21 22:08:57 -05:00
Austin Horstman
97682a1332 nix: bump cava
Signed-off-by: Austin Horstman <khaneliman12@gmail.com>
2025-10-21 22:08:57 -05:00
Austin Horstman
4beb7ddac7 nix: remove useless parens
Signed-off-by: Austin Horstman <khaneliman12@gmail.com>
2025-10-19 17:35:07 -05:00
Alexis Rouillard
84ec25bbeb Merge pull request #4551 from LukashonakV/cavaBump
cava bump & fixing memory leaks
2025-10-19 13:38:58 +02:00
Alexis Rouillard
b475399a22 Merge pull request #4541 from aanderse/master
backlight: gracefully handle a null epoll device
2025-10-19 13:38:39 +02:00
Alexis Rouillard
15a503ae21 Merge pull request #4546 from kosa12/fix/fmt-version
fix: FMT version update from 11.0.2 to 12.0.0
2025-10-19 13:38:15 +02:00
Alexis Rouillard
46d3e80bce Merge pull request #4559 from carljustineoyales/chore/update-pulseaudio-slider-module
fix(pulseaudio-slider): Use `background` in CSS example
2025-10-19 13:38:03 +02:00
Alexis Rouillard
9221508e51 Merge pull request #4560 from NicolasBuchin/fix-css-memory-leak
fix: resolve memory leak by removing old CSS provider before reloading CSS styles
2025-10-19 13:37:48 +02:00
NicolasBuchin
9d37dedb57 fix: resolve memory leak by removing old CSS provider before reloading styles 2025-10-16 10:04:12 +02:00
carljustineoyales
6021261383 fix(pulseaudio-slider): Use background in CSS example
The `background-color` property does not work as expected for the slider. Using the `background` shorthand property correctly applies the color.
2025-10-15 20:47:35 +08:00
Viktar Lukashonak
966da11f3b cava bump & fixing memory leaks 2025-10-12 14:53:49 +03:00
Kosa Matyas
7add8b2726 fix: FMT version update from 11.0.2 to 12.0.0 2025-10-10 19:40:43 +03:00
Aaron Andersen
bef35e48fe backlight: gracefully handle a null epoll device 2025-10-09 20:52:51 -04:00
Alex
559079e9a6 fix: lint 2025-10-05 10:56:24 +02:00
Alexis Rouillard
0c41cf47c2 Merge pull request #4359 from zjeffer/fix/zjeffer/thread-sanitizer-warning
Fix Hyprland IPC thread sanitizer warning, other IPC & general fixes
2025-10-05 10:56:02 +02:00
Alexis Rouillard
a16d53b30d Merge branch 'master' into fix/zjeffer/thread-sanitizer-warning 2025-10-05 10:51:47 +02:00
Alex
151cf54532 fix: lint 2025-10-05 09:58:34 +02:00
Alexis Rouillard
b3f1d02b16 Merge pull request #4516 from DreamMaoMao/fix-ext-ws
fix: right and middle button not work in ext/workspace module
2025-10-05 09:57:50 +02:00
Alexis Rouillard
bea012d06d Merge pull request #4518 from DreamMaoMao/fix-network
fix: Correct the error in converting network speed units
2025-10-05 09:57:29 +02:00
Alexis Rouillard
197ee78080 Merge pull request #4525 from lairez/makepkg
Fixes #4521 and #4522
2025-10-05 09:57:06 +02:00
Pierre Lairez
d8e2392410 Fixes #4521 and #4522
The problem is commit 2b552f7 which introduces a minimum interval time
of 1ms. But then, in modules/custom.cpp, the constructor tests if the
interval is nonzero to distinguish continuous workers from delay workers.
2025-10-03 11:24:18 +02:00
DreamMaoMao
801319f024 fix: Correct the error in converting network speed units 2025-10-02 08:55:40 +08:00
DreamMaoMao
6f308d8ea1 fix: right and middle button not work in ext/workspace module 2025-10-01 22:30:23 +08:00
Alexis Rouillard
18a9835b7c Merge pull request #4246 from edeustua/master
feat: Add ISO 8601 calendar to clock module
2025-10-01 14:29:37 +02:00
Alexis Rouillard
632af16b19 Merge pull request #4448 from winkelnp/gamemode-icon
Fix: styling: set gamemode icon size and spacing to 0 if use-icon is false
2025-10-01 14:28:30 +02:00
Alexis Rouillard
9acf032c0c Merge pull request #4458 from kolayne/patch-1
Fix: style: show active workspace on hyprland
2025-10-01 14:28:02 +02:00
Alexis Rouillard
9dd75d4f6b Merge pull request #4507 from workflow/niri-language-add-css-classes
feat(niri/language): add CSS classes
2025-10-01 14:27:35 +02:00
Alexis Rouillard
4f16ec16f9 Merge pull request #4395 from pol-rivero/workspace-taskbar-improvements
[hyprland/workspaces] Taskbar improvements
2025-10-01 14:27:13 +02:00
Alexis Rouillard
b4c80cfb56 Merge pull request #4387 from seschwar/include-xdg-data-home
fix: display icons for userwide installed applications
2025-10-01 14:26:39 +02:00
Alexis Rouillard
e00db5886e Merge pull request #4372 from rellimn/fix-menu-hover
Fix module and tray item staying in hover state after opening menu
2025-10-01 14:25:23 +02:00
Alexis Rouillard
a613cd54b0 Merge pull request #4371 from khaneliman/nixfmt
fix(flake): fix formatter configuration
2025-10-01 14:24:23 +02:00
Alexis Rouillard
5c01ad75f1 Merge pull request #4358 from labruzese/master
Moved workspace id failing to parse from an error to part of the trace
2025-10-01 14:23:59 +02:00
Alexis Rouillard
3cc5943c08 Merge pull request #4373 from Arkoniak/4354-wildcard-config-regression
bugfix: expanding wildcards in config includes (#4354)
2025-10-01 14:23:31 +02:00
Alexis Rouillard
c7a77f2c08 Merge pull request #4390 from aidansunbury/master
Support millisecond precision for script intervals
2025-10-01 14:22:17 +02:00
Alexis Rouillard
a15565ac48 Merge pull request #4408 from lfos/fix-hyprland-ipc-destructor
Prevent child zombie process from tearing down Hyprland IPC
2025-10-01 14:21:17 +02:00
Alexis Rouillard
23220eb541 Merge pull request #4410 from lfos/fix-clock-asan-use-after-scope
clock: fix use after scope
2025-10-01 14:20:34 +02:00
Alexis Rouillard
32d4cf4c7b Merge pull request #4414 from PedroManse/master
docs: fix waybar menu example and formatting
2025-10-01 14:20:07 +02:00
Alexis Rouillard
f29e843d6e Merge pull request #4428 from Alexays/update_flake_lock_action
flake.lock: Update
2025-10-01 14:19:50 +02:00
Alexis Rouillard
97f1e54b70 Merge pull request #4447 from guttermonk/clock-fix
Clock Module: Independent clock tooltip formatting and fix for blank line at the end of the timezone list
2025-10-01 14:18:28 +02:00
Alexis Rouillard
6824a76595 Merge pull request #4380 from khaneliman/test-tweak
feat(makefile): support more detailed test output
2025-10-01 14:18:01 +02:00
Alexis Rouillard
0f1d31147a Merge pull request #4457 from dmyTRUEk/fix-4455
fix(temperature): critical style not being removed
2025-10-01 14:17:14 +02:00
Alexis Rouillard
d3b094503e Merge pull request #4493 from LukashonakV/cava_backend
Cava backend. Comminication using signals
2025-10-01 14:16:51 +02:00
Alexis Rouillard
fbec045492 Merge pull request #4437 from jp7677/ext-workspaces-remove-dirty-tracking
ext/workspaces: fix appearing of hidden workspaces
2025-10-01 14:16:03 +02:00
Alexis Rouillard
c31d15045a Merge pull request #4452 from dmyTRUEk/master
docs(temperature): add missed `warning` style
2025-10-01 14:15:10 +02:00
Alexis Rouillard
8bb19a9505 Merge pull request #4474 from LordMZTE/river-vacant-startup
fix(river): hide vacant tags on initial startup
2025-10-01 14:14:54 +02:00
Alexis Rouillard
08b36955de Merge pull request #4488 from RQuarx/patch-1
fix: changed *waybar-styles(5)" to *waybar-styles(5)* in the last line
2025-10-01 14:13:54 +02:00
Alexis Rouillard
6978193c6a Merge pull request #4485 from coleleavitt/master
fix: handle null GDK window reference in surface initialization
2025-10-01 14:13:33 +02:00
Alexis Rouillard
7092244402 Merge pull request #4495 from stefonarch/patch-2
Fix example in waybar-niri-language.5.scd
2025-10-01 14:12:53 +02:00
Alexis Rouillard
8013556d2b Merge pull request #4476 from notpeelz/fix-sni-item-menu-destroy
fix: close sni menu on item destruction
2025-10-01 14:12:35 +02:00
Pol Rivero
5f1db15c2e Workspaces containing only ignored windows should be considered empty
This fixes #4479
2025-10-01 08:06:11 +02:00
github-actions[bot]
db2dfb6f3c flake.lock: Update
Flake lock file updates:

• Updated input 'nixpkgs':
    'github:NixOS/nixpkgs/dc9637876d0dcc8c9e5e22986b857632effeb727?narHash=sha256-cKgvtz6fKuK1Xr5LQW/zOUiAC0oSQoA9nOISB0pJZqM%3D' (2025-07-28)
  → 'github:NixOS/nixpkgs/e9f00bd893984bc8ce46c895c3bf7cac95331127?narHash=sha256-0m27AKv6ka%2Bq270dw48KflE0LwQYrO7Fm4/2//KCVWg%3D' (2025-09-28)
2025-10-01 00:13:30 +00:00
workflow
862ba2f568 feat(niri/language): add CSS classes 2025-09-29 17:43:23 +03:00
Viktar Lukashonak
76d3b47ffd Cava back/front end transformation 2025-09-26 23:34:11 +03:00
Viktar Lukashonak
cbab9c9713 spdlog bump 2025-09-25 21:46:13 +03:00
Standreas
cbd8930e22 Fix example in waybar-niri-language.5.scd 2025-09-23 16:32:45 +02:00
Jens Peters
b08d0c21f3 ext/workspaces: add deactivate action 2025-09-20 14:11:46 +02:00
RQuarx
9e3a9f7d35 fix: changed *waybar-styles(5)" to *waybar-styles(5)* in the last line 2025-09-20 15:05:16 +07:00
Cole Leavitt
45cfaf4a0b fix: validate 'swap-icon-label' configuration type and log warnings 2025-09-17 21:20:43 -07:00
Cole Leavitt
4a5358e8c5 fix: handle null GDK window reference in surface initialization 2025-09-17 21:17:26 -07:00
peelz
0c3e82219f fix: close sni menu on item destruction 2025-09-16 14:03:45 -04:00
LordMZTE
fd601801b4 fix(river): hide vacant tags on initial startup
Before this, vacant tags would show with `hide-vacant` set on initial
startup, because we receive initial tag events from River before we show
the bar. In that case, we won't call `set_visible(false)` on the
respective buttons because they're not shown yet. This registers the
output status listener after we show the bar so we won't miss any
events.
2025-09-16 16:04:25 +02:00
winkelnp
e87ece4462 set gamemode icon size and spacing to 0 if use-icon is false 2025-09-15 22:03:23 +02:00
Nikolai Nechaev
3435e33845 Fix: style: show active workspace on hyprland
The `hyprland/workspaces` module has the CSS class
`active` rather than `focused` for the current workspace.

Update the default CSS selector for the current workspace
to match both `button.focused` and `button.active`.
2025-09-13 08:40:30 +09:00
dmyTRUEk
09a07cd429 fix(temperature): critical style not being removed (#4455) 2025-09-12 20:00:43 +03:00
dmyTRUEk
e8a2e6c66f docs(temperature): add missed warning style 2025-09-10 13:21:04 +03:00
guttermonk
d45ce841e3 Keep the local timezone from being in the tooltip. 2025-09-06 08:40:09 -05:00
guttermonk
97fa6aa4dd Added option to show timezones in tooltip only and removed the extra
blank line at the bottom of the timezone list.
2025-09-05 21:01:23 -05:00
Jens Peters
af9c31ccd3 ext/workspaces: fix appearing of hidden workspaces
Do this by removing the needs-update tracking. The gain
was questionable to begin with and turns out it  doesn't
work correctly with multiple outputs.
2025-09-03 06:53:21 +02:00
Manse
19468d4365 docs: fix waybar menu example and formatting
fix example's hibernate id typo
fix xml and json formatting
2025-08-25 10:50:51 -03:00
zjeffer
9720d80524 add asan.supp 2025-08-23 18:25:45 +02:00
Lukas Fleischer
8e488b4d5e clock: fix use after scope
Signed-off-by: Lukas Fleischer <lfleischer@lfos.de>
2025-08-23 00:25:50 -04:00
Lukas Fleischer
5a29473080 Prevent child zombie process from tearing down Hyprland IPC
In rare circumstances, we may fork(), e.g., as part of a custom module,
and the child process may fail to exec() and exit. In those cases, the
IPC destructor will be called in the child process.

Prior to this commit, this call would then result in the shared socket
being closed. Prevent this by only closing the socket from the original
process.

Fixes #3975 and #4152.

Signed-off-by: Lukas Fleischer <lfleischer@lfos.de>
2025-08-22 18:58:53 -04:00
zjeffer
3c3164eb8e Fix warning if swap-icon-label is not defined in config 2025-08-19 23:56:10 +02:00
zjeffer
556c5f5a30 Add tsan.supp file to easily ignore common tsan issues from external libraries 2025-08-19 23:56:08 +02:00
Pol Rivero
45d01ce6e5 Implement "active-window-position" 2025-08-18 21:23:36 +02:00
Pol Rivero
691b7d427b Implement "reverse-direction" 2025-08-18 20:49:14 +02:00
Aidan Sunbury
5a87a9d60a Merge pull request #1 from aidansunbury/AS-millisecond-intervals 2025-08-16 16:02:43 -07:00
aidansunbury
2b81782fa9 more changes 2025-08-16 16:01:41 -07:00
aidansunbury
2b552f7fb6 compat 2025-08-16 15:34:43 -07:00
aidansunbury
6dc5a73a02 initial changes 2025-08-16 15:29:59 -07:00
Sebastian Schwarz
e8755b1a7f fix: display icons for userwide installed applications
Previously Waybar only displayed icons for applications which were
installed systemwide.  Icons were resolved via `.desktop` files in
directories specified by the environment variable `XDG_DATA_DIRS`.
However the [XDG specification](https://specifications.freedesktop.org/basedir-spec/0.8/#variables)
notes that this variable should only consulted **in addition** to
`XDG_DATA_HOME`:

> `$XDG_DATA_DIRS` defines the preference-ordered set of base
> directories to search for data files in addition to the
> `$XDG_DATA_HOME` base directory.

This because `XDG_DATA_DIRS` contains only systemwide directories,
whereas `XDG_DATA_HOME` contains the userwide directory.  Also
including the latter when looking up `.desktop` files allows Waybar to
display icons for applications which where installed userwide.
2025-08-16 14:14:59 +02:00
Austin Horstman
25ac6b7a80 refactor(makefile): allow build on test command
meson will skip building, if not needed, but we want to make sure we're
actually testing what we expect.

Signed-off-by: Austin Horstman <khaneliman12@gmail.com>
2025-08-13 14:09:01 -05:00
Austin Horstman
8fe76317fb feat(makefile): support more detailed test output
Add a command to show a prettier test output so you can see what's going
on easier.

Signed-off-by: Austin Horstman <khaneliman12@gmail.com>
2025-08-13 14:09:01 -05:00
Arkoniak
691e66a7fd tests: additional tests for bugfix (#4354) 2025-08-13 10:30:25 +03:00
Arkoniak
5ac28f3947 bugfix: expanding wildcards in config includes (#4354) 2025-08-12 22:31:59 +03:00
rellimn
089b9a20fc Fix module and tray item staying in hover state after opening menu
Fixes #3980
2025-08-12 20:51:35 +02:00
Austin Horstman
d09a4072e5 chore(flake): nixfmt-rfc-style -> nixfmt
Marked stable and uses new name after replacing classic.

Signed-off-by: Austin Horstman <khaneliman12@gmail.com>
2025-08-12 13:28:07 -05:00
Austin Horstman
a0c21318f9 chore(format): run treefmt
Signed-off-by: Austin Horstman <khaneliman12@gmail.com>
2025-08-12 13:26:02 -05:00
Austin Horstman
be48f6bff2 fix(flake): fix formatter configuration
Signed-off-by: Austin Horstman <khaneliman12@gmail.com>
2025-08-12 13:25:50 -05:00
zjeffer
5079884b78 Hyprland IPC improvements, fix tsan warning, WindowCount shouldn't create a separate IPC 2025-08-12 19:39:36 +02:00
Pol Rivero
83f16a2092 Document newer config options of workspace-taskbar
Adds some configs that were only documented in the GitHub wiki to the manpage.
2025-08-12 16:43:31 +02:00
Skylar Abruzese
64b64d0316 Moved workspace id failing to parse from an error to part of the trace.
With named persistent workspaces it is expected behavior that they have
no id since their workspace may not have been created by hyprland yet.
2025-08-09 18:33:35 -04:00
Alex
41de8964f1 chore: 0.14.0 2025-08-08 09:15:22 +02:00
Alex
7e0cbf4a1f fix: lint 2025-08-08 08:59:10 +02:00
Alexis Rouillard
b3fbe1b5ed Merge pull request #4319 from M0streng0/master
wireplumber & backlight: fix states and support for microphone
2025-08-08 08:56:07 +02:00
Alexis Rouillard
477f30705c Merge pull request #4208 from markx86/feat/battery-events
battery: Add support for battery level related events
2025-08-08 08:54:32 +02:00
Alexis Rouillard
07d3a4da10 Merge pull request #4333 from Arkoniak/relative_paths_in_includes
Relative paths in included configs
2025-08-08 08:53:55 +02:00
Alexis Rouillard
61b3c6d7d1 Merge pull request #3929 from xb-bx/master
sway/workspaces: Implement reverse-scroll
2025-08-08 08:45:42 +02:00
Alexis Rouillard
c63e332fb2 Merge pull request #4278 from rwsalie/master
add openbsd support
2025-08-08 08:43:52 +02:00
Alex
79c30e77a7 fix: lint 2025-08-08 08:42:17 +02:00
Alexis Rouillard
b0983e9c37 Merge pull request #3833 from Bahnschrift/master 2025-08-08 08:26:21 +02:00
Alexis Rouillard
3dce0956ec Merge pull request #3930 from Invertisment/master 2025-08-08 08:24:58 +02:00
Alexis Rouillard
9a545e75e4 Merge pull request #4080 from proycon/river-layout-class 2025-08-08 08:23:12 +02:00
Alexis Rouillard
7cfa708b1a Merge pull request #4326 from notpeelz/feat-network-match-altnames 2025-08-08 08:21:33 +02:00
Alexis Rouillard
f1b7d829c2 Merge pull request #4016 from jp7677/ext-workspaces
ext/workspaces: port from wlr/workspaces to ext-workspace-v1 for a.o. labwc support
2025-08-08 08:18:01 +02:00
Alexis Rouillard
6679801a9c Merge pull request #3849 from haansn08/mpd-format-uri
mpd: add uri and filename format arguments
2025-08-07 23:04:02 +02:00
Alexis Rouillard
13a4e5d43d Merge pull request #4337 from Alexays/update_flake_lock_action
flake.lock: Update
2025-08-07 23:02:17 +02:00
Alexis Rouillard
b9a26f51b6 Merge pull request #3868 from pol-rivero/master
[hyprland/workspaces] Implement workspace taskbars
2025-08-07 23:00:22 +02:00
github-actions[bot]
ff69525e29 flake.lock: Update
Flake lock file updates:

• Updated input 'nixpkgs':
    'github:NixOS/nixpkgs/30e2e2857ba47844aa71991daa6ed1fc678bcbb7?narHash=sha256-krGXKxvkBhnrSC/kGBmg5MyupUUT5R6IBCLEzx9jhMM%3D' (2025-06-27)
  → 'github:NixOS/nixpkgs/dc9637876d0dcc8c9e5e22986b857632effeb727?narHash=sha256-cKgvtz6fKuK1Xr5LQW/zOUiAC0oSQoA9nOISB0pJZqM%3D' (2025-07-28)
2025-08-01 00:14:36 +00:00
Arkoniak
1e0037a873 fixed extra copy 2025-07-31 21:29:20 +03:00
Pol Rivero
5bbace1d43 Merge remote-tracking branch 'upstream/master' 2025-07-29 23:30:44 +02:00
peelz
4c72033309 refactor: why is that line there 2025-07-29 07:52:46 -04:00
peelz
b5093f3e58 feat: match network interfaces by their altnames 2025-07-29 07:52:46 -04:00
Arkoniak
f824ae9334 Relative paths in included configs 2025-07-29 10:45:31 +03:00
Henrique Oliveira
90f2490407 Fix: Backlight same issue with states 2025-07-23 20:26:17 +02:00
Henrique Oliveira
a6ac75983f Add: WirePlumber - format-source support 2025-07-23 16:59:07 +02:00
Henrique Oliveira
7cb1a0e3d6 Add: Wireplumber - support for microphone 2025-07-23 13:19:53 +02:00
Henrique Oliveira
91e57376ef Fix: WirePlumber module - states not working 2025-07-23 12:18:22 +02:00
Alexis Rouillard
0776e694df Merge pull request #4316 from erikeah/master 2025-07-23 08:31:48 +02:00
Erik Alonso
bb190409de fix: unable to disable upower's tooltip 2025-07-22 13:09:33 +01:00
Alexis Rouillard
39d6d80f64 Merge pull request #4315 from notpeelz/style-clang-format 2025-07-21 07:26:58 +02:00
peelz
b4d95b405c style: clang-format 2025-07-20 22:40:29 -04:00
Alexis Rouillard
71b01fe58f Merge pull request #4161 from blackxored/feat/electron-tray-hack
feat: add a way to override electron app tray icons
2025-07-20 18:55:01 +02:00
Alexis Rouillard
2baa93174b Merge pull request #4260 from notpeelz/feat-display-rfkill-setting
feat: add rfkill network setting
2025-07-20 18:54:24 +02:00
Alexis Rouillard
321ed85a67 Merge pull request #4298 from csskevin/docu-arch
adding dependency command for arch
2025-07-20 18:51:57 +02:00
Alexis Rouillard
e526afb963 Merge pull request #4310 from arnaud-ma/remove-persistent-workspace-rules
Fix #4307
2025-07-20 18:51:01 +02:00
arnaud-ma
8dcdd97879 small fixes 2025-07-19 05:01:29 +02:00
arnaud-ma
2dc2b5ccfd fix #4307 2025-07-19 04:50:59 +02:00
arnaud-ma
a4f200cdb5 revert 2025-07-19 04:47:31 +02:00
arnaud-ma
64ed2cd970 fix indentation 2025-07-19 03:23:32 +02:00
arnaud-ma
e45883088d hyprland: Remove redundant workspace rules loading 2025-07-19 03:18:48 +02:00
csskevin
061c561762 adding dependency command for arch 2025-07-15 00:19:55 +02:00
bilaliscarioth
506fd5c597 Merge branch 'Alexays:master' into master 2025-07-14 02:00:51 +02:00
bilaliscarioth
682fc34c1d fix linters for css_reload_helper.cpp 2025-07-13 14:03:09 +02:00
bilaliscarioth
f91889ce1c format SafeSignal.hpp as the linters want 2025-07-13 14:01:59 +02:00
Alexis Rouillard
94777921d9 Merge pull request #4272 from labruzese/master
fix: hyprland named persistent workspaces
2025-07-13 09:07:26 +02:00
Alexis Rouillard
ee9dc6ae05 Merge pull request #4292 from nraffp/4291
respect gtk color scheme variant for gtk css variable
2025-07-13 09:06:25 +02:00
Alexis Rouillard
1cb30e0f85 Merge pull request #4275 from acarl005/master
fix: prevent persistent workspaces from being duplicated if they exist…
2025-07-13 09:05:36 +02:00
Alexis Rouillard
50711bfb87 Merge pull request #4284 from hritix/feature/markup_support_for_tooltip_of_battery_and_pulseaudio
enabled pango markup support for tooltip of battery and pulseaudio modules
2025-07-13 09:04:47 +02:00
Nick Raffaele
19360462ba respect gtk color schema variant for gtk css variable 2025-07-12 09:45:14 -07:00
peelz
73d9c5f560 fix(network): reset is_p2p_ in clearIface 2025-07-10 08:01:20 -04:00
peelz
b85f0c17c3 fix(network): ignore carrier state when the interface is down
I'm not sure why, but my network card (mt7921e) sometimes will report
having a carrier when the interface is down. This usually happens
when rfkill was active before rebooting.
2025-07-10 08:01:20 -04:00
peelz
b02694caef fix(network): initialize all fields
Some fields were previously uninitialized (e.g. carrier), which
could lead to UB.
2025-07-10 08:01:20 -04:00
peelz
2dfbaabf31 fix(network): use atomic_bool to store the rfkill state 2025-07-10 08:01:20 -04:00
peelz
f991af2893 style(network): fix trailing white space 2025-07-10 08:01:20 -04:00
peelz
0e07c7ac5c feat(network): add rfkill setting
This setting makes it possible to have a configuration with two
network modules where one of them displays the ethernet state
(disconnected, linked, ethernet), and the other, the wifi state
(disabled, disconnected, linked, wifi).

Otherwise the ethernet state would show up as "disabled" (instead of
"disconnected") when rfkill is active.
2025-07-10 08:01:20 -04:00
peelz
46a152abc8 fix(network): display as disabled if rfkill and no carrier
We want the "disabled" state even when an interface is selected
explicitly.
2025-07-10 08:01:20 -04:00
hritix
310a473e65 enabled markup support for tooltip of battery and pulseaudio modules 2025-07-09 22:50:03 +05:30
Emiliano Deustua
be819be8bd fix: Revert formatting to clang 2025-07-07 22:10:09 -05:00
bilaliscarioth
d808c00324 avoid useless vars on cpu_frequency, mimic sigrtmin/sigrtmax 2025-07-08 02:21:48 +02:00
bilaliscarioth
0cb605b529 start openbsd ports 2025-07-08 02:13:33 +02:00
Maarten van Gompel
04796988e9 feat(river): set layout name as class
This allows for custom styling for specific river layouts (such as monocle).
2025-07-07 15:13:33 +02:00
xb-bx
4d74bb3004 sway/workspaces: implement reverse-scroll 2025-07-07 14:17:18 +03:00
Andy Carlson
fd67002662 fix: prevent persistent workspaces from being duplicated if they exist under a different name 2025-07-06 23:11:00 -04:00
Pol Rivero
c98cb7095d Merge remote-tracking branch 'upstream/master' 2025-07-06 10:18:59 +02:00
Alexis Rouillard
cae5f9a56f Merge pull request #4274 from tpaau-17DB/master 2025-07-04 21:21:30 +01:00
tpaau-17DB
10c116e54a Change default tooltip for the battery module. 2025-07-04 19:02:10 +02:00
Skylar Abruzese
6d3b93bbf7 fix: added active workspace matching by name as fallback
fixes bug where persistent workspaces would not be marked as active
because their id is based on creation time by hyprland and thus we can't
consistently match the id's without constantly changing them (this would
also cause issues with workspace sorting).
2025-07-03 18:48:04 -04:00
Skylar Abruzese
9ef6dc7380 fix: hyprland named persistent workspaces
allowed persistent workspaces to be defined with names instead of just
id's
2025-07-03 17:44:37 -04:00
Alexis Rouillard
f409f53131 Merge pull request #4256 from Alexays/update_flake_lock_action
flake.lock: Update
2025-07-02 09:51:31 +01:00
Alexis Rouillard
88766de1ee Merge pull request #4258 from notpeelz/fix-network-eth-rfkill-precedence
fix: 'ethernet' network state should have precedence over 'disabled'
2025-07-01 16:31:54 +01:00
peelz
b6c13ba58b fix: 'ethernet' network state should have precedence over 'disabled' 2025-07-01 10:37:31 -04:00
github-actions[bot]
e7a4bafede flake.lock: Update
Flake lock file updates:

• Updated input 'nixpkgs':
    'github:NixOS/nixpkgs/96ec055edbe5ee227f28cdbc3f1ddf1df5965102?narHash=sha256-7doLyJBzCllvqX4gszYtmZUToxKvMUrg45EUWaUYmBg%3D' (2025-05-28)
  → 'github:NixOS/nixpkgs/30e2e2857ba47844aa71991daa6ed1fc678bcbb7?narHash=sha256-krGXKxvkBhnrSC/kGBmg5MyupUUT5R6IBCLEzx9jhMM%3D' (2025-06-27)
2025-07-01 00:14:02 +00:00
Emiliano Deustua
08a39dd9eb refactor: Change config key name 2025-06-30 10:44:46 -05:00
Jens Peters
6c48db6cee ext/workspaces: log workspace id/name
This should help to distinguish between internal and
external ID in the logs.
2025-06-29 21:51:31 +02:00
Jens Peters
984d0de1fc ext/workspaces: introduce ignore-hidden option
Hide hidden workspaces by default, but add an option for overriding.

While at it, move button visibility handling to Workspaces and only
handle add/removal of buttons at WorkspaceManager. This makes it
easier to keep track if sorting is needed.
2025-06-29 21:51:31 +02:00
Jens Peters
29bf5d5da1 ext/workspaces: moved/renamed from wlr/workspaces
The ext-workspace-v1 protocol is not wlr/wlroots
specific.
2025-06-29 21:51:31 +02:00
Jens Peters
255c0ebe28 wlr/workspaces: port to ext-workspace-v1
Rework implementation to match new protocol behavior.
2025-06-29 21:51:31 +02:00
Emiliano Deustua
649a98a679 feat: Add ISO 8601 calendar to clock module 2025-06-28 19:42:55 -05:00
Alexis Rouillard
8516d457ad Merge pull request #4242 from mexanoz/fix-hyprland-language
fix hyprland/language layout parsing
2025-06-27 18:20:27 +01:00
mexanoz
7505e2c3f3 fix hyprland/language layout parsing 2025-06-27 20:54:38 +05:00
Martynas Maciulevičius
c8dc3e7024 Remove unused import 2025-06-27 09:31:51 +03:00
Martynas Maciulevičius
b7ff47fb05 User kill signal config keys: Use underscore instead of dash 2025-06-27 09:31:51 +03:00
Martynas Maciulevičius
7463be9b6a Fix initial null configuration; Fix doc compilation errors 2025-06-27 09:31:51 +03:00
Martynas Maciulevičius
125b59e23b Add more details on how 'reload' works in signals 2025-06-27 09:31:51 +03:00
Martynas Maciulevičius
3c7a9bf432 Documentation for sigusr1 and sigusr2 config 2025-06-27 09:31:51 +03:00
Martynas Maciulevičius
aaea814217 Idempotent bar show/hide via configurable user kill signals 2025-06-27 09:31:51 +03:00
Alexis Rouillard
c336bc5466 Merge pull request #4234 from Invertisment/fix-default-icon 2025-06-26 20:35:45 +01:00
Martynas Maciulevičius
460b19ba1b Fix default icon in tray module 2025-06-26 20:34:56 +03:00
markx86
53d8d3cd2a fix: Code formatting for clang-format/lint CI 2025-06-22 18:55:07 +02:00
markx86
eae22f3273 battery: Document events in waybar-battery manpage 2025-06-22 17:45:16 +02:00
markx86
08da7b5282 feat: Add support for battery related events 2025-06-22 17:45:12 +02:00
Bahnschrift
800c4b56cc Merge remote-tracking branch 'source/master' 2025-06-18 18:42:23 +10:00
Adrian Perez
81fb0daad2 feat: add a way to override electron app tray icons 2025-06-03 16:13:41 -07:00
Pol Rivero
4ae2b6f1ba Implement ignore-list 2025-05-02 15:48:34 +02:00
Pol Rivero
c9215ad818 Minor code cleanup 2025-05-02 14:29:44 +02:00
Pol Rivero
61c5dad895 Fix some windows not being marked as active when opened
In some cases, the active event is arriving before the create event. We need to store the currently active address and initialize the windows accordingly
2025-05-01 21:03:46 +02:00
Pol Rivero
998fd7a192 Fix window title not being updated properly 2025-05-01 20:51:12 +02:00
Pol Rivero
72404a77f0 Initial implementation of active window
TODO:
- Sometimes the active event arrives before the create, in which case the window is not activated.
- The window title event also looks unreliable in some cases, will need to investigate
2025-05-01 20:22:34 +02:00
Pol Rivero
59c270ec06 Respect format-window-separator if workspace-taskbar is enabled 2025-05-01 19:26:44 +02:00
Pol Rivero
a816812f81 Run clang-format 2025-04-30 16:20:11 +02:00
Pol Rivero
451d458545 Fix compilation errors after merge 2025-04-29 20:12:59 +02:00
Pol Rivero
4222032fa1 Merge remote-tracking branch 'upstream/master' 2025-04-29 19:59:42 +02:00
Pol Rivero
e541936df9 Merge remote-tracking branch 'upstream/master' 2025-03-08 17:18:31 +01:00
Pol Rivero
4dbb874f7c Merge remote-tracking branch 'upstream/master' 2025-02-06 12:19:57 +01:00
Pol Rivero
1a9f5aced7 workspace taskbars: Add button param to click command 2025-01-27 11:47:16 +01:00
Pol Rivero
7b854112ed workspace taskbars: Allow custom command on window click 2025-01-27 11:46:35 +01:00
Pol Rivero
b4519c0819 workspace taskbars: Use sigc::mem_fun instead of lambda 2025-01-27 11:46:35 +01:00
Pol Rivero
e0f3695523 workspace taskbars: Minor fixes
- Add missing CSS class to manpage
- Fix rare segfault when address is not found (seems to only happen when compiled for production)
2025-01-27 11:46:35 +01:00
Pol Rivero
42affa4eda workspace taskbars: Update manpage 2025-01-27 11:46:35 +01:00
Pol Rivero
5ee0d1c7fe workspace taskbars: Fix windows not showing
Windows were not being shown or updated unless the window-rewrite config were present.
2025-01-27 11:46:35 +01:00
Pol Rivero
3948c0d154 workspace taskbars: Focus window on click 2025-01-27 11:46:35 +01:00
Pol Rivero
53ca5a4883 workspace taskbars: Display windows in a consistent order
Use a vector instead of a map for for storing the workspace windows.
This orders the windows by the time they were added to the workspace, instead of sorting by address (which is effectively a random order). The new ordering seems to match the wlr/taskbar module
2025-01-27 11:46:35 +01:00
Pol Rivero
e1649b001f workspace taskbars: Fix title not updating
Fix another older bug where the title of a window will not be updated after moving it to another monitor.
In onWindowMoved, when moving an orphan window to the display of the current bar, that window should no longer be an orphan.
2025-01-27 11:46:35 +01:00
Pol Rivero
5e1d6d1cc5 workspace taskbars: Fix title not updating
This seems to be an old bug that has been made visible with the new workspace taskbars feature.
Sometimes, when closing a window and re-opening a window of the same program, hyprland reuses the window address. Since m_orphanWindowMap was not being cleaned up on window close, the new window would not be updated properly.
2025-01-27 11:46:35 +01:00
Pol Rivero
fdb9004048 workspace taskbars: More config options
- orientation
- icon-size
- icon-theme
2025-01-27 11:46:35 +01:00
Pol Rivero
1c07ca0099 workspace taskbars: Add config parsing
Use format from config instead of hardcoding
2025-01-27 11:46:35 +01:00
Pol Rivero
69e2e249a6 Initial implementation of workspace taskbars
Add a list of window titles and icons to each workspace (like wlr/taskbar but grouped by workspace).

Only implemented on hyprland for now.
2025-01-27 11:46:35 +01:00
Pol Rivero
bc2e143ac5 Extract icon loading logic to separate class 2025-01-27 11:46:35 +01:00
Stefan Haan
d100e78872 mpd: add uri and filename format arguments 2024-12-28 13:58:19 +01:00
Bahnschrift
cf64b2c88c fix: un-hide tray when new icons are added 2024-12-19 12:29:58 +11:00
Bahnschrift
622f22d6b5 fix: hide tray when there are no non-passive icons 2024-12-19 12:09:31 +11:00
132 changed files with 4269 additions and 2347 deletions

1
.gitignore vendored
View File

@@ -7,6 +7,7 @@ vgcore.*
*.swp
packagecache
/subprojects/**/
/subprojects/.wraplock
/build*
/dist
/meson.egg-info

View File

@@ -20,8 +20,12 @@ debug-run: build-debug
./build/waybar --log-level debug
test:
meson test -C build --no-rebuild --verbose --suite waybar
meson test -C build --verbose --suite waybar
.PHONY: test
test-detailed:
meson test -C build --verbose --print-errorlogs --test-args='--reporter console -s'
.PHONY: test-detailed
clean:
rm -rf build

View File

@@ -116,6 +116,36 @@ sudo apt install \
libxkbregistry-dev
```
On Arch, you can use this command:
```
pacman -S --asdeps \
gtkmm3 \
jsoncpp \
libsigc++ \
fmt \
wayland \
chrono-date \
spdlog \
gtk3 \
gobject-introspection \
libgirepository \
libpulse \
libnl \
libappindicator-gtk3 \
libdbusmenu-gtk3 \
libmpdclient \
sndio \
libevdev \
libxkbcommon \
upower \
meson \
cmake \
scdoc \
wayland-protocols \
glib2-devel
```
Contributions welcome!<br>
Have fun :)<br>

5
asan.supp Normal file
View File

@@ -0,0 +1,5 @@
# Suppress common address sanitizer issues in dependencies, these are often non-fixable or not an issue.
# Use it like this (when in repo root): ASAN_OPTIONS="suppressions=./asan.supp" ./build/waybar
leak:libpangoft2-1.0.so.0
leak:libgtk-3.so.0
leak:libfontconfig.so.1

12
flake.lock generated
View File

@@ -3,11 +3,11 @@
"flake-compat": {
"flake": false,
"locked": {
"lastModified": 1747046372,
"narHash": "sha256-CIVLLkVgvHYbgI2UpXvIIBJ12HWgX+fjA8Xf8PUmqCY=",
"lastModified": 1767039857,
"narHash": "sha256-vNpUSpF5Nuw8xvDLj2KCwwksIbjua2LZCqhV1LNRDns=",
"owner": "edolstra",
"repo": "flake-compat",
"rev": "9100a0f413b0c601e0533d1d94ffd501ce2e7885",
"rev": "5edf11c44bc78a0d334f6334cdaf7d60d732daab",
"type": "github"
},
"original": {
@@ -18,11 +18,11 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1748460289,
"narHash": "sha256-7doLyJBzCllvqX4gszYtmZUToxKvMUrg45EUWaUYmBg=",
"lastModified": 1766902085,
"narHash": "sha256-coBu0ONtFzlwwVBzmjacUQwj3G+lybcZ1oeNSQkgC0M=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "96ec055edbe5ee227f28cdbc3f1ddf1df5965102",
"rev": "c0b0e0fddf73fd517c3471e546c0df87a42d53f4",
"type": "github"
},
"original": {

View File

@@ -65,7 +65,7 @@
nativeBuildInputs =
pkgs.waybar.nativeBuildInputs
++ (with pkgs; [
nixfmt-rfc-style
nixfmt
clang-tools
gdb
]);
@@ -75,28 +75,26 @@
formatter = genSystems (
pkgs:
pkgs.treefmt.withConfig {
settings = [
{
formatter = {
clang-format = {
options = [ "-i" ];
command = lib.getExe' pkgs.clang-tools "clang-format";
excludes = [ ];
includes = [
"*.c"
"*.cpp"
"*.h"
"*.hpp"
];
};
nixfmt = {
command = lib.getExe pkgs.nixfmt-rfc-style;
includes = [ "*.nix" ];
};
settings = {
formatter = {
clang-format = {
options = [ "-i" ];
command = lib.getExe' pkgs.clang-tools "clang-format";
excludes = [ ];
includes = [
"*.c"
"*.cpp"
"*.h"
"*.hpp"
];
};
tree-root-file = ".git/index";
}
];
nixfmt = {
command = lib.getExe pkgs.nixfmt;
includes = [ "*.nix" ];
};
};
tree-root-file = ".git/index";
};
}
);

View File

@@ -21,7 +21,7 @@ class ALabel : public AModule {
protected:
Gtk::Label label_;
std::string format_;
const std::chrono::seconds interval_;
const std::chrono::milliseconds interval_;
bool alt_ = false;
std::string default_format_;

View File

@@ -14,6 +14,7 @@
#include "AModule.hpp"
#include "group.hpp"
#include "util/kill_signal.hpp"
#include "xdg-output-unstable-v1-client-protocol.h"
namespace waybar {
@@ -68,7 +69,11 @@ class Bar : public sigc::trackable {
void setMode(const std::string &mode);
void setVisible(bool value);
void toggle();
void show();
void hide();
void handleSignal(int);
util::KillSignalAction getOnSigusr1Action();
util::KillSignalAction getOnSigusr2Action();
struct waybar_output *output;
Json::Value config;
@@ -118,6 +123,9 @@ class Bar : public sigc::trackable {
std::unique_ptr<BarIpcClient> _ipc_client;
#endif
std::vector<std::shared_ptr<waybar::AModule>> modules_all_;
waybar::util::KillSignalAction onSigusr1 = util::SIGNALACTION_DEFAULT_SIGUSR1;
waybar::util::KillSignalAction onSigusr2 = util::SIGNALACTION_DEFAULT_SIGUSR2;
};
} // namespace waybar

View File

@@ -56,6 +56,8 @@ class Client {
std::list<struct waybar_output> outputs_;
std::unique_ptr<CssReloadHelper> m_cssReloadHelper;
std::string m_cssFile;
sigc::connection monitor_added_connection_;
sigc::connection monitor_removed_connection_;
};
} // namespace waybar

View File

@@ -35,6 +35,8 @@ class Config {
void setupConfig(Json::Value &dst, const std::string &config_file, int depth);
void resolveConfigIncludes(Json::Value &config, int depth);
void mergeConfig(Json::Value &a_config_, Json::Value &b_config_);
static std::vector<std::string> findIncludePath(
const std::string &name, const std::vector<std::string> &dirs = CONFIG_DIRS);
std::string config_file_;

View File

@@ -6,6 +6,7 @@
#if defined(__linux__)
#include <sys/inotify.h>
#endif
#include <sys/poll.h>
#include <algorithm>
#include <fstream>
@@ -15,6 +16,7 @@
#include "ALabel.hpp"
#include "bar.hpp"
#include "util/sleeper_thread.hpp"
#include "util/udev_deleter.hpp"
namespace waybar::modules {
@@ -35,15 +37,19 @@ class Battery : public ALabel {
std::tuple<uint8_t, float, std::string, float, uint16_t, float> getInfos();
const std::string formatTimeRemaining(float hoursRemaining);
void setBarClass(std::string&);
void processEvents(std::string& state, std::string& status, uint8_t capacity);
int global_watch;
std::map<fs::path, int> batteries_;
std::unique_ptr<udev, util::UdevDeleter> udev_;
std::array<pollfd, 1> poll_fds_;
std::unique_ptr<udev_monitor, util::UdevMonitorDeleter> mon_;
fs::path adapter_;
int battery_watch_fd_;
int global_watch_fd_;
std::mutex battery_list_mutex_;
std::string old_status_;
std::string last_event_;
bool warnFirstTime_{true};
bool weightedAverage_{true};
const Bar& bar_;
util::SleeperThread thread_;

View File

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

View File

@@ -0,0 +1,43 @@
#pragma once
#include <epoxy/gl.h>
#include "AModule.hpp"
#include "cava_backend.hpp"
namespace waybar::modules::cava {
class CavaGLSL final : public AModule, public Gtk::GLArea {
public:
CavaGLSL(const std::string&, const Json::Value&);
~CavaGLSL() = default;
private:
std::shared_ptr<CavaBackend> backend_;
struct ::cava::config_params prm_;
int frame_counter{0};
bool silence_{false};
bool hide_on_silence_{false};
// Cava method
auto onUpdate(const ::cava::audio_raw& input) -> void;
auto onSilence() -> void;
// Member variable to store the shared pointer
std::shared_ptr<::cava::audio_raw> m_data_;
GLuint shaderProgram_;
// OpenGL variables
GLuint fbo_;
GLuint texture_;
GLint uniform_bars_;
GLint uniform_previous_bars_;
GLint uniform_bars_count_;
GLint uniform_time_;
// Methods
void onRealize();
bool onRender(const Glib::RefPtr<Gdk::GLContext>& context);
void initShaders();
void initSurface();
void initGLSL();
GLuint loadShader(const std::string& fileName, GLenum type);
};
} // namespace waybar::modules::cava

View File

@@ -0,0 +1,30 @@
#pragma once
#include "ALabel.hpp"
#include "cava_backend.hpp"
namespace waybar::modules::cava {
class Cava final : public ALabel, public sigc::trackable {
public:
Cava(const std::string&, const Json::Value&);
~Cava() = default;
auto doAction(const std::string& name) -> void override;
private:
std::shared_ptr<CavaBackend> backend_;
// Text to display
Glib::ustring label_text_{""};
bool silence_{false};
bool hide_on_silence_{false};
std::string format_silent_{""};
int ascii_range_{0};
// Cava method
void pause_resume();
auto onUpdate(const std::string& input) -> void;
auto onSilence() -> void;
// ModuleActionMap
static inline std::map<const std::string, void (waybar::modules::cava::Cava::* const)()>
actionMap_{{"mode", &waybar::modules::cava::Cava::pause_resume}};
};
} // namespace waybar::modules::cava

View File

@@ -0,0 +1,84 @@
#pragma once
#include <json/json.h>
#include <sigc++/sigc++.h>
#include "util/sleeper_thread.hpp"
namespace cava {
extern "C" {
// Need sdl_glsl output feature to be enabled on libcava
#ifndef SDL_GLSL
#define SDL_GLSL
#endif
#include <cava/common.h>
#ifdef SDL_GLSL
#undef SDL_GLSL
#endif
}
} // namespace cava
namespace waybar::modules::cava {
using namespace std::literals::chrono_literals;
class CavaBackend final {
public:
static std::shared_ptr<CavaBackend> inst(const Json::Value& config);
virtual ~CavaBackend();
// Methods
int getAsciiRange();
void doPauseResume();
void Update();
const struct ::cava::config_params* getPrm();
std::chrono::milliseconds getFrameTimeMilsec();
// Signal accessor
using type_signal_update = sigc::signal<void(const std::string&)>;
type_signal_update signal_update();
using type_signal_audio_raw_update = sigc::signal<void(const ::cava::audio_raw&)>;
type_signal_audio_raw_update signal_audio_raw_update();
using type_signal_silence = sigc::signal<void()>;
type_signal_silence signal_silence();
private:
CavaBackend(const Json::Value& config);
util::SleeperThread read_thread_;
util::SleeperThread out_thread_;
// Cava API to read audio source
::cava::ptr input_source_{NULL};
struct ::cava::error_s error_{}; // cava errors
struct ::cava::config_params prm_{}; // cava parameters
struct ::cava::audio_raw audio_raw_{}; // cava handled raw audio data(is based on audio_data)
struct ::cava::audio_data audio_data_{}; // cava audio data
struct ::cava::cava_plan* plan_{NULL}; //{new cava_plan{}};
std::chrono::seconds fetch_input_delay_{4};
// Delay to handle audio source
std::chrono::milliseconds frame_time_milsec_{1s};
const Json::Value& config_;
int re_paint_{0};
bool silence_{false};
bool silence_prev_{false};
std::chrono::seconds suspend_silence_delay_{0};
int sleep_counter_{0};
std::string output_{};
// Methods
void invoke();
void execute();
bool isSilence();
void doUpdate(bool force = false);
void loadConfig();
void freeBackend();
// Signal
type_signal_update m_signal_update_;
type_signal_audio_raw_update m_signal_audio_raw_;
type_signal_silence m_signal_silence_;
};
} // namespace waybar::modules::cava

View File

@@ -0,0 +1,27 @@
#pragma once
#ifdef HAVE_LIBCAVA
#include "cavaRaw.hpp"
#include "cava_backend.hpp"
#ifdef HAVE_LIBCAVAGLSL
#include "cavaGLSL.hpp"
#endif
#endif
namespace waybar::modules::cava {
AModule* getModule(const std::string& id, const Json::Value& config) {
#ifdef HAVE_LIBCAVA
const std::shared_ptr<CavaBackend> backend_{waybar::modules::cava::CavaBackend::inst(config)};
switch (backend_->getPrm()->output) {
#ifdef HAVE_LIBCAVAGLSL
case ::cava::output_method::OUTPUT_SDL_GLSL:
return new waybar::modules::cava::CavaGLSL(id, config);
#endif
default:
return new waybar::modules::cava::Cava(id, config);
}
#else
throw std::runtime_error("Unknown module");
#endif
};
} // namespace waybar::modules::cava

View File

@@ -48,8 +48,9 @@ class Clock final : public ALabel {
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
date::day cldBaseDay_{0}; // calendar Cached day. Is used when today is changing(midnight)
std::string cldText_{""}; // calendar text to print
bool iso8601Calendar_{false}; // whether the calendar is in ISO8601
CldMode cldMode_{CldMode::MONTH};
auto get_calendar(const date::year_month_day& today, const date::year_month_day& ymd,
const date::time_zone* tz) -> const std::string;
@@ -62,6 +63,7 @@ class Clock final : public ALabel {
std::vector<const date::time_zone*> tzList_; // time zones list
int tzCurrIdx_; // current time zone index for tzList_
std::string tzText_{""}; // time zones text to print
std::string tzTooltipFormat_{""}; // optional timezone tooltip format
util::SleeperThread thread_;
// ordinal date in tooltip

View File

@@ -0,0 +1,141 @@
#pragma once
#include <fmt/format.h>
#include <gtkmm/button.h>
#include <gtkmm/image.h>
#include <gtkmm/label.h>
#include <map>
#include <memory>
#include <vector>
#include "AModule.hpp"
#include "bar.hpp"
#include "ext-workspace-v1-client-protocol.h"
namespace waybar::modules::ext {
class WorkspaceGroup;
class Workspace;
class WorkspaceManager final : public AModule {
public:
WorkspaceManager(const std::string &id, const waybar::Bar &bar, const Json::Value &config);
~WorkspaceManager() override;
void register_manager(wl_registry *registry, uint32_t name, uint32_t version);
void remove_workspace_group(uint32_t id);
void remove_workspace(uint32_t id);
void set_needs_sorting() { needs_sorting_ = true; }
// wl events
void handle_workspace_group(ext_workspace_group_handle_v1 *handle);
void handle_workspace(ext_workspace_handle_v1 *handle);
void handle_done();
void handle_finished();
// wl requests
void commit() const;
private:
void update() override;
bool has_button(const Gtk::Button *button);
void sort_workspaces();
void clear_buttons();
void update_buttons();
static uint32_t group_global_id;
static uint32_t workspace_global_id;
uint32_t workspace_name = 0;
bool sort_by_id_ = false;
bool sort_by_name_ = true;
bool sort_by_coordinates_ = false;
bool all_outputs_ = false;
const waybar::Bar &bar_;
Gtk::Box box_;
ext_workspace_manager_v1 *ext_manager_ = nullptr;
std::vector<std::unique_ptr<WorkspaceGroup>> groups_;
std::vector<std::unique_ptr<Workspace>> workspaces_;
bool needs_sorting_ = false;
};
class WorkspaceGroup {
public:
WorkspaceGroup(WorkspaceManager &manager, ext_workspace_group_handle_v1 *handle, uint32_t id);
~WorkspaceGroup();
u_int32_t id() const { return id_; }
bool has_output(const wl_output *output);
bool has_workspace(const ext_workspace_handle_v1 *workspace);
// wl events
void handle_capabilities(uint32_t capabilities);
void handle_output_enter(wl_output *output);
void handle_output_leave(wl_output *output);
void handle_workspace_enter(ext_workspace_handle_v1 *handle);
void handle_workspace_leave(ext_workspace_handle_v1 *handle);
void handle_removed();
private:
WorkspaceManager &workspaces_manager_;
ext_workspace_group_handle_v1 *ext_handle_;
uint32_t id_;
std::vector<wl_output *> outputs_;
std::vector<ext_workspace_handle_v1 *> workspaces_;
};
class Workspace {
public:
Workspace(const Json::Value &config, WorkspaceManager &manager, ext_workspace_handle_v1 *handle,
uint32_t id, const std::string &name);
~Workspace();
ext_workspace_handle_v1 *handle() const { return ext_handle_; }
u_int32_t id() const { return id_; }
std::string &workspace_id() { return workspace_id_; }
std::string &name() { return name_; }
std::vector<u_int32_t> &coordinates() { return coordinates_; }
Gtk::Button &button() { return button_; }
void update();
// wl events
void handle_id(const std::string &id);
void handle_name(const std::string &name);
void handle_coordinates(const std::vector<uint32_t> &coordinates);
void handle_state(uint32_t state);
void handle_capabilities(uint32_t capabilities);
void handle_removed();
// gdk events
bool handle_clicked(const GdkEventButton *button) const;
private:
bool has_state(uint32_t state) const { return (state_ & state) == state; }
std::string icon();
WorkspaceManager &workspace_manager_;
ext_workspace_handle_v1 *ext_handle_ = nullptr;
uint32_t id_;
uint32_t state_ = 0;
std::string workspace_id_;
std::string name_;
std::vector<uint32_t> coordinates_;
bool active_only_ = false;
bool ignore_hidden_ = true;
std::string format_;
bool with_icon_ = false;
static std::map<std::string, std::string> icon_map_;
std::string on_click_action_;
std::string on_click_middle_action_;
std::string on_click_right_action_;
Gtk::Button button_;
Gtk::Box content_;
Gtk::Label label_;
};
} // namespace waybar::modules::ext

View File

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

View File

@@ -17,9 +17,13 @@ class EventHandler {
virtual ~EventHandler() = default;
};
/// If you want to use the Hyprland IPC, simply use IPC::inst() to get the singleton instance.
/// Do not create multiple instances.
class IPC {
protected:
IPC(); // use IPC::inst() instead.
public:
IPC();
~IPC();
static IPC& inst();
@@ -42,9 +46,7 @@ class IPC {
util::JsonParser parser_;
std::list<std::pair<std::string, EventHandler*>> callbacks_;
int socketfd_; // the hyprland socket file descriptor
bool running_ = true;
pid_t socketOwnerPid_;
bool running_ = true; // the ipcThread will stop running when this is false
};
inline bool modulesReady = false;
inline std::unique_ptr<IPC> gIPC;
}; // namespace waybar::modules::hyprland

View File

@@ -7,7 +7,6 @@
#include "AAppIconLabel.hpp"
#include "bar.hpp"
#include "modules/hyprland/backend.hpp"
#include "util/json.hpp"
namespace waybar::modules::hyprland {
@@ -26,8 +25,8 @@ class WindowCount : public waybar::AAppIconLabel, public EventHandler {
static auto parse(const Json::Value& value) -> Workspace;
};
static auto getActiveWorkspace(const std::string&) -> Workspace;
static auto getActiveWorkspace() -> Workspace;
auto getActiveWorkspace(const std::string&) -> Workspace;
auto getActiveWorkspace() -> Workspace;
void onEvent(const std::string& ev) override;
void queryActiveWorkspace();
void setClass(const std::string&, bool enable);
@@ -36,6 +35,7 @@ class WindowCount : public waybar::AAppIconLabel, public EventHandler {
std::mutex mutex_;
const Bar& bar_;
Workspace workspace_;
IPC& m_ipc;
};
} // namespace waybar::modules::hyprland

View File

@@ -26,18 +26,31 @@ namespace waybar::modules::hyprland {
class Workspaces;
struct WindowRepr {
std::string address;
std::string window_class;
std::string window_title;
std::string repr_rewrite;
bool isActive = false;
public:
bool empty() const { return address.empty(); }
void setActive(bool value) { isActive = value; }
};
class WindowCreationPayload {
public:
WindowCreationPayload(std::string workspace_name, WindowAddress window_address,
std::string window_repr);
WindowRepr window_repr);
WindowCreationPayload(std::string workspace_name, WindowAddress window_address,
std::string window_class, std::string window_title);
std::string window_class, std::string window_title, bool is_active);
WindowCreationPayload(Json::Value const& client_data);
int incrementTimeSpentUncreated();
bool isEmpty(Workspaces& workspace_manager);
bool reprIsReady() const { return std::holds_alternative<Repr>(m_window); }
std::string repr(Workspaces& workspace_manager);
WindowRepr repr(Workspaces& workspace_manager);
void setActive(bool value) { m_isActive = value; }
std::string getWorkspaceName() const { return m_workspaceName; }
WindowAddress getAddress() const { return m_windowAddress; }
@@ -48,12 +61,13 @@ class WindowCreationPayload {
void clearAddr();
void clearWorkspaceName();
using Repr = std::string;
using Repr = WindowRepr;
using ClassAndTitle = std::pair<std::string, std::string>;
std::variant<Repr, ClassAndTitle> m_window;
WindowAddress m_windowAddress;
std::string m_workspaceName;
bool m_isActive = false;
int m_timeSpentUncreated = 0;
};

View File

@@ -42,7 +42,6 @@ class Workspace {
bool isPersistentConfig() const { return m_isPersistentConfig; };
bool isPersistentRule() const { return m_isPersistentRule; };
bool isVisible() const { return m_isVisible; };
bool isEmpty() const { return m_windows == 0; };
bool isUrgent() const { return m_isUrgent; };
bool handleClicked(GdkEventButton* bt) const;
@@ -54,15 +53,18 @@ class Workspace {
void setWindows(uint value) { m_windows = value; };
void setName(std::string const& value) { m_name = value; };
void setOutput(std::string const& value) { m_output = value; };
bool containsWindow(WindowAddress const& addr) const { return m_windowMap.contains(addr); }
bool containsWindow(WindowAddress const& addr) const {
return std::ranges::any_of(m_windowMap,
[&addr](const auto& window) { return window.address == addr; });
};
void insertWindow(WindowCreationPayload create_window_payload);
std::string removeWindow(WindowAddress const& addr);
void initializeWindowMap(const Json::Value& clients_data);
void setActiveWindow(WindowAddress const& addr);
bool onWindowOpened(WindowCreationPayload const& create_window_payload);
std::optional<std::string> closeWindow(WindowAddress const& addr);
std::optional<WindowRepr> closeWindow(WindowAddress const& addr);
void update(const std::string& format, const std::string& icon);
void update(const std::string& workspace_icon);
private:
Workspaces& m_workspaceManager;
@@ -78,11 +80,17 @@ class Workspace {
bool m_isUrgent = false;
bool m_isVisible = false;
std::map<WindowAddress, std::string> m_windowMap;
std::vector<WindowRepr> m_windowMap;
Gtk::Button m_button;
Gtk::Box m_content;
Gtk::Label m_label;
Gtk::Label m_labelBefore;
Gtk::Label m_labelAfter;
bool isEmpty() const;
void updateTaskbar(const std::string& workspace_icon);
bool handleClick(const GdkEventButton* event_button, WindowAddress const& addr) const;
bool shouldSkipWindow(const WindowRepr& window_repr) const;
IPC& m_ipc;
};

View File

@@ -1,6 +1,7 @@
#pragma once
#include <gtkmm/button.h>
#include <gtkmm/enums.h>
#include <gtkmm/label.h>
#include <json/value.h>
@@ -18,6 +19,7 @@
#include "modules/hyprland/windowcreationpayload.hpp"
#include "modules/hyprland/workspace.hpp"
#include "util/enum.hpp"
#include "util/icon_loader.hpp"
#include "util/regex_collection.hpp"
using WindowAddress = std::string;
@@ -39,14 +41,29 @@ class Workspaces : public AModule, public EventHandler {
auto specialVisibleOnly() const -> bool { return m_specialVisibleOnly; }
auto persistentOnly() const -> bool { return m_persistentOnly; }
auto moveToMonitor() const -> bool { return m_moveToMonitor; }
auto enableTaskbar() const -> bool { return m_enableTaskbar; }
auto taskbarWithIcon() const -> bool { return m_taskbarWithIcon; }
auto getBarOutput() const -> std::string { return m_bar.output->name; }
auto formatBefore() const -> std::string { return m_formatBefore; }
auto formatAfter() const -> std::string { return m_formatAfter; }
auto taskbarFormatBefore() const -> std::string { return m_taskbarFormatBefore; }
auto taskbarFormatAfter() const -> std::string { return m_taskbarFormatAfter; }
auto taskbarIconSize() const -> int { return m_taskbarIconSize; }
auto taskbarOrientation() const -> Gtk::Orientation { return m_taskbarOrientation; }
auto taskbarReverseDirection() const -> bool { return m_taskbarReverseDirection; }
auto onClickWindow() const -> std::string { return m_onClickWindow; }
auto getIgnoredWindows() const -> std::vector<std::regex> { return m_ignoreWindows; }
enum class ActiveWindowPosition { NONE, FIRST, LAST };
auto activeWindowPosition() const -> ActiveWindowPosition { return m_activeWindowPosition; }
std::string getRewrite(std::string window_class, std::string window_title);
std::string& getWindowSeparator() { return m_formatWindowSeparator; }
bool isWorkspaceIgnored(std::string const& workspace_name);
bool windowRewriteConfigUsesTitle() const { return m_anyWindowRewriteRuleUsesTitle; }
const IconLoader& iconLoader() const { return m_iconLoader; }
private:
void onEvent(const std::string& e) override;
@@ -70,6 +87,7 @@ class Workspaces : public AModule, public EventHandler {
auto populateIgnoreWorkspacesConfig(const Json::Value& config) -> void;
auto populateFormatWindowSeparatorConfig(const Json::Value& config) -> void;
auto populateWindowRewriteConfig(const Json::Value& config) -> void;
auto populateWorkspaceTaskbarConfig(const Json::Value& config) -> void;
void registerIpc();
@@ -92,6 +110,7 @@ class Workspaces : public AModule, public EventHandler {
void onWindowMoved(std::string const& payload);
void onWindowTitleEvent(std::string const& payload);
void onActiveWindowChanged(WindowAddress const& payload);
void onConfigReloaded();
@@ -131,7 +150,7 @@ class Workspaces : public AModule, public EventHandler {
// 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;
std::map<WindowAddress, WindowRepr, std::less<>> m_orphanWindowMap;
enum class SortMethod { ID, NAME, NUMBER, SPECIAL_CENTERED, DEFAULT };
util::EnumParser<SortMethod> m_enumParser;
@@ -142,7 +161,8 @@ class Workspaces : public AModule, public EventHandler {
{"SPECIAL-CENTERED", SortMethod::SPECIAL_CENTERED},
{"DEFAULT", SortMethod::DEFAULT}};
std::string m_format;
std::string m_formatBefore;
std::string m_formatAfter;
std::map<std::string, std::string> m_iconsMap;
util::RegexCollection m_windowRewriteRules;
@@ -158,7 +178,28 @@ class Workspaces : public AModule, public EventHandler {
std::vector<std::string> m_workspacesToRemove;
std::vector<WindowCreationPayload> m_windowsToCreate;
IconLoader m_iconLoader;
bool m_enableTaskbar = false;
bool m_updateActiveWindow = false;
bool m_taskbarWithIcon = false;
bool m_taskbarWithTitle = false;
std::string m_taskbarFormatBefore;
std::string m_taskbarFormatAfter;
int m_taskbarIconSize = 16;
Gtk::Orientation m_taskbarOrientation = Gtk::ORIENTATION_HORIZONTAL;
bool m_taskbarReverseDirection = false;
util::EnumParser<ActiveWindowPosition> m_activeWindowEnumParser;
ActiveWindowPosition m_activeWindowPosition = ActiveWindowPosition::NONE;
std::map<std::string, ActiveWindowPosition> m_activeWindowPositionMap = {
{"NONE", ActiveWindowPosition::NONE},
{"FIRST", ActiveWindowPosition::FIRST},
{"LAST", ActiveWindowPosition::LAST},
};
std::string m_onClickWindow;
std::string m_currentActiveWindowAddress;
std::vector<std::regex> m_ignoreWorkspaces;
std::vector<std::regex> m_ignoreWindows;
std::mutex m_mutex;
const Bar& m_bar;

View File

@@ -31,7 +31,7 @@ class Image : public AModule {
std::string path_;
std::string tooltip_;
int size_;
int interval_;
std::chrono::milliseconds interval_;
util::command::res output_;
util::SleeperThread thread_;

View File

@@ -9,6 +9,7 @@
#include <sys/epoll.h>
#include <optional>
#include <vector>
#include "ALabel.hpp"
#include "util/sleeper_thread.hpp"
@@ -27,8 +28,8 @@ class Network : public ALabel {
auto update() -> void override;
private:
static const uint8_t MAX_RETRY = 5;
static const uint8_t EPOLL_MAX = 200;
static const uint8_t MAX_RETRY{5};
static const uint8_t EPOLL_MAX{200};
static int handleEvents(struct nl_msg*, void*);
static int handleEventsDone(struct nl_msg*, void*);
@@ -44,44 +45,44 @@ class Network : public ALabel {
void parseFreq(struct nlattr**);
void parseBssid(struct nlattr**);
bool associatedOrJoined(struct nlattr**);
bool checkInterface(std::string name);
bool matchInterface(const std::string& ifname, const std::vector<std::string>& altnames,
std::string& matched) const;
auto getInfo() -> void;
const std::string getNetworkState() const;
void clearIface();
bool wildcardMatch(const std::string& pattern, const std::string& text) const;
std::optional<std::pair<unsigned long long, unsigned long long>> readBandwidthUsage();
int ifid_;
ip_addr_pref addr_pref_;
struct sockaddr_nl nladdr_ = {0};
struct nl_sock* sock_ = nullptr;
struct nl_sock* ev_sock_ = nullptr;
int efd_;
int ev_fd_;
int nl80211_id_;
int ifid_{-1};
ip_addr_pref addr_pref_{ip_addr_pref::IPV4};
struct sockaddr_nl nladdr_{0};
struct nl_sock* sock_{nullptr};
struct nl_sock* ev_sock_{nullptr};
int efd_{-1};
int ev_fd_{-1};
int nl80211_id_{-1};
std::mutex mutex_;
bool want_route_dump_;
bool want_link_dump_;
bool want_addr_dump_;
bool dump_in_progress_;
bool is_p2p_;
bool want_route_dump_{false};
bool want_link_dump_{false};
bool want_addr_dump_{false};
bool dump_in_progress_{false};
bool is_p2p_{false};
unsigned long long bandwidth_down_total_;
unsigned long long bandwidth_up_total_;
unsigned long long bandwidth_down_total_{0};
unsigned long long bandwidth_up_total_{0};
std::string state_;
std::string essid_;
std::string bssid_;
bool carrier_;
bool carrier_{false};
std::string ifname_;
std::string ipaddr_;
std::string ipaddr6_;
std::string gwaddr_;
std::string netmask_;
std::string netmask6_;
int cidr_;
int cidr6_;
int cidr_{0};
int cidr6_{0};
int32_t signal_strength_dbm_;
uint8_t signal_strength_;
std::string signal_strength_app_;
@@ -90,9 +91,9 @@ class Network : public ALabel {
util::SleeperThread thread_;
util::SleeperThread thread_timer_;
#ifdef WANT_RFKILL
util::Rfkill rfkill_;
util::Rfkill rfkill_{RFKILL_TYPE_WLAN};
#endif
float frequency_;
float frequency_{0};
};
} // namespace waybar::modules

View File

@@ -33,6 +33,7 @@ class Language : public ALabel, public EventHandler {
std::vector<Layout> layouts_;
unsigned current_idx_;
std::string last_short_name_;
};
} // namespace waybar::modules::niri

View File

@@ -24,6 +24,7 @@ class Layout : public waybar::ALabel {
private:
const waybar::Bar &bar_;
std::string name_;
struct wl_output *output_; // stores the output this module belongs to
struct wl_output *focused_output_; // stores the currently focused output
struct zriver_output_status_v1 *output_status_;

View File

@@ -21,6 +21,7 @@ class Tags : public waybar::AModule {
void handle_view_tags(struct wl_array *tags);
void handle_urgent_tags(uint32_t tags);
void handle_show();
void handle_primary_clicked(uint32_t tag);
bool handle_button_press(GdkEventButton *event_button, uint32_t tag);

View File

@@ -26,7 +26,7 @@ struct ToolTip {
class Item : public sigc::trackable {
public:
Item(const std::string&, const std::string&, const Json::Value&, const Bar&);
~Item() = default;
~Item();
std::string bus_name;
std::string object_path;

View File

@@ -21,6 +21,7 @@ class Tray : public AModule {
void onRemove(std::unique_ptr<Item>& item);
static inline std::size_t nb_hosts_ = 0;
bool show_passive_ = false;
Gtk::Box box_;
SNI::Watcher::singleton watcher_;
SNI::Host host_;

View File

@@ -22,6 +22,8 @@ class Wireplumber : public ALabel {
void activatePlugins();
static void updateVolume(waybar::modules::Wireplumber* self, uint32_t id);
static void updateNodeName(waybar::modules::Wireplumber* self, uint32_t id);
static void updateSourceVolume(waybar::modules::Wireplumber* self, uint32_t id);
static void updateSourceName(waybar::modules::Wireplumber* self, uint32_t id); // NEW
static void onPluginActivated(WpObject* p, GAsyncResult* res, waybar::modules::Wireplumber* self);
static void onDefaultNodesApiLoaded(WpObject* p, GAsyncResult* res,
waybar::modules::Wireplumber* self);
@@ -46,7 +48,12 @@ class Wireplumber : public ALabel {
double min_step_;
uint32_t node_id_{0};
std::string node_name_;
std::string source_name_;
gchar* type_;
uint32_t source_node_id_;
bool source_muted_;
double source_volume_;
gchar* default_source_name_;
};
} // namespace waybar::modules

View File

@@ -19,6 +19,7 @@
#include "bar.hpp"
#include "client.hpp"
#include "giomm/desktopappinfo.h"
#include "util/icon_loader.hpp"
#include "util/json.hpp"
#include "wlr-foreign-toplevel-management-unstable-v1-client-protocol.h"
@@ -89,9 +90,6 @@ class Task {
std::string state_string(bool = false) const;
void set_minimize_hint();
void on_button_size_allocated(Gtk::Allocation &alloc);
void set_app_info_from_app_id_list(const std::string &app_id_list);
bool image_load_icon(Gtk::Image &image, const Glib::RefPtr<Gtk::IconTheme> &icon_theme,
Glib::RefPtr<Gio::DesktopAppInfo> app_info, int size);
void hide_if_ignored();
public:
@@ -153,7 +151,7 @@ class Taskbar : public waybar::AModule {
Gtk::Box box_;
std::vector<TaskPtr> tasks_;
std::vector<Glib::RefPtr<Gtk::IconTheme>> icon_themes_;
IconLoader icon_loader_;
std::unordered_set<std::string> ignore_list_;
std::map<std::string, std::string> app_ids_replace_map_;
@@ -178,7 +176,7 @@ class Taskbar : public waybar::AModule {
bool show_output(struct wl_output *) const;
bool all_outputs() const;
const std::vector<Glib::RefPtr<Gtk::IconTheme>> &icon_themes() const;
const IconLoader &icon_loader() const;
const std::unordered_set<std::string> &ignore_list() const;
const std::map<std::string, std::string> &app_ids_replace_map() const;
};

View File

@@ -1,172 +0,0 @@
#pragma once
#include <fmt/format.h>
#include <gtkmm/button.h>
#include <gtkmm/image.h>
#include <gtkmm/label.h>
#include <functional>
#include <map>
#include <memory>
#include <vector>
#include "AModule.hpp"
#include "bar.hpp"
#include "ext-workspace-unstable-v1-client-protocol.h"
namespace waybar::modules::wlr {
class WorkspaceManager;
class WorkspaceGroup;
class Workspace {
public:
Workspace(const waybar::Bar &bar, const Json::Value &config, WorkspaceGroup &workspace_group,
zext_workspace_handle_v1 *workspace, uint32_t id, std::string name);
~Workspace();
auto update() -> void;
auto id() const -> uint32_t { return id_; }
auto is_active() const -> bool { return state_ & static_cast<uint32_t>(State::ACTIVE); }
auto is_urgent() const -> bool { return state_ & static_cast<uint32_t>(State::URGENT); }
auto is_hidden() const -> bool { return state_ & static_cast<uint32_t>(State::HIDDEN); }
auto is_empty() const -> bool { return state_ & static_cast<uint32_t>(State::EMPTY); }
auto is_persistent() const -> bool { return persistent_; }
// wlr stuff
auto handle_name(const std::string &name) -> void;
auto handle_coordinates(const std::vector<uint32_t> &coordinates) -> void;
auto handle_state(const std::vector<uint32_t> &state) -> void;
auto handle_remove() -> void;
auto make_persistent() -> void;
auto handle_duplicate() -> void;
auto handle_done() -> void;
auto handle_clicked(GdkEventButton *bt) -> bool;
auto show() -> void;
auto hide() -> void;
auto get_button_ref() -> Gtk::Button & { return button_; }
auto get_name() -> std::string & { return name_; }
auto get_coords() -> std::vector<uint32_t> & { return coordinates_; }
enum class State {
ACTIVE = (1 << 0),
URGENT = (1 << 1),
HIDDEN = (1 << 2),
EMPTY = (1 << 3),
};
private:
auto get_icon() -> std::string;
const Bar &bar_;
const Json::Value &config_;
WorkspaceGroup &workspace_group_;
// wlr stuff
zext_workspace_handle_v1 *workspace_handle_;
uint32_t state_ = 0;
uint32_t id_;
std::string name_;
std::vector<uint32_t> coordinates_;
static std::map<std::string, std::string> icons_map_;
std::string format_;
bool with_icon_ = false;
bool persistent_ = false;
Gtk::Button button_;
Gtk::Box content_;
Gtk::Label label_;
};
class WorkspaceGroup {
public:
WorkspaceGroup(const waybar::Bar &bar, Gtk::Box &box, const Json::Value &config,
WorkspaceManager &manager, zext_workspace_group_handle_v1 *workspace_group_handle,
uint32_t id);
~WorkspaceGroup();
auto update() -> void;
auto id() const -> uint32_t { return id_; }
auto is_visible() const -> bool;
auto remove_workspace(uint32_t id_) -> void;
auto active_only() const -> bool;
auto creation_delayed() const -> bool;
auto workspaces() -> std::vector<std::unique_ptr<Workspace>> & { return workspaces_; }
auto persistent_workspaces() -> std::vector<std::string> & { return persistent_workspaces_; }
auto sort_workspaces() -> void;
auto set_need_to_sort() -> void { need_to_sort = true; }
auto add_button(Gtk::Button &button) -> void;
auto remove_button(Gtk::Button &button) -> void;
auto fill_persistent_workspaces() -> void;
auto create_persistent_workspaces() -> void;
// wlr stuff
auto handle_workspace_create(zext_workspace_handle_v1 *workspace_handle) -> void;
auto handle_remove() -> void;
auto handle_output_enter(wl_output *output) -> void;
auto handle_output_leave() -> void;
auto handle_done() -> void;
auto commit() -> void;
private:
static uint32_t workspace_global_id;
const waybar::Bar &bar_;
Gtk::Box &box_;
const Json::Value &config_;
WorkspaceManager &workspace_manager_;
// wlr stuff
zext_workspace_group_handle_v1 *workspace_group_handle_;
wl_output *output_ = nullptr;
uint32_t id_;
std::vector<std::unique_ptr<Workspace>> workspaces_;
bool need_to_sort = false;
std::vector<std::string> persistent_workspaces_;
bool persistent_created_ = false;
};
class WorkspaceManager : public AModule {
public:
WorkspaceManager(const std::string &id, const waybar::Bar &bar, const Json::Value &config);
~WorkspaceManager() override;
auto update() -> void override;
auto all_outputs() const -> bool { return all_outputs_; }
auto active_only() const -> bool { return active_only_; }
auto workspace_comparator() const
-> std::function<bool(std::unique_ptr<Workspace> &, std::unique_ptr<Workspace> &)>;
auto creation_delayed() const -> bool { return creation_delayed_; }
auto sort_workspaces() -> void;
auto remove_workspace_group(uint32_t id_) -> void;
// wlr stuff
auto register_manager(wl_registry *registry, uint32_t name, uint32_t version) -> void;
auto handle_workspace_group_create(zext_workspace_group_handle_v1 *workspace_group_handle)
-> void;
auto handle_done() -> void;
auto handle_finished() -> void;
auto commit() -> void;
private:
const waybar::Bar &bar_;
Gtk::Box box_;
std::vector<std::unique_ptr<WorkspaceGroup>> groups_;
// wlr stuff
zext_workspace_manager_v1 *workspace_manager_ = nullptr;
static uint32_t group_global_id;
bool sort_by_name_ = true;
bool sort_by_coordinates_ = true;
bool sort_by_number_ = false;
bool all_outputs_ = false;
bool active_only_ = false;
bool creation_delayed_ = false;
};
} // namespace waybar::modules::wlr

View File

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

View File

@@ -11,6 +11,11 @@
#include <type_traits>
#include <utility>
#ifdef __OpenBSD__
#define SIGRTMIN SIGUSR1 - 1
#define SIGRTMAX SIGUSR1 + 1
#endif
namespace waybar {
/**

View File

@@ -0,0 +1,34 @@
#pragma once
#include <gdkmm/general.h>
#include <gio/gdesktopappinfo.h>
#include <giomm/desktopappinfo.h>
#include <glibmm/fileutils.h>
#include <gtkmm/image.h>
#include <spdlog/spdlog.h>
#include <string>
#include <vector>
#include "util/gtk_icon.hpp"
class IconLoader {
private:
std::vector<Glib::RefPtr<Gtk::IconTheme>> custom_icon_themes_;
Glib::RefPtr<Gtk::IconTheme> default_icon_theme_ = Gtk::IconTheme::get_default();
static std::vector<std::string> search_prefix();
static Glib::RefPtr<Gio::DesktopAppInfo> get_app_info_by_name(const std::string &app_id);
static Glib::RefPtr<Gio::DesktopAppInfo> get_desktop_app_info(const std::string &app_id);
static Glib::RefPtr<Gdk::Pixbuf> load_icon_from_file(std::string const &icon_path, int size);
static std::string get_icon_name_from_icon_theme(const Glib::RefPtr<Gtk::IconTheme> &icon_theme,
const std::string &app_id);
static bool image_load_icon(Gtk::Image &image, const Glib::RefPtr<Gtk::IconTheme> &icon_theme,
Glib::RefPtr<Gio::DesktopAppInfo> app_info, int size);
public:
void add_custom_icon_theme(const std::string &theme_name);
bool image_load_icon(Gtk::Image &image, Glib::RefPtr<Gio::DesktopAppInfo> app_info,
int size) const;
static Glib::RefPtr<Gio::DesktopAppInfo> get_app_info_from_app_id_list(
const std::string &app_id_list);
};

View File

@@ -30,15 +30,16 @@ class JsonParser {
std::istringstream jsonStream(modifiedJsonStr);
std::string errs;
if (!Json::parseFromStream(m_readerBuilder, jsonStream, &root, &errs)) {
// Use local CharReaderBuilder for thread safety - the IPC singleton's
// parser can be called concurrently from multiple module threads
Json::CharReaderBuilder readerBuilder;
if (!Json::parseFromStream(readerBuilder, jsonStream, &root, &errs)) {
throw std::runtime_error("Error parsing JSON: " + errs);
}
return root;
}
private:
Json::CharReaderBuilder m_readerBuilder;
static std::string replaceHexadecimalEscape(const std::string& str) {
static std::regex re("\\\\x");
return std::regex_replace(str, re, "\\u00");

View File

@@ -0,0 +1,26 @@
#pragma once
#include <json/value.h>
#include <cstdint>
namespace waybar::util {
enum class KillSignalAction : std::uint8_t {
TOGGLE,
RELOAD,
SHOW,
HIDE,
NOOP,
};
const std::map<std::string, KillSignalAction> userKillSignalActions = {
{"TOGGLE", KillSignalAction::TOGGLE},
{"RELOAD", KillSignalAction::RELOAD},
{"SHOW", KillSignalAction::SHOW},
{"HIDE", KillSignalAction::HIDE},
{"NOOP", KillSignalAction::NOOP}};
const KillSignalAction SIGNALACTION_DEFAULT_SIGUSR1 = KillSignalAction::TOGGLE;
const KillSignalAction SIGNALACTION_DEFAULT_SIGUSR2 = KillSignalAction::RELOAD;
}; // namespace waybar::util

View File

@@ -5,6 +5,8 @@
#include <sigc++/signal.h>
#include <sigc++/trackable.h>
#include <atomic>
namespace waybar::util {
class Rfkill : public sigc::trackable {
@@ -17,7 +19,7 @@ class Rfkill : public sigc::trackable {
private:
enum rfkill_type rfkill_type_;
bool state_ = false;
std::atomic_bool state_ = false;
int fd_ = -1;
bool on_event(Glib::IOCondition cond);

View File

@@ -23,3 +23,26 @@ inline std::string capitalize(const std::string& str) {
[](unsigned char c) { return std::toupper(c); });
return result;
}
inline std::string toLower(const std::string& str) {
std::string result = str;
std::transform(result.begin(), result.end(), result.begin(),
[](unsigned char c) { return std::tolower(c); });
return result;
}
inline std::vector<std::string> split(std::string_view s, std::string_view delimiter,
int max_splits = -1) {
std::vector<std::string> result;
size_t pos = 0;
size_t next_pos = 0;
while ((next_pos = s.find(delimiter, pos)) != std::string::npos) {
result.push_back(std::string(s.substr(pos, next_pos - pos)));
pos = next_pos + delimiter.size();
if (max_splits > 0 && result.size() == static_cast<size_t>(max_splits)) {
break;
}
}
result.push_back(std::string(s.substr(pos)));
return result;
}

View File

@@ -0,0 +1,21 @@
#pragma once
#include <libudev.h>
namespace waybar::util {
struct UdevDeleter {
void operator()(udev *ptr) const { udev_unref(ptr); }
};
struct UdevDeviceDeleter {
void operator()(udev_device *ptr) const { udev_device_unref(ptr); }
};
struct UdevEnumerateDeleter {
void operator()(udev_enumerate *ptr) const { udev_enumerate_unref(ptr); }
};
struct UdevMonitorDeleter {
void operator()(udev_monitor *ptr) const { udev_monitor_unref(ptr); }
};
} // namespace waybar::util

View File

@@ -91,6 +91,11 @@ The *battery* module displays the current capacity and state (eg. charging) of y
typeof: string ++
Command to execute when scrolling up on the module.
*weighted-average*: ++
typeof: bool ++
default: true ++
Option to combine multiple batteries with different capacities.
*on-scroll-down*: ++
typeof: string ++
Command to execute when scrolling down on the module.
@@ -116,7 +121,7 @@ The *battery* module displays the current capacity and state (eg. charging) of y
*menu-file*: ++
typeof: string ++
Location of the menu descriptor file. There need to be an element of type
GtkMenu with id *menu*
GtkMenu with id *menu*.
*menu-actions*: ++
typeof: array ++
@@ -127,6 +132,10 @@ The *battery* module displays the current capacity and state (eg. charging) of y
default: false ++
Enables this module to consume all left over space dynamically.
*events*: ++
typeof: object ++
Specifies commands to be executed on specific battery states. See *EVENTS* section below.
# FORMAT REPLACEMENTS
*{capacity}*: Capacity in percentage
@@ -166,6 +175,19 @@ The *battery* module allows one to define custom formats based on up to two fact
- The state can be addressed as a CSS class in the *style.css*. The name of the CSS class is the *<name>* of the state. Each class gets activated when the current capacity is equal to or below the configured *<value>*.
- Also each state can have its own *format*. Those can be configured via *format-<name>*. Or if you want to differentiate a bit more even as *format-<status>-<state>*. For more information see *custom-formats*.
# EVENTS
Every entry in the *events* object consists of a *<event-name>* (typeof: *string*) and a *<command>* (typeof: *string*). ++
*<event-name>* can be in one of the following formats:
- *on-<status>-<state>*
- *on-<status>-<capacity>*
Where:
- *<status>* is either *charging* or *discharging*,
- *<state>* is the name of one of the states specified in the *states* object,
- *<capacity>* is a battery level value (between *0-100*).
# EXAMPLES
@@ -178,6 +200,11 @@ The *battery* module allows one to define custom formats based on up to two fact
"warning": 30,
"critical": 15
},
"events": {
"on-discharging-warning": "notify-send -u normal 'Low Battery'",
"on-discharging-critical": "notify-send -u critical 'Very Low Battery'",
"on-charging-100": "notify-send -u normal 'Battery Full!'"
},
"format": "{capacity}% {icon}",
"format-icons": ["", "", "", "", ""],
"max-length": 25

View File

@@ -8,6 +8,8 @@ waybar - cava module
*cava* module for karlstav/cava project. See it on github: https://github.com/karlstav/cava.
Module supports two different frontends starting from the 0.15.0 release. The frontend that
will be used is managed by the method parameter in the [output] section of the cava configuration file.
# FILES
@@ -32,6 +34,10 @@ libcava lives in:
:[ string
:[
:< Path where cava configuration file is placed to
|[ *method* \[output\]
:[ string
:[
:< Manages which frontend Waybar cava module should use. Values: raw, sdl_glsl
|[ *framerate*
:[ integer
:[ 30
@@ -43,7 +49,7 @@ libcava lives in:
|[ *sensitivity*
:[ integer
:[ 100
:[ Manual sensitivity in %. It's recommended to be omitted when *autosens* = 1
:[ Manual sensitivity in %. If autosens is enabled, this will only be the initial value. 200 means double height. Accepts only non-negative values
|[ *bars*
:[ integer
:[ 12
@@ -68,7 +74,7 @@ libcava lives in:
:[ string
:[
:[ Widget's text after sleep_timer elapsed (hide_on_silence has to be false)
|[ *method*
|[ *method* \[input\]
:[ string
:[ pulse
:[ Audio capturing method. Possible methods are: pipewire, pulse, alsa, fifo, sndio or shmem
@@ -105,9 +111,9 @@ libcava lives in:
:[ false
:[ Disables or enables the so-called "Monstercat smoothing" with or without "waves"
|[ *noise_reduction*
:[ double
:[ 0.77
:[ Range between 0 - 1. The raw visualization is very noisy, this factor adjusts the integral and gravity filters to keep the signal smooth. 1 - will be very slow and smooth, 0 - will be fast but noisy
:[ integer
:[ 77
:[ Range between 0 - 100. The raw visualization is very noisy, this factor adjusts the integral and gravity filters to keep the signal smooth. 100 will be very slow and smooth, 0 will be fast but noisy
|[ *input_delay*
:[ integer
:[ 2
@@ -119,11 +125,11 @@ libcava lives in:
|[ *data_format*
:[ string
:[ asci
:[ It's impossible to set it. Waybar sets it to = asci for internal needs
:[ Raw data format. Can be 'binary' or 'ascii'
|[ *raw_target*
:[ string
:[ /dev/stdout
:[ It's impossible to set it. Waybar sets it to = /dev/stdout for internal needs
:[ Raw output target. A fifo will be created if target does not exist
|[ *menu*
:[ string
:[
@@ -136,6 +142,50 @@ libcava lives in:
:[ array
:[
:[ The actions corresponding to the buttons of the menu.
|[ *bar_spacing*
:[ integer
:[
:[ Bars' space between bars in number of characters
|[ *bar_width*
:[ integer
:[
:[ Bars' width between bars in number of characters
|[ *bar_height*
:[ integer
:[
:[ Useless. bar_height is only used for output in "noritake" format
|[ *background*
:[ string
:[
:[ GLSL actual. Support hex code colors only. Must be within ''
|[ *foreground*
:[ string
:[
:[ GLSL actual. Support hex code colors only. Must be within ''
|[ *gradient*
:[ integer
:[ 0
:[ GLSL actual. Gradient mode(0/1 - on/off)
|[ *gradient_count*
:[ integer
:[ 0
:[ GLSL actual. The count of colors for the gradient
|[ *gradient_color_N*
:[ string
:[
:[ GLSL actual. N - the number of the gradient color between 1 and 8. Only hex defined colors are supported. Must be within ''
|[ *sdl_width*
:[ integer
:[
:[ GLSL actual. Manages the width of the waybar cava GLSL frontend module
|[ *sdl_height*
:[ integer
:[
:[ GLSL actual. Manages the height of the waybar cava GLSL frontend module
|[ *continuous_rendering*
:[ integer
:[ 0
:[ GLSL actual. Keep rendering even if no audio. Recommended to set to 1
Configuration can be provided as:
- The only cava configuration file which is provided through *cava_config*. The rest configuration can be skipped
@@ -153,16 +203,17 @@ Configuration can be provided as:
- iniparser
- fftw3
- epoxy (GLSL frontend only)
# SOLVING ISSUES
. On start Waybar throws an exception "error while loading shared libraries: libcava.so: cannot open shared object file: No such file or directory".
It might happen when libcava for some reason hasn't been registered in the system. sudo ldconfig should help
. Waybar is starting but cava module doesn't react to the music
1. In such cases at first need to make sure usual cava application is working as well
2. If so, need to comment all configuration options. Uncomment cava_config and provide the path to the working cava config
3. You might set too huge or too small input_delay. Try to setup to 4 seconds, restart waybar, and check again 4 seconds past. Usual even on weak machines it should be enough
4. You might accidentally switch action mode to pause mode
1. In such cases at first need to make sure usual cava application is working as well
2. If so, need to comment all configuration options. Uncomment cava_config and provide the path to the working cava config
3. You might set too huge or too small input_delay. Try to setup to 4 seconds, restart waybar, and check again 4 seconds past. Usual even on weak machines it should be enough
4. You might accidentally switch action mode to pause mode
# RISING ISSUES
@@ -205,3 +256,453 @@ In case when cava releases new version and you're wanna get it, it should be rai
- *#cava*
- *#cava.silent* Applied after no sound has been detected for sleep_timer seconds
- *#cava.updated* Applied when a new frame is shown
# FRONTENDS
## RAW
The cava raw frontend uses ASCII characters to visualize incoming audio data. Each ASCII symbol position corresponds to the value of the audio power pulse.
Under the hood:
```
. Incoming audio power pulse list is : 12684
. Configured array of ASCII codes is: ["▁", "▂", "▃", "▄", "▅", "▆", "▇", "█" ]. See `format-icons` https://github.com/Alexays/Waybar/wiki/Module:-Cava#example
```
As a result cava frontend will give ▁▂▆█▄
Examples:
waybar config
```
"cava": {
"cava_config": "$XDG_CONFIG_HOME/cava/waybar_raw.conf",
"input_delay": 2,
"format-icons" : ["▁", "▂", "▃", "▄", "▅", "▆", "▇", "█" ],
"actions": {
"on-click-right": "mode"
}
},
```
waybar_raw.conf
```
## Configuration file for CAVA.
# Remove the ; to change parameters.
[general]
# Smoothing mode. Can be 'normal', 'scientific' or 'waves'. DEPRECATED as of 0.6.0
# Accepts only non-negative values.
# 'autosens' will attempt to decrease sensitivity if the bars peak. 1 = on, 0 = off
# new as of 0.6.0 autosens of low values (dynamic range)
# 'overshoot' allows bars to overshoot (in % of terminal height) without initiating autosens. DEPRECATED as of 0.6.0
# Manual sensitivity in %. If autosens is enabled, this will only be the initial value.
# 200 means double height. Accepts only non-negative values.
# The number of bars (0-512). 0 sets it to auto (fill up console).
# Bars' width and space between bars in number of characters.
bars = 12
# bar_height is only used for output in "noritake" format
# For SDL width and space between bars is in pixels, defaults are:
# sdl_glsl have these default values, they are only used to calculate max number of bars.
# Lower and higher cutoff frequencies for lowest and highest bars
# the bandwidth of the visualizer.
# Note: there is a minimum total bandwidth of 43Mhz x number of bars.
# Cava will automatically increase the higher cutoff if a too low band is specified.
# Seconds with no input before cava goes to sleep mode. Cava will not perform FFT or drawing and
# only check for input once per second. Cava will wake up once input is detected. 0 = disable.
sleep_timer = 5
[input]
# Audio capturing method. Possible methods are: 'fifo', 'portaudio', 'pipewire', 'alsa', 'pulse', 'sndio', 'oss', 'jack' or 'shmem'
# Defaults to 'oss', 'pipewire', 'sndio', 'jack', 'pulse', 'alsa', 'portaudio' or 'fifo', in that order, dependent on what support cava was built with.
# On Mac it defaults to 'portaudio' or 'fifo'
# On windows this is automatic and no input settings are needed.
#
# All input methods uses the same config variable 'source'
# to define where it should get the audio.
#
# For pulseaudio and pipewire 'source' will be the source. Default: 'auto', which uses the monitor source of the default sink
# (all pulseaudio sinks(outputs) have 'monitor' sources(inputs) associated with them).
#
# For pipewire 'source' will be the object name or object.serial of the device to capture from.
# Both input and output devices are supported.
#
# For alsa 'source' will be the capture device.
# For fifo 'source' will be the path to fifo-file.
# For shmem 'source' will be /squeezelite-AA:BB:CC:DD:EE:FF where 'AA:BB:CC:DD:EE:FF' will be squeezelite's MAC address
#
# For sndio 'source' will be a raw recording audio descriptor or a monitoring sub-device, e.g. 'rsnd/2' or 'snd/1'. Default: 'default'.
# README.md contains further information on how to setup CAVA for sndio.
#
# For oss 'source' will be the path to a audio device, e.g. '/dev/dsp2'. Default: '/dev/dsp', i.e. the default audio device.
# README.md contains further information on how to setup CAVA for OSS on FreeBSD.
#
# For jack 'source' will be the name of the JACK server to connect to, e.g. 'foobar'. Default: 'default'.
# README.md contains further information on how to setup CAVA for JACK.
#
# The options 'sample_rate', 'sample_bits', 'channels' and 'autoconnect' can be configured for some input methods:
# sample_rate: fifo, pipewire, sndio, oss
# sample_bits: fifo, pipewire, sndio, oss
# channels: sndio, oss, jack
# autoconnect: jack
# Other methods ignore these settings.
#
# For 'sndio' and 'oss' they are only preferred values, i.e. if the values are not supported
# by the chosen audio device, the device will use other supported values instead.
# Example: 48000, 32 and 2, but the device only supports 44100, 16 and 1, then it
# will use 44100, 16 and 1.
#
[output]
# Output method. Can be 'ncurses', 'noncurses', 'raw', 'noritake', 'sdl'
# or 'sdl_glsl'.
# 'noncurses' (default) uses a buffer and cursor movements to only print
# changes from frame to frame in the terminal. Uses less resources and is less
# prone to tearing (vsync issues) than 'ncurses'.
#
# 'raw' is an 8 or 16 bit (configurable via the 'bit_format' option) data
# stream of the bar heights that can be used to send to other applications.
# 'raw' defaults to 200 bars, which can be adjusted in the 'bars' option above.
#
# 'noritake' outputs a bitmap in the format expected by a Noritake VFD display
# in graphic mode. It only support the 3000 series graphical VFDs for now.
#
# 'sdl' uses the Simple DirectMedia Layer to render in a graphical context.
# 'sdl_glsl' uses SDL to create an OpenGL context. Write your own shaders or
# use one of the predefined ones.
method = raw
# Orientation of the visualization. Can be 'bottom', 'top', 'left', 'right' or
# 'horizontal'. Default is 'bottom'. 'left and 'right' are only supported on sdl
# and ncruses output. 'horizontal' (bars go up and down from center) is only supported
# on noncurses output.
# Note: many fonts have weird or missing glyphs for characters used in orientations
# other than 'bottom', which can make output not look right.
# Visual channels. Can be 'stereo' or 'mono'.
# 'stereo' mirrors both channels with low frequencies in center.
# 'mono' outputs left to right lowest to highest frequencies.
# 'mono_option' set mono to either take input from 'left', 'right' or 'average'.
# set 'reverse' to 1 to display frequencies the other way around.
# Raw output target. A fifo will be created if target does not exist.
raw_target = /dev/stdout
# Raw data format. Can be 'binary' or 'ascii'.
data_format = ascii
# Binary bit format, can be '8bit' (0-255) or '16bit' (0-65530).
# Ascii max value. In 'ascii' mode range will run from 0 to value specified here
# Ascii delimiters. In ascii format each bar and frame is separated by a delimiters.
# Use decimal value in ascii table (i.e. 59 = ';' and 10 = '\n' (line feed)).
bar_delimiter = 0
# sdl window size and position. -1,-1 is centered.
# set label on bars on the x-axis. Can be 'frequency' or 'none'. Default: 'none'
# 'frequency' displays the lower cut off frequency of the bar above.
# Only supported on ncurses and noncurses output.
# enable synchronized sync. 1 = on, 0 = off
# removes flickering in alacritty terminal emulator.
# defaults to off since the behaviour in other terminal emulators is unknown
# Shaders for sdl_glsl, located in $HOME/.config/cava/shaders
; for glsl output mode, keep rendering even if no audio
# disable console blank (screen saver) in tty
# (Not supported on FreeBSD)
# show a flat bar at the bottom of the screen when idle, 1 = on, 0 = off
# show waveform instead of frequency spectrum, 1 = on, 0 = off
[color]
# Colors can be one of seven predefined: black, blue, cyan, green, magenta, red, white, yellow.
# Or defined by hex code '#xxxxxx' (hex code must be within ''). User defined colors requires
# a terminal that can change color definitions such as Gnome-terminal or rxvt.
# default is to keep current terminal color
# SDL and sdl_glsl only support hex code colors, these are the default:
# Gradient mode, only hex defined colors are supported,
# background must also be defined in hex or remain commented out. 1 = on, 0 = off.
# You can define as many as 8 different colors. They range from bottom to top of screen
[smoothing]
# Disables or enables the so-called "Monstercat smoothing" with or without "waves". Set to 0 to disable.
# Noise reduction, int 0 - 100. default 77
# the raw visualization is very noisy, this factor adjusts the integral and gravity filters to keep the signal smooth
# 100 will be very slow and smooth, 0 will be fast but noisy.
[eq]
# This one is tricky. You can have as much keys as you want.
# Remember to uncomment more than one key! More keys = more precision.
# Look at readme.md on github for further explanations and examples.
```
## GLSL
The Cava GLSL frontend delegates the visualization of incoming audio data to the GPU via OpenGL.
There are some mandatory dependencies that need to be satisfied in order for Cava GLSL to be built and function properly:
. epoxy library must be installed on the system
. Vertex and fragment shaders from the original project must be used. They should be downloaded, and the file paths must be configured correctly in the Waybar Cava configuration:
1. cava shaders [cava shaders](https://github.com/karlstav/cava/tree/master/output/shaders)
2. libcava shaders [libcava shaders](https://github.com/LukashonakV/cava/tree/master/output/shaders)
. It is highly recommended to have a separate cava configuration for the Waybar Cava GLSL module and to use this as the cava_config in the Waybar configuration.
. It is common for cava configurations to be placed in the XDG_CONFIG_HOME directory, including shaders as well. Consider keeping them in the $XDG_CONFIG_HOME/cava/shaders folder.
Key configuration options:
. bars. The more values the parameter has, the more interesting the visualization becomes.
. method in output section must be set to sdl_glsl
. sdl_width and sdl_height manage the size of the module. Adjust them according to your needs.
. Shaders for sdl_glsl, located in $HOME/.config/cava/shaders. Example: "vertex_shader" = "pass_through.vert" "fragment_shader" = "spectrogram.frag"
. Set continuous_rendering to 1 to enable smooth rendering; set it to 0 otherwise. It is recommended to keep it set to 1.
. background, foreground, and gradient_color_N (where N is a number between 1 and 8) must be defined using hex code
Example:
waybar config
```
"cava": {
"cava_config": "$XDG_CONFIG_HOME/cava/waybar_cava#3.conf",
"input_delay": 2,
"actions": {
"on-click-right": "mode"
}
},
```
waybar_raw.conf
```
## Configuration file for CAVA.
# Remove the ; to change parameters.
[general]
# Smoothing mode. Can be 'normal', 'scientific' or 'waves'. DEPRECATED as of 0.6.0
# Accepts only non-negative values.
# 'autosens' will attempt to decrease sensitivity if the bars peak. 1 = on, 0 = off
# new as of 0.6.0 autosens of low values (dynamic range)
# 'overshoot' allows bars to overshoot (in % of terminal height) without initiating autosens. DEPRECATED as of 0.6.0
# Manual sensitivity in %. If autosens is enabled, this will only be the initial value.
# 200 means double height. Accepts only non-negative values.
# The number of bars (0-512). 0 sets it to auto (fill up console).
# Bars' width and space between bars in number of characters.
bars = 50
# bar_height is only used for output in "noritake" format
# For SDL width and space between bars is in pixels, defaults are:
# sdl_glsl have these default values, they are only used to calculate max number of bars.
# Lower and higher cutoff frequencies for lowest and highest bars
# the bandwidth of the visualizer.
# Note: there is a minimum total bandwidth of 43Mhz x number of bars.
# Cava will automatically increase the higher cutoff if a too low band is specified.
# Seconds with no input before cava goes to sleep mode. Cava will not perform FFT or drawing and
# only check for input once per second. Cava will wake up once input is detected. 0 = disable.
sleep_timer = 5
[input]
# Audio capturing method. Possible methods are: 'fifo', 'portaudio', 'pipewire', 'alsa', 'pulse', 'sndio', 'oss', 'jack' or 'shmem'
# Defaults to 'oss', 'pipewire', 'sndio', 'jack', 'pulse', 'alsa', 'portaudio' or 'fifo', in that order, dependent on what support cava was built with.
# On Mac it defaults to 'portaudio' or 'fifo'
# On windows this is automatic and no input settings are needed.
#
# All input methods uses the same config variable 'source'
# to define where it should get the audio.
#
# For pulseaudio and pipewire 'source' will be the source. Default: 'auto', which uses the monitor source of the default sink
# (all pulseaudio sinks(outputs) have 'monitor' sources(inputs) associated with them).
#
# For pipewire 'source' will be the object name or object.serial of the device to capture from.
# Both input and output devices are supported.
#
# For alsa 'source' will be the capture device.
# For fifo 'source' will be the path to fifo-file.
# For shmem 'source' will be /squeezelite-AA:BB:CC:DD:EE:FF where 'AA:BB:CC:DD:EE:FF' will be squeezelite's MAC address
#
# For sndio 'source' will be a raw recording audio descriptor or a monitoring sub-device, e.g. 'rsnd/2' or 'snd/1'. Default: 'default'.
# README.md contains further information on how to setup CAVA for sndio.
#
# For oss 'source' will be the path to a audio device, e.g. '/dev/dsp2'. Default: '/dev/dsp', i.e. the default audio device.
# README.md contains further information on how to setup CAVA for OSS on FreeBSD.
#
# For jack 'source' will be the name of the JACK server to connect to, e.g. 'foobar'. Default: 'default'.
# README.md contains further information on how to setup CAVA for JACK.
#
# The options 'sample_rate', 'sample_bits', 'channels' and 'autoconnect' can be configured for some input methods:
# sample_rate: fifo, pipewire, sndio, oss
# sample_bits: fifo, pipewire, sndio, oss
# channels: sndio, oss, jack
# autoconnect: jack
# Other methods ignore these settings.
#
# For 'sndio' and 'oss' they are only preferred values, i.e. if the values are not supported
# by the chosen audio device, the device will use other supported values instead.
# Example: 48000, 32 and 2, but the device only supports 44100, 16 and 1, then it
# will use 44100, 16 and 1.
#
[output]
# Output method. Can be 'ncurses', 'noncurses', 'raw', 'noritake', 'sdl'
# or 'sdl_glsl'.
# 'noncurses' (default) uses a buffer and cursor movements to only print
# changes from frame to frame in the terminal. Uses less resources and is less
# prone to tearing (vsync issues) than 'ncurses'.
#
# 'raw' is an 8 or 16 bit (configurable via the 'bit_format' option) data
# stream of the bar heights that can be used to send to other applications.
# 'raw' defaults to 200 bars, which can be adjusted in the 'bars' option above.
#
# 'noritake' outputs a bitmap in the format expected by a Noritake VFD display
# in graphic mode. It only support the 3000 series graphical VFDs for now.
#
# 'sdl' uses the Simple DirectMedia Layer to render in a graphical context.
# 'sdl_glsl' uses SDL to create an OpenGL context. Write your own shaders or
# use one of the predefined ones.
method = sdl_glsl
# Orientation of the visualization. Can be 'bottom', 'top', 'left', 'right' or
# 'horizontal'. Default is 'bottom'. 'left and 'right' are only supported on sdl
# and ncruses output. 'horizontal' (bars go up and down from center) is only supported
# on noncurses output.
# Note: many fonts have weird or missing glyphs for characters used in orientations
# other than 'bottom', which can make output not look right.
# Visual channels. Can be 'stereo' or 'mono'.
# 'stereo' mirrors both channels with low frequencies in center.
# 'mono' outputs left to right lowest to highest frequencies.
# 'mono_option' set mono to either take input from 'left', 'right' or 'average'.
# set 'reverse' to 1 to display frequencies the other way around.
# Raw output target. A fifo will be created if target does not exist.
# Raw data format. Can be 'binary' or 'ascii'.
# Binary bit format, can be '8bit' (0-255) or '16bit' (0-65530).
# Ascii max value. In 'ascii' mode range will run from 0 to value specified here
# Ascii delimiters. In ascii format each bar and frame is separated by a delimiters.
# Use decimal value in ascii table (i.e. 59 = ';' and 10 = '\n' (line feed)).
bar_delimiter = 0
# sdl window size and position. -1,-1 is centered.
sdl_width = 150
sdl_height = 39
# set label on bars on the x-axis. Can be 'frequency' or 'none'. Default: 'none'
# 'frequency' displays the lower cut off frequency of the bar above.
# Only supported on ncurses and noncurses output.
# enable synchronized sync. 1 = on, 0 = off
# removes flickering in alacritty terminal emulator.
# defaults to off since the behaviour in other terminal emulators is unknown
# Shaders for sdl_glsl, located in $HOME/.config/cava/shaders
vertex_shader = pass_through.vert
fragment_shader = bar_spectrum.frag
; for glsl output mode, keep rendering even if no audio
continuous_rendering = 1;
# disable console blank (screen saver) in tty
# (Not supported on FreeBSD)
# show a flat bar at the bottom of the screen when idle, 1 = on, 0 = off
# show waveform instead of frequency spectrum, 1 = on, 0 = off
[color]
# Colors can be one of seven predefined: black, blue, cyan, green, magenta, red, white, yellow.
# Or defined by hex code '#xxxxxx' (hex code must be within ''). User defined colors requires
# a terminal that can change color definitions such as Gnome-terminal or rxvt.
# default is to keep current terminal color
# SDL and sdl_glsl only support hex code colors, these are the default:
background = '#282C34'
# Gradient mode, only hex defined colors are supported,
# background must also be defined in hex or remain commented out. 1 = on, 0 = off.
# You can define as many as 8 different colors. They range from bottom to top of screen
gradient = 1
gradient_count = 2
gradient_color_1 = '#282C34'
gradient_color_2 = '#45475A'
; gradient_color_1 = '#59cc33'
; gradient_color_2 = '#80cc33'
gradient_color_3 = '#a6cc33'
gradient_color_4 = '#cccc33'
gradient_color_5 = '#cca633'
gradient_color_6 = '#cc8033'
gradient_color_7 = '#cc5933'
gradient_color_8 = '#cc3333'
[smoothing]
# Percentage value for integral smoothing. Takes values from 0 - 100.
# Higher values means smoother, but less precise. 0 to disable.
# DEPRECATED as of 0.8.0, use noise_reduction instead
# Disables or enables the so-called "Monstercat smoothing" with or without "waves". Set to 0 to disable.
# Set gravity percentage for "drop off". Higher values means bars will drop faster.
# Accepts only non-negative values. 50 means half gravity, 200 means double. Set to 0 to disable "drop off".
# DEPRECATED as of 0.8.0, use noise_reduction instead
# In bar height, bars that would have been lower that this will not be drawn.
# DEPRECATED as of 0.8.0
# Noise reduction, int 0 - 100. default 77
# the raw visualization is very noisy, this factor adjusts the integral and gravity filters to keep the signal smooth
# 100 will be very slow and smooth, 0 will be fast but noisy.
[eq]
# This one is tricky. You can have as much keys as you want.
# Remember to uncomment more than one key! More keys = more precision.
# Look at readme.md on github for further explanations and examples.
```
Different waybar_cava#N.conf see at [cava GLSL](https://github.com/Alexays/Waybar/wiki/Module:-Cava:-GLSL)

View File

@@ -39,6 +39,12 @@ $XDG_CONFIG_HOME/waybar/config ++
:[ A list of timezones (as in *timezone*) to use for time display, changed using
the scroll wheel. Do not specify *timezone* option when *timezones* is specified.
"" represents the system's local timezone
|[ *timezone-tooltip-format*
:[ string
:[
:[ Format to use for displaying timezones in the tooltip. When set, this allows showing
timezone information (like timezone abbreviations) in the tooltip while keeping the
main display clean. Uses the same format options as *format*
|[ *locale*
:[ string
:[
@@ -126,6 +132,12 @@ View all valid format options in *strftime(3)* or have a look https://en.cpprefe
:[ 1
:[ Value to scroll months/years forward/backward. Can be negative. Is
configured under *on-scroll* option
|[ *iso8601*
:[ bool
:[ false
:[ When enabled, the calendar follows the ISO 8601 standard: weeks begin on
Monday, and the first week of the year is numbered 1. The default week format is
'{:%V}'.
3. Addressed by *clock: calendar: format*
[- *Option*
@@ -229,6 +241,25 @@ View all valid format options in *strftime(3)* or have a look https://en.cpprefe
}
```
4. Show timezone in tooltip only
```
"clock": {
"interval": 60,
"format": "{:%H:%M}",
"timezone-tooltip-format": "{:%H:%M %Z}",
"timezones": [
"",
"America/Chicago",
"America/Los_Angeles",
"Europe/Paris",
"UTC"
],
"tooltip": true,
"tooltip-format": "{tz_list}"
}
```
# STYLE
- *#clock*

View File

@@ -11,9 +11,10 @@ The *cpu* module displays the current CPU utilization.
# CONFIGURATION
*interval*: ++
typeof: integer ++
typeof: integer or float ++
default: 10 ++
The interval in which the information gets polled.
The interval in which the information gets polled. ++
Minimum value is 0.001 (1ms). Values smaller than 1ms will be set to 1ms.
*format*: ++
typeof: string ++

View File

@@ -35,15 +35,17 @@ Addressed by *custom/<name>*
See *return-type*
*interval*: ++
typeof: integer ++
typeof: integer or float ++
The interval (in seconds) in which the information gets polled. ++
Minimum value is 0.001 (1ms). Values smaller than 1ms will be set to 1ms. ++
Use *once* if you want to execute the module only on startup. ++
You can update it manually with a signal. If no *interval* or *signal* is defined, it is assumed that the out script loops itself. ++
If a *signal* is defined then the script will run once on startup and will only update with a signal.
*restart-interval*: ++
typeof: integer ++
typeof: integer or float ++
The restart interval (in seconds). ++
Minimum value is 0.001 (1ms). Values smaller than 1ms will be set to 1ms. ++
Can't be used with the *interval* option, so only with continuous scripts. ++
Once the script exits, it'll be re-executed after the *restart-interval*.
@@ -232,7 +234,6 @@ $text\\n$tooltip\\n$class*
```
"custom/pacman": {
"format": "{text} ",
"interval": 3600, // every hour
"exec": "checkupdates | wc -l", // # of updates
"exec-if": "exit 0", // always run; consider advanced run conditions
"on-click": "termite -e 'sudo pacman -Syu'; pkill -SIGRTMIN+8 waybar", // update system
@@ -240,7 +241,7 @@ $text\\n$tooltip\\n$class*
}
```
You can use the signal and update the number of available packages with *pkill -RTMIN+8 waybar*.
Under the premise that interval is not defined, you can use the signal and update the number of available packages with *pkill -RTMIN+8 waybar*.
# STYLE

View File

@@ -43,6 +43,7 @@ Addressed by *dwl/tags*
- *#tags button*
- *#tags button.occupied*
- *#tags button.empty*
- *#tags button.focused*
- *#tags button.urgent*

View File

@@ -10,7 +10,7 @@ The *workspaces* module displays the currently used workspaces in wayland compos
# CONFIGURATION
Addressed by *wlr/workspaces*
Addressed by *ext/workspaces*
*format*: ++
typeof: string ++
@@ -24,18 +24,18 @@ Addressed by *wlr/workspaces*
*sort-by-name*: ++
typeof: bool ++
default: true ++
Should workspaces be sorted by name.
Should workspaces be sorted by name. Workspace names will be sorted numerically when all names are numbers.
*sort-by-coordinates*: ++
typeof: bool ++
default: true ++
default: false ++
Should workspaces be sorted by coordinates. ++
Note that if both *sort-by-name* and *sort-by-coordinates* are true sort-by name will be first. If both are false - sort by id will be performed.
*sort-by-number*: ++
*sort-by-id*: ++
typeof: bool ++
default: false ++
If set to true, workspace names will be sorted numerically. Takes precedence over any other sort-by option.
Should workspaces be sorted by ID. Workspace ID will be sorted numerically when all ID are numbers. Takes precedence over any other sort-by option.
*all-outputs*: ++
typeof: bool ++
@@ -47,9 +47,16 @@ Addressed by *wlr/workspaces*
default: false ++
If set to true only active or urgent workspaces will be shown.
*ignore-hidden*: ++
typeof: bool ++
default: true ++
If set to false hidden workspaces will be shown.
# FORMAT REPLACEMENTS
*{name}*: Name of workspace assigned by compositor
*{name}*: Name of workspace assigned by compositor.
*{id}*: ID of workspace assigned by compositor.
*{icon}*: Icon, as defined in *format-icons*.
@@ -57,6 +64,8 @@ Addressed by *wlr/workspaces*
*activate*: Switch to workspace.
*deactivate*: Deactivate the workspace.
*close*: Close the workspace.
# ICONS
@@ -69,18 +78,18 @@ In addition to workspace name matching, the following *format-icons* can be set.
# EXAMPLES
```
"wlr/workspaces": {
"ext/workspaces": {
"format": "{name}: {icon}",
"on-click": "activate",
"format-icons": {
"1": "",
"2": "",
"3": "",
"4": "",
"5": "",
"Workspace 1": "",
"Workspace 2": "",
"Workspace 3": "",
"Workspace 4": "",
"active": "",
"default": ""
},
"sort-by-number": true
"sort-by-id": true
}
```

View File

@@ -26,17 +26,77 @@ Addressed by *hyprland/workspaces*
Regex rules to map window class to an icon or preferred method of representation for a workspace's window.
Keys are the rules, while the values are the methods of representation. Values may use the placeholders {class} and {title} to use the window's original class and/or title respectively.
Rules may specify `class<...>`, `title<...>`, or both in order to fine-tune the matching.
You may assign an empty value to a rule to have it ignored from generating any representation in workspaces.
You may assign an empty value to a rule to have it ignored from generating any representation in workspaces. ++
This setting is ignored if *workspace-taskbar.enable* is set to true.
*window-rewrite-default*:
*window-rewrite-default*: ++
typeof: string ++
default: "?" ++
The default method of representation for a workspace's window. This will be used for windows whose classes do not match any of the rules in *window-rewrite*.
The default method of representation for a workspace's window. This will be used for windows whose classes do not match any of the rules in *window-rewrite*. ++
This setting is ignored if *workspace-taskbar.enable* is set to true.
*format-window-separator*: ++
typeof: string ++
default: " " ++
The separator to be used between windows in a workspace.
The separator to be used between windows in a workspace. ++
This setting is ignored if *workspace-taskbar.enable* is set to true.
*workspace-taskbar*: ++
typeof: object ++
Contains settings for the workspace taskbar, an alternative mode for the workspaces module which displays the window icons as images instead of text.
*enable*: ++
typeof: bool ++
default: false ++
Enables the workspace taskbar mode.
*update-active-window*: ++
typeof: bool ++
default: false ++
If true, the active/focused window will have an 'active' class. Could cause higher CPU usage due to more frequent redraws.
*reverse-direction*: ++
typeof: bool ++
default: false ++
If true, the taskbar windows will be added in reverse order (right to left if orientation is horizontal, bottom to top if vertical).
*active-window-position*: ++
typeof: "none" | "first" | "last" ++
default: "none" ++
If set to "first", the active window will be moved at the beginning of the taskbar. If set to "last", it will be moved at the end. It will only work if *update-active-window* is set to true.
*format*: ++
typeof: string ++
default: {icon} ++
Format to use for each window in the workspace taskbar. Available placeholders are {icon} and {title}.
*icon-size*: ++
typeof: int ++
default: 16 ++
Size of the icons in the workspace taskbar.
*icon-theme*: ++
typeof: string | array ++
default: [] ++
Icon theme to use for the workspace taskbar. If an array is provided, the first theme that is found for a given icon will be used. If no theme is found (or the array is empty), the default icon theme is used.
*orientation*: ++
typeof: "horizontal" | "vertical" ++
default: horizontal ++
Direction in which the workspace taskbar is displayed.
*ignore-list*: ++
typeof: array ++
default: [] ++
Regex patterns to match against window class or window title. If a window's class OR title matches any of the patterns, it will not be shown.
*on-click-window*: ++
typeof: string ++
default: "" ++
Command to run when a window is clicked. Available placeholders are: ++
- {address} Hyprland address of the clicked window. ++
- {button} Pressed button number, see https://api.gtkd.org/gdk.c.types.GdkEventButton.button.html. ++
See https://github.com/Alexays/Waybar/wiki/Module:-Hyprland#workspace-taskbars-example for a full example.
*show-special*: ++
typeof: bool ++
@@ -184,3 +244,6 @@ Additional to workspace name matching, the following *format-icons* can be set.
- *#workspaces button.special*
- *#workspaces button.urgent*
- *#workspaces button.hosting-monitor* (gets applied if workspace-monitor == waybar-monitor)
- *#workspaces .workspace-label*
- *#workspaces .taskbar-window* (each window in the taskbar, only if 'workspace-taskbar.enable' is true)
- *#workspaces .taskbar-window.active* (applied to the focused window, only if 'workspace-taskbar.update-active-window' is true)

View File

@@ -24,8 +24,9 @@ The *image* module displays an image from a path.
The width/height to render the image.
*interval*: ++
typeof: integer ++
typeof: integer or float ++
The interval (in seconds) to re-render the image. ++
Minimum value is 0.001 (1ms). Values smaller than 1ms will be set to 1ms. ++
This is useful if the contents of *path* changes. ++
If no *interval* is defined, the image will only be rendered once.

View File

@@ -45,7 +45,7 @@ Addressed by *jack*
The format of information displayed in the tooltip.
*interval*: ++
typeof: integer ++
typeof: integer or float ++
default: 1 ++
The interval in which the information gets polled.

View File

@@ -87,15 +87,15 @@ Module config :
```
"custom/power": {
"format" : "⏻ ",
"tooltip": false,
"menu": "on-click",
"menu-file": "~/.config/waybar/power_menu.xml",
"menu-actions": {
"shutdown": "shutdown",
"reboot": "reboot",
"suspend": "systemctl suspend",
"hibernate": "systemctl hibernate",
},
"tooltip": false,
"menu": "on-click",
"menu-file": "~/.config/waybar/power_menu.xml",
"menu-actions": {
"shutdown": "shutdown",
"reboot": "reboot",
"suspend": "systemctl suspend",
"hibernate": "systemctl hibernate",
},
},
```
@@ -104,28 +104,28 @@ Module config :
<?xml version="1.0" encoding="UTF-8"?>
<interface>
<object class="GtkMenu" id="menu">
<child>
<object class="GtkMenuItem" id="suspend">
<property name="label">Suspend</property>
</object>
</child>
<child>
<object class="GtkMenuItem" id="hibernat">
<property name="label">Hibernate</property>
</object>
</child>
<child>
<object class="GtkMenuItem" id="suspend">
<property name="label">Suspend</property>
</object>
</child>
<child>
<object class="GtkMenuItem" id="hibernate">
<property name="label">Hibernate</property>
</object>
</child>
<child>
<object class="GtkMenuItem" id="shutdown">
<property name="label">Shutdown</property>
</object>
<object class="GtkMenuItem" id="shutdown">
<property name="label">Shutdown</property>
</object>
</child>
<child>
<object class="GtkSeparatorMenuItem" id="delimiter1"/>
</child>
<child>
<object class="GtkMenuItem" id="reboot">
<property name="label">Reboot</property>
</object>
<object class="GtkMenuItem" id="reboot">
<property name="label">Reboot</property>
</object>
</child>
</object>
</interface>

View File

@@ -204,6 +204,10 @@ Addressed by *mpd*
*{queueLength}*: The length of the current queue.
*{uri}*: The URI of the song relative to the MPD music directory.
*{filename}* The last part of the URI.
*{stateIcon}*: The icon corresponding to the playing or paused status of the player (see *state-icons* option)
*{consumeIcon}*: The icon corresponding the "consume" option (see *consume-icons* option)

View File

@@ -16,6 +16,11 @@ Addressed by *network*
typeof: string ++
Use the defined interface instead of auto-detection. Accepts wildcard.
*rfkill*: ++
typeof: bool ++
default: true ++
If enabled, the *disabled* format will be used when rfkill is blocking wlan interfaces.
*interval*: ++
typeof: integer ++
default: 60 ++
@@ -49,7 +54,7 @@ Addressed by *network*
*format-disabled*: ++
typeof: string ++
This format is used when the displayed interface is disabled.
This format is used when rfkill is blocking wlan interfaces.
*format-icons*: ++
typeof: array/object ++
@@ -127,7 +132,7 @@ Addressed by *network*
*tooltip-format-disabled*: ++
typeof: string ++
This format is used when the displayed interface is disabled.
This format is used when rfkill is blocking wlan interfaces.
*menu*: ++
typeof: string ++
@@ -157,7 +162,7 @@ Addressed by *network*
*{netmask}*: The subnetmask corresponding to the IP(V4).
*{netmask6}*: The subnetmask corresponding to the IP(V6).
*{netmask6}*: The subnetmask corresponding to the IP(V6).
*{cidr}*: The subnetmask corresponding to the IP(V4) in CIDR notation.

View File

@@ -52,8 +52,8 @@ Addressed by *niri/language*
```
"niri/language": {
"format": "Lang: {long}"
"format-en": "AMERICA, HELL YEAH!"
"format": "Lang: {long}",
"format-en": "AMERICA, HELL YEAH!",
"format-tr": "As bayrakları"
}
```
@@ -61,3 +61,12 @@ Addressed by *niri/language*
# STYLE
- *#language*
Additionally, a CSS class matching the current layout's short name is added to the widget. This
allows per-language styling, for example:
```
#language.us { color: #00ff00; }
#language.de { color: #ff0000; }
#language.fr { color: #0000ff; }
```

View File

@@ -77,12 +77,12 @@ The slider is a component with multiple CSS Nodes, of which the following are ex
min-height: 80px;
min-width: 10px;
border-radius: 5px;
background-color: black;
background: black;
}
#pulseaudio-slider highlight {
min-width: 10px;
border-radius: 5px;
background-color: green;
background: green;
}
```

View File

@@ -97,7 +97,11 @@ Additionally, you can control the volume by scrolling *up* or *down* while the c
*reverse-scrolling*: ++
typeof: bool ++
Option to reverse the scroll direction.
Option to reverse the scroll direction for touchpads.
*reverse-mouse-scrolling*: ++
typeof: bool ++
Option to reverse the scroll direction for mice.
*tooltip*: ++
typeof: bool ++
@@ -173,8 +177,8 @@ to be selected when the corresponding audio device is muted. This applies to *de
"format-icons": {
"alsa_output.pci-0000_00_1f.3.analog-stereo": "",
"alsa_output.pci-0000_00_1f.3.analog-stereo-muted": "",
"headphones": "",
"handsfree": "",
"headphone": "",
"hands-free": "",
"headset": "",
"phone": "",
"phone-muted": "",

View File

@@ -83,6 +83,7 @@ Addressed by *river/layout*
- *#layout*
- *#layout.focused* Applied when the output this module's bar belongs to is focused.
- *#layout.<layout>* Applied when the output this module's bar belongs uses this layout.
# SEE ALSO

View File

@@ -31,6 +31,11 @@ Addressed by *sway/workspaces*
default: false ++
If set to false, you can scroll to cycle through workspaces. If set to true this behaviour is disabled.
*reverse-scroll*: ++
typeof: bool ++
default: false ++
If set to false, scrolling up will switch to the previous workspace and scrolling down will switch to the next workspace. If set to true, the behavior will be reversed.
*disable-click*: ++
typeof: bool ++
default: false ++
@@ -174,7 +179,6 @@ n.b.: the list of outputs can be obtained from command line using *swaymsg -t ge
"format": "<span size='larger'>{name}</span> {windows}",
"format-window-separator": " | ",
"window-rewrite-default": "{name}",
"window-format": "<span color='#e0e0e0'>{name}</span>",
"window-rewrite": {
"class<firefox>": "",
"class<kitty>": "k",

View File

@@ -40,7 +40,7 @@ Addressed by *temperature*
The threshold before it is considered critical (Celsius).
*interval*: ++
typeof: integer ++
typeof: integer or float ++
default: 10 ++
The interval in which the information gets polled.
@@ -160,4 +160,5 @@ Addressed by *temperature*
# STYLE
- *#temperature*
- *#temperature.warning*
- *#temperature.critical*

View File

@@ -151,6 +151,20 @@ The visual display elements for waybar use a CSS stylesheet, see *waybar-styles(
default: *false* ++
Option to enable reloading the css style if a modification is detected on the style sheet file or any imported css files.
*on-sigusr1* ++
typeof: string ++
default: *toggle* ++
Action that is performed when receiving SIGUSR1 kill signal. ++
Possible values: *show*, *hide*, *toggle*, *reload*, *noop*. ++
Default value: *toggle*.
*on-sigusr2* ++
typeof: string ++
default: *reload* ++
Action that is performed when receiving SIGUSR2 kill signal. ++
Possible values: *show*, *hide*, *toggle*, *reload*, *noop*. ++
Default value: *reload*.
# MODULE FORMAT
You can use PangoMarkupFormat (See https://developer.gnome.org/pango/stable/PangoMarkupFormat.html#PangoMarkupFormat).
@@ -206,14 +220,36 @@ A minimal *config* file could look like this:
Waybar accepts the following signals:
*SIGUSR1*
Toggles the bar visibility (hides if shown, shows if hidden)
By default toggles the bar visibility (hides if shown, shows if hidden)
*SIGUSR2*
Reloads (resets) the bar
By default reloads (resets) the bar
*SIGINT*
Quits the bar
For example, to toggle the bar programmatically, you can invoke `killall -SIGUSR1 waybar`.
## User signal configuration
Config parameters *on-sigusr1* and *on-sigusr2* change what happens when bars receive
*SIGUSR1* and *SIGUSR2* signals.
This means that commands `killall -SIGUSR1 waybar` and `killall -SIGUSR2 waybar`
can perform user-configured action.
It also means that if an external script has the PID of the bar then it can
perform more complex `show`/`hide`/`reload` logic for each instance of Waybar.
One can find the PID e.g. by doing `pgrep -a waybar` which could then match
by config name or other parameters.
## Kill parameter meanings
*show* Switches state to visible (per bar).
*hide* Switches state to hidden (per bar).
*toggle* Switches state between visible and hidden (per bar).
*reload* Reloads all waybars of current waybar process (basically equivalent to
restarting with updated config which sets initial visibility values).
*noop* Does nothing when the kill signal is received.
# MULTI OUTPUT CONFIGURATION
## Limit a configuration to some outputs
@@ -401,4 +437,4 @@ A group may hide all but one element, showing them only on mouse hover. In order
# SEE ALSO
*sway-output(5)*
*waybar-styles(5)"
*waybar-styles(5)*

View File

@@ -1,6 +1,6 @@
project(
'waybar', 'cpp', 'c',
version: '0.13.0',
version: '0.14.0',
license: 'MIT',
meson_version: '>= 0.59.0',
default_options : [
@@ -69,7 +69,7 @@ is_openbsd = host_machine.system() == 'openbsd'
thread_dep = dependency('threads')
fmt = dependency('fmt', version : ['>=8.1.1'], fallback : ['fmt', 'fmt_dep'])
spdlog = dependency('spdlog', version : ['>=1.10.0'], fallback : ['spdlog', 'spdlog_dep'], default_options : ['external_fmt=enabled', 'std_format=disabled', 'tests=disabled'])
spdlog = dependency('spdlog', version : ['>=1.15.2'], fallback : ['spdlog', 'spdlog_dep'], default_options : ['std_format=disabled', 'tests=disabled'])
wayland_client = dependency('wayland-client')
wayland_cursor = dependency('wayland-cursor')
wayland_protos = dependency('wayland-protocols')
@@ -183,6 +183,7 @@ src_files = files(
'src/util/sanitize_str.cpp',
'src/util/rewrite_string.cpp',
'src/util/gtk_icon.cpp',
'src/util/icon_loader.cpp',
'src/util/regex_collection.cpp',
'src/util/css_reload_helper.cpp'
)
@@ -276,6 +277,17 @@ if true
man_files += files('man/waybar-wlr-taskbar.5.scd')
endif
if wayland_protos.version().version_compare('>=1.39')
add_project_arguments('-DHAVE_EXT_WORKSPACES', language: 'cpp')
src_files += files(
'src/modules/ext/workspace_manager.cpp',
'src/modules/ext/workspace_manager_binding.cpp',
)
man_files += files(
'man/waybar-ext-workspaces.5.scd',
)
endif
if true
add_project_arguments('-DHAVE_RIVER', language: 'cpp')
src_files += files(
@@ -485,27 +497,24 @@ else
man_files += files('man/waybar-clock.5.scd')
endif
if get_option('experimental')
add_project_arguments('-DHAVE_WLR_WORKSPACES', language: 'cpp')
src_files += files(
'src/modules/wlr/workspace_manager.cpp',
'src/modules/wlr/workspace_manager_binding.cpp',
)
man_files += files(
'man/waybar-wlr-workspaces.5.scd',
)
endif
cava = dependency('cava',
version : '>=0.10.4',
cava = dependency('libcava',
version : '>=0.10.7',
required: get_option('cava'),
fallback : ['cava', 'cava_dep'],
fallback : ['libcava', 'cava_dep'],
not_found_message: 'cava is not found. Building waybar without cava')
eproxy = dependency('epoxy', required: false)
if cava.found()
add_project_arguments('-DHAVE_LIBCAVA', language: 'cpp')
src_files += files('src/modules/cava.cpp')
src_files += files('src/modules/cava/cavaRaw.cpp',
'src/modules/cava/cava_backend.cpp')
man_files += files('man/waybar-cava.5.scd')
if eproxy.found()
add_project_arguments('-DHAVE_LIBCAVAGLSL', language: 'cpp')
src_files += files('src/modules/cava/cavaGLSL.cpp')
endif
endif
if libgps.found()
@@ -553,6 +562,7 @@ executable(
tz_dep,
xkbregistry,
cava,
eproxy,
libgps
],
include_directories: inc_dirs,

View File

@@ -6,16 +6,17 @@
}:
let
libcava = rec {
version = "0.10.4";
version = "0.10.7-beta";
src = pkgs.fetchFromGitHub {
owner = "LukashonakV";
repo = "cava";
tag = version;
hash = "sha256-9eTDqM+O1tA/3bEfd1apm8LbEcR9CVgELTIspSVPMKM=";
# NOTE: Needs to match the cava.wrap
tag = "v${version}";
hash = "sha256-IX1B375gTwVDRjpRfwKGuzTAZOV2pgDWzUd4bW2cTDU=";
};
};
in
(waybar.overrideAttrs (oldAttrs: {
waybar.overrideAttrs (oldAttrs: {
inherit version;
src = lib.cleanSourceWith {
@@ -30,13 +31,12 @@ in
# nixpkgs checks version, no need when building locally
nativeInstallCheckInputs = [ ];
buildInputs = (builtins.filter (p:
p.pname != "wireplumber" &&
p.pname != "gps"
) oldAttrs.buildInputs) ++ [
pkgs.wireplumber
pkgs.gpsd
];
buildInputs =
(builtins.filter (p: p.pname != "wireplumber" && p.pname != "gps") oldAttrs.buildInputs)
++ [
pkgs.wireplumber
pkgs.gpsd
];
postUnpack = ''
pushd "$sourceRoot"
@@ -44,4 +44,4 @@ in
patchShebangs .
popd
'';
}))
})

View File

@@ -1,306 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="ext_workspace_unstable_v1">
<copyright>
Copyright © 2019 Christopher Billington
Copyright © 2020 Ilia Bozhinov
Permission to use, copy, modify, distribute, and sell this
software and its documentation for any purpose is hereby granted
without fee, provided that the above copyright notice appear in
all copies and that both that copyright notice and this permission
notice appear in supporting documentation, and that the name of
the copyright holders not be used in advertising or publicity
pertaining to distribution of the software without specific,
written prior permission. The copyright holders make no
representations about the suitability of this software for any
purpose. It is provided "as is" without express or implied
warranty.
THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
</copyright>
<interface name="zext_workspace_manager_v1" version="1">
<description summary="list and control workspaces">
Workspaces, also called virtual desktops, are groups of surfaces. A
compositor with a concept of workspaces may only show some such groups of
surfaces (those of 'active' workspaces) at a time. 'Activating' a
workspace is a request for the compositor to display that workspace's
surfaces as normal, whereas the compositor may hide or otherwise
de-emphasise surfaces that are associated only with 'inactive' workspaces.
Workspaces are grouped by which sets of outputs they correspond to, and
may contain surfaces only from those outputs. In this way, it is possible
for each output to have its own set of workspaces, or for all outputs (or
any other arbitrary grouping) to share workspaces. Compositors may
optionally conceptually arrange each group of workspaces in an
N-dimensional grid.
The purpose of this protocol is to enable the creation of taskbars and
docks by providing them with a list of workspaces and their properties,
and allowing them to activate and deactivate workspaces.
After a client binds the zext_workspace_manager_v1, each workspace will be
sent via the workspace event.
</description>
<event name="workspace_group">
<description summary="a workspace group has been created">
This event is emitted whenever a new workspace group has been created.
All initial details of the workspace group (workspaces, outputs) will be
sent immediately after this event via the corresponding events in
zext_workspace_group_handle_v1.
</description>
<arg name="workspace_group" type="new_id" interface="zext_workspace_group_handle_v1"/>
</event>
<request name="commit">
<description summary="all requests about the workspaces have been sent">
The client must send this request after it has finished sending other
requests. The compositor must process a series of requests preceding a
commit request atomically.
This allows changes to the workspace properties to be seen as atomic,
even if they happen via multiple events, and even if they involve
multiple zext_workspace_handle_v1 objects, for example, deactivating one
workspace and activating another.
</description>
</request>
<event name="done">
<description summary="all information about the workspace groups has been sent">
This event is sent after all changes in all workspace groups have been
sent.
This allows changes to one or more zext_workspace_group_handle_v1
properties to be seen as atomic, even if they happen via multiple
events. In particular, an output moving from one workspace group to
another sends an output_enter event and an output_leave event to the two
zext_workspace_group_handle_v1 objects in question. The compositor sends
the done event only after updating the output information in both
workspace groups.
</description>
</event>
<event name="finished">
<description summary="the compositor has finished with the workspace_manager">
This event indicates that the compositor is done sending events to the
zext_workspace_manager_v1. The server will destroy the object
immediately after sending this request, so it will become invalid and
the client should free any resources associated with it.
</description>
</event>
<request name="stop">
<description summary="stop sending events">
Indicates the client no longer wishes to receive events for new
workspace groups. However the compositor may emit further workspace
events, until the finished event is emitted.
The client must not send any more requests after this one.
</description>
</request>
</interface>
<interface name="zext_workspace_group_handle_v1" version="1">
<description summary="a workspace group assigned to a set of outputs">
A zext_workspace_group_handle_v1 object represents a a workspace group
that is assigned a set of outputs and contains a number of workspaces.
The set of outputs assigned to the workspace group is conveyed to the client via
output_enter and output_leave events, and its workspaces are conveyed with
workspace events.
For example, a compositor which has a set of workspaces for each output may
advertise a workspace group (and its workspaces) per output, whereas a compositor
where a workspace spans all outputs may advertise a single workspace group for all
outputs.
</description>
<event name="output_enter">
<description summary="output assigned to workspace group">
This event is emitted whenever an output is assigned to the workspace
group.
</description>
<arg name="output" type="object" interface="wl_output"/>
</event>
<event name="output_leave">
<description summary="output removed from workspace group">
This event is emitted whenever an output is removed from the workspace
group.
</description>
<arg name="output" type="object" interface="wl_output"/>
</event>
<event name="workspace">
<description summary="workspace added to workspace group">
This event is emitted whenever a new workspace has been created.
All initial details of the workspace (name, coordinates, state) will
be sent immediately after this event via the corresponding events in
zext_workspace_handle_v1.
</description>
<arg name="workspace" type="new_id" interface="zext_workspace_handle_v1"/>
</event>
<event name="remove">
<description summary="this workspace group has been destroyed">
This event means the zext_workspace_group_handle_v1 has been destroyed.
It is guaranteed there won't be any more events for this
zext_workspace_group_handle_v1. The zext_workspace_group_handle_v1 becomes
inert so any requests will be ignored except the destroy request.
The compositor must remove all workspaces belonging to a workspace group
before removing the workspace group.
</description>
</event>
<request name="create_workspace">
<description summary="create a new workspace">
Request that the compositor create a new workspace with the given name.
There is no guarantee that the compositor will create a new workspace,
or that the created workspace will have the provided name.
</description>
<arg name="workspace" type="string"/>
</request>
<request name="destroy" type="destructor">
<description summary="destroy the zext_workspace_handle_v1 object">
Destroys the zext_workspace_handle_v1 object.
This request should be called either when the client does not want to
use the workspace object any more or after the remove event to finalize
the destruction of the object.
</description>
</request>
</interface>
<interface name="zext_workspace_handle_v1" version="1">
<description summary="a workspace handing a group of surfaces">
A zext_workspace_handle_v1 object represents a a workspace that handles a
group of surfaces.
Each workspace has a name, conveyed to the client with the name event; a
list of states, conveyed to the client with the state event; and
optionally a set of coordinates, conveyed to the client with the
coordinates event. The client may request that the compositor activate or
deactivate the workspace.
Each workspace can belong to only a single workspace group.
Depepending on the compositor policy, there might be workspaces with
the same name in different workspace groups, but these workspaces are still
separate (e.g. one of them might be active while the other is not).
</description>
<event name="name">
<description summary="workspace name changed">
This event is emitted immediately after the zext_workspace_handle_v1 is
created and whenever the name of the workspace changes.
</description>
<arg name="name" type="string"/>
</event>
<event name="coordinates">
<description summary="workspace coordinates changed">
This event is used to organize workspaces into an N-dimensional grid
within a workspace group, and if supported, is emitted immediately after
the zext_workspace_handle_v1 is created and whenever the coordinates of
the workspace change. Compositors may not send this event if they do not
conceptually arrange workspaces in this way. If compositors simply
number workspaces, without any geometric interpretation, they may send
1D coordinates, which clients should not interpret as implying any
geometry. Sending an empty array means that the compositor no longer
orders the workspace geometrically.
Coordinates have an arbitrary number of dimensions N with an uint32
position along each dimension. By convention if N > 1, the first
dimension is X, the second Y, the third Z, and so on. The compositor may
chose to utilize these events for a more novel workspace layout
convention, however. No guarantee is made about the grid being filled or
bounded; there may be a workspace at coordinate 1 and another at
coordinate 1000 and none in between. Within a workspace group, however,
workspaces must have unique coordinates of equal dimensionality.
</description>
<arg name="coordinates" type="array"/>
</event>
<event name="state">
<description summary="the state of the workspace changed">
This event is emitted immediately after the zext_workspace_handle_v1 is
created and each time the workspace state changes, either because of a
compositor action or because of a request in this protocol.
</description>
<arg name="state" type="array"/>
</event>
<enum name="state">
<description summary="types of states on the workspace">
The different states that a workspace can have.
</description>
<entry name="active" value="0" summary="the workspace is active"/>
<entry name="urgent" value="1" summary="the workspace requests attention"/>
<entry name="hidden" value="2">
<description summary="the workspace is not visible">
The workspace is not visible in its workspace group, and clients
attempting to visualize the compositor workspace state should not
display such workspaces.
</description>
</entry>
</enum>
<event name="remove">
<description summary="this workspace has been destroyed">
This event means the zext_workspace_handle_v1 has been destroyed. It is
guaranteed there won't be any more events for this
zext_workspace_handle_v1. The zext_workspace_handle_v1 becomes inert so
any requests will be ignored except the destroy request.
</description>
</event>
<request name="destroy" type="destructor">
<description summary="destroy the zext_workspace_handle_v1 object">
Destroys the zext_workspace_handle_v1 object.
This request should be called either when the client does not want to
use the workspace object any more or after the remove event to finalize
the destruction of the object.
</description>
</request>
<request name="activate">
<description summary="activate the workspace">
Request that this workspace be activated.
There is no guarantee the workspace will be actually activated, and
behaviour may be compositor-dependent. For example, activating a
workspace may or may not deactivate all other workspaces in the same
group.
</description>
</request>
<request name="deactivate">
<description summary="activate the workspace">
Request that this workspace be deactivated.
There is no guarantee the workspace will be actually deactivated.
</description>
</request>
<request name="remove">
<description summary="remove the workspace">
Request that this workspace be removed.
There is no guarantee the workspace will be actually removed.
</description>
</request>
</interface>
</protocol>

View File

@@ -26,12 +26,17 @@ client_protocols = [
[wl_protocol_dir, 'unstable/xdg-output/xdg-output-unstable-v1.xml'],
[wl_protocol_dir, 'unstable/idle-inhibit/idle-inhibit-unstable-v1.xml'],
['wlr-foreign-toplevel-management-unstable-v1.xml'],
['ext-workspace-unstable-v1.xml'],
['river-status-unstable-v1.xml'],
['river-control-unstable-v1.xml'],
['dwl-ipc-unstable-v2.xml'],
]
if wayland_protos.version().version_compare('>=1.39')
client_protocols += [
[wl_protocol_dir, 'staging/ext-workspace/ext-workspace-v1.xml']
]
endif
client_protos_src = []
client_protos_headers = []

View File

@@ -63,7 +63,7 @@ button:hover {
background: rgba(0, 0, 0, 0.2);
}
#workspaces button.focused {
#workspaces button.focused, #workspaces button.active {
background-color: #64727D;
box-shadow: inset 0 -3px #ffffff;
}

View File

@@ -63,7 +63,8 @@ std::optional<std::string> getDesktopFilePath(const std::string& app_identifier,
return {};
}
const auto data_dirs = Glib::get_system_data_dirs();
auto data_dirs = Glib::get_system_data_dirs();
data_dirs.insert(data_dirs.begin(), Glib::get_user_data_dir());
for (const auto& data_dir : data_dirs) {
const auto data_app_dir = data_dir + "/applications/";
auto desktop_file_suffix = app_identifier + ".desktop";

View File

@@ -36,10 +36,13 @@ AIconLabel::AIconLabel(const Json::Value &config, const std::string &name, const
box_.set_spacing(spacing);
bool swap_icon_label = false;
if (not config_["swap-icon-label"].isBool())
spdlog::warn("'swap-icon-label' must be a bool.");
else
if (config_["swap-icon-label"].isNull()) {
} else if (config_["swap-icon-label"].isBool()) {
swap_icon_label = config_["swap-icon-label"].asBool();
} else {
spdlog::warn("'swap-icon-label' must be a bool, found '{}'. Using default value (false).",
config_["swap-icon-label"].asString());
}
if ((rot == 0 || rot == 3) ^ swap_icon_label) {
box_.add(image_);

View File

@@ -17,10 +17,17 @@ ALabel::ALabel(const Json::Value& config, const std::string& name, const std::st
config["format-alt"].isString() || config["menu"].isString() || enable_click,
enable_scroll),
format_(config_["format"].isString() ? config_["format"].asString() : format),
// Leave the default option outside of the std::max(1L, ...), because the zero value
// (default) is used in modules/custom.cpp to make the difference between
// two types of custom scripts. Fixes #4521.
interval_(config_["interval"] == "once"
? std::chrono::seconds::max()
: std::chrono::seconds(
config_["interval"].isUInt() ? config_["interval"].asUInt() : interval)),
? std::chrono::milliseconds::max()
: std::chrono::milliseconds(
(config_["interval"].isNumeric()
? std::max(1L, // Minimum 1ms due to millisecond precision
static_cast<long>(config_["interval"].asDouble()) * 1000)
: 1000 * (long)interval))),
default_format_(format_) {
label_.set_name(name);
if (!id.empty()) {
@@ -200,7 +207,7 @@ std::string ALabel::getState(uint8_t value, bool lesser) {
}
}
// Sort states
std::sort(states.begin(), states.end(), [&lesser](auto& a, auto& b) {
std::ranges::sort(states.begin(), states.end(), [&lesser](auto& a, auto& b) {
return lesser ? a.second < b.second : a.second > b.second;
});
std::string valid_state;

View File

@@ -172,6 +172,10 @@ bool AModule::handleUserEvent(GdkEventButton* const& e) {
// Popup the menu
gtk_widget_show_all(GTK_WIDGET(menu_));
gtk_menu_popup_at_pointer(GTK_MENU(menu_), reinterpret_cast<GdkEvent*>(e));
// Manually reset prelight to make sure the module doesn't stay in a hover state
if (auto* module = event_box_.get_child(); module != nullptr) {
module->unset_state_flags(Gtk::StateFlags::STATE_FLAG_PRELIGHT);
}
}
}
// Second call user scripts

View File

@@ -8,6 +8,8 @@
#include "client.hpp"
#include "factory.hpp"
#include "group.hpp"
#include "util/enum.hpp"
#include "util/kill_signal.hpp"
#ifdef HAVE_SWAY
#include "modules/sway/bar.hpp"
@@ -277,6 +279,32 @@ waybar::Bar::Bar(struct waybar_output* w_output, const Json::Value& w_config)
}
#endif
waybar::util::EnumParser<util::KillSignalAction> m_signalActionEnumParser;
const auto& configSigusr1 = config["on-sigusr1"];
if (configSigusr1.isString()) {
auto strSigusr1 = configSigusr1.asString();
try {
onSigusr1 =
m_signalActionEnumParser.parseStringToEnum(strSigusr1, util::userKillSignalActions);
} catch (const std::invalid_argument& e) {
onSigusr1 = util::SIGNALACTION_DEFAULT_SIGUSR1;
spdlog::warn(
"Invalid string representation for on-sigusr1. Falling back to default mode (toggle).");
}
}
const auto& configSigusr2 = config["on-sigusr2"];
if (configSigusr2.isString()) {
auto strSigusr2 = configSigusr2.asString();
try {
onSigusr2 =
m_signalActionEnumParser.parseStringToEnum(strSigusr2, util::userKillSignalActions);
} catch (const std::invalid_argument& e) {
onSigusr2 = util::SIGNALACTION_DEFAULT_SIGUSR2;
spdlog::warn(
"Invalid string representation for on-sigusr2. Falling back to default mode (reload).");
}
}
setupWidgets();
window.show_all();
@@ -405,7 +433,18 @@ void waybar::Bar::onMap(GdkEventAny* /*unused*/) {
/*
* Obtain a pointer to the custom layer surface for modules that require it (idle_inhibitor).
*/
auto* gdk_window = window.get_window()->gobj();
auto gdk_window_ref = window.get_window();
if (!gdk_window_ref) {
spdlog::warn("Failed to get GDK window during onMap, deferring surface initialization");
return;
}
auto* gdk_window = gdk_window_ref->gobj();
if (!gdk_window) {
spdlog::warn("GDK window object is null during onMap, deferring surface initialization");
return;
}
surface = gdk_wayland_window_get_wl_surface(gdk_window);
configureGlobalOffset(gdk_window_get_width(gdk_window), gdk_window_get_height(gdk_window));
@@ -422,6 +461,8 @@ void waybar::Bar::setVisible(bool value) {
}
void waybar::Bar::toggle() { setVisible(!visible); }
void waybar::Bar::show() { setVisible(true); }
void waybar::Bar::hide() { setVisible(false); }
// Converting string to button code rn as to avoid doing it later
void waybar::Bar::setupAltFormatKeyForModule(const std::string& module_name) {
@@ -479,6 +520,9 @@ void waybar::Bar::handleSignal(int signal) {
}
}
waybar::util::KillSignalAction waybar::Bar::getOnSigusr1Action() { return this->onSigusr1; }
waybar::util::KillSignalAction waybar::Bar::getOnSigusr2Action() { return this->onSigusr2; }
void waybar::Bar::getModules(const Factory& factory, const std::string& pos,
waybar::Group* group = nullptr) {
auto module_list = group != nullptr ? config[pos]["modules"] : config[pos];
@@ -496,7 +540,11 @@ void waybar::Bar::getModules(const Factory& factory, const std::string& pos,
auto vertical = (group != nullptr ? group->getBox().get_orientation()
: box_.get_orientation()) == Gtk::ORIENTATION_VERTICAL;
auto* group_module = new waybar::Group(id_name, class_name, config[ref], vertical);
auto group_config = config[ref];
if (group_config["modules"].isNull()) {
spdlog::warn("Group definition '{}' has not been found, group will be hidden", ref);
}
auto* group_module = new waybar::Group(id_name, class_name, group_config, vertical);
getModules(factory, ref, group_module);
module = group_module;
} else {

View File

@@ -151,15 +151,19 @@ void waybar::Client::handleDeferredMonitorRemoval(Glib::RefPtr<Gdk::Monitor> mon
const std::string waybar::Client::getStyle(const std::string &style,
std::optional<Appearance> appearance = std::nullopt) {
auto gtk_settings = Gtk::Settings::get_default();
std::optional<std::string> css_file;
if (style.empty()) {
std::vector<std::string> search_files;
switch (appearance.value_or(portal->getAppearance())) {
case waybar::Appearance::LIGHT:
search_files.emplace_back("style-light.css");
gtk_settings->property_gtk_application_prefer_dark_theme() = false;
break;
case waybar::Appearance::DARK:
search_files.emplace_back("style-dark.css");
gtk_settings->property_gtk_application_prefer_dark_theme() = true;
break;
case waybar::Appearance::UNKNOWN:
break;
@@ -169,24 +173,34 @@ const std::string waybar::Client::getStyle(const std::string &style,
} else {
css_file = style;
}
if (!css_file) {
throw std::runtime_error("Missing required resource files");
}
spdlog::info("Using CSS file {}", css_file.value());
return css_file.value();
};
auto waybar::Client::setupCss(const std::string &css_file) -> void {
css_provider_ = Gtk::CssProvider::create();
style_context_ = Gtk::StyleContext::create();
auto screen = Gdk::Screen::get_default();
if (!screen) {
throw std::runtime_error("No default screen");
}
// Load our css file, wherever that may be hiding
if (css_provider_) {
Gtk::StyleContext::remove_provider_for_screen(screen, css_provider_);
css_provider_.reset();
}
css_provider_ = Gtk::CssProvider::create();
if (!css_provider_->load_from_path(css_file)) {
css_provider_.reset();
throw std::runtime_error("Can't open style file");
}
// there's always only one screen
style_context_->add_provider_for_screen(Gdk::Screen::get_default(), css_provider_,
GTK_STYLE_PROVIDER_PRIORITY_USER);
Gtk::StyleContext::add_provider_for_screen(screen, css_provider_,
GTK_STYLE_PROVIDER_PRIORITY_USER);
}
void waybar::Client::bindInterfaces() {
@@ -205,13 +219,22 @@ void waybar::Client::bindInterfaces() {
if (xdg_output_manager == nullptr) {
throw std::runtime_error("Failed to acquire required resources.");
}
// Disconnect previous signal handlers to prevent duplicate handlers on reload
monitor_added_connection_.disconnect();
monitor_removed_connection_.disconnect();
// Clear stale outputs from previous run
outputs_.clear();
// add existing outputs and subscribe to updates
for (auto i = 0; i < gdk_display->get_n_monitors(); ++i) {
auto monitor = gdk_display->get_monitor(i);
handleMonitorAdded(monitor);
}
gdk_display->signal_monitor_added().connect(sigc::mem_fun(*this, &Client::handleMonitorAdded));
gdk_display->signal_monitor_removed().connect(
monitor_added_connection_ = gdk_display->signal_monitor_added().connect(
sigc::mem_fun(*this, &Client::handleMonitorAdded));
monitor_removed_connection_ = gdk_display->signal_monitor_removed().connect(
sigc::mem_fun(*this, &Client::handleMonitorRemoved));
}

View File

@@ -2,7 +2,11 @@
#include <spdlog/spdlog.h>
#include <unistd.h>
#ifndef __OpenBSD__
#include <wordexp.h>
#else
#include <glob.h>
#endif
#include <filesystem>
#include <fstream>
@@ -34,6 +38,7 @@ std::vector<std::string> Config::tryExpandPath(const std::string &base,
spdlog::debug("Try expanding: {}", path.string());
std::vector<std::string> results;
#ifndef __OpenBSD__
wordexp_t p;
if (wordexp(path.c_str(), &p, 0) == 0) {
for (size_t i = 0; i < p.we_wordc; i++) {
@@ -44,6 +49,18 @@ std::vector<std::string> Config::tryExpandPath(const std::string &base,
}
wordfree(&p);
}
#else
glob_t p;
if (glob(path.c_str(), 0, NULL, &p) == 0) {
for (size_t i = 0; i < p.gl_pathc; i++) {
if (access(p.gl_pathv[i], F_OK) == 0) {
results.emplace_back(p.gl_pathv[i]);
spdlog::debug("Found config file: {}", p.gl_pathv[i]);
}
}
globfree(&p);
}
#endif
return results;
}
@@ -89,19 +106,49 @@ void Config::setupConfig(Json::Value &dst, const std::string &config_file, int d
mergeConfig(dst, tmp_config);
}
std::vector<std::string> Config::findIncludePath(const std::string &name,
const std::vector<std::string> &dirs) {
auto match1 = tryExpandPath(name, "");
if (!match1.empty()) {
return match1;
}
if (const char *dir = std::getenv(Config::CONFIG_PATH_ENV)) {
if (auto res = tryExpandPath(dir, name); !res.empty()) {
return res;
}
}
for (const auto &dir : dirs) {
if (auto res = tryExpandPath(dir, name); !res.empty()) {
return res;
}
}
return {};
}
void Config::resolveConfigIncludes(Json::Value &config, int depth) {
Json::Value includes = config["include"];
if (includes.isArray()) {
for (const auto &include : includes) {
spdlog::info("Including resource file: {}", include.asString());
for (const auto &match : tryExpandPath(include.asString(), "")) {
setupConfig(config, match, depth + 1);
auto matches = findIncludePath(include.asString());
if (!matches.empty()) {
for (const auto &match : matches) {
setupConfig(config, match, depth + 1);
}
} else {
spdlog::warn("Unable to find resource file: {}", include.asString());
}
}
} else if (includes.isString()) {
spdlog::info("Including resource file: {}", includes.asString());
for (const auto &match : tryExpandPath(includes.asString(), "")) {
setupConfig(config, match, depth + 1);
auto matches = findIncludePath(includes.asString());
if (!matches.empty()) {
for (const auto &match : matches) {
setupConfig(config, match, depth + 1);
}
} else {
spdlog::warn("Unable to find resource file: {}", includes.asString());
}
}
}

View File

@@ -17,8 +17,8 @@
#ifdef HAVE_WLR_TASKBAR
#include "modules/wlr/taskbar.hpp"
#endif
#ifdef HAVE_WLR_WORKSPACES
#include "modules/wlr/workspace_manager.hpp"
#ifdef HAVE_EXT_WORKSPACES
#include "modules/ext/workspace_manager.hpp"
#endif
#ifdef HAVE_RIVER
#include "modules/river/layout.hpp"
@@ -108,15 +108,13 @@
#ifdef HAVE_LIBWIREPLUMBER
#include "modules/wireplumber.hpp"
#endif
#ifdef HAVE_LIBCAVA
#include "modules/cava.hpp"
#endif
#ifdef HAVE_SYSTEMD_MONITOR
#include "modules/systemd_failed_units.hpp"
#endif
#ifdef HAVE_LIBGPS
#include "modules/gps.hpp"
#endif
#include "modules/cava/cava_frontend.hpp"
#include "modules/cffi.hpp"
#include "modules/custom.hpp"
#include "modules/image.hpp"
@@ -178,9 +176,9 @@ waybar::AModule* waybar::Factory::makeModule(const std::string& name,
return new waybar::modules::wlr::Taskbar(id, bar_, config_[name]);
}
#endif
#ifdef HAVE_WLR_WORKSPACES
if (ref == "wlr/workspaces") {
return new waybar::modules::wlr::WorkspaceManager(id, bar_, config_[name]);
#ifdef HAVE_EXT_WORKSPACES
if (ref == "ext/workspaces") {
return new waybar::modules::ext::WorkspaceManager(id, bar_, config_[name]);
}
#endif
#ifdef HAVE_RIVER
@@ -341,11 +339,9 @@ waybar::AModule* waybar::Factory::makeModule(const std::string& name,
return new waybar::modules::Wireplumber(id, config_[name]);
}
#endif
#ifdef HAVE_LIBCAVA
if (ref == "cava") {
return new waybar::modules::Cava(id, config_[name]);
return waybar::modules::cava::getModule(id, config_[name]);
}
#endif
#ifdef HAVE_SYSTEMD_MONITOR
if (ref == "systemd-failed-units") {
return new waybar::modules::SystemdFailedUnits(id, config_[name]);

View File

@@ -26,7 +26,7 @@ Gtk::RevealerTransitionType getPreferredTransitionType(bool is_vertical) {
Group::Group(const std::string& name, const std::string& id, const Json::Value& config,
bool vertical)
: AModule(config, name, id, true, true),
: AModule(config, name, id, true, false),
box{vertical ? Gtk::ORIENTATION_VERTICAL : Gtk::ORIENTATION_HORIZONTAL, 0},
revealer_box{vertical ? Gtk::ORIENTATION_VERTICAL : Gtk::ORIENTATION_HORIZONTAL, 0} {
box.set_name(name_);

View File

@@ -7,6 +7,7 @@
#include <list>
#include <mutex>
#include "bar.hpp"
#include "client.hpp"
#include "util/SafeSignal.hpp"
@@ -71,6 +72,45 @@ static void catchSignals(waybar::SafeSignal<int>& signal_handler) {
}
}
waybar::util::KillSignalAction getActionForBar(waybar::Bar* bar, int signal) {
switch (signal) {
case SIGUSR1:
return bar->getOnSigusr1Action();
case SIGUSR2:
return bar->getOnSigusr2Action();
default:
return waybar::util::KillSignalAction::NOOP;
}
}
void handleUserSignal(int signal, bool& reload) {
int i = 0;
for (auto& bar : waybar::Client::inst()->bars) {
switch (getActionForBar(bar.get(), signal)) {
case waybar::util::KillSignalAction::HIDE:
spdlog::debug("Visibility 'hide' for bar ", i);
bar->hide();
break;
case waybar::util::KillSignalAction::SHOW:
spdlog::debug("Visibility 'show' for bar ", i);
bar->show();
break;
case waybar::util::KillSignalAction::TOGGLE:
spdlog::debug("Visibility 'toggle' for bar ", i);
bar->toggle();
break;
case waybar::util::KillSignalAction::RELOAD:
spdlog::info("Reloading...");
reload = true;
waybar::Client::inst()->reset();
return;
case waybar::util::KillSignalAction::NOOP:
break;
}
i++;
}
}
// Must be called on the main thread.
//
// If this signal should restart or close the bar, this function will write
@@ -80,21 +120,15 @@ static void handleSignalMainThread(int signum, bool& reload) {
for (auto& bar : waybar::Client::inst()->bars) {
bar->handleSignal(signum);
}
return;
}
switch (signum) {
case SIGUSR1:
spdlog::debug("Visibility toggled");
for (auto& bar : waybar::Client::inst()->bars) {
bar->toggle();
}
handleUserSignal(SIGUSR1, reload);
break;
case SIGUSR2:
spdlog::info("Reloading...");
reload = true;
waybar::Client::inst()->reset();
handleUserSignal(SIGUSR2, reload);
break;
case SIGINT:
spdlog::info("Quitting.");

View File

@@ -38,10 +38,20 @@ auto waybar::modules::Backlight::update() -> void {
event_box_.show();
const uint8_t percent =
best->get_max() == 0 ? 100 : round(best->get_actual() * 100.0f / best->get_max());
std::string desc = fmt::format(fmt::runtime(format_), fmt::arg("percent", percent),
// Get the state and apply state-specific format if available
auto state = getState(percent);
std::string current_format = format_;
if (!state.empty()) {
std::string state_format_name = "format-" + state;
if (config_[state_format_name].isString()) {
current_format = config_[state_format_name].asString();
}
}
std::string desc = fmt::format(fmt::runtime(current_format), fmt::arg("percent", percent),
fmt::arg("icon", getIcon(percent)));
label_.set_markup(desc);
getState(percent);
if (tooltipEnabled()) {
std::string tooltip_format;
if (config_["tooltip-format"].isString()) {

View File

@@ -1,31 +1,41 @@
#include "modules/battery.hpp"
#include <algorithm>
#include <cctype>
#include "util/command.hpp"
#if defined(__FreeBSD__)
#include <sys/sysctl.h>
#endif
#include <libudev.h>
#include <poll.h>
#include <spdlog/spdlog.h>
#include <sys/signalfd.h>
#include <iostream>
waybar::modules::Battery::Battery(const std::string& id, const Bar& bar, const Json::Value& config)
: ALabel(config, "battery", id, "{capacity}%", 60), bar_(bar) {
: ALabel(config, "battery", id, "{capacity}%", 60), last_event_(""), bar_(bar) {
#if defined(__linux__)
battery_watch_fd_ = inotify_init1(IN_CLOEXEC);
if (battery_watch_fd_ == -1) {
throw std::runtime_error("Unable to listen batteries.");
}
global_watch_fd_ = inotify_init1(IN_CLOEXEC);
if (global_watch_fd_ == -1) {
throw std::runtime_error("Unable to listen batteries.");
udev_ = std::unique_ptr<udev, util::UdevDeleter>(udev_new());
if (udev_ == nullptr) {
throw std::runtime_error("udev_new failed");
}
// Watch the directory for any added or removed batteries
global_watch = inotify_add_watch(global_watch_fd_, data_dir_.c_str(), IN_CREATE | IN_DELETE);
if (global_watch < 0) {
throw std::runtime_error("Could not watch for battery plug/unplug");
mon_ = std::unique_ptr<udev_monitor, util::UdevMonitorDeleter>(
udev_monitor_new_from_netlink(udev_.get(), "kernel"));
if (mon_ == nullptr) {
throw std::runtime_error("udev monitor new failed");
}
if (udev_monitor_filter_add_match_subsystem_devtype(mon_.get(), "power_supply", nullptr) < 0) {
throw std::runtime_error("udev failed to add monitor filter");
}
udev_monitor_enable_receiving(mon_.get());
if (config_["weighted-average"].isBool()) weightedAverage_ = config_["weighted-average"].asBool();
#endif
spdlog::debug("battery: worker interval is {}", interval_.count());
worker();
}
@@ -33,11 +43,6 @@ waybar::modules::Battery::~Battery() {
#if defined(__linux__)
std::lock_guard<std::mutex> guard(battery_list_mutex_);
if (global_watch >= 0) {
inotify_rm_watch(global_watch_fd_, global_watch);
}
close(global_watch_fd_);
for (auto it = batteries_.cbegin(), next_it = it; it != batteries_.cend(); it = next_it) {
++next_it;
auto watch_id = (*it).second;
@@ -74,12 +79,18 @@ void waybar::modules::Battery::worker() {
dp.emit();
};
thread_battery_update_ = [this] {
struct inotify_event event = {0};
int nbytes = read(global_watch_fd_, &event, sizeof(event));
if (nbytes != sizeof(event) || event.mask & IN_IGNORED) {
poll_fds_[0].revents = 0;
poll_fds_[0].events = POLLIN;
poll_fds_[0].fd = udev_monitor_get_fd(mon_.get());
int ret = poll(poll_fds_.data(), poll_fds_.size(), -1);
if (ret < 0) {
thread_.stop();
return;
}
if ((poll_fds_[0].revents & POLLIN) != 0) {
signalfd_siginfo signal_info;
read(poll_fds_[0].fd, &signal_info, sizeof(signal_info));
}
refreshBatteries();
dp.emit();
};
@@ -582,8 +593,7 @@ waybar::modules::Battery::getInfos() {
}
// Handle weighted-average
if ((config_["weighted-average"].isBool() ? config_["weighted-average"].asBool() : false) &&
total_energy_exists && total_energy_full_exists) {
if (weightedAverage_ && total_energy_exists && total_energy_full_exists) {
if (total_energy_full > 0.0f)
calculated_capacity = ((float)total_energy * 100.0f / (float)total_energy_full);
}
@@ -676,19 +686,24 @@ auto waybar::modules::Battery::update() -> void {
status = getAdapterStatus(capacity);
}
auto status_pretty = status;
puts(status.c_str());
// Transform to lowercase and replace space with dash
std::transform(status.begin(), status.end(), status.begin(),
[](char ch) { return ch == ' ' ? '-' : std::tolower(ch); });
std::ranges::transform(status.begin(), status.end(), status.begin(),
[](char ch) { return ch == ' ' ? '-' : std::tolower(ch); });
auto format = format_;
auto state = getState(capacity, true);
processEvents(state, status, capacity);
setBarClass(state);
auto time_remaining_formatted = formatTimeRemaining(time_remaining);
if (tooltipEnabled()) {
std::string tooltip_text_default;
std::string tooltip_format = "{timeTo}";
if (time_remaining != 0) {
std::string time_to = std::string("Time to ") + ((time_remaining > 0) ? "empty" : "full");
tooltip_text_default = time_to + ": " + time_remaining_formatted;
if (time_remaining > 0) {
tooltip_text_default = std::string("Empty in ") + time_remaining_formatted;
} else {
tooltip_text_default = std::string("Full in ") + time_remaining_formatted;
}
} else {
tooltip_text_default = status_pretty;
}
@@ -701,7 +716,7 @@ auto waybar::modules::Battery::update() -> void {
} else if (config_["tooltip-format"].isString()) {
tooltip_format = config_["tooltip-format"].asString();
}
label_.set_tooltip_text(
label_.set_tooltip_markup(
fmt::format(fmt::runtime(tooltip_format), fmt::arg("timeTo", tooltip_text_default),
fmt::arg("power", power), fmt::arg("capacity", capacity),
fmt::arg("time", time_remaining_formatted), fmt::arg("cycles", cycles),
@@ -767,3 +782,25 @@ void waybar::modules::Battery::setBarClass(std::string& state) {
bar_.window.get_style_context()->add_class(new_class);
}
}
void waybar::modules::Battery::processEvents(std::string& state, std::string& status,
uint8_t capacity) {
// There are no events specified, skip
auto events = config_["events"];
if (!events.isObject() || events.empty()) {
return;
}
std::string event_name = fmt::format("on-{}-{}", status == "discharging" ? status : "charging",
state.empty() ? std::to_string(capacity) : state);
if (last_event_ != event_name) {
spdlog::debug("battery: triggering event {}", event_name);
if (events[event_name].isString()) {
std::string exec = events[event_name].asString();
// Execute the command if it is not empty
if (!exec.empty()) {
util::command::exec(exec, "");
}
}
last_event_ = event_name;
}
}

View File

@@ -1,211 +0,0 @@
#include "modules/cava.hpp"
#include <spdlog/spdlog.h>
waybar::modules::Cava::Cava(const std::string& id, const Json::Value& config)
: ALabel(config, "cava", id, "{}", 60, false, false, false) {
// Load waybar module config
char cfgPath[PATH_MAX];
cfgPath[0] = '\0';
if (config_["cava_config"].isString()) strcpy(cfgPath, config_["cava_config"].asString().data());
// Load cava config
error_.length = 0;
if (!load_config(cfgPath, &prm_, false, &error_)) {
spdlog::error("Error loading config. {0}", error_.message);
exit(EXIT_FAILURE);
}
// Override cava parameters by the user config
prm_.inAtty = 0;
prm_.output = cava::output_method::OUTPUT_RAW;
strcpy(prm_.data_format, "ascii");
strcpy(prm_.raw_target, "/dev/stdout");
prm_.ascii_range = config_["format-icons"].size() - 1;
prm_.bar_width = 2;
prm_.bar_spacing = 0;
prm_.bar_height = 32;
prm_.bar_width = 1;
prm_.orientation = cava::ORIENT_TOP;
prm_.xaxis = cava::xaxis_scale::NONE;
prm_.mono_opt = cava::AVERAGE;
prm_.autobars = 0;
prm_.gravity = 0;
prm_.integral = 1;
if (config_["framerate"].isInt()) prm_.framerate = config_["framerate"].asInt();
if (config_["autosens"].isInt()) prm_.autosens = config_["autosens"].asInt();
if (config_["sensitivity"].isInt()) prm_.sens = config_["sensitivity"].asInt();
if (config_["bars"].isInt()) prm_.fixedbars = config_["bars"].asInt();
if (config_["lower_cutoff_freq"].isNumeric())
prm_.lower_cut_off = config_["lower_cutoff_freq"].asLargestInt();
if (config_["higher_cutoff_freq"].isNumeric())
prm_.upper_cut_off = config_["higher_cutoff_freq"].asLargestInt();
if (config_["sleep_timer"].isInt()) prm_.sleep_timer = config_["sleep_timer"].asInt();
if (config_["method"].isString())
prm_.input = cava::input_method_by_name(config_["method"].asString().c_str());
if (config_["source"].isString()) prm_.audio_source = config_["source"].asString().data();
if (config_["sample_rate"].isNumeric()) prm_.samplerate = config_["sample_rate"].asLargestInt();
if (config_["sample_bits"].isInt()) prm_.samplebits = config_["sample_bits"].asInt();
if (config_["stereo"].isBool()) prm_.stereo = config_["stereo"].asBool();
if (config_["reverse"].isBool()) prm_.reverse = config_["reverse"].asBool();
if (config_["bar_delimiter"].isInt()) prm_.bar_delim = config_["bar_delimiter"].asInt();
if (config_["monstercat"].isBool()) prm_.monstercat = config_["monstercat"].asBool();
if (config_["waves"].isBool()) prm_.waves = config_["waves"].asBool();
if (config_["noise_reduction"].isDouble())
prm_.noise_reduction = config_["noise_reduction"].asDouble();
if (config_["input_delay"].isInt())
fetch_input_delay_ = std::chrono::seconds(config_["input_delay"].asInt());
if (config_["hide_on_silence"].isBool()) hide_on_silence_ = config_["hide_on_silence"].asBool();
if (config_["format_silent"].isString()) format_silent_ = config_["format_silent"].asString();
// Make cava parameters configuration
plan_ = new cava::cava_plan{};
audio_raw_.height = prm_.ascii_range;
audio_data_.format = -1;
audio_data_.source = new char[1 + strlen(prm_.audio_source)];
audio_data_.source[0] = '\0';
strcpy(audio_data_.source, prm_.audio_source);
audio_data_.rate = 0;
audio_data_.samples_counter = 0;
audio_data_.channels = 2;
audio_data_.IEEE_FLOAT = 0;
audio_data_.input_buffer_size = BUFFER_SIZE * audio_data_.channels;
audio_data_.cava_buffer_size = audio_data_.input_buffer_size * 8;
audio_data_.cava_in = new double[audio_data_.cava_buffer_size]{0.0};
audio_data_.terminate = 0;
audio_data_.suspendFlag = false;
input_source_ = get_input(&audio_data_, &prm_);
if (!input_source_) {
spdlog::error("cava API didn't provide input audio source method");
exit(EXIT_FAILURE);
}
// Calculate delay for Update() thread
frame_time_milsec_ = std::chrono::milliseconds((int)(1e3 / prm_.framerate));
// Init cava plan, audio_raw structure
audio_raw_init(&audio_data_, &audio_raw_, &prm_, plan_);
if (!plan_) spdlog::error("cava plan is not provided");
audio_raw_.previous_frame[0] = -1; // For first Update() call need to rePaint text message
// Read audio source trough cava API. Cava orginizes this process via infinity loop
thread_fetch_input_ = [this] {
thread_fetch_input_.sleep_for(fetch_input_delay_);
input_source_(&audio_data_);
};
thread_ = [this] {
dp.emit();
thread_.sleep_for(frame_time_milsec_);
};
}
waybar::modules::Cava::~Cava() {
thread_fetch_input_.stop();
thread_.stop();
delete plan_;
plan_ = nullptr;
}
void upThreadDelay(std::chrono::milliseconds& delay, std::chrono::seconds& delta) {
if (delta == std::chrono::seconds{0}) {
delta += std::chrono::seconds{1};
delay += delta;
}
}
void downThreadDelay(std::chrono::milliseconds& delay, std::chrono::seconds& delta) {
if (delta > std::chrono::seconds{0}) {
delay -= delta;
delta -= std::chrono::seconds{1};
}
}
auto waybar::modules::Cava::update() -> void {
if (audio_data_.suspendFlag) return;
silence_ = true;
for (int i{0}; i < audio_data_.input_buffer_size; ++i) {
if (audio_data_.cava_in[i]) {
silence_ = false;
sleep_counter_ = 0;
break;
}
}
if (silence_ && prm_.sleep_timer != 0) {
if (sleep_counter_ <=
(int)(std::chrono::milliseconds(prm_.sleep_timer * 1s) / frame_time_milsec_)) {
++sleep_counter_;
silence_ = false;
}
}
if (!silence_ || prm_.sleep_timer == 0) {
downThreadDelay(frame_time_milsec_, suspend_silence_delay_);
// Process: execute cava
pthread_mutex_lock(&audio_data_.lock);
cava::cava_execute(audio_data_.cava_in, audio_data_.samples_counter, audio_raw_.cava_out,
plan_);
if (audio_data_.samples_counter > 0) audio_data_.samples_counter = 0;
pthread_mutex_unlock(&audio_data_.lock);
// Do transformation under raw data
audio_raw_fetch(&audio_raw_, &prm_, &rePaint_, plan_);
if (rePaint_ == 1) {
text_.clear();
for (int i{0}; i < audio_raw_.number_of_bars; ++i) {
audio_raw_.previous_frame[i] = audio_raw_.bars[i];
text_.append(
getIcon((audio_raw_.bars[i] > prm_.ascii_range) ? prm_.ascii_range : audio_raw_.bars[i],
"", prm_.ascii_range + 1));
if (prm_.bar_delim != 0) text_.push_back(prm_.bar_delim);
}
label_.set_markup(text_);
label_.show();
ALabel::update();
label_.get_style_context()->add_class("updated");
}
label_.get_style_context()->remove_class("silent");
} else {
upThreadDelay(frame_time_milsec_, suspend_silence_delay_);
if (hide_on_silence_)
label_.hide();
else if (config_["format_silent"].isString())
label_.set_markup(format_silent_);
label_.get_style_context()->add_class("silent");
label_.get_style_context()->remove_class("updated");
}
}
auto waybar::modules::Cava::doAction(const std::string& name) -> void {
if ((actionMap_[name])) {
(this->*actionMap_[name])();
} else
spdlog::error("Cava. Unsupported action \"{0}\"", name);
}
// Cava actions
void waybar::modules::Cava::pause_resume() {
pthread_mutex_lock(&audio_data_.lock);
if (audio_data_.suspendFlag) {
audio_data_.suspendFlag = false;
pthread_cond_broadcast(&audio_data_.resumeCond);
downThreadDelay(frame_time_milsec_, suspend_silence_delay_);
} else {
audio_data_.suspendFlag = true;
upThreadDelay(frame_time_milsec_, suspend_silence_delay_);
}
pthread_mutex_unlock(&audio_data_.lock);
}

View File

@@ -0,0 +1,271 @@
#include "modules/cava/cavaGLSL.hpp"
#include <spdlog/spdlog.h>
#include <fstream>
waybar::modules::cava::CavaGLSL::CavaGLSL(const std::string& id, const Json::Value& config)
: AModule(config, "cavaGLSL", id, false, false),
backend_{waybar::modules::cava::CavaBackend::inst(config)} {
set_name(name_);
if (config_["hide_on_silence"].isBool()) hide_on_silence_ = config_["hide_on_silence"].asBool();
if (!id.empty()) {
get_style_context()->add_class(id);
}
get_style_context()->add_class(MODULE_CLASS);
set_use_es(true);
// set_auto_render(true);
signal_realize().connect(sigc::mem_fun(*this, &CavaGLSL::onRealize));
signal_render().connect(sigc::mem_fun(*this, &CavaGLSL::onRender), false);
// Get parameters_config struct from the backend
prm_ = *backend_->getPrm();
// Set widget length
int length{0};
if (config_["min-length"].isUInt())
length = config_["min-length"].asUInt();
else if (config_["max-length"].isUInt())
length = config_["max-length"].asUInt();
else
length = prm_.sdl_width;
set_size_request(length, prm_.sdl_height);
// Subscribe for changes
backend_->signal_audio_raw_update().connect(sigc::mem_fun(*this, &CavaGLSL::onUpdate));
// Subscribe for silence
backend_->signal_silence().connect(sigc::mem_fun(*this, &CavaGLSL::onSilence));
event_box_.add(*this);
}
auto waybar::modules::cava::CavaGLSL::onUpdate(const ::cava::audio_raw& input) -> void {
Glib::signal_idle().connect_once([this, input]() {
m_data_ = std::make_shared<::cava::audio_raw>(input);
if (silence_) {
get_style_context()->remove_class("silent");
if (!get_style_context()->has_class("updated")) get_style_context()->add_class("updated");
show();
silence_ = false;
}
queue_render();
});
}
auto waybar::modules::cava::CavaGLSL::onSilence() -> void {
Glib::signal_idle().connect_once([this]() {
if (!silence_) {
if (get_style_context()->has_class("updated")) get_style_context()->remove_class("updated");
if (hide_on_silence_) hide();
silence_ = true;
get_style_context()->add_class("silent");
// Set clear color to black
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
queue_render();
}
});
}
bool waybar::modules::cava::CavaGLSL::onRender(const Glib::RefPtr<Gdk::GLContext>& context) {
if (!m_data_) return true;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture_);
glUniform1i(glGetUniformLocation(shaderProgram_, "inputTexture"), 0);
glUniform1fv(uniform_bars_, m_data_->number_of_bars, m_data_->bars_raw);
glUniform1fv(uniform_previous_bars_, m_data_->number_of_bars, m_data_->previous_bars_raw);
glUniform1i(uniform_bars_count_, m_data_->number_of_bars);
++frame_counter;
glUniform1f(uniform_time_, (frame_counter / backend_->getFrameTimeMilsec().count()) / 1e3);
// glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDrawElements(GL_TRIANGLE_FAN, 4, GL_UNSIGNED_INT, nullptr);
glBindFramebuffer(GL_FRAMEBUFFER, fbo_);
glDrawElements(GL_TRIANGLE_FAN, 4, GL_UNSIGNED_INT, nullptr);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
return true;
}
void waybar::modules::cava::CavaGLSL::onRealize() {
make_current();
initShaders();
initGLSL();
initSurface();
}
struct colors {
uint16_t R;
uint16_t G;
uint16_t B;
};
static void parse_color(char* color_string, struct colors* color) {
if (color_string[0] == '#') {
sscanf(++color_string, "%02hx%02hx%02hx", &color->R, &color->G, &color->B);
}
}
void waybar::modules::cava::CavaGLSL::initGLSL() {
GLint gVertexPos2DLocation{glGetAttribLocation(shaderProgram_, "vertexPosition_modelspace")};
if (gVertexPos2DLocation == -1) {
spdlog::error("{0}. Could not find vertex position shader variable", name_);
}
glClearColor(0.f, 0.f, 0.f, 1.f);
GLfloat vertexData[]{-1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f};
GLint indexData[]{0, 1, 2, 3};
GLuint gVBO{0};
glGenBuffers(1, &gVBO);
glBindBuffer(GL_ARRAY_BUFFER, gVBO);
glBufferData(GL_ARRAY_BUFFER, 2 * 4 * sizeof(GLfloat), vertexData, GL_STATIC_DRAW);
GLuint gIBO{0};
glGenBuffers(1, &gIBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gIBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 4 * sizeof(GLuint), indexData, GL_STATIC_DRAW);
GLuint gVAO{0};
glGenVertexArrays(1, &gVAO);
glBindVertexArray(gVAO);
glEnableVertexAttribArray(gVertexPos2DLocation);
glBindBuffer(GL_ARRAY_BUFFER, gVBO);
glVertexAttribPointer(gVertexPos2DLocation, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), nullptr);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gIBO);
glGenFramebuffers(1, &fbo_);
glBindFramebuffer(GL_FRAMEBUFFER, fbo_);
// Create a texture to attach the framebuffer
glGenTextures(1, &texture_);
glBindTexture(GL_TEXTURE_2D, texture_);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, prm_.sdl_width, prm_.sdl_height, 0, GL_RGBA,
GL_UNSIGNED_BYTE, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture_, 0);
// Check is framebuffer is complete
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
spdlog::error("{0}. Framebuffer not complete", name_);
}
// Unbind the framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, 0);
uniform_bars_ = glGetUniformLocation(shaderProgram_, "bars");
uniform_previous_bars_ = glGetUniformLocation(shaderProgram_, "previous_bars");
uniform_bars_count_ = glGetUniformLocation(shaderProgram_, "bars_count");
uniform_time_ = glGetUniformLocation(shaderProgram_, "shader_time");
GLuint err{glGetError()};
if (err != 0) {
spdlog::error("{0}. Error on initGLSL: {1}", name_, err);
}
}
void waybar::modules::cava::CavaGLSL::initSurface() {
colors color = {0};
GLint uniform_bg_col{glGetUniformLocation(shaderProgram_, "bg_color")};
parse_color(prm_.bcolor, &color);
glUniform3f(uniform_bg_col, (float)color.R / 255.0, (float)color.G / 255.0,
(float)color.B / 255.0);
GLint uniform_fg_col{glGetUniformLocation(shaderProgram_, "fg_color")};
parse_color(prm_.color, &color);
glUniform3f(uniform_fg_col, (float)color.R / 255.0, (float)color.G / 255.0,
(float)color.B / 255.0);
GLint uniform_res{glGetUniformLocation(shaderProgram_, "u_resolution")};
glUniform3f(uniform_res, (float)prm_.sdl_width, (float)prm_.sdl_height, 0.0f);
GLint uniform_bar_width{glGetUniformLocation(shaderProgram_, "bar_width")};
glUniform1i(uniform_bar_width, prm_.bar_width);
GLint uniform_bar_spacing{glGetUniformLocation(shaderProgram_, "bar_spacing")};
glUniform1i(uniform_bar_spacing, prm_.bar_spacing);
GLint uniform_gradient_count{glGetUniformLocation(shaderProgram_, "gradient_count")};
glUniform1i(uniform_gradient_count, prm_.gradient_count);
GLint uniform_gradient_colors{glGetUniformLocation(shaderProgram_, "gradient_colors")};
GLfloat gradient_colors[8][3];
for (int i{0}; i < prm_.gradient_count; ++i) {
parse_color(prm_.gradient_colors[i], &color);
gradient_colors[i][0] = (float)color.R / 255.0;
gradient_colors[i][1] = (float)color.G / 255.0;
gradient_colors[i][2] = (float)color.B / 255.0;
}
glUniform3fv(uniform_gradient_colors, 8, (const GLfloat*)gradient_colors);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDrawElements(GL_TRIANGLE_FAN, 4, GL_UNSIGNED_INT, nullptr);
}
void waybar::modules::cava::CavaGLSL::initShaders() {
shaderProgram_ = glCreateProgram();
GLuint vertexShader{loadShader(prm_.vertex_shader, GL_VERTEX_SHADER)};
GLuint fragmentShader{loadShader(prm_.fragment_shader, GL_FRAGMENT_SHADER)};
glAttachShader(shaderProgram_, vertexShader);
glAttachShader(shaderProgram_, fragmentShader);
glLinkProgram(shaderProgram_);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
// Check for linking errors
GLint success, len;
glGetProgramiv(shaderProgram_, GL_LINK_STATUS, &success);
if (!success) {
glGetProgramiv(shaderProgram_, GL_INFO_LOG_LENGTH, &len);
GLchar* infoLog{(char*)'\0'};
glGetProgramInfoLog(shaderProgram_, len, &len, infoLog);
spdlog::error("{0}. Shader linking error: {1}", name_, infoLog);
}
glReleaseShaderCompiler();
glUseProgram(shaderProgram_);
}
GLuint waybar::modules::cava::CavaGLSL::loadShader(const std::string& fileName, GLenum type) {
spdlog::debug("{0}. loadShader: {1}", name_, fileName);
// Read shader source code from the file
std::ifstream shaderFile{fileName};
if (!shaderFile.is_open()) {
spdlog::error("{0}. Could not open shader file: {1}", name_, fileName);
}
std::ostringstream buffer;
buffer << shaderFile.rdbuf(); // read file content into stringstream
std::string str{buffer.str()};
const char* shaderSource = str.c_str();
shaderFile.close();
GLuint shaderID{glCreateShader(type)};
if (shaderID == 0) spdlog::error("{0}. Error creating shader type: {0}", type);
glShaderSource(shaderID, 1, &shaderSource, nullptr);
glCompileShader(shaderID);
// Check for compilation errors
GLint success, len;
glGetShaderiv(shaderID, GL_COMPILE_STATUS, &success);
if (!success) {
glGetShaderiv(shaderID, GL_INFO_LOG_LENGTH, &len);
GLchar* infoLog{(char*)'\0'};
glGetShaderInfoLog(shaderID, len, nullptr, infoLog);
spdlog::error("{0}. Shader compilation error in {1}: {2}", name_, fileName, infoLog);
}
return shaderID;
}

View File

@@ -0,0 +1,58 @@
#include "modules/cava/cavaRaw.hpp"
#include <spdlog/spdlog.h>
waybar::modules::cava::Cava::Cava(const std::string& id, const Json::Value& config)
: ALabel(config, "cava", id, "{}", 60, false, false, false),
backend_{waybar::modules::cava::CavaBackend::inst(config)} {
if (config_["hide_on_silence"].isBool()) hide_on_silence_ = config_["hide_on_silence"].asBool();
if (config_["format_silent"].isString()) format_silent_ = config_["format_silent"].asString();
ascii_range_ = backend_->getAsciiRange();
backend_->signal_update().connect(sigc::mem_fun(*this, &Cava::onUpdate));
backend_->signal_silence().connect(sigc::mem_fun(*this, &Cava::onSilence));
backend_->Update();
}
auto waybar::modules::cava::Cava::doAction(const std::string& name) -> void {
if ((actionMap_[name])) {
(this->*actionMap_[name])();
} else
spdlog::error("Cava. Unsupported action \"{0}\"", name);
}
// Cava actions
void waybar::modules::cava::Cava::pause_resume() { backend_->doPauseResume(); }
auto waybar::modules::cava::Cava::onUpdate(const std::string& input) -> void {
Glib::signal_idle().connect_once([this, input]() {
if (silence_) {
label_.get_style_context()->remove_class("silent");
if (!label_.get_style_context()->has_class("updated"))
label_.get_style_context()->add_class("updated");
}
label_text_.clear();
for (auto& ch : input)
label_text_.append(getIcon((ch > ascii_range_) ? ascii_range_ : ch, "", ascii_range_ + 1));
label_.set_markup(label_text_);
label_.show();
ALabel::update();
});
silence_ = false;
}
auto waybar::modules::cava::Cava::onSilence() -> void {
Glib::signal_idle().connect_once([this]() {
if (!silence_) {
if (label_.get_style_context()->has_class("updated"))
label_.get_style_context()->remove_class("updated");
if (hide_on_silence_)
label_.hide();
else if (config_["format_silent"].isString())
label_.set_markup(format_silent_);
silence_ = true;
label_.get_style_context()->add_class("silent");
}
});
}

View File

@@ -0,0 +1,273 @@
#include "modules/cava/cava_backend.hpp"
#include <spdlog/spdlog.h>
std::shared_ptr<waybar::modules::cava::CavaBackend> waybar::modules::cava::CavaBackend::inst(
const Json::Value& config) {
static auto* backend = new CavaBackend(config);
static std::shared_ptr<CavaBackend> backend_ptr{backend};
return backend_ptr;
}
waybar::modules::cava::CavaBackend::CavaBackend(const Json::Value& config) : config_(config) {
// Load waybar module config
loadConfig();
// Read audio source trough cava API. Cava orginizes this process via infinity loop
read_thread_ = [this] {
try {
input_source_(&audio_data_);
} catch (const std::runtime_error& e) {
spdlog::warn("Cava backend. Read source error: {0}", e.what());
}
read_thread_.sleep_for(fetch_input_delay_);
loadConfig();
};
// Write outcoming data. Emit signals
out_thread_ = [this] {
doUpdate(false);
out_thread_.sleep_for(frame_time_milsec_);
};
}
waybar::modules::cava::CavaBackend::~CavaBackend() {
out_thread_.stop();
read_thread_.stop();
freeBackend();
}
static bool upThreadDelay(std::chrono::milliseconds& delay, std::chrono::seconds& delta) {
if (delta == std::chrono::seconds{0}) {
delta += std::chrono::seconds{1};
delay += delta;
return true;
}
return false;
}
static bool downThreadDelay(std::chrono::milliseconds& delay, std::chrono::seconds& delta) {
if (delta > std::chrono::seconds{0}) {
delay -= delta;
delta -= std::chrono::seconds{1};
return true;
}
return false;
}
bool waybar::modules::cava::CavaBackend::isSilence() {
for (int i{0}; i < audio_data_.input_buffer_size; ++i) {
if (audio_data_.cava_in[i]) {
return false;
}
}
return true;
}
int waybar::modules::cava::CavaBackend::getAsciiRange() { return prm_.ascii_range; }
// Process: execute cava
void waybar::modules::cava::CavaBackend::invoke() {
pthread_mutex_lock(&audio_data_.lock);
::cava::cava_execute(audio_data_.cava_in, audio_data_.samples_counter, audio_raw_.cava_out,
plan_);
if (audio_data_.samples_counter > 0) audio_data_.samples_counter = 0;
pthread_mutex_unlock(&audio_data_.lock);
}
// Do transformation under raw data
void waybar::modules::cava::CavaBackend::execute() {
invoke();
audio_raw_fetch(&audio_raw_, &prm_, &re_paint_, plan_);
if (re_paint_ == 1) {
output_.clear();
for (int i{0}; i < audio_raw_.number_of_bars; ++i) {
audio_raw_.previous_frame[i] = audio_raw_.bars[i];
output_.push_back(audio_raw_.bars[i]);
if (prm_.bar_delim != 0) output_.push_back(prm_.bar_delim);
}
}
}
void waybar::modules::cava::CavaBackend::doPauseResume() {
pthread_mutex_lock(&audio_data_.lock);
if (audio_data_.suspendFlag) {
audio_data_.suspendFlag = false;
pthread_cond_broadcast(&audio_data_.resumeCond);
downThreadDelay(frame_time_milsec_, suspend_silence_delay_);
} else {
audio_data_.suspendFlag = true;
upThreadDelay(frame_time_milsec_, suspend_silence_delay_);
}
pthread_mutex_unlock(&audio_data_.lock);
Update();
}
waybar::modules::cava::CavaBackend::type_signal_update
waybar::modules::cava::CavaBackend::signal_update() {
return m_signal_update_;
}
waybar::modules::cava::CavaBackend::type_signal_audio_raw_update
waybar::modules::cava::CavaBackend::signal_audio_raw_update() {
return m_signal_audio_raw_;
}
waybar::modules::cava::CavaBackend::type_signal_silence
waybar::modules::cava::CavaBackend::signal_silence() {
return m_signal_silence_;
}
void waybar::modules::cava::CavaBackend::Update() { doUpdate(true); }
void waybar::modules::cava::CavaBackend::doUpdate(bool force) {
if (audio_data_.suspendFlag && !force) return;
silence_ = isSilence();
if (!silence_) sleep_counter_ = 0;
if (silence_ && prm_.sleep_timer != 0) {
if (sleep_counter_ <=
(int)(std::chrono::milliseconds(prm_.sleep_timer * 1s) / frame_time_milsec_)) {
++sleep_counter_;
silence_ = false;
}
}
if (!silence_ || prm_.sleep_timer == 0) {
if (downThreadDelay(frame_time_milsec_, suspend_silence_delay_)) Update();
execute();
if (re_paint_ == 1 || force || prm_.continuous_rendering) {
m_signal_update_.emit(output_);
m_signal_audio_raw_.emit(audio_raw_);
}
} else {
if (upThreadDelay(frame_time_milsec_, suspend_silence_delay_)) Update();
if (silence_ != silence_prev_ || force) m_signal_silence_.emit();
}
silence_prev_ = silence_;
}
void waybar::modules::cava::CavaBackend::freeBackend() {
if (plan_ != NULL) {
cava_destroy(plan_);
plan_ = NULL;
}
audio_raw_clean(&audio_raw_);
pthread_mutex_lock(&audio_data_.lock);
audio_data_.terminate = 1;
pthread_mutex_unlock(&audio_data_.lock);
free_config(&prm_);
free(audio_data_.source);
free(audio_data_.cava_in);
}
void waybar::modules::cava::CavaBackend::loadConfig() {
freeBackend();
// Load waybar module config
char cfgPath[PATH_MAX];
cfgPath[0] = '\0';
if (config_["cava_config"].isString()) strcpy(cfgPath, config_["cava_config"].asString().data());
// Load cava config
error_.length = 0;
if (!load_config(cfgPath, &prm_, &error_)) {
spdlog::error("cava backend. Error loading config. {0}", error_.message);
exit(EXIT_FAILURE);
}
// Override cava parameters by the user config
prm_.inAtty = 0;
auto const output{prm_.output};
// prm_.output = ::cava::output_method::OUTPUT_RAW;
if (config_["data_format"].isString()) {
if (prm_.data_format) free(prm_.data_format);
prm_.data_format = strdup(config_["data_format"].asString().c_str());
}
if (config_["raw_target"].isString()) {
if (prm_.raw_target) free(prm_.raw_target);
prm_.raw_target = strdup(config_["raw_target"].asString().c_str());
}
prm_.ascii_range = config_["format-icons"].size() - 1;
if (config_["bar_spacing"].isInt()) prm_.bar_spacing = config_["bar_spacing"].asInt();
if (config_["bar_width"].isInt()) prm_.bar_width = config_["bar_width"].asInt();
if (config_["bar_height"].isInt()) prm_.bar_height = config_["bar_height"].asInt();
prm_.orientation = ::cava::ORIENT_TOP;
prm_.xaxis = ::cava::xaxis_scale::NONE;
prm_.mono_opt = ::cava::AVERAGE;
prm_.autobars = 0;
if (config_["gravity"].isInt()) prm_.gravity = config_["gravity"].asInt();
if (config_["integral"].isInt()) prm_.integral = config_["integral"].asInt();
if (config_["framerate"].isInt()) prm_.framerate = config_["framerate"].asInt();
// Calculate delay for Update() thread
frame_time_milsec_ = std::chrono::milliseconds((int)(1e3 / prm_.framerate));
if (config_["autosens"].isInt()) prm_.autosens = config_["autosens"].asInt();
if (config_["sensitivity"].isInt()) prm_.sens = config_["sensitivity"].asInt();
if (config_["bars"].isInt()) prm_.fixedbars = config_["bars"].asInt();
if (config_["lower_cutoff_freq"].isNumeric())
prm_.lower_cut_off = config_["lower_cutoff_freq"].asLargestInt();
if (config_["higher_cutoff_freq"].isNumeric())
prm_.upper_cut_off = config_["higher_cutoff_freq"].asLargestInt();
if (config_["sleep_timer"].isInt()) prm_.sleep_timer = config_["sleep_timer"].asInt();
if (config_["method"].isString())
prm_.input = ::cava::input_method_by_name(config_["method"].asString().c_str());
if (config_["source"].isString()) {
if (prm_.audio_source) free(prm_.audio_source);
prm_.audio_source = config_["source"].asString().data();
}
if (config_["sample_rate"].isNumeric()) prm_.samplerate = config_["sample_rate"].asLargestInt();
if (config_["sample_bits"].isInt()) prm_.samplebits = config_["sample_bits"].asInt();
if (config_["stereo"].isBool()) prm_.stereo = config_["stereo"].asBool();
if (config_["reverse"].isBool()) prm_.reverse = config_["reverse"].asBool();
if (config_["bar_delimiter"].isInt()) prm_.bar_delim = config_["bar_delimiter"].asInt();
if (config_["monstercat"].isBool()) prm_.monstercat = config_["monstercat"].asBool();
if (config_["waves"].isBool()) prm_.waves = config_["waves"].asBool();
if (config_["noise_reduction"].isDouble())
prm_.noise_reduction = config_["noise_reduction"].asDouble();
if (config_["input_delay"].isInt())
fetch_input_delay_ = std::chrono::seconds(config_["input_delay"].asInt());
if (config_["gradient"].isInt()) prm_.gradient = config_["gradient"].asInt();
if (prm_.gradient == 0)
prm_.gradient_count = 0;
else if (config_["gradient_count"].isInt())
prm_.gradient_count = config_["gradient_count"].asInt();
if (config_["sdl_width"].isInt()) prm_.sdl_width = config_["sdl_width"].asInt();
if (config_["sdl_height"].isInt()) prm_.sdl_height = config_["sdl_height"].asInt();
audio_raw_.height = prm_.ascii_range;
audio_data_.format = -1;
audio_data_.rate = 0;
audio_data_.samples_counter = 0;
audio_data_.channels = 2;
audio_data_.IEEE_FLOAT = 0;
audio_data_.input_buffer_size = BUFFER_SIZE * audio_data_.channels;
audio_data_.cava_buffer_size = audio_data_.input_buffer_size * 8;
audio_data_.terminate = 0;
audio_data_.suspendFlag = false;
input_source_ = get_input(&audio_data_, &prm_);
if (!input_source_) {
spdlog::error("cava backend API didn't provide input audio source method");
exit(EXIT_FAILURE);
}
prm_.output = ::cava::output_method::OUTPUT_RAW;
// Make cava parameters configuration
// Init cava plan, audio_raw structure
audio_raw_init(&audio_data_, &audio_raw_, &prm_, &plan_);
if (!plan_) spdlog::error("cava backend plan is not provided");
audio_raw_.previous_frame[0] = -1; // For first Update() call need to rePaint text message
prm_.output = output;
}
const struct ::cava::config_params* waybar::modules::cava::CavaBackend::getPrm() { return &prm_; }
std::chrono::milliseconds waybar::modules::cava::CavaBackend::getFrameTimeMilsec() {
return frame_time_milsec_;
};

View File

@@ -30,6 +30,9 @@ waybar::modules::Clock::Clock(const std::string& id, const Json::Value& config)
cldMonShift_{year(1900) / January},
tzInTooltip_{m_tlpFmt_.find("{" + kTZPlaceholder + "}") != std::string::npos},
tzCurrIdx_{0},
tzTooltipFormat_{config_["timezone-tooltip-format"].isString()
? config_["timezone-tooltip-format"].asString()
: ""},
ordInTooltip_{m_tlpFmt_.find("{" + kOrdPlaceholder + "}") != std::string::npos} {
m_tlpText_ = m_tlpFmt_;
@@ -63,8 +66,8 @@ waybar::modules::Clock::Clock(const std::string& id, const Json::Value& config)
if (cldInTooltip_) {
if (config_[kCldPlaceholder]["mode"].isString()) {
const std::string cfgMode{config_[kCldPlaceholder]["mode"].asString()};
const std::map<std::string_view, const CldMode&> monthModes{{"month", CldMode::MONTH},
{"year", CldMode::YEAR}};
const std::map<std::string, CldMode> monthModes{{"month", CldMode::MONTH},
{"year", CldMode::YEAR}};
if (monthModes.find(cfgMode) != monthModes.end())
cldMode_ = monthModes.at(cfgMode);
else
@@ -73,6 +76,11 @@ waybar::modules::Clock::Clock(const std::string& id, const Json::Value& config)
"using instead",
cfgMode);
}
if (config_[kCldPlaceholder]["iso8601"].isBool()) {
iso8601Calendar_ = config_[kCldPlaceholder]["iso8601"].asBool();
}
if (config_[kCldPlaceholder]["weeks-pos"].isString()) {
if (config_[kCldPlaceholder]["weeks-pos"].asString() == "left") cldWPos_ = WS::LEFT;
if (config_[kCldPlaceholder]["weeks-pos"].asString() == "right") cldWPos_ = WS::RIGHT;
@@ -92,23 +100,25 @@ waybar::modules::Clock::Clock(const std::string& id, const Json::Value& config)
fmtMap_.insert({2, "{}"});
if (config_[kCldPlaceholder]["format"]["today"].isString()) {
fmtMap_.insert({3, config_[kCldPlaceholder]["format"]["today"].asString()});
cldBaseDay_ =
year_month_day{
floor<days>(zoned_time{local_zone(), system_clock::now()}.get_local_time())}
.day();
auto local_time = zoned_time{local_zone(), system_clock::now()}.get_local_time();
cldBaseDay_ = year_month_day{floor<days>(local_time)}.day();
} else
fmtMap_.insert({3, "{}"});
if (config_[kCldPlaceholder]["format"]["weeks"].isString() && cldWPos_ != WS::HIDDEN) {
const auto defaultFmt =
iso8601Calendar_ ? "{:%V}" : ((first_day_of_week() == Monday) ? "{:%W}" : "{:%U}");
fmtMap_.insert({4, std::regex_replace(config_[kCldPlaceholder]["format"]["weeks"].asString(),
std::regex("\\{\\}"),
(first_day_of_week() == Monday) ? "{:%W}" : "{:%U}")});
std::regex("\\{\\}"), defaultFmt)});
Glib::ustring tmp{std::regex_replace(fmtMap_[4], std::regex("</?[^>]+>|\\{.*\\}"), "")};
cldWnLen_ += tmp.size();
} else {
if (cldWPos_ != WS::HIDDEN)
fmtMap_.insert({4, (first_day_of_week() == Monday) ? "{:%W}" : "{:%U}"});
else
if (cldWPos_ != WS::HIDDEN) {
const auto defaultFmt =
iso8601Calendar_ ? "{:%V}" : ((first_day_of_week() == Monday) ? "{:%W}" : "{:%U}");
fmtMap_.insert({4, defaultFmt});
} else {
cldWnLen_ = 0;
}
}
if (config_[kCldPlaceholder]["mode-mon-col"].isInt()) {
cldMonCols_ = config_[kCldPlaceholder]["mode-mon-col"].asInt();
@@ -188,11 +198,26 @@ auto waybar::modules::Clock::getTZtext(sys_seconds now) -> std::string {
if (tzList_.size() == 1) return "";
std::stringstream os;
bool first = true;
for (size_t tz_idx{0}; tz_idx < tzList_.size(); ++tz_idx) {
if (static_cast<int>(tz_idx) == tzCurrIdx_) continue;
const auto* tz = tzList_[tz_idx] != nullptr ? tzList_[tz_idx] : local_zone();
// Skip local timezone (nullptr) - never show it in tooltip
if (tzList_[tz_idx] == nullptr) continue;
// Skip current timezone unless timezone-tooltip-format is specified
if (static_cast<int>(tz_idx) == tzCurrIdx_ && tzTooltipFormat_.empty()) continue;
const auto* tz = tzList_[tz_idx];
auto zt{zoned_time{tz, now}};
os << fmt_lib::vformat(m_locale_, format_, fmt_lib::make_format_args(zt)) << '\n';
// Add newline before each entry except the first
if (!first) {
os << '\n';
}
first = false;
// Use timezone-tooltip-format if specified, otherwise use format_
const std::string& fmt = tzTooltipFormat_.empty() ? format_ : tzTooltipFormat_;
os << fmt_lib::vformat(m_locale_, fmt, fmt_lib::make_format_args(zt));
}
return os.str();
@@ -204,9 +229,11 @@ const unsigned cldRowsInMonth(const year_month& ym, const weekday& firstdow) {
auto cldGetWeekForLine(const year_month& ym, const weekday& firstdow, const unsigned line)
-> const year_month_weekday {
unsigned index{line - 2};
if (weekday{ym / 1} == firstdow) ++index;
return ym / firstdow[index];
const unsigned idx = line - 2;
const auto indexed_first_day_of_week =
weekday{ym / 1} == firstdow ? firstdow[idx + 1] : firstdow[idx];
return ym / indexed_first_day_of_week;
}
auto getCalendarLine(const year_month_day& currDate, const year_month ym, const unsigned line,
@@ -265,7 +292,7 @@ auto getCalendarLine(const year_month_day& currDate, const year_month ym, const
}
// Print non-first week
default: {
auto ymdTmp{cldGetWeekForLine(ym, firstdow, line)};
const auto ymdTmp{cldGetWeekForLine(ym, firstdow, line)};
if (ymdTmp.ok()) {
auto d{year_month_day{ymdTmp}.day()};
const auto dlast{(ym / last).day()};
@@ -356,8 +383,9 @@ auto waybar::modules::Clock::get_calendar(const year_month_day& today, const yea
: static_cast<const zoned_seconds&&>(zoned_seconds{
tz, local_days{cldGetWeekForLine(ymTmp, firstdow, line)}})))
<< ' ';
} else
} else {
os << pads;
}
}
}
@@ -481,6 +509,9 @@ using deleting_unique_ptr = std::unique_ptr<T, deleter_from_fn<fn>>;
// Computations done similarly to Linux cal utility.
auto waybar::modules::Clock::first_day_of_week() -> weekday {
if (iso8601Calendar_) {
return Monday;
}
#ifdef HAVE_LANGINFO_1STDAY
deleting_unique_ptr<std::remove_pointer<locale_t>::type, freelocale> posix_locale{
newlocale(LC_ALL, m_locale_.name().c_str(), nullptr)};

View File

@@ -5,11 +5,12 @@
std::vector<float> waybar::modules::CpuFrequency::parseCpuFrequencies() {
std::vector<float> frequencies;
char buffer[256];
size_t len;
int32_t freq;
uint32_t i = 0;
#ifndef __OpenBSD__
char buffer[256];
uint32_t i = 0;
while (true) {
len = 4;
snprintf(buffer, 256, "dev.cpu.%u.freq", i);
@@ -17,6 +18,12 @@ std::vector<float> waybar::modules::CpuFrequency::parseCpuFrequencies() {
frequencies.push_back(freq);
++i;
}
#else
int getMhz[] = {CTL_HW, HW_CPUSPEED};
len = sizeof(freq);
sysctl(getMhz, 2, &freq, &len, NULL, 0);
frequencies.push_back((float)freq);
#endif
if (frequencies.empty()) {
spdlog::warn("cpu/bsd: parseCpuFrequencies failed, not found in sysctl");

View File

@@ -14,6 +14,9 @@ waybar::modules::Custom::Custom(const std::string& name, const std::string& id,
percentage_(0),
fp_(nullptr),
pid_(-1) {
if (config.isNull()) {
spdlog::warn("There is no configuration for 'custom/{}', element will be hidden", name);
}
dp.emit();
if (!config_["signal"].empty() && config_["interval"].empty() &&
config_["restart-interval"].empty()) {
@@ -86,9 +89,11 @@ void waybar::modules::Custom::continuousWorker() {
dp.emit();
spdlog::error("{} stopped unexpectedly, is it endless?", name_);
}
if (config_["restart-interval"].isUInt()) {
if (config_["restart-interval"].isNumeric()) {
pid_ = -1;
thread_.sleep_for(std::chrono::seconds(config_["restart-interval"].asUInt()));
thread_.sleep_for(std::chrono::milliseconds(
std::max(1L, // Minimum 1ms due to millisecond precision
static_cast<long>(config_["restart-interval"].asDouble() * 1000))));
fp_ = util::command::open(cmd, pid_, output_name_);
if (!fp_) {
throw std::runtime_error("Unable to open " + cmd);

View File

@@ -187,6 +187,12 @@ void Tags::handle_view_tags(uint32_t tag, uint32_t state, uint32_t clients, uint
button.get_style_context()->remove_class("occupied");
}
if (clients & TAG_INACTIVE) {
button.get_style_context()->remove_class("empty");
} else {
button.get_style_context()->add_class("empty");
}
if (state & TAG_ACTIVE) {
button.get_style_context()->add_class("focused");
} else {

View File

@@ -0,0 +1,504 @@
#include "modules/ext/workspace_manager.hpp"
#include <gdk/gdkwayland.h>
#include <gtkmm.h>
#include <spdlog/spdlog.h>
#include <algorithm>
#include <iostream>
#include <vector>
#include "client.hpp"
#include "gtkmm/widget.h"
#include "modules/ext/workspace_manager_binding.hpp"
namespace waybar::modules::ext {
// WorkspaceManager
uint32_t WorkspaceManager::group_global_id = 0;
uint32_t WorkspaceManager::workspace_global_id = 0;
std::map<std::string, std::string> Workspace::icon_map_;
WorkspaceManager::WorkspaceManager(const std::string &id, const waybar::Bar &bar,
const Json::Value &config)
: waybar::AModule(config, "workspaces", id, false, false), bar_(bar), box_(bar.orientation, 0) {
add_registry_listener(this);
// parse configuration
const auto config_sort_by_number = config_["sort-by-number"];
if (config_sort_by_number.isBool()) {
spdlog::warn("[ext/workspaces]: Prefer sort-by-id instead of sort-by-number");
sort_by_id_ = config_sort_by_number.asBool();
}
const auto config_sort_by_id = config_["sort-by-id"];
if (config_sort_by_id.isBool()) {
sort_by_id_ = config_sort_by_id.asBool();
}
const auto config_sort_by_name = config_["sort-by-name"];
if (config_sort_by_name.isBool()) {
sort_by_name_ = config_sort_by_name.asBool();
}
const auto config_sort_by_coordinates = config_["sort-by-coordinates"];
if (config_sort_by_coordinates.isBool()) {
sort_by_coordinates_ = config_sort_by_coordinates.asBool();
}
const auto config_all_outputs = config_["all-outputs"];
if (config_all_outputs.isBool()) {
all_outputs_ = config_all_outputs.asBool();
}
// setup UI
box_.set_name("workspaces");
if (!id.empty()) {
box_.get_style_context()->add_class(id);
}
box_.get_style_context()->add_class(MODULE_CLASS);
event_box_.add(box_);
spdlog::debug("[ext/workspaces]: Workspace manager created");
}
WorkspaceManager::~WorkspaceManager() {
workspaces_.clear();
groups_.clear();
if (ext_manager_ != nullptr) {
auto *display = Client::inst()->wl_display;
// Send `stop` request and wait for one roundtrip.
ext_workspace_manager_v1_stop(ext_manager_);
wl_display_roundtrip(display);
}
if (ext_manager_ != nullptr) {
spdlog::warn("[ext/workspaces]: Destroying workspace manager before .finished event");
ext_workspace_manager_v1_destroy(ext_manager_);
}
spdlog::debug("[ext/workspaces]: Workspace manager destroyed");
}
void WorkspaceManager::register_manager(wl_registry *registry, uint32_t name, uint32_t version) {
if (ext_manager_ != nullptr) {
spdlog::warn("[ext/workspaces]: Register workspace manager again although already registered!");
return;
}
if (version != 1) {
spdlog::warn("[ext/workspaces]: Using different workspace manager protocol version: {}",
version);
}
ext_manager_ = workspace_manager_bind(registry, name, version, this);
}
void WorkspaceManager::remove_workspace_group(uint32_t id) {
const auto it =
std::find_if(groups_.begin(), groups_.end(), [id](const auto &g) { return g->id() == id; });
if (it == groups_.end()) {
spdlog::warn("[ext/workspaces]: Can't find workspace group with id {}", id);
return;
}
groups_.erase(it);
}
void WorkspaceManager::remove_workspace(uint32_t id) {
const auto it = std::find_if(workspaces_.begin(), workspaces_.end(),
[id](const auto &w) { return w->id() == id; });
if (it == workspaces_.end()) {
spdlog::warn("[ext/workspaces]: Can't find workspace with id {}", id);
return;
}
workspaces_.erase(it);
}
void WorkspaceManager::handle_workspace_group(ext_workspace_group_handle_v1 *handle) {
const auto new_id = ++group_global_id;
groups_.push_back(std::make_unique<WorkspaceGroup>(*this, handle, new_id));
spdlog::debug("[ext/workspaces]: Workspace group {} created", new_id);
}
void WorkspaceManager::handle_workspace(ext_workspace_handle_v1 *handle) {
const auto new_id = ++workspace_global_id;
const auto new_name = std::to_string(++workspace_name);
workspaces_.push_back(std::make_unique<Workspace>(config_, *this, handle, new_id, new_name));
set_needs_sorting();
spdlog::debug("[ext/workspaces]: Workspace {} created", new_id);
}
void WorkspaceManager::handle_done() { dp.emit(); }
void WorkspaceManager::handle_finished() {
spdlog::debug("[ext/workspaces]: Finishing workspace manager");
ext_workspace_manager_v1_destroy(ext_manager_);
ext_manager_ = nullptr;
}
void WorkspaceManager::commit() const { ext_workspace_manager_v1_commit(ext_manager_); }
void WorkspaceManager::update() {
spdlog::debug("[ext/workspaces]: Updating state");
if (needs_sorting_) {
clear_buttons();
sort_workspaces();
needs_sorting_ = false;
}
update_buttons();
AModule::update();
}
bool WorkspaceManager::has_button(const Gtk::Button *button) {
const auto buttons = box_.get_children();
return std::find(buttons.begin(), buttons.end(), button) != buttons.end();
}
void WorkspaceManager::sort_workspaces() {
// determine if workspace ID's and names can be sort numerically or literally
auto is_numeric = [](const std::string &s) {
return !s.empty() && std::all_of(s.begin(), s.end(), ::isdigit);
};
auto sort_by_workspace_id_numerically =
std::all_of(workspaces_.begin(), workspaces_.end(),
[&](const auto &w) { return is_numeric(w->workspace_id()); });
auto sort_by_name_numerically = std::all_of(workspaces_.begin(), workspaces_.end(),
[&](const auto &w) { return is_numeric(w->name()); });
// sort based on configuration setting with sort-by-id as fallback
std::sort(workspaces_.begin(), workspaces_.end(), [&](const auto &w1, const auto &w2) {
if (sort_by_id_ || (!sort_by_name_ && !sort_by_coordinates_)) {
if (w1->workspace_id() == w2->workspace_id()) {
return w1->id() < w2->id();
}
if (sort_by_workspace_id_numerically) {
// the idea is that phonetic compare can be applied just to numbers
// with same number of digits
return w1->workspace_id().size() < w2->workspace_id().size() ||
(w1->workspace_id().size() == w2->workspace_id().size() &&
w1->workspace_id() < w2->workspace_id());
}
return w1->workspace_id() < w2->workspace_id();
}
if (sort_by_name_) {
if (w1->name() == w2->name()) {
return w1->id() < w2->id();
}
if (sort_by_name_numerically) {
// see above about numeric sorting
return w1->name().size() < w2->name().size() ||
(w1->name().size() == w2->name().size() && w1->name() < w2->name());
}
return w1->name() < w2->name();
}
if (sort_by_coordinates_) {
if (w1->coordinates() == w2->coordinates()) {
return w1->id() < w2->id();
}
return w1->coordinates() < w2->coordinates();
}
return w1->id() < w2->id();
});
}
void WorkspaceManager::clear_buttons() {
for (const auto &workspace : workspaces_) {
if (has_button(&workspace->button())) {
box_.remove(workspace->button());
}
}
}
void WorkspaceManager::update_buttons() {
const auto *output = gdk_wayland_monitor_get_wl_output(bar_.output->monitor->gobj());
// go through all workspace
for (const auto &workspace : workspaces_) {
const bool workspace_on_any_group_for_output =
std::any_of(groups_.begin(), groups_.end(), [&](const auto &group) {
const bool group_on_output = group->has_output(output) || all_outputs_;
const bool workspace_on_group = group->has_workspace(workspace->handle());
return group_on_output && workspace_on_group;
});
const bool bar_contains_button = has_button(&workspace->button());
// add or remove buttons if needed, update button state
if (workspace_on_any_group_for_output) {
if (!bar_contains_button) {
// add button to bar
box_.pack_start(workspace->button(), false, false);
workspace->button().show_all();
}
workspace->update();
} else {
if (bar_contains_button) {
// remove button from bar
box_.remove(workspace->button());
}
}
}
}
// WorkspaceGroup
WorkspaceGroup::WorkspaceGroup(WorkspaceManager &manager, ext_workspace_group_handle_v1 *handle,
uint32_t id)
: workspaces_manager_(manager), ext_handle_(handle), id_(id) {
add_workspace_group_listener(ext_handle_, this);
}
WorkspaceGroup::~WorkspaceGroup() {
if (ext_handle_ != nullptr) {
ext_workspace_group_handle_v1_destroy(ext_handle_);
}
spdlog::debug("[ext/workspaces]: Workspace group {} destroyed", id_);
}
bool WorkspaceGroup::has_output(const wl_output *output) {
return std::find(outputs_.begin(), outputs_.end(), output) != outputs_.end();
}
bool WorkspaceGroup::has_workspace(const ext_workspace_handle_v1 *workspace) {
return std::find(workspaces_.begin(), workspaces_.end(), workspace) != workspaces_.end();
}
void WorkspaceGroup::handle_capabilities(uint32_t capabilities) {
spdlog::debug("[ext/workspaces]: Capabilities for workspace group {}:", id_);
if ((capabilities & EXT_WORKSPACE_GROUP_HANDLE_V1_GROUP_CAPABILITIES_CREATE_WORKSPACE) ==
capabilities) {
spdlog::debug("[ext/workspaces]: - create-workspace");
}
}
void WorkspaceGroup::handle_output_enter(wl_output *output) { outputs_.push_back(output); }
void WorkspaceGroup::handle_output_leave(wl_output *output) {
const auto it = std::find(outputs_.begin(), outputs_.end(), output);
if (it != outputs_.end()) {
outputs_.erase(it);
}
}
void WorkspaceGroup::handle_workspace_enter(ext_workspace_handle_v1 *handle) {
workspaces_.push_back(handle);
}
void WorkspaceGroup::handle_workspace_leave(ext_workspace_handle_v1 *handle) {
const auto it = std::find(workspaces_.begin(), workspaces_.end(), handle);
if (it != workspaces_.end()) {
workspaces_.erase(it);
}
}
void WorkspaceGroup::handle_removed() {
spdlog::debug("[ext/workspaces]: Removing workspace group {}", id_);
workspaces_manager_.remove_workspace_group(id_);
}
// Workspace
Workspace::Workspace(const Json::Value &config, WorkspaceManager &manager,
ext_workspace_handle_v1 *handle, uint32_t id, const std::string &name)
: workspace_manager_(manager), ext_handle_(handle), id_(id), workspace_id_(name), name_(name) {
add_workspace_listener(ext_handle_, this);
// parse configuration
const auto &config_active_only = config["active-only"];
if (config_active_only.isBool()) {
active_only_ = config_active_only.asBool();
}
const auto &config_ignore_hidden = config["ignore-hidden"];
if (config_ignore_hidden.isBool()) {
ignore_hidden_ = config_ignore_hidden.asBool();
}
const auto &config_format = config["format"];
format_ = config_format.isString() ? config_format.asString() : "{name}";
with_icon_ = format_.find("{icon}") != std::string::npos;
if (with_icon_ && icon_map_.empty()) {
const auto &format_icons = config["format-icons"];
for (auto &n : format_icons.getMemberNames()) {
icon_map_.emplace(n, format_icons[n].asString());
}
}
const bool config_on_click = config["on-click"].isString();
if (config_on_click) {
on_click_action_ = config["on-click"].asString();
}
const bool config_on_click_middle = config["on-click-middle"].isString();
if (config_on_click_middle) {
on_click_middle_action_ = config["on-click-middle"].asString();
}
const bool config_on_click_right = config["on-click-right"].isString();
if (config_on_click_right) {
on_click_right_action_ = config["on-click-right"].asString();
}
// setup UI
if (config_on_click || config_on_click_middle || config_on_click_right) {
button_.add_events(Gdk::BUTTON_PRESS_MASK);
button_.signal_button_press_event().connect(sigc::mem_fun(*this, &Workspace::handle_clicked),
false);
}
button_.set_relief(Gtk::RELIEF_NONE);
content_.set_center_widget(label_);
button_.add(content_);
}
Workspace::~Workspace() {
if (ext_handle_ != nullptr) {
ext_workspace_handle_v1_destroy(ext_handle_);
}
spdlog::debug("[ext/workspaces]: Workspace {} destroyed", id_);
}
void Workspace::update() {
const auto style_context = button_.get_style_context();
// update style and visibility
if (!has_state(EXT_WORKSPACE_HANDLE_V1_STATE_ACTIVE)) {
style_context->remove_class("active");
}
if (!has_state(EXT_WORKSPACE_HANDLE_V1_STATE_URGENT)) {
style_context->remove_class("urgent");
}
if (!has_state(EXT_WORKSPACE_HANDLE_V1_STATE_HIDDEN)) {
style_context->remove_class("hidden");
}
if (has_state(EXT_WORKSPACE_HANDLE_V1_STATE_ACTIVE)) {
button_.set_visible(true);
style_context->add_class("active");
}
if (has_state(EXT_WORKSPACE_HANDLE_V1_STATE_URGENT)) {
button_.set_visible(true);
style_context->add_class("urgent");
}
if (has_state(EXT_WORKSPACE_HANDLE_V1_STATE_HIDDEN)) {
button_.set_visible(!active_only_ && !ignore_hidden_);
style_context->add_class("hidden");
}
if (state_ == 0) {
button_.set_visible(!active_only_);
}
// update label
label_.set_markup(fmt::format(fmt::runtime(format_), fmt::arg("name", name_),
fmt::arg("id", workspace_id_),
fmt::arg("icon", with_icon_ ? icon() : "")));
}
void Workspace::handle_id(const std::string &id) {
spdlog::debug("[ext/workspaces]: ID for workspace {}: {}", id_, id);
workspace_id_ = id;
workspace_manager_.set_needs_sorting();
}
void Workspace::handle_name(const std::string &name) {
spdlog::debug("[ext/workspaces]: Name for workspace {}: {}", id_, name);
name_ = name;
workspace_manager_.set_needs_sorting();
}
void Workspace::handle_coordinates(const std::vector<uint32_t> &coordinates) {
coordinates_ = coordinates;
workspace_manager_.set_needs_sorting();
}
void Workspace::handle_state(uint32_t state) { state_ = state; }
void Workspace::handle_capabilities(uint32_t capabilities) {
spdlog::debug("[ext/workspaces]: Capabilities for workspace {}:", id_);
if ((capabilities & EXT_WORKSPACE_HANDLE_V1_WORKSPACE_CAPABILITIES_ACTIVATE) == capabilities) {
spdlog::debug("[ext/workspaces]: - activate");
}
if ((capabilities & EXT_WORKSPACE_HANDLE_V1_WORKSPACE_CAPABILITIES_DEACTIVATE) == capabilities) {
spdlog::debug("[ext/workspaces]: - deactivate");
}
if ((capabilities & EXT_WORKSPACE_HANDLE_V1_WORKSPACE_CAPABILITIES_REMOVE) == capabilities) {
spdlog::debug("[ext/workspaces]: - remove");
}
if ((capabilities & EXT_WORKSPACE_HANDLE_V1_WORKSPACE_CAPABILITIES_ASSIGN) == capabilities) {
spdlog::debug("[ext/workspaces]: - assign");
}
}
void Workspace::handle_removed() {
spdlog::debug("[ext/workspaces]: Removing workspace {}", id_);
workspace_manager_.remove_workspace(id_);
}
bool Workspace::handle_clicked(const GdkEventButton *button) const {
std::string action;
if (button->button == GDK_BUTTON_PRIMARY) {
action = on_click_action_;
} else if (button->button == GDK_BUTTON_MIDDLE) {
action = on_click_middle_action_;
} else if (button->button == GDK_BUTTON_SECONDARY) {
action = on_click_right_action_;
}
if (action.empty()) {
return true;
}
if (action == "activate") {
ext_workspace_handle_v1_activate(ext_handle_);
} else if (action == "deactivate") {
ext_workspace_handle_v1_deactivate(ext_handle_);
} else if (action == "close") {
ext_workspace_handle_v1_remove(ext_handle_);
} else {
spdlog::warn("[ext/workspaces]: Unknown action {}", action);
}
workspace_manager_.commit();
return true;
}
std::string Workspace::icon() {
if (has_state(EXT_WORKSPACE_HANDLE_V1_STATE_ACTIVE)) {
const auto active_icon_it = icon_map_.find("active");
if (active_icon_it != icon_map_.end()) {
return active_icon_it->second;
}
}
const auto named_icon_it = icon_map_.find(name_);
if (named_icon_it != icon_map_.end()) {
return named_icon_it->second;
}
const auto default_icon_it = icon_map_.find("default");
if (default_icon_it != icon_map_.end()) {
return default_icon_it->second;
}
return name_;
}
} // namespace waybar::modules::ext

View File

@@ -0,0 +1,159 @@
#include "modules/ext/workspace_manager_binding.hpp"
#include <spdlog/spdlog.h>
#include <cstdint>
#include "client.hpp"
#include "modules/ext/workspace_manager.hpp"
namespace waybar::modules::ext {
static void handle_global(void *data, wl_registry *registry, uint32_t name, const char *interface,
uint32_t version) {
if (std::strcmp(interface, ext_workspace_manager_v1_interface.name) == 0) {
static_cast<WorkspaceManager *>(data)->register_manager(registry, name, version);
}
}
static void handle_global_remove(void *data, wl_registry *registry, uint32_t name) {
/* Nothing to do here */
}
static const wl_registry_listener registry_listener_impl = {.global = handle_global,
.global_remove = handle_global_remove};
void add_registry_listener(void *data) {
wl_display *display = Client::inst()->wl_display;
wl_registry *registry = wl_display_get_registry(display);
wl_registry_add_listener(registry, &registry_listener_impl, data);
wl_display_roundtrip(display);
}
static void workspace_manager_handle_workspace_group(
void *data, ext_workspace_manager_v1 *_, ext_workspace_group_handle_v1 *workspace_group) {
static_cast<WorkspaceManager *>(data)->handle_workspace_group(workspace_group);
}
static void workspace_manager_handle_workspace(void *data, ext_workspace_manager_v1 *_,
ext_workspace_handle_v1 *workspace) {
static_cast<WorkspaceManager *>(data)->handle_workspace(workspace);
}
static void workspace_manager_handle_done(void *data, ext_workspace_manager_v1 *_) {
static_cast<WorkspaceManager *>(data)->handle_done();
}
static void workspace_manager_handle_finished(void *data, ext_workspace_manager_v1 *_) {
static_cast<WorkspaceManager *>(data)->handle_finished();
}
static const ext_workspace_manager_v1_listener workspace_manager_impl = {
.workspace_group = workspace_manager_handle_workspace_group,
.workspace = workspace_manager_handle_workspace,
.done = workspace_manager_handle_done,
.finished = workspace_manager_handle_finished,
};
ext_workspace_manager_v1 *workspace_manager_bind(wl_registry *registry, uint32_t name,
uint32_t version, void *data) {
auto *workspace_manager = static_cast<ext_workspace_manager_v1 *>(
wl_registry_bind(registry, name, &ext_workspace_manager_v1_interface, version));
if (workspace_manager)
ext_workspace_manager_v1_add_listener(workspace_manager, &workspace_manager_impl, data);
else
spdlog::error("Failed to register manager");
return workspace_manager;
}
static void workspace_group_handle_capabilities(void *data, ext_workspace_group_handle_v1 *_,
uint32_t capabilities) {
static_cast<WorkspaceGroup *>(data)->handle_capabilities(capabilities);
}
static void workspace_group_handle_output_enter(void *data, ext_workspace_group_handle_v1 *_,
wl_output *output) {
static_cast<WorkspaceGroup *>(data)->handle_output_enter(output);
}
static void workspace_group_handle_output_leave(void *data, ext_workspace_group_handle_v1 *_,
wl_output *output) {
static_cast<WorkspaceGroup *>(data)->handle_output_leave(output);
}
static void workspace_group_handle_workspace_enter(void *data, ext_workspace_group_handle_v1 *_,
ext_workspace_handle_v1 *workspace) {
static_cast<WorkspaceGroup *>(data)->handle_workspace_enter(workspace);
}
static void workspace_group_handle_workspace_leave(void *data, ext_workspace_group_handle_v1 *_,
ext_workspace_handle_v1 *workspace) {
static_cast<WorkspaceGroup *>(data)->handle_workspace_leave(workspace);
}
static void workspace_group_handle_removed(void *data, ext_workspace_group_handle_v1 *_) {
static_cast<WorkspaceGroup *>(data)->handle_removed();
}
static const ext_workspace_group_handle_v1_listener workspace_group_impl = {
.capabilities = workspace_group_handle_capabilities,
.output_enter = workspace_group_handle_output_enter,
.output_leave = workspace_group_handle_output_leave,
.workspace_enter = workspace_group_handle_workspace_enter,
.workspace_leave = workspace_group_handle_workspace_leave,
.removed = workspace_group_handle_removed};
void add_workspace_group_listener(ext_workspace_group_handle_v1 *workspace_group_handle,
void *data) {
ext_workspace_group_handle_v1_add_listener(workspace_group_handle, &workspace_group_impl, data);
}
void workspace_handle_name(void *data, struct ext_workspace_handle_v1 *_, const char *name) {
static_cast<Workspace *>(data)->handle_name(name);
}
void workspace_handle_id(void *data, struct ext_workspace_handle_v1 *_, const char *id) {
static_cast<Workspace *>(data)->handle_id(id);
}
void workspace_handle_coordinates(void *data, struct ext_workspace_handle_v1 *_,
struct wl_array *coordinates) {
std::vector<uint32_t> coords_vec;
auto coords = static_cast<uint32_t *>(coordinates->data);
for (size_t i = 0; i < coordinates->size / sizeof(uint32_t); ++i) {
coords_vec.push_back(coords[i]);
}
static_cast<Workspace *>(data)->handle_coordinates(coords_vec);
}
void workspace_handle_state(void *data, struct ext_workspace_handle_v1 *workspace_handle,
uint32_t state) {
static_cast<Workspace *>(data)->handle_state(state);
}
static void workspace_handle_capabilities(void *data,
struct ext_workspace_handle_v1 *workspace_handle,
uint32_t capabilities) {
static_cast<Workspace *>(data)->handle_capabilities(capabilities);
}
void workspace_handle_removed(void *data, struct ext_workspace_handle_v1 *workspace_handle) {
static_cast<Workspace *>(data)->handle_removed();
}
static const ext_workspace_handle_v1_listener workspace_impl = {
.id = workspace_handle_id,
.name = workspace_handle_name,
.coordinates = workspace_handle_coordinates,
.state = workspace_handle_state,
.capabilities = workspace_handle_capabilities,
.removed = workspace_handle_removed};
void add_workspace_listener(ext_workspace_handle_v1 *workspace_handle, void *data) {
ext_workspace_handle_v1_add_listener(workspace_handle, &workspace_impl, data);
}
} // namespace waybar::modules::ext

View File

@@ -53,7 +53,6 @@ Gamemode::Gamemode(const std::string& id, const Json::Value& config)
if (config_["icon-spacing"].isUInt()) {
iconSpacing = config_["icon-spacing"].asUInt();
}
box_.set_spacing(iconSpacing);
// Whether to use icon or not
if (config_["use-icon"].isBool()) {
@@ -64,7 +63,6 @@ Gamemode::Gamemode(const std::string& id, const Json::Value& config)
if (config_["icon-size"].isUInt()) {
iconSize = config_["icon-size"].asUInt();
}
icon_.set_pixel_size(iconSize);
// Format
if (config_["format"].isString()) {
@@ -228,6 +226,11 @@ auto Gamemode::update() -> void {
iconName = DEFAULT_ICON_NAME;
}
icon_.set_from_icon_name(iconName, Gtk::ICON_SIZE_INVALID);
box_.set_spacing(iconSpacing);
icon_.set_pixel_size(iconSize);
} else {
box_.set_spacing(0);
icon_.set_pixel_size(0);
}
// Call parent update

View File

@@ -46,9 +46,14 @@ std::filesystem::path IPC::getSocketFolder(const char* instanceSig) {
IPC::IPC() {
// will start IPC and relay events to parseIPC
ipcThread_ = std::thread([this]() { socketListener(); });
socketOwnerPid_ = getpid();
}
IPC::~IPC() {
// Do no stop Hyprland IPC if a child process (with successful fork() but
// failed exec()) exits.
if (getpid() != socketOwnerPid_) return;
running_ = false;
spdlog::info("Hyprland IPC stopping...");
if (socketfd_ != -1) {
@@ -78,8 +83,6 @@ void IPC::socketListener() {
return;
}
if (!modulesReady) return;
spdlog::info("Hyprland IPC starting");
struct sockaddr_un addr;

View File

@@ -11,8 +11,6 @@ namespace waybar::modules::hyprland {
Language::Language(const std::string& id, const Bar& bar, const Json::Value& config)
: ALabel(config, "language", id, "{}", 0, true), bar_(bar), m_ipc(IPC::inst()) {
modulesReady = true;
// get the active layout when open
initLanguage();
@@ -70,8 +68,14 @@ void Language::onEvent(const std::string& ev) {
// Last comma before variants parenthesis, eg:
// activelayout>>micro-star-int'l-co.,-ltd.-msi-gk50-elite-gaming-keyboard,English (US, intl.,
// with dead keys)
std::string beforParenthesis(begin(ev), begin(ev) + ev.find_last_of('('));
auto layoutName = ev.substr(beforParenthesis.find_last_of(',') + 1);
std::string beforeParenthesis;
auto parenthesisPos = ev.find_last_of('(');
if (parenthesisPos == std::string::npos) {
beforeParenthesis = ev;
} else {
beforeParenthesis = std::string(begin(ev), begin(ev) + parenthesisPos);
}
auto layoutName = ev.substr(beforeParenthesis.find_last_of(',') + 1);
if (config_.isMember("keyboard-name") && kbName != config_["keyboard-name"].asString())
return; // ignore

View File

@@ -2,14 +2,10 @@
#include <spdlog/spdlog.h>
#include "util/sanitize_str.hpp"
namespace waybar::modules::hyprland {
Submap::Submap(const std::string& id, const Bar& bar, const Json::Value& config)
: ALabel(config, "submap", id, "{}", 0, true), bar_(bar), m_ipc(IPC::inst()) {
modulesReady = true;
parseConfig(config);
label_.hide();

View File

@@ -21,7 +21,6 @@ Window::Window(const std::string& id, const Bar& bar, const Json::Value& config)
: AAppIconLabel(config, "window", id, "{title}", 0, true), bar_(bar), m_ipc(IPC::inst()) {
std::unique_lock<std::shared_mutex> windowIpcUniqueLock(windowIpcSmtx);
modulesReady = true;
separateOutputs_ = config["separate-outputs"].asBool();
// register for hyprland ipc

View File

@@ -9,35 +9,29 @@
#include <vector>
#include "modules/hyprland/backend.hpp"
#include "util/sanitize_str.hpp"
namespace waybar::modules::hyprland {
WindowCount::WindowCount(const std::string& id, const Bar& bar, const Json::Value& config)
: AAppIconLabel(config, "windowcount", id, "{count}", 0, true), bar_(bar) {
modulesReady = true;
: AAppIconLabel(config, "windowcount", id, "{count}", 0, true), bar_(bar), m_ipc(IPC::inst()) {
separateOutputs_ =
config.isMember("separate-outputs") ? config["separate-outputs"].asBool() : true;
if (!gIPC) {
gIPC = std::make_unique<IPC>();
}
queryActiveWorkspace();
update();
dp.emit();
// register for hyprland ipc
gIPC->registerForIPC("fullscreen", this);
gIPC->registerForIPC("workspace", this);
gIPC->registerForIPC("focusedmon", this);
gIPC->registerForIPC("openwindow", this);
gIPC->registerForIPC("closewindow", this);
gIPC->registerForIPC("movewindow", this);
m_ipc.registerForIPC("fullscreen", this);
m_ipc.registerForIPC("workspace", this);
m_ipc.registerForIPC("focusedmon", this);
m_ipc.registerForIPC("openwindow", this);
m_ipc.registerForIPC("closewindow", this);
m_ipc.registerForIPC("movewindow", this);
}
WindowCount::~WindowCount() {
gIPC->unregisterForIPC(this);
m_ipc.unregisterForIPC(this);
// wait for possible event handler to finish
std::lock_guard<std::mutex> lg(mutex_);
}
@@ -70,7 +64,7 @@ auto WindowCount::update() -> void {
}
auto WindowCount::getActiveWorkspace() -> Workspace {
const auto workspace = gIPC->getSocket1JsonReply("activeworkspace");
const auto workspace = m_ipc.getSocket1JsonReply("activeworkspace");
if (workspace.isObject()) {
return Workspace::parse(workspace);
@@ -80,24 +74,31 @@ auto WindowCount::getActiveWorkspace() -> Workspace {
}
auto WindowCount::getActiveWorkspace(const std::string& monitorName) -> Workspace {
const auto monitors = gIPC->getSocket1JsonReply("monitors");
const auto monitors = m_ipc.getSocket1JsonReply("monitors");
if (monitors.isArray()) {
auto monitor = std::find_if(monitors.begin(), monitors.end(), [&](Json::Value monitor) {
return monitor["name"] == monitorName;
});
auto monitor = std::ranges::find_if(
monitors, [&](Json::Value monitor) { return monitor["name"] == monitorName; });
if (monitor == std::end(monitors)) {
spdlog::warn("Monitor not found: {}", monitorName);
return Workspace{-1, 0, false};
return Workspace{
.id = -1,
.windows = 0,
.hasfullscreen = false,
};
}
const int id = (*monitor)["activeWorkspace"]["id"].asInt();
const auto workspaces = gIPC->getSocket1JsonReply("workspaces");
const auto workspaces = m_ipc.getSocket1JsonReply("workspaces");
if (workspaces.isArray()) {
auto workspace = std::find_if(workspaces.begin(), workspaces.end(),
[&](Json::Value workspace) { return workspace["id"] == id; });
auto workspace = std::ranges::find_if(
workspaces, [&](Json::Value workspace) { return workspace["id"] == id; });
if (workspace == std::end(workspaces)) {
spdlog::warn("No workspace with id {}", id);
return Workspace{-1, 0, false};
return Workspace{
.id = -1,
.windows = 0,
.hasfullscreen = false,
};
}
return Workspace::parse(*workspace);
};
@@ -108,9 +109,9 @@ auto WindowCount::getActiveWorkspace(const std::string& monitorName) -> Workspac
auto WindowCount::Workspace::parse(const Json::Value& value) -> WindowCount::Workspace {
return Workspace{
value["id"].asInt(),
value["windows"].asInt(),
value["hasfullscreen"].asBool(),
.id = value["id"].asInt(),
.windows = value["windows"].asInt(),
.hasfullscreen = value["hasfullscreen"].asBool(),
};
}

View File

@@ -20,7 +20,7 @@ WindowCreationPayload::WindowCreationPayload(Json::Value const &client_data)
}
WindowCreationPayload::WindowCreationPayload(std::string workspace_name,
WindowAddress window_address, std::string window_repr)
WindowAddress window_address, WindowRepr window_repr)
: m_window(std::move(window_repr)),
m_windowAddress(std::move(window_address)),
m_workspaceName(std::move(workspace_name)) {
@@ -30,10 +30,11 @@ WindowCreationPayload::WindowCreationPayload(std::string workspace_name,
WindowCreationPayload::WindowCreationPayload(std::string workspace_name,
WindowAddress window_address, std::string window_class,
std::string window_title)
std::string window_title, bool is_active)
: m_window(std::make_pair(std::move(window_class), std::move(window_title))),
m_windowAddress(std::move(window_address)),
m_workspaceName(std::move(workspace_name)) {
m_workspaceName(std::move(workspace_name)),
m_isActive(is_active) {
clearAddr();
clearWorkspaceName();
}
@@ -92,13 +93,14 @@ void WindowCreationPayload::moveToWorkspace(std::string &new_workspace_name) {
m_workspaceName = new_workspace_name;
}
std::string WindowCreationPayload::repr(Workspaces &workspace_manager) {
WindowRepr WindowCreationPayload::repr(Workspaces &workspace_manager) {
if (std::holds_alternative<Repr>(m_window)) {
return std::get<Repr>(m_window);
}
if (std::holds_alternative<ClassAndTitle>(m_window)) {
auto [window_class, window_title] = std::get<ClassAndTitle>(m_window);
return workspace_manager.getRewrite(window_class, window_title);
auto const &[window_class, window_title] = std::get<ClassAndTitle>(m_window);
return {m_windowAddress, window_class, window_title,
workspace_manager.getRewrite(window_class, window_title), m_isActive};
}
// Unreachable
spdlog::error("WorkspaceWindow::repr: Unreachable");

View File

@@ -6,6 +6,8 @@
#include <utility>
#include "modules/hyprland/workspaces.hpp"
#include "util/command.hpp"
#include "util/icon_loader.hpp"
namespace waybar::modules::hyprland {
@@ -32,7 +34,12 @@ Workspace::Workspace(const Json::Value &workspace_data, Workspaces &workspace_ma
false);
m_button.set_relief(Gtk::RELIEF_NONE);
m_content.set_center_widget(m_label);
if (m_workspaceManager.enableTaskbar()) {
m_content.set_orientation(m_workspaceManager.taskbarOrientation());
m_content.pack_start(m_labelBefore, false, false);
} else {
m_content.set_center_widget(m_labelBefore);
}
m_button.add(m_content);
initializeWindowMap(clients_data);
@@ -47,9 +54,14 @@ void addOrRemoveClass(const Glib::RefPtr<Gtk::StyleContext> &context, bool condi
}
}
std::optional<std::string> Workspace::closeWindow(WindowAddress const &addr) {
if (m_windowMap.contains(addr)) {
return removeWindow(addr);
std::optional<WindowRepr> Workspace::closeWindow(WindowAddress const &addr) {
auto it = std::ranges::find_if(m_windowMap,
[&addr](const auto &window) { return window.address == addr; });
// If the vector contains the address, remove it and return the window representation
if (it != m_windowMap.end()) {
WindowRepr windowRepr = *it;
m_windowMap.erase(it);
return windowRepr;
}
return std::nullopt;
}
@@ -91,12 +103,43 @@ void Workspace::initializeWindowMap(const Json::Value &clients_data) {
}
}
void Workspace::setActiveWindow(WindowAddress const &addr) {
std::optional<long> activeIdx;
for (size_t i = 0; i < m_windowMap.size(); ++i) {
auto &window = m_windowMap[i];
bool isActive = (window.address == addr);
window.setActive(isActive);
if (isActive) {
activeIdx = i;
}
}
auto activeWindowPos = m_workspaceManager.activeWindowPosition();
if (activeIdx.has_value() && activeWindowPos != Workspaces::ActiveWindowPosition::NONE) {
auto window = std::move(m_windowMap[*activeIdx]);
m_windowMap.erase(m_windowMap.begin() + *activeIdx);
if (activeWindowPos == Workspaces::ActiveWindowPosition::FIRST) {
m_windowMap.insert(m_windowMap.begin(), std::move(window));
} else if (activeWindowPos == Workspaces::ActiveWindowPosition::LAST) {
m_windowMap.emplace_back(std::move(window));
}
}
}
void Workspace::insertWindow(WindowCreationPayload create_window_payload) {
if (!create_window_payload.isEmpty(m_workspaceManager)) {
auto repr = create_window_payload.repr(m_workspaceManager);
if (!repr.empty()) {
m_windowMap[create_window_payload.getAddress()] = repr;
if (!repr.empty() || m_workspaceManager.enableTaskbar()) {
auto addr = create_window_payload.getAddress();
auto it = std::ranges::find_if(
m_windowMap, [&addr](const auto &window) { return window.address == addr; });
// If the vector contains the address, update the window representation, otherwise insert it
if (it != m_windowMap.end()) {
*it = repr;
} else {
m_windowMap.emplace_back(repr);
}
}
}
};
@@ -109,12 +152,6 @@ bool Workspace::onWindowOpened(WindowCreationPayload const &create_window_payloa
return false;
}
std::string Workspace::removeWindow(WindowAddress const &addr) {
std::string windowRepr = m_windowMap[addr];
m_windowMap.erase(addr);
return windowRepr;
}
std::string &Workspace::selectIcon(std::map<std::string, std::string> &icons_map) {
spdlog::trace("Selecting icon for workspace {}", name());
if (isUrgent()) {
@@ -172,7 +209,7 @@ std::string &Workspace::selectIcon(std::map<std::string, std::string> &icons_map
return m_name;
}
void Workspace::update(const std::string &format, const std::string &icon) {
void Workspace::update(const std::string &workspace_icon) {
if (this->m_workspaceManager.persistentOnly() && !this->isPersistent()) {
m_button.hide();
return;
@@ -204,21 +241,144 @@ void Workspace::update(const std::string &format, const std::string &icon) {
addOrRemoveClass(styleContext, m_workspaceManager.getBarOutput() == output(), "hosting-monitor");
std::string windows;
auto windowSeparator = m_workspaceManager.getWindowSeparator();
// Optimization: The {windows} substitution string is only possible if the taskbar is disabled, no
// need to compute this if enableTaskbar() is true
if (!m_workspaceManager.enableTaskbar()) {
auto windowSeparator = m_workspaceManager.getWindowSeparator();
bool isNotFirst = false;
bool isNotFirst = false;
for (auto &[_pid, window_repr] : m_windowMap) {
if (isNotFirst) {
windows.append(windowSeparator);
for (const auto &window_repr : m_windowMap) {
if (isNotFirst) {
windows.append(windowSeparator);
}
isNotFirst = true;
windows.append(window_repr.repr_rewrite);
}
isNotFirst = true;
windows.append(window_repr);
}
m_label.set_markup(fmt::format(fmt::runtime(format), fmt::arg("id", id()),
fmt::arg("name", name()), fmt::arg("icon", icon),
fmt::arg("windows", windows)));
auto formatBefore = m_workspaceManager.formatBefore();
m_labelBefore.set_markup(fmt::format(fmt::runtime(formatBefore), fmt::arg("id", id()),
fmt::arg("name", name()), fmt::arg("icon", workspace_icon),
fmt::arg("windows", windows)));
m_labelBefore.get_style_context()->add_class("workspace-label");
if (m_workspaceManager.enableTaskbar()) {
updateTaskbar(workspace_icon);
}
}
bool Workspace::isEmpty() const {
auto ignore_list = m_workspaceManager.getIgnoredWindows();
if (ignore_list.empty()) {
return m_windows == 0;
}
// If there are windows but they are all ignored, consider the workspace empty
return std::all_of(
m_windowMap.begin(), m_windowMap.end(),
[this, &ignore_list](const auto &window_repr) { return shouldSkipWindow(window_repr); });
}
void Workspace::updateTaskbar(const std::string &workspace_icon) {
for (auto child : m_content.get_children()) {
if (child != &m_labelBefore) {
m_content.remove(*child);
}
}
bool isFirst = true;
auto processWindow = [&](const WindowRepr &window_repr) {
if (shouldSkipWindow(window_repr)) {
return; // skip
}
if (isFirst) {
isFirst = false;
} else if (m_workspaceManager.getWindowSeparator() != "") {
auto windowSeparator = Gtk::make_managed<Gtk::Label>(m_workspaceManager.getWindowSeparator());
m_content.pack_start(*windowSeparator, false, false);
windowSeparator->show();
}
auto window_box = Gtk::make_managed<Gtk::Box>(Gtk::ORIENTATION_HORIZONTAL);
window_box->set_tooltip_text(window_repr.window_title);
window_box->get_style_context()->add_class("taskbar-window");
if (window_repr.isActive) {
window_box->get_style_context()->add_class("active");
}
auto event_box = Gtk::manage(new Gtk::EventBox());
event_box->add(*window_box);
if (m_workspaceManager.onClickWindow() != "") {
event_box->signal_button_press_event().connect(
sigc::bind(sigc::mem_fun(*this, &Workspace::handleClick), window_repr.address));
}
auto text_before = fmt::format(fmt::runtime(m_workspaceManager.taskbarFormatBefore()),
fmt::arg("title", window_repr.window_title));
if (!text_before.empty()) {
auto window_label_before = Gtk::make_managed<Gtk::Label>(text_before);
window_box->pack_start(*window_label_before, true, true);
}
if (m_workspaceManager.taskbarWithIcon()) {
auto app_info_ = IconLoader::get_app_info_from_app_id_list(window_repr.window_class);
int icon_size = m_workspaceManager.taskbarIconSize();
auto window_icon = Gtk::make_managed<Gtk::Image>();
m_workspaceManager.iconLoader().image_load_icon(*window_icon, app_info_, icon_size);
window_box->pack_start(*window_icon, false, false);
}
auto text_after = fmt::format(fmt::runtime(m_workspaceManager.taskbarFormatAfter()),
fmt::arg("title", window_repr.window_title));
if (!text_after.empty()) {
auto window_label_after = Gtk::make_managed<Gtk::Label>(text_after);
window_box->pack_start(*window_label_after, true, true);
}
m_content.pack_start(*event_box, true, false);
event_box->show_all();
};
if (m_workspaceManager.taskbarReverseDirection()) {
for (auto it = m_windowMap.rbegin(); it != m_windowMap.rend(); ++it) {
processWindow(*it);
}
} else {
for (const auto &window_repr : m_windowMap) {
processWindow(window_repr);
}
}
auto formatAfter = m_workspaceManager.formatAfter();
if (!formatAfter.empty()) {
m_labelAfter.set_markup(fmt::format(fmt::runtime(formatAfter), fmt::arg("id", id()),
fmt::arg("name", name()),
fmt::arg("icon", workspace_icon)));
m_content.pack_end(m_labelAfter, false, false);
m_labelAfter.show();
}
}
bool Workspace::handleClick(const GdkEventButton *event_button, WindowAddress const &addr) const {
if (event_button->type == GDK_BUTTON_PRESS) {
std::string command = std::regex_replace(m_workspaceManager.onClickWindow(),
std::regex("\\{address\\}"), "0x" + addr);
command = std::regex_replace(command, std::regex("\\{button\\}"),
std::to_string(event_button->button));
auto res = util::command::execNoRead(command);
if (res.exit_code != 0) {
spdlog::error("Failed to execute {}: {}", command, res.out);
}
}
return true;
}
bool Workspace::shouldSkipWindow(const WindowRepr &window_repr) const {
auto ignore_list = m_workspaceManager.getIgnoredWindows();
auto it = std::ranges::find_if(ignore_list, [&window_repr](const auto &ignoreItem) {
return std::regex_match(window_repr.window_class, ignoreItem) ||
std::regex_match(window_repr.window_title, ignoreItem);
});
return it != ignore_list.end();
}
} // namespace waybar::modules::hyprland

View File

@@ -10,6 +10,7 @@
#include <utility>
#include "util/regex_collection.hpp"
#include "util/string.hpp"
namespace waybar::modules::hyprland {
@@ -18,7 +19,6 @@ Workspaces::Workspaces(const std::string &id, const Bar &bar, const Json::Value
m_bar(bar),
m_box(bar.orientation, 0),
m_ipc(IPC::inst()) {
modulesReady = true;
parseConfig(config);
m_box.set_name("workspaces");
@@ -65,14 +65,17 @@ Json::Value Workspaces::createMonitorWorkspaceData(std::string const &name,
void Workspaces::createWorkspace(Json::Value const &workspace_data,
Json::Value const &clients_data) {
auto workspaceName = workspace_data["name"].asString();
auto workspaceId = workspace_data["id"].asInt();
spdlog::debug("Creating workspace {}", workspaceName);
// avoid recreating existing workspaces
auto workspace =
std::ranges::find_if(m_workspaces, [workspaceName](std::unique_ptr<Workspace> const &w) {
return (workspaceName.starts_with("special:") && workspaceName.substr(8) == w->name()) ||
workspaceName == w->name();
});
auto workspace = std::ranges::find_if(m_workspaces, [&](std::unique_ptr<Workspace> const &w) {
if (workspaceId > 0) {
return w->id() == workspaceId;
}
return (workspaceName.starts_with("special:") && workspaceName.substr(8) == w->name()) ||
workspaceName == w->name();
});
if (workspace != m_workspaces.end()) {
// don't recreate workspace, but update persistency if necessary
@@ -253,10 +256,8 @@ void Workspaces::loadPersistentWorkspacesFromConfig(Json::Value const &clientsJs
// value is an array => create defined workspaces for this monitor
if (canCreate) {
for (const Json::Value &workspace : value) {
if (workspace.isInt()) {
spdlog::debug("Creating workspace {} on monitor {}", workspace, currentMonitor);
persistentWorkspacesToCreate.emplace_back(std::to_string(workspace.asInt()));
}
spdlog::debug("Creating workspace {} on monitor {}", workspace, currentMonitor);
persistentWorkspacesToCreate.emplace_back(workspace.asString());
}
} else {
// key is the workspace and value is array of monitors to create on
@@ -292,8 +293,18 @@ void Workspaces::loadPersistentWorkspacesFromWorkspaceRules(const Json::Value &c
if (!rule["persistent"].asBool()) {
continue;
}
auto const &workspace = rule.isMember("defaultName") ? rule["defaultName"].asString()
: rule["workspaceString"].asString();
auto workspace = rule.isMember("defaultName") ? rule["defaultName"].asString()
: rule["workspaceString"].asString();
// There could be persistent special workspaces, only show those when show-special is enabled.
if (workspace.starts_with("special:") && !showSpecial()) {
continue;
}
// The prefix "name:" cause mismatches with workspace names taken anywhere else.
if (workspace.starts_with("name:")) {
workspace = workspace.substr(5);
}
auto const &monitor = rule["monitor"].asString();
// create this workspace persistently if:
// 1. the allOutputs config option is enabled
@@ -340,6 +351,8 @@ void Workspaces::onEvent(const std::string &ev) {
onWorkspaceRenamed(payload);
} else if (eventName == "windowtitlev2") {
onWindowTitleEvent(payload);
} else if (eventName == "activewindowv2") {
onActiveWindowChanged(payload);
} else if (eventName == "configreloaded") {
onConfigReloaded();
}
@@ -489,12 +502,14 @@ void Workspaces::onWindowOpened(std::string const &payload) {
std::string windowTitle = payload.substr(nextCommaIdx + 1, payload.length() - nextCommaIdx);
m_windowsToCreate.emplace_back(workspaceName, windowAddress, windowClass, windowTitle);
bool isActive = m_currentActiveWindowAddress == windowAddress;
m_windowsToCreate.emplace_back(workspaceName, windowAddress, windowClass, windowTitle, isActive);
}
void Workspaces::onWindowClosed(std::string const &addr) {
spdlog::trace("Window closed: {}", addr);
updateWindowCount();
m_orphanWindowMap.erase(addr);
for (auto &workspace : m_workspaces) {
if (workspace->closeWindow(addr)) {
break;
@@ -507,7 +522,7 @@ void Workspaces::onWindowMoved(std::string const &payload) {
updateWindowCount();
auto [windowAddress, _, workspaceName] = splitTriplePayload(payload);
std::string windowRepr;
WindowRepr windowRepr;
// If the window was still queued to be created, just change its destination
// and exit
@@ -533,6 +548,7 @@ void Workspaces::onWindowMoved(std::string const &payload) {
// ...and then add it to the new workspace
if (!windowRepr.empty()) {
m_orphanWindowMap.erase(windowAddress);
m_windowsToCreate.emplace_back(workspaceName, windowAddress, windowRepr);
}
}
@@ -558,9 +574,10 @@ void Workspaces::onWindowTitleEvent(std::string const &payload) {
(*windowWorkspace)->insertWindow(std::move(wcp));
};
} else {
auto queuedWindow = std::ranges::find_if(m_windowsToCreate, [payload](auto &windowPayload) {
return windowPayload.getAddress() == payload;
});
auto queuedWindow =
std::ranges::find_if(m_windowsToCreate, [&windowAddress](auto &windowPayload) {
return windowPayload.getAddress() == windowAddress;
});
// If the window was queued, rename it in the queue
if (queuedWindow != m_windowsToCreate.end()) {
@@ -571,7 +588,7 @@ void Workspaces::onWindowTitleEvent(std::string const &payload) {
if (inserter.has_value()) {
Json::Value clientsData = m_ipc.getSocket1JsonReply("clients");
std::string jsonWindowAddress = fmt::format("0x{}", payload);
std::string jsonWindowAddress = fmt::format("0x{}", windowAddress);
auto client = std::ranges::find_if(clientsData, [jsonWindowAddress](auto &client) {
return client["address"].asString() == jsonWindowAddress;
@@ -583,6 +600,21 @@ void Workspaces::onWindowTitleEvent(std::string const &payload) {
}
}
void Workspaces::onActiveWindowChanged(WindowAddress const &activeWindowAddress) {
spdlog::trace("Active window changed: {}", activeWindowAddress);
m_currentActiveWindowAddress = activeWindowAddress;
for (auto &[address, window] : m_orphanWindowMap) {
window.setActive(address == activeWindowAddress);
}
for (auto const &workspace : m_workspaces) {
workspace->setActiveWindow(activeWindowAddress);
}
for (auto &window : m_windowsToCreate) {
window.setActive(window.getAddress() == activeWindowAddress);
}
}
void Workspaces::onConfigReloaded() {
spdlog::info("Hyprland config reloaded, reinitializing hyprland/workspaces module...");
init();
@@ -590,8 +622,9 @@ void Workspaces::onConfigReloaded() {
auto Workspaces::parseConfig(const Json::Value &config) -> void {
const auto &configFormat = config["format"];
m_format = configFormat.isString() ? configFormat.asString() : "{name}";
m_withIcon = m_format.find("{icon}") != std::string::npos;
m_formatBefore = configFormat.isString() ? configFormat.asString() : "{name}";
m_withIcon = m_formatBefore.find("{icon}") != std::string::npos;
auto withWindows = m_formatBefore.find("{windows}") != std::string::npos;
if (m_withIcon && m_iconsMap.empty()) {
populateIconsMap(config["format-icons"]);
@@ -609,6 +642,15 @@ auto Workspaces::parseConfig(const Json::Value &config) -> void {
populateIgnoreWorkspacesConfig(config);
populateFormatWindowSeparatorConfig(config);
populateWindowRewriteConfig(config);
if (withWindows) {
populateWorkspaceTaskbarConfig(config);
}
if (m_enableTaskbar) {
auto parts = split(m_formatBefore, "{windows}", 1);
m_formatBefore = parts[0];
m_formatAfter = parts.size() > 1 ? parts[1] : "";
}
}
auto Workspaces::populateIconsMap(const Json::Value &formatIcons) -> void {
@@ -681,6 +723,77 @@ auto Workspaces::populateWindowRewriteConfig(const Json::Value &config) -> void
[this](std::string &window_rule) { return windowRewritePriorityFunction(window_rule); });
}
auto Workspaces::populateWorkspaceTaskbarConfig(const Json::Value &config) -> void {
const auto &workspaceTaskbar = config["workspace-taskbar"];
if (!workspaceTaskbar.isObject()) {
spdlog::debug("workspace-taskbar is not defined or is not an object, using default rules.");
return;
}
populateBoolConfig(workspaceTaskbar, "enable", m_enableTaskbar);
populateBoolConfig(workspaceTaskbar, "update-active-window", m_updateActiveWindow);
populateBoolConfig(workspaceTaskbar, "reverse-direction", m_taskbarReverseDirection);
if (workspaceTaskbar["format"].isString()) {
/* The user defined a format string, use it */
std::string format = workspaceTaskbar["format"].asString();
m_taskbarWithTitle = format.find("{title") != std::string::npos; /* {title} or {title.length} */
auto parts = split(format, "{icon}", 1);
m_taskbarFormatBefore = parts[0];
if (parts.size() > 1) {
m_taskbarWithIcon = true;
m_taskbarFormatAfter = parts[1];
}
} else {
/* The default is to only show the icon */
m_taskbarWithIcon = true;
}
auto iconTheme = workspaceTaskbar["icon-theme"];
if (iconTheme.isArray()) {
for (auto &c : iconTheme) {
m_iconLoader.add_custom_icon_theme(c.asString());
}
} else if (iconTheme.isString()) {
m_iconLoader.add_custom_icon_theme(iconTheme.asString());
}
if (workspaceTaskbar["icon-size"].isInt()) {
m_taskbarIconSize = workspaceTaskbar["icon-size"].asInt();
}
if (workspaceTaskbar["orientation"].isString() &&
toLower(workspaceTaskbar["orientation"].asString()) == "vertical") {
m_taskbarOrientation = Gtk::ORIENTATION_VERTICAL;
}
if (workspaceTaskbar["on-click-window"].isString()) {
m_onClickWindow = workspaceTaskbar["on-click-window"].asString();
}
if (workspaceTaskbar["ignore-list"].isArray()) {
for (auto &windowRegex : workspaceTaskbar["ignore-list"]) {
std::string ruleString = windowRegex.asString();
try {
m_ignoreWindows.emplace_back(ruleString, std::regex_constants::icase);
} catch (const std::regex_error &e) {
spdlog::error("Invalid rule {}: {}", ruleString, e.what());
}
}
}
if (workspaceTaskbar["active-window-position"].isString()) {
auto posStr = workspaceTaskbar["active-window-position"].asString();
try {
m_activeWindowPosition =
m_activeWindowEnumParser.parseStringToEnum(posStr, m_activeWindowPositionMap);
} catch (const std::invalid_argument &e) {
spdlog::warn(
"Invalid string representation for active-window-position. Falling back to 'none'.");
m_activeWindowPosition = ActiveWindowPosition::NONE;
}
}
}
void Workspaces::registerOrphanWindow(WindowCreationPayload create_window_payload) {
if (!create_window_payload.isEmpty(*this)) {
m_orphanWindowMap[create_window_payload.getAddress()] = create_window_payload.repr(*this);
@@ -701,12 +814,18 @@ auto Workspaces::registerIpc() -> void {
m_ipc.registerForIPC("urgent", this);
m_ipc.registerForIPC("configreloaded", this);
if (windowRewriteConfigUsesTitle()) {
if (windowRewriteConfigUsesTitle() || m_taskbarWithTitle) {
spdlog::info(
"Registering for Hyprland's 'windowtitlev2' events because a user-defined window "
"rewrite rule uses the 'title' field.");
m_ipc.registerForIPC("windowtitlev2", this);
}
if (m_updateActiveWindow) {
spdlog::info(
"Registering for Hyprland's 'activewindowv2' events because 'update-active-window' is set "
"to true.");
m_ipc.registerForIPC("activewindowv2", this);
}
}
void Workspaces::removeWorkspacesToRemove() {
@@ -898,7 +1017,7 @@ auto Workspaces::update() -> void {
void Workspaces::updateWindowCount() {
const Json::Value workspacesJson = m_ipc.getSocket1JsonReply("workspaces");
for (auto &workspace : m_workspaces) {
for (auto const &workspace : m_workspaces) {
auto workspaceJson = std::ranges::find_if(workspacesJson, [&](Json::Value const &x) {
return x["name"].asString() == workspace->name() ||
(workspace->isSpecial() && x["name"].asString() == "special:" + workspace->name());
@@ -944,9 +1063,17 @@ bool Workspaces::updateWindowsToCreate() {
void Workspaces::updateWorkspaceStates() {
const std::vector<int> visibleWorkspaces = getVisibleWorkspaces();
auto updatedWorkspaces = m_ipc.getSocket1JsonReply("workspaces");
auto currentWorkspace = m_ipc.getSocket1JsonReply("activeworkspace");
std::string currentWorkspaceName =
currentWorkspace.isMember("name") ? currentWorkspace["name"].asString() : "";
for (auto &workspace : m_workspaces) {
bool isActiveByName =
!currentWorkspaceName.empty() && workspace->name() == currentWorkspaceName;
workspace->setActive(
workspace->id() == m_activeWorkspaceId ||
workspace->id() == m_activeWorkspaceId || isActiveByName ||
(workspace->isSpecial() && workspace->name() == m_activeSpecialWorkspaceName));
if (workspace->isActive() && workspace->isUrgent()) {
workspace->setUrgent(false);
@@ -965,7 +1092,7 @@ void Workspaces::updateWorkspaceStates() {
if (updatedWorkspace != updatedWorkspaces.end()) {
workspace->setOutput((*updatedWorkspace)["monitor"].asString());
}
workspace->update(m_format, workspaceIcon);
workspace->update(workspaceIcon);
}
}
@@ -1019,7 +1146,7 @@ std::optional<int> Workspaces::parseWorkspaceId(std::string const &workspaceIdSt
try {
return workspaceIdStr == "special" ? -99 : std::stoi(workspaceIdStr);
} catch (std::exception const &e) {
spdlog::error("Failed to parse workspace ID: {}", e.what());
spdlog::debug("Workspace \"{}\" is not bound to an id: {}", workspaceIdStr, e.what());
return std::nullopt;
}
}

View File

@@ -14,14 +14,20 @@ waybar::modules::Image::Image(const std::string& id, const Json::Value& config)
size_ = config["size"].asInt();
interval_ = config_["interval"].asInt();
interval_ = config_["interval"] == "once"
? std::chrono::milliseconds::max()
: std::chrono::milliseconds(std::max(
1L, // Minimum 1ms due to millisecond precision
static_cast<long>(
(config_["interval"].isNumeric() ? config_["interval"].asDouble() : 0) *
1000)));
if (size_ == 0) {
size_ = 16;
}
if (interval_ == 0) {
interval_ = INT_MAX;
if (interval_.count() == 0) {
interval_ = std::chrono::milliseconds::max();
}
delayWorker();
@@ -30,8 +36,7 @@ waybar::modules::Image::Image(const std::string& id, const Json::Value& config)
void waybar::modules::Image::delayWorker() {
thread_ = [this] {
dp.emit();
auto interval = std::chrono::seconds(interval_);
thread_.sleep_for(interval);
thread_.sleep_for(interval_);
};
}

View File

@@ -36,7 +36,7 @@ auto waybar::modules::Memory::update() -> void {
float total_swap_gigabytes = 0.01 * round(swaptotal / 10485.76);
int used_ram_percentage = 100 * (memtotal - memfree) / memtotal;
int used_swap_percentage = 0;
if (swaptotal && swapfree) {
if (swaptotal) {
used_swap_percentage = 100 * (swaptotal - swapfree) / swaptotal;
}
float used_ram_gigabytes = 0.01 * round((memtotal - memfree) / 10485.76);

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