#!/usr/bin/env bash set -euo pipefail # Simple script to launch an application or focus it if already running in niri # Usage: niri-launch-or-focus [--class CLASS] [--title TITLE] [args...] # # Examples: # niri-launch-or-focus firefox # niri-launch-or-focus code --class Code --title "My Project" # niri-launch-or-focus kitty --class kitty CLASS="" TITLE="" ARGS=() # Parse arguments while [[ $# -gt 0 ]]; do case $1 in --class) CLASS="$2" shift 2 ;; --title) TITLE="$2" shift 2 ;; *) ARGS+=("$1") shift ;; esac done if [ ${#ARGS[@]} -eq 0 ]; then echo "Usage: $0 [--class CLASS] [--title TITLE] [args...]" >&2 exit 1 fi COMMAND="${ARGS[0]}" APP_NAME=$(basename "$COMMAND") unset 'ARGS[0]' ARGS=("${ARGS[@]}") # If class/title were provided as flags, add them to command args (for apps that support them) if [ -n "$CLASS" ]; then ARGS=("--class=$CLASS" "${ARGS[@]}") fi if [ -n "$TITLE" ]; then ARGS=("--title=$TITLE" "${ARGS[@]}") fi # Find window by app_id (niri uses app-id), title, or app name find_window() { local class="$1" local title="$2" local app="$3" # Check if jq is available if ! command -v jq >/dev/null 2>&1; then echo "Error: jq is required but not found. Please install jq." >&2 return 1 fi # Get windows list from niri as JSON local windows_json windows_json=$(niri msg -j windows 2>/dev/null || echo "[]") if [ -z "$windows_json" ] || [ "$windows_json" = "[]" ]; then return 1 fi # Use jq to find matching window local window_id if [ -n "$class" ]; then # Match by class (app_id) window_id=$(echo "$windows_json" | jq -r --arg class "$class" ' .[] | select(.app_id | ascii_downcase == ($class | ascii_downcase)) | .id ' | head -1) elif [ -n "$title" ]; then # Match by title window_id=$(echo "$windows_json" | jq -r --arg title "$title" ' .[] | select(.title == $title) | .id ' | head -1) else # Match by app name (basename of command) window_id=$(echo "$windows_json" | jq -r --arg app "$app" ' .[] | select(.app_id | ascii_downcase == ($app | ascii_downcase)) | .id ' | head -1) fi if [ -n "$window_id" ] && [ "$window_id" != "null" ]; then echo "$window_id" return 0 fi return 1 } # Try to find existing window WINDOW_ID=$(find_window "$CLASS" "$TITLE" "$APP_NAME" || echo "") # Focus if found, otherwise launch if [ -n "$WINDOW_ID" ]; then niri msg action focus-window --id "$WINDOW_ID" >/dev/null 2>&1 else "$COMMAND" "${ARGS[@]}" >/dev/null 2>&1 & disown fi