#!/bin/bash # restore-wayland-env.sh — probe /proc for a running Wayland client and # inherit its WAYLAND_DISPLAY / DISPLAY / DBUS_SESSION_BUS_ADDRESS / # XDG_RUNTIME_DIR. Used by caffeine.sh and start-swayidle.sh so on-click # scripts run from waybar's context (which doesn't inherit the Sway env) # can still talk to the compositor. # # Why probe /proc? waybar's on-click handler forks the script in waybar's # own process context. That context has WAYLAND_DISPLAY set (waybar is a # Wayland client), but other Sway context (XDG_CURRENT_DESKTOP, sway IPC # socket, etc.) isn't passed to children. We need WAYLAND_DISPLAY for # swaymsg/grim/wl-copy/notify-send, so the env-restoration here covers the # "Wayland client tools" subset. Swaymsg-specific env (I3SOCK / SWAYSOCK) # isn't included because swaymsg falls back to discovery via the # /run/user/UID/sway-ipc.*.sock path. # # Idempotent: if WAYLAND_DISPLAY and DISPLAY are already set, does nothing. # Source-able: `source "$HOME/.config/sway/restore-wayland-env.sh"`. if [[ -n "$WAYLAND_DISPLAY" || -n "$DISPLAY" ]]; then return 0 2>/dev/null || exit 0 fi # Find a running Wayland client. mako, swaybar, foot, wofi — anything # bound to wayland-N. We grab the first one with WAYLAND_DISPLAY set. for pid in /proc/[0-9]*; do [[ -r "$pid/environ" ]] || continue candidate=$(tr '\0' '\n' < "$pid/environ" 2>/dev/null | grep -E '^(WAYLAND_DISPLAY|DISPLAY|DBUS_SESSION_BUS_ADDRESS|XDG_RUNTIME_DIR)=' || true) if [[ -n "$candidate" ]]; then # shellcheck disable=SC2086 export $candidate return 0 2>/dev/null || exit 0 fi done