diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS deleted file mode 100644 index 4e9460ddb315..000000000000 --- a/.github/CODEOWNERS +++ /dev/null @@ -1,2 +0,0 @@ -# Merges to protected branches need sign-off from an org owner. -* @dhh @ryanrhughes diff --git a/.gitignore b/.gitignore index 8de9215b5a47..1de1faa693b8 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,5 @@ # Python bytecode (orchestrator) __pycache__/ *.pyc + +.claude/ diff --git a/AGENTS.md b/AGENTS.md index e4a0084eadf8..6de19cb9a501 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,7 +28,7 @@ Three documentation trees, split by genre and audience: - Prefer `(( ))` over numeric operators inside `[[ ]]` (e.g., `(( count < 50 ))`, not `[[ $count -lt 50 ]]`) - Prefer a full `if`/`else` conditional for simple two-path control flow; don't rely on `exec` or `exit` in one branch to make following statements unreachable - For strings/paths with spaces, quote them instead of escaping spaces with `\ ` (e.g., `"$APP_DIR/Disk Usage.desktop"`, not `$APP_DIR/Disk\ Usage.desktop`) -- Shebangs must use `#!/bin/bash` consistently (never `#!/usr/bin/env bash`) +- Shebangs must use `#!/bin/bash` consistently (never `#!/usr/bin/env bash`). A security-sensitive entrypoint may use the exact `#!/bin/bash -p` form only when it must suppress `BASH_ENV` and exported-function startup injection before its first command; that exception must be explained at the boundary and covered by a regression that rejects an ordinary Bash launch with a decoy `-p` argument. - Scripts under `install/` and `migrations/` may be sourced and intentionally omit shebangs # Command Naming diff --git a/README.md b/README.md index 5cedfc5ce656..5834780f5b78 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,7 @@ Read more at [omarchy.org](https://omarchy.org). ## The Omarchy Manual -The manual lives in [`manual/`](manual/), which is its authoritative source. It's -mirrored to [learn.omacom.io](https://learn.omacom.io/2/the-omarchy-manual), where -its screenshots are also hosted. +The manual lives in [`manual/`](manual/), which is its authoritative source. - [Welcome to Omarchy!](manual/01-welcome-to-omarchy.md) diff --git a/agents/skills/install-scripts.md b/agents/skills/install-scripts.md index 999a6e9ca0a7..aa993e5e54bd 100644 --- a/agents/skills/install-scripts.md +++ b/agents/skills/install-scripts.md @@ -13,6 +13,7 @@ commands and reusable setup leaves: - use `$OMARCHY_INSTALL` and `$OMARCHY_PATH` instead of hard-coded Omarchy paths. - keep root-scoped hardware setup under `install/hardware/` and orchestrate it through `install/hardware/all.sh`. - keep every per-user setup leaf under `install/user/` (including `install/user/hardware/` and `install/user/first-run/`) so it is clear what must run for each user. +- The base install supplies matching kernel headers before hardware setup. DKMS installers should install their driver packages and assume the headers exist. - prefer helper commands for package and command checks where available. Raw `command -v`, `pacman`, and `pacman-key` are acceptable in package-helper diff --git a/agents/skills/visual-verification.md b/agents/skills/visual-verification.md index 56dc8e7841b1..a8ed63d7ae26 100644 --- a/agents/skills/visual-verification.md +++ b/agents/skills/visual-verification.md @@ -15,10 +15,7 @@ Take a full-screen screenshot without opening the editor: omarchy capture screenshot fullscreen save ``` -The command prints the saved path and writes to the configured Pictures -directory. Use `omarchy screenshot` for the interactive smart-region flow. -Capture reference and candidate states as separate images when changing a -layer-shell surface or layout, then compare both. +The command writes to Omasnap's configured screenshot directory. Use `omarchy screenshot` for the interactive capture flow, which copies the capture and shows a timed preview. Use `omarchy screenshot --editor=overlay` to test annotation before output. Capture reference and candidate states as separate images when changing a layer-shell surface or layout, then compare both. Record a short full-screen video for animation, transition, timing, capture, or screen-recording changes: diff --git a/bin/omarchy-agent-usage-codex b/bin/omarchy-agent-usage-codex index 972c164dee96..6e2d918f926f 100755 --- a/bin/omarchy-agent-usage-codex +++ b/bin/omarchy-agent-usage-codex @@ -544,12 +544,20 @@ def fetch_codex_rpc(): rpc_request(proc, 1, "initialize", {"clientInfo": {"name": "omarchy-agent-usage", "version": "1"}}, timeout=8) proc.stdin.write(json.dumps({"method": "initialized", "params": {}}) + "\n") proc.stdin.flush() - account_msg = rpc_request(proc, 2, "account/read", timeout=4) - limits_msg = rpc_request(proc, 3, "account/rateLimits/read", timeout=4) - - account = (account_msg.get("result") or {}).get("account") or {} + limits_msg = rpc_request(proc, 2, "account/rateLimits/read", timeout=8) limits = (limits_msg.get("result") or {}).get("rateLimits") or {} - plan = limits.get("planType") or account.get("planType") or account.get("type") or "" + plan = limits.get("planType") or "" + + # The limits name the plan themselves. account/read is only a fallback + # for when they don't, and never a reason to lose them: Codex 0.158's + # app-server can leave it unanswered for good. + if not plan: + try: + account_msg = rpc_request(proc, 3, "account/read", timeout=2) + account = (account_msg.get("result") or {}).get("account") or {} + plan = account.get("planType") or account.get("type") or "" + except TimeoutError: + pass result["tierLabel"] = str(plan) if plan else "" for window in (limits.get("primary"), limits.get("secondary")): diff --git a/bin/omarchy-capture-screenrecording b/bin/omarchy-capture-screenrecording index d57b26fee50f..0c4c5494c952 100755 --- a/bin/omarchy-capture-screenrecording +++ b/bin/omarchy-capture-screenrecording @@ -15,8 +15,9 @@ # start. # # Env: OMARCHY_SCREENRECORD_DEBUG=true appends gpu-screen-recorder's stderr (and -# the picker target it was launched with) to /tmp/omarchy-screenrecord.log so -# users can attach a log when reporting capture failures. +# the picker target it was launched with) to +# $XDG_RUNTIME_DIR/omarchy-screenrecord.log so users can attach a log when +# reporting capture failures. [[ -f ~/.config/user-dirs.dirs ]] && source ~/.config/user-dirs.dirs OUTPUT_DIR="${OMARCHY_SCREENRECORD_DIR:-${XDG_VIDEOS_DIR:-$HOME/Videos}}" @@ -34,9 +35,18 @@ WEBCAM_SIZE="medium" RESOLUTION="" FULLSCREEN="false" STOP_RECORDING="false" -RECORDING_FILE="/tmp/omarchy-screenrecord-filename" -REGION_FILE="${XDG_RUNTIME_DIR:-/tmp}/omarchy-screenrecord-region" -LOG_FILE=$([[ ${OMARCHY_SCREENRECORD_DEBUG:-false} == "true" ]] && echo "/tmp/omarchy-screenrecord.log" || echo "/dev/null") +# Both of these live in the per-user runtime directory, which is 0700. What +# RECORDING_FILE holds is read back on stop and used as a path -- ffmpeg writes +# beside it, `mv` replaces it, and `rm -f` deletes its preview -- so a name in +# world-writable /tmp is a name any other local account can create first and +# then point wherever it likes. The debug log carries the recorder's stderr and +# the picked geometry, which is nobody else's business either. Fall back to +# the state directory when there is no session runtime dir -- :-/tmp would put +# both files back at the fixed names this comment describes. +RUNTIME_DIR="${XDG_RUNTIME_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/omarchy}" +RECORDING_FILE="$RUNTIME_DIR/omarchy-screenrecord-filename" +REGION_FILE="$RUNTIME_DIR/omarchy-screenrecord-region" +LOG_FILE=$([[ ${OMARCHY_SCREENRECORD_DEBUG:-false} == "true" ]] && echo "$RUNTIME_DIR/omarchy-screenrecord.log" || echo "/dev/null") for arg in "$@"; do case "$arg" in @@ -144,6 +154,11 @@ select_capture_target() { } start_screenrecording() { + mkdir -p "$RUNTIME_DIR" || return 1 + # XDG_STATE_HOME may be outside a private home; protect existing fallbacks too. + if [[ -z ${XDG_RUNTIME_DIR:-} ]]; then + chmod 700 "$RUNTIME_DIR" || return 1 + fi local capture_args=() local target diff --git a/bin/omarchy-capture-screenshot b/bin/omarchy-capture-screenshot index 6f7b91bf537d..ec383fcd5994 100755 --- a/bin/omarchy-capture-screenshot +++ b/bin/omarchy-capture-screenshot @@ -2,81 +2,22 @@ # omarchy:summary=Take a screenshot # omarchy:group=capture -# omarchy:args=[smart|region|windows|fullscreen] [slurp|copy|save] [--editor=] +# omarchy:args=[smart|region|windows|fullscreen|scroll] [copy|save] # omarchy:examples=omarchy screenshot | omarchy capture screenshot region # omarchy:aliases=omarchy screenshot -[[ -f ~/.config/user-dirs.dirs ]] && source ~/.config/user-dirs.dirs -OUTPUT_DIR="${OMARCHY_SCREENSHOT_DIR:-${XDG_PICTURES_DIR:-$HOME/Pictures}}" - -if [[ ! -d $OUTPUT_DIR ]]; then - mkdir -p "$OUTPUT_DIR" - omarchy-notification-send "Created screenshot directory: $OUTPUT_DIR" -t 2000 +if [[ -n ${OMARCHY_SCREENSHOT_DIR:-} && -z ${OMASNAP_SCREENSHOT_DIR:-} ]]; then + export OMASNAP_SCREENSHOT_DIR="$OMARCHY_SCREENSHOT_DIR" fi -pkill slurp && exit 0 - -SCREENSHOT_EDITOR="${OMARCHY_SCREENSHOT_EDITOR:-tensaku-edit}" - -# Parse --editor flag from any position -ARGS=() +omasnap_args=() for arg in "$@"; do - if [[ $arg == --editor=* ]]; then - SCREENSHOT_EDITOR="${arg#--editor=}" - else - ARGS+=("$arg") - fi + case "$arg" in + copy) omasnap_args+=(--copy) ;; + save) omasnap_args+=(--save) ;; + slurp) ;; + *) omasnap_args+=("$arg") ;; + esac done -set -- "${ARGS[@]}" - -MODE="${1:-smart}" -PROCESSING="${2:-slurp}" - -# The picker leaves the screen freeze running (PID on its first output line) -# so grim captures the frozen overlay rather than live content shifting -# during teardown. -# -# Software-composited cursors (Hyprland's fallback on GPUs without working -# hardware cursors) are baked into the frames grim captures, so force -# hardware cursors until after grim runs and restore the setting on exit. -NO_HW_CURSORS=$(hyprctl getoption cursor:no_hardware_cursors -j | jq '.int') - -set_no_hw_cursors() { - hyprctl eval "hl.config({ cursor = { no_hardware_cursors = $1 } })" &>/dev/null || - hyprctl keyword cursor:no_hardware_cursors "$1" &>/dev/null -} - -cleanup() { - [[ -n $FREEZE_PID ]] && kill $FREEZE_PID 2>/dev/null - set_no_hw_cursors "$NO_HW_CURSORS" -} -trap cleanup EXIT - -set_no_hw_cursors 0 -{ read -r FREEZE_PID; read -r SELECTION; } < <(omarchy-capture-region "$MODE" --keep-freeze) - -[[ -z $SELECTION ]] && exit 0 - -FILENAME="screenshot-$(date +'%Y-%m-%d_%H-%M-%S').png" -FILEPATH="$OUTPUT_DIR/$FILENAME" - -case "$PROCESSING" in - slurp) - grim -g "$SELECTION" "$FILEPATH" || exit 1 - echo "$FILEPATH" - wl-copy --type image/png <"$FILEPATH" - # Best-effort: the screenshot is already saved and on the clipboard, so a - # notification outage must not report the capture itself as failed. - omarchy-notification-send "Screenshot saved to clipboard and file" "Edit with Super + Alt + , (or click this)" \ - --image "$FILEPATH" \ - --exec "$SCREENSHOT_EDITOR" "$FILEPATH" || true - ;; - copy) - grim -g "$SELECTION" - | wl-copy --type image/png - ;; - save) - grim -g "$SELECTION" "$FILEPATH" || exit 1 - echo "$FILEPATH" - ;; -esac +exec omasnap "${omasnap_args[@]}" diff --git a/bin/omarchy-capture-webcam-resize b/bin/omarchy-capture-webcam-resize index cde61e087cfa..3c9d12155846 100755 --- a/bin/omarchy-capture-webcam-resize +++ b/bin/omarchy-capture-webcam-resize @@ -8,7 +8,10 @@ set -euo pipefail readonly MARGIN=40 -readonly REGION_FILE="${XDG_RUNTIME_DIR:-/tmp}/omarchy-screenrecord-region" +# Has to resolve to whatever omarchy-capture-screenrecording writes, fallback +# included, or a recording without a session runtime dir anchors the camera to +# the whole monitor instead of the region it recorded. +readonly REGION_FILE="${XDG_RUNTIME_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/omarchy}/omarchy-screenrecord-region" usage() { echo "Usage: omarchy-capture-webcam-resize " >&2 diff --git a/bin/omarchy-channel-set b/bin/omarchy-channel-set index 7e1123885086..039d3292cdf8 100755 --- a/bin/omarchy-channel-set +++ b/bin/omarchy-channel-set @@ -1,10 +1,25 @@ -#!/bin/bash +#!/bin/bash -p # omarchy:summary=Set the Omarchy package channel. # omarchy:args= # omarchy:requires-sudo=true +if [[ $- != *p* ]]; then + echo "Refusing an unsafe Bash startup for channel switching." >&2 + exit 126 +fi +security_entrypoint=$(/usr/bin/readlink -e -- "${BASH_SOURCE[0]}") || exit 126 +source "${security_entrypoint%/*}/omarchy-security-functions" || exit 126 +omarchy_security_require_privileged_bash_startup || exit 126 set -euo pipefail +omarchy_security_sanitize_bash_environment "$0" "$@" +omarchy_security_require_source_root "$0" +user_path=$PATH +# Traps first, so a signal or failure during the entry revocation still +# exits through the cleanup path. +omarchy_security_install_sudo_cleanup_traps +omarchy_security_revoke_sudo_timestamp || exit 1 +omarchy_security_enable_no_update_sudo usage() { echo "Usage: omarchy-channel-set [stable|rc|edge|dev]"; } fail() { echo "Error: $*" >&2; exit 1; } @@ -33,12 +48,40 @@ validate_dev_checkout() { } link_dev_checkout() { - local checkout="$1" - [[ -d $checkout/.git ]] || git clone https://github.com/basecamp/omarchy.git "$checkout" + local checkout="$1" required + [[ -d $checkout/.git ]] || git clone https://github.com/omacom/omarchy.git "$checkout" + + # Check the destination before changing /etc/omarchy.conf or sudo's path. + # An existing checkout is not pulled automatically and may predate this policy. + for required in bin/omarchy-security-functions bin/omarchy-update bin/omarchy-refresh-pacman default/omarchy/sudo-no-update/sudo; do + if [[ ! -f $checkout/$required || ! -r $checkout/$required || + ( $required != "bin/omarchy-security-functions" && ! -x $checkout/$required ) ]]; then + fail "Update the checkout before switching to dev; missing required update support in $required." + fi + done omarchy-dev-link "$checkout" --no-reboot } +# A packaged destination cannot be inspected before its package is installed, +# and a package transaction can replace the running tree with a release that +# predates the command-scoped wrapper. After that, a bare sudo would resolve to +# /usr/bin/sudo and publish a timestamp, and the destination's own updater +# authenticates the same way. Neither may run from a flow that has just run +# user hooks: stop at a consistent point and say how to finish from a fresh +# session. +stop_for_older_destination() { + cat >&2 < 0 )) || { usage; exit 1; } dev_checkout="" @@ -72,6 +115,10 @@ case "$channel" in ;; esac +# A failure past this point leaves the channel switch half-applied, so say how +# to pick it back up rather than dying silently under set -e. +trap 'echo -e "\nThe channel switch did not complete. Review the error above, then rerun: omarchy-channel-set '"$channel"'" >&2' ERR + if [[ -z $dev_checkout && $OMARCHY_PATH != "/usr/share/omarchy" ]]; then leaving_dev=1 fi @@ -79,13 +126,16 @@ fi if [[ -n $dev_checkout ]]; then link_dev_checkout "$dev_checkout" export OMARCHY_PATH="$dev_checkout" - export PATH="$OMARCHY_PATH/bin:$PATH" + omarchy_security_enable_no_update_sudo omarchy-state set reboot-required fi -omarchy-refresh-pacman "$pacman_channel" +OMARCHY_UPDATE_USER_PATH="$user_path" omarchy-refresh-pacman "$pacman_channel" +# Each transaction can have replaced this tree; check before the next sudo. +wrapper_present || stop_for_older_destination # --ask 4 accepts omarchy <-> omarchy-dev replacement prompts without file overwrites. -sudo env OMARCHY_UPDATE_PACMAN=1 pacman -S --needed --noconfirm --ask 4 "${packages[@]}" +omarchy-update-pacman -S --needed --noconfirm --ask 4 "${packages[@]}" +wrapper_present || stop_for_older_destination if [[ -z $dev_checkout ]]; then omarchy-dev-unlink --no-reboot @@ -94,6 +144,7 @@ if [[ -z $dev_checkout ]]; then if (( leaving_dev )); then omarchy-state set reboot-required fi + omarchy_security_enable_no_update_sudo 2>/dev/null || stop_for_older_destination fi -omarchy-update -y +OMARCHY_UPDATE_USER_PATH="$user_path" "$OMARCHY_PATH/bin/omarchy-update" -y diff --git a/bin/omarchy-clipboard-open b/bin/omarchy-clipboard-open index 98f26bb2babb..827fe263376e 100755 --- a/bin/omarchy-clipboard-open +++ b/bin/omarchy-clipboard-open @@ -30,7 +30,7 @@ open_image() { local path="$1" [[ -r $path ]] || exit 1 - exec tensaku-edit "$path" + exec omasnap "$path" } open_text() { diff --git a/bin/omarchy-cmd-browser-handoff b/bin/omarchy-cmd-browser-handoff new file mode 100755 index 000000000000..7dd14b2301ae --- /dev/null +++ b/bin/omarchy-cmd-browser-handoff @@ -0,0 +1,48 @@ +#!/bin/bash + +# omarchy:summary=Hand a command line to the running Chromium-based browser +# omarchy:args= [browser-args...] +# omarchy:hidden=true + +# A second browser process spends ~165ms starting up only to pass its command +# line to the running one over the profile's singleton socket, then exits. Send +# it there directly, and fail when no browser acknowledges it so the caller can +# launch one instead. +config="${XDG_CONFIG_HOME:-$HOME/.config}" + +# Only the browsers themselves: a wrapper in their place may pick a profile or +# add flags of its own, which only running it can honour. +case $(type -P "$1") in +/usr/bin/chromium) profile=chromium flags=chromium-flags.conf ;; +/usr/bin/google-chrome-stable) profile=google-chrome flags=chrome-flags.conf ;; +/usr/bin/brave) profile=BraveSoftware/Brave-Browser flags=brave-flags.conf ;; +/usr/bin/brave-origin) profile=BraveSoftware/Brave-Origin flags=brave-origin-flags.conf ;; +/usr/bin/microsoft-edge-stable) profile=microsoft-edge flags=microsoft-edge-stable-flags.conf ;; +*) exit 1 ;; +esac +shift + +# The running browser already has the process flags Omarchy ships in the flags +# file. Any other flag there may be meant for each launch, and a data directory +# from the environment is another browser, so leave those to the launcher. +if [[ -n ${CHROME_USER_DATA_DIR:-}${CHROME_CONFIG_HOME:-} ]] || + cat "/etc/$flags" "$config/$flags" 2>/dev/null | sed 's/#.*//' | tr -s '[:space:]' '\n' | + grep -vE '^(--(ozone-platform|ozone-platform-hint|password-store|enable-features|load-extension)=.*)?$' | grep -q .; then + exit 1 +fi + +for arg in "$@"; do + [[ $arg == --user-data-dir* ]] && exit 1 +done + +# The socket lives in a /tmp dir, which another user could recreate once a +# crashed browser's is cleaned away, so only a socket of our own gets the URL. +socket="$config/$profile/SingletonSocket" +[[ -S $socket && -O $socket ]] || exit 1 + +reply=$({ + printf 'START\0%s\0browser' "$PWD" + printf '\0%s' "$@" +} | socat -t2 - "UNIX-CONNECT:$socket" 2>/dev/null) + +[[ $reply == "ACK" ]] diff --git a/bin/omarchy-cmd-default-browser b/bin/omarchy-cmd-default-browser new file mode 100755 index 000000000000..f2ce9aa3a5a7 --- /dev/null +++ b/bin/omarchy-cmd-default-browser @@ -0,0 +1,58 @@ +#!/bin/bash + +# omarchy:summary=Print the desktop entry ID of the default web browser +# omarchy:hidden=true + +# Read the http handler from the config-dir mimeapps.list files the way xdg-mime +# does, desktop-specific list first, taking the first listed entry that is +# installed. xdg-settings reaches the same answer through several shell scripts +# in ~70ms, which every browser and web app launch would otherwise pay. +IFS=: read -ra data_dirs <<<"${XDG_DATA_HOME:-$HOME/.local/share}:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}" +IFS=: read -ra config_dirs <<<"${XDG_CONFIG_HOME:-$HOME/.config}:${XDG_CONFIG_DIRS:-/etc/xdg}" +IFS=: read -ra desktops <<<"${XDG_CURRENT_DESKTOP:-}" + +# Installed means the command of the entry the launchers will read, the first +# one found, still resolves: an entry of Omarchy's own can outlive the browser +# it launched. +installed() { + local data_dir command + + for data_dir in "${data_dirs[@]}"; do + [[ -r $data_dir/applications/$1 ]] || continue + command=$(sed -n 's/^Exec=\([^ ]*\).*/\1/p' "$data_dir/applications/$1" | head -1) + [[ -n $command ]] && command -v "$command" >/dev/null + return + done + + return 1 +} + +for config_dir in "${config_dirs[@]}"; do + for desktop in "${desktops[@]}" ""; do + list="$config_dir/${desktop:+${desktop,,}-}mimeapps.list" + [[ -f $list ]] || continue + + entries=$(awk ' + /^\[Default Applications\]/ { section = 1; next } + /^\[/ { section = 0 } + section && index($0, "x-scheme-handler/http=") == 1 { print substr($0, 23); exit } + ' "$list") + + IFS=';' read -ra entries <<<"$entries" + for entry in "${entries[@]}"; do + if [[ -n $entry ]] && installed "$entry"; then + echo "$entry" + exit 0 + fi + done + done +done + +# Nothing set in a config dir: let xdg-settings search the data dirs and caches. +# It consults $BROWSER too, which the session points back at omarchy-launch-browser. +browser=$(env -u BROWSER xdg-settings get default-web-browser 2>/dev/null) +if [[ -z $browser ]]; then + browser=$(xdg-mime query default x-scheme-handler/https 2>/dev/null) +fi + +[[ -n $browser ]] && echo "$browser" diff --git a/bin/omarchy-cmd-missing b/bin/omarchy-cmd-missing index 470d69c31e30..2b48be8152e8 100755 --- a/bin/omarchy-cmd-missing +++ b/bin/omarchy-cmd-missing @@ -3,7 +3,7 @@ # omarchy:summary=Check whether any required commands are missing for cmd in "$@"; do - if ! command -v "$cmd" &>/dev/null; then + if ! command -v -- "$cmd" &>/dev/null; then exit 0 fi done diff --git a/bin/omarchy-cmd-present b/bin/omarchy-cmd-present index 4e758760ab32..57b0510250cf 100755 --- a/bin/omarchy-cmd-present +++ b/bin/omarchy-cmd-present @@ -3,7 +3,7 @@ # omarchy:summary=Check whether all required commands are available for cmd in "$@"; do - command -v "$cmd" &>/dev/null || exit 1 + command -v -- "$cmd" &>/dev/null || exit 1 done exit 0 diff --git a/bin/omarchy-cmd-terminal-cwd b/bin/omarchy-cmd-terminal-cwd index afb7d622c704..60586185014e 100755 --- a/bin/omarchy-cmd-terminal-cwd +++ b/bin/omarchy-cmd-terminal-cwd @@ -1,9 +1,10 @@ #!/bin/bash # omarchy:summary=Print the current working directory of the active terminal window +# omarchy:args=[terminal-pid] # omarchy:hidden=true -terminal_pid=$(hyprctl activewindow | awk '/pid:/ {print $2}') +terminal_pid=${1:-$(hyprctl activewindow | awk '/pid:/ {print $2}')} kitty_socket="$XDG_RUNTIME_DIR/omarchy-kitty-$terminal_pid" cwd="" @@ -11,7 +12,16 @@ if [[ -S $kitty_socket ]]; then cwd=$(kitten @ --to "unix:$kitty_socket" ls --match "state:focused" 2>/dev/null | jq -r '.[].tabs[].windows[].cwd // empty') else - shell_pid=$(pgrep -P "$terminal_pid" | tail -n1) + # The newest child, as pgrep -P | tail -n1 found it, read from the kernel's + # child lists: pgrep scans all of /proc on every new terminal. + shell_pid="" + for children_file in /proc/"$terminal_pid"/task/*/children; do + [[ -r $children_file ]] || continue + read -ra children <"$children_file" || true + for child in "${children[@]}"; do + (( child > ${shell_pid:-0} )) && shell_pid=$child + done + done if [[ -n $shell_pid ]]; then cwd=$(readlink -f "/proc/$shell_pid/cwd" 2>/dev/null) diff --git a/bin/omarchy-default-agent b/bin/omarchy-default-agent index af93d8635f11..4cf77f79fcbc 100755 --- a/bin/omarchy-default-agent +++ b/bin/omarchy-default-agent @@ -50,15 +50,15 @@ esac agent_package=${agent_package:-$agent} -# Hermes reaches mise through its own installer rather than straight from -# here: it needs its interpreter pinned, and a bare `mise use` has nowhere to -# say so. See omarchy-install-hermes-cli. OpenClaw comes from its pacman -# package the same way; see omarchy-install-openclaw-cli. +# Hermes and OpenClaw are not mise tools: Hermes is the desktop app's +# self-updating runtime and OpenClaw comes from its pacman package. Each has +# its own installer with the same --check/--now contract mise-backed agents +# get from mise; see omarchy-install-hermes-cli and omarchy-install-openclaw-cli. if [[ -n ${agent_installer:-} ]]; then - # Not omarchy-cmd-present: the stub is on PATH from first boot and says - # nothing about whether Hermes is installed behind it. Treating a cold stub - # as installed skips the floating terminal and runs the minute-long install - # inside the menu action instead. + # Not omarchy-cmd-present: a command on PATH says nothing about whether the + # install behind it finished or runs the sessions omarchy-agent starts. + # Treating it as installed would skip the floating terminal and run a + # minutes-long install inside the menu action instead. agent_present() { "$agent_installer" --check; } agent_install() { "$agent_installer" --now; } else @@ -78,7 +78,9 @@ if [[ $installing == "false" ]] && ! agent_present; then fi if ! agent_install; then - if [[ $installing == "true" ]]; then + if [[ $installing == "true" && -n ${agent_installer:-} ]]; then + echo "Could not install $name" >&2 + elif [[ $installing == "true" ]]; then echo "Could not install $name with mise" >&2 else echo "Could not set $name as the default coding agent" >&2 @@ -86,6 +88,10 @@ if ! agent_install; then exit 1 fi +if [[ $agent == "claude" ]]; then + omarchy-install-chromium-claude 2>/dev/null || true +fi + mkdir -p "$(dirname "$agent_file")" printf '%s\n' "$agent" >"$agent_file" diff --git a/bin/omarchy-default-editor b/bin/omarchy-default-editor index 25134081d36e..74964fd6fbff 100755 --- a/bin/omarchy-default-editor +++ b/bin/omarchy-default-editor @@ -17,6 +17,9 @@ if (($# == 0)); then read -r editor <"$editor_file" fi + # sublime-text-4 ships `subl`; older defaults stored `sublime_text`. + [[ $editor == sublime_text ]] && editor=subl + [[ -n $editor ]] && echo "$editor" || echo "nvim" exit 0 fi @@ -25,10 +28,10 @@ case "$1" in code) selection="code"; editor="code"; name="VSCode"; glyph= ;; cursor) selection="cursor"; editor="cursor"; name="Cursor"; glyph= ;; zed | zeditor) selection="zed"; editor="zeditor"; name="Zed"; glyph= ;; -sublime_text) selection="sublime_text"; editor="sublime_text"; name="Sublime Text"; glyph= ;; +sublime_text | subl) selection="sublime_text"; editor="subl"; name="Sublime Text"; glyph= ;; helix) selection="helix"; editor="helix"; name="Helix"; glyph= ;; vim) selection="vim"; editor="vim"; name="Vim"; glyph= ;; -emacs) selection="emacs"; editor="emacs"; name="Emacs"; glyph= ;; +emacs) selection="emacs"; editor="emacs"; name="Emacs"; glyph= ;; nvim) selection="nvim"; editor="nvim"; name="Neovim"; glyph= ;; *) echo "Usage: omarchy-default-editor " diff --git a/bin/omarchy-hook b/bin/omarchy-hook index 8c2a59d99c12..499cdf14cfa5 100755 --- a/bin/omarchy-hook +++ b/bin/omarchy-hook @@ -11,6 +11,18 @@ if (( $# < 1 )); then fi HOOK=$1 + +# Hook names are fixed labels chosen by Omarchy code (post-update, theme-set, +# font-set). The name becomes a filename under the hooks directory. A slash +# would turn it into directory levels, and a bare `.` or `..` would point bash +# at the directory itself or its parent. Refuse those rather than follow them. +# Dots inside a name (a..b) are fine; once slashes are out, only the whole +# name being `.` or `..` can leave the directory. +if [[ -z $HOOK || $HOOK == */* || $HOOK == "." || $HOOK == ".." ]]; then + echo "Invalid hook name: $HOOK" >&2 + exit 2 +fi + HOOK_PATH="$HOME/.config/omarchy/hooks/$1" HOOK_DIR="$HOOK_PATH.d" shift diff --git a/bin/omarchy-hook-install b/bin/omarchy-hook-install index 7c53648259be..08b82e5881d1 100755 --- a/bin/omarchy-hook-install +++ b/bin/omarchy-hook-install @@ -15,8 +15,19 @@ fi HOOK_TYPE=$1 HOOK_FILE=$2 + +# Hook types are the same labels omarchy-hook runs (post-update, theme-set). +# The type becomes a directory under the hooks directory. A slash would turn +# it into directory levels. A bare `.` or `..` is a name the runner already +# refuses, so installing under it would write a hook nothing can run. Refuse +# those rather than mkdir/cp into them. Dots inside a name (a..b) are fine. +if [[ -z $HOOK_TYPE || $HOOK_TYPE == */* || $HOOK_TYPE == "." || $HOOK_TYPE == ".." ]]; then + echo "Invalid hook name: $HOOK_TYPE" >&2 + exit 2 +fi + HOOK_DIR="$HOME/.config/omarchy/hooks/$HOOK_TYPE.d" -HOOK_NAME=$(basename "$HOOK_FILE") +HOOK_NAME=$(basename -- "$HOOK_FILE") HOOK_PATH="$HOOK_DIR/$HOOK_NAME" if [[ ! -f $HOOK_FILE ]]; then @@ -25,7 +36,7 @@ if [[ ! -f $HOOK_FILE ]]; then fi mkdir -p "$HOOK_DIR" -cp "$HOOK_FILE" "$HOOK_PATH" +cp -- "$HOOK_FILE" "$HOOK_PATH" chmod 755 "$HOOK_PATH" echo "Installed $HOOK_TYPE hook: $HOOK_PATH" diff --git a/bin/omarchy-hw-match b/bin/omarchy-hw-match index 318ca7e8c69b..cecca3b08e73 100755 --- a/bin/omarchy-hw-match +++ b/bin/omarchy-hw-match @@ -3,5 +3,5 @@ # omarchy:summary=Match against the computer's DMI product name or product family (case-insensitive). # omarchy:args= -grep -qi "$1" /sys/class/dmi/id/product_name 2>/dev/null || -grep -qi "$1" /sys/class/dmi/id/product_family 2>/dev/null +grep -qi -- "$1" /sys/class/dmi/id/product_name 2>/dev/null || +grep -qi -- "$1" /sys/class/dmi/id/product_family 2>/dev/null diff --git a/bin/omarchy-hw-nvidia-display b/bin/omarchy-hw-nvidia-display new file mode 100755 index 000000000000..1cdf5b70d05b --- /dev/null +++ b/bin/omarchy-hw-nvidia-display @@ -0,0 +1,45 @@ +#!/bin/bash + +# omarchy:summary=Detect whether NVIDIA drives the display (rather than a hybrid iGPU). + +# On hybrid laptops the display is usually wired to the integrated GPU while +# the NVIDIA card only handles offloaded rendering. Forcing NVIDIA's VA-API and +# GLX drivers globally then breaks Chromium-based browsers (black video with +# audio still playing), so the Hyprland NVIDIA env only applies when NVIDIA is +# the display GPU. +# +# sysfs exposes which VGA device drives the display via boot_vga. When no +# device claims it (attribute missing or unreadable), assume NVIDIA is the +# display GPU to preserve the current behavior on machines we cannot tell. +# +# Read the cached sysfs IDs rather than lspci, which reads PCI config space and +# resumes runtime-suspended GPUs. +pci_devices_path="${OMARCHY_PCI_DEVICES_PATH:-/sys/bus/pci/devices}" + +shopt -s nullglob + +nvidia_boot=0 +other_boot=0 + +for device in "$pci_devices_path"/*; do + [[ $(< "$device/class") == 0x03* ]] || continue + boot_vga=0 + if [[ -f $device/boot_vga ]]; then + boot_vga=$(< "$device/boot_vga") + fi + if [[ $(< "$device/vendor") == "0x10de" ]]; then + if (( boot_vga == 1 )); then + nvidia_boot=1 + fi + else + if (( boot_vga == 1 )); then + other_boot=1 + fi + fi +done + +if (( other_boot == 1 && nvidia_boot == 0 )); then + exit 1 +else + exit 0 +fi diff --git a/bin/omarchy-hw-vm b/bin/omarchy-hw-vm new file mode 100755 index 000000000000..b6d27a9256fe --- /dev/null +++ b/bin/omarchy-hw-vm @@ -0,0 +1,5 @@ +#!/bin/bash + +# omarchy:summary=Returns true when running in a virtual machine. + +systemd-detect-virt --vm --quiet diff --git a/bin/omarchy-install-ai-hermes b/bin/omarchy-install-ai-hermes index 6b3764fd17b2..8a87420d52ee 100755 --- a/bin/omarchy-install-ai-hermes +++ b/bin/omarchy-install-ai-hermes @@ -10,153 +10,11 @@ if (( EUID == 0 )); then exit 1 fi -echo "Installing Hermes Desktop..." -omarchy-pkg-add hermes-desktop - -if [[ ! -r /usr/share/hermes-desktop/install.sh || ! -r /usr/share/hermes-desktop/runtime.patch ]] || - ! release_commit=$(jq -er 'select(.branch == "main") | .commit | select(test("^[0-9a-f]{40}$"))' /opt/hermes-desktop/resources/install-stamp.json 2>/dev/null); then - echo "The installed Hermes package cannot prepare in-app updates. Run 'omarchy update', then try again." >&2 - exit 1 -fi - -# If Hermes was already installed for the terminal, the app supersedes it: one -# machine, one Hermes. This drops that copy so the terminal, the default agent -# and the app all end up on the app's installation. -omarchy-install-hermes-cli || true - -# Keep the runtime at the root even when invoked from a Hermes profile. -HERMES_HOME=$(realpath -ms -- "${HERMES_HOME:-$HOME/.hermes}") -home_parent=$(dirname -- "$HERMES_HOME") -if [[ ${home_parent##*/} == [Pp][Rr][Oo][Ff][Ii][Ll][Ee][Ss] ]]; then - HERMES_HOME=$(dirname -- "$home_parent") -fi -export HERMES_HOME - -runtime="$HERMES_HOME/hermes-agent" -native_app="$runtime/apps/desktop/release/linux-unpacked" - -runtime_ready() { - [[ -f $runtime/.hermes-bootstrap-complete && -f $runtime/venv/bin/hermes && -x $runtime/venv/bin/hermes && -f $runtime/venv/bin/python && -x $runtime/venv/bin/python ]] && - timeout 15 "$runtime/venv/bin/hermes" --version >/dev/null 2>&1 -} - -check_main() { - local main_commit - main_commit=$(git -C "$runtime" rev-parse --verify refs/heads/main 2>/dev/null || true) - if [[ -n $main_commit && $main_commit != "$release_commit" && $main_commit != "$(git -C "$runtime" rev-parse --verify refs/remotes/origin/main 2>/dev/null)" ]]; then - echo "Hermes main has local commits. Keep that work and prepare the desktop with 'hermes desktop --build-only'." >&2 - return 1 - fi -} - -if ! runtime_ready; then - # The upstream installer can reset an existing checkout. Do not pin a newer - # or modified runtime back to the package release while repairing setup. - if [[ -e $runtime || -L $runtime ]]; then - if [[ $(git -C "$runtime" rev-parse HEAD 2>/dev/null) != "$release_commit" ]] || - [[ -n $(git -C "$runtime" status --porcelain --untracked-files=all) ]]; then - echo "Hermes setup is incomplete at $runtime. Repair that installation before trying again; existing files have been kept." >&2 - exit 1 - fi - check_main - fi - - # Upstream replaces these commands, including foreign files and symlinks. - # Keep their original bytes/links before handing the names to the desktop. - command_backup="" - for command in hermes hermes-agent hermes-acp; do - command_path="$HOME/.local/bin/$command" - if [[ -e $command_path || -L $command_path ]]; then - if [[ ! -f $command_path && ! -L $command_path ]]; then - echo "Cannot replace $command_path: move it aside before installing Hermes Desktop." >&2 - exit 1 - fi - if [[ -z $command_backup ]]; then - command_backup=$(mktemp -d "$HOME/.local/bin/.hermes-before-desktop.XXXXXX") - echo "Saving existing Hermes commands in $command_backup" - fi - cp -a -- "$command_path" "$command_backup/" - fi - done - - echo "Setting up the Hermes runtime..." - bash /usr/share/hermes-desktop/install.sh --skip-setup --branch main --commit "$release_commit" --force-commit --dir "$runtime" --hermes-home "$HERMES_HOME" - if ! runtime_ready; then - echo "Hermes runtime setup did not complete. Re-run this command after resolving the installer error." >&2 - exit 1 - fi -fi - -runtime_commit=$(git -C "$runtime" rev-parse HEAD) -if [[ $runtime_commit == "$release_commit" ]]; then - # The updater switches to main before checking for changes. Start main at - # the packaged release, with enough history for its first fast-forward. - check_main - if [[ $(git -C "$runtime" rev-parse --is-shallow-repository) == "true" ]]; then - git -C "$runtime" fetch --unshallow origin main - fi - git -C "$runtime" switch -C main "$release_commit" - - if git -C "$runtime" apply --check /usr/share/hermes-desktop/runtime.patch >/dev/null 2>&1; then - git -C "$runtime" apply /usr/share/hermes-desktop/runtime.patch - elif ! git -C "$runtime" apply --reverse --check /usr/share/hermes-desktop/runtime.patch >/dev/null 2>&1; then - echo "The Hermes Linux runtime patch conflicts with local changes. Existing files have been kept." >&2 - exit 1 - fi -fi - -if [[ -e $native_app || -L $native_app ]]; then - if [[ ! -f $native_app/Hermes || ! -x $native_app/Hermes || ! -f $native_app/resources/app.asar || ! -f $native_app/resources/install-stamp.json ]]; then - echo "The Hermes desktop app at $native_app is incomplete. Repair it with 'hermes desktop --build-only' before trying again." >&2 - exit 1 - fi -else - if [[ $runtime_commit != "$release_commit" ]]; then - echo "The Hermes runtime has moved beyond the packaged desktop release. Run 'hermes desktop --build-only', then try again." >&2 - exit 1 - fi - desktop_changes=$(git -C "$runtime" status --porcelain --untracked-files=all -- apps/desktop package.json package-lock.json) - if [[ -n $desktop_changes ]]; then - echo "Hermes desktop sources have local changes. Run 'hermes desktop --build-only', then try again; existing files have been kept." >&2 - exit 1 - fi - - mkdir -p -- "${native_app%/*}" - staging=$(mktemp -d "${native_app%/*}/.linux-unpacked.XXXXXX") - trap 'rm -rf -- "$staging"' EXIT - cp -a /opt/hermes-desktop/. "$staging/" - chmod 0755 "$staging/chrome-sandbox" - mv -T --no-clobber -- "$staging" "$native_app" - if [[ -e $staging ]]; then - echo "A Hermes desktop app appeared during setup. It has been kept; please try again." >&2 - exit 1 - fi - trap - EXIT - - # Record this matching prebuilt app using the CLI's own content hash, so - # subsequent menu launches do not rebuild an app that is already current. - env -u PYTHONPATH -u PYTHONHOME "$runtime/venv/bin/python" - "$runtime" <<'PY' -import sys -from pathlib import Path - -sys.path.insert(0, sys.argv[1]) -if Path(sys.argv[1], "hermes_cli/main_desktop.py").is_file(): - from hermes_cli.main_desktop import _write_desktop_build_stamp -else: - from hermes_cli.main import _write_desktop_build_stamp - -_write_desktop_build_stamp(Path(sys.argv[1]), source_mode=False) -PY -fi +# The same install the default agent gets, plus opening the window. +omarchy-install-hermes-cli --now echo "Opening Hermes Desktop..." setsid uwsm-app -- /usr/bin/hermes-desktop >/dev/null 2>&1 & -# Only a running Hermes can be told which skin to show; a unit outlives this -# terminal and reports to the journal. -echo "Matching Hermes to the current theme once it is set up..." -systemctl --user stop omarchy-hermes-theme.service 2>/dev/null || true -systemd-run --user --quiet --collect --unit=omarchy-hermes-theme omarchy-theme-set-hermes --wait - echo "" echo "Hermes Desktop has been installed." diff --git a/bin/omarchy-install-chromium-claude b/bin/omarchy-install-chromium-claude new file mode 100755 index 000000000000..df3382712923 --- /dev/null +++ b/bin/omarchy-install-chromium-claude @@ -0,0 +1,43 @@ +#!/bin/bash + +# omarchy:summary=Install the Claude extension for Chromium-based browsers +# omarchy:requires-sudo=true + +set -euo pipefail + +if (( EUID == 0 )); then + export PATH=/usr/bin:/bin +fi + +EXTENSION_ID="fcoeoabgfenejglbffodgkkbkcdhcgfn" +EXTENSION_JSON='{ "external_update_url": "https://clients2.google.com/service/update2/crx" }' +PACKAGED_PATH=/usr/bin/omarchy-install-chromium-claude + +# Brave and Brave Origin share Chromium's external extension directory. +# Seed all supported browsers, including those installed after choosing Claude. +EXTENSION_DIRS=( + /usr/share/chromium/extensions + /usr/share/google-chrome/extensions + /usr/share/microsoft-edge/extensions +) + +installed=true +for dir in "${EXTENSION_DIRS[@]}"; do + if [[ ! -f $dir/$EXTENSION_ID.json ]] || [[ $(cat "$dir/$EXTENSION_ID.json") != "$EXTENSION_JSON" ]]; then + installed=false + fi +done + +if [[ $installed == "true" ]]; then + exit 0 +fi + +if (( EUID == 0 )); then + for dir in "${EXTENSION_DIRS[@]}"; do + printf '%s\n' "$EXTENSION_JSON" | install -D -m 0644 /dev/stdin "$dir/$EXTENSION_ID.json" + done +elif [[ -t 0 ]]; then + exec sudo "$PACKAGED_PATH" +else + exec pkexec "$PACKAGED_PATH" +fi diff --git a/bin/omarchy-install-dev-env b/bin/omarchy-install-dev-env index 263fd7556371..03577198d6f2 100755 --- a/bin/omarchy-install-dev-env +++ b/bin/omarchy-install-dev-env @@ -12,37 +12,10 @@ if [[ -z $1 ]]; then fi install_php() { - omarchy-pkg-add php composer php-sqlite xdebug + mise tool-alias set php github:nunomaduro/static-php-builds + mise use --global php@latest - # Install Path for Composer - if [[ :$PATH: != *:$HOME/.config/composer/vendor/bin:* ]]; then - echo 'export PATH="$HOME/.config/composer/vendor/bin:$PATH"' >>"$HOME/.bashrc" - source "$HOME/.bashrc" - echo "Added Composer global bin directory to PATH." - else - echo "Composer global bin directory already in PATH." - fi - - # Enable some extensions - local php_ini_path="/etc/php/php.ini" - local extensions_to_enable=( - "bcmath" - "intl" - "iconv" - "openssl" - "pdo_sqlite" - "pdo_mysql" - ) - - # Enable Xdebug - sudo sed -i \ - -e 's/^;zend_extension=xdebug.so/zend_extension=xdebug.so/' \ - -e 's/^;xdebug.mode=debug/xdebug.mode=debug/' \ - /etc/php/conf.d/xdebug.ini - - for ext in "${extensions_to_enable[@]}"; do - sudo sed -i "s/^;extension=${ext}/extension=${ext}/" "$php_ini_path" - done + mise x php -- composer global config bin-dir "$HOME/.local/bin" } install_node() { @@ -84,7 +57,7 @@ laravel) echo -e "Installing PHP and Laravel...\n" install_php install_node - composer global require laravel/installer + mise x php -- composer global require laravel/installer echo -e "\nYou can now run: laravel new myproject" ;; symfony) diff --git a/bin/omarchy-install-gaming-xbox-controllers b/bin/omarchy-install-gaming-xbox-controllers index f4134f767fdf..f2cda4e7c6c4 100755 --- a/bin/omarchy-install-gaming-xbox-controllers +++ b/bin/omarchy-install-gaming-xbox-controllers @@ -10,7 +10,7 @@ set -e echo "Installing Xbox controller Bluetooth support..." # Install xpadneo to ensure controllers work out of the box -omarchy-pkg-add linux-headers xpadneo-dkms +omarchy-pkg-add xpadneo-dkms # Prevent xpad/xpadneo driver conflict echo blacklist xpad | sudo tee /etc/modprobe.d/blacklist-xpad.conf >/dev/null diff --git a/bin/omarchy-install-hermes-cli b/bin/omarchy-install-hermes-cli index 4f4b99d768f1..a5acd0fe7c81 100755 --- a/bin/omarchy-install-hermes-cli +++ b/bin/omarchy-install-hermes-cli @@ -1,280 +1,544 @@ #!/bin/bash -# omarchy:summary=Install the Hermes CLI as a mise-backed wrapper in ~/.local/bin -# omarchy:args=[--check|--now|--owns|--remove] -# omarchy:examples=omarchy install hermes cli | omarchy install hermes cli --now - -# Hermes pins every one of its dependencies exactly and declares -# Requires-Python >=3.11,<3.14, so it can neither be built against Arch's -# Python nor share the python-* packages. mise builds it a private environment -# instead. +# omarchy:summary=Install Hermes Desktop for the default agent; its runtime provides the hermes command +# omarchy:args=<--check|--now|--retire-mise> +# omarchy:examples=omarchy install hermes cli --now | omarchy install hermes cli --check +# omarchy:requires-sudo=true + +# There is one Hermes on a machine, and it is the desktop app's. hermes-desktop +# ships upstream's installer and the release it was built from, and that +# installer makes the only Hermes that can update itself: a checkout under +# ~/.hermes with its own venv, which `hermes update` fast-forwards. The mise +# build this replaced had no checkout, so nothing an update could move. +# Choosing Hermes as the default agent therefore installs the app, the way +# Install > AI does, short of opening its window; see omarchy-install-ai-hermes. +# Hermes is only ever installed through the app: --check asks whether the +# app's Hermes is in and its command is what omarchy-agent would run, and +# --now installs the app whatever else answered to hermes before, saving +# whatever held the command's name aside before upstream's installer takes it. # -# It gets its own installer rather than a line in omarchy-mise-install because -# of the interpreter pin. Given no compatible interpreter to hand, uv builds -# the venv against the system Python in violation of Hermes' own bound, -# reports success, and leaves the breakage to surface later inside a -# dependency -- and omarchy-mise-install writes a fixed stub with nowhere to -# say otherwise. +# The wrapper the retired installer wrote, and the mise environment it built, +# are known here and nowhere else: --retire-mise is what the migration runs, +# and --now runs the same removal once it has replaced the wrapper. # -# There is only ever one Hermes on a machine. hermes-desktop cannot run against -# this one -- it needs a runtime built from its own commit, and the version gap -# fails its readiness probe -- so it installs its own under ~/.hermes and puts -# that on PATH. When the package is present it therefore owns Hermes outright: -# this installer stands aside and removes its own copy, so the terminal, the -# default agent and the app are all the same installation. +# Each mode is named outright. The app's launcher used to call this with no +# arguments to reconcile a mise copy, and a default of --now would turn every +# launch of the app into an install. set -euo pipefail mode=${1:-} -tool='pipx:hermes-agent[extras=all]' -python='3.13' +# Keep the runtime at the root even when invoked from a Hermes profile. +HERMES_HOME=$(realpath -ms -- "${HERMES_HOME:-$HOME/.hermes}") +home_parent=$(dirname -- "$HERMES_HOME") +if [[ ${home_parent##*/} == [Pp][Rr][Oo][Ff][Ii][Ll][Ee][Ss] ]]; then + HERMES_HOME=$(dirname -- "$home_parent") +fi +export HERMES_HOME + +runtime="$HERMES_HOME/hermes-agent" +native_app="$runtime/apps/desktop/release/linux-unpacked" +command_path="$HOME/.local/bin/hermes" -# The line that identifies the stub as this installer's; matched whole, so a -# wrapper that merely mentions the command is not mistaken for ours. -marker='# Written by omarchy-install-hermes-cli.' +# The wrapper the retired mise-backed installer wrote, matched whole so a +# wrapper that merely mentions it is not mistaken for it, and the tool it +# built. Running the wrapper built Hermes through mise, so it is never run to +# find out whether Hermes is there. +legacy_marker='# Written by omarchy-install-hermes-cli.' +legacy_tool='pipx:hermes-agent[extras=all]' -# The package, not the runtime directory: it is installed before the app has -# ever run, and that is exactly when we must not start building a second copy. -desktop_owns_hermes() { - omarchy-pkg-present hermes-desktop +legacy_stub() { + [[ -f $command_path ]] && grep -qxF "$legacy_marker" "$command_path" } -# The venv appears at the python-deps stage, several stages before the one that -# installs the command, so its presence says nothing about being usable. The -# marker is written last, and the command is what the agent actually runs. -desktop_hermes_ready() { - [[ -f $HOME/.hermes/hermes-agent/.hermes-bootstrap-complete ]] || return 1 - - # An executable of that name proves nothing about whose it is; the app's own - # points into ~/.hermes, and anything else is not the install we are asking - # about. Matched as a plain string, because the path carries a dot and an - # unanchored pattern would also claim a wrapper pointing at ~/xhermes. - [[ -f $HOME/.local/bin/hermes ]] || return 1 - grep -qF "$HOME/.hermes" "$HOME/.local/bin/hermes" || return 1 - - # And a marker left behind by an install whose venv has since gone answers - # for nothing, so the command has to run, exactly as a foreign one must. - hermes_prompt_ready +# Only the wrapper Omarchy wrote proves the environment is Omarchy's to remove: +# the regular file at its path, or the copy a run of this installer saved aside +# before upstream's installer took the name, since a user who chose Hermes +# before the migration ran has it there and the environment still requested. +# A link is someone else's arrangement, even when it lands on the wrapper, and +# so is a linked backup directory: the installer makes real ones. +saved_wrapper() { + [[ ! -L ${1%/hermes} && -f $1 && ! -L $1 ]] && grep -qxF "$legacy_marker" "$1" } -# Whether Hermes is really installed, not merely whether the stub exists. A -# stub on its own is cold: running it installs Hermes, which takes minutes. -installed() { - [[ -d "$(mise where "$tool" 2>/dev/null)/hermes-agent/lib/python$python" ]] +legacy_owned() { + local saved + if legacy_stub && [[ ! -L $command_path ]]; then + return 0 + fi + for saved in "$HOME/.local/bin"/.hermes-before-desktop.*/hermes; do + if saved_wrapper "$saved"; then + return 0 + fi + done + return 1 } -# The stub is the only thing this installer owns. Anything else at that path -# -- Hermes' official installer, a hand-rolled wrapper, even a dangling link -# -- was put there by the user and is never deleted or overwritten here. -# Symlinks count as foreign even when they resolve to a marked file: the stub -# is written as a regular file, so a link is someone else's arrangement. -ours() { - [[ -f $HOME/.local/bin/hermes && ! -L $HOME/.local/bin/hermes ]] && - grep -qxF "$marker" "$HOME/.local/bin/hermes" +# Gone means neither installed nor still asked for in the global config, where +# `mise up` would build it again. `mise rm -g` exits 0 whether or not it removed +# anything, so the listing is read instead, and a listing that cannot be read +# -- mise broken, or not there to read it -- is not an answer. The key carries +# the backend and name, with or without the options. +mise_retired() { + local requested + requested=$(mise ls -g --json 2>/dev/null) || return 1 + ! mise where "$legacy_tool" >/dev/null 2>&1 && ! grep -qE '"pipx:hermes-agent(\[|")' <<<"$requested" +} + +# Removes the environment the retired wrapper built, judged by what is left +# rather than by what the commands claimed. Only for a caller that has proved +# it Omarchy's. +retire_mise() { + if mise_retired; then + return 0 + fi + mise rm -g "$legacy_tool" >/dev/null 2>&1 || true + mise uninstall --all "$legacy_tool" >/dev/null 2>&1 || true + if mise_retired; then + return 0 + fi + echo "Could not remove the Hermes that mise built. Finish by hand:" >&2 + if omarchy-cmd-missing mise; then + echo " omarchy pkg add mise" >&2 + fi + echo " mise rm -g '$legacy_tool'" >&2 + echo " mise uninstall --all '$legacy_tool'" >&2 + return 1 } -foreign_hermes() { - [[ -e $HOME/.local/bin/hermes || -L $HOME/.local/bin/hermes ]] && ! ours +# Once the environment is gone the proof has done its work. Left behind it +# would keep --check answering no for an install that is finished, and claim +# an environment the user builds later as Omarchy's. The copies are Omarchy's +# own wrapper, so removing them takes nothing of the user's; a backup directory +# that held nothing else goes with them. +forget_legacy() { + local saved + if legacy_stub && [[ ! -L $command_path ]]; then + rm -f "$command_path" + fi + for saved in "$HOME/.local/bin"/.hermes-before-desktop.*/hermes; do + if saved_wrapper "$saved"; then + rm -f "$saved" + rmdir "${saved%/hermes}" 2>/dev/null || true + fi + done } # A hermes at that path is usable when it is a command that runs: a regular -# executable whose --version answers. The executable bit alone proves little -- a directory -# passes -x on search permission, and a wrapper whose interpreter or target is -# gone passes it too. The desktop app applies the same probe with the same 15 -# second budget, so what passes here is what it will use. +# executable whose --version answers. The executable bit alone proves little -- a +# directory passes -x on search permission, and a wrapper whose interpreter or +# target is gone passes it too. The desktop app applies the same probe with the +# same 15 second budget, so what passes here is what it will use. hermes_runs() { - [[ -f $HOME/.local/bin/hermes && -x $HOME/.local/bin/hermes ]] && - timeout 15 "$HOME/.local/bin/hermes" --version >/dev/null 2>&1 + [[ -f $command_path && -x $command_path ]] && + timeout 15 "$command_path" --version >/dev/null 2>&1 } # A flag counts only when the help defines it, not whenever it is mentioned: -# what follows must be a shape argparse prints after a definition -- the usage -# line's closing bracket, the gap before same-line help text, an uppercase -# metavar, or the end of the line. Prose like "With --tui: run ..." stays -# prose, and --tui-theme or --tui_mode never answers for --tui. Not probed by -# parsing an actual invocation on purpose: a release that ignores unknown -# arguments would turn the probe into a live session. +# closing its short form, followed by its metavar, or padded to a description +# column. Matched against the help text rather than by parsing an actual +# invocation on purpose: a release that ignores unknown arguments would turn +# the probe into a live session. help_defines_flag() { grep -qE -- "$1(]|[[:space:]][[:upper:]]|[[:space:]]{2}|$)" <<<"$2" } # Probed for the flags omarchy-agent actually passes -- --query to seed the # session and --tui to keep it interactive -- rather than a marker standing in -# for them: the old probe keyed on chat carrying --oneshot, which no released -# Hermes did (it lived at the top level until v0.21 added chat's own), so -# every release read as "not ready". +# for them. hermes_prompt_ready() { local help hermes_runs && - help=$(timeout 15 "$HOME/.local/bin/hermes" chat --help 2>/dev/null) && + help=$(timeout 15 "$command_path" chat --help 2>/dev/null) && help_defines_flag '--tui' "$help" && help_defines_flag '--query' "$help" } -# --owns answers whether the wrapper on PATH is the one this command wrote, so -# the migration and Remove Preinstalls do not each carry their own copy of the -# marker and drift from it. -if [[ $mode == "--owns" ]]; then - if ours; then exit 0; else exit 1; fi -fi +# The command upstream's installer writes execs into the runtime. Anything else +# at that path -- an official install elsewhere, a hand-rolled wrapper, even a +# dangling link -- is the user's. Matched as a plain string with its trailing +# slash, because the path carries a dot and a bare prefix would also claim a +# wrapper pointing at ~/.hermes-old. +ours() { + [[ -f $command_path && ! -L $command_path ]] && grep -qF "$HERMES_HOME/" "$command_path" +} -# --remove tears down a Hermes CLI this installer put in place -- the mise tool -# it installed and the stub it marked -- so Remove Hermes clears a CLI the app -# never superseded (an interrupted install, or the terminal CLI from before the -# app existed) rather than leaving it stranded on PATH. The whole teardown -# turns on the marked stub, exactly as replacement does further down: without -# it nothing proves the mise environment is Omarchy's rather than one the user -# built against the same spec, and a user's stays theirs. The desktop takeover -# removes the environment without asking, but that is its own bargain -- a -# second Hermes has to go whoever built it, and the app still provides the -# command afterwards; here nothing would. Idempotent: nothing owned, nothing -# to do. -if [[ $mode == "--remove" ]]; then - if ours; then - mise rm -g "$tool" >/dev/null 2>&1 || true - mise uninstall --all "$tool" >/dev/null 2>&1 || true - rm -f "$HOME/.local/bin/hermes" 2>/dev/null || true - - # Every step is attempted before any is judged, and judged by what is left - # rather than by what the commands claimed: the marked stub still answering - # hermes, or mise still resolving the tool, is a CLI still installed no - # matter how the removal exited. - # Not "run --remove again": once the stub is gone nothing marks the mise - # environment as ours, so a rerun would find nothing it owns and succeed - # without touching what was left. Only the full commands finish the job. - if ours || mise where "$tool" >/dev/null 2>&1; then - echo "Could not remove the Hermes CLI Omarchy installed. Finish by hand:" >&2 - echo " rm -f ~/.local/bin/hermes" >&2 - echo " mise rm -g '$tool'" >&2 - echo " mise uninstall --all '$tool'" >&2 - exit 1 - fi - fi +# What omarchy-agent runs is whichever hermes is first on PATH, and Omarchy puts +# mise's shims ahead of ~/.local/bin. So the command the probe vets has to be +# the one PATH finds, or the agent is on a different Hermes than the one set +# up. A PATH that finds none is not in the way: the theme unit asks from a +# service whose PATH has no ~/.local/bin, and runs the command by its path. +on_path() { + local found + found=$(type -P hermes) || return 0 + [[ $(realpath -m -- "$found") == "$(realpath -m -- "$command_path")" ]] +} - exit 0 -fi +shadowing_hermes() { + type -P hermes || true +} -# --check lets callers tell a cold stub from a working one before they commit -# to a path that assumes Hermes is ready. -if [[ $mode == "--check" ]]; then - if desktop_owns_hermes; then - if desktop_hermes_ready; then exit 0; else exit 1; fi - fi - # A foreign command is ready only when it also supports prompted sessions; - # since it is not ours to replace, nothing this installer does will update it. - if foreign_hermes; then - if hermes_prompt_ready; then exit 0; else exit 1; fi +# The installer writes the marker last, so it is the one thing that says a +# runtime finished installing rather than merely started; the venv appears +# several stages earlier. And a marker left behind by an install whose venv has +# since gone answers for nothing, so the command has to run. +runtime_ready() { + [[ -f $runtime/.hermes-bootstrap-complete && -f $runtime/venv/bin/hermes && -x $runtime/venv/bin/hermes && -f $runtime/venv/bin/python && -x $runtime/venv/bin/python ]] && + timeout 15 "$runtime/venv/bin/hermes" --version >/dev/null 2>&1 +} + +native_app_complete() { + [[ -f $native_app/Hermes && -x $native_app/Hermes && -f $native_app/resources/app.asar && -f $native_app/resources/install-stamp.json ]] +} + +# What --check answers, and what --now has nothing left to do about: the app +# is installed and the Hermes on the machine is its own -- the command +# upstream's installer wrote, the runtime's completion marker and the seeded +# packaged app, because the app only runs against a runtime it prepared and +# the terminal has to be on the same one -- and that command is the one PATH +# finds, with nothing of the retired wrapper's left to remove. The two agree +# on purpose: choosing Hermes from the menu asks first and opens a terminal +# only on a no, so a yes here has to mean --now would take no minutes-long +# step where nobody can watch it. +installed() { + on_path || return 1 + if legacy_owned; then + return 1 fi - if installed && hermes_prompt_ready; then exit 0; else exit 1; fi -fi + omarchy-pkg-present hermes-desktop && ours && [[ -f $runtime/.hermes-bootstrap-complete ]] && native_app_complete && hermes_prompt_ready +} -# Hand Hermes over to the app rather than keeping a second copy beside it. -if desktop_owns_hermes; then - # Not gated on that copy being healthy: `mise up` can rebuild it against the - # wrong interpreter and a half-finished install answers to neither test, and - # either way it is still a second Hermes. Removing nothing is harmless. - if mise where "$tool" >/dev/null 2>&1; then - echo "Hermes Desktop provides Hermes; removing the separate CLI install..." >&2 +# Once a Hermes answers at the command's path, the environment the retired +# wrapper built goes with whatever proof is left of it, and then PATH has to +# agree with the probe: a mise shim, or anything else ahead of ~/.local/bin, is +# what the default agent would run instead. +settle_path() { + if legacy_owned; then + echo "Removing the Hermes that mise built; Hermes now updates itself..." + retire_mise || return 1 + forget_legacy + fi + if ! on_path; then + echo "$command_path is ready, but 'hermes' on PATH is $(shadowing_hermes), which is what the default agent runs." >&2 + echo "Remove or reorder it, then run omarchy-install-hermes-cli --now again." >&2 + return 1 fi +} - mise rm -g "$tool" >/dev/null 2>&1 || true - mise uninstall --all "$tool" >/dev/null 2>&1 || true +# The updater switches to main before checking for changes, so main has to +# start at the packaged release. Whatever main pointed at first is kept under +# another name rather than judged: upstream rewrites its history often enough +# that a clone's main sits off origin/main with no local commit on it, and a +# user's own commits are exactly what must not be lost either way. +keep_main() { + local main_commit kept + main_commit=$(git -C "$runtime" rev-parse --verify refs/heads/main 2>/dev/null || true) + if [[ -n $main_commit && $main_commit != "$release_commit" && $main_commit != "$(git -C "$runtime" rev-parse --verify refs/remotes/origin/main 2>/dev/null)" ]]; then + # A run that stopped after this point keeps it again on the next try; one + # branch at that commit is enough. + if [[ -z $(git -C "$runtime" for-each-ref --points-at "$main_commit" 'refs/heads/main-before-omarchy-*') ]]; then + kept="main-before-omarchy-$(date +%s)" + git -C "$runtime" branch "$kept" "$main_commit" + echo "Kept what Hermes main pointed at as the branch $kept; main now starts at the packaged release." + fi + fi +} - # Our own stub has to go with it. Left in place it still answers `hermes` - # until the app's bootstrap overwrites it, and answering means building the - # second Hermes this whole arrangement exists to avoid. - if ours; then - rm -f "$HOME/.local/bin/hermes" +# The repository a process's GIT_DIR names, canonical: relative to its working +# directory when relative, and with no trailing slash or dot segments either +# way. Read NUL-delimited as the kernel writes it, never through a pipe: a +# path may carry a newline, and grep stopping at a match would fail a pipe +# under pipefail and call a busy git idle. +git_dir_of() { + local pid=$1 entry dir="" cwd + while IFS= read -r -d '' entry; do + if [[ $entry == GIT_DIR=* ]]; then + dir=${entry#GIT_DIR=} + break + fi + done <"/proc/$pid/environ" 2>/dev/null || return 1 + [[ -n $dir ]] || return 1 + if [[ $dir != /* ]]; then + cwd=$(readlink "/proc/$pid/cwd" 2>/dev/null) || return 1 + dir="$cwd/$dir" fi + realpath -m -- "$dir" +} + +# A git of this user working in the runtime: a fetch Hermes started to work +# out its --version, or its updater. Found by working directory, or by a +# GIT_DIR in its environment, rather than by command line, since the remote +# helpers git spawns carry no repository path on theirs. Compared canonical, +# because /proc resolves every link and the runtime path keeps them. +git_busy_in_runtime() { + local pid cwd dir real + real=$(realpath -e -- "$runtime" 2>/dev/null) || return 1 + for pid in $(pgrep -u "$(id -u)" -f '^([^ ]*/)?git(-remote-[a-z]+)?( |$)' 2>/dev/null); do + cwd=$(readlink "/proc/$pid/cwd" 2>/dev/null) || continue + if [[ $cwd == "$real" || $cwd == "$real/"* ]]; then + return 0 + fi + if dir=$(git_dir_of "$pid") && [[ $dir == "$real/.git" ]]; then + return 0 + fi + done + return 1 +} - if desktop_hermes_ready; then - exit 0 +# Hermes works out its --version against origin, and the probe's 15 second +# budget can kill it mid-fetch, which leaves git's shallow.lock behind; a fetch +# of ours that a network blip interrupted leaves the same. Git refuses to clear +# a lock it did not take, and a file's age alone cannot say whether anything +# still holds it, so a live git in the runtime is waited for first, and only a +# lock nobody holds and nothing has touched for a minute is cleared. The fetch +# itself gets three tries. +unshallow_runtime() { + local attempt waited lock="$runtime/.git/shallow.lock" + for attempt in 1 2 3; do + waited=0 + while git_busy_in_runtime && (( waited < 60 )); do + if (( waited == 0 )); then + echo "Waiting for Hermes to finish working in $runtime..." + fi + sleep 2 + waited=$(( waited + 2 )) + done + if git_busy_in_runtime; then + echo "Hermes is still working in $runtime. Let it finish, then run omarchy-install-hermes-cli --now again." >&2 + return 1 + fi + if [[ -e $lock && -n $(find "$lock" -mmin +1 2>/dev/null) ]]; then + rm -f "$lock" + fi + if git -C "$runtime" fetch --unshallow origin main; then + return 0 + fi + if (( attempt < 3 )); then + sleep 2 + fi + done + echo "Could not fetch the Hermes history from origin. Check the network, then run omarchy-install-hermes-cli --now again." >&2 + return 1 +} + +case "$mode" in +--check) + if installed; then exit 0; else exit 1; fi + ;; +--retire-mise) + # The migration's whole job. The environment goes before the wrapper, since + # once the wrapper is gone nothing marks the environment as Omarchy's and a + # rerun could not finish what a failed removal left behind. + if legacy_owned; then + retire_mise || exit 1 + forget_legacy fi + exit 0 + ;; +--now) ;; +*) + echo "Usage: omarchy-install-hermes-cli <--check|--now|--retire-mise>" >&2 + exit 1 + ;; +esac - echo "Hermes Desktop is installed but has not set Hermes up yet." >&2 - echo "Launch Hermes Desktop once to finish installing it." >&2 +if (( EUID == 0 )); then + echo "Run this command as your desktop user, without sudo." >&2 exit 1 fi -# The user already has a hermes of their own. Leave it be: a working one is -# what the default agent will run, and a broken one is theirs to fix. -if foreign_hermes; then - if hermes_prompt_ready; then - exit 0 - fi +if installed; then + exit 0 +fi - if hermes_runs; then - echo "~/.local/bin/hermes does not support the interactive seeded sessions Omarchy needs." >&2 - echo "Update it to a Hermes Agent release with interactive chat queries, then run omarchy-install-hermes-cli again." >&2 - exit 1 - fi +if ! omarchy-pkg-present hermes-desktop; then + echo "Installing Hermes Desktop..." + omarchy-pkg-add hermes-desktop +fi - echo "~/.local/bin/hermes exists but is not runnable, and it was not installed by Omarchy." >&2 - echo "Fix or remove it, then run omarchy-install-hermes-cli again." >&2 +if [[ ! -r /usr/share/hermes-desktop/install.sh || ! -r /usr/share/hermes-desktop/runtime.patch ]] || + ! release_commit=$(jq -er 'select(.branch == "main") | .commit | select(test("^[0-9a-f]{40}$"))' /opt/hermes-desktop/resources/install-stamp.json 2>/dev/null); then + echo "The installed Hermes package cannot prepare in-app updates. Run 'omarchy update', then try again." >&2 exit 1 fi -# Only the marked wrapper proves the matching mise environment is ours to replace. -if installed && ! hermes_prompt_ready; then - if ours; then - echo "Updating Hermes for prompted sessions..." >&2 - mise rm -g "$tool" >/dev/null 2>&1 || true - mise uninstall --all "$tool" >/dev/null 2>&1 || true - else - echo "A Hermes mise environment exists without an Omarchy-owned wrapper." >&2 - echo "Update or remove it explicitly, then run omarchy-install-hermes-cli again." >&2 - exit 1 - fi +runtime_present=false +if runtime_ready; then + runtime_present=true fi -mkdir -p "$HOME/.local/bin" -rm -f "$HOME/.local/bin/hermes" +# A seeded app has to be whole, whatever state the runtime beside it is in. +refuse_unless_app_whole() { + if [[ -e $native_app || -L $native_app ]] && ! native_app_complete; then + echo "The Hermes desktop app at $native_app is incomplete. Repair it with 'hermes desktop --build-only' before trying again." >&2 + return 1 + fi +} -cat >"$HOME/.local/bin/hermes" </dev/null) || [[ -z $runtime_commit ]]; then + echo "Could not read the Hermes runtime's git state at $runtime. Repair that installation before trying again; existing files have been kept." >&2 + return 1 + fi + if [[ $runtime_commit != "$release_commit" ]]; then + echo "The Hermes runtime has moved beyond the packaged desktop release. Run 'hermes desktop --build-only', then try again." >&2 + return 1 + fi + if ! changes=$(git -C "$runtime" status --porcelain --untracked-files=all -- apps/desktop package.json package-lock.json 2>/dev/null); then + echo "Could not read the Hermes runtime's git state at $runtime. Repair that installation before trying again; existing files have been kept." >&2 + return 1 + fi + if [[ -n $changes ]]; then + echo "Hermes desktop sources have local changes. Run 'hermes desktop --build-only', then try again; existing files have been kept." >&2 + return 1 + fi + if ! git -C "$runtime" apply --check /usr/share/hermes-desktop/runtime.patch >/dev/null 2>&1 && + ! git -C "$runtime" apply --reverse --check /usr/share/hermes-desktop/runtime.patch >/dev/null 2>&1; then + echo "The Hermes Linux runtime patch conflicts with local changes. Existing files have been kept." >&2 + return 1 + fi +} -$marker +if [[ $runtime_present == "true" ]]; then + refuse_unless_seedable || exit 1 +elif [[ -e $runtime || -L $runtime ]]; then + # The upstream installer can reset an existing checkout. Do not pin a newer + # or modified runtime back to the package release while repairing setup, + # and a git state that cannot be read is not a clean one. + refuse_unless_app_whole || exit 1 + if ! runtime_commit=$(git -C "$runtime" rev-parse HEAD 2>/dev/null) || [[ $runtime_commit != "$release_commit" ]] || + ! changes=$(git -C "$runtime" status --porcelain --untracked-files=all 2>/dev/null) || [[ -n $changes ]]; then + echo "Hermes setup is incomplete at $runtime. Repair that installation before trying again; existing files have been kept." >&2 + exit 1 + fi +fi -export UV_PYTHON="$python" +# Whether this run gave Hermes something new to show the theme to: a runtime +# it set up, or the app it seeded. Putting a command back is neither. +set_up=false -# Exported rather than set on the install line alone, so the version resolved -# to run agrees with the one just installed. Hermes ships several times a week -# and mise's cooldown would otherwise hold a new release back for days. -export MISE_MINIMUM_RELEASE_AGE=0 +# The command is the runtime's own and runs; anything else at the path gets +# replaced below. The retired wrapper is never run to find out. +command_ready=false +if ! legacy_stub && ours && hermes_runs; then + command_ready=true +fi -# mise up -- which omarchy update runs -- reinstalls without that pin, so this -# asks which interpreter is actually there rather than whether anything is. -if ! [[ -d "\$(mise where '$tool' 2>/dev/null)/hermes-agent/lib/python$python" ]]; then - echo "Installing Hermes on Python $python (this takes a minute)..." >&2 +# Upstream replaces these commands, including foreign files and symlinks, +# whether it sets the runtime up or only writes the commands again. Keep their +# original bytes/links before handing the names to the runtime. +if [[ $runtime_present == "false" || $command_ready == "false" ]]; then + command_backup="" + for command in hermes hermes-agent hermes-acp; do + existing="$HOME/.local/bin/$command" + if [[ -e $existing || -L $existing ]]; then + if [[ ! -f $existing && ! -L $existing ]]; then + echo "Cannot replace $existing: move it aside before installing Hermes." >&2 + exit 1 + fi + if [[ -z $command_backup ]]; then + command_backup=$(mktemp -d "$HOME/.local/bin/.hermes-before-desktop.XXXXXX") + echo "Saving existing Hermes commands in $command_backup" + fi + cp -a -- "$existing" "$command_backup/" + fi + done +fi - # mise's pipx backend shells out to uv, which a stock Omarchy does not have. - # It is fetched here rather than when this stub was written, so setting up a - # machine that never runs Hermes costs nothing. - if omarchy-cmd-missing uv && ! mise where uv >/dev/null 2>&1; then - mise use -g --quiet uv@latest || exit 1 +if [[ $runtime_present == "false" ]]; then + echo "Setting up the Hermes runtime..." + # npx stops to ask before fetching Playwright for the browser tools, and in + # the terminal the menu opens for this nobody is there to say yes. + npm_config_yes=true bash /usr/share/hermes-desktop/install.sh --skip-setup --branch main --commit "$release_commit" --force-commit --dir "$runtime" --hermes-home "$HERMES_HOME" + if ! runtime_ready; then + echo "Hermes runtime setup did not complete. Re-run this command after resolving the installer error." >&2 + exit 1 fi + set_up=true +elif [[ $command_ready == "false" ]]; then + # The runtime is in place but the command is not its own, or does not run: + # gone, the retired wrapper, one the user put there, or the runtime's own + # with its mode bits stripped. Upstream's path stage writes its commands + # without touching the checkout. + echo "Restoring the Hermes commands..." + bash /usr/share/hermes-desktop/install.sh --stage path --dir "$runtime" --hermes-home "$HERMES_HOME" +fi - mise use -g --quiet --force '$tool' || exit 1 +runtime_commit=$(git -C "$runtime" rev-parse HEAD) +if [[ $runtime_commit == "$release_commit" ]]; then + # Start main at the packaged release, with enough history for its first + # fast-forward. + keep_main + if [[ $(git -C "$runtime" rev-parse --is-shallow-repository) == "true" ]]; then + unshallow_runtime + fi + git -C "$runtime" switch -C main "$release_commit" + + if git -C "$runtime" apply --check /usr/share/hermes-desktop/runtime.patch >/dev/null 2>&1; then + git -C "$runtime" apply /usr/share/hermes-desktop/runtime.patch + elif ! git -C "$runtime" apply --reverse --check /usr/share/hermes-desktop/runtime.patch >/dev/null 2>&1; then + echo "The Hermes Linux runtime patch conflicts with local changes. Existing files have been kept." >&2 + exit 1 + fi fi -# The pin belongs to building Hermes, not to everything Hermes then runs. -# Exported it would reach the agent and every command it shells out to, so a -# uv in the user's own project would resolve 3.13 there too -- uv only warns -# when that contradicts the project's requires-python, and builds it anyway. -exec env -u UV_PYTHON mise x '$tool' -- hermes "\$@" -EOF - -chmod +x "$HOME/.local/bin/hermes" - -# The desktop app resolves a hermes on PATH by running `hermes --version` with -# a 15 second budget, then falls back to cloning its own copy when that times -# out. A first-run mise install does not fit in 15 seconds, so anything that -# hands Hermes to the GUI has to install it here rather than leave it stubbed. -if [[ $mode == "--now" ]]; then - "$HOME/.local/bin/hermes" --version - if ! hermes_prompt_ready; then - echo "Hermes installed without the interactive seeded sessions Omarchy needs." >&2 +refuse_unless_seedable || exit 1 +if [[ ! -e $native_app && ! -L $native_app ]]; then + mkdir -p -- "${native_app%/*}" + staging=$(mktemp -d "${native_app%/*}/.linux-unpacked.XXXXXX") + trap 'rm -rf -- "$staging"' EXIT + cp -a /opt/hermes-desktop/. "$staging/" + chmod 0755 "$staging/chrome-sandbox" + mv -T --no-clobber -- "$staging" "$native_app" + if [[ -e $staging ]]; then + echo "A Hermes desktop app appeared during setup. It has been kept; please try again." >&2 exit 1 fi + trap - EXIT + + # Record this matching prebuilt app using the CLI's own content hash, so + # subsequent menu launches do not rebuild an app that is already current. + env -u PYTHONPATH -u PYTHONHOME "$runtime/venv/bin/python" - "$runtime" <<'PY' +import sys +from pathlib import Path + +sys.path.insert(0, sys.argv[1]) +if Path(sys.argv[1], "hermes_cli/main_desktop.py").is_file(): + from hermes_cli.main_desktop import _write_desktop_build_stamp +else: + from hermes_cli.main import _write_desktop_build_stamp + +_write_desktop_build_stamp(Path(sys.argv[1]), source_mode=False) +PY + set_up=true +fi + +# What omarchy-agent runs is the command, not the venv, so the command is what +# has to answer for the seeded sessions. +if ! hermes_prompt_ready; then + echo "Hermes is installed at $runtime, but $command_path does not run the interactive seeded sessions Omarchy needs." >&2 + echo "Update Hermes with 'hermes update', then run omarchy-install-hermes-cli --now again." >&2 + exit 1 +fi + +settle_path || exit 1 + +# Only a running Hermes can be told which skin to show; a unit outlives this +# terminal and reports to the journal. +if [[ $set_up == "true" ]]; then + echo "Matching Hermes to the current theme once it is set up..." + systemctl --user stop omarchy-hermes-theme.service 2>/dev/null || true + systemd-run --user --quiet --collect --unit=omarchy-hermes-theme omarchy-theme-set-hermes --wait fi diff --git a/bin/omarchy-install-preinstalls b/bin/omarchy-install-preinstalls index 549ce792dd8d..c60b5b34cdd7 100755 --- a/bin/omarchy-install-preinstalls +++ b/bin/omarchy-install-preinstalls @@ -23,8 +23,10 @@ if gum confirm "Are you sure you want to restore all preinstalled web apps, TUI moonlight-qt \ lazydocker \ omacut \ + monologue \ omacalc \ - omawrite; then + omawrite \ + hype; then echo -e "\nPreinstalls are still marked as removed. Fix the errors above and try again." exit 1 fi diff --git a/bin/omarchy-install-service-1password b/bin/omarchy-install-service-1password index f59cab9257c9..fc7238a6dd80 100755 --- a/bin/omarchy-install-service-1password +++ b/bin/omarchy-install-service-1password @@ -28,7 +28,7 @@ echo "Installing 1Password extension for Chromium..." install_chromium_extension echo "Opening 1Password..." -uwsm-app -- 1password >/dev/null 2>&1 & +setsid uwsm-app -- 1password >/dev/null 2>&1 & echo "" echo "1Password has been installed. Restart Chromium to load the browser extension." diff --git a/bin/omarchy-install-service-dropbox b/bin/omarchy-install-service-dropbox index 0ee07bfbfc1f..7a4e190ec52f 100755 --- a/bin/omarchy-install-service-dropbox +++ b/bin/omarchy-install-service-dropbox @@ -1,6 +1,7 @@ #!/bin/bash # omarchy:summary=Install and start the Dropbox service. Must then be authenticated via the web. +# omarchy:requires-sudo=true echo "Installing all dependencies..." omarchy-pkg-add dropbox dropbox-cli libappindicator-gtk3 python-gpgme nautilus-dropbox diff --git a/bin/omarchy-launch-browser b/bin/omarchy-launch-browser index 044b220d2268..d858a3a451ca 100755 --- a/bin/omarchy-launch-browser +++ b/bin/omarchy-launch-browser @@ -3,10 +3,7 @@ # omarchy:summary=Launch the default browser as determined by xdg-settings. # omarchy:args=[url] -default_browser=$(env -u BROWSER xdg-settings get default-web-browser) -if [[ -z $default_browser ]]; then - default_browser=$(xdg-mime query default x-scheme-handler/https) -fi +default_browser=$(omarchy-cmd-default-browser) browser_exec=$(sed -n 's/^Exec=\([^ ]*\).*/\1/p' {~/.local,~/.nix-profile,/usr}/share/applications/$default_browser 2>/dev/null | head -1) if $browser_exec --help 2>/dev/null | grep -q MOZ_LOG; then @@ -17,9 +14,11 @@ else private_flag="--incognito" fi -systemd-run --user --quiet --collect --unit="omarchy-browser-$(date +%s%N)" \ - --property=StandardOutput=null --property=StandardError=null \ - uwsm-app -- "$browser_exec" "${@/--private/$private_flag}" +if ! omarchy-cmd-browser-handoff "$browser_exec" "${@/--private/$private_flag}"; then + systemd-run --user --quiet --collect --unit="omarchy-browser-$(date +%s%N)" \ + --property=StandardOutput=null --property=StandardError=null \ + uwsm-app -- "$browser_exec" "${@/--private/$private_flag}" +fi url="" for argument in "$@"; do diff --git a/bin/omarchy-launch-editor b/bin/omarchy-launch-editor index 8a69dabd4bbc..cbf12c787f06 100755 --- a/bin/omarchy-launch-editor +++ b/bin/omarchy-launch-editor @@ -18,17 +18,20 @@ else editor="nvim" fi +# sublime-text-4 ships `subl` on PATH, not `sublime_text`. +[[ $editor == sublime_text ]] && editor=subl + omarchy-cmd-present "$editor" || editor="nvim" case "${editor##*/}" in nvim | vim | nano | micro | hx | helix | fresh) if [[ $inline == "true" ]]; then - exec "$editor" "$@" + exec "$editor" -- "$@" else - exec omarchy-launch-tui "$editor" "$@" + exec omarchy-launch-tui "$editor" -- "$@" fi ;; *) - exec setsid uwsm-app -- "$editor" "$@" + exec setsid uwsm-app -- "$editor" -- "$@" ;; esac diff --git a/bin/omarchy-launch-floating-terminal-with-presentation b/bin/omarchy-launch-floating-terminal-with-presentation index c9cb255abf7e..4497ff0dd74e 100755 --- a/bin/omarchy-launch-floating-terminal-with-presentation +++ b/bin/omarchy-launch-floating-terminal-with-presentation @@ -8,6 +8,7 @@ source omarchy-restart-gum cmd="$*" -presentation_script="omarchy-show-logo; $cmd; if (( \$? != 130 )); then omarchy-show-done; fi" +# 130 is the user bailing with Ctrl-C; anything else gets the Done/Failed prompt. +presentation_script="omarchy-show-logo; $cmd; code=\$?; if (( code != 130 )); then omarchy-show-done \$code; fi" exec setsid uwsm-app -- xdg-terminal-exec --app-id=org.omarchy.terminal --title=Omarchy -e bash -c "$presentation_script" diff --git a/bin/omarchy-launch-screensaver b/bin/omarchy-launch-screensaver index c66c41da3ee2..78cf757116ae 100755 --- a/bin/omarchy-launch-screensaver +++ b/bin/omarchy-launch-screensaver @@ -29,7 +29,8 @@ hypr_exec() { local command printf -v command '%q ' "$@" - hyprctl dispatch "hl.dsp.exec_cmd([[$command]])" >/dev/null 2>&1 || hyprctl dispatch exec -- bash -lc "$command" >/dev/null + hyprctl dispatch "hl.dsp.exec_cmd([[[workspace $workspace] $command]])" >/dev/null 2>&1 || + hyprctl dispatch exec -- "[workspace $workspace]" bash -lc "$command" >/dev/null } SOCKET="$XDG_RUNTIME_DIR/hypr/$HYPRLAND_INSTANCE_SIGNATURE/.socket2.sock" @@ -49,8 +50,10 @@ wait_for_screensaver_window() { done } -for m in $(hyprctl monitors -j | jq -r '.[] | .name'); do +while read -r m special; do hypr_focus_monitor "$m" + # Share a special workspace that is already showing, like the scratchpad, so it is still open afterwards. + workspace=${special:-special:screensaver-$m} case $terminal in *Alacritty*) @@ -68,6 +71,16 @@ for m in $(hyprctl monitors -j | jq -r '.[] | .name'); do esac wait_for_screensaver_window -done +done < <(hyprctl monitors -j | jq -r '.[] | "\(.name) \(.specialWorkspace.name)"') hypr_focus_monitor "$focused" + +# Emptying a special workspace focuses its monitor, so the last screensaver to close would take focus +# with it. Hand focus back to the monitor that had it once they are all gone. +# The class goes through the environment, since in argv the screensaver's pgrep and pkill would match it. +( + while hyprctl clients -j | SCREENSAVER=org.omarchy.screensaver jq -e 'any(.[]; .mapped and .class == env.SCREENSAVER)' >/dev/null; do + IFS= read -r -u "$events" line || exit + done + hypr_focus_monitor "$focused" +) >/dev/null 2>&1 & diff --git a/bin/omarchy-launch-terminal b/bin/omarchy-launch-terminal index a07a1dde4f83..bd0acbf00c1a 100755 --- a/bin/omarchy-launch-terminal +++ b/bin/omarchy-launch-terminal @@ -1,6 +1,12 @@ #!/bin/bash # omarchy:summary=Launch a terminal in the active terminal's current directory -# omarchy:args=[command...] +# omarchy:args=[--pid=] [command...] -exec setsid uwsm-app -- xdg-terminal-exec --dir="$(omarchy-cmd-terminal-cwd)" "$@" +pid="" +if [[ ${1:-} == --pid=* ]]; then + pid=${1#--pid=} + shift +fi + +exec setsid uwsm-app -- xdg-terminal-exec --dir="$(omarchy-cmd-terminal-cwd "$pid")" "$@" diff --git a/bin/omarchy-launch-webapp b/bin/omarchy-launch-webapp index 6ee0f84a2533..392882e5e534 100755 --- a/bin/omarchy-launch-webapp +++ b/bin/omarchy-launch-webapp @@ -3,11 +3,15 @@ # omarchy:summary=Launch a URL as a web app in the default supported browser # omarchy:args= -browser=$(xdg-settings get default-web-browser) +browser=$(omarchy-cmd-default-browser) case $browser in google-chrome* | brave* | microsoft-edge* | opera* | vivaldi* | helium*) ;; *) browser="chromium.desktop" ;; esac -exec setsid uwsm-app -- $(sed -n 's/^Exec=\([^ ]*\).*/\1/p' {~/.local,~/.nix-profile,/usr}/share/applications/$browser 2>/dev/null | head -1) --app="$1" "${@:2}" +browser_exec=$(sed -n 's/^Exec=\([^ ]*\).*/\1/p' {~/.local,~/.nix-profile,/usr}/share/applications/$browser 2>/dev/null | head -1) + +if ! omarchy-cmd-browser-handoff "$browser_exec" --app="$1" "${@:2}"; then + exec setsid uwsm-app -- $browser_exec --app="$1" "${@:2}" +fi diff --git a/bin/omarchy-menu-images b/bin/omarchy-menu-images index 8305cb0fdd72..6b41e65a095c 100755 --- a/bin/omarchy-menu-images +++ b/bin/omarchy-menu-images @@ -1,7 +1,7 @@ #!/bin/bash # omarchy:summary=Open a generic image selector menu -# omarchy:args=[--selected ] [--print-name] [--show-labels] [--filterable] [--lazy-thumbnails] [--preload] [--cache-only] ... +# omarchy:args=[--selected ] [--print-name] [--show-labels] [--filterable] [--lazy-thumbnails] [--preload] [--cache-only] [--print-rows] ... selected_image="" print_name=false @@ -11,10 +11,11 @@ lazy_thumbnails=false prepare_only=false preload=false cache_only=false +print_rows=false image_dirs=() usage() { - echo "Usage: omarchy-menu-images [--selected ] [--print-name] [--show-labels] [--filterable] [--lazy-thumbnails] [--preload] [--cache-only] ..." + echo "Usage: omarchy-menu-images [--selected ] [--print-name] [--show-labels] [--filterable] [--lazy-thumbnails] [--preload] [--cache-only] [--print-rows] ..." } while (( $# > 0 )); do @@ -56,6 +57,10 @@ while (( $# > 0 )); do cache_only=true shift ;; + --print-rows) + print_rows=true + shift + ;; --help|-h) usage exit 0 @@ -328,6 +333,13 @@ if [[ $cache_only == true || $prepare_only == true ]]; then exit 0 fi +# The shell keeps a copy of these rows so its picker can open without waiting +# on this script, and reads them back from stdout to refresh that copy. +if [[ $print_rows == true ]]; then + printf '%s\n' "$rows" + exit 0 +fi + # Image rows can contain newlines and tabs, which don't survive positional # shell IPC arguments. Base64-encode for transit; the ImagePicker plugin # Qt.atob()s on the other side. diff --git a/bin/omarchy-menu-keybindings b/bin/omarchy-menu-keybindings index 767b5dac9813..153a4d29432c 100755 --- a/bin/omarchy-menu-keybindings +++ b/bin/omarchy-menu-keybindings @@ -210,6 +210,9 @@ hl = setmetatable({ elseif type(bind_dispatcher) == "string" and bind_dispatcher ~= "" then kind = "exec" arg = bind_dispatcher + elseif o and o.bind_commands and o.bind_commands[bind_dispatcher] then + kind = "exec" + arg = o.bind_commands[bind_dispatcher] end print(table.concat({ tostring(modmask), opts.description, key, kind, arg }, "\t")) @@ -530,7 +533,7 @@ output_binding_records_uncached() { keybindings_cache_key() { { - printf 'v13\n' + printf 'v14\n' hyprctl devices 2>/dev/null | grep -F 'active keymap:' hyprctl binds 2>/dev/null } | sha256sum | awk '{ print $1 }' diff --git a/bin/omarchy-network-qr b/bin/omarchy-network-qr index 9502c25c29db..fb1c669603fa 100755 --- a/bin/omarchy-network-qr +++ b/bin/omarchy-network-qr @@ -22,7 +22,9 @@ if [[ -z $interface ]]; then # menu's visibility gate describe. Fall back to the first connected Wi-Fi # device. nmcli localizes state names, so pin the locale, and the prefix # match accepts states like "connected (externally)". - route_device=$(ip route get 1.1.1.1 2>/dev/null | awk '{ for (i = 1; i <= NF; i++) if ($i == "dev") { print $(i + 1); exit } }') + if ! route_device=$(ip route get 1.1.1.1 2>/dev/null | awk '{ for (i = 1; i <= NF; i++) if ($i == "dev") { print $(i + 1); exit } }'); then + route_device="" + fi if [[ -n $route_device && -d /sys/class/net/$route_device/wireless ]]; then interface=$route_device else diff --git a/bin/omarchy-pkg-add b/bin/omarchy-pkg-add index 977d7efdbc98..1f5e40913d33 100755 --- a/bin/omarchy-pkg-add +++ b/bin/omarchy-pkg-add @@ -7,15 +7,15 @@ if omarchy-pkg-missing "$@"; then if (( EUID == 0 )); then - pacman -S --noconfirm --needed "$@" || exit 1 + pacman -S --noconfirm --needed -- "$@" || exit 1 else - sudo pacman -S --noconfirm --needed "$@" || exit 1 + sudo pacman -S --noconfirm --needed -- "$@" || exit 1 fi fi for pkg in "$@"; do # Secondary check to handle states where pacman doesn't actually register an error - if ! pacman -Q "$pkg" &>/dev/null; then + if ! pacman -Q -- "$pkg" &>/dev/null; then echo -e "\033[31mError: Package '$pkg' did not install\033[0m" >&2 exit 1 fi diff --git a/bin/omarchy-pkg-aur-add b/bin/omarchy-pkg-aur-add index 7a152be7fe8a..64ad097c6202 100755 --- a/bin/omarchy-pkg-aur-add +++ b/bin/omarchy-pkg-aur-add @@ -4,12 +4,12 @@ # omarchy:args= if omarchy-pkg-missing "$@"; then - yay -S --noconfirm --needed "$@" || exit 1 + yay -S --noconfirm --needed -- "$@" || exit 1 fi for pkg in "$@"; do # Secondary check to handle states where pacman doesn't actually register an error - if ! pacman -Q "$pkg" &>/dev/null; then + if ! pacman -Q -- "$pkg" &>/dev/null; then echo -e "\033[31mError: Package '$pkg' did not install\033[0m" >&2 exit 1 fi diff --git a/bin/omarchy-pkg-aur-install b/bin/omarchy-pkg-aur-install index 3d38b4db75b6..dc393b8dc304 100755 --- a/bin/omarchy-pkg-aur-install +++ b/bin/omarchy-pkg-aur-install @@ -24,6 +24,7 @@ if [[ -n $pkg_names ]]; then source omarchy-sudo-keepalive echo "$pkg_names" | sed 's/^/aur\//' | tr '\n' ' ' | xargs yay -S --noconfirm + code=$? sudo updatedb --prune-bind-mounts=no --add-prunepaths=/.snapshots - omarchy-show-done + omarchy-show-done $code fi diff --git a/bin/omarchy-pkg-drop b/bin/omarchy-pkg-drop index bfb70598fb84..7b173c8de9d3 100755 --- a/bin/omarchy-pkg-drop +++ b/bin/omarchy-pkg-drop @@ -8,9 +8,16 @@ installed=() declare -A installed_exact=() declare -A selected=() +if ! installed_packages=$(pacman -Qq); then + echo "Unable to query installed packages; no packages were removed." >&2 + exit 1 +fi + while IFS= read -r package_name; do - installed_exact[$package_name]=1 -done < <(pacman -Qq) + if [[ -n $package_name ]]; then + installed_exact[$package_name]=1 + fi +done <<< "$installed_packages" for pkg in "$@"; do if [[ -n ${installed_exact[$pkg]} && -z ${selected[$pkg]} ]]; then diff --git a/bin/omarchy-pkg-install b/bin/omarchy-pkg-install index 15e5e288ef17..e5e0fb429f8f 100755 --- a/bin/omarchy-pkg-install +++ b/bin/omarchy-pkg-install @@ -22,5 +22,5 @@ if [[ -n $pkg_names ]]; then # Convert newline-separated selections to space-separated for pacman echo "$pkg_names" | tr '\n' ' ' | xargs sudo pacman -S --noconfirm - omarchy-show-done + omarchy-show-done $? fi diff --git a/bin/omarchy-pkg-missing b/bin/omarchy-pkg-missing index c4059dff83ca..b282d2f33683 100755 --- a/bin/omarchy-pkg-missing +++ b/bin/omarchy-pkg-missing @@ -4,7 +4,7 @@ # omarchy:args= for pkg in "$@"; do - if ! pacman -Q "$pkg" &>/dev/null; then + if ! pacman -Q -- "$pkg" &>/dev/null; then exit 0 fi done diff --git a/bin/omarchy-pkg-present b/bin/omarchy-pkg-present index 8c4340d65f3d..0a0645bda167 100755 --- a/bin/omarchy-pkg-present +++ b/bin/omarchy-pkg-present @@ -4,7 +4,7 @@ # omarchy:args= for pkg in "$@"; do - pacman -Q "$pkg" &>/dev/null || exit 1 + pacman -Q -- "$pkg" &>/dev/null || exit 1 done exit 0 diff --git a/bin/omarchy-pkg-remove b/bin/omarchy-pkg-remove index 486d37721234..37ca448e9b59 100755 --- a/bin/omarchy-pkg-remove +++ b/bin/omarchy-pkg-remove @@ -20,5 +20,5 @@ pkg_names=$(yay -Qqe | fzf "${fzf_args[@]}") if [[ -n $pkg_names ]]; then # Convert newline-separated selections to space-separated for yay echo "$pkg_names" | tr '\n' ' ' | xargs sudo pacman -Rns --noconfirm - omarchy-show-done + omarchy-show-done $? fi diff --git a/bin/omarchy-refresh-pacman b/bin/omarchy-refresh-pacman index 299d6c20d20d..7406e6ad9db3 100755 --- a/bin/omarchy-refresh-pacman +++ b/bin/omarchy-refresh-pacman @@ -1,26 +1,50 @@ -#!/bin/bash +#!/bin/bash -p # omarchy:summary=Overwrite the package configuration for /etc/pacman with the Omarchy default of using its dedicated mirrors and repositories, then update all packages. # omarchy:requires-sudo=true -sudo cp -f /etc/pacman.conf /etc/pacman.conf.bak -sudo cp -f /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.bak +if [[ $- != *p* ]]; then + echo "Refusing an unsafe Bash startup." >&2 + exit 126 +fi -channel="${1:-stable}" +security_entrypoint=$(/usr/bin/readlink -e -- "${BASH_SOURCE[0]}") || exit 126 +source "${security_entrypoint%/*}/omarchy-security-functions" || exit 126 +omarchy_security_require_privileged_bash_startup || exit 126 +set -e +omarchy_security_sanitize_bash_environment "$0" "$@" +omarchy_security_require_source_root "$0" +# Channel switching calls this behind its own sanitized PATH and hands the +# caller's original path over the same way the updater receives it. +user_path=${OMARCHY_UPDATE_USER_PATH:-$PATH} +unset OMARCHY_UPDATE_USER_PATH +# Traps first, so a signal or failure during the entry revocation still +# exits through the cleanup path. +omarchy_security_install_sudo_cleanup_traps +omarchy_security_revoke_sudo_timestamp || exit 1 +omarchy_security_enable_no_update_sudo +channel="${1:-stable}" if [[ $channel != "stable" && $channel != "rc" && $channel != "edge" ]]; then - echo "Error: Invalid channel '$channel'. Must be one of: stable, rc, edge" - exit 1 + echo "Invalid channel: $channel" >&2 + exit 2 fi +sudo cp -f /etc/pacman.conf /etc/pacman.conf.bak +sudo cp -f /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.bak echo "Setting channel to $channel" -echo - sudo cp -f "$OMARCHY_PATH/default/pacman/pacman-$channel.conf" /etc/pacman.conf sudo cp -f "$OMARCHY_PATH/default/pacman/mirrorlist-$channel" /etc/pacman.d/mirrorlist -# Allow user customization of /etc/pacman.conf before the upgrade runs -omarchy-hook pre-refresh-pacman +# Allow user customization of /etc/pacman.conf before the upgrade runs, so +# custom repositories and IgnorePkg entries shape the downgrade-capable +# transaction below. The hook is user code: it runs cold behind the no-update +# wrapper, and the timestamp is revoked again afterwards so any authorization +# the hook obtained for itself cannot carry into the transaction. +omarchy_security_revoke_sudo_timestamp +PATH="$OMARCHY_PATH/default/omarchy/sudo-no-update:$user_path" \ + "$OMARCHY_PATH/bin/omarchy-hook" pre-refresh-pacman +omarchy_security_revoke_sudo_timestamp # Reset all package DBs and then update -sudo env OMARCHY_UPDATE_PACMAN=1 pacman -Syyuu --noconfirm +omarchy-update-pacman -Syyuu --noconfirm diff --git a/bin/omarchy-reinstall-pkgs b/bin/omarchy-reinstall-pkgs index c1d51cbf3ca6..97aff9c6a561 100755 --- a/bin/omarchy-reinstall-pkgs +++ b/bin/omarchy-reinstall-pkgs @@ -11,8 +11,8 @@ set -e omarchy-refresh-pacman # Downgrade any packages to the stable setup -sudo env OMARCHY_UPDATE_PACMAN=1 pacman -Suu --noconfirm +omarchy-update-pacman -Suu --noconfirm # Ensure all packages are installed mapfile -t packages < <(grep -v '^#' "$OMARCHY_PATH/install/omarchy-base.packages" | grep -v '^$') -sudo env OMARCHY_UPDATE_PACMAN=1 pacman -Syu --noconfirm --needed "${packages[@]}" +omarchy-update-pacman -Syu --noconfirm --needed "${packages[@]}" diff --git a/bin/omarchy-remove-ai-hermes b/bin/omarchy-remove-ai-hermes index da8af34cdc57..d2101ff96001 100755 --- a/bin/omarchy-remove-ai-hermes +++ b/bin/omarchy-remove-ai-hermes @@ -6,73 +6,173 @@ # -u so an unset HOME is an error rather than a set of rm -rf paths rooted at /. set -euo pipefail -ensure_hermes_stopped() { - python3 - "$HOME" <<'PY' +unit_dir="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user" + +# Only systemd's own word counts as "stopped": a non-zero exit from is-active +# also covers an unreachable user manager, which says nothing about whether +# the process is alive. +unit_stopped() { + local state + state=$(systemctl --user is-active "$1" 2>/dev/null) || true + [[ $state == "inactive" || $state == "failed" ]] +} + +# Hermes is closed here rather than asked to be: the agent in its terminal, +# the desktop app and its helpers, a gateway run by hand -- every process +# whose program, by its executable or by what it was started as, lives in the +# runtime about to be deleted or in the package; for an interpreter that is +# the script it runs, or Hermes's own package named with -m, so a gateway +# started by hand as `python .../hermes` or `python -m hermes_cli.main` is +# found too. Judged by the program alone, never by a later argument: an +# editor opened on a file in the runtime is the user's. `check` refuses first if anything else has Hermes's files open, by +# its executable, its working directory or a descriptor, that editor or a +# shell sitting in ~/.hermes, so a refusal touches nothing; that +# one is the user's to close, because removing an open SQLite WAL leaves a +# live writer on a deleted generation. `stop` then ends Hermes's own and +# refuses again over whatever is left. +hermes_holders() { + python3 - "$1" "$HOME" <<'PY' import os -from pathlib import Path +import re +import signal import sys +import time +from pathlib import Path -home = Path(sys.argv[1]) +mode, home = sys.argv[1], Path(sys.argv[2]) roots = [str((home / relative).resolve()) for relative in ('.hermes', '.config/Hermes')] roots.append('/opt/hermes-desktop') +runtime = [str((home / relative).resolve()) for relative in ('.hermes/hermes-agent', '.hermes/node', '.hermes/bin')] +runtime.append('/opt/hermes-desktop') -def belongs_to_hermes(target): +def under(target, directories): target = target.removesuffix(' (deleted)') - return any(target == root or target.startswith(root + '/') for root in roots) - -holders = [] -for process in Path('/proc').iterdir(): - if not process.name.isdigit() or int(process.name) == os.getpid(): - continue - try: - if process.stat().st_uid != os.getuid(): + return any(target == directory or target.startswith(directory + '/') for directory in directories) + +def processes(): + found = [] + for process in Path('/proc').iterdir(): + if not process.name.isdigit() or int(process.name) == os.getpid(): continue - targets = [os.fsdecode(arg) for arg in (process / 'cmdline').read_bytes().split(b'\0')] - entries = [process / 'exe', process / 'cwd'] try: - entries.extend((process / 'fd').iterdir()) - except PermissionError: - pass - for entry in entries: + if process.stat().st_uid != os.getuid(): + continue + argv = [os.fsdecode(arg) for arg in (process / 'cmdline').read_bytes().split(b'\0')] + program = [] try: - targets.append(os.readlink(entry)) + program.append(os.readlink(process / 'exe')) except OSError: pass - if any(belongs_to_hermes(target) for target in targets): - holders.append(process.name) - except (FileNotFoundError, ProcessLookupError, PermissionError): - continue - -if holders: - print('Close Hermes and processes using its files before removing it (PIDs: ' - + ', '.join(holders) + '). Then try again.', file=sys.stderr) + touched = list(program) + try: + touched.append(os.readlink(process / 'cwd')) + except OSError: + pass + try: + for entry in (process / 'fd').iterdir(): + try: + touched.append(os.readlink(entry)) + except OSError: + pass + except PermissionError: + pass + started_as = argv[:1] + interpreter = bool(started_as) and re.fullmatch(r'(python[0-9.]*|node|bash|sh)', os.path.basename(started_as[0])) + if interpreter: + started_as = argv[:2] + # Hermes's own package, run as a module from an activated venv. + ours = any(under(target, runtime) for target in started_as + program) or \ + (bool(interpreter) and argv[1:3] and argv[1] == '-m' and argv[2].startswith('hermes_cli')) + if ours or any(under(target, roots) for target in touched): + try: + name = (process / 'comm').read_text().strip() + except OSError: + name = '?' + found.append((int(process.name), ours, name)) + except (FileNotFoundError, ProcessLookupError, PermissionError): + continue + return found + +def named(entries): + return ', '.join(f'{pid} {name}' for pid, ours, name in entries) + +def refuse(entries): + print('Something other than Hermes still has its files open (PIDs: ' + named(entries) + + '). Close it, then run the removal again.', file=sys.stderr) sys.exit(1) + +strangers = [entry for entry in processes() if not entry[1]] +if strangers: + refuse(strangers) +if mode == 'check': + sys.exit(0) + +mine = [entry for entry in processes() if entry[1]] +if mine: + print('Stopping Hermes (PIDs: ' + named(mine) + ')...') + for signum, patience in ((signal.SIGTERM, 10), (signal.SIGKILL, 3)): + for pid, ours, name in mine: + try: + os.kill(pid, signum) + except ProcessLookupError: + pass + deadline = time.monotonic() + patience + while mine and time.monotonic() < deadline: + time.sleep(0.2) + mine = [entry for entry in processes() if entry[1]] + if not mine: + break + if mine: + print('Hermes did not stop (PIDs: ' + named(mine) + '). Close it, then run the removal again.', file=sys.stderr) + sys.exit(1) +left = processes() +if left: + refuse(left) PY } -# Removing an open SQLite WAL leaves a live writer on a deleted generation. -ensure_hermes_stopped -omarchy-pkg-drop hermes-desktop +hermes_holders check + +# The gateway unit that upstream's `hermes gateway install` writes starts the +# runtime about to be deleted, so it goes with it, and it is stopped before +# the processes are, or systemd would start the gateway again the moment it +# was killed. Judged by what the unit starts, as the processes are: a unit +# whose ExecStart runs this runtime is its own whatever home it serves, and +# one that runs a Hermes kept elsewhere is somebody else's arrangement even +# when its home sits under ~/.hermes. A unit that will not stop aborts the +# removal: dropping the package would strand a live gateway on deleted code +# with no way to restart it cleanly. +for unit_file in "$unit_dir"/hermes-gateway*.service; do + [[ -f $unit_file ]] || continue + grep '^ExecStart=' "$unit_file" | grep -qF "$HOME/.hermes/hermes-agent/" || continue + unit=${unit_file##*/} + if systemctl --user disable --now "$unit" 2>/dev/null || unit_stopped "$unit"; then + # .bak is what `gateway install --force` leaves behind when it rewrites a + # unit, so it goes with the unit. + rm -f "$unit_file" "$unit_file.bak" "$unit_dir/default.target.wants/$unit" + systemctl --user daemon-reload 2>/dev/null || true + # A unit that had been failing stays listed as "not-found failed" after + # its file is gone until its failed state is reset. + systemctl --user reset-failed "$unit" 2>/dev/null || true + else + echo "Could not stop $unit; Hermes was not removed." >&2 + exit 1 + fi +done -# The installer leaves a unit waiting to hand the app the Omarchy theme. +# The installer leaves a unit waiting to hand the app the Omarchy theme; it +# runs Hermes itself to do so, so it is stopped before the sweep reaches it. systemctl --user stop omarchy-hermes-theme.service 2>/dev/null || true -# The mise CLI is the app's predecessor, not the app itself: Hermes Desktop takes -# it over on install and runs its own runtime instead, so a copy still here is one -# the app never superseded -- an interrupted install, or the terminal CLI from -# before the app existed. Remove Hermes clears that too, scoped by the installer -# to what Omarchy owns so a hermes the user set up themselves is left alone. -# Tolerated here rather than fatal, so the ~/.hermes handling below still runs; -# the failure is answered for at the end instead of being swallowed. -cli_removed=true -ensure_hermes_stopped -omarchy-install-hermes-cli --remove || cli_removed=false - -# The app writes this when the runtime it provisions under ~/.hermes has landed, -# and it is the only thing that tells that runtime apart from one the user -# installed themselves -- the paths are the same either way. Without it the app -# never got that far: a machine where it was installed but never launched still -# has whatever was there before, and none of it is ours to delete unasked. +hermes_holders stop +omarchy-pkg-drop hermes-desktop + +# Upstream's installer writes this when the runtime under ~/.hermes has landed, +# whether Omarchy ran it for the app or the app's own first launch did, and it +# is the only thing that tells that runtime apart from one the user installed +# themselves -- the paths are the same either way. Without it the install never +# got that far: a machine where the package landed but nothing set Hermes up +# still has whatever was there before, and none of it is ours to delete unasked. if [[ -f $HOME/.hermes/hermes-agent/.hermes-bootstrap-complete ]]; then # The checkout and venv, its own uv, its own node. None of it is any use once # the app is gone, so it goes without asking; what the user made with the app @@ -120,12 +220,12 @@ fi # never owned, a yes takes that with it, and saying so is the prompt's job. # Without a terminal to ask in, keeping everything is the answer. data_removed=false -if [[ -d $HOME/.hermes || -d $HOME/.config/Hermes ]] && [[ -t 0 ]] && omarchy-cmd-present gum; then +if [[ -d $HOME/.hermes || -d $HOME/.config/Hermes ]] && [[ -t 0 ]]; then # du answers non-zero when either directory is missing, and pipefail would # turn that into an aborted removal; the size is worth no such thing. size=$(du -shc "$HOME/.hermes" "$HOME/.config/Hermes" 2>/dev/null | tail -1 | cut -f1 || true) if gum confirm --default=false "Also delete ~/.hermes and ~/.config/Hermes ($size: chats, memories, skills, connections and tokens)?"; then - ensure_hermes_stopped + hermes_holders stop rm -rf "$HOME/.hermes" "$HOME/.config/Hermes" data_removed=true fi @@ -139,9 +239,3 @@ elif [[ -d $HOME/.hermes || -d $HOME/.config/Hermes ]]; then echo "Your chats, memories, and skills are still in ~/.hermes," echo "and your connections and settings in ~/.config/Hermes." fi - -# The messages above still hold -- the app and its runtime are gone -- but a CLI -# teardown that failed already said so on stderr, and that stands. -if [[ $cli_removed == "false" ]]; then - exit 1 -fi diff --git a/bin/omarchy-remove-ai-openclaw b/bin/omarchy-remove-ai-openclaw index e610cbbe02ca..a5b15a23edbf 100755 --- a/bin/omarchy-remove-ai-openclaw +++ b/bin/omarchy-remove-ai-openclaw @@ -61,7 +61,7 @@ gtk-update-icon-cache "$HOME/.local/share/icons/hicolor" &>/dev/null || true # front of the user with the size rather than left silent. Without a terminal # to ask in, keeping it is the answer. state_removed=false -if [[ -d $HOME/.openclaw && -t 0 ]] && omarchy-cmd-present gum; then +if [[ -d $HOME/.openclaw && -t 0 ]]; then size=$(du -sh "$HOME/.openclaw" 2>/dev/null | cut -f1) if gum confirm --default=false "Also delete ~/.openclaw ($size: chats, memories, credentials, and downloaded plugins)?"; then rm -rf "$HOME/.openclaw" diff --git a/bin/omarchy-remove-dev-env b/bin/omarchy-remove-dev-env index a24e7f9e2946..0d8f584bbfa4 100755 --- a/bin/omarchy-remove-dev-env +++ b/bin/omarchy-remove-dev-env @@ -9,7 +9,41 @@ if [[ -z $1 ]]; then exit 1 fi +cleanup_ocaml_sudo_credentials() { + local status=$? + trap - EXIT HUP INT TERM + + if ! /usr/bin/sudo -k >/dev/null 2>&1; then + echo "Failed to invalidate sudo credentials after OCaml removal." >&2 + (( status != 0 )) || status=1 + fi + + exit "$status" +} + +begin_ocaml_sudo_boundary() { + trap cleanup_ocaml_sudo_credentials EXIT + trap 'exit 129' HUP + trap 'exit 130' INT + trap 'exit 143' TERM + + /usr/bin/sudo -k >/dev/null || { + echo "Unable to start OCaml removal with a cold sudo credential state." >&2 + exit 1 + } + + if ! /usr/bin/sudo -N -V >/dev/null 2>&1; then + echo "This sudo does not support --no-update; refusing to remove OCaml." >&2 + exit 1 + fi +} + remove_php() { + mise uninstall php --all + mise rm -g php + mise tool-alias unset php + + # PHP from before it moved to mise omarchy-pkg-drop php composer php-sqlite xdebug } @@ -46,7 +80,9 @@ php) ;; laravel) echo -e "Removing Laravel...\n" - composer global remove laravel/installer 2>/dev/null || true + mise x php -- composer global remove laravel/installer 2>/dev/null || true + + rm -f "$HOME/.local/bin/laravel" "$HOME/.config/composer/vendor/bin/laravel" ;; symfony) echo -e "Removing Symfony CLI...\n" @@ -87,10 +123,15 @@ dotnet) mise rm -g dotnet ;; ocaml) + begin_ocaml_sudo_boundary + echo -e "Removing OCaml...\n" opam switch remove default -y 2>/dev/null || true rm -rf ~/.opam 2>/dev/null || true - sudo rm -f /usr/local/bin/opam 2>/dev/null || true + if ! /usr/bin/sudo -N -- /usr/bin/rm -f /usr/local/bin/opam; then + echo "Failed to remove the system opam launcher." >&2 + exit 1 + fi ;; clojure) echo -e "Removing Clojure...\n" diff --git a/bin/omarchy-remove-gaming-retroarch b/bin/omarchy-remove-gaming-retroarch index 2eb2037b18e0..05c8fe89ce77 100755 --- a/bin/omarchy-remove-gaming-retroarch +++ b/bin/omarchy-remove-gaming-retroarch @@ -25,6 +25,7 @@ omarchy-pkg-drop \ libretro-vice-x128-git libretro-vice-x64-git libretro-vice-x64dtv-git libretro-vice-x64sc-git \ libretro-vice-xcbm2-git libretro-vice-xcbm5x0-git libretro-vice-xpet-git \ libretro-vice-xplus4-git libretro-vice-xscpu64-git libretro-vice-xvic-git \ + libretro-database-git \ retroarch-joypad-autoconfig-git rm -rf \ @@ -35,3 +36,4 @@ rm -rf \ echo "" echo "RetroArch and its cores have been removed." echo "ROMs and BIOS files at ~/Games/roms and ~/Games/bios were left in place." + diff --git a/bin/omarchy-remove-preinstalls b/bin/omarchy-remove-preinstalls index bfb8fe34ec26..1efba06ed994 100755 --- a/bin/omarchy-remove-preinstalls +++ b/bin/omarchy-remove-preinstalls @@ -30,14 +30,6 @@ if gum confirm "Are you sure you want to remove all preinstalled web apps, TUI w rm -f ~/.local/bin/muse fi - # Only the wrapper omarchy-install-hermes-cli wrote is a preinstall. Hermes - # Desktop's command, an official install, or anything else at that path is - # the user's, so it is the installer that decides whether the wrapper is its - # own, rather than a copy of its marker kept here. - if omarchy-install-hermes-cli --owns; then - rm -f ~/.local/bin/hermes - fi - omarchy-pkg-drop \ aether \ cliamp \ @@ -50,6 +42,8 @@ if gum confirm "Are you sure you want to remove all preinstalled web apps, TUI w moonlight-qt \ lazydocker \ omacut \ + monologue \ omacalc \ - omawrite + omawrite \ + hype fi diff --git a/bin/omarchy-remove-security-fingerprint b/bin/omarchy-remove-security-fingerprint index 01295892c2a7..fc53c109652c 100755 --- a/bin/omarchy-remove-security-fingerprint +++ b/bin/omarchy-remove-security-fingerprint @@ -5,6 +5,22 @@ set -e +# Resolve the invoking account before changing authentication or packages. +if (( EUID == 0 )) && [[ -v SUDO_UID ]]; then + if [[ ! $SUDO_UID =~ ^[0-9]+$ ]]; then + echo "Cannot identify the invoking fingerprint user" >&2 + exit 1 + fi + fingerprint_user=$(/usr/bin/id -nu "+$SUDO_UID") || exit 1 +else + fingerprint_user=$(/usr/bin/id -un) || exit 1 +fi + +if [[ -z $fingerprint_user || $fingerprint_user == "." || $fingerprint_user == ".." || $fingerprint_user == */* ]]; then + echo "Unsafe fingerprint user name" >&2 + exit 1 +fi + remove_pam_config() { # Remove from sudo (both the fingerprint module and its clamshell gate) @@ -33,7 +49,9 @@ echo -e "\e[32mRemoving fingerprint scanner from authentication.\n\e[0m" remove_pam_config remove_lock_fingerprint_pam +sudo rm -rf -- "/var/lib/fprint/$fingerprint_user" + echo "Removing fingerprint packages..." omarchy-pkg-drop fprintd libfprint libfprint-git -echo -e "\e[32mFingerprint authentication has been completely removed.\e[0m" +echo -e "\e[32mFingerprint authentication and $fingerprint_user's local saved fingerprints have been removed.\e[0m" diff --git a/bin/omarchy-remove-security-sshd b/bin/omarchy-remove-security-sshd index 3106c89e919b..4bfcc8b09396 100755 --- a/bin/omarchy-remove-security-sshd +++ b/bin/omarchy-remove-security-sshd @@ -1,6 +1,6 @@ #!/bin/bash -# omarchy:summary=Disable the OpenSSH server, close the firewall port, and optionally remove authorized keys +# omarchy:summary=Disable the OpenSSH server, remove standard firewall rules, and optionally remove authorized keys # omarchy:requires-sudo=true set -e @@ -13,9 +13,15 @@ echo "Stopping and disabling the OpenSSH server..." sudo systemctl disable --now sshd.service 2>/dev/null || true if omarchy-cmd-present ufw; then - echo "Closing the SSH port in the firewall..." - sudo ufw --force delete limit 22/tcp >/dev/null 2>&1 || true + echo "Removing standard SSH firewall rules..." + sudo ufw --force delete limit 22/tcp >/dev/null + sudo ufw --force delete allow 22/tcp >/dev/null + sudo ufw --force delete allow ssh >/dev/null + sudo ufw --force delete limit ssh >/dev/null + sudo ufw --force delete allow to any app SSH >/dev/null + sudo ufw --force delete limit to any app SSH >/dev/null sudo ufw reload >/dev/null + echo "Standard SSH firewall rules removed. Review custom firewall rules separately." fi if [[ -s $AUTHORIZED_KEYS ]]; then @@ -28,5 +34,5 @@ if [[ -s $AUTHORIZED_KEYS ]]; then fi fi -echo -e "\e[32m\nThe SSH server has been disabled and its firewall port closed.\e[0m" +echo -e "\e[32m\nThe SSH server has been disabled.\e[0m" echo "The openssh package remains installed since it also provides the ssh client." diff --git a/bin/omarchy-remove-service-ssh-agent b/bin/omarchy-remove-service-ssh-agent new file mode 100755 index 000000000000..9201ebf47f46 --- /dev/null +++ b/bin/omarchy-remove-service-ssh-agent @@ -0,0 +1,16 @@ +#!/bin/bash + +# omarchy:summary=Disable the gcr-ssh-agent SSH agent and its environment override. + +# The file goes before disable reloads the manager, or the environment generator keeps exporting it. +rm -f "$HOME/.config/environment.d/90-gcr-ssh-agent.conf" +systemctl --user disable --now gcr-ssh-agent.socket 2>/dev/null || true +systemctl --user stop gcr-ssh-agent.service 2>/dev/null || true + +# The socket exported SSH_AUTH_SOCK to the user manager, which outlives the agent. +if systemctl --user show-environment | grep -Fqx "SSH_AUTH_SOCK=$XDG_RUNTIME_DIR/gcr/ssh"; then + systemctl --user unset-environment SSH_AUTH_SOCK +fi + +echo "" +echo "SSH agent has been disabled. Log out and back in for it to take full effect." diff --git a/bin/omarchy-restart-app b/bin/omarchy-restart-app index d250650dbd12..e7d7ce5d6d51 100755 --- a/bin/omarchy-restart-app +++ b/bin/omarchy-restart-app @@ -3,5 +3,5 @@ # omarchy:summary=Restart an application by killing it and relaunching via uwsm. # omarchy:args= [application-args...] -pkill -x $1 +pkill -x -- "$1" setsid uwsm-app -- "$@" >/dev/null 2>&1 & diff --git a/bin/omarchy-restart-shell b/bin/omarchy-restart-shell index dfc21724620f..8d3d6ce94aef 100755 --- a/bin/omarchy-restart-shell +++ b/bin/omarchy-restart-shell @@ -61,6 +61,21 @@ relock_session() { return 1 } +# A short timeout keeps an unresponsive user bus from stalling the restart; +# busctl would otherwise wait 25 seconds per probe. +notifications_ready() { + [[ $(busctl --user --timeout=1s call org.freedesktop.DBus /org/freedesktop/DBus \ + org.freedesktop.DBus NameHasOwner s org.freedesktop.Notifications 2>/dev/null) == "b true" ]] +} + +# Core IPC can answer before the notification plugin has registered its bus +# name. Restore an existing notification service before update hooks or setup +# invitations send their one-time toasts; a disabled service need not appear. +notifications_were_running=0 +if notifications_ready; then + notifications_were_running=1 +fi + # Each kill stops the oldest matching instance and only returns once it has # fully exited, so the no-duplicate launch below can't race a dying shell. while timeout 5 quickshell kill -p "$CONFIG_DIR" --any-display >/dev/null 2>&1; do :; done @@ -69,25 +84,50 @@ while timeout 5 quickshell kill -p "$CONFIG_DIR" --any-display >/dev/null 2>&1; # not transient variables from a terminal, SSH connection, or development tool. hyprctl dispatch 'hl.dsp.exec_cmd("omarchy-launch-shell")' >/dev/null +shell_ready=0 for (( attempt = 0; attempt < 20; attempt++ )); do if OMARCHY_PATH="$session_omarchy_path" OMARCHY_SHELL_IPC_TIMEOUT=0.5s omarchy-shell shell ping >/dev/null 2>&1; then - # The session stays compositor-locked after the old lock client died, so - # re-acquire the lock and let the user authenticate out of it. - if (( relock )) && ! relock_session; then - echo "Omarchy shell restarted, but the session lock was not re-secured." >&2 - exit 1 - fi - # Invitation toasts (like Voxtype/fingerprint setup) die with the old - # shell, and their notify-send waiters hang forever: the dying server - # never emits NotificationClosed. A still-running omarchy-*-invitation - # unit is therefore an unanswered invitation — re-run it so its toast - # reappears on the new shell. Answered invitations have already exited - # and been collected, so the glob no longer matches them. - systemctl --user try-restart 'omarchy-*-invitation.service' 2>/dev/null || true - exit 0 + shell_ready=1 + break fi sleep 0.1 done +if (( shell_ready == 0 )); then + echo "Omarchy shell did not become ready after restart." >&2 + exit 1 +fi + +# The session stays compositor-locked after the old lock client died, so +# re-acquire the lock and let the user authenticate out of it. This comes +# first and depends on nothing else: a user stranded behind the failsafe must +# not wait on the notification plugin, which may be slow or absent. +if (( relock )) && ! relock_session; then + echo "Omarchy shell restarted, but the session lock was not re-secured." >&2 + exit 1 +fi + +# Core IPC answers before the notification plugin has registered its bus +# name, so wait for it separately before one-time toasts are sent. +if (( notifications_were_running )); then + notifications_restored=0 + for (( attempt = 0; attempt < 20; attempt++ )); do + if notifications_ready; then + notifications_restored=1 + break + fi + sleep 0.1 + done + if (( notifications_restored == 0 )); then + echo "Omarchy shell restarted, but its notification service did not become ready." >&2 + exit 1 + fi +fi -echo "Omarchy shell did not become ready after restart." >&2 -exit 1 +# Invitation toasts (like Voxtype/fingerprint setup) die with the old +# shell, and their notify-send waiters hang forever: the dying server +# never emits NotificationClosed. A still-running omarchy-*-invitation +# unit is therefore an unanswered invitation — re-run it so its toast +# reappears on the new shell. Answered invitations have already exited +# and been collected, so the glob no longer matches them. +systemctl --user try-restart 'omarchy-*-invitation.service' 2>/dev/null || true +exit 0 diff --git a/bin/omarchy-security-functions b/bin/omarchy-security-functions new file mode 100755 index 000000000000..890d4430d805 --- /dev/null +++ b/bin/omarchy-security-functions @@ -0,0 +1,137 @@ +#!/bin/bash + +# omarchy:hidden=true +# omarchy:summary=Provide internal helpers for command-scoped sudo authentication + +if [[ ${BASH_SOURCE[0]} == "$0" ]]; then + echo "omarchy-security-functions is an internal function library." >&2 + exit 64 +fi + +omarchy_security_require_privileged_bash_startup() { + [[ $- == *p* ]] || return 1 + /usr/bin/env -i /usr/bin/bash -p -c ' + mapfile -d "" -t argv <"/proc/$1/cmdline" || exit 1 + executable=$(/usr/bin/readlink -e -- "/proc/$1/exe") || exit 1 + [[ $executable == "/usr/bin/bash" && + ( ${argv[0]:-} == "/bin/bash" || ${argv[0]:-} == "/usr/bin/bash" ) && + ${argv[1]:-} == "-p" ]] + ' omarchy-bash-startup "$$" +} + +omarchy_security_sanitize_bash_environment() { + local script=$1 + shift + local entry name environment_fd environment_pid + local -a unsets=() + + # Read the raw environment: privileged Bash ignores exported functions, but + # leaves their records for ordinary child interpreters to import later. + exec {environment_fd}< <(/usr/bin/env -0) + environment_pid=$! + while IFS= read -r -d '' entry <&"$environment_fd"; do + name=${entry%%=*} + case "$name" in + BASH_ENV|ENV|SHELLOPTS|BASHOPTS|PS4|CDPATH|GLOBIGNORE|BASH_FUNC_*%%) + unsets+=(-u "$name") + ;; + esac + done + exec {environment_fd}<&- + wait "$environment_pid" || return 1 + if (( ${#unsets[@]} > 0 )); then + exec /usr/bin/env "${unsets[@]}" /usr/bin/bash -p -- "$script" "$@" + fi +} + +omarchy_security_require_source_root() { + local command_source command_name=${1##*/} + command_source=$(/usr/bin/readlink -e -- "$1") || return 1 + + # A runtime root selects the code used by this invocation. Accept the + # canonical checkout containing the entrypoint or the package's bin links. + if [[ ${OMARCHY_PATH:-} != /* || $(/usr/bin/realpath -e -- "$OMARCHY_PATH") != "$OMARCHY_PATH" ]] || + ! { [[ $command_source == "$OMARCHY_PATH/bin/$command_name" ]] || + [[ $OMARCHY_PATH == "/usr/share/omarchy" && $command_source == "/usr/bin/$command_name" ]]; }; then + echo "OMARCHY_PATH does not match this Omarchy command." >&2 + return 1 + fi +} + +omarchy_security_sudo_supports_no_update() { + local help + help=$(LC_ALL=C /usr/bin/sudo -h 2>&1) || return 1 + /usr/bin/grep -Eq '^usage: sudo .*\[[^]]*N[^]]*\]' <<< "$help" +} + +omarchy_security_revoke_sudo_timestamp() { + /usr/bin/sudo -k +} + +omarchy_security_exit_with_revoked_sudo() { + local status=$1 + local message=${2:-Could not invalidate cached sudo authorization.} + + trap - EXIT HUP INT TERM + if ! omarchy_security_revoke_sudo_timestamp; then + echo "$message" >&2 + (( status != 0 )) || status=1 + fi + exit "$status" +} + +omarchy_security_install_signal_exit_traps() { + trap 'exit 129' HUP + trap 'exit 130' INT + trap 'exit 143' TERM +} + +omarchy_security_install_sudo_cleanup_traps() { + OMARCHY_SECURITY_SUDO_CLEANUP_MESSAGE=${1:-Could not invalidate cached sudo authorization.} + trap omarchy_security_run_sudo_cleanup_trap EXIT + omarchy_security_install_signal_exit_traps +} + +omarchy_security_enable_no_update_sudo() { + local wrapper_dir="$OMARCHY_PATH/default/omarchy/sudo-no-update" + if ! omarchy_security_sudo_supports_no_update; then + echo "This sudo does not support --no-update; refusing mixed-trust work." >&2 + return 1 + fi + if [[ ! -f $wrapper_dir/sudo || ! -x $wrapper_dir/sudo ]]; then + echo "The command-scoped sudo wrapper is missing." >&2 + return 1 + fi + PATH="$wrapper_dir:$OMARCHY_PATH/bin:/usr/bin:/usr/sbin:/bin:/sbin" + OMARCHY_SUDO_NO_UPDATE=1 + export PATH OMARCHY_SUDO_NO_UPDATE +} + +omarchy_security_run_sudo_cleanup_trap() { + local status=$? + + omarchy_security_exit_with_revoked_sudo "$status" \ + "${OMARCHY_SECURITY_SUDO_CLEANUP_MESSAGE:-Could not invalidate cached sudo authorization.}" +} + +omarchy_security_assert_root_directory() { + local path=$1 expected_mode=$2 canonical owner actual_mode + + [[ $path == /* && -d $path && ! -L $path ]] || return 1 + canonical=$(/usr/bin/realpath -e -- "$path") || return 1 + [[ $canonical == "$path" ]] || return 1 + read -r owner actual_mode < <(/usr/bin/stat -Lc '%u %a' -- "$path") || return 1 + [[ $owner == "0" && $actual_mode == "$expected_mode" ]] +} + +omarchy_security_prepare_private_root_directory() { + local path=$1 parent=$2 + + omarchy_security_assert_root_directory "$parent" 755 || return 1 + if [[ -e $path || -L $path ]]; then + omarchy_security_assert_root_directory "$path" 700 + else + /usr/bin/install -d -o root -g root -m 0700 -- "$path" || return 1 + omarchy_security_assert_root_directory "$path" 700 + fi +} diff --git a/bin/omarchy-setup-security-fingerprint b/bin/omarchy-setup-security-fingerprint index e46aaed9ba32..a57dea4a1269 100755 --- a/bin/omarchy-setup-security-fingerprint +++ b/bin/omarchy-setup-security-fingerprint @@ -80,7 +80,7 @@ fi # one transaction, so a failed install leaves the existing driver in place. if omarchy-pkg-missing libfprint-git fprintd usbutils; then echo "Installing required packages..." - sudo pacman -S --needed --noconfirm --ask 4 libfprint-git fprintd usbutils + sudo pacman -S --needed --noconfirm --ask 4 -- libfprint-git fprintd usbutils fi # Enroll first fingerprint diff --git a/bin/omarchy-setup-security-ssh-agent b/bin/omarchy-setup-security-ssh-agent new file mode 100755 index 000000000000..0c646f72765e --- /dev/null +++ b/bin/omarchy-setup-security-ssh-agent @@ -0,0 +1,17 @@ +#!/bin/bash + +# omarchy:summary=Enable an SSH agent (gcr-ssh-agent) that prompts for key passphrases graphically. + +set -e + +ENV_FILE="$HOME/.config/environment.d/90-gcr-ssh-agent.conf" + +systemctl --user enable --now gcr-ssh-agent.socket + +mkdir -p "$(dirname "$ENV_FILE")" +echo 'SSH_AUTH_SOCK=$XDG_RUNTIME_DIR/gcr/ssh' >"$ENV_FILE" + +echo "" +echo "SSH agent has been enabled. Log out and back in to make it available everywhere." +echo "The first use of a passphrase-protected key opens a dialog, with the option to" +echo "remember the passphrase in the keyring." diff --git a/bin/omarchy-shell b/bin/omarchy-shell index ac8b3108d17b..8494c4072821 100755 --- a/bin/omarchy-shell +++ b/bin/omarchy-shell @@ -52,6 +52,50 @@ if [[ $1 == "shell" && ( $2 == "summon" || $2 == "toggle" ) ]] && (( $# == 3 )); set -- "$1" "$2" "$3" "{}" fi +# The shell answers on its own socket first: socat starts in ~5ms where a qs +# ipc client takes ~45ms. Fields are split by unit separators and the request +# ends with a record separator, so an argument holding either goes through qs +# ipc instead. The shell replies "OK" with the output once the call has run, +# or "SKIP" when it ran nothing (no such target or function, the wrong number +# of arguments), and qs ipc then gives its exact answer. A timeout after the +# request is out is reported, not retried: the call may already have run. +# Like qs ipc, the socket belongs to one shell, the one running this config on +# this display, and the shell derives its name from the same two values. +socket_id=$(printf '%s\n%s' "$OMARCHY_PATH/shell" "${WAYLAND_DISPLAY:-}" | md5sum) +socket="${XDG_RUNTIME_DIR:-/run/user/$UID}/omarchy-shell-${socket_id:0:16}.sock" +request="$*" +if [[ -S $socket && $request != *$'\x1e'* && $request != *$'\x1f'* ]]; then + saved_ifs=$IFS + IFS=$'\x1f' + request="$*" + IFS=$saved_ifs + # socat waits as long as the shell takes; the timeout alone bounds the call. + # Its own errors land in the reply too, so a connection it could not make + # is told apart from one that failed after the request went out. + reply=$(printf '%s\x1e' "$request" | timeout --kill-after=1s "${OMARCHY_SHELL_IPC_TIMEOUT:-2s}" socat -t 86400 - "UNIX-CONNECT:$socket" 2>&1) + + # An answer counts only once its record separator arrived: a reply cut off + # partway must not pass for the whole of it. + if [[ $reply == OK$'\x1f'*$'\x1e'* ]]; then + output=${reply#OK$'\x1f'} + output=${output%$'\x1e'*} + # Match qs ipc's path, whose $(...) drops trailing newlines. + while [[ $output == *$'\n' ]]; do output=${output%$'\n'}; done + if (( !QUIET )) && [[ -n $output ]]; then + echo "$output" + fi + exit 0 + elif [[ $reply == "SKIP"$'\x1e'* ]]; then + : # The shell ran nothing; qs ipc gives its exact answer below. + elif [[ $reply != OK* && $reply == *" E connect("* ]]; then + : # socat never connected, a stale socket; qs ipc answers below. + else + # Out of time, cut off, or failed after the request went out: the call + # may have run, so it is reported rather than retried. + fail "omarchy-shell is not responding" + fi +fi + # The -- keeps function names that shadow qs subcommands (e.g. show) as # positionals. qs reports connection failures with a nonzero exit, but IPC-level # failures (unknown target/function, bad arguments) go to stdout with exit 0. diff --git a/bin/omarchy-show-done b/bin/omarchy-show-done index d5d8ccdee892..14c9f156a0bb 100755 --- a/bin/omarchy-show-done +++ b/bin/omarchy-show-done @@ -1,6 +1,9 @@ #!/bin/bash -# omarchy:summary=Display a "Done!" message and wait for user to press any key. +# omarchy:summary=Display a "Done!" or "Failed!" message and wait for user to press any key. +# omarchy:args=[exit-code] + +code="${1:-0}" # The device node is there whether or not a terminal is behind it, so opening # it is the only test that means anything. @@ -13,6 +16,10 @@ while read -rsn 1 -t 0.1 _ /dev/tty +if (( code == 0 )); then + printf '\n\033[32m● \033[0mDone! Press any key to close...' >/dev/tty +else + printf '\n\033[31m● \033[0mFailed (exit code %d)! Press any key to close...' "$code" >/dev/tty +fi read -rsn 1 /dev/tty diff --git a/bin/omarchy-state b/bin/omarchy-state index 4fda5b3a63ab..3b2f5e17e40f 100755 --- a/bin/omarchy-state +++ b/bin/omarchy-state @@ -21,6 +21,19 @@ if [[ -z $STATE_NAME ]]; then fi case "$COMMAND" in -set) touch "$STATE_DIR/$STATE_NAME" ;; +set) + # State names are fixed labels (reboot-required, restart-*-required). The + # name becomes a filename under the state directory. A slash would turn it + # into directory levels, and a bare `.` or `..` would touch the directory + # itself or its parent. Refuse those. Dots inside a name (a..b) are fine; + # once slashes are out, only the whole name being `.` or `..` can leave the + # directory. clear needs no such guard: find -name matches basenames only, + # so a pattern can never walk out of the directory. + if [[ $STATE_NAME == */* || $STATE_NAME == "." || $STATE_NAME == ".." ]]; then + echo "Invalid state name: $STATE_NAME" >&2 + exit 2 + fi + touch "$STATE_DIR/$STATE_NAME" + ;; clear) find "$STATE_DIR" -maxdepth 1 -type f -name "$STATE_NAME" -delete ;; esac diff --git a/bin/omarchy-sudo-passwordless b/bin/omarchy-sudo-passwordless index 719d881bfe71..b5f88a941104 100755 --- a/bin/omarchy-sudo-passwordless +++ b/bin/omarchy-sudo-passwordless @@ -1,70 +1,448 @@ -#!/bin/bash +#!/bin/bash -p # omarchy:summary=Toggle passwordless sudo for the current user. # omarchy:args=[MINUTES] # omarchy:requires-sudo=true -NOPASSWD_FILE="/etc/sudoers.d/99-omarchy-nopasswd-${USER}" -TIMER_NAME="omarchy-nopasswd-expire-${USER}" +if [[ $- != *p* && ${BASH_SOURCE[0]} == "$0" ]]; then + echo "Refusing an unsafe Bash startup for passwordless sudo." >&2 + exit 126 +fi + +security_entrypoint=$(/usr/bin/readlink -e -- "${BASH_SOURCE[0]}") || exit 126 +source "${security_entrypoint%/*}/omarchy-security-functions" || exit 126 + +if [[ ${BASH_SOURCE[0]} == "$0" ]]; then + omarchy_security_require_privileged_bash_startup || { + echo "Refusing an unsafe Bash startup for passwordless sudo." >&2 + exit 126 + } + omarchy_security_sanitize_bash_environment "$0" "$@" || exit 126 +fi + +set -euo pipefail -MINUTES=${1:-15} -if [[ $1 && ! $1 =~ ^[0-9]+$ ]]; then +readonly DEFAULT_MINUTES=15 +readonly MAX_MINUTES=1440 +readonly LOCK_FILE=/run/lock/omarchy-sudo-passwordless.lock +readonly BOOT_CLEANUP_FILE=/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf +readonly PACKAGE_HOOK=/usr/share/libalpm/hooks/05-omarchy-passwordless-revoke.hook +readonly REMOVAL_BLOCKER=/run/omarchy-sudo-passwordless-package-removing +readonly MIGRATION_MARKER=/var/lib/omarchy/migrations/1788163635 +readonly QUARANTINE_DIR=/var/lib/omarchy/sudoers-quarantine +readonly INSTALLED_SELF=/usr/bin/omarchy-sudo-passwordless +readonly STATUS_INACTIVE=3 + +usage() { echo "Usage: omarchy-sudo-passwordless [MINUTES]" >&2 + echo "MINUTES must be between 1 and $MAX_MINUTES." >&2 exit 1 -fi +} + +valid_minutes() { + [[ $1 =~ ^0*[1-9][0-9]{0,3}$ ]] && ((10#$1 <= MAX_MINUTES)) +} + +valid_uid() { + [[ $1 =~ ^0*[1-9][0-9]{0,9}$ ]] && ((10#$1 <= 4294967294)) +} + +valid_account_name() { + [[ $1 =~ ^[a-z_][a-z0-9_-]{0,31}\$?$ ]] && (( ${#1} <= 32 )) +} + +resolve_account() { + local uid="$1" entry + valid_uid "$uid" || return 1 + entry=$(/usr/bin/getent passwd "$((10#$uid))") || return 1 + IFS=: read -r ACCOUNT_NAME _ ACCOUNT_UID _ _ _ _ <<<"$entry" + [[ $ACCOUNT_UID == "$((10#$uid))" ]] || return 1 + # Sudoers has metacharacters, and it reads an upper-case word such as ALICE + # as an alias reference rather than a user. Accounts use this portable + # lower-case subset; refusing anything else is safer than attempting to + # quote privileged policy syntax. + valid_account_name "$ACCOUNT_NAME" || return 1 + ACCOUNT_UID=$((10#$uid)) +} + +verify_sudo_caller() { + local requested_uid="$1" + ((EUID == 0)) || return 1 + valid_uid "$requested_uid" || return 1 + [[ ${SUDO_UID:-} =~ ^[0-9]+$ ]] || return 1 + ((10#$SUDO_UID == 10#$requested_uid)) || return 1 + resolve_account "$requested_uid" +} + +with_root_lock() { + local fd rc=0 + # The boot cleanup cannot depend on STATE_DIR or RUNTIME_DIR being healthy: + # those are exactly the kinds of partial-install state it must fail closed + # through. /run/lock is established by the OS before sysinit services run. + omarchy_security_assert_root_directory /run 755 || return 1 + [[ -d /run/lock && ! -L /run/lock ]] || return 1 + [[ $(/usr/bin/stat -Lc '%u' /run/lock) == 0 ]] || return 1 + ! ((8#$(/usr/bin/stat -Lc '%a' /run/lock) & 022)) || return 1 + exec {fd}>"$LOCK_FILE" || return 1 + /usr/bin/chown root:root "$LOCK_FILE" || return 1 + /usr/bin/chmod 0600 "$LOCK_FILE" || return 1 + # Grant operations are short. A stalled holder must not hang a caller + # indefinitely, least of all pacman's pre-transaction hook. + /usr/bin/flock -x -w 60 "$fd" || return 1 + "$@" || rc=$? + /usr/bin/flock -u "$fd" || rc=1 + exec {fd}>&- + return "$rc" +} -arm_expiry() { - if sudo systemd-run --on-active=${MINUTES}m --timer-property=AccuracySec=1s --unit="$TIMER_NAME" \ - rm -f -- "$NOPASSWD_FILE"; then +rule_file() { + printf '/etc/sudoers.d/99-omarchy-nopasswd-%s' "$1" +} + +# The sudoers rule is the only grant record. A missing file is distinct from +# an unreadable, unsafe, or administrator-modified file. +read_grant() { + local file contents + file=$(rule_file "$1") + [[ -e $file || -L $file ]] || return "$STATUS_INACTIVE" + verify_root_path "$file" && [[ -f $file ]] || return 2 + contents=$(/usr/bin/cat -- "$file") || return 2 + [[ $contents =~ ^([a-z_][a-z0-9_-]*\$?)\ ALL=\(ALL\)\ NOTAFTER=([0-9]{14}Z)\ NOPASSWD:\ ALL$ ]] || return 2 + GRANT_NAME=${BASH_REMATCH[1]} + GRANT_DEADLINE=${BASH_REMATCH[2]} + valid_account_name "$GRANT_NAME" || return 2 +} + +# Returns 0 for a rule this command generated, 1 for anything else under the +# owned prefix (preserved as administrator policy), and 2 when unreadable. +classify_generated_rule() { + local file=$1 suffix contents name + + [[ -f $file && ! -L $file ]] || return 1 + contents=$(/usr/bin/cat -- "$file") || return 2 + suffix=${file##*/99-omarchy-nopasswd-} + + # The legacy command wrote the caller's unvalidated name into both the + # filename and the rule. That exact relationship is its fingerprint, so an + # account the current policy would reject still has its old grant removed. + if [[ $contents == "$suffix ALL=(ALL) NOPASSWD: ALL" ]]; then return 0 fi - echo "Failed to schedule passwordless sudo expiry. Revoking access now." >&2 - if ! sudo rm -f -- "$NOPASSWD_FILE"; then - echo "CRITICAL: Could not remove $NOPASSWD_FILE. Remove it as root immediately." >&2 + [[ $suffix =~ ^[0-9]+$ ]] || return 1 + name=${contents%' ALL=(ALL) NOPASSWD: ALL'} + if valid_account_name "$name" && [[ $contents == "$name ALL=(ALL) NOPASSWD: ALL" ]]; then + return 0 fi - return 1 + name=${contents%%' ALL=(ALL) NOTAFTER='*} + valid_account_name "$name" && [[ $contents =~ ^[a-z_][a-z0-9_-]*\$?\ ALL=\(ALL\)\ NOTAFTER=[0-9]{14}Z\ NOPASSWD:\ ALL$ ]] } -echo "Toggle passwordless sudo..." +cleanup_uid_locked() { + local file + file=$(rule_file "$1") + [[ -e $file || -L $file ]] || return 0 + verify_root_path "$file" && classify_generated_rule "$file" || return 1 + /usr/bin/rm -f -- "$file" && [[ ! -e $file && ! -L $file ]] +} -# Safety: if the file exists but the timer doesn't (e.g. after reboot), clean up -if sudo test -f "$NOPASSWD_FILE" && ! systemctl is-active "${TIMER_NAME}.timer" &>/dev/null; then - sudo rm "$NOPASSWD_FILE" -fi +# The generated prefix is reserved: boot cleanup and the package hook already +# remove everything in it, and the legacy writer could produce a rule whose +# body differs from its filename. Nothing unrecognized may stay live there, but +# its content is kept for the administrator instead of being deleted. +quarantine_foreign_rule() { + local file=$1 target + if [[ ! -e /var/lib/omarchy && ! -L /var/lib/omarchy ]]; then + /usr/bin/install -d -o root -g root -m 0755 -- /var/lib/omarchy || return 1 + fi + omarchy_security_prepare_private_root_directory "$QUARANTINE_DIR" /var/lib/omarchy || return 1 + # A legacy filename can already be close to NAME_MAX, so the destination + # name is fixed and the original name travels beside it. + target=$(/usr/bin/mktemp -d "$QUARANTINE_DIR/XXXXXXXXXX") || return 1 + /usr/bin/printf '%s\n' "${file##*/}" >"$target/name" || return 1 + /usr/bin/mv -fT -- "$file" "$target/policy" && [[ ! -e $file && ! -L $file ]] || return 1 + echo "Moved unrecognized sudoers policy $file to $target/policy" >&2 +} + +cleanup_all_locked() { + local file classification failed=0 + verify_root_path /etc/sudoers.d || return 1 + for file in /etc/sudoers.d/99-omarchy-nopasswd-*; do + [[ -e $file || -L $file ]] || continue + if classify_generated_rule "$file"; then + if ! /usr/bin/rm -f -- "$file" || [[ -e $file || -L $file ]]; then + failed=1 + fi + else + classification=$? + if (( classification != 1 )) || ! quarantine_foreign_rule "$file"; then + failed=1 + fi + fi + done + return "$failed" +} + +verify_root_path() { + local file=$1 owner mode canonical current + [[ ( -f $file || -d $file ) && ! -L $file ]] || return 1 + canonical=$(/usr/bin/realpath -e -- "$file") || return 1 + [[ $canonical == "$file" ]] || return 1 + owner=$(/usr/bin/stat -Lc '%u' -- "$file") || return 1 + mode=$(/usr/bin/stat -Lc '%a' -- "$file") || return 1 + [[ $owner == 0 && $mode =~ ^[0-7]+$ ]] && ! ((8#$mode & 022)) || return 1 -# Check for the file directly — sudo -n can stay cached or be granted by other rules -if sudo test -f "$NOPASSWD_FILE"; then - if [[ $1 ]]; then - sudo systemctl stop "${TIMER_NAME}.timer" 2>/dev/null - arm_expiry || exit 1 - echo "Passwordless sudo timer updated. It will now automatically disable in ${MINUTES} minutes." + current=${file%/*} + while :; do + [[ -d $current && ! -L $current ]] || return 1 + canonical=$(/usr/bin/realpath -e -- "$current") || return 1 + [[ $canonical == "$current" ]] || return 1 + read -r owner mode < <(/usr/bin/stat -Lc '%u %a' -- "$current") || return 1 + [[ $owner == 0 && $mode =~ ^[0-7]+$ ]] && ! ((8#$mode & 022)) || return 1 + [[ $current == / ]] && break + current=${current%/*} + [[ -n $current ]] || current=/ + done +} + +verify_boot_cleanup() { + local active_rules hook + [[ ! -e $REMOVAL_BLOCKER && ! -L $REMOVAL_BLOCKER ]] || return 1 + verify_root_path "$BOOT_CLEANUP_FILE" || return 1 + active_rules=$(/usr/bin/awk '!/^[[:space:]]*(#|$)/ { print }' "$BOOT_CLEANUP_FILE") || return 1 + [[ $active_rules == 'r! /etc/sudoers.d/99-omarchy-nopasswd-*' ]] || return 1 + verify_root_path "$PACKAGE_HOOK" || return 1 + hook=$(/usr/bin/cat -- "$PACKAGE_HOOK") || return 1 + [[ $hook == '[Trigger] +Operation = Upgrade +Operation = Remove +Type = Package +Target = omarchy-settings +Target = omarchy-settings-dev + +[Action] +Description = Revoking temporary Omarchy sudo grants before settings changes... +When = PreTransaction +Exec = /usr/bin/omarchy-sudo-passwordless __package-removing +AbortOnFail' ]] +} + +package_removing_locked() { + # ALPM must abort before removing the helper or boot cleanup if revocation + # fails. The marker also blocks publication after this lock is released. + (umask 077; : >"$REMOVAL_BLOCKER") || return 1 + /usr/bin/rm -f -- /etc/sudoers.d/99-omarchy-nopasswd-* || return 1 + cleanup_all_locked +} + +migration_complete() { + [[ -f $MIGRATION_MARKER && ! -s $MIGRATION_MARKER ]] && verify_root_path "$MIGRATION_MARKER" +} + +migrate_locked() { + local directory + if migration_complete; then + return 0 + fi + [[ ! -e $MIGRATION_MARKER && ! -L $MIGRATION_MARKER ]] || return 1 + verify_root_path /var/lib || return 1 + for directory in /var/lib/omarchy /var/lib/omarchy/migrations; do + if [[ ! -e $directory && ! -L $directory ]]; then + /usr/bin/install -d -o root -g root -m 0755 -- "$directory" || return 1 + fi + verify_root_path "$directory" || return 1 + done + cleanup_all_locked || return 1 + # The empty marker is written only after cleanup succeeds, under the same + # machine lock. Later accounts need no sudo and cannot revoke newer grants. + /usr/bin/install -o root -g root -m 0644 /dev/null "$MIGRATION_MARKER" +} + +# Old callbacks only remove an expired current rule. Renewing a grant never +# needs a second state file or a stored timer generation to identify it. +expire_locked() { + local status now + if read_grant "$1"; then + now=$(/usr/bin/date -u +%Y%m%d%H%M%SZ) || return 2 + [[ $now < $GRANT_DEADLINE ]] && return 0 + cleanup_uid_locked "$1" + else + status=$? + if (( status == STATUS_INACTIVE )); then + return 0 + else + cleanup_uid_locked "$1" + fi + fi +} + +status_locked() { + local status now + resolve_account "$1" || return 2 + if read_grant "$1"; then + [[ $GRANT_NAME == "$ACCOUNT_NAME" ]] || return 2 + now=$(/usr/bin/date -u +%Y%m%d%H%M%SZ) || return 2 + if [[ $now < $GRANT_DEADLINE ]]; then + return 0 + fi + cleanup_uid_locked "$1" || return 2 + return "$STATUS_INACTIVE" + else + status=$? + return "$status" + fi +} + +finish_enable() { + local status=$? + trap - EXIT HUP INT TERM + if (( status != 0 )); then + if cleanup_uid_locked "$uid"; then + [[ -z $timer ]] || /usr/bin/systemctl stop "$timer.timer" "$timer.service" >/dev/null 2>&1 || true + else + echo "Could not revoke passwordless sudo; expiry remains armed. Administrator cleanup is required." >&2 + fi + fi + [[ -z $pending ]] || /usr/bin/rm -f -- "$pending" + exit "$status" +} + +enable_locked() ( + local uid=$1 minutes=$2 now expires deadline token timer="" pending="" file status + resolve_account "$uid" && valid_minutes "$minutes" || return 1 + verify_boot_cleanup && verify_root_path /etc/sudoers.d || return 1 + file=$(rule_file "$uid") + if read_grant "$uid"; then + [[ $GRANT_NAME == "$ACCOUNT_NAME" ]] || return 1 else - sudo rm "$NOPASSWD_FILE" - sudo systemctl stop "${TIMER_NAME}.timer" 2>/dev/null + status=$? + (( status == STATUS_INACTIVE )) || return 1 + fi + trap finish_enable EXIT + omarchy_security_install_signal_exit_traps + now=$(/usr/bin/date +%s) || return 1 + expires=$((now + 10#$minutes * 60)) + deadline=$(/usr/bin/date -u -d "@$expires" +%Y%m%d%H%M%SZ) || return 1 + pending=$(/usr/bin/mktemp /etc/sudoers.d/.omarchy-nopasswd.XXXXXX) || return 1 + /usr/bin/printf '%s ALL=(ALL) NOTAFTER=%s NOPASSWD: ALL\n' "$ACCOUNT_NAME" "$deadline" >"$pending" || return 1 + /usr/bin/chown root:root "$pending" && /usr/bin/chmod 0440 "$pending" || return 1 + /usr/sbin/visudo -cf "$pending" >/dev/null || return 1 + token=$(/usr/bin/tr -d '-' &2 + exit 1 +} + +omarchy_security_sudo_supports_no_update || { + echo "This sudo does not support --no-update; refusing the passwordless-sudo workflow." >&2 + exit 1 +} + +omarchy_security_install_sudo_cleanup_traps +/usr/bin/sudo -k >/dev/null 2>&1 || { + echo "Could not start from a cold sudo credential state." >&2 + exit 1 +} + +echo "Toggle passwordless sudo..." +if /usr/bin/sudo -N -- "$INSTALLED_SELF" __status "$uid"; then + if (($# == 0)); then + /usr/bin/sudo -N -- "$INSTALLED_SELF" __disable "$uid" echo "Passwordless sudo has been DISABLED. Sudo will require a password again." + else + /usr/bin/sudo -N -- "$INSTALLED_SELF" __enable "$uid" "$minutes" + echo "Passwordless sudo expiry updated. It will automatically disable in ${minutes} minutes." fi else + status=$? + if (( status != STATUS_INACTIVE )); then + echo "Could not safely inspect passwordless sudo; no grant will be enabled. Resolve the reported authorization or cleanup error first." >&2 + exit 1 + fi echo "" echo "⚠️ WARNING: This will allow ANY process running as your user to" - echo "execute ANY command as root WITHOUT a password for ${MINUTES} minutes." + echo "execute ANY command as root WITHOUT a password for ${minutes} minutes." echo "" echo "This is useful for AI agents that need to run sudo commands," echo "but it significantly weakens the security of your system." echo "Anyone or anything with access to your user account gets full root." echo "" - echo "Passwordless sudo will automatically disable after ${MINUTES} minutes." + echo "Passwordless sudo will automatically disable after ${minutes} minutes," + echo "including if the machine reboots before the deadline." echo "Run this command again to disable it early." echo "" - if gum confirm "Enable passwordless sudo for ${MINUTES} minutes? This is a significant security risk!"; then - echo "${USER} ALL=(ALL) NOPASSWD: ALL" | sudo tee "$NOPASSWD_FILE" > /dev/null - sudo chmod 440 "$NOPASSWD_FILE" - arm_expiry || exit 1 - + if /usr/bin/gum confirm "Enable passwordless sudo for ${minutes} minutes? This is a significant security risk!"; then + /usr/bin/sudo -N -- "$INSTALLED_SELF" __enable "$uid" "$minutes" echo "" - echo "Passwordless sudo has been ENABLED. It will automatically disable in ${MINUTES} minutes." - echo "A restart removes the passwordless sudo rule as well." + echo "Passwordless sudo has been ENABLED. It will automatically disable in ${minutes} minutes." else echo "Aborted. No changes made." fi diff --git a/bin/omarchy-system-factory-reset b/bin/omarchy-system-factory-reset index 51eca40110a1..43348e5a4d0a 100755 --- a/bin/omarchy-system-factory-reset +++ b/bin/omarchy-system-factory-reset @@ -297,19 +297,34 @@ rebuild_next_boot() { umount "$next$esp_mount" } +# Both the staged system and the retained baseline must lose the old hashes. +scrub_factory_accounts() { + local root="$1" user users + + users=$(awk -F: '$3 >= 1000 && $3 < 60000 { print $1 }' "$root/etc/passwd") || return 1 + for user in $users; do + userdel --root "$root" "$user" 2>>"$LOG_FILE" || return 1 + rm -rf "${root:?}/home/$user" || return 1 + done + + # passwd --lock preserves the hash. Replace it, then remove the backups + # that userdel and usermod leave behind. + usermod --root "$root" --password '!' root >>"$LOG_FILE" 2>&1 || return 1 + rm -f "$root/etc/"{shadow-,gshadow-,passwd-,group-,subuid-,subgid-} +} + # Remove the seller's account material and machine identity from the retained # @factory baseline so it can neither be mounted for recovery nor restore the # seller's account on a future reset. Idempotent (a scrubbed baseline has no # uid>=1000 accounts left to remove). sanitize_factory_baseline() { - local factory="$1" user + local factory="$1" btrfs property set -ts "$factory" ro false - for user in $(awk -F: '$3 >= 1000 && $3 < 60000 { print $1 }' "$factory/etc/passwd"); do - userdel --root "$factory" "$user" 2>>"$LOG_FILE" || true - rm -rf "${factory:?}/home/$user" - done - passwd --root "$factory" --lock root >>"$LOG_FILE" 2>&1 || true + if ! scrub_factory_accounts "$factory"; then + btrfs property set -ts "$factory" ro true + fail "could not remove account credentials from the factory baseline (see $LOG_FILE)" + fi rm -f "$factory"/etc/ssh/ssh_host_* rm -f "$factory"/etc/NetworkManager/system-connections/* rm -rf "$factory"/var/lib/NetworkManager/* "$factory/var/lib/tailscale" "$factory/var/lib/iwd" @@ -337,17 +352,13 @@ stage_full_reset() { rm -rf "$next"/var/lib/NetworkManager/* "$next/var/lib/tailscale" "$next/var/lib/iwd" rm -f "$next/var/lib/sddm/state.conf" "$next/etc/sddm.conf.d/autologin.conf" - # A factory snapshot from a normal (normal) install contains the original + # A factory snapshot from a normal install contains the original # user account; first-boot setup must start from none. A leftover account # would keep its password hash and group memberships (including wheel), so # failure here has to abort the reset, not be shrugged off. - local user - for user in $(awk -F: '$3 >= 1000 && $3 < 60000 { print $1 }' "$next/etc/passwd"); do - log "Removing user $user from the factory system" - userdel --root "$next" "$user" 2>>"$LOG_FILE" || - fail "could not remove user $user from the factory system (see $LOG_FILE)" - done - passwd --root "$next" --lock root >>"$LOG_FILE" 2>&1 || true + log "Removing account credentials from the factory system" + scrub_factory_accounts "$next" || + fail "could not remove account credentials from the factory system (see $LOG_FILE)" # @factory itself survives the wipe as the baseline for future resets. If it # came from a normal install it still holds the seller's account and diff --git a/bin/omarchy-theme-set b/bin/omarchy-theme-set index 782b4ba70547..10faf8729880 100755 --- a/bin/omarchy-theme-set +++ b/bin/omarchy-theme-set @@ -10,8 +10,10 @@ if [[ -z $1 ]]; then fi CURRENT_THEME_PATH="$HOME/.local/state/omarchy/current/theme" +CURRENT_THEME_NAME_PATH="$HOME/.local/state/omarchy/current/theme.name" NEXT_THEME_PATH="$HOME/.local/state/omarchy/current/next-theme" CURRENT_BACKGROUND_LINK="$HOME/.local/state/omarchy/current/background" +THEME_BACKGROUND_STATE_PATH="$HOME/.local/state/omarchy/theme-backgrounds" BACKGROUND_TRANSITION_CACHE="$HOME/.cache/omarchy/background-transitions" THEME_SET_LOCK="${XDG_RUNTIME_DIR:-/tmp}/omarchy-theme-set.lock" USER_THEMES_PATH="$HOME/.config/omarchy/themes" @@ -74,6 +76,24 @@ snapshot_current_background() { snapshot_background_path "$current_background" "previous" } +theme_background_state_file() { + local theme="$1" + + [[ -n $theme && ${theme##*/} == $theme && $theme != "." && $theme != ".." ]] || return 1 + printf '%s/%s\n' "$THEME_BACKGROUND_STATE_PATH" "$theme" +} + +remember_current_theme_background() { + local current_background state_file + + state_file=$(theme_background_state_file "$PREVIOUS_THEME_NAME") || return + current_background=$(readlink -f "$CURRENT_BACKGROUND_LINK" 2>/dev/null || true) + [[ -f $current_background ]] || return + + mkdir -p "$THEME_BACKGROUND_STATE_PATH" + printf '%s\n' "$current_background" >"$state_file" +} + background_transition_uses_snapshots() { local next_background="$1" local current_background @@ -86,7 +106,7 @@ choose_theme_background() { local theme_path="${1:-$CURRENT_THEME_PATH}" local current_theme_backgrounds="$CURRENT_THEME_PATH/backgrounds" local backgrounds=() - local current_background index next_index i + local current_background remembered_background state_file index next_index i CHOSEN_THEME_BACKGROUND="" mapfile -d '' -t backgrounds < <( @@ -98,31 +118,47 @@ choose_theme_background() { (( ${#backgrounds[@]} > 0 )) || return 1 - current_background=$(readlink "$CURRENT_BACKGROUND_LINK" 2>/dev/null || true) - if [[ $theme_path != $CURRENT_THEME_PATH && ${current_background%/*} == $current_theme_backgrounds ]]; then - current_background="$theme_path/backgrounds/${current_background##*/}" - fi + if [[ $PREVIOUS_THEME_NAME == "$THEME_NAME" ]]; then + current_background=$(readlink "$CURRENT_BACKGROUND_LINK" 2>/dev/null || true) + if [[ $theme_path != $CURRENT_THEME_PATH && ${current_background%/*} == $current_theme_backgrounds ]]; then + current_background="$theme_path/backgrounds/${current_background##*/}" + fi - index=-1 - for i in "${!backgrounds[@]}"; do - if [[ ${backgrounds[$i]} == $current_background ]]; then - index=$i - break + index=-1 + for i in "${!backgrounds[@]}"; do + if [[ ${backgrounds[$i]} == $current_background ]]; then + index=$i + break + fi + done + + if (( index != -1 )); then + next_index=$(((index + 1) % ${#backgrounds[@]})) + CHOSEN_THEME_BACKGROUND="${backgrounds[$next_index]}" + else + CHOSEN_THEME_BACKGROUND="${backgrounds[0]}" fi - done + return + fi - if (( index == -1 )); then - CHOSEN_THEME_BACKGROUND="${backgrounds[0]}" - else - next_index=$(((index + 1) % ${#backgrounds[@]})) - CHOSEN_THEME_BACKGROUND="${backgrounds[$next_index]}" + state_file=$(theme_background_state_file "$THEME_NAME" 2>/dev/null || true) + remembered_background=$(cat "$state_file" 2>/dev/null || true) + if [[ $theme_path != $CURRENT_THEME_PATH && ${remembered_background%/*} == $current_theme_backgrounds ]]; then + remembered_background="$theme_path/backgrounds/${remembered_background##*/}" fi + if [[ -f $remembered_background ]]; then + CHOSEN_THEME_BACKGROUND="$remembered_background" + return + fi + + CHOSEN_THEME_BACKGROUND="${backgrounds[0]}" } choose_staged_theme_background() { local next_theme_backgrounds="$NEXT_THEME_PATH/backgrounds" choose_theme_background "$NEXT_THEME_PATH" || return 1 + STAGED_THEME_BACKGROUND="$CHOSEN_THEME_BACKGROUND" if [[ ${CHOSEN_THEME_BACKGROUND%/*} == $next_theme_backgrounds ]]; then CHOSEN_THEME_BACKGROUND="$CURRENT_THEME_PATH/backgrounds/${CHOSEN_THEME_BACKGROUND##*/}" @@ -147,8 +183,13 @@ set_theme_background() { new_background="$CHOSEN_THEME_BACKGROUND" new_background_snapshot="" - if [[ $BACKGROUND_TRANSITION_SNAPSHOTS == "true" ]]; then - new_background_snapshot=$(snapshot_background_path "$new_background" "next") + if [[ -n $PREPARED_BACKGROUND_SNAPSHOT && $PREPARED_BACKGROUND == "$new_background" ]]; then + new_background_snapshot="$PREPARED_BACKGROUND_SNAPSHOT" + else + [[ -z $PREPARED_BACKGROUND_SNAPSHOT ]] || rm -f "$PREPARED_BACKGROUND_SNAPSHOT" + if [[ $BACKGROUND_TRANSITION_SNAPSHOTS == "true" ]]; then + new_background_snapshot=$(snapshot_background_path "$new_background" "next") + fi fi if [[ -f $OLD_BACKGROUND_SNAPSHOT && -f $new_background_snapshot ]]; then @@ -296,6 +337,9 @@ fi exec 9>"$THEME_SET_LOCK" flock 9 +PREVIOUS_THEME_NAME=$(cat "$CURRENT_THEME_NAME_PATH" 2>/dev/null || true) +remember_current_theme_background + # Setup clean next theme directory (for atomic theme config swapping) rm -rf "$NEXT_THEME_PATH" mkdir -p "$NEXT_THEME_PATH" @@ -315,11 +359,11 @@ if [[ ! -f $NEXT_THEME_PATH/colors.toml && -f $NEXT_THEME_PATH/alacritty.toml ]] omarchy-theme-colors-from-alacritty "$NEXT_THEME_PATH" fi -# Generate dynamic configs -omarchy-theme-set-templates - CHOSEN_THEME_BACKGROUND="" +STAGED_THEME_BACKGROUND="" OLD_BACKGROUND_SNAPSHOT="" +PREPARED_BACKGROUND="" +PREPARED_BACKGROUND_SNAPSHOT="" BACKGROUND_TRANSITION_SNAPSHOTS=true if [[ $THEME_HEADLESS != "1" && $OMARCHY_THEME_SKIP_BACKGROUND != "1" ]]; then # Resolve the staged choice while the old theme still exists. Video changes @@ -327,18 +371,30 @@ if [[ $THEME_HEADLESS != "1" && $OMARCHY_THEME_SKIP_BACKGROUND != "1" ]]; then if choose_staged_theme_background; then if background_transition_uses_snapshots "$CHOSEN_THEME_BACKGROUND"; then OLD_BACKGROUND_SNAPSHOT=$(snapshot_current_background) + + # Hand the shell the next background now, so it decodes while the + # templates render and the theme swaps in. The staged file is the same + # inode the swap moves into place, so its snapshot is the final image. + PREPARED_BACKGROUND="$CHOSEN_THEME_BACKGROUND" + PREPARED_BACKGROUND_SNAPSHOT=$(snapshot_background_path "$STAGED_THEME_BACKGROUND" "next") + if [[ -n $PREPARED_BACKGROUND_SNAPSHOT ]]; then + shell_ipc background prepare "$PREPARED_BACKGROUND_SNAPSHOT" 9>&- & + fi else BACKGROUND_TRANSITION_SNAPSHOTS=false fi fi fi +# Generate dynamic configs +omarchy-theme-set-templates + # Swap next theme in as current rm -rf "$CURRENT_THEME_PATH" mv "$NEXT_THEME_PATH" "$CURRENT_THEME_PATH" # Store theme name for reference -echo "$THEME_NAME" >"$HOME/.local/state/omarchy/current/theme.name" +echo "$THEME_NAME" >"$CURRENT_THEME_NAME_PATH" # Make the running shell pick up the new palette immediately while the rest of # the theme hooks run. @@ -368,6 +424,7 @@ post_theme_commands=( omarchy-restart-helix omarchy-theme-set-foot omarchy-theme-set-tmux + omarchy-theme-set-hunk omarchy-theme-set-gnome omarchy-theme-set-pi omarchy-theme-set-claude @@ -385,9 +442,10 @@ if [[ $THEME_HEADLESS != "1" ]]; then # Call hook on theme set omarchy-hook theme-set "$THEME_NAME" >/dev/null - # Warm selector caches after the theme is applied. The shell hot-reloads theme - # colors/backgrounds, so keep the running instance alive and preload the picker - # rows/selection to avoid first-open carousel settling after a theme change. - omarchy-theme-switcher --preload >/dev/null 2>&1 + # Mirror the theme to herdr machines. SSH can take a while, so this never holds up the theme change. + setsid omarchy-theme-set-herdr-machines >>"$HOME/.local/state/omarchy/theme-set-herdr-machines.log" 2>&1 /dev/null 2>&1 & fi diff --git a/bin/omarchy-theme-set-browser b/bin/omarchy-theme-set-browser index 612e586fcf8f..d04be45db5b5 100755 --- a/bin/omarchy-theme-set-browser +++ b/bin/omarchy-theme-set-browser @@ -12,25 +12,83 @@ if [[ -f $CHROMIUM_THEME ]]; then THEME_HEX_COLOR=$(browser_policy_theme_hex "$(<$CHROMIUM_THEME)") fi -refresh_running_browser() { - local process="$1" - local command="$2" - local pgrep_args="${3:--x}" +# Tests override this with a temporary directory list; production uses the +# fixed trust-root set from browser-policy.sh. +POLICY_DIRS=("${BROWSER_POLICY_MANAGED_DIRS[@]}") +if [[ -n ${OMARCHY_BROWSER_POLICY_DIRS:-} ]]; then + POLICY_DIRS=() + while IFS= read -r dir; do + POLICY_DIRS+=("$dir") + done <<< "$OMARCHY_BROWSER_POLICY_DIRS" +fi - if omarchy-cmd-present "$command" && pgrep $pgrep_args "$process" >/dev/null; then - "$command" --refresh-platform-policy --no-startup-window &>/dev/null - fi +# A managed color.json is already correct only when it is a regular, root-owned +# file with mode 0644 containing exactly the canonical JSON for the requested +# color. +file_is_canonical() { + local file=$1 + [[ -f $file && ! -L $file ]] || return 1 + [[ $(<"$file") == "$expected_json" ]] || return 1 + [[ $(stat -c '%U:%G %a' "$file") == "root:root 644" ]] } +# Skip the privileged policy write and browser refreshes entirely when every +# existing managed color.json is already canonical. The writer only touches +# directories that exist, so a browser installed since then has no color.json +# yet and takes the write. +expected_json='{"BrowserThemeColor": "'$THEME_HEX_COLOR'", "BrowserColorScheme": "device"}' +saw_any=false +all_unchanged=true +for dir in "${POLICY_DIRS[@]}"; do + [[ -d $dir && ! -L $dir ]] || continue + saw_any=true + + if ! file_is_canonical "$dir/color.json"; then + all_unchanged=false + break + fi +done +$saw_any && $all_unchanged && exit 0 + failed=0 -omarchy-theme-set-browser-policy "${THEME_HEX_COLOR#\#}" || failed=1 +# A script's background job reads /dev/null unless told otherwise, which would +# turn the writer's terminal sudo prompt into a pkexec dialog. Keep stdin. +omarchy-theme-set-browser-policy "${THEME_HEX_COLOR#\#}" <&0 & +policy_pid=$! -refresh_running_browser chromium chromium -refresh_running_browser chrome google-chrome-stable || refresh_running_browser chrome google-chrome -refresh_running_browser msedge microsoft-edge-stable -refresh_running_browser brave brave +# While the policy writes, find the running browsers with one process table +# read. A pgrep per browser rescans /proc each time, ~40ms apiece. +declare -A running_names=() +running_args="" +while read -r name args; do + running_names[$name]=1 + running_args+="$args"$'\n' +done < <(ps -eo comm=,args=) + +# Chrome installs as either binary name, so take whichever exists. +chrome=google-chrome-stable +omarchy-cmd-present "$chrome" || chrome=google-chrome + +browsers_to_refresh=() +for browser in chromium:chromium "chrome:$chrome" msedge:microsoft-edge-stable brave:brave; do + [[ -n ${running_names[${browser%%:*}]:-} ]] && omarchy-cmd-present "${browser#*:}" && browsers_to_refresh+=("${browser#*:}") +done # Match on the binary path: the running process is named plain "brave", and a -# bare -f brave-origin pattern would also match the installer's own terminal. -refresh_running_browser /opt/brave-origin-bin/ brave-origin -f +# bare brave-origin pattern would also match the installer's own terminal. +[[ $running_args == *"/opt/brave-origin-bin/"* ]] && omarchy-cmd-present brave-origin && browsers_to_refresh+=(brave-origin) + +wait "$policy_pid" || failed=1 + +# Refresh each running browser in parallel, so one slow launch doesn't +# serialize the rest. +refresh_pids=() +for command in "${browsers_to_refresh[@]}"; do + "$command" --refresh-platform-policy --no-startup-window &>/dev/null & + refresh_pids+=("$!") +done + +for pid in "${refresh_pids[@]}"; do + wait "$pid" +done exit "$failed" diff --git a/bin/omarchy-theme-set-herdr-machines b/bin/omarchy-theme-set-herdr-machines new file mode 100755 index 000000000000..95d184a19dc4 --- /dev/null +++ b/bin/omarchy-theme-set-herdr-machines @@ -0,0 +1,75 @@ +#!/bin/bash + +# omarchy:summary=Mirror the current theme to your herdr machines that run Omarchy +# omarchy:args=[--available] +# omarchy:hidden=true + +# omarchy-theme-set runs this in the background after every theme change. Sync is off until +# the herdr-theme-sync toggle is turned on, and a machine only accepts themes with it on too. + +# Columns: id, label, SSH target, session, state. +# This machine may be listed too, and it is already on the theme, so it needs no special case. +targets=$(herdr machine list 2>/dev/null | awk -F '\t' '$5 == "enabled" { print $3 }') + +# The menu offers the toggle whenever there is a machine to sync to, whether or not sync is on. +if [[ $1 == "--available" ]]; then + [[ -n $targets ]] + exit +fi + +# Serialize runs and send whichever theme is current once the lock is held, +# so a slow earlier run can never overwrite a later theme change. +exec 9>"${XDG_RUNTIME_DIR:-/tmp}/omarchy-theme-set-herdr-machines.lock" +flock 9 + +# A theme that arrived from another machine stops here, so machines never echo it back. +# The toggle is checked once the lock is held, so turning sync off also stops a queued run. +if [[ -n $OMARCHY_THEME_SYNC_FROM ]] || ! omarchy-toggle-enabled herdr-theme-sync; then + exit 0 +fi + +theme=$(cat "$HOME/.local/state/omarchy/current/theme.name" 2>/dev/null) + +# Runs on the remote machine under a login shell, so OMARCHY_PATH and PATH are set there. +# SSH carries no desktop session, so the environment comes from the live Hyprland instance. +# The flag is read directly, so an Omarchy that predates theme sync simply counts as off. +# Braces make bash read the whole script before running it, so nothing it runs can consume the rest. +read -r -d '' REMOTE_SCRIPT <<'EOF' +{ + if [[ ! -f ~/.local/state/omarchy/toggles/herdr-theme-sync ]]; then + echo "theme sync is off" + exit + fi + + if [[ $(cat ~/.local/state/omarchy/current/theme.name 2>/dev/null) == "$theme" ]]; then + echo "already on $theme" + exit + fi + + export XDG_RUNTIME_DIR="/run/user/$(id -u)" + instance=$(hyprctl instances -j 2>/dev/null | jq -r 'max_by(.time) // empty | "\(.instance) \(.wl_socket)"') + if [[ -z $instance ]]; then + echo "no Hyprland session" + exit + fi + + read -r HYPRLAND_INSTANCE_SIGNATURE WAYLAND_DISPLAY <<<"$instance" + export HYPRLAND_INSTANCE_SIGNATURE WAYLAND_DISPLAY + export DBUS_SESSION_BUS_ADDRESS="unix:path=$XDG_RUNTIME_DIR/bus" + export OMARCHY_THEME_SYNC_FROM="$from" + + if omarchy theme set "$theme" >/dev/null 2>&1; then + echo "set $theme" + else + echo "failed to set $theme" + fi +} &1 | tail -n 1) + echo "$(date '+%F %T') $target: ${result:-unreachable}" +done diff --git a/bin/omarchy-theme-set-hermes b/bin/omarchy-theme-set-hermes index c73b24c7a1c7..b084b20288df 100755 --- a/bin/omarchy-theme-set-hermes +++ b/bin/omarchy-theme-set-hermes @@ -193,7 +193,8 @@ if (( HERMES_ACTIVATE == 0 )); then esac fi -# Omarchy's cold stub installs Hermes when run, so ask the probe before running it. +# The probe vets the command before anything here runs it: a wrapper that is +# not a working Hermes, or the retired mise stub that would build one. if ! omarchy-install-hermes-cli --check 2>/dev/null; then note "Hermes is not ready, so the Omarchy skin is published but not active." note "Once Hermes runs, activate it with: hermes config set display.skin $HERMES_SKIN_NAME" diff --git a/bin/omarchy-theme-set-hunk b/bin/omarchy-theme-set-hunk new file mode 100755 index 000000000000..5c92fa7aa0ae --- /dev/null +++ b/bin/omarchy-theme-set-hunk @@ -0,0 +1,14 @@ +#!/bin/bash + +# omarchy:summary=Tell running Hunk sessions to pick up the new terminal colors +# omarchy:hidden=true + +# Hunk's default terminal theme re-reads the terminal palette on SIGWINCH. Terminals reload +# their colors in parallel with this hook, so nudge once now and once after they have settled; +# Hunk only repaints when the palette actually changed. + +if pgrep -x hunk >/dev/null; then + pkill -WINCH -x hunk + sleep 1 + pkill -WINCH -x hunk +fi diff --git a/bin/omarchy-theme-set-templates b/bin/omarchy-theme-set-templates index de4d599137ec..fdac2a479dfb 100755 --- a/bin/omarchy-theme-set-templates +++ b/bin/omarchy-theme-set-templates @@ -8,55 +8,19 @@ USER_TEMPLATES_DIR="$HOME/.config/omarchy/themed" NEXT_THEME_DIR="$HOME/.local/state/omarchy/current/next-theme" COLORS_FILE="$NEXT_THEME_DIR/colors.toml" +# Theme switching waits on this script before the transition starts, so it +# avoids a process per value: helpers return through REPLY rather than $(...), +# and one awk pass computes the mixes and renders every template. + declare -A THEME_COLORS +MIX_TOKEN_PATTERN='\{\{[[:space:]]*mix(_strip|_rgb)?[[:space:]]+[A-Za-z0-9_]+[[:space:]]+[A-Za-z0-9_]+[[:space:]]+[0-9]+([.][0-9]+)?%?[[:space:]]*\}\}' +GRADIENT_TOKEN_PATTERN='\{\{[[:space:]]*(hypr_gradient|gradient_start|shell_gradient)[[:space:]]+[^}]+[[:space:]]*\}\}' + # Convert hex color to decimal RGB (e.g., "#1e1e2e" -> "30,30,46") hex_to_rgb() { local hex="${1#\#}" - printf "%d,%d,%d" "0x${hex:0:2}" "0x${hex:2:2}" "0x${hex:4:2}" -} - -# Mix two hex colors. Amount may be a fraction (0.30) or percentage (30%). -mix_color() { - local start="${1#\#}" - local end="${2#\#}" - local amount="$3" - - awk -v start="$start" -v end="$end" -v amount="$amount" ' - function hex_value(char) { - return index("0123456789abcdef", tolower(char)) - 1 - } - - function hex_pair_to_int(hex, idx) { - return hex_value(substr(hex, idx, 1)) * 16 + hex_value(substr(hex, idx + 1, 1)) - } - - BEGIN { - if (amount ~ /%$/) { - sub(/%$/, "", amount) - amount = amount / 100 - } else { - amount += 0 - if (amount > 1) amount = amount / 100 - } - - if (amount < 0) amount = 0 - if (amount > 1) amount = 1 - - start_r = hex_pair_to_int(start, 1) - start_g = hex_pair_to_int(start, 3) - start_b = hex_pair_to_int(start, 5) - end_r = hex_pair_to_int(end, 1) - end_g = hex_pair_to_int(end, 3) - end_b = hex_pair_to_int(end, 5) - - red = int(start_r * (1 - amount) + end_r * amount + 0.5) - green = int(start_g * (1 - amount) + end_g * amount + 0.5) - blue = int(start_b * (1 - amount) + end_b * amount + 0.5) - - printf "#%02x%02x%02x\n", red, green, blue - } - ' + printf -v REPLY "%d,%d,%d" "0x${hex:0:2}" "0x${hex:2:2}" "0x${hex:4:2}" } trim() { @@ -64,7 +28,7 @@ trim() { value="${value#"${value%%[![:space:]]*}"}" value="${value%"${value##*[![:space:]]}"}" - printf "%s" "$value" + REPLY="$value" } resolve_theme_ref() { @@ -72,30 +36,26 @@ resolve_theme_ref() { local fallback="${2:-}" if [[ -n ${THEME_COLORS[$ref]+_} ]]; then - printf "%s" "${THEME_COLORS[$ref]}" + REPLY="${THEME_COLORS[$ref]}" elif [[ -n $fallback && -n ${THEME_COLORS[$fallback]+_} ]]; then - printf "%s" "${THEME_COLORS[$fallback]}" + REPLY="${THEME_COLORS[$fallback]}" elif [[ -n $fallback ]]; then - printf "%s" "$fallback" + REPLY="$fallback" else - printf "%s" "$ref" + REPLY="$ref" fi } resolve_gradient_color() { - local color - - color=$(trim "$1") - if [[ -n ${THEME_COLORS[$color]+_} ]]; then - color="${THEME_COLORS[$color]}" + trim "$1" + if [[ -n ${THEME_COLORS[$REPLY]+_} ]]; then + REPLY="${THEME_COLORS[$REPLY]}" fi - - printf "%s" "$color" } parse_gradient() { local spec="$1" - local part color + local part local -a parts GRADIENT_COLORS=() @@ -108,8 +68,8 @@ parse_gradient() { if [[ $part =~ ^-?[0-9]+([.][0-9]+)?deg$ ]]; then GRADIENT_ANGLE="${part%deg}" else - color=$(resolve_gradient_color "$part") - GRADIENT_COLORS+=("$color") + resolve_gradient_color "$part" + GRADIENT_COLORS+=("$REPLY") fi done } @@ -117,12 +77,13 @@ parse_gradient() { color_to_shell_hex() { local color r g b - color=$(resolve_gradient_color "$1") + resolve_gradient_color "$1" + color="$REPLY" if [[ $color =~ ^#[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$ ]]; then - printf "#%s" "${color:1:6}" + REPLY="#${color:1:6}" elif [[ $color =~ ^[Rr][Gg][Bb][Aa]?\(([0-9A-Fa-f]{6})([0-9A-Fa-f]{2})?\)$ ]]; then - printf "#%s" "${BASH_REMATCH[1]}" + REPLY="#${BASH_REMATCH[1]}" elif [[ $color =~ ^[Rr][Gg][Bb][Aa]?\(([0-9]+),([0-9]+),([0-9]+)(,[0-9.]+)?\)$ ]]; then r=${BASH_REMATCH[1]} g=${BASH_REMATCH[2]} @@ -130,40 +91,42 @@ color_to_shell_hex() { (( r > 255 )) && r=255 (( g > 255 )) && g=255 (( b > 255 )) && b=255 - printf "#%02x%02x%02x" "$r" "$g" "$b" + printf -v REPLY "#%02x%02x%02x" "$r" "$g" "$b" elif [[ $color =~ ^0x[0-9A-Fa-f]{8}$ ]]; then - printf "#%s" "${color:4:6}" + REPLY="#${color:4:6}" else - printf "%s" "$color" + REPLY="$color" fi } hypr_gradient_value() { - local spec color index + local spec index value - spec=$(resolve_theme_ref "$1" "${2:-}") + resolve_theme_ref "$1" "${2:-}" + spec="$REPLY" parse_gradient "$spec" if (( ${#GRADIENT_COLORS[@]} == 0 )); then - printf '"%s"' "$spec" + REPLY="\"$spec\"" elif (( ${#GRADIENT_COLORS[@]} == 1 )); then - printf '"%s"' "${GRADIENT_COLORS[0]}" + REPLY="\"${GRADIENT_COLORS[0]}\"" else - printf '{ colors = {' + value='{ colors = {' for index in "${!GRADIENT_COLORS[@]}"; do - (( index > 0 )) && printf ',' - printf ' "%s"' "${GRADIENT_COLORS[$index]}" + (( index > 0 )) && value+=',' + value+=" \"${GRADIENT_COLORS[$index]}\"" done - printf ' }' - [[ -n $GRADIENT_ANGLE ]] && printf ', angle = %s' "$GRADIENT_ANGLE" - printf ' }' + value+=' }' + [[ -n $GRADIENT_ANGLE ]] && value+=", angle = $GRADIENT_ANGLE" + REPLY="$value }" fi } gradient_start_value() { local spec - spec=$(resolve_theme_ref "$1" "${2:-}") + resolve_theme_ref "$1" "${2:-}" + spec="$REPLY" parse_gradient "$spec" if (( ${#GRADIENT_COLORS[@]} == 0 )); then @@ -174,41 +137,45 @@ gradient_start_value() { } shell_gradient_value() { - local spec index + local spec index value="" - spec=$(resolve_theme_ref "$1" "${2:-}") + resolve_theme_ref "$1" "${2:-}" + spec="$REPLY" parse_gradient "$spec" if (( ${#GRADIENT_COLORS[@]} == 0 )); then - printf "%s" "$spec" + REPLY="$spec" return fi for index in "${!GRADIENT_COLORS[@]}"; do - (( index > 0 )) && printf " " - printf "%s" "${GRADIENT_COLORS[$index]}" + (( index > 0 )) && value+=" " + value+="${GRADIENT_COLORS[$index]}" done - [[ -n $GRADIENT_ANGLE ]] && printf " %sdeg" "$GRADIENT_ANGLE" + [[ -n $GRADIENT_ANGLE ]] && value+=" ${GRADIENT_ANGLE}deg" + REPLY="$value" } +# The value table holds token, unit separator, value lines for the renderer to +# substitute. Tokens may contain tabs, so a tab cannot delimit them. add_template_value() { local key="$1" local value="$2" - local rgb - printf 's|{{ %s }}|%s|g\n' "$key" "$value" >>"$sed_script" - printf 's|{{ %s_strip }}|%s|g\n' "$key" "${value#\#}" >>"$sed_script" + printf '{{ %s }}\037%s\n{{ %s_strip }}\037%s\n' "$key" "$value" "$key" "${value#\#}" >>"$value_table" if [[ $value =~ ^#[0-9A-Fa-f]{6}$ ]]; then - rgb=$(hex_to_rgb "$value") - printf 's|{{ %s_rgb }}|%s|g\n' "$key" "$rgb" >>"$sed_script" + hex_to_rgb "$value" + printf '{{ %s_rgb }}\037%s\n' "$key" "$REPLY" >>"$value_table" fi } +# A mix of two hex colors goes to the renderer as mix, token, function, start, +# end and amount, split by unit separators, since awk computes it. add_mix_value() { local token="$1" - local content fn start_key end_key amount start end value + local content fn start_key end_key amount start end content="${token#\{\{}" content="${content%\}\}}" @@ -218,42 +185,14 @@ add_mix_value() { end="${THEME_COLORS[$end_key]:-}" [[ $start =~ ^#[0-9A-Fa-f]{6}$ && $end =~ ^#[0-9A-Fa-f]{6}$ ]] || return + [[ $fn == "mix" || $fn == "mix_strip" || $fn == "mix_rgb" ]] || return - value=$(mix_color "$start" "$end" "$amount") - - case "$fn" in - mix) - ;; - mix_strip) - value="${value#\#}" - ;; - mix_rgb) - value=$(hex_to_rgb "$value") - ;; - *) - return - ;; - esac - - printf 's|%s|%s|g\n' "$token" "$value" >>"$sed_script" -} - -add_mix_values() { - local tpl token - local -A seen=() - - for tpl in "${template_files[@]}"; do - while IFS= read -r token; do - [[ -n ${seen[$token]:-} ]] && continue - seen[$token]=1 - add_mix_value "$token" - done < <(grep -hEo '\{\{[[:space:]]*mix(_strip|_rgb)?[[:space:]]+[A-Za-z0-9_]+[[:space:]]+[A-Za-z0-9_]+[[:space:]]+[0-9]+([.][0-9]+)?%?[[:space:]]*\}\}' "$tpl" 2>/dev/null || true) - done + printf 'mix\037%s\037%s\037%s\037%s\037%s\n' "$token" "$fn" "$start" "$end" "$amount" >>"$mix_table" } add_gradient_function_value() { local token="$1" - local content fn key fallback value + local content fn key fallback content="${token#\{\{}" content="${content%\}\}}" @@ -261,33 +200,40 @@ add_gradient_function_value() { case "$fn" in hypr_gradient) - value=$(hypr_gradient_value "$key" "$fallback") + hypr_gradient_value "$key" "$fallback" ;; gradient_start) - value=$(gradient_start_value "$key" "$fallback") + gradient_start_value "$key" "$fallback" ;; shell_gradient) - value=$(shell_gradient_value "$key" "$fallback") + shell_gradient_value "$key" "$fallback" ;; *) return ;; esac - printf 's|%s|%s|g\n' "$token" "$value" >>"$sed_script" + printf '%s\037%s\n' "$token" "$REPLY" >>"$value_table" } -add_gradient_function_values() { - local tpl token +# Scan every template once for function tokens, instead of a grep per template +# per function family. +add_function_values() { + local token local -A seen=() - for tpl in "${template_files[@]}"; do - while IFS= read -r token; do - [[ -n ${seen[$token]:-} ]] && continue - seen[$token]=1 + (( ${#template_files[@]} > 0 )) || return + + while IFS= read -r token; do + [[ -n ${seen[$token]:-} ]] && continue + seen[$token]=1 + + if [[ $token =~ ^$MIX_TOKEN_PATTERN$ ]]; then + add_mix_value "$token" + else add_gradient_function_value "$token" - done < <(grep -hEo '\{\{[[:space:]]*(hypr_gradient|gradient_start|shell_gradient)[[:space:]]+[^}]+[[:space:]]*\}\}' "$tpl" 2>/dev/null || true) - done + fi + done < <(grep -hEo "$MIX_TOKEN_PATTERN|$GRADIENT_TOKEN_PATTERN" "${template_files[@]}" 2>/dev/null || true) } strip_shell_section_header() { @@ -367,9 +313,123 @@ apply_shell_section_overrides() { done } +# Substitute every template in one awk process. Each {{ ... }} span is looked +# up whole, as the per-template sed script used to match it. A mix is rounded +# with awk's floating point exactly as before, so no generated color moves. +render_templates() { + local tpl filename + local -a pairs=() + + # Process user templates first, then built-in templates (user overrides + # built-in). Don't overwrite configs the theme already ships. + for tpl in "${template_files[@]}"; do + filename=${tpl##*/} + filename=${filename%.tpl} + if [[ ! -f $NEXT_THEME_DIR/$filename && -z ${rendered[$filename]:-} ]]; then + rendered[$filename]=1 + pairs+=("$tpl" "$NEXT_THEME_DIR/$filename") + fi + done + + (( ${#pairs[@]} > 0 )) || return + + awk -v value_table="$value_table" -v mix_table="$mix_table" ' + function hex_value(char) { + return index("0123456789abcdef", tolower(char)) - 1 + } + + function hex_pair_to_int(hex, idx) { + return hex_value(substr(hex, idx, 1)) * 16 + hex_value(substr(hex, idx + 1, 1)) + } + + function mix_color(start, end, amount, start_r, start_g, start_b, end_r, end_g, end_b, red, green, blue) { + start = substr(start, 2) + end = substr(end, 2) + + if (amount ~ /%$/) { + sub(/%$/, "", amount) + amount = amount / 100 + } else { + amount += 0 + if (amount > 1) amount = amount / 100 + } + + if (amount < 0) amount = 0 + if (amount > 1) amount = 1 + + start_r = hex_pair_to_int(start, 1) + start_g = hex_pair_to_int(start, 3) + start_b = hex_pair_to_int(start, 5) + end_r = hex_pair_to_int(end, 1) + end_g = hex_pair_to_int(end, 3) + end_b = hex_pair_to_int(end, 5) + + red = int(start_r * (1 - amount) + end_r * amount + 0.5) + green = int(start_g * (1 - amount) + end_g * amount + 0.5) + blue = int(start_b * (1 - amount) + end_b * amount + 0.5) + + return sprintf("#%02x%02x%02x", red, green, blue) + } + + function render(line, out, open, span, token) { + out = "" + while ((open = index(line, "{{")) > 0) { + span = index(substr(line, open + 2), "}}") + if (span == 0) break + + token = substr(line, open, span + 3) + if (token in values) { + out = out substr(line, 1, open - 1) values[token] + line = substr(line, open + length(token)) + } else { + out = out substr(line, 1, open) + line = substr(line, open + 1) + } + } + return out line + } + + BEGIN { + while ((getline row < value_table) > 0) { + sep = index(row, "\037") + values[substr(row, 1, sep - 1)] = substr(row, sep + 1) + } + close(value_table) + + while ((getline row < mix_table) > 0) { + split(row, field, "\037") + value = mix_color(field[4], field[5], field[6]) + if (field[3] == "mix_strip") { + value = substr(value, 2) + } else if (field[3] == "mix_rgb") { + value = sprintf("%d,%d,%d", hex_pair_to_int(substr(value, 2), 1), hex_pair_to_int(substr(value, 2), 3), hex_pair_to_int(substr(value, 2), 5)) + } + values[field[2]] = value + } + close(mix_table) + + for (i = 1; i < ARGC; i += 2) { + template = ARGV[i] + output = ARGV[i + 1] + # RT holds the terminator each line was read with, so a template that + # ends without a newline renders without one, as sed left it. + while ((getline line < template) > 0) printf "%s%s", render(line), RT > output + close(template) + close(output) + # A template with no lines still leaves its output file behind. + printf "" >> output + close(output) + } + exit + } + ' "${pairs[@]}" +} + # Only generate dynamic templates for themes with a colors.toml definition if [[ -f $COLORS_FILE ]]; then - sed_script=$(mktemp) + value_table=$(mktemp) + mix_table=$(mktemp) + declare -A rendered=() shopt -s nullglob template_files=("$USER_TEMPLATES_DIR"/*.tpl "$TEMPLATES_DIR"/*.tpl) @@ -384,21 +444,10 @@ if [[ -f $COLORS_FILE ]]; then add_template_value "$key" "${THEME_COLORS[$key]}" done - add_mix_values - add_gradient_function_values - - # Process user templates first, then built-in templates (user overrides built-in) - for tpl in "${template_files[@]}"; do - filename=$(basename "$tpl" .tpl) - output_path="$NEXT_THEME_DIR/$filename" - - # Don't overwrite configs already exists in the output directory (copied from theme specific folder) - if [[ ! -f $output_path ]]; then - sed -f "$sed_script" "$tpl" >"$output_path" - fi - done + add_function_values + render_templates - rm "$sed_script" + rm "$value_table" "$mix_table" fi apply_shell_section_overrides diff --git a/bin/omarchy-theme-set-vscode b/bin/omarchy-theme-set-vscode index c87b6bb8e81e..6517809990c6 100755 --- a/bin/omarchy-theme-set-vscode +++ b/bin/omarchy-theme-set-vscode @@ -68,8 +68,17 @@ install_generated_extension() { ui_theme="vs-dark" fi + # VS Code caches loaded color themes in memory and only rebuilds a registry + # entry when the providing extension changes, so derive the version from the + # theme content: identical palettes keep the cache, new palettes invalidate it. + GENERATED_EXTENSION_VERSION="1.0.$(cksum "$GENERATED_THEME" | cut -d' ' -f1)" + mkdir -p "$ext_dir/themes" - ln -sfn "$GENERATED_THEME" "$ext_dir/themes/omarchy-color-theme.json" + # A real file rather than a symlink into current/theme: the _watch watcher + # below needs a same-inode rewrite to fire, and a symlink would dangle while + # omarchy-theme-set swaps current/theme via rm + mv. + rm -f "$ext_dir/themes/omarchy-color-theme.json" + cat "$GENERATED_THEME" >"$ext_dir/themes/omarchy-color-theme.json" cat > "$ext_dir/package.json" <&2 + exit 1 + ;; +esac + +if omarchy-hyprland-toggle-enabled no-animations; then + omarchy-notification-send -g 󰕟 "Animations disabled" +else + omarchy-notification-send -g 󰕟 "Animations enabled" +fi diff --git a/bin/omarchy-toggle-theme-sync b/bin/omarchy-toggle-theme-sync new file mode 100755 index 000000000000..c65a7d520024 --- /dev/null +++ b/bin/omarchy-toggle-theme-sync @@ -0,0 +1,11 @@ +#!/bin/bash + +# omarchy:summary=Toggle mirroring theme changes to and from your herdr machines + +omarchy-toggle herdr-theme-sync + +if omarchy-toggle-enabled herdr-theme-sync; then + omarchy-notification-send -g 󰸌 "Herdr theme sync enabled" +else + omarchy-notification-send -g 󰸌 "Herdr theme sync disabled" +fi diff --git a/bin/omarchy-update b/bin/omarchy-update index e71e808664ee..6e58f6dd8ce3 100755 --- a/bin/omarchy-update +++ b/bin/omarchy-update @@ -1,31 +1,110 @@ -#!/bin/bash +#!/bin/bash -p # omarchy:summary=Update Omarchy and system packages +# omarchy:alias=omarchy up # omarchy:args=[-y] # omarchy:examples=omarchy update | omarchy update -y # omarchy:requires-sudo=true +if [[ $- != *p* ]]; then + echo "Refusing an unsafe Bash startup." >&2 + exit 126 +fi + +security_entrypoint=$(/usr/bin/readlink -e -- "${BASH_SOURCE[0]}") || exit 126 +source "${security_entrypoint%/*}/omarchy-security-functions" || exit 126 +omarchy_security_require_privileged_bash_startup || exit 126 set -e +omarchy_security_sanitize_bash_environment "$0" "$@" +omarchy_security_require_source_root "$0" +# Logging and lock acquisition re-exec this command with a sanitized PATH. +# Preserve the caller's path only for the later hook/mise phases. +user_path=${OMARCHY_UPDATE_USER_PATH:-$PATH} +unset OMARCHY_UPDATE_USER_PATH +# Traps first, so a signal or failure during the entry revocation still +# exits through the cleanup path. Starting cold means the single password +# prompt below always belongs to this update, never to an earlier session. +omarchy_security_install_sudo_cleanup_traps +omarchy_security_revoke_sudo_timestamp || exit 1 +# Validate the no-update wrapper up front: the AUR phase depends on it. Every +# other phase shares the one authorization, so it stays off PATH until then. +omarchy_security_enable_no_update_sudo +PATH="$OMARCHY_PATH/bin:/usr/bin:/usr/sbin:/bin:/sbin" +unset OMARCHY_SUDO_NO_UPDATE +# Helpers that manage their own sudo boundary leave this authorization to us. +export PATH OMARCHY_UPDATE_SUDO_SESSION=1 + +update_stay_awake_stopped=0 +sudo_keepalive_pid="" + +# Ask for the password once, then keep sudo's timestamp fresh so long package +# downloads, migrations, hooks, and mise never outlast it and prompt again. +# Authorize by running a command rather than sudo -v: under the default +# verifypw=all, -v prompts even when passwordless sudo is enabled. +authorize_update() { + /usr/bin/sudo /usr/bin/true || return 1 + + local update_pid=$$ + ( + [[ -z ${OMARCHY_UPDATE_LOCK_FD:-} ]] || exec {OMARCHY_UPDATE_LOCK_FD}>&- + sleep_pid="" + trap - EXIT HUP INT + trap '[[ -z $sleep_pid ]] || kill "$sleep_pid" 2>/dev/null; exit 0' TERM + while :; do + sleep 60 & + sleep_pid=$! + wait "$sleep_pid" + kill -0 "$update_pid" 2>/dev/null || exit 0 + /usr/bin/sudo -n /usr/bin/true 2>/dev/null || exit 0 + done + ) & + sudo_keepalive_pid=$! +} + +end_update_authorization() { + if [[ -n $sudo_keepalive_pid ]]; then + kill "$sudo_keepalive_pid" 2>/dev/null || true + wait "$sudo_keepalive_pid" 2>/dev/null || true + sudo_keepalive_pid="" + fi + omarchy_security_revoke_sudo_timestamp +} + +cleanup_update() { + local status=$? + trap - EXIT HUP INT TERM + if ! end_update_authorization; then + echo "Could not invalidate sudo before update cleanup." >&2 + omarchy_security_exit_with_revoked_sudo 1 + fi + if (( update_stay_awake_stopped == 0 )); then + omarchy-update-stay-awake stop || status=1 + fi + omarchy_security_exit_with_revoked_sudo "$status" +} if [[ -z ${OMARCHY_UPDATE_LOGGED:-} ]]; then script_command=$(printf '%q ' "$0" "$@") - exec env OMARCHY_UPDATE_LOGGED=1 script -qefc "$script_command" "/tmp/omarchy-update.log" + exec env OMARCHY_UPDATE_LOGGED=1 OMARCHY_UPDATE_USER_PATH="$user_path" script -qefc "$script_command" "/tmp/omarchy-update.log" fi if ! omarchy-update-lock held; then - exec omarchy-update-lock run "$0" "$@" + exec env OMARCHY_UPDATE_USER_PATH="$user_path" omarchy-update-lock run "$0" "$@" fi trap 'echo ""; echo -e "\033[0;31mSomething went wrong during the update!\n\nPlease review the output above carefully, correct the error, and retry the update.\n\nIf you need assistance, get help from the community at https://omarchy.org/discord\033[0m"' ERR -trap 'omarchy-update-stay-awake stop' EXIT +trap cleanup_update EXIT +omarchy_security_install_signal_exit_traps omarchy-update-requires-free-space -# -y is a promise not to ask anything. Steps that would need an answer report -# and move on instead of waiting on a prompt nobody is here to give. +# -y suppresses Omarchy confirmation prompts; sudo authorization is still +# required. Interactive review steps report and move on instead of waiting. [[ ${1:-} != "-y" ]] || export OMARCHY_UPDATE_UNATTENDED=1 if [[ ${1:-} == "-y" ]] || omarchy-update-confirm; then + authorize_update + # Before the snapshot: the cache is on the snapshotted subvolume, so pruning # after it frees nothing until that snapshot ages out. omarchy-update-pkg-prune @@ -38,6 +117,7 @@ if [[ ${1:-} == "-y" ]] || omarchy-update-confirm; then omarchy-update-stay-awake start + # Preserve the established development-checkout update ordering. omarchy-update-dev omarchy-update-keyring @@ -45,20 +125,36 @@ if [[ ${1:-} == "-y" ]] || omarchy-update-confirm; then # them, so everything below waits on this finishing. An upgrade that stopped # takes the update with it rather than migrating against what is still on disk. omarchy-update-system-pkgs + omarchy-migrate - omarchy-hook post-update - omarchy-update-aur-pkgs - omarchy-update-mise omarchy-update-orphan-pkgs omarchy-update-analyze-logs omarchy-update-status - # Release update-owned inhibitors before offering a reboot. A confirmed - # reboot can terminate this process before its EXIT trap gets a chance to - # remove the persistent Stay Awake marker. + # Service restart helpers can need sudo. The reboot-only phase below + # performs no privileged work. + omarchy-update-restart --services-only + + # Hooks and mise run with the caller's PATH so user-installed tools resolve. + PATH="$user_path" "$OMARCHY_PATH/bin/omarchy-hook" post-update + PATH="$user_path" "$OMARCHY_PATH/bin/omarchy-update-mise" + + # AUR builds run third-party PKGBUILD code, so they go last and never see the + # update's authorization: revoke it, then authenticate each sudo call with + # the no-update wrapper, for yay and any bare sudo a PKGBUILD runs, so an AUR + # install prompts without caching anything. + end_update_authorization + PATH="$OMARCHY_PATH/default/omarchy/sudo-no-update:$PATH" OMARCHY_SUDO_NO_UPDATE=1 omarchy-update-aur-pkgs + omarchy_security_revoke_sudo_timestamp + + # The sleep inhibitor covers AUR builds, hooks and mise as well; releasing it + # needs no privilege because the held command already dropped to this user. + # Release it before offering a reboot: a confirmed reboot can terminate this + # process before its EXIT trap gets a chance to remove the persistent Stay + # Awake marker. omarchy-update-stay-awake stop - trap - EXIT + update_stay_awake_stopped=1 - omarchy-update-restart + "$OMARCHY_PATH/bin/omarchy-update-restart" --reboot-only fi diff --git a/bin/omarchy-update-aur-pkgs b/bin/omarchy-update-aur-pkgs index 4f496b331fc4..a860a97d3083 100755 --- a/bin/omarchy-update-aur-pkgs +++ b/bin/omarchy-update-aur-pkgs @@ -2,10 +2,17 @@ # omarchy:summary=Update AUR packages if any are installed +sudo_options=() +if [[ ${OMARCHY_SUDO_NO_UPDATE:-0} == "1" ]]; then + sudo_wrapper="$OMARCHY_PATH/default/omarchy/sudo-no-update/sudo" + [[ -x $sudo_wrapper ]] || exit 1 + sudo_options=(--sudo "$sudo_wrapper" --sudoloop=false) +fi + if pacman -Qem >/dev/null; then if omarchy-pkg-aur-accessible; then echo -e "\e[32m\nUpdate AUR packages\e[0m" - yay -Sua --noconfirm --cleanafter --ignore gcc14,gcc14-libs + yay "${sudo_options[@]}" -Sua --noconfirm --cleanafter --ignore gcc14,gcc14-libs || exit 1 echo else echo -e "\e[31m\nAUR is unavailable (so skipping updates)\e[0m" diff --git a/bin/omarchy-update-confirm b/bin/omarchy-update-confirm index 472927f1e95b..c3ca37e669ca 100755 --- a/bin/omarchy-update-confirm +++ b/bin/omarchy-update-confirm @@ -8,7 +8,7 @@ gum style --border normal --padding "1 2" \ "• You cannot stop the update once you start!" \ "• Make sure you're connected to power or have a full battery" \ "" \ - "What's new: https://github.com/basecamp/omarchy/releases/latest" + "What's new: https://github.com/omacom/omarchy/releases/latest" echo diff --git a/bin/omarchy-update-keyring b/bin/omarchy-update-keyring index d561e22a2773..3a1c1c17692e 100755 --- a/bin/omarchy-update-keyring +++ b/bin/omarchy-update-keyring @@ -3,6 +3,11 @@ # omarchy:summary=Ensure the Omarchy and Arch keyring packages are installed and populated # omarchy:requires-sudo=true +# omarchy-update runs this under set -e as a trusted pre-step, so a failed recv +# or a broken keyring has to stop this script here, not surface later as +# signature errors in the middle of the main transaction. +set -euo pipefail + if omarchy-pkg-missing omarchy-keyring || ! sudo pacman-key --list-keys 40DFB630FF42BCFFB047046CF0134EE680CAC571 &>/dev/null; then sudo pacman-key --recv-keys 40DFB630FF42BCFFB047046CF0134EE680CAC571 --keyserver keys.openpgp.org sudo pacman-key --lsign-key 40DFB630FF42BCFFB047046CF0134EE680CAC571 @@ -19,4 +24,8 @@ fi # Always reinstall, as the keyring can be updated without a package version bump. echo -e "\e[32m\nUpdate Arch signing keys\e[0m" sudo pacman -Sy --noconfirm archlinux-keyring >/dev/null 2> >(grep -vE '^warning: archlinux-keyring-[^ ]+ is up to date -- reinstalling$' >&2) + +# Say "correct" only once the key verifiably is: before the failure checks +# above, a failed recv or reinstall still ended here with exit 0. +sudo pacman-key --list-keys 40DFB630FF42BCFFB047046CF0134EE680CAC571 >/dev/null echo "Keys are correct" diff --git a/bin/omarchy-update-pacman b/bin/omarchy-update-pacman new file mode 100755 index 000000000000..66f66731ef14 --- /dev/null +++ b/bin/omarchy-update-pacman @@ -0,0 +1,25 @@ +#!/bin/bash + +# omarchy:summary=Run a pacman transaction for the Omarchy update flow, shielded from desktop session teardown. +# omarchy:args= +# omarchy:hidden=true +# omarchy:requires-sudo=true + +# Upgrading systemd runs its post_upgrade scriptlet mid-transaction, which +# reexecs both the system manager and every user manager. A pacman running +# inside a user-session scope can be SIGKILLed by that reexec, abandoning the +# transaction halfway. Registering the transaction as a PID 1 scope keeps it +# out of the user manager's cgroups entirely, and system scopes survive the +# system manager's own reexec. +scope=() +if [[ -d /run/systemd/system && ! -L /run/systemd/system ]]; then + scope=(systemd-run --scope --quiet --collect) +fi + +# LC_ALL passes through so callers that parse pacman's stderr can pin the locale. +env_args=(OMARCHY_UPDATE_PACMAN=1) +if [[ -n ${LC_ALL:-} ]]; then + env_args+=(LC_ALL="$LC_ALL") +fi + +exec sudo env "${env_args[@]}" "${scope[@]}" pacman "$@" diff --git a/bin/omarchy-update-restart b/bin/omarchy-update-restart index 05f7ba056ec4..393d95e0de75 100755 --- a/bin/omarchy-update-restart +++ b/bin/omarchy-update-restart @@ -1,51 +1,66 @@ #!/bin/bash # omarchy:summary=Prompt for required reboot or service restarts after updates +# omarchy:args=[--services-only|--reboot-only] -echo +mode="${1:-all}" +case "$mode" in + all|--services-only|--reboot-only) ;; + *) echo "Unknown restart phase: $mode" >&2; exit 2 ;; +esac +echo confirm_reboot() { - gum confirm "$1" && { omarchy-system-reboot; exit 0; } + if [[ ${OMARCHY_UPDATE_UNATTENDED:-0} == "1" ]]; then + echo "$1 Run omarchy-system-reboot when ready." + elif gum confirm "$1"; then + omarchy-system-reboot + exit 0 + fi } -running_kernel=$(uname -r) -kernel_updated=true +if [[ $mode != "--services-only" ]]; then + running_kernel=$(uname -r) + kernel_updated=true -for kernel in /usr/lib/modules/*/vmlinuz; do - if [[ -f $kernel ]] && pacman -Qo "$kernel" &>/dev/null; then - installed_kernel=$(basename "$(dirname "$kernel")") + for kernel in /usr/lib/modules/*/vmlinuz; do + if [[ -f $kernel ]] && pacman -Qo "$kernel" &>/dev/null; then + installed_kernel=$(basename "$(dirname "$kernel")") - if [[ $installed_kernel == $running_kernel ]]; then - kernel_updated=false - break + if [[ $installed_kernel == $running_kernel ]]; then + kernel_updated=false + break + fi fi + done + + if [[ $kernel_updated == "true" ]]; then + confirm_reboot "Linux kernel has been updated. Reboot?" + elif [[ -f $HOME/.local/state/omarchy/reboot-required ]]; then + confirm_reboot "Updates require reboot. Ready?" fi -done -if [[ $kernel_updated == "true" ]]; then - confirm_reboot "Linux kernel has been updated. Reboot?" -elif [[ -f $HOME/.local/state/omarchy/reboot-required ]]; then - confirm_reboot "Updates require reboot. Ready?" + running_hyprland=$(readlink /proc/$(pgrep -x Hyprland)/exe 2>/dev/null) + if [[ $running_hyprland == *"(deleted)"* ]]; then + confirm_reboot "Hyprland has been updated. Reboot?" + fi fi -running_hyprland=$(readlink /proc/$(pgrep -x Hyprland)/exe 2>/dev/null) -if [[ $running_hyprland == *"(deleted)"* ]]; then - confirm_reboot "Hyprland has been updated. Reboot?" -fi +if [[ $mode != "--reboot-only" ]]; then + for file in "$HOME"/.local/state/omarchy/restart-*-required; do + if [[ -f $file ]]; then + filename=$(basename "$file") + service=$(echo "$filename" | sed 's/restart-\(.*\)-required/\1/') + echo "Restarting $service" + omarchy-state clear "$filename" + omarchy-restart-"$service" + fi + done -for file in "$HOME"/.local/state/omarchy/restart-*-required; do - if [[ -f $file ]]; then - filename=$(basename "$file") - service=$(echo "$filename" | sed 's/restart-\(.*\)-required/\1/') - echo "Restarting $service" - omarchy-state clear "$filename" - omarchy-restart-"$service" - fi -done - -# Updates routinely replace the shell's QML, and a stale process can lazy-load -# new files into old code. A restart failure (locked session, ssh, TTY) only -# prints its reason: the next update or login gets a fresh shell anyway. -echo -e "\e[32m\nRestarting shell\e[0m" -echo "All plugins have been reloaded" -omarchy-restart-shell || true + # Updates routinely replace the shell's QML, and a stale process can lazy-load + # new files into old code. A restart failure (locked session, ssh, TTY) only + # prints its reason: the next update or login gets a fresh shell anyway. + echo -e "\e[32m\nRestarting shell\e[0m" + echo "All plugins have been reloaded" + omarchy-restart-shell || true +fi diff --git a/bin/omarchy-update-stay-awake b/bin/omarchy-update-stay-awake index 5fd9eb151b57..11b391fe3551 100755 --- a/bin/omarchy-update-stay-awake +++ b/bin/omarchy-update-stay-awake @@ -1,15 +1,238 @@ -#!/bin/bash +#!/bin/bash -p # omarchy:summary=Manage sleep and idle inhibition during an update # omarchy:args= # omarchy:hidden=true +if [[ $- != *p* ]]; then + echo "Refusing an unsafe Bash startup." >&2 + exit 126 +fi + +security_entrypoint=$(/usr/bin/readlink -e -- "${BASH_SOURCE[0]}") || exit 126 +source "${security_entrypoint%/*}/omarchy-security-functions" || exit 126 +omarchy_security_require_privileged_bash_startup || exit 126 set -e +omarchy_security_sanitize_bash_environment "$0" "$@" +omarchy_security_require_source_root "$0" +# omarchy update authorizes once and revokes when it is done. Revoking here +# would throw that away and prompt again for the rest of the update. +update_sudo_session=0 +if [[ ${OMARCHY_UPDATE_SUDO_SESSION:-} == "1" ]]; then + update_sudo_session=1 + omarchy_security_revoke_sudo_timestamp() { :; } +fi +# Traps first, so a signal or failure during the entry revocation still +# exits through the cleanup path. +omarchy_security_install_sudo_cleanup_traps +omarchy_security_revoke_sudo_timestamp || exit 1 +omarchy_security_enable_no_update_sudo -state_dir="${XDG_RUNTIME_DIR:-/tmp/omarchy-$UID}/omarchy-update-stay-awake" -idle_owner_file="$state_dir/idle-owner" -inhibit_pid_file="$state_dir/inhibit-pid" stay_awake_state="$HOME/.local/state/omarchy/indicators/stay-awake" +caller_uid="" +state_base="" +state_dir="" +idle_owner_file="" +inhibit_pid_file="" +launch_control_file="" +launch_pending=0 +launch_token="" + +fail_state_boundary() { + echo "Refusing to use an unsafe Omarchy update inhibitor state path." >&2 + return 1 +} + +directory_is_private() { + local directory="$1" + local expected_owner="$2" + local legacy="${3:-0}" + local canonical="" + local owner="" + local mode="" + + [[ -d $directory && ! -L $directory ]] || return 1 + canonical=$(readlink -e -- "$directory") || return 1 + [[ $canonical == "$directory" ]] || return 1 + read -r owner mode < <(stat -Lc '%u %a' -- "$directory") || return 1 + [[ $owner == "$expected_owner" ]] || return 1 + [[ $mode == "700" ]] || (( legacy == 1 && (8#$mode & 022) == 0 )) +} + +root_owned_parent_chain() { + local directory="$1" + local parent owner mode type canonical + + parent=$(/usr/bin/dirname -- "$directory") || return 1 + while :; do + [[ -d $parent && ! -L $parent ]] || return 1 + canonical=$(/usr/bin/readlink -e -- "$parent") || return 1 + [[ $canonical == "$parent" ]] || return 1 + read -r owner mode type < <(/usr/bin/stat -Lc '%u %a %F' -- "$parent") || return 1 + [[ $owner == 0 && $type == "directory" ]] || return 1 + ! ((8#$mode & 022)) || return 1 + [[ $parent == / ]] && break + parent=$(/usr/bin/dirname -- "$parent") || return 1 + done +} + +runtime_directory_is_private() { + local directory="$1" expected_owner="$2" + directory_is_private "$directory" "$expected_owner" && + root_owned_parent_chain "$directory" +} + +ensure_private_directory() { + local directory="$1" + + if [[ ! -e $directory && ! -L $directory ]]; then + mkdir -m 700 -- "$directory" 2>/dev/null || true + fi + # Older helpers used mkdir -p with the caller's umask. Tighten only a + # canonical, caller-owned directory that other accounts cannot write. + directory_is_private "$directory" "$caller_uid" 1 || return 1 + chmod 700 -- "$directory" || return 1 + directory_is_private "$directory" "$caller_uid" +} + +initialize_state_boundary() { + local canonical_tmp="" + local tmp_owner="" + local tmp_mode="" + + caller_uid="$EUID" + [[ $caller_uid =~ ^[0-9]+$ ]] || return 1 + + if [[ -n ${XDG_RUNTIME_DIR:-} ]]; then + runtime_directory_is_private "$XDG_RUNTIME_DIR" "$caller_uid" || fail_state_boundary + state_base="$XDG_RUNTIME_DIR" + else + [[ -d /tmp && ! -L /tmp ]] || fail_state_boundary + canonical_tmp=$(readlink -e -- /tmp) || fail_state_boundary + read -r tmp_owner tmp_mode < <(stat -Lc '%u %a' -- /tmp) || fail_state_boundary + [[ $canonical_tmp == "/tmp" && $tmp_owner == "0" && $tmp_mode == "1777" ]] || fail_state_boundary + + state_base="/tmp/omarchy-$caller_uid" + ensure_private_directory "$state_base" || fail_state_boundary + fi + + state_dir="$state_base/omarchy-update-stay-awake" + idle_owner_file="$state_dir/idle-owner" + inhibit_pid_file="$state_dir/inhibit-pid" + launch_control_file="$state_dir/launch-control" +} + +state_file_is_private() { + local state_file="$1" + local legacy="${2:-0}" + local owner="" + local mode="" + local links="" + + [[ -f $state_file && ! -L $state_file ]] || return 1 + read -r owner mode links < <(stat -Lc '%u %a %h' -- "$state_file") || return 1 + [[ $owner == "$caller_uid" && $links == "1" ]] || return 1 + [[ $mode == "600" ]] || (( legacy == 1 && (8#$mode & 022) == 0 )) +} + +read_state_record() { + local state_file="$1" + local legacy="${2:-0}" + local records=() + local file_size="" + local LC_ALL=C + + state_file_is_private "$state_file" "$legacy" || return 1 + mapfile -t records <"$state_file" || return 1 + (( ${#records[@]} == 1 )) || return 1 + file_size=$(stat -Lc '%s' -- "$state_file") || return 1 + (( file_size == ${#records[0]} + 1 )) || return 1 + state_file_is_private "$state_file" "$legacy" || return 1 + printf '%s\n' "${records[0]}" +} + +atomic_write_state() { + local state_file="$1" + local record="$2" + local temporary="" + + [[ $record != *$'\n'* ]] || return 1 + temporary=$(mktemp "$state_dir/.${state_file##*/}.XXXXXXXX") || return 1 + chmod 600 "$temporary" || { + rm -f -- "$temporary" + return 1 + } + if ! printf '%s\n' "$record" >"$temporary" || ! state_file_is_private "$temporary"; then + rm -f -- "$temporary" + return 1 + fi + if [[ -e $state_file || -L $state_file ]]; then + state_file_is_private "$state_file" || { + rm -f -- "$temporary" + return 1 + } + fi + mv -fT -- "$temporary" "$state_file" || { + rm -f -- "$temporary" + return 1 + } + state_file_is_private "$state_file" +} + +rollback_pending_launch() { + local control_fd="" + local inhibit_record="" + local inhibit_pid="" + local recorded_start_time="" + local recorded_owner="" + local token="" + + (( launch_pending == 1 )) || return 0 + + if [[ -e $launch_control_file || -L $launch_control_file ]]; then + state_file_is_private "$launch_control_file" || return 1 + exec {control_fd}<>"$launch_control_file" || return 1 + /usr/bin/flock -x "$control_fd" || { + exec {control_fd}>&- + return 1 + } + : >"/proc/self/fd/$control_fd" + printf 'cancelled %s\n' "$launch_token" >&"$control_fd" + rm -f -- "$launch_control_file" + /usr/bin/flock -u "$control_fd" + exec {control_fd}>&- + fi + + inhibit_record=$(read_state_record "$inhibit_pid_file" 2>/dev/null || true) + if [[ $inhibit_record =~ ^1\ ([1-9][0-9]{0,18})\ ([1-9][0-9]{0,18})\ ([0-9]{1,10})\ ($launch_token)$ ]]; then + inhibit_pid="${BASH_REMATCH[1]}" + recorded_start_time="${BASH_REMATCH[2]}" + recorded_owner="${BASH_REMATCH[3]}" + token="${BASH_REMATCH[4]}" + if process_matches "$inhibit_pid" "$recorded_start_time" "$recorded_owner" "$token"; then + discard_launched_inhibitor "$inhibit_pid" "$recorded_start_time" "$recorded_owner" "$token" + fi + [[ $(read_state_record "$inhibit_pid_file" 2>/dev/null || true) != "$inhibit_record" ]] || + rm -f -- "$inhibit_pid_file" + fi + + # A signal may interrupt either parent-side atomic write before its rename. + rm -f -- "$state_dir"/.launch-control.* "$state_dir"/.idle-owner.* + stop_locked || return 1 + launch_pending=0 +} + +cleanup_pending_launch() { + local status=$? + + trap - EXIT HUP INT TERM + if ! rollback_pending_launch; then + echo "Failed to roll back the pending Omarchy update sleep inhibitor." >&2 + (( status != 0 )) || status=1 + fi + omarchy_security_exit_with_revoked_sudo "$status" \ + "Failed to invalidate sudo credentials after the update sleep inhibitor." +} process_start_time() { local process_pid="$1" @@ -21,9 +244,67 @@ process_start_time() { process_stat="${process_stat##*) }" read -r -a stat_fields <<<"$process_stat" (( ${#stat_fields[@]} > 19 )) || return 1 + [[ ${stat_fields[19]} =~ ^[0-9]+$ ]] || return 1 printf '%s\n' "${stat_fields[19]}" } +process_owner() { + local process_pid="$1" + local token="$2" + local owner="" + + if [[ -n $token ]]; then + owner=$(stat -Lc '%u' -- "/proc/$process_pid") || return 1 + else + # Legacy state can name sudo: its real UID remains the invoking account, + # even when /proc ownership reflects its effective root credentials. + owner=$(awk '/^Uid:/ { print $2; exit }' "/proc/$process_pid/status") || return 1 + fi + [[ $owner =~ ^[0-9]+$ ]] || return 1 + printf '%s\n' "$owner" +} + +process_has_token() { + local process_pid="$1" + local token="$2" + local argument="" + local expected="--why=Omarchy update in progress [$token]" + + [[ -r /proc/$process_pid/cmdline ]] || return 1 + while IFS= read -r -d '' argument; do + [[ $argument == "$expected" ]] && return 0 + done <"/proc/$process_pid/cmdline" + return 1 +} + +process_identity() { + local process_pid="$1" + local token="$2" + local start_before="" + local start_after="" + local owner_before="" + local owner_after="" + + start_before=$(process_start_time "$process_pid") || return 1 + owner_before=$(process_owner "$process_pid" "$token") || return 1 + [[ -z $token ]] || process_has_token "$process_pid" "$token" || return 1 + start_after=$(process_start_time "$process_pid") || return 1 + owner_after=$(process_owner "$process_pid" "$token") || return 1 + [[ $start_before == "$start_after" && $owner_before == "$owner_after" ]] || return 1 + printf '%s %s\n' "$start_before" "$owner_before" +} + +process_matches() { + local process_pid="$1" + local expected_start="$2" + local expected_owner="$3" + local token="$4" + local identity="" + + identity=$(process_identity "$process_pid" "$token" 2>/dev/null) || return 1 + [[ $identity == "$expected_start $expected_owner" ]] +} + process_state() { local process_pid="$1" local process_stat="" @@ -34,113 +315,282 @@ process_state() { printf '%s\n' "${process_stat%% *}" } -stop() { +discard_launched_inhibitor() { + local inhibit_pid="$1" + local recorded_start_time="$2" + local recorded_owner="$3" + local token="$4" + + signal_inhibitor "$inhibit_pid" "$recorded_start_time" "$recorded_owner" "$token" TERM || true + for (( attempt = 0; attempt < 25; attempt++ )); do + process_matches "$inhibit_pid" "$recorded_start_time" "$recorded_owner" "$token" || break + [[ $(process_state "$inhibit_pid" 2>/dev/null || true) == "Z" ]] && break + sleep 0.02 + done + if process_matches "$inhibit_pid" "$recorded_start_time" "$recorded_owner" "$token" && + [[ $(process_state "$inhibit_pid" 2>/dev/null || true) != "Z" ]]; then + signal_inhibitor "$inhibit_pid" "$recorded_start_time" "$recorded_owner" "$token" KILL || true + fi + + if [[ ! -e /proc/$inhibit_pid ]] || [[ $(process_state "$inhibit_pid" 2>/dev/null || true) == "Z" ]]; then + wait "$inhibit_pid" 2>/dev/null || true + fi +} + +signal_inhibitor() { + local inhibit_pid="$1" + local recorded_start_time="$2" + local recorded_owner="$3" + local token="$4" + local signal="$5" + + [[ $recorded_owner == "$caller_uid" ]] || return 1 + [[ $signal == "TERM" || $signal == "KILL" ]] || return 1 + process_matches "$inhibit_pid" "$recorded_start_time" "$recorded_owner" "$token" || return 1 + builtin kill -s "$signal" -- "$inhibit_pid" 2>/dev/null +} + +terminate_inhibitor() { + local inhibit_pid="$1" + local recorded_start_time="$2" + local recorded_owner="$3" + local token="$4" + + signal_inhibitor "$inhibit_pid" "$recorded_start_time" "$recorded_owner" "$token" TERM || true + + for (( attempt = 0; attempt < 50; attempt++ )); do + process_matches "$inhibit_pid" "$recorded_start_time" "$recorded_owner" "$token" || return 0 + [[ $(process_state "$inhibit_pid" 2>/dev/null || true) != "Z" ]] || return 0 + sleep 0.02 + done + + process_matches "$inhibit_pid" "$recorded_start_time" "$recorded_owner" "$token" || return 0 + [[ $(process_state "$inhibit_pid" 2>/dev/null || true) == "Z" ]] && return 0 + return 1 +} + +stop_locked() { + local inhibit_record="" local inhibit_pid="" local recorded_start_time="" - local current_start_time="" + local recorded_owner="" + local token="" local idle_owner="" local current_idle_owner="" + local current_start="" + local failed=0 + local remove_inhibit_state=1 - if [[ -s $idle_owner_file ]]; then - idle_owner=$(<"$idle_owner_file") - if [[ -f $stay_awake_state ]]; then - current_idle_owner=$(<"$stay_awake_state") - fi - if [[ -n $idle_owner && $current_idle_owner == "$idle_owner" ]]; then - omarchy-toggle-idle allow-idle >/dev/null 2>&1 || true + if [[ ! -e $state_dir && ! -L $state_dir ]]; then + return 0 + fi + if ! ensure_private_directory "$state_dir"; then + fail_state_boundary + return 1 + fi + + if [[ -e $idle_owner_file || -L $idle_owner_file ]]; then + idle_owner=$(read_state_record "$idle_owner_file" 1 2>/dev/null || true) + if [[ $idle_owner =~ ^[0-9]+:[0-9]+:[0-9]+$ ]]; then + if [[ -f $stay_awake_state ]]; then + current_idle_owner=$(<"$stay_awake_state") + fi + if [[ $current_idle_owner == "$idle_owner" ]]; then + omarchy-toggle-idle allow-idle >/dev/null 2>&1 || true + fi + else + echo "Ignoring unsafe Omarchy update idle ownership state." >&2 + failed=1 fi - rm -f "$idle_owner_file" + rm -f -- "$idle_owner_file" fi - if [[ -s $inhibit_pid_file ]]; then - read -r inhibit_pid recorded_start_time <"$inhibit_pid_file" || true - if [[ $inhibit_pid =~ ^[0-9]+$ ]]; then - current_start_time=$(process_start_time "$inhibit_pid" 2>/dev/null || true) + if [[ -e $inhibit_pid_file || -L $inhibit_pid_file ]]; then + inhibit_record=$(read_state_record "$inhibit_pid_file" 1 2>/dev/null || true) + if state_file_is_private "$inhibit_pid_file" && + [[ $inhibit_record =~ ^1\ ([1-9][0-9]{0,18})\ ([1-9][0-9]{0,18})\ ([0-9]{1,10})\ ([0-9a-f]{32})$ ]]; then + inhibit_pid="${BASH_REMATCH[1]}" + recorded_start_time="${BASH_REMATCH[2]}" + recorded_owner="${BASH_REMATCH[3]}" + token="${BASH_REMATCH[4]}" + elif [[ $inhibit_record =~ ^([1-9][0-9]{0,18})\ ([1-9][0-9]{0,18})$ ]]; then + # The first update starts the old helper and installs this one before + # cleanup. Its protected same-account record predates launch tokens. + inhibit_pid="${BASH_REMATCH[1]}" + recorded_start_time="${BASH_REMATCH[2]}" + recorded_owner="$caller_uid" + if [[ -e /proc/$inhibit_pid && $(process_state "$inhibit_pid" 2>/dev/null || true) != "Z" ]] && + ! process_matches "$inhibit_pid" "$recorded_start_time" "$recorded_owner" ""; then + current_start=$(process_start_time "$inhibit_pid" 2>/dev/null || true) + if [[ -z $current_start || $current_start == "$recorded_start_time" ]]; then + echo "Cannot verify permission to stop the legacy update inhibitor; retained its state for recovery." >&2 + failed=1 + remove_inhibit_state=0 + fi + fi + else + echo "Ignoring unsafe Omarchy update sleep inhibitor state." >&2 + failed=1 fi - if [[ -n $recorded_start_time && $current_start_time == "$recorded_start_time" ]]; then - kill "$inhibit_pid" >/dev/null 2>&1 || true - - for (( attempt = 0; attempt < 50; attempt++ )); do - current_start_time=$(process_start_time "$inhibit_pid" 2>/dev/null || true) - [[ $current_start_time == "$recorded_start_time" ]] || break - [[ $(process_state "$inhibit_pid" 2>/dev/null || true) != "Z" ]] || break - sleep 0.02 - done - - current_start_time=$(process_start_time "$inhibit_pid" 2>/dev/null || true) - if [[ $current_start_time == "$recorded_start_time" ]] && - [[ $(process_state "$inhibit_pid" 2>/dev/null || true) != "Z" ]]; then - echo "Failed to stop the Omarchy update sleep inhibitor." >&2 - return 1 + if [[ -n $inhibit_pid ]] && (( remove_inhibit_state == 1 )); then + if process_matches "$inhibit_pid" "$recorded_start_time" "$recorded_owner" "$token"; then + if ! terminate_inhibitor "$inhibit_pid" "$recorded_start_time" "$recorded_owner" "$token"; then + echo "Failed to stop the Omarchy update sleep inhibitor." >&2 + failed=1 + remove_inhibit_state=0 + fi fi fi - rm -f "$inhibit_pid_file" + (( remove_inhibit_state == 0 )) || rm -f -- "$inhibit_pid_file" fi rmdir "$state_dir" 2>/dev/null || true + (( failed == 0 )) } -start() { +start_locked() { + local idle_owner="$$:$RANDOM:$RANDOM" + local token="" + local launcher_pid="" + local inhibit_record="" local inhibit_pid="" local inhibit_start_time="" - local inhibit_runner=() - local idle_owner="$$:$RANDOM:$RANDOM" + local inhibit_owner="" + local readiness_attempts=0 - stop - mkdir -p "$state_dir" + stop_locked || return 1 + ensure_private_directory "$state_dir" || fail_state_boundary - if omarchy-cmd-present systemd-inhibit; then - if (( EUID != 0 )); then - if [[ -t 0 ]]; then - sudo -v - inhibit_runner=(sudo) - else - inhibit_runner=(pkexec) - fi + token=$(LC_ALL=C /usr/bin/od -An -N16 -tx1 /dev/urandom | /usr/bin/tr -d ' \n') + [[ $token =~ ^[0-9a-f]{32}$ ]] || return 1 + launch_token="$token" + launch_pending=1 + trap cleanup_pending_launch EXIT + atomic_write_state "$launch_control_file" "active $token" || return 1 + + # The child is identifiable by the token in its arguments from the moment it + # starts. It stays a shell so stop's TERM ends it with a clean exit, since + # systemd-inhibit reports a child killed by a signal as an error. + local hold_command=( + /usr/bin/systemd-inhibit --what=sleep:idle --who=omarchy-update + --why="Omarchy update in progress [$token]" --mode=block + /usr/bin/setpriv --reuid "$caller_uid" --regid "$(/usr/bin/id -g)" --clear-groups + /usr/bin/bash -p -c ' + set -e + umask 077 + state_dir=$1 + token=$2 + owner=$3 + control=$4 + temporary="" + cleanup() { [[ -z $temporary ]] || /usr/bin/rm -f -- "$temporary"; } + trap cleanup EXIT + read -r process_stat <"/proc/$$/stat" + process_stat=${process_stat##*) } + read -r -a fields <<<"$process_stat" + temporary=$(/usr/bin/mktemp "$state_dir/.inhibit-pid.XXXXXXXX") + /usr/bin/chmod 600 "$temporary" + printf "1 %s %s %s %s\n" "$$" "${fields[19]}" "$owner" "$token" >"$temporary" + exec {control_fd}<"$control" + /usr/bin/flock -x "$control_fd" + IFS= read -r control_record <&"$control_fd" + [[ $control_record == "active $token" ]] + /usr/bin/mv -fT -- "$temporary" "$state_dir/inhibit-pid" + temporary="" + /usr/bin/flock -u "$control_fd" + exec {control_fd}>&- + trap - EXIT + trap "kill \$!; exit 0" TERM + /usr/bin/sleep infinity & + wait + ' "--why=Omarchy update in progress [$token]" "$state_dir" "$token" "$caller_uid" "$launch_control_file" + ) + + if (( EUID == 0 )); then + ( + [[ -z ${OMARCHY_UPDATE_LOCK_FD:-} ]] || exec {OMARCHY_UPDATE_LOCK_FD}>&- + exec {state_lock_fd}>&- + exec "${hold_command[@]}" + ) & + launcher_pid=$! + elif [[ -t 0 ]] || { (( update_sudo_session )) && /usr/bin/sudo -n -N /usr/bin/true 2>/dev/null; }; then + # Inside an update without a terminal, reuse its authorization + # non-interactively rather than asking again through polkit. + sudo_options=(-N -b) + [[ -t 0 ]] || sudo_options=(-n -N -b) + if ! ( + [[ -z ${OMARCHY_UPDATE_LOCK_FD:-} ]] || exec {OMARCHY_UPDATE_LOCK_FD}>&- + exec {state_lock_fd}>&- + exec /usr/bin/sudo "${sudo_options[@]}" -- "${hold_command[@]}" + ); then + return 1 fi + else + ( + [[ -z ${OMARCHY_UPDATE_LOCK_FD:-} ]] || exec {OMARCHY_UPDATE_LOCK_FD}>&- + exec {state_lock_fd}>&- + exec /usr/bin/pkexec "${hold_command[@]}" + ) & + launcher_pid=$! + fi - if [[ -n ${OMARCHY_UPDATE_LOCK_FD:-} ]]; then - "${inhibit_runner[@]}" systemd-inhibit \ - --what=sleep:idle \ - --who=omarchy-update \ - --why="Omarchy update in progress" \ - --mode=block \ - sleep infinity >/dev/null 2>&1 {OMARCHY_UPDATE_LOCK_FD}>&- & - else - "${inhibit_runner[@]}" systemd-inhibit \ - --what=sleep:idle \ - --who=omarchy-update \ - --why="Omarchy update in progress" \ - --mode=block \ - sleep infinity >/dev/null 2>&1 & + while :; do + inhibit_record=$(read_state_record "$inhibit_pid_file" 2>/dev/null || true) + if [[ $inhibit_record =~ ^1\ ([1-9][0-9]{0,18})\ ([1-9][0-9]{0,18})\ ([0-9]{1,10})\ ($token)$ ]]; then + inhibit_pid="${BASH_REMATCH[1]}" + inhibit_start_time="${BASH_REMATCH[2]}" + inhibit_owner="${BASH_REMATCH[3]}" + process_matches "$inhibit_pid" "$inhibit_start_time" "$inhibit_owner" "$token" && break fi - inhibit_pid=$! - inhibit_start_time=$(process_start_time "$inhibit_pid" 2>/dev/null || true) - if [[ -n $inhibit_start_time ]]; then - printf '%s %s\n' "$inhibit_pid" "$inhibit_start_time" >"$inhibit_pid_file" + if [[ -n $launcher_pid ]] && ! kill -0 "$launcher_pid" 2>/dev/null; then + wait "$launcher_pid" || return 1 + echo "The update sleep inhibitor did not start." >&2 + return 1 fi - fi + (( readiness_attempts += 1 )) + if [[ -z $launcher_pid ]] && (( EUID != 0 && readiness_attempts >= 100 )); then + echo "The update sleep inhibitor did not become ready." >&2 + return 1 + fi + /usr/bin/sleep 0.05 + done + if [[ -e $launch_control_file || -L $launch_control_file ]]; then + state_file_is_private "$launch_control_file" || return 1 + rm -f -- "$launch_control_file" + fi if [[ ! -f $stay_awake_state ]]; then - printf '%s\n' "$idle_owner" >"$idle_owner_file" - mkdir -p "$(dirname "$stay_awake_state")" - if omarchy-toggle-idle stay-awake >/dev/null 2>&1; then - printf '%s\n' "$idle_owner" >"$stay_awake_state" - else - rm -f "$idle_owner_file" + atomic_write_state "$idle_owner_file" "$idle_owner" || return 1 + mkdir -p "$(dirname "$stay_awake_state")" || return 1 + # The idle toggle uses this marker. Publish its owner in the same write so + # cancellation cannot leave an unowned Stay Awake setting behind. + if ! printf '%s\n' "$idle_owner" >"$stay_awake_state"; then + omarchy-toggle-idle allow-idle >/dev/null 2>&1 || true + return 1 fi fi + launch_pending=0 + omarchy_security_install_sudo_cleanup_traps } case "${1:-}" in - start) - start - ;; - stop) - stop - ;; + start | stop) ;; *) echo "Usage: omarchy-update-stay-awake " >&2 exit 2 ;; esac + +initialize_state_boundary +exec {state_lock_fd}<"$state_base" || fail_state_boundary +flock -x "$state_lock_fd" || fail_state_boundary +directory_is_private "$state_base" "$caller_uid" || fail_state_boundary + +case "$1" in + start) + start_locked + ;; + stop) + stop_locked + ;; +esac diff --git a/bin/omarchy-update-system-pkgs b/bin/omarchy-update-system-pkgs index 9e6f99983571..c2e863882683 100755 --- a/bin/omarchy-update-system-pkgs +++ b/bin/omarchy-update-system-pkgs @@ -10,7 +10,7 @@ set -e # a stream, because an upgrade without --noconfirm prompts on stderr. The # handler has already said why, so no heading here either. if [[ ${OMARCHY_UPDATE_CONFLICT:-} == 1 && ${OMARCHY_UPDATE_INTERACTIVE:-} == 1 ]]; then - exec sudo env OMARCHY_UPDATE_PACMAN=1 pacman -Syu --overwrite '/usr/share/omarchy/*' + exec omarchy-update-pacman -Syu --overwrite '/usr/share/omarchy/*' fi echo -e "\e[32m\nUpdate system packages\e[0m" @@ -23,7 +23,7 @@ trap 'rm -f "$errors"' EXIT # # Progress bars stay on stdout. Errors are on stderr, kept for the conflict # handler below; LC_ALL=C is what keeps them parseable in any locale. -if sudo env LC_ALL=C OMARCHY_UPDATE_PACMAN=1 pacman -Syu --noconfirm \ +if LC_ALL=C omarchy-update-pacman -Syu --noconfirm \ --overwrite '/usr/share/omarchy/*' 2>"$errors"; then cat "$errors" >&2 exit 0 diff --git a/bin/omarchy-upgrade-to-quattro b/bin/omarchy-upgrade-to-quattro index e6a27ee610b6..86f1efcef79d 100755 --- a/bin/omarchy-upgrade-to-quattro +++ b/bin/omarchy-upgrade-to-quattro @@ -965,7 +965,7 @@ populate_legacy_hypr_defaults() { tmp_dir=$(mktemp -d) archive_dir="$tmp_dir/archive" mkdir -p "$archive_dir" - if curl -fsSL https://github.com/basecamp/omarchy/archive/refs/heads/master.tar.gz | tar -xz -C "$archive_dir" && + if curl -fsSL https://github.com/omacom/omarchy/archive/refs/heads/master.tar.gz | tar -xz -C "$archive_dir" && [[ -d $archive_dir/omarchy-master/default/hypr ]]; then cp -a "$archive_dir/omarchy-master/default/hypr/." "$shim_hypr_dir/" fi diff --git a/bin/omarchy-windows-vm b/bin/omarchy-windows-vm index f672ed7eee1d..6c8204da905a 100755 --- a/bin/omarchy-windows-vm +++ b/bin/omarchy-windows-vm @@ -1457,8 +1457,31 @@ To stop: omarchy-windows-vm stop" fi # If scale is less than 130%, don't set any scale (use default 100) - # Connect with RDP in fullscreen (auto-detects resolution) - xfreerdp3 /u:"$WIN_USER" /p:"$WIN_PASS" /v:127.0.0.1:3389 -grab-keyboard /sound /microphone /clipboard /cert:ignore /title:"Windows VM - Omarchy" /dynamic-resolution /gfx:AVC444 /floatbar:sticky:off,default:visible,show:fullscreen $RDP_SCALE + RDP_ARGS=( + "/u:$WIN_USER" + "/p:$WIN_PASS" + /v:127.0.0.1:3389 + -grab-keyboard + /sound + /microphone + /clipboard + /cert:ignore + "/title:Windows VM - Omarchy" + /dynamic-resolution + /gfx:AVC444 + /floatbar:sticky:off,default:visible,show:fullscreen + ) + if [[ -n $RDP_SCALE ]]; then + RDP_ARGS+=("$RDP_SCALE") + fi + + # Connect with RDP in fullscreen (auto-detects resolution). The arguments go + # in over stdin rather than on the command line: /proc//cmdline is + # world-readable, so passing the VM password as /p:"$WIN_PASS" would show it + # to every other user on the machine for as long as the session is open. + # /args-from must stay the only argument here — FreeRDP rejects it outright + # when it is combined with any other, so new flags belong in RDP_ARGS above. + printf '%s\n' "${RDP_ARGS[@]}" | xfreerdp3 /args-from:stdin # After RDP closes, stop the container unless --keep-alive was specified if [[ $KEEP_ALIVE = "false" ]]; then diff --git a/config/hypr/bindings.lua b/config/hypr/bindings.lua index 6da7b938d297..1164a339c2bc 100644 --- a/config/hypr/bindings.lua +++ b/config/hypr/bindings.lua @@ -25,4 +25,4 @@ -- Logitech MX Keys examples: -- o.bind("SUPER + SHIFT + S", nil, "omarchy-capture-screenshot") -- o.bind("SUPER + H", nil, "voxtype record toggle") --- o.bind("SUPER + PERIOD", nil, "omarchy-shell shell toggle omarchy.emojis") +-- o.bind("SUPER + PERIOD", nil, { panel = "omarchy.emojis" }) diff --git a/config/imv/config b/config/imv/config index f96aa6a397f0..5de2530e1f4f 100644 --- a/config/imv/config +++ b/config/imv/config @@ -12,5 +12,5 @@ # Rotate the currently open image by 90 degrees = exec mogrify -rotate 90 "$imv_current_file" -# Edit the current image in Tensaku and quit the viewer - = exec tensaku-edit "$imv_current_file" & ; quit +# Edit the current image in Omasnap and quit the viewer + = exec omasnap "$imv_current_file" & ; quit diff --git a/config/obsidian/user-flags.conf b/config/obsidian/user-flags.conf index 2f9cc08229fd..f29c2242ebba 100644 --- a/config/obsidian/user-flags.conf +++ b/config/obsidian/user-flags.conf @@ -1,3 +1,4 @@ # Obsidian reads this file through the Arch package wrapper. --disable-gpu +--disable-gpu +--ozone-platform-hint=auto --enable-wayland-ime diff --git a/config/omarchy/hooks/pre-refresh-pacman.d/add-custom-repo.sample b/config/omarchy/hooks/pre-refresh-pacman.d/add-custom-repo.sample index cebec4fc8dba..fdc3a871ce1d 100644 --- a/config/omarchy/hooks/pre-refresh-pacman.d/add-custom-repo.sample +++ b/config/omarchy/hooks/pre-refresh-pacman.d/add-custom-repo.sample @@ -1,17 +1,17 @@ #!/bin/bash # This hook is called by `omarchy refresh pacman` AFTER the channel template -# is copied to /etc/pacman.conf and BEFORE `pacman -Syyuu` runs. Use it to -# layer customizations onto the freshly-written pacman.conf so they're -# respected by the upgrade — common cases are adding a custom repository -# (e.g. CachyOS, Chaotic-AUR, an internal company repo) or extra IgnorePkg -# lines. +# is copied and BEFORE the package transaction runs, so your changes shape +# that transaction. Use it to layer customizations onto the freshly-written +# pacman.conf — common cases are adding a custom repository (e.g. CachyOS, +# Chaotic-AUR, an internal company repo) or extra IgnorePkg lines. # -# The hook runs as the invoking user with a warm sudo cache. +# The hook runs as the invoking user after Omarchy invalidates its sudo cache. +# A sudo command here therefore requires its own explicit authorization. # # To put it into use, remove .sample from this file name. -# Example: add an Include line above [core] for a custom repo. +# Example: add an Include line above [core]. # Maintain the repo entries in /etc/pacman.d/custom-repos.conf yourself. CONF=/etc/pacman.conf diff --git a/config/omarchy/shell.json b/config/omarchy/shell.json index e6202da85d90..6603a210a496 100644 --- a/config/omarchy/shell.json +++ b/config/omarchy/shell.json @@ -21,6 +21,9 @@ { "id": "omarchy.indicators" }, + { + "id": "omarchy.elsewhen" + }, { "id": "omarchy.clock", "format": "dddd HH:mm", diff --git a/config/wireplumber/wireplumber.conf.d/kef-lsx-no-suspend.conf b/config/wireplumber/wireplumber.conf.d/kef-lsx-no-suspend.conf new file mode 100644 index 000000000000..02955660051b --- /dev/null +++ b/config/wireplumber/wireplumber.conf.d/kef-lsx-no-suspend.conf @@ -0,0 +1,19 @@ +## Never suspend the KEF LSX II LT USB sink. +## The speaker's USB firmware stops answering control requests when the host +## stops the stream after idle (usb_set_interface -110), and only a replug +## recovers it. Keeping the stream open avoids the trigger. + +monitor.alsa.rules = [ + { + matches = [ + { + node.name = "~alsa_output.usb-KEF_LSX_II_LT.*" + } + ] + actions = { + update-props = { + session.suspend-timeout-seconds = 0 + } + } + } +] diff --git a/default/agents/skills/omarchy/capture.md b/default/agents/skills/omarchy/capture.md index 41a52b6cd205..9c242172cde0 100644 --- a/default/agents/skills/omarchy/capture.md +++ b/default/agents/skills/omarchy/capture.md @@ -10,12 +10,11 @@ omarchy screenshot # Interactive smart-region flow omarchy capture screenshot region # Select a region omarchy capture screenshot windows # Pick a window omarchy capture screenshot fullscreen save # Full screen, straight to disk (no editor) +omarchy capture screenshot scroll # Capture and stitch a scrolling region +omarchy screenshot --editor=overlay # Opt into annotation before output ``` -The first argument picks the mode (`smart|region|windows|fullscreen`), the -second what happens with it (`slurp|copy|save`). `save` skips the annotation -editor and prints the saved path. Screenshots land in the configured Pictures -directory (override with `OMARCHY_SCREENSHOT_DIR`). +The first argument picks the Omasnap mode (`smart|region|windows|fullscreen|scroll`). By default, a capture saves to disk, copies to the clipboard, and shows a preview for 10 seconds. Use the preview's Edit action to annotate, or pass `--editor=overlay` or `--editor=window` to edit before output. A second argument of `copy` or `save` skips the preview and sends the screenshot straight to that destination. Saved screenshots land in `~/Pictures/Screenshots` by default (override with `OMASNAP_SCREENSHOT_DIR`; the legacy `OMARCHY_SCREENSHOT_DIR` is also honored by the Omarchy command). Set `[output] autosave = false` in `~/.config/omasnap/omasnap.conf` to disable automatic saving. ## Screen Recording @@ -33,7 +32,7 @@ Recordings land in the configured Videos directory (override with `omarchy capture webcam resize `. If recording fails to start, rerun with `OMARCHY_SCREENRECORD_DEBUG=true` to -collect a log at `/tmp/omarchy-screenrecord.log` worth attaching to a bug +collect a log at `$XDG_RUNTIME_DIR/omarchy-screenrecord.log` (or `${XDG_STATE_HOME:-$HOME/.local/state}/omarchy/omarchy-screenrecord.log` without a session runtime directory) worth attaching to a bug report. ## Text Capture (OCR) diff --git a/default/agents/skills/omarchy/contributing.md b/default/agents/skills/omarchy/contributing.md index b5fd05335d33..c76c12d61f88 100644 --- a/default/agents/skills/omarchy/contributing.md +++ b/default/agents/skills/omarchy/contributing.md @@ -38,7 +38,7 @@ drag-and-drop in the web form, so save the capture and hand the user the file path to attach (`gh` cannot upload media). For screen-recording failures specifically, rerun with -`OMARCHY_SCREENRECORD_DEBUG=true` and attach `/tmp/omarchy-screenrecord.log`. +`OMARCHY_SCREENRECORD_DEBUG=true` and attach `$XDG_RUNTIME_DIR/omarchy-screenrecord.log` (or `${XDG_STATE_HOME:-$HOME/.local/state}/omarchy/omarchy-screenrecord.log` without a session runtime directory). File the issue with `gh` when available: diff --git a/default/agents/skills/omarchy/hooks.md b/default/agents/skills/omarchy/hooks.md index 4f8236ac0b79..5da16fcc1d77 100644 --- a/default/agents/skills/omarchy/hooks.md +++ b/default/agents/skills/omarchy/hooks.md @@ -14,8 +14,8 @@ file first, if one exists. ├── battery-low.d/ # Low battery (percentage in $1) ├── font-set.d/ # After font change (font name in $1) ├── post-boot.d/ # After the desktop starts -├── post-update.d/ # During `omarchy update`, after system packages and migrations -├── pre-refresh-pacman.d/ # Before `omarchy refresh pacman` re-syncs packages +├── post-update.d/ # At the end of `omarchy update`, after privileged work +├── pre-refresh-pacman.d/ # After `omarchy refresh pacman` re-syncs the package config, before it updates packages └── theme-set.d/ # After theme change (theme slug in $1) ``` @@ -26,3 +26,5 @@ THEME_NAME=$1 echo "Theme changed to: $THEME_NAME" # Add custom actions here ``` + +Update-related hooks run as your user after Omarchy invalidates its sudo timestamp, behind the no-update wrapper. A hook that invokes `sudo` must therefore request its own explicit authorization, and Omarchy revokes the timestamp again before continuing. `post-update` runs after every sudo-capable update stage. `pre-refresh-pacman` runs after `omarchy refresh pacman` re-syncs the package config and before the package transaction, so custom repositories and `IgnorePkg` entries shape that transaction; every later privileged command still authenticates without publishing a reusable timestamp, so a detached child left behind by the hook has nothing to wait for. diff --git a/default/agents/skills/omarchy/hyprland.md b/default/agents/skills/omarchy/hyprland.md index fd518ad3b1a5..fd0e1b623187 100644 --- a/default/agents/skills/omarchy/hyprland.md +++ b/default/agents/skills/omarchy/hyprland.md @@ -36,8 +36,12 @@ Edit `~/.config/hypr/bindings.lua`. Format: ```lua o.bind("SUPER + SHIFT + R", "SSH", "alacritty -e ssh your-server") o.bind("SUPER + B", "Browser", { launch = "chromium" }) -- launch wraps with uwsm-app +o.bind("SUPER + M", "Theme menu", { menu = "theme" }) -- toggle an Omarchy menu route +o.bind("SUPER + N", "Network", { panel = "omarchy.network" }) -- toggle a shell panel ``` +Prefer `{ menu = ... }` and `{ panel = ... }` over running `omarchy-menu toggle ...` or `omarchy-shell shell toggle ...` as a command. Routes and panels listed in `$OMARCHY_PATH/default/omarchy/shortcuts` go straight to the running shell as Hyprland global shortcuts, with no process started on each press; any other route or panel still works, through the command. + View current bindings: `omarchy menu keybindings --print` **IMPORTANT: When re-binding an existing key:** diff --git a/default/bash/init b/default/bash/init index c3d8c97a18b5..d172f8452344 100644 --- a/default/bash/init +++ b/default/bash/init @@ -3,7 +3,7 @@ if command -v mise &> /dev/null; then fi if [[ $- == *i* ]] && [[ ${TERM:-} != "dumb" ]] && command -v starship &> /dev/null; then - eval "$(starship init bash)" + eval "$(starship init bash --print-full-init)" fi if command -v zoxide &> /dev/null; then @@ -18,10 +18,9 @@ if command -v try &> /dev/null; then } fi +# Only the key bindings (Ctrl-R, Ctrl-T, Alt-C): fzf's completion.bash rewraps +# ~76 commands' completions on every shell start, adding ~25ms before the prompt. if command -v fzf &> /dev/null; then - if [[ -f /usr/share/fzf/completion.bash ]]; then - source /usr/share/fzf/completion.bash - fi if [[ -f /usr/share/fzf/key-bindings.bash ]]; then source /usr/share/fzf/key-bindings.bash fi diff --git a/default/hypr/apps/1password.lua b/default/hypr/apps/1password.lua index d57bf651dfb3..156835999195 100644 --- a/default/hypr/apps/1password.lua +++ b/default/hypr/apps/1password.lua @@ -1 +1,3 @@ -o.window("^(1[p|P]assword)$", { no_screen_share = true, tag = "+floating-window" }) +-- 1Password 8.12 renamed its app id from "1Password" to the reverse-DNS form, +-- so match both to keep older installs floating too. +o.window("^(1[pP]assword|com\\.onepassword\\.OnePassword)$", { no_screen_share = true, tag = "+floating-window" }) diff --git a/default/hypr/apps/jetbrains.lua b/default/hypr/apps/jetbrains.lua index 678e823e29f6..1b9658e385d8 100644 --- a/default/hypr/apps/jetbrains.lua +++ b/default/hypr/apps/jetbrains.lua @@ -1,2 +1,2 @@ --- Disable mouse focus (see https://github.com/basecamp/omarchy/pull/5183#issuecomment-4189299971). +-- Disable mouse focus (see https://github.com/omacom/omarchy/pull/5183#issuecomment-4189299971). o.window("^(jetbrains-.*)$", { no_follow_mouse = true }) diff --git a/default/hypr/apps/mullvad.lua b/default/hypr/apps/mullvad.lua new file mode 100644 index 000000000000..ae5f33aefb8b --- /dev/null +++ b/default/hypr/apps/mullvad.lua @@ -0,0 +1,2 @@ +-- Mullvad VPN is a fixed-aspect companion popup; tiling stretches the map. +o.window("^(Mullvad VPN|mullvad-vpn|Mullvad)$", { float = true, center = true, size = { 380, 640 } }) diff --git a/default/hypr/apps/omarchy-shell.lua b/default/hypr/apps/omarchy-shell.lua index 117deb8572aa..a06630f88f90 100644 --- a/default/hypr/apps/omarchy-shell.lua +++ b/default/hypr/apps/omarchy-shell.lua @@ -4,10 +4,13 @@ -- Keep the bar instant: no layer-shell fade/slide animation. hl.layer_rule({ match = { namespace = "omarchy-bar" }, no_anim = true, animation = "none" }) --- Launcher, image selector, emojis, clipboard overlays, and keyboard-driven --- panels should pop without compositor layer fades. Panels keep their own --- QML opacity transition for normal open/close, and skip it for panel handoff. -hl.layer_rule({ match = { namespace = "^(omarchy-menu|omarchy-image-selector|omarchy-emojis|omarchy-clipboard|omarchy-keyboard-panel)$" }, no_anim = true, animation = "none" }) +-- Launcher, image selector, emojis, clipboard overlays, the OSD, reminders, the +-- Wi-Fi QR code and keyboard-driven panels should pop without compositor layer +-- animations. The overlays stay mapped between opens and grow from a parked +-- 1x1 when shown, which Hyprland would otherwise animate as a slide in from +-- the corner. Panels keep their own QML opacity transition for normal +-- open/close, and skip it for panel handoff. +hl.layer_rule({ match = { namespace = "^(omarchy-menu|omarchy-image-selector|omarchy-emojis|omarchy-clipboard|omarchy-keyboard-panel|omarchy-osd|omarchy-reminders|omarchy-network-qr)$" }, no_anim = true, animation = "none" }) -- Dev gallery is the main shell workbench; open it maximized like -- SUPER+ALT+F so component previews have the whole workspace. diff --git a/default/hypr/apps/screenshot-selection.lua b/default/hypr/apps/screenshot-selection.lua index f4e3b2fdeaa3..4c93f703ef58 100644 --- a/default/hypr/apps/screenshot-selection.lua +++ b/default/hypr/apps/screenshot-selection.lua @@ -1,2 +1,5 @@ --- Remove the 1px border around the slurp region selection used by screenshots. +-- Remove the 1px border around the slurp region selection used by recordings, OCR, and QR capture. hl.layer_rule({ match = { namespace = "selection" }, no_anim = true, animation = "none" }) + +-- Keep the Omasnap overlay immediate and out of screen shares. +hl.layer_rule({ match = { namespace = "^omasnap$" }, no_anim = true, animation = "none", no_screen_share = true }) diff --git a/default/hypr/apps/system.lua b/default/hypr/apps/system.lua index 789e3e03e514..043fe12c791f 100644 --- a/default/hypr/apps/system.lua +++ b/default/hypr/apps/system.lua @@ -27,14 +27,15 @@ o.window("org.omarchy.about", { float = true }) o.window("org.omarchy.about", { center = true }) o.window("org.omarchy.about", { size = { 920, 480 } }) -o.window("dev.tensaku.Tensaku", { float = true }) -o.window("dev.tensaku.Tensaku", { center = true }) o.window("omacalc", { float = true }) -- Fullscreen screensaver. o.window("org.omarchy.screensaver", { fullscreen = true }) o.window("org.omarchy.screensaver", { float = true }) o.window("org.omarchy.screensaver", { animation = "slide" }) +-- The launcher picks each screensaver's workspace. A terminal mapped again as it closes lands out of sight instead, +-- where its fullscreen rule cannot take fullscreen from a window. +o.window("org.omarchy.screensaver", { workspace = "special:screensaver silent" }) -- No transparency on media windows. o.window( diff --git a/default/hypr/bindings/applications.lua b/default/hypr/bindings/applications.lua index 0c990e64ae6a..e4428a9fb38a 100644 --- a/default/hypr/bindings/applications.lua +++ b/default/hypr/bindings/applications.lua @@ -1,5 +1,5 @@ -- Essential application bindings. -o.bind("SUPER + RETURN", "Terminal", { omarchy = "terminal" }) +o.bind("SUPER + RETURN", "Terminal", o.launch_terminal()) o.bind("SUPER + SHIFT + RETURN", "Browser", { omarchy = "browser" }) o.bind("SUPER + SHIFT + F", "File manager", { omarchy = "nautilus" }) o.bind("SUPER + ALT + SHIFT + F", "File manager (cwd)", { omarchy = "nautilus-cwd" }) diff --git a/default/hypr/bindings/clipboard.lua b/default/hypr/bindings/clipboard.lua index f095ea5cd648..a44fe1578068 100644 --- a/default/hypr/bindings/clipboard.lua +++ b/default/hypr/bindings/clipboard.lua @@ -42,7 +42,8 @@ local function universal_clipboard_shortcut(default_mods, default_key, terminal_ end end -o.bind("SUPER + C", "Universal copy", universal_clipboard_shortcut("CTRL", "C", "CTRL", "Insert")) -o.bind("SUPER + V", "Universal paste", universal_clipboard_shortcut("CTRL", "V", "SHIFT", "Insert")) +o.bind("SUPER + A", "Select all", send_shortcut_once("CTRL", "A")) +o.bind("SUPER + C", "Universal copy", universal_clipboard_shortcut("CTRL", "C", "CTRL SHIFT", "C")) +o.bind("SUPER + V", "Universal paste", universal_clipboard_shortcut("CTRL", "V", "CTRL SHIFT", "V")) o.bind("SUPER + X", "Universal cut", send_shortcut_once("CTRL", "X")) -o.bind("SUPER + CTRL + V", "Clipboard manager", "omarchy-shell shell toggle omarchy.clipboard") +o.bind("SUPER + CTRL + V", "Clipboard manager", { panel = "omarchy.clipboard" }) diff --git a/default/hypr/bindings/media.lua b/default/hypr/bindings/media.lua index 52779baa8a43..6435c060a0c8 100644 --- a/default/hypr/bindings/media.lua +++ b/default/hypr/bindings/media.lua @@ -1,10 +1,10 @@ -- Volume, brightness, keyboard backlight, and touchpad controls. -o.bind("XF86AudioRaiseVolume", "Volume up", "omarchy-audio-output-volume raise", { locked = true, repeating = true }) -o.bind("XF86AudioLowerVolume", "Volume down", "omarchy-audio-output-volume lower", { locked = true, repeating = true }) -o.bind("XF86AudioMute", "Mute", "omarchy-audio-output-volume mute-toggle", { locked = true }) +o.bind("XF86AudioRaiseVolume", "Volume up", { audio = "raise" }, { locked = true, repeating = true }) +o.bind("XF86AudioLowerVolume", "Volume down", { audio = "lower" }, { locked = true, repeating = true }) +o.bind("XF86AudioMute", "Mute", { audio = "mute-toggle" }, { locked = true }) o.bind("XF86AudioMicMute", "Mute microphone", "omarchy-audio-input-mute", { locked = true }) -o.bind("XF86MonBrightnessUp", "Brightness up", "omarchy-brightness-display +5%", { locked = true, repeating = true }) -o.bind("XF86MonBrightnessDown", "Brightness down", "omarchy-brightness-display 5%-", { locked = true, repeating = true }) +o.bind("XF86MonBrightnessUp", "Brightness up", { brightness = "raise" }, { locked = true, repeating = true }) +o.bind("XF86MonBrightnessDown", "Brightness down", { brightness = "lower" }, { locked = true, repeating = true }) o.bind("SHIFT + XF86MonBrightnessUp", "Brightness maximum", "omarchy-brightness-display 100%", { locked = true, repeating = true }) o.bind("SHIFT + XF86MonBrightnessDown", "Brightness minimum", "omarchy-brightness-display 1%", { locked = true, repeating = true }) o.bind("XF86KbdBrightnessUp", "Keyboard brightness up", "omarchy-brightness-keyboard up", { locked = true, repeating = true }) @@ -21,12 +21,12 @@ o.bind("ALT + XF86MonBrightnessUp", "Brightness up precise", "omarchy-brightness o.bind("ALT + XF86MonBrightnessDown", "Brightness down precise", "omarchy-brightness-display 1%-", { locked = true, repeating = true }) -- Media controls. -o.bind("XF86AudioNext", "Next track", "omarchy-shell media next", { locked = true }) -o.bind("ALT + XF86AudioPlay", "Next track", "omarchy-shell media next", { locked = true }) -o.bind("XF86AudioPause", "Pause", "omarchy-shell media playPause", { locked = true }) -o.bind("XF86AudioPlay", "Play", "omarchy-shell media playPause", { locked = true }) -o.bind("XF86AudioPrev", "Previous track", "omarchy-shell media previous", { locked = true }) -o.bind("ALT + SHIFT + XF86AudioPlay", "Previous track", "omarchy-shell media previous", { locked = true }) +o.bind("XF86AudioNext", "Next track", { ipc = "media.next" }, { locked = true }) +o.bind("ALT + XF86AudioPlay", "Next track", { ipc = "media.next" }, { locked = true }) +o.bind("XF86AudioPause", "Pause", { ipc = "media.playPause" }, { locked = true }) +o.bind("XF86AudioPlay", "Play", { ipc = "media.playPause" }, { locked = true }) +o.bind("XF86AudioPrev", "Previous track", { ipc = "media.previous" }, { locked = true }) +o.bind("ALT + SHIFT + XF86AudioPlay", "Previous track", { ipc = "media.previous" }, { locked = true }) o.bind("XF86Eject", "Eject media", "eject", { locked = true }) o.bind("SHIFT + XF86AudioMute", "Switch audio output", "omarchy-audio-output-switch", { locked = true }) diff --git a/default/hypr/bindings/utilities.lua b/default/hypr/bindings/utilities.lua index 9c03d273edd6..7aa23a4a4787 100644 --- a/default/hypr/bindings/utilities.lua +++ b/default/hypr/bindings/utilities.lua @@ -1,12 +1,12 @@ -o.bind("SUPER + SPACE", "Omarchy menu", "omarchy-menu toggle") -o.bind("SUPER + ALT + SPACE", "Apps menu", "omarchy-menu toggle apps") -o.bind("SUPER + CTRL + E", "Emojis", "omarchy-shell shell toggle omarchy.emojis") -o.bind("SUPER + CTRL + C", "Capture menu", "omarchy-menu toggle capture") -o.bind("SUPER + CTRL + O", "Toggle menu", "omarchy-menu toggle toggle") -o.bind("SUPER + CTRL + H", "Hardware menu", "omarchy-menu toggle hardware") -o.bind("SUPER + SHIFT + code:201", "Omarchy menu", "omarchy-menu toggle root") -o.bind("SUPER + ESCAPE", "System menu", "omarchy-menu toggle system") -o.bind("XF86PowerOff", "Power menu", "omarchy-menu toggle system", { locked = true }) +o.bind("SUPER + SPACE", "Omarchy menu", { menu = "root" }) +o.bind("SUPER + ALT + SPACE", "Apps menu", { menu = "apps" }) +o.bind("SUPER + CTRL + E", "Emojis", { panel = "omarchy.emojis" }) +o.bind("SUPER + CTRL + C", "Capture menu", { menu = "capture" }) +o.bind("SUPER + CTRL + O", "Toggle menu", { menu = "toggle" }) +o.bind("SUPER + CTRL + H", "Hardware menu", { menu = "hardware" }) +o.bind("SUPER + SHIFT + code:201", "Omarchy menu", { menu = "root" }) +o.bind("SUPER + ESCAPE", "System menu", { menu = "system" }) +o.bind("XF86PowerOff", "Power menu", { menu = "system" }, { locked = true }) o.bind("SUPER + K", "Keybindings", "omarchy-menu-keybindings") o.bind("SUPER + ALT + K", "Tmux keybindings", "omarchy-menu-tmux-keybindings") o.bind("SUPER + CTRL + K", "Herdr keybindings", "omarchy-menu-herdr-keybindings") @@ -14,19 +14,19 @@ o.bind("SUPER + CTRL + Q", "Calculator", "omacalc") o.bind("XF86Calculator", "Calculator", "omacalc") o.bind_toggle("SUPER + SHIFT + SPACE", "Toggle top bar", "bar") -o.bind("SUPER + CTRL + SPACE", "Background switcher", "omarchy-menu toggle background") -o.bind("SUPER + SHIFT + CTRL + SPACE", "Theme menu", "omarchy-menu toggle theme") +o.bind("SUPER + CTRL + SPACE", "Background switcher", { menu = "background" }) +o.bind("SUPER + SHIFT + CTRL + SPACE", "Theme menu", { menu = "theme" }) o.bind("SUPER + BACKSPACE", "Toggle window transparency", "omarchy-hyprland-window-transparency-toggle") o.bind("SUPER + SHIFT + BACKSPACE", "Toggle window gaps", "omarchy-hyprland-window-gaps-toggle") o.bind("SUPER + CTRL + BACKSPACE", "Toggle single-window square aspect", "omarchy-hyprland-window-single-square-aspect-toggle") o.bind_toggle("SUPER + CTRL + ALT + F", "Toggle full screen desktop", "fullscreen-desktop") -- xkbcommon names the comma keysym "comma"; the upper-case "COMMA" does not match. -o.bind("SUPER + comma", "Dismiss last notification", "omarchy-shell notifications dismissOne") -o.bind("SUPER + SHIFT + comma", "Dismiss all notifications", "omarchy-shell notifications dismissAll") +o.bind("SUPER + comma", "Dismiss last notification", { ipc = "notifications.dismissOne" }) +o.bind("SUPER + SHIFT + comma", "Dismiss all notifications", { ipc = "notifications.dismissAll" }) o.bind_toggle("SUPER + CTRL + comma", "Toggle silencing notifications", "notification-silencing") -o.bind("SUPER + ALT + comma", "Invoke last notification", "omarchy-shell notifications invokeLast") -o.bind("SUPER + SHIFT + ALT + comma", "Open notification history", "omarchy-shell notifications showHistory") +o.bind("SUPER + ALT + comma", "Invoke last notification", { ipc = "notifications.invokeLast" }) +o.bind("SUPER + SHIFT + ALT + comma", "Open notification history", { ipc = "notifications.showHistory" }) o.bind_toggle("SUPER + CTRL + I", "Toggle locking on idle", "idle") o.bind_toggle("SUPER + CTRL + N", "Toggle nightlight", "nightlight") @@ -82,11 +82,11 @@ hl.on("layer.closed", function(layer) end end) -o.bind("SUPER + CTRL + S", "Share", "omarchy-menu toggle share") +o.bind("SUPER + CTRL + S", "Share", { menu = "share" }) o.bind("SUPER + CTRL + PERIOD", "Transcode", "omarchy-transcode") -o.bind("SUPER + CTRL + R", "Set reminder", "omarchy-menu toggle reminder-set") +o.bind("SUPER + CTRL + R", "Set reminder", { menu = "reminder-set" }) o.bind("SUPER + CTRL + ALT + R", "Show reminders", "omarchy-reminder show") o.bind("SUPER + SHIFT + CTRL + R", "Clear reminders", "omarchy-reminder clear") @@ -95,12 +95,13 @@ o.bind("SUPER + CTRL + ALT + B", "Show battery remaining", "omarchy-notification o.bind("SUPER + CTRL + ALT + W", "Toggle weather", "omarchy-notification-weather") o.bind("SUPER + SHIFT + CTRL + A", "Agent", "omarchy-agent --pick") -o.bind("SUPER + CTRL + A", "Audio", "omarchy-shell shell toggle omarchy.audio") -o.bind("SUPER + CTRL + B", "Bluetooth", "omarchy-shell shell toggle omarchy.bluetooth") -o.bind("SUPER + CTRL + D", "Display", "omarchy-shell shell toggle omarchy.monitor") -o.bind("SUPER + CTRL + ALT + D", "Calendar", "omarchy-shell shell toggle omarchy.clock") -o.bind("SUPER + CTRL + W", "Network", "omarchy-shell shell toggle omarchy.network") -o.bind("SUPER + CTRL + P", "Power", "omarchy-shell shell toggle omarchy.power") +o.bind("SUPER + CTRL + A", "Audio", { panel = "omarchy.audio" }) +o.bind("SUPER + CTRL + B", "Bluetooth", { panel = "omarchy.bluetooth" }) +o.bind("SUPER + CTRL + D", "Display", { panel = "omarchy.monitor" }) +o.bind("SUPER + CTRL + ALT + D", "Calendar", { panel = "omarchy.clock" }) +o.bind("SUPER + CTRL + ALT + E", "World clock", { panel = "omarchy.elsewhen" }) +o.bind("SUPER + CTRL + W", "Network", { panel = "omarchy.network" }) +o.bind("SUPER + CTRL + P", "Power", { panel = "omarchy.power" }) o.bind("SUPER + CTRL + T", "Activity", { tui = "btop" }) -- The letters above name a panel; the numbers count them. 1 is the leftmost diff --git a/default/hypr/helpers.lua b/default/hypr/helpers.lua index 04964703f806..05f8f91e51b8 100644 --- a/default/hypr/helpers.lua +++ b/default/hypr/helpers.lua @@ -1,5 +1,7 @@ -- Shared helpers for Hyprland Lua configuration. +local paths = require("default.hypr.paths") + o = o or {} local function shell_quote(value) @@ -53,6 +55,38 @@ function o.cmd_missing(command) return not o.cmd_present(command) end +-- The global shortcuts the shell registers, read from the same list it reads. +local shell_shortcuts = nil + +local function shell_shortcut_registered(name) + if not shell_shortcuts then + shell_shortcuts = {} + local file = io.open(paths.omarchy_path .. "/default/omarchy/shortcuts", "r") + if file then + for line in file:lines() do + local kind, target = line:match("^(%a+)%s+(%S+)%s*$") + if kind then + shell_shortcuts[kind .. "." .. target] = true + end + end + file:close() + end + end + + return shell_shortcuts[name] == true +end + +-- Reach the shell through its global shortcut when it registers one, so the +-- keypress spawns nothing. Anything else runs the command as before. +local function shell_dispatcher(kind, target, command) + local name = kind .. "." .. target + if shell_shortcut_registered(name) then + return hl.dsp.global("omarchy:" .. name) + end + + return command +end + local function command_from(value, description) if type(value) ~= "table" then return value @@ -60,6 +94,18 @@ local function command_from(value, description) if value.omarchy then return "omarchy-launch-" .. value.omarchy + elseif value.menu then + return shell_dispatcher("menu", value.menu, "omarchy-menu toggle " .. shell_quote(value.menu)) + elseif value.panel then + return shell_dispatcher("panel", value.panel, "omarchy-shell shell toggle " .. shell_quote(value.panel)) + elseif value.audio then + return shell_dispatcher("audio", value.audio, "omarchy-audio-output-volume " .. shell_quote(value.audio)) + elseif value.brightness then + local step = value.brightness == "raise" and "+5%" or "5%-" + return shell_dispatcher("brightness", value.brightness, "omarchy-brightness-display " .. step) + elseif value.ipc then + local target, method = value.ipc:match("^([^.]+)%.(.+)$") + return shell_dispatcher("ipc", value.ipc, "omarchy-shell " .. shell_quote(target) .. " " .. shell_quote(method)) elseif value.focus and value.launch then return o.launch_sole(value.focus, value.launch) elseif value.launch then @@ -114,6 +160,26 @@ function o.launch(command) return "uwsm-app -- " .. command end +-- The command each function bind stands for, so the keybindings menu can still +-- run a bind that Hyprland only reports as Lua. +o.bind_commands = {} + +-- Hand the launcher the focused window's pid, which it would otherwise ask +-- Hyprland for, to open the new terminal in that terminal's directory. +function o.launch_terminal() + local function launch() + local window = hl.get_active_window() + if window and window.pid then + hl.exec_cmd("omarchy-launch-terminal --pid=" .. window.pid) + else + hl.exec_cmd("omarchy-launch-terminal") + end + end + + o.bind_commands[launch] = "omarchy-launch-terminal" + return launch +end + function o.exec_on_start(command) hl.on("hyprland.start", function() hl.exec_cmd(command) diff --git a/default/hypr/nvidia.lua b/default/hypr/nvidia.lua index 663fe79e1bb8..a3a155465503 100644 --- a/default/hypr/nvidia.lua +++ b/default/hypr/nvidia.lua @@ -1,6 +1,7 @@ local paths = require("default.hypr.paths") local nvidia = paths.omarchy_path .. "/bin/omarchy-hw-nvidia" +local nvidia_display = paths.omarchy_path .. "/bin/omarchy-hw-nvidia-display" local nvidia_gsp = paths.omarchy_path .. "/bin/omarchy-hw-nvidia-gsp" local nvidia_without_gsp = paths.omarchy_path .. "/bin/omarchy-hw-nvidia-without-gsp" @@ -8,12 +9,20 @@ local nvidia_without_gsp = paths.omarchy_path .. "/bin/omarchy-hw-nvidia-without -- lspci reads PCI config space, which resumes a runtime-suspended GPU, and on a -- hybrid laptop that wake alone outlasts Hyprland's 1.5s config reload budget. if o.shell_succeeds(o.shell_quote(nvidia)) then + -- On hybrid laptops the display is wired to the iGPU, so forcing NVIDIA's + -- VA-API/GLX drivers globally breaks Chromium-based browsers (black video). + -- Only apply those when NVIDIA actually drives the display. + local nvidia_is_display = o.shell_succeeds(o.shell_quote(nvidia_display)) if o.shell_succeeds(o.shell_quote(nvidia_gsp)) then hl.env("NVD_BACKEND", "direct") - hl.env("LIBVA_DRIVER_NAME", "nvidia") - hl.env("__GLX_VENDOR_LIBRARY_NAME", "nvidia") + if nvidia_is_display then + hl.env("LIBVA_DRIVER_NAME", "nvidia") + hl.env("__GLX_VENDOR_LIBRARY_NAME", "nvidia") + end elseif o.shell_succeeds(o.shell_quote(nvidia_without_gsp)) then hl.env("NVD_BACKEND", "egl") - hl.env("__GLX_VENDOR_LIBRARY_NAME", "nvidia") + if nvidia_is_display then + hl.env("__GLX_VENDOR_LIBRARY_NAME", "nvidia") + end end end diff --git a/default/hypr/qconsole.lua b/default/hypr/qconsole.lua index d3a36ae68002..a512f8ae5ed6 100644 --- a/default/hypr/qconsole.lua +++ b/default/hypr/qconsole.lua @@ -5,6 +5,14 @@ -- How much of the usable screen the console covers, measured from the top. local share = 0.5 +-- A console holding a single window is boxed into a centered panel this many +-- times wider than it is tall, rather than stretched the width of the screen. +-- A second app on the scratchpad gets the full width back: two windows splitting +-- a half-width column is worse than the band this replaced. +local box = 2 + +local SCRATCHPAD = "special:scratchpad" + -- Seed the console with the default agent the first time it opens, rather than -- at boot, so nothing is running until it is wanted. The exec rule has to pin -- the workspace itself: Hyprland only tags a spawn with the workspace it came @@ -23,22 +31,25 @@ hl.config({ }, }) +-- The panel is always flush with the top and always centered, so two numbers +-- describe it: the gap down each side and the gap underneath. +-- -- Refitting replaces the rule in place rather than stacking a new one, but it -- still schedules a monitor and window state refresh, and monitor.focused fires --- on every hop between screens. Most of those hops do not change the number, so +-- on every hop between screens. Most of those hops do not change the gaps, so -- only write the rule when it actually moves. -local covering = nil +local beside, below = nil, nil -local function cover(bottom) - if covering == bottom then - return +local function cover(side, bottom) + if beside == side and below == bottom then + return false end - covering = bottom + beside, below = side, bottom hl.workspace_rule({ - workspace = "special:scratchpad", + workspace = SCRATCHPAD, gaps_in = 0, - gaps_out = { top = 0, right = 0, bottom = bottom, left = 0 }, + gaps_out = { top = 0, right = side, bottom = bottom, left = side }, -- Nothing to highlight in a console that is only ever focused when it is -- open, and the active border reads as a stray frame around a panel that @@ -47,39 +58,136 @@ local function cover(bottom) on_created_empty = seed, }) + + return true +end + +-- One window reads as a console and gets the panel. A second app has turned the +-- scratchpad into a workspace, and a workspace wants the whole width. Only tiled +-- windows count: the gaps are what size the panel, and a floating window on top +-- of the console is not laid out by them. +local function alone() + local tiled = 0 + for _, window in ipairs(hl.get_workspace_windows(SCRATCHPAD)) do + if not window.floating then + tiled = tiled + 1 + end + end + return tiled <= 1 end -- Sizing the console with a window rule would freeze it at whatever the screen -- measured when it first opened, because Hyprland resolves those expressions -- once, as the window maps. Rescaling the monitor afterwards would leave a -- console that is no longer half of anything. Gaps are re-applied by the layout --- instead, so the console is sized by the gap left underneath it and that gap --- is recomputed whenever the monitor layout changes. -local function fit() - local monitor = hl.get_active_monitor() - +-- instead, so the console is sized by the area left around it, and that area is +-- recomputed whenever the monitor it opens on changes. +local function fit(monitor) -- A monitor handle whose output has gone away answers nil to every field, and -- layout changes are exactly when that happens, so this also covers reading - -- height and reserved below. + -- width, height and reserved below. if not monitor or not monitor.scale or monitor.scale <= 0 then - return + return false + end + + -- Width and height are the panel's own pixels, so a monitor turned on its + -- side still reports them the way the panel is built. The odd transforms are + -- the quarter turns, and those are the ones that swap the work area. + local width, height = monitor.width, monitor.height + if monitor.transform % 2 == 1 then + width, height = height, width end -- Monitor dimensions are in physical pixels; gaps are logical, so the scale -- has to come out before the reserved area (already logical) comes off. local reserved = monitor.reserved - local usable = monitor.height / monitor.scale - reserved.top - reserved.bottom + height = height / monitor.scale - reserved.top - reserved.bottom + width = width / monitor.scale - reserved.left - reserved.right + + local tall = math.floor(height * share) + local wide = width + if alone() then + wide = math.min(width, tall * box) + end + + return cover(math.floor((width - wide) / 2), math.floor(height - tall)) +end + +-- The console keeps the geometry of the output it is open on: a follow_mouse hop +-- onto another screen must not resize a console that is already showing. While +-- it is hidden there is nothing to size but the output that will show it next. +local function console_monitor() + local ws = hl.get_workspace(SCRATCHPAD) + local mon = ws and ws.visible and ws.monitor - cover(math.max(0, math.floor(usable * (1 - share)))) + if mon and mon.scale and mon.scale > 0 then + return mon + end + + return hl.get_active_monitor() +end + +local function refit(monitor) + if fit(monitor or console_monitor()) then + -- Land the new gaps in this pass rather than a frame later, so the console + -- does not visibly resize itself once it has already dropped down. + hl.exec_scheduled_prop_refresh_immediately() + end end -- Until a monitor can be read, cover the whole work area rather than leaving --- the console unruled, so it is never seeded without its placement. -cover(0) -fit() +-- the console unruled, so it is never seeded without its placement. A reload +-- runs this again with the console already on screen, so it starts from the +-- output the console is on rather than whichever one the pointer is over. +cover(0, 0) +fit(console_monitor()) + +hl.on("monitor.layout_changed", function() + refit() +end) + +hl.on("monitor.focused", function() + refit() +end) + +-- Special workspaces open on the monitor they are toggled on, not on whichever +-- output last happened to be focused when the rule was written, so these two +-- take the monitor they are handed rather than looking one up. +hl.on("workspace.special_active", function(ws, mon) + if ws and ws.name == SCRATCHPAD then + refit(mon) + end +end) + +hl.on("workspace.move_to_monitor", function(ws, mon) + if ws and ws.name == SCRATCHPAD then + refit(mon) + end +end) + +-- The panel is only centered while the console holds one tiled window, so the +-- count has to be rechecked as apps come and go: opened and closed, moved on or +-- off (Super+Alt+S, Super+Shift+1), and floated or tiled (Super+T, Super+O). +-- window.close is left out, since it still counts the window on its way out and +-- window.destroy follows it anyway. Measured on Hyprland 0.56.2, a move is +-- trailed by several window.update_rules, as is a float toggle, and the last of +-- those always reads the settled count; the earlier ones refit to what the rule +-- already is, which cover() skips. +-- +-- Only while it is on screen, though. A hidden console is refitted on its way in +-- by workspace.special_active, and every window opened anywhere on the desktop +-- would otherwise rewrite the rule. +local function recount() + local ws = hl.get_workspace(SCRATCHPAD) + if ws and ws.visible then + refit() + end +end -hl.on("monitor.layout_changed", fit) -hl.on("monitor.focused", fit) +hl.on("window.open", recount) +hl.on("window.destroy", recount) +hl.on("window.move_to_workspace", recount) +hl.on("window.update_rules", recount) -- The direction names the edge the offset is measured from, not where the -- workspace goes: "slide top" drops it down into view, and "slide bottom" diff --git a/default/hypr/toggles/no-animations.lua b/default/hypr/toggles/no-animations.lua new file mode 100644 index 000000000000..504b3b139650 --- /dev/null +++ b/default/hypr/toggles/no-animations.lua @@ -0,0 +1,20 @@ +-- Draw nothing just for show, for machines that render on the CPU, like a VM: +-- no animations, blur or shadows, and opaque windows, so nothing behind a +-- window has to be blended into it. +hl.config({ + animations = { + enabled = false, + }, + + decoration = { + blur = { + enabled = false, + }, + + shadow = { + enabled = false, + }, + }, +}) + +o.window(".*", { opacity = "1 1" }) diff --git a/default/libalpm/hooks/05-omarchy-passwordless-revoke.hook b/default/libalpm/hooks/05-omarchy-passwordless-revoke.hook new file mode 100644 index 000000000000..f0bce15d324d --- /dev/null +++ b/default/libalpm/hooks/05-omarchy-passwordless-revoke.hook @@ -0,0 +1,12 @@ +[Trigger] +Operation = Upgrade +Operation = Remove +Type = Package +Target = omarchy-settings +Target = omarchy-settings-dev + +[Action] +Description = Revoking temporary Omarchy sudo grants before settings changes... +When = PreTransaction +Exec = /usr/bin/omarchy-sudo-passwordless __package-removing +AbortOnFail diff --git a/default/omarchy/omarchy-menu.jsonc b/default/omarchy/omarchy-menu.jsonc index 7583d8d8ce95..36518d09c4b8 100644 --- a/default/omarchy/omarchy-menu.jsonc +++ b/default/omarchy/omarchy-menu.jsonc @@ -91,17 +91,19 @@ "trigger.toggle.notifications": {"icon":"󰂛","label":"Notifications","action":"omarchy-toggle-notification-silencing"}, "trigger.toggle.crash-capture": {"icon":"󱚡","label":"Crash Capture","action":"omarchy-toggle-crash-capture"}, "trigger.toggle.screensaver": {"icon":"󱄄","label":"Screensaver","action":"omarchy-toggle-screensaver"}, + "trigger.toggle.theme-sync": {"icon":"󰸌","label":"Herdr Theme Sync","when":"omarchy-theme-set-herdr-machines --available","action":"omarchy-toggle-theme-sync"}, "trigger.toggle.nightlight": {"icon":"󰔎","label":"Nightlight","action":"omarchy-toggle-nightlight"}, "trigger.toggle.top-bar": {"icon":"󰍜","label":"Menu Bar","action":"omarchy-toggle-bar"}, "trigger.toggle.battery-percentage": {"icon":"󰁹","label":"Battery Percentage","when":"omarchy-hw-laptop","action":"omarchy-shell omarchy.power togglePercentage"}, "trigger.toggle.workspace-layout": {"icon":"󱂬","label":"Workspace Layout","action":"omarchy-hyprland-workspace-layout-toggle"}, "trigger.toggle.window-gaps": {"icon":"","label":"Window Gaps","action":"omarchy-hyprland-window-gaps-toggle"}, + "trigger.toggle.animations": {"icon":"󰕟","label":"Animations","action":"omarchy-toggle-animations"}, "trigger.toggle.one-window-ratio": {"icon":"","label":"1-Window Ratio","action":"omarchy-hyprland-window-single-square-aspect-toggle"}, "trigger.tests.network-speedtest": {"icon":"󰓅","label":"Network Speed Test","action":"omarchy-shell shell summon omarchy.speedtest"}, "trigger.tests.disk-speedtest": {"icon":"󰋊","label":"Disk Speed Test","action":"omarchy-shell shell summon omarchy.disk-speedtest"}, // Style - "style.theme": {"icon":"󰸌","label":"Theme","aliases":["theme","themes"],"action":"theme=$(omarchy-theme-switcher); [[ -n $theme ]] && omarchy-theme-set \"$theme\""}, + "style.theme": {"icon":"󰸌","label":"Theme","aliases":["theme","themes"],"action":"omarchy-shell shell summon omarchy.image-picker '{\"source\":\"themes\"}'"}, "style.background": {"icon":"","label":"Background","aliases":["background","wallpaper"],"action":"background=$(omarchy-theme-bg-switcher); [[ -n $background ]] && omarchy-theme-bg-set \"$background\""}, "style.unlock": {"icon":"󰟵","label":"Unlock","aliases":["unlock"],"action":"unlock=$(omarchy-plymouth-switcher); if [[ $unlock == default ]]; then omarchy-launch-floating-terminal-with-presentation omarchy-plymouth-reset; elif [[ -n $unlock ]]; then omarchy-launch-floating-terminal-with-presentation \"omarchy-plymouth-set-by-theme $(printf %q \"$unlock\")\"; fi"}, "style.font": {"icon":"","label":"Font","provider":"fonts"}, @@ -167,10 +169,10 @@ "setup.default.editor.vscode": {"icon":"","label":"VSCode","checked":"[[ \"$(omarchy-default-editor)\" == \"code\" ]]","action":"omarchy-default-editor code"}, "setup.default.editor.cursor": {"icon":"","iconFont":"omarchy","label":"Cursor","checked":"[[ \"$(omarchy-default-editor)\" == \"cursor\" ]]","action":"omarchy-default-editor cursor"}, "setup.default.editor.zed": {"icon":"","label":"Zed","checked":"[[ \"$(omarchy-default-editor)\" == \"zeditor\" ]]","action":"omarchy-default-editor zed"}, - "setup.default.editor.sublime": {"icon":"","label":"Sublime Text","checked":"[[ \"$(omarchy-default-editor)\" == \"sublime_text\" ]]","action":"omarchy-default-editor sublime_text"}, + "setup.default.editor.sublime": {"icon":"","label":"Sublime Text","checked":"[[ \"$(omarchy-default-editor)\" == \"subl\" ]]","action":"omarchy-default-editor sublime_text"}, "setup.default.editor.helix": {"icon":"","label":"Helix","checked":"[[ \"$(omarchy-default-editor)\" == \"helix\" ]]","action":"omarchy-default-editor helix"}, "setup.default.editor.vim": {"icon":"","label":"Vim","checked":"[[ \"$(omarchy-default-editor)\" == \"vim\" ]]","action":"omarchy-default-editor vim"}, - "setup.default.editor.emacs": {"icon":"","label":"Emacs","checked":"[[ \"$(omarchy-default-editor)\" == \"emacs\" ]]","action":"omarchy-default-editor emacs"}, + "setup.default.editor.emacs": {"icon":" ","label":"Emacs","checked":"[[ \"$(omarchy-default-editor)\" == \"emacs\" ]]","action":"omarchy-default-editor emacs"}, "setup.plugin": {"icon":"󰐱","label":"Plugins","aliases":["plugin","plugins"]}, "setup.plugin.enable": {"icon":"󰄬","label":"Enable Plugin","action":"omarchy-menu-plugin enable"}, "setup.plugin.disable": {"icon":"󰅖","label":"Disable Plugin","action":"omarchy-menu-plugin disable"}, @@ -182,6 +184,7 @@ "setup.security.fingerprint": {"icon":"󰈷","label":"Fingerprint","when":"omarchy-hw-fingerprint","action":"omarchy-launch-floating-terminal-with-presentation omarchy-setup-security-fingerprint"}, "setup.security.fido2": {"icon":"","label":"Fido2","action":"omarchy-launch-floating-terminal-with-presentation omarchy-setup-security-fido2"}, "setup.security.sshd": {"icon":"󰣀","label":"SSHD","action":"omarchy-launch-floating-terminal-with-presentation omarchy-setup-security-sshd"}, + "setup.security.ssh-agent": {"icon":"󰣀","label":"SSH Agent","when":"! systemctl --user -q is-enabled gcr-ssh-agent.socket","action":"omarchy-launch-floating-terminal-with-presentation omarchy-setup-security-ssh-agent"}, "setup.security.passwordless-sudo": {"icon":"󰟵","label":"Passwordless Sudo","action":"omarchy-launch-floating-terminal-with-presentation omarchy-sudo-passwordless"}, "setup.security.sudoless-docker": {"icon":"󰡨","label":"Sudoless Docker","when":"omarchy-sudo-docker --configured","action":"omarchy-launch-floating-terminal-with-presentation omarchy-setup-security-sudoless-docker"}, "setup.config.hyprland": {"icon":"","label":"Hyprland","action":"omarchy-launch-config-editor \"$HOME/.config/hypr/hyprland.lua\""}, @@ -192,7 +195,6 @@ // Install "install.package": {"icon":"󰣇","label":"Package","action":"xdg-terminal-exec --app-id=org.omarchy.terminal omarchy-pkg-install"}, - "install.aur": {"icon":"󰣇","label":"AUR","action":"xdg-terminal-exec --app-id=org.omarchy.terminal omarchy-pkg-aur-install"}, "install.ai": {"icon":"󱚤","label":"AI"}, "install.service": {"icon":"","label":"Service"}, "install.development": {"icon":"󰵮","label":"Development"}, @@ -213,6 +215,7 @@ "install.terminal": {"icon":"","label":"Terminal"}, "install.tui": {"icon":"","label":"TUI","action":"omarchy-launch-floating-terminal-with-presentation omarchy-tui-install"}, "install.windows": {"icon":"󰍲","label":"Windows","disabled":"[[ -f $HOME/.local/share/applications/windows-vm.desktop ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-windows-vm install'"}, + "install.aur": {"icon":"󰣇","label":"AUR","action":"xdg-terminal-exec --app-id=org.omarchy.terminal omarchy-pkg-aur-install"}, "install.preinstalls": {"icon":"󰏓","label":"Preinstalls","disabled":"[[ ! -f $HOME/.local/state/omarchy/preinstalls-removed ]]","action":"omarchy-launch-floating-terminal-with-presentation omarchy-install-preinstalls"}, "install.browser.chrome": {"icon":"","label":"Chrome","disabled":"omarchy-pkg-present google-chrome","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-install-browser chrome'"}, "install.browser.edge": {"icon":"󰇩","label":"Edge","disabled":"omarchy-pkg-present microsoft-edge-stable-bin","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-install-browser edge'"}, @@ -277,8 +280,8 @@ "install.development.javascript.node": {"icon":"","label":"Node.js","disabled":"[[ -d $HOME/.local/share/mise/installs/node ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-install-dev-env node'"}, "install.development.javascript.bun": {"icon":"","label":"Bun","disabled":"[[ -d $HOME/.local/share/mise/installs/bun ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-install-dev-env bun'"}, "install.development.javascript.deno": {"icon":"","label":"Deno","disabled":"[[ -d $HOME/.local/share/mise/installs/deno ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-install-dev-env deno'"}, - "install.development.php.php": {"icon":"","label":"PHP","disabled":"omarchy-pkg-present php","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-install-dev-env php'"}, - "install.development.php.laravel": {"icon":"","label":"Laravel","disabled":"[[ -x $HOME/.config/composer/vendor/bin/laravel ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-install-dev-env laravel'"}, + "install.development.php.php": {"icon":"","label":"PHP","disabled":"[[ -d $HOME/.local/share/mise/installs/php ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-install-dev-env php'"}, + "install.development.php.laravel": {"icon":"","label":"Laravel","disabled":"[[ -x $HOME/.local/bin/laravel ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-install-dev-env laravel'"}, "install.development.php.symfony": {"icon":"","label":"Symfony","disabled":"omarchy-pkg-present symfony-cli","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-install-dev-env symfony'"}, "install.development.elixir.elixir": {"icon":"","label":"Elixir","disabled":"[[ -d $HOME/.local/share/mise/installs/elixir ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-install-dev-env elixir'"}, "install.development.elixir.phoenix": {"icon":"","label":"Phoenix","disabled":"compgen -G \"$HOME/.mix/archives/phx_new*\"","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-install-dev-env phoenix'"}, @@ -309,6 +312,7 @@ "remove.browser.zen": {"icon":"","label":"Zen","when":"omarchy-pkg-present zen-browser-bin","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-remove-browser zen'"}, "remove.service.dropbox": {"icon":"","label":"Dropbox","when":"omarchy-pkg-present dropbox","action":"omarchy-launch-floating-terminal-with-presentation omarchy-remove-service-dropbox"}, "remove.service.tailscale": {"icon":"","label":"Tailscale","when":"omarchy-pkg-present tailscale","action":"omarchy-launch-floating-terminal-with-presentation omarchy-remove-service-tailscale"}, + "remove.service.ssh-agent": {"icon":"󰣀","label":"SSH Agent","when":"systemctl --user -q is-enabled gcr-ssh-agent.socket","action":"omarchy-launch-floating-terminal-with-presentation omarchy-remove-service-ssh-agent"}, "remove.ai.chatgpt": {"icon":"","iconFont":"omarchy","label":"ChatGPT Desktop","when":"omarchy-pkg-present openai-codex-desktop","action":"omarchy-launch-floating-terminal-with-presentation omarchy-remove-ai-chatgpt"}, "remove.ai.claude": {"icon":"","iconFont":"omarchy","label":"Claude Desktop","when":"omarchy-pkg-present claude-desktop","action":"omarchy-launch-floating-terminal-with-presentation omarchy-remove-ai-claude"}, "remove.ai.dictation": {"icon":"","label":"Dictation","when":"omarchy-pkg-present voxtype-bin","action":"omarchy-launch-floating-terminal-with-presentation omarchy-voxtype-remove"}, @@ -343,8 +347,8 @@ "remove.development.javascript.node": {"icon":"","label":"Node.js","when":"[[ -d $HOME/.local/share/mise/installs/node ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-remove-dev-env node'"}, "remove.development.javascript.bun": {"icon":"","label":"Bun","when":"[[ -d $HOME/.local/share/mise/installs/bun ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-remove-dev-env bun'"}, "remove.development.javascript.deno": {"icon":"","label":"Deno","when":"[[ -d $HOME/.local/share/mise/installs/deno ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-remove-dev-env deno'"}, - "remove.development.php.php": {"icon":"","label":"PHP","when":"omarchy-pkg-present php","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-remove-dev-env php'"}, - "remove.development.php.laravel": {"icon":"","label":"Laravel","when":"[[ -x $HOME/.config/composer/vendor/bin/laravel ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-remove-dev-env laravel'"}, + "remove.development.php.php": {"icon":"","label":"PHP","when":"[[ -d $HOME/.local/share/mise/installs/php ]] || omarchy-pkg-present php","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-remove-dev-env php'"}, + "remove.development.php.laravel": {"icon":"","label":"Laravel","when":"[[ -x $HOME/.local/bin/laravel || -x $HOME/.config/composer/vendor/bin/laravel ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-remove-dev-env laravel'"}, "remove.development.php.symfony": {"icon":"","label":"Symfony","when":"omarchy-pkg-present symfony-cli","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-remove-dev-env symfony'"}, "remove.development.elixir.elixir": {"icon":"","label":"Elixir","when":"[[ -d $HOME/.local/share/mise/installs/elixir ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-remove-dev-env elixir'"}, "remove.development.elixir.phoenix": {"icon":"","label":"Phoenix","when":"[[ -d $HOME/.local/share/mise/installs/elixir ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-remove-dev-env phoenix'"}, diff --git a/default/omarchy/shortcuts b/default/omarchy/shortcuts new file mode 100644 index 000000000000..1bdeeeac5de4 --- /dev/null +++ b/default/omarchy/shortcuts @@ -0,0 +1,40 @@ +# Hyprland global shortcuts the Omarchy shell registers, one per line: a menu +# route to toggle, a panel plugin to toggle, a volume or brightness key, or an +# argument-free IPC call as target.method. A binding written as o.bind(keys, +# description, { menu = "theme" }), { panel = "omarchy.emojis" }, +# { audio = "raise" }, { brightness = "raise" } or { ipc = "media.next" } +# dispatches the matching shortcut straight to the shell, with no process to +# spawn per keypress. Anything missing here still binds, through the +# omarchy-menu, omarchy-shell, omarchy-audio-output-volume or +# omarchy-brightness-display command instead. +menu root +menu apps +menu capture +menu toggle +menu hardware +menu system +menu background +menu theme +menu share +menu reminder-set +panel omarchy.clipboard +panel omarchy.emojis +panel omarchy.audio +panel omarchy.bluetooth +panel omarchy.monitor +panel omarchy.clock +panel omarchy.elsewhen +panel omarchy.network +panel omarchy.power +audio raise +audio lower +audio mute-toggle +brightness raise +brightness lower +ipc media.playPause +ipc media.next +ipc media.previous +ipc notifications.dismissOne +ipc notifications.dismissAll +ipc notifications.invokeLast +ipc notifications.showHistory diff --git a/default/omarchy/sudo-no-update/sudo b/default/omarchy/sudo-no-update/sudo new file mode 100755 index 000000000000..7019a4dc0e27 --- /dev/null +++ b/default/omarchy/sudo-no-update/sudo @@ -0,0 +1,20 @@ +#!/bin/bash -p + +# Preserve sudo options while preventing authentication from refreshing the +# credential cache. Timestamp maintenance and informational modes stand alone. +if [[ $- != *p* ]]; then + echo "Refusing an unsafe Bash startup for the sudo boundary." >&2 + exit 126 +fi +security_entrypoint=$(/usr/bin/readlink -e -- "${BASH_SOURCE[0]}") || exit 126 +source "${security_entrypoint%/*}/../../../bin/omarchy-security-functions" || exit 126 +omarchy_security_require_privileged_bash_startup || exit 126 + +if (( $# == 1 )); then + case "$1" in + -k|--reset-timestamp|-K|--remove-timestamp|-h|--help|-V|--version) + exec /usr/bin/sudo "$@" + ;; + esac +fi +exec /usr/bin/sudo -N "$@" diff --git a/default/plymouth/omarchy.script b/default/plymouth/omarchy.script index 581514d73173..0c9492bd97a6 100644 --- a/default/plymouth/omarchy.script +++ b/default/plymouth/omarchy.script @@ -5,8 +5,6 @@ Window.SetBackgroundBottomColor(0.101, 0.105, 0.149); logo.image = Image("logo.png"); logo.sprite = Sprite(logo.image); -logo.sprite.SetX(Window.GetWidth() / 2 - logo.image.GetWidth() / 2); -logo.sprite.SetY(Window.GetHeight() / 2 - logo.image.GetHeight() / 2); logo.sprite.SetOpacity(1); # Use these to adjust the progress bar timing @@ -22,7 +20,18 @@ global.fake_progress_start_time = 0.0; # Track when fake progress started global.password_shown = 0; # Track if password dialog has been shown global.max_progress = 0.0; # Track the maximum progress reached to prevent backwards movement +# Window size the sprites were last laid out for +global.layout_width = 0; +global.layout_height = 0; + fun refresh_callback() { + # Displays can show up after this script ran, e.g. a Thunderbolt monitor + # whose DisplayPort tunnel comes up after plymouthd started. The window + # grows to the largest display, so re-center everything when it changes. + if (Window.GetWidth() != global.layout_width || Window.GetHeight() != global.layout_height) { + layout(); + } + global.animation_frame++; # Animate fake progress to limit over time with easing @@ -108,27 +117,23 @@ entry.image = Image("entry.png"); bullet.image = Image("bullet.png"); entry.sprite = Sprite(entry.image); -entry.x = Window.GetWidth() / 2 - entry.image.GetWidth() / 2; -entry.y = logo.sprite.GetY() + logo.image.GetHeight() + 40; -entry.sprite.SetPosition(entry.x, entry.y, 10001); entry.sprite.SetOpacity(0); # Scale lock to be slightly shorter than entry field height # Original lock is 84x96, entry height determines scale -lock_height = entry.image.GetHeight() * 0.8; -lock_scale = lock_height / 96; -lock_width = 84 * lock_scale; - -scaled_lock = lock.image.Scale(lock_width, lock_height); -lock.sprite = Sprite(scaled_lock); -lock.x = entry.x - lock_width - 15; -lock.y = entry.y + entry.image.GetHeight() / 2 - lock_height / 2; -lock.sprite.SetPosition(lock.x, lock.y, 10001); +lock.height = entry.image.GetHeight() * 0.8; +lock.width = 84 * (lock.height / 96); + +lock.sprite = Sprite(lock.image.Scale(lock.width, lock.height)); lock.sprite.SetOpacity(0); # Bullet array bullet.sprites = []; +fun position_bullet(index) { + bullet.sprites[index].SetPosition(entry.x + 20 + index * (7 + 5), entry.y + entry.image.GetHeight() / 2 - 3.5, 10002); +} + fun display_normal_callback() { hide_password_dialog(); @@ -165,11 +170,8 @@ fun display_password_callback(prompt, bullets) { for (index = 0; index < bullets_to_show; index++) { if (!bullet.sprites[index]) { # Scale bullet image to 7x7 pixels - scaled_bullet = bullet.image.Scale(7, 7); - bullet.sprites[index] = Sprite(scaled_bullet); - bullet.x = entry.x + 20 + index * (7 + 5); - bullet.y = entry.y + entry.image.GetHeight() / 2 - 3.5; - bullet.sprites[index].SetPosition(bullet.x, bullet.y, 10002); + bullet.sprites[index] = Sprite(bullet.image.Scale(7, 7)); + position_bullet(index); } bullet.sprites[index].SetOpacity(1); @@ -183,19 +185,11 @@ Plymouth.SetDisplayPasswordFunction(display_password_callback); progress_box.image = Image("progress_box.png"); progress_box.sprite = Sprite(progress_box.image); - -progress_box.x = Window.GetWidth() / 2 - progress_box.image.GetWidth() / 2; -progress_box.y = entry.y + entry.image.GetHeight() / 2 - progress_box.image.GetHeight() / 2; -progress_box.sprite.SetPosition(progress_box.x, progress_box.y, 0); progress_box.sprite.SetOpacity(0); progress_bar.original_image = Image("progress_bar.png"); progress_bar.sprite = Sprite(); progress_bar.image = progress_bar.original_image.Scale(1, progress_bar.original_image.GetHeight()); - -progress_bar.x = Window.GetWidth() / 2 - progress_bar.original_image.GetWidth() / 2; -progress_bar.y = progress_box.y + (progress_box.image.GetHeight() - progress_bar.original_image.GetHeight()) / 2; -progress_bar.sprite.SetPosition(progress_bar.x, progress_bar.y, 1); progress_bar.sprite.SetOpacity(0); fun progress_callback(duration, progress) { @@ -216,6 +210,39 @@ fun progress_callback(duration, progress) { Plymouth.SetBootProgressFunction(progress_callback); +#----------------------------------------- Layout -------------------------------- + +# Center the logo, dialogue and progress bar for the current window size +fun layout() { + global.layout_width = Window.GetWidth(); + global.layout_height = Window.GetHeight(); + + logo.sprite.SetX(global.layout_width / 2 - logo.image.GetWidth() / 2); + logo.sprite.SetY(global.layout_height / 2 - logo.image.GetHeight() / 2); + + entry.x = global.layout_width / 2 - entry.image.GetWidth() / 2; + entry.y = logo.sprite.GetY() + logo.image.GetHeight() + 40; + entry.sprite.SetPosition(entry.x, entry.y, 10001); + + lock.x = entry.x - lock.width - 15; + lock.y = entry.y + entry.image.GetHeight() / 2 - lock.height / 2; + lock.sprite.SetPosition(lock.x, lock.y, 10001); + + for (index = 0; bullet.sprites[index]; index++) { + position_bullet(index); + } + + progress_box.x = global.layout_width / 2 - progress_box.image.GetWidth() / 2; + progress_box.y = entry.y + entry.image.GetHeight() / 2 - progress_box.image.GetHeight() / 2; + progress_box.sprite.SetPosition(progress_box.x, progress_box.y, 0); + + progress_bar.x = global.layout_width / 2 - progress_bar.original_image.GetWidth() / 2; + progress_bar.y = progress_box.y + (progress_box.image.GetHeight() - progress_bar.original_image.GetHeight()) / 2; + progress_bar.sprite.SetPosition(progress_bar.x, progress_bar.y, 1); +} + +layout(); + #----------------------------------------- Message -------------------------------- message_sprite = Sprite(); diff --git a/default/systemd/user/omarchy-speaker-tuning.service b/default/systemd/user/omarchy-speaker-tuning.service index 53b374478728..ed6145a95844 100644 --- a/default/systemd/user/omarchy-speaker-tuning.service +++ b/default/systemd/user/omarchy-speaker-tuning.service @@ -1,6 +1,6 @@ [Unit] Description=Omarchy speaker tuning filter-chain -Documentation=https://github.com/basecamp/omarchy/blob/master/docs/audio-tuning.md +Documentation=https://github.com/omacom/omarchy/blob/master/docs/audio-tuning.md # WirePlumber does the linking, so starting before it is up risks the output being # linked before the speaker device has been discovered. After=pipewire.service wireplumber.service diff --git a/default/themed/neovim.lua.tpl b/default/themed/neovim.lua.tpl index ad4353f73f85..82de3c36d18e 100644 --- a/default/themed/neovim.lua.tpl +++ b/default/themed/neovim.lua.tpl @@ -1,6 +1,6 @@ return { { - "bjarneo/aether.nvim", + "omacom/aether.nvim", branch = "v3", name = "aether", priority = 1000, diff --git a/default/themed/vscode-theme.json.tpl b/default/themed/vscode-theme.json.tpl index 0897ca0568d1..08cc795cfac7 100644 --- a/default/themed/vscode-theme.json.tpl +++ b/default/themed/vscode-theme.json.tpl @@ -61,7 +61,7 @@ "textPreformat.background": "{{ background }}", "textSeparator.foreground": "{{ muted }}", - "toolbar.hoverBackground": "{{ background }}", + "toolbar.hoverBackground": "{{ muted }}60", "toolbar.activeBackground": "{{ muted }}", "button.background": "{{ accent }}", @@ -69,7 +69,7 @@ "button.hoverBackground": "{{ blue }}", "button.secondaryForeground": "{{ foreground }}", "button.secondaryBackground": "{{ muted }}", - "button.secondaryHoverBackground": "{{ background }}", + "button.secondaryHoverBackground": "{{ muted }}80", "button.border": "{{ accent }}20", "checkbox.background": "{{ background }}", "checkbox.foreground": "{{ foreground }}", @@ -135,7 +135,7 @@ "tree.indentGuidesStroke": "{{ muted }}", "tree.inactiveIndentGuidesStroke": "{{ muted }}60", "tree.tableColumnsBorder": "{{ muted }}", - "tree.tableOddRowsBackground": "{{ background }}40", + "tree.tableOddRowsBackground": "{{ muted }}20", "activityBar.background": "{{ background }}", "activityBar.dropBorder": "{{ accent }}", @@ -145,7 +145,7 @@ "activityBarBadge.background": "{{ accent }}", "activityBarBadge.foreground": "{{ background }}", "activityBar.activeBorder": "{{ accent }}", - "activityBar.activeBackground": "{{ background }}40", + "activityBar.activeBackground": "{{ muted }}80", "sideBar.background": "{{ background }}", "sideBar.foreground": "{{ foreground }}", @@ -230,8 +230,8 @@ "searchEditor.findMatchBackground": "{{ yellow }}40", "searchEditor.findMatchBorder": "{{ yellow }}", "editor.hoverHighlightBackground": "{{ accent }}20", - "editor.lineHighlightBackground": "{{ background }}60", - "editor.lineHighlightBorder": "{{ background }}00", + "editor.lineHighlightBackground": "{{ mix background foreground 6% }}", + "editor.lineHighlightBorder": "{{ mix background foreground 30% }}", "editorLink.activeForeground": "{{ blue }}", "editor.rangeHighlightBackground": "{{ accent }}10", "editor.rangeHighlightBorder": "{{ accent }}20", @@ -440,18 +440,22 @@ "statusBarItem.activeBackground": "{{ muted }}", "statusBarItem.hoverBackground": "{{ muted }}60", "statusBarItem.hoverForeground": "{{ foreground }}", - "statusBarItem.prominentForeground": "{{ foreground }}", + "statusBarItem.prominentForeground": "{{ background }}", "statusBarItem.prominentBackground": "{{ accent }}", "statusBarItem.prominentHoverBackground": "{{ accent }}80", + "statusBarItem.prominentHoverForeground": "{{ background }}", "statusBarItem.remoteBackground": "{{ accent }}", "statusBarItem.remoteForeground": "{{ background }}", "statusBarItem.remoteHoverBackground": "{{ accent }}80", + "statusBarItem.remoteHoverForeground": "{{ background }}", "statusBarItem.errorBackground": "{{ red }}", "statusBarItem.errorForeground": "{{ background }}", "statusBarItem.errorHoverBackground": "{{ red }}80", + "statusBarItem.errorHoverForeground": "{{ background }}", "statusBarItem.warningBackground": "{{ yellow }}", "statusBarItem.warningForeground": "{{ background }}", "statusBarItem.warningHoverBackground": "{{ yellow }}80", + "statusBarItem.warningHoverForeground": "{{ background }}", "statusBarItem.compactHoverBackground": "{{ muted }}", "statusBarItem.focusBorder": "{{ accent }}", @@ -526,7 +530,7 @@ "keybindingLabel.border": "{{ muted }}", "keybindingLabel.bottomBorder": "{{ muted }}", "keybindingTable.headerBackground": "{{ background }}", - "keybindingTable.rowsBackground": "{{ background }}40", + "keybindingTable.rowsBackground": "{{ muted }}20", "terminal.background": "{{ background }}", "terminal.foreground": "{{ foreground }}", @@ -623,7 +627,7 @@ "settings.checkboxBackground": "{{ background }}", "settings.checkboxForeground": "{{ foreground }}", "settings.checkboxBorder": "{{ muted }}", - "settings.rowHoverBackground": "{{ background }}", + "settings.rowHoverBackground": "{{ muted }}60", "settings.textInputBackground": "{{ background }}", "settings.textInputForeground": "{{ foreground }}", "settings.textInputBorder": "{{ muted }}", @@ -704,12 +708,12 @@ "notebook.editorBackground": "{{ background }}", "notebook.cellBorderColor": "{{ muted }}40", - "notebook.cellHoverBackground": "{{ background }}40", + "notebook.cellHoverBackground": "{{ muted }}40", "notebook.cellInsertionIndicator": "{{ accent }}", "notebook.cellStatusBarItemHoverBackground": "{{ muted }}", "notebook.cellToolbarSeparator": "{{ muted }}", "notebook.cellEditorBackground": "{{ background }}", - "notebook.focusedCellBackground": "{{ background }}60", + "notebook.focusedCellBackground": "{{ muted }}80", "notebook.focusedCellBorder": "{{ accent }}", "notebook.focusedEditorBorder": "{{ accent }}", "notebook.inactiveFocusedCellBorder": "{{ muted }}", diff --git a/default/uwsm/default b/default/uwsm/default index d2ad7cc30db1..ba98b166c91e 100644 --- a/default/uwsm/default +++ b/default/uwsm/default @@ -10,8 +10,8 @@ export TERMINAL=xdg-terminal-exec # Used by terminal programs to open files with the selected Omarchy default editor export EDITOR="omarchy-launch-editor --inline" -# Use a custom directory for screenshots (remember to make the directory!) -# export OMARCHY_SCREENSHOT_DIR="$HOME/Pictures/Screenshots" +# Use a custom directory for screenshots +# export OMASNAP_SCREENSHOT_DIR="$HOME/Pictures/Screenshots" # Use a custom directory for screenrecordings (remember to make the directory!) # export OMARCHY_SCREENRECORD_DIR="$HOME/Videos/Screencasts" diff --git a/docs/elsewhen.md b/docs/elsewhen.md new file mode 100644 index 000000000000..db6e2cc1e19f --- /dev/null +++ b/docs/elsewhen.md @@ -0,0 +1,384 @@ +# Elsewhen + +A world clock for the Omarchy shell: a globe in the bar that opens a panel of clocks, one row per city, with a spinnable globe behind it. It lives in `shell/plugins/panels/elsewhen/` under the plugin id `omarchy.elsewhen`, and file names below are relative to that directory. Its checks live in `test/shell.d/elsewhen/` and run as part of `./test/shell` through `test/shell.d/elsewhen-test.sh`. + +Everything it needs is already on an Omarchy install: `date` and `timedatectl` for zone offsets, and `curl` for weather. Weather is the only thing that touches the network: [Open-Meteo](https://open-meteo.com) geocoding and forecasts, without an API key. The globe's coastlines are [Natural Earth](https://www.naturalearthdata.com) 110m (public domain), shipped as `world.json`. Settings live inline on the widget's `shell.json` entry; see [Settings](#settings). + +## Why it shells out to `date` + +Qt's QML engine has no `Intl`, so JavaScript cannot be asked for the time in an arbitrary IANA zone. Instead a single `date` probe reports each zone's current UTC offset and abbreviation, and the rows tick locally against those offsets. Offsets only move at a DST boundary, so the probe re-runs whenever the panel opens and every five minutes while it stays open. + +## Reordering + +Grab the body of a row and drag it up or down. The row lifts and follows the pointer while the ones it passes step aside by exactly one row; the new order is written to `shell.json` on release. + +Three things make it feel solid: + +**The pointer is measured in the Column, not in the row.** The grab area sits inside the row, and the row is translated as it is dragged - so reading `mouse.y` directly is a feedback loop: the local frame slides out from under a stationary pointer, the offset chases itself, and the row stutters. `mapToItem` into the (never-moving) Column gives a stable reading. + +**The target slot has hysteresis.** Recomputing it freely means a pointer resting near a boundary flips between two slots on sub-pixel movement. The target only changes once the pointer is 0.6 of a row past the current slot, so jitter at a midpoint holds steady. + +**The drop is animated.** On release the row glides the remaining distance into its slot and the reorder commits when it arrives, rather than the row vanishing from under the pointer. Rows making room ease aside too - but the dragged row itself is excluded from that easing, or it lags the cursor. + +The list itself is **not** touched while the pointer moves - rows are displaced with a `Translate` transform, which is purely visual and leaves the Column's layout alone. Reordering the model mid-drag would replace the array the Repeater is built from, rebuild every delegate, and drop the gesture half-way through. + +The grab area stops above the daylight strip, so vertical reordering never competes with the strip's horizontal scrub, and it is declared before the remove button so that keeps its taps. A few pixels of slack are required before a drag arms, so a click is never a reorder. + +## The first run + +A fresh install has no configuration and asks for none. The first time the panel opens it writes its own starting list: **the city you are in, plus four well-known destinations spread round the clock from it** - five rows, so it looks like a world clock immediately rather than an empty box with an "add a city" button. + +The four are chosen **relative to home**. A fixed list would hand someone in Paris a second Paris, and would give a reader in Tokyo a spread that is really a spread around California. From Los Angeles the list comes out as New York, London, Dubai, Tokyo; from Copenhagen as Delhi, Tokyo, Los Angeles, New York. + +Candidates are taken in order of how well known they are, and one is kept only if it is at least three hours from home *and* from every city already picked - so the gap does the spreading rather than a rule about spacing. Spacing four cities evenly round the dial and taking whoever is nearest each mark gives a tidier spread but a stranger list: from Los Angeles it produces Sao Paulo, Cairo, Bangkok and Auckland, which is even but reads like a lottery. If somewhere has too little of the world far enough away - the Pacific, mostly - the three-hour gap relaxes rather than returning a short list. The result is sorted eastward, so the list walks round the world. + +It costs one process: the same `date` probe that reads the local zone also prices the candidate cities on that first run, and never again. The local zone is emitted twice in that probe - once as the `LOCAL` marker and once as an ordinary row - so home's own offset is available like any other city's, which the picker needs and cannot ask for in advance. + +Everything is written to `shell.json` as a normal list, so the first thing anyone can do is delete or reorder it. `test/shell.d/elsewhen-model-test.sh` runs the whole thing from fifteen different home cities, including UTC, Kathmandu's forty-five-minute offset, and the Pacific. + +## Adding and removing cities + +`+ Add a city` opens an inline search over the system's zone list. Clicking a result adds it; hovering a row reveals a `×` in its top-right corner to remove it. The last row cannot be removed. Changes are written straight back to this widget's entry in `~/.config/omarchy/shell.json`, so they survive a restart. + +The search is driven from the keyboard: type, walk the results with the up and down arrows, Return adds the highlighted one, Escape closes. The selection starts on the first match, so the common case - type three letters, press Return - never needs an arrow at all, and it wraps at both ends because the list is six long and entirely on screen. A changed query puts the selection back on the first row: the list under it has been replaced, and Return should not add a city nobody looked at. + +Both lists name the zone and say where it is: `Asia/Kathmandu UTC+5:45`. The name alone does not settle it - half a dozen entries share `America/Los_Angeles`, and `Asia/Kolkata` tells you nothing about India being half an hour off the hour until it says `UTC+5:30`. The offset is absolute rather than relative to you, unlike the `+9h` on a tracked row: a city you have not added yet has no relationship to you yet. + +Search results are not covered by the probe that feeds the rows - that one only knows the cities you track - so the offsets come from a second `date` call over whatever the list is currently showing, at most six zones, coalesced while one is in flight. The answers are merged into what is already known rather than replacing it, so the column does not blank on every keystroke. + +The globe's own **jump box** works the same way - arrows, Return, Escape, selection on the first match, wrapping over five results. Its results grow upward out of the field rather than down from it, but the first match is still at the top of them, so Down moves down the screen and down the list at once. + +**A zone is not a city.** Six of the picker's entries share `America/Los_Angeles`; the name is the only thing telling Oakland from Las Vegas from Los Angeles. Committing a choice passes the label alongside the zone, so picking Oakland puts "Oakland" on the list rather than "Los Angeles". + +The `×` is placed from the corner rather than centered in its target, so how tucked-in it reads does not depend on how big the target is. The target itself is anchored flush into the corner and is larger than the mark, because a corner is the easiest place on a row to hit. + +The search is rendered inline rather than in a dropdown popup: the shared `SearchableDropdown` only ever opens downward, and this panel hangs off a vertical bar low on the screen, so its list would run off the bottom edge. + +Inline, the list grows the panel instead - but only up to the card's cap, the screen's height or `space(680)`, whichever is smaller. Past that the content is clipped to the card and scrolls, and while the search is open the panel follows the results down so the last one is not left clipped against the bottom edge. + +Scrolling is the wheel only. The rows own the pointer - drag-to-reorder and the scrub strip are `MouseArea`s with `preventStealing` - so an interactive `Flickable` would be fighting them for every gesture. + +### City aliases + +The tz database ships one representative city per zone, so most places people actually search for are missing — there is no `Miami`, only `America/New_York`. `CITY_ALIASES` in `Model.js` adds extra search entries pointing at the zone that governs them. Adding a city is a one-line change; the only rule is that the zone must be the one that place actually observes, DST rules included. + +Two cities may share a zone (Miami and Boca Raton are both `America/New_York`), so a row is identified by its label and zone together, and removal is by position. + +## The daylight strip + +Each row carries a 24-hour bar, midnight to midnight in that city's own clock, with the daylight lit and a marker at now. Read down the column and you can see who is awake: markers inside the lit band are in daylight, markers out at the dark ends are not. Rows are also filled by phase, lightest at midday and darkest at night. + +The lit band is the city's real day, from the coordinates the weather lookup already geocodes. Reykjavik's four-hour December day and Auckland's long January one are different shapes, and that difference is most of what a daylight bar is worth looking at. A city the geocoder has not placed yet gets a fixed 06:00-18:00 band until its coordinates arrive. + +The marker turns gold while it is inside the lit band and stays white outside it. That is decided geometrically, from the same span the band draws, not from the phase name - so the sun can never be painted sitting in the dark half of its own bar. The gold is a literal color rather than a theme role, because several themes map the palette name `yellow` to something that isn't yellow. + +`Sun.js` computes the day, built on the globe's own `subsolarPoint` rather than a second copy of the astronomy. Declination comes straight off that function and the equation of time is recovered from it - `subsolarPoint` builds its meridian as `lon = -15 * (utcHours - 12) - eot`, so running that relation backwards hands the correction back with nothing new to keep in step. Local solar noon is found by iterating: the subsolar meridian sweeps west at a steady 15 degrees an hour, so the gap between where the sun is and where you want it converts straight into a time correction, and three passes put the residual under a second. + +`test/shell.d/elsewhen-sun-test.sh` checks it against Open-Meteo's published sunrise and sunset for thirteen cities - both hemispheres, both solstices, the equator, and Kashgar, which runs on Beijing time and sees the sun rise at 08:23 by the clock. The reference rows are held in the test verbatim so it stays offline. + +It is inside a minute at mid-latitudes, and about four minutes at Nuuk and Anadyr, both a little past 64 degrees north. That is the shared low-precision solar position doing what it says: it is good to a fraction of a degree, and near the poles the sun crosses the horizon at such a shallow angle that a fraction of a degree is minutes of time. The two high-latitude cities are in the test with the tolerance they actually need rather than left out. + +A bar can be lit at both ends, and that is not a drawing fault. Reykjavik on the June solstice sets four minutes after midnight, so the first four minutes of the same day are lit too - by the sun that rose the morning before. The day is drawn where it falls and again a day either side, and only the parts that land on the bar survive. + +The arrows do not wrap with it. A sunset at 00:04 belongs to the next bar along, and a mark pinned to this one's edge would claim the sun set at midnight. + +Above the Arctic circle there is no sunrise to plot, and that is a real answer rather than an error: `kind` comes back as `midnightSun` or `polarNight`, the band is the whole bar or none of it, and no arrows are drawn. Longyearbyen in June and in December are both in the test. + +### The arrows + +An up arrow just before the band and a down arrow just after it, shown while the pointer is on that row and outside the lit part rather than on its edge - a mark sitting on the boundary reads as part of the band and gets lost in it. The band already says how long the day is; the arrows say which end is which. They keep off the resting state: five rows each carrying two arrows all the time is a lot of furniture for something looked up rarely. + +They are tucked in close to the band. The tap target is finger-sized and the glyph sits in the middle of it, so a box placed flush against the crossing would leave the arrow half a box away. A nudge closes most of that without letting the glyph touch the band. + +Sunrise sits two pixels high and sunset two pixels low. The glyphs are the same height and the same shape reversed, which is the pair the eye is worst at telling apart at this size. The offset gives a second, coarser cue that needs no reading: the one above the line is the one going up. + +Click one and it prints `Sunrise 6:16 AM` in a small dark chip above the bar - named, not just numbered, because a bare time floating over a row that already has a clock on it has to be worked out from which arrow was clicked. One at a time, and it clears when the pointer leaves the row. + +Above and not below, because below is where the pointer is. The chip floats over the date line, which is why it has a ground of its own, and its colors are inverted in every theme the way a tooltip is. The arrows carry `z: 1` so the chip paints over the row's time block, which is declared after them. + +They are declared after the strip's scrub `MouseArea`. That one covers the whole bar to drag time, and an earlier sibling would never see a press - the same later-sibling rule the remove button relies on. + +An arrow hides while the marker is standing on it. Two things drawn at the same point read as a printing fault, and the arrow is the one that can be spared: it marks a boundary that is not going anywhere, while the marker is the only thing on the bar that says when now is. It follows `nowMarker.x` and not the row's progress, so the arrow comes back exactly as the sun clears it - the marker's motion is eased, and progress is where it is going, not where it is. Hidden rather than faded, because invisible is also untappable: a click on the sun should scrub time the way it does everywhere else on the bar. If the marker covers an arrow whose time is open, the chip closes with it. + +Clicking the marker itself does not name the moon's phase: the marker is also the scrub handle, so aiming at a ten-pixel dot to read a label would nudge the whole list off the hour on every miss. Shift-clicking the moon runs the phase animation instead, which is a deliberate gesture rather than one you land on by aiming badly. + +Clicking anywhere else on the row puts the chip away. A tooltip that can only be dismissed by hitting the same few pixels that opened it is a trap. + +A click on an arrow stops at the arrow: the scrub bar and the row's reorder grab underneath record no press at all, so the scrub bar needs no guard against the arrows drawn on top of it. That is measured rather than reasoned - see [Testing what the pointer does](#testing-what-the-pointer-does). + +A press on the row body does still reach the grab, which dismisses, so the two decisions can meet on one click. Neither rule reads the live value; both are answered from what was showing when the press began, which is the same number whichever runs first. The two rules are `Model.chipAfterTap` and `Model.chipAfterRelease`, and `test/shell.d/elsewhen-model-test.sh` plays a click through both delivery orders across every case: opening, closing, swapping one chip for another, and a release that must not undo a chip opened during the same press. + +## Weather + +Each row shows the current temperature beside the city name, and one glyph beside it: sun, partly cloudy, cloud, rain, or snow. The glyph sits with the temperature because the two are the same fact about being outside. + +Open-Meteo reports WMO present-weather codes - nearly a hundred of them, separating drizzle from freezing drizzle from rain showers. `Model.weatherKind` collapses them to those five, which is all a row has space for; fog joins cloud rather than getting a symbol nobody could read at this size. The code travels with the temperature in the same reading, so the two cannot disagree. + +The sun is `white-balance-sunny`, not `weather-sunny`. The obvious one is a hollow ring inside a six-point burst, which at eleven pixels reads as a snowflake - sitting directly beside an actual snowflake. The one in use is a solid disc with short rays, which cannot be mistaken for anything else in the set. + +`Number(null)` is `0`, and `0` is the WMO code for *clear sky* - so a missing reading would quietly render a sun. Absent values are rejected before the conversion; `test/shell.d/elsewhen-model-test.sh` covers it. + +The panel fetches it with `curl`, in two steps: one geocoding request per city it has no coordinates for yet, then one batched forecast for every city. Both results live in memory as `facts`, keyed `label|zone`. Geocodes last the session (a city does not move) and weather twenty minutes (the resolution the source offers), so opening the panel again soon does no network at all. Nothing here is fatal - a failed fetch keeps the previous value, and failing that the row simply renders without it. + +Cities are geocoded by their **label**, not their zone, which matters for aliases: Miami and Boca Raton share `America/New_York` but resolve to their own Florida coordinates and report genuinely different temperatures. Where a label cannot be geocoded, the zone's representative coordinates from `/usr/share/zoneinfo/zone1970.tab` are the fallback; after a network failure that fallback is used for now and the geocode retried on the next refresh. + +## The hour's greeting + +Point at a row and its date line turns into what people there would actually be saying to each other at that moment: Tokyo at midday says こんにちは, at eight in the evening こんばんは, at three in the morning おやすみ. The pronunciation follows it in grey, because a greeting you cannot say out loud is only a decoration. + +The number is the one thing about a time zone that does not travel. "18:40" is the same symbol in every city on the list and says nothing about what 18:40 *is* there. The greeting is the hour as the people in it experience it. + +The table is three levels deep - a zone belongs to a country, a country is greeted in a language, and a handful of cities override their country - and it is baked into `Greetings.js` and never fetched. Greetings do not change, and nothing the panel draws on hover should need the network. + +Two decisions inside it are judgement calls, and are meant to be: + +**It picks the language you would hear, not the one on the paperwork.** Brussels is French, Dublin is Irish, Hong Kong is Cantonese rather than Mandarin, Nairobi is Swahili. An official-languages list would have made several of these duller and one or two of them wrong. + +**It does not invent an hourly split where a language has none.** Burmese greets you with မင်္ဂလာပါ at any hour and Thai barely moves, so those tables are one and two bands long. A short table is a fact about the language, not a gap in the data. + +The boundaries are where the language moves rather than where a clock does, and the same language disagrees with itself: Spanish in Madrid is still saying *buenas tardes* at 20:00, while Spanish in Lima gave it up an hour earlier. Vienna gets *Grüß Gott* and Zurich *Grüezi* where Berlin gets *Guten Tag*. Indonesian has five bands where English has four - *siang* and *sore* split an afternoon English keeps whole. + +The panel's own monospace family carries none of these scripts. Fontconfig substitutes per character, so a Japanese greeting is set in whatever the system has for Japanese and only the Latin ones stay monospaced; Arabic sits right-to-left with its pronunciation in a separate item beside it, which is what keeps the two from being reordered into each other. + +**Every zone the picker offers is covered.** The picker offers every zone `timedatectl list-timezones` returns - 598 of them, not just the 74 in `cities.json` - so the table is built from the system's own `zone.tab`. English is checked at the source rather than in the result: a zone may only be greeted in English because some country asked for English, and a zone missing from the table is a failure rather than a silent fall-through to English. + +The overrides earn their place by being few. Honolulu is Hawaiian though the United States is English, Montreal is French though Canada is not, and that is nearly the whole list - the country is the right answer almost everywhere. + +`test/shell.d/elsewhen-greetings-test.sh` checks everything around the words - that every zone the picker can offer maps to a language, that no hour of any day falls into a gap, that adjacent bands actually differ, and that every non-Latin greeting carries a pronunciation while no Latin one does. The words themselves are the one thing here with no independent reference on this machine, and they want a speaker's eye rather than a test. + +### The legacy aliases + +The zone table matches each zone's *compiled* zoneinfo file against the ones in `zone.tab`. That is exact for real zones and wrong for the legacy aliases, because an alias shares its rules with whatever zone the tz database linked it to - chosen for keeping identical time, not for being anywhere near it. `Iceland` keeps Abidjan's clock all year, so it would match Burkina Faso and say *Bonjour*; `NZ` would match Antarctica, `Asia/Rangoon` the Cocos Islands, `Africa/Asmera` Djibouti. + +Following the tz link table instead does not help: that returns the country of the *canonical* zone, which for `Iceland` is Côte d'Ivoire and for `Pacific/Truk` is Papua New Guinea. There is no rule available here, only places, so the fifteen are named by hand in `ALIAS_COUNTRY` and `countryFor` reads that first. + +Two that look like mistakes and are not: `Antarctica/South_Pole` really is in Antarctica and `Pacific/Ponape` really is in Micronesia, whatever zones they share their rules with. `Europe/Simferopol` stays Ukrainian, which is a choice rather than a lookup. + +The test checks each alias against the canonical zone for the *same place* - `Iceland` against `Atlantic/Reykjavik`, `Pacific/Truk` against `Pacific/Chuuk` - which is an answer that does not come from the table being tested. + +## Time scrubber + +Drag any row's daylight strip and **every** clock moves together, so you can ask "if I propose 3pm, what am I doing to Auckland?" and see the answer rather than compute it. The header shows the shifted time in the accent color with the offset from now (`+3h`), so a scrubbed clock can never be mistaken for the real one. Release and it holds for a couple of seconds - long enough to read - then returns to the present. Closing the panel also returns it. + +The drag maps *absolutely*: the pointer's position across the strip is a local time-of-day for that city, measured against the unscrubbed present, so a drag cannot accumulate drift. It resolves to the nearest occurrence of that time, so dragging slightly left means an hour ago, never twenty-three hours on. + +The rows are modelled on the zone list rather than on the computed clock rows. The clock rows are a binding on the scrubbable, ticking time, so using them as the model would rebuild every delegate on every tick and destroy the `MouseArea` mid-gesture, turning every drag into a single click. + +`test/shell.d/elsewhen-model-test.sh` covers the scrub arithmetic, including scrub direction and the short way round midnight. + +## Globe mode + +Tapping the globe in the header does not swap one view for another: the globe **grows out of the little circle** and shoves the rows aside, and the panel opens out around it. Tapping the cross that takes its place in the circle reverses the whole thing. + +One number, `zoom`, runs from 0 (the list) to 1 (the globe). Everything is a function of it - the stage's height, each row's displacement, the globe's scale and position, the cross in the header, the globe's own footer and search bar - so no part of the transition can fall out of step with any other. The animation is on `zoom` alone: 800ms `OutQuart` opening, which spends its speed early and then settles, and a brisker 500ms `InOutCubic` coming back. + +**Hold Shift while clicking** to run the whole thing at a third speed - the gesture macOS uses for slow-motion window animations, and free here because every Hyprland binding is SUPER-prefixed. Because one number drives everything, slowing that number slows the rows, the fades and the globe's chrome with it. + +The duration and easing are set *before* `globeMode` is flipped, never derived from it. Deriving them from `globeMode` inside the animation is a race - it is the very property whose change starts the animation - and losing that race means an opening transition runs with the closing duration. Every path into globe mode goes through `setGlobeMode` for that reason. + +The globe is scaled about **the center of its own disc**, not the center of its box, so it grows from where it is drawn; the translation then carries that center between the little circle and the middle of the stage. The two globes trade places with a quick crossfade while they are still the same size and in the same spot, so there is never a moment with two of them on screen. + +Rows are shoved in sequence rather than together - each waits its turn, then covers the rest of the distance - so it reads as something arriving from above rather than the list simply leaving. They tilt, shrink, and are thrown a long way sideways in alternating directions. + +They do not fade at all: they fall **clear off the bottom of the panel**. The distance is measured from the list at rest plus a margin, so even the topmost row - which has the whole list below it to fall past - is gone by the end. The fall is squared against the zoom so it accelerates rather than easing out, the way a dropped thing does. + +Everything involved is **opaque**. The globe's ocean and the row cards mix their tones against the panel background and return a color with no alpha, rather than painting low-alpha foreground over it. That looks identical at rest and correct in motion: the globe arrives as a solid object in front of the list rather than as a tinted pane the rows show through. + +The **stage is not clipped**, because at the start of the flight the globe is still up in the header above it and clipping would cut it in half exactly when it is meant to look like the little circle. The rows are clipped instead, by a separate item, so they slide out of the panel rather than piling up past its edge. The globe is **loaded on hover**, not on click, so reading its two data files never lands in the middle of the animation. + +### What it shows + +A spinnable orthographic globe: coastlines, a graticule, the day/night terminator, and a major city for every time zone. Drag to spin (it keeps going and eases to a stop), drag vertically to tilt, and tap a city to read its local time in the footer. Tapping the hero globe again returns to the list, and closing the panel returns to it too - the list stays the way in. + +City names are drawn **in two tones**: light over the sea, dark over the land. They are painted twice - once light over everything, then again dark through a clip of the continents - so a name straddling a coastline comes out dark on its land half and light on its sea half, and every part of it sits against something it contrasts with. An outline cannot do this; it only fattens the letters and dulls both halves. Tracked and home cities keep their distinction through weight and their dot rings rather than label color. + +Names are placed to the left of their dot when placing them to the right would run off the panel, so nothing is truncated at the edge. + +On each row's daylight strip the marker is **gold by day and the moon by night** - not a plain pale dot, but tonight's actual phase, with the unlit part bitten out of it. Sun and moon are the same size: they are the same marker in the same place meaning the same thing, so only their content differs. The whole disc is always drawn faintly underneath, so the marker never disappears at new moon. + +**Shift-click a moon** to walk it through a full lunation and back - the moon is nearly always somewhere unremarkable, so without this there is no way to see that the marker really is drawing a phase. It runs about five seconds, tweening between eight stops, then drops straight back to the real phase (the tween is disabled for that last step, or it would run the month backwards on the way). + +It is one element carrying two facts rather than a new thing on the row, which is the only reason it earns its place. The phase follows the scrubber too, so dragging time walks the moon through its month. + +`GlobeModel.moonPhase` is the mean synodic month against a known new moon - enough to draw a phase, not enough to predict an eclipse. It drifts from the true lunation by up to about half a day, which is under 6% of illumination and sub-pixel on a marker this size. `test/shell.d/elsewhen-globe-test.sh` pins it against five eclipses, which are the one thing that fixes a lunation to a wall clock: a solar eclipse can only happen at new moon and a lunar eclipse only at full. The drawn shape is checked by rasterising it and counting lit pixels against the illumination formula. + +City dots on the globe use the same rule as the list: gold in daylight, pale at night. + +**The city you are in is always on the globe**, always labelled, and drawn the way the panel globe draws it - the dot in the accent color, a dark edge so it does not vanish into the land, and a halo. It is merged in ahead of everything else, so a built-in or a tracked row of the same name cannot shadow it. + +**Cities the list is tracking** get an accent ring around the dot, and first claim on a label slot so they are always named. Matching is by city name, not zone - tracking Miami does not light up New York, because they are different cities that happen to share `America/New_York`. A tracked city that is not one of the globe's own built-ins is merged in using the coordinates the weather script already geocoded, so a city in the list can never be missing from the globe. + +Dots are thinned in screen space before anything is drawn: candidates are offered in priority order and one is kept only if it clears the others by a minimum distance, so a dense region like western Europe shows a few legible cities instead of a smear of overlapping dots. Tracked cities and the current selection are exempt and always survive. The survivors change as the globe turns or the panel resizes, since the test is in pixels rather than degrees. + +Labels are then placed greedily over the survivors with collision avoidance, so names appear and disappear as the globe turns rather than piling up. + +**A city's label is part of its click target.** A two-pixel dot is a hard thing to hit, so label boxes are tested first - before dots - because a label sits beside its own dot and would otherwise lose the proximity test to a neighbouring city. + +**A moving globe is drawn with less in it.** A full paint measures about 14ms - already over a 120Hz frame at 8.3ms - and every frame of movement repaints the whole canvas, because the projection changes, whether the globe is riding the zoom, being dragged, or coasting after a throw. + +Two things dominate that paint: the city names, which cost a layout pass and two passes of text, one of them through a clip built from every coastline ring; and the graticule, 17 stroked polylines. Both are dropped while the globe is in motion and come back the moment it settles, which roughly halves the cost. Nothing is lost that could be read - names on a turning globe are a smear, and mid-zoom the whole thing is a few dozen pixels across. + +Below half size the coastline is drawn at half its vertices as well. That one is tied to how big the globe is being drawn rather than to whether it is transitioning, because the zoom's ease-out spends its slow tail near full size, where the missing islands would be visible and would then snap back in. + +Measured over the open transition, with `smoothMotion` off and on: average paint 11.6ms to 7ms, and the worst gap between frames 105ms to 45ms. Set `smoothMotion` to `false` to draw everything, always. + +**Everything drawn scales with the shell.** Stroke widths and marker radii go through `GlobeModel.scalePx` rather than being pixel literals, because the globe's radius and its labels already follow the shell's base font size, and literal widths would read as proportionally thinner as that size grows. The small globe derives its widths from its own radius, which the large globe cannot do, its radius being hundreds of pixels rather than tens. Widths are floored at one pixel, below which a stroke stops reading as a thin line and starts dropping out of the raster. + +Nothing here touches the network at runtime. The coastlines are Natural Earth 110m, simplified with Douglas-Peucker to 68 rings and 1337 points (14 KB), and the cities were geocoded once at build time - both are plain data files in the plugin. Zone offsets come from the same `date` probe the list uses. + +`test/shell.d/elsewhen-globe-test.sh` covers the projection and solar maths, including a check of the terminator against Open-Meteo's `is_day` for every city. + +### One selection, two views + +The list and the globe are two views of the same choice, so they hold it together. Clicking a row and then opening the globe lands on that city rather than resetting to home, and picking a city on the globe moves the list's focus so the header and the small globe are already on it when the globe closes. + +Picking a city on the globe also brings it round to face you, as opening the globe does for home and the jump box does for what it finds - a city chosen near the limb would otherwise sit where the projection is most foreshortened. Only a hit turns the globe: a tap on open ocean clears the selection and leaves the view alone. + +The pick is `pickAt(x, y)` on the globe's root rather than a body inside the `MouseArea`, so the same code the pointer runs can be driven from a test or over IPC. This desktop cannot inject a pointer at all, and a copy of the logic in a test would be free to drift from the one the mouse actually reaches. + +A globe city the list does not track is the ordinary case - the globe draws every zone's main city, the list holds the handful you chose - and it leaves the list where it was. There is no row to focus, and sending the list home would move it somewhere nobody asked to go. Clicking empty ocean is the same story from the other side: it clears the globe's selection, but the globe's "no city" and the list's "home" are different states and forwarding one as the other would be a lie. + +The list's own focus is held the same way. `focusKey` is the city's `label|zone` and the row number is derived from it, because `zones` is a binding too - replaced wholesale on a reorder or a removal - so a stored index would silently come to mean a different city. Deriving the index means a reorder carries the focus with the city and removing the focused city drops it back to home. + +The crossing is made on `label|zone`, not on an index. The two views index different things - a row is an index into the settings list, the globe's selection is an index into its own catalogue of everything it draws - and that catalogue is a binding, rebuilt whenever the home row, a tracked city's coordinates or a session city lands. A key survives the rebuild. `test/shell.d/elsewhen-model-test.sh` covers the crossing, including the untracked city and the case where both fields have to agree. + +### Jumping to a city + +The bar at the bottom searches the whole zone catalogue - every IANA city plus the aliases - and turns the globe to whatever is picked, centering it by setting the spin to the city's longitude and `viewLat` to its latitude, taking the short way round. + +A city already on the globe is flown to immediately. One that is not is added **for this session only**: the panel geocodes it, and the globe flies there once the coordinates arrive. Nothing is written to `shell.json`, so there is no saved list to delete from, order, or migrate. Want it again, type it again. + +Results are drawn over the globe rather than growing the panel, so the globe does not resize under the pointer while a search is being typed. + +### Turning it off + +Set `globeEnabled` to `false` on the widget's `shell.json` entry. The hero stops being a button and the globe's Loader never activates; nothing else changes. + +### The footer under the globe + +Two lines: the city with its time, and under it the zone with its offset. Opening the globe selects home, so the footer is never empty under a marker sitting plainly on a city. + +A mark sits against the city's name, the same one the rows carry on their strips: a lit dot by day, tonight's moon by night. It is judged by this globe's own daylight, so it agrees with the dot drawn on that same city an inch above it. + +It is sized off the name it stands next to rather than set in pixels, and it stands on the same baseline, so it occupies exactly the band the capital does - never above the cap, never below the letters. `tightBoundingRect` on a capital M gives the ink of the glyph; the mark is one pixel under that, which rasterises to the same 14 device pixels, because a circle's antialiased edge reads a pixel wider than a glyph's stem. Any smaller and the moon reads as a bullet point; a crescent needs room to be a crescent. + +It is not placed with `anchors.baseline`: inside a Row, anchoring to a sibling whose own position depends on the Row's height is a loop, and QML settles it by dropping the dot onto the line below. A Row leaves `y` alone, so both items start at its top and the dot's underside is placed on the baseline directly - `Text.baselineOffset` is the ascent of its first line, the same number the glyph itself is drawn from. + +The mark and the name are their own Row inside the line, so the gap between them can be tighter than the gaps after them - the mark belongs to the name, not to the row of facts. + +There is no "daylight" or "night" word after the time: the city markers and the terminator already say it in the picture. The line cannot fit on one row - "Johannesburg Africa/Johannesburg UTC+2 7:50 PM" runs off the end of the panel - so it is two caption lines, which the footer's reserved height already holds. + +The parts of that line are anchored to a named `footer` id rather than reached through `parent.parent`, because QML resolves a chain that falls a step short to `undefined` in silence. + +## The hero globe + +The globe in the header is drawn, not a glyph, by `MiniGlobe.qml`. A glyph cannot spin: rotating a flat image about the vertical axis squashes it to a line and flips it, which reads as a coin. A sphere keeps its circular outline and moves only its surface across it - so the disc is constant and the graticule and coastlines are re-projected as the spin advances, using the same orthographic projection as globe mode and the same `world.json`. + +Landmasses are filled rather than outlined, and only rings above a size threshold are drawn: at icon size an outline is a scribble and an island is a speck of dirt on the lens. The rim is stroked last so nothing spills over it. + +Both globes fill their continents from the same clipping code in `GlobeModel.js`. Neither strokes a coastline over the fill: the fill's own edge *is* the coastline, and a second pass over every ring is the expensive half. Measured on the large globe, per repaint: outlines only 8.1ms, fill plus outline 13.4ms, **fill alone 9.1ms** - so the filled look costs about 1ms over outlines, against a 16.7ms frame budget. + +Filling means labels and city dots cross light land as often as dark ocean, so labels are outlined and every dot carries a dark edge. + +Clipping a coastline to the visible hemisphere has to produce **one** polygon per ring. Keeping each visible run and closing it makes self-intersecting shapes whose area jumps whenever a run splits, and that is visible: continents morph and pulse at the limb, worst as the spin slows. Sutherland-Hodgman against the hemisphere keeps the ring whole, and walking the limb between an exit and the next entry (rather than cutting straight across) makes the silhouette continuous. Measured over a full rotation, the worst area change per quarter-degree of spin goes from 356 px^2 (split runs) to 278 (whole ring, chords) to **3.5** (whole ring, limb arcs) on a 2463 px^2 disc. `test/shell.d/elsewhen-globe-test.sh` holds it there. + +The globe leans by `GlobeModel.AXIAL_TILT` - 23.44 degrees, the real obliquity, and the same constant the subsolar calculation uses. + +It is drawn at full strength and oversized rather than sitting at text weight: as the centerpiece a dimmed thin globe just reads as washed out. + +A marker shows the city you are in, in the accent color. It carries a dark edge: the marker can be nearly the same lightness as the filled continents, and without one the dot dissolves into whichever landmass it is sitting on. + +**The globe opens on the city you are in.** It flies there as the panel zooms out, so the two motions - growing out of the header and turning round to home - land together rather than one after the other. If your coordinates have not arrived yet, which happens on a cold geocode cache, the request is held and runs the moment they do. + +**Clicking a city row turns the globe to it** and marks it - so a tap on Tokyo swings the globe round and drops the marker on Japan. It takes the shortest way round rather than always turning forward: Los Angeles to Tokyo is 102 degrees west, not 258 east. + +While the globe is showing somewhere else, clicking the header line brings it home. The whole line is the target, not just the name, and it is only live while the globe is away, so it is never a dead click target. Reopening the panel also returns it home. + +The opening spin **lands on home** - the animation runs from `homeLon - 1080` to `homeLon`, three whole turns that finish with your own meridian facing you. At rest a `Binding` holds the globe there, standing down while the animation is writing the property. Until the weather script has geocoded your city the marker is hidden and it rests on Greenwich. + +`Easing.OutQuart` over 1250ms puts most of the rotation in the first third and lets the rest coast out, which is what a globe flicked by hand does rather than a motor driving it at a constant rate. + +## Where "here" is + +The header reads "It's 10:28 AM here in Los Angeles." rather than a bare "here", which names your own city without spending a row on it. The zone comes from the same `date` probe the rows use - one extra `LOCAL|` line, from `timedatectl` - so it costs no additional process and follows a time-zone change on the next refresh. + +The city name is the zone's last segment, and the tz database names zones after a *representative* city: someone in Boca Raton would read "here in New York". Tap your city on the globe to fix that: a city on this machine's zone becomes `homeCity`, and the header and home pin follow it. Tapping the zone's own city clears the choice, and a city on another zone leaves it alone, since the time beside the name is still this machine's. + +## Two offsets, one line + +A row's offset reads `+2h` - how far that city is from you - until you click it, and then every row reads `UTC-5` instead. Both are the same fact from different ends: the relative offset answers "how far ahead are they", the absolute one answers "where is this place", and the click is cheaper than printing both and doubling the width of the line. + +It is one setting for the whole list rather than one per row. A column where each row had picked its own units would be unreadable, and the point of a column is that it can be read down. The choice is stored, so it survives a restart. + +The tap target sits on the offset itself, and works because it is declared late: the drag handle covers the whole body of the row, and later siblings win the tap - the same rule the remove button relies on. + +The globe's footer reads the same setting and offers the same click, so the offset under the globe is never in different units from the offset in the list you just came from, and flipping it in either place flips it in both. There the target is the zone name as well as the number: on your own home city the relative offset is blank, and a control that disappears on one city out of the list is not a control. + +The globe does not own the setting. It publishes `offsetModeToggleRequested` and the panel flips it; the new mode arrives back down the same binding as every other property, so there is only one place the mode can live. + +## Units and notation, on a click + +The temperature and the time are both controls. Click any temperature to swap the whole list between Celsius and Fahrenheit; click any time to swap it between 12- and 24-hour. Both work the way the offset does - one setting for every row, changed where you are already reading rather than in a settings pane, and written straight to `shell.json` so it survives a restart. + +One setting for all rows, not one per row, for the same reason the offsets move together: every clock here exists to be read against the others. + +The starting notation follows the machine. With `hour24` unset, the locale's own short time format decides: `Qt.locale().timeFormat` gives `h:mm Ap` for `en_US` and `en_AU`, `HH:mm` for `en_GB`, `de_DE`, `fr_FR` and `zh_CN`, `H:mm` for `ja_JP` and `H.mm` for `fi_FI`. The test is the AM/PM designator rather than the case of the hour letter - `h` means 1-12 and `H` means 0-23, which is the same answer, but a locale may spell a 24-hour clock with either while a designator only ever belongs to a 12-hour one. Quoted literal text is stripped first, because some locales write the separator as `H'h'mm`. + +Those patterns were read off the running shell, and the ones that matter are in `test/shell.d/elsewhen-model-test.sh` verbatim - including the detail that Qt spells the designator `Ap` and puts U+202F in front of it, not a space. + +The starting unit follows the machine too. With `units` unset, `Qt.locale().measurementSystem` decides: the US system means Fahrenheit and everything else means Celsius. `en_US` reports `ImperialUSSystem`, `en_GB` reports `ImperialUKSystem` and `de_DE` and `ja_JP` report `MetricSystem`, so the rule gives Britain Celsius, which is what Britain uses for weather whatever else it measures in miles. + +The rule is Qt's CLDR data and it is not a survey of thermometers: Liberia, which does use Fahrenheit day to day, reports as metric. That is what the click is for. An explicit `C` or `F` always wins over the automatic answer, so one click is the whole escape hatch, and `""` puts it back on the system's units. `Model.resolveUnits` holds those rules and `test/shell.d/elsewhen-model-test.sh` covers them, including the junk values a hand-edited `shell.json` can produce. + +## Testing what the pointer does + +No pointer can be injected into the running shell, but `qmltestrunner` synthesises real mouse events into an offscreen window, and the structures worth checking are small enough to rebuild in a test: + +```bash +QT_QPA_PLATFORM=offscreen /usr/lib/qt6/bin/qmltestrunner -input test/shell.d/elsewhen/qml +``` + +Use that full path. `/usr/bin/qmltestrunner` is the Qt5 binary; it exits 0 having run nothing and printed nothing, which looks exactly like success. + +`test/shell.d/elsewhen/qml/tst_arrows.qml` settles whether a click on an item in front also reaches a `MouseArea` behind it. It does not. + +## Keys + +| Key | What it does | +|-----|--------------| +| `Space` | opens the globe, and closes it again | +| `+` | opens the city search, or the globe's jump box when the globe is up | +| `a` | opens the city search (list only) | +| `j` | opens the globe's jump box (globe only) | +| `r` | re-probes the zones and refetches the weather | +| `Esc` | closes the search, then leaves the globe, then closes the panel | +| arrows, Return | walk and pick a search result | + +The key catcher reports Space as "activate" and reports Return as a return *and then* an activate, so Return marks itself on the way past and the activate behind it stands down - otherwise Return would work the globe too. + +Escape unwinds one layer per press rather than closing outright, so the way out of the globe is the same key as the way out of everything else. The globe's search hands the keyboard back when it closes: a hidden item keeps its focus, so otherwise the field would go on swallowing keys and the second Escape would go nowhere. + +## Settings + +Inline on the widget's `shell.json` entry: + +| Key | Meaning | +|----------|------------------------------------------------------| +| `zones` | `Label\|IANA name`, comma separated; blank seeds on first run | +| `hour24` | `true` or `false`; unset (the default) follows the system's time format. Click any row's time to flip it | +| `offsetMode` | `home` for the offset from you (default), `utc` for the absolute one | +| `units` | `F` or `C`; blank (the default) follows the system's measurement units. Click any temperature to flip it | +| `globeEnabled` | `false` to remove the globe entry point (default on) | +| `homeCity` | your city for the header (blank = from the system zone); set by tapping a city on this zone on the globe | +| `smoothMotion` | drop labels and detail while the globe moves (default true) | + +## IPC + +```bash +omarchy-shell omarchy.elsewhen toggle +omarchy-shell omarchy.elsewhen globe # switch between list and globe +omarchy-shell omarchy.elsewhen times # JSON, one entry per row +omarchy-shell omarchy.elsewhen add America/New_York Miami +omarchy-shell omarchy.elsewhen remove America/New_York +omarchy-shell omarchy.elsewhen refresh # re-probe offsets +``` diff --git a/docs/file-layout.md b/docs/file-layout.md index f261085f0eae..73c48c4f340a 100644 --- a/docs/file-layout.md +++ b/docs/file-layout.md @@ -116,7 +116,6 @@ default/** ──► omarchy-settings /usr/share/omarchy ├─ hypr/toggles/*.lua (flags, │ single-window-aspect-ratio, window-no-gaps) /etc/skel/.local/state/omarchy/toggles/hypr/ ├─ nautilus-python/extensions/*.py /etc/skel/.local/share/nautilus-python/extensions/ - ├─ tensaku/state.toml /etc/skel/.local/state/tensaku/state.toml ├─ uwsm/env.d/10-omarchy /usr/share/uwsm/env.d/ ├─ environment.d/*.conf /usr/lib/environment.d/ ├─ fontconfig/conf.avail/50-omarchy.conf /usr/share/fontconfig/conf.avail/ diff --git a/docs/omarchy-shell.md b/docs/omarchy-shell.md index d62ff7436df9..32d7af9fb6de 100644 --- a/docs/omarchy-shell.md +++ b/docs/omarchy-shell.md @@ -20,7 +20,17 @@ wait). "author": "You", "description": "A clock that does cool things", "kinds": ["bar-widget"], - "entryPoints": { "barWidget": "Widget.qml" } + "entryPoints": { "barWidget": "Widget.qml" }, + "barWidget": { + "displayName": "Cool clock", + "category": "Time", + "allowMultiple": false, + "defaultSection": "left", + "defaults": { "format": "HH:mm" }, + "schema": [ + { "key": "format", "type": "string", "label": "Format" } + ] + } } ``` @@ -37,7 +47,7 @@ wait). Only one full bar option is active at a time. The built-in `omarchy.bar` is used when `bar.id` is omitted or when a selected third-party bar cannot load. -Panels, overlays, and menus are loaded when summoned. Plugins can set the top-level manifest key `keepLoaded: true` to survive between summons, and to keep a service mounted across plugin hot-reload (so `omarchy.lock` is not destroyed while Hyprland still holds the session lock). First-party services are loaded at startup. +Panels, overlays, and menus are loaded when summoned. Plugins can set the top-level manifest key `keepLoaded: true` to survive between summons, and to keep a service mounted across plugin hot-reload (so `omarchy.lock` is not destroyed while Hyprland still holds the session lock). The kept service instance is not replaced, so changes to its code take effect on a shell restart. First-party services are loaded at startup. Entry points are QML `Item`s. Panel, overlay, and menu entry points expose `open(payloadJson)` and `close()` for summon/hide; on load the host injects `omarchyPath`, `shell`, `manifest`, and the registries (`pluginRegistry` / `barWidgetRegistry`) as properties. Built-in plugins receive the trusted host objects. Third-party plugins receive capability-scoped facades instead: ordinary plugins may look up and control only their own service and lifecycle, built-in clones retain narrow source-specific configuration and UI compatibility, menu plugins receive an application-library facade, and plugins can read detached scalar bar state. A full-bar plugin additionally receives detached bar configuration and widget-catalog snapshots, narrow proxies for the non-authentication services used by built-in bar widgets, and lifecycle control over configured non-authentication UI plugins. Authentication capabilities are stamped from trusted first-party manifests, authentication services are kept out of the host's public service map and QML object tree, and third-party registry/configuration snapshots can be changed only locally without mutating host state. The facades are API boundaries, not same-process QML sandboxes: a visual widget shares the host bar's scene and can walk its parent hierarchy to ordinary host objects. Sensitive state must not rely on the facade alone for isolation. @@ -88,6 +98,10 @@ bar from the CLI — `use | reset | defaults | position | transparent | put | move | set`, with placement flags such as `--section` and `--index`. The lower-level IPC methods remain available through `omarchy-shell shell ...`. +## Elsewhen + +Elsewhen (`omarchy.elsewhen`), the world clock, is a first-party plugin in `shell/plugins/panels/elsewhen/`; [`elsewhen.md`](elsewhen.md) covers how it works. It shipped as the separate `elsewhen` package under the id `omacom.elsewhen` until it moved in. New installs place it immediately before the clock; the placement migration uses `omarchy bar put omarchy.elsewhen --before omarchy.clock`, which preserves an existing placement and uses Elsewhen's normal right-side placement if the clock is absent. With no shell to ask, as in an update from a TTY, it skips the placement rather than failing the update. A later migration renames existing `omacom.elsewhen` entries in `shell.json`, keeping their settings, and removes the retired package and any dev-checkout link to its `/usr/share/omarchy` path, leaving links and checkouts the user made alone. + ## IPC The shell exposes a `shell` target (the host also registers diff --git a/docs/passwordless-sudo.md b/docs/passwordless-sudo.md new file mode 100644 index 000000000000..4aa6e31d58b5 --- /dev/null +++ b/docs/passwordless-sudo.md @@ -0,0 +1,27 @@ +# Temporary passwordless sudo + +`omarchy-sudo-passwordless` publishes a bounded grant for the numeric UID authenticated by sudo. Its user interface runs without a reusable sudo timestamp; fixed installed internal actions run as root and serialize on `/run/lock/omarchy-sudo-passwordless.lock`. + +## Grant lifecycle + +The sudoers rule is the only grant record: it contains the resolved account name and a UTC `NOTAFTER` deadline enforced by sudo itself, including after suspend. Publication validates a dot-prefixed temporary file with `visudo`, arms a calendar cleanup timer, then atomically renames the complete rule into place. There is no separate per-user state file to publish, parse, or reconcile. Failure after renewal starts removes the old grant; failed revocation remains an error and leaves the cleanup timer armed. + +An internal status result is `0` for an active, validated grant and `3` for confirmed inactive access. All other results are errors, including failed authentication and failed revocation. The user interface only offers a new grant after result `3`. It must not turn an inspection failure into a claim that no grant exists. + +Calendar timers clean up expired files; their liveness does not define authorization. Callbacks read the current rule and remove it only when expired. Earlier callbacks cannot shorten a renewed grant, so no timer identity needs to be persisted. Old UID-only and token-bearing callbacks remain accepted. Pending callbacks after renewal or manual disable are harmless and expire within the maximum 24-hour grant window. Boot-time tmpfiles cleanup removes the reserved generated filename namespace before users log in; routine non-boot tmpfiles maintenance leaves live grants alone. + +Legacy cleanup uses a root-owned machine marker under `/var/lib/omarchy/migrations/`, written only after successful cleanup under the grant lock. Later accounts can finish their migration queues without sudo and without revoking grants created after the repair. Old grant state files are no longer consulted. A legacy grant is recognized by its exact filename and rule relationship, since the old command wrote the caller's unvalidated name into both, so accounts outside the current name policy are still cleaned up. The generated filename prefix is reserved: boot cleanup and the package hook already remove everything under it, and the old writer could emit a rule whose body differs from its filename, so the migration moves any other file found there into a fresh root-only directory under `/var/lib/omarchy/sudoers-quarantine/`, as `policy` with the original name stored beside it, rather than leaving it live or deleting its content. + +## Package ownership + +The packaging companion must put the publication/expiry command, `omarchy-security-functions`, `omarchy-nopasswd-sudo.conf`, and the pre-transaction revocation hook in the settings package together. Removing the desktop runtime alone must leave a working expiry command behind. Stable and development package pairs must transfer ownership in one transaction without duplicate files. + +Before settings removal or upgrade, the installed ALPM `PreTransaction` hook invokes the fixed `__package-removing` action, acquires the same grant lock, sets `/run/omarchy-sudo-passwordless-package-removing` and revokes existing policy. The marker prevents a waiting publisher from creating a new grant while package files change. A successful installation clears the marker only after boot cleanup exists. The hook uses `AbortOnFail` because a scriptlet failure alone does not abort pacman. The scriptlets repeat cleanup as a fallback for upgrades from older packages that have no installed hook. New grants require both the boot rule and hook before publication. Failed or interrupted transactions leave the marker set; retry the package transaction successfully before requesting another grant. + +The runtime marker need not survive reboot: pre-removal revokes the old grants before package files disappear, and a new invocation independently verifies boot cleanup. Both root operations use fixed machine paths. The marker is not a user-controlled mode switch. + +## Validation + +The two passwordless-sudo test suites share a private filesystem and command fixture. They cover caller validation, the public prompt boundary, atomic publication, renewal failures, expiry, old callbacks, machine migration, and the source/package lock. Supply `OMARCHY_PKGS_PATH` as either a repository root or its `pkgbuilds` directory. An optional `OMARCHY_TEST_SUDOERS` path to sudo's upstream `testsudoers` executable evaluates the generated policy before and after its deadline without root or changing host policy. + +These local tests do not establish release readiness. The simplified candidate needs fresh installed-package, suspend/resume, boot-cleanup, and package-removal validation in a disposable VM. The shared security library and its interface are unchanged for downstream PRs. diff --git a/docs/testing.md b/docs/testing.md index bcd3b4af2afd..f8cd160e379d 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -52,6 +52,7 @@ directory or an installed Omarchy. Assertions are TAP-flavored and blunt: - `pass "description"` prints `ok - description`. +- `skip "description"` prints `ok - description # SKIP`. Include why the check could not run. Like `pass`, it returns normally; use `exit 0` afterwards only when the rest of the file cannot run either. - `fail "description" [detail]` prints the optional detail and `not ok - description` to stderr, then **exits the file**. There is no counting or continuing within a file: the first failed assertion ends it, @@ -59,19 +60,13 @@ Assertions are TAP-flavored and blunt: already invalidated. - `require_command ` fails the file when a needed tool is absent. -The runner compensates for that early exit: `./test/shell` continues past a -failing file and summarizes the failures at the end. Aborting the whole run at -the first bad file once let a single packaging failure mask 114 of 134 files. -Failure granularity is therefore per file inside a run, per assertion inside a -file. +The runner compensates for that early exit: `./test/shell` continues past a failing file and summarizes the failures at the end. Aborting the whole run at the first bad file once let a single packaging failure mask 114 of 134 files. Failure granularity is therefore per file inside a run, per assertion inside a file. + +The runner also lists files with skipped checks, including files that ran some checks or later failed. Skips do not fail a run. When no files fail, a run with skips is reported as completed without failures rather than having passed every check. ## Compositor-dependent tests -Some tests launch Quickshell or query Hyprland, but the suite must stay green -on headless machines. `require_compositor "description"` handles this: when no -compositor answers it prints `ok - no Wayland compositor; skipping ...` and -exits 0 — a skip is a passing test — and otherwise returns so the file -proceeds. +Some tests launch Quickshell or query Hyprland, but the suite must stay green on headless machines. `require_compositor "description"` handles this: when no compositor answers it calls `skip` with the reason and exits 0, and otherwise returns so the file proceeds. The skip marker lets the runner distinguish unavailable runtime coverage from checks that passed. The probe is more than an environment check, because `WAYLAND_DISPLAY` only proves the variable was inherited. Sandboxes pass the environment through @@ -119,6 +114,7 @@ only a live session can prove. ## Conventions worth copying +- **Redirect background output.** Send background fixtures' stdout to a log or `/dev/null` and clean up the processes on exit. An inherited output pipe can hold the runner open after the test exits. - **Stub the world, run the real code.** Tests build a scratch `bin/` of stub executables (`sudo`, `tmux`, `gsettings`, helper commands) that log their arguments to a file, prepend it to `PATH`, and then run the real script diff --git a/docs/theming.md b/docs/theming.md index 2399a7b0be2f..29986291c9f2 100644 --- a/docs/theming.md +++ b/docs/theming.md @@ -45,6 +45,8 @@ Making a new app follow theme changes means adding its restart/retint command to that list. Runs serialize on a `flock`, so scripted theme changes queue instead of racing. +Last, it starts `omarchy-theme-set-herdr-machines` detached. That command sets the same theme on every enabled `herdr machine list` target that runs Omarchy, over SSH inside the remote's live Hyprland session, and logs each machine's result to `~/.local/state/omarchy/theme-set-herdr-machines.log`. Sync is off by default. The `herdr-theme-sync` toggle turns it on, and a machine only sends and accepts themes while it is on. A mirrored change carries `OMARCHY_THEME_SYNC_FROM`, so the receiving machine never sends it on. + ## What an installed theme may not ship `themes//` in this repo is Omarchy's own code and is trusted. So is a theme the user wrote by hand in `~/.config/omarchy/themes//`: it is their machine and their file, and both stage in full. diff --git a/docs/update-process.md b/docs/update-process.md index bec3350d1d46..b5e00925b461 100644 --- a/docs/update-process.md +++ b/docs/update-process.md @@ -22,6 +22,7 @@ The design goal is: | Path | Owner | Purpose | | --- | --- | --- | | `${XDG_RUNTIME_DIR:-/tmp}/omarchy-update.lock` | user | Prevent overlapping update runs. Owned by `omarchy-update-lock`; compatibility wrappers inherit/respect it. | +| `${XDG_RUNTIME_DIR}/omarchy-update-stay-awake/` | user | Private mode-0700 inhibitor coordination state. If no runtime directory is available, the helper uses the validated mode-0700 `/tmp/omarchy-$UID/` fallback. | | `/tmp/omarchy-update.log` | user | Transcript of `omarchy update`, used by `omarchy-update-analyze-logs`. | | `~/.local/state/omarchy/current/` | user | Generated active theme, selected theme name, and current background symlink. | | `~/.local/state/omarchy/migrations/` | user | Per-user migration markers. | @@ -56,6 +57,8 @@ privileged work should invoke the appropriate helper or privilege prompt. Migrations must be idempotent; if one user already applied a machine-wide repair, the migration should no-op for other users. +When invoked by the update, migrations share its single sudo authorization. The standalone migration runner has its own security changes in the migration-boundary PR; this update change does not establish that standalone boundary. Historical migrations remain strictly ordered. + For watchers and diagnostics, `omarchy-migrate --pending` prints pending migration names and exits `0` when any are pending. When no migrations are pending, it prints nothing and exits non-zero. @@ -82,13 +85,18 @@ Omarchy update command, the hook exits non-zero with `AbortOnFail`, which stops the transaction before packages are changed. `omarchy-update-system-pkgs`, `omarchy-refresh-pacman`, `omarchy-reinstall-pkgs`, -`omarchy-channel-set`, and the v4 upgrader run pacman through: +and `omarchy-channel-set` run pacman through the hidden `omarchy-update-pacman` +helper (the v4 upgrader sets `OMARCHY_UPDATE_PACMAN=1` directly): ```bash -env OMARCHY_UPDATE_PACMAN=1 pacman ... +sudo env OMARCHY_UPDATE_PACMAN=1 systemd-run --scope --quiet --collect pacman ... ``` -so the guard allows Omarchy-owned update flows. A user can intentionally bypass +so the guard allows Omarchy-owned update flows. The `systemd-run --scope` +wrapper registers the transaction as a PID 1 scope: upgrading systemd reexecs +the system and user managers mid-transaction, and a pacman left inside a +user-session scope can be SIGKILLed by that reexec. On unbooted systems (such +as the installer chroot) the helper runs pacman directly. A user can intentionally bypass the guard with: ```bash @@ -118,6 +126,7 @@ omarchy-update ├─ omarchy-update-requires-free-space │ └─ abort below the configured free-space threshold on / ├─ confirm unless -y + ├─ authorize sudo once, then keep the timestamp fresh in the background ├─ omarchy-update-pkg-prune │ └─ trim the pacman cache to two versions per package, deliberately │ before the snapshot since the cache lives on the snapshotted subvolume @@ -125,21 +134,31 @@ omarchy-update │ installed but unconfigured fails the snapshot loudly, pointing at │ install/config/snapper.sh, and the update continues without one) ├─ omarchy-update-stay-awake start - ├─ run package updates, migrations, hooks, and log analysis + ├─ run system-package updates + ├─ run migrations + ├─ run orphan review and log analysis ├─ omarchy-update-status │ └─ refresh or clear the shell update indicator + ├─ restart marked services and the shell + ├─ run the post-update hook, then update mise tools + ├─ stop the keepalive and invalidate sudo, then update AUR packages with + │ no-update authentication, and invalidate again ├─ omarchy-update-stay-awake stop │ └─ release the sleep inhibitor and restore shell idle state, if changed - └─ omarchy-update-restart + └─ offer the unprivileged reboot prompt ``` Important behavior: -- In dev-link mode, `omarchy update` fast-forwards the active checkout from its - configured upstream before changing system packages or running migrations. -- `-y` exports `OMARCHY_UPDATE_UNATTENDED=1` — a promise not to ask anything. - Steps that would prompt (orphan removal, conflict handoff) report and skip - instead of blocking. +- Protected update entrypoints require the session's canonical `OMARCHY_PATH` to match their own checkout or the packaged `/usr/bin` entrypoint before selecting commands or the sudo wrapper. This preserves intentionally trusted development checkouts while rejecting a command paired with a different source root. System phases use a fixed command search path; user PATH is restored for hooks and mise. +- Mixed-trust update entrypoints start Bash in privileged mode, discard `BASH_ENV`, `ENV`, and exported-function records before launching helpers, and reject an ordinary `bash path/to/command` invocation. Run them as executables (normally through the `omarchy` CLI); `/usr/bin/bash -p path/to/command` is the explicit interpreter form. This keeps shell startup injection from replacing the no-update sudo boundary. +- In dev-link mode, `omarchy update` fast-forwards the active checkout from its configured upstream before changing system packages or running migrations. +- The update asks for the sudo password once, right after confirmation. It first invalidates any existing timestamp so that prompt always belongs to this update, then a background keepalive refreshes the timestamp every minute so long downloads, migrations, hooks, and mise never outlast it. Everything except AUR shares that one authorization: package prune, snapshot, stay-awake, keyring, system packages, migrations, orphan removal, service restarts, the post-update hook, and mise. Stay-awake sees `OMARCHY_UPDATE_SUDO_SESSION=1`, uses that authorization non-interactively whatever its stdin is, and leaves it to the update instead of revoking it. The authorization runs a command rather than `sudo -v`, so passwordless sudo still needs no prompt. Standalone commands that keep their own cold boundary, such as `omarchy-refresh-pacman`, still revoke if a post-update hook calls them. +- AUR builds run third-party PKGBUILD code, so they run last and never see the update's authorization. The update stops the keepalive, invalidates the timestamp, and runs yay with the no-update wrapper as its sudo command and its credential loop disabled; an AUR install prompts per command without publishing a reusable timestamp. The timestamp is invalidated again afterwards and on every exit. +- This lifecycle controls authorization created by the protected workflow. `sudo -N` prevents cache updates but can use an existing valid credential, and `sudo -k` revokes the current session's timestamp. It does not isolate the account from unrelated concurrent authentication in another workflow. +- Sleep inhibition authenticates before detaching, drops the held command back to the caller, and closes both update lock descriptors before the persistent process starts. Cleanup accepts only caller-owned, mode-0600, single-link state and revalidates the recorded PID, process start time, owner, and random token immediately before every signal. +- Channel switching establishes the same boundary before dev link/unlink, refresh and package operations. It keeps the wrapper first when changing source roots, carries the original user PATH into update hooks and mise, and checks after each package transaction that the wrapper still exists before any further privileged step, since a transaction can replace the running tree with a release that predates it; when it is gone, or the destination otherwise lacks it, the switch stops after the package switch with instructions to run that release's update from a fresh session rather than letting a bare `sudo` or an updater that authenticates without `--no-update` publish a timestamp. Failed and interrupted channel switches revoke on exit. +- `-y` exports `OMARCHY_UPDATE_UNATTENDED=1` and suppresses Omarchy confirmation prompts. Interactive review steps (orphan removal, conflict handoff) report and skip instead of blocking. Privileged commands still require the one sudo authorization, and AUR installs can prompt separately. - The free-space requirement uses a 10 GiB threshold and stops the update before confirmation when it is not met. If free space cannot be determined, the check is silently skipped. Set `OMARCHY_UPDATE_FORCE=1` to bypass the check. @@ -251,6 +270,9 @@ which pacman repo the mirrorlist points at (and swap between the `omarchy` and `omarchy-dev` packages through a guard-allowed pacman run), while `dev` links the runtime to a git checkout via the dev-link mechanism, after which `omarchy update` fast-forwards that checkout instead of upgrading a package. +Channel switching runs the `pre-refresh-pacman` hook once, during its refresh +step: cold, behind the no-update wrapper, after the package config is re-synced +and before the refresh transaction. It does not run if the switch fails earlier. There is no version file at runtime. `omarchy-version` derives the version from `pacman -Q` on whichever package is installed, or reports `dev ()` for a @@ -272,12 +294,13 @@ scripts. | `omarchy-update-confirm` | Gum confirmation copy for `omarchy update`. | **Question.** Could be inlined into `omarchy-update`; separate file only helps keep copy isolated. | | `omarchy-update-dev` | Fast-forwards the active dev-linked checkout from its configured upstream; no-ops for package-backed installs. | **Keep.** Runs before package updates so a checkout conflict stops the update before system mutation. | | `omarchy-update-keyring` | Ensures Omarchy keyring and Arch keyring are current before the main transaction. | **Keep, but review.** It uses targeted `pacman -Sy` for keyring bootstrapping; acceptable for this special case but should remain tightly scoped. | -| `omarchy-update-system-pkgs` | Runs `sudo env OMARCHY_UPDATE_PACMAN=1 pacman -Syu --noconfirm` with `--overwrite '/usr/share/omarchy/*'`, capturing stderr to a report file; on failure it execs `omarchy-update-system-pkgs-when-conflicted`. | **Keep for now.** Small leaf command, clear/testable. | +| `omarchy-update-system-pkgs` | Runs `omarchy-update-pacman -Syu --noconfirm` with `--overwrite '/usr/share/omarchy/*'`, capturing stderr to a report file; on failure it execs `omarchy-update-system-pkgs-when-conflicted`. | **Keep for now.** Small leaf command, clear/testable. | | `omarchy-update-system-pkgs-when-conflicted` | Hidden conflict handler: quarantines unowned conflicting files under `/var/lib/omarchy/replaced`, retries the upgrade once, restores files the upgrade didn't claim, and hands package-vs-package conflicts to an interactive pacman run (never under `-y`). | **Keep internal/hidden.** Keeps conflict recovery out of the happy path. | | `omarchy-update-pkg-prune` | Trims the pacman cache to two versions per package (`paccache -rk2`) before the snapshot, keeping the offline downgrade path while capping snapshot growth. | **Keep internal/hidden.** | | `omarchy-update-requires-free-space` | Aborts the update below a 10 GiB free-space threshold on `/`; silently skipped when free space cannot be determined; `OMARCHY_UPDATE_FORCE=1` bypasses. | **Keep internal/hidden.** | | `omarchy-migrate` | Public migration command. Waits for pacman, then runs all pending migrations for the current user. Supports `--pending`. | **Keep.** This replaces the discarded `omarchy-update-user-finalize` name and no longer needs `--force`. | | `omarchy-update-pacman-guard` | ALPM pre-transaction guard that aborts direct `pacman -Syu` style upgrades unless Omarchy set `OMARCHY_UPDATE_PACMAN=1` or the user explicitly set `OMARCHY_ALLOW_DIRECT_PACMAN=1`. | **Keep internal/hidden.** This is what nudges users back to `omarchy update`. | +| `omarchy-update-pacman` | Hidden helper that runs a guard-approved pacman transaction as a PID 1 scope (`systemd-run --scope`) so a mid-transaction systemd reexec cannot kill it; runs pacman directly when not booted under systemd. | **Keep internal/hidden.** Single place that owns how Omarchy invokes pacman for system mutation. | | `omarchy-migrate-notify` | Internal login-time notification helper. Uses `omarchy-migrate --pending` and shows a notification only when this user has pending migrations. | **Keep internal/hidden.** Clear name now that the public command is `omarchy-migrate`. | | `omarchy-update-user-notify` | Hidden compatibility wrapper for `omarchy-migrate-notify`. | **Temporary.** Keep only for old callers. | | `omarchy-update-available` | Update checker for shell widget and post-update refresh. | **Keep.** Could eventually be renamed `omarchy-update-check`, but current name matches widget semantics. | @@ -285,7 +308,7 @@ scripts. | `omarchy-update-mise` | Runs `MISE_MINIMUM_RELEASE_AGE=0 mise up` for mise-managed tools — the override of mise's release-age cooldown is the point. | **Keep.** Mise-managed tools are intentionally part of the blessed update path. | | `omarchy-update-orphan-pkgs` | Lists orphans and prompts before removal; noninteractive mode never removes. | **Keep for now.** Safe because it is prompt-only. | | `omarchy-update-analyze-logs` | Scans `/tmp/omarchy-update.log` for known failure patterns, currently initramfs generation. | **Keep/expand.** Useful safety net; should grow only for high-signal checks. | -| `omarchy-update-restart` | Prompts for reboot after kernel/Hyprland updates, restarts components with `restart-*-required` markers, and always restarts the shell. | **Keep.** Important final step; may eventually include service-restart checks. | +| `omarchy-update-restart` | Restarts components selected by `restart-*-required` markers, always restarts the shell, and prompts for reboot after kernel/Hyprland updates. Internal phase flags let the update finish sudo-capable restarts before user hooks and defer only the unprivileged reboot prompt. | **Keep.** Important final step; may eventually include service-restart checks. | | `omarchy-update-firmware` | Manual firmware update command using fwupd. Not part of the normal update pipeline. | **Keep separate.** Firmware is not a routine system update step. | | `omarchy-update-time` | Restarts `systemd-timesyncd`. | **Question.** Not really an update command. Consider renaming/moving under system/time maintenance. | diff --git a/etc/fastfetch/config.jsonc b/etc/fastfetch/config.jsonc index df2fc5526392..203979a985aa 100644 --- a/etc/fastfetch/config.jsonc +++ b/etc/fastfetch/config.jsonc @@ -55,7 +55,7 @@ }, { "type": "swap", - "key": "└ └󰓡 ", + "key": "└ └󰓡", "keyColor": "green" }, { diff --git a/etc/limine-entry-tool.d/omarchy-defaults.conf b/etc/limine-entry-tool.d/omarchy-defaults.conf index 49c6204bcb4b..ec0fa96f4c71 100644 --- a/etc/limine-entry-tool.d/omarchy-defaults.conf +++ b/etc/limine-entry-tool.d/omarchy-defaults.conf @@ -15,7 +15,8 @@ ENABLE_LIMINE_FALLBACK=yes # Find and add other bootloaders FIND_BOOTLOADERS=yes -BOOT_ORDER="*, *fallback, Snapshots" +# Keep T2 Macs on their specialized kernel; prefer linux-omarchy elsewhere. +BOOT_ORDER="linux-t2, linux-omarchy, linux-omarchy-*, *, *fallback, Snapshots" # Snapper is configured with NUMBER_LIMIT="5" (see default/snapper/root), but # limine-snapper-sync can see the newly created sixth snapshot before cleanup diff --git a/etc/sysctl.d/99-omarchy-sysctl.conf b/etc/sysctl.d/99-omarchy-sysctl.conf index 1cce6d7fcc08..dac0fb2b215d 100644 --- a/etc/sysctl.d/99-omarchy-sysctl.conf +++ b/etc/sysctl.d/99-omarchy-sysctl.conf @@ -1,6 +1,12 @@ # Solve common flakiness with SSH (MTU discovery on flaky links). net.ipv4.tcp_mtu_probing=1 +# BBR estimates bottleneck bandwidth and minimum RTT and paces to them, where +# cubic keeps pushing until packets drop. That cuts queueing latency +# (bufferbloat) on fast links. fq is the qdisc BBR is built to pace through. +net.core.default_qdisc=fq +net.ipv4.tcp_congestion_control=bbr + # Tune reclaim for swap on zram, which is orders of magnitude faster than the # disk swapfile these defaults assume. diff --git a/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf b/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf index 2c644ff1fc9c..be81137ad053 100644 --- a/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf +++ b/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf @@ -1,5 +1,5 @@ -# omarchy-sudo-passwordless writes /etc/sudoers.d/99-omarchy-nopasswd- and -# arms a transient systemd-run timer to remove it again. Transient units do not -# survive a reboot, so remove any remaining grant during early boot. Boot-only -# (r!) ensures a later systemd-tmpfiles --remove cannot cut a live grant short. +# omarchy-sudo-passwordless creates grants in this owned filename namespace. +# Transient expiry timers do not survive reboot, so early boot removes every +# remaining grant. The boot-only modifier prevents later tmpfiles runs from +# shortening a live, explicitly requested window. r! /etc/sudoers.d/99-omarchy-nopasswd-* diff --git a/etc/udev/rules.d/60-omarchy-io-scheduler.rules b/etc/udev/rules.d/60-omarchy-io-scheduler.rules new file mode 100644 index 000000000000..1f389f4b9804 --- /dev/null +++ b/etc/udev/rules.d/60-omarchy-io-scheduler.rules @@ -0,0 +1,8 @@ +# Kyber keeps reads in their own queue and throttles the depth it submits to +# hold a 2ms read latency target, so interactive reads keep flowing while a +# large build, copy, or package upgrade floods the disk with writes. The +# kernel's own pick (none or mq-deadline, depending on the device) does not +# regulate latency once the queue fills. Whole disks only: partitions have no +# scheduler of their own, and zram is memory with nothing to schedule. Zoned +# btrfs disks are moved back to mq-deadline by 64-btrfs-zoned.rules. +ACTION=="add|change", SUBSYSTEM=="block", ENV{DEVTYPE}=="disk", KERNEL=="nvme*|sd*|mmcblk*|vd*", ATTR{queue/scheduler}="kyber" diff --git a/install/hardware/all.sh b/install/hardware/all.sh index defeef1c7d22..12add110c51f 100644 --- a/install/hardware/all.sh +++ b/install/hardware/all.sh @@ -14,21 +14,14 @@ run_logged "$OMARCHY_INSTALL/hardware/vulkan.sh" run_logged "$OMARCHY_INSTALL/hardware/intel/video-acceleration.sh" run_logged "$OMARCHY_INSTALL/hardware/intel/lpmd.sh" run_logged "$OMARCHY_INSTALL/hardware/intel/thermald.sh" -# Swap in the Panther Lake kernel before anything pulls DKMS modules in. -# intel-ipu7-camera drags in ipu7-drivers, vision-drivers and v4l2loopback, -# and building all three against the stock kernel only to rebuild them against -# linux-ptl and tear the first set down again cost ~25s of the install. -run_logged "$OMARCHY_INSTALL/hardware/intel/ptl-kernel.sh" run_logged "$OMARCHY_INSTALL/hardware/intel/ipu7-camera.sh" run_logged "$OMARCHY_INSTALL/hardware/intel/fred.sh" run_logged "$OMARCHY_INSTALL/hardware/intel/fix-wifi7-eht.sh" run_logged "$OMARCHY_INSTALL/hardware/intel/sof-firmware.sh" -# Pulls in v4l2loopback-dkms, so it sits after the Panther Lake kernel swap. run_logged "$OMARCHY_INSTALL/hardware/fix-elgato-camlink-4k.sh" -# Rebuilds the boot image, so it has to follow the Panther Lake kernel swap -# above rather than sit with the other Dell leaf at the top of this file. +# Rebuilds the boot image, so it follows camera module setup. run_logged "$OMARCHY_INSTALL/hardware/dell-xps13-sidecar-amps.sh" run_logged "$OMARCHY_INSTALL/hardware/asus/fix-asus-ptl-display-backlight.sh" diff --git a/install/hardware/fix-bcm43xx.sh b/install/hardware/fix-bcm43xx.sh index 6b7e5648f1f0..0f9cf474a5be 100644 --- a/install/hardware/fix-bcm43xx.sh +++ b/install/hardware/fix-bcm43xx.sh @@ -6,5 +6,5 @@ pci_info=$(lspci -nn) if (echo "$pci_info" | grep -q "14e4:43a0" || echo "$pci_info" | grep -q "14e4:4331"); then echo "BCM4360 / BCM4331 detected" - omarchy-pkg-add broadcom-wl-dkms linux-headers + omarchy-pkg-add broadcom-wl-dkms fi diff --git a/install/hardware/fix-elgato-camlink-4k.sh b/install/hardware/fix-elgato-camlink-4k.sh index f726fd9a506d..9ae9e343d47c 100644 --- a/install/hardware/fix-elgato-camlink-4k.sh +++ b/install/hardware/fix-elgato-camlink-4k.sh @@ -4,8 +4,7 @@ # v4l2-relayd re-exposes it at 1280x720 under the same name. if omarchy-hw-elgato-camlink-4k; then - mapfile -t kernel_headers < <(pacman -Qqs '^linux(-zen|-lts|-hardened|-t2|-ptl|-omarchy-bore)?$' | sed 's/$/-headers/') - omarchy-pkg-add "${kernel_headers[@]}" v4l2loopback-dkms v4l2loopback-utils v4l2-relayd + omarchy-pkg-add v4l2loopback-dkms v4l2loopback-utils v4l2-relayd sudo install -Dm644 "$OMARCHY_PATH/default/udev/elgato-camlink-4k.rules" /etc/udev/rules.d/71-elgato-camlink-4k.rules sudo install -Dm644 "$OMARCHY_PATH/default/v4l2-relayd/camlink.conf" /etc/v4l2-relayd.d/camlink.conf diff --git a/install/hardware/fix-tuxedo-backlight.sh b/install/hardware/fix-tuxedo-backlight.sh index 9644d310e612..7fb408e0d543 100644 --- a/install/hardware/fix-tuxedo-backlight.sh +++ b/install/hardware/fix-tuxedo-backlight.sh @@ -1,7 +1,7 @@ # Install Tuxedo drivers for keyboard backlighting on Tuxedo laptops and # compatible devices like the Slimbook Executive (Clevo/Tuxedo chassis). if cat /sys/class/dmi/id/sys_vendor 2>/dev/null | grep -qi "TUXEDO\|Slimbook"; then - omarchy-pkg-add linux-headers tuxedo-drivers-nocompatcheck-dkms + omarchy-pkg-add tuxedo-drivers-nocompatcheck-dkms # Blacklist the legacy clevo_xsm_wmi module which conflicts with the tuxedo-drivers # clevo_wmi module. When clevo_xsm_wmi loads first, it grabs the Clevo WMI GUIDs, diff --git a/install/hardware/fix-yt6801-ethernet-adapter.sh b/install/hardware/fix-yt6801-ethernet-adapter.sh index 34331a0fa883..89997bec3dc8 100644 --- a/install/hardware/fix-yt6801-ethernet-adapter.sh +++ b/install/hardware/fix-yt6801-ethernet-adapter.sh @@ -1,4 +1,4 @@ -# Install drivers for Motorcomm YT6801 ethernet adapter used by the Slimbook Executive -if lspci | grep -i "YT6801\|Motorcomm.*Ethernet"; then - omarchy-pkg-add linux-headers yt6801-dkms -fi +# Fresh installs use the kernel's upstream dwmac-motorcomm driver and do not +# install yt6801-dkms. Existing systems retire that fallback in migration +# 1788279117 only after proving the running kernel alias and every live binding; +# a manual hardware-setup rerun must not remove it ahead of that cutover. diff --git a/install/hardware/intel/ptl-kernel.sh b/install/hardware/intel/ptl-kernel.sh deleted file mode 100644 index 794827249c41..000000000000 --- a/install/hardware/intel/ptl-kernel.sh +++ /dev/null @@ -1,25 +0,0 @@ -# Install Panther Lake kernel for Dell XPS Panther Lake systems -# The linux-ptl kernel includes audio driver patches not yet in mainline. - -if omarchy-hw-match "XPS" && omarchy-hw-intel-ptl; then - echo "Detected Dell XPS Panther Lake, installing PTL kernel..." - - omarchy-pkg-add linux-ptl linux-ptl-headers - pacman -Rdd --noconfirm linux linux-headers || true - - # linux-ptl doesn't provide=linux, so anything depending on linux drags the - # stock kernel back in and the boot menu grows a second, slower entry. - if pacman -Qq linux &>/dev/null; then - echo "WARNING: stock linux kernel still installed alongside linux-ptl:" - pacman -Qi linux | grep -i "required by" - fi - - mkdir -p /etc/limine-entry-tool.d - # Named to sort after omarchy-defaults.conf: drop-ins are read in order and - # the last BOOT_ORDER wins, so an earlier-sorting name is a silent no-op. - rm -f /etc/limine-entry-tool.d/dell-xps-panther-lake.conf - cat > /etc/limine-entry-tool.d/zz-dell-xps-panther-lake.conf <<'EOF' -# Only show Panther Lake kernel in boot menu on Dell XPS Panther Lake -BOOT_ORDER="linux-ptl*, *fallback, Snapshots" -EOF -fi diff --git a/install/hardware/nvidia.sh b/install/hardware/nvidia.sh index e73709955114..1c36787b7705 100644 --- a/install/hardware/nvidia.sh +++ b/install/hardware/nvidia.sh @@ -1,8 +1,4 @@ if lspci | grep -qi 'nvidia'; then - # Check which kernel is installed and set appropriate headers package - KERNEL_PACKAGE=$(pacman -Qqs '^linux(-zen|-lts|-hardened|-t2|-ptl)?$' | head -1 || true) - [[ -n $KERNEL_PACKAGE ]] && omarchy-pkg-add "$KERNEL_PACKAGE-headers" - if omarchy-hw-nvidia-gsp; then PACKAGES=(nvidia-open-dkms nvidia-utils lib32-nvidia-utils libva-nvidia-driver) elif omarchy-hw-nvidia-without-gsp; then diff --git a/install/omarchy-base.packages b/install/omarchy-base.packages index 76e741108cf6..7a96846cb6c9 100644 --- a/install/omarchy-base.packages +++ b/install/omarchy-base.packages @@ -50,6 +50,7 @@ gvfs-mtp gvfs-nfs gvfs-smb herdr +hype hyprland hyprland-guiutils hyprland-preview-share-picker @@ -78,6 +79,7 @@ luarocks man-db mariadb-libs mise-bin +monologue moonlight-qt mpv mpv-mpris @@ -95,6 +97,10 @@ omacalc omacut omawrite omarchy-nvim +omasnap +# OWE owns desktop video backgrounds and feeds the lock screen its frames. +owe +owe-lockfeed pacman-contrib pamixer pinta @@ -108,12 +114,9 @@ ttfx qemu-user-static-binfmt qrencode qt6-imageformats -qt6-multimedia -qt6-multimedia-ffmpeg quickshell ripgrep ruby -tensaku sddm slurp socat diff --git a/install/omarchy-other.packages b/install/omarchy-other.packages index 3214657a6630..ee7607a7573b 100644 --- a/install/omarchy-other.packages +++ b/install/omarchy-other.packages @@ -20,11 +20,9 @@ libva-nvidia-driver limine limine-mkinitcpio-hook limine-snapper-sync -linux linux-firmware -linux-headers -linux-ptl -linux-ptl-headers +linux-omarchy +linux-omarchy-headers macbook12-spi-driver-dkms nvidia-580xx-dkms nvidia-dkms @@ -44,7 +42,6 @@ thermald webp-pixbuf-loader yay-debug tuxedo-drivers-nocompatcheck-dkms -yt6801-dkms zram-generator # Intel encoding processing diff --git a/install/user/all.sh b/install/user/all.sh index 39d98ea57f44..d81c3e757917 100644 --- a/install/user/all.sh +++ b/install/user/all.sh @@ -9,6 +9,7 @@ run_logged "$OMARCHY_INSTALL/user/hardware/asus/fix-mic.sh" run_logged "$OMARCHY_INSTALL/user/hardware/framework/fix-f13-amd-audio-input.sh" run_logged "$OMARCHY_INSTALL/user/hardware/dell/xps13-text-scaling.sh" run_logged "$OMARCHY_INSTALL/user/hardware/fix-nouveau-cursor.sh" +run_logged "$OMARCHY_INSTALL/user/hardware/vm-no-animations.sh" run_logged "$OMARCHY_INSTALL/user/default-keyring.sh" run_logged "$OMARCHY_INSTALL/user/mise.sh" diff --git a/install/user/first-run/enable-user-units.sh b/install/user/first-run/enable-user-units.sh index 9865fc207e4c..e08885c9e0dc 100755 --- a/install/user/first-run/enable-user-units.sh +++ b/install/user/first-run/enable-user-units.sh @@ -14,8 +14,11 @@ set -euo pipefail systemctl --user daemon-reload systemctl --user enable --now \ bt-agent.service \ + owed.service \ omarchy-recover-internal-monitor.service \ omarchy-sleep-lock.service \ omarchy-migrate-notify.service \ omarchy-fcitx5.service \ omarchy-crash-watch.service + +omarchy-hook-install theme-set /usr/share/owe/10-owe-sync diff --git a/install/user/hardware/vm-no-animations.sh b/install/user/hardware/vm-no-animations.sh new file mode 100644 index 000000000000..428fa9698835 --- /dev/null +++ b/install/user/hardware/vm-no-animations.sh @@ -0,0 +1,9 @@ +# A VM usually renders on the CPU, where animations and transparency cost +# every frame, so start it without them. omarchy-toggle-animations brings them +# back. This runs before any Hyprland session exists, so place the flag +# directly rather than through omarchy-hyprland-toggle, which reloads Hyprland. +if omarchy-hw-vm; then + echo "Detected a virtual machine. Turning off animations and transparency." + mkdir -p "$HOME/.local/state/omarchy/toggles/hypr" + cp "$OMARCHY_PATH/default/hypr/toggles/no-animations.lua" "$HOME/.local/state/omarchy/toggles/hypr/" +fi diff --git a/install/user/mise-work.sh b/install/user/mise-work.sh index f77d5561e0e6..75ca0916c43a 100644 --- a/install/user/mise-work.sh +++ b/install/user/mise-work.sh @@ -2,13 +2,6 @@ mkdir -p "$HOME/Work" mkdir -p "$HOME/Work/tries" -cat >"$HOME/Work/.mise.toml" <<'EOF' -[env] -_.path = "{{ cwd }}/bin" -EOF - -mise trust ~/Work/.mise.toml - # Offline installs unpack the Node tarball bundled by the ISO: from # /opt/packages in the ISO chroot, or from the copy staged in provisioning state when # omarchy-provision-owner finalizes the user at first boot. @@ -37,6 +30,11 @@ if [[ -n $NODE_PACKAGE_DIR ]]; then mkdir -p "$NODE_INSTALL_DIR" tar -xzf "$NODE_TARBALL" --strip-components=1 -C "$NODE_INSTALL_DIR" mise use -g node@"$NODE_VERSION" + + # That pinned the exact bundled version, which would exempt Node from + # mise up forever. Loosen it to latest, like an online install gets: + # mise resolves latest to the installed version while offline. + mise config set tools.node latest --file "$HOME/.config/mise/config.toml" fi else mise use -g node@latest diff --git a/install/user/mise.sh b/install/user/mise.sh index 81e0364c69a6..89f1cfb5852b 100644 --- a/install/user/mise.sh +++ b/install/user/mise.sh @@ -19,13 +19,8 @@ omarchy-mise-install npm:@kitlangton/ghui ghui omarchy-mise-install aqua:modem-dev/hunk hunk omarchy-mise-install github:basecamp/hey-cli hey omarchy-mise-install github:basecamp/basecamp-cli basecamp +omarchy-mise-install npm:cf cf omarchy-mise-install github:OpenRouterLabs/ori-releases ori -# Every line above writes a stub and cannot fail. This one can: it exits -# non-zero when Hermes Desktop owns Hermes but has not finished setting it up, -# and this leaf is sourced under `bash -eE`, so that would abort the rest of -# omarchy-provision-user -- the default browser, the mailto handler and the -# finalize-user marker all come after it. -omarchy-install-hermes-cli || true if omarchy-cmd-missing muse; then omarchy-mise-install "http:muse[url=https://api.meta.ai/muse-launcher.sh,bin=muse,version_list_url=https://api.meta.ai/muse-code/channels/muse-stable,version_json_path=.version]" muse fi diff --git a/manual/04-navigation.md b/manual/04-navigation.md index 549833bf32ca..0b3404ffeb6e 100644 --- a/manual/04-navigation.md +++ b/manual/04-navigation.md @@ -66,6 +66,8 @@ Finally, there's a special scratchpad workspace that drops down over whatever wo It works especially well for a terminal running an agent, or for controls you want to interact with quickly without leaving the current workspace. To move a window off the scratchpad, send it directly to another workspace with something like `Super + Shift + 1`. +While the scratchpad holds a single window, it drops down as a centered panel rather than spanning the screen. Put a second app on it and it goes back to the full width, so the two have room to sit side by side. + ### It takes some getting used to! It takes a little while to get used to navigating your desktop like this, but once you do, it'll be hard to go back to a traditional mouse-driven desktop experience! diff --git a/manual/05-the-top-bar.md b/manual/05-the-top-bar.md index 09a028986f4d..3f558d93060e 100644 --- a/manual/05-the-top-bar.md +++ b/manual/05-the-top-bar.md @@ -45,6 +45,7 @@ Clicking a bar icon opens a panel, which is a proper popup with sliders, lists, | `Super + Ctrl + D` | Display | | `Super + Ctrl + P` | Power | | `Super + Ctrl + Alt + D` | Calendar | +| `Super + Ctrl + Alt + E` | World clock | | `Super + Ctrl + 1-9` | Toggle the nth panel in the right section | The panels aren't read-outs. They're where you actually do the thing: diff --git a/manual/07-hotkeys.md b/manual/07-hotkeys.md index 72acdc8a27cb..660b191c0896 100644 --- a/manual/07-hotkeys.md +++ b/manual/07-hotkeys.md @@ -68,6 +68,7 @@ You can see all the main keyboard bindings with `Super + K` (Tmux bindings with | `Super + Ctrl + D` | Display panel | | `Super + Ctrl + P` | Power panel | | `Super + Ctrl + Alt + D` | Calendar panel | +| `Super + Ctrl + Alt + E` | World clock panel | | `Super + Ctrl + 1-9` | Toggle bar panel by position | | `Super + Ctrl + S` | Share menu (via LocalSend) | | `Super + Ctrl + T` | Activity (btop) | diff --git a/manual/12-screenshots-recording.md b/manual/12-screenshots-recording.md index 9c476231d5ea..d6ec72a21557 100644 --- a/manual/12-screenshots-recording.md +++ b/manual/12-screenshots-recording.md @@ -13,13 +13,15 @@ Everything you can grab off the screen hangs off the Print Screen key. One key o ## Screenshots -Hit `Print Screen` and the screen freezes so nothing shifts under you while you aim. Drag a box for a freeform region, or just click once and the shot snaps to whatever rectangle you clicked in — a window if you landed on one, the whole monitor if you landed on the bar or in a gap. Changed your mind? Hit `Print Screen` again to dismiss the picker. +Hit `Print Screen` and Omasnap captures the focused monitor before its overlay appears, so nothing shifts under you while you aim. Drag a freeform region, click a window to capture it, or click open space to capture the whole monitor. Press `S` before drawing to capture a scrolling region. Changed your mind? Hit `Print Screen` again to dismiss Omasnap. -The result goes two places at once: a PNG in your pictures directory, and the clipboard, so you can paste it straight into a chat window with `Super + V`. A notification pops up with a thumbnail. Click it (or hit `Super + Alt + ,` to invoke the last notification) and the shot opens in Tensaku, the annotation editor, where you can draw arrows and boxes on it before you send it. +After you select an area, Omasnap saves the capture, copies it to the clipboard, and shows a preview for 10 seconds. Use the preview's pin button or `Ctrl + P` to keep it on screen, or choose Edit to annotate it. -Files land in `~/Pictures` by default, named `screenshot-2026-08-13_14-22-05.png`. If you'd rather keep them in their own folder, set `OMARCHY_SCREENSHOT_DIR` — see [the FAQ](46-faq.md) for where to put session environment variables. Omarchy creates the directory for you if it isn't there. You can swap the editor too with `OMARCHY_SCREENSHOT_EDITOR`. +The annotation editor can draw arrows, lines, shapes, highlights, numbered markers, text, and secure redactions; crop or cut out part of the image; OCR its text; and add a backdrop. In the editor, press `Enter` to copy and save the finished PNG, `Ctrl + C` to copy it without saving, or `Ctrl + S` to save it without copying. -From the terminal, `omarchy screenshot` takes the same shot, and you can be explicit about it: `omarchy capture screenshot region` for freeform only, `windows` to snap to window and monitor rectangles, or `fullscreen` to skip the picker entirely and grab the focused monitor. A second argument of `copy` puts the shot only on the clipboard, and `save` only on disk. +Saved screenshots land in `~/Pictures/Screenshots` by default, with a name such as `screenshot-2026-08-13_14-22-05-firefox.png`. Set `OMASNAP_SCREENSHOT_DIR` to use another directory — see [the FAQ](46-faq.md) for where to put session environment variables. Omasnap creates the directory when it saves the first shot. Set `[output] autosave = false` in `~/.config/omasnap/omasnap.conf` to disable automatic saving. + +From the terminal, `omarchy screenshot` opens the same overlay, and you can choose its starting mode: `omarchy capture screenshot region`, `windows`, `fullscreen`, or `scroll`. A second argument of `copy` or `save` skips the preview and sends the shot straight to that destination. To edit before output, use `omarchy screenshot --editor=overlay` for a fullscreen editor or `omarchy screenshot --editor=window` for a separate window. ### Driving the picker from the keyboard @@ -27,16 +29,18 @@ While the selection is up, you don't have to use the mouse at all: | Key | Function | | --- | -------- | +| `S` | Toggle scrolling-region mode | +| `Super + Arrow keys` | Move among windows in Window mode | | `Return` | Capture the highlighted window | -| `Ctrl + Return` | Capture the whole screen | -| `Tab` / `Ctrl + Tab` | Highlight the next / previous window | -| Arrow keys | Highlight the window in that direction | +| `Ctrl + A` | Capture the full focused monitor | +| `R` | Restore the last region drawn in this session | +| `Esc` | Dismiss Omasnap | -The arrows and Tab move the cursor to the window they pick, so the highlight follows along and you can see what you're about to capture. These bindings only exist while a selection is on screen, so they can't collide with anything in your own config. +These bindings only exist while Omasnap is open, so they can't collide with anything in your own config. ## Screen recording -`Alt + Print Screen` opens _Trigger > Capture > Screenrecord_, which asks what you want on the soundtrack: no audio, desktop audio, desktop plus microphone, or desktop plus microphone plus webcam. That last one only shows up if you actually have a camera plugged in. Pick one and you get the same picker as a screenshot: drag a region, or click a window or monitor. +`Alt + Print Screen` opens _Trigger > Capture > Screenrecord_, which asks what you want on the soundtrack: no audio, desktop audio, desktop plus microphone, or desktop plus microphone plus webcam. That last one only shows up if you actually have a camera plugged in. Pick one and Omarchy's recording picker lets you drag a region or click a window or monitor. Recording runs on gpu-screen-recorder, which encodes on the GPU at 60fps and falls back to the CPU if it has to. The result is an MP4 in `~/Videos`, named `screenrecording-2026-08-13_14-22-05.mp4`. Set `OMARCHY_SCREENRECORD_DIR` to change that — but note that unlike the screenshot directory, this one has to exist already, or the recording refuses to start. diff --git a/manual/13-toggles-idle-screensaver.md b/manual/13-toggles-idle-screensaver.md index 2effdac1e690..37770f37e269 100644 --- a/manual/13-toggles-idle-screensaver.md +++ b/manual/13-toggles-idle-screensaver.md @@ -15,6 +15,7 @@ From the terminal, the same switches are `omarchy toggle `. Run `omarchy | Stay awake (no idle lock) | `Super + Ctrl + I` | `omarchy toggle idle` | | Crash capture | — | `omarchy toggle crash-capture` | | Screensaver | — | `omarchy toggle screensaver` | +| [Herdr](https://herdr.dev) theme sync | — | `omarchy toggle theme sync` | | Menu bar | `Super + Shift + Space` | `omarchy toggle bar` | | Touchpad | `XF86TouchpadToggle` | `omarchy toggle touchpad` | | Touchscreen | — | `omarchy toggle touchscreen` | diff --git a/manual/14-omarchy-cli.md b/manual/14-omarchy-cli.md index fa5d0a05b70d..76f386e82073 100644 --- a/manual/14-omarchy-cli.md +++ b/manual/14-omarchy-cli.md @@ -50,7 +50,7 @@ Capture commands — Screenshots and screen recording: omarchy capture qr Decode a QR code from a screenshot region omarchy capture screenrecording [--fullscreen] [--with-desktop-audio] [--with-microphone-audio] [--with-webcam] [--webcam-device=] [--webcam-size=] [--resolution=] [--stop-recording] Start or stop screen recording omarchy capture screenrecording with webcam Pick a webcam and start a screen recording with it - omarchy capture screenshot [smart|region|windows|fullscreen] [slurp|copy|save] [--editor=] Take a screenshot + omarchy capture screenshot [smart|region|windows|fullscreen|scroll] [copy|save] Take a screenshot omarchy capture text Extract text from a screenshot region with OCR omarchy capture webcam resize Resize the active webcam recording overlay ``` diff --git a/manual/17-ai.md b/manual/17-ai.md index 8c3d48b024ca..6739a612777b 100644 --- a/manual/17-ai.md +++ b/manual/17-ai.md @@ -1,6 +1,6 @@ # AI -Omarchy treats AI coding agents as first-class citizens, but it doesn't pick a favorite for you. Instead, every major coding-agent CLI comes pre-wired as a lazy-loaded launcher. The launchers are tiny [mise](https://mise.jdx.dev/)-managed stubs in `~/.local/bin/`, so nothing is downloaded until the first time you actually run one. Invoke any of these and authenticate when prompted: +Omarchy treats AI coding agents as first-class citizens, but it doesn't pick a favorite for you. Instead, every major coding-agent CLI comes pre-wired as a lazy-loaded launcher. The launchers are tiny [mise](https://mise.jdx.dev/)-managed stubs in `~/.local/bin/`, so nothing is downloaded until the first time you actually run one. Hermes is the exception: nothing is stubbed for it, and choosing it installs Hermes Desktop, as _Desktop apps_ below explains. Invoke any of these and authenticate when prompted: | Command | Agent | |------------|------------------------------------------------------------------| @@ -26,11 +26,13 @@ To wrap an additional CLI the same way, run `omarchy-mise-install [com Pick your default agent with `omarchy default agent ` or under _Setup > Defaults > Agent_ in the Omarchy Menu (`Super + Space`). If the agent isn't installed yet, picking it installs it first. A fresh Omarchy will invite you to make this choice with a one-time notification. +Choosing Claude also attempts to set up its browser extension for Chromium, Chrome, Brave, Brave Origin, and Edge. The extension setup applies to all users and may ask for your system password; cancelling or a failed extension install still selects and launches Claude. Restart your browser, enable the extension if prompted, and sign in to Claude to finish connecting it. Run `/chrome` in Claude to check the connection. Firefox and Zen do not support this extension. If Claude was already your default before this setup was added, select it again to install the extension. + [Muse Code](https://dev.meta.ai) — Meta's `muse` — uses a preinstalled mise stub like the other agents. Picking it as the default installs Meta's official launcher through mise's HTTP backend. The launcher verifies and updates the native binary for your machine. Once you've chosen, `Super + Shift + Ctrl + A` launches the default agent in a dedicated terminal window (or brings up the picker if you haven't chosen yet). You can also launch it straight into a task with `omarchy agent prompt "Review this project"`. Agents launched this way run unattended in their respective don't-stop-to-ask modes, so be ready for them to actually do things! And since agents refuse to remember trust for your home directory, launches from `$HOME` start in `~/Work` instead. -There are terminal shortcuts too: `a` runs the default agent inline in the current terminal, while `c`, `cx`, and `cy` start OpenCode, Claude Code, and Codex directly (again in their auto-approving modes). Theme changes sync to the agents as well: Claude Code, Pi, OpenCode, and Hermes (once Hermes Desktop is installed) all follow along when you switch the Omarchy theme. +There are terminal shortcuts too: `a` runs the default agent inline in the current terminal, while `c`, `cx`, and `cy` start OpenCode, Claude Code, and Codex directly (again in their auto-approving modes). Theme changes sync to the agents as well: Claude Code, Pi, OpenCode, and Hermes (once Omarchy has installed it) all follow along when you switch the Omarchy theme. ### The agents panel @@ -50,7 +52,7 @@ Crashes can also be silenced one program at a time, which is what the diagnosis The _Install > AI_ menu also carries a few graphical AI apps: the ChatGPT desktop app, the Claude desktop app (Anthropic's Linux beta, with Chat, Cowork, and Claude Code tabs), Grok Bot for chatting with xAI's models, Hermes Desktop, OpenClaw, and the Perplexity desktop app. -Hermes Desktop is the one to know about, because there is only ever one Hermes on a machine. The app only runs against a runtime built from its own commit, so it installs one of its own under `~/.hermes` on first launch, which takes a few minutes and shows its own progress. From then on that is the Hermes the terminal `hermes` command and the default agent use too, whichever order you installed them in. Installing it also hands Hermes the Omarchy theme as a skin named `omarchy`, which every Hermes surface follows as you switch themes; pick another under Hermes' Appearance settings or with `/skin` if you'd rather it didn't, and Omarchy leaves that choice alone. Removing the app under _Remove > AI_ takes that runtime with it, and keeps your chats, memories, and the skills Hermes wrote for itself unless you tell it otherwise: it asks, defaulting to no, whether that data and your connection settings should go too. +Hermes Desktop is the one to know about, because a machine has one Hermes, and it is the app's: Hermes is only ever installed through the app, and the `hermes` command the default agent runs is the app's. Choosing Hermes as the default agent installs the same thing the _Install > AI_ entry does: the package, and a Hermes runtime under `~/.hermes` set up by Hermes' own installer, which takes a few minutes the first time. That runtime is the one Hermes the terminal `hermes` command, the default agent and the app all use, and it updates itself with `hermes update` rather than waiting on an Omarchy release. Installing it also hands Hermes the Omarchy theme as a skin named `omarchy`, which every Hermes surface follows as you switch themes; pick another under Hermes' Appearance settings or with `/skin` if you'd rather it didn't, and Omarchy leaves that choice alone. Removing the app under _Remove > AI_ closes Hermes first, gateway included, takes that runtime with it, and keeps your chats, memories, and the skills Hermes wrote for itself unless you tell it otherwise: it asks, defaulting to no, whether that data and your connection settings should go too. OpenClaw's desktop experience is its Control UI, which opens as a web app backed by its own local gateway. OpenClaw updates arrive through Omarchy's package updates, so skip the Control UI's own "Update Gateway" button: it would try to write into the package-managed install and fail. Removing OpenClaw under _Remove > AI_ takes the gateway service and the app with it and then asks whether `~/.openclaw` should go too, since that holds your chats and credentials alongside the plugin runtimes OpenClaw downloads for itself; the default keeps it. diff --git a/manual/19-shell-tools.md b/manual/19-shell-tools.md index 69965fdd4617..8252d795f95a 100644 --- a/manual/19-shell-tools.md +++ b/manual/19-shell-tools.md @@ -57,3 +57,5 @@ The full manual can be found via `man yt-dlp`. ## try [try](https://github.com/tobi/try) makes it easy to manage programming experiments with date-stamped directories. All experiments live in `~/Work/tries` and you can access them via `try`. + +Omarchy does not add a project's `bin/` directory to `PATH` automatically. Run trusted project-local tools with an explicit relative path, such as `bin/rails` or `./bin/dev`. diff --git a/manual/22-guis.md b/manual/22-guis.md index f5dfa8e8692d..56bc701cf343 100644 --- a/manual/22-guis.md +++ b/manual/22-guis.md @@ -59,6 +59,12 @@ Omarchy's firewall is closed by default except for LocalSend's port, so this wor You start LibreOffice via the application launcher (`Super + Space`). +## Hype + +[Hype](https://github.com/omacom/hype) is Omarchy's own dead-simple presentation app. Your deck is a single Markdown file with its images and videos beside it: write each slide below a live preview, drag slides into order, then present fullscreen or export to PDF and PowerPoint. It even picks up your Omarchy theme. + +You start Hype via the application launcher (`Super + Space`). Press `?` inside it to see every shortcut. + ## Omacalc [Omacalc](https://github.com/omacom-io/omacalc) is Omarchy's own dead-simple calculator, which opens in a floating window. @@ -94,3 +100,11 @@ You start Kdenlive via the application launcher (`Super + Space`). [Omacut](https://github.com/omacom-io/omacut) is Omarchy's own dead-simple video trimmer. When all you need is to cut the start and end off a clip, it beats firing up a full video editor. You start Omacut via the application launcher (`Super + Space`). + +## Monologue + +[Monologue](https://github.com/omacom/monologue) is Omarchy's own dead-simple webcam recorder. Choose your camera and microphone once, then press `Space` to record, and again to pause and resume the same take. It always records at your camera's highest resolution, with a live microphone meter so you can check your levels before you start. + +Stop the take and it opens right away in a built-in editor. Double-click a clip to split it, drag the handles to trim each piece, and remove the parts you don't want. Then save it as an MP4. Your original recording is kept until you discard it, so you can always come back and cut it differently. + +You start Monologue via the application launcher (`Super + Space`). diff --git a/manual/30-updates.md b/manual/30-updates.md index 246138c386a6..f0e82cede850 100644 --- a/manual/30-updates.md +++ b/manual/30-updates.md @@ -2,7 +2,7 @@ Omarchy and your packages are kept up to date via _Update > Omarchy_ in the Omarchy menu (`Super + Space`). -Omarchy itself is installed as regular pacman packages from the [Omarchy Package Repository](https://github.com/omacom-io/omarchy-pkgs), so an update installs [the latest Omarchy release](https://github.com/basecamp/omarchy/releases), runs any pending migrations to get your system in sync with the latest, and updates all system packages from the [Omarchy Arch Mirror](https://github.com/omacom-io/omarchy-mirror) and [AUR](https://aur.archlinux.org/) (if you have installed any AUR packages). +Omarchy itself is installed as regular pacman packages from the [Omarchy Package Repository](https://github.com/omacom-io/omarchy-pkgs), so an update installs [the latest Omarchy release](https://github.com/omacom/omarchy/releases), runs any pending migrations to get your system in sync with the latest, and updates all system packages from the [Omarchy Arch Mirror](https://github.com/omacom-io/omarchy-mirror) and [AUR](https://aur.archlinux.org/) (if you have installed any AUR packages). When new releases are made, a circle arrow icon will appear to the right of your clock. Click it and the update process will start. @@ -10,7 +10,7 @@ When new releases are made, a circle arrow icon will appear to the right of your ### Four channels -Omarchy is updated along four channels: stable, RC, edge, and dev. New installations start on the stable channel, which tracks the [official releases](https://github.com/basecamp/omarchy/releases/), as well as the [stable Omarchy Arch mirror](https://github.com/omacom-io/omarchy-mirror) that's running one month behind the latest, so we can catch any new incompatibilities that require config changes before they cause problems for people. +Omarchy is updated along four channels: stable, RC, edge, and dev. New installations start on the stable channel, which tracks the [official releases](https://github.com/omacom/omarchy/releases/), as well as the [stable Omarchy Arch mirror](https://github.com/omacom-io/omarchy-mirror) that's running one month behind the latest, so we can catch any new incompatibilities that require config changes before they cause problems for people. But if you'd like to help spot those potential issues, you can run on the edge channel. That'll keep your Omarchy packages tracking the latest development builds, and lets you update to the latest Arch packages as soon as they're available. You should only do this if you're experienced with Linux, and know how to recover a system that has problems. diff --git a/manual/31-dotfiles.md b/manual/31-dotfiles.md index ec148b445b14..420350fe761e 100644 --- a/manual/31-dotfiles.md +++ b/manual/31-dotfiles.md @@ -37,12 +37,14 @@ Omarchy fires hooks at a handful of moments, and you can hang your own scripts o | Event | When it runs | | ----- | ------------ | | `post-boot` | Right after the desktop has started | -| `post-update` | During `omarchy update`, after packages and migrations | -| `pre-refresh-pacman` | Before `omarchy refresh pacman` re-syncs the package config | +| `post-update` | Near the end of `omarchy update`, after packages, migrations, and service restarts, before mise tools are updated | +| `pre-refresh-pacman` | After `omarchy refresh pacman` re-syncs the package config, before it updates packages; a channel switch runs it during that same refresh step | | `theme-set` | After a theme change (theme name in `$1`) | | `font-set` | After a font change (font name in `$1`) | | `battery-low` | When the battery gets low (percentage in `$1`) | +The `pre-refresh-pacman` hook is where custom repositories or `IgnorePkg` lines belong, since it runs before the package transaction. Both update-related hooks run as your user after Omarchy clears its cached sudo authorization, so a hook that uses `sudo` needs its own authorization and may ask for your password. + Each of those directories already holds a `.sample` file showing the shape of a hook — drop the `.sample` from the name to put it to work. To install a script you've written elsewhere, use `omarchy hook install post-boot ~/my-hook`, which copies it in and makes it executable. ### Adding your own menu entries diff --git a/manual/32-shell-plugins.md b/manual/32-shell-plugins.md index 38ae40018ade..fc83a16f69d4 100644 --- a/manual/32-shell-plugins.md +++ b/manual/32-shell-plugins.md @@ -95,7 +95,7 @@ omarchy plugin validate ./my-plugin That runs the same checks the shell does at load time: the schema version, the required fields, an id that isn't reserved, entry points that are safe relative paths and actually exist, an entry point for every kind you claimed, and no symlinks anywhere inside the folder. -For the full picture, the source is the documentation: `shell/README.md` in the Omarchy repo covers the manifest schema, the shell's IPC contract, and the exact shape of `shell.json`, and `shell/plugins/README.md` lists every first-party plugin with its id, kinds, and entry points. +For plugin development, see the [shell reference](https://github.com/omacom/omarchy/blob/quattro/docs/omarchy-shell.md) and [first-party plugin catalog](https://github.com/omacom/omarchy/blob/quattro/shell/plugins/README.md). ## Sharing yours with the world diff --git a/manual/39-backgrounds.md b/manual/39-backgrounds.md index f2cd51eb69f4..3bc1f77bfb22 100644 --- a/manual/39-backgrounds.md +++ b/manual/39-backgrounds.md @@ -4,6 +4,8 @@ Every theme ships with its own set of backgrounds, and you can add extras of you You can do this most easily by going to _Install > Style > Background_ in the Omarchy Menu. That'll bring up the folder where the backgrounds for that theme is stored. Hit `Super + Shift + F` to start another file manager, find your background, copy it over. Now it'll be included in the choices of backgrounds you can select between using `Super + Ctrl + Space`. -Backgrounds can be videos as well as stills. Drop an `mp4`, `m4v`, `mov`, `webm`, `mkv`, or `avi` file in the same folder and it appears alongside the images, playing on a loop. Only your first monitor's wallpaper plays a video's sound track, through the default audio output at the system volume, and the lock screen stays silent. Playback stops on its own whenever nothing can see it — while a fullscreen window covers that monitor, while the screensaver is up, and once a locked screen has gone dark — but a video wallpaper still costs far more power than a still one, and each monitor decodes its own copy. +Backgrounds can be videos as well as stills. Drop an `mp4`, `m4v`, `mov`, `webm`, `mkv`, or `avi` file in the same folder and it appears alongside the images. Videos are played by the OWE wallpaper engine. It decodes the video once for all monitors and plays its sound through the default audio output, and it stops playback whenever nothing can see it. The lock screen draws the same decode, muted, through OWE. A video wallpaper still costs far more power than a still one. You can find a huge collection of cool curated backgrounds on https://github.com/dharmx/walls. + +Video backgrounds keep a cached still on the lock screen while playback is paused or unavailable. Animated GIFs play on the desktop and show a still frame on the lock screen. diff --git a/manual/46-faq.md b/manual/46-faq.md index 6c6254072123..5def15d6a881 100644 --- a/manual/46-faq.md +++ b/manual/46-faq.md @@ -54,15 +54,15 @@ Automatic discovery, where printers on the network appear without being added, i ### How do I change where screenshots or screenrecordings are saved? -If you want screenshots to be saved to `~/Pictures/Screenshots` instead of just `~/Pictures`, you can add this to a file under `~/.config/uwsm/env.d/` (like `~/.config/uwsm/env.d/capture`): +Saved screenshots go to `~/Pictures/Screenshots` by default. To use another directory, add this to a file under `~/.config/uwsm/env.d/` (like `~/.config/uwsm/env.d/capture`): ``` -export OMARCHY_SCREENSHOT_DIR="$HOME/Pictures/Screenshots" +export OMASNAP_SCREENSHOT_DIR="$HOME/Pictures/Captures" ``` You can do the same for screenrecordings using `OMARCHY_SCREENRECORD_DIR`. -Just remember to create the directoy you want to save to and restart Omarchy for this to take effect. +Omasnap creates its screenshot directory automatically. Create the screenrecording directory yourself, then restart Omarchy for either environment change to take effect. ### How do I get the speakers + webcam working on my Apple Studio Display? diff --git a/manual/48-security.md b/manual/48-security.md index 45750398e309..6db0dff5f17c 100644 --- a/manual/48-security.md +++ b/manual/48-security.md @@ -20,7 +20,9 @@ It works by restoring the baseline snapshot the installer takes, so it's only av ## Passwordless sudo -Sometimes you want `sudo` to stop asking, most often when an AI agent is doing a long stretch of system work for you. _Setup > Security > Passwordless Sudo_ turns that off for 15 minutes and then puts it back automatically. Run it again before the timer runs out to end it early, and pass your own number of minutes with `omarchy-sudo-passwordless 30` if 15 isn't enough. A restart removes the passwordless sudo rule as well. +Sometimes you want `sudo` to stop asking, most often when an AI agent is doing a long stretch of system work for you. _Setup > Security > Passwordless Sudo_ turns that off for 15 wall-clock minutes and then puts it back automatically, including immediately after resuming from a suspend that crossed the deadline. A package-owned boot-time cleanup rule removes the grant before logins if the computer restarts first. Run the command again before the timer runs out to end it early, and pass your own number of minutes (from 1 to 1440) with `omarchy-sudo-passwordless 30` if 15 isn't enough. + +Updating or removing Omarchy's settings package ends any temporary grant before its expiry support changes. If the command reports an authorization or cleanup error, resolve it before trying to enable another grant; an error does not mean passwordless access is inactive. Be clear-eyed about this one: while it's on, anything running as your user can do anything as root without being asked. That's the whole point, and it's also the whole risk. diff --git a/manual/49-omarchy-on.md b/manual/49-omarchy-on.md index c33642fd7a7a..af066999d07e 100644 --- a/manual/49-omarchy-on.md +++ b/manual/49-omarchy-on.md @@ -6,15 +6,15 @@ ### Apple Virtual Machine -You can also install Omarchy inside a Parallels VM. Quite the cumbersome process, but there's [a user-driven guide](https://github.com/basecamp/omarchy/discussions/452) for that too. +You can also install Omarchy inside a Parallels VM. Quite the cumbersome process, but there's [a user-driven guide](https://github.com/omacom/omarchy/discussions/452) for that too. ### VirtualBox -VirtualBox is a popular VM runner. [You can run Omarchy inside that too](https://github.com/basecamp/omarchy/discussions/176). But performance probably won't be great. +VirtualBox is a popular VM runner. [You can run Omarchy inside that too](https://github.com/omacom/omarchy/discussions/176). But performance probably won't be great. ### VMware Workstation on Windows 11 -Another popular VM runner for Windows. [Omarchy has been setup inside of that as well](https://github.com/basecamp/omarchy/discussions/572). +Another popular VM runner for Windows. [Omarchy has been setup inside of that as well](https://github.com/omacom/omarchy/discussions/572). ### Steam Deck diff --git a/migrations/1786609204.sh b/migrations/1786609204.sh index b7833092083e..ce1442ca0d93 100644 --- a/migrations/1786609204.sh +++ b/migrations/1786609204.sh @@ -1,3 +1 @@ -echo "Install native video wallpaper playback dependencies" - -omarchy-pkg-add qt6-multimedia qt6-multimedia-ffmpeg +echo "Native video dependencies are superseded by the OWE migration" diff --git a/migrations/1787760281.sh b/migrations/1787760281.sh index 952fa9a28101..4d7af7532d8d 100644 --- a/migrations/1787760281.sh +++ b/migrations/1787760281.sh @@ -1,25 +1,3 @@ echo "Install the Hermes CLI wrapper for existing installs" -# Users who removed the preinstalls opted out of the mise wrappers, and Hermes -# is one of them. -[[ -f $HOME/.local/state/omarchy/preinstalls-removed ]] && exit 0 - -# Hermes Desktop provides its own Hermes. The installer stands aside for it, -# removing the mise copy and the Omarchy wrapper an earlier install may have -# left beside the app. It also reports when the app has not finished setting -# Hermes up, which is the app's to finish, not this migration's to fail on. -if omarchy-pkg-present hermes-desktop; then - omarchy-install-hermes-cli || true - exit 0 -fi - -# Anything already answering to hermes that this installer did not write -- -# an official install, a hand-rolled wrapper, even a dangling link -- belongs to -# the user and stays exactly as it is. The installer is asked rather than -# matched against here, so there is one answer to who owns that wrapper. -wrapper="$HOME/.local/bin/hermes" -if [[ -e $wrapper || -L $wrapper ]] && ! omarchy-install-hermes-cli --owns; then - exit 0 -fi - -omarchy-install-hermes-cli +# Nothing to install any more: the mise-backed wrapper this wrote was retired in favour of the self-updating runtime, and the migration that retired it clears any it had already written. diff --git a/migrations/1788129995.sh b/migrations/1788129995.sh new file mode 100644 index 000000000000..965e01db56af --- /dev/null +++ b/migrations/1788129995.sh @@ -0,0 +1,18 @@ +echo "Replace Satty and Tensaku with Omasnap" + +omarchy-pkg-add omasnap + +# The old source installer left a NoDisplay entry that overrides the packaged launcher. +rm -f "$HOME/.local/share/applications/omasnap.desktop" + +imv_config="$HOME/.config/imv/config" +if [[ -f $imv_config ]]; then + sed -i --follow-symlinks \ + -e 's/^# Edit the current image in Tensaku and quit the viewer$/# Edit the current image in Omasnap and quit the viewer/' \ + -e 's/^# Edit the current image in Satty and quit the viewer$/# Edit the current image in Omasnap and quit the viewer/' \ + -e 's|^ = exec tensaku-edit "$imv_current_file" & ; quit$| = exec omasnap "$imv_current_file" \& ; quit|' \ + -e 's|^ = exec satty --filename "$imv_current_file" & ; quit$| = exec omasnap "$imv_current_file" \& ; quit|' \ + "$imv_config" +fi + +omarchy-pkg-drop satty tensaku diff --git a/migrations/1788163635.sh b/migrations/1788163635.sh new file mode 100644 index 000000000000..f0925b408e9d --- /dev/null +++ b/migrations/1788163635.sh @@ -0,0 +1,9 @@ +echo "Remove legacy temporary passwordless sudo grants" + +# Migration queues are per-user; the privileged repair is once per machine. +# The helper beside this migration: the package's /usr/bin copy on an install, +# and under a dev link the checkout's, which may be newer than the package. +helper="$OMARCHY_PATH/bin/omarchy-sudo-passwordless" +if ! "$helper" __migration-complete; then + sudo "$helper" __migrate +fi diff --git a/migrations/1788279117.sh b/migrations/1788279117.sh new file mode 100644 index 000000000000..35f3571a9754 --- /dev/null +++ b/migrations/1788279117.sh @@ -0,0 +1,86 @@ +echo "Replace the YT6801 vendor DKMS driver with the upstream kernel driver" + +if ! yt6801_pci=$(lspci -Dn -d 1f0a:6801); then + echo "Unable to discover YT6801 adapters; rerun omarchy-migrate." >&2 + exit 1 +fi + +yt6801_devices=() +while read -r device _; do + [[ -n $device ]] || continue + if [[ ! $device =~ ^[[:xdigit:]]{4}:[[:xdigit:]]{2}:[[:xdigit:]]{2}\.[0-7]$ ]]; then + echo "Invalid YT6801 PCI address: $device" >&2 + exit 1 + fi + yt6801_devices+=("$device") +done <<< "$yt6801_pci" + +yt6801_uses_upstream() { + local driver + driver=$(readlink -f "/sys/bus/pci/devices/$1/driver") && + [[ $driver == "/sys/bus/pci/drivers/dwmac-motorcomm" ]] +} + +yt6801_check_binding() { + local device + for device in "${yt6801_devices[@]}"; do + if ! yt6801_uses_upstream "$device"; then + echo "YT6801 device $device did not bind to dwmac-motorcomm." >&2 + echo "Reboot into the latest Omarchy kernel and rerun omarchy-migrate." >&2 + exit 1 + fi + done +} + +# Check discovery before changing hardware or packages. A failed query must not +# turn into an empty list and mark the migration complete. +installed_packages=$(pacman -Qq) +loaded_modules=$(lsmod) + +yt6801_pending=() +for device in "${yt6801_devices[@]}"; do + if ! yt6801_uses_upstream "$device"; then + yt6801_pending+=("$device") + fi +done + +if (( ${#yt6801_pending[@]} > 0 )); then + if ! aliases=$(modinfo -F alias dwmac-motorcomm) || + ! grep -Fxq 'pci:v00001F0Ad00006801sv*sd*bc*sc*i*' <<< "$aliases"; then + echo "The running kernel does not provide YT6801 support in dwmac-motorcomm." >&2 + echo "Reboot into the latest Omarchy kernel and rerun omarchy-migrate." >&2 + exit 1 + fi + + # Validate the replacement before unloading the installed fallback. Already + # migrated machines need no module load or privilege prompt for later users. + sudo modprobe dwmac-motorcomm +fi + +if grep -Eq '^yt6801[[:space:]]' <<< "$loaded_modules"; then + # rmmod also works on retries after DKMS has deleted the module files and + # lookup index. Never force removal of a module that is still busy. + sudo rmmod yt6801 +fi + +for device in "${yt6801_pending[@]}"; do + if ! yt6801_uses_upstream "$device"; then + printf '%s\n' "$device" | sudo tee /sys/bus/pci/drivers_probe >/dev/null + fi +done +yt6801_check_binding + +# Keep the package available until the live cutover succeeds. Package removal +# invokes DKMS/depmod hooks, so unloading must happen before this transaction. +if grep -Fxq 'yt6801-dkms' <<< "$installed_packages"; then + omarchy-pkg-drop yt6801-dkms +fi + +installed_packages=$(pacman -Qq) +loaded_modules=$(lsmod) +if grep -Fxq 'yt6801-dkms' <<< "$installed_packages" || + grep -Eq '^yt6801[[:space:]]' <<< "$loaded_modules"; then + echo "The YT6801 vendor package or module is still present; rerun omarchy-migrate." >&2 + exit 1 +fi +yt6801_check_binding diff --git a/migrations/1788996284.sh b/migrations/1788996284.sh new file mode 100644 index 000000000000..c72093bc4651 --- /dev/null +++ b/migrations/1788996284.sh @@ -0,0 +1,51 @@ +echo "Repair remote Neovim clipboard yanks and paste" + +nvim_provider="$HOME/.config/nvim/lua/config/remote_clipboard.lua" +provider_source="/usr/share/omarchy-nvim/config/lua/config/remote_clipboard.lua" + +# Dotfile managers may own either the file or a parent directory through a +# symlink. Preserve that layout rather than detaching or editing its target. +provider_path="$nvim_provider" +while [[ $provider_path != "$HOME" && $provider_path != / ]]; do + if [[ -L $provider_path ]]; then + echo "Preserving symlink-managed Neovim provider: $nvim_provider" + echo "Review remote clipboard settings in your dotfile configuration manually." + exit 0 + fi + provider_path=$(dirname "$provider_path") +done + +[[ -f $nvim_provider ]] || exit 0 + +# Replace only known Omarchy versions, including the June file-backed provider +# and the two earlier proposed fixes. Preserve all user-authored changes. +provider_hash=$(sha256sum "$nvim_provider") +case ${provider_hash%% *} in + c0c15941ed7cf97a1a3d3c60f0b13875e85f641bdb7431c3283e6f86fbc95f4e|bac8268c3dde4e747772467d6671e626aa4982478551d8fc8ebe1259a4854f2c|7f012a235c05e3c559b48211c1534af2f4c919750b76db88ec3d5b7814259d30|8b371d0f271e522b27696f1b71083d0a6ba7896cd3ff7b0a938b7327fcb06a46) ;; + *) + if [[ -f $provider_source ]] && cmp -s "$nvim_provider" "$provider_source"; then + exit 0 + fi + echo "Preserving customized Neovim provider: $nvim_provider" + echo "Review remote clipboard settings manually, or use omarchy-nvim-refresh to reset them." + exit 0 + ;; +esac + +# Updates install packages before migrations. Refuse an older package so this +# migration remains pending instead of installing the provider it must repair. +nvim_package=$(pacman -Q omarchy-nvim) +if [[ $(vercmp "${nvim_package#* }" "2026.9.21-2") == -* ]] || [[ ! -f $provider_source ]]; then + echo "Update omarchy-nvim to 2026.9.21-2 or newer before rerunning this migration." >&2 + exit 1 +fi + +provider_backup=$(mktemp "$nvim_provider.bak.XXXXXX") +cp -p "$nvim_provider" "$provider_backup" +provider_staged=$(mktemp "$nvim_provider.new.XXXXXX") +trap 'rm -f -- "$provider_staged"' EXIT +install -m 0644 "$provider_source" "$provider_staged" +# A failed write leaves the recognized original live, so retries can repair it. +# The temporary file is on the same filesystem for an atomic replacement. +mv -fT -- "$provider_staged" "$nvim_provider" +echo "Previous Neovim provider saved to $provider_backup" diff --git a/migrations/1789095456.sh b/migrations/1789095456.sh new file mode 100644 index 000000000000..381557fc79b7 --- /dev/null +++ b/migrations/1789095456.sh @@ -0,0 +1,99 @@ +echo "Remove automatic project bin directories from PATH" + +work_dir="$HOME/Work" +mise_config="$work_dir/.mise.toml" +# install/user/mise-work.sh as shipped in Omarchy 4.0.3. +stock_sha="bd04f191d63bbde86920f44f76f0989fad980afc84e268e8474c201ec7149245" +cwd_bin='\{\{[[:space:]]*cwd[[:space:]]*\}\}/bin' +unsafe_path="^[[:space:]]*_[.]path[[:space:]]*=[[:space:]]*(\"$cwd_bin\"|'$cwd_bin')[[:space:]]*(#.*)?$" +env_section='^[[:space:]]*\[[[:space:]]*env[[:space:]]*\][[:space:]]*(#.*)?$' +any_section='^[[:space:]]*\[\[?.*\]\]?[[:space:]]*(#.*)?$' + +remove_empty_work_dir=false +if [[ ! -e $work_dir ]]; then + mkdir -p "$work_dir" + remove_empty_work_dir=true +fi + +was_ignored=false +if [[ -d $work_dir ]]; then + mise_state_dir=${MISE_STATE_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/mise} + ignored_configs_dir="$mise_state_dir/ignored-configs" + work_target=$(readlink -m "$work_dir") + config_path_target="$work_target/.mise.toml" + config_target=$(readlink -m "$mise_config") + + if [[ -d $ignored_configs_dir ]]; then + for ignored_entry in "$ignored_configs_dir"/*; do + [[ -L $ignored_entry ]] || continue + ignored_target=$(readlink "$ignored_entry") + if [[ $ignored_target == $work_target || $ignored_target == $config_path_target || $ignored_target == $config_target ]]; then + was_ignored=true + break + fi + done + fi + + if [[ $was_ignored == "false" ]]; then + # Normal Mise trust is recorded against the config-root directory, while + # paranoid trust is recorded against the file and its contents. Stage an + # empty, inert config when the legacy file is gone so either trust mode can + # resolve and revoke the original grant. + remove_empty_mise_config=false + if [[ ! -e $mise_config && ! -L $mise_config ]]; then + if (set -o noclobber; : >"$mise_config") 2>/dev/null; then + remove_empty_mise_config=true + fi + fi + + untrust_target="$work_dir" + if [[ -f $mise_config ]]; then + untrust_target="$mise_config" + fi + + if mise trust --untrust "$untrust_target"; then + : + else + if [[ $remove_empty_mise_config == "true" ]]; then + rm -f -- "$mise_config" + fi + exit 1 + fi + + if [[ $remove_empty_mise_config == "true" ]]; then + rm -f -- "$mise_config" + fi + fi +fi + +if [[ -f $mise_config ]]; then + if [[ ! -L $mise_config && $(sha256sum "$mise_config" | cut -d ' ' -f 1) == $stock_sha ]]; then + rm -f -- "$mise_config" + else + unsafe_env_paths=$(sed -n -E "\\%$env_section%,\\%$any_section% { \\%$unsafe_path%p; }" "$mise_config") + if [[ -n $unsafe_env_paths ]]; then + backup=$(mktemp "$mise_config.bak.XXXXXX") + cp -p -- "$mise_config" "$backup" + sed --follow-symlinks -i -E "\\%$env_section%,\\%$any_section% { \\%$unsafe_path%d; }" "$mise_config" + + printf '\n%s\n' \ + "Automatic project bin directories were removed from your Mise PATH." \ + "Your other Mise settings were preserved." + printf '\nBackup saved to:\n %s\n' "$backup" + fi + fi +fi + +if [[ -f $mise_config ]]; then + if [[ $was_ignored == "true" ]]; then + printf '\n%s\n' "This custom config remains ignored by Mise." + else + printf '\n%s\n %s\n' \ + "Mise trust for this custom config was revoked. Review it before trusting it again:" \ + "mise trust $mise_config" + fi +fi + +if [[ $remove_empty_work_dir == "true" ]]; then + rmdir "$work_dir" 2>/dev/null || true +fi diff --git a/migrations/1789130779.sh b/migrations/1789130779.sh new file mode 100644 index 000000000000..56d9fe2077be --- /dev/null +++ b/migrations/1789130779.sh @@ -0,0 +1,9 @@ +echo "Keep the KEF LSX II LT USB sink from suspending" + +conf="wireplumber/wireplumber.conf.d/kef-lsx-no-suspend.conf" + +if [[ ! -f "$HOME/.config/$conf" ]]; then + omarchy-refresh-config "$conf" + # WirePlumber only reads conf.d at startup; restart it if it is running. + systemctl --user try-restart wireplumber.service 2>/dev/null || true +fi diff --git a/migrations/1789294350.sh b/migrations/1789294350.sh new file mode 100644 index 000000000000..9eba04162ca4 --- /dev/null +++ b/migrations/1789294350.sh @@ -0,0 +1,11 @@ +echo "Switch TCP congestion control to BBR with fq pacing" + +# Boot applies the shipped file regardless; this only makes new connections +# use BBR now. Setting the sysctls autoloads tcp_bbr and sch_fq. Qdiscs +# already attached to interfaces stay until they are recreated, normally at +# reboot. +if [[ $(sysctl -n net.ipv4.tcp_congestion_control) == "bbr" && $(sysctl -n net.core.default_qdisc) == "fq" ]]; then + exit 0 +fi + +sudo sysctl -p /etc/sysctl.d/99-omarchy-sysctl.conf >/dev/null || omarchy-state set reboot-required diff --git a/migrations/1789310715.sh b/migrations/1789310715.sh new file mode 100644 index 000000000000..a182dc8b5482 --- /dev/null +++ b/migrations/1789310715.sh @@ -0,0 +1,5 @@ +echo "Install cf (Cloudflare CLI) via mise wrapper" + +if [[ ! -f $HOME/.local/state/omarchy/preinstalls-removed ]]; then + omarchy-mise-install npm:cf cf +fi diff --git a/migrations/1789325478.sh b/migrations/1789325478.sh new file mode 100644 index 000000000000..14ba7d98b303 --- /dev/null +++ b/migrations/1789325478.sh @@ -0,0 +1,44 @@ +echo "Install the Omarchy kernel and make it the first Limine boot entry" + +# linux-omarchy is an x86_64 kernel. T2 Macs must keep their specialized kernel, +# including when other kernels are installed or the running T2 package is gone. +[[ $(uname -m) == "x86_64" ]] || exit 0 +running_kernel=$(uname -r) +if omarchy-pkg-present linux-t2 || [[ ${running_kernel,,} == *-t2* ]]; then + exit 0 +fi + +limine_conf="${OMARCHY_KERNEL_LIMINE_CONF:-/etc/default/limine}" +rebuild_marker="${OMARCHY_KERNEL_REBUILD_MARKER:-/var/lib/omarchy/migrations/1789325478}" +kernel="linux-omarchy" + +# Completion is machine-wide even though migrations run once per user. Leave +# the old kernel installed so it remains available if the new one cannot boot. +# The new filename and marker also reach users who completed 1789095456. +[[ ! -e $rebuild_marker ]] || exit 0 +omarchy-pkg-add "$kernel" "$kernel-headers" + +# /etc/default/limine has priority over every drop-in, including old Dell +# settings and customized package files whose updates landed in a .pacnew. +# Set the exact kernel first: linux-omarchy-* only matches its older variants. +# Preserve unrelated settings, especially the root filesystem's kernel cmdline. +sudo mkdir -p "$(dirname "$limine_conf")" +sudo touch "$limine_conf" +sudo sed -i -E '/^[[:space:]]*BOOT_ORDER[[:space:]]*=/d' "$limine_conf" +printf '\n%s\n' 'BOOT_ORDER="linux-omarchy, linux-omarchy-*, *, *fallback, Snapshots"' | sudo tee -a "$limine_conf" >/dev/null + +# Package hooks ran before the config repair. Rebuild the new kernel's image +# and boot entry explicitly, including on retries after a failed rebuild. +sudo limine-mkinitcpio "$kernel" + +# limine-mkinitcpio can return success after skipping a failed kernel build. +# Do not mark the migration complete unless the new kernel is in the menu. +if ! sudo limine-entry-tool --tree | grep -E "(^|[^[:alnum:]_-])$kernel([^[:alnum:]_-]|$)" >/dev/null; then + echo "The Omarchy kernel has no Limine boot entry; rerun omarchy-migrate after fixing the boot image build." >&2 + exit 1 +fi + +# Keeping the running kernel installed prevents the updater from detecting a +# kernel replacement, so request the reboot explicitly. +omarchy-state set reboot-required +sudo install -Dm644 /dev/null "$rebuild_marker" diff --git a/migrations/1789444024.sh b/migrations/1789444024.sh new file mode 100644 index 000000000000..b5bc9149dded --- /dev/null +++ b/migrations/1789444024.sh @@ -0,0 +1,10 @@ +echo "Install missing headers for the Omarchy or T2 kernel" + +# Fresh ISO installs mark earlier migrations complete, so the kernel migration +# cannot repair headers omitted by those installers. Package installation is +# idempotent when another user has already applied this repair. +for kernel in linux-omarchy linux-t2; do + if omarchy-pkg-present "$kernel"; then + omarchy-pkg-add "$kernel-headers" + fi +done diff --git a/migrations/1789764927.sh b/migrations/1789764927.sh new file mode 100644 index 000000000000..e2d1541e4fe4 --- /dev/null +++ b/migrations/1789764927.sh @@ -0,0 +1,17 @@ +echo "Enable OWE desktop video backgrounds and lock feed" + +omarchy-pkg-add owe owe-lockfeed +omarchy-hook-install theme-set /usr/share/owe/10-owe-sync + +systemctl --user daemon-reload >/dev/null 2>&1 || true +if ! systemctl --user enable owed.service; then + wants_dir="$HOME/.config/systemd/user/graphical-session.target.wants" + mkdir -p "$wants_dir" + ln -sfn /usr/lib/systemd/user/owed.service "$wants_dir/owed.service" +fi + +# A TTY update enables the next graphical login without starting a renderer +# against a missing Wayland session. A failed live start leaves this pending. +if [[ ${OMARCHY_UPGRADE_TO_QUATTRO_LIVE:-0} != 1 ]] && systemctl --user is-active --quiet graphical-session.target; then + systemctl --user start owed.service +fi diff --git a/migrations/1790017600.sh b/migrations/1790017600.sh new file mode 100644 index 000000000000..4248a67e68c4 --- /dev/null +++ b/migrations/1790017600.sh @@ -0,0 +1,9 @@ +echo "Retire the Hermes that mise built; Hermes now updates itself" + +# Hermes installs the way Hermes Desktop does now: upstream's installer makes a checkout under ~/.hermes that `hermes update` fast-forwards. The wrapper that built Hermes through mise had nothing an update could move, so it goes, with the mise environment it built. The wrapper, the environment and what proves them Omarchy's are known to the installer and nowhere else, so it is asked rather than matched against here; it leaves a hermes the user set up themselves, and a mise environment without the wrapper, as they are, and exits non-zero with the commands to finish by hand when the environment cannot be removed, which keeps this pending rather than done. +omarchy-install-hermes-cli --retire-mise + +# Choosing Hermes again is what installs the runtime, and nothing else will. +if [[ $(omarchy-default-agent) == "hermes" ]] && ! omarchy-install-hermes-cli --check; then + echo "Hermes is the default agent but is no longer installed. Choose it again under Setup > Default Agent, or run: omarchy default agent hermes" +fi diff --git a/migrations/1790042972.sh b/migrations/1790042972.sh new file mode 100644 index 000000000000..4e74c6933bd9 --- /dev/null +++ b/migrations/1790042972.sh @@ -0,0 +1,13 @@ +echo "Put Elsewhen, the world clock, on the bar" + +# Best-effort, like the put below: an update whose shell cannot be asked still +# finishes, and restarts the shell once the migrations are through. +omarchy-shell -q shell rescanPlugins + +# A legacy omacom.elsewhen entry is renamed in place by a later migration. +config_file="$HOME/.config/omarchy/shell.json" +if [[ -s $config_file ]] && jq -e '[.bar.layout[]?[]? | if type == "object" then .id else . end] | index("omacom.elsewhen")' "$config_file" >/dev/null 2>&1; then + echo "Elsewhen is already on the bar" +else + omarchy-bar put omarchy.elsewhen --before omarchy.clock +fi diff --git a/migrations/1790282866.sh b/migrations/1790282866.sh new file mode 100644 index 000000000000..92c9734a88dd --- /dev/null +++ b/migrations/1790282866.sh @@ -0,0 +1,8 @@ +echo "Apply the NVIDIA video driver fix on hybrid laptops" + +if omarchy-hw-nvidia && ! omarchy-hw-nvidia-display; then + # Hyprland applies env at startup. Reloading the updated defaults cannot + # clear the old overrides inherited by the compositor and its applications. + omarchy-state set reboot-required + echo "Reboot to stop forcing NVIDIA VA-API/GLX drivers on the integrated GPU." +fi diff --git a/migrations/1790457067.sh b/migrations/1790457067.sh new file mode 100644 index 000000000000..434263034e13 --- /dev/null +++ b/migrations/1790457067.sh @@ -0,0 +1,7 @@ +echo "Loosen the offline install's exact Node pin so mise up tracks new releases" + +mise_config="$HOME/.config/mise/config.toml" + +if [[ -f $mise_config ]] && grep -qE '^node = "[0-9]+\.[0-9]+\.[0-9]+"$' "$mise_config"; then + sed -i -E 's/^node = "[0-9]+\.[0-9]+\.[0-9]+"$/node = "latest"/' "$mise_config" +fi diff --git a/migrations/1790528634.sh b/migrations/1790528634.sh new file mode 100644 index 000000000000..5b82246242b9 --- /dev/null +++ b/migrations/1790528634.sh @@ -0,0 +1,30 @@ +echo "Move Elsewhen, the world clock, into Omarchy as omarchy.elsewhen" + +# The widget keeps its entry, and with it the cities and settings stored there. +config_file="$HOME/.config/omarchy/shell.json" +if [[ -s $config_file ]]; then + tmp=$(mktemp) + jq ' + def rename: + if . == "omacom.elsewhen" then "omarchy.elsewhen" + elif type == "object" and .id == "omacom.elsewhen" then .id = "omarchy.elsewhen" + end; + + if (.bar.layout | type) == "object" then .bar.layout |= map_values(if type == "array" then map(rename) end) end + | if (.bar.centerAnchor | type) == "string" then .bar.centerAnchor |= rename end + | if (.plugins | type) == "array" then .plugins |= map(rename) end + | if (.disabledPlugins | type) == "array" then .disabledPlugins |= map(rename) end + ' "$config_file" >"$tmp" + mv "$tmp" "$config_file" +fi + +# Dev checkouts found the packaged plugin through this link; one the user made +# elsewhere is left alone. +user_plugin="$HOME/.config/omarchy/plugins/omacom.elsewhen" +if [[ -L $user_plugin && $(readlink "$user_plugin") == /usr/share/omarchy/* ]]; then + rm "$user_plugin" +fi + +rm -rf "${XDG_CACHE_HOME:-$HOME/.cache}/omacom-elsewhen" + +omarchy-pkg-drop elsewhen diff --git a/migrations/1790539857.sh b/migrations/1790539857.sh new file mode 100644 index 000000000000..2fa106206a39 --- /dev/null +++ b/migrations/1790539857.sh @@ -0,0 +1,5 @@ +echo "Install Monologue, the webcam recorder" + +if [[ ! -f $HOME/.local/state/omarchy/preinstalls-removed ]]; then + omarchy-pkg-add monologue +fi diff --git a/migrations/1790542069.sh b/migrations/1790542069.sh new file mode 100644 index 000000000000..be49f21c25c6 --- /dev/null +++ b/migrations/1790542069.sh @@ -0,0 +1,5 @@ +echo "Install Hype, the Markdown presentation app" + +if [[ ! -f $HOME/.local/state/omarchy/preinstalls-removed ]]; then + omarchy-pkg-add hype +fi diff --git a/shell/Commons/Color.qml b/shell/Commons/Color.qml index 54163a400814..4fd2452b3b93 100644 --- a/shell/Commons/Color.qml +++ b/shell/Commons/Color.qml @@ -49,9 +49,15 @@ QtObject { } function flatColor(value, fallback) { + var seen = Object.create(null) var token = firstColorToken(value) var role = String(token || "").replace(/^\s+|\s+$/g, "").toLowerCase() - if (root.shellValues[role] && root.shellValues[role] !== token) return flatColor(root.shellValues[role], fallback) + while (root.shellValues[role] && root.shellValues[role] !== token) { + if (seen[role]) return fallback + seen[role] = true + token = firstColorToken(root.shellValues[role]) + role = String(token || "").replace(/^\s+|\s+$/g, "").toLowerCase() + } if (role === "foreground" || role === "text") return root.foreground if (role === "accent") return root.accent if (role === "urgent") return root.urgent diff --git a/shell/Commons/IpcRegistry.qml b/shell/Commons/IpcRegistry.qml new file mode 100644 index 000000000000..e479df288ecd --- /dev/null +++ b/shell/Commons/IpcRegistry.qml @@ -0,0 +1,77 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Io + +// Every ShellIpc handler, so the shell can answer an omarchy-shell call over +// its own socket instead of through a qs ipc client started per call. It +// answers only what qs ipc would: the first live, enabled handler for a +// target, and only the functions that handler declares. Those are allowed by +// name, never inferred from what a function call happens to reach: QObject +// methods such as destroy() are callable but not enumerable. +Singleton { + id: root + + property var handlers: [] + + // A bare handler's own functions (signals and hooks such as targetChanged), + // which qs ipc never exposes and neither may the socket. + readonly property var builtins: functionNames(bareHandler) + + IpcHandler { + id: bareHandler + enabled: false + } + + function functionNames(object) { + var names = [] + for (var key in object) { + if (typeof object[key] === "function") names.push(key) + } + return names + } + + function register(handler) { + if (handlers.indexOf(handler) === -1) handlers.push(handler) + } + + function unregister(handler) { + var index = handlers.indexOf(handler) + if (index !== -1) handlers.splice(index, 1) + } + + function handlerFor(target) { + for (var i = 0; i < handlers.length; i++) { + var handler = handlers[i] + if (handler && handler.enabled && handler.target === target) return handler + } + return null + } + + // { ran: true, output } once the function ran; { ran: false } when it did + // not (unknown target or function, wrong argument count), so the caller + // can ask qs ipc for its exact answer without running anything twice. + // The functions a handler declares: what it enumerates beyond a bare + // handler, less property change signals. + function declaredFunctions(handler) { + return functionNames(handler).filter(function(name) { + return builtins.indexOf(name) === -1 && !/Changed$/.test(name) + }) + } + + function call(target, method, args) { + var handler = handlerFor(target) + if (!handler) return { ran: false } + if (declaredFunctions(handler).indexOf(method) === -1) return { ran: false } + if (handler[method].length !== args.length) return { ran: false } + + var result + try { + result = handler[method].apply(handler, args) + } catch (error) { + console.warn("ipc " + target + " " + method + " failed: " + error) + return { ran: true, output: "" } + } + return { ran: true, output: result === undefined || result === null ? "" : String(result) } + } +} diff --git a/shell/Commons/ShellIpc.qml b/shell/Commons/ShellIpc.qml new file mode 100644 index 000000000000..15f5d27e5321 --- /dev/null +++ b/shell/Commons/ShellIpc.qml @@ -0,0 +1,12 @@ +import QtQuick +import Quickshell.Io + +// An IpcHandler the shell can also answer over its own socket (see +// IpcRegistry), so omarchy-shell reaches it without a qs ipc client. qs ipc +// still reaches it as before. +IpcHandler { + id: handler + + Component.onCompleted: IpcRegistry.register(handler) + Component.onDestruction: IpcRegistry.unregister(handler) +} diff --git a/shell/Commons/Style.qml b/shell/Commons/Style.qml index ec61252b7626..0582356cfdae 100644 --- a/shell/Commons/Style.qml +++ b/shell/Commons/Style.qml @@ -1,6 +1,7 @@ pragma Singleton import QtQuick import Quickshell +import Quickshell.Hyprland import Quickshell.Io // Shared structural style tokens for the shell. Color is the palette @@ -347,9 +348,19 @@ QtObject { readonly property int statusSlot: root.barToken("status-slot", 21) } + // Off with Hyprland's own animations, as `omarchy toggle animations` turns + // them off for machines that render on the CPU. Every shell animation runs + // for Style.duration(ms), which is then 0, so nothing is drawn in between. + property bool reduceMotion: false + + function duration(ms) { + return reduceMotion ? 0 : ms + } + function refresh() { hyprctlProc.running = true gapsOutProc.running = true + animationsProc.running = true } function scheduleRefresh() { @@ -448,6 +459,30 @@ QtObject { } } + property Process animationsProc: Process { + id: animationsProc + command: ["hyprctl", "-j", "getoption", "animations:enabled"] + stdout: StdioCollector { + waitForEnd: true + onStreamFinished: { + try { + root.reduceMotion = JSON.parse(text || "{}").bool === false + } catch (e) { + // hyprctl missing / Hyprland not running — leave the previous value. + } + } + } + } + + // A reload is when the animations toggle, a theme or the user's own config + // lands, and Hyprland only announces it once the new values are in effect. + property Connections hyprlandEvents: Connections { + target: Hyprland + function onRawEvent(event) { + if (event && String(event.name) === "configreloaded") root.refresh() + } + } + property Process gapsOutProc: Process { id: gapsOutProc command: ["hyprctl", "-j", "getoption", "general:gaps_out"] diff --git a/shell/Commons/Util.qml b/shell/Commons/Util.qml index 14af44fed9ec..cacc98d25517 100644 --- a/shell/Commons/Util.qml +++ b/shell/Commons/Util.qml @@ -61,7 +61,7 @@ QtObject { // Run an argv vector without a shell interpreting it: the constant `exec "$@"` // means the args only ever land in positional parameters, which bash expands // without re-tokenizing — so untrusted data ($(id), a filename) stays literal. - // The login shell (-l) keeps the PATH/session env GUI targets (tensaku, mpv, + // The login shell (-l) keeps the PATH/session env GUI targets (omasnap, mpv, // xdg-open) need. Prefer this over execDetached for anything built from input. function execArgv(argv) { Quickshell.execDetached(["bash", "-lc", 'exec "$@"', "bash"].concat(argv)) diff --git a/shell/Commons/qmldir b/shell/Commons/qmldir index 4bfd0b783812..1c9101c12847 100644 --- a/shell/Commons/qmldir +++ b/shell/Commons/qmldir @@ -1,5 +1,7 @@ module qs.Commons singleton Border 1.0 Border.qml singleton Color 1.0 Color.qml +singleton IpcRegistry 1.0 IpcRegistry.qml singleton Style 1.0 Style.qml singleton Util 1.0 Util.qml +ShellIpc 1.0 ShellIpc.qml diff --git a/shell/README.md b/shell/README.md index ca07b520ae44..5d464a0d072c 100644 --- a/shell/README.md +++ b/shell/README.md @@ -1,302 +1,9 @@ # Omarchy shell -`omarchy-shell` is a single long-running [Quickshell](https://quickshell.org/) -instance that hosts the Omarchy desktop. Hyprland autostart launches one shell -per graphical session; everything else — the bar, background switcher, panels, -and overlays — runs **inside** the shell as a plugin. +The Omarchy desktop runs in one long-lived Quickshell process. Its bar, panels, overlays, menus, and services are plugins hosted by `shell.qml`. -Hosting everything inside one shell means: - -- shared services and singletons live once, not once per process -- summoning a panel is an IPC call into a process that is already running, - not a fresh `quickshell -p ...` cold start -- third-party plugins can be loaded from disk without changing any source - code in Omarchy itself - -The runtime layout: - -``` -shell/ - shell.qml entry point (ShellRoot) - services/ - PluginRegistry.qml discovers, validates plugins, looks up enabled state in shell.json - BarWidgetRegistry.qml unified registry for bar widgets (1p + 3p) - plugins/ - bar/ first-party plugins (see plugins/README.md) - image-picker/ - menu/ - notifications/ - panels/ - audio/ - bluetooth/ - monitor/ - network/ - power/ - weather/ - agents/ - services/ - battery/ - idle/ - osd/ - polkit/ -``` - -The plugin discovery path is documented in [plugins/README.md](plugins/README.md). - -## Plugin manifest - -Every plugin ships a `manifest.json` describing what it is and how the -shell should load it. Minimal example: - -```json -{ - "schemaVersion": 1, - "id": "my.org.cool-clock", - "name": "Cool clock", - "version": "1.0.0", - "author": "You", - "description": "A clock that does cool things", - "kinds": ["bar-widget"], - "entryPoints": { "barWidget": "Widget.qml" }, - "barWidget": { - "displayName": "Cool clock", - "category": "Time", - "allowMultiple": false, - "defaultSection": "left", - "defaults": { "format": "HH:mm" }, - "schema": [ - { "key": "format", "type": "string", "label": "Format" } - ] - } -} -``` - -Supported `kinds`: - -| Kind | What it is | -|--------------|--------------------------------------------------------------| -| `bar-widget` | A component that the active bar can drop into a section | -| `panel` | A persistent or summoned floating window (e.g. OSD) | -| `overlay` | A fullscreen overlay (e.g. background switcher) | -| `menu` | A summoned menu surface | -| `service` | A headless singleton, no UI | -| `bar` | A full bar option that can replace the built-in `omarchy.bar` | - -Only one `bar` plugin is active at a time. Missing or invalid selections fall -back to the built-in `omarchy.bar`, so users always have a safe path home. -Panels, overlays, and menus are loaded when summoned. Plugins that need -to outlive a single summon can set `keepLoaded: true` (e.g. the image -picker keeps its overlay window mounted between summons). The same flag -keeps a service mounted across plugin hot-reload, so tearing down a -changed bar widget cannot destroy `omarchy.lock` while Hyprland still -holds the session lock. The kept instance is not replaced, so code -changes to a `keepLoaded` service itself only take effect on a shell -restart. First-party services are loaded at startup. - -Entry points may declare `omarchyPath`, `shell`, `manifest`, `pluginRegistry`, and `barWidgetRegistry` properties for host injection. Built-in plugins receive the trusted host objects. Third-party plugins receive capability-scoped facades: ordinary plugins can look up and control only their own service and lifecycle, built-in clones retain narrow source-specific configuration and UI compatibility, menu plugins receive an application-library facade, and plugins can read detached scalar bar state. A full-bar plugin additionally receives detached bar configuration and widget-catalog snapshots, narrow proxies for the non-authentication services used by built-in bar widgets, and lifecycle control over configured non-authentication UI plugins. Authentication capabilities are stamped from trusted first-party manifests, authentication services are retained outside the host's public service map and QML object tree, and changing a third-party registry or configuration snapshot cannot mutate host state. Facades do not isolate visual widgets from the parent hierarchy of the shared QML scene, so sensitive state must remain outside that reachable graph. - -Widgets rendered by a third-party replacement bar receive a service-less entry facade with target-scoped lifecycle and settings operations. Their live service objects are available only when the trusted built-in bar hosts them; otherwise the replacement bar could request and retain any configured widget's service. - -The full schema lives in `services/PluginRegistry.qml`. - -## Installing a third-party plugin - -A plugin is a **git repo** with a `manifest.json` at its root. Adding one -clones it straight into `~/.config/omarchy/plugins//` (named by the -manifest id); updating is a fast-forward pull of that checkout. - -```bash -omarchy plugin add https://github.com/acme/omarchy-weather.git -omarchy plugin update acme.weather # fetches, shows a diff, fast-forwards -omarchy plugin update # updates every git-managed plugin -omarchy plugin remove acme.weather -``` - -> ⚠️ **Plugins run as unsandboxed code inside `omarchy-shell`.** Adding warns you before cloning, plugins land disabled so you can review the code before enabling, and updates show a diff of the changes before touching anything. The scoped QML interfaces remove direct authentication-service and generic replacement-bar service lookups, but visual plugins still share and can traverse the ordinary host scene. Only add repos whose code you are willing to run. - -Each command is **interactive** when run bare in a terminal (gum pickers, -confirmation, a diff to review) and fully **non-interactive** when given -arguments. Pass `--yes` to skip every prompt — this is the path for scripts and -AI agents: - -```bash -omarchy plugin add https://github.com/acme/omarchy-weather.git --enable --yes -omarchy plugin update --yes -``` - -The installer never runs plugin code, install hooks, or sudo — it only clones -files, validates the manifest, and toggles enabled state over shell IPC. Since -an installed plugin is a plain git checkout, anything beyond add/update -(pinning a ref, switching branches) is ordinary git in the plugin directory. - -### Installing by hand - -You can still drop a plugin in without git: - -1. Put it in `~/.config/omarchy/plugins//` with a `manifest.json` - plus the QML referenced from its `entryPoints`. -2. `omarchy-shell shell rescanPlugins`. -3. `omarchy plugin enable `. Bar widgets start in - `barWidget.defaultSection`, or in the center when it is omitted, and can be - moved with `omarchy bar move`; a full bar replaces the one in use. - -The lower-level IPC equivalents remain available via `omarchy-shell shell rescanPlugins`, -`omarchy-shell shell enablePlugin '{}'`, and `omarchy-shell shell listPlugins`. -The `omarchy plugin` commands wrap those calls. `omarchy bar move` and -`omarchy bar set` edit the persisted widget layout in `shell.json`. - -To hack on a built-in plugin safely, clone it into user config instead of -editing the built-in source. The complete plugin directory is copied, including -every declared kind and local dependency. A built-in id such as -`omarchy.clock` becomes `.clock` (e.g. `dhh.clock`), with `My Clock` -as its display name. The username prefix keeps shared clones from colliding -with each other or with other plugin authors. - -```bash -omarchy plugin clone omarchy.clock -``` - -Cloning switches from the built-in to the new personal plugin, preserving an -existing bar widget's position and settings. Setup > Plugins > Clone provides -the interactive picker, then opens the new `.*` directory in `$EDITOR`. -Existing shortcuts and shell IPC calls made to the built-in id are routed to -the enabled clone, so cloning does not require changing its callers. Removing -an active clone switches back to its built-in source. -Saving a file anywhere under `~/.config/omarchy/plugins/` reloads plugin code -automatically; `omarchy-shell shell rescanPlugins` remains available to force a reload. - -First-party plugins under `shell/plugins/` are discovered the same way and load -by default. Disabling a non-widget records it in `disabledPlugins[]`; disabling -a widget removes it from the bar layout while leaving its component available -to add again. A full bar has no off state and is replaced by enabling another. - -## IPC contract - -The shell exposes a single `shell` IPC target plus whatever extra targets -individual plugins register (e.g. the bar's `bar` target for refresh -hooks, the image picker's `image-selector` target). `omarchy-menu` uses the -shell target to summon the first-party `omarchy.menu` plugin instead of -running a separate Quickshell instance. - -| Method | Returns | Effect | -|------------------------------------------|---------|-------------------------------------------------------| -| `ping` | `ok` | health check | -| `summon ` | `ok` / `unknown` | load + open a panel/overlay plugin | -| `hide ` | — | close a previously-summoned plugin | -| `toggle ` | — | summon if closed, hide if open | -| `call ` | string | call a method on an already-loaded plugin | -| `rescanPlugins` | — | re-walk plugin dirs and hot-reload plugin code | -| `reloadConfig` | `ok` | reload `~/.config/omarchy/shell.json` | -| `setPluginEnabled ` | `ok` / `unknown` | flip the persisted enabled bit (see note) | -| `listPlugins` | JSON | every discovered plugin, sorted by name | - -Direct invocation: - -``` -quickshell ipc -p $OMARCHY_PATH/shell call shell ping -``` - -Hyprland autostart launches the shell directly with `quickshell -p -$OMARCHY_PATH/shell`. Use `omarchy-restart-shell` to stop every running -instance of that config and launch one fresh shell process. - -A convenience wrapper, [`omarchy-shell`](../bin/omarchy-shell), forwards IPC -calls to the running shell. It does not start the shell. - -``` -omarchy-shell shell ping -omarchy-shell shell toggle omarchy.menu '{"menu":"root"}' -omarchy-shell shell listPlugins -omarchy-shell shell rescanPlugins -``` - -**Note on `setPluginEnabled`:** the `enabled` argument is a string. Only the -literal `"true"` enables the plugin; every other value (including `"True"`, -`"1"`, `"yes"`, or omitted) disables it. This keeps the IPC surface -type-stable across QML's `string`-only IPC arguments. - -## Persisted state - -There is one user config file. Everything that distinguishes your -customization from the shipped defaults lives in it. - -| Path | Owner | Purpose | -|-----------------------------------|----------------|--------------------------------------------------------| -| `~/.config/omarchy/shell.json` | the shell | full layout + per-entry settings + enabled plugin list | -| `~/.config/omarchy/plugins//` | user | drop-in third-party plugin source files | - -The `config/omarchy/shell.json` default config describes the -fresh-install state. When the user has no `shell.json`, the shell uses -the defaults verbatim. Once the user customizes anything, `shell.json` -becomes the authoritative file — we do **not** deep-merge defaults back in. - -### shell.json shape - -```json -{ - "version": 1, - "idle": { - "screensaver": 150, - "lock": 300 - }, - "bar": { - "id": "omarchy.bar", - "position": "top", - "transparent": false, - "centerAnchor": "omarchy.clock", - "layout": { - "left": [ { "id": "omarchy.menu" }, { "id": "omarchy.workspaces" } ], - "center": [ { "id": "omarchy.clock", "format": "HH:mm" } ], - "right": [ - { "id": "omarchy.audio" } - ] - } - }, - "plugins": [] -} -``` - -### Storage rules - -1. **The active bar option is `bar.id`.** Omit it or set it to `omarchy.bar` - to use the built-in bar. Set it to another plugin id whose manifest declares - `kind: "bar"` to replace the full bar. -2. **Every plugin instance is one entry.** Either in `bar.layout.
` - for bar widgets, or in `plugins[]` for panels, overlays, services, - menus, and anything else non-bar. -3. **Settings are inline on the entry.** No `config:` sub-object, no - separate per-plugin settings file, no merge layers. The fields on each - entry are the values the plugin sees. -4. **Built-in widget ids are namespaced.** Use ids such as `omarchy.clock`, - `omarchy.audio`, and `omarchy.network`. The migration rewrites older ids - like `Clock` and `AudioPanel` forward. -5. **Third-party enabled ⇔ present.** A third-party plugin is enabled iff - its id appears somewhere in shell.json. For full bar options, that means - `bar.id`; for bar widgets, plugin enable/disable adds/removes layout entries; - other plugin kinds are enabled the same way. First-party non-bar plugins - are enabled unless listed in `disabledPlugins[]`. -6. **Multiple instances** are allowed when a manifest sets - `allowMultiple: true`. Each instance is independent — e.g. two clock - widgets in different timezones are just two `{"id":"omarchy.clock", "timezone": ...}` - entries with their own values. -7. **Idle timings are top-level.** `idle.screensaver` and `idle.lock` - are seconds since user idle began, so the default lock fires at 300s - even if the 150s screensaver starts first. -8. **`version: 1` is required** at the top level. The shell will fall back - to defaults rather than load an unknown version. - -## Implementation history - -Built up in phases on this branch: - -- Phase 1 — `omarchy-shell phase 1: host the existing bar in a single shell` -- Phase 2 — `omarchy-shell phase 2: plugin registry and bar widget registry` -- Phase 3 — `omarchy-shell phase 3: fold bar-settings into the shell as a panel plugin` -- Phase 4 — `omarchy-shell phase 4: absorb background-switcher as a plugin` -- Phase 5 — `omarchy-shell phase 5: docs, cleanup, and migration crumbs` -- Phase 6 — `omarchy-shell phase 6: reviewer cleanup (path traversal, collision, races)` -- Phase 7 — `omarchy-shell phase 7: replace socket with IpcHandler, rename to image-picker` -- Phase 8a — `omarchy-shell phase 8a: unified shell.json with inline plugin settings` - -Shared services and Pipewire/UPower/Hyprland consolidation are explicitly -out of scope here and deferred to a follow-up after a review pass. +- [Shell reference](../docs/omarchy-shell.md) — plugin manifests, IPC, configuration, and shared UI contracts. +- [Plugin user guide](../manual/32-shell-plugins.md) — install, configure, and clone plugins. +- [First-party plugins](plugins/README.md) — bundled plugin IDs, kinds, and entry points. +- [Shell development guide](../agents/skills/shell-dev.md) — conventions for changing the desktop. +- [Theming reference](../docs/theming.md) — theme tokens, templates, and generated configuration. diff --git a/shell/Ui/BackgroundMedia.qml b/shell/Ui/BackgroundMedia.qml index b281ae223ac5..8640769f3f10 100644 --- a/shell/Ui/BackgroundMedia.qml +++ b/shell/Ui/BackgroundMedia.qml @@ -1,29 +1,27 @@ import QtQuick import qs.Commons +// The shell draws stills only. OWE owns video backgrounds on the desktop, and +// it feeds the lock screen through its own socket. Item { id: root property string path: "" property int version: 0 - property bool playbackEnabled: true - property bool audioEnabled: false - // Bumped when the file behind an unchanged path may have been replaced. - // Images cache-bust through version; a video is rebuilt, since FFmpeg - // would read a query as part of the filename. - property int reloads: 0 - property bool reloading: false - readonly property var current: video ? videoLoader.item : imageLoader.item + // Unversioned images cache by path. A caller whose version changes with every + // new file, as the lock's does, may cache too: the version is in the URL. + property bool cached: version === 0 + // A caller that knows the size its screen needs, in physical pixels, sets + // constrainDecode and decodeSize. The image then waits for that size rather + // than decoding at the file's native size first. + property bool constrainDecode: false + property size decodeSize: Qt.size(0, 0) + readonly property var current: imageLoader.item readonly property bool ready: current ? current.ready : false readonly property bool video: Util.isVideoPath(path) - // Cache-bust images selected in a running lock session. FFmpeg treats the - // query as part of a local filename, so videos must keep their plain URL. - // Each URL is empty for the other kind, so a switch never hands the still - // loader a video, or the player a still, in the moment before it unloads. - // Both test the path directly: going through `video` lets a URL evaluate - // against the stale flag and leak the wrong file for one pass. - readonly property url imageUrl: path && !Util.isVideoPath(path) ? Util.fileUrl(path) + (version ? "?v=" + version : "") : "" - readonly property url videoUrl: path && Util.isVideoPath(path) ? Util.fileUrl(path) : "" + // Cache-bust images selected in a running lock session, so a theme switch + // that replaces the file behind an unchanged path shows the new pixels. + readonly property url imageUrl: path && !video ? Util.fileUrl(path) + (version ? "?v=" + version : "") : "" Loader { id: imageLoader @@ -32,56 +30,17 @@ Item { sourceComponent: imageComponent } - // Loaded by URL rather than from a Component here, so QtMultimedia and its - // audio dependency closure never map into a session that only shows images. - Loader { - id: videoLoader - anchors.fill: parent - active: root.path !== "" && root.video && !root.reloading - source: "BackgroundVideo.qml" - } - - onReloadsChanged: { - if (!video) return - reloading = true - Qt.callLater(function() { root.reloading = false }) - } - - // A player on its way out keeps its source: pushing an empty one starts a - // load of nothing that its destructor then cancels, which FFmpeg logs. - Binding { - target: videoLoader.item - property: "mediaSource" - value: root.videoUrl - when: videoLoader.item !== null && Util.isVideoPath(root.path) - restoreMode: Binding.RestoreNone - } - - Binding { - target: videoLoader.item - property: "playbackEnabled" - value: root.playbackEnabled - when: videoLoader.item !== null - } - - Binding { - target: videoLoader.item - property: "audioEnabled" - value: root.audioEnabled - when: videoLoader.item !== null - } - Component { id: imageComponent Image { readonly property bool ready: status === Image.Ready - source: root.imageUrl + source: !root.constrainDecode || root.decodeSize.width > 0 ? root.imageUrl : "" fillMode: Image.PreserveAspectCrop asynchronous: true - cache: root.version === 0 - sourceSize.width: root.version > 0 ? width : 0 - sourceSize.height: root.version > 0 ? height : 0 + cache: root.cached + sourceSize.width: root.constrainDecode ? root.decodeSize.width : (root.version > 0 ? width : 0) + sourceSize.height: root.constrainDecode ? root.decodeSize.height : (root.version > 0 ? height : 0) } } } diff --git a/shell/Ui/BackgroundVideo.qml b/shell/Ui/BackgroundVideo.qml deleted file mode 100644 index 519e8bd99f02..000000000000 --- a/shell/Ui/BackgroundVideo.qml +++ /dev/null @@ -1,122 +0,0 @@ -import QtQuick -import QtMultimedia - -// Deliberately a bare MediaPlayer and VideoOutput rather than the Video -// convenience type: Video always builds an AudioOutput, and a muted sink still -// decodes the audio stream and opens an audio client on every output. -Item { - id: root - - property url mediaSource: "" - property bool playbackEnabled: true - property bool audioEnabled: false - property int mediaGeneration: 0 - property bool priming: false - property int primingGeneration: -1 - property bool frameReceived: false - readonly property bool ready: player.hasVideo - - onMediaSourceChanged: { - mediaGeneration += 1 - priming = false - primingGeneration = -1 - frameReceived = false - primePauseTimer.stop() - framePauseTimer.stop() - output.clearOutput() - } - - onPlaybackEnabledChanged: { - priming = false - frameReceived = false - primePauseTimer.stop() - framePauseTimer.stop() - if (playbackEnabled) player.play() - else player.pause() - } - - function pauseAfterPrimedFrame() { - if (!priming - || root.playbackEnabled - || primingGeneration !== root.mediaGeneration) return - - priming = false - primePauseTimer.stop() - framePauseTimer.stop() - player.pause() - } - - // A paused MediaPlayer can load a source without presenting its first frame. - // Prime it until VideoOutput receives a frame, with a timeout so a stalled - // decoder cannot keep running indefinitely on battery. - Timer { - id: primePauseTimer - interval: 1000 - repeat: false - - onTriggered: root.pauseAfterPrimedFrame() - } - - // Receiving a frame means the decoder has produced it, but the scene graph - // may not have committed it yet. Give VideoOutput a render cycle before - // pausing so the first frame is not lost on a source switch. - Timer { - id: framePauseTimer - interval: 50 - repeat: false - - onTriggered: root.pauseAfterPrimedFrame() - } - - VideoOutput { - id: output - anchors.fill: parent - fillMode: VideoOutput.PreserveAspectCrop - } - - // Sound is opted into per output: with a player per monitor, every output - // playing the track would layer copies of it. The sink is only built once - // the media reports a sound track, so a silent file never opens an audio - // client or its threads. Priming a paused player must not be heard. - Loader { - id: audioLoader - active: root.audioEnabled && player.hasAudio - sourceComponent: AudioOutput { - muted: root.priming || !root.playbackEnabled - } - } - - MediaPlayer { - id: player - source: root.mediaSource - videoOutput: output - audioOutput: audioLoader.item - loops: MediaPlayer.Infinite - autoPlay: root.playbackEnabled - onMediaStatusChanged: { - if (mediaStatus !== MediaPlayer.LoadedMedia) return - - if (!root.playbackEnabled) { - root.priming = true - root.primingGeneration = root.mediaGeneration - root.frameReceived = false - primePauseTimer.restart() - } - player.play() - } - } - - Connections { - target: output.videoSink - function onVideoFrameChanged() { - if (player.mediaStatus !== MediaPlayer.BufferedMedia) return - if (!root.priming - || root.playbackEnabled - || root.primingGeneration !== root.mediaGeneration - || root.frameReceived) return - - root.frameReceived = true - framePauseTimer.restart() - } - } -} diff --git a/shell/Ui/BarIconButton.qml b/shell/Ui/BarIconButton.qml index e2af8808a769..32214bb4141d 100644 --- a/shell/Ui/BarIconButton.qml +++ b/shell/Ui/BarIconButton.qml @@ -9,7 +9,8 @@ WidgetButton { property real slotSize: Style.bar.iconSlot property real opticalSize: Style.bar.iconCanvas property bool debugOpticalBounds: Quickshell.env("OMARCHY_DEBUG_BAR_ICONS") === "1" - readonly property real opticalCenterErrorX: glyph.visible ? glyph.paintedCenterX - opticalCanvas.width / 2 : 0 + // Measured against the slot, which the open-panel underline centers on. + readonly property real opticalCenterErrorX: glyph.visible ? opticalCanvas.x + glyph.paintedCenterX - root.width / 2 : 0 readonly property real glyphPaintedWidth: glyph.visible ? glyph.tightWidth : 0 readonly property real glyphBaselineY: glyph.visible ? glyph.baselineY : 0 readonly property int glyphFontSize: glyph.visible ? glyph.renderedFontSize : 0 @@ -22,7 +23,10 @@ WidgetButton { Item { id: opticalCanvas - anchors.centerIn: parent + // Placed exactly, not anchored: centerIn snaps an even canvas in an odd slot + // to a whole pixel, pulling every glyph off the open-panel underline. + x: (root.width - width) / 2 + y: (root.height - height) / 2 width: root.opticalSize height: root.opticalSize diff --git a/shell/Ui/Button.qml b/shell/Ui/Button.qml index 2b84577a3c55..09c5806cef92 100644 --- a/shell/Ui/Button.qml +++ b/shell/Ui/Button.qml @@ -125,7 +125,7 @@ BorderSurface { // dedicated selected border. borderSpec: _borderSpec - Behavior on color { ColorAnimation { duration: 120 } } + Behavior on color { ColorAnimation { duration: Style.duration(120) } } ToolTip { visible: root.tooltipText !== "" && mouseArea.containsMouse @@ -174,7 +174,7 @@ BorderSurface { to: 360 duration: 900 loops: Animation.Infinite - running: root.iconSpinning + running: root.iconSpinning && !Style.reduceMotion } } diff --git a/shell/Ui/CursorSurface.qml b/shell/Ui/CursorSurface.qml index 58e46d0629fa..cb715df9e207 100644 --- a/shell/Ui/CursorSurface.qml +++ b/shell/Ui/CursorSurface.qml @@ -36,6 +36,6 @@ BorderSurface { : Border.none())) Behavior on color { - ColorAnimation { duration: 60 } + ColorAnimation { duration: Style.duration(60) } } } diff --git a/shell/Ui/KeyboardPanel.qml b/shell/Ui/KeyboardPanel.qml index b2fb218f46b4..38a2979ce62c 100644 --- a/shell/Ui/KeyboardPanel.qml +++ b/shell/Ui/KeyboardPanel.qml @@ -390,7 +390,7 @@ PanelWindow { Behavior on opacity { enabled: !root.popoutSwitching && !root.popoutSwitchClosing - NumberAnimation { duration: 140; easing.type: Easing.OutCubic } + NumberAnimation { duration: Style.duration(140); easing.type: Easing.OutCubic } } // Swallow clicks on the card so they don't bubble to the dismissal @@ -411,7 +411,7 @@ PanelWindow { Behavior on opacity { enabled: root.popoutSwitching - NumberAnimation { duration: 140; easing.type: Easing.OutCubic } + NumberAnimation { duration: Style.duration(140); easing.type: Easing.OutCubic } } } } diff --git a/shell/Ui/MultiSelect.qml b/shell/Ui/MultiSelect.qml index 85705779fc72..ad2e29553ce4 100644 --- a/shell/Ui/MultiSelect.qml +++ b/shell/Ui/MultiSelect.qml @@ -461,7 +461,7 @@ Item { font.pixelSize: Style.font.body RotationAnimator on rotation { - running: root.loadingOptions + running: root.loadingOptions && !Style.reduceMotion from: 0; to: 360 duration: 800 loops: Animation.Infinite diff --git a/shell/Ui/OpticalGlyph.qml b/shell/Ui/OpticalGlyph.qml index a8881d4909c2..201c2d0197a6 100644 --- a/shell/Ui/OpticalGlyph.qml +++ b/shell/Ui/OpticalGlyph.qml @@ -28,8 +28,10 @@ Item { textFormat: Text.PlainText // Keep the shared line box and baseline intact. Correcting only the // horizontal painted bounds avoids per-glyph vertical drift. - anchors.centerIn: parent - anchors.horizontalCenterOffset: root.horizontalCorrection + // The correction is fractional, so x is set exactly: centerIn would snap it + // to a whole pixel and undo it. y still snaps, keeping the baseline crisp. + x: (root.width - width) / 2 + root.horizontalCorrection + y: Math.round((root.height - height) / 2) text: root.text color: root.color font.family: root.fontFamily diff --git a/shell/Ui/OverlayWindow.qml b/shell/Ui/OverlayWindow.qml new file mode 100644 index 000000000000..43a9c32c27a2 --- /dev/null +++ b/shell/Ui/OverlayWindow.qml @@ -0,0 +1,56 @@ +import QtQuick +import Quickshell +import Quickshell.Hyprland +import Quickshell.Wayland + +// A fullscreen overlay whose surface outlives each open. A fresh surface draws +// its first frames before the compositor sends its fractional scale, so an +// overlay mapped per open flashed blurry until the scale arrived. Closed, the +// surface parks as a 1x1, input-less, content-less layer below windows: small +// enough to cost nothing, off the overlay layer so it never blocks direct +// scanout for fullscreen apps. Opening only resizes and raises it. +PanelWindow { + id: window + + // Whether the overlay is showing. Drive this instead of visible. + property bool shown: false + property int shownLayer: WlrLayer.Overlay + property int shownKeyboardFocus: WlrKeyboardFocus.Exclusive + + // The surface no longer lands on the focused output by being mapped there, + // so it follows the focused monitor each time it is shown. Unset until the + // first show lets the compositor choose. + property var targetScreen: null + property Region emptyRegion: Region {} + + function focusedScreen() { + var monitor = Hyprland.focusedMonitor + var name = monitor ? String(monitor.name || "") : "" + for (var i = 0; i < Quickshell.screens.length; i++) { + if (Quickshell.screens[i].name === name) return Quickshell.screens[i] + } + return null + } + + onShownChanged: if (shown) targetScreen = focusedScreen() || targetScreen + + visible: true + screen: targetScreen + anchors { top: true; left: true; bottom: shown; right: shown } + implicitWidth: 1 + implicitHeight: 1 + mask: shown ? null : emptyRegion + color: "transparent" + exclusionMode: ExclusionMode.Ignore + WlrLayershell.layer: shown ? shownLayer : WlrLayer.Bottom + WlrLayershell.keyboardFocus: shown ? shownKeyboardFocus : WlrKeyboardFocus.None + + // Draw nothing until the surface has actually grown. A frame drawn while it + // is still 1x1 holds only the scrim's color, which the compositor would + // stretch across the whole screen until the fullscreen frame arrives. + Binding { + target: window.contentItem + property: "visible" + value: window.shown && window.width > 1 && window.height > 1 + } +} diff --git a/shell/Ui/Panel.qml b/shell/Ui/Panel.qml index b8866b5be231..371d2c6e1f6c 100644 --- a/shell/Ui/Panel.qml +++ b/shell/Ui/Panel.qml @@ -45,7 +45,7 @@ Item { id: panelController } - IpcHandler { + ShellIpc { enabled: root.manageIpc && root.ipcTarget !== "" target: root.ipcTarget diff --git a/shell/Ui/PanelActionButton.qml b/shell/Ui/PanelActionButton.qml index 05f7d6be06db..d4115e2bdd72 100644 --- a/shell/Ui/PanelActionButton.qml +++ b/shell/Ui/PanelActionButton.qml @@ -66,7 +66,7 @@ BorderSurface { : "transparent") borderSpec: _borderSpec - Behavior on color { ColorAnimation { duration: 60 } } + Behavior on color { ColorAnimation { duration: Style.duration(60) } } Text { textFormat: Text.PlainText diff --git a/shell/Ui/PanelKeyCatcher.qml b/shell/Ui/PanelKeyCatcher.qml index bac394e52473..b110b223592a 100644 --- a/shell/Ui/PanelKeyCatcher.qml +++ b/shell/Ui/PanelKeyCatcher.qml @@ -14,7 +14,7 @@ import QtQuick // onActivateRequested: root.activateCursor() // onCloseRequested: root.close() // onDeleteRequested: root.deleteSelected() -// onTextKey: function(t) { if (t === "r") root.refresh() } +// onTextKey: function(t, modifiers) { if (t === "r") root.refresh() } // // Column { ... panel content ... } // } @@ -41,7 +41,8 @@ Item { signal closeRequested() signal deleteRequested() signal tabRequested(int direction) - signal textKey(string text) + // The held modifiers ride along, so a panel can tell Alt+T from T. + signal textKey(string text, int modifiers) focus: true Keys.priority: Keys.BeforeItem @@ -75,11 +76,11 @@ Item { if (event.key === Qt.Key_Space) { activateRequested(); event.accepted = true; return } - if (event.text === "x" || event.text === "X") { + if (event.key === Qt.Key_Delete || event.text === "x" || event.text === "X") { deleteRequested(); event.accepted = true; return } if (event.text && event.text.length === 1) { - textKey(event.text) + textKey(event.text, event.modifiers) } } } diff --git a/shell/Ui/PanelSlider.qml b/shell/Ui/PanelSlider.qml index d7bf1303b438..64396713efcb 100644 --- a/shell/Ui/PanelSlider.qml +++ b/shell/Ui/PanelSlider.qml @@ -62,7 +62,7 @@ Item { Behavior on width { enabled: !root.dragging - NumberAnimation { duration: 140; easing.type: Easing.OutCubic } + NumberAnimation { duration: Style.duration(140); easing.type: Easing.OutCubic } } } @@ -93,11 +93,11 @@ Item { Behavior on x { enabled: !root.dragging - NumberAnimation { duration: 140; easing.type: Easing.OutCubic } + NumberAnimation { duration: Style.duration(140); easing.type: Easing.OutCubic } } Behavior on scale { - NumberAnimation { duration: 110; easing.type: Easing.OutCubic } + NumberAnimation { duration: Style.duration(110); easing.type: Easing.OutCubic } } } diff --git a/shell/Ui/PopupCard.qml b/shell/Ui/PopupCard.qml index 058b068f9a28..3bc8193a105e 100644 --- a/shell/Ui/PopupCard.qml +++ b/shell/Ui/PopupCard.qml @@ -157,7 +157,7 @@ PopupWindow { opacity: root.open ? 1.0 : 0 Behavior on opacity { - NumberAnimation { duration: 140; easing.type: Easing.OutCubic } + NumberAnimation { duration: Style.duration(140); easing.type: Easing.OutCubic } } Item { diff --git a/shell/Ui/SpeedTestOverlay.qml b/shell/Ui/SpeedTestOverlay.qml index a8f84c7be4a2..f1beef92b23d 100644 --- a/shell/Ui/SpeedTestOverlay.qml +++ b/shell/Ui/SpeedTestOverlay.qml @@ -61,7 +61,7 @@ PanelWindow { onRightValueChanged: expandScale(rightValue) Behavior on fullScale { - NumberAnimation { duration: 400; easing.type: Easing.OutCubic } + NumberAnimation { duration: Style.duration(400); easing.type: Easing.OutCubic } } // The scrim below is a fixed near-black regardless of theme, so text and @@ -178,7 +178,7 @@ PanelWindow { onClicked: root.runAgainRequested() Behavior on opacity { - NumberAnimation { duration: 240; easing.type: Easing.OutCubic } + NumberAnimation { duration: Style.duration(240); easing.type: Easing.OutCubic } } } @@ -236,13 +236,13 @@ PanelWindow { opacity: engaged ? 1 : 0.5 Behavior on opacity { - NumberAnimation { duration: 240; easing.type: Easing.OutCubic } + NumberAnimation { duration: Style.duration(240); easing.type: Easing.OutCubic } } // Live readings land once a second; glide between them rather than snap. Behavior on shown { enabled: !ignition.running - NumberAnimation { duration: 600; easing.type: Easing.OutCubic } + NumberAnimation { duration: Style.duration(600); easing.type: Easing.OutCubic } } onValueChanged: { @@ -257,8 +257,8 @@ PanelWindow { // the live figures take over. SequentialAnimation { id: ignition - NumberAnimation { target: dial; property: "shown"; to: dial.fullScale; duration: 550; easing.type: Easing.InOutCubic } - NumberAnimation { target: dial; property: "shown"; to: 0; duration: 650; easing.type: Easing.OutCubic } + NumberAnimation { target: dial; property: "shown"; to: dial.fullScale; duration: Style.duration(550); easing.type: Easing.InOutCubic } + NumberAnimation { target: dial; property: "shown"; to: 0; duration: Style.duration(650); easing.type: Easing.OutCubic } onFinished: dial.shown = dial.value } diff --git a/shell/Ui/Toggle.qml b/shell/Ui/Toggle.qml index b861fec78296..0f2c9b7c4947 100644 --- a/shell/Ui/Toggle.qml +++ b/shell/Ui/Toggle.qml @@ -52,7 +52,7 @@ BorderSurface { color: Style.controlFill(activeFocus, _hot, foreground, accent) borderSpec: _borderSpec - Behavior on color { ColorAnimation { duration: 100 } } + Behavior on color { ColorAnimation { duration: Style.duration(100) } } Row { id: content diff --git a/shell/Ui/ToggleSwitch.qml b/shell/Ui/ToggleSwitch.qml index 22e6461abe35..f1aa80fa61fd 100644 --- a/shell/Ui/ToggleSwitch.qml +++ b/shell/Ui/ToggleSwitch.qml @@ -84,7 +84,7 @@ Item { : Style.normalFillFor(root.foreground, root.accent) borderSpec: Border.controlSpec(root.checked ? "selected" : "normal", root.foreground, root.accent) - Behavior on color { ColorAnimation { duration: 120 } } + Behavior on color { ColorAnimation { duration: Style.duration(120) } } Rectangle { width: root.knobSize @@ -94,8 +94,8 @@ Item { anchors.verticalCenter: parent.verticalCenter color: root.checked ? Style.selectedStateColor(root.foreground, root.accent) : Qt.darker(root.foreground, 1.25) - Behavior on x { NumberAnimation { duration: 120; easing.type: Easing.OutCubic } } - Behavior on color { ColorAnimation { duration: 120 } } + Behavior on x { NumberAnimation { duration: Style.duration(120); easing.type: Easing.OutCubic } } + Behavior on color { ColorAnimation { duration: Style.duration(120) } } } } diff --git a/shell/Ui/WidgetButton.qml b/shell/Ui/WidgetButton.qml index 87d18050cf29..20c27acde709 100644 --- a/shell/Ui/WidgetButton.qml +++ b/shell/Ui/WidgetButton.qml @@ -69,7 +69,7 @@ Item { implicitHeight: fixedHeight > 0 ? fixedHeight : (vertical ? Math.max(12, label.implicitHeight + scaledVerticalPadding * 2) : barSize) Behavior on opacity { - NumberAnimation { duration: 140; easing.type: Easing.OutCubic } + NumberAnimation { duration: Style.duration(140); easing.type: Easing.OutCubic } } Text { @@ -88,7 +88,7 @@ Item { Behavior on color { enabled: !root.bar || root.bar.foregroundAnimationEnabled - ColorAnimation { duration: 160 } + ColorAnimation { duration: Style.duration(160) } } } diff --git a/shell/Ui/qmldir b/shell/Ui/qmldir index 092caf6c6091..9061ad6ab71f 100644 --- a/shell/Ui/qmldir +++ b/shell/Ui/qmldir @@ -4,7 +4,6 @@ BarIndicator 1.0 BarIndicator.qml BarIconButton 1.0 BarIconButton.qml BarWidget 1.0 BarWidget.qml BackgroundMedia 1.0 BackgroundMedia.qml -BackgroundVideo 1.0 BackgroundVideo.qml BorderOverlay 1.0 BorderOverlay.qml BorderSurface 1.0 BorderSurface.qml Button 1.0 Button.qml @@ -16,6 +15,7 @@ KeyboardPanel 1.0 KeyboardPanel.qml MultiSelect 1.0 MultiSelect.qml NumberField 1.0 NumberField.qml OpticalGlyph 1.0 OpticalGlyph.qml +OverlayWindow 1.0 OverlayWindow.qml Panel 1.0 Panel.qml PanelActionButton 1.0 PanelActionButton.qml PanelController 1.0 PanelController.qml diff --git a/shell/plugins/README.md b/shell/plugins/README.md index 66cb74e14fdb..7ef3daa36db8 100644 --- a/shell/plugins/README.md +++ b/shell/plugins/README.md @@ -23,6 +23,7 @@ User-installed plugins live alongside these conceptually but on disk under | Audio | `omarchy.audio` | `bar-widget` | `panels/audio/Panel.qml` | | Bluetooth | `omarchy.bluetooth` | `bar-widget` | `panels/bluetooth/Panel.qml` | | Clock | `omarchy.clock` | `bar-widget` | `panels/clock/BarWidget.qml` | +| Elsewhen | `omarchy.elsewhen` | `bar-widget` | `panels/elsewhen/Panel.qml` | | Monitor | `omarchy.monitor` | `bar-widget` | `panels/monitor/Panel.qml` | | Network | `omarchy.network` | `bar-widget` | `panels/network/Panel.qml` | | Power | `omarchy.power` | `bar-widget` | `panels/power/Panel.qml` | diff --git a/shell/plugins/agents/Panel.qml b/shell/plugins/agents/Panel.qml index f4ecdd9a09b3..910e9bb46de8 100644 --- a/shell/plugins/agents/Panel.qml +++ b/shell/plugins/agents/Panel.qml @@ -324,7 +324,7 @@ Panel { onTriggered: root.nowMs = Date.now() } - IpcHandler { + ShellIpc { target: root.ipcTarget function open(): void { root.open() } function close(): void { root.close() } @@ -788,7 +788,7 @@ Panel { color: meter.alarming ? root.urgent : root.foreground Behavior on width { - NumberAnimation { duration: 160; easing.type: Easing.OutCubic } + NumberAnimation { duration: Style.duration(160); easing.type: Easing.OutCubic } } } @@ -837,7 +837,7 @@ Panel { color: dayRow.today ? root.foreground : root.alpha(root.foreground, 0.55) Behavior on width { - NumberAnimation { duration: 160; easing.type: Easing.OutCubic } + NumberAnimation { duration: Style.duration(160); easing.type: Easing.OutCubic } } } } @@ -894,7 +894,7 @@ Panel { color: root.alpha(root.foreground, 0.14) Behavior on width { - NumberAnimation { duration: 160; easing.type: Easing.OutCubic } + NumberAnimation { duration: Style.duration(160); easing.type: Easing.OutCubic } } } diff --git a/shell/plugins/background/Background.qml b/shell/plugins/background/Background.qml index dea93a4cf658..7dee71dc7d26 100644 --- a/shell/plugins/background/Background.qml +++ b/shell/plugins/background/Background.qml @@ -1,5 +1,4 @@ import Quickshell -import Quickshell.Hyprland import Quickshell.Io import Quickshell.Wayland import QtQuick @@ -11,15 +10,31 @@ import qs.Ui Item { id: root + property var shell: null readonly property string home: Quickshell.env("HOME") readonly property string stateHome: home + "/.local/state" readonly property string currentBackgroundLink: stateHome + "/omarchy/current/background" property string currentBackground: "" property string displayedBackground: "" - property int displayedReloads: 0 property string incomingBackground: "" property string oldBackground: "" + // A theme switch names its next background before it has staged the rest of + // the theme, so the incoming frame can decode while that work runs. A large + // WebP takes ~130ms to decode at any sourceSize, which the reveal would + // otherwise wait out after the transition arrives. + property string preparedBackground: "" + // The prepare and transition calls travel as separate IPC clients, so a + // prepare can land after its transition. The path it names then must not be + // decoded again. + property string lastTransitionPath: "" + // Native pixel size per wallpaper path, read from the file header before + // the image loads. Decoding at screen size only saves memory for wallpapers + // at least as large as the screen: with PreserveAspectCrop Qt scales the + // decode up to cover sourceSize, so a smaller wallpaper would cost the + // screen's worth of pixels instead of its own. + property var nativeSizes: ({}) + property var sizeQueue: [] property bool finishingTransition: false property int backgroundVersion: 0 property int revealStartedVersion: -1 @@ -28,23 +43,6 @@ Item { property string pendingShellRaw: "" property real revealProgress: 1 - // Injected by the first-party service loader; used to reach the lock and idle - // services so playback can stop whenever nothing can see the wallpaper. - property var shell: null - - // Stop a video wallpaper's decoding whenever it is covered. Qt's FFmpeg - // engine drives its own clock, so an unseen player keeps decoding until it - // is told not to — a locked laptop would otherwise decode until it died. - readonly property var lockService: shell && shell.services ? shell.firstPartyServiceFor("omarchy.lock") : null - readonly property var idleService: shell && shell.services ? shell.firstPartyServiceFor("omarchy.idle") : null - readonly property var batteryService: shell && shell.services ? shell.firstPartyServiceFor("omarchy.battery") : null - readonly property bool lockActive: lockService ? lockService.locked : false - readonly property bool screensaverActive: idleService ? idleService.screensaverWindowCount > 0 : false - readonly property bool powerSaverActive: batteryService ? batteryService.powerSaverOnBattery : false - // A lock or a screensaver covers every output, so it is decided once here. - // Fullscreen is decided per output below, because it only covers its own. - readonly property bool sessionObscured: lockActive || screensaverActive - function isVideo(path) { return Util.isVideoPath(path) } @@ -66,6 +64,13 @@ Item { finalPath = String(finalPath || path).trim() fromPath = String(fromPath || "").trim() if (!path || (!force && finalPath === currentBackground)) return + if (path !== preparedBackground) preparedBackground = "" + preparedBackgroundTimer.stop() + lastTransitionPath = path + // The incoming frame gates the reveal, so its size is read first. + requestNativeSize(path) + requestNativeSize(fromPath || displayedBackground) + requestNativeSize(finalPath) currentBackground = finalPath backgroundVersion += 1 revealStartedVersion = -1 @@ -78,9 +83,7 @@ Item { if (instant || !displayedBackground || isVideo(path) || isVideo(displayedBackground)) { oldBackground = "" incomingBackground = "" - // A theme switch can replace the file behind an unchanged path, which - // an unchanged property would never pick up. - if (displayedBackground === finalPath) displayedReloads += 1 + preparedBackground = "" displayedBackground = finalPath revealProgress = 1 return @@ -128,12 +131,50 @@ Item { revealAnimation.restart() } + function prepareBackground(path) { + path = String(path || "").trim() + // Only a still that is not already on screen is worth decoding ahead. + if (!path || isVideo(path) || path === lastTransitionPath || path === displayedBackground) return + requestNativeSize(path) + preparedBackground = path + preparedBackgroundTimer.restart() + } + + function requestNativeSize(path) { + if (!path || isVideo(path) || nativeSizes[path] !== undefined || sizeQueue.indexOf(path) !== -1) return + sizeQueue = sizeQueue.concat([path]) + probeNextSize() + } + + function probeNextSize() { + if (sizeProbe.running || sizeQueue.length === 0) return + sizeProbe.path = sizeQueue[0] + sizeProbe.command = ["magick", "identify", "-ping", "-format", "%w %h", sizeProbe.path] + sizeProbe.running = true + } + + // Each theme switch names fresh snapshot paths, so keep only the sizes of + // the wallpapers still in play. + function pruneNativeSizes() { + var kept = {} + var paths = [displayedBackground, incomingBackground, oldBackground, preparedBackground] + for (var i = 0; i < paths.length; i++) { + if (paths[i] && nativeSizes[paths[i]] !== undefined) kept[paths[i]] = nativeSizes[paths[i]] + } + nativeSizes = kept + } + function openSelector() { if (!bgSwitchProc.running) bgSwitchProc.running = true } function openThemeSwitcher() { - if (!themeSwitchProc.running) themeSwitchProc.running = true + var payload = JSON.stringify({ source: "themes" }) + + // A cloned background may not summon the picker in-process, so it takes + // the IPC route instead. + if (!root.shell || !root.shell.summon("omarchy.image-picker", payload)) + Util.execArgv(["omarchy-shell", "shell", "summon", "omarchy.image-picker", payload]) } Process { @@ -143,9 +184,20 @@ Item { } Process { - id: themeSwitchProc - command: ["bash", "-c", "theme=$(omarchy-theme-switcher); [[ -n $theme ]] && omarchy-theme-set \"$theme\" >/dev/null 2>&1 &"] - onExited: root.refreshBackground() + id: sizeProbe + property string path: "" + stdout: StdioCollector { id: sizeProbeOut } + onExited: function(exitCode) { + var parts = String(sizeProbeOut.text || "").trim().split(/\s+/) + var width = exitCode === 0 ? parseInt(parts[0], 10) : 0 + var height = exitCode === 0 ? parseInt(parts[1], 10) : 0 + var known = Object.assign({}, root.nativeSizes) + // An unreadable header records 0x0, which decodes at screen size. + known[path] = { width: width > 0 ? width : 0, height: height > 0 ? height : 0 } + root.nativeSizes = known + root.sizeQueue = root.sizeQueue.filter(function(queued) { return queued !== sizeProbe.path }) + root.probeNextSize() + } } Process { @@ -156,7 +208,7 @@ Item { } } - IpcHandler { + ShellIpc { target: "background" function refresh(): void { @@ -178,6 +230,19 @@ Item { function themeTransition(fromPath: string, path: string, finalPath: string, colorsB64: string, shellB64: string): void { root.transitionBackgroundWithTheme(fromPath, path, finalPath, colorsB64, shellB64) } + + function prepare(path: string): void { + root.prepareBackground(path) + } + } + + // A prepared frame that no transition claims, say from a theme switch that + // failed after naming it, must not hold its decoded texture indefinitely. + Timer { + id: preparedBackgroundTimer + interval: 5000 + repeat: false + onTriggered: root.preparedBackground = "" } Timer { @@ -193,7 +258,7 @@ Item { property: "revealProgress" from: 0 to: 1 - duration: 420 + duration: Style.duration(420) easing.type: Easing.InOutCubic onFinished: { if (root.incomingBackground) { @@ -225,25 +290,32 @@ Item { // Keep render updates enabled. The background layer has been observed to // lose its committed buffer while parked with updatesEnabled=false, // leaving a black desktop until omarchy-shell is restarted. A still - // wallpaper costs nothing to keep enabled, and a video one is throttled - // by pausing playback rather than by parking the layer. + // wallpaper costs nothing to keep enabled. OWE manages video layers. updatesEnabled: true - // Pausing every wallpaper for one fullscreen window would freeze the one - // still on show next to it, which costs a viewer more than it saves. The - // workspace on show here knows whether a fullscreen window covers it, - // wherever focus happens to be. - readonly property var hyprlandMonitor: Hyprland.monitorFor(modelData) - readonly property var visibleWorkspace: hyprlandMonitor ? hyprlandMonitor.activeWorkspace : null - readonly property bool fullscreenHere: visibleWorkspace ? visibleWorkspace.hasFullscreen : false - - // A sound track plays from one output only, or every monitor would - // layer its own copy of it. - readonly property bool firstScreen: Quickshell.screens.length > 0 - && String(Quickshell.screens[0].name || "") === String(modelData.name || "") - property bool maskReady: false + // Decode the wallpaper at the size this screen can show, not the size + // it was shipped at. With PreserveAspectCrop Qt takes sourceSize as the + // area to cover, so this is the smallest decode that still fills the + // screen. Stock wallpapers go up to 10456x3455 (144 MB as RGBA); a + // 1080p laptop paid all of that for the 8 MB it can display, and paid + // it up to three times over during a transition. The images wait for + // the window's size and the wallpaper's native size so nothing is ever + // decoded at native size first, and a wallpaper smaller than the screen + // is decoded at its own size rather than scaled up to cover the screen. + readonly property bool sized: width > 0 && height > 0 + readonly property int decodeWidth: sized ? Math.ceil(width * screen.devicePixelRatio) : 0 + readonly property int decodeHeight: sized ? Math.ceil(height * screen.devicePixelRatio) : 0 + + function decodeSize(path) { + if (!sized || !path) return Qt.size(0, 0) + var native = root.nativeSizes[path] + if (native === undefined) return Qt.size(0, 0) + if (native.width > 0 && (native.width < decodeWidth || native.height < decodeHeight)) return Qt.size(native.width, native.height) + return Qt.size(decodeWidth, decodeHeight) + } + function maybeStartReveal() { if (!root.incomingBackground || root.revealProgress !== 0 || maskReady) return if (incomingFrame.status !== Image.Ready) return @@ -259,18 +331,21 @@ Item { WlrLayershell.keyboardFocus: WlrKeyboardFocus.None exclusionMode: ExclusionMode.Ignore + // OWE owns video backgrounds. This layer draws stills, and stays empty + // behind a video so OWE's own layer shows through. BackgroundMedia { id: base anchors.fill: parent path: root.displayedBackground - reloads: root.displayedReloads - playbackEnabled: !root.sessionObscured && !root.powerSaverActive && !panel.fullscreenHere - audioEnabled: panel.firstScreen + constrainDecode: true + decodeSize: panel.decodeSize(root.displayedBackground) onReadyChanged: { if (ready && root.finishingTransition) { root.incomingBackground = "" root.oldBackground = "" + root.preparedBackground = "" root.finishingTransition = false + root.pruneNativeSizes() } } } @@ -278,7 +353,10 @@ Item { Image { id: oldFrame anchors.fill: parent - source: root.imageUrl(root.oldBackground) + readonly property size decode: panel.decodeSize(root.oldBackground) + source: decode.width > 0 ? root.imageUrl(root.oldBackground) : "" + sourceSize.width: decode.width + sourceSize.height: decode.height fillMode: Image.PreserveAspectCrop asynchronous: true cache: false @@ -304,7 +382,13 @@ Item { Image { id: incomingFrame anchors.fill: parent - source: root.imageUrl(root.incomingBackground) + // The same URL and size as a prepared frame keeps its decoded + // image, so a transition to it can reveal at once. + readonly property string framePath: root.incomingBackground || root.preparedBackground + readonly property size decode: panel.decodeSize(framePath) + source: decode.width > 0 ? root.imageUrl(framePath) : "" + sourceSize.width: decode.width + sourceSize.height: decode.height fillMode: Image.PreserveAspectCrop asynchronous: true cache: false diff --git a/shell/plugins/bar/Bar.qml b/shell/plugins/bar/Bar.qml index be9fece40f43..437daef07790 100644 --- a/shell/plugins/bar/Bar.qml +++ b/shell/plugins/bar/Bar.qml @@ -80,9 +80,9 @@ Item { property color background: Color.bar.background property color urgent: Color.bar.active - Behavior on barForeground { enabled: root.foregroundAnimationEnabled; ColorAnimation { duration: 420; easing.type: Easing.InOutCubic } } - Behavior on background { ColorAnimation { duration: 420; easing.type: Easing.InOutCubic } } - Behavior on urgent { ColorAnimation { duration: 420; easing.type: Easing.InOutCubic } } + Behavior on barForeground { enabled: root.foregroundAnimationEnabled; ColorAnimation { duration: Style.duration(420); easing.type: Easing.InOutCubic } } + Behavior on background { ColorAnimation { duration: Style.duration(420); easing.type: Easing.InOutCubic } } + Behavior on urgent { ColorAnimation { duration: Style.duration(420); easing.type: Easing.InOutCubic } } property var tooltipTarget: null property var pendingTooltipTarget: null property string tooltipText: "" @@ -1182,7 +1182,7 @@ Item { // changes land in quick succession, stranding the bar off screen until the // shell restarts. `omarchy-toggle-bar` nudges this after flipping the flag // so the probe re-reads it even when the watch has gone quiet. - IpcHandler { + ShellIpc { target: "omarchy.bar" // Start rather than restart: a probe already in flight was launched by the @@ -1509,7 +1509,7 @@ Item { opacity: root.barMoveCandidate === modelData ? (root.transparent ? 0.45 : 0.7) : 0 Behavior on opacity { - NumberAnimation { duration: 140; easing.type: Easing.OutCubic } + NumberAnimation { duration: Style.duration(140); easing.type: Easing.OutCubic } } } } @@ -1895,7 +1895,7 @@ Item { z: 50 Behavior on opacity { - NumberAnimation { duration: 120; easing.type: Easing.OutCubic } + NumberAnimation { duration: Style.duration(120); easing.type: Easing.OutCubic } } } diff --git a/shell/plugins/bar/README.md b/shell/plugins/bar/README.md index 5741c5f3114d..d0934f114536 100644 --- a/shell/plugins/bar/README.md +++ b/shell/plugins/bar/README.md @@ -14,7 +14,7 @@ the shell for its whole session. ## Customizing -The bar config lives under the `bar:` key of [`~/.config/omarchy/shell.json`](../../README.md#shelljson-shape). Out of the box the shell uses [`config/omarchy/shell.json`](../../../config/omarchy/shell.json). Once you customize anything via the bar gestures, `omarchy bar ...`, or by editing shell.json directly, your file is canonical — there is no deep-merge. +The bar config lives under the `bar:` key of [`~/.config/omarchy/shell.json`](../../../docs/omarchy-shell.md#shelljson). Out of the box the shell uses [`config/omarchy/shell.json`](../../../config/omarchy/shell.json). Once you customize anything via the bar gestures, `omarchy bar ...`, or by editing shell.json directly, your file is canonical — there is no deep-merge. The bar is configured directly on the bar itself: drag empty bar space (or click-and-hold) to move the bar to another screen edge, double-left-click empty center-bar space to toggle transparency, and drag widgets to reorder them. The `omarchy bar position`, `omarchy bar transparent`, `omarchy bar move`, and `omarchy bar set` commands do the same from scripts. Enable or disable widgets with `omarchy plugin enable` and `omarchy plugin disable` (widget ids come from `omarchy plugin list`). @@ -172,9 +172,4 @@ richer popup plugins live in feature directories such as `../panels/audio/`, `manifest.json`. Bar layout ids are namespaced, e.g. `omarchy.audio`, `omarchy.network`, and `omarchy.clock`. -Third-party widgets ship as separate plugins under -`~/.config/omarchy/plugins//` with their own `manifest.json` -declaring `kinds: ["bar-widget"]` and a `barWidget` entry point. See -[../../README.md](../../README.md) for the manifest schema. Rescan, enable, -and place third-party plugins with `omarchy-shell shell rescanPlugins`, -`omarchy plugin enable`, and `omarchy bar move`. +Third-party widgets ship as separate plugins under `~/.config/omarchy/plugins//` with their own `manifest.json` declaring `kinds: ["bar-widget"]` and a `barWidget` entry point. See the [shell reference](../../../docs/omarchy-shell.md#plugin-manifest) for the manifest schema. Rescan, enable, and place third-party plugins with `omarchy-shell shell rescanPlugins`, `omarchy plugin enable`, and `omarchy bar move`. diff --git a/shell/plugins/bar/widgets/ActiveWindow.qml b/shell/plugins/bar/widgets/ActiveWindow.qml index ff7e83d8534e..251d48abca71 100644 --- a/shell/plugins/bar/widgets/ActiveWindow.qml +++ b/shell/plugins/bar/widgets/ActiveWindow.qml @@ -18,7 +18,7 @@ BarWidget { implicitHeight: barSize Behavior on implicitWidth { - NumberAnimation { duration: 180; easing.type: Easing.OutCubic } + NumberAnimation { duration: Style.duration(180); easing.type: Easing.OutCubic } } Item { diff --git a/shell/plugins/bar/widgets/Indicators.qml b/shell/plugins/bar/widgets/Indicators.qml index cb35c5a23ce3..00417eed8591 100644 --- a/shell/plugins/bar/widgets/Indicators.qml +++ b/shell/plugins/bar/widgets/Indicators.qml @@ -165,7 +165,7 @@ BarWidget { ? activeVerticalBlock.implicitHeight + inactiveVerticalArea.implicitHeight : Math.max(activeHorizontalBlock.implicitHeight, inactiveHorizontalArea.implicitHeight) - IpcHandler { + ShellIpc { target: "omarchy.indicators" function refresh(): void { diff --git a/shell/plugins/bar/widgets/SystemUpdate.qml b/shell/plugins/bar/widgets/SystemUpdate.qml index a4f9020f1feb..2baf6b0d07cf 100644 --- a/shell/plugins/bar/widgets/SystemUpdate.qml +++ b/shell/plugins/bar/widgets/SystemUpdate.qml @@ -24,7 +24,7 @@ BarWidget { implicitWidth: button.implicitWidth implicitHeight: button.implicitHeight - IpcHandler { + ShellIpc { target: "omarchy.system-update" function refresh(): void { diff --git a/shell/plugins/bar/widgets/Tray.qml b/shell/plugins/bar/widgets/Tray.qml index 650358c130f2..dfe11ad783c0 100644 --- a/shell/plugins/bar/widgets/Tray.qml +++ b/shell/plugins/bar/widgets/Tray.qml @@ -216,7 +216,7 @@ BarWidget { implicitHeight: root.vertical ? trayContent.implicitHeight : root.barSize Behavior on revealProgress { - NumberAnimation { duration: root.animationDuration; easing.type: Easing.OutCubic } + NumberAnimation { duration: Style.duration(root.animationDuration); easing.type: Easing.OutCubic } } Loader { diff --git a/shell/plugins/clipboard/Clipboard.qml b/shell/plugins/clipboard/Clipboard.qml index da969e65dc2b..a8feb23abb77 100644 --- a/shell/plugins/clipboard/Clipboard.qml +++ b/shell/plugins/clipboard/Clipboard.qml @@ -311,15 +311,10 @@ Item { } } - PanelWindow { + OverlayWindow { id: panel - visible: root.opened - anchors { top: true; bottom: true; left: true; right: true } - color: "transparent" + shown: root.opened WlrLayershell.namespace: "omarchy-clipboard" - WlrLayershell.layer: WlrLayer.Overlay - WlrLayershell.keyboardFocus: WlrKeyboardFocus.Exclusive - exclusionMode: ExclusionMode.Ignore Rectangle { anchors.fill: parent diff --git a/shell/plugins/emojis/Emojis.qml b/shell/plugins/emojis/Emojis.qml index 376c382ead86..b1bcdec0d5de 100644 --- a/shell/plugins/emojis/Emojis.qml +++ b/shell/plugins/emojis/Emojis.qml @@ -157,15 +157,10 @@ Item { path: root.omarchyPath + "/shell/plugins/emojis/emojis.json" onLoaded: root.loadEmojis(text()) } - PanelWindow { + OverlayWindow { id: panel - visible: root.opened - anchors { top: true; bottom: true; left: true; right: true } - color: "transparent" + shown: root.opened WlrLayershell.namespace: "omarchy-emojis" - WlrLayershell.layer: WlrLayer.Overlay - WlrLayershell.keyboardFocus: WlrKeyboardFocus.Exclusive - exclusionMode: ExclusionMode.Ignore Rectangle { anchors.fill: parent diff --git a/shell/plugins/image-picker/ImagePicker.qml b/shell/plugins/image-picker/ImagePicker.qml index 5c002402a627..b6939fad9c32 100644 --- a/shell/plugins/image-picker/ImagePicker.qml +++ b/shell/plugins/image-picker/ImagePicker.qml @@ -5,6 +5,7 @@ import QtQuick import QtQuick.Effects import QtQuick.Shapes import qs.Commons +import qs.Ui import "ImagePickerModel.js" as ImagePickerModel Item { @@ -30,6 +31,11 @@ Item { property string doneFile: "" property string filterText: "" property var doneFilesToRelease: [] + // Themes open from rows the shell already holds, so the picker shows without + // waiting on omarchy-theme-switcher; each open refreshes them behind it. + property string themeRows: "" + property bool themeMode: false + property bool themeOpenPending: false // Bound to the central [image-picker] section in shell.toml via Color.qml. // `dimColor` tints unselected slices and text outlines on top of the scrim; // it intentionally tracks the foundational background, not a surface role. @@ -151,6 +157,14 @@ Item { function applySelected() { var path = currentPath() + + if (themeMode) { + themeMode = false + root.opened = false + if (path) Util.execArgv(["omarchy-theme-set", nameForPath(path)]) + return + } + if (!path || !selectionFile) { cancel() return @@ -168,6 +182,8 @@ Item { } function cancel() { + themeOpenPending = false + if (requestActive) finishDoneFile(doneFile) @@ -179,6 +195,7 @@ Item { function closeSelector(nextDoneFile) { requestSerial += 1 + themeOpenPending = false if (requestActive) finishDoneFile(doneFile) @@ -212,6 +229,8 @@ Item { finishDoneFile(doneFile) requestSerial += 1 + themeMode = false + themeOpenPending = false imageDirs = nextImageDirs imageRows = nextImageRows @@ -255,6 +274,68 @@ Item { property var imageArray: [] + + function currentThemePreview() { + var name = String(themeNameFile.text() || "").trim() + var images = ImagePickerModel.loadRows(themeRows) + for (var i = 0; i < images.length; i++) { + if (nameForPath(images[i].filePath) === name) return images[i].filePath + } + return "" + } + + function openThemes() { + if (themeRows) { + openThemeRows() + } else { + // First open before the startup refresh has landed. + themeOpenPending = true + } + refreshThemeRows() + } + + function openThemeRows() { + openSelector("", themeRows, currentThemePreview(), "", "", true, true) + themeMode = true + } + + function refreshThemeRows() { + if (!themeRowsProc.running) themeRowsProc.running = true + } + + function updateThemeRows(rows) { + var changed = rows !== themeRows + themeRows = rows + + if (themeOpenPending) { + themeOpenPending = false + if (rows) openThemeRows() + } else if (changed && rows && themeMode && opened) { + // A theme was added or removed since the rows were last read. Keep the + // user's place in the carousel rather than jumping back to the current. + selectedImage = currentPath() || currentThemePreview() + imageRows = rows + loadRows(rows, false) + } + } + + FileView { + id: themeNameFile + path: root.stateHome + "/omarchy/current/theme.name" + watchChanges: true + onFileChanged: reload() + } + + Process { + id: themeRowsProc + command: [root.omarchyPath + "/bin/omarchy-theme-switcher", "--print-rows"] + stdout: StdioCollector { + onStreamFinished: root.updateThemeRows(String(text || "").trim()) + } + } + + Component.onCompleted: refreshThemeRows() + function startImageScan(serial, dirs) { if (loadImagesProc.running) { loadImagesProc.queuedSerial = serial @@ -309,6 +390,10 @@ Item { if (payload) { try { args = JSON.parse(payload) || {} } catch (e) { args = {} } } + if (args.source === "themes") { + openThemes() + return + } var dirs = String(args.imageDirs || imageDirs) var rows = String(args.imageRows || "") var sel = String(args.selectedImage || selectedImage) @@ -359,16 +444,11 @@ Item { onExited: root.releaseNextDoneFile() } - PanelWindow { + OverlayWindow { id: panel - - visible: root.opened - anchors { top: true; bottom: true; left: true; right: true } - color: "transparent" + shown: root.opened + shownKeyboardFocus: root.imagesLoaded ? WlrKeyboardFocus.Exclusive : WlrKeyboardFocus.None WlrLayershell.namespace: "omarchy-image-selector" - WlrLayershell.layer: WlrLayer.Overlay - WlrLayershell.keyboardFocus: root.opened && root.imagesLoaded ? WlrKeyboardFocus.Exclusive : WlrKeyboardFocus.None - exclusionMode: ExclusionMode.Ignore Rectangle { anchors.fill: parent diff --git a/shell/plugins/lock/LockFeedSurface.qml b/shell/plugins/lock/LockFeedSurface.qml new file mode 100644 index 000000000000..ecd1f7d47fce --- /dev/null +++ b/shell/plugins/lock/LockFeedSurface.qml @@ -0,0 +1,7 @@ +import QtQuick +import Owe.LockFeed + +// Loaded through a Loader from LockView, so a system without the module shows +// no lock video instead of losing the whole lock screen. +LockFeed { +} diff --git a/shell/plugins/lock/LockView.qml b/shell/plugins/lock/LockView.qml index e7a430ac67fa..999a0a04c981 100644 --- a/shell/plugins/lock/LockView.qml +++ b/shell/plugins/lock/LockView.qml @@ -7,6 +7,7 @@ Item { id: root property string backgroundPath: "" + property string videoPosterPath: "" property int backgroundVersion: 0 property bool fingerprintConfigured: false property bool authenticatingPassword: false @@ -43,6 +44,9 @@ Item { ? Border.surfaceSpec("lock", "border-error", Color.lock.borderError, root.outlineThickness, "border-alpha") : Border.surfaceSpec("lock", "border-active", Color.lock.borderActive, root.outlineThickness, "border-alpha") + readonly property bool video: Util.isVideoPath(root.backgroundPath) + readonly property bool feedActive: root.video && root.loadBackground && !root.displaysBlank && !root.powerSaverActive + signal submitPassword(string password) signal passwordTextEdited(string password) signal clearFailureRequested() @@ -88,16 +92,22 @@ Item { BackgroundMedia { id: wallpaper + objectName: "lockWallpaper" anchors.fill: parent - path: root.loadBackground ? root.backgroundPath : "" + path: root.loadBackground ? (root.video ? root.videoPosterPath : root.backgroundPath) : "" version: root.backgroundVersion - playbackEnabled: root.loadBackground && !root.displaysBlank && !root.powerSaverActive + // Decode only once sized, at the lock's own size: an unsized first + // request decoded the file at its native resolution, then again once + // sized. That size is what the lock service keeps decoded ahead of the + // lock, so the first frame has the wallpaper. + cached: true + constrainDecode: true + decodeSize: Qt.size(width, height) } MultiEffect { anchors.fill: wallpaper - source: wallpaper.video ? null : wallpaper - visible: !wallpaper.video + source: wallpaper autoPaddingEnabled: false blurEnabled: root.loadBackground && wallpaper.ready blur: 1.0 @@ -106,11 +116,22 @@ Item { contrast: -0.08 } - // Qt's video output cannot be sampled by MultiEffect on every renderer. + // The cached poster stays behind the feed when policy pauses playback, + // the module is unavailable, or a new connection has not received a frame. + Loader { + id: feedLoader + objectName: "lockFeedLoader" + anchors.fill: parent + active: root.feedActive + source: "LockFeedSurface.qml" + visible: status === Loader.Ready + } + + // The feed item cannot be sampled by MultiEffect on every renderer. // Keep video wallpapers visible and darken them slightly for legibility. Rectangle { - anchors.fill: wallpaper - visible: wallpaper.video + anchors.fill: feedLoader + visible: root.video color: "#22000000" } diff --git a/shell/plugins/lock/Service.qml b/shell/plugins/lock/Service.qml index 94d43b68ebd0..845e1d1e7aaf 100644 --- a/shell/plugins/lock/Service.qml +++ b/shell/plugins/lock/Service.qml @@ -28,7 +28,11 @@ Item { property string failureMessage: "" property int failedAttempts: 0 property string backgroundPath: "" + property string videoPosterPath: "" property int backgroundVersion: 0 + // The wallpaper file's mtime and size. The lock caches its wallpaper by + // version, so a file overwritten in place must bump the version too. + property string backgroundSignature: "" property string lastEvent: "init" property string lastEventAt: "" property bool displaysBlank: false @@ -113,6 +117,16 @@ Item { if (!readlinkProc.running) readlinkProc.running = true } + function refreshPoster() { + if (!root.videoBackground) { + root.videoPosterPath = "" + return + } + if (posterProc.running) return + posterProc.sourcePath = root.backgroundPath + posterProc.running = true + } + function refreshFingerprintStatus() { if (!fingerprintCheckProc.running) fingerprintCheckProc.running = true } @@ -307,6 +321,7 @@ Item { id: lockView anchors.fill: parent backgroundPath: root.backgroundPath + videoPosterPath: root.videoPosterPath backgroundVersion: root.backgroundVersion fingerprintConfigured: root.fingerprintConfigured authenticatingPassword: root.authenticatingPassword @@ -339,6 +354,7 @@ Item { LockView { anchors.fill: parent backgroundPath: root.backgroundPath + videoPosterPath: root.videoPosterPath backgroundVersion: root.backgroundVersion fingerprintConfigured: root.fingerprintConfigured authenticatingPassword: false @@ -394,6 +410,32 @@ Item { } } + // The lock only starts decoding its wallpaper once locked, and a machine + // suspending right after locking froze that decode partway: waking showed + // the password field on a bare background, then the wallpaper popped in. + // Keep each screen's lock wallpaper decoded in the image cache ahead of + // time, as the lock view requests it (same URL, the screen's logical size, + // PreserveAspectCrop), so the lock draws it on its first frame. + readonly property string lockWallpaperPath: videoBackground ? videoPosterPath : backgroundPath + readonly property string lockWallpaperUrl: lockWallpaperPath && !Util.isVideoPath(lockWallpaperPath) + ? Util.fileUrl(lockWallpaperPath) + (backgroundVersion ? "?v=" + backgroundVersion : "") + : "" + + Variants { + model: Quickshell.screens + + Image { + required property var modelData + visible: false + source: root.lockWallpaperUrl + sourceSize.width: modelData.width + sourceSize.height: modelData.height + fillMode: Image.PreserveAspectCrop + asynchronous: true + cache: true + } + } + Timer { id: fingerprintRetryTimer interval: 250 @@ -403,15 +445,37 @@ Item { Process { id: readlinkProc - command: ["readlink", "-f", root.currentBackgroundLink] + command: ["bash", "-c", "path=$(readlink -f -- \"$1\") && printf '%s\\n%s\\n' \"$path\" \"$(stat -Lc %Y:%s -- \"$path\" 2>/dev/null)\"", "_", root.currentBackgroundLink] stdout: StdioCollector { waitForEnd: true onStreamFinished: { - var next = String(text || "").trim() + var lines = String(text || "").split("\n") + var next = String(lines[0] || "").trim() + var signature = String(lines[1] || "").trim() if (next !== root.backgroundPath) { + root.videoPosterPath = "" root.backgroundPath = next + root.backgroundSignature = signature + root.backgroundVersion += 1 + } else if (signature !== root.backgroundSignature) { + root.backgroundSignature = signature root.backgroundVersion += 1 } + root.refreshPoster() + } + } + } + + Process { + id: posterProc + property string sourcePath: "" + command: ["bash", Quickshell.env("OMARCHY_PATH") + "/shell/plugins/lock/poster.sh", sourcePath] + stdout: StdioCollector { id: posterOutput; waitForEnd: true } + onExited: function(exitCode) { + if (sourcePath !== root.backgroundPath) { + root.refreshPoster() + } else { + root.videoPosterPath = exitCode === 0 ? String(posterOutput.text || "").trim() : "" } } } @@ -577,7 +641,7 @@ Item { checkStrandedLock() } - IpcHandler { + ShellIpc { target: "lock" function lock(): string { diff --git a/shell/plugins/lock/poster.sh b/shell/plugins/lock/poster.sh new file mode 100755 index 000000000000..836d01f06f09 --- /dev/null +++ b/shell/plugins/lock/poster.sh @@ -0,0 +1,24 @@ +#!/bin/bash + +# One cached frame shared by all lock outputs, including when OWE is paused. +set -euo pipefail + +source_path=$1 +cache_dir="${XDG_CACHE_HOME:-$HOME/.cache}/omarchy/lock-poster" +signature=$(stat -Lc '%s:%y:%z' "$source_path") +key=$(printf '%s\n%s' "$source_path" "$signature" | sha256sum | cut -d ' ' -f 1) +poster="$cache_dir/poster-$key.jpg" +mkdir -p "$cache_dir" +exec {lock_fd}>"$cache_dir/.lock" +flock -w 10 "$lock_fd" + +if [[ ! -s $poster ]]; then + temporary=$(mktemp "$cache_dir/.poster-XXXXXX.jpg") + trap 'rm -f "$temporary"' EXIT + timeout -k 1 5 ffmpegthumbnailer -i "$source_path" -o "$temporary" -s 1920 -q 8 {lock_fd}>&- + [[ -s $temporary ]] + mv -f "$temporary" "$poster" + find "$cache_dir" -maxdepth 1 -type f -name 'poster-*.jpg' ! -name "poster-$key.jpg" -delete +fi + +printf '%s\n' "$poster" diff --git a/shell/plugins/menu/Menu.qml b/shell/plugins/menu/Menu.qml index aa879c188fd6..1625375e64b3 100644 --- a/shell/plugins/menu/Menu.qml +++ b/shell/plugins/menu/Menu.qml @@ -138,6 +138,9 @@ Item { var command = String(action || "") if (!command) return + var summon = MenuModel.summonAction(command) + if (summon && root.shell && root.shell.summon(summon.id, summon.payload)) return + Util.execDetached(command) } @@ -1062,15 +1065,10 @@ Item { if (root.guardsPending) Qt.callLater(function() { root.evaluateGuards() }) } } - PanelWindow { + OverlayWindow { id: panel - visible: root.opened && root.rowsLoaded - anchors { top: true; bottom: true; left: true; right: true } - color: "transparent" + shown: root.opened && root.rowsLoaded WlrLayershell.namespace: "omarchy-menu" - WlrLayershell.layer: WlrLayer.Overlay - WlrLayershell.keyboardFocus: WlrKeyboardFocus.Exclusive - exclusionMode: ExclusionMode.Ignore // The card opens centered exactly as always. The first search keystroke // or submenu move freezes the top line where it currently sits — from @@ -1083,12 +1081,13 @@ Item { readonly property int centeredTop: Math.max(Style.gapsOut, Math.round((height - root.cardHeight) / 2)) readonly property int effectiveCardTop: cardTop >= 0 ? cardTop : centeredTop function freezeCardTop() { - if (visible && cardTop < 0) { + if (shown && cardTop < 0) { cardTop = effectiveCardTop maxRowsHeight = root.visibleRowsHeight } } - onVisibleChanged: if (!visible) { cardTop = -1; maxRowsHeight = -1 } + // The surface stays mapped between opens, so closing is shown going false. + onShownChanged: if (!shown) { cardTop = -1; maxRowsHeight = -1 } Rectangle { anchors.fill: parent diff --git a/shell/plugins/menu/MenuModel.js b/shell/plugins/menu/MenuModel.js index 28c995ea2bc6..53c49768e1ff 100644 --- a/shell/plugins/menu/MenuModel.js +++ b/shell/plugins/menu/MenuModel.js @@ -490,8 +490,19 @@ function guardScript(items) { return guards ? guardPrelude(guards) + guards : "" } +// An action that only asks this shell to summon one of its own plugins can be +// run in-process, skipping the bash and qs ipc spawns. Anything more than the +// bare call, such as a second command or a shell-expanded payload, is left to +// bash. +function summonAction(action) { + var match = /^omarchy-shell shell summon ([A-Za-z0-9._-]+)(?: '([^']*)')?$/.exec(String(action || "")) + if (!match) return null + return { id: match[1], payload: match[2] || "{}" } +} + if (typeof module !== "undefined") { module.exports = { + summonAction: summonAction, guardReaders: GUARD_READERS, guardScript: guardScript, stripJsonc: stripJsonc, diff --git a/shell/plugins/notifications/NotificationLogic.js b/shell/plugins/notifications/NotificationLogic.js index b5a6f3ea9910..b152dc06634c 100644 --- a/shell/plugins/notifications/NotificationLogic.js +++ b/shell/plugins/notifications/NotificationLogic.js @@ -223,6 +223,23 @@ function popupRowChanged(row, updated) { return false } +// The same message from the same sender under a new id. A web app open in +// several tabs (HEY, Gmail, Calendar) fires one notification per tab for a +// single reminder, all within the same moment — what the user means by that +// is one toast, not a stack of identical ones. The image and click target +// count too: every screen recording toast shares its text but previews and +// opens a different file. +var DUPLICATE_ROLES = ["app", "summary", "body", "image", "execArgv"] + +function isDuplicatePopup(row, snapshot) { + if (!row || !snapshot || row.originalId === snapshot.originalId) return false + for (var i = 0; i < DUPLICATE_ROLES.length; i++) { + var role = DUPLICATE_ROLES[i] + if ((row[role] || "") !== (snapshot[role] || "")) return false + } + return true +} + // A client updating a notification through replaces_id keeps the identity of // the popup it took over: the file name is the timestamp and id the popup was // first persisted under, and the restore, replace and archive paths all key @@ -462,6 +479,7 @@ if (typeof module !== "undefined") { snapshotOf: snapshotOf, popupRoles: popupRoles, popupRowChanged: popupRowChanged, + isDuplicatePopup: isDuplicatePopup, replacementSnapshot: replacementSnapshot, historyEntry: historyEntry, parseSettings: parseSettings, diff --git a/shell/plugins/notifications/Service.qml b/shell/plugins/notifications/Service.qml index 0122310ee7d6..cba13cbedb74 100644 --- a/shell/plugins/notifications/Service.qml +++ b/shell/plugins/notifications/Service.qml @@ -189,6 +189,7 @@ Item { // Repeater is mid-incubation while we mutate its model. Qt.callLater(function() { removePopupsByOriginalId(snapshot.originalId, NotificationLogic.popupFileName(snapshot)) + removeDuplicatePopups(service.currentContent(notification, snapshot)) popupModel.insert(0, snapshot) // An update that arrived while the insert was deferred found no row to // write to, and a property that already changed will not change again. @@ -310,6 +311,40 @@ Item { } } + // What the notification says now: a replaces_id update may have landed + // while its insert was deferred, and the snapshot still holds the original. + function currentContent(notification, snapshot) { + try { + return NotificationLogic.replacementSnapshot(notification, snapshot.originalId, snapshot.timestamp) + } catch (e) { + // Torn down by the server meanwhile — the snapshot is all there is. + return snapshot + } + } + + // A notification repeating a toast already on screen takes its place, the + // same way a replaces_id update would: the newest copy stays, its timer + // starts fresh, and history keeps a single entry. The superseded copy is + // dismissed at the server so its sender stops holding it open. + // Only toasts with a live notification behind them qualify: a restored or + // replayed row shares its images with an entry already in history, and + // deleting its file here would leave that entry pointing at nothing. + function removeDuplicatePopups(snapshot) { + for (var i = popupModel.count - 1; i >= 0; i--) { + var row = popupModel.get(i) + if (!NotificationLogic.isDuplicatePopup(row, snapshot) || isRestoredRow(row)) continue + var ref = liveRefs[row.originalId] + if (!ref) continue + deletePopupFileFor(row) + popupModel.remove(i) + try { + if (ref.tracked) ref.dismiss() + } catch (e) { + // Object already torn down by the server — nothing to dismiss. + } + } + } + function dismissPopup(index) { removePopup(index, "dismiss") } @@ -854,7 +889,16 @@ Item { // ---------------------------------------------------- IPC - IpcHandler { + // Keybindings reach these handlers as Hyprland global shortcuts, run here + // exactly as the IPC call would run them, with no client to spawn. + function runShortcut(method) { + if (typeof ipcHandler[method] !== "function") return false + ipcHandler[method]() + return true + } + + ShellIpc { + id: ipcHandler target: "notifications" function dndState(): string { diff --git a/shell/plugins/notifications/components/NotificationCard.qml b/shell/plugins/notifications/components/NotificationCard.qml index 64e3870b7c22..d7df8d83655f 100644 --- a/shell/plugins/notifications/components/NotificationCard.qml +++ b/shell/plugins/notifications/components/NotificationCard.qml @@ -207,7 +207,7 @@ BorderSurface { visible: opacity > 0 opacity: root.hovered ? 1 : 0 - Behavior on opacity { NumberAnimation { duration: 100 } } + Behavior on opacity { NumberAnimation { duration: Style.duration(100) } } Text { anchors.centerIn: parent diff --git a/shell/plugins/osd/Osd.qml b/shell/plugins/osd/Osd.qml index 581bfa3c113f..69ddc25bbcd1 100644 --- a/shell/plugins/osd/Osd.qml +++ b/shell/plugins/osd/Osd.qml @@ -112,7 +112,7 @@ Item { text: OsdModel.widestIcon } - IpcHandler { + ShellIpc { target: "osd" function show(payloadJson: string): string { root.open(payloadJson) @@ -123,15 +123,11 @@ Item { function ping(): string { return "ok" } } - PanelWindow { + OverlayWindow { id: panel - visible: root.opened - anchors { top: true; bottom: true; left: true; right: true } - color: "transparent" + shown: root.opened + shownKeyboardFocus: WlrKeyboardFocus.None WlrLayershell.namespace: "omarchy-osd" - WlrLayershell.layer: WlrLayer.Overlay - WlrLayershell.keyboardFocus: WlrKeyboardFocus.None - exclusionMode: ExclusionMode.Ignore // Visual-only surface: keep the layer-shell input region empty so the OSD // never blocks clicks to the desktop below it. mask: Region {} @@ -182,7 +178,7 @@ Item { Behavior on width { enabled: root.opened - NumberAnimation { duration: 140; easing.type: Easing.OutCubic } + NumberAnimation { duration: Style.duration(140); easing.type: Easing.OutCubic } } } } diff --git a/shell/plugins/panels/audio/Panel.qml b/shell/plugins/panels/audio/Panel.qml index 26d0c58d083c..96047e0f61d1 100644 --- a/shell/plugins/panels/audio/Panel.qml +++ b/shell/plugins/panels/audio/Panel.qml @@ -944,7 +944,7 @@ Panel { height: parent.height width: parent.width * Math.max(0, Math.min(1, inputPeakMonitor.peak)) color: root.bar.foreground - Behavior on width { NumberAnimation { duration: 70 } } + Behavior on width { NumberAnimation { duration: Style.duration(70) } } } } } diff --git a/shell/plugins/panels/bluetooth/Panel.qml b/shell/plugins/panels/bluetooth/Panel.qml index b0078f846841..11b0ce0cf8ee 100644 --- a/shell/plugins/panels/bluetooth/Panel.qml +++ b/shell/plugins/panels/bluetooth/Panel.qml @@ -603,14 +603,14 @@ Panel { id: phraseSwap PropertyAnimation { target: heroStatus; property: "opacity" - to: 0.0; duration: 180; easing.type: Easing.OutQuad + to: 0.0; duration: Style.duration(180); easing.type: Easing.OutQuad } ScriptAction { script: root.phraseIndex = (root.phraseIndex + 1) % root.activePhrases.length } PropertyAnimation { target: heroStatus; property: "opacity" - to: 1.0; duration: 260; easing.type: Easing.InQuad + to: 1.0; duration: Style.duration(260); easing.type: Easing.InQuad } } @@ -637,7 +637,7 @@ Panel { Quickshell.execDetached(["omarchy-bluetooth-power", adapter.enabled ? "off" : "on"]) } - IpcHandler { + ShellIpc { target: "omarchy.bluetooth" function open() { root.open() } diff --git a/shell/plugins/panels/clock/BarWidget.qml b/shell/plugins/panels/clock/BarWidget.qml index 61cf0bf5c589..3235a1cc1852 100644 --- a/shell/plugins/panels/clock/BarWidget.qml +++ b/shell/plugins/panels/clock/BarWidget.qml @@ -130,7 +130,7 @@ BarWidget { } } - IpcHandler { + ShellIpc { target: "omarchy.clock" function refresh(): void { root.broadcast("refresh") } diff --git a/shell/plugins/panels/clock/Panel.qml b/shell/plugins/panels/clock/Panel.qml index ec3990e2789c..ec55afd36542 100644 --- a/shell/plugins/panels/clock/Panel.qml +++ b/shell/plugins/panels/clock/Panel.qml @@ -457,7 +457,7 @@ Panel { radius: parent.radius color: Style.selectedStateColor(root.contentForeground, Color.accent) - Behavior on width { NumberAnimation { duration: 160; easing.type: Easing.OutCubic } } + Behavior on width { NumberAnimation { duration: Style.duration(160); easing.type: Easing.OutCubic } } } } } @@ -515,7 +515,7 @@ Panel { radius: parent.radius color: Style.selectedStateColor(root.contentForeground, Color.accent) - Behavior on width { NumberAnimation { duration: 160; easing.type: Easing.OutCubic } } + Behavior on width { NumberAnimation { duration: Style.duration(160); easing.type: Easing.OutCubic } } } } diff --git a/shell/plugins/panels/dropbox/Panel.qml b/shell/plugins/panels/dropbox/Panel.qml index 515b43ced027..1a415846333d 100644 --- a/shell/plugins/panels/dropbox/Panel.qml +++ b/shell/plugins/panels/dropbox/Panel.qml @@ -155,7 +155,7 @@ Panel { function onFilesChanged() { root.ensureCursor() } } - IpcHandler { + ShellIpc { target: root.ipcTarget function open(): void { root.open() } function close(): void { root.close() } @@ -369,14 +369,14 @@ Panel { id: phraseSwap PropertyAnimation { target: hero; property: "metaOpacity" - to: 0.0; duration: 180; easing.type: Easing.OutQuad + to: 0.0; duration: Style.duration(180); easing.type: Easing.OutQuad } ScriptAction { script: root.phraseIndex = (root.phraseIndex + 1) % root.activePhrases.length } PropertyAnimation { target: hero; property: "metaOpacity" - to: 1.0; duration: 260; easing.type: Easing.InQuad + to: 1.0; duration: Style.duration(260); easing.type: Easing.InQuad } } diff --git a/shell/plugins/panels/elsewhen/Arc.js b/shell/plugins/panels/elsewhen/Arc.js new file mode 100644 index 000000000000..922e5cf0a3f8 --- /dev/null +++ b/shell/plugins/panels/elsewhen/Arc.js @@ -0,0 +1,52 @@ +// A line of text laid along a shallow circular arc. `widths` are character +// advances; `rise` is how far the ends sit from the middle, in pixels; `smile` +// bends the ends up. Returns { width, height, chars: [{ x, y, rotation }] } +// with each box's top-left and its turn in degrees about its center. +function layout(widths, rise, smile) { + var chars = [] + var total = 0 + var i + for (i = 0; i < widths.length; i++) total += widths[i] + + if (total <= 0 || rise <= 0) { + var x = 0 + for (i = 0; i < widths.length; i++) { + chars.push({ x: x, y: 0, rotation: 0 }) + x += widths[i] + } + return { width: total, height: 0, chars: chars } + } + + // Keeps the trig in range for absurd rises. + var sag = Math.min(rise, total / 4) + + // Shallow-arc sagitta: R = w^2 / 8s. + var radius = (total * total) / (8 * sag) + var halfAngle = total / (2 * radius) + var maxDrop = radius * (1 - Math.cos(halfAngle)) + var chordWidth = 2 * radius * Math.sin(halfAngle) + + var travelled = 0 + var left = 0, right = chordWidth + for (i = 0; i < widths.length; i++) { + var w = widths[i] + var a = (travelled + w / 2 - total / 2) / radius + var drop = radius * (1 - Math.cos(a)) + var x = chordWidth / 2 + radius * Math.sin(a) - w / 2 + chars.push({ + x: x, + y: smile ? maxDrop - drop : drop, + rotation: (smile ? -a : a) * 180 / Math.PI + }) + left = Math.min(left, x) + right = Math.max(right, x + w) + travelled += w + } + + // End boxes hang past the chord; shift so x starts at zero and width covers them. + for (i = 0; i < chars.length; i++) chars[i].x -= left + + return { width: right - left, height: maxDrop, chars: chars } +} + +if (typeof module !== "undefined") module.exports = { layout: layout } diff --git a/shell/plugins/panels/elsewhen/ArcText.qml b/shell/plugins/panels/elsewhen/ArcText.qml new file mode 100644 index 000000000000..b4ae6ea1667e --- /dev/null +++ b/shell/plugins/panels/elsewhen/ArcText.qml @@ -0,0 +1,70 @@ +import QtQuick +import qs.Commons +import "Arc.js" as Arc + +// One line of text arched over what sits below it, each character turned to +// follow the curve. A Text per character keeps rendering identical to the +// neighbouring Text items, which a Canvas would not. No eliding. +Item { + id: root + + property string text: "" + // How far the ends drop below the middle. + property real rise: 6 + property string fontFamily: Style.font.family + property int pixelSize: Style.font.caption + property color color: Color.foreground + + FontMetrics { + id: metrics + font.family: root.fontFamily + font.pixelSize: root.pixelSize + } + + readonly property var glyphs: text.split("") + + readonly property var placed: { + // advanceWidth does not register the font as a dependency. + var _ = metrics.font.family + metrics.font.pixelSize + var widths = [] + for (var i = 0; i < glyphs.length; i++) widths.push(metrics.advanceWidth(glyphs[i])) + return Arc.layout(widths, rise, false) + } + + // Room for the end characters' corners once they are turned. + readonly property real slack: Math.round(metrics.height / 2) + + implicitWidth: Math.ceil(placed.width) + 2 * slack + implicitHeight: Math.ceil(placed.height + metrics.height) + + readonly property real originX: (width - placed.width) / 2 + + Repeater { + model: root.glyphs.length + + Text { + required property int index + // The count changes a beat before the arrays behind it do. + readonly property string glyph: root.glyphs[index] || "" + readonly property var spot: root.placed.chars[index] || { x: 0, y: 0, rotation: 0 } + + // Exactly one advance wide, so the glyph's middle is where the arc put it. + width: metrics.advanceWidth(glyph) + height: metrics.height + horizontalAlignment: Text.AlignHCenter + verticalAlignment: Text.AlignVCenter + + x: root.originX + spot.x + y: spot.y + rotation: spot.rotation + transformOrigin: Item.Center + + textFormat: Text.PlainText + text: glyph + color: root.color + font.family: root.fontFamily + font.pixelSize: root.pixelSize + renderType: Text.QtRendering // native rendering ignores the rotation + } + } +} diff --git a/shell/plugins/panels/elsewhen/CityMatches.qml b/shell/plugins/panels/elsewhen/CityMatches.qml new file mode 100644 index 000000000000..bb80f7897ade --- /dev/null +++ b/shell/plugins/panels/elsewhen/CityMatches.qml @@ -0,0 +1,86 @@ +import QtQuick +import qs.Commons +import qs.Ui + +// The matches for a CitySearch; hosts that overlay results place this themselves. +Column { + id: list + + required property var citySearch + + spacing: Style.space(2) + + Repeater { + model: list.citySearch.matches + + CursorSurface { + id: match + required property var modelData + required property int index + + width: parent.width + implicitHeight: Style.spacing.popupRowHeight + foreground: list.citySearch.foreground + hasCursor: list.citySearch.selectedIndex === index + + Text { + anchors.left: parent.left + anchors.leftMargin: Style.spacing.xl + anchors.right: matchZone.left + anchors.rightMargin: Style.spacing.lg + anchors.verticalCenter: parent.verticalCenter + textFormat: Text.PlainText + text: match.modelData.label + color: list.citySearch.foreground + font.family: list.citySearch.fontFamily + font.pixelSize: list.citySearch.fontSize + elide: Text.ElideRight + } + + // Two cities in one zone differ by name, two zones with one name by offset. + Row { + id: matchZone + anchors.right: parent.right + anchors.rightMargin: Style.spacing.xl + anchors.verticalCenter: parent.verticalCenter + spacing: Style.spacing.md + + Caption { + text: match.modelData.value + color: list.citySearch.fainter + } + + Caption { + text: list.citySearch.offsetLabel(match.modelData.value) + visible: text !== "" + } + } + + // Only movement moves the selection, so a resting pointer cannot + // steal it from the arrow keys as the list rebuilds. + MouseArea { + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onPositionChanged: list.citySearch.selectedIndex = match.index + onClicked: list.citySearch.pick(match.modelData) + } + } + } + + Caption { + visible: list.citySearch.matches.length === 0 + width: parent.width + horizontalAlignment: Text.AlignHCenter + topPadding: Style.spacing.md + text: list.citySearch.loading ? list.citySearch.loadingText : "No matches" + color: list.citySearch.fainter + } + + component Caption: Text { + textFormat: Text.PlainText + color: list.citySearch.dim + font.family: list.citySearch.fontFamily + font.pixelSize: Style.font.caption + } +} diff --git a/shell/plugins/panels/elsewhen/CityRow.qml b/shell/plugins/panels/elsewhen/CityRow.qml new file mode 100644 index 000000000000..1eaeddfdf9cc --- /dev/null +++ b/shell/plugins/panels/elsewhen/CityRow.qml @@ -0,0 +1,382 @@ +import QtQuick +import QtQuick.Layouts +import qs.Commons +import qs.Ui +import "Model.js" as Model +import "Greetings.js" as Greet + +// One city: name, weather, date (or a local greeting on hover) and the time, +// over its daylight strip. Drag the body to reorder, click it to turn the +// globe there. Every toggle on the row flips the setting for the whole list. +Rectangle { + id: row + + required property var modelData + required property int index + // The owning Panel: the row reads its clock, facts and drag state. + property var panel + + readonly property color foreground: panel.foreground + readonly property color dim: panel.dim + readonly property color fainter: panel.fainter + readonly property string fontFamily: panel.fontFamily + + readonly property var rowData: panel.clockRows[index] + || ({ ready: false, label: modelData.label, id: modelData.id }) + readonly property bool ready: rowData.ready + readonly property var greeting: Greet.greeting(rowData.id, ready ? rowData.hour : 0) + readonly property bool removable: panel.clockRows.length > 1 + readonly property bool dragged: panel.dragIndex === index + + // Lightest at midday, darkest at night, so the list dims into the small hours. + readonly property real dayFill: 0.10 + readonly property real phaseFill: { + var p = ready ? rowData.phase : "day" + if (p === "day") return dayFill + if (p === "night") return 0.035 + return 0.07 + } + readonly property real hoverLift: 0.05 + + readonly property int pad: Style.space(15) + readonly property int stripGap: Style.space(9) + + width: parent.width + // The top pad is measured to the cap height, not the line box, so the row + // looks as tall above the name as below the strip. + implicitHeight: (pad - panel.capGap) + rowLabels.implicitHeight + stripGap + strip.trackHeight + pad + radius: Style.cornerRadius + // Opaque: knocked-aside rows pass over one another and over the globe. + // Hover lifts a row from its own time of day. The picked city takes the + // brightest lifted fill whatever its time of day, so a night row picked by the + // arrow keys never reads darker than the daytime rows around it. + readonly property bool picked: panel.focusIndex === index && !panel.addSelected + readonly property bool lit: rowHover.hovered || picked + color: Model.mix(Color.popups.background, foreground, + picked ? dayFill + hoverLift : rowHover.hovered ? phaseFill + hoverLift : phaseFill) + + // Transforms leave the Column's layout alone: the knock that clears the + // globe's way, then the drag offset. + transform: [ + Translate { + x: Model.knockX(row.index, row.panel.zoom, Style.space(95)) + y: Model.knockY(row.index, row.panel.zoom, row.panel.knockFall) + }, + Rotation { + origin.x: row.width / 2 + origin.y: row.height / 2 + angle: Model.knockTilt(row.index, row.panel.zoom) + }, + Scale { + origin.x: row.width / 2 + origin.y: row.height / 2 + xScale: Model.knockShrink(row.index, row.panel.zoom) + yScale: Model.knockShrink(row.index, row.panel.zoom) + }, + Translate { + y: Model.rowShift(row.index, row.panel.dragIndex, row.panel.dragTarget, + row.panel.dragOffset, row.panel.rowPitch) + // The dragged row follows the pointer one-to-one; the others ease aside. + Behavior on y { + enabled: !row.dragged + NumberAnimation { duration: Style.duration(130); easing.type: Easing.OutCubic } + } + } + ] + z: dragged ? 2 : 0 + opacity: dragged ? 0.9 : 1 + Behavior on opacity { NumberAnimation { duration: Style.duration(120) } } + + HoverHandler { id: rowHover } + + // The row body is the reorder grab; later siblings keep their own taps. + MouseArea { + id: grab + anchors.left: parent.left + anchors.right: parent.right + anchors.top: parent.top + anchors.bottom: strip.top + preventStealing: true + cursorShape: row.dragged ? Qt.ClosedHandCursor : Qt.OpenHandCursor + + property real pressY: 0 + property bool armed: false + property int chipAtPress: Model.NO_CHIP + + // Measured in the Column, which does not move; the row's own frame slides + // with the drag and would feed the offset back into itself. + function pointerY(mouse) { return grab.mapToItem(row.parent, 0, mouse.y).y } + + function finish() { + armed = false + strip.dismissUnlessChanged(chipAtPress) + } + + onPressed: function(mouse) { + pressY = pointerY(mouse) + armed = false + chipAtPress = strip.shownChip + } + + onPositionChanged: function(mouse) { + var dy = pointerY(mouse) - pressY + // A few pixels of slack, so a click is never a reorder. + if (!armed) { + if (Math.abs(dy) < Style.space(4)) return + armed = true + row.panel.beginRowDrag(row.index, row.height + row.parent.spacing) + } + row.panel.moveRowDrag(dy) + } + + onReleased: { + if (armed) row.panel.releaseRowDrag() + else row.panel.focusOn(row.index) + finish() + } + onCanceled: { + row.panel.cancelRowDrag() + finish() + } + } + + Column { + id: rowLabels + anchors.left: parent.left + anchors.leftMargin: Style.spacing.rowPaddingX + anchors.right: timeBlock.left + anchors.rightMargin: Style.spacing.xl + anchors.top: parent.top + anchors.topMargin: row.pad - row.panel.capGap + spacing: Style.space(2) + + // A layout so the name is what gives way when the line is tight. + RowLayout { + width: parent.width + spacing: Style.space(7) + + // Caps the name at its unelided width; the Text's own implicitWidth + // shrinks as it elides, which would make the cap circular. + TextMetrics { + id: nameMetrics + font.family: row.fontFamily + font.pixelSize: Style.font.subtitle + font.weight: Font.DemiBold + text: row.rowData.label + } + + Text { + Layout.fillWidth: true + Layout.maximumWidth: Math.ceil(nameMetrics.advanceWidth) + 2 + Layout.minimumWidth: 0 + Layout.alignment: Qt.AlignBaseline + textFormat: Text.PlainText + text: row.rowData.label + color: row.foreground + font.family: row.fontFamily + font.pixelSize: Style.font.subtitle + font.weight: Font.DemiBold + elide: Text.ElideRight + } + + // Takes the slack, so the weather sits against the time column in every row. + Item { + Layout.fillWidth: true + } + + Caption { + Layout.alignment: Qt.AlignBaseline + text: Model.tempLabel(row.panel.facts[Model.factsKey(row.rowData)], row.panel.units) + visible: text !== "" + color: tempHover.hovered ? row.foreground : row.dim + + HoverHandler { + id: tempHover + cursorShape: Qt.PointingHandCursor + } + TapHandler { onTapped: { row.panel.toggleUnits(); strip.dismissChips() } } + } + + Caption { + Layout.alignment: Qt.AlignBaseline + text: row.panel.weatherGlyph(row.rowData) + visible: text !== "" + font.pixelSize: Style.font.bodySmall + } + } + + // The date, and the greeting in its place while hovered. Stacked in one + // slot so the row never changes size under the pointer. + Item { + width: parent.width + implicitHeight: dateLine.implicitHeight + + // No greeting before the probe lands: a wrong one is worse than none. + readonly property bool greeting: row.ready && rowHover.hovered + + Row { + id: dateLine + spacing: Style.spacing.sm + opacity: parent.greeting ? 0 : 1 + visible: opacity > 0 + Behavior on opacity { NumberAnimation { duration: Style.duration(110) } } + + Caption { + text: row.ready ? row.rowData.date : "\u2026" + color: row.ready && row.rowData.dayLabel !== "" ? row.dim : row.fainter + } + + Caption { + text: "\u00b7" + visible: row.ready && row.rowData.dayLabel !== "" + color: row.fainter + } + + Caption { + text: row.ready ? row.rowData.dayLabel : "" + visible: text !== "" + } + } + + Row { + spacing: Style.space(5) + opacity: parent.greeting ? 1 : 0 + visible: opacity > 0 + Behavior on opacity { NumberAnimation { duration: Style.duration(110) } } + + // Non-Latin scripts fall back per character through fontconfig. + Caption { + text: row.greeting.text + color: row.foreground + } + + // A pronunciation, not a translation; absent for Latin scripts. + Caption { + text: row.greeting.roman + visible: text !== "" + color: row.fainter + } + } + } + } + + DaylightStrip { + id: strip + anchors.left: parent.left + anchors.right: parent.right + anchors.leftMargin: Style.spacing.rowPaddingX + anchors.rightMargin: Style.spacing.rowPaddingX + anchors.verticalCenter: parent.bottom + anchors.verticalCenterOffset: -(row.pad + trackHeight / 2) + + ready: row.ready + offsetMinutes: row.ready ? row.rowData.offsetMinutes : 0 + progress: row.ready ? row.rowData.progress : 0 + fallbackLit: row.ready && row.rowData.lit + place: row.panel.facts[Model.factsKey(row.modelData)] || null + nowMs: row.panel.effectiveMs + hovered: rowHover.hovered + hour24: row.panel.hour24 + moonPhase: row.panel.moonPhase + foreground: row.foreground + fainter: row.fainter + daylightMarker: row.panel.daylightMarker + fontFamily: row.fontFamily + + onScrubStarted: function(fraction) { row.panel.beginScrub(row.rowData, fraction) } + onScrubMoved: function(fraction) { row.panel.scrubTo(row.rowData, fraction) } + onScrubEnded: row.panel.endScrub() + onMoonShowRequested: row.panel.startMoonShow() + } + + // The last city stays; removing it would leave no way back. + PanelActionButton { + anchors.right: parent.right + anchors.top: parent.top + anchors.margins: Style.space(1) + iconText: "\u00d7" + tooltipText: "Remove" + foreground: row.fainter + hoverColor: row.foreground + fontFamily: row.fontFamily + fontSize: Style.font.bodySmall + enabled: row.removable + // Shown on the keyboard's pick too, so Delete's target is plain. + opacity: row.removable && row.lit ? 1 : 0 + visible: opacity > 0 + Behavior on opacity { NumberAnimation { duration: Style.duration(120) } } + onClicked: row.panel.removeCityAt(row.index) + } + + Column { + id: timeBlock + // One width for every row, so the labels beside it line up. + width: Math.max(row.panel.timeColumnWidth, implicitWidth) + anchors.right: parent.right + anchors.rightMargin: Style.spacing.rowPaddingX + anchors.verticalCenter: rowLabels.verticalCenter + spacing: Style.space(1) + + // The hour is already the brightest thing on the row, so hover lifts the meridiem. + LinkRow { + id: timeLine + anchors.right: parent.right + spacing: Style.spacing.xs + onClicked: { row.panel.toggleHour24(); strip.dismissChips() } + + Text { + id: bigTime + textFormat: Text.PlainText + text: row.ready ? row.rowData.time : "--:--" + color: row.foreground + font.family: row.fontFamily + font.pixelSize: Style.font.heading + font.weight: Font.DemiBold + } + + Caption { + anchors.baseline: bigTime.baseline + text: row.rowData.meridiem || "" + visible: text !== "" + color: timeLine.hovered ? row.foreground : row.dim + } + } + + LinkRow { + id: offsetLine + anchors.right: parent.right + spacing: Style.space(5) + visible: row.ready + onClicked: { row.panel.toggleOffsetMode(); strip.dismissChips() } + + Caption { + text: row.ready ? row.rowData.abbr : "" + color: offsetLine.hovered ? row.dim : row.fainter + } + + Caption { + text: row.panel.offsetTextFor(row.rowData) + visible: text !== "" + color: offsetLine.hovered ? row.foreground : row.fainter + } + } + } + + component Caption: Text { + textFormat: Text.PlainText + color: row.dim + font.family: row.fontFamily + font.pixelSize: Style.font.caption + } + + component LinkRow: Row { + id: link + signal clicked() + readonly property bool hovered: linkHover.hovered + HoverHandler { + id: linkHover + cursorShape: Qt.PointingHandCursor + } + TapHandler { onTapped: link.clicked() } + } +} diff --git a/shell/plugins/panels/elsewhen/CitySearch.qml b/shell/plugins/panels/elsewhen/CitySearch.qml new file mode 100644 index 000000000000..e91cae2c509c --- /dev/null +++ b/shell/plugins/panels/elsewhen/CitySearch.qml @@ -0,0 +1,101 @@ +import QtQuick +import qs.Commons +import qs.Ui +import "Model.js" as Model + +// A button that opens into a city search: a field, then the matching cities +// with their zone and offset. Arrows move the selection, Return picks it, +// Escape backs out. Inline rather than a dropdown so the results grow the +// panel instead of running off the bottom of the screen. +Column { + id: search + + // [{ label, value }] from Model.zoneOptions. + property var options: [] + property int limit: 6 + // Zone id -> offset text; read inside a binding, so its dependencies track. + property var offsetLabel: function(zoneId) { return "" } + property bool loading: false + property string buttonText: "+ Add a city" + property string placeholderText: "Search cities\u2026" + property string loadingText: "Loading zones\u2026" + property real fontSize: Style.font.bodySmall + property color foreground: Color.foreground + property color dim: Qt.darker(foreground, 1.55) + property color fainter: Qt.darker(foreground, 2.1) + property string fontFamily: Style.font.family + + // False when the host shows CityMatches elsewhere. + property bool inlineResults: true + // The host's keyboard cursor is on the button. + property bool hasCursor: false + + property bool active: false + readonly property string query: field.text + readonly property var matches: active ? Model.searchZones(options, query, limit) : [] + // An index, not the match itself: the list is rebuilt on every keystroke. + property int selectedIndex: 0 + + signal picked(string label, string id) + signal dismissed() + + onQueryChanged: selectedIndex = 0 + onMatchesChanged: if (selectedIndex >= matches.length) selectedIndex = 0 + + function start() { + selectedIndex = 0 + active = true + Qt.callLater(function() { field.text = ""; field.forceActiveFocus() }) + } + + // The hidden field would keep the keyboard, so the host takes it back on dismissed. + function stop() { + active = false + field.text = "" + dismissed() + } + + function pick(match) { + picked(match.label, match.value) + stop() + } + + function pickSelected() { + if (matches.length > 0) pick(matches[Util.clamp(selectedIndex, 0, matches.length - 1)]) + } + + spacing: Style.spacing.md + + Button { + width: parent.width + // Matches the field, so opening the search does not shift the layout. + height: field.implicitHeight + visible: !search.active + text: search.buttonText + fontSize: search.fontSize + foreground: search.foreground + fontFamily: search.fontFamily + bordered: true + hasCursor: search.hasCursor + onClicked: search.start() + } + + TextField { + id: field + visible: search.active + width: parent.width + placeholderText: search.placeholderText + foreground: search.foreground + Keys.onEscapePressed: search.stop() + Keys.onReturnPressed: search.pickSelected() + Keys.onEnterPressed: search.pickSelected() + Keys.onUpPressed: search.selectedIndex = Model.moveSelection(search.selectedIndex, -1, search.matches.length) + Keys.onDownPressed: search.selectedIndex = Model.moveSelection(search.selectedIndex, 1, search.matches.length) + } + + CityMatches { + width: parent.width + visible: search.active && search.inlineResults + citySearch: search + } +} diff --git a/shell/plugins/panels/elsewhen/DaylightStrip.qml b/shell/plugins/panels/elsewhen/DaylightStrip.qml new file mode 100644 index 000000000000..4c171c98e4b7 --- /dev/null +++ b/shell/plugins/panels/elsewhen/DaylightStrip.qml @@ -0,0 +1,223 @@ +import QtQuick +import QtQuick.Controls +import qs.Commons +import qs.Ui +import "Model.js" as Model +import "Sun.js" as Sun + +// A city's 24 hours, midnight to midnight: its real daylight lit, a marker at +// now (the sun by day, tonight's moon by night), and sunrise/sunset arrows +// while the row is hovered. Dragging along it scrubs every clock. +Item { + id: strip + + property bool ready: false + property int offsetMinutes: 0 + property real progress: 0 + // The fixed civil band's answer, for a city with no coordinates yet. + property bool fallbackLit: false + // { lat, lon } from the fetcher's geocode, or null. + property var place: null + property double nowMs: 0 + property bool hovered: false + property bool hour24: false + property real moonPhase: 0 + property color foreground: Color.foreground + property color fainter: Qt.darker(foreground, 2.1) + property color daylightMarker: "#E5C736" + property string fontFamily: Style.font.family + + readonly property int trackHeight: Math.max(2, Style.space(3)) + + // Which arrow's time is showing: its index, or Model.NO_CHIP. + property int shownChip: Model.NO_CHIP + + signal scrubStarted(real fraction) + signal scrubMoved(real fraction) + signal scrubEnded() + signal moonShowRequested() + + function dismissChips() { shownChip = Model.NO_CHIP } + + // Decided against the value read on press, so either delivery order of a + // tap and the release underneath it lands the same way. + function dismissUnlessChanged(atPress) { + shownChip = Model.chipAfterRelease(shownChip, atPress) + } + + onHoveredChanged: if (!hovered) dismissChips() + + height: Style.space(18) + + // Keyed to local midnight, not the ticking clock, so the sun and the + // Repeaters below rebuild once a day rather than once a second. + readonly property double dayMs: ready ? Sun.localMidnightMs(nowMs, offsetMinutes) : 0 + + readonly property var sun: { + if (!ready || !place || place.lat === undefined || place.lon === undefined) return null + // Local noon: the instant furthest from either edge of the day. + return Sun.sunTimes(place.lat, place.lon, dayMs + 43200000, offsetMinutes) + } + + // Empty in polar day and night, when the sun does not cross the horizon. + readonly property var sunMarks: { + if (!sun || sun.kind !== "normal") return [] + var out = [] + var up = Sun.eventMark(sun.riseMinutes) + var down = Sun.eventMark(sun.setMinutes) + if (up !== null) out.push({ x: up, minutes: sun.riseMinutes, rising: true, name: "Sunrise" }) + if (down !== null) out.push({ x: down, minutes: sun.setMinutes, rising: false, name: "Sunset" }) + return out + } + + // Read from the band that is drawn, so the sun never sits in the dark. + readonly property bool litNow: sun ? Sun.litAt(sun, ready ? progress * 1440 : 0) + : (ready && fallbackLit) + + Rectangle { + id: track + visible: strip.ready + anchors.left: parent.left + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + height: strip.trackHeight + radius: height / 2 + color: Util.alpha(strip.foreground, 0.10) + + // Polar night has no band at all, rather than a zero-width one. + Repeater { + model: strip.sun ? Sun.litSpans(strip.sun) + : [{ x0: Model.daylightStart(), x1: Model.daylightEnd() }] + + Rectangle { + required property var modelData + x: parent.width * modelData.x0 + width: Math.max(1, parent.width * (modelData.x1 - modelData.x0)) + height: parent.height + radius: parent.radius + color: Util.alpha(strip.foreground, 0.28) + } + } + + Rectangle { + id: nowMarker + width: Math.max(8, Style.space(10)) + height: width + radius: width / 2 + x: Math.round(parent.width * (strip.ready ? strip.progress : 0) - width / 2) + y: (parent.height - height) / 2 + color: strip.litNow ? strip.daylightMarker : "transparent" + + MoonDot { + anchors.fill: parent + visible: !strip.litNow + phase: strip.moonPhase + color: strip.foreground + } + + Behavior on x { NumberAnimation { duration: Style.duration(400); easing.type: Easing.OutCubic } } + } + } + + // Scrub, or Shift-click the moon to run its phase show. The arrows below are + // later siblings, so their taps never reach this. + MouseArea { + anchors.fill: parent + cursorShape: Qt.SizeHorCursor + preventStealing: true + enabled: strip.ready + + property bool showing: false + property int chipAtPress: Model.NO_CHIP + + function onMoon(mouse) { + if (strip.litNow) return false + return Math.abs(mouse.x - (nowMarker.x + nowMarker.width / 2)) <= nowMarker.width + } + + function finish() { + if (!showing) strip.scrubEnded() + strip.dismissUnlessChanged(chipAtPress) + showing = false + } + + onPressed: function(mouse) { + showing = (mouse.modifiers & Qt.ShiftModifier) !== 0 && onMoon(mouse) + chipAtPress = strip.shownChip + if (showing) strip.moonShowRequested() + else strip.scrubStarted(mouse.x / width) + } + onPositionChanged: function(mouse) { + if (!showing) strip.scrubMoved(mouse.x / width) + } + onReleased: finish() + onCanceled: finish() + } + + // Sunrise and sunset, just outside the lit band they point at. + Repeater { + model: strip.sunMarks + + Item { + id: arrow + required property var modelData + required property int index + readonly property bool rising: modelData.rising + + // A finger-sized box around a caption-sized glyph, tucked towards the band. + width: Style.space(14) + height: Style.space(16) + anchors.verticalCenter: parent.verticalCenter + x: Model.arrowBox(arrow.modelData.x, strip.width, arrow.width, Style.space(3), arrow.rising) + + // Hidden while the now marker stands on it. nowMarker.x, not progress, + // so it reappears exactly as the eased marker clears. + readonly property bool covered: { + var markerX = nowMarker.x + if (!strip.ready) return false + return Model.arrowCovered(arrow.x, arrow.width, markerX + nowMarker.width / 2, + nowMarker.width, Style.space(4)) + } + + // Gone rather than faded, so a hidden arrow is also untappable. + opacity: strip.hovered && !arrow.covered ? 1 : 0 + visible: opacity > 0 + Behavior on opacity { NumberAnimation { duration: Style.duration(160) } } + + // Sunrise sits a little high and sunset a little low: a cue that needs no reading. + transform: Translate { y: arrow.rising ? -Style.space(2) : Style.space(2) } + + onCoveredChanged: if (arrow.covered && strip.shownChip === arrow.index) strip.dismissChips() + + Text { + anchors.centerIn: parent + textFormat: Text.PlainText + text: arrow.rising ? "\u2191" : "\u2193" + color: arrowHover.hovered || strip.shownChip === arrow.index ? strip.foreground : strip.fainter + font.family: strip.fontFamily + font.pixelSize: Style.font.caption + } + + HoverHandler { + id: arrowHover + cursorShape: Qt.PointingHandCursor + } + + TapHandler { + // Read on press, so a dismissal that already ran underneath cannot + // make an open chip look shut. + property int atPress: Model.NO_CHIP + onPressedChanged: if (pressed) atPress = strip.shownChip + onTapped: strip.shownChip = Model.chipAfterTap(atPress, arrow.index) + } + + PanelToolTip { + visible: strip.shownChip === arrow.index + delay: 0 + closePolicy: Popup.NoAutoClose + text: arrow.modelData.name + " " + Model.formatMinuteOfDay(arrow.modelData.minutes, strip.hour24) + fontFamily: strip.fontFamily + } + } + } +} diff --git a/shell/plugins/panels/elsewhen/Globe.qml b/shell/plugins/panels/elsewhen/Globe.qml new file mode 100644 index 000000000000..335312eca513 --- /dev/null +++ b/shell/plugins/panels/elsewhen/Globe.qml @@ -0,0 +1,619 @@ +import QtQuick +import Quickshell +import Quickshell.Io +import qs.Commons +import qs.Ui +import "GlobeModel.js" as Solar +import "Model.js" as Model + +// A spinnable orthographic globe: coastlines, the day/night terminator and the +// major city of every zone. Owns its data files and clock probe; Panel mounts it. +Item { + id: root + + property color foreground: Color.foreground + property color dim: Qt.darker(foreground, 1.55) + property color fainter: Qt.darker(foreground, 2.1) + property color daylightMarker + // Passed in so the footer's moon agrees with the rows' strips. + property real moonPhase: 0.5 + // Night dots are dark so they read against the bright continents. + readonly property color nightMarker: Util.alpha(Color.background, 0.92) + property string fontFamily: Style.font.family + property bool hour24: false + // The panel's offset setting, and the offset "home" is measured from. + property string offsetMode: "home" + property int homeOffsetMinutes: 0 + // Cities the list tracks, lower-cased: accent color and first label slots. + property var trackedNames: [] + // Faded in near the end of the zoom, where footer and jump bar are legible. + property real chromeOpacity: 1 + + // Opaque tones mixed against the background, so the rows behind never show through. + readonly property color surfaceBase: Color.popups.background + // Light names over sea, dark over land, split at the coastline. + readonly property color seaInk: foreground + readonly property color landInk: surfaceBase + + // Merged into the built-ins so a tracked city always appears. [name, zone, lat, lon, rank] + property var trackedCities: [] + // Reached with the jump box; the panel never saves them. + property var sessionCities: [] + property var jumpOptions: [] // the whole zone catalogue, unfiltered + + // Always shown, always labelled, drawn in the accent like the hero globe's marker. + property var homeRow: [] + readonly property string homeName: + homeRow.length > 0 ? String(homeRow[0]).toLowerCase() : "" + + property string pendingJump: "" // waiting on coordinates to arrive + + signal jumpRequested(string label, string zone) + // The jump box closed; the host should take the keyboard back. + signal jumpDismissed() + signal exitRequested() + // The footer offset was clicked; the panel owns the setting. + signal offsetModeToggleRequested() + // Only real selections: -1 means "no city" here but "home" in the list. + signal citySelected(string label, string zone) + signal cityTapped(string label, string zone) + + // ---- data ------------------------------------------------------------- + property var land: [] // coastline rings, flat [lon,lat,...] + property var landCoarse: [] // half the vertices, for the small end of the zoom + property var cities: [] // [name, zone, lat, lon, rank] + property var offsets: ({}) // zone -> minutes east of UTC + + property real spin: 20 // degrees; the meridian facing the viewer + // Latitude under the viewer. Not "tilt": the hero globe uses that for the axial lean. + property real viewLat: 20 + property real velocity: 0 // degrees per tick, for the throw + + readonly property real dragSpinRate: 0.45 // degrees per pixel + readonly property real dragTiltRate: 0.35 + readonly property real dragLatLimit: 80 + readonly property real flyLatLimit: 70 + readonly property real throwDecay: 0.96 // per 16 ms tick + + // A "label|zone" key, not an index: allCities is rebuilt as its inputs land + // and an index would silently move to another city. + property string selectedKey: "" + readonly property int selected: { + if (selectedKey === "") return -1 + for (var i = 0; i < allCities.length; i++) + if (keyAt(i) === selectedKey) return i + return -1 + } + + function keyAt(i) { + var c = allCities[i] + return (c === undefined || c === null) ? "" : Model.factsKey({ label: c[0], id: c[1] }) + } + + function selectAt(i) { selectedKey = i >= 0 ? keyAt(i) : "" } + + // A click at disc-centered coordinates: select the hit and turn it to face + // you. A miss only clears. On root so tests share the pointer's code path. + function pickAt(cx, cy) { + var hit = hitAt(cx, cy) + selectAt(hit) + if (hit >= 0) { + flyTo(allCities[hit][2], allCities[hit][3]) + cityTapped(allCities[hit][0], allCities[hit][1]) + } + return hit + } + + property double nowMs: Date.now() + property bool dragging: false + + // Both set from Panel, which owns the zoom: 0 in the header, 1 full size. + property bool transitioning: false + property real zoomLevel: 1 + property bool smoothMotion: true + + // A full paint is ~14 ms; names and the graticule are the expensive parts, + // so they drop while the globe moves and nobody can read them anyway. + readonly property bool reduced: smoothMotion + && (dragging || flight.running || transitioning || Math.abs(velocity) > 0.01) + + onReducedChanged: canvas.requestPaint() + + readonly property var allCities: + Model.mergeCities(homeRow, cities, trackedCities, sessionCities) + + readonly property var jumpMatches: jumpSearch.matches + onJumpMatchesChanged: probeZones() + + // Centering a city is setting spin and viewLat to its own coordinates. + function flyTo(lat, lon) { + flight.stop() + velocity = 0 + flightSpin.from = spin + flightSpin.to = spin + Solar.shortestTurn(spin, lon) + flightViewLat.from = viewLat + flightViewLat.to = Util.clamp(lat, -flyLatLimit, flyLatLimit) + flight.restart() + } + + // Home's coordinates can land after the globe on a cold cache; hold the request. + property bool homePending: false + + // Opening lands on home and selects it, so the footer names it. + function showHome() { + if (homeRow.length < 4 || homeRow[2] === undefined || homeRow[2] === null) { + homePending = true + return + } + homePending = false + selectAt(indexOfCity(homeRow[0], homeRow[1])) + flyTo(homeRow[2], homeRow[3]) + } + + onHomeRowChanged: if (homePending) showHome() + + function indexOfCity(label, zone) { + for (var i = 0; i < allCities.length; i++) + if (allCities[i][0] === label && allCities[i][1] === zone) return i + return -1 + } + + function goTo(label, zone) { + var i = indexOfCity(label, zone) + if (i >= 0) { + selectedKey = keyAt(i) + flyTo(allCities[i][2], allCities[i][3]) + pendingJump = "" + return + } + // Not on the globe yet: ask for it, and fly once its coordinates land. + pendingJump = label + "|" + zone + jumpRequested(label, zone) + } + + onAllCitiesChanged: { + probeZones() + canvas.requestPaint() + if (pendingJump === "") return + var parts = pendingJump.split("|") + if (indexOfCity(parts[0], parts[1]) >= 0) goTo(parts[0], parts[1]) + } + + function startJump() { + jumpSearch.start() + } + + // Sub-pixel scale (spaceReal, not space) so thin strokes keep their weights. + readonly property real uiScale: Style.spaceReal(1) + + function scaled(px) { return Solar.scalePx(px, uiScale, 1) } + + readonly property real footerHeight: Style.space(34) + readonly property real jumpHeight: Style.space(4) + jumpSearch.implicitHeight + readonly property real radius: Math.max(40, + Math.min(width, height - footerHeight - jumpHeight) / 2 - Style.space(6)) + readonly property var sub: Solar.subsolarPoint(nowMs) + + // FileView, not XMLHttpRequest: XHR on file:// comes back empty in the shell. + readonly property string pluginDir: Quickshell.env("OMARCHY_PATH") + "/shell/plugins/panels/elsewhen" + + // "UTC+2" or "+9h", per the panel's setting, exactly as the rows print it. + function offsetLabelFor(zone) { + var off = offsets[zone] + if (off === undefined) return "" + return offsetMode === "utc" ? Model.utcOffsetLabel(off) + : Model.relativeOffsetLabel(off, homeOffsetMinutes) + } + + function isTracked(i) { + var c = allCities[i] + return c !== undefined + && trackedNames.indexOf(String(c[0]).toLowerCase()) >= 0 + } + + // Guarded: read from paints while the city list is still being assembled. + function isHome(i) { + var c = allCities[i] + return c !== undefined && homeName !== "" + && String(c[0]).toLowerCase() === homeName + } + + function cityDaylight(i) { + var c = allCities[i] + if (c === undefined) return false + return Solar.isDaylight(c[2], c[3], sub) + } + + // Labels count as part of their city and win over a neighbouring dot. + function hitAt(px, py) { + var pad = Style.space(3) + for (var i = 0; i < labels.length; i++) { + var b = labels[i].box + if (px >= b.x - pad && px <= b.x + b.w + pad + && py >= b.y - pad && py <= b.y + b.h + pad) return labels[i].index + } + var best = -1, bestD = Style.space(13) + for (var j = 0; j < plotted.length; j++) { + var d = Math.hypot(px - plotted[j].x, py - plotted[j].y) + if (d < bestD) { bestD = d; best = plotted[j].index } + } + return best + } + + // ---- what actually gets drawn ----------------------------------------- + // Near-side cities in priority order, thinned; `keep` always survives. + readonly property var plotted: { + if (allCities.length === 0 || radius <= 0) return [] + var cand = [] + for (var i = 0; i < allCities.length; i++) { + var p = Solar.project(allCities[i][2], allCities[i][3], spin, viewLat, radius) + if (!p.visible) continue + var must = isHome(i) || isTracked(i) || i === selected + cand.push({ index: i, x: p.x, y: p.y, cosc: p.cosc, + rank: allCities[i][4], keep: must }) + } + cand.sort(function(a, b) { + if (a.keep !== b.keep) return a.keep ? -1 : 1 + if (a.rank !== b.rank) return a.rank - b.rank + return b.cosc - a.cosc + }) + return Solar.declutter(cand, Style.space(19)) + } + + // ---- labels ----------------------------------------------------------- + readonly property var labels: { + if (reduced) return [] + var cand = [] + for (var i = 0; i < plotted.length; i++) { + var p = plotted[i] + if (p.cosc < 0.12) continue // the rim; labels run off + cand.push({ index: p.index, name: allCities[p.index][0], x: p.x, y: p.y, + rank: p.keep ? 0 : p.rank, cosc: p.cosc }) + } + var charW = Style.font.caption * 0.62 + return Solar.layoutLabels(cand, charW, Style.font.caption + Style.space(3), 14, + width / 2 - Style.space(4), scaled(6)) + } + + FileView { + path: root.pluginDir + "/world.json" + printErrors: true + onLoaded: { + try { + root.land = JSON.parse(text()) + var coarse = [] + for (var i = 0; i < root.land.length; i++) + coarse.push(Solar.decimateRing(root.land[i], 2, 8)) + root.landCoarse = coarse + canvas.requestPaint() + } catch (e) { } + } + } + + FileView { + path: root.pluginDir + "/cities.json" + printErrors: true + onLoaded: { + try { root.cities = JSON.parse(text()); root.probeZones() } catch (e) { } + } + } + + property bool probeQueued: false + + // Queued rather than dropped while running, or late zones never get an offset. + // Includes the jump matches, whose offsets tell two results apart. + function probeZones() { + if (allCities.length === 0) return + if (zoneProc.running) { probeQueued = true; return } + var zones = [], seen = {} + function add(id) { if (!seen[id]) { seen[id] = true; zones.push(id) } } + for (var i = 0; i < allCities.length; i++) add(allCities[i][1]) + for (var j = 0; j < jumpMatches.length; j++) add(jumpMatches[j].value) + zoneProc.command = Model.probeCommand(zones, false) + zoneProc.running = true + } + + Process { + id: zoneProc + stdout: StdioCollector { + onStreamFinished: { + var probe = Model.parseProbe(text) + var map = {} + for (var id in probe) map[id] = probe[id].offsetMinutes + root.offsets = map + canvas.requestPaint() + Qt.callLater(function() { + if (!root.probeQueued) return + root.probeQueued = false + root.probeZones() + }) + } + } + } + + Timer { interval: 20000; running: true; repeat: true + onTriggered: { root.nowMs = Date.now(); canvas.requestPaint() } } + Timer { interval: 300000; running: true; repeat: true; onTriggered: root.probeZones() } + + ParallelAnimation { + id: flight + NumberAnimation { id: flightSpin; target: root; property: "spin" + duration: Style.duration(800); easing.type: Easing.OutCubic } + NumberAnimation { id: flightViewLat; target: root; property: "viewLat" + duration: Style.duration(800); easing.type: Easing.OutCubic } + } + + // The throw: spin keeps going after the drag and eases to a stop. + Timer { + interval: 16 + running: !root.dragging && Math.abs(root.velocity) > 0.01 + repeat: true + onTriggered: { + root.spin += root.velocity + root.velocity *= root.throwDecay + canvas.requestPaint() + } + } + + onPlottedChanged: canvas.requestPaint() + onTrackedNamesChanged: canvas.requestPaint() + onSpinChanged: canvas.requestPaint() + onViewLatChanged: canvas.requestPaint() + onSelectedChanged: { + canvas.requestPaint() + var c = selected >= 0 ? allCities[selected] : null + if (c !== null && c !== undefined) citySelected(String(c[0]), String(c[1])) + } + + // ---- the globe -------------------------------------------------------- + Canvas { + id: canvas + anchors.left: parent.left + anchors.right: parent.right + anchors.top: parent.top + height: parent.height - root.footerHeight - root.jumpHeight + renderStrategy: Canvas.Cooperative + + // The clipped continents from the last paint, reused by the label pass. + property var landPolys: [] + + function paintLabels(ctx, ink) { + ctx.fillStyle = ink + for (var i = 0; i < root.labels.length; i++) { + var L = root.labels[i] + var idx = L.index + var city = root.allCities[idx] + if (city === undefined) continue + var strong = root.isHome(idx) || root.isTracked(idx) + ctx.font = (strong ? "bold " : "") + Style.font.caption + + "px \"" + root.fontFamily + "\"" + ctx.fillText(city[0], L.box.x, L.box.y + L.box.h / 2) + } + } + + // Points arrive as [lat, lon]; runs end exactly on the horizon. + function strokePath(ctx, pts) { + var segs = Solar.visibleSegments(pts, root.spin, root.viewLat, root.radius) + for (var i = 0; i < segs.length; i++) { + ctx.moveTo(segs[i][0].x, segs[i][0].y) + for (var j = 1; j < segs[i].length; j++) ctx.lineTo(segs[i][j].x, segs[i][j].y) + } + } + + onPaint: { + var ctx = getContext("2d") + ctx.reset() + ctx.translate(width / 2, height / 2) + var r = root.radius + var fg = root.foreground + + // Ocean disc. + ctx.beginPath() + ctx.arc(0, 0, r, 0, Math.PI * 2) + ctx.fillStyle = Model.mix(root.surfaceBase, fg, 0.05) + ctx.fill() + ctx.lineWidth = root.scaled(1) + ctx.strokeStyle = Util.alpha(fg, 0.22) + ctx.stroke() + + // Graticule every 30 degrees, or 60 while moving. + var gStep = root.reduced ? 60 : 30 + ctx.beginPath() + var lat, lon, pts, i + for (lon = -180; lon < 180; lon += gStep) { + pts = [] + for (lat = -90; lat <= 90; lat += 3) pts.push([lat, lon]) + strokePath(ctx, pts) + } + for (lat = -60; lat <= 60; lat += gStep) { + pts = [] + for (lon = -180; lon <= 180; lon += 3) pts.push([lat, lon]) + strokePath(ctx, pts) + } + ctx.lineWidth = root.scaled(1) + ctx.strokeStyle = Util.alpha(fg, 0.10) + ctx.stroke() + + // Land, filled bright with no coastline stroke (the stroke pass cost ~4 ms). + // Coarse rings only below half size, where the dropped islands are invisible. + var coarseOk = root.reduced && root.zoomLevel < 0.5 && root.landCoarse.length > 0 + var rings = coarseOk ? root.landCoarse : root.land + var landPolys = [] + ctx.beginPath() + for (i = 0; i < rings.length; i++) { + var poly = Solar.clipRingToDisc(rings[i], root.spin, root.viewLat, root.radius) + if (poly.length < 3) continue + landPolys.push(poly) + ctx.moveTo(poly[0].x, poly[0].y) + for (var q = 1; q < poly.length; q++) ctx.lineTo(poly[q].x, poly[q].y) + ctx.closePath() + } + ctx.fillStyle = Model.mix(root.surfaceBase, fg, 0.92) + ctx.fill() + canvas.landPolys = landPolys + + // Day/night line. + ctx.beginPath() + strokePath(ctx, Solar.terminator(root.sub, 180)) + ctx.lineWidth = root.scaled(1) + ctx.strokeStyle = Util.alpha(root.daylightMarker, 0.55) + ctx.stroke() + + // Cities: gold in daylight, dark at night, each edged in the opposite tone. + for (var pi = 0; pi < root.plotted.length; pi++) { + var p = root.plotted[pi] + i = p.index + var day = root.cityDaylight(i) + var isSel = (i === root.selected) + ctx.beginPath() + ctx.arc(p.x, p.y, root.scaled(isSel ? 3.6 : 2.2), 0, Math.PI * 2) + ctx.fillStyle = day ? root.daylightMarker : root.nightMarker + ctx.fill() + ctx.lineWidth = root.scaled(1.2) + ctx.strokeStyle = day ? Util.alpha(Color.background, 0.7) : Util.alpha(fg, 0.85) + ctx.stroke() + if (root.isHome(i)) { + ctx.beginPath() + ctx.arc(p.x, p.y, root.scaled(3.4), 0, Math.PI * 2) + ctx.fillStyle = Color.accent + ctx.fill() + ctx.lineWidth = root.scaled(1.2) + ctx.strokeStyle = Util.alpha(Color.background, 0.5) + ctx.stroke() + ctx.beginPath() + ctx.arc(p.x, p.y, root.scaled(6.4), 0, Math.PI * 2) + ctx.lineWidth = root.scaled(1.4) + ctx.strokeStyle = Util.alpha(Color.accent, 0.65) + ctx.stroke() + } else if (root.isTracked(i)) { + ctx.beginPath() + ctx.arc(p.x, p.y, root.scaled(4.6), 0, Math.PI * 2) + ctx.lineWidth = root.scaled(1.3) + ctx.strokeStyle = Color.accent + ctx.stroke() + } + if (isSel) { + ctx.beginPath() + ctx.arc(p.x, p.y, root.scaled(7.5), 0, Math.PI * 2) + ctx.lineWidth = root.scaled(1.4) + ctx.strokeStyle = day ? root.daylightMarker : fg + ctx.stroke() + } + } + + // ---- city names: light everywhere, then dark clipped to the land ---- + ctx.textBaseline = "middle" + paintLabels(ctx, root.seaInk) + + ctx.save() + ctx.beginPath() + for (var lp = 0; lp < landPolys.length; lp++) { + var poly2 = landPolys[lp] + ctx.moveTo(poly2[0].x, poly2[0].y) + for (var r2 = 1; r2 < poly2.length; r2++) ctx.lineTo(poly2[r2].x, poly2[r2].y) + ctx.closePath() + } + ctx.clip() + paintLabels(ctx, root.landInk) + ctx.restore() + } + + MouseArea { + anchors.fill: parent + property real lastX: 0 + property real lastY: 0 + property bool moved: false + + onPressed: function(mouse) { + lastX = mouse.x; lastY = mouse.y + moved = false + root.dragging = true + root.velocity = 0 + } + onPositionChanged: function(mouse) { + var dx = mouse.x - lastX, dy = mouse.y - lastY + if (Math.abs(dx) + Math.abs(dy) > 2) moved = true + root.spin -= dx * root.dragSpinRate + root.viewLat = Util.clamp(root.viewLat + dy * root.dragTiltRate, + -root.dragLatLimit, root.dragLatLimit) + root.velocity = -dx * root.dragSpinRate + lastX = mouse.x; lastY = mouse.y + } + onReleased: function(mouse) { + root.dragging = false + if (moved) return + root.velocity = 0 + root.pickAt(mouse.x - canvas.width / 2, mouse.y - canvas.height / 2) + } + } + } + + GlobeFooter { + id: footer + anchors.left: parent.left + anchors.right: parent.right + anchors.bottom: jumpSearch.top + anchors.bottomMargin: Style.space(4) + height: root.footerHeight + opacity: root.chromeOpacity + + city: root.selected >= 0 ? root.allCities[root.selected] : null + // The globe's solar daylight, so the mark agrees with the city's dot. + daylight: footer.has && root.cityDaylight(root.selected) + clock: footer.has ? Model.formatClock(root.nowMs, root.offsets[footer.city[1]], root.hour24) : "" + offsetLabel: footer.has ? root.offsetLabelFor(footer.city[1]) : "" + badge: root.isHome(root.selected) ? "home" : (root.isTracked(root.selected) ? "tracked" : "") + moonPhase: root.moonPhase + foreground: root.foreground + dim: root.dim + fainter: root.fainter + daylightMarker: root.daylightMarker + fontFamily: root.fontFamily + onOffsetClicked: root.offsetModeToggleRequested() + } + + // ---- jump to a city ----------------------------------------------------- + // Searches the whole catalogue; a city not on the globe joins for this session. + CitySearch { + id: jumpSearch + anchors.left: parent.left + anchors.right: parent.right + anchors.bottom: parent.bottom + opacity: root.chromeOpacity + options: root.jumpOptions + limit: 5 + inlineResults: false + loading: root.jumpOptions.length === 0 + buttonText: "Jump to a city" + loadingText: "Loading cities\u2026" + offsetLabel: function(zoneId) { return Model.utcOffsetLabel(root.offsets[zoneId]) } + foreground: root.foreground + dim: root.dim + fainter: root.fainter + fontFamily: root.fontFamily + onPicked: function(label, id) { root.goTo(label, id) } + onDismissed: root.jumpDismissed() + } + + // Results overlay the globe so it never resizes under the pointer mid-search. + Rectangle { + visible: jumpSearch.active + anchors.left: parent.left + anchors.right: parent.right + anchors.bottom: jumpSearch.top + anchors.bottomMargin: Style.space(4) + height: Math.min(results.implicitHeight + Style.space(8), + parent.height - root.jumpHeight - Style.space(20)) + radius: Style.cornerRadius + color: root.surfaceBase + + CityMatches { + id: results + anchors.left: parent.left + anchors.right: parent.right + anchors.top: parent.top + anchors.margins: Style.space(4) + citySearch: jumpSearch + } + } +} diff --git a/shell/plugins/panels/elsewhen/GlobeFooter.qml b/shell/plugins/panels/elsewhen/GlobeFooter.qml new file mode 100644 index 000000000000..5dd1ad2d6909 --- /dev/null +++ b/shell/plugins/panels/elsewhen/GlobeFooter.qml @@ -0,0 +1,128 @@ +import QtQuick +import qs.Commons + +// The selected city under the globe: name, local time and badge, then its +// zone and offset. Blank without a selection; the parent reserves the height. +Item { + id: root + + property var city: null // [name, zone, lat, lon, rank] + property bool daylight: false + property string clock: "" + property string offsetLabel: "" + property string badge: "" // "home", "tracked" or "" + property real moonPhase: 0.5 + property color foreground: Color.foreground + property color dim: Qt.darker(foreground, 1.55) + property color fainter: Qt.darker(foreground, 2.1) + property color daylightMarker + property string fontFamily: Style.font.family + + signal offsetClicked() + + readonly property bool has: city !== null && city !== undefined + + // The mark matches the ink height of the name's capital; a pixel less, since + // a circle's antialiased edge reads a pixel wider than a glyph's. + TextMetrics { + id: capHeight + font.family: root.fontFamily + font.pixelSize: Style.font.caption + font.weight: Font.DemiBold + text: "M" + } + + Column { + anchors.horizontalCenter: parent.horizontalCenter + anchors.verticalCenter: parent.verticalCenter + spacing: Style.space(1) + visible: root.has + + Row { + anchors.horizontalCenter: parent.horizontalCenter + spacing: Style.space(7) + + Row { + anchors.verticalCenter: parent.verticalCenter + spacing: Style.space(4) + + // A lit dot by day, tonight's moon by night, as on the rows' strips. + // Placed on the name's baseline by y: anchors.baseline inside a Row loops. + Rectangle { + y: cityName.baselineOffset - height + width: Math.max(6, Math.round(capHeight.tightBoundingRect.height) - 1) + height: width + radius: width / 2 + visible: root.has + color: root.daylight ? root.daylightMarker : "transparent" + + MoonDot { + anchors.fill: parent + visible: !root.daylight + phase: root.moonPhase + color: root.foreground + } + } + + Text { + id: cityName + textFormat: Text.PlainText + text: root.has ? root.city[0] : "" + color: root.foreground + font.family: root.fontFamily + font.pixelSize: Style.font.caption + font.weight: Font.DemiBold + } + } + + Text { + anchors.verticalCenter: parent.verticalCenter + textFormat: Text.PlainText + text: root.clock + visible: text !== "" + color: root.dim + font.family: root.fontFamily + font.pixelSize: Style.font.caption + } + + Text { + anchors.verticalCenter: parent.verticalCenter + textFormat: Text.PlainText + text: root.badge + visible: root.has && text !== "" + color: Color.accent + font.family: root.fontFamily + font.pixelSize: Style.font.caption + } + } + + // Zone and offset together are the toggle, so it survives a blank offset. + Row { + anchors.horizontalCenter: parent.horizontalCenter + spacing: Style.space(6) + + Text { + textFormat: Text.PlainText + text: root.has ? root.city[1] : "" + color: offsetHover.hovered ? root.dim : root.fainter + font.family: root.fontFamily + font.pixelSize: Style.font.caption + } + + Text { + textFormat: Text.PlainText + text: root.offsetLabel + visible: text !== "" + color: offsetHover.hovered ? root.foreground : root.dim + font.family: root.fontFamily + font.pixelSize: Style.font.caption + } + + HoverHandler { + id: offsetHover + cursorShape: Qt.PointingHandCursor + } + TapHandler { onTapped: root.offsetClicked() } + } + } +} diff --git a/shell/plugins/panels/elsewhen/GlobeModel.js b/shell/plugins/panels/elsewhen/GlobeModel.js new file mode 100644 index 000000000000..979db4c67404 --- /dev/null +++ b/shell/plugins/panels/elsewhen/GlobeModel.js @@ -0,0 +1,300 @@ +.pragma library + +// Orthographic globe math: projection, the day/night terminator, the moon, +// and label placement. + +var DEG = Math.PI / 180 + +// Earth's obliquity, also the hero icon's lean. +var AXIAL_TILT = 23.44 + +// Every `keepEvery`th vertex of a flat [lon, lat, ...] ring, for drawing while +// the globe is scaled down. Rings at or under `minPoints` are returned whole. +function decimateRing(ring, keepEvery, minPoints) { + var step = keepEvery === undefined ? 2 : keepEvery + var floor = minPoints === undefined ? 8 : minPoints + var n = ring.length / 2 + if (step < 2 || n <= floor) return ring + var out = [] + for (var i = 0; i < n; i += step) out.push(ring[i * 2], ring[i * 2 + 1]) + // End on the original last vertex, not a chord back to the start. + var lastI = (n - 1) * 2 + if (out[out.length - 2] !== ring[lastI] || out[out.length - 1] !== ring[lastI + 1]) + out.push(ring[lastI], ring[lastI + 1]) + return out +} + +// A drawn pixel size that follows the shell's UI scale, floored so hairlines +// do not drop out of the raster. +function scalePx(px, scale, minPx) { + var s = (typeof scale === "number" && isFinite(scale) && scale > 0) ? scale : 1 + var n = px * s + var floor = (minPx === undefined) ? 1 : minPx + return n < floor ? floor : n +} + +// Orthographic projection onto a disc of radius r seen from over (viewLat, spin). +function project(lat, lon, spin, viewLat, r) { + var phi = lat * DEG + var lam = (lon - spin) * DEG + var p0 = viewLat * DEG + var cosc = Math.sin(p0) * Math.sin(phi) + Math.cos(p0) * Math.cos(phi) * Math.cos(lam) + return { + x: r * Math.cos(phi) * Math.sin(lam), + y: -r * (Math.cos(p0) * Math.sin(phi) - Math.sin(p0) * Math.cos(phi) * Math.cos(lam)), + visible: cosc > 0, + cosc: cosc + } +} + +// The point with the sun directly overhead, good to a fraction of a degree. +function subsolarPoint(ms) { + var d = new Date(ms) + var jd = ms / 86400000 + 2440587.5 + var n = jd - 2451545.0 + var L = (280.460 + 0.9856474 * n) % 360 // mean longitude + var g = ((357.528 + 0.9856003 * n) % 360) * DEG // mean anomaly + var lambda = (L + 1.915 * Math.sin(g) + 0.020 * Math.sin(2 * g)) * DEG // ecliptic longitude + var eps = (AXIAL_TILT - 0.0000004 * n) * DEG // obliquity, slowly drifting + + var decl = Math.asin(Math.sin(eps) * Math.sin(lambda)) / DEG + + // Equation of time, in minutes, then the subsolar meridian. + var alpha = Math.atan2(Math.cos(eps) * Math.sin(lambda), Math.cos(lambda)) / DEG + var eot = (L - alpha + 540) % 360 - 180 // degrees, wrapped to +-180 + var utcHours = d.getUTCHours() + d.getUTCMinutes() / 60 + d.getUTCSeconds() / 3600 + var lon = -15 * (utcHours - 12) - eot + lon = ((lon + 540) % 360) - 180 + + return { lat: decl, lon: lon } +} + +// Degrees above the horizon, negative below it. +function solarElevation(lat, lon, sub) { + var cosz = Math.sin(lat * DEG) * Math.sin(sub.lat * DEG) + + Math.cos(lat * DEG) * Math.cos(sub.lat * DEG) * Math.cos((lon - sub.lon) * DEG) + return Math.asin(Math.max(-1, Math.min(1, cosz))) / DEG +} + +// -0.833 allows for refraction and the sun's disc, as sunrise tables do. +function isDaylight(lat, lon, sub) { + return solarElevation(lat, lon, sub) > -0.833 +} + +// The great circle 90 degrees from the subsolar point: the day/night line. +function terminator(sub, steps) { + var n = steps || 180 + var out = [] + var slat = sub.lat * DEG, slon = sub.lon * DEG + // Build an orthonormal frame around the subsolar axis and sweep a circle. + var s = [Math.cos(slat) * Math.cos(slon), Math.cos(slat) * Math.sin(slon), Math.sin(slat)] + var up = Math.abs(s[2]) < 0.9 ? [0, 0, 1] : [1, 0, 0] + var a = norm(cross(up, s)) + var b = norm(cross(s, a)) + for (var i = 0; i <= n; i++) { + var t = i / n * 2 * Math.PI + var v = [a[0] * Math.cos(t) + b[0] * Math.sin(t), + a[1] * Math.cos(t) + b[1] * Math.sin(t), + a[2] * Math.cos(t) + b[2] * Math.sin(t)] + out.push([Math.asin(v[2]) / DEG, Math.atan2(v[1], v[0]) / DEG]) + } + return out +} + +function cross(u, v) { + return [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]] +} + +function norm(v) { + var m = Math.hypot(v[0], v[1], v[2]) || 1 + return [v[0] / m, v[1] / m, v[2] / m] +} + +// Keep points, in priority order, that clear every kept point by minDist. +// Points marked `keep` always survive. +function declutter(points, minDist) { + var kept = [] + for (var i = 0; i < points.length; i++) { + var p = points[i] + if (p.keep) { kept.push(p); continue } + var clash = false + for (var j = 0; j < kept.length; j++) { + if (Math.hypot(p.x - kept[j].x, p.y - kept[j].y) < minDist) { clash = true; break } + } + if (!clash) kept.push(p) + } + return kept +} + +// ---- the moon + +// The mean synodic month against a known new moon: good to a few hours. +var SYNODIC_MONTH = 29.530588853 // days +var KNOWN_NEW_MOON_JD = 2451550.1 // 2000-01-06 18:14 UTC + +// Position through the lunation: 0 new, 0.25 first quarter, 0.5 full, +// 0.75 last quarter. +function moonPhase(ms) { + var jd = Number(ms) / 86400000 + 2440587.5 + var p = ((jd - KNOWN_NEW_MOON_JD) / SYNODIC_MONTH) % 1 + return p < 0 ? p + 1 : p +} + +// The lit part of the moon on a disc of radius r at the origin: the limb, then +// the terminator back, a semicircle squashed by the signed cos(2*pi*phase). +function moonLitOutline(phase, r, steps) { + var n = steps || 24 + var theta = 2 * Math.PI * Number(phase) + var squash = Math.cos(theta) + var side = Number(phase) > 0.5 ? -1 : 1 // waning lights the other limb + var out = [] + var i, t + for (i = 0; i <= n; i++) { + t = Math.PI * i / n + out.push({ x: side * r * Math.sin(t), y: -r * Math.cos(t) }) + } + for (i = n; i >= 0; i--) { + t = Math.PI * i / n + out.push({ x: side * r * squash * Math.sin(t), y: -r * Math.cos(t) }) + } + return out +} + +// ---- clipping to the disc + +// Where a [lat, lon] segment crosses the horizon, by bisection. +function limbCrossing(a, b, spin, viewLat, r) { + // Segments spanning the antimeridian cannot be interpolated in lat/lon. + if (Math.abs(b[1] - a[1]) > 180) return null + var lo = 0, hi = 1 + for (var i = 0; i < 8; i++) { + var m = (lo + hi) / 2 + var p = project(a[0] + (b[0] - a[0]) * m, a[1] + (b[1] - a[1]) * m, spin, viewLat, r) + if (p.visible) lo = m; else hi = m + } + return project(a[0] + (b[0] - a[0]) * lo, a[1] + (b[1] - a[1]) * lo, spin, viewLat, r) +} + +// The near-side runs of a polyline, each ending exactly on the horizon. +function visibleSegments(pts, spin, viewLat, r) { + var out = [], run = [], prev = null, prevVis = false + function flush() { if (run.length > 1) out.push(run); run = [] } + for (var i = 0; i < pts.length; i++) { + var p = project(pts[i][0], pts[i][1], spin, viewLat, r) + if (p.visible) { + if (run.length === 0 && prev !== null && !prevVis) { + var enter = limbCrossing(pts[i], prev, spin, viewLat, r) + if (enter) run.push(enter) + } + run.push(p) + } else { + if (run.length > 0 && prev !== null) { + var exit = limbCrossing(prev, pts[i], spin, viewLat, r) + if (exit) run.push(exit) + } + flush() + } + prev = pts[i]; prevVis = p.visible + } + flush() + return out +} + +// A flat [lon, lat, ...] ring clipped to the visible hemisphere as one polygon +// that follows the limb, so its area changes smoothly as the globe turns. +function clipRingToDisc(ring, spin, viewLat, r) { + var pts = [] + for (var k = 0; k < ring.length; k += 2) pts.push([ring[k + 1], ring[k]]) + var out = [] + for (var i = 0; i < pts.length; i++) { + var A = pts[i], B = pts[(i + 1) % pts.length] + var pa = project(A[0], A[1], spin, viewLat, r) + var pb = project(B[0], B[1], spin, viewLat, r) + if (pa.visible && pb.visible) out.push({ p: pb, limb: false }) + else if (pa.visible) { + var ex = limbCrossing(A, B, spin, viewLat, r) + if (ex) out.push({ p: ex, limb: true }) + } else if (pb.visible) { + var en = limbCrossing(B, A, spin, viewLat, r) + if (en) out.push({ p: en, limb: true }) + out.push({ p: pb, limb: false }) + } + } + if (out.length < 3) return [] + + var res = [] + for (var j = 0; j < out.length; j++) { + res.push(out[j].p) + var nx = out[(j + 1) % out.length] + if (!out[j].limb || !nx.limb) continue + var a0 = Math.atan2(out[j].p.y, out[j].p.x) + var a1 = Math.atan2(nx.p.y, nx.p.x) + var d = a1 - a0 + while (d > Math.PI) d -= 2 * Math.PI + while (d < -Math.PI) d += 2 * Math.PI + var steps = Math.max(1, Math.round(Math.abs(d) / 0.15)) + for (var t = 1; t < steps; t++) { + var a = a0 + d * t / steps + res.push({ x: r * Math.cos(a), y: r * Math.sin(a) }) + } + } + return res +} + +// Greedy label placement by rank, then nearest the disc center; a label that +// would pass `maxX` flips to the left of its dot. `gap` is dot to name. +function layoutLabels(candidates, charWidth, lineHeight, limit, maxX, gap) { + var g = (typeof gap === "number" && isFinite(gap) && gap > 0) ? gap : 6 + var placed = [] + var sorted = candidates.slice().sort(function (p, q) { + if (p.rank !== q.rank) return p.rank - q.rank + return q.cosc - p.cosc + }) + for (var i = 0; i < sorted.length; i++) { + var c = sorted[i] + var w = c.name.length * charWidth + var x = c.x + g + if (maxX !== undefined && x + w > maxX) x = c.x - g - w + var box = { x: x, y: c.y - lineHeight / 2, w: w, h: lineHeight } + var clash = false + for (var j = 0; j < placed.length; j++) { + var o = placed[j].box + if (box.x < o.x + o.w && box.x + box.w > o.x && box.y < o.y + o.h && box.y + box.h > o.y) { + clash = true + break + } + } + if (clash) continue + placed.push({ index: c.index, box: box }) + if (limit && placed.length >= limit) break + } + return placed +} + +// Signed degrees in (-180, 180] to turn from one longitude to another. +function shortestTurn(from, to) { + var d = ((to - from) % 360 + 360) % 360 + return d > 180 ? d - 360 : d +} + +if (typeof module !== "undefined") { + module.exports = { + AXIAL_TILT: AXIAL_TILT, + SYNODIC_MONTH: SYNODIC_MONTH, + decimateRing: decimateRing, + scalePx: scalePx, + project: project, + subsolarPoint: subsolarPoint, + solarElevation: solarElevation, + isDaylight: isDaylight, + terminator: terminator, + declutter: declutter, + moonPhase: moonPhase, + moonLitOutline: moonLitOutline, + limbCrossing: limbCrossing, + visibleSegments: visibleSegments, + clipRingToDisc: clipRingToDisc, + layoutLabels: layoutLabels, + shortestTurn: shortestTurn + } +} diff --git a/shell/plugins/panels/elsewhen/Greetings.js b/shell/plugins/panels/elsewhen/Greetings.js new file mode 100644 index 000000000000..a8245ff05c4e --- /dev/null +++ b/shell/plugins/panels/elsewhen/Greetings.js @@ -0,0 +1,978 @@ +// What people say to each other at this hour where a clock points: zone -> +// country -> the language you would hear spoken there, with a few city +// overrides. Bands are local hours ascending from 0; `roman` is a +// pronunciation, given only where the script is not Latin. + +var LANGUAGES = { + en: { name: "English", bands: [ + { from: 0, text: "Good night", roman: "" }, + { from: 5, text: "Good morning", roman: "" }, + { from: 12, text: "Good afternoon", roman: "" }, + { from: 18, text: "Good evening", roman: "" } + ] }, + enAU: { name: "Australian English", bands: [ + { from: 0, text: "Night", roman: "" }, + { from: 5, text: "Morning", roman: "" }, + { from: 12, text: "G'day", roman: "" }, + { from: 18, text: "Evening", roman: "" } + ] }, + ga: { name: "Irish", bands: [ + { from: 0, text: "O\u00edche mhaith", roman: "" }, + { from: 6, text: "Maidin mhaith", roman: "" }, + { from: 12, text: "Tr\u00e1thn\u00f3na maith", roman: "" }, + { from: 19, text: "O\u00edche mhaith", roman: "" } + ] }, + es: { name: "Spanish", bands: [ + { from: 0, text: "Buenas noches", roman: "" }, + { from: 6, text: "Buenos d\u00edas", roman: "" }, + { from: 12, text: "Buenas tardes", roman: "" }, + { from: 19, text: "Buenas noches", roman: "" } + ] }, + esES: { name: "Spanish (Spain)", bands: [ + { from: 0, text: "Buenas noches", roman: "" }, + { from: 6, text: "Buenos d\u00edas", roman: "" }, + { from: 14, text: "Buenas tardes", roman: "" }, + { from: 21, text: "Buenas noches", roman: "" } + ] }, + ca: { name: "Catalan", bands: [ + { from: 0, text: "Bona nit", roman: "" }, + { from: 6, text: "Bon dia", roman: "" }, + { from: 13, text: "Bona tarda", roman: "" }, + { from: 20, text: "Bona nit", roman: "" } + ] }, + pt: { name: "Portuguese", bands: [ + { from: 0, text: "Boa noite", roman: "" }, + { from: 6, text: "Bom dia", roman: "" }, + { from: 12, text: "Boa tarde", roman: "" }, + { from: 20, text: "Boa noite", roman: "" } + ] }, + fr: { name: "French", bands: [ + { from: 0, text: "Bonne nuit", roman: "" }, + { from: 6, text: "Bonjour", roman: "" }, + { from: 18, text: "Bonsoir", roman: "" }, + { from: 22, text: "Bonne nuit", roman: "" } + ] }, + it: { name: "Italian", bands: [ + { from: 0, text: "Buonanotte", roman: "" }, + { from: 5, text: "Buongiorno", roman: "" }, + { from: 14, text: "Buon pomeriggio", roman: "" }, + { from: 18, text: "Buonasera", roman: "" }, + { from: 23, text: "Buonanotte", roman: "" } + ] }, + ro: { name: "Romanian", bands: [ + { from: 0, text: "Noapte bun\u0103", roman: "" }, + { from: 5, text: "Bun\u0103 diminea\u021ba", roman: "" }, + { from: 12, text: "Bun\u0103 ziua", roman: "" }, + { from: 18, text: "Bun\u0103 seara", roman: "" } + ] }, + de: { name: "German", bands: [ + { from: 0, text: "Gute Nacht", roman: "" }, + { from: 5, text: "Guten Morgen", roman: "" }, + { from: 11, text: "Guten Tag", roman: "" }, + { from: 18, text: "Guten Abend", roman: "" }, + { from: 22, text: "Gute Nacht", roman: "" } + ] }, + deAT: { name: "Austrian German", bands: [ + { from: 0, text: "Gute Nacht", roman: "" }, + { from: 5, text: "Guten Morgen", roman: "" }, + { from: 11, text: "Gr\u00fc\u00df Gott", roman: "" }, + { from: 18, text: "Guten Abend", roman: "" }, + { from: 22, text: "Gute Nacht", roman: "" } + ] }, + deCH: { name: "Swiss German", bands: [ + { from: 0, text: "Gute Nacht", roman: "" }, + { from: 5, text: "Guete Morge", roman: "" }, + { from: 11, text: "Gr\u00fcezi", roman: "" }, + { from: 18, text: "Guete Abig", roman: "" }, + { from: 22, text: "Gute Nacht", roman: "" } + ] }, + lb: { name: "Luxembourgish", bands: [ + { from: 0, text: "Gutt Nuecht", roman: "" }, + { from: 5, text: "Moien", roman: "" }, + { from: 12, text: "Gudde M\u00ebtteg", roman: "" }, + { from: 18, text: "Gudden Owend", roman: "" } + ] }, + nl: { name: "Dutch", bands: [ + { from: 0, text: "Goedenacht", roman: "" }, + { from: 6, text: "Goedemorgen", roman: "" }, + { from: 12, text: "Goedemiddag", roman: "" }, + { from: 18, text: "Goedenavond", roman: "" } + ] }, + da: { name: "Danish", bands: [ + { from: 0, text: "Godnat", roman: "" }, + { from: 5, text: "Godmorgen", roman: "" }, + { from: 10, text: "Goddag", roman: "" }, + { from: 18, text: "Godaften", roman: "" } + ] }, + no: { name: "Norwegian", bands: [ + { from: 0, text: "God natt", roman: "" }, + { from: 5, text: "God morgen", roman: "" }, + { from: 10, text: "God dag", roman: "" }, + { from: 18, text: "God kveld", roman: "" } + ] }, + sv: { name: "Swedish", bands: [ + { from: 0, text: "God natt", roman: "" }, + { from: 5, text: "God morgon", roman: "" }, + { from: 10, text: "God dag", roman: "" }, + { from: 18, text: "God kv\u00e4ll", roman: "" } + ] }, + fi: { name: "Finnish", bands: [ + { from: 0, text: "Hyv\u00e4\u00e4 y\u00f6t\u00e4", roman: "" }, + { from: 5, text: "Huomenta", roman: "" }, + { from: 11, text: "P\u00e4iv\u00e4\u00e4", roman: "" }, + { from: 18, text: "Iltaa", roman: "" }, + { from: 23, text: "Hyv\u00e4\u00e4 y\u00f6t\u00e4", roman: "" } + ] }, + is: { name: "Icelandic", bands: [ + { from: 0, text: "G\u00f3\u00f0a n\u00f3tt", roman: "" }, + { from: 6, text: "G\u00f3\u00f0an daginn", roman: "" }, + { from: 18, text: "Gott kv\u00f6ld", roman: "" } + ] }, + fo: { name: "Faroese", bands: [ + { from: 0, text: "G\u00f3\u00f0a n\u00e1tt", roman: "" }, + { from: 5, text: "G\u00f3\u00f0an morgun", roman: "" }, + { from: 10, text: "G\u00f3\u00f0an dag", roman: "" }, + { from: 18, text: "Gott kv\u00f8ld", roman: "" } + ] }, + kl: { name: "Greenlandic", bands: [ + { from: 0, text: "Inuugujoq", roman: "" } + ] }, + et: { name: "Estonian", bands: [ + { from: 0, text: "Head \u00f6\u00f6d", roman: "" }, + { from: 5, text: "Tere hommikust", roman: "" }, + { from: 12, text: "Tere p\u00e4evast", roman: "" }, + { from: 18, text: "Tere \u00f5htust", roman: "" } + ] }, + lv: { name: "Latvian", bands: [ + { from: 0, text: "Ar labu nakti", roman: "" }, + { from: 5, text: "Labr\u012bt", roman: "" }, + { from: 12, text: "Labdien", roman: "" }, + { from: 18, text: "Labvakar", roman: "" } + ] }, + lt: { name: "Lithuanian", bands: [ + { from: 0, text: "Labanakt", roman: "" }, + { from: 5, text: "Labas rytas", roman: "" }, + { from: 12, text: "Laba diena", roman: "" }, + { from: 18, text: "Labas vakaras", roman: "" } + ] }, + pl: { name: "Polish", bands: [ + { from: 0, text: "Dobranoc", roman: "" }, + { from: 5, text: "Dzie\u0144 dobry", roman: "" }, + { from: 18, text: "Dobry wiecz\u00f3r", roman: "" } + ] }, + cs: { name: "Czech", bands: [ + { from: 0, text: "Dobrou noc", roman: "" }, + { from: 5, text: "Dobr\u00e9 r\u00e1no", roman: "" }, + { from: 10, text: "Dobr\u00fd den", roman: "" }, + { from: 18, text: "Dobr\u00fd ve\u010der", roman: "" } + ] }, + sk: { name: "Slovak", bands: [ + { from: 0, text: "Dobr\u00fa noc", roman: "" }, + { from: 5, text: "Dobr\u00e9 r\u00e1no", roman: "" }, + { from: 10, text: "Dobr\u00fd de\u0148", roman: "" }, + { from: 18, text: "Dobr\u00fd ve\u010der", roman: "" } + ] }, + sl: { name: "Slovenian", bands: [ + { from: 0, text: "Lahko no\u010d", roman: "" }, + { from: 5, text: "Dobro jutro", roman: "" }, + { from: 10, text: "Dober dan", roman: "" }, + { from: 18, text: "Dober ve\u010der", roman: "" } + ] }, + hu: { name: "Hungarian", bands: [ + { from: 0, text: "J\u00f3 \u00e9jszak\u00e1t", roman: "" }, + { from: 5, text: "J\u00f3 reggelt", roman: "" }, + { from: 10, text: "J\u00f3 napot", roman: "" }, + { from: 18, text: "J\u00f3 est\u00e9t", roman: "" } + ] }, + hr: { name: "Croatian", bands: [ + { from: 0, text: "Laku no\u0107", roman: "" }, + { from: 5, text: "Dobro jutro", roman: "" }, + { from: 12, text: "Dobar dan", roman: "" }, + { from: 18, text: "Dobra ve\u010der", roman: "" } + ] }, + bs: { name: "Bosnian", bands: [ + { from: 0, text: "Laku no\u0107", roman: "" }, + { from: 5, text: "Dobro jutro", roman: "" }, + { from: 12, text: "Dobar dan", roman: "" }, + { from: 18, text: "Dobro ve\u010de", roman: "" } + ] }, + sq: { name: "Albanian", bands: [ + { from: 0, text: "Nat\u00ebn e mir\u00eb", roman: "" }, + { from: 5, text: "Mir\u00ebm\u00ebngjes", roman: "" }, + { from: 12, text: "Mir\u00ebdita", roman: "" }, + { from: 18, text: "Mir\u00ebmbr\u00ebma", roman: "" } + ] }, + mt: { name: "Maltese", bands: [ + { from: 0, text: "Il-lejl it-tajjeb", roman: "" }, + { from: 5, text: "Bon\u0121u", roman: "" }, + { from: 13, text: "Bonsw\u00e0", roman: "" } + ] }, + tr: { name: "Turkish", bands: [ + { from: 0, text: "\u0130yi geceler", roman: "" }, + { from: 5, text: "G\u00fcnayd\u0131n", roman: "" }, + { from: 12, text: "\u0130yi g\u00fcnler", roman: "" }, + { from: 18, text: "\u0130yi ak\u015famlar", roman: "" } + ] }, + af: { name: "Afrikaans", bands: [ + { from: 0, text: "Goeienag", roman: "" }, + { from: 5, text: "Goeiem\u00f4re", roman: "" }, + { from: 12, text: "Goeiemiddag", roman: "" }, + { from: 18, text: "Goeienaand", roman: "" } + ] }, + yo: { name: "Yoruba", bands: [ + { from: 0, text: "O d\u00e0\u00e1r\u1ecd\u0300", roman: "" }, + { from: 5, text: "\u1eb8 k\u00e1\u00e0\u00e1r\u1ecd\u0300", roman: "" }, + { from: 12, text: "\u1eb8 k\u00e1\u00e0s\u00e1n", roman: "" }, + { from: 16, text: "\u1eb8 k\u00fa\u00f9r\u1ecd\u0300l\u1eb9\u0301", roman: "" }, + { from: 20, text: "\u1eb8 k\u00fa\u00f9\u00e1l\u1eb9\u0301", roman: "" } + ] }, + tw: { name: "Twi", bands: [ + { from: 0, text: "Maadwo", roman: "" }, + { from: 5, text: "Maakye", roman: "" }, + { from: 12, text: "Maaha", roman: "" }, + { from: 18, text: "Maadwo", roman: "" } + ] }, + ha: { name: "Hausa", bands: [ + { from: 0, text: "Barka da dare", roman: "" }, + { from: 5, text: "Barka da safiya", roman: "" }, + { from: 12, text: "Barka da rana", roman: "" }, + { from: 16, text: "Barka da yamma", roman: "" }, + { from: 20, text: "Barka da dare", roman: "" } + ] }, + wo: { name: "Wolof", bands: [ + { from: 0, text: "Fanaanal j\u00e0mm", roman: "" }, + { from: 5, text: "J\u00e0mm nga fanaan", roman: "" }, + { from: 12, text: "Naka nga def", roman: "" }, + { from: 18, text: "J\u00e0mm nga yendoo", roman: "" } + ] }, + sw: { name: "Swahili", bands: [ + { from: 0, text: "Usiku mwema", roman: "" }, + { from: 5, text: "Habari za asubuhi", roman: "" }, + { from: 12, text: "Habari za mchana", roman: "" }, + { from: 16, text: "Habari za jioni", roman: "" }, + { from: 20, text: "Usiku mwema", roman: "" } + ] }, + rw: { name: "Kinyarwanda", bands: [ + { from: 0, text: "Ijoro ryiza", roman: "" }, + { from: 5, text: "Mwaramutse", roman: "" }, + { from: 12, text: "Mwiriwe", roman: "" }, + { from: 18, text: "Ijoro ryiza", roman: "" } + ] }, + lg: { name: "Luganda", bands: [ + { from: 0, text: "Sula bulungi", roman: "" }, + { from: 5, text: "Wasuze otya", roman: "" }, + { from: 12, text: "Osiibye otya", roman: "" }, + { from: 18, text: "Sula bulungi", roman: "" } + ] }, + ny: { name: "Chichewa", bands: [ + { from: 0, text: "Gonani bwino", roman: "" }, + { from: 5, text: "Mwadzuka bwanji", roman: "" }, + { from: 12, text: "Mwaswera bwanji", roman: "" }, + { from: 18, text: "Gonani bwino", roman: "" } + ] }, + sn: { name: "Shona", bands: [ + { from: 0, text: "Manheru", roman: "" }, + { from: 5, text: "Mangwanani", roman: "" }, + { from: 12, text: "Masikati", roman: "" }, + { from: 18, text: "Manheru", roman: "" } + ] }, + st: { name: "Sesotho", bands: [ + { from: 0, text: "Lumela", roman: "" } + ] }, + ss: { name: "Siswati", bands: [ + { from: 0, text: "Sawubona", roman: "" } + ] }, + mg: { name: "Malagasy", bands: [ + { from: 0, text: "Manao ahoana", roman: "" } + ] }, + so: { name: "Somali", bands: [ + { from: 0, text: "Habeen wanaagsan", roman: "" }, + { from: 5, text: "Subax wanaagsan", roman: "" }, + { from: 12, text: "Galab wanaagsan", roman: "" }, + { from: 18, text: "Habeen wanaagsan", roman: "" } + ] }, + id: { name: "Indonesian", bands: [ + { from: 0, text: "Selamat malam", roman: "" }, + { from: 4, text: "Selamat pagi", roman: "" }, + { from: 11, text: "Selamat siang", roman: "" }, + { from: 15, text: "Selamat sore", roman: "" }, + { from: 18, text: "Selamat malam", roman: "" } + ] }, + ms: { name: "Malay", bands: [ + { from: 0, text: "Selamat malam", roman: "" }, + { from: 5, text: "Selamat pagi", roman: "" }, + { from: 12, text: "Selamat tengah hari", roman: "" }, + { from: 15, text: "Selamat petang", roman: "" }, + { from: 19, text: "Selamat malam", roman: "" } + ] }, + tl: { name: "Filipino", bands: [ + { from: 0, text: "Magandang gabi", roman: "" }, + { from: 5, text: "Magandang umaga", roman: "" }, + { from: 12, text: "Magandang tanghali", roman: "" }, + { from: 13, text: "Magandang hapon", roman: "" }, + { from: 18, text: "Magandang gabi", roman: "" } + ] }, + vi: { name: "Vietnamese", bands: [ + { from: 0, text: "Ch\u00fac ng\u1ee7 ngon", roman: "" }, + { from: 5, text: "Ch\u00e0o bu\u1ed5i s\u00e1ng", roman: "" }, + { from: 12, text: "Ch\u00e0o bu\u1ed5i chi\u1ec1u", roman: "" }, + { from: 18, text: "Ch\u00e0o bu\u1ed5i t\u1ed1i", roman: "" } + ] }, + sm: { name: "Samoan", bands: [ + { from: 0, text: "Manuia le po", roman: "" }, + { from: 5, text: "Manuia le taeao", roman: "" }, + { from: 12, text: "Manuia le aoauli", roman: "" }, + { from: 17, text: "Manuia le afiafi", roman: "" }, + { from: 21, text: "Manuia le po", roman: "" } + ] }, + mi: { name: "Maori", bands: [ + { from: 0, text: "P\u014d m\u0101rie", roman: "" }, + { from: 5, text: "M\u014drena", roman: "" }, + { from: 11, text: "Kia ora", roman: "" }, + { from: 17, text: "Ahiahi m\u0101rie", roman: "" }, + { from: 21, text: "P\u014d m\u0101rie", roman: "" } + ] }, + rar: { name: "Cook Islands Maori", bands: [ + { from: 0, text: "Kia orana", roman: "" } + ] }, + niu: { name: "Niuean", bands: [ + { from: 0, text: "Fakalofa lahi atu", roman: "" } + ] }, + tkl: { name: "Tokelauan", bands: [ + { from: 0, text: "M\u0101l\u014d ni", roman: "" } + ] }, + tvl: { name: "Tuvaluan", bands: [ + { from: 0, text: "T\u0101lofa", roman: "" } + ] }, + to: { name: "Tongan", bands: [ + { from: 0, text: "M\u0101l\u014d e lelei", roman: "" } + ] }, + ty: { name: "Tahitian", bands: [ + { from: 0, text: "Ia ora na", roman: "" } + ] }, + fj: { name: "Fijian", bands: [ + { from: 0, text: "Ni sa moce", roman: "" }, + { from: 5, text: "Ni sa yadra", roman: "" }, + { from: 11, text: "Bula", roman: "" }, + { from: 19, text: "Ni sa moce", roman: "" } + ] }, + haw: { name: "Hawaiian", bands: [ + { from: 0, text: "Aloha p\u014d", roman: "" }, + { from: 5, text: "Aloha kakahiaka", roman: "" }, + { from: 11, text: "Aloha awakea", roman: "" }, + { from: 14, text: "Aloha \u02bbauinal\u0101", roman: "" }, + { from: 18, text: "Aloha ahiahi", roman: "" }, + { from: 23, text: "Aloha p\u014d", roman: "" } + ] }, + gil: { name: "Gilbertese", bands: [ + { from: 0, text: "Mauri", roman: "" } + ] }, + ch: { name: "Chamorro", bands: [ + { from: 0, text: "H\u00e5fa adai", roman: "" } + ] }, + mh: { name: "Marshallese", bands: [ + { from: 0, text: "Iakwe", roman: "" } + ] }, + pau: { name: "Palauan", bands: [ + { from: 0, text: "Alii", roman: "" } + ] }, + tpi: { name: "Tok Pisin", bands: [ + { from: 0, text: "Gutnait", roman: "" }, + { from: 5, text: "Moning", roman: "" }, + { from: 12, text: "Apinun", roman: "" }, + { from: 18, text: "Gutnait", roman: "" } + ] }, + bi: { name: "Bislama", bands: [ + { from: 0, text: "Gudnaet", roman: "" }, + { from: 5, text: "Gude", roman: "" }, + { from: 18, text: "Gudnaet", roman: "" } + ] }, + ht: { name: "Haitian Creole", bands: [ + { from: 0, text: "B\u00f2nwit", roman: "" }, + { from: 5, text: "Bonjou", roman: "" }, + { from: 12, text: "Bon apre midi", roman: "" }, + { from: 18, text: "Bonswa", roman: "" } + ] }, + pap: { name: "Papiamento", bands: [ + { from: 0, text: "Bon nochi", roman: "" }, + { from: 5, text: "Bon dia", roman: "" }, + { from: 12, text: "Bon tardi", roman: "" }, + { from: 18, text: "Bon nochi", roman: "" } + ] }, + gn: { name: "Guarani", bands: [ + { from: 0, text: "Mba'\u00e9ichapa", roman: "" } + ] }, + el: { name: "Greek", bands: [ + { from: 0, text: "\u039a\u03b1\u03bb\u03b7\u03bd\u03cd\u03c7\u03c4\u03b1", roman: "kalinihta" }, + { from: 5, text: "\u039a\u03b1\u03bb\u03b7\u03bc\u03ad\u03c1\u03b1", roman: "kalimera" }, + { from: 12, text: "\u039a\u03b1\u03bb\u03b7\u03c3\u03c0\u03ad\u03c1\u03b1", roman: "kalispera" }, + { from: 21, text: "\u039a\u03b1\u03bb\u03b7\u03bd\u03cd\u03c7\u03c4\u03b1", roman: "kalinihta" } + ] }, + ru: { name: "Russian", bands: [ + { from: 0, text: "\u0421\u043f\u043e\u043a\u043e\u0439\u043d\u043e\u0439 \u043d\u043e\u0447\u0438", roman: "spokoynoy nochi" }, + { from: 5, text: "\u0414\u043e\u0431\u0440\u043e\u0435 \u0443\u0442\u0440\u043e", roman: "dobroye utro" }, + { from: 12, text: "\u0414\u043e\u0431\u0440\u044b\u0439 \u0434\u0435\u043d\u044c", roman: "dobryy den" }, + { from: 18, text: "\u0414\u043e\u0431\u0440\u044b\u0439 \u0432\u0435\u0447\u0435\u0440", roman: "dobryy vecher" } + ] }, + uk: { name: "Ukrainian", bands: [ + { from: 0, text: "\u041d\u0430\u0434\u043e\u0431\u0440\u0430\u043d\u0456\u0447", roman: "nadobranich" }, + { from: 5, text: "\u0414\u043e\u0431\u0440\u043e\u0433\u043e \u0440\u0430\u043d\u043a\u0443", roman: "dobroho ranku" }, + { from: 12, text: "\u0414\u043e\u0431\u0440\u043e\u0433\u043e \u0434\u043d\u044f", roman: "dobroho dnya" }, + { from: 18, text: "\u0414\u043e\u0431\u0440\u043e\u0433\u043e \u0432\u0435\u0447\u043e\u0440\u0430", roman: "dobroho vechora" } + ] }, + be: { name: "Belarusian", bands: [ + { from: 0, text: "\u0414\u0430\u0431\u0440\u0430\u043d\u0430\u0447", roman: "dabranach" }, + { from: 5, text: "\u0414\u043e\u0431\u0440\u0430\u0439 \u0440\u0430\u043d\u0456\u0446\u044b", roman: "dobray ranitsy" }, + { from: 12, text: "\u0414\u043e\u0431\u0440\u044b \u0434\u0437\u0435\u043d\u044c", roman: "dobry dzen" }, + { from: 18, text: "\u0414\u043e\u0431\u0440\u044b \u0432\u0435\u0447\u0430\u0440", roman: "dobry vechar" } + ] }, + bg: { name: "Bulgarian", bands: [ + { from: 0, text: "\u041b\u0435\u043a\u0430 \u043d\u043e\u0449", roman: "leka nosht" }, + { from: 5, text: "\u0414\u043e\u0431\u0440\u043e \u0443\u0442\u0440\u043e", roman: "dobro utro" }, + { from: 12, text: "\u0414\u043e\u0431\u044a\u0440 \u0434\u0435\u043d", roman: "dobar den" }, + { from: 18, text: "\u0414\u043e\u0431\u044a\u0440 \u0432\u0435\u0447\u0435\u0440", roman: "dobar vecher" } + ] }, + sr: { name: "Serbian", bands: [ + { from: 0, text: "\u041b\u0430\u043a\u0443 \u043d\u043e\u045b", roman: "laku noc" }, + { from: 5, text: "\u0414\u043e\u0431\u0440\u043e \u0458\u0443\u0442\u0440\u043e", roman: "dobro jutro" }, + { from: 12, text: "\u0414\u043e\u0431\u0430\u0440 \u0434\u0430\u043d", roman: "dobar dan" }, + { from: 18, text: "\u0414\u043e\u0431\u0440\u043e \u0432\u0435\u0447\u0435", roman: "dobro vece" } + ] }, + mk: { name: "Macedonian", bands: [ + { from: 0, text: "\u0414\u043e\u0431\u0440\u0430 \u043d\u043e\u045c", roman: "dobra nok" }, + { from: 5, text: "\u0414\u043e\u0431\u0440\u043e \u0443\u0442\u0440\u043e", roman: "dobro utro" }, + { from: 12, text: "\u0414\u043e\u0431\u0430\u0440 \u0434\u0435\u043d", roman: "dobar den" }, + { from: 18, text: "\u0414\u043e\u0431\u0440\u043e \u0432\u0435\u0447\u0435\u0440", roman: "dobro vecher" } + ] }, + kk: { name: "Kazakh", bands: [ + { from: 0, text: "\u049a\u0430\u0439\u044b\u0440\u043b\u044b \u0442\u04af\u043d", roman: "qaiyrly tun" }, + { from: 5, text: "\u049a\u0430\u0439\u044b\u0440\u043b\u044b \u0442\u0430\u04a3", roman: "qaiyrly tang" }, + { from: 12, text: "\u049a\u0430\u0439\u044b\u0440\u043b\u044b \u043a\u04af\u043d", roman: "qaiyrly kun" }, + { from: 18, text: "\u049a\u0430\u0439\u044b\u0440\u043b\u044b \u043a\u0435\u0448", roman: "qaiyrly kesh" } + ] }, + ky: { name: "Kyrgyz", bands: [ + { from: 0, text: "\u0416\u0430\u043a\u0448\u044b \u0436\u0430\u0442\u044b\u043f \u0442\u0443\u0440\u0443\u04a3\u0443\u0437", roman: "jakshy jatyp turunguz" }, + { from: 5, text: "\u041a\u0430\u0439\u044b\u0440\u043b\u0443\u0443 \u0442\u0430\u04a3", roman: "kaiyrluu tang" }, + { from: 12, text: "\u041a\u0443\u0442\u043c\u0430\u043d\u0434\u0443\u0443 \u043a\u04af\u043d", roman: "kutmanduu kun" }, + { from: 18, text: "\u041a\u0443\u0442\u043c\u0430\u043d\u0434\u0443\u0443 \u043a\u0435\u0447", roman: "kutmanduu kech" } + ] }, + tg: { name: "Tajik", bands: [ + { from: 0, text: "\u0428\u0430\u0431 \u0431\u0430 \u0445\u0430\u0439\u0440", roman: "shab ba khayr" }, + { from: 5, text: "\u0421\u0443\u0431\u04b3 \u0431\u0430 \u0445\u0430\u0439\u0440", roman: "subh ba khayr" }, + { from: 12, text: "\u0420\u04ef\u0437 \u0431\u0430 \u0445\u0430\u0439\u0440", roman: "ruz ba khayr" }, + { from: 18, text: "\u0428\u043e\u043c \u0431\u0430 \u0445\u0430\u0439\u0440", roman: "shom ba khayr" } + ] }, + mn: { name: "Mongolian", bands: [ + { from: 0, text: "\u0421\u0430\u0439\u0445\u0430\u043d \u0430\u043c\u0440\u0430\u0430\u0440\u0430\u0439", roman: "saikhan amraarai" }, + { from: 5, text: "\u04e8\u0433\u043b\u04e9\u04e9\u043d\u0438\u0439 \u043c\u044d\u043d\u0434", roman: "ogloonii mend" }, + { from: 12, text: "\u04e8\u0434\u0440\u0438\u0439\u043d \u043c\u044d\u043d\u0434", roman: "odriin mend" }, + { from: 18, text: "\u041e\u0440\u043e\u0439\u043d \u043c\u044d\u043d\u0434", roman: "oroin mend" } + ] }, + ka: { name: "Georgian", bands: [ + { from: 0, text: "\u10e6\u10d0\u10db\u10d4 \u10db\u10e8\u10d5\u10d8\u10d3\u10dd\u10d1\u10d8\u10e1\u10d0", roman: "ghame mshvidobisa" }, + { from: 5, text: "\u10d3\u10d8\u10da\u10d0 \u10db\u10e8\u10d5\u10d8\u10d3\u10dd\u10d1\u10d8\u10e1\u10d0", roman: "dila mshvidobisa" }, + { from: 12, text: "\u10d3\u10e6\u10d4 \u10db\u10e8\u10d5\u10d8\u10d3\u10dd\u10d1\u10d8\u10e1\u10d0", roman: "dghe mshvidobisa" }, + { from: 18, text: "\u10e1\u10d0\u10e6\u10d0\u10db\u10dd \u10db\u10e8\u10d5\u10d8\u10d3\u10dd\u10d1\u10d8\u10e1\u10d0", roman: "saghamo mshvidobisa" } + ] }, + hy: { name: "Armenian", bands: [ + { from: 0, text: "\u0562\u0561\u0580\u056b \u0563\u056b\u0577\u0565\u0580", roman: "bari gisher" }, + { from: 5, text: "\u0562\u0561\u0580\u056b \u056c\u0578\u0582\u0575\u057d", roman: "bari luys" }, + { from: 12, text: "\u0562\u0561\u0580\u056b \u0585\u0580", roman: "bari or" }, + { from: 18, text: "\u0562\u0561\u0580\u056b \u0565\u0580\u0565\u056f\u0578", roman: "bari ereko" } + ] }, + he: { name: "Hebrew", bands: [ + { from: 0, text: "\u05dc\u05d9\u05dc\u05d4 \u05d8\u05d5\u05d1", roman: "laila tov" }, + { from: 5, text: "\u05d1\u05d5\u05e7\u05e8 \u05d8\u05d5\u05d1", roman: "boker tov" }, + { from: 12, text: "\u05e6\u05d4\u05e8\u05d9\u05d9\u05dd \u05d8\u05d5\u05d1\u05d9\u05dd", roman: "tzohorayim tovim" }, + { from: 17, text: "\u05e2\u05e8\u05d1 \u05d8\u05d5\u05d1", roman: "erev tov" } + ] }, + ar: { name: "Arabic", bands: [ + { from: 0, text: "\u062a\u0635\u0628\u062d \u0639\u0644\u0649 \u062e\u064a\u0631", roman: "tusbih ala khayr" }, + { from: 5, text: "\u0635\u0628\u0627\u062d \u0627\u0644\u062e\u064a\u0631", roman: "sabah al-khayr" }, + { from: 12, text: "\u0645\u0633\u0627\u0621 \u0627\u0644\u062e\u064a\u0631", roman: "masaa al-khayr" } + ] }, + fa: { name: "Persian", bands: [ + { from: 0, text: "\u0634\u0628 \u0628\u062e\u06cc\u0631", roman: "shab bekheir" }, + { from: 5, text: "\u0635\u0628\u062d \u0628\u062e\u06cc\u0631", roman: "sobh bekheir" }, + { from: 12, text: "\u0639\u0635\u0631 \u0628\u062e\u06cc\u0631", roman: "asr bekheir" }, + { from: 20, text: "\u0634\u0628 \u0628\u062e\u06cc\u0631", roman: "shab bekheir" } + ] }, + ur: { name: "Urdu", bands: [ + { from: 0, text: "\u0634\u0628 \u0628\u062e\u06cc\u0631", roman: "shab bakhair" }, + { from: 5, text: "\u0635\u0628\u062d \u0628\u062e\u06cc\u0631", roman: "subah bakhair" }, + { from: 12, text: "\u0627\u0644\u0633\u0644\u0627\u0645 \u0639\u0644\u06cc\u06a9\u0645", roman: "assalam-o-alaikum" }, + { from: 18, text: "\u0634\u0627\u0645 \u0628\u062e\u06cc\u0631", roman: "shaam bakhair" } + ] }, + prs: { name: "Dari", bands: [ + { from: 0, text: "\u0634\u0628 \u0628\u062e\u06cc\u0631", roman: "shab bakhair" }, + { from: 5, text: "\u0635\u0628\u062d \u0628\u062e\u06cc\u0631", roman: "sobh bakhair" }, + { from: 12, text: "\u0631\u0648\u0632 \u0628\u062e\u06cc\u0631", roman: "roz bakhair" }, + { from: 18, text: "\u0634\u0627\u0645 \u0628\u062e\u06cc\u0631", roman: "sham bakhair" } + ] }, + dv: { name: "Dhivehi", bands: [ + { from: 0, text: "\u0787\u07a6\u0787\u07b0\u0790\u07a6\u078d\u07a7\u0789\u07aa \u07a2\u07a6\u078d\u07a6\u0787\u07a8\u0786\u07aa\u0789\u07b0", roman: "assalaamu alaikum" } + ] }, + hi: { name: "Hindi", bands: [ + { from: 0, text: "\u0936\u0941\u092d \u0930\u093e\u0924\u094d\u0930\u093f", roman: "shubh ratri" }, + { from: 5, text: "\u0938\u0941\u092a\u094d\u0930\u092d\u093e\u0924", roman: "suprabhat" }, + { from: 12, text: "\u0928\u092e\u0938\u094d\u0924\u0947", roman: "namaste" }, + { from: 17, text: "\u0936\u0941\u092d \u0938\u0902\u0927\u094d\u092f\u093e", roman: "shubh sandhya" } + ] }, + bn: { name: "Bengali", bands: [ + { from: 0, text: "\u09b6\u09c1\u09ad \u09b0\u09be\u09a4\u09cd\u09b0\u09bf", roman: "shubho ratri" }, + { from: 5, text: "\u09b8\u09c1\u09aa\u09cd\u09b0\u09ad\u09be\u09a4", roman: "suprobhat" }, + { from: 12, text: "\u09a8\u09ae\u09b8\u09cd\u0995\u09be\u09b0", roman: "nomoshkar" }, + { from: 17, text: "\u09b6\u09c1\u09ad \u09b8\u09a8\u09cd\u09a7\u09cd\u09af\u09be", roman: "shubho shondha" } + ] }, + ne: { name: "Nepali", bands: [ + { from: 0, text: "\u0936\u0941\u092d \u0930\u093e\u0924\u094d\u0930\u0940", roman: "shubha ratri" }, + { from: 5, text: "\u0936\u0941\u092d \u092a\u094d\u0930\u092d\u093e\u0924", roman: "shubha prabhat" }, + { from: 12, text: "\u0928\u092e\u0938\u094d\u0924\u0947", roman: "namaste" }, + { from: 17, text: "\u0936\u0941\u092d \u0938\u0928\u094d\u0927\u094d\u092f\u093e", roman: "shubha sandhya" } + ] }, + si: { name: "Sinhala", bands: [ + { from: 0, text: "\u0dc3\u0dd4\u0db6 \u0dbb\u0dcf\u0dad\u0dca\u200d\u0dbb\u0dd2\u0dba\u0d9a\u0dca", roman: "suba rathriyak" }, + { from: 5, text: "\u0dc3\u0dd4\u0db6 \u0d8b\u0daf\u0dd1\u0dc3\u0db1\u0d9a\u0dca", roman: "suba udaesanak" }, + { from: 12, text: "\u0dc3\u0dd4\u0db6 \u0daf\u0dc0\u0dc3\u0d9a\u0dca", roman: "suba dawasak" }, + { from: 18, text: "\u0dc3\u0dd4\u0db6 \u0dc3\u0db1\u0dca\u0db0\u0dca\u200d\u0dba\u0dcf\u0dc0\u0d9a\u0dca", roman: "suba sandhyawak" } + ] }, + ta: { name: "Tamil", bands: [ + { from: 0, text: "\u0b87\u0bb0\u0bb5\u0bc1 \u0bb5\u0ba3\u0b95\u0bcd\u0b95\u0bae\u0bcd", roman: "iravu vanakkam" }, + { from: 5, text: "\u0b95\u0bbe\u0bb2\u0bc8 \u0bb5\u0ba3\u0b95\u0bcd\u0b95\u0bae\u0bcd", roman: "kaalai vanakkam" }, + { from: 12, text: "\u0bae\u0ba4\u0bbf\u0baf \u0bb5\u0ba3\u0b95\u0bcd\u0b95\u0bae\u0bcd", roman: "madhiya vanakkam" }, + { from: 17, text: "\u0bae\u0bbe\u0bb2\u0bc8 \u0bb5\u0ba3\u0b95\u0bcd\u0b95\u0bae\u0bcd", roman: "maalai vanakkam" } + ] }, + dz: { name: "Dzongkha", bands: [ + { from: 0, text: "\u0f40\u0f74\u0f0b\u0f5f\u0f74\u0f0b\u0f5f\u0f44\u0f0b\u0f54\u0f7c\u0f0b\u0f63\u0f42\u0f66", roman: "kuzuzangpo la" } + ] }, + my: { name: "Burmese", bands: [ + { from: 0, text: "\u1019\u1004\u103a\u1039\u1002\u101c\u102c\u1015\u102b", roman: "mingalaba" } + ] }, + th: { name: "Thai", bands: [ + { from: 0, text: "\u0e23\u0e32\u0e15\u0e23\u0e35\u0e2a\u0e27\u0e31\u0e2a\u0e14\u0e34\u0e4c", roman: "ratri sawat" }, + { from: 5, text: "\u0e2d\u0e23\u0e38\u0e13\u0e2a\u0e27\u0e31\u0e2a\u0e14\u0e34\u0e4c", roman: "arun sawat" }, + { from: 12, text: "\u0e2a\u0e27\u0e31\u0e2a\u0e14\u0e35", roman: "sawatdee" } + ] }, + lo: { name: "Lao", bands: [ + { from: 0, text: "\u0eaa\u0eb0\u0e9a\u0eb2\u0e8d\u0e94\u0eb5", roman: "sabaidee" } + ] }, + km: { name: "Khmer", bands: [ + { from: 0, text: "\u179a\u17b6\u178f\u17d2\u179a\u17b8\u179f\u17bd\u179f\u17d2\u178f\u17b8", roman: "reatrei suostei" }, + { from: 5, text: "\u17a2\u179a\u17bb\u178e\u179f\u17bd\u179f\u17d2\u178f\u17b8", roman: "arun suostei" }, + { from: 12, text: "\u1791\u17b7\u179c\u17b6\u179f\u17bd\u179f\u17d2\u178f\u17b8", roman: "tivea suostei" }, + { from: 18, text: "\u179f\u17b6\u1799\u17d0\u178e\u17d2\u17a0\u179f\u17bd\u179f\u17d2\u178f\u17b8", roman: "sayoanh suostei" } + ] }, + zh: { name: "Mandarin", bands: [ + { from: 0, text: "\u665a\u5b89", roman: "wan an" }, + { from: 5, text: "\u65e9\u4e0a\u597d", roman: "zaoshang hao" }, + { from: 11, text: "\u4e2d\u5348\u597d", roman: "zhongwu hao" }, + { from: 14, text: "\u4e0b\u5348\u597d", roman: "xiawu hao" }, + { from: 18, text: "\u665a\u4e0a\u597d", roman: "wanshang hao" } + ] }, + yue: { name: "Cantonese", bands: [ + { from: 0, text: "\u65e9\u551e", roman: "jou tau" }, + { from: 5, text: "\u65e9\u6668", roman: "jou san" }, + { from: 12, text: "\u5348\u5b89", roman: "ng on" }, + { from: 18, text: "\u665a\u5b89", roman: "maan on" } + ] }, + ko: { name: "Korean", bands: [ + { from: 0, text: "\uc548\ub155\ud788 \uc8fc\ubb34\uc138\uc694", roman: "annyeonghi jumuseyo" }, + { from: 5, text: "\uc88b\uc740 \uc544\uce68", roman: "joeun achim" }, + { from: 11, text: "\uc548\ub155\ud558\uc138\uc694", roman: "annyeonghaseyo" }, + { from: 18, text: "\uc88b\uc740 \uc800\ub141", roman: "joeun jeonyeok" } + ] }, + ja: { name: "Japanese", bands: [ + { from: 0, text: "\u304a\u3084\u3059\u307f", roman: "oyasumi" }, + { from: 5, text: "\u304a\u306f\u3088\u3046", roman: "ohayo" }, + { from: 11, text: "\u3053\u3093\u306b\u3061\u306f", roman: "konnichiwa" }, + { from: 18, text: "\u3053\u3093\u3070\u3093\u306f", roman: "konbanwa" } + ] }, + am: { name: "Amharic", bands: [ + { from: 0, text: "\u12f0\u1205\u1293 \u12a5\u12f0\u1229", roman: "dehna ederu" }, + { from: 5, text: "\u12a5\u1295\u12f0\u121d\u1295 \u12a0\u12f0\u1229", roman: "endemin aderu" }, + { from: 12, text: "\u12a5\u1295\u12f0\u121d\u1295 \u12cb\u1209", roman: "endemin walu" }, + { from: 18, text: "\u12a5\u1295\u12f0\u121d\u1295 \u12a0\u1218\u1239", roman: "endemin ameshu" } + ] }, + ti: { name: "Tigrinya", bands: [ + { from: 0, text: "\u1230\u120b\u121d", roman: "selam" } + ] }, + az: { name: "Azerbaijani", bands: [ + { from: 0, text: "Gec\u0259niz xeyr\u0259 qals\u0131n", roman: "" }, + { from: 5, text: "Sabah\u0131n\u0131z xeyir", roman: "" }, + { from: 12, text: "G\u00fcnortan\u0131z xeyir", roman: "" }, + { from: 18, text: "Ax\u015fam\u0131n\u0131z xeyir", roman: "" } + ] }, + uz: { name: "Uzbek", bands: [ + { from: 0, text: "Xayrli tun", roman: "" }, + { from: 5, text: "Xayrli tong", roman: "" }, + { from: 12, text: "Xayrli kun", roman: "" }, + { from: 18, text: "Xayrli kech", roman: "" } + ] }, + tk: { name: "Turkmen", bands: [ + { from: 0, text: "Gij\u00e4\u0148iz rahat", roman: "" }, + { from: 5, text: "Ertiri\u0148iz ha\u00fdyrly", roman: "" }, + { from: 12, text: "Salam", roman: "" }, + { from: 18, text: "Ag\u015famy\u0148yz ha\u00fdyrly", roman: "" } + ] } +} + +var COUNTRIES = { + "AD": "ca", "AE": "ar", "AF": "prs", "AG": "en", "AI": "en", "AL": "sq", + "AM": "hy", "AO": "pt", "AQ": "en", "AR": "es", "AS": "sm", "AT": "deAT", + "AU": "enAU", "AW": "pap", "AX": "sv", "AZ": "az", "BA": "bs", "BB": "en", + "BD": "bn", "BE": "fr", "BF": "fr", "BG": "bg", "BH": "ar", "BI": "fr", + "BJ": "fr", "BL": "fr", "BM": "en", "BN": "ms", "BO": "es", "BQ": "pap", + "BR": "pt", "BS": "en", "BT": "dz", "BW": "en", "BY": "be", "BZ": "en", + "CA": "en", "CC": "en", "CD": "fr", "CF": "fr", "CG": "fr", "CH": "deCH", + "CI": "fr", "CK": "rar", "CL": "es", "CM": "fr", "CN": "zh", "CO": "es", + "CR": "es", "CU": "es", "CV": "pt", "CW": "pap", "CX": "en", "CY": "el", + "CZ": "cs", "DE": "de", "DJ": "fr", "DK": "da", "DM": "en", "DO": "es", + "DZ": "ar", "EC": "es", "EE": "et", "EG": "ar", "EH": "ar", "ER": "ti", + "ES": "esES", "ET": "am", "FI": "fi", "FJ": "fj", "FK": "en", "FM": "en", + "FO": "fo", "FR": "fr", "GA": "fr", "GB": "en", "GD": "en", "GE": "ka", + "GF": "fr", "GG": "en", "GH": "tw", "GI": "en", "GL": "kl", "GM": "en", + "GN": "fr", "GP": "fr", "GQ": "es", "GR": "el", "GS": "en", "GT": "es", + "GU": "ch", "GW": "pt", "GY": "en", "HK": "yue", "HN": "es", "HR": "hr", + "HT": "ht", "HU": "hu", "ID": "id", "IE": "ga", "IL": "he", "IM": "en", + "IN": "hi", "IO": "en", "IQ": "ar", "IR": "fa", "IS": "is", "IT": "it", + "JE": "en", "JM": "en", "JO": "ar", "JP": "ja", "KE": "sw", "KG": "ky", + "KH": "km", "KI": "gil", "KM": "fr", "KN": "en", "KP": "ko", "KR": "ko", + "KW": "ar", "KY": "en", "KZ": "kk", "LA": "lo", "LB": "ar", "LC": "en", + "LI": "deCH", "LK": "si", "LR": "en", "LS": "st", "LT": "lt", "LU": "lb", + "LV": "lv", "LY": "ar", "MA": "ar", "MC": "fr", "MD": "ro", "ME": "hr", + "MF": "fr", "MG": "mg", "MH": "mh", "MK": "mk", "ML": "fr", "MM": "my", + "MN": "mn", "MO": "yue", "MP": "ch", "MQ": "fr", "MR": "ar", "MS": "en", + "MT": "mt", "MU": "fr", "MV": "dv", "MW": "ny", "MX": "es", "MY": "ms", + "MZ": "pt", "NA": "af", "NC": "fr", "NE": "fr", "NF": "en", "NG": "yo", + "NI": "es", "NL": "nl", "NO": "no", "NP": "ne", "NR": "en", "NU": "niu", + "NZ": "mi", "OM": "ar", "PA": "es", "PE": "es", "PF": "ty", "PG": "tpi", + "PH": "tl", "PK": "ur", "PL": "pl", "PM": "fr", "PN": "en", "PR": "es", + "PS": "ar", "PT": "pt", "PW": "pau", "PY": "gn", "QA": "ar", "RE": "fr", + "RO": "ro", "RS": "sr", "RU": "ru", "RW": "rw", "SA": "ar", "SB": "bi", + "SC": "fr", "SD": "ar", "SE": "sv", "SG": "ms", "SH": "en", "SI": "sl", + "SJ": "no", "SK": "sk", "SL": "en", "SM": "it", "SN": "wo", "SO": "so", + "SR": "nl", "SS": "en", "ST": "pt", "SV": "es", "SX": "nl", "SY": "ar", + "SZ": "ss", "TC": "en", "TD": "fr", "TF": "fr", "TG": "fr", "TH": "th", + "TJ": "tg", "TK": "tkl", "TL": "pt", "TM": "tk", "TN": "ar", "TO": "to", + "TR": "tr", "TT": "en", "TV": "tvl", "TW": "zh", "TZ": "sw", "UA": "uk", + "UG": "lg", "UM": "en", "US": "en", "UY": "es", "UZ": "uz", "VA": "it", + "VC": "en", "VE": "es", "VG": "en", "VI": "en", "VN": "vi", "VU": "bi", + "WF": "fr", "WS": "sm", "YE": "ar", "YT": "fr", "ZA": "af", "ZM": "en", + "ZW": "sn" +} + +// Cities whose own language is not their country's. +var OVERRIDES = { + "America/Montreal": "fr", + "Asia/Kolkata": "hi", + "Pacific/Honolulu": "haw" +} + +// Legacy aliases that matching compiled zoneinfo put in the wrong country. +// Europe/Simferopol stays UA in ZONE_COUNTRY by choice. +var ALIAS_COUNTRY = { + "Africa/Asmera": "ER", // Asmara, Eritrea + "Africa/Timbuktu": "ML", // Timbuktu, Mali + "America/Montreal": "CA", + "America/Nipigon": "CA", + "America/Thunder_Bay": "CA", + "America/Virgin": "VI", // the US Virgin Islands + "Asia/Rangoon": "MM", // Yangon, Myanmar + "Canada/Eastern": "CA", + "EST": "US", // a North American offset, not a place + "Iceland": "IS", + "MST": "US", + "NZ": "NZ", + "Pacific/Truk": "FM", // Chuuk, Micronesia + "Pacific/Yap": "FM", // Yap, Micronesia + "Singapore": "SG", + "US/Arizona": "US" +} + +// Every zone the picker can offer, baked from the system's zone.tab. +var ZONE_COUNTRY = { + "Africa/Abidjan": "CI", "Africa/Accra": "GH", "Africa/Addis_Ababa": "ET", + "Africa/Algiers": "DZ", "Africa/Asmara": "ER", "Africa/Asmera": "DJ", + "Africa/Bamako": "ML", "Africa/Bangui": "CF", "Africa/Banjul": "GM", + "Africa/Bissau": "GW", "Africa/Blantyre": "MW", + "Africa/Brazzaville": "CG", "Africa/Bujumbura": "BI", + "Africa/Cairo": "EG", "Africa/Casablanca": "MA", "Africa/Ceuta": "ES", + "Africa/Conakry": "GN", "Africa/Dakar": "SN", + "Africa/Dar_es_Salaam": "TZ", "Africa/Djibouti": "DJ", + "Africa/Douala": "CM", "Africa/El_Aaiun": "EH", "Africa/Freetown": "SL", + "Africa/Gaborone": "BW", "Africa/Harare": "ZW", + "Africa/Johannesburg": "ZA", "Africa/Juba": "SS", "Africa/Kampala": "UG", + "Africa/Khartoum": "SD", "Africa/Kigali": "RW", "Africa/Kinshasa": "CD", + "Africa/Lagos": "NG", "Africa/Libreville": "GA", "Africa/Lome": "TG", + "Africa/Luanda": "AO", "Africa/Lubumbashi": "CD", "Africa/Lusaka": "ZM", + "Africa/Malabo": "GQ", "Africa/Maputo": "MZ", "Africa/Maseru": "LS", + "Africa/Mbabane": "SZ", "Africa/Mogadishu": "SO", "Africa/Monrovia": "LR", + "Africa/Nairobi": "KE", "Africa/Ndjamena": "TD", "Africa/Niamey": "NE", + "Africa/Nouakchott": "MR", "Africa/Ouagadougou": "BF", + "Africa/Porto-Novo": "BJ", "Africa/Sao_Tome": "ST", + "Africa/Timbuktu": "BF", "Africa/Tripoli": "LY", "Africa/Tunis": "TN", + "Africa/Windhoek": "NA", "America/Adak": "US", "America/Anchorage": "US", + "America/Anguilla": "AI", "America/Antigua": "AG", + "America/Araguaina": "BR", "America/Argentina/Buenos_Aires": "AR", + "America/Argentina/Catamarca": "AR", + "America/Argentina/ComodRivadavia": "AR", + "America/Argentina/Cordoba": "AR", "America/Argentina/Jujuy": "AR", + "America/Argentina/La_Rioja": "AR", "America/Argentina/Mendoza": "AR", + "America/Argentina/Rio_Gallegos": "AR", "America/Argentina/Salta": "AR", + "America/Argentina/San_Juan": "AR", "America/Argentina/San_Luis": "AR", + "America/Argentina/Tucuman": "AR", "America/Argentina/Ushuaia": "AR", + "America/Aruba": "AW", "America/Asuncion": "PY", "America/Atikokan": "CA", + "America/Atka": "US", "America/Bahia": "BR", + "America/Bahia_Banderas": "MX", "America/Barbados": "BB", + "America/Belem": "BR", "America/Belize": "BZ", + "America/Blanc-Sablon": "CA", "America/Boa_Vista": "BR", + "America/Bogota": "CO", "America/Boise": "US", + "America/Buenos_Aires": "AR", "America/Cambridge_Bay": "CA", + "America/Campo_Grande": "BR", "America/Cancun": "MX", + "America/Caracas": "VE", "America/Catamarca": "AR", + "America/Cayenne": "GF", "America/Cayman": "KY", "America/Chicago": "US", + "America/Chihuahua": "MX", "America/Ciudad_Juarez": "MX", + "America/Coral_Harbour": "CA", "America/Cordoba": "AR", + "America/Costa_Rica": "CR", "America/Coyhaique": "CL", + "America/Creston": "CA", "America/Cuiaba": "BR", "America/Curacao": "CW", + "America/Danmarkshavn": "GL", "America/Dawson": "CA", + "America/Dawson_Creek": "CA", "America/Denver": "US", + "America/Detroit": "US", "America/Dominica": "DM", + "America/Edmonton": "CA", "America/Eirunepe": "BR", + "America/El_Salvador": "SV", "America/Ensenada": "MX", + "America/Fort_Nelson": "CA", "America/Fort_Wayne": "US", + "America/Fortaleza": "BR", "America/Glace_Bay": "CA", + "America/Godthab": "GL", "America/Goose_Bay": "CA", + "America/Grand_Turk": "TC", "America/Grenada": "GD", + "America/Guadeloupe": "GP", "America/Guatemala": "GT", + "America/Guayaquil": "EC", "America/Guyana": "GY", + "America/Halifax": "CA", "America/Havana": "CU", + "America/Hermosillo": "MX", "America/Indiana/Indianapolis": "US", + "America/Indiana/Knox": "US", "America/Indiana/Marengo": "US", + "America/Indiana/Petersburg": "US", "America/Indiana/Tell_City": "US", + "America/Indiana/Vevay": "US", "America/Indiana/Vincennes": "US", + "America/Indiana/Winamac": "US", "America/Indianapolis": "US", + "America/Inuvik": "CA", "America/Iqaluit": "CA", "America/Jamaica": "JM", + "America/Jujuy": "AR", "America/Juneau": "US", + "America/Kentucky/Louisville": "US", "America/Kentucky/Monticello": "US", + "America/Knox_IN": "US", "America/Kralendijk": "BQ", + "America/La_Paz": "BO", "America/Lima": "PE", "America/Los_Angeles": "US", + "America/Louisville": "US", "America/Lower_Princes": "SX", + "America/Maceio": "BR", "America/Managua": "NI", "America/Manaus": "BR", + "America/Marigot": "MF", "America/Martinique": "MQ", + "America/Matamoros": "MX", "America/Mazatlan": "MX", + "America/Mendoza": "AR", "America/Menominee": "US", + "America/Merida": "MX", "America/Metlakatla": "US", + "America/Mexico_City": "MX", "America/Miquelon": "PM", + "America/Moncton": "CA", "America/Monterrey": "MX", + "America/Montevideo": "UY", "America/Montreal": "BS", + "America/Montserrat": "MS", "America/Nassau": "BS", + "America/New_York": "US", "America/Nipigon": "BS", "America/Nome": "US", + "America/Noronha": "BR", "America/North_Dakota/Beulah": "US", + "America/North_Dakota/Center": "US", + "America/North_Dakota/New_Salem": "US", "America/Nuuk": "GL", + "America/Ojinaga": "MX", "America/Panama": "PA", + "America/Pangnirtung": "CA", "America/Paramaribo": "SR", + "America/Phoenix": "US", "America/Port-au-Prince": "HT", + "America/Port_of_Spain": "TT", "America/Porto_Acre": "BR", + "America/Porto_Velho": "BR", "America/Puerto_Rico": "PR", + "America/Punta_Arenas": "CL", "America/Rainy_River": "CA", + "America/Rankin_Inlet": "CA", "America/Recife": "BR", + "America/Regina": "CA", "America/Resolute": "CA", + "America/Rio_Branco": "BR", "America/Rosario": "AR", + "America/Santa_Isabel": "MX", "America/Santarem": "BR", + "America/Santiago": "CL", "America/Santo_Domingo": "DO", + "America/Sao_Paulo": "BR", "America/Scoresbysund": "GL", + "America/Shiprock": "US", "America/Sitka": "US", + "America/St_Barthelemy": "BL", "America/St_Johns": "CA", + "America/St_Kitts": "KN", "America/St_Lucia": "LC", + "America/St_Thomas": "VI", "America/St_Vincent": "VC", + "America/Swift_Current": "CA", "America/Tegucigalpa": "HN", + "America/Thule": "GL", "America/Thunder_Bay": "BS", + "America/Tijuana": "MX", "America/Toronto": "CA", "America/Tortola": "VG", + "America/Vancouver": "CA", "America/Virgin": "AG", + "America/Whitehorse": "CA", "America/Winnipeg": "CA", + "America/Yakutat": "US", "America/Yellowknife": "CA", + "Antarctica/Casey": "AQ", "Antarctica/Davis": "AQ", + "Antarctica/DumontDUrville": "AQ", "Antarctica/Macquarie": "AU", + "Antarctica/Mawson": "AQ", "Antarctica/McMurdo": "AQ", + "Antarctica/Palmer": "AQ", "Antarctica/Rothera": "AQ", + "Antarctica/South_Pole": "AQ", "Antarctica/Syowa": "AQ", + "Antarctica/Troll": "AQ", "Antarctica/Vostok": "AQ", + "Arctic/Longyearbyen": "SJ", "Asia/Aden": "YE", "Asia/Almaty": "KZ", + "Asia/Amman": "JO", "Asia/Anadyr": "RU", "Asia/Aqtau": "KZ", + "Asia/Aqtobe": "KZ", "Asia/Ashgabat": "TM", "Asia/Ashkhabad": "TM", + "Asia/Atyrau": "KZ", "Asia/Baghdad": "IQ", "Asia/Bahrain": "BH", + "Asia/Baku": "AZ", "Asia/Bangkok": "TH", "Asia/Barnaul": "RU", + "Asia/Beirut": "LB", "Asia/Bishkek": "KG", "Asia/Brunei": "BN", + "Asia/Calcutta": "IN", "Asia/Chita": "RU", "Asia/Choibalsan": "MN", + "Asia/Chongqing": "CN", "Asia/Chungking": "CN", "Asia/Colombo": "LK", + "Asia/Dacca": "BD", "Asia/Damascus": "SY", "Asia/Dhaka": "BD", + "Asia/Dili": "TL", "Asia/Dubai": "AE", "Asia/Dushanbe": "TJ", + "Asia/Famagusta": "CY", "Asia/Gaza": "PS", "Asia/Harbin": "CN", + "Asia/Hebron": "PS", "Asia/Ho_Chi_Minh": "VN", "Asia/Hong_Kong": "HK", + "Asia/Hovd": "MN", "Asia/Irkutsk": "RU", "Asia/Istanbul": "TR", + "Asia/Jakarta": "ID", "Asia/Jayapura": "ID", "Asia/Jerusalem": "IL", + "Asia/Kabul": "AF", "Asia/Kamchatka": "RU", "Asia/Karachi": "PK", + "Asia/Kashgar": "CN", "Asia/Kathmandu": "NP", "Asia/Katmandu": "NP", + "Asia/Khandyga": "RU", "Asia/Kolkata": "IN", "Asia/Krasnoyarsk": "RU", + "Asia/Kuala_Lumpur": "MY", "Asia/Kuching": "MY", "Asia/Kuwait": "KW", + "Asia/Macao": "MO", "Asia/Macau": "MO", "Asia/Magadan": "RU", + "Asia/Makassar": "ID", "Asia/Manila": "PH", "Asia/Muscat": "OM", + "Asia/Nicosia": "CY", "Asia/Novokuznetsk": "RU", "Asia/Novosibirsk": "RU", + "Asia/Omsk": "RU", "Asia/Oral": "KZ", "Asia/Phnom_Penh": "KH", + "Asia/Pontianak": "ID", "Asia/Pyongyang": "KP", "Asia/Qatar": "QA", + "Asia/Qostanay": "KZ", "Asia/Qyzylorda": "KZ", "Asia/Rangoon": "CC", + "Asia/Riyadh": "SA", "Asia/Saigon": "VN", "Asia/Sakhalin": "RU", + "Asia/Samarkand": "UZ", "Asia/Seoul": "KR", "Asia/Shanghai": "CN", + "Asia/Singapore": "SG", "Asia/Srednekolymsk": "RU", "Asia/Taipei": "TW", + "Asia/Tashkent": "UZ", "Asia/Tbilisi": "GE", "Asia/Tehran": "IR", + "Asia/Tel_Aviv": "IL", "Asia/Thimbu": "BT", "Asia/Thimphu": "BT", + "Asia/Tokyo": "JP", "Asia/Tomsk": "RU", "Asia/Ujung_Pandang": "ID", + "Asia/Ulaanbaatar": "MN", "Asia/Ulan_Bator": "MN", "Asia/Urumqi": "CN", + "Asia/Ust-Nera": "RU", "Asia/Vientiane": "LA", "Asia/Vladivostok": "RU", + "Asia/Yakutsk": "RU", "Asia/Yangon": "MM", "Asia/Yekaterinburg": "RU", + "Asia/Yerevan": "AM", "Atlantic/Azores": "PT", "Atlantic/Bermuda": "BM", + "Atlantic/Canary": "ES", "Atlantic/Cape_Verde": "CV", + "Atlantic/Faeroe": "FO", "Atlantic/Faroe": "FO", + "Atlantic/Jan_Mayen": "DE", "Atlantic/Madeira": "PT", + "Atlantic/Reykjavik": "IS", "Atlantic/South_Georgia": "GS", + "Atlantic/St_Helena": "SH", "Atlantic/Stanley": "FK", + "Australia/ACT": "AU", "Australia/Adelaide": "AU", + "Australia/Brisbane": "AU", "Australia/Broken_Hill": "AU", + "Australia/Canberra": "AU", "Australia/Currie": "AU", + "Australia/Darwin": "AU", "Australia/Eucla": "AU", + "Australia/Hobart": "AU", "Australia/LHI": "AU", + "Australia/Lindeman": "AU", "Australia/Lord_Howe": "AU", + "Australia/Melbourne": "AU", "Australia/NSW": "AU", + "Australia/North": "AU", "Australia/Perth": "AU", + "Australia/Queensland": "AU", "Australia/South": "AU", + "Australia/Sydney": "AU", "Australia/Tasmania": "AU", + "Australia/Victoria": "AU", "Australia/West": "AU", + "Australia/Yancowinna": "AU", "Brazil/Acre": "BR", + "Brazil/DeNoronha": "BR", "Brazil/East": "BR", "Brazil/West": "BR", + "CET": "BE", "CST6CDT": "US", "Canada/Atlantic": "CA", + "Canada/Central": "CA", "Canada/Eastern": "BS", "Canada/Mountain": "CA", + "Canada/Newfoundland": "CA", "Canada/Pacific": "CA", + "Canada/Saskatchewan": "CA", "Canada/Yukon": "CA", + "Chile/Continental": "CL", "Chile/EasterIsland": "CL", "Cuba": "CU", + "EET": "GR", "EST": "CA", "EST5EDT": "US", "Egypt": "EG", "Eire": "IE", + "Europe/Amsterdam": "NL", "Europe/Andorra": "AD", + "Europe/Astrakhan": "RU", "Europe/Athens": "GR", "Europe/Belfast": "GB", + "Europe/Belgrade": "RS", "Europe/Berlin": "DE", "Europe/Bratislava": "SK", + "Europe/Brussels": "BE", "Europe/Bucharest": "RO", + "Europe/Budapest": "HU", "Europe/Busingen": "DE", "Europe/Chisinau": "MD", + "Europe/Copenhagen": "DK", "Europe/Dublin": "IE", + "Europe/Gibraltar": "GI", "Europe/Guernsey": "GG", + "Europe/Helsinki": "FI", "Europe/Isle_of_Man": "IM", + "Europe/Istanbul": "TR", "Europe/Jersey": "JE", + "Europe/Kaliningrad": "RU", "Europe/Kiev": "UA", "Europe/Kirov": "RU", + "Europe/Kyiv": "UA", "Europe/Lisbon": "PT", "Europe/Ljubljana": "SI", + "Europe/London": "GB", "Europe/Luxembourg": "LU", "Europe/Madrid": "ES", + "Europe/Malta": "MT", "Europe/Mariehamn": "AX", "Europe/Minsk": "BY", + "Europe/Monaco": "MC", "Europe/Moscow": "RU", "Europe/Nicosia": "CY", + "Europe/Oslo": "NO", "Europe/Paris": "FR", "Europe/Podgorica": "ME", + "Europe/Prague": "CZ", "Europe/Riga": "LV", "Europe/Rome": "IT", + "Europe/Samara": "RU", "Europe/San_Marino": "SM", "Europe/Sarajevo": "BA", + "Europe/Saratov": "RU", "Europe/Simferopol": "UA", "Europe/Skopje": "MK", + "Europe/Sofia": "BG", "Europe/Stockholm": "SE", "Europe/Tallinn": "EE", + "Europe/Tirane": "AL", "Europe/Tiraspol": "MD", "Europe/Ulyanovsk": "RU", + "Europe/Uzhgorod": "UA", "Europe/Vaduz": "LI", "Europe/Vatican": "VA", + "Europe/Vienna": "AT", "Europe/Vilnius": "LT", "Europe/Volgograd": "RU", + "Europe/Warsaw": "PL", "Europe/Zagreb": "HR", "Europe/Zaporozhye": "UA", + "Europe/Zurich": "CH", "GB": "GB", "GB-Eire": "GB", "HST": "US", + "Hongkong": "HK", "Iceland": "BF", "Indian/Antananarivo": "MG", + "Indian/Chagos": "IO", "Indian/Christmas": "CX", "Indian/Cocos": "CC", + "Indian/Comoro": "KM", "Indian/Kerguelen": "TF", "Indian/Mahe": "SC", + "Indian/Maldives": "MV", "Indian/Mauritius": "MU", "Indian/Mayotte": "YT", + "Indian/Reunion": "RE", "Iran": "IR", "Israel": "IL", "Jamaica": "JM", + "Japan": "JP", "Kwajalein": "MH", "Libya": "LY", "MET": "BE", "MST": "CA", + "MST7MDT": "US", "Mexico/BajaNorte": "MX", "Mexico/BajaSur": "MX", + "Mexico/General": "MX", "NZ": "AQ", "NZ-CHAT": "NZ", "Navajo": "US", + "PRC": "CN", "PST8PDT": "US", "Pacific/Apia": "WS", + "Pacific/Auckland": "NZ", "Pacific/Bougainville": "PG", + "Pacific/Chatham": "NZ", "Pacific/Chuuk": "FM", "Pacific/Easter": "CL", + "Pacific/Efate": "VU", "Pacific/Enderbury": "KI", "Pacific/Fakaofo": "TK", + "Pacific/Fiji": "FJ", "Pacific/Funafuti": "TV", "Pacific/Galapagos": "EC", + "Pacific/Gambier": "PF", "Pacific/Guadalcanal": "SB", + "Pacific/Guam": "GU", "Pacific/Honolulu": "US", "Pacific/Johnston": "US", + "Pacific/Kanton": "KI", "Pacific/Kiritimati": "KI", + "Pacific/Kosrae": "FM", "Pacific/Kwajalein": "MH", "Pacific/Majuro": "MH", + "Pacific/Marquesas": "PF", "Pacific/Midway": "UM", "Pacific/Nauru": "NR", + "Pacific/Niue": "NU", "Pacific/Norfolk": "NF", "Pacific/Noumea": "NC", + "Pacific/Pago_Pago": "AS", "Pacific/Palau": "PW", + "Pacific/Pitcairn": "PN", "Pacific/Pohnpei": "FM", "Pacific/Ponape": "FM", + "Pacific/Port_Moresby": "PG", "Pacific/Rarotonga": "CK", + "Pacific/Saipan": "MP", "Pacific/Samoa": "AS", "Pacific/Tahiti": "PF", + "Pacific/Tarawa": "KI", "Pacific/Tongatapu": "TO", "Pacific/Truk": "AQ", + "Pacific/Wake": "UM", "Pacific/Wallis": "WF", "Pacific/Yap": "AQ", + "Poland": "PL", "Portugal": "PT", "ROC": "TW", "ROK": "KR", + "Singapore": "MY", "Turkey": "TR", "US/Alaska": "US", "US/Aleutian": "US", + "US/Arizona": "CA", "US/Central": "US", "US/East-Indiana": "US", + "US/Eastern": "US", "US/Hawaii": "US", "US/Indiana-Starke": "US", + "US/Michigan": "US", "US/Mountain": "US", "US/Pacific": "US", + "US/Samoa": "AS", "W-SU": "RU", "WET": "PT" +} + +var FALLBACK = "en" + +// Offset-only zones such as Etc/GMT+5 have no country and get the fallback. +function languageFor(zoneId) { + var id = String(zoneId) + if (OVERRIDES[id] && LANGUAGES[OVERRIDES[id]]) return OVERRIDES[id] + // countryFor, not ZONE_COUNTRY, so the alias corrections apply. + var key = COUNTRIES[countryFor(id)] + return (key && LANGUAGES[key]) ? key : FALLBACK +} + +// { text, roman, language, key } for a zone at a local hour. +function greeting(zoneId, hour) { + var key = languageFor(zoneId) + var bands = LANGUAGES[key].bands + var h = Math.max(0, Math.min(23, Math.floor(Number(hour)))) + if (!isFinite(h)) h = 0 + var band = bands[0] + for (var i = 1; i < bands.length; i++) { + if (bands[i].from > h) break + band = bands[i] + } + return { text: band.text, roman: band.roman, language: LANGUAGES[key].name, key: key } +} + +function languageKeys() { + var out = [] + for (var key in LANGUAGES) out.push(key) + return out +} + +function zoneIds() { + var out = [] + for (var id in ZONE_COUNTRY) out.push(id) + return out +} + +// "" for the offset-only zones. +function countryFor(zoneId) { + var id = String(zoneId) + return ALIAS_COUNTRY[id] || ZONE_COUNTRY[id] || "" +} + +function countryCodes() { + var out = [] + for (var code in COUNTRIES) out.push(code) + return out +} + +function bandsOf(key) { return LANGUAGES[key].bands } + +if (typeof module !== "undefined") { + module.exports = { + greeting: greeting, + languageFor: languageFor, + countryFor: countryFor, + languageKeys: languageKeys, + zoneIds: zoneIds, + countryCodes: countryCodes, + bandsOf: bandsOf + } +} diff --git a/shell/plugins/panels/elsewhen/HeroTitle.qml b/shell/plugins/panels/elsewhen/HeroTitle.qml new file mode 100644 index 000000000000..9629408f32e2 --- /dev/null +++ b/shell/plugins/panels/elsewhen/HeroTitle.qml @@ -0,0 +1,164 @@ +import QtQuick +import qs.Commons +import "GlobeModel.js" as Solar + +// "World [globe] Clock" under an arched caption. The little globe is the door +// into globe mode and, once the big globe has left it, the cross back out. +Column { + id: hero + + property string caption: "" + property color captionColor: dim + property bool captionClickable: false + property color foreground: Color.foreground + property color dim: Qt.darker(foreground, 1.55) + property string fontFamily: Style.font.family + + // 0 is the list, 1 is the globe filling the panel. + property real zoom: 0 + property bool globeEnabled: true + property real bigGlobeOpacity: 0 + + // Where the little globe rests, and the city it marks. + property real restLon: 0 + property bool markerShown: false + property real markerLat: 0 + property real markerLon: 0 + + readonly property Item icon: heroIcon + readonly property bool iconHovered: heroMouse.containsMouse + readonly property real spin: heroIcon.spin + + signal captionClicked() + signal globeClicked(bool slow) + + // Three turns that land on `lon`; null replays the last endpoints. + function spinOpening(lon) { + globeSpin.stop() + if (lon !== null) { + globeSpin.from = lon - 1080 + globeSpin.to = lon + } + globeSpin.restart() + } + + // `from` is passed in: once the focus changes, the rest binding has already moved spin. + function turn(from, lon) { + globeSpin.stop() + focusSpin.from = from + focusSpin.to = from + Solar.shortestTurn(from, lon) + focusSpin.restart() + } + + spacing: Style.space(2) + + ArcText { + width: parent.width + text: hero.caption + rise: Style.space(6) + color: hero.captionColor + fontFamily: hero.fontFamily + pixelSize: Style.font.caption + + MouseArea { + anchors.fill: parent + enabled: hero.captionClickable + cursorShape: Qt.PointingHandCursor + onClicked: hero.captionClicked() + } + } + + Row { + anchors.horizontalCenter: parent.horizontalCenter + spacing: Style.space(9) + + TitleWord { text: "World" } + + Item { + id: heroIcon + anchors.verticalCenter: parent.verticalCenter + implicitWidth: Math.round(Style.font.display * 1.3) + implicitHeight: Math.round(Style.font.display * 1.3) + + // Degrees of longitude facing the viewer; the globe draws the spin itself. + property real spin: 0 + + Binding { + target: heroIcon + property: "spin" + value: hero.restLon + when: !globeSpin.running && !focusSpin.running + restoreMode: Binding.RestoreNone + } + + rotation: Solar.AXIAL_TILT + + Text { + anchors.centerIn: parent + textFormat: Text.PlainText + text: "\u00d7" + color: heroMouse.containsMouse ? hero.foreground : hero.dim + font.family: hero.fontFamily + font.pixelSize: Math.round(heroIcon.width * 0.8) + // The globe leans with the earth; the cross stays upright. + rotation: -Solar.AXIAL_TILT + opacity: Util.clamp((hero.zoom - 0.2) / 0.35, 0, 1) + visible: opacity > 0 + } + + MiniGlobe { + anchors.fill: parent + opacity: 1 - hero.bigGlobeOpacity + visible: opacity > 0 + spin: heroIcon.spin + // Full strength: at this size a dimmed globe reads as washed out. + color: hero.foreground + bold: true + showMarker: hero.markerShown + markerLat: hero.markerLat + markerLon: hero.markerLon + } + + // A MouseArea rather than a TapHandler: only mouse events carry the + // Shift modifier that asks for slow motion. + MouseArea { + id: heroMouse + anchors.fill: parent + enabled: hero.globeEnabled + hoverEnabled: true + acceptedButtons: Qt.LeftButton + cursorShape: Qt.PointingHandCursor + onClicked: function(mouse) { + hero.globeClicked((mouse.modifiers & Qt.ShiftModifier) !== 0) + } + } + + NumberAnimation { + id: globeSpin + target: heroIcon + property: "spin" + duration: Style.duration(1250) + easing.type: Easing.OutQuart + } + + NumberAnimation { + id: focusSpin + target: heroIcon + property: "spin" + duration: Style.duration(700) + easing.type: Easing.OutCubic + } + } + + TitleWord { text: "Clock" } + } + + component TitleWord: Text { + anchors.verticalCenter: parent.verticalCenter + textFormat: Text.PlainText + color: hero.foreground + font.family: hero.fontFamily + font.pixelSize: Style.font.title + font.weight: Font.DemiBold + } +} diff --git a/shell/plugins/panels/elsewhen/MiniGlobe.qml b/shell/plugins/panels/elsewhen/MiniGlobe.qml new file mode 100644 index 000000000000..7214c6c8af2c --- /dev/null +++ b/shell/plugins/panels/elsewhen/MiniGlobe.qml @@ -0,0 +1,141 @@ +import QtQuick +import Quickshell +import Quickshell.Io +import qs.Commons +import "GlobeModel.js" as Solar +import "Model.js" as Model + +// A small drawn globe for where an icon would go. Drawn, not glyphed, so it +// can spin: `spin` is the longitude facing the viewer; rotate the item to lean it. +Item { + id: root + + property real spin: 0 + property color color: Color.foreground + // Below this size land turns to noise; draw the graticule alone. + readonly property bool showLand: width >= 22 + + property var land: [] + + // Heavier strokes and fuller fills, for a centerpiece rather than an inline icon. + property bool bold: false + + // "You are here". + property bool showMarker: false + property real markerLat: 0 + property real markerLon: 0 + property color markerColor: Color.accent + + readonly property real radius: Math.min(width, height) / 2 - 1 + readonly property string pluginDir: Quickshell.env("OMARCHY_PATH") + "/shell/plugins/panels/elsewhen" + + onSpinChanged: canvas.requestPaint() + onColorChanged: canvas.requestPaint() + onShowMarkerChanged: canvas.requestPaint() + onMarkerLatChanged: canvas.requestPaint() + onMarkerLonChanged: canvas.requestPaint() + + FileView { + path: root.pluginDir + "/world.json" + printErrors: false + onLoaded: { + try { root.land = JSON.parse(text()); canvas.requestPaint() } catch (e) { } + } + } + + Canvas { + id: canvas + anchors.fill: parent + renderStrategy: Canvas.Cooperative + + function strokePath(ctx, pts) { + var segs = Solar.visibleSegments(pts, root.spin, 0, root.radius) + for (var i = 0; i < segs.length; i++) { + ctx.moveTo(segs[i][0].x, segs[i][0].y) + for (var j = 1; j < segs[i].length; j++) ctx.lineTo(segs[i][j].x, segs[i][j].y) + } + } + + onPaint: { + var ctx = getContext("2d") + ctx.reset() + ctx.translate(width / 2, height / 2) + var r = root.radius + if (r <= 0) return + var c = root.color + var lat, lon, pts, i + + // The ocean, opaque like the large globe. + ctx.beginPath() + ctx.arc(0, 0, r, 0, Math.PI * 2) + ctx.fillStyle = Model.mix(Color.popups.background, c, root.bold ? 0.16 : 0.13) + ctx.fill() + + ctx.save() + ctx.beginPath() + ctx.arc(0, 0, r, 0, Math.PI * 2) + ctx.clip() + + // Graticule first, so the land sits on top of it. + ctx.beginPath() + for (lon = -90; lon < 90; lon += 90) { + pts = [] + for (lat = -90; lat <= 90; lat += 6) pts.push([lat, lon]) + strokePath(ctx, pts) + } + pts = [] + for (lon = -180; lon <= 180; lon += 6) pts.push([0, lon]) + strokePath(ctx, pts) + ctx.lineWidth = Math.max(1, r * (root.bold ? 0.055 : 0.045)) + ctx.strokeStyle = Util.alpha(c, root.showLand ? (root.bold ? 0.42 : 0.30) : 0.85) + ctx.stroke() + + if (root.showLand && root.land.length > 0) { + ctx.beginPath() + for (i = 0; i < root.land.length; i++) { + var ring = root.land[i] + // Major landmasses only; islands read as dirt on the lens. + if (ring.length < 40) continue + var poly = Solar.clipRingToDisc(ring, root.spin, 0, root.radius) + if (poly.length < 3) continue + ctx.moveTo(poly[0].x, poly[0].y) + for (var q = 1; q < poly.length; q++) ctx.lineTo(poly[q].x, poly[q].y) + ctx.closePath() + } + ctx.fillStyle = Util.alpha(c, root.bold ? 1.0 : 0.85) + ctx.fill() + } + + // "You are here", only while on the near side. + if (root.showMarker) { + var mp = Solar.project(root.markerLat, root.markerLon, root.spin, 0, r) + if (mp.visible) { + var mr = Math.max(1.6, r * 0.13) + ctx.beginPath() + ctx.arc(mp.x, mp.y, mr, 0, Math.PI * 2) + ctx.fillStyle = root.markerColor + ctx.fill() + // Edged so it does not dissolve into a continent of similar lightness. + ctx.lineWidth = Math.max(1, r * 0.04) + ctx.strokeStyle = Util.alpha(Color.background, 0.5) + ctx.stroke() + + ctx.beginPath() + ctx.arc(mp.x, mp.y, mr * 1.9, 0, Math.PI * 2) + ctx.lineWidth = Math.max(1, r * 0.045) + ctx.strokeStyle = Util.alpha(root.markerColor, 0.65) + ctx.stroke() + } + } + + ctx.restore() + + // The rim last, so nothing spills over it. + ctx.beginPath() + ctx.arc(0, 0, r, 0, Math.PI * 2) + ctx.lineWidth = Math.max(1, r * (root.bold ? 0.095 : 0.08)) + ctx.strokeStyle = Util.alpha(c, root.bold ? 1.0 : 0.95) + ctx.stroke() + } + } +} diff --git a/shell/plugins/panels/elsewhen/Model.js b/shell/plugins/panels/elsewhen/Model.js new file mode 100644 index 000000000000..4ecbd0ce8c8f --- /dev/null +++ b/shell/plugins/panels/elsewhen/Model.js @@ -0,0 +1,942 @@ +// QML has no Intl, so each zone's UTC offset comes from a `date` probe and the +// clocks tick locally against it. + +var DEFAULT_ZONES = "Los Angeles|America/Los_Angeles, Paris|Europe/Paris, Tokyo|Asia/Tokyo" + +var WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] +var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] + +// Keeps the list free of entries that could never name a zone. +var ZONE_ID = /^[A-Za-z0-9_+\-\/]+$/ + +// Labels live in a "Label|Zone, Label|Zone" string, so they may not carry either delimiter. +function cleanLabel(label) { + return String(label || "").replace(/[,|]/g, " ").replace(/\s+/g, " ").trim() +} + +// "Los Angeles|America/Los_Angeles, Asia/Tokyo" -> [{label, id}, ...]. Empty means a fresh install. +function parseZones(spec) { + var text = String(spec === undefined || spec === null ? "" : spec) + var out = [] + var parts = text.split(",") + for (var i = 0; i < parts.length; i++) { + var entry = parts[i].trim() + if (entry === "") continue + var fields = entry.split("|") + var label = "" + var id = "" + if (fields.length >= 2) { + label = fields[0].trim() + id = fields[1].trim() + } else { + id = entry + label = entry.split("/").pop().replace(/_/g, " ") + } + if (id === "" || !ZONE_ID.test(id)) continue + if (label === "") label = id.split("/").pop().replace(/_/g, " ") + out.push({ label: label, id: id }) + } + return out +} + +// ---- the date probe + +// argv for one `date` per zone, printing "Asia/Tokyo|JST|+0900". Zones are +// arguments, never script text. `withLocal` adds "LOCAL|" plus that zone's own line. +function probeCommand(ids, withLocal) { + var script = "for z in \"$@\"; do TZ=\"$z\" date \"+$z|%Z|%z\"; done" + if (withLocal) + script = "tz=$(timedatectl show -p Timezone --value); " + + "printf 'LOCAL|%s\\n' \"$tz\"; TZ=\"$tz\" date \"+$tz|%Z|%z\"; " + script + return ["bash", "-c", script, "bash"].concat(ids || []) +} + +// "-0700" -> -420, or null. +function parseOffset(text) { + var m = /^([+-])(\d{2})(\d{2})$/.exec(String(text || "").trim()) + if (!m) return null + var minutes = parseInt(m[2], 10) * 60 + parseInt(m[3], 10) + return m[1] === "-" ? -minutes : minutes +} + +function parseProbeLine(line) { + var fields = String(line || "").split("|") + if (fields.length < 3) return null + var id = fields[0].trim() + var offset = parseOffset(fields[2]) + if (id === "" || offset === null) return null + return { id: id, abbr: fields[1].trim(), offsetMinutes: offset } +} + +function localZoneFromProbe(text) { + var lines = String(text || "").split("\n") + for (var i = 0; i < lines.length; i++) { + var f = lines[i].split("|") + if (f.length >= 2 && f[0].trim() === "LOCAL") return f[1].trim() + } + return "" +} + +// Probe stdout -> { "America/Los_Angeles": {abbr, offsetMinutes}, ... } +function parseProbe(text) { + var map = {} + var lines = String(text || "").split("\n") + for (var i = 0; i < lines.length; i++) { + var parsed = parseProbeLine(lines[i]) + if (parsed) map[parsed.id] = { abbr: parsed.abbr, offsetMinutes: parsed.offsetMinutes } + } + return map +} + +// Absolute offset: "UTC+2", "UTC-3:30", "UTC". Minutes only when they are not zero. +function utcOffsetLabel(minutes) { + if (minutes === undefined || minutes === null) return "" + var total = Number(minutes) + if (!isFinite(total)) return "" + total = Math.round(total) + if (total === 0) return "UTC" + var abs = Math.abs(total) + var hours = Math.floor(abs / 60) + var mins = abs % 60 + return "UTC" + (total < 0 ? "-" : "+") + hours + + (mins === 0 ? "" : ":" + (mins < 10 ? "0" : "") + mins) +} + +// ---- clock faces + +// Shifting the instant by the offset and reading UTC getters gives the zone's wall clock. +function zoneParts(nowMs, offsetMinutes) { + var d = new Date(Number(nowMs) + Number(offsetMinutes) * 60000) + return { + year: d.getUTCFullYear(), + month: d.getUTCMonth(), + day: d.getUTCDate(), + weekday: d.getUTCDay(), + hour: d.getUTCHours(), + minute: d.getUTCMinutes() + } +} + +function localParts(nowMs) { + var d = new Date(Number(nowMs)) + return { + year: d.getFullYear(), + month: d.getMonth(), + day: d.getDate(), + weekday: d.getDay(), + hour: d.getHours(), + minute: d.getMinutes() + } +} + +// Calendar fields only, so DST cannot skew the count. +function dayDelta(parts, reference) { + var a = Date.UTC(parts.year, parts.month, parts.day) + var b = Date.UTC(reference.year, reference.month, reference.day) + return Math.round((a - b) / 86400000) +} + +function dayLabel(delta) { + if (delta === 0) return "" + if (delta === 1) return "Tomorrow" + if (delta === -1) return "Yesterday" + return delta > 0 ? "+" + delta + " days" : delta + " days" +} + +function pad2(n) { + return (n < 10 ? "0" : "") + n +} + +function formatTime(parts, hour24) { + if (hour24) return pad2(parts.hour) + ":" + pad2(parts.minute) + var h = parts.hour % 12 + if (h === 0) h = 12 + return h + ":" + pad2(parts.minute) +} + +function meridiem(parts) { + return parts.hour < 12 ? "AM" : "PM" +} + +// "14:05" or "2:05 PM" at a zone offset; "" before the offset is known. +function formatClock(nowMs, offsetMinutes, hour24) { + if (offsetMinutes === undefined || offsetMinutes === null) return "" + var parts = zoneParts(nowMs, offsetMinutes) + return formatTime(parts, hour24) + (hour24 ? "" : " " + meridiem(parts)) +} + +function formatDate(parts) { + return WEEKDAYS[parts.weekday].slice(0, 3) + " " + MONTHS[parts.month] + " " + parts.day +} + +function isDaytime(parts) { + return parts.hour >= 6 && parts.hour < 18 +} + +// Fixed civil hours, used until a city's real sunrise is known. +var DAY_START = 6 +var DAY_END = 18 +var DAWN_END = 8 +var DUSK_START = 17 + +function phaseFor(parts) { + var h = parts.hour + if (h < DAY_START || h >= DAY_END + 2) return "night" + if (h < DAWN_END) return "dawn" + if (h < DUSK_START) return "day" + return "dusk" +} + +function phaseLabel(phase) { + if (phase === "dawn") return "sunrise" + if (phase === "dusk") return "sunset" + if (phase === "night") return "night" + return "daytime" +} + +function dayProgress(parts) { + return (parts.hour * 60 + parts.minute) / 1440 +} + +function daylightStart() { return DAY_START / 24 } +function daylightEnd() { return DAY_END / 24 } + +// Geometric, not phaseFor(): "dusk" runs past the end of the lit band. +function inDaylight(progress) { + return progress >= daylightStart() && progress < daylightEnd() +} + +// "+9h" or "-3.5h" from the viewer's clock; "" on the viewer's own offset. +function relativeOffsetLabel(zoneOffsetMinutes, localOffsetMinutes) { + var diff = Number(zoneOffsetMinutes) - Number(localOffsetMinutes) + if (diff === 0) return "" + var hours = diff / 60 + var text = (Math.round(hours * 10) / 10).toString() + return (diff > 0 ? "+" : "") + text + "h" +} + +// Everything a row needs; `ready` is false until the zone has been probed. +function rowFor(zone, probe, nowMs, localOffsetMinutes, hour24) { + var info = probe ? probe[zone.id] : null + if (!info) return { label: zone.label, id: zone.id, ready: false } + var parts = zoneParts(nowMs, info.offsetMinutes) + var here = localParts(nowMs) + var delta = dayDelta(parts, here) + return { + label: zone.label, + id: zone.id, + ready: true, + abbr: info.abbr, + offsetMinutes: info.offsetMinutes, + time: formatTime(parts, hour24), + hour: parts.hour, + meridiem: hour24 ? "" : meridiem(parts), + date: formatDate(parts), + dayLabel: dayLabel(delta), + daytime: isDaytime(parts), + phase: phaseFor(parts), + lit: inDaylight(dayProgress(parts)), + phaseLabel: phaseLabel(phaseFor(parts)), + progress: dayProgress(parts), + relative: relativeOffsetLabel(info.offsetMinutes, localOffsetMinutes) + } +} + +function rows(zones, probe, nowMs, localOffsetMinutes, hour24) { + var out = [] + for (var i = 0; i < zones.length; i++) + out.push(rowFor(zones[i], probe, nowMs, localOffsetMinutes, hour24)) + return out +} + +// ---- editing + +// Rows and globe cities share no index space, so they meet on (label, zone id). +function indexOfZone(zones, label, id) { + var list = zones || [] + for (var i = 0; i < list.length; i++) + if (list[i].label === label && list[i].id === id) return i + return -1 +} + +// Focus is held as a key so it follows the city when `zones` is replaced. +function indexOfZoneKey(zones, key) { + var list = zones || [] + if (!key) return -1 + for (var i = 0; i < list.length; i++) + if (factsKey(list[i]) === key) return i + return -1 +} + +function labelForZoneId(id) { + return String(id || "").split("/").pop().replace(/_/g, " ") +} + +// Tapping a city on this machine's clock makes it "here", and the zone's own +// city clears the choice. The new homeCity setting, or null to leave it. +function homeCityAfterTap(label, zoneId, homeOverride, localZone) { + var name = String(label || "").trim() + var local = String(localZone || "") + if (name === "" || local === "" || String(zoneId || "") !== local) return null + var override = String(homeOverride || "").trim() + var zoneCity = labelForZoneId(local) + if (name === (override === "" ? zoneCity : override)) return null + return name === zoneCity ? "" : name +} + +function serializeZones(zones) { + var parts = [] + for (var i = 0; i < zones.length; i++) { + var z = zones[i] + if (!z || !z.id) continue + parts.push(z.label && z.label !== "" ? z.label + "|" + z.id : z.id) + } + return parts.join(", ") +} + +// Two cities may share a zone, so an entry is its label and zone together. +function hasEntry(zones, id, label) { + for (var i = 0; i < zones.length; i++) + if (zones[i].id === id && zones[i].label === label) return true + return false +} + +// Returns the same array when nothing changes, so callers can skip the write. +function addZone(zones, id, label) { + var zoneId = String(id || "").trim() + if (zoneId === "" || !ZONE_ID.test(zoneId)) return zones + var name = cleanLabel(label) + if (name === "") name = labelForZoneId(zoneId) + if (hasEntry(zones, zoneId, name)) return zones + var out = zones.slice() + out.push({ label: name, id: zoneId }) + return out +} + +// By position: with two rows on one zone, an id cannot say which was clicked. +function removeZoneAt(zones, index) { + if (zones.length <= 1 || index < 0 || index >= zones.length) return zones + var out = zones.slice() + out.splice(index, 1) + return out +} + +function moveZone(zones, from, to) { + var n = zones.length + if (from === to || from < 0 || from >= n || to < 0 || to >= n) return zones + var out = zones.slice() + out.splice(to, 0, out.splice(from, 1)[0]) + return out +} + +// The last city is never removed. +function removeZone(zones, id) { + if (zones.length <= 1) return zones + var out = [] + for (var i = 0; i < zones.length; i++) if (zones[i].id !== id) out.push(zones[i]) + return out.length === zones.length ? zones : out +} + +// `timedatectl list-timezones` plus CITY_ALIASES -> picker options, minus `existing`. +function zoneOptions(text, existing) { + var lines = String(text || "").split("\n") + var seen = {} + var out = [] + + function offer(id, label) { + var key = label + "\u0000" + id + if (seen[key]) return + if (existing && hasEntry(existing, id, label)) return + seen[key] = true + out.push({ value: id, label: label, description: id }) + } + + for (var i = 0; i < lines.length; i++) { + var id = lines[i].trim() + if (id === "" || id.indexOf("/") === -1) continue + offer(id, labelForZoneId(id)) + } + for (var j = 0; j < CITY_ALIASES.length; j++) + offer(CITY_ALIASES[j].id, CITY_ALIASES[j].label) + + out.sort(function(a, b) { return a.label < b.label ? -1 : (a.label > b.label ? 1 : 0) }) + return out +} + +// Matches city name or IANA id; city-name prefixes sort first. +function searchZones(options, query, limit) { + var q = String(query || "").trim().toLowerCase() + var max = limit === undefined ? 6 : limit + var starts = [] + var contains = [] + for (var i = 0; i < options.length; i++) { + var o = options[i] + var label = String(o.label).toLowerCase() + var id = String(o.value).toLowerCase() + if (q === "") { starts.push(o); } + else if (label.indexOf(q) === 0) starts.push(o) + else if (label.indexOf(q) !== -1 || id.indexOf(q) !== -1) contains.push(o) + if (starts.length >= max && q === "") break + } + return starts.concat(contains).slice(0, max) +} + +// Keyboard selection in a result list, wrapping at both ends. +function moveSelection(index, delta, count) { + if (count === 0) return 0 + return ((index + delta) % count + count) % count +} + +// Globe cities as [name, zone, lat, lon, rank]: home first, then the rest, +// first name wins. Tracked and session cities need coordinates. +function mergeCities(home, builtIn, tracked, session) { + var out = [] + var seen = {} + function add(city, needsCoords) { + if (needsCoords && (city[2] === null || city[2] === undefined)) return + var key = String(city[0]).toLowerCase() + if (seen[key]) return + seen[key] = true + out.push(city) + } + if (home && home.length > 0 && home[2] !== undefined) add(home, false) + var i + for (i = 0; i < (builtIn || []).length; i++) add(builtIn[i], false) + for (i = 0; i < (tracked || []).length; i++) add(tracked[i], true) + for (i = 0; i < (session || []).length; i++) add(session[i], true) + return out +} + +// Places people think of that the tz database files under another city's zone. +var CITY_ALIASES = [ + // US Eastern + { label: "Miami", id: "America/New_York" }, + { label: "Boca Raton", id: "America/New_York" }, + { label: "Boston", id: "America/New_York" }, + { label: "Philadelphia", id: "America/New_York" }, + { label: "Washington DC", id: "America/New_York" }, + { label: "Atlanta", id: "America/New_York" }, + { label: "Orlando", id: "America/New_York" }, + { label: "Tampa", id: "America/New_York" }, + { label: "Charlotte", id: "America/New_York" }, + { label: "Pittsburgh", id: "America/New_York" }, + { label: "Cleveland", id: "America/New_York" }, + // US Central + { label: "Chicago", id: "America/Chicago" }, + { label: "Austin", id: "America/Chicago" }, + { label: "Dallas", id: "America/Chicago" }, + { label: "Houston", id: "America/Chicago" }, + { label: "San Antonio", id: "America/Chicago" }, + { label: "Nashville", id: "America/Chicago" }, + { label: "New Orleans", id: "America/Chicago" }, + { label: "Minneapolis", id: "America/Chicago" }, + { label: "Kansas City", id: "America/Chicago" }, + { label: "St. Louis", id: "America/Chicago" }, + { label: "Memphis", id: "America/Chicago" }, + // US Mountain + { label: "Salt Lake City", id: "America/Denver" }, + { label: "Albuquerque", id: "America/Denver" }, + { label: "Colorado Springs", id: "America/Denver" }, + { label: "Boulder", id: "America/Denver" }, + // Arizona does not observe DST, so it is its own zone. + { label: "Tucson", id: "America/Phoenix" }, + { label: "Scottsdale", id: "America/Phoenix" }, + // US Pacific + { label: "San Francisco", id: "America/Los_Angeles" }, + { label: "San Diego", id: "America/Los_Angeles" }, + { label: "San Jose", id: "America/Los_Angeles" }, + { label: "Oakland", id: "America/Los_Angeles" }, + { label: "Sacramento", id: "America/Los_Angeles" }, + { label: "Seattle", id: "America/Los_Angeles" }, + { label: "Portland", id: "America/Los_Angeles" }, + { label: "Las Vegas", id: "America/Los_Angeles" }, + // Canada + { label: "Montreal", id: "America/Toronto" }, + { label: "Ottawa", id: "America/Toronto" }, + { label: "Calgary", id: "America/Edmonton" }, + { label: "Victoria", id: "America/Vancouver" }, + // Latin America + { label: "Rio de Janeiro", id: "America/Sao_Paulo" }, + { label: "Brasilia", id: "America/Sao_Paulo" }, + { label: "Guadalajara", id: "America/Mexico_City" }, + // UK and Ireland + { label: "Manchester", id: "Europe/London" }, + { label: "Edinburgh", id: "Europe/London" }, + { label: "Glasgow", id: "Europe/London" }, + { label: "Birmingham", id: "Europe/London" }, + { label: "Cambridge", id: "Europe/London" }, + { label: "Oxford", id: "Europe/London" }, + // Continental Europe + { label: "Munich", id: "Europe/Berlin" }, + { label: "Frankfurt", id: "Europe/Berlin" }, + { label: "Hamburg", id: "Europe/Berlin" }, + { label: "Cologne", id: "Europe/Berlin" }, + { label: "Lyon", id: "Europe/Paris" }, + { label: "Marseille", id: "Europe/Paris" }, + { label: "Nice", id: "Europe/Paris" }, + { label: "Barcelona", id: "Europe/Madrid" }, + { label: "Valencia", id: "Europe/Madrid" }, + { label: "Seville", id: "Europe/Madrid" }, + { label: "Milan", id: "Europe/Rome" }, + { label: "Naples", id: "Europe/Rome" }, + { label: "Florence", id: "Europe/Rome" }, + { label: "Venice", id: "Europe/Rome" }, + { label: "Turin", id: "Europe/Rome" }, + { label: "Rotterdam", id: "Europe/Amsterdam" }, + { label: "Geneva", id: "Europe/Zurich" }, + { label: "Basel", id: "Europe/Zurich" }, + { label: "Gothenburg", id: "Europe/Stockholm" }, + { label: "Porto", id: "Europe/Lisbon" }, + { label: "Krakow", id: "Europe/Warsaw" }, + { label: "St Petersburg", id: "Europe/Moscow" }, + // Asia + { label: "Beijing", id: "Asia/Shanghai" }, + { label: "Shenzhen", id: "Asia/Shanghai" }, + { label: "Guangzhou", id: "Asia/Shanghai" }, + { label: "Osaka", id: "Asia/Tokyo" }, + { label: "Kyoto", id: "Asia/Tokyo" }, + { label: "Yokohama", id: "Asia/Tokyo" }, + { label: "Nagoya", id: "Asia/Tokyo" }, + { label: "Busan", id: "Asia/Seoul" }, + { label: "Mumbai", id: "Asia/Kolkata" }, + { label: "Delhi", id: "Asia/Kolkata" }, + { label: "New Delhi", id: "Asia/Kolkata" }, + { label: "Bangalore", id: "Asia/Kolkata" }, + { label: "Bengaluru", id: "Asia/Kolkata" }, + { label: "Chennai", id: "Asia/Kolkata" }, + { label: "Hyderabad", id: "Asia/Kolkata" }, + { label: "Pune", id: "Asia/Kolkata" }, + { label: "Abu Dhabi", id: "Asia/Dubai" }, + { label: "Tel Aviv", id: "Asia/Jerusalem" }, + // Oceania and Africa + { label: "Canberra", id: "Australia/Sydney" }, + { label: "Cape Town", id: "Africa/Johannesburg" }, + { label: "Durban", id: "Africa/Johannesburg" }, + { label: "Alexandria", id: "Africa/Cairo" } +] + +// ---- weather + +// Coordinates and weather are keyed by "label|zone". +function factsKey(zone) { + return String(zone.label) + "|" + String(zone.id) +} + +var WEATHER_TTL_MS = 20 * 60 * 1000 + +function geocodeUrl(label) { + return "https://geocoding-api.open-meteo.com/v1/search?count=10&language=en&format=json&name=" + + encodeURIComponent(label) +} + +// { place, answered }: a place in the row's own zone beats the top result, and +// `answered` is false when the request itself failed. +function pickGeocode(text, zone) { + var results + try { results = JSON.parse(text).results || [] } catch (e) { return { place: null, answered: false } } + var best = null + for (var i = 0; i < results.length && !best; i++) if (results[i].timezone === zone) best = results[i] + if (!best && results.length > 0) best = results[0] + return { place: best ? { lat: best.latitude, lon: best.longitude } : null, answered: true } +} + +// The zone's representative city from zone1970.tab (ISO 6709), the offline fallback. +function zoneTabCoords(tabText, zone) { + var lines = String(tabText || "").split("\n") + for (var i = 0; i < lines.length; i++) { + var parts = lines[i].split("\t") + if (lines[i].charAt(0) === "#" || parts.length < 3 || parts[2] !== zone) continue + var m = /^([+-])(\d{2})(\d{2})(\d{2})?([+-])(\d{3})(\d{2})(\d{2})?$/.exec(parts[1]) + if (!m) return null + function dec(sign, d, mm, ss) { return (sign === "-" ? -1 : 1) * (Number(d) + Number(mm) / 60 + Number(ss || 0) / 3600) } + return { lat: Math.round(dec(m[1], m[2], m[3], m[4]) * 1e4) / 1e4, lon: Math.round(dec(m[5], m[6], m[7], m[8]) * 1e4) / 1e4 } + } + return null +} + +function forecastUrl(points) { + return "https://api.open-meteo.com/v1/forecast?current=temperature_2m,weather_code&temperature_unit=celsius" + + "&latitude=" + points.map(function(p) { return p.lat }).join(",") + + "&longitude=" + points.map(function(p) { return p.lon }).join(",") +} + +// Open-Meteo answers one point as an object and several as an array, in request order. +function parseForecast(text, keys, nowMs) { + var payload + try { payload = JSON.parse(text) } catch (e) { return {} } + if (!Array.isArray(payload)) payload = [payload] + var out = {} + for (var i = 0; i < keys.length && i < payload.length; i++) { + var current = (payload[i] && payload[i].current) || {} + if (current.temperature_2m === undefined || current.temperature_2m === null) continue + out[keys[i]] = { c: Math.round(current.temperature_2m * 10) / 10, w: current.weather_code, at: nowMs } + } + return out +} + +function weatherStale(entry, nowMs) { + return !entry || nowMs - entry.at >= WEATHER_TTL_MS +} + +// { "label|zone": { lat, lon, c, w } }, each field only when known. +function mergeFacts(keys, coords, weather) { + var out = {} + keys.forEach(function(key) { + var entry = {} + if (coords[key]) { entry.lat = coords[key].lat; entry.lon = coords[key].lon } + if (weather[key]) { + entry.c = weather[key].c + if (weather[key].w !== undefined && weather[key].w !== null) entry.w = weather[key].w + } + out[key] = entry + }) + return out +} + +// An explicit "C" or "F" wins; anything else follows the system. +function resolveUnits(setting, auto) { + var explicit = String(setting === undefined || setting === null ? "" : setting) + .trim().toUpperCase() + if (explicit === "C" || explicit === "F") return explicit + return String(auto).toUpperCase() === "F" ? "F" : "C" +} + +// Only a 12-hour pattern has an AM/PM designator once quoted literals are stripped. +function usesTwentyFourHour(timeFormat) { + var pattern = String(timeFormat === undefined || timeFormat === null ? "" : timeFormat) + .replace(/'[^']*'/g, "") + return !/[Aa]/.test(pattern) +} + +// An explicit setting wins, and a stored `false` is explicit. +function resolveHour24(setting, auto) { + if (setting === true || setting === false) return setting + var text = String(setting === undefined || setting === null ? "" : setting) + .trim().toLowerCase() + if (text === "true" || text === "24") return true + if (text === "false" || text === "12") return false + return auto === true +} + +function formatTemp(celsius, units) { + if (celsius === undefined || celsius === null) return "" + if (String(units).toUpperCase() === "C") return Math.round(celsius) + "°C" + return Math.round(celsius * 9 / 5 + 32) + "°F" +} + +function tempLabel(facts, units) { + return facts ? formatTemp(facts.c, units) : "" +} + +// WMO present-weather codes collapsed to the five glyphs a row can show. +function weatherKind(code) { + // Number(null) is 0, which means "clear". + if (code === null || code === undefined || code === "") return "" + var c = Number(code) + if (!isFinite(c)) return "" + if (c <= 1) return "sunny" + if (c === 2) return "partly" + if (c === 3 || c === 45 || c === 48) return "cloudy" + if (c >= 71 && c <= 77) return "snow" + if (c === 85 || c === 86) return "snow" + if (c >= 51 && c <= 67) return "rain" + if (c >= 80 && c <= 82) return "rain" + if (c >= 95 && c <= 99) return "rain" + return "" +} + +// ---- scrubbing + +var DAY_MINUTES = 1440 + +// The nearest occurrence of the local time under the pointer, in (-720, 720]. +function scrubDeltaMinutes(fraction, cityLocalMinutes) { + var target = Math.max(0, Math.min(1, fraction)) * DAY_MINUTES + var delta = target - cityLocalMinutes + while (delta > DAY_MINUTES / 2) delta -= DAY_MINUTES + while (delta <= -DAY_MINUTES / 2) delta += DAY_MINUTES + return delta +} + +// Round before splitting into hour and minute, and wrap after, so 419.8 is "7:00". +function formatMinuteOfDay(minute, hour24) { + var m = Math.round(Number(minute)) + m = ((m % DAY_MINUTES) + DAY_MINUTES) % DAY_MINUTES + var hour = Math.floor(m / 60) + return formatTime({ hour: hour, minute: m % 60 }, hour24) + + (hour24 ? "" : (hour < 12 ? " AM" : " PM")) +} + +// "+3h", "-45m", "" for now. +function formatScrubDelta(minutes) { + var m = Math.round(minutes) + if (m === 0) return "" + var sign = m > 0 ? "+" : "-" + var a = Math.abs(m) + // The arrow keys can run past a day, where hours alone stop reading well. + var d = Math.floor(a / DAY_MINUTES), h = Math.floor(a % DAY_MINUTES / 60), rem = a % 60 + var parts = [] + if (d) parts.push(d + "d") + if (h) parts.push(h + "h") + if (rem) parts.push(rem + "m") + return sign + parts.join(" ") +} + +// ---- the strip's sunrise arrows + +function arrowBox(fraction, barWidth, boxWidth, tuck, rising) { + var at = barWidth * fraction + var pos = rising ? at - boxWidth + tuck : at - tuck + return Math.round(Math.max(0, Math.min(barWidth - boxWidth, pos))) +} + +function arrowCovered(boxX, boxWidth, markerCenter, markerWidth, slack) { + return Math.abs(markerCenter - (boxX + boxWidth / 2)) < markerWidth / 2 + slack +} + +// One chip shows at a time. Both rules read what showed at press time, so a +// click comes out the same whichever handler Qt runs first. +var NO_CHIP = -1 + +function chipAfterTap(shownAtPress, slot) { + return shownAtPress === slot ? NO_CHIP : slot +} + +// Clears the chip unless something else changed it during this press. +function chipAfterRelease(shownNow, shownAtPress) { + return shownNow === shownAtPress ? NO_CHIP : shownNow +} + +// ---- globe transition and row drag + +// Rows are knocked aside one after another as `zoom` runs 0..1, alternating sides. +var KNOCK_STAGGER = 0.09 +var KNOCK_MAX_LEAD = 0.5 +var KNOCK_TILT = 14 +var KNOCK_SHRINK = 0.18 + +function knockAt(index, zoom) { + var lead = Math.min(KNOCK_MAX_LEAD, index * KNOCK_STAGGER) + return Math.max(0, Math.min(1, (zoom - lead) / (1 - lead))) +} + +function knockSide(index) { return index % 2 === 0 ? -1 : 1 } + +function knockX(index, zoom, throwX) { return knockAt(index, zoom) * knockSide(index) * throwX } + +// Squared, so rows accelerate as they fall. +function knockY(index, zoom, fall) { + var p = knockAt(index, zoom) + return p * p * fall +} + +function knockTilt(index, zoom) { return knockAt(index, zoom) * knockSide(index) * KNOCK_TILT } +function knockShrink(index, zoom) { return 1 - KNOCK_SHRINK * knockAt(index, zoom) } + +// Rows the pointer must travel past the held slot before the target moves. +var DRAG_HYSTERESIS = 0.6 + +function dragTargetFor(dragIndex, dragOffset, rowPitch, heldTarget, count) { + if (dragIndex < 0 || rowPitch <= 0) return -1 + var raw = dragOffset / rowPitch + var held = heldTarget < 0 ? 0 : heldTarget - dragIndex + var next = Math.abs(raw - held) >= DRAG_HYSTERESIS ? Math.round(raw) : held + return Math.max(0, Math.min(count - 1, dragIndex + next)) +} + +// The dragged row follows the pointer; rows it has passed step aside by one pitch. +function rowShift(index, dragIndex, dragTarget, dragOffset, rowPitch) { + if (dragIndex < 0) return 0 + if (index === dragIndex) return dragOffset + if (dragIndex < dragTarget && index > dragIndex && index <= dragTarget) return -rowPitch + if (dragIndex > dragTarget && index >= dragTarget && index < dragIndex) return rowPitch + return 0 +} + +// Opaque blend of two colors: a Qt color inside QML, {r, g, b, a} under node. +function mix(from, to, t) { + var r = from.r + (to.r - from.r) * t + var g = from.g + (to.g - from.g) * t + var b = from.b + (to.b - from.b) * t + return typeof Qt !== "undefined" ? Qt.rgba(r, g, b, 1) : { r: r, g: g, b: b, a: 1 } +} + +// ---- first run + +// Home plus four well-known cities spread round the clock from it. Rank breaks ties. +var SEED_CANDIDATES = [ + { label: "Honolulu", id: "Pacific/Honolulu", rank: 3 }, + { label: "Anchorage", id: "America/Anchorage", rank: 3 }, + { label: "Los Angeles", id: "America/Los_Angeles", rank: 2 }, + { label: "Vancouver", id: "America/Vancouver", rank: 3 }, + { label: "Mexico City", id: "America/Mexico_City", rank: 3 }, + { label: "Chicago", id: "America/Chicago", rank: 3 }, + { label: "New York", id: "America/New_York", rank: 1 }, + { label: "Sao Paulo", id: "America/Sao_Paulo", rank: 2 }, + { label: "Buenos Aires", id: "America/Argentina/Buenos_Aires", rank: 3 }, + { label: "Reykjavik", id: "Atlantic/Reykjavik", rank: 3 }, + { label: "London", id: "Europe/London", rank: 1 }, + { label: "Lisbon", id: "Europe/Lisbon", rank: 3 }, + { label: "Paris", id: "Europe/Paris", rank: 1 }, + { label: "Berlin", id: "Europe/Berlin", rank: 3 }, + { label: "Madrid", id: "Europe/Madrid", rank: 3 }, + { label: "Rome", id: "Europe/Rome", rank: 3 }, + { label: "Cairo", id: "Africa/Cairo", rank: 3 }, + { label: "Johannesburg", id: "Africa/Johannesburg", rank: 3 }, + { label: "Istanbul", id: "Europe/Istanbul", rank: 3 }, + { label: "Moscow", id: "Europe/Moscow", rank: 3 }, + { label: "Nairobi", id: "Africa/Nairobi", rank: 3 }, + { label: "Dubai", id: "Asia/Dubai", rank: 2 }, + { label: "Karachi", id: "Asia/Karachi", rank: 3 }, + { label: "Delhi", id: "Asia/Kolkata", rank: 2 }, + { label: "Bangkok", id: "Asia/Bangkok", rank: 3 }, + { label: "Jakarta", id: "Asia/Jakarta", rank: 3 }, + { label: "Singapore", id: "Asia/Singapore", rank: 2 }, + { label: "Hong Kong", id: "Asia/Hong_Kong", rank: 2 }, + { label: "Shanghai", id: "Asia/Shanghai", rank: 2 }, + { label: "Perth", id: "Australia/Perth", rank: 3 }, + { label: "Seoul", id: "Asia/Seoul", rank: 3 }, + { label: "Tokyo", id: "Asia/Tokyo", rank: 1 }, + { label: "Sydney", id: "Australia/Sydney", rank: 2 }, + { label: "Auckland", id: "Pacific/Auckland", rank: 3 } +] + +function seedCandidateZones() { + var out = [] + for (var i = 0; i < SEED_CANDIDATES.length; i++) out.push(SEED_CANDIDATES[i].id) + return out +} + +// Minutes east of home, wrapped to one turn of the dial. +function eastOf(offsetMinutes, homeMinutes) { + var d = (offsetMinutes - homeMinutes) % DAY_MINUTES + return d < 0 ? d + DAY_MINUTES : d +} + +function dialDistance(a, b) { + var d = Math.abs(a - b) % DAY_MINUTES + return Math.min(d, DAY_MINUTES - d) +} + +// Best-ranked candidates first, each at least `gap` minutes from home and from every pick. +function pickSeedAt(home, offsets, count, gap) { + var homeOff = offsets[home.id] + var homeLabel = String(home.label || "").toLowerCase() + var picked = [] + for (var r = 1; r <= 3; r++) { + for (var j = 0; j < SEED_CANDIDATES.length && picked.length < count; j++) { + var c = SEED_CANDIDATES[j] + if (c.rank !== r) continue + var off = offsets[c.id] + if (off === undefined || off === null) continue + if (c.id === home.id) continue + if (String(c.label).toLowerCase() === homeLabel) continue + var east = eastOf(off, homeOff) + if (Math.min(east, DAY_MINUTES - east) < gap) continue + var clash = false + for (var k = 0; k < picked.length; k++) + if (dialDistance(picked[k].east, east) < gap) { clash = true; break } + if (clash) continue + picked.push({ label: c.label, id: c.id, east: east }) + } + } + return picked +} + +// `offsets` maps zone id to minutes east of UTC and must include home's. +function pickSeedZones(home, offsets, count) { + var n = count === undefined ? 4 : count + if (!home || !home.id || !offsets) return [] + if (offsets[home.id] === undefined || offsets[home.id] === null) return [] + + // Relax the gap where half the world sits within a couple of hours of home. + var picked = [] + var gaps = [180, 120, 60] + for (var g = 0; g < gaps.length; g++) { + picked = pickSeedAt(home, offsets, n, gaps[g]) + if (picked.length >= n) break + } + + picked.sort(function (a, b) { return a.east - b.east }) + + var out = [] + for (var m = 0; m < picked.length; m++) + out.push({ label: picked[m].label, id: picked[m].id }) + return out +} + +function seedZones(home, offsets, count) { + if (!home || !home.id) return [] + var out = [{ label: home.label, id: home.id }] + var rest = pickSeedZones(home, offsets, count) + for (var i = 0; i < rest.length; i++) out.push(rest[i]) + return out +} + +if (typeof module !== "undefined") { + module.exports = { + DEFAULT_ZONES: DEFAULT_ZONES, + NO_CHIP: NO_CHIP, + SEED_CANDIDATES: SEED_CANDIDATES, + parseZones: parseZones, + probeCommand: probeCommand, + parseOffset: parseOffset, + parseProbe: parseProbe, + localZoneFromProbe: localZoneFromProbe, + utcOffsetLabel: utcOffsetLabel, + relativeOffsetLabel: relativeOffsetLabel, + zoneParts: zoneParts, + localParts: localParts, + formatTime: formatTime, + meridiem: meridiem, + formatClock: formatClock, + daylightStart: daylightStart, + daylightEnd: daylightEnd, + rows: rows, + indexOfZone: indexOfZone, + indexOfZoneKey: indexOfZoneKey, + labelForZoneId: labelForZoneId, + homeCityAfterTap: homeCityAfterTap, + serializeZones: serializeZones, + addZone: addZone, + removeZoneAt: removeZoneAt, + moveZone: moveZone, + removeZone: removeZone, + zoneOptions: zoneOptions, + searchZones: searchZones, + moveSelection: moveSelection, + mergeCities: mergeCities, + factsKey: factsKey, + geocodeUrl: geocodeUrl, + pickGeocode: pickGeocode, + zoneTabCoords: zoneTabCoords, + forecastUrl: forecastUrl, + parseForecast: parseForecast, + weatherStale: weatherStale, + mergeFacts: mergeFacts, + resolveUnits: resolveUnits, + usesTwentyFourHour: usesTwentyFourHour, + resolveHour24: resolveHour24, + formatTemp: formatTemp, + tempLabel: tempLabel, + weatherKind: weatherKind, + scrubDeltaMinutes: scrubDeltaMinutes, + formatMinuteOfDay: formatMinuteOfDay, + formatScrubDelta: formatScrubDelta, + arrowBox: arrowBox, + arrowCovered: arrowCovered, + chipAfterTap: chipAfterTap, + chipAfterRelease: chipAfterRelease, + knockAt: knockAt, + knockX: knockX, + knockY: knockY, + knockTilt: knockTilt, + knockShrink: knockShrink, + dragTargetFor: dragTargetFor, + rowShift: rowShift, + mix: mix, + seedCandidateZones: seedCandidateZones, + pickSeedZones: pickSeedZones, + seedZones: seedZones + } +} diff --git a/shell/plugins/panels/elsewhen/MoonDot.qml b/shell/plugins/panels/elsewhen/MoonDot.qml new file mode 100644 index 000000000000..9645d167efca --- /dev/null +++ b/shell/plugins/panels/elsewhen/MoonDot.qml @@ -0,0 +1,47 @@ +import QtQuick +import qs.Commons +import "GlobeModel.js" as Solar + +// The night marker drawn as the moon's current phase. The faint full disc +// keeps it findable at new moon; the lit part is filled solid on top. +Item { + id: root + + property real phase: 0 // 0 new, 0.25 first quarter, 0.5 full + property color color: Color.foreground + + onPhaseChanged: canvas.requestPaint() + onColorChanged: canvas.requestPaint() + + Canvas { + id: canvas + anchors.fill: parent + renderStrategy: Canvas.Cooperative + + onPaint: { + var ctx = getContext("2d") + ctx.reset() + var r = Math.min(width, height) / 2 + if (r <= 0) return + ctx.translate(width / 2, height / 2) + var c = root.color + + // The whole disc, faint. + ctx.beginPath() + ctx.arc(0, 0, r, 0, Math.PI * 2) + ctx.fillStyle = Util.alpha(c, 0.22) + ctx.fill() + + // The lit part, solid. + var lit = Solar.moonLitOutline(root.phase, r, 28) + if (lit.length > 2) { + ctx.beginPath() + ctx.moveTo(lit[0].x, lit[0].y) + for (var i = 1; i < lit.length; i++) ctx.lineTo(lit[i].x, lit[i].y) + ctx.closePath() + ctx.fillStyle = c + ctx.fill() + } + } + } +} diff --git a/shell/plugins/panels/elsewhen/Panel.qml b/shell/plugins/panels/elsewhen/Panel.qml new file mode 100644 index 000000000000..238b50d8d15e --- /dev/null +++ b/shell/plugins/panels/elsewhen/Panel.qml @@ -0,0 +1,977 @@ +import QtQuick +import Quickshell +import Quickshell.Io +import qs.Commons +import qs.Ui +import "Model.js" as Model +import "GlobeModel.js" as Solar + +// A bar button that opens a panel of clocks, one row per city, and zooms into +// a globe. QML has no Intl, so a `date` probe supplies each zone's offset and +// the rows tick locally against it; the probe re-runs on open and every five +// minutes to catch DST. +Panel { + id: root + moduleName: "omarchy.elsewhen" + ipcTarget: "omarchy.elsewhen" + manageIpc: false + + + // ---- settings + readonly property var zones: Model.parseZones(setting("zones", "")) + readonly property var zoneIds: zones.map(function(z) { return z.id }) + // Never written: the first probe seeds the list around the local zone. + readonly property bool needsSeed: String(setting("zones", "")).trim() === "" + readonly property var probeIds: needsSeed ? zoneIds.concat(Model.seedCandidateZones()) : zoneIds + + readonly property bool autoHour24: Model.usesTwentyFourHour(Qt.locale().timeFormat(Locale.ShortFormat)) + readonly property bool hour24: Model.resolveHour24(setting("hour24", ""), autoHour24) + // "home" shows the distance from here ("+2h"), "utc" the zone itself ("UTC-5"). + readonly property string offsetMode: setting("offsetMode", "home") === "utc" ? "utc" : "home" + // Only the US measurement system means Fahrenheit. + readonly property string autoUnits: Qt.locale().measurementSystem === Locale.ImperialUSSystem ? "F" : "C" + readonly property string units: Model.resolveUnits(setting("units", ""), autoUnits) + readonly property bool globeEnabled: setting("globeEnabled", true) !== false + // Draw the globe with less in it while it moves. + readonly property bool smoothMotion: setting("smoothMotion", true) !== false + + function toggleHour24() { persistSettings({ hour24: !hour24 }) } + function toggleOffsetMode() { persistSettings({ offsetMode: offsetMode === "utc" ? "home" : "utc" }) } + function toggleUnits() { persistSettings({ units: units === "C" ? "F" : "C" }) } + + function offsetTextFor(rowData) { + if (!rowData || !rowData.ready) return "" + return offsetMode === "utc" ? Model.utcOffsetLabel(rowData.offsetMinutes) : rowData.relative + } + + // ---- state + property var probe: ({}) + property var searchProbe: ({}) + property string zoneCatalogText: "" + property var facts: ({}) + // Geocoder answers are final for the session; fallbacks are retried. + property var geo: ({}) + property var fallbackGeo: ({}) + property var weather: ({}) + // Cities jumped to on the globe; never persisted. + property var sessionCities: [] + property int localOffsetMinutes: -(new Date().getTimezoneOffset()) + property string localZone: "" + property double nowMs: Date.now() + property bool probeQueued: false + property bool searchProbeQueued: false + property bool factsQueued: false + + readonly property bool adding: citySearch.active + onAddingChanged: if (!adding) scroller.scrollToTop() + readonly property var zoneOptions: Model.zoneOptions(zoneCatalogText, zones) + // The globe's jump box may go to a city that is already tracked. + readonly property var allZoneOptions: Model.zoneOptions(zoneCatalogText, []) + readonly property var searchZoneIds: { + var out = [] + for (var i = 0; i < citySearch.matches.length; i++) { + var id = citySearch.matches[i].value + if (out.indexOf(id) < 0) out.push(id) + } + return out + } + onSearchZoneIdsChanged: probeSearchZones() + + implicitWidth: button.implicitWidth + implicitHeight: button.implicitHeight + + readonly property color foreground: bar ? bar.foreground : Color.foreground + readonly property color dim: Qt.darker(foreground, 1.55) + readonly property color fainter: Qt.darker(foreground, 2.1) + // A literal gold: several themes' "yellow" is not yellow. + readonly property color daylightMarker: "#E5C736" + readonly property string fontFamily: bar ? bar.fontFamily : Style.font.family + + // ---- the zoom + // One number drives the list-to-globe transition: 0 is the list, 1 the globe. + property bool globeMode: false + property real zoom: globeMode ? 1 : 0 + readonly property bool zoomIdle: zoom === 0 || zoom === 1 + readonly property real bigGlobeOpacity: Util.clamp(zoom / 0.12, 0, 1) + readonly property real globeStageHeight: Style.space(378) + // Far enough for the top row to fall past the whole list. + readonly property real knockFall: listWrap.implicitHeight + Style.space(220) + + // Shift-click the globe to run the transition at a third of the speed. + readonly property int slowMotionFactor: 3 + // Set before globeMode flips, so the animation never reads a stale duration. + property int zoomDuration: 800 + property int zoomEasing: Easing.OutQuart + + function setGlobeMode(on, slow) { + if (on) addSelected = false + zoomDuration = (on ? 800 : 500) * (slow === true ? slowMotionFactor : 1) + zoomEasing = on ? Easing.OutQuart : Easing.InOutCubic + globeMode = on + if (on && globeLoader.item) showFocusOnGlobe() + } + + // The globe opens on the list's focus, when its coordinates are known. + function showFocusOnGlobe() { + var g = globeLoader.item + if (!g) return + if (focusIndex >= 0 && focusKnown) g.goTo(focusZone.label, focusZone.id) + else g.showHome() + } + + function claimHome(label, zone) { + var stored = Model.homeCityAfterTap(label, zone, setting("homeCity", ""), localZone) + if (stored === null) return + persistSettings({ homeCity: stored }) + refreshFacts() + } + + function focusFromGlobe(label, zone) { + var i = Model.indexOfZone(zones, label, zone) + if (i >= 0) focusOn(i) + } + + // The little globe's center in stage coordinates, where the big one grows + // from. The unused sum makes it recompute when the layout above moves. + readonly property var heroCenter: { + var _ = hero.icon.width + hero.icon.height + stage.y + stage.width + var pt = hero.icon.mapToItem(stage, hero.icon.width / 2, hero.icon.height / 2) + return (pt && pt.x !== undefined) ? pt : null + } + readonly property real heroCenterX: heroCenter ? heroCenter.x : stage.width / 2 + readonly property real heroCenterY: heroCenter ? heroCenter.y : 0 + readonly property real heroDiscRadius: Math.max(1, hero.icon.width / 2 - 1) + + // ---- drag to reorder + // Rows move by transform while dragging; the order is committed on drop. + property int dragIndex: -1 + property real dragOffset: 0 + property real rowPitch: 0 + property int dragTarget: -1 + + function beginRowDrag(index, pitch) { + dropAnimation.stop() + dragIndex = index + dragTarget = index + rowPitch = pitch + } + + function moveRowDrag(offset) { + dragOffset = offset + dragTarget = Model.dragTargetFor(dragIndex, dragOffset, rowPitch, dragTarget, zones.length) + } + + // Glide into the slot, then commit. + function releaseRowDrag() { + if (dragIndex < 0) { cancelRowDrag(); return } + dropAnimation.to = (dragTarget - dragIndex) * rowPitch + dropAnimation.restart() + } + + function commitRowDrag() { + if (dragIndex >= 0 && dragTarget >= 0 && dragTarget !== dragIndex) + persistSettings({ zones: Model.serializeZones(Model.moveZone(zones, dragIndex, dragTarget)) }) + cancelRowDrag() + } + + function cancelRowDrag() { + dropAnimation.stop() + dragIndex = -1 + dragTarget = -1 + dragOffset = 0 + } + + // ---- scrubbing + // Set absolutely from the pointer, held briefly after release, then back to now. + property real scrubMinutes: 0 + readonly property double effectiveMs: nowMs + scrubMinutes * 60000 + readonly property string scrubLabel: Model.formatScrubDelta(scrubMinutes) + + // Measured against the unscrubbed present, so a drag cannot drift. + function scrubTo(rowData, fraction) { + if (!rowData || !rowData.ready) return + var parts = Model.zoneParts(nowMs, rowData.offsetMinutes) + scrubMinutes = Model.scrubDeltaMinutes(fraction, parts.hour * 60 + parts.minute) + } + + function beginScrub(rowData, fraction) { + scrubHold.stop() + scrubTo(rowData, fraction) + } + + function endScrub() { scrubHold.restart() } + + // Held until Escape or close: a key press has no release to time from. Unlike a + // drag, which stays within the strip's day, the keys can run on into other days. + function shiftHour(step) { + scrubHold.stop() + scrubMinutes = Math.round(scrubMinutes) + step * 60 + } + + // ---- the moon + // Shift-click a moon marker to walk the phase through a lunation. + property bool moonShowing: false + property real moonDemo: -1 + readonly property var moonShowStops: [0, 0.12, 0.25, 0.38, 0.5, 0.62, 0.75, 0.88, 1] + property int moonShowStep: 0 + readonly property real moonPhase: moonShowing && moonDemo >= 0 ? moonDemo : Solar.moonPhase(effectiveMs) + + function startMoonShow() { + moonShowStep = 0 + moonShowing = true + moonDemo = moonShowStops[0] + moonShowTimer.restart() + } + + function stopMoonShow() { + moonShowTimer.stop() + // Before the value, so the tween does not run the phase back to -1. + moonShowing = false + moonDemo = -1 + } + + // ---- places + readonly property var clockRows: Model.rows(zones, probe, effectiveMs, localOffsetMinutes, hour24) + + // The system zone names a representative city; `homeCity` overrides it. + readonly property string homeCity: { + var override = String(setting("homeCity", "")).trim() + if (override !== "") return override + return localZone === "" ? "" : Model.labelForZoneId(localZone) + } + readonly property var homeZone: ({ label: homeCity, id: localZone }) + + function placeOf(zone) { + var f = facts[Model.factsKey(zone)] + return (f && f.lat !== undefined && f.lon !== undefined) ? f : null + } + + readonly property var homePlace: homeCity === "" || localZone === "" ? null : placeOf(homeZone) + + // Matched by name: Miami should not light up New York. + readonly property var trackedNames: zones.map(function(z) { return String(z.label).toLowerCase() }) + + function globeRows(list, rank) { + var out = [] + for (var i = 0; i < list.length; i++) { + var f = placeOf(list[i]) + if (f) out.push([list[i].label, list[i].id, f.lat, f.lon, rank]) + } + return out + } + readonly property var trackedCities: globeRows(zones, 0) + readonly property var sessionPlaces: globeRows(sessionCities, 1) + + // Held as the city's key, not a row index, so a reorder carries the focus + // with the city and a removal drops it back to home. + property string focusKey: "" + readonly property int focusIndex: Model.indexOfZoneKey(zones, focusKey) + readonly property var focusZone: focusIndex >= 0 ? zones[focusIndex] : homeZone + readonly property var focusPlace: placeOf(focusZone) + readonly property bool focusKnown: focusPlace !== null + readonly property real focusLat: focusKnown ? focusPlace.lat : 0 + readonly property real focusLon: focusKnown ? focusPlace.lon : 0 + + function focusOn(index) { + addSelected = false + var from = hero.spin + focusKey = index >= 0 && index < zones.length ? Model.factsKey(zones[index]) : "" + if (focusKnown) hero.turn(from, focusLon) + } + + // Past the last city, the list's cursor rests on "Add a city"; the globe stays put. + property bool addSelected: false + + // Up and down walk home, each city and then "Add a city", wrapping round like the + // search list. The globe has no add row, so there the walk skips it. + function moveFocus(step) { + var at = addSelected ? zones.length : focusIndex + var next = Model.moveSelection(at + 1, step, zones.length + (globeMode ? 1 : 2)) - 1 + if (next === zones.length) { + addSelected = true + scrollToItem(citySearch) + return + } + focusOn(next) + if (globeMode) showFocusOnGlobe() + else scrollToItem(next >= 0 ? cityRows.itemAt(next) : null) + } + + // The picked city goes, as with its × button, and the cursor lands on the city + // that takes its place. The last city stays, so there is always one clock. + function deleteFocused() { + if (globeMode || addSelected || focusIndex < 0 || zones.length < 2) return + var at = focusIndex + removeCityAt(at) + focusOn(Math.min(at, zones.length - 1)) + } + + function scrollToItem(item) { + if (!item) { scroller.scrollToTop(); return } + var top = item.mapToItem(content, 0, 0).y + if (top < scroller.contentY) scroller.scrollTo(top) + else if (top + item.height > scroller.contentY + scroller.height) + scroller.scrollTo(Math.min(scroller.maxScroll, top + item.height - scroller.height)) + } + + // Surrogate pairs rather than literal glyphs, which re-encoding can break. + function weatherGlyph(zone) { + var f = facts[Model.factsKey(zone)] + if (!f || f.w === undefined) return "" + var kind = Model.weatherKind(f.w) + if (kind === "sunny") return "\udb81\udda8" // white-balance-sunny: a solid disc + if (kind === "partly") return "\udb81\udd95" + if (kind === "cloudy") return "\udb81\udd90" + if (kind === "rain") return "\udb81\udd97" + if (kind === "snow") return "\udb81\udd98" + return "" + } + + readonly property string localTime: { + var here = Model.localParts(effectiveMs) + var text = Model.formatTime(here, hour24) + return hour24 ? text : text + " " + Model.meridiem(here) + } + + // No full stop: a period hanging off the arc reads as a speck. + readonly property string hereLine: "It's " + localTime + " here" + + (homeCity !== "" ? " in " + homeCity : "") + + (scrubLabel !== "" ? " " + scrubLabel : "") + + // A capital's line box has empty space above it; the row's top pad drops by it. + FontMetrics { + id: nameFontMetrics + font.family: root.fontFamily + font.pixelSize: Style.font.subtitle + } + + TextMetrics { + id: nameCapMetrics + font.family: root.fontFamily + font.pixelSize: Style.font.subtitle + text: "M" + } + + readonly property real capGap: Math.max(0, + nameFontMetrics.height - nameFontMetrics.descent + nameCapMetrics.tightBoundingRect.y) + + // The widest a row's time gets, so every row's weather lines up against one + // column rather than hugging "4:06" in one row and "10:06" in the next. + TextMetrics { + id: widestTimeMetrics + font.family: root.fontFamily + font.pixelSize: Style.font.heading + font.weight: Font.DemiBold + text: "00:00" + } + + TextMetrics { + id: meridiemMetrics + font.family: root.fontFamily + font.pixelSize: Style.font.caption + text: "PM" + } + + readonly property real timeColumnWidth: Math.ceil(widestTimeMetrics.advanceWidth + + (hour24 ? 0 : Style.spacing.xs + meridiemMetrics.advanceWidth)) + + function tick() { + nowMs = Date.now() + localOffsetMinutes = -(new Date().getTimezoneOffset()) + } + + // Written straight back to this widget's shell.json entry, like the clock's. + function persistSettings(values) { + var entry = { id: root.moduleName } + for (var existing in root.settings) if (existing !== "id") entry[existing] = root.settings[existing] + for (var key in values) entry[key] = values[key] + + root.settings = entry + if (root.bar && root.bar.shell && typeof root.bar.shell.updateEntryInline === "function") + root.bar.shell.updateEntryInline(root.moduleName, entry) + } + + function setZones(next) { + if (next === zones) return + persistSettings({ zones: Model.serializeZones(next) }) + refresh() + refreshFacts() + } + + // The label matters as much as the zone: many cities share one. + function addCity(id, label) { setZones(Model.addZone(zones, id, label || "")) } + function removeCity(id) { setZones(Model.removeZone(zones, id)) } + function removeCityAt(index) { setZones(Model.removeZoneAt(zones, index)) } + + function startAdding() { citySearch.start() } + + function addSessionCity(label, id) { + for (var i = 0; i < sessionCities.length; i++) + if (sessionCities[i].label === label && sessionCities[i].id === id) return + sessionCities = sessionCities.concat([{ label: label, id: id }]) + refreshFacts() + } + + // The local city plus four places spread round the clock from it. + function seedFirstRun() { + var offs = ({}) + for (var id in probe) offs[id] = probe[id].offsetMinutes + + var seeded = localZone === "" ? [] + : Model.seedZones({ label: Model.labelForZoneId(localZone), id: localZone }, offs, 4) + if (seeded.length === 0) seeded = Model.parseZones(Model.DEFAULT_ZONES) + if (seeded.length === 0) return + + persistSettings({ zones: Model.serializeZones(seeded) }) + refresh() + refreshFacts() + } + + // ---- processes + // Each refresh queues behind one in flight rather than being dropped. + function refresh() { + if (probeIds.length === 0) return + if (probeProc.running) { probeQueued = true; return } + probeProc.running = true + } + + function probeSearchZones() { + if (searchZoneIds.length === 0) return + if (searchProc.running) { searchProbeQueued = true; return } + searchProc.running = true + } + + function refreshFacts() { + if (zones.length === 0) return + if (geoProc.running || weatherProc.running) { factsQueued = true; return } + var missing = factsRequest.filter(function(row) { return !geo[Model.factsKey(row)] }) + if (missing.length === 0) { fetchWeather(); return } + geoProc.rows = missing + geoProc.command = ["bash", "-c", 'for url; do curl -fsS --max-time 8 "$url"; printf "\\n\\036\\n"; done', "bash"] + .concat(missing.map(function(row) { return Model.geocodeUrl(row.label) })) + geoProc.running = true + } + + function coordsFor(key) { + return geo[key] || fallbackGeo[key] || null + } + + function fetchWeather() { + var now = Date.now() + var stale = factsRequest.map(Model.factsKey).filter(function(key) { + return coordsFor(key) && Model.weatherStale(weather[key], now) + }) + if (stale.length === 0) { publishFacts(); return } + weatherProc.keys = stale + weatherProc.command = ["curl", "-fsS", "--max-time", "8", Model.forecastUrl(stale.map(coordsFor))] + weatherProc.running = true + } + + function publishFacts() { + var coords = {} + var keys = factsRequest.map(Model.factsKey) + keys.forEach(function(key) { coords[key] = coordsFor(key) }) + facts = Model.mergeFacts(keys, coords, weather) + if (!factsQueued) return + factsQueued = false + Qt.callLater(refreshFacts) + } + + function loadCatalog() { + if (zoneCatalogText !== "" || catalogProc.running) return + catalogProc.running = true + } + + function utcLabelFor(zoneId) { + var known = searchProbe[zoneId] + return known === undefined ? "" : Model.utcOffsetLabel(known.offsetMinutes) + } + + // Tracked cities, the city you are in (for the globe's home) and session cities. + readonly property var factsRequest: { + var out = zones.map(function(z) { return { label: z.label, id: z.id } }) + if (localZone !== "" && homeCity !== "") out.push({ label: homeCity, id: localZone }) + return out.concat(sessionCities) + } + + // ---- opening spin + // It lands on the home meridian, so it waits for home's coordinates, read + // straight from the facts: focusKnown can flip a beat before focusLon lands. + property bool spinPending: false + + function homeMeridian() { + var f = facts[Model.factsKey(focusZone)] + return (f && f.lon !== undefined && f.lon !== null) ? f.lon : null + } + + function startOpeningSpin() { + var lon = homeMeridian() + if (lon === null) { spinPending = true; spinFallback.restart(); return } + spinPending = false + spinFallback.stop() + hero.spinOpening(lon) + } + + onFactsChanged: if (spinPending) startOpeningSpin() + + // No coordinates on a cold cache without network: spin anyway. + Timer { + id: spinFallback + interval: 1500 + onTriggered: if (root.spinPending) { root.spinPending = false; hero.spinOpening(null) } + } + + onOpenedChanged: { + if (opened) { + focusKey = "" + addSelected = false + tick(); refresh(); refreshFacts(); loadCatalog() + startOpeningSpin() + } else { + citySearch.stop(); setGlobeMode(false, false); scrubMinutes = 0 + spinPending = false; spinFallback.stop() + } + } + Component.onCompleted: refresh() + + Process { + id: probeProc + command: Model.probeCommand(root.probeIds, true) + stdout: StdioCollector { + onStreamFinished: { + root.probe = Model.parseProbe(text) + var lz = Model.localZoneFromProbe(text) + if (lz !== "") root.localZone = lz + if (root.needsSeed) root.seedFirstRun() + root.tick() + Qt.callLater(function() { + if (!root.probeQueued) return + root.probeQueued = false + root.refresh() + }) + } + } + } + + // Merged, so a known offset stays on screen while the next probe runs. + Process { + id: searchProc + command: Model.probeCommand(root.searchZoneIds, false) + stdout: StdioCollector { + onStreamFinished: { + var merged = {} + for (var known in root.searchProbe) merged[known] = root.searchProbe[known] + var fresh = Model.parseProbe(text) + for (var id in fresh) merged[id] = fresh[id] + root.searchProbe = merged + Qt.callLater(function() { + if (!root.searchProbeQueued) return + root.searchProbeQueued = false + root.probeSearchZones() + }) + } + } + } + + Process { + id: catalogProc + command: ["timedatectl", "list-timezones"] + stdout: StdioCollector { + onStreamFinished: root.zoneCatalogText = text + } + } + + FileView { + id: zoneTab + path: "/usr/share/zoneinfo/zone1970.tab" + printErrors: false + } + + Process { + id: geoProc + property var rows: [] + stdout: StdioCollector { + onStreamFinished: { + var answers = text.split("\n\u001e\n") + var nextGeo = Object.assign({}, root.geo) + var nextFallback = {} + geoProc.rows.forEach(function(row, i) { + var key = Model.factsKey(row) + var found = Model.pickGeocode(answers[i] || "", row.id) + var place = found.place || Model.zoneTabCoords(zoneTab.text(), row.id) + if (!place) return + if (found.answered) nextGeo[key] = place + else nextFallback[key] = place + }) + root.geo = nextGeo + root.fallbackGeo = nextFallback + root.fetchWeather() + } + } + } + + Process { + id: weatherProc + property var keys: [] + stdout: StdioCollector { + onStreamFinished: { + root.weather = Object.assign({}, root.weather, Model.parseForecast(text, weatherProc.keys, Date.now())) + root.publishFacts() + } + } + } + + Timer { + interval: 900000 + running: root.opened + repeat: true + onTriggered: root.refreshFacts() + } + + // Heavy on the way out, brisk on the way back. + Behavior on zoom { + NumberAnimation { + duration: Style.duration(root.zoomDuration) + easing.type: root.zoomEasing + } + } + + Timer { + id: moonShowTimer + interval: 620 + repeat: true + onTriggered: { + root.moonShowStep++ + if (root.moonShowStep >= root.moonShowStops.length) root.stopMoonShow() + else root.moonDemo = root.moonShowStops[root.moonShowStep] + } + } + + Behavior on moonDemo { + enabled: root.moonShowing + NumberAnimation { duration: Style.duration(460); easing.type: Easing.InOutSine } + } + + NumberAnimation { + id: dropAnimation + target: root + property: "dragOffset" + duration: Style.duration(150) + easing.type: Easing.OutCubic + onFinished: root.commitRowDrag() + } + + Timer { + id: scrubHold + interval: 2500 + onTriggered: root.scrubMinutes = 0 + } + + Timer { + interval: 1000 + running: root.opened + repeat: true + onTriggered: root.tick() + } + + Timer { + interval: 300000 + running: root.opened + repeat: true + onTriggered: root.refresh() + } + + ShellIpc { + target: root.ipcTarget + function open(): void { root.open() } + function close(): void { root.close() } + function show(): void { root.open() } + function hide(): void { root.close() } + function toggle(): void { root.toggle() } + function refresh(): string { root.refresh(); return "ok" } + + function globe(): string { + if (!root.globeEnabled) return "disabled" + root.setGlobeMode(!root.globeMode, false) + return root.globeMode ? "globe" : "list" + } + + // Ticks first: the clock only runs while the panel is open. + function times(): string { + root.tick() + return JSON.stringify(root.clockRows) + } + function add(zone: string, label: string): string { + root.setZones(Model.addZone(root.zones, zone, label)) + return Model.serializeZones(root.zones) + } + function remove(zone: string): string { root.removeCity(zone); return Model.serializeZones(root.zones) } + } + + BarIconButton { + id: button + anchors.fill: parent + bar: root.bar + text: "󰇧" + tooltipText: "World clock" + onPressed: function(buttonCode) { + if (buttonCode === Qt.RightButton || buttonCode === Qt.MiddleButton) root.refresh() + else root.toggle() + } + } + + KeyboardPanel { + id: panel + anchorItem: button + owner: root + bar: root.bar + open: root.opened + focusTarget: keyCatcher + contentWidth: panel.fittedContentWidth(Style.space(340)) + contentHeight: panel.fittedContentHeight(content.implicitHeight, Style.space(680)) + + PanelKeyCatcher { + id: keyCatcher + anchors.fill: parent + blocked: root.adding + // Escape unwinds one layer: search (its own field), a shifted time, globe, then panel. + onCloseRequested: { + if (root.scrubMinutes !== 0) { scrubHold.stop(); root.scrubMinutes = 0 } + else if (root.globeMode) root.setGlobeMode(false, false) + else root.close() + } + onDeleteRequested: root.deleteFocused() + // Up and down pick a city; left and right move the clocks an hour. + onMoveRequested: function(dx, dy) { + if (dy !== 0) root.moveFocus(dy) + else root.shiftHour(dx) + } + // Return or Space on "Add a city" opens the search. Otherwise Space toggles + // the globe, and Return, which also arrives as an activate, does nothing. + property bool returnHandled: false + onReturnRequested: returnHandled = true + onActivateRequested: { + var fromReturn = returnHandled + returnHandled = false + if (root.addSelected) root.startAdding() + else if (!fromReturn && root.globeEnabled) root.setGlobeMode(!root.globeMode, false) + } + onTabRequested: function(direction) { root.switchPanel(direction) } + // "+" searches in either view; "j" jumps on the globe, "a" adds on the list. + // "t" flips 24-hour and AM/PM time, like clicking a row's time, and Alt+T + // flips Fahrenheit and Celsius, like clicking a temperature. + onTextKey: function(text, modifiers) { + var key = text.toLowerCase() + if (key === "r") root.refresh() + else if (key === "t" && (modifiers & Qt.AltModifier)) root.toggleUnits() + else if (key === "t") root.toggleHour24() + else if (root.globeMode && (key === "+" || key === "j")) { + if (globeLoader.item) globeLoader.item.startJump() + } else if (!root.globeMode && (key === "+" || key === "a")) { + root.startAdding() + } + } + + // Clipped to the card and scrolled by the wheel only: the rows own drags. + Flickable { + id: scroller + anchors.fill: parent + clip: true + interactive: false + contentWidth: width + contentHeight: content.implicitHeight + boundsBehavior: Flickable.StopAtBounds + + readonly property real maxScroll: Math.max(0, contentHeight - height) + + function clamp() { contentY = Util.clamp(contentY, 0, maxScroll) } + onHeightChanged: clamp() + onContentHeightChanged: clamp() + + function scrollTo(y) { + scrollAnim.stop() + scrollAnim.from = contentY + scrollAnim.to = y + scrollAnim.start() + } + function scrollToTop() { scrollTo(0) } + + // Follows maxScroll: the results arrive over several frames after the + // search opens, so a one-shot scroll lands short. + onMaxScrollChanged: if (root.adding) scrollTo(maxScroll) + + // Not a Behavior: the wheel writes contentY too and must track directly. + NumberAnimation { + id: scrollAnim + target: scroller + property: "contentY" + duration: Style.duration(160) + easing.type: Easing.OutCubic + } + + WheelHandler { + acceptedDevices: PointerDevice.Mouse | PointerDevice.TouchPad + onWheel: function(event) { + var d = event.pixelDelta.y !== 0 ? event.pixelDelta.y : event.angleDelta.y / 120 * Style.space(40) + scroller.contentY -= d + scroller.clamp() + } + } + + Column { + id: content + width: scroller.width + spacing: Style.spacing.panelGap + + HeroTitle { + id: hero + width: parent.width + caption: root.hereLine + // Accent while scrubbed, so a shifted time is never taken for now. + captionColor: root.scrubMinutes !== 0 ? Color.accent : root.dim + captionClickable: root.focusIndex >= 0 + foreground: root.foreground + dim: root.dim + fontFamily: root.fontFamily + zoom: root.zoom + globeEnabled: root.globeEnabled + bigGlobeOpacity: root.bigGlobeOpacity + restLon: root.focusLon + markerShown: root.focusKnown + markerLat: root.focusLat + markerLon: root.focusLon + onCaptionClicked: root.focusOn(-1) + onGlobeClicked: function(slow) { root.setGlobeMode(!root.globeMode, slow) } + } + + // ---- stage + // The list and the globe share it; it grows with the zoom. Not + // clipped, so the globe can start from the header above it. + Item { + id: stage + width: parent.width + height: Math.max(1, listWrap.implicitHeight + + (root.globeStageHeight - listWrap.implicitHeight) * root.zoom) + + // Clipped, so knocked rows fall out of the panel. + Item { + anchors.fill: parent + clip: true + + Column { + id: listWrap + width: parent.width + spacing: Style.spacing.panelGap + + Column { + visible: root.zoom < 1 + width: parent.width + spacing: Style.spacing.md + + // The zone list, not clockRows: that ticks, and would + // rebuild every delegate mid-drag. + Repeater { + id: cityRows + model: root.zones + + CityRow { panel: root } + } + } + + CitySearch { + id: citySearch + visible: root.zoom < 1 + width: parent.width + options: root.zoneOptions + loading: root.zoneCatalogText === "" + offsetLabel: function(zoneId) { return root.utcLabelFor(zoneId) } + hasCursor: root.addSelected + foreground: root.foreground + dim: root.dim + fainter: root.fainter + fontFamily: root.fontFamily + onActiveChanged: if (active) root.loadCatalog() + onPicked: function(label, id) { root.addCity(id, label) } + onDismissed: Qt.callLater(function() { keyCatcher.forceActiveFocus() }) + + // Knocked aside last, after every row. + transform: Translate { + x: Model.knockX(root.zones.length, root.zoom, Style.space(95)) + y: Model.knockY(root.zones.length, root.zoom, root.knockFall) + } + } + } + } + + // ---- globe + // Loaded early on hover and kept for the whole flight, so reading + // its data never lands mid-animation. + Loader { + id: globeLoader + active: root.globeEnabled && (root.globeMode || root.zoom > 0 || hero.iconHovered) + visible: root.zoom > 0 + opacity: root.bigGlobeOpacity + width: parent.width + height: root.globeStageHeight + source: "Globe.qml" + + // The disc's center, above the globe's footer and jump bar. + readonly property real discCX: width / 2 + readonly property real discCY: item ? (height - item.footerHeight - item.jumpHeight) / 2 : height / 2 + readonly property real discR: item && item.radius > 0 ? item.radius : 1 + readonly property real startScale: root.heroDiscRadius / discR + readonly property real zoomScale: startScale + (1 - startScale) * root.zoom + + // Scaled about the disc, then carried from the little globe. + transform: [ + Scale { + origin.x: globeLoader.discCX + origin.y: globeLoader.discCY + xScale: globeLoader.zoomScale + yScale: globeLoader.zoomScale + }, + Translate { + x: (root.heroCenterX - globeLoader.discCX) * (1 - root.zoom) + y: (root.heroCenterY - globeLoader.discCY) * (1 - root.zoom) + } + ] + + onLoaded: { + item.foreground = Qt.binding(function() { return root.foreground }) + item.dim = Qt.binding(function() { return root.dim }) + item.fainter = Qt.binding(function() { return root.fainter }) + item.daylightMarker = Qt.binding(function() { return root.daylightMarker }) + item.moonPhase = Qt.binding(function() { return root.moonPhase }) + item.fontFamily = Qt.binding(function() { return root.fontFamily }) + item.hour24 = Qt.binding(function() { return root.hour24 }) + item.trackedNames = Qt.binding(function() { return root.trackedNames }) + item.trackedCities = Qt.binding(function() { return root.trackedCities }) + item.sessionCities = Qt.binding(function() { return root.sessionPlaces }) + item.homeRow = Qt.binding(function() { + var home = root.homePlace + return home ? [root.homeCity, root.localZone, home.lat, home.lon, 0] : [] + }) + item.offsetMode = Qt.binding(function() { return root.offsetMode }) + item.homeOffsetMinutes = Qt.binding(function() { return root.localOffsetMinutes }) + item.smoothMotion = Qt.binding(function() { return root.smoothMotion }) + item.transitioning = Qt.binding(function() { return !root.zoomIdle }) + item.zoomLevel = Qt.binding(function() { return root.zoom }) + // The footer and jump bar arrive once the globe has landed. + item.chromeOpacity = Qt.binding(function() { return Util.clamp((root.zoom - 0.74) / 0.26, 0, 1) }) + item.jumpOptions = Qt.binding(function() { return root.allZoneOptions }) + item.offsetModeToggleRequested.connect(function() { root.toggleOffsetMode() }) + item.jumpRequested.connect(function(label, zone) { root.addSessionCity(label, zone) }) + item.exitRequested.connect(function() { root.setGlobeMode(false, false) }) + item.jumpDismissed.connect(function() { Qt.callLater(function() { keyCatcher.forceActiveFocus() }) }) + item.citySelected.connect(function(label, zone) { root.focusFromGlobe(label, zone) }) + item.cityTapped.connect(function(label, zone) { root.claimHome(label, zone) }) + // A cold start can finish loading after the mode switched on. + if (root.globeMode) root.showFocusOnGlobe() + } + } + } + } + } + } + } +} diff --git a/shell/plugins/panels/elsewhen/Sun.js b/shell/plugins/panels/elsewhen/Sun.js new file mode 100644 index 000000000000..c7edf9b2f4a7 --- /dev/null +++ b/shell/plugins/panels/elsewhen/Sun.js @@ -0,0 +1,110 @@ +.pragma library + +.import "GlobeModel.js" as Solar + +// Sunrise and sunset for a place on its own day, from the globe's own +// subsolarPoint so the strip and the terminator cannot disagree. + +var DEG = Math.PI / 180 + +// Refraction plus the sun's radius, the figure published sunrise tables use. +var HORIZON = -0.833 + +function wrap180(deg) { + return ((deg + 540) % 360) - 180 +} + +// Local solar noon. The subsolar meridian moves 15 degrees an hour, so three +// corrections take the residual below a second. +function solarNoonMs(lon, nearMs) { + var t = nearMs + for (var i = 0; i < 3; i++) { + var sub = Solar.subsolarPoint(t) + t += wrap180(sub.lon - lon) / 15 * 3600000 + } + return t +} + +// The zone's own local midnight, as a UTC instant. +function localMidnightMs(ms, offsetMinutes) { + var local = ms + offsetMinutes * 60000 + return Math.floor(local / 86400000) * 86400000 - offsetMinutes * 60000 +} + +// Sunrise and sunset for the local day containing `ms`, as instants and as +// minutes from local midnight. The minutes may fall outside 0..1440 for a zone +// far from its own sun. `kind` is "normal", "midnightSun" or "polarNight". +function sunTimes(lat, lon, ms, offsetMinutes) { + var midnight = localMidnightMs(ms, offsetMinutes) + var noon = solarNoonMs(lon, midnight + 43200000) + var dec = Solar.subsolarPoint(noon).lat + + var cosH = (Math.sin(HORIZON * DEG) - Math.sin(lat * DEG) * Math.sin(dec * DEG)) + / (Math.cos(lat * DEG) * Math.cos(dec * DEG)) + + if (cosH <= -1) + return { kind: "midnightSun", noonMs: noon, riseMs: null, setMs: null, + riseMinutes: null, setMinutes: null, dayMinutes: 1440 } + if (cosH >= 1) + return { kind: "polarNight", noonMs: noon, riseMs: null, setMs: null, + riseMinutes: null, setMinutes: null, dayMinutes: 0 } + + var halfDayMs = Math.acos(cosH) / DEG / 15 * 3600000 + var riseMs = noon - halfDayMs + var setMs = noon + halfDayMs + + return { + kind: "normal", + noonMs: noon, + riseMs: riseMs, + setMs: setMs, + riseMinutes: (riseMs - midnight) / 60000, + setMinutes: (setMs - midnight) / 60000, + dayMinutes: (setMs - riseMs) / 60000 + } +} + +// The lit parts of a 24-hour strip as 0..1 spans. The day is also drawn a day +// either side, so a sunset past midnight lights the start of the bar too. +function litSpans(times) { + if (!times) return [] + if (times.kind === "polarNight") return [] + if (times.kind === "midnightSun") return [{ x0: 0, x1: 1 }] + + var out = [] + for (var shift = -1440; shift <= 1440; shift += 1440) { + var a = Math.max(0, Math.min(1440, times.riseMinutes + shift)) + var b = Math.max(0, Math.min(1440, times.setMinutes + shift)) + if (b > a) out.push({ x0: a / 1440, x1: b / 1440 }) + } + return out +} + +// Where an event's tick goes, or null when it falls off this bar. +function eventMark(minutes) { + if (minutes === null || minutes === undefined) return null + if (minutes < 0 || minutes > 1440) return null + return minutes / 1440 +} + +// Daylight at `minutes`, read from the same three days litSpans draws. +function litAt(times, minutes) { + if (!times) return false + if (times.kind === "midnightSun") return true + if (times.kind === "polarNight") return false + for (var shift = -1440; shift <= 1440; shift += 1440) + if (minutes >= times.riseMinutes + shift && minutes < times.setMinutes + shift) + return true + return false +} + +if (typeof module !== "undefined") { + module.exports = { + solarNoonMs: solarNoonMs, + localMidnightMs: localMidnightMs, + sunTimes: sunTimes, + litSpans: litSpans, + eventMark: eventMark, + litAt: litAt + } +} diff --git a/shell/plugins/panels/elsewhen/cities.json b/shell/plugins/panels/elsewhen/cities.json new file mode 100644 index 000000000000..90ef4e642725 --- /dev/null +++ b/shell/plugins/panels/elsewhen/cities.json @@ -0,0 +1 @@ +[["Pago Pago","Pacific/Pago_Pago",-14.28,-170.7,3],["Honolulu","Pacific/Honolulu",21.31,-157.86,2],["Anchorage","America/Anchorage",61.22,-149.9,2],["Los Angeles","America/Los_Angeles",34.05,-118.24,1],["Vancouver","America/Vancouver",49.25,-123.12,2],["Denver","America/Denver",39.74,-104.98,2],["Phoenix","America/Phoenix",33.45,-112.07,3],["Mexico City","America/Mexico_City",19.43,-99.13,1],["Chicago","America/Chicago",41.85,-87.65,1],["New York","America/New_York",40.71,-74.01,1],["Toronto","America/Toronto",43.71,-79.4,2],["Bogota","America/Bogota",4.61,-74.08,2],["Lima","America/Lima",-12.04,-77.03,2],["Halifax","America/Halifax",44.64,-63.58,3],["Caracas","America/Caracas",10.49,-66.88,3],["Santiago","America/Santiago",-33.46,-70.65,2],["Sao Paulo","America/Sao_Paulo",-23.55,-46.64,1],["Buenos Aires","America/Argentina/Buenos_Aires",-34.61,-58.38,1],["Praia","Atlantic/Cape_Verde",14.93,-23.51,3],["Reykjavik","Atlantic/Reykjavik",64.14,-21.9,3],["London","Europe/London",51.51,-0.13,1],["Accra","Africa/Accra",5.56,-0.2,3],["Lisbon","Europe/Lisbon",38.73,-9.15,2],["Paris","Europe/Paris",48.85,2.35,1],["Berlin","Europe/Berlin",52.52,13.41,1],["Madrid","Europe/Madrid",40.42,-3.7,2],["Lagos","Africa/Lagos",6.45,3.39,2],["Rome","Europe/Rome",41.89,12.51,2],["Cairo","Africa/Cairo",30.06,31.25,1],["Athens","Europe/Athens",37.98,23.73,2],["Johannesburg","Africa/Johannesburg",-26.2,28.04,1],["Kyiv","Europe/Kyiv",50.45,30.52,2],["Moscow","Europe/Moscow",55.75,37.62,1],["Istanbul","Europe/Istanbul",41.01,28.95,1],["Nairobi","Africa/Nairobi",-1.28,36.82,2],["Riyadh","Asia/Riyadh",24.69,46.72,2],["Tehran","Asia/Tehran",35.69,51.42,2],["Dubai","Asia/Dubai",25.08,55.31,1],["Kabul","Asia/Kabul",34.53,69.17,3],["Karachi","Asia/Karachi",24.86,67.01,2],["Delhi","Asia/Kolkata",28.65,77.23,1],["Kathmandu","Asia/Kathmandu",27.7,85.32,3],["Dhaka","Asia/Dhaka",23.71,90.41,2],["Almaty","Asia/Almaty",43.25,76.91,3],["Yangon","Asia/Yangon",16.81,96.16,3],["Bangkok","Asia/Bangkok",13.75,100.5,1],["Jakarta","Asia/Jakarta",-6.21,106.85,2],["Singapore","Asia/Singapore",1.29,103.85,1],["Shanghai","Asia/Shanghai",31.22,121.46,1],["Hong Kong","Asia/Hong_Kong",22.28,114.17,2],["Perth","Australia/Perth",-31.95,115.86,2],["Seoul","Asia/Seoul",37.57,126.98,1],["Tokyo","Asia/Tokyo",35.69,139.69,1],["Darwin","Australia/Darwin",-12.46,130.84,3],["Adelaide","Australia/Adelaide",-34.93,138.6,3],["Sydney","Australia/Sydney",-33.87,151.21,1],["Brisbane","Australia/Brisbane",-27.47,153.03,3],["Noumea","Pacific/Noumea",-22.27,166.45,3],["Auckland","Pacific/Auckland",-36.85,174.76,1],["Suva","Pacific/Fiji",-18.14,178.43,3],["Apia","Pacific/Apia",-13.83,-171.77,3],["Kiritimati","Pacific/Kiritimati",1.87,-157.43,3],["St John's","America/St_Johns",47.56,-52.71,3],["Copenhagen","Europe/Copenhagen",55.68,12.57,2],["Stockholm","Europe/Stockholm",59.33,18.07,2],["Oslo","Europe/Oslo",59.91,10.75,2],["Amsterdam","Europe/Amsterdam",52.37,4.89,2],["Brussels","Europe/Brussels",50.85,4.35,3],["Zurich","Europe/Zurich",47.37,8.55,2],["Vienna","Europe/Vienna",48.21,16.37,2],["Warsaw","Europe/Warsaw",52.23,21.01,2],["Prague","Europe/Prague",50.09,14.42,2],["Dublin","Europe/Dublin",53.33,-6.25,2],["Helsinki","Europe/Helsinki",60.17,24.94,3]] \ No newline at end of file diff --git a/shell/plugins/panels/elsewhen/manifest.json b/shell/plugins/panels/elsewhen/manifest.json new file mode 100644 index 000000000000..53bee8cfd14d --- /dev/null +++ b/shell/plugins/panels/elsewhen/manifest.json @@ -0,0 +1,78 @@ +{ + "schemaVersion": 1, + "id": "omarchy.elsewhen", + "name": "Elsewhen", + "version": "1.0.0", + "author": "Jason Fried", + "license": "MIT", + "description": "A world clock for the Omarchy shell: the time in several cities at once, with a spinnable globe.", + "kinds": [ + "bar-widget" + ], + "entryPoints": { + "barWidget": "Panel.qml" + }, + "barWidget": { + "displayName": "Elsewhen", + "description": "A world clock: one row per city, and a globe.", + "category": "Time", + "aliases": [ + "worldclock", + "world clock", + "timezones" + ], + "allowMultiple": false, + "defaultSection": "right", + "defaults": { + "zones": "", + "offsetMode": "home", + "units": "", + "globeEnabled": true, + "homeCity": "", + "smoothMotion": true + }, + "schema": [ + { + "key": "zones", + "type": "string", + "label": "Zones (Label|IANA name, comma separated; blank seeds on first run)", + "defaultValue": "" + }, + { + "key": "hour24", + "type": "boolean", + "label": "24-hour time (unset follows the system)" + }, + { + "key": "offsetMode", + "type": "string", + "label": "Row offsets: home (distance from you) or utc", + "defaultValue": "home" + }, + { + "key": "units", + "type": "string", + "label": "Temperature units (F or C; blank follows the system)", + "defaultValue": "" + }, + { + "key": "globeEnabled", + "type": "boolean", + "label": "Globe mode (tap the hero globe)", + "defaultValue": true + }, + { + "key": "homeCity", + "type": "string", + "label": "Your city (blank = from the system time zone)", + "defaultValue": "" + }, + { + "key": "smoothMotion", + "type": "boolean", + "label": "Drop labels and detail while the globe moves", + "defaultValue": true + } + ] + } +} diff --git a/shell/plugins/panels/elsewhen/world.json b/shell/plugins/panels/elsewhen/world.json new file mode 100644 index 000000000000..63f3f1653d12 --- /dev/null +++ b/shell/plugins/panels/elsewhen/world.json @@ -0,0 +1 @@ +[[-59.6,-80.0,-60.2,-81.0,-66.3,-80.3,-59.6,-80.0],[-159.2,-79.5,-163.7,-78.6,-161.2,-78.4,-159.2,-79.5],[-45.2,-78.0,-43.9,-78.5,-43.3,-80.0,-50.5,-81.0,-54.2,-80.6,-48.7,-78.0,-45.2,-78.0],[-121.2,-73.5,-118.7,-73.5,-122.6,-73.7,-121.2,-73.5],[-125.6,-73.5,-124.0,-73.9,-127.3,-73.5,-125.6,-73.5],[-99.0,-71.9,-96.2,-72.5,-102.3,-71.9,-99.0,-71.9],[-68.5,-71.0,-68.8,-72.2,-71.1,-72.5,-75.0,-71.7,-72.1,-71.2,-71.7,-69.5,-70.3,-68.9,-68.5,-71.0],[-58.6,-64.2,-62.0,-64.8,-62.6,-65.5,-62.1,-66.2,-65.7,-68.0,-61.8,-70.7,-60.8,-73.7,-70.6,-76.6,-77.2,-76.7,-73.7,-77.9,-77.9,-78.4,-78.0,-79.2,-58.2,-83.2,-49.8,-81.7,-42.8,-82.1,-28.5,-80.3,-29.7,-79.3,-35.6,-79.5,-35.8,-78.3,-17.5,-75.1,-15.7,-74.5,-16.5,-73.9,-15.4,-73.1,-10.3,-71.3,-7.4,-71.7,-6.9,-70.9,-0.2,-71.6,7.7,-69.9,10.8,-70.8,13.4,-70.0,27.1,-70.5,32.0,-69.7,33.9,-68.5,38.6,-69.8,54.5,-65.8,61.4,-68.0,68.9,-67.9,69.7,-69.2,67.8,-70.3,69.1,-70.7,67.9,-71.9,69.9,-72.3,73.9,-69.9,77.6,-69.5,82.8,-67.2,86.8,-67.2,88.0,-66.2,89.7,-67.2,95.8,-67.4,99.7,-67.2,102.8,-65.6,106.2,-66.9,113.6,-65.9,119.8,-67.3,134.8,-66.2,135.1,-65.3,137.5,-67.0,145.5,-66.9,148.8,-68.4,154.3,-68.6,161.6,-70.6,171.2,-71.7,169.3,-73.7,166.1,-74.4,163.6,-76.2,164.7,-78.2,167.0,-78.8,161.8,-79.2,159.8,-80.9,169.4,-83.8,180,-84.7,180,-90,-180,-90,-180,-84.7,-179.1,-84.1,-170.0,-83.9,-158.1,-85.4,-143.1,-85.0,-153.6,-83.7,-152.9,-82.0,-156.8,-81.1,-150.6,-81.3,-146.4,-80.3,-155.3,-79.1,-158.1,-78.0,-158.4,-76.9,-151.3,-77.4,-146.1,-76.5,-146.2,-75.4,-135.2,-74.3,-121.1,-74.5,-113.9,-73.7,-112.3,-74.7,-107.6,-75.2,-100.1,-74.9,-102.5,-74.1,-103.7,-72.6,-96.3,-73.6,-90.1,-73.3,-89.2,-72.6,-81.5,-73.9,-80.3,-73.1,-74.9,-73.9,-67.4,-72.5,-68.5,-69.7,-67.4,-68.1,-67.7,-67.3,-63.0,-64.6,-57.2,-63.5,-58.6,-64.2],[-67.8,-53.9,-65.0,-54.7,-69.2,-55.5,-74.7,-52.8,-71.1,-54.1,-69.3,-52.5,-67.8,-53.9],[-58.5,-51.1,-58.0,-51.9,-61.2,-51.9,-58.5,-51.1],[145.4,-40.8,148.3,-40.9,147.9,-43.2,146.0,-43.5,144.7,-41.2,145.4,-40.8],[173.0,-40.9,174.2,-41.3,173.1,-43.9,171.5,-44.2,169.3,-46.6,166.7,-46.2,167.0,-45.1,173.0,-40.9],[174.6,-36.2,176.8,-37.9,178.5,-37.7,175.2,-41.7,174.9,-39.9,173.8,-39.5,174.7,-37.4,172.6,-34.5,174.6,-36.2],[50.1,-13.6,50.4,-15.7,49.7,-15.7,47.1,-24.9,45.4,-25.6,44.0,-25.0,43.3,-22.1,44.4,-20.1,44.4,-16.2,47.7,-14.6,49.2,-12.0,50.1,-13.6],[143.6,-13.8,145.4,-15.0,146.4,-19.0,148.8,-20.4,153.1,-26.1,152.9,-31.6,150.0,-37.4,146.3,-39.0,145.0,-37.9,143.6,-38.8,140.6,-38.0,139.6,-36.1,138.1,-35.6,138.2,-34.4,136.8,-35.3,137.8,-32.9,136.0,-34.9,134.3,-32.6,131.3,-31.5,126.1,-32.2,123.7,-33.9,119.9,-34.0,118.0,-35.1,115.0,-34.2,115.7,-31.6,113.3,-26.1,114.2,-26.3,113.4,-24.4,114.1,-21.8,114.2,-22.5,116.7,-20.7,120.9,-19.7,123.0,-16.4,123.9,-17.1,123.5,-16.6,125.7,-14.2,127.1,-13.8,129.6,-15.0,130.6,-12.5,132.6,-12.1,131.8,-11.3,132.4,-11.1,135.3,-12.2,136.5,-11.9,137.0,-12.4,135.5,-15.0,140.2,-17.7,141.3,-16.4,142.5,-10.7,143.6,-13.8],[124.4,-10.1,123.5,-10.2,125.1,-8.7,127.3,-8.4,124.4,-10.1],[108.6,-6.8,110.8,-6.5,115.7,-8.4,105.4,-6.9,106.1,-5.9,108.6,-6.8],[152.0,-5.5,150.2,-6.3,148.3,-5.7,150.8,-5.5,151.5,-4.2,152.3,-4.3,152.0,-5.5],[134.1,-1.2,134.4,-2.8,135.5,-3.4,138.3,-1.7,144.6,-3.9,147.6,-6.1,147.2,-7.4,150.7,-10.6,147.9,-10.1,144.7,-7.6,142.6,-9.3,139.1,-8.1,137.6,-8.4,138.7,-7.3,137.9,-5.4,133.7,-3.5,133.0,-4.1,132.0,-2.8,133.7,-2.2,130.5,-0.9,132.4,-0.4,134.1,-1.2],[125.2,1.4,123.7,0.2,120.2,0.2,120.9,-1.4,123.3,-0.6,121.5,-1.9,123.2,-5.3,122.2,-5.3,122.7,-4.5,121.5,-4.6,121.0,-2.6,120.3,-2.9,120.4,-5.5,119.4,-5.4,119.5,-3.5,118.8,-2.8,120.0,0.6,120.9,1.3,125.2,1.4],[128.7,1.1,128.1,-0.9,127.4,1.0,127.9,2.2,128.7,1.1],[105.8,-5.9,102.6,-4.2,95.3,5.5,97.5,5.2,103.8,0.1,103.4,-0.7,106.1,-3.1,105.8,-5.9],[117.9,1.8,119.0,0.9,117.8,0.8,116.1,-4.0,110.2,-2.9,109.1,-0.5,109.7,2.0,111.2,1.9,111.4,2.7,113.0,3.1,116.7,6.9,119.2,5.4,117.3,3.2,117.9,1.8],[126.4,8.4,126.5,7.2,126.2,6.3,125.8,7.3,125.4,6.8,125.4,5.6,124.2,6.2,123.6,7.8,121.9,7.2,123.5,8.7,125.5,9.0,125.4,9.8,126.4,8.4],[81.2,6.2,79.9,6.8,80.1,9.8,81.8,7.5,81.2,6.2],[118.5,9.3,117.2,8.4,119.5,11.4,118.5,9.3],[121.3,18.5,122.2,18.5,122.5,17.1,121.7,14.3,124.0,13.8,124.1,12.5,120.6,13.9,121.0,14.5,120.1,15.0,119.9,16.4,121.3,18.5],[-72.6,19.9,-68.3,18.6,-70.7,18.4,-71.4,17.6,-74.5,18.3,-72.3,18.7,-73.4,19.6,-72.6,19.9],[-79.7,22.8,-74.2,20.3,-77.8,19.9,-77.1,20.4,-78.7,21.6,-81.8,22.6,-85.0,21.9,-82.3,23.2,-79.7,22.8],[121.2,22.8,120.7,22.0,120.1,23.6,121.5,25.3,121.2,22.8],[15.5,38.2,15.1,36.6,12.4,37.6,15.5,38.2],[141.0,37.1,140.3,35.1,137.2,34.6,135.8,33.5,135.1,34.6,131.0,33.9,132.0,33.1,131.3,31.5,130.2,31.4,130.4,32.3,129.4,33.3,132.6,35.4,135.7,35.5,136.7,37.3,137.4,36.8,139.4,38.2,139.9,40.6,141.4,41.4,141.9,39.2,141.0,37.1],[143.9,44.2,145.3,44.4,145.5,43.3,143.2,42.0,141.6,42.7,141.1,41.6,140.0,41.6,139.8,42.6,141.4,43.4,142.0,45.6,143.9,44.2],[-123.5,48.5,-125.7,48.8,-128.4,50.8,-125.8,50.3,-123.5,48.5],[-56.1,50.7,-56.8,49.8,-53.5,49.2,-53.8,48.5,-53.1,48.7,-52.6,47.5,-53.1,46.7,-54.2,46.8,-54.2,47.8,-55.4,46.9,-56.3,47.6,-59.3,47.6,-57.4,50.7,-55.4,51.6,-56.1,50.7],[143.6,50.7,144.7,49.0,143.2,49.3,142.6,47.9,143.5,46.1,142.7,46.7,142.1,46.0,141.6,51.9,142.2,54.2,143.6,50.7],[-6.8,52.3,-10.0,51.8,-9.2,52.9,-9.7,53.9,-6.7,55.2,-5.7,54.6,-6.8,52.3],[-3.0,58.6,-4.1,57.6,-2.0,57.7,-3.1,56.0,1.7,52.7,1.4,51.3,-5.2,50.0,-5.8,50.2,-3.4,51.4,-5.3,52.0,-4.2,52.3,-4.6,53.5,-2.9,54.0,-4.8,54.8,-5.0,55.8,-5.6,55.3,-6.1,56.8,-5.0,58.6,-3.0,58.6],[-85.2,65.7,-80.1,63.7,-87.2,63.5,-85.9,65.7,-85.2,65.7],[-14.5,66.5,-14.7,65.8,-13.6,65.1,-18.7,63.5,-22.8,64.0,-21.8,64.4,-24.0,64.9,-22.2,65.4,-24.3,65.6,-22.1,66.4,-20.6,65.7,-14.5,66.5],[-175.0,66.6,-171.9,66.9,-169.9,66.0,-172.5,65.4,-173.0,64.3,-178.4,65.4,-178.7,66.1,-179.9,65.9,-180,65.0,-180,69.0,-174.9,67.2,-175.0,66.6],[-95.6,69.1,-99.8,69.4,-98.2,70.1,-95.6,69.1],[-90.5,69.5,-90.6,68.5,-89.2,69.3,-87.4,67.2,-85.6,68.8,-85.5,69.9,-82.6,69.7,-81.3,69.2,-82.0,68.1,-81.3,67.6,-83.3,66.4,-85.8,66.6,-87.3,64.8,-93.2,62.0,-94.7,58.9,-93.2,58.8,-92.3,57.1,-82.3,55.1,-82.1,53.3,-79.9,51.2,-78.6,52.6,-79.8,54.7,-76.5,56.5,-78.5,58.8,-77.3,59.9,-78.1,62.3,-73.8,62.4,-69.6,61.1,-69.3,59.0,-67.6,58.2,-64.6,60.3,-61.4,57.0,-61.8,56.3,-57.3,54.6,-55.8,53.3,-55.7,52.1,-60.0,50.2,-66.4,50.2,-71.1,46.8,-65.1,49.2,-64.2,48.7,-65.1,48.1,-64.5,46.2,-61.5,45.9,-60.5,47.0,-59.8,45.9,-65.4,43.5,-66.2,44.5,-64.4,45.3,-67.1,45.1,-70.7,43.0,-70.0,41.6,-73.7,40.9,-71.9,40.9,-74.0,40.8,-74.9,38.9,-75.5,39.5,-75.1,38.4,-75.9,37.2,-76.3,39.2,-76.3,38.1,-77.0,38.2,-75.7,35.6,-81.3,31.4,-80.1,26.9,-80.4,25.2,-81.7,25.9,-84.1,30.1,-89.2,30.3,-89.2,29.3,-90.2,29.1,-93.8,29.7,-96.6,28.3,-97.4,27.4,-97.9,22.4,-96.3,19.3,-94.4,18.1,-92.0,18.7,-90.8,19.3,-90.3,21.0,-87.1,21.5,-88.9,15.9,-83.4,15.3,-83.8,11.1,-81.4,8.8,-79.6,9.6,-76.8,8.6,-74.9,11.1,-71.8,12.4,-71.1,12.1,-71.9,11.4,-71.7,9.1,-71.4,11.0,-69.9,12.2,-68.2,10.6,-64.9,10.1,-61.9,10.7,-62.4,9.9,-57.1,6.0,-54.0,5.8,-51.3,4.2,-50.0,1.7,-50.4,-0.1,-48.6,-0.2,-48.6,-1.2,-47.8,-0.6,-44.9,-1.6,-44.6,-2.7,-40.0,-2.9,-35.6,-5.1,-34.7,-7.3,-35.1,-9.0,-38.7,-13.1,-39.3,-17.9,-40.9,-21.9,-47.6,-24.9,-48.9,-28.7,-53.8,-34.4,-56.2,-34.9,-58.4,-33.9,-56.8,-36.9,-59.2,-38.7,-62.3,-38.8,-62.7,-41.0,-65.1,-41.1,-65.0,-42.1,-63.5,-42.6,-65.2,-43.5,-65.6,-45.0,-67.3,-45.6,-67.6,-46.3,-65.6,-47.2,-66.0,-48.1,-69.1,-50.7,-68.2,-52.3,-70.8,-52.9,-71.0,-53.8,-74.9,-52.3,-75.6,-48.7,-74.1,-46.9,-75.6,-46.6,-74.4,-44.1,-73.2,-44.5,-72.7,-42.4,-74.3,-43.2,-73.2,-39.3,-73.6,-37.2,-71.4,-32.4,-70.2,-19.8,-71.5,-17.4,-76.0,-14.6,-79.8,-7.2,-81.2,-6.1,-81.4,-4.7,-79.8,-2.7,-81.0,-2.2,-80.9,-1.1,-77.1,3.8,-78.2,8.3,-79.6,8.9,-80.9,7.2,-85.7,9.9,-87.5,13.3,-91.2,13.9,-94.7,16.2,-96.6,15.7,-103.5,18.3,-105.5,19.9,-106.0,22.8,-112.2,29.0,-113.1,31.2,-114.8,31.8,-114.7,30.2,-109.4,23.2,-110.0,22.8,-112.2,24.7,-112.3,26.0,-115.1,27.7,-114.2,28.6,-117.3,33.0,-120.6,34.6,-124.4,40.3,-123.9,45.5,-124.7,48.2,-123.1,48.0,-122.6,47.1,-122.8,49.0,-127.4,50.8,-127.9,52.3,-129.1,52.8,-134.1,58.1,-147.1,60.9,-151.7,59.2,-150.6,61.3,-154.0,59.4,-153.3,58.9,-154.2,58.1,-158.4,56.0,-164.8,54.4,-157.7,57.6,-157.0,58.9,-162.0,58.7,-161.9,59.6,-163.8,59.8,-166.1,61.5,-164.6,63.1,-160.8,63.8,-161.5,64.4,-160.8,64.8,-165.0,64.4,-168.1,65.7,-164.5,66.6,-161.7,66.1,-166.8,68.4,-156.6,71.4,-136.5,68.9,-128.1,70.5,-125.8,69.5,-124.4,70.2,-124.3,69.4,-121.5,69.8,-113.9,68.4,-115.3,67.9,-108.9,67.4,-107.8,67.9,-108.8,68.3,-108.2,68.7,-106.2,68.8,-101.5,67.6,-98.4,67.8,-97.7,68.6,-96.1,68.2,-96.1,67.3,-94.2,69.1,-96.5,70.1,-96.4,71.2,-95.2,71.9,-91.5,70.2,-92.4,69.7,-90.5,69.5],[-114.2,73.1,-114.7,72.7,-109.9,73.0,-108.2,71.7,-107.7,72.1,-108.4,73.1,-106.5,73.1,-104.5,71.0,-101.1,69.6,-102.7,69.5,-102.4,68.8,-113.3,68.5,-117.3,70.0,-112.4,70.4,-117.9,70.5,-118.4,70.9,-116.1,71.3,-119.4,71.6,-117.9,72.7,-114.2,73.1],[-86.6,73.2,-85.8,72.5,-82.3,73.8,-80.6,72.7,-80.7,72.1,-77.8,72.7,-74.1,71.3,-72.2,71.6,-67.0,69.2,-68.8,68.7,-61.9,66.9,-63.9,65.0,-68.0,66.3,-64.7,63.4,-65.0,62.7,-68.8,63.7,-66.2,61.9,-74.8,64.7,-77.7,64.2,-78.6,64.6,-77.9,65.3,-74.0,65.5,-72.9,67.7,-79.0,70.2,-84.9,70.0,-89.9,71.2,-89.4,73.1,-85.8,73.8,-86.6,73.2],[-100.4,73.8,-97.4,73.8,-98.1,73.0,-96.5,72.6,-96.7,71.7,-99.3,71.4,-102.5,72.5,-100.4,72.7,-101.5,73.4,-100.4,73.8],[143.6,73.2,139.9,73.4,142.1,73.9,143.6,73.2],[-93.2,72.8,-95.4,72.1,-96.0,73.4,-94.5,74.1,-90.5,73.9,-93.2,72.8],[-120.5,71.4,-123.1,70.9,-125.9,71.9,-123.9,73.7,-124.9,74.3,-115.5,73.5,-119.2,72.5,-120.5,71.4],[-93.6,75.0,-96.8,74.9,-94.9,75.6,-93.6,75.0],[145.1,75.6,144.3,74.8,139.0,74.6,137.0,75.3,138.8,76.1,145.1,75.6],[-98.5,76.7,-97.7,76.3,-98.2,75,-102.5,75.6,-102.6,76.3,-98.5,76.7],[-108.2,76.2,-105.7,75.5,-112.2,74.4,-113.9,74.7,-111.8,75.2,-117.7,75.2,-115.4,76.5,-109.1,75.5,-110.5,76.4,-108.2,76.2],[57.5,70.7,53.7,70.8,51.5,72.0,55.6,75.1,61.2,76.3,68.9,76.5,58.5,74.3,55.4,72.4,57.5,70.7],[-94.7,77.1,-89.2,75.6,-81.1,75.7,-79.8,74.9,-89.8,74.5,-97.1,76.8,-94.7,77.1],[-116.2,77.6,-117.1,76.5,-122.9,76.1,-116.2,77.6],[107.0,77.0,114.1,75.8,109.4,74.2,123.2,73.0,123.3,73.7,127.0,73.6,131.3,70.8,132.3,71.8,139.9,71.5,139.1,72.4,140.5,72.8,149.5,72.2,153.0,70.8,159.0,70.9,160.9,69.4,167.8,69.6,169.6,68.7,170.8,69.0,170.0,69.7,170.5,70.1,175.7,69.9,180,69.0,180,65.0,177.4,64.6,179.2,62.3,173.7,61.7,170.3,59.9,168.9,60.6,163.5,59.9,162.0,58.2,163.2,57.6,162.1,54.9,160.4,54.3,160.0,53.2,158.5,53.0,156.8,51.0,155.4,55.4,155.9,56.8,163.7,61.1,164.5,62.6,160.1,60.5,159.3,61.8,156.7,61.4,154.2,59.8,155.0,59.1,151.3,58.8,151.3,59.5,149.8,59.7,142.2,59.0,135.1,54.7,138.2,53.8,139.9,54.2,141.4,52.2,140.1,48.4,138.2,46.3,134.9,43.4,132.3,43.3,127.5,39.8,129.5,36.8,129.1,35.1,126.5,34.4,126.1,36.7,126.9,36.9,124.7,38.1,125.3,39.6,121.1,38.9,122.2,40.4,121.6,40.9,118.0,39.2,117.5,38.7,118.9,37.4,122.4,37.5,119.2,34.9,121.9,31.7,121.3,30.7,122.1,29.8,121.7,28.2,118.7,24.5,115.9,22.8,110.8,21.4,110.4,20.3,108.5,21.7,105.9,19.8,109.3,13.4,109.2,11.7,105.2,8.6,105.1,9.9,100.1,13.4,99.2,9.2,103.0,5.5,104.2,1.3,101.4,2.8,100.1,6.5,98.5,8.4,98.3,7.8,98.8,11.4,97.2,16.9,95.4,15.7,94.2,16.0,94.3,18.2,91.4,22.8,90.5,22.8,90.3,21.8,87.0,21.5,86.5,20.2,80.3,15.9,79.9,10.4,77.5,8.0,73.5,16.0,72.6,21.4,70.5,20.9,66.4,25.4,57.4,25.7,56.5,27.1,54.7,26.5,51.5,27.9,50.1,30.1,48.0,30.0,50.8,24.8,51.0,26.0,51.6,25.8,51.8,24.0,54.0,24.1,56.4,26.4,56.8,24.2,59.8,22.3,57.8,20.2,57.7,18.9,55.3,17.2,48.7,14.0,43.5,12.6,42.6,16.8,39.1,21.3,38.5,23.7,34.6,28.1,34.9,29.5,33.9,27.6,32.4,29.9,35.5,23.1,36.9,22.0,37.5,18.6,43.3,12.4,42.7,11.7,44.6,10.4,51.1,12.0,51.0,10.6,47.7,4.2,40.3,-2.6,39.2,-4.7,38.8,-6.5,40.5,-10.8,40.8,-14.7,39.5,-16.7,34.8,-19.8,35.6,-23.7,32.6,-25.7,32.2,-28.8,28.2,-32.8,25.8,-33.9,19.6,-34.8,18.4,-34.1,18.2,-31.7,15.2,-27.1,14.3,-22.1,11.8,-18.1,11.8,-15.8,13.7,-10.7,11.9,-5.0,8.8,-1.1,9.4,3.7,8.5,4.8,5.9,4.3,4.3,6.3,-2.0,4.7,-9.0,4.8,-12.4,7.3,-16.6,12.2,-17.6,14.7,-16.1,18.1,-17.0,21.9,-14.4,26.3,-9.6,29.9,-9.3,32.6,-5.9,35.8,-2.2,35.2,1.5,36.6,9.5,37.4,11.1,36.9,10.3,33.8,19.1,30.3,20.1,32.2,21.5,32.8,28.9,30.9,31.0,31.6,33.8,31.0,36.0,34.6,36.2,36.7,27.6,36.7,26.2,39.5,29.2,41.2,33.5,42.0,38.3,40.9,41.7,42.0,36.7,45.2,39.1,47.3,35.0,46.3,36.3,45.1,33.9,44.4,32.5,45.3,33.3,46.1,30.7,46.6,27.7,42.6,28.8,41.1,26.4,40.2,24.9,40.9,23.7,40.7,23.9,40.0,22.6,40.3,24.0,37.7,23.1,37.9,23.2,36.4,22.5,36.4,19.4,40.3,19.5,41.7,13.1,45.7,12.3,45.4,12.6,44.1,18.5,40.2,16.9,40.4,17.1,38.9,16.1,38.0,15.4,40.0,8.9,44.4,6.5,43.1,3.1,43.1,3.0,41.9,0.8,41.0,0.1,38.7,-2.1,36.7,-5.4,35.9,-6.5,36.9,-8.9,36.9,-9.4,43.0,-1.4,44.0,-1.2,46.0,-4.6,48.7,-1.6,48.6,-1.9,49.8,1.3,50.1,4.7,53.1,8.1,53.5,8.8,54.0,8.1,55.5,8.5,57.1,10.6,57.7,10.9,56.5,9.7,55.5,10.9,54.0,19.7,54.4,21.3,55.2,21.6,57.4,24.1,57.0,24.4,58.4,23.3,59.2,29.1,60.0,22.9,59.8,21.3,60.7,21.5,63.2,25.4,65.1,23.9,66.0,22.2,65.7,21.4,64.4,17.8,62.7,17.1,61.3,18.8,60.1,16.8,58.7,15.9,56.1,12.9,55.4,10.4,59.5,8.4,58.3,5.7,58.6,5.0,62.0,10.5,64.5,14.8,67.8,24.5,71.0,28.2,71.2,31.3,70.5,30.0,70.2,31.1,69.6,36.5,69.1,41.1,67.5,41.1,66.8,38.4,66.0,33.2,66.6,34.8,65.9,34.9,64.4,37.0,63.8,36.5,64.8,37.2,65.1,39.6,64.5,40.4,64.8,39.8,65.5,42.1,66.5,43.9,66.1,44.5,66.8,43.5,68.6,46.3,68.3,46.8,67.7,45.6,67.0,46.3,66.7,53.7,68.9,54.5,68.8,53.5,68.2,58.8,68.9,59.9,68.3,61.1,68.9,60.0,69.5,60.6,69.9,68.5,68.1,69.2,68.6,66.9,69.5,66.7,71.0,69.2,72.8,72.6,72.8,71.8,71.4,72.8,70.4,72.6,69.0,73.7,68.4,71.3,66.3,72.4,66.2,75.1,67.8,74.9,69.0,73.6,69.6,74.4,70.6,73.1,71.4,74.9,72.1,74.7,72.8,75.7,72.3,75.3,71.3,76.4,71.2,75.9,71.9,77.6,72.3,81.5,71.8,80.5,73.6,86.8,73.9,86.0,74.5,87.2,75.1,100.8,76.4,104.4,77.7,107.0,77.0],[24.7,77.9,20.7,77.7,22.9,78.5,24.7,77.9],[-95.8,78.1,-98.1,78.1,-98.6,78.9,-95.8,78.1],[-100.1,78.3,-99.7,77.9,-105.2,78.4,-104.2,78.7,-105.5,79.3,-100.1,78.3],[105.1,78.3,99.4,77.9,102.1,79.3,105.1,78.3],[18.3,79.7,21.5,79.0,15.9,76.8,10.4,79.7,18.3,79.7],[25.4,80.4,27.4,80.1,23.0,79.4,17.4,80.3,25.4,80.4],[51.1,80.5,47.6,80.0,44.8,80.6,51.1,80.5],[99.9,78.9,95.0,79.0,91.2,80.3,95.9,81.3,100.2,79.8,99.9,78.9],[-87.0,79.7,-85.8,79.3,-90.8,78.2,-96.7,80.2,-92.4,81.3,-87.0,79.7],[-68.5,83.1,-61.9,82.6,-67.7,81.5,-65.5,81.5,-71.2,79.8,-76.9,79.3,-75.4,78.5,-79.8,77.2,-77.9,76.8,-80.6,76.2,-89.5,76.5,-87.8,77.2,-88.3,77.9,-85.0,77.5,-88.0,78.4,-85.1,79.3,-86.9,80.3,-81.8,80.5,-87.6,80.5,-91.6,81.9,-79.3,83.1,-68.5,83.1],[-27.1,83.5,-20.8,82.7,-31.9,82.2,-22.1,81.7,-23.2,81.2,-15.8,81.9,-12.2,81.3,-20.0,80.2,-17.7,80.1,-19.7,78.8,-19.7,77.6,-18.5,77.0,-21.7,76.6,-19.8,76.1,-19.6,75.2,-20.7,75.2,-19.4,74.3,-23.6,73.3,-22.3,72.2,-24.8,72.3,-21.8,70.7,-25.5,71.4,-25.2,70.8,-26.4,70.2,-22.3,70.1,-39.8,65.5,-42.8,62.7,-42.4,61.9,-43.4,60.1,-48.3,60.9,-51.6,63.6,-54.0,67.2,-50.9,69.9,-54.7,69.6,-54.4,70.8,-51.4,70.6,-55.8,71.7,-54.7,72.6,-58.6,75.5,-68.5,76.1,-71.4,77.0,-66.8,77.4,-73.3,78.0,-65.7,79.4,-68.0,80.1,-62.2,81.3,-62.7,81.8,-50.4,82.4,-44.5,81.7,-46.8,82.6,-38.6,83.5,-27.1,83.5]] \ No newline at end of file diff --git a/shell/plugins/panels/monitor/Panel.qml b/shell/plugins/panels/monitor/Panel.qml index bec38820ba15..44f73f4a91b9 100644 --- a/shell/plugins/panels/monitor/Panel.qml +++ b/shell/plugins/panels/monitor/Panel.qml @@ -217,7 +217,7 @@ Panel { }) } - IpcHandler { + ShellIpc { target: "omarchy.monitor" function brightness(percent: string): string { return root.brightnessIpc(percent) } diff --git a/shell/plugins/panels/network/Panel.qml b/shell/plugins/panels/network/Panel.qml index 97729dcc5a35..87f160c1a34f 100644 --- a/shell/plugins/panels/network/Panel.qml +++ b/shell/plugins/panels/network/Panel.qml @@ -207,7 +207,7 @@ Panel { Qt.callLater(function() { root.refresh(true) }) } - IpcHandler { + ShellIpc { target: "omarchy.network" function open() { root.open() } @@ -965,14 +965,14 @@ Panel { id: connectionPhraseSwap PropertyAnimation { target: heroMeta; property: "opacity" - to: 0.0; duration: 180; easing.type: Easing.OutQuad + to: 0.0; duration: Style.duration(180); easing.type: Easing.OutQuad } ScriptAction { script: root.connectionPhraseIndex = (root.connectionPhraseIndex + 1) % root.connectionPhrases.length } PropertyAnimation { target: heroMeta; property: "opacity" - to: 1.0; duration: 260; easing.type: Easing.InQuad + to: 1.0; duration: Style.duration(260); easing.type: Easing.InQuad } } @@ -1472,10 +1472,10 @@ Panel { opacity: root.bandPillsVisible ? 1 : 0 Behavior on height { - NumberAnimation { duration: 140; easing.type: Easing.OutCubic } + NumberAnimation { duration: Style.duration(140); easing.type: Easing.OutCubic } } Behavior on opacity { - NumberAnimation { duration: 140; easing.type: Easing.OutCubic } + NumberAnimation { duration: Style.duration(140); easing.type: Easing.OutCubic } } Row { diff --git a/shell/plugins/panels/power/Panel.qml b/shell/plugins/panels/power/Panel.qml index b1c34da26f24..80b8ff672dfe 100644 --- a/shell/plugins/panels/power/Panel.qml +++ b/shell/plugins/panels/power/Panel.qml @@ -174,7 +174,7 @@ Panel { if (root.bar && root.bar.shell) root.bar.shell.updateEntryInline(root.moduleName, root.settings) } - IpcHandler { + ShellIpc { target: "omarchy.power" function open() { root.open() } @@ -246,7 +246,7 @@ Panel { id: phraseSwap PropertyAnimation { target: heroStatus; property: "opacity" - to: 0.0; duration: 180; easing.type: Easing.OutQuad + to: 0.0; duration: Style.duration(180); easing.type: Easing.OutQuad } ScriptAction { script: { @@ -256,7 +256,7 @@ Panel { } PropertyAnimation { target: heroStatus; property: "opacity" - to: 1.0; duration: 260; easing.type: Easing.InQuad + to: 1.0; duration: Style.duration(260); easing.type: Easing.InQuad } } @@ -333,7 +333,7 @@ Panel { anchors.left: parent.left anchors.verticalCenter: parent.verticalCenter - Behavior on color { ColorAnimation { duration: 200 } } + Behavior on color { ColorAnimation { duration: Style.duration(200) } } } Column { @@ -380,7 +380,7 @@ Panel { anchors.right: parent.right anchors.verticalCenter: parent.verticalCenter - Behavior on color { ColorAnimation { duration: 200 } } + Behavior on color { ColorAnimation { duration: Style.duration(200) } } } } @@ -405,12 +405,12 @@ Panel { color: root.batteryFillColor width: Math.max(barTrack.height, barTrack.width * root.batteryFraction) - Behavior on width { NumberAnimation { duration: 320; easing.type: Easing.OutCubic } } - Behavior on color { ColorAnimation { duration: 220 } } + Behavior on width { NumberAnimation { duration: Style.duration(320); easing.type: Easing.OutCubic } } + Behavior on color { ColorAnimation { duration: Style.duration(220) } } // Subtle pulse while charging — visible signal that energy is flowing in. SequentialAnimation on opacity { - running: root.charging && !root.fullyCharged && root.opened + running: root.charging && !root.fullyCharged && root.opened && !Style.reduceMotion loops: Animation.Infinite alwaysRunToEnd: true NumberAnimation { from: 1.0; to: 0.55; duration: 950; easing.type: Easing.InOutSine } diff --git a/shell/plugins/panels/tailscale/Panel.qml b/shell/plugins/panels/tailscale/Panel.qml index 6a9763072b25..8d0a84cb2342 100644 --- a/shell/plugins/panels/tailscale/Panel.qml +++ b/shell/plugins/panels/tailscale/Panel.qml @@ -363,7 +363,7 @@ Panel { function onAccountsAccessDeniedChanged() { root.ensureCursor() } } - IpcHandler { + ShellIpc { target: root.ipcTarget function open(): void { root.open() } function close(): void { root.close() } @@ -726,14 +726,14 @@ Panel { id: phraseSwap PropertyAnimation { target: hero; property: "metaOpacity" - to: 0.0; duration: 180; easing.type: Easing.OutQuad + to: 0.0; duration: Style.duration(180); easing.type: Easing.OutQuad } ScriptAction { script: root.phraseIndex = (root.phraseIndex + 1) % root.activePhrases.length } PropertyAnimation { target: hero; property: "metaOpacity" - to: 1.0; duration: 260; easing.type: Easing.InQuad + to: 1.0; duration: Style.duration(260); easing.type: Easing.InQuad } } @@ -834,7 +834,7 @@ Panel { opacity: accountRow.switchingAccount ? 0.45 : 1.0 SequentialAnimation on opacity { - running: accountRow.switchingAccount + running: accountRow.switchingAccount && !Style.reduceMotion NumberAnimation { to: 1.0; duration: 420; easing.type: Easing.InOutQuad } NumberAnimation { to: 0.45; duration: 420; easing.type: Easing.InOutQuad } loops: Animation.Infinite @@ -1150,7 +1150,7 @@ Panel { anchors.verticalCenter: parent.verticalCenter NumberAnimation on rotation { - running: exitNodeRow.settingExitNode + running: exitNodeRow.settingExitNode && !Style.reduceMotion from: 0 to: 360 duration: 900 diff --git a/shell/plugins/panels/weather/Panel.qml b/shell/plugins/panels/weather/Panel.qml index d9d43b684b72..e9fa5c318ea9 100644 --- a/shell/plugins/panels/weather/Panel.qml +++ b/shell/plugins/panels/weather/Panel.qml @@ -475,7 +475,7 @@ Panel { onTriggered: root.refresh() } - IpcHandler { + ShellIpc { target: root.ipcTarget function open(): void { root.openFromHotkey() } @@ -657,7 +657,7 @@ Panel { font.pixelSize: Style.font.bodySmall RotationAnimator on rotation { - running: root.savingLocation + running: root.savingLocation && !Style.reduceMotion from: 0; to: 360 duration: 800 loops: Animation.Infinite diff --git a/shell/plugins/panels/wifiqr/Panel.qml b/shell/plugins/panels/wifiqr/Panel.qml index 1426b5fd601b..1fdf4deca025 100644 --- a/shell/plugins/panels/wifiqr/Panel.qml +++ b/shell/plugins/panels/wifiqr/Panel.qml @@ -210,14 +210,9 @@ Item { } } - PanelWindow { - visible: root.opened - anchors { top: true; bottom: true; left: true; right: true } - color: "transparent" - exclusionMode: ExclusionMode.Ignore + OverlayWindow { + shown: root.opened WlrLayershell.namespace: "omarchy-network-qr" - WlrLayershell.layer: WlrLayer.Overlay - WlrLayershell.keyboardFocus: WlrKeyboardFocus.Exclusive // Deep scrim: the floating code needs the backdrop to carry the contrast // on any wallpaper. diff --git a/shell/plugins/polkit/PolkitAgent.qml b/shell/plugins/polkit/PolkitAgent.qml index 8786eeebc1be..98d6a0ace678 100644 --- a/shell/plugins/polkit/PolkitAgent.qml +++ b/shell/plugins/polkit/PolkitAgent.qml @@ -153,9 +153,9 @@ Item { SequentialAnimation { id: shakeAnimation - NumberAnimation { target: root; property: "shakeOffset"; to: -8; duration: 35; easing.type: Easing.OutQuad } - NumberAnimation { target: root; property: "shakeOffset"; to: 8; duration: 50; easing.type: Easing.InOutQuad } - NumberAnimation { target: root; property: "shakeOffset"; to: 0; duration: 55; easing.type: Easing.OutQuad } + NumberAnimation { target: root; property: "shakeOffset"; to: -8; duration: Style.duration(35); easing.type: Easing.OutQuad } + NumberAnimation { target: root; property: "shakeOffset"; to: 8; duration: Style.duration(50); easing.type: Easing.InOutQuad } + NumberAnimation { target: root; property: "shakeOffset"; to: 0; duration: Style.duration(55); easing.type: Easing.OutQuad } } FileView { path: "/etc/pam.d/polkit-1" diff --git a/shell/plugins/reminders/ReminderFlow.qml b/shell/plugins/reminders/ReminderFlow.qml index fef95cf08670..efdff65ce767 100644 --- a/shell/plugins/reminders/ReminderFlow.qml +++ b/shell/plugins/reminders/ReminderFlow.qml @@ -92,15 +92,10 @@ Item { } } - PanelWindow { + OverlayWindow { id: panel - visible: root.opened - anchors { top: true; bottom: true; left: true; right: true } - color: "transparent" + shown: root.opened WlrLayershell.namespace: "omarchy-reminders" - WlrLayershell.layer: WlrLayer.Overlay - WlrLayershell.keyboardFocus: WlrKeyboardFocus.Exclusive - exclusionMode: ExclusionMode.Ignore Rectangle { anchors.fill: parent diff --git a/shell/plugins/services/battery/Service.qml b/shell/plugins/services/battery/Service.qml index a1b01cfff60a..eb7561f10f91 100644 --- a/shell/plugins/services/battery/Service.qml +++ b/shell/plugins/services/battery/Service.qml @@ -59,6 +59,16 @@ Item { if (!powerProfileReadProcess.running) powerProfileReadProcess.running = true } + function parseActiveProfile(text) { + // busctl --json=short prints {"type":"s","data":"balanced"}; an empty or + // malformed reply (daemon not running) reads as no active profile. + try { + return String(JSON.parse(text).data || "").trim() + } catch (e) { + return "" + } + } + Process { id: warningProcess } Process { @@ -71,17 +81,23 @@ Item { Process { id: powerProfileReadProcess - command: ["powerprofilesctl", "get"] + // Read the property straight from the daemon rather than via + // `powerprofilesctl get`. That is a PyGObject script, and spawning a Python + // interpreter for it every two seconds trips a CPython 3.14 shutdown race + // (python/cpython#124619): the GLib D-Bus worker thread re-enters the + // interpreter after finalization and the process dies with SIGSEGV, + // leaving a core dump and a crash notification behind roughly daily. + command: ["busctl", "--json=short", "get-property", "net.hadess.PowerProfiles", "/net/hadess/PowerProfiles", "net.hadess.PowerProfiles", "ActiveProfile"] stdout: StdioCollector { waitForEnd: true - onStreamFinished: root.activePowerProfile = String(text || "").trim() + onStreamFinished: root.activePowerProfile = root.parseActiveProfile(text) } } Timer { - // powerprofilesctl has no portable monitor subcommand; keep profile changes - // visible to consumers such as the wallpaper service without requiring the - // power panel to be open. + // There is no portable way to subscribe to profile changes from QML; keep + // them visible to consumers such as the wallpaper service without requiring + // the power panel to be open. interval: 2000 running: true repeat: true diff --git a/shell/plugins/services/idle/Service.qml b/shell/plugins/services/idle/Service.qml index 1453920d1240..19dab2a2d446 100644 --- a/shell/plugins/services/idle/Service.qml +++ b/shell/plugins/services/idle/Service.qml @@ -4,6 +4,7 @@ import Quickshell.Hyprland import Quickshell.Io import Quickshell.Wayland import "IdleModel.js" as IdleModel +import qs.Commons Item { id: root @@ -335,7 +336,7 @@ Item { refreshStayAwakeState() } - IpcHandler { + ShellIpc { target: "idle" function status(): string { diff --git a/shell/plugins/services/media/BarWidget.qml b/shell/plugins/services/media/BarWidget.qml index 02650efcd4eb..d8052be3f8dd 100644 --- a/shell/plugins/services/media/BarWidget.qml +++ b/shell/plugins/services/media/BarWidget.qml @@ -40,7 +40,7 @@ BarWidget { font.pixelSize: Style.font.body Behavior on color { enabled: !root.bar || root.bar.foregroundAnimationEnabled - ColorAnimation { duration: 160 } + ColorAnimation { duration: Style.duration(160) } } } @@ -65,7 +65,9 @@ BarWidget { NumberAnimation on x { id: scrollAnim - running: labelText.needsScroll && !root.popupOpen && !root.bar.vertical + running: labelText.needsScroll && !root.popupOpen && !root.bar.vertical && !Style.reduceMotion + // Stopped for reduced motion, the title reads from its start again. + onRunningChanged: if (!running && Style.reduceMotion) labelText.x = 0 loops: Animation.Infinite duration: Math.max(6000, labelText.implicitWidth * 25) from: scrollClip.width diff --git a/shell/plugins/services/media/MediaModel.js b/shell/plugins/services/media/MediaModel.js index 3edd3a084030..c40ccd45c518 100644 --- a/shell/plugins/services/media/MediaModel.js +++ b/shell/plugins/services/media/MediaModel.js @@ -119,6 +119,20 @@ function osdMessage(player, fallback) { return label || fallback } +// What a volume key does to the output, by omarchy-audio-output-volume's rules: +// raise and lower step 5 and clamp to 0..100 (so a boosted sink drops to 100 +// on raise), unmuting as they go; mute-toggle flips mute and keeps the volume. +function volumeKeyStep(action, percent, muted) { + if (action === "raise") return { percent: Math.min(percent + 5, 100), muted: false } + if (action === "lower") return { percent: Math.max(percent - 5, 0), muted: false } + if (action === "mute-toggle") return { percent: percent, muted: !muted } + return null +} + +function volumeOsdIcon(percent, muted) { + return muted || percent === 0 ? "volume-muted" : "volume-high" +} + if (typeof module !== "undefined") { module.exports = { isProxyPlayer: isProxyPlayer, @@ -137,6 +151,8 @@ if (typeof module !== "undefined") { trackSignature: trackSignature, trackChanged: trackChanged, labelFor: labelFor, - osdMessage: osdMessage + osdMessage: osdMessage, + volumeKeyStep: volumeKeyStep, + volumeOsdIcon: volumeOsdIcon } } diff --git a/shell/plugins/services/media/Service.qml b/shell/plugins/services/media/Service.qml index 1cfeb9c9043c..0653627cf60a 100644 --- a/shell/plugins/services/media/Service.qml +++ b/shell/plugins/services/media/Service.qml @@ -4,6 +4,7 @@ import Quickshell.Io import Quickshell.Services.Mpris import Quickshell.Services.Pipewire import "MediaModel.js" as MediaModel +import qs.Commons Item { id: root @@ -455,6 +456,55 @@ Item { PwObjectTracker { objects: root.playbackStreams } + // ------------------------------------------------------------- volume keys + // + // The volume keys arrive as global shortcuts and change the volume here, + // with no process per press, stepping, clamping, unmuting and debouncing the + // way omarchy-audio-output-volume does, so either path lands on the same + // volume and OSD. That script resolves a DSP sink through to the physical + // sink it feeds on every press, from the live routing. An ALSA sink is its + // own physical sink, so only then do the keys act here; any other default + // sink falls back to the script. + readonly property var defaultSink: Pipewire.defaultAudioSink + readonly property var volumeSink: defaultSink && String(defaultSink.name).indexOf("alsa_output.") === 0 ? defaultSink : null + property double lastMuteToggle: 0 + + // Returns false when the default sink is not one to control here, so the + // caller falls back to the script. + function handleVolumeKey(action) { + var audio = volumeSink && volumeSink.audio + if (!audio) return false + + var step = MediaModel.volumeKeyStep(action, Math.round(audio.volume * 100), audio.muted) + if (!step) return false + + if (action === "mute-toggle") { + // Some keyboards bounce the mute key; the script ignores a second + // toggle within 250ms too. + var now = Date.now() + if (now - lastMuteToggle < 250) return true + lastMuteToggle = now + audio.muted = step.muted + } else { + audio.muted = false + audio.volume = step.percent / 100 + } + + // The payload omarchy-osd builds, from the values just set: the node may + // not report them back before the OSD draws. + shell.summon("omarchy.osd", JSON.stringify({ + icon: MediaModel.volumeOsdIcon(step.percent, step.muted), + message: "", + value: String(step.percent), + progressText: step.percent + "%", + max: "100", + duration: "" + })) + return true + } + + PwObjectTracker { objects: root.defaultSink ? [root.defaultSink] : [] } + function statusJson() { var p = activePlayer return JSON.stringify({ @@ -473,7 +523,16 @@ Item { }) } - IpcHandler { + // Keybindings reach these handlers as Hyprland global shortcuts, run here + // exactly as the IPC call would run them, with no client to spawn. + function runShortcut(method) { + if (typeof ipcHandler[method] !== "function") return false + ipcHandler[method]() + return true + } + + ShellIpc { + id: ipcHandler target: "media" function status(): string { diff --git a/shell/plugins/services/nightlight/Service.qml b/shell/plugins/services/nightlight/Service.qml index 388b77981203..18ed7d16eaaf 100644 --- a/shell/plugins/services/nightlight/Service.qml +++ b/shell/plugins/services/nightlight/Service.qml @@ -1,6 +1,7 @@ import QtQuick import Quickshell.Io import "NightlightModel.js" as NightlightModel +import qs.Commons Item { id: root @@ -85,7 +86,7 @@ Item { Component.onCompleted: refresh() - IpcHandler { + ShellIpc { target: "nightlight" function status(): string { diff --git a/shell/services/BrightnessKeys.qml b/shell/services/BrightnessKeys.qml new file mode 100644 index 000000000000..0f14b141af04 --- /dev/null +++ b/shell/services/BrightnessKeys.qml @@ -0,0 +1,101 @@ +import QtQuick +import Quickshell +import Quickshell.Hyprland +import Quickshell.Io +import qs.Commons +import "BrightnessModel.js" as BrightnessModel + +// The display brightness keys, arriving as global shortcuts. On the internal +// panel they step the backlight here: one brightnessctl write and the OSD in +// process, instead of omarchy-brightness-display resolving the monitor and +// device, reading, writing and reading back, then an IPC client for the OSD. +// They step, clamp and read back the way that script does, so either path +// lands on the same level and OSD. External and Apple displays go through the +// script, which drives them over DDC or their own helper. +Item { + id: root + + // The shell host, for summoning the OSD. + property var host: null + // The backlight omarchy-hw-display picks. Devices do not come and go at + // runtime, but each press refreshes it for the next. + property string device: "" + readonly property string devicePath: device ? "/sys/class/backlight/" + device : "" + + // Returns false when the focused display is not one to handle here, so the + // caller falls back to the script. + function handle(action) { + var monitor = Hyprland.focusedMonitor + var name = monitor ? String(monitor.name || "") : "" + if (!/^(eDP|LVDS|DSI)-/.test(name) || !device) return false + if (action !== "raise" && action !== "lower") return false + + // The script drops a press that overlaps one still being applied, so key + // repeat cannot race the writes. + if (setProc.running) return true + + var max = readNumber(maxFile) + if (!(max > 0)) return false + var current = Math.round(100 * readNumber(brightnessFile) / max) + + setProc.command = ["brightnessctl", "-q", "-d", device, "set", BrightnessModel.brightnessKeyTarget(action, current) + "%"] + setProc.running = true + return true + } + + // reload() reads in the background, so wait for it: text() would otherwise + // still hold the previous reading, and a level changed elsewhere (the + // monitor panel, a script) would step from the wrong place. + function readNumber(file) { + file.reload() + file.waitForJob() + return Number(String(file.text() || "").trim()) + } + + // The payload omarchy-osd builds, from the level read back after the write. + function showOsd() { + var max = readNumber(maxFile) + if (!host || !(max > 0)) return + var percent = Math.round(100 * readNumber(brightnessFile) / max) + host.summon("omarchy.osd", JSON.stringify({ + icon: "brightness", + message: "", + value: String(percent), + progressText: percent + "%", + max: "100", + duration: "" + })) + } + + FileView { + id: brightnessFile + path: root.devicePath ? root.devicePath + "/brightness" : "" + blockLoading: true + printErrors: false + } + + FileView { + id: maxFile + path: root.devicePath ? root.devicePath + "/max_brightness" : "" + blockLoading: true + printErrors: false + } + + Process { + id: setProc + onExited: { + root.showOsd() + if (!deviceProc.running) deviceProc.running = true + } + } + + Process { + id: deviceProc + command: ["omarchy-hw-display"] + running: true + stdout: StdioCollector { + waitForEnd: true + onStreamFinished: root.device = String(text || "").trim() + } + } +} diff --git a/shell/services/BrightnessModel.js b/shell/services/BrightnessModel.js new file mode 100644 index 000000000000..531d6e36e430 --- /dev/null +++ b/shell/services/BrightnessModel.js @@ -0,0 +1,12 @@ +// omarchy-brightness-display's steps for the brightness keys: 1% at or below +// 5%, otherwise 5%, kept between 1% and 100%. +function brightnessKeyTarget(action, current) { + if (action === "raise") return Math.min(current < 5 ? current + 1 : current + 5, 100) + return Math.max(current <= 5 ? current - 1 : current - 5, 1) +} + +if (typeof module !== "undefined") { + module.exports = { + brightnessKeyTarget: brightnessKeyTarget + } +} diff --git a/shell/shell.qml b/shell/shell.qml index 8208062429f1..888d871ff9cf 100644 --- a/shell/shell.qml +++ b/shell/shell.qml @@ -1,6 +1,7 @@ import QtQuick import QtQml.Models import Quickshell +import Quickshell.Hyprland import Quickshell.Io import qs.Commons @@ -19,6 +20,7 @@ ShellRoot { property PluginRegistry pluginRegistry: PluginRegistry { } property BarWidgetRegistry barWidgetRegistry: BarWidgetRegistry { } property AppLibrary appLibrary: AppLibrary { } + property BrightnessKeys brightnessKeys: BrightnessKeys { host: shell } property string home: Quickshell.env("HOME") @@ -1233,7 +1235,7 @@ ShellRoot { function unloadPanels() { for (var id in panelLoaders) hide(id) - panelEntries = [] + panelEntryModel.clear() panelLoaders = ({}) pendingPayloads = ({}) openPanelIds = ({}) @@ -1282,7 +1284,43 @@ ShellRoot { // One Loader per discoverable panel/overlay/menu plugin. Active when the // host marks it open. The Loader holds onto the instance while active so the // plugin's FloatingWindow + state survive between summons within a session. - property var panelEntries: [] + // + // The entries live in a ListModel synced in place. Handing the Instantiator + // a fresh array instead rebuilt every panel on every plugin change, four + // times over during startup: each rebuild started a new asynchronous load of + // every keepLoaded panel while the last was in flight, so two OSDs could run + // at once, each registering its IPC handler. A full plugin reload clears + // the model in unloadPanels, so panels still rebuild from fresh code then. + ListModel { id: panelEntryModel } + + function syncPanelEntries() { + var wanted = ({}) + var order = [] + var entries = computePanelEntries() + for (var i = 0; i < entries.length; i++) { + var entry = entries[i] + entry.sourceUrl = String(shell.pluginRegistry.entryPointUrl(entry.manifest, entry.kind) || "") + wanted[entry.id] = entry + order.push(entry.id) + } + + // Keep an entry whose plugin still loads the same way; drop the rest. + for (var j = panelEntryModel.count - 1; j >= 0; j--) { + var row = panelEntryModel.get(j) + var next = wanted[row.pluginId] + if (next && next.kind === row.entryKind && next.keepLoaded === row.keepLoaded && next.sourceUrl === row.sourceUrl) { + delete wanted[row.pluginId] + } else { + panelEntryModel.remove(j) + } + } + + for (var k = 0; k < order.length; k++) { + var added = wanted[order[k]] + if (!added) continue + panelEntryModel.append({ pluginId: added.id, entryKind: added.kind, keepLoaded: added.keepLoaded, sourceUrl: added.sourceUrl }) + } + } function computePanelEntries() { var out = [] @@ -1305,21 +1343,21 @@ ShellRoot { Connections { target: shell.pluginRegistry - function onPluginsChanged() { if (!shell.pluginReloading) shell.panelEntries = shell.computePanelEntries() } + function onPluginsChanged() { if (!shell.pluginReloading) shell.syncPanelEntries() } } Instantiator { - model: shell.panelEntries + model: panelEntryModel active: true delegate: QtObject { id: panelEntry - required property var modelData - readonly property string pluginId: modelData.id - readonly property var manifest: modelData.manifest - readonly property string entryKind: modelData.kind - readonly property bool keepLoaded: modelData.keepLoaded === true - readonly property string sourceUrl: shell.pluginRegistry.entryPointUrl(manifest, entryKind) + required property string pluginId + required property string entryKind + required property bool keepLoaded + required property string sourceUrl + // The manifest can be replaced on a rescan without the entry changing. + readonly property var manifest: shell.pluginRegistry.installedPlugins[pluginId] property Loader panelLoader: Loader { source: panelEntry.sourceUrl @@ -1475,7 +1513,7 @@ ShellRoot { } shell.pluginReloading = false shell._syncServices() - shell.panelEntries = shell.computePanelEntries() + shell.syncPanelEntries() shell.syncPluginWidgets() } } @@ -1513,6 +1551,104 @@ ShellRoot { } } + // ------------------------------------------------------ global shortcuts + // + // Bindings that open a menu route or panel, or step the volume, dispatch + // these through Hyprland, so a keypress reaches the shell without spawning + // an IPC client or script. The list is shared with default/hypr/helpers.lua, which binds a + // route or panel missing from it through the command instead. + + function parseShortcuts(raw) { + var entries = [] + var lines = String(raw || "").split("\n") + for (var i = 0; i < lines.length; i++) { + var match = /^([A-Za-z]+)\s+(\S+)\s*$/.exec(lines[i]) + if (match && ["menu", "panel", "audio", "brightness", "ipc"].indexOf(match[1]) !== -1) + entries.push({ kind: match[1], target: match[2], name: match[1] + "." + match[2] }) + } + return entries + } + + // The IPC targets an ipc shortcut may name, and the service that owns each. + readonly property var ipcShortcutServices: ({ media: "omarchy.media", notifications: "omarchy.notifications" }) + + function runShortcut(entry) { + if (entry.kind === "menu") { + shell.toggle("omarchy.menu", JSON.stringify({ menu: entry.target })) + } else if (entry.kind === "ipc") { + // "media.next" runs the media service's own IPC handler for next. + var dot = entry.target.indexOf(".") + var target = entry.target.slice(0, dot) + var method = entry.target.slice(dot + 1) + var service = shell.serviceFor(shell.ipcShortcutServices[target] || "") + if (!service || !service.runShortcut(method)) + Util.execArgv(["omarchy-shell", target, method]) + } else if (entry.kind === "brightness") { + if (!shell.brightnessKeys.handle(entry.target)) + Util.execArgv(["omarchy-brightness-display", entry.target === "raise" ? "+5%" : "5%-"]) + } else if (entry.kind === "audio") { + var media = shell.serviceFor("omarchy.media") + if (!media || !media.handleVolumeKey(entry.target)) + Util.execArgv(["omarchy-audio-output-volume", entry.target]) + } else { + shell.toggle(entry.target, "{}") + } + } + + FileView { + id: shortcutsFile + path: shell.omarchyPath + "/default/omarchy/shortcuts" + watchChanges: true + onFileChanged: reload() + } + + Variants { + model: shell.parseShortcuts(shortcutsFile.text()) + + GlobalShortcut { + required property var modelData + + appid: "omarchy" + name: modelData.name + description: modelData.kind === "audio" || modelData.kind === "brightness" ? (modelData.kind === "audio" ? "Volume " : "Brightness ") + modelData.target : (modelData.kind === "ipc" ? "Run " + modelData.target : "Toggle the " + modelData.target + " " + modelData.kind) + onPressed: shell.runShortcut(modelData) + } + } + + // ------------------------------------------------------------ IPC socket + // + // omarchy-shell reaches the shell here first: a qs ipc client costs ~45ms + // to start per call, socat ~5ms. A request is target, method and arguments + // separated by unit separators and ended by a record separator. The reply is + // "OK" and the output, or "SKIP" when nothing ran (no such target or + // function, or the wrong number of arguments), which omarchy-shell hands to + // qs ipc for its exact answer. The socket sits in XDG_RUNTIME_DIR, private + // to the user like qs ipc's own. Like qs ipc, it belongs to one shell: the + // one running this config on this display. omarchy-shell derives the same + // name from the same two values. + readonly property string ipcSocketPath: Quickshell.env("XDG_RUNTIME_DIR") + "/omarchy-shell-" + + Qt.md5(shell.omarchyPath + "/shell\n" + Quickshell.env("WAYLAND_DISPLAY")).slice(0, 16) + ".sock" + + SocketServer { + active: shell.omarchyPath !== "" + path: shell.ipcSocketPath + + handler: Socket { + id: connection + + parser: SplitParser { + splitMarker: "\u001e" + onRead: function(data) { + var fields = String(data).split("\u001f") + var result = fields.length >= 2 ? IpcRegistry.call(fields[0], fields[1], fields.slice(2)) : { ran: false } + connection.write(result.ran ? "OK\u001f" + result.output + "\u001e" : "SKIP\u001e") + connection.flush() + connection.connected = false + } + } + } + } + // --------------------------------------------------- image selector IPC function imagePickerItem() { @@ -1520,7 +1656,7 @@ ShellRoot { return loader && loader.item ? loader.item : null } - IpcHandler { + ShellIpc { target: "image-selector" function open(imageDirs: string, @@ -1571,7 +1707,7 @@ ShellRoot { // ---------------------------------------------------------- shell IPC - IpcHandler { + ShellIpc { target: "shell" function ping(): string { diff --git a/test/acceptance.d/base-test.sh b/test/acceptance.d/base-test.sh index 023223a1f686..7bc9a1aff53a 100644 --- a/test/acceptance.d/base-test.sh +++ b/test/acceptance.d/base-test.sh @@ -81,6 +81,17 @@ layer_absent() { ! layer_present "$1" } +# Overlays built on OverlayWindow (the menu, image selector, emoji picker, +# clipboard and the like) stay mapped between opens, parked 1x1 on the bottom +# layer, so they keep their fractional scale. Showing means on the overlay. +layer_on_overlay() { + hyprctl -j layers | jq -e --arg ns "$1" '[.[].levels["3"][]? | select(.namespace == $ns)] | length > 0' +} + +layer_off_overlay() { + ! layer_on_overlay "$1" +} + # A layer can be mapped but parked off the monitor: the bar hides that way so # revealing it does not have to rebuild the surface. Assert on geometry when # what matters is that the user can actually see it. Layer boxes are local to diff --git a/test/acceptance.d/menu-test.sh b/test/acceptance.d/menu-test.sh index 500dc1e43260..64bdd0ff853a 100644 --- a/test/acceptance.d/menu-test.sh +++ b/test/acceptance.d/menu-test.sh @@ -63,7 +63,7 @@ source_file=$DEFAULTS_FILE original_position=$(jq -r '.bar.position // "top"' "$source_file") omarchy-shell shell summon omarchy.menu '{"menu":"root"}' >/dev/null -wait_until "root menu opens" 15 layer_present "omarchy-menu" +wait_until "root menu opens" 15 layer_on_overlay "omarchy-menu" wait_until "root menu content is visible" 15 screen_contains "Apps" screenshot "success-menu-01-root" @@ -86,7 +86,7 @@ screenshot "success-menu-05-position-submenu" wtype -k Down -k Down -k Return wait_until "menu bar position changes to left" 20 bar_position_is "left" wait_until "menu bar becomes vertical" 20 bar_is_vertical -wait_until "menu closes after selecting a position" 15 layer_absent "omarchy-menu" +wait_until "menu closes after selecting a position" 15 layer_off_overlay "omarchy-menu" screenshot "success-menu-06-bar-left" if ((config_existed)); then diff --git a/test/acceptance.d/shell-surfaces-test.sh b/test/acceptance.d/shell-surfaces-test.sh index 9e10e85ccbdf..7d7630ed53e7 100644 --- a/test/acceptance.d/shell-surfaces-test.sh +++ b/test/acceptance.d/shell-surfaces-test.sh @@ -24,12 +24,12 @@ open_and_close() { # Search and select an emoji. The host harness separately proves the shortcut # with a QMP hardware key chord, while this test focuses on UI behavior. omarchy-shell shell summon omarchy.emojis >/dev/null -wait_until "emoji picker opens" 15 layer_present "omarchy-emojis" +wait_until "emoji picker opens" 15 layer_on_overlay "omarchy-emojis" wtype "rocket" sleep 1 screenshot "success-emoji-picker-search" wtype -k Return -wait_until "emoji picker selection closes" 15 layer_absent "omarchy-emojis" +wait_until "emoji picker selection closes" 15 layer_off_overlay "omarchy-emojis" # Seed two clipboard entries, search for the older one, and copy it back out. clipboard_token="Omarchy acceptance clipboard $(date +%s)" @@ -39,42 +39,42 @@ printf '%s' "clipboard decoy" | wl-copy sleep 1 omarchy-shell shell summon omarchy.clipboard >/dev/null -wait_until "clipboard opens" 15 layer_present "omarchy-clipboard" +wait_until "clipboard opens" 15 layer_on_overlay "omarchy-clipboard" wtype "$clipboard_token" wait_until "clipboard search finds test text" 15 screen_contains "Omarchy acceptance clipboard" screenshot "success-clipboard-search" wtype -M shift -k Return -m shift -wait_until "clipboard selection closes" 15 layer_absent "omarchy-clipboard" +wait_until "clipboard selection closes" 15 layer_off_overlay "omarchy-clipboard" wait_until "clipboard selection restores test text" 15 bash -c '[[ $(wl-paste --no-newline) == "$1" ]]' _ "$clipboard_token" # Exercise the system branch without invoking any destructive action. omarchy-shell shell summon omarchy.menu '{"menu":"system"}' >/dev/null -wait_until "system menu opens" 15 layer_present "omarchy-menu" +wait_until "system menu opens" 15 layer_on_overlay "omarchy-menu" wait_until "system menu content is visible" 15 screen_contains "Shutdown" screenshot "success-system-menu" wtype -k Escape -wait_until "system menu closes" 15 layer_absent "omarchy-menu" +wait_until "system menu closes" 15 layer_off_overlay "omarchy-menu" # Preview both visual selectors and cancel without changing user state. These # cover thumbnail generation, the image-grid overlay, and current selection. launch_app "omarchy-theme-bg-switcher" -wait_until "background selector opens" 30 layer_present "omarchy-image-selector" +wait_until "background selector opens" 30 layer_on_overlay "omarchy-image-selector" sleep 1 screenshot "success-background-selector" wtype -k Escape -wait_until "background selector closes" 15 layer_absent "omarchy-image-selector" +wait_until "background selector closes" 15 layer_off_overlay "omarchy-image-selector" launch_app "omarchy-theme-switcher" -wait_until "theme selector opens" 30 layer_present "omarchy-image-selector" +wait_until "theme selector opens" 30 layer_on_overlay "omarchy-image-selector" sleep 1 screenshot "success-theme-selector" wtype -k Escape -wait_until "theme selector closes" 15 layer_absent "omarchy-image-selector" +wait_until "theme selector closes" 15 layer_off_overlay "omarchy-image-selector" # Walk the reminder flow through each input screen, but dismiss before it # schedules a real timer in the test user's session. omarchy-shell shell summon omarchy.reminders >/dev/null -wait_until "reminder flow opens" 15 layer_present "omarchy-reminders" +wait_until "reminder flow opens" 15 layer_on_overlay "omarchy-reminders" screenshot "success-reminder-01-minutes-prompt" wtype "5" sleep 1 @@ -83,7 +83,7 @@ wtype -k Return wait_until "reminder message prompt opens" 15 screen_contains "Reminder message" screenshot "success-reminder-03-message-prompt" wtype -k Escape -wait_until "reminder flow closes" 15 layer_absent "omarchy-reminders" +wait_until "reminder flow closes" 15 layer_off_overlay "omarchy-reminders" # Render a real shell notification and clear it through the notification IPC. omarchy-shell notifications dismissAll >/dev/null @@ -101,7 +101,7 @@ if window_present "(?i)omawrite" >/dev/null 2>&1; then fi omarchy-menu summon apps >/dev/null -wait_until "apps menu opens" 15 layer_present "omarchy-menu" +wait_until "apps menu opens" 15 layer_on_overlay "omarchy-menu" sleep 1 screenshot "success-apps-menu-open" @@ -111,7 +111,7 @@ screenshot "success-apps-menu-search" wtype -k Return wait_until "apps menu launches the top search hit" 60 window_present "(?i)omawrite" -wait_until "apps menu closes after launching" 15 layer_absent "omarchy-menu" +wait_until "apps menu closes after launching" 15 layer_off_overlay "omarchy-menu" close_windows "(?i)omawrite" wait_until "Omawrite window closes" 30 window_absent "(?i)omawrite" diff --git a/test/acceptance.d/system-test.sh b/test/acceptance.d/system-test.sh index 0d648e9c16ea..af0d5204f83c 100644 --- a/test/acceptance.d/system-test.sh +++ b/test/acceptance.d/system-test.sh @@ -24,6 +24,20 @@ verify_core_packages() { pass "all Omarchy core packages are installed (${#missing[@]} missing)" } +verify_kernel_headers() { + local kernel=linux-omarchy + local release + release=$(uname -r) + omarchy-pkg-present linux-t2 && kernel=linux-t2 + + [[ $(cat "/usr/lib/modules/$release/pkgbase") == "$kernel" ]] || + fail "the installed system boots the supported kernel" "$release is not $kernel" + omarchy-pkg-present "$kernel-headers" || fail "kernel headers are installed" "$kernel-headers is missing" + [[ $(cat "/usr/lib/modules/$release/build/include/config/kernel.release") == "$release" ]] || + fail "headers match the running kernel" "$release has missing or mismatched headers" + pass "the running $kernel kernel has matching headers ($release)" +} + verify_defaults() { [[ $(omarchy-default-browser) == "chromium" ]] || fail "Chromium is the default browser" pass "Chromium is the default browser" @@ -112,7 +126,7 @@ verify_user_setup() { pass "Omarchy user state and shell configuration exist" } -for check in verify_core_packages verify_defaults verify_services verify_runtime_tools verify_user_setup; do +for check in verify_core_packages verify_kernel_headers verify_defaults verify_services verify_runtime_tools verify_user_setup; do if ! ("$check"); then status=1 fi diff --git a/test/cli b/test/cli index 1643d2dbf6a1..4081921c4dfb 100755 --- a/test/cli +++ b/test/cli @@ -550,6 +550,33 @@ TMUX_LOG="$PI_TMPDIR/tmux.log" PATH="$FAKE_BIN:$ROOT/bin:$PATH" HOME="$PI_TMPDIR grep -q 'set-environment -g COLORFGBG 0;15' "$PI_TMPDIR/tmux.log" || fail "tmux sync reads mode from colors.toml" pass "tmux sync reads mode from colors.toml" +cat >"$FAKE_BIN/pgrep" <<'EOF' +#!/bin/bash +[[ -n $HUNK_RUNNING ]] +EOF +chmod +x "$FAKE_BIN/pgrep" + +cat >"$FAKE_BIN/pkill" <<'EOF' +#!/bin/bash +echo "$*" >>"${PKILL_LOG:-/dev/null}" +EOF +chmod +x "$FAKE_BIN/pkill" + +cat >"$FAKE_BIN/sleep" <<'EOF' +#!/bin/bash +exit 0 +EOF +chmod +x "$FAKE_BIN/sleep" + +HUNK_RUNNING=1 PKILL_LOG="$PI_TMPDIR/pkill.log" PATH="$FAKE_BIN:$ROOT/bin:$PATH" HOME="$PI_TMPDIR" "$ROOT/bin/omarchy-theme-set-hunk" +[[ $(grep -c -- '-WINCH -x hunk' "$PI_TMPDIR/pkill.log") == "2" ]] || fail "hunk sync signals running hunk sessions" +pass "hunk sync signals running hunk sessions" + +PKILL_LOG="$PI_TMPDIR/pkill-idle.log" PATH="$FAKE_BIN:$ROOT/bin:$PATH" HOME="$PI_TMPDIR" "$ROOT/bin/omarchy-theme-set-hunk" +[[ ! -e $PI_TMPDIR/pkill-idle.log ]] || fail "hunk sync skips signaling without running hunk" +pass "hunk sync skips signaling without running hunk" +rm -f "$FAKE_BIN/pgrep" "$FAKE_BIN/pkill" "$FAKE_BIN/sleep" + cat >"$FAKE_BIN/gsettings" <<'EOF' #!/bin/bash echo "$*" >>"${GSETTINGS_LOG:-/dev/null}" diff --git a/test/shell b/test/shell index c7d7e5fca6bb..34a2ca490831 100755 --- a/test/shell +++ b/test/shell @@ -21,16 +21,31 @@ fi # Keep going after a failing file. A test file exits at its first failed # assertion, so aborting the run there too would hide every file after it -- # one packaging failure was masking 114 of 134 files. +output=$(mktemp) +trap 'rm -f "$output"' EXIT failed=() +skipped=() for test in "${tests[@]}"; do printf '==> %s\n' "${test#$ROOT/}" - bash "$test" || failed+=("${test#$ROOT/}") + bash "$test" | tee "$output" || failed+=("${test#$ROOT/}") + if grep -q '^ok - .* # SKIP$' "$output"; then + skipped+=("${test#$ROOT/}") + fi done +if (( ${#skipped[@]} > 0 )); then + printf '\nSkipped checks in %d of %d test files:\n' "${#skipped[@]}" "${#tests[@]}" + printf ' %s\n' "${skipped[@]}" +fi + if (( ${#failed[@]} > 0 )); then printf '\n%d of %d test files failed:\n' "${#failed[@]}" "${#tests[@]}" >&2 printf ' %s\n' "${failed[@]}" >&2 exit 1 fi -printf '\nAll %d test files passed.\n' "${#tests[@]}" +if (( ${#skipped[@]} == 0 )); then + printf '\nAll %d test files passed.\n' "${#tests[@]}" +else + printf '\n%d test files completed without failures; %d had skipped checks.\n' "${#tests[@]}" "${#skipped[@]}" +fi diff --git a/test/shell.d/agent-usage-codex-scanner-test.sh b/test/shell.d/agent-usage-codex-scanner-test.sh index 3ce4883cdbfb..4b0b7fb64972 100644 --- a/test/shell.d/agent-usage-codex-scanner-test.sh +++ b/test/shell.d/agent-usage-codex-scanner-test.sh @@ -26,10 +26,12 @@ while read -r request; do jq -cn --argjson id "$id" '{id: $id, result: {}}' ;; account/read) - jq -cn --argjson id "$id" '{id: $id, result: {account: {}}}' + # Codex 0.158 can leave this one unanswered for good. + [[ -n ${CODEX_ACCOUNT_READ_HANGS:-} ]] || + jq -cn --argjson id "$id" '{id: $id, result: {account: {}}}' ;; account/rateLimits/read) - jq -cn --argjson id "$id" '{id: $id, result: {rateLimits: {}}}' + jq -cn --argjson id "$id" --argjson limits "${CODEX_RATE_LIMITS:-{\}}" '{id: $id, result: {rateLimits: $limits}}' ;; esac done @@ -603,3 +605,14 @@ result=$(HOME="$INTERRUPTED_HOME" CODEX_HOME="$INTERRUPTED_HOME/.codex" XDG_CACH [[ $(jq -r '.todayTotalTokens' <<<"$result") == "9" ]] || fail "Codex collector does not reuse a snapshot from an interrupted scan" "$result" pass "Codex collector does not cache an interrupted opencode scan" + +# The limits name the plan themselves, so an account/read that never answers +# costs nothing: the limits still arrive, and quickly. +started=$(date +%s) +result=$(HOME="$TEST_HOME" CODEX_HOME="$TEST_HOME/.codex" XDG_DATA_HOME="$TEST_HOME/.local/share" PATH="$TEST_HOME/bin:$PATH" \ + CODEX_ACCOUNT_READ_HANGS=1 CODEX_RATE_LIMITS='{"planType":"pro","primary":{"usedPercent":36,"windowDurationMins":10080}}' \ + "$ROOT/bin/omarchy-agent-usage-codex" --limits-only) +(( $(date +%s) - started < 4 )) || fail "Codex collector doesn't wait on account/read when the limits name the plan" +[[ $(jq -c '{tierLabel, usageStatusText, limits: [.limits[] | {label, percent}]}' <<<"$result") == '{"tierLabel":"pro","usageStatusText":"","limits":[{"label":"Weekly (7-day)","percent":0.36}]}' ]] || + fail "Codex collector reads limits even when account/read never answers" "$result" +pass "Codex collector reads limits even when account/read never answers" diff --git a/test/shell.d/apply-lock-test.sh b/test/shell.d/apply-lock-test.sh index 5e7170cf5415..490e7c8c253c 100644 --- a/test/shell.d/apply-lock-test.sh +++ b/test/shell.d/apply-lock-test.sh @@ -43,7 +43,7 @@ if (( EUID != 0 )); then fi if (( ! root_runtime_available )); then - pass "no unprivileged user namespace; skipping the root lock-helper lookup matrix" + skip "no unprivileged user namespace; skipping the root lock-helper lookup matrix" exit 0 fi diff --git a/test/shell.d/background-test.sh b/test/shell.d/background-test.sh index 9762e6d3a2c5..2a0d832dd497 100644 --- a/test/shell.d/background-test.sh +++ b/test/shell.d/background-test.sh @@ -7,8 +7,9 @@ const fs = require('fs') const backgroundQml = fs.readFileSync(path.join(root, 'shell/plugins/background/Background.qml'), 'utf8') assert( - /theme=\$\(omarchy-theme-switcher\); \[\[ -n \$theme \]\] && omarchy-theme-set \\"\$theme\\" >\/dev\/null 2>&1 &/.test(backgroundQml), - 'background theme switcher starts theme application asynchronously after selection' + /function openThemeSwitcher\(\) \{[\s\S]*if \(!root\.shell \|\| !root\.shell\.summon\("omarchy\.image-picker", payload\)\)\s*Util\.execArgv\(\["omarchy-shell", "shell", "summon", "omarchy\.image-picker", payload\]\)/.test(backgroundQml) && + !backgroundQml.includes('omarchy-theme-switcher'), + 'background opens the in-shell theme picker instead of spawning the switcher script' ) assert( @@ -18,4 +19,59 @@ assert( !backgroundQml.includes('pendingThemeVersion !== backgroundVersion'), 'background theme transition applies pending colors even if image reveal stalls' ) + +const themeSet = fs.readFileSync(path.join(root, 'bin/omarchy-theme-set'), 'utf8') + +// The next background decodes while the theme stages, rather than after the +// transition arrives: WebP decodes take as long at screen size as at native. +assert( + /function prepare\(path: string\): void \{\s*root\.prepareBackground\(path\)/.test(backgroundQml) && + backgroundQml.includes('readonly property string framePath: root.incomingBackground || root.preparedBackground'), + 'background decodes a prepared theme background in the hidden incoming frame' +) +assert( + /path === lastTransitionPath/.test(backgroundQml) && + /id: preparedBackgroundTimer[\s\S]*?onTriggered: root\.preparedBackground = ""/.test(backgroundQml), + 'background ignores a late prepare and drops an unclaimed one' +) +assert( + themeSet.indexOf('shell_ipc background prepare') !== -1 && + themeSet.indexOf('shell_ipc background prepare') < themeSet.indexOf('\nomarchy-theme-set-templates\n'), + 'theme set hands the shell its next background before rendering templates' +) +assert( + themeSet.includes('shell_ipc background prepare "$PREPARED_BACKGROUND_SNAPSHOT" 9>&- &'), + 'theme set sends the prepare without holding the theme lock or waiting on it' +) + +// The wallpaper is decoded at the screen's physical size, never at the size +// it was shipped at, unless it is smaller than the screen: then it is decoded +// at its own size instead of being scaled up to cover the screen. +const mediaQml = fs.readFileSync(path.join(root, 'shell/Ui/BackgroundMedia.qml'), 'utf8') +assert( + backgroundQml.includes('readonly property bool sized: width > 0 && height > 0') && + backgroundQml.includes('readonly property int decodeWidth: sized ? Math.ceil(width * screen.devicePixelRatio) : 0') && + backgroundQml.includes('readonly property int decodeHeight: sized ? Math.ceil(height * screen.devicePixelRatio) : 0'), + 'background derives its decode size from the screen in physical pixels' +) +assert( + backgroundQml.includes('["magick", "identify", "-ping", "-format", "%w %h", sizeProbe.path]') && + backgroundQml.includes('if (native.width > 0 && (native.width < decodeWidth || native.height < decodeHeight)) return Qt.size(native.width, native.height)'), + 'background reads the wallpaper header and never decodes larger than the native size' +) +const count = (needle) => backgroundQml.split(needle).length - 1 +assertEqual(count('sourceSize.width: decode.width'), 2, 'both transition frames bind their decode width') +assertEqual(count('sourceSize.height: decode.height'), 2, 'both transition frames bind their decode height') +assertEqual(count('source: decode.width > 0 ? root.imageUrl('), 2, 'both transition frames wait for the screen and native sizes before loading') +assert( + /constrainDecode: true\s*decodeSize: panel\.decodeSize\(root\.displayedBackground\)/.test(backgroundQml) && + mediaQml.includes('source: !root.constrainDecode || root.decodeSize.width > 0 ? root.imageUrl : ""') && + mediaQml.includes('sourceSize.width: root.constrainDecode ? root.decodeSize.width : (root.version > 0 ? width : 0)'), + 'the displayed wallpaper waits for and decodes at the same size' +) +assert( + /function requestNativeSize\(path\) \{\s*if \(!path \|\| isVideo\(path\)/.test(backgroundQml) && + /function prepareBackground[\s\S]*?requestNativeSize\(path\)/.test(backgroundQml), + 'background never probes videos and probes a prepared frame ahead of its transition' +) JS diff --git a/test/shell.d/bar-icon-geometry-test.sh b/test/shell.d/bar-icon-geometry-test.sh index 1bfcdf0cfb77..626bf405ec0e 100644 --- a/test/shell.d/bar-icon-geometry-test.sh +++ b/test/shell.d/bar-icon-geometry-test.sh @@ -7,7 +7,7 @@ source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" require_compositor "bar icon geometry test" if ! command -v quickshell >/dev/null 2>&1; then - pass "quickshell not installed; skipping bar icon geometry test" + skip "quickshell not installed; skipping bar icon geometry test" exit 0 fi @@ -40,8 +40,9 @@ ShellRoot { fail(name + " optical canvas is " + icon.opticalSize) return false } - if (Math.abs(icon.opticalCenterErrorX) > 0.5) { - fail(name + " painted bounds are over half a pixel off center by " + icon.opticalCenterErrorX) + // The open-panel underline centers on the slot, so the glyph must too. + if (Math.abs(icon.opticalCenterErrorX) > 0.05) { + fail(name + " painted bounds are off the slot's center by " + icon.opticalCenterErrorX) return false } if (icon.glyphFontSize !== Style.bar.iconFont) { @@ -57,6 +58,7 @@ ShellRoot { if (!checkIcon(audio, "audio")) return if (!checkIcon(monitor, "monitor")) return if (!checkIcon(power, "power")) return + if (!checkIcon(elsewhen, "elsewhen")) return var baseline = bluetooth.glyphBaselineY if (network.glyphBaselineY !== baseline || audio.glyphBaselineY !== baseline || monitor.glyphBaselineY !== baseline || power.glyphBaselineY !== baseline) { @@ -79,7 +81,7 @@ ShellRoot { fail("indicator does not use the secondary icon scale") return } - if (Math.abs(verticalIndicator.opticalCenterErrorX) > 0.5) { + if (Math.abs(verticalIndicator.opticalCenterErrorX) > 0.05) { fail("vertical indicator is not optically centered") return } @@ -134,6 +136,7 @@ ShellRoot { BarIconButton { id: audio; bar: testBar; text: "󰖁" } BarIconButton { id: monitor; bar: testBar; text: "󰍹" } BarIconButton { id: power; bar: testBar; text: "󰁹" } + BarIconButton { id: elsewhen; bar: testBar; text: "󰇧" } BarIconButton { id: vector bar: testBar diff --git a/test/shell.d/bar-widget-contract-test.sh b/test/shell.d/bar-widget-contract-test.sh index 95fd52b96e8e..1a022ed5f3df 100755 --- a/test/shell.d/bar-widget-contract-test.sh +++ b/test/shell.d/bar-widget-contract-test.sh @@ -21,7 +21,7 @@ trap cleanup EXIT require_compositor "bar widget contract test" if ! command -v quickshell >/dev/null 2>&1; then - pass "quickshell not installed; skipping bar widget contract test" + skip "quickshell not installed; skipping bar widget contract test" exit 0 fi diff --git a/test/shell.d/base-test.sh b/test/shell.d/base-test.sh index 9de42cf3b10a..476b8f8316d6 100644 --- a/test/shell.d/base-test.sh +++ b/test/shell.d/base-test.sh @@ -14,6 +14,10 @@ pass() { printf 'ok - %s\n' "$1" } +skip() { + printf 'ok - %s # SKIP\n' "$1" +} + fail() { local description="$1" local detail="${2:-}" @@ -23,6 +27,15 @@ fail() { exit 1 } +# The IPC socket a shell running an OMARCHY_PATH's config on this display +# serves, derived as omarchy-shell derives it. A test that starts the real +# shell removes it afterwards: killing the shell leaves the file behind. +shell_ipc_socket() { + local id + id=$(printf '%s\n%s' "$1/shell" "${WAYLAND_DISPLAY:-}" | md5sum) + printf '%s/omarchy-shell-%s.sock\n' "${XDG_RUNTIME_DIR:-/run/user/$UID}" "${id:0:16}" +} + require_command() { local command="$1" @@ -72,7 +85,7 @@ require_compositor() { return 0 fi - pass "no Wayland compositor; skipping $description" + skip "no Wayland compositor; skipping $description" exit 0 } diff --git a/test/shell.d/brightness-display-apple-cache-test.sh b/test/shell.d/brightness-display-apple-cache-test.sh index 18b65cd04344..0ed281cb1619 100755 --- a/test/shell.d/brightness-display-apple-cache-test.sh +++ b/test/shell.d/brightness-display-apple-cache-test.sh @@ -123,7 +123,7 @@ if [[ -n $real_hiddev ]]; then fail "wrapper did not trust a valid cached hiddev node: $real_hiddev" pass "wrapper trusts a cached hiddev character device without re-detecting" else - pass "no /dev/hiddev* character device present; skipping the valid-cache case" + skip "no /dev/hiddev* character device present; skipping the valid-cache case" fi # --- With no XDG_RUNTIME_DIR, the predictable /tmp cache is not consulted ------ @@ -148,5 +148,5 @@ if mkfifo "$tmp_cache" 2>/dev/null; then "it blocked reading the FIFO decoy at $tmp_cache" pass "wrapper ignores the /tmp cache path when XDG_RUNTIME_DIR is unset" else - pass "$tmp_cache already present or not safely creatable; skipping the /tmp-fallback case" + skip "$tmp_cache already present or not safely creatable; skipping the /tmp-fallback case" fi diff --git a/test/shell.d/brightness-keys-test.sh b/test/shell.d/brightness-keys-test.sh new file mode 100644 index 000000000000..9fa22fee34b1 --- /dev/null +++ b/test/shell.d/brightness-keys-test.sh @@ -0,0 +1,45 @@ +#!/bin/bash + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +run_node_test <<'JS' +const fs = require('fs') +const model = requireFromRoot('shell/services/BrightnessModel.js') + +// The in-shell brightness keys follow omarchy-brightness-display's steps. +const steps = [ + ['raise', 60, 65], ['lower', 60, 55], + ['raise', 4, 5], ['raise', 5, 10], ['lower', 5, 4], ['lower', 6, 1], + ['raise', 98, 100], ['raise', 100, 100], ['lower', 1, 1], ['lower', 2, 1], +] +for (const [action, current, target] of steps) { + assertEqual(model.brightnessKeyTarget(action, current), target, `brightness ${action} from ${current}% lands on ${target}%`) +} + +const qml = fs.readFileSync(path.join(root, 'shell/services/BrightnessKeys.qml'), 'utf8') +assert( + qml.includes('if (!/^(eDP|LVDS|DSI)-/.test(name) || !device) return false'), + 'brightness keys act in the shell only on the internal panel and defer external and Apple displays to the script' +) +assert( + /if \(setProc\.running\) return true/.test(qml), + 'brightness keys drop a press that overlaps one still being applied, as the script does' +) +assert( + /file\.reload\(\)\s*file\.waitForJob\(\)/.test(qml), + 'brightness keys read the current level fresh, so a level changed elsewhere steps from the right place' +) +assert( + qml.includes('var current = Math.round(100 * readNumber(brightnessFile) / max)') && + qml.includes('var percent = Math.round(100 * readNumber(brightnessFile) / max)'), + 'brightness keys compute percentages as brightnessctl reports them' +) + +const shellQml = fs.readFileSync(path.join(root, 'shell/shell.qml'), 'utf8') +assert( + /if \(!shell\.brightnessKeys\.handle\(entry\.target\)\)\s*Util\.execArgv\(\["omarchy-brightness-display", entry\.target === "raise" \? "\+5%" : "5%-"\]\)/.test(shellQml), + 'a brightness key the shell declines runs omarchy-brightness-display' +) +JS diff --git a/test/shell.d/browser-handoff-test.sh b/test/shell.d/browser-handoff-test.sh new file mode 100644 index 000000000000..c188399d9938 --- /dev/null +++ b/test/shell.d/browser-handoff-test.sh @@ -0,0 +1,85 @@ +#!/bin/bash + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +require_command python3 +require_command socat + +# The handoff only stands in for the packaged browser itself. +if [[ $(type -P chromium) != "/usr/bin/chromium" ]]; then + skip "browser handoff needs /usr/bin/chromium" + exit 0 +fi + +test_tmp=$(mktemp -d) +trap 'rm -rf "$test_tmp"' EXIT + +export XDG_CONFIG_HOME="$test_tmp/config" +socket="$XDG_CONFIG_HOME/chromium/SingletonSocket" +received="$test_tmp/received" +mkdir -p "${socket%/*}" +flags_file="$XDG_CONFIG_HOME/chromium-flags.conf" +cp "$ROOT/config/chromium-flags.conf" "$flags_file" +echo "# A comment of the user's" >>"$flags_file" + +# A running browser's side of the singleton socket: take each command line and +# acknowledge it, as Chromium does. +python3 - "$socket" "$received" <<'PY' & +import socket, sys +server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) +server.bind(sys.argv[1]) +server.listen(1) +while True: + connection, _ = server.accept() + message = b"" + while chunk := connection.recv(4096): + message += chunk + open(sys.argv[2], "wb").write(message) + connection.sendall(b"ACK") + connection.close() +PY +server=$! +trap 'kill "$server" 2>/dev/null || true; rm -rf "$test_tmp"' EXIT + +for _ in $(seq 100); do + [[ -S $socket ]] && break + sleep 0.02 +done + +(cd "$test_tmp" && "$ROOT/bin/omarchy-cmd-browser-handoff" chromium --app="https://example.test/a b") || + fail "the running browser acknowledges a handed off command line" + +expected=$(printf 'START\0%s\0browser\0--app=https://example.test/a b' "$test_tmp" | od -c) +[[ $(od -c <"$received") == "$expected" ]] || + fail "the handoff sends the working directory and arguments as Chromium's singleton expects" "$(od -c <"$received")" +pass "a command line is handed to the running browser over its singleton socket" + +! "$ROOT/bin/omarchy-cmd-browser-handoff" chromium --user-data-dir=/elsewhere https://example.test || + fail "another data directory is left to a browser of its own" +mkdir -p "$test_tmp/wrapper" +printf '#!/bin/bash\nexec /usr/bin/chromium --profile-directory=Work "$@"\n' >"$test_tmp/wrapper/chromium" +chmod +x "$test_tmp/wrapper/chromium" +! PATH="$test_tmp/wrapper:$PATH" "$ROOT/bin/omarchy-cmd-browser-handoff" chromium https://example.test || + fail "a wrapper standing in for the browser is left to run" +! CHROME_USER_DATA_DIR=/elsewhere "$ROOT/bin/omarchy-cmd-browser-handoff" chromium https://example.test || + fail "a data directory from the environment is left to a browser of its own" + +# The handoff forwards no flags file, so any flag beyond Omarchy's own, which +# may be meant for each launch, needs the launcher. +for flag in '--new-window' '--enable-features=A --profile-directory="Profile 1"'; do + cp "$ROOT/config/chromium-flags.conf" "$flags_file" + echo "$flag" >>"$flags_file" + ! "$ROOT/bin/omarchy-cmd-browser-handoff" chromium https://example.test || + fail "a flags file with $flag is left to the launcher" +done + +# The browser is gone but its socket file is left, as after a crash. +kill "$server" +wait "$server" 2>/dev/null || true +! "$ROOT/bin/omarchy-cmd-browser-handoff" chromium --app=https://example.test || + fail "a socket no browser answers on fails the handoff" +! "$ROOT/bin/omarchy-cmd-browser-handoff" firefox https://example.test || + fail "a browser without a singleton socket fails the handoff" +pass "the handoff fails when no Chromium-based browser answers, so the caller launches one" diff --git a/test/shell.d/browser-policy-dir-test.sh b/test/shell.d/browser-policy-dir-test.sh index 0d66d21666ed..fd679f898388 100755 --- a/test/shell.d/browser-policy-dir-test.sh +++ b/test/shell.d/browser-policy-dir-test.sh @@ -46,7 +46,7 @@ mode=$(stat -c '%a' "$write_dir/color.json") pass "theme colour writes a 0644 color.json" if (( EUID == 0 )); then - pass "running as root; skipping the mktemp-failure check" + skip "running as root; skipping the mktemp-failure check" else chmod u+w "$write_dir" export TMPDIR=$test_tmp/missing-tmp diff --git a/test/shell.d/browser-policy-sudoers-test.sh b/test/shell.d/browser-policy-sudoers-test.sh index 2af8ea2ba6f0..e9c3244d6849 100755 --- a/test/shell.d/browser-policy-sudoers-test.sh +++ b/test/shell.d/browser-policy-sudoers-test.sh @@ -82,7 +82,7 @@ SH chmod +x "$stub_bin/sudo" if ((EUID == 0)); then - pass "running as root; skipping the elevation checks, which would rewrite this machine's browser policy" + skip "running as root; skipping the elevation checks, which would rewrite this machine's browser policy" else elevation_for() { : >"$test_tmp/elevation" @@ -133,6 +133,13 @@ fi setter_bin="$test_tmp/setter-bin" mkdir -p "$setter_bin" +# The setter now skips its privileged policy write when every managed +# color.json already matches. Give it a fixed out-of-range fixture so every +# theme below takes the writer path. +policy_tmp="$test_tmp/policies" +mkdir -p "$policy_tmp/a" +printf '{"BrowserThemeColor": "#ff0000", "BrowserColorScheme": "device"}\n' > "$policy_tmp/a/color.json" + cat >"$setter_bin/omarchy-theme-set-browser-policy" <<'SH' #!/bin/bash printf '%s\n' "$*" >"$COLOR_LOG" @@ -158,6 +165,7 @@ color_for_theme() { fi HOME="$setter_home" COLOR_LOG="$test_tmp/color" PATH="$setter_bin:$stub_bin:$PATH" \ + OMARCHY_BROWSER_POLICY_DIRS="$policy_tmp/a" \ OMARCHY_PATH="$ROOT" bash "$setter" /dev/null 2>&1 || true cat "$test_tmp/color" } diff --git a/test/shell.d/button-border-stability-test.sh b/test/shell.d/button-border-stability-test.sh index a120f8ef70de..22b56dc0de47 100644 --- a/test/shell.d/button-border-stability-test.sh +++ b/test/shell.d/button-border-stability-test.sh @@ -20,7 +20,7 @@ JS require_compositor "Button hover geometry runtime test" if ! command -v quickshell >/dev/null 2>&1; then - pass "quickshell not installed; skipping Button hover geometry runtime test" + skip "quickshell not installed; skipping Button hover geometry runtime test" exit 0 fi diff --git a/test/shell.d/channel-sudo-boundary-test.sh b/test/shell.d/channel-sudo-boundary-test.sh new file mode 100755 index 000000000000..f98934c2bb20 --- /dev/null +++ b/test/shell.d/channel-sudo-boundary-test.sh @@ -0,0 +1,210 @@ +#!/bin/bash + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" +source "$SHELL_TEST_DIR/fixtures/sudo-boundary-test.sh" +copy_boundary_file bin/omarchy-channel-set +copy_boundary_file bin/omarchy-refresh-pacman +copy_boundary_file bin/omarchy-update +export OMARCHY_UPDATE_LOGGED=1 + +# Relocate the package root into the fixture, including the explicit handoff +# from the development checkout. All privileged operations remain stand-ins. +python3 - "$SUDO_TEST_ROOT/bin/omarchy-channel-set" "$SUDO_TEST_ROOT" <<'PY' +import sys +from pathlib import Path +p = Path(sys.argv[1]) +p.write_text(p.read_text().replace('/usr/share/omarchy', sys.argv[2])) +PY + +for command in omarchy-dev-link omarchy-dev-unlink omarchy-state gum git; do + cat >"$SUDO_TEST_ROOT/bin/$command" <<'STUB' +#!/bin/bash +set -euo pipefail +step=${0##*/} +printf 'step:%s %s\n' "$step" "$*" >>"$SUDO_TEST_LOG" +case "$step" in + omarchy-dev-link|omarchy-dev-unlink) sudo /usr/bin/true ;; + git) + [[ $1 == "clone" ]] || exit 90 + /usr/bin/cp -a "$SUDO_TEST_ROOT" "${@: -1}" + mkdir -p "${@: -1}/.git" "${@: -1}/shell" + ;; +esac +STUB + chmod +x "$SUDO_TEST_ROOT/bin/$command" +done + +assert_scoped_channel() { + local label=$1 + assert_boundary_cold "$label" + python3 - "$SUDO_TEST_LOG" <<'PY' +import sys +events = open(sys.argv[1]).read().splitlines() +assert events[0] == 'sudo -k', events +# The switch itself authorizes command by command. The update it hands off to +# starts cold and authorizes once for its own phases. +auth = events.index('sudo /usr/bin/true') +sudo = [event for event in events[:auth] if event.startswith('sudo ')] +assert all(event in ('sudo -h', 'sudo -k') or event.startswith('sudo -N ') for event in sudo), events +hooks = [i for i, event in enumerate(events) if event.startswith('step:omarchy-hook ')] +assert len(hooks) == 2, events +assert events[hooks[0]] == 'step:omarchy-hook pre-refresh-pacman', events +assert events[hooks[1]] == 'step:omarchy-hook post-update', events +assert events[hooks[0] - 1] == 'sudo -k' and events[hooks[0] + 1] == 'sudo -k', events +transaction = next(i for i, event in enumerate(events) if event.startswith('step:pacman ')) +assert hooks[0] < transaction < auth < hooks[1], events +assert 'sudo -k' in events[transaction:auth], events +PY +} + +run_channel() { + "$OMARCHY_PATH/bin/omarchy-channel-set" "$@" >"$boundary_tmp/output" 2>&1 +} +for channel in stable rc edge dev; do + reset_boundary + run_channel "$channel" || fail "$channel failed" "$(<"$boundary_tmp/output")" + assert_scoped_channel "$channel" + pass "$channel starts cold, authorizes the switch per command, runs the refresh hook cold, hands off to one update authorization and exits cold" +done + +reset_boundary +wrapper="$SUDO_TEST_HOME/omarchy/default/omarchy/sudo-no-update/sudo" +mv "$wrapper" "$boundary_tmp/saved-wrapper" +if run_channel dev; then fail "an old checkout without the wrapper was accepted"; fi +if grep -Eq '^step:omarchy-(dev-link|state)|^sudo -N ' "$SUDO_TEST_LOG"; then + fail "an incompatible dev checkout changed the system before rejection" +fi +grep -q 'Update the checkout before switching to dev' "$boundary_tmp/output" || fail "stale checkout rejection lacks recovery guidance" +assert_boundary_cold "stale checkout" +mv "$boundary_tmp/saved-wrapper" "$wrapper" +pass "a stale dev checkout is rejected before linking or privileged work" + +reset_boundary +OMARCHY_PATH="$SUDO_TEST_HOME/omarchy" run_channel stable || fail "leaving dev failed" "$(<"$boundary_tmp/output")" +assert_scoped_channel "dev to stable" +pass "leaving dev preserves no-update sudo through unlink and hands off to the packaged update" + +# A packaged destination that predates the wrapper cannot be checked before its +# package is installed. Its updater authenticates without --no-update, so the +# switch must not launch it: it stops at a consistent point with instructions. +reset_boundary +mv "$SUDO_TEST_ROOT/default/omarchy/sudo-no-update/sudo" "$boundary_tmp/saved-package-wrapper" +mv "$SUDO_TEST_ROOT/bin/omarchy-update" "$boundary_tmp/saved-package-update" +ln -s test-step "$SUDO_TEST_ROOT/bin/omarchy-update" +if OMARCHY_PATH="$SUDO_TEST_HOME/omarchy" run_channel stable; then fail "an older packaged destination was updated with ordinary sudo" "$(<"$SUDO_TEST_LOG")"; fi +grep -q "predates command-scoped sudo" "$boundary_tmp/output" || fail "an older packaged destination was not reported" "$(<"$boundary_tmp/output")" +grep -q "Run 'omarchy update' from a new terminal to finish" "$boundary_tmp/output" || fail "an older packaged destination lacks recovery guidance" "$(<"$boundary_tmp/output")" +grep -Fxq 'step:omarchy-dev-unlink --no-reboot' "$SUDO_TEST_LOG" || fail "the package switch was not completed before stopping" "$(<"$SUDO_TEST_LOG")" +grep -Fxq 'step:omarchy-state set reboot-required' "$SUDO_TEST_LOG" || fail "leaving dev for an older release did not mark the reboot" "$(<"$SUDO_TEST_LOG")" +if grep -q '^step:omarchy-update ' "$SUDO_TEST_LOG"; then fail "an older packaged updater was launched from the hardened switch" "$(<"$SUDO_TEST_LOG")"; fi +grep -q 'The channel switch did not complete' "$boundary_tmp/output" && fail "the stop was reported as an error needing a rerun" "$(<"$boundary_tmp/output")" +assert_boundary_cold "older packaged destination" +rm "$SUDO_TEST_ROOT/bin/omarchy-update" +mv "$boundary_tmp/saved-package-update" "$SUDO_TEST_ROOT/bin/omarchy-update" +mv "$boundary_tmp/saved-package-wrapper" "$SUDO_TEST_ROOT/default/omarchy/sudo-no-update/sudo" +pass "an older packaged destination stops the switch cold with instructions instead of running its updater" + +# A package-backed source can be downgraded by its own transaction to a release +# without the wrapper. From then on a bare sudo would be the real one, so no +# privileged step may follow either transaction without checking first. A decoy +# sudo in the package bin catches any such call instead of reaching the host. +rm "$SUDO_TEST_ROOT/bin/sudo" +cat >"$SUDO_TEST_ROOT/bin/sudo" <<'STUB' +#!/bin/bash +printf 'unwrapped-sudo %s\n' "$*" >>"$SUDO_TEST_LOG" +exit 97 +STUB +chmod +x "$SUDO_TEST_ROOT/bin/sudo" +cp "$SUDO_TEST_ROOT/default/omarchy/sudo-no-update/sudo" "$boundary_tmp/saved-package-wrapper" +for pattern in 'pacman -Syyuu*' 'pacman -S --needed*'; do + reset_boundary + export SUDO_TEST_REMOVE_WRAPPER_STEP=$pattern + if run_channel rc; then fail "a downgrade during '$pattern' was not detected" "$(<"$SUDO_TEST_LOG")"; fi + unset SUDO_TEST_REMOVE_WRAPPER_STEP + grep -q "predates command-scoped sudo" "$boundary_tmp/output" || fail "downgrade during '$pattern' was not reported" "$(<"$boundary_tmp/output")" + if grep -q '^unwrapped-sudo ' "$SUDO_TEST_LOG"; then fail "downgrade during '$pattern' reached ordinary sudo" "$(<"$SUDO_TEST_LOG")"; fi + if grep -q '^step:omarchy-dev-unlink' "$SUDO_TEST_LOG"; then fail "downgrade during '$pattern' still unlinked" "$(<"$SUDO_TEST_LOG")"; fi + if grep -q '^step:omarchy-update ' "$SUDO_TEST_LOG"; then fail "downgrade during '$pattern' still updated" "$(<"$SUDO_TEST_LOG")"; fi + python3 - "$SUDO_TEST_LOG" "$pattern" <<'PY' +import sys +events = open(sys.argv[1]).read().splitlines() +transactions = [e for e in events if e.startswith('step:pacman ')] +assert len(transactions) == (1 if sys.argv[2].startswith('pacman -Syyuu') else 2), events +assert all(e in ('sudo -h', 'sudo -k') or e.startswith('sudo -N ') for e in events if e.startswith('sudo ')), events +PY + assert_boundary_cold "downgrade during $pattern" + cp "$boundary_tmp/saved-package-wrapper" "$SUDO_TEST_ROOT/default/omarchy/sudo-no-update/sudo" + pass "a transaction that removes the wrapper stops the switch before any further sudo ($pattern)" +done +rm "$SUDO_TEST_ROOT/bin/sudo" +ln -s ../mock/sudo "$SUDO_TEST_ROOT/bin/sudo" + +mkdir "$boundary_tmp/user tools" +cat >"$boundary_tmp/user tools/channel-user-tool" <<'STUB' +#!/bin/bash +printf 'user-tool:%s\n' "$*" >>"$SUDO_TEST_LOG" +STUB +chmod +x "$boundary_tmp/user tools/channel-user-tool" +for command in omarchy-hook omarchy-update-mise; do + rm "$SUDO_TEST_ROOT/bin/$command" + cat >"$SUDO_TEST_ROOT/bin/$command" <<'STUB' +#!/bin/bash +if [[ ${1:-} == "pre-refresh-pacman" ]]; then + [[ ! -e $SUDO_TEST_CACHE ]] || exit 91 + [[ $(command -v sudo) == "$OMARCHY_PATH/default/omarchy/sudo-no-update/sudo" ]] || exit 92 +else + [[ -e $SUDO_TEST_CACHE ]] || exit 94 + [[ $(command -v sudo) != "$OMARCHY_PATH/default/omarchy/sudo-no-update/sudo" ]] || exit 95 +fi +channel-user-tool "${0##*/}" "$@" +STUB + chmod +x "$SUDO_TEST_ROOT/bin/$command" +done +reset_boundary +PATH="$boundary_tmp/user tools:$PATH" run_channel stable || fail "channel hooks lost the user's PATH" "$(<"$boundary_tmp/output")" +for event in 'omarchy-hook post-update' 'omarchy-update-mise' 'omarchy-hook pre-refresh-pacman'; do + grep -Fxq "user-tool:$event" "$SUDO_TEST_LOG" || fail "user PATH was not preserved for $event" +done +assert_boundary_cold "channel user PATH" +for command in omarchy-hook omarchy-update-mise; do + ln -sfn test-step "$SUDO_TEST_ROOT/bin/$command" +done +pass "channel switching preserves user tools for both hooks and mise" + +for step in pacman omarchy-update-system-pkgs omarchy-hook; do + reset_boundary + if SUDO_TEST_FAIL_STEP="$step" run_channel stable; then fail "$step failure was ignored"; fi + assert_boundary_cold "$step failure" + if grep -q '^step:omarchy-hook post-update$' "$SUDO_TEST_LOG"; then fail "$step failure reached the post-update hook"; fi + pass "$step failure exits cold without the post-update hook" +done + +for signal in HUP INT TERM; do + reset_boundary + cat >"$SUDO_TEST_ROOT/bin/omarchy-dev-unlink" <<'STUB' +#!/bin/bash +sudo /usr/bin/true || exit 1 +kill -s "$SUDO_TEST_CHANNEL_SIGNAL" "$PPID" +STUB + if SUDO_TEST_CHANNEL_SIGNAL="$signal" run_channel stable; then fail "$signal was ignored"; fi + assert_boundary_cold "$signal" + if grep -q '^step:omarchy-hook post-update$' "$SUDO_TEST_LOG"; then fail "$signal reached the post-update hook"; fi + pass "$signal stops the channel transition and revokes authorization" +done + +for refusal in unsupported-sudo failed-revocation ordinary-bash; do + reset_boundary + case "$refusal" in + unsupported-sudo) export SUDO_TEST_UNSUPPORTED=1 ;; + failed-revocation) export SUDO_TEST_REVOKE_FAIL=1 ;; + esac + if [[ $refusal == "ordinary-bash" ]]; then + if /usr/bin/bash "$SUDO_TEST_ROOT/bin/omarchy-channel-set" -p >"$boundary_tmp/output" 2>&1; then fail "$refusal was accepted"; fi + elif run_channel stable; then + fail "$refusal was accepted" + fi + if grep -q '^step:' "$SUDO_TEST_LOG"; then fail "$refusal reached channel work"; fi + pass "$refusal is rejected before channel work" +done diff --git a/test/shell.d/channel-test.sh b/test/shell.d/channel-test.sh index 664e17c50b53..cbbfc6e88311 100644 --- a/test/shell.d/channel-test.sh +++ b/test/shell.d/channel-test.sh @@ -4,10 +4,18 @@ set -euo pipefail source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" -test_tmp=$(mktemp -d) -trap 'rm -rf "$test_tmp"' EXIT - -stub_bin="$test_tmp/bin" +source "$SHELL_TEST_DIR/fixtures/sudo-boundary-test.sh" +test_tmp="$boundary_tmp" +package_root="$SUDO_TEST_ROOT" +copy_boundary_file bin/omarchy-channel-set +python3 - "$SUDO_TEST_ROOT/bin/omarchy-channel-set" "$package_root" <<'PYTHON' +import sys +from pathlib import Path +p = Path(sys.argv[1]) +p.write_text(p.read_text().replace("/usr/share/omarchy", sys.argv[2])) +PYTHON + +stub_bin="$SUDO_TEST_ROOT/bin" log_file="$test_tmp/channel.log" mkdir -p "$stub_bin" "$test_tmp/home" @@ -15,6 +23,7 @@ write_stub() { local name="$1" local body="$2" + rm -f "$stub_bin/$name" cat >"$stub_bin/$name" <<<"$body" chmod +x "$stub_bin/$name" } @@ -26,11 +35,23 @@ printf "\n" >>"$OMARCHY_CHANNEL_TEST_LOG" ' write_stub sudo '#!/bin/bash +case "${1:-}" in + -h) echo "usage: sudo [-ABbEHkNnPS] command"; exit 0 ;; + -k|-K) exit 0 ;; +esac printf "sudo" >>"$OMARCHY_CHANNEL_TEST_LOG" for arg in "$@"; do printf "\t%s" "$arg" >>"$OMARCHY_CHANNEL_TEST_LOG"; done printf "\n" >>"$OMARCHY_CHANNEL_TEST_LOG" ' +cp "$stub_bin/sudo" "$SUDO_TEST_ROOT/mock/sudo" + +write_stub omarchy-update-pacman '#!/bin/bash +printf "update-pacman" >>"$OMARCHY_CHANNEL_TEST_LOG" +for arg in "$@"; do printf "\t%s" "$arg" >>"$OMARCHY_CHANNEL_TEST_LOG"; done +printf "\n" >>"$OMARCHY_CHANNEL_TEST_LOG" +' + write_stub omarchy-dev-unlink '#!/bin/bash printf "unlink" >>"$OMARCHY_CHANNEL_TEST_LOG" for arg in "$@"; do printf "\t%s" "$arg" >>"$OMARCHY_CHANNEL_TEST_LOG"; done @@ -63,7 +84,8 @@ for arg in "$@"; do printf "\t%s" "$arg" >>"$OMARCHY_CHANNEL_TEST_LOG"; done printf "\n" >>"$OMARCHY_CHANNEL_TEST_LOG" if [[ $1 == "clone" ]]; then dest="${@: -1}" - mkdir -p "$dest/.git" "$dest/bin" "$dest/default" "$dest/shell" + /usr/bin/cp -a "$SUDO_TEST_ROOT" "$dest" + mkdir -p "$dest/.git" "$dest/shell" fi ' @@ -90,10 +112,10 @@ esac run_channel() { : >"$log_file" OMARCHY_CHANNEL_TEST_LOG="$log_file" \ - OMARCHY_PATH="${OMARCHY_TEST_PATH:-/usr/share/omarchy}" \ + OMARCHY_PATH="${OMARCHY_TEST_PATH:-$package_root}" \ HOME="$test_tmp/home" \ PATH="$stub_bin:$ROOT/bin:$PATH" \ - "$ROOT/bin/omarchy-channel-set" "$@" + "${OMARCHY_TEST_PATH:-$package_root}/bin/omarchy-channel-set" "$@" } assert_log_line() { @@ -106,9 +128,9 @@ assert_log_line() { run_channel stable assert_log_line $'refresh\tstable' "stable refreshes the stable pacman channel" -assert_log_line $'sudo\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy\tomarchy-settings' "stable installs stable Omarchy packages" +assert_log_line $'update-pacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy\tomarchy-settings' "stable installs stable Omarchy packages" assert_log_line $'unlink\t--no-reboot' "stable restores the package-backed Omarchy path without an early reboot prompt" -assert_log_line $'update\t-y\tOMARCHY_PATH=/usr/share/omarchy' "stable runs the normal update pipeline from the package-backed path" +assert_log_line $'update\t-y\tOMARCHY_PATH='"$package_root" "stable runs the normal update pipeline from the package-backed path" if grep -q $'^state\tset\treboot-required$' "$log_file"; then fail "stable does not require reboot when already package-backed" "$(cat "$log_file")" fi @@ -116,17 +138,19 @@ pass "stable does not require reboot when already package-backed" run_channel rc assert_log_line $'refresh\trc' "rc refreshes the rc pacman channel" -assert_log_line $'sudo\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy\tomarchy-settings' "rc installs rc Omarchy packages" +assert_log_line $'update-pacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy\tomarchy-settings' "rc installs rc Omarchy packages" assert_log_line $'unlink\t--no-reboot' "rc restores the package-backed Omarchy path without an early reboot prompt" -assert_log_line $'update\t-y\tOMARCHY_PATH=/usr/share/omarchy' "rc runs the normal update pipeline from the package-backed path" +assert_log_line $'update\t-y\tOMARCHY_PATH='"$package_root" "rc runs the normal update pipeline from the package-backed path" -OMARCHY_TEST_PATH="$ROOT" run_channel edge +active_checkout="$test_tmp/active-checkout" +cp -a "$package_root" "$active_checkout" +OMARCHY_TEST_PATH="$active_checkout" run_channel edge assert_log_line $'refresh\tedge' "edge refreshes the edge pacman channel" -assert_log_line $'sudo\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev' "edge installs development Omarchy packages" +assert_log_line $'update-pacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev' "edge installs development Omarchy packages" assert_log_line $'unlink\t--no-reboot' "edge unlinks dev without an early reboot prompt" assert_log_line $'state\tset\treboot-required' "edge marks reboot required when leaving dev" -assert_log_line $'update\t-y\tOMARCHY_PATH=/usr/share/omarchy' "edge runs the normal update pipeline from the package-backed path" -[[ $(grep -E '^(unlink|state|update)' "$log_file") == $'unlink\t--no-reboot\nstate\tset\treboot-required\nupdate\t-y\tOMARCHY_PATH=/usr/share/omarchy' ]] || +assert_log_line $'update\t-y\tOMARCHY_PATH='"$package_root" "edge runs the normal update pipeline from the package-backed path" +[[ $(grep -E $'^(unlink|state|update)\t' "$log_file") == $'unlink\t--no-reboot\nstate\tset\treboot-required\nupdate\t-y\tOMARCHY_PATH='"$package_root" ]] || fail "edge defers the reboot prompt until the update restart stage" "$(cat "$log_file")" pass "edge defers the reboot prompt until the update restart stage" @@ -146,12 +170,12 @@ rmdir "$checkout" run_channel dev assert_log_line $'gum\tconfirm\t--default=false\tSwitch to dev channel?' "dev asks for confirmation" assert_log_line $'refresh\tedge' "dev refreshes the edge pacman channel" -assert_log_line $'sudo\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev' "dev installs development Omarchy packages" -assert_log_line $'git\tclone\thttps://github.com/basecamp/omarchy.git\t'"$checkout" "dev clones the source checkout to ~/omarchy" +assert_log_line $'update-pacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev' "dev installs development Omarchy packages" +assert_log_line $'git\tclone\thttps://github.com/omacom/omarchy.git\t'"$checkout" "dev clones the source checkout to ~/omarchy" assert_log_line $'link\t'"$checkout"$'\t--no-reboot' "dev links ~/omarchy without an early reboot prompt" assert_log_line $'state\tset\treboot-required' "dev defers the reboot prompt to the update pipeline" assert_log_line $'update\t-y\tOMARCHY_PATH='"$checkout" "dev runs the normal update pipeline from the source checkout" -[[ $(grep -E '^(git|link|state|refresh|sudo|update)' "$log_file") == $'git\tclone\thttps://github.com/basecamp/omarchy.git\t'"$checkout"$'\nlink\t'"$checkout"$'\t--no-reboot\nstate\tset\treboot-required\nrefresh\tedge\nsudo\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev\nupdate\t-y\tOMARCHY_PATH='"$checkout" ]] || +[[ $(grep -E '^(git|link|state|refresh|sudo|update)' "$log_file") == $'git\tclone\thttps://github.com/omacom/omarchy.git\t'"$checkout"$'\nlink\t'"$checkout"$'\t--no-reboot\nstate\tset\treboot-required\nrefresh\tedge\nupdate-pacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev\nupdate\t-y\tOMARCHY_PATH='"$checkout" ]] || fail "dev activates the checkout before changing or updating packages" "$(cat "$log_file")" pass "dev activates the checkout before changing or updating packages" diff --git a/test/shell.d/chromium-claude-test.sh b/test/shell.d/chromium-claude-test.sh new file mode 100644 index 000000000000..04ad51d3c6cd --- /dev/null +++ b/test/shell.d/chromium-claude-test.sh @@ -0,0 +1,50 @@ +#!/bin/bash + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +# Exercise the privileged installer without writing to the host's /usr/share. +if ! command -v bwrap >/dev/null || ! bwrap --ro-bind / / --unshare-user --uid 0 --gid 0 true 2>/dev/null; then + skip "user namespaces unavailable; skipping isolated Claude extension installation" + exit 0 +fi + +test_tmp=$(mktemp -d) +trap 'rm -rf "$test_tmp"' EXIT +mkdir -p "$test_tmp/share" "$test_tmp/bin" +installer="$ROOT/bin/omarchy-install-chromium-claude" +extension_id=fcoeoabgfenejglbffodgkkbkcdhcgfn +sandbox=(bwrap --ro-bind / / --bind "$test_tmp" "$test_tmp" --dev /dev --proc /proc --unshare-user) + +"${sandbox[@]}" --uid 0 --gid 0 --bind "$test_tmp/share" /usr/share bash "$installer" +for browser in chromium google-chrome microsoft-edge; do + file="$test_tmp/share/$browser/extensions/$extension_id.json" + jq -e '.external_update_url == "https://clients2.google.com/service/update2/crx"' "$file" >/dev/null || + fail "$browser registers the official Claude Web Store extension" + [[ $(stat -c '%a' "$file") == "644" ]] || fail "$browser extension registration is readable" +done +pass "Claude extension installer registers all supported browser families" + +cat >"$test_tmp/bin/pkexec" <<'SH' +#!/bin/bash +printf '%s\n' "$@" >"$AUTH_LOG" +exit 42 +SH +chmod +x "$test_tmp/bin/pkexec" +export AUTH_LOG="$test_tmp/auth-log" +export PATH="$test_tmp/bin:$PATH" + +# A read-only /usr/share and a failing auth stub prove that a repeated run +# neither rewrites the files nor requests authentication. +"${sandbox[@]}" --uid 1000 --gid 1000 --ro-bind "$test_tmp/share" /usr/share bash "$installer" "$EDITOR_PATH_OUT" cat "$1" >"$EDITOR_TEXT_OUT" SH -cat >"$TMPDIR/bin/tensaku-edit" <<'SH' +cat >"$TMPDIR/bin/omasnap" <<'SH' #!/bin/bash -printf '%s\n' "$*" >"$TENSAKU_OUT" +printf '%s\n' "$*" >"$OMASNAP_OUT" SH -chmod +x "$TMPDIR/bin/wl-copy" "$TMPDIR/bin/wl-paste" "$TMPDIR/bin/wtype" "$TMPDIR/bin/omarchy-launch-browser" "$TMPDIR/bin/omarchy-launch-editor" "$TMPDIR/bin/tensaku-edit" +chmod +x "$TMPDIR/bin/wl-copy" "$TMPDIR/bin/wl-paste" "$TMPDIR/bin/wtype" "$TMPDIR/bin/omarchy-launch-browser" "$TMPDIR/bin/omarchy-launch-editor" "$TMPDIR/bin/omasnap" capture_output=$(XDG_RUNTIME_DIR="$TMPDIR" XDG_STATE_HOME="$TMPDIR/state" PATH="$TMPDIR/bin:$PATH" "$ROOT/shell/plugins/clipboard/capture.sh") [[ $capture_output == '{"type":"text","text":"terminal copy"}' ]] || fail "clipboard capture records normal text events" @@ -513,8 +513,8 @@ pass "clipboard open helper opens text entries in editor" [[ $(<"$TMPDIR/editor-path") == "$TMPDIR"/state/omarchy/clipboard-open/clipboard.*.txt ]] || fail "clipboard open helper writes text entries to a temporary file" pass "clipboard open helper writes text entries to a temporary file" -TENSAKU_OUT="$TMPDIR/tensaku" HOME="$TMPDIR/home" PATH="$TMPDIR/bin:$PATH" \ +OMASNAP_OUT="$TMPDIR/omasnap" HOME="$TMPDIR/home" PATH="$TMPDIR/bin:$PATH" \ "$ROOT/bin/omarchy-clipboard-open" --history-index 2 -[[ $(<"$TMPDIR/tensaku") == "$TMPDIR/image.png" ]] || fail "clipboard open helper opens image entries in Tensaku" -pass "clipboard open helper opens image entries in Tensaku" +[[ $(<"$TMPDIR/omasnap") == "$TMPDIR/image.png" ]] || fail "clipboard open helper opens image entries in Omasnap" +pass "clipboard open helper opens image entries in Omasnap" diff --git a/test/shell.d/clock-test.sh b/test/shell.d/clock-test.sh index e10d62f12267..d2bde8a1bb6c 100755 --- a/test/shell.d/clock-test.sh +++ b/test/shell.d/clock-test.sh @@ -265,7 +265,7 @@ shell_json=$(cd "$ROOT" && jq -r '[.bar.layout.center[].id] | join(",")' config/ [[ $shell_json != *"omarchy.calendar"* ]] || fail "clock hosts the calendar instead of a second bar pill" "center: $shell_json" pass "default bar layout includes the clock widget" -grep -q 'o.bind("SUPER + CTRL + ALT + D", "Calendar", "omarchy-shell shell toggle omarchy.clock")' \ +grep -q 'o.bind("SUPER + CTRL + ALT + D", "Calendar", { panel = "omarchy.clock" })' \ "$ROOT/default/hypr/bindings/utilities.lua" || fail "SUPER+CTRL+ALT+D toggles the calendar panel" pass "SUPER+CTRL+ALT+D toggles the calendar panel" diff --git a/test/shell.d/color-reference-test.sh b/test/shell.d/color-reference-test.sh new file mode 100755 index 000000000000..498f6789e35c --- /dev/null +++ b/test/shell.d/color-reference-test.sh @@ -0,0 +1,52 @@ +#!/bin/bash +set -euo pipefail +source "$(dirname "$0")/base-test.sh" + +run_node_test <<'JS' +const fs = require('fs') +const vm = require('vm') + +const source = fs.readFileSync(path.join(root, 'shell/Commons/Color.qml'), 'utf8') +const geometry = fs.readFileSync(path.join(root, 'shell/Commons/BorderGeometry.js'), 'utf8').replace(/^\.pragma library\n/, '') +const palette = { foreground: '#eeeeee', background: '#111111', accent: '#abcdef', urgent: '#ff0000', muted: '#777777' } +const context = vm.createContext({ root: { ...palette, shellValues: {} }, Geometry: {} }) +vm.runInNewContext(geometry, context.Geometry) +for (const name of ['firstColorToken', 'flatColor', 'parseShell']) { + const fn = source.match(new RegExp(` function ${name}\\([^]*?\\n }`)) + if (!fn) fail(`Color.qml provides ${name}`) + vm.runInContext(fn[0], context) +} + +function check(values, input, expected, description) { + context.root.shellValues = values + context.input = input + const result = vm.runInContext('flatColor(input, "#123456")', context, { timeout: 1000 }) + assertEqual(result, expected, description) +} + +const cycle = context.parseShell('[bar]\nbackground = "menu.background"\n[menu]\nbackground = "bar.background"') +check(cycle, 'bar.background', '#123456', 'two-entry theme cycle returns the supplied fallback') +check({ 'a.color': 'b.color', 'b.color': 'c.color', 'c.color': 'a.color' }, 'a.color', '#123456', 'longer cycle returns fallback') +check({ 'start.color': 'a.color', 'a.color': 'b.color', 'b.color': 'a.color' }, 'start.color', '#123456', 'chain entering a cycle returns fallback') +check({ 'a.color': 'a.color' }, 'a.color', '#123456', 'direct self-reference returns fallback') +check({ 'a.color': ' A.COLOR ' }, 'a.color', '#123456', 'normalized self-reference returns fallback') +check({ 'a.color': '45deg b.color #ffffff', 'b.color': 'a.color' }, 'a.color', '#123456', 'gradient first-stop cycle returns fallback') + +check({ 'a.color': 'b.color', 'b.color': '#abcdef' }, 'a.color', '#abcdef', 'acyclic references preserve the final color') +check({ 'a.color': ' B.COLOR ', 'b.color': '#abcdef' }, 'A.COLOR', '#abcdef', 'each reference keeps case and whitespace normalization') +check({ 'a.color': 'b.color', 'b.color': 'accent' }, 'a.color', palette.accent, 'acyclic references preserve palette roles') +check({ 'a.color': '45deg rgba(11223380) #ffffff' }, 'a.color', '#11223380', 'referenced gradient keeps its first color and alpha') +check({ 'a.color': 'missing.color' }, 'a.color', '#123456', 'missing reference returns fallback') +check({}, '', '#123456', 'empty input returns fallback') +for (const [role, color] of Object.entries(palette)) check({}, role, color, `palette role ${role} is unchanged`) +check({}, 'text', palette.foreground, 'text alias is unchanged') +for (const [input, output] of [['#abc', '#aabbcc'], ['#abcdef', '#abcdef'], ['rgb(abcdef)', '#abcdef'], ['rgba(11223380)', '#11223380']]) { + check({}, input, output, `direct color ${input} is unchanged`) +} + +const chain = {} +for (let i = 0; i < 10000; i++) chain[`chain.c${i}`] = `chain.c${i + 1}` +chain['chain.c10000'] = '#abcdef' +check(chain, 'chain.c0', '#abcdef', 'long acyclic chains do not exhaust the call stack') +check({ 'a.color': '#abcdef' }, 'a.color', '#abcdef', 'visited references do not leak between resolutions') +JS diff --git a/test/shell.d/command-operand-boundaries-test.sh b/test/shell.d/command-operand-boundaries-test.sh new file mode 100755 index 000000000000..652b1ce71d26 --- /dev/null +++ b/test/shell.d/command-operand-boundaries-test.sh @@ -0,0 +1,259 @@ +#!/bin/bash + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +export OMARCHY_PATH="$ROOT" + +if "$ROOT/bin/omarchy-cmd-present" -p; then + fail "cmd-present treats an option-shaped command name literally" +fi +pass "cmd-present treats an option-shaped command name literally" + +"$ROOT/bin/omarchy-cmd-missing" -p || + fail "cmd-missing treats an option-shaped command name literally" +pass "cmd-missing treats an option-shaped command name literally" + +"$ROOT/bin/omarchy-cmd-present" bash || fail "cmd-present still finds an ordinary command" +pass "cmd-present still finds an ordinary command" + +test_tmp=$(mktemp -d) +trap 'rm -rf "$test_tmp"' EXIT + +mock_bin="$test_tmp/bin" +mkdir -p "$mock_bin" + +cat >"$mock_bin/pacman" <<'STUB' +#!/bin/bash + +if [[ -n ${OMARCHY_TEST_PACKAGE_CALLS:-} ]]; then + { + printf 'pacman' + printf ' <%s>' "$@" + printf '\n' + } >>"$OMARCHY_TEST_PACKAGE_CALLS" +fi + +if [[ $1 == "-S" ]]; then + exit 0 +elif [[ $1 != "-Q" ]]; then + exit 2 +fi +shift + +if [[ -n ${OMARCHY_TEST_PACKAGE_CALLS:-} ]]; then + exit 0 +elif [[ ${1:-} == "--" ]]; then + shift + [[ ${1:-} == "installed" ]] +elif [[ ${1:-} == "--help" ]]; then + exit 0 +else + [[ ${1:-} == "installed" ]] +fi +STUB +chmod +x "$mock_bin/pacman" + +if PATH="$mock_bin:$PATH" "$ROOT/bin/omarchy-pkg-present" --help; then + fail "pkg-present treats an option-shaped package name literally" +fi +pass "pkg-present treats an option-shaped package name literally" + +PATH="$mock_bin:$PATH" "$ROOT/bin/omarchy-pkg-missing" --help || + fail "pkg-missing treats an option-shaped package name literally" +pass "pkg-missing treats an option-shaped package name literally" + +PATH="$mock_bin:$PATH" "$ROOT/bin/omarchy-pkg-present" installed || + fail "pkg-present still finds an installed package" +pass "pkg-present still finds an installed package" + +package_calls="$test_tmp/package-calls" +cat >"$mock_bin/omarchy-pkg-missing" <<'STUB' +#!/bin/bash + +exit 0 +STUB +cat >"$mock_bin/sudo" <<'STUB' +#!/bin/bash + +exec "$@" +STUB +cat >"$mock_bin/yay" <<'STUB' +#!/bin/bash + +: "${OMARCHY_TEST_PACKAGE_CALLS:?}" +{ + printf 'yay' + printf ' <%s>' "$@" + printf '\n' +} >>"$OMARCHY_TEST_PACKAGE_CALLS" +STUB +chmod +x "$mock_bin/omarchy-pkg-missing" "$mock_bin/sudo" "$mock_bin/yay" + +: >"$package_calls" +PATH="$mock_bin:$ROOT/bin:$PATH" OMARCHY_TEST_PACKAGE_CALLS="$package_calls" \ + "$ROOT/bin/omarchy-pkg-add" --hookdir=/tmp/hooks + +grep -Fx 'pacman <-S> <--noconfirm> <--needed> <--> <--hookdir=/tmp/hooks>' "$package_calls" >/dev/null || + fail "pkg-add separates package operands from pacman options" "$(<"$package_calls")" +grep -Fx 'pacman <-Q> <--> <--hookdir=/tmp/hooks>' "$package_calls" >/dev/null || + fail "pkg-add verifies an option-shaped package name literally" "$(<"$package_calls")" +pass "pkg-add keeps option-shaped package names out of pacman option parsing" + +: >"$package_calls" +PATH="$mock_bin:$ROOT/bin:$PATH" OMARCHY_TEST_PACKAGE_CALLS="$package_calls" \ + "$ROOT/bin/omarchy-pkg-aur-add" --hookdir=/tmp/hooks + +grep -Fx 'yay <-S> <--noconfirm> <--needed> <--> <--hookdir=/tmp/hooks>' "$package_calls" >/dev/null || + fail "pkg-aur-add separates package operands from yay options" "$(<"$package_calls")" +grep -Fx 'pacman <-Q> <--> <--hookdir=/tmp/hooks>' "$package_calls" >/dev/null || + fail "pkg-aur-add verifies an option-shaped package name literally" "$(<"$package_calls")" +pass "pkg-aur-add keeps option-shaped package names out of package-manager option parsing" + +cat >"$mock_bin/grep" <<'STUB' +#!/bin/bash + +if [[ $1 != "-qi" ]]; then + exit 2 +fi +shift + +if [[ ${1:-} == "--help" ]]; then + exit 0 +elif [[ ${1:-} == "--" ]]; then + shift +fi +[[ ${1:-} == "known-hardware" ]] +STUB +chmod +x "$mock_bin/grep" + +if PATH="$mock_bin:$PATH" "$ROOT/bin/omarchy-hw-match" --help; then + fail "hw-match treats an option-shaped hardware pattern literally" +fi +pass "hw-match treats an option-shaped hardware pattern literally" + +PATH="$mock_bin:$PATH" "$ROOT/bin/omarchy-hw-match" known-hardware || + fail "hw-match still accepts an ordinary hardware pattern" +pass "hw-match still accepts an ordinary hardware pattern" + +pkill_calls="$test_tmp/pkill-calls" +cat >"$mock_bin/pkill" <<'STUB' +#!/bin/bash + +: "${OMARCHY_TEST_PKILL_CALLS:?}" +printf '<%s>\n' "$@" >"$OMARCHY_TEST_PKILL_CALLS" +STUB +cat >"$mock_bin/setsid" <<'STUB' +#!/bin/bash + +if [[ -n ${OMARCHY_TEST_SETSID_CALLS:-} ]]; then + printf '<%s>\n' "$@" >"$OMARCHY_TEST_SETSID_CALLS" +fi +exit 0 +STUB +chmod +x "$mock_bin/pkill" "$mock_bin/setsid" + +PATH="$mock_bin:$PATH" OMARCHY_TEST_PKILL_CALLS="$pkill_calls" \ + "$ROOT/bin/omarchy-restart-app" "-9 kitty" + +pkill_argv=$(<"$pkill_calls") +[[ $pkill_argv == $'<-x>\n<-->\n<-9 kitty>' ]] || + fail "restart-app treats the application name as one literal pkill pattern" "$pkill_argv" +pass "restart-app treats the application name as one literal pkill pattern" + +fake_home="$test_tmp/home" +editor_calls="$test_tmp/editor-calls" +mkdir -p "$fake_home/.local/state/omarchy/defaults" +printf 'nvim\n' >"$fake_home/.local/state/omarchy/defaults/editor" + +cat >"$mock_bin/nvim" <<'STUB' +#!/bin/bash + +: "${OMARCHY_TEST_EDITOR_CALLS:?}" +printf '<%s>\n' "$@" >"$OMARCHY_TEST_EDITOR_CALLS" +STUB +chmod +x "$mock_bin/nvim" + +HOME="$fake_home" PATH="$mock_bin:$ROOT/bin:$PATH" OMARCHY_TEST_EDITOR_CALLS="$editor_calls" \ + "$ROOT/bin/omarchy-launch-editor" --inline -cquit + +editor_argv=$(<"$editor_calls") +[[ $editor_argv == $'<-->\n<-cquit>' ]] || + fail "launch-editor separates an option-shaped path from editor options" "$editor_argv" +pass "launch-editor separates an option-shaped path from editor options" + +cat >"$mock_bin/omarchy-launch-tui" <<'STUB' +#!/bin/bash + +: "${OMARCHY_TEST_EDITOR_CALLS:?}" +printf '<%s>\n' "$@" >"$OMARCHY_TEST_EDITOR_CALLS" +STUB +chmod +x "$mock_bin/omarchy-launch-tui" + +HOME="$fake_home" PATH="$mock_bin:$ROOT/bin:$PATH" OMARCHY_TEST_EDITOR_CALLS="$editor_calls" \ + "$ROOT/bin/omarchy-launch-editor" -cquit + +editor_argv=$(<"$editor_calls") +[[ $editor_argv == $'\n<-->\n<-cquit>' ]] || + fail "launch-editor separates a terminal editor path from editor options" "$editor_argv" +pass "launch-editor separates a terminal editor path from editor options" + +setsid_calls="$test_tmp/setsid-calls" +printf 'code\n' >"$fake_home/.local/state/omarchy/defaults/editor" +cat >"$mock_bin/code" <<'STUB' +#!/bin/bash + +exit 0 +STUB +chmod +x "$mock_bin/code" + +HOME="$fake_home" PATH="$mock_bin:$ROOT/bin:$PATH" OMARCHY_TEST_SETSID_CALLS="$setsid_calls" \ + "$ROOT/bin/omarchy-launch-editor" -cquit + +setsid_argv=$(<"$setsid_calls") +[[ $setsid_argv == $'\n<-->\n\n<-->\n<-cquit>' ]] || + fail "launch-editor separates a graphical editor path from editor options" "$setsid_argv" +pass "launch-editor separates a graphical editor path from editor options" + +hook_calls="$test_tmp/hook-calls" +hook_home="$test_tmp/hook-home" +printf '#!/bin/bash\n' >"$test_tmp/--help" +cat >"$mock_bin/basename" <<'STUB' +#!/bin/bash + +: "${OMARCHY_TEST_HOOK_CALLS:?}" +{ + printf 'basename' + printf ' <%s>' "$@" + printf '\n' +} >>"$OMARCHY_TEST_HOOK_CALLS" +printf 'literal-hook\n' +STUB +cat >"$mock_bin/cp" <<'STUB' +#!/bin/bash + +: "${OMARCHY_TEST_HOOK_CALLS:?}" +{ + printf 'cp' + printf ' <%s>' "$@" + printf '\n' +} >>"$OMARCHY_TEST_HOOK_CALLS" +STUB +for command in mkdir chmod; do + printf '#!/bin/bash\nexit 0\n' >"$mock_bin/$command" +done +chmod +x "$mock_bin/basename" "$mock_bin/cp" "$mock_bin/mkdir" "$mock_bin/chmod" + +: >"$hook_calls" +( + cd -- "$test_tmp" + HOME="$hook_home" PATH="$mock_bin:$PATH" OMARCHY_TEST_HOOK_CALLS="$hook_calls" \ + "$ROOT/bin/omarchy-hook-install" post-update --help >/dev/null +) + +hook_argv=$(<"$hook_calls") +expected_hook_argv=$'basename <--> <--help>\ncp <--> <--help> <'"$hook_home"'/.config/omarchy/hooks/post-update.d/literal-hook>' +[[ $hook_argv == $expected_hook_argv ]] || + fail "hook-install treats its source file as an operand" "$hook_argv" +pass "hook-install treats its source file as an operand" diff --git a/test/shell.d/compositor-guard-test.sh b/test/shell.d/compositor-guard-test.sh index 5ea10358f6ef..e50d2b176222 100644 --- a/test/shell.d/compositor-guard-test.sh +++ b/test/shell.d/compositor-guard-test.sh @@ -62,7 +62,7 @@ run_guard() { ' bash "$SHELL_TEST_DIR" 2>&1 || printf 'guard exited %s\n' "$?" } -skipped="ok - no Wayland compositor; skipping sample runtime test" +skipped="ok - no Wayland compositor; skipping sample runtime test # SKIP" output=$(run_guard -u WAYLAND_DISPLAY XDG_RUNTIME_DIR="$runtime_dir") [[ $output == "$skipped" ]] || fail "guard skips without a display" "$output" @@ -76,7 +76,7 @@ pass "guard skips when the socket is unreachable" # Everything below needs a socket to stand in for a live or abandoned compositor. if (( ! socket_bound )); then - pass "cannot bind a Unix socket here; skipping the cases that need one" + skip "cannot bind a Unix socket here; skipping the cases that need one" exit 0 fi diff --git a/test/shell.d/config-test.sh b/test/shell.d/config-test.sh index 355ca26b9e02..12ffd85074da 100755 --- a/test/shell.d/config-test.sh +++ b/test/shell.d/config-test.sh @@ -33,6 +33,15 @@ jq -e ' ' "$ROOT/config/omarchy/shell.json" >/dev/null pass "default center anchor exists in center layout" +jq -e ' + def ids: map(.id // .); + (.bar.layout.center | ids) as $ids | + ($ids | index("omarchy.elsewhen")) as $elsewhen | + ($ids | index("omarchy.clock")) as $clock | + $elsewhen != null and $clock == $elsewhen + 1 +' "$ROOT/config/omarchy/shell.json" >/dev/null +pass "default center layout puts elsewhen immediately before the clock" + jq -e ' any(.bar.layout.center[]; (.id // .) == "omarchy.clock" and (.formatAlt // "") == "d MMMM \u0027W\u0027ww yyyy") ' "$ROOT/config/omarchy/shell.json" >/dev/null diff --git a/test/shell.d/copy-url-shortcut-migration-test.sh b/test/shell.d/copy-url-shortcut-migration-test.sh deleted file mode 100644 index 934a57eeb020..000000000000 --- a/test/shell.d/copy-url-shortcut-migration-test.sh +++ /dev/null @@ -1,238 +0,0 @@ -#!/bin/bash - -set -euo pipefail - -source "$(dirname "${BASH_SOURCE[0]}")/base-test.sh" - -require_command jq -require_command python3 - -migration="$ROOT/migrations/1786643346.sh" -test_dir=$(mktemp -d) -trap 'rm -rf "$test_dir"' EXIT - -home="$test_dir/home" -profile_root="$home/.config/chromium" -preferences="$profile_root/Default/Preferences" -mkdir -p "$(dirname "$preferences")" - -# Any id Chromium once derived from the extension's keyless load path; the -# repair keys off the registered command name, not the id. -ghost_id="ikkebdkaanlebnifjnbeiaklodhbjcci" -pinned_id="bgpiichlckmfanooecilcjemknkcpngb" - -write_stale_preferences() { - jq -n --arg ghost "$ghost_id" --arg pinned "$pinned_id" '{extensions: {commands: {"linux:Alt+Shift+L": {command_name: "copy-url", extension: $ghost, global: false}}, settings: {($ghost): {commands: {"copy-url": {suggested_key: "Alt+Shift+L", was_assigned: true}}}, ($pinned): {commands: {"copy-url": {suggested_key: "Alt+Shift+L"}}}}}}' >"$preferences" -} - -stub_bin="$test_dir/bin" -mkdir -p "$stub_bin" - -cat >"$stub_bin/python3" <<'STUB' -#!/bin/bash -exit 127 -STUB -chmod +x "$stub_bin/python3" - -# Test stubs must delegate to the system interpreter, not a user shim that can -# route python3 back through the stubs and recurse. -REAL_PYTHON=$(PATH="$stub_bin:$PATH" command -p -v python3) -[[ $REAL_PYTHON != "$stub_bin/python3" ]] || fail "real Python resolution bypasses user shims" -export REAL_PYTHON -rm -f "$stub_bin/python3" - -run_migration() { - HOME="$home" PATH="$stub_bin:$PATH" bash -euo pipefail "$migration" >/dev/null 2>&1 -} - -# A running Chromium-family browser marks its profile root with a SingletonLock -# symlink to -, a target that never exists on disk. That lock — -# not the mere presence of a browser process — is what the migration waits on. -open_browser() { - mkdir -p "$profile_root" - ln -sfn "test-host-1234" "$profile_root/SingletonLock" -} -close_browser() { - rm -f "$profile_root/SingletonLock" -} - -# The affected profile being open prompts for the windows to be closed; -# declining (or having no terminal to ask in) defers the repair so a -# rewrite-on-exit cannot revert it. -printf '#!/bin/bash\nexit 1\n' >"$stub_bin/gum" -chmod +x "$stub_bin/gum" -write_stale_preferences -open_browser - -before_hash=$(sha256sum "$preferences" | cut -d' ' -f1) - -run_migration && fail "migration defers while the affected profile is open" -[[ $(sha256sum "$preferences" | cut -d' ' -f1) == "$before_hash" ]] || - fail "migration leaves preferences alone while the affected profile is open" -pass "migration defers the repair while the affected profile is open" - -# gum paints its prompt on stderr, so that stream has to stay attached: -# suppressing it leaves gum reading keys behind an unpainted screen, which -# reads as a hung update. -cat >"$stub_bin/gum" <<'STUB' -#!/bin/bash -echo "gum-prompt-painted" >&2 -exit 1 -STUB -prompt_stderr="$test_dir/prompt-stderr" -HOME="$home" PATH="$stub_bin:$PATH" bash -euo pipefail "$migration" >/dev/null 2>"$prompt_stderr" && - fail "migration defers when the browser prompt is declined" -grep -q "gum-prompt-painted" "$prompt_stderr" || fail "migration keeps the browser prompt visible" -pass "migration keeps the browser prompt visible" - -# A browser holding a different profile root cannot revert this repair, so it -# must not hold the update: the repair goes through without ever reaching the -# prompt, which the still-declining gum stub would otherwise fail. -close_browser -mkdir -p "$home/.config/google-chrome" -ln -sfn "test-host-1234" "$home/.config/google-chrome/SingletonLock" -write_stale_preferences -run_migration || fail "migration repairs while a different profile root is open" -jq -e --arg pinned "$pinned_id" '.extensions.commands["linux:Alt+Shift+L"].extension == $pinned' "$preferences" >/dev/null || - fail "migration repairs the shortcut while a different profile root is open" -pass "migration ignores a browser on a different profile root" -rm -f "$home/.config/google-chrome/SingletonLock" "$preferences.omarchy-copy-url-repair.bak" - -# Closing the affected profile and confirming the prompt lets the repair -# proceed. -write_stale_preferences -open_browser -cat >"$stub_bin/gum" <<'STUB' -#!/bin/bash -"$CLOSE_BROWSER" -touch "${GUM_CALLED:?}" -exit 0 -STUB -cat >"$stub_bin/close-browser" <<'STUB' -#!/bin/bash -rm -f "$HOME/.config/chromium/SingletonLock" -STUB -chmod +x "$stub_bin/gum" "$stub_bin/close-browser" -GUM_CALLED="$test_dir/gum-called" CLOSE_BROWSER="$stub_bin/close-browser" \ - HOME="$home" PATH="$stub_bin:$PATH" bash -euo pipefail "$migration" >/dev/null 2>&1 || - fail "migration proceeds once the profile is closed and the prompt confirmed" -[[ -e $test_dir/gum-called ]] || fail "migration asks before repairing under a running browser" -jq -e --arg pinned "$pinned_id" '.extensions.commands["linux:Alt+Shift+L"].extension == $pinned' "$preferences" >/dev/null || - fail "migration repairs after the browser prompt is confirmed" -pass "migration asks to close the browser and repairs on confirmation" -rm -f "$preferences.omarchy-copy-url-repair.bak" - -# With the affected profile closed the ghost registration moves to the pinned id. -printf '#!/bin/bash\nexit 1\n' >"$stub_bin/gum" -close_browser -write_stale_preferences -run_migration || fail "migration repairs the shortcut when no browser is running" - -jq -e --arg ghost "$ghost_id" --arg pinned "$pinned_id" ' - .extensions.commands["linux:Alt+Shift+L"].extension == $pinned and - (.extensions.settings | has($ghost) | not) and - .extensions.settings[$pinned].commands["copy-url"].was_assigned == true -' "$preferences" >/dev/null || fail "migration rebinds the Copy URL shortcut to the pinned extension id" -[[ -f $preferences.omarchy-copy-url-repair.bak ]] || - fail "migration backs up preferences before the repair" -pass "migration rebinds the Copy URL shortcut to the pinned extension id" - -# A repaired profile has no ghost registration left, so nothing is pending — -# even while that same profile is open. -rm "$preferences.omarchy-copy-url-repair.bak" -repaired_hash=$(sha256sum "$preferences" | cut -d' ' -f1) -open_browser -run_migration || fail "migration reruns cleanly after the repair" -[[ $(sha256sum "$preferences" | cut -d' ' -f1) == "$repaired_hash" && ! -e $preferences.omarchy-copy-url-repair.bak ]] || - fail "migration is idempotent after the repair" -pass "migration is idempotent after the repair" -close_browser - -# A remapped shortcut keeps the user's chosen key while moving to the pinned id. -jq -n --arg ghost "$ghost_id" '{extensions: {commands: {"linux:Ctrl+Alt+P": {command_name: "copy-url", extension: $ghost, global: false}}, settings: {}}}' >"$preferences" -run_migration || fail "migration repairs remapped shortcuts" -jq -e --arg pinned "$pinned_id" '.extensions.commands["linux:Ctrl+Alt+P"].extension == $pinned' "$preferences" >/dev/null || - fail "migration keeps the remapped key while rebinding to the pinned id" -pass "migration keeps remapped shortcut keys" - -# When the pinned extension already holds a copy-url binding (the user fixed -# it by hand), the ghost is dropped rather than doubled into a second binding. -jq -n --arg ghost "$ghost_id" --arg pinned "$pinned_id" '{extensions: {commands: {"linux:Ctrl+Alt+P": {command_name: "copy-url", extension: $pinned, global: false}, "linux:Alt+Shift+L": {command_name: "copy-url", extension: $ghost, global: false}}, settings: {}}}' >"$preferences" -run_migration || fail "migration cleans ghosts alongside a manual repair" -jq -e --arg pinned "$pinned_id" ' - (.extensions.commands | has("linux:Alt+Shift+L") | not) and - .extensions.commands["linux:Ctrl+Alt+P"].extension == $pinned -' "$preferences" >/dev/null || fail "migration drops the ghost instead of double-binding the pinned extension" -pass "migration never double-binds the pinned extension" - -# A browser starting mid-repair may write stale Preferences back on exit, so -# the migration must stay pending for a later browser-free run to verify. A -# stub hands the repair call through and opens the profile right after it. -write_stale_preferences -close_browser -rm -f "$preferences.omarchy-copy-url-repair.bak" -cat >"$stub_bin/python3" <<'STUB' -#!/bin/bash -# Called as `python3 -c