From e5c2b7fc80bfce6c06cc1a48f6fc57e088d7307c Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Tue, 1 Sep 2026 19:31:35 -0500 Subject: [PATCH] feat(recording): centralize wf-recorder script with Niri and Hyprland support - Move `record.sh` to `modules/user/scripts/record.sh` and register it as a declarative `record` binary in Home Manager. - Add `wf-recorder` package to user application modules. - Update script logic to dynamically support both Niri and Hyprland compositors for window and monitor target detection. - Add Niri keybindings for screen recording in `custom.kdl`. - Update README documentation. --- README.md | 12 +- hosts/desktop/config/hypr/scripts/record.sh | 77 +++++----- modules/user/apps.nix | 7 +- modules/user/config/niri/custom.kdl | 6 + modules/user/scripts/record.sh | 148 ++++++++++++++++++++ 5 files changed, 210 insertions(+), 40 deletions(-) create mode 100755 modules/user/scripts/record.sh diff --git a/README.md b/README.md index e7fdad4..ef0b7ef 100644 --- a/README.md +++ b/README.md @@ -84,14 +84,14 @@ flowchart TD * **Script Location:** [hosts/desktop/monitor.py](hosts/desktop/monitor.py) * **Systemd Integration:** Managed via [hosts/desktop/dynu.nix](hosts/desktop/dynu.nix) which triggers the monitor service every 30 minutes. -### 2. GPU-Accelerated Video Recording (`record.sh`) -* **Script Location:** [hosts/desktop/config/hypr/scripts/record.sh](hosts/desktop/config/hypr/scripts/record.sh) -* **Functionality:** Uses `wf-recorder` to record Wayland outputs. +### 2. GPU-Accelerated Video Recording (`record`) +* **Script Location:** [modules/user/scripts/record.sh](modules/user/scripts/record.sh) +* **Functionality:** Uses `wf-recorder` to record Wayland outputs across both Niri and Hyprland sessions. * **Modes:** * `area` — Manually drag and draw a target bounding box using `slurp`. - * `window` — Target coordinates dynamically parsed from `hyprctl activewindow`. - * `output` — Matches coordinates of the currently active focused monitor. - * `screen` — Default full layout grab. + * `window` — Target active window or interactively select via `slurp`. + * `output` — Matches coordinates of the currently active focused monitor (`niri msg` / `hyprctl`). + * `screen` — Full layout capture. * `audio` flag — Parses `wpctl` to dynamically resolve output system loopback paths from PipeWire/WirePlumber to include sound. ### 3. Git Automation Shorthand (`git.sh`) diff --git a/hosts/desktop/config/hypr/scripts/record.sh b/hosts/desktop/config/hypr/scripts/record.sh index 8e3caad..98d2bf3 100755 --- a/hosts/desktop/config/hypr/scripts/record.sh +++ b/hosts/desktop/config/hypr/scripts/record.sh @@ -1,15 +1,15 @@ #!/usr/bin/env bash -# 📹 Hyprland Screen Recording Utility +# 📹 Wayland Screen Recording Utility (Niri & Hyprland compatible) # Leverages 'wf-recorder' for GPU-accelerated video recording and pipewire audio routing. -# Supports capturing specific bounding boxes, active windows, virtual outputs, or full displays. +# Supports capturing specific regions, active windows, focused monitors, or full displays. # # Usage: # record.sh [area | window | output | screen] [audio] PID_FILE="/tmp/wf-recorder.pid" TYPE_FILE="/tmp/wf-recorder.type" -OUTPUT_DIR="$HOME/Videos" +OUTPUT_DIR="${XDG_VIDEOS_DIR:-$HOME/Videos}" # Ensure output directory exists mkdir -p "$OUTPUT_DIR" @@ -54,8 +54,10 @@ fi MODE="${1:-area}" AUDIO_DEVICE="" TYPE_DESC="Screen Recording" +GEOM="" +OUTPUT_TARGET="" -# Extract geometric regions based on requested target +# Extract geometric regions or output target based on requested mode case "$MODE" in area) # Interactive region selector using 'slurp'. User clicks and drags to select. @@ -67,69 +69,80 @@ case "$MODE" in TYPE_DESC="Area Recording" ;; window) - # Fetch the active window coordinates and dimensions using hyprctl JSON output - GEOM=$(hyprctl activewindow -j | jq -r '"\(.at[0]),\(.at[1]) \(.size[0])x\(.size[1])"') + # Try querying Hyprland active window coordinates if on Hyprland + if [ "$XDG_CURRENT_DESKTOP" = "Hyprland" ] && command -v hyprctl >/dev/null 2>&1; then + GEOM=$(hyprctl activewindow -j 2>/dev/null | jq -r '"\(.at[0]),\(.at[1]) \(.size[0])x\(.size[1])"') + fi + # Fallback to interactive window / region selection via slurp if [ -z "$GEOM" ] || [ "$GEOM" = "null,null nullxnull" ]; then - notify-send -t 2000 "Screen Recorder" "No active window found" + GEOM=$(slurp) + fi + if [ -z "$GEOM" ]; then + notify-send -t 2000 "Screen Recorder" "Recording cancelled" exit 1 fi TYPE_DESC="Window Recording" ;; output) - # Query active monitors and match the geometry of the current cursor focus - GEOM=$(hyprctl monitors -j | jq -r '.[] | select(.focused == true) | "\(.x),\(.y) \(.width)x\(.height)"') + # Query focused monitor on Niri or Hyprland + if [ "$XDG_CURRENT_DESKTOP" = "niri" ] || command -v niri >/dev/null 2>&1; then + OUTPUT_TARGET=$(niri msg -j focused-output 2>/dev/null | jq -r '.name // empty') + fi + if [ -z "$OUTPUT_TARGET" ] && command -v hyprctl >/dev/null 2>&1; then + OUTPUT_TARGET=$(hyprctl monitors -j 2>/dev/null | jq -r '.[] | select(.focused == true) | .name // empty') + fi TYPE_DESC="Monitor Recording" ;; screen) - # Clear geometry: captures the full desktop layout spanning all connected monitors + # Full desktop layout across monitors GEOM="" + OUTPUT_TARGET="" TYPE_DESC="Full Screen Recording" ;; esac -# Resolve dynamic audio monitor node if the user specified "audio" as the second flag -if [ "$2" = "audio" ]; then +# Resolve dynamic audio monitor node if requested +if [ "$2" = "audio" ] || [ "$1" = "audio" ]; then # Parse status output of wireplumber to determine the currently active output Sink ID - SINK_ID=$(wpctl status | sed -n '/Sinks:/,/Sources:/p' | grep '*' | awk '{print $3}' | tr -d '.') + SINK_ID=$(wpctl status 2>/dev/null | sed -n '/Sinks:/,/Sources:/p' | grep '\*' | awk '{print $3}' | tr -d '.' | head -n 1) if [ -n "$SINK_ID" ]; then - # Query wireplumber to resolve the dynamic node name of the identified sink (e.g. alsa_output.pci...) - NODE_NAME=$(wpctl inspect "$SINK_ID" | grep 'node.name' | awk -F'"' '{print $2}') + # Query wireplumber to resolve the dynamic node name of the identified sink + NODE_NAME=$(wpctl inspect "$SINK_ID" 2>/dev/null | grep 'node.name' | awk -F'"' '{print $2}') if [ -n "$NODE_NAME" ]; then # Append .monitor to route output system audio loopback to the recording device AUDIO_DEVICE="${NODE_NAME}.monitor" fi fi - # Fallback to default system input/source if parsing failed + # Fallback to default system source if parsing failed if [ -z "$AUDIO_DEVICE" ]; then AUDIO_DEVICE="default" fi TYPE_DESC="${TYPE_DESC} (with Audio)" fi -# Define output filename format (ISO-like timestamping) +# Define output filename format FILENAME="recording_$(date +%Y-%m-%d_%H-%M-%S).mp4" FILEPATH="$OUTPUT_DIR/$FILENAME" -# Trigger user-facing low-priority desktop notification +# Desktop notification before starting notify-send -t 2000 -u low "Screen Recorder" "Starting $TYPE_DESC..." -# Execute wf-recorder in the background with appropriate flags +# Build wf-recorder arguments array +CMD=(wf-recorder) if [ -n "$AUDIO_DEVICE" ]; then - if [ -n "$GEOM" ]; then - wf-recorder -a "$AUDIO_DEVICE" -g "$GEOM" -f "$FILEPATH" & - else - wf-recorder -a "$AUDIO_DEVICE" -f "$FILEPATH" & - fi -else - if [ -n "$GEOM" ]; then - wf-recorder -g "$GEOM" -f "$FILEPATH" & - else - wf-recorder -f "$FILEPATH" & - fi + CMD+=(-a "$AUDIO_DEVICE") fi +if [ -n "$GEOM" ]; then + CMD+=(-g "$GEOM") +elif [ -n "$OUTPUT_TARGET" ]; then + CMD+=(-o "$OUTPUT_TARGET") +fi +CMD+=(-f "$FILEPATH") -# Track PID and Type metadata in /tmp for future toggle invocation +# Execute wf-recorder in background +"${CMD[@]}" & PID=$! + +# Track PID and Type metadata in /tmp for toggle invocation echo "$PID" > "$PID_FILE" echo "$TYPE_DESC" > "$TYPE_FILE" - diff --git a/modules/user/apps.nix b/modules/user/apps.nix index e1b550a..75b013b 100644 --- a/modules/user/apps.nix +++ b/modules/user/apps.nix @@ -1,16 +1,19 @@ { inputs, pkgs, ... }: let - # Declaratively compile the Python script as a user utility package using writeScriptBin + # Declaratively compile scripts as user utility packages using writeScriptBin bundleProject = pkgs.writeScriptBin "bundle-project" (builtins.readFile ./scripts/bundle_project.py); + recordScript = pkgs.writeScriptBin "record" (builtins.readFile ./scripts/record.sh); in { home.packages = with pkgs; [ # Custom Flake injections: Google Antigravity CLI helper inputs.antigravity.packages.${pkgs.stdenv.hostPlatform.system}.google-antigravity-cli - # Local Python utilities + # Local CLI & Workflow utilities bundleProject + recordScript + wf-recorder # Light recorder for Wayland-based window managers # Media, Note-taking & Graphical Tools mpv # Fast, scriptable, keyboard-driven CLI media player diff --git a/modules/user/config/niri/custom.kdl b/modules/user/config/niri/custom.kdl index fb16b3c..b4bdbd3 100644 --- a/modules/user/config/niri/custom.kdl +++ b/modules/user/config/niri/custom.kdl @@ -27,6 +27,12 @@ binds { Mod+Alt+S hotkey-overlay-title="Screenshot: Full Screen" { screenshot-screen; } Mod+Ctrl+Alt+S hotkey-overlay-title="Screenshot: Full Screen" { screenshot-screen; } + // === Screen Recording (wf-recorder toggle) === + Mod+W hotkey-overlay-title="Record: Area Selection" { spawn "record" "area"; } + Mod+Shift+W hotkey-overlay-title="Record: Focused Monitor" { spawn "record" "output"; } + Mod+Ctrl+W hotkey-overlay-title="Record: Area + Audio" { spawn "record" "area" "audio"; } + Mod+Ctrl+Shift+W hotkey-overlay-title="Record: Focused Monitor + Audio" { spawn "record" "output" "audio"; } + // === Color Picker === Mod+Shift+C hotkey-overlay-title="Color Picker (Eyedropper)" { spawn "bash" "-c" "color=$(niri msg pick-color) && [ -n \"$color\" ] && echo -n \"$color\" | wl-copy && notify-send -a 'Niri' 'Color Picker' \"Copied $color to clipboard\""; diff --git a/modules/user/scripts/record.sh b/modules/user/scripts/record.sh new file mode 100755 index 0000000..3971149 --- /dev/null +++ b/modules/user/scripts/record.sh @@ -0,0 +1,148 @@ +#!/usr/bin/env bash + +# 📹 Wayland Screen Recording Utility (Niri & Hyprland compatible) +# Leverages 'wf-recorder' for GPU-accelerated video recording and pipewire audio routing. +# Supports capturing specific regions, active windows, focused monitors, or full displays. +# +# Usage: +# record [area | window | output | screen] [audio] + +PID_FILE="/tmp/wf-recorder.pid" +TYPE_FILE="/tmp/wf-recorder.type" +OUTPUT_DIR="${XDG_VIDEOS_DIR:-$HOME/Videos}" + +# Ensure output directory exists +mkdir -p "$OUTPUT_DIR" + +# Stop any active recording session gracefully +stop_recording() { + # Check if we have a saved process ID + if [ -f "$PID_FILE" ]; then + PID=$(cat "$PID_FILE") + if kill -0 "$PID" 2>/dev/null; then + # Send INT signal (Ctrl+C equivalent) so wf-recorder can flush the output container + kill -INT "$PID" + # Wait briefly to permit filesystem write finalization + sleep 0.5 + fi + rm -f "$PID_FILE" + fi + + # Sweep for orphan instances of wf-recorder to prevent background process leaks + if pgrep -x "wf-recorder" > /dev/null; then + pkill -INT -x wf-recorder + sleep 0.5 + fi + + # Read the recording type metadata for user notification + TYPE="Recording" + if [ -f "$TYPE_FILE" ]; then + TYPE=$(cat "$TYPE_FILE") + rm -f "$TYPE_FILE" + fi + + notify-send -t 3000 -u normal "Screen Recorder" "$TYPE stopped and saved to $OUTPUT_DIR" + exit 0 +} + +# If the script is invoked while a recording is already running, toggle it OFF +if pgrep -x "wf-recorder" > /dev/null; then + stop_recording +fi + +# Define operation modes +MODE="${1:-area}" +AUDIO_DEVICE="" +TYPE_DESC="Screen Recording" +GEOM="" +OUTPUT_TARGET="" + +# Extract geometric regions or output target based on requested mode +case "$MODE" in + area) + # Interactive region selector using 'slurp'. User clicks and drags to select. + GEOM=$(slurp) + if [ -z "$GEOM" ]; then + notify-send -t 2000 "Screen Recorder" "Recording cancelled" + exit 1 + fi + TYPE_DESC="Area Recording" + ;; + window) + # Try querying Hyprland active window coordinates if on Hyprland + if [ "$XDG_CURRENT_DESKTOP" = "Hyprland" ] && command -v hyprctl >/dev/null 2>&1; then + GEOM=$(hyprctl activewindow -j 2>/dev/null | jq -r '"\(.at[0]),\(.at[1]) \(.size[0])x\(.size[1])"') + fi + # Fallback to interactive window / region selection via slurp + if [ -z "$GEOM" ] || [ "$GEOM" = "null,null nullxnull" ]; then + GEOM=$(slurp) + fi + if [ -z "$GEOM" ]; then + notify-send -t 2000 "Screen Recorder" "Recording cancelled" + exit 1 + fi + TYPE_DESC="Window Recording" + ;; + output) + # Query focused monitor on Niri or Hyprland + if [ "$XDG_CURRENT_DESKTOP" = "niri" ] || command -v niri >/dev/null 2>&1; then + OUTPUT_TARGET=$(niri msg -j focused-output 2>/dev/null | jq -r '.name // empty') + fi + if [ -z "$OUTPUT_TARGET" ] && command -v hyprctl >/dev/null 2>&1; then + OUTPUT_TARGET=$(hyprctl monitors -j 2>/dev/null | jq -r '.[] | select(.focused == true) | .name // empty') + fi + TYPE_DESC="Monitor Recording" + ;; + screen) + # Full desktop layout across monitors + GEOM="" + OUTPUT_TARGET="" + TYPE_DESC="Full Screen Recording" + ;; +esac + +# Resolve dynamic audio monitor node if requested +if [ "$2" = "audio" ] || [ "$1" = "audio" ]; then + # Parse status output of wireplumber to determine the currently active output Sink ID + SINK_ID=$(wpctl status 2>/dev/null | sed -n '/Sinks:/,/Sources:/p' | grep '\*' | awk '{print $3}' | tr -d '.' | head -n 1) + if [ -n "$SINK_ID" ]; then + # Query wireplumber to resolve the dynamic node name of the identified sink + NODE_NAME=$(wpctl inspect "$SINK_ID" 2>/dev/null | grep 'node.name' | awk -F'"' '{print $2}') + if [ -n "$NODE_NAME" ]; then + # Append .monitor to route output system audio loopback to the recording device + AUDIO_DEVICE="${NODE_NAME}.monitor" + fi + fi + # Fallback to default system source if parsing failed + if [ -z "$AUDIO_DEVICE" ]; then + AUDIO_DEVICE="default" + fi + TYPE_DESC="${TYPE_DESC} (with Audio)" +fi + +# Define output filename format +FILENAME="recording_$(date +%Y-%m-%d_%H-%M-%S).mp4" +FILEPATH="$OUTPUT_DIR/$FILENAME" + +# Desktop notification before starting +notify-send -t 2000 -u low "Screen Recorder" "Starting $TYPE_DESC..." + +# Build wf-recorder arguments array +CMD=(wf-recorder) +if [ -n "$AUDIO_DEVICE" ]; then + CMD+=(-a "$AUDIO_DEVICE") +fi +if [ -n "$GEOM" ]; then + CMD+=(-g "$GEOM") +elif [ -n "$OUTPUT_TARGET" ]; then + CMD+=(-o "$OUTPUT_TARGET") +fi +CMD+=(-f "$FILEPATH") + +# Execute wf-recorder in background +"${CMD[@]}" & +PID=$! + +# Track PID and Type metadata in /tmp for toggle invocation +echo "$PID" > "$PID_FILE" +echo "$TYPE_DESC" > "$TYPE_FILE"