diff --git a/Makefile b/Makefile index 02f07514..772fe78a 100644 --- a/Makefile +++ b/Makefile @@ -5,16 +5,19 @@ # make WVKBD= WTYPE= # make install DESTDIR= OMARCHY= DBUS_NEXT= # -# The only compiles are the on-screen keyboard (wvkbd with this repository's -# patches) and the startup cursor helper (wtype); desktop/install-tree puts -# every file in place. +# Build the on-screen keyboard, startup cursor helper and shell IPC client. +# desktop/install-tree puts every file in place. BUILD ?= build CC ?= cc CFLAGS ?= -O2 PKG_CONFIG ?= pkg-config -all: $(BUILD)/wvkbd-mobintl $(BUILD)/wtype +all: $(BUILD)/wvkbd-mobintl $(BUILD)/wtype $(BUILD)/omarchy-shell-ipc + +$(BUILD)/omarchy-shell-ipc: desktop/ipc/client.c + mkdir -p $(BUILD) + $(CC) $(CPPFLAGS) $(CFLAGS) $< $(LDFLAGS) -o $@ $(BUILD)/wvkbd-mobintl: @test -d "$(WVKBD)" || { echo 'Set WVKBD to the wvkbd v0.20 source' >&2; exit 1; } diff --git a/desktop/armv7/README.md b/desktop/armv7/README.md index 5adb02fb..af662d51 100644 --- a/desktop/armv7/README.md +++ b/desktop/armv7/README.md @@ -3,12 +3,14 @@ `python -m release.package --output DIR --architecture armv7h` makes the ARMv7 `omarchy-a` package of the checkout (the keyboard and cursor helper compiled for ARMv7) in the ARMv7 builder. The image installs it, and `wlroots0.20`, `labwc`, -`omafox`, `omactivity`, `folio-touch` (Files) and `omacalc` from the ARMv7 channel of the +`omafox`, `omactivity`, `folio-touch` (Files), `omacalc` and `mesa` from the ARMv7 channel of the [Orchard package repository](https://github.com/OrchardLinux/packages) (`repo-armv7h`), listed before Arch Linux ARM's repositories. Upstream Omarchy publishes no ARMv7 packages, so an ARMv7 image has no `[omarchy]` repository and Omacalc is the Orchard repository's build of upstream's pinned source. -Mesa is Arch Linux ARM's there. +Mesa is the Orchard repository's too: OrchardLinux's fork with the SGX543's +OpenGL ES 2 driver (the A5 and A6) and software OpenGL, in the place of Arch +Linux ARM's. A provisioned native ARMv7 Arch Linux ARM environment can run the recipes with `ORCHARD_BUILD_NATIVE=1` and `ORCHARD_BUILD_ENV_ID` set to its reproducible image diff --git a/desktop/configuration/auto-brightness b/desktop/configuration/auto-brightness index 6571893c..484c6516 100755 --- a/desktop/configuration/auto-brightness +++ b/desktop/configuration/auto-brightness @@ -29,7 +29,7 @@ import time IIO_ROOT = "/sys/bus/iio/devices" BACKLIGHT_ROOT = "/sys/class/backlight" -TICK = 0.1 +STATE_INTERVAL = 2.0 # powerd's als-state is request/reply, without change notifications RAMP_TICK = 1.0 / 30 # loop period while a ramp runs: small, frequent steps look like a fade RAMP_GAMMA = 2.2 # ramp in perceived brightness (raw ~ perceived ** gamma), not raw PWM RAMP_MIN_SECS, RAMP_MAX_SECS = 0.3, 3.0 @@ -326,15 +326,15 @@ class IioSource: def __init__(self, root, hz): self.root = root - self.interval = 1.0 / max(hz, 0.5) + self.interval = max(STATE_INTERVAL, 1.0 / hz) if hz > 0 else STATE_INTERVAL self.due = 0.0 self.warned = False def poll(self, timeout): - wait = max(0.0, min(timeout, self.due - time.monotonic())) - time.sleep(wait) - if time.monotonic() < self.due: - return [] + remaining = self.due - time.monotonic() + if remaining > 0: + time.sleep(min(timeout, remaining)) + return [] # recheck the panel before touching the sensor self.due = time.monotonic() + self.interval dev = find_iio_light(self.root) lux = read_iio_lux(dev) if dev else None @@ -423,6 +423,7 @@ class ProxySource: self.master = None self.buf = b"" self.retry_at = 0.0 + self.cmd = None @staticmethod def command(): @@ -439,13 +440,19 @@ class ProxySource: return cmd def start(self): - cmd = self.command() + if self.cmd is None: + self.cmd = self.command() master, slave = pty.openpty() - self.proc = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=slave, stderr=slave, close_fds=True) - os.close(slave) + try: + self.proc = subprocess.Popen(self.cmd, stdin=subprocess.DEVNULL, stdout=slave, stderr=slave, close_fds=True) + except OSError: + os.close(master) + raise + finally: + os.close(slave) self.master = master self.buf = b"" - log("started", " ".join(cmd)) + log("started", " ".join(self.cmd)) def stop(self): if self.proc: @@ -454,6 +461,7 @@ class ProxySource: self.proc.wait(timeout=3) except subprocess.TimeoutExpired: self.proc.kill() + self.proc.wait() if self.master is not None: os.close(self.master) self.proc = self.master = None @@ -603,6 +611,7 @@ class Daemon: self.moves = 0 self.stop = False self.shown = None + self.last_status = None # -- helpers def tolerance(self): @@ -623,8 +632,11 @@ class Daemon: if not is_enabled(conf): self.pause("off") self.write_status(now, enabled=False) - return + return False + raw = self.backlight.read() hold = [] if self.dry else holds() + if raw is None or raw <= 0: + hold = hold or ["backlight"] if hold != self.hold: if hold: log("holding for", ", ".join(hold)) @@ -634,10 +646,7 @@ class Daemon: if hold or now < self.settle_until: self.pause("hold") self.write_status(now, enabled=True) - return - raw = self.backlight.read() - if raw is None: - return + return False # A change we didn't make: a brightness key, the menu. if self.last_written is not None and abs(raw - self.last_written) > self.tolerance(): self.override_until = now + conf["override_secs"] @@ -646,7 +655,7 @@ class Daemon: self.pause("manual change") if now < self.override_until: self.write_status(now, enabled=True, override=self.override_until - now) - return + return True if not self.active: self.active = True log("auto-brightness on") @@ -668,6 +677,7 @@ class Daemon: if self.goal_raw is not None: self.step(raw, now) self.write_status(now, enabled=True) + return True # Perceived brightness in [0, 1]: equal steps here look equal on the panel. def perceived(self, raw): @@ -728,13 +738,15 @@ class Daemon: "hold": self.hold, "override_secs_left": round(override, 1), "moves": self.moves, - "time": time.time(), } + if data == self.last_status: + return tmp = status_path() + ".tmp" try: with open(tmp, "w") as f: - json.dump(data, f) + json.dump(dict(data, time=time.time()), f) os.replace(tmp, status_path()) + self.last_status = data except OSError: pass @@ -749,13 +761,27 @@ class Daemon: os.kill(int(compositor), 0) except (OSError, ValueError): break - if not is_enabled(self.conf): - self.tick(time.monotonic()) - time.sleep(1) # off means no 10Hz backlight/status work + now = time.monotonic() + wait = STATE_INTERVAL if end is None else min(STATE_INTERVAL, max(0, end - now)) + if not self.tick(now): + if isinstance(self.source, ProxySource): + self.source.stop() # dropping monitor-sensor releases its ClaimLight + self.latest = None + if now < self.settle_until: + wait = min(wait, self.settle_until - now) + time.sleep(wait) continue - for lux in self.source.poll(RAMP_TICK if self.ramping() else TICK): + # Reuse the last signalled lux while the median and low-pass filter + # settle. Stable light needs no intermediate policy ticks. + if self.latest is not None and now >= self.override_until: + target = max(0.0, self.latest * self.conf["lux_scale"]) + if (self.smoother.level is None or self.smoother.readings != [target] * self.smoother.window + or abs(math.log1p(target) - self.smoother.level) > 0.001): + wait = min(wait, max(0.0, self.next_sample - now)) + if self.ramping(): + wait = min(wait, RAMP_TICK) + for lux in self.source.poll(wait): self.latest = lux - self.tick(time.monotonic()) self.source.close() try: os.unlink(status_path()) @@ -843,7 +869,7 @@ def main(): os.kill(int(compositor), 0) except (OSError, ValueError): return 0 - time.sleep(1) + time.sleep(STATE_INTERVAL) name = find_backlight(conf["backlight"]) source = make_source(args, conf) daemon = Daemon(conf, source, Backlight(name), args.dry_run, args.debug) diff --git a/desktop/configuration/login-session b/desktop/configuration/login-session index 5d5b98cc..749f143e 100644 --- a/desktop/configuration/login-session +++ b/desktop/configuration/login-session @@ -34,25 +34,42 @@ export LIBGL_ALWAYS_SOFTWARE=1 LIBSEAT_BACKEND=seatd MOZ_ENABLE_WAYLAND=1 # which (journalctl -t omarchy-gpu-probe). On the GPU desktop the shell and # its apps draw with Qt Quick on the GPU; on the software desktop with Qt's # software renderer. -gpu= +# A board with the A5's or A6's PowerVR SGX543 (kernel driver apple-sgx) has one +# card that is both its display controller and its GPU, and Mesa's sgx driver +# draws OpenGL ES 2 on it: there Labwc draws on wlroots' GLES2 renderer on that +# card and applications get the GPU's OpenGL ES, once gpu-probe has drawn a frame +# that way in this boot. The shell keeps Qt's software renderer: the SGX has +# OpenGL ES 2 only, and Qt Quick on it is untested. The lite shell avoids +# offscreen passes for masks and shadows on this tile-based GPU. +gpu= gpu_driver= for node in /sys/class/drm/renderD*; do - if [[ $(basename "$(readlink -f "$node/device/driver")") == powervr ]]; then gpu=$node; fi + driver=$(basename "$(readlink -f "$node/device/driver")") + if [[ $driver == powervr || $driver == apple-sgx ]]; then gpu=$node gpu_driver=$driver; fi done if [[ -n $gpu ]]; then gpu_probe=/usr/lib/omarchy-a/gpu-probe gpu_log=$XDG_RUNTIME_DIR/omarchy-gpu-probe.log - # The GPU has no display outputs: Labwc must open the display's card only. + # The PowerVR GPU has no display outputs: Labwc must open the display's card + # only. The SGX's card is the display. display= for card in /sys/class/drm/card*; do - if [[ ${card##*/} =~ ^card[0-9]+$ && $(readlink -f "$card/device") != "$(readlink -f "$gpu/device")" ]]; then + [[ ${card##*/} =~ ^card[0-9]+$ ]] || continue + if [[ $gpu_driver == apple-sgx ]]; then + if [[ $(readlink -f "$card/device") == "$(readlink -f "$gpu/device")" ]]; then display=/dev/dri/${card##*/}; fi + elif [[ $(readlink -f "$card/device") != "$(readlink -f "$gpu/device")" ]]; then display=/dev/dri/${card##*/} fi done - # GTK draws with Vulkan: GTK 4 takes its Vulkan renderer by itself only when the driver offers a dma-buf - # modifier other than LINEAR. Where it offers LINEAR alone (the A7), GTK took its GL renderer on Zink, which - # drew text twice and WebKit's pages not at all (Web showed an empty window); Vulkan draws them right. - gpu_desktop=(WLR_RENDERER=gles2 "WLR_RENDER_DRM_DEVICE=/dev/dri/${gpu##*/}" - MESA_LOADER_DRIVER_OVERRIDE=zink PVR_I_WANT_A_BROKEN_VULKAN_DRIVER=1 GSK_RENDERER=vulkan) + if [[ $gpu_driver == apple-sgx ]]; then + # The display's own card renders: wlroots finds the GPU through it. + gpu_desktop=(WLR_RENDERER=gles2) + else + # GTK draws with Vulkan: GTK 4 takes its Vulkan renderer by itself only when the driver offers a dma-buf + # modifier other than LINEAR. Where it offers LINEAR alone (the A7), GTK took its GL renderer on Zink, which + # drew text twice and WebKit's pages not at all (Web showed an empty window); Vulkan draws them right. + gpu_desktop=(WLR_RENDERER=gles2 "WLR_RENDER_DRM_DEVICE=/dev/dri/${gpu##*/}" + MESA_LOADER_DRIVER_OVERRIDE=zink PVR_I_WANT_A_BROKEN_VULKAN_DRIVER=1 GSK_RENDERER=vulkan) + fi if [[ -n $display ]]; then gpu_desktop+=("WLR_DRM_DEVICES=$display") # simpledrm cannot scan out a buffer the GPU drew (it takes no dma-buf), so @@ -64,7 +81,9 @@ if [[ -n $gpu ]]; then gpu_desktop+=(WLR_SCENE_DISABLE_DIRECT_SCANOUT=1) fi fi - if [[ ! -e /usr/share/vulkan/icd.d/powervr_mesa_icd.json ]]; then + if [[ $gpu_driver == apple-sgx && ! -e /usr/lib/dri/apple_sgx_dri.so ]]; then + gpu_verdict='software desktop: this image has no OpenGL ES driver for the GPU' + elif [[ $gpu_driver == powervr && ! -e /usr/share/vulkan/icd.d/powervr_mesa_icd.json ]]; then gpu_verdict='software desktop: this image has no Vulkan driver for the GPU' elif [[ -z $display || ! -x $gpu_probe ]]; then gpu_verdict='software desktop: no display card or no gpu-probe to test the GPU with' @@ -77,6 +96,7 @@ if [[ -n $gpu ]]; then gpu_key= if [[ -n $gpu_cache ]]; then gpu_icd_sig=$(stat -Lc '%Y:%s' /usr/share/vulkan/icd.d/powervr_mesa_icd.json 2>/dev/null || echo icd) + if [[ $gpu_driver == apple-sgx ]]; then gpu_icd_sig=$(stat -Lc '%Y:%s' /usr/lib/libgbm.so.1 2>/dev/null || echo gbm); fi gpu_probe_sig=$(stat -Lc '%Y:%s' "$gpu_probe" 2>/dev/null || echo probe) gpu_key="$(uname -r)|${display_driver:-none}|$gpu_icd_sig|$gpu_probe_sig" fi @@ -86,6 +106,7 @@ if [[ -n $gpu ]]; then export "${gpu_desktop[@]}" MESA_DISK_CACHE_SINGLE_FILE=1 unset LIBGL_ALWAYS_SOFTWARE QT_QUICK_BACKEND export QSG_NO_DEPTH_BUFFER=1 QSG_NO_STENCIL_BUFFER=1 + if [[ $gpu_driver == apple-sgx ]]; then export QT_QUICK_BACKEND=software OMARCHY_SHELL_LITE=1; fi else # The probe runs with the environment the desktop would get. The login # waits for it 10 s at most and does not depend on it ending: a probe @@ -109,6 +130,7 @@ if [[ -n $gpu ]]; then # keeps a full-size depth/stencil buffer in memory that the UI never # reads (on the iPod touch 6 that is about 50 MB in the shell alone). export QSG_NO_DEPTH_BUFFER=1 QSG_NO_STENCIL_BUFFER=1 + if [[ $gpu_driver == apple-sgx ]]; then export QT_QUICK_BACKEND=software OMARCHY_SHELL_LITE=1; fi if [[ -n $gpu_cache ]]; then mkdir -p "$(dirname "$gpu_cache")" 2>/dev/null || true printf '%s\n%s\n' "$gpu_key" "$gpu_detail" >"$gpu_cache.tmp" 2>/dev/null && diff --git a/desktop/configuration/rotate-output b/desktop/configuration/rotate-output index 284ca368..747bf370 100644 --- a/desktop/configuration/rotate-output +++ b/desktop/configuration/rotate-output @@ -206,6 +206,22 @@ def apply(value, speaker_transform=None): return True +def watch_unlock(lock): + # Watch the existing inode, so removing the lock wakes a settled pose + # even when monitor-sensor has nothing more to say. + import ctypes + libc = ctypes.CDLL(None) + if not hasattr(libc, 'inotify_init1'): + return None + fd = libc.inotify_init1(os.O_CLOEXEC | os.O_NONBLOCK) + if fd < 0: + return None + if libc.inotify_add_watch(fd, os.fsencode(lock), 0x400 | 0x800) < 0: # DELETE_SELF | MOVE_SELF + os.close(fd) + return None + return fd + + def main(): lock = Path(os.environ.get('XDG_CONFIG_HOME', str(Path.home() / '.config'))) / 'omarchy/rotation-lock' state = Orientation(float(os.environ.get('ROTATE_SETTLE', '.4')), @@ -237,23 +253,63 @@ def main(): process.stdout.close() monitor = start_monitor() restart_at = None + retry_apply_at = 0.0 + lock_fd = parent_fd = None running = True def stop(*_): - nonlocal running - running = False + raise SystemExit(0) # interrupt even an indefinite selector wait signal.signal(signal.SIGTERM, stop) signal.signal(signal.SIGINT, stop) buffered = b'' eof = False try: + if parent and hasattr(os, 'pidfd_open'): + try: + parent_fd = os.pidfd_open(parent) + except ProcessLookupError: + return + except OSError: + pass # older kernels: fall back to the liveness check + else: + selector.register(parent_fd, selectors.EVENT_READ, 'parent') while running: - if parent: + now = time.monotonic() + deadlines = [] + if parent and parent_fd is None: try: os.kill(parent, 0) except ProcessLookupError: break - wait_s = 0.1 if (state.waiting() or eof) else 1.0 - for key, _ in selector.select(wait_s): + deadlines.append(now + 2) + if not sensors and not saw_proxy and discovery_timeout > 0: + deadlines.append(started + discovery_timeout) + if restart_at is not None: + deadlines.append(restart_at) + if eof and not parent: + deadlines.append(state.since + state.settle + state.cooldown + 5) + if state.waiting(): + if lock.exists(): + if lock_fd is None: + lock_fd = watch_unlock(lock) + if lock_fd is not None: + selector.register(lock_fd, selectors.EVENT_READ, 'unlock') + if lock_fd is None: + deadlines.append(now + 2 if lock.exists() else now) + elif now < retry_apply_at: + deadlines.append(retry_apply_at) + elif motion: + deadlines.append(now + 0.1) # gravity only while a turn is settling + else: + deadlines.append(max(state.since + state.settle, state.last_apply + state.cooldown)) + wait = max(0.0, min(deadlines) - now) if deadlines else None + for key, _ in selector.select(wait): + if key.data == 'parent': + return + if key.data == 'unlock': + selector.unregister(lock_fd) + os.close(lock_fd) + lock_fd = None + continue data = os.read(key.fd, 8192) if not data: eof = True @@ -273,6 +329,8 @@ def main(): if value is not None: saw_proxy = True trace(f'sensor orientation={value}') + if value != state.pending: + retry_apply_at = 0.0 state.observe(value, time.monotonic()) now = time.monotonic() if not running: @@ -280,30 +338,32 @@ def main(): if not sensors and not saw_proxy and discovery_timeout > 0 and now - started >= discovery_timeout: print('rotation: no accelerometer or iio-sensor-proxy after discovery window; exiting', flush=True) break + locked = lock.exists() if motion: - if state.waiting(): + if state.waiting() and not locked and now >= retry_apply_at: motion.sample(now) else: motion.forget() - value = state.ready(now, lock.exists(), bool(motion and motion.turning()), + value = state.ready(now, locked, bool(motion and motion.turning()), motion.trusted_facing() if motion else None) - if value is not None: + if value is not None and now >= retry_apply_at: trace(f'stable orientation={value} waited_ms={(now - state.since) * 1000:.0f}') try: if apply(value, speaker_transform): state.committed(value, now) if motion: motion.judged(value) + else: + retry_apply_at = now + 60 # no eligible output except (OSError, subprocess.SubprocessError) as error: print(f'rotation failed: {error}', flush=True) - state.last_apply = now # bounded retry; never mark failure applied + retry_apply_at = now + 2 if eof: # No accelerated apply on EOF: wait out any pending stability window. - if not (lock.exists() or state.pending is None or state.pending == state.applied - or now - state.since > state.settle + state.cooldown + 5): - continue if not parent: - break + if locked or not state.waiting() or now >= state.since + state.settle + state.cooldown + 5: + break + continue # Inside a session the sensor reader may end (iio-sensor-proxy # not up yet at login, or restarted). Rotation must not stay # dead until the next login: start it again, at most every 2 s. @@ -314,10 +374,11 @@ def main(): stop_monitor(monitor) monitor = start_monitor() buffered, eof, restart_at = b'', False, None - else: - time.sleep(.1) finally: selector.close() + for fd in (lock_fd, parent_fd): + if fd is not None: + os.close(fd) stop_monitor(monitor) diff --git a/desktop/install-tree b/desktop/install-tree index ed917a7f..69619bcc 100755 --- a/desktop/install-tree +++ b/desktop/install-tree @@ -78,6 +78,7 @@ done # The keyboard and the startup cursor helper. put "$build/wvkbd-mobintl" "$omarchy/trials/wvkbd-mobintl-v0.20-font18-special15-state" 755 +put "$build/omarchy-shell-ipc" "$root/usr/libexec/omarchy-shell-ipc" 755 put "$build/wtype" "$root/usr/libexec/omarchy-wtype" 755 put "$build/wtype.LICENSE" "$root/usr/share/licenses/omarchy-wtype/LICENSE" diff --git a/desktop/ipc/client.c b/desktop/ipc/client.c new file mode 100644 index 00000000..d58561c5 --- /dev/null +++ b/desktop/ipc/client.c @@ -0,0 +1,57 @@ +/* One request on the shell's display/config-specific AF_UNIX socket. + * Exit 2 only if it is safe for the wrapper to try qs ipc. The wrapper's + * timeout covers connect, send and receive together. */ +#include +#include +#include +#include +#include +#include +#include +#include + +static int write_all(int fd, const char *data, size_t size) { + while (size) { + ssize_t n = write(fd, data, size); + if (n < 0 && errno == EINTR) continue; + if (n <= 0) return -1; + data += n; + size -= (size_t)n; + } + return 0; +} + +int main(int argc, char **argv) { + struct sockaddr_un addr = {.sun_family = AF_UNIX}; + if (argc < 4 || strlen(argv[1]) >= sizeof addr.sun_path) return 2; + strcpy(addr.sun_path, argv[1]); + size_t size = 0; + for (int i = 2; i < argc; ++i) { + if (strpbrk(argv[i], "\036\037")) return 2; + size += strlen(argv[i]) + 1; + } + char *request = malloc(size); + if (!request) return 1; + char *field = request; + for (int i = 2; i < argc; ++i) { + size_t len = strlen(argv[i]); + memcpy(field, argv[i], len); + field += len; + *field++ = i + 1 == argc ? '\036' : '\037'; + } + + int fd = socket(AF_UNIX, SOCK_STREAM, 0); + if (fd < 0 || connect(fd, (struct sockaddr *)&addr, sizeof addr) < 0) return 2; + if (write_all(fd, request, size) < 0) return 1; + free(request); + + FILE *stream = fdopen(fd, "r"); + if (!stream) return 1; + char *reply = NULL; + size_t capacity = 0; + ssize_t n = getdelim(&reply, &capacity, '\036', stream); + if (n <= 0 || reply[n - 1] != '\036') return 1; + if (n == 5 && !memcmp(reply, "SKIP\036", 5)) return 2; + if (n < 4 || memcmp(reply, "OK\037", 3)) return 1; + return write_all(STDOUT_FILENO, reply + 3, (size_t)n - 4) < 0; +} diff --git a/desktop/shell/bin/omarchy-battery-status b/desktop/shell/bin/omarchy-battery-status index f94bcd77..2040dd98 100644 --- a/desktop/shell/bin/omarchy-battery-status +++ b/desktop/shell/bin/omarchy-battery-status @@ -7,43 +7,43 @@ set -euo pipefail [[ $# == 1 && $1 == --shell ]] || { echo 'Usage: omarchy-battery-status --shell' >&2; exit 2; } base=${OMARCHY_POWER_SUPPLY_PATH:-/sys/class/power_supply} battery='' -for candidate in "$base"/*; do - [[ -r $candidate/type && $(<"$candidate/type") == Battery ]] || continue - [[ ! -r $candidate/present || $(<"$candidate/present") == 1 ]] || continue - [[ -z $battery ]] || exit 0 # Ambiguous: show UPower alone. - battery=$candidate -done -[[ -n $battery && -r $battery/capacity ]] || exit 0 -read -r percentage < "$battery/capacity" -[[ $percentage =~ ^[0-9]+$ && $percentage -le 100 ]] || exit 0 -printf 'percentage\t%s%%\n' "$percentage" - external=unknown for candidate in "$base"/*; do - [[ -r $candidate/type && $(<"$candidate/type") != Battery && -r $candidate/online ]] || continue - if read -r online < "$candidate/online"; then + [[ -r $candidate/type ]] && read -r type < "$candidate/type" || continue + if [[ $type == Battery ]]; then + if [[ -r $candidate/present ]]; then + read -r present < "$candidate/present" && [[ $present == 1 ]] || continue + fi + [[ -z $battery ]] || exit 0 # Ambiguous: show UPower alone. + battery=$candidate + elif [[ $external != connected && -r $candidate/online ]] && read -r online < "$candidate/online"; then case "$online" in - 1) external=connected; break ;; + 1) external=connected ;; 0) external=disconnected ;; esac fi done +[[ -n $battery && -r $battery/capacity ]] || exit 0 +read -r percentage < "$battery/capacity" +[[ $percentage =~ ^[0-9]+$ && 10#$percentage -le 100 ]] || exit 0 +printf 'percentage\t%s%%\n' "$percentage" printf 'external_power\t%s\n' "$external" if [[ -r $battery/energy_full ]] && read -r full < "$battery/energy_full" && - [[ $full =~ ^[0-9]+$ && $full -gt 0 ]]; then - awk -v uwh="$full" 'BEGIN { printf "size\t%.1fWh\n", uwh / 1000000 }' + [[ $full =~ ^[0-9]+$ && 10#$full -gt 0 ]]; then + LC_NUMERIC=C printf 'size\t%.1fWh\n' "${full}e-6" fi if [[ -r $battery/cycle_count ]] && read -r cycles < "$battery/cycle_count"; then [[ ! $cycles =~ ^[0-9]+$ ]] || printf 'cycles\t%s\n' "$cycles" fi if [[ -r $battery/power_now ]]; then read -r microwatts < "$battery/power_now" - [[ ! $microwatts =~ ^-?[0-9]+$ ]] || awk -v u="$microwatts" 'BEGIN { if (u < 0) u = -u; printf "rate\t%.1fW\n", u / 1000000 }' + [[ ! $microwatts =~ ^-?[0-9]+$ ]] || LC_NUMERIC=C printf 'rate\t%.1fW\n' "${microwatts#-}e-6" elif [[ -r $battery/current_now && -r $battery/voltage_now ]]; then read -r microamps < "$battery/current_now" read -r microvolts < "$battery/voltage_now" if [[ $microamps =~ ^-?[0-9]+$ && $microvolts =~ ^[0-9]+$ ]]; then - awk -v i="$microamps" -v v="$microvolts" 'BEGIN { if (i < 0) i = -i; printf "rate\t%.1fW\n", i * v / 1000000000000 }' + picowatts=$((10#${microamps#-} * 10#$microvolts)) + LC_NUMERIC=C printf 'rate\t%.1fW\n' "${picowatts}e-12" fi fi diff --git a/desktop/shell/bin/omarchy-bottom-swipe b/desktop/shell/bin/omarchy-bottom-swipe index 3d4cbb06..7e2d143b 100755 --- a/desktop/shell/bin/omarchy-bottom-swipe +++ b/desktop/shell/bin/omarchy-bottom-swipe @@ -9,10 +9,10 @@ # still come here over one (an older labwc), it puts that one away. Over an # app it brings the keyboard up. runtime="${XDG_RUNTIME_DIR:-/run/user/$UID}" -if [[ -e $runtime/omarchy-notification-center-open ]]; then +if [[ -s $runtime/omarchy-notification-center-open ]]; then exec omarchy-shell omarchy.notificationcenter close fi -if [[ -e $runtime/omarchy-control-center-open ]]; then +if [[ -s $runtime/omarchy-control-center-open ]]; then exec omarchy-shell omarchy.controlcenter close fi exec omarchy-keyboard show diff --git a/desktop/shell/bin/omarchy-home-button b/desktop/shell/bin/omarchy-home-button index 311037e3..e417b8f8 100755 --- a/desktop/shell/bin/omarchy-home-button +++ b/desktop/shell/bin/omarchy-home-button @@ -8,47 +8,8 @@ # was half of Home + Power (a screenshot) never gets here, and no keyboard # state or compositor binding stands in between. runtime="${XDG_RUNTIME_DIR:-/run/user/$UID}" -stamp="$runtime/omarchy-home-press" -# When the press happened, in ms, from bash's own clock (no fork). -now=$(( ${EPOCHREALTIME/[.,]/} / 1000 )) - -# A locked session's Home is the lock screen's (waking is omarchy-powerd's). -[[ $(omarchy-shell lock status 2>/dev/null) == *'"secure":true'* ]] && exit 0 - -# The control center goes away at once. A single press then opens nothing -# else; a second one still opens the overview. -control_center= -if [[ -e $runtime/omarchy-control-center-open ]]; then - control_center=1 - omarchy-shell omarchy.controlcenter close >/dev/null 2>&1 & -fi -# The notification center likewise. -if [[ -e $runtime/omarchy-notification-center-open ]]; then - control_center=1 - omarchy-shell omarchy.notificationcenter close >/dev/null 2>&1 & -fi - -# In the overview Home goes back to the desktop (omarchy-overview-changed -# keeps the note). -if [[ -e $runtime/omarchy-overview-open ]]; then - rm -f "$stamp" - exec labwc --overview -fi - -# Two presses open the overview of all windows, and must not flash the -# launcher on the way. So one press waits a moment for a second: the launcher -# opens only once it is certain that the press stays alone. The stamp is -# this press's at once, so the first one, still waiting, will not open the -# launcher meanwhile. -last=$(cat "$stamp" 2>/dev/null) -echo "$now" >"$stamp" -if [[ $last =~ ^[0-9]+$ ]] && (( now - last < 300 )); then - rm -f "$stamp" - exec labwc --overview -fi -sleep 0.3 -# A second press has taken the stamp. -[[ $(cat "$stamp" 2>/dev/null) == "$now" ]] || exit 0 -rm -f "$stamp" -[[ -z $control_center ]] || exit 0 -exec omarchy-shell omarchy.dock apps +overview=0 +[[ -e $runtime/omarchy-overview-open ]] && overview=1 +# Reuse the packaged transport in this Bash process, including powerd's +# display recovery. Its native socket, timeout and fallback match the CLI. +source "${OMARCHY_PATH:?}/bin/omarchy-shell" shell home "$overview" "$(( ${EPOCHREALTIME/[.,]/} / 1000 ))" diff --git a/desktop/shell/bin/omarchy-keyboard b/desktop/shell/bin/omarchy-keyboard index 67ea0b1c..9c586068 100644 --- a/desktop/shell/bin/omarchy-keyboard +++ b/desktop/shell/bin/omarchy-keyboard @@ -308,6 +308,14 @@ def run(): def main(mode): + if mode in ("hold-while-open", "show-while-open"): + opening, closing = ("hold", "release") if mode.startswith("hold") else ("show", "hide") + main(opening) + try: + sys.stdin.buffer.read(1) + finally: + main(closing) + return if mode == "toggle": mode = "hide" if visible() else "show" if mode == "show": diff --git a/desktop/shell/bin/omarchy-shell b/desktop/shell/bin/omarchy-shell index 9d14a54a..29431c46 100755 --- a/desktop/shell/bin/omarchy-shell +++ b/desktop/shell/bin/omarchy-shell @@ -51,7 +51,10 @@ runtime_dir="${XDG_RUNTIME_DIR:-/run/user/$UID}" display_socket=${WAYLAND_DISPLAY:-} [[ $display_socket == /* ]] || display_socket="$runtime_dir/$display_socket" if [[ -z ${WAYLAND_DISPLAY:-} || ! -e $display_socket ]]; then - socket=$(ls -t "$runtime_dir"/wayland-[0-9]* 2>/dev/null | grep -v '\.lock$' | head -n1) + socket= + for candidate in "$runtime_dir"/wayland-[0-9]*; do + [[ -S $candidate && ( -z $socket || $candidate -nt $socket ) ]] && socket=$candidate + done [[ -n $socket ]] && export WAYLAND_DISPLAY=${socket##*/} fi @@ -68,10 +71,31 @@ fi # 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" +# The packaged config has a short, display-specific address. Older shells and +# alternate config paths use the hash. Both always select this config/display. +socket= +if [[ $OMARCHY_PATH == /usr/share/omarchy && ${WAYLAND_DISPLAY:-} =~ ^wayland-[0-9]+$ ]]; then + socket="$runtime_dir/omarchy-shell-display-$WAYLAND_DISPLAY.sock" +fi +if [[ ! -S $socket ]]; then + socket_id=$(printf '%s\n%s' "$OMARCHY_PATH/shell" "${WAYLAND_DISPLAY:-}" | md5sum) + socket="$runtime_dir/omarchy-shell-${socket_id:0:16}.sock" +fi + +trace_ipc() { + if [[ ${OMARCHY_SHELL_IPC_TRACE:-} == 1 ]]; then + printf 'omarchy-shell transport=%s target=%s method=%s socket=%s\n' "$1" "$2" "$3" "$socket" >&2 + fi +} request="$*" -if [[ -S $socket && $request != *$'\x1e'* && $request != *$'\x1f'* ]]; then +if [[ -S $socket && -x /usr/libexec/omarchy-shell-ipc ]]; then + output=$(timeout --kill-after=1s "${OMARCHY_SHELL_IPC_TIMEOUT:-2s}" /usr/libexec/omarchy-shell-ipc "$socket" "$@") + case $? in + 0) trace_ipc /usr/libexec/omarchy-shell-ipc "$1" "$2"; if (( !QUIET )) && [[ -n $output ]]; then printf '%s\n' "$output"; fi; exit 0 ;; + 2) ;; # No request dispatched; let qs provide its normal response. + *) fail "omarchy-shell is not responding" ;; + esac +elif [[ -S $socket && $request != *$'\x1e'* && $request != *$'\x1f'* ]] && command -v socat >/dev/null; then saved_ifs=$IFS IFS=$'\x1f' request="$*" @@ -84,6 +108,7 @@ if [[ -S $socket && $request != *$'\x1e'* && $request != *$'\x1f'* ]]; then # 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 + trace_ipc socat "$1" "$2" output=${reply#OK$'\x1f'} output=${output%$'\x1e'*} # Match qs ipc's path, whose $(...) drops trailing newlines. @@ -106,6 +131,7 @@ 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. +trace_ipc qs "$1" "$2" ipc_timeout=${OMARCHY_SHELL_IPC_TIMEOUT:-2s} output=$(timeout --kill-after=1s "$ipc_timeout" qs ipc -n -p "$OMARCHY_PATH/shell" call -- "$@" 2>/dev/null) ipc_status=$? diff --git a/desktop/shell/bin/omarchy-toggle-launcher-frosted b/desktop/shell/bin/omarchy-toggle-launcher-frosted index 1bf41ee8..3279be93 100755 --- a/desktop/shell/bin/omarchy-toggle-launcher-frosted +++ b/desktop/shell/bin/omarchy-toggle-launcher-frosted @@ -2,7 +2,7 @@ # omarchy:summary=Show the launcher on the frosted wallpaper, or on the theme's plain background # Opaque by default. Turned on, the launcher-frosted flag says so; the -# launcher reads it each time it opens. +# shell watches it for changes. set -euo pipefail [[ $# == 0 ]] || { echo 'Usage: omarchy-toggle-launcher-frosted' >&2; exit 2; } toggles=$HOME/.local/state/omarchy/toggles diff --git a/desktop/shell/shell/Commons/AfterStartup.qml b/desktop/shell/shell/Commons/AfterStartup.qml new file mode 100644 index 00000000..c411ba22 --- /dev/null +++ b/desktop/shell/shell/Commons/AfterStartup.qml @@ -0,0 +1,7 @@ +import QtQuick + +// A one-shot task. Components opened later run it on their next event turn. +Timer { + interval: 0 + running: Startup.ready +} diff --git a/desktop/shell/shell/Commons/BatteryStatus.qml b/desktop/shell/shell/Commons/BatteryStatus.qml new file mode 100644 index 00000000..65e1f574 --- /dev/null +++ b/desktop/shell/shell/Commons/BatteryStatus.qml @@ -0,0 +1,122 @@ +pragma Singleton +import QtQuick +import QtQml.Models +import Qt.labs.folderlistmodel +import Quickshell +import Quickshell.Io +import Quickshell.Services.UPower +import "../plugins/panels/power/Model.js" as Model + +// Orchard: the battery state the bar's icon shows, apart from the panel, so +// the status cluster, the lock and the control center show the same thing. +// The panel binds its own properties of these names to it. +Singleton { + id: root + + // One uevent file contains the measured properties of each power supply. + // Read them together when UPower signals or the one-minute fallback fires. + readonly property string supplyDir: Quickshell.env("OMARCHY_POWER_SUPPLY_PATH") || "/sys/class/power_supply" + FolderListModel { + id: supplies + folder: "file://" + root.supplyDir + showFiles: false + showDotAndDotDot: false + } + Instantiator { + id: readings + model: supplies + delegate: FileView { + required property string fileName + path: root.supplyDir + "/" + fileName + "/uevent" + printErrors: false + onLoaded: Qt.callLater(root.collect) + onLoadFailed: Qt.callLater(root.collect) + } + onObjectRemoved: Qt.callLater(root.collect) + } + property var batteryInfo: ({}) + function collect() { + var battery = null, packs = 0, power = "unknown" + for (var i = 0; i < readings.count; i++) { + var file = readings.objectAt(i) + if (!file || !file.loaded) continue + var props = {} + for (var line of file.text().split("\n")) { + var match = /^POWER_SUPPLY_(\w+)=(.*)$/.exec(line) + if (match) props[match[1]] = match[2] + } + if (props.TYPE === "Battery" && props.PRESENT !== "0") { packs++; battery = props } + else if (props.ONLINE === "1") power = "connected" + else if (props.ONLINE === "0" && power !== "connected") power = "disconnected" + } + var info = { external_power: power } + if (packs === 1 && /^\d+$/.test(battery.CAPACITY) && Number(battery.CAPACITY) <= 100) { + info.percentage = battery.CAPACITY + "%" + if (Number(battery.ENERGY_FULL) > 0) info.size = (Number(battery.ENERGY_FULL) / 1e6).toFixed(1) + "Wh" + if (battery.CYCLE_COUNT !== undefined) info.cycles = battery.CYCLE_COUNT + var watts = battery.POWER_NOW !== undefined ? Number(battery.POWER_NOW) / 1e6 + : Number(battery.CURRENT_NOW) * Number(battery.VOLTAGE_NOW) / 1e12 + if (isFinite(watts)) info.rate = Math.abs(watts).toFixed(1) + "W" + } + root.batteryInfo = info + } + readonly property bool externalPower: batteryInfo.external_power === "connected" + readonly property var batteryDevice: { + var device = UPower.displayDevice + if (device && device.isPresent) return device + var measured = Model.batteryPercentage(null, root.batteryInfo) + // Do not invent a charging/discharging state when only capacity is known. + return measured === null ? null : { isPresent: true, percentage: measured / 100, state: 0 } + } + readonly property bool batteryPresent: batteryDevice !== null + readonly property var displayedPercentage: Model.batteryPercentage(batteryDevice, batteryInfo) + readonly property bool discharging: { + var device = UPower.displayDevice + return !!(device && device.isPresent && device.state === UPowerDeviceState.Discharging) + } + readonly property string icon: Model.batteryIcon(batteryDevice, discharging, upowerStates(), externalPower) + + function upowerStates() { + return { + Charging: UPowerDeviceState.Charging, + Discharging: UPowerDeviceState.Discharging, + FullyCharged: UPowerDeviceState.FullyCharged, + PendingCharge: UPowerDeviceState.PendingCharge + } + } + + function refresh() { + scheduleRead.restart() + } + + Timer { + id: scheduleRead + interval: 100 + onTriggered: { + for (var i = 0; i < readings.count; i++) { + var file = readings.objectAt(i) + if (file) file.reload() + } + } + } + + Connections { + target: UPower + function onOnBatteryChanged() { root.refresh() } + } + + Connections { + target: UPower.displayDevice + function onIsPresentChanged() { root.refresh() } + function onPercentageChanged() { root.refresh() } + function onStateChanged() { root.refresh() } + } + + Timer { + interval: 60000 + running: true + repeat: true + triggeredOnStart: true + onTriggered: root.refresh() + } +} diff --git a/desktop/shell/shell/Commons/IpcRegistry.qml b/desktop/shell/shell/Commons/IpcRegistry.qml index 4184260c..2a60f966 100644 --- a/desktop/shell/shell/Commons/IpcRegistry.qml +++ b/desktop/shell/shell/Commons/IpcRegistry.qml @@ -13,6 +13,7 @@ Singleton { id: root property var handlers: [] + readonly property var methods: new WeakMap() // A bare handler's own functions (signals and hooks such as targetChanged), // which qs ipc never exposes and neither may the socket. @@ -77,9 +78,12 @@ Singleton { // 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) { + if (methods.has(handler)) return methods.get(handler) + var names = functionNames(handler).filter(function(name) { return builtins.indexOf(name) === -1 && !/Changed$/.test(name) }) + methods.set(handler, names) + return names } function call(target, method, args) { diff --git a/desktop/shell/shell/Commons/Lite.qml b/desktop/shell/shell/Commons/Lite.qml new file mode 100644 index 00000000..b342f6e9 --- /dev/null +++ b/desktop/shell/shell/Commons/Lite.qml @@ -0,0 +1,12 @@ +pragma Singleton + +import QtQuick +import Quickshell + +QtObject { + readonly property bool enabled: Quickshell.env("OMARCHY_SHELL_LITE") === "1" + + function duration(ms) { + return enabled ? Math.min(ms, 80) : ms + } +} diff --git a/desktop/shell/shell/Commons/SessionStatus.qml b/desktop/shell/shell/Commons/SessionStatus.qml new file mode 100644 index 00000000..b435ef3a --- /dev/null +++ b/desktop/shell/shell/Commons/SessionStatus.qml @@ -0,0 +1,42 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Io +import "../plugins/panels/network" as Network +import "../plugins/status" as Status + +Singleton { + id: root + readonly property Network.Status network: Network.Status {} + readonly property Status.RotationLock rotation: Status.RotationLock {} + + readonly property string backlight: ShellFacts.hardware ? ShellFacts.hardware.backlight : "" + readonly property bool autoAvailable: !!backlight && !!ShellFacts.hardware.lightSensor + readonly property int brightness: { + var max = Number(maxFile.text().trim()) + var raw = actualFile.text().trim() || brightnessFile.text().trim() + return raw && max > 0 ? Math.round(Number(raw) * 100 / max) : -1 + } + function refreshBrightness() { + display.reread() + config.reread() + if (backlight) { brightnessFile.reload(); actualFile.reload() } + } + FileView { id: maxFile; path: root.backlight ? root.backlight + "/max_brightness" : ""; printErrors: false } + FileView { id: actualFile; path: root.backlight ? root.backlight + "/actual_brightness" : ""; printErrors: false } + FileView { id: brightnessFile; path: root.backlight ? root.backlight + "/brightness" : ""; printErrors: false } + + WatchedFile { + id: display + path: (Quickshell.env("XDG_STATE_HOME") || Quickshell.env("HOME") + "/.local/state") + "/omarchy/display" + } + WatchedFile { + id: config + path: (Quickshell.env("XDG_CONFIG_HOME") || Quickshell.env("HOME") + "/.config") + "/omarchy/als-brightness.conf" + } + readonly property bool autoOn: { + var state = /^\s*auto_brightness\s*=\s*(on|off)\b/m.exec(display.text) + if (state) return state[1] === "on" + return /^\s*enabled\s*=\s*(on|yes|true|1)\s*(?:#.*)?$/mi.test(config.text) + } +} diff --git a/desktop/shell/shell/Commons/ShellFacts.qml b/desktop/shell/shell/Commons/ShellFacts.qml new file mode 100644 index 00000000..c6b714e7 --- /dev/null +++ b/desktop/shell/shell/Commons/ShellFacts.qml @@ -0,0 +1,55 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Io + +// Menu definitions and package transactions invalidate command availability. +// Keep the result here while windows and their individual pages come and go. +Singleton { + id: root + property var hardware: null + property bool settled: false + property var unavailableReaders: ({}) + function hasReader(name) { return settled && !unavailableReaders[name] } + property var missing: ({}) + property var hyprland: ({}) + readonly property bool hypr: !!Quickshell.env("HYPRLAND_INSTANCE_SIGNATURE") + property var names: [] + property bool dirty: true + signal updated() + + function configure(commands) { + var next = Object.keys(commands).sort() + if (next.join(" ") === names.join(" ")) return + names = next + invalidate() + } + function invalidate() { + dirty = true + Qt.callLater(start) + } + function start() { + if (!Startup.ready || reader.running || !dirty) return + dirty = false + reader.command = ["python3", Quickshell.env("OMARCHY_PATH") + "/shell/services/shell-facts.py", + hardware ? "commands" : "session"].concat(names) + reader.running = true + } + AfterStartup { onTriggered: root.start() } + Process { + id: reader + stdout: StdioCollector { id: result; waitForEnd: true } + onExited: function(code) { + if (code === 0) { + var facts = JSON.parse(result.text) + root.unavailableReaders = facts.unavailableReaders || {} + root.missing = facts.missing + root.hyprland = facts.hyprland + if (facts.hardware) root.hardware = facts.hardware + } + root.settled = true + root.updated() + if (root.dirty) Qt.callLater(root.start) + } + } +} diff --git a/desktop/shell/shell/Commons/Startup.qml b/desktop/shell/shell/Commons/Startup.qml new file mode 100644 index 00000000..27c238f5 --- /dev/null +++ b/desktop/shell/shell/Commons/Startup.qml @@ -0,0 +1,13 @@ +pragma Singleton + +import QtQuick + +// Give the first frame priority. If the startup lock is being drawn, its +// service releases the timer once the compositor can show the PIN screen. +Timer { + property bool ready: false + property bool drawingLock: false + interval: 2000 + running: !drawingLock && !ready + onTriggered: ready = true +} diff --git a/desktop/shell/shell/Commons/Style.qml b/desktop/shell/shell/Commons/Style.qml index 6016cce4..68f2f375 100644 --- a/desktop/shell/shell/Commons/Style.qml +++ b/desktop/shell/shell/Commons/Style.qml @@ -361,9 +361,11 @@ QtObject { // 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 + // Looping pulses and marquees should stay still at lite transition speeds. + readonly property bool animateLoops: !reduceMotion && !Commons.Lite.enabled function duration(ms) { - return reduceMotion ? 0 : ms + return reduceMotion ? 0 : Commons.Lite.duration(ms) } // A strong ease-out, for anything appearing or moving in answer to the diff --git a/desktop/shell/shell/Commons/Wallpaper.qml b/desktop/shell/shell/Commons/Wallpaper.qml new file mode 100644 index 00000000..90b7ac2d --- /dev/null +++ b/desktop/shell/shell/Commons/Wallpaper.qml @@ -0,0 +1,16 @@ +pragma Singleton + +import QtQuick + +// Qt shares a decoded image by URL and requested size. The desktop, lock +// surface and its wake preload all display the same still on a given output. +QtObject { + property int revision: 0 + + function decodeSize(native, width, height) { + if (native && native.width > 0 && native.height > 0 + && (native.width < width || native.height < height)) + return Qt.size(native.width, native.height) + return Qt.size(width, height) + } +} diff --git a/desktop/shell/shell/Commons/qmldir b/desktop/shell/shell/Commons/qmldir index 24f4db12..6e858ed5 100644 --- a/desktop/shell/shell/Commons/qmldir +++ b/desktop/shell/shell/Commons/qmldir @@ -1,16 +1,23 @@ module qs.Commons singleton AudioNodes 1.0 AudioNodes.qml +singleton BatteryStatus 1.0 BatteryStatus.qml singleton Border 1.0 Border.qml singleton Color 1.0 Color.qml singleton I18n 1.0 I18n.qml singleton InputDevices 1.0 InputDevices.qml singleton IpcRegistry 1.0 IpcRegistry.qml singleton InputMethodState 1.0 InputMethodState.qml +singleton Lite 1.0 Lite.qml +singleton Startup 1.0 Startup.qml singleton Style 1.0 Style.qml singleton TimeZone 1.0 TimeZone.qml singleton TimeFormat 1.0 TimeFormat.qml singleton UntypedInput 1.0 UntypedInput.qml singleton Util 1.0 Util.qml +singleton Wallpaper 1.0 Wallpaper.qml +AfterStartup 1.0 AfterStartup.qml ShellIpc 1.0 ShellIpc.qml Translations 1.0 Translations.qml WatchedFile 1.0 WatchedFile.qml +singleton ShellFacts 1.0 ShellFacts.qml +singleton SessionStatus 1.0 SessionStatus.qml diff --git a/desktop/shell/shell/Ui/AppIconImage.qml b/desktop/shell/shell/Ui/AppIconImage.qml new file mode 100644 index 00000000..687597e8 --- /dev/null +++ b/desktop/shell/shell/Ui/AppIconImage.qml @@ -0,0 +1,15 @@ +import QtQuick +import qs.Commons + +Image { + property real outputScale: Screen.devicePixelRatio + readonly property int pixelSize: Math.round(width * outputScale) + // Qt applies DPR itself to SVGs and image providers. Ordinary PNGs + // (including the raster cache) take a sourceSize in physical pixels. + readonly property bool scalable: /^image:|\.(svgz?|pdf)([?#]|$)/i.test(String(source)) + sourceSize: Qt.size(scalable ? width : pixelSize, scalable ? height : Math.round(height * outputScale)) + cache: true + fillMode: Image.PreserveAspectFit + smooth: true + mipmap: !Lite.enabled +} diff --git a/desktop/shell/shell/Ui/BackgroundMedia.qml b/desktop/shell/shell/Ui/BackgroundMedia.qml index fd818598..9efdea40 100644 --- a/desktop/shell/shell/Ui/BackgroundMedia.qml +++ b/desktop/shell/shell/Ui/BackgroundMedia.qml @@ -10,6 +10,7 @@ Item { property int version: 0 // 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 asynchronous: true 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 @@ -38,12 +39,13 @@ Item { Image { readonly property bool ready: status === Image.Ready readonly property bool failed: status === Image.Error - source: !root.constrainDecode || root.decodeSize.width > 0 ? root.imageUrl : "" + source: sourceSize.width > 0 && sourceSize.height > 0 ? root.imageUrl : "" fillMode: Image.PreserveAspectCrop - asynchronous: true + asynchronous: root.asynchronous + retainWhileLoading: root.asynchronous 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) + sourceSize.width: root.constrainDecode ? root.decodeSize.width : Math.ceil(width * Screen.devicePixelRatio) + sourceSize.height: root.constrainDecode ? root.decodeSize.height : Math.ceil(height * Screen.devicePixelRatio) } } } diff --git a/desktop/shell/shell/Ui/Button.qml b/desktop/shell/shell/Ui/Button.qml index 5d34baa1..27cf8a9c 100644 --- a/desktop/shell/shell/Ui/Button.qml +++ b/desktop/shell/shell/Ui/Button.qml @@ -196,7 +196,7 @@ BorderSurface { to: 360 duration: Style.duration(900) loops: Animation.Infinite - running: root.iconSpinning && !Style.reduceMotion + running: root.iconSpinning && Style.animateLoops } } diff --git a/desktop/shell/shell/Ui/KeyboardSession.qml b/desktop/shell/shell/Ui/KeyboardSession.qml new file mode 100644 index 00000000..b6f66689 --- /dev/null +++ b/desktop/shell/shell/Ui/KeyboardSession.qml @@ -0,0 +1,15 @@ +import Quickshell +import Quickshell.Io + +// Closing the input pipe releases the keyboard even when a different surface +// (such as the launcher) takes over before the opening command has run. +Process { + id: session + required property string action + required property bool active + command: [(Quickshell.env("OMARCHY_PATH") || "/usr/share/omarchy") + "/bin/omarchy-keyboard", action + "-while-open"] + stdinEnabled: active + function startIfActive() { if (active && !running) running = true } + onActiveChanged: if (active) Qt.callLater(startIfActive) + onExited: function(code) { if (!code && active) Qt.callLater(startIfActive) } +} diff --git a/desktop/shell/shell/Ui/LazyKeyboardPanel.qml b/desktop/shell/shell/Ui/LazyKeyboardPanel.qml new file mode 100644 index 00000000..94735d4b --- /dev/null +++ b/desktop/shell/shell/Ui/LazyKeyboardPanel.qml @@ -0,0 +1,38 @@ +import QtQuick + +// A bar button and its IPC remain live. A host such as Control Center can +// also use content directly without constructing a separate popup window. +OnDemandLoader { + id: loader + required property Item anchorItem + required property QtObject bar + property var owner: null + property bool open: false + property bool centerOnBar: false + property bool yielding: false + property Item focusTarget: null + property int contentWidth: 0 + property int contentHeight: 0 + property Component content + readonly property Item loadedContent: item ? item.loadedContent : null + readonly property real loadedContentHeight: item ? item.loadedContentHeight : 0 + + function ensureContent() { return load().ensureContent() } + function fittedContentWidth(width, cap) { return item ? item.fittedContentWidth(width, cap) : width } + function fittedContentHeight(height, cap) { return item ? item.fittedContentHeight(height, cap) : height } + + keepAlive: !!item && item.visible + requested: open + sourceComponent: KeyboardPanel { + anchorItem: loader.anchorItem + owner: loader.owner + bar: loader.bar + open: !!loader.item && loader.open + centerOnBar: loader.centerOnBar + yielding: loader.yielding + focusTarget: loader.focusTarget + contentWidth: loader.contentWidth + contentHeight: loader.contentHeight + content: loader.content + } +} diff --git a/desktop/shell/shell/Ui/MultiSelect.qml b/desktop/shell/shell/Ui/MultiSelect.qml index 4e3a8d71..81d0feb8 100644 --- a/desktop/shell/shell/Ui/MultiSelect.qml +++ b/desktop/shell/shell/Ui/MultiSelect.qml @@ -472,7 +472,7 @@ Item { font.pixelSize: Style.font.body RotationAnimator on rotation { - running: root.loadingOptions && !Style.reduceMotion + running: root.loadingOptions && Style.animateLoops from: 0; to: 360 duration: Style.duration(800) loops: Animation.Infinite diff --git a/desktop/shell/shell/Ui/OnDemandLoader.qml b/desktop/shell/shell/Ui/OnDemandLoader.qml new file mode 100644 index 00000000..fb595e31 --- /dev/null +++ b/desktop/shell/shell/Ui/OnDemandLoader.qml @@ -0,0 +1,21 @@ +import QtQuick + +// Keep rapid reopens warm. Controllers and IPC live outside their visual trees. +Loader { + id: loader + active: false + property bool keepAlive: false + property bool requested: false + onRequestedChanged: if (requested) active = true + + Timer { + interval: 1500 + running: loader.active && !loader.requested && !loader.keepAlive + onTriggered: loader.active = false + } + + function load() { + active = true + return item + } +} diff --git a/desktop/shell/shell/Ui/qmldir b/desktop/shell/shell/Ui/qmldir index e45214be..c09c8131 100644 --- a/desktop/shell/shell/Ui/qmldir +++ b/desktop/shell/shell/Ui/qmldir @@ -1,5 +1,6 @@ module qs.Ui +AppIconImage 1.0 AppIconImage.qml BarIndicator 1.0 BarIndicator.qml BarIconButton 1.0 BarIconButton.qml BarIconContent 1.0 BarIconContent.qml @@ -15,8 +16,11 @@ Dropdown 1.0 Dropdown.qml FilterInput 1.0 FilterInput.qml IconContentBounds 1.0 IconContentBounds.qml KeyboardPanel 1.0 KeyboardPanel.qml +KeyboardSession 1.0 KeyboardSession.qml +LazyKeyboardPanel 1.0 LazyKeyboardPanel.qml MultiSelect 1.0 MultiSelect.qml NumberField 1.0 NumberField.qml +OnDemandLoader 1.0 OnDemandLoader.qml OpticalGlyph 1.0 OpticalGlyph.qml OverlayWindow 1.0 OverlayWindow.qml Panel 1.0 Panel.qml diff --git a/desktop/shell/shell/controlcenter/ControlCenter.qml b/desktop/shell/shell/controlcenter/ControlCenter.qml index 7567a33f..1f8964bc 100644 --- a/desktop/shell/shell/controlcenter/ControlCenter.qml +++ b/desktop/shell/shell/controlcenter/ControlCenter.qml @@ -8,14 +8,8 @@ import Quickshell.Services.UPower import qs.Commons import qs.Commons as Commons import qs.Ui -import "../plugins/panels/network" as Network import "../plugins/panels/bluetooth" as BluetoothStatus import "../plugins/panels/bluetooth/Model.js" as BluetoothModel -import "../plugins/status" as StatusParts -import "../plugins/panels/monitor" as Monitor -import "../plugins/panels/network" as NetworkPanel -import "../plugins/panels/audio" as AudioPanel -import "../plugins/panels/power" as PowerPanel import "../plugins/panels/power/Model.js" as PowerModel // The control center (SHELL-SPEC, step 2): the main view. States you flip @@ -31,7 +25,7 @@ Item { // Over an app it takes the keyboard: the app's text field going off must // not put the on-screen keyboard away, which stays, under the control // center (omarchy-keyboard hold … release). - onMappedChanged: run([omarchy("omarchy-keyboard"), mapped ? "hold" : "release"]) + KeyboardSession { action: "hold"; active: root.mapped } property real reveal: 0 readonly property bool gpu: Quickshell.env("QT_QUICK_BACKEND") !== "software" @@ -49,9 +43,9 @@ Item { // ------------------------------------------------------------ state - Network.Status { id: network } + readonly property var network: SessionStatus.network BluetoothStatus.Status { id: bluetooth } - StatusParts.RotationLock { id: rotation } + readonly property var rotation: SessionStatus.rotation readonly property var idleService: shell ? shell.firstPartyServiceFor("omarchy.idle") : null readonly property bool stayAwake: idleService ? idleService.stayAwake === true : false @@ -84,7 +78,7 @@ Item { readonly property bool keyboardShown: keyboardState.loaded && keyboardState.text().trim() === "1" property int brightness: -1 - property bool autoBrightness: false + readonly property bool autoBrightness: SessionStatus.autoOn readonly property string wifiSubtitle: { if (!network.wifiEnabled) return Commons.I18n.t("controlCenter.off") @@ -109,8 +103,7 @@ Item { // A module's page: its panel's content, pushed in from the right. A // module without a page yet opens the bar's panel for it. function openPage(module) { - var panelForPage = root.modules[module] - if (panelForPage) { panelForPage.open(); return } + if (root.modules.open(module)) return root.close() run(["omarchy-shell", "shell", "toggle", module]) } @@ -120,62 +113,13 @@ Item { // in for the bar it would read its colours and font from, and opening or // closing it shows or leaves the page. - QtObject { - id: pageHost - readonly property color foreground: root.text - readonly property color barForeground: root.text - readonly property color urgent: Commons.Color.urgent - readonly property string fontFamily: Style.font.family - readonly property var shell: root.shell - readonly property string position: "top" - readonly property bool vertical: false - readonly property int barSize: Style.bar.sizeHorizontal - // The rest of what a panel's own bar button and popup ask of a bar, - // inert here: hosted, neither is ever shown. - readonly property var activePopout: null - readonly property bool foregroundAnimationEnabled: false - readonly property int sizeHorizontal: Style.bar.sizeHorizontal - readonly property int iconFont: Style.font.icon - readonly property int iconSize: Style.font.icon - readonly property int iconSlot: Style.space(28) - readonly property bool iconCanvas: false - readonly property var clickTargets: [] - function barSizeFor() { return Style.bar.sizeHorizontal } - function showTooltip() {} - function hideTooltip() {} - function requestPopout() { return false } - function releasePopout() {} - function notePopoutCard() {} - function popoutCardFor() { return null } - function targetBelongsToWindow() { return false } - function run(command) { Quickshell.execDetached(["sh", "-c", command]) } - function switchPanelFrom(panel, direction) { return false } - function showPage(panel) { root.showPage(panel) } - function leavePage(panel) { root.leavePage(panel) } - // How tall a page can be (pageLoader's cap), for content that fills it. - readonly property real pageRoom: pageLoader.maxHeight - } - - Item { - visible: false - Monitor.Panel { id: displayModule; host: pageHost; bar: pageHost; moduleName: "omarchy.monitor" } - NetworkPanel.Panel { id: networkModule; host: pageHost; bar: pageHost; moduleName: "omarchy.network" } - AudioPanel.Panel { id: audioModule; host: pageHost; bar: pageHost; moduleName: "omarchy.audio" } - BluetoothStatus.Panel { id: bluetoothModule; host: pageHost; bar: pageHost; moduleName: "omarchy.bluetooth" } - PowerPanel.Panel { id: powerModule; host: pageHost; bar: pageHost; moduleName: "omarchy.power" } - } - readonly property var modules: ({ - "omarchy.monitor": displayModule, - "omarchy.network": networkModule, - "omarchy.audio": audioModule, - "omarchy.bluetooth": bluetoothModule, - "omarchy.power": powerModule - }) + required property var modules + readonly property real pageRoom: pageLoader.maxHeight // The battery: how full, whether it charges, and at how many watts. Its // page (the battery panel) has the rest; with no battery found the row // is dimmed and the page says so. - PowerPanel.Status { id: battery } + readonly property var battery: Commons.BatteryStatus readonly property string batteryNote: { if (!battery.batteryPresent) return Commons.I18n.t("controlCenter.noBattery", "No battery") var parts = [] @@ -258,6 +202,7 @@ Item { } // The screen follows the finger while it drags: one write at a time, and // a level moved to during a write is written as soon as that one ends. + readonly property bool writingBrightness: brightnessSet.running || brightnessQueued property bool brightnessQueued: false function setBrightness(percent) { root.brightness = Math.max(1, Math.min(100, Math.round(percent))) @@ -271,24 +216,9 @@ Item { id: brightnessSet onRunningChanged: if (!running && root.brightnessQueued) root.setBrightness(root.brightness) } - Process { - id: brightnessRead - command: ["omarchy-brightness-display"] - stdout: StdioCollector { - waitForEnd: true - onStreamFinished: { - var value = parseInt(text, 10) - root.brightness = isNaN(value) ? -1 : value - } - } - } - Process { - id: autoRead - command: ["omarchy-auto-brightness", "status"] - stdout: StdioCollector { - waitForEnd: true - onStreamFinished: root.autoBrightness = /auto-brightness: on/.test(text) - } + Connections { + target: SessionStatus + function onBrightnessChanged() { if (!brightnessSet.running) root.brightness = SessionStatus.brightness } } // ------------------------------------------------------------ cells @@ -377,8 +307,8 @@ Item { // ----------------------------------------------------------- lifecycle function prepare() { - if (!brightnessRead.running) brightnessRead.running = true - if (!autoRead.running) autoRead.running = true + root.brightness = SessionStatus.brightness + SessionStatus.refreshBrightness() root.focusKey = "" } @@ -430,7 +360,8 @@ Item { property bool popupStyle: false function togglePopup() { if (root.opened) { root.close(); return } - root.popupStyle = !root.phone + var screen = panel.focusedScreen() + root.popupStyle = screen ? Math.min(screen.width, screen.height) >= 600 : !root.phone root.show() } function animateIn() { @@ -559,41 +490,7 @@ Item { // Moving: the spring, a finger, or a popup's fade. readonly property bool moving: spring.running || root.pulling || popupIn.running || popupOut.running - // While open, a note for the Home button (omarchy-home-button closes it). - readonly property string openNote: (Quickshell.env("XDG_RUNTIME_DIR") || "/tmp") + "/omarchy-control-center-open" - // One writer, run again until the note matches: two detached commands could - // finish out of order and leave the note behind a closed control center, - // and Home would then only ever "close" it. A note left from an earlier - // shell goes at start. - property bool noteWritten: true - function writeOpenNote() { - if (noteWriter.running || root.noteWritten === root.opened) return - noteWriter.writing = root.opened - noteWriter.command = root.opened ? ["touch", root.openNote] : ["rm", "-f", root.openNote] - noteWriter.running = true - } - Process { - id: noteWriter - property bool writing: false - onExited: { - root.noteWritten = writing - root.writeOpenNote() - } - } - Component.onCompleted: writeOpenNote() - onOpenedChanged: { - writeOpenNote() - Qt.callLater(notePopupCard) - } - - ShellIpc { - target: "omarchy.controlcenter" - function toggle(): void { root.toggle() } - function open(): void { if (!root.opened) root.open() } - function close(): void { root.close() } - // Open at a module's page: omarchy.monitor, … - function page(module: string): void { root.openPage(module) } - } + onOpenedChanged: Qt.callLater(notePopupCard) // ------------------------------------------------------------- window diff --git a/desktop/shell/shell/controlcenter/ControlCenterModules.qml b/desktop/shell/shell/controlcenter/ControlCenterModules.qml new file mode 100644 index 00000000..e50ca7dd --- /dev/null +++ b/desktop/shell/shell/controlcenter/ControlCenterModules.qml @@ -0,0 +1,97 @@ +import QtQuick +import Quickshell +import "../plugins/panels/power" as Power +import "../plugins/panels/bluetooth" as Bluetooth +import "../plugins/panels/audio" as Audio +import "../plugins/panels/network" as Network +import "../plugins/panels/monitor" as Monitor +import qs.Commons +import qs.Ui +import qs.Commons as Commons + +// Page controllers own asynchronous operations such as joining Wi-Fi. Only +// create a controller when its page is requested, and let it finish its work +// when the sheet and its page content have been dismissed. +Item { + id: root + required property var shell + required property var center + visible: false + + QtObject { + id: pageHost + readonly property color foreground: Commons.Color.popups.text + readonly property color barForeground: Commons.Color.popups.text + readonly property color urgent: Commons.Color.urgent + readonly property string fontFamily: Style.font.family + readonly property var shell: root.shell + readonly property string position: "top" + readonly property bool vertical: false + readonly property int barSize: Style.bar.sizeHorizontal + // The rest of what a panel's own bar button and popup ask of a bar, + // inert here: hosted, neither is ever shown. + readonly property var activePopout: null + readonly property bool foregroundAnimationEnabled: false + readonly property int sizeHorizontal: Style.bar.sizeHorizontal + readonly property int iconFont: Style.font.icon + readonly property int iconSize: Style.font.icon + readonly property int iconSlot: Style.space(28) + readonly property bool iconCanvas: false + readonly property var clickTargets: [] + function barSizeFor() { return Style.bar.sizeHorizontal } + function showTooltip() {} + function hideTooltip() {} + function requestPopout() { return false } + function releasePopout() {} + function notePopoutCard() {} + function popoutCardFor() { return null } + function targetBelongsToWindow() { return false } + function run(command) { Quickshell.execDetached(["sh", "-c", command]) } + function switchPanelFrom(panel, direction) { return false } + function showPage(panel) { if (root.center) root.center.showPage(panel) } + function leavePage(panel) { if (root.center) root.center.leavePage(panel) } + // How tall a page can be (pageLoader's cap), for content that fills it. + readonly property real pageRoom: root.center ? root.center.pageRoom : 0 + } + + readonly property var loaders: ({ + "omarchy.monitor": monitor, "omarchy.network": network, "omarchy.audio": audio, + "omarchy.bluetooth": bluetooth, "omarchy.power": power + }) + + function open(module) { + if (!Object.prototype.hasOwnProperty.call(loaders, module)) return false + loaders[module].load().open() + return true + } + + OnDemandLoader { + id: monitor + keepAlive: true + sourceComponent: Monitor.Panel { host: pageHost; bar: pageHost; moduleName: "omarchy.monitor" } + } + + OnDemandLoader { + id: network + keepAlive: true + sourceComponent: Network.Panel { host: pageHost; bar: pageHost; moduleName: "omarchy.network" } + } + + OnDemandLoader { + id: audio + keepAlive: true + sourceComponent: Audio.Panel { host: pageHost; bar: pageHost; moduleName: "omarchy.audio" } + } + + OnDemandLoader { + id: bluetooth + keepAlive: true + sourceComponent: Bluetooth.Panel { host: pageHost; bar: pageHost; moduleName: "omarchy.bluetooth" } + } + + OnDemandLoader { + id: power + keepAlive: true + sourceComponent: Power.Panel { host: pageHost; bar: pageHost; moduleName: "omarchy.power" } + } +} diff --git a/desktop/shell/shell/launcher/Launcher.qml b/desktop/shell/shell/launcher/Launcher.qml index 147679a1..2776f89e 100644 --- a/desktop/shell/shell/launcher/Launcher.qml +++ b/desktop/shell/shell/launcher/Launcher.qml @@ -39,8 +39,7 @@ Item { property int cursor: 0 property bool cursorShown: false - property var apps: [] - property bool appsStale: true + readonly property var apps: appLibrary ? appLibrary.entries : [] property var recentFiles: [] property double now: Date.now() @@ -54,15 +53,17 @@ Item { // ------------------------------------------------------------- geometry - readonly property real screenWidth: panel.width - readonly property real screenHeight: panel.height + // The layer surface is recreated on show. Its transient geometry must not + // repaginate the phone grid and discard every icon between opens. + readonly property var layoutScreen: panel.targetScreen || panel.focusedScreen() + readonly property real screenWidth: layoutScreen ? layoutScreen.width : 0 + readonly property real screenHeight: layoutScreen ? layoutScreen.height : 0 readonly property bool phone: Model.isPhone(screenWidth, screenHeight) - readonly property bool landscape: screenWidth > screenHeight readonly property int columns: Model.columnsFor(screenWidth, screenHeight, phone) - readonly property int sideMargin: phone ? Style.space(16) : (landscape ? Style.space(56) : Style.space(32)) + readonly property int sideMargin: Model.sideMargin(screenWidth, screenHeight, Style) readonly property int contentWidth: Math.max(0, screenWidth - sideMargin * 2) readonly property real cellWidth: contentWidth / Math.max(1, columns) - readonly property int iconSize: Math.round(Math.min(Style.space(56), cellWidth * 0.6)) + readonly property int iconSize: Model.iconSize(screenWidth, screenHeight, Style) readonly property int labelLines: 2 readonly property int cellHeight: Style.space(10) + iconSize + Style.spacing.md + Math.ceil(labelMetrics.height) * labelLines + Style.space(10) readonly property int barInset: Style.bar.sizeHorizontal @@ -560,106 +561,9 @@ Item { enabled: root.gpu && root.opened NumberAnimation { duration: Style.duration(180); easing.type: Easing.OutCubic } } - // The wallpaper the desktop shows (a video one leaves the plain colour). - property string wallpaper: "" - - Process { - id: wallpaperProc - command: ["readlink", "-f", (Quickshell.env("HOME") || "") + "/.local/state/omarchy/current/background"] - stdout: StdioCollector { - onStreamFinished: { - var path = text.trim() - root.wallpaper = path && !Util.isVideoPath(path) ? path : "" - } - } - } - - Component.onCompleted: { wallpaperProc.running = true; opaqueProc.running = true } - - // Orchard: on the theme's plain background by default (no blurred copy - // is made then); Trigger > Toggle > Frosted Launcher puts it on the frosted - // wallpaper. Read as it opens. - property bool opaque: true - Process { - id: opaqueProc - command: ["omarchy-toggle-enabled", "launcher-frosted"] - onExited: function(code) { root.opaque = code !== 0 } - } - - // The background plugin names the new wallpaper the moment a theme or - // background switch sets it, before its own fade: the blurred copy is made - // then, not when the launcher next opens. - readonly property var backgroundService: root.shell && root.shell.bootIntro ? root.shell.bootIntro.backgroundService : null - readonly property string shownWallpaper: backgroundService ? String(backgroundService.currentBackground || "") : "" - onShownWallpaperChanged: if (shownWallpaper) root.wallpaper = Util.isVideoPath(shownWallpaper) ? "" : shownWallpaper - - // The frosted background: one file per wallpaper, theme colour and - // orientation, in the runtime directory. Both orientations are made - // together, so turning the iPad only switches between two ready images. - readonly property var backdropScreen: panel.screen || (Quickshell.screens.length > 0 ? Quickshell.screens[0] : null) - readonly property real backdropScale: backdropScreen ? backdropScreen.devicePixelRatio : 1 - readonly property int backdropWidth: backdropScreen ? Math.round(backdropScreen.width * backdropScale) : 0 - readonly property int backdropHeight: backdropScreen ? Math.round(backdropScreen.height * backdropScale) : 0 - // How much of the theme's menu background lies over the blurred wallpaper. - readonly property real backdropTint: 0.8 - readonly property color backdropColor: Commons.Color.menu.background - // Everything but the size: what makes a background outdated. - readonly property string backdropLook: wallpaper && !opaque - ? ["frosted4", wallpaper, Math.round(backdropColor.r * 255), Math.round(backdropColor.g * 255), Math.round(backdropColor.b * 255), backdropTint].join("|") : "" - readonly property string backdropKey: backdropKeyFor(backdropWidth, backdropHeight) - readonly property string backdropPath: backdropPathFor(backdropKey) - // key -> path of the backgrounds made so far - property var backdropSaved: ({}) - property var backdropQueue: [] - readonly property bool backdropReady: backdropKey !== "" && !!backdropSaved[backdropKey] - - function backdropKeyFor(width, height) { - return root.backdropLook && width > 0 && height > 0 ? root.backdropLook + "|" + width + "x" + height : "" - } - - function backdropPathFor(key) { - return (Quickshell.env("XDG_RUNTIME_DIR") || "/tmp") + "/omarchy-launcher-backdrop-" + Qt.md5(key) + ".png" - } - - // The orientation on screen first, then the other one. - onBackdropKeyChanged: { - if (!root.backdropKey) return - var wanted = [root.backdropKey, root.backdropKeyFor(root.backdropHeight, root.backdropWidth)] - root.backdropQueue = wanted.filter(function(key) { return key && !root.backdropSaved[key] }) - if (!backdropProc.running) root.makeNextBackdrop() - } - - function makeNextBackdrop() { - if (root.backdropQueue.length === 0) return - var key = root.backdropQueue[0] - root.backdropQueue = root.backdropQueue.slice(1) - var size = key.substring(key.lastIndexOf("|") + 1).split("x") - var look = key.split("|") - backdropProc.key = key - backdropProc.command = [Quickshell.env("OMARCHY_PATH") + "/bin/omarchy-launcher-backdrop", root.wallpaper, - root.backdropPathFor(key), size[0], size[1], look[2], look[3], look[4], look[5]] - backdropProc.running = true - } - - Process { - id: backdropProc - property string key: "" - onExited: function(exitCode) { - if (exitCode === 0) { - var saved = ({}) - for (var k in root.backdropSaved) { - // A background of an earlier wallpaper or theme colour is not - // needed again; both orientations of the current one are. - if (k.indexOf(root.backdropLook + "|") === 0) saved[k] = root.backdropSaved[k] - else Quickshell.execDetached(["rm", "-f", root.backdropSaved[k]]) - } - if (key.indexOf(root.backdropLook + "|") === 0) saved[key] = root.backdropPathFor(key) - else Quickshell.execDetached(["rm", "-f", root.backdropPathFor(key)]) - root.backdropSaved = saved - } - Qt.callLater(root.makeNextBackdrop) - } - } + readonly property int backdropWidth: layoutScreen ? Math.round(screenWidth * layoutScreen.devicePixelRatio) : 0 + readonly property int backdropHeight: layoutScreen ? Math.round(screenHeight * layoutScreen.devicePixelRatio) : 0 + readonly property string backdropPath: appLibrary ? appLibrary.backdrop.cachedPath(backdropWidth, backdropHeight) : "" property bool mapped: false NumberAnimation { @@ -688,13 +592,6 @@ Item { if (bar && bar.activePopout && typeof bar.activePopout.close === "function") bar.activePopout.close() if (root.shell && root.shell.controlCenter && root.shell.controlCenter.opened) root.shell.controlCenter.close() if (root.shell && root.shell.notificationCenter && root.shell.notificationCenter.opened) root.shell.notificationCenter.close() - if (root.appLibrary) root.appLibrary.refreshIcons() - if (root.appsStale || root.apps.length === 0) root.rebuild() - // Stop Screenrecording and the session list follow what is true now. - if (root.menu) root.menu.evaluateGuards() - // A wallpaper changed since: the next open shows it. - wallpaperProc.running = true - opaqueProc.running = true root.endSearch() root.pageIndex = 0 root.zone = "" @@ -756,12 +653,6 @@ Item { } } - function rebuild() { - root.appsStale = false - var rows = root.appLibrary ? root.appLibrary.sortedEntries("") : [] - root.apps = rows.map(function(row) { return row.entry }) - } - function showTab(name) { root.pageIndex = root.firstPage(name) } @@ -778,7 +669,7 @@ Item { if (root.searching) return root.searching = true root.now = Date.now() - recentFilesProc.running = true + if (Date.now() - recentFilesProc.lastRead >= 30000) recentFilesProc.running = true } // Cancel, Escape, or a tap beside an empty search: back to the tabs. @@ -852,7 +743,10 @@ Item { return } root.close() - if (root.menu) root.menu.runAction(e.action) + if (root.menu) { + root.menu.runAction(e.action) + guardRefresh.restart() + } } function runRow(row) { @@ -996,7 +890,9 @@ LC_ALL=C pacman -Qi omarchy-a 2>/dev/null | awk \'/^Depends On/ { on = 1 } /^Opt Process { id: recentFilesProc - command: ["bash", "-lc", 'exec "$@"', "bash", Quickshell.env("OMARCHY_PATH") + "/bin/omarchy-launcher-recent-files", "6"] + property double lastRead: 0 + command: [Quickshell.env("OMARCHY_PATH") + "/bin/omarchy-launcher-recent-files", "6"] + onExited: function(code) { if (code === 0) lastRead = Date.now() } stdout: StdioCollector { onStreamFinished: { try { @@ -1011,10 +907,6 @@ LC_ALL=C pacman -Qi omarchy-a 2>/dev/null | awk \'/^Depends On/ { on = 1 } /^Opt Connections { target: root.appLibrary - function onAppsChanged() { - if (root.opened) root.rebuild() - else root.appsStale = true - } function onRemovalNeedsTerminal() { if (root.opened) root.close() } @@ -1059,9 +951,10 @@ LC_ALL=C pacman -Qi omarchy-a 2>/dev/null | awk \'/^Depends On/ { on = 1 } /^Opt y: -root.barInset width: panel.width height: panel.height - visible: root.backdropReady - source: root.backdropReady ? Util.fileUrl(root.backdropPath) : "" - asynchronous: false + visible: !!root.backdropPath + source: root.backdropPath ? Util.fileUrl(root.backdropPath) : "" + sourceSize: Qt.size(root.backdropWidth, root.backdropHeight) + asynchronous: true cache: false smooth: false } @@ -1176,7 +1069,7 @@ LC_ALL=C pacman -Qi omarchy-a 2>/dev/null | awk \'/^Depends On/ { on = 1 } /^Opt x: root.sideMargin y: root.barInset + (root.compact ? Style.space(8) : Style.space(root.phone ? 12 : 24)) width: root.contentWidth - height: parent.height - y - (root.compact ? Style.space(4) : Style.space(root.phone ? 16 : 24)) + height: root.screenHeight - y - (root.compact ? Style.space(4) : Style.space(root.phone ? 16 : 24)) opacity: root.reveal transform: [ Scale { @@ -1550,12 +1443,26 @@ LC_ALL=C pacman -Qi omarchy-a 2>/dev/null | awk \'/^Depends On/ { on = 1 } /^Opt Repeater { model: root.pages Loader { + id: pageSlot required property var modelData required property int index + // Keep the landing page warm. While swiping, instantiate both + // visible pages and the destination of a keyboard/tab jump. + active: index === 0 || (root.mapped && (index === root.pageIndex + || (index >= Math.floor(pager.pageFloat) && index <= Math.ceil(pager.pageFloat)))) width: pager.width height: pager.height sourceComponent: modelData.tab === "apps" ? (root.phone ? phoneAppsPage : padAppsPage) : groupsPage - onLoaded: item.pageData = modelData + property real scrollY: 0 + onLoaded: { + item.pageData = modelData + if ("contentY" in item) item.contentY = scrollY + } + Connections { + target: pageSlot.item + ignoreUnknownSignals: true + function onContentYChanged() { if (target) pageSlot.scrollY = target.contentY } + } } } } @@ -1665,7 +1572,7 @@ LC_ALL=C pacman -Qi omarchy-a 2>/dev/null | awk \'/^Depends On/ { on = 1 } /^Opt text: recentColumn.index === 0 ? Commons.I18n.t("launcher.recentApps") : Commons.I18n.t("launcher.recentFiles") } Repeater { - model: recentColumn.rows + model: recentFlick.visible ? recentColumn.rows : [] ResultRow { required property var modelData required property int index @@ -1788,7 +1695,7 @@ LC_ALL=C pacman -Qi omarchy-a 2>/dev/null | awk \'/^Depends On/ { on = 1 } /^Opt layoutDirection: Qt.LeftToRight Repeater { - model: root.sessionEntries + model: root.phone ? [] : root.sessionEntries // The shell's button: [controls] fills, borders and focus ring; // Shutdown in the theme's urgent colour. Button { @@ -2016,19 +1923,16 @@ LC_ALL=C pacman -Qi omarchy-a 2>/dev/null | awk \'/^Depends On/ { on = 1 } /^Opt holds: true } - Image { + AppIconImage { id: appIcon scale: cellSqueeze.value anchors.horizontalCenter: parent.horizontalCenter y: Style.space(10) width: root.iconSize height: root.iconSize - sourceSize: Qt.size(root.iconSize * 2, root.iconSize * 2) - source: cell.app && root.appLibrary ? root.appLibrary.iconSource(cell.app.icon) : "" - fillMode: Image.PreserveAspectFit + outputScale: root.layoutScreen ? root.layoutScreen.devicePixelRatio : 1 + source: cell.app && root.appLibrary ? root.appLibrary.rasterSource(cell.app.icon, pixelSize) : "" asynchronous: false - smooth: true - mipmap: true } Text { @@ -2193,11 +2097,12 @@ LC_ALL=C pacman -Qi omarchy-a 2>/dev/null | awk \'/^Depends On/ { on = 1 } /^Opt visible: false onPressedChanged: { - if (!root.gpu) return + if (Lite.enabled || !root.gpu) return if (pressed) { out.stop(); press.restart() } else release() } function release() { + if (Lite.enabled || !root.gpu) return press.stop() out.restart() } @@ -2347,15 +2252,12 @@ LC_ALL=C pacman -Qi omarchy-a 2>/dev/null | awk \'/^Depends On/ { on = 1 } /^Opt font.family: root.glyphFont(resultRow.menuEntry) font.pixelSize: Style.font.heading } - Image { + AppIconImage { visible: !resultRow.menuEntry anchors.fill: parent - sourceSize: Qt.size(width * 2, height * 2) + outputScale: root.layoutScreen ? root.layoutScreen.devicePixelRatio : 1 source: resultRow.menuEntry || !root.appLibrary ? "" - : (resultRow.app ? root.appLibrary.iconSource(resultRow.app.icon) : Quickshell.iconPath("text-x-generic", true)) - fillMode: Image.PreserveAspectFit - smooth: true - mipmap: true + : (resultRow.app ? root.appLibrary.rasterSource(resultRow.app.icon, pixelSize) : Quickshell.iconPath("text-x-generic", true)) } } diff --git a/desktop/shell/shell/launcher/LauncherModel.js b/desktop/shell/shell/launcher/LauncherModel.js index 56d5bb47..4cfcddb0 100644 --- a/desktop/shell/shell/launcher/LauncherModel.js +++ b/desktop/shell/shell/launcher/LauncherModel.js @@ -17,6 +17,16 @@ function isPhone(width, height) { return Math.min(width, height) < PHONE_WIDTH } +function sideMargin(width, height, style) { + return style.space(isPhone(width, height) ? 16 : width > height ? 56 : 32) +} + +function iconSize(width, height, style) { + var columns = columnsFor(width, height, isPhone(width, height)) + var cellWidth = Math.max(0, width - 2 * sideMargin(width, height, style)) / columns + return Math.round(Math.min(style.space(56), cellWidth * 0.6)) +} + // The menu's System list as the session actions: its children in menu order, // without About (it belongs to Settings) and without Alt stand-ins. function sessionIds(itemOrder, items, altIds) { diff --git a/desktop/shell/shell/launcher/RecentApps.qml b/desktop/shell/shell/launcher/RecentApps.qml index c6eee60e..43cfe542 100644 --- a/desktop/shell/shell/launcher/RecentApps.qml +++ b/desktop/shell/shell/launcher/RecentApps.qml @@ -135,7 +135,6 @@ Item { } Component.onCompleted: { - Quickshell.execDetached(["mkdir", "-p", root.statePath.substring(0, root.statePath.lastIndexOf("/"))]) syncWindows() readState() } diff --git a/desktop/shell/shell/notificationcenter/NotificationCenter.qml b/desktop/shell/shell/notificationcenter/NotificationCenter.qml index 720560ed..aeece32b 100644 --- a/desktop/shell/shell/notificationcenter/NotificationCenter.qml +++ b/desktop/shell/shell/notificationcenter/NotificationCenter.qml @@ -6,7 +6,6 @@ import Quickshell.Wayland import qs.Commons import qs.Commons as Commons import qs.Ui -import "../plugins/panels/weather" as Weather // The notification center (SHELL-SPEC, step 3): "Today" (a large clock, the // date, the weather) and the notifications, over upstream's notification @@ -24,8 +23,6 @@ Item { property bool opened: false property bool mapped: false property real reveal: 0 - // Opened once: the weather is fetched from then on, not from shell start. - property bool everOpened: false readonly property bool gpu: Quickshell.env("QT_QUICK_BACKEND") !== "software" readonly property real screenWidth: panel.width > 0 ? panel.width : 1024 @@ -125,47 +122,7 @@ Item { return Qt.locale(I18n.formatLocale).toString(new Date(ts * 1000), "ddd") } - // The weather panel, hosted for its data only (never shown). - QtObject { - id: weatherHost - readonly property color foreground: root.text - readonly property color barForeground: root.text - readonly property color urgent: Commons.Color.urgent - readonly property string fontFamily: Style.font.family - readonly property var shell: root.shell - readonly property string position: "top" - readonly property bool vertical: false - readonly property int barSize: Style.bar.sizeHorizontal - readonly property var activePopout: null - readonly property bool foregroundAnimationEnabled: false - readonly property int sizeHorizontal: Style.bar.sizeHorizontal - readonly property int iconFont: Style.font.icon - readonly property int iconSize: Style.font.icon - readonly property int iconSlot: Style.space(28) - readonly property bool iconCanvas: false - readonly property var clickTargets: [] - function barSizeFor() { return Style.bar.sizeHorizontal } - function showTooltip() {} - function hideTooltip() {} - function requestPopout() { return false } - function releasePopout() {} - function notePopoutCard() {} - function popoutCardFor() { return null } - function targetBelongsToWindow() { return false } - function run(command) { Quickshell.execDetached(["sh", "-c", command]) } - function switchPanelFrom(panel, direction) { return false } - function showPage(panel) {} - function leavePage(panel) {} - } - Item { - visible: false - Loader { - id: weatherLoader - active: root.everOpened - sourceComponent: Weather.Panel { host: weatherHost; bar: weatherHost; moduleName: "omarchy.weather" } - } - } - readonly property var weather: weatherLoader.item + property var weather: null readonly property bool hasWeather: !!weather && weather.reportTempNum !== "" readonly property string weatherHighLow: { if (!weather || !weather.forecastDays || weather.forecastDays.length === 0) return "" @@ -195,7 +152,6 @@ Item { function show() { root.clearOthers() - root.everOpened = true // Stacks open closed again, and the list starts at the top. root.openGroups = ({}) root.markAllSeen() @@ -219,33 +175,8 @@ Item { function togglePopup() { root.toggle() } function animateIn() { root.settle(1, 0) } - // While open, a note for the Home button (omarchy-home-button closes it), - // written by one writer until it matches. - readonly property string openNote: (Quickshell.env("XDG_RUNTIME_DIR") || "/tmp") + "/omarchy-notification-center-open" - property bool noteWritten: true - function writeOpenNote() { - if (noteWriter.running || root.noteWritten === root.opened) return - noteWriter.writing = root.opened - noteWriter.command = root.opened ? ["touch", root.openNote] : ["rm", "-f", root.openNote] - noteWriter.running = true - } - Process { - id: noteWriter - property bool writing: false - onExited: { root.noteWritten = writing; root.writeOpenNote() } - } - Component.onCompleted: { writeOpenNote(); syncGroups() } - onOpenedChanged: { - writeOpenNote() - if (!opened && typing) endReply() - } - - ShellIpc { - target: "omarchy.notificationcenter" - function toggle(): void { root.toggle() } - function open(): void { if (!root.opened) root.open() } - function close(): void { root.close() } - } + Component.onCompleted: syncGroups() + onOpenedChanged: if (!opened && typing) endReply() // ------------------------------------------------------------ the pull @@ -263,7 +194,6 @@ Item { spring.running = false if (!root.opened) { root.clearOthers() - root.everOpened = true root.openGroups = ({}) root.markAllSeen() scroller.contentY = 0 @@ -439,19 +369,14 @@ Item { // finger) lies over the center then, and goes with the reply. property bool typing: false property bool replyKeyboard: false + KeyboardSession { action: "show"; active: root.replyKeyboard } function beginReply(byTouch) { root.typing = true - if (byTouch && !root.replyKeyboard) { - root.replyKeyboard = true - Quickshell.execDetached([(Quickshell.env("OMARCHY_PATH") || "/usr/share/omarchy") + "/bin/omarchy-keyboard", "show"]) - } + if (byTouch) root.replyKeyboard = true } function endReply() { root.typing = false - if (root.replyKeyboard) { - root.replyKeyboard = false - Quickshell.execDetached([(Quickshell.env("OMARCHY_PATH") || "/usr/share/omarchy") + "/bin/omarchy-keyboard", "hide"]) - } + root.replyKeyboard = false keyCatcher.forceActiveFocus() } @@ -1053,8 +978,8 @@ Item { anchors.fill: parent visible: card.iconUrl !== "" source: card.iconUrl - sourceSize.width: width * 2 - sourceSize.height: height * 2 + sourceSize.width: Math.ceil(width * Screen.devicePixelRatio) + sourceSize.height: Math.ceil(height * Screen.devicePixelRatio) fillMode: Image.PreserveAspectFit asynchronous: true } diff --git a/desktop/shell/shell/notificationcenter/NotificationWeather.qml b/desktop/shell/shell/notificationcenter/NotificationWeather.qml new file mode 100644 index 00000000..049bf699 --- /dev/null +++ b/desktop/shell/shell/notificationcenter/NotificationWeather.qml @@ -0,0 +1,46 @@ +import QtQuick +import Quickshell +import qs.Commons +import qs.Commons as Commons +import "../plugins/panels/weather" as Weather + +// The forecast keeps refreshing after the first visit, even with no sheet. +Weather.Panel { + id: weather + required property var shell + host: weatherHost + bar: weatherHost + moduleName: "omarchy.weather" + + QtObject { + id: weatherHost + readonly property color foreground: Commons.Color.popups.text + readonly property color barForeground: Commons.Color.popups.text + readonly property color urgent: Commons.Color.urgent + readonly property string fontFamily: Style.font.family + readonly property var shell: weather.shell + readonly property string position: "top" + readonly property bool vertical: false + readonly property int barSize: Style.bar.sizeHorizontal + readonly property var activePopout: null + readonly property bool foregroundAnimationEnabled: false + readonly property int sizeHorizontal: Style.bar.sizeHorizontal + readonly property int iconFont: Style.font.icon + readonly property int iconSize: Style.font.icon + readonly property int iconSlot: Style.space(28) + readonly property bool iconCanvas: false + readonly property var clickTargets: [] + function barSizeFor() { return Style.bar.sizeHorizontal } + function showTooltip() {} + function hideTooltip() {} + function requestPopout() { return false } + function releasePopout() {} + function notePopoutCard() {} + function popoutCardFor() { return null } + function targetBelongsToWindow() { return false } + function run(command) { Quickshell.execDetached(["sh", "-c", command]) } + function switchPanelFrom(panel, direction) { return false } + function showPage(panel) {} + function leavePage(panel) {} + } +} diff --git a/desktop/shell/shell/plugins/agents/Main.qml b/desktop/shell/shell/plugins/agents/Main.qml index e9426987..b725667f 100644 --- a/desktop/shell/shell/plugins/agents/Main.qml +++ b/desktop/shell/shell/plugins/agents/Main.qml @@ -22,7 +22,7 @@ Item { FileView { id: localModelFile - path: root.home + "/.local/state/omarchy/agent-local/status.json" + path: Startup.ready ? root.home + "/.local/state/omarchy/agent-local/status.json" : "" watchChanges: true printErrors: false onFileChanged: reload() @@ -40,7 +40,7 @@ Item { FileView { id: localRecipesFile - path: root.home + "/.local/state/omarchy/agent-local/list.json" + path: Startup.ready ? root.home + "/.local/state/omarchy/agent-local/list.json" : "" watchChanges: true printErrors: false onFileChanged: reload() @@ -83,7 +83,7 @@ Item { FileView { id: networkFile - path: root.home + "/.local/state/omarchy/agent-local/network.json" + path: Startup.ready ? root.home + "/.local/state/omarchy/agent-local/network.json" : "" watchChanges: true printErrors: false onFileChanged: reload() @@ -97,7 +97,7 @@ Item { FileView { id: clientsFile - path: root.home + "/.local/state/omarchy/agent-local/clients.json" + path: Startup.ready ? root.home + "/.local/state/omarchy/agent-local/clients.json" : "" watchChanges: true printErrors: false onFileChanged: reload() @@ -452,9 +452,11 @@ Item { else limitsRetry.stop() } - Component.onCompleted: { - rescanAgents() - if (syncConfigured()) scheduleSync() + AfterStartup { + onTriggered: { + root.rescanAgents() + if (root.syncConfigured()) root.scheduleSync() + } } // -------------------------------------------------------------- refresh @@ -484,7 +486,7 @@ Item { Timer { interval: root.nearLimit ? Math.min(180, root.refreshIntervalSec) * 1000 : root.refreshIntervalSec * 1000 - running: true + running: Startup.ready repeat: true triggeredOnStart: true onTriggered: root.runUpdate(root.nearLimit ? "limits" : "normal") @@ -660,7 +662,7 @@ Item { FileView { id: orderFile - path: root.orderPath + path: Startup.ready ? root.orderPath : "" watchChanges: true atomicWrites: true printErrors: false @@ -840,7 +842,7 @@ Item { FileView { id: syncSnapshotFile - path: root.syncSnapshotPath + path: Startup.ready ? root.syncSnapshotPath : "" watchChanges: false atomicWrites: true printErrors: false @@ -848,7 +850,7 @@ Item { FileView { id: hostnameFile - path: "/etc/hostname" + path: Startup.ready ? "/etc/hostname" : "" watchChanges: false printErrors: false onLoaded: root.detectedHostname = String(text() || "").trim() @@ -881,6 +883,7 @@ Item { } function scheduleSync() { + if (!Startup.ready) return if (!syncConfigured()) return syncDebounce.restart() } diff --git a/desktop/shell/shell/plugins/agents/Panel.qml b/desktop/shell/shell/plugins/agents/Panel.qml index 67b1a842..50ae3044 100644 --- a/desktop/shell/shell/plugins/agents/Panel.qml +++ b/desktop/shell/shell/plugins/agents/Panel.qml @@ -1565,7 +1565,7 @@ Panel { } } - KeyboardPanel { + LazyKeyboardPanel { id: panel anchorItem: button owner: root diff --git a/desktop/shell/shell/plugins/background/Background.qml b/desktop/shell/shell/plugins/background/Background.qml index 19765990..fd44bb7b 100644 --- a/desktop/shell/shell/plugins/background/Background.qml +++ b/desktop/shell/shell/plugins/background/Background.qml @@ -40,7 +40,6 @@ Item { property var sizeQueue: [] property bool finishingTransition: false property int backgroundVersion: 0 - property int reloadVersion: 0 property int revealStartedVersion: -1 property int pendingThemeVersion: -1 property string pendingColorsRaw: "" @@ -98,7 +97,7 @@ Item { } function setBackground(path, instant) { - if (instant) reloadVersion += 1 + if (instant) Wallpaper.revision++ transitionBackground("", path, path, instant, instant) } @@ -131,11 +130,12 @@ Item { // Video frames are not fed through the image-only reveal stack. Switching // instantly also avoids decoding two full videos during a transition. - if (instant || Quickshell.env("QT_QUICK_BACKEND") === "software" || !displayedBackground || isVideo(path) || isVideo(displayedBackground)) { + if (instant || Lite.enabled || Quickshell.env("QT_QUICK_BACKEND") === "software" || !displayedBackground || isVideo(path) || isVideo(displayedBackground)) { oldBackground = "" incomingBackground = "" preparedBackground = "" displayedBackground = finalPath + pruneNativeSizes() revealProgress = 1 return } @@ -220,6 +220,7 @@ Item { function prepareBackground(path) { path = String(path || "").trim() // Only a still that is not already on screen is worth decoding ahead. + if (Lite.enabled || Quickshell.env("QT_QUICK_BACKEND") === "software") return if (!path || isVideo(path) || path === lastTransitionPath || path === displayedBackground) return requestNativeSize(path) preparedBackground = path @@ -285,6 +286,7 @@ Item { // 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.pruneNativeSizes() root.sizeQueue = root.sizeQueue.filter(function(queued) { return queued !== sizeProbe.path }) root.probeNextSize() } @@ -391,7 +393,12 @@ Item { } } - Component.onCompleted: refreshBackground() + Component.onCompleted: { + if (Quickshell.env("OMARCHY_START_LOCKED") !== "1") refreshBackground() + } + AfterStartup { + onTriggered: if (Quickshell.env("OMARCHY_START_LOCKED") === "1" && !root.currentBackground) root.refreshBackground() + } Variants { id: backgrounds @@ -450,26 +457,15 @@ Item { // 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 - // On a tablet, swapping width/height must not clear and asynchronously - // decode the wallpaper again. Keep one orientation-independent decode. - // A high-water mark also ignores intermediate geometry during rotation. - readonly property bool tabletRotation: Quickshell.env("OMARCHY_TOUCH_MODE") === "1" - readonly property int requestedDecodeEdge: sized ? Math.ceil(Math.max(width, height) * screen.devicePixelRatio) : 0 - property int stableDecodeEdge: 0 - onRequestedDecodeEdgeChanged: { - if (requestedDecodeEdge > stableDecodeEdge) stableDecodeEdge = requestedDecodeEdge - } - readonly property int decodeWidth: sized ? (tabletRotation ? Math.max(stableDecodeEdge, requestedDecodeEdge) : Math.ceil(width * screen.devicePixelRatio)) : 0 - readonly property int decodeHeight: sized ? (tabletRotation ? Math.max(stableDecodeEdge, requestedDecodeEdge) : Math.ceil(height * screen.devicePixelRatio)) : 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] // ImageMagick metadata is optional: missing/late probes must never // prevent Qt's own decoder from drawing a wallpaper. - if (native === undefined) return Qt.size(decodeWidth, decodeHeight) - if (native.width > 0 && (native.width < decodeWidth || native.height < decodeHeight)) return Qt.size(native.width, native.height) - return Qt.size(decodeWidth, decodeHeight) + return Wallpaper.decodeSize(native, decodeWidth, decodeHeight) } function maybeStartReveal() { @@ -491,7 +487,7 @@ Item { id: base anchors.fill: parent path: root.displayedBackground - version: root.reloadVersion + version: Wallpaper.revision cached: true constrainDecode: true decodeSize: panel.decodeSize(root.displayedBackground) @@ -553,7 +549,7 @@ Item { id: revealMask anchors.fill: parent visible: false - layer.enabled: true + layer.enabled: !Lite.enabled readonly property real slant: -0.18 readonly property real centerTop: width / 2 - slant * height / 2 @@ -593,7 +589,7 @@ Item { // under it while a video plays. A clear layer above the video and below // every window keeps the desktop's double-clicks working meanwhile. Variants { - model: Quickshell.screens + model: root.suspended ? Quickshell.screens : [] PanelWindow { required property var modelData diff --git a/desktop/shell/shell/plugins/bar/Bar.qml b/desktop/shell/shell/plugins/bar/Bar.qml index 5e2ecfef..6f4e5662 100644 --- a/desktop/shell/shell/plugins/bar/Bar.qml +++ b/desktop/shell/shell/plugins/bar/Bar.qml @@ -116,6 +116,7 @@ Item { property string pendingTooltipText: "" property bool tooltipShown: false property int tooltipRequest: 0 + property bool screenRecording: false property var activePopout: null // Where the open panel's card stands, and in which section of the bar, so // a panel taking over in the same section can start its card from there. @@ -812,8 +813,8 @@ Item { // A bar going clear waits for its text color before dropping its // background, so a glassy one stays glassy until then rather than // flashing opaque. Once clear, transparent wins over a stale glassy. - if (look !== "none") glassy = look === "glassy" - if (look !== glassSyncedLook) { + if (look !== "none") glassy = !Lite.enabled && look === "glassy" + if (ShellFacts.hypr && !Lite.enabled && look !== glassSyncedLook) { glassSyncedLook = look Util.execDetached("omarchy-bar sync-glass") } @@ -1214,7 +1215,7 @@ Item { // whole room in 120ms. // Armed for removal, there is no target: every place gives its room up. function fadeDragRoom(seconds) { - var duration = Style.duration(120) + var duration = Style.reduceMotion ? 0 : 120 var step = duration > 0 ? seconds * 1000 / duration : 1 var target = barDragRemoveArmed ? "" : dragShareKey(barDragRoom) barDragShares = BarModel.fadeShares(barDragShares, target, step) @@ -1524,6 +1525,7 @@ Item { function refreshTransparentForeground() { if (!requestedTransparent || transparentForegroundProc.running) return + if (!ShellFacts.hasReader("omarchy-bar-text-color")) return transparentForegroundProc.command = [ "omarchy-bar-text-color", root.position, @@ -1534,6 +1536,10 @@ Item { transparentForegroundProc.running = true } + Connections { + target: ShellFacts + function onUpdated() { root.scheduleTransparentForegroundRefresh() } + } onRequestedTransparentChanged: scheduleTransparentForegroundRefresh() onPositionChanged: scheduleTransparentForegroundRefresh() onThemeForegroundChanged: scheduleTransparentForegroundRefresh() @@ -1644,19 +1650,17 @@ Item { // Presence of the `bar-off` flag = bar hidden. Watching the parent toggles // directory because FileView can't observe a file that doesn't exist yet, // and the flag is created/removed by `omarchy-toggle-bar`. - Process { - id: barHiddenProbe - running: true - command: ["bash", "-c", "[[ -f $HOME/.local/state/omarchy/toggles/bar-off ]] && echo yes || echo no"] - stdout: SplitParser { onRead: function(line) { root.barHidden = String(line).trim() === "yes" } } - } FileView { - path: root.home + "/.local/state/omarchy/toggles" + id: barHiddenFlag watchChanges: true + onFileChanged: reload() + path: root.home + "/.local/state/omarchy/toggles/bar-off" printErrors: false - onFileChanged: barHiddenProbe.running = true + onLoaded: root.barHidden = true + onLoadFailed: root.barHidden = false } + // The directory watch can permanently stop delivering events after flag // changes land in quick succession, stranding the bar off screen until the // shell restarts. `omarchy-toggle-bar` nudges this after flipping the flag @@ -1668,7 +1672,7 @@ Item { // directory watch after the flag flipped, so its answer is current, and // killing it here can swallow the result entirely. function syncHidden(): void { - barHiddenProbe.running = true + barHiddenFlag.reload() } } @@ -1694,7 +1698,7 @@ Item { } Variants { - model: Quickshell.screens + model: root.barDragSource || root.barPoof ? Quickshell.screens : [] delegate: Component { DragGhostPanel { @@ -1707,7 +1711,7 @@ Item { } Variants { - model: Quickshell.screens + model: root.barMoveActive ? Quickshell.screens : [] delegate: Component { BarMoveGhostPanel { @@ -1901,10 +1905,14 @@ Item { } } - PopupWindow { + OnDemandLoader { + id: tooltipLoader + requested: root.tooltipShown && root.tooltipTarget !== null && root.tooltipText !== "" && root.targetBelongsToWindow(root.tooltipTarget, barWindow) + sourceComponent: barWindow.tooltipComponent + } + property Component tooltipComponent: PopupWindow { id: tooltipWindow - - visible: root.tooltipShown && root.tooltipTarget !== null && root.tooltipText !== "" && root.targetBelongsToWindow(root.tooltipTarget, barWindow) + visible: tooltipLoader.requested color: "transparent" implicitWidth: Math.ceil(tooltipBubble.implicitWidth) implicitHeight: Math.ceil(tooltipBubble.implicitHeight) @@ -2207,7 +2215,7 @@ Item { // Built with the ghost's surface rather than at the release, which // would cost the poof its first frames while the effect sets up. // Until the poof plays the cloud holds nothing to draw. - layer.enabled: ghostWindow.visible + layer.enabled: !Lite.enabled && ghostWindow.visible layer.effect: MultiEffect { blurEnabled: true blur: 0.6 @@ -3288,7 +3296,7 @@ Item { Timer { interval: Math.max(1, Number(customRoot.setting("interval", 5))) * 1000 - running: String(customRoot.setting("exec", "")) !== "" + running: Startup.ready && String(customRoot.setting("exec", "")) !== "" repeat: true triggeredOnStart: true onTriggered: root.runProcess(customProc) diff --git a/desktop/shell/shell/plugins/bar/indicators/PasswordlessSudo.qml b/desktop/shell/shell/plugins/bar/indicators/PasswordlessSudo.qml index 6639aa51..fb19c2da 100644 --- a/desktop/shell/shell/plugins/bar/indicators/PasswordlessSudo.qml +++ b/desktop/shell/shell/plugins/bar/indicators/PasswordlessSudo.qml @@ -18,7 +18,12 @@ BarIndicator { useActiveColor: true activeColor: Commons.Color.urgent + Connections { + target: ShellFacts + function onUpdated() { root.refresh() } + } function refresh() { + if (!ShellFacts.hasReader("omarchy-sudo-passwordless")) return if (!root.bar) return if (statusProc.running) { root.refreshPending = true @@ -28,8 +33,8 @@ BarIndicator { statusProc.running = true } - onBarChanged: refresh() - Component.onCompleted: refresh() + onBarChanged: if (Startup.ready) refresh() + AfterStartup { onTriggered: root.refresh() } // No polling: each probe is a hardened script plus sudo calls that can log. // omarchy-sudo-passwordless refreshes omarchy.indicators on enable, disable diff --git a/desktop/shell/shell/plugins/bar/indicators/Reminder.qml b/desktop/shell/shell/plugins/bar/indicators/Reminder.qml index 3441edbe..4254fd04 100644 --- a/desktop/shell/shell/plugins/bar/indicators/Reminder.qml +++ b/desktop/shell/shell/plugins/bar/indicators/Reminder.qml @@ -1,4 +1,5 @@ import QtQuick +import qs.Commons import Quickshell import Quickshell.Io import qs.Ui @@ -15,7 +16,12 @@ BarIndicator { activeTooltipText: tooltip inactiveTooltipText: tooltip + Connections { + target: ShellFacts + function onUpdated() { root.refresh() } + } function refresh() { + if (!ShellFacts.hasReader("omarchy-reminder")) return if (!jsonProc.running) jsonProc.running = true } @@ -29,7 +35,7 @@ BarIndicator { tooltip = String(data.tooltip || "") } - Component.onCompleted: refresh() + AfterStartup { onTriggered: root.refresh() } Connections { target: root.indicatorHost diff --git a/desktop/shell/shell/plugins/bar/indicators/ScreenRecording.qml b/desktop/shell/shell/plugins/bar/indicators/ScreenRecording.qml index 9e93047e..f6a1f64f 100644 --- a/desktop/shell/shell/plugins/bar/indicators/ScreenRecording.qml +++ b/desktop/shell/shell/plugins/bar/indicators/ScreenRecording.qml @@ -68,14 +68,19 @@ BarIndicator { activeTooltipText: I18n.t("bar.stopRecording") inactiveTooltipText: I18n.t("bar.screenRecording") + Connections { + target: ShellFacts + function onUpdated() { root.refresh() } + } function refresh() { + if (!ShellFacts.hasReader("omarchy-capture-screenrecording")) return if (!root.bar || statusProc.running) return statusProc.command = ["omarchy-capture-screenrecording", "--status"] statusProc.running = true } - onBarChanged: refresh() - Component.onCompleted: refresh() + onBarChanged: if (Startup.ready) refresh() + AfterStartup { onTriggered: root.refresh() } Connections { target: root.indicatorHost @@ -87,6 +92,7 @@ BarIndicator { id: statusProc onExited: function(exitCode) { root.recording = exitCode === 0 + if (root.bar && "screenRecording" in root.bar) root.bar.screenRecording = root.recording } } diff --git a/desktop/shell/shell/plugins/bar/widgets/Indicators.qml b/desktop/shell/shell/plugins/bar/widgets/Indicators.qml index 043bb3b1..4d98ce3e 100644 --- a/desktop/shell/shell/plugins/bar/widgets/Indicators.qml +++ b/desktop/shell/shell/plugins/bar/widgets/Indicators.qml @@ -227,8 +227,8 @@ BarWidget { Component.onCompleted: { syncInactiveIndicatorModel() - root.refreshRequested() } + AfterStartup { onTriggered: root.refreshRequested() } // Instantiating both orientation trees and toggling `visible` doubled every // indicator per bar (and every process an indicator spawns, once per diff --git a/desktop/shell/shell/plugins/bar/widgets/KeyboardLayout.qml b/desktop/shell/shell/plugins/bar/widgets/KeyboardLayout.qml index 48f3c651..f5e3b0e7 100644 --- a/desktop/shell/shell/plugins/bar/widgets/KeyboardLayout.qml +++ b/desktop/shell/shell/plugins/bar/widgets/KeyboardLayout.qml @@ -56,6 +56,7 @@ BarWidget { property bool refreshPending: false function refresh() { + if (!ShellFacts.hypr) return if (queryProc.running) { refreshPending = true return @@ -109,7 +110,7 @@ BarWidget { refreshTimer.restart() } - Component.onCompleted: refresh() + AfterStartup { onTriggered: root.refresh() } Connections { target: Hyprland diff --git a/desktop/shell/shell/plugins/bar/widgets/SystemUpdate.qml b/desktop/shell/shell/plugins/bar/widgets/SystemUpdate.qml index ed88af74..13e74b32 100644 --- a/desktop/shell/shell/plugins/bar/widgets/SystemUpdate.qml +++ b/desktop/shell/shell/plugins/bar/widgets/SystemUpdate.qml @@ -14,7 +14,12 @@ BarWidget { // during a check that started offline) runs once that check exits. property bool refreshPending: false + Connections { + target: ShellFacts + function onUpdated() { root.refresh() } + } function refresh() { + if (!ShellFacts.hasReader("omarchy-update-available")) return if (updateProc.running) refreshPending = true else updateProc.running = true } @@ -56,11 +61,11 @@ BarWidget { // Recheck as soon as NetworkManager reports full internet connectivity, so a // check that ran before Wi-Fi came up doesn't hide the icon for six hours. readonly property bool online: Networking.connectivity === NetworkConnectivity.Full - onOnlineChanged: if (online) root.refresh() + onOnlineChanged: if (online && Startup.ready) root.refresh() Timer { interval: 21600000 - running: true + running: Startup.ready repeat: true triggeredOnStart: true onTriggered: root.refresh() diff --git a/desktop/shell/shell/plugins/bar/widgets/Tray.qml b/desktop/shell/shell/plugins/bar/widgets/Tray.qml index c7ec6bef..7eb1b97d 100644 --- a/desktop/shell/shell/plugins/bar/widgets/Tray.qml +++ b/desktop/shell/shell/plugins/bar/widgets/Tray.qml @@ -107,7 +107,7 @@ BarWidget { // Flickable keeps its offset across a model swap whenever the new content // is still tall enough to hold it, so a menu dismissed while scrolled // would otherwise reopen part-way down with its first entries off screen. - trayMenuFlick.contentY = 0 + if (trayMenuPopupLoader.item) trayMenuPopupLoader.item.resetScroll() // Clear the reactive stack before tearing anything down, so no binding can // read a partially-destroyed opener while this runs. Then destroy deepest // first: an inner opener's menu entry is owned by its parent's children @@ -329,7 +329,7 @@ BarWidget { x: root.fixedAtStart ? root.sectionExtent : 0 anchors.verticalCenter: parent.verticalCenter spacing: root.trayItemGap - layer.enabled: true + layer.enabled: !Lite.enabled Repeater { model: root.drawerItems @@ -420,7 +420,7 @@ BarWidget { y: root.fixedAtStart ? root.sectionExtent : 0 anchors.horizontalCenter: parent.horizontalCenter spacing: root.trayItemGap - layer.enabled: true + layer.enabled: !Lite.enabled Repeater { model: root.drawerItems @@ -454,12 +454,13 @@ BarWidget { } } - PopupCard { + OnDemandLoader { id: managePopupLoader; requested: root.managePopupOpen; sourceComponent: root.managePopupComponent } + property Component managePopupComponent: PopupCard { id: managePopup anchorItem: root owner: root bar: root.bar - open: root.managePopupOpen + open: !!managePopupLoader.item && root.managePopupOpen contentWidth: managePopup.fittedContentWidth(Style.space(300)) contentHeight: managePopup.fittedContentHeight(manageColumn.implicitHeight) @@ -580,12 +581,14 @@ BarWidget { menu: root.activeTrayItem ? root.activeTrayItem.menu : null } - PopupCard { + OnDemandLoader { id: trayMenuPopupLoader; requested: root.trayMenuOpen; sourceComponent: root.trayMenuPopupComponent } + property Component trayMenuPopupComponent: PopupCard { id: trayMenuPopup + function resetScroll() { trayMenuFlick.contentY = 0 } anchorItem: root.activeTrayAnchor || root owner: root bar: root.bar - open: root.trayMenuOpen + open: !!trayMenuPopupLoader.item && root.trayMenuOpen // The card fades out over 140ms (visible stays true for that whole time -- // see PopupCard's own visible: open || card.opacity > 0), so resetting on // "open" would swap a live submenu for the root menu mid-fade: a visible @@ -835,7 +838,7 @@ BarWidget { component TrayIcon: Item { id: trayIconRoot required property var icon - readonly property bool symbolic: root.iconIsSymbolic(icon) + readonly property bool symbolic: !Lite.enabled && root.iconIsSymbolic(icon) Image { id: trayIconImage diff --git a/desktop/shell/shell/plugins/bar/widgets/Workspaces.qml b/desktop/shell/shell/plugins/bar/widgets/Workspaces.qml index 0166c429..244de116 100644 --- a/desktop/shell/shell/plugins/bar/widgets/Workspaces.qml +++ b/desktop/shell/shell/plugins/bar/widgets/Workspaces.qml @@ -156,6 +156,7 @@ BarWidget { } function readMode() { + if (!ShellFacts.hypr) return if (modeProc.running) { root.modeStale = true return @@ -185,8 +186,8 @@ BarWidget { root.bar.run(command) } - Component.onCompleted: refresh() - onMonitorChanged: root.showActiveMode() + AfterStartup { onTriggered: root.refresh() } + onMonitorChanged: if (Startup.ready) root.showActiveMode() Connections { target: root.monitor diff --git a/desktop/shell/shell/plugins/clipboard/Clipboard.qml b/desktop/shell/shell/plugins/clipboard/Clipboard.qml index bb2b4c0f..e2166131 100644 --- a/desktop/shell/shell/plugins/clipboard/Clipboard.qml +++ b/desktop/shell/shell/plugins/clipboard/Clipboard.qml @@ -35,8 +35,8 @@ Item { property int contentMargin: Style.spacing.panelPadding property int headerHeight: Math.max(Style.space(34), Style.font.title + Style.spacing.controlPaddingY * 2) property int contentSpacing: Style.spacing.md - property int cardWidth: Math.min(Style.space(875), panel.width - Style.gapsOut * 2) - property int cardHeight: Math.min(Style.space(600), panel.height - Style.gapsOut * 2) + property int cardWidth: !panel ? 0 : Math.min(Style.space(875), panel.width - Style.gapsOut * 2) + property int cardHeight: !panel ? 0 : Math.min(Style.space(600), panel.height - Style.gapsOut * 2) property int rowHeight: Math.max(Style.space(50), Style.font.body + Style.font.caption + Style.spacing.rowPaddingX * 2) property int historyLimit: 500 @@ -246,7 +246,7 @@ Item { Quickshell.execDetached([root.omarchyPath + "/bin/omarchy-clipboard-open", "--history-index", String(row.historyIndex)]) } - Component.onCompleted: initProc.running = true + Component.onCompleted: Qt.callLater(function() { initProc.running = true }) ListModel { id: displayModel } @@ -319,9 +319,19 @@ Item { } } - OverlayWindow { + readonly property var panel: windowLoader.item + readonly property var card: panel ? panel.card : null + readonly property var resultList: panel ? panel.resultList : null + readonly property var keyCatcher: panel ? panel.keyCatcher : null + readonly property var clearConfirm: panel ? panel.clearConfirm : null + OnDemandLoader { id: windowLoader; requested: root.opened; sourceComponent: windowComponent } + property Component windowComponent: OverlayWindow { id: panel - shown: root.opened + property alias card: card + property alias resultList: resultList + property alias keyCatcher: keyCatcher + property alias clearConfirm: clearConfirm + shown: !!windowLoader.item && root.opened WlrLayershell.namespace: "omarchy-clipboard" Rectangle { diff --git a/desktop/shell/shell/plugins/dock/AppGrid.qml b/desktop/shell/shell/plugins/dock/AppGrid.qml index 6df1c278..489378a0 100644 --- a/desktop/shell/shell/plugins/dock/AppGrid.qml +++ b/desktop/shell/shell/plugins/dock/AppGrid.qml @@ -27,12 +27,13 @@ Item { property point menuPoint property string filterText: "" property int selectedIndex: 0 - property var apps: [] + readonly property var apps: !appLibrary ? [] : !filterText ? appLibrary.entries + : appLibrary.sortedEntries(filterText).map(function(row) { return row.entry }) + readonly property var layoutScreen: panel.targetScreen || panel.focusedScreen() readonly property int iconSize: Math.round(56 * Style.fontScale) readonly property int labelHeight: Math.ceil(labelMetrics.height) * 2 - // Orchard: no version under the selected app (upstream shows the package's). - readonly property bool showVersions: false + readonly property bool showVersions: !!appLibrary && appLibrary.showVersions readonly property int versionHeight: showVersions ? Style.spacing.xs + Math.ceil(versionMetrics.height) : 0 readonly property int cellGutter: Style.spacing.sm readonly property int cellPadding: Style.spacing.lg @@ -49,25 +50,15 @@ Item { // The card fits whole columns, and the grid sits centered in it so any // leftover width splits evenly on both sides. - readonly property int cardWidth: Math.min(panel.width - screenMargin * 2, maxColumns * cellWidth + inset * 2) + readonly property int cardWidth: Math.min((layoutScreen ? layoutScreen.width : 0) - screenMargin * 2, maxColumns * cellWidth + inset * 2) readonly property int columns: Math.max(1, Math.floor((cardWidth - inset * 2) / cellWidth)) readonly property int gridWidth: columns * cellWidth - readonly property int cardHeight: Math.min(panel.height - screenMargin * 2, inset * 2 + headerHeight + headerSpacing + visibleRows * cellHeight) + readonly property int cardHeight: Math.min((layoutScreen ? layoutScreen.height : 0) - screenMargin * 2, inset * 2 + headerHeight + headerSpacing + visibleRows * cellHeight) function open() { root.selectedIndex = 0 - if (root.appLibrary) { - root.appLibrary.refreshIcons() - if (root.showVersions) root.appLibrary.refreshVersions() - } - // The cells from last time are reused when nothing changed, so the grid - // opens with its icons already drawn. - if (root.appsStale || root.filterText !== "" || root.apps.length === 0) { - root.filterText = "" - root.rebuild() - } else { - grid.positionViewAtBeginning() - } + root.filterText = "" + grid.positionViewAtBeginning() root.opened = true Qt.callLater(function() { searchField.forceActiveFocus() }) } @@ -128,27 +119,13 @@ Item { else root.open() } - function rebuild() { - root.appsStale = false - var rows = root.appLibrary ? root.appLibrary.sortedEntries(root.filterText) : [] - root.apps = rows.map(function(row) { return row.entry }) - root.selectedIndex = Math.max(0, Math.min(root.selectedIndex, root.apps.length - 1)) - grid.positionViewAtBeginning() - } - onFilterTextChanged: if (searchField.text !== filterText) searchField.text = filterText - // Apps came or went while the grid is open: keep the user where they were. - function refresh() { - var position = grid.contentY - root.rebuild() - grid.forceLayout() - grid.contentY = Math.max(0, Math.min(position, grid.contentHeight - grid.height)) - } + onAppsChanged: selectedIndex = Math.max(0, Math.min(selectedIndex, apps.length - 1)) function setFilter(text) { root.filterText = text root.selectedIndex = 0 - root.rebuild() + grid.positionViewAtBeginning() } function select(delta) { @@ -177,16 +154,8 @@ Item { font.pixelSize: Style.font.caption } - // Apps installed or removed while the grid is closed are picked up when it - // next opens. - property bool appsStale: false - Connections { target: root.appLibrary - function onAppsChanged() { - if (root.opened) root.refresh() - else root.appsStale = true - } function onRemovalNeedsTerminal() { if (root.opened) root.close() } @@ -341,7 +310,7 @@ Item { GridView { id: grid anchors.fill: parent - model: root.apps + model: root.apps.length clip: true cellWidth: root.cellWidth cellHeight: root.cellHeight @@ -351,7 +320,7 @@ Item { id: cell required property int index - required property var modelData + readonly property var modelData: root.apps[index] || null readonly property bool selected: index === root.selectedIndex property point pressPoint // A press that wanders is a drag in the making, not a click. @@ -360,20 +329,17 @@ Item { width: root.cellWidth height: root.cellHeight - Image { + AppIconImage { id: icon anchors.horizontalCenter: parent.horizontalCenter y: root.cellPadding width: root.iconSize height: root.iconSize - sourceSize: Qt.size(root.iconSize * 2, root.iconSize * 2) - source: root.appLibrary ? root.appLibrary.iconSource(cell.modelData.icon) : "" - fillMode: Image.PreserveAspectFit + outputScale: root.layoutScreen ? root.layoutScreen.devicePixelRatio : 1 + source: cell.modelData && root.appLibrary ? root.appLibrary.rasterSource(cell.modelData.icon, pixelSize) : "" // Loaded with the cell, from Qt's image cache after the first // open, so icons do not pop in after the grid has appeared. asynchronous: false - smooth: true - mipmap: true } // The selection marks the app's name, not the whole cell. @@ -470,17 +436,14 @@ Item { } } // The dragged app's icon, under the pointer. - Image { + AppIconImage { visible: root.dragging && !!root.dragEntry x: root.dragPoint.x - width / 2 y: root.dragPoint.y - height / 2 width: root.iconSize height: root.iconSize - sourceSize: Qt.size(root.iconSize * 2, root.iconSize * 2) - source: root.dragEntry && root.appLibrary ? root.appLibrary.iconSource(root.dragEntry.icon) : "" - fillMode: Image.PreserveAspectFit - smooth: true - mipmap: true + outputScale: root.layoutScreen ? root.layoutScreen.devicePixelRatio : 1 + source: root.dragEntry && root.appLibrary ? root.appLibrary.rasterSource(root.dragEntry.icon, pixelSize) : "" } // Right-click on an app: open it, or keep it in the dock or take it out. diff --git a/desktop/shell/shell/plugins/dock/Dock.qml b/desktop/shell/shell/plugins/dock/Dock.qml index 4a955814..50267050 100644 --- a/desktop/shell/shell/plugins/dock/Dock.qml +++ b/desktop/shell/shell/plugins/dock/Dock.qml @@ -2,6 +2,7 @@ import QtQuick import Quickshell import Quickshell.Hyprland import Quickshell.Io +import qs.Ui import qs.Commons import "DockModel.js" as DockModel @@ -34,6 +35,7 @@ Item { // Entries that can claim a terminal app's window: those run in a terminal, // and those that hand the terminal an app id of their own. readonly property var terminalEntries: { + if (!Startup.ready) return [] var values = DesktopEntries.applications.values var out = [] for (var i = 0; i < values.length; i++) { @@ -54,6 +56,7 @@ Item { // A pinned app that is not installed has nothing to launch, so it is left // out until it is. Windows are matched to the desktop entry that claims them. readonly property var items: { + if (!Startup.ready) return [] var appsRevision = DesktopEntries.applications.values.length var pinned = (root.pendingPins || DockModel.pinnedIds(dockConfig, defaultDockConfig)).filter(function(id) { return !!DesktopEntries.byId(id) @@ -134,14 +137,19 @@ Item { var launch = root.launches[key] var item = root.itemsByKey[key] var windows = item ? item.windows.length : 0 - if (windows > launch.windows || now - launch.at > root.launchTimeout) changed = true + if (windows > launch.windows || now - launch.at >= root.launchTimeout) changed = true else next[key] = launch } if (changed) root.launches = next } Timer { - interval: 1000 + interval: { + var deadline = Infinity + for (var key in root.launches) + deadline = Math.min(deadline, root.launches[key].at + root.launchTimeout) + return isFinite(deadline) ? Math.max(1, deadline - Date.now()) : root.launchTimeout + } repeat: true running: Object.keys(root.launches).length > 0 onTriggered: root.settleLaunches() @@ -151,10 +159,23 @@ Item { return item ? DesktopEntries.byId(item.key) : null } - function iconFor(item) { + function iconName(item) { var entry = entryFor(item) - var icon = entry && entry.icon ? entry.icon : (item ? item.key : "") - return root.appLibrary ? root.appLibrary.iconSource(icon) : Quickshell.iconPath(icon, true) + return entry && entry.icon ? entry.icon : (item ? item.key : "") + } + + // Include pinned and running apps without a matching desktop entry in the + // background raster pass. A window count change keeps the same name list. + Binding { + target: root.appLibrary + when: !!root.appLibrary + property: "dockIconNames" + value: JSON.stringify(root.items.map(root.iconName).sort()) + } + + function iconFor(item, pixels) { + var icon = iconName(item) + return root.appLibrary ? root.appLibrary.rasterSource(icon, pixels) : Quickshell.iconPath(icon, true) } function launch(item) { @@ -221,7 +242,7 @@ Item { } function openApps() { - appGrid.open() + appGrid.load().open() } readonly property var pinnedKeys: root.pendingPins || DockModel.pinnedIds(root.dockConfig, root.defaultDockConfig) @@ -287,7 +308,7 @@ Item { } function readMode(workspaceId) { - if (!(workspaceId >= 1) || root.readModes[workspaceId]) return + if (!Startup.ready || !(workspaceId >= 1) || root.readModes[workspaceId]) return root.readModes[workspaceId] = true root.pendingModes.push(workspaceId) root.readNextMode() @@ -316,9 +337,9 @@ Item { } Component.onCompleted: { - refresh() syncItemModel() } + AfterStartup { onTriggered: root.refresh() } Process { id: modeProc @@ -360,9 +381,9 @@ Item { // The layout commands call this after changing a workspace's mode. function refresh(): void { root.refresh() } - function apps(): void { appGrid.toggle() } - function closeApps(): void { if (appGrid.opened) appGrid.close() } - function openApps(): void { if (!appGrid.opened) appGrid.open() } + function apps(): void { appGrid.load().toggle() } + function closeApps(): void { if (appGrid.item && appGrid.item.opened) appGrid.item.close() } + function openApps(): void { if (!appGrid.item || !appGrid.item.opened) appGrid.load().open() } } // An app dragged out of the app grid: the grid holds the pointer and @@ -408,9 +429,9 @@ Item { } } - AppGrid { + OnDemandLoader { id: appGrid - appLibrary: root.appLibrary - dock: root + keepAlive: true + sourceComponent: AppGrid { appLibrary: root.appLibrary; dock: root } } } diff --git a/desktop/shell/shell/plugins/dock/DockWindow.qml b/desktop/shell/shell/plugins/dock/DockWindow.qml index 66ad8cc3..005c60a8 100644 --- a/desktop/shell/shell/plugins/dock/DockWindow.qml +++ b/desktop/shell/shell/plugins/dock/DockWindow.qml @@ -496,7 +496,7 @@ PanelWindow { y: window.iconInset width: window.iconSize height: window.iconSize - source: window.dock && appSlot.modelData ? window.dock.iconFor(appSlot.modelData) : "" + source: window.dock && appSlot.modelData ? window.dock.iconFor(appSlot.modelData, Math.round(width * window.devicePixelRatio)) : "" opacity: appSlot.launching ? appSlot.pulse : 1 transform: Translate { x: window.vertical ? 0 : appSlot.displayedShift @@ -511,7 +511,7 @@ PanelWindow { // With animations off it holds still rather than spinning through // zero-length steps. SequentialAnimation { - running: appSlot.launching && !Style.reduceMotion + running: appSlot.launching && Style.animateLoops loops: Animation.Infinite onRunningChanged: if (!running) appSlot.pulse = 1 @@ -543,24 +543,16 @@ PanelWindow { } Component.onCompleted: current.source = appIcon.source - Image { + AppIconImage { id: previous anchors.fill: parent - sourceSize: current.sourceSize - fillMode: Image.PreserveAspectFit asynchronous: true - smooth: true - mipmap: true } - Image { + AppIconImage { id: current anchors.fill: parent - sourceSize: Qt.size(window.iconSize * 2, window.iconSize * 2) - fillMode: Image.PreserveAspectFit asynchronous: true - smooth: true - mipmap: true onStatusChanged: appIcon.reveal() } diff --git a/desktop/shell/shell/plugins/emojis/Emojis.qml b/desktop/shell/shell/plugins/emojis/Emojis.qml index dc8f0ef2..d055e7d7 100644 --- a/desktop/shell/shell/plugins/emojis/Emojis.qml +++ b/desktop/shell/shell/plugins/emojis/Emojis.qml @@ -36,8 +36,8 @@ Item { property int contentMargin: Style.spacing.panelPadding property int headerHeight: Math.max(Style.space(34), Style.font.title + Style.spacing.controlPaddingY * 2) property int contentSpacing: Style.spacing.md - property int cardWidth: Math.min(Style.space(400), panel.width - Style.gapsOut * 2) - property int cardHeight: Math.min(Style.space(500), panel.height - Style.gapsOut * 2) + property int cardWidth: !panel ? 0 : Math.min(Style.space(400), panel.width - Style.gapsOut * 2) + property int cardHeight: !panel ? 0 : Math.min(Style.space(500), panel.height - Style.gapsOut * 2) property int cellWidth: Math.max(Style.space(44), Style.font.display + Style.spacing.md) property int cellHeight: Math.max(Style.space(44), Style.font.display + Style.spacing.md) @@ -155,12 +155,28 @@ Item { ListModel { id: displayModel } FileView { - path: root.omarchyPath + "/shell/plugins/emojis/emojis.json" + path: windowLoader.active ? root.omarchyPath + "/shell/plugins/emojis/emojis.json" : "" + blockLoading: true onLoaded: root.loadEmojis(text()) } - OverlayWindow { + readonly property var panel: windowLoader.item + readonly property var keyCatcher: panel ? panel.keyCatcher : null + readonly property var resultGrid: panel ? panel.resultGrid : null + OnDemandLoader { + id: windowLoader + requested: root.opened + sourceComponent: root.windowComponent + onActiveChanged: if (!active) { + root.emojis = [] + root.filteredEmojis = [] + displayModel.clear() + } + } + property Component windowComponent: OverlayWindow { id: panel - shown: root.opened + property alias keyCatcher: keyCatcher + property alias resultGrid: resultGrid + shown: !!windowLoader.item && root.opened WlrLayershell.namespace: "omarchy-emojis" Rectangle { diff --git a/desktop/shell/shell/plugins/flash/Flash.qml b/desktop/shell/shell/plugins/flash/Flash.qml index 4e1610cc..50b2e350 100644 --- a/desktop/shell/shell/plugins/flash/Flash.qml +++ b/desktop/shell/shell/plugins/flash/Flash.qml @@ -14,10 +14,7 @@ Item { property bool opened: false function flash() { - flashAnimation.stop() - white.opacity = 0 - opened = true - flashAnimation.start() + flashWindow.load().play() } ShellIpc { @@ -26,8 +23,15 @@ Item { function ping(): string { return "ok" } } - OverlayWindow { + OnDemandLoader { id: flashWindow; requested: root.opened; sourceComponent: windowComponent } + property Component windowComponent: OverlayWindow { id: panel + function play() { + flashAnimation.stop() + white.opacity = 0 + root.opened = true + flashAnimation.start() + } shown: root.opened shownKeyboardFocus: WlrKeyboardFocus.None WlrLayershell.namespace: "omarchy-flash" @@ -40,13 +44,13 @@ Item { color: "white" opacity: 0 } - } - // Full white at once, then a gentle fade. - SequentialAnimation { - id: flashAnimation - PropertyAction { target: white; property: "opacity"; value: 0.95 } - NumberAnimation { target: white; property: "opacity"; to: 0; duration: 500; easing.type: Easing.InOutSine } - onFinished: root.opened = false + // Full white at once, then a gentle fade. + SequentialAnimation { + id: flashAnimation + PropertyAction { target: white; property: "opacity"; value: 0.95 } + NumberAnimation { target: white; property: "opacity"; to: 0; duration: Lite.duration(500); easing.type: Easing.InOutSine } + onFinished: root.opened = false + } } } diff --git a/desktop/shell/shell/plugins/image-picker/ImagePicker.qml b/desktop/shell/shell/plugins/image-picker/ImagePicker.qml index a77ad983..ff4b3869 100644 --- a/desktop/shell/shell/plugins/image-picker/ImagePicker.qml +++ b/desktop/shell/shell/plugins/image-picker/ImagePicker.qml @@ -35,8 +35,7 @@ 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. + // Keep the rows after the first theme request. Later opens refresh them behind the picker. property string themeRows: "" property bool themeMode: false property bool themeOpenPending: false @@ -61,19 +60,21 @@ Item { // Orchard: on a phone-wide screen the selected card takes what is left // after 16-point margins and a slim slice of each neighbour, so it shows // whole and the carousel still reads as one. - readonly property bool narrow: panel.width > 0 && panel.width < 600 + readonly property int windowWidth: panel ? panel.width : 0 + readonly property int windowHeight: panel ? panel.height : 0 + readonly property bool narrow: windowWidth > 0 && windowWidth < 600 readonly property int narrowMargin: 16 property int expandedWidth: narrow - ? Math.max(160, panel.width - 2 * narrowMargin - 2 * (sliceWidth + sliceSpacing)) - : Math.min(768, Math.max(320, Math.floor((panel.width - 32) * 0.60))) - property int expandedHeight: Math.min(475, Math.round(expandedWidth * 475 / 768), Math.max(200, panel.height - 64 - bottomChromeHeight)) + ? Math.max(160, windowWidth - 2 * narrowMargin - 2 * (sliceWidth + sliceSpacing)) + : Math.min(768, Math.max(320, Math.floor((windowWidth - 32) * 0.60))) + property int expandedHeight: Math.min(475, Math.round(expandedWidth * 475 / 768), Math.max(200, windowHeight - 64 - bottomChromeHeight)) property int sliceWidth: narrow ? 44 : Math.min(108, Math.max(72, Math.round(expandedWidth * 108 / 768))) property int sliceHeight: Math.min(432, Math.round(expandedHeight * 432 / 475)) property int sliceSpacing: -Math.round(sliceWidth * 0.28) property int skewOffset: 28 property int bottomChromeHeight: showLabels ? (filterable ? 104 : 74) : (filterable ? 60 : 30) // Render only what fits on this display, plus one prefetch slice per side. - readonly property int previewRadius: Math.max(1, Math.min(16, Math.ceil((panel.width - expandedWidth) / (2 * (sliceWidth + sliceSpacing))) + 1)) + readonly property int previewRadius: Math.max(1, Math.min(16, Math.ceil((windowWidth - expandedWidth) / (2 * (sliceWidth + sliceSpacing))) + 1)) onPreviewRadiusChanged: updateVisibleItems() onOpenedChanged: if (!opened) { layoutSettled = false; renderedFrames = 0; deleteConfirmOpen = false; pendingDeleteTheme = ""; deleteSelectionPath = ""; awaitingDeleteRefresh = false } @@ -90,7 +91,7 @@ Item { } function focusPicker() { - if (root.opened && root.imagesLoaded && root.layoutSettled) + if (carousel && root.opened && root.imagesLoaded && root.layoutSettled) carousel.forceActiveFocus() } @@ -105,7 +106,7 @@ Item { // complete frame instead of flashing its images in as each asynchronous // decode and layer upload finishes. function allPreviewsSettled() { - if (!opened || !imagesLoaded || layoutSettled || imageArray.length === 0 || imageCards.count === 0) return false + if (!opened || !imagesLoaded || layoutSettled || imageArray.length === 0 || !imageCards || imageCards.count === 0) return false for (var i = 0; i < imageCards.count; i++) { var item = imageCards.itemAt(i) if (!item || !item.previewSettled) return false @@ -367,6 +368,7 @@ Item { } function enableNeighborsWhenReady() { + if (!imageCards) return for (var i = 0; i < imageCards.count; i++) { var item = imageCards.itemAt(i) if (item && item.selected && item.previewReady) neighborImagesEnabled = true @@ -389,7 +391,7 @@ Item { if (themeRows) { openThemeRows() } else { - // First open before the startup refresh has landed. + // A cold picker opens as soon as the theme listing arrives. themeOpenPending = true } refreshThemeRows() @@ -530,12 +532,6 @@ Item { } } - Component.onCompleted: { - refreshThemeRows() - refreshExtraThemes() - refreshStockThemes() - } - function startImageScan(serial, dirs) { if (loadImagesProc.running) { loadImagesProc.queuedSerial = serial @@ -645,9 +641,17 @@ Item { onExited: root.releaseNextDoneFile() } - OverlayWindow { + readonly property var panel: windowLoader.item + readonly property var carousel: panel ? panel.carousel : null + readonly property var imageCards: panel ? panel.imageCards : null + readonly property var deleteConfirm: panel ? panel.deleteConfirm : null + OnDemandLoader { id: windowLoader; requested: root.opened; sourceComponent: root.windowComponent } + property Component windowComponent: OverlayWindow { id: panel - shown: root.opened + property alias carousel: carousel + property alias imageCards: imageCards + property alias deleteConfirm: deleteConfirm + shown: !!windowLoader.item && root.opened shownKeyboardFocus: root.imagesLoaded ? WlrKeyboardFocus.Exclusive : WlrKeyboardFocus.None WlrLayershell.namespace: "omarchy-image-selector" @@ -775,7 +779,7 @@ Item { y: selected ? 0 : (root.expandedHeight - root.sliceHeight) / 2 z: selected ? 100 : 50 - Math.min(Math.abs(relativeIndex), 40) - readonly property real skAbs: Math.abs(root.skewOffset) + readonly property real skAbs: Lite.enabled ? 0 : Math.abs(root.skewOffset) readonly property real topLeft: root.skewOffset >= 0 ? skAbs : 0 readonly property real topRight: root.skewOffset >= 0 ? width : width - skAbs readonly property real bottomRight: root.skewOffset >= 0 ? width - skAbs : width @@ -785,7 +789,7 @@ Item { id: maskShape anchors.fill: parent visible: false - layer.enabled: true + layer.enabled: !Lite.enabled Shape { anchors.fill: parent @@ -805,7 +809,8 @@ Item { Item { anchors.fill: parent - layer.enabled: true + layer.enabled: !Lite.enabled + clip: Lite.enabled layer.smooth: true layer.effect: MultiEffect { maskEnabled: true diff --git a/desktop/shell/shell/plugins/lock/LockView.qml b/desktop/shell/shell/plugins/lock/LockView.qml index 52b8a59d..b14654d5 100644 --- a/desktop/shell/shell/plugins/lock/LockView.qml +++ b/desktop/shell/shell/plugins/lock/LockView.qml @@ -11,6 +11,7 @@ Item { property string backgroundPath: "" property string videoPosterPath: "" + property var nativeWallpaperSize: null property int backgroundVersion: 0 property bool fingerprintConfigured: false property bool fingerprintUnavailable: false @@ -72,7 +73,7 @@ Item { // A soft shadow in the theme's background under the clock, the slots and // the failure: readable on any wallpaper without darkening all of it. The // GPU draws it; software rendering goes without. - readonly property bool gpu: Quickshell.env("QT_QUICK_BACKEND") !== "software" + readonly property bool drawShadows: !Lite.enabled && Quickshell.env("QT_QUICK_BACKEND") !== "software" // A soft dark shadow (the theme background at 80 %, about 8 px of blur, // 1 px down): text stays readable over busy parts of the wallpaper. component Shade: MultiEffect { @@ -188,7 +189,9 @@ Item { // lock, so the first frame has the wallpaper. cached: true constrainDecode: true - decodeSize: Qt.size(width, height) + asynchronous: false + decodeSize: Wallpaper.decodeSize(root.nativeWallpaperSize, Math.ceil(width * Screen.devicePixelRatio), + Math.ceil(height * Screen.devicePixelRatio)) } // One even scrim over the whole wallpaper: the theme's lock.scrim (its @@ -248,7 +251,7 @@ Item { // ------------------------------------------------------ clock Column { id: clockBlock - layer.enabled: root.gpu + layer.enabled: root.drawShadows layer.effect: Shade {} spacing: Style.space(6) // x, not an anchor: an anchor let go on rotation keeps its place. @@ -414,7 +417,7 @@ Item { Grid { id: keypad visible: root.touchPin - layer.enabled: root.gpu + layer.enabled: root.drawShadows layer.effect: Shade {} columns: 3 rowSpacing: root.pt("keyGap") @@ -476,7 +479,7 @@ Item { visible: root.touchPin width: parent.width height: root.pt("slotRow") - layer.enabled: root.gpu + layer.enabled: root.drawShadows layer.effect: Shade {} Row { anchors.horizontalCenter: parent.horizontalCenter @@ -506,7 +509,7 @@ Item { Text { id: failureLine objectName: "lockFailure" - layer.enabled: root.gpu && text.length > 0 + layer.enabled: root.drawShadows && text.length > 0 layer.effect: Shade {} width: parent.width // Above the keys, the line is the gap to them: as wide as the one diff --git a/desktop/shell/shell/plugins/lock/Service.qml b/desktop/shell/shell/plugins/lock/Service.qml index 5828d9f9..69f9a8db 100644 --- a/desktop/shell/shell/plugins/lock/Service.qml +++ b/desktop/shell/shell/plugins/lock/Service.qml @@ -1,4 +1,5 @@ import QtQuick +import qs.Ui import Quickshell import Quickshell.Io import Quickshell.Services.Pam @@ -72,7 +73,6 @@ Item { 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: "" @@ -148,6 +148,10 @@ Item { return } + if (!Quickshell.env("HYPRLAND_INSTANCE_SIGNATURE")) { + strandedLockResolved = true + return + } strandedLockCheckProc.running = true } @@ -159,8 +163,23 @@ Item { beginLock() } + // Watch the link and its current target, including an overwrite in place. + // Never preload the wallpaper into a FileView just to watch its metadata. + FileView { + path: root.stateHome + "/omarchy/current" + preload: false + watchChanges: true + onFileChanged: { reload(); root.refreshBackground() } + } + FileView { + path: root.backgroundPath + preload: false + watchChanges: true + onFileChanged: { reload(); root.refreshBackground() } + } function refreshBackground() { - if (!readlinkProc.running) readlinkProc.running = true + if (readlinkProc.running) readlinkProc.pending = true + else readlinkProc.running = true } function refreshPoster() { @@ -174,7 +193,20 @@ Item { } function refreshFingerprintStatus() { - if (!fingerprintCheckProc.running) fingerprintCheckProc.running = true + fingerprintConfig.reload() + fingerprintConfig.text() + } + FileView { + id: fingerprintConfig + path: "/etc/pam.d/omarchy-lock-fingerprint" + printErrors: false + preload: false + // An enrollment change can happen outside the shell. Only ask fprintd + // on machines configured to use it. + onLoaded: if (!fingerprintCheckProc.running) fingerprintCheckProc.running = true + onLoadFailed: function(error) { + root.applyFingerprintProbe(error === FileViewError.FileNotFound ? "no" : "") + } } // Only definitive enrollment results may disable authentication. @@ -247,7 +279,6 @@ Item { queueSessionLock() Qt.callLater(function() { - root.refreshBackground() root.refreshFingerprintStatus() }) @@ -543,7 +574,8 @@ Item { anchors.fill: parent backgroundPath: root.backgroundPath videoPosterPath: root.videoPosterPath - backgroundVersion: root.backgroundVersion + backgroundVersion: Wallpaper.revision + nativeWallpaperSize: root.lockWallpaperSize fingerprintConfigured: root.fingerprintConfigured || root.fingerprintUnavailable fingerprintUnavailable: root.fingerprintUnavailable authenticatingPassword: root.authenticatingPassword @@ -573,7 +605,8 @@ Item { } } - PanelWindow { + OnDemandLoader { id: windowLoader; requested: root.previewVisible; sourceComponent: windowComponent } + property Component windowComponent: PanelWindow { id: previewWindow // Right-to-left languages read this window mirrored. Binding { target: previewWindow.contentItem; property: "LayoutMirroring.enabled"; value: Commons.I18n.rightToLeft } @@ -591,7 +624,8 @@ Item { anchors.fill: parent backgroundPath: root.backgroundPath videoPosterPath: root.videoPosterPath - backgroundVersion: root.backgroundVersion + backgroundVersion: Wallpaper.revision + nativeWallpaperSize: root.lockWallpaperSize fingerprintConfigured: root.fingerprintConfigured || root.fingerprintUnavailable fingerprintUnavailable: root.fingerprintUnavailable authenticatingPassword: false @@ -655,22 +689,25 @@ Item { // 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, + // time, as the lock view requests it (same URL, the screen's physical size, // PreserveAspectCrop), so the lock draws it on its first frame. readonly property string lockWallpaperPath: videoBackground ? videoPosterPath : backgroundPath + readonly property var backgroundService: shell ? shell.firstPartyServiceFor("omarchy.background") : null + readonly property var lockWallpaperSize: backgroundService && backgroundService.nativeSizes + ? backgroundService.nativeSizes[lockWallpaperPath] : null readonly property string lockWallpaperUrl: lockWallpaperPath && !Util.isVideoPath(lockWallpaperPath) - ? Util.fileUrl(lockWallpaperPath) + (backgroundVersion ? "?v=" + backgroundVersion : "") + ? Util.fileUrl(lockWallpaperPath) + (Wallpaper.revision ? "?v=" + Wallpaper.revision : "") : "" Variants { - model: Quickshell.screens + model: !root.startLocked || root.startupLifted ? Quickshell.screens : [] Image { required property var modelData visible: false source: root.lockWallpaperUrl - sourceSize.width: modelData.width - sourceSize.height: modelData.height + sourceSize: Wallpaper.decodeSize(root.lockWallpaperSize, Math.ceil(modelData.width * modelData.devicePixelRatio), + Math.ceil(modelData.height * modelData.devicePixelRatio)) fillMode: Image.PreserveAspectCrop asynchronous: true cache: true @@ -733,6 +770,8 @@ Item { Process { id: readlinkProc + property bool pending: false + onExited: if (pending) { pending = false; Qt.callLater(root.refreshBackground) } 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 @@ -744,10 +783,10 @@ Item { root.videoPosterPath = "" root.backgroundPath = next root.backgroundSignature = signature - root.backgroundVersion += 1 + Wallpaper.revision++ } else if (signature !== root.backgroundSignature) { root.backgroundSignature = signature - root.backgroundVersion += 1 + Wallpaper.revision++ } root.refreshPoster() } @@ -815,12 +854,12 @@ Item { Process { id: wakeProcess - command: ["bash", "-c", Quickshell.env("OMARCHY_TOUCH_MODE") === "1" ? "/usr/libexec/omarchy-powerctl wake" : "omarchy-system-wake"] + command: Quickshell.env("OMARCHY_TOUCH_MODE") === "1" ? ["/usr/libexec/omarchy-powerctl", "wake"] : ["omarchy-system-wake"] } Process { id: blankProcess - command: ["bash", "-c", Quickshell.env("OMARCHY_TOUCH_MODE") === "1" ? "/usr/libexec/omarchy-powerctl idle" : "omarchy-brightness-keyboard off; omarchy-brightness-display off"] + command: Quickshell.env("OMARCHY_TOUCH_MODE") === "1" ? ["/usr/libexec/omarchy-powerctl", "idle"] : ["bash", "-c", "omarchy-brightness-keyboard off; omarchy-brightness-display off"] } Timer { @@ -947,6 +986,12 @@ Item { // The lock is on screen: lift Labwc's startup cover, and record for the // installer that the PIN screen is on (omarchy-desktop-ready pin-screen). + Binding { + target: Startup + property: "drawingLock" + value: root.startLocked && root.lockRequested && !root.startupLifted + } + function liftStartup() { if (startupLifted) return startupLifted = true @@ -983,7 +1028,6 @@ Item { function woke(): string { if (root.currentlyLocked()) { - root.displaysBlank = false root.armBlankTimer() root.resumeFingerprint() } @@ -1012,7 +1056,6 @@ Item { } function preview(): string { - root.refreshBackground() root.refreshFingerprintStatus() root.previewVisible = true return "ok" diff --git a/desktop/shell/shell/plugins/menu/Menu.qml b/desktop/shell/shell/plugins/menu/Menu.qml index 3efa2138..5239e721 100644 --- a/desktop/shell/shell/plugins/menu/Menu.qml +++ b/desktop/shell/shell/plugins/menu/Menu.qml @@ -2,10 +2,12 @@ import Quickshell import Quickshell.Io import Quickshell.Wayland import QtQuick +import Qt.labs.folderlistmodel import qs.Commons import qs.Commons as Commons import qs.Ui import "MenuModel.js" as MenuModel +import "../../settings/SettingsModel.js" as SettingsModel Item { id: root @@ -90,7 +92,7 @@ Item { property string activeMenu: "root" property string filterText: "" // Resets of filterText reach the search line; its edits come back through setFilter. - onFilterTextChanged: if (filterInput.text !== filterText) filterInput.text = filterText + onFilterTextChanged: if (filterInput && filterInput.text !== filterText) filterInput.text = filterText property int selectedIndex: 0 property bool cursorActive: false // Rows with a `alt:` stand-in show and run it while this holds. @@ -137,9 +139,9 @@ Item { property int dividerHeight: Style.space(17) property bool searchDivider: false property int layoutSerial: 0 - property int cardWidth: Math.min(root.dmenuActive ? Style.space(root.dmenuWidth) : ((root.activeMenu === "trigger.capture.screenrecord" || root.activeMenu === "appearance.font" || root.activeMenu === "update.kernel") ? Style.space(520) : Style.space(300)), panel.width - Style.gapsOut * 2) + property int cardWidth: !panel ? 0 : Math.min(root.dmenuActive ? Style.space(root.dmenuWidth) : ((root.activeMenu === "trigger.capture.screenrecord" || root.activeMenu === "appearance.font" || root.activeMenu === "update.kernel") ? Style.space(520) : Style.space(300)), panel.width - Style.gapsOut * 2) property int visibleRowsHeight: root.dmenuActive ? dmenuRowListHeight(layoutSerial, displayModel.count, filterText) : rowListHeight(layoutSerial, displayModel.count, filterText, searchDivider) - property int cardHeight: root.dmenuActive + property int cardHeight: !panel ? 0 : root.dmenuActive ? Math.min(contentMargin * 2 + headerHeight + (mode === "input" ? 0 : contentSpacing + visibleRowsHeight), panel.usableHeight - Style.gapsOut * 2) : Math.min(contentMargin * 2 + headerHeight + contentSpacing + visibleRowsHeight, panel.usableHeight - Style.gapsOut * 2) @@ -184,6 +186,7 @@ Item { // Uses panel.cardTop rather than effectiveCardTop: the centered top is // derived from the card height, which this value feeds. function availableRowsHeight() { + if (!panel) return 0 var top = panel.cardTop >= 0 ? panel.cardTop : Style.gapsOut var available = panel.usableHeight - top - Style.gapsOut - root.contentMargin * 2 - root.headerHeight - root.contentSpacing // The starting menu sets the ceiling along with the offset: drilling into @@ -306,8 +309,18 @@ Item { root.providerQueue = [] root.items = mergedMenu.items root.itemOrder = mergedMenu.itemOrder + if (!skipGuards) { + var commands = {} + for (var id in mergedMenu.items) { + var entry = mergedMenu.items[id] + var provider = entry.provider ? root.providers[entry.provider] : null + for (var name of SettingsModel.commandsIn((entry.action || "") + "\n" + (provider ? provider.script : ""))) + commands[name] = true + } + ShellFacts.configure(commands) + } root.rowsLoaded = true - if (!skipGuards && root.defaultMenuSettled && root.userMenuSettled) root.evaluateGuards() + if (!skipGuards && root.defaultMenuSettled && root.userMenuSettled) root.scheduleGuards() if (root.opened) { root.rebuildDisplay() if (!root.dmenuActive) { @@ -791,7 +804,7 @@ Item { // the neighbor entirely and losing the fold affordance. Keep the next // hidden row peeking past the cursor in the direction of travel. function revealCursor() { - if (displayModel.count === 0) return + if (!resultList || displayModel.count === 0) return resultList.positionViewAtIndex(root.selectedIndex, ListView.Contain) var item = resultList.itemAtIndex(root.selectedIndex) @@ -960,6 +973,7 @@ Item { opened = false filterText = "" root.runAction(action) + guardInputsChanged.restart() } function cancel() { @@ -982,7 +996,6 @@ Item { selectedIndex = 0 cursorActive = true root.disarmPointer() - root.evaluateGuards() opened = true rebuildDisplay() invalidateVolatileProvider(activeMenu) @@ -1166,6 +1179,7 @@ Item { Connections { target: root.appLibrary + function onPackagesChanged() { ShellFacts.invalidate() } function onAppsChanged() { if (root.providersLoaded["apps"]) root.mergeAppRows() } @@ -1184,7 +1198,7 @@ Item { printErrors: false onLoaded: { root.defaultMenuItems = MenuModel.keepMenuRows(root.defaultMenuItems, text(), true); root.defaultMenuSettled = true; root.rebuildItemsFromSources() } // A user file that loaded first held its evaluation for this one. - onLoadFailed: { root.defaultMenuSettled = true; if (root.userMenuSettled) root.evaluateGuards() } + onLoadFailed: { root.defaultMenuSettled = true; if (root.userMenuSettled) root.scheduleGuards() } onFileChanged: reload() } @@ -1232,7 +1246,50 @@ Item { property var disabledResults: ({}) // id → true|false (dim, skip cursor) property bool guardsPending: false + // The launcher shares these answers. Refresh when their inputs change, + // including changes made outside Settings, without tying work to a window. + Timer { + id: guardInputsChanged + interval: 600 + onTriggered: if (root.defaultMenuSettled && root.userMenuSettled) root.scheduleGuards() + } + FolderListModel { + id: toggles + folder: Util.fileUrl(Quickshell.env("HOME") + "/.local/state/omarchy/toggles") + showDirs: false + } + Connections { + target: toggles + function onDataChanged() { guardInputsChanged.restart() } + function onRowCountChanged() { guardInputsChanged.restart() } + } + Connections { + target: root.shell ? root.shell.bar : null + ignoreUnknownSignals: true + function onBarConfigChanged() { guardInputsChanged.restart() } + function onScreenRecordingChanged() { guardInputsChanged.restart() } + } + FileView { + path: (Quickshell.env("XDG_CONFIG_HOME") || Quickshell.env("HOME") + "/.config") + "/mimeapps.list" + preload: false + watchChanges: true + onFileChanged: guardInputsChanged.restart() + } + + property bool guardsDeferred: false + Connections { + target: ShellFacts + function onUpdated() { guardInputsChanged.restart() } + } + function scheduleGuards() { + if (Startup.ready || opened) evaluateGuards() + else guardsDeferred = true + } + AfterStartup { onTriggered: if (root.guardsDeferred) root.evaluateGuards() } + function evaluateGuards() { + if (!ShellFacts.settled) { guardsDeferred = true; return } + guardsDeferred = false // Process ignores a command change while it is running, and `collected` // belongs to the run in flight, so a second evaluation cannot overwrite // the first: it would throw away the lines already read and never start. @@ -1245,24 +1302,20 @@ Item { } root.guardsPending = false - var script = MenuModel.guardScript(root.items) + var script = MenuModel.guardScript(root.items, ShellFacts.hardware, ShellFacts.hypr, ShellFacts.hyprland) if (!script) { root.whenResults = ({}) root.checkedResults = ({}) root.disabledResults = ({}) return } - guardProc.collected = "" - guardProc.command = ["bash", "-lc", script] + guardProc.command = ["bash", "-c", script] guardProc.running = true } Process { id: guardProc - property string collected: "" - stdout: SplitParser { - onRead: function(data) { guardProc.collected += data + "\n" } - } + stdout: StdioCollector { id: guardOutput; waitForEnd: true } onExited: function(exitCode, exitStatus) { // A batch that was killed rather than finished has only told us about // the rows it reached, and a row whose `when:` went unanswered shows. @@ -1276,7 +1329,7 @@ Item { var nextWhen = ({}) var nextChecked = ({}) var nextDisabled = ({}) - var lines = guardProc.collected.split("\n") + var lines = guardOutput.text.split("\n") for (var i = 0; i < lines.length; i++) { var line = lines[i].trim() if (!line) continue @@ -1301,9 +1354,19 @@ Item { if (root.guardsPending) Qt.callLater(function() { root.evaluateGuards() }) } } - OverlayWindow { + readonly property var panel: windowLoader.item + readonly property var filterInput: panel ? panel.filterInput : null + readonly property var resultList: panel ? panel.resultList : null + readonly property var card: panel ? panel.card : null + readonly property var deleteConfirm: panel ? panel.deleteConfirm : null + OnDemandLoader { id: windowLoader; requested: root.opened; sourceComponent: windowComponent } + property Component windowComponent: OverlayWindow { id: panel - shown: root.opened && root.rowsLoaded + property alias filterInput: filterInput + property alias resultList: resultList + property alias card: card + property alias deleteConfirm: deleteConfirm + shown: !!windowLoader.item && root.opened && root.rowsLoaded WlrLayershell.namespace: "omarchy-menu" // The card opens centered exactly as always. The first search keystroke diff --git a/desktop/shell/shell/plugins/menu/MenuModel.js b/desktop/shell/shell/plugins/menu/MenuModel.js index 3a486a84..1f23753a 100644 --- a/desktop/shell/shell/plugins/menu/MenuModel.js +++ b/desktop/shell/shell/plugins/menu/MenuModel.js @@ -537,7 +537,9 @@ function guardPackageSnapshot() { } function guardHelpers() { - return 'declare -A __omarchy_pkgs=()\n' + return 'omarchy-toggle-enabled() { [[ $# == 1 && $1 =~ ^[a-z0-9-]+$ && -e $HOME/.local/state/omarchy/toggles/$1 ]]; }\n' + + 'omarchy-hyprland-toggle-enabled() { [[ -f $HOME/.local/state/omarchy/toggles/hypr/$1.lua ]]; }\n' + + 'declare -A __omarchy_pkgs=()\n' + guardPackageSnapshot() + 'for __omarchy_pkg in "${__omarchy_pkg_names[@]}"; do __omarchy_pkgs[$__omarchy_pkg]=1; done\n' + '__omarchy_pkg_has() { [[ -n ${__omarchy_pkgs[$1]-} ]] && return 0; ' @@ -620,14 +622,31 @@ var GUARD_GROUPS = 8 // has left its remaining rows unanswered, and the menu keeps the last full // set only when the batch fails. So each group is waited for by pid, and the // batch's status is nonzero if any of them was. -function guardScript(items) { +// Only fold the simple predicates used by the shipped menu. A custom shell +// expression can depend on stdout or compose commands and must run as written. +function cachedGuard(expr, hardware) { + var match = /^(! )?(omarchy-hw-[a-z0-9-]+)(?= && |$)/.exec(expr) + if (match && !/[|;\n]/.test(expr) && hardware && typeof hardware[match[2]] === "boolean") { + var ok = hardware[match[2]] !== !!match[1] + if (!ok) return "false" + return expr.slice(match[0].length + 4) || "true" + } + return expr +} + +function guardScript(items, hardware, hypr, incompatible) { var lines = [] var ids = Object.keys(items || {}) for (var i = 0; i < ids.length; i++) { var entry = items[ids[i]] if (!entry) continue - if (entry.when) lines.push(guardLine(ids[i], "w", entry.when)) + var when = cachedGuard(entry.when || "", hardware) + // Skip Hyprland-only commands and their state readers outside that session. + if (hypr === false && (/\b(?:hyprctl|omarchy-hyprland-[\w-]+)/.test([entry.action, entry.when, entry.checked].join(" ")) + || (incompatible && incompatible[String(entry.action || "").split(" ")[0]]))) when = "false" + if (when) lines.push(guardLine(ids[i], "w", when)) + if (when === "false") continue if (entry.checked) lines.push(guardLine(ids[i], "c", entry.checked)) if (entry.disabled) lines.push(guardLine(ids[i], "d", entry.disabled)) } diff --git a/desktop/shell/shell/plugins/notifications/Service.qml b/desktop/shell/shell/plugins/notifications/Service.qml index e26b28a0..aecc8000 100644 --- a/desktop/shell/shell/plugins/notifications/Service.qml +++ b/desktop/shell/shell/plugins/notifications/Service.qml @@ -260,10 +260,17 @@ Item { property int refsRevision: 0 property int keySeed: 0 + property bool bannerRequested: false + Timer { + interval: 1500 + running: service.bannerRequested && toasts.count === 0 + onTriggered: service.bannerRequested = false + } ListModel { id: toasts onCountChanged: { - if (count === 0) service.deckDisplayName = "" + if (count > 0) service.bannerRequested = true + else service.deckDisplayName = "" if (service.keyboardMode) Qt.callLater(function() { service.keepSelection(0) }) } } @@ -1618,7 +1625,8 @@ Item { onExited: function(code) { service.storeReady = code === 0 } } - Component.onCompleted: { storePrepare.running = true; stackModeProc.running = true } + Component.onCompleted: storePrepare.running = true // quiet.json supplies the lock's Focus icon. + AfterStartup { onTriggered: stackModeProc.running = true } // A reload or a clean exit inside the save delay still writes. Component.onDestruction: flushStore() @@ -1794,11 +1802,11 @@ Item { // // One fixed-size layer per output, so the compositor never scales a stale // buffer; the mask makes everything outside the deck click-through. It stays - // mapped while idle (remapping re-evaluates focus and drags a scrolling - // layout's viewport), except where it steps aside for a fullscreen window. + // mapped across a burst so remapping cannot disturb a scrolling viewport. + // Once the last toast has left, give back the surface and its buffers. Variants { id: surfaceVariants - model: Quickshell.screens + model: service.bannerRequested ? Quickshell.screens : [] PanelWindow { id: surface diff --git a/desktop/shell/shell/plugins/notifications/Toast.qml b/desktop/shell/shell/plugins/notifications/Toast.qml index e31ca7f0..db49e513 100644 --- a/desktop/shell/shell/plugins/notifications/Toast.qml +++ b/desktop/shell/shell/plugins/notifications/Toast.qml @@ -421,7 +421,7 @@ Item { Rectangle { id: bannerShadow - visible: card.banner && card.gpu + visible: !Lite.enabled && card.banner && card.gpu anchors.fill: bannerBox color: "black" layer.enabled: visible @@ -811,7 +811,8 @@ Item { // rounded like the card, only when the theme rounds at all. readonly property bool rounded: thumb.photo && Style.cornerRadius > 0 opacity: thumb.mono ? 0.85 : 1 - layer.enabled: visible && (thumb.mono || rounded) + clip: Lite.enabled && thumb.photo + layer.enabled: !Lite.enabled && visible && (thumb.mono || rounded) layer.effect: MultiEffect { maskEnabled: picture.rounded maskSource: mask @@ -825,7 +826,7 @@ Item { id: mask anchors.fill: parent visible: false - layer.enabled: true + layer.enabled: !Lite.enabled radius: Style.cornerRadius color: "black" } diff --git a/desktop/shell/shell/plugins/osd/Osd.qml b/desktop/shell/shell/plugins/osd/Osd.qml index 68e11f7b..2d05fb15 100644 --- a/desktop/shell/shell/plugins/osd/Osd.qml +++ b/desktop/shell/shell/plugins/osd/Osd.qml @@ -19,38 +19,6 @@ Item { property bool hasProgress: true property int duration: 1200 - readonly property bool mediaOsd: iconKey.indexOf("media") === 0 || iconKey.indexOf("player") === 0 - - // The card is built out of measured columns instead of fixed widths, so it - // keeps exactly `pad` between border and content on every side whatever - // glyph or message it carries. Messages grow with their text up to - // `maxMessageWidth` and elide beyond it. - readonly property int pad: Style.space(16) - readonly property int gap: Style.space(16) - // A glyph next to a message reads airier than it measures: the icon outline - // and the letterforms both fall away from their ink extremes, so the space - // between them opens up well past the nominal gap. Text takes two thirds of - // it; the progress bar's hard edge keeps the full gap. - readonly property int messageGap: Math.round(root.gap * 2 / 3) - readonly property int barWidth: Style.space(142) - readonly property int maxMessageWidth: root.mediaOsd ? Style.space(325) : Style.space(190) - - // Nerd Font glyphs draw well outside their monospace cell, so the icon - // column is measured by ink rather than by advance width. Progress OSDs pin - // it to the widest glyph the model can return, so the bar doesn't shift when - // volume crosses an icon threshold. - readonly property int iconInkWidth: Math.ceil(iconMetrics.tightBoundingRect.width) - readonly property int iconWidth: root.hasProgress - ? Math.max(root.iconInkWidth, Math.ceil(widestIconMetrics.tightBoundingRect.width)) - : root.iconInkWidth - // Same idea for the readout: it is as wide as the longest percentage so the - // digits don't jitter between 9% and 100%. - readonly property int valueWidth: Math.ceil(Math.max(valueMetrics.advanceWidth, messageMetrics.advanceWidth)) - readonly property int messageWidth: Math.min(Math.ceil(messageMetrics.advanceWidth), root.maxMessageWidth) - readonly property int contentWidth: root.hasProgress - ? root.iconWidth + root.gap + root.barWidth + root.gap + root.valueWidth - : (root.message === "" ? root.iconWidth : root.iconWidth + root.messageGap + root.messageWidth) - function iconFor(name, percent) { return OsdModel.iconFor(name, percent) } @@ -86,33 +54,6 @@ Item { onTriggered: root.opened = false } - TextMetrics { - id: messageMetrics - font.family: Style.font.family - font.bold: true - font.pixelSize: Style.font.title - text: root.message - } - - TextMetrics { - id: valueMetrics - font: messageMetrics.font - text: Commons.I18n.formatNumber(100) + "%" - } - - TextMetrics { - id: iconMetrics - font.family: Style.font.family - font.pixelSize: Style.font.displayLarge - text: root.icon - } - - TextMetrics { - id: widestIconMetrics - font: iconMetrics.font - text: OsdModel.widestIcon - } - ShellIpc { target: "osd" function show(payloadJson: string): string { @@ -127,19 +68,79 @@ Item { function ping(): string { return "ok" } } - OverlayWindow { + OnDemandLoader { id: windowLoader; requested: root.opened; sourceComponent: windowComponent } + property Component windowComponent: OverlayWindow { id: panel - shown: root.opened + shown: !!windowLoader.item && root.opened shownKeyboardFocus: WlrKeyboardFocus.None WlrLayershell.namespace: "omarchy-osd" // Visual-only surface: keep the layer-shell input region empty so the OSD // never blocks clicks to the desktop below it. mask: Region {} + readonly property bool mediaOsd: root.iconKey.indexOf("media") === 0 || root.iconKey.indexOf("player") === 0 + + // The card is built out of measured columns instead of fixed widths, so it + // keeps exactly `pad` between border and content on every side whatever + // glyph or message it carries. Messages grow with their text up to + // `maxMessageWidth` and elide beyond it. + readonly property int pad: Style.space(16) + readonly property int gap: Style.space(16) + // A glyph next to a message reads airier than it measures: the icon outline + // and the letterforms both fall away from their ink extremes, so the space + // between them opens up well past the nominal gap. Text takes two thirds of + // it; the progress bar's hard edge keeps the full gap. + readonly property int messageGap: Math.round(panel.gap * 2 / 3) + readonly property int barWidth: Style.space(142) + readonly property int maxMessageWidth: panel.mediaOsd ? Style.space(325) : Style.space(190) + + // Nerd Font glyphs draw well outside their monospace cell, so the icon + // column is measured by ink rather than by advance width. Progress OSDs pin + // it to the widest glyph the model can return, so the bar doesn't shift when + // volume crosses an icon threshold. + readonly property int iconInkWidth: Math.ceil(iconMetrics.tightBoundingRect.width) + readonly property int iconWidth: root.hasProgress + ? Math.max(panel.iconInkWidth, Math.ceil(widestIconMetrics.tightBoundingRect.width)) + : panel.iconInkWidth + // Same idea for the readout: it is as wide as the longest percentage so the + // digits don't jitter between 9% and 100%. + readonly property int valueWidth: Math.ceil(Math.max(valueMetrics.advanceWidth, messageMetrics.advanceWidth)) + readonly property int messageWidth: Math.min(Math.ceil(messageMetrics.advanceWidth), panel.maxMessageWidth) + readonly property int contentWidth: root.hasProgress + ? panel.iconWidth + panel.gap + panel.barWidth + panel.gap + panel.valueWidth + : (root.message === "" ? panel.iconWidth : panel.iconWidth + panel.messageGap + panel.messageWidth) + + TextMetrics { + id: messageMetrics + font.family: Style.font.family + font.bold: true + font.pixelSize: Style.font.title + text: root.message + } + + TextMetrics { + id: valueMetrics + font: messageMetrics.font + text: Commons.I18n.formatNumber(100) + "%" + } + + TextMetrics { + id: iconMetrics + font.family: Style.font.family + font.pixelSize: Style.font.displayLarge + text: root.icon + } + + TextMetrics { + id: widestIconMetrics + font: iconMetrics.font + text: OsdModel.widestIcon + } + BorderSurface { id: card - width: card.borderLeft + root.pad + root.contentWidth + root.pad + card.borderRight - height: card.borderTop + root.pad + Style.font.displayLarge + root.pad + card.borderBottom + width: card.borderLeft + panel.pad + panel.contentWidth + panel.pad + card.borderRight + height: card.borderTop + panel.pad + Style.font.displayLarge + panel.pad + card.borderBottom anchors.horizontalCenter: parent.horizontalCenter anchors.bottom: parent.bottom anchors.bottomMargin: Style.space(67) @@ -150,19 +151,19 @@ Item { Row { anchors.fill: parent - anchors.topMargin: card.borderTop + root.pad - anchors.rightMargin: card.borderRight + root.pad - anchors.bottomMargin: card.borderBottom + root.pad - anchors.leftMargin: card.borderLeft + root.pad - spacing: root.hasProgress ? root.gap : root.messageGap + anchors.topMargin: card.borderTop + panel.pad + anchors.rightMargin: card.borderRight + panel.pad + anchors.bottomMargin: card.borderBottom + panel.pad + anchors.leftMargin: card.borderLeft + panel.pad + spacing: root.hasProgress ? panel.gap : panel.messageGap Item { - width: root.iconWidth + width: panel.iconWidth height: parent.height Text { textFormat: Text.PlainText // Sit the glyph's ink flush in the column, centered when the // column is wider than this particular glyph. - x: Math.round((root.iconWidth - root.iconInkWidth) / 2 - iconMetrics.tightBoundingRect.x) + x: Math.round((panel.iconWidth - panel.iconInkWidth) / 2 - iconMetrics.tightBoundingRect.x) anchors.verticalCenter: parent.verticalCenter text: root.icon font: iconMetrics.font @@ -171,7 +172,7 @@ Item { } Rectangle { visible: root.hasProgress - width: root.barWidth + width: panel.barWidth height: Math.max(Style.space(6), Style.spacing.sm) anchors.verticalCenter: parent.verticalCenter color: Util.alpha(Commons.Color.popups.text, 0.45) @@ -191,7 +192,7 @@ Item { Text { textFormat: Text.PlainText visible: root.message !== "" - width: root.hasProgress ? root.valueWidth : root.messageWidth + width: root.hasProgress ? panel.valueWidth : panel.messageWidth // The readout hugs the card edge so a short percentage doesn't leave // a hole in the padding; the slack lands in the gap after the bar. horizontalAlignment: root.hasProgress ? Text.AlignRight : Text.AlignLeft diff --git a/desktop/shell/shell/plugins/panels/audio/Panel.qml b/desktop/shell/shell/plugins/panels/audio/Panel.qml index 30582cde..5837a03f 100644 --- a/desktop/shell/shell/plugins/panels/audio/Panel.qml +++ b/desktop/shell/shell/plugins/panels/audio/Panel.qml @@ -16,8 +16,8 @@ Panel { readonly property var sink: Pipewire.defaultAudioSink readonly property var source: Pipewire.defaultAudioSource - readonly property var nodes: Pipewire.nodes ? Pipewire.nodes.values : [] - readonly property var mprisPlayers: Mpris.players ? Mpris.players.values : [] + readonly property var nodes: (Startup.ready || opened) && Pipewire.nodes ? Pipewire.nodes.values : [] + readonly property var mprisPlayers: opened && Mpris.players ? Mpris.players.values : [] readonly property var mediaService: bar?.shell?.firstPartyServiceFor("omarchy.media") readonly property var activeMediaPlayer: mediaService ? mediaService.activePlayer : null @@ -157,11 +157,11 @@ Panel { // Re-resolve whenever the selected output changes, and when nodes or links // come and go: a tuning being applied or removed underneath us, or a DSP sink // rerouted to another output, shows up as exactly that. - onSinkChanged: resolveVolumeSink() - onNodesChanged: volumeSinkResolveTimer.restart() + onSinkChanged: if (Startup.ready || opened) resolveVolumeSink() + onNodesChanged: if (Startup.ready || opened) volumeSinkResolveTimer.restart() Connections { - target: Pipewire.linkGroups + target: Startup.ready || root.opened ? Pipewire.linkGroups : null function onValuesChanged() { volumeSinkResolveTimer.restart() } } @@ -179,6 +179,7 @@ Panel { volumeSinkName = String(sink.name) return } + if (!ShellFacts.hasReader("omarchy-audio-output-sink")) return if (volumeSinkProc.running) { volumeSinkStale = true return @@ -369,6 +370,7 @@ Panel { onOpenedChanged: { if (opened) { + resolveVolumeSink() refreshDisplayAudioModels() focusSection = "output" selectedIndex = -1 // first keyboard cursor reveal starts on the output slider @@ -705,7 +707,7 @@ Panel { Timer { interval: 5000 - running: root.opened + running: root.opened && ShellFacts.hasReader("omarchy-audio-sink-availability") repeat: true triggeredOnStart: true onTriggered: { @@ -724,7 +726,11 @@ Panel { onTriggered: root.resolveVolumeSink() } - Component.onCompleted: root.resolveVolumeSink() + Connections { + target: ShellFacts + function onUpdated() { root.resolveVolumeSink() } + } + AfterStartup { onTriggered: root.resolveVolumeSink() } Timer { id: audioModelRefreshTimer @@ -756,7 +762,7 @@ Panel { // The content, for a host that shows it as a page (the control center). readonly property Component pageContent: panel.content - KeyboardPanel { + LazyKeyboardPanel { id: panel anchorItem: button owner: root diff --git a/desktop/shell/shell/plugins/panels/bluetooth/Panel.qml b/desktop/shell/shell/plugins/panels/bluetooth/Panel.qml index 0e5b9c06..48a1fe22 100644 --- a/desktop/shell/shell/plugins/panels/bluetooth/Panel.qml +++ b/desktop/shell/shell/plugins/panels/bluetooth/Panel.qml @@ -705,7 +705,7 @@ Panel { // The content, for a host that shows it as a page (the control center). readonly property Component pageContent: panel.content - KeyboardPanel { + LazyKeyboardPanel { id: panel anchorItem: button owner: root diff --git a/desktop/shell/shell/plugins/panels/clock/BarWidget.qml b/desktop/shell/shell/plugins/panels/clock/BarWidget.qml index c2069650..68941f23 100644 --- a/desktop/shell/shell/plugins/panels/clock/BarWidget.qml +++ b/desktop/shell/shell/plugins/panels/clock/BarWidget.qml @@ -74,6 +74,7 @@ BarWidget { readonly property bool opened: panelLoader.item ? panelLoader.item.opened === true : false function open() { + panelLoader.active = true if (panelLoader.item) panelLoader.item.open() } @@ -82,10 +83,12 @@ BarWidget { } function togglePanel() { + panelLoader.active = true if (panelLoader.item) panelLoader.item.toggle() } function toggleWeekStart() { + panelLoader.active = true if (panelLoader.item) panelLoader.item.toggleWeekStart() } @@ -129,7 +132,7 @@ BarWidget { Loader { id: panelLoader - active: true + active: false source: Qt.resolvedUrl("Panel.qml") visible: false onLoaded: { diff --git a/desktop/shell/shell/plugins/panels/dropbox/DropboxIcon.qml b/desktop/shell/shell/plugins/panels/dropbox/DropboxIcon.qml index 5f0d411d..bf64bbb0 100644 --- a/desktop/shell/shell/plugins/panels/dropbox/DropboxIcon.qml +++ b/desktop/shell/shell/plugins/panels/dropbox/DropboxIcon.qml @@ -19,7 +19,7 @@ Item { Shape { anchors.fill: parent antialiasing: true - layer.enabled: true + layer.enabled: !Lite.enabled layer.samples: 4 scale: root.artworkScale diff --git a/desktop/shell/shell/plugins/panels/dropbox/Panel.qml b/desktop/shell/shell/plugins/panels/dropbox/Panel.qml index e861c646..e054c839 100644 --- a/desktop/shell/shell/plugins/panels/dropbox/Panel.qml +++ b/desktop/shell/shell/plugins/panels/dropbox/Panel.qml @@ -199,7 +199,7 @@ Panel { } } - KeyboardPanel { + LazyKeyboardPanel { id: panel anchorItem: button owner: root diff --git a/desktop/shell/shell/plugins/panels/dropbox/Service.qml b/desktop/shell/shell/plugins/panels/dropbox/Service.qml index 86896ccf..17b7ef28 100644 --- a/desktop/shell/shell/plugins/panels/dropbox/Service.qml +++ b/desktop/shell/shell/plugins/panels/dropbox/Service.qml @@ -185,7 +185,7 @@ Item { id: refreshTimer interval: root.refreshIntervalSec * 1000 repeat: true - running: true + running: Startup.ready triggeredOnStart: true onTriggered: root.refresh() } @@ -199,7 +199,7 @@ Item { property int ticks: 0 interval: 2000 repeat: true - running: true + running: Startup.ready onTriggered: { ticks += 1 if (root.running || ticks >= 15) startupRamp.running = false diff --git a/desktop/shell/shell/plugins/panels/elsewhen/Avatar.qml b/desktop/shell/shell/plugins/panels/elsewhen/Avatar.qml index b3acd3f5..13fd5f16 100644 --- a/desktop/shell/shell/plugins/panels/elsewhen/Avatar.qml +++ b/desktop/shell/shell/plugins/panels/elsewhen/Avatar.qml @@ -53,7 +53,8 @@ Item { Image { id: picture anchors.fill: parent - visible: false + visible: Lite.enabled && avatar.pictured + clip: Lite.enabled source: avatar.source === "" ? "" : "file://" + avatar.source + "?v=" + avatar.stamp sourceSize.width: Math.ceil(avatar.size * Screen.devicePixelRatio) sourceSize.height: Math.ceil(avatar.size * Screen.devicePixelRatio) @@ -67,7 +68,7 @@ Item { id: disc anchors.fill: parent visible: false - layer.enabled: true + layer.enabled: !Lite.enabled Rectangle { anchors.fill: parent @@ -76,13 +77,16 @@ Item { } } - MultiEffect { + Loader { anchors.fill: parent + active: !Lite.enabled visible: avatar.pictured - source: picture - maskEnabled: true - maskSource: disc - maskThresholdMin: 0.5 - maskSpreadAtMin: 1.0 + sourceComponent: MultiEffect { + source: picture + maskEnabled: true + maskSource: disc + maskThresholdMin: 0.5 + maskSpreadAtMin: 1.0 + } } } diff --git a/desktop/shell/shell/plugins/panels/elsewhen/DaylightStrip.qml b/desktop/shell/shell/plugins/panels/elsewhen/DaylightStrip.qml index 205ad9d2..cd64bbea 100644 --- a/desktop/shell/shell/plugins/panels/elsewhen/DaylightStrip.qml +++ b/desktop/shell/shell/plugins/panels/elsewhen/DaylightStrip.qml @@ -123,13 +123,14 @@ Item { color: strip.foreground } - Behavior on x { NumberAnimation { duration: Style.duration(400); easing.type: Easing.OutCubic } } + Behavior on x { NumberAnimation { duration: scrubArea.pressed && !Style.reduceMotion ? 400 : 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 { + id: scrubArea anchors.fill: parent cursorShape: Qt.SizeHorCursor preventStealing: true diff --git a/desktop/shell/shell/plugins/panels/elsewhen/Panel.qml b/desktop/shell/shell/plugins/panels/elsewhen/Panel.qml index 44584048..e08c2be0 100644 --- a/desktop/shell/shell/plugins/panels/elsewhen/Panel.qml +++ b/desktop/shell/shell/plugins/panels/elsewhen/Panel.qml @@ -724,7 +724,7 @@ Panel { spinPending = false; spinFallback.stop() } } - Component.onCompleted: refresh() + AfterStartup { onTriggered: root.refresh() } Process { id: probeProc @@ -922,7 +922,7 @@ Panel { } Timer { - interval: 1000 + interval: 60000 - (root.nowMs % 60000) running: root.opened repeat: true onTriggered: root.tick() @@ -993,7 +993,7 @@ Panel { } } - KeyboardPanel { + LazyKeyboardPanel { id: panel anchorItem: button owner: root diff --git a/desktop/shell/shell/plugins/panels/monitor/Panel.qml b/desktop/shell/shell/plugins/panels/monitor/Panel.qml index 9922e2b7..33f9c40f 100644 --- a/desktop/shell/shell/plugins/panels/monitor/Panel.qml +++ b/desktop/shell/shell/plugins/panels/monitor/Panel.qml @@ -37,8 +37,8 @@ Panel { // Orchard: the tablet's own row, which upstream's panel does not have: // ambient-light auto-brightness (hidden without the tool). Rotation lock and // Stay Awake are the control center's toggles. - property bool autoAvailable: false - property bool autoOn: false + readonly property bool autoAvailable: SessionStatus.autoAvailable + readonly property bool autoOn: SessionStatus.autoOn // Orchard: the screen turns with the iPad (arch-ipad-rotate-output, under // the rotation lock); labwc has no command to turn it by hand, so upstream's // rotate menu stays shut. @@ -49,7 +49,6 @@ Panel { function setAuto(on) { if (!autoAvailable || autoWriteProc.running) return - root.autoOn = on // optimistic: the switch moves at once autoWriteProc.command = ["omarchy-auto-brightness", on ? "on" : "off"] autoWriteProc.running = true } @@ -400,7 +399,6 @@ Panel { function refresh() { if (!stateProc.running) stateProc.running = true - if (!autoReadProc.running && !autoWriteProc.running) autoReadProc.running = true } // The focused display's brightness, for the bar icon's wheel and IPC. @@ -674,7 +672,7 @@ Panel { implicitWidth: button.implicitWidth implicitHeight: button.implicitHeight - Component.onCompleted: refresh() + AfterStartup { onTriggered: root.refresh() } // KeyboardPanel primes focus at open-time, so SUPER-bound IPC summons land // with j/k ready to navigate. Keep a default landing point, but don't paint @@ -818,20 +816,6 @@ Panel { } } - // Orchard: the tablet rows' state. - Process { - id: autoReadProc - command: ["omarchy-auto-brightness", "status"] - stdout: StdioCollector { - waitForEnd: true - onStreamFinished: { - var m = /^auto-brightness:\s*(on|off)/m.exec(String(text || "")) - root.autoAvailable = m !== null - if (m) root.autoOn = m[1] === "on" - } - } - } - Process { id: autoWriteProc stdout: StdioCollector { waitForEnd: true } @@ -857,7 +841,7 @@ Panel { // The content, for a host that shows it as a page (the control center). readonly property Component pageContent: panel.content - KeyboardPanel { + LazyKeyboardPanel { id: panel anchorItem: button owner: root diff --git a/desktop/shell/shell/plugins/panels/network/Panel.qml b/desktop/shell/shell/plugins/panels/network/Panel.qml index e043de0a..f66eceea 100644 --- a/desktop/shell/shell/plugins/panels/network/Panel.qml +++ b/desktop/shell/shell/plugins/panels/network/Panel.qml @@ -71,7 +71,7 @@ Panel { readonly property string connectionPhrase: connectionPhrases[connectionPhraseIndex % connectionPhrases.length] // Orchard: the connection state lives in Status.qml, which the status // cluster and the lock share; these names stay the panel's. - Status { id: status } + readonly property var status: SessionStatus.network readonly property bool networkManagerAvailable: status.networkManagerAvailable readonly property var networkDevices: status.networkDevices readonly property var wifiDevice: status.wifiDevice @@ -567,12 +567,13 @@ Panel { function refresh(scanWifi) { checkConnectivity() if (scanWifi === undefined) scanWifi = false + if (!opened) return if (!detailsProc.running) detailsProc.running = true if (!dnsProc.running) { - dnsProc.command = ["bash", "-c", root.dnsCommand("")] + dnsProc.command = ["omarchy-dns"] dnsProc.running = true } - if (!bandProc.running) { + if (wifiDevice && !bandProc.running) { bandProc.command = ["omarchy-network-band"] bandProc.running = true } @@ -749,12 +750,6 @@ Panel { bar.shell.summon("omarchy.speedtest", connection ? JSON.stringify({ connection: connection }) : "{}") } - function dnsCommand(provider) { - var command = "omarchy-dns" - if (provider) command += " " + Util.shellQuote(provider) - return command - } - function setDns(provider) { if (!root.bar || !provider || actionProc.running) return @@ -769,7 +764,7 @@ Panel { // The panel stays open, so the choice can be seen taking hold and another // tried without reopening it. root.pendingDnsProvider = provider - actionProc.command = ["bash", "-c", root.dnsCommand(provider)] + actionProc.command = ["omarchy-dns", provider] actionProc.running = true } @@ -943,8 +938,8 @@ Panel { implicitWidth: networkManagerAvailable ? button.implicitWidth : 0 implicitHeight: networkManagerAvailable ? button.implicitHeight : 0 - Component.onCompleted: if (networkManagerAvailable) refresh() - onNetworkManagerAvailableChanged: if (networkManagerAvailable) refresh() + AfterStartup { onTriggered: if (root.networkManagerAvailable) root.refresh() } + onNetworkManagerAvailableChanged: if (networkManagerAvailable && (Startup.ready || opened)) refresh() // Pulls everything we want about the active route's interface in one shot. Process { @@ -998,7 +993,7 @@ Panel { id: bandPoll interval: 4000 repeat: true - running: root.opened + running: root.opened && !!root.wifiDevice onTriggered: { if (bandProc.running) return bandProc.command = ["omarchy-network-band"] @@ -1123,7 +1118,7 @@ Panel { // The content, for a host that shows it as a page (the control center). readonly property Component pageContent: panel.content - KeyboardPanel { + LazyKeyboardPanel { id: panel anchorItem: button owner: root diff --git a/desktop/shell/shell/plugins/panels/network/Status.qml b/desktop/shell/shell/plugins/panels/network/Status.qml index 6f21d166..4818ee0c 100644 --- a/desktop/shell/shell/plugins/panels/network/Status.qml +++ b/desktop/shell/shell/plugins/panels/network/Status.qml @@ -81,8 +81,21 @@ Item { activeApSignalGeneration++ } + FileView { id: wireless; path: "/proc/net/wireless"; printErrors: false } function pollActiveApSignal() { - if (activeApSignalProc.running) return + if (activeApSignalProc.running || !wifiDevice) return + // cfg80211 exposes the current link RSSI on many drivers even when + // NetworkManager has no strength for the profile. Read it without a scan. + wireless.reload() + wireless.waitForJob() + var lines = wireless.text().split("\n") + for (var line of lines) { + var m = /^\s*([^:]+):\s+\S+\s+\S+\s+(-\d+)\.?\s/.exec(line) + if (m && m[1] === wifiDevice.name && Number(m[2]) >= -120) { + activeApSignal = Math.max(1, Math.min(100, (Number(m[2]) + 100) * 2)) + return + } + } activeApSignalRequest = activeApSignalGeneration activeApSignalProc.running = true } diff --git a/desktop/shell/shell/plugins/panels/power/Panel.qml b/desktop/shell/shell/plugins/panels/power/Panel.qml index c41758f0..b564525b 100644 --- a/desktop/shell/shell/plugins/panels/power/Panel.qml +++ b/desktop/shell/shell/plugins/panels/power/Panel.qml @@ -14,11 +14,8 @@ Panel { // manageIpc: false so this panel can own the single IpcHandler the target // permits — needed for the togglePercentage method below. manageIpc: false - // Orchard: the battery state lives in Status.qml, which the status cluster - // and the lock share; these names stay the panel's. - Status { id: status } - readonly property var batteryInfo: status.batteryInfo - readonly property bool externalPower: status.externalPower + readonly property var batteryInfo: Commons.BatteryStatus.batteryInfo + readonly property bool externalPower: Commons.BatteryStatus.externalPower property var profiles: [] property string activeProfile: "" property int profileIndex: 0 @@ -28,9 +25,9 @@ Panel { // icon, so the open-panel mark takes the painted width instead of the // icon-sized fraction of the slot the fallback assumes. readonly property real openPanelIndicatorWidth: showPercentage && !button.vertical ? button.glyphPaintedWidth : 0 - readonly property var batteryDevice: status.batteryDevice - readonly property bool batteryPresent: status.batteryPresent - readonly property var displayedPercentage: status.displayedPercentage + readonly property var batteryDevice: Commons.BatteryStatus.batteryDevice + readonly property bool batteryPresent: Commons.BatteryStatus.batteryPresent + readonly property var displayedPercentage: Commons.BatteryStatus.displayedPercentage function upowerStates() { return { @@ -157,8 +154,8 @@ Panel { : Commons.I18n.t("power.noBattery", "No battery found") function refresh() { - status.refresh() - if (!profilesProc.running) profilesProc.running = true + Commons.BatteryStatus.refresh() + if (ShellFacts.hasReader("powerprofilesctl") && !profilesProc.running && !root.profiles.length) profilesProc.running = true } function updateProfiles(raw) { @@ -220,10 +217,10 @@ Panel { onBatteryPresentChanged: { if (!batteryPresent && !hosted) close() - else Qt.callLater(root.refresh) + else if (Startup.ready || opened) Qt.callLater(root.refresh) } - Component.onCompleted: refresh() + AfterStartup { onTriggered: root.refresh() } visible: batteryPresent implicitWidth: batteryPresent ? button.implicitWidth : 0 @@ -237,16 +234,24 @@ Panel { Process { id: actionProc - onExited: root.refresh() + onExited: refreshProfiles.restart() } + // Get the installed list once. PowerProfiles delivers external changes + // (including the performance profile becoming available) over D-Bus. + Connections { + target: ShellFacts.hasReader("powerprofilesctl") ? PowerProfiles : null + function onProfileChanged() { refreshProfiles.restart() } + function onHasPerformanceProfileChanged() { refreshProfiles.restart() } + } + Connections { + target: ShellFacts + function onUpdated() { root.refresh() } + } Timer { - interval: 1000 - // The battery reading is Status.qml's own; open, the profiles too. - running: root.opened - repeat: true - triggeredOnStart: true - onTriggered: root.refresh() + id: refreshProfiles + interval: 100 + onTriggered: if (profilesProc.running) restart(); else profilesProc.running = true } // Rotate the status phrase while the panel is open and we're in a @@ -312,7 +317,7 @@ Panel { // The content, for a host that shows it as a page (the control center). readonly property Component pageContent: panel.content - KeyboardPanel { + LazyKeyboardPanel { id: panel anchorItem: button owner: root @@ -458,7 +463,7 @@ Panel { // Subtle pulse while charging — visible signal that energy is flowing in. SequentialAnimation on opacity { - running: root.charging && !root.fullyCharged && root.opened && !Style.reduceMotion + running: root.charging && !root.fullyCharged && root.opened && Style.animateLoops loops: Animation.Infinite alwaysRunToEnd: true NumberAnimation { from: 1.0; to: 0.55; duration: Style.duration(950); easing.type: Easing.InOutSine } diff --git a/desktop/shell/shell/plugins/panels/power/Status.qml b/desktop/shell/shell/plugins/panels/power/Status.qml deleted file mode 100644 index d668d8d8..00000000 --- a/desktop/shell/shell/plugins/panels/power/Status.qml +++ /dev/null @@ -1,67 +0,0 @@ -import QtQuick -import Quickshell -import Quickshell.Io -import Quickshell.Services.UPower -import "Model.js" as Model - -// Orchard: the battery state the bar's icon shows, apart from the panel, so -// the status cluster, the lock and the control center show the same thing. -// The panel binds its own properties of these names to it. -Item { - id: root - visible: false - - // The battery script's readings (omarchy-battery-status --shell), read - // every second: discovery must not depend on a charger event or on UPower. - property var batteryInfo: ({}) - readonly property bool externalPower: batteryInfo.external_power === "connected" - readonly property var batteryDevice: { - var device = UPower.displayDevice - if (device && device.isPresent) return device - var measured = Model.batteryPercentage(null, root.batteryInfo) - // Do not invent a charging/discharging state when only capacity is known. - return measured === null ? null : { isPresent: true, percentage: measured / 100, state: 0 } - } - readonly property bool batteryPresent: batteryDevice !== null - readonly property var displayedPercentage: Model.batteryPercentage(batteryDevice, batteryInfo) - readonly property bool discharging: { - var device = UPower.displayDevice - return !!(device && device.isPresent && device.state === UPowerDeviceState.Discharging) - } - readonly property string icon: Model.batteryIcon(batteryDevice, discharging, upowerStates(), externalPower) - - function upowerStates() { - return { - Charging: UPowerDeviceState.Charging, - Discharging: UPowerDeviceState.Discharging, - FullyCharged: UPowerDeviceState.FullyCharged, - PendingCharge: UPowerDeviceState.PendingCharge - } - } - - function refresh() { - if (!batteryProc.running) batteryProc.running = true - } - - function updateKeyValue(raw) { - var next = Model.parseKeyValue(raw) - // Keep last known good data if a refresh briefly returns nothing — happens - // around AC plug/unplug events. Avoids the section collapsing mid-transition. - if (Object.keys(next).length > 0) batteryInfo = next - else batteryInfo = Object.assign({}, batteryInfo, { external_power: "unknown" }) - } - - Process { - id: batteryProc - command: ["omarchy-battery-status", "--shell"] - stdout: StdioCollector { waitForEnd: true; onStreamFinished: root.updateKeyValue(text) } - } - - Timer { - interval: 1000 - running: true - repeat: true - triggeredOnStart: true - onTriggered: root.refresh() - } -} diff --git a/desktop/shell/shell/plugins/panels/tailscale/Panel.qml b/desktop/shell/shell/plugins/panels/tailscale/Panel.qml index 40f46b65..961cb9ee 100644 --- a/desktop/shell/shell/plugins/panels/tailscale/Panel.qml +++ b/desktop/shell/shell/plugins/panels/tailscale/Panel.qml @@ -554,7 +554,7 @@ Panel { } } - KeyboardPanel { + LazyKeyboardPanel { id: panel anchorItem: button owner: root @@ -1211,7 +1211,7 @@ Panel { opacity: accountRow.switchingAccount || accountRow.renameInFlight ? 0.45 : 1.0 SequentialAnimation on opacity { - running: (accountRow.switchingAccount || accountRow.renameInFlight) && !Style.reduceMotion + running: (accountRow.switchingAccount || accountRow.renameInFlight) && Style.animateLoops NumberAnimation { to: 1.0; duration: Style.duration(420); easing.type: Easing.InOutQuad } NumberAnimation { to: 0.45; duration: Style.duration(420); easing.type: Easing.InOutQuad } loops: Animation.Infinite @@ -1455,7 +1455,7 @@ Panel { anchors.verticalCenter: parent.verticalCenter NumberAnimation on rotation { - running: exitNodeRow.settingExitNode && !Style.reduceMotion + running: exitNodeRow.settingExitNode && Style.animateLoops from: 0 to: 360 duration: Style.duration(900) diff --git a/desktop/shell/shell/plugins/panels/tailscale/Service.qml b/desktop/shell/shell/plugins/panels/tailscale/Service.qml index 2d3c6a21..f4d091ac 100644 --- a/desktop/shell/shell/plugins/panels/tailscale/Service.qml +++ b/desktop/shell/shell/plugins/panels/tailscale/Service.qml @@ -489,7 +489,7 @@ Item { id: refreshTimer interval: root.refreshIntervalSec * 1000 repeat: true - running: true + running: Startup.ready triggeredOnStart: true onTriggered: root.refresh() } @@ -502,7 +502,7 @@ Item { property int ticks: 0 interval: 2000 repeat: true - running: true + running: Startup.ready onTriggered: { ticks += 1 if (root.running || ticks >= 15) startupRamp.running = false diff --git a/desktop/shell/shell/plugins/panels/weather/Panel.qml b/desktop/shell/shell/plugins/panels/weather/Panel.qml index f17ce8d9..779beba0 100644 --- a/desktop/shell/shell/plugins/panels/weather/Panel.qml +++ b/desktop/shell/shell/plugins/panels/weather/Panel.qml @@ -24,9 +24,8 @@ Panel { property var hostWidget: null readonly property var barIdentity: hostWidget || root - // Open-Meteo's API answers curl's default User-Agent with 403 Forbidden, - // which leaves the forecast fetch failing and the bar widget hidden. - // Identify the caller the way the API asks and the same query answers 200. + // Open-Meteo asks API clients to identify themselves. A generic user agent + // can receive a 403 and leave the weather card empty. readonly property string openMeteoUserAgent: "omarchy-shell (+https://github.com/omacom/omarchy)" function open() { @@ -73,7 +72,7 @@ Panel { property var detectedLocationState: ({ name: "", latitude: null, longitude: null }) property bool detectingLocation: false readonly property bool autoLocation: Model.isAutoLocation(configuredLocationState) - onAutoLocationChanged: if (autoLocation) detectLocation() + onAutoLocationChanged: if (autoLocation && (Startup.ready || opened)) detectLocation() // The query is the wttr.in path segment (coordinates when known, else the // encoded name); empty means wttr.in's own IP auto-detect, used only when @@ -88,9 +87,9 @@ Panel { if (savingLocation) savingLocationQueryStarted = true forecastRetries = 0 dailyForecastRetries = 0 - forecastProc.running = false - dailyForecastProc.running = false - Qt.callLater(refresh) + forecastProc.cancel() + dailyForecastProc.cancel() + if (Startup.ready || opened) Qt.callLater(refresh) } property FileView locationFile: FileView { @@ -108,7 +107,7 @@ Panel { // state doesn't change locationQuery and so triggers no refetch. Timer { interval: 1500 - running: true + running: Startup.ready onTriggered: locationFile.reload() } @@ -165,7 +164,7 @@ Panel { // rather than have wttr.in look this machine up. Its answer, or its // failure, refreshes again. if (detectingLocation && locationQuery === "") return - if (!forecastProc.running) forecastProc.running = true + if (!forecastProc.running) forecastProc.get("https://wttr.in/" + root.locationQuery + "?format=j1") // With coordinates this fetches open-meteo right away — no need to wait // for the slow wttr response. Without them it's a no-op until wttr // reports the area. @@ -175,7 +174,7 @@ Panel { function detectLocation() { if (locationProc.running) return detectingLocation = true - locationProc.running = true + locationProc.get("https://geo.omarchy.org/") } function refreshDailyForecast(sourceReport) { @@ -198,8 +197,7 @@ Panel { + "¤t=temperature_2m,apparent_temperature,relative_humidity_2m,wind_speed_10m,weather_code,is_day" + "&forecast_days=4" + "&timezone=auto" - dailyForecastProc.command = ["curl", "-fsS", "--max-time", "5", "-A", root.openMeteoUserAgent, url] - dailyForecastProc.running = true + dailyForecastProc.get(url) } // ---- Location editing. Clicking the location label swaps it for a search @@ -283,7 +281,7 @@ Panel { locationSaveProc.running = true } - // Debounced geocoding. Only one curl runs at a time; if the query moved on + // Debounced geocoding. Only one request runs at a time; if the query moved on // while a fetch was in flight, the latest query is fetched right after. function requestGeocode() { var locationField = root.locationInput() @@ -298,9 +296,7 @@ Panel { function startGeocode() { geocodeActiveQuery = geocodePendingQuery - geocodeProc.command = ["curl", "-fsS", "--max-time", "5", "-A", root.openMeteoUserAgent, - "https://geocoding-api.open-meteo.com/v1/search?name=" + encodeURIComponent(geocodeActiveQuery) + "&count=5&language=en&format=json"] - geocodeProc.running = true + geocodeProc.get("https://geocoding-api.open-meteo.com/v1/search?name=" + encodeURIComponent(geocodeActiveQuery) + "&count=5&language=en&format=json") } function buildForecastDays() { @@ -355,34 +351,31 @@ Panel { return Model.iconForCode(code, night) } - Process { + WeatherRequest { id: forecastProc - command: ["curl", "-fsS", "--max-time", "10", "https://wttr.in/" + root.locationQuery + "?format=j1"] - stdout: StdioCollector { - waitForEnd: true - onStreamFinished: { - var raw = String(text || "").trim() - if (!raw) { - root.scheduleForecastRetry() - return - } - try { - var parsed = JSON.parse(raw) - root.report = parsed - if (!root.hasConfiguredCoordinates) - root.label = Model.provisionalCurrentIcon(parsed.current_condition && parsed.current_condition[0], root.label) - root.forecastRetries = 0 - if (Model.weatherResponseCompletesSave(root.hasConfiguredCoordinates, "wttr")) - root.finishSavingLocation() - // Known coordinates already drove the fast open-meteo fetch from - // refresh(); only a name, or wttr's own IP lookup, needs the area - // wttr reported. - if (!root.hasCoordinates) - root.refreshDailyForecast(parsed) - } catch (e) { - // Keep last-good report visible, but try again shortly. - root.scheduleForecastRetry() - } + timeoutMs: 10000 + onFinished: function(text) { + var raw = String(text || "").trim() + if (!raw) { + root.scheduleForecastRetry() + return + } + try { + var parsed = JSON.parse(raw) + root.report = parsed + if (!root.hasConfiguredCoordinates) + root.label = Model.provisionalCurrentIcon(parsed.current_condition && parsed.current_condition[0], root.label) + root.forecastRetries = 0 + if (Model.weatherResponseCompletesSave(root.hasConfiguredCoordinates, "wttr")) + root.finishSavingLocation() + // Known coordinates already drove the fast open-meteo fetch from + // refresh(); only a name, or wttr's own IP lookup, needs the area + // wttr reported. + if (!root.hasCoordinates) + root.refreshDailyForecast(parsed) + } catch (e) { + // Keep last-good report visible, but try again shortly. + root.scheduleForecastRetry() } } } @@ -398,7 +391,7 @@ Panel { Timer { id: forecastRetryTimer interval: 2500 - onTriggered: if (!forecastProc.running) forecastProc.running = true + onTriggered: if (!forecastProc.running) forecastProc.get("https://wttr.in/" + root.locationQuery + "?format=j1") } // With configured coordinates this fetch is the only thing that updates the @@ -416,41 +409,39 @@ Panel { onTriggered: root.refreshDailyForecast(null) } - Process { + WeatherRequest { id: dailyForecastProc - stdout: StdioCollector { - waitForEnd: true - onStreamFinished: { - var raw = String(text || "").trim() - if (!raw) { - root.scheduleDailyForecastRetry() - return - } - try { - var parsed = JSON.parse(raw) - var parsedCurrent = Model.openMeteoCurrentCondition(parsed) - root.dailyForecastReport = parsed - root.label = Model.currentIcon(parsedCurrent, root.label) - root.dailyForecastRetries = 0 - if (Model.weatherResponseCompletesSave(root.hasConfiguredCoordinates, "open-meteo")) - root.finishSavingLocation() - } catch (e) { - // Keep last-good daily forecast visible, but try again shortly. - root.scheduleDailyForecastRetry() - } + timeoutMs: 5000 + userAgent: root.openMeteoUserAgent + onFinished: function(text) { + var raw = String(text || "").trim() + if (!raw) { + root.scheduleDailyForecastRetry() + return + } + try { + var parsed = JSON.parse(raw) + var parsedCurrent = Model.openMeteoCurrentCondition(parsed) + root.dailyForecastReport = parsed + root.label = Model.currentIcon(parsedCurrent, root.label) + root.dailyForecastRetries = 0 + if (Model.weatherResponseCompletesSave(root.hasConfiguredCoordinates, "open-meteo")) + root.finishSavingLocation() + } catch (e) { + // Keep last-good daily forecast visible, but try again shortly. + root.scheduleDailyForecastRetry() } } } - Process { + WeatherRequest { id: geocodeProc - stdout: StdioCollector { - waitForEnd: true - onStreamFinished: { - root.locationSuggestions = root.editingLocation ? Model.parseGeocodingResults(text) : [] - root.suggestionIndex = 0 - if (root.geocodePendingQuery !== root.geocodeActiveQuery) Qt.callLater(root.startGeocode) - } + timeoutMs: 5000 + userAgent: root.openMeteoUserAgent + onFinished: function(text) { + root.locationSuggestions = root.editingLocation ? Model.parseGeocodingResults(text) : [] + root.suggestionIndex = 0 + if (root.geocodePendingQuery !== root.geocodeActiveQuery) Qt.callLater(root.startGeocode) } } @@ -472,8 +463,8 @@ Panel { root.savingLocationQueryStarted = true root.forecastRetries = 0 root.dailyForecastRetries = 0 - forecastProc.running = false - dailyForecastProc.running = false + forecastProc.cancel() + dailyForecastProc.cancel() Qt.callLater(root.refresh) } } @@ -481,23 +472,20 @@ Panel { // Omarchy's own lookup: city and coordinates from Cloudflare's view of // this network, in weather.json's shape. - Process { + WeatherRequest { id: locationProc - command: ["curl", "-fsS", "--max-time", "4", "https://geo.omarchy.org/"] - stdout: StdioCollector { - waitForEnd: true - onStreamFinished: { - root.detectingLocation = false - var detected = Model.parseLocationFile(text) - var query = Model.wttrLocationQuery(detected.name, detected.latitude, detected.longitude) - // A new place changes locationQuery, which refreshes. An unchanged - // one was already fetched; a failure keeps the last place, or with - // none falls back to wttr.in's own lookup. - if (query !== "" && query !== root.locationQuery) - root.detectedLocationState = detected - else if (root.locationQuery === "") - root.refresh() - } + timeoutMs: 4000 + onFinished: function(text) { + root.detectingLocation = false + var detected = Model.parseLocationFile(text) + var query = Model.wttrLocationQuery(detected.name, detected.latitude, detected.longitude) + // A new place changes locationQuery, which refreshes. An unchanged + // one was already fetched; a failure keeps the last place, or with + // none falls back to wttr.in's own lookup. + if (query !== "" && query !== root.locationQuery) + root.detectedLocationState = detected + else if (root.locationQuery === "") + root.refresh() } } @@ -506,12 +494,12 @@ Panel { // scheduled refresh. Restarting the timer fetches at once (triggeredOnStart) // and counts the next scheduled refresh from there. readonly property bool online: Networking.connectivity === NetworkConnectivity.Full - onOnlineChanged: if (online) refreshTimer.restart() + onOnlineChanged: if (online && Startup.ready) refreshTimer.restart() Timer { id: refreshTimer interval: root.refreshMinutes * 60 * 1000 - running: true + running: Startup.ready repeat: true triggeredOnStart: true onTriggered: { @@ -531,7 +519,7 @@ Panel { function edit(): void { root.openFromHotkey(); root.startEditingLocation() } } - KeyboardPanel { + LazyKeyboardPanel { id: panel anchorItem: root.anchorItem owner: root.barIdentity @@ -709,7 +697,7 @@ Panel { font.pixelSize: Style.font.bodySmall RotationAnimator on rotation { - running: root.savingLocation && !Style.reduceMotion + running: root.savingLocation && Style.animateLoops from: 0; to: 360 duration: Style.duration(800) loops: Animation.Infinite diff --git a/desktop/shell/shell/plugins/panels/weather/WeatherRequest.qml b/desktop/shell/shell/plugins/panels/weather/WeatherRequest.qml new file mode 100644 index 00000000..db4e5f90 --- /dev/null +++ b/desktop/shell/shell/plugins/panels/weather/WeatherRequest.qml @@ -0,0 +1,39 @@ +import QtQuick + +// A cancellable asynchronous GET. A superseded response belongs to the old +// location and must not update the card or consume the new retry budget. +QtObject { + id: root + required property int timeoutMs + property string userAgent: "" + property var request: null + readonly property bool running: request !== null + signal finished(string text) + + function cancel() { + var previous = request + request = null + deadline.stop() + if (previous) previous.abort() + } + function get(url) { + cancel() + var xhr = new XMLHttpRequest() + request = xhr + xhr.onreadystatechange = function() { + if (root.request !== xhr || xhr.readyState !== XMLHttpRequest.DONE) return + deadline.stop() + root.request = null + root.finished(xhr.status >= 200 && xhr.status < 300 ? xhr.responseText : "") + } + xhr.open("GET", url) + if (userAgent) xhr.setRequestHeader("User-Agent", userAgent) + deadline.restart() + xhr.send() + } + readonly property Timer deadline: Timer { + interval: root.timeoutMs + onTriggered: { root.cancel(); root.finished("") } + } + Component.onDestruction: cancel() +} diff --git a/desktop/shell/shell/plugins/polkit/PolkitAgent.qml b/desktop/shell/shell/plugins/polkit/PolkitAgent.qml index a2d662ba..68fc9f06 100644 --- a/desktop/shell/shell/plugins/polkit/PolkitAgent.qml +++ b/desktop/shell/shell/plugins/polkit/PolkitAgent.qml @@ -46,10 +46,10 @@ Item { // a password — including immediately when the lid is shut and the clamshell // gate skips pam_fprintd — we switch to the password field instead. readonly property bool fingerprintMode: fingerprintConfigured && !laptopClosed && dialogVisible && !responseRequired && !submitted && !errorFlash - readonly property int cardHeight: panel.height > 0 ? Math.min(fieldHeight + contentMargin * 2, panel.height - Style.gapsOut * 2) : fieldHeight + contentMargin * 2 + readonly property int cardHeight: !panel ? 0 : panel.height > 0 ? Math.min(fieldHeight + contentMargin * 2, panel.height - Style.gapsOut * 2) : fieldHeight + contentMargin * 2 // Password mode is a wide field; fingerprint mode collapses to a square that // just frames the centered sensor icon. - readonly property int cardWidth: fingerprintMode ? cardHeight : Math.min(Style.space(312), Math.max(Style.space(260), panel.width - Style.gapsOut * 2)) + readonly property int cardWidth: !panel ? 0 : fingerprintMode ? cardHeight : Math.min(Style.space(312), Math.max(Style.space(260), panel.width - Style.gapsOut * 2)) function authorizationLabel(message) { return message ? PolkitModel.authorizationLabel(message, I18n.t) : I18n.t("polkit.authenticationNeeded") @@ -72,7 +72,7 @@ Item { failed = false errorFlash = false submitted = false - passwordInput.text = "" + if (passwordInput) passwordInput.text = "" } function syncFromFlow() { @@ -90,10 +90,11 @@ Item { } function beginFlow() { + windowLoader.load() closeTimer.stop() closing = false submitted = false - passwordInput.text = "" + if (passwordInput) passwordInput.text = "" refreshLidState() syncFromFlow() Qt.callLater(refocus) @@ -113,13 +114,13 @@ Item { submitted = true errorFlash = false flow.submit(passwordInput.text) - passwordInput.text = "" + if (passwordInput) passwordInput.text = "" keyCatcher.forceActiveFocus() } function cancelRequest() { var flow = polkitAgent.flow - passwordInput.text = "" + if (passwordInput) passwordInput.text = "" submitted = false closing = true closeTimer.restart() @@ -129,7 +130,7 @@ Item { function triggerFailureFeedback() { submitted = false errorFlash = true - passwordInput.text = "" + if (passwordInput) passwordInput.text = "" errorTimer.restart() shakeAnimation.restart() Qt.callLater(refocus) @@ -194,7 +195,7 @@ Item { function onIsResponseRequiredChanged() { root.syncFromFlow() - if (!polkitAgent.flow || !polkitAgent.flow.isResponseRequired) passwordInput.text = "" + if (passwordInput && (!polkitAgent.flow || !polkitAgent.flow.isResponseRequired)) passwordInput.text = "" Qt.callLater(root.refocus) } @@ -219,8 +220,14 @@ Item { } } - PanelWindow { + readonly property var panel: windowLoader.item + readonly property var keyCatcher: panel ? panel.keyCatcher : null + readonly property var passwordInput: panel ? panel.passwordInput : null + OnDemandLoader { id: windowLoader; requested: root.dialogVisible; sourceComponent: windowComponent } + property Component windowComponent: PanelWindow { id: panel + property alias keyCatcher: keyCatcher + property alias passwordInput: passwordInput // Right-to-left languages read this window mirrored. Binding { target: panel.contentItem; property: "LayoutMirroring.enabled"; value: Commons.I18n.rightToLeft } Binding { target: panel.contentItem; property: "LayoutMirroring.childrenInherit"; value: true } diff --git a/desktop/shell/shell/plugins/reminders/ReminderFlow.qml b/desktop/shell/shell/plugins/reminders/ReminderFlow.qml index e99650dc..c5446181 100644 --- a/desktop/shell/shell/plugins/reminders/ReminderFlow.qml +++ b/desktop/shell/shell/plugins/reminders/ReminderFlow.qml @@ -27,8 +27,8 @@ Item { readonly property int cornerRadius: Style.cornerRadius property int contentMargin: Style.spacing.panelPadding property int headerHeight: Math.max(Style.space(34), Style.font.title + Style.spacing.controlPaddingY * 2) - property int cardWidth: Math.min(Style.space(300), panel.width - Style.gapsOut * 2) - property int cardHeight: Math.min(contentMargin * 2 + headerHeight, panel.height - Style.gapsOut * 2) + property int cardWidth: !panel ? 0 : Math.min(Style.space(300), panel.width - Style.gapsOut * 2) + property int cardHeight: !panel ? 0 : Math.min(contentMargin * 2 + headerHeight, panel.height - Style.gapsOut * 2) readonly property string promptText: root.step === "message" ? I18n.t("reminders.messagePrompt") : I18n.t("reminders.minutesPrompt") function open(payloadJson) { @@ -93,9 +93,13 @@ Item { } } - OverlayWindow { + readonly property var panel: windowLoader.item + readonly property var keyCatcher: panel ? panel.keyCatcher : null + OnDemandLoader { id: windowLoader; requested: root.opened; sourceComponent: root.windowComponent } + property Component windowComponent: OverlayWindow { id: panel - shown: root.opened + property alias keyCatcher: keyCatcher + shown: !!windowLoader.item && root.opened WlrLayershell.namespace: "omarchy-reminders" Rectangle { diff --git a/desktop/shell/shell/plugins/services/battery/Service.qml b/desktop/shell/shell/plugins/services/battery/Service.qml index ce4a4089..d741c6ab 100644 --- a/desktop/shell/shell/plugins/services/battery/Service.qml +++ b/desktop/shell/shell/plugins/services/battery/Service.qml @@ -126,7 +126,7 @@ Item { Timer { interval: 30000 - running: true + running: Startup.ready repeat: true triggeredOnStart: true onTriggered: root.checkBattery() @@ -141,5 +141,5 @@ Item { } } - Component.onCompleted: root.refreshPowerProfile() + AfterStartup { onTriggered: root.refreshPowerProfile() } } diff --git a/desktop/shell/shell/plugins/services/media/BarWidget.qml b/desktop/shell/shell/plugins/services/media/BarWidget.qml index b4c9a7d3..4be1e7b6 100644 --- a/desktop/shell/shell/plugins/services/media/BarWidget.qml +++ b/desktop/shell/shell/plugins/services/media/BarWidget.qml @@ -69,7 +69,7 @@ BarWidget { // track is playing and the bar is on screen to show it. NumberAnimation on x { id: scrollAnim - running: labelText.needsScroll && root.isPlaying && root.visible && !root.bar.barHidden && !root.popupOpen && !root.bar.vertical && !Style.reduceMotion + running: labelText.needsScroll && root.isPlaying && root.visible && !root.bar.barHidden && !root.popupOpen && !root.bar.vertical && Style.animateLoops // Stopped, the title reads from its start again. onRunningChanged: if (!running) labelText.x = 0 loops: Animation.Infinite @@ -107,12 +107,13 @@ BarWidget { onExited: if (root.bar) root.bar.hideTooltip(root) } - PopupCard { + OnDemandLoader { id: popupLoader; requested: root.popupOpen; sourceComponent: root.popupComponent } + property Component popupComponent: PopupCard { id: popup anchorItem: root bar: root.bar owner: root - open: root.popupOpen + open: !!popupLoader.item && root.popupOpen contentWidth: popup.fittedContentWidth(Style.space(320)) contentHeight: popup.fittedContentHeight(column.implicitHeight) @@ -133,7 +134,7 @@ BarWidget { borderSpec: Border.controlSpec("normal", root.bar.foreground, Commons.Color.accent) // Decode the art at the size it is drawn, not the size the player - // serves it at. The popup is built on every monitor at startup. + // serves it at. SizedImage { anchors.fill: parent anchors.margins: Style.space(2) diff --git a/desktop/shell/shell/plugins/services/media/Service.qml b/desktop/shell/shell/plugins/services/media/Service.qml index 86c5cca3..e45c5d7f 100644 --- a/desktop/shell/shell/plugins/services/media/Service.qml +++ b/desktop/shell/shell/plugins/services/media/Service.qml @@ -15,8 +15,10 @@ Item { property var pendingTrackOsd: null property int playSerial: 0 - readonly property var players: Mpris.players ? Mpris.players.values : [] - readonly property var nodes: Pipewire.nodes ? Pipewire.nodes.values : [] + property bool mediaRequested: false + readonly property bool watchMedia: Startup.ready || mediaRequested + readonly property var players: watchMedia && Mpris.players ? Mpris.players.values : [] + readonly property var nodes: watchMedia && Pipewire.nodes ? Pipewire.nodes.values : [] readonly property var playbackStreams: { var list = [] for (var i = 0; i < nodes.length; i++) { @@ -257,6 +259,7 @@ Item { } function selectPlayer(key) { + mediaRequested = true var player = playerForKey(key) if (!player || !hasMetadata(player)) return false preferredPlayerKey = playerKey(player) @@ -286,6 +289,7 @@ Item { } function switchSource(delta, transferPlayback, showFeedback) { + mediaRequested = true var list = sourceCyclePlayers if (!list || list.length === 0) return false @@ -340,6 +344,7 @@ Item { } function runAction(action, showFeedback, targetKey) { + mediaRequested = true var player = playerForAction(action, targetKey) var key = playerKey(player) var actionLabel = I18n.t("media.playPause") @@ -406,7 +411,6 @@ Item { // syncPlayingOrder only depends on the set of players and each player's // isPlaying state: onPlayersChanged covers players appearing/disappearing, // and the Instantiator wires isPlayingChanged for each live player. - Component.onCompleted: root.syncPlayingOrder() onPlayersChanged: root.syncPlayingOrder() Instantiator { @@ -477,6 +481,7 @@ Item { PwObjectTracker { objects: root.defaultSink ? [root.defaultSink] : [] } function statusJson() { + mediaRequested = true var p = activePlayer return JSON.stringify({ hasPlayer: p !== null, diff --git a/desktop/shell/shell/plugins/services/nightlight/Service.qml b/desktop/shell/shell/plugins/services/nightlight/Service.qml index 90bce7f9..b6028613 100644 --- a/desktop/shell/shell/plugins/services/nightlight/Service.qml +++ b/desktop/shell/shell/plugins/services/nightlight/Service.qml @@ -86,7 +86,7 @@ Item { } } - Component.onCompleted: refresh() + AfterStartup { onTriggered: root.refresh() } ShellIpc { target: "nightlight" diff --git a/desktop/shell/shell/plugins/services/remote-session/Service.qml b/desktop/shell/shell/plugins/services/remote-session/Service.qml index fd94248a..c76e0eaa 100644 --- a/desktop/shell/shell/plugins/services/remote-session/Service.qml +++ b/desktop/shell/shell/plugins/services/remote-session/Service.qml @@ -1,4 +1,5 @@ import QtQuick +import qs.Commons import Quickshell import Quickshell.Hyprland import Quickshell.Io @@ -53,7 +54,7 @@ Item { root.stateLoaded = true } - Component.onCompleted: refresh() + AfterStartup { onTriggered: root.refresh() } Component.onDestruction: root.setCaptureOverride(false, true) // gliff-server captures the screen through ext-image-copy-capture, so a diff --git a/desktop/shell/shell/plugins/status/RotationLock.qml b/desktop/shell/shell/plugins/status/RotationLock.qml index 776eaf75..0440051f 100644 --- a/desktop/shell/shell/plugins/status/RotationLock.qml +++ b/desktop/shell/shell/plugins/status/RotationLock.qml @@ -1,9 +1,10 @@ import QtQuick +import qs.Commons import Quickshell import Quickshell.Io // Whether rotation is locked: omarchy-rotation-lock's file, which only exists -// while it is. Read every two seconds, as a missing file cannot be watched. +// while it is. The parent watch also sees creation and removal. // And whether there is anything to lock: iio-sensor-proxy's accelerometer, // which the rotation daemon follows. Without one the lock is unavailable. Item { @@ -22,7 +23,7 @@ Item { root.sensor = exitCode === 0 && probeOut.text.trim() === "b true" } } - Component.onCompleted: probe.running = true + AfterStartup { onTriggered: probe.running = true } // The proxy may still be starting when the shell does: ask once more. Timer { interval: 10000 @@ -32,15 +33,11 @@ Item { FileView { id: file + watchChanges: true + onFileChanged: reload() path: (Quickshell.env("XDG_CONFIG_HOME") || (Quickshell.env("HOME") + "/.config")) + "/omarchy/rotation-lock" printErrors: false onLoaded: root.locked = true onLoadFailed: root.locked = false } - Timer { - interval: 2000 - running: true - repeat: true - onTriggered: file.reload() - } } diff --git a/desktop/shell/shell/plugins/status/StatusCluster.qml b/desktop/shell/shell/plugins/status/StatusCluster.qml index 64bb50ee..c4ded7d4 100644 --- a/desktop/shell/shell/plugins/status/StatusCluster.qml +++ b/desktop/shell/shell/plugins/status/StatusCluster.qml @@ -3,9 +3,7 @@ import Quickshell import Quickshell.Services.Pipewire import qs.Commons import qs.Commons as Commons -import "../panels/network" as Network import "../panels/bluetooth" as BluetoothStatus -import "../panels/power" as Power // The status cluster (SHELL-SPEC, step 2): mic muted, rotation lock, Focus // and Stay Awake while on, Bluetooth while on, Wi-Fi, battery percentage and @@ -26,10 +24,10 @@ Row { spacing: Style.space(10) - Network.Status { id: network } + readonly property var network: SessionStatus.network BluetoothStatus.Status { id: bluetooth } - Power.Status { id: battery } - RotationLock { id: rotation } + readonly property var battery: Commons.BatteryStatus + readonly property var rotation: SessionStatus.rotation readonly property var source: Pipewire.defaultAudioSource PwObjectTracker { objects: root.source ? [root.source] : [] } diff --git a/desktop/shell/shell/services/AppLibrary.qml b/desktop/shell/shell/services/AppLibrary.qml index e68dec16..1f0fc40c 100644 --- a/desktop/shell/shell/services/AppLibrary.qml +++ b/desktop/shell/shell/services/AppLibrary.qml @@ -3,6 +3,7 @@ import Quickshell import Quickshell.Io import Quickshell.Wayland import qs.Commons +import "../launcher/LauncherModel.js" as LauncherModel import "AppSearch.js" as AppSearch // Shared desktop-application library: the sorted entry list with hidden-entry @@ -11,8 +12,10 @@ import "AppSearch.js" as AppSearch Item { id: root + readonly property LauncherBackdrop backdrop: LauncherBackdrop {} property string omarchyPath: Quickshell.env("OMARCHY_PATH") + readonly property bool indexActive: Startup.ready property var configuredHiddenEntryIds: ({}) property var desktopHiddenEntryIds: ({}) // Desktop id -> X-Omarchy-Dock-Click, which Quickshell doesn't parse. @@ -35,10 +38,12 @@ Item { readonly property string userIconsPath: (Quickshell.env("XDG_DATA_HOME") || home + "/.local/share") + "/icons/" property int themeRevision: 0 - // Maps a desktop id to the version of the package that owns it. Rescanned - // each time the app grid opens, since upgrades leave desktop entries alone. + // The Orchard grid currently hides package versions. If enabled, populate + // them after startup and on package transactions, even with the grid closed. + readonly property bool showVersions: false property var versions: ({}) property var pendingVersions: ({}) + property bool versionRescanQueued: false property int launchSerial: 0 property int launchToplevelCount: 0 @@ -52,6 +57,7 @@ Item { // Emitted whenever the visible application set may have changed: desktop // entries appeared or vanished, or the hidden-entry filters reloaded. signal appsChanged() + signal packagesChanged() // Emitted when removing an entry has to open a terminal (a package // uninstall asking for a password), so an open launcher can step aside. @@ -71,7 +77,14 @@ Item { return root.configuredHiddenEntryIds[id] === true || root.desktopHiddenEntryIds[id] === true } + readonly property var allRows: indexActive ? searchEntries("") : [] + readonly property var entries: allRows.map(function(row) { return row.entry }) + function sortedEntries(query) { + return query ? searchEntries(query) : allRows + } + + function searchEntries(query) { var values = DesktopEntries.applications.values || [] return AppSearch.sortedEntries(values, query, function(entry) { return root.isHiddenEntry(entry) }) } @@ -91,17 +104,72 @@ Item { return Quickshell.iconPath("application-x-executable", true) } - // The shell may start before first-install packages have finished placing - // their icons; consumers call this when they open so icons appear live. + // Prepare only sizes actually used on the attached screens. The launcher + // and dock may be unmapped here, so there is no Qt Quick item to grab. + readonly property var rasterSizes: { + var sizes = new Set() + for (var screen of Quickshell.screens) { + var launcherSize = LauncherModel.iconSize(screen.width, screen.height, Style) + for (var size of [launcherSize, Style.space(36), Math.round(36 * Style.fontScale), Math.round(56 * Style.fontScale)]) { + var pixels = Math.round(size * screen.devicePixelRatio) + if (pixels > 0) sizes.add(pixels) + } + } + return Array.from(sizes) + } + property string dockIconNames: "[]" + property var rasterIndex: ({}) + property bool rasterPending: false + property bool iconsScanned: false + + function rasterSource(icon, pixels) { + var source = iconSource(icon) + var sizes = rasterIndex[source] + return (sizes && sizes[pixels]) || source + } + + function prepareRasters() { + if (!iconsScanned) return + if (rasterScan.running) { rasterPending = true; return } + rasterPending = false + var sources = new Set() + var names = JSON.parse(dockIconNames).concat(entries.map(entry => entry.icon)) + for (var name of names) { + var source = iconSource(name) + if (/^file:.*\.svg(?:\?|$)/i.test(source)) sources.add(source) + } + rasterScan.request = JSON.stringify({ sources: Array.from(sources), sizes: rasterSizes }) + rasterScan.running = true + } + onRasterSizesChanged: Qt.callLater(prepareRasters) + onDockIconNamesChanged: Qt.callLater(prepareRasters) + onEntriesChanged: if (iconsScanned) Qt.callLater(prepareRasters) + + Process { + id: rasterScan + property string request + command: ["python3", root.omarchyPath + "/shell/services/raster-icons.py"] + stdinEnabled: true + onStarted: { write(request + "\n"); request = "" } + stdout: StdioCollector { id: rasterResult } + onExited: function(code, status) { + if (!code && !status && rasterResult.text) root.rasterIndex = JSON.parse(rasterResult.text) + if (root.rasterPending) Qt.callLater(root.prepareRasters) + } + } + // A request during a scan queues one more, since the running scan may have // listed icons before they changed. function refreshIcons() { + if (!indexActive) return if (iconIndexScan.running) root.iconRescanQueued = true else iconIndexScan.running = true } function refreshVersions() { - if (!versionScan.running) versionScan.running = true + if (!showVersions || !indexActive) return + if (versionScan.running) versionRescanQueued = true + else versionScan.running = true } function version(entry) { @@ -300,7 +368,10 @@ Item { command: ["bash", "-c", root.desktopEntryScanCommand()] stdout: SplitParser { onRead: function(line) { desktopEntryOutput.text += line + "\n" } } onStarted: desktopEntryOutput.text = "" - onExited: root.loadDesktopEntryScan(desktopEntryOutput.text) + onExited: { + root.loadDesktopEntryScan(desktopEntryOutput.text) + desktopEntryOutput.text = "" + } } Process { @@ -312,6 +383,8 @@ Item { // newly found icons appear without rebuilding the list. onExited: { root.iconIndex = root.pendingIconIndex + root.iconsScanned = true + Qt.callLater(root.prepareRasters) if (root.iconRescanQueued) { root.iconRescanQueued = false running = true @@ -329,7 +402,13 @@ Item { } } onStarted: root.pendingVersions = ({}) - onExited: root.versions = root.pendingVersions + onExited: { + root.versions = root.pendingVersions + if (root.versionRescanQueued) { + root.versionRescanQueued = false + Qt.callLater(root.refreshVersions) + } + } } // Coalesces bursts of app-list changes (a package install touches many @@ -337,11 +416,26 @@ Item { Timer { id: iconIndexDebounce interval: 750 - onTriggered: if (!iconIndexScan.running) iconIndexScan.running = true + onTriggered: root.refreshIcons() + } + + FileView { + property bool transactionChanged: false + path: root.indexActive ? (Quickshell.env("OMARCHY_PACMAN_DB_PATH") || "/var/lib/pacman") + "/db.lck" : "" + watchChanges: true + printErrors: false + onFileChanged: { transactionChanged = true; reload() } + onLoadFailed: { + if (!transactionChanged) return + transactionChanged = false + root.packagesChanged() + iconIndexDebounce.restart() + root.refreshVersions() + } } FileView { - path: root.home + "/.local/state/omarchy/current/icons.revision" + path: root.indexActive ? root.home + "/.local/state/omarchy/current/icons.revision" : "" watchChanges: true printErrors: false onFileChanged: { @@ -386,7 +480,7 @@ Item { } Connections { - target: DesktopEntries.applications + target: root.indexActive ? DesktopEntries.applications : null function onValuesChanged() { desktopEntryScan.running = true iconIndexDebounce.restart() @@ -394,8 +488,13 @@ Item { } } - Component.onCompleted: { - desktopEntryScan.running = true - iconIndexScan.running = true + Timer { + interval: 0 + running: root.indexActive + onTriggered: { + desktopEntryScan.running = true + iconIndexScan.running = true + root.refreshVersions() + } } } diff --git a/desktop/shell/shell/services/BackgroundIntro.qml b/desktop/shell/shell/services/BackgroundIntro.qml index 62f667fb..7d5721f4 100644 --- a/desktop/shell/shell/services/BackgroundIntro.qml +++ b/desktop/shell/shell/services/BackgroundIntro.qml @@ -126,7 +126,7 @@ Item { // short, and the new still may still be decoding then. function finishTheme(token, cut) { if (token !== themeToken) return - themeCut = !!cut + themeCut = !Lite.enabled && !!cut if (backgroundReady || !backgroundService) revealTheme() else themeFinishing = true } @@ -276,7 +276,7 @@ Item { Component.onCompleted: { checked = true - if (!startupBackgroundPath && !startupPending) startupBackground.running = true + if (cover && !startupBackgroundPath && !startupPending) startupBackground.running = true // Orchard: without the cover there is no intro to play or wait for. if (cover) introProc.running = true } @@ -294,7 +294,7 @@ Item { // retain the current desktop and never map this startup cover. Variants { id: startupCovers - model: Quickshell.screens + model: root.startupPending ? Quickshell.screens : [] PanelWindow { required property var modelData @@ -327,7 +327,7 @@ Item { Variants { id: covers - model: Quickshell.screens + model: root.cover || root.themeBackground !== "" ? Quickshell.screens : [] PanelWindow { id: panel diff --git a/desktop/shell/shell/services/BarWidgetRegistry.qml b/desktop/shell/shell/services/BarWidgetRegistry.qml index 69491289..5b0578f4 100644 --- a/desktop/shell/shell/services/BarWidgetRegistry.qml +++ b/desktop/shell/shell/services/BarWidgetRegistry.qml @@ -14,11 +14,19 @@ QtObject { signal changed() function register(id, component, metadata) { + setEntry(id, { component: component, metadata: metadata || {} }) + } + + function registerDeferred(id, resolve, metadata) { + setEntry(id, { get component() { return resolve() }, metadata: metadata }) + } + + function setEntry(id, entry) { var key = String(id) if (!key) return var next = {} for (var k in widgets) next[k] = widgets[k] - next[key] = { component: component, metadata: metadata || {} } + next[key] = entry widgets = next revision++ changed() diff --git a/desktop/shell/shell/services/BrightnessKeys.qml b/desktop/shell/shell/services/BrightnessKeys.qml index 0f9818f5..afb90bbe 100644 --- a/desktop/shell/shell/services/BrightnessKeys.qml +++ b/desktop/shell/shell/services/BrightnessKeys.qml @@ -92,7 +92,7 @@ Item { Process { id: deviceProc command: ["omarchy-hw-display"] - running: true + running: Startup.ready && ShellFacts.hypr stdout: StdioCollector { waitForEnd: true onStreamFinished: root.device = String(text || "").trim() diff --git a/desktop/shell/shell/services/LauncherBackdrop.qml b/desktop/shell/shell/services/LauncherBackdrop.qml new file mode 100644 index 00000000..a75946b1 --- /dev/null +++ b/desktop/shell/shell/services/LauncherBackdrop.qml @@ -0,0 +1,129 @@ +import QtQuick +import Quickshell +import Quickshell.Io +import qs.Commons +import qs.Commons as Commons + +Item { + id: root + property var backgroundService + readonly property string stateDir: Quickshell.env("HOME") + "/.local/state/omarchy" + readonly property bool opaque: Lite.enabled || !frosted.present + readonly property string currentBackground: backgroundService ? backgroundService.currentBackground : "" + readonly property string wallpaper: { + var path = currentBackground || linkTarget + return Util.isVideoPath(path) ? "" : path + } + property string linkTarget: "" + + FileView { + id: frosted + property bool present: false + path: Startup.ready && !Lite.enabled ? root.stateDir + "/toggles/launcher-frosted" : "" + watchChanges: true + printErrors: false + onLoaded: present = true + onLoadFailed: present = false + onFileChanged: reload() + } + + // With the background plugin disabled (e.g. swaybg), follow the same link. + FileView { + id: backgroundLink + path: !root.opaque && !root.currentBackground ? root.stateDir + "/current/background" : "" + preload: false + watchChanges: true + onPathChanged: if (path) Qt.callLater(resolveLink) + onFileChanged: resolveLink() + property bool pending: false + function resolveLink() { + if (readLink.running) pending = true + else if (path) readLink.running = true + } + } + Process { + id: readLink + command: ["readlink", "-f", backgroundLink.path] + stdout: StdioCollector { id: linkOutput } + onExited: { + root.linkTarget = linkOutput.text.trim() + if (backgroundLink.pending) { + backgroundLink.pending = false + Qt.callLater(backgroundLink.resolveLink) + } + } + } + + // The frosted background: one file per wallpaper, theme colour and + // orientation, in the runtime directory. Both orientations are made + // together, so turning the iPad only switches between two ready images. + // How much of the theme's menu background lies over the blurred wallpaper. + readonly property real backdropTint: 0.8 + readonly property color backdropColor: Commons.Color.menu.background + // Everything but the size: what makes a background outdated. + readonly property string backdropLook: wallpaper && !opaque + ? ["frosted4", wallpaper, Math.round(backdropColor.r * 255), Math.round(backdropColor.g * 255), Math.round(backdropColor.b * 255), backdropTint].join("|") : "" + // key -> path of the backgrounds made so far + property var backdropSaved: ({}) + property var backdropQueue: [] + function cachedPath(width, height) { + return backdropSaved[backdropKeyFor(width, height)] || "" + } + + function backdropKeyFor(width, height) { + return root.backdropLook && width > 0 && height > 0 ? root.backdropLook + "|" + width + "x" + height : "" + } + + function backdropPathFor(key) { + return (Quickshell.env("XDG_RUNTIME_DIR") || "/tmp") + "/omarchy-launcher-backdrop-" + Qt.md5(key) + ".png" + } + + // Prepare both orientations for every output independently of launcher visibility. + readonly property var wantedKeys: { + var keys = [] + for (var screen of Quickshell.screens) { + var w = Math.round(screen.width * screen.devicePixelRatio) + var h = Math.round(screen.height * screen.devicePixelRatio) + for (var key of [backdropKeyFor(w, h), backdropKeyFor(h, w)]) + if (key && keys.indexOf(key) < 0) keys.push(key) + } + return keys + } + onWantedKeysChanged: Qt.callLater(updateQueue) + function updateQueue() { + backdropQueue = wantedKeys.filter(key => !backdropSaved[key] && !(backdropProc.running && backdropProc.key === key)) + if (!backdropProc.running) makeNextBackdrop() + } + + function makeNextBackdrop() { + if (root.backdropQueue.length === 0) return + var key = root.backdropQueue[0] + root.backdropQueue = root.backdropQueue.slice(1) + var size = key.substring(key.lastIndexOf("|") + 1).split("x") + var look = key.split("|") + backdropProc.key = key + backdropProc.command = [Quickshell.env("OMARCHY_PATH") + "/bin/omarchy-launcher-backdrop", root.wallpaper, + root.backdropPathFor(key), size[0], size[1], look[2], look[3], look[4], look[5]] + backdropProc.running = true + } + + Process { + id: backdropProc + property string key: "" + onExited: function(exitCode) { + if (exitCode === 0) { + var saved = ({}) + for (var k in root.backdropSaved) { + // A background of an earlier wallpaper or theme colour is not + // needed again; both orientations of the current one are. + if (k.indexOf(root.backdropLook + "|") === 0) saved[k] = root.backdropSaved[k] + else Quickshell.execDetached(["rm", "-f", root.backdropSaved[k]]) + } + if (key.indexOf(root.backdropLook + "|") === 0) saved[key] = root.backdropPathFor(key) + else Quickshell.execDetached(["rm", "-f", root.backdropPathFor(key)]) + root.backdropSaved = saved + } + Qt.callLater(root.makeNextBackdrop) + } + } +} diff --git a/desktop/shell/shell/services/PluginRegistry.qml b/desktop/shell/shell/services/PluginRegistry.qml index 8ee43474..3e2216b6 100644 --- a/desktop/shell/shell/services/PluginRegistry.qml +++ b/desktop/shell/shell/services/PluginRegistry.qml @@ -804,5 +804,5 @@ QtObject { return slash === -1 ? relative : relative.slice(0, slash) } - Component.onCompleted: ensureUserDir() + property AfterStartup watcherSetup: AfterStartup { onTriggered: registry.ensureUserDir() } } diff --git a/desktop/shell/shell/services/raster-icons.py b/desktop/shell/shell/services/raster-icons.py new file mode 100644 index 00000000..5350aa67 --- /dev/null +++ b/desktop/shell/shell/services/raster-icons.py @@ -0,0 +1,69 @@ +"""Warm the launcher's on-disk icon cache without mapping a Qt Quick window.""" +import fcntl +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +from urllib.parse import unquote, urlsplit + + +def prepare(request): + converter = shutil.which("rsvg-convert") + if not converter or not request["sources"]: + return {} + cache = Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache") / "omarchy/icon-raster" + cache.mkdir(parents=True, exist_ok=True) + # Several shell instances can prepare the same cache. Serialize admission + # so they cannot each spend the same remaining bytes. At capacity callers + # use the original, display-sized SVG. Keep published URLs valid. + with (cache / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + used = sum(path.stat().st_size for path in cache.glob("*.png")) + return prepare_sizes(request, converter, cache, max(0, 32 * 1024**2 - used)) + + +def prepare_sizes(request, converter, cache, remaining): + index = {} + for source in request["sources"]: + path = Path(unquote(urlsplit(source).path)) + try: + path = path.resolve(strict=True) + stamp = path.stat().st_mtime_ns + except (OSError, RuntimeError): + continue + key = hashlib.sha256(os.fsencode(path)).hexdigest() + sizes = {} + for pixels in request["sizes"]: + target = cache / f"{key}-{stamp}-{pixels}.png" + try: + if not target.is_file(): + if remaining <= 0: + continue + with tempfile.NamedTemporaryFile(dir=cache) as tmp: + result = subprocess.run([converter, "--keep-aspect-ratio", "-w", str(pixels), + "-h", str(pixels), str(path)], stdout=tmp) + if result.returncode or not 0 < tmp.tell() <= remaining: + continue + # Publish a complete PNG even if the shell restarts mid-render. + try: + os.link(tmp.name, target) + remaining -= tmp.tell() + except FileExistsError: + pass + sizes[pixels] = target.as_uri() + except OSError: + continue + index[source] = sizes + return index + + +if __name__ == "__main__": + try: + index = prepare(json.loads(sys.stdin.readline())) + except OSError: + index = {} + print(json.dumps(index)) diff --git a/desktop/shell/shell/services/shell-facts.py b/desktop/shell/shell/services/shell-facts.py new file mode 100644 index 00000000..2a2e61de --- /dev/null +++ b/desktop/shell/shell/services/shell-facts.py @@ -0,0 +1,67 @@ +"""Look up the commands referenced by menu definitions in one session PATH scan.""" +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys + + +def probe(command): + try: + return subprocess.run([command], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + timeout=4).returncode == 0 + except (OSError, subprocess.TimeoutExpired): + return False + + +def hardware(hypr): + machine = os.uname().machine + model = Path("/proc/device-tree/model") + mobile_apple = os.access(model, os.R_OK) and model.read_bytes().startswith((b"iPad", b"iPhone", b"Apple iPad", b"Apple iPhone")) + backlights = [p for p in Path("/sys/class/backlight").glob("*") if (p / "max_brightness").is_file()] + return { + "omarchy-hw-x86": machine == "x86_64", + "omarchy-hw-aarch64-apple": machine == "aarch64" and probe("omarchy-hw-aarch64-apple"), + "omarchy-hw-laptop": not mobile_apple and probe("omarchy-hw-laptop"), + "omarchy-hw-dell-xps-haptic-touchpad": machine == "x86_64" and probe("omarchy-hw-dell-xps-haptic-touchpad"), + # These two helpers specifically detect devices configurable by Hyprland. + "omarchy-hw-touchpad": hypr and probe("omarchy-hw-touchpad"), + "omarchy-hw-touchscreen": hypr and probe("omarchy-hw-touchscreen"), + "backlight": str(backlights[0]) if len(backlights) == 1 else "", + "lightSensor": any(Path("/sys/bus/iio/devices").glob("iio:device*/in_illuminance_input")) + or any(Path("/sys/bus/iio/devices").glob("iio:device*/in_illuminance_raw")), + } + + +def main(): + hypr = bool(os.environ.get("HYPRLAND_INSTANCE_SIGNATURE")) + result = {"missing": {}, "hyprland": {}} + if sys.argv[1] == "session": + result["hardware"] = hardware(hypr) + # Optional readers used by the bar even if the corresponding tool has + # been withheld from this installation. They need no source inspection. + for name in ("omarchy-audio-sink-availability", "omarchy-audio-output-sink", + "omarchy-bar-text-color", "omarchy-capture-screenrecording", "omarchy-reminder", + "omarchy-sudo-passwordless", "omarchy-update-available", "powerprofilesctl"): + if not shutil.which(name): + result.setdefault("unavailableReaders", {})[name] = True + for name in sys.argv[2:]: + path = shutil.which(name) + if not path: + result["missing"][name] = True + elif not hypr and name != "omarchy-bar": + try: + stream = open(path, "rb") + except OSError: + continue + with stream: + # A native executable is opaque. Inspect only scripts. + if stream.read(2) == b"#!" and re.search(rb"\bhyprctl\b|\bomarchy-hyprland-", stream.read()): + result["hyprland"][name] = True + print(json.dumps(result)) + + +if __name__ == "__main__": + main() diff --git a/desktop/shell/shell/settings/AboutPage.qml b/desktop/shell/shell/settings/AboutPage.qml index e7f6b24a..9c4cd858 100644 --- a/desktop/shell/shell/settings/AboutPage.qml +++ b/desktop/shell/shell/settings/AboutPage.qml @@ -1,5 +1,6 @@ import QtQuick import Quickshell +import Quickshell.Io import qs.Commons import qs.Commons as Commons @@ -10,11 +11,21 @@ Item { id: page property var settings: null - // Read by Settings as its window opens (Settings.qml), so the table is - // whole when the page comes in instead of growing under the finger; read - // again here, as storage changes. - readonly property var facts: settings && settings.host ? settings.host.aboutFacts : [] - Component.onCompleted: if (settings && settings.host) settings.host.readAbout() + property var facts: [] + Process { + running: true + command: ["python3", Quickshell.env("OMARCHY_PATH") + "/shell/settings/page-data.py", "about"] + stdout: StdioCollector { + waitForEnd: true + onStreamFinished: { + if (!text.trim()) return + var data = JSON.parse(text) + page.facts = Object.keys(data).filter(function(key) { return !!data[key] }).map(function(key) { + return { label: Commons.I18n.t("settings.about" + key), value: data[key] } + }) + } + } + } readonly property bool ready: facts.length > 0 width: parent ? parent.width : 0 diff --git a/desktop/shell/shell/settings/BackgroundPage.qml b/desktop/shell/shell/settings/BackgroundPage.qml index 4b6dd218..fee82bee 100644 --- a/desktop/shell/shell/settings/BackgroundPage.qml +++ b/desktop/shell/shell/settings/BackgroundPage.qml @@ -27,29 +27,16 @@ Item { Process { id: lister running: true - command: ["bash", "-lc", [ - "readlink -f ~/.local/state/omarchy/current/background 2>/dev/null; echo", - "theme=$(cat ~/.local/state/omarchy/current/theme.name 2>/dev/null)", - "for dir in ~/.local/state/omarchy/current/theme/backgrounds \"$HOME/.config/omarchy/backgrounds/$theme\"; do", - " [[ -d $dir ]] || continue", - " find -L \"$dir\" -maxdepth 1 -type f \\( -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.png' -o -iname '*.webp' -o -iname '*.gif' -o -iname '*.bmp' -o -iname '*.mp4' -o -iname '*.webm' -o -iname '*.mov' -o -iname '*.mkv' \\) -print 2>/dev/null | sort | while read -r f; do printf 'i\\t%s\\t%s\\n' \"$f\" \"$(readlink -f \"$f\")\"; done", - "done" - ].join("\n")] - property string collected: "" - stdout: SplitParser { onRead: function(data) { lister.collected += data + "\n" } } - onExited: { - var lines = lister.collected.split("\n") - page.current = lines[0].trim() - var out = [] - for (var i = 1; i < lines.length; i++) { - var parts = lines[i].split("\t") - if (parts[0] !== "i" || !parts[1]) continue - var file = parts[1] - var name = file.replace(/^.*\//, "").replace(/\.[^.]*$/, "").replace(/^\d+-/, "").replace(/-/g, " ") - out.push({ path: file, real: parts[2] || file, name: name, video: /\.(mp4|webm|mov|mkv)$/i.test(file) }) + command: ["python3", Quickshell.env("OMARCHY_PATH") + "/shell/settings/page-data.py", "backgrounds"] + stdout: StdioCollector { + waitForEnd: true + onStreamFinished: { + if (!text.trim()) return + var data = JSON.parse(text) + page.current = data.current + page.images = data.rows.map(function(row) { row.name = row.path.replace(/^.*\//, "").replace(/\.[^.]*$/, "").replace(/^\d+-/, "").replace(/-/g, " "); return row }) + page.ready = true } - page.images = out - page.ready = true } } @@ -91,8 +78,8 @@ Item { anchors.fill: parent anchors.margins: parent.border.width visible: !tile.modelData.video - source: tile.modelData.video ? "" : Util.fileUrl(tile.modelData.path) - sourceSize.width: Math.round(page.cell * 1.5) + source: width <= 0 || height <= 0 || tile.modelData.video ? "" : Util.fileUrl(tile.modelData.path) + sourceSize: Qt.size(Math.ceil(width * Screen.devicePixelRatio), Math.ceil(height * Screen.devicePixelRatio)) fillMode: Image.PreserveAspectCrop asynchronous: true cache: false diff --git a/desktop/shell/shell/settings/DisplayPage.qml b/desktop/shell/shell/settings/DisplayPage.qml index 235642d2..a472954a 100644 --- a/desktop/shell/shell/settings/DisplayPage.qml +++ b/desktop/shell/shell/settings/DisplayPage.qml @@ -3,7 +3,6 @@ import Quickshell import Quickshell.Io import qs.Commons import qs.Commons as Commons -import "../plugins/status" as StatusParts // Display: brightness (and following the light, where there is a sensor) and // rotation lock, through the commands the control center uses; the menu's @@ -12,43 +11,19 @@ Item { id: page property var settings: null - // Its data read: Settings shows it (and slides it in) only then. - readonly property bool ready: brightnessDone && autoDone - property bool brightnessDone: false - property bool autoDone: false - width: parent ? parent.width : 0 height: column.height - StatusParts.RotationLock { id: rotation } + readonly property var rotation: SessionStatus.rotation - property int brightness: -1 // percent, -1 until read (or no backlight) - property bool autoAvailable: false - property bool autoOn: false + property int brightness: SessionStatus.brightness // percent, -1 until read (or no backlight) + readonly property bool autoAvailable: SessionStatus.autoAvailable + readonly property bool autoOn: SessionStatus.autoOn + Component.onCompleted: SessionStatus.refreshBrightness() - Process { - id: brightnessRead - running: true - command: ["omarchy-brightness-display"] - stdout: StdioCollector { - onStreamFinished: { - var value = parseInt(String(text).trim(), 10) - page.brightness = isNaN(value) ? -1 : value - page.brightnessDone = true - } - } - } - Process { - id: autoRead - running: true - command: ["bash", "-c", "omarchy-auto-brightness available && omarchy-auto-brightness status"] - stdout: StdioCollector { - onStreamFinished: { - page.autoAvailable = /auto-brightness: (on|off)/.test(text) - page.autoOn = /auto-brightness: on/.test(text) - page.autoDone = true - } - } + Connections { + target: SessionStatus + function onBrightnessChanged() { if (!brightnessSet.running) page.brightness = SessionStatus.brightness } } // As the control center sets it: no OSD, and one command for a burst of moves. @@ -94,8 +69,7 @@ Item { isSwitch: true switchOn: page.autoOn onActivated: { - page.autoOn = !page.autoOn - Quickshell.execDetached(["omarchy-auto-brightness", page.autoOn ? "on" : "off"]) + Quickshell.execDetached(["omarchy-auto-brightness", page.autoOn ? "off" : "on"]) } } } diff --git a/desktop/shell/shell/settings/IconsPage.qml b/desktop/shell/shell/settings/IconsPage.qml index 4fabc6b8..cfa338af 100644 --- a/desktop/shell/shell/settings/IconsPage.qml +++ b/desktop/shell/shell/settings/IconsPage.qml @@ -29,31 +29,16 @@ Item { Process { id: lister running: true - command: ["bash", "-lc", [ - "omarchy-icons-current --id 2>/dev/null; echo", - "for dir in ~/.config/omarchy/icons/*/ \"$OMARCHY_PATH\"/icons/*/; do", - " [[ -d $dir ]] || continue", - " name=${dir%/}; name=${name##*/}", - " preview=; [[ -f $dir/preview.png ]] && preview=$dir/preview.png", - " printf 's\\t%s\\t%s\\n' \"$name\" \"$preview\"", - "done", - "printf 's\\toriginal\\t\\n'" - ].join("\n")] - property string collected: "" - stdout: SplitParser { onRead: function(data) { lister.collected += data + "\n" } } - onExited: { - var lines = lister.collected.split("\n") - page.current = lines[0].trim() - var seen = {} - var out = [] - for (var i = 1; i < lines.length; i++) { - var parts = lines[i].split("\t") - if (parts[0] !== "s" || !parts[1] || seen[parts[1]]) continue - seen[parts[1]] = true - out.push({ id: parts[1], name: Model.displayName(parts[1]), preview: parts[2] || "" }) + command: ["python3", Quickshell.env("OMARCHY_PATH") + "/shell/settings/page-data.py", "icons"] + stdout: StdioCollector { + waitForEnd: true + onStreamFinished: { + if (!text.trim()) return + var data = JSON.parse(text) + page.current = data.current + page.sets = data.rows.map(function(row) { row.name = Model.displayName(row.id); return row }) + page.ready = true } - page.sets = out - page.ready = true } } @@ -89,8 +74,8 @@ Item { width: parent.width * 1.15 height: parent.height * 1.15 visible: tile.modelData.preview !== "" - source: tile.modelData.preview ? Util.fileUrl(tile.modelData.preview) : "" - sourceSize.width: Math.round(page.cell * 2) + source: width > 0 && height > 0 && tile.modelData.preview ? Util.fileUrl(tile.modelData.preview) : "" + sourceSize: Qt.size(Math.ceil(width * Screen.devicePixelRatio), Math.ceil(height * Screen.devicePixelRatio)) fillMode: Image.PreserveAspectCrop asynchronous: true cache: false diff --git a/desktop/shell/shell/settings/Settings.qml b/desktop/shell/shell/settings/Settings.qml index ca9e99bb..a62aeff3 100644 --- a/desktop/shell/shell/settings/Settings.qml +++ b/desktop/shell/shell/settings/Settings.qml @@ -33,6 +33,8 @@ Item { return loader ? loader.item : null } + readonly property var menuChildren: Model.childIndex(menu ? menu.items : {}, menu ? menu.itemOrder : []) + function open(target) { root.path = String(target || "") root.pathRevision++ @@ -48,47 +50,53 @@ Item { // submenu here rather than in the menu. function places(id) { if (!root.menu || !root.menu.items) return false - return Model.sectionFor(Layout.SECTIONS, { items: root.menu.items, itemOrder: root.menu.itemOrder }, id) !== "" + return Model.sectionFor(Layout.SECTIONS, { items: root.menu.items, itemOrder: root.menu.itemOrder, children: root.menuChildren }, id) !== "" } function close() { root.opened = false } - // About's facts: model, system, version, kernel, memory and storage, read - // as the window opens so the page shows them whole. A line the system - // cannot answer is left out. - property var aboutFacts: [] - onOpenedChanged: if (opened) readAbout() - function readAbout() { if (!aboutReader.running) { aboutReader.collected = ""; aboutReader.running = true } } + onOpenedChanged: { + if (opened) windowLoader.setSource(Qt.resolvedUrl("SettingsWindow.qml"), { host: root }) + else { + windowLoader.source = "" + Qt.callLater(function() { gc() }) + } + } + + // The format used by the General row is the system time-zone ID. + readonly property var values: ({ + "page:datetime": timezone, + "appearance.theme": Model.displayName(themeName.text.trim()) || "Unknown", + "appearance.icons": Model.displayName(iconsName.text.trim() || "papercraft"), + "appearance.font": appearance.font || "", + "appearance.background": appearance.background || "" + }) + property string timezone: "" + AfterStartup { onTriggered: zoneReader.running = true } + Connections { + target: Commons.TimeZone + function onRevisionChanged() { zoneReader.running = true } + } Process { - id: aboutReader - command: ["bash", "-lc", [ - "model=$(tr -d '\\0' < /proc/device-tree/model 2>/dev/null); [[ -n $model ]] || model=$(cat /sys/class/dmi/id/product_name 2>/dev/null)", - "printf 'device\\t%s\\n' \"$model\"", - "printf 'name\\t%s\\n' \"$(cat /etc/hostname 2>/dev/null || uname -n)\"", - "printf 'system\\t%s\\n' \"$(. /etc/os-release 2>/dev/null; echo \"$PRETTY_NAME\")\"", - "printf 'version\\t%s\\n' \"$(omarchy-version 2>/dev/null)\"", - "printf 'kernel\\t%s\\n' \"$(uname -r)\"", - "printf 'memory\\t%s\\n' \"$(awk '/^MemTotal:/ { printf \"%.1f GB\", $2 / 1048576 }' /proc/meminfo)\"", - "printf 'storage\\t%s\\n' \"$(df -B1 / 2>/dev/null | awk 'NR == 2 { printf \"%.0f GB of %.0f GB free\", $4 / 1e9, $2 / 1e9 }')\"" - ].join("\n")] - property string collected: "" - stdout: SplitParser { onRead: function(data) { aboutReader.collected += data + "\n" } } - onExited: { - var labels = { - device: "settings.aboutDevice", name: "settings.aboutName", system: "settings.aboutSystem", - version: "settings.aboutVersion", kernel: "settings.aboutKernel", memory: "settings.aboutMemory", - storage: "settings.aboutStorage" - } - var out = [] - var lines = aboutReader.collected.split("\n") - for (var i = 0; i < lines.length; i++) { - var parts = lines[i].split("\t") - if (!labels[parts[0]] || !parts[1] || !parts[1].trim()) continue - out.push({ label: Commons.I18n.t(labels[parts[0]]), value: parts[1].trim() }) - } - root.aboutFacts = out + id: zoneReader + command: ["timedatectl", "show", "-p", "Timezone", "--value"] + stdout: StdioCollector { waitForEnd: true; onStreamFinished: root.timezone = text.trim() } + } + readonly property string current: Quickshell.env("HOME") + "/.local/state/omarchy/current/" + WatchedFile { id: themeName; path: root.current + "theme.name" } + WatchedFile { id: iconsName; path: root.current + "icons.name" } + property var appearance: ({}) + function readAppearance() { + if (!appearanceReader.running) appearanceReader.running = true + } + Process { + id: appearanceReader + command: ["python3", Quickshell.env("OMARCHY_PATH") + "/shell/settings/page-data.py", "appearance"] + stdout: StdioCollector { + waitForEnd: true + onStreamFinished: { if (text.trim()) root.appearance = JSON.parse(text) } } } @@ -105,7 +113,7 @@ Item { // shell restarts. property bool bluetoothScan: false property bool owesDiscoveryStop: false - readonly property var adapter: Bluetooth.defaultAdapter + readonly property var adapter: bluetoothScan || owesDiscoveryStop ? Bluetooth.defaultAdapter : null Timer { interval: 1000 repeat: true @@ -141,18 +149,11 @@ Item { function open(page: string): void { root.open(page) } function close(): void { root.close() } function toggle(): void { root.toggle() } + function contentReady(): bool { return !!windowLoader.item && windowLoader.item.contentReady } } Loader { id: windowLoader - active: root.opened - asynchronous: false - sourceComponent: SettingsWindow { - host: root - menu: root.menu - } - // A window torn down frees what it held; the engine collects it on its - // own time otherwise, which on a small device is memory held for nothing. - onActiveChanged: if (!active) Qt.callLater(function() { gc() }) + asynchronous: true } } diff --git a/desktop/shell/shell/settings/SettingsContent.qml b/desktop/shell/shell/settings/SettingsContent.qml new file mode 100644 index 00000000..efbfee44 --- /dev/null +++ b/desktop/shell/shell/settings/SettingsContent.qml @@ -0,0 +1,1036 @@ +import QtQuick +import Quickshell +import Quickshell.Io +import qs.Commons +import qs.Commons as Commons +import qs.Ui +import "SettingsLayout.js" as Layout +import "SettingsModel.js" as Model + +// The window: a sidebar of sections beside the page (wide), or the section +// list and then a page over it (narrow, a phone). Rows come from the layout +// and the menu (SettingsModel.js); a row does what its menu entry does. +Item { + id: win + + required property var host + readonly property var menu: host.menu + readonly property color color: Commons.Color.background + + // ------------------------------------------------------------- the data + + readonly property color text: Commons.Color.foreground + readonly property color dim: Util.alpha(Commons.Color.foreground, 0.6) + readonly property color faint: Util.alpha(Commons.Color.foreground, 0.4) + readonly property color fill: Util.alpha(Commons.Color.foreground, 0.04) + readonly property color line: Util.alpha(Commons.Color.foreground, 0.12) + readonly property color accent: Commons.Color.accent + + readonly property bool wide: content.width >= Style.space(640) + readonly property bool twoColumns: content.width >= Style.space(940) + readonly property int rowHeight: Style.space(42) + readonly property int pad: Style.space(20) + readonly property int sidebarWidth: content.width >= Style.space(940) ? Style.space(260) : Style.space(216) + + // What the menu knows now; every row reads it. + readonly property var values: host.values + // A switch flipped a moment ago shows its new state until the menu has + // checked again. + property var pending: ({}) + readonly property var ctx: ({ + items: menu ? menu.items : ({}), + itemOrder: menu ? menu.itemOrder : [], + whenResults: menu ? menu.whenResults : ({}), + checkedResults: menu ? menu.checkedResults : ({}), + disabledResults: menu ? menu.disabledResults : ({}), + values: values, + missing: ShellFacts.missing, + hyprland: ShellFacts.hyprland, + children: host.menuChildren + }) + readonly property var providers: menu ? menu.providers : ({}) + function t(key) { return Commons.I18n.t(key) } + + readonly property var sections: Layout.SECTIONS + readonly property var sectionBlocks: { + var out = [] + for (var i = 0; i < sections.length; i++) { + if (i === 0 || sections[i].startsGroup) out.push([]) + out[out.length - 1].push(sections[i]) + } + return out + } + + function sectionById(id) { + for (var i = 0; i < sections.length; i++) if (sections[i].id === id) return sections[i] + return null + } + function sectionIcon(section) { + if (section.icon) return section.icon + var e = ctx.items[section.iconEntry] + return e ? e.icon : "" + } + + // ------------------------------------------------------------ navigation + + // The section shown ("" on a phone: the list of sections), and the pages + // opened inside it: { kind: "menu" | "choice" | "native", id, page }. + property string section: "" + property var stack: [] + property string query: "" + readonly property bool searching: query.trim() !== "" + + // A page comes in over the one before from the right and leaves to the + // right again, as on an iPad: the old page is held as a picture while the + // new one is built, so both move together. On a phone the section list is + // a page too; on a wide window the sidebar stays and a section shows in + // place. Without a GPU (software rendering) pages change at once. + readonly property bool gpu: Quickshell.env("QT_QUICK_BACKEND") !== "software" + property int navDirection: 0 + property real navT: 1 + property var navChange: null + property bool navPhone: false + property var navPicture: null + function navigate(direction, change) { + if (Lite.enabled || !win.gpu || direction === 0 || content.width <= 0 || navAnim.running || navWait.running) { + if (navAnim.running) navAnim.complete() + change() + return + } + win.navPhone = !win.wide + // A phone's whole window moves; a wide window's page only. + var picture = win.navPhone ? shot : pageShot + picture.sourceItem = win.navPhone ? content : pageMover + if (win.navPhone) { + shot.x = 0 + shot.width = content.width + shot.height = content.height + } + // Only a picture in the scene is taken: shown (too faint to see) until + // it has the old page. + win.navT = 1 + picture.visible = true + picture.scheduleUpdate() + win.navPicture = picture + win.navDirection = direction + win.navChange = change + navWait.start() + } + // A frame for the picture to be taken before the page changes under it. + Timer { + id: navWait + interval: 34 + onTriggered: { + win.navChange() + win.navChange = null + win.navT = 0 + navAnim.restart() + } + } + NumberAnimation { + id: navAnim + target: win; property: "navT"; from: 0; to: 1 + duration: Style.duration(340) + easing.type: Easing.OutCubic + onFinished: { + if (win.navPicture) { win.navPicture.visible = false; win.navPicture.sourceItem = null } + win.navPicture = null + win.navDirection = 0 + } + } + readonly property real navWidth: navPhone ? content.width : pageArea.width + // Where the new page and the picture of the old one stand now. + readonly property real slideNew: navDirection > 0 ? (1 - navT) * navWidth + : navDirection < 0 ? -(1 - navT) * navWidth * 0.3 : 0 + readonly property real slideOld: navDirection > 0 ? -navT * navWidth * 0.3 + : navDirection < 0 ? navT * navWidth : 0 + + function goSection(id) { + // From a phone's list into a section: a page in. + if (!win.wide && win.section === "" && id !== "" && !win.searching) { + win.navigate(1, function() { win.showSection(id) }) + return + } + win.showSection(id) + } + function showSection(id) { + if (id !== "" && id !== sections[0].id) win.chosen = true + win.section = id + win.stack = [] + win.query = "" + searchField.text = "" + win.cursor = -1 + scroller.contentY = 0 + } + function push(page) { + win.navigate(1, function() { win.pushNow(page) }) + } + function pushNow(page) { + win.stack = win.stack.concat([page]) + win.cursor = -1 + scroller.contentY = 0 + if (page.kind === "choice") { + var e = ctx.items[page.id] + if (e && e.provider && menu) { + menu.invalidateVolatileProvider(page.id) + menu.loadProviderForMenu(page.id) + } + } + } + // Back to the page shown under it: a native page's pick (a time zone) puts + // its list away. + function backTo(page) { + var at = -1 + for (var i = 0; i < win.stack.length; i++) if (win.stack[i].page === page) at = i + if (at < 0 || at === win.stack.length - 1) return + win.navigate(-1, function() { win.stack = win.stack.slice(0, at + 1); win.cursor = -1 }) + } + function back() { + if (win.searching) { win.query = ""; searchField.text = ""; return true } + if (win.stack.length > 0) { + win.navigate(-1, function() { win.stack = win.stack.slice(0, -1); win.cursor = -1 }) + return true + } + if (!win.wide && win.section !== "") { + win.navigate(-1, function() { win.section = ""; win.cursor = -1 }) + return true + } + return false + } + function openPath(path) { + var r = Model.route(path, sections, ctx) + win.chosen = r.section !== "" + win.showSection(r.section || (win.wide ? sections[0].id : "")) + if (r.page) win.pushNow(r.page) + } + // Opened without a page: a wide window shows its first section beside the + // list, a phone the list itself. The window learns its width only once it + // is placed, so the choice follows it until a section is picked. + property bool chosen: false + onWideChanged: { + if (win.chosen || win.stack.length > 0 || win.searching) return + win.section = win.wide ? sections[0].id : "" + } + + readonly property var currentPage: stack.length > 0 ? stack[stack.length - 1] : null + + readonly property string pageTitle: { + if (win.searching) return win.t("settings.searchResults") + if (currentPage) { + if (currentPage.kind === "native") { + if (currentPage.title) return currentPage.title + if (currentPage.titleKey) return win.t(currentPage.titleKey) + var nativeEntry = { theme: "appearance.theme", background: "appearance.background", icons: "appearance.icons" }[currentPage.page] + return nativeEntry && ctx.items[nativeEntry] ? ctx.items[nativeEntry].label : currentPage.page + } + var e = ctx.items[currentPage.id] + return e ? (e.title || e.label) : "" + } + var s = sectionById(win.section) + return s ? win.t(s.label) : win.t("settings.title") + } + // "Appearance ›" above a page opened inside a section. + readonly property string backLabel: { + if (!currentPage) return "" + if (stack.length > 1) { + var prev = stack[stack.length - 2] + if (prev.kind === "native" && (prev.title || prev.titleKey)) return prev.title || win.t(prev.titleKey) + var e = prev.kind === "native" ? null : ctx.items[prev.id] + return e ? e.label : "" + } + var s = sectionById(win.section) + return s ? win.t(s.label) : "" + } + + // The rows the page shows, in groups. + readonly property var groups: { + var c = win.ctx + if (win.searching) { + var found = Model.search(win.query, sections, c, providers, win.t) + return found.length ? [{ label: "", rows: found.slice(0, 60) }] : [] + } + if (currentPage) { + if (currentPage.kind === "menu") return [{ label: "", rows: Model.resolveRows(Model.menuSpecs(c, currentPage.id), c, providers, win.t) }] + if (currentPage.kind === "choice") return [{ label: "", rows: Model.choiceRows(c, c.items[currentPage.id]) }] + return [] + } + return Model.sectionGroups(sectionById(win.section), c, providers, win.t) + } + readonly property var nativePage: { + if (win.searching) return "" + if (currentPage && currentPage.kind === "native") return currentPage.page + var s = sectionById(win.section) + return !currentPage && s && s.page ? s.page : "" + } + readonly property var flatRows: { + var out = [] + for (var g = 0; g < groups.length; g++) for (var r = 0; r < groups[g].rows.length; r++) out.push(groups[g].rows[r]) + return out + } + + // ----------------------------------------------------------- doing things + + function activate(row) { + if (!row || row.available === false || row.off) return + if (row.section !== undefined && row.section !== win.section && win.searching) { + // A search result opens where it lives, then does what it does. + var target = row + win.goSection(row.section || win.section || sections[0].id) + win.activate(target) + return + } + if (row.kind === "switch") { + var next = Object.assign({}, win.pending) + next[row.key] = !row.on + win.pending = next + run(row.entry.action) + return + } + if (row.kind === "choice") { win.push({ kind: "choice", id: row.entry.id }); return } + if (row.kind === "page") { win.push({ kind: "menu", id: row.entry.id }); return } + if (row.kind === "native") { + if (sectionById(win.section) && sectionById(win.section).page === row.page && !currentPage) return + win.push({ kind: "native", page: row.page, title: row.label }) + return + } + if (row.kind === "option" || row.kind === "action") run(row.entry.action) + } + + function run(action) { + if (!action || !menu) return + menu.runAction(action) + refreshSoon.restart() + } + + function switchOn(row) { + return win.pending[row.key] !== undefined ? win.pending[row.key] === true : row.on === true + } + + // What changed shows as soon as the menu has checked again: right after + // a change, and once more for commands that take a moment. + Timer { id: refreshSoon; interval: 500; onTriggered: { win.refresh(); refreshLater.restart() } } + Timer { id: refreshLater; interval: 2000; onTriggered: win.refresh() } + function refresh() { + if (menu) menu.evaluateGuards() + if (win.section === "appearance") host.readAppearance() + } + onSectionChanged: if (section === "appearance") host.readAppearance() + Connections { + target: win.menu + function onWhenResultsChanged() { win.pending = ({}) } + } + + Component.onCompleted: { + if (host) openPath(host.path) + content.forceActiveFocus() + } + Connections { + target: win.host + function onPathRevisionChanged() { if (win.host.path) win.openPath(win.host.path) } + } + + // ------------------------------------------------------------- keyboard + + // A cursor over the page's rows, shown once a key moves it. + property int cursor: -1 + function moveCursor(step) { + var n = win.flatRows.length + if (n === 0) return + var i = win.cursor + for (var tries = 0; tries < n; tries++) { + i = i < 0 ? (step > 0 ? 0 : n - 1) : (i + step + n) % n + if (win.flatRows[i].available !== false && !win.flatRows[i].off) break + } + win.cursor = i + } + function moveSection(step) { + var i = 0 + for (var k = 0; k < sections.length; k++) if (sections[k].id === win.section) i = k + win.goSection(sections[(i + step + sections.length) % sections.length].id) + } + + // ---------------------------------------------------------------- layout + + // The old page during a transition: under the new one going forward, over + // it going back, fading as it goes. + ShaderEffectSource { + id: shot + visible: false + live: false + hideSource: false + // It fades as it goes; while it is being taken (navT still 1) it is too + // faint to see. + opacity: Math.max(0.01, 1 - win.navT) + z: win.navDirection < 0 ? 2 : -1 + transform: Translate { x: win.slideOld } + } + + Item { + id: content + anchors.fill: parent + focus: true + transform: Translate { x: win.navPhone && win.navDirection !== 0 ? win.slideNew : 0 } + // Opaque, so the page going forward covers the picture under it. + Rectangle { anchors.fill: parent; color: win.color; visible: win.navPhone && win.navDirection !== 0 } + + Keys.onPressed: function(event) { + var ctrl = (event.modifiers & Qt.ControlModifier) !== 0 + if (event.key === Qt.Key_Down) { win.moveCursor(1); event.accepted = true } + else if (event.key === Qt.Key_Up) { win.moveCursor(-1); event.accepted = true } + else if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) { + if (win.cursor >= 0 && win.cursor < win.flatRows.length) win.activate(win.flatRows[win.cursor]) + event.accepted = true + } + else if (event.key === Qt.Key_Escape || event.key === Qt.Key_Backspace || (event.key === Qt.Key_Left && (event.modifiers & Qt.AltModifier))) { + event.accepted = win.back() + } + else if (event.key === Qt.Key_PageDown || (ctrl && event.key === Qt.Key_Tab)) { win.moveSection(1); event.accepted = true } + else if (event.key === Qt.Key_PageUp || (ctrl && event.key === Qt.Key_Backtab)) { win.moveSection(-1); event.accepted = true } + else if ((ctrl && event.key === Qt.Key_F) || event.key === Qt.Key_Slash) { searchField.forceActiveFocus(); event.accepted = true } + else if (event.text && event.text.length === 1 && event.text > " " && !ctrl) { + searchField.forceActiveFocus() + searchField.text += event.text + event.accepted = true + } + } + + // ------------------------------------------------------------ sidebar + + Item { + id: sidebar + visible: win.wide || win.section === "" + width: win.wide ? win.sidebarWidth : parent.width + height: parent.height + + Flickable { + anchors.fill: parent + contentHeight: sideColumn.height + win.pad * 2 + clip: true + boundsBehavior: Flickable.StopAtBounds + interactive: contentHeight > height + + Column { + id: sideColumn + x: win.pad + y: win.pad + width: parent.width - win.pad * (win.wide ? 1.5 : 2) + spacing: Style.space(14) + + Text { + text: win.t("settings.title") + color: win.text + font.family: Style.font.family + font.pixelSize: Style.font.display + font.bold: true + } + + // Search: every setting, and every menu entry beside them. + Rectangle { + width: parent.width + height: Style.space(38) + color: win.fill + border.width: 1 + border.color: searchField.activeFocus ? Util.alpha(win.accent, 0.7) : win.line + Text { + id: searchGlyph + x: Style.space(12) + anchors.verticalCenter: parent.verticalCenter + text: "" + color: win.faint + font.family: Style.font.menuFamily + font.pixelSize: Style.font.body + } + TextInput { + id: searchField + x: searchGlyph.x + searchGlyph.width + Style.space(10) + width: parent.width - x - Style.space(10) + anchors.verticalCenter: parent.verticalCenter + color: win.text + font.family: Style.font.family + font.pixelSize: Style.font.subtitle + selectionColor: Util.alpha(win.accent, 0.4) + clip: true + onTextChanged: { win.query = text; win.cursor = -1 } + Keys.onPressed: function(event) { + if (event.key === Qt.Key_Escape) { text = ""; content.forceActiveFocus(); event.accepted = true } + else if (event.key === Qt.Key_Down || event.key === Qt.Key_Return || event.key === Qt.Key_Enter) { + content.forceActiveFocus() + if (event.key === Qt.Key_Down) win.moveCursor(1) + else if (win.flatRows.length > 0) win.activate(win.flatRows[0]) + event.accepted = true + } + } + Text { + visible: searchField.text === "" + text: win.t("settings.search") + color: win.faint + font: searchField.font + } + } + } + + // A phone's search results, under the field. + Text { + visible: !win.wide && win.searching && win.groups.length === 0 + text: win.t("settings.noResults") + color: win.faint + font.family: Style.font.family + font.pixelSize: Style.font.subtitle + } + Repeater { + model: !win.wide && win.searching ? win.groups : [] + Group { + required property var modelData + width: sideColumn.width + group: modelData + } + } + + // The sections; on a phone, the root list with what each holds, in + // one box with a line between rows. + // The sections fall into kinds (startsGroup), a gap between. + Column { + width: parent.width + visible: !(win.searching && !win.wide) + spacing: win.wide ? Style.space(12) : Style.space(16) + Repeater { + model: win.sectionBlocks + Rectangle { + id: block + required property var modelData + required property int index + width: parent.width + height: sectionList.height + (win.wide ? 0 : 2) + color: win.wide ? "transparent" : win.fill + border.width: win.wide ? 0 : 1 + border.color: win.line + // In the sidebar, a faint line in the gap above each kind. + Rectangle { + visible: win.wide && block.index > 0 + x: Style.space(12) + y: -Style.space(6) - 1 + width: parent.width - 2 * Style.space(12) + height: 1 + color: Util.alpha(win.text, 0.08) + } + Column { + id: sectionList + x: win.wide ? 0 : 1 + y: win.wide ? 0 : 1 + width: parent.width - (win.wide ? 0 : 2) + spacing: win.wide ? Style.space(2) : 0 + Repeater { + model: block.modelData + Rectangle { + id: sectionRow + required property var modelData + required property int index + readonly property bool current: win.wide && win.section === modelData.id && !win.searching + width: parent.width + height: win.wide ? Style.space(40) : Style.space(54) + color: current ? Util.alpha(win.accent, 0.14) : "transparent" + Rectangle { + visible: !win.wide && sectionRow.index > 0 + width: parent.width; height: 1 + color: Util.alpha(win.text, 0.07) + } + Rectangle { + visible: sectionRow.current + width: Style.space(2); height: parent.height + color: win.accent + } + Text { + id: sectionGlyph + x: Style.space(12) + width: Style.space(22) + anchors.verticalCenter: parent.verticalCenter + text: win.sectionIcon(sectionRow.modelData) + color: sectionRow.current || !win.wide ? win.accent : win.dim + font.family: Style.font.menuFamily + font.pixelSize: Style.font.title + horizontalAlignment: Text.AlignHCenter + } + Column { + x: sectionGlyph.x + sectionGlyph.width + Style.space(12) + width: parent.width - x - Style.space(30) + anchors.verticalCenter: parent.verticalCenter + spacing: Style.space(2) + Text { + width: parent.width + text: win.t(sectionRow.modelData.label) + color: win.text + font.family: Style.font.family + font.pixelSize: Style.font.subtitle + font.bold: sectionRow.current + elide: Text.ElideRight + } + // What it holds: its groups, as the section itself names them. + Text { + visible: !win.wide && text !== "" + width: parent.width + text: { + var names = [] + var gs = sectionRow.modelData.groups + for (var i = 0; i < gs.length && names.length < 3; i++) if (gs[i].label) names.push(win.t(gs[i].label)) + return names.join(", ") + } + color: win.faint + font.family: Style.font.family + font.pixelSize: Style.font.bodySmall + elide: Text.ElideRight + } + } + Text { + visible: !win.wide + anchors.right: parent.right + anchors.rightMargin: Style.space(14) + anchors.verticalCenter: parent.verticalCenter + text: "›" + color: win.faint + font.family: Style.font.family + font.pixelSize: Style.font.heading + } + TapHandler { onTapped: { win.chosen = true; win.goSection(sectionRow.modelData.id) } } + } + } + } + } + } + } + } + } + } + + // --------------------------------------------------------------- page + + Item { + id: pageArea + // On a phone a search shows under its field, in the list. + visible: win.wide || win.section !== "" + x: win.wide ? sidebar.width : 0 + width: parent.width - x + height: parent.height + // On a wide window a page moves within its own area, never over the + // sidebar. + clip: true + + // The old page during a transition here: under the new one going + // forward, over it going back. + ShaderEffectSource { + id: pageShot + width: pageArea.width + height: pageArea.height + visible: false + live: false + hideSource: false + opacity: Math.max(0.01, 1 - win.navT) + z: win.navDirection < 0 ? 2 : 0 + transform: Translate { x: win.slideOld } + } + + Item { + id: pageMover + anchors.fill: parent + z: 1 + transform: Translate { x: !win.navPhone && win.navDirection !== 0 ? win.slideNew : 0 } + // Opaque, so the page going forward covers the picture under it. + Rectangle { anchors.fill: parent; color: win.color; visible: !win.navPhone && win.navDirection !== 0 } + + Flickable { + id: scroller + anchors.fill: parent + contentHeight: pageColumn.height + win.pad * 2 + clip: true + boundsBehavior: Flickable.StopAtBounds + interactive: contentHeight > height + + Column { + id: pageColumn + x: win.pad + y: win.pad + width: parent.width - win.pad * 2 + spacing: Style.space(14) + + // Back and the title. On a phone the back reads "‹ Settings" at + // the top of a section. + Item { + width: parent.width + height: Math.max(titleText.height, backRow.visible ? backRow.height : 0) + Row { + id: backRow + visible: win.stack.length > 0 || (!win.wide && (win.section !== "" || win.searching)) + anchors.verticalCenter: parent.verticalCenter + spacing: Style.space(6) + // A drawn chevron, so it sits on the label's middle whatever + // the font does with its glyphs. + Item { + width: Style.space(10) + height: backLabelText.height + anchors.verticalCenter: parent.verticalCenter + Repeater { + model: [-1, 1] + Rectangle { + required property var modelData + width: Style.space(9) + height: Math.max(2, Style.space(2)) + radius: height / 2 + color: win.accent + antialiasing: true + x: Style.space(1) + y: (parent.height - height) / 2 + rotation: modelData * 45 + transformOrigin: Item.Left + } + } + } + Text { + id: backLabelText + text: win.stack.length > 0 ? win.backLabel : win.t("settings.title") + color: win.accent + font.family: Style.font.family + font.pixelSize: Style.font.subtitle + anchors.verticalCenter: parent.verticalCenter + } + TapHandler { onTapped: win.back() } + } + // On a phone the title stands in the middle, as a phone's + // settings show it; on a wide window after the back link. + Text { + id: titleText + readonly property bool centered: !win.wide && backRow.visible + // Worked out from the back link and the text alone, so where it + // stands and how wide it is never wait on each other. + readonly property real leftEdge: backRow.visible ? backRow.width + Style.space(centered ? 12 : 16) : 0 + readonly property real titleWidth: centered + ? Math.min(implicitWidth, parent.width - 2 * leftEdge) + : parent.width - leftEdge - (moreButton.visible ? moreButton.width + Style.space(10) : 0) + x: centered ? Math.max(leftEdge, (parent.width - titleWidth) / 2) : leftEdge + width: titleWidth + horizontalAlignment: centered ? Text.AlignHCenter : Text.AlignLeft + anchors.verticalCenter: parent.verticalCenter + text: win.pageTitle + color: win.text + font.family: Style.font.family + font.pixelSize: !backRow.visible ? Style.font.display : Style.font.heading + font.bold: true + elide: Text.ElideRight + } + // The theme page's "Get more", where the menu offers it. + Rectangle { + id: moreButton + readonly property var entry: win.ctx.items["update.themes"] + visible: win.nativePage === "theme" && !!entry && Model.shown(win.ctx, entry) + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + width: moreText.width + Style.space(24) + height: Style.space(32) + color: "transparent" + border.width: 1 + border.color: win.line + Text { + id: moreText + anchors.centerIn: parent + text: moreButton.entry ? moreButton.entry.label : "" + color: win.text + font.family: Style.font.family + font.pixelSize: Style.font.body + } + TapHandler { onTapped: win.run(moreButton.entry.action) } + } + } + + Text { + visible: win.searching && win.groups.length === 0 + text: win.t("settings.noResults") + color: win.faint + font.family: Style.font.family + font.pixelSize: Style.font.subtitle + } + + Loader { + id: nativeLoader + width: parent.width + readonly property string pageFile: ({ + theme: "Theme", background: "Background", icons: "Icons", about: "About", + wifi: "Wifi", wifinetwork: "WifiNetwork", bluetooth: "Bluetooth", sound: "Sound", + display: "Display", datetime: "DateTime", timezone: "Timezone", shortcuts: "Shortcuts" + })[win.nativePage] || "" + asynchronous: true + visible: !!item + property bool initialized: false + onPageFileChanged: if (initialized) loadPage() + Component.onCompleted: { initialized = true; loadPage() } + function loadPage() { + if (pageFile) setSource(Qt.resolvedUrl(pageFile + "Page.qml"), { settings: win }) + else source = "" + } + } + + // The section's groups: the card first, then two columns where the + // window is wide enough, one otherwise. + Repeater { + model: win.groups.filter(function(g) { return g.card }) + ThemeCard { + required property var modelData + width: pageColumn.width + row: modelData.rows[0] + } + } + Row { + id: columns + // A section's own page shows its groups under it (Wi-Fi, About). + visible: win.nativePage === "" || !win.currentPage + width: parent.width + spacing: Style.space(18) + readonly property var plain: win.groups.filter(function(g) { return !g.card }) + readonly property bool split: win.twoColumns && plain.length > 1 && !win.currentPage && !win.searching + // Groups go to the shorter column, in order. + readonly property var halves: { + var left = [], right = [], lh = 0, rh = 0 + for (var i = 0; i < plain.length; i++) { + var h = plain[i].rows.length + (plain[i].label ? 1 : 0) + 1 + if (!split || lh <= rh) { left.push(plain[i]); lh += h } else { right.push(plain[i]); rh += h } + } + return [left, right] + } + Repeater { + model: columns.split ? 2 : 1 + Column { + required property int index + width: columns.split ? (columns.width - columns.spacing) / 2 : columns.width + spacing: Style.space(14) + Repeater { + model: columns.halves[index] + Group { + required property var modelData + width: parent.width + group: modelData + } + } + } + } + } + + } + } + } + } + } + + // ----------------------------------------------------------- components + + component Group: Column { + property var group: null + spacing: Style.space(6) + Text { + visible: !!group && group.label !== "" + text: group ? group.label.toUpperCase() : "" + color: win.faint + font.family: Style.font.family + font.pixelSize: Style.font.caption + font.letterSpacing: 1.5 + leftPadding: Style.space(2) + } + Rectangle { + width: parent.width + height: rowsColumn.height + 2 + color: win.fill + border.width: 1 + border.color: win.line + Column { + id: rowsColumn + x: 1; y: 1 + width: parent.width - 2 + Repeater { + model: group ? group.rows : [] + SettingRow { + required property var modelData + required property int index + width: rowsColumn.width + row: modelData + first: index === 0 + } + } + } + } + } + + component SettingRow: Item { + id: rowItem + property var row: null + property bool first: false + readonly property bool usable: !!row && row.available !== false && !row.off + readonly property bool focused: win.cursor >= 0 && win.flatRows[win.cursor] === row + readonly property bool isSwitch: !!row && row.kind === "switch" + readonly property bool opens: !!row && (row.kind === "page" || row.kind === "choice" || row.kind === "native") + height: win.rowHeight + (row && row.path && win.searching ? Style.space(12) : 0) + + Rectangle { + visible: !rowItem.first + width: parent.width; height: 1 + color: Util.alpha(win.text, 0.07) + } + Rectangle { + anchors.fill: parent + color: rowPress.pressed ? Util.alpha(win.text, 0.08) : (rowItem.focused ? Util.alpha(win.accent, 0.12) : "transparent") + border.width: rowItem.focused ? 1 : 0 + border.color: Util.alpha(win.accent, 0.6) + } + + Column { + x: Style.space(14) + width: rightSide.x - x - Style.space(10) + anchors.verticalCenter: parent.verticalCenter + spacing: Style.space(1) + opacity: rowItem.usable ? 1 : 0.45 + // The name, and after it what it needs that is not here (Hyprland). + Row { + width: parent.width + spacing: Style.space(10) + Text { + id: labelText + width: Math.min(implicitWidth, parent.width - (tagBox.visible ? tagBox.width + parent.spacing : 0)) + anchors.verticalCenter: parent.verticalCenter + text: rowItem.row ? rowItem.row.label : "" + color: rowItem.row && rowItem.row.current ? win.accent : win.text + font.family: Style.font.family + font.pixelSize: Style.font.subtitle + elide: Text.ElideRight + } + Rectangle { + id: tagBox + visible: !!rowItem.row && !!rowItem.row.tag + anchors.verticalCenter: parent.verticalCenter + width: tagText.width + Style.space(10) + height: tagText.height + Style.space(4) + color: "transparent" + border.width: 1 + border.color: win.line + Text { + id: tagText + anchors.centerIn: parent + text: rowItem.row && rowItem.row.tag ? rowItem.row.tag : "" + color: win.faint + font.family: Style.font.family + font.pixelSize: Style.font.caption + } + } + } + // Where a search result lives. + Text { + visible: !!rowItem.row && !!rowItem.row.path && win.searching + width: parent.width + text: rowItem.row && rowItem.row.path ? rowItem.row.path : "" + color: win.faint + font.family: Style.font.family + font.pixelSize: Style.font.caption + elide: Text.ElideRight + } + } + + Row { + id: rightSide + anchors.right: parent.right + anchors.rightMargin: Style.space(12) + anchors.verticalCenter: parent.verticalCenter + spacing: Style.space(10) + opacity: rowItem.usable ? 1 : 0.45 + Text { + visible: !!rowItem.row && !!rowItem.row.value && !rowItem.isSwitch + width: Math.min(implicitWidth, rowItem.width * 0.45) + anchors.verticalCenter: parent.verticalCenter + text: rowItem.row && rowItem.row.value ? rowItem.row.value : "" + color: win.dim + font.family: Style.font.family + font.pixelSize: Style.font.body + elide: Text.ElideRight + } + Text { + visible: !!rowItem.row && (rowItem.row.current === true || (!!rowItem.row.off && rowItem.row.kind === "option")) + anchors.verticalCenter: parent.verticalCenter + text: "✓" + color: win.accent + font.family: Style.font.family + font.pixelSize: Style.font.title + } + ToggleSwitch { + visible: rowItem.isSwitch + anchors.verticalCenter: parent.verticalCenter + checked: rowItem.row ? win.switchOn(rowItem.row) : false + interactive: false + cursorRing: false + } + Text { + visible: rowItem.opens + anchors.verticalCenter: parent.verticalCenter + text: "›" + color: win.faint + font.family: Style.font.family + font.pixelSize: Style.font.heading + } + } + + TapHandler { + id: rowPress + enabled: rowItem.usable + onTapped: win.activate(rowItem.row) + } + } + + // The current theme as a card: its colours and name. + component ThemeCard: Rectangle { + id: card + property var row: null + height: Style.space(84) + color: win.fill + border.width: 1 + border.color: win.line + // The current theme's own colours, from its colors.toml. + FileView { + id: themeColors + path: Quickshell.env("HOME") + "/.local/state/omarchy/current/theme/colors.toml" + watchChanges: true + printErrors: false + onFileChanged: reload() + } + Row { + id: swatches + x: Style.space(18) + anchors.verticalCenter: parent.verticalCenter + spacing: Style.space(4) + Repeater { + model: Model.swatchesOf(Model.parseColors(themeColors.loaded ? themeColors.text() : "")) + Rectangle { required property var modelData; width: Style.space(12); height: width; color: modelData } + } + } + Column { + x: swatches.x + swatches.width + Style.space(24) + anchors.verticalCenter: parent.verticalCenter + spacing: Style.space(3) + Text { + text: card.row && card.row.value ? card.row.value : (card.row ? card.row.label : "") + color: win.text + font.family: Style.font.family + font.pixelSize: Style.font.title + font.bold: true + } + Text { + text: card.row ? card.row.label : "" + color: win.faint + font.family: Style.font.family + font.pixelSize: Style.font.bodySmall + } + } + Text { + anchors.right: parent.right + anchors.rightMargin: Style.space(16) + anchors.verticalCenter: parent.verticalCenter + text: "›" + color: win.faint + font.family: Style.font.family + font.pixelSize: Style.font.heading + } + TapHandler { onTapped: if (card.row) win.activate(card.row) } + } + +} diff --git a/desktop/shell/shell/settings/SettingsLayout.js b/desktop/shell/shell/settings/SettingsLayout.js index 2561963d..3519cd50 100644 --- a/desktop/shell/shell/settings/SettingsLayout.js +++ b/desktop/shell/shell/settings/SettingsLayout.js @@ -17,8 +17,7 @@ // switch: on while the second is shown // { page: "", label: "", icon: "" } // a Settings page with no menu entry -// and may add `value: ""`, whose first line is the row's current -// value where the entry itself does not say it. +// Values beside these rows come from the Settings host. // // A section is { id, label, icon or iconEntry, groups: [{ label, rows }] }, // or a menu's children as they are (`menu`, Learn); `startsGroup` puts a @@ -57,7 +56,7 @@ var SECTIONS = [ { entry: "setup.language" }, // The time zone and automatic time, in place of the menu's Timezone // and Time (which only restarts time sync). - { page: "datetime", label: "settings.dateTime", icon: "󰥔", value: "timedatectl show -p Timezone --value" } + { page: "datetime", label: "settings.dateTime", icon: "󰥔" } ] }, { label: "", rows: [ { entry: "setup.config" }, @@ -75,13 +74,12 @@ var SECTIONS = [ iconEntry: "appearance", groups: [ { label: "", card: true, rows: [ - { entry: "appearance.theme", page: "theme", value: "omarchy-theme-current" } + { entry: "appearance.theme", page: "theme" } ] }, { label: "settings.style", rows: [ - { entry: "appearance.background", page: "background", - value: "f=$(readlink -f ~/.local/state/omarchy/current/background 2>/dev/null) && f=${f##*/} && f=${f%.*} && f=${f#[0-9]-} && f=${f#[0-9][0-9]-} && echo \"${f//-/ }\"" }, - { entry: "appearance.font", value: "omarchy-font-current" }, - { entry: "appearance.icons", page: "icons", value: "omarchy-icons-current" }, + { entry: "appearance.background", page: "background" }, + { entry: "appearance.font" }, + { entry: "appearance.icons", page: "icons" }, { entry: "appearance.unlock" }, { toggle: ["appearance.animations-on", "appearance.animations-off"], label: "settings.animations" } ] }, @@ -279,12 +277,4 @@ var ELSEWHERE = [ "update.timezone", "update.time" ] -// Upstream commands that mention Hyprland but were checked to work under -// labwc: Settings does not dim their rows (SettingsModel.stateScript). -var LABWC_CHECKED = [ - // Bar style, clock format, battery %: the shell's config, through - // omarchy-shell-config; it reloads Hyprland only for a glassy bar's blur. - "omarchy-bar" -] - -if (typeof module !== "undefined") module.exports = { SECTIONS: SECTIONS, ELSEWHERE: ELSEWHERE, LABWC_CHECKED: LABWC_CHECKED } +if (typeof module !== "undefined") module.exports = { SECTIONS: SECTIONS, ELSEWHERE: ELSEWHERE } diff --git a/desktop/shell/shell/settings/SettingsModel.js b/desktop/shell/shell/settings/SettingsModel.js index ccf242f4..ae291ed6 100644 --- a/desktop/shell/shell/settings/SettingsModel.js +++ b/desktop/shell/shell/settings/SettingsModel.js @@ -20,7 +20,17 @@ function whenAllows(ctx, entry) { return !(ctx.whenResults && ctx.whenResults[entry.id] === false) } +function childIndex(items, order) { + var index = Object.create(null) + for (var i = 0; i < order.length; i++) { + var child = items[order[i]] + if (child) (index[child.parent] || (index[child.parent] = [])).push(child) + } + return index +} + function childrenOf(ctx, id) { + if (ctx && ctx.children) return ctx.children[id] || [] var out = [] var order = ctx && Array.isArray(ctx.itemOrder) ? ctx.itemOrder : [] for (var i = 0; i < order.length; i++) { @@ -429,54 +439,6 @@ function pathLabel(ctx, entry) { return parts.join(" › ") } -// The commands a set of rows needs and the values they show, as one bash -// script: one line per answer, "m\t" for a command not installed, -// "v\t\t" for a value. -function stateScript(sections, ctx, providers) { - var commands = {} - var lines = [] - var order = Array.isArray(ctx.itemOrder) ? ctx.itemOrder : [] - for (var i = 0; i < order.length; i++) { - var entry = item(ctx, order[i]) - if (!entry) continue - var names = commandsIn(entry.action) - if (entry.provider && providers && providers[entry.provider]) names = names.concat(commandsIn(providers[entry.provider].script)) - for (var n = 0; n < names.length; n++) commands[names[n]] = true - } - var checked = (ctx.labwcChecked || []) - var list = Object.keys(commands).sort() - // Missing, or (outside a Hyprland session) calling hyprctl: in doubt a row - // stays dimmed. A command checked to work under labwc too (layout's - // LABWC_CHECKED: omarchy-bar reloads Hyprland only for its blur) is not. - if (list.length) lines.push("for c in " + list.join(" ") + "; do p=$(command -v \"$c\" 2>/dev/null) || { printf 'm\\t%s\\n' \"$c\"; continue; }; [[ -z $HYPRLAND_INSTANCE_SIGNATURE ]] && [[ \" " + checked.join(" ") + " \" != *\" $c \"* ]] && grep -qE '\\bhyprctl\\b|\\bomarchy-hyprland-' \"$p\" 2>/dev/null && printf 'h\\t%s\\n' \"$c\"; done") - for (var s = 0; s < sections.length; s++) - for (var g = 0; g < sections[s].groups.length; g++) - for (var r = 0; r < sections[s].groups[g].rows.length; r++) { - var spec = sections[s].groups[g].rows[r] - if (!spec.value) continue - lines.push("v=$( { " + spec.value + " ; } 2>/dev/null | head -n1 ); [[ -n $v ]] && printf 'v\\t%s\\t%s\\n' " + shellQuote(rowKey(spec)) + " \"$v\"") - } - return lines.join("\n") -} - -function parseState(text) { - var missing = {} - var hyprland = {} - var values = {} - var lines = String(text || "").split("\n") - for (var i = 0; i < lines.length; i++) { - var parts = lines[i].split("\t") - if (parts[0] === "m" && parts[1]) missing[parts[1]] = true - else if (parts[0] === "h" && parts[1]) hyprland[parts[1]] = true - else if (parts[0] === "v" && parts[1]) values[parts[1]] = parts.slice(2).join("\t") - } - return { missing: missing, hyprland: hyprland, values: values } -} - -function shellQuote(value) { - return "'" + String(value).replace(/'/g, "'\\''") + "'" -} - // A deep link: "appearance", "appearance/theme", or a menu id // ("setup.security"), into the section that places it and the page to open. function route(path, sections, ctx) { @@ -557,6 +519,6 @@ if (typeof module !== "undefined") module.exports = { nativePages: nativePages, parseColors: parseColors, displayName: displayName, swatchesOf: swatchesOf, commandsIn: commandsIn, resolveRow: resolveRow, resolveRows: resolveRows, menuSpecs: menuSpecs, choiceRows: choiceRows, sectionGroups: sectionGroups, sectionFor: sectionFor, unplaced: unplaced, - search: search, stateScript: stateScript, parseState: parseState, route: route, pairLabel: pairLabel, + search: search, childIndex: childIndex, route: route, pairLabel: pairLabel, childrenOf: childrenOf, shown: shown, isChoice: isChoice } diff --git a/desktop/shell/shell/settings/SettingsWindow.qml b/desktop/shell/shell/settings/SettingsWindow.qml index 4f024151..af0a2166 100644 --- a/desktop/shell/shell/settings/SettingsWindow.qml +++ b/desktop/shell/shell/settings/SettingsWindow.qml @@ -1,1089 +1,44 @@ import QtQuick import Quickshell -import Quickshell.Io -import qs.Commons import qs.Commons as Commons -import qs.Ui -import "SettingsLayout.js" as Layout -import "SettingsModel.js" as Model -// The window: a sidebar of sections beside the page (wide), or the section -// list and then a page over it (narrow, a phone). Rows come from the layout -// and the menu (SettingsModel.js); a row does what its menu entry does. FloatingWindow { - id: win - - property var host: null - property var menu: null - + id: window + required property var host + readonly property bool contentReady: body.status === Loader.Ready title: Commons.I18n.t("settings.title") color: Commons.Color.background implicitWidth: 980 implicitHeight: 700 minimumSize: Qt.size(320, 420) visible: true - - onClosed: if (host) host.close() - - // ------------------------------------------------------------- the data - - readonly property color text: Commons.Color.foreground - readonly property color dim: Util.alpha(Commons.Color.foreground, 0.6) - readonly property color faint: Util.alpha(Commons.Color.foreground, 0.4) - readonly property color fill: Util.alpha(Commons.Color.foreground, 0.04) - readonly property color line: Util.alpha(Commons.Color.foreground, 0.12) - readonly property color accent: Commons.Color.accent - - readonly property bool wide: content.width >= Style.space(640) - readonly property bool twoColumns: content.width >= Style.space(940) - readonly property int rowHeight: Style.space(42) - readonly property int pad: Style.space(20) - readonly property int sidebarWidth: content.width >= Style.space(940) ? Style.space(260) : Style.space(216) - - // What the menu knows now; every row reads it. - property var values: ({}) - property var missing: ({}) - property var hyprland: ({}) - // A switch flipped a moment ago shows its new state until the menu has - // checked again. - property var pending: ({}) - readonly property var ctx: ({ - items: menu ? menu.items : ({}), - itemOrder: menu ? menu.itemOrder : [], - whenResults: menu ? menu.whenResults : ({}), - checkedResults: menu ? menu.checkedResults : ({}), - disabledResults: menu ? menu.disabledResults : ({}), - values: values, - missing: missing, - hyprland: hyprland, - labwcChecked: Layout.LABWC_CHECKED - }) - readonly property var providers: menu ? menu.providers : ({}) - function t(key) { return Commons.I18n.t(key) } - - readonly property var sections: Layout.SECTIONS - readonly property var sectionBlocks: { - var out = [] - for (var i = 0; i < sections.length; i++) { - if (i === 0 || sections[i].startsGroup) out.push([]) - out[out.length - 1].push(sections[i]) - } - return out - } - - function sectionById(id) { - for (var i = 0; i < sections.length; i++) if (sections[i].id === id) return sections[i] - return null - } - function sectionIcon(section) { - if (section.icon) return section.icon - var e = ctx.items[section.iconEntry] - return e ? e.icon : "" - } - - // ------------------------------------------------------------ navigation - - // The section shown ("" on a phone: the list of sections), and the pages - // opened inside it: { kind: "menu" | "choice" | "native", id, page }. - property string section: "" - property var stack: [] - property string query: "" - readonly property bool searching: query.trim() !== "" - - // A page comes in over the one before from the right and leaves to the - // right again, as on an iPad: the old page is held as a picture while the - // new one is built, so both move together. On a phone the section list is - // a page too; on a wide window the sidebar stays and a section shows in - // place. Without a GPU (software rendering) pages change at once. - readonly property bool gpu: Quickshell.env("QT_QUICK_BACKEND") !== "software" - property int navDirection: 0 - property real navT: 1 - property var navChange: null - property bool navPhone: false - property var navPicture: null - function navigate(direction, change) { - if (!win.gpu || direction === 0 || content.width <= 0 || navAnim.running || navWait.running || win.navHeld) { - if (navAnim.running) navAnim.complete() - change() - return - } - win.navPhone = !win.wide - // A phone's whole window moves; a wide window's page only. - var picture = win.navPhone ? shot : pageShot - picture.sourceItem = win.navPhone ? content : pageMover - if (win.navPhone) { - shot.x = 0 - shot.width = content.width - shot.height = content.height - } - // Only a picture in the scene is taken: shown (too faint to see) until - // it has the old page. - win.navT = 1 - picture.visible = true - picture.scheduleUpdate() - win.navPicture = picture - win.navDirection = direction - win.navChange = change - navWait.start() - } - // A frame for the picture to be taken before the page changes under it. - Timer { - id: navWait - interval: 34 - onTriggered: { - win.navChange() - win.navChange = null - win.navT = 0 - // A page still reading what it shows comes in once it has it: the old - // one stays put till then. - if (win.holdPage) { win.navHeld = true; return } - navAnim.restart() - } - } - property bool navHeld: false - // A native page with data to read (About's facts, the themes) is shown - // only once it has them, or half a second on, so it never comes in short - // and then grows. - readonly property bool pageReady: !nativeLoader.item || nativeLoader.item.ready !== false - property bool holdPage: false - onPageReadyChanged: if (pageReady) holdPage = false - onHoldPageChanged: if (!holdPage && navHeld) { navHeld = false; navAnim.restart() } - Timer { id: readyCap; interval: 500; onTriggered: win.holdPage = false } - NumberAnimation { - id: navAnim - target: win; property: "navT"; from: 0; to: 1 - duration: Style.duration(340) - easing.type: Easing.OutCubic - onStopped: win.navHeld = false - onFinished: { - if (win.navPicture) { win.navPicture.visible = false; win.navPicture.sourceItem = null } - win.navPicture = null - win.navDirection = 0 - } - } - readonly property real navWidth: navPhone ? content.width : pageArea.width - // Where the new page and the picture of the old one stand now. - readonly property real slideNew: navDirection > 0 ? (1 - navT) * navWidth - : navDirection < 0 ? -(1 - navT) * navWidth * 0.3 : 0 - readonly property real slideOld: navDirection > 0 ? -navT * navWidth * 0.3 - : navDirection < 0 ? navT * navWidth : 0 - - function goSection(id) { - // From a phone's list into a section: a page in. - if (!win.wide && win.section === "" && id !== "" && !win.searching) { - win.navigate(1, function() { win.showSection(id) }) - return - } - win.showSection(id) - } - function showSection(id) { - if (id !== "" && id !== sections[0].id) win.chosen = true - win.section = id - win.stack = [] - win.query = "" - searchField.text = "" - win.cursor = -1 - scroller.contentY = 0 - } - function push(page) { - win.navigate(1, function() { win.pushNow(page) }) - } - function pushNow(page) { - win.stack = win.stack.concat([page]) - win.cursor = -1 - scroller.contentY = 0 - if (page.kind === "choice") { - var e = ctx.items[page.id] - if (e && e.provider && menu) { - menu.invalidateVolatileProvider(page.id) - menu.loadProviderForMenu(page.id) - } - } - } - // Back to the page shown under it: a native page's pick (a time zone) puts - // its list away. - function backTo(page) { - var at = -1 - for (var i = 0; i < win.stack.length; i++) if (win.stack[i].page === page) at = i - if (at < 0 || at === win.stack.length - 1) return - win.navigate(-1, function() { win.stack = win.stack.slice(0, at + 1); win.cursor = -1 }) - } - function back() { - if (win.searching) { win.query = ""; searchField.text = ""; return true } - if (win.stack.length > 0) { - win.navigate(-1, function() { win.stack = win.stack.slice(0, -1); win.cursor = -1 }) - return true - } - if (!win.wide && win.section !== "") { - win.navigate(-1, function() { win.section = ""; win.cursor = -1 }) - return true - } - return false - } - function openPath(path) { - var r = Model.route(path, sections, ctx) - win.chosen = r.section !== "" - win.showSection(r.section || (win.wide ? sections[0].id : "")) - if (r.page) win.pushNow(r.page) - } - // Opened without a page: a wide window shows its first section beside the - // list, a phone the list itself. The window learns its width only once it - // is placed, so the choice follows it until a section is picked. - property bool chosen: false - onWideChanged: { - if (win.chosen || win.stack.length > 0 || win.searching) return - win.section = win.wide ? sections[0].id : "" - } - - readonly property var top: stack.length > 0 ? stack[stack.length - 1] : null - - readonly property string pageTitle: { - if (win.searching) return win.t("settings.searchResults") - if (top) { - if (top.kind === "native") { - if (top.title) return top.title - if (top.titleKey) return win.t(top.titleKey) - var nativeEntry = { theme: "appearance.theme", background: "appearance.background", icons: "appearance.icons" }[top.page] - return nativeEntry && ctx.items[nativeEntry] ? ctx.items[nativeEntry].label : top.page - } - var e = ctx.items[top.id] - return e ? (e.title || e.label) : "" - } - var s = sectionById(win.section) - return s ? win.t(s.label) : win.t("settings.title") - } - // "Appearance ›" above a page opened inside a section. - readonly property string backLabel: { - if (!top) return "" - if (stack.length > 1) { - var prev = stack[stack.length - 2] - if (prev.kind === "native" && (prev.title || prev.titleKey)) return prev.title || win.t(prev.titleKey) - var e = prev.kind === "native" ? null : ctx.items[prev.id] - return e ? e.label : "" - } - var s = sectionById(win.section) - return s ? win.t(s.label) : "" - } - - // The rows the page shows, in groups. - readonly property var groups: { - var c = win.ctx - if (win.searching) { - var found = Model.search(win.query, sections, c, providers, win.t) - return found.length ? [{ label: "", rows: found.slice(0, 60) }] : [] - } - if (top) { - if (top.kind === "menu") return [{ label: "", rows: Model.resolveRows(Model.menuSpecs(c, top.id), c, providers, win.t) }] - if (top.kind === "choice") return [{ label: "", rows: Model.choiceRows(c, c.items[top.id]) }] - return [] - } - return Model.sectionGroups(sectionById(win.section), c, providers, win.t) - } - readonly property var nativePage: { - if (win.searching) return "" - if (top && top.kind === "native") return top.page - var s = sectionById(win.section) - return !top && s && s.page ? s.page : "" - } - readonly property var flatRows: { - var out = [] - for (var g = 0; g < groups.length; g++) for (var r = 0; r < groups[g].rows.length; r++) out.push(groups[g].rows[r]) - return out - } - - // ----------------------------------------------------------- doing things - - function activate(row) { - if (!row || row.available === false || row.off) return - if (row.section !== undefined && row.section !== win.section && win.searching) { - // A search result opens where it lives, then does what it does. - var target = row - win.goSection(row.section || win.section || sections[0].id) - win.activate(target) - return - } - if (row.kind === "switch") { - var next = Object.assign({}, win.pending) - next[row.key] = !row.on - win.pending = next - run(row.entry.action) - return - } - if (row.kind === "choice") { win.push({ kind: "choice", id: row.entry.id }); return } - if (row.kind === "page") { win.push({ kind: "menu", id: row.entry.id }); return } - if (row.kind === "native") { - if (sectionById(win.section) && sectionById(win.section).page === row.page && !top) return - win.push({ kind: "native", page: row.page, title: row.label }) - return - } - if (row.kind === "option" || row.kind === "action") run(row.entry.action) - } - - function run(action) { - if (!action || !menu) return - menu.runAction(action) - refreshSoon.restart() - } - - function switchOn(row) { - return win.pending[row.key] !== undefined ? win.pending[row.key] === true : row.on === true - } - - // What changed shows as soon as the menu has checked again: right after - // a change, and once more for commands that take a moment. - Timer { id: refreshSoon; interval: 500; onTriggered: { win.refresh(); refreshLater.restart() } } - Timer { id: refreshLater; interval: 2000; onTriggered: win.refresh() } - function refresh() { - if (menu) menu.evaluateGuards() - stateProc.collected = "" - stateProc.command = ["bash", "-lc", Model.stateScript(sections, ctx, providers)] - stateProc.running = true - } - Connections { - target: win.menu - function onWhenResultsChanged() { win.pending = ({}) } - } - Process { - id: stateProc - property string collected: "" - stdout: SplitParser { onRead: function(data) { stateProc.collected += data + "\n" } } - onExited: { - var s = Model.parseState(stateProc.collected) - win.values = s.values - win.missing = s.missing - win.hyprland = s.hyprland - } - } - - Component.onCompleted: { - if (host) openPath(host.path) - refresh() - content.forceActiveFocus() - } - Connections { - target: win.host - function onPathRevisionChanged() { if (win.host.path) win.openPath(win.host.path) } - } - - // ------------------------------------------------------------- keyboard - - // A cursor over the page's rows, shown once a key moves it. - property int cursor: -1 - function moveCursor(step) { - var n = win.flatRows.length - if (n === 0) return - var i = win.cursor - for (var tries = 0; tries < n; tries++) { - i = i < 0 ? (step > 0 ? 0 : n - 1) : (i + step + n) % n - if (win.flatRows[i].available !== false && !win.flatRows[i].off) break - } - win.cursor = i - } - function moveSection(step) { - var i = 0 - for (var k = 0; k < sections.length; k++) if (sections[k].id === win.section) i = k - win.goSection(sections[(i + step + sections.length) % sections.length].id) - } - - // ---------------------------------------------------------------- layout - - // The old page during a transition: under the new one going forward, over - // it going back, fading as it goes. - ShaderEffectSource { - id: shot - visible: false - live: false - hideSource: false - // It fades as it goes; while it is being taken (navT still 1) it is too - // faint to see. - opacity: Math.max(0.01, 1 - win.navT) - z: win.navDirection < 0 ? 2 : -1 - transform: Translate { x: win.slideOld } - } - - Item { - id: content + onClosed: host.close() + + Text { + x: Commons.Style.space(20) + y: x + visible: !body.item + text: window.title + color: Commons.Color.foreground + font.family: Commons.Style.font.family + font.pixelSize: Commons.Style.font.display + font.bold: true + } + Loader { + id: body anchors.fill: parent + asynchronous: true focus: true - transform: Translate { x: win.navPhone && win.navDirection !== 0 ? win.slideNew : 0 } - // Opaque, so the page going forward covers the picture under it. - Rectangle { anchors.fill: parent; color: win.color; visible: win.navPhone && win.navDirection !== 0 } - - Keys.onPressed: function(event) { - var ctrl = (event.modifiers & Qt.ControlModifier) !== 0 - if (event.key === Qt.Key_Down) { win.moveCursor(1); event.accepted = true } - else if (event.key === Qt.Key_Up) { win.moveCursor(-1); event.accepted = true } - else if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) { - if (win.cursor >= 0 && win.cursor < win.flatRows.length) win.activate(win.flatRows[win.cursor]) - event.accepted = true - } - else if (event.key === Qt.Key_Escape || event.key === Qt.Key_Backspace || (event.key === Qt.Key_Left && (event.modifiers & Qt.AltModifier))) { - event.accepted = win.back() - } - else if (event.key === Qt.Key_PageDown || (ctrl && event.key === Qt.Key_Tab)) { win.moveSection(1); event.accepted = true } - else if (event.key === Qt.Key_PageUp || (ctrl && event.key === Qt.Key_Backtab)) { win.moveSection(-1); event.accepted = true } - else if ((ctrl && event.key === Qt.Key_F) || event.key === Qt.Key_Slash) { searchField.forceActiveFocus(); event.accepted = true } - else if (event.text && event.text.length === 1 && event.text > " " && !ctrl) { - searchField.forceActiveFocus() - searchField.text += event.text - event.accepted = true - } - } - - // ------------------------------------------------------------ sidebar - - Item { - id: sidebar - visible: win.wide || win.section === "" - width: win.wide ? win.sidebarWidth : parent.width - height: parent.height - - Flickable { - anchors.fill: parent - contentHeight: sideColumn.height + win.pad * 2 - clip: true - boundsBehavior: Flickable.StopAtBounds - interactive: contentHeight > height - - Column { - id: sideColumn - x: win.pad - y: win.pad - width: parent.width - win.pad * (win.wide ? 1.5 : 2) - spacing: Style.space(14) - - Text { - text: win.t("settings.title") - color: win.text - font.family: Style.font.family - font.pixelSize: Style.font.display - font.bold: true - } - - // Search: every setting, and every menu entry beside them. - Rectangle { - width: parent.width - height: Style.space(38) - color: win.fill - border.width: 1 - border.color: searchField.activeFocus ? Util.alpha(win.accent, 0.7) : win.line - Text { - id: searchGlyph - x: Style.space(12) - anchors.verticalCenter: parent.verticalCenter - text: "" - color: win.faint - font.family: Style.font.menuFamily - font.pixelSize: Style.font.body - } - TextInput { - id: searchField - x: searchGlyph.x + searchGlyph.width + Style.space(10) - width: parent.width - x - Style.space(10) - anchors.verticalCenter: parent.verticalCenter - color: win.text - font.family: Style.font.family - font.pixelSize: Style.font.subtitle - selectionColor: Util.alpha(win.accent, 0.4) - clip: true - onTextChanged: { win.query = text; win.cursor = -1 } - Keys.onPressed: function(event) { - if (event.key === Qt.Key_Escape) { text = ""; content.forceActiveFocus(); event.accepted = true } - else if (event.key === Qt.Key_Down || event.key === Qt.Key_Return || event.key === Qt.Key_Enter) { - content.forceActiveFocus() - if (event.key === Qt.Key_Down) win.moveCursor(1) - else if (win.flatRows.length > 0) win.activate(win.flatRows[0]) - event.accepted = true - } - } - Text { - visible: searchField.text === "" - text: win.t("settings.search") - color: win.faint - font: searchField.font - } - } - } - - // A phone's search results, under the field. - Text { - visible: !win.wide && win.searching && win.groups.length === 0 - text: win.t("settings.noResults") - color: win.faint - font.family: Style.font.family - font.pixelSize: Style.font.subtitle - } - Repeater { - model: !win.wide && win.searching ? win.groups : [] - Group { - required property var modelData - width: sideColumn.width - group: modelData - } - } - - // The sections; on a phone, the root list with what each holds, in - // one box with a line between rows. - // The sections fall into kinds (startsGroup), a gap between. - Column { - width: parent.width - visible: !(win.searching && !win.wide) - spacing: win.wide ? Style.space(12) : Style.space(16) - Repeater { - model: win.sectionBlocks - Rectangle { - id: block - required property var modelData - required property int index - width: parent.width - height: sectionList.height + (win.wide ? 0 : 2) - color: win.wide ? "transparent" : win.fill - border.width: win.wide ? 0 : 1 - border.color: win.line - // In the sidebar, a faint line in the gap above each kind. - Rectangle { - visible: win.wide && block.index > 0 - x: Style.space(12) - y: -Style.space(6) - 1 - width: parent.width - 2 * Style.space(12) - height: 1 - color: Util.alpha(win.text, 0.08) - } - Column { - id: sectionList - x: win.wide ? 0 : 1 - y: win.wide ? 0 : 1 - width: parent.width - (win.wide ? 0 : 2) - spacing: win.wide ? Style.space(2) : 0 - Repeater { - model: block.modelData - Rectangle { - id: sectionRow - required property var modelData - required property int index - readonly property bool current: win.wide && win.section === modelData.id && !win.searching - width: parent.width - height: win.wide ? Style.space(40) : Style.space(54) - color: current ? Util.alpha(win.accent, 0.14) : "transparent" - Rectangle { - visible: !win.wide && sectionRow.index > 0 - width: parent.width; height: 1 - color: Util.alpha(win.text, 0.07) - } - Rectangle { - visible: sectionRow.current - width: Style.space(2); height: parent.height - color: win.accent - } - Text { - id: sectionGlyph - x: Style.space(12) - width: Style.space(22) - anchors.verticalCenter: parent.verticalCenter - text: win.sectionIcon(sectionRow.modelData) - color: sectionRow.current || !win.wide ? win.accent : win.dim - font.family: Style.font.menuFamily - font.pixelSize: Style.font.title - horizontalAlignment: Text.AlignHCenter - } - Column { - x: sectionGlyph.x + sectionGlyph.width + Style.space(12) - width: parent.width - x - Style.space(30) - anchors.verticalCenter: parent.verticalCenter - spacing: Style.space(2) - Text { - width: parent.width - text: win.t(sectionRow.modelData.label) - color: win.text - font.family: Style.font.family - font.pixelSize: Style.font.subtitle - font.bold: sectionRow.current - elide: Text.ElideRight - } - // What it holds: its groups, as the section itself names them. - Text { - visible: !win.wide && text !== "" - width: parent.width - text: { - var names = [] - var gs = sectionRow.modelData.groups - for (var i = 0; i < gs.length && names.length < 3; i++) if (gs[i].label) names.push(win.t(gs[i].label)) - return names.join(", ") - } - color: win.faint - font.family: Style.font.family - font.pixelSize: Style.font.bodySmall - elide: Text.ElideRight - } - } - Text { - visible: !win.wide - anchors.right: parent.right - anchors.rightMargin: Style.space(14) - anchors.verticalCenter: parent.verticalCenter - text: "›" - color: win.faint - font.family: Style.font.family - font.pixelSize: Style.font.heading - } - TapHandler { onTapped: { win.chosen = true; win.goSection(sectionRow.modelData.id) } } - } - } - } - } - } - } - } - } - } - - // --------------------------------------------------------------- page - - Item { - id: pageArea - // On a phone a search shows under its field, in the list. - visible: win.wide || win.section !== "" - x: win.wide ? sidebar.width : 0 - width: parent.width - x - height: parent.height - // On a wide window a page moves within its own area, never over the - // sidebar. - clip: true - - // The old page during a transition here: under the new one going - // forward, over it going back. - ShaderEffectSource { - id: pageShot - width: pageArea.width - height: pageArea.height - visible: false - live: false - hideSource: false - opacity: Math.max(0.01, 1 - win.navT) - z: win.navDirection < 0 ? 2 : 0 - transform: Translate { x: win.slideOld } - } - - Item { - id: pageMover - anchors.fill: parent - z: 1 - transform: Translate { x: !win.navPhone && win.navDirection !== 0 ? win.slideNew : 0 } - // Opaque, so the page going forward covers the picture under it. - Rectangle { anchors.fill: parent; color: win.color; visible: !win.navPhone && win.navDirection !== 0 } - - Flickable { - id: scroller - anchors.fill: parent - contentHeight: pageColumn.height + win.pad * 2 - clip: true - boundsBehavior: Flickable.StopAtBounds - interactive: contentHeight > height - - Column { - id: pageColumn - x: win.pad - y: win.pad - width: parent.width - win.pad * 2 - spacing: Style.space(14) - // Shown in place (a wide window's section) only with its data in. - opacity: win.holdPage && win.navDirection === 0 ? 0 : 1 - - // Back and the title. On a phone the back reads "‹ Settings" at - // the top of a section. - Item { - width: parent.width - height: Math.max(titleText.height, backRow.visible ? backRow.height : 0) - Row { - id: backRow - visible: win.stack.length > 0 || (!win.wide && (win.section !== "" || win.searching)) - anchors.verticalCenter: parent.verticalCenter - spacing: Style.space(6) - // A drawn chevron, so it sits on the label's middle whatever - // the font does with its glyphs. - Item { - width: Style.space(10) - height: backLabelText.height - anchors.verticalCenter: parent.verticalCenter - Repeater { - model: [-1, 1] - Rectangle { - required property var modelData - width: Style.space(9) - height: Math.max(2, Style.space(2)) - radius: height / 2 - color: win.accent - antialiasing: true - x: Style.space(1) - y: (parent.height - height) / 2 - rotation: modelData * 45 - transformOrigin: Item.Left - } - } - } - Text { - id: backLabelText - text: win.stack.length > 0 ? win.backLabel : win.t("settings.title") - color: win.accent - font.family: Style.font.family - font.pixelSize: Style.font.subtitle - anchors.verticalCenter: parent.verticalCenter - } - TapHandler { onTapped: win.back() } - } - // On a phone the title stands in the middle, as a phone's - // settings show it; on a wide window after the back link. - Text { - id: titleText - readonly property bool centered: !win.wide && backRow.visible - // Worked out from the back link and the text alone, so where it - // stands and how wide it is never wait on each other. - readonly property real leftEdge: backRow.visible ? backRow.width + Style.space(centered ? 12 : 16) : 0 - readonly property real titleWidth: centered - ? Math.min(implicitWidth, parent.width - 2 * leftEdge) - : parent.width - leftEdge - (moreButton.visible ? moreButton.width + Style.space(10) : 0) - x: centered ? Math.max(leftEdge, (parent.width - titleWidth) / 2) : leftEdge - width: titleWidth - horizontalAlignment: centered ? Text.AlignHCenter : Text.AlignLeft - anchors.verticalCenter: parent.verticalCenter - text: win.pageTitle - color: win.text - font.family: Style.font.family - font.pixelSize: !backRow.visible ? Style.font.display : Style.font.heading - font.bold: true - elide: Text.ElideRight - } - // The theme page's "Get more", where the menu offers it. - Rectangle { - id: moreButton - readonly property var entry: win.ctx.items["update.themes"] - visible: win.nativePage === "theme" && !!entry && Model.shown(win.ctx, entry) - anchors.right: parent.right - anchors.verticalCenter: parent.verticalCenter - width: moreText.width + Style.space(24) - height: Style.space(32) - color: "transparent" - border.width: 1 - border.color: win.line - Text { - id: moreText - anchors.centerIn: parent - text: moreButton.entry ? moreButton.entry.label : "" - color: win.text - font.family: Style.font.family - font.pixelSize: Style.font.body - } - TapHandler { onTapped: win.run(moreButton.entry.action) } - } - } - - Text { - visible: win.searching && win.groups.length === 0 - text: win.t("settings.noResults") - color: win.faint - font.family: Style.font.family - font.pixelSize: Style.font.subtitle - } - - Loader { - id: nativeLoader - width: parent.width - onLoaded: if (!win.pageReady) { win.holdPage = true; readyCap.restart() } - active: win.nativePage !== "" - visible: active - sourceComponent: win.nativePage === "theme" ? themePage - : win.nativePage === "background" ? backgroundPage - : win.nativePage === "icons" ? iconsPage - : win.nativePage === "about" ? aboutPage - : win.nativePage === "wifi" ? wifiPage - : win.nativePage === "wifinetwork" ? wifiNetworkPage - : win.nativePage === "bluetooth" ? bluetoothPage - : win.nativePage === "sound" ? soundPage - : win.nativePage === "display" ? displayPage - : win.nativePage === "datetime" ? dateTimePage - : win.nativePage === "timezone" ? timezonePage - : win.nativePage === "shortcuts" ? shortcutsPage : null - } - - // The section's groups: the card first, then two columns where the - // window is wide enough, one otherwise. - Repeater { - model: win.groups.filter(function(g) { return g.card }) - ThemeCard { - required property var modelData - width: pageColumn.width - row: modelData.rows[0] - } - } - Row { - id: columns - // A section's own page shows its groups under it (Wi-Fi, About). - visible: win.nativePage === "" || !win.top - width: parent.width - spacing: Style.space(18) - readonly property var plain: win.groups.filter(function(g) { return !g.card }) - readonly property bool split: win.twoColumns && plain.length > 1 && !win.top && !win.searching - // Groups go to the shorter column, in order. - readonly property var halves: { - var left = [], right = [], lh = 0, rh = 0 - for (var i = 0; i < plain.length; i++) { - var h = plain[i].rows.length + (plain[i].label ? 1 : 0) + 1 - if (!split || lh <= rh) { left.push(plain[i]); lh += h } else { right.push(plain[i]); rh += h } - } - return [left, right] - } - Repeater { - model: columns.split ? 2 : 1 - Column { - required property int index - width: columns.split ? (columns.width - columns.spacing) / 2 : columns.width - spacing: Style.space(14) - Repeater { - model: columns.halves[index] - Group { - required property var modelData - width: parent.width - group: modelData - } - } - } - } - } - - } - } - } - } - } - - // ----------------------------------------------------------- components - - component Group: Column { - property var group: null - spacing: Style.space(6) - Text { - visible: !!group && group.label !== "" - text: group ? group.label.toUpperCase() : "" - color: win.faint - font.family: Style.font.family - font.pixelSize: Style.font.caption - font.letterSpacing: 1.5 - leftPadding: Style.space(2) - } - Rectangle { - width: parent.width - height: rowsColumn.height + 2 - color: win.fill - border.width: 1 - border.color: win.line - Column { - id: rowsColumn - x: 1; y: 1 - width: parent.width - 2 - Repeater { - model: group ? group.rows : [] - SettingRow { - required property var modelData - required property int index - width: rowsColumn.width - row: modelData - first: index === 0 - } - } - } - } - } - - component SettingRow: Item { - id: rowItem - property var row: null - property bool first: false - readonly property bool usable: !!row && row.available !== false && !row.off - readonly property bool focused: win.cursor >= 0 && win.flatRows[win.cursor] === row - readonly property bool isSwitch: !!row && row.kind === "switch" - readonly property bool opens: !!row && (row.kind === "page" || row.kind === "choice" || row.kind === "native") - height: win.rowHeight + (row && row.path && win.searching ? Style.space(12) : 0) - - Rectangle { - visible: !rowItem.first - width: parent.width; height: 1 - color: Util.alpha(win.text, 0.07) - } - Rectangle { - anchors.fill: parent - color: rowPress.pressed ? Util.alpha(win.text, 0.08) : (rowItem.focused ? Util.alpha(win.accent, 0.12) : "transparent") - border.width: rowItem.focused ? 1 : 0 - border.color: Util.alpha(win.accent, 0.6) - } - - Column { - x: Style.space(14) - width: rightSide.x - x - Style.space(10) - anchors.verticalCenter: parent.verticalCenter - spacing: Style.space(1) - opacity: rowItem.usable ? 1 : 0.45 - // The name, and after it what it needs that is not here (Hyprland). - Row { - width: parent.width - spacing: Style.space(10) - Text { - id: labelText - width: Math.min(implicitWidth, parent.width - (tagBox.visible ? tagBox.width + parent.spacing : 0)) - anchors.verticalCenter: parent.verticalCenter - text: rowItem.row ? rowItem.row.label : "" - color: rowItem.row && rowItem.row.current ? win.accent : win.text - font.family: Style.font.family - font.pixelSize: Style.font.subtitle - elide: Text.ElideRight - } - Rectangle { - id: tagBox - visible: !!rowItem.row && !!rowItem.row.tag - anchors.verticalCenter: parent.verticalCenter - width: tagText.width + Style.space(10) - height: tagText.height + Style.space(4) - color: "transparent" - border.width: 1 - border.color: win.line - Text { - id: tagText - anchors.centerIn: parent - text: rowItem.row && rowItem.row.tag ? rowItem.row.tag : "" - color: win.faint - font.family: Style.font.family - font.pixelSize: Style.font.caption - } - } - } - // Where a search result lives. - Text { - visible: !!rowItem.row && !!rowItem.row.path && win.searching - width: parent.width - text: rowItem.row && rowItem.row.path ? rowItem.row.path : "" - color: win.faint - font.family: Style.font.family - font.pixelSize: Style.font.caption - elide: Text.ElideRight - } - } - - Row { - id: rightSide - anchors.right: parent.right - anchors.rightMargin: Style.space(12) - anchors.verticalCenter: parent.verticalCenter - spacing: Style.space(10) - opacity: rowItem.usable ? 1 : 0.45 - Text { - visible: !!rowItem.row && !!rowItem.row.value && !rowItem.isSwitch - width: Math.min(implicitWidth, rowItem.width * 0.45) - anchors.verticalCenter: parent.verticalCenter - text: rowItem.row && rowItem.row.value ? rowItem.row.value : "" - color: win.dim - font.family: Style.font.family - font.pixelSize: Style.font.body - elide: Text.ElideRight - } - Text { - visible: !!rowItem.row && (rowItem.row.current === true || (!!rowItem.row.off && rowItem.row.kind === "option")) - anchors.verticalCenter: parent.verticalCenter - text: "✓" - color: win.accent - font.family: Style.font.family - font.pixelSize: Style.font.title - } - ToggleSwitch { - visible: rowItem.isSwitch - anchors.verticalCenter: parent.verticalCenter - checked: rowItem.row ? win.switchOn(rowItem.row) : false - interactive: false - cursorRing: false - } - Text { - visible: rowItem.opens - anchors.verticalCenter: parent.verticalCenter - text: "›" - color: win.faint - font.family: Style.font.family - font.pixelSize: Style.font.heading - } - } - - TapHandler { - id: rowPress - enabled: rowItem.usable - onTapped: win.activate(rowItem.row) - } } - - // The current theme as a card: its colours and name. - component ThemeCard: Rectangle { - id: card - property var row: null - height: Style.space(84) - color: win.fill - border.width: 1 - border.color: win.line - // The current theme's own colours, from its colors.toml. - FileView { - id: themeColors - path: Quickshell.env("HOME") + "/.local/state/omarchy/current/theme/colors.toml" - watchChanges: true - printErrors: false - onFileChanged: reload() - } - Row { - id: swatches - x: Style.space(18) - anchors.verticalCenter: parent.verticalCenter - spacing: Style.space(4) - Repeater { - model: Model.swatchesOf(Model.parseColors(themeColors.loaded ? themeColors.text() : "")) - Rectangle { required property var modelData; width: Style.space(12); height: width; color: modelData } - } - } - Column { - x: swatches.x + swatches.width + Style.space(24) - anchors.verticalCenter: parent.verticalCenter - spacing: Style.space(3) - Text { - text: card.row && card.row.value ? card.row.value : (card.row ? card.row.label : "") - color: win.text - font.family: Style.font.family - font.pixelSize: Style.font.title - font.bold: true - } - Text { - text: card.row ? card.row.label : "" - color: win.faint - font.family: Style.font.family - font.pixelSize: Style.font.bodySmall - } - } - Text { - anchors.right: parent.right - anchors.rightMargin: Style.space(16) - anchors.verticalCenter: parent.verticalCenter - text: "›" - color: win.faint - font.family: Style.font.family - font.pixelSize: Style.font.heading + FrameAnimation { + property bool requested: false + running: window.visible && !requested + onTriggered: { + if (currentFrame < 2) return + // An already-compiled component may only emit sourceChanged after + // incubation finishes. Disarm before setSource can start that work. + requested = true + body.setSource(Qt.resolvedUrl("SettingsContent.qml"), { host: window.host }) } - TapHandler { onTapped: if (card.row) win.activate(card.row) } } - - // ------------------------------------------------------- native pages - - Component { id: themePage; ThemePage { settings: win } } - Component { id: backgroundPage; BackgroundPage { settings: win } } - Component { id: iconsPage; IconsPage { settings: win } } - Component { id: aboutPage; AboutPage { settings: win } } - Component { id: wifiPage; WifiPage { settings: win } } - Component { id: bluetoothPage; BluetoothPage { settings: win } } - Component { id: soundPage; SoundPage { settings: win } } - Component { id: displayPage; DisplayPage { settings: win } } - Component { id: dateTimePage; DateTimePage { settings: win } } - Component { id: timezonePage; TimezonePage { settings: win } } - Component { id: wifiNetworkPage; WifiNetworkPage { settings: win } } - Component { id: shortcutsPage; ShortcutsPage { settings: win } } } diff --git a/desktop/shell/shell/settings/ThemePage.qml b/desktop/shell/shell/settings/ThemePage.qml index cd410f3c..28b9231d 100644 --- a/desktop/shell/shell/settings/ThemePage.qml +++ b/desktop/shell/shell/settings/ThemePage.qml @@ -28,32 +28,16 @@ Item { Process { id: lister running: true - command: ["bash", "-lc", [ - "cat ~/.local/state/omarchy/current/theme.name 2>/dev/null; echo", - "for dir in ~/.config/omarchy/themes/*/ \"$OMARCHY_PATH\"/themes/*/; do", - " [[ -f $dir/colors.toml ]] || continue", - " name=${dir%/}; name=${name##*/}", - // The wallpaper a switch to it starts on: omarchy-theme-set's first. - " bg=$(find -L \"$dir/backgrounds\" -maxdepth 1 -type f ! -name '._*' \\( -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.png' -o -iname '*.webp' \\) -printf '%f\\n' 2>/dev/null | sort | head -1)", - " [[ -n $bg ]] && bg=${dir}backgrounds/$bg", - " printf 't\\t%s\\t%s\\t%s\\n' \"$name\" \"$(tr '\\n' ';' < \"$dir/colors.toml\")\" \"$bg\"", - "done" - ].join("\n")] - property string collected: "" - stdout: SplitParser { onRead: function(data) { lister.collected += data + "\n" } } - onExited: { - var lines = lister.collected.split("\n") - page.current = lines[0].trim() - var seen = {} - var out = [] - for (var i = 1; i < lines.length; i++) { - var parts = lines[i].split("\t") - if (parts[0] !== "t" || !parts[1] || seen[parts[1]]) continue - seen[parts[1]] = true - out.push({ slug: parts[1], name: Model.displayName(parts[1]), colors: Model.parseColors((parts[2] || "").split(";").join("\n")), wallpaper: parts[3] || "" }) + command: ["python3", Quickshell.env("OMARCHY_PATH") + "/shell/settings/page-data.py", "themes"] + stdout: StdioCollector { + waitForEnd: true + onStreamFinished: { + if (!text.trim()) return + var data = JSON.parse(text) + page.current = data.current + page.themes = data.rows.map(function(row) { row.name = Model.displayName(row.slug); row.colors = Model.parseColors(row.colors); return row }) + page.ready = true } - page.themes = out - page.ready = true } } @@ -86,8 +70,8 @@ Item { anchors.fill: parent anchors.margins: parent.border.width visible: status === Image.Ready - source: tile.modelData.wallpaper ? Util.fileUrl(tile.modelData.wallpaper) : "" - sourceSize.width: Math.ceil(width * 2) + source: width > 0 && height > 0 && tile.modelData.wallpaper ? Util.fileUrl(tile.modelData.wallpaper) : "" + sourceSize: Qt.size(Math.ceil(width * Screen.devicePixelRatio), Math.ceil(height * Screen.devicePixelRatio)) fillMode: Image.PreserveAspectCrop asynchronous: true cache: false diff --git a/desktop/shell/shell/settings/TimezonePage.qml b/desktop/shell/shell/settings/TimezonePage.qml index d847d53a..d5436e00 100644 --- a/desktop/shell/shell/settings/TimezonePage.qml +++ b/desktop/shell/shell/settings/TimezonePage.qml @@ -12,7 +12,7 @@ Item { property var settings: null // The region this page lists, or "" for the regions and the search. - readonly property string region: settings && settings.top && settings.top.region ? settings.top.region : "" + readonly property string region: settings && settings.currentPage && settings.currentPage.region ? settings.currentPage.region : "" width: parent ? parent.width : 0 height: column.height @@ -20,7 +20,7 @@ Item { property var zones: [] // The list read: Settings shows the page (and slides it in) only then. readonly property bool ready: zones.length > 0 - property string current: "" + readonly property string current: settings ? settings.host.timezone : "" Process { running: true command: ["timedatectl", "list-timezones"] @@ -32,11 +32,7 @@ Item { }) } } - Process { - running: true - command: ["timedatectl", "show", "-p", "Timezone", "--value"] - stdout: StdioCollector { onStreamFinished: page.current = String(text).trim() } - } + // "America/Argentina/Buenos_Aires": the city, then where it is. function city(zone) { var p = zone.split("/"); return p[p.length - 1].replace(/_/g, " ") } diff --git a/desktop/shell/shell/settings/WifiNetworkPage.qml b/desktop/shell/shell/settings/WifiNetworkPage.qml index 54e0d993..020176cb 100644 --- a/desktop/shell/shell/settings/WifiNetworkPage.qml +++ b/desktop/shell/shell/settings/WifiNetworkPage.qml @@ -4,7 +4,6 @@ import Quickshell.Io import Quickshell.Networking import qs.Commons import qs.Commons as Commons -import "../plugins/panels/network" as Network import "../plugins/panels/network/Model.js" as NetModel // One network's page (Wi-Fi > a known network's info button, or the network @@ -15,12 +14,12 @@ Item { id: page property var settings: null - readonly property string ssid: settings && settings.top && settings.top.ssid ? settings.top.ssid : "" + readonly property string ssid: settings && settings.currentPage && settings.currentPage.ssid ? settings.currentPage.ssid : "" width: parent ? parent.width : 0 height: column.height - Network.Status { id: status } + readonly property var status: SessionStatus.network readonly property var network: { var list = status.wifiNetworkObjects || [] @@ -42,24 +41,37 @@ Item { property string router: "" property var dns: [] property bool ready: false - function read() { if (!reader.running) reader.running = true } - Component.onCompleted: read() - onConnectedChanged: read() - onKnownChanged: { read(); if (!known && !changing && ready && settings) settings.back() } + readonly property string profileId: network && network.nmSettings && network.nmSettings.length + ? network.nmSettings[0].uuid : "" + property bool pendingRead: false + function read() { + if (reader.running) { pendingRead = true; return } + pendingRead = false + reader.running = true + } + onProfileIdChanged: Qt.callLater(page.read) + Component.onCompleted: Qt.callLater(page.read) + onConnectedChanged: Qt.callLater(page.read) + onKnownChanged: { Qt.callLater(page.read); if (!known && !changing && ready && settings) settings.back() } Process { id: reader + onExited: if (page.pendingRead) Qt.callLater(page.read) command: ["bash", "-c", [ - "ssid=$1 dev=$2", - "while IFS=: read -r u t; do", - " [[ $t == 802-11-wireless ]] || continue", - " [[ $(nmcli -g 802-11-wireless.ssid connection show \"$u\" 2>/dev/null) == \"$ssid\" ]] || continue", - " printf 'uuid\\t%s\\n' \"$u\"", - " printf 'auto\\t%s\\n' \"$(nmcli -g connection.autoconnect connection show \"$u\")\"", - " printf 'key\\t%s\\n' \"$(nmcli -g 802-11-wireless-security.key-mgmt connection show \"$u\")\"", - " break", - "done < <(nmcli -g UUID,TYPE connection show 2>/dev/null)", - "[[ -n $dev ]] && nmcli -t -f IP4.ADDRESS,IP4.GATEWAY,IP4.DNS device show \"$dev\" 2>/dev/null | sed 's/^/ip\\t/'" - ].join("\n"), "wifi-network", page.ssid, page.connected ? page.device : ""] + 'export LC_ALL=C; ssid=$1 dev=$2 u=$3', + // Older backends can omit the saved profile. Resolve it by SSID then. + 'if [[ -z $u && $4 == known ]]; then', + ' while IFS=: read -r id type; do', + ' [[ $type == 802-11-wireless ]] || continue', + ' [[ $(nmcli -g 802-11-wireless.ssid connection show uuid "$id") == "$ssid" ]] && { u=$id; break; }', + ' done < <(nmcli -g UUID,TYPE connection show)', + 'fi', + 'if [[ -n $u ]]; then', + ' mapfile -t profile < <(nmcli -g connection.autoconnect,802-11-wireless-security.key-mgmt connection show uuid "$u")', + ' printf "uuid\\t%s\\nauto\\t%s\\nkey\\t%s\\n" "$u" "${profile[0]}" "${profile[1]}"', + 'fi', + 'if [[ -n $dev ]]; then while IFS= read -r line; do printf "ip\\t%s\\n" "$line"; done < <(nmcli -t -f IP4.ADDRESS,IP4.GATEWAY,IP4.DNS device show "$dev"); fi' + ].join("\n"), "wifi-network", page.ssid, page.connected ? page.device : "", page.profileId, + page.known ? "known" : ""] stdout: StdioCollector { onStreamFinished: { var uuid = "", auto = true, key = "", address = "", router = "", dns = [] diff --git a/desktop/shell/shell/settings/WifiPage.qml b/desktop/shell/shell/settings/WifiPage.qml index 4a7b5590..a3d6ef41 100644 --- a/desktop/shell/shell/settings/WifiPage.qml +++ b/desktop/shell/shell/settings/WifiPage.qml @@ -4,7 +4,6 @@ import Quickshell.Io import Quickshell.Networking import qs.Commons import qs.Commons as Commons -import "../plugins/panels/network" as Network import "../plugins/panels/network/Model.js" as NetModel // Wi-Fi: the switch, the network in use, known and other networks (a tap @@ -21,7 +20,7 @@ Item { width: parent ? parent.width : 0 height: column.height - Network.Status { id: status } + readonly property var status: SessionStatus.network readonly property bool wifiOn: status.wifiEnabled readonly property bool hasWifi: !!status.wifiDevice diff --git a/desktop/shell/shell/settings/page-data.py b/desktop/shell/shell/settings/page-data.py new file mode 100644 index 00000000..7826d9e4 --- /dev/null +++ b/desktop/shell/shell/settings/page-data.py @@ -0,0 +1,90 @@ +"""Read data for the Settings page being displayed. Paths in JSON can contain newlines.""" +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys + +home = Path.home() +current = home / ".local/state/omarchy/current" +config = home / ".config/omarchy" +omarchy = Path(os.environ["OMARCHY_PATH"]) +pictures = {".jpg", ".jpeg", ".png", ".webp"} +videos = {".mp4", ".webm", ".mov", ".mkv"} + + +def read(path): + try: + return path.read_text(errors="replace").strip("\0\n ") + except OSError: + return "" + + +def output(*argv): + try: + return subprocess.check_output(argv, stderr=subprocess.DEVNULL, text=True, timeout=4).strip() + except (OSError, subprocess.SubprocessError): + return "" + + +def appearance(): + background = (current / "background").resolve().stem + return {"font": output("fc-match", "monospace", "-f", "%{family}").partition(",")[0], + "background": re.sub(r"^\d+-", "", background).replace("-", " ") if (current / "background").exists() else ""} + + +def entries(kind): + seen = set() + for base in (config, omarchy): + for path in sorted((base / kind).glob("*/")): + if path.name not in seen and path.is_dir() and (kind != "themes" or (path / "colors.toml").is_file()): + seen.add(path.name) + yield path + + +def themes(): + rows = [] + for path in entries("themes"): + images = sorted(p for p in (path / "backgrounds").glob("*") if not p.name.startswith("._") + and p.suffix.lower() in pictures and p.is_file()) + rows.append({"slug": path.name, "colors": read(path / "colors.toml"), + "wallpaper": str(images[0]) if images else ""}) + return {"current": read(current / "theme.name"), "rows": rows} + + +def icons(): + rows = [{"id": p.name, "preview": str(p / "preview.png") if (p / "preview.png").is_file() else ""} + for p in entries("icons")] + if all(row["id"] != "original" for row in rows): + rows.append({"id": "original", "preview": ""}) + return {"current": read(current / "icons.name") or "papercraft", "rows": rows} + + +def backgrounds(): + rows = [] + theme = read(current / "theme.name") + for folder in (current / "theme/backgrounds", config / "backgrounds" / theme): + for p in sorted(folder.glob("*")): + ext = p.suffix.lower() + if ext in pictures | videos | {".gif", ".bmp"} and p.is_file(): + rows.append({"path": str(p), "real": str(p.resolve()), "video": ext in videos}) + return {"current": str((current / "background").resolve()), "rows": rows} + + +def about(): + import platform + usage = shutil.disk_usage("/") + memory = next((line.split()[1] for line in read(Path("/proc/meminfo")).splitlines() + if line.startswith("MemTotal:")), "") + return {"Device": read(Path("/proc/device-tree/model")) or read(Path("/sys/class/dmi/id/product_name")), + "Name": os.uname().nodename, "System": platform.freedesktop_os_release().get("PRETTY_NAME", ""), + "Version": output("omarchy-version"), "Kernel": os.uname().release, + "Memory": f"{int(memory) / 1048576:.1f} GB" if memory else "", + "Storage": f"{usage.free / 1e9:.0f} GB of {usage.total / 1e9:.0f} GB free"} + + +if __name__ == "__main__": + print(json.dumps({"appearance": appearance, "themes": themes, "icons": icons, + "backgrounds": backgrounds, "about": about}[sys.argv[1]]())) diff --git a/desktop/shell/shell/shell.qml b/desktop/shell/shell/shell.qml index 4f4de6d7..eabc1c93 100644 --- a/desktop/shell/shell/shell.qml +++ b/desktop/shell/shell/shell.qml @@ -11,6 +11,7 @@ import Quickshell.Io import qs.Commons import qs.Commons as Commons +import qs.Ui import "plugins/bar" import "launcher" @@ -29,31 +30,94 @@ ShellRoot { // own empty copies. property PluginRegistry pluginRegistry: PluginRegistry { } property BarWidgetRegistry barWidgetRegistry: BarWidgetRegistry { } - property AppLibrary appLibrary: AppLibrary { } + property AppLibrary appLibrary: AppLibrary { backdrop.backgroundService: shell.bootIntro ? shell.bootIntro.backgroundService : null } // Orchard: the launcher answers the stock Apps menu action // (`omarchy-shell omarchy.dock apps`), so Home, Super, Super+Space and the // bar's logo open it, without mapping Hyprland's dock. - Launcher { id: appGrid; shell: shell; appLibrary: shell.appLibrary } - // Orchard: the control center (`omarchy-shell omarchy.controlcenter toggle`). - ControlCenter { id: controlCenter; shell: shell } - NotificationCenter { id: notificationCenter; shell: shell } - Settings { id: settings; shell: shell } - // The bar pulls it down from the top edge's right third (Bar.qml). - readonly property var controlCenter: controlCenter - readonly property var notificationCenter: notificationCenter - readonly property var settings: settings - readonly property var launcher: appGrid + // Lazy panels get the root through their loader: inside the component, `shell` + // names the panel's own (still null) shell property, not this object. + OnDemandLoader { + id: appGrid + keepAlive: true + readonly property var rootShell: shell + sourceComponent: Launcher { shell: appGrid.rootShell; appLibrary: appGrid.rootShell.appLibrary } + } + readonly property var launcher: appGrid.item ShellIpc { target: "omarchy.dock" - function apps(): void { appGrid.toggle() } - // For callers that must not toggle: the overview puts the drawer away - // when it opens. - function closeApps(): void { if (appGrid.opened) appGrid.close() } - // The long bottom swipe (labwc's bottomSwipeFarCommand) opens it, and - // never closes it. - function openApps(): void { if (!appGrid.opened) appGrid.open() } + function apps(): void { appGrid.load().toggle() } + function closeApps(): void { if (shell.launcher && shell.launcher.opened) shell.launcher.close() } + function openApps(): void { if (!shell.launcher || !shell.launcher.opened) appGrid.load().open() } + } + + component CenterLoader: OnDemandLoader { + id: center + required property string noteName + readonly property bool opened: !!item && item.opened + readonly property bool mapped: !!item && item.mapped + requested: mapped + function open() { if (!opened) load().open() } + function close() { if (item) item.close() } + function toggle() { load().toggle() } + function togglePopup() { load().togglePopup() } + function beginPull() { load().beginPull() } + function pullTo(distance) { if (item) item.pullTo(distance) } + function endPull(velocity) { if (item) item.endPull(velocity) } + + // Home and the bottom swipe read a nonempty marker while this center is open. + FileView { + id: note + path: (Quickshell.env("XDG_RUNTIME_DIR") || "/tmp") + "/" + center.noteName + blockAllReads: true + blockWrites: true + printErrors: false + } + function writeOpenNote() { + var value = opened ? "1" : "" + if (note.text() !== value) note.setText(value) + } + Component.onCompleted: writeOpenNote() + onOpenedChanged: writeOpenNote() + } + + readonly property CenterLoader controlCenter: CenterLoader { + id: controlCenterLoader + keepAlive: !!item && item.writingBrightness + noteName: "omarchy-control-center-open" + readonly property var rootShell: shell + readonly property bool popupStyle: !!item && item.popupStyle + property ControlCenterModules modules: ControlCenterModules { shell: controlCenterLoader.rootShell; center: controlCenterLoader.item } + sourceComponent: ControlCenter { shell: controlCenterLoader.rootShell; modules: controlCenterLoader.modules } } + ShellIpc { + target: "omarchy.controlcenter" + function toggle(): void { shell.controlCenter.toggle() } + function open(): void { shell.controlCenter.open() } + function close(): void { shell.controlCenter.close() } + function page(module: string): void { shell.controlCenter.load().openPage(module) } + } + readonly property CenterLoader notificationCenter: CenterLoader { + id: notificationCenterLoader + noteName: "omarchy-notification-center-open" + readonly property var rootShell: shell + OnDemandLoader { + id: weatherLoader + requested: notificationCenterLoader.mapped + keepAlive: true + sourceComponent: NotificationWeather { shell: notificationCenterLoader.rootShell } + } + sourceComponent: NotificationCenter { shell: notificationCenterLoader.rootShell; weather: weatherLoader.item } + } + ShellIpc { + target: "omarchy.notificationcenter" + function toggle(): void { shell.notificationCenter.toggle() } + function open(): void { shell.notificationCenter.open() } + function close(): void { shell.notificationCenter.close() } + } + + readonly property var settingsHost: shell + readonly property Settings settings: Settings { shell: settingsHost } // labwc's long bottom swipe (bottomSwipeFarSocket): lines "p 0.42" while // the finger moves past where the overview turns back, then "end 1" (let @@ -65,8 +129,8 @@ ShellRoot { parser: SplitParser { onRead: function(line) { var parts = String(line).trim().split(" ") - if (parts[0] === "p") appGrid.follow(Number(parts[1]) || 0) - else if (parts[0] === "end") appGrid.followEnd(parts[1] === "1") + if (parts[0] === "p" && (appGrid.item || Number(parts[1]) > 0)) appGrid.load().follow(Number(parts[1]) || 0) + else if (parts[0] === "end" && appGrid.item) appGrid.item.followEnd(parts[1] === "1") } } } @@ -244,9 +308,7 @@ ShellRoot { pluginRegistry.firstPartyDir = shell.firstPartyPluginsDir pluginRegistry.shellConfigProvider = function() { return shell.shellConfig } pluginRegistry.shellConfigMutator = function(mutate) { shell.mutateShellConfig(mutate) } - // PluginRegistry.ensureUserDir() runs in its own Component.onCompleted and - // chains rescan() once the directory exists. We also kick a scan here in - // case the user dir already existed at startup. + // Discover the lock, bar and IPC immediately. The user plugin watcher starts later. pluginRegistry.rescan() shell._syncServices() } @@ -1570,6 +1632,18 @@ ShellRoot { firstParty: !!manifest.__isFirstParty } + // Settings lists every enabled widget, even though the default bar + // uses only a few. Publish their metadata without compiling the panels. + // Custom bars still get a real Component when they read the entry. + if ((!existing || existing.url !== url) && !shell.pluginRegistry.inBar(pluginId)) { + existing = { url: url, resolve: shell.deferredWidget(registryKey, url) } + setPluginWidgetComponent(registryKey, existing) + } + if (existing && existing.url === url && existing.resolve) { + shell.barWidgetRegistry.registerDeferred(registryKey, existing.resolve, meta) + continue + } + // A load already in flight for this URL registers itself when it // finishes. Starting a second one produces a second Component for the // same widget, and swapping a slot's component rebuilds its item — @@ -1693,6 +1767,18 @@ ShellRoot { pluginWidgetComponents = next } + function deferredWidget(id, url) { + var component = null + return function() { + if (!component) { + component = Qt.createComponent(url, Component.PreferSynchronous) + if (component.status === Component.Error) + shell.pluginRegistry.pluginLoadFailed(id, component.errorString()) + } + return component.status === Component.Error ? null : component + } + } + function loadPluginWidget(registryKey, url, meta) { // Claim the key before the component exists. Qt.createComponent is // asynchronous and syncPluginWidgets runs several times while the shell @@ -1794,8 +1880,13 @@ ShellRoot { // 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" + readonly property string ipcSocketPath: { + var display = Quickshell.env("WAYLAND_DISPLAY") || "" + var id = shell.omarchyPath === "/usr/share/omarchy" && /^wayland-[0-9]+$/.test(display) + ? "display-" + display + : Qt.md5(shell.omarchyPath + "/shell\n" + display).slice(0, 16) + return Quickshell.env("XDG_RUNTIME_DIR") + "/omarchy-shell-" + id + ".sock" + } SocketServer { active: shell.omarchyPath !== "" @@ -1871,9 +1962,43 @@ ShellRoot { // ---------------------------------------------------------- shell IPC + // Hold a single press for the double-press window. Check the lock again + // on expiry since a lock request can arrive while the timer is armed. + function homeLocked() { + var state = IpcRegistry.call("lock", "isLocked", []) + return state.ran ? state.output !== "false" : Quickshell.env("OMARCHY_START_LOCKED") === "1" + } + Timer { + id: homePress + property double stamp: 0 + property bool dismissedCenter: false + interval: 300 + onTriggered: { + if (!dismissedCenter && !shell.homeLocked()) appGrid.load().toggle() + stamp = 0 + } + } + ShellIpc { target: "shell" + function home(overview: string, timestamp: string): void { + if (shell.homeLocked()) { homePress.stop(); homePress.stamp = 0; return } + var dismissed = shell.controlCenter.opened || shell.notificationCenter.opened + shell.controlCenter.close() + shell.notificationCenter.close() + var stamp = Number(timestamp) + if (overview === "1" || (homePress.running && stamp >= homePress.stamp && stamp - homePress.stamp < 300)) { + homePress.stop() + homePress.stamp = 0 + Quickshell.execDetached(["labwc", "--overview"]) + } else { + homePress.stamp = stamp + homePress.dismissedCenter = dismissed + homePress.restart() + } + } + function prepareThemeIntro(fromPath: string, token: string, colorsB64: string, shellB64: string): void { shell.bootIntro.prepareTheme(fromPath, token, colorsB64, shellB64) } diff --git a/docs/native-session-helper-proposal.md b/docs/native-session-helper-proposal.md new file mode 100644 index 00000000..5cecd74d --- /dev/null +++ b/docs/native-session-helper-proposal.md @@ -0,0 +1,21 @@ +# Proposal for one native sensor and keyboard daemon + +On the iPhone 5, auto-brightness, rotation and the keyboard policy listener occupy about 15, 12 and 12 MB RSS respectively. Replace those three resident Python processes with one unprivileged C process per labwc session. Budget 3–6 MB RSS for the daemon, including its loaded libraries. That would save roughly **33–36 MB of summed RSS** against the measured 39 MB. Shared Python pages count in more than one process, so the actual RAM recovered will be smaller. Measure summed PSS from `/proc/PID/smaps_rollup` before and after. The estimate excludes powerd, iio-sensor-proxy, the light/acceleration monitor clients and the visible keyboard program. + +## Build and lifetime + +Add one target to the existing Makefile alongside the C Wayland helpers. Use the existing compiler and pkg-config path for armv7h and aarch64. Use libsystemd's sd-event and sd-bus for the event loop, the system bus, fd watches and timers. Install the binary and compatibility entry points through `desktop/install-tree`. + +Start the daemon from the packaged labwc autostart. Keep labwc's existing `omarchy-keyboard listen` command. It can pass its stdin pipe to the daemon over a private Unix socket using `SCM_RIGHTS` and exit immediately. Allow either entry point to start the owner under a runtime lock, since labwc may send facts before autostart runs. On EOF detach the keyboard policy. On compositor exit release sensor claims, close all descriptors and remove the session socket. A sensor arriving late, disappearing or losing its D-Bus owner must allow the other policies to continue. + +## Interfaces to preserve + +| Policy | Compatibility contract | +| --- | --- | +| Light | Keep both helper names, CLI switches, probe/list and dry-run modes, config keys, the `display` preference file and existing status JSON. Claim/release light on `net.hadess.SensorProxy`, consume `LightLevel` in lux, and retain slow IIO fallback. Port the median, asymmetric smoothing, hysteresis, perceptual fade and manual override. Keep the `als-state` and `brightness PANEL NEW EXPECTED` exchanges on powerd's socket. | +| Rotation | Consume the proxy's accelerometer orientation, retain the mount-matrix and bounded motion check, debounce, cooldown and lock/unlock semantics. Keep the rotation-lock file, internal-output selection, transform mapping and optional speaker-transform publication. Issue the Wayland output request only for a settled change. | +| Keyboard | Accept the same newline-delimited labwc facts, manual actions on `$XDG_RUNTIME_DIR/omarchy-keyboard.sock`, and the CLI's hold/release and show/hide behavior. Retain the tap, drag, hardware-key and delayed-hide policy, the visibility and PID files, and wvkbd's SIGUSR1/SIGUSR2 contract. The themed keyboard still runs as its own Wayland client. | + +## Acceptance + +Replay the inputs in the existing policy tests. On the iPhone 5, compare RSS, PSS and 60 s of idle CPU with the same shell and sensor claims. Exercise a dark/wake cycle, manual brightness, a locked half-turn and unlock, keyboard hold/release, and a sensor-proxy restart. The first target is a single resident policy PID at or below 6 MB RSS, zero light reads while dark and no recurring keyboard or rotation wakeups while settled. Powerd continues to own lock, screen power and suspend. diff --git a/docs/shell-memory.md b/docs/shell-memory.md new file mode 100644 index 00000000..5587e077 --- /dev/null +++ b/docs/shell-memory.md @@ -0,0 +1,134 @@ +# Shell memory and panel latency + +## What the default session loads + +The stock bar instantiates Menu, Clock, Indicators (DND and Stay Awake), Audio, Bluetooth, Network, Monitor and Power per applicable output. The host also owns the plugin and widget registries, app library and icon index, keyboard-state watcher, settings controller, startup and wallpaper switching controllers, brightness keys, IPC sockets and shortcut registrations. Startup unlocks deferred work such as desktop entry indexing. The background layer, idle service, session lock/PAM and notification daemon remain available. Menu, flash, OSD and image picker keep their command handlers. The four ordinary panel plugins (gallery, disk speed test, speed test and Wi-Fi QR) load when summoned. Settings creates a normal window on demand. The optional Hyprland dock is disabled in the default configuration. Its IPC name opens the Orchard launcher. + +Previously every enabled widget's component was compiled, including unplaced Agents and Elsewhen. After first use the two centers, five duplicate Control Center modules, every launcher page, the banner surface and most plugin popup windows could remain resident. The notification daemon owns history independently of its windows. Timers, running processes, font glyphs, JS maps and compiled QML contribute to the remaining heap. The supplied smaps group allocations by mapping and cannot attribute the 55–65 MB difference to individual components. + +## What to expect + +| Change | Size or scaling on N42 | Latency consideration | +| --- | --- | --- | +| Share desktop, lock and wake-preload image cache keys | One avoided 640 × 1136 RGBA copy is 2.77 MiB. A landscape still decoded to cover portrait can be larger. A video or a different lock image may share nothing. | Lock preload survives. | +| Release an empty banner surface | Up to 2.77 MiB per full-screen RGBA buffer before alignment. Buffer count and driver accounting vary. Saving requires a toast to have appeared. | A new burst maps a fresh surface. | +| Release closed center and plugin window trees | Scales with cards, widgets and output count. Component bytes need the A/B. | Reopens within 1.5 s of unmapping reuse the tree. Later reopens rebuild it. Control Center creates settings controllers only as visited and lets their operations finish. Weather data stays warm. | +| Create visible launcher pages and keep its landing page warm | Each avoided 96 × 96 RGBA icon represents 36 KiB of decoded pixels before Qt cache retention, plus its tile objects. The tablet app grid already virtualizes cells. | Reopening reuses the landing page. Offscreen tabs build as needed. | +| Defer unplaced widget compilation and the Settings window | Depends on the enabled widget catalog, imports and disk-cache state. | Selected widgets use the existing asynchronous startup path. An unused widget compiles on first access. | +| Bound image bookkeeping | The icon helper admits published PNGs up to 32 MiB on disk, across concurrent callers. A cache already above budget accepts no new files. Overflow uses the original icon at display size. Wallpaper dimensions retain active paths. | Existing raster hits remain available. | + +These defaults apply on both architectures. Pixel storage scales with output dimensions and buffer format. A 1536 × 2048 RGBA buffer is 12 MiB. Pointer-heavy object trees can cost more on arm64. Measurements on one architecture do not quantify the other. The existing lite/software instant wallpaper transition skips its unused prepared image. The visible transition, animation layers, glyph styles and renderer settings are preserved. The three unsized bar drag images consume widget-sized in-memory grabs. Wallpaper and launcher images already request an output-specific decode. The general-purpose SizedImage helper has a special intrinsic-aspect SVG path. + +## Install and compare + +From the linux-a9 checkout, remove the benchmark's documented timing assignment for both runs. The packaged session does not set it. If the measured process still shows it, inspect the session's actual launch wrapper. + +```sh +scripts/a6/n42-ssh.sh 'f=/etc/environment.d/90-qsg-timing.conf; if test -f "$f"; then sed -i "/^[[:space:]]*QSG_RENDER_TIMING=/d" "$f"; fi; runuser -u tablet -- env XDG_RUNTIME_DIR=/run/user/1000 systemctl --user unset-environment QSG_RENDER_TIMING' +scripts/a6/n42-shell-ab.sh qs-mem-base build/omarchy-a-helpers +``` + +Unlock to a still desktop, with the same wallpaper, notifications, orientation, apps and jemalloc settings for both runs. Run the measurement below with `tag=qs-mem-base`. Then install the candidate, unlock and repeat with `tag=qs-mem`. + +```sh +scripts/a6/n42-shell-ab.sh qs-mem build/omarchy-a-qsmem +``` + +The following command uses the existing usability script's instance selection, tablet credentials, IPC targets and Stay Awake restoration. The Python block underneath is its input. Run in Bash with pipefail to propagate a failed measurement. + +```bash +set -o pipefail +tag=qs-mem +plan=build/omarchy-a-qsmem/docs/shell-memory.md +{ sed '/^if __name__ ==/,$d' scripts/a6/n42-usability-device.py + sed -n '/^```python$/,/^```$/{ /^```/d; p; }' "$plan" +} | scripts/a6/n42-ssh.sh 'python3 -u -' | tee "build/a6-n42-flights/memory-$tag.txt" +``` + +```python +from concurrent.futures import ThreadPoolExecutor + +s = Session() +s.ensure_unlocked() +pid = s.pids["qs"] +proc = Path("/proc") / str(pid) +env = dict(entry.split("=", 1) for entry in read(proc / "environ").split("\0") if "=" in entry) +for key in ("QSG_RENDER_TIMING", "QT_QPA_PLATFORMTHEME", "QT_QUICK_BACKEND", "QSG_RHI_BACKEND", "MALLOC_CONF"): + print(key, env.get(key, "")) +print("GTK mappings", sorted({line.split()[-1] for line in read(proc / "maps").splitlines() + if any(x in line for x in ("libqgtk3", "libgtk-3", "libgdk-3"))})) +cache = Path(s.env["HOME"]) / ".cache/omarchy/icon-raster" +files = list(cache.glob("*.png")) +print("cached PNGs", len(files), "disk bytes", sum(f.stat().st_size for f in files)) + +def memory(label): + print(label, *(l for l in read(proc / "smaps_rollup").splitlines() + if l.split(":")[0] in ("Rss", "Pss", "Pss_Anon", "Pss_File", "Private_Dirty", "Swap", "SwapPss"))) + +def pixels(): + ppm = sp.check_output(["grim", "-s", "0.125", "-t", "ppm", "-"], env=s.env, **s.creds, timeout=5) + header = re.match(rb"P6\s+(\d+)\s+(\d+)\s+255\s", ppm) + w, h = map(int, header.groups()) + data = ppm[header.end():] + assert len(data) == 3*w*h + return data[(h//10)*w*3:] # exclude the clock and status bar + +def open_panel(target, method): + s.ipc(target, method) + return time.monotonic() + +def ticks(): + return sum(map(int, (proc / "stat").read_text().rsplit(")", 1)[1].split()[11:13])) + +with stay_awake(s), ThreadPoolExecutor(max_workers=1) as pool: + time.sleep(20) + memory("settled KiB") + for cycle in range(1, 4): + for name, (target, show, hide) in PANELS.items(): + baseline = pixels() + before = ticks() + start = previous = time.monotonic() + ack = pool.submit(open_panel, target, show) + try: + while time.monotonic() - start < 45: + capture_start = time.monotonic() + frame = pixels() + end = time.monotonic() + if sum(abs(a-b) > 12 for a,b in zip(frame, baseline)) > len(frame)*0.02: + break + previous = capture_start + else: + raise RuntimeError(f"No visible change for {name}") + first_ticks = ticks() - before + print(cycle, name, "IPC ms", round(1000*(ack.result()-start)), + "visible change ms interval", round(1000*(previous-start)), round(1000*(end-start)), + "qs ticks through capture", first_ticks, "CLK_TCK", HZ) + time.sleep(1.5) + finally: + try: + ack.result() + finally: + s.ipc(target, hide) + time.sleep(4) + memory(f"closed cycle {cycle} KiB") + time.sleep(20) + memory("settled after 3 cycles KiB") +``` + +Compare first opens separately from cycles two and three. The interval brackets the first sampled visible change above a 2% channel threshold. The IPC time includes client startup. Both capture and CPU scheduling add uncertainty. A difference smaller than the capture interval is unresolved. Compare Pss_Anon together with SwapPss to distinguish reclaimed pages from pages moved to zram. + +## Runtime options + +Qt 6.12 enables the QML disk cache by default. Keep the N42 local-QML-cache Quickshell build for both measurements. The QV4 heap uses incremental collection by default. The observed 1.7 MB JIT code mapping bounds the direct code-page opportunity for a separate interpreter trial (`QV4_FORCE_INTERPRETER=1`). Aggressive GC would add work throughout allocation. The candidate keeps the existing environment. [Qt memory management](https://doc.qt.io/qt-6/qtqml-javascript-memory.html) + +Qt's gtk3 platform-theme plugin links GTK3 and implements native dialogs as well as appearance settings. The map check above establishes whether this build loaded it. For a separate, shell-only comparison, stage a temporary copy with a Quickshell environment pragma before QApplication starts. Run the same measurement and inspect themed fallback icons, fonts, colors and Settings on the phone and tablet before choosing a system default. [Qt GTK3 plugin](https://github.com/qt/qtbase/tree/v6.12.1/src/plugins/platformthemes/gtk3) · [Qt generic Unix theme](https://github.com/qt/qtbase/blob/v6.12.1/src/gui/platform/unix/qgenericunixtheme.cpp) + +```bash +stage=$(mktemp -d) +mkdir -p "$stage/desktop/shell" +cp -R build/omarchy-a-qsmem/desktop/shell/shell "$stage/desktop/shell/" +python3 -c 'from pathlib import Path; import sys; p = Path(sys.argv[1]); p.write_text("//@ pragma Env QT_QPA_PLATFORMTHEME = generic\n" + p.read_text())' "$stage/desktop/shell/shell/shell.qml" +scripts/a6/n42-shell-ab.sh qs-mem-generic "$stage" +``` + +Use `tag=qs-mem-generic` for the measurement and reinstall the candidate with the earlier command afterwards. Quickshell applies the pragma after process launch, so confirm the GTK comparison through the mappings. The process's initial environment in procfs can still show gtk3. diff --git a/docs/shell-responsiveness.md b/docs/shell-responsiveness.md new file mode 100644 index 00000000..493b96ce --- /dev/null +++ b/docs/shell-responsiveness.md @@ -0,0 +1,21 @@ +# Settings and Home on N42 + +The measured baseline is `3de0a60`. On the phone, Settings first changed the screen at 18–20 s, the shell used 6.7–7.8 CPU seconds, and a 22 s system-wide recording saw 395 executions. That included 191 instances of grep. The profile's strcmp samples do not identify their callers. + +## Open paths + +| Surface | Work and invalidation | +| --- | --- | +| Settings | The IPC handler requests a small asynchronous FloatingWindow. It draws its title before starting the body loader. The body compiles just the active native page. The persistent Settings controller indexes menu children once per model change. Closing releases the window, delegates and images. | +| Menu data shared by Settings and launcher | After startup, one Python process checks command presence and classifies scripts that use Hyprland. Package transactions and menu-definition changes invalidate those answers. The first run also records hardware predicates and the backlight path. The menu keeps its guard results and the existing pacman transaction-stamped package/provides cache. Flag checks run inside the guard batch. A labwc session skips Hyprland predicates and readers. Settings opening runs neither the guard batch nor an X11/default-app probe. | +| Settings pages | Wi-Fi scanning and Bluetooth discovery use the session buses. Wi-Fi profile details query nmcli for the selected profile and interface. Appearance reads theme and icon names through FileView and asks for the font and background only while visiting Appearance. Each picker lists its own files in one process. About reads procfs, os-release and filesystem usage on demand and asks omarchy-version for the installed version. Date & Time queries timedated on visit. Timezone lists are loaded only in the picker. Sound uses PipeWire. Display reads the shared backlight, auto-brightness and rotation state. Commands that write settings still run on activation. | +| Launcher and Home | Opening the grid runs no menu guard or file search. Search invokes omarchy-launcher-recent-files on first use and after its 30 s cache expires. App removal checks run on the app's context menu. Desktop entry, icon raster and version scans belong to session initialization and package or icon changes. Home sends one IPC call. The shell checks the lock, dismisses any open centers and resolves single versus double press with its 300 ms timer. A double press or a press in the overview invokes labwc. | +| Control Center | Opening reads brightness and its configured automatic mode through shared FileViews. Rotation discovery uses one session busctl probe with a retry if sensor-proxy was late. Wi-Fi status is shared with the bar and lock. When the connected profile lacks strength, it uses procfs RSSI with a shared nmcli fallback on drivers without RSSI. Graph updates for an untyped audio source may use wpctl and pactl. | +| Control Center detail pages | Live network details/latency use omarchy-network-status while open (1.5 s), band details use omarchy-network-band while showing Wi-Fi (4 s), and DNS uses omarchy-dns. Display modes use omarchy-monitor-state while visible (5 s). Audio uses the optional sink/source availability helper while visible (5 s) and the optional DSP sink resolver on graph changes. The stock package withholds both. Power profile enumeration uses powerprofilesctl via omarchy-powerprofiles-list and refreshes on profile changes. Bluetooth discovery uses BlueZ. These are detail-page workloads. | +| Notification Center | Weather fetches, retries and the 15 minute refresh use asynchronous Qt HTTP requests with timeouts. The weather controller retains the last report across sheet closes. Geocoding uses the same transport. Changing the saved location still invokes omarchy-weather-location. Opening the notification list reads existing daemon history. | +| Bar | UPower events and the minute timer read sysfs power-supply uevent files. FileView watches bar visibility. Keyboard devices, workspace layout and glass synchronization query Hyprland only in that session. Optional update (6 h or reconnect), recording, reminder, sudo and contrast readers are gated on installed commands. User-configured exec widgets retain their own commands and intervals. | +| Lock | A watched wallpaper directory and target refresh the resolved path/signature with readlink and stat. Video poster generation runs for video backgrounds. The fingerprint configuration file gates the fprintd enrollment check and retry. Input/wake/idle power operations preserve the daemon protocol. The Hyprland stranded-lock check is gated on Hyprland. The woke handler re-arms blanking and resumes fingerprint retries. | + +The native client uses the shell's per-display Unix socket and passes empty arguments intact. The packaged config names its socket after the Wayland display. Other configs and older shells use the existing hashed address. Home runs the same CLI code inside the button's Bash process, including display discovery when launched by powerd. Set `OMARCHY_SHELL_IPC_TRACE=1` to print the transport to stderr. A partial reply or timeout after dispatch fails the call without repeating it. + +The N42 flight of `569c08a` recorded 16–19 system-wide execs per Settings open, including the native IPC client each time. The shell still consumed 21.76–21.82 CPU seconds in each 22 s recording. With an already-compiled body and slow incubation, the frame handler could request the body again before the loader notified its source change. A Qt host reproduction made 260 requests in four seconds. The window now disarms that handler before it starts incubation. The same reproduction completed one request and loaded the body. The window requests 980 × 700 with a 320 × 420 minimum. The reported maximized 0 × 0 configure comes from the Wayland compositor and the loop also reproduces offscreen. diff --git a/docs/tablet-sensors.md b/docs/tablet-sensors.md index fc017b0d..52d6d8f7 100644 --- a/docs/tablet-sensors.md +++ b/docs/tablet-sensors.md @@ -2,7 +2,7 @@ Orientation already comes from iio-sensor-proxy and the kernel's accelerometer mount matrix. Labwc maps touch to the panel, so display and touch rotate together. This remains the native orientation path; no extra board matrix or second sensor reader is installed. -The Display panel's Rotation Lock and `omarchy-rotation-lock on|off|toggle|status` use the same lock as the orientation helper. While locked the helper keeps watching; after unlock it applies the last settled pose even without a new sensor event. Undefined/flat poses stay ignored and the existing half-second settling remains. The helper exits with labwc. +The Display panel's Rotation Lock and `omarchy-rotation-lock on|off|status` use the same lock as the orientation helper. While locked the helper keeps watching; after unlock it applies the last settled pose even without a new sensor event. Undefined/flat poses stay ignored and the default settling time is 0.4 s. The helper exits with labwc. Auto Brightness uses the existing tablet ALS curve, smoothing, hysteresis, ramp and manual-change pause policy. It is **off by default** because panel/light calibration still needs device validation. Enable it with the Auto Brightness switch in the Display panel, or: @@ -14,7 +14,7 @@ omarchy-auto-brightness off It reads generic IIO lux or iio-sensor-proxy. Missing sensors are harmless; the switch appears when an IIO light sensor and panel exist. Its process follows the compositor lifetime. Logs are in `$XDG_RUNTIME_DIR/arch-ipad-auto-brightness.log`; `--list` shows discovery and `--probe 20` computes a dry run without backlight writes. -User preferences live in `~/.config/omarchy/als-brightness.conf` and the switch is saved in `~/.local/state/omarchy/display`. Optional configuration keys are `enabled`, `backlight`, `curve`, `min_pct`, `max_pct`, `lux_scale`, `smooth_secs`, `hysteresis`, `min_pct_step`, `min_interval`, `ramp_pct_per_s`, `override_secs`, and `poll_hz`. The default curve is `0:10, 5:18, 20:30, 80:50, 250:70, 700:90, 1500:100` (lux:percent). Readings pass through a five-sample median and log-lux smoothing. Manual changes pause automatic adjustment for 30 seconds. +User preferences live in `~/.config/omarchy/als-brightness.conf` and the switch is saved in `~/.local/state/omarchy/display`. Optional configuration keys are `enabled`, `backlight`, `curve`, `min_pct`, `max_pct`, `lux_scale`, `smooth_secs`, `hysteresis`, `min_pct_step`, `min_interval`, `ramp_pct_per_s`, `override_secs`, and `poll_hz`. The default curve is `0:15, 5:25, 20:38, 80:58, 250:78, 700:94, 1500:100` (lux:percent). Readings pass through a three-sample median and log-lux smoothing. Manual changes pause automatic adjustment for 30 seconds. Automatic writes use omarchy-powerd's control socket, serialized with its existing screen/sleep/wake state machine. The request names the panel and supplies the expected old raw value. Powerd accepts only positive, in-range levels for that panel while lit and rejects stale values. A dark panel, unavailable power daemon or manual edit therefore stops a ramp. Wake still restores the level through powerd before automatic adjustment resumes. No brightnessctl helper, root user daemon or passwordless brightness sudo rule is added. @@ -23,6 +23,27 @@ Both fresh desktop staging and the public-root builder include the helper and it Host checks cover the retained light policy, switch state, missing power daemon, stale-value/dark-panel refusal, manual pause, actual socket writes, rotation debounce/lock/unlock and compositor exit, plus staging and public-root inclusion. Physical lux response, all four orientation directions, touch mapping and power-button/idle/sleep coexistence still need a device run. +## Background helper cost + +On 2026-12-01, a 60-second shell profile on the iPhone 5 attributed 4.2% of samples to the battery helper and 3.4% to `awk`. At idle, auto-brightness used about 2% CPU and iio-sensor-proxy 1.4%. Process RSS was 15 MB for auto-brightness, 12 MB each for rotation and the keyboard listener, and 21 MB for the separate power daemon. + +- Battery views now share one sysfs snapshot per shell process. UPower source, presence, percentage and state changes refresh it, as does opening the power panel. The fallback runs every 60 s. Previously each view launched a reader every 5 s. The reader formats the same tab-separated fields with Bash builtins. +- Auto-brightness follows light changes through `monitor-sensor`. Direct IIO reads are at least 2 s apart. Powerd exposes its light state by request, so the helper checks it at most 2 s apart while idle. Off, a dark or unreadable backlight, or a powerd hold releases the light claim and stops IIO reads. After a hold, wake gets its existing 1 s to settle. Filtering a light change and animating a fade still use shorter timers. +- Rotation blocks on the accelerometer monitor, compositor exit and removal of a pending rotation lock on Linux. It samples raw acceleration every 100 ms only while judging a turn. The keyboard listener already sleeps on labwc stdin and its control socket, with a 250 ms deadline for a pending hide. + +For an on-device comparison, use the same shell layout, charge state and ambient light on both revisions. Collect an idle minute with the panel lit. Repeat with the screen dark, then check charger, orientation and keyboard transitions separately. + +```sh +ps -eo pid,ppid,rss,pcpu,args | grep -E '[a]uto-brightness|[r]otate-output|[o]marchy-keyboard listen|[i]io-sensor-proxy|[o]marchy-powerd' +helpers=$(pgrep -d, -f '([a]rch-ipad-(auto-brightness|rotate-output)|[o]marchy-keyboard listen|[i]io-sensor-proxy)') +pidstat -u -w -p "$helpers" 1 60 +shell_pid=$(pgrep -of '(^|/)qs -p /usr/share/omarchy/shell/shell[.]qml$') +perf record -o /var/tmp/omarchy-shell-idle.data -e cpu-clock -F 99 -p "$shell_pid" -- sleep 60 +perf report -i /var/tmp/omarchy-shell-idle.data --stdio --no-children --sort comm,dso +``` + +With steady power, expect one scheduled battery invocation per minute per shell and zero `awk` children from it. After settling, the target for each Python helper is below 0.5% of one core over the minute. Rotation still claims the accelerometer, so darkening the screen need not take iio-sensor-proxy to zero. Check that the light monitor disappears while dark and that the first light change after wake adjusts the panel. RSS savings from replacing Python are a separate proposal. + ## Side mute switch The kernel reports the ring/silent switch (iPhone, older iPads) as `KEY_MUTE` of the `gpio-keys` input device, held down while the switch is on silent. `omarchy-mute-switch` (`/usr/libexec`, started by the session's autostart) mutes the default output while the switch is on silent and unmutes it on ring: quietly at login, with the volume OSD (`omarchy-volume mute-on|mute-off`) when the switch is moved. A suspend and resume, which the kernel reports as a release and a press, changes nothing. Without such a switch it exits at once; it ends with labwc. Logs are in `$XDG_RUNTIME_DIR/omarchy-mute-switch.log`. diff --git a/release/audit.py b/release/audit.py index cd218a00..6bee9cce 100644 --- a/release/audit.py +++ b/release/audit.py @@ -15,8 +15,9 @@ from .public_root import sha -# The two compiled helpers of the omarchy-a package, of the root's architecture. -HELPERS = {'usr/libexec/omarchy-wtype': 'startup cursor helper', +# The compiled helpers of the omarchy-a package, of the root's architecture. +HELPERS = {'usr/libexec/omarchy-shell-ipc': 'shell socket client', + 'usr/libexec/omarchy-wtype': 'startup cursor helper', 'usr/share/omarchy/trials/wvkbd-mobintl-v0.20-font18-special15-state': 'on-screen keyboard'} def private_firmware(orchard=None): diff --git a/system/assemble-rootfs b/system/assemble-rootfs index 9eff3e29..94af7186 100755 --- a/system/assemble-rootfs +++ b/system/assemble-rootfs @@ -151,11 +151,10 @@ if [[ ! $release =~ ^[0-9] && $architecture == aarch64 ]]; then fi # Every dependency of every installed package is met. pacman --config "$config" --root "$root" --gpgdir "$gpgdir" -Dk -if [[ $architecture == aarch64 ]]; then - # OpenGL, the GPU's Vulkan driver and the GPU probe are the fork's Mesa's. - [[ $(pacman --root "$root" -Qoq "$root/usr/lib/libEGL_mesa.so.0" "$root/usr/lib/libgbm.so.1" \ - "$root/usr/lib/libvulkan_powervr_mesa.so" "$root/usr/lib/orchard/gpu-probe" | sort -u) == mesa ]] -fi +# OpenGL, the GPU's driver (64-bit: its Vulkan driver) and the GPU probe are the fork's Mesa's. +mesa_files=("$root/usr/lib/libEGL_mesa.so.0" "$root/usr/lib/libgbm.so.1") +[[ $architecture != aarch64 ]] || mesa_files+=("$root/usr/lib/libvulkan_powervr_mesa.so") +[[ $(pacman --root "$root" -Qoq "${mesa_files[@]}" "$root/usr/lib/orchard/gpu-probe" | sort -u) == mesa ]] # The home starts as /etc/skel, which the omarchy-a package filled: the tablet # user's defaults, and the record that every migration it ships is done. useradd --root "$root" --create-home --uid 1000 --user-group --shell /bin/bash tablet diff --git a/system/orchard-packages.txt b/system/orchard-packages.txt index 90c5775c..9474410a 100644 --- a/system/orchard-packages.txt +++ b/system/orchard-packages.txt @@ -12,10 +12,11 @@ labwc omafox omactivity folio-touch -# 64-bit boards: Mesa from OrchardLinux's fork in the place of Arch's (OpenGL through Zink or in -# software, the GPU's Vulkan driver, the login's GPU probe), and the VA-API bridge to the hardware -# video decoders. The GPU parts and the bridge sit unused on a board without that hardware. -mesa aarch64 +# Mesa from OrchardLinux's fork in the place of Arch's, with the login's GPU probe: on 64-bit +# boards OpenGL through Zink or in software and the PowerVR GPU's Vulkan driver, on 32-bit boards +# the SGX543's OpenGL ES 2 driver and software OpenGL. 64-bit boards also take the VA-API bridge to +# the hardware video decoders. The GPU parts and the bridge sit unused on a board without that hardware. +mesa libva-v4l2-request aarch64 # Omacalc: upstream Omarchy publishes it for aarch64 only; the Orchard repository has ARMv7's. omacalc armv7h diff --git a/system/overlay/usr/libexec/omarchy-powerd b/system/overlay/usr/libexec/omarchy-powerd index 37b2ccc3..46e70f67 100755 --- a/system/overlay/usr/libexec/omarchy-powerd +++ b/system/overlay/usr/libexec/omarchy-powerd @@ -12,6 +12,7 @@ import os from pathlib import Path import pwd import queue +import re import select import signal import socket @@ -305,17 +306,24 @@ def parse_logind_started(line): return False -def streams_running(dump): - """Whether `pw-dump` output has an audio or video playback stream that is running.""" - try: - for item in json.loads(dump): - info = item.get('info') or {} - media = (info.get('props') or {}).get('media.class', '') - if media.startswith('Stream/Output/') and info.get('state') == 'running': - return True - except (ValueError, AttributeError): - pass - return False +def update_streams(streams, dump): + """Apply one pw-dump array. Objects absent from a monitor update still exist.""" + objects = json.loads(dump) + if not isinstance(objects, list): + raise ValueError('expected a pw-dump array') + for item in objects: + ident = item['id'] + info = item.get('info') or {} + media = (info.get('props') or {}).get('media.class', '') + if media.startswith('Stream/Output/'): + streams[ident] = (media, info.get('state')) + else: + streams.pop(ident, None) + return any(state == 'running' for _, state in streams.values()) + + +# pw-dump ends each pretty-printed array with ']' in column zero. +DUMP_END = re.compile(rb'^(?:\]|\[.*\])[ \t]*\r?\n', re.MULTILINE) EV_KEY, KEY_VOLUMEDOWN, KEY_POWER, KEY_HOMEPAGE = 1, 114, 116, 172 @@ -521,13 +529,13 @@ def command(*argv, timeout=5, **options): return subprocess.run(argv, capture_output=True, text=True, timeout=timeout, **options) -def session_user(): +def session_user(*, check=False): """The desktop user on seat0, or None for the greeter (nothing to lock) or no session.""" - session = command('loginctl', 'show-seat', 'seat0', '-p', 'ActiveSession', '--value').stdout.strip() + session = command('loginctl', 'show-seat', 'seat0', '-p', 'ActiveSession', '--value', check=check).stdout.strip() if not session: return None fields = dict(line.split('=', 1) for line in - command('loginctl', 'show-session', session, '-p', 'Name', '-p', 'Class').stdout.splitlines() + command('loginctl', 'show-session', session, '-p', 'Name', '-p', 'Class', check=check).stdout.splitlines() if '=' in line) if fields.get('Class') != 'user' or not fields.get('Name'): return None @@ -539,11 +547,11 @@ def user_env(user): 'OMARCHY_PATH': SHELL_ROOT, 'PATH': '/usr/local/bin:/usr/bin'} -def spawn_as_user(user, *argv, env=None): +def spawn_as_user(user, *argv, env=None, stdout=subprocess.DEVNULL): """Start ARGV as the user and return at once (as_user waits for it).""" return subprocess.Popen(('setpriv', f'--reuid={user.pw_uid}', f'--regid={user.pw_gid}', '--init-groups', '--', *argv), env={**user_env(user), **(env or {})}, cwd='/', - stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + stdin=subprocess.DEVNULL, stdout=stdout, stderr=subprocess.DEVNULL, start_new_session=True) @@ -586,7 +594,8 @@ class Daemon: self.cancel = threading.Event() self.dim_saved = None self.dim_level = None - self.dark = threading.Event() + self.playback = None + self.playback_fallback_logged = False self.session_jobs = queue.Queue() self.inhibitor = None self.monitor = None @@ -739,8 +748,20 @@ class Daemon: self.monitor = subprocess.Popen( ['busctl', '--json=short', 'monitor', LOGIND, "--match=type='signal',interface='org.freedesktop.login1.Manager',member='PrepareForSleep'", + "--match=type='signal',path='/org/freedesktop/login1',interface='org.freedesktop.DBus.Properties'," + "member='PropertiesChanged',arg0='org.freedesktop.login1.Manager'", f"--match=type='signal',sender='org.freedesktop.DBus',member='NameOwnerChanged',arg0='{LOGIND}'"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, bufsize=0) + self.refresh_playback_inhibitor() + + def refresh_playback_inhibitor(self): + # A block inhibitor can be released without a PipeWire change. Re-read it on + # logind notifications (also after reconnect), and keep the final pre-suspend check. + if self.playback is not None: + try: + self.playback.send(b'.') + except BlockingIOError: + pass # a refresh is already pending def read_monitor(self): chunk = os.read(self.monitor.stdout.fileno(), 65536) @@ -757,6 +778,10 @@ class Daemon: log('logind started') self.logind_asleep = False # a new logind is in no sleep self.renew_inhibitor() + self.refresh_playback_inhibitor() + return + if 'PropertiesChanged' in line and 'BlockInhibited' in line: + self.refresh_playback_inhibitor() return sleeping = parse_sleep_signal(line) if sleeping is None: @@ -792,7 +817,15 @@ class Daemon: log(f't={when:.6f} {event}: {before} -> {self.machine.state} {" ".join(actions) or "-"}') for action in actions: getattr(self, 'do_' + action.replace('-', '_'))(before) - self.dark.set() if self.machine.state in (SETTLING, DARK) else self.dark.clear() + if self.machine.state in (SETTLING, DARK): + if self.playback is None: + self.playback, wake = socket.socketpair() + self.playback.setblocking(False) + threading.Thread(target=self.playback_worker, args=(self.playback, wake, self.machine.playing), + daemon=True).start() + elif self.playback is not None: + self.playback.close() # wake the worker even when PipeWire has no updates + self.playback = None def undim(self): panel = self.backlight() @@ -980,6 +1013,7 @@ class Daemon: def block_inhibited(self): result = command('busctl', 'get-property', 'org.freedesktop.login1', '/org/freedesktop/login1', 'org.freedesktop.login1.Manager', 'BlockInhibited') + result.check_returncode() return 'sleep' in result.stdout def request_suspend(self): @@ -1058,23 +1092,87 @@ class Daemon: time.sleep(0.1) return False - def playback_worker(self): - while not self.stopping: - self.dark.wait(1) - if not self.dark.is_set(): - continue - try: - user = session_user() - playing = self.block_inhibited() or ( - user is not None and streams_running(as_user(user, 'pw-dump', timeout=2).stdout)) - except (OSError, KeyError, ValueError, subprocess.SubprocessError) as error: - # No answer is not "nothing is playing". - log(f'playback check: {error}') - time.sleep(1) - continue - if playing != self.machine.playing: - self.post('playing' if playing else 'not-playing') - time.sleep(1) + def playback_fallback(self, error): + if not self.playback_fallback_logged: + log(f'playback monitor: {error}; polling every 10 s') + self.playback_fallback_logged = True + + def playback_worker(self, session, wake, playing): + monitor = None + fallback = False + audio = blocked = None + next_audio = next_inhibitor = 0 + pending = bytearray() + streams = {} + try: + while self.playback is session and not self.stopping: + now = time.monotonic() + if now >= next_inhibitor: + try: + blocked = self.block_inhibited() + next_inhibitor = float('inf') + except (OSError, subprocess.SubprocessError): + blocked, next_inhibitor = None, now + 10 + if now >= next_audio and self.playback is session: + next_audio = now + 10 + user = None + try: + user = session_user(check=True) + if self.playback is not session: + break + if user is None: + audio = False + elif fallback: + result = as_user(user, 'pw-dump', timeout=2) + result.check_returncode() + audio = update_streams({}, result.stdout) + else: + monitor = spawn_as_user(user, 'pw-dump', '--monitor', '--no-colors', stdout=subprocess.PIPE) + next_audio = float('inf') + except (OSError, KeyError, TypeError, AttributeError, ValueError, subprocess.SubprocessError) as error: + audio = None + if not fallback and user is not None: + self.playback_fallback(error) + fallback = True + + # Either source may keep us awake. Silence requires two successful answers. + active = bool(audio or blocked) + known = active or (audio is not None and blocked is not None) + if known and active != playing: + self.post((session, 'playing' if active else 'not-playing')) + playing = active + + deadline = min(next_audio, next_inhibitor) + delay = None if deadline == float('inf') else max(0, deadline - time.monotonic()) + ready, _, _ = select.select([wake, monitor.stdout] if monitor else [wake], [], [], delay) + if wake in ready: + if not wake.recv(4096): + break + next_inhibitor = 0 + if monitor and monitor.stdout in ready: + try: + chunk = os.read(monitor.stdout.fileno(), 65536) + if not chunk: + raise ValueError('pw-dump exited') + # The closing line may be split across reads. + start = pending.rfind(b'\n') + 1 + pending.extend(chunk) + while end := DUMP_END.search(pending, start): + audio = update_streams(streams, pending[:end.end()]) + del pending[:end.end()] + start = 0 + except (OSError, KeyError, TypeError, AttributeError, ValueError) as error: + self.playback_fallback(error) + monitor.terminate() + monitor.wait() + monitor.stdout.close() + monitor, audio, fallback, next_audio = None, None, True, 0 + finally: + wake.close() + if monitor is not None: + monitor.terminate() + monitor.wait() + monitor.stdout.close() # --- control socket ----------------------------------------------------- def control(self, server): @@ -1251,8 +1349,7 @@ class Daemon: self.take_inhibitor() self.start_monitor() self.start_uevents() - for worker in (self.session_worker, self.playback_worker): - threading.Thread(target=worker, daemon=True).start() + threading.Thread(target=self.session_worker, daemon=True).start() log('ready: ON') while not self.stopping: delay = self.timeout() @@ -1298,7 +1395,11 @@ class Daemon: os.read(self.wake_read, 512) while not self.events.empty(): event = self.events.get() - if event.startswith('sleep-over '): + if isinstance(event, tuple): + session, change = event + if self.playback is session: + self.feed(change) + elif event.startswith('sleep-over '): if int(event.split()[1]) == self.sleep_record: self.sleep_finished('unit') else: diff --git a/tests/package_tree.py b/tests/package_tree.py index 4e715a84..bc11cfcb 100644 --- a/tests/package_tree.py +++ b/tests/package_tree.py @@ -32,7 +32,7 @@ def inputs(base): """BUILD, OMARCHY and DBUS_NEXT for install-tree, under BASE.""" build, upstream, wheel = base / 'build', base / 'omarchy', base / 'wheel' build.mkdir() - for name in ('wvkbd-mobintl', 'wtype'): + for name in ('wvkbd-mobintl', 'wtype', 'omarchy-shell-ipc'): (build / name).write_bytes(elf()) (build / 'wtype.LICENSE').write_text('MIT\n') (upstream / 'themes/jade-horse/backgrounds').mkdir(parents=True) diff --git a/tests/test_bluetooth_pairing.py b/tests/test_bluetooth_pairing.py index c32d3e37..d8167442 100644 --- a/tests/test_bluetooth_pairing.py +++ b/tests/test_bluetooth_pairing.py @@ -79,7 +79,7 @@ def test_named_release_bindings_and_brightness_repeat(self): # labwc only keeps the key from the focused app. self.assertIsNone(bindings[0].get('onRelease')) self.assertEqual(bindings[0].find('action').get('command'), '/usr/bin/true') - self.assertIn(command, (PROJECT / 'desktop/shell/bin/omarchy-home-button').read_text()) + self.assertIn('source "${OMARCHY_PATH:?}/bin/omarchy-shell" shell home', (PROJECT / 'desktop/shell/bin/omarchy-home-button').read_text()) continue self.assertEqual(bindings[0].get('onRelease'), 'yes') self.assertEqual(bindings[0].find('action').get('command'), command) diff --git a/tests/test_keyboard_shortcuts.py b/tests/test_keyboard_shortcuts.py index d3ca7b59..9adc4450 100644 --- a/tests/test_keyboard_shortcuts.py +++ b/tests/test_keyboard_shortcuts.py @@ -69,14 +69,12 @@ def test_overview_triggers(self): self.assertIn('omarchy-keyboard hide', changed) self.assertIn('mode == "hide"', (PROJECT / 'desktop/shell/bin/omarchy-keyboard').read_text()) home = (PROJECT / 'desktop/shell/bin/omarchy-home-button').read_text() - self.assertIn('labwc --overview', home) - # One press waits for a second before the drawer opens: two presses - # must not flash the drawer on the way to the overview. - self.assertLess(home.index('sleep'), home.index('omarchy-shell omarchy.dock apps')) - # A locked session's Home is the lock screen's. (A press that woke the - # screen or was half of Home + Power never starts the script: see - # omarchy-powerd's 'home-up'.) - self.assertLess(home.index('lock status'), home.index('omarchy-overview-open')) + self.assertIn('source "${OMARCHY_PATH:?}/bin/omarchy-shell" shell home', home) + self.assertIn('omarchy-overview-open', home) + self.assertIn('Quickshell.execDetached(["labwc", "--overview"])', shell) + self.assertIn('interval: 300', shell) + self.assertIn('if (!dismissedCenter && !shell.homeLocked()) appGrid.load().toggle()', shell) + self.assertLess(shell.index('if (shell.homeLocked())'), shell.index('if (overview === "1"')) self.assertIn('omarchy-overview-open"', changed) self.assertIn('omarchy-overview-open', (PROJECT / 'desktop/shell/default/labwc/autostart').read_text()) diff --git a/tests/test_orchard_repository.py b/tests/test_orchard_repository.py index 6d8955c1..5d05cea7 100644 --- a/tests/test_orchard_repository.py +++ b/tests/test_orchard_repository.py @@ -28,7 +28,7 @@ Include = /etc/pacman.d/mirrorlist ''' ORCHARD = {'aarch64': ['wlroots0.20', 'labwc', 'omafox', 'omactivity', 'folio-touch', 'mesa', 'libva-v4l2-request'], - 'armv7h': ['wlroots0.20', 'labwc', 'omafox', 'omactivity', 'folio-touch', 'omacalc']} + 'armv7h': ['wlroots0.20', 'labwc', 'omafox', 'omactivity', 'folio-touch', 'mesa', 'omacalc']} def section(start, end): @@ -150,12 +150,14 @@ def test_one_transaction_installs_ours_with_everything_else(self): self.assertFalse([call for call in calls if re.search(r'(^| )-(R|U)', call)]) self.assertNotIn('-U', ASSEMBLE.read_text()) - def test_armv7_takes_files_and_omacalc_from_ours_and_keeps_archs_mesa(self): + def test_armv7_takes_files_omacalc_and_mesa_from_ours(self): code, calls, error = self.install('armv7h') self.assertEqual(code, 0, error) - wanted = 'base labwc wlroots0.20 omafox omactivity folio-touch omacalc omarchy-a' - self.assertEqual(calls, [f'download -Sy --noconfirm {wanted}', f'-S --print --print-format %r/%n {wanted}', - f'-S --noconfirm {wanted}', 'repositories', '-Dk']) + wanted = 'base labwc wlroots0.20 omafox omactivity folio-touch mesa omacalc omarchy-a' + self.assertEqual(calls[:5], [f'download -Sy --noconfirm {wanted}', f'-S --print --print-format %r/%n {wanted}', + f'-S --noconfirm {wanted}', 'repositories', '-Dk']) + self.assertIn('/r/usr/lib/libgbm.so.1 /r/usr/lib/orchard/gpu-probe', calls[5]) + self.assertNotIn('libvulkan_powervr_mesa.so', calls[5]) def test_a_package_of_ours_taken_elsewhere_stops_before_anything_installs(self): for planned in ([name for name in ORCHARD['aarch64'] if name != 'mesa'], # mesa would be Arch's diff --git a/tests/test_package.py b/tests/test_package.py index 237b676a..f2be90e7 100644 --- a/tests/test_package.py +++ b/tests/test_package.py @@ -353,7 +353,7 @@ def test_changed_files_links_modes_and_a_missing_install_step_fail(self): audit.verify_package_setup(self.ENTRIES, hashes) def test_the_compiled_helpers_are_of_the_roots_architecture(self): - self.assertEqual(set(audit.HELPERS), {'usr/libexec/omarchy-wtype', + self.assertEqual(set(audit.HELPERS), {'usr/libexec/omarchy-shell-ipc', 'usr/libexec/omarchy-wtype', 'usr/share/omarchy/trials/wvkbd-mobintl-v0.20-font18-special15-state'}) from release.architecture import check_elf check_elf(elf('aarch64'), 'aarch64') diff --git a/tests/test_powerd.py b/tests/test_powerd.py index cafc9d6c..0c617d62 100644 --- a/tests/test_powerd.py +++ b/tests/test_powerd.py @@ -516,13 +516,19 @@ def owner(name, new): self.assertFalse(powerd.parse_logind_started('Monitoring bus message stream.')) def test_only_a_running_playback_stream_counts(self): - def node(media, state): - return {'info': {'state': state, 'props': {'media.class': media}}} - self.assertTrue(powerd.streams_running(json.dumps([node('Stream/Output/Audio', 'running')]))) - for nodes in ([node('Stream/Output/Audio', 'idle')], [node('Stream/Input/Audio', 'running')], - [node('Audio/Sink', 'running')], [{'type': 'PipeWire:Interface:Core'}], []): - self.assertFalse(powerd.streams_running(json.dumps(nodes))) - self.assertFalse(powerd.streams_running('not json')) + def update(streams, *nodes): + return powerd.update_streams(streams, json.dumps(nodes)) + def node(ident, media, state): + return {'id': ident, 'info': {'state': state, 'props': {'media.class': media}}} + streams = {} + self.assertTrue(update(streams, node(1, 'Stream/Output/Audio', 'running'))) + self.assertTrue(update(streams, node(2, 'Audio/Sink', 'running'))) + self.assertTrue(update(streams, node(3, 'Stream/Output/Video', 'running'))) + self.assertTrue(update(streams, {'id': 1, 'info': None})) + self.assertFalse(update(streams, node(3, 'Stream/Output/Video', 'idle'))) + self.assertFalse(update(streams, node(1, 'Stream/Input/Audio', 'running'))) + with self.assertRaises(ValueError): + powerd.update_streams(streams, 'not json') class Integration(unittest.TestCase): @@ -547,7 +553,7 @@ def test_every_way_to_dark_uses_the_same_client_and_the_decided_times(self): client = '/usr/libexec/omarchy-powerctl' lock = (PROJECT / 'desktop/shell/shell/plugins/lock/Service.qml').read_text() idle = (PROJECT / 'desktop/shell/shell/plugins/services/idle/Service.qml').read_text() - self.assertIn(f'{client} idle', lock) + self.assertIn(f'["{client}", "idle"]', lock) self.assertIn(f'{client} idle', idle) self.assertIn('"1" ? 30000 : 5000', lock) self.assertEqual(powerd.SETTLE_SECONDS, 10.0) @@ -862,7 +868,7 @@ def setUp(self): ('STATS', self.stats), ('BACKLIGHTS', self.work / 'backlight'), ('BRIGHTNESS', self.remembered), ('WAKEUP_COUNT', self.work / 'wakeup_count'), ('SOCKET', str(self.work / 'ctl')), - ('session_user', lambda: None), ('command', self.fake_command), ('log', lambda *_: None)): + ('session_user', lambda **_: None), ('command', self.fake_command), ('log', lambda *_: None)): patcher = patch.object(powerd, target, value) patcher.start() self.addCleanup(patcher.stop) diff --git a/tests/test_settings_layout.py b/tests/test_settings_layout.py index ab6a50a3..962b0cb1 100644 --- a/tests/test_settings_layout.py +++ b/tests/test_settings_layout.py @@ -52,11 +52,20 @@ def test_a_pair_is_one_switch_that_runs_the_shown_entry(self): def test_a_command_checked_under_labwc_is_not_taken_for_hyprland(self): # omarchy-bar mentions Hyprland (a glassy bar's blur) but works here. - self.run_node(r''' -assert.ok(L.LABWC_CHECKED.includes('omarchy-bar')); -const script = M.stateScript(L.SECTIONS, ctx({ labwcChecked: L.LABWC_CHECKED }), {}); -assert.match(script, / omarchy-bar " != \*" \$c "\*/); -''') + import json + import os + import sys + import tempfile + with tempfile.TemporaryDirectory() as directory: + command = Path(directory) / 'omarchy-bar' + command.write_text('#!/bin/sh\nhyprctl reload\n') + command.chmod(0o755) + env = dict(os.environ, PATH=directory, HYPRLAND_INSTANCE_SIGNATURE='') + raw = subprocess.check_output([sys.executable, ROOT / 'shell/services/shell-facts.py', + 'commands', 'omarchy-bar', 'omarchy-absent'], env=env) + result = json.loads(raw) + self.assertEqual(result['hyprland'], {}) + self.assertEqual(result['missing'], {'omarchy-absent': True}) def test_a_page_whose_rows_are_all_hidden_is_dimmed(self): # Touchpad Haptics on anything but a Dell XPS: every level's guard says no. @@ -94,7 +103,6 @@ def test_deep_links_and_state(self): assert.deepEqual(M.route('appearance/theme', L.SECTIONS, ctx()), { section: 'appearance', page: { kind: 'native', page: 'theme' } }); assert.deepEqual(M.route('setup.security', L.SECTIONS, ctx()), { section: 'security', page: { kind: 'menu', id: 'setup.security' } }); assert.deepEqual(M.route('nowhere', L.SECTIONS, ctx()), { section: '', page: null }); -assert.deepEqual(M.parseState('m\tomarchy-bar\nh\tomarchy-x\nv\tappearance.icons\tPapercraft\n'), { missing: { 'omarchy-bar': true }, hyprland: { 'omarchy-x': true }, values: { 'appearance.icons': 'Papercraft' } }); // A command that is here but Hyprland's: dimmed and tagged outside Hyprland. const corners = M.resolveRow({ entry: 'appearance.windows.corners' }, ctx({ hyprland: Object.fromEntries(M.commandsIn(menu.items['appearance.windows.corners.sharp'].action).map(c => [c, true])) }), {}); assert.equal(corners.available, false); diff --git a/tools/measure-shell-open.py b/tools/measure-shell-open.py new file mode 100644 index 00000000..d41639b9 --- /dev/null +++ b/tools/measure-shell-open.py @@ -0,0 +1,147 @@ +"""Measure a settled, unlocked N42 session from a staged file under /var/tmp.""" +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +import os +from pathlib import Path +import re +import runpy +import select +import shutil +import signal +import subprocess as sp +import sys +import time + +bench = runpy.run_path(str(Path(__file__).with_name("n42-usability-device.py"))) +session = bench["Session"]() +pid = session.pids["qs"] +stat = Path(f"/proc/{pid}/stat") +env = dict(session.env, OMARCHY_SHELL_IPC_TIMEOUT="40s") +clock = time.monotonic +tag = sys.argv[1] +hz = os.sysconf("SC_CLK_TCK") + + +def cpu_ticks(): + fields = stat.read_text().rsplit(")", 1)[1].split() + return int(fields[11]) + int(fields[12]) + + +def idle_ticks(label): + start, ticks = clock(), cpu_ticks() + time.sleep(10) + used, elapsed = cpu_ticks() - ticks, clock() - start + print(label, f"qs {used} ticks in {elapsed:.3f} s ({100 * used / hz / elapsed:.2f}% of one core)", flush=True) + + +def timed_call(command, cmd_env): + start = clock() + result = sp.run(command, env=dict(cmd_env, OMARCHY_SHELL_IPC_TRACE="1"), **session.creds, + stdin=sp.DEVNULL, capture_output=True, text=True, timeout=45) + elapsed = round((clock() - start) * 1000) + if result.stderr.strip(): + print(result.stderr.strip(), flush=True) + result.check_returncode() + return elapsed + + +def pixels(): + raw = sp.check_output(["grim", "-s", "0.125", "-t", "ppm", "-"], env=env, + **session.creds, timeout=8) + header = re.match(rb"P6\s+(\d+)\s+(\d+)\s+255\s", raw) + width, height = map(int, header.groups()) + data = raw[header.end():] + assert len(data) == width * height * 3 + return data[(height // 10) * width * 3:] + + +def visible(command): + base = pixels() + start = previous = clock() + with ThreadPoolExecutor(1) as waiter: + client = waiter.submit(timed_call, [command], env) + while clock() - start < 45: + before = clock() + frame = pixels() + end = clock() + if sum(abs(a - b) > 12 for a, b in zip(base, frame)) > len(base) * .02: + print(command, "visible interval ms", round((previous-start)*1000), round((end-start)*1000), + "client elapsed ms", client.result(), flush=True) + return + previous = before + raise RuntimeError(f"No visible change for {command}") + + +def record(label, command=None): + data = Path(__file__).parent / f"{tag}-{label}.perf" + ctl_r, ctl_w = os.pipe() + ack_r, ack_w = os.pipe() + with sp.Popen(["perf", "record", "-a", "-D", "-1", f"--control=fd:{ctl_r},{ack_w}", + "-e", "sched:sched_process_exec", "-o", str(data)], + pass_fds=(ctl_r, ack_w), stdin=sp.DEVNULL) as perf: + os.close(ctl_r) + os.close(ack_w) + try: + os.write(ctl_w, b"enable\n") + if not select.select([ack_r], [], [], 10)[0] or not os.read(ack_r, 32).startswith(b"ack"): + raise RuntimeError("perf did not enable sched_process_exec") + before = cpu_ticks() + start = clock() + if command: + session.command(command) + time.sleep(max(0, 22 - (clock() - start))) + elapsed, used = clock() - start, (cpu_ticks() - before) / hz + finally: + if perf.poll() is None: + perf.send_signal(signal.SIGINT) + perf.wait(timeout=10) + os.close(ctl_w) + os.close(ack_r) + trace = sp.check_output(["perf", "script", "-i", str(data)], text=True) + names = Counter(re.findall(r"\bfilename=(.*?)\s+pid=", trace)) + (data.with_suffix(".txt")).write_text(trace) + print(label, f"{elapsed:.2f} s, qs CPU {used:.2f} s, {sum(names.values())} execs", names, flush=True) + + +with bench["stay_awake"](session): + session.ipc("omarchy.settings", "close") + session.ipc("omarchy.dock", "closeApps") + time.sleep(20) + record("idle") + idle_ticks("settings closed") + power_env = dict(env, PATH="/usr/local/bin:/usr/bin") + power_env.pop("WAYLAND_DISPLAY", None) + for name in ("omarchy-home-button", "omarchy-shell"): + path = shutil.which(name, path=power_env["PATH"]) + if not path: + raise RuntimeError(f"{name} missing from powerd PATH") + print("powerd PATH", name, Path(path).resolve(), flush=True) + print("shell ping (no capture) ms", timed_call(["omarchy-shell", "shell", "ping"], power_env), flush=True) + for cycle in range(1, 4): + for command, target, close in [("omarchy-settings", "omarchy.settings", "close"), + ("omarchy-home-button", "omarchy.dock", "closeApps")]: + try: + print("cycle", cycle, flush=True) + visible(command) + finally: + session.ipc(target, close) + time.sleep(4) + try: + # Match the physical button daemon's PATH and missing WAYLAND_DISPLAY. + print("powerd Home (no capture) ms", timed_call(["omarchy-home-button"], power_env), flush=True) + time.sleep(2) + finally: + session.ipc("omarchy.dock", "closeApps") + time.sleep(4) + for i in range(3): + try: + record(f"settings-{i+1}", "omarchy-settings") + try: + ready = session.ipc("omarchy.settings", "contentReady") + except sp.CalledProcessError: + ready = "unavailable on this revision" + print("settings body ready", ready, flush=True) + idle_ticks(f"settings-{i+1} open") + finally: + session.ipc("omarchy.settings", "close") + time.sleep(4)