A hardened Linux desktop, rebuilt from scratch, with your Windows apps built in. Free and open source.
Fixes from testing, faster under memory pressure, and more polish
Dan03285a11cd28
diff --git a/.gitattributes b/.gitattributesindex 7f7b633..f8cae7d 100644--- a/.gitattributes+++ b/.gitattributes@@ -4,4 +4,5 @@*.ps1 text eol=crlf*.png binary*.jpg binary+*.webp binary*.svg text eol=lfdiff --git a/branding/CREDITS.md b/branding/CREDITS.mdindex 4438229..f38d303 100644--- a/branding/CREDITS.md+++ b/branding/CREDITS.md@@ -4,5 +4,20 @@|---|---|---|---|| `logo/*.svg` (mark, white, ink, app icon, favicon) | Wild OS Design System | Wild OS project | GPL-3.0-or-later, like the rest of the project || `wallpaper/misty-lake.jpg` | [Pexels photo 6346489](https://www.pexels.com/photo/6346489/) | Quang Nguyen Vinh | [Pexels licence](https://www.pexels.com/license/): free to use and modify, no attribution required. Not to be sold unaltered or redistributed as a stock photo, and it does not imply the photographer endorses Wild OS. |+| `wallpaper/photos/fog-ridges.webp` (Fog Ridges) | [Pexels photo](https://www.pexels.com/photo/6136314/) | Quang Nguyen Vinh | [Pexels licence](https://www.pexels.com/license/) |+| `wallpaper/photos/fog-ridges-evening.webp` (Evening Ridges) | [Pexels photo](https://www.pexels.com/photo/6136306/) | Quang Nguyen Vinh | [Pexels licence](https://www.pexels.com/license/) |+| `wallpaper/photos/misty-lake-sunrise.webp` (Misty Lake Sunrise) | [Unsplash photo](https://unsplash.com/photos/MprDXksPXlE) | Scott Goodwill | [Unsplash licence](https://unsplash.com/license) |+| `wallpaper/photos/golden-haze.webp` (Golden Haze) | [Unsplash photo](https://unsplash.com/photos/2BmDckO4cfs) | Nguyen Duc | [Unsplash licence](https://unsplash.com/license) |+| `wallpaper/photos/black-curve.webp` (Black Curve) | [Unsplash photo](https://unsplash.com/photos/0wFwSZn6I-I) | Pawel Czerwinski | [Unsplash licence](https://unsplash.com/license) |+| `wallpaper/photos/dark-waves.webp` (Dark Waves) | [Unsplash photo](https://unsplash.com/photos/JTKKRK05NAM) | Milad Fakurian | [Unsplash licence](https://unsplash.com/license) |+| `wallpaper/photos/storm-lake.webp` (Storm Lake) | [Unsplash photo](https://unsplash.com/photos/SaBZ-sEPBtU) | v2osk | [Unsplash licence](https://unsplash.com/license) |+| `wallpaper/photos/green-lines.webp` (Green Lines) | [Unsplash photo](https://unsplash.com/photos/PLSN4T63oCg) | Pawel Czerwinski | [Unsplash licence](https://unsplash.com/license) |+| `wallpaper/photos/green-ribbons.webp` (Green Ribbons) | [Unsplash photo](https://unsplash.com/photos/RmMCdS-Nh74) | Pawel Czerwinski | [Unsplash licence](https://unsplash.com/license) |+| `wallpaper/photos/spectrum.webp` (Spectrum) | [Unsplash photo](https://unsplash.com/photos/LeG68PrXA6Y) | Codioful | [Unsplash licence](https://unsplash.com/license) |+| `wallpaper/photos/white-dunes.webp` (White Dunes) | [Unsplash photo](https://unsplash.com/photos/Vnnlb1m78w4) | Joseph Corl | [Unsplash licence](https://unsplash.com/license) |+| `wallpaper/photos/snowdonia.webp` (Snowdonia) | [Pexels photo](https://www.pexels.com/photo/18573601/) | T6 Adventures | [Pexels licence](https://www.pexels.com/license/) |+| `wallpaper/photos/llandudno.webp` (Llandudno) | [Pexels photo](https://www.pexels.com/photo/7541798/) | Lisa Fotios | [Pexels licence](https://www.pexels.com/license/) |+| `wallpaper/photos/penmaenpool.webp` (Penmaenpool) | [Pexels photo](https://www.pexels.com/photo/9575573/) | Simon J | [Pexels licence](https://www.pexels.com/license/) |+| `wallpaper/photos/ogmore-by-sea.webp` (Ogmore-by-Sea) | [Pexels photo](https://www.pexels.com/photo/36948108/) | Tim Morgan | [Pexels licence](https://www.pexels.com/license/) |-The wallpaper is not under the project's GPL licence. Anyone redistributing Wild OS images keeps it under the Pexels licence above.+The wallpapers are not under the project's GPL licence. Each stays under its own licence above, Pexels or Unsplash: free to use and modify, no attribution required, not to be sold unaltered or redistributed as stock photos, and no endorsement of Wild OS by the photographers is implied.diff --git a/branding/wallpaper/make-masters.py b/branding/wallpaper/make-masters.pynew file mode 100644index 0000000..5e32086--- /dev/null+++ b/branding/wallpaper/make-masters.py@@ -0,0 +1,35 @@+#!/usr/bin/env python3+"""Makes the wallpaper masters from the photographers' original files.++ python3 make-masters.py <folder of originals>++Run by hand when photos.json changes, not by the package build: the+originals are 100 MB and more and stay out of the repository. Each photo is+scaled and centre-cropped to 5120 by 2880 (16:9, 5K), the largest screen+Wild OS draws for, and saved as photos/<id>.webp. Plasma scales that down+for smaller screens and crops it for other shapes, so one size covers all.+"""++import json+import sys+from pathlib import Path++from PIL import Image, ImageOps++SIZE = (5120, 2880)+QUALITY = 88++here = Path(__file__).resolve().parent+originals = Path(sys.argv[1])+out = here / "photos"+out.mkdir(exist_ok=True)+Image.MAX_IMAGE_PIXELS = None++for photo in json.loads((here / "photos.json").read_text()):+ image = ImageOps.exif_transpose(Image.open(originals / photo["file"])).convert("RGB")+ # A few per cent of enlargement is invisible; more would soften it.+ if max(SIZE[0] / image.width, SIZE[1] / image.height) > 1.05:+ sys.exit(f"{photo['file']} is {image.width}x{image.height}, too small for {SIZE[0]}x{SIZE[1]}")+ target = out / f"{photo['id']}.webp"+ ImageOps.fit(image, SIZE, Image.LANCZOS).save(target, "WEBP", quality=QUALITY, method=6)+ print(target, round(target.stat().st_size / 1e6, 1), "MB")diff --git a/branding/wallpaper/photos.json b/branding/wallpaper/photos.jsonnew file mode 100644index 0000000..48fb94f--- /dev/null+++ b/branding/wallpaper/photos.json@@ -0,0 +1,17 @@+[+ {"id": "fog-ridges", "title": "Fog Ridges", "theme": "dawn", "file": "dawn-fog-ridges-sunset_quang-nguyen-vinh.jpg", "author": "Quang Nguyen Vinh", "source": "https://www.pexels.com/photo/6136314/", "licence": "Pexels"},+ {"id": "fog-ridges-evening", "title": "Evening Ridges", "theme": "dawn", "file": "dawn-fog-ridges-evening_quang-nguyen-vinh.jpg", "author": "Quang Nguyen Vinh", "source": "https://www.pexels.com/photo/6136306/", "licence": "Pexels"},+ {"id": "misty-lake-sunrise", "title": "Misty Lake Sunrise", "theme": "dawn", "file": "dawn-misty-lake-sunrise_scott-goodwill.jpg", "author": "Scott Goodwill", "source": "https://unsplash.com/photos/MprDXksPXlE", "licence": "Unsplash"},+ {"id": "golden-haze", "title": "Golden Haze", "theme": "orchard", "file": "ember-golden-haze-lake_nguyen-duc.jpg", "author": "Nguyen Duc", "source": "https://unsplash.com/photos/2BmDckO4cfs", "licence": "Unsplash"},+ {"id": "black-curve", "title": "Black Curve", "theme": "graphite", "file": "graphite-black-curve_pawel-czerwinski.jpg", "author": "Pawel Czerwinski", "source": "https://unsplash.com/photos/0wFwSZn6I-I", "licence": "Unsplash"},+ {"id": "dark-waves", "title": "Dark Waves", "theme": "graphite", "file": "graphite-dark-waves_milad-fakurian.jpg", "author": "Milad Fakurian", "source": "https://unsplash.com/photos/JTKKRK05NAM", "licence": "Unsplash"},+ {"id": "storm-lake", "title": "Storm Lake", "theme": "graphite", "file": "graphite-storm-mountain-lake_v2osk.jpg", "author": "v2osk", "source": "https://unsplash.com/photos/SaBZ-sEPBtU", "licence": "Unsplash"},+ {"id": "green-lines", "title": "Green Lines", "theme": "overclock", "file": "overclock-green-lines_pawel-czerwinski.jpg", "author": "Pawel Czerwinski", "source": "https://unsplash.com/photos/PLSN4T63oCg", "licence": "Unsplash"},+ {"id": "green-ribbons", "title": "Green Ribbons", "theme": "overclock", "file": "overclock-green-ribbons_pawel-czerwinski.jpg", "author": "Pawel Czerwinski", "source": "https://unsplash.com/photos/RmMCdS-Nh74", "licence": "Unsplash"},+ {"id": "spectrum", "title": "Spectrum", "theme": "overclock", "file": "spectrum-rainbow-gradient_codioful.jpg", "author": "Codioful", "source": "https://unsplash.com/photos/LeG68PrXA6Y", "licence": "Unsplash"},+ {"id": "white-dunes", "title": "White Dunes", "theme": "ember", "file": "ember-white-dunes-sunset_joseph-corl.jpg", "author": "Joseph Corl", "source": "https://unsplash.com/photos/Vnnlb1m78w4", "licence": "Unsplash"},+ {"id": "snowdonia", "title": "Snowdonia", "theme": "estuary", "file": "estuary-snowdonia-valleys_t6-adventures.jpg", "author": "T6 Adventures", "source": "https://www.pexels.com/photo/18573601/", "licence": "Pexels"},+ {"id": "llandudno", "title": "Llandudno", "theme": "estuary", "file": "estuary-llandudno-sunset_lisa-fotios.jpg", "author": "Lisa Fotios", "source": "https://www.pexels.com/photo/7541798/", "licence": "Pexels"},+ {"id": "penmaenpool", "title": "Penmaenpool", "theme": "estuary", "file": "estuary-penmaenpool-river_simon-j.jpg", "author": "Simon J", "source": "https://www.pexels.com/photo/9575573/", "licence": "Pexels"},+ {"id": "ogmore-by-sea", "title": "Ogmore-by-Sea", "theme": "estuary", "file": "estuary-ogmore-by-sea_tim-morgan.jpg", "author": "Tim Morgan", "source": "https://www.pexels.com/photo/36948108/", "licence": "Pexels"}+]diff --git a/branding/wallpaper/photos/black-curve.webp b/branding/wallpaper/photos/black-curve.webpnew file mode 100644index 0000000..b5ab02dBinary files /dev/null and b/branding/wallpaper/photos/black-curve.webp differdiff --git a/branding/wallpaper/photos/dark-waves.webp b/branding/wallpaper/photos/dark-waves.webpnew file mode 100644index 0000000..6b625d5Binary files /dev/null and b/branding/wallpaper/photos/dark-waves.webp differdiff --git a/branding/wallpaper/photos/fog-ridges-evening.webp b/branding/wallpaper/photos/fog-ridges-evening.webpnew file mode 100644index 0000000..63f6923Binary files /dev/null and b/branding/wallpaper/photos/fog-ridges-evening.webp differdiff --git a/branding/wallpaper/photos/fog-ridges.webp b/branding/wallpaper/photos/fog-ridges.webpnew file mode 100644index 0000000..6294249Binary files /dev/null and b/branding/wallpaper/photos/fog-ridges.webp differdiff --git a/branding/wallpaper/photos/golden-haze.webp b/branding/wallpaper/photos/golden-haze.webpnew file mode 100644index 0000000..00d11a2Binary files /dev/null and b/branding/wallpaper/photos/golden-haze.webp differdiff --git a/branding/wallpaper/photos/green-lines.webp b/branding/wallpaper/photos/green-lines.webpnew file mode 100644index 0000000..23f27afBinary files /dev/null and b/branding/wallpaper/photos/green-lines.webp differdiff --git a/branding/wallpaper/photos/green-ribbons.webp b/branding/wallpaper/photos/green-ribbons.webpnew file mode 100644index 0000000..8d414b4Binary files /dev/null and b/branding/wallpaper/photos/green-ribbons.webp differdiff --git a/branding/wallpaper/photos/llandudno.webp b/branding/wallpaper/photos/llandudno.webpnew file mode 100644index 0000000..f40cedbBinary files /dev/null and b/branding/wallpaper/photos/llandudno.webp differdiff --git a/branding/wallpaper/photos/misty-lake-sunrise.webp b/branding/wallpaper/photos/misty-lake-sunrise.webpnew file mode 100644index 0000000..c556229Binary files /dev/null and b/branding/wallpaper/photos/misty-lake-sunrise.webp differdiff --git a/branding/wallpaper/photos/ogmore-by-sea.webp b/branding/wallpaper/photos/ogmore-by-sea.webpnew file mode 100644index 0000000..e17a799Binary files /dev/null and b/branding/wallpaper/photos/ogmore-by-sea.webp differdiff --git a/branding/wallpaper/photos/penmaenpool.webp b/branding/wallpaper/photos/penmaenpool.webpnew file mode 100644index 0000000..52a5ce9Binary files /dev/null and b/branding/wallpaper/photos/penmaenpool.webp differdiff --git a/branding/wallpaper/photos/snowdonia.webp b/branding/wallpaper/photos/snowdonia.webpnew file mode 100644index 0000000..113e403Binary files /dev/null and b/branding/wallpaper/photos/snowdonia.webp differdiff --git a/branding/wallpaper/photos/spectrum.webp b/branding/wallpaper/photos/spectrum.webpnew file mode 100644index 0000000..329a80eBinary files /dev/null and b/branding/wallpaper/photos/spectrum.webp differdiff --git a/branding/wallpaper/photos/storm-lake.webp b/branding/wallpaper/photos/storm-lake.webpnew file mode 100644index 0000000..6adfa22Binary files /dev/null and b/branding/wallpaper/photos/storm-lake.webp differdiff --git a/branding/wallpaper/photos/white-dunes.webp b/branding/wallpaper/photos/white-dunes.webpnew file mode 100644index 0000000..30d0acfBinary files /dev/null and b/branding/wallpaper/photos/white-dunes.webp differdiff --git a/build-iso.sh b/build-iso.shindex 5d9a579..8e0b9bf 100644--- a/build-iso.sh+++ b/build-iso.sh@@ -2,6 +2,8 @@# Builds the Wild OS ISO into ./out using the builder container.# --incremental reuses the last build (see build/incremental.sh).# WILDOS_CACHE names the volume or directory kept between builds.+# WILDOS_WORK names the scratch volume: one per worktree lets several builds+# run at once without wiping each other's work.set -euo pipefailcd "$(dirname "$0")"@@ -22,6 +24,6 @@ docker run --rm --privileged \-e WILDOS_ONLY \-v "$PWD":/src:ro \-v "$PWD/out":/out \- -v wildos-work:/work \+ -v "${WILDOS_WORK:-wildos-work}":/work \-v "${WILDOS_CACHE:-wildos-cache}":/cache \wildos-builder bash /src/build/build.sh "$@"diff --git a/build/Dockerfile b/build/Dockerfileindex 99c7b11..76c3967 100644--- a/build/Dockerfile+++ b/build/Dockerfile@@ -50,6 +50,10 @@ RUN apt-get update \kwin-dev \libcups2-dev \libglib2.0-dev \+ libcamel1.2-dev \+ libedataserver1.2-dev \+ liblitehtml-dev \+ qtkeychain-qt6-dev \libksysguard-dev \python3 \python3-pil \@@ -82,3 +86,29 @@ RUN apt-get update \python3-gi \gir1.2-glib-2.0 \&& rm -rf /var/lib/apt/lists/*++# wildos-rdp, Windows mode's window client, builds against FreeRDP 3.32+# from trixie-backports, the version the image pins (wildos-base's+# wildos-freerdp.pref); trixie's own 3.15 drew RemoteApp windows wrongly.+# wayland-protocols has the window icon protocol it speaks to KWin.+RUN echo "deb http://deb.debian.org/debian trixie-backports main" > /etc/apt/sources.list.d/backports.list \+ && apt-get update \+ && apt-get install -y --no-install-recommends -t trixie-backports \+ freerdp3-dev \+ libwinpr3-dev \+ && apt-get install -y --no-install-recommends \+ wayland-protocols \+ && rm -rf /var/lib/apt/lists/*++# Calendar (wildos-mail) builds against evolution-data-server's calendar+# library. New build dependencies go in layers of their own like this one:+# adding one to the big list above makes Docker reinstall all of it.+RUN apt-get update \+ && apt-get install -y --no-install-recommends libecal2.0-dev \+ && rm -rf /var/lib/apt/lists/*++# Quick Look in Files (wildos-files) previews PDFs through QtQuick.Pdf; its+# QML is compiled against the module's types.+RUN apt-get update \+ && apt-get install -y --no-install-recommends qml6-module-qtquick-pdf qml6-module-qtmultimedia \+ && rm -rf /var/lib/apt/lists/*diff --git a/build/build.sh b/build/build.shindex 28b0c44..68dea3e 100644--- a/build/build.sh+++ b/build/build.sh@@ -21,7 +21,9 @@ set -euo pipefail# build changes the running build. Work from a snapshot instead.if [ -z "${WILDOS_SNAPSHOT:-}" ]; thenrm -rf /tmp/src && mkdir -p /tmp/src- tar -C /src --exclude=./out --exclude=./.git -cf - . | tar -C /tmp/src -xf -+ # site/ is the update repository publish-local.sh clones beside the+ # checkout: hundreds of megabytes the build never reads.+ tar -C /src --exclude=./out --exclude=./.git --exclude=./site -cf - . | tar -C /tmp/src -xf -WILDOS_SNAPSHOT=1 exec bash /tmp/src/build/build.sh "$@"fi@@ -35,7 +37,7 @@ VERSION=$(sed -n '1s/.*(\(.*\)).*/\1/p' "$SRC/packages/wildos-base/debian/changeISO_NAME="wildos-${VERSION}-amd64.iso"KICKSECURE_KEY=/usr/share/keyrings/kicksecure-derivative.asc-log() { printf '\n==> %s\n' "$*"; }+log() { printf '\n==> [%s] %s\n' "$(date +%T)" "$*"; }ROOTFS=$WORK/rootfsSQUASH_LEVEL=19@@ -58,6 +60,12 @@ cp -r "$SRC/packages/." "$WORK/pkgsrc/"# their sizes and formats from it.rm -rf "$WORK/pkgsrc/wildos-branding/branding"cp -r "$SRC/branding" "$WORK/pkgsrc/wildos-branding/branding"+# Remote is built on Windows mode's Remote Desktop engine. Its own copy+# makes its build stand alone and changes the package's hash whenever the+# engine changes, so an incremental build rebuilds it too.+rm -rf "$WORK/pkgsrc/wildos-remote/rdp-engine"+mkdir -p "$WORK/pkgsrc/wildos-remote/rdp-engine"+cp -r "$SRC/packages/wildos-rdp/engine.cmake" "$SRC/packages/wildos-rdp/src" "$WORK/pkgsrc/wildos-remote/rdp-engine/"# Windows bind mounts report every file as executable. debhelper treats an# executable debian/install as a script and installs its output instead of its# contents, which silently produces empty packages.@@ -97,6 +105,16 @@ fiif [ "$INCREMENTAL" = 1 ]; theninc_build_packageselse+ # Several packages at once: much of a package build (debhelper, QML+ # caches, compressing) uses one core, so one at a time leaves most of+ # them idle. Each keeps its own log, shown if it fails.+ # Counted here: `jobs` inside $(...) sees no jobs, which once let the+ # build carry on before the packages were made.+ max_jobs=$(( $(nproc) / 4 ))+ [ "$max_jobs" -lt 2 ] && max_jobs=2+ failed=0+ running=0+ built=()for pkg in "$WORK"/pkgsrc/*/; do# Work in progress is kept out of the image until it is ready.[ -e "$pkg/NOT-READY" ] && continue@@ -105,10 +123,29 @@ elseif [ -n "${WILDOS_ONLY+set}" ] && [[ " $WILDOS_ONLY " != *" $(basename "$pkg") "* ]]; thencontinuefi- (cd "$pkg" && DEB_BUILD_OPTIONS="parallel=$(nproc)" dpkg-buildpackage -us -uc -b -d -tc >/dev/null)+ if [ "$running" -ge "$max_jobs" ]; then+ wait -n || failed=1+ running=$((running - 1))+ fi+ name=$(basename "$pkg")+ built+=("$name")+ (cd "$pkg" && DEB_BUILD_OPTIONS="parallel=$(nproc)" dpkg-buildpackage -us -uc -b -d -tc >"$WORK/build-$name.log" 2>&1 \+ || { echo "ERROR: $name failed to build:" >&2; tail -40 "$WORK/build-$name.log" >&2; exit 1; }) &+ running=$((running + 1))+ done+ while [ "$running" -gt 0 ]; do+ wait -n || failed=1+ running=$((running - 1))done+ [ "$failed" = 0 ] || exit 1+ rm -f "$WORK"/build-*.logfifind "$WORK/pkgsrc" -maxdepth 1 -name '*.deb' -exec mv {} "$WORK/repo/" \;+# Every package asked for has to have come out of it.+for name in "${built[@]:-}"; do+ [ -z "$name" ] && continue+ ls "$WORK/repo/${name}_"*.deb >/dev/null 2>&1 || { echo "ERROR: no package came out of $name" >&2; exit 1; }+done# Debian's plymouth declares "Conflicts: console-common", which Kicksecure's# core layer depends on. The two share no files: the conflict dates from@@ -292,6 +329,135 @@ find "$WORK/pkgsrc" -maxdepth 1 -name '*.deb' -exec mv {} "$WORK/repo/" \;ficp "$cached"/*.deb "$WORK/repo/")+# evolution-data-server with Camel's mail modules (IMAP, SMTP and the rest)+# split into evolution-data-server-camel-providers, which needs only+# libcamel, and its calendar and contacts services into+# evolution-data-server-core. Wild OS Mail, Calendar and People use those+# without the rest of EDS, whose package brings WebKitGTK, GTK and+# gnome-keyring (a second Secret Service beside KWallet).+# evolution-data-server itself depends on both, so Evolution works as+# before. A packaging change, not a source patch, so it+# is made here; republished +wildos1 like KIO, since its packages require+# each other's exact version.+(+ cd "$WORK"+ version=$(apt-cache policy libcamel-1.2-64t64 | sed -n 's/^ Candidate: //p')+ if [ -z "$version" ] || [ "$version" = "(none)" ]; then+ apt-get update -qq+ version=$(apt-cache policy libcamel-1.2-64t64 | sed -n 's/^ Candidate: //p')+ fi+ stamp=$(sed -n '/^# evolution-data-server with Camel/,/^)$/p' "$SRC/build/build.sh" | sha256sum | cut -c1-12)+ cached="/cache/eds/$version$(wildos_suffix eds)-$stamp"+ if [ ! -d "$cached" ]; then+ log "Building evolution-data-server $version with the Camel providers split out"+ echo "deb-src http://deb.debian.org/debian $SUITE main" > /etc/apt/sources.list.d/wildos-src.list+ echo "deb-src http://deb.debian.org/debian-security $SUITE-security main" >> /etc/apt/sources.list.d/wildos-src.list+ apt-get update -qq+ DEBIAN_FRONTEND=noninteractive apt-get build-dep -y -qq "evolution-data-server=$version" >/dev/null+ rm -rf eds-src && mkdir eds-src && cd eds-src+ apt-get source -qq "evolution-data-server=$version" >/dev/null+ cd evolution-data-server-*/+ # The lists below divide Debian's install list between three+ # packages, so they are only right for the list they were written+ # against. dh_missing catches a file left out.+ echo "addacfaf2a60e9914c1baeaa549c9d1f6674edd8dc9d1e687b926c08255f3ee7 debian/evolution-data-server.install" | sha256sum -c --quiet \+ || { echo "ERROR: evolution-data-server's install list changed; update the split" >&2; exit 1; }+ printf '%s\n' 'usr/lib/evolution-data-server/camel-providers/*.urls' 'usr/lib/evolution-data-server/camel-providers/*.so' \+ > debian/evolution-data-server-camel-providers.install+ # The core: the source registry and the calendar and contacts+ # services with their backends, none of which link GTK or WebKit.+ # Wild OS Calendar and People run on it, with KWallet's Secret+ # Service holding their passwords.+ cat > debian/evolution-data-server-core.install <<'LIST'+usr/libexec/evolution-addressbook-*+usr/libexec/evolution-calendar-*+usr/libexec/evolution-data-server/addressbook-export+usr/libexec/evolution-data-server/csv2vcard+usr/libexec/evolution-data-server/list-sources+usr/libexec/evolution-scan-gconf-tree-xml+usr/libexec/evolution-source-registry+usr/lib/evolution-data-server/addressbook-backends/*.so+usr/lib/evolution-data-server/calendar-backends/libecalbackendcaldav.so+usr/lib/evolution-data-server/calendar-backends/libecalbackendcontacts.so+usr/lib/evolution-data-server/calendar-backends/libecalbackendfile.so+usr/lib/evolution-data-server/calendar-backends/libecalbackendgtasks.so+usr/lib/evolution-data-server/calendar-backends/libecalbackendhttp.so+usr/lib/evolution-data-server/calendar-backends/libecalbackendwebdavnotes.so+usr/lib/evolution-data-server/registry-modules/module-cache-reaper.so+usr/lib/evolution-data-server/registry-modules/module-google-backend.so+usr/lib/evolution-data-server/registry-modules/module-oauth2-services.so+usr/lib/evolution-data-server/registry-modules/module-outlook-backend.so+usr/lib/evolution-data-server/registry-modules/module-secret-monitor.so+usr/lib/evolution-data-server/registry-modules/module-webdav-backend.so+usr/lib/evolution-data-server/registry-modules/module-yahoo-backend.so+usr/lib/systemd/user/evolution-addressbook-factory.service+usr/lib/systemd/user/evolution-calendar-factory.service+usr/lib/systemd/user/evolution-source-registry.service+LIST+ # What stays: the GTK and WebKit programs (reminders, prompts, the+ # OAuth window, the certificate prompt), weather, GNOME Online+ # Accounts and Camel's helpers, with gnome-keyring as before.+ cat > debian/evolution-data-server.install <<'LIST'+etc+usr/libexec/camel-*+usr/libexec/evolution-data-server/evolution-alarm-notify+usr/libexec/evolution-data-server/evolution-oauth2-handler+usr/libexec/evolution-user-prompter+usr/lib/evolution-data-server/calendar-backends/libecalbackendweather.so+usr/lib/evolution-data-server/credential-modules/*.so+usr/lib/evolution-data-server/registry-modules/module-gnome-online-accounts.so+usr/lib/evolution-data-server/registry-modules/module-trust-prompt.so+usr/lib/systemd/user/evolution-user-prompter.service+usr/share/applications/org.gnome.Evolution-alarm-notify.desktop+usr/share/applications/org.gnome.evolution-data-server.OAuth2-handler.desktop+usr/share/icons/hicolor/scalable/apps/org.gnome.Evolution-alarm-notify.svg+LIST+ sed -i 's/^ libcamel-1.2-64t64 (= ${binary:Version}),$/&\n evolution-data-server-camel-providers (= ${binary:Version}),\n evolution-data-server-core (= ${binary:Version}),/' debian/control+ grep -q 'evolution-data-server-core (= ' debian/control \+ || { echo "ERROR: evolution-data-server's Depends changed shape; update the split" >&2; exit 1; }+ cat >> debian/control <<'STANZA'++Package: evolution-data-server-camel-providers+Architecture: any+Depends: ${shlibs:Depends},+ ${misc:Depends},+ libcamel-1.2-64t64 (= ${binary:Version}),+Breaks: evolution-data-server (<< ${binary:Version})+Replaces: evolution-data-server (<< ${binary:Version})+Description: Camel mail providers (IMAP, SMTP, POP3 and local mail)+ The modules Camel, Evolution Data Server's mail library, uses to reach+ mail servers and mail stored on disk, split out of evolution-data-server+ for programs that use Camel without the rest of it.++Package: evolution-data-server-core+Architecture: any+Depends: ${shlibs:Depends},+ ${misc:Depends},+ evolution-data-server-common (>= ${source:Version}),+ libcamel-1.2-64t64 (= ${binary:Version}),+Breaks: evolution-data-server (<< ${binary:Version})+Replaces: evolution-data-server (<< ${binary:Version})+Description: Evolution Data Server's calendar and contacts services+ The source registry and the calendar and address book services with+ their backends (local, CalDAV, CardDAV, Google, LDAP), split out of+ evolution-data-server for desktops that do not use GTK. Passwords go to+ whichever Secret Service the desktop runs.+STANZA+ {+ printf 'evolution-data-server (%s%s) %s; urgency=medium\n\n' "$version" "$(wildos_suffix eds)" "$SUITE"+ printf ' * Wild OS: Camel providers in evolution-data-server-camel-providers,\n the calendar and contacts services in evolution-data-server-core.\n\n'+ printf ' -- Wild OS Developers <[email protected]> %s\n\n' "$(date -R)"+ cat debian/changelog+ } > debian/changelog.new+ mv debian/changelog.new debian/changelog+ DEB_BUILD_OPTIONS="nocheck nodoc parallel=$(nproc)" dpkg-buildpackage -us -uc -b >/dev/null+ mkdir -p "$cached"+ cp ../*+wildos[0-9]*_*.deb "$cached/"+ rm -f "$cached"/*dbgsym* "$cached"/*-tests_* "$cached"/*-doc_*+ cd "$WORK" && rm -rf eds-src+ fi+ cp "$cached"/*.deb "$WORK/repo/"+)(cd "$WORK/repo" && apt-ftparchive packages . > Packages)ls -1 "$WORK/repo"/*.deb# What the update repository publishes: the Wilddiff --git a/packages/wildos-base/debian/control b/packages/wildos-base/debian/controlindex 916e33f..75f5bbd 100644--- a/packages/wildos-base/debian/control+++ b/packages/wildos-base/debian/control@@ -16,6 +16,8 @@ Depends:sudo,polkitd,locales,+ systemd-zram-generator,+ systemd-oomd,Description: Wild OS base systemIdentity and security layer of Wild OS. Pulls in the Kicksecure hardeningpackages (kernel and sysctl hardening, AppArmor profiles, secure time sync,diff --git a/packages/wildos-base/debian/install b/packages/wildos-base/debian/installindex 4309427..370f76c 100644--- a/packages/wildos-base/debian/install+++ b/packages/wildos-base/debian/install@@ -12,3 +12,8 @@ files/apt/wildos-freerdp.pref etc/apt/preferences.d/files/grub/10_wildos usr/lib/wildos/grub.d/files/grub/31_wildos_firmware usr/lib/wildos/grub.d/files/systemd/* usr/lib/systemd/system/+files/performance/zram-generator.conf usr/lib/systemd/+files/performance/999-wildos-performance.conf usr/lib/sysctl.d/+files/udev/60-wildos-io-scheduler.rules usr/lib/udev/rules.d/+files/oomd/wildos.conf usr/lib/systemd/system/[email protected]/+files/oomd/oomd.conf usr/lib/systemd/oomd.conf.d/diff --git a/packages/wildos-base/debian/postinst b/packages/wildos-base/debian/postinstindex ffc6299..ebc0aa3 100644--- a/packages/wildos-base/debian/postinst+++ b/packages/wildos-base/debian/postinst@@ -67,4 +67,17 @@ if [ "$1" = "configure" ] && getent group privleap >/dev/null && getent group codonefi+# The memory and disk tuning reaches a running PC with this update, not only+# after the next restart. The image build has no running systemd, so there+# it only enables oomd and the rest starts on first boot.+if [ "$1" = "configure" ] && [ -d /run/systemd/system ]; then+ sysctl -q --load=/usr/lib/sysctl.d/999-wildos-performance.conf || true+ udevadm trigger --subsystem-match=block --action=change || true+ systemctl daemon-reload || true+ systemctl start [email protected] || true+ systemctl enable --now systemd-oomd.service || true+elif [ "$1" = "configure" ]; then+ systemctl enable systemd-oomd.service || true+fi+#DEBHELPER#diff --git a/packages/wildos-base/files/oomd/oomd.conf b/packages/wildos-base/files/oomd/oomd.confnew file mode 100644index 0000000..0254657--- /dev/null+++ b/packages/wildos-base/files/oomd/oomd.conf@@ -0,0 +1,2 @@+[OOM]+DefaultMemoryPressureDurationSec=20sdiff --git a/packages/wildos-base/files/oomd/wildos.conf b/packages/wildos-base/files/oomd/wildos.confnew file mode 100644index 0000000..f443bb0--- /dev/null+++ b/packages/wildos-base/files/oomd/wildos.conf@@ -0,0 +1,7 @@+# When an app has been starved of memory for 20 seconds, systemd-oomd closes+# the app causing it instead of letting the whole PC freeze. Each app runs in+# its own scope under the user's session, so only that app goes. Windows mode+# runs outside the session and is not touched.+[Service]+ManagedOOMMemoryPressure=kill+ManagedOOMMemoryPressureLimit=60%diff --git a/packages/wildos-base/files/performance/999-wildos-performance.conf b/packages/wildos-base/files/performance/999-wildos-performance.confnew file mode 100644index 0000000..65c117a--- /dev/null+++ b/packages/wildos-base/files/performance/999-wildos-performance.conf@@ -0,0 +1,18 @@+# Sorts after Kicksecure's 990-security-misc.conf, which sets swappiness to 1+# to keep memory off the disk. With zram at a higher priority, swapping goes+# to compressed memory first, and anything that overflows lands in the swap+# file inside the encrypted root, so a high value no longer means plain text+# on disk.+vm.swappiness = 100++# zram reads single pages fast, so reading ahead in clusters only wastes work.+vm.page-cluster = 0++# Keep directory and inode caches longer, which keeps Files and app launches+# quick after something big has gone through memory.+vm.vfs_cache_pressure = 50++# Fixed limits instead of a share of RAM, so copying a large file to a slow+# USB stick never builds up gigabytes of pending writes that freeze the desktop.+vm.dirty_bytes = 268435456+vm.dirty_background_bytes = 67108864diff --git a/packages/wildos-base/files/performance/zram-generator.conf b/packages/wildos-base/files/performance/zram-generator.confnew file mode 100644index 0000000..8c49574--- /dev/null+++ b/packages/wildos-base/files/performance/zram-generator.conf@@ -0,0 +1,7 @@+# Compressed swap in memory, used before the encrypted swap file on disk.+# Pages compress about 3:1 with zstd, so a PC under memory pressure slows+# down gently instead of stalling on disk.+[zram0]+zram-size = min(ram / 2, 8192)+compression-algorithm = zstd+swap-priority = 100diff --git a/packages/wildos-base/files/udev/60-wildos-io-scheduler.rules b/packages/wildos-base/files/udev/60-wildos-io-scheduler.rulesnew file mode 100644index 0000000..c94e100--- /dev/null+++ b/packages/wildos-base/files/udev/60-wildos-io-scheduler.rules@@ -0,0 +1,6 @@+# NVMe drives are fastest with no scheduler, SATA SSDs and memory cards with+# mq-deadline, and spinning disks with BFQ, which keeps the desktop responsive+# while something reads or writes a lot.+ACTION=="add|change", KERNEL=="nvme[0-9]*n[0-9]*", ATTR{queue/scheduler}="none"+ACTION=="add|change", KERNEL=="sd[a-z]*|mmcblk[0-9]*", ATTR{queue/rotational}=="0", ATTR{queue/scheduler}="mq-deadline"+ACTION=="add|change", KERNEL=="sd[a-z]*", ATTR{queue/rotational}=="1", ATTR{queue/scheduler}="bfq"diff --git a/packages/wildos-branding/debian/changelog b/packages/wildos-branding/debian/changelogindex 16e6bc5..58cfa2f 100644--- a/packages/wildos-branding/debian/changelog+++ b/packages/wildos-branding/debian/changelog@@ -1,3 +1,15 @@+wildos-branding (0.1.2) trixie; urgency=medium++ * Every Plasma style has a solid twin for stronger text on glass.++ -- Wild OS Developers <[email protected]> Tue, 10 Nov 2026 08:10:42 +0000++wildos-branding (0.1.1) trixie; urgency=medium++ * .deb, .flatpakref and .flatpak files open in the Store by default.++ -- Wild OS Developers <[email protected]> Tue, 10 Nov 2026 07:50:00 +0000+wildos-branding (0.1.0) trixie; urgency=medium* Initial release.diff --git a/packages/wildos-branding/debian/control b/packages/wildos-branding/debian/controlindex d1ceadb..1df786e 100644--- a/packages/wildos-branding/debian/control+++ b/packages/wildos-branding/debian/control@@ -16,6 +16,7 @@ Depends:wildos-desktop-view,breeze,breeze-cursor-theme,+ sound-theme-freedesktop,plasma-workspace,kded6,libnotify-bin,@@ -53,6 +54,8 @@ Depends:qml6-module-org-kde-bluezqt,qml6-module-org-kde-kitemmodels,qml6-module-org-kde-plasma-plasma5support,+ qml6-module-org-kde-pipewire,+ procps,libkf6config-bin,dbus-bin,kde-cli-tools,diff --git a/packages/wildos-branding/debian/install b/packages/wildos-branding/debian/installindex b686eeb..94162e9 100644--- a/packages/wildos-branding/debian/install+++ b/packages/wildos-branding/debian/install@@ -2,6 +2,7 @@ files/look-and-feel/* usr/share/plasma/look-and-feel/org.wildos.desktop/files/*.colors usr/share/color-schemes/files/xdg/* etc/xdg/files/desktoptheme/* usr/share/plasma/desktoptheme/wildos/+files/themes/*.json usr/share/wildos/themes/files/plasmoids/* usr/share/plasma/plasmoids/files/libexec/* usr/libexec/wildos/files/plymouth/wildos/* usr/share/plymouth/themes/wildos/@@ -22,3 +23,4 @@ files/skel/.config etc/skel/files/polkit/* usr/share/polkit-1/actions/files/grub/45_wildos_theme.cfg etc/default/grub.d/files/pam-configs/* usr/share/pam-configs/+files/sounds/wildos usr/share/sounds/diff --git a/packages/wildos-branding/debian/links b/packages/wildos-branding/debian/linksnew file mode 100644index 0000000..d97cf8c--- /dev/null+++ b/packages/wildos-branding/debian/links@@ -0,0 +1,6 @@+usr/share/sounds/wildos/stereo/bell.oga usr/share/sounds/wildos/stereo/bell-window-system.oga+usr/share/sounds/wildos/stereo/complete.oga usr/share/sounds/wildos/stereo/completion-success.oga+usr/share/sounds/wildos/stereo/dialog-error.oga usr/share/sounds/wildos/stereo/dialog-error-serious.oga+usr/share/sounds/wildos/stereo/dialog-question.oga usr/share/sounds/wildos/stereo/dialog-warning-auth.oga+usr/share/sounds/wildos/stereo/message.oga usr/share/sounds/wildos/stereo/message-new-email.oga+usr/share/sounds/wildos/stereo/screen-capture.oga usr/share/sounds/wildos/stereo/camera-shutter.ogadiff --git a/packages/wildos-branding/debian/postinst b/packages/wildos-branding/debian/postinstindex cd06bb1..4483e78 100644--- a/packages/wildos-branding/debian/postinst+++ b/packages/wildos-branding/debian/postinst@@ -38,6 +38,12 @@ if [ "$1" = "configure" ]; thenecho 'RestoreControllerDeviceState=true' >> "$conf"fifi+ # That setting did not do it (see usb-release). A computer where USB+ # protection was turned off before this fix is still holding every new+ # device back, so it is let go now rather than at the next restart.+ if [ -d /run/systemd/system ] && ! systemctl is-active --quiet usbguard.service; then+ /usr/libexec/wildos/usb-release || true+ fi# The sign-in screen picks up the last person's accessibility choices# through a PAM session step (see /usr/libexec/wildos/greeter-access);diff --git a/packages/wildos-branding/debian/rules b/packages/wildos-branding/debian/rulesindex 3d158d7..d10ba7e 100644--- a/packages/wildos-branding/debian/rules+++ b/packages/wildos-branding/debian/rules@@ -19,6 +19,11 @@ execute_after_dh_install:magick $(SRC_WALL) -resize 600x375^ -gravity center -extent 600x375 \-quality 85 $(WALL)/contents/screenshot.jpginstall -Dm644 files/wallpaper-metadata.json $(WALL)/metadata.json+ # The themes' photos, one package each, from the 5K masters in+ # branding/wallpaper/photos (see the tool and photos.json).+ python3 tools/wallpapers.py branding debian/wildos-branding/usr/share/wallpapers+ # A Plasma style per theme glass, for Start, the flyouts and tooltips.+ python3 tools/theme-variants.py files/desktoptheme files/themes debian/wildos-branding/usr/share/plasma/desktoptheme# The default account picture is a square of the same photo centred on# the island, so it stays a proper picture when cropped to a circle.# The offsets are the island's place in misty-lake.jpg (7792x5197).diff --git a/packages/wildos-branding/files/kwin/effects/org.wildos.snap/contents/config/main.xml b/packages/wildos-branding/files/kwin/effects/org.wildos.snap/contents/config/main.xmlindex e79122a..9305e5f 100644--- a/packages/wildos-branding/files/kwin/effects/org.wildos.snap/contents/config/main.xml+++ b/packages/wildos-branding/files/kwin/effects/org.wildos.snap/contents/config/main.xml@@ -27,5 +27,11 @@<entry name="ButtonMarginTopMaximized" type="Int"><default>0</default></entry><!-- Aurorae's ButtonSize factor (auroraerc), needed only below 1.0, where it does not change the title bar height. --><entry name="ButtonSizeFactor" type="Double"><default>1.0</default></entry>+ <!--+ Written by Settings > System > Multitasking. The effect stays loaded+ while either is on, so snap assist works without the layout picker.+ -->+ <entry name="ShowLayouts" type="Bool"><default>true</default></entry>+ <entry name="SnapAssist" type="Bool"><default>true</default></entry></group></kcfg>diff --git a/packages/wildos-branding/files/kwin/effects/org.wildos.snap/contents/ui/AssistCard.qml b/packages/wildos-branding/files/kwin/effects/org.wildos.snap/contents/ui/AssistCard.qmlnew file mode 100644index 0000000..8815739--- /dev/null+++ b/packages/wildos-branding/files/kwin/effects/org.wildos.snap/contents/ui/AssistCard.qml@@ -0,0 +1,146 @@+import QtQuick+import QtQuick.Effects+import org.kde.kwin as KWin+import org.kde.kirigami as Kirigami+import WildOS.UI as UI++// One window snap assist offers: icon and title above a live preview, drawn+// as the Alt+Tab switcher draws its windows so the two read as one family.+// The selected window wears the accent ring and a soft accent fill.+Item {+ id: card++ property var window: null+ property bool selected: false+ property int wellHeight: 150+ readonly property bool hovered: mouse.containsMouse++ signal activated()++ height: wellHeight + 52++ Accessible.role: Accessible.Button+ Accessible.name: window ? window.caption : ""+ Accessible.selected: selected+ Accessible.onPressAction: card.activated()++ Rectangle {+ anchors.fill: parent+ radius: UI.Style.radiusLg+ color: card.selected ? UI.Style.accentSoft+ : card.hovered ? UI.Style.surfaceHover+ : "transparent"+ border.width: 2+ border.color: card.selected ? UI.Style.accent : "transparent"++ Behavior on color {+ enabled: !card.selected+ ColorAnimation { duration: UI.Style.hoverDuration }+ }+ }++ MouseArea {+ id: mouse+ anchors.fill: parent+ hoverEnabled: true+ onClicked: card.activated()+ }++ Row {+ id: header++ x: 12+ y: 12+ width: parent.width - 24+ height: 18+ spacing: 8++ Kirigami.Icon {+ id: appIcon+ width: 18+ height: 18+ anchors.verticalCenter: parent.verticalCenter+ source: card.window ? card.window.icon : ""+ }++ UI.Label {+ width: header.width - appIcon.width - header.spacing+ anchors.verticalCenter: parent.verticalCenter+ text: card.window ? card.window.caption : ""+ font.weight: Font.Medium+ }+ }++ Rectangle {+ id: well++ x: 12+ y: header.y + header.height + 10+ width: parent.width - 24+ height: card.wellHeight+ radius: 10+ color: UI.Style.glassWindow++ // Stands in for the preview when there is none: windows KWin cannot+ // preview, and software rendering (virtual machines without 3D),+ // where KWin draws no thumbnails at all.+ Kirigami.Icon {+ anchors.centerIn: parent+ width: 48+ height: 48+ source: card.window ? card.window.icon : ""+ visible: thumbnail.implicitWidth <= 0 || GraphicsInfo.api === GraphicsInfo.Software+ }++ Item {+ id: preview++ anchors.fill: parent+ anchors.margins: 1+ visible: false+ clip: true+ layer.enabled: true++ // The whole window scaled down to fit the well and centred, never+ // cropped.+ KWin.WindowThumbnail {+ id: thumbnail++ readonly property real fitScale: implicitWidth > 0 && implicitHeight > 0+ ? Math.min(preview.width / implicitWidth, preview.height / implicitHeight)+ : 1++ wId: card.window ? card.window.internalId : ""+ width: implicitWidth > 0 ? Math.floor(implicitWidth * fitScale) : preview.width+ height: implicitHeight > 0 ? Math.floor(implicitHeight * fitScale) : preview.height+ x: Math.round((preview.width - width) / 2)+ y: Math.round((preview.height - height) / 2)+ }+ }++ Rectangle {+ id: previewMask+ anchors.fill: preview+ radius: well.radius - 1+ visible: false+ layer.enabled: true+ }++ MultiEffect {+ anchors.fill: preview+ source: preview+ maskEnabled: true+ maskSource: previewMask+ maskThresholdMin: 0.5+ maskSpreadAtMin: 1.0+ }++ Rectangle {+ anchors.fill: parent+ radius: well.radius+ color: "transparent"+ border.width: 1+ border.color: UI.Style.borderGlass+ }+ }+}diff --git a/packages/wildos-branding/files/kwin/effects/org.wildos.snap/contents/ui/AssistLayer.qml b/packages/wildos-branding/files/kwin/effects/org.wildos.snap/contents/ui/AssistLayer.qmlnew file mode 100644index 0000000..fcb4f56--- /dev/null+++ b/packages/wildos-branding/files/kwin/effects/org.wildos.snap/contents/ui/AssistLayer.qml@@ -0,0 +1,177 @@+pragma ComponentBehavior: Bound++import QtQuick+import WildOS.UI as UI++import "layouts.js" as Layouts++// Snap assist on the screen it belongs to: the zone being filled holds the+// menu glass with the other windows to choose from, and the zones after it+// wait in the accent tint the drag preview uses. Presses on the glass stay+// here; presses anywhere else reach the scene and close assist.+Item {+ id: layer++ required property var owner+ required property var screen++ readonly property rect area: owner.areaFor(screen)+ readonly property var layout: owner.assistLayout >= 0 ? Layouts.layouts[owner.assistLayout] : null+ readonly property int zone: owner.assistZones.length > 0 ? owner.assistZones[0] : -1++ // A zone's preview rectangle in this layer's coordinates.+ function zoneBox(zoneIndex: int): rect {+ if (!layout || zoneIndex < 0 || !screen) {+ return Qt.rect(0, 0, 0, 0);+ }+ const r = owner.previewRect(layout.zones[zoneIndex], area);+ const g = screen.geometry;+ return Qt.rect(r.x - g.x, r.y - g.y, r.width, r.height);+ }++ Repeater {+ model: layer.owner.assistZones.slice(1)++ delegate: Rectangle {+ required property int modelData+ readonly property rect box: layer.zoneBox(modelData)++ x: box.x+ y: box.y+ width: box.width+ height: box.height+ radius: UI.Style.windowRadius+ color: UI.Style.accentAlpha(0.16, 0.12)+ border.width: 2+ border.color: UI.Style.accentAlpha(0.70, 0.60)+ }+ }++ UI.Glass {+ id: panel++ readonly property rect box: layer.zoneBox(layer.zone)+ readonly property int padding: 18+ readonly property int gap: 12+ // A card is its preview well, wellRatio as tall as it is wide, plus+ // cardChrome for the title row and the space around it.+ readonly property real wellRatio: 0.6+ readonly property int cardChrome: 52++ visible: layer.zone >= 0+ level: "menu"+ x: box.x+ y: box.y+ width: box.width+ height: box.height++ Accessible.role: Accessible.List+ Accessible.name: title.text++ opacity: 0+ scale: 0.97+ Component.onCompleted: {+ opacity = 1;+ scale = 1;+ }++ Behavior on opacity {+ NumberAnimation { duration: 140; easing.type: Easing.OutCubic }+ }+ Behavior on scale {+ NumberAnimation { duration: 140; easing.type: Easing.OutCubic }+ }++ MouseArea {+ anchors.fill: parent+ }++ UI.Label {+ id: title++ x: panel.padding+ y: panel.padding+ width: panel.width - panel.padding * 2+ text: layer.layout && layer.zone >= 0+ ? "Fill the " + layer.layout.labels[layer.zone].toLowerCase()+ : ""+ size: 12+ font.weight: Font.DemiBold+ color: UI.Style.inkStatus+ }++ UI.Label {+ id: hint++ x: panel.padding+ y: panel.height - panel.padding - height+ width: panel.width - panel.padding * 2+ text: "Pick a window, or press Esc to leave the rest empty."+ size: 12+ wrapMode: Text.Wrap+ color: UI.Style.inkMuted+ }++ Flickable {+ id: scroller++ // The card width that fits every window into the zone at the+ // largest size, capped so two windows do not fill a whole half.+ // Ties go to more columns, which reads as a grid, not a list.+ readonly property var fit: {+ const n = Math.max(1, layer.owner.assistWindows.length);+ let best = { columns: 1, width: 0 };+ for (let c = 1; c <= n; ++c) {+ const rows = Math.ceil(n / c);+ const byWidth = (width - (c - 1) * panel.gap) / c;+ const byHeight = ((height - (rows - 1) * panel.gap) / rows - panel.cardChrome) / panel.wellRatio;+ const w = Math.min(byWidth, byHeight, 280);+ if (w >= best.width) {+ best = { columns: c, width: w };+ }+ }+ best.width = Math.floor(Math.max(best.width, 120));+ return best;+ }++ x: panel.padding+ y: title.y + title.height + 12+ width: panel.width - panel.padding * 2+ height: hint.y - 12 - y+ clip: true+ contentWidth: width+ contentHeight: Math.max(height, grid.height)+ boundsBehavior: Flickable.StopAtBounds+ interactive: grid.height > height++ Grid {+ id: grid++ x: Math.max(0, Math.round((scroller.width - width) / 2))+ y: Math.max(0, Math.round((scroller.height - height) / 2))+ columns: scroller.fit.columns+ spacing: panel.gap++ Repeater {+ model: layer.owner.assistWindows++ delegate: AssistCard {+ required property var modelData+ required property int index++ width: scroller.fit.width+ wellHeight: Math.round(width * panel.wellRatio)+ window: modelData+ selected: layer.owner.assistIndex === index+ onHoveredChanged: {+ if (hovered) {+ layer.owner.assistIndex = index;+ }+ }+ onActivated: layer.owner.assistChoose(modelData)+ }+ }+ }+ }+ }+}diff --git a/packages/wildos-branding/files/kwin/effects/org.wildos.snap/contents/ui/PickerScene.qml b/packages/wildos-branding/files/kwin/effects/org.wildos.snap/contents/ui/PickerScene.qmlindex acc27f3..e350c89 100644--- a/packages/wildos-branding/files/kwin/effects/org.wildos.snap/contents/ui/PickerScene.qml+++ b/packages/wildos-branding/files/kwin/effects/org.wildos.snap/contents/ui/PickerScene.qml@@ -4,11 +4,12 @@ import WildOS.UI as UIimport "layouts.js" as Layouts-// What one screen shows while Meta+Z is open. A KWin scene effect draws-// instead of the desktop, so the desktop is redrawn here from live window-// previews (the way KWin's own tile editor does it), lightly dimmed, with the-// picker's panel under the target window's maximise button. Running as an-// effect is what gives the picker the keyboard; KWin scripts cannot have it.+// What one screen shows while Meta+Z or snap assist is open. A KWin scene+// effect draws instead of the desktop, so the desktop is redrawn here from+// live window previews (the way KWin's own tile editor does it), lightly+// dimmed, with the picker's panel under the target window's maximise button,+// or snap assist's window choice over the empty zones. Running as an effect+// is what gives them the keyboard; KWin scripts cannot have it.FocusScope {id: scene@@ -16,6 +17,7 @@ FocusScope {readonly property var screen: KWin.SceneView.screenreadonly property var target: owner.targetreadonly property bool hasTarget: target !== null && target.output === screen+ readonly property bool assisting: owner.mode === "assist"// Worked out once: the window cannot move while the overlay is up, and// the title bar geometry it is derived from has no change signal.property rect anchorRect: Qt.rect(0, 0, 0, 0)@@ -23,6 +25,36 @@ FocusScope {focus: trueKeys.onPressed: event => {+ // Keys reach the scene on the screen KWin gives them to, which need+ // not be the one showing assist, so its state lives in the effect.+ if (scene.assisting) {+ switch (event.key) {+ case Qt.Key_Escape:+ scene.owner.close();+ break;+ case Qt.Key_Left:+ case Qt.Key_Up:+ case Qt.Key_Backtab:+ scene.owner.assistMove(-1);+ break;+ case Qt.Key_Right:+ case Qt.Key_Down:+ case Qt.Key_Tab:+ scene.owner.assistMove(1);+ break;+ case Qt.Key_Return:+ case Qt.Key_Enter:+ case Qt.Key_Space:+ if (scene.owner.assistIndex >= 0) {+ scene.owner.assistChoose(scene.owner.assistWindows[scene.owner.assistIndex]);+ }+ break;+ default:+ return;+ }+ event.accepted = true;+ return;+ }if (!scene.hasTarget) {if (event.key === Qt.Key_Escape) {scene.owner.close();@@ -133,7 +165,7 @@ FocusScope {readonly property rect area: scene.owner.areaFor(scene.screen)- visible: scene.hasTarget+ visible: scene.hasTarget && !scene.assistinghint: "Use the arrow keys to pick a zone, then press Enter."// Centred under the maximise button when there is one, otherwise@@ -169,6 +201,13 @@ FocusScope {}}+ AssistLayer {+ anchors.fill: parent+ visible: scene.assisting && scene.owner.assistOutput === scene.screen+ owner: scene.owner+ screen: scene.screen+ }+Connections {target: panel.gridfunction onZoneChosen(layoutIndex: int, zoneIndex: int): void {diff --git a/packages/wildos-branding/files/kwin/effects/org.wildos.snap/contents/ui/main.qml b/packages/wildos-branding/files/kwin/effects/org.wildos.snap/contents/ui/main.qmlindex 80b7ac5..11faf46 100644--- a/packages/wildos-branding/files/kwin/effects/org.wildos.snap/contents/ui/main.qml+++ b/packages/wildos-branding/files/kwin/effects/org.wildos.snap/contents/ui/main.qml@@ -1,4 +1,5 @@import QtQuick+import QtQml.Modelsimport org.kde.kwin as KWinimport "layouts.js" as Layouts@@ -15,6 +16,11 @@ import "layouts.js" as Layouts// This is a scene effect rather than a KWin script because only effects can// take the keyboard, which Meta+Z needs. The hover and drag pickers are// ordinary flyout windows owned by the same effect.+//+// Snap assist, as in Windows: once a window lands in a zone, by any of those+// or by KWin's own quick tiling (edge drag, Meta+arrow, the window menu), the+// other zones of its layout offer the remaining windows, one zone at a time.+// It shares the scene with Meta+Z; `mode` says which one the scene shows.KWin.SceneEffect {id: effect@@ -22,6 +28,18 @@ KWin.SceneEffect {// which leaves out the taskbar.readonly property int maximizeArea: 2+ // "layouts" for Meta+Z, "assist" for snap assist.+ property string mode: "layouts"++ readonly property bool showLayouts: effect.configuration.ShowLayouts !== false+ readonly property bool assistEnabled: effect.configuration.SnapAssist !== false++ onShowLayoutsChanged: {+ if (!showLayouts) {+ hideFlyout();+ }+ }+property var target: null// KWin creates one per screen, outside this file's context, so the@@ -79,6 +97,18 @@ KWin.SceneEffect {}function snap(window: var, layoutIndex: int, zoneIndex: int, output: var): void {+ if (!eligible(window) || layoutIndex < 0 || zoneIndex < 0) {+ return;+ }+ const screen = output ?? window.output;+ // Halves and quarters go through quick tiling, whose tile change+ // would offer assist a second time.+ quietTimer.restart();+ placeWindow(window, layoutIndex, zoneIndex, screen);+ offerAssist(window, layoutIndex, zoneIndex, screen);+ }++ function placeWindow(window: var, layoutIndex: int, zoneIndex: int, output: var): void {if (!eligible(window) || layoutIndex < 0 || zoneIndex < 0) {return;}@@ -110,17 +140,32 @@ KWin.SceneEffect {function open(): void {const window = KWin.Workspace.activeWindow;- if (!eligible(window)) {+ if (!showLayouts || !eligible(window)) {return;}hideFlyout();+ // Clears an assist waiting between zones.+ close();target = window;visible = true;}function close(): void {+ const assisting = mode === "assist";visible = false;+ resumeTimer.stop();target = null;+ mode = "layouts";+ assistOutput = null;+ assistLayout = -1;+ assistZones = [];+ assistWindows = [];+ assistIndex = -1;+ // The windows assist just placed report their new tiles late on+ // Wayland, and must not start it again.+ if (assisting) {+ quietTimer.restart();+ }}function choose(layoutIndex: int, zoneIndex: int): void {@@ -136,6 +181,177 @@ KWin.SceneEffect {onActivated: effect.visible ? effect.close() : effect.open()}+ // Snap assist++ property var assistOutput: null+ property int assistLayout: -1+ // Zone indices still to fill, the one on offer first.+ property var assistZones: []+ // Windows on offer, most recently used first.+ property var assistWindows: []+ property int assistIndex: -1+ property var pendingAssist: null++ function onCurrentDesktop(window: var): bool {+ const desktop = KWin.Workspace.currentDesktop;+ const activity = KWin.Workspace.currentActivity;+ return (window.onAllDesktops || window.desktops.includes(desktop))+ && (window.activities.length === 0 || window.activities.includes(activity));+ }++ // Normal windows on the screen and desktop that could fill a zone,+ // minimised ones included, as Windows offers them.+ function assistCandidates(output: var, exclude: var): var {+ return KWin.Workspace.stackingOrder.filter(w => !w.deleted+ && w.normalWindow && !w.specialWindow && !w.skipTaskbar+ && w.moveable && w.resizeable && !w.fullScreen+ && w.output === output && onCurrentDesktop(w)+ && !exclude.includes(w)).reverse();+ }++ // A zone another window already fills needs no suggestion: one that+ // fills it exactly, or a tiled one that covers it, such as a half under+ // the quarter just snapped beside it.+ function zoneTaken(rect: rect, output: var, ignore: var): bool {+ const covers = f => f.x <= rect.x + 2 && f.y <= rect.y + 2+ && f.x + f.width >= rect.x + rect.width - 2 && f.y + f.height >= rect.y + rect.height - 2;+ return KWin.Workspace.stackingOrder.some(w => w !== ignore && !w.deleted+ && w.normalWindow && !w.minimized && w.output === output && onCurrentDesktop(w)+ && (Layouts.sameRect(w.frameGeometry, rect) || (w.tile && covers(w.frameGeometry))));+ }++ function offerAssist(window: var, layoutIndex: int, zoneIndex: int, output: var): void {+ if (!assistEnabled || visible) {+ return;+ }+ pendingAssist = { window: window, layout: layoutIndex, zone: zoneIndex, output: output };+ assistTimer.restart();+ }++ function startAssist(): void {+ const p = pendingAssist;+ pendingAssist = null;+ if (p === null || visible || !assistEnabled || !eligible(p.window) || p.window.output !== p.output) {+ return;+ }+ const area = areaFor(p.output);+ const zones = Layouts.layouts[p.layout].zones;+ const empty = [];+ for (let z = 0; z < zones.length; ++z) {+ if (z !== p.zone && !zoneTaken(Layouts.zoneRect(zones[z], area), p.output, p.window)) {+ empty.push(z);+ }+ }+ const windows = assistCandidates(p.output, [p.window]);+ if (empty.length === 0 || windows.length === 0) {+ return;+ }+ hideFlyout();+ target = null;+ assistOutput = p.output;+ assistLayout = p.layout;+ assistZones = empty;+ assistWindows = windows;+ assistIndex = 0;+ mode = "assist";+ visible = true;+ }++ function assistChoose(window: var): void {+ if (mode !== "assist" || assistZones.length === 0 || !assistWindows.includes(window)) {+ return;+ }+ const zone = assistZones[0];+ quietTimer.restart();+ if (window.minimized) {+ window.minimized = false;+ }+ placeWindow(window, assistLayout, zone, assistOutput);+ const rest = assistZones.slice(1);+ const windows = assistWindows.filter(w => w !== window);+ if (rest.length === 0 || windows.length === 0) {+ close();+ return;+ }+ assistZones = rest;+ assistWindows = windows;+ assistIndex = 0;+ // The scene steps aside while the window takes its place, so the+ // real desktop shows it landing, then comes back for the next zone.+ // Kept up instead, the scene stopped redrawing cleanly once a window+ // under it was resized.+ visible = false;+ resumeTimer.restart();+ }++ function assistMove(step: int): void {+ const count = assistWindows.length;+ if (count > 0) {+ assistIndex = assistIndex < 0 ? 0 : (assistIndex + step + count) % count;+ }+ }++ // KWin's own quick tiling (edge drag, Meta+arrow, the window menu) tells+ // effects nothing but the window's new tile. A tile that matches a zone+ // of one of the layouts counts as snapping into that zone.+ function tileChangedFor(window: var): void {+ if (quietTimer.running || visible || !assistEnabled) {+ return;+ }+ const tile = window ? window.tile : null;+ if (!tile || !eligible(window)) {+ return;+ }+ const r = tile.relativeGeometry;+ const near = (a, b) => Math.abs(a - b) < 0.01;+ for (let l = 0; l < Layouts.layouts.length; ++l) {+ const zones = Layouts.layouts[l].zones;+ for (let z = 0; z < zones.length; ++z) {+ const zone = zones[z];+ if (near(r.x, zone[0]) && near(r.y, zone[1]) && near(r.width, zone[2]) && near(r.height, zone[3])) {+ offerAssist(window, l, z, window.output);+ return;+ }+ }+ }+ }++ // Long enough for a drag's flyout and KWin's own snap outline to go and+ // for a Wayland window to take its new size before the scene redraws it.+ Timer {+ id: assistTimer+ interval: 200+ onTriggered: effect.startAssist()+ }++ Timer {+ id: quietTimer+ interval: 800+ }++ Timer {+ id: resumeTimer+ interval: 250+ onTriggered: {+ if (effect.mode === "assist" && effect.assistZones.length > 0 && effect.assistWindows.length > 0) {+ effect.visible = true;+ }+ }+ }++ Instantiator {+ model: KWin.WindowModel {}++ delegate: Connections {+ id: watch+ target: model.window++ function onTileChanged(): void {+ effect.tileChangedFor(watch.target);+ }+ }+ }+// Hover and dragproperty var dragWindow: null@@ -285,7 +501,7 @@ KWin.SceneEffect {target: KWin.Workspacefunction onCursorPosChanged(): void {- if (effect.visible) {+ if (effect.visible || !effect.showLayouts) {return;}const p = KWin.Workspace.cursorPos;@@ -315,6 +531,13 @@ KWin.SceneEffect {if (window === effect.target) {effect.close();}+ if (effect.mode === "assist" && effect.assistWindows.includes(window)) {+ effect.assistWindows = effect.assistWindows.filter(w => w !== window);+ effect.assistIndex = Math.min(effect.assistIndex, effect.assistWindows.length - 1);+ if (effect.assistWindows.length === 0) {+ effect.close();+ }+ }}function onWindowActivated(): void {@@ -323,6 +546,13 @@ KWin.SceneEffect {}}+ // Assist offers the windows of one desktop; another desktop has others.+ function onCurrentDesktopChanged(): void {+ if (effect.mode === "assist") {+ effect.close();+ }+ }+function onScreensChanged(): void {effect.seedTiles();}diff --git a/packages/wildos-branding/files/kwin/effects/org.wildos.snap/metadata.json b/packages/wildos-branding/files/kwin/effects/org.wildos.snap/metadata.jsonindex a7d780b..aebf44b 100644--- a/packages/wildos-branding/files/kwin/effects/org.wildos.snap/metadata.json+++ b/packages/wildos-branding/files/kwin/effects/org.wildos.snap/metadata.json@@ -8,7 +8,7 @@}],"Category": "Window Management",- "Description": "Pick a layout and a zone to snap a window into: hover the maximise button, drag a window to the top of the screen or press Meta+Z",+ "Description": "Pick a layout and a zone to snap a window into: hover the maximise button, drag a window to the top of the screen or press Meta+Z. Once a window is snapped, other windows are offered for the rest of the layout","EnabledByDefault": true,"Id": "org.wildos.snap","License": "GPL-3.0-or-later",diff --git a/packages/wildos-branding/files/libexec/security-status b/packages/wildos-branding/files/libexec/security-statusindex b78a721..cf34785 100644--- a/packages/wildos-branding/files/libexec/security-status+++ b/packages/wildos-branding/files/libexec/security-status@@ -36,9 +36,39 @@# people; for diagnostics and Settings.# kernel=on|off Kicksecure's kernel hardening is in force. Not# shown to people; for diagnostics and Settings.+# ignored=a,b Warnings this person chose to ignore (see below).+#+# Some warnings describe a choice a person can reasonably make and live with:+# Secure Boot off (turning it on after installing can stop some computers+# starting), a disk installed without encryption, USB or app protection off.+#+# security-status ignore KEY stop warning about KEY for this person+# security-status unignore KEY warn about it again+#+# Only encryption, apps, devices and secureboot can be ignored. Security+# updates never can. The list lives in ~/.config/wildos/security-ignored.export LC_ALL=C+ignored_file="${XDG_CONFIG_HOME:-$HOME/.config}/wildos/security-ignored"+case "${1:-}" in+ ignore | unignore)+ case "${2:-}" in+ encryption | apps | devices | secureboot) ;;+ *) echo "security-status: $1 takes encryption, apps, devices or secureboot" >&2; exit 2 ;;+ esac+ mkdir -p "$(dirname "$ignored_file")"+ touch "$ignored_file"+ others=$(grep -vx "$2" "$ignored_file" || true)+ {+ [ -n "$others" ] && printf '%s\n' "$others"+ [ "$1" = ignore ] && printf '%s\n' "$2"+ } > "$ignored_file.new"+ mv "$ignored_file.new" "$ignored_file"+ exit 0+ ;;+esac+# A service that is still starting counts as on: at login some are a few# seconds behind, and that is not a reason to warn anyone.service() {@@ -210,3 +240,6 @@ if [ "$(cat /proc/sys/kernel/kptr_restrict 2>/dev/null)" = "2" ]; thenelseecho "kernel=off"fi++# Only known keys, so a hand-edited file can't hide anything else.+echo "ignored=$(grep -xE 'encryption|apps|devices|secureboot' "$ignored_file" 2>/dev/null | sort -u | paste -sd, -)"diff --git a/packages/wildos-branding/files/libexec/taskbar-items b/packages/wildos-branding/files/libexec/taskbar-itemsnew file mode 100644index 0000000..681c783--- /dev/null+++ b/packages/wildos-branding/files/libexec/taskbar-items@@ -0,0 +1,30 @@+#!/bin/sh+# Brings a taskbar made before an update up to date, each change once per+# account, from the session's autostart. It waits for the shell to be up+# and its bar laid out, because changing a locked bar while Plasma is still+# starting leaves it undrawn.++set -u++state=${XDG_STATE_HOME:-$HOME/.local/state}/wildos+# Each change: its marker and its script.+pending=""+for change in winmode-added:taskbar-winmode.js winmode-left:taskbar-winmode-left.js; do+ [ -e "$state/taskbar-${change%%:*}" ] || pending="$pending $change"+done+[ -n "$pending" ] || exit 0++i=0+until busctl --user status org.kde.plasmashell >/dev/null 2>&1; do+ i=$((i + 1))+ [ "$i" -ge 120 ] && exit 0+ sleep 1+done+sleep 5++mkdir -p "$state" || exit 0+for change in $pending; do+ script=$(cat "/usr/libexec/wildos/${change#*:}") || continue+ busctl --user call org.kde.plasmashell /PlasmaShell org.kde.PlasmaShell evaluateScript s "$script" >/dev/null 2>&1 || continue+ : > "$state/taskbar-${change%%:*}"+donediff --git a/packages/wildos-branding/files/libexec/taskbar-winmode-left.js b/packages/wildos-branding/files/libexec/taskbar-winmode-left.jsnew file mode 100644index 0000000..6c2cad7--- /dev/null+++ b/packages/wildos-branding/files/libexec/taskbar-winmode-left.js@@ -0,0 +1,27 @@+// Moves Windows mode's status to the left end of a floating bar, where it+// went just before Start until 2026-11-09. Same steps as Settings' own+// placement (wildos-settings system.cpp): off, then back on the bar's+// first pixel, which a panel takes to mean "before everything".+panels().forEach(function (p) {+ var all = p.widgets();+ all.sort(function (a, b) { return a.geometry.x - b.geometry.x; });+ var w = -1;+ for (var i = 0; i < all.length; i++) {+ if (all[i].type === "org.wildos.winmode") {+ w = i;+ }+ }+ if (w <= 0) {+ return;+ }+ var locked = p.locked;+ p.locked = false;+ all[w].remove();+ var item = p.addWidget("org.wildos.winmode", 0, 0, -1, -1);+ if (item) {+ item.currentConfigGroup = [];+ item.writeConfig("immutability", 2);+ item.locked = true;+ }+ p.locked = locked;+});diff --git a/packages/wildos-branding/files/libexec/taskbar-winmode.js b/packages/wildos-branding/files/libexec/taskbar-winmode.jsnew file mode 100644index 0000000..f6ccba6--- /dev/null+++ b/packages/wildos-branding/files/libexec/taskbar-winmode.js@@ -0,0 +1,24 @@+// Puts Windows mode's status on a taskbar made before it existed (boards+// 4.13 and 4.14), at the left end of the bar in either style. New accounts get it from the Wild OS layout, and a+// taskbar that has it already is left alone. taskbar-items runs this once+// per account, on a running shell: from a Plasma update script, which runs+// while the shell is starting, unlocking the bar left it undrawn until the+// next sign-in.+panels().forEach(function (p) {+ if (p.widgets("org.wildos.tasks").length === 0 || p.widgets("org.wildos.winmode").length > 0) {+ return;+ }+ // The layout locks the bar, and Plasma adds nothing to a locked one.+ var locked = p.locked;+ p.locked = false;+ // Dropped on the bar's first pixel, a panel puts it before everything.+ var item = p.addWidget("org.wildos.winmode", 0, 0, -1, -1);+ if (item) {+ // Locked like the rest of the bar (see the layout), so it can't be+ // removed or moved by accident.+ item.currentConfigGroup = [];+ item.writeConfig("immutability", 2);+ item.locked = true;+ }+ p.locked = locked;+});diff --git a/packages/wildos-branding/files/libexec/usb-release b/packages/wildos-branding/files/libexec/usb-releasenew file mode 100644index 0000000..abb2380--- /dev/null+++ b/packages/wildos-branding/files/libexec/usb-release@@ -0,0 +1,22 @@+#!/bin/sh+# Runs as root each time USBGuard stops (usbguard.service.d/wildos-release.conf).+# While USBGuard runs it holds every new device back by setting each USB+# controller's authorized_default to 0. USBGuard 1.1 leaves it at 0 when it+# stops, even with RestoreControllerDeviceState, so turning USB protection off+# in Settings blocked every device plugged in afterwards, with nothing left+# running to allow it. This gives the decision back to the kernel and lets+# the devices USBGuard was holding back work. On a restart USBGuard decides+# again for every device present as soon as it is back up.++export LC_ALL=C++for controller in /sys/bus/usb/devices/usb*; do+ [ -e "$controller/authorized_default" ] && echo 1 > "$controller/authorized_default"+done++# Interfaces (with a colon) follow their device.+for dev in /sys/bus/usb/devices/*; do+ case ${dev##*/} in *:*) continue ;; esac+ [ "$(cat "$dev/authorized" 2>/dev/null)" = "0" ] && echo 1 > "$dev/authorized"+done+exit 0diff --git a/packages/wildos-branding/files/look-and-feel/contents/layouts/org.kde.plasma.desktop-layout.js b/packages/wildos-branding/files/look-and-feel/contents/layouts/org.kde.plasma.desktop-layout.jsindex e54fdd5..4e82969 100644--- a/packages/wildos-branding/files/look-and-feel/contents/layouts/org.kde.plasma.desktop-layout.js+++ b/packages/wildos-branding/files/look-and-feel/contents/layouts/org.kde.plasma.desktop-layout.js@@ -1,6 +1,7 @@-// The Wild OS desktop: the taskbar docked along the bottom, Start and the-// apps centred on the screen, and the security chip, a divider, quick-// settings and the clock at the right end. Sizes follow the Taskbar artboard+// The Wild OS desktop: the taskbar docked along the bottom, Windows mode's+// status at the left end (it takes no room until Windows mode is set up),+// Start and the apps centred on the screen, and the security chip, a+// divider, quick settings and the clock at the right end. Sizes follow the Taskbar artboard// in the design. Settings > Personalisation can switch it to floating glass// pills instead.//@@ -35,6 +36,11 @@ bar.hiding = "none";// edge) make it 76.bar.height = 52;+// Where Windows 11 puts its weather. It keeps 8 px from the screen edge+// itself, so no spacer goes before it: Settings takes the leftmost spacer to+// be the one that centres the apps.+bar.addWidget("org.wildos.winmode");+// Two expanding spacers either side of the centre group let Plasma centre it// on the screen rather than in the space left of the tray.var leftSpacer = bar.addWidget("org.kde.plasma.panelspacer");@@ -57,6 +63,7 @@ tasks.currentConfigGroup = ["General"];tasks.writeConfig("launchers", ["applications:org.wildos.files.desktop","applications:brave-browser.desktop",+ "applications:org.wildos.mail.desktop","applications:org.wildos.store.desktop","applications:org.wildos.settings.desktop"]);diff --git a/packages/wildos-branding/files/look-and-feel/contents/lockscreen/components/LockClock.qml b/packages/wildos-branding/files/look-and-feel/contents/lockscreen/components/LockClock.qmlindex 69c91c4..2ce6592 100644--- a/packages/wildos-branding/files/look-and-feel/contents/lockscreen/components/LockClock.qml+++ b/packages/wildos-branding/files/look-and-feel/contents/lockscreen/components/LockClock.qml@@ -2,7 +2,8 @@ import QtQuickimport QtQuick.Effectsimport WildOS.UI as UI-// Day-first date over a large 24-hour time, as on the lock screen. The time+// The date over a large time, as on the lock screen, both in the regional+// format; the time leaves out AM and PM, as Windows does here. The time// box is exactly 136px tall like the design's line-height: 1, so the glyphs// are shifted up by half the font's extra leading.Item {@@ -10,6 +11,9 @@ Item {property date now: new Date()+ readonly property string dateFormat: Qt.locale().dateFormat(Locale.LongFormat).replace(/[,.\s]*y+[.年]?/, "").trim()+ .replace(/^dddd, d MMMM$/, "dddd d MMMM")+implicitWidth: Math.max(dateLabel.implicitWidth, timeLabel.implicitWidth)implicitHeight: dateLabel.height + 6 + timeBox.height@@ -35,7 +39,7 @@ Item {Text {id: dateLabelanchors.horizontalCenter: parent.horizontalCenter- text: Qt.locale().toString(clock.now, "dddd d MMMM")+ text: Qt.locale("en_GB").toString(clock.now, clock.dateFormat)font.family: UI.Style.fontFamilyfont.pixelSize: UI.Style.px(22)font.weight: Font.Normal@@ -54,7 +58,7 @@ Item {id: timeLabelanchors.horizontalCenter: parent.horizontalCentery: (136 - timeMetrics.height) / 2- text: Qt.formatTime(clock.now, "HH:mm")+ text: Qt.locale().toString(clock.now, Qt.locale().timeFormat(Locale.ShortFormat)).replace(Qt.locale().amText, "").replace(Qt.locale().pmText, "").trim()font.family: "Inter Display"renderType: Text.CurveRenderingfont.pixelSize: 136diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.clock/contents/ui/CalendarCard.qml b/packages/wildos-branding/files/plasmoids/org.wildos.clock/contents/ui/CalendarCard.qmlindex b2386cb..d1d7e58 100644--- a/packages/wildos-branding/files/plasmoids/org.wildos.clock/contents/ui/CalendarCard.qml+++ b/packages/wildos-branding/files/plasmoids/org.wildos.clock/contents/ui/CalendarCard.qml@@ -3,10 +3,12 @@ pragma ComponentBehavior: Boundimport QtQuickimport QtQuick.Layoutsimport WildOS.UI as UI+import "Formats.js" as Formats// The design's calendar card: today's date as the heading, the month shown-// beneath it with previous and next buttons, a Monday-first month grid with-// today in the accent, and a line along the foot about the day chosen.+// beneath it with previous and next buttons, a month grid that starts on the+// regional format's first day of the week with today in the accent, and a+// line along the foot about the day chosen.// Wild OS has no calendar of events, so choosing a day says how far away// it is, the question a calendar flyout mostly answers, rather than// claiming the day is free.@@ -26,12 +28,13 @@ ColumnLayout {}readonly property var locale: Qt.locale("en_GB")+ readonly property int firstDay: Formats.firstDayOfWeek()- // Six weeks from the Monday on or before the first, so the card keeps- // one height from month to month.+ // Six weeks from the first day of the week on or before the 1st, so the+ // card keeps one height from month to month.readonly property var days: {const first = new Date(year, month, 1);- const offset = (first.getDay() + 6) % 7;+ const offset = (first.getDay() - firstDay + 7) % 7;const list = [];for (let i = 0; i < 42; i++) {const day = new Date(year, month, 1 - offset + i);@@ -41,7 +44,7 @@ ColumnLayout {inMonth: day.getMonth() === month,isToday: day.getFullYear() === today.getFullYear() && day.getMonth() === today.getMonth()&& day.getDate() === today.getDate(),- label: locale.toString(day, "dddd d MMMM yyyy")+ label: Formats.longDate(day)});}return list;@@ -82,7 +85,7 @@ ColumnLayout {if (days === 0) {return "Today, week " + weekNumber(day);}- return locale.toString(day, "dddd d MMMM") + ", " + when.charAt(0).toLowerCase() + when.slice(1);+ return Formats.dayAndMonth(day) + ", " + when.charAt(0).toLowerCase() + when.slice(1);}spacing: 12@@ -97,7 +100,7 @@ ColumnLayout {UI.Label {Layout.fillWidth: true- text: card.locale.toString(card.today, "dddd d MMMM")+ text: Formats.dayAndMonth(card.today)size: 14font.weight: Font.DemiBoldAccessible.role: Accessible.Heading@@ -192,7 +195,7 @@ ColumnLayout {Accessible.name: card.locale.toString(new Date(card.year, card.month, 1), "MMMM yyyy")Repeater {- model: ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"]+ model: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"].map((_, i, names) => names[(i + card.firstDay) % 7])UI.Label {required property string modelDatadiff --git a/packages/wildos-branding/files/plasmoids/org.wildos.clock/contents/ui/ClockButton.qml b/packages/wildos-branding/files/plasmoids/org.wildos.clock/contents/ui/ClockButton.qmlindex c94716c..101e5a3 100644--- a/packages/wildos-branding/files/plasmoids/org.wildos.clock/contents/ui/ClockButton.qml+++ b/packages/wildos-branding/files/plasmoids/org.wildos.clock/contents/ui/ClockButton.qml@@ -1,6 +1,8 @@import QtQuickimport QtQuick.Layoutsimport WildOS.UI as UI+import org.wildos.shell as WildOS+import "Formats.js" as Formats// The clock button from the design's taskbar: the time over the date, right// aligned, in a 44 px tall button with 12 px padding. A small moon shows when@@ -58,14 +60,14 @@ MouseArea {UI.Label {id: timeLayout.alignment: Qt.AlignRight- text: Qt.formatTime(button.clock.now, "HH:mm")+ text: Formats.time(button.clock.now, WildOS.TaskbarStyle.clockSeconds)font.weight: Font.Mediumfont.features: { "tnum": 1 }}UI.Label {Layout.alignment: Qt.AlignRight- text: Qt.formatDate(button.clock.now, "dd/MM/yyyy")+ text: WildOS.TaskbarStyle.clockLongDate ? Formats.longDate(button.clock.now) : Formats.shortDate(button.clock.now)size: 12font.features: { "tnum": 1 }color: UI.Style.inkStatusdiff --git a/packages/wildos-branding/files/plasmoids/org.wildos.clock/contents/ui/Formats.js b/packages/wildos-branding/files/plasmoids/org.wildos.clock/contents/ui/Formats.jsnew file mode 100644index 0000000..df200a5--- /dev/null+++ b/packages/wildos-branding/files/plasmoids/org.wildos.clock/contents/ui/Formats.js@@ -0,0 +1,40 @@+// Dates and times in the regional format chosen in Settings > Language and+// region (LC_TIME, which Qt.locale() follows), with day and month names in+// English because the rest of Wild OS is in English.++function names() {+ return Qt.locale("en_GB");+}++function time(when, seconds) {+ let format = Qt.locale().timeFormat(Locale.ShortFormat);+ // The short format has no seconds; the long one adds a time zone, which+ // the taskbar has no room for, so seconds go in after the minutes.+ if (seconds && format.indexOf("s") < 0) {+ format = format.replace(/mm/, "mm:ss");+ }+ return Qt.locale().toString(when, format);+}++function shortDate(when) {+ return names().toString(when, Qt.locale().dateFormat(Locale.ShortFormat));+}++// Qt writes UK dates as "Monday, 9 November"; the design has no comma.+function longFormat() {+ return Qt.locale().dateFormat(Locale.LongFormat).replace(/^dddd, d MMMM/, "dddd d MMMM");+}++function longDate(when) {+ return names().toString(when, longFormat());+}++// The long date without its year: "Monday 9 November", "Monday, November 9".+function dayAndMonth(when) {+ return names().toString(when, longFormat().replace(/[,.\s]*y+[.年]?/, "").trim());+}++// 0 for Sunday to 6 for Saturday, as Date.getDay() numbers them.+function firstDayOfWeek() {+ return Qt.locale().firstDayOfWeek;+}diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.clock/contents/ui/JobProgress.qml b/packages/wildos-branding/files/plasmoids/org.wildos.clock/contents/ui/JobProgress.qmlindex fc9d5b2..2279faa 100644--- a/packages/wildos-branding/files/plasmoids/org.wildos.clock/contents/ui/JobProgress.qml+++ b/packages/wildos-branding/files/plasmoids/org.wildos.clock/contents/ui/JobProgress.qml@@ -99,7 +99,8 @@ ColumnLayout {unit++;}const decimals = value < 10 ? 1 : 0;- return Number(value.toFixed(decimals)).toString() + " " + units[unit];+ const rounded = Number(value.toFixed(decimals));+ return rounded.toLocaleString(Qt.locale(), "f", rounded % 1 === 0 ? 0 : decimals) + " " + units[unit];}function timeLeft(): string {@@ -144,7 +145,7 @@ ColumnLayout {// KIO names the job with one word ("Copying", "Moving"); the count// makes it the design's "Copying 214 items".if (totalItems > 1 && verb.indexOf(" ") < 0) {- return verb + " " + totalItems.toLocaleString(Qt.locale("en_GB"), "f", 0) + " items";+ return verb + " " + totalItems.toLocaleString(Qt.locale(), "f", 0) + " items";}return verb;}@@ -339,7 +340,7 @@ ColumnLayout {UI.Label {visible: job.totalItems > 0- text: "Items left: " + Math.max(0, job.totalItems - job.processedItems).toLocaleString(Qt.locale("en_GB"), "f", 0)+ text: "Items left: " + Math.max(0, job.totalItems - job.processedItems).toLocaleString(Qt.locale(), "f", 0)+ (job.bytesKnown ? " (" + job.size(Math.max(0, job.totalBytes - job.processedBytes)) + ")" : "")size: 12color: UI.Style.inkStatusdiff --git a/packages/wildos-branding/files/plasmoids/org.wildos.clock/contents/ui/NotificationItem.qml b/packages/wildos-branding/files/plasmoids/org.wildos.clock/contents/ui/NotificationItem.qmlindex 04a9a84..44c6f40 100644--- a/packages/wildos-branding/files/plasmoids/org.wildos.clock/contents/ui/NotificationItem.qml+++ b/packages/wildos-branding/files/plasmoids/org.wildos.clock/contents/ui/NotificationItem.qml@@ -5,6 +5,7 @@ import QtQuick.Layoutsimport org.kde.kirigami as Kirigamiimport org.kde.notificationmanager as NotificationManagerimport WildOS.UI as UI+import "Formats.js" as Formats// One notification as the design draws it: a 20 px icon, a 13 px semibold// title with the time on the right, a 12 px body, and any actions as a row of@@ -91,7 +92,7 @@ CardButton {if (hours < 24) {return hours + " hr";}- return hours < 48 ? "Yesterday" : Qt.formatDate(time, "dd/MM");+ return hours < 48 ? "Yesterday" : Formats.shortDate(time);}Rectangle {diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.clock/contents/ui/main.qml b/packages/wildos-branding/files/plasmoids/org.wildos.clock/contents/ui/main.qmlindex 08e60b7..8d30c9c 100644--- a/packages/wildos-branding/files/plasmoids/org.wildos.clock/contents/ui/main.qml+++ b/packages/wildos-branding/files/plasmoids/org.wildos.clock/contents/ui/main.qml@@ -5,6 +5,8 @@ import org.kde.plasma.plasmoidimport org.kde.plasma.core as PlasmaCoreimport org.kde.plasma.plasma5support as P5Supportimport org.kde.notificationmanager as NotificationManager+import org.wildos.shell as WildOS+import "Formats.js" as Formats// The clock at the end of the taskbar: 24-hour time over the date, opening// the design's notifications and calendar cards. With "showPopups" on it also@@ -19,8 +21,8 @@ PlasmoidItem {id: timeSourceengine: "time"connectedSources: ["Local"]- interval: 60000- intervalAlignment: P5Support.Types.AlignToMinute+ interval: WildOS.TaskbarStyle.clockSeconds ? 1000 : 60000+ intervalAlignment: WildOS.TaskbarStyle.clockSeconds ? P5Support.Types.NoAlignment : P5Support.Types.AlignToMinute}readonly property date now: timeSource.data.Local ? timeSource.data.Local.DateTime : new Date()@@ -160,7 +162,7 @@ PlasmoidItem {Plasmoid.backgroundHints: PlasmaCore.Types.NoBackgroundPlasmoid.icon: "preferences-system-time"Plasmoid.title: "Date, time and notifications"- toolTipMainText: Qt.locale("en_GB").toString(now, "dddd d MMMM yyyy")+ toolTipMainText: Formats.longDate(now)toolTipSubText: {const unread = history.unreadNotificationsCount;const lines = [];diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.protected/contents/ui/Flyout.qml b/packages/wildos-branding/files/plasmoids/org.wildos.protected/contents/ui/Flyout.qmlindex 1766e79..e1b82d9 100644--- a/packages/wildos-branding/files/plasmoids/org.wildos.protected/contents/ui/Flyout.qml+++ b/packages/wildos-branding/files/plasmoids/org.wildos.protected/contents/ui/Flyout.qml@@ -209,13 +209,26 @@ FocusScope {chevron: modelData.action.length === 0onClicked: flyout.open(modelData.run)- UI.Button {- visible: area.modelData.action.length > 0+ Row {anchors.verticalCenter: parent.verticalCenter- size: "small"- text: area.modelData.action- focusPolicy: Qt.NoFocus- onClicked: flyout.open(area.modelData.run)+ spacing: 6++ UI.Button {+ visible: area.modelData.ignorable === true+ size: "small"+ kind: "text"+ text: "Ignore"+ focusPolicy: Qt.NoFocus+ onClicked: flyout.open("ignore:" + area.modelData.id)+ }++ UI.Button {+ visible: area.modelData.action.length > 0+ size: "small"+ text: area.modelData.action+ focusPolicy: Qt.NoFocus+ onClicked: flyout.open(area.modelData.run)+ }}}}diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.protected/contents/ui/main.qml b/packages/wildos-branding/files/plasmoids/org.wildos.protected/contents/ui/main.qmlindex cad3131..76d1341 100644--- a/packages/wildos-branding/files/plasmoids/org.wildos.protected/contents/ui/main.qml+++ b/packages/wildos-branding/files/plasmoids/org.wildos.protected/contents/ui/main.qml@@ -121,6 +121,26 @@ PlasmoidItem {if (s.secureboot === "off") {row("secureboot", "chip", "Startup protection", "Secure Boot is off", "warn", "How to turn it on", "help:secure-boot");}++ // A warning the person chose to ignore stays listed but quiet, with+ // the way back; one they could ignore gets an Ignore button. Security+ // updates are never in either set.+ const ignored = String(s.ignored || "").split(",").filter(k => k.length > 0);+ const ignorable = ["encryption", "apps", "devices", "secureboot"];+ for (const area of list) {+ area.ignorable = false;+ if (area.tone !== "warn" || !ignorable.includes(area.id)) {+ continue;+ }+ if (ignored.includes(area.id)) {+ area.tone = "quiet";+ area.status += ". Ignored";+ area.action = "Show again";+ area.run = "unignore:" + area.id;+ } else {+ area.ignorable = true;+ }+ }return list;}@@ -132,14 +152,19 @@ PlasmoidItem {if (minutes < 60) {return "Checked " + minutes + " min ago";}- return "Checked at " + Qt.formatTime(new Date(lastChecked), "HH:mm");+ return "Checked at " + new Date(lastChecked).toLocaleTimeString(Qt.locale(), Locale.ShortFormat);}P5Support.DataSource {id: checkerengine: "executable"readonly property string command: security.libexec + "security-status"- connectedSources: [command]+ // Each refresh is its own source (a numbered comment), as with run():+ // the engine hands a source it already has its last output, so the+ // same command reconnected could report the state from before an+ // Ignore.+ property string current: command+ connectedSources: [current]// Most of this rarely changes, but a minute keeps the chip honest// after a service stops or updates arrive.interval: 60000@@ -171,9 +196,21 @@ PlasmoidItem {maybeNotifyUpdates();}+ property int checkCount: 0+function refreshStatus(): void {- checker.disconnectSource(checker.command);- checker.connectSource(checker.command);+ checker.disconnectSource(checker.current);+ checkCount += 1;+ checker.current = checker.command + " #" + checkCount;+ checker.connectSource(checker.current);+ }++ // The status is read again just after an Ignore or Show again, once the+ // command has written the list.+ Timer {+ id: ignoreRefresh+ interval: 400+ onTriggered: security.refreshStatus()}Timer {@@ -360,6 +397,13 @@ PlasmoidItem {openPrivacy();} else if (what === "updates") {openUpdates();+ } else if (what.indexOf("ignore:") === 0 || what.indexOf("unignore:") === 0) {+ const at = what.indexOf(":");+ const key = what.slice(at + 1);+ if (["encryption", "apps", "devices", "secureboot"].includes(key)) {+ run(libexec + "security-status " + what.slice(0, at) + " " + key);+ ignoreRefresh.restart();+ }} else if (what.indexOf("help:") === 0) {Qt.openUrlExternally(helpBase + (helpArticles[what.slice(5)] || ""));expanded = false;diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/Flyout.qml b/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/Flyout.qmlindex 08c6205..0cebf6e 100644--- a/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/Flyout.qml+++ b/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/Flyout.qml@@ -59,8 +59,8 @@ FocusScope {// does, rather than shown greyed out (EmptyStates.dc): on a desktop PC// Ethernet moves up to the first slot. Cast and Accessibility fill the// free slots of a six-tile grid, or stay once someone adds them.- readonly property var allTiles: ["wifi", "ethernet", "bluetooth", "flight", "dnd", "nightlight", "vpn", "cast", "accessibility"]- readonly property var fillers: ["cast", "accessibility"]+ readonly property var allTiles: ["wifi", "ethernet", "bluetooth", "flight", "dnd", "nightlight", "vpn", "cast", "accessibility", "awake"]+ readonly property var fillers: ["cast", "accessibility", "awake"]readonly property var presentTiles: allTiles.filter(id => tileApplies(id))readonly property var visibleTiles: {const core = presentTiles.filter(id => fillers.indexOf(id) < 0 && quick.hiddenTiles.indexOf(id) < 0);@@ -91,6 +91,8 @@ FocusScope {return true;case "accessibility":return quick.access !== null;+ case "awake":+ return power !== null;}return false;}@@ -212,6 +214,22 @@ FocusScope {pageName: "",description: quick.access.anyOn ? "Some accessibility features are on. Opens the list" : "Opens magnifier and colour settings"};+ case "awake": {+ const until = quick.keepAwakeUntil > 0+ ? "Until " + Qt.formatTime(new Date(quick.keepAwakeUntil), Qt.locale().timeFormat(Locale.ShortFormat)) : "";+ return {+ label: "Keep awake",+ status: quick.keepingAwake ? until : "",+ icon: Icons.coffee,+ fill: "",+ checked: quick.keepingAwake,+ hasPage: false,+ pageName: "",+ description: !quick.keepingAwake ? "Off"+ : until.length > 0 ? "The screen stays on and the computer won't sleep " + until.toLowerCase()+ : "The screen stays on and the computer won't sleep until you turn this off"+ };+ }}return {};}@@ -248,6 +266,9 @@ FocusScope {case "accessibility":showPage("accessibility");break;+ case "awake":+ quick.keepAwake(quick.keepingAwake ? -1 : 0);+ break;}}@@ -270,6 +291,21 @@ FocusScope {if (info.switchable !== false) {entries.push({ text: info.checked ? "Turn off" : "Turn on", icon: "menu-power", run: () => flyout.toggle(id) });}+ if (id === "awake") {+ entries.push({ text: "For 1 hour", icon: "clock", run: () => flyout.quick.keepAwake(60) });+ entries.push({ text: "For 4 hours", icon: "clock", run: () => flyout.quick.keepAwake(240) });+ entries.push({ text: "Until I turn it off", icon: "clock", run: () => flyout.quick.keepAwake(0) });+ if (info.checked) {+ entries.push({ text: "Turn off", icon: "menu-power", run: () => flyout.quick.keepAwake(-1) });+ }+ entries.push({ separator: true });+ entries.push({ text: "Power settings", icon: "menu-settings", run: () => flyout.quick.openSettings("power") });+ entries.push({ separator: true });+ entries.push({ text: "Edit quick settings", icon: "menu-apps", run: () => flyout.editing = true });+ tileMenu.entries = entries;+ tileMenu.popup(item, x, y);+ return;+ }const settings = tileSettings[id];if (settings) {entries.push({ text: settings[0], icon: "menu-settings", run: () => flyout.quick.openSettings(settings[1]) });diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/Icons.qml b/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/Icons.qmlindex 26d178e..ec6f663 100644--- a/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/Icons.qml+++ b/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/Icons.qml@@ -22,6 +22,7 @@ QtObject {readonly property string bluetooth: "M7 7l10 10-5 5V2l5 5L7 17"readonly property string flight: "M12 3v6M8.5 9h7M12 9l-9 6v2l9-3 9 3v-2zM12 14v5M9 21h6"readonly property string moon: "M20 14.5A8.5 8.5 0 0 1 9.5 4 8.5 8.5 0 1 0 20 14.5z"+ readonly property string coffee: "M5 9.5h11V14a5 5 0 0 1-5 5h-1a5 5 0 0 1-5-5V9.5zM16 11h1.5a2.5 2.5 0 0 1 0 5H16M8 3.5v3M10.5 3.5v3M13 3.5v3"readonly property string sun: "M16 12a4 4 0 1 1-8 0a4 4 0 1 1 8 0zM12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"readonly property string vpn: "M12 3l7 3v6c0 4.4-3 7.6-7 9-4-1.4-7-4.6-7-9V6zM9.5 12h5"readonly property string speaker: "M4 9.5h4l5-4v13l-5-4H4z"diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/NotificationsBackend.qml b/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/NotificationsBackend.qmlindex 3aaa834..148d52c 100644--- a/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/NotificationsBackend.qml+++ b/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/NotificationsBackend.qml@@ -1,5 +1,6 @@import QtQuickimport org.kde.notificationmanager as NotificationManager+import org.kde.plasma.plasma5support as P5Support// Do not disturb is the notification server's inhibition setting. The clock// flyout and Plasma read the same setting, so all of them agree.@@ -18,12 +19,70 @@ Item {live: true}- // A timed do not disturb ends on its own, so check once a minute.+ // A timed do not disturb ends on its own, so check once a minute. The+ // same tick checks quiet hours.Timer {interval: 60000running: truerepeat: true- onTriggered: dnd.now = Date.now()+ triggeredOnStart: true+ onTriggered: {+ dnd.now = Date.now();+ quietHours.connectSource(dnd.readQuietHours);+ }+ }++ // Quiet hours, set in Settings > System > Notifications and kept in+ // wildosrc: Enabled, From and To as "HHMM".+ readonly property string readQuietHours: "for k in Enabled From To; do kreadconfig6 --file wildosrc --group QuietHours --key $k; done"+ // The start of the quiet period already applied, so turning do not+ // disturb off early is not undone a minute later.+ property real quietApplied: 0++ P5Support.DataSource {+ id: quietHours+ engine: "executable"+ onNewData: (source, data) => {+ disconnectSource(source);+ const lines = String(data.stdout).split("+");+ if (lines[0].trim() !== "true") {+ return;+ }+ dnd.applyQuietHours(lines[1].trim() || "2200", lines[2].trim() || "0700");+ }+ }++ function at(day: date, hhmm: string): date {+ const d = new Date(day);+ d.setHours(Number(hhmm.slice(0, 2)), Number(hhmm.slice(2, 4)), 0, 0);+ return d;+ }++ function applyQuietHours(from: string, to: string): void {+ const now = new Date();+ let start = at(now, from);+ let end = at(now, to);+ if (end <= start) {+ // Overnight: before the end time this morning, the period+ // started yesterday evening.+ if (now < end) {+ start.setDate(start.getDate() - 1);+ } else {+ end.setDate(end.getDate() + 1);+ }+ }+ if (now < start || now >= end || start.getTime() === quietApplied) {+ return;+ }+ quietApplied = start.getTime();+ const until = settings.notificationsInhibitedUntil;+ if (!isNaN(until.getTime()) && until.getTime() >= end.getTime()) {+ return;+ }+ settings.notificationsInhibitedUntil = end;+ settings.save();+ dnd.now = Date.now();}function setActive(on: bool): void {diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/PowerBackend.qml b/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/PowerBackend.qmlindex 11f96db..73b20f7 100644--- a/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/PowerBackend.qml+++ b/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/PowerBackend.qml@@ -69,6 +69,21 @@ Item {NightLightControl { id: nightLight }+ // Keep awake holds powerdevil's manual block, the same one the stock+ // Power applet's "Manually block sleep" sets, so the screen stays on and+ // the computer does not sleep until it is released or the shell exits.+ BatteryMonitor.InhibitionControl { id: inhibition }++ readonly property bool keepingAwake: inhibition.isManuallyInhibited++ function setKeepAwake(on: bool): void {+ if (on && !inhibition.isManuallyInhibited) {+ inhibition.inhibit("Keep awake is on in quick settings");+ } else if (!on && inhibition.isManuallyInhibited) {+ inhibition.uninhibit();+ }+ }+// The flyout has one brightness slider, for the first display that can be// dimmed, which on a laptop is the built-in panel.Instantiator {diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/TrayButton.qml b/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/TrayButton.qmlindex a574534..7283773 100644--- a/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/TrayButton.qml+++ b/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/TrayButton.qml@@ -2,6 +2,7 @@ import QtQuickimport QtQuick.Layoutsimport QtQuick.Templates as Timport WildOS.UI as UI+import org.wildos.shell as WildOS// The tray button from the design's taskbar: network, volume and battery// glyphs together in one 44 px tall button with 12 px padding and gaps.@@ -143,5 +144,14 @@ MouseArea {charging: button.quick.power ? button.quick.power.charging : falselow: button.quick.batteryLow}++ UI.Label {+ visible: button.showBattery && WildOS.TaskbarStyle.batteryPercent+ Layout.leftMargin: -4+ text: (button.quick.power ? button.quick.power.percent : 0) + "%"+ size: 12+ font.features: { "tnum": 1 }+ color: UI.Style.iconInk+ }}}diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/main.qml b/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/main.qmlindex c039b29..2447a85 100644--- a/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/main.qml+++ b/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/main.qml@@ -156,6 +156,44 @@ PlasmoidItem {shell.connectSource(command);}+ // Keep awake: until a set time, or until turned off when keepAwakeUntil+ // is 0. The block itself lives in powerdevil, so if something else+ // releases it the timer here is dropped too.+ readonly property bool keepingAwake: power !== null && power.keepingAwake+ property real keepAwakeUntil: 0++ function keepAwake(minutes: int): void {+ if (!power) {+ return;+ }+ if (minutes < 0) {+ keepAwakeUntil = 0;+ keepAwakeTimer.stop();+ power.setKeepAwake(false);+ return;+ }+ power.setKeepAwake(true);+ keepAwakeUntil = minutes > 0 ? Date.now() + minutes * 60000 : 0;+ if (minutes > 0) {+ keepAwakeTimer.interval = minutes * 60000;+ keepAwakeTimer.restart();+ } else {+ keepAwakeTimer.stop();+ }+ }++ onKeepingAwakeChanged: {+ if (!keepingAwake) {+ keepAwakeUntil = 0;+ keepAwakeTimer.stop();+ }+ }++ Timer {+ id: keepAwakeTimer+ onTriggered: quick.keepAwake(-1)+ }+readonly property string reconfigureKWin: "dbus-send --session --type=method_call --dest=org.kde.KWin /KWin org.kde.KWin.reconfigure"// On means warmer colours on the screen right now, which is what the tilediff --git a/packages/wildos-branding/files/plasmoids/org.wildos.start/contents/config/main.xml b/packages/wildos-branding/files/plasmoids/org.wildos.start/contents/config/main.xmlindex 1f6d4b2..8b9b142 100644--- a/packages/wildos-branding/files/plasmoids/org.wildos.start/contents/config/main.xml+++ b/packages/wildos-branding/files/plasmoids/org.wildos.start/contents/config/main.xml@@ -11,7 +11,7 @@</entry><entry name="favorites" type="StringList"><label>Apps pinned the first time this Start menu runs. Afterwards the pins live in the activity manager, so changing this has no effect once favoritesPortedToKAstats is true. Apps that are not installed are skipped.</label>- <default>org.wildos.files.desktop,brave-browser.desktop,mullvad-browser.desktop,org.wildos.store.desktop,org.wildos.settings.desktop,org.wildos.terminal.desktop,org.kde.kcalc.desktop,org.kde.kwrite.desktop,org.kde.okular.desktop,org.kde.gwenview.desktop,org.keepassxc.KeePassXC.desktop</default>+ <default>org.wildos.mail.desktop,org.wildos.files.desktop,org.wildos.calendar.desktop,brave-browser.desktop,mullvad-browser.desktop,org.wildos.store.desktop,org.wildos.settings.desktop,org.wildos.terminal.desktop,org.kde.kcalc.desktop,org.kde.kwrite.desktop,org.kde.okular.desktop,org.kde.gwenview.desktop,org.keepassxc.KeePassXC.desktop</default></entry><entry name="favoritesPortedToKAstats" type="Bool"><label>Whether the default pins have been copied into the activity manager.</label>diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/PipeWireThumbnail.qml b/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/PipeWireThumbnail.qmlnew file mode 100644index 0000000..6c74513--- /dev/null+++ b/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/PipeWireThumbnail.qml@@ -0,0 +1,30 @@+/*+ SPDX-FileCopyrightText: 2020 Aleix Pol Gonzalez <[email protected]>+ SPDX-FileCopyrightText: 2026 Wild OS <[email protected]>++ SPDX-License-Identifier: LGPL-2.0-or-later++ Plasma 6.3.6 task manager's PipeWireThumbnail.qml: KWin streams one+ window over PipeWire for as long as this item lives. Loaded through a+ Loader so the preview still opens, with the app's icon, on a system+ without the PipeWire QML module.+*/++import QtQuick+import org.kde.pipewire as PipeWire+import org.kde.taskmanager as TaskManager++PipeWire.PipeWireSourceItem {+ id: stream++ property var winId++ readonly property bool hasThumbnail: ready && streamSize.width > 0 && streamSize.height > 0++ nodeId: request.nodeId++ TaskManager.ScreencastingRequest {+ id: request+ uuid: String(stream.winId ?? "")+ }+}diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/Task.qml b/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/Task.qmlindex 45a525a..af347c2 100644--- a/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/Task.qml+++ b/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/Task.qml@@ -210,11 +210,16 @@ Item {// so it never waits on the app or the model: down to 0.86, a spring past// full size to 1.04, and back, 100 ms in all.onPressedChanged: {- if (pressed && !reducedMotion) {- dip.restart();+ if (pressed) {+ tasksRoot.mutePreview(task);+ if (!reducedMotion) {+ dip.restart();+ }}}+ onHoveredChanged: tasksRoot.taskHovered(task, hovered)+SequentialAnimation {id: dipNumberAnimation { target: icon; property: "scale"; to: Style.dipScale; duration: 35; easing.type: Easing.OutCubic }diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/TaskMenu.qml b/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/TaskMenu.qmlindex 8aa82b3..b4daa2d 100644--- a/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/TaskMenu.qml+++ b/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/TaskMenu.qml@@ -8,10 +8,11 @@Wild OS fork of the Plasma 6.3.6 task manager's ContextMenu.qml. Thejump list a right click opens on an app (MenusShell.dc "Taskbar app"):its pinned places or recent files under small headings, the app's own- tasks, then the app itself in 600, pin or unpin and close, nearest the- taskbar as on Windows 11. A Windows app adds one quiet line saying it- runs in Windows mode and a way to its settings. It is the shared Wild- OS menu in a window of its own, as the taskbar is too short to hold it.+ tasks, then the app itself in 600, pin or unpin, close and End task,+ nearest the taskbar as on Windows 11. A Windows app adds one quiet line+ saying it runs in Windows mode and a way to its settings. It is the+ shared Wild OS menu in a window of its own, as the taskbar is too short+ to hold it.*/pragma ComponentBehavior: Bound@@ -192,6 +193,10 @@ UI.Menu {}}+ // Windows apps get their launchers from wildos-appbridge, which names+ // every one wildos-winapp-<app>.desktop.+ const windowsApp = /wildos-winapp-[^\/]*\.desktop$/.test(String(launcherUrl || ""));+if (!isLauncher && !isStartup) {const group = get(atm.IsGroupParent) === true;list.push({@@ -201,11 +206,16 @@ UI.Menu {run: () => tasksModel.requestClose(menu.modelIndex),enabled: get(atm.IsClosable) !== false});++ // Every Windows app's window comes from the one Windows mode+ // viewer, so ending it would close all of them at once.+ const pids = appPids(group);+ if (!windowsApp && pids.length > 0) {+ list.push({ text: "End task", icon: "menu-task-manager", run: () => menu.endTask(pids) });+ }}- // Windows apps get their launchers from wildos-appbridge, which names- // every one wildos-winapp-<app>.desktop.- if (/wildos-winapp-[^\/]*\.desktop$/.test(String(launcherUrl || ""))) {+ if (windowsApp) {list.push({ separator: true },{ text: "Runs in Windows mode", icon: "menu-windows-mode", enabled: false },{ text: "Windows mode settings", icon: "menu-settings", run: () => menu.runner.connectSource(@@ -215,6 +225,42 @@ UI.Menu {entries = list;}+ // The processes behind the app's windows; a group's windows can come+ // from more than one.+ function appPids(group: bool): var {+ const indexes = [];+ if (group) {+ for (let i = 0; i < tasksModel.rowCount(modelIndex); ++i) {+ indexes.push(tasksModel.makeModelIndex(task.index, i));+ }+ } else {+ indexes.push(modelIndex);+ }+ const pids = [];+ for (const index of indexes) {+ const pid = Math.floor(Number(tasksModel.data(index, atm.AppPid) ?? 0));+ if (pid > 1 && !pids.includes(pid)) {+ pids.push(pid);+ }+ }+ return pids;+ }++ // End task, as on Windows 11, for an app that no longer answers: the app+ // and everything it started are asked to quit, and whatever is still+ // running three seconds later is killed. The desktop's own processes are+ // left alone: their dialogs are tasks too, and ending them would end the+ // session. setsid lets the wait outlive this menu, which is gone the+ // moment the entry is chosen.+ function endTask(pids: var): void {+ const script = "all=; walk() { for p; do case $(cat /proc/$p/comm 2>/dev/null) in plasmashell|kwin_wayland|ksmserver|Xwayland|kded6|systemd) continue;; esac; all=\"$all $p\"; walk $(pgrep -P \"$p\"); done; }; "+ + "walk " + pids.join(" ") + "; kill -TERM $all 2>/dev/null; "+ + "for i in 1 2 3 4 5 6; do sleep 0.5; left=; "+ + "for p in $all; do kill -0 $p 2>/dev/null && left=\"$left $p\"; done; "+ + "[ -z \"$left\" ] && exit 0; done; kill -KILL $left 2>/dev/null";+ runner.connectSource("setsid -f sh -c '" + script + "'");+ }+// "Show all" in the places list asks for the menu again with every place.property Connections placesWatcher: Connections {target: menu.tasksRoot.backenddiff --git a/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/WindowPreview.qml b/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/WindowPreview.qmlnew file mode 100644index 0000000..eed4562--- /dev/null+++ b/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/WindowPreview.qml@@ -0,0 +1,338 @@+/*+ SPDX-FileCopyrightText: 2026 Wild OS <[email protected]>++ SPDX-License-Identifier: GPL-2.0-or-later++ The window previews over a running app, as on Windows 11: a live picture+ of each of its windows with the title and a close button. Pointing at+ one brings that window forward full size and fades the rest (KWin's+ highlight effect, through Plasma's task manager backend); clicking it+ switches to it and a middle click closes it. The glass is Plasma's+ popup frame, the one the clock and quick settings flyouts are drawn+ with, so it follows the theme's glass and text settings with them.+*/++pragma ComponentBehavior: Bound++import QtQuick+import QtQuick.Effects+import org.kde.ksvg as KSvg+import org.kde.kirigami as Kirigami+import org.kde.plasma.core as PlasmaCore+import WildOS.UI as UI++PlasmaCore.Dialog {+ id: preview++ required property Item tasksRoot+ // The button whose windows are shown.+ property Item task: null+ property bool shown: false++ readonly property var tasksModel: tasksRoot.tasksModel+ readonly property var backend: tasksRoot.backend+ readonly property var atm: tasksRoot.atm+ readonly property bool hovered: hover.hovered++ readonly property bool group: task !== null && task.model.IsGroupParent === true+ readonly property int windowCount: task === null || !task.isWindow ? 0 : group ? task.childCount : 1++ // Titles and minimised states change while the preview is up; every+ // tile reads them again when the model says something changed.+ property int revision: 0++ // Between the preview and the top of the taskbar, as for the menu.+ readonly property int gap: 12+ readonly property int glassBorder: 1+ readonly property int pad: 6+ readonly property int tilePad: 6+ readonly property int tileGap: 4+ readonly property int headerHeight: 28+ // The design's 16:9 picture, narrowed when many windows would not fit+ // across the screen.+ readonly property int pictureWidth: {+ const screen = tasksModel.screenGeometry;+ const room = (screen.width > 0 ? screen.width : 1920) - 32 - 2 * (glassBorder + pad);+ const n = Math.max(1, windowCount);+ const tile = Math.floor((room + tileGap) / n - tileGap);+ return Math.max(120, Math.min(200, tile - 2 * tilePad));+ }+ readonly property int pictureHeight: Math.round(pictureWidth * 9 / 16)+ readonly property int tileWidth: pictureWidth + 2 * tilePad+ readonly property int tileHeight: tilePad + headerHeight + 4 + pictureHeight + tilePad++ readonly property real glassWidth: 2 * (glassBorder + pad) + windowCount * tileWidth + Math.max(0, windowCount - 1) * tileGap+ readonly property real glassHeight: 2 * (glassBorder + pad) + tileHeight++ // A notification-type window is placed exactly where it is told, never+ // takes keyboard focus, and KWin's highlight effect leaves it unfaded.+ type: PlasmaCore.Dialog.Notification+ flags: Qt.WindowStaysOnTopHint | Qt.WindowDoesNotAcceptFocus+ location: PlasmaCore.Types.Floating+ hideOnWindowDeactivate: false+ visible: shown && windowCount > 0++ onVisibleChanged: {+ if (visible) {+ place();+ settle.restart();+ } else {+ backend.cancelHighlightWindows();+ // Closing the last window hides it too; the next hover waits+ // again rather than opening at once.+ shown = false;+ }+ }+ onShownChanged: if (shown) place()+ onTaskChanged: {+ backend.cancelHighlightWindows();+ if (visible) {+ place();+ }+ }+ onWidthChanged: if (visible) place()+ onHeightChanged: if (visible) place()++ // Centred over the button, its foot 12 px above the taskbar's window and+ // kept 8 px inside the screen.+ function place(): void {+ if (!task) {+ return;+ }+ const rect = backend.globalRect(task);+ const barTop = rect.y - task.mapToItem(null, 0, 0).y;+ const screen = tasksModel.screenGeometry;+ let left = Math.round(rect.x + rect.width / 2 - width / 2);+ if (screen.width > 0) {+ left = Math.max(screen.x + 8, Math.min(left, screen.x + screen.width - 8 - width));+ }+ x = left;+ y = Math.round(barTop - gap - height);+ }++ // Plasma can still be sizing the window as it appears.+ property Timer settle: Timer {+ interval: 120+ onTriggered: preview.place()+ }++ function highlight(winId: string, on: bool): void {+ if (winId.length > 0) {+ backend.windowsHovered([winId], on);+ }+ }++ mainItem: Item {+ Connections {+ target: preview.tasksModel+ enabled: preview.visible+ function onDataChanged(): void {+ preview.revision++;+ }+ }++ KSvg.FrameSvgItem {+ id: frame+ imagePath: "dialogs/background"+ visible: false+ }++ width: preview.glassWidth - frame.margins.left - frame.margins.right+ height: preview.glassHeight - frame.margins.top - frame.margins.bottom++ HoverHandler {+ id: hover+ }++ Row {+ x: preview.glassBorder + preview.pad - frame.margins.left+ y: preview.glassBorder + preview.pad - frame.margins.top+ spacing: preview.tileGap++ Repeater {+ model: preview.windowCount++ delegate: Item {+ id: tile++ required property int index++ width: preview.tileWidth+ height: preview.tileHeight++ function modelIndex(): var {+ const at = preview.task.index;+ return preview.group ? preview.tasksModel.makeModelIndex(at, index) : preview.tasksModel.makeModelIndex(at);+ }++ function get(role: int): var {+ return preview.task ? preview.tasksModel.data(modelIndex(), role) : undefined;+ }++ readonly property string winId: {+ preview.revision;+ const ids = get(preview.atm.WinIdList);+ return ids && ids.length > 0 ? String(ids[0]) : "";+ }+ readonly property string title: {+ preview.revision;+ return String(get(Qt.DisplayRole) ?? "");+ }+ readonly property bool minimized: {+ preview.revision;+ return get(preview.atm.IsMinimized) === true;+ }+ readonly property var icon: {+ preview.revision;+ return get(Qt.DecorationRole);+ }++ function activate(): void {+ preview.backend.cancelHighlightWindows();+ preview.tasksModel.requestActivate(modelIndex());+ preview.tasksRoot.hidePreview();+ }++ function close(): void {+ preview.backend.cancelHighlightWindows();+ preview.tasksModel.requestClose(modelIndex());+ }++ Accessible.role: Accessible.Button+ Accessible.name: title+ Accessible.onPressAction: activate()++ HoverHandler {+ id: tileHover+ onHoveredChanged: preview.highlight(tile.winId, hovered)+ }++ TapHandler {+ id: tileTap+ acceptedButtons: Qt.LeftButton+ gesturePolicy: TapHandler.ReleaseWithinBounds+ onTapped: tile.activate()+ }++ TapHandler {+ acceptedButtons: Qt.MiddleButton+ gesturePolicy: TapHandler.ReleaseWithinBounds+ onTapped: tile.close()+ }++ Rectangle {+ anchors.fill: parent+ radius: UI.Style.radiusSm+ color: tileTap.pressed ? UI.Style.surfacePressed+ : tileHover.hovered ? UI.Style.surfaceHover+ : "transparent"+ Behavior on color {+ ColorAnimation { duration: UI.Style.hoverDuration }+ }+ }++ Kirigami.Icon {+ id: smallIcon+ x: preview.tilePad + 2+ y: preview.tilePad + (preview.headerHeight - height) / 2+ width: 16+ height: 16+ source: tile.icon ?? ""+ animated: false+ }++ UI.Label {+ anchors.left: smallIcon.right+ anchors.leftMargin: 8+ anchors.right: closeButton.left+ anchors.rightMargin: 4+ y: preview.tilePad+ height: preview.headerHeight+ size: 12+ text: tile.title+ }++ // Shown on the tile under the pointer, as Windows does,+ // so a row of previews is not a row of close buttons.+ UI.IconButton {+ id: closeButton+ x: tile.width - preview.tilePad - width+ y: preview.tilePad + (preview.headerHeight - height) / 2+ width: 24+ height: 24+ iconName: "close"+ iconSize: 12+ tip: "Close window"+ focusPolicy: Qt.NoFocus+ opacity: tileHover.hovered ? 1 : 0+ enabled: tileHover.hovered+ onClicked: tile.close()+ }++ Item {+ id: picture+ x: preview.tilePad+ y: preview.tilePad + preview.headerHeight + 4+ width: preview.pictureWidth+ height: preview.pictureHeight++ readonly property bool live: stream.item !== null && stream.item.hasThumbnail+ readonly property size streamSize: stream.item ? stream.item.streamSize : Qt.size(0, 0)+ readonly property real fit: streamSize.width > 0 && streamSize.height > 0+ ? Math.min(width / streamSize.width, height / streamSize.height) : 1++ // Fitted to the window's shape, with the design's+ // corners.+ Item {+ id: shot+ anchors.centerIn: parent+ width: picture.streamSize.width > 0 ? Math.round(picture.streamSize.width * picture.fit) : picture.width+ height: picture.streamSize.height > 0 ? Math.round(picture.streamSize.height * picture.fit) : picture.height+ opacity: picture.live ? 1 : 0+ layer.enabled: true+ layer.effect: MultiEffect {+ maskEnabled: true+ maskSource: corners+ }++ // A minimised window has nothing to stream; its+ // icon stands in, as for an app KWin cannot capture.+ Loader {+ id: stream+ anchors.fill: parent+ active: !tile.minimized && tile.winId.length > 0+ source: "PipeWireThumbnail.qml"+ onLoaded: item.winId = Qt.binding(() => tile.winId)+ }+ }++ Rectangle {+ id: corners+ width: shot.width+ height: shot.height+ radius: UI.Style.radiusXs+ visible: false+ layer.enabled: true+ }++ // Waits a moment for the stream before showing the+ // icon, so a live picture does not flash it first.+ Timer {+ id: patience+ interval: 300+ running: true+ }++ Kirigami.Icon {+ anchors.centerIn: parent+ width: 48+ height: 48+ source: tile.icon ?? ""+ visible: !picture.live && (tile.minimized || !stream.active || !patience.running)+ }+ }+ }+ }+ }+ }+}diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/main.qml b/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/main.qmlindex a30fbbb..048f5b0 100644--- a/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/main.qml+++ b/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/main.qml@@ -6,10 +6,10 @@Wild OS fork of the Plasma 6.3.6 task manager (org.kde.plasma.taskmanager).The task models and backend are Plasma's own C++ (org.kde.taskmanager and- org.kde.plasma.private.taskmanager); the buttons, launch feedback and the- right-click menu are redrawn to the Wild OS Taskbar design, and the- options Wild OS never shows (text labels, stripes, tooltips, window- previews, activities) are gone.+ org.kde.plasma.private.taskmanager); the buttons, launch feedback, the+ right-click menu and the window previews are redrawn to the Wild OS+ Taskbar design, and the options Wild OS never shows (text labels,+ stripes, tooltips, activities) are gone.*/pragma ComponentBehavior: Bound@@ -114,6 +114,93 @@ PlasmoidItem {onDragSourceChanged: {if (dragSource === null) {tasksModel.syncLaunchers();+ } else {+ hidePreview();+ }+ }++ // Window previews: they open after a short rest on a running app, follow+ // the pointer from app to app while up, and close a moment after it has+ // left both the buttons and the preview, so crossing the gap between+ // them does not close it.+ WindowPreview {+ id: windowPreview+ tasksRoot: tasks++ onHoveredChanged: {+ if (hovered) {+ previewCloseTimer.stop();+ } else {+ previewCloseTimer.restart();+ }+ }+ }++ property Item previewPending: null+ // A button just clicked keeps its preview away until the pointer leaves+ // it, as on Windows.+ property Item previewMuted: null++ function taskHovered(task: Item, hovered: bool): void {+ if (!hovered) {+ if (previewMuted === task) {+ previewMuted = null;+ }+ if (previewPending === task) {+ previewPending = null;+ previewOpenTimer.stop();+ }+ previewCloseTimer.restart();+ return;+ }+ const wanted = (task as Task).isWindow && previewMuted !== task && menuTask === null && dragSource === null;+ if (!wanted) {+ previewOpenTimer.stop();+ previewCloseTimer.restart();+ return;+ }+ previewCloseTimer.stop();+ if (windowPreview.visible) {+ windowPreview.task = task;+ return;+ }+ previewPending = task;+ previewOpenTimer.restart();+ }++ function hidePreview(): void {+ previewOpenTimer.stop();+ previewCloseTimer.stop();+ previewPending = null;+ windowPreview.shown = false;+ }++ function mutePreview(task: Item): void {+ previewMuted = task;+ hidePreview();+ }++ Timer {+ id: previewOpenTimer+ interval: 400+ onTriggered: {+ const task = tasks.previewPending as Task;+ tasks.previewPending = null;+ if (task && task.hovered && task.isWindow) {+ windowPreview.task = task;+ windowPreview.shown = true;+ }+ }+ }++ Timer {+ id: previewCloseTimer+ interval: 300+ onTriggered: {+ const task = windowPreview.task as Task;+ if (!windowPreview.hovered && !(task && task.hovered)) {+ tasks.hidePreview();+ }}}@@ -162,7 +249,9 @@ PlasmoidItem {readonly property TaskManagerApplet.Backend backend: TaskManagerApplet.Backend {id: backend- highlightWindows: false+ // Only the window previews ask for it: pointing at one shows that+ // window full size and fades the others.+ highlightWindows: trueonAddLauncher: url => tasks.addLauncher(url)}@@ -390,6 +479,7 @@ PlasmoidItem {tasksRoot: tasks,keyboard: fromKeyboard});+ hidePreview();menuTask = task;menu.closed.connect(() => {if (tasks.menuTask === task) {diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/config/main.xml b/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/config/main.xmlnew file mode 100644index 0000000..5072c2d--- /dev/null+++ b/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/config/main.xml@@ -0,0 +1,12 @@+<?xml version="1.0" encoding="UTF-8"?>+<kcfg xmlns="http://www.kde.org/standards/kcfg/1.0"+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"+ xsi:schemaLocation="http://www.kde.org/standards/kcfg/1.0 http://www.kde.org/standards/kcfg/1.0/kcfg.xsd">+ <kcfgfile name=""/>+ <group name="General">+ <!-- Settings > Personalisation > Taskbar turns it off. -->+ <entry name="shown" type="Bool">+ <default>true</default>+ </entry>+ </group>+</kcfg>diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/Chip.qml b/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/Chip.qmlnew file mode 100644index 0000000..6bd0171--- /dev/null+++ b/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/Chip.qml@@ -0,0 +1,112 @@+import QtQuick+import QtQuick.Layouts+import WildOS.UI as UI+import org.wildos.shell as WildOS++// The taskbar item from board 4.13: the window-with-shield mark that+// Settings uses for Windows apps, its status dot, and two lines, "Windows+// mode" and the state. A 40 px button with 10 px corners, 10 px in on the+// left and 12 on the right. It sits at the left end of the bar in both+// styles and carries its own gap from the screen edge, so the bar needs no+// spacer before it: 8 px docked; 13 px floating, where its pill starts 5 px+// in, so with the bar's own 12 px margin the pill sits 17 px from the left+// edge, as the status pill does from the right, with 8 px inside. It takes no room at all+// until Windows mode is set up or when it is turned off.+MouseArea {+ id: chip++ required property var winmode++ readonly property int edge: WildOS.TaskbarStyle.floating ? 13 : 8+ property bool wasExpanded: false++ readonly property real fullWidth: edge + button.width+ Layout.minimumWidth: winmode.shown ? fullWidth : 0+ Layout.preferredWidth: Layout.minimumWidth+ Layout.maximumWidth: Layout.minimumWidth+ Layout.minimumHeight: winmode.shown ? 40 : 0+ // Plasma shows the compact representation itself whatever it says, so+ // hiding is no width and nothing drawn.+ enabled: winmode.shown++ hoverEnabled: true+ Accessible.role: Accessible.Button+ Accessible.name: "Windows mode: " + winmode.stateText+ Accessible.description: winmode.toolTipSubText++ // Remembering the state at press time stops a click that closes the popup+ // (it loses focus first) from opening it again straight away.+ onPressed: wasExpanded = winmode.expanded+ onClicked: winmode.expanded = !wasExpanded++ Rectangle {+ id: button+ visible: chip.winmode.shown+ x: chip.edge+ anchors.verticalCenter: parent.verticalCenter+ width: row.implicitWidth + 22+ height: 40+ radius: 10+ color: chip.pressed ? UI.Style.surfacePressed+ : chip.winmode.expanded || chip.containsMouse ? UI.Style.tone(0.12) : UI.Style.tone(0.07)+ border.width: 1+ border.color: chip.winmode.expanded ? UI.Style.tone(0.10) : "transparent"+ Behavior on color {+ ColorAnimation { duration: UI.Style.hoverDuration }+ }++ RowLayout {+ id: row+ x: 10+ anchors.verticalCenter: parent.verticalCenter+ spacing: 10++ Item {+ Layout.preferredWidth: 20+ Layout.preferredHeight: 20++ UI.Icon {+ anchors.fill: parent+ name: "windowsapps"+ size: 20+ strokeWidth: 1.8+ color: UI.Style.ink+ }++ // A ring of the bar's colour around the dot keeps it apart+ // from the mark's stroke underneath.+ Rectangle {+ x: 20 + 3 - width+ y: 20 + 2 - height+ width: 12+ height: 12+ radius: 6+ color: Tones.bar++ StatusDot {+ anchors.centerIn: parent+ level: chip.winmode.level+ }+ }+ }++ ColumnLayout {+ spacing: 1++ UI.Label {+ text: "Windows mode"+ size: 12+ font.weight: Font.DemiBold+ lineHeight: 1.2+ }++ UI.Label {+ text: chip.winmode.stateText+ size: 11+ lineHeight: 1.2+ color: chip.winmode.level === "attention" ? Tones.dot("attention") : UI.Style.inkMuted+ }+ }+ }+ }+}diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/Meter.qml b/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/Meter.qmlnew file mode 100644index 0000000..a1eb9b0--- /dev/null+++ b/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/Meter.qml@@ -0,0 +1,24 @@+import QtQuick+import WildOS.UI as UI++// The 6 px memory meter from board 4.14: the accent on a faint track, paler+// while Windows is paused and the memory is only held.+Rectangle {+ id: meter++ property real value: 0+ property bool held: false++ implicitHeight: 6+ radius: 3+ color: UI.Style.tone(0.12)+ Accessible.role: Accessible.ProgressBar++ Rectangle {+ width: Math.round(meter.width * Math.max(0, Math.min(1, meter.value)))+ height: parent.height+ radius: 3+ color: meter.held ? Qt.rgba(UI.Style.accent.r, UI.Style.accent.g, UI.Style.accent.b, 0.6) : UI.Style.accent+ visible: width > 0+ }+}diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/Sparkline.qml b/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/Sparkline.qmlnew file mode 100644index 0000000..600b367--- /dev/null+++ b/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/Sparkline.qml@@ -0,0 +1,56 @@+import QtQuick+import QtQuick.Shapes+import WildOS.UI as UI++// Processor use over the last minute, as on board 4.14: a line in the+// accent over a soft fill, oldest on the left, with a dot on the latest+// reading. points: [{x: 0 to 1, y: 0 to 100}].+Item {+ id: spark++ property var points: []+ // The line keeps clear of the top so a busy minute's peak and the end+ // dot are not clipped.+ readonly property real headroom: 4+ readonly property var line: points.map(p => Qt.point(p.x * width, headroom + (height - headroom) * (1 - p.y / 100)))++ implicitHeight: 34++ Shape {+ anchors.fill: parent+ visible: spark.line.length > 1+ preferredRendererType: Shape.CurveRenderer++ ShapePath {+ strokeColor: "transparent"+ fillColor: UI.Style.accentChip+ PathPolyline {+ path: spark.line.length > 1+ ? [Qt.point(spark.line[0].x, spark.height)].concat(spark.line, [Qt.point(spark.line[spark.line.length - 1].x, spark.height)])+ : []+ }+ }++ ShapePath {+ strokeColor: UI.Style.accent+ strokeWidth: 1.6+ fillColor: "transparent"+ joinStyle: ShapePath.RoundJoin+ capStyle: ShapePath.RoundCap+ PathPolyline {+ path: spark.line+ }+ }+ }++ Rectangle {+ visible: spark.line.length > 0+ readonly property point last: spark.line.length > 0 ? spark.line[spark.line.length - 1] : Qt.point(0, 0)+ x: Math.min(spark.width - width, last.x - width / 2)+ y: last.y - height / 2+ width: 6+ height: 6+ radius: 3+ color: UI.Style.accent+ }+}diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/StatusDot.qml b/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/StatusDot.qmlnew file mode 100644index 0000000..5f2d42f--- /dev/null+++ b/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/StatusDot.qml@@ -0,0 +1,49 @@+import QtQuick+import WildOS.UI as UI++// The 8 px status dot. While Windows is starting or updating a ring around+// it pulses; with reduced motion the ring stays still, as drawn on the board.+Item {+ id: dot++ property string level: ""+ readonly property bool pulsing: level === "starting" || level === "updating"+ readonly property color colour: Tones.dot(level)++ implicitWidth: 8+ implicitHeight: 8++ Rectangle {+ id: ring+ anchors.centerIn: parent+ width: 16+ height: 16+ radius: 8+ color: "transparent"+ border.width: 1.5+ border.color: dot.colour+ opacity: 0.45+ visible: dot.pulsing++ SequentialAnimation {+ running: dot.pulsing && !UI.Style.reducedMotion && dot.visible+ loops: Animation.Infinite+ onStopped: {+ ring.scale = 1;+ ring.opacity = 0.45;+ }++ ParallelAnimation {+ NumberAnimation { target: ring; property: "scale"; from: 0.6; to: 1.15; duration: 1100; easing.type: Easing.OutCubic }+ NumberAnimation { target: ring; property: "opacity"; from: 0.6; to: 0; duration: 1100; easing.type: Easing.OutCubic }+ }+ PauseAnimation { duration: 300 }+ }+ }++ Rectangle {+ anchors.fill: parent+ radius: width / 2+ color: dot.colour+ }+}diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/StatusPanel.qml b/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/StatusPanel.qmlnew file mode 100644index 0000000..545577c--- /dev/null+++ b/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/StatusPanel.qml@@ -0,0 +1,462 @@+pragma ComponentBehavior: Bound++import QtQuick+import QtQuick.Layouts+import QtQuick.Templates as T+import org.kde.kirigami as Kirigami+import org.kde.ksvg as KSvg+import WildOS.UI as UI++// The panel from board 4.14. While Windows apps are open: the edition, a+// Running pill, processor use over the last minute, memory against the limit+// set for Windows, what is open, and Pause now and Save to disk along a+// darker foot. While paused (and once saved or off) it is narrower: how long,+// the memory held, and the app to open again. It only offers what the person+// can act on, so Save to disk waits until the service can save, and an app+// is only offered once one has been opened. Plasma's theme draws the glass;+// sizes are the board's outer edge with the theme's frame margins taken off,+// as in the security flyout.+FocusScope {+ id: panel++ required property var winmode++ KSvg.FrameSvgItem {+ id: frame+ imagePath: "dialogs/background"+ visible: false+ }++ readonly property real edgeLeft: frame.margins.left+ readonly property real edgeRight: frame.margins.right+ readonly property real edgeTop: frame.margins.top+ readonly property real edgeBottom: frame.margins.bottom++ readonly property string level: winmode.level+ readonly property bool running: level === "running"+ readonly property bool resting: level === "paused" || level === "saved" || level === "off"+ readonly property bool vmRunning: winmode.system !== null && winmode.system.vm === "running"++ readonly property int glassBorder: 1+ readonly property int pad: 18+ readonly property int frameRadius: 22+ readonly property int outerWidth: running ? 360 : 330+ readonly property real innerWidth: outerWidth - 2 * (glassBorder + pad)++ readonly property bool hasFoot: !resting+ readonly property real footHeight: hasFoot ? foot.implicitHeight + 26 : 0+ readonly property real glassHeight: 2 * glassBorder + pad + body.implicitHeight + (hasFoot ? 14 + footHeight : pad)++ readonly property real contentWidth: outerWidth - edgeLeft - edgeRight+ readonly property real contentHeight: glassHeight - edgeTop - edgeBottom++ Layout.minimumWidth: contentWidth+ Layout.preferredWidth: contentWidth+ Layout.maximumWidth: contentWidth+ Layout.minimumHeight: contentHeight+ Layout.preferredHeight: contentHeight+ Layout.maximumHeight: contentHeight++ focus: true++ Keys.onPressed: event => {+ if (event.key === Qt.Key_Escape) {+ panel.winmode.expanded = false;+ event.accepted = true;+ }+ }++ Connections {+ target: panel.winmode+ function onExpandedChanged() {+ if (panel.winmode.expanded) {+ panel.forceActiveFocus();+ }+ }+ }++ component Caption: UI.Label {+ size: 12+ color: UI.Style.inkMuted+ }++ component Figure: UI.Label {+ size: 13+ font.weight: Font.DemiBold+ font.features: ({ "tnum": 1 })+ }++ component Note: UI.Label {+ Layout.fillWidth: true+ size: 11+ color: UI.Style.inkMuted+ wrapMode: Text.Wrap+ elide: Text.ElideNone+ }++ component Action: UI.Button {+ Layout.fillWidth: true+ Layout.preferredHeight: 34+ }++ // "Windows mode settings" and a chevron across the panel's width. Inline+ // components can't reach the panel's ids, so each use says what a click+ // does.+ component SettingsLink: T.AbstractButton {+ id: link+ Layout.fillWidth: true+ implicitHeight: 20+ hoverEnabled: true+ focusPolicy: Qt.StrongFocus+ text: "Windows mode settings"+ Accessible.role: Accessible.Link+ Accessible.name: text++ background: Item {+ UI.FocusRing {+ visible: link.visualFocus+ targetRadius: UI.Style.radiusXs+ }+ }++ contentItem: RowLayout {+ spacing: 8++ UI.Label {+ Layout.fillWidth: true+ text: link.text+ size: 12+ color: UI.Style.accentText+ font.underline: link.hovered+ opacity: link.down ? 0.75 : 1+ }++ UI.Glyph {+ Layout.preferredWidth: 12+ Layout.preferredHeight: 12+ path: "M9 6l6 6-6 6"+ color: UI.Style.accentText+ strokeWidth: 2+ }+ }+ }++ ColumnLayout {+ id: body+ x: panel.glassBorder + panel.pad - panel.edgeLeft+ y: panel.glassBorder + panel.pad - panel.edgeTop+ width: panel.innerWidth+ spacing: panel.running ? 16 : 14++ // The mark in an accent tile, "Windows mode" and what it is doing,+ // and the state in a pill.+ RowLayout {+ Layout.fillWidth: true+ spacing: 12++ Rectangle {+ Layout.preferredWidth: 38+ Layout.preferredHeight: 38+ radius: 10+ color: UI.Style.accentChip++ UI.Icon {+ anchors.centerIn: parent+ name: "windowsapps"+ size: 20+ strokeWidth: 1.8+ color: UI.Style.accentText+ }+ }++ ColumnLayout {+ Layout.fillWidth: true+ spacing: 2++ UI.Label {+ Layout.fillWidth: true+ text: "Windows mode"+ size: 15+ font.weight: Font.DemiBold+ Accessible.role: Accessible.Heading+ }++ Caption {+ Layout.fillWidth: true+ text: panel.winmode.subtitle()+ }+ }++ Rectangle {+ Layout.preferredHeight: 22+ Layout.preferredWidth: pill.implicitWidth + 18+ radius: 11+ color: Tones.pillFill(panel.level)++ RowLayout {+ id: pill+ anchors.centerIn: parent+ spacing: 6++ StatusDot {+ level: panel.level+ }++ UI.Label {+ text: panel.winmode.pillText+ size: 11+ font.weight: Font.DemiBold+ color: Tones.pillText(panel.level)+ }+ }+ }+ }++ ColumnLayout {+ visible: panel.running && panel.winmode.qemu !== null+ Layout.fillWidth: true+ spacing: 6++ RowLayout {+ Layout.fillWidth: true++ Caption {+ Layout.fillWidth: true+ text: "Processor, last minute"+ }++ Figure {+ text: panel.winmode.processorPercent + "%"+ }+ }++ Sparkline {+ Layout.fillWidth: true+ Layout.preferredHeight: 34+ points: panel.winmode.processorTrace+ }+ }++ ColumnLayout {+ visible: (panel.running || panel.level === "paused") && panel.winmode.qemu !== null+ Layout.fillWidth: true+ spacing: 6++ RowLayout {+ Layout.fillWidth: true++ Caption {+ Layout.fillWidth: true+ text: panel.running ? "Memory" : "Memory held"+ }++ Figure {+ text: panel.running && panel.winmode.memoryLimit > 0+ ? panel.winmode.bytesText(panel.winmode.memoryHeld) + " of " + panel.winmode.bytesText(panel.winmode.memoryLimit)+ : panel.winmode.bytesText(panel.winmode.memoryHeld)+ }+ }++ Meter {+ Layout.fillWidth: true+ value: panel.winmode.memoryLimit > 0 ? panel.winmode.memoryHeld / panel.winmode.memoryLimit : 0+ held: !panel.running+ Accessible.name: panel.running ? "Memory" : "Memory held"+ }++ Note {+ text: panel.running ? "Unused memory goes back to Wild OS" : "No processor use. Ready in about a second."+ }+ }++ // Saved or off: nothing held, so no meter, only what it costs to+ // come back.+ UI.Label {+ visible: panel.level === "saved" || panel.level === "off"+ Layout.fillWidth: true+ size: 12+ color: UI.Style.inkMuted+ lineHeight: 1.5+ wrapMode: Text.Wrap+ elide: Text.ElideNone+ text: panel.level === "saved" ? "Uses no memory. Ready in a few seconds when you open a Windows app."+ : "Uses no memory. Starts when you open a Windows app, which takes about a minute."+ }++ UI.Label {+ visible: panel.level === "starting" || panel.level === "updating" || panel.level === "attention"+ Layout.fillWidth: true+ size: 13+ lineHeight: 1.5+ wrapMode: Text.Wrap+ elide: Text.ElideNone+ color: panel.level === "attention" ? UI.Style.ink : UI.Style.inkMuted+ text: panel.level === "starting" ? "Getting Windows ready. Your app opens as soon as it is."+ : panel.level === "updating" ? "Installing Windows and Office updates that Wild OS has tested. Your apps open as normal once it's done."+ : panel.winmode.attentionText()+ }++ ColumnLayout {+ visible: panel.running && panel.winmode.openApps.length > 0+ Layout.fillWidth: true+ spacing: 0++ Rectangle {+ Layout.fillWidth: true+ Layout.bottomMargin: 8+ implicitHeight: 1+ color: UI.Style.tone(0.08)+ }++ Caption {+ Layout.bottomMargin: 2+ text: "Open now"+ }++ Repeater {+ model: panel.winmode.openApps++ RowLayout {+ id: app+ required property var modelData+ Layout.fillWidth: true+ Layout.preferredHeight: 44+ spacing: 12++ Rectangle {+ Layout.preferredWidth: 30+ Layout.preferredHeight: 30+ radius: 8+ color: UI.Style.tone(0.08)++ Kirigami.Icon {+ anchors.centerIn: parent+ width: 20+ height: 20+ source: app.modelData.icon || "wildos-windows-app"+ fallback: "wildos-windows-app"+ }+ }++ ColumnLayout {+ Layout.fillWidth: true+ spacing: 1++ UI.Label {+ Layout.fillWidth: true+ text: app.modelData.name+ size: 13+ }++ UI.Label {+ visible: text.length > 0+ Layout.fillWidth: true+ text: app.modelData.title || ""+ size: 11+ color: UI.Style.inkMuted+ }+ }+ }+ }+ }++ UI.Label {+ readonly property string idle: panel.running ? panel.winmode.idleText() : ""+ visible: idle.length > 0+ Layout.fillWidth: true+ size: 12+ color: UI.Style.inkMuted+ lineHeight: 1.5+ wrapMode: Text.Wrap+ elide: Text.ElideNone+ text: idle+ }++ // Resting: Save to disk while it can still free memory, and the app+ // to open again as the main action. With neither, the way to the+ // settings.+ RowLayout {+ id: restingActions+ readonly property bool canSave: panel.level === "paused" && panel.winmode.canSave+ readonly property bool canOpen: panel.winmode.lastApp !== null+ visible: panel.resting && (canSave || canOpen)+ Layout.fillWidth: true+ spacing: 8++ Action {+ visible: restingActions.canSave+ enabled: !panel.winmode.busyAction+ text: "Save to disk"+ onClicked: panel.winmode.saveToDisk()+ }++ Action {+ visible: restingActions.canOpen+ kind: "primary"+ text: restingActions.canOpen ? "Open " + panel.winmode.lastApp.name : ""+ onClicked: panel.winmode.openApp(panel.winmode.lastApp.id)+ }+ }++ SettingsLink {+ visible: panel.resting && !restingActions.visible+ onClicked: panel.winmode.openSettings()+ }+ }++ // The darker foot, edge to edge inside the glass border, as on quick+ // settings: Pause now and Save to disk while Windows runs, and the way+ // to Windows mode's settings.+ Rectangle {+ visible: panel.hasFoot+ anchors.left: parent.left+ anchors.leftMargin: panel.glassBorder - panel.edgeLeft+ anchors.right: parent.right+ anchors.rightMargin: panel.glassBorder - panel.edgeRight+ anchors.bottom: parent.bottom+ anchors.bottomMargin: panel.glassBorder - panel.edgeBottom+ height: panel.footHeight+ color: UI.Style.surfaceBand+ bottomLeftRadius: panel.frameRadius - panel.glassBorder+ bottomRightRadius: panel.frameRadius - panel.glassBorder++ Rectangle {+ anchors.top: parent.top+ anchors.left: parent.left+ anchors.right: parent.right+ height: 1+ color: UI.Style.tone(0.07)+ }++ ColumnLayout {+ id: foot+ x: panel.pad+ y: 12+ width: panel.innerWidth+ spacing: 10++ RowLayout {+ visible: panel.vmRunning && (panel.running || panel.level === "attention")+ Layout.fillWidth: true+ spacing: 8++ Action {+ enabled: !panel.winmode.busyAction+ text: "Pause now"+ onClicked: panel.winmode.pauseNow()+ }++ Action {+ visible: panel.winmode.canSave+ enabled: !panel.winmode.busyAction+ text: "Save to disk"+ onClicked: panel.winmode.saveToDisk()+ }+ }++ SettingsLink {+ onClicked: panel.winmode.openSettings()+ }+ }+ }+}diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/Tones.qml b/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/Tones.qmlnew file mode 100644index 0000000..201b070--- /dev/null+++ b/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/Tones.qml@@ -0,0 +1,51 @@+pragma Singleton++import QtQuick+import WildOS.UI as UI++// The status colours from board 4.13, dark then light: green while running,+// blue while paused or starting, grey once saved or off, sand while updating+// or when something needs attention. The word beside the dot always says+// the state too, so colour is never the only signal.+QtObject {+ readonly property bool dark: UI.Style.dark++ function dot(level: string): color {+ switch (level) {+ case "running":+ return dark ? "#7fe0ad" : "#1c9a62";+ case "paused":+ case "starting":+ return dark ? "#8fb4ff" : "#3a56c4";+ case "updating":+ case "attention":+ return dark ? "#f5c27a" : "#b7791f";+ }+ return dark ? Qt.rgba(232 / 255, 236 / 255, 248 / 255, 0.55) : Qt.rgba(20 / 255, 26 / 255, 46 / 255, 0.45);+ }++ // The panel's state pill: a soft fill of the dot's colour with lighter+ // text in dark mode (the Running and Paused pills on board 4.14).+ function pillText(level: string): color {+ switch (level) {+ case "running":+ return UI.Style.success;+ case "paused":+ case "starting":+ return UI.Style.accentText;+ case "updating":+ case "attention":+ return dot(level);+ }+ return UI.Style.inkMuted;+ }++ function pillFill(level: string): color {+ const c = dot(level);+ return level === "saved" || level === "off" ? UI.Style.tone(0.10) : Qt.rgba(c.r, c.g, c.b, dark ? 0.16 : 0.12);+ }++ // The taskbar behind the chip, for the ring that sets the dot off the+ // window mark.+ readonly property color bar: dark ? Qt.rgba(14 / 255, 18 / 255, 34 / 255, 0.88) : Qt.rgba(246 / 255, 248 / 255, 252 / 255, 0.92)+}diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/main.qml b/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/main.qmlnew file mode 100644index 0000000..f7baf1c--- /dev/null+++ b/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/main.qml@@ -0,0 +1,370 @@+pragma ComponentBehavior: Bound++import QtQuick+import org.kde.plasma.plasmoid+import org.kde.plasma.core as PlasmaCore+import org.kde.plasma.plasma5support as P5Support++// Windows mode's status at the left end of the taskbar, where Windows 11+// puts its weather (boards 4.13 and 4.14): what Windows mode is doing in a+// word, the memory it holds on hover, and a panel with processor use, memory+// and the Windows apps open. Everything comes from "wildos-winmode status",+// so it only appears once this account has Windows mode set up.+PlasmoidItem {+ id: winmode++ readonly property string statusCommand: "wildos-winmode status --if-set-up"++ // The agent's and the system service's status (winmode/agent.py and+ // winmode/system.py), as last read.+ property var agent: null+ property var system: null+ // False when Windows mode is set up but its services didn't reply.+ property bool answering: true+ property real now: Date.now()++ // {t: ms, cpu: QEMU's processor seconds}, the last minute and a bit.+ property var samples: []+ // Used when QEMU's processor count can't be read.+ property int hostCores: 0++ readonly property var setupRecord: system ? system.setup : null+ readonly property bool setUp: !answering || (system !== null && (system.vm || "") !== ""+ && !(setupRecord && setupRecord.running) && (!setupRecord || setupRecord.stage === "done"))+ readonly property bool shown: setUp && Plasmoid.configuration.shown++ readonly property var openApps: agent && Array.isArray(agent.openApps) ? agent.openApps : systemWindows(system)+ readonly property int appCount: {+ const ids = {};+ for (const w of openApps) {+ ids[w.id] = true;+ }+ return Object.keys(ids).length;+ }++ // One of: running, paused, saved, off, starting, updating, attention.+ // Not "state": Item has one.+ readonly property string level: levelFor(system, agent, answering, openApps.length)+ readonly property string stateText: ({+ running: appCount === 0 ? "Running" : appCount === 1 ? "Running, 1 app" : "Running, " + appCount + " apps",+ paused: "Paused",+ saved: "Saved to disk",+ off: "Not running",+ starting: "Starting",+ updating: "Updating",+ attention: "Needs attention"+ })[level]+ readonly property string pillText: ({+ running: "Running", paused: "Paused", saved: "Saved", off: "Off",+ starting: "Starting", updating: "Updating", attention: "Needs attention"+ })[level]++ readonly property var qemu: system && system.qemu ? system.qemu : null+ readonly property real memoryHeld: qemu ? Number(qemu.rss_bytes) || 0 : 0+ readonly property real memoryLimit: system ? Number(system.memory_bytes) || 0 : 0+ readonly property int processors: qemu && qemu.vcpus > 0 ? qemu.vcpus : Math.max(1, hostCores)+ readonly property var lastApp: agent && agent.lastApp && /^[a-z0-9-]+$/.test(agent.lastApp.id) ? agent.lastApp : null+ readonly property bool canSave: system !== null && system.save_to_disk === true+ readonly property bool busyAction: system !== null && !!system.action++ function levelFor(sys: var, ag: var, ok: bool, windows: int): string {+ if (!ok || !sys) {+ return "attention";+ }+ if (sys.state === "Error" || sys.error) {+ return "attention";+ }+ const busy = Array.isArray(sys.busy) ? sys.busy : [];+ if (busy.includes("update") || busy.includes("maintenance")) {+ return "updating";+ }+ if (ag && ag.starting && windows === 0) {+ return "starting";+ }+ return ({ Running: "running", Paused: "paused", Saved: "saved" })[sys.state] || "off";+ }++ // Without the agent, the system service's list still says what is open,+ // by program name.+ function systemWindows(sys: var): var {+ if (!sys || !Array.isArray(sys.windows)) {+ return [];+ }+ return sys.windows.filter(w => w && !w.owner && w.app).map(w => ({+ id: w.app, name: w.app.charAt(0).toUpperCase() + w.app.slice(1),+ icon: "wildos-windows-app", title: w.title || ""+ }));+ }++ function bytesText(bytes: real): string {+ if (bytes < 1073741824) {+ return Math.max(1, Math.round(bytes / 1048576)) + " MB";+ }+ const gb = bytes / 1073741824;+ return (gb >= 10 ? Math.round(gb) : Math.round(gb * 10) / 10) + " GB";+ }++ function plural(n: int, one: string, many: string): string {+ return n === 1 ? "1 " + one : n + " " + many;+ }++ // QEMU's processor seconds over the time between the first and last+ // sample, as a share of every processor Windows has.+ function share(from: var, to: var): real {+ const seconds = (to.t - from.t) / 1000;+ if (seconds <= 0) {+ return 0;+ }+ return Math.max(0, Math.min(100, (to.cpu - from.cpu) / seconds / processors * 100));+ }++ readonly property int processorPercent: samples.length < 2 ? 0 : Math.round(share(samples[0], samples[samples.length - 1]))++ // Each step between samples as {x: 0 to 1 across the last minute, y: %}.+ readonly property var processorTrace: {+ const out = [];+ const start = now - 60000;+ for (let i = 1; i < samples.length; i++) {+ out.push({ x: Math.max(0, (samples[i].t - start) / 60000), y: share(samples[i - 1], samples[i]) });+ }+ return out;+ }++ function addSample(q: var): void {+ if (!q || typeof q.cpu_seconds !== "number") {+ samples = [];+ return;+ }+ const t = Date.now();+ const last = samples.length > 0 ? samples[samples.length - 1] : null;+ // A lower count means a new QEMU (Windows started again).+ const kept = last && q.cpu_seconds >= last.cpu && q.pid === last.pid ? samples.filter(s => s.t >= t - 63000) : [];+ kept.push({ t: t, cpu: q.cpu_seconds, pid: q.pid });+ samples = kept;+ }++ function editionText(): string {+ const id = String(system && system.edition || "").toLowerCase();+ const names = {+ professional: "Windows 11 Pro", professionalworkstation: "Windows 11 Pro for Workstations",+ core: "Windows 11 Home", coresinglelanguage: "Windows 11 Home", corecountryspecific: "Windows 11 Home",+ enterprise: "Windows 11 Enterprise", education: "Windows 11 Education"+ };+ const name = names[id] || "Windows 11";+ const activated = setupRecord && setupRecord.licence ? setupRecord.licence.activated : null;+ return activated === true ? name + ", activated" : activated === false ? name + ", not activated" : name;+ }++ // When the idle action ran, from the system service's record of it.+ function sinceText(action: string, lead: string): string {+ const last = system ? system.last : null;+ if (!last || last.action !== action || !(last.at > 0)) {+ return "";+ }+ const minutes = Math.floor((now / 1000 - last.at) / 60);+ if (minutes < 1) {+ return lead + " just now";+ }+ if (minutes < 60) {+ return lead + " for " + plural(minutes, "minute", "minutes");+ }+ return lead + " since " + new Date(last.at * 1000).toLocaleTimeString(Qt.locale(), Locale.ShortFormat);+ }++ function subtitle(): string {+ switch (level) {+ case "running":+ return editionText();+ case "paused":+ return sinceText("pause", "Paused") || "Paused";+ case "saved":+ return sinceText("save", "Saved to disk") || "Saved to disk";+ case "off":+ return "Switched off";+ case "starting":+ return "Getting Windows ready";+ case "updating":+ return "Installing updates";+ }+ return "Needs attention";+ }++ // What the panel says the idle policy will do (winmode/lifecycle.py).+ // Saving to disk is off in the service for now, and then it pauses.+ function idleText(): string {+ if (!system) {+ return "";+ }+ const toDisk = canSave && (system.when_idle === "save" || (system.when_idle === "automatic" && system.on_battery));+ const seconds = Number(system.idle_seconds) || 60;+ const wait = seconds === 60 ? "a minute" : seconds % 60 === 0 ? plural(seconds / 60, "minute", "minutes") : plural(seconds, "second", "seconds");+ if (openApps.length > 0) {+ return (toDisk ? "Saves to disk " : "Pauses ") + wait + " after you close the last one.";+ }+ if (typeof system.idle_in === "number") {+ const left = Math.max(1, Math.round(system.idle_in));+ return "No Windows apps are open. " + (toDisk ? "Saves to disk in " : "Pauses in ") + plural(left, "second", "seconds") + ".";+ }+ return "";+ }++ function attentionText(): string {+ if (!answering || !system) {+ return "Windows mode isn't answering. Restart the PC, then try again.";+ }+ if (system.state === "Error") {+ return "Windows stopped unexpectedly. Restart the PC, then open a Windows app to start it again.";+ }+ const last = system.last && system.last.action === "save" ? "save Windows to disk" : "pause Windows";+ return "Windows mode couldn't " + last + ", so it's still using memory. Restarting the PC puts it right.";+ }++ P5Support.DataSource {+ id: reader+ engine: "executable"+ // Each read is its own source (a numbered comment): the engine hands+ // a source it already has its last output instead of running it.+ property string current: ""+ onNewData: (source, data) => {+ disconnectSource(source);+ if (source === current) {+ current = "";+ winmode.receive(String(data.stdout));+ }+ }+ }++ property int readCount: 0+ property int misses: 0++ function refresh(): void {+ if (reader.current !== "") {+ return;+ }+ readCount += 1;+ reader.current = statusCommand + " #" + readCount;+ reader.connectSource(reader.current);+ }++ function receive(stdout: string): void {+ let parsed;+ try {+ parsed = JSON.parse(stdout);+ } catch (e) {+ return;+ }+ if (!parsed || typeof parsed !== "object") {+ return;+ }+ // The services can be slow to answer while the desktop is still+ // starting, so one miss is never shown as a problem.+ if (parsed.answering === false && misses < 1) {+ misses += 1;+ return;+ }+ misses = 0;+ now = Date.now();+ answering = parsed.answering !== false;+ agent = parsed.agent && typeof parsed.agent === "object" ? parsed.agent : null;+ system = parsed.system && typeof parsed.system === "object" ? parsed.system : null;+ addSample(qemu);+ if (!shown) {+ expanded = false;+ }+ }++ // Every second while the panel is open, for the processor graph and the+ // memory figure; every ten seconds behind the chip; once a minute on a PC that hasn't+ // set Windows mode up, which costs a check for a file and nothing more.+ Timer {+ running: true+ repeat: true+ triggeredOnStart: true+ interval: winmode.expanded ? 1000 : winmode.setUp ? 10000 : 60000+ onTriggered: winmode.refresh()+ }++ P5Support.DataSource {+ id: shell+ engine: "executable"+ onNewData: (source, data) => {+ disconnectSource(source);+ winmode.commandFinished(source, String(data.stdout).trim());+ }+ }++ property int runCount: 0++ function run(command: string): void {+ runCount += 1;+ shell.connectSource(command + " #" + runCount);+ }++ function commandFinished(command: string, answer: string): void {+ if (command.indexOf("nproc") === 0) {+ hostCores = parseInt(answer, 10) || 0;+ return;+ }+ refresh();+ }++ function pauseNow(): void {+ run("wildos-winmode idle pause");+ }++ function saveToDisk(): void {+ run("wildos-winmode idle save");+ }++ // The app's Start entry through kstart, the way Task Manager and Start+ // open Windows apps, so the taskbar shows it starting.+ function openApp(id: string): void {+ if (!/^[a-z0-9-]+$/.test(id)) {+ return;+ }+ const entry = "wildos-winmode-" + id;+ run("if command -v kstart >/dev/null 2>&1 && [ -e \"${XDG_DATA_HOME:-$HOME/.local/share}/applications/" + entry + ".desktop\" ]; "+ + "then kstart --application " + entry + "; else wildos-winmode launch " + id + "; fi");+ expanded = false;+ }++ // Settings ships with Wild OS, but if it has gone the click still says+ // something rather than doing nothing.+ function openSettings(): void {+ run("if command -v wildos-settings >/dev/null; then setsid -f wildos-settings --page windowsmode >/dev/null 2>&1; "+ + "else notify-send -a 'Wild OS' -i preferences-system 'Settings is missing' "+ + "'Reinstall it from the Store to change this.'; fi");+ expanded = false;+ }++ onExpandedChanged: () => {+ if (winmode.expanded) {+ now = Date.now();+ refresh();+ }+ }++ Plasmoid.backgroundHints: PlasmaCore.Types.NoBackground+ Plasmoid.icon: "wildos-windows-app"+ Plasmoid.title: "Windows mode"+ Plasmoid.status: !shown ? PlasmaCore.Types.HiddenStatus+ : level === "attention" ? PlasmaCore.Types.NeedsAttentionStatus : PlasmaCore.Types.PassiveStatus+ toolTipMainText: "Windows mode: " + stateText.charAt(0).toLowerCase() + stateText.slice(1)+ toolTipSubText: level === "attention" ? attentionText()+ : memoryHeld > 0 ? bytesText(memoryHeld) + " of memory held" : "Holding no memory"++ preferredRepresentation: compactRepresentation+ compactRepresentation: Chip {+ winmode: winmode+ }+ fullRepresentation: StatusPanel {+ winmode: winmode+ }++ Component.onCompleted: {+ if (Plasmoid.hasOwnProperty("activationTogglesExpanded")) {+ Plasmoid.activationTogglesExpanded = true;+ }+ run("nproc");+ }+}diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/qmldir b/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/qmldirnew file mode 100644index 0000000..b322b3b--- /dev/null+++ b/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/qmldir@@ -0,0 +1 @@+singleton Tones 1.0 Tones.qmldiff --git a/packages/wildos-branding/files/plasmoids/org.wildos.winmode/metadata.json b/packages/wildos-branding/files/plasmoids/org.wildos.winmode/metadata.jsonnew file mode 100644index 0000000..b9d77b3--- /dev/null+++ b/packages/wildos-branding/files/plasmoids/org.wildos.winmode/metadata.json@@ -0,0 +1,15 @@+{+ "KPlugin": {+ "Authors": [{ "Email": "[email protected]", "Name": "Wild OS" }],+ "Category": "System Information",+ "Description": "Shows what Windows mode is doing, the memory it holds and the Windows apps open",+ "Icon": "wildos-windows-app",+ "Id": "org.wildos.winmode",+ "License": "GPL-3.0-or-later",+ "Name": "Windows mode",+ "Version": "0.1.0",+ "Website": "https://wildos.io"+ },+ "KPackageStructure": "Plasma/Applet",+ "X-Plasma-API-Minimum-Version": "6.0"+}diff --git a/packages/wildos-branding/files/sddm/wildos/components/LockClock.qml b/packages/wildos-branding/files/sddm/wildos/components/LockClock.qmlindex 69c91c4..2ce6592 100644--- a/packages/wildos-branding/files/sddm/wildos/components/LockClock.qml+++ b/packages/wildos-branding/files/sddm/wildos/components/LockClock.qml@@ -2,7 +2,8 @@ import QtQuickimport QtQuick.Effectsimport WildOS.UI as UI-// Day-first date over a large 24-hour time, as on the lock screen. The time+// The date over a large time, as on the lock screen, both in the regional+// format; the time leaves out AM and PM, as Windows does here. The time// box is exactly 136px tall like the design's line-height: 1, so the glyphs// are shifted up by half the font's extra leading.Item {@@ -10,6 +11,9 @@ Item {property date now: new Date()+ readonly property string dateFormat: Qt.locale().dateFormat(Locale.LongFormat).replace(/[,.\s]*y+[.年]?/, "").trim()+ .replace(/^dddd, d MMMM$/, "dddd d MMMM")+implicitWidth: Math.max(dateLabel.implicitWidth, timeLabel.implicitWidth)implicitHeight: dateLabel.height + 6 + timeBox.height@@ -35,7 +39,7 @@ Item {Text {id: dateLabelanchors.horizontalCenter: parent.horizontalCenter- text: Qt.locale().toString(clock.now, "dddd d MMMM")+ text: Qt.locale("en_GB").toString(clock.now, clock.dateFormat)font.family: UI.Style.fontFamilyfont.pixelSize: UI.Style.px(22)font.weight: Font.Normal@@ -54,7 +58,7 @@ Item {id: timeLabelanchors.horizontalCenter: parent.horizontalCentery: (136 - timeMetrics.height) / 2- text: Qt.formatTime(clock.now, "HH:mm")+ text: Qt.locale().toString(clock.now, Qt.locale().timeFormat(Locale.ShortFormat)).replace(Qt.locale().amText, "").replace(Qt.locale().pmText, "").trim()font.family: "Inter Display"renderType: Text.CurveRenderingfont.pixelSize: 136diff --git a/packages/wildos-branding/files/sounds/wildos/index.theme b/packages/wildos-branding/files/sounds/wildos/index.themenew file mode 100644index 0000000..fb0bf17--- /dev/null+++ b/packages/wildos-branding/files/sounds/wildos/index.theme@@ -0,0 +1,10 @@+[Sound Theme]+Name=Wild OS+Comment=Deep, warm and restrained, made for Wild OS+# Anything an app asks for that Wild OS has no sound of its own for comes+# from the freedesktop set, never KDE's Ocean, so the two styles don't mix.+Inherits=freedesktop+Directories=stereo++[stereo]+OutputProfile=stereodiff --git a/packages/wildos-branding/files/sounds/wildos/stereo/audio-volume-change.oga b/packages/wildos-branding/files/sounds/wildos/stereo/audio-volume-change.oganew file mode 100644index 0000000..7a76783Binary files /dev/null and b/packages/wildos-branding/files/sounds/wildos/stereo/audio-volume-change.oga differdiff --git a/packages/wildos-branding/files/sounds/wildos/stereo/battery-caution.oga b/packages/wildos-branding/files/sounds/wildos/stereo/battery-caution.oganew file mode 100644index 0000000..11e9a17Binary files /dev/null and b/packages/wildos-branding/files/sounds/wildos/stereo/battery-caution.oga differdiff --git a/packages/wildos-branding/files/sounds/wildos/stereo/battery-full.oga b/packages/wildos-branding/files/sounds/wildos/stereo/battery-full.oganew file mode 100644index 0000000..e269581Binary files /dev/null and b/packages/wildos-branding/files/sounds/wildos/stereo/battery-full.oga differdiff --git a/packages/wildos-branding/files/sounds/wildos/stereo/battery-low.oga b/packages/wildos-branding/files/sounds/wildos/stereo/battery-low.oganew file mode 100644index 0000000..d9a7f29Binary files /dev/null and b/packages/wildos-branding/files/sounds/wildos/stereo/battery-low.oga differdiff --git a/packages/wildos-branding/files/sounds/wildos/stereo/bell.oga b/packages/wildos-branding/files/sounds/wildos/stereo/bell.oganew file mode 100644index 0000000..efdef59Binary files /dev/null and b/packages/wildos-branding/files/sounds/wildos/stereo/bell.oga differdiff --git a/packages/wildos-branding/files/sounds/wildos/stereo/complete.oga b/packages/wildos-branding/files/sounds/wildos/stereo/complete.oganew file mode 100644index 0000000..271d70eBinary files /dev/null and b/packages/wildos-branding/files/sounds/wildos/stereo/complete.oga differdiff --git a/packages/wildos-branding/files/sounds/wildos/stereo/completion-fail.oga b/packages/wildos-branding/files/sounds/wildos/stereo/completion-fail.oganew file mode 100644index 0000000..af57264Binary files /dev/null and b/packages/wildos-branding/files/sounds/wildos/stereo/completion-fail.oga differdiff --git a/packages/wildos-branding/files/sounds/wildos/stereo/completion-rotation.oga b/packages/wildos-branding/files/sounds/wildos/stereo/completion-rotation.oganew file mode 100644index 0000000..8486c04Binary files /dev/null and b/packages/wildos-branding/files/sounds/wildos/stereo/completion-rotation.oga differdiff --git a/packages/wildos-branding/files/sounds/wildos/stereo/desktop-login.oga b/packages/wildos-branding/files/sounds/wildos/stereo/desktop-login.oganew file mode 100644index 0000000..892e036Binary files /dev/null and b/packages/wildos-branding/files/sounds/wildos/stereo/desktop-login.oga differdiff --git a/packages/wildos-branding/files/sounds/wildos/stereo/desktop-logout.oga b/packages/wildos-branding/files/sounds/wildos/stereo/desktop-logout.oganew file mode 100644index 0000000..c852931Binary files /dev/null and b/packages/wildos-branding/files/sounds/wildos/stereo/desktop-logout.oga differdiff --git a/packages/wildos-branding/files/sounds/wildos/stereo/device-added.oga b/packages/wildos-branding/files/sounds/wildos/stereo/device-added.oganew file mode 100644index 0000000..41fd48cBinary files /dev/null and b/packages/wildos-branding/files/sounds/wildos/stereo/device-added.oga differdiff --git a/packages/wildos-branding/files/sounds/wildos/stereo/device-removed.oga b/packages/wildos-branding/files/sounds/wildos/stereo/device-removed.oganew file mode 100644index 0000000..d2c3843Binary files /dev/null and b/packages/wildos-branding/files/sounds/wildos/stereo/device-removed.oga differdiff --git a/packages/wildos-branding/files/sounds/wildos/stereo/dialog-error-critical.oga b/packages/wildos-branding/files/sounds/wildos/stereo/dialog-error-critical.oganew file mode 100644index 0000000..c24e761Binary files /dev/null and b/packages/wildos-branding/files/sounds/wildos/stereo/dialog-error-critical.oga differdiff --git a/packages/wildos-branding/files/sounds/wildos/stereo/dialog-error.oga b/packages/wildos-branding/files/sounds/wildos/stereo/dialog-error.oganew file mode 100644index 0000000..0487953Binary files /dev/null and b/packages/wildos-branding/files/sounds/wildos/stereo/dialog-error.oga differdiff --git a/packages/wildos-branding/files/sounds/wildos/stereo/dialog-information.oga b/packages/wildos-branding/files/sounds/wildos/stereo/dialog-information.oganew file mode 100644index 0000000..1ea361bBinary files /dev/null and b/packages/wildos-branding/files/sounds/wildos/stereo/dialog-information.oga differdiff --git a/packages/wildos-branding/files/sounds/wildos/stereo/dialog-question.oga b/packages/wildos-branding/files/sounds/wildos/stereo/dialog-question.oganew file mode 100644index 0000000..de4a42bBinary files /dev/null and b/packages/wildos-branding/files/sounds/wildos/stereo/dialog-question.oga differdiff --git a/packages/wildos-branding/files/sounds/wildos/stereo/dialog-warning.oga b/packages/wildos-branding/files/sounds/wildos/stereo/dialog-warning.oganew file mode 100644index 0000000..7c874c6Binary files /dev/null and b/packages/wildos-branding/files/sounds/wildos/stereo/dialog-warning.oga differdiff --git a/packages/wildos-branding/files/sounds/wildos/stereo/message-new-instant.oga b/packages/wildos-branding/files/sounds/wildos/stereo/message-new-instant.oganew file mode 100644index 0000000..9767c25Binary files /dev/null and b/packages/wildos-branding/files/sounds/wildos/stereo/message-new-instant.oga differdiff --git a/packages/wildos-branding/files/sounds/wildos/stereo/message.oga b/packages/wildos-branding/files/sounds/wildos/stereo/message.oganew file mode 100644index 0000000..2b5d33aBinary files /dev/null and b/packages/wildos-branding/files/sounds/wildos/stereo/message.oga differdiff --git a/packages/wildos-branding/files/sounds/wildos/stereo/power-plug.oga b/packages/wildos-branding/files/sounds/wildos/stereo/power-plug.oganew file mode 100644index 0000000..4960f0dBinary files /dev/null and b/packages/wildos-branding/files/sounds/wildos/stereo/power-plug.oga differdiff --git a/packages/wildos-branding/files/sounds/wildos/stereo/power-unplug.oga b/packages/wildos-branding/files/sounds/wildos/stereo/power-unplug.oganew file mode 100644index 0000000..7fe9ba9Binary files /dev/null and b/packages/wildos-branding/files/sounds/wildos/stereo/power-unplug.oga differdiff --git a/packages/wildos-branding/files/sounds/wildos/stereo/screen-capture.oga b/packages/wildos-branding/files/sounds/wildos/stereo/screen-capture.oganew file mode 100644index 0000000..e9d9089Binary files /dev/null and b/packages/wildos-branding/files/sounds/wildos/stereo/screen-capture.oga differdiff --git a/packages/wildos-branding/files/sounds/wildos/stereo/trash-empty.oga b/packages/wildos-branding/files/sounds/wildos/stereo/trash-empty.oganew file mode 100644index 0000000..62a693fBinary files /dev/null and b/packages/wildos-branding/files/sounds/wildos/stereo/trash-empty.oga differdiff --git a/packages/wildos-branding/files/systemd/usbguard.service.d/wildos-release.conf b/packages/wildos-branding/files/systemd/usbguard.service.d/wildos-release.confnew file mode 100644index 0000000..1890ea9--- /dev/null+++ b/packages/wildos-branding/files/systemd/usbguard.service.d/wildos-release.conf@@ -0,0 +1,4 @@+# USB protection off means USB works again: see /usr/libexec/wildos/usb-release.+# The + runs it outside the service's sandbox, which keeps /sys read-only.+[Service]+ExecStopPost=+/usr/libexec/wildos/usb-releasediff --git a/packages/wildos-branding/files/themes/dawn.json b/packages/wildos-branding/files/themes/dawn.jsonnew file mode 100644index 0000000..3a650e8--- /dev/null+++ b/packages/wildos-branding/files/themes/dawn.json@@ -0,0 +1,26 @@+{+ "id": "dawn",+ "name": "Dawn",+ "order": 1,+ "default": true,+ "description": "The Wild OS look. Calm and easy on the eyes, day or night.",+ "mode": "dark",+ "accent": {+ "name": "Glacier",+ "colour": "#8fb4ff"+ },+ "textOnAccent": "#0f1530",+ "accentText": "#b9cfff",+ "glass": {+ "colour": "#121628",+ "alpha": 0.86+ },+ "wallpaper": "/usr/share/wallpapers/WildOS",+ "moreWallpapers": [+ "/usr/share/wallpapers/WildOS-fog-ridges",+ "/usr/share/wallpapers/WildOS-fog-ridges-evening",+ "/usr/share/wallpapers/WildOS-misty-lake-sunrise"+ ],+ "underglow": false,+ "desktopTheme": "wildos"+}diff --git a/packages/wildos-branding/files/themes/ember.json b/packages/wildos-branding/files/themes/ember.jsonnew file mode 100644index 0000000..fb40b37--- /dev/null+++ b/packages/wildos-branding/files/themes/ember.json@@ -0,0 +1,21 @@+{+ "id": "ember",+ "name": "Ember",+ "order": 5,+ "default": false,+ "description": "Warm, low-blue tones for evenings. Pairs with Night light.",+ "mode": "dark",+ "accent": {+ "name": "Ember",+ "colour": "#ff8a5c"+ },+ "textOnAccent": "#0f1530",+ "accentText": "#ffb99d",+ "glass": {+ "colour": "#1c121a",+ "alpha": 0.86+ },+ "wallpaper": "/usr/share/wallpapers/WildOS-white-dunes",+ "underglow": false,+ "desktopTheme": "wildos-ember"+}diff --git a/packages/wildos-branding/files/themes/estuary.json b/packages/wildos-branding/files/themes/estuary.jsonnew file mode 100644index 0000000..e01c0ca--- /dev/null+++ b/packages/wildos-branding/files/themes/estuary.json@@ -0,0 +1,26 @@+{+ "id": "estuary",+ "name": "Estuary",+ "order": 6,+ "default": false,+ "description": "Fresh and airy, like a walk along the coast.",+ "mode": "light",+ "accent": {+ "name": "Sea",+ "colour": "#1b9a8f"+ },+ "textOnAccent": "#0f1530",+ "accentText": "#11625b",+ "glass": {+ "colour": "#fafbfe",+ "alpha": 0.82+ },+ "wallpaper": "/usr/share/wallpapers/WildOS-snowdonia",+ "moreWallpapers": [+ "/usr/share/wallpapers/WildOS-llandudno",+ "/usr/share/wallpapers/WildOS-penmaenpool",+ "/usr/share/wallpapers/WildOS-ogmore-by-sea"+ ],+ "underglow": false,+ "desktopTheme": "wildos-light"+}diff --git a/packages/wildos-branding/files/themes/graphite.json b/packages/wildos-branding/files/themes/graphite.jsonnew file mode 100644index 0000000..89bba39--- /dev/null+++ b/packages/wildos-branding/files/themes/graphite.json@@ -0,0 +1,25 @@+{+ "id": "graphite",+ "name": "Graphite",+ "order": 3,+ "default": false,+ "description": "Minimal and quiet, so nothing competes with your work.",+ "mode": "dark",+ "accent": {+ "name": "Silver",+ "colour": "#c9ced8"+ },+ "textOnAccent": "#06120a",+ "accentText": "#dfe2e8",+ "glass": {+ "colour": "#0e1016",+ "alpha": 0.86+ },+ "wallpaper": "/usr/share/wallpapers/WildOS-black-curve",+ "moreWallpapers": [+ "/usr/share/wallpapers/WildOS-dark-waves",+ "/usr/share/wallpapers/WildOS-storm-lake"+ ],+ "underglow": false,+ "desktopTheme": "wildos-graphite"+}diff --git a/packages/wildos-branding/files/themes/orchard.json b/packages/wildos-branding/files/themes/orchard.jsonnew file mode 100644index 0000000..871dbb9--- /dev/null+++ b/packages/wildos-branding/files/themes/orchard.json@@ -0,0 +1,21 @@+{+ "id": "orchard",+ "name": "Orchard",+ "order": 2,+ "default": false,+ "description": "Bright, soft and clean. For daytime and creative work.",+ "mode": "light",+ "accent": {+ "name": "Sky",+ "colour": "#1f7aec"+ },+ "textOnAccent": "#0b1020",+ "accentText": "#0f55ad",+ "glass": {+ "colour": "#fafbfe",+ "alpha": 0.82+ },+ "wallpaper": "/usr/share/wallpapers/WildOS-golden-haze",+ "underglow": false,+ "desktopTheme": "wildos-light"+}diff --git a/packages/wildos-branding/files/themes/overclock.json b/packages/wildos-branding/files/themes/overclock.jsonnew file mode 100644index 0000000..2ebaaf4--- /dev/null+++ b/packages/wildos-branding/files/themes/overclock.json@@ -0,0 +1,29 @@+{+ "id": "overclock",+ "name": "Overclock",+ "order": 4,+ "default": false,+ "description": "Black glass and neon green for gaming setups, with lighting that follows your accent.",+ "mode": "dark",+ "accent": {+ "name": "Neon",+ "colour": "#3dff7a"+ },+ "textOnAccent": "#06120a",+ "accentText": "#8bffaf",+ "glass": {+ "colour": "#0a0d0c",+ "alpha": 0.88+ },+ "taskbarGlass": {+ "colour": "#080a09",+ "alpha": 0.92+ },+ "wallpaper": "/usr/share/wallpapers/WildOS-green-lines",+ "moreWallpapers": [+ "/usr/share/wallpapers/WildOS-green-ribbons",+ "/usr/share/wallpapers/WildOS-spectrum"+ ],+ "underglow": true,+ "desktopTheme": "wildos-overclock"+}diff --git a/packages/wildos-branding/files/wallpaper-metadata.json b/packages/wildos-branding/files/wallpaper-metadata.jsonindex 7d3c914..cd7ce84 100644--- a/packages/wildos-branding/files/wallpaper-metadata.json+++ b/packages/wildos-branding/files/wallpaper-metadata.json@@ -7,6 +7,6 @@],"Id": "WildOS","License": "Pexels License",- "Name": "Wild OS"+ "Name": "Dawn"}}diff --git a/packages/wildos-branding/files/xdg/autostart/wildos-taskbar-items.desktop b/packages/wildos-branding/files/xdg/autostart/wildos-taskbar-items.desktopnew file mode 100644index 0000000..2815315--- /dev/null+++ b/packages/wildos-branding/files/xdg/autostart/wildos-taskbar-items.desktop@@ -0,0 +1,7 @@+[Desktop Entry]+Type=Application+Name=Wild OS taskbar items+Exec=/usr/libexec/wildos/taskbar-items+OnlyShowIn=KDE;+NoDisplay=true+X-KDE-autostart-phase=2diff --git a/packages/wildos-branding/files/xdg/kdeglobals b/packages/wildos-branding/files/xdg/kdeglobalsindex a7dcbbb..751a463 100644--- a/packages/wildos-branding/files/xdg/kdeglobals+++ b/packages/wildos-branding/files/xdg/kdeglobals@@ -59,3 +59,7 @@ ghns=false# nothing and has no such setting.[KDE Control Module Restrictions]kcm_feedback=false++# Wild OS's own sounds (/usr/share/sounds/wildos), in place of KDE's Ocean.+[Sounds]+Theme=wildosdiff --git a/packages/wildos-branding/files/xdg/mimeapps.list b/packages/wildos-branding/files/xdg/mimeapps.listindex 1535de9..427f6b0 100644--- a/packages/wildos-branding/files/xdg/mimeapps.list+++ b/packages/wildos-branding/files/xdg/mimeapps.list@@ -9,10 +9,22 @@ x-scheme-handler/about=brave-browser.desktopx-scheme-handler/unknown=brave-browser.desktopapplication/pdf=org.kde.okular.desktop+# Email links open in Wild OS Mail.+x-scheme-handler/mailto=org.wildos.mail.desktop+# Folders open in Wild OS Files, links to apps in the Wild OS Store.inode/directory=org.wildos.files.desktopx-scheme-handler/appstream=org.wildos.store.desktop+# Package files open on their own install page in the Store, which says+# plainly that nothing has checked them.+application/vnd.debian.binary-package=org.wildos.store.desktop+application/x-deb=org.wildos.store.desktop+application/vnd.flatpak.ref=org.wildos.store.desktop+application/x-flatpak-ref=org.wildos.store.desktop+application/vnd.flatpak=org.wildos.store.desktop+application/x-flatpak=org.wildos.store.desktop+# Windows programs open in the App Bridge, which explains what will happen# and runs them in a sandbox.application/x-ms-dos-executable=org.wildos.run.desktopdiff --git a/packages/wildos-branding/files/xdg/plasma_workspace.notifyrc b/packages/wildos-branding/files/xdg/plasma_workspace.notifyrcnew file mode 100644index 0000000..220aeaa--- /dev/null+++ b/packages/wildos-branding/files/xdg/plasma_workspace.notifyrc@@ -0,0 +1,5 @@+# A sound when the desktop starts, as Windows plays one; signing out stays+# silent, as it does on Windows. Settings > Sound turns the start-up sound+# off. The sound itself is desktop-login in the Wild OS sound theme.+[Event/startkde]+Action=Sounddiff --git a/packages/wildos-branding/tools/sounds/make-sounds.py b/packages/wildos-branding/tools/sounds/make-sounds.pynew file mode 100644index 0000000..d293cb2--- /dev/null+++ b/packages/wildos-branding/tools/sounds/make-sounds.py@@ -0,0 +1,394 @@+#!/usr/bin/env python3+"""Synthesises the Wild OS sound theme from scratch.++ python3 make-sounds.py OUT_DIR++Deep, warm and restrained: one voice (mostly sine and triangle, a touch of+saw, through a low-pass filter that breathes as each note starts), a low+register, D minor 9 harmony, no slides or effects for their own sake. The+signature is the W (down, up, down, up), which the start-up states in full+and the other sounds borrow a step of. The lowest notes carry their+overtones so their depth survives a laptop's small speakers.++Writes OUT_DIR/stereo/<name>.oga (Ogg Vorbis, 48 kHz stereo) for every name+in the freedesktop sound naming spec that Plasma's notifications ask for.+Names that share a sound are links, made by the package (debian/links).+Needs numpy, scipy and ffmpeg; the build machine has none of them, so the+rendered files are kept in the repository and rebuilt by hand.+"""++import os+import subprocess+import sys+import wave++import numpy as np+from scipy.signal import butter, fftconvolve, sosfilt++RATE = 48000+++def T(s):+ return np.arange(int(s * RATE)) / RATE+++def bl_osc(freq_curve, shape):+ """Band-limited oscillator following a per-sample frequency curve.+ shape: 'saw', 'tri', 'sine'. Built from harmonics up to 12 kHz."""+ phase = 2 * np.pi * np.cumsum(freq_curve) / RATE+ f0 = float(np.max(freq_curve))+ out = np.zeros_like(phase)+ if shape == "sine":+ return np.sin(phase)+ k = 1+ while f0 * k < 12000 and k < 40:+ if shape == "saw":+ out += np.sin(k * phase) / k+ elif shape == "square" and k % 2:+ out += np.sin(k * phase) / k+ elif shape == "tri" and k % 2:+ out += ((-1) ** ((k - 1) // 2)) * np.sin(k * phase) / (k * k)+ k += 1+ return out / (0.9 if shape == "saw" else 0.8)+++def svf_lowpass(x, cutoff_curve, q=0.8):+ """Chamberlin state-variable low-pass with a cutoff that moves sample by+ sample, so the filter really sweeps (the 'bloom' of a synth note)."""+ low = band = 0.0+ out = np.empty_like(x)+ damp = 1.0 / q+ fc = np.clip(cutoff_curve, 20, RATE / 6)+ f = 2 * np.sin(np.pi * fc / RATE)+ for i in range(len(x)):+ low += f[i] * band+ high = x[i] - low - damp * band+ band += f[i] * high+ out[i] = low+ return out+++rng = np.random.default_rng(1971)+N = {"D1": 36.71, "A1": 55.0, "D2": 73.42, "E2": 82.41, "F2": 87.31, "G2": 98.0, "A2": 110.0,+ "C3": 130.81, "D3": 146.83, "E3": 164.81, "F3": 174.61, "G3": 196.0, "A3": 220.0, "C4": 261.63,+ "D4": 293.66, "E4": 329.63, "F4": 349.23, "A4": 440.0}+++def hz(n):+ return N[n] if isinstance(n, str) else n+++def lp(x, f, o=2):+ return sosfilt(butter(o, f, "low", fs=RATE, output="sos"), x)+++def hp(x, f, o=2):+ return sosfilt(butter(o, f, "high", fs=RATE, output="sos"), x)+++def warm(note, dur, attack=0.03, release=0.3, gain=0.5, breathe=2.2, rest=1.3, breathe_t=0.08, pan=0.0, edge=0.18):+ """The voice. edge: how much saw is in it (the only bright part).+ breathe/rest: the filter's cutoff, as multiples of the pitch, at its+ brief opening and at rest. No pitch movement at all."""+ f = hz(note)+ t = T(dur)+ curve = np.full(len(t), f)+ layers = (("sine", 0, 0.55, 0.0), ("tri", 4, 0.42, -0.5), ("tri", -4, 0.42, 0.5), ("saw", 0, edge, 0.0),+ ("sine", -1200, 0.22, 0.0))+ left = np.zeros_like(t)+ right = np.zeros_like(t)+ for shape, cents, g, side in layers:+ osc = bl_osc(curve * 2 ** (cents / 1200), shape) * g+ left += osc * np.cos((side + 1) * np.pi / 4)+ right += osc * np.sin((side + 1) * np.pi / 4)+ cut = f * (rest + (breathe - rest) * np.exp(-t / breathe_t) * np.clip(t / 0.01, 0, 1))+ amp = np.clip(t / attack, 0, 1) ** 1.4 * np.clip((dur - t) / release, 0, 1) ** 1.8 * gain+ l = svf_lowpass(left, cut, 0.8) * amp+ r = svf_lowpass(right, cut, 0.8) * amp+ # Small speakers can't play the lowest notes, but the ear rebuilds a+ # fundamental from its overtones. So low notes carry their 2nd to 5th+ # harmonics, added after the filter (which would otherwise remove them),+ # strongly enough to be heard as deep on a laptop.+ if f < 160:+ lift = min(1.0, (160 - f) / 90) * 0.5 + 0.5+ over = sum(np.sin(2 * np.pi * f * k * t + k) * g for k, g in ((2, 0.34), (3, 0.22), (4, 0.12), (5, 0.06)))+ over = over * amp * lift+ l = l + over+ r = r + over+ return np.vstack([l * np.cos((pan + 1) * np.pi / 4) * 1.41, r * np.sin((pan + 1) * np.pi / 4) * 1.41])+++def chord(notes, at, dur, gain, **k):+ return [(at, warm(n, dur, gain=gain, pan=(-0.5 + i / max(len(notes) - 1, 1)) * 0.8, **k)) for i, n in enumerate(notes)]+++def place(parts, dur):+ out = np.zeros((2, int(dur * RATE)))+ for at, sig in parts:+ i = int(at * RATE)+ n = min(sig.shape[1], out.shape[1] - i)+ out[:, i:i + n] += sig[:, :n]+ return out+++def space(x, size, wet, damp=3000):+ L = int(size * RATE)+ t = np.arange(L) / RATE+ out = np.zeros((2, x.shape[1] + L - 1))+ for ch in range(2):+ ir = rng.standard_normal(L) * np.exp(-t / size * 5.0)+ ir = hp(lp(ir, damp), 140)+ ir[: int(0.02 * RATE)] = 0+ ir /= np.sqrt(np.sum(ir ** 2))+ out[ch] = np.pad(x[ch], (0, L - 1)) * (1 - wet) + fftconvolve(x[ch], ir) * wet * 2.0+ return out+++def finish(x, peak_db, floor=-54):+ x = x / np.max(np.abs(x))+ x = np.tanh(x * 1.15) / np.tanh(1.15)+ x = np.vstack([hp(c, 30) for c in x])+ # Presence around 700 Hz to 2.5 kHz, gently, so low notes still read on+ # a laptop's small speakers.+ x = np.vstack([c + 0.3 * sosfilt(butter(2, [700, 2500], "band", fs=RATE, output="sos"), c) for c in x])+ e = np.max(np.abs(x), axis=0)+ last = np.max(np.nonzero(e > 10 ** (floor / 20) * e.max()))+ x = x[:, : last + int(0.03 * RATE)]+ fd = int(0.06 * RATE)+ x[:, -fd:] *= np.linspace(1, 0, fd) ** 2+ return x / np.max(np.abs(x)) * 10 ** (peak_db / 20)+++S = {}+++def sound(name, peak):+ def reg(fn):+ S[name] = (fn, peak)+ return fn+ return reg+++# D minor 9, voiced low and open.+DM9 = ["D2", "A2", "F3", "C4", "E4"]+W = ["A3", "D3", "F3", "D3", "A3"]+++@sound("desktop-login", -4)+def login():+ # One chord that blooms open over a second and a half, the W stated+ # softly inside it, then a low D that grounds it.+ parts = chord(DM9, 0.0, 4.6, 0.16, attack=1.3, release=1.8, breathe=2.6, rest=1.8, breathe_t=1.6, edge=0.12)+ for i, (n, at) in enumerate(zip(W, (1.5, 1.72, 1.94, 2.16, 2.45))):+ parts.append((at, warm(n, 0.45 if i < 4 else 1.6, attack=0.04, release=0.25 if i < 4 else 1.0, gain=0.24,+ breathe=2.6, rest=1.4, pan=-0.3 + i * 0.15)))+ parts.append((2.45, warm("D1", 2.2, attack=0.25, release=1.4, gain=0.35, rest=1.1, breathe=1.3, edge=0.0)))+ return space(place(parts, 4.8), size=2.4, wet=0.26)+++@sound("desktop-logout", -5)+def logout():+ parts = []+ for i, (n, at) in enumerate(zip(["A3", "F3", "D3"], (0.0, 0.24, 0.5))):+ parts.append((at, warm(n, 0.45 if i < 2 else 1.6, attack=0.05, release=0.25 if i < 2 else 1.0, gain=0.38)))+ parts += chord(["D2", "A2", "F3"], 0.5, 2.0, 0.17, attack=0.4, release=1.3, breathe=1.8, rest=1.3)+ return space(place(parts, 2.6), size=2.0, wet=0.24)+++@sound("message-new-instant", -8)+def notification():+ # The end of the W, down then up, over a quiet low fifth.+ parts = [(0.0, warm("F3", 0.24, attack=0.012, release=0.12, gain=0.5, breathe=3.0)),+ (0.14, warm("A3", 0.5, attack=0.012, release=0.32, gain=0.5, breathe=3.0))]+ parts += chord(["D2", "A2"], 0.0, 0.6, 0.18, attack=0.03, release=0.35, breathe=1.6, rest=1.2, edge=0.05)+ return space(place(parts, 0.8), size=0.8, wet=0.16)+++@sound("message", -9)+def message():+ parts = [(0.0, warm("A3", 0.45, attack=0.012, release=0.3, gain=0.55, breathe=2.8))]+ parts += chord(["D2"], 0.0, 0.45, 0.2, attack=0.02, release=0.3, edge=0.0)+ return space(place(parts, 0.6), size=0.7, wet=0.14)+++@sound("complete", -8)+def complete():+ parts = []+ for i, (n, at) in enumerate(zip(["D3", "F3", "A3"], (0.0, 0.12, 0.24))):+ parts.append((at, warm(n, 0.3 if i < 2 else 0.8, attack=0.012, release=0.15 if i < 2 else 0.5, gain=0.42, breathe=2.8)))+ parts += chord(["D2", "A2", "E3"], 0.24, 0.9, 0.14, attack=0.08, release=0.55, breathe=1.8, rest=1.3)+ return space(place(parts, 1.2), size=1.0, wet=0.18)+++@sound("dialog-information", -10)+def information():+ parts = [(0.0, warm("D3", 0.45, attack=0.015, release=0.3, gain=0.5, breathe=2.4))]+ parts += chord(["A2"], 0.0, 0.45, 0.2, attack=0.02, release=0.3, edge=0.05)+ return space(place(parts, 0.6), size=0.7, wet=0.14)+++@sound("dialog-question", -10)+def question():+ parts = [(0.0, warm("D3", 0.22, attack=0.015, release=0.1, gain=0.5)),+ (0.14, warm("E3", 0.45, attack=0.015, release=0.28, gain=0.5))]+ return space(place(parts, 0.7), size=0.7, wet=0.14)+++@sound("dialog-warning", -8)+def warning():+ # A falling minor third, low and unhurried.+ parts = [(0.0, warm("C3", 0.28, attack=0.015, release=0.14, gain=0.55, breathe=2.2)),+ (0.18, warm("A2", 0.55, attack=0.015, release=0.35, gain=0.55, breathe=2.0))]+ parts += chord(["A1"], 0.18, 0.5, 0.14, attack=0.02, release=0.3, edge=0.0)+ return space(place(parts, 0.85), size=0.8, wet=0.15)+++@sound("dialog-error", -7)+def error():+ # Two low notes a fourth apart, falling, close and short: a firm no.+ parts = [(0.0, warm("D3", 0.2, attack=0.008, release=0.1, gain=0.6, breathe=2.0, rest=1.2)),+ (0.12, warm("A2", 0.38, attack=0.008, release=0.25, gain=0.6, breathe=1.8, rest=1.15))]+ parts += chord(["D2"], 0.0, 0.5, 0.17, attack=0.008, release=0.3, edge=0.0)+ return space(place(parts, 0.6), size=0.5, wet=0.1)+++@sound("device-added", -9)+def device_added():+ parts = [(0.0, warm("D3", 0.2, attack=0.012, release=0.1, gain=0.5, breathe=2.8)),+ (0.12, warm("A3", 0.45, attack=0.012, release=0.28, gain=0.5, breathe=2.8))]+ return space(place(parts, 0.7), size=0.7, wet=0.14)+++@sound("device-removed", -9)+def device_removed():+ parts = [(0.0, warm("A3", 0.2, attack=0.012, release=0.1, gain=0.5, breathe=2.6)),+ (0.12, warm("D3", 0.45, attack=0.012, release=0.28, gain=0.5, breathe=2.4))]+ return space(place(parts, 0.7), size=0.7, wet=0.14)+++@sound("power-plug", -9)+def power_plug():+ parts = [(0.0, warm("A2", 0.2, attack=0.02, release=0.1, gain=0.45)),+ (0.11, warm("D3", 0.2, attack=0.02, release=0.1, gain=0.45)),+ (0.22, warm("A3", 0.5, attack=0.02, release=0.3, gain=0.48, breathe=2.6))]+ return space(place(parts, 0.85), size=0.7, wet=0.14)+++@sound("power-unplug", -9)+def power_unplug():+ parts = [(0.0, warm("A3", 0.2, attack=0.015, release=0.1, gain=0.45)),+ (0.11, warm("D3", 0.45, attack=0.015, release=0.28, gain=0.48))]+ return space(place(parts, 0.65), size=0.6, wet=0.12)+++@sound("battery-low", -8)+def battery_low():+ parts = [(at, warm("C3", 0.18, attack=0.015, release=0.08, gain=0.5)) for at in (0.0, 0.2)]+ parts += [(0.4, warm("A2", 0.55, attack=0.015, release=0.35, gain=0.55, breathe=2.0))]+ parts += chord(["A1"], 0.4, 0.5, 0.14, attack=0.02, release=0.3, edge=0.0)+ return space(place(parts, 1.05), size=0.8, wet=0.14)+++@sound("screen-capture", -10)+def screen_capture():+ parts = [(0.0, warm("D4", 0.12, attack=0.004, release=0.07, gain=0.4, breathe=3.2, rest=1.5)),+ (0.06, warm("A3", 0.18, attack=0.004, release=0.1, gain=0.42, breathe=3.0, rest=1.5))]+ return space(place(parts, 0.3), size=0.35, wet=0.08)+++@sound("trash-empty", -9)+def trash_empty():+ parts = []+ for i, (n, at) in enumerate(zip(["A3", "F3", "D3"], (0.0, 0.07, 0.14))):+ parts.append((at, warm(n, 0.16 if i < 2 else 0.4, attack=0.008, release=0.08 if i < 2 else 0.25, gain=0.45)))+ return space(place(parts, 0.6), size=0.5, wet=0.1)+++@sound("audio-volume-change", -15)+def volume():+ return place([(0.0, warm("D3", 0.08, attack=0.003, release=0.05, gain=0.7, breathe=3.0, rest=2.0))], 0.09)+++@sound("bell", -12)+def bell():+ return space(place([(0.0, warm("D3", 0.2, attack=0.006, release=0.1, gain=0.6, breathe=2.0))], 0.25), size=0.35, wet=0.08)+++@sound("battery-caution", -7)+def battery_caution():+ # More urgent than battery-low: three falling notes, the last held.+ parts = []+ for n, at in (("C3", 0.0), ("C3", 0.18), ("A2", 0.36)):+ parts.append((at, warm(n, 0.16 if at < 0.3 else 0.6, attack=0.012, release=0.08 if at < 0.3 else 0.35, gain=0.55)))+ parts += chord(["A1"], 0.36, 0.55, 0.14, attack=0.02, release=0.3, edge=0.0)+ return space(place(parts, 1.1), size=0.8, wet=0.14)+++@sound("battery-full", -10)+def battery_full():+ parts = [(0.0, warm("D3", 0.25, attack=0.02, release=0.12, gain=0.45)),+ (0.14, warm("A3", 0.6, attack=0.02, release=0.38, gain=0.45, breathe=2.4))]+ parts += chord(["D2", "A2"], 0.14, 0.6, 0.12, attack=0.06, release=0.4, breathe=1.6, rest=1.2)+ return space(place(parts, 0.9), size=0.8, wet=0.16)+++@sound("completion-fail", -9)+def completion_fail():+ parts = [(0.0, warm("F3", 0.2, attack=0.012, release=0.1, gain=0.5)),+ (0.13, warm("D3", 0.45, attack=0.012, release=0.28, gain=0.5, breathe=2.0))]+ return space(place(parts, 0.7), size=0.6, wet=0.12)+++@sound("completion-rotation", -15)+def completion_rotation():+ return place([(0.0, warm("A3", 0.07, attack=0.003, release=0.04, gain=0.6, breathe=2.6, rest=1.8))], 0.08)+++@sound("dialog-error-critical", -6)+def error_critical():+ # The error, stated twice: for something that really went wrong.+ parts = []+ for at in (0.0, 0.42):+ parts += [(at, warm("D3", 0.2, attack=0.008, release=0.1, gain=0.6, breathe=2.0, rest=1.2)),+ (at + 0.12, warm("A2", 0.36, attack=0.008, release=0.24, gain=0.6, breathe=1.8, rest=1.15))]+ parts += chord(["D2"], 0.0, 0.95, 0.15, attack=0.01, release=0.4, edge=0.0)+ return space(place(parts, 1.1), size=0.6, wet=0.12)+++# Names that share another sound's file: alias -> sound. The package links+# them (debian/links) rather than shipping copies.+ALIASES = {+ "bell-window-system": "bell",+ "completion-success": "complete",+ "dialog-error-serious": "dialog-error",+ "dialog-warning-auth": "dialog-question",+ "message-new-email": "message",+ "camera-shutter": "screen-capture",+}+++def write(name, x, out):+ pcm = (np.clip(x.T, -1, 1) * 32767).astype("<i2")+ os.makedirs(os.path.join(out, "stereo"), exist_ok=True)+ wav = os.path.join(out, name + ".wav")+ with wave.open(wav, "wb") as w:+ w.setnchannels(2)+ w.setsampwidth(2)+ w.setframerate(RATE)+ w.writeframes(pcm.tobytes())+ oga = os.path.join(out, "stereo", name + ".oga")+ subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-i", wav, "-map_metadata", "-1", "-c:a", "libvorbis",+ "-q:a", "6", "-fflags", "+bitexact", "-flags:a", "+bitexact", oga], check=True)+ os.remove(wav)+ return x.shape[1] / RATE+++def main():+ out = sys.argv[1] if len(sys.argv) > 1 else "."+ for name, (fn, peak) in S.items():+ seconds = write(name, finish(fn(), peak), out)+ print(f"{name:24s} {seconds:4.2f} s")+++if __name__ == "__main__":+ main()diff --git a/packages/wildos-branding/tools/theme-variants.py b/packages/wildos-branding/tools/theme-variants.pynew file mode 100644index 0000000..1a76528--- /dev/null+++ b/packages/wildos-branding/tools/theme-variants.py@@ -0,0 +1,153 @@+#!/usr/bin/env python3+"""Builds a Plasma style for each theme's glass from the Wild OS one.++ python3 tools/theme-variants.py files/desktoptheme files/themes <desktoptheme dir>++Start, the flyouts, tooltips and every Plasma popup are drawn from the+frames in files/desktoptheme, whose glass is Dawn's. A theme with glass of its+own names a Plasma style in its "desktopTheme" (wildos-overclock, ...); this+writes that style as a copy of the Wild OS one with the glass recoloured, the+same way WildOS.UI's Style.tinted recolours the app surfaces: each channel+scaled by the theme's share of the reference glass, the alpha moved by the+difference. "wildos-light" is the light glass of the light artboards.++Every style also gets a "-solid" twin for Settings > Accessibility > Stronger+text on glass, its glass most of the way to opaque by the same rule as+Style.solid, so text in Start, the flyouts and tooltips no longer sits over+whatever is behind them.++wildos-auto-theme switches the style to match the theme, the mode and that+setting.+"""++import json+import re+import shutil+import sys+from pathlib import Path++DARK_REFERENCE = ((18, 22, 40), 0.86)+LIGHT_REFERENCE = ((250, 251, 254), 0.82)++# The fills the frames are painted with (see glass-svg.py and+# desktoptheme-dialogs.py).+PANEL = (16, 20, 38) # Start, flyouts, tooltips: glass-panel, 0.76+BAR = (12, 16, 32) # the floating taskbar: glass-bar, 0.55+SHADOW = (4, 8, 24) # the flyout shadow, at many alphas+WHITE = (255, 255, 255) # the 0.12 edge and the 0.10 highlight++# Style.solid in WildOS.UI: the glass goes this far towards opaque.+SOLID = 0.8++FILL = re.compile(r'fill="rgb\((\d+),(\d+),(\d+)\)" fill-opacity="([0-9.]+)"')+++def hex_colour(value):+ """{"colour": "#rrggbb", "alpha": a} as ((r, g, b), a)."""+ h = value["colour"].lstrip("#")+ return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4)), float(value.get("alpha", 1.0))+++def tint(rgb, alpha, glass, reference, shift_alpha=True):+ (tr, tg, tb), ta = glass+ (rr, rg, rb), ra = reference+ r, g, b = rgb+ out = (min(255, round(r * tr / rr)), min(255, round(g * tg / rg)), min(255, round(b * tb / rb)))+ if shift_alpha:+ alpha = max(0.0, min(1.0, alpha + ta - ra))+ return out, alpha+++def fmt(rgb, alpha):+ a = ("%.3f" % alpha).rstrip("0").rstrip(".") or "0"+ return 'fill="rgb(%d,%d,%d)" fill-opacity="%s"' % (rgb + (a,))+++def recolour(svg, light, glass, taskbar, solid=False):+ reference = LIGHT_REFERENCE if light else DARK_REFERENCE++ def glass_fill(rgb, alpha):+ if solid:+ alpha = alpha + (1.0 - alpha) * SOLID+ return fmt(rgb, alpha)++ def swap(match):+ rgb = tuple(int(match.group(i)) for i in (1, 2, 3))+ alpha = float(match.group(4))+ if rgb == PANEL:+ if light:+ rgb, alpha = (250, 251, 254), 0.86+ return glass_fill(*tint(rgb, alpha, glass, reference))+ if rgb == BAR:+ if taskbar:+ # As Style.taskbarFloating: the theme's taskbar glass, as+ # much lighter as the stock pills are than the docked bar.+ return glass_fill(taskbar[0], max(0.0, taskbar[1] - (0.23 if light else 0.33)))+ if light:+ rgb, alpha = (250, 251, 254), 0.67+ return glass_fill(*tint(rgb, alpha, glass, reference))+ if rgb == SHADOW:+ if light:+ # Shadows keep their shape at about 40% strength in light+ # mode (Style.shadowFlyout).+ return fmt((20, 30, 60), alpha * 0.4)+ return fmt(*tint(rgb, alpha, glass, reference, shift_alpha=False))+ if rgb == WHITE and light:+ # The edge becomes the navy hairline (Style.tone), the top+ # highlight stays white and grows to show on pale glass.+ if abs(alpha - 0.12) < 1e-6:+ return fmt((30, 40, 70), 0.09)+ if abs(alpha - 0.1) < 1e-6:+ return fmt(WHITE, 0.7)+ return match.group(0)++ return FILL.sub(swap, svg)+++def build(source, dest, name, title, light, glass, taskbar, solid=False):+ target = dest / name+ if target.exists():+ shutil.rmtree(target)+ shutil.copytree(source, target)+ for svg in target.rglob("*.svg"):+ # The task manager's frames are Plasma's own, which Wild OS does not+ # show; they keep their colours.+ if svg.name == "tasks.svg":+ continue+ svg.write_text(recolour(svg.read_text(), light, glass, taskbar, solid))+ metadata = json.loads((source / "metadata.json").read_text())+ metadata["KPlugin"]["Id"] = name+ metadata["KPlugin"]["Name"] = title+ metadata["KPlugin"]["Description"] = ("Light" if light else "Dark") + (" solid" if solid else " glass") + " panels and popups"+ (target / "metadata.json").write_text(json.dumps(metadata, indent=4) + "\n")+ print(target)+++def main():+ source, themes, dest = (Path(p) for p in sys.argv[1:4])+ dest.mkdir(parents=True, exist_ok=True)+ styles = [+ ("wildos", "Wild OS", False, DARK_REFERENCE, None),+ ("wildos-light", "Wild OS Light", True, LIGHT_REFERENCE, None),+ ]+ named = {"wildos", "wildos-light"}+ for path in sorted(themes.glob("*.json")):+ theme = json.loads(path.read_text())+ name = theme.get("desktopTheme", "wildos")+ if name in named:+ continue+ light = theme["mode"] == "light"+ glass = hex_colour(theme["glass"])+ taskbar = hex_colour(theme["taskbarGlass"]) if "taskbarGlass" in theme else None+ styles.append((name, "Wild OS " + theme["name"], light, glass, taskbar))+ named.add(name)++ for name, title, light, glass, taskbar in styles:+ # The plain dark style is the source itself, installed as it is.+ if name != "wildos":+ build(source, dest, name, title, light, glass, taskbar)+ build(source, dest, name + "-solid", title + " Solid", light, glass, taskbar, solid=True)+++if __name__ == "__main__":+ main()diff --git a/packages/wildos-branding/tools/wallpapers.py b/packages/wildos-branding/tools/wallpapers.pynew file mode 100644index 0000000..ef93b89--- /dev/null+++ b/packages/wildos-branding/tools/wallpapers.py@@ -0,0 +1,53 @@+#!/usr/bin/env python3+"""Builds the theme wallpapers as Plasma wallpaper packages.++ python3 tools/wallpapers.py <branding dir> <wallpapers dir>++Each photo in branding/wallpaper/photos.json becomes+<wallpapers dir>/WildOS-<id>, laid out like the WildOS package:+contents/images/5120x2880.webp, a screenshot for the pickers and a+metadata.json naming the photographer and the licence. The 5K masters in+branding/wallpaper/photos are made from the originals by make-masters.py;+Plasma scales them down for smaller screens.+"""++import json+import subprocess+import sys+from pathlib import Path++LICENCES = {"Pexels": "Pexels License", "Unsplash": "Unsplash License"}+++def main():+ branding = Path(sys.argv[1])+ dest = Path(sys.argv[2])+ photos = json.loads((branding / "wallpaper" / "photos.json").read_text())++ for photo in photos:+ package = dest / f"WildOS-{photo['id']}"+ images = package / "contents" / "images"+ images.mkdir(parents=True, exist_ok=True)++ master = branding / "wallpaper" / "photos" / f"{photo['id']}.webp"+ (images / "5120x2880.webp").write_bytes(master.read_bytes())++ subprocess.run(["magick", str(master), "-resize", "600x375^", "-gravity", "center",+ "-extent", "600x375", "-quality", "85", str(package / "contents" / "screenshot.jpg")],+ check=True)++ metadata = {+ "KPlugin": {+ "Authors": [{"Name": photo["author"]}],+ "Id": f"WildOS-{photo['id']}",+ "License": LICENCES[photo["licence"]],+ "Name": photo["title"],+ "Website": photo["source"],+ }+ }+ (package / "metadata.json").write_text(json.dumps(metadata, indent=4) + "\n")+ print(package)+++if __name__ == "__main__":+ main()diff --git a/packages/wildos-desktop-view/qml/DesktopIcon.qml b/packages/wildos-desktop-view/qml/DesktopIcon.qmlindex 864deec..92e02a8 100644--- a/packages/wildos-desktop-view/qml/DesktopIcon.qml+++ b/packages/wildos-desktop-view/qml/DesktopIcon.qml@@ -156,7 +156,7 @@ Item {property bool deferSelect: falseonPressed: mouse => {- tile.view.forceActiveFocus();+ tile.view.takeFocus();tile.view.pointerUsed();pressPoint = Qt.point(mouse.x, mouse.y);deferSelect = false;diff --git a/packages/wildos-desktop-view/qml/DesktopView.qml b/packages/wildos-desktop-view/qml/DesktopView.qmlindex 28d7b25..501eb06 100644--- a/packages/wildos-desktop-view/qml/DesktopView.qml+++ b/packages/wildos-desktop-view/qml/DesktopView.qml@@ -63,6 +63,20 @@ FocusScope {keyboardUsed = false;}+ // A press anywhere on the desktop takes the keyboard back from whatever+ // inside it holds it, so an open name editor loses focus and keeps the+ // new name, as clicking away does on Windows. forceActiveFocus() alone+ // is not enough: this item is a FocusScope, so it hands active focus+ // straight back to the child that had it.+ function takeFocus() {+ const w = view.Window.window;+ const item = w ? w.activeFocusItem : null;+ if (item && item !== view) {+ item.focus = false;+ }+ view.forceActiveFocus();+ }+// Commands shared by the menus and the keyboard.function selectedRowsOfKind(kind) {@@ -590,7 +604,7 @@ FocusScope {property rect bandonPressed: mouse => {- view.forceActiveFocus();+ view.takeFocus();view.pointerUsed();start = Qt.point(mouse.x, mouse.y);banding = false;diff --git a/packages/wildos-desktop-view/src/format.cpp b/packages/wildos-desktop-view/src/format.cppindex 1bc870d..79ef803 100644--- a/packages/wildos-desktop-view/src/format.cpp+++ b/packages/wildos-desktop-view/src/format.cpp@@ -71,9 +71,13 @@ QString date(const QDateTime &when)if (!when.isValid()) {return QString();}+ // The regional format chosen in Settings decides the order and the+ // clock; the words stay English, as the rest of Wild OS is.+ const QLocale names(QLocale::English, QLocale::UnitedKingdom);+ const QLocale format = QLocale::system();const QDateTime local = when.toLocalTime();const QDate today = QDate::currentDate();- const QString time = local.toString(QStringLiteral("HH:mm"));+ const QString time = format.toString(local.time(), QLocale::ShortFormat);const qint64 days = local.date().daysTo(today);if (days == 0) {return QStringLiteral("Today ") + time;@@ -82,9 +86,9 @@ QString date(const QDateTime &when)return QStringLiteral("Yesterday ") + time;}if (days > 1 && days < 7) {- return QLocale(QLocale::English, QLocale::UnitedKingdom).dayName(local.date().dayOfWeek()) + QLatin1Char(' ') + time;+ return names.dayName(local.date().dayOfWeek()) + QLatin1Char(' ') + time;}- return local.toString(QStringLiteral("dd/MM/yyyy"));+ return names.toString(local.date(), format.dateFormat(QLocale::ShortFormat));}QString longDate(const QDateTime &when)@@ -93,8 +97,15 @@ QString longDate(const QDateTime &when)return QString();}const QDateTime local = when.toLocalTime();- const QLocale uk(QLocale::English, QLocale::UnitedKingdom);- return uk.toString(local, QStringLiteral("dddd d MMMM yyyy, HH:mm"));+ const QLocale names(QLocale::English, QLocale::UnitedKingdom);+ const QLocale format = QLocale::system();+ // Qt writes UK dates as "Monday, 9 November"; Wild OS has no comma.+ QString day = format.dateFormat(QLocale::LongFormat);+ if (day.startsWith(QLatin1String("dddd, d MMMM"))) {+ day.remove(4, 1);+ }+ return names.toString(local.date(), day) + QStringLiteral(", ")+ + format.toString(local.time(), QLocale::ShortFormat);}QString size(qint64 bytes)@@ -102,11 +113,12 @@ QString size(qint64 bytes)if (bytes < 0) {return QString();}- const QLocale uk(QLocale::English, QLocale::UnitedKingdom);+ // Separators from the regional format chosen in Settings (LC_NUMERIC).+ const QLocale numbers = QLocale::system();// Windows rounds small files up, so a 200 byte note is 1 KB, not 0.if (bytes < 1024 * 1024) {const qint64 kb = bytes == 0 ? 0 : (bytes + 1023) / 1024;- return uk.toString(kb) + QStringLiteral(" KB");+ return numbers.toString(kb) + QStringLiteral(" KB");}static const char *units[] = {"MB", "GB", "TB", "PB"};double value = bytes / (1024.0 * 1024.0);@@ -117,12 +129,12 @@ QString size(qint64 bytes)}// Three significant figures: 4.21 MB, 12.3 MB, 123 MB.const int decimals = value < 10 ? 2 : value < 100 ? 1 : 0;- QString text = uk.toString(value, 'f', decimals);- if (text.contains(QLatin1Char('.'))) {+ QString text = numbers.toString(value, 'f', decimals);+ if (text.contains(numbers.decimalPoint())) {while (text.endsWith(QLatin1Char('0'))) {text.chop(1);}- if (text.endsWith(QLatin1Char('.'))) {+ if (text.endsWith(numbers.decimalPoint())) {text.chop(1);}}@@ -131,14 +143,12 @@ QString size(qint64 bytes)QString exactSize(qint64 bytes){- const QLocale uk(QLocale::English, QLocale::UnitedKingdom);- return size(bytes) + QStringLiteral(" (") + uk.toString(bytes) + (bytes == 1 ? QStringLiteral(" byte)") : QStringLiteral(" bytes)"));+ return size(bytes) + QStringLiteral(" (") + QLocale::system().toString(bytes) + (bytes == 1 ? QStringLiteral(" byte)") : QStringLiteral(" bytes)"));}QString count(qint64 n, const QString &one, const QString &many){- const QLocale uk(QLocale::English, QLocale::UnitedKingdom);- return uk.toString(n) + QLatin1Char(' ') + (n == 1 ? one : many);+ return QLocale::system().toString(n) + QLatin1Char(' ') + (n == 1 ? one : many);}}diff --git a/packages/wildos-desktop/debian/control b/packages/wildos-desktop/debian/controlindex c2573ac..1f0d8aa 100644--- a/packages/wildos-desktop/debian/control+++ b/packages/wildos-desktop/debian/control@@ -24,9 +24,12 @@ Depends:wildos-winmode,wildos-terminal,wildos-launch,+ wildos-lighting,wildos-setup,wildos-portal,wildos-taskmanager,+ wildos-mail,+ wildos-remote,wildos-overlays,kde-plasma-desktop,plasma-workspace,@@ -52,6 +55,11 @@ Depends:usbguard-notifier,python3,xdg-user-dirs,+# kwalletd's Secret Service (secret-tool, Brave, Windows mode's keyring)+# needs QCA's OpenSSL plugin for its encrypted sessions, and without it+# every libsecret call fails. QCA only recommends it, and recommends are+# not installed.+ libqca-qt6-plugins,# KDE Connect opens network ports for phone pairing, which a security-focused# system should not do unasked; Konqueror would be a second browser; Kup is a# backup tray app that sits in the bar. desktop-base is Debian's artworkdiff --git a/packages/wildos-files/CMakeLists.txt b/packages/wildos-files/CMakeLists.txtindex 9d6759b..547bcba 100644--- a/packages/wildos-files/CMakeLists.txt+++ b/packages/wildos-files/CMakeLists.txt@@ -42,6 +42,7 @@ qt_add_qml_module(wildos-filessrc/zipjob.cpp src/zipjob.hsrc/filemeta.cpp src/filemeta.hsrc/imageproviders.cpp src/imageproviders.h+ src/previewsource.cpp src/previewsource.h)target_include_directories(wildos-files PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)diff --git a/packages/wildos-files/debian/control b/packages/wildos-files/debian/controlindex 6c1ad6e..390b1f9 100644--- a/packages/wildos-files/debian/control+++ b/packages/wildos-files/debian/control@@ -17,6 +17,8 @@ Build-Depends:libkf6purpose-dev,libkf6archive-dev,libkf6filemetadata-dev,+ qml6-module-qtmultimedia,+ qml6-module-qtquick-pdf,Standards-Version: 4.7.0Rules-Requires-Root: no@@ -25,15 +27,19 @@ Architecture: anyDepends:${shlibs:Depends},${misc:Depends},+ fonts-jetbrains-mono,kio6,qml6-module-qtcore,+ qml6-module-qtmultimedia,qml6-module-qtquick,qml6-module-qtquick-controls,qml6-module-qtquick-effects,qml6-module-qtquick-layouts,+ qml6-module-qtquick-pdf,qml6-module-qtquick-shapes,qml6-module-qtquick-templates,qml6-module-qtquick-window,+ qt6-image-formats-plugins,qt6-svg-plugins,wildos-ui,Recommends:diff --git a/packages/wildos-files/qml/FilesView.qml b/packages/wildos-files/qml/FilesView.qmlindex 5e062ea..3adaf56 100644--- a/packages/wildos-files/qml/FilesView.qml+++ b/packages/wildos-files/qml/FilesView.qml@@ -66,10 +66,21 @@ Item {focusContent();}+ // Takes the keyboard from whatever inside the view holds it first, so a+ // click anywhere closes an open name editor and keeps the new name, as+ // clicking away does on Windows. forceActiveFocus() alone hands focus+ // straight back to the editor: each view is a FocusScope.function focusContent() {- if (content.item) {- content.item.forceActiveFocus();+ const view = content.item;+ if (!view) {+ return;+ }+ const w = root.Window.window;+ const held = w ? w.activeFocusItem : null;+ if (held && held !== view) {+ held.focus = false;}+ view.forceActiveFocus();}function showError(message) {@@ -631,12 +642,19 @@ Item {f.clearSelection();break;case Qt.Key_Space:+ // Ctrl+Space toggles the item, as in Explorer; a space in the+ // middle of typing a name is part of the name; otherwise Space+ // is Quick Look.if (ctrl && cur >= 0) {f.select(cur, Qt.ControlModifier);- } else if (cur >= 0 && !f.isSelected(cur)) {- f.select(cur, 0);} else if (root.typed.length > 0) {typeAhead(" ");+ } else if (f.kind === "computer") {+ if (cur >= 0 && !f.isSelected(cur)) {+ f.select(cur, 0);+ }+ } else {+ quickLook();}break;case Qt.Key_Menu:@@ -704,6 +722,43 @@ Item {}}+ // Quick Look shows the item with the keyboard focus when it is selected,+ // the first selected item otherwise. With nothing selected, Space picks+ // the focused item first, as it did before Quick Look.+ property var quickLookWindow: null++ function quickLook() {+ const f = folder;+ let row = f.currentIndex;+ if (row < 0 || !f.isSelected(row)) {+ if (f.selectedCount > 0) {+ row = f.rowForUrl(selection()[0]);+ } else if (row >= 0) {+ f.select(row, 0);+ }+ }+ if (row < 0) {+ return;+ }+ if (!quickLookWindow) {+ quickLookWindow = quickLookComponent.createObject(root, { transientParent: root.Window.window });+ }+ quickLookWindow.show(f.urlAt(row));+ }++ // The arrow keys while Quick Look is open: Left and Right step through+ // the items in order whatever the layout, Up and Down by a row.+ function quickLookStep(delta, vertical) {+ const f = folder;+ if (!f || f.count === 0) {+ return;+ }+ const rowSize = vertical && content.item ? content.item.columns() : 1;+ const cur = f.currentIndex < 0 ? 0 : f.currentIndex;+ keyboardUsed = true;+ f.moveCurrent(Math.max(0, Math.min(f.count - 1, cur + delta * rowSize)), 0);+ }+function openContextAtCurrent(view) {if (folder.selectedCount === 0) {openFolderMenu(view, 24, 24);@@ -1002,6 +1057,13 @@ Item {PropertiesWindow {}}+ Component {+ id: quickLookComponent+ QuickLook {+ view: root+ }+ }+ShortcutDialog {id: shortcutDialogonClosed: root.focusContent()diff --git a/packages/wildos-files/qml/PromptDialog.qml b/packages/wildos-files/qml/PromptDialog.qmlindex c678bcc..515c46a 100644--- a/packages/wildos-files/qml/PromptDialog.qml+++ b/packages/wildos-files/qml/PromptDialog.qml@@ -17,10 +17,13 @@ UI.Dialog {title: p.title ?? ""text: p.text ?? ""+ // Reads p itself: kind is a binding on p and may not have caught up when+ // this handler runs, which left every question unasked and the queue+ // behind it stuck (Empty Recycle Bin did nothing).onPChanged: {all = false;answered = false;- if (kind.length > 0 && mine) {+ if ((p.kind ?? "").length > 0 && mine) {open();} else {close();diff --git a/packages/wildos-files/qml/QuickLook.qml b/packages/wildos-files/qml/QuickLook.qmlnew file mode 100644index 0000000..f6c5cc4--- /dev/null+++ b/packages/wildos-files/qml/QuickLook.qml@@ -0,0 +1,533 @@+pragma ComponentBehavior: Bound++import QtQuick+import QtQuick.Controls+import QtQuick.Layouts+import QtQuick.Window+import QtMultimedia+import QtQuick.Pdf+import WildOS.Files+import WildOS.UI as UI++// Quick Look (Space on a selected item), as on a Mac or PowerToys Peek: a+// window of its own over Files with a preview of the item. Space or Escape+// closes it, the arrow keys move the selection in Files and the preview+// follows, Enter opens the item.+UI.AppWindow {+ id: ql++ required property var view+ property url url+ readonly property string kind: info.isDir ? "folder" : peek.kind+ readonly property string appName: url.toString().length > 0 && !info.isDir ? FileOps.defaultAppName(url) : ""++ deep: true+ width: 920+ height: 660+ minimumWidth: 480+ minimumHeight: 360+ title: info.name++ function show(itemUrl) {+ url = itemUrl;+ visible = true;+ raise();+ requestActivate();+ body.forceActiveFocus();+ }++ // Opens the item shown, as Enter on it in Files would, even when more+ // than one item is selected there.+ function openItem() {+ const f = view.folder;+ const row = f.rowForUrl(url);+ close();+ f.activate(row);+ }++ function openWithApp() {+ if (info.isDir || appName.length > 0) {+ openItem();+ return;+ }+ const target = url;+ close();+ view.chooseApp([target]);+ }++ function clock(ms) {+ const total = Math.max(0, Math.floor(ms / 1000));+ const h = Math.floor(total / 3600);+ const m = Math.floor(total / 60) % 60;+ const s = String(total % 60).padStart(2, "0");+ return h > 0 ? h + ":" + String(m).padStart(2, "0") + ":" + s : m + ":" + s;+ }++ // Hiding unloads the preview, which stops a video or song playing on.+ onVisibleChanged: {+ if (!visible) {+ url = "";+ if (view.Window.window) {+ view.Window.window.requestActivate();+ }+ view.focusContent();+ }+ }++ ItemInfo {+ id: info+ urls: ql.url.toString().length > 0 ? [ql.url] : []+ }++ PreviewSource {+ id: peek+ url: ql.url+ }++ // The preview follows the item the arrow keys or a click land on in+ // Files, and goes away when Files moves to another folder or tab.+ Connections {+ target: ql.visible ? ql.view.folder : null+ function onCurrentIndexChanged() {+ const f = ql.view.folder;+ if (f.currentIndex >= 0 && f.isSelected(f.currentIndex)) {+ ql.url = f.urlAt(f.currentIndex);+ }+ }+ function onUrlChanged() {+ ql.close();+ }+ }++ Connections {+ target: ql.view+ function onFolderChanged() {+ if (ql.visible) {+ ql.close();+ }+ }+ }++ Shortcut {+ sequences: ["Space", "Escape"]+ onActivated: ql.close()+ }+ Shortcut {+ sequences: ["Left"]+ onActivated: ql.view.quickLookStep(-1, false)+ }+ Shortcut {+ sequences: ["Right"]+ onActivated: ql.view.quickLookStep(1, false)+ }+ Shortcut {+ sequences: ["Up"]+ onActivated: ql.view.quickLookStep(-1, true)+ }+ Shortcut {+ sequences: ["Down"]+ onActivated: ql.view.quickLookStep(1, true)+ }+ Shortcut {+ sequences: ["Return", "Enter"]+ onActivated: ql.openItem()+ }++ ColumnLayout {+ anchors.fill: parent+ anchors.margins: ql.maximised ? 0 : 1+ spacing: 0++ UI.TitleBar {+ Layout.fillWidth: true+ frame: ql.frame+ buttons.showMinimise: false++ Row {+ x: -2+ width: parent.width+ height: parent.height+ spacing: 10++ UI.ThemeIcon {+ anchors.verticalCenter: parent.verticalCenter+ width: 16+ height: 16+ name: info.iconName+ }++ UI.Label {+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - 26+ text: info.name+ font.weight: Font.Medium+ color: ql.active ? UI.Style.ink : UI.Style.inkMuted+ }+ }+ }++ Rectangle {+ Layout.fillWidth: true+ implicitHeight: 1+ color: UI.Style.divider+ }++ FocusScope {+ id: body+ Layout.fillWidth: true+ Layout.fillHeight: true+ clip: true++ Loader {+ anchors.fill: parent+ sourceComponent: ({+ "": loadingComponent,+ "image": imageComponent,+ "animated": animatedComponent,+ "pdf": pdfComponent,+ "video": videoComponent,+ "audio": audioComponent,+ "text": textComponent,+ "folder": aboutComponent,+ "other": aboutComponent+ })[ql.kind] ?? aboutComponent+ }+ }++ Rectangle {+ Layout.fillWidth: true+ implicitHeight: 1+ color: UI.Style.divider+ }++ RowLayout {+ Layout.fillWidth: true+ Layout.preferredHeight: 56+ Layout.leftMargin: 18+ Layout.rightMargin: 14+ spacing: 12++ UI.Label {+ Layout.fillWidth: true+ text: [info.type, info.isDir ? info.contains : info.size, info.modified].filter(s => s.length > 0).join(" · ")+ color: UI.Style.inkMuted+ font.pixelSize: UI.Style.px(12)+ }++ UI.Button {+ focusPolicy: Qt.TabFocus+ kind: "primary"+ text: info.isDir ? "Open" : ql.appName.length > 0 ? "Open with " + ql.appName : "Open with…"+ visible: ql.url.toString().length > 0+ onClicked: ql.openWithApp()+ }+ }+ }++ Component {+ id: loadingComponent+ Item {+ UI.Spinner {+ anchors.centerIn: parent+ size: 24+ }+ }+ }++ // Pictures at their own size, or shrunk to fit the window; never+ // stretched past it, so an icon-sized PNG stays crisp. A photo is+ // decoded at no more than 4K, which keeps a 50 megapixel camera file+ // from taking hundreds of megabytes.+ Component {+ id: imageComponent+ Item {+ Image {+ id: picture+ anchors.centerIn: parent+ width: Math.min(parent.width - 32, implicitWidth)+ height: Math.min(parent.height - 32, implicitHeight)+ source: ql.url+ sourceSize: Qt.size(3840, 3840)+ fillMode: Image.PreserveAspectFit+ autoTransform: true+ asynchronous: true+ cache: false+ smooth: true+ mipmap: true+ }+ UI.Spinner {+ anchors.centerIn: parent+ visible: picture.status === Image.Loading+ size: 24+ }+ Loader {+ anchors.fill: parent+ active: picture.status === Image.Error+ sourceComponent: aboutComponent+ }+ }+ }++ Component {+ id: animatedComponent+ Item {+ AnimatedImage {+ id: animation+ anchors.centerIn: parent+ width: Math.min(parent.width - 32, implicitWidth)+ height: Math.min(parent.height - 32, implicitHeight)+ source: ql.url+ fillMode: Image.PreserveAspectFit+ cache: false+ smooth: true+ }+ Loader {+ anchors.fill: parent+ active: animation.status === Image.Error+ sourceComponent: aboutComponent+ }+ }+ }++ Component {+ id: pdfComponent+ Item {+ PdfDocument {+ id: pdf+ source: ql.url+ onStatusChanged: {+ if (pdf.status === PdfDocument.Ready) {+ Qt.callLater(() => pages.scaleToWidth(pages.width, pages.height));+ }+ }+ }+ PdfMultiPageView {+ id: pages+ anchors.fill: parent+ document: pdf+ visible: pdf.status === PdfDocument.Ready+ }+ UI.Spinner {+ anchors.centerIn: parent+ visible: pdf.status === PdfDocument.Loading+ size: 24+ }+ // Locked or damaged files get the icon and details.+ Loader {+ anchors.fill: parent+ active: pdf.status === PdfDocument.Error+ sourceComponent: aboutComponent+ }+ }+ }++ // Play, the time so far, a seek bar and the length, under the video or+ // the song's artwork.+ component MediaBar: RowLayout {+ id: bar+ required property MediaPlayer player+ spacing: 10++ UI.IconButton {+ focusPolicy: Qt.NoFocus+ tip: bar.player.playbackState === MediaPlayer.PlayingState ? "Pause" : "Play"+ iconName: "play"+ glyph: bar.player.playbackState === MediaPlayer.PlayingState ? "M9 5v14M15 5v14" : ""+ onClicked: bar.player.playbackState === MediaPlayer.PlayingState ? bar.player.pause() : bar.player.play()+ }+ UI.Label {+ text: ql.clock(bar.player.position)+ color: UI.Style.inkMuted+ font.pixelSize: UI.Style.px(12)+ font.features: { "tnum": 1 }+ }+ UI.Slider {+ Layout.fillWidth: true+ focusPolicy: Qt.NoFocus+ accessibleName: "Position"+ enabled: bar.player.seekable+ from: 0+ to: Math.max(1, bar.player.duration)+ stepSize: 0+ value: bar.player.position+ onMoved: bar.player.position = value+ }+ UI.Label {+ text: ql.clock(bar.player.duration)+ color: UI.Style.inkMuted+ font.pixelSize: UI.Style.px(12)+ font.features: { "tnum": 1 }+ }+ }++ Component {+ id: videoComponent+ Item {+ MediaPlayer {+ id: movie+ source: ql.url+ videoOutput: videoOut+ audioOutput: AudioOutput {}+ Component.onCompleted: play()+ }+ VideoOutput {+ id: videoOut+ anchors.fill: parent+ anchors.bottomMargin: controls.height + 16+ visible: movie.error === MediaPlayer.NoError+ }+ MouseArea {+ anchors.fill: videoOut+ onClicked: movie.playbackState === MediaPlayer.PlayingState ? movie.pause() : movie.play()+ }+ MediaBar {+ id: controls+ anchors.left: parent.left+ anchors.right: parent.right+ anchors.bottom: parent.bottom+ anchors.margins: 12+ player: movie+ visible: movie.error === MediaPlayer.NoError+ }+ Loader {+ anchors.fill: parent+ active: movie.error !== MediaPlayer.NoError+ sourceComponent: aboutComponent+ }+ }+ }++ Component {+ id: audioComponent+ Item {+ MediaPlayer {+ id: song+ source: ql.url+ audioOutput: AudioOutput {}+ Component.onCompleted: play()+ }+ ColumnLayout {+ anchors.centerIn: parent+ width: Math.min(parent.width - 64, 480)+ spacing: 18++ FileIcon {+ Layout.alignment: Qt.AlignHCenter+ size: 160+ iconName: info.iconName+ url: ql.url+ preview: info.preview+ stamp: info.stamp+ }+ UI.Label {+ Layout.fillWidth: true+ text: info.name+ font.pixelSize: UI.Style.px(15)+ font.weight: Font.DemiBold+ horizontalAlignment: Text.AlignHCenter+ }+ MediaBar {+ Layout.fillWidth: true+ player: song+ visible: song.error === MediaPlayer.NoError+ }+ UI.Label {+ Layout.fillWidth: true+ visible: song.error !== MediaPlayer.NoError+ text: "This cannot be played here."+ color: UI.Style.inkMuted+ horizontalAlignment: Text.AlignHCenter+ }+ }+ }+ }++ Component {+ id: textComponent+ Item {+ Flickable {+ id: page+ anchors.fill: parent+ anchors.bottomMargin: note.visible ? note.height : 0+ contentWidth: Math.max(width, code.implicitWidth)+ contentHeight: code.implicitHeight+ clip: true+ boundsBehavior: Flickable.StopAtBounds+ ScrollBar.vertical: UI.ScrollBar {}+ ScrollBar.horizontal: UI.ScrollBar {}++ TextEdit {+ id: code+ width: page.contentWidth+ padding: 18+ text: peek.text+ readOnly: true+ selectByMouse: true+ activeFocusOnPress: false+ textFormat: TextEdit.PlainText+ wrapMode: TextEdit.NoWrap+ font.family: "JetBrains Mono"+ font.pixelSize: UI.Style.px(12)+ color: UI.Style.ink+ selectionColor: UI.Style.accentSelected+ selectedTextColor: UI.Style.ink+ }+ }+ UI.Label {+ id: note+ anchors.bottom: parent.bottom+ width: parent.width+ height: 30+ visible: peek.truncated+ text: "Showing the first 200 KB. Open the file to read the rest."+ color: UI.Style.inkMuted+ font.pixelSize: UI.Style.px(12)+ horizontalAlignment: Text.AlignHCenter+ verticalAlignment: Text.AlignVCenter+ }+ }+ }++ // Folders, and anything with no preview of its own: a large icon (or+ // the thumbnail KIO makes for it) with what the details pane says.+ Component {+ id: aboutComponent+ Item {+ ColumnLayout {+ anchors.centerIn: parent+ width: Math.min(parent.width - 64, 420)+ spacing: 8++ FileIcon {+ Layout.alignment: Qt.AlignHCenter+ Layout.bottomMargin: 10+ size: info.preview ? 220 : 128+ iconName: info.iconName+ url: ql.url+ preview: info.preview+ stamp: info.stamp+ }+ UI.Label {+ Layout.fillWidth: true+ text: info.name+ font.pixelSize: UI.Style.px(17)+ font.weight: Font.DemiBold+ horizontalAlignment: Text.AlignHCenter+ wrapMode: Text.Wrap+ maximumLineCount: 3+ }+ Repeater {+ model: [info.type, info.isDir ? info.contains : "", info.size, info.modified.length > 0 ? "Modified " + info.modified : ""]+ delegate: UI.Label {+ required property string modelData+ Layout.fillWidth: true+ visible: modelData.length > 0+ text: modelData+ color: UI.Style.inkMuted+ horizontalAlignment: Text.AlignHCenter+ }+ }+ }+ }+ }+}diff --git a/packages/wildos-files/qml/StatusBar.qml b/packages/wildos-files/qml/StatusBar.qmlindex 6e9942a..0f7b3f3 100644--- a/packages/wildos-files/qml/StatusBar.qml+++ b/packages/wildos-files/qml/StatusBar.qml@@ -12,7 +12,7 @@ Item {height: Metrics.statusHeightfunction plural(n, one, many) {- return n.toLocaleString(Qt.locale("en_GB"), "f", 0) + " " + (n === 1 ? one : many);+ return n.toLocaleString(Qt.locale(), "f", 0) + " " + (n === 1 ? one : many);}Rectangle {diff --git a/packages/wildos-files/src/drives.cpp b/packages/wildos-files/src/drives.cppindex 431eb53..4e02b7c 100644--- a/packages/wildos-files/src/drives.cpp+++ b/packages/wildos-files/src/drives.cpp@@ -1,5 +1,6 @@#include "drives.h"+#include <QLocale>#include <QDir>#include <QFile>#include <QFileInfo>@@ -74,9 +75,10 @@ QString sizeName(qint64 bytes)value /= 1000;unit = QStringLiteral("TB");}- QString number = QString::number(value, 'f', value < 10 ? 1 : 0);- if (number.endsWith(QStringLiteral(".0"))) {- number.chop(2);+ const QLocale numbers = QLocale::system();+ QString number = numbers.toString(value, 'f', value < 10 ? 1 : 0);+ if (number.endsWith(numbers.decimalPoint() + QLatin1Char('0'))) {+ number.chop(numbers.decimalPoint().size() + 1);}return number + QLatin1Char(' ') + unit + QStringLiteral(" drive");}diff --git a/packages/wildos-files/src/format.cpp b/packages/wildos-files/src/format.cppindex 1bc870d..79ef803 100644--- a/packages/wildos-files/src/format.cpp+++ b/packages/wildos-files/src/format.cpp@@ -71,9 +71,13 @@ QString date(const QDateTime &when)if (!when.isValid()) {return QString();}+ // The regional format chosen in Settings decides the order and the+ // clock; the words stay English, as the rest of Wild OS is.+ const QLocale names(QLocale::English, QLocale::UnitedKingdom);+ const QLocale format = QLocale::system();const QDateTime local = when.toLocalTime();const QDate today = QDate::currentDate();- const QString time = local.toString(QStringLiteral("HH:mm"));+ const QString time = format.toString(local.time(), QLocale::ShortFormat);const qint64 days = local.date().daysTo(today);if (days == 0) {return QStringLiteral("Today ") + time;@@ -82,9 +86,9 @@ QString date(const QDateTime &when)return QStringLiteral("Yesterday ") + time;}if (days > 1 && days < 7) {- return QLocale(QLocale::English, QLocale::UnitedKingdom).dayName(local.date().dayOfWeek()) + QLatin1Char(' ') + time;+ return names.dayName(local.date().dayOfWeek()) + QLatin1Char(' ') + time;}- return local.toString(QStringLiteral("dd/MM/yyyy"));+ return names.toString(local.date(), format.dateFormat(QLocale::ShortFormat));}QString longDate(const QDateTime &when)@@ -93,8 +97,15 @@ QString longDate(const QDateTime &when)return QString();}const QDateTime local = when.toLocalTime();- const QLocale uk(QLocale::English, QLocale::UnitedKingdom);- return uk.toString(local, QStringLiteral("dddd d MMMM yyyy, HH:mm"));+ const QLocale names(QLocale::English, QLocale::UnitedKingdom);+ const QLocale format = QLocale::system();+ // Qt writes UK dates as "Monday, 9 November"; Wild OS has no comma.+ QString day = format.dateFormat(QLocale::LongFormat);+ if (day.startsWith(QLatin1String("dddd, d MMMM"))) {+ day.remove(4, 1);+ }+ return names.toString(local.date(), day) + QStringLiteral(", ")+ + format.toString(local.time(), QLocale::ShortFormat);}QString size(qint64 bytes)@@ -102,11 +113,12 @@ QString size(qint64 bytes)if (bytes < 0) {return QString();}- const QLocale uk(QLocale::English, QLocale::UnitedKingdom);+ // Separators from the regional format chosen in Settings (LC_NUMERIC).+ const QLocale numbers = QLocale::system();// Windows rounds small files up, so a 200 byte note is 1 KB, not 0.if (bytes < 1024 * 1024) {const qint64 kb = bytes == 0 ? 0 : (bytes + 1023) / 1024;- return uk.toString(kb) + QStringLiteral(" KB");+ return numbers.toString(kb) + QStringLiteral(" KB");}static const char *units[] = {"MB", "GB", "TB", "PB"};double value = bytes / (1024.0 * 1024.0);@@ -117,12 +129,12 @@ QString size(qint64 bytes)}// Three significant figures: 4.21 MB, 12.3 MB, 123 MB.const int decimals = value < 10 ? 2 : value < 100 ? 1 : 0;- QString text = uk.toString(value, 'f', decimals);- if (text.contains(QLatin1Char('.'))) {+ QString text = numbers.toString(value, 'f', decimals);+ if (text.contains(numbers.decimalPoint())) {while (text.endsWith(QLatin1Char('0'))) {text.chop(1);}- if (text.endsWith(QLatin1Char('.'))) {+ if (text.endsWith(numbers.decimalPoint())) {text.chop(1);}}@@ -131,14 +143,12 @@ QString size(qint64 bytes)QString exactSize(qint64 bytes){- const QLocale uk(QLocale::English, QLocale::UnitedKingdom);- return size(bytes) + QStringLiteral(" (") + uk.toString(bytes) + (bytes == 1 ? QStringLiteral(" byte)") : QStringLiteral(" bytes)"));+ return size(bytes) + QStringLiteral(" (") + QLocale::system().toString(bytes) + (bytes == 1 ? QStringLiteral(" byte)") : QStringLiteral(" bytes)"));}QString count(qint64 n, const QString &one, const QString &many){- const QLocale uk(QLocale::English, QLocale::UnitedKingdom);- return uk.toString(n) + QLatin1Char(' ') + (n == 1 ? one : many);+ return QLocale::system().toString(n) + QLatin1Char(' ') + (n == 1 ? one : many);}}diff --git a/packages/wildos-files/src/previewsource.cpp b/packages/wildos-files/src/previewsource.cppnew file mode 100644index 0000000..6721ea6--- /dev/null+++ b/packages/wildos-files/src/previewsource.cpp@@ -0,0 +1,149 @@+#include "previewsource.h"++#include <QCoreApplication>+#include <QFile>+#include <QFileInfo>+#include <QImageReader>+#include <QMimeDatabase>+#include <QPointer>+#include <QStringDecoder>+#include <QtConcurrentRun>++namespace+{+// Enough for any source file people read in a preview; a log of hundreds of+// megabytes would otherwise be loaded whole into a text view.+constexpr qint64 TextLimit = 200 * 1024;++struct Result {+ QString kind;+ QString mimeType;+ QString text;+ bool truncated = false;+};++// Text is a file with no NUL bytes near its start. Catches JSON, YAML, logs+// and config files whose MIME type does not say text/plain.+bool looksLikeText(const QByteArray &head)+{+ return !head.isEmpty() && !head.contains('\0');+}++Result inspect(const QString &path)+{+ Result r;+ const QFileInfo info(path);+ if (info.isDir()) {+ r.kind = QStringLiteral("folder");+ return r;+ }+ const QMimeType mime = QMimeDatabase().mimeTypeForFile(path);+ const QString name = mime.name();+ r.mimeType = name;++ static const QList<QByteArray> images = QImageReader::supportedMimeTypes();+ if (name == QLatin1String("application/pdf")) {+ r.kind = QStringLiteral("pdf");+ return r;+ }+ if (name == QLatin1String("image/gif") || name == QLatin1String("image/webp")) {+ r.kind = QStringLiteral("animated");+ return r;+ }+ if (name.startsWith(QLatin1String("image/")) && images.contains(name.toLatin1())) {+ r.kind = QStringLiteral("image");+ return r;+ }++ const bool textType = mime.inherits(QStringLiteral("text/plain"));+ if (!textType && name.startsWith(QLatin1String("video/"))) {+ r.kind = QStringLiteral("video");+ return r;+ }+ if (!textType && name.startsWith(QLatin1String("audio/"))) {+ r.kind = QStringLiteral("audio");+ return r;+ }++ r.kind = QStringLiteral("other");+ if (info.size() == 0) {+ return r;+ }+ QFile file(path);+ if (!file.open(QIODevice::ReadOnly)) {+ return r;+ }+ const QByteArray data = file.read(TextLimit);+ if (!looksLikeText(data.left(8192))) {+ return r;+ }+ r.truncated = info.size() > data.size();+ QByteArray body = data;+ // Cut at the last whole line, so a character split by the limit never+ // shows up as a replacement mark.+ if (r.truncated) {+ const qsizetype end = body.lastIndexOf('\n');+ if (end > 0) {+ body.truncate(end);+ }+ }+ QStringDecoder utf8(QStringDecoder::Utf8);+ QString text = utf8.decode(body);+ if (utf8.hasError()) {+ // Older Windows text files are not UTF-8; Latin-1 shows them close+ // enough to read.+ text = QString::fromLatin1(body);+ }+ r.kind = QStringLiteral("text");+ r.text = text;+ return r;+}+}++PreviewSource::PreviewSource(QObject *parent)+ : QObject(parent)+{+}++void PreviewSource::setUrl(const QUrl &url)+{+ if (url == m_url) {+ return;+ }+ m_url = url;+ Q_EMIT urlChanged();+ m_kind.clear();+ m_mimeType.clear();+ m_text.clear();+ m_truncated = false;+ const int generation = ++m_generation;+ if (url.isEmpty()) {+ Q_EMIT changed();+ return;+ }+ // Anything outside the local file system (the Recycle Bin, network+ // places) is read through KIO, which the image and media views cannot+ // do, so those get the icon and details.+ if (!url.isLocalFile()) {+ m_kind = QStringLiteral("other");+ Q_EMIT changed();+ return;+ }+ Q_EMIT changed();++ const QString path = url.toLocalFile();+ QPointer<PreviewSource> self(this);+ (void)QtConcurrent::run([path, self, generation] {+ const Result r = inspect(path);+ QMetaObject::invokeMethod(qApp, [self, generation, r] {+ if (!self || self->m_generation != generation) {+ return;+ }+ self->m_kind = r.kind;+ self->m_mimeType = r.mimeType;+ self->m_text = r.text;+ self->m_truncated = r.truncated;+ Q_EMIT self->changed();+ });+ });+}diff --git a/packages/wildos-files/src/previewsource.h b/packages/wildos-files/src/previewsource.hnew file mode 100644index 0000000..585f123--- /dev/null+++ b/packages/wildos-files/src/previewsource.h@@ -0,0 +1,45 @@+#pragma once++#include <QObject>+#include <QQmlEngine>+#include <QUrl>++// What Quick Look shows for one item: which kind of preview fits it and,+// for text and code, the start of the file. Worked out on a worker thread,+// so a slow drive never holds up the window.+class PreviewSource : public QObject+{+ Q_OBJECT+ QML_ELEMENT++ Q_PROPERTY(QUrl url READ url WRITE setUrl NOTIFY urlChanged)+ // "", while it is being worked out, then "folder", "image", "animated",+ // "pdf", "video", "audio", "text" or "other".+ Q_PROPERTY(QString kind READ kind NOTIFY changed)+ Q_PROPERTY(QString mimeType READ mimeType NOTIFY changed)+ Q_PROPERTY(QString text READ text NOTIFY changed)+ // True when the file is longer than the part read for the preview.+ Q_PROPERTY(bool truncated READ truncated NOTIFY changed)++public:+ explicit PreviewSource(QObject *parent = nullptr);++ QUrl url() const { return m_url; }+ void setUrl(const QUrl &url);+ QString kind() const { return m_kind; }+ QString mimeType() const { return m_mimeType; }+ QString text() const { return m_text; }+ bool truncated() const { return m_truncated; }++Q_SIGNALS:+ void urlChanged();+ void changed();++private:+ QUrl m_url;+ QString m_kind;+ QString m_mimeType;+ QString m_text;+ bool m_truncated = false;+ int m_generation = 0;+};diff --git a/packages/wildos-lighting/CMakeLists.txt b/packages/wildos-lighting/CMakeLists.txtnew file mode 100644index 0000000..11ff8f2--- /dev/null+++ b/packages/wildos-lighting/CMakeLists.txt@@ -0,0 +1,30 @@+cmake_minimum_required(VERSION 3.25)+project(wildos-lighting VERSION 0.1.0 LANGUAGES CXX)++set(CMAKE_CXX_STANDARD 20)+set(CMAKE_CXX_STANDARD_REQUIRED ON)+include(GNUInstallDirs)++find_package(Qt6 6.8 REQUIRED COMPONENTS Core Gui DBus Network)+find_package(KF6Config REQUIRED)+qt_standard_project_setup(REQUIRES 6.8)++# QtGui for QColor only; the program opens no windows.+qt_add_executable(wildos-lighting src/main.cpp src/lighting.cpp src/lighting.h src/plan.cpp src/plan.h)+target_link_libraries(wildos-lighting PRIVATE Qt6::Core Qt6::Gui Qt6::DBus Qt6::Network KF6::ConfigCore)++install(TARGETS wildos-lighting RUNTIME DESTINATION libexec/wildos)+install(PROGRAMS libexec/rgb-devices DESTINATION libexec/wildos)+install(FILES data/wildos-lighting.service data/wildos-openrgb.service DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/systemd/user)+install(FILES data/60-openrgb.rules DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/udev/rules.d)++include(CTest)+if(BUILD_TESTING)+ find_package(Qt6 6.8 REQUIRED COMPONENTS Test)+ add_executable(plantest tests/plantest.cpp src/plan.cpp)+ target_include_directories(plantest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)+ target_link_libraries(plantest PRIVATE Qt6::Core Qt6::Gui Qt6::Test)+ add_test(NAME plan COMMAND plantest)+ # rgb-devices against a fake sysfs and rules file.+ add_test(NAME scripts COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/tests/scripts.sh ${CMAKE_CURRENT_SOURCE_DIR}/libexec)+endif()diff --git a/packages/wildos-lighting/data/60-openrgb.rules b/packages/wildos-lighting/data/60-openrgb.rulesnew file mode 100644index 0000000..9ae9e90--- /dev/null+++ b/packages/wildos-lighting/data/60-openrgb.rules@@ -0,0 +1,27 @@+# Device access for OpenRGB, in place of the rules OpenRGB ships.+#+# wildos-lighting moves OpenRGB's own 60-openrgb.rules aside (to+# 60-openrgb.rules.stock, which udev does not read) because they give more+# than keyboard and mouse lighting needs:+#+# - every I2C/SMBus bus to whoever is at the screen: memory modules and+# motherboard and graphics card controllers sit on them, where a bad+# write can damage hardware; /dev/port likewise;+# - write access for every account on the computer to some laptops'+# keyboard backlight controls (chmod a+w);+# - each listed USB device whole, raw USB node included, through which+# firmware can be replaced, and its keyboard interface, through which+# every key typed can be read, passwords included.+#+# Here the person at the screen (the uaccess tag: logind grants the active+# session's user, and takes it back when another account comes to the+# front) gets the hidraw nodes of USB devices in OpenRGB's table, except+# nodes that report key presses. No other account gets anything. OpenRGB+# then drives USB keyboards, mice and other HID lighting; it cannot reach+# memory, motherboard or graphics card lighting, controllers it drives+# through raw USB, or keyboards whose lighting shares the interface that+# carries the keys.+ACTION=="remove", GOTO="wildos_openrgb_end"+SUBSYSTEM!="hidraw", GOTO="wildos_openrgb_end"+PROGRAM="/usr/libexec/wildos/rgb-devices access %p", TAG+="uaccess"+LABEL="wildos_openrgb_end"diff --git a/packages/wildos-lighting/data/wildos-lighting.service b/packages/wildos-lighting/data/wildos-lighting.servicenew file mode 100644index 0000000..a34f7de--- /dev/null+++ b/packages/wildos-lighting/data/wildos-lighting.service@@ -0,0 +1,16 @@+[Unit]+Description=Keep keyboard and mouse lighting in step with the taskbar underglow+PartOf=graphical-session.target+After=graphical-session.target+# Debian trixie has no OpenRGB package; without one installed there is+# nothing to light.+ConditionFileIsExecutable=/usr/bin/openrgb++[Service]+Type=exec+ExecStart=/usr/libexec/wildos/wildos-lighting+Restart=on-failure+RestartSec=5++[Install]+WantedBy=graphical-session.targetdiff --git a/packages/wildos-lighting/data/wildos-openrgb.service b/packages/wildos-lighting/data/wildos-openrgb.servicenew file mode 100644index 0000000..ff234e3--- /dev/null+++ b/packages/wildos-lighting/data/wildos-openrgb.service@@ -0,0 +1,21 @@+[Unit]+Description=OpenRGB server for Wild OS keyboard and mouse lighting+Documentation=man:openrgb(1)+# Started and stopped by wildos-lighting only, while Settings has the+# lighting on and this account's session is in front; it goes when that does.+PartOf=wildos-lighting.service+ConditionFileIsExecutable=/usr/bin/openrgb++[Service]+Type=exec+# OpenRGB's SDK has no authentication, so it listens on the loopback only,+# set here rather than left to OpenRGB's default. Its settings and profiles+# live in a directory of their own.+ExecStart=/usr/bin/openrgb --server --server-host 127.0.0.1 --server-port 6742 --config %S/wildos/openrgb+StateDirectory=wildos/openrgb+Restart=on-failure+RestartSec=5+NoNewPrivileges=yes+# Local sockets, the loopback and udev's device events; no IPv6, no raw or+# packet sockets, no Bluetooth.+RestrictAddressFamilies=AF_UNIX AF_INET AF_NETLINKdiff --git a/packages/wildos-lighting/debian/changelog b/packages/wildos-lighting/debian/changelognew file mode 100644index 0000000..df40bb6--- /dev/null+++ b/packages/wildos-lighting/debian/changelog@@ -0,0 +1,6 @@+wildos-lighting (0.1.0) trixie; urgency=medium++ * Keyboard and mouse lighting that follows the taskbar underglow, through+ an OpenRGB server on the loopback that runs only while it is turned on.++ -- Wild OS Developers <[email protected]> Mon, 09 Nov 2026 12:00:00 +0000diff --git a/packages/wildos-lighting/debian/control b/packages/wildos-lighting/debian/controlnew file mode 100644index 0000000..e1ef94c--- /dev/null+++ b/packages/wildos-lighting/debian/control@@ -0,0 +1,29 @@+Source: wildos-lighting+Section: x11+Priority: optional+Maintainer: Wild OS Developers <[email protected]>+Build-Depends:+ debhelper-compat (= 13),+ cmake,+ qt6-base-dev,+ libkf6config-dev,+Standards-Version: 4.7.0+Rules-Requires-Root: no++Package: wildos-lighting+Architecture: any+Depends:+ ${shlibs:Depends},+ ${misc:Depends},+ udev,+Suggests:+ openrgb (>= 1.0),+Description: Wild OS keyboard and mouse lighting+ Sets RGB keyboards, mice and other USB lighting to the colour and effect+ of the taskbar underglow, through OpenRGB, when Settings has it turned on.+ .+ OpenRGB's server runs only while the lighting is on and the session is in+ front, and listens on the loopback only. OpenRGB's own udev rules are+ replaced with narrower ones: the person at the screen gets the hidraw+ nodes of supported USB devices, except those that report key presses, and+ nothing else.diff --git a/packages/wildos-lighting/debian/postinst b/packages/wildos-lighting/debian/postinstnew file mode 100644index 0000000..dc57f63--- /dev/null+++ b/packages/wildos-lighting/debian/postinst@@ -0,0 +1,11 @@+#!/bin/sh+set -e++# Apply the rules to devices already plugged in. Outside a running system+# (the image build) there is no udev to ask, which is fine.+if [ "$1" = "configure" ]; then+ udevadm control --reload >/dev/null 2>&1 || true+ udevadm trigger --subsystem-match=hidraw --action=change >/dev/null 2>&1 || true+fi++#DEBHELPER#diff --git a/packages/wildos-lighting/debian/postrm b/packages/wildos-lighting/debian/postrmnew file mode 100644index 0000000..fca61a6--- /dev/null+++ b/packages/wildos-lighting/debian/postrm@@ -0,0 +1,11 @@+#!/bin/sh+set -e++if [ "$1" = "remove" ] || [ "$1" = "purge" ] || [ "$1" = "abort-install" ]; then+ dpkg-divert --package wildos-lighting --remove --rename \+ --divert /usr/lib/udev/rules.d/60-openrgb.rules.stock \+ /usr/lib/udev/rules.d/60-openrgb.rules >/dev/null || true+ udevadm control --reload >/dev/null 2>&1 || true+fi++#DEBHELPER#diff --git a/packages/wildos-lighting/debian/preinst b/packages/wildos-lighting/debian/preinstnew file mode 100644index 0000000..0f860e5--- /dev/null+++ b/packages/wildos-lighting/debian/preinst@@ -0,0 +1,14 @@+#!/bin/sh+set -e++# OpenRGB's udev rules give more than lighting needs (see 60-openrgb.rules+# in this package). Divert them under a name udev does not read, so ours+# take their place and their device table stays readable. The diversion+# also catches an OpenRGB installed later.+if [ "$1" = "install" ] || [ "$1" = "upgrade" ]; then+ dpkg-divert --package wildos-lighting --add --rename \+ --divert /usr/lib/udev/rules.d/60-openrgb.rules.stock \+ /usr/lib/udev/rules.d/60-openrgb.rules >/dev/null+fi++#DEBHELPER#diff --git a/packages/wildos-lighting/debian/rules b/packages/wildos-lighting/debian/rulesnew file mode 100644index 0000000..393af14--- /dev/null+++ b/packages/wildos-lighting/debian/rules@@ -0,0 +1,7 @@+#!/usr/bin/make -f++%:+ dh $@++override_dh_auto_configure:+ dh_auto_configure -- -DCMAKE_BUILD_TYPE=Releasediff --git a/packages/wildos-lighting/debian/source/format b/packages/wildos-lighting/debian/source/formatnew file mode 100644index 0000000..89ae9db--- /dev/null+++ b/packages/wildos-lighting/debian/source/format@@ -0,0 +1 @@+3.0 (native)diff --git a/packages/wildos-lighting/libexec/rgb-devices b/packages/wildos-lighting/libexec/rgb-devicesnew file mode 100644index 0000000..353c113--- /dev/null+++ b/packages/wildos-lighting/libexec/rgb-devices@@ -0,0 +1,140 @@+#!/bin/sh+# OpenRGB devices for Settings and for udev.+#+# rgb-devices How many plugged-in devices OpenRGB can light+# for this user: 0 when there are none or+# OpenRGB is not installed. Settings shows the+# lighting row only when this is above 0.+# rgb-devices access DEVPATH For 60-openrgb.rules: succeeds when the+# hidraw node at DEVPATH may be given to the+# person at the screen.+#+# Both only read sysfs and OpenRGB's own udev rules, which carry its table of+# supported USB devices; they start no server and open no device. The count+# needs no privileges and takes a few milliseconds.+#+# A device counts when OpenRGB lists it and this user may open one of its+# hidraw nodes, so devices USBGuard blocks, and devices whose only hidraw+# nodes are the keyboard ones held back below, are not counted.+#+# A trailing ROOT argument reads a fake sysfs and rules file under ROOT+# instead, for the tests.++export LC_ALL=C++if [ "${1:-}" = access ]; then+ devpath=${2:-}+ root=${3:-}+else+ root=${1:-}+fi+# Installing OpenRGB puts its rules here: Wild OS moves them aside (see+# wildos-lighting's preinst) and reads only its device table.+stock=$root/usr/lib/udev/rules.d/60-openrgb.rules.stock++# The USB device a sysfs device belongs to, by walking up to the first+# parent with vendor and product IDs.+usb_parent() {+ d=$1+ while [ -n "$d" ] && [ "$d" != "$root/sys" ] && [ "$d" != / ]; do+ if [ -r "$d/idVendor" ] && [ -r "$d/idProduct" ]; then+ echo "$d"+ return 0+ fi+ up=${d%/*}+ [ "$up" = "$d" ] && break+ d=$up+ done+ return 1+}++# Whether OpenRGB's rules give access to this vendor and product, in the+# exact form OpenRGB writes them.+listed() {+ vid=$(cat "$1/idVendor" 2>/dev/null)+ pid=$(cat "$1/idProduct" 2>/dev/null)+ case "$vid$pid" in+ *[!0-9a-f]* | "") return 1 ;;+ esac+ [ ${#vid} -eq 4 ] && [ ${#pid} -eq 4 ] || return 1+ grep -qF "ATTRS{idVendor}==\"$vid\", ATTRS{idProduct}==\"$pid\", TAG+=\"uaccess\"" "$stock" \+ || grep -qF "ATTRS{idVendor}==\"$vid\", TAG+=\"uaccess\"" "$stock"+}++# Whether a HID interface reports key presses: its report descriptor has a+# keyboard or keypad application collection, or an input on the keyboard+# usage page. Anyone who can read such a node can read what is typed,+# passwords included, so these stay root's alone. The descriptor comes from+# the device, so it is read as numbers and never trusted to be well formed.+carries_keys() {+ [ -r "$1" ] || return 0+ od -An -v -tu1 "$1" | awk '+ { for (i = 1; i <= NF; i++) b[n++] = $i }+ END {+ page = 0; usage = -1; upage = -1; keys = 0; i = 0+ while (i < n) {+ p = b[i]+ if (p == 254) {+ if (i + 1 >= n) break+ i += 3 + b[i + 1]+ continue+ }+ size = p % 4+ if (size == 3) size = 4+ type = int(p / 4) % 4+ tag = int(p / 16)+ v = 0+ for (k = size; k >= 1; k--) v = v * 256 + b[i + k]+ if (type == 1 && tag == 0) {+ page = v+ } else if (type == 2 && tag == 0 && usage < 0) {+ if (size == 4) { upage = int(v / 65536); usage = v % 65536 }+ else { upage = page; usage = v }+ } else if (type == 0) {+ if (tag == 10 && v == 1 && upage == 1 && (usage == 6 || usage == 7)) keys = 1+ if (tag == 8 && page == 7) keys = 1+ usage = -1+ upage = -1+ }+ i += 1 + size+ }+ exit keys ? 0 : 1+ }'+}++[ -x "$root/usr/bin/openrgb" ] && [ -r "$stock" ] || {+ [ "${1:-}" = access ] && exit 1+ echo 0+ exit 0+}++if [ "${1:-}" = access ]; then+ case "$devpath" in+ */../* | */..) exit 1 ;;+ /devices/*/hidraw/hidraw[0-9]*) ;;+ *) exit 1 ;;+ esac+ node=$root/sys$devpath+ hid=${node%/hidraw/*}+ usb=$(usb_parent "$hid") || exit 1+ listed "$usb" || exit 1+ carries_keys "$hid/report_descriptor" && exit 1+ exit 0+fi++seen=+count=0+for link in "$root"/sys/class/hidraw/hidraw*; do+ [ -e "$link" ] || continue+ name=${link##*/}+ [ -r "$root/dev/$name" ] && [ -w "$root/dev/$name" ] || continue+ hid=$(readlink -f "$link/device") || continue+ usb=$(usb_parent "$hid") || continue+ case " $seen " in+ *" $usb "*) continue ;;+ esac+ listed "$usb" || continue+ seen="$seen $usb"+ count=$((count + 1))+done+echo "$count"diff --git a/packages/wildos-lighting/src/lighting.cpp b/packages/wildos-lighting/src/lighting.cppnew file mode 100644index 0000000..401305e--- /dev/null+++ b/packages/wildos-lighting/src/lighting.cpp@@ -0,0 +1,298 @@+#include "lighting.h"+#include "plan.h"++#include <KConfigGroup>+#include <KSharedConfig>++#include <QDBusArgument>+#include <QDBusConnection>+#include <QDBusMessage>+#include <QDBusPendingCallWatcher>+#include <QDBusPendingReply>+#include <QDBusVariant>+#include <QDir>+#include <QStandardPaths>+#include <QHostAddress>+#include <QTcpSocket>++namespace+{+const QString openrgb = QStringLiteral("/usr/bin/openrgb");+const QString serverUnit = QStringLiteral("wildos-openrgb.service");+// OpenRGB's own default, which its command line looks for when it joins a+// running server. wildos-openrgb.service binds it on 127.0.0.1 only.+constexpr quint16 serverPort = 6742;++const QString login1 = QStringLiteral("org.freedesktop.login1");+const QString upower = QStringLiteral("org.freedesktop.UPower");+const QString properties = QStringLiteral("org.freedesktop.DBus.Properties");++void getProperty(const QDBusConnection &bus, const QString &service, const QString &path, const QString &interface, const QString &name,+ QObject *context, std::function<void(const QVariant &)> done)+{+ QDBusMessage call = QDBusMessage::createMethodCall(service, path, properties, QStringLiteral("Get"));+ call << interface << name;+ auto watcher = new QDBusPendingCallWatcher(bus.asyncCall(call), context);+ QObject::connect(watcher, &QDBusPendingCallWatcher::finished, context, [watcher, done] {+ watcher->deleteLater();+ const QDBusPendingReply<QDBusVariant> reply = *watcher;+ if (!reply.isError()) {+ done(reply.value().variant());+ }+ });+}+}++Lighting::Lighting(QObject *parent)+ : QObject(parent)+ , m_wildos(KConfigWatcher::create(KSharedConfig::openConfig(QStringLiteral("wildosrc"))))+ , m_globals(KConfigWatcher::create(KSharedConfig::openConfig(QStringLiteral("kdeglobals"))))+{+ // Settings writes several keys at once; act on the last of them.+ m_sync.setSingleShot(true);+ m_sync.setInterval(300);+ connect(&m_sync, &QTimer::timeout, this, &Lighting::sync);++ m_retry.setInterval(500);+ connect(&m_retry, &QTimer::timeout, this, &Lighting::waitForServer);++ connect(m_wildos.data(), &KConfigWatcher::configChanged, this, [this](const KConfigGroup &group) {+ if (group.name() == QLatin1String("Underglow") || group.name() == QLatin1String("Lighting")) {+ readSettings();+ }+ });+ connect(m_globals.data(), &KConfigWatcher::configChanged, this, [this](const KConfigGroup &group) {+ if (group.name() == QLatin1String("General") || group.name() == QLatin1String("KDE")) {+ readSettings();+ }+ });++ QDBusConnection system = QDBusConnection::systemBus();+ system.connect(upower, QStringLiteral("/org/freedesktop/UPower"), properties, QStringLiteral("PropertiesChanged"), this,+ SLOT(upowerChanged(QString, QVariantMap, QStringList)));+ // Devices come back from suspend in their own default lighting.+ system.connect(login1, QStringLiteral("/org/freedesktop/login1"), QStringLiteral("org.freedesktop.login1.Manager"),+ QStringLiteral("PrepareForSleep"), this, SLOT(prepareForSleep(bool)));++ readSettings();+ readBattery();+ findSession();+}++void Lighting::readSettings()+{+ KSharedConfigPtr wildos = KSharedConfig::openConfig(QStringLiteral("wildosrc"));+ wildos->reparseConfiguration();+ m_rgb = wildos->group(QStringLiteral("Lighting")).readEntry("Rgb", false);+ const KConfigGroup glow = wildos->group(QStringLiteral("Underglow"));+ m_colour = glow.readEntry("Colour", QString());+ m_custom = glow.readEntry("Custom", QString());+ m_effect = glow.readEntry("Effect", QString());++ KSharedConfigPtr globals = KSharedConfig::openConfig(QStringLiteral("kdeglobals"));+ globals->reparseConfiguration();+ m_accent = globals->group(QStringLiteral("General")).readEntry("AccentColor", QString());+ m_reducedMotion = globals->group(QStringLiteral("KDE")).readEntry("AnimationDurationFactor", 1.0) <= 0.0;++ m_sync.start();+}++void Lighting::readBattery()+{+ getProperty(QDBusConnection::systemBus(), upower, QStringLiteral("/org/freedesktop/UPower"), upower, QStringLiteral("OnBattery"), this,+ [this](const QVariant &value) {+ if (value.toBool() != m_onBattery) {+ m_onBattery = value.toBool();+ m_sync.start();+ }+ });+}++void Lighting::upowerChanged(const QString &interface, const QVariantMap &changed, const QStringList &invalidated)+{+ if (interface != upower) {+ return;+ }+ if (changed.contains(QStringLiteral("OnBattery"))) {+ const bool onBattery = changed.value(QStringLiteral("OnBattery")).toBool();+ if (onBattery != m_onBattery) {+ m_onBattery = onBattery;+ m_sync.start();+ }+ } else if (invalidated.contains(QLatin1String("OnBattery"))) {+ readBattery();+ }+}++void Lighting::findSession()+{+ // This runs as a user service, outside the session itself, so the+ // session is found through the user: Display is the graphical session+ // this account is signed in with.+ getProperty(QDBusConnection::systemBus(), login1, QStringLiteral("/org/freedesktop/login1/user/self"), QStringLiteral("org.freedesktop.login1.User"),+ QStringLiteral("Display"), this, [this](const QVariant &value) {+ const QDBusArgument arg = value.value<QDBusArgument>();+ QString id;+ QDBusObjectPath path;+ arg.beginStructure();+ arg >> id >> path;+ arg.endStructure();+ if (path.path().isEmpty() || path.path() == QLatin1String("/")) {+ return;+ }+ m_session = path;+ QDBusConnection::systemBus().connect(login1, path.path(), properties, QStringLiteral("PropertiesChanged"), this,+ SLOT(sessionChanged(QString, QVariantMap, QStringList)));+ readSessionActive();+ });+}++void Lighting::readSessionActive()+{+ getProperty(QDBusConnection::systemBus(), login1, m_session.path(), QStringLiteral("org.freedesktop.login1.Session"), QStringLiteral("Active"), this,+ [this](const QVariant &value) {+ if (value.toBool() != m_sessionActive) {+ m_sessionActive = value.toBool();+ m_sync.start();+ }+ });+}++void Lighting::sessionChanged(const QString &interface, const QVariantMap &changed, const QStringList &invalidated)+{+ if (interface != QLatin1String("org.freedesktop.login1.Session")) {+ return;+ }+ if (changed.contains(QStringLiteral("Active"))) {+ const bool active = changed.value(QStringLiteral("Active")).toBool();+ if (active != m_sessionActive) {+ m_sessionActive = active;+ m_sync.start();+ }+ } else if (invalidated.contains(QLatin1String("Active"))) {+ readSessionActive();+ }+}++void Lighting::prepareForSleep(bool sleeping)+{+ if (!sleeping && m_serverReady) {+ QTimer::singleShot(2000, this, &Lighting::apply);+ }+}++void Lighting::sync()+{+ const bool wanted = m_rgb && m_sessionActive;+ setServer(wanted);+ if (wanted && m_serverReady) {+ apply();+ }+}++void Lighting::setServer(bool on)+{+ // The first time round the server is stopped even if it seems off: one+ // left behind by a crashed copy of this program must not keep running.+ if (m_serverKnown && on == m_serverOn) {+ return;+ }+ m_serverKnown = true;+ m_serverOn = on;+ m_serverReady = false;+ m_retry.stop();++ QDBusMessage call = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.systemd1"), QStringLiteral("/org/freedesktop/systemd1"),+ QStringLiteral("org.freedesktop.systemd1.Manager"),+ on ? QStringLiteral("StartUnit") : QStringLiteral("StopUnit"));+ call << serverUnit << QStringLiteral("replace");+ QDBusConnection::sessionBus().asyncCall(call);+ qInfo("%s the OpenRGB server", on ? "Starting" : "Stopping");++ if (on) {+ m_waits = 0;+ m_retry.start();+ }+}++void Lighting::waitForServer()+{+ // A refused connection on the loopback answers at once, so this never+ // holds the event loop for long.+ QTcpSocket probe;+ probe.connectToHost(QHostAddress::LocalHost, serverPort);+ if (probe.waitForConnected(250)) {+ probe.abort();+ m_retry.stop();+ m_serverReady = true;+ // Detection can still be running when the server starts listening;+ // a second pass catches devices it found after the first.+ QTimer::singleShot(2000, this, &Lighting::apply);+ QTimer::singleShot(15000, this, &Lighting::apply);+ return;+ }+ if (++m_waits >= 120) {+ m_retry.stop();+ qWarning("The OpenRGB server did not start listening within a minute");+ }+}++void Lighting::run(const QStringList &arguments, std::function<void(const QString &)> done)+{+ // --nodetect: if the server has gone, the command does nothing rather+ // than open the devices itself. Its settings stay apart from the+ // server's and out of ~/.config.+ const QString config = QStandardPaths::writableLocation(QStandardPaths::GenericStateLocation) + QStringLiteral("/wildos/openrgb-client");+ QDir().mkpath(config);++ m_running = new QProcess(this);+ m_running->setProgram(openrgb);+ m_running->setArguments(QStringList{QStringLiteral("--nodetect"), QStringLiteral("--config"), config} + arguments);+ m_running->setProcessChannelMode(QProcess::SeparateChannels);+ QProcess *process = m_running;+ auto timeout = new QTimer(process);+ timeout->setSingleShot(true);+ connect(timeout, &QTimer::timeout, process, &QProcess::kill);+ connect(process, &QProcess::finished, this, [this, process, done] {+ const QString out = QString::fromUtf8(process->readAllStandardOutput());+ process->deleteLater();+ m_running = nullptr;+ done(out);+ });+ connect(process, &QProcess::errorOccurred, this, [this, process](QProcess::ProcessError error) {+ if (error == QProcess::FailedToStart) {+ process->deleteLater();+ m_running = nullptr;+ }+ });+ timeout->start(30000);+ process->start();+}++void Lighting::apply()+{+ if (!m_serverReady) {+ return;+ }+ if (m_running) {+ m_applyAgain = true;+ return;+ }+ m_applyAgain = false;++ const Plan::Look look = Plan::look(m_colour, m_effect, m_onBattery, m_reducedMotion);+ const QColor colour = Plan::colourFor(m_colour, m_custom, Plan::parseAccent(m_accent));+ run({QStringLiteral("--list-detailed")}, [this, look, colour](const QString &listing) {+ const QStringList args = Plan::arguments(Plan::parseDevices(listing), look, colour);+ const auto finish = [this](const QString &) {+ if (m_applyAgain) {+ apply();+ }+ };+ if (args.isEmpty()) {+ finish(QString());+ return;+ }+ run(args, finish);+ });+}diff --git a/packages/wildos-lighting/src/lighting.h b/packages/wildos-lighting/src/lighting.hnew file mode 100644index 0000000..0a8661a--- /dev/null+++ b/packages/wildos-lighting/src/lighting.h@@ -0,0 +1,64 @@+#pragma once++#include <KConfigWatcher>++#include <QDBusObjectPath>+#include <QObject>+#include <QProcess>+#include <QTimer>++#include <functional>++// Keeps the keyboard and mouse lighting in step with the taskbar underglow.+//+// OpenRGB's server (wildos-openrgb.service) runs only while Settings has+// the lighting on (wildosrc [Lighting] Rgb) and this session is the one in+// front: on a switch to another account it stops and lets go of the+// devices, so this account keeps no hold on them meanwhile. The colours are+// set through openrgb's command line, which joins the running server as a+// client instead of opening the devices itself.+class Lighting : public QObject+{+ Q_OBJECT++public:+ explicit Lighting(QObject *parent = nullptr);++private Q_SLOTS:+ void upowerChanged(const QString &interface, const QVariantMap &changed, const QStringList &invalidated);+ void sessionChanged(const QString &interface, const QVariantMap &changed, const QStringList &invalidated);+ void prepareForSleep(bool sleeping);++private:+ void readSettings();+ void readBattery();+ void findSession();+ void readSessionActive();+ void sync();+ void setServer(bool on);+ void waitForServer();+ void apply();+ void run(const QStringList &arguments, std::function<void(const QString &)> done);++ KConfigWatcher::Ptr m_wildos;+ KConfigWatcher::Ptr m_globals;+ QTimer m_sync;+ QTimer m_retry;++ bool m_rgb = false;+ QString m_colour;+ QString m_custom;+ QString m_effect;+ QString m_accent;+ bool m_reducedMotion = false;+ bool m_onBattery = false;+ bool m_sessionActive = true;+ QDBusObjectPath m_session;++ bool m_serverOn = false;+ bool m_serverKnown = false;+ bool m_serverReady = false;+ int m_waits = 0;+ QProcess *m_running = nullptr;+ bool m_applyAgain = false;+};diff --git a/packages/wildos-lighting/src/main.cpp b/packages/wildos-lighting/src/main.cppnew file mode 100644index 0000000..07ea08d--- /dev/null+++ b/packages/wildos-lighting/src/main.cpp@@ -0,0 +1,11 @@+#include "lighting.h"++#include <QCoreApplication>++int main(int argc, char **argv)+{+ QCoreApplication app(argc, argv);+ app.setApplicationName(QStringLiteral("wildos-lighting"));+ Lighting lighting;+ return app.exec();+}diff --git a/packages/wildos-lighting/src/plan.cpp b/packages/wildos-lighting/src/plan.cppnew file mode 100644index 0000000..2952959--- /dev/null+++ b/packages/wildos-lighting/src/plan.cpp@@ -0,0 +1,208 @@+#include "plan.h"++#include <QRegularExpression>++namespace Plan+{+namespace+{+// Glacier, as everywhere in Wild OS before an accent is picked.+const QColor glacier(0x8f, 0xb4, 0xff);++QString hex(const QColor &c)+{+ return c.name(QColor::HexRgb).mid(1);+}++// The first of `wanted` the device offers, in the device's own spelling.+QString pick(const QStringList &modes, const QStringList &wanted)+{+ for (const QString &w : wanted) {+ for (const QString &m : modes) {+ if (m.compare(w, Qt::CaseInsensitive) == 0) {+ return m;+ }+ }+ }+ return QString();+}++QColor spectrumAt(qreal t)+{+ const QList<QColor> stops = spectrum();+ const qreal scaled = t * (stops.size() - 1);+ const int i = qBound(0, int(scaled), int(stops.size()) - 2);+ const qreal f = scaled - i;+ const QColor a = stops[i];+ const QColor b = stops[i + 1];+ return QColor::fromRgbF(a.redF() + (b.redF() - a.redF()) * f, a.greenF() + (b.greenF() - a.greenF()) * f,+ a.blueF() + (b.blueF() - a.blueF()) * f);+}+}++QList<QColor> spectrum()+{+ return {QColor(0xff, 0x3d, 0x6e), QColor(0xff, 0xb0, 0x3d), QColor(0xf5, 0xff, 0x3d), QColor(0x3d, 0xff, 0x7a),+ QColor(0x3d, 0xd5, 0xff), QColor(0x5c, 0x7c, 0xff), QColor(0xc8, 0x5c, 0xff), QColor(0xff, 0x3d, 0x6e)};+}++QColor parseAccent(const QString &value)+{+ // The colours module writes "r,g,b"; older tools wrote a #hex name.+ const QStringList parts = value.split(QLatin1Char(','));+ QColor colour;+ if (parts.size() >= 3) {+ colour = QColor(parts[0].trimmed().toInt(), parts[1].trimmed().toInt(), parts[2].trimmed().toInt());+ } else if (!value.isEmpty()) {+ colour = QColor(value.trimmed());+ }+ return colour.isValid() ? colour : glacier;+}++QColor colourFor(const QString &colour, const QString &custom, const QColor &accent)+{+ static const QRegularExpression rrggbb(QStringLiteral("^#[0-9a-fA-F]{6}$"));+ if (colour.trimmed().compare(QLatin1String("custom"), Qt::CaseInsensitive) == 0 && rrggbb.match(custom.trimmed()).hasMatch()) {+ return QColor(custom.trimmed());+ }+ return accent;+}++Look look(const QString &colour, const QString &effect, bool onBattery, bool reducedMotion)+{+ const bool still = onBattery || reducedMotion;+ const QString e = effect.trimmed().toLower();+ if (colour.trimmed().compare(QLatin1String("rgb"), Qt::CaseInsensitive) == 0) {+ return still || e == QLatin1String("steady") ? Look::FrozenSpectrum : Look::Spectrum;+ }+ return !still && e == QLatin1String("breathing") ? Look::Breathing : Look::Colour;+}++QStringList splitNames(const QString &line)+{+ QStringList names;+ QString current;+ bool quoted = false;+ bool inName = false;+ for (const QChar c : line) {+ if (quoted) {+ if (c == QLatin1Char('\'')) {+ quoted = false;+ } else {+ current += c;+ }+ } else if (c == QLatin1Char(' ')) {+ if (inName) {+ names.append(current);+ current.clear();+ inName = false;+ }+ } else if (c == QLatin1Char('\'') && !inName) {+ quoted = true;+ inName = true;+ } else {+ current += c;+ inName = true;+ }+ }+ if (inName) {+ names.append(current);+ }+ return names;+}++QList<Device> parseDevices(const QString &listing)+{+ static const QRegularExpression header(QStringLiteral("^(\\d+): (.*)$"));+ QList<Device> devices;+ for (const QString &line : listing.split(QLatin1Char('\n'))) {+ const QRegularExpressionMatch m = header.match(line);+ if (m.hasMatch()) {+ Device d;+ d.index = m.captured(1).toInt();+ d.name = m.captured(2).trimmed();+ devices.append(d);+ continue;+ }+ if (devices.isEmpty()) {+ continue;+ }+ const QString trimmed = line.trimmed();+ if (trimmed.startsWith(QLatin1String("Modes:"))) {+ // The active mode is shown in brackets, outside the quotes of a+ // name with spaces: ['Spectrum Cycle']. Moving the brackets+ // inside lets the name split like the others.+ QString rest = trimmed.mid(6);+ rest.replace(QLatin1String("['"), QLatin1String("'["));+ rest.replace(QLatin1String("']"), QLatin1String("]'"));+ QStringList modes = splitNames(rest);+ for (QString &mode : modes) {+ if (mode.startsWith(QLatin1Char('[')) && mode.endsWith(QLatin1Char(']'))) {+ mode = mode.mid(1, mode.size() - 2);+ }+ }+ devices.last().modes = modes;+ } else if (trimmed.startsWith(QLatin1String("LEDs:"))) {+ devices.last().leds = splitNames(trimmed.mid(5)).size();+ }+ }+ return devices;+}++QStringList arguments(const QList<Device> &devices, Look look, const QColor &colour)+{+ static const QStringList solid = {QStringLiteral("Static"), QStringLiteral("Direct")};+ static const QStringList breathing = {QStringLiteral("Breathing")};+ static const QStringList flowing = {QStringLiteral("Rainbow Wave"), QStringLiteral("Rainbow"), QStringLiteral("Spectrum Cycle"),+ QStringLiteral("Wave")};++ QStringList args;+ for (const Device &d : devices) {+ const auto set = [&args, &d](const QString &mode, const QString &colours) {+ args << QStringLiteral("--device") << QString::number(d.index) << QStringLiteral("--mode") << mode;+ if (!colours.isEmpty()) {+ args << QStringLiteral("--color") << colours;+ }+ };++ if (look == Look::Spectrum) {+ const QString mode = pick(d.modes, flowing);+ if (!mode.isEmpty()) {+ set(mode, QString());+ continue;+ }+ }+ if (look == Look::Spectrum || look == Look::FrozenSpectrum) {+ // Direct takes a colour per LED, so the spectrum can be laid+ // across the device. A device that can only show one colour+ // takes the spectrum's middle.+ const QString direct = pick(d.modes, {QStringLiteral("Direct")});+ if (!direct.isEmpty() && d.leds > 1) {+ QStringList colours;+ for (int i = 0; i < d.leds; ++i) {+ colours << hex(spectrumAt(qreal(i) / d.leds));+ }+ set(direct, colours.join(QLatin1Char(',')));+ continue;+ }+ const QString mode = pick(d.modes, solid);+ if (!mode.isEmpty()) {+ set(mode, hex(spectrum().at(4)));+ }+ continue;+ }+ if (look == Look::Breathing) {+ const QString mode = pick(d.modes, breathing);+ if (!mode.isEmpty()) {+ set(mode, hex(colour));+ continue;+ }+ }+ const QString mode = pick(d.modes, solid);+ if (!mode.isEmpty()) {+ set(mode, hex(colour));+ }+ }+ return args;+}+}diff --git a/packages/wildos-lighting/src/plan.h b/packages/wildos-lighting/src/plan.hnew file mode 100644index 0000000..5b54a5d--- /dev/null+++ b/packages/wildos-lighting/src/plan.h@@ -0,0 +1,54 @@+#pragma once++#include <QColor>+#include <QList>+#include <QString>+#include <QStringList>++// What the keyboard and mouse lighting shows, and the openrgb command that+// shows it, kept apart from processes and D-Bus so it can be tested alone.+// The lighting copies the taskbar underglow: the same colour and effect from+// wildosrc [Underglow], on the same rules as wildos-shell's+// underglowsettings.cpp, which the two packages cannot share.+namespace Plan+{+enum class Look {+ Colour,+ Breathing,+ Spectrum,+ // The spectrum standing still: RGB set to steady, or on battery or+ // with Reduce motion on.+ FrozenSpectrum,+};++// The spectrum's stops, as the board's RGB gradient has them.+QList<QColor> spectrum();++QColor parseAccent(const QString &value);++// The colour the devices take for accent or custom. A custom value that is+// not #rrggbb falls back to the accent, as on the taskbar.+QColor colourFor(const QString &colour, const QString &custom, const QColor &accent);++// The underglow's effect after the steady fallbacks. Full screen is left+// out: the devices run their effect themselves, which costs a game nothing.+Look look(const QString &colour, const QString &effect, bool onBattery, bool reducedMotion);++struct Device {+ int index = -1;+ QString name;+ QStringList modes;+ int leds = 0;+};++// Reads `openrgb --list-detailed`.+QList<Device> parseDevices(const QString &listing);++// One line of that listing split into names, where a name with spaces is+// in single quotes.+QStringList splitNames(const QString &line);++// The openrgb arguments that set every device to `look`. A device that+// offers none of the modes the look needs is left as it is.+QStringList arguments(const QList<Device> &devices, Look look, const QColor &colour);+}diff --git a/packages/wildos-lighting/tests/plantest.cpp b/packages/wildos-lighting/tests/plantest.cppnew file mode 100644index 0000000..2df5b10--- /dev/null+++ b/packages/wildos-lighting/tests/plantest.cpp@@ -0,0 +1,144 @@+#include "plan.h"++#include <QTest>++using namespace Plan;++namespace+{+// The shape `openrgb --list-detailed` prints (cli.cpp, OptionListDevices).+const QString listing = QStringLiteral(+ "0: Corsair K70 RGB PRO\n"+ " Type: Keyboard\n"+ " Description: Corsair Peripheral Device\n"+ " Modes: [Direct] Static Breathing 'Rainbow Wave' 'Spectrum Cycle'\n"+ " Zones: Keyboard\n"+ " LEDs: 'Key: Escape' 'Key: F1' 'Key: F2' 'Key: F3'\n"+ "\n"+ "1: Logitech G203\n"+ " Type: Mouse\n"+ " Modes: Off Static ['Spectrum Cycle'] Breathing\n"+ " LEDs: Logo\n"+ "\n"+ "2: Odd Lights\n"+ " Modes: Direct\n"+ " LEDs: A B C D E F G H\n"+ "\n"+ "3: Fixed Glow\n"+ " Modes: Custom\n");+}++class PlanTest : public QObject+{+ Q_OBJECT++private Q_SLOTS:+ void splitsQuotedNames()+ {+ QCOMPARE(splitNames(QStringLiteral(" Direct 'Rainbow Wave' Static")),+ QStringList({QStringLiteral("Direct"), QStringLiteral("Rainbow Wave"), QStringLiteral("Static")}));+ QCOMPARE(splitNames(QString()), QStringList());+ }++ void parsesDevices()+ {+ const QList<Device> devices = parseDevices(listing);+ QCOMPARE(devices.size(), 4);+ QCOMPARE(devices[0].index, 0);+ QCOMPARE(devices[0].name, QStringLiteral("Corsair K70 RGB PRO"));+ QCOMPARE(devices[0].modes,+ QStringList({QStringLiteral("Direct"), QStringLiteral("Static"), QStringLiteral("Breathing"), QStringLiteral("Rainbow Wave"),+ QStringLiteral("Spectrum Cycle")}));+ QCOMPARE(devices[0].leds, 4);+ QCOMPARE(devices[1].modes,+ QStringList({QStringLiteral("Off"), QStringLiteral("Static"), QStringLiteral("Spectrum Cycle"), QStringLiteral("Breathing")}));+ QCOMPARE(devices[1].leds, 1);+ QCOMPARE(devices[2].leds, 8);+ QCOMPARE(devices[3].leds, 0);+ }++ void looks_data()+ {+ QTest::addColumn<QString>("colour");+ QTest::addColumn<QString>("effect");+ QTest::addColumn<bool>("battery");+ QTest::addColumn<bool>("reduced");+ QTest::addColumn<int>("expected");+ QTest::newRow("accent steady") << "accent" << "steady" << false << false << int(Look::Colour);+ QTest::newRow("custom breathing") << "custom" << "breathing" << false << false << int(Look::Breathing);+ QTest::newRow("breathing on battery") << "accent" << "breathing" << true << false << int(Look::Colour);+ QTest::newRow("breathing reduced") << "accent" << "breathing" << false << true << int(Look::Colour);+ QTest::newRow("accent flowing") << "accent" << "flowing" << false << false << int(Look::Colour);+ QTest::newRow("rgb") << "rgb" << "flowing" << false << false << int(Look::Spectrum);+ QTest::newRow("rgb no effect") << "rgb" << "" << false << false << int(Look::Spectrum);+ QTest::newRow("rgb steady") << "rgb" << "steady" << false << false << int(Look::FrozenSpectrum);+ QTest::newRow("rgb on battery") << "rgb" << "flowing" << true << false << int(Look::FrozenSpectrum);+ }++ void looks()+ {+ QFETCH(QString, colour);+ QFETCH(QString, effect);+ QFETCH(bool, battery);+ QFETCH(bool, reduced);+ QFETCH(int, expected);+ QCOMPARE(int(look(colour, effect, battery, reduced)), expected);+ }++ void colours()+ {+ const QColor accent(0x3d, 0xff, 0x7a);+ QCOMPARE(colourFor(QStringLiteral("custom"), QStringLiteral("#ff2d95"), accent), QColor(0xff, 0x2d, 0x95));+ QCOMPARE(colourFor(QStringLiteral("custom"), QStringLiteral("pink"), accent), accent);+ QCOMPARE(colourFor(QStringLiteral("accent"), QStringLiteral("#ff2d95"), accent), accent);+ QCOMPARE(parseAccent(QStringLiteral("61,255,122")), accent);+ QCOMPARE(parseAccent(QStringLiteral("#3dff7a")), accent);+ QCOMPARE(parseAccent(QString()), QColor(0x8f, 0xb4, 0xff));+ }++ void breathingPrefersBreathingMode()+ {+ const QStringList args = arguments(parseDevices(listing), Look::Breathing, QColor(0xff, 0x2d, 0x95));+ QCOMPARE(args,+ QStringList({"--device", "0", "--mode", "Breathing", "--color", "ff2d95",+ "--device", "1", "--mode", "Breathing", "--color", "ff2d95",+ "--device", "2", "--mode", "Direct", "--color", "ff2d95"}));+ }++ void colourPrefersStatic()+ {+ const QStringList args = arguments(parseDevices(listing), Look::Colour, QColor(0x3d, 0xff, 0x7a));+ QCOMPARE(args,+ QStringList({"--device", "0", "--mode", "Static", "--color", "3dff7a",+ "--device", "1", "--mode", "Static", "--color", "3dff7a",+ "--device", "2", "--mode", "Direct", "--color", "3dff7a"}));+ }++ void spectrumUsesDeviceEffects()+ {+ const QStringList args = arguments(parseDevices(listing), Look::Spectrum, QColor());+ QCOMPARE(args.mid(0, 4), QStringList({"--device", "0", "--mode", "Rainbow Wave"}));+ QCOMPARE(args.mid(4, 4), QStringList({"--device", "1", "--mode", "Spectrum Cycle"}));+ // No rainbow mode: the spectrum laid across the LEDs.+ QCOMPARE(args.mid(8, 4), QStringList({"--device", "2", "--mode", "Direct"}));+ QCOMPARE(args.at(12), QStringLiteral("--color"));+ const QStringList colours = args.at(13).split(QLatin1Char(','));+ QCOMPARE(colours.size(), 8);+ QCOMPARE(colours.first(), QStringLiteral("ff3d6e"));+ QCOMPARE(args.size(), 14);+ }++ void frozenSpectrum()+ {+ const QStringList args = arguments(parseDevices(listing), Look::FrozenSpectrum, QColor());+ // Four LEDs: a quarter of the way along the gradient each.+ QCOMPARE(args.mid(0, 5), QStringList({"--device", "0", "--mode", "Direct", "--color"}));+ QCOMPARE(args.at(5).split(QLatin1Char(',')).size(), 4);+ // One LED and no Direct: the spectrum's middle colour.+ QCOMPARE(args.mid(6, 6), QStringList({"--device", "1", "--mode", "Static", "--color", "3dd5ff"}));+ }+};++QTEST_GUILESS_MAIN(PlanTest)++#include "plantest.moc"diff --git a/packages/wildos-lighting/tests/scripts.sh b/packages/wildos-lighting/tests/scripts.shnew file mode 100644index 0000000..765e32c--- /dev/null+++ b/packages/wildos-lighting/tests/scripts.sh@@ -0,0 +1,109 @@+#!/bin/sh+# Tests rgb-devices against a fake sysfs, /dev and OpenRGB rules file.+# scripts.sh LIBEXEC_DIR+set -eu++script=$1/rgb-devices+root=$(mktemp -d)+trap 'rm -rf "$root"' EXIT+fail=0++check() {+ if [ "$2" = "$3" ]; then+ echo "PASS: $1"+ else+ echo "FAIL: $1: expected '$2', got '$3'"+ fail=1+ fi+}++# Writes the given decimal byte values to a file.+bytes() {+ out=$1+ shift+ : >"$out"+ for b in "$@"; do+ printf "\\$(printf %03o "$b")" >>"$out"+ done+}++usb() {+ d=$root/sys/devices/pci0/usb1/$1+ mkdir -p "$d"+ echo "$2" >"$d/idVendor"+ echo "$3" >"$d/idProduct"+}++# A HID interface with one hidraw node, its descriptor from the remaining+# arguments.+hid() {+ dir=$root/sys/devices/pci0/usb1/$1/$2+ node=$3+ shift 3+ mkdir -p "$dir/hidraw/$node" "$root/sys/class/hidraw" "$root/dev"+ bytes "$dir/report_descriptor" "$@"+ ln -s ../.. "$dir/hidraw/$node/device"+ ln -s "$dir/hidraw/$node" "$root/sys/class/hidraw/$node"+ : >"$root/dev/$node"+ echo "${dir#$root/sys}/hidraw/$node"+}++keyboard="5 1 9 6 161 1 5 7 25 224 41 231 21 0 37 1 117 1 149 8 129 2 192"+vendor="6 0 255 9 1 161 1 21 0 38 255 0 117 8 149 64 9 1 129 2 9 1 145 2 192"+nkro_in_vendor="6 0 255 9 1 161 1 5 7 25 0 41 255 129 2 192"+mouse="5 1 9 2 161 1 9 1 161 0 5 9 25 1 41 3 129 2 192 192"+extended_keyboard_usage="5 12 11 6 0 1 0 161 1 192"++check "no OpenRGB: none" 0 "$(sh "$script" "$root")"++mkdir -p "$root/usr/bin" "$root/usr/lib/udev/rules.d"+printf '#!/bin/sh\n' >"$root/usr/bin/openrgb"+chmod +x "$root/usr/bin/openrgb"+cat >"$root/usr/lib/udev/rules.d/60-openrgb.rules.stock" <<'EOF'+# Corsair K70 RGB PRO+SUBSYSTEMS=="usb|hidraw", ATTRS{idVendor}=="1b1c", ATTRS{idProduct}=="1b2d", TAG+="uaccess", TAG+="Corsair_K70_RGB_PRO"+# Whole vendor+SUBSYSTEMS=="usb|hidraw", ATTRS{idVendor}=="1532", TAG+="uaccess", TAG+="Razer"+EOF++check "no devices: none" 0 "$(sh "$script" "$root")"++usb 1-1 1b1c 1b2d+kbd=$(hid 1-1 1-1:1.0/0003:1B1C:1B2D.0001 hidraw0 $keyboard)+light=$(hid 1-1 1-1:1.1/0003:1B1C:1B2D.0002 hidraw1 $vendor)+nkro=$(hid 1-1 1-1:1.2/0003:1B1C:1B2D.0003 hidraw2 $nkro_in_vendor)+usb 1-2 dead beef+other=$(hid 1-2 1-2:1.0/0003:DEAD:BEEF.0004 hidraw3 $vendor)+usb 1-3 1532 0084+razer=$(hid 1-3 1-3:1.0/0003:1532:0084.0005 hidraw4 $mouse)+extended=$(hid 1-3 1-3:1.1/0003:1532:0084.0006 hidraw5 $extended_keyboard_usage)++access() {+ if sh "$script" access "$1" "$root"; then echo granted; else echo refused; fi+}++check "keyboard interface refused" refused "$(access "$kbd")"+check "lighting interface granted" granted "$(access "$light")"+check "keys on a vendor page refused" refused "$(access "$nkro")"+check "keyboard usage with its page in the usage refused" refused "$(access "$extended")"+check "device OpenRGB does not list refused" refused "$(access "$other")"+check "listed vendor, mouse interface granted" granted "$(access "$razer")"+check "path outside hidraw refused" refused "$(access /devices/pci0/usb1/1-1)"+check "path climbing out refused" refused "$(access "/devices/../../etc/hidraw/hidraw0")"++# Two listed devices, the Corsair through three nodes; the unlisted one is+# not counted.+check "counts listed devices once" 2 "$(sh "$script" "$root")"++# Root can open every node, so the permission case is only testable as a+# normal user.+if [ "$(id -u)" != 0 ]; then+ chmod 000 "$root"/dev/hidraw4 "$root"/dev/hidraw5+ check "devices this user cannot open are not counted" 1 "$(sh "$script" "$root")"+fi++rm "$root/usr/bin/openrgb"+check "OpenRGB removed: none" 0 "$(sh "$script" "$root")"+check "OpenRGB removed: refused" refused "$(access "$light")"++exit $faildiff --git a/packages/wildos-mail/CMakeLists.txt b/packages/wildos-mail/CMakeLists.txtnew file mode 100644index 0000000..4613150--- /dev/null+++ b/packages/wildos-mail/CMakeLists.txt@@ -0,0 +1,67 @@+cmake_minimum_required(VERSION 3.25)+project(wildos-mail VERSION 0.1.0 LANGUAGES CXX)++set(CMAKE_CXX_STANDARD 20)+set(CMAKE_CXX_STANDARD_REQUIRED ON)+include(GNUInstallDirs)++find_package(Qt6 6.8 REQUIRED COMPONENTS Core Gui DBus Network Qml Quick QuickControls2)+find_package(Qt6Keychain REQUIRED)+find_package(litehtml REQUIRED)+find_package(PkgConfig REQUIRED)+pkg_check_modules(CAMEL REQUIRED IMPORTED_TARGET camel-1.2)+pkg_check_modules(EDS REQUIRED IMPORTED_TARGET libedataserver-1.2)+pkg_check_modules(ECAL REQUIRED IMPORTED_TARGET libecal-2.0)++qt_standard_project_setup(REQUIRES 6.8)++qt_add_executable(wildos-mail src/main.cpp)+target_compile_definitions(wildos-mail PRIVATE WILDOS_MAIL_VERSION="${PROJECT_VERSION}" QT_NO_KEYWORDS)++file(GLOB QML_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} qml/*.qml qml/*.js)+set_source_files_properties(qml/MailIcons.qml PROPERTIES QT_QML_SINGLETON_TYPE TRUE)+foreach(file ${QML_SOURCES})+ get_filename_component(name ${file} NAME)+ set_source_files_properties(${file} PROPERTIES QT_RESOURCE_ALIAS ${name})+endforeach()++qt_add_qml_module(wildos-mail+ URI WildOS.Mail+ QML_FILES ${QML_SOURCES}+ RESOURCES data/litehtml-master.css data/caught-up.svg+ SOURCES+ src/camelsession.cpp src/camelsession.h+ src/accounts.cpp src/accounts.h+ src/models.cpp src/models.h+ src/mailengine.cpp src/mailengine.h+ src/messageview.cpp src/messageview.h+ src/htmlview.cpp src/htmlview.h+ src/composer.cpp src/composer.h+ src/autoconfig.cpp src/autoconfig.h+ src/notifier.cpp src/notifier.h+ src/formatter.cpp src/formatter.h+ src/googlesignin.cpp src/googlesignin.h+ src/calendarengine.cpp src/calendarengine.h+ src/reminders.cpp src/reminders.h+ src/apps.h+ src/formats.h+)++target_include_directories(wildos-mail PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)++target_link_libraries(wildos-mail PRIVATE+ Qt6::Gui Qt6::DBus Qt6::Network Qt6::Qml Qt6::Quick Qt6::QuickControls2+ qt6keychain+ litehtml+ PkgConfig::CAMEL+ PkgConfig::EDS+ PkgConfig::ECAL+)++install(TARGETS wildos-mail RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})+# Calendar is the same program started by another name (main.cpp).+install(CODE "execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink wildos-mail \$ENV{DESTDIR}${CMAKE_INSTALL_FULL_BINDIR}/wildos-calendar)")++install(FILES data/org.wildos.mail.desktop data/org.wildos.calendar.desktop DESTINATION ${CMAKE_INSTALL_DATADIR}/applications)+install(FILES data/org.wildos.mail.svg data/org.wildos.calendar.svg DESTINATION ${CMAKE_INSTALL_DATADIR}/icons/hicolor/scalable/apps)+install(FILES data/org.wildos.calendar-reminders.desktop DESTINATION ${CMAKE_INSTALL_SYSCONFDIR}/xdg/autostart)diff --git a/packages/wildos-mail/data/caught-up.svg b/packages/wildos-mail/data/caught-up.svgnew file mode 100644index 0000000..31c732a--- /dev/null+++ b/packages/wildos-mail/data/caught-up.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" width="120" height="96" viewBox="0 0 120 96"><rect x="14" y="30" width="92" height="56" rx="10" fill="rgba(143,180,255,0.10)" stroke="rgba(143,180,255,0.45)" stroke-width="1.5"/><path d="M14 58h26l6 10h28l6-10h26" fill="none" stroke="rgba(143,180,255,0.45)" stroke-width="1.5"/><circle cx="60" cy="24" r="16" fill="#5fd38d"/><path d="M52 24l6 6 10-11" fill="none" stroke="#0d1530" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/></svg>diff --git a/packages/wildos-mail/data/litehtml-master.css b/packages/wildos-mail/data/litehtml-master.cssnew file mode 100644index 0000000..39febea--- /dev/null+++ b/packages/wildos-mail/data/litehtml-master.css@@ -0,0 +1,327 @@+html {+ display: block;+ height:100%;+ width:100%;+ position: relative;+}++head {+ display: none+}++meta {+ display: none+}++title {+ display: none+}++link {+ display: none+}++style {+ display: none+}++script {+ display: none+}++body {+ display:block;+ margin:8px;+ height:100%;+ width:100%;+}++p {+ display:block;+ margin-top:1em;+ margin-bottom:1em;+}++b, strong {+ display:inline;+ font-weight:bold;+}++i, em {+ display:inline;+ font-style:italic;+}++center+{+ text-align:center;+ display:block;+}++a:link+{+ text-decoration: underline;+ color: #00f;+ cursor: pointer;+}++h1, h2, h3, h4, h5, h6, div {+ display:block;+}++h1 {+ font-weight:bold;+ margin-top:0.67em;+ margin-bottom:0.67em;+ font-size: 2em;+}++h2 {+ font-weight:bold;+ margin-top:0.83em;+ margin-bottom:0.83em;+ font-size: 1.5em;+}++h3 {+ font-weight:bold;+ margin-top:1em;+ margin-bottom:1em;+ font-size:1.17em;+}++h4 {+ font-weight:bold;+ margin-top:1.33em;+ margin-bottom:1.33em+}++h5 {+ font-weight:bold;+ margin-top:1.67em;+ margin-bottom:1.67em;+ font-size:.83em;+}++h6 {+ font-weight:bold;+ margin-top:2.33em;+ margin-bottom:2.33em;+ font-size:.67em;+}++br {+ display:inline-block;+}++br[clear="all"]+{+ clear:both;+}++br[clear="left"]+{+ clear:left;+}++br[clear="right"]+{+ clear:right;+}++span {+ display:inline+}++img {+ display: inline-block;+}++img[align="right"]+{+ float: right;+}++img[align="left"]+{+ float: left;+}++hr {+ display: block;+ margin-top: 0.5em;+ margin-bottom: 0.5em;+ margin-left: auto;+ margin-right: auto;+ border-style: inset;+ border-width: 1px+}+++/***************** TABLES ********************/++table {+ display: table;+ border-collapse: separate;+ border-spacing: 2px;+ border-top-color:gray;+ border-left-color:gray;+ border-bottom-color:black;+ border-right-color:black;+}++tbody, tfoot, thead {+ display:table-row-group;+ vertical-align:middle;+}++tr {+ display: table-row;+ vertical-align: inherit;+ border-color: inherit;+}++td, th {+ display: table-cell;+ vertical-align: inherit;+ border-width:1px;+ padding:1px;+}++th {+ font-weight: bold;+}++table[border] {+ border-style:solid;+}++table[border|=0] {+ border-style:none;+}++table[border] td, table[border] th {+ border-style:solid;+ border-top-color:black;+ border-left-color:black;+ border-bottom-color:gray;+ border-right-color:gray;+}++table[border|=0] td, table[border|=0] th {+ border-style:none;+}++caption {+ display: table-caption;+}++td[nowrap], th[nowrap] {+ white-space:nowrap;+}++tt, code, kbd, samp {+ font-family: monospace+}++pre, xmp, plaintext, listing {+ display: block;+ font-family: monospace;+ white-space: pre;+ margin: 1em 0+}++/***************** LISTS ********************/++ul, menu, dir {+ display: block;+ list-style-type: disc;+ margin-top: 1em;+ margin-bottom: 1em;+ margin-left: 0;+ margin-right: 0;+ padding-left: 40px+}++ol {+ display: block;+ list-style-type: decimal;+ margin-top: 1em;+ margin-bottom: 1em;+ margin-left: 0;+ margin-right: 0;+ padding-left: 40px+}++li {+ display: list-item;+}++ul ul, ol ul {+ list-style-type: circle;+}++ol ol ul, ol ul ul, ul ol ul, ul ul ul {+ list-style-type: square;+}++dd {+ display: block;+ margin-left: 40px;+}++dl {+ display: block;+ margin-top: 1em;+ margin-bottom: 1em;+ margin-left: 0;+ margin-right: 0;+}++dt {+ display: block;+}++ol ul, ul ol, ul ul, ol ol {+ margin-top: 0;+ margin-bottom: 0+}++blockquote {+ display: block;+ margin-top: 1em;+ margin-bottom: 1em;+ margin-left: 40px;+ margin-right: 40px;+}++/*********** FORM ELEMENTS ************/++form {+ display: block;+ margin-top: 0em;+}++option {+ display: none;+}++input, textarea, keygen, select, button, isindex {+ margin: 0em;+ color: initial;+ line-height: normal;+ text-transform: none;+ text-indent: 0;+ text-shadow: none;+ display: inline-block;+}+input[type="hidden"] {+ display: none;+}+++article, aside, footer, header, hgroup, nav, section+{+ display: block;+}+diff --git a/packages/wildos-mail/data/org.wildos.calendar-reminders.desktop b/packages/wildos-mail/data/org.wildos.calendar-reminders.desktopnew file mode 100644index 0000000..e211734--- /dev/null+++ b/packages/wildos-mail/data/org.wildos.calendar-reminders.desktop@@ -0,0 +1,10 @@+[Desktop Entry]+Type=Application+Name=Calendar reminders+Comment=Shows reminders for your events+Exec=wildos-calendar --reminders+Icon=org.wildos.calendar+Terminal=false+NoDisplay=true+X-KDE-autostart-phase=2+X-GNOME-Autostart-Delay=5diff --git a/packages/wildos-mail/data/org.wildos.calendar.desktop b/packages/wildos-mail/data/org.wildos.calendar.desktopnew file mode 100644index 0000000..28e7ecd--- /dev/null+++ b/packages/wildos-mail/data/org.wildos.calendar.desktop@@ -0,0 +1,11 @@+[Desktop Entry]+Type=Application+Name=Calendar+GenericName=Calendar+Comment=Your events, with Google, iCloud and CalDAV calendars+Exec=wildos-calendar+Icon=org.wildos.calendar+Terminal=false+StartupNotify=true+Categories=Qt;Office;Calendar;+Keywords=calendar;events;meetings;reminders;diary;agenda;schedule;diff --git a/packages/wildos-mail/data/org.wildos.calendar.svg b/packages/wildos-mail/data/org.wildos.calendar.svgnew file mode 100644index 0000000..42ba945--- /dev/null+++ b/packages/wildos-mail/data/org.wildos.calendar.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256"><defs><filter id="i3cs" x="-25%" y="-25%" width="150%" height="150%"><feDropShadow dx="0" dy="7" stdDeviation="8" flood-color="#060c2a" flood-opacity="0.35"/></filter><linearGradient id="i3ct" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#ff8a6e"/><stop offset="1" stop-color="#d9362b"/></linearGradient><linearGradient id="i3cg" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#fff" stop-opacity="0.22"/><stop offset="0.55" stop-color="#fff" stop-opacity="0"/></linearGradient><linearGradient id="i3cp" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#ffffff"/><stop offset="1" stop-color="#ffe6e1"/></linearGradient></defs><g filter="url(#i3cs)"><rect x="80" y="30" width="156" height="196" rx="24" fill="url(#i3cp)"/><path d="M80 54a24 24 0 0 1 24-24h108a24 24 0 0 1 24 24v18H80z" fill="#f2a196"/></g><g fill="#f5cfc8"><rect x="150" y="92" width="18" height="18" rx="5"/><rect x="178" y="92" width="18" height="18" rx="5"/><rect x="206" y="92" width="18" height="18" rx="5"/><rect x="150" y="120" width="18" height="18" rx="5"/><rect x="178" y="120" width="18" height="18" rx="5" fill="#e8564a"/><rect x="206" y="120" width="18" height="18" rx="5"/><rect x="150" y="148" width="18" height="18" rx="5"/><rect x="178" y="148" width="18" height="18" rx="5"/><rect x="206" y="148" width="18" height="18" rx="5"/><rect x="150" y="176" width="18" height="18" rx="5"/><rect x="178" y="176" width="18" height="18" rx="5"/></g><g filter="url(#i3cs)"><rect x="14" y="70" width="124" height="124" rx="30" fill="url(#i3ct)"/><rect x="14" y="70" width="124" height="124" rx="30" fill="url(#i3cg)"/><rect x="15.5" y="71.5" width="121" height="121" rx="28" fill="none" stroke="#fff" stroke-opacity="0.18" stroke-width="2"/><rect x="42" y="104" width="68" height="62" rx="10" fill="none" stroke="#ffffff" stroke-width="7"/><path d="M42 124h68" stroke="#ffffff" stroke-width="7"/><path d="M60 94v18M92 94v18" stroke="#ffffff" stroke-width="7" stroke-linecap="round"/><rect x="56" y="134" width="14" height="14" rx="3.5" fill="#ffffff"/></g></svg>diff --git a/packages/wildos-mail/data/org.wildos.mail.desktop b/packages/wildos-mail/data/org.wildos.mail.desktopnew file mode 100644index 0000000..cf0292c--- /dev/null+++ b/packages/wildos-mail/data/org.wildos.mail.desktop@@ -0,0 +1,13 @@+[Desktop Entry]+Type=Application+Name=Mail+GenericName=Email+Comment=Read and write email, with trackers blocked+Exec=wildos-mail %u+Icon=org.wildos.mail+Terminal=false+StartupNotify=true+StartupWMClass=wildos-mail+Categories=Qt;Network;Email;+MimeType=x-scheme-handler/mailto;x-scheme-handler/com.googleusercontent.apps.590402290962-2i0b7rqma8b9nmtfrcp7fa06g6cf7g74;+Keywords=email;mail;inbox;imap;smtp;gmail;outlook;diff --git a/packages/wildos-mail/data/org.wildos.mail.svg b/packages/wildos-mail/data/org.wildos.mail.svgnew file mode 100644index 0000000..dbf2b8a--- /dev/null+++ b/packages/wildos-mail/data/org.wildos.mail.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256"><defs><filter id="i1ms" x="-25%" y="-25%" width="150%" height="150%"><feDropShadow dx="0" dy="7" stdDeviation="8" flood-color="#060c2a" flood-opacity="0.35"/></filter><linearGradient id="i1mt" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#3fb6ff"/><stop offset="1" stop-color="#0a63d1"/></linearGradient><linearGradient id="i1mg" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#fff" stop-opacity="0.22"/><stop offset="0.55" stop-color="#fff" stop-opacity="0"/></linearGradient><linearGradient id="i1me" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#c4e8ff"/><stop offset="1" stop-color="#7cc0f5"/></linearGradient><linearGradient id="i1mf" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#effaff"/><stop offset="1" stop-color="#a9dafc"/></linearGradient></defs><g filter="url(#i1ms)"><rect x="70" y="56" width="170" height="130" rx="22" fill="url(#i1me)"/><path d="M70 74 L155 132 L240 74 V164 a22 22 0 0 1 -22 22 H92 a22 22 0 0 1 -22 -22Z" fill="url(#i1mf)"/></g><g filter="url(#i1ms)"><rect x="14" y="70" width="124" height="124" rx="30" fill="url(#i1mt)"/><rect x="14" y="70" width="124" height="124" rx="30" fill="url(#i1mg)"/><rect x="15.5" y="71.5" width="121" height="121" rx="28" fill="none" stroke="#fff" stroke-opacity="0.18" stroke-width="2"/><path d="M76.8 169.0C84.8 169.0 92.3 167.0 96.2 165.2L93.1 157.1C89.9 158.4 84.1 160.1 77.7 160.1C59.1 160.1 49.1 150.2 49.1 132.1C49.1 114.4 58.9 103.8 77.2 103.8C94.6 103.8 103.3 113.9 103.3 129.1C103.3 139.2 101.6 143.7 96.7 143.7C94.3 143.7 93.2 142.2 93.2 139.7V113.5H85.3V117.5H84.8C83.3 114.6 79.5 112.6 74.4 112.6C64.4 112.6 57.5 120.5 57.5 132.0C57.5 143.5 63.6 151.4 74.2 151.4C80.3 151.4 84.5 148.7 85.9 144.9H86.2C87.0 149.4 91.6 151.3 96.7 151.3C108.2 151.3 112.7 141.2 112.7 128.3C112.7 109.3 99.0 95.0 76.5 95.0C52.5 95.0 39.3 110.1 39.3 132.4C39.3 155.7 53.0 169.0 76.8 169.0ZM75.3 143.1C69.0 143.1 66.1 138.3 66.1 131.8C66.1 125.7 69.5 121.4 75.4 121.4C81.5 121.4 84.8 124.4 84.8 131.8C84.8 139.2 81.7 143.1 75.3 143.1Z" fill="#ffffff"/></g></svg>diff --git a/packages/wildos-mail/debian/changelog b/packages/wildos-mail/debian/changelognew file mode 100644index 0000000..a4dafca--- /dev/null+++ b/packages/wildos-mail/debian/changelog@@ -0,0 +1,40 @@+wildos-mail (0.2.1) trixie; urgency=medium++ * Calendar is a tab of Mail's window; Open in new window on the rail.+ * Gmail accounts bring their calendar.++ -- Wild OS Developers <[email protected]> Mon, 09 Nov 2026 23:10:00 +0000++wildos-mail (0.2.0) trixie; urgency=medium++ * Calendar (wildos-calendar), on evolution-data-server's calendar service:+ day, work week, week and month, events with people, repeats, reminders+ and notes, Google, iCloud, CalDAV and web calendars, and reminders shown+ as notifications from sign-in.+ * Mail answers invitations: Accept, Maybe and Decline, with the day the+ event is on beside them.+ * Mail and Calendar share the app rail.++ -- Wild OS Developers <[email protected]> Mon, 09 Nov 2026 22:20:00 +0000++wildos-mail (0.1.2) trixie; urgency=medium++ * Camel's IMAP and SMTP modules come from evolution-data-server-camel-providers,+ split out of Wild OS's rebuild of evolution-data-server, instead of copies+ carried by Mail, so they get Debian's fixes.++ -- Wild OS Developers <[email protected]> Mon, 09 Nov 2026 21:10:00 +0000++wildos-mail (0.1.1) trixie; urgency=medium++ * Carry Camel's IMAP and SMTP modules, copied at build time from+ evolution-data-server, which Wild OS doesn't install. Temporary until a+ split evolution-data-server-camel-providers package exists.++ -- Wild OS Developers <[email protected]> Mon, 09 Nov 2026 20:40:00 +0000++wildos-mail (0.1.0) trixie; urgency=medium++ * Initial release.++ -- Wild OS Developers <[email protected]> Mon, 09 Nov 2026 18:00:00 +0000diff --git a/packages/wildos-mail/debian/control b/packages/wildos-mail/debian/controlnew file mode 100644index 0000000..769b921--- /dev/null+++ b/packages/wildos-mail/debian/control@@ -0,0 +1,44 @@+Source: wildos-mail+Section: mail+Priority: optional+Maintainer: Wild OS Developers <[email protected]>+Build-Depends:+ debhelper-compat (= 13),+ cmake,+ pkg-config,+ qt6-base-dev,+ qt6-declarative-dev,+ qtkeychain-qt6-dev,+ libcamel1.2-dev,+ libedataserver1.2-dev,+ libecal2.0-dev,+ liblitehtml-dev,+Standards-Version: 4.7.0+Rules-Requires-Root: no++Package: wildos-mail+Architecture: any+Depends:+ ${shlibs:Depends},+ ${misc:Depends},+ evolution-data-server-camel-providers,+ evolution-data-server-core,+ wildos-ui,+ evolution-data-server-common,+ qml6-module-qtcore,+ qml6-module-qtquick,+ qml6-module-qtquick-controls,+ qml6-module-qtquick-layouts,+ qml6-module-qtquick-shapes,+ qml6-module-qtquick-dialogs,+ qml6-module-qtqml-workerscript,+ fonts-noto-core,+Description: Wild OS Mail+ Email for Wild OS on evolution-data-server's mail engine: IMAP and SMTP+ accounts kept on the PC for offline reading, messages drawn without+ scripts and with web pictures blocked until asked for, trackers blocked+ even then, and photo locations removed from attachments.+ .+ Also Wild OS Calendar, on evolution-data-server's calendar service: day,+ week and month views, Google, iCloud, CalDAV and web calendars,+ invitations answered from Mail, and reminders as notifications.diff --git a/packages/wildos-mail/debian/rules b/packages/wildos-mail/debian/rulesnew file mode 100644index 0000000..2c5acaf--- /dev/null+++ b/packages/wildos-mail/debian/rules@@ -0,0 +1,7 @@+#!/usr/bin/make -f++%:+ dh $@++override_dh_auto_configure:+ dh_auto_configure -- -Wno-dev -DCMAKE_BUILD_TYPE=Releasediff --git a/packages/wildos-mail/debian/source/format b/packages/wildos-mail/debian/source/formatnew file mode 100644index 0000000..89ae9db--- /dev/null+++ b/packages/wildos-mail/debian/source/format@@ -0,0 +1 @@+3.0 (native)diff --git a/packages/wildos-mail/qml/AddAccount.qml b/packages/wildos-mail/qml/AddAccount.qmlnew file mode 100644index 0000000..272a885--- /dev/null+++ b/packages/wildos-mail/qml/AddAccount.qml@@ -0,0 +1,706 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Mail+import WildOS.UI as UI++// Adding an account (MailMsAccount.dc, MailMsSetupManual.dc,+// MailMsSetupSync.dc, MailMsSetupDone.dc): the address, then a password+// (an app password for Gmail, iCloud, Yahoo and Fastmail), or the server+// settings for anything Mail can't find by itself, then the name people+// see. Shown over the window.+Item {+ id: dialog++ // email, password, manual, details, done+ property string step: "email"+ property var settings: ({})+ property bool testing: false+ property string error+ property bool guessed: false++ // The password, app password or (for Sign in with Google) refresh token+ // that passed the test, kept for saving.+ property string secret++ signal finished()++ function open() {+ step = "email";+ settings = {};+ error = "";+ email.text = "";+ password.text = "";+ visible = true;+ email.forceActiveFocus();+ }+ function close() {+ GoogleSignIn.cancel();+ visible = false;+ finished();+ }+ function choose(provider) {+ error = "";+ if (provider === "other") {+ settings = Object.assign({ provider: "other", email: email.text.trim(), user: email.text.trim() }, settings.imapHost ? settings : {});+ fillManual();+ step = "manual";+ return;+ }+ settings = autoConfig.preset(provider, email.text.trim());+ if (provider === "gmail") {+ startGoogle();+ return;+ }+ step = "password";+ password.forceActiveFocus();+ }+ // Gmail and Google Workspace: Google's own sign-in page in the browser.+ function startGoogle() {+ settings = Object.assign({}, autoConfig.preset("gmail", email.text.trim()), { auth: "google" });+ step = "google";+ GoogleSignIn.start(email.text.trim());+ }+ function useAppPassword() {+ GoogleSignIn.cancel();+ settings = Object.assign({}, settings, { auth: "password" });+ step = "password";+ password.forceActiveFocus();+ }+ function fillManual() {+ imapHost.text = settings.imapHost || "";+ imapPort.text = settings.imapPort || 993;+ imapSecurity.currentIndex = ["ssl", "starttls", "none"].indexOf(settings.imapSecurity || "ssl");+ smtpHost.text = settings.smtpHost || "";+ smtpPort.text = settings.smtpPort || 465;+ smtpSecurity.currentIndex = ["ssl", "starttls", "none"].indexOf(settings.smtpSecurity || "ssl");+ user.text = settings.user || email.text.trim();+ }+ function test(pw) {+ error = "";+ secret = pw;+ testing = true;+ MailEngine.testAccount(settings, pw);+ }+ readonly property var appPasswordHelp: ({+ gmail: { name: "Gmail", url: "https://myaccount.google.com/apppasswords", how: qsTr("Gmail needs an app password: a separate password just for Mail, which you can take back any time. Turn on 2-Step Verification in your Google account first, then create one.") },+ icloud: { name: "iCloud Mail", url: "https://account.apple.com", how: qsTr("iCloud needs an app-specific password. In your Apple Account, open Sign-In and Security, then App-Specific Passwords.") },+ yahoo: { name: "Yahoo Mail", url: "https://login.yahoo.com/myaccount/security/app-password", how: qsTr("Yahoo needs an app password, made in your Yahoo account's security settings.") },+ fastmail: { name: "Fastmail", url: "https://app.fastmail.com/settings/security/apps", how: qsTr("Fastmail needs an app password. In Fastmail, open Settings, Privacy and security, then Manage app passwords, and give it access to mail.") },+ aol: { name: "AOL Mail", url: "https://login.aol.com/account/security", how: qsTr("AOL needs an app password, made in your AOL account's security settings.") },+ other: { name: "", url: "", how: "" }+ })++ visible: false+ anchors.fill: parent+ z: 50++ Connections {+ target: MailEngine+ function onAccountTested(ok, message) {+ if (!dialog.visible) {+ return;+ }+ dialog.testing = false;+ if (ok) {+ fullName.text = dialog.settings.fullName || MailEngine.systemFullName();+ accountName.text = MailEngine.accounts.length === 0 ? qsTr("Personal") : dialog.settings.email;+ dialog.step = "details";+ } else {+ dialog.error = message;+ }+ }+ }++ Connections {+ target: GoogleSignIn+ function onSignedIn(address, refreshToken) {+ if (dialog.visible && dialog.step === "google") {+ dialog.test(refreshToken);+ }+ }+ function onFailed(message) {+ if (dialog.visible && dialog.step === "google") {+ dialog.error = message;+ }+ }+ }++ AutoConfig {+ id: autoConfig+ onFound: function (found, wasGuessed) {+ dialog.guessed = wasGuessed;+ if (found.provider === "outlook") {+ dialog.error = qsTr("Outlook and Microsoft 365 accounts need Microsoft's own sign-in, which is coming in an update.");+ return;+ }+ dialog.settings = found;+ if (found.provider === "gmail") {+ dialog.startGoogle();+ return;+ }+ if (found.provider !== "other" || !wasGuessed) {+ if (found.provider === "other") {+ dialog.settings.provider = "other";+ }+ dialog.step = "password";+ password.forceActiveFocus();+ } else {+ dialog.fillManual();+ dialog.step = "manual";+ }+ }+ }++ Rectangle {+ anchors.fill: parent+ color: UI.Style.scrim+ MouseArea {+ anchors.fill: parent+ }+ }++ Rectangle {+ id: card+ anchors.centerIn: parent+ width: Math.min(600, parent.width - 48)+ // Always the size of what is in it: every step is laid out to fit+ // Mail's smallest window, so nothing here ever scrolls.+ height: content.implicitHeight + 48+ radius: UI.Style.radiusDialog+ // Solid: the compositor's blur can't reach what is inside this same+ // window, so glass would show the mail underneath.+ color: UI.Style.windowOpaque+ border.width: 1+ border.color: UI.Style.borderDialog++ Item {+ anchors.fill: parent+ anchors.margins: 24++ ColumnLayout {+ id: content+ width: card.width - 48+ spacing: 12++ UI.Label {+ visible: text.length > 0+ text: dialog.step === "email" || dialog.step === "done" ? "" : dialog.step === "details" ? qsTr("Step 3 of 3") : qsTr("Step 2 of 3")+ size: 12+ color: UI.Style.inkMuted+ }+ UI.Label {+ Layout.fillWidth: true+ text: dialog.step === "email" ? qsTr("Add an account")+ : dialog.step === "google" ? qsTr("Sign in with Google")+ : dialog.step === "password" ? (dialog.appPasswordHelp[dialog.settings.provider] || dialog.appPasswordHelp.other).name || qsTr("Sign in")+ : dialog.step === "manual" ? qsTr("Other account")+ : dialog.step === "details" ? qsTr("You're signed in")+ : qsTr("You're all set")+ size: 22+ font.weight: Font.DemiBold+ wrapMode: Text.WordWrap+ }++ // Step 1: the address, or a provider.+ ColumnLayout {+ visible: dialog.step === "email"+ Layout.fillWidth: true+ spacing: 12++ UI.Label {+ Layout.fillWidth: true+ text: qsTr("Your mail, and for Gmail your calendar too.")+ size: 13+ color: UI.Style.inkMuted+ wrapMode: Text.WordWrap+ }+ UI.Label {+ text: qsTr("Email address")+ size: 13+ font.weight: Font.Medium+ }+ UI.TextField {+ id: email+ Layout.fillWidth: true+ placeholderText: "[email protected]"+ inputMethodHints: Qt.ImhEmailCharactersOnly | Qt.ImhNoAutoUppercase+ onAccepted: if (continueButton.enabled) continueButton.clicked()+ }+ UI.Label {+ Layout.fillWidth: true+ text: qsTr("We'll find the right settings for you. No server names needed.")+ size: 12+ color: UI.Style.inkMuted+ wrapMode: Text.WordWrap+ }+ UI.Label {+ Layout.topMargin: 6+ text: qsTr("or choose your provider")+ size: 12+ color: UI.Style.inkMuted+ }++ GridLayout {+ Layout.fillWidth: true+ columns: 2+ columnSpacing: 8+ rowSpacing: 8++ Repeater {+ model: [+ { id: "gmail", name: "Gmail", note: qsTr("Sign in with Google") },+ { id: "outlook", name: qsTr("Outlook and Microsoft 365"), note: qsTr("Coming in an update") },+ { id: "icloud", name: qsTr("iCloud Mail"), note: qsTr("Uses an app-specific password") },+ { id: "yahoo", name: qsTr("Yahoo Mail"), note: qsTr("Uses an app password") },+ { id: "fastmail", name: "Fastmail", note: qsTr("Uses an app password") },+ { id: "other", name: qsTr("Other account"), note: qsTr("Any IMAP and SMTP mail") }+ ]++ // A compact tile per provider, two to a row, so the+ // first step fits without scrolling.+ delegate: Rectangle {+ id: tile+ required property var modelData+ readonly property bool available: modelData.id !== "outlook"+ Layout.fillWidth: true+ Layout.preferredWidth: 1+ implicitHeight: 54+ radius: 8+ color: tileMouse.containsMouse && available ? UI.Style.surfaceHover : UI.Style.surfaceRaised+ border.width: 1+ border.color: UI.Style.borderSubtle+ opacity: available ? 1 : 0.55++ MouseArea {+ id: tileMouse+ anchors.fill: parent+ hoverEnabled: true+ enabled: tile.available+ cursorShape: Qt.PointingHandCursor+ onClicked: {+ if (email.text.trim().indexOf("@") < 1) {+ dialog.error = qsTr("Type your email address first.");+ email.forceActiveFocus();+ return;+ }+ dialog.choose(tile.modelData.id);+ }+ }+ ColumnLayout {+ anchors.fill: parent+ anchors.leftMargin: 14+ anchors.rightMargin: 10+ anchors.topMargin: 8+ anchors.bottomMargin: 8+ spacing: 1+ UI.Label {+ Layout.fillWidth: true+ text: tile.modelData.name+ size: 13+ font.weight: Font.DemiBold+ elide: Text.ElideRight+ }+ UI.Label {+ Layout.fillWidth: true+ text: tile.modelData.note+ size: 11.5+ color: UI.Style.inkMuted+ elide: Text.ElideRight+ }+ }+ }+ }+ }+ }++ // Step 2 for Gmail: Google's page in the browser+ // (MailMsSetupSignin.dc).+ ColumnLayout {+ visible: dialog.step === "google"+ Layout.fillWidth: true+ spacing: 12++ UI.Label {+ Layout.fillWidth: true+ text: qsTr("We've opened Google's sign-in page in your browser. Sign in there and allow access to your mail and calendar, then come back here.")+ size: 13+ wrapMode: Text.WordWrap+ }+ Rectangle {+ Layout.fillWidth: true+ implicitHeight: 64+ radius: 8+ color: UI.Style.surfaceRaised+ border.width: 1+ border.color: UI.Style.borderSubtle++ RowLayout {+ anchors.fill: parent+ anchors.leftMargin: 14+ anchors.rightMargin: 14+ spacing: 12+ SenderBadge {+ size: 32+ initials: MailEngine.initialsOf(email.text.trim())+ colourIndex: MailEngine.colourOf(email.text.trim())+ }+ ColumnLayout {+ Layout.fillWidth: true+ spacing: 1+ UI.Label {+ Layout.fillWidth: true+ text: email.text.trim()+ size: 13+ font.weight: Font.DemiBold+ elide: Text.ElideRight+ }+ UI.Label {+ text: dialog.testing ? qsTr("Checking your mail") : qsTr("Waiting for you to sign in")+ size: 12+ color: UI.Style.inkMuted+ }+ }+ UI.Spinner {+ size: 20+ }+ }+ }+ UI.Label {+ Layout.fillWidth: true+ text: qsTr("Google's page names Evolution: that's the mail engine Wild OS Mail is built on. Mail asks for your mail and your calendar, and you can take its access back in your Google account.")+ size: 12+ color: UI.Style.inkMuted+ wrapMode: Text.WordWrap+ }+ RowLayout {+ spacing: 18+ UI.LinkButton {+ text: qsTr("Open the page again")+ onClicked: GoogleSignIn.reopen()+ }+ UI.LinkButton {+ text: qsTr("Use an app password instead")+ onClicked: dialog.useAppPassword()+ }+ }+ }++ // Step 2: the password.+ ColumnLayout {+ visible: dialog.step === "password"+ Layout.fillWidth: true+ spacing: 12++ UI.Label {+ Layout.fillWidth: true+ text: email.text.trim()+ size: 13+ color: UI.Style.inkMuted+ }+ UI.Label {+ Layout.fillWidth: true+ visible: text.length > 0+ text: (dialog.appPasswordHelp[dialog.settings.provider] || dialog.appPasswordHelp.other).how+ size: 13+ wrapMode: Text.WordWrap+ }+ UI.LinkButton {+ visible: ((dialog.appPasswordHelp[dialog.settings.provider] || dialog.appPasswordHelp.other).url || "").length > 0+ text: qsTr("Open the page to make one")+ onClicked: Qt.openUrlExternally(dialog.appPasswordHelp[dialog.settings.provider].url)+ }+ UI.Label {+ text: dialog.settings.provider === "other" ? qsTr("Password") : qsTr("App password")+ size: 13+ font.weight: Font.Medium+ }+ UI.TextField {+ id: password+ Layout.fillWidth: true+ revealable: true+ onAccepted: if (password.text.length > 0) dialog.test(password.text)+ }+ RowLayout {+ spacing: 8+ MailIcon {+ name: "lock"+ size: 14+ color: UI.Style.success+ }+ UI.Label {+ Layout.fillWidth: true+ text: MailEngine.passwordInWallet ? qsTr("Kept in this PC's password store, KWallet, not in Mail's own files.") : qsTr("Kept in a file only your account on this PC can read.")+ size: 12+ color: UI.Style.inkMuted+ wrapMode: Text.WordWrap+ }+ }+ UI.LinkButton {+ visible: dialog.settings.provider === "other"+ text: qsTr("Change server settings")+ onClicked: {+ dialog.fillManual();+ dialog.step = "manual";+ }+ }+ }++ // Step 2 for anything else: the servers.+ GridLayout {+ visible: dialog.step === "manual"+ Layout.fillWidth: true+ columns: 3+ columnSpacing: 10+ rowSpacing: 8++ UI.Label {+ Layout.columnSpan: 3+ Layout.fillWidth: true+ text: dialog.guessed ? qsTr("We couldn't find settings for this address, so these are a guess. Check them against what your email provider gives.") : qsTr("Enter the settings from your email provider. We fill in what we can find.")+ size: 13+ color: UI.Style.inkMuted+ wrapMode: Text.WordWrap+ }+ UI.Label {+ Layout.columnSpan: 3+ Layout.topMargin: 6+ text: qsTr("Incoming mail (IMAP)")+ size: 13+ font.weight: Font.DemiBold+ }+ UI.TextField {+ id: imapHost+ Layout.fillWidth: true+ placeholderText: qsTr("Server")+ }+ UI.TextField {+ id: imapPort+ Layout.preferredWidth: 80+ placeholderText: qsTr("Port")+ validator: IntValidator { bottom: 1; top: 65535 }+ }+ UI.ComboBox {+ id: imapSecurity+ Layout.preferredWidth: 130+ model: [{ value: "ssl", text: "SSL/TLS" }, { value: "starttls", text: "STARTTLS" }, { value: "none", text: qsTr("None") }]+ }+ UI.Label {+ Layout.columnSpan: 3+ Layout.topMargin: 6+ text: qsTr("Outgoing mail (SMTP)")+ size: 13+ font.weight: Font.DemiBold+ }+ UI.TextField {+ id: smtpHost+ Layout.fillWidth: true+ placeholderText: qsTr("Server")+ }+ UI.TextField {+ id: smtpPort+ Layout.preferredWidth: 80+ placeholderText: qsTr("Port")+ validator: IntValidator { bottom: 1; top: 65535 }+ }+ UI.ComboBox {+ id: smtpSecurity+ Layout.preferredWidth: 130+ model: [{ value: "ssl", text: "SSL/TLS" }, { value: "starttls", text: "STARTTLS" }, { value: "none", text: qsTr("None") }]+ }+ // Username and password side by side, to keep the step+ // short enough never to scroll.+ GridLayout {+ Layout.columnSpan: 3+ Layout.fillWidth: true+ Layout.topMargin: 6+ columns: 2+ columnSpacing: 10+ rowSpacing: 8++ UI.Label {+ text: qsTr("Username")+ size: 13+ font.weight: Font.DemiBold+ }+ UI.Label {+ text: qsTr("Password")+ size: 13+ font.weight: Font.DemiBold+ }+ UI.TextField {+ id: user+ Layout.fillWidth: true+ Layout.preferredWidth: 1+ }+ UI.TextField {+ id: manualPassword+ Layout.fillWidth: true+ Layout.preferredWidth: 1+ revealable: true+ }+ }+ UI.Label {+ Layout.columnSpan: 3+ Layout.fillWidth: true+ visible: imapSecurity.currentIndex === 2 || smtpSecurity.currentIndex === 2+ text: qsTr("Without SSL/TLS or STARTTLS your password and mail cross the network unprotected.")+ size: 12+ color: UI.Style.warning+ wrapMode: Text.WordWrap+ }+ }++ // Step 3: the name people see.+ ColumnLayout {+ visible: dialog.step === "details"+ Layout.fillWidth: true+ spacing: 10++ UI.Label {+ Layout.fillWidth: true+ text: qsTr("You can change any of this later in Settings.")+ size: 13+ color: UI.Style.inkMuted+ }+ UI.Label {+ text: qsTr("Your name, as people see it")+ size: 13+ font.weight: Font.Medium+ }+ UI.TextField {+ id: fullName+ Layout.fillWidth: true+ }+ UI.Label {+ text: qsTr("What to call this account in Mail")+ size: 13+ font.weight: Font.Medium+ }+ UI.TextField {+ id: accountName+ Layout.fillWidth: true+ }+ UI.SettingRow {+ Layout.fillWidth: true+ title: qsTr("Keep all mail on this PC")+ description: qsTr("Read and search everything offline. Off keeps only what you open.")++ UI.Toggle {+ id: keepAll+ checked: true+ }+ }+ }++ // Done.+ ColumnLayout {+ visible: dialog.step === "done"+ Layout.fillWidth: true+ spacing: 10++ UI.Label {+ Layout.fillWidth: true+ text: qsTr("You can start using Mail now. Older messages keep arriving in the background.")+ size: 13+ color: UI.Style.inkMuted+ wrapMode: Text.WordWrap+ }+ RowLayout {+ visible: MailEngine.syncStatus.length > 0+ spacing: 8+ UI.Spinner {+ size: 14+ }+ UI.Label {+ text: MailEngine.syncStatus+ size: 13+ }+ }+ }++ UI.Label {+ Layout.fillWidth: true+ visible: dialog.error.length > 0+ text: dialog.error+ size: 13+ color: UI.Style.danger+ wrapMode: Text.WordWrap+ }++ RowLayout {+ Layout.fillWidth: true+ Layout.topMargin: 8+ spacing: 8++ UI.Button {+ visible: dialog.step === "done"+ text: qsTr("Add another account")+ onClicked: dialog.open()+ }+ UI.Button {+ visible: dialog.step === "password" || dialog.step === "manual" || dialog.step === "google"+ text: qsTr("Back")+ enabled: !dialog.testing+ onClicked: {+ GoogleSignIn.cancel();+ dialog.error = "";+ dialog.step = "email";+ }+ }+ Item {+ Layout.fillWidth: true+ }+ UI.Button {+ visible: dialog.step !== "done"+ text: qsTr("Cancel")+ enabled: !dialog.testing+ onClicked: dialog.close()+ }+ UI.Button {+ id: continueButton+ visible: dialog.step !== "google"+ kind: "primary"+ busy: dialog.testing || autoConfig.busy+ enabled: !dialog.testing && !autoConfig.busy+ && (dialog.step !== "email" || email.text.trim().indexOf("@") > 0)+ && (dialog.step !== "password" || password.text.length > 0)+ && (dialog.step !== "manual" || (imapHost.text.length > 0 && smtpHost.text.length > 0 && manualPassword.text.length > 0))+ text: dialog.step === "email" ? qsTr("Continue") : dialog.step === "details" ? qsTr("Finish")+ : dialog.step === "done" ? qsTr("Go to Inbox") : dialog.testing ? qsTr("Checking") : qsTr("Sign in")+ onClicked: {+ dialog.error = "";+ if (dialog.step === "email") {+ autoConfig.lookup(email.text.trim());+ } else if (dialog.step === "password") {+ dialog.test(password.text);+ } else if (dialog.step === "manual") {+ const sec = ["ssl", "starttls", "none"];+ dialog.settings = Object.assign({}, dialog.settings, {+ email: email.text.trim(), provider: "other",+ imapHost: imapHost.text.trim(), imapPort: parseInt(imapPort.text), imapSecurity: sec[imapSecurity.currentIndex],+ smtpHost: smtpHost.text.trim(), smtpPort: parseInt(smtpPort.text), smtpSecurity: sec[smtpSecurity.currentIndex],+ user: user.text.trim()+ });+ password.text = manualPassword.text;+ dialog.test(manualPassword.text);+ } else if (dialog.step === "details") {+ const s = Object.assign({}, dialog.settings, { fullName: fullName.text.trim(), name: accountName.text.trim() || dialog.settings.email, keepAll: keepAll.checked });+ MailEngine.saveAccount(s, dialog.secret);+ // Google's sign-in allowed calendars and contacts too.+ if (s.auth === "google") {+ CalendarEngine.addGoogleAccount(s.email, dialog.secret);+ }+ dialog.secret = "";+ password.text = "";+ manualPassword.text = "";+ dialog.step = "done";+ } else {+ dialog.close();+ }+ }+ }+ }+ }+ }+ }+}diff --git a/packages/wildos-mail/qml/AddCalendar.qml b/packages/wildos-mail/qml/AddCalendar.qmlnew file mode 100644index 0000000..9010a7f--- /dev/null+++ b/packages/wildos-mail/qml/AddCalendar.qml@@ -0,0 +1,401 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Mail+import WildOS.UI as UI++// Adding a calendar: a Google account (Google's own sign-in page), iCloud+// with an app-specific password, any other CalDAV server, a calendar from+// the web, or a new one on this PC. Shown over the window and sized to+// what's in it, like adding a mail account, so it never scrolls.+Item {+ id: dialog++ // choose, google, icloud, caldav, web, local, done+ property string step: "choose"+ property string error+ property bool working: false++ function start() {+ step = "choose";+ error = "";+ working = false;+ for (const f of [googleEmail, icloudEmail, icloudPassword, server, serverUser, serverPassword, serverName, webAddress, webName, localName]) {+ f.text = "";+ }+ visible = true;+ }+ function close() {+ GoogleSignIn.cancel();+ visible = false;+ }+ function go(next) {+ error = "";+ step = next;+ const first = { google: googleEmail, icloud: icloudEmail, caldav: server, web: webAddress, local: localName }[next];+ if (first) {+ first.forceActiveFocus();+ }+ }++ visible: false+ anchors.fill: parent+ z: 50++ Connections {+ target: GoogleSignIn+ function onSignedIn(address, refreshToken) {+ if (dialog.visible && dialog.step === "google") {+ dialog.working = true;+ CalendarEngine.addGoogleAccount(googleEmail.text.trim(), refreshToken);+ }+ }+ function onFailed(message) {+ if (dialog.visible && dialog.step === "google") {+ dialog.error = message;+ }+ }+ }+ Connections {+ target: CalendarEngine+ function onAccountAdded(uid) {+ if (dialog.visible) {+ dialog.working = false;+ dialog.step = "done";+ }+ }+ function onAccountFailed(message) {+ if (dialog.visible) {+ dialog.working = false;+ dialog.error = message;+ }+ }+ }++ Rectangle {+ anchors.fill: parent+ color: UI.Style.scrim+ MouseArea {+ anchors.fill: parent+ }+ }++ Rectangle {+ id: card+ anchors.centerIn: parent+ width: Math.min(560, parent.width - 48)+ height: content.implicitHeight + 48+ radius: UI.Style.radiusDialog+ color: UI.Style.windowOpaque+ border.width: 1+ border.color: UI.Style.borderDialog++ ColumnLayout {+ id: content+ x: 24+ y: 24+ width: card.width - 48+ spacing: 12++ UI.Label {+ Layout.fillWidth: true+ text: dialog.step === "choose" ? qsTr("Add a calendar")+ : dialog.step === "google" ? qsTr("Google Calendar")+ : dialog.step === "icloud" ? qsTr("iCloud Calendar")+ : dialog.step === "caldav" ? qsTr("Another calendar account")+ : dialog.step === "web" ? qsTr("A calendar from the web")+ : dialog.step === "local" ? qsTr("A new calendar on this PC")+ : qsTr("You're all set")+ size: 22+ font.weight: Font.DemiBold+ wrapMode: Text.WordWrap+ }++ // What kind.+ ColumnLayout {+ visible: dialog.step === "choose"+ Layout.fillWidth: true+ spacing: 8+ Repeater {+ model: [+ { id: "google", name: qsTr("Google"), note: qsTr("Gmail and Google Workspace calendars, with Google's sign-in") },+ { id: "icloud", name: qsTr("iCloud"), note: qsTr("Your Apple calendars, with an app-specific password") },+ { id: "caldav", name: qsTr("Another calendar account"), note: qsTr("Fastmail, Nextcloud, Proton Bridge and any CalDAV server") },+ { id: "web", name: qsTr("Subscribe from the web"), note: qsTr("A calendar address (webcal or .ics), such as fixtures or term dates") },+ { id: "local", name: qsTr("New calendar on this PC"), note: qsTr("Kept only on this computer") }+ ]+ delegate: Rectangle {+ id: tile+ required property var modelData+ Layout.fillWidth: true+ implicitHeight: 54+ radius: 8+ color: tileMouse.containsMouse ? UI.Style.surfaceHover : UI.Style.surfaceRaised+ border.width: 1+ border.color: UI.Style.borderSubtle+ MouseArea {+ id: tileMouse+ anchors.fill: parent+ hoverEnabled: true+ cursorShape: Qt.PointingHandCursor+ onClicked: dialog.go(tile.modelData.id)+ }+ ColumnLayout {+ anchors.fill: parent+ anchors.leftMargin: 14+ anchors.rightMargin: 10+ anchors.topMargin: 8+ anchors.bottomMargin: 8+ spacing: 1+ UI.Label {+ text: tile.modelData.name+ size: 13+ font.weight: Font.DemiBold+ }+ UI.Label {+ Layout.fillWidth: true+ text: tile.modelData.note+ size: 11.5+ color: UI.Style.inkMuted+ elide: Text.ElideRight+ }+ }+ }+ }+ }++ // Google.+ ColumnLayout {+ visible: dialog.step === "google"+ Layout.fillWidth: true+ spacing: 10+ UI.Label {+ Layout.fillWidth: true+ text: GoogleSignIn.waiting ? qsTr("We've opened Google's sign-in page in your browser. Sign in there and allow access to your calendars and contacts, then come back here.")+ : qsTr("Your Google address. Google's own page opens in your browser to sign in; Wild OS never sees your password.")+ size: 13+ wrapMode: Text.WordWrap+ }+ UI.TextField {+ id: googleEmail+ Layout.fillWidth: true+ enabled: !GoogleSignIn.waiting+ placeholderText: "[email protected]"+ inputMethodHints: Qt.ImhEmailCharactersOnly | Qt.ImhNoAutoUppercase+ onAccepted: googleButton.clicked()+ }+ UI.LinkButton {+ visible: GoogleSignIn.waiting+ text: qsTr("Open Google's page again")+ onClicked: GoogleSignIn.reopen()+ }+ }++ // iCloud.+ ColumnLayout {+ visible: dialog.step === "icloud"+ Layout.fillWidth: true+ spacing: 10+ UI.Label {+ Layout.fillWidth: true+ text: qsTr("iCloud needs an app-specific password, not your Apple Account password. In your Apple Account, open Sign-In and Security, then App-Specific Passwords.")+ size: 13+ wrapMode: Text.WordWrap+ }+ UI.LinkButton {+ text: qsTr("Open Apple Account")+ onClicked: Qt.openUrlExternally("https://account.apple.com")+ }+ UI.TextField {+ id: icloudEmail+ Layout.fillWidth: true+ placeholderText: qsTr("Apple Account email")+ inputMethodHints: Qt.ImhEmailCharactersOnly | Qt.ImhNoAutoUppercase+ }+ UI.TextField {+ id: icloudPassword+ Layout.fillWidth: true+ placeholderText: qsTr("App-specific password")+ echoMode: TextInput.Password+ revealable: true+ onAccepted: icloudButton.clicked()+ }+ }++ // Any CalDAV server.+ ColumnLayout {+ visible: dialog.step === "caldav"+ Layout.fillWidth: true+ spacing: 10+ UI.TextField {+ id: server+ Layout.fillWidth: true+ placeholderText: qsTr("Server address, for example https://caldav.fastmail.com")+ inputMethodHints: Qt.ImhUrlCharactersOnly | Qt.ImhNoAutoUppercase+ }+ UI.TextField {+ id: serverUser+ Layout.fillWidth: true+ placeholderText: qsTr("User name, often your email address")+ inputMethodHints: Qt.ImhNoAutoUppercase+ }+ UI.TextField {+ id: serverPassword+ Layout.fillWidth: true+ placeholderText: qsTr("Password or app password")+ echoMode: TextInput.Password+ revealable: true+ }+ UI.TextField {+ id: serverName+ Layout.fillWidth: true+ placeholderText: qsTr("Name in the list (optional)")+ onAccepted: caldavButton.clicked()+ }+ }++ // A calendar from the web.+ ColumnLayout {+ visible: dialog.step === "web"+ Layout.fillWidth: true+ spacing: 10+ UI.TextField {+ id: webAddress+ Layout.fillWidth: true+ placeholderText: "webcal://… or https://….ics"+ inputMethodHints: Qt.ImhUrlCharactersOnly | Qt.ImhNoAutoUppercase+ }+ UI.TextField {+ id: webName+ Layout.fillWidth: true+ placeholderText: qsTr("Name in the list")+ onAccepted: webButton.clicked()+ }+ UI.Label {+ Layout.fillWidth: true+ text: qsTr("Calendar checks it twice a day. You can see these events but not change them.")+ size: 12+ color: UI.Style.inkMuted+ wrapMode: Text.WordWrap+ }+ }++ // On this PC.+ ColumnLayout {+ visible: dialog.step === "local"+ Layout.fillWidth: true+ spacing: 10+ UI.TextField {+ id: localName+ Layout.fillWidth: true+ placeholderText: qsTr("Name, for example Family")+ onAccepted: localButton.clicked()+ }+ }++ UI.Label {+ visible: dialog.step === "done"+ Layout.fillWidth: true+ text: qsTr("Its calendars appear in the list as soon as they've been fetched, usually within a minute.")+ size: 13+ wrapMode: Text.WordWrap+ }++ UI.Label {+ visible: dialog.error.length > 0+ Layout.fillWidth: true+ text: dialog.error+ size: 13+ color: UI.Style.danger+ wrapMode: Text.WordWrap+ }++ RowLayout {+ Layout.fillWidth: true+ Layout.topMargin: 8+ spacing: 8+ UI.Button {+ visible: dialog.step !== "choose" && dialog.step !== "done"+ text: qsTr("Back")+ onClicked: {+ GoogleSignIn.cancel();+ dialog.go("choose");+ }+ }+ Item {+ Layout.fillWidth: true+ }+ UI.Button {+ visible: dialog.step !== "done"+ text: qsTr("Cancel")+ onClicked: dialog.close()+ }+ UI.Button {+ id: googleButton+ visible: dialog.step === "google"+ kind: "primary"+ busy: GoogleSignIn.waiting || dialog.working+ enabled: googleEmail.text.indexOf("@") > 0 && !busy+ text: qsTr("Sign in with Google")+ onClicked: {+ dialog.error = "";+ GoogleSignIn.startCalendar(googleEmail.text.trim());+ }+ }+ UI.Button {+ id: icloudButton+ visible: dialog.step === "icloud"+ kind: "primary"+ busy: dialog.working+ enabled: icloudEmail.text.indexOf("@") > 0 && icloudPassword.text.length > 0 && !busy+ text: qsTr("Add")+ onClicked: {+ dialog.working = true;+ CalendarEngine.addCalDavAccount("iCloud", "https://caldav.icloud.com/", icloudEmail.text.trim(), icloudPassword.text);+ }+ }+ UI.Button {+ id: caldavButton+ visible: dialog.step === "caldav"+ kind: "primary"+ busy: dialog.working+ enabled: server.text.trim().length > 3 && serverUser.text.trim().length > 0 && serverPassword.text.length > 0 && !busy+ text: qsTr("Add")+ onClicked: {+ dialog.working = true;+ CalendarEngine.addCalDavAccount(serverName.text.trim(), server.text.trim(), serverUser.text.trim(), serverPassword.text);+ }+ }+ UI.Button {+ id: webButton+ visible: dialog.step === "web"+ kind: "primary"+ enabled: webAddress.text.trim().length > 8+ text: qsTr("Subscribe")+ onClicked: {+ CalendarEngine.addWebCalendar(webName.text.trim(), webAddress.text.trim(), "");+ dialog.step = "done";+ }+ }+ UI.Button {+ id: localButton+ visible: dialog.step === "local"+ kind: "primary"+ enabled: localName.text.trim().length > 0+ text: qsTr("Create")+ onClicked: {+ CalendarEngine.addLocalCalendar(localName.text.trim(), "");+ dialog.close();+ }+ }+ UI.Button {+ visible: dialog.step === "done"+ kind: "primary"+ text: qsTr("Done")+ onClicked: dialog.close()+ }+ }+ }+ }++ Keys.onEscapePressed: close()+}diff --git a/packages/wildos-mail/qml/AppRail.qml b/packages/wildos-mail/qml/AppRail.qmlnew file mode 100644index 0000000..f3cebba--- /dev/null+++ b/packages/wildos-mail/qml/AppRail.qml@@ -0,0 +1,94 @@+import QtQuick+import WildOS.Mail+import WildOS.UI as UI++// The rail down the left of Mail and Calendar (MailMicrosoft.dc,+// CalendarMicrosoft.dc): each is a tab of the same window, and+// right-clicking one opens it in a window of its own. People and Tasks+// join it when they are built.+Rectangle {+ id: rail++ property string current: "mail"+ property bool squareCorner: false++ signal picked(string app)++ implicitWidth: 60+ color: UI.Style.shade(0.30, 0.04)+ bottomLeftRadius: squareCorner ? 0 : UI.Style.windowRadius - 1++ Column {+ x: 4+ y: 8+ spacing: 4++ Repeater {+ model: [+ { id: "mail", name: qsTr("Mail"), icon: "mail" },+ { id: "calendar", name: qsTr("Calendar"), icon: "calendar" }+ ]+ delegate: Rectangle {+ id: item+ required property var modelData+ readonly property bool active: rail.current === modelData.id+ width: 52+ height: 52+ radius: 8+ color: active ? UI.Style.accentSelected : mouse.containsMouse ? UI.Style.surfaceHover : "transparent"+ Accessible.role: Accessible.Button+ Accessible.name: modelData.name++ Rectangle {+ visible: item.active+ x: 0+ y: 10+ width: 3+ height: 32+ radius: 2+ color: UI.Style.accent+ }+ Column {+ anchors.centerIn: parent+ spacing: 3+ MailIcon {+ anchors.horizontalCenter: parent.horizontalCenter+ name: item.modelData.icon+ size: 19+ color: item.active ? UI.Style.accent : UI.Style.iconMuted+ }+ UI.Label {+ anchors.horizontalCenter: parent.horizontalCenter+ text: item.modelData.name+ size: 10+ font.weight: item.active ? Font.DemiBold : Font.Normal+ color: item.active ? UI.Style.accent : UI.Style.inkMuted+ }+ }+ MouseArea {+ id: mouse+ anchors.fill: parent+ hoverEnabled: true+ acceptedButtons: Qt.LeftButton | Qt.RightButton+ cursorShape: item.active ? Qt.ArrowCursor : Qt.PointingHandCursor+ onClicked: function (event) {+ if (event.button === Qt.RightButton && item.modelData.id === "calendar") {+ railMenu.app = item.modelData.id;+ railMenu.popup();+ } else if (!item.active) {+ rail.picked(item.modelData.id);+ }+ }+ }+ }+ }+ }++ UI.Menu {+ id: railMenu+ property string app+ entries: [+ { text: qsTr("Open in new window"), icon: "external", run: () => Apps.openWindow(railMenu.app) }+ ]+ }+}diff --git a/packages/wildos-mail/qml/CalendarList.qml b/packages/wildos-mail/qml/CalendarList.qmlnew file mode 100644index 0000000..8f54826--- /dev/null+++ b/packages/wildos-mail/qml/CalendarList.qml@@ -0,0 +1,231 @@+import QtQuick+import QtQuick.Controls as QQC+import QtQuick.Layouts+import WildOS.Mail+import WildOS.UI as UI++// The calendars (CalendarMicrosoft.dc, under the small month): the ones on+// this PC first, then each account's, each with a box in its own colour+// that shows or hides it. Right-click one to rename it, change its colour,+// make new events go to it, or remove it.+QQC.ScrollView {+ id: list++ signal addCalendar()++ property var collapsed: ({})+ readonly property var groups: {+ const out = [];+ for (const c of CalendarEngine.calendars) {+ let g = out.find(x => x.name === c.group);+ if (!g) {+ g = { name: c.group, uid: c.groupUid, items: [] };+ out.push(g);+ }+ g.items.push(c);+ }+ return out;+ }+ readonly property var palette: [+ { c: "#6f9bff", n: qsTr("Blue") }, { c: "#4cc38a", n: qsTr("Green") }, { c: "#f0a04b", n: qsTr("Orange") },+ { c: "#ee6f9a", n: qsTr("Pink") }, { c: "#a98bf5", n: qsTr("Purple") }, { c: "#46c2c9", n: qsTr("Teal") },+ { c: "#e5c55a", n: qsTr("Yellow") }, { c: "#9aa3b5", n: qsTr("Grey") }+ ]++ clip: true+ contentWidth: availableWidth++ ColumnLayout {+ width: list.availableWidth+ spacing: 2++ Repeater {+ model: list.groups+ delegate: ColumnLayout {+ id: group+ required property var modelData+ readonly property bool open: !list.collapsed[modelData.name]+ Layout.fillWidth: true+ spacing: 2++ Item {+ Layout.fillWidth: true+ implicitHeight: 30+ RowLayout {+ anchors.fill: parent+ spacing: 6+ MailIcon {+ name: group.open ? "chevron-down" : "chevron-right"+ size: 12+ color: UI.Style.iconMuted+ }+ UI.Label {+ Layout.fillWidth: true+ text: group.modelData.name+ size: 13+ font.weight: Font.DemiBold+ elide: Text.ElideRight+ }+ }+ MouseArea {+ anchors.fill: parent+ cursorShape: Qt.PointingHandCursor+ onClicked: {+ const c = Object.assign({}, list.collapsed);+ c[group.modelData.name] = group.open;+ list.collapsed = c;+ }+ }+ }++ Repeater {+ model: group.open ? group.modelData.items : []+ delegate: Rectangle {+ id: row+ required property var modelData+ Layout.fillWidth: true+ implicitHeight: 30+ radius: 6+ color: rowMouse.containsMouse ? UI.Style.surfaceHover : "transparent"++ RowLayout {+ anchors.fill: parent+ anchors.leftMargin: 18+ anchors.rightMargin: 6+ spacing: 10+ Rectangle {+ width: 16+ height: 16+ radius: 4+ color: row.modelData.selected ? row.modelData.color : "transparent"+ border.width: 1.5+ border.color: row.modelData.color+ MailIcon {+ anchors.centerIn: parent+ visible: row.modelData.selected+ name: "check"+ size: 12+ strokeWidth: 2.4+ color: "#10152a"+ }+ }+ UI.Label {+ Layout.fillWidth: true+ text: row.modelData.name+ size: 13+ elide: Text.ElideRight+ }+ UI.Label {+ visible: row.modelData.uid === CalendarEngine.defaultCalendar && CalendarEngine.calendars.length > 1+ text: qsTr("Default")+ size: 11+ color: UI.Style.inkSubtle+ }+ }+ MouseArea {+ id: rowMouse+ anchors.fill: parent+ hoverEnabled: true+ acceptedButtons: Qt.LeftButton | Qt.RightButton+ cursorShape: Qt.PointingHandCursor+ Accessible.role: Accessible.CheckBox+ Accessible.name: row.modelData.name+ onClicked: function (event) {+ if (event.button === Qt.RightButton) {+ menu.calendar = row.modelData;+ menu.popup();+ } else {+ CalendarEngine.setSelected(row.modelData.uid, !row.modelData.selected);+ }+ }+ }+ }+ }+ }+ }++ UI.LinkButton {+ Layout.topMargin: 6+ Layout.leftMargin: 2+ text: "+ " + qsTr("Add calendar")+ onClicked: list.addCalendar()+ }+ }++ UI.Menu {+ id: menu+ property var calendar: ({})+ entries: [+ { text: qsTr("Rename"), enabled: !calendar.readOnly || calendar.kind === "webcal", run: () => renameDialog.ask(menu.calendar) },+ { text: qsTr("Colour"), submenu: list.palette.map(p => ({ text: p.n, radio: true, checked: p.c === menu.calendar.color, run: () => CalendarEngine.setColor(menu.calendar.uid, p.c) })) },+ { text: qsTr("New events go here"), enabled: !calendar.readOnly, checked: calendar.uid === CalendarEngine.defaultCalendar, run: () => CalendarEngine.defaultCalendar = menu.calendar.uid },+ { separator: true },+ { text: calendar.kind === "system" ? qsTr("This PC's calendar can't be removed") : calendar.groupUid ? qsTr("Hide from Calendar") : qsTr("Remove"),+ icon: "delete", danger: calendar.kind !== "system", enabled: calendar.kind !== "system",+ run: () => removeConfirm.ask(menu.calendar) }+ ]+ }++ UI.Dialog {+ id: renameDialog+ property var calendar: ({})+ function ask(c) {+ calendar = c;+ renameField.text = c.name;+ open();+ renameField.forceActiveFocus();+ renameField.selectAll();+ }+ title: qsTr("Rename calendar")+ UI.TextField {+ id: renameField+ Layout.fillWidth: true+ onAccepted: renameButton.clicked()+ }+ buttons: [+ UI.Button {+ text: qsTr("Cancel")+ onClicked: renameDialog.close()+ },+ UI.Button {+ id: renameButton+ kind: "primary"+ text: qsTr("Rename")+ enabled: renameField.text.trim().length > 0+ onClicked: {+ CalendarEngine.renameCalendar(renameDialog.calendar.uid, renameField.text.trim());+ renameDialog.close();+ }+ }+ ]+ }++ UI.Dialog {+ id: removeConfirm+ property var calendar: ({})+ function ask(c) {+ calendar = c;+ open();+ }+ title: calendar.groupUid ? qsTr("Hide %1?").arg(calendar.name) : qsTr("Remove %1?").arg(calendar.name)+ text: calendar.groupUid ? qsTr("It stays in your account; Calendar stops showing it. Add the account again to bring it back.")+ : calendar.kind === "local" ? qsTr("The calendar and every event in it are deleted from this PC. This can't be undone.")+ : qsTr("Calendar stops showing it.")+ iconName: "warning"+ buttons: [+ UI.Button {+ text: qsTr("Cancel")+ onClicked: removeConfirm.close()+ },+ UI.Button {+ kind: "primary"+ danger: true+ text: removeConfirm.calendar.groupUid ? qsTr("Hide") : qsTr("Remove")+ onClicked: {+ CalendarEngine.removeCalendar(removeConfirm.calendar.uid);+ removeConfirm.close();+ }+ }+ ]+ }+}diff --git a/packages/wildos-mail/qml/CalendarMain.qml b/packages/wildos-mail/qml/CalendarMain.qmlnew file mode 100644index 0000000..8f35258--- /dev/null+++ b/packages/wildos-mail/qml/CalendarMain.qml@@ -0,0 +1,94 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Mail+import WildOS.UI as UI++// Calendar in a window of its own, from right-clicking Calendar on the+// rail and choosing Open in new window. Normally it's a tab of Mail.+UI.AppWindow {+ id: window++ width: 1384+ height: 802+ minimumWidth: 960+ minimumHeight: 640+ visible: true+ title: qsTr("Calendar")++ function showEvent(key, day) {+ page.showEvent(key, day);+ }++ Shortcut {+ sequence: "Ctrl+E"+ onActivated: search.forceActiveFocus()+ }++ ColumnLayout {+ anchors.fill: parent+ anchors.margins: window.maximised ? 0 : 1+ spacing: 0++ UI.TitleBar {+ Layout.fillWidth: true+ title: qsTr("Calendar")+ tinted: true+ frame: window.frame++ Item {+ anchors.fill: parent+ UI.SearchField {+ id: search+ anchors.centerIn: parent+ width: Math.min(520, parent.width - 160)+ height: 32+ placeholderText: qsTr("Search events")+ onTextChanged: searchTimer.restart()+ onEscapePressed: {+ text = "";+ page.clearSearch();+ }+ onAccepted: {+ searchTimer.stop();+ page.search(text);+ }+ }+ Timer {+ id: searchTimer+ interval: 300+ onTriggered: page.search(search.text)+ }+ CommandButton {+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ iconOnly: true+ iconName: "settings"+ tip: qsTr("Settings")+ onClicked: page.toggleSettings()+ }+ }+ }++ RowLayout {+ Layout.fillWidth: true+ Layout.fillHeight: true+ spacing: 0++ AppRail {+ Layout.fillHeight: true+ current: "calendar"+ squareCorner: window.maximised+ onPicked: function (app) {+ if (app === "mail") {+ Apps.open("mail");+ }+ }+ }+ CalendarPage {+ id: page+ Layout.fillWidth: true+ Layout.fillHeight: true+ }+ }+ }+}diff --git a/packages/wildos-mail/qml/CalendarPage.qml b/packages/wildos-mail/qml/CalendarPage.qmlnew file mode 100644index 0000000..b0dbc0e--- /dev/null+++ b/packages/wildos-mail/qml/CalendarPage.qml@@ -0,0 +1,732 @@+import QtCore+import QtQuick+import QtQuick.Controls as QQC+import QtQuick.Layouts+import WildOS.Mail+import WildOS.UI as UI+import "Formats.js" as Formats++// Calendar (CalendarMicrosoft.dc and the boards after it): the ribbon,+// then the small month and the calendars beside the day, week or month,+// which turns into the event being written. A tab of the Mail window, or+// a window of its own (CalendarMain) from "Open in new window"; the+// window around it has the title bar, its search and the app rail.+Item {+ id: window++ // Mail's Google accounts whose calendars aren't here yet, offered in a+ // bar (empty in a window of its own, which doesn't run Mail).+ property var mailAccounts: []+ signal addGoogleCalendar(string email)++ property string view: prefs.view+ // A day inside what's on screen.+ property date anchor: today()+ property bool editing: false+ property bool showSettings: false+ property string openKey: ""+ // An event to open once its days have loaded (from a reminder or search).+ property string pendingKey: ""++ function today() {+ const n = new Date();+ return new Date(n.getFullYear(), n.getMonth(), n.getDate());+ }+ function addDays(d, n) {+ return new Date(d.getFullYear(), d.getMonth(), d.getDate() + n);+ }+ function weekStart(d) {+ return addDays(d, -((d.getDay() - prefs.firstDay + 7) % 7));+ }+ readonly property var workDays: (prefs.workDays || "1,2,3,4,5").split(",").map(Number)+ // The work week runs from the first working day to the last, counted+ // from the first day of the week.+ readonly property int workFirst: Math.min.apply(null, workDays.map(d => (d - prefs.firstDay + 7) % 7))+ readonly property int workLast: Math.max.apply(null, workDays.map(d => (d - prefs.firstDay + 7) % 7))+ readonly property date rangeFrom: view === "day" ? anchor : view === "workweek" ? addDays(weekStart(anchor), workFirst)+ : view === "week" ? weekStart(anchor) : monthView.firstShown+ readonly property int rangeDays: view === "day" ? 1 : view === "workweek" ? workLast - workFirst + 1 : view === "week" ? 7 : 42+ readonly property date rangeTo: addDays(rangeFrom, rangeDays)+ onRangeFromChanged: Qt.callLater(pushRange)+ onRangeDaysChanged: Qt.callLater(pushRange)+ function pushRange() {+ CalendarEngine.setRange(rangeFrom, rangeTo);+ }++ readonly property string rangeTitle: {+ if (view === "day") {+ return Formats.longDate(anchor);+ }+ if (view === "month") {+ return Formats.monthAndYear(anchor);+ }+ const last = addDays(rangeTo, -1);+ // "9 to 15 November 2026" only reads right where the day comes first.+ if (rangeFrom.getMonth() === last.getMonth() && Formats.dayFirst()) {+ return qsTr("%1 to %2").arg(rangeFrom.getDate()).arg(Formats.dayMonthYear(last));+ }+ if (rangeFrom.getFullYear() === last.getFullYear()) {+ return qsTr("%1 to %2").arg(Formats.dayAndMonth(rangeFrom)).arg(Formats.dayMonthYear(last));+ }+ return qsTr("%1 to %2").arg(Formats.dayMonthYear(rangeFrom)).arg(Formats.dayMonthYear(last));+ }++ function step(n) {+ if (view === "month") {+ anchor = new Date(anchor.getFullYear(), anchor.getMonth() + n, 1);+ } else {+ anchor = addDays(anchor, n * (view === "day" ? 1 : 7));+ }+ miniMonth.month = new Date(anchor.getFullYear(), anchor.getMonth(), 1);+ }+ function goTo(day) {+ anchor = new Date(day.getFullYear(), day.getMonth(), day.getDate());+ miniMonth.month = new Date(anchor.getFullYear(), anchor.getMonth(), 1);+ }+ function setView(v) {+ view = v;+ prefs.view = v;+ editing = false;+ showSettings = false;+ }+ function newEvent(defaults) {+ if (!CalendarEngine.ready) {+ return;+ }+ showSettings = false;+ peek.close();+ editing = true;+ editor.start(null, defaults || {});+ }+ function editEvent(event) {+ showSettings = false;+ editing = true;+ editor.start(event, {});+ }+ function openEvent(key, block) {+ openKey = key;+ peek.show(key, block);+ }+ // From the command line: a reminder's Open, or search.+ function showEvent(key, day) {+ editing = false;+ showSettings = false;+ if (day) {+ goTo(day);+ }+ pendingKey = key;+ Qt.callLater(tryPending);+ }+ property string lastSearch+ function search(text) {+ lastSearch = text;+ if (text.trim().length > 0) {+ CalendarEngine.search(text);+ } else {+ results.close();+ }+ }+ function clearSearch() {+ lastSearch = "";+ results.close();+ }+ function toggleSettings() {+ editing = false;+ showSettings = !showSettings;+ }+ function tryPending() {+ if (!pendingKey) {+ return;+ }+ const e = CalendarEngine.event(pendingKey.split("\u001f").length === 3 ? pendingKey : pendingKey + "\u001f");+ if (e.key) {+ pendingKey = "";+ openKey = e.key;+ peek.show(e.key, header);+ }+ }++ Settings {+ id: prefs+ category: "calendar"+ property string view: "week"+ property int firstDay: 1+ property string workDays: "1,2,3,4,5"+ property real workStart: 9+ property real workEnd: 17.5+ property int defaultReminder: 15+ property int defaultLength: 60+ property bool weekNumbers: false+ }++ Connections {+ target: CalendarEngine+ function onNotice(text) {+ toast.show(text);+ }+ function onEventsChanged() {+ if (window.pendingKey) {+ window.tryPending();+ }+ }+ function onSaved(key) {+ toast.show(qsTr("Saved"));+ }+ }++ Shortcut {+ sequence: StandardKey.New+ enabled: window.visible+ onActivated: window.newEvent({})+ }+ Shortcut {+ sequence: "F5"+ enabled: window.visible+ onActivated: CalendarEngine.refresh()+ }+ Shortcut {+ sequence: "Alt+Left"+ enabled: window.visible && !window.editing+ onActivated: window.step(-1)+ }+ Shortcut {+ sequence: "Alt+Right"+ enabled: window.visible && !window.editing+ onActivated: window.step(1)+ }+ Shortcut {+ sequence: "Ctrl+1"+ enabled: window.visible+ onActivated: window.setView("day")+ }+ Shortcut {+ sequence: "Ctrl+2"+ enabled: window.visible+ onActivated: window.setView("workweek")+ }+ Shortcut {+ sequence: "Ctrl+3"+ enabled: window.visible+ onActivated: window.setView("week")+ }+ Shortcut {+ sequence: "Ctrl+4"+ enabled: window.visible+ onActivated: window.setView("month")+ }+ Shortcut {+ sequence: "Ctrl+T"+ enabled: window.visible+ onActivated: window.goTo(window.today())+ }++ ColumnLayout {+ anchors.fill: parent+ spacing: 0++ // The calendar service didn't start.+ Rectangle {+ visible: CalendarEngine.problem.length > 0+ Layout.fillWidth: true+ implicitHeight: 40+ color: UI.Style.warningSoft+ UI.Label {+ anchors.verticalCenter: parent.verticalCenter+ x: 18+ text: CalendarEngine.problem+ size: 13+ }+ }++ // A Google account Mail has whose calendar isn't here yet.+ Repeater {+ model: window.mailAccounts.filter(a => !CalendarEngine.accounts.some(c => (c.email || "").toLowerCase() === a.email.toLowerCase()))+ delegate: Rectangle {+ required property var modelData+ Layout.fillWidth: true+ Layout.leftMargin: 16+ Layout.rightMargin: 12+ Layout.topMargin: 8+ implicitHeight: 44+ radius: 8+ color: UI.Style.accentSoft+ border.width: 1+ border.color: UI.Style.accentBorder+ RowLayout {+ anchors.fill: parent+ anchors.leftMargin: 14+ anchors.rightMargin: 8+ spacing: 10+ MailIcon {+ name: "calendar"+ size: 16+ color: UI.Style.accent+ }+ UI.Label {+ Layout.fillWidth: true+ text: qsTr("Show the calendar for %1 here too. Google asks once to allow it.").arg(modelData.email)+ size: 13+ elide: Text.ElideRight+ }+ UI.Button {+ size: "small"+ kind: "primary"+ text: GoogleSignIn.waiting ? qsTr("Waiting for Google") : qsTr("Show my calendar")+ busy: GoogleSignIn.waiting+ enabled: !GoogleSignIn.waiting+ onClicked: window.addGoogleCalendar(modelData.email)+ }+ }+ }+ }++ RowLayout {+ Layout.fillWidth: true+ Layout.fillHeight: true+ spacing: 0++ ColumnLayout {+ Layout.fillWidth: true+ Layout.fillHeight: true+ Layout.bottomMargin: 12+ spacing: 10++ // The ribbon: Home, View and Help.+ ColumnLayout {+ visible: !window.showSettings+ Layout.fillWidth: true+ Layout.leftMargin: 16+ Layout.rightMargin: 12+ spacing: 2++ Row {+ id: tabs+ property string current: "home"+ leftPadding: 4+ spacing: 22+ Repeater {+ model: [{ id: "home", name: qsTr("Home") }, { id: "view", name: qsTr("View") }, { id: "help", name: qsTr("Help") }]+ delegate: Item {+ id: tab+ required property var modelData+ readonly property bool active: tabs.current === modelData.id+ width: tabLabel.implicitWidth + 4+ height: 36+ UI.Label {+ id: tabLabel+ anchors.centerIn: parent+ text: tab.modelData.name+ size: 13+ font.weight: tab.active ? Font.DemiBold : Font.Normal+ color: tab.active ? UI.Style.ink : UI.Style.inkMuted+ }+ Rectangle {+ visible: tab.active+ anchors.left: parent.left+ anchors.right: parent.right+ anchors.bottom: parent.bottom+ anchors.bottomMargin: 4+ height: 2+ radius: 1+ color: UI.Style.accent+ }+ MouseArea {+ anchors.fill: parent+ cursorShape: Qt.PointingHandCursor+ onClicked: tabs.current = tab.modelData.id+ }+ }+ }+ }++ Rectangle {+ Layout.fillWidth: true+ implicitHeight: 46+ radius: 10+ color: UI.Style.surfaceRest+ border.width: 1+ border.color: UI.Style.borderSubtle+ clip: true++ // Home+ RowLayout {+ visible: tabs.current === "home"+ anchors.fill: parent+ anchors.leftMargin: 8+ anchors.rightMargin: 8+ spacing: 2++ UI.Button {+ kind: "primary"+ size: "small"+ text: qsTr("New event")+ iconName: "plus"+ enabled: CalendarEngine.ready+ Layout.rightMargin: 6+ onClicked: window.newEvent({})+ }+ Repeater {+ model: [+ { id: "day", name: qsTr("Day"), icon: "calendar" },+ { id: "workweek", name: qsTr("Work week"), icon: "calendar" },+ { id: "week", name: qsTr("Week"), icon: "calendar" },+ { id: "month", name: qsTr("Month"), icon: "grid" }+ ]+ delegate: CommandButton {+ required property var modelData+ text: modelData.name+ iconName: modelData.icon+ checkable: false+ background: Rectangle {+ radius: 6+ color: window.view === modelData.id && !window.editing ? UI.Style.accentSelected : parent.hovered ? UI.Style.surfaceHover : "transparent"+ }+ onClicked: window.setView(modelData.id)+ }+ }+ Rectangle {+ implicitWidth: 1+ implicitHeight: 22+ Layout.leftMargin: 6+ Layout.rightMargin: 6+ color: UI.Style.borderSubtle+ }+ CommandButton {+ text: qsTr("Today")+ iconName: "calendar"+ onClicked: {+ window.editing = false;+ window.goTo(window.today());+ }+ }+ Item {+ Layout.fillWidth: true+ }+ CommandButton {+ iconOnly: true+ iconName: "refresh"+ tip: qsTr("Check for changes")+ onClicked: CalendarEngine.refresh()+ }+ }++ // View+ RowLayout {+ visible: tabs.current === "view"+ anchors.fill: parent+ anchors.leftMargin: 8+ anchors.rightMargin: 8+ spacing: 2+ CommandButton {+ text: prefs.firstDay === 1 ? qsTr("Weeks start on Monday") : qsTr("Weeks start on Sunday")+ iconName: "calendar"+ onClicked: prefs.firstDay = prefs.firstDay === 1 ? 0 : 1+ }+ CommandButton {+ text: qsTr("Calendar settings")+ iconName: "settings"+ onClicked: {+ settingsPage.section = "calendar";+ window.showSettings = true;+ }+ }+ Item {+ Layout.fillWidth: true+ }+ }++ // Help+ RowLayout {+ visible: tabs.current === "help"+ anchors.fill: parent+ anchors.leftMargin: 8+ anchors.rightMargin: 8+ spacing: 2+ CommandButton {+ text: qsTr("Using Calendar")+ iconName: "external"+ onClicked: Qt.openUrlExternally("https://help.wildos.io/using/calendar/")+ }+ CommandButton {+ text: qsTr("Keyboard shortcuts")+ iconName: "external"+ onClicked: Qt.openUrlExternally("https://help.wildos.io/using/calendar/#keyboard-shortcuts")+ }+ Item {+ Layout.fillWidth: true+ }+ }+ }+ }++ RowLayout {+ Layout.fillWidth: true+ Layout.fillHeight: true+ Layout.rightMargin: 12+ spacing: 12+ visible: !window.showSettings++ // The small month and the calendars.+ ColumnLayout {+ Layout.preferredWidth: 236+ Layout.maximumWidth: 236+ Layout.fillWidth: false+ Layout.fillHeight: true+ Layout.leftMargin: 14+ spacing: 14++ MiniMonth {+ id: miniMonth+ Layout.fillWidth: true+ firstDay: prefs.firstDay+ // In Month, the week of the day chosen, as the board has it.+ rangeFrom: window.view === "month" ? window.weekStart(window.anchor) : window.rangeFrom+ rangeTo: window.view === "month" ? window.addDays(window.weekStart(window.anchor), 7) : window.rangeTo+ onPicked: function (day) {+ window.editing = false;+ window.goTo(day);+ }+ }++ CalendarList {+ Layout.fillWidth: true+ Layout.fillHeight: true+ onAddCalendar: addCalendar.start()+ }+ }++ // The days, or the event being written.+ Rectangle {+ id: main+ visible: !window.editing+ Layout.fillWidth: true+ Layout.fillHeight: true+ radius: 10+ color: UI.Style.surfaceRest+ border.width: 1+ border.color: UI.Style.borderSubtle+ clip: true++ ColumnLayout {+ anchors.fill: parent+ spacing: 0++ RowLayout {+ id: header+ Layout.fillWidth: true+ Layout.leftMargin: 12+ Layout.rightMargin: 14+ Layout.topMargin: 10+ Layout.bottomMargin: 6+ spacing: 8+ UI.Button {+ size: "small"+ text: qsTr("Today")+ onClicked: window.goTo(window.today())+ }+ UI.IconButton {+ iconName: "chevron-left"+ tip: window.view === "month" ? qsTr("Previous month") : window.view === "day" ? qsTr("Previous day") : qsTr("Previous week")+ onClicked: window.step(-1)+ }+ UI.IconButton {+ iconName: "chevron-right"+ tip: window.view === "month" ? qsTr("Next month") : window.view === "day" ? qsTr("Next day") : qsTr("Next week")+ onClicked: window.step(1)+ }+ UI.Label {+ Layout.leftMargin: 8+ text: window.rangeTitle+ size: 17+ font.weight: Font.DemiBold+ }+ Item {+ Layout.fillWidth: true+ }+ UI.Label {+ text: qsTr("Times in %1").arg(CalendarEngine.timeZoneName)+ size: 12+ color: UI.Style.inkMuted+ }+ }++ WeekView {+ id: weekView+ visible: window.view !== "month"+ Layout.fillWidth: true+ Layout.fillHeight: true+ startDate: window.view === "month" ? window.anchor : window.rangeFrom+ days: window.view === "month" ? 7 : window.rangeDays+ scrollToHour: Math.max(0, Math.floor(prefs.workStart) - 1)+ openKey: peek.opened ? window.openKey : ""+ onEventClicked: function (key, block) {+ window.openEvent(key, block);+ }+ onNewAt: function (start, allDay) {+ window.newEvent({ start: start, allDay: allDay });+ }+ onDayClicked: function (day) {+ window.goTo(day);+ window.setView("day");+ }+ }++ MonthView {+ id: monthView+ visible: window.view === "month"+ Layout.fillWidth: true+ Layout.fillHeight: true+ month: window.anchor+ firstDay: prefs.firstDay+ openKey: peek.opened ? window.openKey : ""+ onEventClicked: function (key, block) {+ window.openEvent(key, block);+ }+ onNewAt: function (start, allDay) {+ const d = start;+ window.newEvent({ start: new Date(d.getFullYear(), d.getMonth(), d.getDate(), Math.floor(prefs.workStart), 0), allDay: false });+ }+ onDayClicked: function (day) {+ window.goTo(day);+ window.setView("day");+ }+ }+ }++ // Before the calendar service has answered.+ UI.Spinner {+ anchors.centerIn: parent+ visible: !CalendarEngine.ready && CalendarEngine.problem.length === 0+ running: visible+ }+ }++ EventEditor {+ id: editor+ visible: window.editing+ Layout.fillWidth: true+ Layout.fillHeight: true+ onClosed: window.editing = false+ }+ }++ CalendarSettings {+ id: settingsPage+ visible: window.showSettings+ Layout.fillWidth: true+ Layout.fillHeight: true+ Layout.rightMargin: 12+ onCloseRequested: window.showSettings = false+ onAddAccount: addCalendar.start()+ }+ }+ }+ }++ EventPeek {+ id: peek+ parent: QQC.Overlay.overlay+ onEditRequested: function (event) {+ window.editEvent(event);+ }+ onMessageEveryone: function (addresses, subject) {+ Qt.openUrlExternally("mailto:" + addresses.join(",") + "?subject=" + encodeURIComponent(subject));+ }+ }++ // Search results, under the search box.+ QQC.Popup {+ id: results+ property var items: []+ parent: QQC.Overlay.overlay+ x: (parent.width - width) / 2+ y: 44+ width: Math.min(520, parent.width - 160)+ height: Math.min(420, list.contentHeight + 16)+ padding: 8+ background: Rectangle {+ radius: 10+ color: UI.Style.glassMenu+ border.width: 1+ border.color: UI.Style.borderContextMenu+ }+ contentItem: ListView {+ id: list+ clip: true+ model: results.items+ delegate: Rectangle {+ required property var modelData+ width: ListView.view.width+ height: 48+ radius: 6+ color: rowMouse.containsMouse ? UI.Style.surfaceHover : "transparent"+ Rectangle {+ x: 10+ anchors.verticalCenter: parent.verticalCenter+ width: 4+ height: 30+ radius: 2+ color: modelData.color+ }+ Column {+ x: 24+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - 34+ UI.Label {+ width: parent.width+ text: modelData.title+ size: 13+ font.weight: Font.DemiBold+ elide: Text.ElideRight+ }+ UI.Label {+ width: parent.width+ text: Formats.mediumDate(new Date(modelData.start)) + (modelData.allDay ? "" : ", " + Formats.time(new Date(modelData.start)))+ + (modelData.location ? " · " + modelData.location : "")+ size: 12+ color: UI.Style.inkMuted+ elide: Text.ElideRight+ }+ }+ MouseArea {+ id: rowMouse+ anchors.fill: parent+ hoverEnabled: true+ cursorShape: Qt.PointingHandCursor+ onClicked: {+ results.close();+ window.showEvent(modelData.key, new Date(modelData.start));+ }+ }+ }+ }+ Connections {+ target: CalendarEngine+ function onSearchDone(text, items) {+ if (text !== window.lastSearch) {+ return;+ }+ results.items = items.length > 0 ? items : [];+ if (items.length > 0) {+ results.open();+ } else {+ results.close();+ toast.show(qsTr("Nothing found for \"%1\" in the year either side of today.").arg(text));+ }+ }+ }+ }++ AddCalendar {+ id: addCalendar+ parent: QQC.Overlay.overlay+ }++ UI.Toast {+ id: toast+ anchors.horizontalCenter: parent.horizontalCenter+ anchors.bottom: parent.bottom+ anchors.bottomMargin: 24+ z: 60+ }+}diff --git a/packages/wildos-mail/qml/CalendarSettings.qml b/packages/wildos-mail/qml/CalendarSettings.qmlnew file mode 100644index 0000000..b1ef437--- /dev/null+++ b/packages/wildos-mail/qml/CalendarSettings.qml@@ -0,0 +1,419 @@+import QtCore+import QtQuick+import QtQuick.Controls as QQC+import QtQuick.Layouts+import WildOS.Mail+import WildOS.UI as UI+import "Formats.js" as Formats++// Calendar's settings (CalMsSettings.dc), in the window in place of the+// days: the accounts its calendars come from, and the week, events and+// extra calendars.+Rectangle {+ id: page++ property string section: "calendar"++ signal closeRequested()+ signal addAccount()++ radius: 10+ color: UI.Style.surfaceRest+ border.width: 1+ border.color: UI.Style.borderSubtle+ clip: true++ readonly property var sections: [+ { id: "accounts", name: qsTr("Accounts"), icon: "people", blurb: qsTr("Where your calendars come from") },+ { id: "calendar", name: qsTr("Calendar"), icon: "calendar", blurb: qsTr("Your week, reminders and extra calendars") }+ ]++ Settings {+ id: prefs+ category: "calendar"+ property int firstDay: 1+ property string workDays: "1,2,3,4,5"+ property real workStart: 9+ property real workEnd: 17.5+ property int defaultReminder: 15+ property int defaultLength: 60+ }++ function hourChoices() {+ const list = [];+ for (let h = 0; h < 24; h += 0.5) {+ const whole = Math.floor(h);+ list.push({ value: h, text: (whole < 10 ? "0" : "") + whole + (h % 1 ? ":30" : ":00") });+ }+ return list;+ }+ readonly property var hours: hourChoices()++ RowLayout {+ anchors.fill: parent+ spacing: 0++ ColumnLayout {+ Layout.preferredWidth: 236+ Layout.fillHeight: true+ Layout.margins: 10+ spacing: 2++ RowLayout {+ Layout.fillWidth: true+ Layout.bottomMargin: 8+ UI.IconButton {+ iconName: "back"+ tip: qsTr("Back to calendar")+ onClicked: page.closeRequested()+ }+ UI.Label {+ text: qsTr("Settings")+ size: 16+ font.weight: Font.DemiBold+ }+ }++ Repeater {+ model: page.sections+ delegate: Rectangle {+ id: nav+ required property var modelData+ Layout.fillWidth: true+ implicitHeight: 34+ radius: 6+ color: page.section === modelData.id ? UI.Style.accentSelected : navMouse.containsMouse ? UI.Style.surfaceHover : "transparent"+ MouseArea {+ id: navMouse+ anchors.fill: parent+ hoverEnabled: true+ cursorShape: Qt.PointingHandCursor+ onClicked: page.section = nav.modelData.id+ }+ RowLayout {+ anchors.fill: parent+ anchors.leftMargin: 12+ spacing: 10+ MailIcon {+ name: nav.modelData.icon+ size: 16+ color: page.section === nav.modelData.id ? UI.Style.accent : UI.Style.iconInk+ }+ UI.Label {+ Layout.fillWidth: true+ text: nav.modelData.name+ size: 13+ font.weight: page.section === nav.modelData.id ? Font.DemiBold : Font.Normal+ }+ }+ }+ }+ Item {+ Layout.fillHeight: true+ }+ }++ Rectangle {+ Layout.fillHeight: true+ implicitWidth: 1+ color: UI.Style.borderSubtle+ }++ QQC.ScrollView {+ Layout.fillWidth: true+ Layout.fillHeight: true+ clip: true+ contentWidth: availableWidth++ ColumnLayout {+ width: Math.min(760, parent.width - 56)+ x: 28+ spacing: 14++ Item {+ implicitHeight: 14+ }+ UI.Label {+ text: page.sections.find(s => s.id === page.section).name+ size: 22+ font.weight: Font.DemiBold+ }+ UI.Label {+ text: page.sections.find(s => s.id === page.section).blurb+ size: 13+ color: UI.Style.inkMuted+ }++ // Accounts+ UI.Card {+ visible: page.section === "accounts"+ Layout.fillWidth: true+ ColumnLayout {+ width: parent.width+ UI.SettingRow {+ Layout.fillWidth: true+ title: qsTr("This PC")+ description: qsTr("Calendars kept only on this computer")+ }+ Repeater {+ model: CalendarEngine.accounts+ delegate: UI.SettingRow {+ required property var modelData+ Layout.fillWidth: true+ title: modelData.name+ description: modelData.kind === "google" ? qsTr("Google") : qsTr("Calendar server")+ UI.Button {+ size: "small"+ text: qsTr("Remove")+ onClicked: removeAccount.ask(modelData)+ }+ }+ }+ }+ }+ UI.Button {+ visible: page.section === "accounts"+ text: qsTr("Add account")+ iconName: "plus"+ onClicked: page.addAccount()+ }++ // Calendar: your week+ UI.Label {+ visible: page.section === "calendar"+ Layout.topMargin: 4+ text: qsTr("Your week")+ size: 13+ font.weight: Font.DemiBold+ }+ UI.Card {+ visible: page.section === "calendar"+ Layout.fillWidth: true+ ColumnLayout {+ width: parent.width+ UI.SettingRow {+ Layout.fillWidth: true+ title: qsTr("First day of the week")+ UI.ComboBox {+ readonly property var choices: [{ value: 1, text: Formats.names().dayName(1) }, { value: 0, text: Formats.names().dayName(0) }, { value: 6, text: Formats.names().dayName(6) }]+ model: choices+ currentIndex: Math.max(0, choices.findIndex(c => c.value === prefs.firstDay))+ onActivated: function (i) {+ prefs.firstDay = choices[i].value;+ }+ }+ }+ UI.SettingRow {+ Layout.fillWidth: true+ title: qsTr("Working days")+ description: qsTr("The days Work week shows")+ Row {+ spacing: 6+ Repeater {+ model: 7+ // A box per day (CalMsSettings.dc): outlined in the+ // accent when it's a working day.+ delegate: Rectangle {+ id: dayBox+ required property int index+ readonly property int day: (index + prefs.firstDay) % 7+ readonly property var days: prefs.workDays.split(",").map(Number)+ readonly property bool on: days.indexOf(day) >= 0+ width: 32+ height: 30+ radius: 6+ color: on ? UI.Style.accentSoft : dayMouse.containsMouse ? UI.Style.surfaceHover : UI.Style.surfaceControl+ border.width: on ? 1.5 : 1+ border.color: on ? UI.Style.accent : UI.Style.borderSubtle+ Accessible.role: Accessible.CheckBox+ Accessible.name: Formats.names().dayName(day)+ Accessible.checked: on+ UI.Label {+ anchors.centerIn: parent+ text: Formats.names().dayName(dayBox.day, Locale.ShortFormat).charAt(0).toUpperCase()+ size: 12+ font.weight: dayBox.on ? Font.DemiBold : Font.Normal+ color: dayBox.on ? UI.Style.ink : UI.Style.inkMuted+ }+ MouseArea {+ id: dayMouse+ anchors.fill: parent+ hoverEnabled: true+ cursorShape: Qt.PointingHandCursor+ onClicked: {+ let d = dayBox.days.slice();+ if (dayBox.on) {+ // A week needs at least one working day.+ if (d.length > 1) {+ d.splice(d.indexOf(dayBox.day), 1);+ }+ } else {+ d.push(dayBox.day);+ }+ prefs.workDays = d.sort().join(",");+ }+ }+ }+ }+ }+ }+ UI.SettingRow {+ Layout.fillWidth: true+ title: qsTr("Working hours")+ description: qsTr("Where the week opens each morning")+ RowLayout {+ spacing: 8+ UI.ComboBox {+ implicitWidth: 96+ model: page.hours+ currentIndex: Math.max(0, page.hours.findIndex(h => h.value === prefs.workStart))+ onActivated: function (i) {+ prefs.workStart = page.hours[i].value;+ }+ }+ UI.Label {+ text: qsTr("to")+ size: 13+ color: UI.Style.inkMuted+ }+ UI.ComboBox {+ implicitWidth: 96+ model: page.hours+ currentIndex: Math.max(0, page.hours.findIndex(h => h.value === prefs.workEnd))+ onActivated: function (i) {+ prefs.workEnd = page.hours[i].value;+ }+ }+ }+ }+ UI.SettingRow {+ Layout.fillWidth: true+ title: qsTr("Time zone")+ description: qsTr("This PC's time zone. Change it in Settings, Time and language.")+ UI.Label {+ text: CalendarEngine.timeZoneName+ size: 13+ }+ }+ }+ }++ // Calendar: events+ UI.Label {+ visible: page.section === "calendar"+ Layout.topMargin: 4+ text: qsTr("Events")+ size: 13+ font.weight: Font.DemiBold+ }+ UI.Card {+ visible: page.section === "calendar"+ Layout.fillWidth: true+ ColumnLayout {+ width: parent.width+ UI.SettingRow {+ Layout.fillWidth: true+ title: qsTr("Default reminder")+ UI.ComboBox {+ readonly property var choices: [+ { value: -1, text: qsTr("No reminder") },+ { value: 0, text: qsTr("When it starts") },+ { value: 5, text: qsTr("5 minutes before") },+ { value: 15, text: qsTr("15 minutes before") },+ { value: 30, text: qsTr("30 minutes before") },+ { value: 60, text: qsTr("1 hour before") }+ ]+ model: choices+ currentIndex: Math.max(0, choices.findIndex(c => c.value === prefs.defaultReminder))+ onActivated: function (i) {+ prefs.defaultReminder = choices[i].value;+ }+ }+ }+ UI.SettingRow {+ Layout.fillWidth: true+ title: qsTr("Default length")+ Row {+ spacing: 6+ UI.SegmentButton {+ text: qsTr("30 min")+ checked: prefs.defaultLength === 30+ onClicked: prefs.defaultLength = 30+ }+ UI.SegmentButton {+ text: qsTr("1 hour")+ checked: prefs.defaultLength === 60+ onClicked: prefs.defaultLength = 60+ }+ }+ }+ }+ }++ // Calendar: extra calendars+ UI.Label {+ visible: page.section === "calendar"+ Layout.topMargin: 4+ text: qsTr("Extra calendars")+ size: 13+ font.weight: Font.DemiBold+ }+ UI.Card {+ visible: page.section === "calendar"+ Layout.fillWidth: true+ ColumnLayout {+ width: parent.width+ UI.SettingRow {+ Layout.fillWidth: true+ title: qsTr("UK bank holidays")+ description: qsTr("England and Wales, from GOV.UK")+ UI.Toggle {+ checked: CalendarEngine.calendars.length >= 0 && CalendarEngine.hasHolidays()+ onToggled: CalendarEngine.setHolidays(checked)+ }+ }+ UI.SettingRow {+ Layout.fillWidth: true+ title: qsTr("Birthdays from contacts")+ description: qsTr("From the birthdays saved with your contacts")+ UI.Toggle {+ checked: CalendarEngine.calendars.length >= 0 && CalendarEngine.hasBirthdays()+ onToggled: CalendarEngine.setBirthdays(checked)+ }+ }+ }+ }+ Item {+ implicitHeight: 20+ }+ }+ }+ }++ UI.Dialog {+ id: removeAccount+ property var account: ({})+ function ask(a) {+ account = a;+ open();+ }+ title: qsTr("Remove %1?").arg(account.name)+ text: qsTr("Its calendars leave this PC. Nothing is deleted from the account itself.")+ iconName: "warning"+ buttons: [+ UI.Button {+ text: qsTr("Cancel")+ onClicked: removeAccount.close()+ },+ UI.Button {+ kind: "primary"+ danger: true+ text: qsTr("Remove")+ onClicked: {+ CalendarEngine.removeAccount(removeAccount.account.uid);+ removeAccount.close();+ }+ }+ ]+ }+}diff --git a/packages/wildos-mail/qml/CommandButton.qml b/packages/wildos-mail/qml/CommandButton.qmlnew file mode 100644index 0000000..1f17cce--- /dev/null+++ b/packages/wildos-mail/qml/CommandButton.qml@@ -0,0 +1,62 @@+import QtQuick+import QtQuick.Templates as T+import WildOS.UI as UI++// A button in Mail's command bar (MailMicrosoft.dc): 34px, icon and label+// in 13px ink, no fill until hovered. Set `menu` to open it on click.+T.AbstractButton {+ id: control++ property string iconName+ property bool iconOnly: false+ property string tip: text+ property UI.Menu menu: null++ implicitHeight: 34+ implicitWidth: iconOnly ? 34 : row.implicitWidth + 20+ hoverEnabled: true+ focusPolicy: Qt.TabFocus+ opacity: enabled ? 1 : 0.45+ Accessible.name: tip++ onClicked: if (menu) menu.popup(control, 0, control.height + 4)++ background: Rectangle {+ radius: control.iconOnly ? UI.Style.radiusSm : 6+ color: control.down ? UI.Style.surfacePressed : control.hovered ? UI.Style.surfaceHover : "transparent"+ UI.FocusRing {+ visible: control.visualFocus+ targetRadius: parent.radius+ }+ }++ contentItem: Item {+ Row {+ id: row+ anchors.centerIn: parent+ spacing: 7++ MailIcon {+ anchors.verticalCenter: parent.verticalCenter+ name: control.iconName+ size: 17+ color: UI.Style.accent+ visible: control.iconName.length > 0+ }++ Text {+ anchors.verticalCenter: parent.verticalCenter+ visible: !control.iconOnly+ text: control.text+ color: UI.Style.ink+ font.family: UI.Style.fontFamily+ font.pixelSize: UI.Style.px(13)+ }+ }+ }++ UI.Tooltip {+ visible: control.iconOnly && control.hovered && control.tip.length > 0+ text: control.tip+ }+}diff --git a/packages/wildos-mail/qml/ComposePane.qml b/packages/wildos-mail/qml/ComposePane.qmlnew file mode 100644index 0000000..9af0264--- /dev/null+++ b/packages/wildos-mail/qml/ComposePane.qml@@ -0,0 +1,470 @@+import QtQuick+import QtQuick.Controls as QQC+import QtQuick.Dialogs+import QtQuick.Layouts+import WildOS.Mail+import WildOS.UI as UI++// Writing a message, in the reading pane's place (MailMsCompose.dc): Send+// and Discard, From, To, Cc and Bcc, Subject, the words, the message being+// answered under them, and the photo-location promise at the bottom.+Rectangle {+ id: pane++ readonly property alias composer: composer+ readonly property alias formatter: formatter+ property bool showCc: false+ property bool showBcc: false++ signal closed()+ signal problem(string text)+ signal sentMessage()++ radius: 10+ color: UI.Style.surfaceRest+ border.width: 1+ border.color: UI.Style.borderSubtle+ clip: true++ // True while start() fills the fields, so filling them isn't taken for+ // writing and no empty draft is saved.+ property bool filling: false++ function start(data) {+ filling = true;+ composer.start(data || {});+ to.setText(composer.to);+ cc.setText(composer.cc);+ bcc.setText("");+ showCc = composer.cc.length > 0;+ showBcc = false;+ subject.text = composer.subject;+ editor.text = "";+ if (data && data.body) {+ editor.text = data.body;+ } else if (composer.bodyText.length > 0) {+ editor.text = composer.bodyText.replace(/&/g, "&").replace(/</g, "<").replace(/\n/g, "<br>");+ }+ filling = false;+ if (to.people.length === 0) {+ to.forceActiveFocus();+ } else {+ editor.forceActiveFocus();+ editor.cursorPosition = 0;+ }+ }+ function sync() {+ composer.to = to.text;+ composer.cc = cc.text;+ composer.bcc = bcc.text;+ composer.subject = subject.text;+ composer.bodyHtml = formatter.html();+ composer.bodyText = formatter.plainText();+ }+ function send() {+ sync();+ if (composer.send()) {+ pane.sentMessage();+ pane.closed();+ }+ }+ function attach() {+ fileDialog.open();+ }++ Composer {+ id: composer+ onProblem: function (text) {+ pane.problem(text);+ }+ }++ Formatter {+ id: formatter+ document: editor.textDocument+ selectionStart: editor.selectionStart+ selectionEnd: editor.selectionEnd+ cursorPosition: editor.cursorPosition+ }++ FileDialog {+ id: fileDialog+ title: qsTr("Attach files")+ fileMode: FileDialog.OpenFiles+ onAccepted: {+ for (const f of selectedFiles) {+ composer.addAttachment(f);+ }+ }+ }++ ColumnLayout {+ anchors.fill: parent+ spacing: 0++ ColumnLayout {+ Layout.fillWidth: true+ Layout.leftMargin: 22+ Layout.rightMargin: 22+ Layout.topMargin: 12+ spacing: 0++ RowLayout {+ Layout.fillWidth: true+ Layout.bottomMargin: 10+ spacing: 8++ UI.Button {+ kind: "primary"+ size: "small"+ text: qsTr("Send")+ iconName: "send"+ busy: composer.sending+ onClicked: pane.send()+ }+ UI.Button {+ size: "small"+ text: qsTr("Discard")+ iconName: "delete"+ onClicked: {+ composer.discard();+ pane.closed();+ }+ }+ Item {+ Layout.fillWidth: true+ }+ UI.Label {+ visible: composer.savedAt.length > 0+ text: qsTr("Draft saved at %1").arg(composer.savedAt)+ size: 12+ color: UI.Style.inkMuted+ }+ }++ // From, with a choice when there is more than one account.+ Item {+ Layout.fillWidth: true+ implicitHeight: 40++ Rectangle {+ anchors.left: parent.left+ anchors.right: parent.right+ anchors.bottom: parent.bottom+ height: 1+ color: UI.Style.borderSubtle+ }+ UI.Label {+ x: 4+ width: 56+ anchors.verticalCenter: parent.verticalCenter+ text: qsTr("From")+ size: 13+ color: UI.Style.inkMuted+ }+ MouseArea {+ id: fromArea+ x: 70+ width: fromRow.implicitWidth + 8+ height: parent.height+ enabled: MailEngine.accounts.length > 1+ cursorShape: enabled ? Qt.PointingHandCursor : Qt.ArrowCursor+ onClicked: fromMenu.popup(fromArea, 0, fromArea.height)++ Row {+ id: fromRow+ anchors.verticalCenter: parent.verticalCenter+ spacing: 6+ UI.Label {+ readonly property var account: MailEngine.account(composer.accountId)+ text: account.fullName ? qsTr("%1 (%2)").arg(account.fullName).arg(account.name) : (account.email || "")+ size: 13+ }+ MailIcon {+ visible: fromArea.enabled+ anchors.verticalCenter: parent.verticalCenter+ name: "chevron-down"+ size: 13+ color: UI.Style.inkMuted+ }+ }+ }+ UI.Menu {+ id: fromMenu+ entries: MailEngine.accounts.map(a => ({ text: a.fullName ? a.fullName + " <" + a.email + ">" : a.email, radio: true, checked: a.id === composer.accountId, run: () => { composer.accountId = a.id; composer.touch(); } }))+ }+ }++ RecipientField {+ id: to+ Layout.fillWidth: true+ label: qsTr("To")+ next: pane.showCc ? cc : pane.showBcc ? bcc : subject+ onEdited: composer.touch()++ UI.LinkButton {+ visible: !pane.showCc+ text: qsTr("Cc")+ onClicked: {+ pane.showCc = true;+ cc.forceActiveFocus();+ }+ }+ UI.LinkButton {+ visible: !pane.showBcc+ text: qsTr("Bcc")+ onClicked: {+ pane.showBcc = true;+ bcc.forceActiveFocus();+ }+ }+ }+ RecipientField {+ id: cc+ visible: pane.showCc+ Layout.fillWidth: true+ label: qsTr("Cc")+ next: pane.showBcc ? bcc : subject+ onEdited: composer.touch()+ }+ RecipientField {+ id: bcc+ visible: pane.showBcc+ Layout.fillWidth: true+ label: qsTr("Bcc")+ next: subject+ onEdited: composer.touch()+ }++ Item {+ Layout.fillWidth: true+ implicitHeight: 40++ Rectangle {+ anchors.left: parent.left+ anchors.right: parent.right+ anchors.bottom: parent.bottom+ height: 1+ color: UI.Style.borderSubtle+ }+ UI.Label {+ x: 4+ width: 56+ anchors.verticalCenter: parent.verticalCenter+ text: qsTr("Subject")+ size: 13+ color: UI.Style.inkMuted+ }+ TextInput {+ id: subject+ x: 70+ width: parent.width - 74+ anchors.verticalCenter: parent.verticalCenter+ color: UI.Style.ink+ selectionColor: UI.Style.accentSelected+ font.family: UI.Style.fontFamily+ font.pixelSize: UI.Style.px(14)+ font.weight: Font.Medium+ clip: true+ onTextEdited: composer.touch()+ KeyNavigation.tab: editor+ }+ }+ }++ Flow {+ visible: composer.attachments.length > 0+ Layout.fillWidth: true+ Layout.leftMargin: 22+ Layout.rightMargin: 22+ Layout.topMargin: 10+ spacing: 8++ Repeater {+ model: composer.attachments+ delegate: Rectangle {+ id: att+ required property var modelData+ width: 220+ height: 44+ radius: 6+ color: "transparent"+ border.width: 1+ border.color: UI.Style.borderSubtle++ RowLayout {+ anchors.fill: parent+ anchors.leftMargin: 10+ anchors.rightMargin: 6+ spacing: 8+ MailIcon {+ name: att.modelData.type.startsWith("image/") ? "picture" : "paperclip"+ size: 16+ color: UI.Style.accent+ }+ ColumnLayout {+ Layout.fillWidth: true+ spacing: 0+ UI.Label {+ Layout.fillWidth: true+ text: att.modelData.name+ size: 12.5+ elide: Text.ElideMiddle+ }+ UI.Label {+ text: att.modelData.photo ? qsTr("%1, location removed").arg(att.modelData.size)+ : att.modelData.uncleaned ? qsTr("%1, location couldn't be removed").arg(att.modelData.size) : att.modelData.size+ size: 11+ color: att.modelData.uncleaned ? UI.Style.warning : UI.Style.inkMuted+ }+ }+ UI.IconButton {+ iconName: "close"+ iconSize: 12+ tip: qsTr("Remove")+ implicitWidth: 26+ implicitHeight: 26+ onClicked: composer.removeAttachment(att.modelData.index)+ }+ }+ }+ }+ }++ QQC.ScrollView {+ Layout.fillWidth: true+ Layout.fillHeight: true+ Layout.topMargin: 8+ clip: true+ QQC.ScrollBar.vertical: UI.ScrollBar {}++ ColumnLayout {+ width: pane.width+ spacing: 0++ QQC.TextArea {+ id: editor+ Layout.fillWidth: true+ Layout.maximumWidth: 660+ Layout.minimumHeight: 100+ leftPadding: 26+ rightPadding: 26+ topPadding: 10+ textFormat: TextEdit.RichText+ wrapMode: TextEdit.Wrap+ color: UI.Style.ink+ selectionColor: UI.Style.accentSelected+ selectedTextColor: UI.Style.ink+ font.family: UI.Style.fontFamily+ font.pixelSize: UI.Style.px(14.5)+ font.weight: Font.Normal+ placeholderText: qsTr("Write your message")+ placeholderTextColor: UI.Style.inkPlaceholder+ background: null+ onTextChanged: if (!pane.filling) composer.touch()+ onLinkActivated: function (link) {+ Qt.openUrlExternally(link);+ }+ Keys.onPressed: function (event) {+ if ((event.modifiers & Qt.ControlModifier) && (event.key === Qt.Key_Return || event.key === Qt.Key_Enter)) {+ pane.send();+ event.accepted = true;+ } else if ((event.modifiers & Qt.ControlModifier) && event.key === Qt.Key_B) {+ formatter.toggleBold();+ event.accepted = true;+ } else if ((event.modifiers & Qt.ControlModifier) && event.key === Qt.Key_I) {+ formatter.toggleItalic();+ event.accepted = true;+ } else if ((event.modifiers & Qt.ControlModifier) && event.key === Qt.Key_U) {+ formatter.toggleUnderline();+ event.accepted = true;+ }+ }+ }++ // The message being answered, under the reply.+ ColumnLayout {+ visible: composer.quote.length > 0+ Layout.fillWidth: true+ Layout.leftMargin: 26+ Layout.rightMargin: 26+ Layout.topMargin: 6+ Layout.bottomMargin: 16+ spacing: 3++ Rectangle {+ Layout.fillWidth: true+ implicitHeight: quoteColumn.implicitHeight+ color: "transparent"++ Rectangle {+ width: 2+ height: parent.height+ color: UI.Style.borderSubtle+ }+ ColumnLayout {+ id: quoteColumn+ x: 12+ width: parent.width - 12+ spacing: 3+ UI.Label {+ Layout.fillWidth: true+ text: composer.quoteHeader+ size: 12+ color: UI.Style.inkMuted+ wrapMode: Text.WordWrap+ }+ UI.Label {+ id: quoteText+ property bool expanded: false+ Layout.fillWidth: true+ text: composer.quote+ size: 13+ color: UI.Style.inkMuted+ wrapMode: Text.WordWrap+ maximumLineCount: expanded ? 100000 : 2+ elide: Text.ElideRight+ MouseArea {+ anchors.fill: parent+ cursorShape: Qt.PointingHandCursor+ onClicked: quoteText.expanded = !quoteText.expanded+ }+ }+ }+ }+ }+ }+ }++ Rectangle {+ Layout.fillWidth: true+ Layout.leftMargin: 14+ Layout.rightMargin: 14+ Layout.bottomMargin: 14+ implicitHeight: promise.implicitHeight + 20+ radius: 8+ color: UI.Style.successSoft+ border.width: 1+ border.color: Qt.alpha(UI.Style.success, 0.25)++ RowLayout {+ id: promise+ anchors.fill: parent+ anchors.leftMargin: 12+ anchors.rightMargin: 12+ spacing: 10+ MailIcon {+ name: "shield-check"+ size: 16+ color: UI.Style.success+ }+ UI.Label {+ Layout.fillWidth: true+ text: qsTr("Photos you attach have their location removed before sending.")+ size: 12.5+ wrapMode: Text.WordWrap+ }+ }+ }+ }+}diff --git a/packages/wildos-mail/qml/EventEditor.qml b/packages/wildos-mail/qml/EventEditor.qmlnew file mode 100644index 0000000..28a9287--- /dev/null+++ b/packages/wildos-mail/qml/EventEditor.qml@@ -0,0 +1,663 @@+import QtCore+import QtQuick+import QtQuick.Controls as QQC+import QtQuick.Layouts+import WildOS.Mail+import WildOS.UI as UI+import "Formats.js" as Formats++// A new event or one being changed (CalMsNew.dc), in place of the days: the+// title, who's invited, when, how often, where, the reminder, the calendar+// and notes, with the chosen day beside the form so a clash shows before+// saving.+Rectangle {+ id: editor++ // The event being changed, from CalendarEngine.event(); empty for a new one.+ property var original: ({})+ property string calendarUid+ property date startTime: new Date()+ property date endTime: new Date()+ property bool allDay: false+ property bool busy: true+ property bool isPrivate: false+ property string repeat: "none"+ property int reminder: 15+ property var dayEvents: []+ property date shownDay: startTime++ signal closed()++ readonly property bool editing: original.key !== undefined+ readonly property bool repeatOfSeries: editing && original.recurring === true++ function start(event, defaults) {+ original = event || {};+ const now = new Date();+ if (editing) {+ title.text = original.title === qsTr("(No title)") ? "" : original.title;+ people.people = (original.people || []).filter(p => !p.me).map(p => p.name ? p.name + " <" + p.email + ">" : p.email);+ location.text = original.location || "";+ notes.text = original.description || "";+ calendarUid = original.calendarUid;+ allDay = original.allDay === true;+ startTime = new Date(original.start);+ endTime = allDay ? new Date(new Date(original.end).getTime() - 86400000) : new Date(original.end);+ busy = original.busy !== false;+ isPrivate = original.private === true;+ repeat = original.repeat || "none";+ reminder = original.reminder === undefined ? -1 : original.reminder;+ } else {+ title.text = "";+ people.setText((defaults && defaults.attendees) ? defaults.attendees.join(", ") : "");+ location.text = "";+ notes.text = "";+ calendarUid = CalendarEngine.defaultCalendar;+ allDay = defaults && defaults.allDay === true;+ const s = defaults && defaults.start ? new Date(defaults.start) : new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours() + 1);+ startTime = s;+ endTime = allDay ? s : new Date(s.getTime() + prefs.defaultLength * 60000);+ busy = true;+ isPrivate = false;+ repeat = "none";+ reminder = allDay ? -1 : prefs.defaultReminder;+ }+ shownDay = startTime;+ title.forceActiveFocus();+ }+ function save(wholeSeries) {+ const s = startTime;+ let e = endTime;+ if (!allDay && e <= s) {+ e = new Date(s.getTime() + 30 * 60000);+ }+ CalendarEngine.saveEvent({+ key: original.key || "",+ calendarUid: calendarUid,+ title: title.text.trim().length > 0 ? title.text.trim() : qsTr("(No title)"),+ start: s,+ end: e,+ allDay: allDay,+ location: location.text,+ description: notes.text,+ reminder: reminder,+ repeat: repeat,+ attendees: people.people.concat(people.text.length > 0 && people.people.length === 0 ? [people.text] : []).map(a => people.addressOf(a)),+ busy: busy,+ private: isPrivate,+ wholeSeries: wholeSeries+ });+ closed();+ }+ function withDate(day, time) {+ return new Date(day.getFullYear(), day.getMonth(), day.getDate(), time.getHours(), time.getMinutes());+ }+ function timeChoices(from) {+ const list = [];+ for (let m = 0; m < 24 * 60; m += 15) {+ const h = Math.floor(m / 60);+ const t = (h < 10 ? "0" : "") + h + ":" + (m % 60 === 0 ? "00" : m % 60);+ list.push({ value: m, text: t });+ }+ return list;+ }+ readonly property var times: timeChoices()+ function minutesOf(d) {+ return d.getHours() * 60 + d.getMinutes();+ }+ function indexFor(d) {+ const m = minutesOf(d);+ return Math.min(times.length - 1, Math.round(m / 15));+ }++ onShownDayChanged: CalendarEngine.loadDay(shownDay)+ Connections {+ target: CalendarEngine+ function onDayLoaded(day, events) {+ if (day.getFullYear() === editor.shownDay.getFullYear() && day.getMonth() === editor.shownDay.getMonth() && day.getDate() === editor.shownDay.getDate()) {+ editor.dayEvents = events.filter(e => e.key !== editor.original.key);+ }+ }+ }++ radius: 10+ color: UI.Style.surfaceRest+ border.width: 1+ border.color: UI.Style.borderSubtle+ clip: true++ Settings {+ id: prefs+ category: "calendar"+ property int defaultLength: 60+ property int defaultReminder: 15+ }++ ColumnLayout {+ anchors.fill: parent+ spacing: 0++ // Save, Discard, Busy, Repeat, Private.+ RowLayout {+ Layout.fillWidth: true+ Layout.margins: 14+ spacing: 6+ UI.Button {+ id: saveButton+ kind: "primary"+ size: "small"+ text: qsTr("Save")+ iconName: "check"+ onClicked: editor.repeatOfSeries ? seriesMenu.popup(saveButton, 0, saveButton.height + 4) : editor.save(true)+ }+ UI.Button {+ size: "small"+ text: qsTr("Discard")+ iconName: "trash"+ onClicked: editor.closed()+ }+ Rectangle {+ implicitWidth: 1+ implicitHeight: 22+ Layout.leftMargin: 6+ Layout.rightMargin: 6+ color: UI.Style.borderSubtle+ }+ CommandButton {+ text: editor.busy ? qsTr("Busy") : qsTr("Free")+ iconName: "clock"+ tip: qsTr("Whether this time shows as busy to people who can see your calendar")+ onClicked: editor.busy = !editor.busy+ }+ CommandButton {+ id: repeatButton+ text: qsTr("Repeat")+ iconName: "repeat"+ onClicked: repeatMenu.popup(repeatButton, 0, repeatButton.height + 4)+ }+ CommandButton {+ text: editor.isPrivate ? qsTr("Private") : qsTr("Not private")+ iconName: "lock"+ tip: qsTr("Private events show only as busy to people you share this calendar with")+ onClicked: editor.isPrivate = !editor.isPrivate+ }+ Item {+ Layout.fillWidth: true+ }+ UI.IconButton {+ iconName: "close"+ tip: qsTr("Close")+ onClicked: editor.closed()+ }+ }+ Rectangle {+ Layout.fillWidth: true+ implicitHeight: 1+ color: UI.Style.borderSubtle+ }++ RowLayout {+ Layout.fillWidth: true+ Layout.fillHeight: true+ spacing: 0++ // The form.+ ColumnLayout {+ Layout.fillWidth: true+ Layout.fillHeight: true+ Layout.margins: 24+ spacing: 14++ QQC.TextField {+ id: title+ Layout.fillWidth: true+ placeholderText: qsTr("Add a title")+ placeholderTextColor: UI.Style.inkPlaceholder+ color: UI.Style.ink+ font.family: UI.Style.fontFamily+ font.pixelSize: UI.Style.px(20)+ font.weight: Font.DemiBold+ leftPadding: 0+ bottomPadding: 10+ background: Rectangle {+ anchors.bottom: parent.bottom+ width: parent.width+ height: title.activeFocus ? 2 : 1+ color: title.activeFocus ? UI.Style.accent : UI.Style.borderSubtle+ }+ Keys.onReturnPressed: editor.save(true)+ }++ component FormRow: RowLayout {+ id: formRow+ property string icon+ default property alias content: holder.data+ Layout.fillWidth: true+ spacing: 14+ MailIcon {+ Layout.alignment: Qt.AlignVCenter+ name: formRow.icon+ size: 17+ color: UI.Style.iconMuted+ }+ RowLayout {+ id: holder+ Layout.fillWidth: true+ spacing: 10+ }+ }++ FormRow {+ icon: "people"+ RecipientField {+ id: people+ Layout.fillWidth: true+ label: ""+ placeholder: qsTr("Invite people")+ }+ }+ // A calendar on this PC has nobody to send invitations as.+ UI.Label {+ readonly property var calendar: CalendarEngine.calendars.find(c => c.uid === editor.calendarUid) || {}+ visible: (people.people.length > 0 || people.text.length > 0) && !calendar.email+ Layout.fillWidth: true+ Layout.leftMargin: 31+ Layout.topMargin: -8+ text: qsTr("Only Google and CalDAV calendars send invitations. On this calendar the people are noted on the event but not told.")+ size: 12+ color: UI.Style.inkMuted+ wrapMode: Text.WordWrap+ }++ FormRow {+ icon: "clock"+ QQC.Button {+ id: dateButton+ implicitWidth: 180+ implicitHeight: 36+ onClicked: datePopup.open()+ background: Rectangle {+ radius: 6+ color: dateButton.hovered ? UI.Style.surfaceHover : UI.Style.surfaceControl+ border.width: 1+ border.color: UI.Style.borderField+ }+ contentItem: RowLayout {+ UI.Label {+ Layout.fillWidth: true+ leftPadding: 4+ text: Formats.dayAndShortDate(editor.startTime)+ size: 13+ }+ MailIcon {+ name: "chevron-down"+ size: 12+ color: UI.Style.iconMuted+ }+ }+ QQC.Popup {+ id: datePopup+ y: parent.height + 4+ width: 260+ padding: 12+ background: Rectangle {+ radius: 10+ color: UI.Style.glassMenu+ border.width: 1+ border.color: UI.Style.borderContextMenu+ }+ contentItem: MiniMonth {+ month: new Date(editor.startTime.getFullYear(), editor.startTime.getMonth(), 1)+ rangeFrom: new Date(editor.startTime.getFullYear(), editor.startTime.getMonth(), editor.startTime.getDate())+ rangeTo: new Date(editor.startTime.getFullYear(), editor.startTime.getMonth(), editor.startTime.getDate() + 1)+ onPicked: function (day) {+ const length = editor.endTime - editor.startTime;+ editor.startTime = editor.withDate(day, editor.startTime);+ editor.endTime = new Date(editor.startTime.getTime() + length);+ editor.shownDay = day;+ datePopup.close();+ }+ }+ }+ }+ UI.ComboBox {+ visible: !editor.allDay+ implicitWidth: 96+ model: editor.times+ currentIndex: editor.indexFor(editor.startTime)+ onActivated: function (i) {+ const length = editor.endTime - editor.startTime;+ const m = editor.times[i].value;+ const s = editor.startTime;+ editor.startTime = new Date(s.getFullYear(), s.getMonth(), s.getDate(), Math.floor(m / 60), m % 60);+ editor.endTime = new Date(editor.startTime.getTime() + length);+ }+ }+ UI.Label {+ visible: !editor.allDay+ text: qsTr("to")+ size: 13+ color: UI.Style.inkMuted+ }+ UI.ComboBox {+ visible: !editor.allDay+ implicitWidth: 96+ model: editor.times+ currentIndex: editor.indexFor(editor.endTime)+ onActivated: function (i) {+ const m = editor.times[i].value;+ const s = editor.startTime;+ let e = new Date(s.getFullYear(), s.getMonth(), s.getDate(), Math.floor(m / 60), m % 60);+ // Past midnight means the next day.+ if (e <= s) {+ e = new Date(e.getTime() + 86400000);+ }+ editor.endTime = e;+ }+ }+ UI.Toggle {+ Layout.leftMargin: 8+ checked: editor.allDay+ onToggled: {+ editor.allDay = checked;+ if (!checked && editor.endTime <= editor.startTime) {+ const s = editor.startTime;+ editor.startTime = new Date(s.getFullYear(), s.getMonth(), s.getDate(), 9, 0);+ editor.endTime = new Date(editor.startTime.getTime() + prefs.defaultLength * 60000);+ }+ }+ }+ UI.Label {+ text: qsTr("All day")+ size: 13+ }+ Item {+ Layout.fillWidth: true+ }+ }++ FormRow {+ icon: "repeat"+ UI.ComboBox {+ id: repeatBox+ implicitWidth: 220+ readonly property var choices: [+ { value: "none", text: qsTr("Doesn't repeat") },+ { value: "daily", text: qsTr("Every day") },+ { value: "weekdays", text: qsTr("Every weekday") },+ { value: "weekly", text: qsTr("Every week on %1").arg(Formats.names().toString(editor.startTime, "dddd")) },+ { value: "monthly", text: qsTr("Every month on the %1").arg(editor.startTime.getDate()) },+ { value: "yearly", text: qsTr("Every year on %1").arg(Formats.dayAndMonth(editor.startTime)) }+ ].concat(editor.repeat === "other" ? [{ value: "other", text: qsTr("As set in another app") }] : [])+ model: choices+ currentIndex: Math.max(0, choices.findIndex(c => c.value === editor.repeat))+ onActivated: function (i) {+ editor.repeat = choices[i].value;+ }+ }+ Item {+ Layout.fillWidth: true+ }+ }++ FormRow {+ icon: "location"+ UI.TextField {+ id: location+ Layout.fillWidth: true+ placeholderText: qsTr("Add a place")+ }+ }++ FormRow {+ icon: "bell"+ UI.ComboBox {+ implicitWidth: 200+ readonly property var choices: [+ { value: -1, text: qsTr("No reminder") },+ { value: 0, text: qsTr("When it starts") },+ { value: 5, text: qsTr("5 minutes before") },+ { value: 15, text: qsTr("15 minutes before") },+ { value: 30, text: qsTr("30 minutes before") },+ { value: 60, text: qsTr("1 hour before") },+ { value: 120, text: qsTr("2 hours before") },+ { value: 1440, text: qsTr("1 day before") },+ { value: 10080, text: qsTr("1 week before") }+ ]+ model: choices+ currentIndex: Math.max(0, choices.findIndex(c => c.value === editor.reminder))+ onActivated: function (i) {+ editor.reminder = choices[i].value;+ }+ }+ UI.ComboBox {+ id: calendarBox+ implicitWidth: 220+ readonly property var choices: CalendarEngine.calendars.filter(c => !c.readOnly).map(c => ({ value: c.uid, text: c.name + (c.groupUid ? " · " + c.group : ""), color: c.color }))+ model: choices+ currentIndex: Math.max(0, choices.findIndex(c => c.value === editor.calendarUid))+ onActivated: function (i) {+ editor.calendarUid = choices[i].value;+ }+ }+ Item {+ Layout.fillWidth: true+ }+ }++ FormRow {+ icon: "notes"+ Layout.fillHeight: true+ QQC.ScrollView {+ Layout.fillWidth: true+ Layout.fillHeight: true+ Layout.minimumHeight: 90+ QQC.TextArea {+ id: notes+ wrapMode: TextEdit.Wrap+ color: UI.Style.ink+ font.family: UI.Style.fontFamily+ font.pixelSize: UI.Style.px(13)+ placeholderText: qsTr("Add notes")+ placeholderTextColor: UI.Style.inkPlaceholder+ padding: 12+ background: Rectangle {+ radius: 6+ color: UI.Style.surfaceSunken+ border.width: 1+ border.color: notes.activeFocus ? UI.Style.accent : UI.Style.borderField+ }+ }+ }+ }+ }++ Rectangle {+ Layout.fillHeight: true+ implicitWidth: 1+ color: UI.Style.borderSubtle+ }++ // The day, with this event drawn among the others.+ ColumnLayout {+ Layout.preferredWidth: 300+ Layout.fillHeight: true+ Layout.margins: 12+ spacing: 8++ RowLayout {+ Layout.fillWidth: true+ UI.IconButton {+ iconName: "chevron-left"+ tip: qsTr("Previous day")+ onClicked: editor.shownDay = new Date(editor.shownDay.getFullYear(), editor.shownDay.getMonth(), editor.shownDay.getDate() - 1)+ }+ UI.Label {+ Layout.fillWidth: true+ horizontalAlignment: Text.AlignHCenter+ text: Formats.weekdayAndDay(editor.shownDay)+ size: 13+ font.weight: Font.DemiBold+ }+ UI.IconButton {+ iconName: "chevron-right"+ tip: qsTr("Next day")+ onClicked: editor.shownDay = new Date(editor.shownDay.getFullYear(), editor.shownDay.getMonth(), editor.shownDay.getDate() + 1)+ }+ }++ // A clash, or none.+ Rectangle {+ id: clashBar+ readonly property bool sameDay: editor.shownDay.toDateString() === editor.startTime.toDateString()+ readonly property var clashes: {+ if (!sameDay || editor.allDay) {+ return [];+ }+ const s = editor.minutesOf(editor.startTime);+ const e = s + (editor.endTime - editor.startTime) / 60000;+ return editor.dayEvents.filter(x => !x.allDay && x.busy && x.startMinute < e && x.endMinute > s);+ }+ visible: sameDay && !editor.allDay+ Layout.fillWidth: true+ implicitHeight: 32+ radius: 6+ color: clashes.length > 0 ? UI.Style.warningSoft : UI.Style.successSoft+ RowLayout {+ anchors.fill: parent+ anchors.leftMargin: 10+ anchors.rightMargin: 10+ spacing: 8+ MailIcon {+ name: clashBar.clashes.length > 0 ? "clock" : "check"+ size: 14+ color: clashBar.clashes.length > 0 ? UI.Style.warning : UI.Style.success+ }+ UI.Label {+ Layout.fillWidth: true+ text: clashBar.clashes.length > 0 ? qsTr("Overlaps %1").arg(clashBar.clashes[0].title) : qsTr("You're free at this time")+ size: 12+ elide: Text.ElideRight+ }+ }+ }++ Flickable {+ id: dayHours+ Layout.fillWidth: true+ Layout.fillHeight: true+ clip: true+ readonly property real hour: 50+ contentHeight: 24 * hour+ contentY: Math.max(0, Math.min(contentHeight - height, (editor.allDay ? 8 : editor.startTime.getHours() - 1) * hour))+ boundsBehavior: Flickable.StopAtBounds++ Repeater {+ model: 24+ delegate: Item {+ required property int index+ y: index * dayHours.hour+ width: dayHours.width+ height: dayHours.hour+ UI.Label {+ width: 40+ y: -6+ visible: index > 0+ text: (index < 10 ? "0" : "") + index + ":00"+ size: 11+ color: UI.Style.inkSubtle+ }+ Rectangle {+ x: 46+ width: parent.width - 46+ height: 1+ color: UI.Style.borderSubtle+ }+ }+ }+ Repeater {+ model: editor.dayEvents.filter(e => !e.allDay)+ delegate: Rectangle {+ required property var modelData+ x: 50+ y: modelData.startMinute / 60 * dayHours.hour + 1+ width: dayHours.width - 54+ height: Math.max(18, (modelData.endMinute - modelData.startMinute) / 60 * dayHours.hour - 3)+ radius: 4+ color: Qt.rgba(Qt.color(modelData.color).r, Qt.color(modelData.color).g, Qt.color(modelData.color).b, 0.36)+ clip: true+ Rectangle {+ width: 3+ height: parent.height+ color: modelData.color+ }+ Column {+ x: 9+ y: 3+ UI.Label {+ text: modelData.title+ size: 12+ font.weight: Font.DemiBold+ }+ UI.Label {+ text: modelData.rangeText+ size: 11+ color: UI.Style.inkMuted+ }+ }+ }+ }+ // This event, dashed.+ Rectangle {+ visible: clashBar.sameDay && !editor.allDay+ x: 50+ y: editor.minutesOf(editor.startTime) / 60 * dayHours.hour + 1+ width: dayHours.width - 54+ height: Math.max(18, (editor.endTime - editor.startTime) / 3600000 * dayHours.hour - 3)+ radius: 4+ color: UI.Style.accentSoft+ border.width: 1.5+ border.color: UI.Style.accent+ Column {+ x: 9+ y: 3+ UI.Label {+ text: title.text.length > 0 ? title.text : qsTr("New event")+ size: 12+ font.weight: Font.DemiBold+ }+ UI.Label {+ text: qsTr("%1 to %2").arg(Formats.time(editor.startTime)).arg(Formats.time(editor.endTime))+ size: 11+ color: UI.Style.inkMuted+ }+ }+ }+ }+ }+ }+ }++ UI.Menu {+ id: repeatMenu+ entries: repeatBox.choices.map(c => ({ text: c.text, checked: c.value === editor.repeat, run: () => { editor.repeat = c.value; } }))+ }+ UI.Menu {+ id: seriesMenu+ entries: [+ { text: qsTr("Save this one only"), run: () => editor.save(false) },+ { text: qsTr("Save the whole series"), run: () => editor.save(true) }+ ]+ }++ Shortcut {+ sequence: "Ctrl+S"+ enabled: editor.visible+ onActivated: editor.save(true)+ }+ Shortcut {+ sequence: "Escape"+ enabled: editor.visible+ onActivated: editor.closed()+ }+}diff --git a/packages/wildos-mail/qml/EventPeek.qml b/packages/wildos-mail/qml/EventPeek.qmlnew file mode 100644index 0000000..d3bbbd0--- /dev/null+++ b/packages/wildos-mail/qml/EventPeek.qml@@ -0,0 +1,352 @@+import QtQuick+import QtQuick.Controls as QQC+import QtQuick.Layouts+import WildOS.Mail+import WildOS.UI as UI+import "Formats.js" as Formats++// The card an event opens (CalMsEvent.dc): when and where, your answer if+// someone invited you, the reminder, the calendar, the notes and who's+// going, with Edit, Delete and Message everyone.+QQC.Popup {+ id: peek++ property var event: ({})+ property string calendarName+ readonly property bool has: event.key !== undefined++ signal editRequested(var event)+ signal messageEveryone(var addresses, string subject)++ function show(key, anchor) {+ const e = CalendarEngine.event(key);+ if (!e.key) {+ return;+ }+ event = e;+ const cal = CalendarEngine.calendars.find(c => c.uid === e.calendarUid);+ calendarName = cal ? cal.name : "";+ // Beside the event, on whichever side has room.+ const p = anchor.mapToItem(parent, 0, 0);+ const right = p.x + anchor.width + 12;+ x = right + width < parent.width - 8 ? right : Math.max(8, p.x - width - 12);+ y = Math.max(8, Math.min(parent.height - implicitHeight - 8, p.y - 40));+ open();+ }+ function dateText(e) {+ if (!e.start) {+ return "";+ }+ const s = new Date(e.start);+ const en = new Date(e.end);+ const day = Formats.dayAndShortDate(s);+ if (e.allDay) {+ const last = new Date(en.getFullYear(), en.getMonth(), en.getDate() - 1);+ return last > s ? qsTr("%1 to %2").arg(day).arg(Formats.dayAndShortDate(last)) : qsTr("%1, all day").arg(day);+ }+ return qsTr("%1, %2 to %3").arg(day).arg(Formats.time(s)).arg(Formats.time(en));+ }+ function reminderText(minutes) {+ if (minutes < 0) {+ return qsTr("No reminder");+ }+ if (minutes === 0) {+ return qsTr("Reminder when it starts");+ }+ if (minutes % 1440 === 0) {+ return minutes === 1440 ? qsTr("Reminder 1 day before") : minutes === 10080 ? qsTr("Reminder 1 week before") : qsTr("Reminder %1 days before").arg(minutes / 1440);+ }+ if (minutes % 60 === 0) {+ return minutes === 60 ? qsTr("Reminder 1 hour before") : qsTr("Reminder %1 hours before").arg(minutes / 60);+ }+ return minutes === 1 ? qsTr("Reminder 1 minute before") : qsTr("Reminder %1 minutes before").arg(minutes);+ }+ function statusText(s) {+ return s === "organiser" ? qsTr("Organiser") : s === "going" ? qsTr("Going") : s === "maybe" ? qsTr("Maybe")+ : s === "notGoing" ? qsTr("Not going") : qsTr("Not replied yet");+ }++ width: 384+ padding: 0+ modal: false+ focus: true+ closePolicy: QQC.Popup.CloseOnEscape | QQC.Popup.CloseOnPressOutside++ background: Rectangle {+ radius: 10+ color: UI.Style.glassMenu+ border.width: 1+ border.color: UI.Style.borderContextMenu+ Rectangle {+ width: parent.width+ height: 3+ topLeftRadius: 10+ topRightRadius: 10+ color: peek.event.color || UI.Style.accent+ }+ }++ contentItem: ColumnLayout {+ spacing: 12++ RowLayout {+ Layout.fillWidth: true+ Layout.topMargin: 18+ Layout.leftMargin: 16+ Layout.rightMargin: 10+ spacing: 2+ ColumnLayout {+ Layout.fillWidth: true+ spacing: 2+ UI.Label {+ Layout.fillWidth: true+ text: peek.event.title || ""+ size: 18+ font.weight: Font.DemiBold+ wrapMode: Text.Wrap+ maximumLineCount: 3+ elide: Text.ElideRight+ }+ UI.Label {+ text: peek.dateText(peek.event) + (peek.event.recurring ? " · " + qsTr("Repeats") : "")+ size: 13+ color: UI.Style.inkMuted+ }+ }+ UI.IconButton {+ Layout.alignment: Qt.AlignTop+ visible: !peek.event.readOnly+ iconName: "pencil"+ tip: qsTr("Edit")+ onClicked: {+ peek.close();+ peek.editRequested(peek.event);+ }+ }+ UI.IconButton {+ id: deleteButton+ Layout.alignment: Qt.AlignTop+ visible: !peek.event.readOnly+ iconName: "trash"+ tip: qsTr("Delete")+ onClicked: {+ if (peek.event.recurring) {+ deleteMenu.popup(deleteButton, 0, deleteButton.height + 4);+ } else {+ CalendarEngine.removeEvent(peek.event.key, true);+ peek.close();+ }+ }+ }+ UI.IconButton {+ Layout.alignment: Qt.AlignTop+ iconName: "close"+ tip: qsTr("Close")+ onClicked: peek.close()+ }+ }++ // Your answer, for an event someone else organised.+ RowLayout {+ visible: peek.event.invited === true+ Layout.fillWidth: true+ Layout.leftMargin: 16+ Layout.rightMargin: 16+ spacing: 6+ Repeater {+ model: [+ { id: "going", text: qsTr("Going"), icon: "check" },+ { id: "maybe", text: qsTr("Maybe"), icon: "more" },+ { id: "notGoing", text: qsTr("Not going"), icon: "close" }+ ]+ delegate: UI.Button {+ required property var modelData+ Layout.fillWidth: true+ size: "small"+ kind: peek.event.myStatus === modelData.id ? "primary" : "secondary"+ text: modelData.text+ iconName: modelData.icon+ onClicked: {+ CalendarEngine.respond(peek.event.key, modelData.id);+ const e = peek.event;+ e.myStatus = modelData.id;+ peek.event = e;+ }+ }+ }+ }++ component Detail: RowLayout {+ id: detail+ property string icon+ property alias text: label.text+ property alias subtext: sub.text+ property color dot: "transparent"+ default property alias extra: extraRow.data+ Layout.fillWidth: true+ Layout.leftMargin: 16+ Layout.rightMargin: 16+ spacing: 12+ MailIcon {+ Layout.alignment: Qt.AlignTop+ Layout.topMargin: 1+ name: detail.icon+ size: 16+ color: UI.Style.iconMuted+ }+ ColumnLayout {+ Layout.fillWidth: true+ spacing: 1+ RowLayout {+ spacing: 8+ Rectangle {+ visible: detail.dot.a > 0+ width: 9+ height: 9+ radius: 4.5+ color: detail.dot+ }+ UI.Label {+ id: label+ Layout.fillWidth: true+ size: 13+ wrapMode: Text.Wrap+ }+ }+ UI.Label {+ id: sub+ visible: text.length > 0+ size: 12+ color: UI.Style.inkMuted+ }+ Row {+ id: extraRow+ }+ }+ }++ Detail {+ visible: (peek.event.location || "").length > 0+ icon: "location"+ text: peek.event.location || ""+ UI.LinkButton {+ text: qsTr("Open in Maps")+ onClicked: Qt.openUrlExternally("https://www.openstreetmap.org/search?query=" + encodeURIComponent(peek.event.location))+ }+ }+ Detail {+ icon: "bell"+ text: peek.reminderText(peek.event.reminder === undefined ? -1 : peek.event.reminder)+ }+ Detail {+ icon: "calendar"+ text: peek.calendarName+ dot: peek.event.color || "transparent"+ }+ Detail {+ visible: (peek.event.description || "").trim().length > 0+ icon: "notes"+ text: (peek.event.description || "").trim()+ }++ // Who's going.+ ColumnLayout {+ visible: (peek.event.people || []).length > 0+ Layout.fillWidth: true+ Layout.leftMargin: 16+ Layout.rightMargin: 16+ spacing: 8+ RowLayout {+ Layout.fillWidth: true+ Layout.topMargin: 4+ UI.Label {+ Layout.fillWidth: true+ text: (peek.event.people || []).length === 1 ? qsTr("1 person") : qsTr("%1 people").arg((peek.event.people || []).length)+ size: 13+ font.weight: Font.DemiBold+ }+ UI.Label {+ text: {+ const parts = [];+ if (peek.event.going > 0)+ parts.push(qsTr("%1 going").arg(peek.event.going));+ if (peek.event.maybe > 0)+ parts.push(qsTr("%1 maybe").arg(peek.event.maybe));+ return parts.join(", ");+ }+ size: 12+ color: UI.Style.inkMuted+ }+ }+ Repeater {+ model: (peek.event.people || []).slice(0, 6)+ delegate: RowLayout {+ required property var modelData+ Layout.fillWidth: true+ spacing: 10+ SenderBadge {+ size: 28+ initials: Apps.initialsOf(modelData.name || modelData.email)+ colourIndex: Apps.colourOf(modelData.email)+ }+ ColumnLayout {+ Layout.fillWidth: true+ spacing: 0+ UI.Label {+ Layout.fillWidth: true+ text: (modelData.name || modelData.email) + (modelData.me ? " " + qsTr("(you)") : "")+ size: 13+ elide: Text.ElideRight+ }+ UI.Label {+ text: peek.statusText(modelData.status)+ size: 12+ color: modelData.status === "going" ? UI.Style.success : modelData.status === "maybe" ? UI.Style.warning+ : modelData.status === "notGoing" ? UI.Style.danger : UI.Style.inkMuted+ }+ }+ }+ }+ }++ RowLayout {+ Layout.fillWidth: true+ Layout.leftMargin: 16+ Layout.rightMargin: 16+ Layout.bottomMargin: 16+ Layout.topMargin: 2+ spacing: 8+ UI.Button {+ visible: (peek.event.people || []).length > 0+ size: "small"+ text: qsTr("Message everyone")+ iconName: "mail"+ onClicked: {+ const addresses = (peek.event.people || []).filter(p => !p.me).map(p => p.email);+ peek.close();+ peek.messageEveryone(addresses, peek.event.title);+ }+ }+ UI.Button {+ visible: !peek.event.readOnly+ size: "small"+ text: qsTr("Open event")+ onClicked: {+ peek.close();+ peek.editRequested(peek.event);+ }+ }+ Item {+ Layout.fillWidth: true+ }+ }+ }++ UI.Menu {+ id: deleteMenu+ entries: [+ { text: qsTr("Delete this one"), run: () => { CalendarEngine.removeEvent(peek.event.key, false); peek.close(); } },+ { text: qsTr("Delete the whole series"), icon: "delete", danger: true, run: () => { CalendarEngine.removeEvent(peek.event.key, true); peek.close(); } }+ ]+ }+}diff --git a/packages/wildos-mail/qml/FolderPane.qml b/packages/wildos-mail/qml/FolderPane.qmlnew file mode 100644index 0000000..3006fe0--- /dev/null+++ b/packages/wildos-mail/qml/FolderPane.qml@@ -0,0 +1,276 @@+import QtQuick+import QtQuick.Controls as QQC+import QtQuick.Layouts+import WildOS.Mail+import WildOS.UI as UI++// The folder pane (MailMicrosoft.dc, 236px): Favourites, then each account+// with its folders, "Create new folder", and what Mail kept out this week.+Item {+ id: pane++ signal addAccount()+ signal createFolder(string accountId)+ signal openPrivacy()+ signal folderMenu(string accountId, string fullName, string name, string role)+ signal crossAccount()++ function iconFor(role) {+ switch (role) {+ case "inbox": return "inbox";+ case "sent": return "sent";+ case "drafts": return "drafts";+ case "archive": return "archive";+ case "trash": return "trash";+ case "junk": return "junk";+ case "outbox": return "outbox";+ }+ return "folder";+ }++ ColumnLayout {+ anchors.fill: parent+ anchors.topMargin: 6+ spacing: 0++ ListView {+ id: list+ Layout.fillWidth: true+ Layout.fillHeight: true+ clip: true+ model: MailEngine.folders+ boundsBehavior: Flickable.StopAtBounds+ QQC.ScrollBar.vertical: UI.ScrollBar {}++ delegate: Item {+ id: row++ required property int index+ required property string kind+ required property string accountId+ required property string fullName+ required property string name+ required property string folderRole+ required property int depth+ required property int count+ required property bool expanded++ readonly property bool current: kind === "folder" && !MailEngine.searching+ && (accountId === "" ? MailEngine.folderAccount === "" && MailEngine.folderRole === fullName+ : MailEngine.folderAccount === accountId && MailEngine.folderName === fullName)++ width: list.width+ height: kind === "header" ? 36 : kind === "create" ? 30 : 32++ Rectangle {+ anchors.fill: parent+ anchors.leftMargin: 6+ anchors.rightMargin: 6+ anchors.topMargin: row.kind === "header" ? 4 : 0+ radius: 6+ visible: row.kind === "folder"+ color: drop.containsDrag ? UI.Style.accentSelected : row.current ? UI.Style.accentSelected : mouse.containsMouse ? UI.Style.surfaceHover : "transparent"+ border.width: drop.containsDrag ? 1 : 0+ border.color: UI.Style.accent+ }++ // Messages dragged from the list move here (MessageRowItem).+ DropArea {+ id: drop+ anchors.fill: parent+ enabled: row.kind === "folder" && row.accountId.length > 0 && row.folderRole !== "outbox"+ keys: ["wildos-mail-messages"]+ onDropped: function (event) {+ const keys = event.source.keys || [];+ const here = keys.filter(k => k.split("\x1f")[0] === row.accountId);+ if (here.length < keys.length) {+ pane.crossAccount();+ }+ if (here.length === 0) {+ return;+ }+ if (row.folderRole === "trash") {+ MailEngine.removeKeys(here);+ } else if (row.folderRole === "junk") {+ MailEngine.junkKeys(here);+ } else {+ MailEngine.moveKeys(here, row.fullName);+ }+ event.accept();+ }+ }++ MouseArea {+ id: mouse+ anchors.fill: parent+ hoverEnabled: true+ cursorShape: Qt.PointingHandCursor+ acceptedButtons: Qt.LeftButton | Qt.RightButton+ onClicked: function (event) {+ if (event.button === Qt.RightButton) {+ if (row.kind === "folder" && row.accountId.length > 0 && row.folderRole !== "outbox") {+ pane.folderMenu(row.accountId, row.fullName, row.name, row.folderRole);+ }+ return;+ }+ if (row.kind === "header") {+ MailEngine.toggleExpanded(row.accountId);+ } else if (row.kind === "create") {+ pane.createFolder(row.accountId);+ } else {+ MailEngine.openFolder(row.accountId, row.fullName);+ }+ }+ }++ // Account or Favourites heading.+ RowLayout {+ visible: row.kind === "header"+ anchors.fill: parent+ anchors.leftMargin: 16+ anchors.rightMargin: 16+ anchors.topMargin: 4+ spacing: 8++ MailIcon {+ name: row.expanded ? "chevron-down" : "chevron-right"+ size: 13+ color: UI.Style.inkMuted+ }+ UI.Label {+ Layout.fillWidth: true+ text: row.name+ size: 13+ font.weight: Font.DemiBold+ elide: Text.ElideRight+ }+ }++ RowLayout {+ visible: row.kind === "folder"+ anchors.fill: parent+ anchors.leftMargin: 16 + 18 + Math.max(0, row.depth - 1) * 14+ anchors.rightMargin: 16+ spacing: 10++ MailIcon {+ name: pane.iconFor(row.folderRole)+ size: 16+ color: row.current ? UI.Style.accent : UI.Style.iconInk+ }+ UI.Label {+ Layout.fillWidth: true+ text: row.name+ size: 13+ font.weight: row.current ? Font.DemiBold : Font.Normal+ elide: Text.ElideRight+ }+ UI.Label {+ visible: row.count > 0+ text: row.count+ size: 12+ font.weight: Font.DemiBold+ color: UI.Style.accent+ }+ }++ UI.Label {+ visible: row.kind === "create"+ anchors.verticalCenter: parent.verticalCenter+ x: 44+ text: row.name+ size: 13+ color: mouse.containsMouse ? UI.Style.accentHover : UI.Style.accent+ }+ }++ footer: Item {+ width: list.width+ height: 38++ MouseArea {+ id: addMouse+ anchors.fill: parent+ anchors.leftMargin: 6+ anchors.rightMargin: 6+ hoverEnabled: true+ cursorShape: Qt.PointingHandCursor+ onClicked: pane.addAccount()+ }++ RowLayout {+ anchors.fill: parent+ anchors.leftMargin: 16+ spacing: 8++ MailIcon {+ name: "plus"+ size: 15+ color: UI.Style.accent+ }+ UI.Label {+ text: qsTr("Add account")+ size: 13+ color: addMouse.containsMouse ? UI.Style.accentHover : UI.Style.accent+ }+ Item {+ Layout.fillWidth: true+ }+ }+ }+ }++ // What Mail kept away from senders this week.+ Rectangle {+ Layout.fillWidth: true+ Layout.leftMargin: 10+ Layout.rightMargin: 10+ Layout.bottomMargin: 12+ Layout.topMargin: 8+ implicitHeight: trackers.implicitHeight + 22+ radius: 10+ color: UI.Style.surfaceRest+ border.width: 1+ border.color: UI.Style.borderSubtle++ MouseArea {+ anchors.fill: parent+ cursorShape: Qt.PointingHandCursor+ onClicked: pane.openPrivacy()+ }++ RowLayout {+ id: trackers+ anchors.fill: parent+ anchors.margins: 11+ anchors.leftMargin: 12+ spacing: 10++ MailIcon {+ name: "shield-check"+ size: 18+ color: UI.Style.success+ }+ ColumnLayout {+ Layout.fillWidth: true+ spacing: 2++ UI.Label {+ Layout.fillWidth: true+ text: MailEngine.trackersThisWeek === 1 ? qsTr("1 tracker blocked") : qsTr("%1 trackers blocked").arg(MailEngine.trackersThisWeek)+ size: 12+ font.weight: Font.DemiBold+ elide: Text.ElideRight+ }+ UI.Label {+ Layout.fillWidth: true+ text: qsTr("This week, across all mail")+ size: 11+ color: UI.Style.inkMuted+ elide: Text.ElideRight+ }+ }+ }+ }+ }+}diff --git a/packages/wildos-mail/qml/Formats.js b/packages/wildos-mail/qml/Formats.jsnew file mode 100644index 0000000..0bd2792--- /dev/null+++ b/packages/wildos-mail/qml/Formats.js@@ -0,0 +1,71 @@+// Dates and times in the regional format chosen in Settings > Language and+// region (LC_TIME, which Qt.locale() follows), with day and month names in+// English because the rest of Wild OS is in English. The taskbar clock's+// Formats.js works the same way.++function names() {+ return Qt.locale("en_GB");+}++function time(when) {+ return Qt.locale().toString(when, Qt.locale().timeFormat(Locale.ShortFormat));+}++// "Mon 09/11/2026", "Mon 11/9/26".+function dayAndShortDate(when) {+ return names().toString(when, "ddd " + Qt.locale().dateFormat(Locale.ShortFormat));+}++// Qt writes UK dates as "Monday, 9 November 2026"; the design has no comma.+function longFormat() {+ return Qt.locale().dateFormat(Locale.LongFormat).replace(/^dddd, d MMMM/, "dddd d MMMM");+}++function withoutYear(format) {+ return format.replace(/[,.\s]*y+[.年]?/, "").trim();+}++function withoutWeekday(format) {+ return format.replace(/d{4}[,.\s]*/, "").trim();+}++// "Monday 9 November 2026", "Monday, November 9, 2026".+function longDate(when) {+ return names().toString(when, longFormat());+}++// "Mon 9 November 2026", "Mon, November 9, 2026".+function mediumDate(when) {+ return names().toString(when, longFormat().replace("dddd", "ddd"));+}++// "Monday 9 November", "Monday, November 9".+function weekdayAndDay(when) {+ return names().toString(when, withoutYear(longFormat()));+}++// "9 November 2026", "November 9, 2026".+function dayMonthYear(when) {+ return names().toString(when, withoutWeekday(longFormat()));+}++// "9 November", "November 9".+function dayAndMonth(when) {+ return names().toString(when, withoutWeekday(withoutYear(longFormat())));+}++// "9 Nov", "Nov 9".+function shortDayAndMonth(when) {+ return names().toString(when, withoutWeekday(withoutYear(longFormat())).replace("MMMM", "MMM"));+}++// "November 2026" in most formats, "2026年11月" where the year comes first.+function monthAndYear(when) {+ return names().toString(when, withoutWeekday(longFormat()).replace(/d{1,2}[,.\s日]*/, "").trim());+}++// True when the day comes before the month, as in "9 November".+function dayFirst() {+ const f = withoutWeekday(longFormat());+ return f.indexOf("d") < f.indexOf("M");+}diff --git a/packages/wildos-mail/qml/InvitationCard.qml b/packages/wildos-mail/qml/InvitationCard.qmlnew file mode 100644index 0000000..e7787f2--- /dev/null+++ b/packages/wildos-mail/qml/InvitationCard.qml@@ -0,0 +1,373 @@+import QtCore+import QtQuick+import QtQuick.Layouts+import WildOS.Mail+import WildOS.UI as UI+import "Formats.js" as Formats++// An invitation in the reading pane (MailMsInvite.dc): Accept, Maybe and+// Decline, when and where, who's coming, and the day it's on with whatever+// it overlaps. The answer goes through Calendar: where a Google or CalDAV+// calendar already has the event, its server tells the organiser;+// otherwise it goes into your calendar and the organiser gets a reply by+// mail. A cancellation offers to take the event out.+Rectangle {+ id: card++ // The iCalendar text in the message, and the account it came to.+ property string ics+ property string accountId+ property string myEmail+ property string messageKey++ readonly property var invite: ics.length > 0 ? CalendarEngine.describeInvitation(ics, myEmail) : ({})+ readonly property bool isRequest: invite.method === "request"+ readonly property bool isCancel: invite.method === "cancel"+ readonly property string answerKey: "invites/" + (invite.uid || "").replace(/[\/\\]/g, "_") + "_" + (invite.sequence || 0)+ property string answered: ""+ property var dayEvents: []+ property bool busy: false++ visible: invite.uid !== undefined && (isRequest || isCancel)+ implicitHeight: visible ? content.implicitHeight + 32 : 0+ radius: 8+ color: UI.Style.surfaceRaised+ border.width: 1+ border.color: UI.Style.borderSubtle++ onInviteChanged: {+ answered = invite.uid ? (store.value(answerKey, "") || invite.myStatus || "") : "";+ if (answered === "waiting") {+ answered = "";+ }+ dayEvents = [];+ if (invite.start && !invite.allDay) {+ CalendarEngine.loadDay(new Date(invite.start));+ }+ }++ function answer(status) {+ busy = true;+ CalendarEngine.answerInvitation(ics, status, myEmail);+ }+ function whenText() {+ const s = new Date(invite.start);+ const e = new Date(invite.end);+ const day = Formats.dayAndShortDate(s);+ if (invite.allDay) {+ return e > s ? qsTr("%1 to %2").arg(day).arg(Formats.dayAndShortDate(e)) : qsTr("%1, all day").arg(day);+ }+ return qsTr("%1, %2 to %3").arg(day).arg(Formats.time(s)).arg(Formats.time(e));+ }+ function sameDay(a, b) {+ return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();+ }++ Settings {+ id: store+ category: "mail"+ }++ // The reply by mail, for an organiser no calendar server will tell.+ Composer {+ id: replyComposer+ }++ Connections {+ target: CalendarEngine+ function onDayLoaded(day, events) {+ if (card.invite.start && card.sameDay(day, new Date(card.invite.start))) {+ card.dayEvents = events.filter(e => !e.allDay && e.title !== card.invite.title);+ }+ }+ function onInvitationAnswered(uid, status, reply, organizer, title) {+ if (uid !== card.invite.uid) {+ return;+ }+ card.busy = false;+ card.answered = status;+ store.setValue(card.answerKey, status);+ if (reply.length > 0 && organizer.length > 0) {+ const verb = status === "going" ? qsTr("Accepted") : status === "maybe" ? qsTr("Tentative") : qsTr("Declined");+ replyComposer.start({ accountId: card.accountId, to: [organizer], subject: verb + ": " + title, calendarReply: reply });+ const words = status === "going" ? qsTr("I'll be there.") : status === "maybe" ? qsTr("I might be able to make it.") : qsTr("I can't make it, sorry.");+ replyComposer.bodyText = words;+ replyComposer.bodyHtml = "<p>" + words + "</p>";+ replyComposer.send();+ }+ }+ function onNotice(text) {+ card.busy = false;+ }+ }++ RowLayout {+ id: content+ x: 16+ y: 16+ width: card.width - 32+ spacing: 16++ ColumnLayout {+ Layout.fillWidth: true+ Layout.alignment: Qt.AlignTop+ spacing: 12++ RowLayout {+ spacing: 8+ Rectangle {+ implicitWidth: badge.implicitWidth + 14+ implicitHeight: badge.implicitHeight + 6+ radius: 4+ color: card.isCancel ? Qt.alpha(UI.Style.danger, 0.18) : Qt.alpha(UI.Style.warning, 0.18)+ UI.Label {+ id: badge+ anchors.centerIn: parent+ text: card.isCancel ? qsTr("Cancelled") : qsTr("Invitation")+ size: 11.5+ font.weight: Font.DemiBold+ color: card.isCancel ? UI.Style.danger : UI.Style.warning+ }+ }+ UI.Label {+ visible: card.answered.length > 0 && card.isRequest+ text: card.answered === "going" ? qsTr("You're going") : card.answered === "maybe" ? qsTr("You said maybe") : qsTr("You declined")+ size: 12+ color: UI.Style.inkMuted+ }+ }++ // Your answer.+ RowLayout {+ visible: card.isRequest+ spacing: 8+ Repeater {+ model: [+ { id: "going", text: qsTr("Accept"), icon: "check" },+ { id: "maybe", text: qsTr("Maybe"), icon: "more" },+ { id: "notGoing", text: qsTr("Decline"), icon: "close" }+ ]+ delegate: UI.Button {+ required property var modelData+ size: "small"+ kind: card.answered === modelData.id || (card.answered === "" && modelData.id === "going") ? "primary" : "secondary"+ text: modelData.text+ iconName: modelData.icon+ enabled: !card.busy+ onClicked: card.answer(modelData.id)+ }+ }+ }+ UI.Button {+ visible: card.isCancel+ size: "small"+ text: qsTr("Remove from calendar")+ iconName: "delete"+ onClicked: CalendarEngine.removeInvitation(card.ics)+ }++ component Line: RowLayout {+ id: line+ property string icon+ property alias text: main.text+ property alias subtext: sub.text+ default property alias extra: extraRow.data+ Layout.fillWidth: true+ spacing: 12+ MailIcon {+ Layout.alignment: Qt.AlignTop+ Layout.topMargin: 1+ name: line.icon+ size: 16+ color: UI.Style.iconMuted+ }+ ColumnLayout {+ Layout.fillWidth: true+ spacing: 1+ UI.Label {+ id: main+ Layout.fillWidth: true+ size: 13.5+ wrapMode: Text.Wrap+ }+ UI.Label {+ id: sub+ visible: text.length > 0+ size: 12+ color: UI.Style.inkMuted+ }+ Row {+ id: extraRow+ }+ }+ }++ Line {+ icon: "clock"+ text: card.invite.start ? card.whenText() : ""+ subtext: card.invite.recurring ? qsTr("Repeats") : qsTr("Doesn't repeat")+ }+ Line {+ visible: (card.invite.location || "").length > 0+ icon: "location"+ text: card.invite.location || ""+ UI.LinkButton {+ text: qsTr("Open in Maps")+ size: 12+ onClicked: Qt.openUrlExternally("https://www.openstreetmap.org/search?query=" + encodeURIComponent(card.invite.location))+ }+ }+ Line {+ visible: card.invite.people > 0+ icon: "people"+ text: {+ const who = card.invite.organizerName || card.invite.organizer || "";+ const others = card.invite.people - 1;+ return others > 0 ? (others === 1 ? qsTr("%1 and 1 other").arg(who) : qsTr("%1 and %2 others").arg(who).arg(others)) : who;+ }+ subtext: {+ const parts = [];+ if (card.invite.accepted > 0)+ parts.push(qsTr("%1 accepted").arg(card.invite.accepted));+ if (card.invite.waiting > 0)+ parts.push(qsTr("%1 not replied yet").arg(card.invite.waiting));+ return parts.join(", ");+ }+ }+ }++ // The day it's on (MailMsInvite.dc, right).+ Rectangle {+ id: dayBox+ visible: !card.invite.allDay && card.invite.start !== undefined && card.width > 620+ Layout.preferredWidth: 300+ Layout.preferredHeight: 280+ Layout.alignment: Qt.AlignTop+ radius: 8+ color: UI.Style.surfaceRest+ border.width: 1+ border.color: UI.Style.borderSubtle+ clip: true++ readonly property date start: card.invite.start ? new Date(card.invite.start) : new Date()+ readonly property date end: card.invite.end ? new Date(card.invite.end) : new Date()+ readonly property real startHour: start.getHours() + start.getMinutes() / 60+ readonly property real endHour: Math.max(startHour + 0.5, end.getHours() + end.getMinutes() / 60 + (end.getDate() !== start.getDate() ? 24 : 0))+ // From an hour before to an hour after, as the board shows it.+ readonly property int firstHour: Math.max(0, Math.floor(startHour) - 2)+ readonly property real hour: 34+ readonly property var clashes: card.dayEvents.filter(e => e.busy && e.startMinute < endHour * 60 && e.endMinute > startHour * 60)++ UI.Label {+ x: 12+ y: 10+ text: Formats.weekdayAndDay(dayBox.start)+ size: 13+ font.weight: Font.DemiBold+ }+ Rectangle {+ x: 12+ y: 34+ width: parent.width - 24+ height: 28+ radius: 6+ color: dayBox.clashes.length > 0 ? UI.Style.warningSoft : UI.Style.successSoft+ RowLayout {+ anchors.fill: parent+ anchors.leftMargin: 10+ anchors.rightMargin: 10+ spacing: 8+ MailIcon {+ name: dayBox.clashes.length > 0 ? "clock" : "check"+ size: 13+ color: dayBox.clashes.length > 0 ? UI.Style.warning : UI.Style.success+ }+ UI.Label {+ Layout.fillWidth: true+ text: dayBox.clashes.length > 0 ? qsTr("Overlaps %1").arg(dayBox.clashes[0].title) : qsTr("Nothing else on at this time")+ size: 12+ elide: Text.ElideRight+ }+ }+ }+ Item {+ id: hours+ x: 12+ y: 70+ width: parent.width - 24+ height: parent.height - 76+ clip: true+ // Side by side when they overlap: what's on at the left,+ // the invitation at the right.+ readonly property real lane: dayBox.clashes.length > 0 ? (width - 52) / 2 : width - 52+ Repeater {+ model: 7+ delegate: Item {+ required property int index+ y: 8 + index * dayBox.hour+ width: parent.width+ height: dayBox.hour+ UI.Label {+ y: -6+ text: ((dayBox.firstHour + index) % 24 < 10 ? "0" : "") + (dayBox.firstHour + index) % 24 + ":00"+ size: 11+ color: UI.Style.inkSubtle+ }+ Rectangle {+ x: 46+ width: parent.width - 46+ height: 1+ color: UI.Style.borderSubtle+ }+ }+ }+ Repeater {+ model: card.dayEvents+ delegate: Rectangle {+ required property var modelData+ x: 50+ y: 8 + (modelData.startMinute / 60 - dayBox.firstHour) * dayBox.hour + 1+ width: hours.lane - 2+ height: Math.max(16, (modelData.endMinute - modelData.startMinute) / 60 * dayBox.hour - 2)+ radius: 4+ color: Qt.rgba(Qt.color(modelData.color).r, Qt.color(modelData.color).g, Qt.color(modelData.color).b, 0.4)+ Rectangle {+ width: 3+ height: parent.height+ color: modelData.color+ }+ UI.Label {+ x: 8+ y: 2+ width: parent.width - 12+ text: modelData.title+ size: 11.5+ font.weight: Font.DemiBold+ elide: Text.ElideRight+ }+ }+ }+ // The invitation, dashed.+ Rectangle {+ x: 50 + (dayBox.clashes.length > 0 ? hours.lane : 0)+ y: 8 + (dayBox.startHour - dayBox.firstHour) * dayBox.hour + 1+ width: hours.lane+ height: Math.max(16, (dayBox.endHour - dayBox.startHour) * dayBox.hour - 2)+ radius: 4+ color: UI.Style.accentSoft+ border.width: 1.5+ border.color: UI.Style.accent+ UI.Label {+ x: 8+ y: 2+ width: parent.width - 12+ text: card.invite.title || ""+ size: 11.5+ font.weight: Font.DemiBold+ elide: Text.ElideRight+ }+ }+ }+ }+ }+}diff --git a/packages/wildos-mail/qml/MailIcon.qml b/packages/wildos-mail/qml/MailIcon.qmlnew file mode 100644index 0000000..24c71d3--- /dev/null+++ b/packages/wildos-mail/qml/MailIcon.qml@@ -0,0 +1,37 @@+import QtQuick+import QtQuick.Shapes+import WildOS.UI as UI++// One of Mail's line icons (MailIcons), or a system one by the same name.+Item {+ id: icon++ property string name+ property color color: UI.Style.iconInk+ property real size: 16+ property real strokeWidth: size <= 16 ? 2 : 1.8++ implicitWidth: size+ implicitHeight: size++ Shape {+ width: 24+ height: 24+ preferredRendererType: Shape.CurveRenderer+ transform: Scale {+ xScale: icon.size / 24+ yScale: icon.size / 24+ }++ ShapePath {+ strokeColor: icon.color+ strokeWidth: icon.strokeWidth+ fillColor: "transparent"+ capStyle: ShapePath.RoundCap+ joinStyle: ShapePath.RoundJoin+ PathSvg {+ path: MailIcons.paths[icon.name] || UI.Icons.paths[icon.name] || ""+ }+ }+ }+}diff --git a/packages/wildos-mail/qml/MailIcons.qml b/packages/wildos-mail/qml/MailIcons.qmlnew file mode 100644index 0000000..7252b9c--- /dev/null+++ b/packages/wildos-mail/qml/MailIcons.qml@@ -0,0 +1,68 @@+pragma Singleton++import QtQuick++// Mail's own line icons, drawn on the same 24px grid and stroke as the+// system set (WildOS.UI Icons), taken from the Mail and Calendar artboards.+QtObject {+ readonly property var paths: ({+ "inbox": "M3 13l3-8h12l3 8v6H3zM3 13h5l1 3h6l1-3h5",+ "sent": "M21 3L10 14M21 3l-7 18-4-7-7-4z",+ "drafts": "M14 3H6v18h12V7zM14 3v4h4M9 13h6M9 17h4",+ "archive": "M3 4h18v4H3zM5 8v11a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8M10 12h4",+ "trash": "M4 7h16M10 11v6M14 11v6M5 7l1 12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2l1-12M9 7V4h6v3",+ "junk": "M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM5.7 5.7l12.6 12.6",+ "folder": "M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",+ "outbox": "M12 15V3M7 8l5-5 5 5M4 13v7h16v-7",+ "star": "M12 3.5l2.6 5.3 5.9.9-4.3 4.1 1 5.8-5.2-2.8-5.2 2.8 1-5.8-4.3-4.1 5.9-.9z",+ "flag": "M5 21V4M5 4h12l-2.5 4.5L17 13H5",+ "clock": "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM12 7v5l3 2",+ "paperclip": "M20 11.5l-8.5 8.5a5 5 0 0 1-7-7L13 4.5a3.4 3.4 0 0 1 4.8 4.8l-8.4 8.4a1.7 1.7 0 0 1-2.4-2.4L15 7.3",+ "shield-check": "M12 3l8 3v6c0 4.5-3.5 8-8 9-4.5-1-8-4.5-8-9V6zM8.5 12l2.5 2.5 4.5-5",+ "shield": "M12 3l8 3v6c0 4.5-3.5 8-8 9-4.5-1-8-4.5-8-9V6z",+ "filter": "M4 6h16M7 12h10M10 18h4",+ "reply": "M9 17l-5-5 5-5M4 12h11a5 5 0 0 1 5 5v2",+ "reply-all": "M8 17l-5-5 5-5M13 17l-5-5 5-5M8 12h7a5 5 0 0 1 5 5v2",+ "forward": "M15 17l5-5-5-5M20 12H9a5 5 0 0 0-5 5v2",+ "search": "M11 18a7 7 0 1 0 0-14 7 7 0 0 0 0 14zM20 20l-4-4",+ "new-mail": "M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z",+ "apps": "M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4zM14 14h6v6h-6z",+ "bell": "M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9M10.3 21a1.9 1.9 0 0 0 3.4 0",+ "settings": "M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM19.4 15a1.6 1.6 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.6 1.6 0 0 0-1.8-.3 1.6 1.6 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.6 1.6 0 0 0-1-1.5 1.6 1.6 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.6 1.6 0 0 0 .3-1.8 1.6 1.6 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.6 1.6 0 0 0 1.5-1 1.6 1.6 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.6 1.6 0 0 0 1.8.3H9a1.6 1.6 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.6 1.6 0 0 0 1 1.5 1.6 1.6 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.6 1.6 0 0 0-.3 1.8V9a1.6 1.6 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.6 1.6 0 0 0-1.5 1z",+ "mail": "M3 5h18v14H3zM3 6l9 7 9-7",+ "read-unread": "M3 9l9-6 9 6v11H3zM3 9l9 6 9-6",+ "pin": "M12 16v5M6 16h12l-2-4V5h1V3H7v2h1v7z",+ "move": "M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2zM10 13h6M13 10l3 3-3 3",+ "report": "M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM12 8v5M12 16h.01",+ "calendar": "M4 6h16v14H4zM4 10h16M8 3v4M16 3v4",+ "grid": "M4 4h7v7H4zM13 4h7v7h-7zM4 13h7v7H4zM13 13h7v7h-7z",+ "repeat": "M17 2l3 3-3 3M4 11V9a4 4 0 0 1 4-4h12M7 22l-3-3 3-3M20 13v2a4 4 0 0 1-4 4H4",+ "notes": "M4 6h16M4 12h16M4 18h10",+ "people": "M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM2 21v-1a6 6 0 0 1 12 0v1M16 3.5a4 4 0 0 1 0 7.5M22 21v-1a6 6 0 0 0-4-5.6",+ "tasks": "M4 6l2 2 3-3M4 13l2 2 3-3M12 7h8M12 14h8M12 20h8",+ "more": "M5 12h.01M12 12h.01M19 12h.01",+ "chevron-down": "M6 9l6 6 6-6",+ "chevron-right": "M9 6l6 6-6 6",+ "plus": "M12 5v14M5 12h14",+ "picture": "M3 5h18v14H3zM3 16l5-5 4 4 3-3 6 6",+ "link": "M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1",+ "emoji": "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM8.5 14a4.5 4.5 0 0 0 7 0M9 9.5h.01M15 9.5h.01",+ "bold": "M7 5h6a3.5 3.5 0 0 1 0 7H7zM7 12h7a3.5 3.5 0 0 1 0 7H7z",+ "italic": "M14 5h-4M14 19h-4M14 5l-4 14",+ "underline": "M7 4v7a5 5 0 0 0 10 0V4M5 20h14",+ "bullets": "M9 6h11M9 12h11M9 18h11M4.5 6h.01M4.5 12h.01M4.5 18h.01",+ "numbering": "M10 6h10M10 12h10M10 18h10M4 5h1v4M4 9h2M4 15h2l-2 3h2",+ "lock": "M5 11h14v10H5zM8 11V7a4 4 0 0 1 8 0v4",+ "offline": "M2 8.8a15 15 0 0 1 4.2-2.6M10.7 5.1A15 15 0 0 1 22 8.8M5 12.5a10 10 0 0 1 5.2-2.7M16.8 10.7a10 10 0 0 1 2.2 1.8M8.5 16a5 5 0 0 1 7 0M12 20h.01M3 3l18 18",+ "key": "M15 7a3 3 0 1 0 0 .01M13 9.5L4 18.5V21h3v-2h2v-2h2l2.5-2.5",+ "server": "M4 4h16v6H4zM4 14h16v6H4zM8 7h.01M8 17h.01",+ "refresh": "M20 11a8 8 0 1 0-2.3 5.7M20 4v7h-7",+ "download": "M12 3v12M7 10l5 5 5-5M5 21h14",+ "layout": "M3 4h18v16H3zM9 4v16M9 12h21",+ "signature": "M3 17c3-6 5-9 6-9s-1 8 1 8 3-5 4-5-1 5 1 5 3-2 6-2M3 21h18",+ "palette": "M12 21a9 9 0 1 1 9-9c0 2-1.5 3-3 3h-2a2 2 0 0 0-1.5 3.3A1.6 1.6 0 0 1 12 21zM7.5 11h.01M10 7h.01M15 7.5h.01",+ "check": "M5 12l5 5L20 7",+ "close": "M6 6l12 12M18 6L6 18",+ "file": "M14 3H6v18h12V7zM14 3v4h4"+ })+}diff --git a/packages/wildos-mail/qml/Main.qml b/packages/wildos-mail/qml/Main.qmlnew file mode 100644index 0000000..5efe629--- /dev/null+++ b/packages/wildos-mail/qml/Main.qml@@ -0,0 +1,1187 @@+import QtCore+import QtQuick+import QtQuick.Controls as QQC+import QtQuick.Layouts+import WildOS.Mail+import WildOS.UI as UI++// Wild OS Mail (MailMicrosoft.dc and the boards after it): the title bar+// with search, the app rail, the ribbon, then folders, messages and the+// reading pane, which turns into the message being written.+UI.AppWindow {+ id: window++ property bool composing: false+ property bool showSettings: false+ // Which tab the rail shows: "mail" or "calendar".+ property string section: "mail"++ width: 1384+ height: 802+ minimumWidth: 960+ // Tall enough for every step of adding an account without scrolling.+ minimumHeight: 640+ visible: true+ title: section === "calendar" ? qsTr("Calendar") : qsTr("Mail")++ // From main.cpp: Calendar's own launcher, or a reminder's Open.+ function showCalendar(key, day) {+ section = "calendar";+ if (key && key.length > 0) {+ Qt.callLater(() => calendarLoader.item.showEvent(key, day));+ }+ }+ // Mail's Google accounts, for Calendar's bar offering their calendars.+ readonly property var googleAccounts: MailEngine.accounts.filter(a => a.auth === "google")++ // A mailto: link, from main.cpp.+ function compose(data) {+ showSettings = false;+ composing = true;+ composePane.start(data || {});+ }+ function reply(mode) {+ if (!readingPane.view.key) {+ return;+ }+ compose(readingPane.view.replyData(mode));+ }+ function selectedKey() {+ return MailEngine.selected;+ }+ // Read or unread for everything selected: all read if any is unread.+ function toggleReadSelection() {+ const keys = MailEngine.selection;+ let anyUnread = false;+ for (const k of keys) {+ const i = MailEngine.messages.indexOf(k);+ if (i >= 0 && MailEngine.messages.unreadAt(i)) {+ anyUnread = true;+ }+ }+ MailEngine.setReadKeys(keys, anyUnread);+ }+ function toggleFlagSelection() {+ const keys = MailEngine.selection;+ let anyUnflagged = false;+ for (const k of keys) {+ const i = MailEngine.messages.indexOf(k);+ if (i >= 0 && !MailEngine.messages.flaggedAt(i)) {+ anyUnflagged = true;+ }+ }+ MailEngine.setFlaggedKeys(keys, anyUnflagged);+ }+ function openMessage(key) {+ messageWindow.createObject(null, { messageKey: key, main: window });+ }+ function openLink(url) {+ if (url.startsWith("mailto:")) {+ window.compose({ to: [url.substring(7).split("?")[0]] });+ } else {+ linkConfirm.ask(url);+ }+ }+ // The account's signature where the cursor is, or Settings to make one.+ function insertSignature() {+ const account = MailEngine.account(composePane.composer.accountId);+ if (!account.signature) {+ settingsPage.section = "writing";+ window.showSettings = true;+ toast.show(qsTr("Write your signature here, then add it from the message."));+ return;+ }+ composePane.formatter.insertText("\n" + account.signature);+ }++ Component {+ id: messageWindow+ MessageWindow {+ onClosing: destroy()+ }+ }+ function snoozeUntil(choice) {+ const d = new Date();+ if (choice === "later") {+ d.setHours(d.getHours() + 3);+ } else if (choice === "tomorrow") {+ d.setDate(d.getDate() + 1);+ d.setHours(8, 0, 0, 0);+ } else if (choice === "weekend") {+ d.setDate(d.getDate() + ((6 - d.getDay() + 7) % 7 || 7));+ d.setHours(8, 0, 0, 0);+ } else {+ d.setDate(d.getDate() + ((8 - d.getDay()) % 7 || 7));+ d.setHours(8, 0, 0, 0);+ }+ return d;+ }++ Settings {+ id: prefs+ category: "Window"+ property string readingPane: "right"+ }++ Connections {+ target: MailEngine+ function onNotice(text) {+ toast.show(text);+ }+ function onUndoable(text) {+ toast.show(text, qsTr("Undo"));+ }+ }+ // The address Calendar's bar is signing in, between asking Google and+ // its answer.+ property string calendarSignIn: ""+ Connections {+ target: GoogleSignIn+ function onSignedIn(address, refreshToken) {+ if (window.calendarSignIn.length > 0) {+ CalendarEngine.addGoogleAccount(window.calendarSignIn, refreshToken);+ window.calendarSignIn = "";+ return;+ }+ if (signInDialog.googleAccount.length > 0) {+ MailEngine.signInAgain(signInDialog.googleAccount, refreshToken);+ signInDialog.googleAccount = "";+ }+ }+ function onFailed(message) {+ if (window.calendarSignIn.length > 0) {+ toast.show(message);+ window.calendarSignIn = "";+ return;+ }+ if (signInDialog.googleAccount.length > 0) {+ toast.show(message);+ signInDialog.googleAccount = "";+ }+ }+ }+ Connections {+ target: Notifier+ function onOpenRequested(key) {+ const parts = key.split("\x1f");+ window.showSettings = false;+ window.composing = false;+ MailEngine.openFolder(parts[0], parts[1]);+ MailEngine.selected = key;+ window.raise();+ window.requestActivate();+ }+ }++ Shortcut {+ sequence: StandardKey.New+ enabled: window.section === "mail"+ onActivated: window.compose({})+ }+ Shortcut {+ sequence: "Ctrl+R"+ enabled: window.section === "mail" && (!window.composing && !window.showSettings)+ onActivated: window.reply("reply")+ }+ Shortcut {+ sequence: "Ctrl+Shift+R"+ enabled: window.section === "mail" && (!window.composing && !window.showSettings)+ onActivated: window.reply("replyAll")+ }+ Shortcut {+ sequence: "Ctrl+Shift+F"+ enabled: window.section === "mail" && (!window.composing && !window.showSettings)+ onActivated: window.reply("forward")+ }+ Shortcut {+ sequence: "Ctrl+E"+ onActivated: search.forceActiveFocus()+ }+ Shortcut {+ sequence: "F5"+ enabled: window.section === "mail"+ onActivated: MailEngine.refresh()+ }+ Shortcut {+ sequence: "Ctrl+Q"+ enabled: window.section === "mail" && (!window.composing)+ onActivated: MailEngine.setReadKeys(MailEngine.selection, true)+ }+ Shortcut {+ sequence: "Ctrl+U"+ enabled: window.section === "mail" && (!window.composing)+ onActivated: MailEngine.setReadKeys(MailEngine.selection, false)+ }+ // Only from the message list, never while typing anywhere else.+ Shortcut {+ sequence: "Backspace"+ enabled: window.section === "mail" && (messageList.listFocused && !window.composing)+ onActivated: MailEngine.archiveKeys(MailEngine.selection)+ }++ ColumnLayout {+ anchors.fill: parent+ anchors.margins: window.maximised ? 0 : 1+ spacing: 0++ UI.TitleBar {+ id: titleBar+ Layout.fillWidth: true+ title: window.section === "calendar" ? qsTr("Calendar") : qsTr("Mail")+ tinted: true+ frame: window.frame++ Item {+ anchors.fill: parent++ UI.SearchField {+ id: search+ anchors.centerIn: parent+ width: Math.min(520, parent.width - 160)+ height: 32+ placeholderText: window.section === "calendar" ? qsTr("Search events") : qsTr("Search mail and people")+ onTextChanged: searchTimer.restart()+ onEscapePressed: {+ text = "";+ if (window.section === "calendar") {+ calendarLoader.item.clearSearch();+ } else {+ MailEngine.clearSearch();+ }+ }+ onAccepted: {+ searchTimer.stop();+ if (window.section === "calendar") {+ calendarLoader.item.search(text);+ } else {+ MailEngine.search(text);+ }+ }+ }+ Timer {+ id: searchTimer+ interval: 300+ onTriggered: {+ if (window.section === "calendar") {+ calendarLoader.item.search(search.text);+ } else if (search.text.trim().length > 0) {+ MailEngine.search(search.text);+ } else {+ MailEngine.clearSearch();+ }+ }+ }+ CommandButton {+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ iconOnly: true+ iconName: "settings"+ tip: qsTr("Settings")+ onClicked: {+ if (window.section === "calendar") {+ calendarLoader.item.toggleSettings();+ return;+ }+ window.composing = false;+ window.showSettings = !window.showSettings;+ }+ }+ }+ }++ // You're offline (MailMsStates.dc).+ Rectangle {+ visible: !MailEngine.online && MailEngine.hasAccounts && window.section === "mail"+ Layout.fillWidth: true+ implicitHeight: 40+ color: UI.Style.warningSoft++ RowLayout {+ anchors.fill: parent+ anchors.leftMargin: 18+ anchors.rightMargin: 12+ spacing: 10+ MailIcon {+ name: "offline"+ size: 16+ color: UI.Style.warning+ }+ UI.Label {+ Layout.fillWidth: true+ text: qsTr("You're offline. New mail will arrive when you reconnect, and anything you send waits in the Outbox.")+ size: 13+ elide: Text.ElideRight+ }+ UI.Button {+ size: "small"+ text: qsTr("Try again")+ onClicked: MailEngine.refresh()+ }+ }+ }++ // An account that needs its password again.+ Repeater {+ model: MailEngine.problems+ delegate: Rectangle {+ required property var modelData+ visible: MailEngine.online && window.section === "mail"+ Layout.fillWidth: true+ implicitHeight: 40+ color: UI.Style.warningSoft++ RowLayout {+ anchors.fill: parent+ anchors.leftMargin: 18+ anchors.rightMargin: 12+ spacing: 10+ MailIcon {+ name: modelData.kind === "password" ? "key" : "warning"+ size: 16+ color: UI.Style.warning+ }+ UI.Label {+ Layout.fillWidth: true+ text: modelData.name + ": " + modelData.text+ size: 13+ elide: Text.ElideRight+ }+ UI.Button {+ size: "small"+ text: modelData.kind === "password" ? qsTr("Sign in again") : qsTr("Try again")+ onClicked: modelData.kind === "password" ? signInDialog.ask(modelData.accountId) : MailEngine.refresh()+ }+ }+ }+ }++ RowLayout {+ Layout.fillWidth: true+ Layout.fillHeight: true+ spacing: 0++ AppRail {+ Layout.fillHeight: true+ current: window.section+ squareCorner: window.maximised+ onPicked: function (app) {+ search.text = "";+ window.section = app;+ }+ }++ // Calendar, made the first time its tab is chosen.+ Loader {+ id: calendarLoader+ active: window.section === "calendar" || item !== null+ visible: window.section === "calendar"+ Layout.fillWidth: true+ Layout.fillHeight: true+ sourceComponent: CalendarPage {+ mailAccounts: window.googleAccounts+ onAddGoogleCalendar: function (email) {+ window.calendarSignIn = email;+ GoogleSignIn.startCalendar(email);+ }+ }+ }++ ColumnLayout {+ visible: window.section === "mail"+ Layout.fillWidth: true+ Layout.fillHeight: true+ Layout.bottomMargin: 12+ spacing: 10++ // The ribbon (MailMicrosoft.dc): Home, View and Help, or+ // Message while writing (MailMsCompose.dc).+ ColumnLayout {+ Layout.fillWidth: true+ Layout.leftMargin: 16+ Layout.rightMargin: 12+ spacing: 2+ // Nothing on the ribbon works without an account.+ visible: !window.showSettings && MailEngine.hasAccounts++ Row {+ id: tabs+ property string current: "home"+ leftPadding: 4+ spacing: 22++ Repeater {+ model: window.composing ? [{ id: "message", name: qsTr("Message") }]+ : [{ id: "home", name: qsTr("Home") }, { id: "view", name: qsTr("View") }, { id: "help", name: qsTr("Help") }]+ delegate: Item {+ id: tab+ required property var modelData+ readonly property bool active: window.composing || tabs.current === modelData.id+ width: tabLabel.implicitWidth + 4+ height: 36++ UI.Label {+ id: tabLabel+ anchors.centerIn: parent+ text: tab.modelData.name+ size: 13+ font.weight: tab.active ? Font.DemiBold : Font.Normal+ color: tab.active ? UI.Style.ink : UI.Style.inkMuted+ }+ Rectangle {+ visible: tab.active+ anchors.left: parent.left+ anchors.right: parent.right+ anchors.bottom: parent.bottom+ anchors.bottomMargin: 4+ height: 2+ radius: 1+ color: UI.Style.accent+ }+ MouseArea {+ anchors.fill: parent+ cursorShape: Qt.PointingHandCursor+ onClicked: tabs.current = tab.modelData.id+ }+ }+ }+ }++ Rectangle {+ Layout.fillWidth: true+ implicitHeight: 46+ radius: 10+ color: UI.Style.surfaceRest+ border.width: 1+ border.color: UI.Style.borderSubtle+ clip: true++ // Home+ RowLayout {+ visible: !window.composing && tabs.current === "home"+ anchors.fill: parent+ anchors.leftMargin: 8+ anchors.rightMargin: 8+ spacing: 2+++ UI.Button {+ kind: "primary"+ size: "small"+ text: qsTr("New mail")+ iconName: "pencil"+ enabled: MailEngine.hasAccounts+ Layout.rightMargin: 6+ onClicked: window.compose({})+ }+ CommandButton {+ text: qsTr("Delete")+ iconName: "trash"+ enabled: MailEngine.selection.length > 0+ onClicked: MailEngine.removeKeys(MailEngine.selection)+ }+ CommandButton {+ text: qsTr("Archive")+ iconName: "archive"+ enabled: MailEngine.selection.length > 0+ onClicked: MailEngine.archiveKeys(MailEngine.selection)+ }+ CommandButton {+ text: MailEngine.folderRole === "junk" ? qsTr("Not junk") : qsTr("Report")+ iconName: "report"+ enabled: MailEngine.selection.length > 0+ onClicked: MailEngine.folderRole === "junk" ? MailEngine.notJunk(MailEngine.selected) : MailEngine.junkKeys(MailEngine.selection)+ }+ Rectangle {+ implicitWidth: 1+ implicitHeight: 22+ Layout.leftMargin: 6+ Layout.rightMargin: 6+ color: UI.Style.borderSubtle+ }+ CommandButton {+ id: moveButton+ text: qsTr("Move to")+ iconName: "move"+ enabled: MailEngine.selection.length > 0+ onClicked: moveMenu.openFor(moveButton)+ }+ Rectangle {+ implicitWidth: 1+ implicitHeight: 22+ Layout.leftMargin: 6+ Layout.rightMargin: 6+ color: UI.Style.borderSubtle+ }+ CommandButton {+ text: qsTr("Reply")+ iconName: "reply"+ enabled: MailEngine.selection.length > 0+ onClicked: window.reply("reply")+ }+ CommandButton {+ text: qsTr("Reply all")+ iconName: "reply-all"+ enabled: MailEngine.selection.length > 0+ onClicked: window.reply("replyAll")+ }+ CommandButton {+ text: qsTr("Forward")+ iconName: "forward"+ enabled: MailEngine.selection.length > 0+ onClicked: window.reply("forward")+ }+ Rectangle {+ implicitWidth: 1+ implicitHeight: 22+ Layout.leftMargin: 6+ Layout.rightMargin: 6+ color: UI.Style.borderSubtle+ }+ CommandButton {+ text: qsTr("Read or unread")+ iconName: "read-unread"+ enabled: MailEngine.selection.length > 0+ onClicked: window.toggleReadSelection()+ }+ CommandButton {+ text: qsTr("Flag")+ iconName: "flag"+ enabled: MailEngine.selection.length > 0+ onClicked: window.toggleFlagSelection()+ }+ CommandButton {+ text: qsTr("Pin")+ iconName: "pin"+ enabled: MailEngine.selection.length > 0+ onClicked: MailEngine.togglePin(MailEngine.selected)+ }+ CommandButton {+ text: qsTr("Snooze")+ iconName: "clock"+ enabled: MailEngine.selection.length > 0+ menu: snoozeMenu+ }+ Item {+ Layout.fillWidth: true+ }+ CommandButton {+ iconOnly: true+ iconName: "refresh"+ tip: qsTr("Check for new mail")+ onClicked: MailEngine.refresh()+ }+ }++ // View+ RowLayout {+ visible: !window.composing && tabs.current === "view"+ anchors.fill: parent+ anchors.leftMargin: 8+ anchors.rightMargin: 8+ spacing: 2++ CommandButton {+ text: prefs.readingPane === "off" ? qsTr("Reading pane: off") : qsTr("Reading pane: on the right")+ iconName: "layout"+ onClicked: prefs.readingPane = prefs.readingPane === "off" ? "right" : "off"+ }+ CommandButton {+ text: MailEngine.messages.conversations ? qsTr("Conversations: on") : qsTr("Conversations: off")+ iconName: "list"+ onClicked: MailEngine.messages.conversations = !MailEngine.messages.conversations+ }+ CommandButton {+ text: qsTr("Filter")+ iconName: "filter"+ menu: viewFilterMenu+ }+ Item {+ Layout.fillWidth: true+ }+ }++ // Help+ RowLayout {+ visible: !window.composing && tabs.current === "help"+ anchors.fill: parent+ anchors.leftMargin: 8+ anchors.rightMargin: 8+ spacing: 2++ CommandButton {+ text: qsTr("Help with Mail")+ iconName: "question"+ onClicked: Qt.openUrlExternally("https://help.wildos.io/using/mail/")+ }+ CommandButton {+ text: qsTr("Keyboard shortcuts")+ iconName: "font"+ onClicked: shortcutsDialog.open()+ }+ CommandButton {+ text: qsTr("Send feedback")+ iconName: "send"+ onClicked: Qt.openUrlExternally("https://github.com/wildorigins/wildos/discussions")+ }+ Item {+ Layout.fillWidth: true+ }+ }++ // Message, while writing+ RowLayout {+ visible: window.composing+ anchors.fill: parent+ anchors.leftMargin: 8+ anchors.rightMargin: 8+ spacing: 2++ CommandButton {+ iconOnly: true+ iconName: "bold"+ tip: qsTr("Bold")+ onClicked: composePane.formatter.toggleBold()+ }+ CommandButton {+ iconOnly: true+ iconName: "italic"+ tip: qsTr("Italic")+ onClicked: composePane.formatter.toggleItalic()+ }+ CommandButton {+ iconOnly: true+ iconName: "underline"+ tip: qsTr("Underline")+ onClicked: composePane.formatter.toggleUnderline()+ }+ CommandButton {+ iconOnly: true+ iconName: "bullets"+ tip: qsTr("Bullets")+ onClicked: composePane.formatter.bullets()+ }+ CommandButton {+ iconOnly: true+ iconName: "numbering"+ tip: qsTr("Numbering")+ onClicked: composePane.formatter.numbering()+ }+ Rectangle {+ implicitWidth: 1+ implicitHeight: 22+ Layout.leftMargin: 6+ Layout.rightMargin: 6+ color: UI.Style.borderSubtle+ }+ CommandButton {+ text: qsTr("Attach file")+ iconName: "paperclip"+ onClicked: composePane.attach()+ }+ CommandButton {+ text: qsTr("Link")+ iconName: "link"+ onClicked: linkDialog.open()+ }+ CommandButton {+ text: qsTr("Signature")+ iconName: "signature"+ onClicked: window.insertSignature()+ }+ Item {+ Layout.fillWidth: true+ }+ }+ }+ }++ RowLayout {+ Layout.fillWidth: true+ Layout.fillHeight: true+ Layout.rightMargin: 12+ spacing: 10++ FolderPane {+ Layout.preferredWidth: 236+ Layout.fillHeight: true+ visible: MailEngine.hasAccounts && !window.showSettings+ onAddAccount: addAccount.open()+ onCreateFolder: function (accountId) {+ newFolderDialog.ask(accountId);+ }+ onOpenPrivacy: {+ settingsPage.section = "privacy";+ window.showSettings = true;+ }+ onFolderMenu: function (accountId, fullName, name, role) {+ folderMenu.accountId = accountId;+ folderMenu.fullName = fullName;+ folderMenu.name = name;+ folderMenu.role = role;+ folderMenu.popup();+ }+ onCrossAccount: toast.show(qsTr("Messages can only be moved within the same account."))+ }++ MessageList {+ id: messageList+ Layout.preferredWidth: prefs.readingPane === "off" && !window.composing ? -1 : 392+ Layout.fillWidth: prefs.readingPane === "off" && !window.composing && !MailEngine.selected+ Layout.fillHeight: true+ visible: MailEngine.hasAccounts && !window.showSettings && !(prefs.readingPane === "off" && MailEngine.selected && !window.composing)+ onContextMenu: function (key, x, y) {+ messageMenu.popup();+ }+ onOpenMessage: function (key) {+ window.openMessage(key);+ }+ }++ ReadingPane {+ id: readingPane+ Layout.fillWidth: true+ Layout.fillHeight: true+ visible: MailEngine.hasAccounts && !window.composing && !window.showSettings+ && (prefs.readingPane !== "off" || MailEngine.selected.length > 0)+ onReply: function (mode) {+ window.reply(mode);+ }+ onMoreMenu: function (x, y, from) {+ messageMenu.popup(from, x, y);+ }+ onOpenLink: function (url) {+ window.openLink(url);+ }+ onSaved: function (path) {+ toast.show(qsTr("Saved to %1").arg(path));+ }+ }++ ComposePane {+ id: composePane+ Layout.fillWidth: true+ Layout.fillHeight: true+ visible: window.composing && !window.showSettings+ onClosed: window.composing = false+ onProblem: function (text) {+ toast.show(text);+ }+ onSentMessage: toast.show(MailEngine.online ? qsTr("Sending") : qsTr("Saved in the Outbox. It goes when you're back online."))+ }++ SettingsPage {+ id: settingsPage+ Layout.fillWidth: true+ Layout.fillHeight: true+ visible: window.showSettings+ readingPane: prefs.readingPane+ onReadingPaneChanged: prefs.readingPane = readingPane+ onCloseRequested: window.showSettings = false+ onAddAccount: addAccount.open()+ onSignIn: function (accountId) {+ signInDialog.ask(accountId);+ }+ }++ // No account yet.+ Item {+ Layout.fillWidth: true+ Layout.fillHeight: true+ visible: !MailEngine.hasAccounts && !window.showSettings++ ColumnLayout {+ anchors.centerIn: parent+ width: Math.min(460, parent.width - 48)+ spacing: 12+ MailIcon {+ Layout.alignment: Qt.AlignHCenter+ name: "mail"+ size: 56+ strokeWidth: 1.2+ color: UI.Style.accent+ }+ UI.Label {+ Layout.alignment: Qt.AlignHCenter+ text: qsTr("Bring your mail to Wild OS")+ size: 22+ font.weight: Font.DemiBold+ }+ UI.Label {+ Layout.fillWidth: true+ horizontalAlignment: Text.AlignHCenter+ wrapMode: Text.WordWrap+ text: qsTr("Your mail stays with your provider and on this PC. Pictures that track you are blocked, and nothing runs inside a message.")+ size: 13+ color: UI.Style.inkMuted+ }+ UI.Button {+ Layout.alignment: Qt.AlignHCenter+ Layout.topMargin: 8+ kind: "primary"+ size: "large"+ text: qsTr("Add an account")+ onClicked: addAccount.open()+ }+ }+ }+ }+ }+ }+ }++ AddAccount {+ id: addAccount+ }++ UI.Menu {+ id: messageMenu+ entries: {+ const k = MailEngine.selected;+ const keys = MailEngine.selection;+ const several = keys.length > 1;+ return several ? [+ { text: qsTr("Mark as read"), run: () => MailEngine.setReadKeys(keys, true) },+ { text: qsTr("Mark as unread"), run: () => MailEngine.setReadKeys(keys, false) },+ { text: qsTr("Flag"), run: () => MailEngine.setFlaggedKeys(keys, true) },+ { separator: true },+ { text: qsTr("Archive"), run: () => MailEngine.archiveKeys(keys) },+ { text: qsTr("Move to"), submenu: moveEntries() },+ { text: qsTr("Report as junk"), run: () => MailEngine.junkKeys(keys) },+ { separator: true },+ { text: qsTr("Delete %1 messages").arg(keys.length), icon: "delete", danger: true, run: () => MailEngine.removeKeys(keys) }+ ] : [+ { text: qsTr("Open in a new window"), icon: "external", run: () => window.openMessage(k) },+ { separator: true },+ { text: qsTr("Reply"), icon: "back", run: () => window.reply("reply") },+ { text: qsTr("Reply all"), run: () => window.reply("replyAll") },+ { text: qsTr("Forward"), icon: "forward", run: () => window.reply("forward") },+ { separator: true },+ { text: qsTr("Read or unread"), run: () => MailEngine.toggleRead(k) },+ { text: qsTr("Flag"), run: () => MailEngine.toggleFlag(k) },+ { text: qsTr("Pin"), icon: "pin", run: () => MailEngine.togglePin(k) },+ { text: qsTr("Snooze"), submenu: snoozeEntries() },+ { separator: true },+ { text: qsTr("Archive"), run: () => MailEngine.archiveKeys([k]) },+ { text: qsTr("Move to"), submenu: moveEntries() },+ { text: MailEngine.folderRole === "junk" ? qsTr("Not junk") : qsTr("Report as junk"), run: () => MailEngine.folderRole === "junk" ? MailEngine.notJunk(k) : MailEngine.reportJunk(k) },+ { separator: true },+ { text: qsTr("Delete"), icon: "delete", danger: true, run: () => MailEngine.removeKeys([k]) }+ ];+ }+ }++ function snoozeEntries() {+ return [+ { text: qsTr("Later today"), run: () => MailEngine.snooze(MailEngine.selected, snoozeUntil("later")) },+ { text: qsTr("Tomorrow"), run: () => MailEngine.snooze(MailEngine.selected, snoozeUntil("tomorrow")) },+ { text: qsTr("This weekend"), run: () => MailEngine.snooze(MailEngine.selected, snoozeUntil("weekend")) },+ { text: qsTr("Next week"), run: () => MailEngine.snooze(MailEngine.selected, snoozeUntil("week")) }+ ];+ }+ function moveEntries() {+ const account = MailEngine.accountForKey(MailEngine.selected);+ const here = MailEngine.selected.split("\x1f")[1];+ return MailEngine.moveTargets(account).filter(f => f.fullName !== here).map(f => ({ text: " ".repeat(Math.max(0, f.depth)) + f.name, run: () => MailEngine.moveKeys(MailEngine.selection, f.fullName) }));+ }++ UI.Menu {+ id: folderMenu+ property string accountId+ property string fullName+ property string name+ property string role+ readonly property bool special: role !== "folder"+ entries: [+ { text: qsTr("Mark all as read"), run: () => MailEngine.markFolderRead(folderMenu.accountId, folderMenu.fullName) },+ { text: qsTr("Empty folder"), visible: true, enabled: role === "trash" || role === "junk", run: () => emptyConfirm.ask(folderMenu.accountId, folderMenu.fullName, folderMenu.name) },+ { separator: true },+ { text: qsTr("Create new folder"), icon: "new-folder", run: () => newFolderDialog.ask(folderMenu.accountId) },+ { text: qsTr("Rename"), enabled: !special, run: () => renameDialog.ask(folderMenu.accountId, folderMenu.fullName, folderMenu.name) },+ { text: qsTr("Delete folder"), icon: "delete", danger: true, enabled: !special, run: () => deleteFolderConfirm.ask(folderMenu.accountId, folderMenu.fullName, folderMenu.name) }+ ]+ }++ UI.Dialog {+ id: renameDialog+ property string accountId+ property string fullName+ function ask(account, full, name) {+ accountId = account;+ fullName = full;+ renameField.text = name;+ open();+ renameField.forceActiveFocus();+ renameField.selectAll();+ }+ title: qsTr("Rename folder")+ UI.TextField {+ id: renameField+ Layout.fillWidth: true+ onAccepted: renameButton.clicked()+ }+ buttons: [+ UI.Button {+ text: qsTr("Cancel")+ onClicked: renameDialog.close()+ },+ UI.Button {+ id: renameButton+ kind: "primary"+ text: qsTr("Rename")+ enabled: renameField.text.trim().length > 0 && renameField.text.indexOf("/") < 0+ onClicked: {+ MailEngine.renameFolder(renameDialog.accountId, renameDialog.fullName, renameField.text);+ renameDialog.close();+ }+ }+ ]+ }++ UI.Dialog {+ id: deleteFolderConfirm+ property string accountId+ property string fullName+ property string name+ function ask(account, full, n) {+ accountId = account;+ fullName = full;+ name = n;+ open();+ }+ title: qsTr("Delete %1?").arg(name)+ text: qsTr("The folder and the mail in it are deleted from your email provider too. This can't be undone.")+ iconName: "warning"+ buttons: [+ UI.Button {+ text: qsTr("Cancel")+ onClicked: deleteFolderConfirm.close()+ },+ UI.Button {+ kind: "primary"+ danger: true+ text: qsTr("Delete folder")+ onClicked: {+ MailEngine.deleteFolder(deleteFolderConfirm.accountId, deleteFolderConfirm.fullName);+ deleteFolderConfirm.close();+ }+ }+ ]+ }++ UI.Dialog {+ id: emptyConfirm+ property string accountId+ property string fullName+ property string name+ function ask(account, full, n) {+ accountId = account;+ fullName = full;+ name = n;+ open();+ }+ title: qsTr("Empty %1?").arg(name)+ text: qsTr("Everything in it is deleted for good, from your email provider too.")+ iconName: "warning"+ buttons: [+ UI.Button {+ text: qsTr("Cancel")+ onClicked: emptyConfirm.close()+ },+ UI.Button {+ kind: "primary"+ danger: true+ text: qsTr("Empty")+ onClicked: {+ MailEngine.emptyFolder(emptyConfirm.accountId, emptyConfirm.fullName);+ emptyConfirm.close();+ }+ }+ ]+ }++ UI.Menu {+ id: snoozeMenu+ entries: window.snoozeEntries()+ }+ UI.Menu {+ id: moveMenu+ function openFor(item) {+ entries = window.moveEntries();+ popup(item, 0, item.height + 4);+ }+ }+ UI.Menu {+ id: viewFilterMenu+ entries: [+ { text: qsTr("All"), radio: true, checked: MailEngine.messages.filter === "all", run: () => MailEngine.messages.filter = "all" },+ { text: qsTr("Unread"), radio: true, checked: MailEngine.messages.filter === "unread", run: () => MailEngine.messages.filter = "unread" },+ { text: qsTr("Flagged"), radio: true, checked: MailEngine.messages.filter === "flagged", run: () => MailEngine.messages.filter = "flagged" },+ { text: qsTr("Has attachments"), radio: true, checked: MailEngine.messages.filter === "attachments", run: () => MailEngine.messages.filter = "attachments" }+ ]+ }++ // A link in a message opens in the browser after one look at where it+ // really goes: the words of a link and its address can disagree.+ UI.Dialog {+ id: linkConfirm+ property string url+ function ask(u) {+ url = u;+ open();+ }+ title: qsTr("Open this link?")+ text: url+ iconName: "external"+ buttons: [+ UI.Button {+ text: qsTr("Cancel")+ onClicked: linkConfirm.close()+ },+ UI.Button {+ kind: "primary"+ text: qsTr("Open")+ onClicked: {+ Qt.openUrlExternally(linkConfirm.url);+ linkConfirm.close();+ }+ }+ ]+ }++ UI.Dialog {+ id: newFolderDialog+ property string accountId+ function ask(id) {+ accountId = id;+ folderName.text = "";+ open();+ folderName.forceActiveFocus();+ }+ title: qsTr("Create new folder")+ UI.TextField {+ id: folderName+ Layout.fillWidth: true+ placeholderText: qsTr("Folder name")+ onAccepted: createButton.clicked()+ }+ buttons: [+ UI.Button {+ text: qsTr("Cancel")+ onClicked: newFolderDialog.close()+ },+ UI.Button {+ id: createButton+ kind: "primary"+ text: qsTr("Create")+ enabled: folderName.text.trim().length > 0+ onClicked: {+ MailEngine.createFolder(newFolderDialog.accountId, folderName.text);+ newFolderDialog.close();+ }+ }+ ]+ }++ UI.Dialog {+ id: signInDialog+ property string accountId+ // An account signed in with Google signs in again on Google's page.+ property string googleAccount+ function ask(id) {+ const account = MailEngine.account(id);+ if (account.auth === "google") {+ googleAccount = id;+ GoogleSignIn.start(account.email);+ toast.show(qsTr("Sign in on Google's page in your browser."));+ return;+ }+ accountId = id;+ signInPassword.text = "";+ open();+ signInPassword.forceActiveFocus();+ }+ title: qsTr("Sign in again")+ text: qsTr("Type the password for %1. For Gmail, iCloud, Yahoo and Fastmail, that's an app password.").arg(MailEngine.account(accountId).email || "")+ UI.TextField {+ id: signInPassword+ Layout.fillWidth: true+ revealable: true+ onAccepted: signInButton.clicked()+ }+ buttons: [+ UI.Button {+ text: qsTr("Cancel")+ onClicked: signInDialog.close()+ },+ UI.Button {+ id: signInButton+ kind: "primary"+ text: qsTr("Sign in")+ enabled: signInPassword.text.length > 0+ onClicked: {+ MailEngine.signInAgain(signInDialog.accountId, signInPassword.text);+ signInPassword.text = "";+ signInDialog.close();+ }+ }+ ]+ }++ UI.Dialog {+ id: linkDialog+ title: qsTr("Insert link")+ UI.TextField {+ id: linkUrl+ Layout.fillWidth: true+ placeholderText: "https://"+ }+ buttons: [+ UI.Button {+ text: qsTr("Cancel")+ onClicked: linkDialog.close()+ },+ UI.Button {+ kind: "primary"+ text: qsTr("Insert")+ enabled: linkUrl.text.trim().length > 0+ onClicked: {+ let u = linkUrl.text.trim();+ if (!/^[a-z]+:/i.test(u)) {+ u = "https://" + u;+ }+ composePane.formatter.insertLink(u, "");+ linkUrl.text = "";+ linkDialog.close();+ }+ }+ ]+ }++ UI.Dialog {+ id: shortcutsDialog+ title: qsTr("Keyboard shortcuts")+ text: qsTr("New mail: Ctrl+N\nReply: Ctrl+R\nReply all: Ctrl+Shift+R\nForward: Ctrl+Shift+F\nSend: Ctrl+Enter\nSearch: Ctrl+E\nMark as read: Ctrl+Q\nMark as unread: Ctrl+U\nArchive: Backspace\nDelete: Delete\nCheck for new mail: F5")+ buttons: [+ UI.Button {+ kind: "primary"+ text: qsTr("Close")+ onClicked: shortcutsDialog.close()+ }+ ]+ }++ UI.Toast {+ id: toast+ onActionClicked: MailEngine.undo()+ anchors.horizontalCenter: parent.horizontalCenter+ anchors.bottom: parent.bottom+ anchors.bottomMargin: 24+ z: 60+ }++ Component.onCompleted: {+ if (MailEngine.hasAccounts) {+ MailEngine.openFolder("", "inbox");+ }+ }+}diff --git a/packages/wildos-mail/qml/MessageList.qml b/packages/wildos-mail/qml/MessageList.qmlnew file mode 100644index 0000000..742b1b5--- /dev/null+++ b/packages/wildos-mail/qml/MessageList.qml@@ -0,0 +1,227 @@+import QtQuick+import QtQuick.Controls as QQC+import QtQuick.Layouts+import WildOS.Mail+import WildOS.UI as UI++// The message list (MailMicrosoft.dc, 392px): the folder's name and the+// filter button over one list, newest first, grouped by day. No Focused+// and Other, and no conversations unless they are turned on in Settings.+Rectangle {+ id: pane++ signal contextMenu(string key, real x, real y)+ signal openMessage(string key)+ readonly property bool listFocused: list.activeFocus++ radius: 10+ color: UI.Style.surfaceRest+ border.width: 1+ border.color: UI.Style.borderSubtle+ clip: true++ readonly property bool inSearch: MailEngine.searching++ function moveSelection(step) {+ const count = list.count;+ if (count === 0) {+ return;+ }+ let i = MailEngine.messages.indexOf(MailEngine.selected);+ i = Math.max(0, Math.min(count - 1, i < 0 ? 0 : i + step));+ MailEngine.selected = MailEngine.messages.keyAt(i);+ list.positionViewAtIndex(i, ListView.Contain);+ }++ ColumnLayout {+ anchors.fill: parent+ spacing: 0++ RowLayout {+ Layout.fillWidth: true+ Layout.preferredHeight: 44+ Layout.leftMargin: 16+ Layout.rightMargin: 10+ spacing: 8++ UI.Label {+ text: MailEngine.folderTitle+ size: 16+ font.weight: Font.DemiBold+ elide: Text.ElideRight+ Layout.maximumWidth: pane.width - 120+ }+ UI.Label {+ visible: pane.inSearch+ text: MailEngine.messages.count === 1 ? qsTr("1 message") : qsTr("%1 messages").arg(MailEngine.messages.count)+ size: 12+ color: UI.Style.inkMuted+ }+ UI.Spinner {+ visible: MailEngine.loading+ size: 14+ }+ Item {+ Layout.fillWidth: true+ }+ CommandButton {+ iconOnly: true+ iconName: "filter"+ tip: qsTr("Filter")+ menu: filterMenu+ }+ }++ Rectangle {+ Layout.fillWidth: true+ Layout.leftMargin: 16+ Layout.rightMargin: 16+ implicitHeight: 1+ color: UI.Style.borderSubtle+ }++ // Filtering keeps a chip on show, so a filtered list is never+ // mistaken for an empty folder.+ RowLayout {+ visible: MailEngine.messages.filter !== "all"+ Layout.fillWidth: true+ Layout.leftMargin: 16+ Layout.rightMargin: 16+ Layout.topMargin: 8++ UI.Chip {+ text: MailEngine.messages.filter === "unread" ? qsTr("Unread") : MailEngine.messages.filter === "flagged" ? qsTr("Flagged") : qsTr("Has attachments")+ }+ UI.LinkButton {+ text: qsTr("Show all")+ onClicked: MailEngine.messages.filter = "all"+ }+ Item {+ Layout.fillWidth: true+ }+ }++ ListView {+ id: list+ Layout.fillWidth: true+ Layout.fillHeight: true+ Layout.topMargin: 2+ clip: true+ model: MailEngine.messages+ boundsBehavior: Flickable.StopAtBounds+ keyNavigationEnabled: false+ activeFocusOnTab: true+ reuseItems: true+ QQC.ScrollBar.vertical: UI.ScrollBar {}++ Keys.onUpPressed: pane.moveSelection(-1)+ Keys.onDownPressed: pane.moveSelection(1)+ Keys.onDeletePressed: if (MailEngine.selection.length > 0) MailEngine.removeKeys(MailEngine.selection)+ Keys.onReturnPressed: if (MailEngine.selected) pane.openMessage(MailEngine.selected)+ Keys.onPressed: function (event) {+ if ((event.modifiers & Qt.ControlModifier) && event.key === Qt.Key_A) {+ MailEngine.selectAll();+ event.accepted = true;+ }+ }++ section.property: pane.inSearch ? "" : "section"+ section.criteria: ViewSection.FullString+ section.delegate: Item {+ required property string section+ width: list.width+ height: 32++ UI.Label {+ anchors.left: parent.left+ anchors.leftMargin: 16+ anchors.bottom: parent.bottom+ anchors.bottomMargin: 4+ text: parent.section+ size: 12+ font.weight: Font.DemiBold+ color: UI.Style.inkMuted+ }+ }++ delegate: MessageRowItem {+ width: list.width+ showFolder: pane.inSearch+ highlight: pane.inSearch ? MailEngine.searchText : ""+ onSelected: function (key) {+ MailEngine.selected = key;+ list.forceActiveFocus();+ }+ onMenuRequested: function (key, x, y) {+ pane.contextMenu(key, x, y);+ }+ onOpenRequested: function (key) {+ pane.openMessage(key);+ }+ }++ footer: Item {+ width: list.width+ height: pane.inSearch && list.count > 0 ? 44 : 8++ RowLayout {+ visible: pane.inSearch && list.count > 0+ anchors.centerIn: parent+ spacing: 6++ MailIcon {+ name: "lock"+ size: 13+ color: UI.Style.inkMuted+ }+ UI.Label {+ text: qsTr("Searched on this PC. Nothing is sent anywhere.")+ size: 12+ color: UI.Style.inkMuted+ }+ }+ }+ }+ }++ // Nothing in the folder (MailMsStates.dc).+ ColumnLayout {+ anchors.centerIn: parent+ anchors.verticalCenterOffset: 20+ visible: list.count === 0 && !MailEngine.loading && MailEngine.hasAccounts+ width: pane.width - 64+ spacing: 8++ Image {+ Layout.alignment: Qt.AlignHCenter+ visible: !pane.inSearch && MailEngine.messages.filter === "all"+ source: "qrc:/qt/qml/WildOS/Mail/data/caught-up.svg"+ sourceSize: Qt.size(120, 96)+ }+ UI.Label {+ Layout.alignment: Qt.AlignHCenter+ text: pane.inSearch ? qsTr("Nothing found") : MailEngine.messages.filter !== "all" ? qsTr("Nothing here") : MailEngine.folderRole === "inbox" ? qsTr("You're all caught up") : qsTr("This folder is empty")+ size: 15+ font.weight: Font.DemiBold+ }+ UI.Label {+ Layout.fillWidth: true+ horizontalAlignment: Text.AlignHCenter+ wrapMode: Text.WordWrap+ text: pane.inSearch ? qsTr("Try another word, or part of a name or address.") : MailEngine.folderRole === "inbox" && MailEngine.messages.filter === "all" ? qsTr("No new mail. Enjoy the quiet.") : ""+ visible: text.length > 0+ size: 13+ color: UI.Style.inkMuted+ }+ }++ UI.Menu {+ id: filterMenu+ entries: [+ { text: qsTr("All"), radio: true, checked: MailEngine.messages.filter === "all", run: () => MailEngine.messages.filter = "all" },+ { text: qsTr("Unread"), radio: true, checked: MailEngine.messages.filter === "unread", run: () => MailEngine.messages.filter = "unread" },+ { text: qsTr("Flagged"), radio: true, checked: MailEngine.messages.filter === "flagged", run: () => MailEngine.messages.filter = "flagged" },+ { text: qsTr("Has attachments"), radio: true, checked: MailEngine.messages.filter === "attachments", run: () => MailEngine.messages.filter = "attachments" }+ ]+ }+}diff --git a/packages/wildos-mail/qml/MessageRowItem.qml b/packages/wildos-mail/qml/MessageRowItem.qmlnew file mode 100644index 0000000..b1fb6f1--- /dev/null+++ b/packages/wildos-mail/qml/MessageRowItem.qml@@ -0,0 +1,290 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Mail+import WildOS.UI as UI++// One message in the list (MailMicrosoft.dc): the sender's initials, name,+// subject and time, and a line of preview. Unread mail is bold with its+// subject and time in the accent and a bar at the left edge.+Item {+ id: row++ required property int index+ required property string key+ required property string from+ required property string initials+ required property int avatar+ required property string subject+ required property string preview+ required property string time+ required property bool unread+ required property bool flagged+ required property bool pinned+ required property bool attachment+ required property bool draft+ required property string folderName+ required property int threadCount++ property bool showFolder: false+ property string highlight++ signal selected(string key)+ signal menuRequested(string key, real x, real y)+ signal openRequested(string key)++ readonly property bool current: MailEngine.selection.indexOf(key) >= 0+ readonly property bool hovered: mouse.containsMouse || actions.hovered++ // Wraps each match in the search in bold (MailMsSearch.dc).+ function marked(text) {+ const plain = text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");+ if (highlight.length === 0) {+ return plain;+ }+ const escaped = highlight.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");+ return plain.replace(new RegExp("(" + escaped + ")", "ig"), "<b>$1</b>");+ }++ implicitHeight: content.implicitHeight + 18++ Rectangle {+ anchors.fill: parent+ anchors.leftMargin: 6+ anchors.rightMargin: 6+ radius: 6+ color: row.current ? UI.Style.accentSelected : mouse.containsMouse ? UI.Style.surfaceHover : "transparent"++ Rectangle {+ visible: row.unread+ x: 0+ y: 8+ width: 3+ height: parent.height - 16+ radius: 2+ color: UI.Style.accent+ }+ }++ // What a dragged message carries to a folder: every selected message+ // if it is one of them, otherwise just itself.+ Item {+ id: dragProxy+ width: 1+ height: 1+ property bool dragging: false+ Drag.active: dragging+ Drag.keys: ["wildos-mail-messages"]+ Drag.mimeData: ({ "text/plain": row.subject })+ Drag.hotSpot.x: 0+ Drag.hotSpot.y: 0+ property var keys: MailEngine.selection.indexOf(row.key) >= 0 ? MailEngine.selection : [row.key]+ }++ MouseArea {+ id: mouse+ anchors.fill: parent+ hoverEnabled: true+ acceptedButtons: Qt.LeftButton | Qt.RightButton+ // Without this the list takes the pointer to scroll, and a message+ // can't be dragged to a folder.+ preventStealing: true+ property point pressedAt+ onPressed: function (event) {+ pressedAt = Qt.point(event.x, event.y);+ }+ // The dragged point follows the pointer exactly, so the folder under+ // the pointer is the one that takes the drop.+ onPositionChanged: function (event) {+ if (!pressed) {+ return;+ }+ dragProxy.x = event.x;+ dragProxy.y = event.y;+ if (!dragProxy.dragging && Math.abs(event.x - pressedAt.x) + Math.abs(event.y - pressedAt.y) > 10) {+ dragProxy.dragging = true;+ }+ }+ onReleased: {+ if (dragProxy.dragging) {+ dragProxy.Drag.drop();+ dragProxy.dragging = false;+ }+ }+ onCanceled: dragProxy.dragging = false+ onClicked: function (event) {+ if (dragProxy.dragging) {+ return;+ }+ if (event.button === Qt.RightButton) {+ if (MailEngine.selection.indexOf(row.key) < 0) {+ row.selected(row.key);+ }+ row.menuRequested(row.key, event.x, event.y);+ } else if (event.modifiers & Qt.ControlModifier) {+ MailEngine.toggleSelect(row.key);+ } else if (event.modifiers & Qt.ShiftModifier) {+ MailEngine.extendSelect(row.key);+ } else {+ row.selected(row.key);+ }+ }+ onDoubleClicked: function (event) {+ if (event.button === Qt.LeftButton) {+ row.openRequested(row.key);+ }+ }+ }++ // Outlook's quick actions, shown while the pointer is over the message.+ Row {+ id: actions+ property bool hovered: hoverActions.hovered+ visible: row.hovered && !row.draft+ z: 2+ anchors.right: parent.right+ anchors.rightMargin: 14+ anchors.top: parent.top+ anchors.topMargin: 6+ spacing: 2++ HoverHandler {+ id: hoverActions+ }+ Rectangle {+ width: actionRow.implicitWidth + 4+ height: 30+ radius: 7+ color: UI.Style.windowOpaque+ border.width: 1+ border.color: UI.Style.borderSubtle++ Row {+ id: actionRow+ anchors.centerIn: parent+ spacing: 0+ CommandButton {+ iconOnly: true+ iconName: "trash"+ tip: qsTr("Delete")+ implicitWidth: 28+ implicitHeight: 26+ onClicked: MailEngine.removeKeys([row.key])+ }+ CommandButton {+ iconOnly: true+ iconName: "read-unread"+ tip: row.unread ? qsTr("Mark as read") : qsTr("Mark as unread")+ implicitWidth: 28+ implicitHeight: 26+ onClicked: MailEngine.setReadKeys([row.key], row.unread)+ }+ CommandButton {+ iconOnly: true+ iconName: "flag"+ tip: row.flagged ? qsTr("Clear flag") : qsTr("Flag")+ implicitWidth: 28+ implicitHeight: 26+ onClicked: MailEngine.setFlaggedKeys([row.key], !row.flagged)+ }+ CommandButton {+ iconOnly: true+ iconName: "pin"+ tip: row.pinned ? qsTr("Unpin") : qsTr("Pin")+ implicitWidth: 28+ implicitHeight: 26+ onClicked: MailEngine.togglePin(row.key)+ }+ }+ }+ }++ RowLayout {+ id: content+ anchors.left: parent.left+ anchors.right: parent.right+ anchors.top: parent.top+ anchors.leftMargin: 20+ anchors.rightMargin: 18+ anchors.topMargin: 9+ spacing: 11++ SenderBadge {+ Layout.alignment: Qt.AlignTop+ initials: row.initials+ colourIndex: row.avatar+ }++ ColumnLayout {+ Layout.fillWidth: true+ spacing: 1++ RowLayout {+ Layout.fillWidth: true+ spacing: 6++ UI.Label {+ Layout.fillWidth: true+ text: row.draft ? qsTr("[Draft] ") + row.from : row.from+ size: 13.5+ font.weight: row.unread ? Font.DemiBold : Font.Normal+ color: row.draft ? UI.Style.danger : UI.Style.ink+ elide: Text.ElideRight+ }+ UI.Label {+ visible: row.threadCount > 1+ text: row.threadCount+ size: 11.5+ color: UI.Style.inkMuted+ }+ MailIcon {+ visible: row.pinned+ name: "pin"+ size: 14+ color: UI.Style.inkMuted+ }+ MailIcon {+ visible: row.attachment+ name: "paperclip"+ size: 14+ color: UI.Style.inkMuted+ }+ MailIcon {+ visible: row.flagged+ name: "flag"+ size: 14+ color: UI.Style.danger+ }+ }++ RowLayout {+ Layout.fillWidth: true+ spacing: 8++ UI.Label {+ Layout.fillWidth: true+ text: row.marked(row.subject)+ textFormat: Text.StyledText+ size: 13+ font.weight: row.unread ? Font.DemiBold : Font.Normal+ color: row.unread ? UI.Style.accent : UI.Style.ink+ elide: Text.ElideRight+ }+ UI.Label {+ text: row.time+ size: 12+ color: row.unread ? UI.Style.accent : UI.Style.inkMuted+ }+ }++ UI.Label {+ Layout.fillWidth: true+ visible: text.length > 0+ text: row.showFolder ? row.folderName + " " + row.preview : row.preview+ size: 12.5+ color: UI.Style.inkMuted+ elide: Text.ElideRight+ maximumLineCount: 1+ }+ }+ }+}diff --git a/packages/wildos-mail/qml/MessageWindow.qml b/packages/wildos-mail/qml/MessageWindow.qmlnew file mode 100644index 0000000..4469826--- /dev/null+++ b/packages/wildos-mail/qml/MessageWindow.qml@@ -0,0 +1,134 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Mail+import WildOS.UI as UI++// A message in a window of its own, from a double-click in the list: the+// reading pane with Reply, Reply all, Forward, Delete and the rest above it.+// Replies are written in the main window.+UI.AppWindow {+ id: window++ property string messageKey+ property var main: null++ width: 900+ height: 760+ minimumWidth: 560+ minimumHeight: 480+ visible: true+ title: pane.view.subject.length > 0 ? pane.view.subject : qsTr("Message")++ function reply(mode) {+ if (main) {+ main.compose(pane.view.replyData(mode));+ main.raise();+ main.requestActivate();+ }+ }++ ColumnLayout {+ anchors.fill: parent+ anchors.margins: window.maximised ? 0 : 1+ spacing: 0++ UI.TitleBar {+ Layout.fillWidth: true+ title: window.title+ tinted: true+ frame: window.frame+ }++ Rectangle {+ Layout.fillWidth: true+ Layout.leftMargin: 12+ Layout.rightMargin: 12+ Layout.topMargin: 8+ implicitHeight: 46+ radius: 10+ color: UI.Style.surfaceRest+ border.width: 1+ border.color: UI.Style.borderSubtle++ RowLayout {+ anchors.fill: parent+ anchors.leftMargin: 8+ anchors.rightMargin: 8+ spacing: 2++ CommandButton {+ text: qsTr("Reply")+ iconName: "reply"+ onClicked: window.reply("reply")+ }+ CommandButton {+ text: qsTr("Reply all")+ iconName: "reply-all"+ onClicked: window.reply("replyAll")+ }+ CommandButton {+ text: qsTr("Forward")+ iconName: "forward"+ onClicked: window.reply("forward")+ }+ Rectangle {+ implicitWidth: 1+ implicitHeight: 22+ Layout.leftMargin: 6+ Layout.rightMargin: 6+ color: UI.Style.borderSubtle+ }+ CommandButton {+ text: qsTr("Delete")+ iconName: "trash"+ onClicked: {+ MailEngine.removeKeys([window.messageKey]);+ window.close();+ }+ }+ CommandButton {+ text: qsTr("Archive")+ iconName: "archive"+ onClicked: {+ MailEngine.archiveKeys([window.messageKey]);+ window.close();+ }+ }+ CommandButton {+ text: qsTr("Flag")+ iconName: "flag"+ onClicked: MailEngine.toggleFlag(window.messageKey)+ }+ Item {+ Layout.fillWidth: true+ }+ }+ }++ ReadingPane {+ id: pane+ Layout.fillWidth: true+ Layout.fillHeight: true+ Layout.margins: 12+ messageKey: window.messageKey+ onReply: function (mode) {+ window.reply(mode);+ }+ onOpenLink: function (url) {+ if (window.main) {+ window.main.openLink(url);+ }+ }+ }+ }++ Component.onCompleted: {+ raise();+ requestActivate();+ }++ Shortcut {+ sequence: "Escape"+ onActivated: window.close()+ }+}diff --git a/packages/wildos-mail/qml/MiniMonth.qml b/packages/wildos-mail/qml/MiniMonth.qmlnew file mode 100644index 0000000..26e489f--- /dev/null+++ b/packages/wildos-mail/qml/MiniMonth.qml@@ -0,0 +1,128 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Mail+import WildOS.UI as UI+import "Formats.js" as Formats++// The small month (CalendarMicrosoft.dc, left pane): the days on screen+// share one band, today is the filled circle. Choosing a day goes there.+ColumnLayout {+ id: mini++ // The month shown, as its first day.+ property date month: new Date()+ // The days on screen, highlighted together.+ property date rangeFrom: new Date()+ property date rangeTo: new Date()+ property int firstDay: 1+ property bool showBusy: true++ signal picked(date day)++ spacing: 6++ function sameDay(a, b) {+ return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();+ }+ function dayAt(index) {+ const first = new Date(month.getFullYear(), month.getMonth(), 1);+ const offset = (first.getDay() - firstDay + 7) % 7;+ return new Date(month.getFullYear(), month.getMonth(), 1 - offset + index);+ }+ function shift(months) {+ month = new Date(month.getFullYear(), month.getMonth() + months, 1);+ }++ RowLayout {+ Layout.fillWidth: true+ UI.Label {+ Layout.fillWidth: true+ text: Formats.monthAndYear(mini.month)+ size: 13+ font.weight: Font.DemiBold+ }+ UI.IconButton {+ iconName: "chevron-left"+ implicitWidth: 26+ implicitHeight: 26+ tip: qsTr("Previous month")+ onClicked: mini.shift(-1)+ }+ UI.IconButton {+ iconName: "chevron-right"+ implicitWidth: 26+ implicitHeight: 26+ tip: qsTr("Next month")+ onClicked: mini.shift(1)+ }+ }++ Grid {+ id: grid+ columns: 7+ Layout.fillWidth: true+ readonly property real cell: Math.floor(width / 7)++ Repeater {+ model: 7+ delegate: UI.Label {+ required property int index+ width: grid.cell+ height: 22+ horizontalAlignment: Text.AlignHCenter+ text: Formats.names().dayName((index + mini.firstDay) % 7, Locale.ShortFormat).charAt(0).toUpperCase()+ size: 11+ font.weight: Font.DemiBold+ color: UI.Style.inkSubtle+ }+ }+ Repeater {+ model: 42+ delegate: Item {+ id: cell+ required property int index+ readonly property date day: mini.dayAt(index)+ readonly property bool inMonth: day.getMonth() === mini.month.getMonth()+ readonly property bool today: mini.sameDay(day, new Date())+ readonly property bool inRange: day >= mini.rangeFrom && day < mini.rangeTo+ readonly property bool rangeStart: inRange && (index % 7 === 0 || mini.sameDay(day, mini.rangeFrom))+ readonly property bool rangeEnd: inRange && (index % 7 === 6 || mini.sameDay(new Date(day.getFullYear(), day.getMonth(), day.getDate() + 1), mini.rangeTo))+ width: grid.cell+ height: 33+ // Six rows only when the month needs them.+ visible: index < 35 || mini.dayAt(35).getMonth() === mini.month.getMonth()++ Rectangle {+ visible: cell.inRange+ anchors.verticalCenter: parent.verticalCenter+ x: cell.rangeStart ? 2 : 0+ width: parent.width - (cell.rangeStart ? 2 : 0) - (cell.rangeEnd ? 2 : 0)+ height: 28+ radius: cell.rangeStart || cell.rangeEnd ? 14 : 0+ color: UI.Style.accentSelected+ }+ Rectangle {+ anchors.centerIn: parent+ width: 28+ height: 28+ radius: 14+ color: cell.today ? UI.Style.accent : mouse.containsMouse ? UI.Style.surfaceHover : "transparent"+ }+ UI.Label {+ anchors.centerIn: parent+ text: cell.day.getDate()+ size: 12+ font.weight: cell.today || cell.inRange ? Font.DemiBold : Font.Normal+ color: cell.today ? UI.Style.textOnAccent : cell.inMonth ? UI.Style.ink : UI.Style.inkSubtle+ }+ MouseArea {+ id: mouse+ anchors.fill: parent+ hoverEnabled: true+ cursorShape: Qt.PointingHandCursor+ onClicked: mini.picked(cell.day)+ }+ }+ }+ }+}diff --git a/packages/wildos-mail/qml/MonthView.qml b/packages/wildos-mail/qml/MonthView.qmlnew file mode 100644index 0000000..aae3dcb--- /dev/null+++ b/packages/wildos-mail/qml/MonthView.qml@@ -0,0 +1,193 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Mail+import WildOS.UI as UI+import "Formats.js" as Formats++// Month (CalMsMonth.dc): six weeks under the day names, each day with as+// many of its events as fit, all-day ones as filled bars and the rest as a+// dot, a time and a title. Today is the circled date and its cell is lit.+Item {+ id: view++ // Any day in the month shown.+ property date month: new Date()+ property int firstDay: 1+ property string openKey++ signal eventClicked(string key, Item block)+ signal dayClicked(date day)+ signal newAt(date start, bool allDay)++ readonly property date firstShown: {+ const first = new Date(month.getFullYear(), month.getMonth(), 1);+ const offset = (first.getDay() - firstDay + 7) % 7;+ return new Date(month.getFullYear(), month.getMonth(), 1 - offset);+ }+ readonly property date endShown: new Date(firstShown.getFullYear(), firstShown.getMonth(), firstShown.getDate() + 42)+ readonly property real cellWidth: width / 7+ readonly property real cellHeight: (height - 30) / 6++ function sameDay(a, b) {+ return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();+ }++ Row {+ id: names+ width: parent.width+ height: 30+ Repeater {+ model: 7+ delegate: Item {+ required property int index+ width: view.cellWidth+ height: 30+ UI.Label {+ x: 10+ anchors.verticalCenter: parent.verticalCenter+ text: Formats.names().dayName((index + view.firstDay) % 7, Locale.LongFormat)+ size: 12+ color: UI.Style.inkMuted+ }+ Rectangle {+ anchors.right: parent.right+ width: 1+ height: parent.height+ color: UI.Style.borderSubtle+ }+ }+ }+ }++ Grid {+ y: 30+ columns: 7+ Repeater {+ model: 42+ delegate: Rectangle {+ id: cell+ required property int index+ readonly property date day: new Date(view.firstShown.getFullYear(), view.firstShown.getMonth(), view.firstShown.getDate() + index)+ readonly property bool inMonth: day.getMonth() === view.month.getMonth()+ readonly property bool today: view.sameDay(day, new Date())+ readonly property var events: CalendarEngine.revision >= 0 ? CalendarEngine.eventsOn(day) : []+ readonly property int room: Math.max(0, Math.floor((height - 34) / 18))+ width: view.cellWidth+ height: view.cellHeight+ color: today ? UI.Style.accentSoft : cellMouse.containsMouse ? UI.Style.surfaceHover : "transparent"++ Rectangle {+ anchors.top: parent.top+ width: parent.width+ height: 1+ color: UI.Style.borderSubtle+ }+ Rectangle {+ anchors.right: parent.right+ width: 1+ height: parent.height+ color: UI.Style.borderSubtle+ }+ MouseArea {+ id: cellMouse+ anchors.fill: parent+ hoverEnabled: true+ onDoubleClicked: view.newAt(cell.day, true)+ }++ Rectangle {+ visible: cell.today+ x: 6+ y: 5+ width: 24+ height: 24+ radius: 12+ color: UI.Style.accent+ }+ UI.Label {+ x: cell.today ? 6 + (24 - implicitWidth) / 2 : 10+ y: 9+ // The first of a month carries its name.+ text: cell.day.getDate() === 1 ? Formats.shortDayAndMonth(cell.day) : cell.day.getDate()+ size: 13+ font.weight: cell.today ? Font.DemiBold : Font.Normal+ color: cell.today ? UI.Style.textOnAccent : cell.inMonth ? UI.Style.ink : UI.Style.inkSubtle+ MouseArea {+ anchors.fill: parent+ anchors.margins: -4+ cursorShape: Qt.PointingHandCursor+ onClicked: view.dayClicked(cell.day)+ }+ }++ Column {+ x: 6+ y: 32+ width: parent.width - 12+ spacing: 0+ Repeater {+ model: cell.events.length > cell.room ? cell.events.slice(0, Math.max(0, cell.room - 1)) : cell.events+ delegate: Rectangle {+ id: line+ required property var modelData+ readonly property bool bar: modelData.allDay || modelData.timeText === ""+ width: parent.width+ height: 18+ radius: 3+ color: bar ? Qt.rgba(Qt.color(modelData.color).r, Qt.color(modelData.color).g, Qt.color(modelData.color).b, 0.38)+ : lineMouse.containsMouse || view.openKey === modelData.key ? UI.Style.surfaceHover : "transparent"+ opacity: cell.inMonth ? 1 : 0.6++ Row {+ anchors.verticalCenter: parent.verticalCenter+ x: line.bar ? 6 : 4+ spacing: 6+ width: parent.width - 8+ Rectangle {+ visible: !line.bar+ anchors.verticalCenter: parent.verticalCenter+ width: 7+ height: 7+ radius: 3.5+ color: line.modelData.color+ }+ UI.Label {+ visible: !line.bar+ text: line.modelData.timeText+ size: 12+ color: UI.Style.inkMuted+ }+ UI.Label {+ width: parent.width - (line.bar ? 0 : 60)+ text: line.modelData.title+ size: 12+ font.weight: line.bar ? Font.DemiBold : Font.Medium+ elide: Text.ElideRight+ }+ }+ MouseArea {+ id: lineMouse+ anchors.fill: parent+ hoverEnabled: true+ cursorShape: Qt.PointingHandCursor+ onClicked: view.eventClicked(line.modelData.key, line)+ }+ }+ }+ UI.Label {+ visible: cell.events.length > cell.room+ leftPadding: 4+ text: qsTr("%1 more").arg(cell.events.length - Math.max(0, cell.room - 1))+ size: 12+ color: UI.Style.accentText+ MouseArea {+ anchors.fill: parent+ cursorShape: Qt.PointingHandCursor+ onClicked: view.dayClicked(cell.day)+ }+ }+ }+ }+ }+ }+}diff --git a/packages/wildos-mail/qml/ReadingPane.qml b/packages/wildos-mail/qml/ReadingPane.qmlnew file mode 100644index 0000000..7572e2b--- /dev/null+++ b/packages/wildos-mail/qml/ReadingPane.qml@@ -0,0 +1,495 @@+import QtQuick+import QtQuick.Controls as QQC+import QtQuick.Layouts+import WildOS.Mail+import WildOS.UI as UI++// The reading pane (MailMicrosoft.dc): subject, sender, the pictures+// notice, attachments, the message and the reply buttons under it.+Rectangle {+ id: pane++ property alias view: message+ // The message shown: the list's selection, or one fixed message in its+ // own window.+ property string messageKey: MailEngine.selected++ signal reply(string mode)+ signal moreMenu(real x, real y, Item from)+ signal openLink(string url)+ signal saved(string path)++ radius: 10+ color: UI.Style.surfaceRest+ border.width: 1+ border.color: UI.Style.borderSubtle+ clip: true++ MessageView {+ id: message+ key: pane.messageKey+ onAttachmentSaved: function (path) {+ pane.saved(path);+ }+ }++ readonly property bool hasMessage: message.key.length > 0 && !message.loading && message.error.length === 0++ // Nothing selected (MailMsStates.dc).+ ColumnLayout {+ anchors.centerIn: parent+ visible: message.key.length === 0+ spacing: 6++ MailIcon {+ Layout.alignment: Qt.AlignHCenter+ name: "mail"+ size: 40+ strokeWidth: 1.4+ color: UI.Style.inkSubtle+ }+ UI.Label {+ Layout.alignment: Qt.AlignHCenter+ text: qsTr("Select a message to read")+ size: 15+ font.weight: Font.DemiBold+ }+ UI.Label {+ Layout.alignment: Qt.AlignHCenter+ text: qsTr("Nothing is selected")+ size: 13+ color: UI.Style.inkMuted+ }+ }++ UI.Spinner {+ anchors.centerIn: parent+ visible: message.loading+ size: 24+ }++ ColumnLayout {+ anchors.centerIn: parent+ width: parent.width - 80+ visible: message.key.length > 0 && !message.loading && message.error.length > 0+ spacing: 8++ UI.Label {+ Layout.alignment: Qt.AlignHCenter+ text: qsTr("This message couldn't be opened")+ size: 15+ font.weight: Font.DemiBold+ }+ UI.Label {+ Layout.fillWidth: true+ horizontalAlignment: Text.AlignHCenter+ wrapMode: Text.WordWrap+ text: MailEngine.online ? message.error : qsTr("It hasn't been downloaded yet. It will open once you're back online.")+ size: 13+ color: UI.Style.inkMuted+ }+ }++ Flickable {+ id: flick+ anchors.fill: parent+ visible: pane.hasMessage+ contentWidth: width+ contentHeight: header.height + html.contentHeight + footer.height + 24+ boundsBehavior: Flickable.StopAtBounds+ clip: true+ QQC.ScrollBar.vertical: UI.ScrollBar {}++ onVisibleChanged: contentY = 0+ Connections {+ target: message+ function onKeyChanged() {+ flick.contentY = 0;+ }+ }++ ColumnLayout {+ id: header+ width: flick.width+ spacing: 0++ RowLayout {+ Layout.fillWidth: true+ Layout.topMargin: 16+ Layout.leftMargin: 22+ Layout.rightMargin: 22+ Layout.bottomMargin: 10+ spacing: 10++ UI.Label {+ Layout.fillWidth: true+ text: message.subject.length > 0 ? message.subject : qsTr("(No subject)")+ size: 19+ font.weight: Font.DemiBold+ wrapMode: Text.WordWrap+ }+ Rectangle {+ visible: message.accountName.length > 0+ Layout.alignment: Qt.AlignTop+ Layout.topMargin: 4+ implicitWidth: tag.implicitWidth + 16+ implicitHeight: tag.implicitHeight + 4+ radius: 4+ color: UI.Style.accentChip++ UI.Label {+ id: tag+ anchors.centerIn: parent+ text: message.accountName+ size: 11.5+ color: UI.Style.accentText+ }+ }+ }++ Rectangle {+ Layout.fillWidth: true+ Layout.leftMargin: 14+ Layout.rightMargin: 14+ implicitHeight: senderRow.implicitHeight + 24+ radius: 8+ color: UI.Style.surfaceRaised++ RowLayout {+ id: senderRow+ anchors.fill: parent+ anchors.margins: 12+ spacing: 12++ SenderBadge {+ id: senderBadge+ size: 40+ Component.onCompleted: refresh()+ function refresh() {+ initials = MailEngine.initialsOf(message.fromName.length > 0 ? message.fromName : message.fromAddress);+ colourIndex = MailEngine.colourOf(message.fromAddress);+ }+ Connections {+ target: message+ function onLoaded() {+ senderBadge.refresh();+ }+ }+ }++ ColumnLayout {+ Layout.fillWidth: true+ spacing: 2++ UI.Label {+ Layout.fillWidth: true+ text: message.fromName+ size: 14+ font.weight: Font.DemiBold+ elide: Text.ElideRight++ UI.Tooltip {+ visible: fromHover.hovered+ text: message.fromAddress+ }+ HoverHandler {+ id: fromHover+ }+ }+ UI.Label {+ Layout.fillWidth: true+ text: qsTr("To: %1").arg(message.to) + (message.cc.length > 0 ? qsTr(" Cc: %1").arg(message.cc) : "")+ size: 12+ color: UI.Style.inkMuted+ elide: Text.ElideRight+ }+ }++ ColumnLayout {+ spacing: 2++ Row {+ Layout.alignment: Qt.AlignRight+ CommandButton {+ iconOnly: true+ iconName: "reply"+ tip: qsTr("Reply")+ onClicked: pane.reply("reply")+ }+ CommandButton {+ iconOnly: true+ iconName: "reply-all"+ tip: qsTr("Reply all")+ onClicked: pane.reply("replyAll")+ }+ CommandButton {+ iconOnly: true+ iconName: "forward"+ tip: qsTr("Forward")+ onClicked: pane.reply("forward")+ }+ CommandButton {+ id: moreButton+ iconOnly: true+ iconName: "more"+ tip: qsTr("More actions")+ onClicked: pane.moreMenu(0, height + 4, moreButton)+ }+ }+ UI.Label {+ Layout.alignment: Qt.AlignRight+ text: message.date+ size: 12+ color: UI.Style.inkMuted+ }+ }+ }+ }++ InvitationCard {+ Layout.fillWidth: true+ Layout.leftMargin: 14+ Layout.rightMargin: 14+ Layout.topMargin: visible ? 10 : 0+ ics: pane.hasMessage ? message.calendarData : ""+ messageKey: message.key+ accountId: message.key.split("\u001f")[0]+ myEmail: {+ const a = MailEngine.account(accountId);+ return a && a.email ? a.email : "";+ }+ }++ // Pictures from the web wait for the person (MailMicrosoft.dc).+ Rectangle {+ visible: message.remoteImages > 0+ Layout.fillWidth: true+ Layout.leftMargin: 14+ Layout.rightMargin: 14+ Layout.topMargin: 10+ implicitHeight: notice.implicitHeight + 16+ radius: 6+ color: message.showPictures ? UI.Style.successSoft : UI.Style.warningSoft+ border.width: 1+ border.color: message.showPictures ? Qt.alpha(UI.Style.success, 0.3) : Qt.alpha(UI.Style.warning, 0.3)++ RowLayout {+ id: notice+ anchors.fill: parent+ anchors.leftMargin: 12+ anchors.rightMargin: 12+ spacing: 10++ MailIcon {+ name: "shield"+ size: 15+ color: message.showPictures ? UI.Style.success : UI.Style.warning+ }+ UI.Label {+ Layout.fillWidth: true+ wrapMode: Text.WordWrap+ size: 12.5+ text: !message.showPictures ? qsTr("Pictures from the web are blocked so the sender can't track when you read this.")+ : message.trackers === 1 ? qsTr("Pictures are showing. 1 tracker is still blocked.")+ : message.trackers > 1 ? qsTr("Pictures are showing. %1 trackers are still blocked.").arg(message.trackers)+ : qsTr("Pictures are showing. The sender can tell you opened this.")+ }+ UI.LinkButton {+ visible: !message.showPictures+ text: qsTr("Show pictures")+ size: 13+ onClicked: message.showPictures = true+ }+ }+ }++ Flow {+ visible: message.attachments.length > 0+ Layout.fillWidth: true+ Layout.leftMargin: 14+ Layout.rightMargin: 14+ Layout.topMargin: 12+ spacing: 8++ Repeater {+ model: message.attachments++ delegate: Rectangle {+ id: tile+ required property var modelData+ width: 250+ height: 52+ radius: 6+ color: tileMouse.containsMouse ? UI.Style.surfaceHover : "transparent"+ border.width: 1+ border.color: UI.Style.borderSubtle++ MouseArea {+ id: tileMouse+ anchors.fill: parent+ hoverEnabled: true+ cursorShape: Qt.PointingHandCursor+ onDoubleClicked: message.openAttachment(tile.modelData.index)+ onClicked: attachmentMenu.popup()+ }++ RowLayout {+ anchors.fill: parent+ anchors.leftMargin: 12+ anchors.rightMargin: 10+ spacing: 10++ Rectangle {+ implicitWidth: 34+ implicitHeight: 34+ radius: 6+ color: UI.Style.successSoft++ MailIcon {+ anchors.centerIn: parent+ name: tile.modelData.type.startsWith("image/") ? "picture" : "file"+ size: 18+ color: UI.Style.success+ }+ }+ ColumnLayout {+ Layout.fillWidth: true+ spacing: 0+ UI.Label {+ Layout.fillWidth: true+ text: tile.modelData.name+ size: 13+ elide: Text.ElideMiddle+ }+ UI.Label {+ text: tile.modelData.size+ size: 11.5+ color: UI.Style.inkMuted+ }+ }+ MailIcon {+ name: "chevron-down"+ size: 14+ color: UI.Style.inkMuted+ }+ }++ UI.Menu {+ id: attachmentMenu+ entries: [+ { text: qsTr("Open"), run: () => message.openAttachment(tile.modelData.index) },+ { text: qsTr("Save to Downloads"), run: () => message.saveAttachment(tile.modelData.index) },+ { separator: true },+ { text: qsTr("Save all to Downloads"), enabled: message.attachments.length > 1, run: () => message.saveAllAttachments() }+ ]+ }+ }+ }+ }++ Item {+ Layout.fillWidth: true+ implicitHeight: 20+ }+ }++ // Designed mail sits on white paper, as its sender saw it.+ Rectangle {+ visible: message.paper && html.contentHeight > 0+ x: 14+ y: header.height - 6+ width: flick.width - 28+ height: html.contentHeight + 32+ radius: 8+ color: "#ffffff"+ }++ // The message itself. It stays in view while the pane scrolls and+ // draws the part of the message that is on screen.+ HtmlView {+ id: html+ readonly property real bodyTop: header.height + (message.paper ? 10 : 0)+ x: message.paper ? 30 : 26+ width: Math.min(flick.width - x * 2, message.paper ? 100000 : 680)+ y: Math.max(bodyTop, flick.contentY)+ height: Math.max(0, flick.height - Math.max(0, bodyTop - flick.contentY))+ contentY: Math.max(0, flick.contentY - bodyTop)+ message: message+ html: pane.hasMessage ? message.html : ""+ paper: message.paper+ allowRemote: message.showPictures+ textColor: UI.Style.ink+ linkColor: UI.Style.accent+ quoteColor: UI.Style.inkMuted+ fontSize: 14.5 * UI.Style.textScale+ onLinkActivated: function (url) {+ pane.openLink(url);+ }+ onContextRequested: function (link, x, y) {+ bodyMenu.link = link;+ bodyMenu.popup(html, x, y);+ }+ }++ RowLayout {+ id: footer+ y: html.bodyTop + html.contentHeight + (message.paper ? 34 : 6)+ x: 26+ spacing: 8++ UI.Button {+ text: qsTr("Reply")+ iconName: "back"+ size: "small"+ onClicked: pane.reply("reply")+ }+ UI.Button {+ text: qsTr("Reply all")+ size: "small"+ onClicked: pane.reply("replyAll")+ }+ UI.Button {+ text: qsTr("Forward")+ iconName: "forward"+ size: "small"+ onClicked: pane.reply("forward")+ }+ }+ }++ UI.Menu {+ id: bodyMenu+ property string link+ entries: [+ { text: qsTr("Open link"), icon: "external", enabled: bodyMenu.link.length > 0, run: () => pane.openLink(bodyMenu.link) },+ { text: qsTr("Copy link address"), icon: "link", enabled: bodyMenu.link.length > 0, run: () => message.copyToClipboard(bodyMenu.link.replace(/^mailto:/, "")) },+ { separator: true },+ { text: qsTr("Copy the message's text"), icon: "copy", run: () => message.copyText() }+ ]+ }++ // Where a link really goes, before it is clicked.+ Rectangle {+ visible: html.hoveredLink.length > 0+ anchors.left: parent.left+ anchors.bottom: parent.bottom+ anchors.margins: 8+ width: Math.min(linkText.implicitWidth + 16, parent.width - 16)+ height: 26+ radius: 6+ color: UI.Style.windowOpaque+ border.width: 1+ border.color: UI.Style.borderMenu++ UI.Label {+ id: linkText+ anchors.fill: parent+ anchors.leftMargin: 8+ anchors.rightMargin: 8+ verticalAlignment: Text.AlignVCenter+ text: html.hoveredLink+ size: 12+ elide: Text.ElideMiddle+ }+ }+}diff --git a/packages/wildos-mail/qml/RecipientField.qml b/packages/wildos-mail/qml/RecipientField.qmlnew file mode 100644index 0000000..dfa3f9b--- /dev/null+++ b/packages/wildos-mail/qml/RecipientField.qml@@ -0,0 +1,189 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Mail+import WildOS.UI as UI++// To, Cc or Bcc (MailMsCompose.dc): each address becomes a chip with the+// person's initials once a comma, Enter or Tab follows it. A focus scope,+// so focusing the field puts the cursor in it.+FocusScope {+ id: field++ property string label+ property string placeholder+ property var people: []+ // Where Tab goes from here.+ property Item next: null+ readonly property string text: people.concat(input.text.trim().length > 0 ? [input.text.trim()] : []).join(", ")+ default property alias trailing: extras.data++ signal edited()++ function setText(value) {+ people = value.split(/\s*,\s*/).filter(s => s.length > 0);+ input.text = "";+ }+ function commit() {+ const parts = input.text.split(/[,;]/).map(s => s.trim()).filter(s => s.length > 0);+ if (parts.length > 0) {+ people = people.concat(parts);+ input.text = "";+ edited();+ }+ }+ function nameOf(address) {+ const m = address.match(/^\s*"?([^"<]*?)"?\s*<([^>]+)>\s*$/);+ return m && m[1].length > 0 ? m[1] : address;+ }+ function addressOf(address) {+ const m = address.match(/<([^>]+)>/);+ return m ? m[1] : address;+ }++ implicitHeight: Math.max(40, flow.implicitHeight + 12)++ MouseArea {+ anchors.fill: parent+ z: -1+ cursorShape: Qt.IBeamCursor+ onClicked: input.forceActiveFocus()+ }++ Rectangle {+ anchors.left: parent.left+ anchors.right: parent.right+ anchors.bottom: parent.bottom+ height: 1+ color: UI.Style.borderSubtle+ }++ UI.Label {+ id: caption+ x: 4+ anchors.verticalCenter: parent.verticalCenter+ width: field.label.length > 0 ? 56 : 0+ text: field.label+ size: 13+ color: UI.Style.inkMuted+ }++ Flow {+ id: flow+ anchors.left: caption.right+ anchors.leftMargin: field.label.length > 0 ? 10 : 0+ anchors.right: extras.left+ anchors.rightMargin: 10+ anchors.verticalCenter: parent.verticalCenter+ spacing: 6++ Repeater {+ model: field.people++ delegate: Rectangle {+ id: chip+ required property string modelData+ required property int index+ height: 26+ width: chipRow.implicitWidth + 9+ radius: 13+ color: UI.Style.accentChip++ Row {+ id: chipRow+ x: 3+ anchors.verticalCenter: parent.verticalCenter+ spacing: 7++ SenderBadge {+ anchors.verticalCenter: parent.verticalCenter+ size: 20+ initials: Apps.initialsOf(field.nameOf(chip.modelData))+ colourIndex: Apps.colourOf(field.addressOf(chip.modelData))+ }+ UI.Label {+ anchors.verticalCenter: parent.verticalCenter+ text: field.nameOf(chip.modelData)+ size: 13+ }+ MailIcon {+ anchors.verticalCenter: parent.verticalCenter+ name: "close"+ size: 12+ color: UI.Style.inkMuted++ MouseArea {+ anchors.fill: parent+ anchors.margins: -4+ cursorShape: Qt.PointingHandCursor+ onClicked: {+ const list = field.people.slice();+ list.splice(chip.index, 1);+ field.people = list;+ field.edited();+ }+ }+ }+ }++ UI.Tooltip {+ visible: chipHover.hovered+ text: field.addressOf(chip.modelData)+ }+ HoverHandler {+ id: chipHover+ }+ }+ }++ TextInput {+ id: input+ focus: true+ width: 200+ height: 26+ verticalAlignment: TextInput.AlignVCenter+ color: UI.Style.ink+ selectionColor: UI.Style.accentSelected+ font.family: UI.Style.fontFamily+ font.pixelSize: UI.Style.px(13)+ clip: true+ onTextEdited: {+ if (/[,;]/.test(text)) {+ field.commit();+ }+ field.edited();+ }+ onEditingFinished: field.commit()++ Text {+ visible: input.text.length === 0 && field.people.length === 0+ anchors.verticalCenter: parent.verticalCenter+ text: field.placeholder+ color: UI.Style.inkPlaceholder+ font: input.font+ }+ Keys.onReturnPressed: field.commit()+ Keys.onTabPressed: function (event) {+ field.commit();+ if (field.next) {+ field.next.forceActiveFocus();+ event.accepted = true;+ }+ }+ Keys.onPressed: function (event) {+ if (event.key === Qt.Key_Backspace && text.length === 0 && field.people.length > 0) {+ field.people = field.people.slice(0, -1);+ field.edited();+ event.accepted = true;+ }+ }+ }+ }++ Row {+ id: extras+ anchors.right: parent.right+ anchors.rightMargin: 4+ anchors.verticalCenter: parent.verticalCenter+ spacing: 12+ }+}diff --git a/packages/wildos-mail/qml/SenderBadge.qml b/packages/wildos-mail/qml/SenderBadge.qmlnew file mode 100644index 0000000..49ff0a3--- /dev/null+++ b/packages/wildos-mail/qml/SenderBadge.qml@@ -0,0 +1,42 @@+import QtQuick+import WildOS.UI as UI++// A sender's initials in a coloured circle. The colour comes from the+// address, so the same person always looks the same.+Rectangle {+ id: badge++ property string initials+ property int colourIndex: 0+ property real size: 32++ readonly property var pairs: [+ ["#f59e8b", "#d9607e"], ["#6ec3ff", "#2f7ad8"], ["#8fd6a4", "#2f9a64"], ["#ffd27a", "#e59b2f"],+ ["#c5a3ff", "#7b55e0"], ["#ff9fc0", "#d4518a"], ["#9ad8d0", "#2c9a8f"], ["#a8b4cc", "#5d6a86"]+ ]+ readonly property var pair: pairs[Math.abs(colourIndex) % pairs.length]++ width: size+ height: size+ radius: size / 2+ gradient: Gradient {+ orientation: Gradient.Vertical+ GradientStop {+ position: 0+ color: badge.pair[0]+ }+ GradientStop {+ position: 1+ color: badge.pair[1]+ }+ }++ Text {+ anchors.centerIn: parent+ text: badge.initials+ color: "#ffffff"+ font.family: UI.Style.fontFamily+ font.pixelSize: Math.round(badge.size * 0.375)+ font.weight: Font.DemiBold+ }+}diff --git a/packages/wildos-mail/qml/SettingsPage.qml b/packages/wildos-mail/qml/SettingsPage.qmlnew file mode 100644index 0000000..a5d36fe--- /dev/null+++ b/packages/wildos-mail/qml/SettingsPage.qml@@ -0,0 +1,464 @@+import QtQuick+import QtQuick.Controls as QQC+import QtQuick.Layouts+import WildOS.Mail+import WildOS.UI as UI++// Mail's settings (MailMsSetAccounts.dc, MailMsSetMail.dc,+// MailMsSetPrivacy.dc), in the window in place of the mail. Only what Mail+// does today is here; nothing is shown that doesn't work yet.+Rectangle {+ id: page++ property string section: "accounts"+ property string readingPane: "right"++ signal closeRequested()+ signal addAccount()+ signal signIn(string accountId)++ radius: 10+ color: UI.Style.surfaceRest+ border.width: 1+ border.color: UI.Style.borderSubtle+ clip: true++ readonly property var sections: [+ { id: "accounts", name: qsTr("Accounts"), icon: "people" },+ { id: "mail", name: qsTr("Mail"), icon: "layout" },+ { id: "writing", name: qsTr("Writing and signatures"), icon: "signature" },+ { id: "privacy", name: qsTr("Privacy and security"), icon: "shield" },+ { id: "notifications", name: qsTr("Notifications"), icon: "bell" }+ ]++ RowLayout {+ anchors.fill: parent+ spacing: 0++ ColumnLayout {+ Layout.preferredWidth: 236+ Layout.fillHeight: true+ Layout.margins: 10+ spacing: 2++ RowLayout {+ Layout.fillWidth: true+ Layout.bottomMargin: 8+ UI.IconButton {+ iconName: "back"+ tip: qsTr("Back to mail")+ onClicked: page.closeRequested()+ }+ UI.Label {+ text: qsTr("Settings")+ size: 16+ font.weight: Font.DemiBold+ }+ }++ Repeater {+ model: page.sections+ delegate: Rectangle {+ id: nav+ required property var modelData+ Layout.fillWidth: true+ implicitHeight: 34+ radius: 6+ color: page.section === modelData.id ? UI.Style.accentSelected : navMouse.containsMouse ? UI.Style.surfaceHover : "transparent"++ MouseArea {+ id: navMouse+ anchors.fill: parent+ hoverEnabled: true+ cursorShape: Qt.PointingHandCursor+ onClicked: page.section = nav.modelData.id+ }+ RowLayout {+ anchors.fill: parent+ anchors.leftMargin: 12+ spacing: 10+ MailIcon {+ name: nav.modelData.icon+ size: 16+ color: page.section === nav.modelData.id ? UI.Style.accent : UI.Style.iconInk+ }+ UI.Label {+ Layout.fillWidth: true+ text: nav.modelData.name+ size: 13+ font.weight: page.section === nav.modelData.id ? Font.DemiBold : Font.Normal+ elide: Text.ElideRight+ }+ }+ }+ }+ Item {+ Layout.fillHeight: true+ }+ }++ Rectangle {+ Layout.fillHeight: true+ implicitWidth: 1+ color: UI.Style.borderSubtle+ }++ QQC.ScrollView {+ Layout.fillWidth: true+ Layout.fillHeight: true+ clip: true+ contentWidth: availableWidth++ ColumnLayout {+ width: Math.min(720, parent.width - 56)+ x: 28+ spacing: 14++ Item {+ implicitHeight: 14+ }+ UI.Label {+ text: page.sections.find(s => s.id === page.section).name+ size: 22+ font.weight: Font.DemiBold+ }+ UI.Label {+ Layout.fillWidth: true+ wrapMode: Text.WordWrap+ size: 13+ color: UI.Style.inkMuted+ text: page.section === "accounts" ? qsTr("Mail accounts on this PC")+ : page.section === "mail" ? qsTr("Layout, reading and how messages are sorted")+ : page.section === "writing" ? qsTr("What goes at the end of what you write")+ : page.section === "privacy" ? qsTr("What senders can learn about you, and what leaves this PC")+ : qsTr("When Mail lets you know")+ }++ // Accounts+ Repeater {+ model: page.section === "accounts" ? MailEngine.accounts : []+ delegate: UI.Card {+ id: accountCard+ required property var modelData+ Layout.fillWidth: true+ padding: 16++ ColumnLayout {+ width: parent.width+ spacing: 10++ RowLayout {+ Layout.fillWidth: true+ spacing: 12+ SenderBadge {+ size: 36+ initials: MailEngine.initialsOf(accountCard.modelData.fullName || accountCard.modelData.email)+ colourIndex: MailEngine.colourOf(accountCard.modelData.email)+ }+ ColumnLayout {+ Layout.fillWidth: true+ spacing: 1+ UI.Label {+ text: accountCard.modelData.email+ size: 14+ font.weight: Font.DemiBold+ }+ UI.Label {+ Layout.fillWidth: true+ text: accountCard.modelData.problem ? accountCard.modelData.problem+ : accountCard.modelData.connected ? qsTr("Up to date") : MailEngine.online ? qsTr("Connecting") : qsTr("Offline")+ color: accountCard.modelData.problem ? UI.Style.warning : UI.Style.inkMuted+ size: 12+ wrapMode: Text.WordWrap+ }+ }+ }++ UI.SettingRow {+ Layout.fillWidth: true+ title: qsTr("Name people see")+ UI.TextField {+ width: 240+ text: accountCard.modelData.fullName+ onEditingFinished: {+ const a = MailEngine.account(accountCard.modelData.id);+ a.fullName = text.trim();+ MailEngine.updateAccount(a);+ }+ }+ }+ UI.SettingRow {+ Layout.fillWidth: true+ title: qsTr("Account name in Mail")+ UI.TextField {+ width: 240+ text: accountCard.modelData.name+ onEditingFinished: {+ const a = MailEngine.account(accountCard.modelData.id);+ a.name = text.trim() || a.email;+ MailEngine.updateAccount(a);+ }+ }+ }+ UI.SettingRow {+ Layout.fillWidth: true+ title: qsTr("Keep all mail on this PC")+ description: qsTr("Read and search everything offline. Off keeps only what you open.")+ UI.Toggle {+ checked: accountCard.modelData.keepAll+ onToggled: {+ const a = MailEngine.account(accountCard.modelData.id);+ a.keepAll = checked;+ MailEngine.updateAccount(a);+ }+ }+ }+ RowLayout {+ spacing: 8+ UI.Button {+ text: qsTr("Sign in again")+ size: "small"+ iconName: "refresh"+ onClicked: page.signIn(accountCard.modelData.id)+ }+ UI.Button {+ text: qsTr("Remove account")+ size: "small"+ danger: true+ onClicked: removeConfirm.ask(accountCard.modelData)+ }+ }+ }+ }+ }+ UI.Button {+ visible: page.section === "accounts"+ text: qsTr("Add account")+ iconName: "plus"+ onClicked: page.addAccount()+ }++ UI.Card {+ visible: page.section === "mail"+ Layout.fillWidth: true+ ColumnLayout {+ width: parent.width+ UI.SettingRow {+ Layout.fillWidth: true+ title: qsTr("Reading pane")+ description: qsTr("Off opens messages in the whole window")+ UI.ComboBox {+ model: [{ value: "right", text: qsTr("On the right") }, { value: "off", text: qsTr("Off") }]+ currentIndex: page.readingPane === "off" ? 1 : 0+ onActivated: function (i) {+ page.readingPane = i === 1 ? "off" : "right";+ }+ }+ }+ UI.SettingRow {+ Layout.fillWidth: true+ title: qsTr("Group messages into conversations")+ description: qsTr("One row per topic, showing the newest message")+ UI.Toggle {+ checked: MailEngine.messages.conversations+ onToggled: MailEngine.messages.conversations = checked+ }+ }+ UI.SettingRow {+ Layout.fillWidth: true+ title: qsTr("Mark as read")+ description: qsTr("After a message has been open for 2 seconds")+ }+ UI.SettingRow {+ Layout.fillWidth: true+ title: qsTr("After deleting or archiving")+ description: qsTr("The next message opens")+ }+ }+ }++ // Writing and signatures+ Repeater {+ model: page.section === "writing" ? MailEngine.accounts : []+ delegate: UI.Card {+ id: sigCard+ required property var modelData+ Layout.fillWidth: true+ padding: 16+ ColumnLayout {+ width: parent.width+ spacing: 8+ UI.Label {+ text: qsTr("Signature for %1").arg(sigCard.modelData.email)+ size: 13+ font.weight: Font.DemiBold+ }+ QQC.TextArea {+ Layout.fillWidth: true+ Layout.preferredHeight: 110+ text: sigCard.modelData.signature+ wrapMode: TextEdit.Wrap+ color: UI.Style.ink+ font.family: UI.Style.fontFamily+ font.pixelSize: UI.Style.px(13)+ placeholderText: qsTr("For example, your name and phone number")+ placeholderTextColor: UI.Style.inkPlaceholder+ background: Rectangle {+ radius: 6+ color: UI.Style.surfaceSunken+ border.width: 1+ border.color: UI.Style.borderField+ }+ onEditingFinished: {+ const a = MailEngine.account(sigCard.modelData.id);+ a.signature = text;+ MailEngine.updateAccount(a);+ }+ }+ }+ }+ }++ // Privacy and security+ RowLayout {+ visible: page.section === "privacy"+ Layout.fillWidth: true+ spacing: 10+ Repeater {+ model: [+ { n: MailEngine.trackersThisWeek, t: qsTr("trackers blocked this week") },+ { n: 0, t: qsTr("read receipts sent") },+ { n: MailEngine.photosCleaned, t: qsTr("photos sent without location") }+ ]+ delegate: UI.Card {+ required property var modelData+ Layout.fillWidth: true+ padding: 16+ ColumnLayout {+ width: parent.width+ spacing: 2+ UI.Label {+ text: modelData.n+ size: 26+ font.weight: Font.DemiBold+ }+ UI.Label {+ Layout.fillWidth: true+ text: modelData.t+ size: 12+ color: UI.Style.inkMuted+ wrapMode: Text.WordWrap+ }+ }+ }+ }+ }+ UI.Card {+ visible: page.section === "privacy"+ Layout.fillWidth: true+ ColumnLayout {+ width: parent.width+ UI.SettingRow {+ Layout.fillWidth: true+ title: qsTr("Pictures from the web")+ description: qsTr("Loading pictures tells the sender you opened the message, and roughly where you are. Mail asks each time.")+ UI.Label {+ text: qsTr("Always ask")+ size: 13+ color: UI.Style.inkMuted+ }+ }+ UI.SettingRow {+ Layout.fillWidth: true+ title: qsTr("Trackers")+ description: qsTr("Tiny or hidden pictures that report when you read a message stay blocked, even after Show pictures")+ UI.Label {+ text: qsTr("Always blocked")+ size: 13+ color: UI.Style.inkMuted+ }+ }+ UI.SettingRow {+ Layout.fillWidth: true+ title: qsTr("Read receipts")+ description: qsTr("When someone asks to know you read their message")+ UI.Label {+ text: qsTr("Never sent")+ size: 13+ color: UI.Style.inkMuted+ }+ }+ UI.SettingRow {+ Layout.fillWidth: true+ title: qsTr("Remove location from photos")+ description: qsTr("Location, camera and date details are taken out of photos before they're attached")+ UI.Label {+ text: qsTr("Always")+ size: 13+ color: UI.Style.inkMuted+ }+ }+ UI.SettingRow {+ Layout.fillWidth: true+ title: qsTr("Scripts in messages")+ description: qsTr("Mail shows messages without running anything in them")+ UI.Label {+ text: qsTr("Never run")+ size: 13+ color: UI.Style.inkMuted+ }+ }+ }+ }++ // Notifications+ UI.Card {+ visible: page.section === "notifications"+ Layout.fillWidth: true+ UI.SettingRow {+ width: parent.width+ title: qsTr("New mail")+ description: qsTr("A notification for new mail in your Inbox while Mail is open, with Reply, Mark as read and Archive")+ UI.Toggle {+ checked: Notifier.enabled+ onToggled: Notifier.enabled = checked+ }+ }+ }++ Item {+ implicitHeight: 24+ }+ }+ }+ }+++ UI.Dialog {+ id: removeConfirm+ property var target: ({})+ function ask(account) {+ target = account;+ open();+ }+ title: qsTr("Remove %1?").arg(target.email || "")+ text: qsTr("Mail and settings kept on this PC for this account are deleted. Nothing is deleted from your email provider.")+ iconName: "warning"+ buttons: [+ UI.Button {+ text: qsTr("Cancel")+ onClicked: removeConfirm.close()+ },+ UI.Button {+ kind: "primary"+ danger: true+ text: qsTr("Remove")+ onClicked: {+ MailEngine.removeAccount(removeConfirm.target.id);+ removeConfirm.close();+ }+ }+ ]+ }+}diff --git a/packages/wildos-mail/qml/WeekView.qml b/packages/wildos-mail/qml/WeekView.qmlnew file mode 100644index 0000000..0b4644f--- /dev/null+++ b/packages/wildos-mail/qml/WeekView.qml@@ -0,0 +1,406 @@+import QtQuick+import QtQuick.Controls as QQC+import QtQuick.Layouts+import WildOS.Mail+import WildOS.UI as UI+import "Formats.js" as Formats++// Day, work week and week (CalendarMicrosoft.dc): a column per day under+// its date, events that fill whole days in the band above the hours, and+// the hours themselves, 40px each, with a line at the time now. Events can+// be dragged to another time or day; a double-click on an empty slot+// starts a new event there.+Item {+ id: view++ property date startDate: new Date()+ property int days: 7+ property real hourHeight: 40+ property int scrollToHour: 8+ // The event the card is open for, drawn raised.+ property string openKey++ signal eventClicked(string key, Item block)+ signal newAt(date start, bool allDay)+ signal dayClicked(date day)++ readonly property real gutter: 58+ readonly property real columnWidth: Math.max(40, (width - gutter - 1) / days)+ readonly property date endDate: dayAfter(startDate, days)++ function dayAfter(d, n) {+ return new Date(d.getFullYear(), d.getMonth(), d.getDate() + n);+ }+ function sameDay(a, b) {+ return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();+ }+ function scrollToStart() {+ hours.contentY = Math.max(0, Math.min(hours.contentHeight - hours.height, scrollToHour * hourHeight - 8));+ }+ onStartDateChanged: Qt.callLater(scrollToStart)+ Component.onCompleted: Qt.callLater(scrollToStart)++ // Ticks once a minute for the line at the time now.+ property date now: new Date()+ Timer {+ interval: 30000+ running: true+ repeat: true+ onTriggered: view.now = new Date()+ }++ ColumnLayout {+ anchors.fill: parent+ spacing: 0++ // The dates.+ Row {+ Layout.fillWidth: true+ Layout.leftMargin: view.gutter+ height: 58++ Repeater {+ model: view.days+ delegate: Item {+ id: head+ required property int index+ readonly property date day: view.dayAfter(view.startDate, index)+ readonly property bool today: view.sameDay(day, view.now)+ width: view.columnWidth+ height: 58++ Rectangle {+ visible: head.today+ x: 0+ y: 0+ width: parent.width - 1+ height: 2+ color: UI.Style.accent+ }+ Column {+ x: 12+ y: 8+ spacing: 0+ UI.Label {+ text: head.day.getDate()+ size: 20+ font.weight: Font.DemiBold+ color: head.today ? UI.Style.accent : UI.Style.ink+ }+ UI.Label {+ text: Formats.names().toString(head.day, "dddd")+ size: 12+ color: head.today ? UI.Style.accent : UI.Style.inkMuted+ elide: Text.ElideRight+ width: view.columnWidth - 16+ }+ }+ Rectangle {+ anchors.right: parent.right+ width: 1+ height: parent.height+ color: UI.Style.borderSubtle+ }+ MouseArea {+ anchors.fill: parent+ cursorShape: Qt.PointingHandCursor+ onClicked: view.dayClicked(head.day)+ }+ }+ }+ }++ // Events that fill whole days.+ Item {+ id: band+ Layout.fillWidth: true+ readonly property var items: CalendarEngine.revision >= 0 ? CalendarEngine.allDayBetween(view.startDate, view.endDate) : []+ readonly property int rows: items.reduce((n, e) => Math.max(n, e.row + 1), 0)+ implicitHeight: Math.max(26, rows * 22 + 6)++ Rectangle {+ anchors.top: parent.top+ width: parent.width+ height: 1+ color: UI.Style.borderSubtle+ }+ Rectangle {+ anchors.bottom: parent.bottom+ width: parent.width+ height: 1+ color: UI.Style.borderSubtle+ }+ UI.Label {+ x: 0+ width: view.gutter - 10+ y: 6+ horizontalAlignment: Text.AlignRight+ text: qsTr("all-day")+ size: 11+ color: UI.Style.inkSubtle+ }+ Repeater {+ model: view.days+ delegate: Item {+ required property int index+ x: view.gutter + index * view.columnWidth+ width: view.columnWidth+ height: band.height+ Rectangle {+ anchors.right: parent.right+ width: 1+ height: parent.height+ color: UI.Style.borderSubtle+ }+ MouseArea {+ anchors.fill: parent+ onDoubleClicked: view.newAt(view.dayAfter(view.startDate, index), true)+ }+ }+ }+ Repeater {+ model: band.items+ delegate: Rectangle {+ id: chip+ required property var modelData+ x: view.gutter + modelData.firstColumn * view.columnWidth + 3+ y: 4 + modelData.row * 22+ width: (modelData.lastColumn - modelData.firstColumn + 1) * view.columnWidth - 7+ height: 19+ radius: 3+ color: Qt.rgba(Qt.color(modelData.color).r, Qt.color(modelData.color).g, Qt.color(modelData.color).b, view.openKey === modelData.key ? 0.55 : 0.38)+ border.width: view.openKey === modelData.key ? 1 : 0+ border.color: modelData.color++ Rectangle {+ width: 3+ height: parent.height+ radius: 1+ color: chip.modelData.color+ }+ UI.Label {+ anchors.verticalCenter: parent.verticalCenter+ x: 9+ width: parent.width - 14+ text: chip.modelData.title+ size: 12+ font.weight: Font.DemiBold+ elide: Text.ElideRight+ }+ MouseArea {+ anchors.fill: parent+ cursorShape: Qt.PointingHandCursor+ onClicked: view.eventClicked(chip.modelData.key, chip)+ }+ }+ }+ }++ // The hours.+ Flickable {+ id: hours+ Layout.fillWidth: true+ Layout.fillHeight: true+ clip: true+ contentHeight: 24 * view.hourHeight + 1+ boundsBehavior: Flickable.StopAtBounds+ QQC.ScrollBar.vertical: UI.ScrollBar {}++ Item {+ width: view.width+ height: hours.contentHeight++ // Hour lines and times.+ Repeater {+ model: 24+ delegate: Item {+ required property int index+ y: index * view.hourHeight+ width: view.width+ height: view.hourHeight+ UI.Label {+ visible: index > 0+ width: view.gutter - 10+ y: -7+ horizontalAlignment: Text.AlignRight+ text: (index < 10 ? "0" : "") + index + ":00"+ size: 11+ color: UI.Style.inkSubtle+ }+ Rectangle {+ x: view.gutter+ width: parent.width - view.gutter+ height: 1+ color: UI.Style.borderSubtle+ }+ Rectangle {+ x: view.gutter+ y: view.hourHeight / 2+ width: parent.width - view.gutter+ height: 1+ color: UI.Style.borderSubtle+ opacity: 0.4+ }+ }+ }++ // A column per day, with its events.+ Repeater {+ model: view.days+ delegate: Item {+ id: column+ required property int index+ readonly property date day: view.dayAfter(view.startDate, index)+ readonly property var events: CalendarEngine.revision >= 0 ? CalendarEngine.timedOn(day) : []+ x: view.gutter + index * view.columnWidth+ width: view.columnWidth+ height: parent.height++ Rectangle {+ anchors.right: parent.right+ width: 1+ height: parent.height+ color: UI.Style.borderSubtle+ }+ MouseArea {+ anchors.fill: parent+ onDoubleClicked: function (mouse) {+ const minutes = Math.floor(mouse.y / view.hourHeight * 2) * 30;+ const d = column.day;+ view.newAt(new Date(d.getFullYear(), d.getMonth(), d.getDate(), Math.floor(minutes / 60), minutes % 60), false);+ }+ }++ Repeater {+ model: column.events+ delegate: Rectangle {+ id: block+ required property var modelData+ readonly property real slot: (column.width - 6) / modelData.columns+ readonly property bool open: view.openKey === modelData.key+ property real dragDx: 0+ property real dragDy: 0+ x: 3 + modelData.column * slot + dragDx+ y: modelData.startMinute / 60 * view.hourHeight + 1 + dragDy+ z: drag.active || open ? 5 : 1+ width: slot - 3+ height: Math.max(18, (modelData.endMinute - modelData.startMinute) / 60 * view.hourHeight - 3)+ radius: 4+ color: Qt.rgba(Qt.color(modelData.color).r, Qt.color(modelData.color).g, Qt.color(modelData.color).b, open ? 0.55 : 0.36)+ border.width: open ? 1.5 : 0+ border.color: Qt.lighter(modelData.color, 1.2)+ opacity: modelData.invited && modelData.myStatus === "notGoing" ? 0.5 : 1+ clip: true++ Rectangle {+ width: 3+ height: parent.height+ color: block.modelData.color+ }+ Column {+ x: 9+ y: 3+ width: parent.width - 13+ spacing: 0+ UI.Label {+ width: parent.width+ text: block.modelData.title+ size: 12+ font.weight: Font.DemiBold+ elide: Text.ElideRight+ }+ UI.Label {+ visible: block.height > 34+ width: parent.width+ text: block.modelData.rangeText+ size: 11+ color: UI.Style.inkMuted+ elide: Text.ElideRight+ }+ UI.Label {+ visible: block.height > 52 && block.modelData.location.length > 0+ width: parent.width+ text: block.modelData.location+ size: 11+ color: UI.Style.inkMuted+ elide: Text.ElideRight+ }+ }++ MouseArea {+ id: drag+ property real startX+ property real startY+ property bool active: false+ anchors.fill: parent+ cursorShape: active ? Qt.ClosedHandCursor : Qt.PointingHandCursor+ preventStealing: true+ onPressed: function (mouse) {+ startX = mouse.x;+ startY = mouse.y;+ }+ onPositionChanged: function (mouse) {+ const dx = mouse.x - startX;+ const dy = mouse.y - startY;+ if (!active && Math.abs(dx) + Math.abs(dy) > 8 && !block.modelData.readOnly) {+ active = true;+ }+ if (active) {+ // Snaps to quarter hours and whole days.+ const quarter = view.hourHeight / 4;+ block.dragDy = Math.round(dy / quarter) * quarter;+ const dayShift = Math.round(dx / view.columnWidth);+ const target = Math.max(0, Math.min(view.days - 1, column.index + dayShift));+ block.dragDx = (target - column.index) * view.columnWidth;+ }+ }+ onReleased: {+ if (!active) {+ return;+ }+ active = false;+ const dayShift = Math.round(block.dragDx / view.columnWidth);+ const minutes = block.modelData.startMinute + Math.round(block.dragDy / (view.hourHeight / 4)) * 15;+ block.dragDx = 0;+ block.dragDy = 0;+ if (dayShift === 0 && minutes === block.modelData.startMinute) {+ return;+ }+ const s = block.modelData.start;+ const d = view.dayAfter(column.day, dayShift);+ CalendarEngine.moveEvent(block.modelData.key, new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, minutes));+ }+ onClicked: if (!active) view.eventClicked(block.modelData.key, block)+ }+ }+ }+ }+ }++ // The time now.+ Item {+ readonly property int todayIndex: Math.floor((new Date(view.now.getFullYear(), view.now.getMonth(), view.now.getDate()) - view.startDate) / 86400000 + 0.5)+ visible: todayIndex >= 0 && todayIndex < view.days+ y: (view.now.getHours() * 60 + view.now.getMinutes()) / 60 * view.hourHeight+ x: view.gutter+ width: view.width - view.gutter+ z: 10+ Rectangle {+ width: parent.width+ height: 1.5+ color: UI.Style.accent+ opacity: 0.85+ }+ Rectangle {+ x: parent.todayIndex * view.columnWidth - 4+ y: -3.25+ width: 8+ height: 8+ radius: 4+ color: UI.Style.accent+ }+ }+ }+ }+ }+}diff --git a/packages/wildos-mail/src/accounts.cpp b/packages/wildos-mail/src/accounts.cppnew file mode 100644index 0000000..c623a12--- /dev/null+++ b/packages/wildos-mail/src/accounts.cpp@@ -0,0 +1,250 @@+#include "accounts.h"++#include <QDir>+#include <QFile>+#include <QJsonArray>+#include <QJsonDocument>+#include <QJsonObject>+#include <QSaveFile>+#include <cstdio>+#include <QStandardPaths>+#include <QUuid>++#include <qt6keychain/keychain.h>++namespace+{+const QString keychainService = QStringLiteral("Wild OS Mail");++QString passwordFile()+{+ return QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QStringLiteral("/passwords.json");+}++QJsonObject readFallback()+{+ QFile file(passwordFile());+ return file.open(QIODevice::ReadOnly) ? QJsonDocument::fromJson(file.readAll()).object() : QJsonObject();+}++// Written to a new file that is only ever readable by this account (it is+// created that way, never loosened and tightened), then renamed over the old+// one, so there is no moment with a half-written or readable file.+void writeFallback(const QJsonObject &passwords)+{+ const QString path = passwordFile();+ if (passwords.isEmpty()) {+ QFile::remove(path);+ return;+ }+ QDir().mkpath(QFileInfo(path).absolutePath());+ const QString temp = path + QStringLiteral(".new");+ QFile::remove(temp);+ QFile file(temp);+ if (!file.open(QIODevice::WriteOnly | QIODevice::NewOnly, QFileDevice::ReadOwner | QFileDevice::WriteOwner)) {+ return;+ }+ file.write(QJsonDocument(passwords).toJson(QJsonDocument::Compact));+ file.flush();+ file.close();+ ::rename(QFile::encodeName(temp).constData(), QFile::encodeName(path).constData());+}++QString accountsFile()+{+ return QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation) + QStringLiteral("/accounts.json");+}+}++QVariantMap Account::toMap() const+{+ return {+ {QStringLiteral("id"), id},+ {QStringLiteral("name"), name},+ {QStringLiteral("email"), email},+ {QStringLiteral("fullName"), fullName},+ {QStringLiteral("provider"), provider},+ {QStringLiteral("imapHost"), imapHost},+ {QStringLiteral("imapPort"), imapPort},+ {QStringLiteral("imapSecurity"), imapSecurity},+ {QStringLiteral("smtpHost"), smtpHost},+ {QStringLiteral("smtpPort"), smtpPort},+ {QStringLiteral("smtpSecurity"), smtpSecurity},+ {QStringLiteral("user"), user},+ {QStringLiteral("auth"), auth},+ {QStringLiteral("keepAll"), keepAll},+ {QStringLiteral("signature"), signature},+ };+}++Account Account::fromMap(const QVariantMap &map)+{+ Account a;+ a.id = map.value(QStringLiteral("id")).toString();+ a.name = map.value(QStringLiteral("name")).toString();+ a.email = map.value(QStringLiteral("email")).toString();+ a.fullName = map.value(QStringLiteral("fullName")).toString();+ a.provider = map.value(QStringLiteral("provider"), QStringLiteral("other")).toString();+ a.imapHost = map.value(QStringLiteral("imapHost")).toString();+ a.imapPort = map.value(QStringLiteral("imapPort"), 993).toInt();+ a.imapSecurity = map.value(QStringLiteral("imapSecurity"), QStringLiteral("ssl")).toString();+ a.smtpHost = map.value(QStringLiteral("smtpHost")).toString();+ a.smtpPort = map.value(QStringLiteral("smtpPort"), 465).toInt();+ a.smtpSecurity = map.value(QStringLiteral("smtpSecurity"), QStringLiteral("ssl")).toString();+ a.user = map.value(QStringLiteral("user")).toString();+ a.auth = map.value(QStringLiteral("auth"), QStringLiteral("password")).toString();+ a.keepAll = map.value(QStringLiteral("keepAll"), true).toBool();+ a.signature = map.value(QStringLiteral("signature")).toString();+ if (a.name.isEmpty()) {+ a.name = a.email;+ }+ if (a.user.isEmpty()) {+ a.user = a.email;+ }+ return a;+}++AccountStore::AccountStore(QObject *parent)+ : QObject(parent)+{+ load();+}++const Account *AccountStore::find(const QString &id) const+{+ for (const Account &a : m_accounts) {+ if (a.id == id) {+ return &a;+ }+ }+ return nullptr;+}++void AccountStore::add(const Account &account)+{+ m_accounts.append(account);+ save();+ Q_EMIT changed();+}++void AccountStore::update(const Account &account)+{+ for (Account &a : m_accounts) {+ if (a.id == account.id) {+ a = account;+ }+ }+ save();+ Q_EMIT changed();+}++void AccountStore::remove(const QString &id)+{+ m_accounts.removeIf([&](const Account &a) {+ return a.id == id;+ });+ save();+ QJsonObject fallback = readFallback();+ fallback.remove(id);+ writeFallback(fallback);+ if (!walletExists()) {+ Q_EMIT changed();+ return;+ }+ auto *job = new QKeychain::DeletePasswordJob(keychainService);+ job->setKey(id);+ job->start();+ Q_EMIT changed();+}++bool AccountStore::walletExists()+{+ return QFile::exists(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QStringLiteral("/kwalletd/kdewallet.kwl"));+}++void AccountStore::readPassword(const QString &id, std::function<void(const QString &)> done)+{+ QJsonObject fallback = readFallback();+ if (fallback.contains(id)) {+ const QString password = QString::fromUtf8(QByteArray::fromBase64(fallback.value(id).toString().toLatin1()));+ // A wallet exists now: the password moves into it, and the file+ // copy goes once the wallet has it.+ if (walletExists()) {+ writePassword(id, password);+ }+ done(password);+ return;+ }+ if (!walletExists()) {+ done({});+ return;+ }+ auto *job = new QKeychain::ReadPasswordJob(keychainService, this);+ job->setKey(id);+ connect(job, &QKeychain::Job::finished, this, [job, done]() {+ done(job->error() == QKeychain::NoError ? job->textData() : QString());+ });+ job->start();+}++void AccountStore::writePassword(const QString &id, const QString &password, std::function<void(bool)> done)+{+ if (!walletExists()) {+ QJsonObject fallback = readFallback();+ fallback.insert(id, QString::fromLatin1(password.toUtf8().toBase64()));+ writeFallback(fallback);+ if (done) {+ done(true);+ }+ return;+ }+ auto *job = new QKeychain::WritePasswordJob(keychainService, this);+ job->setKey(id);+ job->setTextData(password);+ connect(job, &QKeychain::Job::finished, this, [job, id, done]() {+ const bool ok = job->error() == QKeychain::NoError;+ // Safely in the wallet: no copy stays in the file.+ if (ok) {+ QJsonObject fallback = readFallback();+ if (fallback.contains(id)) {+ fallback.remove(id);+ writeFallback(fallback);+ }+ }+ if (done) {+ done(ok);+ }+ });+ job->start();+}++QString AccountStore::newId()+{+ return QUuid::createUuid().toString(QUuid::Id128).left(12);+}++void AccountStore::load()+{+ QFile file(accountsFile());+ if (!file.open(QIODevice::ReadOnly)) {+ return;+ }+ const QJsonArray list = QJsonDocument::fromJson(file.readAll()).object().value(QStringLiteral("accounts")).toArray();+ for (const QJsonValue &value : list) {+ m_accounts.append(Account::fromMap(value.toObject().toVariantMap()));+ }+}++void AccountStore::save() const+{+ QDir().mkpath(QFileInfo(accountsFile()).absolutePath());+ QJsonArray list;+ for (const Account &a : m_accounts) {+ list.append(QJsonObject::fromVariantMap(a.toMap()));+ }+ QSaveFile file(accountsFile());+ if (file.open(QIODevice::WriteOnly)) {+ file.write(QJsonDocument(QJsonObject{{QStringLiteral("accounts"), list}}).toJson());+ file.commit();+ }+}diff --git a/packages/wildos-mail/src/accounts.h b/packages/wildos-mail/src/accounts.hnew file mode 100644index 0000000..93016a3--- /dev/null+++ b/packages/wildos-mail/src/accounts.h@@ -0,0 +1,82 @@+#pragma once++#include <QList>+#include <QObject>+#include <QString>+#include <QVariantMap>++#include <functional>++// A mail account as Mail keeps it: where its mail lives and how to reach+// it. Saved in ~/.config/wildos-mail/accounts.json; the password is not in+// there, it is in the system's password store (KWallet) through QtKeychain.+struct Account {+ QString id;+ // What the folder pane calls it ("Personal", "Work"); the email address+ // until the person renames it.+ QString name;+ QString email;+ // How the person's name appears on mail they send.+ QString fullName;+ // gmail, icloud, yahoo, outlook or other: picks the help text and+ // provider quirks (Gmail files sent mail itself).+ QString provider;+ QString imapHost;+ int imapPort = 993;+ // ssl, starttls or none+ QString imapSecurity = QStringLiteral("ssl");+ QString smtpHost;+ int smtpPort = 465;+ QString smtpSecurity = QStringLiteral("ssl");+ QString user;+ // "password" (an ordinary or app password) or "google" (Sign in with+ // Google: the stored secret is the refresh token).+ QString auth = QStringLiteral("password");+ // Keep every message on this PC for offline reading and search, or only+ // the newest.+ bool keepAll = true;+ QString signature;++ QVariantMap toMap() const;+ static Account fromMap(const QVariantMap &map);+};++class AccountStore : public QObject+{+ Q_OBJECT++public:+ explicit AccountStore(QObject *parent = nullptr);++ const QList<Account> &accounts() const+ {+ return m_accounts;+ }+ const Account *find(const QString &id) const;++ void add(const Account &account);+ void update(const Account &account);+ void remove(const QString &id);++ // The password store answers asynchronously; done gets "" when there is+ // none or the store is locked and the person said no.+ void readPassword(const QString &id, std::function<void(const QString &)> done);+ void writePassword(const QString &id, const QString &password, std::function<void(bool ok)> done = {});++ static QString newId();++ // KWallet when the account has a wallet. Asking KWallet when it has+ // none makes it ask the person to create one (the Blowfish or GPG+ // dialog), which is what happens after Wild OS's automatic first+ // sign-in; then the password goes in a file only this account can read.+ static bool walletExists();++Q_SIGNALS:+ void changed();++private:+ void load();+ void save() const;++ QList<Account> m_accounts;+};diff --git a/packages/wildos-mail/src/apps.h b/packages/wildos-mail/src/apps.hnew file mode 100644index 0000000..a5dba51--- /dev/null+++ b/packages/wildos-mail/src/apps.h@@ -0,0 +1,44 @@+#pragma once++#include <QObject>+#include <QProcess>+#include <QtQml/qqmlregistration.h>++#include "models.h"++// What Mail and Calendar share without starting the other's engine: the+// app rail's buttons (Mail and Calendar are separate windows with their own+// taskbar buttons, so moving between them starts, or brings forward, the+// other) and a person's initials and colour.+class Apps : public QObject+{+ Q_OBJECT+ QML_ELEMENT+ QML_SINGLETON++public:+ using QObject::QObject;++ Q_INVOKABLE void open(const QString &app) const+ {+ QProcess::startDetached(app == QLatin1String("calendar") ? QStringLiteral("wildos-calendar") : QStringLiteral("wildos-mail"), {});+ }+ // Right-clicking the rail: Calendar in a window of its own. Mail has+ // one window, so for Mail this is the same as choosing it.+ Q_INVOKABLE void openWindow(const QString &app) const+ {+ if (app == QLatin1String("calendar")) {+ QProcess::startDetached(QStringLiteral("wildos-calendar"), {QStringLiteral("--new-window")});+ } else {+ open(app);+ }+ }+ Q_INVOKABLE static QString initialsOf(const QString &name)+ {+ return MessageModel::initials(name);+ }+ Q_INVOKABLE static int colourOf(const QString &address)+ {+ return MessageModel::colourOf(address);+ }+};diff --git a/packages/wildos-mail/src/autoconfig.cpp b/packages/wildos-mail/src/autoconfig.cppnew file mode 100644index 0000000..9d6d0c1--- /dev/null+++ b/packages/wildos-mail/src/autoconfig.cpp@@ -0,0 +1,233 @@+#include "autoconfig.h"++#include <QDnsLookup>+#include <QNetworkAccessManager>+#include <QNetworkReply>+#include <QUrl>+#include <QXmlStreamReader>++namespace+{+QString domainOf(const QString &email)+{+ return email.section(QLatin1Char('@'), 1).trimmed().toLower();+}++QVariantMap settings(const QString &provider, const QString &imapHost, int imapPort, const QString &imapSecurity, const QString &smtpHost, int smtpPort,+ const QString &smtpSecurity)+{+ return {+ {QStringLiteral("provider"), provider},+ {QStringLiteral("imapHost"), imapHost},+ {QStringLiteral("imapPort"), imapPort},+ {QStringLiteral("imapSecurity"), imapSecurity},+ {QStringLiteral("smtpHost"), smtpHost},+ {QStringLiteral("smtpPort"), smtpPort},+ {QStringLiteral("smtpSecurity"), smtpSecurity},+ };+}++QString securityOf(const QString &socketType)+{+ const QString s = socketType.toUpper();+ if (s == QLatin1String("SSL")) {+ return QStringLiteral("ssl");+ }+ if (s == QLatin1String("STARTTLS")) {+ return QStringLiteral("starttls");+ }+ return QStringLiteral("none");+}++// Thunderbird's autoconfig XML: the first IMAP server and the first SMTP+// server, with %EMAILADDRESS% and friends filled in.+QVariantMap parseConfig(const QByteArray &xml, const QString &email)+{+ QXmlStreamReader reader(xml);+ QVariantMap out;+ QString section;+ QVariantMap current;+ const auto fill = [&](QString value) {+ value.replace(QLatin1String("%EMAILADDRESS%"), email);+ value.replace(QLatin1String("%EMAILLOCALPART%"), email.section(QLatin1Char('@'), 0, 0));+ value.replace(QLatin1String("%EMAILDOMAIN%"), domainOf(email));+ return value;+ };+ while (!reader.atEnd()) {+ reader.readNext();+ if (reader.isStartElement()) {+ const QString name = reader.name().toString();+ if (name == QLatin1String("incomingServer") || name == QLatin1String("outgoingServer")) {+ section = reader.attributes().value(QLatin1String("type")).toString();+ current.clear();+ } else if (!section.isEmpty() && (name == QLatin1String("hostname") || name == QLatin1String("port") || name == QLatin1String("socketType")+ || name == QLatin1String("username"))) {+ current.insert(name, fill(reader.readElementText()));+ }+ } else if (reader.isEndElement()) {+ const QString name = reader.name().toString();+ if ((name == QLatin1String("incomingServer") && section == QLatin1String("imap") && !out.contains(QStringLiteral("imapHost")))) {+ out.insert(QStringLiteral("imapHost"), current.value(QStringLiteral("hostname")));+ out.insert(QStringLiteral("imapPort"), current.value(QStringLiteral("port")).toInt());+ out.insert(QStringLiteral("imapSecurity"), securityOf(current.value(QStringLiteral("socketType")).toString()));+ out.insert(QStringLiteral("user"), current.value(QStringLiteral("username")));+ } else if (name == QLatin1String("outgoingServer") && section == QLatin1String("smtp") && !out.contains(QStringLiteral("smtpHost"))) {+ out.insert(QStringLiteral("smtpHost"), current.value(QStringLiteral("hostname")));+ out.insert(QStringLiteral("smtpPort"), current.value(QStringLiteral("port")).toInt());+ out.insert(QStringLiteral("smtpSecurity"), securityOf(current.value(QStringLiteral("socketType")).toString()));+ }+ if (name == QLatin1String("incomingServer") || name == QLatin1String("outgoingServer")) {+ section.clear();+ }+ }+ }+ if (!out.contains(QStringLiteral("imapHost")) || !out.contains(QStringLiteral("smtpHost"))) {+ return {};+ }+ out.insert(QStringLiteral("provider"), QStringLiteral("other"));+ return out;+}+}++AutoConfig::AutoConfig(QObject *parent)+ : QObject(parent)+ , m_network(new QNetworkAccessManager(this))+{+ m_network->setCookieJar(nullptr);+}++QString AutoConfig::providerOf(const QString &email)+{+ const QString domain = domainOf(email);+ if (domain == QLatin1String("gmail.com") || domain == QLatin1String("googlemail.com")) {+ return QStringLiteral("gmail");+ }+ if (domain == QLatin1String("icloud.com") || domain == QLatin1String("me.com") || domain == QLatin1String("mac.com")) {+ return QStringLiteral("icloud");+ }+ if (domain.startsWith(QLatin1String("yahoo.")) || domain.startsWith(QLatin1String("ymail.")) || domain == QLatin1String("rocketmail.com")) {+ return QStringLiteral("yahoo");+ }+ if (domain.startsWith(QLatin1String("outlook.")) || domain.startsWith(QLatin1String("hotmail.")) || domain.startsWith(QLatin1String("live."))+ || domain == QLatin1String("msn.com")) {+ return QStringLiteral("outlook");+ }+ if (domain == QLatin1String("aol.com")) {+ return QStringLiteral("aol");+ }+ if (domain == QLatin1String("fastmail.com") || domain == QLatin1String("fastmail.fm")) {+ return QStringLiteral("fastmail");+ }+ return QStringLiteral("other");+}++QVariantMap AutoConfig::preset(const QString &provider, const QString &email)+{+ QVariantMap s;+ if (provider == QLatin1String("gmail")) {+ s = settings(provider, QStringLiteral("imap.gmail.com"), 993, QStringLiteral("ssl"), QStringLiteral("smtp.gmail.com"), 465, QStringLiteral("ssl"));+ } else if (provider == QLatin1String("icloud")) {+ s = settings(provider, QStringLiteral("imap.mail.me.com"), 993, QStringLiteral("ssl"), QStringLiteral("smtp.mail.me.com"), 587, QStringLiteral("starttls"));+ } else if (provider == QLatin1String("yahoo")) {+ s = settings(provider, QStringLiteral("imap.mail.yahoo.com"), 993, QStringLiteral("ssl"), QStringLiteral("smtp.mail.yahoo.com"), 465, QStringLiteral("ssl"));+ } else if (provider == QLatin1String("fastmail")) {+ s = settings(provider, QStringLiteral("imap.fastmail.com"), 993, QStringLiteral("ssl"), QStringLiteral("smtp.fastmail.com"), 465, QStringLiteral("ssl"));+ } else if (provider == QLatin1String("aol")) {+ s = settings(provider, QStringLiteral("imap.aol.com"), 993, QStringLiteral("ssl"), QStringLiteral("smtp.aol.com"), 465, QStringLiteral("ssl"));+ } else if (provider == QLatin1String("outlook")) {+ s = settings(provider, QStringLiteral("outlook.office365.com"), 993, QStringLiteral("ssl"), QStringLiteral("smtp-mail.outlook.com"), 587, QStringLiteral("starttls"));+ } else {+ return {};+ }+ s.insert(QStringLiteral("email"), email);+ s.insert(QStringLiteral("user"), email);+ return s;+}++void AutoConfig::lookup(const QString &email)+{+ ++m_generation;+ const QString domain = domainOf(email);+ if (domain.isEmpty()) {+ return;+ }+ m_busy = true;+ Q_EMIT busyChanged();+ const QString provider = providerOf(email);+ if (provider != QLatin1String("other")) {+ finish(preset(provider, email), false);+ return;+ }+ tryUrl({QStringLiteral("https://autoconfig.%1/mail/config-v1.1.xml").arg(domain),+ QStringLiteral("https://%1/.well-known/autoconfig/mail/config-v1.1.xml").arg(domain),+ QStringLiteral("https://autoconfig.thunderbird.net/v1.1/%1").arg(domain)},+ email);+}++void AutoConfig::tryUrl(const QStringList &urls, const QString &email)+{+ if (urls.isEmpty()) {+ tryMx(email);+ return;+ }+ const int generation = m_generation;+ QNetworkRequest request{QUrl(urls.first())};+ request.setTransferTimeout(6000);+ QNetworkReply *reply = m_network->get(request);+ connect(reply, &QNetworkReply::finished, this, [this, reply, urls, email, generation]() {+ reply->deleteLater();+ if (generation != m_generation) {+ return;+ }+ QVariantMap s = reply->error() == QNetworkReply::NoError ? parseConfig(reply->readAll(), email) : QVariantMap();+ if (!s.isEmpty()) {+ s.insert(QStringLiteral("email"), email);+ if (s.value(QStringLiteral("user")).toString().isEmpty()) {+ s.insert(QStringLiteral("user"), email);+ }+ finish(s, false);+ return;+ }+ tryUrl(urls.mid(1), email);+ });+}++// Mail for many company and custom domains is run by Google or Microsoft;+// the domain's mail server record says which.+void AutoConfig::tryMx(const QString &email)+{+ const int generation = m_generation;+ auto *dns = new QDnsLookup(QDnsLookup::MX, domainOf(email), this);+ connect(dns, &QDnsLookup::finished, this, [this, dns, email, generation]() {+ dns->deleteLater();+ if (generation != m_generation) {+ return;+ }+ QString mx;+ if (dns->error() == QDnsLookup::NoError && !dns->mailExchangeRecords().isEmpty()) {+ mx = dns->mailExchangeRecords().first().exchange().toLower();+ }+ if (mx.endsWith(QLatin1String("google.com")) || mx.endsWith(QLatin1String("googlemail.com"))) {+ finish(preset(QStringLiteral("gmail"), email), false);+ return;+ }+ if (mx.endsWith(QLatin1String("outlook.com"))) {+ finish(preset(QStringLiteral("outlook"), email), false);+ return;+ }+ const QString domain = domainOf(email);+ QVariantMap s = settings(QStringLiteral("other"), QStringLiteral("imap.") + domain, 993, QStringLiteral("ssl"), QStringLiteral("smtp.") + domain, 465,+ QStringLiteral("ssl"));+ s.insert(QStringLiteral("email"), email);+ s.insert(QStringLiteral("user"), email);+ finish(s, true);+ });+ dns->lookup();+}++void AutoConfig::finish(const QVariantMap &settings, bool guessed)+{+ m_busy = false;+ Q_EMIT busyChanged();+ Q_EMIT found(settings, guessed);+}diff --git a/packages/wildos-mail/src/autoconfig.h b/packages/wildos-mail/src/autoconfig.hnew file mode 100644index 0000000..0cc3f34--- /dev/null+++ b/packages/wildos-mail/src/autoconfig.h@@ -0,0 +1,47 @@+#pragma once++#include <QObject>+#include <QVariantMap>+#include <QtQml/qqmlregistration.h>++class QNetworkAccessManager;++// Finds the server settings for an email address, so people type their+// address and password and nothing else. Known providers are built in;+// for the rest it asks the domain's own autoconfig file, then Thunderbird's+// public database (which learns only the domain, never the address), then+// guesses the usual names.+class AutoConfig : public QObject+{+ Q_OBJECT+ QML_ELEMENT++ Q_PROPERTY(bool busy READ busy NOTIFY busyChanged)++public:+ explicit AutoConfig(QObject *parent = nullptr);++ bool busy() const+ {+ return m_busy;+ }++ // Answers through found(), always: with a guess when nothing better+ // turned up.+ Q_INVOKABLE void lookup(const QString &email);+ Q_INVOKABLE static QVariantMap preset(const QString &provider, const QString &email);+ Q_INVOKABLE static QString providerOf(const QString &email);++Q_SIGNALS:+ void busyChanged();+ void found(const QVariantMap &settings, bool guessed);++private:+ void tryUrl(const QStringList &urls, const QString &email);+ void tryMx(const QString &email);+ void finish(const QVariantMap &settings, bool guessed);++ QNetworkAccessManager *m_network;+ bool m_busy = false;+ int m_generation = 0;+};diff --git a/packages/wildos-mail/src/calendarengine.cpp b/packages/wildos-mail/src/calendarengine.cppnew file mode 100644index 0000000..1d97ed0--- /dev/null+++ b/packages/wildos-mail/src/calendarengine.cpp@@ -0,0 +1,2057 @@+#include "calendarengine.h"+#include "formats.h"++#include <QJSEngine>+#include <QPointer>+#include <QSettings>+#include <QThreadPool>+#include <QUrl>++#include <algorithm>++Q_LOGGING_CATEGORY(calendarLog, "wildos.calendar", QtInfoMsg)++namespace+{+const QChar sep(0x1f);+const QString holidaysUrl = QStringLiteral("https://www.gov.uk/bank-holidays/england-and-wales.ics");++// The colours a new calendar takes in turn (the board's list).+const QStringList palette = {+ QStringLiteral("#6f9bff"), QStringLiteral("#4cc38a"), QStringLiteral("#f0a04b"), QStringLiteral("#ee6f9a"),+ QStringLiteral("#a98bf5"), QStringLiteral("#46c2c9"), QStringLiteral("#e5c55a"), QStringLiteral("#9aa3b5"),+};++QString str(const gchar *s)+{+ return s ? QString::fromUtf8(s) : QString();+}++QString takeStr(gchar *s)+{+ const QString out = str(s);+ g_free(s);+ return out;+}++QString keyOf(const QString &calendar, const QString &uid, const QString &rid)+{+ return calendar + sep + uid + sep + rid;+}++bool splitKey(const QString &key, QString *calendar, QString *uid, QString *rid)+{+ const QStringList parts = key.split(sep);+ if (parts.size() != 3) {+ return false;+ }+ *calendar = parts[0];+ *uid = parts[1];+ *rid = parts[2];+ return true;+}++QString backendOf(ESource *source)+{+ if (!e_source_has_extension(source, E_SOURCE_EXTENSION_CALENDAR)) {+ return {};+ }+ auto *ext = E_SOURCE_BACKEND(e_source_get_extension(source, E_SOURCE_EXTENSION_CALENDAR));+ return str(e_source_backend_get_backend_name(ext));+}++QString mailtoless(const gchar *value)+{+ QString v = str(value);+ if (v.startsWith(QLatin1String("mailto:"), Qt::CaseInsensitive)) {+ v = v.mid(7);+ }+ return v.trimmed().toLower();+}++QString partstatName(ICalParameterPartstat p)+{+ switch (p) {+ case I_CAL_PARTSTAT_ACCEPTED:+ return QStringLiteral("going");+ case I_CAL_PARTSTAT_TENTATIVE:+ return QStringLiteral("maybe");+ case I_CAL_PARTSTAT_DECLINED:+ return QStringLiteral("notGoing");+ default:+ return QStringLiteral("waiting");+ }+}++// An sexp string, quoted for the calendar service.+QString quoted(const QString &text)+{+ QString t = text;+ t.replace(QLatin1Char('\\'), QLatin1String("\\\\"));+ t.replace(QLatin1Char('"'), QLatin1String("\\\""));+ return QLatin1Char('"') + t + QLatin1Char('"');+}++QString isoUtc(const QDateTime &t)+{+ return t.toUTC().toString(QStringLiteral("yyyyMMdd'T'HHmmss'Z'"));+}+}++CalendarEngine *CalendarEngine::instance()+{+ static CalendarEngine *engine = new CalendarEngine();+ return engine;+}++CalendarEngine *CalendarEngine::create(QQmlEngine *, QJSEngine *)+{+ CalendarEngine *engine = instance();+ QJSEngine::setObjectOwnership(engine, QJSEngine::CppOwnership);+ return engine;+}++CalendarEngine::CalendarEngine(QObject *parent)+ : QObject(parent)+{+ const QString zoneId = QSettings().value(QStringLiteral("calendar/timeZone")).toString();+ m_zone = zoneId.isEmpty() ? QTimeZone::systemTimeZone() : QTimeZone(zoneId.toUtf8());+ if (!m_zone.isValid()) {+ m_zone = QTimeZone::systemTimeZone();+ }++ m_reloadTimer.setSingleShot(true);+ m_reloadTimer.setInterval(120);+ connect(&m_reloadTimer, &QTimer::timeout, this, &CalendarEngine::reload);++ m_cancel = g_cancellable_new();+ // The registry starts the calendar service on the session bus if it+ // isn't running yet, which can take a few seconds the first time.+ e_source_registry_new(m_cancel, &CalendarEngine::onRegistryReady, this);+}++CalendarEngine::~CalendarEngine()+{+ g_cancellable_cancel(m_cancel);+ for (ECalClientView *view : std::as_const(m_views)) {+ e_cal_client_view_stop(view, nullptr);+ g_object_unref(view);+ }+ for (ECalClient *client : std::as_const(m_clients)) {+ g_object_unref(client);+ }+ g_clear_object(&m_registry);+ g_clear_object(&m_cancel);+}++void CalendarEngine::onRegistryReady(GObject *, GAsyncResult *result, gpointer data)+{+ auto *self = static_cast<CalendarEngine *>(data);+ GError *error = nullptr;+ ESourceRegistry *registry = e_source_registry_new_finish(result, &error);+ if (!registry) {+ if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {+ qCWarning(calendarLog) << "the calendar service didn't start:" << (error ? error->message : "");+ self->m_problem = tr("The calendar service didn't start.");+ Q_EMIT self->readyChanged();+ }+ g_clear_error(&error);+ return;+ }+ self->m_registry = registry;+ for (const char *signal : {"source-added", "source-removed", "source-changed", "source-enabled", "source-disabled"}) {+ g_signal_connect(registry, signal, G_CALLBACK(&CalendarEngine::onSourceChanged), self);+ }+ self->rebuildCalendars();+ Q_EMIT self->readyChanged();+}++void CalendarEngine::onSourceChanged(ESourceRegistry *, ESource *, gpointer data)+{+ auto *self = static_cast<CalendarEngine *>(data);+ // Several arrive at once when an account's calendars are found.+ QMetaObject::invokeMethod(self, &CalendarEngine::rebuildCalendars, Qt::QueuedConnection);+}++void CalendarEngine::rebuildCalendars()+{+ if (!m_registry) {+ return;+ }+ QVariantList calendars;+ QVariantList accounts;+ QSet<QString> present;++ GList *sources = e_source_registry_list_enabled(m_registry, E_SOURCE_EXTENSION_CALENDAR);+ for (GList *l = sources; l; l = l->next) {+ auto *source = E_SOURCE(l->data);+ const QString backend = backendOf(source);+ // Weather needs GNOME's location services and isn't offered.+ if (backend == QLatin1String("weather")) {+ continue;+ }+ const QString uid = str(e_source_get_uid(source));+ auto *selectable = E_SOURCE_SELECTABLE(e_source_get_extension(source, E_SOURCE_EXTENSION_CALENDAR));+ QString color = takeStr(e_source_selectable_dup_color(selectable));+ if (color.isEmpty()) {+ color = palette.value(calendars.size() % palette.size());+ }+ const bool selected = e_source_selectable_get_selected(selectable);++ QString group = tr("My calendars");+ QString groupUid;+ const QString parentUid = str(e_source_get_parent(source));+ if (!parentUid.isEmpty() && !parentUid.endsWith(QLatin1String("-stub"))) {+ if (ESource *parent = e_source_registry_ref_source(m_registry, parentUid.toUtf8().constData())) {+ group = str(e_source_get_display_name(parent));+ groupUid = parentUid;+ g_object_unref(parent);+ }+ }++ QString kind = backend;+ if (uid == QLatin1String("system-calendar")) {+ kind = QStringLiteral("system");+ }+ QString name = str(e_source_get_display_name(source));+ // The calendar every PC has, named as the board names it.+ if (uid == QLatin1String("system-calendar")) {+ name = tr("Calendar");+ } else if (uid == QLatin1String("birthdays")) {+ name = tr("Birthdays");+ }+ ECalClient *c = m_clients.value(uid);+ const bool readOnly = backend == QLatin1String("webcal") || backend == QLatin1String("contacts")+ || (c && e_client_is_readonly(E_CLIENT(c)));++ calendars << QVariantMap{+ {QStringLiteral("uid"), uid},+ {QStringLiteral("name"), name},+ {QStringLiteral("color"), color},+ {QStringLiteral("selected"), selected},+ {QStringLiteral("group"), group},+ {QStringLiteral("groupUid"), groupUid},+ {QStringLiteral("readOnly"), readOnly},+ {QStringLiteral("kind"), kind},+ // Who invitations go out as; empty where none can be sent.+ {QStringLiteral("email"), myAddress(uid)},+ };+ m_colors.insert(uid, color);+ if (readOnly) {+ m_readOnly.insert(uid);+ } else {+ m_readOnly.remove(uid);+ }+ present.insert(uid);+ if (selected && !m_clients.contains(uid)) {+ connectClient(source);+ } else if (!selected && m_clients.contains(uid)) {+ dropClient(uid);+ }+ }+ g_list_free_full(sources, g_object_unref);++ GList *collections = e_source_registry_list_enabled(m_registry, E_SOURCE_EXTENSION_COLLECTION);+ for (GList *l = collections; l; l = l->next) {+ auto *source = E_SOURCE(l->data);+ auto *ext = E_SOURCE_COLLECTION(e_source_get_extension(source, E_SOURCE_EXTENSION_COLLECTION));+ if (!e_source_collection_get_calendar_enabled(ext)) {+ continue;+ }+ const QString backend = str(e_source_backend_get_backend_name(E_SOURCE_BACKEND(ext)));+ accounts << QVariantMap{+ {QStringLiteral("uid"), str(e_source_get_uid(source))},+ {QStringLiteral("name"), str(e_source_get_display_name(source))},+ {QStringLiteral("kind"), backend},+ {QStringLiteral("email"), takeStr(e_source_collection_dup_identity(ext))},+ };+ }+ g_list_free_full(collections, g_object_unref);++ // The holidays and birthdays first in My calendars, after the PC's own.+ std::stable_sort(calendars.begin(), calendars.end(), [](const QVariant &a, const QVariant &b) {+ auto rank = [](const QVariantMap &m) {+ if (!m.value(QStringLiteral("groupUid")).toString().isEmpty()) {+ return 3;+ }+ const QString kind = m.value(QStringLiteral("kind")).toString();+ return kind == QLatin1String("system") ? 0 : (kind == QLatin1String("contacts") || kind == QLatin1String("webcal")) ? 2 : 1;+ };+ const QVariantMap ma = a.toMap();+ const QVariantMap mb = b.toMap();+ if (rank(ma) != rank(mb)) {+ return rank(ma) < rank(mb);+ }+ if (ma.value(QStringLiteral("group")) != mb.value(QStringLiteral("group"))) {+ return ma.value(QStringLiteral("group")).toString() < mb.value(QStringLiteral("group")).toString();+ }+ return false;+ });++ for (const QString &uid : m_clients.keys()) {+ if (!present.contains(uid)) {+ dropClient(uid);+ }+ }+ m_calendars = calendars;+ m_accounts = accounts;+ Q_EMIT calendarsChanged();+}++void CalendarEngine::connectClient(ESource *source)+{+ const QString uid = str(e_source_get_uid(source));+ m_clients.insert(uid, nullptr);+ auto *pending = new QString(uid);+ e_cal_client_connect(source, E_CAL_CLIENT_SOURCE_TYPE_EVENTS, 30, m_cancel, &CalendarEngine::onClientConnected, pending);+}++void CalendarEngine::onClientConnected(GObject *, GAsyncResult *result, gpointer data)+{+ const QString uid = *static_cast<QString *>(data);+ delete static_cast<QString *>(data);+ GError *error = nullptr;+ EClient *client = e_cal_client_connect_finish(result, &error);+ CalendarEngine *self = instance();+ if (!client) {+ if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {+ qCWarning(calendarLog) << "couldn't open calendar" << uid << (error ? error->message : "");+ self->m_clients.remove(uid);+ }+ g_clear_error(&error);+ return;+ }+ // Unselected while it was connecting.+ if (!self->m_clients.contains(uid)) {+ g_object_unref(client);+ return;+ }+ auto *cal = E_CAL_CLIENT(client);+ e_cal_client_set_default_timezone(cal, self->zone());+ self->m_clients.insert(uid, cal);+ self->rebuildCalendars();+ self->startView(uid);+ self->scheduleReload();+}++void CalendarEngine::dropClient(const QString &uid)+{+ if (ECalClientView *view = m_views.take(uid)) {+ g_signal_handlers_disconnect_by_data(view, this);+ e_cal_client_view_stop(view, nullptr);+ g_object_unref(view);+ }+ if (ECalClient *client = m_clients.take(uid)) {+ g_object_unref(client);+ }+ if (m_perCalendar.remove(uid)) {+ flatten();+ }+}++// Only a sign that something changed in the days on screen; the events+// themselves are fetched again, with repeats expanded.+void CalendarEngine::startView(const QString &uid)+{+ ECalClient *client = m_clients.value(uid);+ if (!client || !m_from.isValid()) {+ return;+ }+ if (ECalClientView *old = m_views.take(uid)) {+ g_signal_handlers_disconnect_by_data(old, this);+ e_cal_client_view_stop(old, nullptr);+ g_object_unref(old);+ }+ const QDateTime from(m_from, QTime(0, 0), m_zone);+ const QDateTime to(m_to, QTime(0, 0), m_zone);+ const QString sexp = QStringLiteral("(occur-in-time-range? (make-time \"%1\") (make-time \"%2\"))").arg(isoUtc(from), isoUtc(to));+ auto *pending = new QString(uid);+ e_cal_client_get_view(client, sexp.toUtf8().constData(), m_cancel, &CalendarEngine::onViewReady, pending);+}++void CalendarEngine::onViewReady(GObject *object, GAsyncResult *result, gpointer data)+{+ const QString uid = *static_cast<QString *>(data);+ delete static_cast<QString *>(data);+ ECalClientView *view = nullptr;+ GError *error = nullptr;+ if (!e_cal_client_get_view_finish(E_CAL_CLIENT(object), result, &view, &error)) {+ g_clear_error(&error);+ return;+ }+ CalendarEngine *self = instance();+ if (!self->m_clients.value(uid)) {+ g_object_unref(view);+ return;+ }+ if (ECalClientView *old = self->m_views.take(uid)) {+ g_signal_handlers_disconnect_by_data(old, self);+ e_cal_client_view_stop(old, nullptr);+ g_object_unref(old);+ }+ // Only changes matter; the first batch is what reload already has.+ e_cal_client_view_set_flags(view, E_CAL_CLIENT_VIEW_FLAGS_NONE, nullptr);+ for (const char *signal : {"objects-added", "objects-modified", "objects-removed"}) {+ g_signal_connect(view, signal, G_CALLBACK(&CalendarEngine::onViewObjects), self);+ }+ e_cal_client_view_start(view, nullptr);+ self->m_views.insert(uid, view);+}++void CalendarEngine::onViewObjects(ECalClientView *, gpointer, gpointer data)+{+ static_cast<CalendarEngine *>(data)->scheduleReload();+}++void CalendarEngine::scheduleReload()+{+ m_reloadTimer.start();+}++void CalendarEngine::run(std::function<void()> work, std::function<void()> done)+{+ QPointer<CalendarEngine> self(this);+ QThreadPool::globalInstance()->start([self, work, done]() {+ work();+ if (done && self) {+ QMetaObject::invokeMethod(self, done, Qt::QueuedConnection);+ }+ });+}++ECalClient *CalendarEngine::client(const QString &uid) const+{+ return m_clients.value(uid);+}++ICalTimezone *CalendarEngine::zone() const+{+ ICalTimezone *z = i_cal_timezone_get_builtin_timezone(m_zone.id().constData());+ return z ? z : i_cal_timezone_get_utc_timezone();+}++QDateTime CalendarEngine::toDateTime(ICalTime *time) const+{+ if (!time) {+ return {};+ }+ if (i_cal_time_is_date(time)) {+ return QDateTime(QDate(i_cal_time_get_year(time), i_cal_time_get_month(time), i_cal_time_get_day(time)), QTime(0, 0), m_zone);+ }+ ICalTimezone *z = i_cal_time_get_timezone(time);+ const time_t secs = i_cal_time_as_timet_with_zone(time, z ? z : zone());+ return QDateTime::fromSecsSinceEpoch(qint64(secs), m_zone);+}++QString CalendarEngine::myAddress(const QString &calendarUid) const+{+ if (!m_registry) {+ return {};+ }+ QString address;+ ESource *source = e_source_registry_ref_source(m_registry, calendarUid.toUtf8().constData());+ if (!source) {+ return {};+ }+ if (e_source_has_extension(source, E_SOURCE_EXTENSION_WEBDAV_BACKEND)) {+ auto *webdav = E_SOURCE_WEBDAV(e_source_get_extension(source, E_SOURCE_EXTENSION_WEBDAV_BACKEND));+ address = takeStr(e_source_webdav_dup_email_address(webdav));+ }+ if (address.isEmpty()) {+ const QString parentUid = str(e_source_get_parent(source));+ if (ESource *parent = parentUid.isEmpty() ? nullptr : e_source_registry_ref_source(m_registry, parentUid.toUtf8().constData())) {+ if (e_source_has_extension(parent, E_SOURCE_EXTENSION_COLLECTION)) {+ address = takeStr(e_source_collection_dup_identity(E_SOURCE_COLLECTION(e_source_get_extension(parent, E_SOURCE_EXTENSION_COLLECTION))));+ }+ g_object_unref(parent);+ }+ }+ g_object_unref(source);+ return address.toLower();+}++namespace+{+struct FetchContext {+ const CalendarEngine *engine;+ QString calendarUid;+ QString me;+ std::function<void(ICalComponent *, ICalTime *, ICalTime *)> add;+};++gboolean addInstance(ICalComponent *icomp, ICalTime *start, ICalTime *end, gpointer data, GCancellable *, GError **)+{+ static_cast<FetchContext *>(data)->add(icomp, start, end);+ return TRUE;+}+}++QList<CalendarEngine::Instance> CalendarEngine::fetch(ECalClient *client, const QString &calendarUid, const QDate &from, const QDate &to) const+{+ QList<Instance> out;+ const time_t start = QDateTime(from, QTime(0, 0), m_zone).toSecsSinceEpoch();+ const time_t end = QDateTime(to, QTime(0, 0), m_zone).toSecsSinceEpoch();+ FetchContext context;+ context.engine = this;+ context.calendarUid = calendarUid;+ context.me = myAddress(calendarUid);+ context.add = [&](ICalComponent *icomp, ICalTime *s, ICalTime *e) {+ Instance i;+ i.calendarUid = calendarUid;+ i.uid = str(i_cal_component_get_uid(icomp));+ i.rid = takeStr(e_cal_util_component_get_recurid_as_string(icomp));+ i.key = keyOf(calendarUid, i.uid, i.rid);+ i.title = str(i_cal_component_get_summary(icomp));+ i.location = str(i_cal_component_get_location(icomp));+ i.allDay = i_cal_time_is_date(s);+ i.start = toDateTime(s);+ i.end = toDateTime(e);+ if (!i.end.isValid() || i.end <= i.start) {+ i.end = i.allDay ? i.start.addDays(1) : i.start.addSecs(i.allDay ? 86400 : 0);+ }+ i.recurring = e_cal_util_component_has_recurrences(icomp) || !i.rid.isEmpty();+ // Free or busy, and whether someone else asked you.+ ICalProperty *transp = i_cal_component_get_first_property(icomp, I_CAL_TRANSP_PROPERTY);+ if (transp) {+ i.busy = i_cal_property_get_transp(transp) != I_CAL_TRANSP_TRANSPARENT;+ g_object_unref(transp);+ }+ if (e_cal_util_component_has_attendee(icomp)) {+ ICalProperty *organizer = i_cal_component_get_first_property(icomp, I_CAL_ORGANIZER_PROPERTY);+ const QString org = organizer ? mailtoless(i_cal_property_get_organizer(organizer)) : QString();+ g_clear_object(&organizer);+ i.invited = !context.me.isEmpty() && !org.isEmpty() && org != context.me;+ for (ICalProperty *p = i_cal_component_get_first_property(icomp, I_CAL_ATTENDEE_PROPERTY); p;+ p = i_cal_component_get_next_property(icomp, I_CAL_ATTENDEE_PROPERTY)) {+ if (mailtoless(i_cal_property_get_attendee(p)) == context.me) {+ ICalParameter *param = i_cal_property_get_first_parameter(p, I_CAL_PARTSTAT_PARAMETER);+ i.myStatus = partstatName(param ? i_cal_parameter_get_partstat(param) : I_CAL_PARTSTAT_NEEDSACTION);+ g_clear_object(¶m);+ }+ g_object_unref(p);+ }+ }+ out << i;+ };+ e_cal_client_generate_instances_sync(client, start, end, nullptr, &addInstance, &context);+ return out;+}++void CalendarEngine::setRange(const QDate &from, const QDate &to)+{+ if (from == m_from && to == m_to) {+ return;+ }+ m_from = from;+ m_to = to;+ ++m_generation;+ Q_EMIT rangeChanged();+ for (const QString &uid : m_clients.keys()) {+ startView(uid);+ }+ reload();+}++void CalendarEngine::reload()+{+ if (!m_from.isValid()) {+ return;+ }+ const int generation = m_generation;+ const QDate from = m_from;+ const QDate to = m_to;+ for (auto it = m_clients.cbegin(); it != m_clients.cend(); ++it) {+ if (!it.value()) {+ continue;+ }+ const QString uid = it.key();+ ECalClient *client = it.value();+ g_object_ref(client);+ auto result = std::make_shared<QList<Instance>>();+ run([this, client, uid, from, to, result]() {+ *result = fetch(client, uid, from, to);+ g_object_unref(client);+ }, [this, uid, generation, result]() {+ if (generation != m_generation || !m_clients.value(uid)) {+ return;+ }+ qCDebug(calendarLog) << "fetched" << result->size() << "events from" << uid;+ m_perCalendar.insert(uid, *result);+ flatten();+ });+ }+}++void CalendarEngine::flatten()+{+ m_instances.clear();+ m_byKey.clear();+ for (const QList<Instance> &list : std::as_const(m_perCalendar)) {+ m_instances << list;+ }+ std::sort(m_instances.begin(), m_instances.end(), [](const Instance &a, const Instance &b) {+ if (a.start != b.start) {+ return a.start < b.start;+ }+ return a.end > b.end;+ });+ for (int i = 0; i < m_instances.size(); ++i) {+ m_byKey.insert(m_instances[i].key, i);+ }+ ++m_revision;+ Q_EMIT eventsChanged();+}++QVariantMap CalendarEngine::row(const Instance &i) const+{+ return {+ {QStringLiteral("key"), i.key},+ {QStringLiteral("calendarUid"), i.calendarUid},+ {QStringLiteral("title"), i.title.isEmpty() ? tr("(No title)") : i.title},+ {QStringLiteral("location"), i.location},+ {QStringLiteral("color"), m_colors.value(i.calendarUid)},+ {QStringLiteral("readOnly"), m_readOnly.contains(i.calendarUid)},+ {QStringLiteral("start"), i.start},+ {QStringLiteral("end"), i.end},+ {QStringLiteral("allDay"), i.allDay},+ {QStringLiteral("recurring"), i.recurring},+ {QStringLiteral("invited"), i.invited},+ {QStringLiteral("busy"), i.busy},+ {QStringLiteral("myStatus"), i.myStatus},+ {QStringLiteral("timeText"), i.allDay ? QString() : Formats::time(i.start)},+ {QStringLiteral("rangeText"), i.allDay ? tr("All day") : tr("%1 to %2").arg(Formats::time(i.start), Formats::time(i.end))},+ };+}++namespace+{+bool fillsDays(const QDateTime &start, const QDateTime &end, bool allDay)+{+ return allDay || start.secsTo(end) >= 86400;+}+}++QVariantList CalendarEngine::timedOn(const QDate &day) const+{+ struct Seg {+ const Instance *i;+ int s;+ int e;+ int column = 0;+ int columns = 1;+ };+ QList<Seg> segs;+ const QDateTime dayStart(day, QTime(0, 0), m_zone);+ const QDateTime dayEnd(day.addDays(1), QTime(0, 0), m_zone);+ for (const Instance &i : m_instances) {+ if (fillsDays(i.start, i.end, i.allDay) || i.end <= dayStart || i.start >= dayEnd) {+ continue;+ }+ const int s = i.start < dayStart ? 0 : int(dayStart.secsTo(i.start) / 60);+ int e = i.end > dayEnd ? 24 * 60 : int(dayStart.secsTo(i.end) / 60);+ // Short events still need room for their title.+ e = std::max(e, s + 15);+ segs << Seg{&i, s, e};+ }+ std::sort(segs.begin(), segs.end(), [](const Seg &a, const Seg &b) {+ return a.s != b.s ? a.s < b.s : a.e > b.e;+ });+ // Overlapping events share the width: each cluster of overlaps is split+ // into as many columns as it needs at its busiest.+ int clusterStart = 0;+ int clusterEnd = -1;+ QList<int> columnEnds;+ auto closeCluster = [&](int upTo) {+ for (int k = clusterStart; k < upTo; ++k) {+ segs[k].columns = int(columnEnds.size());+ }+ };+ for (int k = 0; k < segs.size(); ++k) {+ if (segs[k].s >= clusterEnd) {+ closeCluster(k);+ clusterStart = k;+ columnEnds.clear();+ }+ int c = 0;+ while (c < columnEnds.size() && columnEnds[c] > segs[k].s) {+ ++c;+ }+ if (c == columnEnds.size()) {+ columnEnds << segs[k].e;+ } else {+ columnEnds[c] = segs[k].e;+ }+ segs[k].column = c;+ clusterEnd = std::max(clusterEnd, segs[k].e);+ }+ closeCluster(int(segs.size()));++ QVariantList out;+ for (const Seg &s : segs) {+ QVariantMap m = row(*s.i);+ m.insert(QStringLiteral("startMinute"), s.s);+ m.insert(QStringLiteral("endMinute"), s.e);+ m.insert(QStringLiteral("column"), s.column);+ m.insert(QStringLiteral("columns"), s.columns);+ out << m;+ }+ return out;+}++QVariantList CalendarEngine::allDayBetween(const QDate &from, const QDate &to) const+{+ QVariantList out;+ QList<QList<QPair<int, int>>> rows;+ const int days = int(from.daysTo(to));+ for (const Instance &i : m_instances) {+ if (!fillsDays(i.start, i.end, i.allDay)) {+ continue;+ }+ const QDate first = i.start.date();+ // An all-day end is the start of the day after.+ const QDate last = (i.end.time() == QTime(0, 0) ? i.end.date().addDays(-1) : i.end.date());+ if (last < from || first >= to) {+ continue;+ }+ const int a = std::max(0, int(from.daysTo(first)));+ const int b = std::min(days - 1, int(from.daysTo(last)));+ int r = 0;+ for (; r < rows.size(); ++r) {+ bool free = true;+ for (const auto &span : rows[r]) {+ if (!(b < span.first || a > span.second)) {+ free = false;+ break;+ }+ }+ if (free) {+ break;+ }+ }+ if (r == rows.size()) {+ rows.append(QList<QPair<int, int>>());+ }+ rows[r].append({a, b});+ QVariantMap m = row(i);+ m.insert(QStringLiteral("firstColumn"), a);+ m.insert(QStringLiteral("lastColumn"), b);+ m.insert(QStringLiteral("row"), r);+ out << m;+ }+ return out;+}++QVariantList CalendarEngine::eventsOn(const QDate &day) const+{+ QVariantList allDay;+ QVariantList timed;+ const QDateTime dayStart(day, QTime(0, 0), m_zone);+ const QDateTime dayEnd(day.addDays(1), QTime(0, 0), m_zone);+ for (const Instance &i : m_instances) {+ if (i.end <= dayStart || i.start >= dayEnd) {+ continue;+ }+ (fillsDays(i.start, i.end, i.allDay) ? allDay : timed) << row(i);+ }+ return allDay + timed;+}++bool CalendarEngine::busyOn(const QDate &day) const+{+ const QDateTime dayStart(day, QTime(0, 0), m_zone);+ const QDateTime dayEnd(day.addDays(1), QTime(0, 0), m_zone);+ for (const Instance &i : m_instances) {+ if (i.end > dayStart && i.start < dayEnd) {+ return true;+ }+ }+ return false;+}++QVariantMap CalendarEngine::event(const QString &key) const+{+ QString calendarUid, uid, rid;+ if (!splitKey(key, &calendarUid, &uid, &rid)) {+ return {};+ }+ ECalClient *c = client(calendarUid);+ if (!c) {+ return {};+ }+ ICalComponent *icomp = nullptr;+ GError *error = nullptr;+ if (!e_cal_client_get_object_sync(c, uid.toUtf8().constData(), rid.isEmpty() ? nullptr : rid.toUtf8().constData(), &icomp, nullptr, &error)) {+ qCWarning(calendarLog) << "couldn't read event:" << (error ? error->message : "");+ g_clear_error(&error);+ return {};+ }+ ECalComponent *comp = e_cal_component_new_from_icalcomponent(icomp);+ if (!comp) {+ return {};+ }+ QVariantMap m;+ const int index = m_byKey.value(key, -1);+ if (index >= 0) {+ m = row(m_instances[index]);+ } else {+ m.insert(QStringLiteral("key"), key);+ m.insert(QStringLiteral("calendarUid"), calendarUid);+ m.insert(QStringLiteral("color"), m_colors.value(calendarUid));+ m.insert(QStringLiteral("title"), str(i_cal_component_get_summary(icomp)));+ m.insert(QStringLiteral("location"), str(i_cal_component_get_location(icomp)));+ ECalComponentDateTime *dt = e_cal_component_get_dtstart(comp);+ ECalComponentDateTime *de = e_cal_component_get_dtend(comp);+ if (dt) {+ ICalTime *t = e_cal_component_datetime_get_value(dt);+ m.insert(QStringLiteral("allDay"), bool(i_cal_time_is_date(t)));+ m.insert(QStringLiteral("start"), toDateTime(t));+ }+ if (de) {+ m.insert(QStringLiteral("end"), toDateTime(e_cal_component_datetime_get_value(de)));+ }+ e_cal_component_datetime_free(dt);+ e_cal_component_datetime_free(de);+ }++ QStringList notes;+ GSList *descriptions = e_cal_component_get_descriptions(comp);+ for (GSList *l = descriptions; l; l = l->next) {+ notes << str(e_cal_component_text_get_value(static_cast<ECalComponentText *>(l->data)));+ }+ g_slist_free_full(descriptions, reinterpret_cast<GDestroyNotify>(e_cal_component_text_free));+ m.insert(QStringLiteral("description"), notes.join(QLatin1Char('\n')));++ // The first reminder, in minutes before the start.+ int reminder = -1;+ GSList *alarmUids = e_cal_component_get_alarm_uids(comp);+ for (GSList *l = alarmUids; l && reminder < 0; l = l->next) {+ ECalComponentAlarm *alarm = e_cal_component_get_alarm(comp, static_cast<const gchar *>(l->data));+ if (!alarm) {+ continue;+ }+ ECalComponentAlarmTrigger *trigger = e_cal_component_alarm_get_trigger(alarm);+ if (trigger && e_cal_component_alarm_trigger_get_kind(trigger) == E_CAL_COMPONENT_ALARM_TRIGGER_RELATIVE_START) {+ ICalDuration *d = e_cal_component_alarm_trigger_get_duration(trigger);+ if (d) {+ reminder = std::max(0, -int(i_cal_duration_as_int(d)) / 60);+ }+ }+ e_cal_component_alarm_free(alarm);+ }+ g_slist_free_full(alarmUids, g_free);+ m.insert(QStringLiteral("reminder"), reminder);++ QString repeat = QStringLiteral("none");+ if (e_cal_component_has_rrules(comp)) {+ GSList *rules = e_cal_component_get_rrules(comp);+ if (rules) {+ auto *r = static_cast<ICalRecurrence *>(rules->data);+ const QString text = takeStr(i_cal_recurrence_to_string(r));+ switch (i_cal_recurrence_get_freq(r)) {+ case I_CAL_DAILY_RECURRENCE:+ repeat = QStringLiteral("daily");+ break;+ case I_CAL_WEEKLY_RECURRENCE:+ repeat = text.contains(QLatin1String("BYDAY=MO,TU,WE,TH,FR")) ? QStringLiteral("weekdays") : QStringLiteral("weekly");+ break;+ case I_CAL_MONTHLY_RECURRENCE:+ repeat = QStringLiteral("monthly");+ break;+ case I_CAL_YEARLY_RECURRENCE:+ repeat = QStringLiteral("yearly");+ break;+ default:+ repeat = QStringLiteral("other");+ }+ }+ g_slist_free_full(rules, g_object_unref);+ }+ m.insert(QStringLiteral("repeat"), repeat);+ m.insert(QStringLiteral("recurring"), repeat != QLatin1String("none") || !rid.isEmpty());+ m.insert(QStringLiteral("busy"), e_cal_component_get_transparency(comp) != E_CAL_COMPONENT_TRANSP_TRANSPARENT);+ m.insert(QStringLiteral("private"), e_cal_component_get_classification(comp) == E_CAL_COMPONENT_CLASS_PRIVATE+ || e_cal_component_get_classification(comp) == E_CAL_COMPONENT_CLASS_CONFIDENTIAL);++ const QString me = myAddress(calendarUid);+ QString organizer;+ QString organizerName;+ if (ECalComponentOrganizer *o = e_cal_component_get_organizer(comp)) {+ organizer = mailtoless(e_cal_component_organizer_get_value(o));+ organizerName = str(e_cal_component_organizer_get_cn(o));+ e_cal_component_organizer_free(o);+ }+ QVariantList people;+ int going = 0, maybe = 0;+ QString myStatus;+ GSList *attendees = e_cal_component_get_attendees(comp);+ for (GSList *l = attendees; l; l = l->next) {+ auto *a = static_cast<ECalComponentAttendee *>(l->data);+ const QString email = mailtoless(e_cal_component_attendee_get_value(a));+ const QString status = partstatName(e_cal_component_attendee_get_partstat(a));+ going += status == QLatin1String("going");+ maybe += status == QLatin1String("maybe");+ if (email == me) {+ myStatus = status;+ }+ people << QVariantMap{+ {QStringLiteral("email"), email},+ {QStringLiteral("name"), str(e_cal_component_attendee_get_cn(a))},+ {QStringLiteral("status"), email == organizer ? QStringLiteral("organiser") : status},+ {QStringLiteral("me"), email == me},+ };+ }+ g_slist_free_full(attendees, reinterpret_cast<GDestroyNotify>(e_cal_component_attendee_free));+ // The organiser first, as the board lists them.+ std::stable_sort(people.begin(), people.end(), [](const QVariant &a, const QVariant &b) {+ return a.toMap().value(QStringLiteral("status")) == QLatin1String("organiser") && b.toMap().value(QStringLiteral("status")) != QLatin1String("organiser");+ });+ if (!organizer.isEmpty() && !people.isEmpty()) {+ bool listed = false;+ for (const QVariant &p : std::as_const(people)) {+ listed = listed || p.toMap().value(QStringLiteral("email")) == organizer;+ }+ if (!listed) {+ people.prepend(QVariantMap{{QStringLiteral("email"), organizer}, {QStringLiteral("name"), organizerName}, {QStringLiteral("status"), QStringLiteral("organiser")}, {QStringLiteral("me"), organizer == me}});+ }+ }+ m.insert(QStringLiteral("people"), people);+ m.insert(QStringLiteral("going"), going);+ m.insert(QStringLiteral("maybe"), maybe);+ m.insert(QStringLiteral("myStatus"), myStatus);+ m.insert(QStringLiteral("invited"), !organizer.isEmpty() && !me.isEmpty() && organizer != me && !people.isEmpty());+ m.insert(QStringLiteral("organizer"), organizer);+ m.insert(QStringLiteral("me"), me);+ bool readOnly = e_client_is_readonly(E_CLIENT(c));+ m.insert(QStringLiteral("readOnly"), readOnly);+ g_object_unref(comp);+ return m;+}++namespace+{+ICalTime *icalTime(const QDateTime &t, bool allDay, ICalTimezone *zone)+{+ if (allDay) {+ ICalTime *d = i_cal_time_new_null_time();+ i_cal_time_set_date(d, t.date().year(), t.date().month(), t.date().day());+ i_cal_time_set_is_date(d, TRUE);+ return d;+ }+ return i_cal_time_new_from_timet_with_zone(time_t(t.toSecsSinceEpoch()), FALSE, zone);+}++void setTimes(ECalComponent *comp, const QDateTime &start, const QDateTime &end, bool allDay, ICalTimezone *zone)+{+ const gchar *tzid = allDay ? nullptr : i_cal_timezone_get_tzid(zone);+ ECalComponentDateTime *s = e_cal_component_datetime_new_take(icalTime(start, allDay, zone), g_strdup(tzid));+ // An all-day event ends at the start of the day after its last.+ const QDateTime e = allDay ? QDateTime(end.date().addDays(1), QTime(0, 0), end.timeZone()) : end;+ ECalComponentDateTime *f = e_cal_component_datetime_new_take(icalTime(e, allDay, zone), g_strdup(tzid));+ e_cal_component_set_dtstart(comp, s);+ e_cal_component_set_dtend(comp, f);+ e_cal_component_datetime_free(s);+ e_cal_component_datetime_free(f);+}++void setRepeat(ECalComponent *comp, const QString &repeat)+{+ QString rule;+ if (repeat == QLatin1String("daily")) {+ rule = QStringLiteral("FREQ=DAILY");+ } else if (repeat == QLatin1String("weekdays")) {+ rule = QStringLiteral("FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR");+ } else if (repeat == QLatin1String("weekly")) {+ rule = QStringLiteral("FREQ=WEEKLY");+ } else if (repeat == QLatin1String("monthly")) {+ rule = QStringLiteral("FREQ=MONTHLY");+ } else if (repeat == QLatin1String("yearly")) {+ rule = QStringLiteral("FREQ=YEARLY");+ } else if (repeat == QLatin1String("other")) {+ // A rule made elsewhere that this form can't show; left as it is.+ return;+ }+ if (rule.isEmpty()) {+ e_cal_component_set_rrules(comp, nullptr);+ return;+ }+ GSList *rules = g_slist_prepend(nullptr, i_cal_recurrence_new_from_string(rule.toUtf8().constData()));+ e_cal_component_set_rrules(comp, rules);+ g_slist_free_full(rules, g_object_unref);+}++void setReminder(ECalComponent *comp, int minutes, const QString &title)+{+ e_cal_component_remove_all_alarms(comp);+ if (minutes < 0) {+ return;+ }+ ECalComponentAlarm *alarm = e_cal_component_alarm_new();+ e_cal_component_alarm_set_action(alarm, E_CAL_COMPONENT_ALARM_DISPLAY);+ ICalDuration *before = i_cal_duration_new_from_int(-minutes * 60);+ ECalComponentAlarmTrigger *trigger = e_cal_component_alarm_trigger_new_relative(E_CAL_COMPONENT_ALARM_TRIGGER_RELATIVE_START, before);+ e_cal_component_alarm_take_trigger(alarm, trigger);+ g_object_unref(before);+ e_cal_component_alarm_take_description(alarm, e_cal_component_text_new(title.toUtf8().constData(), nullptr));+ e_cal_component_add_alarm(comp, alarm);+ e_cal_component_alarm_free(alarm);+}++void setPeople(ECalComponent *comp, const QStringList &emails, const QString &me, const QVariantList &previous)+{+ if (emails.isEmpty()) {+ e_cal_component_set_attendees(comp, nullptr);+ e_cal_component_set_organizer(comp, nullptr);+ return;+ }+ QHash<QString, QString> statuses;+ for (const QVariant &v : previous) {+ const QVariantMap p = v.toMap();+ statuses.insert(p.value(QStringLiteral("email")).toString(), p.value(QStringLiteral("status")).toString());+ }+ GSList *list = nullptr;+ for (const QString &email : emails) {+ const QString e = email.trimmed().toLower();+ if (e.isEmpty() || e == me) {+ continue;+ }+ const QString was = statuses.value(e);+ const ICalParameterPartstat partstat = was == QLatin1String("going") ? I_CAL_PARTSTAT_ACCEPTED+ : was == QLatin1String("maybe") ? I_CAL_PARTSTAT_TENTATIVE+ : was == QLatin1String("notGoing") ? I_CAL_PARTSTAT_DECLINED : I_CAL_PARTSTAT_NEEDSACTION;+ list = g_slist_append(list, e_cal_component_attendee_new_full(("mailto:" + e).toUtf8().constData(), nullptr, I_CAL_CUTYPE_INDIVIDUAL,+ I_CAL_ROLE_REQPARTICIPANT, partstat, TRUE, nullptr, nullptr, nullptr, nullptr, nullptr));+ }+ if (!me.isEmpty()) {+ // The organiser goes along too.+ list = g_slist_prepend(list, e_cal_component_attendee_new_full(("mailto:" + me).toUtf8().constData(), nullptr, I_CAL_CUTYPE_INDIVIDUAL,+ I_CAL_ROLE_CHAIR, I_CAL_PARTSTAT_ACCEPTED, FALSE, nullptr, nullptr, nullptr, nullptr, nullptr));+ ECalComponentOrganizer *organizer = e_cal_component_organizer_new_full(("mailto:" + me).toUtf8().constData(), nullptr, nullptr, nullptr);+ e_cal_component_set_organizer(comp, organizer);+ e_cal_component_organizer_free(organizer);+ }+ e_cal_component_set_attendees(comp, list);+ g_slist_free_full(list, reinterpret_cast<GDestroyNotify>(e_cal_component_attendee_free));+}+}++// data: key (empty for a new event), calendarUid, title, start, end+// (QDateTime; for all-day events the first and last day), allDay, location,+// description, reminder (minutes before, -1 for none), repeat (none, daily,+// weekdays, weekly, monthly, yearly), attendees (addresses), busy, private,+// wholeSeries (for a change to one repeat of a series).+void CalendarEngine::saveEvent(const QVariantMap &data)+{+ const QString key = data.value(QStringLiteral("key")).toString();+ QString calendarUid = data.value(QStringLiteral("calendarUid")).toString();+ QString oldCalendar, uid, rid;+ if (!key.isEmpty()) {+ splitKey(key, &oldCalendar, &uid, &rid);+ }+ if (calendarUid.isEmpty()) {+ calendarUid = oldCalendar.isEmpty() ? defaultCalendar() : oldCalendar;+ }+ ECalClient *target = client(calendarUid);+ if (!target) {+ Q_EMIT notice(tr("That calendar isn't open. Turn it on in the list and try again."));+ return;+ }+ ECalClient *source = oldCalendar.isEmpty() ? nullptr : client(oldCalendar);+ const bool moving = source && oldCalendar != calendarUid;+ const bool wholeSeries = data.value(QStringLiteral("wholeSeries"), true).toBool();+ const QVariantMap previous = key.isEmpty() ? QVariantMap() : event(key);+ const QString me = myAddress(calendarUid);+ ICalTimezone *z = zone();+ g_object_ref(target);+ if (source) {+ g_object_ref(source);+ }+ auto result = std::make_shared<QString>();+ auto error = std::make_shared<QString>();+ run([=]() {+ ECalComponent *comp = nullptr;+ if (!uid.isEmpty() && !moving) {+ ICalComponent *icomp = nullptr;+ const QByteArray r = wholeSeries ? QByteArray() : rid.toUtf8();+ if (e_cal_client_get_object_sync(target, uid.toUtf8().constData(), r.isEmpty() ? nullptr : r.constData(), &icomp, nullptr, nullptr)) {+ comp = e_cal_component_new_from_icalcomponent(icomp);+ }+ }+ const bool creating = !comp;+ if (creating) {+ comp = e_cal_component_new();+ e_cal_component_set_new_vtype(comp, E_CAL_COMPONENT_EVENT);+ gchar *newUid = e_util_generate_uid();+ e_cal_component_set_uid(comp, newUid);+ g_free(newUid);+ }+ const QString title = data.value(QStringLiteral("title")).toString().trimmed();+ ECalComponentText *summary = e_cal_component_text_new(title.toUtf8().constData(), nullptr);+ e_cal_component_set_summary(comp, summary);+ e_cal_component_text_free(summary);+ const QString location = data.value(QStringLiteral("location")).toString().trimmed();+ e_cal_component_set_location(comp, location.isEmpty() ? nullptr : location.toUtf8().constData());+ const QString notes = data.value(QStringLiteral("description")).toString();+ GSList *descriptions = notes.trimmed().isEmpty() ? nullptr : g_slist_prepend(nullptr, e_cal_component_text_new(notes.toUtf8().constData(), nullptr));+ e_cal_component_set_descriptions(comp, descriptions);+ g_slist_free_full(descriptions, reinterpret_cast<GDestroyNotify>(e_cal_component_text_free));++ const bool allDay = data.value(QStringLiteral("allDay")).toBool();+ // Moving one repeat keeps the series' times; changing the series+ // keeps each repeat where the rule puts it.+ if (!(rid.isEmpty() == false && wholeSeries && !creating)) {+ setTimes(comp, data.value(QStringLiteral("start")).toDateTime(), data.value(QStringLiteral("end")).toDateTime(), allDay, z);+ }+ if (rid.isEmpty() || wholeSeries) {+ setRepeat(comp, data.value(QStringLiteral("repeat")).toString());+ }+ setReminder(comp, data.value(QStringLiteral("reminder"), -1).toInt(), title);+ e_cal_component_set_transparency(comp, data.value(QStringLiteral("busy"), true).toBool() ? E_CAL_COMPONENT_TRANSP_OPAQUE : E_CAL_COMPONENT_TRANSP_TRANSPARENT);+ e_cal_component_set_classification(comp, data.value(QStringLiteral("private")).toBool() ? E_CAL_COMPONENT_CLASS_PRIVATE : E_CAL_COMPONENT_CLASS_PUBLIC);+ setPeople(comp, data.value(QStringLiteral("attendees")).toStringList(), me, previous.value(QStringLiteral("people")).toList());+ if (!creating) {+ e_cal_component_commit_sequence(comp);+ }++ GError *err = nullptr;+ if (!allDay) {+ e_cal_client_add_timezone_sync(target, z, nullptr, nullptr);+ }+ ICalComponent *icomp = e_cal_component_get_icalcomponent(comp);+ bool ok;+ gchar *newUid = nullptr;+ if (creating) {+ ok = e_cal_client_create_object_sync(target, icomp, E_CAL_OPERATION_FLAG_NONE, &newUid, nullptr, &err);+ } else {+ ok = e_cal_client_modify_object_sync(target, icomp, (rid.isEmpty() || wholeSeries) ? E_CAL_OBJ_MOD_ALL : E_CAL_OBJ_MOD_THIS,+ E_CAL_OPERATION_FLAG_NONE, nullptr, &err);+ }+ if (ok && moving) {+ e_cal_client_remove_object_sync(source, uid.toUtf8().constData(), nullptr, E_CAL_OBJ_MOD_ALL, E_CAL_OPERATION_FLAG_NONE, nullptr, nullptr);+ }+ if (ok) {+ const QString savedUid = newUid ? str(newUid) : str(e_cal_component_get_uid(comp));+ *result = keyOf(calendarUid, savedUid, (creating || wholeSeries) ? QString() : rid);+ } else {+ *error = str(err ? err->message : nullptr);+ }+ g_free(newUid);+ g_clear_error(&err);+ g_object_unref(comp);+ g_object_unref(target);+ if (source) {+ g_object_unref(source);+ }+ }, [this, result, error]() {+ if (!error->isEmpty()) {+ qCWarning(calendarLog) << "couldn't save event:" << *error;+ Q_EMIT notice(tr("The event wasn't saved. %1").arg(*error));+ return;+ }+ scheduleReload();+ Q_EMIT saved(*result);+ });+}++void CalendarEngine::removeEvent(const QString &key, bool wholeSeries)+{+ QString calendarUid, uid, rid;+ if (!splitKey(key, &calendarUid, &uid, &rid)) {+ return;+ }+ ECalClient *c = client(calendarUid);+ if (!c) {+ return;+ }+ // Gone from the view at once; the service catches up.+ if (m_perCalendar.contains(calendarUid)) {+ auto &list = m_perCalendar[calendarUid];+ list.erase(std::remove_if(list.begin(), list.end(), [&](const Instance &i) {+ return i.uid == uid && (wholeSeries || i.rid == rid);+ }), list.end());+ flatten();+ }+ g_object_ref(c);+ auto error = std::make_shared<QString>();+ run([=]() {+ GError *err = nullptr;+ const bool all = wholeSeries || rid.isEmpty();+ if (!e_cal_client_remove_object_sync(c, uid.toUtf8().constData(), all ? nullptr : rid.toUtf8().constData(),+ all ? E_CAL_OBJ_MOD_ALL : E_CAL_OBJ_MOD_THIS, E_CAL_OPERATION_FLAG_NONE, nullptr, &err)) {+ *error = str(err ? err->message : nullptr);+ }+ g_clear_error(&err);+ g_object_unref(c);+ }, [this, error]() {+ if (!error->isEmpty()) {+ Q_EMIT notice(tr("The event wasn't deleted. %1").arg(*error));+ }+ scheduleReload();+ });+}++void CalendarEngine::respond(const QString &key, const QString &status)+{+ QString calendarUid, uid, rid;+ if (!splitKey(key, &calendarUid, &uid, &rid)) {+ return;+ }+ ECalClient *c = client(calendarUid);+ const QString me = myAddress(calendarUid);+ if (!c || me.isEmpty()) {+ return;+ }+ const ICalParameterPartstat partstat = status == QLatin1String("going") ? I_CAL_PARTSTAT_ACCEPTED+ : status == QLatin1String("maybe") ? I_CAL_PARTSTAT_TENTATIVE : I_CAL_PARTSTAT_DECLINED;+ g_object_ref(c);+ auto error = std::make_shared<QString>();+ run([=]() {+ ICalComponent *icomp = nullptr;+ GError *err = nullptr;+ if (!e_cal_client_get_object_sync(c, uid.toUtf8().constData(), nullptr, &icomp, nullptr, &err)) {+ *error = str(err ? err->message : nullptr);+ g_clear_error(&err);+ g_object_unref(c);+ return;+ }+ for (ICalProperty *p = i_cal_component_get_first_property(icomp, I_CAL_ATTENDEE_PROPERTY); p;+ p = i_cal_component_get_next_property(icomp, I_CAL_ATTENDEE_PROPERTY)) {+ if (mailtoless(i_cal_property_get_attendee(p)) == me) {+ i_cal_property_remove_parameter_by_kind(p, I_CAL_PARTSTAT_PARAMETER);+ ICalParameter *param = i_cal_parameter_new_partstat(partstat);+ i_cal_property_take_parameter(p, param);+ i_cal_property_remove_parameter_by_kind(p, I_CAL_RSVP_PARAMETER);+ }+ g_object_unref(p);+ }+ // The calendar's server tells the organiser.+ if (!e_cal_client_modify_object_sync(c, icomp, E_CAL_OBJ_MOD_ALL, E_CAL_OPERATION_FLAG_NONE, nullptr, &err)) {+ *error = str(err ? err->message : nullptr);+ }+ g_clear_error(&err);+ g_object_unref(icomp);+ g_object_unref(c);+ }, [this, error]() {+ if (!error->isEmpty()) {+ Q_EMIT notice(tr("Your answer wasn't saved. %1").arg(*error));+ }+ scheduleReload();+ });+}++void CalendarEngine::moveEvent(const QString &key, const QDateTime &start)+{+ const int index = m_byKey.value(key, -1);+ if (index < 0) {+ return;+ }+ const Instance i = m_instances[index];+ const qint64 length = i.start.secsTo(i.end);+ QVariantMap data = event(key);+ if (data.isEmpty() || data.value(QStringLiteral("readOnly")).toBool()) {+ return;+ }+ QStringList attendees;+ for (const QVariant &p : data.value(QStringLiteral("people")).toList()) {+ attendees << p.toMap().value(QStringLiteral("email")).toString();+ }+ data.insert(QStringLiteral("attendees"), attendees);+ data.insert(QStringLiteral("start"), start);+ data.insert(QStringLiteral("end"), i.allDay ? start.addSecs(length - 86400) : start.addSecs(length));+ // A dragged repeat moves on its own.+ data.insert(QStringLiteral("wholeSeries"), !i.recurring);+ // Drawn where it was dropped straight away.+ if (m_perCalendar.contains(i.calendarUid)) {+ for (Instance &x : m_perCalendar[i.calendarUid]) {+ if (x.key == key) {+ x.start = start;+ x.end = start.addSecs(length);+ }+ }+ flatten();+ }+ saveEvent(data);+}++void CalendarEngine::loadDay(const QDate &day)+{+ QList<QPair<QString, ECalClient *>> clients;+ for (auto it = m_clients.cbegin(); it != m_clients.cend(); ++it) {+ if (it.value()) {+ g_object_ref(it.value());+ clients << qMakePair(it.key(), it.value());+ }+ }+ auto result = std::make_shared<QList<Instance>>();+ run([this, clients, day, result]() {+ for (const auto &[uid, c] : clients) {+ *result << fetch(c, uid, day, day.addDays(1));+ g_object_unref(c);+ }+ }, [this, day, result]() {+ std::sort(result->begin(), result->end(), [](const Instance &a, const Instance &b) {+ return a.start < b.start;+ });+ QVariantList rows;+ for (const Instance &i : std::as_const(*result)) {+ QVariantMap m = row(i);+ const QDateTime dayStart(day, QTime(0, 0), m_zone);+ m.insert(QStringLiteral("startMinute"), i.allDay ? 0 : std::max<qint64>(0, dayStart.secsTo(i.start) / 60));+ m.insert(QStringLiteral("endMinute"), i.allDay ? 24 * 60 : std::min<qint64>(24 * 60, dayStart.secsTo(i.end) / 60));+ rows << m;+ }+ Q_EMIT dayLoaded(day, rows);+ });+}++void CalendarEngine::search(const QString &text)+{+ const QString t = text.trimmed();+ if (t.isEmpty()) {+ Q_EMIT searchDone(text, {});+ return;+ }+ const QDateTime now = QDateTime::currentDateTime();+ const QString sexp = QStringLiteral("(and (occur-in-time-range? (make-time \"%1\") (make-time \"%2\")) (or (contains? \"summary\" %3) (contains? \"location\" %3) (contains? \"description\" %3)))")+ .arg(isoUtc(now.addYears(-1)), isoUtc(now.addYears(1)), quoted(t));+ QList<QPair<QString, ECalClient *>> clients;+ for (auto it = m_clients.cbegin(); it != m_clients.cend(); ++it) {+ if (it.value()) {+ g_object_ref(it.value());+ clients << qMakePair(it.key(), it.value());+ }+ }+ auto result = std::make_shared<QVariantList>();+ run([this, clients, sexp, result]() {+ for (const auto &[uid, c] : clients) {+ GSList *objects = nullptr;+ if (e_cal_client_get_object_list_sync(c, sexp.toUtf8().constData(), &objects, nullptr, nullptr)) {+ for (GSList *l = objects; l; l = l->next) {+ auto *icomp = static_cast<ICalComponent *>(l->data);+ ICalTime *start = i_cal_component_get_dtstart(icomp);+ const QDateTime when = toDateTime(start);+ const bool allDay = start && i_cal_time_is_date(start);+ g_clear_object(&start);+ const QString rid = takeStr(e_cal_util_component_get_recurid_as_string(icomp));+ *result << QVariantMap{+ {QStringLiteral("key"), keyOf(uid, str(i_cal_component_get_uid(icomp)), rid)},+ {QStringLiteral("title"), str(i_cal_component_get_summary(icomp))},+ {QStringLiteral("location"), str(i_cal_component_get_location(icomp))},+ {QStringLiteral("start"), when},+ {QStringLiteral("allDay"), allDay},+ {QStringLiteral("calendarUid"), uid},+ };+ }+ g_slist_free_full(objects, g_object_unref);+ }+ g_object_unref(c);+ }+ }, [this, text, result]() {+ QVariantList rows = *result;+ for (QVariant &v : rows) {+ QVariantMap m = v.toMap();+ m.insert(QStringLiteral("color"), m_colors.value(m.value(QStringLiteral("calendarUid")).toString()));+ v = m;+ }+ std::sort(rows.begin(), rows.end(), [](const QVariant &a, const QVariant &b) {+ return a.toMap().value(QStringLiteral("start")).toDateTime() < b.toMap().value(QStringLiteral("start")).toDateTime();+ });+ Q_EMIT searchDone(text, rows);+ });+}++void CalendarEngine::setSelected(const QString &calendarUid, bool selected)+{+ if (!m_registry) {+ return;+ }+ ESource *source = e_source_registry_ref_source(m_registry, calendarUid.toUtf8().constData());+ if (!source) {+ return;+ }+ auto *selectable = E_SOURCE_SELECTABLE(e_source_get_extension(source, E_SOURCE_EXTENSION_CALENDAR));+ e_source_selectable_set_selected(selectable, selected);+ e_source_write(source, nullptr, nullptr, nullptr);+ g_object_unref(source);+ // The list changes now; the registry confirms it a moment later.+ for (QVariant &v : m_calendars) {+ QVariantMap m = v.toMap();+ if (m.value(QStringLiteral("uid")) == calendarUid) {+ m.insert(QStringLiteral("selected"), selected);+ v = m;+ }+ }+ Q_EMIT calendarsChanged();+}++QString CalendarEngine::defaultCalendar() const+{+ if (!m_registry) {+ return QStringLiteral("system-calendar");+ }+ ESource *source = e_source_registry_ref_default_calendar(m_registry);+ const QString uid = source ? str(e_source_get_uid(source)) : QStringLiteral("system-calendar");+ g_clear_object(&source);+ return uid;+}++void CalendarEngine::setDefaultCalendar(const QString &uid)+{+ if (!m_registry) {+ return;+ }+ if (ESource *source = e_source_registry_ref_source(m_registry, uid.toUtf8().constData())) {+ e_source_registry_set_default_calendar(m_registry, source);+ g_object_unref(source);+ Q_EMIT calendarsChanged();+ }+}++QString CalendarEngine::timeZoneId() const+{+ return QString::fromUtf8(m_zone.id());+}++QString CalendarEngine::timeZoneName() const+{+ QString city = QString::fromUtf8(m_zone.id()).section(QLatin1Char('/'), -1).replace(QLatin1Char('_'), QLatin1Char(' '));+ return tr("%1 (%2)").arg(city, m_zone.abbreviation(QDateTime::currentDateTime()));+}++void CalendarEngine::setTimeZoneId(const QString &id)+{+ QTimeZone z = id.isEmpty() ? QTimeZone::systemTimeZone() : QTimeZone(id.toUtf8());+ if (!z.isValid() || z == m_zone) {+ return;+ }+ m_zone = z;+ QSettings().setValue(QStringLiteral("calendar/timeZone"), id);+ for (ECalClient *c : std::as_const(m_clients)) {+ if (c) {+ e_cal_client_set_default_timezone(c, zone());+ }+ }+ Q_EMIT timeZoneChanged();+ ++m_generation;+ reload();+}++void CalendarEngine::createSources(const QList<ESource *> &sources, std::function<void(bool, const QString &)> done)+{+ if (!m_registry) {+ done(false, tr("The calendar service isn't running."));+ return;+ }+ ESourceRegistry *registry = m_registry;+ g_object_ref(registry);+ auto error = std::make_shared<QString>();+ run([registry, sources, error]() {+ GList *list = nullptr;+ for (ESource *s : sources) {+ list = g_list_append(list, s);+ }+ GError *err = nullptr;+ if (!e_source_registry_create_sources_sync(registry, list, nullptr, &err)) {+ *error = str(err ? err->message : "");+ }+ g_clear_error(&err);+ g_list_free(list);+ g_object_unref(registry);+ }, [sources, error, done]() {+ for (ESource *s : sources) {+ g_object_unref(s);+ }+ done(error->isEmpty(), *error);+ });+}++namespace+{+ESource *newCalendarSource(const QString &parent, const QString &backend, const QString &name, const QString &color)+{+ ESource *source = e_source_new(nullptr, nullptr, nullptr);+ e_source_set_parent(source, parent.toUtf8().constData());+ e_source_set_display_name(source, name.toUtf8().constData());+ auto *ext = e_source_get_extension(source, E_SOURCE_EXTENSION_CALENDAR);+ e_source_backend_set_backend_name(E_SOURCE_BACKEND(ext), backend.toUtf8().constData());+ e_source_selectable_set_color(E_SOURCE_SELECTABLE(ext), color.toUtf8().constData());+ e_source_selectable_set_selected(E_SOURCE_SELECTABLE(ext), TRUE);+ return source;+}+}++void CalendarEngine::addLocalCalendar(const QString &name, const QString &color)+{+ const QString c = color.isEmpty() ? palette.value(m_calendars.size() % palette.size()) : color;+ createSources({newCalendarSource(QStringLiteral("local-stub"), QStringLiteral("local"), name, c)}, [this](bool ok, const QString &error) {+ if (!ok) {+ Q_EMIT notice(tr("The calendar wasn't made. %1").arg(error));+ }+ });+}++void CalendarEngine::addWebCalendar(const QString &name, const QString &address, const QString &color)+{+ QString a = address.trimmed();+ if (a.startsWith(QLatin1String("webcal://"), Qt::CaseInsensitive)) {+ a = QStringLiteral("https://") + a.mid(9);+ }+ const QUrl url(a);+ if (!url.isValid() || (url.scheme() != QLatin1String("https") && url.scheme() != QLatin1String("http"))) {+ Q_EMIT notice(tr("That isn't a calendar address."));+ return;+ }+ const QString c = color.isEmpty() ? palette.value(m_calendars.size() % palette.size()) : color;+ ESource *source = newCalendarSource(QStringLiteral("webcal-stub"), QStringLiteral("webcal"), name.isEmpty() ? url.host() : name, c);+ auto *webdav = E_SOURCE_WEBDAV(e_source_get_extension(source, E_SOURCE_EXTENSION_WEBDAV_BACKEND));+ GUri *uri = g_uri_parse(url.toString(QUrl::FullyEncoded).toUtf8().constData(), GUriFlags(G_URI_FLAGS_HAS_PASSWORD | G_URI_FLAGS_ENCODED_PATH | G_URI_FLAGS_ENCODED_QUERY | G_URI_FLAGS_ENCODED_FRAGMENT | G_URI_FLAGS_SCHEME_NORMALIZE | G_URI_FLAGS_PARSE_RELAXED), nullptr);+ if (uri) {+ e_source_webdav_set_uri(webdav, uri);+ g_uri_unref(uri);+ }+ auto *refresh = E_SOURCE_REFRESH(e_source_get_extension(source, E_SOURCE_EXTENSION_REFRESH));+ e_source_refresh_set_enabled(refresh, TRUE);+ e_source_refresh_set_interval_minutes(refresh, 12 * 60);+ const QString uid = str(e_source_get_uid(source));+ createSources({source}, [this, uid, a](bool ok, const QString &error) {+ if (!ok) {+ Q_EMIT notice(tr("The calendar wasn't added. %1").arg(error));+ } else if (a == holidaysUrl) {+ QSettings().setValue(QStringLiteral("calendar/holidaysUid"), uid);+ Q_EMIT calendarsChanged();+ }+ });+}++void CalendarEngine::renameCalendar(const QString &uid, const QString &name)+{+ if (ESource *source = m_registry ? e_source_registry_ref_source(m_registry, uid.toUtf8().constData()) : nullptr) {+ e_source_set_display_name(source, name.toUtf8().constData());+ e_source_write(source, nullptr, nullptr, nullptr);+ g_object_unref(source);+ }+}++void CalendarEngine::setColor(const QString &uid, const QString &color)+{+ if (ESource *source = m_registry ? e_source_registry_ref_source(m_registry, uid.toUtf8().constData()) : nullptr) {+ e_source_selectable_set_color(E_SOURCE_SELECTABLE(e_source_get_extension(source, E_SOURCE_EXTENSION_CALENDAR)), color.toUtf8().constData());+ e_source_write(source, nullptr, nullptr, nullptr);+ g_object_unref(source);+ }+}++void CalendarEngine::removeCalendar(const QString &uid)+{+ if (ESource *source = m_registry ? e_source_registry_ref_source(m_registry, uid.toUtf8().constData()) : nullptr) {+ if (e_source_get_removable(source)) {+ e_source_remove(source, nullptr, nullptr, nullptr);+ } else {+ // Built in (Birthdays, an account's calendar): hidden instead.+ e_source_set_enabled(source, FALSE);+ e_source_write(source, nullptr, nullptr, nullptr);+ }+ g_object_unref(source);+ }+}++void CalendarEngine::removeAccount(const QString &uid)+{+ removeCalendar(uid);+}++void CalendarEngine::refresh()+{+ for (ECalClient *c : std::as_const(m_clients)) {+ if (c) {+ e_client_refresh(E_CLIENT(c), nullptr, nullptr, nullptr);+ }+ }+}++namespace+{+ESource *refSource(gpointer registry, const gchar *uid)+{+ return e_source_registry_ref_source(static_cast<ESourceRegistry *>(registry), uid);+}++ESource *newCollection(const QString &name, const QString &backend, const QString &identity)+{+ ESource *source = e_source_new(nullptr, nullptr, nullptr);+ e_source_set_display_name(source, name.toUtf8().constData());+ auto *collection = E_SOURCE_COLLECTION(e_source_get_extension(source, E_SOURCE_EXTENSION_COLLECTION));+ e_source_backend_set_backend_name(E_SOURCE_BACKEND(collection), backend.toUtf8().constData());+ e_source_collection_set_identity(collection, identity.toUtf8().constData());+ e_source_collection_set_calendar_enabled(collection, TRUE);+ e_source_collection_set_contacts_enabled(collection, TRUE);+ // Mail reads the account's mail itself.+ e_source_collection_set_mail_enabled(collection, FALSE);+ return source;+}+}++void CalendarEngine::addGoogleAccount(const QString &email, const QString &refreshToken)+{+ if (!m_registry) {+ Q_EMIT accountFailed(tr("The calendar service isn't running."));+ return;+ }+ ESource *source = newCollection(email, QStringLiteral("google"), email);+ auto *auth = E_SOURCE_AUTHENTICATION(e_source_get_extension(source, E_SOURCE_EXTENSION_AUTHENTICATION));+ e_source_authentication_set_user(auth, email.toUtf8().constData());+ e_source_authentication_set_method(auth, "Google");+ const QString uid = str(e_source_get_uid(source));+ ESourceRegistry *registry = m_registry;+ g_object_ref(registry);+ g_object_ref(source);+ auto error = std::make_shared<QString>();+ // The token goes where the service's Google module looks for it.+ run([registry, source, refreshToken, error]() {+ EOAuth2Services *services = e_oauth2_services_new();+ EOAuth2Service *service = e_oauth2_services_find(services, source);+ GError *err = nullptr;+ if (!service) {+ *error = QStringLiteral("no Google sign-in in the calendar service");+ } else if (!e_oauth2_service_refresh_and_store_token_sync(service, source, refreshToken.toUtf8().constData(), &refSource, registry, nullptr, &err)) {+ *error = str(err ? err->message : "");+ }+ g_clear_error(&err);+ g_clear_object(&service);+ g_object_unref(services);+ g_object_unref(registry);+ }, [this, source, uid, error]() {+ if (!error->isEmpty()) {+ g_object_unref(source);+ qCWarning(calendarLog) << "Google token for calendar not stored:" << *error;+ Q_EMIT accountFailed(tr("Google didn't let Calendar in. %1").arg(*error));+ return;+ }+ createSources({source}, [this, uid](bool ok, const QString &e) {+ if (ok) {+ Q_EMIT accountAdded(uid);+ } else {+ Q_EMIT accountFailed(tr("The account wasn't added. %1").arg(e));+ }+ });+ });+}++void CalendarEngine::addCalDavAccount(const QString &name, const QString &address, const QString &user, const QString &password)+{+ const QUrl url = QUrl::fromUserInput(address.trimmed());+ if (!url.isValid() || url.host().isEmpty()) {+ Q_EMIT accountFailed(tr("That isn't a server address."));+ return;+ }+ ESource *source = newCollection(name.isEmpty() ? url.host() : name, QStringLiteral("webdav"), user);+ auto *collection = E_SOURCE_COLLECTION(e_source_get_extension(source, E_SOURCE_EXTENSION_COLLECTION));+ e_source_collection_set_calendar_url(collection, url.toString(QUrl::FullyEncoded).toUtf8().constData());+ e_source_collection_set_contacts_url(collection, url.toString(QUrl::FullyEncoded).toUtf8().constData());+ auto *auth = E_SOURCE_AUTHENTICATION(e_source_get_extension(source, E_SOURCE_EXTENSION_AUTHENTICATION));+ e_source_authentication_set_user(auth, user.toUtf8().constData());+ e_source_authentication_set_host(auth, url.host().toUtf8().constData());+ e_source_authentication_set_port(auth, guint16(url.port(url.scheme() == QLatin1String("http") ? 80 : 443)));+ e_source_authentication_set_method(auth, "plain/password");+ const QString uid = str(e_source_get_uid(source));+ g_object_ref(source);+ createSources({source}, [this, source, uid, password](bool ok, const QString &e) {+ if (!ok) {+ g_object_unref(source);+ Q_EMIT accountFailed(tr("The account wasn't added. %1").arg(e));+ return;+ }+ // Kept by KWallet's Secret Service, where the calendar service+ // looks for it.+ auto error = std::make_shared<QString>();+ run([source, password, error]() {+ GError *err = nullptr;+ if (!e_source_store_password_sync(source, password.toUtf8().constData(), TRUE, nullptr, &err)) {+ *error = str(err ? err->message : "");+ }+ g_clear_error(&err);+ }, [this, source, uid, error]() {+ if (!error->isEmpty()) {+ Q_EMIT accountFailed(tr("The password wasn't saved. %1").arg(*error));+ } else {+ // Look for the calendars now the password is there.+ e_source_invoke_authenticate(source, nullptr, nullptr, nullptr, nullptr);+ Q_EMIT accountAdded(uid);+ }+ g_object_unref(source);+ });+ });+}++bool CalendarEngine::hasHolidays() const+{+ const QString uid = QSettings().value(QStringLiteral("calendar/holidaysUid")).toString();+ for (const QVariant &v : m_calendars) {+ if (v.toMap().value(QStringLiteral("uid")) == uid) {+ return true;+ }+ }+ return false;+}++void CalendarEngine::setHolidays(bool on)+{+ if (on == hasHolidays()) {+ return;+ }+ if (on) {+ addWebCalendar(tr("UK holidays"), holidaysUrl, QStringLiteral("#9aa3b5"));+ } else {+ removeCalendar(QSettings().value(QStringLiteral("calendar/holidaysUid")).toString());+ }+}++bool CalendarEngine::hasBirthdays() const+{+ for (const QVariant &v : m_calendars) {+ if (v.toMap().value(QStringLiteral("uid")) == QLatin1String("birthdays")) {+ return true;+ }+ }+ return false;+}++void CalendarEngine::setBirthdays(bool on)+{+ if (ESource *source = m_registry ? e_source_registry_ref_source(m_registry, "birthdays") : nullptr) {+ e_source_set_enabled(source, on);+ e_source_write(source, nullptr, nullptr, nullptr);+ g_object_unref(source);+ }+}++namespace+{+// The event in an invitation's VCALENDAR (or the VEVENT itself).+ICalComponent *eventOf(ICalComponent *cal)+{+ if (i_cal_component_isa(cal) == I_CAL_VEVENT_COMPONENT) {+ return I_CAL_COMPONENT(g_object_ref(cal));+ }+ return i_cal_component_get_first_component(cal, I_CAL_VEVENT_COMPONENT);+}++// A start or end in an invitation, with its time zone found in the+// invitation's own VTIMEZONE, else the built-in one of that name.+QDateTime inviteTime(ICalComponent *cal, ICalComponent *event, ICalPropertyKind kind, bool *allDay)+{+ ICalProperty *prop = i_cal_component_get_first_property(event, kind);+ if (!prop) {+ return {};+ }+ ICalTime *t = kind == I_CAL_DTSTART_PROPERTY ? i_cal_property_get_dtstart(prop) : i_cal_property_get_dtend(prop);+ QDateTime out;+ if (t) {+ if (i_cal_time_is_date(t)) {+ if (allDay) {+ *allDay = true;+ }+ out = QDateTime(QDate(i_cal_time_get_year(t), i_cal_time_get_month(t), i_cal_time_get_day(t)), QTime(0, 0));+ } else {+ ICalTimezone *zone = nullptr;+ ICalTimezone *owned = nullptr;+ if (i_cal_time_is_utc(t)) {+ zone = i_cal_timezone_get_utc_timezone();+ } else if (ICalParameter *tzid = i_cal_property_get_first_parameter(prop, I_CAL_TZID_PARAMETER)) {+ const gchar *id = i_cal_parameter_get_tzid(tzid);+ owned = i_cal_component_get_timezone(cal, id);+ zone = owned ? owned : i_cal_timezone_get_builtin_timezone(id);+ g_object_unref(tzid);+ }+ if (zone) {+ out = QDateTime::fromSecsSinceEpoch(qint64(i_cal_time_as_timet_with_zone(t, zone)));+ } else {+ // Floating: the same clock time wherever you are.+ out = QDateTime(QDate(i_cal_time_get_year(t), i_cal_time_get_month(t), i_cal_time_get_day(t)),+ QTime(i_cal_time_get_hour(t), i_cal_time_get_minute(t)));+ }+ g_clear_object(&owned);+ }+ g_object_unref(t);+ }+ g_object_unref(prop);+ return out;+}++QString methodName(ICalComponent *cal)+{+ switch (i_cal_component_get_method(cal)) {+ case I_CAL_METHOD_REQUEST:+ return QStringLiteral("request");+ case I_CAL_METHOD_CANCEL:+ return QStringLiteral("cancel");+ case I_CAL_METHOD_REPLY:+ return QStringLiteral("reply");+ case I_CAL_METHOD_COUNTER:+ return QStringLiteral("counter");+ default:+ return QStringLiteral("publish");+ }+}++void setMyStatus(ICalComponent *event, const QString &me, ICalParameterPartstat partstat, bool addIfMissing)+{+ bool found = false;+ for (ICalProperty *p = i_cal_component_get_first_property(event, I_CAL_ATTENDEE_PROPERTY); p;+ p = i_cal_component_get_next_property(event, I_CAL_ATTENDEE_PROPERTY)) {+ if (mailtoless(i_cal_property_get_attendee(p)) == me) {+ i_cal_property_remove_parameter_by_kind(p, I_CAL_PARTSTAT_PARAMETER);+ i_cal_property_take_parameter(p, i_cal_parameter_new_partstat(partstat));+ i_cal_property_remove_parameter_by_kind(p, I_CAL_RSVP_PARAMETER);+ found = true;+ }+ g_object_unref(p);+ }+ if (!found && addIfMissing) {+ ICalProperty *p = i_cal_property_new_attendee(("mailto:" + me).toUtf8().constData());+ i_cal_property_take_parameter(p, i_cal_parameter_new_partstat(partstat));+ i_cal_component_take_property(event, p);+ }+}+}++QVariantMap CalendarEngine::describeInvitation(const QString &ics, const QString &me) const+{+ ICalComponent *cal = ics.isEmpty() ? nullptr : i_cal_component_new_from_string(ics.toUtf8().constData());+ if (!cal) {+ return {};+ }+ ICalComponent *event = eventOf(cal);+ if (!event) {+ g_object_unref(cal);+ return {};+ }+ const QString mine = me.trimmed().toLower();+ bool allDay = false;+ const QDateTime start = inviteTime(cal, event, I_CAL_DTSTART_PROPERTY, &allDay);+ QDateTime end = inviteTime(cal, event, I_CAL_DTEND_PROPERTY, nullptr);+ if (!end.isValid()) {+ end = allDay ? start.addDays(1) : start;+ }+ QString organizer, organizerName;+ if (ICalProperty *o = i_cal_component_get_first_property(event, I_CAL_ORGANIZER_PROPERTY)) {+ organizer = mailtoless(i_cal_property_get_organizer(o));+ if (ICalParameter *cn = i_cal_property_get_first_parameter(o, I_CAL_CN_PARAMETER)) {+ organizerName = str(i_cal_parameter_get_cn(cn));+ g_object_unref(cn);+ }+ g_object_unref(o);+ }+ int people = 0, accepted = 0, waiting = 0;+ QString myStatus;+ for (ICalProperty *p = i_cal_component_get_first_property(event, I_CAL_ATTENDEE_PROPERTY); p;+ p = i_cal_component_get_next_property(event, I_CAL_ATTENDEE_PROPERTY)) {+ ++people;+ ICalParameter *param = i_cal_property_get_first_parameter(p, I_CAL_PARTSTAT_PARAMETER);+ const QString status = partstatName(param ? i_cal_parameter_get_partstat(param) : I_CAL_PARTSTAT_NEEDSACTION);+ g_clear_object(¶m);+ accepted += status == QLatin1String("going");+ waiting += status == QLatin1String("waiting");+ if (mailtoless(i_cal_property_get_attendee(p)) == mine) {+ myStatus = status;+ }+ g_object_unref(p);+ }+ QVariantMap m{+ {QStringLiteral("method"), methodName(cal)},+ {QStringLiteral("uid"), str(i_cal_component_get_uid(event))},+ {QStringLiteral("sequence"), i_cal_component_get_sequence(event)},+ {QStringLiteral("title"), str(i_cal_component_get_summary(event))},+ {QStringLiteral("location"), str(i_cal_component_get_location(event))},+ {QStringLiteral("description"), str(i_cal_component_get_description(event))},+ {QStringLiteral("start"), start},+ // The last day, for an all-day event.+ {QStringLiteral("end"), allDay ? end.addDays(-1) : end},+ {QStringLiteral("allDay"), allDay},+ {QStringLiteral("recurring"), bool(e_cal_util_component_has_recurrences(event))},+ {QStringLiteral("organizer"), organizer},+ {QStringLiteral("organizerName"), organizerName},+ {QStringLiteral("people"), people},+ {QStringLiteral("accepted"), accepted},+ {QStringLiteral("waiting"), waiting},+ {QStringLiteral("myStatus"), myStatus},+ };+ g_object_unref(event);+ g_object_unref(cal);+ return m;+}++void CalendarEngine::answerInvitation(const QString &ics, const QString &status, const QString &me)+{+ if (!m_registry) {+ Q_EMIT notice(tr("The calendar service is still starting. Try again in a moment."));+ return;+ }+ const QString mine = me.trimmed().toLower();+ const ICalParameterPartstat partstat = status == QLatin1String("going") ? I_CAL_PARTSTAT_ACCEPTED+ : status == QLatin1String("maybe") ? I_CAL_PARTSTAT_TENTATIVE : I_CAL_PARTSTAT_DECLINED;+ ESourceRegistry *registry = m_registry;+ g_object_ref(registry);+ const QString defaultUid = defaultCalendar();+ struct Outcome {+ QString uid, reply, organizer, title, error;+ };+ auto outcome = std::make_shared<Outcome>();+ run([=]() {+ ICalComponent *cal = i_cal_component_new_from_string(ics.toUtf8().constData());+ ICalComponent *event = cal ? eventOf(cal) : nullptr;+ if (!event) {+ outcome->error = tr("The invitation can't be read.");+ g_clear_object(&cal);+ g_object_unref(registry);+ return;+ }+ const QString uid = str(i_cal_component_get_uid(event));+ outcome->uid = uid;+ outcome->title = str(i_cal_component_get_summary(event));+ if (ICalProperty *o = i_cal_component_get_first_property(event, I_CAL_ORGANIZER_PROPERTY)) {+ outcome->organizer = mailtoless(i_cal_property_get_organizer(o));+ g_object_unref(o);+ }++ // Where a calendar already has it: a Google or CalDAV account puts+ // invitations in the calendar itself, and its server answers for you.+ bool handledByServer = false;+ bool found = false;+ GList *sources = e_source_registry_list_enabled(registry, E_SOURCE_EXTENSION_CALENDAR);+ for (GList *l = sources; l && !found; l = l->next) {+ auto *source = E_SOURCE(l->data);+ const QString backend = backendOf(source);+ if (backend == QLatin1String("webcal") || backend == QLatin1String("contacts") || backend == QLatin1String("weather")) {+ continue;+ }+ EClient *client = e_cal_client_connect_sync(source, E_CAL_CLIENT_SOURCE_TYPE_EVENTS, 15, nullptr, nullptr);+ if (!client) {+ continue;+ }+ ICalComponent *existing = nullptr;+ if (e_cal_client_get_object_sync(E_CAL_CLIENT(client), uid.toUtf8().constData(), nullptr, &existing, nullptr, nullptr) && existing) {+ found = true;+ const bool server = backend != QLatin1String("local");+ if (partstat == I_CAL_PARTSTAT_DECLINED && !server) {+ e_cal_client_remove_object_sync(E_CAL_CLIENT(client), uid.toUtf8().constData(), nullptr, E_CAL_OBJ_MOD_ALL, E_CAL_OPERATION_FLAG_NONE, nullptr, nullptr);+ } else {+ setMyStatus(existing, mine, partstat, false);+ GError *err = nullptr;+ if (!e_cal_client_modify_object_sync(E_CAL_CLIENT(client), existing, E_CAL_OBJ_MOD_ALL, E_CAL_OPERATION_FLAG_NONE, nullptr, &err)) {+ outcome->error = str(err ? err->message : "");+ }+ g_clear_error(&err);+ }+ handledByServer = server;+ g_object_unref(existing);+ }+ g_object_unref(client);+ }+ g_list_free_full(sources, g_object_unref);++ // Not in any calendar yet: going or maybe adds it to the default one.+ if (!found && partstat != I_CAL_PARTSTAT_DECLINED) {+ if (ESource *source = e_source_registry_ref_source(registry, defaultUid.toUtf8().constData())) {+ if (EClient *client = e_cal_client_connect_sync(source, E_CAL_CLIENT_SOURCE_TYPE_EVENTS, 15, nullptr, nullptr)) {+ // The invitation's own time zones go in with it.+ for (ICalComponent *tz = i_cal_component_get_first_component(cal, I_CAL_VTIMEZONE_COMPONENT); tz;+ tz = i_cal_component_get_next_component(cal, I_CAL_VTIMEZONE_COMPONENT)) {+ // A copy: the zone takes over the component it's given.+ ICalComponent *own = i_cal_component_clone(tz);+ ICalTimezone *zone = i_cal_timezone_new();+ if (i_cal_timezone_set_component(zone, own)) {+ e_cal_client_add_timezone_sync(E_CAL_CLIENT(client), zone, nullptr, nullptr);+ }+ g_object_unref(own);+ g_object_unref(zone);+ g_object_unref(tz);+ }+ ICalComponent *copy = i_cal_component_clone(event);+ setMyStatus(copy, mine, partstat, true);+ GError *err = nullptr;+ if (!e_cal_client_create_object_sync(E_CAL_CLIENT(client), copy, E_CAL_OPERATION_FLAG_NONE, nullptr, nullptr, &err)) {+ outcome->error = str(err ? err->message : "");+ }+ g_clear_error(&err);+ g_object_unref(copy);+ g_object_unref(client);+ }+ g_object_unref(source);+ }+ }++ // The organiser hears by mail unless a server told them.+ if (!handledByServer && !outcome->organizer.isEmpty()) {+ ICalComponent *reply = i_cal_component_new_vcalendar();+ i_cal_component_take_property(reply, i_cal_property_new_version("2.0"));+ i_cal_component_take_property(reply, i_cal_property_new_prodid("-//Wild OS//Calendar//EN"));+ i_cal_component_set_method(reply, I_CAL_METHOD_REPLY);+ for (ICalComponent *tz = i_cal_component_get_first_component(cal, I_CAL_VTIMEZONE_COMPONENT); tz;+ tz = i_cal_component_get_next_component(cal, I_CAL_VTIMEZONE_COMPONENT)) {+ i_cal_component_take_component(reply, i_cal_component_clone(tz));+ g_object_unref(tz);+ }+ ICalComponent *answer = i_cal_component_new_vevent();+ i_cal_component_set_uid(answer, uid.toUtf8().constData());+ i_cal_component_set_sequence(answer, i_cal_component_get_sequence(event));+ ICalTime *now = i_cal_time_new_current_with_zone(i_cal_timezone_get_utc_timezone());+ i_cal_component_set_dtstamp(answer, now);+ g_object_unref(now);+ for (ICalPropertyKind kind : {I_CAL_DTSTART_PROPERTY, I_CAL_DTEND_PROPERTY, I_CAL_SUMMARY_PROPERTY, I_CAL_ORGANIZER_PROPERTY, I_CAL_RECURRENCEID_PROPERTY}) {+ if (ICalProperty *p = i_cal_component_get_first_property(event, kind)) {+ i_cal_component_take_property(answer, i_cal_property_clone(p));+ g_object_unref(p);+ }+ }+ ICalProperty *attendee = i_cal_property_new_attendee(("mailto:" + mine).toUtf8().constData());+ i_cal_property_take_parameter(attendee, i_cal_parameter_new_partstat(partstat));+ i_cal_component_take_property(answer, attendee);+ i_cal_component_take_component(reply, answer);+ outcome->reply = takeStr(i_cal_component_as_ical_string(reply));+ g_object_unref(reply);+ }+ g_object_unref(event);+ g_object_unref(cal);+ g_object_unref(registry);+ }, [this, outcome, status]() {+ if (!outcome->error.isEmpty()) {+ Q_EMIT notice(tr("Your answer wasn't saved. %1").arg(outcome->error));+ return;+ }+ scheduleReload();+ Q_EMIT invitationAnswered(outcome->uid, status, outcome->reply, outcome->organizer, outcome->title);+ });+}++void CalendarEngine::removeInvitation(const QString &ics)+{+ if (!m_registry) {+ return;+ }+ ICalComponent *cal = i_cal_component_new_from_string(ics.toUtf8().constData());+ ICalComponent *event = cal ? eventOf(cal) : nullptr;+ const QString uid = event ? str(i_cal_component_get_uid(event)) : QString();+ g_clear_object(&event);+ g_clear_object(&cal);+ if (uid.isEmpty()) {+ return;+ }+ ESourceRegistry *registry = m_registry;+ g_object_ref(registry);+ run([registry, uid]() {+ GList *sources = e_source_registry_list_enabled(registry, E_SOURCE_EXTENSION_CALENDAR);+ for (GList *l = sources; l; l = l->next) {+ if (EClient *client = e_cal_client_connect_sync(E_SOURCE(l->data), E_CAL_CLIENT_SOURCE_TYPE_EVENTS, 15, nullptr, nullptr)) {+ if (!e_client_is_readonly(client)) {+ e_cal_client_remove_object_sync(E_CAL_CLIENT(client), uid.toUtf8().constData(), nullptr, E_CAL_OBJ_MOD_ALL, E_CAL_OPERATION_FLAG_NONE, nullptr, nullptr);+ }+ g_object_unref(client);+ }+ }+ g_list_free_full(sources, g_object_unref);+ g_object_unref(registry);+ }, [this]() {+ scheduleReload();+ Q_EMIT notice(tr("Taken out of your calendar"));+ });+}diff --git a/packages/wildos-mail/src/calendarengine.h b/packages/wildos-mail/src/calendarengine.hnew file mode 100644index 0000000..346640f--- /dev/null+++ b/packages/wildos-mail/src/calendarengine.h@@ -0,0 +1,223 @@+#pragma once++#include <QDate>+#include <QDateTime>+#include <QHash>+#include <QObject>+#include <QSet>+#include <QTimeZone>+#include <QTimer>+#include <QVariantList>+#include <QtQml/qqmlregistration.h>++#include <functional>++#include <libecal/libecal.h>++#include <QLoggingCategory>++Q_DECLARE_LOGGING_CATEGORY(calendarLog)++class QQmlEngine;+class QJSEngine;++// Everything Calendar knows, on top of evolution-data-server's calendar+// service: the calendars from its source registry (on this PC, Google,+// CalDAV and web calendars) and the events in the days on screen, with+// repeating events already expanded. The service does the syncing; this+// asks it for what to draw and hands it what was changed.+class CalendarEngine : public QObject+{+ Q_OBJECT+ QML_ELEMENT+ QML_SINGLETON++ Q_PROPERTY(bool ready READ ready NOTIFY readyChanged)+ Q_PROPERTY(QString problem READ problem NOTIFY readyChanged)+ // [{uid, name, color, selected, group, groupUid, readOnly, kind}]+ Q_PROPERTY(QVariantList calendars READ calendars NOTIFY calendarsChanged)+ // [{uid, name, kind, email}]: Google and CalDAV accounts.+ Q_PROPERTY(QVariantList accounts READ accounts NOTIFY calendarsChanged)+ Q_PROPERTY(QString defaultCalendar READ defaultCalendar WRITE setDefaultCalendar NOTIFY calendarsChanged)+ Q_PROPERTY(QDate rangeStart READ rangeStart NOTIFY rangeChanged)+ Q_PROPERTY(QDate rangeEnd READ rangeEnd NOTIFY rangeChanged)+ // Goes up whenever the events in the range change; views bind to it.+ Q_PROPERTY(int revision READ revision NOTIFY eventsChanged)+ Q_PROPERTY(QString timeZoneName READ timeZoneName NOTIFY timeZoneChanged)+ Q_PROPERTY(QString timeZoneId READ timeZoneId WRITE setTimeZoneId NOTIFY timeZoneChanged)++public:+ static CalendarEngine *instance();+ static CalendarEngine *create(QQmlEngine *, QJSEngine *);+ ~CalendarEngine() override;++ bool ready() const+ {+ return m_registry != nullptr;+ }+ QString problem() const+ {+ return m_problem;+ }+ QVariantList calendars() const+ {+ return m_calendars;+ }+ QVariantList accounts() const+ {+ return m_accounts;+ }+ QString defaultCalendar() const;+ void setDefaultCalendar(const QString &uid);+ QDate rangeStart() const+ {+ return m_from;+ }+ QDate rangeEnd() const+ {+ return m_to;+ }+ int revision() const+ {+ return m_revision;+ }+ QString timeZoneName() const;+ QString timeZoneId() const;+ void setTimeZoneId(const QString &id);++ // The days on screen: from the first up to, not including, the last.+ Q_INVOKABLE void setRange(const QDate &from, const QDate &to);+ Q_INVOKABLE void setSelected(const QString &calendarUid, bool selected);++ // What a view draws, from the events already fetched for the range.+ // Timed events on one day, laid out side by side where they overlap:+ // [{key, title, location, color, startMinute, endMinute, column, columns, ...}]+ Q_INVOKABLE QVariantList timedOn(const QDate &day) const;+ // Events that fill whole days, or run past midnight for a day or more,+ // across the days from..to: [{key, title, color, firstColumn, lastColumn, row}]+ Q_INVOKABLE QVariantList allDayBetween(const QDate &from, const QDate &to) const;+ // Everything on one day, all-day first, for a month cell.+ Q_INVOKABLE QVariantList eventsOn(const QDate &day) const;+ // Days in the range with something on, for the small month.+ Q_INVOKABLE bool busyOn(const QDate &day) const;++ // One event in full, for the event card and editing it.+ Q_INVOKABLE QVariantMap event(const QString &key) const;+ // Creates or changes an event (see calendarengine.cpp for the fields).+ Q_INVOKABLE void saveEvent(const QVariantMap &data);+ Q_INVOKABLE void removeEvent(const QString &key, bool wholeSeries);+ // Going, Maybe or Not going, for an event someone invited you to.+ Q_INVOKABLE void respond(const QString &key, const QString &status);+ // A dragged event, to its new start; it keeps its length.+ Q_INVOKABLE void moveEvent(const QString &key, const QDateTime &start);++ // Events for one day outside the range, for the editor's day beside the+ // form: answered with dayLoaded.+ Q_INVOKABLE void loadDay(const QDate &day);+ // Events whose title, place or notes contain the text, a year either+ // side of today: answered with searchDone.+ Q_INVOKABLE void search(const QString &text);++ Q_INVOKABLE void addLocalCalendar(const QString &name, const QString &color);+ Q_INVOKABLE void addWebCalendar(const QString &name, const QString &url, const QString &color);+ Q_INVOKABLE void renameCalendar(const QString &uid, const QString &name);+ Q_INVOKABLE void setColor(const QString &uid, const QString &color);+ Q_INVOKABLE void removeCalendar(const QString &uid);+ // A Google account from a refresh token (GoogleSignIn), or a CalDAV+ // server with a password; the service finds the calendars in it.+ Q_INVOKABLE void addGoogleAccount(const QString &email, const QString &refreshToken);+ Q_INVOKABLE void addCalDavAccount(const QString &name, const QString &url, const QString &user, const QString &password);+ Q_INVOKABLE void removeAccount(const QString &uid);+ Q_INVOKABLE void refresh();++ // An invitation in a message (MailMsInvite.dc): what it's for, and+ // the answer. me is the address it came to.+ Q_INVOKABLE QVariantMap describeInvitation(const QString &ics, const QString &me) const;+ // Going, Maybe or Not going: changes your answer on the event where a+ // calendar account has it (its server tells the organiser), or adds it+ // to the default calendar; answered with invitationAnswered, whose+ // reply is the iCalendar to mail the organiser when no server will.+ Q_INVOKABLE void answerInvitation(const QString &ics, const QString &status, const QString &me);+ // A cancelled event, taken out of whichever calendar has it.+ Q_INVOKABLE void removeInvitation(const QString &ics);++ // UK bank holidays and birthdays from contacts (CalMsSettings).+ Q_INVOKABLE bool hasHolidays() const;+ Q_INVOKABLE void setHolidays(bool on);+ Q_INVOKABLE bool hasBirthdays() const;+ Q_INVOKABLE void setBirthdays(bool on);++Q_SIGNALS:+ void readyChanged();+ void calendarsChanged();+ void rangeChanged();+ void eventsChanged();+ void timeZoneChanged();+ void notice(const QString &text);+ void saved(const QString &key);+ void dayLoaded(const QDate &day, const QVariantList &events);+ void searchDone(const QString &text, const QVariantList &results);+ void accountAdded(const QString &uid);+ void accountFailed(const QString &message);+ void invitationAnswered(const QString &uid, const QString &status, const QString &reply, const QString &organizer, const QString &title);++private:+ explicit CalendarEngine(QObject *parent = nullptr);++ struct Instance {+ QString key;+ QString calendarUid;+ QString uid;+ QString rid;+ QString title;+ QString location;+ QDateTime start;+ QDateTime end;+ bool allDay = false;+ bool recurring = false;+ bool invited = false;+ bool busy = true;+ QString myStatus;+ };++ static void onRegistryReady(GObject *, GAsyncResult *result, gpointer self);+ static void onSourceChanged(ESourceRegistry *, ESource *, gpointer self);+ static void onClientConnected(GObject *, GAsyncResult *result, gpointer data);+ static void onViewReady(GObject *, GAsyncResult *result, gpointer data);+ static void onViewObjects(ECalClientView *, gpointer, gpointer self);++ void rebuildCalendars();+ void connectClient(ESource *source);+ void dropClient(const QString &uid);+ void startView(const QString &uid);+ void scheduleReload();+ void reload();+ void flatten();+ void run(std::function<void()> work, std::function<void()> done);+ ECalClient *client(const QString &uid) const;+ ICalTimezone *zone() const;+ QDateTime toDateTime(ICalTime *time) const;+ QVariantMap row(const Instance &i) const;+ QList<Instance> fetch(ECalClient *client, const QString &calendarUid, const QDate &from, const QDate &to) const;+ QString myAddress(const QString &calendarUid) const;+ void createSources(const QList<ESource *> &sources, std::function<void(bool, const QString &)> done);++ ESourceRegistry *m_registry = nullptr;+ GCancellable *m_cancel = nullptr;+ QString m_problem;+ QHash<QString, ECalClient *> m_clients;+ QHash<QString, ECalClientView *> m_views;+ QHash<QString, QString> m_colors;+ QSet<QString> m_readOnly;+ QVariantList m_calendars;+ QVariantList m_accounts;+ QDate m_from;+ QDate m_to;+ QHash<QString, QList<Instance>> m_perCalendar;+ QList<Instance> m_instances;+ QHash<QString, int> m_byKey;+ int m_revision = 0;+ int m_generation = 0;+ QTimer m_reloadTimer;+ QTimeZone m_zone;+};diff --git a/packages/wildos-mail/src/camelsession.cpp b/packages/wildos-mail/src/camelsession.cppnew file mode 100644index 0000000..9e85a62--- /dev/null+++ b/packages/wildos-mail/src/camelsession.cpp@@ -0,0 +1,182 @@+#include "camelsession.h"++#include <QDir>+#include <QStandardPaths>++#include "googlesignin.h"++namespace+{+struct MailSession {+ CamelSession parent;+};+struct MailSessionClass {+ CamelSessionClass parent_class;+};++G_DEFINE_TYPE(MailSession, mail_session, CAMEL_TYPE_SESSION)++gchar *getPassword(CamelSession *, CamelService *service, const gchar *, const gchar *, guint32, GError **error)+{+ const QString password = Session::instance().password(Session::accountOf(service));+ if (password.isEmpty()) {+ g_set_error_literal(error, G_IO_ERROR, G_IO_ERROR_PERMISSION_DENIED, "No password saved for this account");+ return nullptr;+ }+ return g_strdup(password.toUtf8().constData());+}++// One try with the saved password. A wrong one is reported, not retried:+// asking again belongs to the window, which shows "Sign in again".+gboolean authenticateSync(CamelSession *, CamelService *service, const gchar *mechanism, GCancellable *cancellable, GError **error)+{+ const QString account = Session::accountOf(service);+ // Google accounts sign in with XOAUTH2, which asks the session for a+ // token itself; there is no password to hand over.+ if (Session::instance().oauth(account)) {+ return camel_service_authenticate_sync(service, mechanism, cancellable, error) == CAMEL_AUTHENTICATION_ACCEPTED;+ }+ const QString password = Session::instance().password(account);+ if (password.isEmpty()) {+ g_set_error_literal(error, CAMEL_SERVICE_ERROR, CAMEL_SERVICE_ERROR_UNAVAILABLE, "Waiting for the password store");+ return FALSE;+ }+ camel_service_set_password(service, password.toUtf8().constData());+ const CamelAuthenticationResult result = camel_service_authenticate_sync(service, mechanism, cancellable, error);+ if (result == CAMEL_AUTHENTICATION_REJECTED && error && !*error) {+ g_set_error_literal(error, CAMEL_SERVICE_ERROR, CAMEL_SERVICE_ERROR_CANT_AUTHENTICATE, "The password was not accepted");+ }+ return result == CAMEL_AUTHENTICATION_ACCEPTED;+}++// A certificate the system doesn't trust is refused. Mail never offers to+// accept one anyway, since that is exactly what an attacker in the middle of+// the connection would hope for.+CamelCertTrust trustPrompt(CamelSession *, CamelService *, GTlsCertificate *, GTlsCertificateFlags errors)+{+ return errors == 0 ? CAMEL_CERT_TRUST_FULLY : CAMEL_CERT_TRUST_NEVER;+}++gboolean getOAuth2AccessToken(CamelSession *, CamelService *service, gchar **outToken, gint *outExpiresIn, GCancellable *, GError **error)+{+ QString token;+ QString message;+ int expires = 0;+ if (!Session::instance().accessToken(Session::accountOf(service), &token, &expires, &message)) {+ g_set_error_literal(error, CAMEL_SERVICE_ERROR, CAMEL_SERVICE_ERROR_CANT_AUTHENTICATE,+ message.isEmpty() ? "Google sign-in has expired" : message.toUtf8().constData());+ return FALSE;+ }+ if (outToken) {+ *outToken = g_strdup(token.toUtf8().constData());+ }+ if (outExpiresIn) {+ *outExpiresIn = expires;+ }+ return TRUE;+}++CamelFilterDriver *getFilterDriver(CamelSession *session, const gchar *, CamelFolder *, GError **)+{+ return camel_filter_driver_new(session);+}++void mail_session_class_init(MailSessionClass *klass)+{+ auto *session = CAMEL_SESSION_CLASS(klass);+ session->get_password = getPassword;+ session->authenticate_sync = authenticateSync;+ session->trust_prompt = trustPrompt;+ session->get_filter_driver = getFilterDriver;+ session->get_oauth2_access_token_sync = getOAuth2AccessToken;+}++void mail_session_init(MailSession *)+{+}+}++Session &Session::instance()+{+ static Session session;+ return session;+}++Session::Session()+{+ const QString data = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);+ const QString cache = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);+ QDir().mkpath(data);+ QDir().mkpath(cache);+ camel_init(data.toUtf8().constData(), FALSE);+ camel_provider_init();+ m_session = CAMEL_SESSION(g_object_new(mail_session_get_type(),+ "user-data-dir", data.toUtf8().constData(),+ "user-cache-dir", cache.toUtf8().constData(),+ nullptr));+ camel_session_set_online(m_session, TRUE);+}++void Session::setPassword(const QString &accountId, const QString &password)+{+ QMutexLocker lock(&m_lock);+ m_passwords.insert(accountId, password);+}++QString Session::password(const QString &accountId) const+{+ QMutexLocker lock(&m_lock);+ return m_passwords.value(accountId);+}++void Session::setOAuth(const QString &accountId, bool oauth)+{+ QMutexLocker lock(&m_lock);+ if (oauth) {+ m_oauth.insert(accountId);+ } else {+ m_oauth.remove(accountId);+ }+ m_tokens.remove(accountId);+}++bool Session::oauth(const QString &accountId) const+{+ QMutexLocker lock(&m_lock);+ return m_oauth.contains(accountId);+}++bool Session::accessToken(const QString &accountId, QString *token, int *expiresIn, QString *error)+{+ QString refresh;+ {+ QMutexLocker lock(&m_lock);+ const Token cached = m_tokens.value(accountId);+ // Reused until a minute before Google says it runs out.+ if (!cached.value.isEmpty() && cached.expires > QDateTime::currentDateTimeUtc().addSecs(60)) {+ *token = cached.value;+ *expiresIn = int(QDateTime::currentDateTimeUtc().secsTo(cached.expires));+ return true;+ }+ refresh = m_passwords.value(accountId);+ }+ if (refresh.isEmpty()) {+ *error = QStringLiteral("Waiting for the password store");+ return false;+ }+ if (!GoogleSignIn::accessToken(refresh, token, expiresIn, error)) {+ return false;+ }+ QMutexLocker lock(&m_lock);+ m_tokens.insert(accountId, {*token, QDateTime::currentDateTimeUtc().addSecs(*expiresIn)});+ return true;+}++QString Session::accountOf(CamelService *service)+{+ QString uid = QString::fromUtf8(camel_service_get_uid(service));+ if (uid.endsWith(QLatin1String(".smtp"))) {+ uid.chop(5);+ }+ return uid;+}diff --git a/packages/wildos-mail/src/camelsession.h b/packages/wildos-mail/src/camelsession.hnew file mode 100644index 0000000..35cb47c--- /dev/null+++ b/packages/wildos-mail/src/camelsession.h@@ -0,0 +1,50 @@+#pragma once++#include <QHash>+#include <QDateTime>+#include <QMutex>+#include <QSet>+#include <QString>++#include <camel/camel.h>++// The one CamelSession Mail runs on. Camel asks it for passwords and whether+// to trust a server's certificate; everything else (connecting, syncing,+// caching for offline use) Camel does itself. Its services are named by the+// account id, with ".smtp" for the outgoing side.+class Session+{+public:+ static Session &instance();++ CamelSession *camel() const+ {+ return m_session;+ }++ // Called from the GUI thread before a service connects; read from+ // Camel's worker threads.+ void setPassword(const QString &accountId, const QString &password);+ QString password(const QString &accountId) const;+ // Accounts signed in with Google: their stored secret is a refresh+ // token, traded for short-lived access tokens as Camel needs them.+ void setOAuth(const QString &accountId, bool oauth);+ bool oauth(const QString &accountId) const;+ bool accessToken(const QString &accountId, QString *token, int *expiresIn, QString *error);++ // The account a service belongs to: "abc" for both "abc" and "abc.smtp".+ static QString accountOf(CamelService *service);++private:+ Session();++ CamelSession *m_session = nullptr;+ mutable QMutex m_lock;+ QHash<QString, QString> m_passwords;+ QSet<QString> m_oauth;+ struct Token {+ QString value;+ QDateTime expires;+ };+ QHash<QString, Token> m_tokens;+};diff --git a/packages/wildos-mail/src/composer.cpp b/packages/wildos-mail/src/composer.cppnew file mode 100644index 0000000..f3c7b90--- /dev/null+++ b/packages/wildos-mail/src/composer.cpp@@ -0,0 +1,428 @@+#include "composer.h"+#include "formats.h"++#include <QBuffer>+#include <QFile>+#include <QFileInfo>+#include <QImageReader>+#include <QImageWriter>+#include <QMimeDatabase>+#include <QRegularExpression>+#include <QSettings>+#include <QTime>+#include <QUrl>+#include <QUuid>++#include <camel/camel.h>++#include "mailengine.h"++namespace+{+QString str(const gchar *s)+{+ return s ? QString::fromUtf8(s) : QString();+}++CamelMimePart *textPart(const QString &text, const char *subtype)+{+ CamelMimePart *part = camel_mime_part_new();+ const QByteArray bytes = text.toUtf8();+ const QByteArray type = QByteArray("text/") + subtype + "; charset=utf-8";+ camel_mime_part_set_content(part, bytes.constData(), bytes.size(), type.constData());+ camel_mime_part_set_encoding(part, CAMEL_TRANSFER_ENCODING_QUOTEDPRINTABLE);+ return part;+}++CamelInternetAddress *addresses(const QString &text)+{+ CamelInternetAddress *list = camel_internet_address_new();+ if (!text.trimmed().isEmpty()) {+ camel_address_unformat(CAMEL_ADDRESS(list), text.toUtf8().constData());+ }+ return list;+}++bool validAddresses(const QString &text, QString *bad)+{+ static const QRegularExpression email(QStringLiteral(R"(^[^@\s<>]+@[^@\s<>]+\.[^@\s<>]+$)"));+ CamelInternetAddress *list = addresses(text);+ bool ok = true;+ for (int i = 0; i < camel_address_length(CAMEL_ADDRESS(list)); ++i) {+ const gchar *a = nullptr;+ camel_internet_address_get(list, i, nullptr, &a);+ if (!email.match(str(a)).hasMatch()) {+ *bad = str(a);+ ok = false;+ break;+ }+ }+ g_object_unref(list);+ return ok;+}++// Photos lose everything but the picture: where they were taken, the camera+// and when. The picture is drawn the right way up first, since the rotation+// lives in the same data.+QByteArray cleanPhoto(const QByteArray &data, const QByteArray &format, const QByteArray &readFormat = {})+{+ QBuffer in;+ in.setData(data);+ in.open(QIODevice::ReadOnly);+ QImageReader reader(&in, readFormat.isEmpty() ? format : readFormat);+ reader.setAutoTransform(true);+ const QImage image = reader.read();+ if (image.isNull()) {+ return {};+ }+ QByteArray out;+ QBuffer buffer(&out);+ buffer.open(QIODevice::WriteOnly);+ QImageWriter writer(&buffer, format);+ writer.setQuality(92);+ return writer.write(image) ? out : QByteArray();+}++QString quoteHtml(const QString &header, const QString "e)+{+ if (quote.isEmpty()) {+ return {};+ }+ QString body = quote.toHtmlEscaped();+ body.replace(QLatin1Char('\n'), QStringLiteral("<br>"));+ QString head = header.toHtmlEscaped();+ head.replace(QLatin1Char('\n'), QStringLiteral("<br>"));+ return QStringLiteral("<br><div>%1</div><blockquote style=\"margin:0 0 0 4px;padding-left:12px;border-left:2px solid #c3c8d4;color:#555b6b\">%2</blockquote>")+ .arg(head, body);+}++QString quotePlain(const QString &header, const QString "e)+{+ if (quote.isEmpty()) {+ return {};+ }+ QString out = QStringLiteral("\n\n") + header + QLatin1Char('\n');+ for (const QString &line : quote.split(QLatin1Char('\n'))) {+ out += QStringLiteral("> ") + line + QLatin1Char('\n');+ }+ return out;+}+}++Composer::Composer(QObject *parent)+ : QObject(parent)+{+ m_draftTimer.setSingleShot(true);+ m_draftTimer.setInterval(2000);+ connect(&m_draftTimer, &QTimer::timeout, this, &Composer::saveDraft);+}++QVariantList Composer::attachments() const+{+ QVariantList list;+ for (int i = 0; i < m_attachments.size(); ++i) {+ const Attachment &a = m_attachments[i];+ list.append(QVariantMap{{QStringLiteral("name"), a.name},+ {QStringLiteral("size"), QLocale().formattedDataSize(a.data.size(), 0, QLocale::DataSizeTraditionalFormat)},+ {QStringLiteral("type"), a.mimeType},+ {QStringLiteral("photo"), a.photoCleaned},+ {QStringLiteral("uncleaned"), a.photoUncleaned},+ {QStringLiteral("index"), i}});+ }+ return list;+}++void Composer::start(const QVariantMap &data)+{+ m_accountId = data.value(QStringLiteral("accountId")).toString();+ if (m_accountId.isEmpty()) {+ const QVariantList accounts = MailEngine::instance()->accountList();+ if (!accounts.isEmpty()) {+ m_accountId = accounts.first().toMap().value(QStringLiteral("id")).toString();+ }+ }+ m_to = data.value(QStringLiteral("to")).toStringList().join(QStringLiteral(", "));+ m_cc = data.value(QStringLiteral("cc")).toStringList().join(QStringLiteral(", "));+ m_bcc.clear();+ m_subject = data.value(QStringLiteral("subject")).toString();+ m_quoteHeader = data.value(QStringLiteral("quoteHeader")).toString();+ m_quote = data.value(QStringLiteral("quote")).toString();+ m_inReplyTo = data.value(QStringLiteral("inReplyTo")).toString();+ m_references = data.value(QStringLiteral("references")).toString();+ m_calendarReply = data.value(QStringLiteral("calendarReply")).toString();+ m_bodyHtml.clear();+ m_bodyText.clear();+ m_attachments.clear();+ m_draftUid.clear();+ m_savedAt.clear();+ m_started = true;+ if (const Account *a = MailEngine::instance()->accountData(m_accountId); a && !a->signature.isEmpty()) {+ m_bodyText = QStringLiteral("\n\n") + a->signature;+ }+ Q_EMIT changed();+ Q_EMIT attachmentsChanged();+ Q_EMIT savedAtChanged();+}++void Composer::addAttachment(const QUrl &url)+{+ QFile file(url.toLocalFile());+ if (!file.open(QIODevice::ReadOnly)) {+ Q_EMIT problem(tr("That file couldn't be opened."));+ return;+ }+ if (file.size() > 25 * 1024 * 1024) {+ Q_EMIT problem(tr("That file is over 25 MB, more than most email providers accept."));+ return;+ }+ Attachment a;+ a.name = QFileInfo(file).fileName();+ a.mimeType = QMimeDatabase().mimeTypeForFile(file.fileName()).name();+ a.data = file.readAll();+ QByteArray format;+ if (a.mimeType == QLatin1String("image/jpeg")) {+ format = "jpeg";+ } else if (a.mimeType == QLatin1String("image/png")) {+ format = "png";+ } else if (a.mimeType == QLatin1String("image/webp")) {+ format = "webp";+ }+ if (!format.isEmpty()) {+ const QByteArray clean = cleanPhoto(a.data, format);+ if (!clean.isEmpty()) {+ a.data = clean;+ a.photoCleaned = true;+ }+ } else if (a.mimeType.startsWith(QLatin1String("image/")) && a.mimeType != QLatin1String("image/gif") && a.mimeType != QLatin1String("image/svg+xml")) {+ // Other photo formats (HEIC from iPhones, TIFF, RAW) go as JPEG, the+ // one way to be sure their location goes too.+ const QByteArray clean = cleanPhoto(a.data, "jpeg", QByteArray());+ if (!clean.isEmpty()) {+ a.data = clean;+ a.mimeType = QStringLiteral("image/jpeg");+ a.name = QFileInfo(a.name).completeBaseName() + QStringLiteral(".jpg");+ a.photoCleaned = true;+ }+ }+ a.photoUncleaned = a.mimeType.startsWith(QLatin1String("image/")) && !a.photoCleaned && a.mimeType != QLatin1String("image/gif")+ && a.mimeType != QLatin1String("image/svg+xml");+ m_attachments.append(a);+ Q_EMIT attachmentsChanged();+ touch();+}++void Composer::removeAttachment(int index)+{+ if (index >= 0 && index < m_attachments.size()) {+ m_attachments.removeAt(index);+ Q_EMIT attachmentsChanged();+ touch();+ }+}++void Composer::touch()+{+ if (m_started && !m_sending) {+ m_draftTimer.start();+ }+}++QByteArray Composer::build(bool draft, int *cleanedPhotos) const+{+ const Account *account = MailEngine::instance()->accountData(m_accountId);+ CamelMimeMessage *message = camel_mime_message_new();+ CamelInternetAddress *from = camel_internet_address_new();+ if (account) {+ camel_internet_address_add(from, account->fullName.toUtf8().constData(), account->email.toUtf8().constData());+ }+ camel_mime_message_set_from(message, from);+ g_object_unref(from);+ for (const auto &[type, text] : {std::pair{CAMEL_RECIPIENT_TYPE_TO, m_to}, std::pair{CAMEL_RECIPIENT_TYPE_CC, m_cc}, std::pair{CAMEL_RECIPIENT_TYPE_BCC, m_bcc}}) {+ CamelInternetAddress *list = addresses(text);+ camel_mime_message_set_recipients(message, type, list);+ g_object_unref(list);+ }+ camel_mime_message_set_subject(message, m_subject.toUtf8().constData());+ camel_mime_message_set_date(message, CAMEL_MESSAGE_DATE_CURRENT, 0);+ // A random id at the sender's own domain: nothing about this PC or the+ // program in it.+ const QString domain = account ? account->email.section(QLatin1Char('@'), 1) : QStringLiteral("localhost");+ camel_mime_message_set_message_id(message, (QUuid::createUuid().toString(QUuid::Id128) + QLatin1Char('@') + domain).toUtf8().constData());+ if (!m_inReplyTo.isEmpty()) {+ camel_medium_set_header(CAMEL_MEDIUM(message), "In-Reply-To", ('<' + m_inReplyTo.toUtf8() + '>').constData());+ camel_medium_set_header(CAMEL_MEDIUM(message), "References", m_references.toUtf8().constData());+ }+ // No X-Mailer: what program wrote the mail is nobody's business.+ if (draft) {+ camel_medium_set_header(CAMEL_MEDIUM(message), "X-Wildos-Draft-Account", m_accountId.toUtf8().constData());+ }++ // Plain and HTML versions of the same words, so every mail program+ // shows them.+ CamelMultipart *alternative = camel_multipart_new();+ camel_data_wrapper_set_mime_type(CAMEL_DATA_WRAPPER(alternative), "multipart/alternative");+ camel_multipart_set_boundary(alternative, nullptr);+ CamelMimePart *plain = textPart(m_bodyText + quotePlain(m_quoteHeader, m_quote), "plain");+ QString html = m_bodyHtml;+ const QString quote = quoteHtml(m_quoteHeader, m_quote);+ if (html.contains(QLatin1String("</body>"))) {+ html.replace(QLatin1String("</body>"), quote + QStringLiteral("</body>"));+ } else {+ html += quote;+ }+ CamelMimePart *rich = textPart(html, "html");+ camel_multipart_add_part(alternative, plain);+ camel_multipart_add_part(alternative, rich);+ g_object_unref(plain);+ g_object_unref(rich);+ if (!m_calendarReply.isEmpty()) {+ CamelMimePart *calendar = camel_mime_part_new();+ const QByteArray ics = m_calendarReply.toUtf8();+ camel_mime_part_set_content(calendar, ics.constData(), ics.size(), "text/calendar; method=REPLY; charset=utf-8");+ camel_mime_part_set_encoding(calendar, CAMEL_TRANSFER_ENCODING_QUOTEDPRINTABLE);+ camel_multipart_add_part(alternative, calendar);+ g_object_unref(calendar);+ }++ int cleaned = 0;+ if (m_attachments.isEmpty()) {+ camel_medium_set_content(CAMEL_MEDIUM(message), CAMEL_DATA_WRAPPER(alternative));+ } else {+ CamelMultipart *mixed = camel_multipart_new();+ camel_data_wrapper_set_mime_type(CAMEL_DATA_WRAPPER(mixed), "multipart/mixed");+ camel_multipart_set_boundary(mixed, nullptr);+ CamelMimePart *body = camel_mime_part_new();+ camel_medium_set_content(CAMEL_MEDIUM(body), CAMEL_DATA_WRAPPER(alternative));+ camel_multipart_add_part(mixed, body);+ g_object_unref(body);+ for (const Attachment &a : m_attachments) {+ CamelMimePart *part = camel_mime_part_new();+ camel_mime_part_set_content(part, a.data.constData(), a.data.size(), a.mimeType.toUtf8().constData());+ camel_mime_part_set_filename(part, a.name.toUtf8().constData());+ camel_mime_part_set_disposition(part, "attachment");+ camel_mime_part_set_encoding(part, CAMEL_TRANSFER_ENCODING_BASE64);+ camel_multipart_add_part(mixed, part);+ g_object_unref(part);+ cleaned += a.photoCleaned ? 1 : 0;+ }+ camel_medium_set_content(CAMEL_MEDIUM(message), CAMEL_DATA_WRAPPER(mixed));+ g_object_unref(mixed);+ }+ g_object_unref(alternative);+ if (cleanedPhotos) {+ *cleanedPhotos = cleaned;+ }++ GByteArray *bytes = g_byte_array_new();+ CamelStream *stream = camel_stream_mem_new_with_byte_array(bytes);+ camel_data_wrapper_write_to_stream_sync(CAMEL_DATA_WRAPPER(message), stream, nullptr, nullptr);+ QByteArray out(reinterpret_cast<const char *>(bytes->data), int(bytes->len));+ g_object_unref(stream);+ g_object_unref(message);+ return out;+}++bool Composer::send()+{+ if (m_to.trimmed().isEmpty() && m_cc.trimmed().isEmpty() && m_bcc.trimmed().isEmpty()) {+ Q_EMIT problem(tr("Add someone to send this to."));+ return false;+ }+ for (const QString &field : {m_to, m_cc, m_bcc}) {+ QString bad;+ if (!validAddresses(field, &bad)) {+ Q_EMIT problem(tr("\"%1\" doesn't look like an email address.").arg(bad));+ return false;+ }+ }+ if (!MailEngine::instance()->accountData(m_accountId)) {+ Q_EMIT problem(tr("Add an account to send mail from."));+ return false;+ }+ m_draftTimer.stop();+ m_sending = true;+ Q_EMIT sendingChanged();+ int cleaned = 0;+ const QByteArray message = build(false, &cleaned);+ MailEngine *engine = MailEngine::instance();+ engine->countCleanedPhotos(cleaned);+ engine->queueOutbox(m_accountId, message);+ engine->sendOutbox();+ deleteDraft(m_draftUid);+ m_draftUid.clear();+ m_started = false;+ m_sending = false;+ Q_EMIT sendingChanged();+ Q_EMIT sent();+ return true;+}++void Composer::discard()+{+ m_draftTimer.stop();+ deleteDraft(m_draftUid);+ m_draftUid.clear();+ m_started = false;+}++void Composer::saveDraft()+{+ if (!m_started || m_accountId.isEmpty()) {+ return;+ }+ const QByteArray bytes = build(true, nullptr);+ const QString account = m_accountId;+ const QString previous = m_draftUid;+ auto uid = std::make_shared<QString>();+ auto ok = std::make_shared<bool>(false);+ MailEngine *engine = MailEngine::instance();+ engine->run([engine, account, bytes, previous, uid, ok]() {+ CamelFolder *drafts = engine->roleFolderSync(account, QStringLiteral("drafts"), nullptr);+ if (!drafts) {+ return;+ }+ CamelMimeMessage *message = camel_mime_message_new();+ CamelStream *stream = camel_stream_mem_new_with_buffer(bytes.constData(), bytes.size());+ camel_data_wrapper_construct_from_stream_sync(CAMEL_DATA_WRAPPER(message), stream, nullptr, nullptr);+ g_object_unref(stream);+ CamelMessageInfo *info = camel_message_info_new(nullptr);+ camel_message_info_set_flags(info, CAMEL_MESSAGE_DRAFT | CAMEL_MESSAGE_SEEN, CAMEL_MESSAGE_DRAFT | CAMEL_MESSAGE_SEEN);+ gchar *appended = nullptr;+ *ok = camel_folder_append_message_sync(drafts, message, info, &appended, nullptr, nullptr);+ *uid = str(appended);+ g_free(appended);+ g_object_unref(info);+ g_object_unref(message);+ if (*ok && !previous.isEmpty()) {+ camel_folder_set_message_flags(drafts, previous.toUtf8().constData(), CAMEL_MESSAGE_DELETED, CAMEL_MESSAGE_DELETED);+ }+ camel_folder_synchronize_sync(drafts, TRUE, nullptr, nullptr);+ }, [this, uid, ok]() {+ if (!*ok) {+ return;+ }+ // Sent or thrown away while this draft was being filed.+ if (!m_started) {+ deleteDraft(*uid);+ return;+ }+ m_draftUid = *uid;+ m_savedAt = Formats::time(QDateTime::currentDateTime());+ Q_EMIT savedAtChanged();+ });+}++void Composer::deleteDraft(const QString &uid)+{+ if (uid.isEmpty()) {+ return;+ }+ const QString account = m_accountId;+ MailEngine *engine = MailEngine::instance();+ engine->run([engine, account, uid]() {+ if (CamelFolder *drafts = engine->roleFolderSync(account, QStringLiteral("drafts"), nullptr)) {+ camel_folder_set_message_flags(drafts, uid.toUtf8().constData(), CAMEL_MESSAGE_DELETED, CAMEL_MESSAGE_DELETED);+ camel_folder_synchronize_sync(drafts, TRUE, nullptr, nullptr);+ }+ });+}diff --git a/packages/wildos-mail/src/composer.h b/packages/wildos-mail/src/composer.hnew file mode 100644index 0000000..faf781d--- /dev/null+++ b/packages/wildos-mail/src/composer.h@@ -0,0 +1,92 @@+#pragma once++#include <QObject>+#include <QStringList>+#include <QTimer>+#include <QUrl>+#include <QVariantList>+#include <QtQml/qqmlregistration.h>++// A message being written. QML fills in the fields; send() builds the+// message, puts it in the Outbox and lets the engine send it, so a message+// written offline simply waits there. Drafts save themselves a moment after+// each change.+class Composer : public QObject+{+ Q_OBJECT+ QML_ELEMENT++ Q_PROPERTY(QString accountId MEMBER m_accountId NOTIFY changed)+ Q_PROPERTY(QString to MEMBER m_to NOTIFY changed)+ Q_PROPERTY(QString cc MEMBER m_cc NOTIFY changed)+ Q_PROPERTY(QString bcc MEMBER m_bcc NOTIFY changed)+ Q_PROPERTY(QString subject MEMBER m_subject NOTIFY changed)+ Q_PROPERTY(QString bodyHtml MEMBER m_bodyHtml NOTIFY changed)+ Q_PROPERTY(QString bodyText MEMBER m_bodyText NOTIFY changed)+ Q_PROPERTY(QString quoteHeader MEMBER m_quoteHeader NOTIFY changed)+ Q_PROPERTY(QString quote MEMBER m_quote NOTIFY changed)+ Q_PROPERTY(QString inReplyTo MEMBER m_inReplyTo NOTIFY changed)+ Q_PROPERTY(QString references MEMBER m_references NOTIFY changed)+ // An answer to an invitation, as iCalendar (METHOD:REPLY), sent as a+ // version of the message calendar programs read.+ Q_PROPERTY(QString calendarReply MEMBER m_calendarReply NOTIFY changed)+ Q_PROPERTY(QVariantList attachments READ attachments NOTIFY attachmentsChanged)+ Q_PROPERTY(QString savedAt READ savedAt NOTIFY savedAtChanged)+ Q_PROPERTY(bool sending READ sending NOTIFY sendingChanged)++public:+ explicit Composer(QObject *parent = nullptr);++ QVariantList attachments() const;+ QString savedAt() const+ {+ return m_savedAt;+ }+ bool sending() const+ {+ return m_sending;+ }++ // Starts from a reply or forward (MessageView.replyData) or empty.+ Q_INVOKABLE void start(const QVariantMap &data);+ Q_INVOKABLE void addAttachment(const QUrl &file);+ Q_INVOKABLE void removeAttachment(int index);+ // Checks the addresses first; answers through problem() when one won't+ // do.+ Q_INVOKABLE bool send();+ Q_INVOKABLE void discard();+ Q_INVOKABLE void touch();++Q_SIGNALS:+ void changed();+ void attachmentsChanged();+ void savedAtChanged();+ void sendingChanged();+ void sent();+ void problem(const QString &text);++private:+ struct Attachment {+ QString name;+ QString mimeType;+ QByteArray data;+ bool photoCleaned = false;+ // A photo whose details couldn't be taken out, said so on its tile.+ bool photoUncleaned = false;+ };++ // The message as bytes, ready to send or file as a draft.+ QByteArray build(bool draft, int *cleanedPhotos) const;+ void saveDraft();+ void deleteDraft(const QString &uid);++ QString m_accountId;+ QString m_to, m_cc, m_bcc, m_subject, m_bodyHtml, m_bodyText, m_quoteHeader, m_quote, m_inReplyTo, m_references;+ QString m_calendarReply;+ QList<Attachment> m_attachments;+ QString m_draftUid;+ QString m_savedAt;+ bool m_sending = false;+ bool m_started = false;+ QTimer m_draftTimer;+};diff --git a/packages/wildos-mail/src/formats.h b/packages/wildos-mail/src/formats.hnew file mode 100644index 0000000..f150768--- /dev/null+++ b/packages/wildos-mail/src/formats.h@@ -0,0 +1,37 @@+#pragma once++#include <QDateTime>+#include <QLocale>+#include <QRegularExpression>++// Dates and times in the regional format chosen in Settings (LC_TIME, which+// QLocale::system() follows), with day and month names in English as the+// rest of Wild OS is. qml/Formats.js does the same for the QML side.+namespace Formats+{+inline QLocale names()+{+ return QLocale(QLocale::English, QLocale::UnitedKingdom);+}++inline QString time(const QDateTime &when)+{+ return QLocale::system().toString(when.time(), QLocale::ShortFormat);+}++inline QString shortDate(const QDate &day)+{+ return names().toString(day, QLocale::system().dateFormat(QLocale::ShortFormat));+}++// "Mon 9 Nov", "Mon, Nov 9": the long date without its year, with short names.+inline QString shortDayAndMonth(const QDate &day)+{+ QString format = QLocale::system().dateFormat(QLocale::LongFormat);+ format.remove(QRegularExpression(QStringLiteral("[,.\s]*y+[.\u5e74]?")));+ format.replace(QStringLiteral("dddd, d MMMM"), QStringLiteral("dddd d MMMM"));+ format.replace(QStringLiteral("dddd"), QStringLiteral("ddd"));+ format.replace(QStringLiteral("MMMM"), QStringLiteral("MMM"));+ return names().toString(day, format.trimmed());+}+}diff --git a/packages/wildos-mail/src/formatter.cpp b/packages/wildos-mail/src/formatter.cppnew file mode 100644index 0000000..4f0fb86--- /dev/null+++ b/packages/wildos-mail/src/formatter.cpp@@ -0,0 +1,199 @@+#include "formatter.h"++#include <QRegularExpression>+#include <QTextBlock>+#include <QTextCursor>+#include <QTextDocument>+#include <QTextList>++void Formatter::setDocument(QQuickTextDocument *document)+{+ if (document == m_document) {+ return;+ }+ m_document = document;+ Q_EMIT documentChanged();+ connect(this, &Formatter::selectionChanged, this, &Formatter::formatChanged, Qt::UniqueConnection);+}++QTextCursor Formatter::cursor() const+{+ if (!m_document) {+ return {};+ }+ QTextCursor c(m_document->textDocument());+ if (m_start != m_end) {+ c.setPosition(m_start);+ c.setPosition(m_end, QTextCursor::KeepAnchor);+ } else {+ c.setPosition(m_cursor);+ }+ return c;+}++QTextCharFormat Formatter::current() const+{+ QTextCursor c = cursor();+ if (c.isNull()) {+ return {};+ }+ if (!c.hasSelection() && c.position() > 0) {+ // The format of the character before the cursor, which is what+ // the next character typed will take.+ c.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor);+ }+ return c.charFormat();+}++bool Formatter::bold() const+{+ return current().fontWeight() >= QFont::DemiBold;+}++bool Formatter::italic() const+{+ return current().fontItalic();+}++bool Formatter::underline() const+{+ return current().fontUnderline();+}++void Formatter::merge(const QTextCharFormat &format)+{+ QTextCursor c = cursor();+ if (c.isNull()) {+ return;+ }+ if (!c.hasSelection()) {+ c.select(QTextCursor::WordUnderCursor);+ }+ c.mergeCharFormat(format);+ Q_EMIT formatChanged();+}++void Formatter::toggleBold()+{+ QTextCharFormat f;+ f.setFontWeight(bold() ? QFont::Normal : QFont::Bold);+ merge(f);+}++void Formatter::toggleItalic()+{+ QTextCharFormat f;+ f.setFontItalic(!italic());+ merge(f);+}++void Formatter::toggleUnderline()+{+ QTextCharFormat f;+ f.setFontUnderline(!underline());+ merge(f);+}++void Formatter::setColour(const QColor &colour)+{+ QTextCharFormat f;+ f.setForeground(colour);+ merge(f);+}++void Formatter::setPointSize(int size)+{+ QTextCharFormat f;+ f.setFontPointSize(size);+ merge(f);+}++void Formatter::list(QTextListFormat::Style style)+{+ QTextCursor c = cursor();+ if (c.isNull()) {+ return;+ }+ if (QTextList *existing = c.currentList(); existing && existing->format().style() == style) {+ // Pressing the same list button again takes the list away.+ QTextBlockFormat block = c.blockFormat();+ existing->remove(c.block());+ block.setIndent(0);+ c.setBlockFormat(block);+ return;+ }+ QTextListFormat format;+ format.setStyle(style);+ c.createList(format);+}++void Formatter::bullets()+{+ list(QTextListFormat::ListDisc);+}++void Formatter::numbering()+{+ list(QTextListFormat::ListDecimal);+}++void Formatter::indent(int step)+{+ QTextCursor c = cursor();+ if (c.isNull()) {+ return;+ }+ QTextBlockFormat block = c.blockFormat();+ block.setIndent(qMax(0, block.indent() + step));+ c.setBlockFormat(block);+}++void Formatter::insertLink(const QString &url, const QString &text)+{+ QTextCursor c = cursor();+ if (c.isNull() || url.isEmpty()) {+ return;+ }+ QTextCharFormat f;+ f.setAnchor(true);+ f.setAnchorHref(url);+ f.setFontUnderline(true);+ f.setForeground(QColor(0x1a, 0x5f, 0xd0));+ const QString shown = text.isEmpty() ? (c.hasSelection() ? c.selectedText() : url) : text;+ c.insertText(shown, f);+ c.insertText(QStringLiteral(" "), QTextCharFormat());+}++void Formatter::insertText(const QString &text)+{+ QTextCursor c = cursor();+ if (!c.isNull()) {+ c.insertText(text);+ }+}++QString Formatter::html() const+{+ if (!m_document) {+ return {};+ }+ QString body = m_document->textDocument()->toHtml();+ // Qt writes its own head and a body style naming the app's font; mail+ // gets a plain document in Inter with a system fallback.+ const int start = body.indexOf(QLatin1String("<body"));+ const int open = body.indexOf(QLatin1Char('>'), start);+ const int close = body.lastIndexOf(QLatin1String("</body>"));+ if (start >= 0 && open > start && close > open) {+ body = body.mid(open + 1, close - open - 1);+ }+ // Qt's own style properties mean nothing to other mail programs.+ static const QRegularExpression qtStyle(QStringLiteral(R"(\s*-qt-[a-z-]+:[^;"]*;?)"));+ body.remove(qtStyle);+ return QStringLiteral("<html><head><meta charset=\"utf-8\"></head><body style=\"font-family: Inter, 'Segoe UI', Arial, sans-serif; font-size: 11pt;\">")+ + body + QStringLiteral("</body></html>");+}++QString Formatter::plainText() const+{+ return m_document ? m_document->textDocument()->toPlainText() : QString();+}diff --git a/packages/wildos-mail/src/formatter.h b/packages/wildos-mail/src/formatter.hnew file mode 100644index 0000000..d028468--- /dev/null+++ b/packages/wildos-mail/src/formatter.h@@ -0,0 +1,68 @@+#pragma once++#include <QObject>+#include <QPointer>+#include <QQuickTextDocument>+#include <QTextCharFormat>+#include <QTextFormat>+#include <QtQml/qqmlregistration.h>++// Bold, italic, lists and links for the message being written: QML's+// TextArea edits rich text but has no buttons' worth of API, so this works+// on its document through a text cursor.+class Formatter : public QObject+{+ Q_OBJECT+ QML_ELEMENT++ Q_PROPERTY(QQuickTextDocument *document READ document WRITE setDocument NOTIFY documentChanged)+ Q_PROPERTY(int selectionStart MEMBER m_start NOTIFY selectionChanged)+ Q_PROPERTY(int selectionEnd MEMBER m_end NOTIFY selectionChanged)+ Q_PROPERTY(int cursorPosition MEMBER m_cursor NOTIFY selectionChanged)+ Q_PROPERTY(bool bold READ bold NOTIFY formatChanged)+ Q_PROPERTY(bool italic READ italic NOTIFY formatChanged)+ Q_PROPERTY(bool underline READ underline NOTIFY formatChanged)++public:+ using QObject::QObject;++ QQuickTextDocument *document() const+ {+ return m_document;+ }+ void setDocument(QQuickTextDocument *document);+ bool bold() const;+ bool italic() const;+ bool underline() const;++ Q_INVOKABLE void toggleBold();+ Q_INVOKABLE void toggleItalic();+ Q_INVOKABLE void toggleUnderline();+ Q_INVOKABLE void setColour(const QColor &colour);+ Q_INVOKABLE void setPointSize(int size);+ Q_INVOKABLE void bullets();+ Q_INVOKABLE void numbering();+ Q_INVOKABLE void indent(int step);+ Q_INVOKABLE void insertLink(const QString &url, const QString &text);+ Q_INVOKABLE void insertText(const QString &text);+ // The words as HTML for sending, without Qt's document boilerplate+ // and with Inter as the font.+ Q_INVOKABLE QString html() const;+ Q_INVOKABLE QString plainText() const;++Q_SIGNALS:+ void documentChanged();+ void selectionChanged();+ void formatChanged();++private:+ QTextCursor cursor() const;+ void merge(const QTextCharFormat &format);+ QTextCharFormat current() const;+ void list(QTextListFormat::Style style);++ QPointer<QQuickTextDocument> m_document;+ int m_start = 0;+ int m_end = 0;+ int m_cursor = 0;+};diff --git a/packages/wildos-mail/src/googlesignin.cpp b/packages/wildos-mail/src/googlesignin.cppnew file mode 100644index 0000000..866c4e4--- /dev/null+++ b/packages/wildos-mail/src/googlesignin.cpp@@ -0,0 +1,253 @@+#include "googlesignin.h"+#include "mailengine.h"++#include <QCryptographicHash>+#include <QDesktopServices>+#include <QEventLoop>+#include <QJSEngine>+#include <QJsonDocument>+#include <QJsonObject>+#include <QNetworkAccessManager>+#include <QNetworkReply>+#include <QRandomGenerator>+#include <QTimer>+#include <QUrl>+#include <QUrlQuery>++#include <libedataserver/libedataserver.h>++namespace+{+// Adding Gmail to Mail asks for mail, calendars, contacts and tasks in one+// go, so the account's calendar comes with it; Calendar's own sign-in (for+// an account Mail had before, whose token covers mail only) asks for the+// rest. Calendars, contacts and tasks are what evolution-data-server's+// Google module reads.+const QString mailScope = QStringLiteral("https://mail.google.com/");+const QString calendarScope = QStringLiteral("https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/carddav https://www.googleapis.com/auth/tasks");++struct GoogleApp {+ QString clientId;+ QString clientSecret;+ QString authUri;+ QString tokenUri;+ QString redirectUri;+};++// evolution-data-server's Google app, read from the library itself, so+// Mail always uses the registration the installed engine was built with.+const GoogleApp &googleApp()+{+ static const GoogleApp app = []() {+ GoogleApp a;+ GError *error = nullptr;+ ESource *source = e_source_new(nullptr, nullptr, &error);+ g_clear_error(&error);+ EOAuth2Services *services = e_oauth2_services_new();+ GSList *list = e_oauth2_services_list(services);+ for (GSList *l = list; l && source; l = l->next) {+ auto *service = E_OAUTH2_SERVICE(l->data);+ if (g_strcmp0(e_oauth2_service_get_name(service), "Google") != 0) {+ continue;+ }+ a.clientId = QString::fromUtf8(e_oauth2_service_get_client_id(service, source));+ a.clientSecret = QString::fromUtf8(e_oauth2_service_get_client_secret(service, source));+ a.authUri = QString::fromUtf8(e_oauth2_service_get_authentication_uri(service, source));+ a.tokenUri = QString::fromUtf8(e_oauth2_service_get_refresh_uri(service, source));+ a.redirectUri = QString::fromUtf8(e_oauth2_service_get_redirect_uri(service, source));+ }+ g_slist_free_full(list, g_object_unref);+ g_object_unref(services);+ g_clear_object(&source);+ return a;+ }();+ return app;+}++QByteArray randomUrlSafe(int bytes)+{+ QByteArray raw(bytes, Qt::Uninitialized);+ QRandomGenerator::system()->generate(reinterpret_cast<quint32 *>(raw.data()), reinterpret_cast<quint32 *>(raw.data() + (bytes / 4) * 4));+ return raw.toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals);+}++// A token request, waited for here: Camel asks for tokens from its own+// threads, so each call has its own network access and event loop.+QByteArray post(const QString &uri, const QByteArray &body, QString *error)+{+ QNetworkAccessManager network;+ network.setCookieJar(nullptr);+ QNetworkRequest request{QUrl(uri)};+ request.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/x-www-form-urlencoded"));+ request.setTransferTimeout(30000);+ QNetworkReply *reply = network.post(request, body);+ QEventLoop loop;+ QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);+ loop.exec();+ const QByteArray data = reply->readAll();+ if (reply->error() != QNetworkReply::NoError && error) {+ const QJsonObject json = QJsonDocument::fromJson(data).object();+ const QString detail = json.value(QStringLiteral("error_description")).toString();+ *error = detail.isEmpty() ? reply->errorString() : detail;+ }+ const bool ok = reply->error() == QNetworkReply::NoError;+ delete reply;+ return ok ? data : QByteArray();+}+}++GoogleSignIn *GoogleSignIn::instance()+{+ static GoogleSignIn *signIn = new GoogleSignIn();+ return signIn;+}++GoogleSignIn *GoogleSignIn::create(QQmlEngine *, QJSEngine *)+{+ GoogleSignIn *signIn = instance();+ QJSEngine::setObjectOwnership(signIn, QJSEngine::CppOwnership);+ return signIn;+}++GoogleSignIn::GoogleSignIn(QObject *parent)+ : QObject(parent)+ , m_network(nullptr)+{+}++bool GoogleSignIn::isRedirect(const QString &url)+{+ const QString redirect = googleApp().redirectUri;+ return !redirect.isEmpty() && url.startsWith(redirect);+}++void GoogleSignIn::startCalendar(const QString &email)+{+ m_scope = calendarScope;+ begin(email);+}++void GoogleSignIn::start(const QString &email)+{+ m_scope = mailScope + QLatin1Char(' ') + calendarScope;+ begin(email);+}++void GoogleSignIn::begin(const QString &email)+{+ const GoogleApp &app = googleApp();+ if (app.clientId.isEmpty()) {+ Q_EMIT failed(tr("Google sign-in isn't available on this PC."));+ return;+ }+ m_email = email.trimmed();+ m_state = QString::fromLatin1(randomUrlSafe(24));+ // PKCE: only the copy of Mail that started the sign-in can finish it.+ m_verifier = randomUrlSafe(48);+ const QByteArray challenge = QCryptographicHash::hash(m_verifier, QCryptographicHash::Sha256).toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals);++ QUrl url(app.authUri);+ QUrlQuery query;+ query.addQueryItem(QStringLiteral("client_id"), app.clientId);+ query.addQueryItem(QStringLiteral("redirect_uri"), app.redirectUri);+ query.addQueryItem(QStringLiteral("response_type"), QStringLiteral("code"));+ query.addQueryItem(QStringLiteral("scope"), m_scope);+ query.addQueryItem(QStringLiteral("access_type"), QStringLiteral("offline"));+ query.addQueryItem(QStringLiteral("prompt"), QStringLiteral("consent"));+ query.addQueryItem(QStringLiteral("state"), m_state);+ query.addQueryItem(QStringLiteral("code_challenge"), QString::fromLatin1(challenge));+ query.addQueryItem(QStringLiteral("code_challenge_method"), QStringLiteral("S256"));+ if (!m_email.isEmpty()) {+ query.addQueryItem(QStringLiteral("login_hint"), m_email);+ }+ url.setQuery(query);+ m_url = url.toString(QUrl::FullyEncoded);+ qCInfo(mailLog) << "opening Google sign-in in the browser";+ Q_EMIT waitingChanged();+ QDesktopServices::openUrl(QUrl(m_url));+}++void GoogleSignIn::reopen()+{+ if (!m_url.isEmpty()) {+ QDesktopServices::openUrl(QUrl(m_url));+ }+}++void GoogleSignIn::cancel()+{+ m_state.clear();+ m_verifier.clear();+ m_url.clear();+ Q_EMIT waitingChanged();+}++bool GoogleSignIn::handleRedirect(const QString &address)+{+ if (!isRedirect(address)) {+ return false;+ }+ qCInfo(mailLog) << "Google sent the browser back to Mail";+ const QUrlQuery query(QUrl(address).query());+ const QString state = query.queryItemValue(QStringLiteral("state"));+ const QString code = query.queryItemValue(QStringLiteral("code"), QUrl::FullyDecoded);+ const QString error = query.queryItemValue(QStringLiteral("error"));+ // Only the sign-in this copy of Mail started.+ if (m_state.isEmpty() || state != m_state) {+ qCWarning(mailLog) << "ignored a Google answer for a sign-in this Mail didn't start";+ return true;+ }+ const QByteArray verifier = m_verifier;+ const QString email = m_email;+ cancel();+ if (!error.isEmpty() || code.isEmpty()) {+ Q_EMIT failed(error == QLatin1String("access_denied") ? tr("Google sign-in was cancelled.") : tr("Google didn't sign you in: %1").arg(error));+ return true;+ }++ const GoogleApp &app = googleApp();+ QUrlQuery body;+ body.addQueryItem(QStringLiteral("code"), code);+ body.addQueryItem(QStringLiteral("client_id"), app.clientId);+ body.addQueryItem(QStringLiteral("client_secret"), app.clientSecret);+ body.addQueryItem(QStringLiteral("redirect_uri"), app.redirectUri);+ body.addQueryItem(QStringLiteral("grant_type"), QStringLiteral("authorization_code"));+ body.addQueryItem(QStringLiteral("code_verifier"), QString::fromLatin1(verifier));+ if (!m_network) {+ m_network = new QNetworkAccessManager(this);+ m_network->setCookieJar(nullptr);+ }+ QNetworkRequest request{QUrl(app.tokenUri)};+ request.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/x-www-form-urlencoded"));+ request.setTransferTimeout(30000);+ QNetworkReply *reply = m_network->post(request, body.query(QUrl::FullyEncoded).toUtf8());+ connect(reply, &QNetworkReply::finished, this, [this, reply, email]() {+ reply->deleteLater();+ const QJsonObject json = QJsonDocument::fromJson(reply->readAll()).object();+ const QString refresh = json.value(QStringLiteral("refresh_token")).toString();+ if (reply->error() != QNetworkReply::NoError || refresh.isEmpty()) {+ const QString detail = json.value(QStringLiteral("error_description")).toString();+ qCWarning(mailLog) << "Google token exchange failed:" << (detail.isEmpty() ? reply->errorString() : detail);+ Q_EMIT failed(tr("Google didn't finish signing you in. %1").arg(detail.isEmpty() ? reply->errorString() : detail));+ return;+ }+ qCInfo(mailLog) << "Google sign-in finished";+ Q_EMIT signedIn(email, refresh);+ });+ return true;+}++bool GoogleSignIn::accessToken(const QString &refreshToken, QString *token, int *expiresIn, QString *error)+{+ const GoogleApp &app = googleApp();+ QUrlQuery body;+ body.addQueryItem(QStringLiteral("refresh_token"), refreshToken);+ body.addQueryItem(QStringLiteral("client_id"), app.clientId);+ body.addQueryItem(QStringLiteral("client_secret"), app.clientSecret);+ body.addQueryItem(QStringLiteral("grant_type"), QStringLiteral("refresh_token"));+ const QByteArray data = post(app.tokenUri, body.query(QUrl::FullyEncoded).toUtf8(), error);+ const QJsonObject json = QJsonDocument::fromJson(data).object();+ *token = json.value(QStringLiteral("access_token")).toString();+ *expiresIn = json.value(QStringLiteral("expires_in")).toInt(3600);+ return !token->isEmpty();+}diff --git a/packages/wildos-mail/src/googlesignin.h b/packages/wildos-mail/src/googlesignin.hnew file mode 100644index 0000000..08e67d3--- /dev/null+++ b/packages/wildos-mail/src/googlesignin.h@@ -0,0 +1,73 @@+#pragma once++#include <QByteArray>+#include <QDateTime>+#include <QObject>+#include <QString>+#include <QQmlEngine>+#include <QtQml/qqmlregistration.h>++class QNetworkAccessManager;++// "Sign in with Google" for Gmail, through the Google app that+// evolution-data-server is registered as (Mail is built on its engine, so+// Google's page names Evolution). Google's own sign-in page opens in the+// browser; when the person has signed in, Google sends the browser to a+// com.googleusercontent.apps address that Wild OS hands to Mail+// (org.wildos.mail.desktop), and Mail trades the code in it for a token+// that signs in to IMAP and SMTP. Mail asks for mail and calendars.+class GoogleSignIn : public QObject+{+ Q_OBJECT+ QML_ELEMENT+ QML_SINGLETON++ Q_PROPERTY(bool waiting READ waiting NOTIFY waitingChanged)++public:+ static GoogleSignIn *instance();+ static GoogleSignIn *create(QQmlEngine *, QJSEngine *);++ bool waiting() const+ {+ return !m_state.isEmpty();+ }++ // Opens Google's page for this address in the browser, for mail and+ // calendars.+ Q_INVOKABLE void start(const QString &email);+ // The same for Calendar, asking for calendars, contacts and tasks+ // instead of mail; the token goes to evolution-data-server.+ Q_INVOKABLE void startCalendar(const QString &email);+ // Opens the same page again, for a closed browser tab.+ Q_INVOKABLE void reopen();+ Q_INVOKABLE void cancel();++ // The address Google sent the browser to, from main.cpp.+ bool handleRedirect(const QString &url);++ // A fresh access token for an account signed in with Google, from its+ // refresh token. Blocks: Camel calls it from its own threads.+ static bool accessToken(const QString &refreshToken, QString *token, int *expiresIn, QString *error);++ static bool isRedirect(const QString &url);++Q_SIGNALS:+ void waitingChanged();+ // The refresh token is what Mail keeps (in KWallet, or its private+ // file) in place of a password.+ void signedIn(const QString &email, const QString &refreshToken);+ void failed(const QString &message);++private:+ explicit GoogleSignIn(QObject *parent = nullptr);+ void begin(const QString &email);+ QByteArray tokenRequest(const QByteArray &body, QString *error) const;++ QString m_email;+ QString m_state;+ QByteArray m_verifier;+ QString m_url;+ QString m_scope;+ QNetworkAccessManager *m_network;+};diff --git a/packages/wildos-mail/src/htmlview.cpp b/packages/wildos-mail/src/htmlview.cppnew file mode 100644index 0000000..f6f4290--- /dev/null+++ b/packages/wildos-mail/src/htmlview.cpp@@ -0,0 +1,747 @@+#include "htmlview.h"++#include <QCursor>+#include <QFile>+#include <QFontDatabase>+#include <QFontMetrics>+#include <QGuiApplication>+#include <QNetworkAccessManager>+#include <QNetworkReply>+#include <QPainter>+#include <QPainterPath>+#include <QRegularExpression>+#include <QUrl>++#include "messageview.h"++namespace+{+QColor colourOf(const litehtml::web_color &c)+{+ return QColor(c.red, c.green, c.blue, c.alpha);+}++QString utf8(const litehtml::tchar_t *s)+{+ return s ? QString::fromUtf8(s) : QString();+}++const QByteArray &masterCss()+{+ static const QByteArray css = []() {+ QFile file(QStringLiteral(":/qt/qml/WildOS/Mail/data/litehtml-master.css"));+ return file.open(QIODevice::ReadOnly) ? file.readAll() : QByteArray();+ }();+ return css;+}++QPainterPath roundedPath(const QRectF &r, const litehtml::border_radiuses &rad)+{+ QPainterPath path;+ const qreal tl = rad.top_left_x;+ const qreal tr = rad.top_right_x;+ const qreal br = rad.bottom_right_x;+ const qreal bl = rad.bottom_left_x;+ path.moveTo(r.left() + tl, r.top());+ path.lineTo(r.right() - tr, r.top());+ if (tr > 0) {+ path.arcTo(QRectF(r.right() - 2 * tr, r.top(), 2 * tr, 2 * tr), 90, -90);+ }+ path.lineTo(r.right(), r.bottom() - br);+ if (br > 0) {+ path.arcTo(QRectF(r.right() - 2 * br, r.bottom() - 2 * br, 2 * br, 2 * br), 0, -90);+ }+ path.lineTo(r.left() + bl, r.bottom());+ if (bl > 0) {+ path.arcTo(QRectF(r.left(), r.bottom() - 2 * bl, 2 * bl, 2 * bl), 270, -90);+ }+ path.lineTo(r.left(), r.top() + tl);+ if (tl > 0) {+ path.arcTo(QRectF(r.left(), r.top(), 2 * tl, 2 * tl), 180, -90);+ }+ path.closeSubpath();+ return path;+}++bool hasRadius(const litehtml::border_radiuses &r)+{+ return r.top_left_x || r.top_right_x || r.bottom_left_x || r.bottom_right_x;+}+}++HtmlView::HtmlView(QQuickItem *parent)+ : QQuickPaintedItem(parent)+{+ setAcceptHoverEvents(true);+ setAcceptedMouseButtons(Qt::LeftButton | Qt::RightButton);+ setAntialiasing(true);+ setOpaquePainting(false);+}++HtmlView::~HtmlView()+{+ m_document.reset();+}++void HtmlView::setHtml(const QString &html)+{+ if (html == m_html) {+ return;+ }+ m_html = html;+ m_images.clear();+ m_fetching.clear();+ Q_EMIT htmlChanged();+ rebuild();+}++void HtmlView::setMessage(MessageView *message)+{+ if (message != m_message) {+ m_message = message;+ Q_EMIT messageChanged();+ }+}++void HtmlView::setAllowRemote(bool allow)+{+ if (allow == m_allowRemote) {+ return;+ }+ m_allowRemote = allow;+ Q_EMIT allowRemoteChanged();+ rebuild();+}++void HtmlView::setPaper(bool paper)+{+ if (paper != m_paper) {+ m_paper = paper;+ Q_EMIT paperChanged();+ rebuild();+ }+}++void HtmlView::setTextColor(const QColor &c)+{+ if (c != m_textColor) {+ m_textColor = c;+ Q_EMIT coloursChanged();+ rebuild();+ }+}++void HtmlView::setLinkColor(const QColor &c)+{+ if (c != m_linkColor) {+ m_linkColor = c;+ Q_EMIT coloursChanged();+ rebuild();+ }+}++void HtmlView::setQuoteColor(const QColor &c)+{+ if (c != m_quoteColor) {+ m_quoteColor = c;+ Q_EMIT coloursChanged();+ rebuild();+ }+}++void HtmlView::setFontSize(qreal size)+{+ if (!qFuzzyCompare(size, m_fontSize)) {+ m_fontSize = size;+ Q_EMIT coloursChanged();+ rebuild();+ }+}++void HtmlView::setContentY(qreal y)+{+ if (!qFuzzyCompare(y + 1, m_contentY + 1)) {+ m_contentY = y;+ Q_EMIT contentYChanged();+ update();+ }+}++void HtmlView::rebuild()+{+ m_document.reset();+ m_fonts.clear();+ if (m_html.isEmpty()) {+ m_contentHeight = 0;+ Q_EMIT contentHeightChanged();+ update();+ return;+ }+ if (!m_context) {+ m_context = std::make_unique<litehtml::context>();+ m_context->load_master_stylesheet(masterCss().constData());+ }+ // How Mail dresses a message: plain mail in the window's own type and+ // colours; designed mail on white with dark text, as its sender saw it.+ const QString ink = m_paper ? QStringLiteral("#1b1f2a") : m_textColor.name(QColor::HexRgb);+ const QString link = m_paper ? QStringLiteral("#1a5fd0") : m_linkColor.name(QColor::HexRgb);+ const QString quote = m_paper ? QStringLiteral("#5b6275") : m_quoteColor.name(QColor::HexRgb);+ const QString css = QStringLiteral(+ "html, body { height: auto; }"+ "body { color: %1; font-family: Inter, sans-serif; font-size: %4px; line-height: 1.6; margin: 0; }"+ "a { color: %2; }"+ "blockquote { margin: 0 0 0 4px; padding-left: 12px; border-left: 2px solid %3; color: %3; }"+ "img { max-width: 100%; }"+ "p { margin: 0 0 15px 0; }")+ .arg(ink, link, quote)+ .arg(m_fontSize);+ const QByteArray userCss = css.toUtf8();+ litehtml::css user;+ user.parse_stylesheet(userCss.constData(), nullptr, nullptr, litehtml::media_query_list::ptr());+ user.sort_selectors();+ m_pageColour = QColor();+ static const QRegularExpression bodyTag(QStringLiteral(R"(<body\b[^>]*>)"), QRegularExpression::CaseInsensitiveOption);+ static const QRegularExpression bgAttr(QStringLiteral(R"(\bbgcolor\s*=\s*["']?(#?[0-9a-z]+))"), QRegularExpression::CaseInsensitiveOption);+ static const QRegularExpression bgStyle(QStringLiteral(R"(background(?:-color)?\s*:\s*(#[0-9a-f]{3,8}|rgba?\([^)]*\)|[a-z]+))"), QRegularExpression::CaseInsensitiveOption);+ if (const auto body = bodyTag.match(m_html); body.hasMatch()) {+ auto m = bgStyle.match(body.captured(0));+ if (!m.hasMatch()) {+ m = bgAttr.match(body.captured(0));+ }+ if (m.hasMatch()) {+ const QColor c = QColor::fromString(m.captured(1));+ if (c.isValid()) {+ m_pageColour = c;+ }+ }+ }+ const QByteArray bytes = m_html.toUtf8();+ m_document = litehtml::document::createFromUTF8(bytes.constData(), this, m_context.get(), &user);+ m_renderedWidth = -1;+ relayout();+}++void HtmlView::relayout()+{+ if (!m_document) {+ return;+ }+ const int w = qMax(100, int(width()));+ if (w != m_renderedWidth) {+ m_renderedWidth = w;+ m_document->render(w);+ }+ const int h = m_document->height();+ const int cw = m_document->width();+ if (h != m_contentHeight || cw != m_contentWidth) {+ m_contentHeight = h;+ m_contentWidth = cw;+ Q_EMIT contentHeightChanged();+ }+ update();+}++void HtmlView::geometryChange(const QRectF &newGeometry, const QRectF &oldGeometry)+{+ QQuickPaintedItem::geometryChange(newGeometry, oldGeometry);+ if (newGeometry.width() != oldGeometry.width()) {+ relayout();+ }+}++void HtmlView::paint(QPainter *painter)+{+ if (!m_document) {+ return;+ }+ m_painter = painter;+ painter->setRenderHint(QPainter::Antialiasing);+ painter->setRenderHint(QPainter::TextAntialiasing);+ painter->setRenderHint(QPainter::SmoothPixmapTransform);+ painter->translate(0, -m_contentY);+ litehtml::position clip(0, int(m_contentY), int(width()), int(height()) + 1);+ m_document->draw(reinterpret_cast<litehtml::uint_ptr>(painter), 0, 0, &clip);+ m_painter = nullptr;+ m_clips.clear();+}++void HtmlView::hoverMoveEvent(QHoverEvent *event)+{+ if (!m_document) {+ return;+ }+ litehtml::position::vector redraw;+ const QPointF p = event->position();+ m_document->on_mouse_over(int(p.x()), int(p.y() + m_contentY), int(p.x()), int(p.y()), redraw);+ if (!redraw.empty()) {+ update();+ }+}++void HtmlView::hoverLeaveEvent(QHoverEvent *)+{+ if (!m_document) {+ return;+ }+ litehtml::position::vector redraw;+ m_document->on_mouse_leave(redraw);+ set_cursor("auto");+ update();+}++void HtmlView::mousePressEvent(QMouseEvent *event)+{+ if (!m_document) {+ event->ignore();+ return;+ }+ if (event->button() == Qt::RightButton) {+ Q_EMIT contextRequested(m_hoveredLink, event->position().x(), event->position().y());+ return;+ }+ litehtml::position::vector redraw;+ const QPointF p = event->position();+ m_document->on_lbutton_down(int(p.x()), int(p.y() + m_contentY), int(p.x()), int(p.y()), redraw);+ m_pressedLink = m_hoveredLink;+ // Only links take the click; anything else lets the pane scroll.+ if (m_hoveredLink.isEmpty()) {+ event->ignore();+ }+}++void HtmlView::mouseReleaseEvent(QMouseEvent *event)+{+ if (!m_document || event->button() != Qt::LeftButton) {+ return;+ }+ litehtml::position::vector redraw;+ const QPointF p = event->position();+ m_document->on_lbutton_up(int(p.x()), int(p.y() + m_contentY), int(p.x()), int(p.y()), redraw);+ update();+}++litehtml::uint_ptr HtmlView::create_font(const litehtml::tchar_t *faceName, int size, int weight, litehtml::font_style italic, unsigned int decoration,+ litehtml::font_metrics *fm)+{+ QStringList families;+ for (QString family : utf8(faceName).split(QLatin1Char(','), Qt::SkipEmptyParts)) {+ family = family.trimmed().remove(QLatin1Char('"')).remove(QLatin1Char('\''));+ const QString lower = family.toLower();+ if (lower == QLatin1String("serif") || lower.contains(QLatin1String("times")) || lower == QLatin1String("georgia")) {+ families << QStringLiteral("Noto Serif");+ } else if (lower == QLatin1String("monospace") || lower.contains(QLatin1String("courier")) || lower.contains(QLatin1String("consolas"))) {+ families << QStringLiteral("Noto Sans Mono");+ } else if (lower == QLatin1String("sans-serif") || lower.contains(QLatin1String("arial")) || lower.contains(QLatin1String("helvetica"))+ || lower.contains(QLatin1String("segoe")) || lower == QLatin1String("system-ui") || lower == QLatin1String("-apple-system")) {+ families << QStringLiteral("Inter");+ } else {+ families << family;+ }+ }+ families << QStringLiteral("Inter");+ QFont font;+ font.setFamilies(families);+ font.setPixelSize(qMax(1, size));+ font.setWeight(QFont::Weight(qBound(100, weight, 900)));+ font.setItalic(italic == litehtml::fontStyleItalic);+ font.setUnderline(decoration & litehtml::font_decoration_underline);+ font.setStrikeOut(decoration & litehtml::font_decoration_linethrough);+ font.setOverline(decoration & litehtml::font_decoration_overline);+ const QFontMetrics metrics(font);+ if (fm) {+ fm->ascent = metrics.ascent();+ fm->descent = metrics.descent();+ fm->height = metrics.height();+ fm->x_height = metrics.xHeight();+ fm->draw_spaces = font.underline() || font.strikeOut() || font.overline();+ }+ const litehtml::uint_ptr handle = m_nextFont++;+ m_fonts.insert(handle, font);+ return handle;+}++void HtmlView::delete_font(litehtml::uint_ptr hFont)+{+ m_fonts.remove(hFont);+}++QFont HtmlView::fontFor(litehtml::uint_ptr handle) const+{+ return m_fonts.value(handle, QFont(QStringLiteral("Inter")));+}++int HtmlView::text_width(const litehtml::tchar_t *text, litehtml::uint_ptr hFont)+{+ return QFontMetrics(fontFor(hFont)).horizontalAdvance(utf8(text));+}++void HtmlView::draw_text(litehtml::uint_ptr hdc, const litehtml::tchar_t *text, litehtml::uint_ptr hFont, litehtml::web_color color, const litehtml::position &pos)+{+ auto *painter = reinterpret_cast<QPainter *>(hdc);+ const QFont font = fontFor(hFont);+ painter->setFont(font);+ painter->setPen(colourOf(color));+ painter->drawText(pos.x, pos.y + QFontMetrics(font).ascent(), utf8(text));+}++int HtmlView::pt_to_px(int pt) const+{+ return qRound(pt * 96.0 / 72.0);+}++int HtmlView::get_default_font_size() const+{+ return qRound(m_fontSize);+}++const litehtml::tchar_t *HtmlView::get_default_font_name() const+{+ return "Inter";+}++void HtmlView::draw_list_marker(litehtml::uint_ptr hdc, const litehtml::list_marker &marker)+{+ auto *painter = reinterpret_cast<QPainter *>(hdc);+ const QRectF r(marker.pos.x, marker.pos.y, marker.pos.width, marker.pos.height);+ painter->setPen(QPen(colourOf(marker.color), 1));+ switch (marker.marker_type) {+ case litehtml::list_style_type_disc:+ painter->setBrush(colourOf(marker.color));+ painter->drawEllipse(r);+ break;+ case litehtml::list_style_type_circle:+ painter->setBrush(Qt::NoBrush);+ painter->drawEllipse(r);+ break;+ case litehtml::list_style_type_square:+ painter->fillRect(r, colourOf(marker.color));+ break;+ default:+ break;+ }+ painter->setBrush(Qt::NoBrush);+}++QString HtmlView::resolve(const QString &src) const+{+ if (m_baseUrl.isEmpty() || src.contains(QLatin1Char(':'))) {+ return src;+ }+ return QUrl(m_baseUrl).resolved(QUrl(src)).toString();+}++void HtmlView::load_image(const litehtml::tchar_t *src, const litehtml::tchar_t *, bool)+{+ const QString url = resolve(utf8(src));+ if (url.isEmpty() || m_images.contains(url)) {+ return;+ }+ if (m_message) {+ const QImage image = m_message->inlineImage(url);+ if (!image.isNull()) {+ m_images.insert(url, image);+ return;+ }+ }+ // Pictures from the web only with the person's say-so, and trackers+ // never: "Show pictures" shows pictures, not the read receipt hidden+ // among them.+ if (m_allowRemote && (url.startsWith(QLatin1String("https://")) || url.startsWith(QLatin1String("http://")))+ && !(m_message && m_message->isTracker(url))) {+ fetch(url);+ }+}++void HtmlView::fetch(const QString &url)+{+ if (m_fetching.contains(url)) {+ return;+ }+ m_fetching.insert(url);+ if (!m_network) {+ m_network = new QNetworkAccessManager(this);+ m_network->setCookieJar(nullptr);+ m_network->setRedirectPolicy(QNetworkRequest::NoLessSafeRedirectPolicy);+ }+ QNetworkRequest request{QUrl(url)};+ // Nothing that tells the sender more than the picture's address already+ // does: no cookies, no referrer, a browser-like agent.+ request.setHeader(QNetworkRequest::UserAgentHeader, QStringLiteral("Mozilla/5.0"));+ request.setAttribute(QNetworkRequest::CookieLoadControlAttribute, QNetworkRequest::Manual);+ request.setAttribute(QNetworkRequest::CookieSaveControlAttribute, QNetworkRequest::Manual);+ request.setTransferTimeout(20000);+ QNetworkReply *reply = m_network->get(request);+ const QString html = m_html;+ connect(reply, &QNetworkReply::finished, this, [this, reply, url, html]() {+ reply->deleteLater();+ if (html != m_html || reply->error() != QNetworkReply::NoError) {+ return;+ }+ const QImage image = QImage::fromData(reply->read(8 * 1024 * 1024));+ if (image.isNull()) {+ return;+ }+ m_images.insert(url, image);+ // A picture arriving can change the layout around it.+ m_renderedWidth = -1;+ relayout();+ });+}++void HtmlView::get_image_size(const litehtml::tchar_t *src, const litehtml::tchar_t *, litehtml::size &sz)+{+ const QImage image = m_images.value(resolve(utf8(src)));+ sz.width = image.width();+ sz.height = image.height();+}++void HtmlView::draw_background(litehtml::uint_ptr hdc, const litehtml::background_paint &bg)+{+ auto *painter = reinterpret_cast<QPainter *>(hdc);+ // The page itself: transparent over the window's glass for plain mail,+ // white for designed mail.+ if (bg.is_root) {+ // The page colour fills the whole message, not just the part+ // litehtml thinks of as the window.+ const QRect page(0, 0, int(width()), m_contentHeight);+ if (m_paper) {+ painter->fillRect(page, Qt::white);+ }+ if (bg.color.alpha > 0 && m_paper) {+ painter->fillRect(page, colourOf(bg.color));+ } else if (m_pageColour.isValid() && m_paper) {+ painter->fillRect(page, m_pageColour);+ }+ if (bg.image.empty()) {+ return;+ }+ }+ const QRectF box(bg.border_box.x, bg.border_box.y, bg.border_box.width, bg.border_box.height);+ painter->save();+ painter->setClipRect(QRect(bg.clip_box.x, bg.clip_box.y, bg.clip_box.width, bg.clip_box.height), Qt::IntersectClip);+ if (bg.color.alpha > 0 && !bg.is_root) {+ if (hasRadius(bg.border_radius)) {+ painter->fillPath(roundedPath(box, bg.border_radius), colourOf(bg.color));+ } else {+ painter->fillRect(box, colourOf(bg.color));+ }+ }+ if (!bg.image.empty()) {+ const QImage image = m_images.value(resolve(utf8(bg.image.c_str())));+ if (!image.isNull() && bg.image_size.width > 0 && bg.image_size.height > 0) {+ const QImage scaled = image.scaled(bg.image_size.width, bg.image_size.height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);+ const QRect origin(bg.origin_box.x, bg.origin_box.y, bg.origin_box.width, bg.origin_box.height);+ const QPoint start(origin.x() + bg.position_x, origin.y() + bg.position_y);+ switch (bg.repeat) {+ case litehtml::background_repeat_no_repeat:+ painter->drawImage(start, scaled);+ break;+ case litehtml::background_repeat_repeat_x:+ painter->drawTiledPixmap(QRect(bg.clip_box.x, start.y(), bg.clip_box.width, scaled.height()), QPixmap::fromImage(scaled),+ QPoint((bg.clip_box.x - start.x()) % qMax(1, scaled.width()), 0));+ break;+ case litehtml::background_repeat_repeat_y:+ painter->drawTiledPixmap(QRect(start.x(), bg.clip_box.y, scaled.width(), bg.clip_box.height), QPixmap::fromImage(scaled),+ QPoint(0, (bg.clip_box.y - start.y()) % qMax(1, scaled.height())));+ break;+ default:+ painter->drawTiledPixmap(QRect(bg.clip_box.x, bg.clip_box.y, bg.clip_box.width, bg.clip_box.height), QPixmap::fromImage(scaled),+ QPoint((bg.clip_box.x - start.x()) % qMax(1, scaled.width()), (bg.clip_box.y - start.y()) % qMax(1, scaled.height())));+ break;+ }+ }+ }+ painter->restore();+}++void HtmlView::draw_borders(litehtml::uint_ptr hdc, const litehtml::borders &borders, const litehtml::position &draw_pos, bool)+{+ auto *painter = reinterpret_cast<QPainter *>(hdc);+ const QRectF r(draw_pos.x, draw_pos.y, draw_pos.width, draw_pos.height);+ const auto penFor = [](const litehtml::border &b) {+ QPen pen(colourOf(b.color), b.width);+ pen.setCapStyle(Qt::FlatCap);+ if (b.style == litehtml::border_style_dashed) {+ pen.setStyle(Qt::DashLine);+ } else if (b.style == litehtml::border_style_dotted) {+ pen.setStyle(Qt::DotLine);+ }+ return pen;+ };+ const auto visible = [](const litehtml::border &b) {+ return b.width > 0 && b.style != litehtml::border_style_none && b.style != litehtml::border_style_hidden && b.color.alpha > 0;+ };+ const bool uniform = borders.left.width == borders.top.width && borders.top.width == borders.right.width && borders.right.width == borders.bottom.width+ && colourOf(borders.left.color) == colourOf(borders.top.color) && colourOf(borders.top.color) == colourOf(borders.right.color)+ && colourOf(borders.right.color) == colourOf(borders.bottom.color);+ painter->save();+ if (uniform && visible(borders.top) && hasRadius(borders.radius)) {+ const qreal half = borders.top.width / 2.0;+ painter->setPen(penFor(borders.top));+ painter->setBrush(Qt::NoBrush);+ painter->drawPath(roundedPath(r.adjusted(half, half, -half, -half), borders.radius));+ } else {+ if (visible(borders.top)) {+ painter->setPen(penFor(borders.top));+ const qreal y = r.top() + borders.top.width / 2.0;+ painter->drawLine(QPointF(r.left(), y), QPointF(r.right(), y));+ }+ if (visible(borders.bottom)) {+ painter->setPen(penFor(borders.bottom));+ const qreal y = r.bottom() - borders.bottom.width / 2.0;+ painter->drawLine(QPointF(r.left(), y), QPointF(r.right(), y));+ }+ if (visible(borders.left)) {+ painter->setPen(penFor(borders.left));+ const qreal x = r.left() + borders.left.width / 2.0;+ painter->drawLine(QPointF(x, r.top()), QPointF(x, r.bottom()));+ }+ if (visible(borders.right)) {+ painter->setPen(penFor(borders.right));+ const qreal x = r.right() - borders.right.width / 2.0;+ painter->drawLine(QPointF(x, r.top()), QPointF(x, r.bottom()));+ }+ }+ painter->restore();+}++void HtmlView::set_caption(const litehtml::tchar_t *)+{+}++void HtmlView::set_base_url(const litehtml::tchar_t *base_url)+{+ m_baseUrl = utf8(base_url);+}++void HtmlView::link(const std::shared_ptr<litehtml::document> &, const litehtml::element::ptr &)+{+}++void HtmlView::on_anchor_click(const litehtml::tchar_t *url, const litehtml::element::ptr &)+{+ const QString target = resolve(utf8(url));+ if (!target.isEmpty() && !target.startsWith(QLatin1Char('#'))) {+ Q_EMIT linkActivated(target);+ }+}++void HtmlView::set_cursor(const litehtml::tchar_t *cursor)+{+ const bool pointer = qstrcmp(cursor, "pointer") == 0;+ setCursor(pointer ? Qt::PointingHandCursor : Qt::ArrowCursor);+ // litehtml only says "pointer" over a link; the address itself comes+ // from the element under the mouse.+ QString link;+ if (pointer && m_document) {+ // The status line shows where a link really goes, the way a browser+ // does, which is how a disguised link gives itself away.+ const QPointF p = mapFromGlobal(QCursor::pos());+ litehtml::element::ptr el = m_document->root() ? m_document->root()->get_element_by_point(int(p.x()), int(p.y() + m_contentY), int(p.x()), int(p.y())) : nullptr;+ while (el) {+ if (const char *tag = el->get_tagName(); tag && qstricmp(tag, "a") == 0) {+ link = resolve(utf8(el->get_attr("href")));+ break;+ }+ el = el->parent();+ }+ }+ if (link != m_hoveredLink) {+ m_hoveredLink = link;+ Q_EMIT hoveredLinkChanged();+ }+}++void HtmlView::transform_text(litehtml::tstring &text, litehtml::text_transform tt)+{+ QString s = QString::fromUtf8(text.c_str());+ switch (tt) {+ case litehtml::text_transform_uppercase:+ s = s.toUpper();+ break;+ case litehtml::text_transform_lowercase:+ s = s.toLower();+ break;+ case litehtml::text_transform_capitalize:+ if (!s.isEmpty()) {+ s[0] = s[0].toUpper();+ }+ break;+ default:+ break;+ }+ text = s.toStdString();+}++// Style sheets from the web would tell the sender the message was opened,+// just like pictures, so none are fetched.+void HtmlView::import_css(litehtml::tstring &text, const litehtml::tstring &, litehtml::tstring &)+{+ text.clear();+}++void HtmlView::set_clip(const litehtml::position &pos, const litehtml::border_radiuses &, bool valid_x, bool valid_y)+{+ QRect clip(pos.x, pos.y, pos.width, pos.height);+ if (!valid_x) {+ clip.setLeft(-100000);+ clip.setRight(100000);+ }+ if (!valid_y) {+ clip.setTop(-1000000);+ clip.setBottom(1000000);+ }+ if (!m_clips.isEmpty()) {+ clip = clip.intersected(m_clips.top());+ }+ m_clips.push(clip);+ if (m_painter) {+ m_painter->setClipRect(clip);+ }+}++void HtmlView::del_clip()+{+ if (!m_clips.isEmpty()) {+ m_clips.pop();+ }+ if (m_painter) {+ if (m_clips.isEmpty()) {+ m_painter->setClipping(false);+ } else {+ m_painter->setClipRect(m_clips.top());+ }+ }+}++void HtmlView::get_client_rect(litehtml::position &client) const+{+ client.x = 0;+ client.y = 0;+ client.width = int(width());+ client.height = int(height());+}++std::shared_ptr<litehtml::element> HtmlView::create_element(const litehtml::tchar_t *, const litehtml::string_map &, const std::shared_ptr<litehtml::document> &)+{+ return nullptr;+}++void HtmlView::get_media_features(litehtml::media_features &media) const+{+ media.type = litehtml::media_type_screen;+ media.width = int(width());+ media.height = int(height());+ media.device_width = int(width());+ media.device_height = int(height());+ media.color = 8;+ media.monochrome = 0;+ media.color_index = 256;+ media.resolution = 96;+}++void HtmlView::get_language(litehtml::tstring &language, litehtml::tstring &culture) const+{+ language = "en";+ culture.clear();+}diff --git a/packages/wildos-mail/src/htmlview.h b/packages/wildos-mail/src/htmlview.hnew file mode 100644index 0000000..51334c7--- /dev/null+++ b/packages/wildos-mail/src/htmlview.h@@ -0,0 +1,189 @@+#pragma once++#include <QColor>+#include <QFont>+#include <QHash>+#include <QImage>+#include <QPointer>+#include <QQuickPaintedItem>+#include <QStack>+#include <QtQml/qqmlregistration.h>++#include <litehtml/litehtml.h>++#include <memory>++#include "messageview.h"+class QNetworkAccessManager;++// Draws an email's HTML with litehtml: HTML and CSS only, no scripts, no+// plug-ins, nothing fetched unless the person says "Show pictures". It is a+// viewport onto the rendered message: QML scrolls it by setting contentY,+// so a long newsletter never needs one huge texture.+class HtmlView : public QQuickPaintedItem, private litehtml::document_container+{+ Q_OBJECT+ QML_ELEMENT++ Q_PROPERTY(QString html READ html WRITE setHtml NOTIFY htmlChanged)+ Q_PROPERTY(MessageView *message READ message WRITE setMessage NOTIFY messageChanged)+ Q_PROPERTY(bool allowRemote READ allowRemote WRITE setAllowRemote NOTIFY allowRemoteChanged)+ Q_PROPERTY(bool paper READ paper WRITE setPaper NOTIFY paperChanged)+ Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor NOTIFY coloursChanged)+ Q_PROPERTY(QColor linkColor READ linkColor WRITE setLinkColor NOTIFY coloursChanged)+ Q_PROPERTY(QColor quoteColor READ quoteColor WRITE setQuoteColor NOTIFY coloursChanged)+ Q_PROPERTY(qreal fontSize READ fontSize WRITE setFontSize NOTIFY coloursChanged)+ Q_PROPERTY(qreal contentY READ contentY WRITE setContentY NOTIFY contentYChanged)+ Q_PROPERTY(int contentHeight READ contentHeight NOTIFY contentHeightChanged)+ Q_PROPERTY(int contentWidth READ contentWidth NOTIFY contentHeightChanged)+ Q_PROPERTY(QString hoveredLink READ hoveredLink NOTIFY hoveredLinkChanged)++public:+ explicit HtmlView(QQuickItem *parent = nullptr);+ ~HtmlView() override;++ QString html() const+ {+ return m_html;+ }+ void setHtml(const QString &html);+ MessageView *message() const+ {+ return m_message;+ }+ void setMessage(MessageView *message);+ bool allowRemote() const+ {+ return m_allowRemote;+ }+ void setAllowRemote(bool allow);+ bool paper() const+ {+ return m_paper;+ }+ void setPaper(bool paper);+ QColor textColor() const+ {+ return m_textColor;+ }+ void setTextColor(const QColor &c);+ QColor linkColor() const+ {+ return m_linkColor;+ }+ void setLinkColor(const QColor &c);+ QColor quoteColor() const+ {+ return m_quoteColor;+ }+ void setQuoteColor(const QColor &c);+ qreal fontSize() const+ {+ return m_fontSize;+ }+ void setFontSize(qreal size);+ qreal contentY() const+ {+ return m_contentY;+ }+ void setContentY(qreal y);+ int contentHeight() const+ {+ return m_contentHeight;+ }+ int contentWidth() const+ {+ return m_contentWidth;+ }+ QString hoveredLink() const+ {+ return m_hoveredLink;+ }++ void paint(QPainter *painter) override;++Q_SIGNALS:+ void htmlChanged();+ void messageChanged();+ void allowRemoteChanged();+ void paperChanged();+ void coloursChanged();+ void contentYChanged();+ void contentHeightChanged();+ void hoveredLinkChanged();+ void linkActivated(const QString &url);+ // A right click, with the link under the pointer if there is one.+ void contextRequested(const QString &link, qreal x, qreal y);++protected:+ void geometryChange(const QRectF &newGeometry, const QRectF &oldGeometry) override;+ void hoverMoveEvent(QHoverEvent *event) override;+ void hoverLeaveEvent(QHoverEvent *event) override;+ void mousePressEvent(QMouseEvent *event) override;+ void mouseReleaseEvent(QMouseEvent *event) override;++private:+ // litehtml::document_container+ litehtml::uint_ptr create_font(const litehtml::tchar_t *faceName, int size, int weight, litehtml::font_style italic, unsigned int decoration,+ litehtml::font_metrics *fm) override;+ void delete_font(litehtml::uint_ptr hFont) override;+ int text_width(const litehtml::tchar_t *text, litehtml::uint_ptr hFont) override;+ void draw_text(litehtml::uint_ptr hdc, const litehtml::tchar_t *text, litehtml::uint_ptr hFont, litehtml::web_color color, const litehtml::position &pos) override;+ int pt_to_px(int pt) const override;+ int get_default_font_size() const override;+ const litehtml::tchar_t *get_default_font_name() const override;+ void draw_list_marker(litehtml::uint_ptr hdc, const litehtml::list_marker &marker) override;+ void load_image(const litehtml::tchar_t *src, const litehtml::tchar_t *baseurl, bool redraw_on_ready) override;+ void get_image_size(const litehtml::tchar_t *src, const litehtml::tchar_t *baseurl, litehtml::size &sz) override;+ void draw_background(litehtml::uint_ptr hdc, const litehtml::background_paint &bg) override;+ void draw_borders(litehtml::uint_ptr hdc, const litehtml::borders &borders, const litehtml::position &draw_pos, bool root) override;+ void set_caption(const litehtml::tchar_t *caption) override;+ void set_base_url(const litehtml::tchar_t *base_url) override;+ void link(const std::shared_ptr<litehtml::document> &doc, const litehtml::element::ptr &el) override;+ void on_anchor_click(const litehtml::tchar_t *url, const litehtml::element::ptr &el) override;+ void set_cursor(const litehtml::tchar_t *cursor) override;+ void transform_text(litehtml::tstring &text, litehtml::text_transform tt) override;+ void import_css(litehtml::tstring &text, const litehtml::tstring &url, litehtml::tstring &baseurl) override;+ void set_clip(const litehtml::position &pos, const litehtml::border_radiuses &bdr_radius, bool valid_x, bool valid_y) override;+ void del_clip() override;+ void get_client_rect(litehtml::position &client) const override;+ std::shared_ptr<litehtml::element> create_element(const litehtml::tchar_t *tag_name, const litehtml::string_map &attributes,+ const std::shared_ptr<litehtml::document> &doc) override;+ void get_media_features(litehtml::media_features &media) const override;+ void get_language(litehtml::tstring &language, litehtml::tstring &culture) const override;++ void rebuild();+ void relayout();+ QString resolve(const QString &src) const;+ void fetch(const QString &url);+ QFont fontFor(litehtml::uint_ptr handle) const;++ QString m_html;+ QPointer<MessageView> m_message;+ bool m_allowRemote = false;+ bool m_paper = false;+ QColor m_textColor = QColor(238, 241, 248);+ QColor m_linkColor = QColor(143, 180, 255);+ QColor m_quoteColor = QColor(238, 241, 248, 158);+ qreal m_fontSize = 14.5;+ qreal m_contentY = 0;+ int m_contentHeight = 0;+ int m_contentWidth = 0;+ int m_renderedWidth = -1;+ QString m_hoveredLink;+ QString m_pressedLink;++ std::unique_ptr<litehtml::context> m_context;+ litehtml::document::ptr m_document;+ QHash<litehtml::uint_ptr, QFont> m_fonts;+ litehtml::uint_ptr m_nextFont = 1;+ QHash<QString, QImage> m_images;+ QSet<QString> m_fetching;+ QNetworkAccessManager *m_network = nullptr;+ QString m_baseUrl;+ QPainter *m_painter = nullptr;+ QStack<QRect> m_clips;+ // The colour a newsletter gives its <body>, which browsers paint across+ // the whole page and litehtml only behind the body's own box.+ QColor m_pageColour;+};diff --git a/packages/wildos-mail/src/mailengine.cpp b/packages/wildos-mail/src/mailengine.cppnew file mode 100644index 0000000..8687183--- /dev/null+++ b/packages/wildos-mail/src/mailengine.cpp@@ -0,0 +1,1981 @@+#include "mailengine.h"++#include <QDir>+#include <QJSEngine>+#include <QLoggingCategory>+#include <QFile>+#include <QNetworkInformation>+#include <QSettings>+#include <QStandardPaths>+#include <QThreadPool>+#include <QUuid>++#include "camelsession.h"++#include <pwd.h>+#include <unistd.h>++Q_LOGGING_CATEGORY(mailLog, "wildos.mail", QtInfoMsg)++namespace+{+const QChar keySep = QLatin1Char('\x1f');++QString str(const gchar *s)+{+ return s ? QString::fromUtf8(s) : QString();+}++QString errorText(GError *error)+{+ return error ? QString::fromUtf8(error->message) : QString();+}++CamelNetworkSecurityMethod securityOf(const QString &security)+{+ if (security == QLatin1String("ssl")) {+ return CAMEL_NETWORK_SECURITY_METHOD_SSL_ON_ALTERNATE_PORT;+ }+ if (security == QLatin1String("starttls")) {+ return CAMEL_NETWORK_SECURITY_METHOD_STARTTLS_ON_STANDARD_PORT;+ }+ return CAMEL_NETWORK_SECURITY_METHOD_NONE;+}++// The folder's job, from the server's special-use flags or, for servers+// that don't send them, from its name.+QString roleOf(const CamelFolderInfo *fi, const QString &provider)+{+ switch (fi->flags & CAMEL_FOLDER_TYPE_MASK) {+ case CAMEL_FOLDER_TYPE_INBOX:+ return QStringLiteral("inbox");+ case CAMEL_FOLDER_TYPE_SENT:+ return QStringLiteral("sent");+ case CAMEL_FOLDER_TYPE_DRAFTS:+ return QStringLiteral("drafts");+ case CAMEL_FOLDER_TYPE_TRASH:+ return QStringLiteral("trash");+ case CAMEL_FOLDER_TYPE_JUNK:+ return QStringLiteral("junk");+ case CAMEL_FOLDER_TYPE_ARCHIVE:+ return QStringLiteral("archive");+ case CAMEL_FOLDER_TYPE_ALL:+ // Gmail archives by taking the Inbox label off, which leaves the+ // message in All Mail.+ return provider == QLatin1String("gmail") ? QStringLiteral("archive") : QStringLiteral("all");+ default:+ break;+ }+ const QString name = str(fi->display_name).toLower();+ const QString full = str(fi->full_name).toLower();+ if (full == QLatin1String("inbox")) {+ return QStringLiteral("inbox");+ }+ if (name == QLatin1String("sent") || name == QLatin1String("sent items") || name == QLatin1String("sent messages") || name == QLatin1String("sent mail")) {+ return QStringLiteral("sent");+ }+ if (name == QLatin1String("drafts") || name == QLatin1String("draft")) {+ return QStringLiteral("drafts");+ }+ if (name == QLatin1String("trash") || name == QLatin1String("deleted items") || name == QLatin1String("deleted messages") || name == QLatin1String("bin")) {+ return QStringLiteral("trash");+ }+ if (name == QLatin1String("junk") || name == QLatin1String("spam") || name == QLatin1String("junk e-mail") || name == QLatin1String("junk email") || name == QLatin1String("bulk mail")) {+ return QStringLiteral("junk");+ }+ if (name == QLatin1String("archive") || name == QLatin1String("archives")) {+ return QStringLiteral("archive");+ }+ return QStringLiteral("folder");+}++QString roleName(const QString &role)+{+ if (role == QLatin1String("inbox")) {+ return MailEngine::tr("Inbox");+ }+ if (role == QLatin1String("sent")) {+ return MailEngine::tr("Sent items");+ }+ if (role == QLatin1String("drafts")) {+ return MailEngine::tr("Drafts");+ }+ if (role == QLatin1String("trash")) {+ return MailEngine::tr("Deleted items");+ }+ if (role == QLatin1String("junk")) {+ return MailEngine::tr("Junk email");+ }+ if (role == QLatin1String("archive")) {+ return MailEngine::tr("Archive");+ }+ if (role == QLatin1String("outbox")) {+ return MailEngine::tr("Outbox");+ }+ return {};+}++int roleOrder(const QString &role)+{+ static const QStringList order = {QStringLiteral("inbox"), QStringLiteral("drafts"), QStringLiteral("outbox"), QStringLiteral("sent"),+ QStringLiteral("archive"), QStringLiteral("trash"), QStringLiteral("junk")};+ const int i = order.indexOf(role);+ return i < 0 ? order.size() : i;+}++void parseAddress(const gchar *raw, QString *name, QString *address)+{+ name->clear();+ address->clear();+ if (!raw || !*raw) {+ return;+ }+ CamelInternetAddress *addr = camel_internet_address_new();+ if (camel_address_decode(CAMEL_ADDRESS(addr), raw) > 0) {+ const gchar *n = nullptr;+ const gchar *a = nullptr;+ camel_internet_address_get(addr, 0, &n, &a);+ *name = str(n);+ *address = str(a);+ }+ g_object_unref(addr);+ if (name->isEmpty()) {+ *name = address->isEmpty() ? str(raw) : *address;+ }+}++QString firstNames(const gchar *raw)+{+ if (!raw || !*raw) {+ return {};+ }+ CamelInternetAddress *addr = camel_internet_address_new();+ QStringList names;+ if (camel_address_decode(CAMEL_ADDRESS(addr), raw) > 0) {+ for (int i = 0; i < camel_address_length(CAMEL_ADDRESS(addr)); ++i) {+ const gchar *n = nullptr;+ const gchar *a = nullptr;+ camel_internet_address_get(addr, i, &n, &a);+ names << (n && *n ? str(n) : str(a));+ }+ }+ g_object_unref(addr);+ return names.join(QStringLiteral(", "));+}++QString outboxDir(const QString &accountId)+{+ return QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QStringLiteral("/outbox/") + accountId;+}++MessageRow rowFrom(const QString &accountId, const QString &folder, CamelMessageInfo *mi)+{+ MessageRow r;+ r.accountId = accountId;+ r.folder = folder;+ r.uid = str(camel_message_info_get_uid(mi));+ parseAddress(camel_message_info_get_from(mi), &r.fromName, &r.fromAddress);+ r.to = firstNames(camel_message_info_get_to(mi));+ QString toName;+ parseAddress(camel_message_info_get_to(mi), &toName, &r.toAddress);+ r.subject = str(camel_message_info_get_subject(mi));+ r.preview = str(camel_message_info_get_preview(mi)).simplified();+ gint64 when = camel_message_info_get_date_received(mi);+ if (when <= 0) {+ when = camel_message_info_get_date_sent(mi);+ }+ r.date = QDateTime::fromSecsSinceEpoch(when);+ const guint32 flags = camel_message_info_get_flags(mi);+ r.unread = !(flags & CAMEL_MESSAGE_SEEN);+ r.flagged = flags & CAMEL_MESSAGE_FLAGGED;+ r.attachment = flags & CAMEL_MESSAGE_ATTACHMENTS;+ r.draft = flags & CAMEL_MESSAGE_DRAFT;+ r.pinned = camel_message_info_get_user_flag(mi, "wildos-pinned");+ if (const gchar *snooze = camel_message_info_get_user_tag(mi, "wildos-snooze")) {+ r.snoozedUntil = QDateTime::fromString(str(snooze), Qt::ISODate);+ }+ return r;+}++const char *trackerDayKey(const QDate &d)+{+ static thread_local QByteArray key;+ key = "trackers/" + d.toString(Qt::ISODate).toLatin1();+ return key.constData();+}+}++MailEngine *MailEngine::instance()+{+ static MailEngine *engine = new MailEngine();+ return engine;+}++MailEngine *MailEngine::create(QQmlEngine *, QJSEngine *)+{+ MailEngine *engine = instance();+ QJSEngine::setObjectOwnership(engine, QJSEngine::CppOwnership);+ return engine;+}++MailEngine::MailEngine(QObject *parent)+ : QObject(parent)+ , m_folderModel(new FolderModel(this))+ , m_messageModel(new MessageModel(this))+{+ Session::instance();+ m_messageModel->folderName = [this](const QString &accountId, const QString &folder) {+ return folderLabel(accountId, folder);+ };++ m_reloadTimer.setSingleShot(true);+ m_reloadTimer.setInterval(250);+ connect(&m_reloadTimer, &QTimer::timeout, this, [this]() {+ reloadMessages();+ for (const QString &id : m_live.keys()) {+ listFolders(id);+ }+ });++ // IDLE brings new mail to the Inbox as it arrives; the other folders+ // are looked at every five minutes.+ m_pollTimer.setInterval(5 * 60 * 1000);+ connect(&m_pollTimer, &QTimer::timeout, this, &MailEngine::refresh);+ m_pollTimer.start();++ // Snoozed mail comes back on time, unread, at the top.+ m_snoozeTimer.setInterval(60 * 1000);+ connect(&m_snoozeTimer, &QTimer::timeout, this, [this]() {+ reloadMessages();+ });+ m_snoozeTimer.start();++ if (QNetworkInformation::loadBackendByFeatures(QNetworkInformation::Feature::Reachability)) {+ auto *info = QNetworkInformation::instance();+ m_online = info->reachability() != QNetworkInformation::Reachability::Disconnected;+ connect(info, &QNetworkInformation::reachabilityChanged, this, [this](QNetworkInformation::Reachability r) {+ setOnline(r != QNetworkInformation::Reachability::Disconnected);+ });+ }++ connect(&m_store, &AccountStore::changed, this, &MailEngine::accountsChanged);+ for (const Account &account : m_store.accounts()) {+ startAccount(account);+ }+ rebuildFolderModel();+}++QVariantList MailEngine::accountList() const+{+ QVariantList list;+ for (const Account &a : m_store.accounts()) {+ QVariantMap map = a.toMap();+ const Live live = m_live.value(a.id);+ map.insert(QStringLiteral("problem"), live.problem);+ map.insert(QStringLiteral("problemKind"), live.problemKind);+ map.insert(QStringLiteral("connected"), live.connected);+ list.append(map);+ }+ return list;+}++QString MailEngine::folderTitle() const+{+ if (searching()) {+ return tr("Search results");+ }+ if (m_folderAccount.isEmpty()) {+ return roleName(m_folderRole);+ }+ return folderLabel(m_folderAccount, m_folderFullName);+}++QString MailEngine::folderLabel(const QString &accountId, const QString &fullName) const+{+ for (const FolderEntry &e : m_live.value(accountId).folders) {+ if (e.fullName == fullName) {+ return e.displayName;+ }+ }+ return fullName.section(QLatin1Char('/'), -1);+}++void MailEngine::select(const QString &key)+{+ if (key == m_selected) {+ return;+ }+ m_selected = key;+ m_selection = key.isEmpty() ? QStringList() : QStringList{key};+ m_anchor = key;+ Q_EMIT selectedChanged();+ // A message counts as read once it has been open for two seconds, so+ // arrowing past it doesn't (Settings > Mail > Mark as read).+ QTimer::singleShot(2000, this, [this, key]() {+ if (key != m_selected) {+ return;+ }+ if (const MessageRow *r = m_messageModel->row(key); r && r->unread) {+ setRead(key, true);+ }+ });+}++int MailEngine::trackersThisWeek() const+{+ QSettings settings;+ int sum = 0;+ const QDate today = QDate::currentDate();+ for (int i = 0; i < 7; ++i) {+ sum += settings.value(QLatin1String(trackerDayKey(today.addDays(-i)))).toInt();+ }+ return sum;+}++void MailEngine::countTrackers(int blocked, const QString &messageId)+{+ if (blocked <= 0) {+ return;+ }+ QSettings settings;+ const QString seen = QStringLiteral("trackersCounted/") + QString::number(qHash(messageId), 16);+ if (settings.contains(seen)) {+ return;+ }+ settings.setValue(seen, QDate::currentDate());+ // Only this week's are worth remembering.+ settings.beginGroup(QStringLiteral("trackersCounted"));+ for (const QString &k : settings.childKeys()) {+ if (settings.value(k).toDate() < QDate::currentDate().addDays(-8)) {+ settings.remove(k);+ }+ }+ settings.endGroup();+ const char *key = trackerDayKey(QDate::currentDate());+ settings.setValue(QLatin1String(key), settings.value(QLatin1String(key)).toInt() + blocked);+ Q_EMIT trackersChanged();+}++QString MailEngine::systemFullName()+{+ const passwd *pw = getpwuid(getuid());+ if (!pw || !pw->pw_gecos) {+ return {};+ }+ return QString::fromLocal8Bit(pw->pw_gecos).section(QLatin1Char(','), 0, 0).trimmed();+}++int MailEngine::photosCleaned() const+{+ return QSettings().value(QStringLiteral("privacy/photosCleaned")).toInt();+}++void MailEngine::countCleanedPhotos(int photos)+{+ if (photos > 0) {+ QSettings settings;+ settings.setValue(QStringLiteral("privacy/photosCleaned"), settings.value(QStringLiteral("privacy/photosCleaned")).toInt() + photos);+ Q_EMIT trackersChanged();+ }+}++QVariantList MailEngine::problems() const+{+ QVariantList list;+ for (const Account &a : m_store.accounts()) {+ const Live &live = m_live[a.id];+ if (!live.problem.isEmpty()) {+ list.append(QVariantMap{{QStringLiteral("accountId"), a.id},+ {QStringLiteral("name"), a.name},+ {QStringLiteral("kind"), live.problemKind},+ {QStringLiteral("text"), live.problem}});+ }+ }+ return list;+}++int MailEngine::outboxCount() const+{+ int n = 0;+ for (const Account &a : m_store.accounts()) {+ n += QDir(outboxDir(a.id)).entryList({QStringLiteral("*.eml")}, QDir::Files).size();+ }+ return n;+}++void MailEngine::run(std::function<void()> work, std::function<void()> done)+{+ QPointer<MailEngine> self(this);+ QThreadPool::globalInstance()->start([self, work, done]() {+ work();+ if (done && self) {+ QMetaObject::invokeMethod(self, done, Qt::QueuedConnection);+ }+ });+}++void MailEngine::configure(CamelService *store, CamelService *smtp, const Account &account) const+{+ if (store) {+ CamelSettings *settings = camel_service_ref_settings(store);+ g_object_set(settings,+ "host", account.imapHost.toUtf8().constData(),+ "port", guint(account.imapPort),+ "user", account.user.toUtf8().constData(),+ "security-method", securityOf(account.imapSecurity),+ "use-idle", TRUE,+ "check-all", TRUE,+ "use-subscriptions", FALSE,+ "stay-synchronized", account.keepAll,+ "auth-mechanism", account.auth == QLatin1String("google") ? "XOAUTH2" : nullptr,+ nullptr);+ g_object_unref(settings);+ }+ if (smtp) {+ CamelSettings *settings = camel_service_ref_settings(smtp);+ g_object_set(settings,+ "host", account.smtpHost.toUtf8().constData(),+ "port", guint(account.smtpPort),+ "user", account.user.toUtf8().constData(),+ "security-method", securityOf(account.smtpSecurity),+ "auth-mechanism", account.auth == QLatin1String("google") ? "XOAUTH2" : "PLAIN",+ nullptr);+ g_object_unref(settings);+ }+}++void MailEngine::startAccount(const Account &account)+{+ CamelSession *session = Session::instance().camel();+ // Workers read m_live under the folder lock, so changes to it here take+ // the lock too.+ QMutexLocker lock(&m_folderLock);+ Live &live = m_live[account.id];+ GError *error = nullptr;+ if (!live.store) {+ CamelService *service = camel_session_add_service(session, account.id.toUtf8().constData(), "imapx", CAMEL_PROVIDER_STORE, &error);+ if (!service) {+ const QString text = errorText(error);+ g_clear_error(&error);+ lock.unlock();+ setProblem(account.id, QStringLiteral("unreachable"), text);+ return;+ }+ live.store = CAMEL_STORE(service);+ watchStore(live.store);+ // Offline until it has its password: what is kept on this PC shows+ // at once, and nothing tries the server without a password.+ camel_offline_store_set_online_sync(CAMEL_OFFLINE_STORE(service), FALSE, nullptr, nullptr);+ }+ if (!live.smtp) {+ live.smtp = camel_session_add_service(session, (account.id + QStringLiteral(".smtp")).toUtf8().constData(), "smtp", CAMEL_PROVIDER_TRANSPORT, &error);+ g_clear_error(&error);+ }+ configure(CAMEL_SERVICE(live.store), live.smtp, account);+ lock.unlock();+ Session::instance().setOAuth(account.id, account.auth == QLatin1String("google"));++ // The cached folders and mail show straight away, before the password+ // store answers and the server is reached.+ listFolders(account.id);+ const QString id = account.id;+ m_store.readPassword(id, [this, id](const QString &password) {+ if (password.isEmpty()) {+ setProblem(id, QStringLiteral("password"), tr("Wild OS Mail needs your password again."));+ return;+ }+ Session::instance().setPassword(id, password);+ connectAccount(id);+ });+}++void MailEngine::stopAccount(const QString &id)+{+ Live live;+ {+ QMutexLocker lock(&m_folderLock);+ live = m_live.take(id);+ for (auto it = m_folderCache.begin(); it != m_folderCache.end();) {+ if (it.key().startsWith(id + keySep)) {+ m_watched.remove(it.value());+ g_object_unref(it.value());+ it = m_folderCache.erase(it);+ } else {+ ++it;+ }+ }+ }+ CamelSession *session = Session::instance().camel();+ if (live.store) {+ CamelService *service = CAMEL_SERVICE(live.store);+ run([service]() {+ camel_service_disconnect_sync(service, FALSE, nullptr, nullptr);+ }, [session, service]() {+ camel_session_remove_service(session, service);+ });+ }+ if (live.smtp) {+ camel_session_remove_service(session, live.smtp);+ }+}++void MailEngine::connectAccount(const QString &id)+{+ if (!m_live.contains(id) || !m_online) {+ return;+ }+ CamelStore *store = m_live[id].store;+ g_object_ref(store);+ auto problem = std::make_shared<QString>();+ auto kind = std::make_shared<QString>();+ ++m_loading;+ Q_EMIT loadingChanged();+ run([store, problem, kind]() {+ GError *error = nullptr;+ camel_offline_store_set_online_sync(CAMEL_OFFLINE_STORE(store), TRUE, nullptr, nullptr);+ if (!camel_service_connect_sync(CAMEL_SERVICE(store), nullptr, &error)) {+ *problem = errorText(error);+ const bool auth = error && error->domain == CAMEL_SERVICE_ERROR && error->code == CAMEL_SERVICE_ERROR_CANT_AUTHENTICATE;+ *kind = auth ? QStringLiteral("password") : QStringLiteral("unreachable");+ g_clear_error(&error);+ }+ }, [this, id, store, problem, kind]() {+ g_object_unref(store);+ --m_loading;+ Q_EMIT loadingChanged();+ if (!m_live.contains(id)) {+ return;+ }+ if (!problem->isEmpty()) {+ qCWarning(mailLog) << "account" << id << "couldn't connect:" << *problem;+ setProblem(id, *kind, *kind == QLatin1String("password") ? tr("The password wasn't accepted. Sign in again to keep getting mail.") : *problem);+ return;+ }+ {+ QMutexLocker lock(&m_folderLock);+ m_live[id].connected = true;+ m_live[id].fetchedAfterConnect = false;+ }+ Q_EMIT accountsChanged();+ setProblem(id, {}, {});+ listFolders(id);+ reloadMessages();+ // Now it can reach the server: fetch what arrived while Mail was+ // closed, for the open folder and the counts of the rest.+ refresh();+ // Mail kept on this PC for reading offline and searching. Camel+ // downloads what is missing in the background.+ const Account *account = m_store.find(id);+ if (account && account->keepAll) {+ CamelStore *s = m_live[id].store;+ g_object_ref(s);+ setSyncStatus(tr("Downloading mail"));+ run([s]() {+ camel_offline_store_prepare_for_offline_sync(CAMEL_OFFLINE_STORE(s), nullptr, nullptr);+ g_object_unref(s);+ }, [this]() {+ setSyncStatus({});+ });+ }+ });+}++void MailEngine::setProblem(const QString &id, const QString &kind, const QString &text)+{+ if (!m_live.contains(id)) {+ return;+ }+ {+ QMutexLocker lock(&m_folderLock);+ Live &live = m_live[id];+ if (live.problem == text && live.problemKind == kind) {+ return;+ }+ live.problem = text;+ live.problemKind = kind;+ }+ Q_EMIT problemsChanged();+ Q_EMIT accountsChanged();+}++void MailEngine::setSyncStatus(const QString &status)+{+ if (status != m_syncStatus) {+ m_syncStatus = status;+ Q_EMIT syncStatusChanged();+ }+}++void MailEngine::setOnline(bool online)+{+ if (online == m_online) {+ return;+ }+ m_online = online;+ camel_session_set_online(Session::instance().camel(), online);+ Q_EMIT onlineChanged();+ if (online) {+ for (const QString &id : m_live.keys()) {+ if (!Session::instance().password(id).isEmpty()) {+ connectAccount(id);+ }+ }+ } else {+ QMutexLocker lock(&m_folderLock);+ for (Live &live : m_live) {+ live.connected = false;+ }+ }+}++void MailEngine::listFolders(const QString &id)+{+ if (!m_live.contains(id)) {+ return;+ }+ const Account *account = m_store.find(id);+ if (!account) {+ return;+ }+ CamelStore *store = m_live[id].store;+ g_object_ref(store);+ const QString provider = account->provider;+ auto entries = std::make_shared<QList<FolderEntry>>();+ run([store, id, provider, entries]() {+ GError *error = nullptr;+ CamelFolderInfo *root = camel_store_get_folder_info_sync(store, nullptr,+ CamelStoreGetFolderInfoFlags(CAMEL_STORE_FOLDER_INFO_RECURSIVE | CAMEL_STORE_FOLDER_INFO_SUBSCRIBED),+ nullptr, &error);+ g_clear_error(&error);+ QList<FolderEntry> special;+ QList<FolderEntry> rest;+ std::function<void(CamelFolderInfo *, int)> walk = [&](CamelFolderInfo *fi, int depth) {+ for (; fi; fi = fi->next) {+ const QString full = str(fi->full_name);+ // Camel's own virtual Trash and Junk stand in for servers+ // without them; the server's real folders are what people+ // know.+ if (full.startsWith(QLatin1String(".#evolution")) || (fi->flags & CAMEL_FOLDER_VIRTUAL)) {+ continue;+ }+ const bool container = fi->flags & CAMEL_FOLDER_NOSELECT;+ if (!container) {+ FolderEntry e;+ e.accountId = id;+ e.fullName = full;+ e.role = roleOf(fi, provider);+ if (e.role == QLatin1String("all")) {+ e.role = QStringLiteral("folder");+ }+ e.displayName = roleName(e.role);+ if (e.displayName.isEmpty()) {+ e.displayName = str(fi->display_name);+ }+ e.unread = qMax(0, fi->unread);+ e.total = qMax(0, fi->total);+ if (e.role == QLatin1String("folder")) {+ e.depth = depth;+ rest.append(e);+ } else if (std::none_of(special.cbegin(), special.cend(), [&](const FolderEntry &s) { return s.role == e.role; })) {+ special.append(e);+ } else {+ rest.append(e);+ }+ }+ // Gmail's "[Gmail]" holds the special folders; its children+ // sit at the top level rather than under a folder that can't+ // be opened.+ walk(fi->child, container ? depth : depth + 1);+ }+ };+ walk(root, 0);+ if (root) {+ camel_folder_info_free(root);+ }+ // Drafts show how many there are; the server's count can still+ // include ones replaced a moment ago, so ask the folder itself.+ for (FolderEntry &e : special) {+ if (e.role != QLatin1String("drafts")) {+ continue;+ }+ CamelFolder *folder = camel_store_get_folder_sync(store, e.fullName.toUtf8().constData(), CamelStoreGetFolderFlags(0), nullptr, nullptr);+ if (folder) {+ e.total = qMax(0, camel_folder_get_message_count(folder) - camel_folder_get_deleted_message_count(folder));+ g_object_unref(folder);+ }+ }+ std::stable_sort(special.begin(), special.end(), [](const FolderEntry &a, const FolderEntry &b) {+ return roleOrder(a.role) < roleOrder(b.role);+ });+ *entries = special + rest;+ g_object_unref(store);+ }, [this, id, entries]() {+ if (!m_live.contains(id)) {+ return;+ }+ bool fetch = false;+ {+ QMutexLocker lock(&m_folderLock);+ Live &live = m_live[id];+ live.folders = *entries;+ fetch = live.connected && !live.fetchedAfterConnect && !entries->isEmpty();+ if (fetch) {+ live.fetchedAfterConnect = true;+ }+ }+ if (fetch) {+ for (const auto &[account, full] : currentFolders()) {+ if (account != id) {+ continue;+ }+ const QString a = account;+ const QString f = full;+ run([this, a, f]() {+ if (CamelFolder *folder = folderSync(a, f, nullptr)) {+ camel_folder_refresh_info_sync(folder, nullptr, nullptr);+ }+ }, [this]() {+ reloadMessages();+ });+ }+ }+ // The first folder list after start-up: open the Inbox.+ if (m_folderRole == QLatin1String("inbox") && m_folderAccount.isEmpty() && m_folderFullName.isEmpty()) {+ reloadMessages();+ }+ rebuildFolderModel();+ });+}++void MailEngine::rebuildFolderModel()+{+ QList<FolderEntry> entries;+ const QList<Account> &accounts = m_store.accounts();+ if (accounts.isEmpty()) {+ m_folderModel->reset({});+ return;+ }++ // Favourites: Inbox, Sent items and Drafts across every account.+ FolderEntry fav;+ fav.kind = FolderEntry::Header;+ fav.displayName = tr("Favourites");+ fav.expanded = m_expanded.value(QString(), true);+ entries.append(fav);+ if (fav.expanded) {+ for (const QString &role : {QStringLiteral("inbox"), QStringLiteral("sent"), QStringLiteral("drafts")}) {+ FolderEntry e;+ e.fullName = role;+ e.role = role;+ e.displayName = roleName(role);+ e.depth = 1;+ for (const Account &a : accounts) {+ for (const FolderEntry &f : m_live.value(a.id).folders) {+ if (f.role == role) {+ e.unread += f.unread;+ e.total += f.total;+ }+ }+ }+ entries.append(e);+ }+ }++ for (const Account &a : accounts) {+ FolderEntry header;+ header.kind = FolderEntry::Header;+ header.accountId = a.id;+ header.displayName = a.name;+ header.expanded = m_expanded.value(a.id, accounts.size() == 1 || &a == &accounts.first());+ entries.append(header);+ if (!header.expanded) {+ continue;+ }+ QList<FolderEntry> folders = m_live.value(a.id).folders;+ const int queued = QDir(outboxDir(a.id)).entryList({QStringLiteral("*.eml")}, QDir::Files).size();+ if (queued > 0) {+ FolderEntry outbox;+ outbox.accountId = a.id;+ outbox.fullName = QStringLiteral(".outbox");+ outbox.role = QStringLiteral("outbox");+ outbox.displayName = roleName(outbox.role);+ outbox.total = queued;+ int at = 0;+ while (at < folders.size() && roleOrder(folders[at].role) <= roleOrder(outbox.role)) {+ ++at;+ }+ folders.insert(at, outbox);+ }+ for (FolderEntry f : folders) {+ f.depth += 1;+ entries.append(f);+ }+ FolderEntry create;+ create.kind = FolderEntry::Create;+ create.accountId = a.id;+ create.displayName = tr("Create new folder");+ entries.append(create);+ }+ m_folderModel->reset(entries);+}++void MailEngine::toggleExpanded(const QString &accountId)+{+ const bool now = m_expanded.value(accountId, accountId.isEmpty() || m_store.accounts().size() == 1+ || (!m_store.accounts().isEmpty() && m_store.accounts().first().id == accountId));+ m_expanded.insert(accountId, !now);+ rebuildFolderModel();+}++QString MailEngine::roleFullName(const QString &accountId, const QString &role) const+{+ for (const FolderEntry &f : m_live.value(accountId).folders) {+ if (f.role == role) {+ return f.fullName;+ }+ }+ return {};+}++QList<QPair<QString, QString>> MailEngine::currentFolders() const+{+ QList<QPair<QString, QString>> list;+ if (m_folderAccount.isEmpty()) {+ for (const Account &a : m_store.accounts()) {+ const QString full = roleFullName(a.id, m_folderRole);+ if (!full.isEmpty()) {+ list.append({a.id, full});+ }+ }+ } else if (m_folderRole != QLatin1String("outbox")) {+ list.append({m_folderAccount, m_folderFullName});+ }+ return list;+}++void MailEngine::openFolder(const QString &accountId, const QString &fullName)+{+ m_searchText.clear();+ m_folderAccount = accountId;+ if (accountId.isEmpty()) {+ m_folderRole = fullName;+ m_folderFullName.clear();+ } else {+ m_folderFullName = fullName;+ m_folderRole = QStringLiteral("folder");+ for (const FolderEntry &f : m_live.value(accountId).folders) {+ if (f.fullName == fullName) {+ m_folderRole = f.role;+ }+ }+ if (fullName == QLatin1String(".outbox")) {+ m_folderRole = QStringLiteral("outbox");+ }+ }+ m_messageModel->setFilter(QStringLiteral("all"));+ m_messageModel->reset({});+ m_selected.clear();+ Q_EMIT selectedChanged();+ Q_EMIT searchChanged();+ Q_EMIT folderChanged();+ reloadMessages();++ // Opening a folder asks the server for anything new in it.+ for (const auto &[account, full] : currentFolders()) {+ if (!m_online || !m_live.value(account).connected) {+ continue;+ }+ const QString a = account;+ const QString f = full;+ run([this, a, f]() {+ GError *error = nullptr;+ if (CamelFolder *folder = folderSync(a, f, &error)) {+ camel_folder_refresh_info_sync(folder, nullptr, nullptr);+ }+ g_clear_error(&error);+ });+ }+}++void MailEngine::scheduleReload()+{+ m_reloadTimer.start();+}++CamelFolder *MailEngine::folderSync(const QString &accountId, const QString &fullName, GError **error)+{+ const QString cacheKey = accountId + keySep + fullName;+ CamelStore *store = nullptr;+ {+ QMutexLocker lock(&m_folderLock);+ if (CamelFolder *folder = m_folderCache.value(cacheKey)) {+ return folder;+ }+ store = m_live.value(accountId).store;+ if (!store) {+ g_set_error_literal(error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND, "No such account");+ return nullptr;+ }+ g_object_ref(store);+ }+ CamelFolder *folder = camel_store_get_folder_sync(store, fullName.toUtf8().constData(), CamelStoreGetFolderFlags(0), nullptr, error);+ g_object_unref(store);+ if (!folder) {+ return nullptr;+ }+ QMutexLocker lock(&m_folderLock);+ if (CamelFolder *existing = m_folderCache.value(cacheKey)) {+ g_object_unref(folder);+ return existing;+ }+ m_folderCache.insert(cacheKey, folder);+ QMetaObject::invokeMethod(this, [this, folder]() {+ watchFolder(folder);+ }, Qt::QueuedConnection);+ return folder;+}++CamelFolder *MailEngine::roleFolderSync(const QString &accountId, const QString &role, GError **error)+{+ QString full;+ {+ QMutexLocker lock(&m_folderLock);+ full = roleFullName(accountId, role);+ }+ if (full.isEmpty()) {+ g_set_error(error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND, "This account has no %s folder", role.toUtf8().constData());+ return nullptr;+ }+ return folderSync(accountId, full, error);+}++CamelService *MailEngine::transport(const QString &accountId) const+{+ return m_live.value(accountId).smtp;+}++void MailEngine::watchFolder(CamelFolder *folder)+{+ if (m_watched.contains(folder)) {+ return;+ }+ m_watched.insert(folder);+ g_signal_connect(folder, "changed", G_CALLBACK(&MailEngine::onFolderChanged), this);+}++void MailEngine::watchStore(CamelStore *store)+{+ for (const char *signal : {"folder-created", "folder-deleted", "folder-renamed", "folder-info-stale"}) {+ g_signal_connect(store, signal, G_CALLBACK(&MailEngine::onStoreChanged), this);+ }+}++void MailEngine::onFolderChanged(CamelFolder *, CamelFolderChangeInfo *, gpointer self)+{+ auto *engine = static_cast<MailEngine *>(self);+ QMetaObject::invokeMethod(engine, &MailEngine::scheduleReload, Qt::QueuedConnection);+}++void MailEngine::onStoreChanged(CamelStore *, gpointer, gpointer self)+{+ auto *engine = static_cast<MailEngine *>(self);+ QMetaObject::invokeMethod(engine, &MailEngine::scheduleReload, Qt::QueuedConnection);+}++void MailEngine::reloadMessages()+{+ if (searching()) {+ search(m_searchText);+ return;+ }+ const int generation = ++m_generation;+ const QList<QPair<QString, QString>> folders = currentFolders();+ const bool outbox = m_folderRole == QLatin1String("outbox");+ const QString outboxAccount = m_folderAccount;+ auto rows = std::make_shared<QList<MessageRow>>();+ auto inbox = std::make_shared<QHash<QString, QList<MessageRow>>>();+ QSet<QString> outgoingFolders;+ for (auto it = m_live.cbegin(); it != m_live.cend(); ++it) {+ for (const FolderEntry &f : it->folders) {+ if (f.role == QLatin1String("sent") || f.role == QLatin1String("drafts")) {+ outgoingFolders.insert(it.key() + keySep + f.fullName);+ }+ }+ }+ run([this, folders, rows, inbox, outbox, outboxAccount, outgoingFolders]() {+ if (outbox) {+ const QDir dir(outboxDir(outboxAccount));+ for (const QFileInfo &file : dir.entryInfoList({QStringLiteral("*.eml")}, QDir::Files)) {+ CamelMimeMessage *message = camel_mime_message_new();+ CamelStream *stream = camel_stream_fs_new_with_name(file.filePath().toUtf8().constData(), O_RDONLY, 0, nullptr);+ if (stream && camel_data_wrapper_construct_from_stream_sync(CAMEL_DATA_WRAPPER(message), stream, nullptr, nullptr)) {+ MessageRow r;+ r.accountId = outboxAccount;+ r.folder = QStringLiteral(".outbox");+ r.uid = file.fileName();+ r.to = firstNames(camel_address_format(CAMEL_ADDRESS(camel_mime_message_get_recipients(message, CAMEL_RECIPIENT_TYPE_TO))));+ r.fromName = r.to;+ r.draft = true;+ r.subject = str(camel_mime_message_get_subject(message));+ r.date = file.lastModified();+ rows->append(r);+ }+ g_clear_object(&stream);+ g_object_unref(message);+ }+ return;+ }+ for (const auto &[accountId, full] : folders) {+ GError *error = nullptr;+ CamelFolder *folder = folderSync(accountId, full, &error);+ g_clear_error(&error);+ if (!folder) {+ continue;+ }+ camel_folder_summary_prepare_fetch_all(camel_folder_get_folder_summary(folder), nullptr);+ GPtrArray *uids = camel_folder_get_uids(folder);+ for (guint i = 0; i < uids->len; ++i) {+ CamelMessageInfo *mi = camel_folder_get_message_info(folder, static_cast<const char *>(uids->pdata[i]));+ if (!mi) {+ continue;+ }+ const guint32 flags = camel_message_info_get_flags(mi);+ if (!(flags & (CAMEL_MESSAGE_DELETED | CAMEL_MESSAGE_JUNK)) || full.contains(QLatin1String("Junk"), Qt::CaseInsensitive)) {+ MessageRow r = rowFrom(accountId, full, mi);+ r.outgoing = outgoingFolders.contains(accountId + keySep + full);+ rows->append(r);+ if ((camel_folder_get_flags(folder) & CAMEL_FOLDER_IS_JUNK) == 0 && full.compare(QLatin1String("INBOX"), Qt::CaseInsensitive) == 0) {+ (*inbox)[accountId].append(r);+ }+ }+ g_object_unref(mi);+ }+ camel_folder_free_uids(folder, uids);+ }+ }, [this, generation, rows, inbox]() {+ for (auto it = inbox->cbegin(); it != inbox->cend(); ++it) {+ checkNewMail(it.key(), it.value());+ }+ if (generation != m_generation) {+ return;+ }+ m_messageModel->reset(*rows);+ });+}++// A message in the Inbox that wasn't there the last time Mail looked, and+// is unread, gets a notification. The first look after start-up only+// learns what is there.+void MailEngine::checkNewMail(const QString &accountId, const QList<MessageRow> &inboxRows)+{+ if (!m_live.contains(accountId)) {+ return;+ }+ Live &live = m_live[accountId];+ QSet<QString> now;+ for (const MessageRow &r : inboxRows) {+ now.insert(r.uid);+ if (live.inboxPrimed && r.unread && !live.knownInboxUids.contains(r.uid)+ && r.date > QDateTime::currentDateTime().addDays(-1)) {+ Q_EMIT newMail(r.key(), r.fromName, r.subject, r.preview);+ }+ }+ live.knownInboxUids.unite(now);+ live.inboxPrimed = live.connected || live.inboxPrimed;+}++void MailEngine::refresh()+{+ if (!m_online) {+ return;+ }+ for (auto it = m_live.cbegin(); it != m_live.cend(); ++it) {+ if (!it->connected) {+ if (!Session::instance().password(it.key()).isEmpty()) {+ connectAccount(it.key());+ }+ continue;+ }+ CamelStore *store = it->store;+ g_object_ref(store);+ run([store]() {+ // Asks for each folder's counts; Camel fetches new mail for the+ // folders it has open.+ CamelFolderInfo *fi = camel_store_get_folder_info_sync(store, nullptr,+ CamelStoreGetFolderInfoFlags(CAMEL_STORE_FOLDER_INFO_RECURSIVE | CAMEL_STORE_FOLDER_INFO_REFRESH),+ nullptr, nullptr);+ if (fi) {+ camel_folder_info_free(fi);+ }+ g_object_unref(store);+ });+ }+ for (const auto &[account, full] : currentFolders()) {+ const QString a = account;+ const QString f = full;+ run([this, a, f]() {+ if (CamelFolder *folder = folderSync(a, f, nullptr)) {+ camel_folder_refresh_info_sync(folder, nullptr, nullptr);+ }+ });+ }+ sendOutbox();+}++bool MailEngine::splitKey(const QString &key, QString *accountId, QString *folder, QString *uid)+{+ const QStringList parts = key.split(keySep);+ if (parts.size() != 3) {+ return false;+ }+ *accountId = parts[0];+ *folder = parts[1];+ *uid = parts[2];+ return true;+}++QString MailEngine::accountForKey(const QString &key) const+{+ return key.section(keySep, 0, 0);+}++void MailEngine::setFlags(const QString &key, guint32 mask, guint32 set)+{+ QString accountId, full, uid;+ if (!splitKey(key, &accountId, &full, &uid)) {+ return;+ }+ run([this, accountId, full, uid, mask, set]() {+ CamelFolder *folder = folderSync(accountId, full, nullptr);+ if (!folder) {+ return;+ }+ camel_folder_set_message_flags(folder, uid.toUtf8().constData(), mask, set);+ // Sent to the server now if online, or the next time it is.+ camel_folder_synchronize_sync(folder, FALSE, nullptr, nullptr);+ });+}++void MailEngine::setRead(const QString &key, bool read)+{+ m_messageModel->updateRow(key, [read](MessageRow &r) {+ r.unread = !read;+ });+ setFlags(key, CAMEL_MESSAGE_SEEN, read ? CAMEL_MESSAGE_SEEN : 0);+}++void MailEngine::toggleRead(const QString &key)+{+ if (const MessageRow *r = m_messageModel->row(key)) {+ setRead(key, r->unread);+ }+}++void MailEngine::toggleFlag(const QString &key)+{+ if (const MessageRow *r = m_messageModel->row(key)) {+ setFlaggedKeys({key}, !r->flagged);+ }+}++void MailEngine::togglePin(const QString &key)+{+ QString accountId, full, uid;+ const MessageRow *r = m_messageModel->row(key);+ if (!r || !splitKey(key, &accountId, &full, &uid)) {+ return;+ }+ const bool pin = !r->pinned;+ m_messageModel->updateRow(key, [pin](MessageRow &r) {+ r.pinned = pin;+ });+ run([this, accountId, full, uid, pin]() {+ if (CamelFolder *folder = folderSync(accountId, full, nullptr)) {+ if (CamelMessageInfo *mi = camel_folder_get_message_info(folder, uid.toUtf8().constData())) {+ camel_message_info_set_user_flag(mi, "wildos-pinned", pin);+ g_object_unref(mi);+ }+ }+ });+}++void MailEngine::snooze(const QString &key, const QDateTime &until)+{+ QString accountId, full, uid;+ if (!splitKey(key, &accountId, &full, &uid)) {+ return;+ }+ const QString next = m_messageModel->neighbour(key);+ const QByteArray when = until.toString(Qt::ISODate).toUtf8();+ run([this, accountId, full, uid, when]() {+ if (CamelFolder *folder = folderSync(accountId, full, nullptr)) {+ if (CamelMessageInfo *mi = camel_folder_get_message_info(folder, uid.toUtf8().constData())) {+ camel_message_info_set_user_tag(mi, "wildos-snooze", when.constData());+ // It comes back unread.+ camel_message_info_set_flags(mi, CAMEL_MESSAGE_SEEN, 0);+ g_object_unref(mi);+ }+ }+ }, [this]() {+ reloadMessages();+ });+ select(next);+}++// Moves happen in the list at once; the server is told in the background.+// What was moved is remembered so Undo can put it back.+void MailEngine::transfer(const QStringList &keys, const QString &targetRole, const QString &targetFullName, bool junkFlag)+{+ struct Item {+ QString accountId, full, uid, target;+ bool permanent = false;+ };+ QList<Item> items;+ for (const QString &key : keys) {+ Item item;+ if (!splitKey(key, &item.accountId, &item.full, &item.uid) || item.full == QLatin1String(".outbox")) {+ continue;+ }+ item.target = targetFullName.isEmpty() ? roleFullName(item.accountId, targetRole) : targetFullName;+ item.permanent = targetRole == QLatin1String("trash") && (item.target.isEmpty() || item.target == item.full);+ if (item.target.isEmpty() && targetRole == QLatin1String("archive")) {+ // No Archive folder on this server yet: make one, as Outlook does.+ item.target = QStringLiteral("Archive");+ }+ if (item.target.isEmpty() && !item.permanent) {+ Q_EMIT notice(tr("This account has no folder for that."));+ return;+ }+ if (!item.permanent && item.target == item.full) {+ continue;+ }+ items.append(item);+ }+ if (items.isEmpty()) {+ return;+ }++ QStringList moved;+ for (const Item &item : items) {+ moved << item.accountId + keySep + item.full + keySep + item.uid;+ }+ // The selection moves on to the next message left in the list.+ QString next;+ for (const QString &key : moved) {+ const QString candidate = m_messageModel->neighbour(key);+ if (!moved.contains(candidate)) {+ next = candidate;+ }+ }+ m_messageModel->removeKeys(moved);+ select(next);++ const int count = items.size();+ const bool permanentAll = std::all_of(items.cbegin(), items.cend(), [](const Item &i) {+ return i.permanent;+ });+ const QString what = count == 1 ? tr("1 message") : tr("%1 messages").arg(count);+ const QString label = permanentAll ? tr("Deleted %1 for good").arg(what)+ : targetRole == QLatin1String("archive") ? tr("Archived %1").arg(what)+ : targetRole == QLatin1String("trash") ? tr("Deleted %1").arg(what)+ : targetRole == QLatin1String("junk") ? tr("Moved %1 to Junk email").arg(what)+ : targetRole == QLatin1String("inbox") ? tr("Moved %1 to the Inbox").arg(what)+ : tr("Moved %1").arg(what);+ if (permanentAll) {+ Q_EMIT notice(label);+ } else {+ Q_EMIT undoable(label);+ }++ auto error = std::make_shared<QString>();+ auto done = std::make_shared<QList<Moved>>();+ run([this, items, junkFlag, error, done]() {+ // One server request per folder, not one per message.+ QMap<QPair<QString, QString>, QList<Item>> groups;+ for (const Item &item : items) {+ groups[{item.accountId, item.full}].append(item);+ }+ for (auto it = groups.cbegin(); it != groups.cend(); ++it) {+ GError *gerror = nullptr;+ const QString accountId = it.key().first;+ CamelFolder *source = folderSync(accountId, it.key().second, &gerror);+ if (!source) {+ *error = errorText(gerror);+ g_clear_error(&gerror);+ continue;+ }+ QMap<QString, QList<Item>> byTarget;+ for (const Item &item : it.value()) {+ if (item.permanent) {+ camel_folder_set_message_flags(source, item.uid.toUtf8().constData(), CAMEL_MESSAGE_DELETED | CAMEL_MESSAGE_SEEN,+ CAMEL_MESSAGE_DELETED | CAMEL_MESSAGE_SEEN);+ } else {+ byTarget[item.target].append(item);+ }+ }+ for (auto t = byTarget.cbegin(); t != byTarget.cend(); ++t) {+ CamelFolder *dest = folderSync(accountId, t.key(), &gerror);+ if (!dest && t.key() == QLatin1String("Archive")) {+ g_clear_error(&gerror);+ if (CamelFolderInfo *fi = camel_store_create_folder_sync(camel_folder_get_parent_store(source), nullptr, "Archive", nullptr, &gerror)) {+ camel_folder_info_free(fi);+ dest = folderSync(accountId, t.key(), &gerror);+ }+ }+ if (!dest) {+ *error = errorText(gerror);+ g_clear_error(&gerror);+ continue;+ }+ GPtrArray *uids = g_ptr_array_new();+ QList<QByteArray> keep;+ for (const Item &item : t.value()) {+ keep << item.uid.toUtf8();+ }+ for (QByteArray &u : keep) {+ camel_folder_set_message_flags(source, u.constData(), CAMEL_MESSAGE_JUNK | CAMEL_MESSAGE_NOTJUNK, junkFlag ? CAMEL_MESSAGE_JUNK : 0);+ g_ptr_array_add(uids, u.data());+ }+ GPtrArray *newUids = nullptr;+ if (!camel_folder_transfer_messages_to_sync(source, uids, dest, TRUE, &newUids, nullptr, &gerror)) {+ *error = errorText(gerror);+ g_clear_error(&gerror);+ } else if (newUids) {+ for (guint i = 0; i < newUids->len; ++i) {+ const char *n = static_cast<const char *>(newUids->pdata[i]);+ if (n && *n) {+ done->append({accountId, it.key().second, t.key(), QString::fromUtf8(n)});+ }+ }+ }+ if (newUids) {+ g_ptr_array_set_free_func(newUids, g_free);+ g_ptr_array_free(newUids, TRUE);+ }+ g_ptr_array_free(uids, TRUE);+ }+ camel_folder_synchronize_sync(source, TRUE, nullptr, nullptr);+ }+ }, [this, error, done]() {+ if (!error->isEmpty()) {+ Q_EMIT notice(*error);+ }+ m_undo = *done;+ Q_EMIT undoChanged();+ reloadMessages();+ });+}++void MailEngine::undo()+{+ if (m_undo.isEmpty()) {+ return;+ }+ const QList<Moved> moves = m_undo;+ m_undo.clear();+ Q_EMIT undoChanged();+ auto error = std::make_shared<QString>();+ run([this, moves, error]() {+ for (const Moved &m : moves) {+ GError *gerror = nullptr;+ CamelFolder *from = folderSync(m.accountId, m.to, &gerror);+ CamelFolder *back = from ? folderSync(m.accountId, m.from, &gerror) : nullptr;+ if (!from || !back) {+ *error = errorText(gerror);+ g_clear_error(&gerror);+ continue;+ }+ camel_folder_refresh_info_sync(from, nullptr, nullptr);+ GPtrArray *uids = g_ptr_array_new();+ QByteArray u = m.uid.toUtf8();+ g_ptr_array_add(uids, u.data());+ camel_folder_set_message_flags(from, u.constData(), CAMEL_MESSAGE_JUNK, 0);+ if (!camel_folder_transfer_messages_to_sync(from, uids, back, TRUE, nullptr, nullptr, &gerror)) {+ *error = errorText(gerror);+ g_clear_error(&gerror);+ }+ g_ptr_array_free(uids, TRUE);+ camel_folder_synchronize_sync(from, TRUE, nullptr, nullptr);+ }+ }, [this, error]() {+ Q_EMIT notice(error->isEmpty() ? tr("Put back") : *error);+ reloadMessages();+ });+}++void MailEngine::remove(const QString &key)+{+ removeKeys({key});+}++void MailEngine::archive(const QString &key)+{+ archiveKeys({key});+}++void MailEngine::reportJunk(const QString &key)+{+ junkKeys({key});+}++void MailEngine::notJunk(const QString &key)+{+ transfer({key}, QStringLiteral("inbox"), {}, false);+}++void MailEngine::moveTo(const QString &key, const QString &fullName)+{+ moveKeys({key}, fullName);+}++void MailEngine::removeKeys(const QStringList &keys)+{+ transfer(keys, QStringLiteral("trash"), {}, false);+}++void MailEngine::archiveKeys(const QStringList &keys)+{+ transfer(keys, QStringLiteral("archive"), {}, false);+}++void MailEngine::junkKeys(const QStringList &keys)+{+ transfer(keys, QStringLiteral("junk"), {}, true);+}++void MailEngine::moveKeys(const QStringList &keys, const QString &fullName)+{+ transfer(keys, QStringLiteral("folder"), fullName, false);+}++void MailEngine::setReadKeys(const QStringList &keys, bool read)+{+ for (const QString &key : keys) {+ setRead(key, read);+ }+}++void MailEngine::setFlaggedKeys(const QStringList &keys, bool flagged)+{+ for (const QString &key : keys) {+ m_messageModel->updateRow(key, [flagged](MessageRow &r) {+ r.flagged = flagged;+ });+ setFlags(key, CAMEL_MESSAGE_FLAGGED, flagged ? CAMEL_MESSAGE_FLAGGED : 0);+ }+}++void MailEngine::toggleSelect(const QString &key)+{+ if (m_selection.contains(key)) {+ m_selection.removeAll(key);+ if (m_selected == key) {+ m_selected = m_selection.isEmpty() ? QString() : m_selection.last();+ }+ } else {+ m_selection.append(key);+ m_selected = key;+ }+ m_anchor = key;+ Q_EMIT selectedChanged();+}++void MailEngine::extendSelect(const QString &key)+{+ const int from = m_messageModel->indexOf(m_anchor.isEmpty() ? m_selected : m_anchor);+ const int to = m_messageModel->indexOf(key);+ if (from < 0 || to < 0) {+ select(key);+ return;+ }+ m_selection.clear();+ for (int i = qMin(from, to); i <= qMax(from, to); ++i) {+ m_selection.append(m_messageModel->keyAt(i));+ }+ m_selected = key;+ Q_EMIT selectedChanged();+}++void MailEngine::selectAll()+{+ m_selection.clear();+ for (int i = 0; i < m_messageModel->rowCount(); ++i) {+ m_selection.append(m_messageModel->keyAt(i));+ }+ Q_EMIT selectedChanged();+}++void MailEngine::markFolderRead(const QString &accountId, const QString &fullName)+{+ run([this, accountId, fullName]() {+ CamelFolder *folder = folderSync(accountId, fullName, nullptr);+ if (!folder) {+ return;+ }+ GPtrArray *uids = camel_folder_get_uids(folder);+ camel_folder_freeze(folder);+ for (guint i = 0; i < uids->len; ++i) {+ camel_folder_set_message_flags(folder, static_cast<const char *>(uids->pdata[i]), CAMEL_MESSAGE_SEEN, CAMEL_MESSAGE_SEEN);+ }+ camel_folder_thaw(folder);+ camel_folder_free_uids(folder, uids);+ camel_folder_synchronize_sync(folder, FALSE, nullptr, nullptr);+ }, [this]() {+ reloadMessages();+ });+}++void MailEngine::renameFolder(const QString &accountId, const QString &fullName, const QString &name)+{+ if (!m_live.contains(accountId) || name.trimmed().isEmpty() || name.contains(QLatin1Char('/'))) {+ return;+ }+ CamelStore *store = m_live[accountId].store;+ g_object_ref(store);+ const int slash = fullName.lastIndexOf(QLatin1Char('/'));+ const QString target = (slash >= 0 ? fullName.left(slash + 1) : QString()) + name.trimmed();+ auto error = std::make_shared<QString>();+ run([this, store, accountId, fullName, target, error]() {+ {+ // Camel's open folder goes with the old name.+ QMutexLocker lock(&m_folderLock);+ if (CamelFolder *f = m_folderCache.take(accountId + keySep + fullName)) {+ m_watched.remove(f);+ g_object_unref(f);+ }+ }+ GError *gerror = nullptr;+ if (!camel_store_rename_folder_sync(store, fullName.toUtf8().constData(), target.toUtf8().constData(), nullptr, &gerror)) {+ *error = errorText(gerror);+ g_clear_error(&gerror);+ }+ g_object_unref(store);+ }, [this, accountId, fullName, target, error]() {+ if (!error->isEmpty()) {+ Q_EMIT notice(*error);+ } else if (m_folderAccount == accountId && m_folderFullName == fullName) {+ openFolder(accountId, target);+ }+ listFolders(accountId);+ });+}++void MailEngine::deleteFolder(const QString &accountId, const QString &fullName)+{+ if (!m_live.contains(accountId)) {+ return;+ }+ CamelStore *store = m_live[accountId].store;+ g_object_ref(store);+ auto error = std::make_shared<QString>();+ run([this, store, accountId, fullName, error]() {+ {+ QMutexLocker lock(&m_folderLock);+ if (CamelFolder *f = m_folderCache.take(accountId + keySep + fullName)) {+ m_watched.remove(f);+ g_object_unref(f);+ }+ }+ GError *gerror = nullptr;+ if (!camel_store_delete_folder_sync(store, fullName.toUtf8().constData(), nullptr, &gerror)) {+ *error = errorText(gerror);+ g_clear_error(&gerror);+ }+ g_object_unref(store);+ }, [this, accountId, fullName, error]() {+ if (!error->isEmpty()) {+ Q_EMIT notice(*error);+ } else if (m_folderAccount == accountId && m_folderFullName == fullName) {+ openFolder({}, QStringLiteral("inbox"));+ }+ listFolders(accountId);+ });+}++// Deleted items and Junk email: everything in them goes for good.+void MailEngine::emptyFolder(const QString &accountId, const QString &fullName)+{+ if (m_folderAccount == accountId && m_folderFullName == fullName) {+ m_messageModel->reset({});+ }+ run([this, accountId, fullName]() {+ CamelFolder *folder = folderSync(accountId, fullName, nullptr);+ if (!folder) {+ return;+ }+ GPtrArray *uids = camel_folder_get_uids(folder);+ camel_folder_freeze(folder);+ for (guint i = 0; i < uids->len; ++i) {+ camel_folder_set_message_flags(folder, static_cast<const char *>(uids->pdata[i]), CAMEL_MESSAGE_DELETED, CAMEL_MESSAGE_DELETED);+ }+ camel_folder_thaw(folder);+ camel_folder_free_uids(folder, uids);+ camel_folder_synchronize_sync(folder, TRUE, nullptr, nullptr);+ }, [this]() {+ Q_EMIT notice(tr("Emptied"));+ reloadMessages();+ });+}++QVariantList MailEngine::moveTargets(const QString &accountId) const+{+ QVariantList list;+ for (const FolderEntry &f : m_live.value(accountId).folders) {+ list.append(QVariantMap{{QStringLiteral("fullName"), f.fullName},+ {QStringLiteral("name"), f.displayName},+ {QStringLiteral("role"), f.role},+ {QStringLiteral("depth"), f.depth}});+ }+ return list;+}++void MailEngine::createFolder(const QString &accountId, const QString &name)+{+ if (!m_live.contains(accountId) || name.trimmed().isEmpty()) {+ return;+ }+ CamelStore *store = m_live[accountId].store;+ g_object_ref(store);+ auto error = std::make_shared<QString>();+ const QByteArray n = name.trimmed().toUtf8();+ run([store, n, error]() {+ GError *gerror = nullptr;+ if (CamelFolderInfo *fi = camel_store_create_folder_sync(store, nullptr, n.constData(), nullptr, &gerror)) {+ camel_folder_info_free(fi);+ } else {+ *error = errorText(gerror);+ g_clear_error(&gerror);+ }+ g_object_unref(store);+ }, [this, accountId, error]() {+ if (!error->isEmpty()) {+ Q_EMIT notice(*error);+ }+ listFolders(accountId);+ });+}++// Searches the summaries kept on this PC: sender, recipients and subject.+// Camel would send a body search to the server, so Mail doesn't ask for+// one; nothing typed here leaves the PC.+void MailEngine::search(const QString &text)+{+ const QString query = text.trimmed();+ if (query.isEmpty()) {+ clearSearch();+ return;+ }+ const bool started = m_searchText.isEmpty();+ m_searchText = query;+ if (started) {+ m_messageModel->setFilter(QStringLiteral("all"));+ m_selected.clear();+ Q_EMIT selectedChanged();+ }+ Q_EMIT searchChanged();+ Q_EMIT folderChanged();++ QList<QPair<QString, QString>> folders;+ for (const Account &a : m_store.accounts()) {+ for (const FolderEntry &f : m_live.value(a.id).folders) {+ if (f.role != QLatin1String("trash") && f.role != QLatin1String("junk")) {+ folders.append({a.id, f.fullName});+ }+ }+ }+ const int generation = ++m_generation;+ auto rows = std::make_shared<QList<MessageRow>>();+ run([this, folders, query, rows]() {+ QByteArray escaped = query.toUtf8();+ escaped.replace("\\", "\\\\").replace("\"", "\\\"");+ const QByteArray expr = "(match-all (or (header-contains \"subject\" \"" + escaped + "\") (header-contains \"from\" \"" + escaped+ + "\") (header-contains \"to\" \"" + escaped + "\") (header-contains \"cc\" \"" + escaped + "\")))";+ for (const auto &[accountId, full] : folders) {+ CamelFolder *folder = folderSync(accountId, full, nullptr);+ if (!folder) {+ continue;+ }+ GPtrArray *uids = camel_folder_search_by_expression(folder, expr.constData(), nullptr, nullptr);+ if (!uids) {+ continue;+ }+ for (guint i = 0; i < uids->len; ++i) {+ if (CamelMessageInfo *mi = camel_folder_get_message_info(folder, static_cast<const char *>(uids->pdata[i]))) {+ if (!(camel_message_info_get_flags(mi) & CAMEL_MESSAGE_DELETED)) {+ rows->append(rowFrom(accountId, full, mi));+ }+ g_object_unref(mi);+ }+ }+ camel_folder_search_free(folder, uids);+ }+ }, [this, generation, rows]() {+ if (generation == m_generation) {+ m_messageModel->reset(*rows);+ }+ });+}++void MailEngine::clearSearch()+{+ if (m_searchText.isEmpty()) {+ return;+ }+ m_searchText.clear();+ Q_EMIT searchChanged();+ Q_EMIT folderChanged();+ reloadMessages();+}++QVariantMap MailEngine::account(const QString &id) const+{+ const Account *a = m_store.find(id);+ return a ? a->toMap() : QVariantMap();+}++void MailEngine::testAccount(const QVariantMap &settings, const QString &password)+{+ Account account = Account::fromMap(settings);+ const QString testId = QStringLiteral("test-") + AccountStore::newId();+ Session::instance().setPassword(testId, password);+ Session::instance().setOAuth(testId, account.auth == QLatin1String("google"));+ CamelSession *session = Session::instance().camel();+ GError *error = nullptr;+ CamelService *store = camel_session_add_service(session, testId.toUtf8().constData(), "imapx", CAMEL_PROVIDER_STORE, &error);+ QString why = errorText(error);+ g_clear_error(&error);+ CamelService *smtp = camel_session_add_service(session, (testId + QStringLiteral(".smtp")).toUtf8().constData(), "smtp", CAMEL_PROVIDER_TRANSPORT, &error);+ if (why.isEmpty()) {+ why = errorText(error);+ }+ g_clear_error(&error);+ if (!store || !smtp) {+ qCWarning(mailLog) << "couldn't create the mail services:" << why;+ g_clear_object(&store);+ g_clear_object(&smtp);+ Q_EMIT accountTested(false, tr("Mail couldn't start a connection. %1").arg(why));+ return;+ }+ configure(store, smtp, account);+ auto message = std::make_shared<QString>();+ auto ok = std::make_shared<bool>(false);+ // A server that never answers gets 45 seconds, then the person is told,+ // rather than left watching a spinner.+ GCancellable *cancellable = g_cancellable_new();+ g_object_ref(cancellable);+ QTimer::singleShot(45000, this, [cancellable]() {+ g_cancellable_cancel(cancellable);+ g_object_unref(cancellable);+ });+ qCInfo(mailLog) << "testing account" << account.imapHost << account.imapPort << account.imapSecurity << account.smtpHost << account.smtpPort+ << account.smtpSecurity << "sign-in" << account.auth;+ run([store, smtp, message, ok, cancellable]() {+ GError *gerror = nullptr;+ camel_offline_store_set_online_sync(CAMEL_OFFLINE_STORE(store), TRUE, cancellable, nullptr);+ qCInfo(mailLog) << "connecting to incoming server";+ if (!camel_service_connect_sync(store, cancellable, &gerror)) {+ qCWarning(mailLog) << "incoming server:" << errorText(gerror);+ if (g_cancellable_is_cancelled(cancellable)) {+ *message = MailEngine::tr("The incoming mail server didn't answer. Check the server name and port, and that this PC is online.");+ g_clear_error(&gerror);+ return;+ }+ const bool auth = gerror->domain == CAMEL_SERVICE_ERROR && gerror->code == CAMEL_SERVICE_ERROR_CANT_AUTHENTICATE;+ *message = auth ? MailEngine::tr("Your email provider didn't accept that password.") : MailEngine::tr("Couldn't reach the incoming mail server: %1").arg(errorText(gerror));+ g_clear_error(&gerror);+ return;+ }+ qCInfo(mailLog) << "incoming server signed in";+ camel_service_disconnect_sync(store, TRUE, nullptr, nullptr);+ // Picks a sign-in method the outgoing server offers.+ // Google accounts keep XOAUTH2.+ CamelSettings *current = camel_service_ref_settings(smtp);+ gchar *chosen = nullptr;+ g_object_get(current, "auth-mechanism", &chosen, nullptr);+ g_object_unref(current);+ const bool keep = g_strcmp0(chosen, "XOAUTH2") == 0;+ g_free(chosen);+ GList *types = keep ? nullptr : camel_service_query_auth_types_sync(smtp, cancellable, nullptr);+ const char *mechanism = nullptr;+ for (GList *l = types; l; l = l->next) {+ auto *type = static_cast<CamelServiceAuthType *>(l->data);+ if (g_strcmp0(type->authproto, "PLAIN") == 0) {+ mechanism = "PLAIN";+ break;+ }+ if (g_strcmp0(type->authproto, "LOGIN") == 0) {+ mechanism = "LOGIN";+ }+ }+ g_list_free(types);+ if (mechanism) {+ CamelSettings *s = camel_service_ref_settings(smtp);+ g_object_set(s, "auth-mechanism", mechanism, nullptr);+ g_object_unref(s);+ }+ qCInfo(mailLog) << "connecting to outgoing server with" << (mechanism ? mechanism : (keep ? "XOAUTH2" : "default"));+ if (!camel_service_connect_sync(smtp, cancellable, &gerror)) {+ qCWarning(mailLog) << "outgoing server:" << errorText(gerror);+ if (g_cancellable_is_cancelled(cancellable)) {+ *message = MailEngine::tr("The outgoing mail server didn't answer. Check the server name and port, and that this PC is online.");+ g_clear_error(&gerror);+ return;+ }+ const bool auth = gerror->domain == CAMEL_SERVICE_ERROR && gerror->code == CAMEL_SERVICE_ERROR_CANT_AUTHENTICATE;+ *message = auth ? MailEngine::tr("The outgoing mail server didn't accept that password.") : MailEngine::tr("Couldn't reach the outgoing mail server: %1").arg(errorText(gerror));+ g_clear_error(&gerror);+ return;+ }+ camel_service_disconnect_sync(smtp, TRUE, nullptr, nullptr);+ qCInfo(mailLog) << "outgoing server signed in";+ *ok = true;+ }, [this, session, store, smtp, testId, message, ok, cancellable]() {+ g_object_unref(cancellable);+ camel_session_remove_service(session, store);+ camel_session_remove_service(session, smtp);+ Session::instance().setPassword(testId, {});+ Q_EMIT accountTested(*ok, *message);+ });+}++void MailEngine::saveAccount(const QVariantMap &settings, const QString &password)+{+ Account account = Account::fromMap(settings);+ if (account.id.isEmpty()) {+ account.id = AccountStore::newId();+ }+ if (account.name == account.email && m_store.accounts().isEmpty()) {+ account.name = tr("Personal");+ }+ Session::instance().setPassword(account.id, password);+ Session::instance().setOAuth(account.id, account.auth == QLatin1String("google"));+ m_store.writePassword(account.id, password);+ m_store.add(account);+ startAccount(account);+ Session::instance().setPassword(account.id, password);+ connectAccount(account.id);+ rebuildFolderModel();+ if (m_store.accounts().size() == 1) {+ openFolder({}, QStringLiteral("inbox"));+ }+ Q_EMIT accountSaved(account.id);+}++void MailEngine::updateAccount(const QVariantMap &settings)+{+ Account account = Account::fromMap(settings);+ if (!m_store.find(account.id)) {+ return;+ }+ m_store.update(account);+ if (m_live.contains(account.id)) {+ configure(CAMEL_SERVICE(m_live[account.id].store), m_live[account.id].smtp, account);+ }+ rebuildFolderModel();+}++void MailEngine::removeAccount(const QString &id)+{+ stopAccount(id);+ m_store.remove(id);+ // What was kept on this PC for the account goes with it.+ QDir(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QStringLiteral("/") + id).removeRecursively();+ QDir(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QStringLiteral("/") + id).removeRecursively();+ QDir(outboxDir(id)).removeRecursively();+ if (m_folderAccount == id) {+ openFolder({}, QStringLiteral("inbox"));+ } else {+ reloadMessages();+ }+ rebuildFolderModel();+ Q_EMIT problemsChanged();+}++void MailEngine::signInAgain(const QString &id, const QString &password)+{+ Session::instance().setPassword(id, password);+ m_store.writePassword(id, password);+ setProblem(id, {}, {});+ connectAccount(id);+}++void MailEngine::queueOutbox(const QString &accountId, const QByteArray &message)+{+ QDir().mkpath(outboxDir(accountId));+ QFile file(outboxDir(accountId) + QStringLiteral("/") + QUuid::createUuid().toString(QUuid::Id128) + QStringLiteral(".eml"));+ if (file.open(QIODevice::WriteOnly)) {+ file.write(message);+ }+ Q_EMIT outboxChanged();+ rebuildFolderModel();+}++// Sends what waited in the Outbox, oldest first, once the account is+// reachable again.+void MailEngine::sendOutbox()+{+ if (!m_online) {+ return;+ }+ for (const Account &a : m_store.accounts()) {+ const QFileInfoList files = QDir(outboxDir(a.id)).entryInfoList({QStringLiteral("*.eml")}, QDir::Files, QDir::Time | QDir::Reversed);+ if (files.isEmpty() || !m_live.value(a.id).smtp || Session::instance().password(a.id).isEmpty()) {+ continue;+ }+ CamelService *smtp = m_live[a.id].smtp;+ g_object_ref(smtp);+ const QString id = a.id;+ const bool gmail = a.provider == QLatin1String("gmail");+ auto failure = std::make_shared<QString>();+ run([this, smtp, files, id, gmail, failure]() {+ for (const QFileInfo &file : files) {+ CamelMimeMessage *message = camel_mime_message_new();+ CamelStream *stream = camel_stream_fs_new_with_name(file.filePath().toUtf8().constData(), O_RDONLY, 0, nullptr);+ bool sent = false;+ if (stream && camel_data_wrapper_construct_from_stream_sync(CAMEL_DATA_WRAPPER(message), stream, nullptr, nullptr)) {+ CamelAddress *from = CAMEL_ADDRESS(camel_mime_message_get_from(message));+ CamelAddress *recipients = CAMEL_ADDRESS(camel_internet_address_new());+ for (const char *type : {CAMEL_RECIPIENT_TYPE_TO, CAMEL_RECIPIENT_TYPE_CC, CAMEL_RECIPIENT_TYPE_BCC}) {+ if (CamelInternetAddress *list = camel_mime_message_get_recipients(message, type)) {+ camel_address_cat(recipients, CAMEL_ADDRESS(list));+ }+ }+ gboolean saved = FALSE;+ GError *error = nullptr;+ if (camel_service_connect_sync(smtp, nullptr, &error)) {+ sent = camel_transport_send_to_sync(CAMEL_TRANSPORT(smtp), message, from, recipients, &saved, nullptr, &error);+ }+ if (!sent) {+ *failure = errorText(error);+ }+ g_clear_error(&error);+ g_object_unref(recipients);+ if (sent && !gmail && !saved) {+ if (CamelFolder *folder = roleFolderSync(id, QStringLiteral("sent"), nullptr)) {+ CamelMessageInfo *info = camel_message_info_new(nullptr);+ camel_message_info_set_flags(info, CAMEL_MESSAGE_SEEN, CAMEL_MESSAGE_SEEN);+ camel_folder_append_message_sync(folder, message, info, nullptr, nullptr, nullptr);+ g_object_unref(info);+ }+ }+ }+ g_clear_object(&stream);+ g_object_unref(message);+ if (!sent) {+ break;+ }+ QFile::remove(file.filePath());+ }+ g_object_unref(smtp);+ }, [this, failure]() {+ if (!failure->isEmpty()) {+ Q_EMIT notice(tr("Couldn't send yet, so it's waiting in the Outbox. %1").arg(*failure));+ }+ Q_EMIT outboxChanged();+ rebuildFolderModel();+ if (m_folderRole == QLatin1String("outbox")) {+ reloadMessages();+ }+ });+ }+}diff --git a/packages/wildos-mail/src/mailengine.h b/packages/wildos-mail/src/mailengine.hnew file mode 100644index 0000000..dc34fd0--- /dev/null+++ b/packages/wildos-mail/src/mailengine.h@@ -0,0 +1,311 @@+#pragma once++#include <QHash>+#include <QMutex>+#include <QObject>+#include <QPointer>+#include <QSet>+#include <QTimer>+#include <QVariantList>+#include <QtQml/qqmlregistration.h>++#include <camel/camel.h>++#include <functional>++#include "accounts.h"+#include "models.h"++#include <QLoggingCategory>++Q_DECLARE_LOGGING_CATEGORY(mailLog)++class QQmlEngine;+class QJSEngine;++// Everything Mail knows about accounts, folders and messages, on top of+// Camel (evolution-data-server's mail library). Camel's calls block, so they+// run on worker threads; their results come back to the window's thread as+// plain rows for the models.+class MailEngine : public QObject+{+ Q_OBJECT+ QML_ELEMENT+ QML_SINGLETON++ Q_PROPERTY(QVariantList accounts READ accountList NOTIFY accountsChanged)+ Q_PROPERTY(bool hasAccounts READ hasAccounts NOTIFY accountsChanged)+ Q_PROPERTY(FolderModel *folders READ folders CONSTANT)+ Q_PROPERTY(MessageModel *messages READ messages CONSTANT)+ Q_PROPERTY(QString folderTitle READ folderTitle NOTIFY folderChanged)+ Q_PROPERTY(QString folderRole READ folderRole NOTIFY folderChanged)+ Q_PROPERTY(QString folderAccount READ folderAccount NOTIFY folderChanged)+ Q_PROPERTY(QString folderName READ folderName NOTIFY folderChanged)+ Q_PROPERTY(QString selected READ selected WRITE select NOTIFY selectedChanged)+ // Every selected message: one, or several picked with Ctrl and Shift.+ Q_PROPERTY(QStringList selection READ selection NOTIFY selectedChanged)+ Q_PROPERTY(bool canUndo READ canUndo NOTIFY undoChanged)+ Q_PROPERTY(bool online READ online NOTIFY onlineChanged)+ Q_PROPERTY(bool loading READ loading NOTIFY loadingChanged)+ Q_PROPERTY(int trackersThisWeek READ trackersThisWeek NOTIFY trackersChanged)+ Q_PROPERTY(int photosCleaned READ photosCleaned NOTIFY trackersChanged)+ Q_PROPERTY(QVariantList problems READ problems NOTIFY problemsChanged)+ Q_PROPERTY(QString searchText READ searchText NOTIFY searchChanged)+ Q_PROPERTY(bool searching READ searching NOTIFY searchChanged)+ Q_PROPERTY(int outboxCount READ outboxCount NOTIFY outboxChanged)+ Q_PROPERTY(QString syncStatus READ syncStatus NOTIFY syncStatusChanged)+ Q_PROPERTY(bool passwordInWallet READ passwordInWallet CONSTANT)++public:+ static MailEngine *instance();+ static MailEngine *create(QQmlEngine *, QJSEngine *);++ QVariantList accountList() const;+ bool hasAccounts() const+ {+ return !m_store.accounts().isEmpty();+ }+ FolderModel *folders() const+ {+ return m_folderModel;+ }+ MessageModel *messages() const+ {+ return m_messageModel;+ }+ QString folderTitle() const;+ QString folderRole() const+ {+ return m_folderRole;+ }+ QString folderAccount() const+ {+ return m_folderAccount;+ }+ QString folderName() const+ {+ return m_folderFullName;+ }+ QString selected() const+ {+ return m_selected;+ }+ void select(const QString &key);+ QStringList selection() const+ {+ return m_selection;+ }+ bool canUndo() const+ {+ return !m_undo.isEmpty();+ }+ bool online() const+ {+ return m_online;+ }+ bool loading() const+ {+ return m_loading > 0;+ }+ int trackersThisWeek() const;+ QVariantList problems() const;+ QString searchText() const+ {+ return m_searchText;+ }+ bool searching() const+ {+ return !m_searchText.isEmpty();+ }+ int outboxCount() const;+ QString syncStatus() const+ {+ return m_syncStatus;+ }+ bool passwordInWallet() const+ {+ return AccountStore::walletExists();+ }++ // Favourites have no account: openFolder("", "inbox") shows every+ // account's inbox together.+ Q_INVOKABLE void openFolder(const QString &accountId, const QString &fullName);+ Q_INVOKABLE void toggleExpanded(const QString &accountId);+ // Ctrl+click adds or takes away one message; Shift+click takes+ // everything from the last one clicked.+ Q_INVOKABLE void toggleSelect(const QString &key);+ Q_INVOKABLE void extendSelect(const QString &key);+ Q_INVOKABLE void selectAll();++ // The same actions on several messages at once.+ Q_INVOKABLE void removeKeys(const QStringList &keys);+ Q_INVOKABLE void archiveKeys(const QStringList &keys);+ Q_INVOKABLE void junkKeys(const QStringList &keys);+ Q_INVOKABLE void moveKeys(const QStringList &keys, const QString &fullName);+ Q_INVOKABLE void setReadKeys(const QStringList &keys, bool read);+ Q_INVOKABLE void setFlaggedKeys(const QStringList &keys, bool flagged);+ // Puts the last delete, archive or move back.+ Q_INVOKABLE void undo();++ // A folder's right-click menu.+ Q_INVOKABLE void markFolderRead(const QString &accountId, const QString &fullName);+ Q_INVOKABLE void renameFolder(const QString &accountId, const QString &fullName, const QString &name);+ Q_INVOKABLE void deleteFolder(const QString &accountId, const QString &fullName);+ Q_INVOKABLE void emptyFolder(const QString &accountId, const QString &fullName);+ Q_INVOKABLE void refresh();++ Q_INVOKABLE void setRead(const QString &key, bool read);+ Q_INVOKABLE void toggleRead(const QString &key);+ Q_INVOKABLE void toggleFlag(const QString &key);+ Q_INVOKABLE void togglePin(const QString &key);+ Q_INVOKABLE void remove(const QString &key);+ Q_INVOKABLE void archive(const QString &key);+ Q_INVOKABLE void reportJunk(const QString &key);+ Q_INVOKABLE void notJunk(const QString &key);+ Q_INVOKABLE void moveTo(const QString &key, const QString &fullName);+ Q_INVOKABLE void snooze(const QString &key, const QDateTime &until);+ Q_INVOKABLE QVariantList moveTargets(const QString &accountId) const;+ Q_INVOKABLE void createFolder(const QString &accountId, const QString &name);+ Q_INVOKABLE QString accountForKey(const QString &key) const;++ Q_INVOKABLE void search(const QString &text);+ Q_INVOKABLE void clearSearch();++ // Account setup. testAccount connects with the settings given and+ // answers through accountTested; saveAccount keeps an account that+ // passed.+ Q_INVOKABLE void testAccount(const QVariantMap &settings, const QString &password);+ Q_INVOKABLE void saveAccount(const QVariantMap &settings, const QString &password);+ Q_INVOKABLE void updateAccount(const QVariantMap &settings);+ Q_INVOKABLE void removeAccount(const QString &id);+ Q_INVOKABLE void signInAgain(const QString &id, const QString &password);+ Q_INVOKABLE QVariantMap account(const QString &id) const;+ Q_INVOKABLE static QString initialsOf(const QString &name)+ {+ return MessageModel::initials(name);+ }+ // The person's name from their Wild OS account, to start "Your name"+ // with.+ Q_INVOKABLE static QString systemFullName();+ Q_INVOKABLE static int colourOf(const QString &address)+ {+ return MessageModel::colourOf(address);+ }++ // Called by the message view when it keeps trackers out of a message;+ // each message counts once, however often it is opened.+ void countTrackers(int blocked, const QString &messageId);+ int photosCleaned() const;+ void countCleanedPhotos(int photos);++ // For the message view and the composer, on a worker thread.+ CamelFolder *folderSync(const QString &accountId, const QString &fullName, GError **error);+ CamelFolder *roleFolderSync(const QString &accountId, const QString &role, GError **error);+ CamelService *transport(const QString &accountId) const;+ const Account *accountData(const QString &id) const+ {+ return m_store.find(id);+ }+ const MessageRow *row(const QString &key) const+ {+ return m_messageModel->row(key);+ }+ static bool splitKey(const QString &key, QString *accountId, QString *folder, QString *uid);+ QString folderLabel(const QString &accountId, const QString &fullName) const;+ void queueOutbox(const QString &accountId, const QByteArray &message);+ void sendOutbox();++ // Runs work on a worker thread, then done on this one.+ void run(std::function<void()> work, std::function<void()> done = {});++Q_SIGNALS:+ void accountsChanged();+ void folderChanged();+ void selectedChanged();+ void onlineChanged();+ void loadingChanged();+ void trackersChanged();+ void problemsChanged();+ void searchChanged();+ void outboxChanged();+ void syncStatusChanged();+ void accountTested(bool ok, const QString &message);+ void accountSaved(const QString &id);+ void notice(const QString &text);+ // A notice with Undo.+ void undoable(const QString &text);+ void undoChanged();+ void newMail(const QString &key, const QString &from, const QString &subject, const QString &preview);++private:+ struct Live {+ CamelStore *store = nullptr;+ CamelService *smtp = nullptr;+ QString problem;+ // ok, password or unreachable+ QString problemKind;+ bool connected = false;+ QList<CamelFolderInfo *> infos;+ QList<FolderEntry> folders;+ QSet<QString> knownInboxUids;+ bool inboxPrimed = false;+ // The first folder list after connecting fetches the open folders.+ bool fetchedAfterConnect = false;+ };++ explicit MailEngine(QObject *parent = nullptr);++ void startAccount(const Account &account);+ void stopAccount(const QString &id);+ void connectAccount(const QString &id);+ void configure(CamelService *store, CamelService *smtp, const Account &account) const;+ void listFolders(const QString &id);+ void rebuildFolderModel();+ void reloadMessages();+ void scheduleReload();+ void watchFolder(CamelFolder *folder);+ void watchStore(CamelStore *store);+ QList<QPair<QString, QString>> currentFolders() const;+ void transfer(const QStringList &keys, const QString &targetRole, const QString &targetFullName, bool junkFlag);+ struct Moved {+ QString accountId;+ QString from;+ QString to;+ QString uid;+ };+ QList<Moved> m_undo;+ QStringList m_selection;+ QString m_anchor;+ void setFlags(const QString &key, guint32 mask, guint32 set);+ void setOnline(bool online);+ void setProblem(const QString &id, const QString &kind, const QString &text);+ void setSyncStatus(const QString &status);+ void checkNewMail(const QString &accountId, const QList<MessageRow> &inboxRows);+ QString roleFullName(const QString &accountId, const QString &role) const;++ static void onFolderChanged(CamelFolder *folder, CamelFolderChangeInfo *info, gpointer self);+ static void onStoreChanged(CamelStore *store, gpointer arg, gpointer self);++ AccountStore m_store;+ FolderModel *m_folderModel;+ MessageModel *m_messageModel;+ QHash<QString, Live> m_live;+ QHash<QString, bool> m_expanded;++ mutable QMutex m_folderLock;+ QHash<QString, CamelFolder *> m_folderCache;+ QSet<CamelFolder *> m_watched;++ QString m_folderAccount;+ QString m_folderFullName;+ QString m_folderRole = QStringLiteral("inbox");+ QString m_selected;+ QString m_searchText;+ QString m_syncStatus;+ int m_generation = 0;+ int m_loading = 0;+ bool m_online = true;+ QTimer m_reloadTimer;+ QTimer m_pollTimer;+ QTimer m_snoozeTimer;+};diff --git a/packages/wildos-mail/src/main.cpp b/packages/wildos-mail/src/main.cppnew file mode 100644index 0000000..dcd99a0--- /dev/null+++ b/packages/wildos-mail/src/main.cpp@@ -0,0 +1,331 @@+#include <QCommandLineParser>+#include <QDBusConnection>+#include <QDBusConnectionInterface>+#include <QDBusMessage>+#include <QGuiApplication>+#include <QIcon>+#include <QQmlApplicationEngine>+#include <QQuickWindow>+#include <QUrl>+#include <QUrlQuery>++#include "googlesignin.h"+#include "reminders.h"++#include <QCoreApplication>+#include <QDate>+#include <QFileInfo>+#include <QProcess>++namespace+{+const QString serviceName = QStringLiteral("org.wildos.Mail");+const QString objectPath = QStringLiteral("/Mail");+const QString calendarService = QStringLiteral("org.wildos.Calendar");+const QString calendarPath = QStringLiteral("/Calendar");+const QString remindersService = QStringLiteral("org.wildos.CalendarReminders");++bool registered(const QString &name)+{+ QDBusConnection bus = QDBusConnection::sessionBus();+ return bus.isConnected() && bus.interface()->isServiceRegistered(name);+}++void callOpen(const QString &service, const QString &path, const QString &arg)+{+ auto message = QDBusMessage::createMethodCall(service, path, service, QStringLiteral("open"));+ message << arg;+ QDBusConnection::sessionBus().call(message);+}++void raise(QQmlApplicationEngine *engine)+{+ const auto roots = engine->rootObjects();+ if (auto window = roots.isEmpty() ? nullptr : qobject_cast<QQuickWindow *>(roots.constFirst())) {+ if (window->visibility() == QWindow::Minimized) {+ window->showNormal();+ }+ window->show();+ window->raise();+ window->requestActivate();+ }+}++// mailto:[email protected]?subject=Hi&cc=...&body=... as composer fields.+QVariantMap fromMailto(const QString &arg)+{+ QVariantMap data;+ const QUrl url(arg);+ if (url.scheme() != QLatin1String("mailto")) {+ return data;+ }+ QStringList to = url.path().split(QLatin1Char(','), Qt::SkipEmptyParts);+ const QUrlQuery query(url);+ for (const auto &[key, value] : query.queryItems(QUrl::FullyDecoded)) {+ const QString k = key.toLower();+ if (k == QLatin1String("to")) {+ to << value.split(QLatin1Char(','), Qt::SkipEmptyParts);+ } else if (k == QLatin1String("cc")) {+ data.insert(QStringLiteral("cc"), value.split(QLatin1Char(','), Qt::SkipEmptyParts));+ } else if (k == QLatin1String("subject")) {+ data.insert(QStringLiteral("subject"), value);+ } else if (k == QLatin1String("body")) {+ data.insert(QStringLiteral("body"), value);+ }+ }+ data.insert(QStringLiteral("to"), to);+ return data;+}+}++// Opening Mail again (or a mailto: link) brings the open window forward+// instead of starting a second one.+class Remote : public QObject+{+ Q_OBJECT+ Q_CLASSINFO("D-Bus Interface", "org.wildos.Mail")++public:+ explicit Remote(QQmlApplicationEngine *engine)+ : QObject(engine)+ , m_engine(engine)+ {+ }++public Q_SLOTS:+ Q_SCRIPTABLE void open(const QString &arg)+ {+ const auto roots = m_engine->rootObjects();+ if (roots.isEmpty()) {+ return;+ }+ QObject *root = roots.constFirst();+ // Google sends the browser back here after "Sign in with Google";+ // Mail comes forward only if the sign-in was its own.+ if (GoogleSignIn::isRedirect(arg)) {+ const bool mine = GoogleSignIn::instance()->waiting();+ GoogleSignIn::instance()->handleRedirect(arg);+ if (mine) {+ raise(m_engine);+ }+ return;+ }+ const QVariantMap mailto = fromMailto(arg);+ if (!mailto.isEmpty()) {+ QMetaObject::invokeMethod(root, "compose", Q_ARG(QVariant, mailto));+ }+ raise(m_engine);+ }+ // Calendar's launcher, or a reminder's Open: the Calendar tab, at the+ // event if one is named.+ Q_SCRIPTABLE void showCalendar(const QString &key, const QString &day)+ {+ const auto roots = m_engine->rootObjects();+ if (!roots.isEmpty()) {+ QMetaObject::invokeMethod(roots.constFirst(), "showCalendar", Q_ARG(QVariant, key),+ Q_ARG(QVariant, QVariant::fromValue(QDate::fromString(day, Qt::ISODate))));+ }+ raise(m_engine);+ }++private:+ QQmlApplicationEngine *m_engine;+};++// The same for Calendar: opening it again, or a reminder's Open, which+// names an event and its day.+class CalendarRemote : public QObject+{+ Q_OBJECT+ Q_CLASSINFO("D-Bus Interface", "org.wildos.Calendar")++public:+ explicit CalendarRemote(QQmlApplicationEngine *engine)+ : QObject(engine)+ , m_engine(engine)+ {+ }++public Q_SLOTS:+ Q_SCRIPTABLE void open(const QString &arg)+ {+ if (GoogleSignIn::isRedirect(arg)) {+ if (!GoogleSignIn::instance()->waiting()) {+ return;+ }+ GoogleSignIn::instance()->handleRedirect(arg);+ }+ raise(m_engine);+ }+ Q_SCRIPTABLE void showEvent(const QString &key, const QString &day)+ {+ const auto roots = m_engine->rootObjects();+ if (!roots.isEmpty() && !key.isEmpty()) {+ QMetaObject::invokeMethod(roots.constFirst(), "showEvent", Q_ARG(QVariant, key),+ Q_ARG(QVariant, QVariant::fromValue(QDate::fromString(day, Qt::ISODate))));+ }+ raise(m_engine);+ }++private:+ QQmlApplicationEngine *m_engine;+};++namespace+{+// wildos-calendar --reminders: no window, just the reminders, from sign-in.+int runReminders(int argc, char *argv[])+{+ QCoreApplication app(argc, argv);+ app.setApplicationName(QStringLiteral("wildos-mail"));+ app.setOrganizationDomain(QStringLiteral("wildos.io"));+ if (registered(remindersService)) {+ return 0;+ }+ Reminders reminders;+ if (!reminders.start()) {+ return 1;+ }+ QDBusConnection::sessionBus().registerService(remindersService);+ return app.exec();+}++int runCalendar(int argc, char *argv[])+{+ QGuiApplication app(argc, argv);+ app.setApplicationName(QStringLiteral("wildos-mail"));+ app.setOrganizationDomain(QStringLiteral("wildos.io"));+ app.setApplicationDisplayName(QStringLiteral("Calendar"));+ app.setApplicationVersion(QStringLiteral(WILDOS_MAIL_VERSION));+ app.setDesktopFileName(QStringLiteral("org.wildos.calendar"));+ app.setWindowIcon(QIcon::fromTheme(QStringLiteral("org.wildos.calendar")));++ QCommandLineParser parser;+ parser.setApplicationDescription(QStringLiteral("Wild OS Calendar"));+ parser.addHelpOption();+ parser.addVersionOption();+ const QCommandLineOption event(QStringLiteral("event"), QStringLiteral("An event to open."), QStringLiteral("key"));+ const QCommandLineOption day(QStringLiteral("day"), QStringLiteral("The day it is on, as YYYY-MM-DD."), QStringLiteral("date"));+ parser.addOption(event);+ parser.addOption(day);+ parser.addOption(QCommandLineOption(QStringLiteral("calendar")));+ parser.addOption(QCommandLineOption(QStringLiteral("new-window")));+ parser.process(app);++ if (registered(calendarService)) {+ auto message = QDBusMessage::createMethodCall(calendarService, calendarPath, calendarService, QStringLiteral("showEvent"));+ message << parser.value(event) << parser.value(day);+ QDBusConnection::sessionBus().call(message);+ return 0;+ }++ QQmlApplicationEngine engine;+ QObject::connect(&engine, &QQmlApplicationEngine::objectCreationFailed, &app, []() {+ QCoreApplication::exit(1);+ }, Qt::QueuedConnection);+ engine.loadFromModule("WildOS.Mail", "CalendarMain");++ auto *remote = new CalendarRemote(&engine);+ QDBusConnection bus = QDBusConnection::sessionBus();+ if (bus.isConnected()) {+ bus.registerObject(calendarPath, remote, QDBusConnection::ExportScriptableSlots);+ bus.registerService(calendarService);+ }+ if (parser.isSet(event)) {+ remote->showEvent(parser.value(event), parser.value(day));+ }+ // Reminders start at sign-in; started here too in case that was missed.+ if (!registered(remindersService)) {+ QProcess::startDetached(QCoreApplication::applicationFilePath(), {QStringLiteral("--reminders")});+ }+ return app.exec();+}+}++int main(int argc, char *argv[])+{+ // One program: wildos-calendar is a link to it, and opens Mail's window+ // on its Calendar tab; --new-window gives Calendar a window of its own+ // (the rail's Open in new window), --reminders runs without a window.+ bool calendar = QFileInfo(QString::fromLocal8Bit(argv[0])).fileName() == QLatin1String("wildos-calendar");+ for (int i = 1; i < argc; ++i) {+ if (qstrcmp(argv[i], "--reminders") == 0) {+ return runReminders(argc, argv);+ }+ if (qstrcmp(argv[i], "--new-window") == 0) {+ return runCalendar(argc, argv);+ }+ calendar = calendar || qstrcmp(argv[i], "--calendar") == 0;+ }++ QGuiApplication app(argc, argv);+ app.setApplicationName(QStringLiteral("wildos-mail"));+ app.setOrganizationDomain(QStringLiteral("wildos.io"));+ app.setApplicationDisplayName(QStringLiteral("Mail"));+ app.setApplicationVersion(QStringLiteral(WILDOS_MAIL_VERSION));+ app.setDesktopFileName(QStringLiteral("org.wildos.mail"));+ app.setWindowIcon(QIcon::fromTheme(QStringLiteral("org.wildos.mail")));++ QCommandLineParser parser;+ parser.setApplicationDescription(QStringLiteral("Wild OS Mail"));+ parser.addHelpOption();+ parser.addVersionOption();+ parser.addPositionalArgument(QStringLiteral("mailto"), QStringLiteral("A mailto: link to start a message from."));+ const QCommandLineOption calendarOption(QStringLiteral("calendar"), QStringLiteral("Open on the Calendar tab."));+ const QCommandLineOption event(QStringLiteral("event"), QStringLiteral("An event to open in Calendar."), QStringLiteral("key"));+ const QCommandLineOption day(QStringLiteral("day"), QStringLiteral("The day it is on, as YYYY-MM-DD."), QStringLiteral("date"));+ parser.addOption(calendarOption);+ parser.addOption(event);+ parser.addOption(day);+ parser.process(app);+ const QString arg = parser.positionalArguments().value(0);+ calendar = calendar || parser.isSet(calendarOption) || parser.isSet(event);++ QDBusConnection bus = QDBusConnection::sessionBus();+ // Google's answer to a sign-in goes to whichever of Mail and Calendar+ // started it (each ignores one it didn't), and never opens a window.+ if (GoogleSignIn::isRedirect(arg)) {+ if (registered(serviceName)) {+ callOpen(serviceName, objectPath, arg);+ }+ if (registered(calendarService)) {+ callOpen(calendarService, calendarPath, arg);+ }+ return 0;+ }+ if (registered(serviceName)) {+ if (calendar) {+ auto message = QDBusMessage::createMethodCall(serviceName, objectPath, serviceName, QStringLiteral("showCalendar"));+ message << parser.value(event) << parser.value(day);+ bus.call(message);+ } else {+ callOpen(serviceName, objectPath, arg);+ }+ return 0;+ }++ QQmlApplicationEngine engine;+ QObject::connect(&engine, &QQmlApplicationEngine::objectCreationFailed, &app, []() {+ QCoreApplication::exit(1);+ }, Qt::QueuedConnection);+ engine.loadFromModule("WildOS.Mail", "Main");++ auto *remote = new Remote(&engine);+ if (bus.isConnected()) {+ bus.registerObject(objectPath, remote, QDBusConnection::ExportScriptableSlots);+ bus.registerService(serviceName);+ }+ if (!arg.isEmpty()) {+ remote->open(arg);+ }+ if (calendar) {+ remote->showCalendar(parser.value(event), parser.value(day));+ }+ // Reminders start at sign-in; started here too in case that was missed.+ if (!registered(remindersService)) {+ QProcess::startDetached(QCoreApplication::applicationFilePath(), {QStringLiteral("--reminders")});+ }+ return app.exec();+}++#include "main.moc"diff --git a/packages/wildos-mail/src/messageview.cpp b/packages/wildos-mail/src/messageview.cppnew file mode 100644index 0000000..5c90e54--- /dev/null+++ b/packages/wildos-mail/src/messageview.cpp@@ -0,0 +1,549 @@+#include "messageview.h"+#include "formats.h"++#include <QClipboard>+#include <QDesktopServices>+#include <QGuiApplication>+#include <QDir>+#include <QFile>+#include <QLocale>+#include <QMimeDatabase>+#include <QRegularExpression>+#include <QStandardPaths>+#include <QStringDecoder>+#include <QTextDocumentFragment>+#include <QUrl>++#include <camel/camel.h>++#include "mailengine.h"++namespace+{+QString str(const gchar *s)+{+ return s ? QString::fromUtf8(s) : QString();+}++QByteArray decoded(CamelDataWrapper *wrapper)+{+ GByteArray *bytes = g_byte_array_new();+ CamelStream *stream = camel_stream_mem_new_with_byte_array(bytes);+ camel_data_wrapper_decode_to_stream_sync(wrapper, stream, nullptr, nullptr);+ QByteArray out(reinterpret_cast<const char *>(bytes->data), int(bytes->len));+ g_object_unref(stream);+ return out;+}++QString textOf(CamelMimePart *part)+{+ CamelDataWrapper *content = camel_medium_get_content(CAMEL_MEDIUM(part));+ const QByteArray bytes = decoded(content);+ const char *charset = camel_content_type_param(camel_mime_part_get_content_type(part), "charset");+ QStringDecoder decoder(charset && *charset ? charset : "UTF-8");+ if (!decoder.isValid()) {+ decoder = QStringDecoder(QStringDecoder::Utf8);+ }+ QString text = decoder(bytes);+ if (decoder.hasError() && (!charset || !*charset)) {+ text = QString::fromLatin1(bytes);+ }+ return text;+}++QString formatList(CamelInternetAddress *list, QString *addresses)+{+ QStringList names;+ QStringList addrs;+ if (!list) {+ return {};+ }+ for (int i = 0; i < camel_address_length(CAMEL_ADDRESS(list)); ++i) {+ const gchar *n = nullptr;+ const gchar *a = nullptr;+ camel_internet_address_get(list, i, &n, &a);+ names << (n && *n ? str(n) : str(a));+ if (addresses) {+ addrs << (n && *n ? QStringLiteral("%1 <%2>").arg(str(n), str(a)) : str(a));+ }+ }+ if (addresses) {+ *addresses = addrs.join(QStringLiteral(", "));+ }+ return names.join(QStringLiteral(", "));+}++struct Parsed {+ QString html;+ QString plain;+ // An invitation's iCalendar (text/calendar), wherever it was.+ QString calendar;+ QHash<QString, QByteArray> inlineParts;+ struct Att {+ QString name;+ QString mime;+ QByteArray data;+ };+ QList<Att> attachments;+};++void walk(CamelMimePart *part, Parsed &out)+{+ CamelDataWrapper *content = camel_medium_get_content(CAMEL_MEDIUM(part));+ CamelContentType *type = camel_mime_part_get_content_type(part);+ if (!content) {+ return;+ }+ if (CAMEL_IS_MULTIPART(content)) {+ CamelMultipart *multi = CAMEL_MULTIPART(content);+ const guint count = camel_multipart_get_number(multi);+ if (camel_content_type_is(type, "multipart", "alternative")) {+ // The richest version: HTML (possibly with its pictures in a+ // multipart/related), else the last one.+ CamelMimePart *best = nullptr;+ for (guint i = 0; i < count; ++i) {+ CamelMimePart *child = camel_multipart_get_part(multi, i);+ CamelContentType *ct = camel_mime_part_get_content_type(child);+ if (camel_content_type_is(ct, "text", "html") || camel_content_type_is(ct, "multipart", "related")) {+ best = child;+ }+ if (camel_content_type_is(ct, "text", "plain") && out.plain.isEmpty()) {+ out.plain = textOf(child);+ }+ // Invitations carry the event as one of the versions.+ if (camel_content_type_is(ct, "text", "calendar") && out.calendar.isEmpty()) {+ out.calendar = textOf(child);+ }+ }+ if (!best && count > 0) {+ best = camel_multipart_get_part(multi, count - 1);+ }+ if (best) {+ walk(best, out);+ }+ return;+ }+ for (guint i = 0; i < count; ++i) {+ walk(camel_multipart_get_part(multi, i), out);+ }+ return;+ }++ const char *disposition = camel_mime_part_get_disposition(part);+ const bool attached = disposition && g_ascii_strcasecmp(disposition, "attachment") == 0;+ const QString filename = str(camel_mime_part_get_filename(part));+ const QString contentId = str(camel_mime_part_get_content_id(part));+ gchar *simple = camel_content_type_simple(type);+ const QString mime = str(simple).toLower();+ g_free(simple);++ if ((mime == QLatin1String("text/calendar") || mime == QLatin1String("application/ics")) && out.calendar.isEmpty()) {+ out.calendar = textOf(part);+ if (!attached) {+ return;+ }+ }+ if (!attached && mime == QLatin1String("text/html") && out.html.isEmpty()) {+ out.html = textOf(part);+ return;+ }+ if (!attached && mime == QLatin1String("text/plain") && filename.isEmpty() && out.html.isEmpty()) {+ if (out.plain.isEmpty()) {+ out.plain = textOf(part);+ } else {+ out.plain += QStringLiteral("\n\n") + textOf(part);+ }+ return;+ }+ const QByteArray data = decoded(content);+ if (!contentId.isEmpty() && mime.startsWith(QLatin1String("image/"))) {+ out.inlineParts.insert(contentId, data);+ if (!attached) {+ return;+ }+ }+ QString name = filename;+ if (name.isEmpty()) {+ if (CAMEL_IS_MIME_MESSAGE(content)) {+ name = str(camel_mime_message_get_subject(CAMEL_MIME_MESSAGE(content))) + QStringLiteral(".eml");+ } else {+ const QMimeType t = QMimeDatabase().mimeTypeForName(mime);+ name = MessageView::tr("Attachment") + (t.isValid() && !t.preferredSuffix().isEmpty() ? QLatin1Char('.') + t.preferredSuffix() : QString());+ }+ }+ out.attachments.append({name, mime, data});+}++const QRegularExpression &remoteImageRe()+{+ static const QRegularExpression re(QStringLiteral(R"(<img\b[^>]*?\bsrc\s*=\s*["']?(https?://[^"'\s>]+)[^>]*>)"),+ QRegularExpression::CaseInsensitiveOption);+ return re;+}++// What gives a web picture away as a tracker: one or two pixels in size,+// hidden, or an address shaped like the open-tracking services'.+bool trackerTag(const QString &tag, const QString &url)+{+ static const QRegularExpression tiny(QStringLiteral(R"(\b(width|height)\s*=\s*["']?[0-2](px)?["'\s>/])"), QRegularExpression::CaseInsensitiveOption);+ static const QRegularExpression tinyStyle(QStringLiteral(R"((width|height)\s*:\s*[0-2]px|display\s*:\s*none|visibility\s*:\s*hidden)"), QRegularExpression::CaseInsensitiveOption);+ static const QRegularExpression trackUrl(QStringLiteral(R"((/open(\.gif|\.php|\.aspx)?(\?|/|$)|/track(ing)?/|/pixel|/beacon|/wf/open|/e/o/|/o\.gif|mailtrack|list-manage\.com/track|/emimp/|/imp\?))"),+ QRegularExpression::CaseInsensitiveOption);+ return tiny.match(tag).hasMatch() || tinyStyle.match(tag).hasMatch() || trackUrl.match(url).hasMatch();+}++QString stripActive(QString html)+{+ static const QRegularExpression blocks(QStringLiteral(R"(<(script|iframe|object|embed|frameset|applet)\b.*?</\1\s*>)"),+ QRegularExpression::CaseInsensitiveOption | QRegularExpression::DotMatchesEverythingOption);+ static const QRegularExpression singles(QStringLiteral(R"(<(script|iframe|object|embed|link|meta|base)\b[^>]*>)"), QRegularExpression::CaseInsensitiveOption);+ html.remove(blocks);+ html.remove(singles);+ return html;+}++// Mail that sets its own colours or lays itself out in tables was designed+// on white, so it is shown on white.+bool designedOnWhite(const QString &html)+{+ static const QRegularExpression styled(QStringLiteral(R"(bgcolor|background|<table|[^-]color\s*[:=])"), QRegularExpression::CaseInsensitiveOption);+ return styled.match(html).hasMatch();+}+}++MessageView::MessageView(QObject *parent)+ : QObject(parent)+{+}++void MessageView::setKey(const QString &key)+{+ if (key == m_key) {+ return;+ }+ m_key = key;+ m_showPictures = false;+ Q_EMIT keyChanged();+ Q_EMIT showPicturesChanged();+ load();+}++void MessageView::setShowPictures(bool show)+{+ if (show != m_showPictures) {+ m_showPictures = show;+ Q_EMIT showPicturesChanged();+ }+}++QString MessageView::date() const+{+ if (!m_date.isValid()) {+ return {};+ }+ return Formats::names().dayName(m_date.date().dayOfWeek(), QLocale::ShortFormat) + QLatin1Char(' ') + Formats::shortDate(m_date.date())+ + QLatin1Char(' ') + Formats::time(m_date);+}++void MessageView::load()+{+ const int generation = ++m_generation;+ m_attachments.clear();+ m_calendar.clear();+ m_attachmentData.clear();+ m_inline.clear();+ m_trackerUrls.clear();+ m_html.clear();+ m_plain.clear();+ m_error.clear();+ m_remoteImages = 0;+ m_trackers = 0;+ if (m_key.isEmpty()) {+ m_loading = false;+ Q_EMIT loaded();+ return;+ }+ m_loading = true;+ Q_EMIT loaded();++ QString accountId, folderName, uid;+ MailEngine *engine = MailEngine::instance();+ if (!MailEngine::splitKey(m_key, &accountId, &folderName, &uid)) {+ return;+ }+ if (const Account *a = engine->accountData(accountId)) {+ m_accountName = engine->accountList().size() > 1 ? a->name : QString();+ }++ struct Result {+ QString error;+ QString subject, fromName, fromAddress, replyTo, to, cc, toAddresses, ccAddresses, messageId, references;+ QDateTime date;+ Parsed parsed;+ };+ auto result = std::make_shared<Result>();+ const bool outbox = folderName == QLatin1String(".outbox");+ engine->run([engine, accountId, folderName, uid, result, outbox]() {+ GError *error = nullptr;+ CamelMimeMessage *message = nullptr;+ if (outbox) {+ message = camel_mime_message_new();+ const QString path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QStringLiteral("/outbox/") + accountId + QLatin1Char('/') + uid;+ CamelStream *stream = camel_stream_fs_new_with_name(path.toUtf8().constData(), O_RDONLY, 0, &error);+ if (!stream || !camel_data_wrapper_construct_from_stream_sync(CAMEL_DATA_WRAPPER(message), stream, nullptr, &error)) {+ g_clear_object(&message);+ }+ g_clear_object(&stream);+ } else if (CamelFolder *folder = engine->folderSync(accountId, folderName, &error)) {+ message = camel_folder_get_message_sync(folder, uid.toUtf8().constData(), nullptr, &error);+ }+ if (!message) {+ result->error = error ? str(error->message) : MessageView::tr("This message couldn't be opened.");+ g_clear_error(&error);+ return;+ }+ result->subject = str(camel_mime_message_get_subject(message));+ CamelInternetAddress *from = camel_mime_message_get_from(message);+ if (from && camel_address_length(CAMEL_ADDRESS(from)) > 0) {+ const gchar *n = nullptr;+ const gchar *a = nullptr;+ camel_internet_address_get(from, 0, &n, &a);+ result->fromName = str(n).isEmpty() ? str(a) : str(n);+ result->fromAddress = str(a);+ }+ if (CamelInternetAddress *replyTo = camel_mime_message_get_reply_to(message); replyTo && camel_address_length(CAMEL_ADDRESS(replyTo)) > 0) {+ formatList(replyTo, &result->replyTo);+ }+ result->to = formatList(camel_mime_message_get_recipients(message, CAMEL_RECIPIENT_TYPE_TO), &result->toAddresses);+ result->cc = formatList(camel_mime_message_get_recipients(message, CAMEL_RECIPIENT_TYPE_CC), &result->ccAddresses);+ result->messageId = str(camel_mime_message_get_message_id(message));+ result->references = str(camel_medium_get_header(CAMEL_MEDIUM(message), "References"));+ gint offset = 0;+ const gint64 when = camel_mime_message_get_date(message, &offset);+ result->date = when > 0 ? QDateTime::fromSecsSinceEpoch(when) : QDateTime();+ walk(CAMEL_MIME_PART(message), result->parsed);+ g_object_unref(message);+ }, [this, generation, result]() {+ if (generation != m_generation) {+ return;+ }+ m_loading = false;+ m_error = result->error;+ m_subject = result->subject;+ m_fromName = result->fromName;+ m_fromAddress = result->fromAddress;+ m_replyTo = result->replyTo;+ m_to = result->to;+ m_cc = result->cc;+ m_toAddresses = result->toAddresses;+ m_ccAddresses = result->ccAddresses;+ m_messageId = result->messageId;+ m_references = result->references;+ m_date = result->date;+ m_inline = result->parsed.inlineParts;++ const Parsed &p = result->parsed;+ m_calendar = p.calendar;+ if (!p.html.isEmpty()) {+ m_html = stripActive(p.html);+ m_paper = designedOnWhite(m_html);+ m_plain = p.plain.isEmpty() ? QTextDocumentFragment::fromHtml(m_html).toPlainText() : p.plain;+ } else {+ m_plain = p.plain;+ m_html = plainToHtml(p.plain);+ m_paper = false;+ }+ auto it = remoteImageRe().globalMatch(m_html);+ while (it.hasNext()) {+ const auto m = it.next();+ ++m_remoteImages;+ if (trackerTag(m.captured(0), m.captured(1))) {+ m_trackerUrls.insert(m.captured(1));+ }+ }+ m_trackers = m_trackerUrls.size();+ MailEngine::instance()->countTrackers(m_trackers, m_messageId.isEmpty() ? m_key : m_messageId);++ for (int i = 0; i < p.attachments.size(); ++i) {+ const auto &a = p.attachments[i];+ m_attachmentData.append({a.name, a.mime, a.data});+ m_attachments.append(QVariantMap{{QStringLiteral("name"), a.name},+ {QStringLiteral("size"), QLocale().formattedDataSize(a.data.size(), 0, QLocale::DataSizeTraditionalFormat)},+ {QStringLiteral("type"), a.mime},+ {QStringLiteral("index"), i}});+ }+ Q_EMIT loaded();+ });+}++QImage MessageView::inlineImage(const QString &src) const+{+ if (src.startsWith(QLatin1String("cid:"), Qt::CaseInsensitive)) {+ const QString id = src.mid(4);+ auto it = m_inline.constFind(id);+ if (it == m_inline.cend()) {+ it = m_inline.constFind(QUrl::fromPercentEncoding(id.toUtf8()));+ }+ return it == m_inline.cend() ? QImage() : QImage::fromData(it.value());+ }+ if (src.startsWith(QLatin1String("data:image/"), Qt::CaseInsensitive)) {+ const int comma = src.indexOf(QLatin1Char(','));+ if (comma > 0 && src.left(comma).endsWith(QLatin1String(";base64"), Qt::CaseInsensitive)) {+ return QImage::fromData(QByteArray::fromBase64(src.mid(comma + 1).toLatin1()));+ }+ }+ return {};+}++QString MessageView::writeAttachment(int index, const QString &dir) const+{+ if (index < 0 || index >= m_attachmentData.size()) {+ return {};+ }+ const Attachment &a = m_attachmentData[index];+ QString name = QFileInfo(a.name).fileName();+ name.replace(QLatin1Char('/'), QLatin1Char('_'));+ if (name.isEmpty()) {+ name = tr("Attachment");+ }+ QDir().mkpath(dir);+ QString path = dir + QLatin1Char('/') + name;+ const QFileInfo info(path);+ for (int n = 2; QFile::exists(path); ++n) {+ path = dir + QLatin1Char('/') + info.completeBaseName() + QStringLiteral(" (%1)").arg(n)+ + (info.suffix().isEmpty() ? QString() : QLatin1Char('.') + info.suffix());+ }+ QFile file(path);+ if (!file.open(QIODevice::WriteOnly)) {+ return {};+ }+ file.write(a.data);+ return path;+}++void MessageView::openAttachment(int index)+{+ // Opened from a private folder only this user can read, so another+ // account on the PC can't pick it up.+ const QString dir = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QStringLiteral("/open");+ const QString path = writeAttachment(index, dir);+ if (!path.isEmpty()) {+ QFile::setPermissions(dir, QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ExeOwner);+ QDesktopServices::openUrl(QUrl::fromLocalFile(path));+ }+}++void MessageView::saveAttachment(int index)+{+ const QString path = writeAttachment(index, QStandardPaths::writableLocation(QStandardPaths::DownloadLocation));+ if (!path.isEmpty()) {+ Q_EMIT attachmentSaved(path);+ }+}++void MessageView::saveAllAttachments()+{+ QString last;+ for (int i = 0; i < m_attachmentData.size(); ++i) {+ last = writeAttachment(i, QStandardPaths::writableLocation(QStandardPaths::DownloadLocation));+ }+ if (!last.isEmpty()) {+ Q_EMIT attachmentSaved(QFileInfo(last).absolutePath());+ }+}++QVariantMap MessageView::replyData(const QString &mode) const+{+ QString accountId, folder, uid;+ MailEngine::splitKey(m_key, &accountId, &folder, &uid);+ const Account *account = MailEngine::instance()->accountData(accountId);+ const QString self = account ? account->email.toLower() : QString();++ QVariantMap data;+ data.insert(QStringLiteral("accountId"), accountId);+ QString subject = m_subject;+ static const QRegularExpression prefix(QStringLiteral(R"(^\s*(re|fw|fwd|aw|sv|antw)\s*:\s*)"), QRegularExpression::CaseInsensitiveOption);+ if (mode == QLatin1String("forward")) {+ if (!subject.contains(QRegularExpression(QStringLiteral(R"(^\s*(fw|fwd)\s*:)"), QRegularExpression::CaseInsensitiveOption))) {+ subject = QStringLiteral("Fw: ") + subject;+ }+ } else if (!prefix.match(subject).hasMatch()) {+ subject = QStringLiteral("Re: ") + subject;+ }+ data.insert(QStringLiteral("subject"), subject);++ if (mode != QLatin1String("forward")) {+ const QString sender = m_replyTo.isEmpty() ? (m_fromName.isEmpty() || m_fromName == m_fromAddress ? m_fromAddress : QStringLiteral("%1 <%2>").arg(m_fromName, m_fromAddress)) : m_replyTo;+ QStringList to{sender};+ QStringList cc;+ if (mode == QLatin1String("replyAll")) {+ for (const QString &a : m_toAddresses.split(QStringLiteral(", "), Qt::SkipEmptyParts)) {+ if (!a.toLower().contains(self) && !a.toLower().contains(m_fromAddress.toLower())) {+ to << a;+ }+ }+ for (const QString &a : m_ccAddresses.split(QStringLiteral(", "), Qt::SkipEmptyParts)) {+ if (!a.toLower().contains(self)) {+ cc << a;+ }+ }+ }+ data.insert(QStringLiteral("to"), to);+ data.insert(QStringLiteral("cc"), cc);+ data.insert(QStringLiteral("inReplyTo"), m_messageId);+ data.insert(QStringLiteral("references"), (m_references + QLatin1Char(' ') + QLatin1Char('<') + m_messageId + QLatin1Char('>')).trimmed());+ }+ const QString when = date();+ const QString header = mode == QLatin1String("forward")+ ? tr("From: %1\nSent: %2\nTo: %3\nSubject: %4").arg(m_fromName.isEmpty() ? m_fromAddress : QStringLiteral("%1 <%2>").arg(m_fromName, m_fromAddress), when, m_to, m_subject)+ : tr("On %1, %2 wrote:").arg(when, m_fromName.isEmpty() ? m_fromAddress : m_fromName);+ data.insert(QStringLiteral("quoteHeader"), header);+ data.insert(QStringLiteral("quote"), m_plain.trimmed());+ if (mode == QLatin1String("forward")) {+ data.insert(QStringLiteral("forwardKey"), m_key);+ }+ return data;+}++void MessageView::copyText() const+{+ copyToClipboard(m_plain);+}++void MessageView::copyToClipboard(const QString &text)+{+ QGuiApplication::clipboard()->setText(text);+}++QString MessageView::plainToHtml(const QString &text)+{+ static const QRegularExpression url(QStringLiteral(R"((https?://[^\s<>"]+[^\s<>".,;:!?)\]]))"));+ QString out;+ bool inQuote = false;+ const QStringList lines = text.split(QLatin1Char('\n'));+ for (QString line : lines) {+ if (line.endsWith(QLatin1Char('\r'))) {+ line.chop(1);+ }+ const bool quoted = line.startsWith(QLatin1Char('>'));+ if (quoted && !inQuote) {+ out += QStringLiteral("<blockquote>");+ } else if (!quoted && inQuote) {+ out += QStringLiteral("</blockquote>");+ }+ inQuote = quoted;+ if (quoted) {+ line = line.mid(1);+ if (line.startsWith(QLatin1Char(' '))) {+ line = line.mid(1);+ }+ }+ QString escaped = line.toHtmlEscaped();+ escaped.replace(url, QStringLiteral(R"(<a href="\1">\1</a>)"));+ out += escaped + QStringLiteral("<br>");+ }+ if (inQuote) {+ out += QStringLiteral("</blockquote>");+ }+ return QStringLiteral("<div class=\"plain\">") + out + QStringLiteral("</div>");+}diff --git a/packages/wildos-mail/src/messageview.h b/packages/wildos-mail/src/messageview.hnew file mode 100644index 0000000..07abe62--- /dev/null+++ b/packages/wildos-mail/src/messageview.h@@ -0,0 +1,181 @@+#pragma once++#include <QDateTime>+#include <QHash>+#include <QImage>+#include <QSet>+#include <QObject>+#include <QVariantList>+#include <QtQml/qqmlregistration.h>++// The message in the reading pane: who sent it, its body ready for+// HtmlView, its attachments and what was kept out of it. Set key to load a+// message; everything else follows.+class MessageView : public QObject+{+ Q_OBJECT+ QML_ELEMENT++ Q_PROPERTY(QString key READ key WRITE setKey NOTIFY keyChanged)+ Q_PROPERTY(bool loading READ loading NOTIFY loaded)+ Q_PROPERTY(QString error READ error NOTIFY loaded)+ Q_PROPERTY(QString subject READ subject NOTIFY loaded)+ Q_PROPERTY(QString fromName READ fromName NOTIFY loaded)+ Q_PROPERTY(QString fromAddress READ fromAddress NOTIFY loaded)+ Q_PROPERTY(QString to READ to NOTIFY loaded)+ Q_PROPERTY(QString cc READ cc NOTIFY loaded)+ Q_PROPERTY(QString date READ date NOTIFY loaded)+ Q_PROPERTY(QString accountName READ accountName NOTIFY loaded)+ Q_PROPERTY(QString html READ html NOTIFY loaded)+ // Mail with its own colours and layout is shown on white paper, as it+ // was designed; plain and simple mail takes the window's colours.+ Q_PROPERTY(bool paper READ paper NOTIFY loaded)+ Q_PROPERTY(int remoteImages READ remoteImages NOTIFY loaded)+ Q_PROPERTY(int trackers READ trackers NOTIFY loaded)+ Q_PROPERTY(bool showPictures READ showPictures WRITE setShowPictures NOTIFY showPicturesChanged)+ Q_PROPERTY(QVariantList attachments READ attachments NOTIFY loaded)+ Q_PROPERTY(QString plainText READ plainText NOTIFY loaded)+ // The event in an invitation, as iCalendar text; empty for other mail.+ Q_PROPERTY(QString calendarData READ calendarData NOTIFY loaded)++public:+ explicit MessageView(QObject *parent = nullptr);++ QString key() const+ {+ return m_key;+ }+ void setKey(const QString &key);+ bool loading() const+ {+ return m_loading;+ }+ QString error() const+ {+ return m_error;+ }+ QString subject() const+ {+ return m_subject;+ }+ QString fromName() const+ {+ return m_fromName;+ }+ QString fromAddress() const+ {+ return m_fromAddress;+ }+ QString to() const+ {+ return m_to;+ }+ QString cc() const+ {+ return m_cc;+ }+ QString date() const;+ QString accountName() const+ {+ return m_accountName;+ }+ QString html() const+ {+ return m_html;+ }+ bool paper() const+ {+ return m_paper;+ }+ int remoteImages() const+ {+ return m_remoteImages;+ }+ int trackers() const+ {+ return m_trackers;+ }+ bool showPictures() const+ {+ return m_showPictures;+ }+ void setShowPictures(bool show);+ QVariantList attachments() const+ {+ return m_attachments;+ }+ QString plainText() const+ {+ return m_plain;+ }+ QString calendarData() const+ {+ return m_calendar;+ }++ // An image the message carries itself (cid: or data:), for HtmlView.+ QImage inlineImage(const QString &src) const;+ // Whether a picture from the web looks like a tracker: so small or+ // hidden it can only be there to report the opening.+ bool isTracker(const QString &src) const+ {+ return m_trackerUrls.contains(src);+ }++ Q_INVOKABLE void openAttachment(int index);+ Q_INVOKABLE void saveAttachment(int index);+ Q_INVOKABLE void saveAllAttachments();+ // To, Cc, subject and the quoted text for a reply ("reply", "replyAll")+ // or a forward ("forward").+ Q_INVOKABLE QVariantMap replyData(const QString &mode) const;+ // The message body can't be selected (litehtml draws it), so its text+ // and links are copied whole.+ Q_INVOKABLE void copyText() const;+ Q_INVOKABLE static void copyToClipboard(const QString &text);++ static QString plainToHtml(const QString &text);++Q_SIGNALS:+ void keyChanged();+ void loaded();+ void showPicturesChanged();+ void attachmentSaved(const QString &path);++private:+ struct Attachment {+ QString name;+ QString mimeType;+ QByteArray data;+ };++ void load();+ QString writeAttachment(int index, const QString &dir) const;++ QString m_key;+ bool m_loading = false;+ QString m_error;+ QString m_subject;+ QString m_fromName;+ QString m_fromAddress;+ QString m_replyTo;+ QString m_to;+ QString m_cc;+ QString m_toAddresses;+ QString m_ccAddresses;+ QString m_messageId;+ QString m_references;+ QDateTime m_date;+ QString m_accountName;+ QString m_html;+ QString m_plain;+ QString m_calendar;+ bool m_paper = false;+ int m_remoteImages = 0;+ int m_trackers = 0;+ bool m_showPictures = false;+ QVariantList m_attachments;+ QList<Attachment> m_attachmentData;+ QHash<QString, QByteArray> m_inline;+ QSet<QString> m_trackerUrls;+ int m_generation = 0;+};diff --git a/packages/wildos-mail/src/models.cpp b/packages/wildos-mail/src/models.cppnew file mode 100644index 0000000..2854fda--- /dev/null+++ b/packages/wildos-mail/src/models.cpp@@ -0,0 +1,416 @@+#include "models.h"+#include "formats.h"++#include <QLocale>+#include <QRegularExpression>+#include <QSettings>++#include <algorithm>++int FolderModel::rowCount(const QModelIndex &parent) const+{+ return parent.isValid() ? 0 : m_entries.size();+}++QVariant FolderModel::data(const QModelIndex &index, int role) const+{+ if (!index.isValid() || index.row() >= m_entries.size()) {+ return {};+ }+ const FolderEntry &e = m_entries.at(index.row());+ switch (role) {+ case KindRole:+ return e.kind == FolderEntry::Header ? QStringLiteral("header") : e.kind == FolderEntry::Create ? QStringLiteral("create") : QStringLiteral("folder");+ case AccountRole:+ return e.accountId;+ case FullNameRole:+ return e.fullName;+ case NameRole:+ return e.displayName;+ case FolderRoleRole:+ return e.role;+ case DepthRole:+ return e.depth;+ case UnreadRole:+ // Drafts and the Outbox count what is in them, the way the design+ // shows "Drafts 1"; everything else counts unread mail.+ return e.role == QLatin1String("drafts") || e.role == QLatin1String("outbox") ? e.total : e.unread;+ case ExpandedRole:+ return e.expanded;+ }+ return {};+}++QHash<int, QByteArray> FolderModel::roleNames() const+{+ return {+ {KindRole, "kind"},+ {AccountRole, "accountId"},+ {FullNameRole, "fullName"},+ {NameRole, "name"},+ {FolderRoleRole, "folderRole"},+ {DepthRole, "depth"},+ {UnreadRole, "count"},+ {ExpandedRole, "expanded"},+ };+}++void FolderModel::reset(const QList<FolderEntry> &entries)+{+ // Only the counts changed: update in place so the pane doesn't flicker.+ if (entries.size() == m_entries.size()) {+ bool same = true;+ for (int i = 0; i < entries.size() && same; ++i) {+ same = entries[i].kind == m_entries[i].kind && entries[i].accountId == m_entries[i].accountId+ && entries[i].fullName == m_entries[i].fullName && entries[i].expanded == m_entries[i].expanded+ && entries[i].displayName == m_entries[i].displayName;+ }+ if (same) {+ m_entries = entries;+ Q_EMIT dataChanged(index(0), index(m_entries.size() - 1), {UnreadRole});+ return;+ }+ }+ beginResetModel();+ m_entries = entries;+ endResetModel();+}++MessageModel::MessageModel(QObject *parent)+ : QAbstractListModel(parent)+{+ m_conversations = QSettings().value(QStringLiteral("mail/conversations"), false).toBool();+}++void MessageModel::setConversations(bool on)+{+ if (on == m_conversations) {+ return;+ }+ m_conversations = on;+ QSettings().setValue(QStringLiteral("mail/conversations"), on);+ beginResetModel();+ applyFilter();+ endResetModel();+ Q_EMIT conversationsChanged();+ Q_EMIT countChanged();+}++// The subject without its Re:, Fw: and their translations, which is how+// Outlook decides two messages belong to one conversation.+QString MessageModel::topic(const QString &subject)+{+ static const QRegularExpression prefix(QStringLiteral(R"(^\s*((re|fw|fwd|aw|wg|sv|vs|antw|tr|rif|r)\s*(\[\d+\])?\s*:\s*)+)"),+ QRegularExpression::CaseInsensitiveOption);+ QString t = subject;+ t.remove(prefix);+ return t.simplified().toLower();+}++int MessageModel::rowCount(const QModelIndex &parent) const+{+ return parent.isValid() ? 0 : m_visible.size();+}++QVariant MessageModel::data(const QModelIndex &index, int role) const+{+ const MessageRow *r = rowAt(index.row());+ if (!r) {+ return {};+ }+ switch (role) {+ case KeyRole:+ return r->key();+ case FromRole:+ return r->draft || r->outgoing ? (r->to.isEmpty() ? tr("(No recipient)") : r->to) : r->fromName;+ case FromAddressRole:+ return r->outgoing ? r->toAddress : r->fromAddress;+ case InitialsRole:+ return r->outgoing ? initials(r->to.isEmpty() ? r->toAddress : r->to) : initials(r->fromName.isEmpty() ? r->fromAddress : r->fromName);+ case AvatarRole:+ return colourOf(r->outgoing ? r->toAddress : r->fromAddress);+ case SubjectRole:+ return r->subject.isEmpty() ? tr("(No subject)") : r->subject;+ case PreviewRole:+ return r->preview;+ case TimeRole:+ return timeLabel(r->date);+ case SectionRole:+ return sectionOf(r->date, r->pinned);+ case UnreadRole:+ return r->unread;+ case FlaggedRole:+ return r->flagged;+ case PinnedRole:+ return r->pinned;+ case AttachmentRole:+ return r->attachment;+ case DraftRole:+ return r->draft;+ case FolderNameRole:+ return folderName ? folderName(r->accountId, r->folder) : r->folder;+ case AccountRole:+ return r->accountId;+ case ThreadCountRole:+ return m_conversations ? m_threadCounts.value(topic(r->subject), 1) : 1;+ }+ return {};+}++QHash<int, QByteArray> MessageModel::roleNames() const+{+ return {+ {KeyRole, "key"},+ {FromRole, "from"},+ {FromAddressRole, "fromAddress"},+ {InitialsRole, "initials"},+ {AvatarRole, "avatar"},+ {SubjectRole, "subject"},+ {PreviewRole, "preview"},+ {TimeRole, "time"},+ {SectionRole, "section"},+ {UnreadRole, "unread"},+ {FlaggedRole, "flagged"},+ {PinnedRole, "pinned"},+ {AttachmentRole, "attachment"},+ {DraftRole, "draft"},+ {FolderNameRole, "folderName"},+ {AccountRole, "accountId"},+ {ThreadCountRole, "threadCount"},+ };+}++void MessageModel::setFilter(const QString &filter)+{+ if (filter == m_filter) {+ return;+ }+ m_filter = filter;+ beginResetModel();+ applyFilter();+ endResetModel();+ Q_EMIT filterChanged();+ Q_EMIT countChanged();+}++void MessageModel::reset(const QList<MessageRow> &rows)+{+ QList<MessageRow> sorted = rows;+ std::stable_sort(sorted.begin(), sorted.end(), [](const MessageRow &a, const MessageRow &b) {+ if (a.pinned != b.pinned) {+ return a.pinned;+ }+ return a.date > b.date;+ });++ QList<int> oldVisible = m_visible;+ QList<MessageRow> oldAll = m_all;+ m_all = sorted;+ QList<int> newVisible;+ std::swap(newVisible, m_visible);+ applyFilter();++ bool sameKeys = oldVisible.size() == m_visible.size();+ for (int i = 0; sameKeys && i < m_visible.size(); ++i) {+ sameKeys = oldAll[oldVisible[i]].key() == m_all[m_visible[i]].key();+ }+ if (sameKeys) {+ if (!m_visible.isEmpty()) {+ Q_EMIT dataChanged(index(0), index(m_visible.size() - 1));+ }+ } else {+ beginResetModel();+ endResetModel();+ }+ Q_EMIT countChanged();+}++void MessageModel::removeKeys(const QStringList &keys)+{+ const QSet<QString> gone(keys.cbegin(), keys.cend());+ for (int i = m_visible.size() - 1; i >= 0; --i) {+ if (gone.contains(m_all.at(m_visible.at(i)).key())) {+ beginRemoveRows({}, i, i);+ m_visible.removeAt(i);+ endRemoveRows();+ }+ }+ QList<MessageRow> kept;+ QHash<int, int> newIndex;+ for (int i = 0; i < m_all.size(); ++i) {+ if (!gone.contains(m_all.at(i).key())) {+ newIndex.insert(i, kept.size());+ kept.append(m_all.at(i));+ }+ }+ for (int &v : m_visible) {+ v = newIndex.value(v);+ }+ m_all = kept;+ Q_EMIT countChanged();+}++void MessageModel::updateRow(const QString &key, const std::function<void(MessageRow &)> &change)+{+ for (int i = 0; i < m_all.size(); ++i) {+ if (m_all[i].key() == key) {+ change(m_all[i]);+ const int shown = m_visible.indexOf(i);+ if (shown >= 0) {+ Q_EMIT dataChanged(index(shown), index(shown));+ }+ return;+ }+ }+}++const MessageRow *MessageModel::row(const QString &key) const+{+ for (const MessageRow &r : m_all) {+ if (r.key() == key) {+ return &r;+ }+ }+ return nullptr;+}++const MessageRow *MessageModel::rowAt(int i) const+{+ if (i < 0 || i >= m_visible.size()) {+ return nullptr;+ }+ return &m_all.at(m_visible.at(i));+}++int MessageModel::indexOf(const QString &key) const+{+ for (int i = 0; i < m_visible.size(); ++i) {+ if (m_all.at(m_visible.at(i)).key() == key) {+ return i;+ }+ }+ return -1;+}++QString MessageModel::keyAt(int i) const+{+ const MessageRow *r = rowAt(i);+ return r ? r->key() : QString();+}++QString MessageModel::neighbour(const QString &key) const+{+ const int i = indexOf(key);+ if (i < 0) {+ return {};+ }+ if (i + 1 < m_visible.size()) {+ return keyAt(i + 1);+ }+ return i > 0 ? keyAt(i - 1) : QString();+}++void MessageModel::applyFilter()+{+ m_visible.clear();+ m_threadCounts.clear();+ QSet<QString> shown;+ const QDateTime now = QDateTime::currentDateTime();+ for (int i = 0; i < m_all.size(); ++i) {+ const MessageRow &r = m_all.at(i);+ if (r.snoozedUntil.isValid() && r.snoozedUntil > now) {+ continue;+ }+ if ((m_filter == QLatin1String("unread") && !r.unread) || (m_filter == QLatin1String("flagged") && !r.flagged)+ || (m_filter == QLatin1String("attachments") && !r.attachment)) {+ continue;+ }+ // m_all is newest first, so the first of each topic is the one+ // the conversation shows.+ if (m_conversations && !r.subject.trimmed().isEmpty()) {+ const QString t = topic(r.subject);+ m_threadCounts[t] += 1;+ if (shown.contains(t)) {+ continue;+ }+ shown.insert(t);+ }+ m_visible.append(i);+ }+}++int MessageModel::colourOf(const QString &address)+{+ quint32 h = 2166136261u;+ for (const QChar c : address.toLower()) {+ h = (h ^ c.unicode()) * 16777619u;+ }+ return int(h % 8);+}++QString MessageModel::initials(const QString &name)+{+ QString clean = name;+ clean.remove(QLatin1Char('"'));+ const int at = clean.indexOf(QLatin1Char('@'));+ if (at > 0) {+ clean = clean.left(at).replace(QLatin1Char('.'), QLatin1Char(' '));+ }+ const QStringList words = clean.split(QLatin1Char(' '), Qt::SkipEmptyParts);+ QString out;+ for (const QString &w : words) {+ if (w.at(0).isLetterOrNumber()) {+ out += w.at(0).toUpper();+ }+ if (out.size() == 2) {+ break;+ }+ }+ if (out.isEmpty() && !clean.isEmpty()) {+ out = clean.left(1).toUpper();+ }+ return out;+}++QString MessageModel::timeLabel(const QDateTime &date)+{+ const QDate today = QDate::currentDate();+ const QDate d = date.date();+ if (d == today) {+ return Formats::time(date);+ }+ if (d == today.addDays(-1)) {+ return tr("Yesterday");+ }+ if (d > today.addDays(-7)) {+ return Formats::names().dayName(d.dayOfWeek(), QLocale::ShortFormat);+ }+ return Formats::shortDate(d);+}++QString MessageModel::sectionOf(const QDateTime &date, bool pinned)+{+ if (pinned) {+ return tr("Pinned");+ }+ const QDate today = QDate::currentDate();+ const QDate d = date.date();+ if (d == today) {+ return tr("Today");+ }+ if (d == today.addDays(-1)) {+ return tr("Yesterday");+ }+ // The last seven days, as the design groups Saturday and Friday under+ // "This week" on a Monday.+ if (d > today.addDays(-7)) {+ return tr("This week");+ }+ if (d > today.addDays(-14)) {+ return tr("Last week");+ }+ if (d.year() == today.year()) {+ return Formats::names().standaloneMonthName(d.month());+ }+ return QString::number(d.year());+}diff --git a/packages/wildos-mail/src/models.h b/packages/wildos-mail/src/models.hnew file mode 100644index 0000000..0a59d79--- /dev/null+++ b/packages/wildos-mail/src/models.h@@ -0,0 +1,195 @@+#pragma once++#include <QAbstractListModel>+#include <QDateTime>+#include <QList>+#include <QString>+#include <QStringList>++#include <functional>+#include <QtQml/qqmlregistration.h>++// One line of the folder pane: an account (or Favourites) heading, a folder+// under it, or the "Create new folder" link at the end of an account.+struct FolderEntry {+ enum Kind { Header, Folder, Create };+ Kind kind = Folder;+ // Empty for Favourites, which gather the same folder from every account.+ QString accountId;+ QString fullName;+ QString displayName;+ // inbox, drafts, sent, archive, trash, junk, outbox or folder+ QString role;+ int depth = 0;+ int unread = 0;+ int total = 0;+ bool expanded = true;+};++class FolderModel : public QAbstractListModel+{+ Q_OBJECT+ QML_ELEMENT+ QML_UNCREATABLE("Mail makes these itself")++public:+ enum Roles {+ KindRole = Qt::UserRole + 1,+ AccountRole,+ FullNameRole,+ NameRole,+ FolderRoleRole,+ DepthRole,+ UnreadRole,+ ExpandedRole,+ };++ using QAbstractListModel::QAbstractListModel;++ int rowCount(const QModelIndex &parent = {}) const override;+ QVariant data(const QModelIndex &index, int role) const override;+ QHash<int, QByteArray> roleNames() const override;++ void reset(const QList<FolderEntry> &entries);+ const QList<FolderEntry> &entries() const+ {+ return m_entries;+ }++private:+ QList<FolderEntry> m_entries;+};++// A message as the list shows it, read from Camel's summary so the list+// never waits for the network.+struct MessageRow {+ QString accountId;+ QString folder;+ QString uid;+ QString fromName;+ QString fromAddress;+ QString to;+ QString subject;+ QString preview;+ QDateTime date;+ bool unread = false;+ bool flagged = false;+ bool pinned = false;+ bool attachment = false;+ bool draft = false;+ // Sent mail and drafts are listed by who they're to, as in Outlook.+ bool outgoing = false;+ QString toAddress;+ QDateTime snoozedUntil;++ QString key() const+ {+ return accountId + QLatin1Char('\x1f') + folder + QLatin1Char('\x1f') + uid;+ }+};++class MessageModel : public QAbstractListModel+{+ Q_OBJECT+ QML_ELEMENT+ QML_UNCREATABLE("Mail makes these itself")+ // The list's filter button: all, unread, flagged or attachments. One+ // list, newest first, no conversations: the classic Outlook view.+ Q_PROPERTY(QString filter READ filter WRITE setFilter NOTIFY filterChanged)+ Q_PROPERTY(int count READ rowCount NOTIFY countChanged)+ Q_PROPERTY(int total READ total NOTIFY countChanged)+ // Settings > Mail > Group messages into conversations, off by default:+ // one row per conversation topic, showing its newest message.+ Q_PROPERTY(bool conversations READ conversations WRITE setConversations NOTIFY conversationsChanged)++public:+ enum Roles {+ KeyRole = Qt::UserRole + 1,+ FromRole,+ FromAddressRole,+ InitialsRole,+ AvatarRole,+ SubjectRole,+ PreviewRole,+ TimeRole,+ SectionRole,+ UnreadRole,+ FlaggedRole,+ PinnedRole,+ AttachmentRole,+ DraftRole,+ FolderNameRole,+ AccountRole,+ ThreadCountRole,+ };++ explicit MessageModel(QObject *parent = nullptr);++ int rowCount(const QModelIndex &parent = {}) const override;+ QVariant data(const QModelIndex &index, int role) const override;+ QHash<int, QByteArray> roleNames() const override;++ QString filter() const+ {+ return m_filter;+ }+ void setFilter(const QString &filter);+ int total() const+ {+ return m_all.size();+ }+ bool conversations() const+ {+ return m_conversations;+ }+ void setConversations(bool on);+ static QString topic(const QString &subject);++ // Replaces every row; keeps the view where it was when the same rows+ // come back with a flag changed.+ void reset(const QList<MessageRow> &rows);+ const MessageRow *row(const QString &key) const;+ // Changes shown at once, before the server has done them; the next+ // reload from Camel confirms or corrects them.+ void removeKeys(const QStringList &keys);+ void updateRow(const QString &key, const std::function<void(MessageRow &)> &change);+ const MessageRow *rowAt(int index) const;+ Q_INVOKABLE int indexOf(const QString &key) const;+ Q_INVOKABLE QString keyAt(int index) const;+ Q_INVOKABLE bool unreadAt(int index) const+ {+ const MessageRow *r = rowAt(index);+ return r && r->unread;+ }+ Q_INVOKABLE bool flaggedAt(int index) const+ {+ const MessageRow *r = rowAt(index);+ return r && r->flagged;+ }+ // The row after (or before, at the end) the one going away, for moving+ // the selection along when a message is deleted or archived.+ QString neighbour(const QString &key) const;++ // How a folder is named in search results.+ std::function<QString(const QString &accountId, const QString &folder)> folderName;++ static QString initials(const QString &name);+ // The same sender gets the same colour every time Mail opens.+ static int colourOf(const QString &address);+ static QString timeLabel(const QDateTime &date);+ static QString sectionOf(const QDateTime &date, bool pinned);++Q_SIGNALS:+ void filterChanged();+ void conversationsChanged();+ void countChanged();++private:+ void applyFilter();++ QString m_filter = QStringLiteral("all");+ bool m_conversations = false;+ QHash<QString, int> m_threadCounts;+ QList<MessageRow> m_all;+ QList<int> m_visible;+};diff --git a/packages/wildos-mail/src/notifier.cpp b/packages/wildos-mail/src/notifier.cppnew file mode 100644index 0000000..bb8e474--- /dev/null+++ b/packages/wildos-mail/src/notifier.cpp@@ -0,0 +1,112 @@+#include "notifier.h"++#include <QDBusConnection>+#include <QDBusMessage>+#include <QDBusPendingCallWatcher>+#include <QDBusPendingReply>+#include <QSettings>++#include "composer.h"+#include "mailengine.h"+#include "messageview.h"++namespace+{+const QString service = QStringLiteral("org.freedesktop.Notifications");+const QString path = QStringLiteral("/org/freedesktop/Notifications");+}++Notifier::Notifier(QObject *parent)+ : QObject(parent)+{+ m_enabled = QSettings().value(QStringLiteral("notifications/mail"), true).toBool();+ connect(this, &Notifier::enabledChanged, this, [this]() {+ QSettings().setValue(QStringLiteral("notifications/mail"), m_enabled);+ });+ connect(MailEngine::instance(), &MailEngine::newMail, this, &Notifier::onNewMail);+ QDBusConnection bus = QDBusConnection::sessionBus();+ bus.connect(service, path, service, QStringLiteral("ActionInvoked"), this, SLOT(onAction(uint, QString)));+ bus.connect(service, path, service, QStringLiteral("NotificationReplied"), this, SLOT(onReplied(uint, QString)));+ bus.connect(service, path, service, QStringLiteral("NotificationClosed"), this, SLOT(onClosed(uint, uint)));+}++void Notifier::onNewMail(const QString &key, const QString &from, const QString &subject, const QString &preview)+{+ if (!m_enabled) {+ return;+ }+ QDBusMessage call = QDBusMessage::createMethodCall(service, path, service, QStringLiteral("Notify"));+ const QStringList actions = {QStringLiteral("default"), tr("Open"),+ QStringLiteral("inline-reply"), tr("Reply"),+ QStringLiteral("read"), tr("Mark as read"),+ QStringLiteral("archive"), tr("Archive")};+ const QVariantMap hints = {+ {QStringLiteral("desktop-entry"), QStringLiteral("org.wildos.mail")},+ {QStringLiteral("category"), QStringLiteral("email.arrived")},+ {QStringLiteral("x-kde-reply-placeholder-text"), tr("Type a reply")},+ {QStringLiteral("x-kde-reply-submit-button-text"), tr("Send")},+ };+ QString body = subject.toHtmlEscaped();+ if (!preview.isEmpty()) {+ body += QStringLiteral("\n") + preview.left(160).toHtmlEscaped();+ }+ call << QStringLiteral("Mail") << uint(0) << QStringLiteral("org.wildos.mail") << from << body << actions << hints << int(-1);+ auto *watcher = new QDBusPendingCallWatcher(QDBusConnection::sessionBus().asyncCall(call), this);+ connect(watcher, &QDBusPendingCallWatcher::finished, this, [this, watcher, key]() {+ QDBusPendingReply<uint> reply = *watcher;+ if (!reply.isError()) {+ m_keys.insert(reply.value(), key);+ }+ watcher->deleteLater();+ });+}++void Notifier::onAction(uint id, const QString &action)+{+ const QString key = m_keys.value(id);+ if (key.isEmpty()) {+ return;+ }+ if (action == QLatin1String("default")) {+ Q_EMIT openRequested(key);+ } else if (action == QLatin1String("read")) {+ MailEngine::instance()->setRead(key, true);+ } else if (action == QLatin1String("archive")) {+ MailEngine::instance()->archive(key);+ }+}++void Notifier::onReplied(uint id, const QString &text)+{+ const QString key = m_keys.value(id);+ if (!key.isEmpty() && !text.trimmed().isEmpty()) {+ quickReply(key, text);+ }+}++void Notifier::onClosed(uint id, uint)+{+ m_keys.remove(id);+}++// A reply typed in the notification goes out as an ordinary reply, with the+// original quoted under it, and the message counts as read.+void Notifier::quickReply(const QString &key, const QString &text)+{+ auto *view = new MessageView(this);+ connect(view, &MessageView::loaded, this, [this, view, key, text]() {+ if (view->loading()) {+ return;+ }+ if (view->error().isEmpty()) {+ Composer composer;+ composer.start(view->replyData(QStringLiteral("reply")));+ composer.setProperty("bodyText", text);+ composer.setProperty("bodyHtml", text.toHtmlEscaped().replace(QLatin1Char('\n'), QStringLiteral("<br>")));+ composer.send();+ MailEngine::instance()->setRead(key, true);+ }+ view->deleteLater();+ });+ view->setKey(key);+}diff --git a/packages/wildos-mail/src/notifier.h b/packages/wildos-mail/src/notifier.hnew file mode 100644index 0000000..3e29b81--- /dev/null+++ b/packages/wildos-mail/src/notifier.h@@ -0,0 +1,36 @@+#pragma once++#include <QHash>+#include <QObject>+#include <QtQml/qqmlregistration.h>++// New mail notifications through the desktop's notification server, with+// Mark as read, Archive and a reply typed right in the notification+// (MailCalMsNotify). Choosing the notification itself opens the message.+class Notifier : public QObject+{+ Q_OBJECT+ QML_ELEMENT+ QML_SINGLETON++ Q_PROPERTY(bool enabled MEMBER m_enabled NOTIFY enabledChanged)++public:+ explicit Notifier(QObject *parent = nullptr);++Q_SIGNALS:+ void enabledChanged();+ void openRequested(const QString &key);++private Q_SLOTS:+ void onNewMail(const QString &key, const QString &from, const QString &subject, const QString &preview);+ void onAction(uint id, const QString &action);+ void onReplied(uint id, const QString &text);+ void onClosed(uint id, uint reason);++private:+ void quickReply(const QString &key, const QString &text);++ QHash<uint, QString> m_keys;+ bool m_enabled = true;+};diff --git a/packages/wildos-mail/src/reminders.cpp b/packages/wildos-mail/src/reminders.cppnew file mode 100644index 0000000..9d493c1--- /dev/null+++ b/packages/wildos-mail/src/reminders.cpp@@ -0,0 +1,180 @@+#include "reminders.h"+#include "formats.h"++#include <QDBusConnection>+#include <QDBusMessage>+#include <QDBusPendingCallWatcher>+#include <QDBusPendingReply>+#include <QDateTime>+#include <QLocale>+#include <QProcess>+#include <QScopeGuard>+#include <QTimeZone>++namespace+{+const QString service = QStringLiteral("org.freedesktop.Notifications");+const QString path = QStringLiteral("/org/freedesktop/Notifications");++QString str(const gchar *s)+{+ return s ? QString::fromUtf8(s) : QString();+}++// "in 5 minutes", "now", "started 10 minutes ago".+QString whenText(qint64 start)+{+ const qint64 minutes = (start - QDateTime::currentSecsSinceEpoch() + 30) / 60;+ if (minutes == 0) {+ return QObject::tr("now");+ }+ if (minutes > 0) {+ if (minutes < 60) {+ return minutes == 1 ? QObject::tr("in 1 minute") : QObject::tr("in %1 minutes").arg(minutes);+ }+ if (minutes < 24 * 60) {+ return minutes < 90 ? QObject::tr("in 1 hour") : QObject::tr("in %1 hours").arg((minutes + 30) / 60);+ }+ return minutes < 36 * 60 ? QObject::tr("tomorrow") : QObject::tr("in %1 days").arg((minutes + 12 * 60) / (24 * 60));+ }+ return minutes == -1 ? QObject::tr("started 1 minute ago") : QObject::tr("started %1 minutes ago").arg(-minutes);+}+}++Reminders::Reminders(QObject *parent)+ : QObject(parent)+{+ QDBusConnection bus = QDBusConnection::sessionBus();+ bus.connect(service, path, service, QStringLiteral("ActionInvoked"), this, SLOT(onAction(uint, QString)));+ bus.connect(service, path, service, QStringLiteral("NotificationClosed"), this, SLOT(onClosed(uint, uint)));+}++Reminders::~Reminders()+{+ for (EReminderData *rd : std::as_const(m_shown)) {+ e_reminder_data_free(rd);+ }+ g_clear_object(&m_watcher);+ g_clear_object(&m_registry);+}++bool Reminders::start()+{+ GError *error = nullptr;+ m_registry = e_source_registry_new_sync(nullptr, &error);+ if (!m_registry) {+ qWarning("Calendar reminders: the calendar service didn't start: %s", error ? error->message : "");+ g_clear_error(&error);+ return false;+ }+ m_watcher = e_reminder_watcher_new(m_registry);+ ICalTimezone *zone = i_cal_timezone_get_builtin_timezone(QTimeZone::systemTimeZoneId().constData());+ if (zone) {+ e_reminder_watcher_set_default_zone(m_watcher, zone);+ }+ g_signal_connect(m_watcher, "triggered", G_CALLBACK(&Reminders::onTriggered), this);+ return true;+}++void Reminders::onTriggered(EReminderWatcher *, const GSList *reminders, gboolean, gpointer self)+{+ qInfo("Calendar reminders: %u due", g_slist_length(const_cast<GSList *>(reminders)));+ for (const GSList *l = reminders; l; l = l->next) {+ static_cast<Reminders *>(self)->show(static_cast<const EReminderData *>(l->data));+ }+}++void Reminders::show(const EReminderData *data)+{+ ECalComponent *comp = e_reminder_data_get_component(data);+ const ECalComponentAlarmInstance *instance = e_reminder_data_get_instance(data);+ if (!comp || !instance) {+ return;+ }+ ICalComponent *icomp = e_cal_component_get_icalcomponent(comp);+ QString title = str(i_cal_component_get_summary(icomp));+ if (title.isEmpty()) {+ title = tr("(No title)");+ }+ const QString location = str(i_cal_component_get_location(icomp));+ const qint64 start = e_cal_component_alarm_instance_get_occur_start(instance);+ const qint64 end = e_cal_component_alarm_instance_get_occur_end(instance);+ const QDateTime s = QDateTime::fromSecsSinceEpoch(start);+ const QDateTime e = QDateTime::fromSecsSinceEpoch(end);+ ICalTime *dtstart = i_cal_component_get_dtstart(icomp);+ const bool allDay = dtstart && i_cal_time_is_date(dtstart);+ g_clear_object(&dtstart);++ QString body = allDay ? tr("All day") : tr("%1 to %2").arg(Formats::time(s), Formats::time(e));+ if (s.date() != QDate::currentDate()) {+ body = Formats::shortDayAndMonth(s.date()) + QStringLiteral(", ") + body;+ }+ if (!location.isEmpty()) {+ body += QStringLiteral(", ") + location;+ }++ QDBusMessage call = QDBusMessage::createMethodCall(service, path, service, QStringLiteral("Notify"));+ const QStringList actions = {QStringLiteral("default"), tr("Open"),+ QStringLiteral("snooze"), tr("Snooze for 5 minutes"),+ QStringLiteral("dismiss"), tr("Dismiss")};+ const QVariantMap hints = {+ {QStringLiteral("desktop-entry"), QStringLiteral("org.wildos.calendar")},+ {QStringLiteral("category"), QStringLiteral("x-wildos.calendar.reminder")},+ {QStringLiteral("resident"), true},+ {QStringLiteral("urgency"), QVariant::fromValue<uchar>(1)},+ };+ // "Calendar in 5 minutes" over the event, as the board has it.+ const QString heading = allDay ? title : tr("%1, %2").arg(title, whenText(start));+ call << tr("Calendar") << uint(0) << QStringLiteral("org.wildos.calendar") << heading << body.toHtmlEscaped() << actions << hints << int(0);+ EReminderData *copy = e_reminder_data_copy(data);+ auto *watcher = new QDBusPendingCallWatcher(QDBusConnection::sessionBus().asyncCall(call), this);+ connect(watcher, &QDBusPendingCallWatcher::finished, this, [this, watcher, copy]() {+ QDBusPendingReply<uint> reply = *watcher;+ if (reply.isError()) {+ e_reminder_data_free(copy);+ } else {+ m_shown.insert(reply.value(), copy);+ }+ watcher->deleteLater();+ });+}++void Reminders::onAction(uint id, const QString &action)+{+ EReminderData *rd = m_shown.take(id);+ if (!rd) {+ return;+ }+ // Resident notifications stay after a button; this one is done.+ QDBusConnection::sessionBus().asyncCall(QDBusMessage::createMethodCall(service, path, service, QStringLiteral("CloseNotification")) << id);+ const auto cleanup = qScopeGuard([rd]() {+ e_reminder_data_free(rd);+ });+ if (action == QLatin1String("snooze")) {+ e_reminder_watcher_snooze(m_watcher, rd, QDateTime::currentSecsSinceEpoch() + 5 * 60);+ } else if (action == QLatin1String("dismiss")) {+ e_reminder_watcher_dismiss_sync(m_watcher, rd, nullptr, nullptr);+ } else if (action == QLatin1String("default")) {+ ECalComponent *comp = e_reminder_data_get_component(rd);+ const ECalComponentAlarmInstance *instance = e_reminder_data_get_instance(rd);+ const QString uid = str(e_cal_component_get_uid(comp));+ const qint64 start = instance ? e_cal_component_alarm_instance_get_occur_start(instance) : 0;+ // Opening it counts as having seen it.+ e_reminder_watcher_dismiss_sync(m_watcher, rd, nullptr, nullptr);+ QProcess::startDetached(QStringLiteral("wildos-calendar"),+ {QStringLiteral("--event"), str(e_reminder_data_get_source_uid(rd)) + QChar(0x1f) + uid,+ QStringLiteral("--day"), QDateTime::fromSecsSinceEpoch(start).date().toString(Qt::ISODate)});+ }+}++void Reminders::onClosed(uint id, uint reason)+{+ // 2 is closed by the person; a reminder closed without snoozing is+ // dismissed, so it doesn't come back.+ if (EReminderData *rd = m_shown.take(id)) {+ if (reason == 2) {+ e_reminder_watcher_dismiss_sync(m_watcher, rd, nullptr, nullptr);+ }+ e_reminder_data_free(rd);+ }+}diff --git a/packages/wildos-mail/src/reminders.h b/packages/wildos-mail/src/reminders.hnew file mode 100644index 0000000..583a6fd--- /dev/null+++ b/packages/wildos-mail/src/reminders.h@@ -0,0 +1,36 @@+#pragma once++#include <QHash>+#include <QObject>++#include <libecal/libecal.h>++// Event reminders (MailCalMsNotify), from evolution-data-server's reminder+// watcher, which knows every calendar's reminders, snoozes and the ones+// missed while the PC was off. Runs at sign-in as wildos-calendar+// --reminders, without a window, in place of evolution-data-server's own+// GTK reminder program. Each shows as a notification that stays until it+// is snoozed or dismissed; choosing it opens Calendar at the event.+class Reminders : public QObject+{+ Q_OBJECT++public:+ explicit Reminders(QObject *parent = nullptr);+ ~Reminders() override;++ // false when the calendar service can't be reached.+ bool start();++private Q_SLOTS:+ void onAction(uint id, const QString &action);+ void onClosed(uint id, uint reason);++private:+ static void onTriggered(EReminderWatcher *, const GSList *reminders, gboolean snoozed, gpointer self);+ void show(const EReminderData *data);++ ESourceRegistry *m_registry = nullptr;+ EReminderWatcher *m_watcher = nullptr;+ QHash<uint, EReminderData *> m_shown;+};diff --git a/packages/wildos-overlays/clipboard/qml/ClipboardPage.qml b/packages/wildos-overlays/clipboard/qml/ClipboardPage.qmlindex 7cf8b22..9d7ecb0 100644--- a/packages/wildos-overlays/clipboard/qml/ClipboardPage.qml+++ b/packages/wildos-overlays/clipboard/qml/ClipboardPage.qml@@ -66,6 +66,14 @@ Item {page.items = out;}+ // "9 Nov" or "Nov 9" as the regional format in Settings orders them,+ // from its long date with the weekday and year taken out.+ function dayAndMonth(when: var): string {+ const format = Qt.locale().dateFormat(Locale.LongFormat)+ .replace(/d{4}[,.\s]*/, "").replace(/[,.\s]*y+[.年]?/, "").replace("MMMM", "MMM").trim();+ return Qt.locale("en_GB").toString(when, format);+ }+function ago(time: real): string {const minutes = Math.floor((now - time) / 60000);if (minutes < 1) {@@ -78,7 +86,7 @@ Item {if (hours < 24) {return hours + " hr ago";}- return hours < 48 ? "Yesterday" : Qt.formatDate(new Date(time), "d MMM");+ return hours < 48 ? "Yesterday" : dayAndMonth(new Date(time));}// A file path as people read it: ~ for home, and how many more.diff --git a/packages/wildos-portal/src/clash.cpp b/packages/wildos-portal/src/clash.cppindex c2353d1..4fadeae 100644--- a/packages/wildos-portal/src/clash.cpp+++ b/packages/wildos-portal/src/clash.cpp@@ -47,7 +47,7 @@ QString suggestKeepBothName(const QUrl &dest, bool isDir)QString when(qint64 ms){- return ms > 0 ? QDateTime::fromMSecsSinceEpoch(ms).toLocalTime().toString(QStringLiteral("dd/MM/yyyy")) : QString();+ return ms > 0 ? QLocale::system().toString(QDateTime::fromMSecsSinceEpoch(ms).toLocalTime().date(), QLocale::ShortFormat) : QString();}QString facts(qint64 ms, qint64 size, bool isDir)@@ -111,7 +111,7 @@ QString Clash::summary() constconst QString verb = m_move ? QStringLiteral("Moving") : QStringLiteral("Copying");const QString thing = m_folders ? QStringLiteral("folder") : QStringLiteral("file");if (m_items > 1) {- const QString items = QStringLiteral("%1 %2 items.").arg(verb, QLocale(QLocale::English, QLocale::UnitedKingdom).toString(m_items));+ const QString items = QStringLiteral("%1 %2 items.").arg(verb, QLocale::system().toString(m_items));if (m_clashes > 1) {return items + QStringLiteral(" %1 have the same name as items already there.").arg(m_clashes);}diff --git a/packages/wildos-portal/src/dirmodel.cpp b/packages/wildos-portal/src/dirmodel.cppindex 2b2d13e..38a69d3 100644--- a/packages/wildos-portal/src/dirmodel.cpp+++ b/packages/wildos-portal/src/dirmodel.cpp@@ -2,6 +2,7 @@#include "format.h"+#include <QLocale>#include <KConfigGroup>#include <KCoreDirLister>#include <KIO/MkdirJob>@@ -465,7 +466,7 @@ DirModel::Entry DirModel::makeEntry(const KFileItem &item) conste.hidden = item.isHidden();const QDateTime modified = item.time(KFileItem::ModificationTime);e.dateKey = modified.isValid() ? modified.toMSecsSinceEpoch() : 0;- e.date = modified.isValid() ? modified.toLocalTime().toString(QStringLiteral("dd/MM/yyyy HH:mm")) : QString();+ e.date = modified.isValid() ? QLocale::system().toString(modified.toLocalTime(), QLocale::ShortFormat) : QString();e.type = Format::typeName(item.currentMimeType(), e.isDir);if (!e.isDir) {e.sizeKey = qint64(item.size());diff --git a/packages/wildos-portal/src/format.cpp b/packages/wildos-portal/src/format.cppindex e8704ae..27e6d59 100644--- a/packages/wildos-portal/src/format.cpp+++ b/packages/wildos-portal/src/format.cpp@@ -71,9 +71,13 @@ QString date(const QDateTime &when)if (!when.isValid()) {return QString();}+ // The regional format chosen in Settings decides the order and the+ // clock; the words stay English, as the rest of Wild OS is.+ const QLocale names(QLocale::English, QLocale::UnitedKingdom);+ const QLocale format = QLocale::system();const QDateTime local = when.toLocalTime();const QDate today = QDate::currentDate();- const QString time = local.toString(QStringLiteral("HH:mm"));+ const QString time = format.toString(local.time(), QLocale::ShortFormat);const qint64 days = local.date().daysTo(today);if (days == 0) {return QStringLiteral("Today ") + time;@@ -82,9 +86,9 @@ QString date(const QDateTime &when)return QStringLiteral("Yesterday ") + time;}if (days > 1 && days < 7) {- return QLocale(QLocale::English, QLocale::UnitedKingdom).dayName(local.date().dayOfWeek()) + QLatin1Char(' ') + time;+ return names.dayName(local.date().dayOfWeek()) + QLatin1Char(' ') + time;}- return local.toString(QStringLiteral("dd/MM/yyyy"));+ return names.toString(local.date(), format.dateFormat(QLocale::ShortFormat));}QString longDate(const QDateTime &when)@@ -93,8 +97,15 @@ QString longDate(const QDateTime &when)return QString();}const QDateTime local = when.toLocalTime();- const QLocale uk(QLocale::English, QLocale::UnitedKingdom);- return uk.toString(local, QStringLiteral("dddd d MMMM yyyy, HH:mm"));+ const QLocale names(QLocale::English, QLocale::UnitedKingdom);+ const QLocale format = QLocale::system();+ // Qt writes UK dates as "Monday, 9 November"; Wild OS has no comma.+ QString day = format.dateFormat(QLocale::LongFormat);+ if (day.startsWith(QLatin1String("dddd, d MMMM"))) {+ day.remove(4, 1);+ }+ return names.toString(local.date(), day) + QStringLiteral(", ")+ + format.toString(local.time(), QLocale::ShortFormat);}QString size(qint64 bytes)@@ -102,11 +113,12 @@ QString size(qint64 bytes)if (bytes < 0) {return QString();}- const QLocale uk(QLocale::English, QLocale::UnitedKingdom);+ // Separators from the regional format chosen in Settings (LC_NUMERIC).+ const QLocale numbers = QLocale::system();// Windows rounds small files up, so a 200 byte note is 1 KB, not 0.if (bytes < 1024 * 1024) {const qint64 kb = bytes == 0 ? 0 : (bytes + 1023) / 1024;- return uk.toString(kb) + QStringLiteral(" KB");+ return numbers.toString(kb) + QStringLiteral(" KB");}static const char *units[] = {"MB", "GB", "TB", "PB"};double value = bytes / (1024.0 * 1024.0);@@ -117,12 +129,12 @@ QString size(qint64 bytes)}// Three significant figures: 4.21 MB, 12.3 MB, 123 MB.const int decimals = value < 10 ? 2 : value < 100 ? 1 : 0;- QString text = uk.toString(value, 'f', decimals);- if (text.contains(QLatin1Char('.'))) {+ QString text = numbers.toString(value, 'f', decimals);+ if (text.contains(numbers.decimalPoint())) {while (text.endsWith(QLatin1Char('0'))) {text.chop(1);}- if (text.endsWith(QLatin1Char('.'))) {+ if (text.endsWith(numbers.decimalPoint())) {text.chop(1);}}@@ -131,14 +143,12 @@ QString size(qint64 bytes)QString exactSize(qint64 bytes){- const QLocale uk(QLocale::English, QLocale::UnitedKingdom);- return size(bytes) + QStringLiteral(" (") + uk.toString(bytes) + (bytes == 1 ? QStringLiteral(" byte)") : QStringLiteral(" bytes)"));+ return size(bytes) + QStringLiteral(" (") + QLocale::system().toString(bytes) + (bytes == 1 ? QStringLiteral(" byte)") : QStringLiteral(" bytes)"));}QString count(qint64 n, const QString &one, const QString &many){- const QLocale uk(QLocale::English, QLocale::UnitedKingdom);- return uk.toString(n) + QLatin1Char(' ') + (n == 1 ? one : many);+ return QLocale::system().toString(n) + QLatin1Char(' ') + (n == 1 ? one : many);}}diff --git a/packages/wildos-rdp/CMakeLists.txt b/packages/wildos-rdp/CMakeLists.txtnew file mode 100644index 0000000..94cf542--- /dev/null+++ b/packages/wildos-rdp/CMakeLists.txt@@ -0,0 +1,58 @@+cmake_minimum_required(VERSION 3.25)+project(wildos-rdp VERSION 0.1.0 LANGUAGES C CXX)++set(CMAKE_CXX_STANDARD 20)+set(CMAKE_CXX_STANDARD_REQUIRED ON)+include(GNUInstallDirs)++# Qt6::GuiPrivate (below) only for QPlatformNativeInterface: the xdg_toplevel behind a+# window, which Qt 6.8 offers no public way to reach.+find_package(Qt6 6.8 REQUIRED COMPONENTS Core Gui DBus)+find_package(KF6Config REQUIRED)+find_package(KF6WindowSystem REQUIRED)+include(engine.cmake)+pkg_check_modules(WAYLAND REQUIRED IMPORTED_TARGET wayland-client)+pkg_get_variable(WAYLAND_PROTOCOLS wayland-protocols pkgdatadir)+find_program(WAYLAND_SCANNER wayland-scanner REQUIRED)++# Client code for the two protocols wayland.cpp speaks to the compositor.+set(PROTOCOLS+ ${WAYLAND_PROTOCOLS}/stable/xdg-shell/xdg-shell.xml+ ${WAYLAND_PROTOCOLS}/staging/xdg-toplevel-icon/xdg-toplevel-icon-v1.xml)+set(PROTOCOL_SOURCES)+foreach(xml ${PROTOCOLS})+ get_filename_component(name ${xml} NAME_WE)+ add_custom_command(+ OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${name}-client-protocol.h ${CMAKE_CURRENT_BINARY_DIR}/${name}-protocol.c+ COMMAND ${WAYLAND_SCANNER} client-header ${xml} ${CMAKE_CURRENT_BINARY_DIR}/${name}-client-protocol.h+ COMMAND ${WAYLAND_SCANNER} private-code ${xml} ${CMAKE_CURRENT_BINARY_DIR}/${name}-protocol.c+ DEPENDS ${xml})+ list(APPEND PROTOCOL_SOURCES ${CMAKE_CURRENT_BINARY_DIR}/${name}-client-protocol.h ${CMAKE_CURRENT_BINARY_DIR}/${name}-protocol.c)+endforeach()++qt_standard_project_setup(REQUIRES 6.8)++qt_add_executable(wildos-rdp+ src/main.cpp+ src/railwindow.cpp src/railwindow.h+ src/rail.cpp src/rail.h+ src/loading.cpp src/loading.h+ src/style.cpp src/style.h+ src/service.cpp src/service.h+ src/selftest.cpp src/selftest.h+ src/wayland.cpp src/wayland.h+ src/kwin.cpp src/kwin.h+ ${PROTOCOL_SOURCES}+)+target_include_directories(wildos-rdp PRIVATE ${CMAKE_CURRENT_BINARY_DIR})+target_compile_definitions(wildos-rdp PRIVATE WILDOS_RDP_VERSION="${PROJECT_VERSION}")++target_link_libraries(wildos-rdp PRIVATE+ Qt6::Gui Qt6::GuiPrivate Qt6::DBus+ KF6::ConfigCore KF6::WindowSystem+ wildos-rdp-engine PkgConfig::WAYLAND+)++install(TARGETS wildos-rdp RUNTIME DESTINATION ${CMAKE_INSTALL_LIBEXECDIR}/wildos)+# Puts each Windows app where it was last time; enabled by default.+install(DIRECTORY kwin/org.wildos.rdp.place DESTINATION ${CMAKE_INSTALL_DATADIR}/kwin/scripts)diff --git a/packages/wildos-rdp/debian/changelog b/packages/wildos-rdp/debian/changelognew file mode 100644index 0000000..a35e7e6--- /dev/null+++ b/packages/wildos-rdp/debian/changelog@@ -0,0 +1,168 @@+wildos-rdp (0.1.11) trixie; urgency=medium++ * The engine is a library Remote shares, with a whole-desktop session+ beside the app windows. It now links Qt Network, for the time a+ desktop tab takes to reach its computer.+ * App windows and desktops send the keyboard, mouse and wheel through+ the same code, so a fix to one reaches both.++ -- Wild OS Developers <[email protected]> Tue, 10 Nov 2026 07:45:00 +0000++wildos-rdp (0.1.10) trixie; urgency=medium++ * A loading window whose program ended before showing any window (it+ crashed, or gave up) says so: "X closed before it opened", with Try+ again and Close, instead of waiting as if it were still opening. The+ agent tells it, from what wild-guest sees in Windows.++ -- Wild OS Developers <[email protected]> Mon, 09 Nov 2026 23:30:00 +0000++wildos-rdp (0.1.9) trixie; urgency=medium++ * --prepare-session signs in to Windows and leaves the session ready and+ disconnected, asking for no app, so the first app opened later takes+ over a session that is already there: about 3 seconds less, measured.+ * Every step of a connection is logged with its time (connected, app+ channel ready, Windows' windows sent, app asked for and started, first+ window), for working out where a slow open spends its time.++ -- Wild OS Developers <[email protected]> Mon, 09 Nov 2026 23:00:00 +0000++wildos-rdp (0.1.8) trixie; urgency=medium++ * Programs with nothing to lose (Explorer, Character Map, Calculator,+ Settings and a few more) leave the screen the moment they are closed.+ Explorer redraws a folder window as it closes and can take seconds to+ end it; that read as a question, so the window stayed up meanwhile.+ * A window Windows disables after its close has a modal question up: it+ stays, or comes back if it was already hidden.++ -- Wild OS Developers <[email protected]> Mon, 09 Nov 2026 22:00:00 +0000++wildos-rdp (0.1.7) trixie; urgency=medium++ * Only the connection's own loading window ignores the windows Windows+ sends first on connecting: an app opened in the session while the+ connection was starting can be among them, and its loading window+ takes it (it opened separately, with the generic W).+ * A window's program, once Windows names it, always replaces the generic+ W as its app id.+ * An app that opens before its loading window was due (board 9.12) gets+ its program's app id when the loading window did not know its app,+ not the generic W.++ -- Wild OS Developers <[email protected]> Mon, 09 Nov 2026 21:30:00 +0000++wildos-rdp (0.1.6) trixie; urgency=medium++ * Where each app was last placed is saved again: the KWin script's+ numbers reached SavePlacement as doubles, which the method did not+ take, so no place was ever kept.+ * A window of a program Windows mode has no entry for, taken by a loading+ window that did not know its app, gets its program's own app id+ instead of keeping the generic W.+ * Opening a program Windows mode has no entry for shows the loading+ window too, named after the program.+ * Closing the loading window means no: the app's window, if Windows+ starts it anyway within two minutes, is closed as it comes instead of+ appearing after the person said no. Closing it while it is handing+ over to the app closes the app (it did nothing before).+ * A reconnection no longer opens a second copy of the connection's first+ app: FreeRDP asked Windows for it again every time it reconnected.+ * Windows that were already open when a connection began never take a+ loading window or end one: on connecting, Windows first sends every+ window already open (an app the last connection left), and one of+ those took the loading window of the app being opened, which then+ opened on its own. Windows marks the end of that first list.+ * A window closed while it was still taking over from its loading window+ ends that loading window; it waited again and took the next launch's+ window.++ -- Wild OS Developers <[email protected]> Mon, 09 Nov 2026 20:50:00 +0000++wildos-rdp (0.1.5) trixie; urgency=medium++ * A loading window that takes its app's size (a fixed dialog, or an app+ that kept its own size) changes size about its centre: KWin moves and+ resizes it in one step. Without KWin it resizes from its corner as+ before.+ * A loading window that knows its program is never taken by a window+ whose program Windows has not named (a window another app left open,+ sent again on reconnecting); a window named too late to be taken makes+ the loading window give way.++ -- Wild OS Developers <[email protected]> Mon, 09 Nov 2026 20:30:00 +0000++wildos-rdp (0.1.4) trixie; urgency=medium++ * The loading window hands over as soon as the app has drawn, whether or+ not the app takes the loading window's size. A window Windows will not+ resize (Character Map) gives the loading window its own size as it+ arrives, and is remembered at it for next time.+ * A window that draws nothing is shown after 4 seconds anyway; a window+ of the app's program the loading window did not take (a first-run+ question) makes it give way; a window owned by another program whose+ title names the app is taken. The slow state only ever means Windows+ itself is slow.+ * The light keeps running its laps in the slow state, so it never looks+ hung. Reduced motion still shows a still frame.+ * The fade from the loading window into the app is finished by the+ clock as well as by the compositor's frames, so a lost frame can no+ longer leave the app half faded in.++ -- Wild OS Developers <[email protected]> Mon, 09 Nov 2026 19:30:00 +0000++wildos-rdp (0.1.3) trixie; urgency=medium++ * Closing without flicker: a closed window stays exactly as it is+ while Windows deals with it. Gone within half a second: it simply+ goes. Drawing again or opening a dialog: it is asking, and stays. No+ word from Windows at all: it leaves the screen and the taskbar after+ half a second, and is handled in the background as before.+ * Alt+F4 no longer leaves Windows' key tips or menu open behind it.+ * Popups Windows draws with transparency (rounded menus, key tips) keep+ it instead of showing black corners.++ -- Wild OS Developers <[email protected]> Mon, 09 Nov 2026 18:30:00 +0000++wildos-rdp (0.1.2) trixie; urgency=medium++ * Closing is ours to show at once: a window closed from the taskbar or+ with Alt+F4 leaves the screen and the taskbar in the same frame, and+ Windows is told in the background. A question it asks before closing+ (Save changes?) is shown straight away, and the window comes back if+ the answer is not to close; one that asks inside itself (Windows 11's+ Paint and Notepad) keeps drawing, and comes back for the answer. A+ window Windows does not close stays+ hidden: with unsaved changes it is kept and a notification offers to+ show it; with none, the agent ends its program after 10 seconds.+ * Windows of a dropped connection leave the screen after 2 seconds of+ trying to reconnect, and come back when it does.+ * A loading window closes when the app was already open and Windows+ only brought its window forward.+ * Leaving never waits for a FreeRDP call that does not return.++ -- Wild OS Developers <[email protected]> Mon, 09 Nov 2026 18:00:00 +0000++wildos-rdp (0.1.1) trixie; urgency=medium++ * The loading window goes to the first window of the app's own program,+ asked of Windows, not to whichever window comes first; a window that is+ hidden or cloaked before the app shows in it hands the loading window+ back, so none is ever left on the taskbar.+ * Windows' cloaked windows stay off screen.+ * Every window of an app's program takes the app's id; a window nothing+ is known about gets its program's own id and the icon Windows sends,+ never Windows mode's W.+ * One log line for every decision about a window, for testing on real+ hardware.++ -- Wild OS Developers <[email protected]> Mon, 09 Nov 2026 17:30:00 +0000++wildos-rdp (0.1.0) trixie; urgency=medium++ * First version: RemoteApp windows as native Wayland windows, the+ loading window with the Wild OS mark, and org.wildos.RemoteApp for the+ Windows mode agent.++ -- Wild OS Developers <[email protected]> Mon, 09 Nov 2026 16:00:00 +0000diff --git a/packages/wildos-rdp/debian/control b/packages/wildos-rdp/debian/controlnew file mode 100644index 0000000..d5bd83c--- /dev/null+++ b/packages/wildos-rdp/debian/control@@ -0,0 +1,32 @@+Source: wildos-rdp+Section: x11+Priority: optional+Maintainer: Wild OS Developers <[email protected]>+Build-Depends:+ debhelper-compat (= 13),+ cmake,+ pkgconf,+ qt6-base-dev,+ qt6-base-private-dev,+ libwayland-dev,+ wayland-protocols,+ libkf6config-dev,+ libkf6windowsystem-dev,+ freerdp3-dev (>= 3.32),+ libwinpr3-dev (>= 3.32),+Standards-Version: 4.7.0+Rules-Requires-Root: no++Package: wildos-rdp+Architecture: any+Depends:+ ${shlibs:Depends},+ ${misc:Depends},+ libfreerdp3-3 (>= 3.32),+ libfreerdp-client3-3 (>= 3.32),+ qt6-wayland,+Description: Wild OS window client for Windows mode+ Shows each Windows app from Windows mode as a window of its own on the+ Wild OS desktop, drawn at the screen's own scale, with copy and paste,+ sound and the shared folders. While Windows wakes, the window is already+ there with the Wild OS mark in it.diff --git a/packages/wildos-rdp/debian/rules b/packages/wildos-rdp/debian/rulesnew file mode 100644index 0000000..567eb2c--- /dev/null+++ b/packages/wildos-rdp/debian/rules@@ -0,0 +1,7 @@+#!/usr/bin/make -f++%:+ dh $@++override_dh_auto_configure:+ dh_auto_configure -- -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_LIBEXECDIR=libexecdiff --git a/packages/wildos-rdp/debian/source/format b/packages/wildos-rdp/debian/source/formatnew file mode 100644index 0000000..89ae9db--- /dev/null+++ b/packages/wildos-rdp/debian/source/format@@ -0,0 +1 @@+3.0 (native)diff --git a/packages/wildos-rdp/engine.cmake b/packages/wildos-rdp/engine.cmakenew file mode 100644index 0000000..d7d97c4--- /dev/null+++ b/packages/wildos-rdp/engine.cmake@@ -0,0 +1,28 @@+# The Remote Desktop engine, shared by Windows mode's window client+# (wildos-rdp) and the Remote app (wildos-remote): the FreeRDP connection+# and its graphics pipeline, clipboard, sound and drives, reconnecting,+# keyboard layout and input, and the whole-desktop session.+#+# include() it from either package; it adds the static library+# wildos-rdp-engine, with its headers on the include path.++set(WILDOS_RDP_ENGINE_DIR ${CMAKE_CURRENT_LIST_DIR})++find_package(Qt6 6.8 REQUIRED COMPONENTS Core Gui Network)+find_package(PkgConfig REQUIRED)+# 3.32 is the first FreeRDP that drew RemoteApp windows properly on Wild OS+# hardware; 3.15 drew only the first frame of each window.+pkg_check_modules(FREERDP REQUIRED IMPORTED_TARGET freerdp3>=3.32 freerdp-client3>=3.32 winpr3>=3.32)++add_library(wildos-rdp-engine STATIC+ ${WILDOS_RDP_ENGINE_DIR}/src/client.cpp ${WILDOS_RDP_ENGINE_DIR}/src/client.h+ ${WILDOS_RDP_ENGINE_DIR}/src/clipboard.cpp ${WILDOS_RDP_ENGINE_DIR}/src/clipboard.h+ ${WILDOS_RDP_ENGINE_DIR}/src/keymap.cpp ${WILDOS_RDP_ENGINE_DIR}/src/keymap.h+ ${WILDOS_RDP_ENGINE_DIR}/src/input.cpp ${WILDOS_RDP_ENGINE_DIR}/src/input.h+ ${WILDOS_RDP_ENGINE_DIR}/src/desktop.cpp ${WILDOS_RDP_ENGINE_DIR}/src/desktop.h+)+set_target_properties(wildos-rdp-engine PROPERTIES AUTOMOC ON POSITION_INDEPENDENT_CODE ON)+target_include_directories(wildos-rdp-engine PUBLIC ${WILDOS_RDP_ENGINE_DIR}/src)+# Nothing here may lean on API FreeRDP has already marked for removal.+target_compile_definitions(wildos-rdp-engine PUBLIC WITHOUT_FREERDP_3x_DEPRECATED)+target_link_libraries(wildos-rdp-engine PUBLIC Qt6::Gui Qt6::Network PkgConfig::FREERDP)diff --git a/packages/wildos-rdp/kwin/org.wildos.rdp.place/contents/ui/main.qml b/packages/wildos-rdp/kwin/org.wildos.rdp.place/contents/ui/main.qmlnew file mode 100644index 0000000..a51c4e1--- /dev/null+++ b/packages/wildos-rdp/kwin/org.wildos.rdp.place/contents/ui/main.qml@@ -0,0 +1,119 @@+import QtQuick+import org.kde.kwin as KWin++// A Windows app opens where it was last time (board 9.11). Wayland leaves+// placing windows to the compositor, so this script does it for wildos-rdp:+// the client keeps each app's place between sessions (Placements and+// SavePlacement on org.wildos.RemoteApp), and this puts the app's first+// window there as it opens and reports where it is moved to.+Item {+ id: root++ property var places: ({})+ property bool loaded: false+ property var waiting: []++ function appOf(window) {+ const id = String(window.desktopFileName || window.resourceClass || "");+ // Windows apps the agent knows (wildos-winmode-*) and ones it does+ // not (windows-*, named after their program by wildos-rdp).+ return id.startsWith("wildos-winmode-") || id.startsWith("windows-") ? id : "";+ }++ function placeable(window) {+ return window && !window.deleted && window.normalWindow && !window.transient && root.appOf(window) !== "";+ }++ function openFor(app, except) {+ return KWin.Workspace.windows.some(w => w !== except && !w.deleted && root.appOf(w) === app && w.normalWindow);+ }++ Component {+ id: callComponent+ KWin.DBusCall {+ service: "org.wildos.RemoteApp"+ path: "/org/wildos/RemoteApp"+ dbusInterface: "org.wildos.RemoteApp"+ }+ }++ function call(method, args, done) {+ const c = callComponent.createObject(root, { method: method, arguments: args });+ c.finished.connect(values => {+ if (done) {+ done(values);+ }+ c.destroy();+ });+ c.failed.connect(() => c.destroy());+ c.call();+ }++ function place(window) {+ const p = root.places[root.appOf(window)];+ if (!p || root.openFor(root.appOf(window), window)) {+ return;+ }+ const g = window.frameGeometry;+ let x = p.x;+ let y = p.y;+ // Never off screen: a monitor that has gone since brings it back.+ const area = KWin.Workspace.clientArea(KWin.Workspace.PlacementArea, window);+ if (area && area.width > 0) {+ x = Math.max(area.x, Math.min(x, area.x + area.width - Math.min(g.width, area.width)));+ y = Math.max(area.y, Math.min(y, area.y + area.height - Math.min(g.height, area.height)));+ }+ window.frameGeometry = Qt.rect(x, y, g.width, g.height);+ }++ function remember(window) {+ if (!root.placeable(window)) {+ return;+ }+ const g = window.frameGeometry;+ const app = root.appOf(window);+ root.places[app] = { x: Math.round(g.x), y: Math.round(g.y) };+ root.call("SavePlacement", [app, Math.round(g.x), Math.round(g.y)]);+ }++ function track(window) {+ window.frameGeometryChanged.connect(() => {+ if (window.move || window.resize || window.deleted) {+ return;+ }+ Qt.callLater(() => root.remember(window));+ });+ window.interactiveMoveResizeFinished.connect(() => root.remember(window));+ }++ Connections {+ target: KWin.Workspace++ function onWindowAdded(window) {+ if (!root.placeable(window)) {+ return;+ }+ root.track(window);+ if (root.loaded) {+ root.place(window);+ return;+ }+ root.waiting.push(window);+ root.call("Placements", [], values => {+ try {+ root.places = JSON.parse(values[0]);+ } catch (e) {+ root.places = {};+ }+ root.loaded = true;+ const pending = root.waiting;+ root.waiting = [];+ pending.forEach(w => {+ if (!w.deleted) {+ root.place(w);+ }+ });+ });+ }+ }+}diff --git a/packages/wildos-rdp/kwin/org.wildos.rdp.place/metadata.json b/packages/wildos-rdp/kwin/org.wildos.rdp.place/metadata.jsonnew file mode 100644index 0000000..fd2cacf--- /dev/null+++ b/packages/wildos-rdp/kwin/org.wildos.rdp.place/metadata.json@@ -0,0 +1,20 @@+{+ "KPackageStructure": "KWin/Script",+ "KPlugin": {+ "Authors": [+ {+ "Email": "[email protected]",+ "Name": "Wild OS"+ }+ ],+ "Description": "Opens each Windows app where it was last time",+ "EnabledByDefault": true,+ "Id": "org.wildos.rdp.place",+ "License": "GPL-3.0-or-later",+ "Name": "Windows app places",+ "Version": "0.1.0",+ "Website": "https://wildos.io"+ },+ "X-Plasma-API": "declarativescript",+ "X-Plasma-MainScript": "ui/main.qml"+}diff --git a/packages/wildos-rdp/src/client.cpp b/packages/wildos-rdp/src/client.cppnew file mode 100644index 0000000..0d70ae9--- /dev/null+++ b/packages/wildos-rdp/src/client.cpp@@ -0,0 +1,998 @@+#include "client.h"+#include "clipboard.h"+#include "keymap.h"++#include <QDebug>+#include <QMetaObject>++#include <freerdp/channels/channels.h>+#include <freerdp/client/channels.h>+#include <freerdp/client/cliprdr.h>+#include <freerdp/client/cmdline.h>+#include <freerdp/codec/color.h>+#include <freerdp/codec/region.h>+#include <freerdp/gdi/gdi.h>+#include <freerdp/gdi/gfx.h>+#include <freerdp/graphics.h>+#include <freerdp/rail.h>+#include <freerdp/window.h>+#include <winpr/synch.h>++#include <QElapsedTimer>++#include <cstring>+#include <vector>++namespace+{+// Where the time goes when an app opens: one line per step of the+// connection, in milliseconds since it began (launch-stats reads them).+QElapsedTimer connectClock;+bool firstOf[9] = {};++void step(int which, const char *what)+{+ if (which >= 0 && which < 9) {+ if (firstOf[which]) {+ return;+ }+ firstOf[which] = true;+ }+ qInfo("wildos-rdp: step %s at %lld ms", what, connectClock.isValid() ? qint64(connectClock.elapsed()) : -1);+}++Client *clientOf(rdpContext *context)+{+ return reinterpret_cast<WrdpContext *>(context)->client;+}++// The pointer FreeRDP keeps for each Windows cursor, with the picture made+// from it once.+struct Pointer {+ rdpPointer pointer;+ QImage *image;+};++QString utf8(const RAIL_UNICODE_STRING &s)+{+ char *text = rail_string_to_utf8_string(&s);+ const QString out = QString::fromUtf8(text ? text : "");+ free(text);+ return out;+}++QImage iconImage(const ICON_INFO *info)+{+ if (!info || info->width == 0 || info->height == 0 || info->width > 256 || info->height > 256) {+ return {};+ }+ QImage image(int(info->width), int(info->height), QImage::Format_ARGB32);+ if (!freerdp_image_copy_from_icon_data(image.bits(), PIXEL_FORMAT_BGRA32, UINT32(image.bytesPerLine()), 0, 0, UINT16(info->width),+ UINT16(info->height), info->bitsColor, UINT16(info->cbBitsColor), info->bitsMask,+ UINT16(info->cbBitsMask), info->colorTable, UINT16(info->cbColorTable), info->bpp)) {+ return {};+ }+ return image;+}++QRegion regionOf(const REGION16 *region)+{+ UINT32 n = 0;+ const RECTANGLE_16 *rects = region16_rects(region, &n);+ QRegion out;+ for (UINT32 i = 0; i < n; ++i) {+ out += QRect(rects[i].left, rects[i].top, rects[i].right - rects[i].left, rects[i].bottom - rects[i].top);+ }+ return out;+}+}++// FreeRDP's callbacks. They run on FreeRDP's threads: the connection's for+// window orders and drawing, a channel's own for channel messages.+struct ClientCallbacks {+ static BOOL clientNew(freerdp *instance, rdpContext *)+ {+ instance->PreConnect = preConnect;+ instance->PostConnect = postConnect;+ instance->PostDisconnect = postDisconnect;+ instance->AuthenticateEx = authenticate;+ instance->VerifyCertificateEx = verifyCertificate;+ instance->VerifyChangedCertificateEx = verifyChangedCertificate;+ instance->LogonErrorInfo = logonErrorInfo;+ instance->RetryDialog = retryDialog;+ instance->PresentGatewayMessage = nullptr;+ return TRUE;+ }++ static void clientFree(freerdp *, rdpContext *)+ {+ }++ static int clientStart(rdpContext *)+ {+ return 0;+ }++ static int clientStop(rdpContext *)+ {+ return 0;+ }++ static BOOL preConnect(freerdp *instance)+ {+ step(0, "connecting");+ rdpContext *context = instance->context;+ rdpSettings *settings = context->settings;+ Client *self = clientOf(context);+ if (!freerdp_settings_set_uint32(settings, FreeRDP_OsMajorType, OSMAJORTYPE_UNIX)+ || !freerdp_settings_set_uint32(settings, FreeRDP_OsMinorType, OSMINORTYPE_NATIVE_WAYLAND)) {+ return FALSE;+ }+ if (PubSub_SubscribeChannelConnected(context->pubSub, channelConnected) < 0+ || PubSub_SubscribeChannelDisconnected(context->pubSub, channelDisconnected) < 0) {+ return FALSE;+ }+ // Windows lays its apps out on a desktop the size of the screen in+ // physical pixels, at the screen's own scale, so every pixel it+ // sends is one on the screen.+ if (self->m_physical.isValid()) {+ (void)freerdp_settings_set_uint32(settings, FreeRDP_DesktopWidth, UINT32(self->m_physical.width()));+ (void)freerdp_settings_set_uint32(settings, FreeRDP_DesktopHeight, UINT32(self->m_physical.height()));+ }+ const UINT32 percent = UINT32(qBound(100.0, self->m_scale * 100.0 + 0.5, 500.0));+ const UINT32 device = self->m_scale >= 1.6 ? 180 : self->m_scale >= 1.2 ? 140 : 100;+ (void)freerdp_settings_set_uint32(settings, FreeRDP_DesktopScaleFactor, percent);+ (void)freerdp_settings_set_uint32(settings, FreeRDP_DeviceScaleFactor, device);+ if (freerdp_settings_get_uint32(settings, FreeRDP_KeyboardLayout) == 0) {+ if (const uint32_t layout = keymap::windowsLayout()) {+ (void)freerdp_settings_set_uint32(settings, FreeRDP_KeyboardLayout, layout);+ }+ }+ (void)freerdp_settings_set_bool(settings, FreeRDP_RemoteAppLanguageBarSupported, FALSE);+ // Which process a window belongs to (its image name), so the window an+ // app being opened shows is told apart from every other window.+ (void)freerdp_settings_set_uint32(settings, FreeRDP_RemoteAppFeatureFlags,+ freerdp_settings_get_uint32(settings, FreeRDP_RemoteAppFeatureFlags)+ | TS_RAIL_CLIENTSTATUS_GET_APPID_RESPONSE_EX_SUPPORTED);+ // Text has to stay sharp: the graphics pipeline with its exact+ // codecs, not video compression, which smears small type and costs+ // the most to decode.+ (void)freerdp_settings_set_bool(settings, FreeRDP_SupportGraphicsPipeline, TRUE);+ (void)freerdp_settings_set_bool(settings, FreeRDP_GfxH264, FALSE);+ (void)freerdp_settings_set_bool(settings, FreeRDP_GfxAVC444, FALSE);+ (void)freerdp_settings_set_bool(settings, FreeRDP_GfxAVC444v2, FALSE);+ return TRUE;+ }++ static BOOL postConnect(freerdp *instance)+ {+ step(1, "connected (signed in, session ready)");+ rdpContext *context = instance->context;+ Client *self = clientOf(context);+ if (!gdi_init(instance, PIXEL_FORMAT_BGRA32)) {+ return FALSE;+ }+ rdpPointer pointer = {};+ pointer.size = sizeof(Pointer);+ pointer.New = pointerNew;+ pointer.Free = pointerFree;+ pointer.Set = pointerSet;+ pointer.SetNull = pointerSetNull;+ pointer.SetDefault = pointerSetDefault;+ pointer.SetPosition = pointerSetPosition;+ graphics_register_pointer(context->graphics, &pointer);++ context->update->BeginPaint = beginPaint;+ context->update->EndPaint = endPaint;+ context->update->DesktopResize = desktopResize;+ context->update->PlaySound = playSound;+ Q_EMIT self->connected();+ return TRUE;+ }++ static void postDisconnect(freerdp *instance)+ {+ gdi_free(instance);+ }++ static BOOL authenticate(freerdp *instance, char **username, char **password, char **, rdp_auth_reason)+ {+ // There is nobody to ask: the account and password come with the+ // arguments, and a session without them must fail, not prompt.+ Q_UNUSED(instance);+ return username && *username && **username && password && *password && **password;+ }++ static DWORD verifyCertificate(freerdp *, const char *host, UINT16, const char *, const char *, const char *, const char *, DWORD)+ {+ // /cert:tofu accepts and remembers a certificate seen for the first+ // time before ever asking; anything that reaches here is refused.+ qWarning("wildos-rdp: refused the certificate of %s", host);+ return 0;+ }++ static DWORD verifyChangedCertificate(freerdp *, const char *host, UINT16, const char *, const char *, const char *, const char *,+ const char *, const char *, const char *, DWORD)+ {+ qWarning("wildos-rdp: %s presented a different certificate from the one it had; refused", host);+ return 0;+ }++ static int logonErrorInfo(freerdp *, UINT32 data, UINT32 type)+ {+ qInfo("wildos-rdp: logon %s [%s] at %lld ms", freerdp_get_logon_error_info_data(data), freerdp_get_logon_error_info_type(type),+ connectClock.isValid() ? qint64(connectClock.elapsed()) : -1);+ return 1;+ }++ static SSIZE_T retryDialog(freerdp *, const char *what, size_t current, void *)+ {+ // Windows is on this PC: a dropped connection is back within a+ // second or two, or not at all.+ qInfo("wildos-rdp: reconnecting %s, attempt %zu", what, current + 1);+ return current < 2 ? 500 : 2000;+ }++ static void channelConnected(void *ctx, const ChannelConnectedEventArgs *e)+ {+ if (qEnvironmentVariableIsSet("WILDOS_RDP_DEBUG")) {+ qInfo("channel %s connected", e->name);+ }+ auto *context = static_cast<rdpContext *>(ctx);+ Client *self = clientOf(context);+ if (strcmp(e->name, RAIL_SVC_CHANNEL_NAME) == 0) {+ step(2, "app channel open");+ auto *rail = static_cast<RailClientContext *>(e->pInterface);+ rail->custom = self;+ rail->ServerExecuteResult = execResult;+ rail->ServerHandshake = serverHandshake;+ rail->ServerHandshakeEx = serverHandshakeEx;+ rail->ServerLocalMoveSize = localMoveSize;+ rail->ServerMinMaxInfo = minMaxInfo;+ rail->ServerSystemParam = serverSystemParam;+ rail->ServerCloak = serverCloak;+ rail->ServerGetAppidResponseExtended = appIdResponse;+ rdpWindowUpdate *window = context->update->window;+ window->WindowCreate = windowOrder;+ window->WindowUpdate = windowOrder;+ window->WindowIcon = windowIcon;+ window->WindowCachedIcon = windowCachedIcon;+ window->WindowDelete = windowDelete;+ window->MonitoredDesktop = monitoredDesktop;+ window->NonMonitoredDesktop = nonMonitoredDesktop;+ std::lock_guard lock(self->m_channels);+ self->m_rail = rail;+ } else if (strcmp(e->name, CLIPRDR_SVC_CHANNEL_NAME) == 0) {+ self->m_clipboard->attach(static_cast<CliprdrClientContext *>(e->pInterface));+ } else if (strcmp(e->name, RDPGFX_DVC_CHANNEL_NAME) == 0) {+ freerdp_client_OnChannelConnectedEventHandler(ctx, e);+ auto *gfx = static_cast<RdpgfxClientContext *>(e->pInterface);+ gfx->UpdateWindowFromSurface = updateWindowFromSurface;+ if (qEnvironmentVariableIsSet("WILDOS_RDP_DEBUG")) {+ watchGfx(gfx);+ }+ std::lock_guard lock(self->m_channels);+ self->m_gfx = gfx;+ } else {+ freerdp_client_OnChannelConnectedEventHandler(ctx, e);+ }+ }++ static void channelDisconnected(void *ctx, const ChannelDisconnectedEventArgs *e)+ {+ auto *context = static_cast<rdpContext *>(ctx);+ Client *self = clientOf(context);+ if (strcmp(e->name, RAIL_SVC_CHANNEL_NAME) == 0) {+ std::lock_guard lock(self->m_channels);+ self->m_rail = nullptr;+ } else if (strcmp(e->name, CLIPRDR_SVC_CHANNEL_NAME) == 0) {+ self->m_clipboard->detach(static_cast<CliprdrClientContext *>(e->pInterface));+ } else if (strcmp(e->name, RDPGFX_DVC_CHANNEL_NAME) == 0) {+ {+ std::lock_guard lock(self->m_channels);+ self->m_gfx = nullptr;+ }+ freerdp_client_OnChannelDisconnectedEventHandler(ctx, e);+ } else {+ freerdp_client_OnChannelDisconnectedEventHandler(ctx, e);+ }+ }++ static BOOL beginPaint(rdpContext *context)+ {+ rdpGdi *gdi = context->gdi;+ gdi->primary->hdc->hwnd->invalid->null = TRUE;+ gdi->primary->hdc->hwnd->ninvalid = 0;+ return TRUE;+ }++ static BOOL endPaint(rdpContext *context)+ {+ rdpGdi *gdi = context->gdi;+ HGDI_WND hwnd = gdi->primary->hdc->hwnd;+ if (hwnd->invalid->null || hwnd->ninvalid <= 0) {+ return TRUE;+ }+ QRegion damage;+ for (INT32 i = 0; i < hwnd->ninvalid; ++i) {+ const GDI_RGN &r = hwnd->cinvalid[i];+ damage += QRect(r.x, r.y, r.w, r.h);+ }+ clientOf(context)->queuePrimaryDamage(damage);+ return TRUE;+ }++ static BOOL desktopResize(rdpContext *context)+ {+ return gdi_resize(context->gdi, freerdp_settings_get_uint32(context->settings, FreeRDP_DesktopWidth),+ freerdp_settings_get_uint32(context->settings, FreeRDP_DesktopHeight));+ }++ static BOOL playSound(rdpContext *, const PLAY_SOUND_UPDATE *)+ {+ return TRUE;+ }++ static UINT execResult(RailClientContext *rail, const RAIL_EXEC_RESULT_ORDER *result)+ {+ auto *self = static_cast<Client *>(rail->custom);+ step(5, "app started");+ if (result->execResult != RAIL_EXEC_S_OK) {+ qWarning("wildos-rdp: Windows could not start the app (result %u, %u)", unsigned(result->execResult), unsigned(result->rawResult));+ Q_EMIT self->execFailed(result->execResult);+ freerdp_abort_connect_context(self->m_context);+ }+ return CHANNEL_RC_OK;+ }++ static UINT localMoveSize(RailClientContext *rail, const RAIL_LOCALMOVESIZE_ORDER *order)+ {+ auto *self = static_cast<Client *>(rail->custom);+ Q_EMIT self->localMoveSize(order->windowId, order->isMoveSizeStart, order->moveSizeType, order->posX, order->posY);+ return CHANNEL_RC_OK;+ }++ static UINT minMaxInfo(RailClientContext *rail, const RAIL_MINMAXINFO_ORDER *info)+ {+ auto *self = static_cast<Client *>(rail->custom);+ Q_EMIT self->minMaxInfo(info->windowId, QSize(info->minTrackWidth, info->minTrackHeight), QSize(info->maxTrackWidth, info->maxTrackHeight));+ return CHANNEL_RC_OK;+ }++ static UINT serverSystemParam(RailClientContext *, const RAIL_SYSPARAM_ORDER *)+ {+ return CHANNEL_RC_OK;+ }++ static UINT serverCloak(RailClientContext *rail, const RAIL_CLOAK *cloak)+ {+ // Windows hides windows it is still preparing (cloaks them) rather+ // than leaving them unshown; FreeRDP tells Windows its clients follow+ // this, so a cloaked window must not be on screen here either.+ auto *self = static_cast<Client *>(rail->custom);+ Q_EMIT self->windowCloaked(cloak->windowId, cloak->cloak);+ return CHANNEL_RC_OK;+ }++ static UINT appIdResponse(RailClientContext *rail, const RAIL_GET_APPID_RESP_EX *id)+ {+ auto *self = static_cast<Client *>(rail->custom);+ const QString image = QString::fromUtf16(reinterpret_cast<const char16_t *>(id->processImageName));+ const QString appUserModel = QString::fromUtf16(reinterpret_cast<const char16_t *>(id->applicationID));+ Q_EMIT self->windowProcess(id->windowID, image, appUserModel, id->processId);+ return CHANNEL_RC_OK;+ }++ static BOOL windowOrder(rdpContext *context, const WINDOW_ORDER_INFO *info, const WINDOW_STATE_ORDER *state)+ {+ if ((info->fieldFlags & WINDOW_ORDER_STATE_NEW) && (info->fieldFlags & WINDOW_ORDER_FIELD_SHOW) && state->showState != 0+ && state->windowWidth >= 160 && state->windowHeight >= 100) {+ step(6, "first window from Windows");+ }+ RailOrder o;+ o.id = info->windowId;+ o.fields = info->fieldFlags;+ o.created = info->fieldFlags & WINDOW_ORDER_STATE_NEW;+ o.owner = state->ownerWindowId;+ o.style = state->style;+ o.exStyle = state->extendedStyle;+ o.showState = state->showState;+ if (info->fieldFlags & WINDOW_ORDER_FIELD_TITLE) {+ o.title = utf8(state->titleInfo);+ }+ o.offset = QPoint(state->windowOffsetX, state->windowOffsetY);+ o.size = QSize(int(state->windowWidth), int(state->windowHeight));+ o.clientOffset = QPoint(state->clientOffsetX, state->clientOffsetY);+ o.clientSize = QSize(int(state->clientAreaWidth), int(state->clientAreaHeight));+ o.visibleOffset = QPoint(state->visibleOffsetX, state->visibleOffsetY);+ o.resizeMargins = QMargins(int(state->resizeMarginLeft), int(state->resizeMarginTop), int(state->resizeMarginRight),+ int(state->resizeMarginBottom));+ if (info->fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY) {+ for (UINT32 i = 0; i < state->numVisibilityRects; ++i) {+ const RECTANGLE_16 &r = state->visibilityRects[i];+ o.visibility.append(QRect(r.left, r.top, r.right - r.left, r.bottom - r.top));+ }+ }+ Q_EMIT clientOf(context)->windowChanged(o);+ return TRUE;+ }++ static BOOL windowIcon(rdpContext *context, const WINDOW_ORDER_INFO *info, const WINDOW_ICON_ORDER *order)+ {+ Client *self = clientOf(context);+ const QImage image = iconImage(order->iconInfo);+ if (image.isNull()) {+ return TRUE;+ }+ if (order->iconInfo->cacheId != 0xFF) {+ self->m_icons.insert((order->iconInfo->cacheId << 16) | order->iconInfo->cacheEntry, image);+ }+ Q_EMIT self->windowIcon(info->windowId, image, info->fieldFlags & WINDOW_ORDER_FIELD_ICON_BIG);+ return TRUE;+ }++ static BOOL windowCachedIcon(rdpContext *context, const WINDOW_ORDER_INFO *info, const WINDOW_CACHED_ICON_ORDER *order)+ {+ Client *self = clientOf(context);+ const QImage image = self->m_icons.value((order->cachedIcon.cacheId << 16) | order->cachedIcon.cacheEntry);+ if (!image.isNull()) {+ Q_EMIT self->windowIcon(info->windowId, image, info->fieldFlags & WINDOW_ORDER_FIELD_ICON_BIG);+ }+ return TRUE;+ }++ static BOOL windowDelete(rdpContext *context, const WINDOW_ORDER_INFO *info)+ {+ Q_EMIT clientOf(context)->windowDeleted(info->windowId);+ return TRUE;+ }++ // Windows is told about this client (its status and settings) and asked+ // for the connection's app.+ static bool requestApp(Client *self, RailClientContext *rail)+ {+ // After a reconnection the session still has every app open: asking+ // for the first one again would open a second copy of it. Without a+ // program FreeRDP still sends the client's status and settings, and+ // only the request itself fails.+ const bool again = self->m_appRequested.exchange(true) || self->m_prepareOnly;+ rdpSettings *settings = self->m_context->settings;+ QByteArray program;+ if (again) {+ program = freerdp_settings_get_string(settings, FreeRDP_RemoteApplicationProgram);+ freerdp_settings_set_string(settings, FreeRDP_RemoteApplicationProgram, nullptr);+ }+ const UINT rc = client_rail_server_start_cmd(rail);+ if (again) {+ freerdp_settings_set_string(settings, FreeRDP_RemoteApplicationProgram, program.isEmpty() ? nullptr : program.constData());+ }+ if (rc != CHANNEL_RC_OK && !(again && rc == ERROR_INVALID_PARAMETER)) {+ qWarning("wildos-rdp: the app could not be asked for");+ return false;+ }+ return true;+ }++ // Only to time the step: FreeRDP's own answer is sent as before.+ static UINT serverHandshake(RailClientContext *rail, const RAIL_HANDSHAKE_ORDER *)+ {+ step(7, "app channel ready");+ auto *self = static_cast<Client *>(rail->custom);+ // FreeRDP's own answer, which a handler of this message replaces.+ const RAIL_HANDSHAKE_ORDER reply = {freerdp_settings_get_uint32(self->m_context->settings, FreeRDP_ClientBuild)};+ UINT rc = rail->ClientHandshake(rail, &reply);+ if (rc != CHANNEL_RC_OK) {+ return rc;+ }+ return CHANNEL_RC_OK;+ }++ static UINT serverHandshakeEx(RailClientContext *rail, const RAIL_HANDSHAKE_EX_ORDER *)+ {+ return serverHandshake(rail, nullptr);+ }++ static BOOL monitoredDesktop(rdpContext *context, const WINDOW_ORDER_INFO *info, const MONITORED_DESKTOP_ORDER *desktop)+ {+ Client *self = clientOf(context);+ if (info->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ARC_BEGAN) {+ step(3, "Windows sends its windows");+ }+ if (info->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ARC_COMPLETED) {+ step(4, "app asked for");+ Q_EMIT self->desktopSynced();+ // Windows is ready for RemoteApp: now the app is asked for. (Asking+ // at the channel's handshake instead gains nothing: this comes 15+ // ms after it, measured.)+ RailClientContext *rail = nullptr;+ {+ std::lock_guard lock(self->m_channels);+ rail = self->m_rail;+ }+ if (rail && !requestApp(self, rail)) {+ return FALSE;+ }+ }+ const bool hasZ = info->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ZORDER;+ const bool hasActive = info->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ACTIVE_WND;+ if (hasZ || hasActive) {+ QList<quint32> z;+ if (hasZ && desktop->windowIds) {+ z.reserve(qsizetype(desktop->numWindowIds));+ for (UINT32 i = 0; i < desktop->numWindowIds; ++i) {+ z.append(desktop->windowIds[i]);+ }+ }+ Q_EMIT self->desktopChanged(desktop->activeWindowId, hasActive, z, hasZ);+ }+ return TRUE;+ }++ static BOOL nonMonitoredDesktop(rdpContext *, const WINDOW_ORDER_INFO *)+ {+ return TRUE;+ }++ // With WILDOS_RDP_DEBUG: which surfaces Windows makes and which codecs it+ // draws them with, to see where memory and time go.+ static inline pcRdpgfxCreateSurface createSurface = nullptr;+ static inline pcRdpgfxDeleteSurface deleteSurface = nullptr;+ static inline pcRdpgfxSurfaceCommand surfaceCommand = nullptr;+ static inline QHash<quint32, quint64> codecBytes;++ static void watchGfx(RdpgfxClientContext *gfx)+ {+ createSurface = gfx->CreateSurface;+ deleteSurface = gfx->DeleteSurface;+ surfaceCommand = gfx->SurfaceCommand;+ gfx->CreateSurface = [](RdpgfxClientContext *c, const RDPGFX_CREATE_SURFACE_PDU *p) -> UINT {+ qInfo("gfx surface %u created %ux%u format %u", p->surfaceId, p->width, p->height, p->pixelFormat);+ return createSurface(c, p);+ };+ gfx->DeleteSurface = [](RdpgfxClientContext *c, const RDPGFX_DELETE_SURFACE_PDU *p) -> UINT {+ qInfo("gfx surface %u deleted", p->surfaceId);+ return deleteSurface(c, p);+ };+ gfx->SurfaceCommand = [](RdpgfxClientContext *c, const RDPGFX_SURFACE_COMMAND *cmd) -> UINT {+ quint64 &total = codecBytes[cmd->codecId];+ if (total == 0) {+ qInfo("gfx codec %u first used on surface %u", cmd->codecId, cmd->surfaceId);+ }+ total += cmd->length;+ return surfaceCommand(c, cmd);+ };+ }++ static UINT updateWindowFromSurface(RdpgfxClientContext *gfx, gdiGfxSurface *surface)+ {+ // Called with the pipeline's lock held, at the end of each frame.+ auto *gdi = static_cast<rdpGdi *>(gfx->custom);+ Client *self = clientOf(gdi->context);+ const QRegion damage = regionOf(&surface->invalidRegion);+ region16_clear(&surface->invalidRegion);+ const QSize size(int(surface->mappedWidth ? surface->mappedWidth : surface->width),+ int(surface->mappedHeight ? surface->mappedHeight : surface->height));+ if (!damage.isEmpty()) {+ self->queueSurfaceDamage(surface->windowId, surface->surfaceId, damage, size);+ }+ return CHANNEL_RC_OK;+ }++ static BOOL pointerNew(rdpContext *context, rdpPointer *p)+ {+ auto *pointer = reinterpret_cast<Pointer *>(p);+ pointer->image = nullptr;+ if (p->width == 0 || p->height == 0 || p->width > 384 || p->height > 384) {+ return TRUE;+ }+ auto *image = new QImage(int(p->width), int(p->height), QImage::Format_ARGB32);+ if (!freerdp_image_copy_from_pointer_data(image->bits(), PIXEL_FORMAT_BGRA32, UINT32(image->bytesPerLine()), 0, 0, p->width, p->height,+ p->xorMaskData, p->lengthXorMask, p->andMaskData, p->lengthAndMask, p->xorBpp,+ &context->gdi->palette)) {+ delete image;+ return FALSE;+ }+ pointer->image = image;+ return TRUE;+ }++ static void pointerFree(rdpContext *, rdpPointer *p)+ {+ auto *pointer = reinterpret_cast<Pointer *>(p);+ delete pointer->image;+ pointer->image = nullptr;+ }++ static BOOL pointerSet(rdpContext *context, rdpPointer *p)+ {+ auto *pointer = reinterpret_cast<Pointer *>(p);+ if (pointer->image) {+ Q_EMIT clientOf(context)->pointerImage(pointer->image->copy(), QPoint(int(p->xPos), int(p->yPos)));+ }+ return TRUE;+ }++ static BOOL pointerSetNull(rdpContext *context)+ {+ Q_EMIT clientOf(context)->pointerHidden();+ return TRUE;+ }++ static BOOL pointerSetDefault(rdpContext *context)+ {+ Q_EMIT clientOf(context)->pointerDefault();+ return TRUE;+ }++ static BOOL pointerSetPosition(rdpContext *, UINT32, UINT32)+ {+ // Windows may not move the person's pointer.+ return TRUE;+ }+};++Client::Client(QObject *parent)+ : QObject(parent)+ , m_clipboard(new Clipboard(this))+{+ qRegisterMetaType<RailOrder>();+ RDP_CLIENT_ENTRY_POINTS entry = {};+ entry.Version = RDP_CLIENT_INTERFACE_VERSION;+ entry.Size = sizeof(RDP_CLIENT_ENTRY_POINTS_V1);+ entry.ContextSize = sizeof(WrdpContext);+ entry.ClientNew = ClientCallbacks::clientNew;+ entry.ClientFree = ClientCallbacks::clientFree;+ entry.ClientStart = ClientCallbacks::clientStart;+ entry.ClientStop = ClientCallbacks::clientStop;+ m_context = freerdp_client_context_new(&entry);+ if (m_context) {+ reinterpret_cast<WrdpContext *>(m_context)->client = this;+ }+}++Client::~Client()+{+ stop();+ if (m_thread.joinable()) {+ m_thread.join();+ }+ if (m_context) {+ freerdp_client_context_free(m_context);+ }+}++rdpContext *Client::context() const+{+ return m_context;+}++bool Client::configure(const QList<QByteArray> &args, QString *error)+{+ if (!m_context) {+ *error = QStringLiteral("FreeRDP could not be set up");+ return false;+ }+ std::vector<QByteArray> storage;+ storage.reserve(size_t(args.size()) + 1);+ storage.push_back(QByteArrayLiteral("wildos-rdp"));+ for (const QByteArray &a : args) {+ storage.push_back(a);+ }+ std::vector<char *> argv;+ for (QByteArray &a : storage) {+ argv.push_back(a.data());+ }+ argv.push_back(nullptr);+ const int status = freerdp_client_settings_parse_command_line(m_context->settings, int(argv.size() - 1), argv.data(), FALSE);+ // The password was among them; FreeRDP keeps its own copy.+ for (QByteArray &a : storage) {+ a.fill('\0');+ }+ if (status != 0) {+ *error = QStringLiteral("the connection settings could not be read (%1)").arg(status);+ return false;+ }+ if (!freerdp_settings_get_bool(m_context->settings, FreeRDP_RemoteApplicationMode)) {+ *error = QStringLiteral("no app to open (/app is missing)");+ return false;+ }+ return true;+}++void Client::setDisplay(const QSize &physical, double scale)+{+ m_physical = physical;+ m_scale = scale;+}++QSize Client::desktopSize() const+{+ return QSize(int(freerdp_settings_get_uint32(m_context->settings, FreeRDP_DesktopWidth)),+ int(freerdp_settings_get_uint32(m_context->settings, FreeRDP_DesktopHeight)));+}++void Client::start()+{+ if (m_running || !m_context) {+ return;+ }+ m_running = true;+ connectClock.start();+ if (freerdp_client_start(m_context) != 0) {+ m_running = false;+ Q_EMIT finished(QStringLiteral("FREERDP_ERROR_START"), false);+ return;+ }+ m_thread = std::thread([this] { run(); });+}++void Client::stop()+{+ if (m_running && m_context) {+ m_stopping = true;+ freerdp_abort_connect_context(m_context);+ }+}++void Client::run()+{+ freerdp *instance = m_context->instance;+ QString error;+ bool authFailed = false;+ if (!freerdp_connect(instance)) {+ const UINT32 code = freerdp_get_last_error(m_context);+ error = QString::fromUtf8(freerdp_get_last_error_name(code));+ authFailed = code == FREERDP_ERROR_AUTHENTICATION_FAILED || code == FREERDP_ERROR_CONNECT_LOGON_FAILURE+ || code == FREERDP_ERROR_CONNECT_WRONG_PASSWORD || code == FREERDP_ERROR_CONNECT_ACCOUNT_RESTRICTION;+ qWarning("wildos-rdp: connection failed: %s: %s", qPrintable(error), freerdp_get_last_error_string(code));+ } else {+ while (!freerdp_shall_disconnect_context(m_context)) {+ HANDLE handles[MAXIMUM_WAIT_OBJECTS] = {};+ const DWORD count = freerdp_get_event_handles(m_context, handles, ARRAYSIZE(handles));+ if (count == 0) {+ break;+ }+ if (WaitForMultipleObjects(count, handles, FALSE, INFINITE) == WAIT_FAILED) {+ break;+ }+ if (!freerdp_check_event_handles(m_context)) {+ if (m_stopping) {+ break;+ }+ Q_EMIT connectionLost();+ if (client_auto_reconnect(instance)) {+ Q_EMIT connectionBack();+ continue;+ }+ const UINT32 code = freerdp_get_last_error(m_context);+ if (code != FREERDP_ERROR_SUCCESS) {+ error = QString::fromUtf8(freerdp_get_last_error_name(code));+ }+ break;+ }+ }+ const UINT32 info = freerdp_error_info(instance);+ if (error.isEmpty() && info != ERRINFO_SUCCESS && info != ERRINFO_LOGOFF_BY_USER && info != ERRINFO_RPC_INITIATED_DISCONNECT_BY_USER) {+ error = QString::fromUtf8(freerdp_get_error_info_name(info));+ }+ if (!error.isEmpty()) {+ qWarning("wildos-rdp: disconnected: %s", qPrintable(error));+ }+ }+ if (m_stopping) {+ // Ended here, on purpose: not a failure.+ error.clear();+ authFailed = false;+ }+ freerdp_disconnect(instance);+ (void)freerdp_client_stop(m_context);+ m_running = false;+ Q_EMIT finished(error, authFailed);+}++void Client::queueSurfaceDamage(quint64 windowId, quint16 surfaceId, const QRegion &damage, const QSize &size)+{+ std::lock_guard lock(m_damageLock);+ Damage &d = m_damage[windowId];+ if (d.surfaceId != surfaceId || d.size != size) {+ d.region = QRegion();+ }+ d.surfaceId = surfaceId;+ d.size = size;+ d.region += damage;+ if (!m_deliveryQueued) {+ m_deliveryQueued = true;+ QMetaObject::invokeMethod(this, &Client::deliverDamage, Qt::QueuedConnection);+ }+}++void Client::queuePrimaryDamage(const QRegion &damage)+{+ std::lock_guard lock(m_damageLock);+ m_primaryDamage += damage;+ if (!m_deliveryQueued) {+ m_deliveryQueued = true;+ QMetaObject::invokeMethod(this, &Client::deliverDamage, Qt::QueuedConnection);+ }+}++void Client::deliverDamage()+{+ QHash<quint64, Damage> damage;+ QRegion primary;+ {+ std::lock_guard lock(m_damageLock);+ damage.swap(m_damage);+ primary.swap(m_primaryDamage);+ m_deliveryQueued = false;+ }+ for (auto it = damage.cbegin(); it != damage.cend(); ++it) {+ Q_EMIT surfaceDamaged(it.key(), it->surfaceId, it->region, it->size);+ }+ if (!primary.isEmpty()) {+ Q_EMIT primaryDamaged(primary);+ }+}++bool Client::withSurface(quint16 surfaceId, const std::function<void(const uchar *, int, QSize)> &paint)+{+ std::lock_guard lock(m_channels);+ if (!m_gfx) {+ return false;+ }+ EnterCriticalSection(&m_gfx->mux);+ auto *surface = static_cast<gdiGfxSurface *>(m_gfx->GetSurfaceData(m_gfx, surfaceId));+ if (surface && surface->data) {+ const QSize size(int(surface->mappedWidth ? surface->mappedWidth : surface->width),+ int(surface->mappedHeight ? surface->mappedHeight : surface->height));+ paint(surface->data, int(surface->scanline), size);+ }+ LeaveCriticalSection(&m_gfx->mux);+ return surface != nullptr;+}++bool Client::withPrimary(const std::function<void(const uchar *, int, QSize)> &paint)+{+ rdpGdi *gdi = m_context ? m_context->gdi : nullptr;+ if (!gdi || !gdi->primary_buffer) {+ return false;+ }+ rdp_update_lock(m_context->update);+ paint(gdi->primary_buffer, int(gdi->stride), QSize(gdi->width, gdi->height));+ rdp_update_unlock(m_context->update);+ return true;+}++void Client::sendMouse(quint16 flags, int x, int y)+{+ if (m_running) {+ (void)freerdp_client_send_button_event(reinterpret_cast<rdpClientContext *>(m_context), FALSE, flags, x, y);+ }+}++void Client::sendExtendedMouse(quint16 flags, int x, int y)+{+ if (m_running) {+ (void)freerdp_client_send_extended_button_event(reinterpret_cast<rdpClientContext *>(m_context), FALSE, flags, x, y);+ }+}++void Client::sendWheel(quint16 flags, int x, int y)+{+ if (m_running) {+ (void)freerdp_input_send_mouse_event(m_context->input, flags, UINT16(qBound(0, x, 65535)), UINT16(qBound(0, y, 65535)));+ }+}++void Client::sendKey(bool down, bool repeat, quint32 scancode)+{+ if (m_running) {+ (void)freerdp_input_send_keyboard_event_ex(m_context->input, down, repeat, scancode);+ }+}++void Client::sendUnicode(bool down, quint16 code)+{+ if (m_running) {+ (void)freerdp_input_send_unicode_keyboard_event(m_context->input, down ? 0 : KBD_FLAGS_RELEASE, code);+ }+}++void Client::sendPause()+{+ if (m_running) {+ (void)freerdp_input_send_keyboard_pause_event(m_context->input);+ }+}++void Client::sendFocusIn(quint16 toggles)+{+ if (m_running) {+ (void)freerdp_input_send_focus_in_event(m_context->input, toggles);+ }+}++void Client::activate(quint32 id, bool active)+{+ std::lock_guard lock(m_channels);+ if (m_rail) {+ RAIL_ACTIVATE_ORDER order = {};+ order.windowId = id;+ order.enabled = active;+ (void)m_rail->ClientActivate(m_rail, &order);+ }+}++void Client::sysCommand(quint32 id, quint16 command)+{+ std::lock_guard lock(m_channels);+ if (m_rail) {+ RAIL_SYSCOMMAND_ORDER order = {};+ order.windowId = id;+ order.command = command;+ (void)m_rail->ClientSystemCommand(m_rail, &order);+ }+}++void Client::moveWindow(quint32 id, const QRect &frame)+{+ std::lock_guard lock(m_channels);+ if (m_rail) {+ RAIL_WINDOW_MOVE_ORDER order = {};+ order.windowId = id;+ order.left = INT16(frame.left());+ order.top = INT16(frame.top());+ order.right = INT16(frame.left() + frame.width());+ order.bottom = INT16(frame.top() + frame.height());+ (void)m_rail->ClientWindowMove(m_rail, &order);+ }+}++void Client::systemMenu(quint32 id, int x, int y)+{+ std::lock_guard lock(m_channels);+ if (m_rail) {+ RAIL_SYSMENU_ORDER order = {};+ order.windowId = id;+ order.left = INT16(x);+ order.top = INT16(y);+ (void)m_rail->ClientSystemMenu(m_rail, &order);+ }+}++void Client::setWorkArea(const QRect &area)+{+ std::lock_guard lock(m_channels);+ if (m_rail && area.isValid()) {+ RAIL_SYSPARAM_ORDER param = {};+ param.params = SPI_MASK_SET_WORK_AREA;+ param.workArea.left = UINT16(area.left());+ param.workArea.top = UINT16(area.top());+ param.workArea.right = UINT16(area.left() + area.width());+ param.workArea.bottom = UINT16(area.top() + area.height());+ (void)m_rail->ClientSystemParam(m_rail, ¶m);+ }+}++void Client::refresh(const QRect &area)+{+ if (!m_running || !m_context->update || !m_context->update->RefreshRect) {+ return;+ }+ const QRect r = area.intersected(QRect(QPoint(0, 0), desktopSize()));+ if (r.isEmpty()) {+ return;+ }+ RECTANGLE_16 rect = {UINT16(r.left()), UINT16(r.top()), UINT16(r.left() + r.width()), UINT16(r.top() + r.height())};+ (void)m_context->update->RefreshRect(m_context, 1, &rect);+}++void Client::requestProcess(quint32 id)+{+ std::lock_guard lock(m_channels);+ if (m_rail && m_rail->ClientGetAppIdRequest) {+ RAIL_GET_APPID_REQ_ORDER request = {};+ request.windowId = id;+ (void)m_rail->ClientGetAppIdRequest(m_rail, &request);+ }+}diff --git a/packages/wildos-rdp/src/client.h b/packages/wildos-rdp/src/client.hnew file mode 100644index 0000000..5446866--- /dev/null+++ b/packages/wildos-rdp/src/client.h@@ -0,0 +1,175 @@+#pragma once++#include <QHash>+#include <QImage>+#include <QList>+#include <QMargins>+#include <QObject>+#include <QRect>+#include <QRegion>++#include <freerdp/client.h>+#include <freerdp/client/rail.h>+#include <freerdp/client/rdpgfx.h>+#include <freerdp/freerdp.h>++#include <atomic>+#include <functional>+#include <mutex>+#include <thread>++class Client;+class Clipboard;++// FreeRDP allocates the context; ContextSize makes room for this.+struct WrdpContext {+ rdpClientContext common;+ Client *client;+};++// One RemoteApp window order, copied off FreeRDP's thread. Only the fields+// named in `fields` (WINDOW_ORDER_FIELD_*) carry news.+struct RailOrder {+ quint32 id = 0;+ quint32 fields = 0;+ bool created = false;+ quint32 owner = 0;+ quint32 style = 0;+ quint32 exStyle = 0;+ quint32 showState = 0;+ QString title;+ QPoint offset;+ QSize size;+ QPoint clientOffset;+ QSize clientSize;+ QPoint visibleOffset;+ QMargins resizeMargins;+ QList<QRect> visibility;+};+Q_DECLARE_METATYPE(RailOrder)++// The FreeRDP session: settings, the connection thread and its callbacks.+// Everything FreeRDP reports arrives here on its own threads and leaves as+// queued signals for the GUI thread; the GUI thread sends input and+// RemoteApp requests straight through, which FreeRDP allows from any+// thread.+class Client : public QObject+{+ Q_OBJECT++public:+ explicit Client(QObject *parent = nullptr);+ ~Client() override;++ // FreeRDP's own arguments, as xfreerdp3 takes them; the password among+ // them. Returns false with the reason in `error` when they do not parse.+ bool configure(const QList<QByteArray> &args, QString *error);+ // The output the session is laid out for, in physical pixels, and the+ // scale Windows should draw at.+ void setDisplay(const QSize &physical, double scale);+ void start();+ void stop();+ void setPrepareOnly(bool on) { m_prepareOnly = on; }+ bool running() const { return m_running; }++ rdpContext *context() const;+ QSize desktopSize() const;++ // Input, in Windows' desktop coordinates.+ void sendMouse(quint16 flags, int x, int y);+ void sendExtendedMouse(quint16 flags, int x, int y);+ void sendWheel(quint16 flags, int x, int y);+ void sendKey(bool down, bool repeat, quint32 scancode);+ void sendUnicode(bool down, quint16 code);+ void sendPause();+ void sendFocusIn(quint16 toggles);++ // RemoteApp requests.+ void activate(quint32 id, bool active);+ void sysCommand(quint32 id, quint16 command);+ void moveWindow(quint32 id, const QRect &frame);+ void systemMenu(quint32 id, int x, int y);+ void setWorkArea(const QRect &area);+ // Asks Windows to send this part of its desktop again.+ void refresh(const QRect &area);+ // Asks Windows which process a window belongs to (windowProcess).+ void requestProcess(quint32 id);++ // Calls `paint` with a window's pixels from the graphics pipeline,+ // under the lock FreeRDP decodes into them with, so the copy is never+ // torn. False when the surface is gone.+ bool withSurface(quint16 surfaceId, const std::function<void(const uchar *data, int stride, QSize size)> &paint);+ // The same for the whole desktop picture when the server draws without+ // the graphics pipeline.+ bool withPrimary(const std::function<void(const uchar *data, int stride, QSize size)> &paint);++ Clipboard *clipboard() const { return m_clipboard; }++Q_SIGNALS:+ void connected();+ // The session ended. `error` is FreeRDP's name for why, empty when it+ // ended normally; `authFailed` when Windows refused the account.+ void finished(const QString &error, bool authFailed);+ void windowChanged(const RailOrder &order);+ void windowDeleted(quint32 id);+ void windowIcon(quint32 id, const QImage &icon, bool big);+ void desktopChanged(quint32 activeId, bool hasActive, const QList<quint32> &zOrder, bool hasZOrder);+ void surfaceDamaged(quint64 windowId, quint16 surfaceId, const QRegion &damage, const QSize &size);+ void primaryDamaged(const QRegion &damage);+ void localMoveSize(quint32 id, bool start, quint16 type, int x, int y);+ void minMaxInfo(quint32 id, const QSize &minTrack, const QSize &maxTrack);+ void pointerImage(const QImage &image, const QPoint &hotspot);+ void pointerHidden();+ void pointerDefault();+ void execFailed(quint16 result);+ // Windows has sent every window already open in the session (the end of+ // its desktop sync); the connection's app is asked for now.+ void desktopSynced();+ void windowCloaked(quint32 id, bool cloaked);+ // The connection dropped and is being made again, and is back.+ void connectionLost();+ void connectionBack();+ // The process behind a window: its image (full path), App User Model+ // ID and process id.+ void windowProcess(quint32 id, const QString &image, const QString &appUserModel, quint32 pid);++private:+ friend struct ClientCallbacks;++ void run();+ void queueSurfaceDamage(quint64 windowId, quint16 surfaceId, const QRegion &damage, const QSize &size);+ void queuePrimaryDamage(const QRegion &damage);+ void deliverDamage();++ rdpContext *m_context = nullptr;+ std::thread m_thread;+ std::atomic<bool> m_running = false;+ std::atomic<bool> m_stopping = false;+ QSize m_physical;+ double m_scale = 1.0;++ std::mutex m_channels;+ // The connection's app has been asked for; a reconnection must not ask+ // again.+ std::atomic_bool m_appRequested = false;+ // Only signing in: the session is made ready and no app is asked for.+ bool m_prepareOnly = false;+ RailClientContext *m_rail = nullptr;+ RdpgfxClientContext *m_gfx = nullptr;+ Clipboard *m_clipboard = nullptr;++ // Damage collects here between deliveries, so a slow GUI thread gets+ // one update per window instead of a queue of them.+ struct Damage {+ quint16 surfaceId = 0;+ QRegion region;+ QSize size;+ };+ std::mutex m_damageLock;+ QHash<quint64, Damage> m_damage;+ QRegion m_primaryDamage;+ bool m_deliveryQueued = false;++ // The RemoteApp icon cache, used only on FreeRDP's thread.+ QHash<quint32, QImage> m_icons;+};diff --git a/packages/wildos-rdp/src/clipboard.cpp b/packages/wildos-rdp/src/clipboard.cppnew file mode 100644index 0000000..c83dac7--- /dev/null+++ b/packages/wildos-rdp/src/clipboard.cpp@@ -0,0 +1,313 @@+#include "clipboard.h"++#include <QBuffer>+#include <QClipboard>+#include <QGuiApplication>+#include <QImage>+#include <QMimeData>+#include <QtEndian>++#include <cstring>++namespace+{+// Windows' standard clipboard formats.+constexpr quint32 cfUnicodeText = 13;+constexpr quint32 cfDib = 8;+// Nothing larger is taken from either side: a picture this size is+// already well past anything worth pasting.+constexpr qsizetype maxBytes = 256 * 1024 * 1024;++QString fromWindowsText(const QByteArray &data)+{+ const auto *units = reinterpret_cast<const char16_t *>(data.constData());+ qsizetype n = data.size() / 2;+ for (qsizetype i = 0; i < n; ++i) {+ if (units[i] == 0) {+ n = i;+ break;+ }+ }+ QString text = QString::fromUtf16(units, n);+ text.replace(QLatin1String("\r\n"), QLatin1String("\n"));+ return text;+}++QByteArray toWindowsText(QString text)+{+ text.replace(QLatin1String("\r\n"), QLatin1String("\n"));+ text.replace(u'\n', QLatin1String("\r\n"));+ QByteArray out(reinterpret_cast<const char *>(text.utf16()), text.size() * 2);+ out.append(2, '\0');+ return out;+}++// A device-independent bitmap as Windows keeps it on the clipboard is a+// BMP file without its first 14 bytes.+QImage fromDib(const QByteArray &dib)+{+ if (dib.size() < 40) {+ return {};+ }+ const auto *h = reinterpret_cast<const uchar *>(dib.constData());+ const quint32 headerSize = qFromLittleEndian<quint32>(h);+ const quint16 bitCount = qFromLittleEndian<quint16>(h + 14);+ const quint32 compression = qFromLittleEndian<quint32>(h + 16);+ const quint32 coloursUsed = qFromLittleEndian<quint32>(h + 32);+ quint32 masks = 0;+ if (headerSize == 40 && compression == 3) {+ masks = 12;+ } else if (headerSize == 40 && compression == 6) {+ masks = 16;+ }+ const quint32 palette = coloursUsed ? coloursUsed * 4 : (bitCount <= 8 ? (1u << bitCount) * 4 : 0);+ QByteArray file(14, '\0');+ file[0] = 'B';+ file[1] = 'M';+ qToLittleEndian<quint32>(quint32(14 + dib.size()), file.data() + 2);+ qToLittleEndian<quint32>(14 + headerSize + masks + palette, file.data() + 10);+ file.append(dib);+ return QImage::fromData(file, "BMP");+}++QByteArray toDib(const QImage &source)+{+ const QImage image = source.convertToFormat(QImage::Format_ARGB32);+ const int w = image.width();+ const int h = image.height();+ QByteArray dib(40 + qsizetype(w) * h * 4, '\0');+ auto *p = reinterpret_cast<uchar *>(dib.data());+ qToLittleEndian<quint32>(40, p);+ qToLittleEndian<qint32>(w, p + 4);+ qToLittleEndian<qint32>(h, p + 8);+ qToLittleEndian<quint16>(1, p + 12);+ qToLittleEndian<quint16>(32, p + 14);+ qToLittleEndian<quint32>(quint32(w) * h * 4, p + 20);+ uchar *pixels = p + 40;+ for (int y = 0; y < h; ++y) {+ // Bottom-up rows; ARGB32 in memory is B, G, R, A, as Windows has it.+ std::memcpy(pixels + qsizetype(h - 1 - y) * w * 4, image.constScanLine(y), size_t(w) * 4);+ }+ return dib;+}+}++Clipboard::Clipboard(QObject *parent)+ : QObject(parent)+{+ connect(QGuiApplication::clipboard(), &QClipboard::dataChanged, this, [this] {+ if (!m_settingOwn) {+ announce();+ }+ });+}++void Clipboard::attach(CliprdrClientContext *context)+{+ std::lock_guard lock(m_lock);+ m_context = context;+ m_ready = false;+ context->custom = this;+ context->MonitorReady = monitorReady;+ context->ServerCapabilities = serverCapabilities;+ context->ServerFormatList = serverFormatList;+ context->ServerFormatListResponse = serverFormatListResponse;+ context->ServerFormatDataRequest = serverDataRequest;+ context->ServerFormatDataResponse = serverDataResponse;+}++void Clipboard::detach(CliprdrClientContext *context)+{+ std::lock_guard lock(m_lock);+ if (m_context == context) {+ m_context = nullptr;+ m_ready = false;+ }+ context->custom = nullptr;+}++UINT Clipboard::monitorReady(CliprdrClientContext *context, const CLIPRDR_MONITOR_READY *)+{+ auto *self = static_cast<Clipboard *>(context->custom);+ CLIPRDR_GENERAL_CAPABILITY_SET general = {};+ general.capabilitySetType = CB_CAPSTYPE_GENERAL;+ general.capabilitySetLength = CB_CAPSTYPE_GENERAL_LEN;+ general.version = CB_CAPS_VERSION_2;+ general.generalFlags = CB_USE_LONG_FORMAT_NAMES;+ CLIPRDR_CAPABILITIES caps = {};+ caps.cCapabilitiesSets = 1;+ caps.capabilitySets = reinterpret_cast<CLIPRDR_CAPABILITY_SET *>(&general);+ const UINT rc = context->ClientCapabilities(context, &caps);+ if (rc != CHANNEL_RC_OK) {+ return rc;+ }+ {+ std::lock_guard lock(self->m_lock);+ self->m_ready = true;+ }+ // Whatever the desktop's clipboard holds already can be pasted in+ // Windows straight away.+ QMetaObject::invokeMethod(self, &Clipboard::announce, Qt::QueuedConnection);+ return CHANNEL_RC_OK;+}++UINT Clipboard::serverCapabilities(CliprdrClientContext *, const CLIPRDR_CAPABILITIES *)+{+ return CHANNEL_RC_OK;+}++UINT Clipboard::serverFormatList(CliprdrClientContext *context, const CLIPRDR_FORMAT_LIST *list)+{+ auto *self = static_cast<Clipboard *>(context->custom);+ bool text = false;+ bool image = false;+ for (UINT32 i = 0; i < list->numFormats; ++i) {+ text |= list->formats[i].formatId == cfUnicodeText;+ image |= list->formats[i].formatId == cfDib;+ }+ CLIPRDR_FORMAT_LIST_RESPONSE response = {};+ response.common.msgFlags = CB_RESPONSE_OK;+ const UINT rc = context->ClientFormatListResponse(context, &response);+ if (qEnvironmentVariableIsSet("WILDOS_RDP_DEBUG")) {+ qInfo("clipboard: Windows offers text %d, picture %d", text, image);+ }+ QMetaObject::invokeMethod(+ self,+ [self, text, image] {+ self->m_offerText = text;+ self->m_offerImage = image;+ self->m_text.clear();+ self->m_image.clear();+ self->m_requested = 0;+ self->fetchNext();+ },+ Qt::QueuedConnection);+ return rc;+}++UINT Clipboard::serverFormatListResponse(CliprdrClientContext *, const CLIPRDR_FORMAT_LIST_RESPONSE *)+{+ return CHANNEL_RC_OK;+}++UINT Clipboard::serverDataRequest(CliprdrClientContext *context, const CLIPRDR_FORMAT_DATA_REQUEST *request)+{+ auto *self = static_cast<Clipboard *>(context->custom);+ const quint32 format = request->requestedFormatId;+ QMetaObject::invokeMethod(self, [self, format] { self->answer(format); }, Qt::QueuedConnection);+ return CHANNEL_RC_OK;+}++UINT Clipboard::serverDataResponse(CliprdrClientContext *context, const CLIPRDR_FORMAT_DATA_RESPONSE *response)+{+ auto *self = static_cast<Clipboard *>(context->custom);+ QByteArray data;+ if ((response->common.msgFlags & CB_RESPONSE_OK) && response->requestedFormatData && response->common.dataLen <= maxBytes) {+ data = QByteArray(reinterpret_cast<const char *>(response->requestedFormatData), qsizetype(response->common.dataLen));+ }+ QMetaObject::invokeMethod(self, [self, data] { self->received(self->m_requested, data); }, Qt::QueuedConnection);+ return CHANNEL_RC_OK;+}++void Clipboard::fetchNext()+{+ quint32 format = 0;+ if (m_offerText && m_text.isNull()) {+ format = cfUnicodeText;+ } else if (m_offerImage && m_image.isNull()) {+ format = cfDib;+ }+ if (!format) {+ auto *mime = new QMimeData;+ if (!m_text.isEmpty()) {+ mime->setText(fromWindowsText(m_text));+ }+ if (!m_image.isEmpty()) {+ const QImage image = fromDib(m_image);+ if (!image.isNull()) {+ mime->setImageData(image);+ }+ }+ if (mime->formats().isEmpty()) {+ delete mime;+ return;+ }+ m_settingOwn = true;+ QGuiApplication::clipboard()->setMimeData(mime);+ m_settingOwn = false;+ if (qEnvironmentVariableIsSet("WILDOS_RDP_DEBUG")) {+ qInfo("clipboard: the desktop's clipboard now holds Windows' copy");+ }+ return;+ }+ std::lock_guard lock(m_lock);+ if (!m_context || !m_ready) {+ return;+ }+ m_requested = format;+ CLIPRDR_FORMAT_DATA_REQUEST request = {};+ request.requestedFormatId = format;+ if (m_context->ClientFormatDataRequest(m_context, &request) != CHANNEL_RC_OK) {+ m_requested = 0;+ }+}++void Clipboard::received(quint32 format, const QByteArray &data)+{+ if (qEnvironmentVariableIsSet("WILDOS_RDP_DEBUG")) {+ qInfo("clipboard: format %u, %lld bytes from Windows", format, qint64(data.size()));+ }+ // A format Windows could not give is marked done with an empty array,+ // which is not a null one.+ const QByteArray value = data.isNull() ? QByteArray("") : data;+ if (format == cfUnicodeText) {+ m_text = value;+ } else if (format == cfDib) {+ m_image = value;+ } else {+ return;+ }+ fetchNext();+}++void Clipboard::announce()+{+ const QMimeData *mime = QGuiApplication::clipboard()->mimeData();+ QList<CLIPRDR_FORMAT> formats;+ if (mime && mime->hasText()) {+ formats.append({cfUnicodeText, nullptr});+ }+ if (mime && mime->hasImage()) {+ formats.append({cfDib, nullptr});+ }+ std::lock_guard lock(m_lock);+ if (!m_context || !m_ready) {+ return;+ }+ CLIPRDR_FORMAT_LIST list = {};+ list.common.msgType = CB_FORMAT_LIST;+ list.numFormats = UINT32(formats.size());+ list.formats = formats.data();+ (void)m_context->ClientFormatList(m_context, &list);+}++void Clipboard::answer(quint32 format)+{+ const QMimeData *mime = QGuiApplication::clipboard()->mimeData();+ QByteArray data;+ if (mime && format == cfUnicodeText && mime->hasText()) {+ data = toWindowsText(mime->text());+ } else if (mime && format == cfDib && mime->hasImage()) {+ data = toDib(qvariant_cast<QImage>(mime->imageData()));+ }+ std::lock_guard lock(m_lock);+ if (!m_context) {+ return;+ }+ CLIPRDR_FORMAT_DATA_RESPONSE response = {};+ response.common.msgType = CB_FORMAT_DATA_RESPONSE;+ response.common.msgFlags = data.isEmpty() || data.size() > maxBytes ? CB_RESPONSE_FAIL : CB_RESPONSE_OK;+ response.common.dataLen = response.common.msgFlags == CB_RESPONSE_OK ? UINT32(data.size()) : 0;+ response.requestedFormatData = reinterpret_cast<const BYTE *>(data.constData());+ (void)m_context->ClientFormatDataResponse(m_context, &response);+}diff --git a/packages/wildos-rdp/src/clipboard.h b/packages/wildos-rdp/src/clipboard.hnew file mode 100644index 0000000..d42eca2--- /dev/null+++ b/packages/wildos-rdp/src/clipboard.h@@ -0,0 +1,51 @@+#pragma once++#include <QByteArray>+#include <QObject>++#include <freerdp/client/cliprdr.h>++#include <mutex>++// Copy and paste between Windows apps and the desktop: text and pictures,+// both ways. When Windows says it has something new on its clipboard the+// text and picture are fetched at once and put on the desktop's clipboard;+// when the desktop's clipboard changes, Windows is told which of the two+// it can ask for, and gets them when it asks.+class Clipboard : public QObject+{+ Q_OBJECT++public:+ explicit Clipboard(QObject *parent = nullptr);++ // On FreeRDP's channel threads.+ void attach(CliprdrClientContext *context);+ void detach(CliprdrClientContext *context);++private:+ static UINT monitorReady(CliprdrClientContext *context, const CLIPRDR_MONITOR_READY *ready);+ static UINT serverCapabilities(CliprdrClientContext *context, const CLIPRDR_CAPABILITIES *caps);+ static UINT serverFormatList(CliprdrClientContext *context, const CLIPRDR_FORMAT_LIST *list);+ static UINT serverFormatListResponse(CliprdrClientContext *context, const CLIPRDR_FORMAT_LIST_RESPONSE *response);+ static UINT serverDataRequest(CliprdrClientContext *context, const CLIPRDR_FORMAT_DATA_REQUEST *request);+ static UINT serverDataResponse(CliprdrClientContext *context, const CLIPRDR_FORMAT_DATA_RESPONSE *response);++ // On the GUI thread.+ void announce();+ void fetchNext();+ void received(quint32 format, const QByteArray &data);+ void answer(quint32 format);++ std::mutex m_lock;+ CliprdrClientContext *m_context = nullptr;+ bool m_ready = false;++ // What Windows offered last, and what has arrived of it so far.+ bool m_offerText = false;+ bool m_offerImage = false;+ quint32 m_requested = 0;+ QByteArray m_text;+ QByteArray m_image;+ bool m_settingOwn = false;+};diff --git a/packages/wildos-rdp/src/desktop.cpp b/packages/wildos-rdp/src/desktop.cppnew file mode 100644index 0000000..a43f239--- /dev/null+++ b/packages/wildos-rdp/src/desktop.cpp@@ -0,0 +1,397 @@+#include "desktop.h"+#include "client.h"++#include <QLocale>+#include <QCryptographicHash>+#include <QDateTime>+#include <QSslCertificate>++#include <freerdp/autodetect.h>+#include <freerdp/client/cmdline.h>+#include <freerdp/client/disp.h>+#include <freerdp/settings.h>++#include <chrono>+#include <cstring>+#include <vector>++namespace+{+DesktopSession *sessionOf(freerdp *instance)+{+ if (!instance || !instance->context) {+ return nullptr;+ }+ Client *client = reinterpret_cast<WrdpContext *>(instance->context)->client;+ return client ? qobject_cast<DesktopSession *>(client->parent()) : nullptr;+}++QString colonHex(const QByteArray &bytes)+{+ QStringList parts;+ for (const char b : bytes) {+ parts.append(QStringLiteral("%1").arg(quint8(b), 2, 16, QLatin1Char('0')).toUpper());+ }+ return parts.join(QLatin1Char(':'));+}++// What the person needs to check a certificate: the name it gives, who+// issued it, when it runs out, and its SHA-256 fingerprint.+QVariantMap certificateInfo(const char *host, UINT16 port, const char *commonName, const char *subject, const char *issuer,+ const char *fingerprint, DWORD flags)+{+ QVariantMap info;+ info.insert(QStringLiteral("host"), QString::fromUtf8(host));+ info.insert(QStringLiteral("port"), int(port));+ info.insert(QStringLiteral("commonName"), QString::fromUtf8(commonName ? commonName : ""));+ info.insert(QStringLiteral("subject"), QString::fromUtf8(subject ? subject : ""));+ info.insert(QStringLiteral("issuer"), QString::fromUtf8(issuer ? issuer : ""));+ info.insert(QStringLiteral("mismatch"), bool(flags & VERIFY_CERT_FLAG_MISMATCH));+ if ((flags & VERIFY_CERT_FLAG_FP_IS_PEM) && fingerprint) {+ const QList<QSslCertificate> certs = QSslCertificate::fromData(QByteArray(fingerprint), QSsl::Pem);+ if (!certs.isEmpty()) {+ const QSslCertificate &c = certs.first();+ info.insert(QStringLiteral("fingerprint"), colonHex(c.digest(QCryptographicHash::Sha256)));+ info.insert(QStringLiteral("validUntil"), QLocale::system().toString(c.expiryDate().toLocalTime().date(), QLocale::ShortFormat));+ info.insert(QStringLiteral("expired"), c.expiryDate() < QDateTime::currentDateTimeUtc());+ info.insert(QStringLiteral("selfSigned"), c.isSelfSigned());+ const QString cn = c.subjectInfo(QSslCertificate::CommonName).value(0);+ if (!cn.isEmpty()) {+ info.insert(QStringLiteral("commonName"), cn);+ }+ const QString issuerName = c.issuerInfo(QSslCertificate::CommonName).value(0);+ if (!issuerName.isEmpty()) {+ info.insert(QStringLiteral("issuer"), issuerName);+ }+ }+ } else if (fingerprint) {+ info.insert(QStringLiteral("fingerprint"), QString::fromUtf8(fingerprint).toUpper());+ }+ return info;+}++void replace(char **slot, const QByteArray &value)+{+ if (!slot) {+ return;+ }+ free(*slot);+ *slot = value.isEmpty() ? nullptr : strdup(value.constData());+}+}++// FreeRDP's questions, on its thread: each one is put to the GUI thread+// as a signal, and the thread waits for the answer.+struct DesktopCallbacks {+ static DWORD verifyCertificate(freerdp *instance, const char *host, UINT16 port, const char *commonName, const char *subject,+ const char *issuer, const char *fingerprint, DWORD flags)+ {+ DesktopSession *self = sessionOf(instance);+ if (!self) {+ return 0;+ }+ return ask(self, certificateInfo(host, port, commonName, subject, issuer, fingerprint, flags), false);+ }++ static DWORD verifyChangedCertificate(freerdp *instance, const char *host, UINT16 port, const char *commonName, const char *subject,+ const char *issuer, const char *fingerprint, const char *, const char *,+ const char *oldFingerprint, DWORD flags)+ {+ DesktopSession *self = sessionOf(instance);+ if (!self) {+ return 0;+ }+ QVariantMap info = certificateInfo(host, port, commonName, subject, issuer, fingerprint, flags);+ const QVariantMap old = certificateInfo(host, port, "", "", "", oldFingerprint, flags);+ info.insert(QStringLiteral("previousFingerprint"), old.value(QStringLiteral("fingerprint")));+ return ask(self, info, true);+ }++ static DWORD ask(DesktopSession *self, const QVariantMap &info, bool changed)+ {+ std::unique_lock lock(self->m_lock);+ self->m_certificateAnswer = -1;+ QMetaObject::invokeMethod(self, [self, info, changed] { Q_EMIT self->certificateNeeded(info, changed); }, Qt::QueuedConnection);+ self->m_wait.wait(lock, [self] { return self->m_certificateAnswer >= 0 || self->m_stopping; });+ // 1 keeps it in FreeRDP's store, 2 trusts it for this session only.+ return self->m_stopping ? 0 : DWORD(self->m_certificateAnswer);+ }++ static BOOL authenticate(freerdp *instance, char **username, char **password, char **domain, rdp_auth_reason)+ {+ DesktopSession *self = sessionOf(instance);+ if (!self) {+ return FALSE;+ }+ if (username && *username && **username && password && *password && **password) {+ return TRUE;+ }+ std::unique_lock lock(self->m_lock);+ self->m_credentialsAnswered = false;+ const QString user = QString::fromUtf8(username && *username ? *username : "");+ const QString dom = QString::fromUtf8(domain && *domain ? *domain : "");+ QMetaObject::invokeMethod(self, [self, user, dom] { Q_EMIT self->credentialsNeeded(user, dom, QStringLiteral("first")); }, Qt::QueuedConnection);+ self->m_wait.wait(lock, [self] { return self->m_credentialsAnswered || self->m_stopping; });+ if (self->m_stopping || !self->m_credentialsOk) {+ return FALSE;+ }+ replace(username, self->m_user);+ replace(password, self->m_password);+ if (domain && !self->m_domain.isEmpty()) {+ replace(domain, self->m_domain);+ }+ self->m_password.fill('\0');+ self->m_password.clear();+ return TRUE;+ }++ static SSIZE_T retry(freerdp *instance, const char *, size_t current, void *)+ {+ DesktopSession *self = sessionOf(instance);+ if (!self) {+ return -1;+ }+ std::unique_lock lock(self->m_lock);+ if (self->m_stopTrying || self->m_stopping || int(current) >= self->m_attempts) {+ return -1;+ }+ self->m_tryNow = false;+ const int attempt = int(current) + 1;+ const int attempts = self->m_attempts;+ QMetaObject::invokeMethod(self, [self, attempt, attempts] { Q_EMIT self->reconnecting(attempt, attempts); }, Qt::QueuedConnection);+ // A moment for a network to come back before each try; "Try now"+ // ends the wait.+ const auto wait = std::chrono::milliseconds(current == 0 ? 1500 : 4000);+ self->m_wait.wait_for(lock, wait, [self] { return self->m_tryNow || self->m_stopTrying || self->m_stopping; });+ return self->m_stopTrying || self->m_stopping ? -1 : 0;+ }++ static void channelConnected(void *ctx, const ChannelConnectedEventArgs *e)+ {+ auto *context = static_cast<rdpContext *>(ctx);+ DesktopSession *self = sessionOf(context->instance);+ if (self && strcmp(e->name, DISP_DVC_CHANNEL_NAME) == 0) {+ std::lock_guard lock(self->m_lock);+ self->m_disp = static_cast<DispClientContext *>(e->pInterface);+ }+ }++ static void channelDisconnected(void *ctx, const ChannelDisconnectedEventArgs *e)+ {+ auto *context = static_cast<rdpContext *>(ctx);+ DesktopSession *self = sessionOf(context->instance);+ if (self && strcmp(e->name, DISP_DVC_CHANNEL_NAME) == 0) {+ std::lock_guard lock(self->m_lock);+ self->m_disp = nullptr;+ }+ }+};++DesktopSession::DesktopSession(QObject *parent)+ : QObject(parent)+ , m_client(new Client(this))+{+ connect(m_client, &Client::connected, this, &DesktopSession::connected);+ connect(m_client, &Client::connectionBack, this, &DesktopSession::reconnected);+ connect(m_client, &Client::primaryDamaged, this, &DesktopSession::frameChanged);+ connect(m_client, &Client::pointerImage, this, &DesktopSession::pointerImage);+ connect(m_client, &Client::pointerHidden, this, &DesktopSession::pointerHidden);+ connect(m_client, &Client::pointerDefault, this, &DesktopSession::pointerDefault);+ connect(m_client, &Client::finished, this, [this](const QString &error, bool authFailed) {+ Q_EMIT finished(m_stopping ? QString() : error, authFailed);+ });+}++DesktopSession::~DesktopSession()+{+ stop();+}++bool DesktopSession::configure(const QList<QByteArray> &args, QString *error)+{+ rdpContext *context = m_client->context();+ if (!context) {+ *error = QStringLiteral("FreeRDP could not be set up");+ return false;+ }+ std::vector<QByteArray> storage;+ storage.push_back(QByteArrayLiteral("wildos-remote"));+ for (const QByteArray &a : args) {+ storage.push_back(a);+ }+ std::vector<char *> argv;+ for (QByteArray &a : storage) {+ argv.push_back(a.data());+ }+ argv.push_back(nullptr);+ rdpSettings *settings = context->settings;+ const int status = freerdp_client_settings_parse_command_line(settings, int(argv.size() - 1), argv.data(), FALSE);+ for (QByteArray &a : storage) {+ a.fill('\0');+ }+ if (status != 0) {+ *error = QStringLiteral("the connection settings could not be read (%1)").arg(status);+ return false;+ }+ if (freerdp_settings_get_bool(settings, FreeRDP_RemoteApplicationMode)) {+ *error = QStringLiteral("a desktop session can't open a single app (/app)");+ return false;+ }+ // The certificate itself, so its dates and issuer can be shown.+ (void)freerdp_settings_set_bool(settings, FreeRDP_CertificateCallbackPreferPEM, TRUE);+ (void)freerdp_settings_set_bool(settings, FreeRDP_AutoReconnectionEnabled, TRUE);+ (void)freerdp_settings_set_uint32(settings, FreeRDP_AutoReconnectMaxRetries, UINT32(m_attempts));+ const char *password = freerdp_settings_get_string(settings, FreeRDP_Password);+ m_passwordGiven = password && *password;++ freerdp *instance = context->instance;+ instance->VerifyCertificateEx = DesktopCallbacks::verifyCertificate;+ instance->VerifyChangedCertificateEx = DesktopCallbacks::verifyChangedCertificate;+ instance->AuthenticateEx = DesktopCallbacks::authenticate;+ instance->RetryDialog = DesktopCallbacks::retry;+ (void)PubSub_SubscribeChannelConnected(context->pubSub, DesktopCallbacks::channelConnected);+ (void)PubSub_SubscribeChannelDisconnected(context->pubSub, DesktopCallbacks::channelDisconnected);+ return true;+}++void DesktopSession::setDisplay(const QSize &physical, double scale)+{+ m_client->setDisplay(physical, scale);+}++void DesktopSession::setMonitors(const QList<QRect> &monitors, double scale)+{+ rdpSettings *settings = m_client->context()->settings;+ QRect bounds;+ for (const QRect &m : monitors) {+ bounds |= m;+ }+ if (!freerdp_settings_set_pointer_len(settings, FreeRDP_MonitorDefArray, nullptr, size_t(monitors.size()))) {+ return;+ }+ for (int i = 0; i < monitors.size(); ++i) {+ auto *m = static_cast<rdpMonitor *>(freerdp_settings_get_pointer_array_writable(settings, FreeRDP_MonitorDefArray, size_t(i)));+ if (!m) {+ return;+ }+ // Windows wants the primary monitor at 0,0.+ const QRect r = monitors[i].translated(-monitors.first().topLeft());+ m->x = r.x();+ m->y = r.y();+ m->width = r.width();+ m->height = r.height();+ m->is_primary = i == 0;+ m->orig_screen = UINT32(i);+ }+ (void)freerdp_settings_set_uint32(settings, FreeRDP_MonitorCount, UINT32(monitors.size()));+ (void)freerdp_settings_set_bool(settings, FreeRDP_UseMultimon, TRUE);+ (void)freerdp_settings_set_bool(settings, FreeRDP_ForceMultimon, TRUE);+ m_client->setDisplay(bounds.size(), scale);+}++void DesktopSession::setReconnectAttempts(int attempts)+{+ m_attempts = attempts;+ (void)freerdp_settings_set_uint32(m_client->context()->settings, FreeRDP_AutoReconnectMaxRetries, UINT32(attempts));+}++void DesktopSession::start()+{+ m_stopping = false;+ m_client->start();+}++void DesktopSession::stop()+{+ {+ std::lock_guard lock(m_lock);+ m_stopping = true;+ }+ m_wait.notify_all();+ m_client->stop();+}++void DesktopSession::wake()+{+ m_wait.notify_all();+}++void DesktopSession::answerCertificate(bool accept, bool remember)+{+ {+ std::lock_guard lock(m_lock);+ m_certificateAnswer = accept ? (remember ? 1 : 2) : 0;+ }+ wake();+}++void DesktopSession::answerCredentials(bool ok, const QString &user, const QString &domain, const QString &password)+{+ {+ std::lock_guard lock(m_lock);+ m_credentialsOk = ok;+ m_user = user.toUtf8();+ m_domain = domain.toUtf8();+ m_password = password.toUtf8();+ m_credentialsAnswered = true;+ }+ wake();+}++void DesktopSession::tryNow()+{+ {+ std::lock_guard lock(m_lock);+ m_tryNow = true;+ }+ wake();+}++void DesktopSession::stopTrying()+{+ {+ std::lock_guard lock(m_lock);+ m_stopTrying = true;+ }+ wake();+}++QImage DesktopSession::frame() const+{+ QImage out;+ m_client->withPrimary([&out](const uchar *data, int stride, QSize size) {+ out = QImage(data, size.width(), size.height(), stride, QImage::Format_RGB32).copy();+ });+ return out;+}++QSize DesktopSession::desktopSize() const+{+ return m_client->desktopSize();+}++int DesktopSession::latency() const+{+ rdpContext *context = m_client->context();+ if (!context || !context->autodetect) {+ return 0;+ }+ return int(context->autodetect->netCharAverageRTT);+}++bool DesktopSession::resize(const QSize &physical, double scale)+{+ std::lock_guard lock(m_lock);+ if (!m_disp || !m_disp->SendMonitorLayout) {+ return false;+ }+ DISPLAY_CONTROL_MONITOR_LAYOUT layout = {};+ layout.Flags = DISPLAY_CONTROL_MONITOR_PRIMARY;+ // Windows takes even widths, and nothing under 200 pixels.+ layout.Width = UINT32(std::max(200, physical.width() & ~1));+ layout.Height = UINT32(std::max(200, physical.height()));+ layout.Orientation = ORIENTATION_LANDSCAPE;+ layout.DesktopScaleFactor = UINT32(qBound(100.0, scale * 100.0 + 0.5, 500.0));+ layout.DeviceScaleFactor = scale >= 1.6 ? 180 : scale >= 1.2 ? 140 : 100;+ return m_disp->SendMonitorLayout(m_disp, 1, &layout) == CHANNEL_RC_OK;+}diff --git a/packages/wildos-rdp/src/desktop.h b/packages/wildos-rdp/src/desktop.hnew file mode 100644index 0000000..f6b863d--- /dev/null+++ b/packages/wildos-rdp/src/desktop.h@@ -0,0 +1,105 @@+#pragma once++#include <QByteArray>+#include <QImage>+#include <QList>+#include <QObject>+#include <QRect>+#include <QRegion>+#include <QVariantMap>++#include <condition_variable>+#include <mutex>++#include <freerdp/client/disp.h>++class Client;++// A whole remote desktop, the engine's second mode beside Windows mode's+// RemoteApp windows: the same Client (connection, graphics pipeline,+// clipboard, sound, drives, reconnecting), drawn as one picture.+//+// Where Windows mode trusts its own VM without asking, a desktop belongs to+// someone else: the certificate, the sign-in and each reconnection attempt+// are questions for the person. FreeRDP asks them on its own thread, which+// waits here until the GUI thread answers.+class DesktopSession : public QObject+{+ Q_OBJECT++public:+ explicit DesktopSession(QObject *parent = nullptr);+ ~DesktopSession() override;++ Client *client() const { return m_client; }++ // FreeRDP's arguments, as xfreerdp3 takes them. Without a password among+ // them, the sign-in is asked for (credentialsNeeded).+ bool configure(const QList<QByteArray> &args, QString *error);+ // The size of the remote desktop and the scale it draws at; or, for+ // every monitor, their places side by side in physical pixels.+ void setDisplay(const QSize &physical, double scale);+ void setMonitors(const QList<QRect> &monitors, double scale);+ void setReconnectAttempts(int attempts);+ void start();+ void stop();++ // Answers to the questions, from the GUI thread.+ // accept: trust it; remember: keep it in FreeRDP's store so a change is+ // noticed next time (otherwise for this session only).+ void answerCertificate(bool accept, bool remember);+ void answerCredentials(bool ok, const QString &user, const QString &domain, const QString &password);+ // Reconnecting: "Try now" skips the wait; "Stop trying" gives up.+ void tryNow();+ void stopTrying();++ // The desktop's picture as last drawn, and the round trip Windows+ // measured (0 when it hasn't said).+ QImage frame() const;+ QSize desktopSize() const;+ int latency() const;++ // Asks Windows to lay the desktop out for a new window size (dynamic+ // resolution); false when it can't, and the picture is scaled instead.+ bool resize(const QSize &physical, double scale);++Q_SIGNALS:+ // info: host, port, commonName, subject, issuer, fingerprint (SHA-256,+ // colon separated), validUntil (short date in the regional format), expired, selfSigned,+ // mismatch; with `changed`, also previousFingerprint.+ void certificateNeeded(const QVariantMap &info, bool changed);+ // reason: "first" when nothing was given, "wrong" after a refusal.+ void credentialsNeeded(const QString &user, const QString &domain, const QString &reason);+ void connected();+ void reconnecting(int attempt, int attempts);+ void reconnected();+ // The session ended: `code` is FreeRDP's name for why (empty when it+ // ended normally or was ended here); `authFailed` when Windows refused+ // the account.+ void finished(const QString &code, bool authFailed);+ void frameChanged(const QRegion &damage);+ void pointerImage(const QImage &image, const QPoint &hotspot);+ void pointerHidden();+ void pointerDefault();++private:+ friend struct DesktopCallbacks;+ void wake();++ Client *m_client;+ mutable std::mutex m_lock;+ std::condition_variable m_wait;+ // The answer FreeRDP's thread is waiting for.+ int m_certificateAnswer = -1;+ bool m_credentialsAnswered = false;+ bool m_credentialsOk = false;+ QByteArray m_user;+ QByteArray m_domain;+ QByteArray m_password;+ bool m_tryNow = false;+ bool m_stopTrying = false;+ bool m_stopping = false;+ bool m_passwordGiven = false;+ int m_attempts = 5;+ DispClientContext *m_disp = nullptr;+};diff --git a/packages/wildos-rdp/src/input.cpp b/packages/wildos-rdp/src/input.cppnew file mode 100644index 0000000..a90dc5c--- /dev/null+++ b/packages/wildos-rdp/src/input.cpp@@ -0,0 +1,95 @@+#include "input.h"+#include "client.h"+#include "keymap.h"++#include <QKeyEvent>++#include <freerdp/input.h>++#include <algorithm>++namespace rdpinput+{+void button(Client *client, Qt::MouseButton button, bool down, QPoint at)+{+ const quint16 press = down ? PTR_FLAGS_DOWN : 0;+ switch (button) {+ case Qt::LeftButton: client->sendMouse(PTR_FLAGS_BUTTON1 | press, at.x(), at.y()); break;+ case Qt::RightButton: client->sendMouse(PTR_FLAGS_BUTTON2 | press, at.x(), at.y()); break;+ case Qt::MiddleButton: client->sendMouse(PTR_FLAGS_BUTTON3 | press, at.x(), at.y()); break;+ case Qt::BackButton: client->sendExtendedMouse(PTR_XFLAGS_BUTTON1 | (down ? PTR_XFLAGS_DOWN : 0), at.x(), at.y()); break;+ case Qt::ForwardButton: client->sendExtendedMouse(PTR_XFLAGS_BUTTON2 | (down ? PTR_XFLAGS_DOWN : 0), at.x(), at.y()); break;+ default: break;+ }+}++void move(Client *client, QPoint at)+{+ client->sendMouse(PTR_FLAGS_MOVE, at.x(), at.y());+}++void wheel(Client *client, QPoint angleDelta, QPoint at, int &pendingX, int &pendingY)+{+ pendingY += angleDelta.y();+ pendingX -= angleDelta.x();+ auto send = [&](int &pending, quint16 axis) {+ while (pending != 0) {+ const int step = std::clamp(pending, -255, 255);+ pending -= step;+ const quint16 flags = axis | quint16(step < 0 ? (PTR_FLAGS_WHEEL_NEGATIVE | ((step + 256) & 0xff)) : step);+ client->sendWheel(flags, at.x(), at.y());+ }+ };+ send(pendingY, PTR_FLAGS_WHEEL);+ send(pendingX, PTR_FLAGS_HWHEEL);+}++void key(Client *client, const QKeyEvent *event, bool press, QList<quint32> &down)+{+ const quint32 native = event->nativeScanCode();+ const quint32 evdev = native > 8 ? native - 8 : 0;+ if (press) {+ if (evdev == 119) {+ client->sendPause();+ return;+ }+ if (const quint32 scancode = keymap::rdpScancode(evdev)) {+ client->sendKey(true, event->isAutoRepeat(), scancode);+ if (!down.contains(scancode)) {+ down.append(scancode);+ }+ return;+ }+ for (const QChar c : event->text()) {+ client->sendUnicode(true, c.unicode());+ client->sendUnicode(false, c.unicode());+ }+ return;+ }+ if (event->isAutoRepeat()) {+ return;+ }+ if (const quint32 scancode = keymap::rdpScancode(evdev)) {+ client->sendKey(false, false, scancode);+ down.removeAll(scancode);+ }+}++void releaseAll(Client *client, QList<quint32> &down)+{+ for (const quint32 scancode : std::as_const(down)) {+ client->sendKey(false, false, scancode);+ }+ down.clear();+}++void chord(Client *client, const QList<quint32> &scancodes)+{+ for (const quint32 s : scancodes) {+ client->sendKey(true, false, s);+ }+ for (auto it = scancodes.crbegin(); it != scancodes.crend(); ++it) {+ client->sendKey(false, false, *it);+ }+}+}diff --git a/packages/wildos-rdp/src/input.h b/packages/wildos-rdp/src/input.hnew file mode 100644index 0000000..ab2959d--- /dev/null+++ b/packages/wildos-rdp/src/input.h@@ -0,0 +1,43 @@+#pragma once++#include <QList>+#include <QPoint>+#include <Qt>++class Client;+class QKeyEvent;++// The keyboard and pointer as RDP takes them, for every window the engine+// draws into: a Windows mode app's window and a whole remote desktop.+// Points are in the remote desktop's pixels.+namespace rdpinput+{+void button(Client *client, Qt::MouseButton button, bool down, QPoint at);+void move(Client *client, QPoint at);++// Wheels and touchpads alike: Windows takes 120 units a notch and finer+// steps for smooth scrolling. What doesn't fit in one message waits in+// `pendingX` and `pendingY` for the next.+void wheel(Client *client, QPoint angleDelta, QPoint at, int &pendingX, int &pendingY);++// A key, by the scancode of the physical key behind it, or as the character+// it typed when there is no key (an input method, the on-screen keyboard).+// Keys sent down are kept in `down` until they are sent up.+void key(Client *client, const QKeyEvent *event, bool press, QList<quint32> &down);+// Every key still down goes up: the window lost the keyboard, and Windows+// would otherwise keep Alt (from Alt+Tab) held.+void releaseAll(Client *client, QList<quint32> &down);++// A chord of scancodes pressed in order and let go in reverse, for keys the+// desktop keeps for itself (Ctrl+Alt+Del, the Windows key).+void chord(Client *client, const QList<quint32> &scancodes);++// Scancodes for the chords Remote's Keys menu sends.+constexpr quint32 ctrl = 0x1D;+constexpr quint32 alt = 0x38;+constexpr quint32 shift = 0x2A;+constexpr quint32 del = 0x53 | 0x100;+constexpr quint32 tab = 0x0F;+constexpr quint32 windows = 0x5B | 0x100;+constexpr quint32 printScreen = 0x37 | 0x100;+}diff --git a/packages/wildos-rdp/src/keymap.cpp b/packages/wildos-rdp/src/keymap.cppnew file mode 100644index 0000000..cdc9b71--- /dev/null+++ b/packages/wildos-rdp/src/keymap.cpp@@ -0,0 +1,159 @@+#include "keymap.h"++#include <QFile>+#include <QSettings>+#include <QStandardPaths>+#include <QString>++namespace keymap+{+namespace+{+constexpr uint32_t ext = 0x100;++// Linux key codes 1 to 88 are the PC keyboard's set 1 make codes; the rest+// are listed one by one.+uint32_t beyondSetOne(uint32_t evdev)+{+ switch (evdev) {+ case 89: return 0x73; // RO+ case 92: return 0x79; // Henkan+ case 93: return 0x70; // Katakana/Hiragana+ case 94: return 0x7B; // Muhenkan+ case 96: return 0x1C | ext; // keypad Enter+ case 97: return 0x1D | ext; // right Ctrl+ case 98: return 0x35 | ext; // keypad /+ case 99: return 0x37 | ext; // Print Screen+ case 100: return 0x38 | ext; // right Alt (AltGr)+ case 102: return 0x47 | ext; // Home+ case 103: return 0x48 | ext; // Up+ case 104: return 0x49 | ext; // Page Up+ case 105: return 0x4B | ext; // Left+ case 106: return 0x4D | ext; // Right+ case 107: return 0x4F | ext; // End+ case 108: return 0x50 | ext; // Down+ case 109: return 0x51 | ext; // Page Down+ case 110: return 0x52 | ext; // Insert+ case 111: return 0x53 | ext; // Delete+ case 113: return 0x20 | ext; // Mute+ case 114: return 0x2E | ext; // Volume down+ case 115: return 0x30 | ext; // Volume up+ case 117: return 0x59; // keypad =+ case 121: return 0x7E; // keypad , (Brazil)+ case 122: return 0x72; // Hangul+ case 123: return 0x71; // Hanja+ case 124: return 0x7D; // Yen+ case 125: return 0x5B | ext; // left Windows+ case 126: return 0x5C | ext; // right Windows+ case 127: return 0x5D | ext; // Menu+ case 140: return 0x21 | ext; // Calculator+ case 155: return 0x6C | ext; // Mail+ case 158: return 0x6A | ext; // Back+ case 159: return 0x69 | ext; // Forward+ case 163: return 0x19 | ext; // Next track+ case 164: return 0x22 | ext; // Play/Pause+ case 165: return 0x10 | ext; // Previous track+ case 166: return 0x24 | ext; // Stop+ case 172: return 0x32 | ext; // Home page+ case 217: return 0x65 | ext; // Search+ default: break;+ }+ if (evdev >= 183 && evdev <= 193) {+ return 0x64 + (evdev - 183); // F13 to F23+ }+ if (evdev == 194) {+ return 0x76; // F24+ }+ return 0;+}++struct Layout {+ const char *xkb;+ uint32_t klid;+};++// Plasma's layout names (xkb) to Windows' keyboard layout identifiers.+constexpr Layout layouts[] = {+ {"us", 0x00000409}, {"us(intl)", 0x00020409}, {"us(alt-intl)", 0x00020409}, {"us(dvorak)", 0x00010409},+ {"gb", 0x00000809}, {"ie", 0x00001809}, {"de", 0x00000407}, {"at", 0x00000C07},+ {"ch", 0x00000807}, {"ch(fr)", 0x0000100C}, {"fr", 0x0000040C}, {"be", 0x0000080C},+ {"ca", 0x00001009}, {"ca(multix)", 0x00011009}, {"es", 0x0000040A}, {"latam", 0x0000080A},+ {"pt", 0x00000816}, {"br", 0x00000416}, {"it", 0x00000410}, {"nl", 0x00000413},+ {"se", 0x0000041D}, {"no", 0x00000414}, {"dk", 0x00000406}, {"fi", 0x0000040B},+ {"is", 0x0000040F}, {"pl", 0x00000415}, {"cz", 0x00000405}, {"sk", 0x0000041B},+ {"hu", 0x0000040E}, {"ru", 0x00000419}, {"ua", 0x00000422}, {"gr", 0x00000408},+ {"tr", 0x0000041F}, {"jp", 0x00000411}, {"kr", 0x00000412}, {"il", 0x0000040D},+ {"ara", 0x00000401}, {"ro", 0x00010418}, {"hr", 0x0000041A}, {"si", 0x00000424},+ {"rs", 0x00000C1A}, {"bg", 0x00030402}, {"lt", 0x00010427}, {"lv", 0x00020426},+ {"ee", 0x00000425},+};++uint32_t lookup(const QString &layout, const QString &variant)+{+ const QString full = variant.isEmpty() ? layout : layout + u'(' + variant + u')';+ for (const Layout &l : layouts) {+ if (full == QLatin1String(l.xkb)) {+ return l.klid;+ }+ }+ for (const Layout &l : layouts) {+ if (layout == QLatin1String(l.xkb)) {+ return l.klid;+ }+ }+ return 0;+}++QString first(const QString &list)+{+ return list.section(u',', 0, 0).trimmed();+}+}++uint32_t rdpScancode(uint32_t evdev)+{+ if (evdev >= 1 && evdev <= 88 && evdev != 84 && evdev != 85) {+ return evdev;+ }+ return beyondSetOne(evdev);+}++uint32_t windowsLayout()+{+ const QString kxkbrc = QStandardPaths::locate(QStandardPaths::GenericConfigLocation, QStringLiteral("kxkbrc"));+ if (!kxkbrc.isEmpty()) {+ QSettings s(kxkbrc, QSettings::IniFormat);+ s.beginGroup(QStringLiteral("Layout"));+ const QString layout = first(s.value(QStringLiteral("LayoutList")).toString());+ const QString variant = first(s.value(QStringLiteral("VariantList")).toString());+ if (!layout.isEmpty()) {+ if (const uint32_t id = lookup(layout, variant)) {+ return id;+ }+ }+ }+ // Plasma follows the system layout until the person picks one.+ QFile system(QStringLiteral("/etc/default/keyboard"));+ if (system.open(QIODevice::ReadOnly)) {+ QString layout, variant;+ for (const QByteArray &raw : system.readAll().split('\n')) {+ const QString line = QString::fromUtf8(raw).trimmed();+ const QString value = line.section(u'=', 1).remove(u'"').trimmed();+ if (line.startsWith(QLatin1String("XKBLAYOUT="))) {+ layout = first(value);+ } else if (line.startsWith(QLatin1String("XKBVARIANT="))) {+ variant = first(value);+ }+ }+ if (const uint32_t id = lookup(layout, variant)) {+ return id;+ }+ }+ const QString lang = qEnvironmentVariable("LANG");+ const QString territory = lang.section(u'_', 1).section(u'.', 0, 0).toLower();+ if (territory == QLatin1String("us")) {+ return 0x00000409;+ }+ return lookup(territory, {});+}+}diff --git a/packages/wildos-rdp/src/keymap.h b/packages/wildos-rdp/src/keymap.hnew file mode 100644index 0000000..44a0716--- /dev/null+++ b/packages/wildos-rdp/src/keymap.h@@ -0,0 +1,16 @@+#pragma once++#include <cstdint>++namespace keymap+{+// The RDP scancode (FreeRDP's form: the make code, with 0x100 for the E0+// extended keys) for a Linux evdev key code, or 0 for a key RDP has no+// scancode for.+uint32_t rdpScancode(uint32_t evdev);++// The Windows keyboard layout (KLID) matching the person's first Plasma+// keyboard layout, or their language when Plasma names none; 0 when+// neither is known, which leaves Windows on its own default.+uint32_t windowsLayout();+}diff --git a/packages/wildos-rdp/src/kwin.cpp b/packages/wildos-rdp/src/kwin.cppnew file mode 100644index 0000000..999a356--- /dev/null+++ b/packages/wildos-rdp/src/kwin.cpp@@ -0,0 +1,97 @@+#include "kwin.h"++#include <QCoreApplication>+#include <QDBusConnection>+#include <QDBusMessage>+#include <QDBusPendingCall>+#include <QDir>+#include <QFile>+#include <QJsonArray>+#include <QJsonDocument>+#include <QJsonObject>+#include <QSaveFile>+#include <QStandardPaths>+#include <QTimer>+#include <QWindow>++namespace+{+// The window is found by this process, its app id and its size now; the+// script runs once, inside KWin, and is unloaded again.+const char *script = R"(import QtQuick+import org.kde.kwin as KWin++Item {+ Component.onCompleted: {+ const want = %1;+ for (const w of KWin.Workspace.windows) {+ const g = w.frameGeometry;+ if (w.deleted || w.pid !== want.pid || String(w.desktopFileName) !== want.app+ || Math.round(g.width) !== want.from[0] || Math.round(g.height) !== want.from[1]) {+ continue;+ }+ let x = g.x + (g.width - want.to[0]) / 2;+ let y = g.y + (g.height - want.to[1]) / 2;+ const area = KWin.Workspace.clientArea(KWin.Workspace.PlacementArea, w);+ if (area && area.width > 0) {+ x = Math.max(area.x, Math.min(x, area.x + area.width - Math.min(want.to[0], area.width)));+ y = Math.max(area.y, Math.min(y, area.y + area.height - Math.min(want.to[1], area.height)));+ }+ w.frameGeometry = Qt.rect(Math.round(x), Math.round(y), want.to[0], want.to[1]);+ break;+ }+ }+}+)";++QDBusMessage kwinCall(const QString &path, const QString &interface, const QString &method, const QVariantList &args)+{+ QDBusMessage m = QDBusMessage::createMethodCall(QStringLiteral("org.kde.KWin"), path, interface, method);+ m.setArguments(args);+ return m;+}+}++bool KWinPlace::resizeAroundCentre(QWindow *window, const QString &appId, const QSize &to)+{+ const QString dir = QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation);+ if (dir.isEmpty() || !window->isVisible()) {+ return false;+ }+ static int serial = 0;+ const QString name = QStringLiteral("wildos-rdp-centre-%1-%2").arg(QCoreApplication::applicationPid()).arg(++serial);+ const QString path = dir + u'/' + name + QStringLiteral(".qml");+ QJsonObject want;+ want.insert(QStringLiteral("pid"), qint64(QCoreApplication::applicationPid()));+ want.insert(QStringLiteral("app"), appId);+ want.insert(QStringLiteral("from"), QJsonArray{window->width(), window->height()});+ want.insert(QStringLiteral("to"), QJsonArray{to.width(), to.height()});+ QSaveFile file(path);+ if (!file.open(QIODevice::WriteOnly)) {+ return false;+ }+ file.write(QString::fromLatin1(script).arg(QString::fromUtf8(QJsonDocument(want).toJson(QJsonDocument::Compact))).toUtf8());+ if (!file.commit()) {+ return false;+ }+ QDBusConnection bus = QDBusConnection::sessionBus();+ const QDBusMessage loaded = bus.call(kwinCall(QStringLiteral("/Scripting"), QStringLiteral("org.kde.kwin.Scripting"),+ QStringLiteral("loadDeclarativeScript"), {path, name}),+ QDBus::Block, 500);+ const int id = loaded.arguments().value(0).toInt();+ bool ok = loaded.type() == QDBusMessage::ReplyMessage && id >= 0;+ if (ok) {+ const QDBusMessage ran = bus.call(kwinCall(QStringLiteral("/Scripting/Script%1").arg(id), QStringLiteral("org.kde.kwin.Script"),+ QStringLiteral("run"), {}),+ QDBus::Block, 500);+ ok = ran.type() == QDBusMessage::ReplyMessage;+ }+ // KWin has read the file once the script is running; the script is+ // unloaded when it has had time to run.+ QTimer::singleShot(2000, [name, path] {+ QDBusConnection::sessionBus().asyncCall(+ kwinCall(QStringLiteral("/Scripting"), QStringLiteral("org.kde.kwin.Scripting"), QStringLiteral("unloadScript"), {name}));+ QFile::remove(path);+ });+ return ok;+}diff --git a/packages/wildos-rdp/src/kwin.h b/packages/wildos-rdp/src/kwin.hnew file mode 100644index 0000000..925d2f7--- /dev/null+++ b/packages/wildos-rdp/src/kwin.h@@ -0,0 +1,16 @@+#pragma once++class QSize;+class QString;+class QWindow;++// Wayland leaves where a window is to the compositor: a window that changes+// size from its own side grows and shrinks from its top left corner. KWin+// can move and resize it in one step, so a loading window that takes its+// app's size does so about its centre.+namespace KWinPlace+{+// Asks KWin to give the window this size with its centre where it is.+// False when KWin cannot be asked; the window then resizes itself.+bool resizeAroundCentre(QWindow *window, const QString &appId, const QSize &to);+}diff --git a/packages/wildos-rdp/src/loading.cpp b/packages/wildos-rdp/src/loading.cppnew file mode 100644index 0000000..c6c82b9--- /dev/null+++ b/packages/wildos-rdp/src/loading.cpp@@ -0,0 +1,700 @@+#include "loading.h"++#include <QFont>+#include <QFontMetricsF>+#include <QLinearGradient>+#include <QPainter>+#include <QRadialGradient>+#include <QTextLayout>++#include <algorithm>+#include <cmath>+#include <initializer_list>+#include <utility>+#include <vector>++namespace+{+// The board's loop and where the window starts in it (wlwin begins at 2%).+constexpr double loop = 9.0;+constexpr double introOffset = 0.18;+// Where the board's app is ready: the light has run its laps and the full+// trace starts (wlcomplete, 59.5%).+constexpr double readyPercent = 59.5;+constexpr double lap = 1.75;+constexpr double boardLength = 441;+constexpr double slowAfter = 20;+constexpr double titleBar = 40;++// branding/logo/wild-os-mark.svg, as the board has it.+const QPointF wPoints[] = {{37, 17}, {50.34, 40}, {64.75, 64.84}, {79.16, 40}, {92.5, 17}, {105.84, 40},+ {134.26, 89}, {120.76, 112.28}, {92.5, 63.55}, {64.91, 111.12}, {23.66, 40}};+const QPointF sparkPoints[] = {{148.5, 17}, {162, 40}, {148.5, 63}, {135, 40}};+const QPointF sparkCentre(148.5, 40);++// CSS cubic-bezier easing.+double bezier(double u, double x1, double y1, double x2, double y2)+{+ if (u <= 0) {+ return 0;+ }+ if (u >= 1) {+ return 1;+ }+ double lo = 0, hi = 1;+ for (int n = 0; n < 28; ++n) {+ const double m = (lo + hi) / 2;+ const double x = 3 * (1 - m) * (1 - m) * m * x1 + 3 * (1 - m) * m * m * x2 + m * m * m;+ (x < u ? lo : hi) = m;+ }+ const double m = (lo + hi) / 2;+ return 3 * (1 - m) * (1 - m) * m * y1 + 3 * (1 - m) * m * m * y2 + m * m * m;+}++double ease(double u)+{+ return bezier(u, 0.4, 0, 0.2, 1);+}++// A keyframed value at x percent of the loop: the board's @keyframes, each+// step eased as CSS eases it.+double keyframes(double x, std::initializer_list<std::pair<double, double>> stops, double (*curve)(double) = ease)+{+ const auto *first = stops.begin();+ const auto *last = stops.end() - 1;+ if (x <= first->first) {+ return first->second;+ }+ if (x >= last->first) {+ return last->second;+ }+ for (const auto *s = first; s != last; ++s) {+ const auto *next = s + 1;+ if (x <= next->first) {+ const double span = next->first - s->first;+ const double u = span > 0 ? curve((x - s->first) / span) : 1;+ return s->second + (next->second - s->second) * u;+ }+ }+ return last->second;+}++double completeCurve(double u)+{+ return bezier(u, 0.45, 0, 0.2, 1);+}++QLinearGradient wla()+{+ QLinearGradient g(0, 17, 0, 113);+ g.setColorAt(0, QColor(0xb4, 0xca, 0xff));+ g.setColorAt(0.5, QColor(0x7d, 0x97, 0xec));+ g.setColorAt(1, QColor(0xf0, 0xa3, 0xae));+ return g;+}++QLinearGradient wlt()+{+ QLinearGradient g(20, 0, 165, 0);+ g.setColorAt(0, QColor(0xcf, 0xdc, 0xff));+ g.setColorAt(0.5, QColor(0xff, 0xff, 0xff));+ g.setColorAt(1, QColor(0xff, 0xd2, 0xc8));+ return g;+}++QFont font(double px, int weight = QFont::Normal)+{+ QFont f(QStringLiteral("Inter"));+ f.setPixelSize(int(std::lround(px)));+ f.setWeight(QFont::Weight(weight));+ return f;+}++QColor rgba(int r, int g, int b, double a)+{+ return QColor::fromRgbF(r / 255.0, g / 255.0, b / 255.0, a);+}++// Part of the W's outline: `length` units from `from`, going round, in the+// board's units (the outline is 441 long there).+QPainterPath along(double from, double length, double total)+{+ const double scale = total / boardLength;+ from = std::fmod(from * scale, total);+ if (from < 0) {+ from += total;+ }+ length = std::min(length * scale, total);+ QPainterPath out;+ const int n = int(std::size(wPoints));+ double at = 0;+ bool started = false;+ double remaining = length;+ // Twice round, so a piece that wraps past the start is drawn whole.+ for (int i = 0; i < 2 * n && remaining > 0; ++i) {+ const QPointF a = wPoints[i % n];+ const QPointF b = wPoints[(i + 1) % n];+ const double edge = std::hypot(b.x() - a.x(), b.y() - a.y());+ const double end = at + edge;+ if (end > from) {+ const double s0 = std::max(from, at);+ const double take = std::min(end - s0, remaining);+ const QPointF p0 = a + (b - a) * ((s0 - at) / edge);+ const QPointF p1 = a + (b - a) * ((s0 + take - at) / edge);+ if (!started) {+ out.moveTo(p0);+ started = true;+ }+ out.lineTo(p1);+ remaining -= take;+ from = s0 + take;+ }+ at = end;+ }+ return out;+}++void glowStroke(QPainter &p, const QPainterPath &path, double opacity, bool roundCap)+{+ const double base = p.opacity();+ // drop-shadow(0 0 3px rgba(185,207,255,0.95)) drop-shadow(0 0 10px+ // rgba(143,180,255,0.6)), drawn as soft wide strokes under the line.+ const Qt::PenCapStyle cap = roundCap ? Qt::RoundCap : Qt::FlatCap;+ const struct {+ double width;+ QColor colour;+ } layers[] = {+ {16, rgba(143, 180, 255, 0.05)}, {11, rgba(143, 180, 255, 0.08)}, {7, rgba(143, 180, 255, 0.12)},+ {4.5, rgba(185, 207, 255, 0.30)}, {2.8, rgba(185, 207, 255, 0.55)},+ };+ for (const auto &l : layers) {+ QColor c = l.colour;+ c.setAlphaF(c.alphaF() * opacity);+ p.strokePath(path, QPen(c, l.width, Qt::SolidLine, cap, Qt::RoundJoin));+ }+ QPen line(QBrush(wlt()), 1.4, Qt::SolidLine, cap, Qt::RoundJoin);+ p.setOpacity(base * opacity);+ p.strokePath(path, line);+ p.setOpacity(base);+}++// Text laid out in lines of a set height, centred, as the board's+// paragraphs are.+double drawParagraph(QPainter &p, const QString &text, const QFont &f, double width, double lineHeight, const QPointF &topCentre, bool draw)+{+ QTextLayout layout(text, f);+ layout.beginLayout();+ double y = 0;+ std::vector<std::pair<QTextLine, double>> lines;+ for (;;) {+ QTextLine line = layout.createLine();+ if (!line.isValid()) {+ break;+ }+ line.setLineWidth(width);+ lines.emplace_back(line, y);+ y += lineHeight;+ }+ layout.endLayout();+ if (draw) {+ for (auto &[line, top] : lines) {+ const double x = topCentre.x() - line.naturalTextWidth() / 2 - line.x();+ line.draw(&p, QPointF(x, topCentre.y() + top + (lineHeight - line.height()) / 2));+ }+ }+ return y;+}+}++LoadingView::LoadingView()+{+ m_w.moveTo(wPoints[0]);+ m_length = 0;+ for (size_t i = 1; i <= std::size(wPoints); ++i) {+ const QPointF a = wPoints[i - 1];+ const QPointF b = wPoints[i % std::size(wPoints)];+ m_length += std::hypot(b.x() - a.x(), b.y() - a.y());+ if (i < std::size(wPoints)) {+ m_w.lineTo(b);+ }+ }+ m_w.closeSubpath();+ m_spark.moveTo(sparkPoints[0]);+ for (size_t i = 1; i < std::size(sparkPoints); ++i) {+ m_spark.lineTo(sparkPoints[i]);+ }+ m_spark.closeSubpath();+}++void LoadingView::start(const QString &appName, const QIcon &icon, bool reducedMotion)+{+ m_app = appName;+ m_icon = icon;+ m_still = reducedMotion;+ m_stage = Stage::Starting;+ m_finishAt = -1;+ m_clock.start();+}++double LoadingView::seconds() const+{+ return m_clock.isValid() ? m_clock.elapsed() / 1000.0 : 0;+}++void LoadingView::setStage(Stage stage)+{+ if (stage != m_stage) {+ m_stage = stage;+ m_stageAt = seconds();+ }+}++void LoadingView::setReason(const QString &reason, int percent, const QString &progress)+{+ m_reason = reason;+ m_percent = percent;+ m_progress = progress;+}++void LoadingView::finish()+{+ if (m_finishAt < 0) {+ m_finishAt = seconds();+ }+}++bool LoadingView::slow() const+{+ return m_ended || (m_finishAt < 0 && !m_arrived && seconds() >= slowAfter);+}++void LoadingView::setEnded()+{+ m_ended = true;+ m_reason = QStringLiteral("It may have run into a problem. You can try opening it again.");+ m_percent = -1;+}++double LoadingView::introPercent() const+{+ if (m_still) {+ return readyPercent;+ }+ return std::min((seconds() + introOffset) / loop * 100, readyPercent);+}++double LoadingView::finishPercent() const+{+ if (m_finishAt < 0) {+ return introPercent();+ }+ if (m_still) {+ return 100;+ }+ return std::min(readyPercent + (seconds() - m_finishAt) / loop * 100, 100.0);+}++bool LoadingView::done() const+{+ return m_finishAt >= 0 && finishPercent() >= 79;+}++bool LoadingView::animating() const+{+ // The light keeps running its laps however long opening takes: a still+ // picture on screen reads as something that has stopped. Once the app+ // has ended nothing is under way, and nothing moves.+ return !m_still && !m_ended;+}++double LoadingView::appOpacity() const+{+ if (m_finishAt < 0) {+ return 0;+ }+ return keyframes(finishPercent(), {{70, 0}, {79, 1}});+}++QRectF LoadingView::buttonRect(Hit which, const QSizeF &size) const+{+ switch (which) {+ case Hit::Minimise: return QRectF(size.width() - 138, 0, 46, titleBar);+ case Hit::Maximise: return QRectF(size.width() - 92, 0, 46, titleBar);+ case Hit::Close: return QRectF(size.width() - 46, 0, 46, titleBar);+ default: return {};+ }+}++void LoadingView::paintTitleBar(QPainter &p, const QSizeF &size, double chipOpacity) const+{+ p.fillRect(QRectF(0, 0, size.width(), titleBar), rgba(6, 8, 20, 0.55));+ double x = 14;+ if (!m_icon.isNull()) {+ m_icon.paint(&p, QRect(int(x), 11, 18, 18));+ }+ x += 18 + 10;+ const QFont name = font(13, QFont::Medium);+ p.setFont(name);+ p.setPen(QColor(0xee, 0xf1, 0xf8));+ const double nameWidth = QFontMetricsF(name).horizontalAdvance(m_app);+ p.drawText(QRectF(x, 0, nameWidth + 2, titleBar), Qt::AlignVCenter | Qt::AlignLeft, m_app);+ x += nameWidth + 10;+ if (chipOpacity > 0) {+ const QFont chipFont = font(11);+ const QString chip = QStringLiteral("Windows");+ const double w = QFontMetricsF(chipFont).horizontalAdvance(chip) + 16;+ const QRectF r(x, 10, w, 20);+ const double before = p.opacity();+ p.setOpacity(before * chipOpacity);+ p.setPen(Qt::NoPen);+ p.setBrush(rgba(143, 180, 255, 0.14));+ p.drawRoundedRect(r, 10, 10);+ p.setFont(chipFont);+ p.setPen(QColor(0xb9, 0xcf, 0xff));+ p.drawText(r, Qt::AlignCenter, chip);+ p.setOpacity(before);+ }+ const QColor ink(0xee, 0xf1, 0xf8);+ for (Hit b : {Hit::Minimise, Hit::Maximise, Hit::Close}) {+ const QRectF r = buttonRect(b, size);+ if (m_hover == b) {+ p.fillRect(r, rgba(255, 255, 255, 0.08));+ }+ p.save();+ // The glyphs are 11 px drawings of a 12 unit box.+ p.translate(r.center().x() - 5.5, r.center().y() - 5.5);+ p.scale(11.0 / 12, 11.0 / 12);+ p.setBrush(Qt::NoBrush);+ if (b == Hit::Minimise) {+ p.setPen(QPen(ink, 1.3));+ p.drawLine(QPointF(1.5, 6), QPointF(10.5, 6));+ } else if (b == Hit::Maximise) {+ p.setPen(QPen(ink, 1.2));+ p.drawRoundedRect(QRectF(1.5, 1.5, 9, 9), 1.8, 1.8);+ } else {+ p.setPen(QPen(ink, 1.3, Qt::SolidLine, Qt::RoundCap));+ p.drawLine(QPointF(2, 2), QPointF(10, 10));+ p.drawLine(QPointF(10, 2), QPointF(2, 10));+ }+ p.restore();+ }+}++void LoadingView::paintMark(QPainter &p, const QPointF &origin, double x, double t) const+{+ p.save();+ // The board's 150 px square with viewBox "18 -10.5 150 150".+ p.translate(origin.x() - 18, origin.y() + 10.5);+ const double o = p.opacity();++ // wlbase: the dim W the light runs over.+ const double base = m_still ? 1 : keyframes(x, {{9, 0}, {13, 1}, {62, 1}, {70, 0}});+ if (base > 0) {+ p.setOpacity(o * (base * 0.12));+ p.fillPath(m_w, wla());+ p.setOpacity(o * (base));+ p.strokePath(m_w, QPen(rgba(201, 216, 255, 0.24), 0.9, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin));+ p.setOpacity(o);+ }++ // wltraceon and wltr: a 64 unit light running laps, 1.75 s each. Board+ // 9.13 stops it when opening takes longer; it keeps running here, so+ // the slow state never looks like a crash.+ if (!m_still) {+ const double on = m_ended ? 0 : keyframes(x, {{12, 0}, {14, 1}, {59.5, 1}, {61.5, 0}});+ if (on > 0) {+ const double offset = boardLength * (1 - std::fmod(t + introOffset, lap) / lap);+ glowStroke(p, along(boardLength - offset, 64, m_length), on, true);+ }+ }++ // wlfill: the W in full colour as the app arrives.+ const double fill = keyframes(x, {{62, 0}, {66.5, 1}, {71, 1}, {76, 0}});+ if (fill > 0) {+ p.setOpacity(o * (fill));+ p.fillPath(m_w, wla());+ p.setOpacity(o);+ }++ // wldraw: the outline drawing itself in.+ if (!m_still) {+ const double drawn = boardLength - keyframes(x, {{0, 441}, {4, 441}, {11, 0}});+ const double opacity = keyframes(x, {{0, 1}, {11, 1}, {14, 0}});+ if (drawn > 0 && opacity > 0) {+ p.setOpacity(o * (opacity));+ p.strokePath(along(0, drawn, m_length), QPen(QColor(0xc9, 0xd8, 0xff), 1, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin));+ p.setOpacity(o);+ }+ }++ // wlcomplete: one full trace once the app is ready.+ if (m_finishAt >= 0 && !m_still) {+ const double drawn = boardLength - keyframes(x, {{59.5, 441}, {66, 0}}, completeCurve);+ const double opacity = keyframes(x, {{66, 1}, {70, 0}});+ if (drawn > 0 && opacity > 0) {+ glowStroke(p, along(0, drawn, m_length), opacity, false);+ }+ }++ // wlflash: the spark's flash.+ const double flash = keyframes(x, {{64.9, 0}, {67, 0.95}, {73, 0}});+ if (flash > 0) {+ const double s = keyframes(x, {{64.9, 0.3}, {67, 1}, {73, 1.9}});+ QRadialGradient g(sparkCentre, 34 * s);+ g.setColorAt(0, rgba(255, 255, 255, 0.95));+ g.setColorAt(0.45, rgba(185, 207, 255, 0.4));+ g.setColorAt(1, rgba(185, 207, 255, 0));+ p.setOpacity(o * (std::min(1.0, flash / 0.95)));+ p.setPen(Qt::NoPen);+ p.setBrush(g);+ p.drawEllipse(sparkCentre, 34 * s, 34 * s);+ p.setOpacity(o);+ }++ // wldia: the spark pops in, pulses when the app is ready, and goes.+ const double dia = m_still ? 1 : keyframes(x, {{3, 0}, {6.5, 1}, {69, 1}, {74, 0}});+ if (dia > 0) {+ const double s = m_still ? 1 : keyframes(x, {{3, 0}, {6.5, 1.3}, {8.5, 1}, {63, 1}, {66.5, 1.35}, {69, 1}, {74, 0.6}});+ const double turn = m_still ? 0 : keyframes(x, {{3, -45}, {6.5, 0}});+ const double shift = m_still ? 0 : keyframes(x, {{69, 0}, {74, 1}});+ p.save();+ p.translate(sparkCentre + QPointF(10 * shift, -10 * shift));+ p.rotate(turn);+ p.scale(s, s);+ p.translate(-sparkCentre);+ p.setOpacity(o * (dia));+ p.fillPath(m_spark, wla());+ p.restore();+ }+ p.restore();+}++void LoadingView::paint(QPainter &p, const QSizeF &size, bool background, bool foreground) const+{+ const double t = seconds();+ const double x = finishPercent();+ p.save();+ p.setRenderHint(QPainter::Antialiasing);+ p.setRenderHint(QPainter::TextAntialiasing);++ // wlwin: the window fades and grows in from 97%, about 50% 40%.+ const double intro = m_still ? 1 : keyframes(std::min((t + introOffset) / loop * 100, 4.5), {{2, 0}, {4.5, 1}});+ const double introScale = m_still ? 1 : keyframes(std::min((t + introOffset) / loop * 100, 4.5), {{2, 0.97}, {4.5, 1}});+ // wlloader: the loader fades out (and grows to 104%) as the app fades in.+ const double loader = keyframes(x, {{70, 1}, {78, 0}});+ const double loaderScale = keyframes(x, {{70, 1}, {78, 1.04}});+ const double chip = keyframes(x, {{70, 1}, {78, 0}});++ p.translate(size.width() / 2, size.height() * 0.4);+ p.scale(introScale, introScale);+ p.translate(-size.width() / 2, -size.height() * 0.4);+ p.setOpacity(intro * loader);++ QPainterPath frame;+ frame.addRoundedRect(QRectF(QPointF(0, 0), size).adjusted(0.5, 0.5, -0.5, -0.5), 12, 12);+ if (background) {+ p.fillPath(frame, rgba(16, 20, 38, 0.94));+ }+ p.save();+ p.setClipPath(frame);++ // The body's glow: radial-gradient(ellipse at 50% 42%, rgba(61,91,201,+ // 0.20), transparent 60%), sized to the farthest corner.+ const QRectF body(0, titleBar, size.width(), size.height() - titleBar);+ if (background) {+ const QPointF c(body.center().x(), body.top() + body.height() * 0.42);+ const double rx = body.width() / 2 * M_SQRT2;+ const double ry = std::max(c.y() - body.top(), body.bottom() - c.y()) * M_SQRT2;+ p.save();+ p.translate(c);+ p.scale(1, ry / rx);+ QRadialGradient g(QPointF(0, 0), rx);+ g.setColorAt(0, rgba(61, 91, 201, 0.20));+ g.setColorAt(0.6, rgba(16, 20, 38, 0));+ p.fillRect(QRectF(-rx, -rx, 2 * rx, 2 * rx), g);+ p.restore();+ }++ if (background) {+ paintTitleBar(p, size, chip);+ }+ if (!foreground) {+ p.restore();+ p.setOpacity(intro * loader);+ p.setPen(QPen(rgba(255, 255, 255, 0.11), 1));+ p.setBrush(Qt::NoBrush);+ p.drawPath(frame);+ p.restore();+ return;+ }++ // The body, scaled with wlloader about its centre.+ p.save();+ p.translate(body.center());+ p.scale(loaderScale, loaderScale);+ p.translate(-body.center());++ const bool isSlow = slow();+ const QFont titleFont = font(22, QFont::Medium);+ const QFont bodyFont = font(14);+ const double titleHeight = 27;+ double contentHeight = 150 - 40 + 26 + titleHeight + 10;+ double reasonHeight = 0;+ const bool bar = isSlow && m_percent >= 0;+ if (isSlow) {+ reasonHeight = drawParagraph(p, m_reason, bodyFont, 440, 14 * 1.55, QPointF(), false);+ contentHeight += reasonHeight + 26 + 34;+ if (bar) {+ contentHeight += 4 + 8 + 15 + 26;+ }+ } else {+ contentHeight += 20;+ }+ const double markTop = body.top() + (body.height() - contentHeight) / 2 - 40;+ paintMark(p, QPointF(body.center().x() - 75, markTop), x, t);++ double y = markTop + 150 + 26;+ const double title = m_still ? 1 : keyframes(x, {{6, 0}, {10, 1}, {70, 1}, {74, 0}});+ const double rise = m_still ? 0 : keyframes(x, {{6, 6}, {10, 0}});+ p.setOpacity(intro * loader * title);+ p.setFont(titleFont);+ p.setPen(Qt::white);+ const QString heading = (m_ended ? QStringLiteral("%1 closed before it opened")+ : isSlow ? QStringLiteral("Still opening %1")+ : QStringLiteral("Opening %1"))+ .arg(m_app);+ p.drawText(QRectF(0, y + rise, size.width(), titleHeight), Qt::AlignCenter, heading);+ y += titleHeight + 10;++ p.setFont(bodyFont);+ if (!isSlow) {+ // wls1 and wls2: "Starting Windows mode", then "Almost ready" once+ // the app's own process is up and drawing.+ const double in = m_still ? 1 : keyframes(x, {{10, 0}, {13, 1}});+ const double out = keyframes(x, {{68, 1}, {71, 0}});+ const double fade = 0.27;+ const double since = t - m_stageAt;+ const double almost = m_stage == Stage::AlmostReady ? (m_still ? 1 : std::clamp(since / fade, 0.0, 1.0)) : 0;+ const QRectF line(0, y, size.width(), 20);+ p.setPen(rgba(232, 236, 248, 0.85));+ p.setOpacity(intro * loader * 0.75 * in * out * (1 - almost));+ p.drawText(line, Qt::AlignCenter, QStringLiteral("Starting Windows mode"));+ p.setOpacity(intro * loader * 0.75 * out * almost);+ p.drawText(line, Qt::AlignCenter, QStringLiteral("Almost ready"));+ } else {+ p.setOpacity(intro * loader);+ p.setPen(rgba(232, 236, 248, 0.85));+ drawParagraph(p, m_reason, bodyFont, 440, 14 * 1.55, QPointF(size.width() / 2, y), true);+ y += reasonHeight + 26;+ if (bar) {+ const QRectF track(size.width() / 2 - 160, y, 320, 4);+ p.setPen(Qt::NoPen);+ p.setBrush(rgba(255, 255, 255, 0.1));+ p.drawRoundedRect(track, 2, 2);+ p.setBrush(QColor(0x8f, 0xb4, 0xff));+ p.drawRoundedRect(QRectF(track.topLeft(), QSizeF(320 * std::clamp(m_percent, 0, 100) / 100.0, 4)), 2, 2);+ p.setFont(font(12));+ p.setPen(rgba(232, 236, 248, 0.6));+ p.drawText(QRectF(0, y + 4 + 8, size.width(), 15), Qt::AlignCenter, m_progress.isEmpty() ? QStringLiteral("%1% done").arg(m_percent) : m_progress);+ y += 4 + 8 + 15 + 26;+ }+ const QFont buttonFont = font(13);+ QFontMetricsF fm(buttonFont);+ const auto [first, second] = buttons();+ const double cancelW = fm.horizontalAdvance(first.first) + 32;+ const double detailsW = fm.horizontalAdvance(second.first) + 32;+ double bx = size.width() / 2 - (cancelW + 8 + detailsW) / 2;+ p.setFont(buttonFont);+ for (const auto &[label, w, hit] : {std::tuple{first.first, cancelW, first.second},+ std::tuple{second.first, detailsW, second.second}}) {+ const QRectF r(bx, y, w, 34);+ p.setPen(QPen(rgba(255, 255, 255, 0.12), 1));+ p.setBrush(m_hover == hit ? rgba(255, 255, 255, 0.10) : rgba(255, 255, 255, 0.05));+ p.drawRoundedRect(r.adjusted(0.5, 0.5, -0.5, -0.5), 6, 6);+ p.setPen(QColor(0xee, 0xf1, 0xf8));+ p.drawText(r, Qt::AlignCenter, label);+ bx += w + 8;+ }+ }+ p.restore();+ p.restore();+ if (background) {+ p.setOpacity(intro * loader);+ p.setPen(QPen(rgba(255, 255, 255, 0.11), 1));+ p.setBrush(Qt::NoBrush);+ p.drawPath(frame);+ }+ p.restore();+}++LoadingView::Hit LoadingView::hitTest(const QPointF &at, const QSizeF &size) const+{+ for (Hit b : {Hit::Minimise, Hit::Maximise, Hit::Close}) {+ if (buttonRect(b, size).contains(at)) {+ return b;+ }+ }+ if (at.y() < titleBar) {+ return Hit::Drag;+ }+ if (!slow()) {+ return Hit::None;+ }+ // The two buttons sit at the bottom of the centred column; recompute+ // their place the way paint() lays it out.+ const QSizeF bodySize(size.width(), size.height() - titleBar);+ QFont bodyFont = font(14);+ QImage scratch(1, 1, QImage::Format_ARGB32_Premultiplied);+ QPainter p(&scratch);+ const double reasonHeight = drawParagraph(p, m_reason, bodyFont, 440, 14 * 1.55, QPointF(), false);+ const bool bar = m_percent >= 0;+ double contentHeight = 150 - 40 + 26 + 27 + 10 + reasonHeight + 26 + 34 + (bar ? 4 + 8 + 15 + 26 : 0);+ const double markTop = titleBar + (bodySize.height() - contentHeight) / 2 - 40;+ const double y = markTop + 150 + 26 + 27 + 10 + reasonHeight + 26 + (bar ? 4 + 8 + 15 + 26 : 0);+ QFontMetricsF fm(font(13));+ const auto [first, second] = buttons();+ const double cancelW = fm.horizontalAdvance(first.first) + 32;+ const double detailsW = fm.horizontalAdvance(second.first) + 32;+ const double bx = size.width() / 2 - (cancelW + 8 + detailsW) / 2;+ if (QRectF(bx, y, cancelW, 34).contains(at)) {+ return first.second;+ }+ if (QRectF(bx + cancelW + 8, y, detailsW, 34).contains(at)) {+ return second.second;+ }+ return Hit::None;+}++std::pair<std::pair<QString, LoadingView::Hit>, std::pair<QString, LoadingView::Hit>> LoadingView::buttons() const+{+ if (m_ended) {+ return {{QStringLiteral("Try again"), Hit::Retry}, {QStringLiteral("Close"), Hit::Cancel}};+ }+ return {{QStringLiteral("Cancel"), Hit::Cancel}, {QStringLiteral("Show details"), Hit::Details}};+}++QRectF LoadingView::steadyArea(const QSizeF &size) const+{+ const bool isSlow = slow();+ double contentHeight = 150 - 40 + 26 + 27 + 10 + 20;+ if (isSlow) {+ // Laid out as paint() does it in the slow state, where the reason,+ // the bar and the buttons push the mark up.+ if (m_measured != m_reason) {+ QImage scratch(1, 1, QImage::Format_ARGB32_Premultiplied);+ QPainter p(&scratch);+ m_measuredHeight = drawParagraph(p, m_reason, font(14), 440, 14 * 1.55, QPointF(), false);+ m_measured = m_reason;+ }+ contentHeight = 150 - 40 + 26 + 27 + 10 + m_measuredHeight + 26 + 34 + (m_percent >= 0 ? 4 + 8 + 15 + 26 : 0);+ }+ const double bodyHeight = size.height() - titleBar;+ const double markTop = titleBar + (bodyHeight - contentHeight) / 2 - 40;+ const QRectF mark = QRectF(size.width() / 2 - 75, markTop, 150, 150).adjusted(-24, -24, 24, 24);+ if (isSlow) {+ // Only the light moves; the words and buttons stay as painted.+ return mark;+ }+ const QRectF status(size.width() / 2 - 200, markTop + 150 + 26 + 27 + 10, 400, 20);+ return mark.united(status);+}diff --git a/packages/wildos-rdp/src/loading.h b/packages/wildos-rdp/src/loading.hnew file mode 100644index 0000000..f7e73b1--- /dev/null+++ b/packages/wildos-rdp/src/loading.h@@ -0,0 +1,100 @@+#pragma once++#include <QElapsedTimer>+#include <QIcon>+#include <QPainterPath>+#include <QPointF>+#include <QSizeF>+#include <QString>++#include <utility>++class QPainter;++// The window a Windows app opens in while Windows mode gets it ready+// (boards 9.11 to 9.13, WinAppLaunch*.dc.html): a title bar with the app's+// icon, name and the "Windows" chip, and the W from start-up drawing+// itself, a light running laps round it while Windows connects, then one+// full trace, the W filling with colour and the spark flashing as the app+// fades in. After 20 seconds it says why it is taking longer and offers a+// way out.+//+// The timings are the board's: its keyframes are percentages of a 9 s+// loop, evaluated here against the real moments (the click, the app being+// ready), so the sequence looks the same however long Windows takes.+class LoadingView+{+public:+ enum class Stage { Starting, AlmostReady };+ enum class Hit { None, Drag, Minimise, Maximise, Close, Cancel, Details, Retry };++ LoadingView();++ void start(const QString &appName, const QIcon &icon, bool reducedMotion);+ void setStage(Stage stage);+ // Why it is taking longer, in plain words, and how far along it is+ // (0 to 100) when there is anything to measure; -1 for no bar.+ void setReason(const QString &reason, int percent, const QString &progress);+ // The app is ready: the closing sequence starts now.+ void finish();+ // The app's window is here and only has to draw: from now on opening is+ // not slow, whatever the clock says (unless it already showed as slow).+ void arrive() { m_arrived = !slow(); }+ // The program ended without showing a window: the loading window says+ // so and offers Try again and Close (the slow state's layout).+ void setEnded();+ bool ended() const { return m_ended; }+ // The window it took was not the app's after all.+ void unarrive() { m_arrived = false; }++ bool finishing() const { return m_finishAt >= 0; }+ // The closing sequence has run: only the app is left.+ bool done() const;+ // Whether anything moves, so the window keeps asking for frames.+ bool animating() const;+ bool slow() const;+ // The window has finished fading in (wlwin), so its frame stays as it is.+ bool settled() const { return m_still || seconds() > 0.3; }+ // How much of the app shows through, 0 to 1.+ double appOpacity() const;++ // The frame, glow and title bar (background) and the W and its words+ // (foreground), so a caller can keep the first and redraw the second.+ void paint(QPainter &p, const QSizeF &size, bool background = true, bool foreground = true) const;+ // What changes while the light runs its laps: the mark, and the line+ // under it until opening turns slow.+ QRectF steadyArea(const QSizeF &size) const;+ Hit hitTest(const QPointF &at, const QSizeF &size) const;+ void setHover(Hit hit) { m_hover = hit; }+ Hit hover() const { return m_hover; }++private:+ double seconds() const;+ double introPercent() const;+ double finishPercent() const;+ void paintTitleBar(QPainter &p, const QSizeF &size, double chipOpacity) const;+ void paintMark(QPainter &p, const QPointF &origin, double x, double t) const;+ QRectF buttonRect(Hit which, const QSizeF &size) const;+ // The two buttons of the slow and ended states, with what each does.+ std::pair<std::pair<QString, Hit>, std::pair<QString, Hit>> buttons() const;++ QElapsedTimer m_clock;+ QString m_app;+ QIcon m_icon;+ bool m_still = false;+ Stage m_stage = Stage::Starting;+ double m_stageAt = 0;+ double m_finishAt = -1;+ bool m_arrived = false;+ bool m_ended = false;+ QString m_reason;+ int m_percent = -1;+ QString m_progress;+ Hit m_hover = Hit::None;+ QPainterPath m_w;+ QPainterPath m_spark;+ double m_length = 441;+ // The reason's height, measured once for the slow state's steady area.+ mutable QString m_measured;+ mutable double m_measuredHeight = 0;+};diff --git a/packages/wildos-rdp/src/main.cpp b/packages/wildos-rdp/src/main.cppnew file mode 100644index 0000000..50c03c1--- /dev/null+++ b/packages/wildos-rdp/src/main.cpp@@ -0,0 +1,274 @@+// wildos-rdp: Windows mode's RemoteApp client. Each Windows app window is a+// window of its own on the desktop, drawn at the screen's own scale.+//+// wildos-rdp [--app-id ID --title TITLE --icon ICON --reason TEXT --program EXE] /args-from:stdin+//+// The FreeRDP arguments are the ones xfreerdp3 takes, one per line on+// standard input with the password last, so nothing secret is ever on a+// command line. With --app-id the loading window for that app is on screen+// before they arrive: the agent starts this the moment an app is opened+// and writes them once Windows is awake.++#include "client.h"+#include "rail.h"+#include "railwindow.h"+#include "selftest.h"+#include "service.h"++#include <QElapsedTimer>+#include <QGuiApplication>+#include <QScreen>+#include <QSocketNotifier>+#include <QTimer>++#include <cmath>+#include <csignal>+#include <cstdio>+#include <cstdlib>+#include <fcntl.h>+#include <unistd.h>++namespace+{+int signalPipe[2] = {-1, -1};++void onSignal(int)+{+ const char c = 1;+ (void)!write(signalPipe[1], &c, 1);+}++struct Options {+ QString appId;+ QString title;+ QString icon;+ QString reason;+ QString program;+ bool fromStdin = false;+ // Signs in and leaves the session ready, disconnected, for the next app.+ bool prepareSession = false;+ QList<QByteArray> freerdp;+};++Options parse(int argc, char **argv)+{+ Options o;+ for (int i = 1; i < argc; ++i) {+ const QByteArray a(argv[i]);+ if ((a == "--app-id" || a == "--title" || a == "--icon" || a == "--reason" || a == "--program") && i + 1 < argc) {+ const QString value = QString::fromUtf8(argv[++i]);+ (a == "--app-id" ? o.appId : a == "--title" ? o.title : a == "--icon" ? o.icon : a == "--reason" ? o.reason : o.program) = value;+ } else if (a == "/args-from:stdin") {+ o.fromStdin = true;+ } else if (a == "--prepare-session") {+ o.prepareSession = true;+ } else {+ o.freerdp.append(a);+ }+ }+ return o;+}++// The scale Windows was asked to draw at by the caller, as a fallback for+// when no window has been on screen yet to say what the screen's is.+double askedScale(const QList<QByteArray> &args)+{+ for (const QByteArray &a : args) {+ if (a.startsWith("/scale-desktop:")) {+ bool ok = false;+ const double percent = a.mid(15).toDouble(&ok);+ if (ok && percent >= 100 && percent <= 500) {+ return percent / 100.0;+ }+ }+ }+ return 0;+}+}++int main(int argc, char **argv)+{+ QElapsedTimer clock;+ clock.start();+ // Each window carries its own app's id; this is only the fallback.+ QGuiApplication::setDesktopFileName(QStringLiteral("wildos-winmode"));+ QGuiApplication app(argc, argv);+ QGuiApplication::setQuitOnLastWindowClosed(false);++ Options options = parse(argc, argv);++ if (pipe2(signalPipe, O_CLOEXEC) == 0) {+ std::signal(SIGTERM, onSignal);+ std::signal(SIGINT, onSignal);+ }++ Client client;+ QScreen *screen = QGuiApplication::primaryScreen();+ Rail rail(&client, screen ? screen->devicePixelRatio() : 1.0);+ Service service(&rail, &client);+ if (!service.registerOnBus()) {+ qInfo("wildos-rdp: org.wildos.RemoteApp is not available on the session bus");+ }++ quint32 coldToken = 0;+ // A program Windows mode has no entry for still has a name to show; its+ // window gets the program's own app id when Windows names it.+ if (!options.appId.isEmpty() || !options.title.isEmpty()) {+ coldToken = rail.prepare(options.appId, options.title, options.icon, options.program);+ rail.setCold(coldToken);+ if (!options.reason.isEmpty()) {+ rail.update(coldToken, QString(), options.reason, -1, QString());+ }+ }+ QObject::connect(&rail, &Rail::loadingVisible, &app, [&clock](quint32 token, qint64 ms) {+ qInfo("wildos-rdp: loading window %u on screen %lld ms after it was asked for (%lld ms after start)", token, ms, qint64(clock.elapsed()));+ });++ QElapsedTimer connecting;+ bool firstFrame = false;+ QObject::connect(&rail, &Rail::windowShown, &app, [&](quint32 id, const QString &title) {+ if (!firstFrame && connecting.isValid()) {+ firstFrame = true;+ qInfo("wildos-rdp: first window (%08x \"%s\") %lld ms after connecting began", id, qPrintable(title), qint64(connecting.elapsed()));+ }+ });++ startSelfTest(&rail, &client);++ bool quitting = false;+ if (options.prepareSession) {+ client.setPrepareOnly(true);+ // Windows has started the session's shell and sent its windows: the+ // session is ready. Leaving it disconnected (not signed out) keeps it+ // so; the next connection takes it over in a moment instead of+ // signing in afresh.+ QObject::connect(&client, &Client::desktopSynced, &app, [&] {+ qInfo("wildos-rdp: session ready; disconnecting");+ QTimer::singleShot(500, &app, [&] {+ client.stop();+ QTimer::singleShot(2000, &app, [] { QCoreApplication::exit(0); });+ });+ });+ }+ QObject::connect(&client, &Client::finished, &app, [&](const QString &error, bool authFailed) {+ rail.closeAll();+ if (authFailed) {+ qWarning("wildos-rdp: Windows refused the account (%s)", qPrintable(error));+ }+ quitting = true;+ QCoreApplication::exit(error.isEmpty() ? 0 : authFailed ? 2 : 1);+ });++ auto begin = [&](const QList<QByteArray> &args) {+ QString error;+ if (!client.configure(args, &error)) {+ qWarning("wildos-rdp: %s", qPrintable(error));+ rail.closeAll();+ QCoreApplication::exit(1);+ return;+ }+ // Without --program the app is the one /app names, unless that is+ // wild-guest, which only starts the real app and ends.+ if (coldToken && options.program.isEmpty()) {+ const QString program = QString::fromUtf8(freerdp_settings_get_string(client.context()->settings, FreeRDP_RemoteApplicationProgram));+ if (!program.endsWith(QLatin1String("wild-guest.exe"), Qt::CaseInsensitive)) {+ rail.setProgram(coldToken, program);+ }+ }+ // The screen's scale as a window on it reports it, which on a+ // fractional scale is only known once one has been shown.+ double scale = 0;+ for (QWindow *w : QGuiApplication::topLevelWindows()) {+ if (w->isExposed()) {+ scale = w->devicePixelRatio();+ break;+ }+ }+ if (scale <= 0) {+ scale = askedScale(args);+ }+ if (scale <= 0) {+ scale = screen ? screen->devicePixelRatio() : 1.0;+ }+ rail.setScale(scale);+ const QSize logical = screen ? screen->geometry().size() : QSize(1920, 1080);+ client.setDisplay(QSize(int(std::lround(logical.width() * scale)), int(std::lround(logical.height() * scale))), scale);+ qInfo("wildos-rdp: connecting at scale %.2f, desktop %dx%d", scale, int(std::lround(logical.width() * scale)),+ int(std::lround(logical.height() * scale)));+ connecting.start();+ client.start();+ };++ QByteArray input;+ QSocketNotifier *reader = nullptr;+ if (options.fromStdin) {+ const int flags = fcntl(STDIN_FILENO, F_GETFL);+ fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK);+ reader = new QSocketNotifier(STDIN_FILENO, QSocketNotifier::Read, &app);+ QObject::connect(reader, &QSocketNotifier::activated, &app, [&] {+ char buffer[4096];+ for (;;) {+ const ssize_t n = read(STDIN_FILENO, buffer, sizeof buffer);+ if (n > 0) {+ input.append(buffer, n);+ continue;+ }+ if (n < 0 && (errno == EAGAIN || errno == EINTR)) {+ return;+ }+ break;+ }+ reader->setEnabled(false);+ QList<QByteArray> args = options.freerdp;+ for (const QByteArray &line : input.split('\n')) {+ const QByteArray arg = line.trimmed();+ if (!arg.isEmpty()) {+ args.append(arg);+ }+ }+ input.fill('\0');+ input.clear();+ if (args.isEmpty()) {+ // The agent gave up before Windows woke: nothing to connect to.+ rail.closeAll();+ QCoreApplication::exit(1);+ return;+ }+ begin(args);+ });+ } else {+ QTimer::singleShot(0, &app, [&] { begin(options.freerdp); });+ }++ if (signalPipe[0] >= 0) {+ auto *stopper = new QSocketNotifier(signalPipe[0], QSocketNotifier::Read, &app);+ QObject::connect(stopper, &QSocketNotifier::activated, &app, [&] {+ char c;+ (void)!read(signalPipe[0], &c, 1);+ if (quitting) {+ return;+ }+ if (client.running()) {+ // A clean goodbye to Windows, but never longer than it takes+ // to say it.+ client.stop();+ QTimer::singleShot(2000, &app, [] { QCoreApplication::exit(0); });+ } else {+ rail.closeAll();+ QCoreApplication::exit(0);+ }+ });+ }++ const int code = app.exec();+ rail.closeAll();+ if (client.running()) {+ // FreeRDP is stuck in a call that does not return (a connection to a+ // Windows that stopped answering): waiting for its thread would leave+ // this process, and its windows, behind. Nothing is left to save.+ qWarning("wildos-rdp: the connection did not end in time; leaving without it");+ fflush(stderr);+ std::_Exit(code);+ }+ return code;+}diff --git a/packages/wildos-rdp/src/rail.cpp b/packages/wildos-rdp/src/rail.cppnew file mode 100644index 0000000..de85af8--- /dev/null+++ b/packages/wildos-rdp/src/rail.cpp@@ -0,0 +1,1385 @@+#include "rail.h"+#include "railwindow.h"++#include <QDBusConnection>+#include <QDBusMessage>+#include <QDateTime>+#include <QDBusPendingCallWatcher>+#include <QDBusPendingReply>+#include <QGuiApplication>+#include <QIcon>+#include <QScreen>+#include <QSettings>+#include <QStandardPaths>++#include <freerdp/rail.h>+#include <freerdp/window.h>++#include <cmath>++namespace+{+constexpr quint32 stateHidden = 0x00;+constexpr quint32 stateMinimized = 0x02;+constexpr quint32 stateMaximized = 0x03;+// How long a loading window waits for its app before giving up. Board 9.13+// takes over after 20 s with a way out; this only catches a launch the agent+// forgot.+constexpr int loadingTimeoutMs = 10 * 60 * 1000;+// How long a new window waits for the agent to say which app it is,+// so it is shown once, in the right taskbar group.+constexpr int appIdWaitMs = 400;+// How long a new window waits for Windows to say which program it belongs+// to before a loading window is matched to it by name alone.+constexpr int processWaitMs = 1000;+// How long another window of the program a loading window waits for may+// be on screen before the loading window gives way to it.+constexpr int stepAsideMs = 1500;+// How long after a launch is cancelled its app's window is still closed+// as it comes: Windows may have been waking when it was.+constexpr int cancelledForMs = 120 * 1000;+// How long after Windows first sends windows the client waits to hear that+// its desktop sync is over.+constexpr int syncWaitMs = 4000;+// After our close: when to say a window with unsaved changes has not+// closed, and when a stuck one with nothing unsaved is ended; how long a+// dropped connection may try to come back before its windows leave the+// screen.+constexpr int closeQuietMs = 5000;+// The close's grace period: a window Windows has neither closed nor drawn+// in again after this leaves the screen (and the taskbar) while Windows is+// still dealing with it. One Windows draws in again stays up a little+// longer, to see whether it closes or is asking something (Windows 11's+// Paint asks inside its own window after about 0.6 s). Either way a normal+// close is over before the first deadline, and a question never flickers.+// From the timings measured with WILDOS_RDP_CLOSE_TIMING (see the log).+constexpr int closeGraceMs = 500;+// Programs with nothing to lose: they never ask before closing, so their+// windows leave the screen the moment they are closed. Explorer redraws a+// folder window as it closes and can take seconds to end it, which would+// otherwise read as a question and keep the window up meanwhile.+const QSet<QString> neverAsk = {+ QStringLiteral("explorer.exe"), QStringLiteral("charmap.exe"), QStringLiteral("calculatorapp.exe"),+ QStringLiteral("calc.exe"), QStringLiteral("systemsettings.exe"), QStringLiteral("taskmgr.exe"),+ QStringLiteral("control.exe"), QStringLiteral("regedit.exe"), QStringLiteral("magnify.exe"),+ QStringLiteral("osk.exe"), QStringLiteral("snippingtool.exe"),+};+constexpr int closeAskingMs = 1200;+constexpr int closeEndMs = 10000;+constexpr int lostHideMs = 2000;+// A Windows window nothing is known about. It must match no desktop entry:+// "wildos-winmode" would give it Windows mode's own icon, the W, where the+// icon Windows sends for the window belongs.+const QString genericAppId = QStringLiteral("windows-app");++// A program's file name in lower case, from a full Windows path or not.+QString exeOf(const QString &path)+{+ return path.section(u'\\', -1).section(u'/', -1).toLower();+}++// Menus, tooltips and other windows that belong to another and never take+// the keyboard, told apart from apps and dialogs by their styles.+bool isPopup(quint32 style, quint32 exStyle)+{+ const bool captioned = (style & WS_CAPTION) == WS_CAPTION;+ const bool appLike = captioned || (style & (WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX)) || (exStyle & WS_EX_APPWINDOW);+ const bool toolOrPopup = (exStyle & (WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW)) || (style & WS_POPUP);+ const bool noActivate = (exStyle & WS_EX_NOACTIVATE) && !(exStyle & WS_EX_APPWINDOW);+ return noActivate || (toolOrPopup && !appLike);+}++QString settingsPath()+{+ return QStandardPaths::writableLocation(QStandardPaths::GenericStateLocation) + QStringLiteral("/wildos/windows-mode-windows.ini");+}++QSize rememberedSize(const QString &appId)+{+ QSettings s(settingsPath(), QSettings::IniFormat);+ const QSize size = s.value(appId + QStringLiteral("/size")).toSize();+ if (size.isValid() && size.width() >= 200 && size.height() >= 150) {+ return size;+ }+ const QScreen *screen = QGuiApplication::primaryScreen();+ const QSize avail = screen ? screen->availableGeometry().size() : QSize(1280, 800);+ return QSize(std::min(1100, avail.width() * 7 / 10), std::min(720, avail.height() * 7 / 10));+}++void rememberSize(const QString &appId, const QSize &size)+{+ if (appId.isEmpty() || appId == genericAppId || !size.isValid()) {+ return;+ }+ QSettings s(settingsPath(), QSettings::IniFormat);+ s.setValue(appId + QStringLiteral("/size"), size);+}++// Shows a window with the app id it belongs to; Qt reads the id from the+// application when the window is shown.+void showAs(RailWindow *window, quint32 state)+{+ const QString saved = QGuiApplication::desktopFileName();+ QGuiApplication::setDesktopFileName(window->appId());+ if (state == stateMaximized) {+ window->showMaximized();+ } else if (state == stateMinimized) {+ window->showMinimized();+ } else {+ window->show();+ }+ QGuiApplication::setDesktopFileName(saved);+}+}++Rail::Rail(Client *client, double scale, QObject *parent)+ : QObject(parent)+ , m_client(client)+ , m_scale(scale)+ , m_cursor(Qt::ArrowCursor)+{+ connect(client, &Client::windowChanged, this, &Rail::order);+ connect(client, &Client::desktopSynced, this, &Rail::desktopSynced);+ connect(client, &Client::windowDeleted, this, &Rail::deleted);+ connect(client, &Client::windowIcon, this, &Rail::icon);+ connect(client, &Client::desktopChanged, this, &Rail::desktop);+ connect(client, &Client::surfaceDamaged, this, &Rail::surface);+ connect(client, &Client::primaryDamaged, this, &Rail::primary);+ connect(client, &Client::localMoveSize, this, &Rail::moveSize);+ connect(client, &Client::minMaxInfo, this, &Rail::minMax);+ connect(client, &Client::windowCloaked, this, &Rail::cloak);+ connect(client, &Client::windowProcess, this, &Rail::process);+ connect(client, &Client::connectionLost, this, &Rail::connectionLost);+ connect(client, &Client::connectionBack, this, &Rail::connectionBack);+ QDBusConnection::sessionBus().connect(QStringLiteral("org.freedesktop.Notifications"), QStringLiteral("/org/freedesktop/Notifications"),+ QStringLiteral("org.freedesktop.Notifications"), QStringLiteral("ActionInvoked"), this,+ SLOT(notificationAction(uint, QString)));+ connect(client, &Client::pointerImage, this, [this](const QImage &image, const QPoint &hotspot) {+ QPixmap pixmap = QPixmap::fromImage(image);+ pixmap.setDevicePixelRatio(m_scale);+ setCursorAll(QCursor(pixmap, int(std::lround(hotspot.x() / m_scale)), int(std::lround(hotspot.y() / m_scale))));+ });+ connect(client, &Client::pointerHidden, this, [this] { setCursorAll(QCursor(Qt::BlankCursor)); });+ connect(client, &Client::pointerDefault, this, [this] { setCursorAll(QCursor(Qt::ArrowCursor)); });+}++Rail::~Rail()+{+ closeAll();+}++void Rail::setCursorAll(const QCursor &cursor)+{+ m_cursor = cursor;+ for (RailWindow *w : std::as_const(m_windows)) {+ w->setCursor(cursor);+ }+}++quint32 Rail::prepare(const QString &appId, const QString &title, const QString &icon, const QString &program, int delayMs)+{+ const quint32 token = m_nextToken++;+ auto *window = new RailWindow(this, m_client, appId.isEmpty() ? genericAppId : appId);+ window->setProperty("token", token);+ const QIcon themed = icon.startsWith(u'/') ? QIcon(icon) : QIcon::fromTheme(icon);+ if (!themed.isNull()) {+ window->QWindow::setIcon(themed);+ }+ window->startLoading(title, themed, rememberedSize(appId));+ window->setLoadingReason(QStringLiteral("Windows mode is taking longer than usual to start. %1 will open as soon as it's ready.").arg(title), -1, {});+ Placeholder p;+ p.window = window;+ p.title = title;+ p.program = exeOf(program);+ p.appId = window->appId();+ p.icon = themed;+ if (!p.program.isEmpty() && p.appId != genericAppId) {+ // Every window this program opens belongs to the app, whether the+ // loading window takes it or not.+ m_programApps.insert(p.program, p.appId);+ m_programIcons.insert(p.program, themed);+ }+ p.age.start();+ p.timeout = new QTimer(this);+ p.timeout->setSingleShot(true);+ connect(p.timeout, &QTimer::timeout, this, [this, token] { loadingTimedOut(token); });+ p.timeout->start(loadingTimeoutMs);+ m_placeholders.insert(token, p);+ if (delayMs <= 0) {+ showAs(window, 0x05);+ } else {+ // Board 9.12: an app that opens this quickly opens without the+ // loader at all.+ QPointer<RailWindow> guard(window);+ QTimer::singleShot(delayMs, this, [guard] {+ if (guard && guard->loading() && !guard->isVisible()) {+ showAs(guard, 0x05);+ }+ });+ }+ return token;+}++void Rail::setCold(quint32 token)+{+ if (auto it = m_placeholders.find(token); it != m_placeholders.end()) {+ it->cold = true;+ }+}++void Rail::setProgram(quint32 token, const QString &program)+{+ auto it = m_placeholders.find(token);+ if (it == m_placeholders.end() || program.isEmpty()) {+ return;+ }+ it->program = exeOf(program);+ if (it->appId != genericAppId) {+ m_programApps.insert(it->program, it->appId);+ m_programIcons.insert(it->program, it->icon);+ }+}++bool Rail::update(quint32 token, const QString &stage, const QString &reason, int percent, const QString &progress)+{+ if (token == 0) {+ // The connection's own loading window, which its caller has no+ // token for (it was made from the command line).+ for (auto p = m_placeholders.cbegin(); p != m_placeholders.cend(); ++p) {+ if (p->cold) {+ token = p.key();+ }+ }+ }+ const auto it = m_placeholders.constFind(token);+ RailWindow *w = it != m_placeholders.cend() ? it->window.data() : m_loadingByToken.value(token).data();+ if (!w || !w->loading()) {+ return false;+ }+ if (stage == QLatin1String("almost")) {+ w->setLoadingStage(LoadingView::Stage::AlmostReady);+ } else if (stage == QLatin1String("ended")) {+ qInfo("wildos-rdp: loading window %u: the app ended before it opened", token);+ w->setLoadingEnded();+ return true;+ }+ if (!reason.isEmpty()) {+ w->setLoadingReason(reason, percent, progress);+ }+ return true;+}++void Rail::loadingShown(quint32 token)+{+ auto it = m_placeholders.find(token);+ if (it != m_placeholders.end() && it->age.isValid()) {+ Q_EMIT loadingVisible(token, it->age.elapsed());+ it->age.invalidate();+ }+}++bool Rail::cancel(quint32 token, const QString &reason)+{+ auto it = m_placeholders.find(token);+ if (it == m_placeholders.end()) {+ return false;+ }+ Placeholder p = *it;+ m_placeholders.erase(it);+ delete p.timeout;+ if (p.window) {+ p.window->hide();+ p.window->deleteLater();+ }+ if (reason == QLatin1String("cancelled") && !p.program.isEmpty()) {+ // Windows may well start the app anyway; its window is closed as it+ // comes rather than appear after the person said no.+ m_cancelled[p.program].append(QDateTime::currentMSecsSinceEpoch() + cancelledForMs);+ }+ Q_EMIT loadingFinished(token, reason, 0);+ return true;+}++bool Rail::takeCancelled(const QString &program)+{+ auto it = m_cancelled.find(program);+ if (program.isEmpty() || it == m_cancelled.end()) {+ return false;+ }+ const qint64 now = QDateTime::currentMSecsSinceEpoch();+ it->removeIf([now](qint64 until) { return until < now; });+ const bool taken = !it->isEmpty();+ if (taken) {+ it->removeFirst();+ }+ if (it->isEmpty()) {+ m_cancelled.erase(it);+ }+ return taken;+}++void Rail::loadingTimedOut(quint32 token)+{+ cancel(token, QStringLiteral("timeout"));+}++void Rail::closeAll()+{+ const QList<quint32> tokens = m_placeholders.keys();+ for (quint32 token : tokens) {+ cancel(token, QStringLiteral("ended"));+ }+ const QList<quint32> ids = m_windows.keys();+ for (quint32 id : ids) {+ deleted(id);+ }+ m_pending.clear();+}++RailWindow *Rail::takePlaceholder(quint32 id, const QString &title, bool early)+{+ if (m_placeholders.isEmpty()) {+ return nullptr;+ }+ // The loading window for the program the new window belongs to, when+ // Windows has said which that is; a window of another program is never+ // taken for it. Otherwise the one whose app the title names, or the one+ // waiting longest.+ QList<quint32> tokens = m_placeholders.keys();+ std::sort(tokens.begin(), tokens.end());+ if (early) {+ tokens.removeIf([this](quint32 token) { return m_placeholders.value(token).cold; });+ }+ const QString exe = m_processes.value(id);+ quint32 best = 0;+ if (!exe.isEmpty()) {+ for (quint32 token : tokens) {+ if (m_placeholders.value(token).program == exe) {+ best = token;+ break;+ }+ }+ }+ if (!best) {+ // Another program can own the app's window (a packaged app's frame+ // host, a launcher that starts the real program); a title naming+ // the app is enough then.+ for (quint32 token : tokens) {+ const QString t = m_placeholders.value(token).title;+ if (!t.isEmpty() && title.contains(t, Qt::CaseInsensitive)) {+ best = token;+ break;+ }+ }+ }+ if (!best) {+ // Otherwise only loading windows that do not know their program may+ // still be this window's. One that does is never given a window+ // whose program Windows has not named: on reconnecting, a window+ // another app left open would take it.+ tokens.removeIf([this](quint32 token) { return !m_placeholders.value(token).program.isEmpty(); });+ }+ if (!best && !tokens.isEmpty()) {+ best = tokens.first();+ }+ if (!best) {+ return nullptr;+ }+ Placeholder p = m_placeholders.take(best);+ delete p.timeout;+ p.timeout = nullptr;+ if (!p.window) {+ return nullptr;+ }+ m_adopted.insert(best, p);+ return p.window;+}++QString Rail::appIdFor(quint32 id) const+{+ if (const QString app = m_apps.value(id); !app.isEmpty()) {+ return app;+ }+ const auto it = m_pending.constFind(id);+ if (it != m_pending.cend() && it->state.owner) {+ if (RailWindow *owner = m_windows.value(it->state.owner)) {+ return owner->appId();+ }+ }+ const QString exe = m_processes.value(id);+ if (const QString app = m_programApps.value(exe); !app.isEmpty()) {+ return app;+ }+ // A program nothing is known about still groups its own windows.+ if (!exe.isEmpty()) {+ return QStringLiteral("windows-") + exe.section(u'.', 0, 0);+ }+ return genericAppId;+}++bool Rail::ownedByShownWindow(const RailOrder &s) const+{+ RailWindow *owner = m_windows.value(s.owner);+ return owner && owner->isVisible();+}++RailWindow *Rail::parentFor(quint32 id) const+{+ const RailOrder &s = m_pending.value(id).state;+ if (RailWindow *owner = m_windows.value(s.owner); owner && !owner->isPopup()) {+ return owner;+ }+ // A menu often names no owner: it belongs to the window it opens over,+ // the topmost one first.+ const QPoint origin(s.offset);+ for (quint32 z : m_zOrder) {+ RailWindow *w = m_windows.value(z);+ if (w && !w->isPopup() && w->isVisible() && w->frame().contains(origin)) {+ return w;+ }+ }+ for (RailWindow *w : m_windows) {+ if (!w->isPopup() && w->isVisible() && w->frame().contains(origin)) {+ return w;+ }+ }+ if (RailWindow *active = m_windows.value(m_active); active && !active->isPopup() && active->isVisible()) {+ return active;+ }+ for (RailWindow *w : m_windows) {+ if (!w->isPopup() && w->isVisible()) {+ return w;+ }+ }+ return nullptr;+}++void Rail::desktopSynced()+{+ // Only the first sync counts: after a reconnection the windows Windows+ // sends again are known already, and a new one can be the window of an+ // app opened while the connection was down.+ m_synced = true;+}++void Rail::order(const RailOrder &o)+{+ if (!m_synced && !m_syncWaiting) {+ // A Windows that never says its sync is over is not waited for long.+ m_syncWaiting = true;+ QTimer::singleShot(syncWaitMs, this, &Rail::desktopSynced);+ }+ Pending &p = m_pending[o.id];+ RailOrder &s = p.state;+ if (o.created && !m_synced && !m_windows.contains(o.id)) {+ m_preexisting.insert(o.id);+ }+ if (o.created) {+ s = RailOrder();+ s.id = o.id;+ s.showState = 0x05;+ }+ const quint32 f = o.fields;+ if (f & WINDOW_ORDER_FIELD_OWNER) {+ s.owner = o.owner;+ }+ if (f & WINDOW_ORDER_FIELD_STYLE) {+ s.style = o.style;+ s.exStyle = o.exStyle;+ }+ if (f & WINDOW_ORDER_FIELD_SHOW) {+ s.showState = o.showState;+ }+ if (f & WINDOW_ORDER_FIELD_TITLE) {+ s.title = o.title;+ }+ if (f & WINDOW_ORDER_FIELD_WND_OFFSET) {+ s.offset = o.offset;+ }+ if (f & WINDOW_ORDER_FIELD_WND_SIZE) {+ s.size = o.size;+ }+ if (f & (WINDOW_ORDER_FIELD_RESIZE_MARGIN_X | WINDOW_ORDER_FIELD_RESIZE_MARGIN_Y)) {+ s.resizeMargins = o.resizeMargins;+ }+ if (f & WINDOW_ORDER_FIELD_VISIBILITY) {+ s.visibility = o.visibility;+ }+ s.fields |= f;++ if (qEnvironmentVariableIsSet("WILDOS_RDP_DEBUG")) {+ qInfo("window %08x%s fields=%08x style=%08x ex=%08x owner=%08x show=%u rect=%d,%d %dx%d title=%s", o.id, o.created ? " new" : "", f,+ s.style, s.exStyle, s.owner, s.showState, s.offset.x(), s.offset.y(), s.size.width(), s.size.height(), qPrintable(s.title));+ }++ RailWindow *w = m_windows.value(o.id);+ const bool visible = s.showState != stateHidden && s.size.width() > 0 && s.size.height() > 0;+ if (o.created) {+ log(o.id, QStringLiteral("created \"%1\" show %2").arg(s.title).arg(s.showState));+ }+ if (!w) {+ if (visible) {+ realize(o.id);+ }+ return;+ }+ if (f & WINDOW_ORDER_FIELD_TITLE) {+ w->setRemoteTitle(s.title);+ }+ if (f & (WINDOW_ORDER_FIELD_WND_OFFSET | WINDOW_ORDER_FIELD_WND_SIZE)) {+ w->setFrame(QRect(s.offset, s.size));+ if (w->isPopup()) {+ if (RailWindow *parent = qobject_cast<RailWindow *>(w->transientParent())) {+ const QPoint delta = s.offset - parent->frame().topLeft();+ w->setPosition(parent->position() + QPoint(int(std::lround(delta.x() / m_scale)), int(std::lround(delta.y() / m_scale))));+ }+ }+ }+ if ((f & WINDOW_ORDER_FIELD_STYLE) && (s.style & WS_DISABLED)) {+ if (auto it = m_closing.find(o.id); it != m_closing.end() && !it->disabled) {+ // Disabled by Windows after the close: a modal question is up.+ it->disabled = true;+ log(o.id, QStringLiteral("disabled %1 ms after its close: asking").arg(it->since.elapsed()));+ if (it->hidden && !it->unwanted) {+ reopen(o.id);+ }+ }+ }+ if ((f & WINDOW_ORDER_FIELD_SHOW) && m_closing.contains(o.id)) {+ // Closed here already: it stays off screen whatever Windows says+ // about it, until it goes or the close turns out not to happen.+ w->setShowState(s.showState);+ return;+ }+ if ((f & WINDOW_ORDER_FIELD_SHOW) && w->loading()) {+ // The window a loading window took is being hidden or minimised+ // before the app ever showed in it: not the app's window after all.+ if (s.showState == stateHidden || s.showState == stateMinimized) {+ giveBack(w);+ return;+ }+ w->setShowState(s.showState);+ return;+ }+ if (f & WINDOW_ORDER_FIELD_SHOW) {+ const quint32 before = w->remoteMinimized() ? stateMinimized : 0;+ w->setShowState(s.showState);+ if (s.showState == stateHidden) {+ w->hide();+ } else if (s.showState == stateMinimized) {+ if (!w->isPopup()) {+ w->showMinimized();+ }+ } else if (s.showState == stateMaximized) {+ if (!w->isPopup() && !(w->windowStates() & Qt::WindowMaximized)) {+ w->showMaximized();+ }+ } else {+ if (!w->isVisible()) {+ showAs(w, s.showState);+ } else if (!w->isPopup() && (w->windowStates() & Qt::WindowMaximized)) {+ w->showNormal();+ w->resize(w->logicalSize(s.size));+ } else if (before == stateMinimized) {+ w->requestActivate();+ }+ }+ }+}++void Rail::realize(quint32 id)+{+ Pending &p = m_pending[id];+ const RailOrder &s = p.state;+ if (m_cloaked.contains(id) || m_deciding.contains(id)) {+ return;+ }+ const bool popup = isPopup(s.style, s.exStyle);+ const QRect rect(s.offset, s.size);+ // Windows 11 draws a window's drop shadow as see-through windows round+ // it; the compositor draws shadows here. A see-through window over an+ // app window is content (a XAML island, an overlay) and is shown.+ if ((s.exStyle & WS_EX_LAYERED) && popup && !overlapsAppWindow(rect)) {+ log(id, QStringLiteral("not shown: see-through, beside an app window rather than over one"));+ return;+ }+ RailWindow *parent = nullptr;+ if (popup) {+ parent = parentFor(id);+ if (!parent) {+ log(id, QStringLiteral("waiting: a popup with no window to belong to yet"));+ return;+ }+ }+ // An app's main window is often owned by a hidden window of its own;+ // it is still the app's window, not a dialog of another.+ const bool topLevel = !popup && !ownedByShownWindow(s);+ const bool appSized = s.size.width() >= 160 && s.size.height() >= 100;+ const bool shown = s.showState == 0x05 || s.showState == stateMaximized;+ // A dialog a closing window opens (Save changes?) is its question: the+ // window stays for it. Popups of a window already hidden belong to+ // nothing on screen.+ quint32 closingOwner = 0;+ if (m_closing.contains(s.owner)) {+ if (popup && m_closing.value(s.owner).hidden) {+ return;+ }+ if (!popup) {+ closingOwner = s.owner;+ m_closing[s.owner].dialogs.insert(id);+ log(id, QStringLiteral("opened by a window that is closing; shown for an answer"));+ if (m_closing.value(s.owner).hidden) {+ reopen(s.owner);+ }+ }+ }+ RailWindow *w = nullptr;+ bool adopted = false;+ const bool early = m_preexisting.contains(id);+ if (topLevel && appSized && shown && !closingOwner && (!m_placeholders.isEmpty() || !m_cancelled.isEmpty())) {+ if (!m_processes.contains(id) && !m_askedProcess.contains(id)) {+ // Which program this is decides which loading window it takes;+ // Windows answers within a few milliseconds.+ m_askedProcess.insert(id);+ m_deciding.insert(id);+ m_client->requestProcess(id);+ QTimer::singleShot(processWaitMs, this, [this, id] {+ if (m_deciding.remove(id)) {+ log(id, QStringLiteral("no answer about its program; matched by name"));+ if (m_pending.contains(id) && !m_windows.contains(id)) {+ realize(id);+ }+ }+ });+ return;+ }+ w = takePlaceholder(id, s.title, early);+ if (w && !w->isVisible()) {+ // The app opened before its loading window was due (board 9.12):+ // it opens on its own, with the loading window's app id.+ const quint32 token = w->property("token").toUInt();+ QString app = w->appId();+ if (app == genericAppId && m_processes.contains(id)) {+ // A loading window that did not know its app: the program's.+ app = QStringLiteral("windows-") + m_processes.value(id).section(u'.', 0, 0);+ }+ m_adopted.remove(token);+ w->deleteLater();+ w = nullptr;+ m_apps.insert(id, app);+ Q_EMIT loadingFinished(token, QStringLiteral("window"), id);+ }+ if (w) {+ adopted = true;+ w->adopt(id);+ if (w->appId() == genericAppId && m_processes.contains(id)) {+ // The loading window did not know its app (a program Windows+ // mode has no entry for); Windows has just named the program,+ // which groups its windows and is never the generic W.+ w->setAppId(QStringLiteral("windows-") + m_processes.value(id).section(u'.', 0, 0));+ }+ if (!m_apps.contains(id)) {+ m_apps.insert(id, w->appId());+ }+ log(id, QStringLiteral("takes over loading window %1 (%2)").arg(w->property("token").toUInt()).arg(w->appId()));+ Q_EMIT loadingFinished(w->property("token").toUInt(), QStringLiteral("window"), id);+ }+ }+ if (!w) {+ w = new RailWindow(this, m_client, appIdFor(id));+ if (!m_processes.contains(id) && !m_askedProcess.contains(id) && !popup) {+ m_askedProcess.insert(id);+ m_client->requestProcess(id);+ }+ const QIcon known = m_programIcons.value(m_processes.value(id));+ if (!known.isNull()) {+ w->QWindow::setIcon(known);+ }+ }+ w->setRemoteState(id, s.style, s.exStyle, popup);+ w->setOwner(s.owner);+ w->setShowState(s.showState);+ w->setFrame(rect);+ w->setRemoteTitle(s.title);+ if (!p.icon.isNull()) {+ w->setIcon(p.icon, p.iconBig);+ }+ m_windows.insert(id, w);+ if (const auto known = m_surfaces.constFind(id); known != m_surfaces.cend()) {+ w->surfaceDamaged(known->first, QRect(QPoint(0, 0), known->second), known->second);+ }+ Q_EMIT windowShown(id, s.title);+ if (adopted) {+ m_loadingByToken.insert(w->property("token").toUInt(), w);+ if (!(s.style & WS_THICKFRAME) && !(s.style & WS_MAXIMIZE)) {+ // Its own size, next time, from the start.+ rememberSize(w->appId(), w->logicalSize(s.size));+ }+ w->beginHandoff();+ return;+ }+ if (!popup) {+ stepAsideFor(id);+ }+ if (topLevel && appSized && shown && !closingOwner && takeCancelled(m_processes.value(id))) {+ log(id, QStringLiteral("belongs to a launch cancelled on its loading window; closed without being shown"));+ Closing c;+ c.since.start();+ c.title = s.title;+ c.pid = m_pids.value(id);+ c.hidden = true;+ c.unwanted = true;+ m_closing.insert(id, c);+ m_client->sysCommand(id, SC_CLOSE);+ QTimer::singleShot(closeEndMs, this, [this, id] { closeUnanswered(id, true); });+ return;+ }+ log(id, QStringLiteral("shown as %1 (%2)").arg(popup ? QStringLiteral("a popup") : QStringLiteral("a window"), w->appId()));+ if (popup) {+ w->setTransientParent(parent);+ const QPoint delta = s.offset - parent->frame().topLeft();+ w->setGeometry(QRect(parent->position() + QPoint(int(std::lround(delta.x() / m_scale)), int(std::lround(delta.y() / m_scale))),+ w->logicalSize(s.size)));+ showAs(w, s.showState);+ return;+ }+ if (RailWindow *owner = m_windows.value(s.owner); owner && owner->isVisible()) {+ w->setTransientParent(owner);+ }+ w->resize(w->logicalSize(s.size));+ if (m_apps.contains(id) || ownedByShownWindow(s) || m_programApps.contains(m_processes.value(id))) {+ showAs(w, s.showState);+ return;+ }+ // The agent says which app this is in a moment; showing it once with+ // that app's id puts it straight into the right taskbar group.+ QPointer<RailWindow> guard(w);+ QTimer::singleShot(appIdWaitMs, this, [this, guard, id] {+ if (guard && !guard->isVisible() && m_windows.value(id) == guard) {+ const RailOrder &state = m_pending.value(id).state;+ if (state.showState != stateHidden && !m_cloaked.contains(id)) {+ showAs(guard, state.showState);+ }+ }+ });+}++void Rail::stepAsideFor(quint32 id)+{+ // A window of the program a loading window waits for is on screen but+ // was not the one it took (a first-run question, a small dialog before+ // the main window). The app is up: if the loading window has not taken+ // one by the time this has been showing a moment, it goes, so it never+ // sits there saying the app is still opening.+ const QString exe = m_processes.value(id);+ if (exe.isEmpty()) {+ return;+ }+ QTimer::singleShot(stepAsideMs, this, [this, id, exe] {+ RailWindow *w = m_windows.value(id);+ if (!w || !w->isVisible() || m_closing.contains(id)) {+ return;+ }+ const QList<quint32> tokens = m_placeholders.keys();+ for (quint32 token : tokens) {+ if (m_placeholders.value(token).program == exe && !(m_placeholders.value(token).cold && m_preexisting.contains(id))) {+ log(id, QStringLiteral("is on screen and loading window %1 took nothing; it goes").arg(token));+ cancel(token, QStringLiteral("window"));+ }+ }+ });+}++bool Rail::overlapsAppWindow(const QRect &rect) const+{+ for (RailWindow *w : m_windows) {+ if (!w->isPopup() && w->isVisible() && w->frame().intersects(rect)) {+ return true;+ }+ }+ return false;+}++void Rail::log(quint32 id, const QString &what) const+{+ // One line for each decision about a window, always: what a test on real+ // hardware needs to tell why a window looks the way it does.+ const RailOrder s = m_pending.value(id).state;+ qInfo("wildos-rdp: window %08x [%s, style %08x ex %08x owner %08x %dx%d] %s", id, qPrintable(m_processes.value(id, QStringLiteral("?"))),+ s.style, s.exStyle, s.owner, s.size.width(), s.size.height(), qPrintable(what));+}++void Rail::process(quint32 id, const QString &image, const QString &appUserModel, quint32 pid)+{+ const QString exe = exeOf(image);+ m_processes.insert(id, exe);+ m_pids.insert(id, pid);+ if (auto it = m_closing.find(id); it != m_closing.end()) {+ it->pid = pid;+ }+ qInfo("wildos-rdp: window %08x belongs to %s (process %u%s%s)", id, qPrintable(image), pid, appUserModel.isEmpty() ? "" : ", ",+ qPrintable(appUserModel));+ if (m_deciding.remove(id)) {+ if (m_pending.contains(id) && !m_windows.contains(id)) {+ realize(id);+ }+ return;+ }+ // A window shown before its program was known joins that program's app,+ // unless the agent has already said which app it is.+ RailWindow *w = m_windows.value(id);+ if (!w || w->loading() || m_agentApps.contains(id)) {+ return;+ }+ const QString app = m_programApps.value(exe);+ if (!app.isEmpty() && w->appId() != app) {+ m_apps.insert(id, app);+ w->setAppId(app);+ const QIcon icon = m_programIcons.value(exe);+ if (!icon.isNull() && w->icon().isNull()) {+ w->QWindow::setIcon(icon);+ }+ } else if (app.isEmpty() && w->appId() == genericAppId && !exe.isEmpty()) {+ // Its program's own id, even if the generic one was recorded for it+ // while the program was unknown.+ const QString own = QStringLiteral("windows-") + exe.section(u'.', 0, 0);+ m_apps.insert(id, own);+ w->setAppId(own);+ }+ if (!w->isPopup() && w->isVisible()) {+ // Named too late to take the loading window: it gives way instead.+ stepAsideFor(id);+ }+}++void Rail::cloak(quint32 id, bool cloaked)+{+ log(id, cloaked ? QStringLiteral("cloaked") : QStringLiteral("uncloaked"));+ if (cloaked) {+ m_cloaked.insert(id);+ if (RailWindow *w = m_windows.value(id)) {+ if (w->loading()) {+ giveBack(w);+ } else {+ w->hide();+ }+ }+ return;+ }+ m_cloaked.remove(id);+ const RailOrder s = m_pending.value(id).state;+ const bool visible = s.showState != stateHidden && s.size.width() > 0 && s.size.height() > 0;+ if (!visible || m_closing.contains(id)) {+ return;+ }+ if (RailWindow *w = m_windows.value(id)) {+ if (!w->isVisible()) {+ showAs(w, s.showState);+ }+ } else if (m_pending.contains(id)) {+ realize(id);+ }+}++void Rail::giveBack(RailWindow *w)+{+ // The window a loading window took went away or was hidden before the+ // app showed in it: the loading window waits again, so it is never left+ // on the taskbar with nothing of the app in it.+ const quint32 token = w->property("token").toUInt();+ const quint32 id = w->remoteId();+ log(id, QStringLiteral("hidden before its first picture; loading window %1 waits again").arg(token));+ m_windows.remove(id);+ m_loadingByToken.remove(token);+ Placeholder p = m_adopted.take(token);+ p.window = w;+ p.timeout = new QTimer(this);+ p.timeout->setSingleShot(true);+ connect(p.timeout, &QTimer::timeout, this, [this, token] { loadingTimedOut(token); });+ p.timeout->start(loadingTimeoutMs);+ m_placeholders.insert(token, p);+ w->unadopt();+ if (w->windowStates() & Qt::WindowMinimized) {+ w->showNormal();+ }+}++void Rail::noticeActivation(quint32 active)+{+ // An app that is already open often only brings its window forward+ // when it is opened again (a second Explorer, a document app showing+ // its one window): no new window comes, and the loading window would+ // wait for ever. When Windows makes an existing window of the program+ // active and nothing new has come a moment later, the loading window+ // closes and that window comes forward.+ const QString exe = m_processes.value(active);+ RailWindow *existing = m_windows.value(active);+ if (exe.isEmpty() || !existing || existing->loading()) {+ return;+ }+ for (auto it = m_placeholders.cbegin(); it != m_placeholders.cend(); ++it) {+ if (it->program != exe) {+ continue;+ }+ const quint32 token = it.key();+ QTimer::singleShot(1500, this, [this, token, active] {+ if (!m_placeholders.contains(token) || m_active != active) {+ return;+ }+ log(active, QStringLiteral("already open and brought forward; loading window %1 closes").arg(token));+ cancel(token, QStringLiteral("window"));+ if (RailWindow *w = m_windows.value(active)) {+ w->requestActivate();+ }+ });+ }+}++void Rail::windowDrawn(RailWindow *w)+{+ // An app window of a program is on screen while a loading window for the+ // same program still waits: the app went another way (a second process,+ // a window handed over), so the loading window goes rather than stay on+ // the taskbar with nothing in it, and the app window takes its app id.+ const QString exe = m_processes.value(w->remoteId());+ if (exe.isEmpty() || w->loading()) {+ return;+ }+ const RailOrder s = m_pending.value(w->remoteId()).state;+ if (w->isPopup() || ownedByShownWindow(s) || s.size.width() < 160 || s.size.height() < 100) {+ return;+ }+ const QList<quint32> tokens = m_placeholders.keys();+ for (quint32 token : tokens) {+ const Placeholder p = m_placeholders.value(token);+ if (p.program != exe || (p.cold && m_preexisting.contains(w->remoteId()))) {+ continue;+ }+ log(w->remoteId(), QStringLiteral("its app is on screen; loading window %1 closes").arg(token));+ if (!m_agentApps.contains(w->remoteId())) {+ m_apps.insert(w->remoteId(), p.appId);+ w->setAppId(p.appId);+ if (!p.icon.isNull() && w->icon().isNull()) {+ w->QWindow::setIcon(p.icon);+ }+ }+ cancel(token, QStringLiteral("window"));+ }+}++void Rail::setWindowApp(quint32 id, const QString &appId)+{+ if (appId.isEmpty()) {+ return;+ }+ m_apps.insert(id, appId);+ m_agentApps.insert(id);+ RailWindow *w = m_windows.value(id);+ if (!w) {+ return;+ }+ if (!w->isVisible()) {+ w->setProperty("appIdPending", false);+ const QString saved = w->appId();+ if (saved != appId) {+ // Not on screen yet: the id is simply taken before showing.+ w->setAppId(appId);+ }+ const RailOrder &state = m_pending.value(id).state;+ if (state.showState != stateHidden) {+ showAs(w, state.showState);+ }+ return;+ }+ w->setAppId(appId);+}++void Rail::deleted(quint32 id)+{+ if (RailWindow *w = m_windows.value(id); w && w->loading()) {+ if (m_closing.contains(id)) {+ // Closed by the person while it was still handing over: that+ // launch is over, its loading window does not wait again.+ const quint32 token = w->property("token").toUInt();+ m_loadingByToken.remove(token);+ m_adopted.remove(token);+ } else {+ giveBack(w);+ }+ }+ if (const auto c = m_closing.constFind(id); c != m_closing.cend()) {+ log(id, QStringLiteral("deleted %1 ms after its close").arg(c->since.elapsed()));+ } else {+ log(id, QStringLiteral("deleted"));+ }+ m_closing.remove(id);+ m_pids.remove(id);+ m_hiddenByLoss.remove(id);+ for (auto it = m_closing.begin(); it != m_closing.end(); ++it) {+ if (it->dialogs.remove(id)) {+ // The dialog was answered. If its window is still there a moment+ // later, the answer was not to close (Cancel): it comes back.+ const quint32 parent = it.key();+ QTimer::singleShot(1500, this, [this, parent] {+ if (m_closing.contains(parent) && m_windows.contains(parent) && m_closing.value(parent).dialogs.isEmpty()) {+ reopen(parent);+ }+ });+ }+ }+ m_pending.remove(id);+ m_surfaces.remove(id);+ m_apps.remove(id);+ m_agentApps.remove(id);+ m_processes.remove(id);+ m_askedProcess.remove(id);+ m_cloaked.remove(id);+ m_deciding.remove(id);+ m_preexisting.remove(id);+ RailWindow *w = m_windows.take(id);+ if (!w) {+ return;+ }+ if (!w->isPopup() && w->isVisible()) {+ rememberSize(w->appId(), w->size());+ }+ // Popups of this window go with it.+ for (RailWindow *other : std::as_const(m_windows)) {+ if (other->transientParent() == w) {+ other->hide();+ other->setTransientParent(nullptr);+ }+ }+ if (m_active == id) {+ m_active = 0;+ }+ w->hide();+ w->deleteLater();+ Q_EMIT windowGone(id);+}++void Rail::icon(quint32 id, const QImage &image, bool big)+{+ if (RailWindow *w = m_windows.value(id)) {+ w->setIcon(image, big);+ return;+ }+ if (m_pending.contains(id)) {+ Pending &p = m_pending[id];+ if (big || p.icon.isNull()) {+ p.icon = image;+ p.iconBig = big;+ }+ }+}++void Rail::desktop(quint32 active, bool hasActive, const QList<quint32> &z, bool hasZ)+{+ if (hasZ) {+ m_zOrder = z;+ }+ if (!hasActive) {+ return;+ }+ m_active = active;+ noticeActivation(active);+ RailWindow *w = m_windows.value(active);+ if (w && !w->isPopup() && w->isVisible() && QGuiApplication::focusWindow() != w) {+ w->requestActivate();+ }+}++void Rail::surface(quint64 id, quint16 surfaceId, const QRegion &damage, const QSize &size)+{+ if (const auto seen = m_surfaces.constFind(quint32(id)); seen == m_surfaces.cend() || seen->first != surfaceId) {+ log(quint32(id), QStringLiteral("drawn from surface %1, %2x%3%4")+ .arg(surfaceId)+ .arg(size.width())+ .arg(size.height())+ .arg(seen == m_surfaces.cend() ? QString() : QStringLiteral(" (was surface %1)").arg(seen->first)));+ }+ m_surfaces.insert(quint32(id), {surfaceId, size});+ if (auto it = m_closing.find(quint32(id)); it != m_closing.end()) {+ const qint64 at = it->since.elapsed();+ if (it->firstDamage < 0) {+ it->firstDamage = at;+ if (qEnvironmentVariableIsSet("WILDOS_RDP_CLOSE_TIMING")) {+ log(quint32(id), QStringLiteral("drew again %1 ms after its close").arg(at));+ }+ }+ if (it->hidden && !it->unwanted && !it->quiet) {+ // A question that came after the grace period: it comes back.+ log(quint32(id), QStringLiteral("drew again %1 ms after its close, while hidden; asking, so it comes back").arg(at));+ reopen(quint32(id));+ }+ }+ RailWindow *w = m_windows.value(quint32(id));+ if (!w) {+ // Windows draws windows it has not shown yet (and ones it never+ // will); the whole surface is read when the window appears.+ m_surfaces.insert(quint32(id), {surfaceId, size});+ return;+ }+ w->surfaceDamaged(surfaceId, damage, size);+}++void Rail::primary(const QRegion &damage)+{+ for (RailWindow *w : std::as_const(m_windows)) {+ w->primaryDamaged(damage);+ }+}++void Rail::moveSize(quint32 id, bool start, quint16 type, int, int)+{+ RailWindow *w = m_windows.value(id);+ if (!w || w->isPopup()) {+ return;+ }+ if (start) {+ w->beginLocalMoveSize(type);+ } else {+ w->endLocalMoveSize();+ }+}++void Rail::minMax(quint32 id, const QSize &minTrack, const QSize &maxTrack)+{+ if (RailWindow *w = m_windows.value(id)) {+ w->setMinMax(minTrack, maxTrack);+ }+}++void Rail::windowActivated(RailWindow *window, bool active)+{+ const quint32 id = window->remoteId();+ if (active) {+ if (window->remoteMinimized()) {+ m_client->sysCommand(id, SC_RESTORE);+ }+ if (m_active != id) {+ m_active = id;+ m_client->activate(id, true);+ }+ return;+ }+ // Deactivated: if the keyboard went to another app on the desktop, not+ // to another Windows window, Windows is told, which closes its menus.+ QTimer::singleShot(0, this, [this, id] {+ QWindow *focus = QGuiApplication::focusWindow();+ if (qobject_cast<RailWindow *>(focus)) {+ return;+ }+ if (m_active == id) {+ m_client->activate(id, false);+ m_active = 0;+ }+ });+}++QJsonObject Rail::placements()+{+ QSettings s(settingsPath(), QSettings::IniFormat);+ QJsonObject out;+ for (const QString &app : s.childGroups()) {+ const QPoint at = s.value(app + QStringLiteral("/place")).toPoint();+ if (s.contains(app + QStringLiteral("/place"))) {+ out.insert(app, QJsonObject{{QStringLiteral("x"), at.x()}, {QStringLiteral("y"), at.y()}});+ }+ }+ return out;+}++void Rail::savePlacement(const QString &appId, const QPoint &at)+{+ if (!appId.startsWith(QLatin1String("wildos-winmode-")) && !appId.startsWith(QLatin1String("windows-"))) {+ return;+ }+ QSettings s(settingsPath(), QSettings::IniFormat);+ s.setValue(appId + QStringLiteral("/place"), at);+}++void Rail::closeRequested(RailWindow *w)+{+ // Windows is told at once and the window stays exactly as it is for the+ // grace period: most windows are gone well within it; a window asking+ // about unsaved work is never hidden and shown again.+ const quint32 id = w->remoteId();+ if (!id || m_closing.contains(id)) {+ return;+ }+ Closing c;+ c.since.start();+ c.title = w->title();+ c.pid = m_pids.value(id);+ m_closing.insert(id, c);+ log(id, QStringLiteral("closed here; Windows asked to close it"));+ m_client->sysCommand(id, SC_CLOSE);+ if (neverAsk.contains(m_processes.value(id))) {+ m_closing[id].quiet = true;+ log(id, QStringLiteral("its program never asks; hidden at once"));+ hideClosing(id);+ QTimer::singleShot(closeQuietMs, this, [this, id] { closeUnanswered(id, false); });+ QTimer::singleShot(closeEndMs, this, [this, id] { closeUnanswered(id, true); });+ return;+ }+ QTimer::singleShot(closeGraceMs, this, [this, id] { closeGrace(id, false); });+ QTimer::singleShot(closeAskingMs, this, [this, id] { closeGrace(id, true); });+}++void Rail::closeGrace(quint32 id, bool last)+{+ auto it = m_closing.find(id);+ if (it == m_closing.end() || it->hidden || !m_windows.contains(id)) {+ return;+ }+ const bool asked = !it->dialogs.isEmpty() || it->firstDamage >= 0 || it->disabled;+ if (asked && last) {+ // Still there and it drew in itself or opened a dialog: it is+ // asking. It stays, an ordinary open window again.+ log(id, QStringLiteral("asking before it closes (drew again at %1 ms); stays on screen").arg(it->firstDamage));+ m_closing.erase(it);+ return;+ }+ if (asked) {+ return;+ }+ // No word from Windows at all: the window leaves the screen and the+ // taskbar now, and the rest is handled in the background.+ log(id, QStringLiteral("no answer to its close in %1 ms; hidden").arg(closeGraceMs));+ hideClosing(id);+ QTimer::singleShot(closeQuietMs, this, [this, id] { closeUnanswered(id, false); });+ QTimer::singleShot(closeEndMs, this, [this, id] { closeUnanswered(id, true); });+}++void Rail::hideClosing(quint32 id)+{+ auto it = m_closing.find(id);+ RailWindow *w = m_windows.value(id);+ if (it == m_closing.end() || !w) {+ return;+ }+ it->hidden = true;+ for (RailWindow *other : std::as_const(m_windows)) {+ if (other->transientParent() == w) {+ other->hide();+ }+ }+ w->hide();+}++void Rail::closeUnanswered(quint32 id, bool end)+{+ auto it = m_closing.find(id);+ if (it == m_closing.end() || !m_windows.contains(id)) {+ return;+ }+ // A dialog it showed (Save changes?) is the person's to answer.+ for (quint32 dialog : std::as_const(it->dialogs)) {+ if (m_windows.contains(dialog)) {+ return;+ }+ }+ // Windows apps mark a document with changes that are not saved with an+ // asterisk in the title (Notepad, Paint, most editors).+ const bool unsaved = it->title.contains(u'*');+ if (!end) {+ if (unsaved && !it->notified) {+ it->notified = true;+ notifyUnsaved(id);+ }+ return;+ }+ if (unsaved) {+ // Kept running in the background rather than lose the work.+ return;+ }+ // Nothing unsaved and no answer: the app is stuck. It is ended quietly+ // in Windows, unless its process has other windows still open here.+ for (auto w = m_windows.cbegin(); w != m_windows.cend(); ++w) {+ if (w.key() != id && it->pid && m_pids.value(w.key()) == it->pid && !m_closing.contains(w.key()) && w.value()->isVisible()) {+ log(id, QStringLiteral("did not close; its program has other windows open, so it stays in the background"));+ return;+ }+ }+ log(id, QStringLiteral("did not close in %1 s; asking for its program to be ended").arg(closeEndMs / 1000));+ Q_EMIT closeStalled(id, it->pid, m_processes.value(id));+}++void Rail::notifyUnsaved(quint32 id)+{+ const Closing c = m_closing.value(id);+ RailWindow *w = m_windows.value(id);+ QString app = c.title;+ app.remove(u'*');+ app = app.section(QStringLiteral(" - "), -1).trimmed();+ QDBusMessage call = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.Notifications"), QStringLiteral("/org/freedesktop/Notifications"),+ QStringLiteral("org.freedesktop.Notifications"), QStringLiteral("Notify"));+ QVariantMap hints;+ if (w) {+ hints.insert(QStringLiteral("desktop-entry"), w->appId());+ }+ call << QStringLiteral("Windows mode") << quint32(0) << QString() << QStringLiteral("%1 hasn't closed").arg(app.isEmpty() ? QStringLiteral("The app") : app)+ << QStringLiteral("It has changes that aren't saved, so it's still open in the background.")+ << QStringList{QStringLiteral("show"), QStringLiteral("Show it")} << hints << qint32(-1);+ QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(QDBusConnection::sessionBus().asyncCall(call), this);+ connect(watcher, &QDBusPendingCallWatcher::finished, this, [this, watcher, id] {+ QDBusPendingReply<quint32> reply = *watcher;+ if (reply.isValid()) {+ m_notifications.insert(reply.value(), id);+ }+ watcher->deleteLater();+ });+}++void Rail::notificationAction(quint32 notification, const QString &action)+{+ const quint32 id = m_notifications.take(notification);+ if (!id || action != QLatin1String("show")) {+ return;+ }+ reopen(id);+}++void Rail::reopen(quint32 id)+{+ // The close did not happen (the person cancelled it, or asked to see+ // the window again): it comes back as it was.+ m_closing.remove(id);+ RailWindow *w = m_windows.value(id);+ const RailOrder s = m_pending.value(id).state;+ if (w && s.showState != stateHidden && !m_cloaked.contains(id)) {+ log(id, QStringLiteral("still open after its close; shown again"));+ showAs(w, s.showState);+ w->requestActivate();+ }+}++void Rail::connectionLost()+{+ // Reconnecting: windows that would only sit frozen go from the screen+ // if it takes more than a moment, and come back when it is back.+ m_lostAt.start();+ QTimer::singleShot(lostHideMs, this, [this] {+ if (!m_lostAt.isValid()) {+ return;+ }+ for (auto it = m_windows.cbegin(); it != m_windows.cend(); ++it) {+ if (it.value()->isVisible()) {+ m_hiddenByLoss.insert(it.key());+ it.value()->hide();+ }+ }+ });+}++void Rail::connectionBack()+{+ m_lostAt.invalidate();+ const QSet<quint32> hidden = std::exchange(m_hiddenByLoss, {});+ for (quint32 id : hidden) {+ if (RailWindow *w = m_windows.value(id); w && !m_closing.contains(id)) {+ showAs(w, m_pending.value(id).state.showState);+ }+ }+}diff --git a/packages/wildos-rdp/src/rail.h b/packages/wildos-rdp/src/rail.hnew file mode 100644index 0000000..adc050a--- /dev/null+++ b/packages/wildos-rdp/src/rail.h@@ -0,0 +1,211 @@+#pragma once++#include "client.h"++#include <QCursor>+#include <QElapsedTimer>+#include <QHash>+#include <QIcon>+#include <QSet>+#include <QJsonObject>+#include <QObject>+#include <QPointer>+#include <QTimer>++class RailWindow;++// The windows of the one RemoteApp session: one RailWindow per Windows+// window, the loading windows waiting for their app, and which Windows+// window each loading window turns into.+class Rail : public QObject+{+ Q_OBJECT++public:+ Rail(Client *client, double scale, QObject *parent = nullptr);+ ~Rail() override;++ // The scale Windows draws at: Windows' pixels per desktop unit.+ double scale() const { return m_scale; }+ void setScale(double scale) { m_scale = scale; }++ // Shows a loading window for an app, at once or after `delayMs` if the+ // app has not opened by then. `program` is the app's program (a Windows+ // path or file name): the first app window from it takes the loading+ // window over, and every window from it gets the app's id. Returns the+ // loading window's token.+ quint32 prepare(const QString &appId, const QString &title, const QString &icon, const QString &program = {}, int delayMs = 0);+ // The program of a loading window that was opened without one.+ void setProgram(quint32 token, const QString &program);+ // The loading window of the app the connection itself asks for.+ void setCold(quint32 token);+ // News for a loading window from the agent: stage "almost" once the+ // app's process is up, and why it is taking longer when it knows.+ bool update(quint32 token, const QString &stage, const QString &reason, int percent, const QString &progress);+ // Closes a loading window that is still waiting.+ bool cancel(quint32 token, const QString &reason);+ // Which app a Windows window belongs to, from the agent.+ void setWindowApp(quint32 id, const QString &appId);+ // Every window, loading or not, closes.+ void closeAll();++ RailWindow *window(quint32 id) const { return m_windows.value(id); }+ RailWindow *loadingWindow(quint32 token) const+ {+ RailWindow *w = m_placeholders.value(token).window;+ return w ? w : m_loadingByToken.value(token).data();+ }+ QList<quint32> windowIds() const { return m_windows.keys(); }+ const QCursor &cursor() const { return m_cursor; }++ // Each app's last place on screen, kept between sessions.+ static QJsonObject placements();+ static void savePlacement(const QString &appId, const QPoint &at);++ // From the windows.+ void windowActivated(RailWindow *window, bool active);+ // Our close (taskbar, Alt+F4): off the screen now, Windows told after.+ void closeRequested(RailWindow *window);+ void loadingShown(quint32 token);+ void detailsRequested(quint32 token) { Q_EMIT loadingDetails(token); }+ void retryRequested(quint32 token) { Q_EMIT loadingRetry(token); }+ // A window's first picture is on screen.+ void windowDrawn(RailWindow *window);++Q_SIGNALS:+ // A Windows window appeared on screen, or went.+ void windowShown(quint32 id, const QString &title);+ void windowGone(quint32 id);+ // A loading window finished: "window" when its app's window took it+ // over, "timeout", "cancelled" or "ended" otherwise.+ void loadingFinished(quint32 token, const QString &reason, quint32 id);+ void loadingVisible(quint32 token, qint64 milliseconds);+ // "Show details" on a loading window that is taking longer.+ void loadingDetails(quint32 token);+ void loadingRetry(quint32 token);+ // A window closed here that Windows has not closed, with nothing unsaved+ // in it, and its program has no other window: it can be ended.+ void closeStalled(quint32 id, quint32 pid, const QString &program);++public Q_SLOTS:+ void notificationAction(uint notification, const QString &action);++private:+ void order(const RailOrder &order);+ void deleted(quint32 id);+ void icon(quint32 id, const QImage &image, bool big);+ void desktop(quint32 active, bool hasActive, const QList<quint32> &z, bool hasZ);+ void surface(quint64 id, quint16 surfaceId, const QRegion &damage, const QSize &size);+ void primary(const QRegion &damage);+ void moveSize(quint32 id, bool start, quint16 type, int x, int y);+ void minMax(quint32 id, const QSize &minTrack, const QSize &maxTrack);+ void stepAsideFor(quint32 id);+ void desktopSynced();+ void hideClosing(quint32 id);+ void setCursorAll(const QCursor &cursor);++ void realize(quint32 id);+ void process(quint32 id, const QString &image, const QString &appUserModel, quint32 pid);+ void cloak(quint32 id, bool cloaked);+ void giveBack(RailWindow *window);+ void noticeActivation(quint32 active);+ void closeUnanswered(quint32 id, bool end);+ void closeGrace(quint32 id, bool last);+ void notifyUnsaved(quint32 id);+ void reopen(quint32 id);+ void connectionLost();+ void connectionBack();+ bool ownedByShownWindow(const RailOrder &state) const;+ bool overlapsAppWindow(const QRect &rect) const;+ void log(quint32 id, const QString &what) const;+ RailWindow *parentFor(quint32 id) const;+ RailWindow *takePlaceholder(quint32 id, const QString &title, bool early);+ QString appIdFor(quint32 id) const;+ void loadingTimedOut(quint32 token);++ struct Pending {+ RailOrder state;+ QImage icon;+ bool iconBig = false;+ };++ Client *m_client;+ double m_scale;+ QHash<quint32, RailWindow *> m_windows;+ // Windows' windows that are known but not on screen (hidden, or a+ // popup still without a window to belong to).+ QHash<quint32, Pending> m_pending;+ QHash<quint32, QString> m_apps;+ QHash<quint32, QPair<quint16, QSize>> m_surfaces;+ QList<quint32> m_zOrder;+ quint32 m_active = 0;+ QCursor m_cursor;++ struct Placeholder {+ QPointer<RailWindow> window;+ QString title;+ QString program;+ QString appId;+ QIcon icon;+ QElapsedTimer age;+ QTimer *timeout = nullptr;+ // The connection's own app, asked for when it connected: its window+ // comes after Windows has sent the windows already open.+ bool cold = false;+ };+ QHash<quint32, Placeholder> m_placeholders;+ quint32 m_nextToken = 1;+ // Loading windows already handed to their app, still finishing, and+ // what they were waiting for, in case the window they took goes.+ QHash<quint32, QPointer<RailWindow>> m_loadingByToken;+ QHash<quint32, Placeholder> m_adopted;+ // Each window's program (file name, lower case), the ones asked about,+ // the ones waiting for the answer before they are shown, and Windows'+ // cloaked (hidden while it prepares them) windows.+ QHash<quint32, QString> m_processes;+ QSet<quint32> m_askedProcess;+ QSet<quint32> m_deciding;+ QSet<quint32> m_cloaked;+ // The apps of the programs being opened, and windows whose app the agent+ // named, which nothing here overrides.+ QHash<QString, QString> m_programApps;+ QHash<QString, QIcon> m_programIcons;+ QSet<quint32> m_agentApps;+ QHash<quint32, quint32> m_pids;++ // Windows closed here that Windows has not closed yet.+ struct Closing {+ QElapsedTimer since;+ QString title;+ quint32 pid = 0;+ QSet<quint32> dialogs;+ bool notified = false;+ bool hidden = false;+ qint64 firstDamage = -1;+ // Never shown: the window of a launch the person cancelled. Its+ // first picture is not a question.+ bool unwanted = false;+ // Its program never asks before closing: it is off the screen at+ // once, and its redrawing while Windows ends it is not a question.+ bool quiet = false;+ // Windows disabled it after the close: a modal question is up.+ bool disabled = false;+ };+ QHash<quint32, Closing> m_closing;+ // Programs whose launch the person cancelled on the loading window, with+ // when each cancelled launch stops counting (ms since the epoch).+ QHash<QString, QList<qint64>> m_cancelled;+ // On connecting, Windows first sends every window already open in the+ // session (an app the last connection left, another copy of the same+ // program) and only then starts the connection's app. Those windows are+ // never that app's and say nothing about its launch; an app opened in+ // the session meanwhile can be among them, so other loading windows+ // still take them.+ bool m_synced = false;+ bool m_syncWaiting = false;+ QSet<quint32> m_preexisting;+ bool takeCancelled(const QString &program);+ QHash<quint32, quint32> m_notifications;+ QElapsedTimer m_lostAt;+ QSet<quint32> m_hiddenByLoss;+};diff --git a/packages/wildos-rdp/src/railwindow.cpp b/packages/wildos-rdp/src/railwindow.cppnew file mode 100644index 0000000..ca8d249--- /dev/null+++ b/packages/wildos-rdp/src/railwindow.cpp@@ -0,0 +1,901 @@+#include "railwindow.h"+#include "style.h"+#include "wayland.h"+#include "client.h"+#include "input.h"+#include "kwin.h"+#include "rail.h"++#include <KWindowEffects>++#include <QGuiApplication>+#include <QPainter>+#include <QPainterPath>+#include <QResizeEvent>+#include <QScreen>+#include <QTimer>++#include <freerdp/input.h>+#include <freerdp/rail.h>+#include <freerdp/window.h>++#include <cmath>+#include <cstring>++namespace+{+constexpr quint32 stateMinimized = 0x02;+constexpr quint32 stateMaximized = 0x03;+constexpr quint32 stateHidden = 0x00;+constexpr qreal cornerRadius = 12;+// Once the app has drawn, how long it may take to come to the loading+// window's size before it is shown at the size Windows gave it.+constexpr int handoffResizeMs = 400;+// An app window that has drawn nothing by then is shown anyway: Windows+// says it is open, so the loading window has nothing left to wait for.+constexpr int handoffBlankMs = 4000;+// How long the loading window takes to fade into the app (board 9.11's+// closing sequence, wlcomplete to wlapp).+constexpr int finishMs = 1760;++QRect deviceRect(const QRect &logical, qreal dpr, const QSize &bounds)+{+ const int x0 = int(std::floor(logical.left() * dpr));+ const int y0 = int(std::floor(logical.top() * dpr));+ const int x1 = int(std::ceil((logical.left() + logical.width()) * dpr));+ const int y1 = int(std::ceil((logical.top() + logical.height()) * dpr));+ return QRect(x0, y0, x1 - x0, y1 - y0).intersected(QRect(QPoint(0, 0), bounds));+}++QRect logicalRect(const QRect &device, qreal dpr)+{+ const int x0 = int(std::floor(device.left() / dpr));+ const int y0 = int(std::floor(device.top() / dpr));+ const int x1 = int(std::ceil((device.left() + device.width()) / dpr));+ const int y1 = int(std::ceil((device.top() + device.height()) / dpr));+ return QRect(x0, y0, x1 - x0, y1 - y0);+}++QPainterPath roundedPath(const QSizeF &size)+{+ QPainterPath path;+ path.addRoundedRect(QRectF(QPointF(0, 0), size).adjusted(0.5, 0.5, -0.5, -0.5), cornerRadius, cornerRadius);+ return path;+}++Qt::Edges edgesFor(quint16 type)+{+ switch (type) {+ case RAIL_WMSZ_LEFT: return Qt::LeftEdge;+ case RAIL_WMSZ_RIGHT: return Qt::RightEdge;+ case RAIL_WMSZ_TOP: return Qt::TopEdge;+ case RAIL_WMSZ_TOPLEFT: return Qt::TopEdge | Qt::LeftEdge;+ case RAIL_WMSZ_TOPRIGHT: return Qt::TopEdge | Qt::RightEdge;+ case RAIL_WMSZ_BOTTOM: return Qt::BottomEdge;+ case RAIL_WMSZ_BOTTOMLEFT: return Qt::BottomEdge | Qt::LeftEdge;+ case RAIL_WMSZ_BOTTOMRIGHT: return Qt::BottomEdge | Qt::RightEdge;+ default: return {};+ }+}+}++RailWindow::RailWindow(Rail *rail, Client *client, const QString &appId)+ : m_rail(rail)+ , m_client(client)+ , m_appId(appId)+{+ setSurfaceType(QSurface::RasterSurface);+ QSurfaceFormat format;+ format.setAlphaBufferSize(8);+ setFormat(format);+ setFlags(Qt::Window | Qt::FramelessWindowHint);+ m_store = std::make_unique<QBackingStore>(this);+ setCursor(rail->cursor());+ m_handoffTimer.setSingleShot(true);+ connect(&m_handoffTimer, &QTimer::timeout, this, [this] {+ if (m_handoffResizing && !m_hasSurface && !m_primary) {+ // Nothing drawn yet: whatever comes first is shown, at any size.+ m_handoffResizing = false;+ m_handoffTimer.start(handoffBlankMs);+ return;+ }+ appReady();+ });+}++RailWindow::~RailWindow()+{+ releaseKeys();+}++double RailWindow::scale() const+{+ return m_rail->scale();+}++QSize RailWindow::logicalSize(const QSize &remote) const+{+ return QSize(std::max(1, int(std::lround(remote.width() / scale()))), std::max(1, int(std::lround(remote.height() / scale()))));+}++bool RailWindow::remoteVisible() const+{+ return m_id != 0 && m_showState != stateHidden && m_frame.width() > 0 && m_frame.height() > 0;+}++void RailWindow::startLoading(const QString &title, const QIcon &icon, const QSize &size)+{+ m_loading = true;+ setTitle(title);+ resize(size);+ m_view.start(title, icon, Style::read().reducedMotion);+ KWindowEffects::enableBlurBehind(this, true, QRegion(roundedPath(size).toFillPolygon().toPolygon()));+}++void RailWindow::stopLoading()+{+ if (!m_loading) {+ return;+ }+ m_loading = false;+ m_handoffTimer.stop();+ KWindowEffects::enableBlurBehind(this, false);+ const QString title = property("remoteTitle").toString();+ if (!title.isEmpty()) {+ setTitle(title);+ }+ if (m_frame.isValid() && logicalSize(m_frame.size()) != intendedSize()) {+ resizeAroundCentre(logicalSize(m_frame.size()));+ }+ m_damage = QRect(QPoint(0, 0), m_hasSurface ? m_surfaceSize : m_frame.size());+ m_fullRepaint = true;+ requestUpdate();+}++QSize RailWindow::intendedSize() const+{+ return m_targetSize.isValid() ? m_targetSize : size();+}++void RailWindow::resizeAroundCentre(const QSize &to)+{+ if (to == intendedSize()) {+ return;+ }+ m_targetSize = to;+ if (!KWinPlace::resizeAroundCentre(this, m_appId, to)) {+ resize(to);+ return;+ }+ QTimer::singleShot(400, this, [this, to] {+ if (m_targetSize == to && size() != to) {+ // KWin did not do it: the size matters more than the place.+ resize(to);+ }+ });+}++void RailWindow::setLoadingStage(LoadingView::Stage stage)+{+ m_view.setStage(stage);+}++void RailWindow::setLoadingEnded()+{+ m_view.setEnded();+ m_fullRepaint = true;+ requestUpdate();+}++void RailWindow::setLoadingReason(const QString &reason, int percent, const QString &progress)+{+ m_view.setReason(reason, percent, progress);+ m_fullRepaint = true;+}++void RailWindow::beginHandoff()+{+ m_view.setStage(LoadingView::Stage::AlmostReady);+ m_view.arrive();+ // Nothing moves or resizes once the app shows. A resizable app is asked+ // to take this window's size; one Windows will not resize (a fixed+ // dialog such as Character Map) gives this window its own size now,+ // before its picture comes. The app is shown as soon as it has drawn,+ // whether or not it took the size: the handoff never waits on the app+ // agreeing to it.+ const QSize wanted(int(std::lround(width() * scale())), int(std::lround(height() * scale())));+ m_handoffSize = m_frame.size();+ m_handoffResizing = false;+ if ((m_style & WS_THICKFRAME) && m_frame.isValid() && m_frame.size() != wanted && !(m_style & WS_MAXIMIZE)) {+ m_handoffSize = wanted;+ m_handoffResizing = true;+ m_client->moveWindow(m_id, QRect(m_frame.topLeft(), wanted));+ } else if (m_frame.isValid() && !(m_style & WS_MAXIMIZE) && logicalSize(m_frame.size()) != intendedSize()) {+ resizeAroundCentre(logicalSize(m_frame.size()));+ m_fullRepaint = true;+ requestUpdate();+ }+ m_handoffTimer.start(m_handoffResizing ? handoffResizeMs * 3 : handoffBlankMs);+ if (m_hasSurface || m_primary) {+ handoffContent(m_hasSurface ? m_surfaceSize : m_frame.size());+ }+}++void RailWindow::handoffContent(const QSize &drawn)+{+ if (!m_loading || !m_id || m_view.finishing() || !m_handoffSize.isValid()) {+ return;+ }+ if (!m_handoffResizing || drawn == m_handoffSize) {+ appReady();+ return;+ }+ // Drawn, but not at the size asked for yet: it is given a moment.+ if (!m_handoffTimer.isActive() || m_handoffTimer.remainingTime() > handoffResizeMs) {+ m_handoffTimer.start(handoffResizeMs);+ }+}++void RailWindow::appReady()+{+ if (!m_loading || m_view.finishing()) {+ return;+ }+ m_handoffTimer.stop();+ if (m_frame.isValid() && logicalSize(m_frame.size()) != intendedSize()) {+ // Windows kept its own size (the app did not take this window's):+ // the window takes Windows', once, as the app comes in.+ resizeAroundCentre(logicalSize(m_frame.size()));+ }+ m_view.finish();+ m_fullRepaint = true;+ requestUpdate();+ // The fade is paced by the compositor's frames; if one never comes (a+ // frame lost around a resize), the window would be left half faded+ // into the loading window. It is finished by the clock as well.+ for (int at : {finishMs + 100, finishMs + 1000}) {+ QTimer::singleShot(at, this, [this] {+ if (m_loading && m_view.done()) {+ render();+ }+ });+ }+}++void RailWindow::adopt(quint32 id)+{+ m_id = id;+ // Windows sends a new window's picture straight away; if it has not+ // come (a window Windows had drawn before this connection), it is asked+ // for again.+ for (int delay : {800, 2500}) {+ QTimer::singleShot(delay, this, [this] {+ if (m_loading && !m_hasSurface && !m_primary && m_frame.isValid()) {+ m_client->refresh(m_frame);+ }+ });+ }+}++void RailWindow::unadopt()+{+ m_id = 0;+ m_hasSurface = false;+ m_primary = false;+ m_hasContent = false;+ m_surfaceId = 0;+ m_surfaceSize = QSize();+ m_frame = QRect();+ m_damage = QRegion();+ m_handoffTimer.stop();+ m_handoffSize = QSize();+ m_handoffResizing = false;+ m_view.unarrive();+ m_fullRepaint = true;+ requestUpdate();+}++void RailWindow::setRemoteState(quint32 id, quint32 style, quint32 exStyle, bool popup)+{+ m_id = id;+ m_style = style;+ m_exStyle = exStyle;+ m_layered = (exStyle & WS_EX_LAYERED) && popup;+ if (popup != m_popup && !handle()) {+ m_popup = popup;+ // Menus and tooltips are popups of the window they belong to; they+ // never take the keyboard from it, which Windows keeps routing.+ setFlags(popup ? (Qt::ToolTip | Qt::FramelessWindowHint | Qt::WindowDoesNotAcceptFocus) : (Qt::Window | Qt::FramelessWindowHint));+ }+}++void RailWindow::setFrame(const QRect &frame)+{+ const bool resized = frame.size() != m_frame.size();+ m_frame = frame;+ if (resized && !m_loading && !(windowStates() & Qt::WindowMaximized)) {+ resize(logicalSize(frame.size()));+ }+}++void RailWindow::setShowState(quint32 state)+{+ m_showState = state;+}++void RailWindow::setRemoteTitle(const QString &title)+{+ if (!m_loading) {+ setTitle(title);+ } else {+ // Kept for when the app takes over.+ setProperty("remoteTitle", title);+ }+}++void RailWindow::setIcon(const QImage &image, bool big)+{+ if (image.isNull()) {+ return;+ }+ if (!big && !m_remoteIcon.isNull()) {+ return;+ }+ m_remoteIcon = image;+ QWindow::setIcon(QIcon(QPixmap::fromImage(image)));+ if (isVisible()) {+ sendIcon();+ }+}++void RailWindow::sendIcon()+{+ // Qt 6.8 does not pass a window's icon on to the compositor; the icon+ // Windows sent (or the app's, while loading) goes over the protocol+ // for it, so the taskbar shows it even for an app with no entry.+ if (m_popup) {+ return;+ }+ QImage image = m_remoteIcon;+ if (image.isNull() && !icon().isNull()) {+ image = icon().pixmap(QSize(64, 64)).toImage();+ }+ if (!image.isNull()) {+ m_iconSent = WaylandExtras::instance().setIcon(this, image);+ }+}++void RailWindow::setAppId(const QString &appId)+{+ if (appId == m_appId) {+ return;+ }+ m_appId = appId;+ if (!isVisible() || m_popup || WaylandExtras::instance().setAppId(this, appId)) {+ return;+ }+ // Without the window's own protocol object the app id is only read+ // when the window is shown, so it is shown again to carry the new one.+ {+ const QString saved = QGuiApplication::desktopFileName();+ QGuiApplication::setDesktopFileName(appId);+ hide();+ show();+ QGuiApplication::setDesktopFileName(saved);+ }+}++void RailWindow::setMinMax(const QSize &minTrack, const QSize &maxTrack)+{+ if (minTrack.isValid() && minTrack.width() > 0) {+ setMinimumSize(logicalSize(minTrack));+ }+ if (maxTrack.isValid() && maxTrack.width() > 0 && maxTrack.width() < 30000) {+ setMaximumSize(logicalSize(maxTrack));+ }+}++void RailWindow::surfaceDamaged(quint16 surfaceId, const QRegion &damage, const QSize &size)+{+ if (!m_hasSurface || surfaceId != m_surfaceId || size != m_surfaceSize) {+ m_surfaceId = surfaceId;+ m_surfaceSize = size;+ m_hasSurface = true;+ m_primary = false;+ m_damage = QRect(QPoint(0, 0), size);+ } else {+ m_damage += damage;+ }+ handoffContent(size);+ if (!m_updateQueued) {+ m_updateQueued = true;+ requestUpdate();+ }+}++void RailWindow::primaryDamaged(const QRegion &desktopDamage)+{+ if (m_hasSurface) {+ return;+ }+ const QRegion mine = desktopDamage.intersected(m_frame).translated(-m_frame.topLeft());+ if (mine.isEmpty()) {+ return;+ }+ m_primary = true;+ m_damage += mine;+ handoffContent(m_frame.size());+ if (!m_updateQueued) {+ m_updateQueued = true;+ requestUpdate();+ }+}++bool RailWindow::event(QEvent *event)+{+ switch (event->type()) {+ case QEvent::Hide:+ // A window shown again is a new toplevel to the compositor.+ m_iconSent = false;+ break;+ case QEvent::UpdateRequest:+ m_updateQueued = false;+ render();+ return true;+ case QEvent::Close:+ event->ignore();+ if (m_id) {+ // The app's window, or the loading window that has taken it and+ // is handing over: either way the app is what is being closed.+ if (!m_loading && (m_keysDown.contains(0x38) || m_keysDown.contains(0x38 | 0x100))) {+ // Alt+F4 is the compositor's: Windows saw Alt go down and will+ // see it come up with nothing between, which opens the app's+ // menu or its key tips. A Ctrl tap in between stops that.+ m_client->sendKey(true, false, 0x1D);+ m_client->sendKey(false, false, 0x1D);+ }+ m_rail->closeRequested(this);+ } else if (m_loading) {+ m_rail->cancel(property("token").toUInt(), QStringLiteral("cancelled"));+ }+ return true;+ case QEvent::Enter:+ if (m_moveSize) {+ finishMoveSize(static_cast<QEnterEvent *>(event)->position());+ }+ break;+ case QEvent::WindowStateChange:+ if (m_id && !m_loading && !m_popup) {+ const bool maximized = windowStates() & Qt::WindowMaximized;+ if (maximized && m_showState != stateMaximized) {+ m_client->sysCommand(m_id, SC_MAXIMIZE);+ } else if (!maximized && m_showState == stateMaximized) {+ m_client->sysCommand(m_id, SC_RESTORE);+ }+ }+ break;+ default:+ break;+ }+ return QWindow::event(event);+}++void RailWindow::exposeEvent(QExposeEvent *)+{+ if (!isExposed()) {+ return;+ }+ m_loadingPainted = false;+ if (!m_iconSent) {+ sendIcon();+ }+ if (m_loading) {+ m_rail->loadingShown(property("token").toUInt());+ }+ m_damage = QRect(QPoint(0, 0), m_hasSurface ? m_surfaceSize : m_frame.size());+ render();+}++void RailWindow::resizeEvent(QResizeEvent *event)+{+ m_store->resize(event->size());+ m_loadingPainted = false;+ if (event->size() == m_targetSize) {+ m_targetSize = QSize();+ }+ if (m_loading) {+ KWindowEffects::enableBlurBehind(this, true, QRegion(roundedPath(event->size()).toFillPolygon().toPolygon()));+ }+ if (m_hasSurface) {+ m_damage = QRect(QPoint(0, 0), m_surfaceSize);+ }+ if (!m_loading && m_id && !m_popup && !m_moveSize) {+ // The compositor sized the window itself (snapped to half the+ // screen, maximised): Windows follows.+ const QSize remote(int(std::lround(event->size().width() * scale())), int(std::lround(event->size().height() * scale())));+ const bool maximized = windowStates() & Qt::WindowMaximized;+ if (maximized) {+ m_client->setWorkArea(QRect(QPoint(0, 0), remote));+ } else if (logicalSize(m_frame.size()) != event->size() && m_frame.isValid()) {+ m_client->moveWindow(m_id, QRect(m_frame.topLeft(), remote));+ }+ }+}++void RailWindow::render()+{+ if (!isExposed()) {+ return;+ }+ if (m_loading) {+ if (m_view.done()) {+ stopLoading();+ } else {+ renderLoading();+ return;+ }+ }+ renderRemote();+}++void RailWindow::renderLoading()+{+ const QRect all(QPoint(0, 0), size());+ // While the light runs its laps only the mark and the line under it+ // change; everything else is painted when it does.+ const bool slow = m_view.slow();+ QRegion region = all;+ bool steady = false;+ if (!m_fullRepaint && slow == m_wasSlow && !m_view.finishing() && m_loadingPainted && m_view.settled()) {+ region = m_view.steadyArea(QSizeF(size())).toAlignedRect();+ steady = true;+ }+ m_fullRepaint = false;+ m_wasSlow = slow;+ m_store->beginPaint(region);+ {+ QPainter p(m_store->paintDevice());+ p.setClipRegion(region);+ const qreal dpr = devicePixelRatio();+ if (steady && m_loadingBackground.size() == (QSizeF(size()) * dpr).toSize()) {+ // The frame and title bar do not change between frames: kept from+ // the last full paint, only the W and its words are drawn.+ p.setCompositionMode(QPainter::CompositionMode_Source);+ p.drawImage(QPointF(0, 0), m_loadingBackground);+ p.setCompositionMode(QPainter::CompositionMode_SourceOver);+ m_view.paint(p, QSizeF(size()), false, true);+ } else {+ paintLoading(p);+ if (!m_view.finishing() && m_view.settled()) {+ m_loadingBackground = QImage((QSizeF(size()) * dpr).toSize(), QImage::Format_ARGB32_Premultiplied);+ m_loadingBackground.setDevicePixelRatio(dpr);+ m_loadingBackground.fill(Qt::transparent);+ QPainter bg(&m_loadingBackground);+ m_view.paint(bg, QSizeF(size()), true, false);+ }+ }+ if (m_view.finishing() && (m_hasSurface || m_primary)) {+ // wlapp: the app fades in where it will stay.+ const QImage app = snapshot();+ p.setOpacity(m_view.appOpacity());+ p.drawImage(QRectF(QPointF(0, 0), QSizeF(app.size()) / scale()), app);+ }+ }+ m_store->endPaint();+ m_store->flush(region);+ m_loadingPainted = true;+ if (m_view.animating()) {+ // Paced by the compositor's frames, and stopped while hidden.+ requestUpdate();+ }+}++void RailWindow::renderRemote()+{+ if (m_damage.isEmpty()) {+ return;+ }+ const qreal dpr = devicePixelRatio();+ const QSize logical = size();+ QRegion logicalDamage;+ for (const QRect &r : m_damage) {+ logicalDamage += logicalRect(r, dpr).intersected(QRect(QPoint(0, 0), logical));+ }+ m_damage = QRegion();+ if (logicalDamage.isEmpty()) {+ return;+ }+ m_store->beginPaint(logicalDamage);+ auto *image = dynamic_cast<QImage *>(m_store->paintDevice());+ const bool exact = image && std::abs(dpr - scale()) < 0.01;+ bool opaque = !m_layered && !m_alpha;+ auto copy = [&](const uchar *data, int stride, QSize size) {+ if (exact) {+ const QSize bounds = image->size().boundedTo(size);+ for (const QRect &l : logicalDamage) {+ const QRect d = deviceRect(l, dpr, bounds);+ for (int y = d.top(); y <= d.bottom(); ++y) {+ auto *dst = reinterpret_cast<quint32 *>(image->scanLine(y)) + d.left();+ const auto *src = reinterpret_cast<const quint32 *>(data + qsizetype(y) * stride) + d.left();+ if (opaque) {+ for (int x = 0; x < d.width(); ++x) {+ dst[x] = src[x] | 0xff000000u;+ }+ } else {+ std::memcpy(dst, src, size_t(d.width()) * 4);+ }+ }+ }+ } else {+ // This screen's scale is not the one Windows draws at (the window+ // is on another screen): scaled, which costs some sharpness.+ const QImage source(data, size.width(), size.height(), stride, opaque ? QImage::Format_RGB32 : QImage::Format_ARGB32_Premultiplied);+ QPainter p(m_store->paintDevice());+ p.setRenderHint(QPainter::SmoothPixmapTransform);+ p.setClipRegion(logicalDamage);+ p.setCompositionMode(QPainter::CompositionMode_Source);+ p.drawImage(QRectF(0, 0, size.width() / scale(), size.height() / scale()), source);+ }+ };+ bool ok = false;+ if (m_hasSurface && m_popup && !m_alphaChecked) {+ // A popup Windows draws with real transparency (rounded menus, key+ // tips) is drawn with it here; one drawn by GDI leaves the alpha+ // byte empty everywhere and is opaque.+ m_client->withSurface(m_surfaceId, [this](const uchar *data, int stride, QSize size) {+ bool full = false;+ bool partial = false;+ for (int y = 0; y < size.height() && !(full && partial); ++y) {+ const auto *row = reinterpret_cast<const quint32 *>(data + qsizetype(y) * stride);+ for (int x = 0; x < size.width(); ++x) {+ const quint32 a = row[x] >> 24;+ full |= a == 0xff;+ partial |= a != 0xff;+ }+ }+ m_alpha = full && partial;+ m_alphaChecked = true;+ });+ opaque = !m_layered && !m_alpha;+ }+ if (m_hasSurface) {+ ok = m_client->withSurface(m_surfaceId, [&](const uchar *data, int stride, QSize size) { copy(data, stride, size); });+ } else if (m_primary) {+ ok = m_client->withPrimary([&](const uchar *data, int stride, QSize desktop) {+ const QRect area = m_frame.intersected(QRect(QPoint(0, 0), desktop));+ if (area.isEmpty()) {+ return;+ }+ const uchar *origin = data + qsizetype(area.top()) * stride + qsizetype(area.left()) * 4;+ copy(origin, stride, area.size());+ });+ }+ m_store->endPaint();+ if (ok) {+ m_store->flush(logicalDamage);+ if (!m_hasContent) {+ m_hasContent = true;+ m_rail->windowDrawn(this);+ }+ }+}++QPoint RailWindow::toRemote(const QPointF &local) const+{+ return QPoint(m_frame.x() + int(std::lround(local.x() * scale())), m_frame.y() + int(std::lround(local.y() * scale())));+}++void RailWindow::sendButton(QMouseEvent *event, bool down)+{+ rdpinput::button(m_client, event->button(), down, toRemote(event->position()));+}++void RailWindow::mousePressEvent(QMouseEvent *event)+{+ if (m_loading) {+ loadingPress(event);+ return;+ }+ if (!m_id) {+ return;+ }+ if (!m_popup) {+ m_rail->windowActivated(this, true);+ }+ if (event->button() == Qt::LeftButton) {+ m_pressRemote = toRemote(event->position());+ }+ sendButton(event, true);+}++void RailWindow::mouseReleaseEvent(QMouseEvent *event)+{+ if (!m_id || m_loading) {+ return;+ }+ sendButton(event, false);+}++void RailWindow::mouseMoveEvent(QMouseEvent *event)+{+ if (m_loading) {+ const LoadingView::Hit hit = m_view.hitTest(event->position(), QSizeF(size()));+ const LoadingView::Hit hover = hit == LoadingView::Hit::Drag ? LoadingView::Hit::None : hit;+ if (hover != m_view.hover()) {+ m_view.setHover(hover);+ m_fullRepaint = true;+ requestUpdate();+ }+ return;+ }+ if (!m_id) {+ return;+ }+ if (m_moveSize) {+ if (event->buttons() != Qt::NoButton) {+ return;+ }+ finishMoveSize(event->position());+ }+ rdpinput::move(m_client, toRemote(event->position()));+}++void RailWindow::mouseDoubleClickEvent(QMouseEvent *event)+{+ if (m_loading) {+ if (m_view.hitTest(event->position(), QSizeF(size())) == LoadingView::Hit::Drag) {+ windowStates() & Qt::WindowMaximized ? showNormal() : showMaximized();+ }+ return;+ }+ // Qt sends the second press of a double click as well; Windows works out+ // double clicks from those itself.+}++void RailWindow::loadingPress(QMouseEvent *event)+{+ if (event->button() != Qt::LeftButton) {+ return;+ }+ const quint32 token = property("token").toUInt();+ switch (m_view.hitTest(event->position(), QSizeF(size()))) {+ case LoadingView::Hit::Drag: startSystemMove(); break;+ case LoadingView::Hit::Minimise: showMinimized(); break;+ case LoadingView::Hit::Maximise: windowStates() & Qt::WindowMaximized ? showNormal() : showMaximized(); break;+ case LoadingView::Hit::Close:+ case LoadingView::Hit::Cancel: m_rail->cancel(token, QStringLiteral("cancelled")); break;+ case LoadingView::Hit::Details: m_rail->detailsRequested(token); break;+ case LoadingView::Hit::Retry: m_rail->retryRequested(token); break;+ case LoadingView::Hit::None: break;+ }+}++void RailWindow::wheelEvent(QWheelEvent *event)+{+ if (!m_id || m_loading) {+ return;+ }+ rdpinput::wheel(m_client, event->angleDelta(), toRemote(event->position()), m_wheelX, m_wheelY);+}++void RailWindow::keyPressEvent(QKeyEvent *event)+{+ if (!m_id || m_loading) {+ return;+ }+ rdpinput::key(m_client, event, true, m_keysDown);+}++void RailWindow::keyReleaseEvent(QKeyEvent *event)+{+ if (!m_id || m_loading) {+ return;+ }+ rdpinput::key(m_client, event, false, m_keysDown);+}++void RailWindow::releaseKeys()+{+ // Keys held when the window lost the keyboard would otherwise stay down+ // in Windows: Alt from Alt+Tab is the usual one.+ rdpinput::releaseAll(m_client, m_keysDown);+}++void RailWindow::focusInEvent(QFocusEvent *)+{+ if (m_id && !m_loading && !m_popup) {+ m_rail->windowActivated(this, true);+ }+}++void RailWindow::focusOutEvent(QFocusEvent *)+{+ releaseKeys();+ if (m_id && !m_loading && !m_popup) {+ m_rail->windowActivated(this, false);+ }+}++void RailWindow::beginLocalMoveSize(quint16 type)+{+ bool started = false;+ if (type == RAIL_WMSZ_MOVE) {+ started = startSystemMove();+ } else if (const Qt::Edges edges = edgesFor(type)) {+ started = startSystemResize(edges);+ }+ if (started) {+ m_moveSize = true;+ m_moveSizeType = type;+ m_moveSizeStart = m_frame;+ }+}++void RailWindow::endLocalMoveSize()+{+ m_moveSize = false;+}++void RailWindow::finishMoveSize(const QPointF &)+{+ if (!m_moveSize) {+ return;+ }+ m_moveSize = false;+ // The compositor kept the button's release, so Windows is still in its+ // move loop: it gets the release where the press was, which leaves its+ // window where it is, and then the size the window was given here.+ m_client->sendMouse(PTR_FLAGS_BUTTON1, m_pressRemote.x(), m_pressRemote.y());+ if (m_moveSizeType == RAIL_WMSZ_MOVE) {+ return;+ }+ const QSize remote(int(std::lround(width() * scale())), int(std::lround(height() * scale())));+ const Qt::Edges edges = edgesFor(m_moveSizeType);+ QRect next(m_moveSizeStart.topLeft(), remote);+ if (edges & Qt::LeftEdge) {+ next.moveLeft(m_moveSizeStart.left() + m_moveSizeStart.width() - remote.width());+ }+ if (edges & Qt::TopEdge) {+ next.moveTop(m_moveSizeStart.top() + m_moveSizeStart.height() - remote.height());+ }+ if (next != m_frame) {+ m_client->moveWindow(m_id, next);+ }+}++QImage RailWindow::snapshot() const+{+ QImage out;+ auto copy = [&out](const uchar *data, int stride, QSize size) {+ out = QImage(data, size.width(), size.height(), stride, QImage::Format_RGB32).copy();+ };+ if (m_hasSurface) {+ m_client->withSurface(m_surfaceId, copy);+ } else if (m_primary) {+ m_client->withPrimary([&](const uchar *data, int stride, QSize desktop) {+ const QRect area = m_frame.intersected(QRect(QPoint(0, 0), desktop));+ if (!area.isEmpty()) {+ copy(data + qsizetype(area.top()) * stride + qsizetype(area.left()) * 4, stride, area.size());+ }+ });+ }+ return out;+}++void RailWindow::paintLoading(QPainter &p) const+{+ p.setCompositionMode(QPainter::CompositionMode_Source);+ p.fillRect(QRect(QPoint(0, 0), size()), Qt::transparent);+ p.setCompositionMode(QPainter::CompositionMode_SourceOver);+ m_view.paint(p, QSizeF(size()));+}++QImage RailWindow::loadingSnapshot(qreal dpr) const+{+ QImage image((QSizeF(size()) * dpr).toSize(), QImage::Format_ARGB32_Premultiplied);+ image.setDevicePixelRatio(dpr);+ image.fill(Qt::transparent);+ QPainter p(&image);+ paintLoading(p);+ return image;+}diff --git a/packages/wildos-rdp/src/railwindow.h b/packages/wildos-rdp/src/railwindow.hnew file mode 100644index 0000000..74aa2de--- /dev/null+++ b/packages/wildos-rdp/src/railwindow.h@@ -0,0 +1,165 @@+#pragma once++#include "loading.h"++#include <QBackingStore>+#include <QElapsedTimer>+#include <QImage>+#include <QMargins>+#include <QTimer>+#include <QRegion>+#include <QWindow>++#include <memory>++class Client;+class QPainter;+class Rail;++// One window on the desktop. It starts either as a Windows app's window+// (RemoteApp) or as the loading window shown the moment an app is asked+// for, which becomes that app's window when Windows shows it.+class RailWindow : public QWindow+{+ Q_OBJECT++public:+ RailWindow(Rail *rail, Client *client, const QString &appId);+ ~RailWindow() override;++ // The Windows window this shows; 0 while it is still loading.+ quint32 remoteId() const { return m_id; }+ QString appId() const { return m_appId; }+ bool loading() const { return m_loading; }+ bool isPopup() const { return m_popup; }+ // Where Windows has the window, in its desktop's pixels.+ QRect frame() const { return m_frame; }+ quint32 owner() const { return m_owner; }+ quint32 style() const { return m_style; }+ quint32 exStyle() const { return m_exStyle; }+ bool remoteVisible() const;+ bool remoteMinimized() const { return m_showState == 0x02; }++ // A loading window (boards 9.11 to 9.13).+ void startLoading(const QString &title, const QIcon &icon, const QSize &size);+ void stopLoading();+ void setLoadingStage(LoadingView::Stage stage);+ void setLoadingEnded();+ void setLoadingReason(const QString &reason, int percent, const QString &progress);+ // Hands the window over to Windows window `id`. It keeps showing the+ // loading mark until the first picture of the app arrives.+ void adopt(quint32 id);+ // The window it took turned out not to be the app's: back to waiting.+ void unadopt();+ // Once adopted and placed: asks Windows for the app at this window's+ // size, and starts the closing sequence when it arrives.+ void beginHandoff();++ void setRemoteState(quint32 id, quint32 style, quint32 exStyle, bool popup);+ void setOwner(quint32 owner) { m_owner = owner; }+ void setFrame(const QRect &frame);+ void setShowState(quint32 state);+ void setRemoteTitle(const QString &title);+ void setIcon(const QImage &image, bool big);+ void setAppId(const QString &appId);+ void setMinMax(const QSize &minTrack, const QSize &maxTrack);++ void surfaceDamaged(quint16 surfaceId, const QRegion &damage, const QSize &size);+ void primaryDamaged(const QRegion &desktopDamage);+ // Windows started moving or sizing the window from its own title bar or+ // edge; the compositor takes over until the button is let go.+ void beginLocalMoveSize(quint16 type);+ void endLocalMoveSize();++ // The window's size in device pixels for a size in Windows' pixels.+ QSize logicalSize(const QSize &remote) const;+ // The window's pixels as Windows last sent them.+ QImage snapshot() const;+ // The loading window as it looks now.+ QImage loadingSnapshot(qreal dpr) const;++protected:+ bool event(QEvent *event) override;+ void exposeEvent(QExposeEvent *event) override;+ void resizeEvent(QResizeEvent *event) override;+ void mousePressEvent(QMouseEvent *event) override;+ void mouseReleaseEvent(QMouseEvent *event) override;+ void mouseMoveEvent(QMouseEvent *event) override;+ void mouseDoubleClickEvent(QMouseEvent *event) override;+ void wheelEvent(QWheelEvent *event) override;+ void keyPressEvent(QKeyEvent *event) override;+ void keyReleaseEvent(QKeyEvent *event) override;+ void focusInEvent(QFocusEvent *event) override;+ void focusOutEvent(QFocusEvent *event) override;++private:+ void render();+ void renderLoading();+ void paintLoading(QPainter &p) const;+ void loadingPress(QMouseEvent *event);+ void appReady();+ // The app's window has drawn (at this size, in Windows' pixels).+ void handoffContent(const QSize &drawn);+ // The loading window's size changes about its centre, through KWin.+ void resizeAroundCentre(const QSize &to);+ // The size the window is on its way to, or has.+ QSize intendedSize() const;+ void renderRemote();+ QPoint toRemote(const QPointF &local) const;+ void sendButton(QMouseEvent *event, bool down);+ void releaseKeys();+ void sendIcon();+ void finishMoveSize(const QPointF &local);+ double scale() const;++ Rail *m_rail;+ Client *m_client;+ QString m_appId;+ std::unique_ptr<QBackingStore> m_store;++ quint32 m_id = 0;+ quint32 m_style = 0;+ quint32 m_exStyle = 0;+ quint32 m_owner = 0;+ quint32 m_showState = 0x05;+ bool m_popup = false;+ bool m_layered = false;+ // A popup's own transparency, looked at once in its first picture.+ bool m_alpha = false;+ bool m_alphaChecked = false;+ QRect m_frame;++ // Pixels: the window's surface in the graphics pipeline, or its part+ // of the whole desktop picture when the server draws without one.+ quint16 m_surfaceId = 0;+ bool m_hasSurface = false;+ QSize m_surfaceSize;+ QRegion m_damage;+ bool m_primary = false;+ bool m_hasContent = false;+ bool m_updateQueued = false;++ // Loading.+ bool m_loading = false;+ bool m_loadingPainted = false;+ bool m_fullRepaint = true;+ bool m_wasSlow = false;+ LoadingView m_view;+ QTimer m_handoffTimer;+ QSize m_handoffSize;+ // Windows was asked to resize the app to this window.+ bool m_handoffResizing = false;+ QSize m_targetSize;+ QImage m_loadingBackground;+ QImage m_remoteIcon;+ bool m_iconSent = false;++ // Input.+ QList<quint32> m_keysDown;+ int m_wheelX = 0;+ int m_wheelY = 0;+ bool m_moveSize = false;+ quint16 m_moveSizeType = 0;+ QPoint m_pressRemote;+ QRect m_moveSizeStart;+};diff --git a/packages/wildos-rdp/src/selftest.cpp b/packages/wildos-rdp/src/selftest.cppnew file mode 100644index 0000000..bf8f6d3--- /dev/null+++ b/packages/wildos-rdp/src/selftest.cpp@@ -0,0 +1,160 @@+#include "selftest.h"+#include "client.h"+#include "rail.h"+#include "railwindow.h"++#include <QCoreApplication>+#include <QDir>+#include <QGuiApplication>+#include <QKeyEvent>+#include <QMouseEvent>+#include <QPointer>+#include <QTimer>++#include <memory>+#include <utility>++namespace+{+// US positions of the characters the test types, as Linux key codes.+int evdevFor(QChar c, bool *shift)+{+ static const char *rows[] = {"qwertyuiop", "asdfghjkl", "zxcvbnm"};+ static const int starts[] = {16, 30, 44};+ *shift = c.isUpper();+ const char l = char(c.toLower().unicode());+ for (int r = 0; r < 3; ++r) {+ for (int i = 0; rows[r][i]; ++i) {+ if (rows[r][i] == l) {+ return starts[r] + i;+ }+ }+ }+ if (l >= '1' && l <= '9') {+ return 2 + (l - '1');+ }+ switch (l) {+ case '0': return 11;+ case ' ': return 57;+ case '\n': return 28;+ case '.': return 52;+ case ',': return 51;+ case '-': return 12;+ default: return 0;+ }+}++void key(QWindow *w, int evdev, bool down)+{+ QKeyEvent e(down ? QEvent::KeyPress : QEvent::KeyRelease, 0, Qt::NoModifier, quint32(evdev + 8), 0, 0);+ QCoreApplication::sendEvent(w, &e);+}+}++void startSelfTest(Rail *rail, Client *client)+{+ const QString text = qEnvironmentVariable("WILDOS_RDP_TEST_TYPE");+ const QString click = qEnvironmentVariable("WILDOS_RDP_TEST_CLICK");+ const QString dump = qEnvironmentVariable("WILDOS_RDP_TEST_DUMP");+ const int quit = qEnvironmentVariableIntValue("WILDOS_RDP_TEST_QUIT");+ if (text.isEmpty() && click.isEmpty() && dump.isEmpty()) {+ return;+ }+ if (!dump.isEmpty()) {+ // The loading window every quarter of a second while it is up, at+ // a 4K laptop's 2.25 scale.+ QObject::connect(rail, &Rail::loadingVisible, rail, [=](quint32 token) {+ QDir().mkpath(dump);+ auto *frames = new QTimer(rail);+ auto count = std::make_shared<int>(0);+ QObject::connect(frames, &QTimer::timeout, rail, [=] {+ RailWindow *w = rail->loadingWindow(token);+ if (!w || !w->loading() || ++*count > 120) {+ frames->deleteLater();+ return;+ }+ w->loadingSnapshot(1.5).save(dump + QStringLiteral("/loading-%1-%2.png").arg(token).arg(*count, 3, 10, QLatin1Char('0')));+ });+ frames->start(250);+ });+ }+ QObject::connect(rail, &Rail::windowShown, rail, [=](quint32 id) {+ static bool started = false;+ if (started) {+ return;+ }+ started = true;+ // Long enough for the app to finish drawing and take the keyboard.+ QTimer::singleShot(2500, rail, [=] {+ QPointer<RailWindow> w = rail->window(id);+ if (!w) {+ return;+ }+ if (!click.isEmpty()) {+ const QPointF at(click.section(u',', 0, 0).toDouble(), click.section(u',', 1, 1).toDouble());+ QMouseEvent press(QEvent::MouseButtonPress, at, w->mapToGlobal(at), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);+ QCoreApplication::sendEvent(w, &press);+ QMouseEvent release(QEvent::MouseButtonRelease, at, w->mapToGlobal(at), Qt::LeftButton, Qt::NoButton, Qt::NoModifier);+ QCoreApplication::sendEvent(w, &release);+ }+ // At a quick typist's pace, one key every 30 ms; <ctrl+c> is a+ // chord with Ctrl, <wait> a pause of half a second.+ int at = 0;+ for (qsizetype i = 0; i < text.size(); ++i) {+ bool shift = false;+ bool ctrl = false;+ int code = 0;+ if (text[i] == u'<' && text.indexOf(u'>', i) > i) {+ const qsizetype end = text.indexOf(u'>', i);+ const QString token = text.mid(i + 1, end - i - 1);+ i = end;+ if (token == QLatin1String("wait")) {+ at += 16;+ continue;+ }+ ctrl = token.startsWith(QLatin1String("ctrl+"));+ code = evdevFor(token.back(), &shift);+ } else {+ code = evdevFor(text[i], &shift);+ }+ if (!code) {+ continue;+ }+ QTimer::singleShot(30 * at++, rail, [w, code, shift, ctrl] {+ if (!w) {+ return;+ }+ for (const auto &[held, mod] : {std::pair{ctrl, 29}, std::pair{shift, 42}}) {+ if (held) {+ key(w, mod, true);+ }+ }+ key(w, code, true);+ key(w, code, false);+ for (const auto &[held, mod] : {std::pair{shift, 42}, std::pair{ctrl, 29}}) {+ if (held) {+ key(w, mod, false);+ }+ }+ });+ }+ QTimer::singleShot(1500 + 30 * at, rail, [=] {+ if (!dump.isEmpty()) {+ QDir().mkpath(dump);+ for (quint32 other : rail->windowIds()) {+ if (RailWindow *rw = rail->window(other); rw && rw->isVisible()) {+ const QImage image = rw->snapshot();+ if (!image.isNull()) {+ image.save(dump + QStringLiteral("/%1.png").arg(other, 8, 16, QLatin1Char('0')));+ }+ }+ }+ qInfo("wildos-rdp: test pictures in %s", qPrintable(dump));+ }+ if (quit > 0) {+ QTimer::singleShot(quit * 1000, rail, [client] { client->stop(); });+ }+ });+ });+ });+}diff --git a/packages/wildos-rdp/src/selftest.h b/packages/wildos-rdp/src/selftest.hnew file mode 100644index 0000000..2fc75f5--- /dev/null+++ b/packages/wildos-rdp/src/selftest.h@@ -0,0 +1,16 @@+#pragma once++class Rail;+class Client;++// For the automated Windows mode test (docs/windows-mode-plan.md,+// Hardening): driven by environment variables, it types into and clicks+// the first app window through the same input path a person's keyboard+// and mouse take, and saves each window's pixels as Windows sent them.+//+// WILDOS_RDP_TEST_TYPE text to type once the first window has drawn;+// <ctrl+v> is a chord, <wait> half a second+// WILDOS_RDP_TEST_CLICK x,y in the window to click before typing+// WILDOS_RDP_TEST_DUMP folder for <window id>.png, written after typing+// WILDOS_RDP_TEST_QUIT seconds after typing to end the session+void startSelfTest(Rail *rail, Client *client);diff --git a/packages/wildos-rdp/src/service.cpp b/packages/wildos-rdp/src/service.cppnew file mode 100644index 0000000..8202876--- /dev/null+++ b/packages/wildos-rdp/src/service.cpp@@ -0,0 +1,101 @@+#include "service.h"+#include "client.h"+#include "rail.h"+#include "railwindow.h"++#include <QDBusConnection>+#include <QJsonArray>+#include <QJsonDocument>+#include <QJsonObject>++#include <algorithm>++#include <freerdp/rail.h>++Service::Service(Rail *rail, Client *client, QObject *parent)+ : QObject(parent)+ , m_rail(rail)+ , m_client(client)+{+ connect(rail, &Rail::windowShown, this, [this](quint32 id, const QString &title) { Q_EMIT WindowAdded(id, title); });+ connect(rail, &Rail::windowGone, this, [this](quint32 id) { Q_EMIT WindowRemoved(id); });+ connect(rail, &Rail::loadingVisible, this, [this](quint32 token, qint64 ms) { Q_EMIT LoadingShown(token, uint(ms)); });+ connect(rail, &Rail::closeStalled, this, [this](quint32 id, quint32 pid, const QString &program) { Q_EMIT CloseStalled(id, pid, program); });+ connect(rail, &Rail::loadingDetails, this, [this](quint32 token) { Q_EMIT DetailsRequested(token); });+ connect(rail, &Rail::loadingRetry, this, [this](quint32 token) { Q_EMIT RetryRequested(token); });+ connect(rail, &Rail::loadingFinished, this, [this](quint32 token, const QString &reason, quint32 id) { Q_EMIT LoadingFinished(token, reason, id); });+ connect(client, &Client::connected, this, [this] {+ m_connected = true;+ Q_EMIT Connected();+ });+ connect(client, &Client::finished, this, [this](const QString &error, bool authFailed) {+ m_connected = false;+ Q_EMIT Disconnected(error, authFailed);+ });+}++bool Service::registerOnBus()+{+ QDBusConnection bus = QDBusConnection::sessionBus();+ if (!bus.isConnected()) {+ return false;+ }+ if (!bus.registerObject(QStringLiteral("/org/wildos/RemoteApp"), this, QDBusConnection::ExportAllSlots | QDBusConnection::ExportAllSignals)) {+ return false;+ }+ // A second session (Windows' whole desktop, say) leaves the name to the+ // first; the agent talks to the one that has it.+ return bus.registerService(QStringLiteral("org.wildos.RemoteApp"));+}++uint Service::Prepare(const QString &appId, const QString &title, const QString &icon, const QString &program, uint delayMs)+{+ return m_rail->prepare(appId, title, icon, program, int(std::min(delayMs, 5000u)));+}++bool Service::Update(uint token, const QString &stage, const QString &reason, int percent, const QString &progress)+{+ return m_rail->update(token, stage, reason, std::clamp(percent, -1, 100), progress);+}++bool Service::Cancel(uint token)+{+ return m_rail->cancel(token, QStringLiteral("cancelled"));+}++void Service::SetWindowApp(qulonglong windowId, const QString &appId)+{+ m_rail->setWindowApp(quint32(windowId), appId);+}++void Service::CloseWindow(qulonglong windowId)+{+ m_client->sysCommand(quint32(windowId), SC_CLOSE);+}++void Service::Disconnect()+{+ m_client->stop();+}++QString Service::Status()+{+ QJsonArray windows;+ for (quint32 id : m_rail->windowIds()) {+ RailWindow *w = m_rail->window(id);+ windows.append(QJsonObject{{QStringLiteral("id"), qint64(id)}, {QStringLiteral("app"), w ? w->appId() : QString()},+ {QStringLiteral("visible"), w && w->isVisible()}});+ }+ return QString::fromUtf8(+ QJsonDocument(QJsonObject{{QStringLiteral("connected"), m_connected}, {QStringLiteral("windows"), windows}}).toJson(QJsonDocument::Compact));+}++QString Service::Placements()+{+ return QString::fromUtf8(QJsonDocument(Rail::placements()).toJson(QJsonDocument::Compact));+}++void Service::SavePlacement(const QString &appId, double x, double y)+{+ Rail::savePlacement(appId, QPoint(qRound(x), qRound(y)));+}diff --git a/packages/wildos-rdp/src/service.h b/packages/wildos-rdp/src/service.hnew file mode 100644index 0000000..1f7ea94--- /dev/null+++ b/packages/wildos-rdp/src/service.h@@ -0,0 +1,70 @@+#pragma once++#include <QObject>+#include <QString>++class Rail;+class Client;++// org.wildos.RemoteApp on the session bus, for the Windows mode agent:+// it shows a loading window the moment an app is asked for, tells the+// windows which app they belong to, and hears what happened to both.+class Service : public QObject+{+ Q_OBJECT+ Q_CLASSINFO("D-Bus Interface", "org.wildos.RemoteApp")++public:+ Service(Rail *rail, Client *client, QObject *parent = nullptr);+ bool registerOnBus();++ void setConnected(bool connected) { m_connected = connected; }++public Q_SLOTS:+ // Shows the loading window for an app; returns a token for it. With a+ // delay it only shows if the app has not opened by then (board 9.12:+ // no loader for an app that opens in under half a second).+ // `program` is the app's program as Windows names it (a path or file+ // name), which tells its windows from every other.+ uint Prepare(const QString &appId, const QString &title, const QString &icon, const QString &program, uint delayMs);+ // Stage "almost" once the app's process is up; a reason in plain words+ // for board 9.13, with percent -1 when there is nothing to measure.+ bool Update(uint token, const QString &stage, const QString &reason, int percent, const QString &progress);+ // Closes a loading window that is still waiting; false if it is not.+ bool Cancel(uint token);+ // The app a Windows window belongs to (its taskbar group).+ void SetWindowApp(qulonglong windowId, const QString &appId);+ // Closes a Windows window as its own close button does (Windows asks+ // about unsaved work first, as it always does).+ void CloseWindow(qulonglong windowId);+ // Ends the session.+ void Disconnect();+ // {"connected": bool, "windows": [{"id": n, "app": s, "visible": b}]}+ QString Status();+ // Where each app's window was last, for the org.wildos.rdp.place KWin+ // script: {"wildos-winmode-word": {"x": n, "y": n}}.+ QString Placements();+ // Doubles: the KWin script's numbers are JavaScript's, and D-Bus only+ // delivers a call whose argument types match exactly.+ void SavePlacement(const QString &appId, double x, double y);++Q_SIGNALS:+ void WindowAdded(qulonglong windowId, const QString &title);+ void WindowRemoved(qulonglong windowId);+ void LoadingShown(uint token, uint milliseconds);+ void LoadingFinished(uint token, const QString &reason, qulonglong windowId);+ // "Show details" on a loading window that is taking longer.+ void DetailsRequested(uint token);+ // Try again on a loading window whose app ended before it opened.+ void RetryRequested(uint token);+ // A window closed here that Windows did not close, with nothing unsaved+ // in it: the agent ends its program (`pid`, image `program`).+ void CloseStalled(qulonglong windowId, uint pid, const QString &program);+ void Connected();+ void Disconnected(const QString &error, bool authFailed);++private:+ Rail *m_rail;+ Client *m_client;+ bool m_connected = false;+};diff --git a/packages/wildos-rdp/src/style.cpp b/packages/wildos-rdp/src/style.cppnew file mode 100644index 0000000..d4cc925--- /dev/null+++ b/packages/wildos-rdp/src/style.cpp@@ -0,0 +1,99 @@+#include "style.h"++#include <KConfigGroup>+#include <KSharedConfig>++#include <QFile>+#include <QJsonDocument>+#include <QJsonObject>+#include <QStandardPaths>++#include <algorithm>++namespace+{+const QColor glacier(0x8f, 0xb4, 0xff);+const QColor darkReference = QColor::fromRgbF(18 / 255.0, 22 / 255.0, 40 / 255.0, 0.86);+const QColor lightReference = QColor::fromRgbF(250 / 255.0, 251 / 255.0, 254 / 255.0, 0.82);++QColor parseColour(const QString &value)+{+ const QStringList parts = value.split(QLatin1Char(','));+ if (parts.size() >= 3) {+ return QColor(parts[0].trimmed().toInt(), parts[1].trimmed().toInt(), parts[2].trimmed().toInt());+ }+ return value.isEmpty() ? QColor() : QColor(value);+}++QColor jsonColour(const QJsonValue &value)+{+ if (value.isString()) {+ return QColor(value.toString());+ }+ const QJsonObject object = value.toObject();+ QColor colour(object.value(QStringLiteral("colour")).toString());+ if (colour.isValid()) {+ colour.setAlphaF(object.value(QStringLiteral("alpha")).toDouble(1.0));+ }+ return colour;+}++// Style.tinted: each channel scaled by the theme's share of the reference+// glass, the alpha moved by the theme's difference.+QColor tinted(const QColor &tint, const QColor &ref, int r, int g, int b, double a)+{+ return QColor::fromRgbF(std::min(1.0, r / 255.0 * tint.redF() / ref.redF()), std::min(1.0, g / 255.0 * tint.greenF() / ref.greenF()),+ std::min(1.0, b / 255.0 * tint.blueF() / ref.blueF()),+ std::clamp(a + tint.alphaF() - ref.alphaF(), 0.0, 1.0));+}+}++Style Style::read()+{+ Style s;+ KSharedConfigPtr globals = KSharedConfig::openConfig(QStringLiteral("kdeglobals"));+ const KConfigGroup general = globals->group(QStringLiteral("General"));+ s.accent = parseColour(general.readEntry("AccentColor"));+ if (!s.accent.isValid()) {+ s.accent = glacier;+ }+ const QString scheme = general.readEntry("ColorScheme", QStringLiteral("WildOS"));+ const QColor window = parseColour(globals->group(QStringLiteral("Colors:Window")).readEntry("BackgroundNormal"));+ s.contrast = scheme == QLatin1String("WildOSHighContrast");+ if (s.contrast) {+ s.dark = true;+ } else if (window.isValid()) {+ s.dark = window.lightnessF() < 0.5;+ } else {+ s.dark = !scheme.contains(QLatin1String("Light"));+ }+ s.reducedMotion = globals->group(QStringLiteral("KDE")).readEntry("AnimationDurationFactor", 1.0) <= 0.0;++ const QString id = KSharedConfig::openConfig(QStringLiteral("wildosrc"))->group(QStringLiteral("Theme")).readEntry("Id", QStringLiteral("dawn"));+ QJsonObject theme;+ const QString path = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("wildos/themes/%1.json").arg(id));+ QFile file(path);+ if (!path.isEmpty() && file.open(QIODevice::ReadOnly)) {+ theme = QJsonDocument::fromJson(file.readAll()).object();+ }+ const QString mode = theme.value(QStringLiteral("mode")).toString();+ const QColor themeGlass = jsonColour(theme.value(QStringLiteral("glass")));+ const QColor ref = s.dark ? darkReference : lightReference;+ const bool themed = !s.contrast && !mode.isEmpty() && (mode == QLatin1String("dark")) == s.dark && themeGlass.isValid();+ const QColor tint = themed ? themeGlass : ref;++ if (s.contrast) {+ s.glass = Qt::black;+ s.border = Qt::white;+ s.ink = Qt::white;+ } else if (s.dark) {+ s.glass = tinted(tint, ref, 20, 24, 42, 0.80);+ s.border = QColor::fromRgbF(1, 1, 1, 0.12);+ s.ink = QColor(0xee, 0xf1, 0xf8);+ } else {+ s.glass = tinted(tint, ref, 250, 251, 254, 0.92);+ s.border = QColor::fromRgbF(30 / 255.0, 40 / 255.0, 70 / 255.0, 0.12 * 0.75);+ s.ink = QColor(0x15, 0x1b, 0x2c);+ }+ return s;+}diff --git a/packages/wildos-rdp/src/style.h b/packages/wildos-rdp/src/style.hnew file mode 100644index 0000000..bbd266c--- /dev/null+++ b/packages/wildos-rdp/src/style.h@@ -0,0 +1,19 @@+#pragma once++#include <QColor>++// The few WildOS.UI tokens the loading window needs, read the way+// wildos-ui's Theme reads them (kdeglobals, wildosrc and the theme's JSON),+// so the window matches the rest of the desktop without loading QML.+struct Style {+ bool dark = true;+ bool contrast = false;+ bool reducedMotion = false;+ // Style.glassWindow, Style.borderGlass and Style.ink.+ QColor glass;+ QColor border;+ QColor ink;+ QColor accent;++ static Style read();+};diff --git a/packages/wildos-rdp/src/wayland.cpp b/packages/wildos-rdp/src/wayland.cppnew file mode 100644index 0000000..3b4e493--- /dev/null+++ b/packages/wildos-rdp/src/wayland.cpp@@ -0,0 +1,120 @@+#include "wayland.h"++#include <QGuiApplication>+#include <QPainter>+#include <QWindow>+#include <qpa/qplatformnativeinterface.h>++#include <wayland-client.h>++#include "xdg-shell-client-protocol.h"+#include "xdg-toplevel-icon-v1-client-protocol.h"++#include <cstring>+#include <sys/mman.h>+#include <unistd.h>++WaylandExtras &WaylandExtras::instance()+{+ static WaylandExtras extras;+ return extras;+}++WaylandExtras::WaylandExtras()+{+ auto *app = qGuiApp->nativeInterface<QNativeInterface::QWaylandApplication>();+ if (!app || !app->display()) {+ return;+ }+ static const wl_registry_listener listener = {global, globalRemove};+ m_registry = wl_display_get_registry(app->display());+ wl_registry_add_listener(m_registry, &listener, this);+ wl_display_roundtrip(app->display());+}++void WaylandExtras::global(void *data, wl_registry *registry, uint32_t name, const char *interface, uint32_t)+{+ auto *self = static_cast<WaylandExtras *>(data);+ if (std::strcmp(interface, xdg_toplevel_icon_manager_v1_interface.name) == 0) {+ self->m_icons = static_cast<xdg_toplevel_icon_manager_v1 *>(wl_registry_bind(registry, name, &xdg_toplevel_icon_manager_v1_interface, 1));+ } else if (std::strcmp(interface, wl_shm_interface.name) == 0) {+ self->m_shm = static_cast<wl_shm *>(wl_registry_bind(registry, name, &wl_shm_interface, 1));+ }+}++void WaylandExtras::globalRemove(void *, wl_registry *, uint32_t)+{+}++void *WaylandExtras::toplevel(QWindow *window) const+{+ QPlatformNativeInterface *native = QGuiApplication::platformNativeInterface();+ if (!native || !window || !window->handle()) {+ return nullptr;+ }+ return native->nativeResourceForWindow(QByteArrayLiteral("xdg_toplevel"), window);+}++bool WaylandExtras::setAppId(QWindow *window, const QString &appId)+{+ auto *top = static_cast<xdg_toplevel *>(toplevel(window));+ if (!top) {+ return false;+ }+ xdg_toplevel_set_app_id(top, appId.toUtf8().constData());+ return true;+}++bool WaylandExtras::setIcon(QWindow *window, const QImage &icon)+{+ auto *top = static_cast<xdg_toplevel *>(toplevel(window));+ if (!top || !m_icons || !m_shm || icon.isNull()) {+ return false;+ }+ // The protocol takes square pictures only: the icon is centred in one.+ const int side = std::max(icon.width(), icon.height());+ QImage square(side, side, QImage::Format_ARGB32_Premultiplied);+ square.fill(Qt::transparent);+ {+ QPainter p(&square);+ p.drawImage(QPoint((side - icon.width()) / 2, (side - icon.height()) / 2), icon);+ }+ const int stride = int(square.bytesPerLine());+ const size_t bytes = size_t(stride) * side;+ const int fd = memfd_create("wildos-rdp-icon", MFD_CLOEXEC);+ if (fd < 0) {+ return false;+ }+ if (ftruncate(fd, off_t(bytes)) != 0) {+ close(fd);+ return false;+ }+ void *map = mmap(nullptr, bytes, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);+ if (map == MAP_FAILED) {+ close(fd);+ return false;+ }+ std::memcpy(map, square.constBits(), bytes);+ munmap(map, bytes);+ wl_shm_pool *pool = wl_shm_create_pool(m_shm, fd, int32_t(bytes));+ wl_buffer *buffer = wl_shm_pool_create_buffer(pool, 0, side, side, stride, WL_SHM_FORMAT_ARGB8888);+ wl_shm_pool_destroy(pool);+ close(fd);++ xdg_toplevel_icon_v1 *handle = xdg_toplevel_icon_manager_v1_create_icon(m_icons);+ xdg_toplevel_icon_v1_add_buffer(handle, buffer, 1);+ xdg_toplevel_icon_manager_v1_set_icon(m_icons, top, handle);+ xdg_toplevel_icon_v1_destroy(handle);++ if (wl_buffer *old = m_buffers.take(window)) {+ wl_buffer_destroy(old);+ } else {+ QObject::connect(window, &QObject::destroyed, window, [this, window] {+ if (wl_buffer *b = m_buffers.take(window)) {+ wl_buffer_destroy(b);+ }+ });+ }+ m_buffers.insert(window, buffer);+ return true;+}diff --git a/packages/wildos-rdp/src/wayland.h b/packages/wildos-rdp/src/wayland.hnew file mode 100644index 0000000..811f715--- /dev/null+++ b/packages/wildos-rdp/src/wayland.h@@ -0,0 +1,41 @@+#pragma once++#include <QHash>+#include <QImage>+#include <QPointer>+#include <QString>++class QWindow;+struct wl_buffer;+struct wl_registry;+struct wl_shm;+struct xdg_toplevel_icon_manager_v1;++// What Qt 6.8 does not do for a Wayland window and Windows apps need:+// changing a window's app id while it is on screen (it moves to its app's+// taskbar group without being shown again), and giving it its own icon+// (xdg-toplevel-icon), so a Windows app the desktop has no entry for shows+// the icon Windows sends rather than a generic one.+class WaylandExtras+{+public:+ static WaylandExtras &instance();++ // Both work only while the window is shown; false when the compositor+ // or the window cannot take them.+ bool setAppId(QWindow *window, const QString &appId);+ bool setIcon(QWindow *window, const QImage &icon);++private:+ WaylandExtras();+ void *toplevel(QWindow *window) const;++ static void global(void *data, wl_registry *registry, uint32_t name, const char *interface, uint32_t version);+ static void globalRemove(void *data, wl_registry *registry, uint32_t name);++ wl_registry *m_registry = nullptr;+ wl_shm *m_shm = nullptr;+ xdg_toplevel_icon_manager_v1 *m_icons = nullptr;+ // The buffer behind each window's icon, kept until it is replaced.+ QHash<QWindow *, wl_buffer *> m_buffers;+};diff --git a/packages/wildos-remote/CMakeLists.txt b/packages/wildos-remote/CMakeLists.txtnew file mode 100644index 0000000..0fa9813--- /dev/null+++ b/packages/wildos-remote/CMakeLists.txt@@ -0,0 +1,92 @@+cmake_minimum_required(VERSION 3.25)+project(wildos-remote VERSION 0.1.0 LANGUAGES C CXX)++set(CMAKE_CXX_STANDARD 20)+set(CMAKE_CXX_STANDARD_REQUIRED ON)+include(GNUInstallDirs)++find_package(Qt6 6.8 REQUIRED COMPONENTS Core Gui Widgets DBus Network Qml Quick QuickWidgets QuickControls2)+# Qt6::GuiPrivate only for QPlatformNativeInterface: the wl_surface behind a+# window, which Qt 6.8 offers no public way to reach.+find_package(Qt6Keychain REQUIRED)+find_package(qtermwidget6 REQUIRED)+find_package(KF6WindowSystem REQUIRED)++# The Remote Desktop engine Windows mode draws its apps with. The package+# build copies it in beside this file (build/build.sh); a build from the+# source tree reaches it next door.+if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/rdp-engine/engine.cmake)+ set(WILDOS_RDP_DIR ${CMAKE_CURRENT_SOURCE_DIR}/rdp-engine)+else()+ set(WILDOS_RDP_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../wildos-rdp)+endif()+include(${WILDOS_RDP_DIR}/engine.cmake)++# "Send all shortcuts there" asks KWin through this protocol.+pkg_check_modules(WAYLAND REQUIRED IMPORTED_TARGET wayland-client)+pkg_get_variable(WAYLAND_PROTOCOLS wayland-protocols pkgdatadir)+find_program(WAYLAND_SCANNER wayland-scanner REQUIRED)+set(INHIBIT_XML ${WAYLAND_PROTOCOLS}/unstable/keyboard-shortcuts-inhibit/keyboard-shortcuts-inhibit-unstable-v1.xml)+add_custom_command(+ OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/keyboard-shortcuts-inhibit-unstable-v1-client-protocol.h+ ${CMAKE_CURRENT_BINARY_DIR}/keyboard-shortcuts-inhibit-unstable-v1-protocol.c+ COMMAND ${WAYLAND_SCANNER} client-header ${INHIBIT_XML} ${CMAKE_CURRENT_BINARY_DIR}/keyboard-shortcuts-inhibit-unstable-v1-client-protocol.h+ COMMAND ${WAYLAND_SCANNER} private-code ${INHIBIT_XML} ${CMAKE_CURRENT_BINARY_DIR}/keyboard-shortcuts-inhibit-unstable-v1-protocol.c+ DEPENDS ${INHIBIT_XML})++qt_standard_project_setup(REQUIRES 6.8)++qt_add_executable(wildos-remote src/main.cpp)+target_compile_definitions(wildos-remote PRIVATE+ WILDOS_REMOTE_VERSION="${PROJECT_VERSION}"+ WILDOS_REMOTE_DATADIR="${CMAKE_INSTALL_FULL_DATADIR}/wildos-remote"+ WILDOS_REMOTE_SOURCEDIR="${CMAKE_CURRENT_SOURCE_DIR}/data")++file(GLOB QML_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} qml/*.qml)+set_source_files_properties(qml/RemoteIcons.qml PROPERTIES QT_QML_SINGLETON_TYPE TRUE)+foreach(file ${QML_SOURCES})+ get_filename_component(name ${file} NAME)+ set_source_files_properties(${file} PROPERTIES QT_RESOURCE_ALIAS ${name})+endforeach()++qt_add_qml_module(wildos-remote+ URI WildOS.Remote+ QML_FILES ${QML_SOURCES}+ RESOURCES data/org.wildos.remote.svg+ SOURCES+ src/app.cpp src/app.h+ src/askpass.cpp src/askpass.h+ src/desktopview.cpp src/desktopview.h+ src/filebrowser.cpp src/filebrowser.h+ src/hostkeys.cpp src/hostkeys.h+ src/hosts.cpp src/hosts.h+ src/keychain.cpp src/keychain.h+ src/notify.cpp src/notify.h+ src/paths.h+ src/remotedesktop.cpp src/remotedesktop.h+ src/secrets.cpp src/secrets.h+ src/sessionwindow.cpp src/sessionwindow.h+ src/sftp.cpp src/sftp.h+ src/shortcuts.cpp src/shortcuts.h+ src/snippets.cpp src/snippets.h+ src/terminalview.cpp src/terminalview.h+ src/windowframe.cpp src/windowframe.h+ ${CMAKE_CURRENT_BINARY_DIR}/keyboard-shortcuts-inhibit-unstable-v1-client-protocol.h+ ${CMAKE_CURRENT_BINARY_DIR}/keyboard-shortcuts-inhibit-unstable-v1-protocol.c+)++target_include_directories(wildos-remote PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src ${CMAKE_CURRENT_BINARY_DIR})++target_link_libraries(wildos-remote PRIVATE+ wildos-rdp-engine+ Qt6::GuiPrivate PkgConfig::WAYLAND+ Qt6::Widgets Qt6::DBus Qt6::Network Qt6::Qml Qt6::Quick Qt6::QuickWidgets Qt6::QuickControls2+ qt6keychain+ qtermwidget6+ KF6::WindowSystem+)++install(TARGETS wildos-remote RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})+install(FILES data/org.wildos.remote.desktop DESTINATION ${CMAKE_INSTALL_DATADIR}/applications)+install(FILES data/org.wildos.remote.svg DESTINATION ${CMAKE_INSTALL_DATADIR}/icons/hicolor/scalable/apps)+install(FILES data/Remote.colorscheme DESTINATION ${CMAKE_INSTALL_DATADIR}/wildos-remote)diff --git a/packages/wildos-remote/data/Remote.colorscheme b/packages/wildos-remote/data/Remote.colorschemenew file mode 100644index 0000000..66b33f7--- /dev/null+++ b/packages/wildos-remote/data/Remote.colorscheme@@ -0,0 +1,64 @@+[Background]+Color=11,15,28++[BackgroundIntense]+Color=11,15,28++[Color0]+Color=29,34,56++[Color0Intense]+Color=74,82,114++[Color1]+Color=255,154,138++[Color1Intense]+Color=255,180,168++[Color2]+Color=95,211,154++[Color2Intense]+Color=136,228,182++[Color3]+Color=255,196,106++[Color3Intense]+Color=255,214,150++[Color4]+Color=143,180,255++[Color4Intense]+Color=177,204,255++[Color5]+Color=199,139,255++[Color5Intense]+Color=216,176,255++[Color6]+Color=110,224,208++[Color6Intense]+Color=158,236,224++[Color7]+Color=215,222,239++[Color7Intense]+Color=255,255,255++[Foreground]+Color=215,222,239++[ForegroundIntense]+Bold=true+Color=255,255,255++[General]+Description=Wild OS Remote+Opacity=1diff --git a/packages/wildos-remote/data/org.wildos.remote.desktop b/packages/wildos-remote/data/org.wildos.remote.desktopnew file mode 100644index 0000000..9a5b515--- /dev/null+++ b/packages/wildos-remote/data/org.wildos.remote.desktop@@ -0,0 +1,13 @@+[Desktop Entry]+Type=Application+Name=Remote+GenericName=Remote desktop and SSH+Comment=Connect to other PCs and servers+Exec=wildos-remote %u+Icon=org.wildos.remote+Terminal=false+StartupNotify=true+StartupWMClass=wildos-remote+Categories=Qt;Network;RemoteAccess;+MimeType=x-scheme-handler/rdp;x-scheme-handler/ssh;application/x-rdp;+Keywords=remote desktop;rdp;ssh;sftp;terminal;server;mstsc;putty;diff --git a/packages/wildos-remote/data/org.wildos.remote.svg b/packages/wildos-remote/data/org.wildos.remote.svgnew file mode 100644index 0000000..38e26c1--- /dev/null+++ b/packages/wildos-remote/data/org.wildos.remote.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256"><defs><filter id="rs" x="-25%" y="-25%" width="150%" height="150%"><feDropShadow dx="0" dy="7" stdDeviation="8" flood-color="#060c2a" flood-opacity="0.35"/></filter><linearGradient id="rt" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#ffc25a"/><stop offset="1" stop-color="#e2700f"/></linearGradient><linearGradient id="rg" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#fff" stop-opacity="0.22"/><stop offset="0.55" stop-color="#fff" stop-opacity="0"/></linearGradient><linearGradient id="rm" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#fff6e8"/><stop offset="1" stop-color="#ffe1b8"/></linearGradient><linearGradient id="rc" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#ffd9a0"/><stop offset="1" stop-color="#f6b25e"/></linearGradient></defs><g filter="url(#rs)"><rect x="160" y="196" width="44" height="22" rx="6" fill="#f0c48a"/><rect x="128" y="214" width="108" height="16" rx="8" fill="url(#rm)"/><rect x="72" y="40" width="168" height="166" rx="24" fill="url(#rm)"/></g><rect x="88" y="56" width="136" height="118" rx="12" fill="url(#rc)" opacity="0.55"/><rect x="150" y="72" width="58" height="10" rx="5" fill="#ffffff" opacity="0.8"/><rect x="150" y="92" width="44" height="10" rx="5" fill="#ffffff" opacity="0.8"/><g filter="url(#rs)"><rect x="14" y="70" width="124" height="124" rx="30" fill="url(#rt)"/><rect x="14" y="70" width="124" height="124" rx="30" fill="url(#rg)"/><rect x="15.5" y="71.5" width="121" height="121" rx="28" fill="none" stroke="#fff" stroke-opacity="0.18" stroke-width="2"/><path d="M58.0 98.7 L58.0 157.9 L74.6 142.4 L85.3 165.3 L95.7 160.9 L85.3 137.9 L106.0 137.9Z" fill="#ffffff" stroke="#ffffff" stroke-width="4" stroke-linejoin="round"/></g></svg>diff --git a/packages/wildos-remote/debian/changelog b/packages/wildos-remote/debian/changelognew file mode 100644index 0000000..1147af4--- /dev/null+++ b/packages/wildos-remote/debian/changelog@@ -0,0 +1,7 @@+wildos-remote (0.1.0) trixie; urgency=medium++ * First release: saved desktop and SSH hosts, Remote Desktop sessions on+ the Windows mode engine, an SSH terminal with snippets and suggestions,+ SFTP file copying, a keychain for SSH keys and host identity checks.++ -- Wild OS Developers <[email protected]> Mon, 09 Nov 2026 23:00:00 +0000diff --git a/packages/wildos-remote/debian/control b/packages/wildos-remote/debian/controlnew file mode 100644index 0000000..fbf5b0d--- /dev/null+++ b/packages/wildos-remote/debian/control@@ -0,0 +1,52 @@+Source: wildos-remote+Section: net+Priority: optional+Maintainer: Wild OS Developers <[email protected]>+Build-Depends:+ debhelper-compat (= 13),+ cmake,+ pkgconf,+ qt6-base-dev,+ qt6-base-private-dev,+ qt6-declarative-dev,+ qtkeychain-qt6-dev,+ libqtermwidget-dev,+ libkf6windowsystem-dev,+ libkf6config-dev,+ libwayland-dev,+ wayland-protocols,+ freerdp3-dev (>= 3.32),+ libwinpr3-dev (>= 3.32),+Standards-Version: 4.7.0+Rules-Requires-Root: no++Package: wildos-remote+Architecture: any+Depends:+ ${shlibs:Depends},+ ${misc:Depends},+ wildos-ui,+ openssh-client,+ libfreerdp3-3 (>= 3.32),+ libfreerdp-client3-3 (>= 3.32),+ qtermwidget-data,+ qt6-wayland,+ qml6-module-qtcore,+ qml6-module-qtquick,+ qml6-module-qtquick-controls,+ qml6-module-qtquick-templates,+ qml6-module-qtquick-layouts,+ qml6-module-qtquick-shapes,+ qml6-module-qtquick-effects,+ qml6-module-qtquick-window,+ qml6-module-qtquick-dialogs,+ qml6-module-qtqml-workerscript,+ fonts-jetbrains-mono,+Description: Wild OS Remote+ Remote connects to other computers: Windows PCs and servers with Remote+ Desktop, and servers over SSH. Desktops are drawn by the same engine as+ Windows mode, full screen or in a window. SSH hosts open in a terminal+ with snippets and suggestions from your own history, a file view that+ copies over SFTP, and a keychain for your keys. Host identities are+ checked against known_hosts and a changed one is never accepted without+ asking. Passwords are kept only in the keyring, and only when you tick it.diff --git a/packages/wildos-remote/debian/rules b/packages/wildos-remote/debian/rulesnew file mode 100644index 0000000..2c5acaf--- /dev/null+++ b/packages/wildos-remote/debian/rules@@ -0,0 +1,7 @@+#!/usr/bin/make -f++%:+ dh $@++override_dh_auto_configure:+ dh_auto_configure -- -Wno-dev -DCMAKE_BUILD_TYPE=Releasediff --git a/packages/wildos-remote/debian/source/format b/packages/wildos-remote/debian/source/formatnew file mode 100644index 0000000..89ae9db--- /dev/null+++ b/packages/wildos-remote/debian/source/format@@ -0,0 +1 @@+3.0 (native)diff --git a/packages/wildos-remote/qml/DesktopConnector.qml b/packages/wildos-remote/qml/DesktopConnector.qmlnew file mode 100644index 0000000..80d30d4--- /dev/null+++ b/packages/wildos-remote/qml/DesktopConnector.qml@@ -0,0 +1,169 @@+import QtQuick+import QtQuick.Layouts+import QtQuick.Window+import WildOS.Remote+import WildOS.UI as UI++// A Remote Desktop connection on its way in: the certificate questions+// (RemoteCheck.dc and its changed twin), the sign-in (RemoteSignIn.dc),+// then its own window, one per monitor with all monitors.+Item {+ id: connector++ property var current: null+ // The desktop windows open now, and the questions, for the screen test.+ property var windows: []+ readonly property alias firstDialog: firstDialog+ readonly property alias changedDialog: changedDialog+ readonly property alias signInDialog: signIn++ signal notice(string text)++ anchors.fill: parent++ function start(h, display) {+ Desktops.start(h, display || "");+ }++ Connections {+ target: Desktops+ function onStarted(d) {+ connector.attach(d);+ }+ }++ // Windows mode's desktop starts without the home window; a question+ // brings it up.+ function surface() {+ if (App.desktopOnly && Window.window && !Window.window.visible) {+ Window.window.show();+ }+ }++ function attach(d) {+ current = d;+ d.certificateNeeded.connect((info, changed) => {+ connector.surface();+ if (changed) {+ changedDialog.desktop = d;+ changedDialog.askCertificate({ name: d.name }, { fingerprint: info.fingerprint,+ previous: [{ fingerprint: info.previousFingerprint || "", seen: "" }] });+ } else {+ firstDialog.desktop = d;+ firstDialog.askCertificate({ name: d.name }, info);+ }+ });+ d.credentialsNeeded.connect((user, reason) => {+ connector.surface();+ signIn.ask(d, user, reason);+ });+ d.retryWanted.connect(user => {+ connector.surface();+ signIn.ask(d, user, "wrong");+ });+ d.opened.connect(() => {+ if (current === d) {+ current = null;+ }+ connector.openWindows(d);+ });+ d.stateChanged.connect(() => {+ if (d.state === "ended" && !d.everConnected) {+ if (current === d) {+ current = null;+ }+ if (d.endTitle.length > 0) {+ connector.surface();+ problem.show(d.endTitle, d.endText);+ }+ }+ });+ }++ // One window, or one per screen, each showing its part of the desktop.+ function openWindows(d) {+ const screens = Qt.application.screens;+ if (d.multiMonitor) {+ // Each screen shows the part of the desktop the engine gave it.+ const layout = d.monitors;+ for (let i = 0; i < layout.length; ++i) {+ const s = screens.find(x => x.name === layout[i].screen);+ if (!s) {+ continue;+ }+ windows.push(windowComponent.createObject(null, { desktop: d, screen: s, sourceRect: layout[i].rect, primary: i === 0 }));+ }+ } else {+ windows.push(windowComponent.createObject(null, { desktop: d, primary: true }));+ }+ }++ Component {+ id: windowComponent+ DesktopWindow {}+ }++ // Connecting, before any question or window.+ Rectangle {+ visible: connector.current !== null && connector.current.state === "connecting"+ anchors.horizontalCenter: parent.horizontalCenter+ anchors.bottom: parent.bottom+ anchors.bottomMargin: 24+ width: connectingRow.implicitWidth + 32+ height: 52+ radius: UI.Style.radiusMd+ color: UI.Style.glassMenu+ border.width: 1+ border.color: UI.Style.borderMenu+ z: 50+ RowLayout {+ id: connectingRow+ anchors.centerIn: parent+ spacing: 12+ UI.Spinner {+ size: 18+ running: parent.visible+ }+ UI.Label {+ text: connector.current ? qsTr("Connecting to %1…").arg(connector.current.name) : ""+ size: 14+ }+ UI.Button {+ size: "small"+ text: qsTr("Cancel")+ onClicked: connector.current.disconnectNow()+ }+ }+ }++ HostKeyDialog {+ id: firstDialog+ property var desktop+ onAccepted: (h, result) => desktop.answerCertificate(true, result.remember)+ onDeclined: desktop.answerCertificate(false, false)+ }+ HostChangedDialog {+ id: changedDialog+ property var desktop+ onRebuilt: desktop.answerCertificate(true, true)+ onRefused: desktop.answerCertificate(false, false)+ }+ SignInDialog {+ id: signIn+ }+ UI.Dialog {+ id: problem+ function show(heading, body) {+ title = heading;+ text = body;+ open();+ }+ buttons: [+ UI.Button {+ kind: "primary"+ text: qsTr("OK")+ onClicked: problem.close()+ }+ ]+ }+}diff --git a/packages/wildos-remote/qml/DesktopWindow.qml b/packages/wildos-remote/qml/DesktopWindow.qmlnew file mode 100644index 0000000..43892b9--- /dev/null+++ b/packages/wildos-remote/qml/DesktopWindow.qml@@ -0,0 +1,675 @@+pragma ComponentBehavior: Bound++import QtQuick+import QtQuick.Layouts+import QtQuick.Templates as T+import QtQuick.Window+import WildOS.Remote+import WildOS.UI as UI++// A remote desktop's window. Full screen (RemoteSession.dc), the toolbar+// waits at the top edge: latency, the Keys, Clipboard, Sharing and Displays+// menus, back to a window, minimise, disconnect and a pin to keep it. In a+// window (RemoteWindowed.dc) the same tools sit in the title bar. A dropped+// connection blurs the picture under "Connection lost" while it reconnects.+UI.AppWindow {+ id: window++ property var desktop+ property rect sourceRect: Qt.rect(0, 0, 0, 0)+ // With all monitors, the first window carries the toolbar's choices.+ property bool primary: true+ property bool pinned: false+ property bool toolbarShown: pinned || hoverTop || keysMenu.opened || clipboardMenu.opened || sharingMenu.opened || displaysMenu.opened || summoned+ property bool hoverTop: false+ property bool summoned: false+ readonly property bool full: desktop && desktop.display !== "window"+ readonly property bool lost: desktop && desktop.state === "reconnecting"+ readonly property bool ended: desktop && desktop.state === "ended"++ title: desktop ? qsTr("%1, Remote").arg(desktop.name) : qsTr("Remote")+ color: full ? "#000000" : "transparent"+ width: desktop && desktop.desktopSize.width > 0 ? Math.min(desktop.desktopSize.width / Screen.devicePixelRatio, Screen.desktopAvailableWidth - 40) : 1280+ height: desktop && desktop.desktopSize.height > 0 ? Math.min(desktop.desktopSize.height / Screen.devicePixelRatio + 40, Screen.desktopAvailableHeight - 40) : 800+ minimumWidth: 480+ minimumHeight: 320+ visible: true+ deep: true++ Component.onCompleted: {+ if (full) {+ showFullScreen();+ hint.show();+ }+ view.forceActiveFocus();+ }+ onFullChanged: {+ // A menu opened from the toolbar would float where it no longer is.+ keysMenu.close();+ clipboardMenu.close();+ sharingMenu.close();+ displaysMenu.close();+ if (full) {+ showFullScreen();+ } else {+ showNormal();+ }+ }+ onClosing: {+ if (desktop && desktop.state !== "ended") {+ desktop.disconnectNow();+ }+ }++ Connections {+ target: window.desktop+ function onStateChanged() {+ if (window.desktop.state === "ended" && window.desktop.endTitle.length === 0) {+ // Ended here (Disconnect, closing): nothing to say.+ window.close();+ }+ }+ function onLost() {+ if (!window.active && window.primary) {+ Notify.send(window.desktop.endTitle, window.desktop.endText, qsTr("Reconnect"), () => window.reconnect());+ }+ }+ }++ function openMenu(name) {+ const menus = { keys: [keysMenu, keysButton], clipboard: [clipboardMenu, clipButton], sharing: [sharingMenu, shareButton], displays: [displaysMenu, displayButton] };+ menus[name][0].openAt(menus[name][1]);+ }++ function reconnect() {+ const h = Hosts.host(desktop.hostId);+ window.close();+ if (h.id) {+ Desktops.start(h, desktop.display);+ }+ }++ ShortcutInhibitor {+ window: window+ enabled: window.desktop !== undefined && window.desktop.sendShortcuts && !window.lost+ }++ // The windowed title bar (RemoteWindowed.dc).+ Item {+ id: titleBar+ visible: !window.full+ width: parent.width+ height: 40++ MouseArea {+ anchors.fill: parent+ property point origin+ onPressed: m => origin = Qt.point(m.x, m.y)+ onPositionChanged: m => {+ if (pressed && Math.abs(m.x - origin.x) + Math.abs(m.y - origin.y) > 4) {+ window.startSystemMove();+ }+ }+ onDoubleClicked: window.frame.toggleMaximised()+ }+ Row {+ x: 14+ anchors.verticalCenter: parent.verticalCenter+ spacing: 10+ Image {+ anchors.verticalCenter: parent.verticalCenter+ width: 18+ height: 18+ source: "qrc:/qt/qml/WildOS/Remote/data/org.wildos.remote.svg"+ sourceSize: Qt.size(36, 36)+ }+ UI.Label {+ anchors.verticalCenter: parent.verticalCenter+ text: window.desktop ? window.desktop.name : ""+ size: 14+ font.weight: Font.DemiBold+ }+ UI.Label {+ anchors.verticalCenter: parent.verticalCenter+ text: qsTr("Remote")+ size: 14+ color: UI.Style.inkSubtle+ }+ Latency {+ anchors.verticalCenter: parent.verticalCenter+ leftPadding: 8+ }+ }+ Row {+ anchors.right: windowButtons.left+ anchors.rightMargin: 12+ anchors.verticalCenter: parent.verticalCenter+ spacing: 2+ ToolIcon { id: keysIcon; glyph: RemoteIcons.keyboard; tip: qsTr("Keys"); onClicked: keysMenu.openAt(keysIcon) }+ ToolIcon { id: clipIcon; glyph: RemoteIcons.clipboard; tip: qsTr("Clipboard"); onClicked: clipboardMenu.openAt(clipIcon) }+ ToolIcon { id: shareIcon; glyph: RemoteIcons.folder; tip: qsTr("Sharing"); onClicked: sharingMenu.openAt(shareIcon) }+ ToolIcon { id: displayIcon; glyph: RemoteIcons.displays; tip: qsTr("Displays"); onClicked: displaysMenu.openAt(displayIcon) }+ Rectangle { width: 1; height: 20; anchors.verticalCenter: parent.verticalCenter; color: UI.Style.divider }+ }+ UI.WindowButtons {+ id: windowButtons+ anchors.right: parent.right+ buttonHeight: 40+ frame: window.frame+ }+ }++ // The desktop itself.+ Rectangle {+ id: stage+ y: window.full ? 0 : titleBar.height+ width: parent.width+ height: parent.height - y+ color: window.full ? "#000000" : "#0b0f1c"+ bottomLeftRadius: window.full || window.maximised ? 0 : UI.Style.windowRadius+ bottomRightRadius: bottomLeftRadius+ clip: true++ DesktopView {+ id: view+ anchors.fill: parent+ desktop: window.desktop+ sourceRect: window.sourceRect+ blurred: window.lost || window.ended+ focus: true+ onEscapeRequested: {+ window.desktop.sendShortcuts = false;+ window.summoned = true;+ summonTimer.restart();+ }+ onPointerMoved: (x, y) => window.hoverTop = window.full && (y < 4 || (window.hoverTop && y < 64))+ }++ // Asks Windows for the new size as the window changes, once it+ // settles.+ Timer {+ id: resizeTimer+ interval: 400+ onTriggered: {+ if (window.desktop && window.desktop.session && window.primary) {+ Desktops.resizeTo(window.desktop, Qt.size(stage.width * Screen.devicePixelRatio, stage.height * Screen.devicePixelRatio), Screen.devicePixelRatio);+ }+ }+ }+ onWidthChanged: if (!window.full) resizeTimer.restart()+ onHeightChanged: if (!window.full) resizeTimer.restart()++ // Connection lost (RemoteWindowed.dc).+ Rectangle {+ visible: window.lost || (window.ended && window.desktop.endTitle.length > 0)+ anchors.centerIn: parent+ width: Math.min(450, parent.width - 40)+ height: lostColumn.implicitHeight + 56+ radius: 16+ color: Qt.rgba(22 / 255, 27 / 255, 46 / 255, 0.97)+ border.width: 1+ border.color: UI.Style.tone(0.12)+ ColumnLayout {+ id: lostColumn+ anchors.left: parent.left+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ anchors.margins: 28+ spacing: 12+ UI.Spinner {+ visible: window.lost+ Layout.alignment: Qt.AlignHCenter+ size: 36+ running: window.lost+ }+ UI.Label {+ Layout.fillWidth: true+ horizontalAlignment: Text.AlignHCenter+ text: window.lost ? qsTr("Connection lost") : window.desktop ? window.desktop.endTitle : ""+ size: 18+ font.weight: Font.Bold+ color: "#eef1f8"+ }+ UI.Label {+ Layout.fillWidth: true+ horizontalAlignment: Text.AlignHCenter+ text: window.lost+ ? qsTr("Reconnecting to %1, attempt %2 of %3. Windows keeps your session running while you're away, so your apps stay open.")+ .arg(window.desktop.name).arg(window.desktop.attempt).arg(window.desktop.attempts)+ : window.desktop ? window.desktop.endText : ""+ size: 14+ color: Qt.rgba(238 / 255, 241 / 255, 248 / 255, 0.78)+ wrapMode: Text.Wrap+ lineHeight: 1.35+ }+ Row {+ Layout.alignment: Qt.AlignHCenter+ Layout.topMargin: 6+ spacing: 10+ UI.Button {+ text: window.lost ? qsTr("Stop trying") : qsTr("Close")+ onClicked: window.lost ? window.desktop.stopTrying() : window.close()+ }+ UI.Button {+ kind: "primary"+ text: window.lost ? qsTr("Try now") : qsTr("Reconnect")+ onClicked: window.lost ? window.desktop.tryNow() : window.reconnect()+ }+ }+ }+ }+ }++ // The full screen toolbar (RemoteSession.dc).+ Rectangle {+ id: toolbar+ visible: window.full && window.primary+ anchors.horizontalCenter: parent.horizontalCenter+ y: window.toolbarShown ? 0 : -height - 2+ width: toolRow.implicitWidth + 24+ height: 48+ bottomLeftRadius: 14+ bottomRightRadius: 14+ color: Qt.rgba(16 / 255, 20 / 255, 36 / 255, 0.92)+ border.width: 1+ border.color: UI.Style.tone(0.1)+ z: 10+ Behavior on y {+ NumberAnimation { duration: UI.Style.motionNormal; easing.type: UI.Style.easeEnter }+ }+ HoverHandler {+ onHoveredChanged: if (hovered) window.hoverTop = true; else if (!window.pinned) leaveTimer.restart()+ }+ Timer {+ id: leaveTimer+ interval: 600+ onTriggered: window.hoverTop = false+ }++ RowLayout {+ id: toolRow+ anchors.centerIn: parent+ spacing: 4+ Image {+ Layout.leftMargin: 4+ Layout.preferredWidth: 18+ Layout.preferredHeight: 18+ source: "qrc:/qt/qml/WildOS/Remote/data/org.wildos.remote.svg"+ sourceSize: Qt.size(36, 36)+ }+ UI.Label {+ Layout.leftMargin: 6+ text: window.desktop ? window.desktop.name : ""+ size: 14+ font.weight: Font.DemiBold+ color: "#eef1f8"+ }+ Latency { Layout.leftMargin: 8; Layout.rightMargin: 8 }+ Divider {}+ ToolText { id: keysButton; glyph: RemoteIcons.keyboard; text: qsTr("Keys"); on: keysMenu.opened; onClicked: keysMenu.openAt(keysButton) }+ ToolText { id: clipButton; glyph: RemoteIcons.clipboard; text: qsTr("Clipboard"); on: clipboardMenu.opened; onClicked: clipboardMenu.openAt(clipButton) }+ ToolText { id: shareButton; glyph: RemoteIcons.folder; text: qsTr("Sharing"); on: sharingMenu.opened; onClicked: sharingMenu.openAt(shareButton) }+ ToolText { id: displayButton; glyph: RemoteIcons.displays; text: qsTr("Displays"); on: displaysMenu.opened; onClicked: displaysMenu.openAt(displayButton) }+ Divider {}+ ToolText { glyph: RemoteIcons.exitFull; text: qsTr("Window"); onClicked: window.desktop.display = "window" }+ ToolText { iconName: "minus"; text: qsTr("Minimise"); onClicked: window.showMinimized() }+ ToolText {+ glyph: RemoteIcons.power+ text: qsTr("Disconnect")+ colour: "#ff9a8a"+ onClicked: window.desktop.disconnectNow()+ }+ Divider {}+ UI.IconButton {+ width: 32+ height: 32+ iconName: window.pinned ? "unpin" : "pin"+ iconSize: 15+ iconColor: window.pinned ? UI.Style.accent : "#eef1f8"+ tip: window.pinned ? qsTr("Let the toolbar hide") : qsTr("Keep the toolbar showing")+ focusPolicy: Qt.NoFocus+ onClicked: window.pinned = !window.pinned+ }+ }+ }++ Timer {+ id: summonTimer+ interval: 4000+ onTriggered: window.summoned = false+ }++ // How to get out of full screen, said once.+ Rectangle {+ id: hint+ visible: opacity > 0+ opacity: 0+ anchors.right: parent.right+ anchors.bottom: parent.bottom+ anchors.margins: 24+ width: hintRow.implicitWidth + 32+ height: 36+ radius: 10+ color: Qt.rgba(16 / 255, 20 / 255, 36 / 255, 0.92)+ z: 10+ function show() {+ opacity = 1;+ hintTimer.restart();+ }+ Behavior on opacity {+ NumberAnimation { duration: UI.Style.motionSlow }+ }+ Timer {+ id: hintTimer+ interval: 6000+ onTriggered: hint.opacity = 0+ }+ Row {+ id: hintRow+ anchors.centerIn: parent+ spacing: 10+ UI.Icon {+ anchors.verticalCenter: parent.verticalCenter+ name: "monitor"+ size: 14+ color: "#eef1f8"+ }+ UI.Label {+ anchors.verticalCenter: parent.verticalCenter+ text: qsTr("Full screen. Move to the top edge for the toolbar, or press Ctrl+Alt+Home")+ size: 13+ color: "#eef1f8"+ }+ }+ }++ // Menus.+ ToolMenu {+ id: keysMenu+ MenuRow { text: qsTr("Send Ctrl+Alt+Del"); shortcut: "Ctrl+Alt+End"; onClicked: window.desktop.sendKeys("ctrl-alt-del") }+ MenuRow { text: qsTr("Send the Windows key"); onClicked: window.desktop.sendKeys("windows") }+ MenuRow { text: qsTr("Send Print Screen"); onClicked: window.desktop.sendKeys("print") }+ MenuRow { text: qsTr("Switch app on the remote PC"); shortcut: "Alt+Tab"; onClicked: window.desktop.sendKeys("alt-tab") }+ MenuLine {}+ MenuToggle {+ text: qsTr("Send all shortcuts there")+ detail: qsTr("Alt+Tab, Super and the rest go to the remote PC while it's in front. Ctrl+Alt+Home always comes back here.")+ checked: window.desktop ? window.desktop.sendShortcuts : false+ onToggled: on => window.desktop.sendShortcuts = on+ }+ }+ ToolMenu {+ id: clipboardMenu+ MenuToggle {+ text: qsTr("Share the clipboard")+ detail: qsTr("Copy here, paste there and the other way round: text and pictures.")+ checked: window.desktop ? window.desktop.sharing.clipboard === true : false+ onToggled: on => window.desktop.setSharing("clipboard", on)+ }+ Reconnect {}+ }+ ToolMenu {+ id: sharingMenu+ MenuToggle {+ text: qsTr("Sound plays here")+ checked: window.desktop ? window.desktop.sharing.sound === true : false+ onToggled: on => window.desktop.setSharing("sound", on)+ }+ MenuToggle {+ text: qsTr("Microphone")+ checked: window.desktop ? window.desktop.sharing.microphone === true : false+ onToggled: on => window.desktop.setSharing("microphone", on)+ }+ MenuToggle {+ text: qsTr("Printers")+ checked: window.desktop ? window.desktop.sharing.printers === true : false+ onToggled: on => window.desktop.setSharing("printers", on)+ }+ MenuToggle {+ text: qsTr("Folders")+ detail: qsTr("The folder chosen for this PC, which the remote PC can change")+ checked: window.desktop ? window.desktop.sharing.folders === true : false+ onToggled: on => window.desktop.setSharing("folders", on)+ }+ Reconnect {}+ }+ ToolMenu {+ id: displaysMenu+ MenuRow {+ text: qsTr("Full screen on this monitor")+ ticked: window.desktop && window.desktop.display === "full"+ onClicked: window.desktop.display = "full"+ }+ MenuRow {+ text: qsTr("In a window")+ ticked: window.desktop && window.desktop.display === "window"+ onClicked: window.desktop.display = "window"+ }+ MenuRow {+ visible: Qt.application.screens.length > 1+ text: qsTr("All my monitors")+ detail: qsTr("Reconnects to lay the desktop out across them")+ ticked: window.desktop && window.desktop.multiMonitor+ onClicked: {+ const h = Hosts.host(window.desktop.hostId);+ window.close();+ if (h.id) {+ Desktops.start(h, "all");+ }+ }+ }+ }++ component Latency: Row {+ spacing: 6+ readonly property bool down: window.lost+ visible: window.desktop !== undefined && (down || window.desktop.latency > 0)+ UI.Glyph {+ anchors.verticalCenter: parent.verticalCenter+ width: 13+ height: 13+ path: RemoteIcons.signal+ color: parent.down ? "#ff9a8a" : "#5fd39a"+ }+ UI.Label {+ anchors.verticalCenter: parent.verticalCenter+ text: parent.down ? qsTr("No connection") : qsTr("%1 ms").arg(window.desktop ? window.desktop.latency : 0)+ size: 13+ color: parent.down ? "#ff9a8a" : "#5fd39a"+ }+ }+ component Divider: Rectangle {+ Layout.preferredWidth: 1+ Layout.preferredHeight: 22+ Layout.leftMargin: 4+ Layout.rightMargin: 4+ color: UI.Style.tone(0.12)+ }+ component ToolIcon: UI.IconButton {+ width: 32+ height: 30+ iconSize: 16+ iconColor: UI.Style.iconMuted+ focusPolicy: Qt.NoFocus+ }+ component ToolText: Rectangle {+ id: tool+ property string text+ property string glyph+ property string iconName+ property bool on: false+ property color colour: "#eef1f8"+ signal clicked()+ implicitWidth: toolLabelRow.implicitWidth + 20+ implicitHeight: 34+ radius: 8+ color: on ? Qt.rgba(143 / 255, 180 / 255, 255 / 255, 0.18) : toolMouse.containsMouse ? Qt.rgba(1, 1, 1, 0.08) : "transparent"+ Accessible.role: Accessible.Button+ Accessible.name: text+ Row {+ id: toolLabelRow+ anchors.centerIn: parent+ spacing: 8+ UI.Glyph {+ visible: tool.glyph.length > 0+ anchors.verticalCenter: parent.verticalCenter+ width: 15+ height: 15+ path: tool.glyph+ color: tool.on ? "#8fb4ff" : tool.colour+ }+ UI.Icon {+ visible: tool.iconName.length > 0+ anchors.verticalCenter: parent.verticalCenter+ name: tool.iconName+ size: 15+ color: tool.colour+ }+ UI.Label {+ anchors.verticalCenter: parent.verticalCenter+ text: tool.text+ size: 14+ font.weight: Font.DemiBold+ color: tool.on ? "#8fb4ff" : tool.colour+ }+ }+ MouseArea {+ id: toolMouse+ anchors.fill: parent+ hoverEnabled: true+ onClicked: tool.clicked()+ }+ }+ component ToolMenu: T.Popup {+ id: menu+ default property alias rows: menuColumn.data+ function openAt(item) {+ const p = item.mapToItem(null, 0, item.height + 6);+ x = Math.min(p.x, window.width - width - 8);+ y = p.y;+ open();+ }+ parent: T.Overlay.overlay+ width: 314+ padding: 6+ implicitHeight: menuColumn.implicitHeight + 12+ closePolicy: T.Popup.CloseOnEscape | T.Popup.CloseOnPressOutside+ onClosed: view.forceActiveFocus()+ background: Rectangle {+ radius: 12+ color: Qt.rgba(22 / 255, 27 / 255, 46 / 255, 0.97)+ border.width: 1+ border.color: UI.Style.tone(0.12)+ }+ contentItem: Column {+ id: menuColumn+ spacing: 0+ }+ }+ component MenuRow: Rectangle {+ id: row+ property string text+ property string shortcut+ property string detail+ property bool ticked: false+ signal clicked()+ width: 302+ height: detail.length > 0 ? 52 : 36+ radius: 7+ color: rowMouse.containsMouse ? Qt.rgba(1, 1, 1, 0.07) : "transparent"+ UI.Icon {+ visible: row.ticked+ x: 10+ anchors.verticalCenter: parent.verticalCenter+ name: "check"+ size: 14+ color: "#8fb4ff"+ }+ Column {+ x: 12 + (row.ticked ? 20 : 0)+ anchors.verticalCenter: parent.verticalCenter+ spacing: 2+ UI.Label { text: row.text; size: 14; color: "#eef1f8" }+ UI.Label { visible: row.detail.length > 0; text: row.detail; size: 12; color: Qt.rgba(238 / 255, 241 / 255, 248 / 255, 0.6) }+ }+ UI.Label {+ anchors.right: parent.right+ anchors.rightMargin: 12+ anchors.verticalCenter: parent.verticalCenter+ text: row.shortcut+ size: 12+ color: Qt.rgba(238 / 255, 241 / 255, 248 / 255, 0.55)+ }+ MouseArea {+ id: rowMouse+ anchors.fill: parent+ hoverEnabled: true+ onClicked: {+ row.clicked();+ keysMenu.close();+ displaysMenu.close();+ }+ }+ }+ component MenuLine: Rectangle {+ width: 290+ x: 6+ height: 1+ color: Qt.rgba(1, 1, 1, 0.08)+ }+ component MenuToggle: Item {+ id: toggleRow+ property string text+ property string detail+ property bool checked+ signal toggled(bool on)+ width: 302+ height: Math.max(44, toggleText.implicitHeight + 20)+ Column {+ id: toggleText+ x: 12+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - 80+ spacing: 3+ UI.Label { width: parent.width; text: toggleRow.text; size: 14; font.weight: Font.DemiBold; color: "#eef1f8" }+ UI.Label {+ visible: toggleRow.detail.length > 0+ width: parent.width+ text: toggleRow.detail+ size: 12+ color: Qt.rgba(238 / 255, 241 / 255, 248 / 255, 0.62)+ wrapMode: Text.Wrap+ }+ }+ UI.Toggle {+ anchors.right: parent.right+ anchors.rightMargin: 12+ anchors.verticalCenter: parent.verticalCenter+ checked: toggleRow.checked+ focusPolicy: Qt.NoFocus+ Accessible.name: toggleRow.text+ onToggled: toggleRow.toggled(checked)+ }+ }+ component Reconnect: Column {+ visible: window.desktop !== undefined && window.desktop.sharingChanged+ width: 302+ topPadding: 6+ spacing: 8+ Rectangle { width: 290; x: 6; height: 1; color: Qt.rgba(1, 1, 1, 0.08) }+ UI.Label {+ x: 12+ width: 278+ text: qsTr("Remote Desktop settles what's shared as it connects, so this takes effect when you reconnect.")+ size: 12+ color: Qt.rgba(238 / 255, 241 / 255, 248 / 255, 0.62)+ wrapMode: Text.Wrap+ }+ UI.Button {+ x: 12+ size: "small"+ text: qsTr("Reconnect now")+ onClicked: window.reconnect()+ }+ }+}diff --git a/packages/wildos-remote/qml/FilesView.qml b/packages/wildos-remote/qml/FilesView.qmlnew file mode 100644index 0000000..9423cc2--- /dev/null+++ b/packages/wildos-remote/qml/FilesView.qml@@ -0,0 +1,542 @@+pragma ComponentBehavior: Bound++import QtQuick+import QtQuick.Layouts+import WildOS.Remote+import WildOS.UI as UI++// Copying files to and from a server (RemoteFiles.dc): this PC on the left,+// the server on the right, the arrows between them, and the copies in+// progress below.+Item {+ id: view++ property var tab: null+ readonly property var files: tab ? tab.files : null++ signal notice(string text)++ Connections {+ target: view.files+ function onNotice(text) {+ view.notice(text);+ }+ }++ Rectangle {+ anchors.fill: parent+ color: "#0b0f1c"+ }++ ColumnLayout {+ anchors.fill: parent+ anchors.margins: 18+ anchors.topMargin: 18+ spacing: 14++ RowLayout {+ Layout.fillWidth: true+ Layout.fillHeight: true+ spacing: 10++ FilePane {+ id: localPane+ Layout.fillWidth: true+ Layout.fillHeight: true+ remote: false+ title: qsTr("This PC")+ path: view.files ? view.files.localShown : ""+ entries: view.files ? view.files.localEntries : []+ onOpenFolder: name => view.files.openLocal(name)+ onOpenFile: name => view.files.openLocalFile(name)+ onBack: view.files.localBack()+ onRefresh: view.files.refreshLocal()+ onNewFolder: newFolderDialog.ask(false)+ }++ Column {+ Layout.alignment: Qt.AlignVCenter+ spacing: 12+ Arrow {+ iconName: "chevron-right"+ primary: localPane.selection.length > 0+ enabled: localPane.selection.length > 0 && view.files && view.files.remoteReady+ tip: qsTr("Upload to %1").arg(view.tab ? view.tab.title : "")+ onClicked: {+ view.files.upload(localPane.selection);+ localPane.selection = [];+ }+ }+ Arrow {+ iconName: "chevron-left"+ primary: remotePane.selection.length > 0+ enabled: remotePane.selection.length > 0+ tip: qsTr("Download to this PC")+ onClicked: {+ view.files.download(remotePane.selection);+ remotePane.selection = [];+ }+ }+ }++ FilePane {+ id: remotePane+ Layout.fillWidth: true+ Layout.fillHeight: true+ remote: true+ title: view.tab ? view.tab.title : ""+ tint: view.tab ? view.tab.colour : "#5fd39a"+ path: view.files ? view.files.remotePath : ""+ entries: view.files ? view.files.remoteEntries : []+ loading: view.files ? view.files.loading : false+ error: view.files ? view.files.remoteError : ""+ onOpenFolder: name => view.files.openRemote(name)+ onOpenFile: name => view.files.editRemote(name)+ onBack: view.files.remoteBack()+ onRefresh: view.files.remoteReady ? view.files.refreshRemote() : view.files.retry()+ onNewFolder: newFolderDialog.ask(true)+ onDeleteRequested: names => deleteDialog.ask(names)+ onRenameRequested: name => renameDialog.ask(name)+ }+ }++ // Copies in progress.+ Rectangle {+ visible: view.files !== null && view.files.transfers.length > 0+ Layout.fillWidth: true+ Layout.preferredHeight: Math.min(transferColumn.implicitHeight + 28, 220)+ radius: 12+ color: UI.Style.tone(0.035)+ border.width: 1+ border.color: UI.Style.tone(0.08)+ Column {+ id: transferColumn+ x: 16+ y: 14+ width: parent.width - 32+ spacing: 12+ Item {+ width: parent.width+ height: 20+ UI.Label {+ text: view.files ? view.files.transferTitle : ""+ size: 14+ font.weight: Font.Bold+ }+ Row {+ anchors.right: parent.right+ spacing: 14+ UI.Label {+ text: view.files ? view.files.transferSummary : ""+ size: 13+ color: UI.Style.inkMuted+ }+ UI.LinkButton {+ visible: view.files !== null && !view.files.transferring+ anchors.verticalCenter: parent.verticalCenter+ text: qsTr("Clear")+ onClicked: view.files.clearFinished()+ }+ UI.LinkButton {+ visible: view.files !== null && view.files.transferring+ anchors.verticalCenter: parent.verticalCenter+ text: qsTr("Stop")+ onClicked: view.files.cancelTransfers()+ }+ }+ }+ Repeater {+ model: view.files ? view.files.transfers.slice(-6) : []+ Item {+ id: transfer+ required property var modelData+ width: transferColumn.width+ height: 26+ UI.Glyph {+ x: 2+ anchors.verticalCenter: parent.verticalCenter+ width: 14+ height: 14+ path: transfer.modelData.upload ? RemoteIcons.upload : RemoteIcons.download+ color: transfer.modelData.state === "failed" ? UI.Style.danger : "#5fd39a"+ }+ UI.Label {+ x: 28+ anchors.verticalCenter: parent.verticalCenter+ width: 180+ text: transfer.modelData.name+ size: 13+ }+ Rectangle {+ x: 222+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - 222 - 150+ height: 4+ radius: 2+ color: UI.Style.tone(0.1)+ Rectangle {+ width: parent.width * Math.max(0, Math.min(1, transfer.modelData.progress))+ height: parent.height+ radius: 2+ color: transfer.modelData.state === "done" ? "#5fd39a" : transfer.modelData.state === "failed" ? UI.Style.danger : "#8fb4ff"+ }+ }+ UI.Label {+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ width: 136+ horizontalAlignment: Text.AlignRight+ text: transfer.modelData.detail+ size: 13+ color: transfer.modelData.state === "failed" ? UI.Style.danger : UI.Style.inkMuted+ }+ }+ }+ }+ }++ Row {+ spacing: 10+ UI.Glyph {+ anchors.verticalCenter: parent.verticalCenter+ width: 14+ height: 14+ path: RemoteIcons.file+ color: UI.Style.iconMuted+ }+ UI.Label {+ text: qsTr("Double-click a file on the server to open it here. Saving it uploads it back.")+ size: 13+ color: UI.Style.inkMuted+ }+ }+ }++ UI.Dialog {+ id: newFolderDialog+ property bool remote+ function ask(r) {+ remote = r;+ title = qsTr("New folder");+ folderName.text = "";+ open();+ folderName.forceActiveFocus();+ }+ UI.TextField {+ id: folderName+ Layout.fillWidth: true+ placeholderText: qsTr("Name")+ onAccepted: folderMake.clicked()+ }+ buttons: [+ UI.Button {+ text: qsTr("Cancel")+ onClicked: newFolderDialog.close()+ },+ UI.Button {+ id: folderMake+ kind: "primary"+ text: qsTr("Make")+ enabled: folderName.text.trim().length > 0+ onClicked: {+ newFolderDialog.remote ? view.files.newRemoteFolder(folderName.text) : view.files.newLocalFolder(folderName.text);+ newFolderDialog.close();+ }+ }+ ]+ }+ UI.Dialog {+ id: deleteDialog+ property var names: []+ function ask(n) {+ names = n;+ title = n.length === 1 ? qsTr("Delete %1 from the server?").arg(n[0]) : qsTr("Delete %1 items from the server?").arg(n.length);+ text = qsTr("There's no bin on the server: this can't be undone.");+ open();+ }+ buttons: [+ UI.Button {+ text: qsTr("Cancel")+ onClicked: deleteDialog.close()+ },+ UI.Button {+ kind: "primary"+ danger: true+ text: qsTr("Delete")+ onClicked: {+ view.files.removeRemote(deleteDialog.names);+ remotePane.selection = [];+ deleteDialog.close();+ }+ }+ ]+ }+ UI.Dialog {+ id: renameDialog+ property string from+ function ask(name) {+ from = name;+ title = qsTr("Rename %1").arg(name);+ renameField.text = name;+ open();+ renameField.forceActiveFocus();+ renameField.selectAll();+ }+ UI.TextField {+ id: renameField+ Layout.fillWidth: true+ onAccepted: renameGo.clicked()+ }+ buttons: [+ UI.Button {+ text: qsTr("Cancel")+ onClicked: renameDialog.close()+ },+ UI.Button {+ id: renameGo+ kind: "primary"+ text: qsTr("Rename")+ enabled: renameField.text.trim().length > 0 && renameField.text !== renameDialog.from+ onClicked: {+ view.files.renameRemote(renameDialog.from, renameField.text);+ renameDialog.close();+ }+ }+ ]+ }++ component Arrow: UI.IconButton {+ property bool primary: false+ width: 40+ height: 40+ radius: 20+ iconSize: 16+ selected: primary && enabled+ iconColor: UI.Style.ink+ }++ component FilePane: Rectangle {+ id: pane+ property bool remote+ property string title+ property string path+ property var entries: []+ property bool loading: false+ property string error+ property color tint: "#8fb4ff"+ property var selection: []+ property int anchorIndex: -1+ signal openFolder(string name)+ signal openFile(string name)+ signal back()+ signal refresh()+ signal newFolder()+ signal deleteRequested(var names)+ signal renameRequested(string name)++ onPathChanged: {+ selection = [];+ anchorIndex = -1;+ }++ radius: 12+ color: UI.Style.tone(0.035)+ border.width: 1+ border.color: UI.Style.tone(0.08)++ function choose(index, name, mods) {+ if (mods & Qt.ShiftModifier && anchorIndex >= 0) {+ const a = Math.min(anchorIndex, index);+ const b = Math.max(anchorIndex, index);+ selection = shownEntries.slice(a, b + 1).map(e => e.name);+ } else if (mods & Qt.ControlModifier) {+ const s = selection.slice();+ const i = s.indexOf(name);+ i >= 0 ? s.splice(i, 1) : s.push(name);+ selection = s;+ anchorIndex = index;+ } else {+ selection = [name];+ anchorIndex = index;+ }+ }+ // This PC's dot files stay out of the way; the server's are often+ // the point (.htaccess, .env).+ readonly property var shownEntries: remote ? entries : entries.filter(e => !e.hidden)++ ColumnLayout {+ anchors.fill: parent+ spacing: 0++ Item {+ Layout.fillWidth: true+ Layout.preferredHeight: 48+ Rectangle {+ x: 14+ anchors.verticalCenter: parent.verticalCenter+ width: 26+ height: 26+ radius: 7+ color: Qt.rgba(pane.tint.r, pane.tint.g, pane.tint.b, 0.16)+ UI.Icon {+ anchors.centerIn: parent+ name: pane.remote ? "terminal" : "monitor"+ size: 14+ color: pane.tint+ }+ }+ Row {+ x: 52+ anchors.verticalCenter: parent.verticalCenter+ spacing: 10+ UI.Label {+ text: pane.title+ size: 14+ font.weight: Font.Bold+ }+ UI.Label {+ text: pane.path+ size: 13+ font.family: "JetBrains Mono"+ color: UI.Style.inkMuted+ }+ }+ Row {+ anchors.right: parent.right+ anchors.rightMargin: 8+ anchors.verticalCenter: parent.verticalCenter+ spacing: 6+ UI.IconButton { width: 32; height: 32; iconName: "chevron-left"; iconSize: 14; iconColor: UI.Style.iconMuted; tip: qsTr("Back"); onClicked: pane.back() }+ UI.IconButton { width: 32; height: 32; iconName: "refresh"; iconSize: 14; iconColor: UI.Style.iconMuted; tip: qsTr("Refresh"); onClicked: pane.refresh() }+ UI.IconButton { width: 32; height: 32; iconName: "plus"; iconSize: 14; iconColor: UI.Style.iconMuted; tip: qsTr("New folder"); onClicked: pane.newFolder() }+ }+ Rectangle {+ anchors.bottom: parent.bottom+ width: parent.width+ height: 1+ color: UI.Style.tone(0.07)+ }+ }+ Item {+ Layout.fillWidth: true+ Layout.preferredHeight: 32+ UI.Label { x: 14; anchors.verticalCenter: parent.verticalCenter; text: qsTr("Name"); size: 12; color: UI.Style.inkSubtle }+ UI.Label { x: parent.width - 260; width: 110; horizontalAlignment: Text.AlignRight; anchors.verticalCenter: parent.verticalCenter; text: qsTr("Size"); size: 12; color: UI.Style.inkSubtle }+ UI.Label { anchors.right: parent.right; anchors.rightMargin: 14; anchors.verticalCenter: parent.verticalCenter; text: qsTr("Modified"); size: 12; color: UI.Style.inkSubtle }+ Rectangle {+ anchors.bottom: parent.bottom+ width: parent.width+ height: 1+ color: UI.Style.tone(0.07)+ }+ }+ ListView {+ id: fileList+ Layout.fillWidth: true+ Layout.fillHeight: true+ clip: true+ model: pane.shownEntries+ boundsBehavior: Flickable.StopAtBounds+ delegate: Rectangle {+ id: fileRow+ required property var modelData+ required property int index+ readonly property bool chosen: pane.selection.indexOf(modelData.name) >= 0+ width: ListView.view.width+ height: 38+ color: chosen ? UI.Style.tone(0.09) : rowMouse.containsMouse ? UI.Style.tone(0.04) : "transparent"+ UI.Glyph {+ x: 16+ anchors.verticalCenter: parent.verticalCenter+ width: 15+ height: 15+ path: fileRow.modelData.dir ? RemoteIcons.folder : RemoteIcons.file+ color: fileRow.modelData.dir ? "#ffc46a" : UI.Style.iconMuted+ }+ UI.Label {+ x: 40+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - 40 - 270+ text: fileRow.modelData.name+ size: 14+ }+ UI.Label {+ x: parent.width - 260+ width: 110+ horizontalAlignment: Text.AlignRight+ anchors.verticalCenter: parent.verticalCenter+ text: fileRow.modelData.sizeText+ size: 13+ color: UI.Style.inkMuted+ }+ UI.Label {+ anchors.right: parent.right+ anchors.rightMargin: 14+ anchors.verticalCenter: parent.verticalCenter+ text: fileRow.modelData.modified+ size: 13+ color: UI.Style.inkMuted+ }+ MouseArea {+ id: rowMouse+ anchors.fill: parent+ hoverEnabled: true+ acceptedButtons: Qt.LeftButton | Qt.RightButton+ onClicked: m => {+ if (m.button === Qt.RightButton) {+ if (!fileRow.chosen) {+ pane.choose(fileRow.index, fileRow.modelData.name, 0);+ }+ if (pane.remote) {+ rowMenu.entries = [+ { text: fileRow.modelData.dir ? qsTr("Open") : qsTr("Open here"), icon: "open", bold: true,+ run: () => fileRow.modelData.dir ? pane.openFolder(fileRow.modelData.name) : pane.openFile(fileRow.modelData.name) },+ { text: qsTr("Download"), icon: "download", run: () => { view.files.download(pane.selection); pane.selection = []; } },+ { text: qsTr("Rename"), icon: "rename", enabled: pane.selection.length === 1, run: () => pane.renameRequested(fileRow.modelData.name) },+ { separator: true },+ { text: qsTr("Delete"), icon: "delete", danger: true, run: () => pane.deleteRequested(pane.selection) }+ ];+ rowMenu.popup(fileRow, m.x, m.y);+ }+ return;+ }+ pane.choose(fileRow.index, fileRow.modelData.name, m.modifiers);+ }+ onDoubleClicked: fileRow.modelData.dir ? pane.openFolder(fileRow.modelData.name) : pane.openFile(fileRow.modelData.name)+ }+ }+ }+ }++ Column {+ visible: pane.remote && (pane.error.length > 0 || (pane.loading && pane.entries.length === 0))+ anchors.centerIn: parent+ width: parent.width - 60+ spacing: 14+ UI.Spinner {+ visible: pane.error.length === 0+ anchors.horizontalCenter: parent.horizontalCenter+ size: 22+ }+ UI.Label {+ visible: pane.error.length > 0+ width: parent.width+ horizontalAlignment: Text.AlignHCenter+ text: pane.error+ size: 14+ color: UI.Style.inkMuted+ wrapMode: Text.Wrap+ }+ UI.Button {+ visible: pane.error.length > 0+ anchors.horizontalCenter: parent.horizontalCenter+ text: qsTr("Try again")+ onClicked: view.files.retry()+ }+ }++ UI.Menu {+ id: rowMenu+ }+ }+}diff --git a/packages/wildos-remote/qml/ForwardingPage.qml b/packages/wildos-remote/qml/ForwardingPage.qmlnew file mode 100644index 0000000..4dbd0bc--- /dev/null+++ b/packages/wildos-remote/qml/ForwardingPage.qml@@ -0,0 +1,111 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Remote+import WildOS.UI as UI++// Every port forward, from every SSH host. Each one is open while its+// host's terminal is, on this PC only (127.0.0.1).+Item {+ id: page++ signal editHost(string id)++ readonly property var rows: {+ const out = [];+ for (const h of Hosts.hosts) {+ if (h.kind !== "terminal") {+ continue;+ }+ for (const f of (h.ssh.forwards || [])) {+ out.push({ host: h, forward: f });+ }+ }+ return out;+ }++ ColumnLayout {+ anchors.fill: parent+ anchors.leftMargin: 36+ anchors.rightMargin: 36+ anchors.topMargin: 22+ anchors.bottomMargin: 26+ spacing: 14++ UI.Label {+ Layout.preferredHeight: 44+ text: qsTr("Port forwarding")+ size: 26+ font.weight: Font.Bold+ }+ UI.Label {+ Layout.fillWidth: true+ Layout.maximumWidth: 900+ text: qsTr("A forward makes a port on a server, or on a machine the server can reach, answer on this PC. It's open while that host's terminal is, and only programs on this PC can use it. Add one from a host's settings.")+ size: 14+ color: UI.Style.inkMuted+ wrapMode: Text.Wrap+ lineHeight: 1.35+ }++ ListView {+ Layout.fillWidth: true+ Layout.fillHeight: true+ Layout.maximumWidth: 900+ spacing: 10+ clip: true+ model: page.rows+ boundsBehavior: Flickable.StopAtBounds+ delegate: Rectangle {+ id: row+ required property var modelData+ width: ListView.view.width+ height: 62+ radius: 12+ color: UI.Style.tone(0.045)+ border.width: 1+ border.color: UI.Style.tone(0.07)+ UI.Glyph {+ x: 18+ anchors.verticalCenter: parent.verticalCenter+ width: 18+ height: 18+ path: RemoteIcons.forward+ color: UI.Style.accent+ }+ Column {+ x: 50+ anchors.verticalCenter: parent.verticalCenter+ spacing: 4+ UI.Label {+ text: qsTr("localhost:%1 to %2:%3").arg(row.modelData.forward.localPort).arg(row.modelData.forward.remoteHost || "localhost").arg(row.modelData.forward.remotePort)+ size: 14+ font.family: "JetBrains Mono"+ font.weight: Font.DemiBold+ }+ UI.Label {+ text: qsTr("Through %1").arg(row.modelData.host.name)+ size: 13+ color: UI.Style.inkMuted+ }+ }+ UI.Button {+ anchors.right: parent.right+ anchors.rightMargin: 14+ anchors.verticalCenter: parent.verticalCenter+ size: "small"+ text: qsTr("Edit host")+ onClicked: page.editHost(row.modelData.host.id)+ }+ }+ footer: UI.Label {+ visible: page.rows.length === 0+ width: ListView.view.width+ topPadding: 40+ horizontalAlignment: Text.AlignHCenter+ text: qsTr("No forwards yet")+ size: 18+ font.weight: Font.DemiBold+ }+ }+ }+}diff --git a/packages/wildos-remote/qml/HostChangedDialog.qml b/packages/wildos-remote/qml/HostChangedDialog.qmlnew file mode 100644index 0000000..3ce2cc3--- /dev/null+++ b/packages/wildos-remote/qml/HostChangedDialog.qml@@ -0,0 +1,177 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Remote+import WildOS.UI as UI++// The server isn't the one Remote knew (RemoteHostChanged.dc). Not+// connecting is the big button; trusting the new identity is the small red+// one, and nothing changes in known_hosts (or FreeRDP's store) unless it is+// pressed.+Panel {+ id: dialog++ property var host: ({})+ property var result: ({})+ property string kind: "ssh"++ signal rebuilt(var host, var result)+ signal refused()++ width: 500+ padding: 28++ function ask(h, r) {+ host = h;+ result = r;+ kind = "ssh";+ open();+ }+ function askCertificate(h, r) {+ host = h;+ result = r;+ kind = "rdp";+ open();+ }++ function shortFingerprint(fp) {+ if (!fp) {+ return "";+ }+ // SHA256:Kd7f…pR2a, as the board shows it; the whole of each is in+ // its tooltip.+ const body = fp.startsWith("SHA256:") ? fp.substring(7) : fp.replace(/:/g, "");+ return (fp.startsWith("SHA256:") ? "SHA256:" : "") + body.substring(0, 4) + "…" + body.substring(body.length - 4);+ }+ readonly property var previous: (result.previous || [])[0] || {}++ contentItem: ColumnLayout {+ spacing: 16++ Rectangle {+ Layout.alignment: Qt.AlignHCenter+ Layout.preferredWidth: 56+ Layout.preferredHeight: 56+ radius: 14+ color: Qt.rgba(255 / 255, 154 / 255, 138 / 255, 0.16)+ UI.Icon {+ anchors.centerIn: parent+ name: "shield-alert"+ size: 26+ strokeWidth: 1.8+ color: "#ff9a8a"+ }+ }+ UI.Label {+ Layout.fillWidth: true+ horizontalAlignment: Text.AlignHCenter+ text: dialog.kind === "ssh" ? qsTr("%1 isn't the same server").arg(dialog.host.name || "") : qsTr("%1 isn't the same computer").arg(dialog.host.name || "")+ size: 20+ font.weight: Font.Bold+ wrapMode: Text.Wrap+ }+ UI.Label {+ Layout.fillWidth: true+ horizontalAlignment: Text.AlignHCenter+ text: dialog.kind === "ssh"+ ? qsTr("Its identity has changed since you last connected. That's normal after a server is rebuilt or reinstalled. If nobody did that, someone could be listening in, so don't connect.")+ : qsTr("Its identity has changed since you last connected. That's normal after Windows is reinstalled or its certificate is renewed. If nobody did that, someone could be listening in, so don't connect.")+ size: 14+ color: UI.Style.inkStatus+ wrapMode: Text.Wrap+ lineHeight: 1.4+ }+ Rectangle {+ Layout.fillWidth: true+ implicitHeight: compare.implicitHeight + 8+ radius: 12+ color: UI.Style.surfaceRest+ border.width: 1+ border.color: UI.Style.borderSubtle+ GridLayout {+ id: compare+ anchors.left: parent.left+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ anchors.leftMargin: 16+ anchors.rightMargin: 16+ columns: 3+ rowSpacing: 0+ columnSpacing: 16++ UI.Label { Layout.preferredHeight: 40; text: qsTr("Last time"); size: 14; color: UI.Style.inkMuted }+ UI.Label {+ Layout.fillWidth: true+ Layout.preferredHeight: 40+ text: dialog.shortFingerprint(dialog.previous.fingerprint)+ size: 13+ font.family: "JetBrains Mono"+ font.weight: Font.DemiBold+ UI.Tooltip { text: dialog.previous.fingerprint || ""; visible: lastMouse.containsMouse }+ MouseArea { id: lastMouse; anchors.fill: parent; hoverEnabled: true }+ }+ UI.Label {+ Layout.preferredHeight: 40+ text: dialog.previous.seen ? qsTr("Seen %1").arg(dialog.previous.seen) : ""+ size: 13+ color: UI.Style.inkMuted+ }+ UI.Label { Layout.preferredHeight: 40; text: qsTr("Now"); size: 14; color: UI.Style.inkMuted }+ UI.Label {+ Layout.fillWidth: true+ Layout.preferredHeight: 40+ text: dialog.shortFingerprint(dialog.result.fingerprint)+ size: 13+ font.family: "JetBrains Mono"+ font.weight: Font.DemiBold+ color: "#ff9a8a"+ UI.Tooltip { text: dialog.result.fingerprint || ""; visible: nowMouse.containsMouse }+ MouseArea { id: nowMouse; anchors.fill: parent; hoverEnabled: true }+ }+ UI.Label {+ Layout.preferredHeight: 40+ text: qsTr("Different")+ size: 13+ color: "#ff9a8a"+ }+ }+ }+ UI.Button {+ Layout.fillWidth: true+ size: "large"+ kind: "primary"+ text: qsTr("Don't connect")+ focus: true+ onClicked: dialog.close()+ }+ UI.Label {+ id: trustLink+ Layout.alignment: Qt.AlignHCenter+ text: dialog.kind === "ssh" ? qsTr("It was rebuilt, trust the new identity") : qsTr("It was reinstalled, trust the new identity")+ size: 14+ font.weight: Font.DemiBold+ font.underline: trustMouse.containsMouse || trustLink.activeFocus+ color: "#ff9a8a"+ activeFocusOnTab: true+ Accessible.role: Accessible.Button+ Accessible.name: text+ Keys.onReturnPressed: trustMouse.clicked(null)+ Keys.onSpacePressed: trustMouse.clicked(null)+ MouseArea {+ id: trustMouse+ anchors.fill: parent+ anchors.margins: -6+ hoverEnabled: true+ cursorShape: Qt.PointingHandCursor+ onClicked: {+ dialog.answered = true;+ dialog.close();+ dialog.rebuilt(dialog.host, dialog.result);+ }+ }+ }+ }++ property bool answered: false+ onAboutToShow: answered = false+ onClosed: if (!answered) refused()+}diff --git a/packages/wildos-remote/qml/HostDialog.qml b/packages/wildos-remote/qml/HostDialog.qmlnew file mode 100644index 0000000..bb666d6--- /dev/null+++ b/packages/wildos-remote/qml/HostDialog.qml@@ -0,0 +1,660 @@+import QtQuick+import QtQuick.Dialogs+import QtQuick.Layouts+import WildOS.Remote+import WildOS.UI as UI++// A new host, or changes to one (RemoteNew.dc). Desktops: the computer,+// how to sign in, how to show it, and what it may reach of this PC.+// Terminals: the server, the account and key, ports to forward and the+// colour of its tab.+Panel {+ id: dialog++ property var host: ({})+ property string kind: "desktop"+ property bool editing: false+ property var forwards: []++ signal saved(string id, bool connect)++ width: Math.min(900, parent ? parent.width - 48 : 900)+ padding: 28+ topPadding: 26++ function create(k) {+ editing = false;+ host = {};+ kind = k || "desktop";+ load();+ open();+ address.forceActiveFocus();+ }+ function edit(id) {+ const h = Hosts.host(id);+ if (!h.id) {+ return;+ }+ editing = true;+ host = h;+ kind = h.kind;+ load();+ open();+ }+ function load() {+ const h = host;+ const d = h.desktop || {};+ const s = h.ssh || {};+ address.text = h.address || "";+ name.text = h.name && h.name !== h.address ? h.name : "";+ group.currentIndex = Math.max(0, groupModel.findIndex(o => o.value === (h.group || "")));+ user.text = h.user || "";+ note.text = h.note || "";+ passwordMode = d.password || "ask";+ display = d.display || "full";+ resolution.currentIndex = Math.max(0, resolutionModel.findIndex(o => o.value === (d.resolution || "match")));+ scaling.currentIndex = Math.max(0, scalingModel.findIndex(o => o.value === (d.scaling || "auto")));+ clipboard.checked = d.clipboard !== false;+ sound.checked = d.sound !== false;+ microphone.checked = d.microphone === true;+ printers.checked = d.printers === true;+ folders.checked = d.folders === true;+ folderPath = d.folderPath || App.homePath() + "/Downloads";+ gateway.text = d.gateway || "";+ speed.currentIndex = Math.max(0, speedModel.findIndex(o => o.value === (d.speed || "auto")));+ advanced = (d.gateway || "").length > 0;+ forwards = (s.forwards || []).slice();+ colour = s.colour || Hosts.colours()[0];+ identity.currentIndex = Math.max(0, identityModel.findIndex(o => o.value === (s.identity || "")));+ }+ function collect() {+ const out = Object.assign({}, host);+ out.kind = kind;+ out.address = address.text.trim();+ out.name = name.text.trim() || out.address.split(":")[0];+ out.group = group.currentValue || "";+ out.user = user.text.trim();+ out.note = note.text.trim();+ if (kind === "desktop") {+ out.desktop = Object.assign({}, host.desktop || {}, {+ password: passwordMode,+ display: display,+ resolution: resolution.currentValue,+ scaling: scaling.currentValue,+ clipboard: clipboard.checked,+ sound: sound.checked,+ microphone: microphone.checked,+ printers: printers.checked,+ folders: folders.checked,+ folderPath: folderPath,+ gateway: gateway.text.trim(),+ speed: speed.currentValue+ });+ } else {+ out.ssh = Object.assign({}, host.ssh || {}, {+ identity: identity.currentValue || "",+ forwards: forwards,+ colour: colour+ });+ }+ return out;+ }+ function save(connect) {+ if (kind === "desktop" && passwordMode === "ask" && host.desktop && host.desktop.password === "keyring") {+ // Asking every time from now on: the saved password goes.+ Secrets.remove("desktop:" + host.id);+ }+ const id = Hosts.save(collect());+ close();+ saved(id, connect);+ }++ property string passwordMode: "ask"+ property string display: "full"+ property string folderPath+ property bool advanced: false+ property string colour: "#5fd39a"++ readonly property var groupModel: [{ value: "", text: qsTr("No group") }].concat(Hosts.groups.map(g => ({ value: g, text: g })))+ readonly property var resolutionModel: [+ { value: "match", text: qsTr("Match my screen") },+ { value: "1920x1080", text: "1920 × 1080" },+ { value: "1600x900", text: "1600 × 900" },+ { value: "1366x768", text: "1366 × 768" },+ { value: "1280x720", text: "1280 × 720" }+ ]+ readonly property var scalingModel: [+ { value: "auto", text: qsTr("Automatic") },+ { value: "100", text: "100%" },+ { value: "125", text: "125%" },+ { value: "150", text: "150%" },+ { value: "200", text: "200%" }+ ]+ readonly property var speedModel: [+ { value: "auto", text: qsTr("Work it out") },+ { value: "lan", text: qsTr("Fast network") },+ { value: "broadband", text: qsTr("Home broadband") },+ { value: "modem", text: qsTr("Slow connection") }+ ]+ readonly property var identityModel: [{ value: "", text: qsTr("Any key in my keychain") }].concat(Keychain.keys.map(k => ({ value: k.path, text: k.label })))++ contentItem: ColumnLayout {+ spacing: 18++ // Heading+ RowLayout {+ Layout.fillWidth: true+ spacing: 14+ Image {+ Layout.preferredWidth: 40+ Layout.preferredHeight: 40+ source: "qrc:/qt/qml/WildOS/Remote/data/org.wildos.remote.svg"+ sourceSize: Qt.size(80, 80)+ }+ ColumnLayout {+ Layout.fillWidth: true+ spacing: 2+ UI.Label {+ text: dialog.editing ? qsTr("Edit %1").arg(dialog.host.name) : dialog.kind === "desktop" ? qsTr("New connection") : qsTr("New host")+ size: 22+ font.weight: Font.Bold+ }+ UI.Label {+ text: dialog.kind === "desktop" ? qsTr("Connect to a Windows PC or server with Remote Desktop switched on")+ : qsTr("Connect to a server over SSH, in a terminal with its files beside it")+ size: 14+ color: UI.Style.inkMuted+ }+ }+ Segments {+ visible: !dialog.editing+ Layout.alignment: Qt.AlignTop+ options: [{ value: "desktop", text: qsTr("Desktop") }, { value: "terminal", text: qsTr("Terminal") }]+ value: dialog.kind+ onChosen: v => dialog.kind = v+ }+ }++ RowLayout {+ Layout.fillWidth: true+ spacing: 32++ // Left: the computer and signing in.+ ColumnLayout {+ Layout.preferredWidth: 1+ Layout.fillWidth: true+ Layout.alignment: Qt.AlignTop+ spacing: 8++ Heading { text: dialog.kind === "desktop" ? qsTr("Computer") : qsTr("Server") }+ FieldLabel { text: qsTr("Address") }+ UI.TextField {+ id: address+ Layout.fillWidth: true+ size: "large"+ leftPadding: 40+ placeholderText: dialog.kind === "desktop" ? "studio-02.office.lan" : "web-01.hosting.lan"+ UI.Icon {+ x: 14+ anchors.verticalCenter: parent.verticalCenter+ name: dialog.kind === "desktop" ? "monitor" : "terminal"+ size: 15+ color: UI.Style.iconMuted+ }+ }+ UI.Label {+ text: dialog.kind === "desktop" ? qsTr("A name or IP address. Add :port if it isn't 3389")+ : qsTr("A name or IP address. Add :port if it isn't 22")+ size: 12+ color: UI.Style.inkSubtle+ }+ RowLayout {+ Layout.fillWidth: true+ Layout.topMargin: 4+ spacing: 12+ ColumnLayout {+ Layout.fillWidth: true+ spacing: 8+ FieldLabel { text: qsTr("Name") }+ UI.TextField {+ id: name+ Layout.fillWidth: true+ size: "large"+ placeholderText: address.text.split(":")[0] || qsTr("Studio 2")+ }+ }+ ColumnLayout {+ Layout.preferredWidth: 156+ spacing: 8+ FieldLabel { text: qsTr("Group") }+ UI.ComboBox {+ id: group+ Layout.fillWidth: true+ look: "field"+ model: dialog.groupModel+ }+ }+ }++ Heading { text: qsTr("Signing in"); Layout.topMargin: 10 }+ FieldLabel { text: qsTr("Username") }+ UI.TextField {+ id: user+ Layout.fillWidth: true+ size: "large"+ leftPadding: 40+ placeholderText: dialog.kind === "desktop" ? "administrator" : "alex"+ UI.Icon {+ x: 14+ anchors.verticalCenter: parent.verticalCenter+ name: "account"+ size: 15+ color: UI.Style.iconMuted+ }+ }+ Segments {+ visible: dialog.kind === "desktop"+ Layout.fillWidth: true+ options: [{ value: "ask", text: qsTr("Ask every time") }, { value: "keyring", text: qsTr("Save in keyring") }]+ value: dialog.passwordMode+ onChosen: v => dialog.passwordMode = v+ }+ UI.Label {+ visible: dialog.kind === "desktop" && dialog.passwordMode === "keyring"+ Layout.fillWidth: true+ text: qsTr("You type it once when you first connect; it's kept in your keyring, never in a file.")+ size: 12+ color: UI.Style.inkSubtle+ wrapMode: Text.Wrap+ }+ ColumnLayout {+ visible: dialog.kind === "terminal"+ Layout.fillWidth: true+ spacing: 8+ FieldLabel { text: qsTr("Key") }+ UI.ComboBox {+ id: identity+ Layout.fillWidth: true+ look: "field"+ model: dialog.identityModel+ }+ UI.Label {+ Layout.fillWidth: true+ text: identity.currentIndex === 0+ ? qsTr("ssh tries your keys and the key agent, then asks for a password in the terminal.")+ : qsTr("Only this key is offered to the server.")+ size: 12+ color: UI.Style.inkSubtle+ wrapMode: Text.Wrap+ }+ }++ Heading { text: dialog.kind === "desktop" ? qsTr("Display") : qsTr("Card"); Layout.topMargin: 10 }+ Segments {+ visible: dialog.kind === "desktop"+ Layout.fillWidth: true+ options: [{ value: "window", text: qsTr("Window") }, { value: "full", text: qsTr("Full screen") }, { value: "all", text: qsTr("All monitors") }]+ value: dialog.display+ onChosen: v => dialog.display = v+ }+ RowLayout {+ visible: dialog.kind === "desktop"+ Layout.fillWidth: true+ Layout.topMargin: 4+ spacing: 12+ ColumnLayout {+ Layout.fillWidth: true+ spacing: 8+ FieldLabel { text: qsTr("Resolution") }+ UI.ComboBox {+ id: resolution+ Layout.fillWidth: true+ look: "field"+ model: dialog.resolutionModel+ }+ }+ ColumnLayout {+ Layout.fillWidth: true+ spacing: 8+ FieldLabel { text: qsTr("Scaling") }+ UI.ComboBox {+ id: scaling+ Layout.fillWidth: true+ look: "field"+ model: dialog.scalingModel+ }+ }+ }+ ColumnLayout {+ visible: dialog.kind === "terminal"+ Layout.fillWidth: true+ spacing: 8+ FieldLabel { text: qsTr("Note") }+ UI.TextField {+ id: note+ Layout.fillWidth: true+ size: "large"+ placeholderText: qsTr("Shown on its card, like Ubuntu 24.04")+ }+ Row {+ Layout.topMargin: 6+ spacing: 8+ Repeater {+ model: Hosts.colours()+ Rectangle {+ required property string modelData+ width: 26+ height: 26+ radius: 13+ color: modelData+ border.width: dialog.colour === modelData ? 3 : 0+ border.color: UI.Style.ink+ Accessible.role: Accessible.RadioButton+ Accessible.name: qsTr("Tab colour")+ MouseArea {+ anchors.fill: parent+ cursorShape: Qt.PointingHandCursor+ onClicked: dialog.colour = parent.modelData+ }+ }+ }+ }+ }+ }++ // Right: what the remote PC may reach, or ports to forward.+ ColumnLayout {+ Layout.preferredWidth: 1+ Layout.fillWidth: true+ Layout.alignment: Qt.AlignTop+ spacing: 0++ Heading { text: dialog.kind === "desktop" ? qsTr("Share with this PC") : qsTr("Port forwarding") }+ UI.Label {+ Layout.fillWidth: true+ Layout.topMargin: 8+ Layout.bottomMargin: 10+ text: dialog.kind === "desktop"+ ? qsTr("Anything left off, the remote PC can't reach. Changes made from the toolbar during a session take effect when it reconnects.")+ : qsTr("Reach a port on the server, or a machine it can see, as if it were on this PC. Only this PC can use it, and only while the terminal is open.")+ size: 13+ color: UI.Style.inkMuted+ wrapMode: Text.Wrap+ lineHeight: 1.35+ }++ ColumnLayout {+ visible: dialog.kind === "desktop"+ Layout.fillWidth: true+ spacing: 0+ ShareRow { id: clipboard; title: qsTr("Clipboard"); detail: qsTr("Copy and paste both ways"); glyph: RemoteIcons.clipboard }+ ShareRow { id: sound; title: qsTr("Sound plays here"); detail: qsTr("Through this PC's speakers"); iconName: "sound" }+ ShareRow { id: microphone; title: qsTr("Microphone"); detail: qsTr("For calls on the remote PC"); iconName: "mic" }+ ShareRow { id: printers; title: qsTr("Printers"); detail: qsTr("Print from the remote PC to yours"); iconName: "printer" }+ ShareRow {+ id: folders+ title: qsTr("Folders")+ detail: dialog.folderPath.replace(App.homePath(), "~").split("/").pop() + qsTr(", the remote PC can change what's in it")+ glyph: RemoteIcons.folder+ UI.LinkButton {+ anchors.verticalCenter: parent.verticalCenter+ text: qsTr("Choose")+ onClicked: folderDialog.open()+ }+ }+ ShareRow {+ id: monitors+ title: qsTr("Use all my monitors")+ detail: qsTr("Only in full screen")+ glyph: RemoteIcons.displays+ checked: dialog.display === "all"+ onToggled: dialog.display = checked ? "all" : "full"+ }+ Item {+ Layout.fillWidth: true+ Layout.preferredHeight: 42+ Row {+ anchors.verticalCenter: parent.verticalCenter+ spacing: 10+ UI.Icon {+ anchors.verticalCenter: parent.verticalCenter+ name: dialog.advanced ? "chevron-down" : "chevron-right"+ size: 13+ color: UI.Style.iconMuted+ }+ UI.Label {+ text: qsTr("Advanced: gateway, connection speed")+ size: 14+ color: UI.Style.inkMuted+ }+ }+ MouseArea {+ anchors.fill: parent+ cursorShape: Qt.PointingHandCursor+ onClicked: dialog.advanced = !dialog.advanced+ }+ }+ GridLayout {+ visible: dialog.advanced+ Layout.fillWidth: true+ columns: 2+ columnSpacing: 12+ rowSpacing: 8+ FieldLabel { text: qsTr("Gateway") }+ FieldLabel { text: qsTr("Connection") }+ UI.TextField {+ id: gateway+ Layout.fillWidth: true+ placeholderText: qsTr("None")+ }+ UI.ComboBox {+ id: speed+ Layout.fillWidth: true+ model: dialog.speedModel+ }+ }+ }++ ColumnLayout {+ visible: dialog.kind === "terminal"+ Layout.fillWidth: true+ spacing: 8+ Repeater {+ model: dialog.forwards+ Rectangle {+ required property var modelData+ required property int index+ Layout.fillWidth: true+ Layout.preferredHeight: 44+ radius: 10+ color: UI.Style.surfaceRest+ border.width: 1+ border.color: UI.Style.borderSubtle+ UI.Glyph {+ x: 12+ anchors.verticalCenter: parent.verticalCenter+ width: 16+ height: 16+ path: RemoteIcons.forward+ color: UI.Style.accent+ }+ UI.Label {+ x: 38+ anchors.verticalCenter: parent.verticalCenter+ text: qsTr("localhost:%1 to %2:%3").arg(modelData.localPort).arg(modelData.remoteHost || "localhost").arg(modelData.remotePort)+ size: 13+ font.family: "JetBrains Mono"+ }+ UI.IconButton {+ anchors.right: parent.right+ anchors.rightMargin: 6+ anchors.verticalCenter: parent.verticalCenter+ iconName: "close"+ iconSize: 13+ width: 30+ height: 30+ tip: qsTr("Remove")+ onClicked: {+ const f = dialog.forwards.slice();+ f.splice(index, 1);+ dialog.forwards = f;+ }+ }+ }+ }+ RowLayout {+ Layout.fillWidth: true+ spacing: 8+ UI.TextField {+ id: localPort+ Layout.preferredWidth: 100+ placeholderText: qsTr("This PC's port")+ validator: IntValidator { bottom: 1024; top: 65535 }+ }+ UI.Label { text: qsTr("to"); size: 13; color: UI.Style.inkMuted }+ UI.TextField {+ id: remoteHost+ Layout.fillWidth: true+ placeholderText: "localhost"+ }+ UI.TextField {+ id: remotePort+ Layout.preferredWidth: 80+ placeholderText: qsTr("Port")+ validator: IntValidator { bottom: 1; top: 65535 }+ }+ UI.Button {+ text: qsTr("Add")+ enabled: localPort.acceptableInput && remotePort.acceptableInput+ onClicked: {+ dialog.forwards = dialog.forwards.concat([{+ localPort: parseInt(localPort.text),+ remoteHost: remoteHost.text.trim() || "localhost",+ remotePort: parseInt(remotePort.text)+ }]);+ localPort.text = "";+ remoteHost.text = "";+ remotePort.text = "";+ }+ }+ }+ UI.Label {+ Layout.fillWidth: true+ text: qsTr("Ports from 1024 up, so no administrator rights are needed.")+ size: 12+ color: UI.Style.inkSubtle+ }+ }+ }+ }++ RowLayout {+ Layout.fillWidth: true+ Layout.topMargin: 6+ spacing: 10+ Item { Layout.fillWidth: true }+ UI.Button {+ size: "large"+ text: qsTr("Cancel")+ onClicked: dialog.close()+ }+ UI.Button {+ size: "large"+ text: qsTr("Save")+ enabled: address.text.trim().length > 0+ onClicked: dialog.save(false)+ }+ UI.Button {+ size: "large"+ kind: "primary"+ text: qsTr("Save and connect")+ enabled: address.text.trim().length > 0+ onClicked: dialog.save(true)+ }+ }+ }++ FolderDialog {+ id: folderDialog+ title: qsTr("Choose a folder to share")+ currentFolder: "file://" + dialog.folderPath+ onAccepted: dialog.folderPath = decodeURIComponent(selectedFolder.toString().replace("file://", ""))+ }++ component Heading: UI.Label {+ size: 12+ font.weight: Font.Bold+ font.letterSpacing: 0.6+ font.capitalization: Font.AllUppercase+ color: UI.Style.inkMuted+ }+ component FieldLabel: UI.Label {+ size: 13+ font.weight: Font.DemiBold+ }+ component ShareRow: Item {+ id: shareRow+ property string title+ property string detail+ property string iconName+ property string glyph+ property alias checked: toggle.checked+ default property alias extra: extraRow.data+ signal toggled()++ Layout.fillWidth: true+ Layout.preferredHeight: 52++ Rectangle {+ width: parent.width+ height: 1+ color: UI.Style.divider+ }+ UI.Icon {+ visible: shareRow.glyph.length === 0+ anchors.verticalCenter: parent.verticalCenter+ name: shareRow.iconName+ size: 16+ color: UI.Style.iconMuted+ }+ UI.Glyph {+ visible: shareRow.glyph.length > 0+ anchors.verticalCenter: parent.verticalCenter+ width: 16+ height: 16+ path: shareRow.glyph+ color: UI.Style.iconMuted+ }+ Column {+ x: 29+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - 29 - toggle.width - extraRow.width - 20+ spacing: 2+ UI.Label {+ width: parent.width+ text: shareRow.title+ size: 14+ font.weight: Font.DemiBold+ }+ UI.Label {+ width: parent.width+ text: shareRow.detail+ size: 12+ color: UI.Style.inkMuted+ }+ }+ Row {+ id: extraRow+ anchors.right: toggle.left+ anchors.rightMargin: 14+ anchors.verticalCenter: parent.verticalCenter+ }+ UI.Toggle {+ id: toggle+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ Accessible.name: shareRow.title+ onToggled: shareRow.toggled()+ }+ }+}diff --git a/packages/wildos-remote/qml/HostKeyDialog.qml b/packages/wildos-remote/qml/HostKeyDialog.qmlnew file mode 100644index 0000000..fc605a8--- /dev/null+++ b/packages/wildos-remote/qml/HostKeyDialog.qml@@ -0,0 +1,150 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Remote+import WildOS.UI as UI++// The first connection to a server or PC (RemoteCheck.dc): nothing vouches+// for it yet, so its fingerprint is shown to check against the one the+// server shows its own administrator.+//+// For SSH the key goes into known_hosts when the person connects: ssh only+// connects to servers whose key is there, and that is what lets Remote+// warn if it ever changes. For a desktop the person can choose to remember+// the certificate (FreeRDP keeps it) or trust it for this session only.+Panel {+ id: dialog++ property var host: ({})+ property var result: ({})+ // "ssh" or "rdp"+ property string kind: "ssh"+ property bool remember: true++ signal accepted(var host, var result)+ signal declined()++ width: 520+ padding: 28++ function ask(h, r) {+ host = h;+ result = r;+ kind = "ssh";+ remember = true;+ open();+ }+ function askCertificate(h, r) {+ host = h;+ result = r;+ kind = "rdp";+ remember = true;+ open();+ }++ readonly property var rows: kind === "ssh" ? [+ { label: qsTr("Server"), value: result.name || "" },+ { label: qsTr("Key type"), value: result.keyType || "" },+ { label: qsTr("Fingerprint"), value: result.fingerprint || "", wide: true }+ ] : [+ { label: qsTr("Computer"), value: result.host || "" },+ { label: qsTr("Calls itself"), value: result.commonName || qsTr("No name given") },+ { label: qsTr("Identity issued by"), value: result.selfSigned ? qsTr("Itself (normal for most PCs)") : (result.issuer || "") },+ { label: qsTr("Valid until"), value: result.validUntil || "", colour: result.expired ? UI.Style.danger : "" },+ { label: qsTr("Fingerprint"), value: result.fingerprint || "", wide: true }+ ]++ contentItem: ColumnLayout {+ spacing: 16++ Rectangle {+ Layout.alignment: Qt.AlignHCenter+ Layout.preferredWidth: 56+ Layout.preferredHeight: 56+ radius: 14+ color: UI.Style.tone(0.08)+ UI.Icon {+ anchors.centerIn: parent+ name: "shield"+ size: 26+ strokeWidth: 1.8+ color: "#ffc46a"+ }+ }+ UI.Label {+ Layout.fillWidth: true+ horizontalAlignment: Text.AlignHCenter+ text: dialog.kind === "ssh" ? qsTr("Is this the right server?") : qsTr("Is this the right computer?")+ size: 20+ font.weight: Font.Bold+ }+ UI.Label {+ Layout.fillWidth: true+ horizontalAlignment: Text.AlignHCenter+ text: qsTr("This is your first time connecting to %1, so Remote can't vouch for it yet. If you can, check the fingerprint below matches the one on the %2.")+ .arg(dialog.host.name || "").arg(dialog.kind === "ssh" ? qsTr("server") : qsTr("PC"))+ size: 14+ color: UI.Style.inkStatus+ wrapMode: Text.Wrap+ lineHeight: 1.4+ }+ UI.Label {+ visible: dialog.kind === "rdp" && dialog.result.mismatch === true+ Layout.fillWidth: true+ horizontalAlignment: Text.AlignHCenter+ text: dialog.result.commonName+ ? qsTr("Its certificate is made out to %1, not to the address you typed.").arg(dialog.result.commonName)+ : qsTr("Its certificate doesn't name any computer, so only the fingerprint can say it's the right one.")+ size: 13+ color: UI.Style.warning+ wrapMode: Text.Wrap+ }+ InfoRows {+ Layout.fillWidth: true+ rows: dialog.rows+ }+ RowLayout {+ Layout.fillWidth: true+ spacing: 12+ UI.Toggle {+ visible: dialog.kind === "rdp"+ checked: dialog.remember+ onToggled: dialog.remember = checked+ Accessible.name: rememberLabel.text+ }+ UI.Label {+ id: rememberLabel+ Layout.fillWidth: true+ text: dialog.kind === "rdp" ? qsTr("Remember this computer and warn me if it ever changes")+ : qsTr("Connecting adds it to your known hosts, so Remote can warn you if it ever changes.")+ size: dialog.kind === "rdp" ? 14 : 13+ color: dialog.kind === "rdp" ? UI.Style.ink : UI.Style.inkMuted+ wrapMode: Text.Wrap+ }+ }+ RowLayout {+ Layout.fillWidth: true+ spacing: 10+ Item { Layout.fillWidth: true }+ UI.Button {+ size: "large"+ text: qsTr("Cancel")+ onClicked: dialog.close()+ }+ UI.Button {+ size: "large"+ kind: "primary"+ text: qsTr("Connect")+ onClicked: {+ dialog.answered = true;+ dialog.close();+ dialog.accepted(dialog.host, Object.assign({}, dialog.result, { remember: dialog.remember }));+ }+ }+ }+ }++ // Cancel, Escape or anything else that closes it is a no.+ property bool answered: false+ onAboutToShow: answered = false+ onClosed: if (!answered) declined()+}diff --git a/packages/wildos-remote/qml/HostsPage.qml b/packages/wildos-remote/qml/HostsPage.qmlnew file mode 100644index 0000000..5226b9a--- /dev/null+++ b/packages/wildos-remote/qml/HostsPage.qml@@ -0,0 +1,515 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Remote+import WildOS.UI as UI++// The hosts (RemoteHosts.dc): terminal and desktop hosts together, by+// group, with All, Terminal and Desktop to narrow them. Above them, the+// desktops used last with the screen they ended on (RemoteStart.dc).+Item {+ id: page++ property string view: "hosts"+ property string search+ property string filter: "all"++ signal connectHost(string id)+ signal hostMenu(string id, Item item, real x, real y)+ signal newHost(string kind)++ readonly property string title: view === "favourites" ? qsTr("Favourites")+ : view.startsWith("group:") ? view.substring(6) : qsTr("All hosts")++ function matches(h) {+ if (view === "favourites" && !h.favourite) {+ return false;+ }+ if (view.startsWith("group:") && h.group !== view.substring(6)) {+ return false;+ }+ if (filter !== "all" && h.kind !== filter) {+ return false;+ }+ const q = search.trim().toLowerCase();+ if (q.length > 0) {+ const hay = (h.name + " " + h.address + " " + h.user + " " + (h.note || "")).toLowerCase();+ return hay.indexOf(q) >= 0;+ }+ return true;+ }+ // [{ name, hosts }], in the order of the groups, then hosts without one.+ readonly property var sections: {+ Hosts.revision;+ const out = [];+ const groups = Hosts.groups.slice();+ const all = Hosts.hosts.filter(h => page.matches(h));+ for (const g of groups) {+ const list = all.filter(h => h.group === g);+ if (list.length > 0) {+ out.push({ name: g, hosts: list });+ }+ }+ const loose = all.filter(h => !h.group || groups.indexOf(h.group) < 0);+ if (loose.length > 0) {+ out.push({ name: groups.length > 0 && out.length > 0 ? qsTr("Other") : "", hosts: loose });+ }+ return out;+ }+ readonly property int shownCount: {+ let n = 0;+ for (const s of sections) {+ n += s.hosts.length;+ }+ return n;+ }+ readonly property var recent: {+ Hosts.revision;+ if (filter === "terminal" || search.length > 0 || view !== "hosts") {+ return [];+ }+ return Hosts.hosts.filter(h => h.kind === "desktop" && h.lastUsed)+ .sort((a, b) => b.lastUsed.localeCompare(a.lastUsed)).slice(0, 3);+ }+ onRecentChanged: {+ for (const h of recent) {+ Hosts.probe(h.id);+ }+ }++ function lastUsedText(iso) {+ if (!iso) {+ return qsTr("Not used yet");+ }+ const d = new Date(iso);+ const now = new Date();+ const day = new Date(now.getFullYear(), now.getMonth(), now.getDate());+ const then = new Date(d.getFullYear(), d.getMonth(), d.getDate());+ const days = Math.round((day - then) / 86400000);+ if (days === 0) {+ return qsTr("Last used Today, %1").arg(d.toLocaleTimeString(Qt.locale(), Locale.ShortFormat));+ }+ if (days === 1) {+ return qsTr("Last used Yesterday");+ }+ if (days < 7) {+ return qsTr("Last used %1").arg(Qt.locale("en_GB").dayName(d.getDay(), Locale.ShortFormat));+ }+ return qsTr("Last used %1").arg(d.toLocaleDateString(Qt.locale(), Locale.ShortFormat));+ }+ function addressText(h) {+ return h.user ? qsTr("%1 on %2").arg(h.user).arg(h.address) : h.address;+ }+ function detailText(h) {+ if (h.note) {+ return h.note;+ }+ if (h.kind === "terminal") {+ const f = h.ssh.forwards || [];+ if (f.length > 0) {+ return qsTr("Forwards %1").arg(f.map(x => x.localPort).join(", "));+ }+ return h.ssh.identity ? qsTr("Key only") : "";+ }+ return "";+ }++ Flickable {+ id: flick+ anchors.fill: parent+ contentHeight: content.height + 40+ clip: true+ boundsBehavior: Flickable.StopAtBounds++ Column {+ id: content+ x: 36+ y: 22+ width: flick.width - 72+ spacing: 0++ Item {+ width: parent.width+ height: 44++ UI.Label {+ anchors.verticalCenter: parent.verticalCenter+ text: page.title+ size: 26+ font.weight: Font.Bold+ }+ Row {+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ spacing: 8+ Repeater {+ model: [{ v: "all", t: qsTr("All") }, { v: "terminal", t: qsTr("Terminal") }, { v: "desktop", t: qsTr("Desktop") }]+ Pill {+ required property var modelData+ text: modelData.t+ checked: page.filter === modelData.v+ onClicked: page.filter = modelData.v+ }+ }+ }+ }++ // Recent desktops, with their last screens.+ Column {+ visible: page.recent.length > 0+ width: parent.width+ spacing: 12+ topPadding: 8+ bottomPadding: 18++ Item {+ width: parent.width+ height: 24+ UI.Label {+ anchors.verticalCenter: parent.verticalCenter+ text: qsTr("Recent")+ size: 18+ font.weight: Font.Bold+ }+ UI.Label {+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ text: qsTr("Screens are from the end of your last session, kept on this PC only")+ size: 13+ color: UI.Style.inkMuted+ }+ }+ Row {+ spacing: 22+ Repeater {+ model: page.recent+ RecentCard {+ required property var modelData+ width: (content.width - 44) / 3+ host: modelData+ }+ }+ }+ }++ Repeater {+ model: page.sections+ Column {+ id: section+ required property var modelData+ width: content.width+ spacing: 12+ topPadding: 6+ bottomPadding: 16++ Row {+ visible: section.modelData.name.length > 0+ spacing: 10+ UI.Label {+ text: section.modelData.name+ size: 18+ font.weight: Font.Bold+ }+ UI.Label {+ anchors.baseline: parent.children[0].baseline+ text: section.modelData.hosts.length === 1 ? qsTr("1 host") : qsTr("%1 hosts").arg(section.modelData.hosts.length)+ size: 13+ color: UI.Style.inkSubtle+ }+ }+ Grid {+ columns: Math.max(1, Math.floor((content.width + 14) / 340))+ columnSpacing: 14+ rowSpacing: 14+ Repeater {+ model: section.modelData.hosts+ HostCard {+ required property var modelData+ width: (content.width - 14 * (parent.columns - 1)) / parent.columns+ host: modelData+ }+ }+ }+ }+ }++ // Nothing saved yet, or nothing matches.+ Column {+ visible: page.shownCount === 0+ width: parent.width+ topPadding: 80+ spacing: 14+ UI.Label {+ anchors.horizontalCenter: parent.horizontalCenter+ text: Hosts.hosts.length === 0 ? qsTr("Connect to another computer") : qsTr("Nothing here matches")+ size: 20+ font.weight: Font.DemiBold+ }+ UI.Label {+ anchors.horizontalCenter: parent.horizontalCenter+ width: Math.min(parent.width, 520)+ horizontalAlignment: Text.AlignHCenter+ wrapMode: Text.Wrap+ text: Hosts.hosts.length === 0+ ? qsTr("Add a Windows PC or server with Remote Desktop switched on, or a server you reach over SSH. You can also type an address like alex@web-01 in the box above.")+ : qsTr("Try another name, or type an address above to connect to it.")+ size: 14+ color: UI.Style.inkMuted+ lineHeight: 1.4+ }+ Row {+ visible: Hosts.hosts.length === 0+ anchors.horizontalCenter: parent.horizontalCenter+ spacing: 10+ topPadding: 6+ UI.Button {+ text: qsTr("New desktop")+ iconName: "monitor"+ onClicked: page.newHost("desktop")+ }+ UI.Button {+ text: qsTr("New SSH host")+ iconName: "terminal"+ onClicked: page.newHost("terminal")+ }+ }+ }+ }+ }++ component Pill: Rectangle {+ id: pill+ property string text+ property bool checked+ signal clicked()+ width: pillLabel.implicitWidth + 26+ height: 30+ radius: 15+ color: checked ? UI.Style.accent : pillMouse.containsMouse ? UI.Style.surfaceHover : UI.Style.surfaceControl+ Accessible.role: Accessible.RadioButton+ Accessible.name: text+ Accessible.checked: checked+ UI.Label {+ id: pillLabel+ anchors.centerIn: parent+ text: pill.text+ size: 13+ font.weight: Font.DemiBold+ color: pill.checked ? UI.Style.textOnAccent : UI.Style.ink+ }+ MouseArea {+ id: pillMouse+ anchors.fill: parent+ hoverEnabled: true+ cursorShape: Qt.PointingHandCursor+ onClicked: pill.clicked()+ }+ }++ component HostCard: Rectangle {+ id: card+ property var host+ readonly property bool desktop: host.kind === "desktop"+ readonly property color tint: desktop ? "#8fb4ff" : (host.ssh.colour || "#5fd39a")++ height: 74+ radius: 12+ color: cardMouse.containsMouse ? UI.Style.tone(0.07) : UI.Style.tone(0.045)+ border.width: 1+ border.color: UI.Style.tone(0.07)+ Accessible.role: Accessible.Button+ Accessible.name: host.name++ Rectangle {+ x: 14+ anchors.verticalCenter: parent.verticalCenter+ width: 42+ height: 42+ radius: 10+ color: Qt.rgba(card.tint.r, card.tint.g, card.tint.b, 0.15)+ UI.Icon {+ anchors.centerIn: parent+ name: card.desktop ? "monitor" : "terminal"+ size: 19+ strokeWidth: 1.8+ color: card.tint+ }+ }+ Column {+ x: 70+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - 70 - rightCol.width - 18+ spacing: 4+ Row {+ spacing: 6+ width: parent.width+ UI.Label {+ text: card.host.name+ size: 15+ font.weight: Font.DemiBold+ width: Math.min(implicitWidth, parent.width - 20)+ }+ UI.Icon {+ visible: card.host.favourite === true+ anchors.verticalCenter: parent.verticalCenter+ name: "star"+ size: 13+ color: "#ffc46a"+ }+ }+ UI.Label {+ width: parent.width+ text: page.addressText(card.host)+ size: 13+ color: UI.Style.inkMuted+ }+ }+ Column {+ id: rightCol+ anchors.right: parent.right+ anchors.rightMargin: 14+ anchors.verticalCenter: parent.verticalCenter+ spacing: 5+ Rectangle {+ anchors.right: parent.right+ width: kindLabel.implicitWidth + 14+ height: 20+ radius: 5+ color: UI.Style.tone(0.08)+ UI.Label {+ id: kindLabel+ anchors.centerIn: parent+ text: card.desktop ? qsTr("Desktop") : qsTr("Terminal")+ size: 11+ font.weight: Font.DemiBold+ color: UI.Style.inkMuted+ }+ }+ UI.Label {+ anchors.right: parent.right+ text: page.detailText(card.host)+ size: 12+ color: UI.Style.inkSubtle+ }+ }+ MouseArea {+ id: cardMouse+ anchors.fill: parent+ hoverEnabled: true+ acceptedButtons: Qt.LeftButton | Qt.RightButton+ cursorShape: Qt.PointingHandCursor+ onClicked: m => m.button === Qt.RightButton ? page.hostMenu(card.host.id, card, m.x, m.y) : page.connectHost(card.host.id)+ }+ }++ component RecentCard: Rectangle {+ id: recentCard+ property var host+ readonly property string reach: Hosts.reach[host.id] || ""+ readonly property url screen: { Hosts.revision; return Hosts.screenUrl(host.id); }++ height: 282+ radius: 14+ color: UI.Style.tone(0.045)+ border.width: 1+ border.color: UI.Style.tone(0.08)+ clip: true++ Rectangle {+ id: shot+ width: parent.width+ height: 194+ topLeftRadius: 14+ topRightRadius: 14+ color: Qt.rgba(13 / 255, 21 / 255, 48 / 255, 1)+ clip: true+ Image {+ anchors.fill: parent+ source: recentCard.screen+ fillMode: Image.PreserveAspectCrop+ asynchronous: true+ sourceSize.width: 720+ }+ UI.Icon {+ visible: recentCard.screen.toString().length === 0+ anchors.centerIn: parent+ name: "monitor"+ size: 40+ strokeWidth: 1.4+ color: UI.Style.tone(0.25)+ }+ Rectangle {+ visible: recentCard.reach.length > 0+ x: 12+ y: 12+ width: reachRow.implicitWidth + 16+ height: 24+ radius: 12+ color: Qt.rgba(8 / 255, 12 / 255, 28 / 255, 0.72)+ Row {+ id: reachRow+ anchors.centerIn: parent+ spacing: 6+ Rectangle {+ anchors.verticalCenter: parent.verticalCenter+ width: 7+ height: 7+ radius: 3.5+ color: recentCard.reach === "online" ? "#5fd39a" : "#8b93a8"+ }+ UI.Label {+ text: recentCard.reach === "online" ? qsTr("Online") : qsTr("Offline")+ size: 12+ font.weight: Font.DemiBold+ color: "#eef1f8"+ }+ }+ }+ }+ Column {+ x: 16+ y: shot.height + 14+ width: parent.width - 32 - connectButton.width+ spacing: 3+ Row {+ spacing: 6+ UI.Label {+ text: recentCard.host.name+ size: 16+ font.weight: Font.DemiBold+ }+ UI.Icon {+ visible: recentCard.host.favourite === true+ anchors.verticalCenter: parent.verticalCenter+ name: "star"+ size: 13+ color: "#ffc46a"+ }+ }+ UI.Label {+ width: parent.width+ text: page.addressText(recentCard.host)+ size: 13+ color: UI.Style.inkMuted+ }+ UI.Label {+ text: page.lastUsedText(recentCard.host.lastUsed)+ size: 12+ color: UI.Style.inkSubtle+ }+ }+ UI.Button {+ id: connectButton+ anchors.right: parent.right+ anchors.rightMargin: 16+ y: shot.height + 24+ kind: recentCard.reach === "offline" ? "secondary" : "primary"+ text: qsTr("Connect")+ onClicked: page.connectHost(recentCard.host.id)+ }+ MouseArea {+ anchors.fill: shot+ acceptedButtons: Qt.RightButton+ onClicked: m => page.hostMenu(recentCard.host.id, shot, m.x, m.y)+ }+ }+}diff --git a/packages/wildos-remote/qml/InfoRows.qml b/packages/wildos-remote/qml/InfoRows.qmlnew file mode 100644index 0000000..d825c99--- /dev/null+++ b/packages/wildos-remote/qml/InfoRows.qml@@ -0,0 +1,90 @@+import QtQuick+import QtQuick.Layouts+import WildOS.UI as UI++// The facts box of the identity questions (RemoteCheck.dc): label on the+// left, value on the right, hairlines between; a fingerprint gets a row of+// its own in monospace.+Rectangle {+ id: box++ // [{ label, value, mono, wide, colour }]+ property var rows: []++ implicitHeight: column.implicitHeight + 8+ radius: 12+ color: UI.Style.surfaceRest+ border.width: 1+ border.color: UI.Style.borderSubtle++ ColumnLayout {+ id: column+ anchors.left: parent.left+ anchors.right: parent.right+ anchors.top: parent.top+ anchors.margins: 4+ anchors.leftMargin: 16+ anchors.rightMargin: 16+ spacing: 0++ Repeater {+ model: box.rows+ Item {+ id: rowItem+ required property var modelData+ required property int index+ Layout.fillWidth: true+ Layout.preferredHeight: modelData.wide ? wideColumn.implicitHeight + 22 : 37++ Rectangle {+ visible: rowItem.index > 0+ width: parent.width+ height: 1+ color: UI.Style.divider+ }+ UI.Label {+ visible: !rowItem.modelData.wide+ anchors.verticalCenter: parent.verticalCenter+ text: rowItem.modelData.label+ size: 14+ color: UI.Style.inkMuted+ }+ UI.Label {+ visible: !rowItem.modelData.wide+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ width: Math.min(implicitWidth, parent.width * 0.62)+ horizontalAlignment: Text.AlignRight+ text: rowItem.modelData.value+ size: 14+ font.weight: Font.DemiBold+ font.family: rowItem.modelData.mono ? "JetBrains Mono" : UI.Style.fontFamily+ color: rowItem.modelData.colour || UI.Style.ink+ }+ Column {+ id: wideColumn+ visible: rowItem.modelData.wide === true+ y: 11+ width: parent.width+ spacing: 6+ UI.Label {+ text: rowItem.modelData.label+ size: 14+ color: UI.Style.inkMuted+ }+ TextEdit {+ width: parent.width+ text: rowItem.modelData.value+ readOnly: true+ selectByMouse: true+ wrapMode: TextEdit.WrapAnywhere+ color: UI.Style.ink+ selectionColor: UI.Style.accentSelected+ font.family: "JetBrains Mono"+ font.pixelSize: UI.Style.px(12)+ }+ }+ }+ }+ }+}diff --git a/packages/wildos-remote/qml/KeyPassphraseDialog.qml b/packages/wildos-remote/qml/KeyPassphraseDialog.qmlnew file mode 100644index 0000000..3983fd3--- /dev/null+++ b/packages/wildos-remote/qml/KeyPassphraseDialog.qml@@ -0,0 +1,80 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Remote+import WildOS.UI as UI++// A key's passphrase: saving it in the keyring (checked against the key+// first), or giving the key a new one (ssh-keygen asks for the old one).+UI.Dialog {+ id: dialog++ property string keyPath+ // "save" or "change"+ property string mode: "save"+ property bool busy: false++ signal notice(string text)++ function ask(path, m) {+ keyPath = path;+ mode = m;+ const k = Keychain.key(path);+ title = m === "save" ? qsTr("Save the passphrase of %1").arg(k.label)+ : k.encrypted ? qsTr("Change the passphrase of %1").arg(k.label) : qsTr("Add a passphrase to %1").arg(k.label);+ text = m === "save" ? qsTr("It's checked against the key, then kept in your keyring. Remote adds the key to your key agent when you connect, so you're not asked.")+ : k.encrypted ? qsTr("You're asked for the current one first.")+ : qsTr("Anyone who gets a copy of the key file then needs the passphrase too.");+ first.text = "";+ second.text = "";+ busy = false;+ open();+ first.forceActiveFocus();+ }++ UI.TextField {+ id: first+ Layout.fillWidth: true+ revealable: true+ placeholderText: dialog.mode === "save" ? qsTr("Passphrase") : qsTr("New passphrase")+ onAccepted: if (dialog.mode === "save") go.clicked()+ }+ UI.TextField {+ id: second+ visible: dialog.mode === "change"+ Layout.fillWidth: true+ revealable: true+ placeholderText: qsTr("Type it again")+ error: text.length > 0 && text !== first.text+ }++ buttons: [+ UI.Button {+ text: qsTr("Cancel")+ onClicked: dialog.close()+ },+ UI.Button {+ id: go+ kind: "primary"+ busy: dialog.busy+ text: dialog.mode === "save" ? qsTr("Save") : qsTr("Change")+ enabled: !dialog.busy && first.text.length > 0 && (dialog.mode === "save" || first.text === second.text)+ onClicked: {+ dialog.busy = true;+ const done = (ok, message) => {+ dialog.busy = false;+ first.text = "";+ second.text = "";+ if (ok) {+ dialog.close();+ }+ dialog.notice(ok ? (dialog.mode === "save" ? qsTr("Passphrase saved in your keyring") : qsTr("Passphrase changed")) : message);+ };+ if (dialog.mode === "save") {+ Keychain.savePassphrase(dialog.keyPath, first.text, done);+ } else {+ Keychain.changePassphrase(dialog.keyPath, first.text, done);+ }+ }+ }+ ]+}diff --git a/packages/wildos-remote/qml/KeychainPage.qml b/packages/wildos-remote/qml/KeychainPage.qmlnew file mode 100644index 0000000..013eebb--- /dev/null+++ b/packages/wildos-remote/qml/KeychainPage.qml@@ -0,0 +1,477 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Remote+import WildOS.UI as UI++// SSH keys (RemoteKeychain.dc): the keys in ~/.ssh on the left, the chosen+// one on the right with its public half to copy or send, where its private+// half is and how it's protected, and the hosts that use it. What it says+// about protection is read from the key file itself.+Item {+ id: page++ property string selectedPath++ signal importRequested()+ signal newKeyRequested()+ signal sendRequested(string path, Item item)+ signal exportRequested(string path)+ signal deleteRequested(string path)+ signal passphraseRequested(string path, string mode)+ signal notice(string text)++ readonly property var keys: Keychain.keys+ readonly property var selected: {+ for (const k of keys) {+ if (k.path === selectedPath) {+ return k;+ }+ }+ return keys.length > 0 ? keys[0] : null;+ }+ readonly property var legacy: keys.filter(k => k.legacy)++ function protection(k) {+ if (k.securityKey) {+ return qsTr("Needs a touch on the key");+ }+ if (!k.encrypted) {+ return qsTr("No passphrase");+ }+ if (k.passphraseSaved) {+ return qsTr("Passphrase, saved in your keyring");+ }+ return qsTr("Passphrase");+ }+ function shortFingerprint(fp) {+ const body = fp.substring(7);+ return "SHA256:" + body.substring(0, 4) + "…" + body.substring(body.length - 4);+ }+ function usedText(k) {+ if (k.usedBy.length === 0) {+ return qsTr("Not set for a host");+ }+ if (k.usedBy.length === 1) {+ return qsTr("Used by %1").arg(k.usedBy[0]);+ }+ return qsTr("Used by %1 hosts").arg(k.usedBy.length);+ }++ RowLayout {+ anchors.fill: parent+ anchors.leftMargin: 36+ anchors.rightMargin: 36+ anchors.topMargin: 22+ anchors.bottomMargin: 26+ spacing: 28++ ColumnLayout {+ Layout.fillWidth: true+ Layout.preferredWidth: 560+ Layout.fillHeight: true+ spacing: 14++ RowLayout {+ Layout.fillWidth: true+ Layout.preferredHeight: 44+ UI.Label {+ Layout.fillWidth: true+ text: qsTr("Keychain")+ size: 26+ font.weight: Font.Bold+ }+ UI.Button {+ size: "small"+ text: qsTr("Import")+ onClicked: page.importRequested()+ }+ UI.Button {+ size: "small"+ kind: "primary"+ iconName: "plus"+ text: qsTr("New key")+ onClicked: page.newKeyRequested()+ }+ }++ UI.Label {+ Layout.fillWidth: true+ visible: !Keychain.agent+ text: qsTr("No key agent is running in this session, so ssh asks for a key's passphrase each time it's used.")+ size: 13+ color: UI.Style.warning+ wrapMode: Text.Wrap+ }++ ListView {+ id: list+ Layout.fillWidth: true+ Layout.fillHeight: true+ spacing: 14+ clip: true+ model: page.keys+ boundsBehavior: Flickable.StopAtBounds+ delegate: Rectangle {+ id: keyCard+ required property var modelData+ readonly property bool current: page.selected && page.selected.path === modelData.path+ width: ListView.view.width+ height: 76+ radius: 12+ color: current ? UI.Style.accentTint : keyMouse.containsMouse ? UI.Style.tone(0.07) : UI.Style.tone(0.045)+ border.width: 1+ border.color: current ? UI.Style.accentBorderStrong : UI.Style.tone(0.07)+ Accessible.role: Accessible.ListItem+ Accessible.name: modelData.label++ Rectangle {+ x: 16+ anchors.verticalCenter: parent.verticalCenter+ width: 42+ height: 42+ radius: 10+ color: keyCard.modelData.legacy ? Qt.rgba(1, 196 / 255, 106 / 255, 0.16) : UI.Style.accentChip+ UI.Glyph {+ anchors.centerIn: parent+ width: 19+ height: 19+ path: keyCard.modelData.securityKey ? RemoteIcons.securityKey : RemoteIcons.key+ strokeWidth: 1.8+ color: keyCard.modelData.legacy ? "#ffc46a" : UI.Style.accent+ }+ }+ Column {+ x: 72+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - 72 - rightCol.width - 24+ spacing: 4+ Row {+ spacing: 10+ UI.Label {+ text: keyCard.modelData.label+ size: 15+ font.weight: Font.DemiBold+ }+ Rectangle {+ anchors.verticalCenter: parent.verticalCenter+ width: typeLabel.implicitWidth + 12+ height: 20+ radius: 5+ color: UI.Style.tone(0.08)+ UI.Label {+ id: typeLabel+ anchors.centerIn: parent+ text: keyCard.modelData.type + (keyCard.modelData.bits ? " " + keyCard.modelData.bits : "")+ size: 11+ font.weight: Font.DemiBold+ color: UI.Style.inkMuted+ }+ }+ }+ UI.Label {+ width: parent.width+ text: page.protection(keyCard.modelData)+ size: 13+ color: keyCard.modelData.encrypted || keyCard.modelData.securityKey ? UI.Style.inkMuted : UI.Style.warning+ }+ }+ Column {+ id: rightCol+ anchors.right: parent.right+ anchors.rightMargin: 16+ anchors.verticalCenter: parent.verticalCenter+ spacing: 4+ UI.Label {+ anchors.right: parent.right+ text: page.shortFingerprint(keyCard.modelData.fingerprint)+ size: 12+ font.family: "JetBrains Mono"+ color: UI.Style.inkSubtle+ }+ UI.Label {+ anchors.right: parent.right+ text: page.usedText(keyCard.modelData)+ size: 13+ color: UI.Style.inkMuted+ }+ }+ MouseArea {+ id: keyMouse+ anchors.fill: parent+ hoverEnabled: true+ cursorShape: Qt.PointingHandCursor+ onClicked: page.selectedPath = keyCard.modelData.path+ }+ }+ footer: Column {+ width: ListView.view.width+ topPadding: 14+ spacing: 14+ Rectangle {+ visible: page.legacy.length > 0+ width: parent.width+ height: warnText.implicitHeight + 32+ radius: 12+ color: Qt.rgba(1, 196 / 255, 106 / 255, 0.08)+ border.width: 1+ border.color: Qt.rgba(1, 196 / 255, 106 / 255, 0.28)+ UI.Icon {+ x: 16+ y: 17+ name: "warning"+ size: 17+ color: "#ffc46a"+ }+ UI.Label {+ id: warnText+ x: 46+ y: 16+ width: parent.width - 62+ textFormat: Text.StyledText+ text: qsTr("<b>%1</b> still works, but newer keys are shorter and faster. Make a new key and send it to its hosts from here.").arg(page.legacy.length > 0 ? page.legacy[0].label : "")+ size: 13+ wrapMode: Text.Wrap+ lineHeight: 1.35+ }+ }+ Column {+ visible: page.keys.length === 0+ width: parent.width+ topPadding: 40+ spacing: 10+ UI.Label {+ anchors.horizontalCenter: parent.horizontalCenter+ text: qsTr("No keys yet")+ size: 18+ font.weight: Font.DemiBold+ }+ UI.Label {+ anchors.horizontalCenter: parent.horizontalCenter+ width: Math.min(parent.width, 420)+ horizontalAlignment: Text.AlignHCenter+ wrapMode: Text.Wrap+ text: qsTr("A key signs you in to servers without a password. Make one here, or import one you already have.")+ size: 14+ color: UI.Style.inkMuted+ }+ }+ }+ }+ }++ // The chosen key.+ Rectangle {+ visible: page.selected !== null+ Layout.preferredWidth: 486+ Layout.fillHeight: true+ radius: 14+ color: UI.Style.tone(0.03)+ border.width: 1+ border.color: UI.Style.tone(0.07)++ ColumnLayout {+ anchors.fill: parent+ anchors.margins: 22+ spacing: 12++ RowLayout {+ spacing: 14+ Rectangle {+ Layout.preferredWidth: 46+ Layout.preferredHeight: 46+ radius: 11+ color: UI.Style.accentChip+ UI.Glyph {+ anchors.centerIn: parent+ width: 20+ height: 20+ path: page.selected && page.selected.securityKey ? RemoteIcons.securityKey : RemoteIcons.key+ strokeWidth: 1.8+ color: UI.Style.accent+ }+ }+ ColumnLayout {+ spacing: 2+ UI.Label {+ text: page.selected ? page.selected.label : ""+ size: 19+ font.weight: Font.Bold+ }+ UI.Label {+ text: page.selected ? qsTr("%1, made %2").arg(page.selected.type).arg(page.selected.made) : ""+ size: 13+ color: UI.Style.inkMuted+ }+ }+ }++ Caption { text: qsTr("Public key"); Layout.topMargin: 6 }+ Rectangle {+ Layout.fillWidth: true+ Layout.preferredHeight: publicText.implicitHeight + 24+ radius: 10+ color: Qt.rgba(11 / 255, 15 / 255, 28 / 255, UI.Style.dark ? 0.9 : 0.06)+ TextEdit {+ id: publicText+ x: 12+ y: 12+ width: parent.width - 24+ text: page.selected ? page.selected.publicKey : ""+ readOnly: true+ selectByMouse: true+ wrapMode: TextEdit.WrapAnywhere+ color: UI.Style.ink+ selectionColor: UI.Style.accentSelected+ font.family: "JetBrains Mono"+ font.pixelSize: UI.Style.px(12)+ }+ }+ Row {+ spacing: 8+ UI.Button {+ size: "small"+ iconName: "copy"+ text: qsTr("Copy")+ onClicked: {+ Keychain.copyPublic(page.selected.path);+ page.notice(qsTr("Public key copied"));+ }+ }+ UI.Button {+ id: sendButton+ size: "small"+ iconName: "send"+ text: qsTr("Send to a server")+ onClicked: page.sendRequested(page.selected.path, sendButton)+ }+ }++ Caption { text: qsTr("Private key"); Layout.topMargin: 6 }+ RowLayout {+ Layout.fillWidth: true+ spacing: 10+ UI.Icon {+ Layout.alignment: Qt.AlignTop+ Layout.topMargin: 2+ name: page.selected && (page.selected.encrypted || page.selected.securityKey) ? "lock" : "warning"+ size: 15+ color: page.selected && (page.selected.encrypted || page.selected.securityKey) ? UI.Style.success : UI.Style.warning+ }+ UI.Label {+ Layout.fillWidth: true+ text: {+ const k = page.selected;+ if (!k) {+ return "";+ }+ const where = qsTr("It's the file %1 in your .ssh folder, readable only by you, and it's only copied if you export it.").arg(k.file);+ if (k.securityKey) {+ return qsTr("The key itself stays on your security key; this PC only holds a handle that needs the key and a touch to use. ") + where;+ }+ if (!k.encrypted) {+ return qsTr("Not protected by a passphrase: anyone who gets a copy of the file can use it. ") + where;+ }+ if (k.passphraseSaved) {+ return qsTr("Encrypted with its passphrase, which is saved in your keyring. When you connect, Remote unlocks it into your key agent, so you're not asked. ") + where;+ }+ return qsTr("Encrypted with its passphrase, which you're asked for when it's used. ") + where;+ }+ size: 13+ color: UI.Style.inkStatus+ wrapMode: Text.Wrap+ lineHeight: 1.35+ }+ }+ Flow {+ Layout.fillWidth: true+ spacing: 8+ visible: page.selected !== null && !page.selected.securityKey+ UI.Button {+ size: "small"+ visible: page.selected && page.selected.encrypted && !page.selected.passphraseSaved+ text: qsTr("Save passphrase in keyring")+ onClicked: page.passphraseRequested(page.selected.path, "save")+ }+ UI.Button {+ size: "small"+ visible: page.selected && page.selected.passphraseSaved+ text: qsTr("Forget saved passphrase")+ onClicked: Keychain.forgetPassphrase(page.selected.path)+ }+ UI.Button {+ size: "small"+ text: page.selected && page.selected.encrypted ? qsTr("Change passphrase") : qsTr("Add a passphrase")+ onClicked: page.passphraseRequested(page.selected.path, "change")+ }+ UI.Button {+ size: "small"+ visible: Keychain.agent && page.selected && !page.selected.inAgent+ text: qsTr("Add to key agent")+ onClicked: Keychain.addToAgent(page.selected.path, (ok, message) => page.notice(ok ? qsTr("Unlocked in your key agent until you sign out") : message))+ }+ }+ UI.Label {+ visible: page.selected !== null && page.selected.inAgent+ text: qsTr("Unlocked in your key agent now")+ size: 12+ color: UI.Style.success+ }++ Caption { text: qsTr("Used by"); Layout.topMargin: 6 }+ Flow {+ Layout.fillWidth: true+ spacing: 8+ Repeater {+ model: page.selected ? page.selected.usedBy : []+ Rectangle {+ required property string modelData+ width: chipLabel.implicitWidth + 20+ height: 28+ radius: 7+ color: UI.Style.tone(0.07)+ UI.Label {+ id: chipLabel+ anchors.centerIn: parent+ text: parent.modelData+ size: 13+ }+ }+ }+ UI.Label {+ visible: page.selected !== null && page.selected.usedBy.length === 0+ text: qsTr("No host is set to use it. Hosts left to choose their own key may still be offered it.")+ width: parent.width+ size: 13+ color: UI.Style.inkMuted+ wrapMode: Text.Wrap+ }+ }++ Item { Layout.fillHeight: true }+ RowLayout {+ Layout.fillWidth: true+ UI.Button {+ size: "small"+ text: qsTr("Export")+ onClicked: page.exportRequested(page.selected.path)+ }+ Item { Layout.fillWidth: true }+ UI.Button {+ size: "small"+ danger: true+ text: qsTr("Delete")+ onClicked: page.deleteRequested(page.selected.path)+ }+ }+ }+ }+ }++ component Caption: UI.Label {+ size: 12+ font.weight: Font.Bold+ font.letterSpacing: 0.6+ font.capitalization: Font.AllUppercase+ color: UI.Style.inkMuted+ }+}diff --git a/packages/wildos-remote/qml/KnownHostsPage.qml b/packages/wildos-remote/qml/KnownHostsPage.qmlnew file mode 100644index 0000000..b10b698--- /dev/null+++ b/packages/wildos-remote/qml/KnownHostsPage.qml@@ -0,0 +1,108 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Remote+import WildOS.UI as UI++// ~/.ssh/known_hosts, the identities this PC has seen, shared with every+// other SSH program. Names are stored hashed, so a name shows only when it+// matches one of your hosts.+Item {+ id: page++ signal notice(string text)++ ColumnLayout {+ anchors.fill: parent+ anchors.leftMargin: 36+ anchors.rightMargin: 36+ anchors.topMargin: 22+ anchors.bottomMargin: 26+ spacing: 14++ UI.Label {+ Layout.preferredHeight: 44+ text: qsTr("Known hosts")+ size: 26+ font.weight: Font.Bold+ }+ UI.Label {+ Layout.fillWidth: true+ Layout.maximumWidth: 900+ text: qsTr("Each server's identity, from the first time you connected. Remote won't connect to a server whose identity has changed without asking you. Removing one means the next connection asks again, as if it were new.")+ size: 14+ color: UI.Style.inkMuted+ wrapMode: Text.Wrap+ lineHeight: 1.35+ }++ ListView {+ Layout.fillWidth: true+ Layout.fillHeight: true+ Layout.maximumWidth: 900+ spacing: 10+ clip: true+ model: HostKeys.known+ boundsBehavior: Flickable.StopAtBounds+ delegate: Rectangle {+ id: row+ required property var modelData+ width: ListView.view.width+ height: 62+ radius: 12+ color: UI.Style.tone(0.045)+ border.width: 1+ border.color: UI.Style.tone(0.07)+ UI.Glyph {+ x: 18+ anchors.verticalCenter: parent.verticalCenter+ width: 18+ height: 18+ path: RemoteIcons.knownHosts+ color: row.modelData.marker === "@revoked" ? UI.Style.danger : UI.Style.iconMuted+ }+ Column {+ x: 50+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - 170+ spacing: 4+ UI.Label {+ width: parent.width+ text: row.modelData.name.length > 0 ? row.modelData.name+ : row.modelData.hashed ? qsTr("A server you haven't saved (its name is hashed)") : qsTr("Unnamed")+ size: 14+ font.weight: Font.DemiBold+ color: row.modelData.name.length > 0 ? UI.Style.ink : UI.Style.inkMuted+ }+ UI.Label {+ width: parent.width+ text: row.modelData.keyType + " " + row.modelData.fingerprint + (row.modelData.seen ? " · " + qsTr("added %1").arg(row.modelData.seen) : "")+ size: 12+ font.family: "JetBrains Mono"+ color: UI.Style.inkSubtle+ }+ }+ UI.Button {+ anchors.right: parent.right+ anchors.rightMargin: 14+ anchors.verticalCenter: parent.verticalCenter+ size: "small"+ text: qsTr("Remove")+ onClicked: {+ if (!HostKeys.forget(row.modelData.index)) {+ page.notice(qsTr("Your known hosts file couldn't be changed."));+ }+ }+ }+ }+ footer: UI.Label {+ visible: HostKeys.known.length === 0+ width: ListView.view.width+ topPadding: 40+ horizontalAlignment: Text.AlignHCenter+ text: qsTr("No known hosts yet")+ size: 18+ font.weight: Font.DemiBold+ }+ }+ }+}diff --git a/packages/wildos-remote/qml/Main.qml b/packages/wildos-remote/qml/Main.qmlnew file mode 100644index 0000000..f9a247b--- /dev/null+++ b/packages/wildos-remote/qml/Main.qml@@ -0,0 +1,525 @@+import QtQuick+import QtQuick.Controls as QQC+import QtQuick.Dialogs+import QtQuick.Layouts+import WildOS.Remote+import WildOS.UI as UI++// Remote's home window (RemoteHosts.dc, RemoteStart.dc): the title bar with+// the address box, the side column, and the hosts, keychain, snippets,+// port forwarding and known hosts pages. Connecting starts here: SSH hosts+// have their identity checked (RemoteHostChanged.dc) before a terminal tab+// opens; desktops ask about their certificate and sign-in here+// (RemoteCheck.dc, RemoteSignIn.dc) before their own window opens.+UI.AppWindow {+ id: window++ property string page: "hosts"++ width: 1384+ height: 802+ minimumWidth: 980+ minimumHeight: 620+ visible: !App.desktopOnly+ title: qsTr("Remote")++ function addressOf(h) {+ return h.user ? h.user + " on " + h.address : h.address;+ }++ // What happens once an SSH host checks out: a terminal tab, unless+ // something else asked for the check (sending a key).+ property var afterCheck: null++ // An SSH host: is it the same server as last time?+ function connectHost(id, then) {+ const h = Hosts.host(id);+ if (!h.id) {+ return;+ }+ if (h.kind === "desktop") {+ desktops.start(h);+ return;+ }+ afterCheck = then || (() => App.openTerminal(id));+ toast.show(qsTr("Checking %1…").arg(h.name));+ HostKeys.check(Hosts.hostName(h), Hosts.port(h), result => {+ toast.hide();+ if (result.state === "known") {+ afterCheck();+ } else if (result.state === "new") {+ hostKeyDialog.ask(h, result);+ } else if (result.state === "changed") {+ hostChangedDialog.ask(h, result);+ } else if (result.state === "revoked") {+ problemDialog.show(qsTr("%1 can't be trusted").arg(h.name),+ qsTr("The key %1 offers has been revoked on this PC, so Remote won't connect to it.").arg(h.name));+ } else {+ problemDialog.show(qsTr("Couldn't reach %1").arg(h.name), result.error);+ }+ });+ }++ // What was typed in the address box: a saved host with that address,+ // or a new one saved as typed.+ function quickConnect(address) {+ for (const h of Hosts.hosts) {+ if (h.kind === address.kind && h.address === address.address && (h.user === address.user || !address.user)) {+ connectHost(h.id);+ return;+ }+ }+ const id = Hosts.save({+ kind: address.kind,+ name: address.address.split(":")[0],+ address: address.address,+ user: address.user,+ group: ""+ });+ toast.show(qsTr("Saved to your hosts"));+ connectHost(id);+ }++ function openHostMenu(id, item, x, y) {+ const h = Hosts.host(id);+ const entries = [{ text: qsTr("Connect"), icon: h.kind === "desktop" ? "monitor" : "terminal", bold: true, run: () => connectHost(id) }];+ if (h.kind === "desktop") {+ entries.push({ text: h.desktop.display === "window" ? qsTr("Connect full screen") : qsTr("Connect in a window"), icon: "fullscreen",+ run: () => desktops.start(h, h.desktop.display === "window" ? "full" : "window") });+ }+ entries.push({ separator: true },+ { text: h.favourite ? qsTr("Remove from favourites") : qsTr("Add to favourites"), icon: "star", run: () => Hosts.setFavourite(id, !h.favourite) },+ { text: qsTr("Edit"), icon: "pencil", run: () => hostDialog.edit(id) },+ { text: qsTr("Copy address"), icon: "copy", run: () => App.copyText(h.address) },+ { separator: true },+ { text: qsTr("Delete"), icon: "delete", danger: true, run: () => deleteDialog.ask(id) });+ hostMenu.entries = entries;+ hostMenu.popup(item, x, y);+ }++ Connections {+ target: App+ function onConnectRequested(id) {+ window.connectHost(id);+ }+ function onEditRequested(id) {+ window.raise();+ window.requestActivate();+ hostDialog.edit(id);+ }+ function onQuickConnectRequested(address) {+ window.raise();+ window.quickConnect(address);+ }+ function onRaiseRequested() {+ window.show();+ window.raise();+ window.requestActivate();+ }+ }+ Connections {+ target: AskPass+ function onPassphraseNeeded(id, title, prompt, kind) {+ window.raise();+ passphraseDialog.ask(id, title, prompt, kind);+ }+ function onQuestionClosed(id) {+ passphraseDialog.closeFor(id);+ }+ }++ Shortcut {+ sequence: "Ctrl+L"+ onActivated: search.forceActiveFocus()+ }+ Shortcut {+ sequence: "Ctrl+N"+ onActivated: hostDialog.create(window.page === "keychain" ? "terminal" : "")+ }++ ColumnLayout {+ anchors.fill: parent+ anchors.margins: window.maximised ? 0 : 1+ spacing: 0++ // The title bar: 56px, as the boards draw it.+ Item {+ Layout.fillWidth: true+ Layout.preferredHeight: 56++ MouseArea {+ anchors.fill: parent+ acceptedButtons: Qt.LeftButton+ property point origin+ onPressed: m => origin = Qt.point(m.x, m.y)+ onPositionChanged: m => {+ if (pressed && Math.abs(m.x - origin.x) + Math.abs(m.y - origin.y) > 4) {+ window.startSystemMove();+ }+ }+ onDoubleClicked: window.frame.toggleMaximised()+ }++ Image {+ id: appIcon+ x: 18+ anchors.verticalCenter: parent.verticalCenter+ width: 24+ height: 24+ source: "qrc:/qt/qml/WildOS/Remote/data/org.wildos.remote.svg"+ sourceSize: Qt.size(48, 48)+ }+ UI.Label {+ x: 54+ anchors.verticalCenter: parent.verticalCenter+ text: qsTr("Remote")+ size: 15+ font.weight: Font.DemiBold+ }++ UI.TextField {+ id: search+ x: 256+ anchors.verticalCenter: parent.verticalCenter+ width: Math.min(480, parent.width - 256 - 340)+ height: 34+ leftPadding: 36+ font.family: text.length > 0 ? UI.Style.fontFamily : "JetBrains Mono"+ placeholderText: qsTr("ssh user@host, or search your hosts")+ onTextChanged: if (window.page !== "hosts" && window.page !== "favourites" && !window.page.startsWith("group:")) window.page = "hosts"+ onAccepted: {+ const address = Hosts.parseAddress(text);+ if (address.kind) {+ window.quickConnect(address);+ text = "";+ }+ }+ UI.Icon {+ x: 12+ anchors.verticalCenter: parent.verticalCenter+ name: "terminal"+ size: 15+ color: UI.Style.iconMuted+ }+ }++ UI.Button {+ anchors.right: windowButtons.left+ anchors.rightMargin: 20+ anchors.verticalCenter: parent.verticalCenter+ kind: "primary"+ size: "small"+ iconName: "plus"+ text: window.page === "keychain" ? qsTr("New key") : window.page === "snippets" ? qsTr("New snippet") : qsTr("New host")+ onClicked: {+ if (window.page === "keychain") {+ newKeyDialog.open();+ } else if (window.page === "snippets") {+ snippetDialog.edit({});+ } else {+ hostDialog.create("");+ }+ }+ }++ UI.WindowButtons {+ id: windowButtons+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ frame: window.frame+ }++ Rectangle {+ anchors.bottom: parent.bottom+ width: parent.width+ height: 1+ color: UI.Style.divider+ }+ }++ RowLayout {+ Layout.fillWidth: true+ Layout.fillHeight: true+ spacing: 0++ Sidebar {+ Layout.preferredWidth: 236+ Layout.fillHeight: true+ page: window.page+ onPageChosen: p => {+ window.page = p;+ if (p === "knownhosts") {+ HostKeys.reload();+ } else if (p === "keychain") {+ Keychain.refresh();+ }+ }+ onNewGroup: groupDialog.ask("")+ onGroupMenu: (name, item) => {+ groupMenu.entries = [+ { text: qsTr("Rename"), icon: "rename", run: () => groupDialog.ask(name) },+ { text: qsTr("Delete group"), icon: "delete", danger: true, run: () => {+ Hosts.removeGroup(name);+ if (window.page === "group:" + name) window.page = "hosts";+ } }+ ];+ groupMenu.popup(item, item.width - 20, item.height);+ }+ }++ StackLayout {+ Layout.fillWidth: true+ Layout.fillHeight: true+ currentIndex: window.page === "keychain" ? 1 : window.page === "snippets" ? 2 : window.page === "forwarding" ? 3+ : window.page === "knownhosts" ? 4 : 0++ HostsPage {+ view: window.page+ search: search.text+ onConnectHost: id => window.connectHost(id)+ onHostMenu: (id, item, x, y) => window.openHostMenu(id, item, x, y)+ onNewHost: kind => hostDialog.create(kind)+ }+ KeychainPage {+ onImportRequested: importDialog.open()+ onNewKeyRequested: newKeyDialog.open()+ onSendRequested: (path, item) => window.openSendMenu(path, item)+ onExportRequested: path => {+ exportDialog.keyPath = path;+ exportDialog.open();+ }+ onDeleteRequested: path => deleteKeyDialog.ask(path)+ onPassphraseRequested: (path, mode) => keyPassphraseDialog.ask(path, mode)+ onNotice: text => toast.show(text)+ }+ SnippetsPage {+ onEditRequested: s => snippetDialog.edit(s)+ }+ ForwardingPage {+ onEditHost: id => hostDialog.edit(id)+ }+ KnownHostsPage {+ onNotice: text => toast.show(text)+ }+ }+ }+ }++ // Sending a public key to a server: ssh-copy-id in a terminal tab, where+ // the server asks for its password as it would anywhere else.+ function openSendMenu(path, item) {+ const entries = [];+ for (const h of Hosts.hosts) {+ if (h.kind === "terminal") {+ entries.push({ text: h.name, icon: "terminal", run: () => window.connectHost(h.id, () => App.sendKey(path, h.id)) });+ }+ }+ if (entries.length === 0) {+ entries.push({ text: qsTr("No SSH hosts yet"), enabled: false });+ }+ sendMenu.entries = entries;+ sendMenu.popup(item, 0, item.height + 4);+ }++ UI.Menu {+ id: hostMenu+ minimumWidth: 230+ }+ UI.Menu {+ id: groupMenu+ }+ UI.Menu {+ id: sendMenu+ minimumWidth: 220+ }++ HostDialog {+ id: hostDialog+ onSaved: (id, connect) => {+ if (connect) {+ window.connectHost(id);+ }+ }+ }+ HostKeyDialog {+ id: hostKeyDialog+ onAccepted: (h, result) => {+ if (HostKeys.trust(Hosts.hostName(h), Hosts.port(h), result.keyLine)) {+ window.afterCheck();+ } else {+ toast.show(qsTr("Your known hosts file couldn't be written."));+ }+ }+ }+ HostChangedDialog {+ id: hostChangedDialog+ onRebuilt: (h, result) => {+ if (HostKeys.replace(Hosts.hostName(h), Hosts.port(h), result.keyLine)) {+ window.afterCheck();+ } else {+ toast.show(qsTr("Your known hosts file couldn't be written."));+ }+ }+ }+ DesktopConnector {+ id: desktops+ onNotice: text => toast.show(text)+ }+ PassphraseDialog {+ id: passphraseDialog+ }+ NewKeyDialog {+ id: newKeyDialog+ onNotice: text => toast.show(text)+ }+ KeyPassphraseDialog {+ id: keyPassphraseDialog+ onNotice: text => toast.show(text)+ }+ SnippetDialog {+ id: snippetDialog+ }++ FileDialog {+ id: importDialog+ title: qsTr("Import a key")+ currentFolder: "file://" + App.homePath() + "/.ssh"+ onAccepted: Keychain.importKey(selectedFile, (ok, message, path) => toast.show(ok ? qsTr("Key imported into your .ssh folder") : message))+ }+ FolderDialog {+ id: exportDialog+ property string keyPath+ title: qsTr("Export the key to")+ onAccepted: Keychain.exportKey(keyPath, selectedFolder, (ok, message) => toast.show(ok ? qsTr("Exported to %1").arg(message) : message))+ }++ UI.Dialog {+ id: problemDialog+ function show(heading, body) {+ title = heading;+ text = body;+ open();+ }+ buttons: [+ UI.Button {+ kind: "primary"+ text: qsTr("OK")+ onClicked: problemDialog.close()+ }+ ]+ }++ UI.Dialog {+ id: deleteDialog+ property string hostId+ function ask(id) {+ hostId = id;+ const h = Hosts.host(id);+ title = qsTr("Delete %1?").arg(h.name);+ text = h.kind === "desktop"+ ? qsTr("It goes from your hosts, with its saved password and its last screen. The PC itself isn't changed.")+ : qsTr("It goes from your hosts. Its entry in known hosts stays, so Remote still knows it if you add it again.");+ open();+ }+ buttons: [+ UI.Button {+ text: qsTr("Cancel")+ onClicked: deleteDialog.close()+ },+ UI.Button {+ kind: "primary"+ danger: true+ text: qsTr("Delete")+ onClicked: {+ Secrets.remove("desktop:" + deleteDialog.hostId);+ Hosts.remove(deleteDialog.hostId);+ deleteDialog.close();+ }+ }+ ]+ }++ UI.Dialog {+ id: deleteKeyDialog+ property string keyPath+ function ask(path) {+ keyPath = path;+ const k = Keychain.key(path);+ title = qsTr("Delete %1?").arg(k.label);+ text = k.usedBy.length > 0+ ? qsTr("%1 use it. The key and its public half go to the bin, so you can bring them back from there until it's emptied.").arg(k.usedBy.join(", "))+ : qsTr("The key and its public half go to the bin, so you can bring them back from there until it's emptied.");+ open();+ }+ buttons: [+ UI.Button {+ text: qsTr("Cancel")+ onClicked: deleteKeyDialog.close()+ },+ UI.Button {+ kind: "primary"+ danger: true+ text: qsTr("Delete")+ onClicked: {+ if (!Keychain.remove(deleteKeyDialog.keyPath)) {+ toast.show(qsTr("The key couldn't be moved to the bin."));+ }+ deleteKeyDialog.close();+ }+ }+ ]+ }++ UI.Dialog {+ id: groupDialog+ property string renaming+ function ask(name) {+ renaming = name;+ title = name.length > 0 ? qsTr("Rename %1").arg(name) : qsTr("New group");+ groupName.text = name;+ open();+ groupName.forceActiveFocus();+ }+ UI.TextField {+ id: groupName+ Layout.fillWidth: true+ placeholderText: qsTr("Name")+ onAccepted: groupSave.clicked()+ }+ buttons: [+ UI.Button {+ text: qsTr("Cancel")+ onClicked: groupDialog.close()+ },+ UI.Button {+ id: groupSave+ kind: "primary"+ text: groupDialog.renaming.length > 0 ? qsTr("Rename") : qsTr("Add")+ enabled: groupName.text.trim().length > 0+ onClicked: {+ if (groupDialog.renaming.length > 0) {+ Hosts.renameGroup(groupDialog.renaming, groupName.text);+ if (window.page === "group:" + groupDialog.renaming) window.page = "group:" + groupName.text.trim();+ } else {+ Hosts.addGroup(groupName.text);+ }+ groupDialog.close();+ }+ }+ ]+ }++ UI.Toast {+ id: toast+ anchors.horizontalCenter: parent.horizontalCenter+ anchors.bottom: parent.bottom+ anchors.bottomMargin: 24+ z: 60+ }++ // The automated screen test (App.testScript), never in normal use.+ Loader {+ active: App.testScript.toString().length > 0+ source: App.testScript+ }+}diff --git a/packages/wildos-remote/qml/NewKeyDialog.qml b/packages/wildos-remote/qml/NewKeyDialog.qmlnew file mode 100644index 0000000..8eca649--- /dev/null+++ b/packages/wildos-remote/qml/NewKeyDialog.qml@@ -0,0 +1,111 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Remote+import WildOS.UI as UI++// A new SSH key: Ed25519, made on this PC by ssh-keygen and kept in+// ~/.ssh. The passphrase is what protects it if the file is ever copied;+// the keyring keeps it only when asked.+UI.Dialog {+ id: dialog++ signal notice(string text)++ title: qsTr("New key")+ text: qsTr("An Ed25519 key, made on this PC and kept in your .ssh folder, where ssh and git find it too.")+ size: "medium"++ onAboutToShow: {+ label.text = "";+ passphrase.text = "";+ again.text = "";+ save.checked = true;+ busy = false;+ label.forceActiveFocus();+ }+ property bool busy: false+ readonly property bool matches: passphrase.text === again.text++ UI.Label {+ text: qsTr("Name")+ size: 13+ font.weight: Font.DemiBold+ }+ UI.TextField {+ id: label+ Layout.fillWidth: true+ placeholderText: qsTr("Wild OS laptop")+ }+ UI.Label {+ Layout.topMargin: 6+ text: qsTr("Passphrase")+ size: 13+ font.weight: Font.DemiBold+ }+ UI.TextField {+ id: passphrase+ Layout.fillWidth: true+ revealable: true+ placeholderText: qsTr("Passphrase")+ }+ UI.TextField {+ id: again+ Layout.fillWidth: true+ revealable: true+ placeholderText: qsTr("Type it again")+ error: again.text.length > 0 && !dialog.matches+ }+ UI.Label {+ Layout.fillWidth: true+ text: passphrase.text.length === 0+ ? qsTr("Without a passphrase, anyone who gets a copy of the key file can use it.")+ : qsTr("Use something you'll remember: a lost passphrase can't be recovered.")+ size: 12+ color: passphrase.text.length === 0 ? UI.Style.warning : UI.Style.inkSubtle+ wrapMode: Text.Wrap+ }+ RowLayout {+ Layout.fillWidth: true+ Layout.topMargin: 4+ spacing: 12+ enabled: passphrase.text.length > 0+ opacity: enabled ? 1 : 0.5+ UI.Toggle {+ id: save+ checked: true+ Accessible.name: saveLabel.text+ }+ UI.Label {+ id: saveLabel+ Layout.fillWidth: true+ text: qsTr("Save the passphrase in my keyring, so I'm not asked each time")+ size: 13+ wrapMode: Text.Wrap+ }+ }++ buttons: [+ UI.Button {+ text: qsTr("Cancel")+ onClicked: dialog.close()+ },+ UI.Button {+ kind: "primary"+ text: qsTr("Make key")+ busy: dialog.busy+ enabled: dialog.matches && !dialog.busy+ onClicked: {+ dialog.busy = true;+ Keychain.generate(label.text, passphrase.text, save.checked && passphrase.text.length > 0, (ok, message) => {+ dialog.busy = false;+ passphrase.text = "";+ again.text = "";+ if (ok) {+ dialog.close();+ }+ dialog.notice(ok ? (message || qsTr("Key made")) : message);+ });+ }+ }+ ]+}diff --git a/packages/wildos-remote/qml/Panel.qml b/packages/wildos-remote/qml/Panel.qmlnew file mode 100644index 0000000..92e62d5--- /dev/null+++ b/packages/wildos-remote/qml/Panel.qml@@ -0,0 +1,53 @@+import QtQuick+import QtQuick.Effects+import QtQuick.Templates as T+import QtQuick.Window+import WildOS.UI as UI++// A dialog of Remote's own size and layout, on the Wild OS dialog glass+// (radius 18, the dialog glass and edge, the menu shadow, the scrim+// behind). For the forms and questions the boards draw larger than+// UI.Dialog's two sizes.+T.Popup {+ id: control++ parent: T.Overlay.overlay+ anchors.centerIn: parent+ // The templates leave a popup's size to the style; this one has none.+ implicitWidth: implicitContentWidth + leftPadding + rightPadding+ implicitHeight: implicitContentHeight + topPadding + bottomPadding+ modal: true+ focus: true+ padding: 28+ closePolicy: T.Popup.CloseOnEscape++ T.Overlay.modal: Rectangle {+ radius: Window.window && Window.window.visibility !== Window.Maximized && Window.window.visibility !== Window.FullScreen ? UI.Style.windowRadius : 0+ color: UI.Style.scrim+ }++ background: Rectangle {+ radius: UI.Style.radiusDialog+ // Nearly solid: a dialog inside the window gets no blur from the+ // compositor, and the hosts behind would show through the glass.+ color: Qt.rgba(UI.Style.glassDialog.r, UI.Style.glassDialog.g, UI.Style.glassDialog.b, 0.98)+ border.width: 1+ border.color: UI.Style.borderDialog+ layer.enabled: true+ layer.effect: MultiEffect {+ shadowEnabled: true+ shadowColor: UI.Style.shadowMenu+ shadowVerticalOffset: 24+ shadowBlur: 1.0+ blurMax: 48+ }+ }++ enter: Transition {+ NumberAnimation { property: "opacity"; from: 0; to: 1; duration: UI.Style.motionFast; easing.type: Easing.OutCubic }+ NumberAnimation { property: "scale"; from: UI.Style.scaleEnter; to: 1; duration: UI.Style.motionNormal; easing.type: UI.Style.easeEnter }+ }+ exit: Transition {+ NumberAnimation { property: "opacity"; from: 1; to: 0; duration: UI.Style.motionFast; easing.type: UI.Style.easeExit }+ }+}diff --git a/packages/wildos-remote/qml/PassphraseDialog.qml b/packages/wildos-remote/qml/PassphraseDialog.qmlnew file mode 100644index 0000000..bf1f058--- /dev/null+++ b/packages/wildos-remote/qml/PassphraseDialog.qml@@ -0,0 +1,73 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Remote+import WildOS.UI as UI++// A question from ssh, ssh-keygen or ssh-add (through AskPass): a+// passphrase, a password, a yes or no, or "touch your security key", which+// stays up until the key is touched.+UI.Dialog {+ id: dialog++ property string askId+ property string kind: "passphrase"+ property bool answered: false++ function ask(id, heading, prompt, k) {+ askId = id;+ kind = k;+ answered = false;+ title = k === "touch" ? qsTr("Touch your security key")+ : k === "confirm" ? (heading || qsTr("Are you sure?"))+ : heading || (k === "pin" ? qsTr("Enter your security key's PIN") : qsTr("Enter the passphrase"));+ // ssh's own prompt, minus the colon it ends with.+ text = prompt.replace(/:\s*$/, "");+ field.text = "";+ open();+ if (k !== "touch" && k !== "confirm") {+ field.forceActiveFocus();+ }+ }+ function closeFor(id) {+ if (id === askId) {+ answered = true;+ close();+ }+ }++ onClosed: if (!answered) AskPass.cancel(askId)++ UI.TextField {+ id: field+ visible: dialog.kind !== "touch" && dialog.kind !== "confirm"+ Layout.fillWidth: true+ revealable: true+ placeholderText: dialog.kind === "pin" ? qsTr("PIN") : dialog.kind === "password" ? qsTr("Password") : qsTr("Passphrase")+ onAccepted: okButton.clicked()+ }+ UI.Spinner {+ visible: dialog.kind === "touch"+ Layout.alignment: Qt.AlignHCenter+ size: 22+ }++ buttons: [+ UI.Button {+ text: qsTr("Cancel")+ visible: dialog.kind !== "touch"+ onClicked: dialog.close()+ },+ UI.Button {+ id: okButton+ kind: "primary"+ visible: dialog.kind !== "touch"+ text: dialog.kind === "confirm" ? qsTr("Yes") : qsTr("OK")+ onClicked: {+ dialog.answered = true;+ AskPass.answer(dialog.askId, field.text);+ field.text = "";+ dialog.close();+ }+ }+ ]+}diff --git a/packages/wildos-remote/qml/RemoteIcons.qml b/packages/wildos-remote/qml/RemoteIcons.qmlnew file mode 100644index 0000000..0f916b5--- /dev/null+++ b/packages/wildos-remote/qml/RemoteIcons.qml@@ -0,0 +1,29 @@+pragma Singleton++import QtQuick++// The line icons Remote's boards draw that Wild OS's set doesn't have, as+// path data on the same 24px grid, for UI.Glyph and UI.IconButton's glyph.+QtObject {+ readonly property string key: "M15 9a4 4 0 1 1-3.9 4.9L4 21H2v-3l1-1h2v-2h2l2.1-2.1A4 4 0 0 1 15 9zM16.5 7.5h.01"+ readonly property string snippets: "M8 7l-5 5 5 5M16 7l5 5-5 5"+ readonly property string forward: "M4 12h13M13 7l5 5-5 5M20 5v14"+ readonly property string knownHosts: "M12 3l8 3v6c0 4.5-3.5 8-8 9-4.5-1-8-4.5-8-9V6z"+ readonly property string noSync: "M3 3l18 18M10.6 6.1A9.8 9.8 0 0 1 12 6c6 0 9.5 6 9.5 6a17 17 0 0 1-3 3.6M6.3 7.6A16.6 16.6 0 0 0 2.5 12S6 18 12 18a9 9 0 0 0 4-.9M9.9 10a3 3 0 0 0 4.2 4.2"+ readonly property string broadcast: "M12 12h.01M8.5 8.5a5 5 0 0 0 0 7M15.5 8.5a5 5 0 0 1 0 7M5.6 5.6a9 9 0 0 0 0 12.8M18.4 5.6a9 9 0 0 1 0 12.8"+ readonly property string columns: "M3 4h18v16H3zM12 4v16"+ readonly property string folder: "M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"+ readonly property string clock: "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM12 7v5l3 2"+ readonly property string play: "M8 5l11 7-11 7z"+ readonly property string terminalTile: "M4 5h16v14H4zM8 10l2 2-2 2M12 14h4"+ readonly property string securityKey: "M9 3h6v6H9zM7 9h10v9a3 3 0 0 1-3 3h-4a3 3 0 0 1-3-3z"+ readonly property string signal: "M5 19v-3M10 19v-6M15 19v-9M20 19V7"+ readonly property string upload: "M12 18V6M7 11l5-5 5 5M5 20h14"+ readonly property string download: "M12 6v12M7 13l5 5 5-5M5 4h14"+ readonly property string file: "M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8zM14 3v5h5"+ readonly property string keyboard: "M3 6h18v12H3zM7 10h.01M11 10h.01M15 10h.01M7 14h10"+ readonly property string clipboard: "M9 4h6v3H9zM9 5H6v15h12V5h-3"+ readonly property string displays: "M3 5h12v9H3zM9 14v3M6 17h6M17 9h4v8h-7"+ readonly property string exitFull: "M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5"+ readonly property string power: "M12 3v8M6.3 6.3a8 8 0 1 0 11.4 0"+}diff --git a/packages/wildos-remote/qml/Segments.qml b/packages/wildos-remote/qml/Segments.qmlnew file mode 100644index 0000000..029edb9--- /dev/null+++ b/packages/wildos-remote/qml/Segments.qml@@ -0,0 +1,86 @@+import QtQuick+import WildOS.UI as UI++// A choice of two or three, side by side in one sunken track, the chosen+// one raised (RemoteNew.dc: "Ask every time" or "Save in keyring", Window,+// Full screen or All monitors). Arrow keys move the choice.+Rectangle {+ id: segments++ property var options: []+ property string value+ signal chosen(string value)++ // From the labels, not the row, whose segments share out its width.+ implicitWidth: {+ let w = 8;+ for (const o of options) {+ w += metrics.advanceWidth(o.text) + 34;+ }+ return Math.ceil(w);+ }+ FontMetrics {+ id: metrics+ font.family: UI.Style.fontFamily+ font.pixelSize: UI.Style.px(14)+ font.weight: Font.DemiBold+ }+ implicitHeight: 38+ radius: 10+ color: UI.Style.surfaceSunken+ border.width: 1+ border.color: UI.Style.borderField+ activeFocusOnTab: true+ Accessible.role: Accessible.List++ Keys.onLeftPressed: step(-1)+ Keys.onRightPressed: step(1)+ function step(d) {+ const i = options.findIndex(o => o.value === value);+ const next = options[Math.max(0, Math.min(options.length - 1, i + d))];+ if (next) {+ chosen(next.value);+ }+ }++ Row {+ id: row+ anchors.fill: parent+ anchors.margins: 4+ spacing: 2+ Repeater {+ model: segments.options+ Rectangle {+ id: seg+ required property var modelData+ readonly property bool current: segments.value === modelData.value+ width: (row.width - row.spacing * (segments.options.length - 1)) / segments.options.length+ height: row.height+ radius: 7+ color: current ? UI.Style.tone(0.12) : segMouse.containsMouse ? UI.Style.surfaceHover : "transparent"+ Accessible.role: Accessible.RadioButton+ Accessible.name: modelData.text+ Accessible.checked: current+ UI.Label {+ id: segLabel+ anchors.centerIn: parent+ text: seg.modelData.text+ size: 14+ font.weight: seg.current ? Font.DemiBold : Font.Medium+ color: seg.current ? UI.Style.ink : UI.Style.inkMuted+ }+ MouseArea {+ id: segMouse+ anchors.fill: parent+ hoverEnabled: true+ cursorShape: Qt.PointingHandCursor+ onClicked: segments.chosen(seg.modelData.value)+ }+ }+ }+ }+ UI.FocusRing {+ visible: segments.activeFocus+ targetRadius: 10+ }+}diff --git a/packages/wildos-remote/qml/SessionChrome.qml b/packages/wildos-remote/qml/SessionChrome.qmlnew file mode 100644index 0000000..d28d045--- /dev/null+++ b/packages/wildos-remote/qml/SessionChrome.qml@@ -0,0 +1,601 @@+pragma ComponentBehavior: Bound++import QtQuick+import QtQuick.Layouts+import WildOS.Remote+import WildOS.UI as UI++// Everything of the terminal window that isn't a terminal (RemoteTerminal.dc,+// RemoteFiles.dc): the tabs in the title bar, the snippets panel, the+// status bar, the suggestions under the cursor and the files view. It is a+// transparent layer over the terminals, which the window lets the pointer+// through to wherever this layer isn't drawing.+Item {+ id: root++ readonly property var tab: host.currentTab+ readonly property bool glass: host.blurAvailable+ readonly property real radius: host.maximised ? 0 : UI.Style.windowRadius+ readonly property rect area: host.terminalArea+ // RemoteTerminal.dc: the bars are rgba(14,18,34,0.88) over the blur.+ readonly property color barColour: Qt.rgba(14 / 255, 18 / 255, 34 / 255, glass ? 0.88 : 1)+ property bool runAll: false++ // While any of these is up, the whole window belongs to this layer.+ Binding {+ target: host+ property: "chromeFull"+ value: tabMenu.opened || plusMenu.opened || runAllDialog.opened || forwardMenu.opened+ }++ // The suggestions under the cursor, and the part of the window they+ // take from the terminal.+ readonly property bool suggesting: tab !== null && tab.suggestions.length > 0 && !tab.filesOpen+ Binding {+ target: host+ property: "overlay"+ value: root.suggesting ? Qt.rect(suggestions.x, suggestions.y, suggestions.width, suggestions.height) : Qt.rect(0, 0, 0, 0)+ }++ // The title bar and status bar glass; the terminal area between them is+ // drawn by the window in the terminal's own colour.+ Rectangle {+ width: parent.width+ height: 46+ topLeftRadius: root.radius+ topRightRadius: root.radius+ color: root.barColour+ }+ Rectangle {+ y: parent.height - 32+ width: parent.width+ height: 32+ bottomLeftRadius: root.radius+ bottomRightRadius: root.radius+ color: root.barColour+ Rectangle {+ width: parent.width+ height: 1+ color: UI.Style.tone(0.06)+ }+ }++ // Title bar: moving the window from any empty part of it.+ MouseArea {+ width: parent.width+ height: 46+ property point origin+ onPressed: m => origin = Qt.point(m.x, m.y)+ onPositionChanged: m => {+ if (pressed && Math.abs(m.x - origin.x) + Math.abs(m.y - origin.y) > 4) {+ host.startMove();+ }+ }+ onDoubleClicked: host.toggleMaximised()+ }++ Image {+ x: 16+ y: 13+ width: 20+ height: 20+ source: "qrc:/qt/qml/WildOS/Remote/data/org.wildos.remote.svg"+ sourceSize: Qt.size(40, 40)+ MouseArea {+ id: homeMouse+ anchors.fill: parent+ hoverEnabled: true+ cursorShape: Qt.PointingHandCursor+ onClicked: host.showHome()+ }+ UI.Tooltip {+ text: qsTr("Your hosts")+ visible: homeMouse.containsMouse+ }+ }++ Row {+ id: tabRow+ x: 50+ y: 7+ height: 32+ spacing: 4+ Repeater {+ model: host.tabs+ Rectangle {+ id: tabItem+ required property var modelData+ required property int index+ readonly property bool current: index === host.currentIndex+ width: Math.min(200, tabText.implicitWidth + 58)+ height: 32+ radius: 8+ color: current ? UI.Style.tone(0.09) : tabMouse.containsMouse ? UI.Style.tone(0.05) : "transparent"+ Accessible.role: Accessible.PageTab+ Accessible.name: modelData.title++ Rectangle {+ x: 12+ anchors.verticalCenter: parent.verticalCenter+ width: 7+ height: 7+ radius: 3.5+ color: tabItem.modelData.ended ? UI.Style.inkDisabled : tabItem.modelData.colour+ }+ UI.Label {+ id: tabText+ x: 26+ anchors.verticalCenter: parent.verticalCenter+ width: Math.min(implicitWidth, 130)+ text: tabItem.modelData.title+ size: 14+ font.weight: tabItem.current ? Font.DemiBold : Font.Medium+ color: tabItem.current ? UI.Style.ink : UI.Style.inkMuted+ }+ MouseArea {+ id: tabMouse+ anchors.fill: parent+ hoverEnabled: true+ acceptedButtons: Qt.LeftButton | Qt.MiddleButton | Qt.RightButton+ onClicked: m => {+ if (m.button === Qt.MiddleButton) {+ host.closeTab(tabItem.index);+ } else if (m.button === Qt.RightButton) {+ root.openTabMenu(tabItem.index, tabItem, m.x, m.y);+ } else {+ host.currentIndex = tabItem.index;+ }+ }+ }+ UI.IconButton {+ anchors.right: parent.right+ anchors.rightMargin: 4+ anchors.verticalCenter: parent.verticalCenter+ width: 22+ height: 22+ radius: 5+ iconName: "close"+ iconSize: 11+ iconColor: UI.Style.iconMuted+ tip: qsTr("Close tab")+ focusPolicy: Qt.NoFocus+ onClicked: host.closeTab(tabItem.index)+ }+ }+ }+ UI.IconButton {+ id: plusButton+ width: 32+ height: 32+ iconName: "plus"+ iconSize: 15+ iconColor: UI.Style.iconMuted+ tip: qsTr("New tab")+ focusPolicy: Qt.NoFocus+ onClicked: root.openPlusMenu()+ }+ }++ Row {+ id: tools+ anchors.right: windowButtons.left+ anchors.rightMargin: 14+ y: 6+ spacing: 2+ ToolButton {+ glyph: RemoteIcons.columns+ tip: root.tab && root.tab.split ? qsTr("One terminal") : qsTr("Two terminals side by side")+ on: root.tab !== null && root.tab.split+ enabled: root.tab !== null && !root.tab.filesOpen && !root.tab.ended+ onClicked: root.tab.toggleSplit()+ }+ ToolButton {+ glyph: RemoteIcons.folder+ tip: root.tab && root.tab.filesOpen ? qsTr("Back to the terminal") : qsTr("Files")+ on: root.tab !== null && root.tab.filesOpen+ enabled: root.tab !== null && !root.tab.local+ onClicked: root.tab.setFilesOpen(!root.tab.filesOpen)+ }+ ToolButton {+ glyph: RemoteIcons.snippets+ tip: host.snippetsOpen ? qsTr("Hide snippets") : qsTr("Snippets")+ on: host.snippetsOpen+ onClicked: host.snippetsOpen = !host.snippetsOpen+ }+ ToolButton {+ id: forwardButton+ glyph: RemoteIcons.forward+ tip: qsTr("Port forwarding")+ enabled: root.tab !== null && !root.tab.local+ onClicked: root.openForwardMenu()+ }+ }++ UI.WindowButtons {+ id: windowButtons+ anchors.right: parent.right+ handleActions: false+ buttonHeight: 46+ maximised: host.maximised+ windowActive: host.windowActive+ onMinimiseClicked: host.minimise()+ onMaximiseClicked: host.toggleMaximised()+ onCloseClicked: host.closeWindow()+ }++ // The snippets panel.+ Rectangle {+ id: panel+ visible: host.snippetsOpen+ x: parent.width - 332+ y: 46+ width: 332+ height: parent.height - 46 - 32+ color: root.barColour+ Rectangle {+ width: 1+ height: parent.height+ color: UI.Style.tone(0.06)+ }+ SnippetsPanel {+ anchors.fill: parent+ anchors.leftMargin: 17+ anchors.rightMargin: 16+ anchors.topMargin: 14+ anchors.bottomMargin: 16+ tab: root.tab+ runAll: root.runAll+ onRunAllToggled: root.runAll = !root.runAll+ onRunRequested: command => root.runSnippet(command)+ }+ }++ function runSnippet(command) {+ if (!root.tab) {+ return;+ }+ if (root.runAll && host.terminalTabCount() > 1) {+ runAllDialog.command = command;+ runAllDialog.open();+ return;+ }+ root.tab.run(command);+ }++ // The files, over where the terminal is.+ FilesView {+ visible: root.tab !== null && root.tab.filesOpen+ x: root.area.x+ y: root.area.y+ width: root.area.width+ height: root.area.height+ tab: root.tab+ onNotice: text => toast.show(text)+ }++ // The connection ended.+ Rectangle {+ visible: root.tab !== null && root.tab.ended && !root.tab.filesOpen+ x: root.area.x + 16+ y: root.area.y + root.area.height - height - 16+ width: root.area.width - 32+ height: 56+ radius: 12+ color: UI.Style.glassMenu+ border.width: 1+ border.color: UI.Style.borderMenu+ UI.Icon {+ x: 18+ anchors.verticalCenter: parent.verticalCenter+ name: "info"+ size: 17+ color: UI.Style.accent+ }+ UI.Label {+ x: 46+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - 46 - endButtons.width - 30+ text: root.tab && root.tab.local ? qsTr("The shell has ended.")+ : root.tab ? qsTr("The connection to %1 has ended. What ssh said is above.").arg(root.tab.title) : ""+ size: 14+ }+ Row {+ id: endButtons+ anchors.right: parent.right+ anchors.rightMargin: 12+ anchors.verticalCenter: parent.verticalCenter+ spacing: 8+ UI.Button {+ size: "small"+ text: qsTr("Close tab")+ onClicked: host.closeTab(host.currentIndex)+ }+ UI.Button {+ size: "small"+ kind: "primary"+ text: root.tab && root.tab.local ? qsTr("Start again") : qsTr("Reconnect")+ onClicked: root.tab.reconnect()+ }+ }+ }++ // Suggestions under the cursor (RemoteTerminal.dc).+ Rectangle {+ id: suggestions+ visible: root.suggesting+ readonly property rect cursor: root.tab ? root.tab.cursor : Qt.rect(0, 0, 0, 0)+ width: 482+ height: suggestionColumn.implicitHeight + 12+ x: Math.min(root.area.x + Math.max(0, cursor.x - 28), root.area.x + root.area.width - width - 8)+ y: {+ const below = root.area.y + cursor.y + cursor.height + 10;+ return below + height > root.area.y + root.area.height ? root.area.y + cursor.y - height - 8 : below;+ }+ radius: 10+ color: Qt.rgba(22 / 255, 27 / 255, 46 / 255, 0.98)+ border.width: 1+ border.color: UI.Style.tone(0.12)++ Column {+ id: suggestionColumn+ x: 6+ y: 6+ width: parent.width - 12+ Repeater {+ model: root.suggesting ? root.tab.suggestions : []+ Rectangle {+ id: suggestion+ required property var modelData+ required property int index+ readonly property bool current: root.tab && index === root.tab.selected+ width: suggestionColumn.width+ height: 34+ radius: 7+ color: current ? UI.Style.tone(0.09) : "transparent"+ UI.Glyph {+ x: 10+ anchors.verticalCenter: parent.verticalCenter+ width: 14+ height: 14+ path: suggestion.modelData.kind === "snippet" ? RemoteIcons.snippets : RemoteIcons.clock+ color: suggestion.modelData.kind === "snippet" ? UI.Style.accent : UI.Style.iconMuted+ }+ UI.Label {+ x: 34+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - 34 - detail.width - 20+ text: suggestion.modelData.text+ size: 13+ font.family: "JetBrains Mono"+ }+ UI.Label {+ id: detail+ anchors.right: parent.right+ anchors.rightMargin: 10+ anchors.verticalCenter: parent.verticalCenter+ text: suggestion.modelData.detail+ size: 12+ font.family: "JetBrains Mono"+ color: UI.Style.inkSubtle+ }+ MouseArea {+ anchors.fill: parent+ cursorShape: Qt.PointingHandCursor+ onClicked: root.tab.accept(suggestion.index)+ }+ }+ }+ UI.Label {+ leftPadding: 10+ topPadding: 6+ bottomPadding: 2+ text: qsTr("Tab to accept, keep typing to ignore. History stays on this PC")+ size: 12+ font.family: "JetBrains Mono"+ color: UI.Style.inkSubtle+ }+ }+ }++ // Status bar.+ RowLayout {+ x: 14+ y: parent.height - 32+ width: parent.width - 28+ height: 32+ spacing: 22+ visible: root.tab !== null++ UI.Label {+ text: root.tab ? root.tab.userHost : ""+ size: 13+ font.weight: Font.DemiBold+ }+ Row {+ spacing: 7+ UI.Icon {+ anchors.verticalCenter: parent.verticalCenter+ name: "lock"+ size: 13+ color: UI.Style.success+ }+ UI.Label {+ anchors.verticalCenter: parent.verticalCenter+ text: root.tab ? root.tab.auth : ""+ size: 13+ color: UI.Style.inkMuted+ }+ }+ Row {+ visible: root.tab !== null && root.tab.forwards.length > 0+ spacing: 7+ UI.Glyph {+ anchors.verticalCenter: parent.verticalCenter+ width: 13+ height: 13+ path: RemoteIcons.forward+ color: "#c78bff"+ }+ UI.Label {+ anchors.verticalCenter: parent.verticalCenter+ text: root.tab && root.tab.forwards.length > 0 ? root.tab.forwards[0] + (root.tab.forwards.length > 1 ? qsTr(" and %1 more").arg(root.tab.forwards.length - 1) : "") : ""+ size: 13+ color: UI.Style.inkMuted+ }+ }+ Row {+ visible: root.tab !== null && root.tab.latency.length > 0+ spacing: 7+ UI.Glyph {+ anchors.verticalCenter: parent.verticalCenter+ width: 13+ height: 13+ path: RemoteIcons.signal+ color: UI.Style.success+ }+ UI.Label {+ anchors.verticalCenter: parent.verticalCenter+ text: root.tab ? root.tab.latency : ""+ size: 13+ color: UI.Style.inkMuted+ MouseArea {+ id: latencyMouse+ anchors.fill: parent+ anchors.leftMargin: -20+ hoverEnabled: true+ }+ UI.Tooltip {+ text: qsTr("How long the server took to answer when this tab connected")+ visible: latencyMouse.containsMouse+ }+ }+ }+ Item { Layout.fillWidth: true }+ UI.Label {+ text: "UTF-8"+ size: 13+ color: UI.Style.inkMuted+ }+ UI.Label {+ text: root.tab ? root.tab.size : ""+ size: 13+ color: UI.Style.inkMuted+ }+ }++ // Resize grips, outside the terminal.+ ResizeGrips {+ anchors.fill: parent+ enabled: !host.maximised+ }++ // The window's hairline edge, over everything.+ Rectangle {+ anchors.fill: parent+ radius: root.radius+ color: "transparent"+ border.width: host.maximised ? 0 : 1+ border.color: UI.Style.windowEdge+ z: 900+ }++ function openTabMenu(index, item, x, y) {+ const t = host.tabs[index];+ tabMenu.entries = [+ { text: qsTr("Reconnect"), icon: "refresh", enabled: t.ended, run: () => t.reconnect() },+ { text: qsTr("Edit host"), icon: "pencil", enabled: !t.local, run: () => host.editHost(t.hostId) },+ { separator: true },+ { text: qsTr("Close tab"), icon: "close", shortcut: "Ctrl+Shift+W", run: () => host.closeTab(index) }+ ];+ tabMenu.popup(item, x, y);+ }+ function openPlusMenu() {+ const entries = [{ text: qsTr("This PC"), icon: "computer", shortcut: "Ctrl+Shift+T", run: () => host.openLocal() }, { separator: true }];+ for (const h of Hosts.hosts) {+ if (h.kind === "terminal") {+ entries.push({ text: h.name, icon: "terminal", run: () => host.openHost(h.id) });+ }+ }+ entries.push({ separator: true }, { text: qsTr("All hosts"), icon: "monitor", run: () => host.showHome() });+ plusMenu.entries = entries;+ plusMenu.popup(plusButton, 0, plusButton.height + 4);+ }+ function openForwardMenu() {+ const entries = [];+ for (const f of root.tab.forwards) {+ entries.push({ text: f, enabled: false });+ }+ if (entries.length === 0) {+ entries.push({ text: qsTr("No ports forwarded"), enabled: false });+ }+ entries.push({ separator: true }, { text: qsTr("Change forwards"), icon: "pencil", run: () => host.editHost(root.tab.hostId) });+ forwardMenu.entries = entries;+ forwardMenu.popup(forwardButton, 0, forwardButton.height + 4);+ }++ UI.Menu {+ id: tabMenu+ }+ UI.Menu {+ id: plusMenu+ minimumWidth: 230+ }+ UI.Menu {+ id: forwardMenu+ minimumWidth: 260+ }++ UI.Dialog {+ id: runAllDialog+ property string command+ title: qsTr("Run in %1 tabs?").arg(host.terminalTabCount())+ text: qsTr("%1 runs on every open tab, which may be on different servers.").arg(command)+ buttons: [+ UI.Button {+ text: qsTr("Cancel")+ onClicked: runAllDialog.close()+ },+ UI.Button {+ kind: "primary"+ text: qsTr("Run in all")+ onClicked: {+ host.runEverywhere(runAllDialog.command);+ runAllDialog.close();+ }+ }+ ]+ }++ UI.Toast {+ id: toast+ anchors.horizontalCenter: parent.horizontalCenter+ anchors.bottom: parent.bottom+ anchors.bottomMargin: 48+ z: 60+ }++ component ToolButton: UI.IconButton {+ property bool on: false+ width: 34+ height: 34+ radius: 8+ iconSize: 16+ iconColor: on ? UI.Style.accent : UI.Style.iconMuted+ stroke: 1.8+ checked: on+ focusPolicy: Qt.NoFocus+ }++ component ResizeGrips: Item {+ id: grips+ readonly property int g: 5+ MouseArea { width: grips.width; height: grips.g; cursorShape: Qt.SizeVerCursor; enabled: grips.enabled; onPressed: host.startResize(Qt.TopEdge) }+ MouseArea { y: grips.height - grips.g; width: grips.width; height: grips.g; cursorShape: Qt.SizeVerCursor; enabled: grips.enabled; onPressed: host.startResize(Qt.BottomEdge) }+ MouseArea { width: grips.g; height: grips.height; cursorShape: Qt.SizeHorCursor; enabled: grips.enabled; onPressed: host.startResize(Qt.LeftEdge) }+ MouseArea { x: grips.width - grips.g; width: grips.g; height: grips.height; cursorShape: Qt.SizeHorCursor; enabled: grips.enabled; onPressed: host.startResize(Qt.RightEdge) }+ MouseArea { width: 10; height: 10; cursorShape: Qt.SizeFDiagCursor; enabled: grips.enabled; onPressed: host.startResize(Qt.TopEdge | Qt.LeftEdge) }+ MouseArea { x: grips.width - 10; width: 10; height: 10; cursorShape: Qt.SizeBDiagCursor; enabled: grips.enabled; onPressed: host.startResize(Qt.TopEdge | Qt.RightEdge) }+ MouseArea { y: grips.height - 10; width: 10; height: 10; cursorShape: Qt.SizeBDiagCursor; enabled: grips.enabled; onPressed: host.startResize(Qt.BottomEdge | Qt.LeftEdge) }+ MouseArea { x: grips.width - 10; y: grips.height - 10; width: 10; height: 10; cursorShape: Qt.SizeFDiagCursor; enabled: grips.enabled; onPressed: host.startResize(Qt.BottomEdge | Qt.RightEdge) }+ }+}diff --git a/packages/wildos-remote/qml/Sidebar.qml b/packages/wildos-remote/qml/Sidebar.qmlnew file mode 100644index 0000000..85c86fa--- /dev/null+++ b/packages/wildos-remote/qml/Sidebar.qml@@ -0,0 +1,262 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Remote+import WildOS.UI as UI++// The side column (RemoteHosts.dc): every host, favourites, the groups,+// then the tools, and what Remote keeps where at the foot.+Item {+ id: side++ property string page: "hosts"+ signal pageChosen(string page)+ signal newGroup()+ signal groupMenu(string name, Item item)++ readonly property var hosts: Hosts.hosts+ function count(test) {+ let n = 0;+ for (const h of hosts) {+ if (test(h)) {+ n++;+ }+ }+ return n;+ }+ function forwardCount() {+ let n = 0;+ for (const h of hosts) {+ if (h.kind === "terminal") {+ n += (h.ssh.forwards || []).length;+ }+ }+ return n;+ }++ implicitWidth: 236++ Rectangle {+ anchors.right: parent.right+ width: 1+ height: parent.height+ color: UI.Style.divider+ }++ Flickable {+ anchors.fill: parent+ anchors.bottomMargin: footCard.height + 28+ contentHeight: column.height + 24+ clip: true+ boundsBehavior: Flickable.StopAtBounds++ Column {+ id: column+ x: 10+ y: 6+ width: side.width - 21+ spacing: 2++ NavRow {+ width: parent.width+ text: qsTr("All hosts")+ iconName: "monitor"+ count: side.hosts.length+ current: side.page === "hosts"+ onClicked: side.pageChosen("hosts")+ }+ NavRow {+ width: parent.width+ text: qsTr("Favourites")+ iconName: "star"+ count: side.count(h => h.favourite)+ current: side.page === "favourites"+ onClicked: side.pageChosen("favourites")+ }++ UI.Label {+ text: qsTr("Groups")+ size: 12+ color: UI.Style.inkSubtle+ font.weight: Font.Medium+ leftPadding: 10+ topPadding: 14+ bottomPadding: 6+ }+ Repeater {+ model: Hosts.groups+ NavRow {+ id: groupRow+ required property string modelData+ width: column.width+ text: modelData+ iconName: modelData === "Servers" ? "server" : modelData === "Home" ? "home" : "box"+ count: side.count(h => h.group === modelData)+ current: side.page === "group:" + modelData+ onClicked: side.pageChosen("group:" + modelData)+ onMenuRequested: side.groupMenu(modelData, groupRow)+ }+ }+ NavRow {+ width: parent.width+ text: qsTr("New group")+ iconName: "plus"+ muted: true+ count: -1+ onClicked: side.newGroup()+ }++ UI.Label {+ text: qsTr("Tools")+ size: 12+ color: UI.Style.inkSubtle+ font.weight: Font.Medium+ leftPadding: 10+ topPadding: 14+ bottomPadding: 6+ }+ NavRow {+ width: parent.width+ text: qsTr("Keychain")+ glyph: RemoteIcons.key+ count: Keychain.keys.length+ current: side.page === "keychain"+ onClicked: side.pageChosen("keychain")+ }+ NavRow {+ width: parent.width+ text: qsTr("Snippets")+ glyph: RemoteIcons.snippets+ count: Snippets.snippets.length+ current: side.page === "snippets"+ onClicked: side.pageChosen("snippets")+ }+ NavRow {+ width: parent.width+ text: qsTr("Port forwarding")+ glyph: RemoteIcons.forward+ count: side.forwardCount()+ current: side.page === "forwarding"+ onClicked: side.pageChosen("forwarding")+ }+ NavRow {+ width: parent.width+ text: qsTr("Known hosts")+ glyph: RemoteIcons.knownHosts+ count: HostKeys.known.length+ current: side.page === "knownhosts"+ onClicked: side.pageChosen("knownhosts")+ }+ }+ }++ // What lives where, said plainly (RemoteStart.dc's "Passwords kept+ // safe" and RemoteHosts.dc's "No cloud sync" in one card).+ Rectangle {+ id: footCard+ anchors.left: parent.left+ anchors.right: parent.right+ anchors.bottom: parent.bottom+ anchors.margins: 14+ anchors.rightMargin: 15+ height: footText.implicitHeight + 28+ radius: 10+ color: UI.Style.surfaceRest+ border.width: 1+ border.color: UI.Style.borderSubtle++ UI.Glyph {+ x: 14+ y: 15+ width: 18+ height: 18+ path: RemoteIcons.noSync+ color: UI.Style.accent+ strokeWidth: 1.8+ }+ Column {+ id: footText+ x: 42+ y: 14+ width: parent.width - 54+ spacing: 3+ UI.Label {+ width: parent.width+ text: qsTr("No cloud sync")+ size: 13+ font.weight: Font.DemiBold+ }+ UI.Label {+ width: parent.width+ text: qsTr("Hosts and keys live on this PC only. Passwords go in your keyring, and only if you tick it.")+ size: 12+ color: UI.Style.inkMuted+ wrapMode: Text.Wrap+ lineHeight: 1.3+ }+ }+ }++ component NavRow: Rectangle {+ id: row+ property string text+ property string iconName+ property string glyph+ property int count: 0+ property bool current: false+ property bool muted: false+ signal clicked()+ signal menuRequested()++ height: 36+ radius: UI.Style.radiusSm+ color: current ? UI.Style.accentSoft : mouse.containsMouse ? UI.Style.surfaceHover : "transparent"+ Accessible.role: Accessible.Button+ Accessible.name: text++ UI.Icon {+ visible: row.glyph.length === 0+ x: 10+ anchors.verticalCenter: parent.verticalCenter+ name: row.iconName+ size: 17+ strokeWidth: 1.8+ color: row.current ? UI.Style.accent : UI.Style.iconMuted+ }+ UI.Glyph {+ visible: row.glyph.length > 0+ x: 10+ anchors.verticalCenter: parent.verticalCenter+ width: 17+ height: 17+ path: row.glyph+ strokeWidth: 1.8+ color: row.current ? UI.Style.accent : UI.Style.iconMuted+ }+ UI.Label {+ x: 38+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - 80+ text: row.text+ size: 14+ font.weight: row.current ? Font.DemiBold : Font.Medium+ color: row.muted ? UI.Style.inkMuted : UI.Style.ink+ }+ UI.Label {+ visible: row.count >= 0+ anchors.right: parent.right+ anchors.rightMargin: 10+ anchors.verticalCenter: parent.verticalCenter+ text: row.count+ size: 12+ color: UI.Style.inkSubtle+ }+ MouseArea {+ id: mouse+ anchors.fill: parent+ hoverEnabled: true+ acceptedButtons: Qt.LeftButton | Qt.RightButton+ cursorShape: Qt.PointingHandCursor+ onClicked: m => m.button === Qt.RightButton ? row.menuRequested() : row.clicked()+ }+ }+}diff --git a/packages/wildos-remote/qml/SignInDialog.qml b/packages/wildos-remote/qml/SignInDialog.qmlnew file mode 100644index 0000000..16bc5af--- /dev/null+++ b/packages/wildos-remote/qml/SignInDialog.qml@@ -0,0 +1,191 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Remote+import WildOS.UI as UI++// Signing in to a PC (RemoteSignIn.dc): the connection is up and checked,+// and Windows is waiting for an account.+Panel {+ id: dialog++ property var desktop: null+ property string error+ property bool answered: false++ width: 460+ padding: 28++ function ask(d, user, reason) {+ desktop = d;+ error = reason === "wrong" ? qsTr("That didn't work. Check the username and password, then try again.") : "";+ userField.text = user || "";+ password.text = "";+ save.checked = false;+ answered = false;+ open();+ if (userField.text.length > 0) {+ password.forceActiveFocus();+ } else {+ userField.forceActiveFocus();+ }+ }++ onClosed: {+ if (!answered && desktop) {+ desktop.cancelSignIn();+ }+ password.text = "";+ }++ contentItem: ColumnLayout {+ spacing: 14++ RowLayout {+ spacing: 14+ Image {+ Layout.preferredWidth: 40+ Layout.preferredHeight: 40+ source: "qrc:/qt/qml/WildOS/Remote/data/org.wildos.remote.svg"+ sourceSize: Qt.size(80, 80)+ }+ ColumnLayout {+ spacing: 2+ UI.Label {+ text: dialog.desktop ? qsTr("Sign in to %1").arg(dialog.desktop.name) : ""+ size: 20+ font.weight: Font.Bold+ }+ UI.Label {+ text: dialog.desktop ? dialog.desktop.address : ""+ size: 13+ color: UI.Style.inkMuted+ }+ }+ }++ Rectangle {+ Layout.fillWidth: true+ Layout.preferredHeight: 56+ radius: 10+ color: dialog.error.length > 0 ? Qt.rgba(255 / 255, 154 / 255, 138 / 255, 0.10) : UI.Style.tone(0.05)+ RowLayout {+ anchors.fill: parent+ anchors.leftMargin: 14+ anchors.rightMargin: 14+ spacing: 12+ UI.Spinner {+ visible: dialog.error.length === 0+ size: 22+ running: dialog.visible+ }+ UI.Icon {+ visible: dialog.error.length > 0+ name: "warning"+ size: 18+ color: "#ff9a8a"+ }+ ColumnLayout {+ Layout.fillWidth: true+ spacing: 1+ UI.Label {+ Layout.fillWidth: true+ text: dialog.error.length > 0 ? qsTr("Windows didn't accept that") : dialog.desktop ? qsTr("Connected to %1").arg(dialog.desktop.name) : ""+ size: 13+ font.weight: Font.DemiBold+ }+ UI.Label {+ Layout.fillWidth: true+ text: dialog.error.length > 0 ? dialog.error : qsTr("Its identity checks out. Waiting for you to sign in")+ size: 12+ color: UI.Style.inkMuted+ wrapMode: Text.Wrap+ }+ }+ }+ }++ UI.Label {+ text: qsTr("Username")+ size: 13+ font.weight: Font.DemiBold+ }+ UI.TextField {+ id: userField+ Layout.fillWidth: true+ size: "large"+ leftPadding: 40+ placeholderText: qsTr("Name, or DOMAIN\\name")+ UI.Icon {+ x: 14+ anchors.verticalCenter: parent.verticalCenter+ name: "account"+ size: 15+ color: UI.Style.iconMuted+ }+ }+ UI.Label {+ text: qsTr("Password")+ size: 13+ font.weight: Font.DemiBold+ }+ UI.TextField {+ id: password+ Layout.fillWidth: true+ size: "large"+ leftPadding: 40+ revealable: true+ placeholderText: qsTr("Password")+ onAccepted: go.clicked()+ UI.Icon {+ x: 14+ anchors.verticalCenter: parent.verticalCenter+ name: "lock"+ size: 15+ color: UI.Style.iconMuted+ }+ }+ RowLayout {+ spacing: 12+ UI.Toggle {+ id: save+ Accessible.name: saveLabel.text+ }+ UI.Label {+ id: saveLabel+ text: qsTr("Save in my keyring")+ size: 14+ }+ }+ UI.Label {+ Layout.fillWidth: true+ text: qsTr("Your keyring is locked with your Wild OS password, so saved passwords are only readable while you're signed in. Nothing is saved until Windows accepts it.")+ size: 12+ color: UI.Style.inkMuted+ wrapMode: Text.Wrap+ lineHeight: 1.35+ }+ RowLayout {+ Layout.fillWidth: true+ Layout.topMargin: 4+ spacing: 10+ Item { Layout.fillWidth: true }+ UI.Button {+ size: "large"+ text: qsTr("Cancel")+ onClicked: dialog.close()+ }+ UI.Button {+ id: go+ size: "large"+ kind: "primary"+ text: qsTr("Sign in")+ enabled: userField.text.trim().length > 0 && password.text.length > 0+ onClicked: {+ dialog.answered = true;+ dialog.desktop.signIn(userField.text.trim(), password.text, save.checked);+ dialog.close();+ }+ }+ }+ }+}diff --git a/packages/wildos-remote/qml/SnippetDialog.qml b/packages/wildos-remote/qml/SnippetDialog.qmlnew file mode 100644index 0000000..2bd8237--- /dev/null+++ b/packages/wildos-remote/qml/SnippetDialog.qml@@ -0,0 +1,63 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Remote+import WildOS.UI as UI++// A snippet: a name, the command, and a short note shown with it.+UI.Dialog {+ id: dialog++ property var snippet: ({})++ function edit(s) {+ snippet = s || {};+ title = snippet.id ? qsTr("Edit snippet") : qsTr("New snippet");+ name.text = snippet.title || "";+ command.text = snippet.command || "";+ note.text = snippet.note || "";+ open();+ name.forceActiveFocus();+ }++ UI.TextField {+ id: name+ Layout.fillWidth: true+ placeholderText: qsTr("Name, like Reload nginx safely")+ }+ UI.TextField {+ id: command+ Layout.fillWidth: true+ font.family: "JetBrains Mono"+ placeholderText: "sudo nginx -t && sudo systemctl reload nginx"+ }+ UI.TextField {+ id: note+ Layout.fillWidth: true+ placeholderText: qsTr("Note, like tests the config first")+ }++ buttons: [+ UI.Button {+ visible: dialog.snippet.id !== undefined+ danger: true+ text: qsTr("Delete")+ onClicked: {+ Snippets.remove(dialog.snippet.id);+ dialog.close();+ }+ },+ UI.Button {+ text: qsTr("Cancel")+ onClicked: dialog.close()+ },+ UI.Button {+ kind: "primary"+ text: qsTr("Save")+ enabled: name.text.trim().length > 0 && command.text.trim().length > 0+ onClicked: {+ Snippets.save({ id: dialog.snippet.id || "", title: name.text.trim(), command: command.text.trim(), note: note.text.trim() });+ dialog.close();+ }+ }+ ]+}diff --git a/packages/wildos-remote/qml/SnippetsPage.qml b/packages/wildos-remote/qml/SnippetsPage.qmlnew file mode 100644index 0000000..ee5de08--- /dev/null+++ b/packages/wildos-remote/qml/SnippetsPage.qml@@ -0,0 +1,122 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Remote+import WildOS.UI as UI++// Saved commands, the same list the terminal's snippets panel runs from.+Item {+ id: page++ signal editRequested(var snippet)++ ColumnLayout {+ anchors.fill: parent+ anchors.leftMargin: 36+ anchors.rightMargin: 36+ anchors.topMargin: 22+ anchors.bottomMargin: 26+ spacing: 14++ RowLayout {+ Layout.fillWidth: true+ Layout.preferredHeight: 44+ ColumnLayout {+ Layout.fillWidth: true+ spacing: 2+ UI.Label {+ text: qsTr("Snippets")+ size: 26+ font.weight: Font.Bold+ }+ }+ UI.Button {+ size: "small"+ kind: "primary"+ iconName: "plus"+ text: qsTr("New snippet")+ onClicked: page.editRequested({})+ }+ }+ UI.Label {+ Layout.fillWidth: true+ text: qsTr("Commands you run often, ready in the terminal's side panel, and offered as you type. They stay on this PC.")+ size: 14+ color: UI.Style.inkMuted+ wrapMode: Text.Wrap+ }++ ListView {+ Layout.fillWidth: true+ Layout.fillHeight: true+ Layout.maximumWidth: 900+ spacing: 10+ clip: true+ model: Snippets.snippets+ boundsBehavior: Flickable.StopAtBounds+ delegate: Rectangle {+ id: row+ required property var modelData+ width: ListView.view.width+ height: 66+ radius: 12+ color: rowMouse.containsMouse ? UI.Style.tone(0.07) : UI.Style.tone(0.045)+ border.width: 1+ border.color: UI.Style.tone(0.07)+ Column {+ x: 18+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - 80+ spacing: 5+ Row {+ spacing: 10+ UI.Label {+ text: row.modelData.title+ size: 15+ font.weight: Font.DemiBold+ }+ UI.Label {+ visible: (row.modelData.note || "").length > 0+ anchors.baseline: parent.children[0].baseline+ text: row.modelData.note || ""+ size: 13+ color: UI.Style.inkSubtle+ }+ }+ UI.Label {+ width: parent.width+ text: row.modelData.command+ size: 13+ font.family: "JetBrains Mono"+ color: UI.Style.inkMuted+ }+ }+ UI.IconButton {+ anchors.right: parent.right+ anchors.rightMargin: 12+ anchors.verticalCenter: parent.verticalCenter+ iconName: "pencil"+ tip: qsTr("Edit")+ onClicked: page.editRequested(row.modelData)+ }+ MouseArea {+ id: rowMouse+ anchors.fill: parent+ anchors.rightMargin: 56+ hoverEnabled: true+ onDoubleClicked: page.editRequested(row.modelData)+ }+ }+ footer: Column {+ visible: Snippets.snippets.length === 0+ width: ListView.view.width+ topPadding: 40+ UI.Label {+ anchors.horizontalCenter: parent.horizontalCenter+ text: qsTr("No snippets yet")+ size: 18+ font.weight: Font.DemiBold+ }+ }+ }+ }+}diff --git a/packages/wildos-remote/qml/SnippetsPanel.qml b/packages/wildos-remote/qml/SnippetsPanel.qmlnew file mode 100644index 0000000..9eb6998--- /dev/null+++ b/packages/wildos-remote/qml/SnippetsPanel.qml@@ -0,0 +1,190 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Remote+import WildOS.UI as UI++// The terminal's snippets (RemoteTerminal.dc): saved commands to run with+// one click, a search over them, and whether a click runs in every open+// tab.+Item {+ id: panel++ property var tab: null+ property bool runAll: false+ property string chosen++ signal runRequested(string command)+ signal runAllToggled()++ readonly property var shown: {+ const q = search.text.trim().toLowerCase();+ return Snippets.snippets.filter(s => q.length === 0 || (s.title + " " + s.command).toLowerCase().indexOf(q) >= 0);+ }++ ColumnLayout {+ anchors.fill: parent+ spacing: 12++ RowLayout {+ Layout.fillWidth: true+ UI.Label {+ Layout.fillWidth: true+ text: qsTr("Snippets")+ size: 16+ font.weight: Font.Bold+ }+ UI.IconButton {+ width: 28+ height: 28+ iconName: "plus"+ iconSize: 15+ iconColor: UI.Style.iconMuted+ tip: qsTr("New snippet")+ focusPolicy: Qt.NoFocus+ onClicked: snippetDialog.edit({})+ }+ }+ UI.TextField {+ id: search+ Layout.fillWidth: true+ height: 32+ leftPadding: 34+ placeholderText: qsTr("Search snippets")+ UI.Icon {+ x: 12+ anchors.verticalCenter: parent.verticalCenter+ name: "search"+ size: 14+ color: UI.Style.iconMuted+ }+ }++ ListView {+ Layout.fillWidth: true+ Layout.fillHeight: true+ spacing: 10+ clip: true+ model: panel.shown+ boundsBehavior: Flickable.StopAtBounds+ delegate: Rectangle {+ id: card+ required property var modelData+ readonly property bool current: panel.chosen === modelData.id+ width: ListView.view.width+ height: 61+ radius: 10+ color: current ? Qt.rgba(143 / 255, 180 / 255, 255 / 255, 0.12) : cardMouse.containsMouse ? UI.Style.tone(0.06) : UI.Style.tone(0.04)+ border.width: 1+ border.color: current ? Qt.rgba(143 / 255, 180 / 255, 255 / 255, 0.5) : UI.Style.tone(0.06)+ Column {+ x: 12+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - 48+ spacing: 6+ UI.Label {+ width: parent.width+ text: card.modelData.title+ size: 14+ font.weight: Font.DemiBold+ }+ UI.Label {+ width: parent.width+ text: card.modelData.command+ size: 12+ font.family: "JetBrains Mono"+ color: UI.Style.inkMuted+ }+ }+ MouseArea {+ id: cardMouse+ anchors.fill: parent+ hoverEnabled: true+ acceptedButtons: Qt.LeftButton | Qt.RightButton+ onClicked: m => {+ panel.chosen = card.modelData.id;+ if (m.button === Qt.RightButton) {+ snippetDialog.edit(card.modelData);+ }+ }+ onDoubleClicked: panel.runRequested(card.modelData.command)+ }+ UI.IconButton {+ anchors.right: parent.right+ anchors.rightMargin: 6+ anchors.top: parent.top+ anchors.topMargin: 6+ width: 26+ height: 26+ glyph: RemoteIcons.play+ iconSize: 13+ iconColor: card.current ? UI.Style.accent : UI.Style.iconMuted+ tip: panel.runAll ? qsTr("Run in all open tabs") : qsTr("Run")+ focusPolicy: Qt.NoFocus+ enabled: panel.tab !== null && !panel.tab.ended+ onClicked: {+ panel.chosen = card.modelData.id;+ panel.runRequested(card.modelData.command);+ }+ }+ }+ footer: UI.Label {+ visible: panel.shown.length === 0+ width: ListView.view.width+ topPadding: 20+ horizontalAlignment: Text.AlignHCenter+ wrapMode: Text.Wrap+ text: Snippets.snippets.length === 0 ? qsTr("Save commands you run often, and run them from here.") : qsTr("No snippet matches")+ size: 13+ color: UI.Style.inkMuted+ }+ }++ Rectangle {+ Layout.fillWidth: true+ Layout.preferredHeight: 68+ radius: 10+ color: UI.Style.tone(0.04)+ border.width: 1+ border.color: UI.Style.tone(0.06)+ UI.Glyph {+ x: 13+ anchors.verticalCenter: parent.verticalCenter+ width: 16+ height: 16+ path: RemoteIcons.broadcast+ color: panel.runAll ? UI.Style.accent : UI.Style.iconMuted+ }+ Column {+ x: 38+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - 38 - 64+ spacing: 2+ UI.Label {+ text: qsTr("Run in all open tabs")+ size: 13+ font.weight: Font.DemiBold+ }+ UI.Label {+ width: parent.width+ text: qsTr("Asks before running on more than one server")+ size: 12+ color: UI.Style.inkMuted+ wrapMode: Text.Wrap+ }+ }+ UI.Toggle {+ anchors.right: parent.right+ anchors.rightMargin: 12+ anchors.verticalCenter: parent.verticalCenter+ checked: panel.runAll+ focusPolicy: Qt.NoFocus+ Accessible.name: qsTr("Run in all open tabs")+ onToggled: panel.runAllToggled()+ }+ }+ }++ SnippetDialog {+ id: snippetDialog+ }+}diff --git a/packages/wildos-remote/src/app.cpp b/packages/wildos-remote/src/app.cppnew file mode 100644index 0000000..9442913--- /dev/null+++ b/packages/wildos-remote/src/app.cpp@@ -0,0 +1,194 @@+#include "app.h"+#include "hosts.h"+#include "keychain.h"+#include "sessionwindow.h"++#include <QApplication>+#include <QClipboard>+#include <QDir>+#include <QKeyEvent>+#include <QProcess>+#include <QQuickWindow>+#include <QUrl>+#include <QWidget>+#include <QWindow>++App *App::instance()+{+ static App *app = new App;+ return app;+}++App *App::create(QQmlEngine *, QJSEngine *)+{+ App *a = instance();+ QJSEngine::setObjectOwnership(a, QJSEngine::CppOwnership);+ return a;+}++App::App(QObject *parent)+ : QObject(parent)+{+}++QString App::version() const+{+ return QStringLiteral(WILDOS_REMOTE_VERSION);+}++QString App::homePath() const+{+ return QDir::homePath();+}++QUrl App::testScript() const+{+ const QString path = qEnvironmentVariable("WILDOS_REMOTE_TEST");+ return path.isEmpty() ? QUrl() : QUrl::fromLocalFile(path);+}++void App::testShot(const QString &name)+{+ // A folder: every window Remote has open, as drawn (headless KWin has no+ // screenshot effect without a GPU).+ const QString dir = qEnvironmentVariable("WILDOS_REMOTE_TEST_SHOT");+ if (dir.isEmpty()) {+ return;+ }+ int n = 0;+ for (QWindow *w : QGuiApplication::topLevelWindows()) {+ if (!w->isVisible() || w->width() < 200) {+ continue;+ }+ QImage image;+ if (auto *quick = qobject_cast<QQuickWindow *>(w)) {+ image = quick->grabWindow();+ } else {+ for (QWidget *widget : QApplication::topLevelWidgets()) {+ if (widget->windowHandle() == w) {+ image = widget->grab().toImage();+ }+ }+ }+ if (!image.isNull()) {+ image.save(QStringLiteral("%1/%2%3.png").arg(dir, name, n > 0 ? QStringLiteral("-%1").arg(n) : QString()));+ ++n;+ }+ }+}++void App::testType(const QString &text)+{+ for (const QChar c : text) {+ QWidget *target = QApplication::focusWidget();+ if (!target) {+ return;+ }+ const int key = c == QLatin1Char('\r') ? Qt::Key_Return : c.toUpper().unicode();+ const QString t = c == QLatin1Char('\r') ? QStringLiteral("\r") : QString(c);+ QKeyEvent press(QEvent::KeyPress, key, Qt::NoModifier, t);+ QApplication::sendEvent(target, &press);+ QKeyEvent release(QEvent::KeyRelease, key, Qt::NoModifier, t);+ QApplication::sendEvent(target, &release);+ }+}++void App::testKey(int key)+{+ if (QWidget *target = QApplication::focusWidget()) {+ QKeyEvent press(QEvent::KeyPress, key, Qt::NoModifier);+ QApplication::sendEvent(target, &press);+ }+}++void App::testRun(const QString &command)+{+ if (qEnvironmentVariableIsSet("WILDOS_REMOTE_TEST")) {+ QProcess::startDetached(QStringLiteral("/bin/sh"), {QStringLiteral("-c"), command});+ }+}++QObject *App::testSessionWindow() const+{+ SessionWindow *window = SessionWindow::instance(false);+ // It has no parent; QML must not take it for its own and collect it.+ if (window) {+ QJSEngine::setObjectOwnership(window, QJSEngine::CppOwnership);+ }+ return window;+}++void App::copyText(const QString &text)+{+ QGuiApplication::clipboard()->setText(text);+}++void App::openTerminal(const QString &hostId)+{+ const QVariantMap host = Hosts::instance()->host(hostId);+ if (host.isEmpty()) {+ return;+ }+ Hosts::instance()->touch(hostId);+ const QString identity = host.value(QStringLiteral("ssh")).toMap().value(QStringLiteral("identity")).toString();+ auto open = [this, hostId] {+ SessionWindow *window = SessionWindow::instance();+ connect(window, &SessionWindow::homeRequested, this, &App::fromSession, Qt::UniqueConnection);+ // The host as saved now, which may have changed since the check.+ window->open(Hosts::instance()->host(hostId));+ };+ if (identity.isEmpty()) {+ open();+ } else {+ Keychain::instance()->prepare(identity, open);+ }+}++void App::openLocal()+{+ SessionWindow *window = SessionWindow::instance();+ connect(window, &SessionWindow::homeRequested, this, &App::fromSession, Qt::UniqueConnection);+ window->open({});+}++void App::sendKey(const QString &keyPath, const QString &hostId)+{+ QVariantMap host = Hosts::instance()->host(hostId);+ if (host.isEmpty()) {+ return;+ }+ QStringList exec{QStringLiteral("ssh-copy-id"), QStringLiteral("-i"), keyPath + QStringLiteral(".pub"),+ QStringLiteral("-p"), QString::number(Hosts::instance()->port(host)),+ QStringLiteral("-o"), QStringLiteral("StrictHostKeyChecking=yes")};+ const QString user = host.value(QStringLiteral("user")).toString();+ exec.append((user.isEmpty() ? QString() : user + QLatin1Char('@')) + Hosts::instance()->hostName(host));+ host.insert(QStringLiteral("exec"), exec);+ SessionWindow *window = SessionWindow::instance();+ connect(window, &SessionWindow::homeRequested, this, &App::fromSession, Qt::UniqueConnection);+ window->open(host);+}++void App::fromSession(const QString &what)+{+ if (what.startsWith(QLatin1String("edit:"))) {+ Q_EMIT editRequested(what.mid(5));+ } else if (!what.isEmpty()) {+ Q_EMIT connectRequested(what);+ } else {+ Q_EMIT raiseRequested();+ }+}++void App::openArgument(const QString &arg)+{+ if (arg.isEmpty()) {+ Q_EMIT raiseRequested();+ return;+ }+ const QVariantMap address = Hosts::instance()->parseAddress(arg);+ if (address.isEmpty()) {+ Q_EMIT raiseRequested();+ return;+ }+ Q_EMIT quickConnectRequested(address);+}diff --git a/packages/wildos-remote/src/app.h b/packages/wildos-remote/src/app.hnew file mode 100644index 0000000..4385052--- /dev/null+++ b/packages/wildos-remote/src/app.h@@ -0,0 +1,68 @@+#pragma once++#include <QObject>+#include <QQmlEngine>+#include <QUrl>++// What the home window asks of the rest of Remote: opening terminals, and+// hearing when the terminal window wants the home window (to check a host+// before a new tab, or to edit one).+class App : public QObject+{+ Q_OBJECT+ QML_ELEMENT+ QML_SINGLETON++ Q_PROPERTY(QString version READ version CONSTANT)+ // For the automated screen test only: WILDOS_REMOTE_TEST names a QML+ // file loaded into the home window that drives it step by step,+ // WILDOS_REMOTE_TEST_SHOT a command that saves the screen (given a name).+ Q_PROPERTY(QUrl testScript READ testScript CONSTANT)+ // Started by Windows mode for its desktop: the home window stays hidden+ // unless a question needs asking.+ Q_PROPERTY(bool desktopOnly READ desktopOnly CONSTANT)++public:+ static App *instance();+ static App *create(QQmlEngine *, QJSEngine *);++ QString version() const;+ bool desktopOnly() const { return m_desktopOnly; }+ void setDesktopOnly(bool on) { m_desktopOnly = on; }++ // After the host's identity checked out: a tab in the terminal window,+ // with the key unlocked first when the keyring has its passphrase.+ Q_INVOKABLE void openTerminal(const QString &hostId);+ Q_INVOKABLE void openLocal();+ // ssh-copy-id in a terminal tab: the server asks for its password+ // there, as it would in any terminal.+ Q_INVOKABLE void sendKey(const QString &keyPath, const QString &hostId);+ Q_INVOKABLE void copyText(const QString &text);+ Q_INVOKABLE QString homePath() const;++ QUrl testScript() const;+ Q_INVOKABLE void testShot(const QString &name);+ // Types into the focused widget as a keyboard would, through its event+ // filters (the terminal's suggestions listen there).+ Q_INVOKABLE void testType(const QString &text);+ Q_INVOKABLE void testKey(int key);+ Q_INVOKABLE QObject *testSessionWindow() const;+ // Runs a shell command in the test rig (dropping a server mid-session).+ Q_INVOKABLE void testRun(const QString &command);++ // From the command line or a second launch: an ssh:// or rdp:// link.+ void openArgument(const QString &arg);++Q_SIGNALS:+ // The home window takes these over.+ void connectRequested(const QString &hostId);+ void editRequested(const QString &hostId);+ void quickConnectRequested(const QVariantMap &address);+ void raiseRequested();++private:+ explicit App(QObject *parent = nullptr);+ void fromSession(const QString &what);++ bool m_desktopOnly = false;+};diff --git a/packages/wildos-remote/src/askpass.cpp b/packages/wildos-remote/src/askpass.cppnew file mode 100644index 0000000..ec8caee--- /dev/null+++ b/packages/wildos-remote/src/askpass.cpp@@ -0,0 +1,190 @@+#include "askpass.h"+#include "paths.h"++#include <QCoreApplication>+#include <QFile>+#include <QJsonDocument>+#include <QJsonObject>+#include <QLocalServer>+#include <QLocalSocket>+#include <QTextStream>+#include <QUuid>++#include <cstdio>++namespace+{+const char *tokenVariable = "WILDOS_REMOTE_ASKPASS_TOKEN";+const char *socketVariable = "WILDOS_REMOTE_ASKPASS_SOCKET";+}++AskPass *AskPass::instance()+{+ static AskPass *askPass = new AskPass;+ return askPass;+}++AskPass *AskPass::create(QQmlEngine *, QJSEngine *)+{+ AskPass *a = instance();+ QJSEngine::setObjectOwnership(a, QJSEngine::CppOwnership);+ return a;+}++AskPass::AskPass(QObject *parent)+ : QObject(parent)+{+}++void AskPass::listen()+{+ if (m_server) {+ return;+ }+ m_path = Paths::runtime() + QStringLiteral("/askpass-%1").arg(QCoreApplication::applicationPid());+ QLocalServer::removeServer(m_path);+ m_server = new QLocalServer(this);+ // Only this user: the folder already says so, and the socket agrees.+ m_server->setSocketOptions(QLocalServer::UserAccessOption);+ if (!m_server->listen(m_path)) {+ qWarning("wildos-remote: could not listen for passphrase questions: %s", qPrintable(m_server->errorString()));+ return;+ }+ connect(m_server, &QLocalServer::newConnection, this, &AskPass::incoming);+}++QString AskPass::newToken(const Provider &provider, const QString &title)+{+ listen();+ const QString token = QUuid::createUuid().toString(QUuid::WithoutBraces);+ m_runs.insert(token, {provider, title, 0});+ return token;+}++void AskPass::release(const QString &token)+{+ m_runs.remove(token);+}++QProcessEnvironment AskPass::environment(const QString &token, QProcessEnvironment env)+{+ listen();+ env.insert(QStringLiteral("SSH_ASKPASS"), QCoreApplication::applicationFilePath());+ env.insert(QStringLiteral("SSH_ASKPASS_REQUIRE"), QStringLiteral("force"));+ // OpenSSH only uses askpass with a display to show it on; the helper+ // needs none, but a session without either would never get asked.+ if (!env.contains(QStringLiteral("DISPLAY")) && !env.contains(QStringLiteral("WAYLAND_DISPLAY"))) {+ env.insert(QStringLiteral("DISPLAY"), QStringLiteral(":0"));+ }+ env.insert(QString::fromLatin1(tokenVariable), token);+ env.insert(QString::fromLatin1(socketVariable), m_path);+ return env;+}++void AskPass::incoming()+{+ while (QLocalSocket *socket = m_server->nextPendingConnection()) {+ connect(socket, &QLocalSocket::disconnected, socket, &QObject::deleteLater);+ connect(socket, &QLocalSocket::readyRead, this, [this, socket] {+ if (!socket->canReadLine()) {+ return;+ }+ const QJsonObject q = QJsonDocument::fromJson(socket->readLine()).object();+ const QString token = q.value(QStringLiteral("token")).toString();+ const QString prompt = q.value(QStringLiteral("prompt")).toString().trimmed();+ const QString kind = q.value(QStringLiteral("kind")).toString();+ auto run = m_runs.find(token);+ if (run == m_runs.end()) {+ // Not a run Remote started: nothing to answer with.+ reply(socket, false, {});+ return;+ }+ ++run->count;+ if (run->provider && kind != QLatin1String("touch")) {+ if (const auto answer = run->provider(prompt, run->count)) {+ reply(socket, true, *answer);+ return;+ }+ }+ const QString id = QString::number(m_next++);+ m_waiting.insert(id, socket);+ // The tool gave up waiting, or (for a touch notice) is done.+ connect(socket, &QLocalSocket::disconnected, this, [this, id] {+ if (m_waiting.remove(id)) {+ Q_EMIT questionClosed(id);+ }+ });+ QString shown = kind;+ if (shown.isEmpty()) {+ shown = prompt.contains(QLatin1String("passphrase"), Qt::CaseInsensitive) ? QStringLiteral("passphrase")+ : prompt.contains(QLatin1String("PIN")) ? QStringLiteral("pin")+ : QStringLiteral("password");+ }+ Q_EMIT passphraseNeeded(id, run->title, prompt, shown);+ });+ }+}++void AskPass::reply(QLocalSocket *socket, bool ok, const QString &text)+{+ QJsonObject a;+ a.insert(QStringLiteral("ok"), ok);+ a.insert(QStringLiteral("text"), text);+ socket->write(QJsonDocument(a).toJson(QJsonDocument::Compact) + '\n');+ socket->flush();+}++void AskPass::answer(const QString &id, const QString &text)+{+ if (QLocalSocket *socket = m_waiting.take(id)) {+ reply(socket, true, text);+ }+}++void AskPass::cancel(const QString &id)+{+ if (QLocalSocket *socket = m_waiting.take(id)) {+ reply(socket, false, {});+ }+}++int AskPass::ask(const QString &prompt)+{+ const QString path = qEnvironmentVariable(socketVariable);+ const QString token = qEnvironmentVariable(tokenVariable);+ if (path.isEmpty() || token.isEmpty()) {+ QTextStream(stderr) << "wildos-remote --askpass only answers for Remote\n";+ return 1;+ }+ // SSH_ASKPASS_PROMPT is "confirm" for a yes or no question and "none"+ // for a notice that stays up until ssh is done (touch your security+ // key).+ const QString mode = qEnvironmentVariable("SSH_ASKPASS_PROMPT");+ QLocalSocket socket;+ socket.connectToServer(path);+ if (!socket.waitForConnected(3000)) {+ return 1;+ }+ QJsonObject q;+ q.insert(QStringLiteral("token"), token);+ q.insert(QStringLiteral("prompt"), prompt);+ q.insert(QStringLiteral("kind"), mode == QLatin1String("confirm") ? QStringLiteral("confirm") : mode == QLatin1String("none") ? QStringLiteral("touch") : QString());+ socket.write(QJsonDocument(q).toJson(QJsonDocument::Compact) + '\n');+ socket.flush();+ while (!socket.canReadLine()) {+ if (!socket.waitForReadyRead(-1)) {+ return 1;+ }+ }+ const QJsonObject a = QJsonDocument::fromJson(socket.readLine()).object();+ if (!a.value(QStringLiteral("ok")).toBool()) {+ return 1;+ }+ if (mode != QLatin1String("confirm") && mode != QLatin1String("none")) {+ const QByteArray text = a.value(QStringLiteral("text")).toString().toUtf8();+ std::fwrite(text.constData(), 1, size_t(text.size()), stdout);+ std::fputc('\n', stdout);+ std::fflush(stdout);+ }+ return 0;+}diff --git a/packages/wildos-remote/src/askpass.h b/packages/wildos-remote/src/askpass.hnew file mode 100644index 0000000..bacc8bb--- /dev/null+++ b/packages/wildos-remote/src/askpass.h@@ -0,0 +1,70 @@+#pragma once++#include <QHash>+#include <QObject>+#include <QPointer>+#include <QProcessEnvironment>+#include <QQmlEngine>++#include <functional>+#include <optional>++class QLocalServer;+class QLocalSocket;++// How ssh, ssh-keygen and ssh-add ask Remote for a passphrase without one+// ever appearing on a command line (where any process on the PC can read+// it). Remote runs them with SSH_ASKPASS pointing back at itself; that copy+// of Remote (`wildos-remote --askpass PROMPT`) passes the prompt over a+// socket only this user can reach and prints the answer for the tool.+//+// Each run gets a token. An answer comes from the provider registered for+// the token (a passphrase just typed, or one from the keyring), or the+// question goes to the window as passphraseNeeded.+class AskPass : public QObject+{+ Q_OBJECT+ QML_ELEMENT+ QML_SINGLETON++public:+ // Returns the answer, or an empty optional to ask the person.+ using Provider = std::function<std::optional<QString>(const QString &prompt, int count)>;++ static AskPass *instance();+ static AskPass *create(QQmlEngine *, QJSEngine *);++ // The environment for a tool run with this token.+ QProcessEnvironment environment(const QString &token, QProcessEnvironment base = QProcessEnvironment::systemEnvironment());+ QString newToken(const Provider &provider = {}, const QString &title = {});+ void release(const QString &token);++ // The helper side, in the copy of Remote ssh starts. Prints the answer+ // and returns 0, or returns 1 when the question was cancelled.+ static int ask(const QString &prompt);++ Q_INVOKABLE void answer(const QString &id, const QString &text);+ Q_INVOKABLE void cancel(const QString &id);++Q_SIGNALS:+ // `kind` is "passphrase", "password", "confirm" (yes or no) or "pin".+ void passphraseNeeded(const QString &id, const QString &title, const QString &prompt, const QString &kind);+ void questionClosed(const QString &id);++private:+ explicit AskPass(QObject *parent = nullptr);+ void listen();+ void incoming();+ void reply(QLocalSocket *socket, bool ok, const QString &text);++ struct Run {+ Provider provider;+ QString title;+ int count = 0;+ };+ QLocalServer *m_server = nullptr;+ QString m_path;+ QHash<QString, Run> m_runs;+ QHash<QString, QPointer<QLocalSocket>> m_waiting;+ int m_next = 1;+};diff --git a/packages/wildos-remote/src/desktopview.cpp b/packages/wildos-remote/src/desktopview.cppnew file mode 100644index 0000000..0b7fc24--- /dev/null+++ b/packages/wildos-remote/src/desktopview.cpp@@ -0,0 +1,241 @@+#include "desktopview.h"+#include "remotedesktop.h"++#include "client.h"+#include "desktop.h"+#include "input.h"++#include <QCursor>+#include <QPainter>+#include <QQuickWindow>+#include <QSGImageNode>+#include <QSGTexture>++#include <cstring>++DesktopView::DesktopView(QQuickItem *parent)+ : QQuickItem(parent)+{+ setFlag(ItemHasContents);+ setFlag(ItemIsFocusScope);+ setAcceptedMouseButtons(Qt::AllButtons);+ setAcceptHoverEvents(true);+ setActiveFocusOnTab(true);+}++void DesktopView::setDesktop(RemoteDesktop *desktop)+{+ if (desktop == m_desktop) {+ return;+ }+ if (m_desktop && m_desktop->session()) {+ m_desktop->session()->disconnect(this);+ }+ m_desktop = desktop;+ if (desktop && desktop->session()) {+ DesktopSession *s = desktop->session();+ connect(s, &DesktopSession::frameChanged, this, &DesktopView::damaged);+ connect(s, &DesktopSession::pointerImage, this, [this](const QImage &image, const QPoint &hotspot) {+ // Windows sends the pointer at its own pixels; the screen's+ // scale makes it the right size here.+ QPixmap pixmap = QPixmap::fromImage(image);+ const qreal dpr = window() ? window()->devicePixelRatio() : 1.0;+ pixmap.setDevicePixelRatio(dpr);+ setCursor(QCursor(pixmap, int(hotspot.x() / dpr), int(hotspot.y() / dpr)));+ });+ connect(s, &DesktopSession::pointerHidden, this, [this] { setCursor(Qt::BlankCursor); });+ connect(s, &DesktopSession::pointerDefault, this, [this] { setCursor(Qt::ArrowCursor); });+ // A picture already drawn (a second monitor's window opening later).+ const QImage frame = s->frame();+ if (!frame.isNull()) {+ m_image = frame;+ m_dirty = true;+ update();+ Q_EMIT pictureChanged();+ }+ }+ Q_EMIT desktopChanged();+}++void DesktopView::setSourceRect(const QRect &rect)+{+ if (rect != m_sourceRect) {+ m_sourceRect = rect;+ update();+ Q_EMIT sourceRectChanged();+ }+}++void DesktopView::setBlurred(bool blurred)+{+ if (blurred != m_blurred) {+ m_blurred = blurred;+ m_dirty = true;+ update();+ Q_EMIT blurredChanged();+ }+}++void DesktopView::damaged(const QRegion ®ion)+{+ if (!m_desktop || !m_desktop->session()) {+ return;+ }+ const bool had = !m_image.isNull();+ m_desktop->session()->client()->withPrimary([this, ®ion](const uchar *data, int stride, QSize size) {+ if (m_image.size() != size) {+ // A new desktop size: the whole picture again.+ m_image = QImage(data, size.width(), size.height(), stride, QImage::Format_RGB32).copy();+ return;+ }+ for (const QRect &r : region) {+ const QRect c = r.intersected(QRect(QPoint(0, 0), size));+ for (int y = c.top(); y <= c.bottom(); ++y) {+ std::memcpy(m_image.scanLine(y) + qsizetype(c.left()) * 4, data + qsizetype(y) * stride + qsizetype(c.left()) * 4,+ size_t(c.width()) * 4);+ }+ }+ });+ m_dirty = true;+ update();+ if (!had) {+ Q_EMIT pictureChanged();+ }+}++QRect DesktopView::source() const+{+ const QRect all(QPoint(0, 0), m_image.size());+ return m_sourceRect.isValid() ? m_sourceRect.intersected(all) : all;+}++QRectF DesktopView::pictureRect() const+{+ const QRect src = source();+ if (src.isEmpty() || width() <= 0 || height() <= 0) {+ return {};+ }+ const double s = std::min(width() / src.width(), height() / src.height());+ const QSizeF shown(src.width() * s, src.height() * s);+ return QRectF(QPointF((width() - shown.width()) / 2, (height() - shown.height()) / 2), shown);+}++QPoint DesktopView::toRemote(const QPointF &local) const+{+ const QRectF pic = pictureRect();+ const QRect src = source();+ if (pic.isEmpty()) {+ return {};+ }+ const double x = (local.x() - pic.x()) / pic.width() * src.width() + src.x();+ const double y = (local.y() - pic.y()) / pic.height() * src.height() + src.y();+ return QPoint(std::clamp(int(x), 0, std::max(0, m_image.width() - 1)), std::clamp(int(y), 0, std::max(0, m_image.height() - 1)));+}++QSGNode *DesktopView::updatePaintNode(QSGNode *old, UpdatePaintNodeData *)+{+ auto *node = static_cast<QSGImageNode *>(old);+ if (m_image.isNull() || !window()) {+ delete node;+ return nullptr;+ }+ if (!node) {+ node = window()->createImageNode();+ node->setOwnsTexture(true);+ node->setFiltering(QSGTexture::Linear);+ }+ if (m_dirty || !node->texture()) {+ QImage shown = m_image;+ if (m_blurred) {+ // Behind "Connection lost": soft, so the question reads.+ const QSize small = m_image.size() / 16;+ shown = m_image.scaled(small, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)+ .scaled(m_image.size() / 2, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);+ QPainter p(&shown);+ p.fillRect(shown.rect(), QColor(8, 12, 28, 110));+ }+ node->setTexture(window()->createTextureFromImage(shown));+ m_dirty = false;+ }+ const QRect src = source();+ const double ratio = m_blurred ? 0.5 : 1.0;+ node->setSourceRect(QRectF(src.x() * ratio, src.y() * ratio, src.width() * ratio, src.height() * ratio));+ node->setRect(pictureRect());+ return node;+}++void DesktopView::mousePressEvent(QMouseEvent *event)+{+ forceActiveFocus(Qt::MouseFocusReason);+ if (m_desktop && m_desktop->session() && !m_blurred) {+ rdpinput::button(m_desktop->session()->client(), event->button(), true, toRemote(event->position()));+ }+ event->accept();+}++void DesktopView::mouseReleaseEvent(QMouseEvent *event)+{+ if (m_desktop && m_desktop->session() && !m_blurred) {+ rdpinput::button(m_desktop->session()->client(), event->button(), false, toRemote(event->position()));+ }+}++void DesktopView::mouseMoveEvent(QMouseEvent *event)+{+ if (m_desktop && m_desktop->session() && !m_blurred) {+ rdpinput::move(m_desktop->session()->client(), toRemote(event->position()));+ }+ Q_EMIT pointerMoved(event->position().x(), event->position().y());+}++void DesktopView::hoverMoveEvent(QHoverEvent *event)+{+ if (m_desktop && m_desktop->session() && !m_blurred) {+ rdpinput::move(m_desktop->session()->client(), toRemote(event->position()));+ }+ Q_EMIT pointerMoved(event->position().x(), event->position().y());+}++void DesktopView::wheelEvent(QWheelEvent *event)+{+ if (m_desktop && m_desktop->session() && !m_blurred) {+ rdpinput::wheel(m_desktop->session()->client(), event->angleDelta(), toRemote(event->position()), m_wheelX, m_wheelY);+ }+}++void DesktopView::keyPressEvent(QKeyEvent *event)+{+ const auto mods = event->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::ShiftModifier | Qt::MetaModifier);+ if (event->key() == Qt::Key_Home && mods == (Qt::ControlModifier | Qt::AltModifier)) {+ // Ctrl and Alt are already down over there: they come up first.+ if (m_desktop && m_desktop->session()) {+ rdpinput::releaseAll(m_desktop->session()->client(), m_keysDown);+ }+ Q_EMIT escapeRequested();+ return;+ }+ if (m_desktop && m_desktop->session() && !m_blurred) {+ rdpinput::key(m_desktop->session()->client(), event, true, m_keysDown);+ }+}++void DesktopView::keyReleaseEvent(QKeyEvent *event)+{+ if (m_desktop && m_desktop->session()) {+ rdpinput::key(m_desktop->session()->client(), event, false, m_keysDown);+ }+}++void DesktopView::focusOutEvent(QFocusEvent *event)+{+ if (m_desktop && m_desktop->session()) {+ rdpinput::releaseAll(m_desktop->session()->client(), m_keysDown);+ }+ QQuickItem::focusOutEvent(event);+}++void DesktopView::geometryChange(const QRectF &newGeometry, const QRectF &oldGeometry)+{+ QQuickItem::geometryChange(newGeometry, oldGeometry);+ update();+}diff --git a/packages/wildos-remote/src/desktopview.h b/packages/wildos-remote/src/desktopview.hnew file mode 100644index 0000000..d15f0df--- /dev/null+++ b/packages/wildos-remote/src/desktopview.h@@ -0,0 +1,77 @@+#pragma once++#include <QImage>+#include <QPointer>+#include <QQuickItem>+#include <QRegion>++#include "remotedesktop.h"++// The remote desktop's picture, and the keyboard and pointer going to it+// (RemoteSession.dc, RemoteWindowed.dc). It shows `sourceRect` of the+// desktop (all of it unless set: one monitor's part with all monitors),+// filling the item at the same aspect, and maps input back to the desktop's+// pixels.+//+// Ctrl+Alt+Home never goes to the remote PC: it brings the toolbar, and+// gives the desktop's own shortcuts back while "Send all shortcuts there"+// is on.+class DesktopView : public QQuickItem+{+ Q_OBJECT+ QML_ELEMENT++ Q_PROPERTY(RemoteDesktop *desktop READ desktop WRITE setDesktop NOTIFY desktopChanged)+ Q_PROPERTY(QRect sourceRect READ sourceRect WRITE setSourceRect NOTIFY sourceRectChanged)+ Q_PROPERTY(bool blurred READ blurred WRITE setBlurred NOTIFY blurredChanged)+ Q_PROPERTY(bool hasPicture READ hasPicture NOTIFY pictureChanged)++public:+ explicit DesktopView(QQuickItem *parent = nullptr);++ RemoteDesktop *desktop() const { return m_desktop; }+ void setDesktop(RemoteDesktop *desktop);+ QRect sourceRect() const { return m_sourceRect; }+ void setSourceRect(const QRect &rect);+ bool blurred() const { return m_blurred; }+ void setBlurred(bool blurred);+ bool hasPicture() const { return !m_image.isNull(); }++ // The part of the item the picture covers.+ Q_INVOKABLE QRectF pictureRect() const;++Q_SIGNALS:+ void desktopChanged();+ void sourceRectChanged();+ void blurredChanged();+ void pictureChanged();+ // Ctrl+Alt+Home.+ void escapeRequested();+ void pointerMoved(qreal x, qreal y);++protected:+ QSGNode *updatePaintNode(QSGNode *old, UpdatePaintNodeData *) override;+ void mousePressEvent(QMouseEvent *event) override;+ void mouseReleaseEvent(QMouseEvent *event) override;+ void mouseMoveEvent(QMouseEvent *event) override;+ void hoverMoveEvent(QHoverEvent *event) override;+ void wheelEvent(QWheelEvent *event) override;+ void keyPressEvent(QKeyEvent *event) override;+ void keyReleaseEvent(QKeyEvent *event) override;+ void focusOutEvent(QFocusEvent *event) override;+ void geometryChange(const QRectF &newGeometry, const QRectF &oldGeometry) override;++private:+ void damaged(const QRegion ®ion);+ QRect source() const;+ QPoint toRemote(const QPointF &local) const;++ QPointer<RemoteDesktop> m_desktop;+ QRect m_sourceRect;+ QImage m_image;+ bool m_dirty = false;+ bool m_blurred = false;+ QList<quint32> m_keysDown;+ int m_wheelX = 0;+ int m_wheelY = 0;+};diff --git a/packages/wildos-remote/src/filebrowser.cpp b/packages/wildos-remote/src/filebrowser.cppnew file mode 100644index 0000000..aa56443--- /dev/null+++ b/packages/wildos-remote/src/filebrowser.cpp@@ -0,0 +1,600 @@+#include "filebrowser.h"+#include "paths.h"++#include <QDateTime>+#include <QDesktopServices>+#include <QDir>+#include <QDirIterator>+#include <QFileInfo>+#include <QFileSystemWatcher>+#include <QLocale>+#include <QUrl>++#include <algorithm>++namespace+{+QString sizeText(qint64 bytes)+{+ if (bytes < 1024 * 1024) {+ return QStringLiteral("%1 KB").arg(std::max<qint64>(1, (bytes + 1023) / 1024));+ }+ if (bytes < 1024LL * 1024 * 1024) {+ return QStringLiteral("%1 MB").arg(QLocale::system().toString(bytes / (1024.0 * 1024.0), 'f', bytes < 10LL * 1024 * 1024 ? 1 : 0));+ }+ return QStringLiteral("%1 GB").arg(QLocale::system().toString(bytes / (1024.0 * 1024.0 * 1024.0), 'f', 1));+}++QString whenText(qint64 secs)+{+ if (secs <= 0) {+ return {};+ }+ const QDateTime t = QDateTime::fromSecsSinceEpoch(secs);+ const QDate today = QDate::currentDate();+ if (t.date() == today) {+ return QStringLiteral("Today, ") + QLocale::system().toString(t.time(), QLocale::ShortFormat);+ }+ if (t.date() == today.addDays(-1)) {+ return QStringLiteral("Yesterday");+ }+ return QLocale::system().toString(t.date(), QLocale::ShortFormat);+}++QString secondsText(qint64 s)+{+ if (s < 60) {+ return s <= 1 ? QStringLiteral("about a second left") : QStringLiteral("about %1 seconds left").arg(s);+ }+ const qint64 m = (s + 30) / 60;+ return m == 1 ? QStringLiteral("about a minute left") : QStringLiteral("about %1 minutes left").arg(m);+}+}++FileBrowser::FileBrowser(const QString &hostName, QObject *parent)+ : QObject(parent)+ , m_hostName(hostName)+ , m_sftp(new Sftp(this))+{+ m_localPath = QDir::homePath();+ listLocal();+ connect(m_sftp, &Sftp::readyChanged, this, [this] {+ if (m_sftp->ready()) {+ m_remoteError.clear();+ if (m_remotePath.isEmpty()) {+ m_sftp->realPath(QStringLiteral("."), [this](const QString &path, const QString &) {+ m_remotePath = path.isEmpty() ? QStringLiteral("/") : path;+ listRemote();+ });+ } else {+ listRemote();+ }+ }+ Q_EMIT remoteChanged();+ });+ connect(m_sftp, &Sftp::failed, this, [this](const QString &error) {+ m_loading = false;+ // ssh's own words, but plainer for the one everyone meets.+ m_remoteError = error.contains(QLatin1String("Control socket")) || error.contains(QLatin1String("Permission denied"))+ ? QStringLiteral("Files use the terminal's connection. Sign in to %1 in the terminal first, then try again.").arg(m_hostName)+ : error;+ Q_EMIT remoteChanged();+ });+ m_progressTimer.setInterval(250);+ connect(&m_progressTimer, &QTimer::timeout, this, &FileBrowser::transfersChanged);+ m_saveTimer.setSingleShot(true);+ m_saveTimer.setInterval(600);+ connect(&m_saveTimer, &QTimer::timeout, this, [this] {+ const QStringList changed = std::exchange(m_changed, {});+ for (const QString &local : changed) {+ const QString remote = m_editing.value(local);+ if (remote.isEmpty() || !QFileInfo::exists(local)) {+ continue;+ }+ // Editors that save by replacing the file drop the watch.+ if (!m_watcher->files().contains(local)) {+ m_watcher->addPath(local);+ }+ queueUpload(local, remote, QFileInfo(local).fileName());+ }+ });+}++FileBrowser::~FileBrowser() = default;++void FileBrowser::connectTo(const QStringList &sshArgs)+{+ m_sshArgs = sshArgs;+ m_loading = true;+ m_remoteError.clear();+ Q_EMIT remoteChanged();+ m_sftp->start(sshArgs);+}++void FileBrowser::disconnectNow()+{+ m_sftp->stop();+}++void FileBrowser::retry()+{+ if (!m_sshArgs.isEmpty()) {+ connectTo(m_sshArgs);+ }+}++QString FileBrowser::localShown() const+{+ const QString home = QDir::homePath();+ if (m_localPath == home) {+ return QStringLiteral("~");+ }+ if (m_localPath.startsWith(home + QLatin1Char('/'))) {+ return QStringLiteral("~") + m_localPath.mid(home.size());+ }+ return m_localPath;+}++QVariantMap FileBrowser::entryMap(const QString &name, bool dir, qint64 size, qint64 mtime)+{+ return {{QStringLiteral("name"), name},+ {QStringLiteral("dir"), dir},+ {QStringLiteral("size"), size},+ {QStringLiteral("sizeText"), dir ? QString() : sizeText(size)},+ {QStringLiteral("modified"), whenText(mtime)},+ {QStringLiteral("hidden"), name.startsWith(QLatin1Char('.'))}};+}++void FileBrowser::listLocal()+{+ QVariantList list;+ const QDir dir(m_localPath);+ for (const QFileInfo &fi : dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden, QDir::DirsFirst | QDir::Name | QDir::IgnoreCase)) {+ list.append(entryMap(fi.fileName(), fi.isDir(), fi.size(), fi.lastModified().toSecsSinceEpoch()));+ }+ m_localEntries = list;+ Q_EMIT localChanged();+}++void FileBrowser::listRemote()+{+ if (!m_sftp->ready()) {+ return;+ }+ m_loading = true;+ Q_EMIT remoteChanged();+ const QString path = m_remotePath;+ m_sftp->list(path, [this, path](const QList<Sftp::Entry> &entries, const QString &error) {+ if (path != m_remotePath) {+ return;+ }+ m_loading = false;+ if (!error.isEmpty()) {+ Q_EMIT notice(error);+ }+ QList<Sftp::Entry> sorted = entries;+ std::sort(sorted.begin(), sorted.end(), [](const Sftp::Entry &a, const Sftp::Entry &b) {+ if (a.dir != b.dir) {+ return a.dir;+ }+ return a.name.compare(b.name, Qt::CaseInsensitive) < 0;+ });+ QVariantList list;+ for (const Sftp::Entry &e : std::as_const(sorted)) {+ list.append(entryMap(e.name, e.dir, e.size, e.mtime));+ }+ m_remoteEntries = list;+ Q_EMIT remoteChanged();+ });+}++QString FileBrowser::joinRemote(const QString &dir, const QString &name) const+{+ return dir.endsWith(QLatin1Char('/')) ? dir + name : dir + QLatin1Char('/') + name;+}++void FileBrowser::openLocal(const QString &path)+{+ QString target = path;+ if (!QDir::isAbsolutePath(target)) {+ target = QDir(m_localPath).absoluteFilePath(target);+ }+ target = QDir::cleanPath(target);+ if (!QFileInfo(target).isDir()) {+ return;+ }+ m_localHistory.append(m_localPath);+ m_localPath = target;+ listLocal();+}++void FileBrowser::openRemote(const QString &path)+{+ QString target = path.startsWith(QLatin1Char('/')) ? path : joinRemote(m_remotePath, path);+ target = QDir::cleanPath(target);+ m_remoteHistory.append(m_remotePath);+ m_remotePath = target;+ listRemote();+}++void FileBrowser::localBack()+{+ if (!m_localHistory.isEmpty()) {+ m_localPath = m_localHistory.takeLast();+ } else {+ m_localPath = QFileInfo(m_localPath).absolutePath();+ }+ listLocal();+}++void FileBrowser::remoteBack()+{+ if (!m_remoteHistory.isEmpty()) {+ m_remotePath = m_remoteHistory.takeLast();+ } else if (m_remotePath != QLatin1String("/")) {+ m_remotePath = QDir::cleanPath(m_remotePath + QStringLiteral("/.."));+ }+ listRemote();+}++void FileBrowser::refreshLocal()+{+ listLocal();+}++void FileBrowser::refreshRemote()+{+ listRemote();+}++void FileBrowser::newLocalFolder(const QString &name)+{+ if (!name.trimmed().isEmpty() && !QDir(m_localPath).mkdir(name.trimmed())) {+ Q_EMIT notice(QStringLiteral("The folder couldn't be made here."));+ }+ listLocal();+}++void FileBrowser::newRemoteFolder(const QString &name)+{+ if (name.trimmed().isEmpty()) {+ return;+ }+ m_sftp->mkdir(joinRemote(m_remotePath, name.trimmed()), [this](const QString &error) {+ if (!error.isEmpty()) {+ Q_EMIT notice(error);+ }+ listRemote();+ });+}++void FileBrowser::removeRemote(const QStringList &names)+{+ for (const QString &name : names) {+ bool dir = false;+ for (const QVariant &v : std::as_const(m_remoteEntries)) {+ if (v.toMap().value(QStringLiteral("name")).toString() == name) {+ dir = v.toMap().value(QStringLiteral("dir")).toBool();+ }+ }+ const QString path = joinRemote(m_remotePath, name);+ auto done = [this](const QString &error) {+ if (!error.isEmpty()) {+ Q_EMIT notice(error.contains(QLatin1String("Failure")) ? QStringLiteral("Only empty folders can be deleted from here.") : error);+ }+ listRemote();+ };+ if (dir) {+ m_sftp->rmdir(path, done);+ } else {+ m_sftp->remove(path, done);+ }+ }+}++void FileBrowser::renameRemote(const QString &from, const QString &to)+{+ if (to.trimmed().isEmpty() || to.contains(QLatin1Char('/'))) {+ return;+ }+ m_sftp->rename(joinRemote(m_remotePath, from), joinRemote(m_remotePath, to.trimmed()), [this](const QString &error) {+ if (!error.isEmpty()) {+ Q_EMIT notice(error);+ }+ listRemote();+ });+}++void FileBrowser::queueUpload(const QString &local, const QString &remote, const QString &shown)+{+ Job j;+ j.upload = true;+ j.name = shown;+ j.local = local;+ j.remote = remote;+ j.size = QFileInfo(local).size();+ m_jobs.append(j);+ startNext();+}++void FileBrowser::upload(const QStringList &names)+{+ m_cancelled = false;+ for (const QString &name : names) {+ const QString local = QDir(m_localPath).absoluteFilePath(name);+ const QFileInfo fi(local);+ const QString remote = joinRemote(m_remotePath, name);+ if (!fi.isDir()) {+ queueUpload(local, remote, name);+ continue;+ }+ // A folder: its folders are made first, in order, then its files.+ QStringList dirs{QString()};+ QList<QPair<QString, QString>> files;+ QDirIterator it(local, QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden, QDirIterator::Subdirectories);+ while (it.hasNext()) {+ it.next();+ const QString rel = QDir(local).relativeFilePath(it.filePath());+ if (it.fileInfo().isDir()) {+ dirs.append(rel);+ } else if (it.fileInfo().isFile()) {+ files.append({it.filePath(), rel});+ }+ }+ std::sort(dirs.begin(), dirs.end(), [](const QString &a, const QString &b) { return a.count(QLatin1Char('/')) < b.count(QLatin1Char('/')) || (a.count(QLatin1Char('/')) == b.count(QLatin1Char('/')) && a < b); });+ auto remaining = QSharedPointer<int>::create(int(dirs.size()));+ for (const QString &d : std::as_const(dirs)) {+ const QString target = d.isEmpty() ? remote : joinRemote(remote, d);+ // An existing folder is fine: its files are copied into it.+ m_sftp->mkdir(target, [this, remaining, files, remote, name](const QString &) {+ if (--*remaining == 0) {+ for (const auto &f : files) {+ queueUpload(f.first, joinRemote(remote, f.second), name + QLatin1Char('/') + f.second);+ }+ if (files.isEmpty()) {+ listRemote();+ }+ }+ });+ }+ }+}++void FileBrowser::queueDownload(const QString &remote, const QString &local, const QString &shown, bool isDir, qint64 size)+{+ if (!isDir) {+ Job j;+ j.upload = false;+ j.name = shown;+ j.local = local;+ j.remote = remote;+ j.size = size;+ m_jobs.append(j);+ startNext();+ return;+ }+ QDir().mkpath(local);+ ++m_pendingLists;+ m_sftp->list(remote, [this, remote, local, shown](const QList<Sftp::Entry> &entries, const QString &error) {+ --m_pendingLists;+ if (!error.isEmpty()) {+ Q_EMIT notice(error);+ }+ for (const Sftp::Entry &e : entries) {+ if (e.link) {+ continue;+ }+ queueDownload(joinRemote(remote, e.name), local + QLatin1Char('/') + e.name, shown + QLatin1Char('/') + e.name, e.dir, e.size);+ }+ if (m_pendingLists == 0 && m_active < 0) {+ listLocal();+ }+ });+}++void FileBrowser::download(const QStringList &names)+{+ m_cancelled = false;+ for (const QString &name : names) {+ for (const QVariant &v : std::as_const(m_remoteEntries)) {+ const QVariantMap e = v.toMap();+ if (e.value(QStringLiteral("name")).toString() == name) {+ queueDownload(joinRemote(m_remotePath, name), QDir(m_localPath).absoluteFilePath(name), name, e.value(QStringLiteral("dir")).toBool(),+ e.value(QStringLiteral("size")).toLongLong());+ }+ }+ }+}++void FileBrowser::startNext()+{+ if (m_active >= 0 || m_cancelled) {+ return;+ }+ for (int i = 0; i < m_jobs.size(); ++i) {+ if (m_jobs[i].state != QLatin1String("waiting")) {+ continue;+ }+ if (!m_batchClock.isValid()) {+ m_batchClock.start();+ m_batchStartBytes = 0;+ m_progressTimer.start();+ }+ m_active = i;+ m_jobs[i].state = QStringLiteral("active");+ Q_EMIT transfersChanged();+ auto progress = [this, i](qint64 done) {+ if (i < m_jobs.size()) {+ m_jobs[i].done = done;+ }+ };+ auto done = [this, i](const QString &error) {+ if (i < m_jobs.size()) {+ m_jobs[i].state = error.isEmpty() ? QStringLiteral("done") : QStringLiteral("failed");+ m_jobs[i].error = error;+ if (error.isEmpty()) {+ m_jobs[i].done = m_jobs[i].size;+ }+ }+ m_active = -1;+ Q_EMIT transfersChanged();+ startNext();+ if (m_active < 0) {+ finishBatch();+ }+ };+ if (m_jobs[i].upload) {+ m_sftp->upload(m_jobs[i].local, m_jobs[i].remote, progress, done);+ } else {+ m_sftp->download(m_jobs[i].remote, m_jobs[i].local, progress, done);+ }+ return;+ }+}++void FileBrowser::finishBatch()+{+ m_progressTimer.stop();+ m_batchClock.invalidate();+ bool anyUpload = false;+ bool anyDownload = false;+ for (const Job &j : std::as_const(m_jobs)) {+ anyUpload |= j.upload;+ anyDownload |= !j.upload;+ }+ if (anyUpload) {+ listRemote();+ }+ if (anyDownload) {+ listLocal();+ }+ // Copies made for editing say so when they are back on the server.+ for (const Job &j : std::as_const(m_jobs)) {+ if (j.upload && m_editing.contains(j.local) && j.state == QLatin1String("done")) {+ Q_EMIT notice(QStringLiteral("Saved %1 to %2").arg(j.name, m_hostName));+ }+ }+ Q_EMIT transfersChanged();+}++QVariantList FileBrowser::transfers() const+{+ QVariantList out;+ for (const Job &j : m_jobs) {+ out.append(QVariantMap{+ {QStringLiteral("name"), j.name},+ {QStringLiteral("upload"), j.upload},+ {QStringLiteral("state"), j.state},+ {QStringLiteral("progress"), j.size > 0 ? double(j.done) / double(j.size) : (j.state == QLatin1String("done") ? 1.0 : 0.0)},+ {QStringLiteral("detail"), j.state == QLatin1String("done") ? QStringLiteral("Done")+ : j.state == QLatin1String("failed") ? j.error+ : j.state == QLatin1String("waiting") ? QStringLiteral("Waiting")+ : QStringLiteral("%1 of %2").arg(sizeText(j.done).section(QLatin1Char(' '), 0, 0), sizeText(j.size))},+ });+ }+ return out;+}++bool FileBrowser::transferring() const+{+ return m_active >= 0;+}++QString FileBrowser::transferTitle() const+{+ if (m_jobs.isEmpty()) {+ return {};+ }+ int up = 0;+ int down = 0;+ for (const Job &j : m_jobs) {+ (j.upload ? up : down)++;+ }+ const bool upload = up >= down;+ const int n = upload ? up : down;+ const QString files = n == 1 ? QStringLiteral("1 file") : QStringLiteral("%1 files").arg(n);+ if (m_active < 0) {+ return upload ? QStringLiteral("Uploaded %1 to %2").arg(files, m_hostName) : QStringLiteral("Downloaded %1 from %2").arg(files, m_hostName);+ }+ return upload ? QStringLiteral("Uploading %1 to %2").arg(files, m_hostName) : QStringLiteral("Downloading %1 from %2").arg(files, m_hostName);+}++QString FileBrowser::transferSummary() const+{+ int done = 0;+ int failed = 0;+ qint64 total = 0;+ qint64 moved = 0;+ for (const Job &j : m_jobs) {+ done += j.state == QLatin1String("done");+ failed += j.state == QLatin1String("failed");+ total += j.size;+ moved += j.done;+ }+ QString text = QStringLiteral("%1 of %2 done").arg(done).arg(m_jobs.size());+ if (failed > 0) {+ text += failed == 1 ? QStringLiteral(", 1 didn't copy") : QStringLiteral(", %1 didn't copy").arg(failed);+ }+ // Only once there's enough to go on.+ if (m_active >= 0 && m_batchClock.isValid() && m_batchClock.elapsed() > 1000 && moved > 0) {+ const double rate = double(moved) / (m_batchClock.elapsed() / 1000.0);+ const qint64 left = qint64((total - moved) / std::max(1.0, rate));+ text += QStringLiteral(", ") + secondsText(left);+ }+ return text;+}++void FileBrowser::clearFinished()+{+ if (m_active >= 0) {+ return;+ }+ m_jobs.clear();+ Q_EMIT transfersChanged();+}++void FileBrowser::cancelTransfers()+{+ m_cancelled = true;+ for (Job &j : m_jobs) {+ if (j.state == QLatin1String("waiting")) {+ j.state = QStringLiteral("failed");+ j.error = QStringLiteral("Cancelled");+ }+ }+ Q_EMIT transfersChanged();+}++void FileBrowser::openLocalFile(const QString &name)+{+ QDesktopServices::openUrl(QUrl::fromLocalFile(QDir(m_localPath).absoluteFilePath(name)));+}++void FileBrowser::editRemote(const QString &name)+{+ const QString remote = joinRemote(m_remotePath, name);+ // A folder of its own per host and path, so two files called index.html+ // never meet.+ const QString dir = Paths::cache() + QStringLiteral("/editing/") + m_hostName + QString(m_remotePath).replace(QLatin1Char('/'), QLatin1Char('_'));+ QDir().mkpath(dir);+ QFile::setPermissions(Paths::cache() + QStringLiteral("/editing"), QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ExeOwner);+ const QString local = dir + QLatin1Char('/') + name;+ m_sftp->download(remote, local, {}, [this, local, remote](const QString &error) {+ if (!error.isEmpty()) {+ Q_EMIT notice(error);+ return;+ }+ if (!m_watcher) {+ m_watcher = new QFileSystemWatcher(this);+ connect(m_watcher, &QFileSystemWatcher::fileChanged, this, [this](const QString &path) {+ if (!m_changed.contains(path)) {+ m_changed.append(path);+ }+ m_saveTimer.start();+ });+ }+ m_editing.insert(local, remote);+ m_watcher->addPath(local);+ QDesktopServices::openUrl(QUrl::fromLocalFile(local));+ });+}diff --git a/packages/wildos-remote/src/filebrowser.h b/packages/wildos-remote/src/filebrowser.hnew file mode 100644index 0000000..c467047--- /dev/null+++ b/packages/wildos-remote/src/filebrowser.h@@ -0,0 +1,131 @@+#pragma once++#include "sftp.h"++#include <QElapsedTimer>+#include <QHash>+#include <QObject>+#include <QQmlEngine>+#include <QStringList>+#include <QTimer>+#include <QVariantList>++class QFileSystemWatcher;++// Copying files between this PC and a server (RemoteFiles.dc): the two+// folders side by side, and the copies in progress below them. Folders are+// copied with everything in them.+class FileBrowser : public QObject+{+ Q_OBJECT+ QML_ANONYMOUS++ Q_PROPERTY(QString localPath READ localPath NOTIFY localChanged)+ Q_PROPERTY(QString localShown READ localShown NOTIFY localChanged)+ Q_PROPERTY(QVariantList localEntries READ localEntries NOTIFY localChanged)+ Q_PROPERTY(QString remotePath READ remotePath NOTIFY remoteChanged)+ Q_PROPERTY(QVariantList remoteEntries READ remoteEntries NOTIFY remoteChanged)+ Q_PROPERTY(bool remoteReady READ remoteReady NOTIFY remoteChanged)+ Q_PROPERTY(QString remoteError READ remoteError NOTIFY remoteChanged)+ Q_PROPERTY(bool loading READ loading NOTIFY remoteChanged)+ Q_PROPERTY(QVariantList transfers READ transfers NOTIFY transfersChanged)+ Q_PROPERTY(QString transferTitle READ transferTitle NOTIFY transfersChanged)+ Q_PROPERTY(QString transferSummary READ transferSummary NOTIFY transfersChanged)+ Q_PROPERTY(bool transferring READ transferring NOTIFY transfersChanged)++public:+ FileBrowser(const QString &hostName, QObject *parent = nullptr);+ ~FileBrowser() override;++ // Connects through the terminal's shared connection.+ void connectTo(const QStringList &sshArgs);+ void disconnectNow();++ QString localPath() const { return m_localPath; }+ QString localShown() const;+ QVariantList localEntries() const { return m_localEntries; }+ QString remotePath() const { return m_remotePath; }+ QVariantList remoteEntries() const { return m_remoteEntries; }+ bool remoteReady() const { return m_sftp->ready(); }+ QString remoteError() const { return m_remoteError; }+ bool loading() const { return m_loading; }+ QVariantList transfers() const;+ QString transferTitle() const;+ QString transferSummary() const;+ bool transferring() const;++ Q_INVOKABLE void openLocal(const QString &path);+ Q_INVOKABLE void openRemote(const QString &path);+ Q_INVOKABLE void localBack();+ Q_INVOKABLE void remoteBack();+ Q_INVOKABLE void refreshLocal();+ Q_INVOKABLE void refreshRemote();+ Q_INVOKABLE void retry();+ Q_INVOKABLE void upload(const QStringList &names);+ Q_INVOKABLE void download(const QStringList &names);+ Q_INVOKABLE void newLocalFolder(const QString &name);+ Q_INVOKABLE void newRemoteFolder(const QString &name);+ Q_INVOKABLE void removeRemote(const QStringList &names);+ Q_INVOKABLE void renameRemote(const QString &from, const QString &to);+ // Opens a server file in its app here; saving it uploads it back.+ Q_INVOKABLE void editRemote(const QString &name);+ Q_INVOKABLE void openLocalFile(const QString &name);+ Q_INVOKABLE void clearFinished();+ Q_INVOKABLE void cancelTransfers();++Q_SIGNALS:+ void localChanged();+ void remoteChanged();+ void transfersChanged();+ void notice(const QString &text);++private:+ struct Job {+ bool upload = true;+ QString name;+ QString local;+ QString remote;+ qint64 size = 0;+ qint64 done = 0;+ // "waiting", "active", "done", "failed"+ QString state = QStringLiteral("waiting");+ QString error;+ // Shown in the list: a folder's files show as one row per file.+ bool silent = false;+ };++ static QVariantMap entryMap(const QString &name, bool dir, qint64 size, qint64 mtime);+ void listLocal();+ void listRemote();+ void queueUpload(const QString &local, const QString &remote, const QString &shown);+ void queueDownload(const QString &remote, const QString &local, const QString &shown, bool isDir, qint64 size);+ void startNext();+ void finishBatch();+ QString joinRemote(const QString &dir, const QString &name) const;++ QString m_hostName;+ Sftp *m_sftp;+ QStringList m_sshArgs;+ QString m_localPath;+ QStringList m_localHistory;+ QVariantList m_localEntries;+ QString m_remotePath;+ QStringList m_remoteHistory;+ QVariantList m_remoteEntries;+ QString m_remoteError;+ bool m_loading = false;++ QList<Job> m_jobs;+ int m_active = -1;+ int m_pendingLists = 0;+ QElapsedTimer m_batchClock;+ qint64 m_batchStartBytes = 0;+ QTimer m_progressTimer;+ bool m_cancelled = false;++ QFileSystemWatcher *m_watcher = nullptr;+ // A local copy being edited -> the file on the server it saves to.+ QHash<QString, QString> m_editing;+ QTimer m_saveTimer;+ QStringList m_changed;+};diff --git a/packages/wildos-remote/src/hostkeys.cpp b/packages/wildos-remote/src/hostkeys.cppnew file mode 100644index 0000000..28d93fa--- /dev/null+++ b/packages/wildos-remote/src/hostkeys.cpp@@ -0,0 +1,454 @@+#include "hostkeys.h"+#include "hosts.h"+#include "paths.h"++#include <QLocale>+#include <QCryptographicHash>+#include <QDate>+#include <QFile>+#include <QJsonDocument>+#include <QJsonObject>+#include <QMessageAuthenticationCode>+#include <QProcess>+#include <QRandomGenerator>+#include <QRegularExpression>+#include <QSaveFile>++namespace+{+struct Entry {+ QString marker;+ QString patterns;+ QString type;+ QString key;+ int index = -1;+};++QList<Entry> parse(const QString &path)+{+ QList<Entry> out;+ QFile f(path);+ if (!f.open(QIODevice::ReadOnly)) {+ return out;+ }+ int index = 0;+ while (!f.atEnd()) {+ const QString line = QString::fromUtf8(f.readLine()).trimmed();+ const int at = index++;+ if (line.isEmpty() || line.startsWith(QLatin1Char('#'))) {+ continue;+ }+ QStringList parts = line.split(QRegularExpression(QStringLiteral("\\s+")), Qt::SkipEmptyParts);+ Entry e;+ e.index = at;+ if (!parts.isEmpty() && parts.first().startsWith(QLatin1Char('@'))) {+ e.marker = parts.takeFirst();+ }+ if (parts.size() < 3) {+ continue;+ }+ e.patterns = parts[0];+ e.type = parts[1];+ e.key = parts[2];+ out.append(e);+ }+ return out;+}++bool hashedMatch(const QString &pattern, const QString &name)+{+ // |1|salt|hash, the hash an HMAC-SHA1 of the name keyed by the salt.+ const QStringList p = pattern.split(QLatin1Char('|'));+ if (p.size() != 4 || p[1] != QLatin1String("1")) {+ return false;+ }+ const QByteArray salt = QByteArray::fromBase64(p[2].toLatin1());+ const QByteArray hash = QByteArray::fromBase64(p[3].toLatin1());+ return QMessageAuthenticationCode::hash(name.toUtf8(), salt, QCryptographicHash::Sha1) == hash;+}++bool matches(const QString &patterns, const QString &name)+{+ if (patterns.startsWith(QLatin1String("|1|"))) {+ return hashedMatch(patterns, name);+ }+ bool hit = false;+ for (const QString &raw : patterns.split(QLatin1Char(','), Qt::SkipEmptyParts)) {+ const bool negated = raw.startsWith(QLatin1Char('!'));+ const QString p = negated ? raw.mid(1) : raw;+ // ssh's patterns know only * and ?; the brackets of [host]:port+ // are literal.+ QString rx = QRegularExpression::escape(p);+ rx.replace(QLatin1String("\\*"), QLatin1String(".*")).replace(QLatin1String("\\?"), QLatin1String("."));+ const QRegularExpression re(QRegularExpression::anchoredPattern(rx), QRegularExpression::CaseInsensitiveOption);+ if (re.match(name).hasMatch()) {+ if (negated) {+ return false;+ }+ hit = true;+ }+ }+ return hit;+}++QString shortType(const QString &type)+{+ if (type == QLatin1String("ssh-ed25519")) {+ return QStringLiteral("ED25519");+ }+ if (type == QLatin1String("[email protected]")) {+ return QStringLiteral("ED25519-SK");+ }+ if (type.startsWith(QLatin1String("sk-ecdsa"))) {+ return QStringLiteral("ECDSA-SK");+ }+ if (type.startsWith(QLatin1String("ecdsa"))) {+ return QStringLiteral("ECDSA");+ }+ if (type == QLatin1String("ssh-rsa")) {+ return QStringLiteral("RSA");+ }+ return type;+}++int preference(const QString &type)+{+ // OpenSSH's own order of preference for host keys.+ if (type == QLatin1String("ssh-ed25519")) {+ return 0;+ }+ if (type.startsWith(QLatin1String("ecdsa"))) {+ return 1;+ }+ return 2;+}++QString datesFile()+{+ return Paths::data() + QStringLiteral("/host-keys-seen.json");+}+}++HostKeys *HostKeys::instance()+{+ static HostKeys *keys = new HostKeys;+ return keys;+}++HostKeys *HostKeys::create(QQmlEngine *, QJSEngine *)+{+ HostKeys *k = instance();+ QJSEngine::setObjectOwnership(k, QJSEngine::CppOwnership);+ return k;+}++HostKeys::HostKeys(QObject *parent)+ : QObject(parent)+{+}++QString HostKeys::knownHostsFile()+{+ return Paths::ssh() + QStringLiteral("/known_hosts");+}++QString HostKeys::entryName(const QString &host, int port)+{+ return port == 22 || port <= 0 ? host : QStringLiteral("[%1]:%2").arg(host).arg(port);+}++QString HostKeys::fingerprint(const QString &keyLine)+{+ const QStringList parts = keyLine.split(QRegularExpression(QStringLiteral("\\s+")), Qt::SkipEmptyParts);+ for (const QString &p : parts) {+ // The key is the first field that decodes to a blob starting with+ // its own type name.+ const QByteArray blob = QByteArray::fromBase64(p.toLatin1());+ if (blob.size() > 20 && blob.at(0) == 0 && blob.at(1) == 0 && blob.at(2) == 0) {+ const QByteArray hash = QCryptographicHash::hash(blob, QCryptographicHash::Sha256).toBase64(QByteArray::OmitTrailingEquals);+ return QStringLiteral("SHA256:") + QString::fromLatin1(hash);+ }+ }+ return {};+}++void HostKeys::check(const QString &host, int port, const QJSValue &callback)+{+ auto *scan = new QProcess(this);+ scan->setProgram(QStringLiteral("ssh-keyscan"));+ scan->setArguments({QStringLiteral("-T"), QStringLiteral("8"), QStringLiteral("-p"), QString::number(port),+ QStringLiteral("-t"), QStringLiteral("ed25519,ecdsa,rsa"), QStringLiteral("--"), host});+ connect(scan, &QProcess::finished, this, [this, scan, host, port, callback](int, QProcess::ExitStatus) mutable {+ scan->deleteLater();+ const QString name = entryName(host, port);+ QVariantMap result;+ result.insert(QStringLiteral("name"), name);++ // What the server offers now, best first.+ QList<QPair<QString, QString>> offered;+ for (const QByteArray &raw : scan->readAllStandardOutput().split('\n')) {+ const QStringList f = QString::fromUtf8(raw).trimmed().split(QLatin1Char(' '), Qt::SkipEmptyParts);+ if (f.size() >= 3 && !f[0].startsWith(QLatin1Char('#'))) {+ offered.append({f[1], f[2]});+ }+ }+ std::sort(offered.begin(), offered.end(), [](const auto &a, const auto &b) {+ return preference(a.first) < preference(b.first);+ });+ if (offered.isEmpty()) {+ result.insert(QStringLiteral("state"), QStringLiteral("error"));+ const QString err = QString::fromUtf8(scan->readAllStandardError()).trimmed();+ result.insert(QStringLiteral("error"), err.contains(QLatin1String("Name or service not known")) || err.contains(QLatin1String("not known"))+ ? QStringLiteral("Remote couldn't find %1 on the network. Check the address.").arg(host)+ : QStringLiteral("%1 didn't answer on port %2. Check it's switched on and that SSH is running there.").arg(host).arg(port));+ if (callback.isCallable()) {+ callback.call({qjsEngine(this)->toScriptValue(result)});+ }+ return;+ }++ QList<Entry> known = parse(knownHostsFile());+ for (Entry &e : parse(QStringLiteral("/etc/ssh/ssh_known_hosts"))) {+ e.index = -1;+ known.append(e);+ }+ QList<Entry> mine;+ bool revoked = false;+ for (const Entry &e : std::as_const(known)) {+ if (!matches(e.patterns, name)) {+ continue;+ }+ if (e.marker == QLatin1String("@revoked")) {+ for (const auto &o : std::as_const(offered)) {+ revoked |= o.second == e.key;+ }+ continue;+ }+ if (e.marker.isEmpty()) {+ mine.append(e);+ }+ }++ const auto &best = offered.first();+ result.insert(QStringLiteral("keyType"), shortType(best.first));+ result.insert(QStringLiteral("keyLine"), best.first + QLatin1Char(' ') + best.second);+ result.insert(QStringLiteral("fingerprint"), fingerprint(best.second));+ QString state = QStringLiteral("new");+ if (revoked) {+ state = QStringLiteral("revoked");+ } else {+ for (const Entry &e : std::as_const(mine)) {+ for (const auto &o : std::as_const(offered)) {+ if (o.first == e.type && o.second == e.key) {+ state = QStringLiteral("known");+ }+ }+ }+ if (state != QLatin1String("known") && !mine.isEmpty()) {+ state = QStringLiteral("changed");+ // The new key of the same type as the old one, if there is+ // one: that is the comparison the person can check.+ for (const auto &o : std::as_const(offered)) {+ if (o.first == mine.first().type) {+ result.insert(QStringLiteral("keyType"), shortType(o.first));+ result.insert(QStringLiteral("keyLine"), o.first + QLatin1Char(' ') + o.second);+ result.insert(QStringLiteral("fingerprint"), fingerprint(o.second));+ break;+ }+ }+ }+ }+ result.insert(QStringLiteral("state"), state);+ QVariantList previous;+ for (const Entry &e : std::as_const(mine)) {+ const QString fp = fingerprint(e.key);+ previous.append(QVariantMap{{QStringLiteral("keyType"), shortType(e.type)},+ {QStringLiteral("fingerprint"), fp},+ {QStringLiteral("seen"), seen(fp)}});+ }+ result.insert(QStringLiteral("previous"), previous);+ if (callback.isCallable()) {+ callback.call({qjsEngine(this)->toScriptValue(result)});+ }+ });+ scan->start();+}++bool HostKeys::append(const QString &line)+{+ QFile f(knownHostsFile());+ if (!f.open(QIODevice::Append | QIODevice::Text)) {+ return false;+ }+ // A file that does not end in a newline would join our entry to its+ // last one.+ if (f.size() > 0) {+ QFile check(knownHostsFile());+ if (check.open(QIODevice::ReadOnly) && check.seek(check.size() - 1) && check.read(1) != "\n") {+ f.write("\n");+ }+ }+ f.write(line.toUtf8() + '\n');+ f.close();+ f.setPermissions(QFileDevice::ReadOwner | QFileDevice::WriteOwner);+ m_loaded = false;+ Q_EMIT knownChanged();+ return true;+}++bool HostKeys::trust(const QString &host, int port, const QString &keyLine)+{+ const QStringList k = keyLine.split(QLatin1Char(' '), Qt::SkipEmptyParts);+ if (k.size() < 2) {+ return false;+ }+ // Hashed as Debian's ssh hashes the names it adds (HashKnownHosts), so+ // the file doesn't list where this PC connects to.+ QByteArray salt(20, Qt::Uninitialized);+ QRandomGenerator::system()->fillRange(reinterpret_cast<quint32 *>(salt.data()), salt.size() / 4);+ const QByteArray hash = QMessageAuthenticationCode::hash(entryName(host, port).toUtf8(), salt, QCryptographicHash::Sha1);+ const QString hashed = QStringLiteral("|1|%1|%2").arg(QString::fromLatin1(salt.toBase64()), QString::fromLatin1(hash.toBase64()));+ if (!append(hashed + QLatin1Char(' ') + k[0] + QLatin1Char(' ') + k[1])) {+ return false;+ }+ remember(fingerprint(k[1]));+ return true;+}++bool HostKeys::replace(const QString &host, int port, const QString &keyLine)+{+ const QString name = entryName(host, port);+ QFile f(knownHostsFile());+ if (f.open(QIODevice::ReadOnly)) {+ QStringList kept;+ const QList<QByteArray> lines = f.readAll().split('\n');+ f.close();+ for (const QByteArray &raw : lines) {+ const QString line = QString::fromUtf8(raw);+ QStringList parts = line.trimmed().split(QRegularExpression(QStringLiteral("\\s+")), Qt::SkipEmptyParts);+ if (!parts.isEmpty() && parts.first().startsWith(QLatin1Char('@'))) {+ // Revocations and certificate authorities are kept.+ kept.append(line);+ continue;+ }+ if (!parts.isEmpty() && !line.trimmed().startsWith(QLatin1Char('#')) && matches(parts.first(), name)) {+ continue;+ }+ kept.append(line);+ }+ while (!kept.isEmpty() && kept.last().trimmed().isEmpty()) {+ kept.removeLast();+ }+ QSaveFile out(knownHostsFile());+ if (!out.open(QIODevice::WriteOnly)) {+ return false;+ }+ out.write(kept.join(QLatin1Char('\n')).toUtf8());+ if (!kept.isEmpty()) {+ out.write("\n");+ }+ if (!out.commit()) {+ return false;+ }+ }+ return trust(host, port, keyLine);+}++void HostKeys::remember(const QString &fp)+{+ QFile f(datesFile());+ QJsonObject dates;+ if (f.open(QIODevice::ReadOnly)) {+ dates = QJsonDocument::fromJson(f.readAll()).object();+ f.close();+ }+ dates.insert(fp, QDate::currentDate().toString(Qt::ISODate));+ QDir().mkpath(Paths::data());+ QSaveFile out(datesFile());+ if (out.open(QIODevice::WriteOnly)) {+ out.write(QJsonDocument(dates).toJson());+ out.commit();+ }+}++QString HostKeys::seen(const QString &fp) const+{+ QFile f(datesFile());+ if (!f.open(QIODevice::ReadOnly)) {+ return {};+ }+ const QString iso = QJsonDocument::fromJson(f.readAll()).object().value(fp).toString();+ const QDate d = QDate::fromString(iso, Qt::ISODate);+ return d.isValid() ? QLocale::system().toString(d, QLocale::ShortFormat) : QString();+}++void HostKeys::reload()+{+ m_loaded = false;+ Q_EMIT knownChanged();+}++QVariantList HostKeys::known()+{+ if (m_loaded) {+ return m_known;+ }+ m_loaded = true;+ m_known.clear();+ // The names a hashed entry could be: every saved terminal host.+ QStringList names;+ for (const QVariant &v : Hosts::instance()->hosts()) {+ const QVariantMap h = v.toMap();+ if (h.value(QStringLiteral("kind")).toString() == QLatin1String("terminal")) {+ names.append(entryName(Hosts::instance()->hostName(h), Hosts::instance()->port(h)));+ }+ }+ for (const Entry &e : parse(knownHostsFile())) {+ QVariantMap m;+ m.insert(QStringLiteral("index"), e.index);+ const bool hashed = e.patterns.startsWith(QLatin1String("|1|"));+ QString name = e.patterns;+ if (hashed) {+ name.clear();+ for (const QString &n : std::as_const(names)) {+ if (hashedMatch(e.patterns, n)) {+ name = n;+ break;+ }+ }+ }+ m.insert(QStringLiteral("name"), name);+ m.insert(QStringLiteral("hashed"), hashed);+ m.insert(QStringLiteral("marker"), e.marker);+ m.insert(QStringLiteral("keyType"), shortType(e.type));+ const QString fp = fingerprint(e.key);+ m.insert(QStringLiteral("fingerprint"), fp);+ m.insert(QStringLiteral("seen"), seen(fp));+ m_known.append(m);+ }+ return m_known;+}++bool HostKeys::forget(int index)+{+ QFile f(knownHostsFile());+ if (!f.open(QIODevice::ReadOnly)) {+ return false;+ }+ QList<QByteArray> lines = f.readAll().split('\n');+ f.close();+ if (index < 0 || index >= lines.size()) {+ return false;+ }+ lines.removeAt(index);+ QSaveFile out(knownHostsFile());+ if (!out.open(QIODevice::WriteOnly)) {+ return false;+ }+ out.write(lines.join('\n'));+ if (!out.commit()) {+ return false;+ }+ reload();+ return true;+}diff --git a/packages/wildos-remote/src/hostkeys.h b/packages/wildos-remote/src/hostkeys.hnew file mode 100644index 0000000..0c86a00--- /dev/null+++ b/packages/wildos-remote/src/hostkeys.h@@ -0,0 +1,66 @@+#pragma once++#include <QJSValue>+#include <QObject>+#include <QQmlEngine>+#include <QVariantList>+#include <QVariantMap>++// Is this the same server as last time? Host identities for SSH, kept in+// ~/.ssh/known_hosts like every other SSH program on the PC uses them.+//+// Before a terminal connects, Remote asks the server for its keys+// (ssh-keyscan) and looks them up (ssh-keygen -F, which understands hashed+// entries and the system's own list). A key seen before connects; a host+// never seen asks first; a host whose key changed gets the warning+// (RemoteHostChanged.dc) and nothing is changed unless the person says the+// server was rebuilt. ssh itself then runs with StrictHostKeyChecking=yes,+// so whatever the scan saw, the connection only goes ahead with a key in+// known_hosts: nothing is ever accepted on the way.+class HostKeys : public QObject+{+ Q_OBJECT+ QML_ELEMENT+ QML_SINGLETON++ Q_PROPERTY(QVariantList known READ known NOTIFY knownChanged)++public:+ static HostKeys *instance();+ static HostKeys *create(QQmlEngine *, QJSEngine *);++ // callback({ state: "known" | "new" | "changed" | "revoked" | "error",+ // name, keyType, fingerprint, keyLine,+ // previous: [{ keyType, fingerprint, seen }], error })+ Q_INVOKABLE void check(const QString &host, int port, const QJSValue &callback);+ // Adds the key a check found, in the form the system asks for (hashed+ // names, Debian's default).+ Q_INVOKABLE bool trust(const QString &host, int port, const QString &keyLine);+ // The server was rebuilt: every old key for it goes, the new one is+ // added.+ Q_INVOKABLE bool replace(const QString &host, int port, const QString &keyLine);++ // The entries of ~/.ssh/known_hosts for the Known hosts tab: [{ index,+ // name, hashed, keyType, fingerprint, seen }]. A hashed name is shown+ // as the saved host it matches, if any.+ QVariantList known();+ Q_INVOKABLE void reload();+ Q_INVOKABLE bool forget(int index);++ static QString knownHostsFile();+ static QString entryName(const QString &host, int port);+ // SHA256:... for a key line or a public key file's text.+ static QString fingerprint(const QString &keyLine);++Q_SIGNALS:+ void knownChanged();++private:+ explicit HostKeys(QObject *parent = nullptr);+ void remember(const QString &fingerprint);+ QString seen(const QString &fingerprint) const;+ bool append(const QString &line);++ QVariantList m_known;+ bool m_loaded = false;+};diff --git a/packages/wildos-remote/src/hosts.cpp b/packages/wildos-remote/src/hosts.cppnew file mode 100644index 0000000..39e986d--- /dev/null+++ b/packages/wildos-remote/src/hosts.cpp@@ -0,0 +1,395 @@+#include "hosts.h"+#include "paths.h"++#include <QDateTime>+#include <QDir>+#include <QFile>+#include <QFileInfo>+#include <QJsonArray>+#include <QJsonDocument>+#include <QJsonObject>+#include <QProcess>+#include <QRegularExpression>+#include <QSaveFile>+#include <QTcpSocket>+#include <QTimer>+#include <QUrl>+#include <QUuid>++namespace+{+QString file()+{+ return Paths::config() + QStringLiteral("/hosts.json");+}++QVariantMap desktopDefaults()+{+ return {+ {QStringLiteral("display"), QStringLiteral("full")},+ {QStringLiteral("resolution"), QStringLiteral("match")},+ {QStringLiteral("scaling"), QStringLiteral("auto")},+ {QStringLiteral("password"), QStringLiteral("ask")},+ {QStringLiteral("clipboard"), true},+ {QStringLiteral("sound"), true},+ {QStringLiteral("microphone"), false},+ {QStringLiteral("printers"), false},+ {QStringLiteral("folders"), false},+ {QStringLiteral("folderPath"), QDir::homePath() + QStringLiteral("/Downloads")},+ {QStringLiteral("gateway"), QString()},+ {QStringLiteral("speed"), QStringLiteral("auto")},+ };+}++QVariantMap sshDefaults()+{+ return {+ {QStringLiteral("identity"), QString()},+ {QStringLiteral("forwards"), QVariantList()},+ {QStringLiteral("colour"), QStringLiteral("#5fd39a")},+ };+}++// Fills in whatever an older or hand-written entry leaves out.+QVariantMap complete(QVariantMap h)+{+ const bool desktop = h.value(QStringLiteral("kind")).toString() == QLatin1String("desktop");+ h.insert(QStringLiteral("kind"), desktop ? QStringLiteral("desktop") : QStringLiteral("terminal"));+ const QString section = desktop ? QStringLiteral("desktop") : QStringLiteral("ssh");+ QVariantMap options = desktop ? desktopDefaults() : sshDefaults();+ const QVariantMap given = h.value(section).toMap();+ for (auto it = given.cbegin(); it != given.cend(); ++it) {+ options.insert(it.key(), it.value());+ }+ h.insert(section, options);+ if (h.value(QStringLiteral("name")).toString().trimmed().isEmpty()) {+ h.insert(QStringLiteral("name"), h.value(QStringLiteral("address")).toString());+ }+ return h;+}++// "web-01:2222" or "[fe80::1]:2222".+QPair<QString, int> splitAddress(const QString &address)+{+ const QString a = address.trimmed();+ static const QRegularExpression bracketed(QStringLiteral("^\\[([^\\]]+)\\](?::(\\d+))?$"));+ if (const auto m = bracketed.match(a); m.hasMatch()) {+ return {m.captured(1), m.captured(2).isEmpty() ? 0 : m.captured(2).toInt()};+ }+ if (a.count(QLatin1Char(':')) == 1) {+ const QString port = a.section(QLatin1Char(':'), 1);+ bool ok = false;+ const int p = port.toInt(&ok);+ if (ok) {+ return {a.section(QLatin1Char(':'), 0, 0), p};+ }+ }+ return {a, 0};+}+}++Hosts *Hosts::instance()+{+ static Hosts *hosts = new Hosts;+ return hosts;+}++Hosts *Hosts::create(QQmlEngine *, QJSEngine *)+{+ Hosts *hosts = instance();+ QJSEngine::setObjectOwnership(hosts, QJSEngine::CppOwnership);+ return hosts;+}++Hosts::Hosts(QObject *parent)+ : QObject(parent)+{+ load();+}++void Hosts::load()+{+ QFile f(file());+ if (!f.open(QIODevice::ReadOnly)) {+ m_groups = {QStringLiteral("Work"), QStringLiteral("Servers"), QStringLiteral("Home")};+ return;+ }+ const QJsonObject root = QJsonDocument::fromJson(f.readAll()).object();+ for (const QJsonValue &g : root.value(QStringLiteral("groups")).toArray()) {+ m_groups.append(g.toString());+ }+ for (const QJsonValue &h : root.value(QStringLiteral("hosts")).toArray()) {+ m_hosts.append(complete(h.toObject().toVariantMap()));+ }+}++void Hosts::write()+{+ QDir().mkpath(Paths::config());+ QJsonObject root;+ root.insert(QStringLiteral("groups"), QJsonArray::fromStringList(m_groups));+ root.insert(QStringLiteral("hosts"), QJsonArray::fromVariantList(m_hosts));+ QSaveFile f(file());+ if (f.open(QIODevice::WriteOnly)) {+ f.write(QJsonDocument(root).toJson());+ f.commit();+ // Addresses and user names are nobody else's business.+ QFile::setPermissions(file(), QFileDevice::ReadOwner | QFileDevice::WriteOwner);+ }+ ++m_revision;+ Q_EMIT changed();+}++int Hosts::indexOf(const QString &id) const+{+ for (int i = 0; i < m_hosts.size(); ++i) {+ if (m_hosts[i].toMap().value(QStringLiteral("id")).toString() == id) {+ return i;+ }+ }+ return -1;+}++QVariantMap Hosts::host(const QString &id) const+{+ const int i = indexOf(id);+ return i >= 0 ? m_hosts[i].toMap() : QVariantMap();+}++QString Hosts::save(const QVariantMap &input)+{+ QVariantMap h = complete(input);+ QString id = h.value(QStringLiteral("id")).toString();+ const int i = id.isEmpty() ? -1 : indexOf(id);+ if (i < 0) {+ if (id.isEmpty()) {+ id = QUuid::createUuid().toString(QUuid::WithoutBraces).left(12);+ }+ h.insert(QStringLiteral("id"), id);+ m_hosts.append(h);+ } else {+ m_hosts[i] = h;+ }+ const QString group = h.value(QStringLiteral("group")).toString();+ if (!group.isEmpty() && !m_groups.contains(group)) {+ m_groups.append(group);+ }+ write();+ return id;+}++void Hosts::remove(const QString &id)+{+ const int i = indexOf(id);+ if (i < 0) {+ return;+ }+ m_hosts.removeAt(i);+ QFile::remove(screenPath(id));+ write();+}++void Hosts::setFavourite(const QString &id, bool favourite)+{+ const int i = indexOf(id);+ if (i < 0) {+ return;+ }+ QVariantMap h = m_hosts[i].toMap();+ h.insert(QStringLiteral("favourite"), favourite);+ m_hosts[i] = h;+ write();+}++void Hosts::touch(const QString &id)+{+ const int i = indexOf(id);+ if (i < 0) {+ return;+ }+ QVariantMap h = m_hosts[i].toMap();+ h.insert(QStringLiteral("lastUsed"), QDateTime::currentDateTime().toString(Qt::ISODate));+ m_hosts[i] = h;+ write();+}++void Hosts::addGroup(const QString &name)+{+ const QString n = name.trimmed();+ if (!n.isEmpty() && !m_groups.contains(n)) {+ m_groups.append(n);+ write();+ }+}++void Hosts::renameGroup(const QString &from, const QString &to)+{+ const QString n = to.trimmed();+ const int g = m_groups.indexOf(from);+ if (g < 0 || n.isEmpty() || m_groups.contains(n)) {+ return;+ }+ m_groups[g] = n;+ for (QVariant &v : m_hosts) {+ QVariantMap h = v.toMap();+ if (h.value(QStringLiteral("group")).toString() == from) {+ h.insert(QStringLiteral("group"), n);+ v = h;+ }+ }+ write();+}++void Hosts::removeGroup(const QString &name)+{+ // The hosts stay, without a group.+ if (!m_groups.removeOne(name)) {+ return;+ }+ for (QVariant &v : m_hosts) {+ QVariantMap h = v.toMap();+ if (h.value(QStringLiteral("group")).toString() == name) {+ h.insert(QStringLiteral("group"), QString());+ v = h;+ }+ }+ write();+}++QVariantMap Hosts::parseAddress(const QString &text) const+{+ QString t = text.trimmed();+ if (t.isEmpty()) {+ return {};+ }+ QVariantMap out;+ if (t.startsWith(QLatin1String("rdp://"), Qt::CaseInsensitive) || t.startsWith(QLatin1String("ssh://"), Qt::CaseInsensitive)) {+ const QUrl url(t);+ if (!url.isValid() || url.host().isEmpty()) {+ return {};+ }+ const bool rdp = url.scheme().toLower() == QLatin1String("rdp");+ out.insert(QStringLiteral("kind"), rdp ? QStringLiteral("desktop") : QStringLiteral("terminal"));+ out.insert(QStringLiteral("user"), url.userName());+ out.insert(QStringLiteral("address"), url.port() > 0 ? QStringLiteral("%1:%2").arg(url.host()).arg(url.port()) : url.host());+ return out;+ }+ if (t.startsWith(QLatin1String("ssh "))) {+ // As ssh takes it: ssh [-p port] [-l user] [user@]host.+ const QStringList args = QProcess::splitCommand(t).mid(1);+ QString user, hostPart;+ int port = 0;+ for (int i = 0; i < args.size(); ++i) {+ const QString &a = args[i];+ if (a == QLatin1String("-p") && i + 1 < args.size()) {+ port = args[++i].toInt();+ } else if (a == QLatin1String("-l") && i + 1 < args.size()) {+ user = args[++i];+ } else if (a.startsWith(QLatin1Char('-'))) {+ // Anything else ssh takes a value for is skipped with it.+ if (QStringLiteral("bcDEeFIiJLmOoQRSWw").contains(a.mid(1, 1)) && a.size() == 2) {+ ++i;+ }+ } else if (hostPart.isEmpty()) {+ hostPart = a;+ }+ }+ if (hostPart.contains(QLatin1Char('@'))) {+ user = hostPart.section(QLatin1Char('@'), 0, -2);+ hostPart = hostPart.section(QLatin1Char('@'), -1);+ }+ if (hostPart.isEmpty()) {+ return {};+ }+ out.insert(QStringLiteral("kind"), QStringLiteral("terminal"));+ out.insert(QStringLiteral("user"), user);+ out.insert(QStringLiteral("address"), port > 0 ? QStringLiteral("%1:%2").arg(hostPart).arg(port) : hostPart);+ return out;+ }+ // user@host is an SSH address; host:3389 a desktop. A bare word is a+ // search unless it looks like a name on a network or an IP address.+ static const QRegularExpression userAt(QStringLiteral("^([^@\\s]+)@([^@\\s]+)$"));+ if (const auto m = userAt.match(t); m.hasMatch()) {+ const auto [h, p] = splitAddress(m.captured(2));+ out.insert(QStringLiteral("kind"), p == 3389 ? QStringLiteral("desktop") : QStringLiteral("terminal"));+ out.insert(QStringLiteral("user"), m.captured(1));+ out.insert(QStringLiteral("address"), m.captured(2));+ return out;+ }+ static const QRegularExpression addressLike(QStringLiteral("^(\\[[0-9a-fA-F:]+\\]|[0-9]{1,3}(\\.[0-9]{1,3}){3}|[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)+)(:\\d+)?$"));+ if (addressLike.match(t).hasMatch()) {+ const auto [h, p] = splitAddress(t);+ out.insert(QStringLiteral("kind"), p == 22 ? QStringLiteral("terminal") : QStringLiteral("desktop"));+ out.insert(QStringLiteral("user"), QString());+ out.insert(QStringLiteral("address"), t);+ return out;+ }+ return {};+}++QString Hosts::hostName(const QVariantMap &h) const+{+ return splitAddress(h.value(QStringLiteral("address")).toString()).first;+}++int Hosts::port(const QVariantMap &h) const+{+ const int p = splitAddress(h.value(QStringLiteral("address")).toString()).second;+ if (p > 0) {+ return p;+ }+ return h.value(QStringLiteral("kind")).toString() == QLatin1String("desktop") ? 3389 : 22;+}++void Hosts::probe(const QString &id)+{+ const QVariantMap h = host(id);+ if (h.isEmpty()) {+ return;+ }+ auto *socket = new QTcpSocket(this);+ auto finish = [this, socket, id](bool online) {+ if (socket->property("done").toBool()) {+ return;+ }+ socket->setProperty("done", true);+ m_reach.insert(id, online ? QStringLiteral("online") : QStringLiteral("offline"));+ Q_EMIT reachChanged();+ socket->abort();+ socket->deleteLater();+ };+ connect(socket, &QTcpSocket::connected, this, [finish] { finish(true); });+ connect(socket, &QTcpSocket::errorOccurred, this, [finish] { finish(false); });+ QTimer::singleShot(2500, socket, [finish] { finish(false); });+ socket->connectToHost(hostName(h), quint16(port(h)));+}++QString Hosts::screenPath(const QString &id) const+{+ return Paths::cache() + QStringLiteral("/screens/") + id + QStringLiteral(".png");+}++QUrl Hosts::screenUrl(const QString &id) const+{+ const QString path = screenPath(id);+ if (!QFileInfo::exists(path)) {+ return {};+ }+ QUrl url = QUrl::fromLocalFile(path);+ // A new screen under the same name must not come from QML's cache.+ url.setQuery(QStringLiteral("v=%1").arg(m_screens.value(id, QFileInfo(path).lastModified().toSecsSinceEpoch())));+ return url;+}++void Hosts::screenSaved(const QString &id)+{+ m_screens.insert(id, QDateTime::currentMSecsSinceEpoch());+ ++m_revision;+ Q_EMIT changed();+}++QStringList Hosts::colours() const+{+ return {QStringLiteral("#5fd39a"), QStringLiteral("#6ee0d0"), QStringLiteral("#8fb4ff"), QStringLiteral("#c78bff"),+ QStringLiteral("#ff9ac0"), QStringLiteral("#ff9a8a"), QStringLiteral("#ffc46a")};+}diff --git a/packages/wildos-remote/src/hosts.h b/packages/wildos-remote/src/hosts.hnew file mode 100644index 0000000..79dbd5a--- /dev/null+++ b/packages/wildos-remote/src/hosts.h@@ -0,0 +1,88 @@+#pragma once++#include <QHash>+#include <QObject>+#include <QQmlEngine>+#include <QVariantList>+#include <QVariantMap>++// The saved hosts, desktop (Remote Desktop) and terminal (SSH) alike, with+// their groups. Kept in ~/.config/wildos-remote/hosts.json, which never+// holds a password: those go to the keyring (Secrets) and only when the+// person ticks it. Screens from the end of a desktop session are kept in+// the cache folder, on this PC only.+//+// A host is a map:+// id, kind ("desktop" or "terminal"), name, address (host or host:port),+// user, group, note, favourite, lastUsed (ISO date),+// desktop: { display, resolution, scaling, password ("ask" or+// "keyring"), clipboard, sound, microphone, printers,+// folders, folderPath, gateway, speed }+// ssh: { identity (a private key path, or empty for ssh's own choice),+// forwards: [{ localPort, remoteHost, remotePort }], colour }+class Hosts : public QObject+{+ Q_OBJECT+ QML_ELEMENT+ QML_SINGLETON++ Q_PROPERTY(QVariantList hosts READ hosts NOTIFY changed)+ Q_PROPERTY(QStringList groups READ groups NOTIFY changed)+ Q_PROPERTY(QVariantMap reach READ reach NOTIFY reachChanged)+ Q_PROPERTY(int revision READ revision NOTIFY changed)++public:+ static Hosts *instance();+ static Hosts *create(QQmlEngine *, QJSEngine *);++ QVariantList hosts() const { return m_hosts; }+ QStringList groups() const { return m_groups; }+ QVariantMap reach() const { return m_reach; }+ int revision() const { return m_revision; }++ Q_INVOKABLE QVariantMap host(const QString &id) const;+ // Adds the host when its id is new or empty; returns the id.+ Q_INVOKABLE QString save(const QVariantMap &host);+ Q_INVOKABLE void remove(const QString &id);+ Q_INVOKABLE void setFavourite(const QString &id, bool favourite);+ Q_INVOKABLE void touch(const QString &id);+ Q_INVOKABLE void addGroup(const QString &name);+ Q_INVOKABLE void renameGroup(const QString &from, const QString &to);+ Q_INVOKABLE void removeGroup(const QString &name);++ // What the search box can connect to as typed: "ssh alex@web-01 -p+ // 2222", "alex@web-01", "rdp://pc" or "pc:3389". An empty map when the+ // text is a search, not an address.+ Q_INVOKABLE QVariantMap parseAddress(const QString &text) const;+ // A host's address split into host and port, with the kind's default+ // port when none is given.+ Q_INVOKABLE QString hostName(const QVariantMap &host) const;+ Q_INVOKABLE int port(const QVariantMap &host) const;++ // Whether each host answers on its port, for Online and Offline on the+ // recent desktops. Only opens and closes a TCP connection.+ Q_INVOKABLE void probe(const QString &id);+ // The screen at the end of the last session, or an empty URL.+ Q_INVOKABLE QUrl screenUrl(const QString &id) const;+ QString screenPath(const QString &id) const;+ void screenSaved(const QString &id);++ // The colours a terminal host's tile can take (RemoteHosts.dc).+ Q_INVOKABLE QStringList colours() const;++Q_SIGNALS:+ void changed();+ void reachChanged();++private:+ explicit Hosts(QObject *parent = nullptr);+ void load();+ void write();+ int indexOf(const QString &id) const;++ QVariantList m_hosts;+ QStringList m_groups;+ QVariantMap m_reach;+ QHash<QString, qint64> m_screens;+ int m_revision = 0;+};diff --git a/packages/wildos-remote/src/keychain.cpp b/packages/wildos-remote/src/keychain.cppnew file mode 100644index 0000000..4d10700--- /dev/null+++ b/packages/wildos-remote/src/keychain.cpp@@ -0,0 +1,584 @@+#include "keychain.h"+#include "askpass.h"+#include "hostkeys.h"+#include "hosts.h"+#include "paths.h"+#include "secrets.h"++#include <QLocale>+#include <QClipboard>+#include <QDateTime>+#include <QDir>+#include <QFile>+#include <QFileInfo>+#include <QGuiApplication>+#include <QJsonDocument>+#include <QJsonObject>+#include <QProcess>+#include <QRegularExpression>+#include <QSaveFile>+#include <QUrl>++namespace+{+QString labelsFile()+{+ return Paths::data() + QStringLiteral("/keys.json");+}++constexpr QFileDevice::Permissions ownerOnly = QFileDevice::ReadOwner | QFileDevice::WriteOwner;++// Whether a private key file is protected by a passphrase, from its own+// header: OpenSSH's format names its cipher ("none" when it is not), the+// old PEM format says ENCRYPTED.+bool encrypted(const QString &path)+{+ QFile f(path);+ if (!f.open(QIODevice::ReadOnly)) {+ return false;+ }+ const QByteArray text = f.read(64 * 1024);+ if (text.contains("ENCRYPTED")) {+ return true;+ }+ const int begin = text.indexOf("-----BEGIN OPENSSH PRIVATE KEY-----");+ const int end = text.indexOf("-----END OPENSSH PRIVATE KEY-----");+ if (begin < 0 || end < 0) {+ return false;+ }+ QByteArray body = text.mid(begin + 35, end - begin - 35);+ body.replace('\n', "").replace('\r', "");+ const QByteArray blob = QByteArray::fromBase64(body);+ const QByteArray magic("openssh-key-v1\0", 15);+ if (!blob.startsWith(magic) || blob.size() < 19) {+ return false;+ }+ const auto *p = reinterpret_cast<const uchar *>(blob.constData()) + 15;+ const quint32 len = (quint32(p[0]) << 24) | (quint32(p[1]) << 16) | (quint32(p[2]) << 8) | quint32(p[3]);+ return blob.mid(19, int(len)) != "none";+}++bool isPrivateKey(const QString &path)+{+ QFile f(path);+ if (!f.open(QIODevice::ReadOnly) || f.size() > 64 * 1024) {+ return false;+ }+ return f.read(64).contains("PRIVATE KEY-----");+}++QString typeName(const QString &type)+{+ if (type == QLatin1String("ssh-ed25519")) {+ return QStringLiteral("ED25519");+ }+ if (type == QLatin1String("[email protected]")) {+ return QStringLiteral("ED25519-SK");+ }+ if (type.startsWith(QLatin1String("sk-ecdsa"))) {+ return QStringLiteral("ECDSA-SK");+ }+ if (type.startsWith(QLatin1String("ecdsa"))) {+ return QStringLiteral("ECDSA");+ }+ if (type == QLatin1String("ssh-rsa")) {+ return QStringLiteral("RSA");+ }+ if (type == QLatin1String("ssh-dss")) {+ return QStringLiteral("DSA");+ }+ return type;+}++// An RSA key's size from its public blob: the modulus is the third field.+int rsaBits(const QString &base64)+{+ const QByteArray blob = QByteArray::fromBase64(base64.toLatin1());+ int at = 0;+ auto field = [&](QByteArray *out) {+ if (at + 4 > blob.size()) {+ return false;+ }+ const auto *p = reinterpret_cast<const uchar *>(blob.constData()) + at;+ const int len = int((quint32(p[0]) << 24) | (quint32(p[1]) << 16) | (quint32(p[2]) << 8) | quint32(p[3]));+ at += 4;+ if (len < 0 || at + len > blob.size()) {+ return false;+ }+ *out = blob.mid(at, len);+ at += len;+ return true;+ };+ QByteArray type, e, n;+ if (!field(&type) || !field(&e) || !field(&n)) {+ return 0;+ }+ while (!n.isEmpty() && n.at(0) == 0) {+ n.remove(0, 1);+ }+ return n.size() * 8;+}++QString slug(const QString &label)+{+ QString s = label.toLower();+ s.replace(QRegularExpression(QStringLiteral("[^a-z0-9]+")), QStringLiteral("_"));+ s = s.mid(0, 32);+ while (s.startsWith(QLatin1Char('_'))) {+ s.remove(0, 1);+ }+ while (s.endsWith(QLatin1Char('_'))) {+ s.chop(1);+ }+ return s.isEmpty() ? QStringLiteral("key") : s;+}++QString uniquePath(const QString &base)+{+ QString path = base;+ for (int n = 2; QFileInfo::exists(path) || QFileInfo::exists(path + QStringLiteral(".pub")); ++n) {+ path = base + QStringLiteral("_%1").arg(n);+ }+ return path;+}+}++Keychain *Keychain::instance()+{+ static Keychain *k = new Keychain;+ return k;+}++Keychain *Keychain::create(QQmlEngine *, QJSEngine *)+{+ Keychain *k = instance();+ QJSEngine::setObjectOwnership(k, QJSEngine::CppOwnership);+ return k;+}++Keychain::Keychain(QObject *parent)+ : QObject(parent)+{+ QFile f(labelsFile());+ if (f.open(QIODevice::ReadOnly)) {+ m_labels = QJsonDocument::fromJson(f.readAll()).object().toVariantMap();+ }+ connect(Hosts::instance(), &Hosts::changed, this, &Keychain::refresh);+ refresh();+}++bool Keychain::agent() const+{+ const QString sock = qEnvironmentVariable("SSH_AUTH_SOCK");+ return !sock.isEmpty() && QFileInfo::exists(sock);+}++void Keychain::writeLabels()+{+ QDir().mkpath(Paths::data());+ QSaveFile f(labelsFile());+ if (f.open(QIODevice::WriteOnly)) {+ f.write(QJsonDocument(QJsonObject::fromVariantMap(m_labels)).toJson());+ f.commit();+ }+}++void Keychain::call(const QJSValue &callback, const QVariantList &args)+{+ if (!callback.isCallable()) {+ return;+ }+ QJSEngine *engine = qjsEngine(this);+ QJSValueList values;+ for (const QVariant &a : args) {+ values.append(engine ? engine->toScriptValue(a) : QJSValue());+ }+ QJSValue(callback).call(values);+}++QString Keychain::label(const QString &path) const+{+ const QString l = m_labels.value(path).toMap().value(QStringLiteral("label")).toString();+ return l.isEmpty() ? QFileInfo(path).fileName() : l;+}++QVariantMap Keychain::key(const QString &path) const+{+ for (const QVariant &v : m_keys) {+ if (v.toMap().value(QStringLiteral("path")).toString() == path) {+ return v.toMap();+ }+ }+ return {};+}++void Keychain::loadAgent(const std::function<void()> &done)+{+ if (!agent()) {+ m_agentFingerprints.clear();+ done();+ return;+ }+ auto *p = new QProcess(this);+ p->setProgram(QStringLiteral("ssh-add"));+ p->setArguments({QStringLiteral("-l"), QStringLiteral("-E"), QStringLiteral("sha256")});+ connect(p, &QProcess::finished, this, [this, p, done](int, QProcess::ExitStatus) {+ m_agentFingerprints.clear();+ for (const QByteArray &line : p->readAllStandardOutput().split('\n')) {+ const QStringList f = QString::fromUtf8(line).split(QLatin1Char(' '), Qt::SkipEmptyParts);+ if (f.size() >= 2 && f[1].startsWith(QLatin1String("SHA256:"))) {+ m_agentFingerprints.insert(f[1]);+ }+ }+ p->deleteLater();+ done();+ });+ p->start();+}++void Keychain::refresh()+{+ loadAgent([this] {+ QVariantList keys;+ const QDir dir(Paths::ssh());+ const QVariantList hosts = Hosts::instance()->hosts();+ for (const QFileInfo &pub : dir.entryInfoList({QStringLiteral("*.pub")}, QDir::Files, QDir::Name)) {+ const QString path = pub.absolutePath() + QLatin1Char('/') + pub.completeBaseName();+ if (!QFileInfo::exists(path) || !isPrivateKey(path)) {+ continue;+ }+ QFile f(pub.absoluteFilePath());+ if (!f.open(QIODevice::ReadOnly)) {+ continue;+ }+ const QString publicKey = QString::fromUtf8(f.readAll()).trimmed();+ const QStringList parts = publicKey.split(QLatin1Char(' '), Qt::SkipEmptyParts);+ if (parts.size() < 2) {+ continue;+ }+ const QString type = typeName(parts[0]);+ const QString fp = HostKeys::fingerprint(parts[1]);+ QVariantMap k;+ k.insert(QStringLiteral("path"), path);+ k.insert(QStringLiteral("file"), QFileInfo(path).fileName());+ const QVariantMap meta = m_labels.value(path).toMap();+ QString lab = meta.value(QStringLiteral("label")).toString();+ if (lab.isEmpty()) {+ lab = parts.size() > 2 ? parts.mid(2).join(QLatin1Char(' ')) : QFileInfo(path).fileName();+ }+ k.insert(QStringLiteral("label"), lab);+ k.insert(QStringLiteral("type"), type);+ k.insert(QStringLiteral("bits"), type == QLatin1String("RSA") ? rsaBits(parts[1]) : 0);+ k.insert(QStringLiteral("fingerprint"), fp);+ k.insert(QStringLiteral("publicKey"), publicKey);+ const bool sk = type.endsWith(QLatin1String("-SK"));+ k.insert(QStringLiteral("securityKey"), sk);+ k.insert(QStringLiteral("encrypted"), !sk && encrypted(path));+ k.insert(QStringLiteral("inAgent"), m_agentFingerprints.contains(fp));+ k.insert(QStringLiteral("passphraseSaved"), meta.value(QStringLiteral("passphraseSaved")).toBool());+ QDateTime made = QDateTime::fromString(meta.value(QStringLiteral("made")).toString(), Qt::ISODate);+ if (!made.isValid()) {+ made = QFileInfo(path).birthTime().isValid() ? QFileInfo(path).birthTime() : QFileInfo(path).lastModified();+ }+ k.insert(QStringLiteral("made"), QLocale::system().toString(made.date(), QLocale::ShortFormat));+ k.insert(QStringLiteral("legacy"), type == QLatin1String("RSA") || type == QLatin1String("DSA"));+ // Only the hosts set to use this key; a host left to ssh's own+ // choice may be offered any key in the folder.+ QStringList usedBy;+ for (const QVariant &v : hosts) {+ const QVariantMap h = v.toMap();+ if (h.value(QStringLiteral("ssh")).toMap().value(QStringLiteral("identity")).toString() == path) {+ usedBy.append(h.value(QStringLiteral("name")).toString());+ }+ }+ k.insert(QStringLiteral("usedBy"), usedBy);+ // Fix a key ssh would refuse to use for being readable by others.+ if (QFileInfo(path).permissions() & (QFileDevice::ReadGroup | QFileDevice::ReadOther | QFileDevice::WriteGroup | QFileDevice::WriteOther)) {+ QFile::setPermissions(path, ownerOnly);+ }+ keys.append(k);+ }+ m_keys = keys;+ Q_EMIT changed();+ });+}++void Keychain::generate(const QString &label, const QString &passphrase, bool savePassphrase, const QJSValue &callback)+{+ const QString name = label.trimmed().isEmpty() ? QStringLiteral("Wild OS") : label.trimmed();+ const QString path = uniquePath(Paths::ssh() + QStringLiteral("/id_ed25519_") + slug(name));+ auto *p = new QProcess(this);+ // The passphrase goes to ssh-keygen through askpass, never as an+ // argument.+ const QString token = AskPass::instance()->newToken([passphrase](const QString &, int) -> std::optional<QString> {+ return passphrase;+ });+ p->setProcessEnvironment(AskPass::instance()->environment(token));+ p->setProgram(QStringLiteral("ssh-keygen"));+ p->setArguments({QStringLiteral("-q"), QStringLiteral("-t"), QStringLiteral("ed25519"), QStringLiteral("-a"), QStringLiteral("100"),+ QStringLiteral("-C"), name, QStringLiteral("-f"), path});+ p->setStandardInputFile(QProcess::nullDevice());+ connect(p, &QProcess::finished, this, [=, this](int code, QProcess::ExitStatus) {+ AskPass::instance()->release(token);+ const QString err = QString::fromUtf8(p->readAllStandardError()).trimmed();+ p->deleteLater();+ if (code != 0 || !QFileInfo::exists(path)) {+ call(callback, {false, err.isEmpty() ? QStringLiteral("The key couldn't be made.") : err, QString()});+ return;+ }+ QFile::setPermissions(path, ownerOnly);+ QVariantMap meta;+ meta.insert(QStringLiteral("label"), name);+ meta.insert(QStringLiteral("made"), QDateTime::currentDateTime().toString(Qt::ISODate));+ m_labels.insert(path, meta);+ writeLabels();+ if (savePassphrase && !passphrase.isEmpty()) {+ QFile pub(path + QStringLiteral(".pub"));+ pub.open(QIODevice::ReadOnly);+ const QString fp = HostKeys::fingerprint(QString::fromUtf8(pub.readAll()));+ Secrets::instance()->write(Secrets::passphraseKey(fp), passphrase, [this, path, callback](bool ok) {+ QVariantMap m = m_labels.value(path).toMap();+ m.insert(QStringLiteral("passphraseSaved"), ok);+ m_labels.insert(path, m);+ writeLabels();+ refresh();+ call(callback, {true, ok ? QString() : QStringLiteral("The key is made, but the keyring didn't take its passphrase."), path});+ });+ return;+ }+ refresh();+ call(callback, {true, QString(), path});+ });+ p->start();+}++void Keychain::importKey(const QUrl &file, const QJSValue &callback)+{+ const QString source = file.toLocalFile();+ if (!isPrivateKey(source)) {+ call(callback, {false, QStringLiteral("That file isn't an SSH private key."), QString()});+ return;+ }+ const QString path = uniquePath(Paths::ssh() + QLatin1Char('/') + QFileInfo(source).fileName());+ if (!QFile::copy(source, path)) {+ call(callback, {false, QStringLiteral("The key couldn't be copied into your .ssh folder."), QString()});+ return;+ }+ QFile::setPermissions(path, ownerOnly);+ QVariantMap meta;+ meta.insert(QStringLiteral("label"), QFileInfo(source).fileName());+ meta.insert(QStringLiteral("made"), QFileInfo(source).lastModified().toString(Qt::ISODate));+ m_labels.insert(path, meta);+ writeLabels();+ if (QFileInfo::exists(source + QStringLiteral(".pub"))) {+ QFile::copy(source + QStringLiteral(".pub"), path + QStringLiteral(".pub"));+ refresh();+ call(callback, {true, QString(), path});+ return;+ }+ // Without its public half: ssh-keygen works it out, asking for the+ // passphrase if the key has one.+ auto *p = new QProcess(this);+ const QString token = AskPass::instance()->newToken({}, QStringLiteral("Import %1").arg(QFileInfo(source).fileName()));+ p->setProcessEnvironment(AskPass::instance()->environment(token));+ p->setStandardInputFile(QProcess::nullDevice());+ p->setProgram(QStringLiteral("ssh-keygen"));+ p->setArguments({QStringLiteral("-y"), QStringLiteral("-f"), path});+ connect(p, &QProcess::finished, this, [=, this](int code, QProcess::ExitStatus) {+ AskPass::instance()->release(token);+ const QByteArray pub = p->readAllStandardOutput();+ p->deleteLater();+ if (code != 0 || pub.isEmpty()) {+ QFile::remove(path);+ m_labels.remove(path);+ writeLabels();+ call(callback, {false, QStringLiteral("The key couldn't be opened. Check its passphrase."), QString()});+ return;+ }+ QFile out(path + QStringLiteral(".pub"));+ if (out.open(QIODevice::WriteOnly)) {+ out.write(pub);+ }+ refresh();+ call(callback, {true, QString(), path});+ });+ p->start();+}++void Keychain::exportKey(const QString &path, const QUrl &folder, const QJSValue &callback)+{+ const QString dir = folder.toLocalFile();+ const QString target = uniquePath(dir + QLatin1Char('/') + QFileInfo(path).fileName());+ const bool ok = QFile::copy(path, target) && QFile::setPermissions(target, ownerOnly) && QFile::copy(path + QStringLiteral(".pub"), target + QStringLiteral(".pub"));+ call(callback, {ok, ok ? target : QStringLiteral("The key couldn't be copied there."), target});+}++bool Keychain::remove(const QString &path)+{+ const QVariantMap k = key(path);+ if (k.isEmpty()) {+ return false;+ }+ if (!QFile::moveToTrash(path)) {+ return false;+ }+ QFile::moveToTrash(path + QStringLiteral(".pub"));+ Secrets::instance()->remove(Secrets::passphraseKey(k.value(QStringLiteral("fingerprint")).toString()));+ m_labels.remove(path);+ writeLabels();+ refresh();+ return true;+}++void Keychain::rename(const QString &path, const QString &label)+{+ QVariantMap m = m_labels.value(path).toMap();+ m.insert(QStringLiteral("label"), label.trimmed());+ m_labels.insert(path, m);+ writeLabels();+ refresh();+}++void Keychain::copyPublic(const QString &path)+{+ QGuiApplication::clipboard()->setText(key(path).value(QStringLiteral("publicKey")).toString());+}++void Keychain::changePassphrase(const QString &path, const QString &newPassphrase, const QJSValue &callback)+{+ auto *p = new QProcess(this);+ // ssh-keygen asks for the old passphrase first (only if there is one),+ // then the new one twice; the old one comes from the person.+ const QString token = AskPass::instance()->newToken(+ [newPassphrase](const QString &prompt, int) -> std::optional<QString> {+ if (prompt.contains(QLatin1String("new passphrase"), Qt::CaseInsensitive) || prompt.contains(QLatin1String("same passphrase"), Qt::CaseInsensitive)) {+ return newPassphrase;+ }+ return std::nullopt;+ },+ QStringLiteral("Change the passphrase of %1").arg(label(path)));+ p->setProcessEnvironment(AskPass::instance()->environment(token));+ p->setStandardInputFile(QProcess::nullDevice());+ p->setProgram(QStringLiteral("ssh-keygen"));+ p->setArguments({QStringLiteral("-q"), QStringLiteral("-p"), QStringLiteral("-a"), QStringLiteral("100"), QStringLiteral("-f"), path});+ connect(p, &QProcess::finished, this, [=, this](int code, QProcess::ExitStatus) {+ AskPass::instance()->release(token);+ p->deleteLater();+ const QVariantMap k = key(path);+ // An old saved passphrase no longer opens it.+ if (code == 0 && k.value(QStringLiteral("passphraseSaved")).toBool()) {+ forgetPassphrase(path);+ }+ refresh();+ call(callback, {code == 0, code == 0 ? QString() : QStringLiteral("The passphrase wasn't changed.")});+ });+ p->start();+}++void Keychain::savePassphrase(const QString &path, const QString &passphrase, const QJSValue &callback)+{+ auto *p = new QProcess(this);+ const QString token = AskPass::instance()->newToken([passphrase](const QString &, int count) -> std::optional<QString> {+ // Asked a second time means the first was wrong: give up.+ return count == 1 ? std::optional<QString>(passphrase) : std::optional<QString>(QString());+ });+ p->setProcessEnvironment(AskPass::instance()->environment(token));+ p->setStandardInputFile(QProcess::nullDevice());+ p->setProgram(QStringLiteral("ssh-keygen"));+ p->setArguments({QStringLiteral("-y"), QStringLiteral("-f"), path});+ connect(p, &QProcess::finished, this, [=, this](int code, QProcess::ExitStatus) {+ AskPass::instance()->release(token);+ p->deleteLater();+ if (code != 0) {+ call(callback, {false, QStringLiteral("That passphrase doesn't open this key.")});+ return;+ }+ const QString fp = key(path).value(QStringLiteral("fingerprint")).toString();+ Secrets::instance()->write(Secrets::passphraseKey(fp), passphrase, [this, path, callback](bool ok) {+ QVariantMap m = m_labels.value(path).toMap();+ m.insert(QStringLiteral("passphraseSaved"), ok);+ m_labels.insert(path, m);+ writeLabels();+ refresh();+ call(callback, {ok, ok ? QString() : QStringLiteral("The keyring didn't take the passphrase.")});+ });+ });+ p->start();+}++void Keychain::forgetPassphrase(const QString &path)+{+ Secrets::instance()->remove(Secrets::passphraseKey(key(path).value(QStringLiteral("fingerprint")).toString()));+ QVariantMap m = m_labels.value(path).toMap();+ m.insert(QStringLiteral("passphraseSaved"), false);+ m_labels.insert(path, m);+ writeLabels();+ refresh();+}++void Keychain::addToAgent(const QString &path, const QJSValue &callback)+{+ if (!agent()) {+ call(callback, {false, QStringLiteral("No key agent is running in this session.")});+ return;+ }+ const QVariantMap k = key(path);+ auto run = [=, this](const QString &saved) {+ auto *p = new QProcess(this);+ const QString token = AskPass::instance()->newToken(+ [saved](const QString &, int count) -> std::optional<QString> {+ if (!saved.isEmpty() && count == 1) {+ return saved;+ }+ return std::nullopt;+ },+ QStringLiteral("Unlock %1").arg(label(path)));+ p->setProcessEnvironment(AskPass::instance()->environment(token));+ p->setStandardInputFile(QProcess::nullDevice());+ p->setProgram(QStringLiteral("ssh-add"));+ p->setArguments({QStringLiteral("--"), path});+ connect(p, &QProcess::finished, this, [=, this](int code, QProcess::ExitStatus) {+ AskPass::instance()->release(token);+ p->deleteLater();+ refresh();+ call(callback, {code == 0, code == 0 ? QString() : QStringLiteral("The key wasn't added to the agent.")});+ });+ p->start();+ };+ if (k.value(QStringLiteral("passphraseSaved")).toBool()) {+ Secrets::instance()->read(Secrets::passphraseKey(k.value(QStringLiteral("fingerprint")).toString()),+ [run](const QString &secret, bool) { run(secret); });+ } else {+ run(QString());+ }+}++void Keychain::prepare(const QString &path, const std::function<void()> &done)+{+ const QVariantMap k = key(path);+ if (k.isEmpty() || !agent() || k.value(QStringLiteral("inAgent")).toBool() || !k.value(QStringLiteral("passphraseSaved")).toBool()) {+ done();+ return;+ }+ Secrets::instance()->read(Secrets::passphraseKey(k.value(QStringLiteral("fingerprint")).toString()), [=, this](const QString &secret, bool found) {+ if (!found) {+ done();+ return;+ }+ auto *p = new QProcess(this);+ const QString token = AskPass::instance()->newToken([secret](const QString &, int count) -> std::optional<QString> {+ return count == 1 ? std::optional<QString>(secret) : std::optional<QString>(QString());+ });+ p->setProcessEnvironment(AskPass::instance()->environment(token));+ p->setStandardInputFile(QProcess::nullDevice());+ p->setProgram(QStringLiteral("ssh-add"));+ p->setArguments({QStringLiteral("--"), path});+ connect(p, &QProcess::finished, this, [=, this](int, QProcess::ExitStatus) {+ AskPass::instance()->release(token);+ p->deleteLater();+ refresh();+ done();+ });+ p->start();+ });+}diff --git a/packages/wildos-remote/src/keychain.h b/packages/wildos-remote/src/keychain.hnew file mode 100644index 0000000..e0e6fa0--- /dev/null+++ b/packages/wildos-remote/src/keychain.h@@ -0,0 +1,74 @@+#pragma once++#include <QJSValue>+#include <QObject>+#include <QQmlEngine>+#include <QSet>+#include <QVariantList>++// SSH keys (RemoteKeychain.dc). The keys are ordinary OpenSSH key files in+// ~/.ssh, private ones readable only by their owner, so ssh, scp, git and+// everything else finds them too; Remote only adds a label for each in its+// own data folder. Keys are made with ssh-keygen and loaded into the+// session's ssh-agent with ssh-add. A passphrase is only kept when the+// person asks, in the keyring.+//+// Each key is a map: path, file, label, type ("ED25519", "ED25519-SK",+// "RSA"), bits, fingerprint, publicKey, encrypted (has a passphrase),+// securityKey (a hardware key that must be touched), inAgent,+// passphraseSaved, made (short date in the regional format), usedBy (host names), legacy.+class Keychain : public QObject+{+ Q_OBJECT+ QML_ELEMENT+ QML_SINGLETON++ Q_PROPERTY(QVariantList keys READ keys NOTIFY changed)+ // An ssh-agent is running in this session (SSH_AUTH_SOCK).+ Q_PROPERTY(bool agent READ agent NOTIFY changed)++public:+ static Keychain *instance();+ static Keychain *create(QQmlEngine *, QJSEngine *);++ QVariantList keys() const { return m_keys; }+ bool agent() const;++ Q_INVOKABLE void refresh();+ Q_INVOKABLE QVariantMap key(const QString &path) const;+ // The label shown for a private key path, or its file name.+ Q_INVOKABLE QString label(const QString &path) const;++ // callback(ok, message, path)+ Q_INVOKABLE void generate(const QString &label, const QString &passphrase, bool savePassphrase, const QJSValue &callback);+ Q_INVOKABLE void importKey(const QUrl &file, const QJSValue &callback);+ Q_INVOKABLE void exportKey(const QString &path, const QUrl &folder, const QJSValue &callback);+ // Moves the key and its public half to the bin.+ Q_INVOKABLE bool remove(const QString &path);+ Q_INVOKABLE void rename(const QString &path, const QString &label);+ Q_INVOKABLE void copyPublic(const QString &path);+ // Changes or adds a passphrase; asks for the old one if it has one.+ Q_INVOKABLE void changePassphrase(const QString &path, const QString &newPassphrase, const QJSValue &callback);+ // Checks the passphrase opens the key before the keyring gets it.+ Q_INVOKABLE void savePassphrase(const QString &path, const QString &passphrase, const QJSValue &callback);+ Q_INVOKABLE void forgetPassphrase(const QString &path);+ // ssh-add, with the passphrase from the keyring when it is there.+ Q_INVOKABLE void addToAgent(const QString &path, const QJSValue &callback);++ // Before a terminal connects with this key: into the agent, if there is+ // one and the keyring has the passphrase, so ssh doesn't ask.+ void prepare(const QString &path, const std::function<void()> &done);++Q_SIGNALS:+ void changed();++private:+ explicit Keychain(QObject *parent = nullptr);+ void loadAgent(const std::function<void()> &done);+ void writeLabels();+ void call(const QJSValue &callback, const QVariantList &args);++ QVariantList m_keys;+ QVariantMap m_labels;+ QSet<QString> m_agentFingerprints;+};diff --git a/packages/wildos-remote/src/main.cpp b/packages/wildos-remote/src/main.cppnew file mode 100644index 0000000..52afc7e--- /dev/null+++ b/packages/wildos-remote/src/main.cpp@@ -0,0 +1,148 @@+// wildos-remote: Remote, Wild OS's app for other computers. Remote Desktop+// to Windows PCs and servers on the Windows mode engine, and SSH to+// servers with a terminal, files and a keychain.+//+// wildos-remote [ssh://user@host:port | rdp://host | user@host]+// wildos-remote /args-from:stdin+//+// The second is how Windows mode opens the whole Windows desktop with+// Remote: FreeRDP's arguments as xfreerdp3 takes them, one per line on+// standard input with the password last, so nothing secret is ever on a+// command line. Only that desktop's window opens.+//+// ssh, ssh-keygen and ssh-add also run this binary as their SSH_ASKPASS;+// it then only passes the question back to the Remote that started them.++#include "app.h"+#include "askpass.h"+#include "remotedesktop.h"+#include "sessionwindow.h"++#include <QFile>++#include <QApplication>+#include <QCommandLineParser>+#include <QDBusConnection>+#include <QDBusConnectionInterface>+#include <QDBusMessage>+#include <QIcon>+#include <QQmlApplicationEngine>+#include <QQuickStyle>+#include <QQuickWindow>++namespace+{+const QString serviceName = QStringLiteral("org.wildos.Remote");+const QString objectPath = QStringLiteral("/Remote");+}++// A second launch (or a link) goes to the Remote already running.+class Bus : public QObject+{+ Q_OBJECT+ Q_CLASSINFO("D-Bus Interface", "org.wildos.Remote")++public:+ using QObject::QObject;++public Q_SLOTS:+ Q_SCRIPTABLE void open(const QString &arg)+ {+ App::instance()->openArgument(arg);+ }+};++int main(int argc, char *argv[])+{+ if (qEnvironmentVariableIsSet("WILDOS_REMOTE_ASKPASS_TOKEN") && argc >= 1) {+ QCoreApplication helper(argc, argv);+ return AskPass::ask(argc > 1 ? QString::fromLocal8Bit(argv[1]) : QString());+ }++ QApplication app(argc, argv);+ app.setApplicationName(QStringLiteral("wildos-remote"));+ app.setOrganizationDomain(QStringLiteral("wildos.io"));+ app.setApplicationDisplayName(QStringLiteral("Remote"));+ app.setApplicationVersion(QStringLiteral(WILDOS_REMOTE_VERSION));+ app.setDesktopFileName(QStringLiteral("org.wildos.remote"));+ app.setWindowIcon(QIcon::fromTheme(QStringLiteral("org.wildos.remote")));+ // Closing the home window while a terminal or desktop is open leaves+ // those running.+ app.setQuitOnLastWindowClosed(true);++ if (app.arguments().contains(QStringLiteral("/args-from:stdin"))) {+ QList<QByteArray> args;+ QString title = QStringLiteral("Windows desktop");+ QFile in;+ if (in.open(stdin, QIODevice::ReadOnly)) {+ while (!in.atEnd()) {+ QByteArray line = in.readLine();+ while (line.endsWith('\n') || line.endsWith('\r')) {+ line.chop(1);+ }+ if (line.startsWith("/title:")) {+ title = QString::fromUtf8(line.mid(7));+ } else if (!line.isEmpty()) {+ args.append(line);+ }+ }+ }+ if (args.isEmpty()) {+ return 1;+ }+ QQuickStyle::setStyle(QStringLiteral("Basic"));+ QQuickWindow::setDefaultAlphaBuffer(true);+ App::instance()->setDesktopOnly(true);+ QQmlApplicationEngine engine;+ engine.loadFromModule("WildOS.Remote", "Main");+ Desktops::instance()->startWithArguments(title, args);+ for (QByteArray &a : args) {+ a.fill('\0');+ }+ const int status = app.exec();+ Desktops::instance()->closeAll();+ return status;+ }++ QCommandLineParser parser;+ parser.setApplicationDescription(QStringLiteral("Wild OS Remote"));+ parser.addHelpOption();+ parser.addVersionOption();+ parser.addPositionalArgument(QStringLiteral("address"), QStringLiteral("An ssh:// or rdp:// link, or user@host, to connect to."));+ parser.process(app);+ const QString arg = parser.positionalArguments().value(0);++ QDBusConnection bus = QDBusConnection::sessionBus();+ if (bus.isConnected() && bus.interface()->isServiceRegistered(serviceName)) {+ auto message = QDBusMessage::createMethodCall(serviceName, objectPath, serviceName, QStringLiteral("open"));+ message << arg;+ bus.call(message);+ return 0;+ }++ QQuickStyle::setStyle(QStringLiteral("Basic"));+ QQuickWindow::setDefaultAlphaBuffer(true);++ QQmlApplicationEngine engine;+ QObject::connect(&engine, &QQmlApplicationEngine::objectCreationFailed, &app, []() {+ QCoreApplication::exit(1);+ }, Qt::QueuedConnection);+ engine.loadFromModule("WildOS.Remote", "Main");++ auto *exported = new Bus(&app);+ if (bus.isConnected()) {+ bus.registerObject(objectPath, exported, QDBusConnection::ExportScriptableSlots);+ bus.registerService(serviceName);+ }+ if (!arg.isEmpty()) {+ QMetaObject::invokeMethod(App::instance(), [arg] { App::instance()->openArgument(arg); }, Qt::QueuedConnection);+ }+ const int status = app.exec();+ Desktops::instance()->closeAll();+ // The terminal window's QML goes before the engines and the+ // application it depends on.+ delete SessionWindow::instance(false);+ return status;+}++#include "main.moc"diff --git a/packages/wildos-remote/src/notify.cpp b/packages/wildos-remote/src/notify.cppnew file mode 100644index 0000000..1f97781--- /dev/null+++ b/packages/wildos-remote/src/notify.cpp@@ -0,0 +1,56 @@+#include "notify.h"++#include <QDBusConnection>+#include <QDBusMessage>+#include <QDBusPendingCallWatcher>+#include <QDBusPendingReply>++namespace+{+const QString service = QStringLiteral("org.freedesktop.Notifications");+const QString path = QStringLiteral("/org/freedesktop/Notifications");+}++Notify *Notify::instance()+{+ static Notify *n = new Notify;+ return n;+}++Notify *Notify::create(QQmlEngine *, QJSEngine *)+{+ Notify *n = instance();+ QJSEngine::setObjectOwnership(n, QJSEngine::CppOwnership);+ return n;+}++Notify::Notify(QObject *parent)+ : QObject(parent)+{+ QDBusConnection::sessionBus().connect(service, path, service, QStringLiteral("ActionInvoked"), this, SLOT(invoked(uint, QString)));+}++void Notify::send(const QString &title, const QString &body, const QString &action, const QJSValue &onAction)+{+ QDBusMessage m = QDBusMessage::createMethodCall(service, path, service, QStringLiteral("Notify"));+ const QStringList actions = action.isEmpty() ? QStringList() : QStringList{QStringLiteral("default"), action, QStringLiteral("act"), action};+ QVariantMap hints;+ hints.insert(QStringLiteral("desktop-entry"), QStringLiteral("org.wildos.remote"));+ m << QStringLiteral("Remote") << uint(0) << QStringLiteral("org.wildos.remote") << title << body << actions << hints << int(-1);+ auto *watcher = new QDBusPendingCallWatcher(QDBusConnection::sessionBus().asyncCall(m), this);+ connect(watcher, &QDBusPendingCallWatcher::finished, this, [this, watcher, onAction] {+ QDBusPendingReply<uint> reply = *watcher;+ if (!reply.isError() && onAction.isCallable()) {+ m_actions.insert(reply.value(), onAction);+ }+ watcher->deleteLater();+ });+}++void Notify::invoked(uint id, const QString &)+{+ QJSValue callback = m_actions.take(id);+ if (callback.isCallable()) {+ callback.call();+ }+}diff --git a/packages/wildos-remote/src/notify.h b/packages/wildos-remote/src/notify.hnew file mode 100644index 0000000..4a95a29--- /dev/null+++ b/packages/wildos-remote/src/notify.h@@ -0,0 +1,30 @@+#pragma once++#include <QHash>+#include <QJSValue>+#include <QObject>+#include <QQmlEngine>++// A desktop notification with one action, for news that matters when the+// window isn't in front: a remote PC that disconnected (RemoteWindowed.dc,+// "Work PC disconnected" with Reconnect).+class Notify : public QObject+{+ Q_OBJECT+ QML_ELEMENT+ QML_SINGLETON++public:+ static Notify *instance();+ static Notify *create(QQmlEngine *, QJSEngine *);++ Q_INVOKABLE void send(const QString &title, const QString &body, const QString &action, const QJSValue &onAction);++private Q_SLOTS:+ void invoked(uint id, const QString &key);++private:+ explicit Notify(QObject *parent = nullptr);++ QHash<uint, QJSValue> m_actions;+};diff --git a/packages/wildos-remote/src/paths.h b/packages/wildos-remote/src/paths.hnew file mode 100644index 0000000..10234e0--- /dev/null+++ b/packages/wildos-remote/src/paths.h@@ -0,0 +1,53 @@+#pragma once++#include <QDir>+#include <QFile>+#include <QStandardPaths>+#include <QString>++// Where Remote keeps things, all of it on this PC: settings and hosts in+// ~/.config/wildos-remote, snippets and history in ~/.local/share, screens+// in the cache, sockets in the runtime folder, and keys where ssh expects+// them.+namespace Paths+{+inline QString config()+{+ return QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation) + QStringLiteral("/wildos-remote");+}++inline QString data()+{+ return QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QStringLiteral("/wildos-remote");+}++inline QString cache()+{+ return QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation) + QStringLiteral("/wildos-remote");+}++// Only this user may enter it: the askpass and connection-sharing sockets+// live here.+inline QString runtime()+{+ QString base = QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation);+ if (base.isEmpty()) {+ base = QDir::tempPath();+ }+ const QString dir = base + QStringLiteral("/wildos-remote");+ QDir().mkpath(dir);+ QFile::setPermissions(dir, QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ExeOwner);+ return dir;+}++// ~/.ssh, made the way ssh insists on: only its owner may enter.+inline QString ssh()+{+ const QString dir = QDir::homePath() + QStringLiteral("/.ssh");+ if (!QDir(dir).exists()) {+ QDir().mkpath(dir);+ QFile::setPermissions(dir, QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ExeOwner);+ }+ return dir;+}+}diff --git a/packages/wildos-remote/src/remotedesktop.cpp b/packages/wildos-remote/src/remotedesktop.cppnew file mode 100644index 0000000..79d0f01--- /dev/null+++ b/packages/wildos-remote/src/remotedesktop.cpp@@ -0,0 +1,511 @@+#include "remotedesktop.h"+#include "hosts.h"+#include "secrets.h"++#include "client.h"+#include "desktop.h"+#include "input.h"++#include <QDir>+#include <QFileInfo>+#include <QGuiApplication>+#include <QScreen>++namespace+{+QByteArray arg(const QString &text)+{+ return text.toUtf8();+}++// What FreeRDP's names for an ending mean to the person.+QPair<QString, QString> explain(const QString &code, const QString &name, const QString &address, bool wasOpen)+{+ if (code.contains(QLatin1String("DISCONNECTED_BY_OTHERCONNECTION"))) {+ return {QStringLiteral("%1 disconnected").arg(name),+ QStringLiteral("Someone signed in at the PC itself or from another device, which ends a remote session. Your apps are still open there.")};+ }+ if (code.contains(QLatin1String("RPC_INITIATED_DISCONNECT"))) {+ return {QStringLiteral("%1 disconnected").arg(name), QStringLiteral("Someone on %1 ended the session.").arg(name)};+ }+ if (code.contains(QLatin1String("IDLE_TIMEOUT")) || code.contains(QLatin1String("LOGON_TIMEOUT"))) {+ return {QStringLiteral("%1 disconnected").arg(name), QStringLiteral("%1 ends sessions left idle for a while. Your apps are still open there.").arg(name)};+ }+ if (code.contains(QLatin1String("INSUFFICIENT_PRIVILEGES")) || code.contains(QLatin1String("ACCOUNT_RESTRICTION"))) {+ return {QStringLiteral("Not allowed on %1").arg(name), QStringLiteral("That account isn't allowed to use Remote Desktop on %1. Its administrator can add it to Remote Desktop Users.").arg(name)};+ }+ if (code.contains(QLatin1String("LOCKED_OUT"))) {+ return {QStringLiteral("Account locked"), QStringLiteral("%1 has locked that account after too many tries. Try again later, or ask its administrator.").arg(name)};+ }+ if (code.contains(QLatin1String("PASSWORD_EXPIRED")) || code.contains(QLatin1String("PASSWORD_MUST_CHANGE"))) {+ return {QStringLiteral("Password needs changing"), QStringLiteral("The account's password has expired. Sign in at the PC itself to set a new one.")};+ }+ if (code.contains(QLatin1String("DNS_NAME_NOT_FOUND"))) {+ return {QStringLiteral("Couldn't find %1").arg(name), QStringLiteral("There's no computer called %1 on this network. Check the address.").arg(address)};+ }+ if (code.contains(QLatin1String("CONNECT_CANCELLED"))) {+ return {};+ }+ if (code.contains(QLatin1String("TRANSPORT_FAILED")) || code.contains(QLatin1String("CONNECT_FAILED")) || code.contains(QLatin1String("TLS_CONNECT"))) {+ if (wasOpen) {+ return {QStringLiteral("%1 disconnected").arg(name), QStringLiteral("The connection was lost and didn't come back. Your session is still running on the PC, so reconnecting picks it up.")};+ }+ return {QStringLiteral("Couldn't reach %1").arg(name),+ QStringLiteral("Check %1 is switched on, that Remote Desktop is on in its settings, and that its firewall lets it through.").arg(name)};+ }+ if (code.isEmpty()) {+ return {};+ }+ return {QStringLiteral("%1 disconnected").arg(name), QStringLiteral("The connection ended (%1).").arg(code)};+}+}++RemoteDesktop::RemoteDesktop(const QVariantMap &host, const QString &display, QObject *parent)+ : QObject(parent)+ , m_host(host)+ , m_display(display)+ , m_user(host.value(QStringLiteral("user")).toString())+{+ const QVariantMap d = host.value(QStringLiteral("desktop")).toMap();+ if (m_display.isEmpty()) {+ m_display = d.value(QStringLiteral("display"), QStringLiteral("full")).toString();+ }+ m_clipboard = d.value(QStringLiteral("clipboard"), true).toBool();+ for (const char *k : {"sound", "microphone", "printers", "folders"}) {+ m_sharing.insert(QString::fromLatin1(k), d.value(QString::fromLatin1(k)).toBool());+ }+ m_sharing.insert(QStringLiteral("clipboard"), m_clipboard);+ m_latencyTimer.setInterval(2000);+ connect(&m_latencyTimer, &QTimer::timeout, this, [this] {+ const int l = m_session ? m_session->latency() : 0;+ if (l != m_latency) {+ m_latency = l;+ Q_EMIT latencyChanged();+ }+ });+}++RemoteDesktop::~RemoteDesktop()+{+ if (m_session) {+ m_session->stop();+ }+}++QObject *RemoteDesktop::sessionObject() const+{+ return m_session;+}++QSize RemoteDesktop::desktopSize() const+{+ return m_session ? m_session->desktopSize() : QSize();+}++void RemoteDesktop::setState(const QString &state)+{+ if (state != m_state) {+ m_state = state;+ Q_EMIT stateChanged();+ }+}++void RemoteDesktop::setDisplay(const QString &display)+{+ if (display != m_display) {+ m_display = display;+ Q_EMIT displayChanged();+ }+}++QList<QByteArray> RemoteDesktop::arguments(const QString &password) const+{+ const QList<QByteArray> raw = m_host.value(QStringLiteral("arguments")).value<QList<QByteArray>>();+ if (!raw.isEmpty()) {+ return raw;+ }+ Hosts *hosts = Hosts::instance();+ const QVariantMap d = m_host.value(QStringLiteral("desktop")).toMap();+ QList<QByteArray> out;+ out << arg(QStringLiteral("/v:%1:%2").arg(hosts->hostName(m_host)).arg(hosts->port(m_host)));+ // DOMAIN\user or user@domain, as Windows' own client takes them.+ QString user = m_user;+ if (user.contains(QLatin1Char('\\'))) {+ out << arg(QStringLiteral("/d:") + user.section(QLatin1Char('\\'), 0, 0));+ user = user.section(QLatin1Char('\\'), 1);+ }+ if (!user.isEmpty()) {+ out << arg(QStringLiteral("/u:") + user);+ }+ if (!password.isEmpty()) {+ out << arg(QStringLiteral("/p:") + password);+ }+ out << (m_sharing.value(QStringLiteral("clipboard")).toBool() ? QByteArrayLiteral("+clipboard") : QByteArrayLiteral("-clipboard"));+ // Without sound here, Windows doesn't play it there either.+ out << (m_sharing.value(QStringLiteral("sound")).toBool() ? QByteArrayLiteral("/sound:sys:pulse") : QByteArrayLiteral("/audio-mode:2"));+ if (m_sharing.value(QStringLiteral("microphone")).toBool()) {+ out << QByteArrayLiteral("/microphone:sys:pulse");+ }+ if (m_sharing.value(QStringLiteral("printers")).toBool()) {+ out << QByteArrayLiteral("/printer");+ }+ if (m_sharing.value(QStringLiteral("folders")).toBool()) {+ QString path = d.value(QStringLiteral("folderPath")).toString();+ if (path.isEmpty() || !QFileInfo(path).isDir()) {+ path = QDir::homePath() + QStringLiteral("/Downloads");+ }+ // The folder's own name is what Windows shows it as.+ QString shown = QFileInfo(path).fileName().remove(QLatin1Char(','));+ out << arg(QStringLiteral("/drive:%1,%2").arg(shown.isEmpty() ? QStringLiteral("Wild OS") : shown, path));+ }+ const QString gateway = d.value(QStringLiteral("gateway")).toString();+ if (!gateway.isEmpty()) {+ out << arg(QStringLiteral("/gateway:g:") + gateway);+ }+ const QString speed = d.value(QStringLiteral("speed"), QStringLiteral("auto")).toString();+ out << arg(QStringLiteral("/network:") + (speed == QLatin1String("lan") ? QStringLiteral("lan")+ : speed == QLatin1String("broadband") ? QStringLiteral("broadband-high")+ : speed == QLatin1String("modem") ? QStringLiteral("modem")+ : QStringLiteral("auto")));+ const QString resolution = d.value(QStringLiteral("resolution"), QStringLiteral("match")).toString();+ if (resolution != QLatin1String("match")) {+ out << arg(QStringLiteral("/size:") + resolution);+ } else {+ // A window's size follows the window.+ out << QByteArrayLiteral("/dynamic-resolution");+ }+ out << QByteArrayLiteral("+auto-reconnect") << QByteArrayLiteral("/log-level:WARN");+ return out;+}++void RemoteDesktop::start(const QString &password)+{+ if (m_session) {+ m_session->disconnect(this);+ m_session->stop();+ m_session->deleteLater();+ }+ m_session = new DesktopSession(this);+ m_attempt = 0;+ m_endTitle.clear();+ m_endText.clear();+ setState(QStringLiteral("connecting"));++ QString error;+ QList<QByteArray> args = arguments(password);+ if (!m_session->configure(args, &error)) {+ m_endTitle = QStringLiteral("Couldn't connect to %1").arg(name());+ m_endText = error;+ setState(QStringLiteral("ended"));+ return;+ }+ // Laid out for the screen the window will be on, at that screen's+ // scale; a chosen resolution or scaling wins.+ QScreen *screen = QGuiApplication::primaryScreen();+ const QVariantMap d = m_host.value(QStringLiteral("desktop")).toMap();+ const QString scaling = d.value(QStringLiteral("scaling"), QStringLiteral("auto")).toString();+ const double dpr = screen ? screen->devicePixelRatio() : 1.0;+ const double scale = scaling == QLatin1String("auto") ? dpr : scaling.toDouble() / 100.0;+ if (m_display == QLatin1String("all") && QGuiApplication::screens().size() > 1) {+ QList<QRect> monitors;+ // The primary screen first; each in physical pixels, at its place.+ QList<QScreen *> screens = QGuiApplication::screens();+ screens.removeOne(screen);+ screens.prepend(screen);+ m_monitors.clear();+ for (QScreen *s : std::as_const(screens)) {+ const QRect g = s->geometry();+ const double r = s->devicePixelRatio();+ const QRect physical(qRound(g.x() * r), qRound(g.y() * r), qRound(g.width() * r), qRound(g.height() * r));+ monitors.append(physical);+ m_monitors.append(QVariantMap{{QStringLiteral("screen"), s->name()},+ {QStringLiteral("rect"), physical.translated(-monitors.first().topLeft())}});+ }+ m_session->setMonitors(monitors, scale);+ } else if (screen && d.value(QStringLiteral("resolution"), QStringLiteral("match")).toString() == QLatin1String("match")) {+ QSize size = screen->size() * dpr;+ if (m_display == QLatin1String("window")) {+ // A window a little smaller than the screen, its title bar+ // above the picture.+ size = (screen->availableSize() * 0.8 - QSize(0, 40)) * dpr;+ }+ m_session->setDisplay(size, scale);+ }++ connect(m_session, &DesktopSession::certificateNeeded, this, [this](const QVariantMap &info, bool changed) {+ setState(QStringLiteral("certificate"));+ Q_EMIT certificateNeeded(info, changed);+ });+ connect(m_session, &DesktopSession::credentialsNeeded, this, [this](const QString &user, const QString &, const QString &reason) {+ setState(QStringLiteral("signin"));+ Q_EMIT credentialsNeeded(user.isEmpty() ? m_user : user, reason);+ });+ connect(m_session, &DesktopSession::connected, this, [this] {+ m_everConnected = true;+ m_attempt = 0;+ setState(QStringLiteral("connected"));+ m_latencyTimer.start();+ // Only now, signed in, does a typed password go to the keyring.+ if (m_savePassword && !m_pendingPassword.isEmpty()) {+ Secrets::instance()->write(Secrets::hostKey(hostId()), m_pendingPassword);+ }+ m_pendingPassword.fill(QLatin1Char('\0'));+ m_pendingPassword.clear();+ Hosts::instance()->touch(hostId());+ Q_EMIT opened();+ });+ connect(m_session, &DesktopSession::reconnecting, this, [this](int attempt, int) {+ m_attempt = attempt;+ setState(QStringLiteral("reconnecting"));+ });+ connect(m_session, &DesktopSession::reconnected, this, [this] {+ m_attempt = 0;+ setState(QStringLiteral("connected"));+ });+ connect(m_session, &DesktopSession::frameChanged, this, [this] {+ if (desktopSize() != m_lastFrame.size()) {+ Q_EMIT desktopSizeChanged();+ }+ });+ connect(m_session, &DesktopSession::finished, this, &RemoteDesktop::finished);+ m_session->start();+}++void RemoteDesktop::finished(const QString &code, bool authFailed)+{+ m_latencyTimer.stop();+ if (m_everConnected) {+ saveScreen();+ }+ if (authFailed && !m_everConnected) {+ // Asked again on a new connection; a saved password that no longer+ // works is forgotten.+ Secrets::instance()->remove(Secrets::hostKey(hostId()));+ setState(QStringLiteral("signin"));+ Q_EMIT retryWanted(m_user);+ return;+ }+ const auto [title, text] = explain(code, name(), address(), m_everConnected);+ m_endTitle = title;+ m_endText = text;+ const bool unexpected = !title.isEmpty();+ setState(QStringLiteral("ended"));+ if (unexpected && m_everConnected) {+ Q_EMIT lost();+ }+}++void RemoteDesktop::answerCertificate(bool accept, bool remember)+{+ if (m_session) {+ setState(QStringLiteral("connecting"));+ m_session->answerCertificate(accept, remember);+ }+}++void RemoteDesktop::signIn(const QString &user, const QString &password, bool save)+{+ m_user = user;+ m_savePassword = save;+ m_pendingPassword = password;+ if (save) {+ QVariantMap h = Hosts::instance()->host(hostId());+ if (!h.isEmpty()) {+ QVariantMap d = h.value(QStringLiteral("desktop")).toMap();+ d.insert(QStringLiteral("password"), QStringLiteral("keyring"));+ h.insert(QStringLiteral("desktop"), d);+ h.insert(QStringLiteral("user"), user);+ Hosts::instance()->save(h);+ }+ }+ setState(QStringLiteral("connecting"));+ if (m_session && m_session->client()->running()) {+ QString domain;+ QString name = user;+ if (user.contains(QLatin1Char('\\'))) {+ domain = user.section(QLatin1Char('\\'), 0, 0);+ name = user.section(QLatin1Char('\\'), 1);+ }+ m_session->answerCredentials(true, name, domain, password);+ } else {+ start(password);+ }+}++void RemoteDesktop::cancelSignIn()+{+ if (m_session) {+ m_session->answerCredentials(false, {}, {}, {});+ m_session->stop();+ }+ m_endTitle.clear();+ setState(QStringLiteral("ended"));+}++void RemoteDesktop::tryNow()+{+ if (m_session) {+ m_session->tryNow();+ }+}++void RemoteDesktop::stopTrying()+{+ if (m_session) {+ m_session->stopTrying();+ }+}++void RemoteDesktop::disconnectNow()+{+ if (m_everConnected) {+ saveScreen();+ }+ if (m_session) {+ m_session->stop();+ }+}++void RemoteDesktop::sendKeys(const QString &which)+{+ if (!m_session) {+ return;+ }+ Client *c = m_session->client();+ using namespace rdpinput;+ if (which == QLatin1String("ctrl-alt-del")) {+ chord(c, {ctrl, alt, del});+ } else if (which == QLatin1String("windows")) {+ chord(c, {windows});+ } else if (which == QLatin1String("print")) {+ chord(c, {printScreen});+ } else if (which == QLatin1String("alt-tab")) {+ chord(c, {alt, tab});+ }+}++void RemoteDesktop::setClipboard(bool on)+{+ setSharing(QStringLiteral("clipboard"), on);+}++void RemoteDesktop::setSharing(const QString &key, bool on)+{+ if (m_sharing.value(key).toBool() == on) {+ return;+ }+ m_sharing.insert(key, on);+ if (key == QLatin1String("clipboard")) {+ m_clipboard = on;+ }+ // RDP agrees what's shared as it connects: the change waits for the+ // next connection, and the host keeps it for then.+ m_sharingPending = true;+ QVariantMap h = Hosts::instance()->host(hostId());+ if (!h.isEmpty()) {+ QVariantMap d = h.value(QStringLiteral("desktop")).toMap();+ d.insert(key, on);+ h.insert(QStringLiteral("desktop"), d);+ Hosts::instance()->save(h);+ }+ Q_EMIT sharingChanged();+}++void RemoteDesktop::setSendShortcuts(bool on)+{+ if (on != m_sendShortcuts) {+ m_sendShortcuts = on;+ Q_EMIT sendShortcutsChanged();+ }+}++void RemoteDesktop::saveScreen()+{+ if (!m_session || hostId().isEmpty()) {+ return;+ }+ const QImage frame = m_session->frame();+ if (frame.isNull() || frame.width() < 64) {+ return;+ }+ m_lastFrame = frame;+ const QString path = Hosts::instance()->screenPath(hostId());+ QDir().mkpath(QFileInfo(path).absolutePath());+ QFile::setPermissions(QFileInfo(path).absolutePath(), QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ExeOwner);+ if (frame.scaledToWidth(720, Qt::SmoothTransformation).save(path)) {+ QFile::setPermissions(path, QFileDevice::ReadOwner | QFileDevice::WriteOwner);+ Hosts::instance()->screenSaved(hostId());+ }+}++Desktops *Desktops::instance()+{+ static Desktops *d = new Desktops;+ return d;+}++Desktops *Desktops::create(QQmlEngine *, QJSEngine *)+{+ Desktops *d = instance();+ QJSEngine::setObjectOwnership(d, QJSEngine::CppOwnership);+ return d;+}++Desktops::Desktops(QObject *parent)+ : QObject(parent)+{+}++RemoteDesktop *Desktops::start(const QVariantMap &host, const QString &display)+{+ auto *desktop = new RemoteDesktop(host, display, this);+ QJSEngine::setObjectOwnership(desktop, QJSEngine::CppOwnership);+ m_open.append(desktop);+ Q_EMIT started(desktop);+ const bool keyring = host.value(QStringLiteral("desktop")).toMap().value(QStringLiteral("password")).toString() == QLatin1String("keyring");+ if (keyring && !host.value(QStringLiteral("id")).toString().isEmpty()) {+ Secrets::instance()->read(Secrets::hostKey(host.value(QStringLiteral("id")).toString()), [desktop = QPointer(desktop)](const QString &secret, bool) {+ if (desktop) {+ desktop->start(secret);+ }+ });+ } else {+ desktop->start(QString());+ }+ return desktop;+}++RemoteDesktop *Desktops::startWithArguments(const QString &title, const QList<QByteArray> &args)+{+ QVariantMap host;+ host.insert(QStringLiteral("name"), title);+ for (const QByteArray &a : args) {+ if (a.startsWith("/v:")) {+ host.insert(QStringLiteral("address"), QString::fromUtf8(a.mid(3)));+ } else if (a.startsWith("/u:")) {+ host.insert(QStringLiteral("user"), QString::fromUtf8(a.mid(3)));+ }+ }+ host.insert(QStringLiteral("arguments"), QVariant::fromValue(args));+ auto *desktop = new RemoteDesktop(host, QStringLiteral("window"), this);+ QJSEngine::setObjectOwnership(desktop, QJSEngine::CppOwnership);+ m_open.append(desktop);+ Q_EMIT started(desktop);+ desktop->start(QString());+ return desktop;+}++bool Desktops::resizeTo(RemoteDesktop *desktop, const QSize &physical, double scale)+{+ return desktop && desktop->session() && desktop->session()->resize(physical, scale);+}++void Desktops::closeAll()+{+ // Each one's connection thread is joined as it goes, before anything it+ // uses is torn down with the process.+ const auto open = std::exchange(m_open, {});+ for (const QPointer<RemoteDesktop> &d : open) {+ delete d.data();+ }+}diff --git a/packages/wildos-remote/src/remotedesktop.h b/packages/wildos-remote/src/remotedesktop.hnew file mode 100644index 0000000..6f0c00c--- /dev/null+++ b/packages/wildos-remote/src/remotedesktop.h@@ -0,0 +1,165 @@+#pragma once++#include <QImage>+#include <QObject>+#include <QPointer>+#include <QQmlEngine>+#include <QTimer>+#include <QVariantMap>++class DesktopSession;++// One Remote Desktop connection from Remote (RemoteCheck.dc to+// RemoteWindowed.dc): its host's settings turned into FreeRDP's, the+// questions it asks on the way in, the session while it runs, and why it+// ended.+//+// state: "connecting", "certificate", "signin", "connected",+// "reconnecting" or "ended".+class RemoteDesktop : public QObject+{+ Q_OBJECT+ QML_ANONYMOUS++ Q_PROPERTY(QString hostId READ hostId CONSTANT)+ Q_PROPERTY(QString name READ name CONSTANT)+ Q_PROPERTY(QString address READ address CONSTANT)+ Q_PROPERTY(QString user READ user NOTIFY stateChanged)+ Q_PROPERTY(QString state READ state NOTIFY stateChanged)+ Q_PROPERTY(bool everConnected READ everConnected NOTIFY stateChanged)+ Q_PROPERTY(int attempt READ attempt NOTIFY stateChanged)+ Q_PROPERTY(int attempts READ attempts CONSTANT)+ Q_PROPERTY(int latency READ latency NOTIFY latencyChanged)+ Q_PROPERTY(QString endTitle READ endTitle NOTIFY stateChanged)+ Q_PROPERTY(QString endText READ endText NOTIFY stateChanged)+ Q_PROPERTY(QString display READ display WRITE setDisplay NOTIFY displayChanged)+ Q_PROPERTY(bool multiMonitor READ multiMonitor CONSTANT)+ // With all monitors: [{ screen (its name), rect (its part of the+ // desktop) }], as the desktop was laid out.+ Q_PROPERTY(QVariantList monitors READ monitors NOTIFY stateChanged)+ Q_PROPERTY(QSize desktopSize READ desktopSize NOTIFY desktopSizeChanged)+ Q_PROPERTY(bool clipboard READ clipboard WRITE setClipboard NOTIFY sharingChanged)+ Q_PROPERTY(QVariantMap sharing READ sharing NOTIFY sharingChanged)+ Q_PROPERTY(bool sharingChanged READ sharingPending NOTIFY sharingChanged)+ Q_PROPERTY(bool sendShortcuts READ sendShortcuts WRITE setSendShortcuts NOTIFY sendShortcutsChanged)+ Q_PROPERTY(QObject *session READ sessionObject CONSTANT)++public:+ RemoteDesktop(const QVariantMap &host, const QString &display, QObject *parent = nullptr);+ ~RemoteDesktop() override;++ QString hostId() const { return m_host.value(QStringLiteral("id")).toString(); }+ QString name() const { return m_host.value(QStringLiteral("name")).toString(); }+ QString address() const { return m_host.value(QStringLiteral("address")).toString(); }+ QString user() const { return m_user; }+ QString state() const { return m_state; }+ bool everConnected() const { return m_everConnected; }+ int attempt() const { return m_attempt; }+ int attempts() const { return 5; }+ int latency() const { return m_latency; }+ QString endTitle() const { return m_endTitle; }+ QString endText() const { return m_endText; }+ QString display() const { return m_display; }+ void setDisplay(const QString &display);+ bool multiMonitor() const { return m_monitors.size() > 1; }+ QVariantList monitors() const { return m_monitors; }+ QSize desktopSize() const;+ bool clipboard() const { return m_clipboard; }+ void setClipboard(bool on);+ QVariantMap sharing() const { return m_sharing; }+ bool sharingPending() const { return m_sharingPending; }+ bool sendShortcuts() const { return m_sendShortcuts; }+ void setSendShortcuts(bool on);+ DesktopSession *session() const { return m_session; }+ QObject *sessionObject() const;++ // Begins connecting; a password from the keyring comes along if the+ // host keeps one there.+ void start(const QString &password);++ Q_INVOKABLE void answerCertificate(bool accept, bool remember);+ Q_INVOKABLE void signIn(const QString &user, const QString &password, bool save);+ Q_INVOKABLE void cancelSignIn();+ Q_INVOKABLE void tryNow();+ Q_INVOKABLE void stopTrying();+ Q_INVOKABLE void disconnectNow();+ // "ctrl-alt-del", "windows", "print", "alt-tab"+ Q_INVOKABLE void sendKeys(const QString &which);+ // A sharing switch from the toolbar, for when it reconnects.+ Q_INVOKABLE void setSharing(const QString &key, bool on);+ // The screen as it ends, for the start page (kept on this PC only).+ void saveScreen();++Q_SIGNALS:+ void stateChanged();+ void latencyChanged();+ void displayChanged();+ void desktopSizeChanged();+ void sharingChanged();+ void sendShortcutsChanged();+ void certificateNeeded(const QVariantMap &info, bool changed);+ void credentialsNeeded(const QString &user, const QString &reason);+ // Signed in: the window opens.+ void opened();+ // Ended after being open, by the other end: a notification if the+ // window isn't in front.+ void lost();+ // The wrong password: ask again, on a fresh connection.+ void retryWanted(const QString &user);++private:+ QList<QByteArray> arguments(const QString &password) const;+ void finished(const QString &code, bool authFailed);+ void setState(const QString &state);++ QVariantMap m_host;+ QString m_display;+ QVariantList m_monitors;+ QString m_user;+ QString m_state = QStringLiteral("connecting");+ bool m_everConnected = false;+ bool m_savePassword = false;+ QString m_pendingPassword;+ int m_attempt = 0;+ int m_latency = 0;+ QString m_endTitle;+ QString m_endText;+ bool m_clipboard = true;+ QVariantMap m_sharing;+ bool m_sharingPending = false;+ bool m_sendShortcuts = false;+ DesktopSession *m_session = nullptr;+ QTimer m_latencyTimer;+ QImage m_lastFrame;+};++// Starting desktops from QML, and the ones open now.+class Desktops : public QObject+{+ Q_OBJECT+ QML_ELEMENT+ QML_SINGLETON++public:+ static Desktops *instance();+ static Desktops *create(QQmlEngine *, QJSEngine *);++ // display: "window", "full", "all", or empty for the host's own choice.+ Q_INVOKABLE RemoteDesktop *start(const QVariantMap &host, const QString &display);+ // A window of a new size: Windows lays the desktop out for it when it+ // can (dynamic resolution), otherwise the picture is scaled.+ Q_INVOKABLE bool resizeTo(RemoteDesktop *desktop, const QSize &physical, double scale);+ // From Windows mode: FreeRDP's arguments as they come for xfreerdp3.+ RemoteDesktop *startWithArguments(const QString &title, const QList<QByteArray> &args);++ // Ends every session cleanly (on quit).+ void closeAll();++Q_SIGNALS:+ // A RemoteDesktop to show questions for and then a window.+ void started(RemoteDesktop *desktop);++private:+ explicit Desktops(QObject *parent = nullptr);+ QList<QPointer<RemoteDesktop>> m_open;+};diff --git a/packages/wildos-remote/src/secrets.cpp b/packages/wildos-remote/src/secrets.cppnew file mode 100644index 0000000..2cf4c0e--- /dev/null+++ b/packages/wildos-remote/src/secrets.cpp@@ -0,0 +1,78 @@+#include "secrets.h"++#include <qt6keychain/keychain.h>++namespace+{+const QString service = QStringLiteral("Wild OS Remote");+}++Secrets *Secrets::instance()+{+ static Secrets *secrets = new Secrets;+ return secrets;+}++Secrets *Secrets::create(QQmlEngine *, QJSEngine *)+{+ Secrets *secrets = instance();+ QJSEngine::setObjectOwnership(secrets, QJSEngine::CppOwnership);+ return secrets;+}++Secrets::Secrets(QObject *parent)+ : QObject(parent)+{+}++void Secrets::read(const QString &key, const std::function<void(const QString &, bool)> &done)+{+ auto *job = new QKeychain::ReadPasswordJob(service, this);+ job->setKey(key);+ connect(job, &QKeychain::Job::finished, this, [job, done]() {+ const bool found = job->error() == QKeychain::NoError;+ done(found ? job->textData() : QString(), found);+ });+ job->start();+}++void Secrets::write(const QString &key, const QString &secret, const std::function<void(bool)> &done)+{+ auto *job = new QKeychain::WritePasswordJob(service, this);+ job->setKey(key);+ job->setTextData(secret);+ connect(job, &QKeychain::Job::finished, this, [job, done]() {+ if (job->error() != QKeychain::NoError) {+ qWarning("wildos-remote: the keyring did not take a secret: %s", qPrintable(job->errorString()));+ }+ if (done) {+ done(job->error() == QKeychain::NoError);+ }+ });+ job->start();+}++void Secrets::remove(const QString &key)+{+ auto *job = new QKeychain::DeletePasswordJob(service, this);+ job->setKey(key);+ job->start();+}++void Secrets::read(const QString &key, const QJSValue &callback)+{+ read(key, [callback](const QString &secret, bool found) mutable {+ if (callback.isCallable()) {+ callback.call({QJSValue(secret), QJSValue(found)});+ }+ });+}++void Secrets::write(const QString &key, const QString &secret, const QJSValue &callback)+{+ write(key, secret, [callback](bool ok) mutable {+ if (callback.isCallable()) {+ callback.call({QJSValue(ok)});+ }+ });+}diff --git a/packages/wildos-remote/src/secrets.h b/packages/wildos-remote/src/secrets.hnew file mode 100644index 0000000..2025178--- /dev/null+++ b/packages/wildos-remote/src/secrets.h@@ -0,0 +1,38 @@+#pragma once++#include <QJSValue>+#include <QObject>+#include <QQmlEngine>++#include <functional>++// Passwords and key passphrases in the keyring (KWallet through+// QtKeychain), only ever when the person ticks "Save in my keyring". Nothing+// here writes a secret to a file: when the keyring cannot take it, saving+// fails and Remote asks again next time.+class Secrets : public QObject+{+ Q_OBJECT+ QML_ELEMENT+ QML_SINGLETON++public:+ static Secrets *instance();+ static Secrets *create(QQmlEngine *, QJSEngine *);++ void read(const QString &key, const std::function<void(const QString &secret, bool found)> &done);+ void write(const QString &key, const QString &secret, const std::function<void(bool ok)> &done = {});+ Q_INVOKABLE void remove(const QString &key);++ // From QML: callback(secret, found) and callback(ok).+ Q_INVOKABLE void read(const QString &key, const QJSValue &callback);+ Q_INVOKABLE void write(const QString &key, const QString &secret, const QJSValue &callback);++ // The keyring names for a desktop host's password and a key's+ // passphrase.+ static QString hostKey(const QString &hostId) { return QStringLiteral("desktop:") + hostId; }+ static QString passphraseKey(const QString &fingerprint) { return QStringLiteral("key:") + fingerprint; }++private:+ explicit Secrets(QObject *parent = nullptr);+};diff --git a/packages/wildos-remote/src/sessionwindow.cpp b/packages/wildos-remote/src/sessionwindow.cppnew file mode 100644index 0000000..104fc6d--- /dev/null+++ b/packages/wildos-remote/src/sessionwindow.cpp@@ -0,0 +1,622 @@+#include "sessionwindow.h"+#include "filebrowser.h"+#include "hosts.h"+#include "keychain.h"+#include "paths.h"+#include "terminalview.h"+#include "windowframe.h"++#include <QElapsedTimer>+#include <QGuiApplication>+#include <QPainter>+#include <QPainterPath>+#include <QQmlContext>+#include <QQmlEngine>+#include <QQuickItem>+#include <QQuickWidget>+#include <QShortcut>+#include <QSplitter>+#include <QStackedWidget>+#include <QTcpSocket>+#include <QTimer>+#include <QVBoxLayout>+#include <QWindow>++namespace+{+constexpr int inset = 6;+constexpr int grip = 5;+const QColor terminalBackground(11, 15, 28);+}++SessionTab::SessionTab(const QVariantMap &host, QObject *parent)+ : QObject(parent)+ , m_local(host.isEmpty())+ , m_hostId(host.value(QStringLiteral("id")).toString())+ , m_host(host)+{+ m_page = new QWidget;+ m_page->setAttribute(Qt::WA_TranslucentBackground);+ auto *layout = new QVBoxLayout(m_page);+ layout->setContentsMargins(0, 0, 0, 0);+ m_splitter = new QSplitter(Qt::Horizontal, m_page);+ m_splitter->setHandleWidth(2);+ m_splitter->setStyleSheet(QStringLiteral("QSplitter::handle { background: rgba(255,255,255,0.08); }"));+ layout->addWidget(m_splitter);++ if (m_local) {+ m_title = QStringLiteral("Local");+ m_colour = QStringLiteral("#8b93a8");+ m_userHost = qEnvironmentVariable("USER") + QLatin1Char('@') + QSysInfo::machineHostName();+ m_auth = QStringLiteral("This PC");+ } else {+ Hosts *hosts = Hosts::instance();+ m_title = host.value(QStringLiteral("name")).toString();+ const QVariantMap ssh = host.value(QStringLiteral("ssh")).toMap();+ m_colour = ssh.value(QStringLiteral("colour")).toString();+ const QString user = host.value(QStringLiteral("user")).toString();+ m_userHost = (user.isEmpty() ? QString() : user + QLatin1Char('@')) + hosts->hostName(host);+ const QString identity = ssh.value(QStringLiteral("identity")).toString();+ m_auth = identity.isEmpty() ? QStringLiteral("SSH") : QStringLiteral("SSH, key “%1”").arg(Keychain::instance()->label(identity));+ for (const QVariant &v : ssh.value(QStringLiteral("forwards")).toList()) {+ const QVariantMap f = v.toMap();+ const QString target = f.value(QStringLiteral("remoteHost")).toString();+ m_forwards.append(QStringLiteral("localhost:%1 to %2").arg(f.value(QStringLiteral("localPort")).toInt())+ .arg(target.isEmpty() || target == QLatin1String("localhost") ? m_title : target));+ }+ m_files = new FileBrowser(m_title, this);+ measureLatency();+ }+ makeView(true);+}++SessionTab::~SessionTab()+{+ delete m_page;+}++QStringList SessionTab::sshArgs(bool withForwards) const+{+ Hosts *hosts = Hosts::instance();+ const QVariantMap ssh = m_host.value(QStringLiteral("ssh")).toMap();+ QStringList args{+ // Every tab, split and file view to the same host shares one+ // connection: one sign-in, and the file view needs no other.+ QStringLiteral("-o"), QStringLiteral("ControlMaster=auto"),+ QStringLiteral("-o"), QStringLiteral("ControlPath=") + Paths::runtime() + QStringLiteral("/cm-%C"),+ QStringLiteral("-o"), QStringLiteral("ControlPersist=no"),+ // Only a key already in known_hosts: Remote asked about anything+ // new before this ran, and a changed key is never taken.+ QStringLiteral("-o"), QStringLiteral("StrictHostKeyChecking=yes"),+ QStringLiteral("-o"), QStringLiteral("UpdateHostKeys=no"),+ QStringLiteral("-o"), QStringLiteral("ServerAliveInterval=30"),+ QStringLiteral("-p"), QString::number(hosts->port(m_host)),+ };+ const QString identity = ssh.value(QStringLiteral("identity")).toString();+ if (!identity.isEmpty()) {+ args << QStringLiteral("-i") << identity << QStringLiteral("-o") << QStringLiteral("IdentitiesOnly=yes");+ }+ if (withForwards) {+ for (const QVariant &v : ssh.value(QStringLiteral("forwards")).toList()) {+ const QVariantMap f = v.toMap();+ QString target = f.value(QStringLiteral("remoteHost")).toString();+ if (target.isEmpty()) {+ target = QStringLiteral("localhost");+ }+ // Bound to this PC only, never to the network.+ args << QStringLiteral("-L")+ << QStringLiteral("127.0.0.1:%1:%2:%3").arg(f.value(QStringLiteral("localPort")).toInt()).arg(target).arg(f.value(QStringLiteral("remotePort")).toInt());+ }+ }+ const QString user = m_host.value(QStringLiteral("user")).toString();+ if (!user.isEmpty()) {+ args << QStringLiteral("-l") << user;+ }+ args << QStringLiteral("--") << hosts->hostName(m_host);+ return args;+}++TerminalView *SessionTab::makeView(bool first)+{+ TerminalView *view;+ if (m_local) {+ QString shell = qEnvironmentVariable("SHELL");+ if (shell.isEmpty()) {+ shell = QStringLiteral("/bin/bash");+ }+ view = new TerminalView(shell, {}, QStringLiteral("local"));+ } else if (const QStringList exec = m_host.value(QStringLiteral("exec")).toStringList(); !exec.isEmpty()) {+ view = new TerminalView(exec.first(), exec.mid(1), QString());+ } else {+ view = new TerminalView(QStringLiteral("ssh"), sshArgs(first), m_hostId);+ }+ m_splitter->addWidget(view);+ m_views.append(view);+ m_current = view;+ connect(view, &TerminalView::suggestionsChanged, this, &SessionTab::suggestionsChanged);+ connect(view, &TerminalView::focused, this, [this, view] {+ m_current = view;+ Q_EMIT suggestionsChanged();+ });+ connect(view, &TerminalView::exitedChanged, this, [this, view] {+ // A second pane that ends just goes; the tab ends with its last.+ if (m_views.size() > 1) {+ m_views.removeOne(view);+ view->deleteLater();+ m_current = m_views.constFirst();+ }+ Q_EMIT changed();+ Q_EMIT endedChanged();+ });+ return view;+}++TerminalView *SessionTab::current() const+{+ return m_current ? m_current.data() : (m_views.isEmpty() ? nullptr : m_views.constFirst());+}++QString SessionTab::size() const+{+ if (TerminalView *v = current()) {+ return QStringLiteral("%1 × %2").arg(v->screenColumnsCount()).arg(v->screenLinesCount());+ }+ return {};+}++bool SessionTab::ended() const+{+ return !m_views.isEmpty() && m_views.constFirst()->exited() && m_views.size() == 1;+}++QVariantList SessionTab::suggestions() const+{+ TerminalView *v = current();+ return v ? v->suggestions() : QVariantList();+}++int SessionTab::selected() const+{+ TerminalView *v = current();+ return v ? v->selected() : 0;+}++QRect SessionTab::cursor() const+{+ TerminalView *v = current();+ if (!v) {+ return {};+ }+ const QRect r = v->cursorRect();+ // In the page's coordinates, which the window places in the terminal area.+ return QRect(v->mapTo(m_page, r.topLeft()), r.size());+}++void SessionTab::reconnect()+{+ for (TerminalView *v : std::as_const(m_views)) {+ v->deleteLater();+ }+ m_views.clear();+ makeView(true);+ focusTerminal();+ if (m_files && m_filesOpen) {+ m_files->retry();+ }+ Q_EMIT changed();+}++void SessionTab::setFilesOpen(bool open)+{+ if (m_local || open == m_filesOpen) {+ return;+ }+ m_filesOpen = open;+ if (open && !m_files->remoteReady()) {+ m_files->connectTo(sshArgs(false));+ }+ m_splitter->setVisible(!open);+ Q_EMIT changed();+}++void SessionTab::toggleSplit()+{+ if (m_views.size() > 1) {+ TerminalView *last = m_views.takeLast();+ last->deleteLater();+ m_current = m_views.constFirst();+ } else {+ makeView(false);+ }+ focusTerminal();+ Q_EMIT changed();+}++void SessionTab::accept(int index)+{+ if (TerminalView *v = current()) {+ v->accept(index);+ }+}++void SessionTab::dismiss()+{+ if (TerminalView *v = current()) {+ v->dismiss();+ }+}++void SessionTab::run(const QString &command)+{+ if (TerminalView *v = current()) {+ v->run(command);+ v->setFocus();+ }+}++void SessionTab::focusTerminal()+{+ if (TerminalView *v = current()) {+ v->setFocus();+ }+}++void SessionTab::measureLatency()+{+ // One TCP handshake, timed, when the tab opens: the round trip to the+ // server, without keeping anything open.+ auto *socket = new QTcpSocket(this);+ auto *clock = new QElapsedTimer;+ clock->start();+ // Looking the name up isn't the round trip.+ connect(socket, &QTcpSocket::hostFound, this, [clock] {+ clock->restart();+ });+ connect(socket, &QTcpSocket::connected, this, [this, socket, clock] {+ m_latency = QStringLiteral("%1 ms").arg(std::max<qint64>(1, clock->elapsed()));+ delete clock;+ socket->abort();+ socket->deleteLater();+ Q_EMIT changed();+ });+ connect(socket, &QTcpSocket::errorOccurred, this, [socket, clock] {+ delete clock;+ socket->deleteLater();+ });+ socket->connectToHost(Hosts::instance()->hostName(m_host), quint16(Hosts::instance()->port(m_host)));+}++SessionWindow *SessionWindow::instance(bool create)+{+ static QPointer<SessionWindow> window;+ if (!window && create) {+ window = new SessionWindow;+ }+ return window;+}++SessionWindow::SessionWindow()+ : QWidget(nullptr)+{+ setAttribute(Qt::WA_TranslucentBackground);+ setAttribute(Qt::WA_DeleteOnClose);+ setWindowFlags(Qt::Window | Qt::FramelessWindowHint);+ setWindowTitle(QStringLiteral("Remote"));+ setWindowIcon(QIcon::fromTheme(QStringLiteral("org.wildos.remote")));+ setMinimumSize(640, 360);++ m_stack = new QStackedWidget(this);+ m_stack->setAttribute(Qt::WA_TranslucentBackground);+ m_stack->setAutoFillBackground(false);++ m_chrome = new QQuickWidget(this);+ m_chrome->setAttribute(Qt::WA_AlwaysStackOnTop);+ m_chrome->setAttribute(Qt::WA_TranslucentBackground);+ m_chrome->setClearColor(Qt::transparent);+ m_chrome->setResizeMode(QQuickWidget::SizeRootObjectToView);+ m_chrome->setFocusPolicy(Qt::ClickFocus);+ m_chrome->rootContext()->setContextProperty(QStringLiteral("host"), this);+ m_chrome->setSource(QUrl(QStringLiteral("qrc:/qt/qml/WildOS/Remote/SessionChrome.qml")));+ if (m_chrome->status() == QQuickWidget::Error) {+ for (const auto &e : m_chrome->errors()) {+ qWarning().noquote() << e.toString();+ }+ }+ m_chrome->raise();++ auto add = [this](const QString &key, auto slot) {+ auto *s = new QShortcut(QKeySequence(key), this);+ s->setContext(Qt::WindowShortcut);+ connect(s, &QShortcut::activated, this, slot);+ };+ add(QStringLiteral("Ctrl+Shift+T"), [this] { openLocal(); });+ add(QStringLiteral("Ctrl+Shift+W"), [this] { closeTab(m_current); });+ add(QStringLiteral("Ctrl+Tab"), [this] { setCurrentIndex((m_current + 1) % std::max<qsizetype>(1, m_tabs.size())); });+ add(QStringLiteral("Ctrl+Shift+Tab"), [this] { setCurrentIndex((m_current + m_tabs.size() - 1) % std::max<qsizetype>(1, m_tabs.size())); });++ resize(1384, 802);+}++SessionWindow::~SessionWindow()+{+ for (SessionTab *t : std::as_const(m_tabs)) {+ disconnect(t, nullptr, this, nullptr);+ }+ delete m_chrome;+ m_chrome = nullptr;+ qDeleteAll(m_tabs);+}++void SessionWindow::showEvent(QShowEvent *event)+{+ QWidget::showEvent(event);+ if (!m_frame && windowHandle()) {+ m_frame = new WindowFrame(windowHandle(), this);+ updateBlur();+ }+}++QList<QObject *> SessionWindow::tabs() const+{+ QList<QObject *> list;+ for (SessionTab *t : m_tabs) {+ list.append(t);+ }+ return list;+}++SessionTab *SessionWindow::currentTab() const+{+ return m_current >= 0 && m_current < m_tabs.size() ? m_tabs[m_current] : nullptr;+}++int SessionWindow::terminalTabCount() const+{+ int n = 0;+ for (SessionTab *t : m_tabs) {+ n += t->ended() ? 0 : 1;+ }+ return n;+}++void SessionWindow::setCurrentIndex(int index)+{+ if (index < 0 || index >= m_tabs.size()) {+ return;+ }+ m_current = index;+ m_stack->setCurrentWidget(m_tabs[index]->page());+ setWindowTitle(m_tabs[index]->title() + QStringLiteral(", Remote"));+ Q_EMIT currentChanged();+ Q_EMIT layoutChanged();+ updateMask();+ m_tabs[index]->focusTerminal();+}++void SessionWindow::open(const QVariantMap &host)+{+ auto *tab = new SessionTab(host, this);+ m_stack->addWidget(tab->page());+ connect(tab, &SessionTab::changed, this, [this, tab] {+ if (tab == currentTab()) {+ updateMask();+ Q_EMIT layoutChanged();+ }+ });+ m_tabs.append(tab);+ Q_EMIT tabsChanged();+ setCurrentIndex(int(m_tabs.size()) - 1);+ layoutChildren();+ if (!isVisible()) {+ show();+ }+ raise();+ activateWindow();+}++void SessionWindow::openHost(const QString &hostId)+{+ const QVariantMap h = Hosts::instance()->host(hostId);+ if (!h.isEmpty()) {+ Q_EMIT homeRequested(hostId);+ }+}++void SessionWindow::openLocal()+{+ open({});+}++void SessionWindow::closeTab(int index)+{+ if (index < 0 || index >= m_tabs.size()) {+ return;+ }+ SessionTab *tab = m_tabs.takeAt(index);+ m_stack->removeWidget(tab->page());+ tab->deleteLater();+ Q_EMIT tabsChanged();+ if (m_tabs.isEmpty()) {+ m_current = -1;+ close();+ return;+ }+ setCurrentIndex(std::min(index, int(m_tabs.size()) - 1));+}++void SessionWindow::runEverywhere(const QString &command)+{+ for (SessionTab *t : std::as_const(m_tabs)) {+ if (!t->ended()) {+ t->run(command);+ }+ }+}++void SessionWindow::showHome()+{+ Q_EMIT homeRequested(QString());+}++void SessionWindow::editHost(const QString &hostId)+{+ Q_EMIT homeRequested(QStringLiteral("edit:") + hostId);+}++bool SessionWindow::maximised() const+{+ return windowState() & (Qt::WindowMaximized | Qt::WindowFullScreen);+}++bool SessionWindow::blurAvailable() const+{+ return m_frame && m_frame->blurAvailable();+}++void SessionWindow::setSnippetsOpen(bool open)+{+ if (open != m_snippetsOpen) {+ m_snippetsOpen = open;+ layoutChildren();+ Q_EMIT layoutChanged();+ }+}++void SessionWindow::setChromeFull(bool full)+{+ if (full != m_chromeFull) {+ m_chromeFull = full;+ updateMask();+ Q_EMIT layoutChanged();+ if (full) {+ m_chrome->setFocus();+ } else if (SessionTab *t = currentTab()) {+ t->focusTerminal();+ }+ }+}++void SessionWindow::setOverlay(const QRect &rect)+{+ if (rect != m_overlay) {+ m_overlay = rect;+ updateMask();+ }+}++QRect SessionWindow::terminalArea() const+{+ const int side = maximised() ? 0 : inset;+ const int right = m_snippetsOpen ? snippetsWidth : side;+ return QRect(side, titleHeight, width() - side - right, height() - titleHeight - statusHeight);+}++void SessionWindow::minimise()+{+ showMinimized();+}++void SessionWindow::toggleMaximised()+{+ maximised() ? showNormal() : showMaximized();+}++void SessionWindow::startMove()+{+ if (windowHandle()) {+ windowHandle()->startSystemMove();+ }+}++void SessionWindow::startResize(int edges)+{+ if (windowHandle()) {+ windowHandle()->startSystemResize(Qt::Edges(edges));+ }+}++void SessionWindow::closeWindow()+{+ close();+}++void SessionWindow::updateMask()+{+ if (!m_chrome) {+ return;+ }+ SessionTab *tab = currentTab();+ // Files are drawn by the layer, over where the terminal would be.+ if (m_chromeFull || (tab && (tab->filesOpen() || tab->ended()))) {+ m_chrome->clearMask();+ return;+ }+ QRegion region(rect());+ region -= terminalArea();+ if (m_overlay.isValid()) {+ region += m_overlay;+ }+ m_chrome->setMask(region);+}++void SessionWindow::updateBlur()+{+ if (!m_frame) {+ return;+ }+ const int r = maximised() ? 0 : radius;+ m_frame->setRadius(r);+ m_frame->setShadow(!maximised());+ m_frame->setBlurRegion(WindowFrame::roundedRegion(size(), r));+}++void SessionWindow::layoutChildren()+{+ m_chrome->setGeometry(rect());+ m_stack->setGeometry(terminalArea());+ // The terminal works out its columns and rows once it has its new size.+ if (SessionTab *t = currentTab()) {+ QTimer::singleShot(60, t, &SessionTab::changed);+ }+ updateMask();+ updateBlur();+ Q_EMIT layoutChanged();+}++void SessionWindow::resizeEvent(QResizeEvent *event)+{+ QWidget::resizeEvent(event);+ layoutChildren();+}++void SessionWindow::changeEvent(QEvent *event)+{+ QWidget::changeEvent(event);+ if (event->type() == QEvent::ActivationChange) {+ if (m_frame && isActiveWindow()) {+ m_frame->recheck();+ }+ Q_EMIT stateChanged();+ } else if (event->type() == QEvent::WindowStateChange) {+ layoutChildren();+ update();+ Q_EMIT stateChanged();+ }+}++void SessionWindow::paintEvent(QPaintEvent *)+{+ QPainter p(this);+ p.setCompositionMode(QPainter::CompositionMode_Source);+ p.fillRect(rect(), Qt::transparent);+ // The terminal's own colour under the gap around it, so the terminal+ // and the window edge read as one surface.+ p.setRenderHint(QPainter::Antialiasing);+ const qreal r = maximised() ? 0 : radius;+ QPainterPath path;+ path.addRoundedRect(QRectF(rect()), r, r);+ QPainterPath area;+ const QRect t = terminalArea();+ area.addRect(QRectF(0, t.top(), t.right() + 1, t.height()));+ p.fillPath(path.intersected(area), terminalBackground);+}diff --git a/packages/wildos-remote/src/sessionwindow.h b/packages/wildos-remote/src/sessionwindow.hnew file mode 100644index 0000000..b0ce968--- /dev/null+++ b/packages/wildos-remote/src/sessionwindow.h@@ -0,0 +1,190 @@+#pragma once++#include <QList>+#include <QPointer>+#include <QQmlEngine>+#include <QVariantList>+#include <QVariantMap>+#include <QWidget>++class FileBrowser;+class QQuickWidget;+class QSplitter;+class QStackedWidget;+class TerminalView;+class WindowFrame;++// One tab of the terminal window (RemoteTerminal.dc, RemoteFiles.dc): a+// host over SSH, or a shell on this PC. A host's tab can be split into two+// terminals and can show its files instead of its terminal.+class SessionTab : public QObject+{+ Q_OBJECT+ QML_ANONYMOUS++ Q_PROPERTY(QString title READ title CONSTANT)+ Q_PROPERTY(QString colour READ colour CONSTANT)+ Q_PROPERTY(bool local READ local CONSTANT)+ Q_PROPERTY(QString hostId READ hostId CONSTANT)+ Q_PROPERTY(QString userHost READ userHost CONSTANT)+ Q_PROPERTY(QString auth READ auth CONSTANT)+ Q_PROPERTY(QStringList forwards READ forwards CONSTANT)+ Q_PROPERTY(QString latency READ latency NOTIFY changed)+ Q_PROPERTY(QString size READ size NOTIFY changed)+ Q_PROPERTY(bool ended READ ended NOTIFY changed)+ Q_PROPERTY(bool filesOpen READ filesOpen NOTIFY changed)+ Q_PROPERTY(bool split READ split NOTIFY changed)+ Q_PROPERTY(FileBrowser *files READ files CONSTANT)+ Q_PROPERTY(QVariantList suggestions READ suggestions NOTIFY suggestionsChanged)+ Q_PROPERTY(int selected READ selected NOTIFY suggestionsChanged)+ Q_PROPERTY(QRect cursor READ cursor NOTIFY suggestionsChanged)++public:+ SessionTab(const QVariantMap &host, QObject *parent = nullptr);+ ~SessionTab() override;++ QString title() const { return m_title; }+ QString colour() const { return m_colour; }+ bool local() const { return m_local; }+ QString hostId() const { return m_hostId; }+ QString userHost() const { return m_userHost; }+ QString auth() const { return m_auth; }+ QStringList forwards() const { return m_forwards; }+ QString latency() const { return m_latency; }+ QString size() const;+ bool ended() const;+ bool filesOpen() const { return m_filesOpen; }+ bool split() const { return m_views.size() > 1; }+ FileBrowser *files() const { return m_files; }+ QVariantList suggestions() const;+ int selected() const;+ QRect cursor() const;++ QWidget *page() const { return m_page; }+ TerminalView *current() const;+ // The ssh arguments that reach this host, ending with the destination.+ QStringList sshArgs(bool withForwards) const;++ Q_INVOKABLE void reconnect();+ Q_INVOKABLE void setFilesOpen(bool open);+ Q_INVOKABLE void toggleSplit();+ Q_INVOKABLE void accept(int index);+ Q_INVOKABLE void dismiss();+ Q_INVOKABLE void run(const QString &command);+ Q_INVOKABLE void focusTerminal();++Q_SIGNALS:+ void changed();+ void suggestionsChanged();+ void endedChanged();++private:+ TerminalView *makeView(bool first);+ void measureLatency();++ QString m_title;+ QString m_colour;+ bool m_local = false;+ QString m_hostId;+ QVariantMap m_host;+ QString m_userHost;+ QString m_auth;+ QStringList m_forwards;+ QString m_latency;+ bool m_filesOpen = false;+ QWidget *m_page = nullptr;+ QSplitter *m_splitter = nullptr;+ QList<TerminalView *> m_views;+ QPointer<TerminalView> m_current;+ FileBrowser *m_files = nullptr;+};++// The terminal window: tabs of hosts in the title bar, the terminals+// (widgets) below, and everything else (tab bar, snippets, the status bar,+// files, menus and dialogs) as QML in a transparent layer over them, as in+// Wild OS Terminal. The layer takes the pointer only where it draws.+class SessionWindow : public QWidget+{+ Q_OBJECT+ QML_ANONYMOUS++ Q_PROPERTY(QList<QObject *> tabs READ tabs NOTIFY tabsChanged)+ Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentChanged)+ Q_PROPERTY(SessionTab *currentTab READ currentTab NOTIFY currentChanged)+ Q_PROPERTY(bool maximised READ maximised NOTIFY stateChanged)+ Q_PROPERTY(bool windowActive READ windowActive NOTIFY stateChanged)+ Q_PROPERTY(bool blurAvailable READ blurAvailable NOTIFY stateChanged)+ Q_PROPERTY(bool snippetsOpen READ snippetsOpen WRITE setSnippetsOpen NOTIFY layoutChanged)+ Q_PROPERTY(bool chromeFull READ chromeFull WRITE setChromeFull NOTIFY layoutChanged)+ Q_PROPERTY(QRect overlay READ overlay WRITE setOverlay NOTIFY layoutChanged)+ Q_PROPERTY(QRect terminalArea READ terminalArea NOTIFY layoutChanged)++public:+ static SessionWindow *instance(bool create = true);+ ~SessionWindow() override;++ static constexpr int titleHeight = 46;+ static constexpr int statusHeight = 32;+ static constexpr int snippetsWidth = 332;+ static constexpr int radius = 14;++ QList<QObject *> tabs() const;+ int currentIndex() const { return m_current; }+ void setCurrentIndex(int index);+ SessionTab *currentTab() const;+ bool maximised() const;+ bool windowActive() const { return isActiveWindow(); }+ bool blurAvailable() const;+ bool snippetsOpen() const { return m_snippetsOpen; }+ void setSnippetsOpen(bool open);+ bool chromeFull() const { return m_chromeFull; }+ void setChromeFull(bool full);+ QRect overlay() const { return m_overlay; }+ void setOverlay(const QRect &rect);+ QRect terminalArea() const;++ // Opens a host (or this PC, for an empty map) in a new tab.+ void open(const QVariantMap &host);++ Q_INVOKABLE void openHost(const QString &hostId);+ Q_INVOKABLE void openLocal();+ Q_INVOKABLE void closeTab(int index);+ Q_INVOKABLE void minimise();+ Q_INVOKABLE void toggleMaximised();+ Q_INVOKABLE void startMove();+ Q_INVOKABLE void startResize(int edges);+ Q_INVOKABLE void closeWindow();+ Q_INVOKABLE void showHome();+ Q_INVOKABLE void editHost(const QString &hostId);+ // Runs a snippet in every terminal tab.+ Q_INVOKABLE void runEverywhere(const QString &command);+ Q_INVOKABLE int terminalTabCount() const;++Q_SIGNALS:+ void tabsChanged();+ void currentChanged();+ void stateChanged();+ void layoutChanged();+ void homeRequested(const QString &hostId);++protected:+ void paintEvent(QPaintEvent *event) override;+ void resizeEvent(QResizeEvent *event) override;+ void changeEvent(QEvent *event) override;+ void showEvent(QShowEvent *event) override;++private:+ SessionWindow();+ void layoutChildren();+ void updateMask();+ void updateBlur();++ QQuickWidget *m_chrome = nullptr;+ QStackedWidget *m_stack = nullptr;+ WindowFrame *m_frame = nullptr;+ QList<SessionTab *> m_tabs;+ int m_current = -1;+ bool m_snippetsOpen = true;+ bool m_chromeFull = false;+ QRect m_overlay;+};diff --git a/packages/wildos-remote/src/sftp.cpp b/packages/wildos-remote/src/sftp.cppnew file mode 100644index 0000000..605aed3--- /dev/null+++ b/packages/wildos-remote/src/sftp.cpp@@ -0,0 +1,585 @@+#include "sftp.h"++#include <QFile>+#include <QSharedPointer>+#include <QtEndian>++namespace+{+enum : quint8 {+ FxpInit = 1,+ FxpVersion = 2,+ FxpOpen = 3,+ FxpClose = 4,+ FxpRead = 5,+ FxpWrite = 6,+ FxpLstat = 7,+ FxpOpendir = 11,+ FxpReaddir = 12,+ FxpRemove = 13,+ FxpMkdir = 14,+ FxpRmdir = 15,+ FxpRealpath = 16,+ FxpStat = 17,+ FxpRename = 18,+ FxpStatus = 101,+ FxpHandle = 102,+ FxpData = 103,+ FxpName = 104,+ FxpAttrs = 105,+};++enum : quint32 {+ FlagRead = 0x01,+ FlagWrite = 0x02,+ FlagCreate = 0x08,+ FlagTruncate = 0x10,+};++enum : quint32 {+ AttrSize = 0x1,+ AttrUidGid = 0x2,+ AttrPermissions = 0x4,+ AttrTimes = 0x8,+ AttrExtended = 0x80000000,+};++// How much is read or written per request, and how many requests are in+// flight at once: enough to keep a link busy without a reply per chunk.+constexpr quint32 chunk = 32 * 1024;+constexpr int window = 16;++void putU32(QByteArray &b, quint32 v)+{+ char d[4];+ qToBigEndian(v, d);+ b.append(d, 4);+}++void putU64(QByteArray &b, quint64 v)+{+ char d[8];+ qToBigEndian(v, d);+ b.append(d, 8);+}++void putString(QByteArray &b, const QByteArray &s)+{+ putU32(b, quint32(s.size()));+ b.append(s);+}++struct Reader {+ const QByteArray &data;+ int at = 0;+ bool ok = true;++ quint32 u32()+ {+ if (at + 4 > data.size()) {+ ok = false;+ return 0;+ }+ const quint32 v = qFromBigEndian<quint32>(data.constData() + at);+ at += 4;+ return v;+ }+ quint64 u64()+ {+ if (at + 8 > data.size()) {+ ok = false;+ return 0;+ }+ const quint64 v = qFromBigEndian<quint64>(data.constData() + at);+ at += 8;+ return v;+ }+ QByteArray string()+ {+ const quint32 n = u32();+ if (!ok || at + int(n) > data.size()) {+ ok = false;+ return {};+ }+ const QByteArray s = data.mid(at, int(n));+ at += int(n);+ return s;+ }+ Sftp::Entry attrs()+ {+ Sftp::Entry e;+ const quint32 flags = u32();+ if (flags & AttrSize) {+ e.size = qint64(u64());+ }+ if (flags & AttrUidGid) {+ u32();+ u32();+ }+ if (flags & AttrPermissions) {+ e.permissions = u32();+ e.dir = (e.permissions & 0170000) == 0040000;+ e.link = (e.permissions & 0170000) == 0120000;+ }+ if (flags & AttrTimes) {+ u32();+ e.mtime = qint64(u32());+ }+ if (flags & AttrExtended) {+ const quint32 n = u32();+ for (quint32 i = 0; i < n && ok; ++i) {+ string();+ string();+ }+ }+ return e;+ }+};++QByteArray pathBytes(const QString &path)+{+ return path.toUtf8();+}+}++Sftp::Sftp(QObject *parent)+ : QObject(parent)+{+}++Sftp::~Sftp()+{+ stop();+}++void Sftp::start(const QStringList &sshArgs)+{+ stop();+ m_process = new QProcess(this);+ m_process->setProgram(QStringLiteral("ssh"));+ QStringList args = sshArgs;+ // Never a prompt: the terminal's connection is used, or nothing.+ args.prepend(QStringLiteral("BatchMode=yes"));+ args.prepend(QStringLiteral("-o"));+ // -s is an option, so it goes before the destination (the last of+ // sshArgs, after its "--"); the subsystem's name comes after it, where+ // a command would.+ const qsizetype end = args.lastIndexOf(QStringLiteral("--"));+ args.insert(end >= 0 ? end : args.size() - 1, QStringLiteral("-s"));+ args.append(QStringLiteral("sftp"));+ m_process->setArguments(args);+ connect(m_process, &QProcess::readyReadStandardOutput, this, &Sftp::readyRead);+ connect(m_process, &QProcess::readyReadStandardError, this, [this] {+ m_stderr += QString::fromUtf8(m_process->readAllStandardError());+ });+ connect(m_process, &QProcess::finished, this, [this](int, QProcess::ExitStatus) {+ const bool was = m_ready;+ m_ready = false;+ const auto pending = std::exchange(m_pending, {});+ for (const Reply &r : pending) {+ QByteArray status;+ putU32(status, 4);+ putString(status, "The connection to the server ended");+ putString(status, "");+ r(FxpStatus, status);+ }+ if (was) {+ Q_EMIT readyChanged();+ }+ Q_EMIT failed(m_stderr.trimmed().isEmpty() ? QStringLiteral("The file connection ended.") : m_stderr.trimmed());+ });+ m_process->start();+ QByteArray init;+ init.append(char(FxpInit));+ putU32(init, 3);+ QByteArray framed;+ putU32(framed, quint32(init.size()));+ framed.append(init);+ m_process->write(framed);+}++void Sftp::stop()+{+ if (!m_process) {+ return;+ }+ m_process->disconnect(this);+ m_process->closeWriteChannel();+ if (!m_process->waitForFinished(500)) {+ m_process->kill();+ m_process->waitForFinished(500);+ }+ m_process->deleteLater();+ m_process = nullptr;+ m_pending.clear();+ m_buffer.clear();+ if (m_ready) {+ m_ready = false;+ Q_EMIT readyChanged();+ }+}++void Sftp::send(quint8 type, const QByteArray &payload, const Reply &reply)+{+ if (!m_process || m_process->state() != QProcess::Running) {+ QByteArray status;+ putU32(status, 4);+ putString(status, "Not connected");+ putString(status, "");+ reply(FxpStatus, status);+ return;+ }+ const quint32 id = m_nextId++;+ QByteArray body;+ body.append(char(type));+ putU32(body, id);+ body.append(payload);+ QByteArray framed;+ putU32(framed, quint32(body.size()));+ framed.append(body);+ m_pending.insert(id, reply);+ m_process->write(framed);+}++void Sftp::readyRead()+{+ m_buffer += m_process->readAllStandardOutput();+ while (m_buffer.size() >= 4) {+ const quint32 len = qFromBigEndian<quint32>(m_buffer.constData());+ if (len > 256 * 1024 * 1024) {+ m_process->kill();+ return;+ }+ if (m_buffer.size() < int(len) + 4) {+ return;+ }+ const QByteArray p = m_buffer.mid(4, int(len));+ m_buffer.remove(0, int(len) + 4);+ packet(p);+ }+}++void Sftp::packet(const QByteArray &data)+{+ if (data.isEmpty()) {+ return;+ }+ const quint8 type = quint8(data.at(0));+ if (type == FxpVersion) {+ m_ready = true;+ Q_EMIT readyChanged();+ return;+ }+ if (data.size() < 5) {+ return;+ }+ const quint32 id = qFromBigEndian<quint32>(data.constData() + 1);+ const Reply reply = m_pending.take(id);+ if (reply) {+ reply(type, data.mid(5));+ }+}++QString Sftp::statusText(const QByteArray &body)+{+ Reader r{body};+ const quint32 code = r.u32();+ const QString message = QString::fromUtf8(r.string());+ switch (code) {+ case 0: return {};+ case 2: return QStringLiteral("That file or folder isn't there any more.");+ case 3: return QStringLiteral("The server doesn't allow that here.");+ default: return message.isEmpty() ? QStringLiteral("The server couldn't do that.") : message;+ }+}++void Sftp::realPath(const QString &path, const std::function<void(const QString &, const QString &)> &done)+{+ QByteArray p;+ putString(p, pathBytes(path));+ send(FxpRealpath, p, [done](quint8 type, const QByteArray &body) {+ if (type == FxpName) {+ Reader r{body};+ if (r.u32() >= 1) {+ done(QString::fromUtf8(r.string()), {});+ return;+ }+ }+ done({}, type == FxpStatus ? statusText(body) : QStringLiteral("Unexpected answer"));+ });+}++void Sftp::stat(const QString &path, const std::function<void(const Entry &, const QString &)> &done)+{+ QByteArray p;+ putString(p, pathBytes(path));+ send(FxpStat, p, [done, path](quint8 type, const QByteArray &body) {+ if (type == FxpAttrs) {+ Reader r{body};+ Entry e = r.attrs();+ e.name = path.section(QLatin1Char('/'), -1);+ done(e, {});+ return;+ }+ done({}, type == FxpStatus ? statusText(body) : QStringLiteral("Unexpected answer"));+ });+}++void Sftp::list(const QString &path, const Listed &done)+{+ QByteArray p;+ putString(p, pathBytes(path));+ send(FxpOpendir, p, [this, done](quint8 type, const QByteArray &body) {+ if (type != FxpHandle) {+ done({}, type == FxpStatus ? statusText(body) : QStringLiteral("Unexpected answer"));+ return;+ }+ Reader r{body};+ const QByteArray handle = r.string();+ auto entries = QSharedPointer<QList<Entry>>::create();+ auto next = QSharedPointer<std::function<void()>>::create();+ *next = [this, handle, entries, next, done]() {+ QByteArray q;+ putString(q, handle);+ send(FxpReaddir, q, [this, handle, entries, next, done](quint8 type, const QByteArray &body) {+ if (type == FxpName) {+ Reader r{body};+ const quint32 n = r.u32();+ for (quint32 i = 0; i < n && r.ok; ++i) {+ const QString name = QString::fromUtf8(r.string());+ r.string();+ Entry e = r.attrs();+ e.name = name;+ if (name != QLatin1String(".") && name != QLatin1String("..")) {+ entries->append(e);+ }+ }+ (*next)();+ return;+ }+ closeHandle(handle);+ // End of the folder is a status of EOF (1).+ Reader r{body};+ const quint32 code = type == FxpStatus ? r.u32() : 4;+ done(*entries, code == 1 ? QString() : statusText(body));+ // Breaks the cycle between the request and itself.+ *next = nullptr;+ });+ };+ (*next)();+ });+}++void Sftp::mkdir(const QString &path, const Done &done)+{+ QByteArray p;+ putString(p, pathBytes(path));+ putU32(p, 0);+ send(FxpMkdir, p, [done](quint8 type, const QByteArray &body) {+ done(type == FxpStatus ? statusText(body) : QStringLiteral("Unexpected answer"));+ });+}++void Sftp::remove(const QString &path, const Done &done)+{+ QByteArray p;+ putString(p, pathBytes(path));+ send(FxpRemove, p, [done](quint8 type, const QByteArray &body) {+ done(type == FxpStatus ? statusText(body) : QStringLiteral("Unexpected answer"));+ });+}++void Sftp::rmdir(const QString &path, const Done &done)+{+ QByteArray p;+ putString(p, pathBytes(path));+ send(FxpRmdir, p, [done](quint8 type, const QByteArray &body) {+ done(type == FxpStatus ? statusText(body) : QStringLiteral("Unexpected answer"));+ });+}++void Sftp::rename(const QString &from, const QString &to, const Done &done)+{+ QByteArray p;+ putString(p, pathBytes(from));+ putString(p, pathBytes(to));+ send(FxpRename, p, [done](quint8 type, const QByteArray &body) {+ done(type == FxpStatus ? statusText(body) : QStringLiteral("Unexpected answer"));+ });+}++void Sftp::openHandle(const QString &path, quint32 flags, const std::function<void(const QByteArray &, const QString &)> &done)+{+ QByteArray p;+ putString(p, pathBytes(path));+ putU32(p, flags);+ if (flags & FlagCreate) {+ // rw-r--r--, the usual for a new file; the server's umask applies.+ putU32(p, AttrPermissions);+ putU32(p, 0644);+ } else {+ putU32(p, 0);+ }+ send(FxpOpen, p, [done](quint8 type, const QByteArray &body) {+ if (type == FxpHandle) {+ Reader r{body};+ done(r.string(), {});+ return;+ }+ done({}, type == FxpStatus ? statusText(body) : QStringLiteral("Unexpected answer"));+ });+}++void Sftp::closeHandle(const QByteArray &handle)+{+ QByteArray p;+ putString(p, handle);+ send(FxpClose, p, [](quint8, const QByteArray &) {});+}++void Sftp::upload(const QString &local, const QString &remote, const Progress &progress, const Done &done)+{+ auto file = QSharedPointer<QFile>::create(local);+ if (!file->open(QIODevice::ReadOnly)) {+ done(QStringLiteral("%1 couldn't be read.").arg(local.section(QLatin1Char('/'), -1)));+ return;+ }+ openHandle(remote, FlagWrite | FlagCreate | FlagTruncate, [this, file, progress, done](const QByteArray &handle, const QString &error) {+ if (!error.isEmpty()) {+ done(error);+ return;+ }+ struct State {+ quint64 offset = 0;+ qint64 acknowledged = 0;+ int inFlight = 0;+ bool failed = false;+ bool finished = false;+ };+ auto state = QSharedPointer<State>::create();+ auto pump = QSharedPointer<std::function<void()>>::create();+ *pump = [this, file, handle, state, pump, progress, done]() {+ while (!state->failed && state->inFlight < window && !file->atEnd()) {+ const QByteArray data = file->read(chunk);+ if (data.isEmpty()) {+ break;+ }+ QByteArray p;+ putString(p, handle);+ putU64(p, state->offset);+ putString(p, data);+ state->offset += quint64(data.size());+ ++state->inFlight;+ const qint64 size = data.size();+ send(FxpWrite, p, [this, state, pump, size, progress, done, handle](quint8 type, const QByteArray &body) {+ --state->inFlight;+ const QString err = type == FxpStatus ? statusText(body) : QStringLiteral("Unexpected answer");+ if (!err.isEmpty() && !state->failed) {+ state->failed = true;+ closeHandle(handle);+ done(err);+ *pump = nullptr;+ return;+ }+ state->acknowledged += size;+ if (progress) {+ progress(state->acknowledged);+ }+ if (*pump) {+ (*pump)();+ }+ });+ }+ if (!state->failed && !state->finished && state->inFlight == 0 && file->atEnd()) {+ state->finished = true;+ closeHandle(handle);+ done({});+ *pump = nullptr;+ }+ };+ (*pump)();+ });+}++void Sftp::download(const QString &remote, const QString &local, const Progress &progress, const Done &done)+{+ auto file = QSharedPointer<QFile>::create(local);+ if (!file->open(QIODevice::WriteOnly | QIODevice::Truncate)) {+ done(QStringLiteral("%1 couldn't be written.").arg(local.section(QLatin1Char('/'), -1)));+ return;+ }+ openHandle(remote, FlagRead, [this, file, progress, done](const QByteArray &handle, const QString &error) {+ if (!error.isEmpty()) {+ file->remove();+ done(error);+ return;+ }+ struct State {+ quint64 next = 0;+ qint64 written = 0;+ int inFlight = 0;+ bool eof = false;+ bool failed = false;+ bool finished = false;+ };+ auto state = QSharedPointer<State>::create();+ auto pump = QSharedPointer<std::function<void()>>::create();+ *pump = [this, file, handle, state, pump, progress, done]() {+ while (!state->failed && !state->eof && state->inFlight < window) {+ QByteArray p;+ putString(p, handle);+ const quint64 offset = state->next;+ putU64(p, offset);+ putU32(p, chunk);+ state->next += chunk;+ ++state->inFlight;+ send(FxpRead, p, [this, file, state, pump, offset, progress, done, handle](quint8 type, const QByteArray &body) {+ --state->inFlight;+ if (state->failed) {+ return;+ }+ if (type == FxpData) {+ Reader r{body};+ const QByteArray data = r.string();+ // Replies may arrive in any order; each lands where+ // it belongs.+ file->seek(qint64(offset));+ file->write(data);+ state->written += data.size();+ if (progress) {+ progress(state->written);+ }+ // A short read from a regular file is its end.+ if (quint32(data.size()) < chunk) {+ state->eof = true;+ }+ } else {+ Reader r{body};+ const quint32 code = type == FxpStatus ? r.u32() : 4;+ if (code == 1) {+ state->eof = true;+ } else {+ state->failed = true;+ closeHandle(handle);+ file->remove();+ done(statusText(body));+ *pump = nullptr;+ return;+ }+ }+ if (*pump) {+ (*pump)();+ }+ });+ }+ if (!state->failed && !state->finished && state->eof && state->inFlight == 0) {+ state->finished = true;+ closeHandle(handle);+ file->close();+ done({});+ *pump = nullptr;+ }+ };+ (*pump)();+ });+}diff --git a/packages/wildos-remote/src/sftp.h b/packages/wildos-remote/src/sftp.hnew file mode 100644index 0000000..5ac08ed--- /dev/null+++ b/packages/wildos-remote/src/sftp.h@@ -0,0 +1,69 @@+#pragma once++#include <QByteArray>+#include <QHash>+#include <QObject>+#include <QProcess>++#include <functional>++// An SFTP (version 3) client over `ssh -s sftp`. It rides on the+// terminal's connection through OpenSSH's connection sharing, so it needs+// no second sign-in and checks nothing ssh hasn't already checked.+class Sftp : public QObject+{+ Q_OBJECT++public:+ struct Entry {+ QString name;+ bool dir = false;+ bool link = false;+ qint64 size = 0;+ qint64 mtime = 0;+ quint32 permissions = 0;+ };+ // An empty error means it worked.+ using Done = std::function<void(const QString &error)>;+ using Listed = std::function<void(const QList<Entry> &entries, const QString &error)>;+ using Progress = std::function<void(qint64 done)>;++ explicit Sftp(QObject *parent = nullptr);+ ~Sftp() override;++ // The ssh arguments that reach the host (control path, port, user@host).+ void start(const QStringList &sshArgs);+ void stop();+ bool ready() const { return m_ready; }++ void realPath(const QString &path, const std::function<void(const QString &path, const QString &error)> &done);+ void list(const QString &path, const Listed &done);+ void stat(const QString &path, const std::function<void(const Entry &entry, const QString &error)> &done);+ void mkdir(const QString &path, const Done &done);+ void remove(const QString &path, const Done &done);+ void rmdir(const QString &path, const Done &done);+ void rename(const QString &from, const QString &to, const Done &done);+ void upload(const QString &local, const QString &remote, const Progress &progress, const Done &done);+ void download(const QString &remote, const QString &local, const Progress &progress, const Done &done);++Q_SIGNALS:+ void readyChanged();+ // The connection ended, or never came up: `error` says why.+ void failed(const QString &error);++private:+ using Reply = std::function<void(quint8 type, const QByteArray &body)>;+ void send(quint8 type, const QByteArray &payload, const Reply &reply);+ void readyRead();+ void packet(const QByteArray &data);+ static QString statusText(const QByteArray &body);+ void openHandle(const QString &path, quint32 flags, const std::function<void(const QByteArray &handle, const QString &error)> &done);+ void closeHandle(const QByteArray &handle);++ QProcess *m_process = nullptr;+ QByteArray m_buffer;+ quint32 m_nextId = 1;+ QHash<quint32, Reply> m_pending;+ bool m_ready = false;+ QString m_stderr;+};diff --git a/packages/wildos-remote/src/shortcuts.cpp b/packages/wildos-remote/src/shortcuts.cppnew file mode 100644index 0000000..54c213a--- /dev/null+++ b/packages/wildos-remote/src/shortcuts.cpp@@ -0,0 +1,122 @@+#include "shortcuts.h"++#include <QGuiApplication>+#include <qpa/qplatformnativeinterface.h>++#include <wayland-client.h>++#include "keyboard-shortcuts-inhibit-unstable-v1-client-protocol.h"++#include <cstring>++namespace+{+zwp_keyboard_shortcuts_inhibit_manager_v1 *s_manager = nullptr;+bool s_looked = false;++void global(void *, wl_registry *registry, uint32_t name, const char *interface, uint32_t)+{+ if (std::strcmp(interface, zwp_keyboard_shortcuts_inhibit_manager_v1_interface.name) == 0) {+ s_manager = static_cast<zwp_keyboard_shortcuts_inhibit_manager_v1 *>(+ wl_registry_bind(registry, name, &zwp_keyboard_shortcuts_inhibit_manager_v1_interface, 1));+ }+}++void globalRemove(void *, wl_registry *, uint32_t)+{+}+}++ShortcutInhibitor::ShortcutInhibitor(QObject *parent)+ : QObject(parent)+{+}++ShortcutInhibitor::~ShortcutInhibitor()+{+ release();+}++zwp_keyboard_shortcuts_inhibit_manager_v1 *ShortcutInhibitor::manager()+{+ if (!s_looked) {+ s_looked = true;+ auto *app = qGuiApp->nativeInterface<QNativeInterface::QWaylandApplication>();+ if (app && app->display()) {+ static const wl_registry_listener listener = {global, globalRemove};+ wl_registry *registry = wl_display_get_registry(app->display());+ wl_registry_add_listener(registry, &listener, nullptr);+ wl_display_roundtrip(app->display());+ }+ }+ return s_manager;+}++bool ShortcutInhibitor::available() const+{+ return manager() != nullptr;+}++void ShortcutInhibitor::setWindow(QQuickWindow *window)+{+ if (window == m_window) {+ return;+ }+ release();+ if (m_window) {+ m_window->disconnect(this);+ }+ m_window = window;+ if (window) {+ connect(window, &QWindow::activeChanged, this, &ShortcutInhibitor::apply);+ connect(window, &QWindow::visibleChanged, this, &ShortcutInhibitor::apply);+ }+ apply();+ Q_EMIT changed();+}++void ShortcutInhibitor::setEnabled(bool enabled)+{+ if (enabled != m_enabled) {+ m_enabled = enabled;+ apply();+ Q_EMIT changed();+ }+}++void ShortcutInhibitor::apply()+{+ const bool want = m_enabled && m_window && m_window->isVisible() && m_window->isActive();+ if (!want) {+ release();+ return;+ }+ if (m_inhibitor || !manager()) {+ return;+ }+ QPlatformNativeInterface *native = QGuiApplication::platformNativeInterface();+ auto *app = qGuiApp->nativeInterface<QNativeInterface::QWaylandApplication>();+ auto *surface = native ? static_cast<wl_surface *>(native->nativeResourceForWindow(QByteArrayLiteral("surface"), m_window)) : nullptr;+ wl_seat *seat = app ? app->seat() : nullptr;+ if (!surface || !seat) {+ return;+ }+ m_inhibitor = zwp_keyboard_shortcuts_inhibit_manager_v1_inhibit_shortcuts(s_manager, surface, seat);+ m_active = true;+ Q_EMIT activeChanged();+}++void ShortcutInhibitor::release()+{+ if (m_inhibitor) {+ zwp_keyboard_shortcuts_inhibitor_v1_destroy(m_inhibitor);+ m_inhibitor = nullptr;+ if (auto *app = qGuiApp->nativeInterface<QNativeInterface::QWaylandApplication>()) {+ wl_display_flush(app->display());+ }+ }+ if (m_active) {+ m_active = false;+ Q_EMIT activeChanged();+ }+}diff --git a/packages/wildos-remote/src/shortcuts.h b/packages/wildos-remote/src/shortcuts.hnew file mode 100644index 0000000..4268bfc--- /dev/null+++ b/packages/wildos-remote/src/shortcuts.h@@ -0,0 +1,51 @@+#pragma once++#include <QObject>+#include <QPointer>+#include <QQmlEngine>+#include <QQuickWindow>++struct zwp_keyboard_shortcuts_inhibit_manager_v1;+struct zwp_keyboard_shortcuts_inhibitor_v1;++// "Send all shortcuts there" (RemoteSession.dc): while on, the desktop's own+// shortcuts (Alt+Tab, the Windows key, Ctrl+Alt+Del's neighbours) reach the+// window instead of Wild OS, through Wayland's keyboard shortcuts inhibit+// protocol, which KWin offers. Only while the window has the keyboard.+class ShortcutInhibitor : public QObject+{+ Q_OBJECT+ QML_ELEMENT++ Q_PROPERTY(QQuickWindow *window READ window WRITE setWindow NOTIFY changed)+ Q_PROPERTY(bool enabled READ enabled WRITE setEnabled NOTIFY changed)+ // The compositor agreed; false when it can't (not KWin, or the+ // protocol is missing).+ Q_PROPERTY(bool active READ active NOTIFY activeChanged)+ Q_PROPERTY(bool available READ available CONSTANT)++public:+ explicit ShortcutInhibitor(QObject *parent = nullptr);+ ~ShortcutInhibitor() override;++ QQuickWindow *window() const { return m_window; }+ void setWindow(QQuickWindow *window);+ bool enabled() const { return m_enabled; }+ void setEnabled(bool enabled);+ bool active() const { return m_active; }+ bool available() const;++Q_SIGNALS:+ void changed();+ void activeChanged();++private:+ void apply();+ void release();+ static zwp_keyboard_shortcuts_inhibit_manager_v1 *manager();++ QPointer<QQuickWindow> m_window;+ bool m_enabled = false;+ bool m_active = false;+ zwp_keyboard_shortcuts_inhibitor_v1 *m_inhibitor = nullptr;+};diff --git a/packages/wildos-remote/src/snippets.cpp b/packages/wildos-remote/src/snippets.cppnew file mode 100644index 0000000..c92a504--- /dev/null+++ b/packages/wildos-remote/src/snippets.cpp@@ -0,0 +1,188 @@+#include "snippets.h"+#include "paths.h"++#include <QFile>+#include <QJsonArray>+#include <QJsonDocument>+#include <QJsonObject>+#include <QSaveFile>+#include <QUuid>++#include <algorithm>++namespace+{+QString snippetsFile()+{+ return Paths::data() + QStringLiteral("/snippets.json");+}++QString historyFile()+{+ return Paths::data() + QStringLiteral("/history.json");+}++// How many commands each host keeps; the least used go first.+constexpr int historyLimit = 500;++void writeJson(const QString &path, const QJsonDocument &doc)+{+ QDir().mkpath(Paths::data());+ QSaveFile f(path);+ if (f.open(QIODevice::WriteOnly)) {+ f.write(doc.toJson());+ f.commit();+ QFile::setPermissions(path, QFileDevice::ReadOwner | QFileDevice::WriteOwner);+ }+}+}++Snippets *Snippets::instance()+{+ static Snippets *s = new Snippets;+ return s;+}++Snippets *Snippets::create(QQmlEngine *, QJSEngine *)+{+ Snippets *s = instance();+ QJSEngine::setObjectOwnership(s, QJSEngine::CppOwnership);+ return s;+}++Snippets::Snippets(QObject *parent)+ : QObject(parent)+{+ QFile s(snippetsFile());+ if (s.open(QIODevice::ReadOnly)) {+ m_snippets = QJsonDocument::fromJson(s.readAll()).array().toVariantList();+ }+ QFile h(historyFile());+ if (h.open(QIODevice::ReadOnly)) {+ const QJsonObject root = QJsonDocument::fromJson(h.readAll()).object();+ for (auto it = root.begin(); it != root.end(); ++it) {+ QHash<QString, int> &commands = m_history[it.key()];+ const QJsonObject o = it.value().toObject();+ for (auto c = o.begin(); c != o.end(); ++c) {+ commands.insert(c.key(), c.value().toInt());+ }+ }+ }+}++void Snippets::writeSnippets()+{+ writeJson(snippetsFile(), QJsonDocument(QJsonArray::fromVariantList(m_snippets)));+ Q_EMIT changed();+}++void Snippets::writeHistory()+{+ QJsonObject root;+ for (auto it = m_history.cbegin(); it != m_history.cend(); ++it) {+ QJsonObject o;+ for (auto c = it->cbegin(); c != it->cend(); ++c) {+ o.insert(c.key(), c.value());+ }+ root.insert(it.key(), o);+ }+ writeJson(historyFile(), QJsonDocument(root));+}++QString Snippets::save(const QVariantMap &input)+{+ QVariantMap s = input;+ QString id = s.value(QStringLiteral("id")).toString();+ if (id.isEmpty()) {+ id = QUuid::createUuid().toString(QUuid::WithoutBraces).left(8);+ s.insert(QStringLiteral("id"), id);+ m_snippets.append(s);+ } else {+ for (QVariant &v : m_snippets) {+ if (v.toMap().value(QStringLiteral("id")).toString() == id) {+ v = s;+ }+ }+ }+ writeSnippets();+ return id;+}++void Snippets::remove(const QString &id)+{+ m_snippets.erase(std::remove_if(m_snippets.begin(), m_snippets.end(),+ [&](const QVariant &v) { return v.toMap().value(QStringLiteral("id")).toString() == id; }),+ m_snippets.end());+ writeSnippets();+}++void Snippets::record(const QString &hostKey, const QString &command)+{+ const QString c = command.trimmed();+ // A command typed with a space first is one the person asked the shell+ // not to remember; Remote doesn't either.+ if (c.size() < 3 || command.startsWith(QLatin1Char(' '))) {+ return;+ }+ QHash<QString, int> &commands = m_history[hostKey];+ ++commands[c];+ if (commands.size() > historyLimit) {+ auto least = std::min_element(commands.begin(), commands.end());+ commands.erase(least);+ }+ writeHistory();+}++void Snippets::clearHistory(const QString &hostKey)+{+ if (hostKey.isEmpty()) {+ m_history.clear();+ } else {+ m_history.remove(hostKey);+ }+ writeHistory();+}++QVariantList Snippets::suggest(const QString &hostKey, const QString &typed) const+{+ QVariantList out;+ if (typed.trimmed().size() < 3) {+ return out;+ }+ QList<QPair<QString, int>> matches;+ const QHash<QString, int> commands = m_history.value(hostKey);+ for (auto it = commands.cbegin(); it != commands.cend(); ++it) {+ if (it.key().size() > typed.size() && it.key().startsWith(typed)) {+ matches.append({it.key(), it.value()});+ }+ }+ std::sort(matches.begin(), matches.end(), [](const auto &a, const auto &b) {+ return a.second != b.second ? a.second > b.second : a.first < b.first;+ });+ for (int i = 0; i < matches.size() && i < 2; ++i) {+ out.append(QVariantMap{{QStringLiteral("kind"), QStringLiteral("history")},+ {QStringLiteral("text"), matches[i].first},+ {QStringLiteral("completion"), matches[i].first},+ {QStringLiteral("detail"), matches[i].second == 1 ? QStringLiteral("Used once") : QStringLiteral("Used %1 times").arg(matches[i].second)}});+ }+ // A snippet whose command starts the same way, or whose name has the+ // last word typed in it.+ const QString lastWord = typed.section(QLatin1Char(' '), -1).trimmed();+ for (const QVariant &v : m_snippets) {+ const QVariantMap s = v.toMap();+ const QString command = s.value(QStringLiteral("command")).toString();+ const QString title = s.value(QStringLiteral("title")).toString();+ const bool byCommand = command.startsWith(typed) && command.size() > typed.size();+ const bool byWord = lastWord.size() >= 3 && title.contains(lastWord, Qt::CaseInsensitive);+ if (byCommand || byWord) {+ const QString note = s.value(QStringLiteral("note")).toString();+ out.append(QVariantMap{{QStringLiteral("kind"), QStringLiteral("snippet")},+ {QStringLiteral("text"), title},+ {QStringLiteral("completion"), command},+ {QStringLiteral("replace"), !byCommand},+ {QStringLiteral("detail"), note.isEmpty() ? QStringLiteral("Snippet") : QStringLiteral("Snippet: ") + note}});+ break;+ }+ }+ return out;+}diff --git a/packages/wildos-remote/src/snippets.h b/packages/wildos-remote/src/snippets.hnew file mode 100644index 0000000..4c0d4e5--- /dev/null+++ b/packages/wildos-remote/src/snippets.h@@ -0,0 +1,50 @@+#pragma once++#include <QHash>+#include <QObject>+#include <QQmlEngine>+#include <QVariantList>++// Snippets (saved commands with a name) and each host's command history,+// for the snippets panel and the suggestions under the cursor+// (RemoteTerminal.dc). Both stay on this PC, in ~/.local/share/wildos-remote.+// A line only counts as history once the terminal has shown it back, so+// whatever is typed at a password prompt (which isn't shown) is never+// kept.+class Snippets : public QObject+{+ Q_OBJECT+ QML_ELEMENT+ QML_SINGLETON++ // [{ id, title, command, note }]+ Q_PROPERTY(QVariantList snippets READ snippets NOTIFY changed)++public:+ static Snippets *instance();+ static Snippets *create(QQmlEngine *, QJSEngine *);++ QVariantList snippets() const { return m_snippets; }++ Q_INVOKABLE QString save(const QVariantMap &snippet);+ Q_INVOKABLE void remove(const QString &id);++ void record(const QString &hostKey, const QString &command);+ Q_INVOKABLE void clearHistory(const QString &hostKey);+ // Up to three suggestions for what has been typed so far: the host's+ // most used commands that start with it, then a snippet.+ // [{ kind: "history" | "snippet", text, completion, detail }]+ QVariantList suggest(const QString &hostKey, const QString &typed) const;++Q_SIGNALS:+ void changed();++private:+ explicit Snippets(QObject *parent = nullptr);+ void writeSnippets();+ void writeHistory();++ QVariantList m_snippets;+ // host key -> command -> times used+ QHash<QString, QHash<QString, int>> m_history;+};diff --git a/packages/wildos-remote/src/terminalview.cpp b/packages/wildos-remote/src/terminalview.cppnew file mode 100644index 0000000..798c0b3--- /dev/null+++ b/packages/wildos-remote/src/terminalview.cpp@@ -0,0 +1,309 @@+#include "terminalview.h"+#include "snippets.h"++#include <QApplication>+#include <QClipboard>+#include <QDesktopServices>+#include <QDir>+#include <QFileInfo>+#include <QFontDatabase>+#include <QKeyEvent>+#include <QProcessEnvironment>+#include <QRegularExpression>+#include <QScrollBar>+#include <QTimer>++namespace+{+const QString scrollBarStyle = QStringLiteral(+ "QScrollBar:vertical { background: transparent; width: 12px; margin: 2px; border: none; }"+ "QScrollBar::handle:vertical { background: rgba(255,255,255,0.28); border-radius: 3px; min-height: 32px; margin: 0px 2px; }"+ "QScrollBar::handle:vertical:hover { background: rgba(255,255,255,0.40); margin: 0px 1px; }"+ "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0px; border: none; background: none; }"+ "QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { background: none; }");++QString schemePath()+{+ const QString installed = QStringLiteral(WILDOS_REMOTE_DATADIR "/Remote.colorscheme");+ return QFileInfo::exists(installed) ? installed : QStringLiteral(WILDOS_REMOTE_SOURCEDIR "/Remote.colorscheme");+}++QFont terminalFont()+{+ // The boards' JetBrains Mono, at the size Terminal opens with.+ QFont font(QStringLiteral("JetBrains Mono"));+ if (!QFontDatabase::families().contains(font.family())) {+ font = QFontDatabase::systemFont(QFontDatabase::FixedFont);+ }+ font.setPointSizeF(10.5);+ font.setStyleHint(QFont::Monospace);+ return font;+}+}++TerminalView::TerminalView(const QString &program, const QStringList &args, const QString &historyKey, QWidget *parent)+ : QTermWidget(0, parent)+ , m_historyKey(historyKey)+{+ setShellProgram(program);+ setArgs(args);+ setWorkingDirectory(QDir::homePath());+ QProcessEnvironment env = QProcessEnvironment::systemEnvironment();+ env.insert(QStringLiteral("TERM"), QStringLiteral("xterm-256color"));+ env.insert(QStringLiteral("COLORTERM"), QStringLiteral("truecolor"));+ env.remove(QStringLiteral("DESKTOP_STARTUP_ID"));+ env.remove(QStringLiteral("XDG_ACTIVATION_TOKEN"));+ setEnvironment(env.toStringList());++ setTerminalSizeHint(false);+ setFlowControlEnabled(false);+ setFlowControlWarningEnabled(false);+ setConfirmMultilinePaste(false);+ setMotionAfterPasting(2);+ setScrollBarPosition(QTermWidget::ScrollBarRight);+ setMargin(8);+ // The output stays when ssh ends, so the reason can be read.+ setAutoClose(false);+ setColorScheme(schemePath());+ setTerminalFont(terminalFont());+ setKeyboardCursorShape(KeyboardCursorShape::BlockCursor);+ setHistorySize(10000);+ if (QScrollBar *bar = findChild<QScrollBar *>()) {+ bar->setAttribute(Qt::WA_TranslucentBackground);+ bar->setAutoFillBackground(false);+ bar->setStyleSheet(scrollBarStyle);+ }++ m_display = display();+ if (m_display) {+ m_display->installEventFilter(this);+ }+ connect(this, &QTermWidget::termGetFocus, this, &TerminalView::focused);+ connect(this, &QTermWidget::receivedData, this, &TerminalView::received);+ connect(this, &QTermWidget::finished, this, [this] {+ m_exited = true;+ dismiss();+ Q_EMIT exitedChanged();+ });+ connect(this, &QTermWidget::urlActivated, this, [](const QUrl &url, bool) {+ QDesktopServices::openUrl(url);+ });+ startShellProgram();+}++QWidget *TerminalView::display() const+{+ for (QWidget *w : findChildren<QWidget *>()) {+ if (QByteArray(w->metaObject()->className()).contains("TerminalDisplay")) {+ return w;+ }+ }+ return nullptr;+}++QRect TerminalView::cursorRect() const+{+ if (!m_display) {+ return {};+ }+ const QRect r = m_display->inputMethodQuery(Qt::ImCursorRectangle).toRect();+ return QRect(m_display->mapTo(this, r.topLeft()), r.size());+}++void TerminalView::received(const QString &text)+{+ // Only the printable part matters: the line as the shell shows it back.+ static const QRegularExpression escapes(QStringLiteral("\x1b\\[[0-9;?]*[ -/]*[@-~]|\x1b\\][^\x07\x1b]*(\x07|\x1b\\\\)|\x1b[@-_]|[\x00-\x08\x0e-\x1f]"));+ m_echo += QString(text).remove(escapes);+ if (m_echo.size() > 16384) {+ const qsizetype drop = m_echo.size() - 8192;+ m_echo.remove(0, drop);+ m_echoDropped += drop;+ }+}++void TerminalView::lineEntered()+{+ // The shell shows the line back as it is typed, but over a slow link+ // the last of it can arrive after Enter: it is looked for a moment+ // later, in what the terminal has shown since the line began.+ const QString line = m_line;+ const qint64 from = m_lineStart;+ m_lineStart = m_echoDropped + m_echo.size();+ if (!m_lineValid || line.trimmed().isEmpty() || m_historyKey.isEmpty()) {+ return;+ }+ QTimer::singleShot(400, this, [this, line, from] {+ const qint64 at = std::max<qint64>(0, from - m_echoDropped);+ if (m_echo.mid(at).contains(line.trimmed())) {+ Snippets::instance()->record(m_historyKey, line);+ }+ });+}++void TerminalView::updateSuggestions()+{+ QVariantList next;+ if (m_lineValid && !m_hidden && !m_historyKey.isEmpty()) {+ next = Snippets::instance()->suggest(m_historyKey, m_line);+ }+ if (next != m_suggestions) {+ m_suggestions = next;+ m_selected = 0;+ Q_EMIT suggestionsChanged();+ }+}++void TerminalView::dismiss()+{+ m_hidden = true;+ if (!m_suggestions.isEmpty()) {+ m_suggestions.clear();+ Q_EMIT suggestionsChanged();+ }+}++void TerminalView::setSelected(int index)+{+ if (index >= 0 && index < m_suggestions.size() && index != m_selected) {+ m_selected = index;+ Q_EMIT suggestionsChanged();+ }+}++void TerminalView::accept(int index)+{+ if (index < 0 || index >= m_suggestions.size()) {+ return;+ }+ const QVariantMap s = m_suggestions[index].toMap();+ const QString completion = s.value(QStringLiteral("completion")).toString();+ if (completion.startsWith(m_line) && !s.value(QStringLiteral("replace")).toBool()) {+ sendText(completion.mid(m_line.size()));+ } else {+ // Ctrl+U clears what is typed before the cursor, in bash, zsh and+ // fish alike.+ sendText(QStringLiteral("\x15") + completion);+ }+ m_line = completion;+ dismiss();+ if (m_display) {+ m_display->setFocus();+ }+}++void TerminalView::run(const QString &command)+{+ sendText(QStringLiteral("\x15") + command + QLatin1Char('\r'));+ m_line.clear();+ m_lineValid = true;+ m_lineStart = m_echoDropped + m_echo.size();+ dismiss();+ m_hidden = false;+}++void TerminalView::copy()+{+ const QString text = selectedText(true);+ if (!text.isEmpty()) {+ QApplication::clipboard()->setText(text);+ }+}++void TerminalView::paste()+{+ QString text = QApplication::clipboard()->text();+ if (text.isEmpty()) {+ return;+ }+ text.replace(QStringLiteral("\r\n"), QStringLiteral("\n"));+ text.replace(QLatin1Char('\n'), QLatin1Char('\r'));+ bracketText(text);+ sendText(text);+ m_lineValid = false;+}++bool TerminalView::eventFilter(QObject *watched, QEvent *event)+{+ if (watched != m_display) {+ return QTermWidget::eventFilter(watched, event);+ }+ if (event->type() == QEvent::ShortcutOverride) {+ auto *key = static_cast<QKeyEvent *>(event);+ // The window's own shortcuts (Ctrl+Shift+...) win over the emulator.+ if ((key->modifiers() & Qt::ControlModifier) && (key->modifiers() & Qt::ShiftModifier)) {+ event->ignore();+ return true;+ }+ return QTermWidget::eventFilter(watched, event);+ }+ if (event->type() != QEvent::KeyPress) {+ return QTermWidget::eventFilter(watched, event);+ }+ auto *key = static_cast<QKeyEvent *>(event);+ const auto mods = key->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier);++ if (!m_suggestions.isEmpty()) {+ switch (key->key()) {+ case Qt::Key_Tab:+ accept(m_selected);+ return true;+ case Qt::Key_Down:+ setSelected((m_selected + 1) % m_suggestions.size());+ return true;+ case Qt::Key_Up:+ setSelected((m_selected + m_suggestions.size() - 1) % m_suggestions.size());+ return true;+ case Qt::Key_Escape:+ dismiss();+ return true;+ default:+ break;+ }+ }++ if (mods == Qt::ControlModifier && key->modifiers() & Qt::ShiftModifier) {+ if (key->key() == Qt::Key_C) {+ copy();+ return true;+ }+ if (key->key() == Qt::Key_V) {+ paste();+ return true;+ }+ }++ switch (key->key()) {+ case Qt::Key_Return:+ case Qt::Key_Enter:+ lineEntered();+ m_line.clear();+ m_lineValid = true;+ dismiss();+ m_hidden = false;+ break;+ case Qt::Key_Backspace:+ if (!m_line.isEmpty()) {+ m_line.chop(1);+ }+ m_hidden = false;+ QTermWidget::eventFilter(watched, event);+ updateSuggestions();+ return false;+ default:+ if (mods == Qt::NoModifier && !key->text().isEmpty() && key->text().at(0).isPrint()) {+ m_line += key->text();+ const bool result = QTermWidget::eventFilter(watched, event);+ updateSuggestions();+ return result;+ }+ // Arrows, Tab, Ctrl+anything: the line is no longer one Remote can+ // follow.+ if (key->key() != Qt::Key_Shift && key->key() != Qt::Key_Control && key->key() != Qt::Key_Alt && key->key() != Qt::Key_Meta) {+ m_lineValid = false;+ dismiss();+ }+ break;+ }+ return QTermWidget::eventFilter(watched, event);+}diff --git a/packages/wildos-remote/src/terminalview.h b/packages/wildos-remote/src/terminalview.hnew file mode 100644index 0000000..34ff80e--- /dev/null+++ b/packages/wildos-remote/src/terminalview.h@@ -0,0 +1,64 @@+#pragma once++#include <QPointer>+#include <QVariantList>+#include <qtermwidget.h>++// One terminal: QTermWidget, the emulator Wild OS Terminal is built on,+// running ssh (or the person's shell for a local tab), with suggestions+// layered on top (RemoteTerminal.dc).+//+// Remote can't see the shell's own line, so it follows what is typed since+// the last Enter. Anything that moves the cursor or edits the line in ways+// it can't follow (arrows, Tab completion, Ctrl+R) puts suggestions away+// until the next line. A line counts as history only when the terminal+// shows it back, which a password prompt never does.+class TerminalView : public QTermWidget+{+ Q_OBJECT++public:+ TerminalView(const QString &program, const QStringList &args, const QString &historyKey, QWidget *parent = nullptr);++ QVariantList suggestions() const { return m_suggestions; }+ int selected() const { return m_selected; }+ // Where the cursor is, in this widget's coordinates.+ QRect cursorRect() const;++ void accept(int index);+ void dismiss();+ void setSelected(int index);+ // Types a command and presses Enter.+ void run(const QString &command);+ void copy();+ void paste();+ bool exited() const { return m_exited; }++Q_SIGNALS:+ void suggestionsChanged();+ void focused();+ void exitedChanged();++protected:+ bool eventFilter(QObject *watched, QEvent *event) override;++private:+ QWidget *display() const;+ void updateSuggestions();+ void received(const QString &text);+ void lineEntered();++ QString m_historyKey;+ QPointer<QWidget> m_display;+ QString m_line;+ bool m_lineValid = true;+ // What the terminal has shown, escapes removed, the oldest dropped as it+ // grows; positions are counted from the start of the session.+ QString m_echo;+ qint64 m_echoDropped = 0;+ qint64 m_lineStart = 0;+ QVariantList m_suggestions;+ int m_selected = 0;+ bool m_hidden = false;+ bool m_exited = false;+};diff --git a/packages/wildos-remote/src/windowframe.cpp b/packages/wildos-remote/src/windowframe.cppnew file mode 100644index 0000000..dc4d0ee--- /dev/null+++ b/packages/wildos-remote/src/windowframe.cpp@@ -0,0 +1,228 @@+#include "windowframe.h"++#include <KWindowEffects>+#include <KWindowShadow>+#include <QEvent>+#include <QImage>+#include <QTimer>+#include <cmath>++namespace+{+// shadow-window from the design tokens: 0 30px 80px rgba(4,8,24,0.45). A CSS+// blur of 80px is a Gaussian with a sigma of 40, which has faded to nothing+// two sigmas out.+constexpr int shadowOffset = 30;+constexpr double shadowSigma = 40.0;+constexpr int shadowReach = 80;+constexpr double shadowAlpha = 0.45;+const QColor shadowColour(4, 8, 24);++double coverage(double t, double from, double to)+{+ const double k = shadowSigma * std::sqrt(2.0);+ return 0.5 * (std::erf((t - from) / k) - std::erf((t - to) / k));+}++bool insideRounded(double x, double y, const QRectF &rect, double radius)+{+ if (!rect.contains(x, y)) {+ return false;+ }+ const double cx = std::clamp(x, rect.left() + radius, rect.right() - radius);+ const double cy = std::clamp(y, rect.top() + radius, rect.bottom() - radius);+ const double dx = x - cx;+ const double dy = y - cy;+ return dx * dx + dy * dy <= radius * radius;+}++KWindowShadowTile::Ptr tile(const QImage &image, const QRect &area)+{+ auto t = KWindowShadowTile::Ptr::create();+ t->setImage(image.copy(area));+ t->create();+ return t;+}+}++QRegion WindowFrame::roundedRegion(const QSize &size, int radius, bool roundBottom)+{+ if (radius <= 0) {+ return QRegion(QRect(QPoint(0, 0), size));+ }+ QRegion region(QRect(0, radius, size.width(), size.height() - (roundBottom ? 2 : 1) * radius));+ for (int row = 0; row < radius; ++row) {+ const double dy = radius - row - 0.5;+ const int inset = int(std::ceil(radius - std::sqrt(std::max(0.0, double(radius * radius) - dy * dy))));+ region += QRect(inset, row, size.width() - 2 * inset, 1);+ if (roundBottom) {+ region += QRect(inset, size.height() - 1 - row, size.width() - 2 * inset, 1);+ } else {+ region += QRect(0, size.height() - 1 - row, size.width(), 1);+ }+ }+ return region;+}++WindowFrame::WindowFrame(QWindow *window, QObject *parent)+ : QObject(parent)+ , m_window(window)+{+ m_blurAvailable = KWindowEffects::isEffectAvailable(KWindowEffects::BlurBehind);+ m_window->installEventFilter(this);+ connect(m_window, &QWindow::visibleChanged, this, &WindowFrame::schedule);+ connect(m_window, &QWindow::widthChanged, this, &WindowFrame::schedule);+ connect(m_window, &QWindow::heightChanged, this, &WindowFrame::schedule);+ schedule();+}++WindowFrame::~WindowFrame() = default;++bool WindowFrame::eventFilter(QObject *watched, QEvent *event)+{+ // Shadow and blur belong to the surface; a recreated surface needs+ // them again.+ if (watched == m_window && event->type() == QEvent::PlatformSurface) {+ if (m_shadow) {+ m_shadow->destroy();+ }+ m_blurApplied = false;+ schedule();+ }+ return QObject::eventFilter(watched, event);+}++void WindowFrame::setRadius(int radius)+{+ if (m_radius != radius) {+ m_radius = radius;+ if (m_shadow) {+ m_shadow->destroy();+ }+ schedule();+ }+}++void WindowFrame::setShadow(bool on)+{+ if (m_shadowOn != on) {+ m_shadowOn = on;+ schedule();+ }+}++void WindowFrame::setBlurRegion(const QRegion ®ion)+{+ if (region != m_blurRegion) {+ m_blurRegion = region;+ schedule();+ }+}++bool WindowFrame::recheck()+{+ const bool available = KWindowEffects::isEffectAvailable(KWindowEffects::BlurBehind);+ if (available != m_blurAvailable) {+ m_blurAvailable = available;+ m_blurApplied = false;+ schedule();+ return true;+ }+ return false;+}++// Resizing sends a burst of size changes; one update per pass of the event+// loop is plenty for the compositor.+void WindowFrame::schedule()+{+ if (m_pending) {+ return;+ }+ m_pending = true;+ QTimer::singleShot(0, this, [this] {+ m_pending = false;+ apply();+ });+}++void WindowFrame::apply()+{+ if (!m_window || !m_window->isVisible() || !m_window->handle()) {+ return;+ }+ applyShadow();+ const QRegion blur = m_blurAvailable ? m_blurRegion : QRegion();+ if (!m_blurApplied || blur != m_appliedBlur) {+ KWindowEffects::enableBlurBehind(m_window, !blur.isEmpty(), blur);+ m_appliedBlur = blur;+ m_blurApplied = true;+ }+}++void WindowFrame::applyShadow()+{+ if (!m_shadowOn) {+ if (m_shadow) {+ m_shadow->destroy();+ delete m_shadow;+ m_shadow = nullptr;+ }+ return;+ }+ if (m_shadow && m_shadow->window() == m_window && m_shadow->isCreated()) {+ return;+ }++ const int r = m_radius;+ const int padLeft = shadowReach;+ const int padRight = shadowReach;+ const int padTop = shadowReach - shadowOffset;+ const int padBottom = shadowReach + shadowOffset;+ // A reference window wide enough that its far edges add nothing to the+ // pieces cut from the near ones.+ const int side = 2 * (shadowReach + r) + 1;+ const int width = padLeft + side + padRight;+ const int height = padTop + side + padBottom;+ const QRectF windowRect(padLeft, padTop, side, side);++ QImage image(width, height, QImage::Format_ARGB32_Premultiplied);+ for (int y = 0; y < height; ++y) {+ auto *line = reinterpret_cast<QRgb *>(image.scanLine(y));+ const double cy = y + 0.5;+ const double fy = coverage(cy, windowRect.top() + shadowOffset, windowRect.bottom() + shadowOffset);+ for (int x = 0; x < width; ++x) {+ const double cx = x + 0.5;+ // Nothing under the window itself: the glass is translucent and+ // a shadow beneath it would muddy it.+ if (insideRounded(cx, cy, windowRect, r)) {+ line[x] = 0;+ continue;+ }+ const double a = shadowAlpha * fy * coverage(cx, windowRect.left(), windowRect.right());+ const int alpha = std::clamp(int(std::lround(a * 255.0)), 0, 255);+ line[x] = qPremultiply(qRgba(shadowColour.red(), shadowColour.green(), shadowColour.blue(), alpha));+ }+ }++ const int midX = padLeft + side / 2;+ const int midY = padTop + side / 2;+ const int right = padLeft + side;+ const int bottom = padTop + side;++ if (!m_shadow) {+ m_shadow = new KWindowShadow(this);+ } else {+ m_shadow->destroy();+ }+ m_shadow->setTopLeftTile(tile(image, QRect(0, 0, padLeft + r, padTop + r)));+ m_shadow->setTopTile(tile(image, QRect(midX, 0, 1, padTop)));+ m_shadow->setTopRightTile(tile(image, QRect(right - r, 0, padRight + r, padTop + r)));+ m_shadow->setRightTile(tile(image, QRect(right, midY, padRight, 1)));+ m_shadow->setBottomRightTile(tile(image, QRect(right - r, bottom - r, padRight + r, padBottom + r)));+ m_shadow->setBottomTile(tile(image, QRect(midX, bottom, 1, padBottom)));+ m_shadow->setBottomLeftTile(tile(image, QRect(0, bottom - r, padLeft + r, padBottom + r)));+ m_shadow->setLeftTile(tile(image, QRect(0, midY, padLeft, 1)));+ m_shadow->setPadding(QMargins(padLeft, padTop, padRight, padBottom));+ m_shadow->setWindow(m_window);+ m_shadow->create();+}diff --git a/packages/wildos-remote/src/windowframe.h b/packages/wildos-remote/src/windowframe.hnew file mode 100644index 0000000..6243ba0--- /dev/null+++ b/packages/wildos-remote/src/windowframe.h@@ -0,0 +1,51 @@+#pragma once++#include <QObject>+#include <QPointer>+#include <QRegion>+#include <QWindow>++class KWindowShadow;++// What the Aurorae decoration gives every other window and a frameless one+// has to ask the compositor for itself: the design's soft shadow and the+// frosted blur behind the glass. The same numbers Files and Settings use,+// so the three windows sit on the desktop alike.+class WindowFrame : public QObject+{+ Q_OBJECT++public:+ explicit WindowFrame(QWindow *window, QObject *parent = nullptr);+ ~WindowFrame() override;++ void setRadius(int radius);+ void setShadow(bool on);+ // The part of the window to blur, in window coordinates.+ void setBlurRegion(const QRegion ®ion);+ bool blurAvailable() const { return m_blurAvailable; }+ // KWin loads and unloads its blur effect when transparency effects are+ // switched, and nothing announces it, so the window asks again when it+ // is activated. True when the answer changed.+ bool recheck();++ static QRegion roundedRegion(const QSize &size, int radius, bool roundBottom = true);++protected:+ bool eventFilter(QObject *watched, QEvent *event) override;++private:+ void schedule();+ void apply();+ void applyShadow();++ QPointer<QWindow> m_window;+ int m_radius = 14;+ bool m_shadowOn = true;+ bool m_blurAvailable = false;+ bool m_pending = false;+ KWindowShadow *m_shadow = nullptr;+ QRegion m_blurRegion;+ QRegion m_appliedBlur;+ bool m_blurApplied = false;+};diff --git a/packages/wildos-settings/CMakeLists.txt b/packages/wildos-settings/CMakeLists.txtindex 68e4c5b..466066d 100644--- a/packages/wildos-settings/CMakeLists.txt+++ b/packages/wildos-settings/CMakeLists.txt@@ -40,10 +40,13 @@ qt_add_qml_module(wildos-settingsSOURCESsrc/kcmhost.cpp src/kcmhost.hsrc/system.cpp src/system.h+ src/themes.cpp src/themes.hsrc/updates.cpp src/updates.hsrc/appsmodel.cpp src/appsmodel.hsrc/windowsapps.cpp src/windowsapps.hsrc/windowsmode.cpp src/windowsmode.h+ src/processor.cpp src/processor.h+ src/graphics.cpp src/graphics.hsrc/inputdevices.cpp src/inputdevices.hsrc/defaultapps.cpp src/defaultapps.hsrc/clock.cpp src/clock.h@@ -66,6 +69,7 @@ qt_add_qml_module(wildos-settingssrc/activityhistory.cpp src/activityhistory.hsrc/olderapps.cpp src/olderapps.hsrc/network.cpp src/network.h src/netshared.h+ src/soundtheme.cpp src/soundtheme.hsrc/accessibility.cpp src/accessibility.hsrc/accesscore.cpp src/accesscore.h)@@ -88,7 +92,7 @@ install(TARGETS wildos-settings RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})install(FILES data/org.wildos.settings.desktop DESTINATION ${CMAKE_INSTALL_DATADIR}/applications)# The helpers are looked up by these exact paths (polkit pins the update# helper to it), so they do not follow the distribution's libexec layout.-install(PROGRAMS data/settings-update-policy data/settings-users data/settings-locale data/settings-protection data/settings-network DESTINATION ${CMAKE_INSTALL_PREFIX}/libexec/wildos)+install(PROGRAMS data/settings-update-policy data/settings-users data/settings-locale data/settings-protection data/settings-network data/settings-cpu-threads data/settings-graphics-driver DESTINATION ${CMAKE_INSTALL_PREFIX}/libexec/wildos)install(FILES data/org.wildos.settings.policy DESTINATION ${CMAKE_INSTALL_DATADIR}/polkit-1/actions)# The automatic theme runs in every session and must not pull in thediff --git a/packages/wildos-settings/data/org.wildos.settings.policy b/packages/wildos-settings/data/org.wildos.settings.policyindex fe3d70b..71c2b03 100644--- a/packages/wildos-settings/data/org.wildos.settings.policy+++ b/packages/wildos-settings/data/org.wildos.settings.policy@@ -35,6 +35,30 @@<annotate key="org.freedesktop.policykit.exec.path">/usr/libexec/wildos/settings-protection</annotate></action>+ <action id="org.wildos.settings.cpu-threads">+ <description>Turn hyper-threading on or off</description>+ <message>Change whether this computer uses hyper-threading?</message>+ <icon_name>cpu</icon_name>+ <defaults>+ <allow_any>no</allow_any>+ <allow_inactive>no</allow_inactive>+ <allow_active>auth_admin_keep</allow_active>+ </defaults>+ <annotate key="org.freedesktop.policykit.exec.path">/usr/libexec/wildos/settings-cpu-threads</annotate>+ </action>++ <action id="org.wildos.settings.graphics-driver">+ <description>Change the graphics driver</description>+ <message>Change which driver your NVIDIA graphics card uses?</message>+ <icon_name>video-display</icon_name>+ <defaults>+ <allow_any>no</allow_any>+ <allow_inactive>no</allow_inactive>+ <allow_active>auth_admin_keep</allow_active>+ </defaults>+ <annotate key="org.freedesktop.policykit.exec.path">/usr/libexec/wildos/settings-graphics-driver</annotate>+ </action>+<action id="org.wildos.settings.network"><description>Turn the VPN kill switch on or off</description><message>Change whether Wild OS blocks the internet when a VPN drops?</message>diff --git a/packages/wildos-settings/data/settings-cpu-threads b/packages/wildos-settings/data/settings-cpu-threadsnew file mode 100644index 0000000..e109fd9--- /dev/null+++ b/packages/wildos-settings/data/settings-cpu-threads@@ -0,0 +1,56 @@+#!/bin/sh+# Turns hyper-threading on or off from the next start-up: "Use every processor+# thread" in Settings > System > Power and battery, also offered by Windows+# mode setup. Runs as root through pkexec (org.wildos.settings.cpu-threads),+# and from settings-protection, which turns it off at Strict and Maximum.+#+# Wild OS ships with it off. Kicksecure's boot options (nosmt=force, ",nosmt"+# on several CPU flaw mitigations, and l1tf=full,force) keep the second thread+# of every core offline, so a program can't read what another one leaves in a+# core they share. Turning it on keeps every mitigation and only lets those+# threads run: ",nosmt" and "nosmt=force" go, and l1tf drops to "flush", which+# still clears the cache each time a virtual machine runs. The kernel decides+# this at boot, so it takes a restart.+#+# on | off save the choice and rebuild the boot menu++set -eu++CHOICE=/etc/wildos/cpu-threads+DROPIN=/etc/default/grub.d/41_wildos_cpu_threads.cfg+LEVEL_FILE=/etc/wildos/protection-level++case "${1:-}" in+on)+ # Strict and Maximum keep every CPU flaw protection on; Settings greys the+ # switch out there, and this refuses in case anything else asks.+ case "$(cat "$LEVEL_FILE" 2>/dev/null || true)" in+ strict | maximum)+ echo "Strict and Maximum protection keep hyper-threading off." >&2+ exit 3+ ;;+ esac+ mkdir -p /etc/wildos+ echo on > "$CHOICE"+ # Sorts after 40_cpu_mitigations.cfg, so it edits what that file added.+ cat > "$DROPIN" <<'EOF'+# Written by Wild OS Settings: hyper-threading is on. Every CPU flaw mitigation+# stays; only the options that keep the second thread of each core offline go.+GRUB_CMDLINE_LINUX="$(printf '%s' "$GRUB_CMDLINE_LINUX" | sed -e 's/ nosmt=force//g' -e 's/,nosmt//g' -e 's/l1tf=full,force/l1tf=flush/g')"+EOF+ ;;+off)+ [ -e "$CHOICE" ] || [ -e "$DROPIN" ] || exit 0+ rm -f "$CHOICE" "$DROPIN"+ ;;+*)+ echo "usage: $0 on|off" >&2+ exit 2+ ;;+esac++if command -v update-grub >/dev/null 2>&1; then+ update-grub >/dev/null 2>&1+else+ grub-mkconfig -o /boot/grub/grub.cfg >/dev/null 2>&1+fidiff --git a/packages/wildos-settings/data/settings-graphics-driver b/packages/wildos-settings/data/settings-graphics-drivernew file mode 100644index 0000000..1f688ff--- /dev/null+++ b/packages/wildos-settings/data/settings-graphics-driver@@ -0,0 +1,104 @@+#!/bin/sh+# Switches an NVIDIA graphics card between the open driver Wild OS ships+# (nouveau) and NVIDIA's own driver from Debian, for Settings > System >+# Display > Graphics driver. Runs as root through pkexec+# (org.wildos.settings.graphics-driver).+#+# nvidia install NVIDIA's driver. Stops with exit 4 when Debian's driver+# doesn't support this card (nvidia-detect decides). With Secure+# Boot on, the module is built here, so it is signed with this PC's+# own key (dkms makes one), and that key is queued for enrolment:+# the firmware asks for the code printed here at the next restart.+# open remove NVIDIA's driver; nouveau is back from the next start-up.+#+# Settings reads the lines this prints: "step <what is happening>" while it+# works, and "code <digits>" when the key needs enrolling.++set -eu+export DEBIAN_FRONTEND=noninteractive+MOK_KEY=/var/lib/dkms/mok.key+MOK_PUB=/var/lib/dkms/mok.pub+APT="apt-get -y -q -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold"++step() { echo "step $*"; }++secure_boot() {+ mokutil --sb-state 2>/dev/null | grep -q "SecureBoot enabled"+}++rebuild_initramfs() {+ # The nouveau blacklist and the modules must be in the start-up image.+ step "Updating the start-up files"+ if command -v dracut >/dev/null 2>&1; then+ dracut --force --regenerate-all >/dev/null 2>&1+ else+ update-initramfs -u -k all >/dev/null 2>&1+ fi+}++case "${1:-}" in+nvidia)+ step "Checking for updates"+ apt-get -q update >/dev/null 2>&1 || true++ step "Checking this graphics card"+ $APT install nvidia-detect >/dev/null 2>&1+ # It recommends a package per card; only the current one, nvidia-driver,+ # is what this installs (legacy cards are told to use older ones).+ if ! nvidia-detect 2>/dev/null | grep -qx '[[:space:]]*nvidia-driver'; then+ echo "Debian's NVIDIA driver doesn't support this graphics card." >&2+ exit 4+ fi++ step "Downloading NVIDIA's driver"+ # Headers for every installed kernel, so dkms can build the module for+ # the one running now and the one that starts next.+ headers="linux-headers-amd64"+ if apt-cache show "linux-headers-$(uname -r)" >/dev/null 2>&1; then+ headers="$headers linux-headers-$(uname -r)"+ fi+ # shellcheck disable=SC2086+ $APT install $headers dkms mokutil >/dev/null 2>&1++ step "Installing NVIDIA's driver"+ $APT install nvidia-driver firmware-misc-nonfree nvidia-suspend-common >/dev/null 2>&1++ # Wayland needs the kernel's mode setting from NVIDIA's module.+ mkdir -p /etc/modprobe.d+ printf '%s\n' '# Written by Wild OS Settings: NVIDIA driver for the desktop (Wayland).' \+ 'options nvidia-drm modeset=1 fbdev=1' > /etc/modprobe.d/60-wildos-nvidia.conf++ rebuild_initramfs++ # Store apps from Flathub need NVIDIA's graphics libraries in their own runtime.+ if command -v flatpak >/dev/null 2>&1; then+ step "Updating Store apps for the new driver"+ flatpak update --system --noninteractive >/dev/null 2>&1 || true+ fi++ if secure_boot && [ -f "$MOK_PUB" ] && ! mokutil --test-key "$MOK_PUB" 2>/dev/null | grep -q "already enrolled"; then+ step "Preparing Secure Boot"+ # Eight digits: typed once into the firmware's own screen, which+ # shows nothing as you type.+ code=$(od -An -N4 -tu4 /dev/urandom | tr -d ' ' | cut -c1-8)+ while [ "${#code}" -lt 8 ]; do code="${code}0"; done+ printf '%s\n%s\n' "$code" "$code" | mokutil --import "$MOK_PUB" >/dev/null 2>&1+ echo "code $code"+ fi+ step "Done"+ ;;+open)+ step "Removing NVIDIA's driver"+ # shellcheck disable=SC2046+ $APT purge $(dpkg-query -W -f='${Package}\n' 'nvidia-*' 'libnvidia-*' 'xserver-xorg-video-nvidia*' 2>/dev/null \+ | grep -v -E '^(nvidia-detect)$' || true) >/dev/null 2>&1 || true+ $APT autoremove >/dev/null 2>&1 || true+ rm -f /etc/modprobe.d/60-wildos-nvidia.conf+ rebuild_initramfs+ step "Done"+ ;;+*)+ echo "usage: $0 nvidia|open" >&2+ exit 2+ ;;+esacdiff --git a/packages/wildos-settings/data/settings-protection b/packages/wildos-settings/data/settings-protectionindex 24eefac..cafc410 100644--- a/packages/wildos-settings/data/settings-protection+++ b/packages/wildos-settings/data/settings-protection@@ -4,10 +4,11 @@# from wildos-protection.service to load the firewall again. Takes only the# requests below.#-# standard What Wild OS ships: the hardened system with no extra limits.-# strict Adds a firewall that turns away anything arriving unasked,-# and USB devices found at start-up wait for permission like-# ones plugged in later.+# standard What Wild OS ships: the hardened system, with a firewall+# that turns away anything arriving unasked and lets+# everything this computer starts go out.+# strict Standard, plus USB devices found at start-up wait for+# permission like ones plugged in later.# maximum Strict, plus the firewall blocks network discovery (finding# printers and screens), Bluetooth is off and the camera's# driver is blocked.@@ -30,12 +31,14 @@ saved_level() {}# Incoming connections are refused unless they answer something this-# computer asked for. The Windows mode bridge stays open, since Windows-# reaches its shared folders and printers through it, and so does mDNS at-# Strict, which is how printers and screens on the network are found.+# computer asked for. The Windows mode bridge (virbr-wildos) stays open:+# Windows gets its address and DNS from this computer through it, and+# Windows mode's own table (wildos_win) already limits what may come in+# there. A drop here would be final whatever that table allows. mDNS stays+# open at Standard and Strict, which is how printers and screens on the+# network are found. Nothing outgoing is limited at any level.firewall() {nft delete table inet "$TABLE" 2>/dev/null || true- [ "$1" = standard ] && return 0command -v nft >/dev/null || return 0discovery='udp dport 5353 accept'[ "$1" = maximum ] && discovery=''@@ -46,7 +49,7 @@ table inet $TABLE {ct state established,related acceptct state invalid dropiif lo accept- iifname "wildos-win*" accept+ iifname { "virbr-wildos", "wildos-win*" } acceptmeta l4proto ipv6-icmp accepticmp type { echo-reply, destination-unreachable, time-exceeded, parameter-problem } acceptudp sport 67 udp dport 68 accept@@ -110,6 +113,11 @@ case "${1:-}" inusb "$1"bluetooth "$1" "$previous"camera "$1"+ # Strict and Maximum keep every CPU flaw protection on, so hyper-threading+ # goes off from the next start-up. Standard leaves the person's choice.+ if [ "$1" != standard ] && [ -x /usr/libexec/wildos/settings-cpu-threads ]; then+ /usr/libexec/wildos/settings-cpu-threads off || true+ fiif [ "$1" = standard ]; thenrm -f "$LEVEL_FILE"elsediff --git a/packages/wildos-settings/data/wildos-protection.service b/packages/wildos-settings/data/wildos-protection.serviceindex 3cc2008..b99b223 100644--- a/packages/wildos-settings/data/wildos-protection.service+++ b/packages/wildos-settings/data/wildos-protection.service@@ -6,7 +6,6 @@ DefaultDependencies=noBefore=network-pre.targetWants=network-pre.targetAfter=local-fs.target-ConditionPathExists=/etc/wildos/protection-level[Service]Type=oneshotdiff --git a/packages/wildos-settings/debian/changelog b/packages/wildos-settings/debian/changelogindex b37a10a..a7df4f7 100644--- a/packages/wildos-settings/debian/changelog+++ b/packages/wildos-settings/debian/changelog@@ -1,3 +1,13 @@+wildos-settings (0.1.1) trixie; urgency=medium++ * Accessibility has Outline windows, Stronger text on glass and Blur windows+ in the background, with a blur strength and a choice to blur the desktop+ too.+ * wildos-auto-theme puts on the solid Plasma style while stronger text on+ glass is on.++ -- Wild OS Developers <[email protected]> Tue, 10 Nov 2026 08:10:42 +0000+wildos-settings (0.1.0) trixie; urgency=medium* Initial release.diff --git a/packages/wildos-settings/debian/postinst b/packages/wildos-settings/debian/postinstindex 2b599e6..5c0ec5b 100644--- a/packages/wildos-settings/debian/postinst+++ b/packages/wildos-settings/debian/postinst@@ -18,6 +18,11 @@ if [ "$1" = "configure" ]; thenif [ -d /run/systemd/system ] && systemctl is-active --quiet NetworkManager.service; thennmcli general reload >/dev/null 2>&1 || truefi+ # The firewall's rules change with the package; loaded again now rather+ # than at the next start-up.+ if [ -d /run/systemd/system ] && [ -x /usr/libexec/wildos/settings-protection ] && command -v nft >/dev/null; then+ /usr/libexec/wildos/settings-protection boot || true+ fifi#DEBHELPER#diff --git a/packages/wildos-settings/qml/components/Pages.qml b/packages/wildos-settings/qml/components/Pages.qmlindex 30974a4..eaaa600 100644--- a/packages/wildos-settings/qml/components/Pages.qml+++ b/packages/wildos-settings/qml/components/Pages.qml@@ -25,12 +25,14 @@ QtObject {"display": { title: "Display", parent: "system", icon: "display", component: "DisplayPage", fallback: "kcm_kscreen",description: "Monitors, brightness, resolution and scale",keywords: "screen monitor resolution scale scaling zoom brightness refresh rate hz orientation rotate portrait hdr second screen multiple monitors projector arrange identify detect extend duplicate mirror main display primary variable refresh vrr freesync gsync" },+ "graphicsdriver": { title: "Graphics driver", parent: "display", icon: "chip", component: "GraphicsDriverPage",+ description: "Open driver or NVIDIA's own" },"nightlight": { title: "Night light", parent: "display", icon: "moon", component: "NightLightPage", fallback: "kcm_nightlight",description: "Warmer colours in the evening",keywords: "blue light warm colour color temperature evening sleep" },"sound": { title: "Sound", parent: "system", icon: "sound", component: "SoundPage", fallback: "kcm_pulseaudio",description: "Volume, output and input devices",- keywords: "volume audio speakers headphones headset microphone mic input output mute balance mixer volume mixer app volume per app system sounds notification sounds windows apps hdmi bluetooth" },+ keywords: "volume audio speakers headphones headset microphone mic input output mute balance mixer volume mixer app volume per app system sounds notification sounds windows apps hdmi bluetooth sound scheme sound theme startup sound start-up sound login sound beeps" },"notifications": { title: "Notifications", parent: "system", icon: "bell", component: "NotificationsPage", fallback: "kcm_notifications",description: "Alerts from apps and Wild OS, do not disturb",keywords: "alerts do not disturb focus banners popups badges" },@@ -42,7 +44,7 @@ QtObject {keywords: "disk space drive free space bin trash recycle hard drive ssd clean up" },"multitasking": { title: "Multitasking", parent: "system", icon: "multitasking", component: "MultitaskingPage",description: "Snap windows, desktops and Alt+Tab",- keywords: "snap layouts alt tab task switcher windows side by side taskbar all desktops open windows" },+ keywords: "snap layouts snap assist suggest fill alt tab task switcher windows side by side taskbar all desktops open windows" },"appnotifications": { title: "Notifications from apps", parent: "notifications", icon: "bell", component: "AppNotificationsPage",description: "Choose which apps can notify you",keywords: "app notifications notify sounds popups pop ups banners history notification list per app senders turn off mute" },@@ -110,8 +112,11 @@ QtObject {keywords: "802.1x eap enterprise wpa2 enterprise eduroam certificate bond bridge vlan team openconnect anyconnect l2tp pptp ipsec" },"personalisation": { title: "Personalisation", icon: "palette", component: "PersonalisationPage",- children: ["background", "colours", "lockscreen", "taskbar", "fonts"],+ children: ["themes", "background", "colours", "lockscreen", "taskbar", "fonts"],keywords: "personalize personalise customise customize theme look light dark font fonts text size bigger" },+ "themes": { title: "Themes", parent: "personalisation", icon: "brush", component: "ThemesPage",+ description: "Wallpaper, light or dark, accent and glass in one go",+ keywords: "theme themes look style dawn orchard graphite overclock ember estuary gaming neon glass tint rgb lighting underglow glow keyboard lighting mouse lighting openrgb" },"background": { title: "Background", parent: "personalisation", icon: "image", component: "BackgroundPage",description: "Pictures and your own photos",keywords: "wallpaper background desktop picture photo image" },@@ -122,8 +127,8 @@ QtObject {description: "Lock screen picture and screen lock",keywords: "lock screen picture wallpaper" },"taskbar": { title: "Taskbar", parent: "personalisation", icon: "taskbar", component: "TaskbarPage",- description: "Hiding the taskbar",- keywords: "taskbar panel auto hide autohide" },+ description: "Hiding the taskbar, Windows mode status",+ keywords: "taskbar panel auto hide autohide windows mode status virtual machine" },"fonts": { title: "Fonts", parent: "personalisation", icon: "font", component: "FontsPage",description: "Install and remove fonts",keywords: "font fonts typeface install font ttf otf typography" },@@ -181,7 +186,7 @@ QtObject {keywords: "typing spelling spell check spellcheck dictionary misspelt misspelled words" },"accessibility": { title: "Accessibility", icon: "accessibility", component: "AccessibilityPage", fallback: "kcm_access",- keywords: "accessibility ease of access text size bigger larger pointer cursor mouse pointer colour color size magnifier magnify zoom screen reader orca narrator read aloud high contrast flash visual alerts bell deaf hearing mono audio on-screen keyboard virtual keyboard touch keyboard sticky keys slow keys bounce keys filter keys" },+ keywords: "accessibility ease of access text size bigger larger pointer cursor mouse pointer colour color size magnifier magnify zoom screen reader orca narrator read aloud high contrast flash visual alerts bell deaf hearing mono audio on-screen keyboard virtual keyboard touch keyboard sticky keys slow keys bounce keys filter keys outline windows window border focus ring focused window blur background windows inactive windows dim low vision stronger text glass transparency readable contrast" },"slowbouncekeys": { title: "Slow and bounce keys", parent: "accessibility", icon: "keyboard", component: "SlowBounceKeysPage",description: "Ignore quick or repeated presses",keywords: "slow keys bounce keys filter keys repeated presses double letters tremor hold key delay" },diff --git a/packages/wildos-settings/qml/components/Protection.qml b/packages/wildos-settings/qml/components/Protection.qmlindex c174641..35b253d 100644--- a/packages/wildos-settings/qml/components/Protection.qml+++ b/packages/wildos-settings/qml/components/Protection.qml@@ -30,8 +30,16 @@ QtObject {readonly property var items: known.filter(item => status[item.key] !== undefined)readonly property bool checked: items.length > 0- // True when the item is fine or simply does not apply here.+ // Warnings the person chose to ignore from the taskbar's security chip+ // (security-status ignore): shown as they are, but not raised.+ readonly property var ignored: String(status.ignored || "").split(",").filter(k => k.length > 0)++ // True when the item is fine, simply does not apply here, or is a+ // warning the person chose to ignore.function good(item) {+ if (ignored.includes(item.key)) {+ return true;+ }const v = status[item.key];switch (item.key) {case "updates":@@ -60,6 +68,11 @@ QtObject {readonly property bool allOn: checked && attention.length === 0function value(item) {+ const base = rawValue(item);+ return ignored.includes(item.key) && rawValue(item) !== "On" ? base + ", warning ignored" : base;+ }++ function rawValue(item) {const v = status[item.key];switch (item.key) {case "encryption":@@ -205,9 +218,9 @@ QtObject {if (v === "on") {return { text: count("devices_blocked") > 0? Format.plural(count("devices_blocked"), "device is", "devices are") + " held back. Allow the ones you trust from the shield on the taskbar."- : "New USB devices stay switched off until you allow them from the shield on the taskbar. Devices you have allowed keep working.", action: "" };+ : "Memory sticks, drives, a keyboard, a mouse, webcams and audio devices work straight away. Other new USB devices stay switched off until you allow them from the shield on the taskbar.", action: "" };}- return { text: "Anything plugged into a USB port works straight away, including devices made to attack a computer. Turn this on to hold new devices back until you allow them.", action: "usb" };+ return { text: "Anything plugged into a USB port works straight away, including devices made to attack a computer. Turn this on to hold back new devices that are not ordinary drives, keyboards, mice, webcams or audio devices until you allow them.", action: "usb" };case "secureboot":if (v === "on") {return { text: "The computer checks that nothing has tampered with Wild OS before it starts.", action: "" };diff --git a/packages/wildos-settings/qml/components/ThemePreview.qml b/packages/wildos-settings/qml/components/ThemePreview.qmlnew file mode 100644index 0000000..c90347f--- /dev/null+++ b/packages/wildos-settings/qml/components/ThemePreview.qml@@ -0,0 +1,193 @@+pragma ComponentBehavior: Bound++import QtQuick+import QtQuick.Effects+import WildOS.Settings+import WildOS.UI as UI++// A theme in miniature (SettingsThemes.dc): its wallpaper with a window of+// its glass on it, holding a button and a switch in its accent, and its+// taskbar along the bottom. Drawn from the theme itself, not the current+// look, so every card shows what it will give. The board's card is 250 by+// 124; everything scales with the width.+Item {+ id: preview++ required property var theme+ readonly property bool light: theme.mode === "light"+ readonly property real s: width / 250+ readonly property color ink: light ? Qt.rgba(20 / 255, 26 / 255, 46 / 255, 0.85) : Qt.rgba(238 / 255, 241 / 255, 248 / 255, 0.9)+ readonly property color faint: light ? Qt.rgba(20 / 255, 26 / 255, 46 / 255, 0.14) : Qt.rgba(238 / 255, 241 / 255, 248 / 255, 0.22)+ readonly property color taskbar: theme.taskbarGlass && theme.taskbarGlass.a > 0 ? theme.taskbarGlass+ : light ? Qt.rgba(246 / 255, 248 / 255, 252 / 255, 0.88) : Qt.rgba(14 / 255, 18 / 255, 34 / 255, 0.85)++ implicitWidth: 250+ implicitHeight: 124++ readonly property real radius: 7.2 * s++ // Drawn square, then rounded as a whole by the mask below.+ Rectangle {+ id: scene+ anchors.fill: parent+ color: UI.Style.lakeNavy+ visible: false+ layer.enabled: true++ Image {+ anchors.fill: parent+ source: System.thumbnail(preview.theme.wallpaper)+ fillMode: Image.PreserveAspectCrop+ sourceSize.width: 500+ asynchronous: true+ }++ Rectangle {+ x: 28.7 * preview.s+ y: 22.7 * preview.s+ width: 137.6 * preview.s+ height: 89.7 * preview.s+ radius: 5.4 * preview.s+ color: preview.theme.glass+ border.width: 1+ border.color: preview.faint++ Column {+ x: 7.2 * preview.s+ y: 7.2 * preview.s+ width: parent.width - 2 * x+ spacing: 5.4 * preview.s++ Row {+ spacing: 2.4 * preview.s+ Repeater {+ model: 2+ Rectangle {+ width: 3.6 * preview.s+ height: width+ radius: width / 2+ color: preview.faint+ }+ }+ }+ Rectangle {+ width: parent.width * 0.7+ height: 4.8 * preview.s+ radius: height / 2+ color: preview.ink+ opacity: 0.85+ }+ Rectangle {+ width: parent.width * 0.9+ height: 3.6 * preview.s+ radius: height / 2+ color: preview.faint+ }+ Rectangle {+ width: parent.width * 0.76+ height: 3.6 * preview.s+ radius: height / 2+ color: preview.faint+ }+ }++ Rectangle {+ x: 7.2 * preview.s+ y: parent.height - 7.2 * preview.s - height+ width: 41.9 * preview.s+ height: 13.2 * preview.s+ radius: 3.6 * preview.s+ color: preview.theme.accent+ }++ Rectangle {+ x: parent.width - 7.2 * preview.s - width+ y: parent.height - 7.2 * preview.s - 13.2 * preview.s + (13.2 - 10.8) / 2 * preview.s+ width: 20.3 * preview.s+ height: 10.8 * preview.s+ radius: height / 2+ color: preview.theme.accent++ Rectangle {+ anchors.right: parent.right+ anchors.rightMargin: 2.4 * preview.s+ anchors.verticalCenter: parent.verticalCenter+ width: 6 * preview.s+ height: width+ radius: width / 2+ color: preview.theme.textOnAccent+ }+ }+ }++ Rectangle {+ id: bar+ anchors.left: parent.left+ anchors.right: parent.right+ anchors.bottom: parent.bottom+ height: 13.2 * preview.s+ color: preview.taskbar++ Row {+ anchors.centerIn: parent+ spacing: 3.6 * preview.s+ Repeater {+ model: 6+ Rectangle {+ required property int index+ width: 6 * preview.s+ height: width+ radius: 1.8 * preview.s+ color: index === 2 ? preview.theme.accent : preview.faint+ }+ }+ }+ }++ // The underglow along the top of the taskbar, for themes that+ // bring it: a bright line with a soft glow either side.+ Rectangle {+ visible: preview.theme.underglow+ anchors.left: parent.left+ anchors.right: parent.right+ y: bar.y - height / 2 - 0.6 * preview.s+ height: 6 * preview.s+ gradient: Gradient {+ GradientStop { position: 0; color: "transparent" }+ GradientStop { position: 0.5; color: Qt.rgba(preview.theme.accent.r, preview.theme.accent.g, preview.theme.accent.b, 0.45) }+ GradientStop { position: 1; color: "transparent" }+ }+ }+ Rectangle {+ visible: preview.theme.underglow+ anchors.left: parent.left+ anchors.right: parent.right+ y: bar.y - height+ height: Math.max(1, 1.2 * preview.s)+ color: preview.theme.accent+ }+ }++ Rectangle {+ id: mask+ anchors.fill: parent+ radius: preview.radius+ visible: false+ layer.enabled: true+ }++ MultiEffect {+ anchors.fill: parent+ source: scene+ maskEnabled: true+ maskSource: mask+ }++ Rectangle {+ anchors.fill: parent+ radius: preview.radius+ color: "transparent"+ border.width: 1+ border.color: UI.Style.borderField+ }+}diff --git a/packages/wildos-settings/qml/pages/AccessibilityPage.qml b/packages/wildos-settings/qml/pages/AccessibilityPage.qmlindex 23d7118..6644747 100644--- a/packages/wildos-settings/qml/pages/AccessibilityPage.qml+++ b/packages/wildos-settings/qml/pages/AccessibilityPage.qml@@ -20,6 +20,11 @@ PageScroll {return on ? "On" : "Off";}+ readonly property var blurSteps: ["Lightest", "Light", "Medium", "Strong", "Strongest"]+ readonly property string windowEffectsReason: Accessibility.windowEffectsInstalled+ ? "This needs graphics acceleration, which this computer isn't using"+ : "The window effects aren't installed on this computer"+Component.onCompleted: {Accessibility.refresh();Accessibility.refreshMagnifier();@@ -205,6 +210,91 @@ PageScroll {onToggled: Accessibility.setHighContrast(checked)}}++ UI.SettingRow {+ title: "Outline windows"+ description: "A clear edge round every window, and a thick one round the window you're using"+ status: page.onOff(Accessibility.outlineWindows)++ UI.Toggle {+ anchors.verticalCenter: parent.verticalCenter+ checked: Accessibility.outlineWindows+ locked: !Accessibility.windowEffectsSupported+ lockedReason: page.windowEffectsReason+ Accessible.name: "Outline windows"+ onToggled: Accessibility.setOutlineWindows(checked)+ }+ }++ UI.SettingRow {+ title: "Stronger text on glass"+ description: "Solid backing and brighter text on the taskbar, Start, flyouts and Wild OS apps"+ status: page.onOff(Accessibility.strongerText)++ UI.Toggle {+ anchors.verticalCenter: parent.verticalCenter+ checked: Accessibility.strongerText+ Accessible.name: "Stronger text on glass"+ onToggled: Accessibility.setStrongerText(checked)+ }+ }++ UI.SettingRow {+ title: "Blur windows in the background"+ description: "Every window but the one you're using goes soft and a little darker"+ status: page.onOff(Accessibility.blurBackground)++ UI.Toggle {+ anchors.verticalCenter: parent.verticalCenter+ checked: Accessibility.blurBackground+ locked: !Accessibility.windowEffectsSupported+ lockedReason: page.windowEffectsReason+ Accessible.name: "Blur windows in the background"+ onToggled: Accessibility.setBlurBackground(checked)+ }+ }++ UI.SettingRow {+ visible: Accessibility.blurBackground && Accessibility.windowEffectsSupported+ title: "Blur strength"+ status: page.blurSteps[Math.round(blurStrength.value) - 1]++ UI.Slider {+ id: blurStrength+ anchors.verticalCenter: parent.verticalCenter+ implicitWidth: 140+ implicitHeight: 20+ flat: true+ from: 1+ to: page.blurSteps.length+ stepSize: 1+ snapMode: T.Slider.SnapAlways+ wheelEnabled: false+ value: Accessibility.blurStrength+ accessibleName: "Blur strength"+ Accessible.description: page.blurSteps[Math.round(value) - 1]+ // KWin redraws the blur at each step, so dragging+ // shows each strength as it is passed.+ onMoved: {+ Accessibility.setBlurStrength(Math.round(value));+ value = Qt.binding(() => Accessibility.blurStrength);+ }+ }+ }++ UI.SettingRow {+ visible: Accessibility.blurBackground && Accessibility.windowEffectsSupported+ title: "Blur the desktop too"+ description: "Whenever a window is in use"+ status: page.onOff(Accessibility.blurDesktop)++ UI.Toggle {+ anchors.verticalCenter: parent.verticalCenter+ checked: Accessibility.blurDesktop+ Accessible.name: "Blur the desktop too"+ onToggled: Accessibility.setBlurDesktop(checked)+ }+ }}}}diff --git a/packages/wildos-settings/qml/pages/ColoursPage.qml b/packages/wildos-settings/qml/pages/ColoursPage.qmlindex b30bbb5..0dd7f47 100644--- a/packages/wildos-settings/qml/pages/ColoursPage.qml+++ b/packages/wildos-settings/qml/pages/ColoursPage.qml@@ -48,7 +48,7 @@ PageScroll {Layout.fillWidth: truetext: {const chosen = UI.Style.accents.find(a => Qt.colorEqual(a.colour, System.accent));- return chosen ? chosen.name : "Your own colour";+ return chosen ? chosen.name : Themes.accentName(System.accent) || "Your own colour";}color: UI.Style.inkMuted}diff --git a/packages/wildos-settings/qml/pages/DisplayPage.qml b/packages/wildos-settings/qml/pages/DisplayPage.qmlindex 988fb31..40d0db4 100644--- a/packages/wildos-settings/qml/pages/DisplayPage.qml+++ b/packages/wildos-settings/qml/pages/DisplayPage.qml@@ -603,7 +603,7 @@ PageScroll {UI.Label {Layout.fillWidth: truevisible: Displays.available- text: "Changes to resolution and refresh rate show a preview and switch back on their own after 15 seconds unless you choose Keep."+ text: "Changes to resolution, refresh rate and HDR show a preview and switch back on their own after 15 seconds unless you choose Keep."size: 12color: UI.Style.inkMutedlineHeight: 1.5@@ -708,6 +708,25 @@ PageScroll {}}}++ // Only PCs with an NVIDIA card have a choice of driver.+ UI.Card {+ Layout.fillWidth: true+ visible: Graphics.hasNvidia++ Column {+ width: parent.width++ UI.SettingRow {+ iconName: "chip"+ title: "Graphics driver"+ description: Graphics.nvidiaName+ status: Graphics.restartNeeded ? "Restart needed" : Graphics.driverInUse === "nvidia" ? "NVIDIA" : "Open"+ chevron: true+ onClicked: Navigator.open("graphicsdriver")+ }+ }+ }}// Identify: each screen's number, large in its bottom left corner, fordiff --git a/packages/wildos-settings/qml/pages/GraphicsDriverPage.qml b/packages/wildos-settings/qml/pages/GraphicsDriverPage.qmlnew file mode 100644index 0000000..e4b676a--- /dev/null+++ b/packages/wildos-settings/qml/pages/GraphicsDriverPage.qml@@ -0,0 +1,177 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Settings+import WildOS.UI as UI++// Display > Graphics driver, shown on PCs with an NVIDIA card: the open+// driver Wild OS ships, or NVIDIA's own from Debian (Graphics,+// settings-graphics-driver). Everything happens here; with Secure Boot on,+// the one step outside Wild OS is typing a code into the firmware's own blue+// screen at the next restart, so the page shows that code and what to press.+PageScroll {+ id: page++ // What the cards show as chosen: what is installed, until a card is picked.+ property string choice: Graphics.nvidiaInstalled ? "nvidia" : "open"+ readonly property string installed: Graphics.nvidiaInstalled ? "nvidia" : "open"++ Notice {+ id: notice+ Layout.fillWidth: true+ }++ Connections {+ target: Graphics+ function onChanged() {+ if (!Graphics.busy && Graphics.error.length > 0) {+ notice.show("The driver was not changed", Graphics.error, true);+ page.choice = page.installed;+ }+ }+ }++ UI.Card {+ Layout.fillWidth: true++ Column {+ width: parent.width++ UI.SettingRow {+ iconName: "chip"+ title: Graphics.nvidiaName+ description: Graphics.driverInUse === "nvidia" ? "Using NVIDIA's driver"+ : Graphics.driverInUse === "nouveau" ? "Using the open driver"+ : "No driver is using it yet"+ }+ }+ }++ ColumnLayout {+ Layout.fillWidth: true+ spacing: 10++ SectionTitle {+ text: "Driver"+ }++ UI.ChoiceCard {+ Layout.fillWidth: true+ title: "Open driver (built in)"+ description: "Comes with Wild OS and works on every NVIDIA card. Fine for everyday use, slower in games and 3D."+ showIndicator: true+ checkable: false+ checked: page.choice === "open"+ enabled: !Graphics.busy+ onClicked: page.choice = "open"+ }++ UI.ChoiceCard {+ Layout.fillWidth: true+ title: "NVIDIA's driver"+ description: "Much faster in games and 3D. Made by NVIDIA, closed source, installed from Debian. Supports GeForce GTX 900 series cards up to RTX 40 series; RTX 50 cards keep the open driver for now."+ showIndicator: true+ checkable: false+ checked: page.choice === "nvidia"+ enabled: !Graphics.busy+ onClicked: page.choice = "nvidia"+ }++ UI.Button {+ visible: page.choice !== page.installed && !Graphics.busy+ text: page.choice === "nvidia" ? "Install NVIDIA's driver" : "Go back to the open driver"+ onClicked: Graphics.useDriver(page.choice)+ }+ }++ // While the helper works: its step, under a bar that moves.+ UI.Card {+ Layout.fillWidth: true+ visible: Graphics.busy++ ColumnLayout {+ width: parent.width+ spacing: 10++ UI.Label {+ Layout.fillWidth: true+ text: Graphics.step + "…"+ wrapMode: Text.WordWrap+ }++ UI.ProgressBar {+ Layout.fillWidth: true+ indeterminate: true+ }++ UI.Label {+ Layout.fillWidth: true+ text: "This takes a few minutes. You can keep using the PC."+ size: 13+ color: UI.Style.inkMuted+ wrapMode: Text.WordWrap+ }+ }+ }++ // Secure Boot: the module was built on this PC, so the firmware has to be+ // told to trust this PC's key. It asks once, at the next restart.+ UI.Card {+ Layout.fillWidth: true+ visible: !Graphics.busy && Graphics.enrolCode.length > 0++ ColumnLayout {+ width: parent.width+ spacing: 12++ UI.Label {+ Layout.fillWidth: true+ text: "One more step at the next restart"+ font.weight: Font.DemiBold+ wrapMode: Text.WordWrap+ }++ UI.Label {+ Layout.fillWidth: true+ text: "Secure Boot is on, so your PC needs to trust the key that signed NVIDIA's driver. When it restarts, a blue screen appears before Wild OS. Press a key to continue, then choose Enroll MOK, Continue and Yes, type this code and press Enter, then choose Reboot."+ wrapMode: Text.WordWrap+ color: UI.Style.inkMuted+ }++ UI.Label {+ text: Graphics.enrolCode+ size: 28+ font.weight: Font.DemiBold+ font.letterSpacing: 3+ }++ UI.Label {+ Layout.fillWidth: true+ text: "Nothing appears on screen as you type it. If the blue screen goes by, Wild OS starts with basic graphics until the key is enrolled. Install again from here to get a new code."+ size: 13+ color: UI.Style.inkMuted+ wrapMode: Text.WordWrap+ }+ }+ }++ UI.Card {+ Layout.fillWidth: true+ visible: !Graphics.busy && Graphics.restartNeeded++ Column {+ width: parent.width++ UI.SettingRow {+ iconName: "restart"+ title: "Restart to finish"+ description: Graphics.nvidiaInstalled ? "The PC starts with NVIDIA's driver after a restart." : "The PC starts with the open driver after a restart."++ UI.Button {+ anchors.verticalCenter: parent.verticalCenter+ text: "Restart now"+ onClicked: Updates.restart()+ }+ }+ }+ }+}diff --git a/packages/wildos-settings/qml/pages/MultitaskingPage.qml b/packages/wildos-settings/qml/pages/MultitaskingPage.qmlindex 2534aa2..0e89b73 100644--- a/packages/wildos-settings/qml/pages/MultitaskingPage.qml+++ b/packages/wildos-settings/qml/pages/MultitaskingPage.qml@@ -3,21 +3,49 @@ import QtQuick.Layoutsimport WildOS.Settingsimport WildOS.UI as UI-// Multitasking: snapping, Alt+Tab and the taskbar across desktops. The-// snapping and Alt+Tab switches write kwinrc and ask KWin to reload, so the-// change applies without signing out; the taskbar choice is the taskbar's-// own setting, changed through plasmashell.+// Multitasking: snapping, screen corners, Alt+Tab and the taskbar across+// desktops. The snapping, corner and Alt+Tab settings write kwinrc and ask+// KWin to reload, so the change applies without signing out; the taskbar+// choice is the taskbar's own setting, changed through plasmashell.PageScroll {id: pageComponent.onCompleted: System.readTaskbarDesktops()+ readonly property var cornerActions: [+ { value: "taskview", text: "Task view" },+ { value: "desktop", text: "Show the desktop" },+ { value: "lock", text: "Lock the screen" },+ { value: "none", text: "Nothing" }+ ]+UI.Card {Layout.fillWidth: trueColumn {width: parent.width+ UI.SettingRow {+ title: "Double-clicking a title bar will"++ UI.ComboBox {+ anchors.verticalCenter: parent.verticalCenter+ Accessible.name: "Double-clicking a title bar will"+ model: [+ { value: "Maximize", text: "Maximise or restore" },+ { value: "Minimize", text: "Minimise" },+ { value: "Nothing", text: "Do nothing" }+ ]+ property string choice: System.config("kwinrc", "MouseBindings", "CommandTitlebarDblClick", "Maximize")+ currentIndex: Math.max(0, model.findIndex(o => o.value === choice))+ onActivated: index => {+ System.setConfig("kwinrc", "MouseBindings", "CommandTitlebarDblClick", model[index].value);+ System.reloadKWin();+ choice = model[index].value;+ }+ }+ }+UI.SettingRow {iconName: "multitasking"title: "Snap windows"@@ -45,6 +73,61 @@ PageScroll {onToggled: System.snapLayouts = checked}}++ UI.SettingRow {+ iconName: "split-right"+ title: "Suggest windows to fill the rest"+ description: "After you snap a window, pick other open windows to fill the empty spaces beside it"+ status: (System.snapAssist) ? "On" : "Off"++ UI.Toggle {+ anchors.verticalCenter: parent.verticalCenter+ checked: System.snapAssist+ Accessible.name: "Suggest windows to fill the rest"+ onToggled: System.snapAssist = checked+ }+ }+ }+ }++ ColumnLayout {+ Layout.fillWidth: true+ spacing: 10++ SectionTitle {+ text: "Screen corners"+ }++ UI.Card {+ Layout.fillWidth: true++ Column {+ width: parent.width++ Repeater {+ model: [+ { corner: 7, title: "Top left corner" },+ { corner: 1, title: "Top right corner" },+ { corner: 5, title: "Bottom left corner" },+ { corner: 3, title: "Bottom right corner" }+ ]++ UI.SettingRow {+ id: cornerRow+ required property var modelData+ title: modelData.title++ UI.ComboBox {+ anchors.verticalCenter: parent.verticalCenter+ Accessible.name: cornerRow.modelData.title+ model: page.cornerActions+ readonly property string choice: System.screenCorners[String(cornerRow.modelData.corner)] ?? "none"+ currentIndex: model.findIndex(o => o.value === choice)+ onActivated: index => System.setScreenCorner(cornerRow.modelData.corner, model[index].value)+ }+ }+ }+ }}}diff --git a/packages/wildos-settings/qml/pages/NetworkAdvancedPage.qml b/packages/wildos-settings/qml/pages/NetworkAdvancedPage.qmlindex 258b61c..ba4987b 100644--- a/packages/wildos-settings/qml/pages/NetworkAdvancedPage.qml+++ b/packages/wildos-settings/qml/pages/NetworkAdvancedPage.qml@@ -134,7 +134,11 @@ PageScroll {if (!kbits) {return "";}- return kbits >= 1000000 ? (kbits / 1000000).toFixed(1).replace(/\.0$/, "") + " Gbps" : Math.round(kbits / 1000) + " Mbps";+ if (kbits < 1000000) {+ return Math.round(kbits / 1000) + " Mbps";+ }+ const gbps = Number((kbits / 1000000).toFixed(1));+ return gbps.toLocaleString(Qt.locale(), "f", gbps % 1 === 0 ? 0 : 1) + " Gbps";}function frequencyText(mhz) {diff --git a/packages/wildos-settings/qml/pages/NotificationsPage.qml b/packages/wildos-settings/qml/pages/NotificationsPage.qmlindex 45f4565..a483afe 100644--- a/packages/wildos-settings/qml/pages/NotificationsPage.qml+++ b/packages/wildos-settings/qml/pages/NotificationsPage.qml@@ -49,6 +49,30 @@ PageScroll {now = Date.now();}+ // Quiet hours live in wildosrc; the taskbar's quick settings checks them+ // once a minute and turns do not disturb on until the end time, so it+ // still ends on time if Settings is closed.+ property int quietRevision: 0+ readonly property bool quietHours: { quietRevision; return System.config("wildosrc", "QuietHours", "Enabled", false); }+ readonly property string quietFrom: { quietRevision; return System.config("wildosrc", "QuietHours", "From", "2200"); }+ readonly property string quietTo: { quietRevision; return System.config("wildosrc", "QuietHours", "To", "0700"); }++ function setQuiet(key, value) {+ System.setConfig("wildosrc", "QuietHours", key, value);+ quietRevision++;+ }++ function hours() {+ const list = [];+ for (let h = 0; h < 24; ++h) {+ for (const m of [0, 30]) {+ const text = (h < 10 ? "0" : "") + h + ":" + (m === 0 ? "00" : "30");+ list.push({ value: text.replace(":", ""), text: text });+ }+ }+ return list;+ }+UI.Card {Layout.fillWidth: true@@ -69,6 +93,47 @@ PageScroll {}}+ UI.SettingRow {+ title: "Turn on do not disturb automatically at set times"+ description: "Quiet hours, for example overnight. You can still turn it off early"+ status: (page.quietHours) ? "On" : "Off"++ UI.Toggle {+ anchors.verticalCenter: parent.verticalCenter+ checked: page.quietHours+ Accessible.name: "Turn on do not disturb automatically at set times"+ onToggled: page.setQuiet("Enabled", checked)+ }+ }++ UI.SettingRow {+ visible: page.quietHours+ title: "From"++ UI.ComboBox {+ anchors.verticalCenter: parent.verticalCenter+ Accessible.name: "Quiet hours start"+ model: page.hours()+ readonly property var choice: page.quietFrom+ currentIndex: model ? model.findIndex(o => o.value === choice) : -1+ onActivated: index => page.setQuiet("From", model[index].value)+ }+ }++ UI.SettingRow {+ visible: page.quietHours+ title: "To"++ UI.ComboBox {+ anchors.verticalCenter: parent.verticalCenter+ Accessible.name: "Quiet hours end"+ model: page.hours()+ readonly property var choice: page.quietTo+ currentIndex: model ? model.findIndex(o => o.value === choice) : -1+ onActivated: index => page.setQuiet("To", model[index].value)+ }+ }+UI.SettingRow {title: "Turn on do not disturb automatically when sharing or mirroring the screen"description: "So alerts never show during a presentation"diff --git a/packages/wildos-settings/qml/pages/PersonalisationPage.qml b/packages/wildos-settings/qml/pages/PersonalisationPage.qmlindex 301737b..dd58ffc 100644--- a/packages/wildos-settings/qml/pages/PersonalisationPage.qml+++ b/packages/wildos-settings/qml/pages/PersonalisationPage.qml@@ -252,7 +252,7 @@ PageScroll {width: parent.widthRepeater {- model: ["background", "lockscreen", "taskbar", "fonts"]+ model: ["themes", "background", "lockscreen", "taskbar", "fonts"]UI.SettingRow {required property string modelDatadiff --git a/packages/wildos-settings/qml/pages/PowerPage.qml b/packages/wildos-settings/qml/pages/PowerPage.qmlindex b43aa00..e9a20e8 100644--- a/packages/wildos-settings/qml/pages/PowerPage.qml+++ b/packages/wildos-settings/qml/pages/PowerPage.qml@@ -128,6 +128,68 @@ PageScroll {}}+ // Hyper-threading, for the whole PC: Linux apps and games as well as+ // Windows mode. A boot option, so a change offers a restart.+ UI.Card {+ id: threadsCard+ Layout.fillWidth: true+ visible: Processor.threadsAvailable+ readonly property bool pending: Processor.everyThread !== Processor.everyThreadActive++ Column {+ width: parent.width++ UI.SettingRow {+ iconName: "chip"+ title: "Use every processor thread"+ description: Processor.everyThreadLocked+ ? "Off at Strict and Maximum protection, which keep every CPU flaw protection on."+ : threadsCard.pending+ ? "Restart to finish turning it " + (Processor.everyThread ? "on." : "off.")+ : "Faster heavy apps, one less CPU-flaw protection for the whole PC. Needs a restart."++ UI.Toggle {+ id: threadsToggle+ anchors.verticalCenter: parent.verticalCenter+ checked: Processor.everyThread && !Processor.everyThreadLocked+ enabled: !Processor.busy && !Processor.everyThreadLocked+ locked: Processor.everyThreadLocked+ lockedReason: "Strict and Maximum protection keep this off"+ Accessible.name: "Use every processor thread"+ onToggled: Processor.setEveryThread(checked)+ }+ }++ UI.SettingRow {+ visible: threadsCard.pending && !Processor.everyThreadLocked+ title: "Restart to apply"+ description: "Open apps are asked to save first."++ UI.Button {+ anchors.verticalCenter: parent.verticalCenter+ text: "Restart now"+ onClicked: Updates.restart()+ }+ }+ }++ Connections {+ target: Processor+ // A cancelled password leaves the choice as it was, so the switch goes back to it.+ function onChanged() { threadsToggle.checked = Processor.everyThread && !Processor.everyThreadLocked }+ function onFailed(message) { threadsError.text = message }+ }+ }++ UI.Label {+ id: threadsError+ visible: text.length > 0 && Processor.threadsAvailable+ Layout.fillWidth: true+ wrapMode: Text.WordWrap+ size: 13+ color: UI.Style.warning+ }+ColumnLayout {Layout.fillWidth: truespacing: 10diff --git a/packages/wildos-settings/qml/pages/PrivacyPage.qml b/packages/wildos-settings/qml/pages/PrivacyPage.qmlindex b80fe39..86af6d0 100644--- a/packages/wildos-settings/qml/pages/PrivacyPage.qml+++ b/packages/wildos-settings/qml/pages/PrivacyPage.qml@@ -97,8 +97,8 @@ PageScroll {}}- // Standard is what Wild OS ships. Strict adds a firewall and holds back- // unknown USB devices found at start-up; Maximum also blocks network+ // Standard is what Wild OS ships, firewall included. Strict also holds+ // back unknown USB devices found at start-up; Maximum also blocks network// discovery, Bluetooth and the camera (settings-protection). Both// shorten the screen lock.ColumnLayout {@@ -293,7 +293,7 @@ PageScroll {minHeight: 64title: "Block new USB devices"description: page.usbError.length > 0 ? page.usbError- : "Stops anything plugged in from working until you allow it from the shield on the taskbar."+ : "Memory sticks, drives, a keyboard, a mouse, webcams and audio devices work straight away. Anything else waits until you allow it from the shield on the taskbar."status: (Protection.status.devices === "on") ? "On" : "Off"UI.Toggle {diff --git a/packages/wildos-settings/qml/pages/SoundPage.qml b/packages/wildos-settings/qml/pages/SoundPage.qmlindex 117ad84..131ac48 100644--- a/packages/wildos-settings/qml/pages/SoundPage.qml+++ b/packages/wildos-settings/qml/pages/SoundPage.qml@@ -251,6 +251,9 @@ PageScroll {readonly property var output: PreferredDevice.sink && PreferredDevice.sink.name !== "auto_null" ? PreferredDevice.sink : nullreadonly property var input: PreferredDevice.source+ // The microphone is only opened while someone tests it, never just+ // because the page is open.+ property bool testingMic: false// Windows mode's apps all play through its one FreeRDP connection,// whose PulseAudio backend names itself "freerdp" (rdpsnd_pulse.c) and@@ -382,21 +385,28 @@ PageScroll {UI.SettingRow {title: "Microphone"- description: page.input ? page.inputInfo(page.input).phrase + ". Speak to test it." : "No microphone found"+ description: !page.input ? "No microphone found"+ : page.testingMic ? page.inputInfo(page.input).phrase + ". Listening, speak to test it."+ : page.inputInfo(page.input).phraseminHeight: 54- // The level of whatever the microphone hears. It lives- // in the row, so it starts with the page and stops when- // the page goes; plasma-pa keeps its own stream out of- // the taskbar's "microphone in use" mark.+ // The level of whatever the microphone hears, only while+ // a test runs: with no target the monitor opens no+ // stream. Leaving the page ends it too.VolumeMonitor {id: micLevel- target: page.input+ target: page.testingMic ? page.input : null+ }++ Timer {+ running: page.testingMic+ interval: 15000+ onTriggered: page.testingMic = false}Row {anchors.verticalCenter: parent.verticalCenter- visible: page.input !== null+ visible: page.input !== null && page.testingMicspacing: 3Accessible.role: Accessible.IndicatorAccessible.name: "Microphone level"@@ -420,6 +430,14 @@ PageScroll {}}+ UI.Button {+ anchors.verticalCenter: parent.verticalCenter+ visible: page.input !== null+ text: page.testingMic ? "Stop" : "Test"+ Accessible.name: page.testingMic ? "Stop testing the microphone" : "Test the microphone"+ onClicked: page.testingMic = !page.testingMic+ }+UI.ComboBox {anchors.verticalCenter: parent.verticalCentervisible: page.inputs.length > 0@@ -480,6 +498,61 @@ PageScroll {}}+ ColumnLayout {+ Layout.fillWidth: true+ spacing: 10++ SectionTitle {+ text: "Sounds"+ }++ UI.Card {+ Layout.fillWidth: true++ Column {+ width: parent.width++ UI.SettingRow {+ iconName: "sound"+ title: "Sound scheme"+ description: "The sounds for notifications, warnings, devices and more"++ UI.ComboBox {+ anchors.verticalCenter: parent.verticalCenter+ Accessible.name: "Sound scheme"+ model: [+ { value: "wildos", text: "Wild OS" },+ { value: "ocean", text: "Ocean (KDE)" },+ { value: "none", text: "No sounds" }+ ]+ currentIndex: model.findIndex(o => o.value === SoundTheme.scheme)+ onActivated: index => SoundTheme.setScheme(model[index].value)+ }+ }++ UI.SettingRow {+ iconName: "power"+ title: "Play a sound when Wild OS starts"+ description: "When the desktop appears after you sign in"+ status: SoundTheme.startupSound ? "On" : "Off"+ enabled: SoundTheme.scheme !== "none"++ UI.Toggle {+ anchors.verticalCenter: parent.verticalCenter+ checked: SoundTheme.startupSound+ Accessible.name: "Play a sound when Wild OS starts"+ onToggled: {+ SoundTheme.setStartupSound(checked);+ if (checked) {+ SoundTheme.preview("desktop-login");+ }+ }+ }+ }+ }+ }+ }+// The percentage beside a slider keeps its place as the digits change.component Percent: UI.Label {width: 34diff --git a/packages/wildos-settings/qml/pages/TaskbarPage.qml b/packages/wildos-settings/qml/pages/TaskbarPage.qmlindex 2f6bdb3..1a98404 100644--- a/packages/wildos-settings/qml/pages/TaskbarPage.qml+++ b/packages/wildos-settings/qml/pages/TaskbarPage.qml@@ -3,17 +3,38 @@ import QtQuick.Layoutsimport WildOS.Settingsimport WildOS.UI as UI-// Taskbar behaviour. The panel is changed through Plasma's own scripting-// interface, so the setting takes effect at once and survives restarts.+// Taskbar behaviour and items. The panel is changed through Plasma's own+// scripting interface, so the setting takes effect at once and survives+// restarts.PageScroll {id: page+ Component.onCompleted: System.readTaskbarWinModeStatus()+readonly property var choices: [{ mode: 0, title: "Always show the taskbar", description: "Windows stop above it" },{ mode: 1, title: "Hide the taskbar automatically", description: "Move the pointer to the bottom of the screen to show it" },{ mode: 2, title: "Hide it when a window covers it", description: "It stays visible until a window needs the space" }]+ // Clock and battery choices live in wildosrc [Taskbar]; the taskbar+ // watches the file and follows straight away.+ property int revision: 0+ function taskbarOption(key) {+ revision;+ return System.config("wildosrc", "Taskbar", key, false);+ }+ function setTaskbarOption(key, on) {+ System.setConfig("wildosrc", "Taskbar", key, on);+ revision++;+ }++ readonly property var clockOptions: [+ { key: "ClockSeconds", title: "Show seconds in the clock" },+ { key: "ClockLongDate", title: "Show the full date", description: "The day of the week and the month written out" },+ { key: "BatteryPercent", title: "Show battery percentage", description: "Beside the battery icon, on computers with a battery" }+ ]+ColumnLayout {Layout.fillWidth: truespacing: 10@@ -52,5 +73,85 @@ PageScroll {}}}++ UI.Card {+ Layout.fillWidth: true++ Column {+ width: parent.width++ UI.SettingRow {+ title: "Show the desktop from the taskbar's far corner"+ description: "Click the right end of the taskbar to show the desktop, and again to bring your windows back"+ status: (System.taskbarShowDesktop) ? "On" : "Off"++ UI.Toggle {+ anchors.verticalCenter: parent.verticalCenter+ checked: System.taskbarShowDesktop+ Accessible.name: "Show the desktop from the taskbar's far corner"+ onToggled: System.taskbarShowDesktop = checked+ }+ }++ UI.SettingRow {+ title: "Peek at the desktop"+ description: "Rest the pointer on that corner to see the desktop until you move away"+ status: (System.taskbarPeek) ? "On" : "Off"+ enabled: System.taskbarShowDesktop++ UI.Toggle {+ anchors.verticalCenter: parent.verticalCenter+ checked: System.taskbarPeek+ Accessible.name: "Peek at the desktop"+ onToggled: System.taskbarPeek = checked+ }+ }+ }+ }++ SectionTitle {+ text: "Taskbar items"+ }++ UI.Card {+ Layout.fillWidth: true++ Column {+ width: parent.width++ UI.SettingRow {+ iconName: "windowsapps"+ title: "Show Windows mode status on the taskbar"+ description: "Once Windows mode is set up: whether it's running and the memory it holds"+ status: (System.taskbarWinModeStatus) ? "On" : "Off"++ UI.Toggle {+ anchors.verticalCenter: parent.verticalCenter+ checked: System.taskbarWinModeStatus+ Accessible.name: "Show Windows mode status on the taskbar"+ onToggled: System.setTaskbarWinModeStatus(checked)+ }+ }++ Repeater {+ model: page.clockOptions++ UI.SettingRow {+ id: optionRow+ required property var modelData+ title: modelData.title+ description: modelData.description ?? ""+ status: page.taskbarOption(modelData.key) ? "On" : "Off"++ UI.Toggle {+ anchors.verticalCenter: parent.verticalCenter+ checked: page.taskbarOption(optionRow.modelData.key)+ Accessible.name: optionRow.modelData.title+ onToggled: page.setTaskbarOption(optionRow.modelData.key, checked)+ }+ }+ }+ }+ }}}diff --git a/packages/wildos-settings/qml/pages/ThemesPage.qml b/packages/wildos-settings/qml/pages/ThemesPage.qmlnew file mode 100644index 0000000..1c2979a--- /dev/null+++ b/packages/wildos-settings/qml/pages/ThemesPage.qml@@ -0,0 +1,293 @@+pragma ComponentBehavior: Bound++import QtQuick+import QtQuick.Layouts+import QtQuick.Templates as T+import WildOS.Settings+import WildOS.UI as UI++// Themes, laid out as SettingsThemes.dc: the six themes three to a row,+// then the wallpaper and, for a theme that brings it (Overclock) or once the+// person has turned it on, the taskbar underglow and keyboard and mouse+// lighting (UnderglowOptions.dc). A theme sets the wallpaper, light or dark,+// the accent and the glass at once; each can still be changed on its own+// page afterwards.+PageScroll {+ id: page++ readonly property var theme: Themes.currentTheme+ readonly property bool underglowShown: (theme.underglow || false) || Themes.underglow+ readonly property bool custom: Themes.underglowColour === "custom"++ Component.onCompleted: Themes.refreshRgbDevices()++ GridLayout {+ Layout.fillWidth: true+ columns: 3+ columnSpacing: 18+ rowSpacing: 16+ Accessible.role: Accessible.Grouping+ Accessible.name: "Theme"++ Repeater {+ model: Themes.themes++ T.AbstractButton {+ id: card++ required property var modelData+ readonly property bool selected: Themes.current === modelData.id++ Layout.fillWidth: true+ Layout.preferredWidth: 1+ implicitHeight: frame.height + 8 + nameRow.implicitHeight+ padding: 0+ hoverEnabled: true+ focusPolicy: Qt.StrongFocus+ Accessible.role: Accessible.RadioButton+ Accessible.name: modelData.name+ Accessible.description: modelData.description+ Accessible.checked: selected+ onClicked: Themes.apply(modelData.id)++ UI.Tooltip {+ text: card.modelData.description+ visible: card.hovered && card.modelData.description.length > 0+ }++ background: Item {+ Rectangle {+ id: frame+ width: parent.width+ height: Math.round((width - 8) * 124 / 250) + 8+ radius: UI.Style.radiusMd+ color: "transparent"+ border.width: card.selected ? 2 : 1+ border.color: card.selected ? UI.Style.accent : card.hovered ? UI.Style.borderControl : UI.Style.borderGlass+ Behavior on border.color {+ ColorAnimation { duration: UI.Style.hoverDuration }+ }++ ThemePreview {+ anchors.fill: parent+ anchors.margins: 4+ theme: card.modelData+ }++ UI.FocusRing {+ visible: card.visualFocus+ anchors.margins: -3+ targetRadius: UI.Style.radiusMd + 3+ }+ }++ RowLayout {+ id: nameRow+ anchors.left: parent.left+ anchors.right: parent.right+ anchors.top: frame.bottom+ anchors.topMargin: 8+ spacing: 8++ UI.Label {+ Layout.fillWidth: true+ text: card.modelData.name+ size: 13+ font.weight: card.selected ? Font.DemiBold : Font.Medium+ }++ Rectangle {+ Layout.preferredWidth: 12+ Layout.preferredHeight: 12+ radius: 6+ color: card.modelData.accent+ border.width: 1+ border.color: UI.Style.tone(0.20)+ Accessible.ignored: true+ }+ }+ }+ }+ }+ }++ UI.Card {+ Layout.fillWidth: true++ Column {+ width: parent.width++ UI.SettingRow {+ title: "Wallpaper"+ description: {+ const more = page.theme.moreWallpaperNames || [];+ const also = more.length === 0 ? ""+ : more.length === 1 ? " " + more[0] + " is also included."+ : " " + more.slice(0, -1).join(", ") + " and " + more[more.length - 1] + " are also included.";+ return System.wallpaperName + "." + also;+ }++ UI.Button {+ anchors.verticalCenter: parent.verticalCenter+ size: "small"+ text: "Change"+ Accessible.name: "Change wallpaper"+ onClicked: Navigator.open("background")+ }+ }++ UI.SettingRow {+ visible: page.underglowShown && Themes.rgbDevices > 0+ title: "Lighting on RGB keyboards and mice"+ description: "Matches the underglow on most gaming keyboards, mice and laptops"+ status: Themes.lightingRgb ? "On" : "Off"++ UI.Toggle {+ anchors.verticalCenter: parent.verticalCenter+ checked: Themes.lightingRgb+ Accessible.name: "Lighting on RGB keyboards and mice"+ onToggled: Themes.setLightingRgb(checked)+ }+ }++ UI.SettingRow {+ visible: page.underglowShown+ title: "Taskbar underglow"+ description: "A thin line of light along the top of the taskbar"+ status: Themes.underglow ? "On" : "Off"++ UI.Toggle {+ anchors.verticalCenter: parent.verticalCenter+ checked: Themes.underglow+ Accessible.name: "Taskbar underglow"+ onToggled: Themes.setUnderglow(checked)+ }+ }++ UI.SettingRow {+ visible: page.underglowShown && Themes.underglow+ title: "Underglow colour and effect"+ description: Themes.rgbDevices > 0 && Themes.lightingRgb+ ? "Keyboard and mouse lighting copies these"+ : "Your accent, a colour of your own, or every colour in turn"++ UI.ComboBox {+ anchors.verticalCenter: parent.verticalCenter+ Accessible.name: "Underglow colour"+ model: [+ { value: "accent", text: "Accent" },+ { value: "rgb", text: "RGB" },+ { value: "custom", text: "Custom" }+ ]+ readonly property string choice: Themes.underglowColour+ currentIndex: model.findIndex(o => o.value === choice)+ onActivated: index => Themes.setUnderglowColour(model[index].value)+ }++ UI.ComboBox {+ anchors.verticalCenter: parent.verticalCenter+ Accessible.name: "Underglow effect"+ // RGB flows along the bar; a single colour is steady or+ // breathes.+ model: Themes.underglowColour === "rgb"+ ? [{ value: "flowing", text: "Flowing" }]+ : [{ value: "steady", text: "Steady" }, { value: "breathing", text: "Breathing" }]+ readonly property string choice: Themes.underglowEffect+ currentIndex: model.findIndex(o => o.value === choice)+ onActivated: index => Themes.setUnderglowEffect(model[index].value)+ }+ }++ UI.SettingRow {+ id: customRow+ visible: page.underglowShown && Themes.underglow && page.custom+ title: "Custom colour"++ readonly property var swatches: [+ { colour: "#3dff7a", name: "Green" },+ { colour: "#ff2d95", name: "Pink" },+ { colour: "#3dd5ff", name: "Cyan" },+ { colour: "#ffb03d", name: "Amber" },+ { colour: "#c85cff", name: "Violet" },+ { colour: "#ffffff", name: "White" }+ ]++ Row {+ anchors.verticalCenter: parent.verticalCenter+ spacing: 12+ Accessible.role: Accessible.Grouping+ Accessible.name: "Custom colour"++ Repeater {+ model: customRow.swatches++ UI.Swatch {+ required property var modelData+ anchors.verticalCenter: parent.verticalCenter+ size: 28+ colour: modelData.colour+ name: modelData.name+ selected: Qt.colorEqual(Themes.underglowCustom, modelData.colour)+ onClicked: Themes.setUnderglowCustom(modelData.colour)+ }+ }+ }++ UI.Label {+ anchors.verticalCenter: parent.verticalCenter+ leftPadding: 6+ text: "Or any colour"+ size: 12+ color: UI.Style.inkMuted+ }++ UI.TextField {+ id: hexField+ anchors.verticalCenter: parent.verticalCenter+ width: 124+ leftPadding: 36+ placeholderText: "#RRGGBB"+ maximumLength: 7+ Accessible.name: "Underglow colour, as a hex code"+ validator: RegularExpressionValidator { regularExpression: /#?[0-9A-Fa-f]{0,6}/ }+ readonly property string normalised: (text.startsWith("#") ? text : "#" + text).toLowerCase()+ readonly property bool complete: /^#[0-9a-f]{6}$/.test(normalised)+ error: activeFocus && text.length > 0 && !complete+ onAccepted: save()+ onActiveFocusChanged: {+ if (!activeFocus) {+ save();+ }+ }+ function save(): void {+ if (complete) {+ Themes.setUnderglowCustom(normalised);+ }+ text = Themes.underglowCustom.toString().toUpperCase();+ }+ Component.onCompleted: text = Themes.underglowCustom.toString().toUpperCase()++ Connections {+ target: Themes+ function onUnderglowChanged() {+ if (!hexField.activeFocus) {+ hexField.text = Themes.underglowCustom.toString().toUpperCase();+ }+ }+ }++ Rectangle {+ x: 12+ anchors.verticalCenter: parent.verticalCenter+ width: 16+ height: 16+ radius: 4+ color: hexField.complete ? hexField.normalised : Themes.underglowCustom+ border.width: 1+ border.color: UI.Style.tone(0.20)+ }+ }+ }+ }+ }+}diff --git a/packages/wildos-settings/qml/pages/WindowsAppsPage.qml b/packages/wildos-settings/qml/pages/WindowsAppsPage.qmlindex ba26112..a2549a9 100644--- a/packages/wildos-settings/qml/pages/WindowsAppsPage.qml+++ b/packages/wildos-settings/qml/pages/WindowsAppsPage.qml@@ -11,6 +11,7 @@ PageScroll {id: pageproperty var removing: null+ readonly property var windowsModeApps: WindowsMode.state === "ready" ? (WindowsMode.status.apps || []) : []UI.Label {Layout.fillWidth: true@@ -114,8 +115,24 @@ PageScroll {}}+ // Apps installed inside Windows mode, as its Start menu lists+ // them. They are removed inside Windows, like any program.+ Repeater {+ model: page.windowsModeApps++ UI.SettingRow {+ required property var modelData+ minHeight: 68+ iconTile: true+ iconName: "windowsapps"+ themeIcon: modelData.icon+ title: modelData.name+ description: "Runs in Windows mode. To uninstall it, open the Windows desktop from the Windows mode page."+ }+ }+UI.SettingRow {- visible: WindowsApps.apps.length === 0+ visible: WindowsApps.apps.length === 0 && page.windowsModeApps.length === 0title: "No Windows apps yet"description: WindowsApps.installed? "Open a Windows installer, an .exe or .msi file, and Wild OS offers to set it up here."diff --git a/packages/wildos-settings/qml/pages/WindowsModePage.qml b/packages/wildos-settings/qml/pages/WindowsModePage.qmlindex d654539..b900938 100644--- a/packages/wildos-settings/qml/pages/WindowsModePage.qml+++ b/packages/wildos-settings/qml/pages/WindowsModePage.qml@@ -1,5 +1,6 @@import QtQuickimport QtQuick.Layouts+import QtQuick.Templates as Timport WildOS.Settingsimport WildOS.UI as UI@@ -178,7 +179,11 @@ PageScroll {UI.ListRow {minHeight: 54title: "Memory Windows mode can use"- description: "Unused memory is handed back to Wild OS. A change applies the next time Windows starts."+ // Windows only takes a new limit when it starts from off, so+ // until then the row says plainly that the change is waiting.+ description: page.status.memoryPending+ ? "Windows gets " + (page.options.memoryGb || 4) + " GB when it next starts. Wild OS restarts it by itself once no Windows app is open."+ : "Unused memory is handed back to Wild OS. A change applies once no Windows app is open, when Windows restarts."UI.ComboBox {anchors.verticalCenter: parent.verticalCenter@@ -189,6 +194,24 @@ PageScroll {}}+ // A shortcut: the switch lives in System > Power and battery, because+ // it speeds up the whole PC, not only Windows mode.+ UI.ListRow {+ minHeight: 54+ visible: Processor.threadsAvailable+ title: "Use every processor thread"+ description: Processor.everyThreadLocked+ ? "Off at Strict and Maximum protection."+ : "Faster Windows apps and games. Set in Power and battery."+ status: Processor.everyThread && !Processor.everyThreadLocked ? "On" : "Off"++ UI.Button {+ anchors.verticalCenter: parent.verticalCenter+ text: "Change"+ onClicked: Navigator.open("power")+ }+ }+UI.ListRow {minHeight: 54title: "Folders Windows apps can see"@@ -277,40 +300,76 @@ PageScroll {elide: Text.ElideNone}+ // The dialog stays open while the key goes in, which can take a few+ // minutes when Windows has to start first, and says how it went.UI.Dialog {id: keyDialogtitle: "Change the Windows product key"text: "Windows checks the key with Microsoft and activates with it. The key from this PC's firmware stays where it is."- onOpened: keyField.text = ""+ closePolicy: WindowsMode.activating ? T.Popup.NoAutoClose : T.Popup.CloseOnEscape++ property string keyProblem++ onOpened: {+ keyField.text = "";+ keyProblem = "";+ }++ Connections {+ target: WindowsMode+ function onProductKeyDone(answer) {+ if (answer === "") {+ keyDialog.close();+ page.show("");+ } else {+ keyDialog.keyProblem = answer;+ }+ }+ }UI.TextField {id: keyFieldLayout.fillWidth: true+ enabled: !WindowsMode.activatingplaceholderText: "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX"error: text.length >= 25 && !WindowsMode.keyShapeValid(text)Accessible.name: "Windows product key"}+ UI.Label {+ Layout.fillWidth: true+ visible: text.length > 0+ text: WindowsMode.activating ? "Activating Windows. If Windows was asleep it starts first, which can take a few minutes."+ : keyDialog.keyProblem+ size: 13+ color: WindowsMode.activating ? UI.Style.inkStatus : UI.Style.warning+ wrapMode: Text.Wrap+ elide: Text.ElideNone+ Accessible.role: Accessible.AlertMessage+ }+buttons: [UI.Button {text: "Cancel"+ enabled: !WindowsMode.activatingonClicked: keyDialog.close()},UI.Button {text: "Use this PC's licence"visible: page.licence.source !== "firmware"+ enabled: !WindowsMode.activatingonClicked: {- keyDialog.close();- page.show(WindowsMode.setProductKey("firmware"));+ keyDialog.keyProblem = "";+ WindowsMode.setProductKey("firmware");}},UI.Button {kind: "primary"- text: "Use this key"- enabled: WindowsMode.keyShapeValid(keyField.text)+ text: WindowsMode.activating ? "Activating" : "Use this key"+ enabled: !WindowsMode.activating && WindowsMode.keyShapeValid(keyField.text)onClicked: {- page.show(WindowsMode.setProductKey(keyField.text));- keyDialog.close();+ keyDialog.keyProblem = "";+ WindowsMode.setProductKey(keyField.text);}}]diff --git a/packages/wildos-settings/src/accesscore.cpp b/packages/wildos-settings/src/accesscore.cppindex a849ec9..c358a23 100644--- a/packages/wildos-settings/src/accesscore.cpp+++ b/packages/wildos-settings/src/accesscore.cpp@@ -14,11 +14,14 @@#include <QDir>#include <QFile>#include <QFileInfo>+#include <QLibraryInfo>#include <QPointer>#include <QProcess>#include <QStandardPaths>#include <QTimer>+#include <algorithm>+#include <signal.h>#include <sys/stat.h>#include <unistd.h>@@ -191,6 +194,42 @@ const PointerColour pointerList[] = {{"seaglass", "Sea glass", "#7fd6c8", "WildOS-SeaGlass"},};+// wildos-shell's effects, by their KWin plugin ids.+const QString outlineEffect = QStringLiteral("wildos_outline");+const QString blurEffect = QStringLiteral("wildos_blurinactive");+const QString blurGroup = QStringLiteral("Effect-wildos_blurinactive");++void callEffects(const QString &method, const QString &effect)+{+ QDBusMessage message = QDBusMessage::createMethodCall(kwinService, QStringLiteral("/Effects"), QStringLiteral("org.kde.kwin.Effects"), method);+ message << effect;+ QDBusConnection::sessionBus().asyncCall(message);+}++bool effectEnabled(const QString &effect)+{+ return fresh(QStringLiteral("kwinrc"))->group(QStringLiteral("Plugins")).readEntry(effect + QStringLiteral("Enabled"), false);+}++// What System Settings' effects page does: the Plugins key is what KWin+// reads at the next sign-in, the D-Bus call changes the running session.+void setEffectEnabled(const QString &effect, bool on)+{+ KSharedConfigPtr kwin = fresh(QStringLiteral("kwinrc"));+ kwin->group(QStringLiteral("Plugins")).writeEntry(effect + QStringLiteral("Enabled"), on, KConfig::Notify);+ kwin->sync();+ callEffects(on ? QStringLiteral("loadEffect") : QStringLiteral("unloadEffect"), effect);+}++template<typename T>+void writeBlurSetting(const char *key, const T &value)+{+ KSharedConfigPtr kwin = fresh(QStringLiteral("kwinrc"));+ kwin->group(blurGroup).writeEntry(key, value, KConfig::Notify);+ kwin->sync();+ callEffects(QStringLiteral("reconfigureEffect"), blurEffect);+}+QString cursorTheme(){QString theme = fresh(QStringLiteral("kcminputrc"))->group(QStringLiteral("Mouse")).readEntry("cursorTheme", QString());@@ -622,4 +661,71 @@ void setMonoAudio(bool on)bus.call(disable, QDBus::Block, 5000);}}++bool windowEffectsInstalled()+{+ const QString dir = QLibraryInfo::path(QLibraryInfo::PluginsPath) + QStringLiteral("/kwin/effects/plugins/");+ return QFile::exists(dir + outlineEffect + QStringLiteral(".so")) && QFile::exists(dir + blurEffect + QStringLiteral(".so"));+}++bool windowEffectsSupported()+{+ QDBusMessage message = QDBusMessage::createMethodCall(kwinService, QStringLiteral("/Effects"), QStringLiteral("org.kde.kwin.Effects"),+ QStringLiteral("isEffectSupported"));+ message << outlineEffect;+ const QDBusReply<bool> reply = QDBusConnection::sessionBus().call(message, QDBus::Block, 2000);+ // No answer (KWin busy or not running) is not a reason to lock the+ // switches; KWin refuses to load an effect it cannot run anyway.+ return !reply.isValid() || reply.value();+}++bool outlineWindows()+{+ return effectEnabled(outlineEffect);+}++void setOutlineWindows(bool on)+{+ setEffectEnabled(outlineEffect, on);+}++bool blurBackground()+{+ return effectEnabled(blurEffect);+}++void setBlurBackground(bool on)+{+ setEffectEnabled(blurEffect, on);+}++int blurStrength()+{+ return std::clamp(fresh(QStringLiteral("kwinrc"))->group(blurGroup).readEntry("Strength", 3), 1, 5);+}++void setBlurStrength(int step)+{+ writeBlurSetting("Strength", std::clamp(step, 1, 5));+}++bool blurDesktop()+{+ return fresh(QStringLiteral("kwinrc"))->group(blurGroup).readEntry("Desktop", true);+}++void setBlurDesktop(bool on)+{+ writeBlurSetting("Desktop", on);+}++bool strongerText()+{+ return fresh(QStringLiteral("wildosrc"))->group(QStringLiteral("Accessibility")).readEntry("StrongerText", false);+}++void setStrongerText(bool on)+{+ writeWildos("Accessibility", "StrongerText", on);+}}diff --git a/packages/wildos-settings/src/accesscore.h b/packages/wildos-settings/src/accesscore.hindex 1b6686f..460510e 100644--- a/packages/wildos-settings/src/accesscore.h+++ b/packages/wildos-settings/src/accesscore.h@@ -16,10 +16,13 @@// screen reader, as kcm_access writes them; KWin's plugins// watch the file, so every write carries KConfig::Notify// kdeglobals the high contrast colour scheme-// kwinrc the zoom effect and the on-screen keyboard+// kwinrc the zoom effect, the on-screen keyboard, and the window+// outline and background blur effects with the blur's+// settings// kcminputrc the pointer theme and size-// wildosrc what the lock and sign-in screens need to know, and the-// theme to go back to when high contrast is turned off+// wildosrc what the lock and sign-in screens need to know, the theme+// to go back to when high contrast is turned off, and+// stronger text on glassnamespace AccessCore{// Wild OS's high contrast scheme (wildos-branding).@@ -73,4 +76,24 @@ void setPointer(const QString &colourId, int size);bool monoAudio();void setMonoAudio(bool on);++// wildos-shell's KWin effects, loaded and unloaded at once and kept for+// the next sign-in. Supported is false where KWin draws without OpenGL.+bool windowEffectsInstalled();+bool windowEffectsSupported();+bool outlineWindows();+void setOutlineWindows(bool on);+bool blurBackground();+void setBlurBackground(bool on);+// 1 (lightest) to 5.+int blurStrength();+void setBlurStrength(int step);+bool blurDesktop();+void setBlurDesktop(bool on);++// Glass behind text (the taskbar, Start, the flyouts, Wild OS apps) made+// nearly solid and muted text brighter. WildOS.UI follows the key, and+// wildos-auto-theme puts on the solid Plasma style that matches the theme.+bool strongerText();+void setStrongerText(bool on);}diff --git a/packages/wildos-settings/src/accessibility.cpp b/packages/wildos-settings/src/accessibility.cppindex 83c2619..d993da1 100644--- a/packages/wildos-settings/src/accessibility.cpp+++ b/packages/wildos-settings/src/accessibility.cpp@@ -17,6 +17,8 @@ Accessibility::Accessibility(QObject *parent)!QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("color-schemes/%1.colors").arg(AccessCore::highContrastScheme())).isEmpty();m_monoAudioInstalled = QFile::exists(QStringLiteral("/usr/lib/systemd/user/wildos-mono-audio.service"));m_keyboardInstalled = !AccessCore::keyboardDesktopFile().isEmpty();+ m_windowEffectsInstalled = AccessCore::windowEffectsInstalled();+ m_windowEffectsSupported = m_windowEffectsInstalled && AccessCore::windowEffectsSupported();// Shortcuts, kcm_access, the Plasma keyboard indicator or another// Settings window can change any of these while the page is open.@@ -24,6 +26,7 @@ Accessibility::Accessibility(QObject *parent)watch(QStringLiteral("kdeglobals"));watch(QStringLiteral("kcminputrc"));watch(QStringLiteral("kwinrc"));+ watch(QStringLiteral("wildosrc"));QDBusConnection::sessionBus().connect(QStringLiteral("org.kde.KWin"), QStringLiteral("/VirtualKeyboard"), QStringLiteral("org.kde.kwin.VirtualKeyboard"),QStringLiteral("enabledChanged"), this, SLOT(refresh()));@@ -61,6 +64,11 @@ void Accessibility::refresh()m_slowKeysDelay = AccessCore::slowKeysDelay();m_bounceKeys = AccessCore::bounceKeys();m_bounceKeysDelay = AccessCore::bounceKeysDelay();+ m_outlineWindows = AccessCore::outlineWindows();+ m_blurBackground = AccessCore::blurBackground();+ m_blurStrength = AccessCore::blurStrength();+ m_blurDesktop = AccessCore::blurDesktop();+ m_strongerText = AccessCore::strongerText();Q_EMIT changed();}@@ -172,3 +180,38 @@ void Accessibility::setBounceKeysDelay(int ms)m_bounceKeysDelay = ms;Q_EMIT changed();}++void Accessibility::setOutlineWindows(bool on)+{+ AccessCore::setOutlineWindows(on);+ m_outlineWindows = on;+ Q_EMIT changed();+}++void Accessibility::setBlurBackground(bool on)+{+ AccessCore::setBlurBackground(on);+ m_blurBackground = on;+ Q_EMIT changed();+}++void Accessibility::setBlurStrength(int step)+{+ AccessCore::setBlurStrength(step);+ m_blurStrength = AccessCore::blurStrength();+ Q_EMIT changed();+}++void Accessibility::setBlurDesktop(bool on)+{+ AccessCore::setBlurDesktop(on);+ m_blurDesktop = on;+ Q_EMIT changed();+}++void Accessibility::setStrongerText(bool on)+{+ AccessCore::setStrongerText(on);+ m_strongerText = on;+ Q_EMIT changed();+}diff --git a/packages/wildos-settings/src/accessibility.h b/packages/wildos-settings/src/accessibility.hindex e0dc3cc..0775d61 100644--- a/packages/wildos-settings/src/accessibility.h+++ b/packages/wildos-settings/src/accessibility.h@@ -38,6 +38,13 @@ class Accessibility : public QObjectQ_PROPERTY(int slowKeysDelay READ slowKeysDelay NOTIFY changed)Q_PROPERTY(bool bounceKeys READ bounceKeys NOTIFY changed)Q_PROPERTY(int bounceKeysDelay READ bounceKeysDelay NOTIFY changed)+ Q_PROPERTY(bool windowEffectsInstalled READ windowEffectsInstalled CONSTANT)+ Q_PROPERTY(bool windowEffectsSupported READ windowEffectsSupported CONSTANT)+ Q_PROPERTY(bool outlineWindows READ outlineWindows NOTIFY changed)+ Q_PROPERTY(bool blurBackground READ blurBackground NOTIFY changed)+ Q_PROPERTY(int blurStrength READ blurStrength NOTIFY changed)+ Q_PROPERTY(bool blurDesktop READ blurDesktop NOTIFY changed)+ Q_PROPERTY(bool strongerText READ strongerText NOTIFY changed)public:explicit Accessibility(QObject *parent = nullptr);@@ -62,6 +69,13 @@ public:int slowKeysDelay() const { return m_slowKeysDelay; }bool bounceKeys() const { return m_bounceKeys; }int bounceKeysDelay() const { return m_bounceKeysDelay; }+ bool windowEffectsInstalled() const { return m_windowEffectsInstalled; }+ bool windowEffectsSupported() const { return m_windowEffectsSupported; }+ bool outlineWindows() const { return m_outlineWindows; }+ bool blurBackground() const { return m_blurBackground; }+ int blurStrength() const { return m_blurStrength; }+ bool blurDesktop() const { return m_blurDesktop; }+ bool strongerText() const { return m_strongerText; }Q_INVOKABLE void setPointerColour(const QString &id);Q_INVOKABLE void setPointerSize(int size);@@ -76,6 +90,11 @@ public:Q_INVOKABLE void setSlowKeysDelay(int ms);Q_INVOKABLE void setBounceKeys(bool on);Q_INVOKABLE void setBounceKeysDelay(int ms);+ Q_INVOKABLE void setOutlineWindows(bool on);+ Q_INVOKABLE void setBlurBackground(bool on);+ Q_INVOKABLE void setBlurStrength(int step);+ Q_INVOKABLE void setBlurDesktop(bool on);+ Q_INVOKABLE void setStrongerText(bool on);public Q_SLOTS:// Rereads everything. KWin has no signal for zoom, so the page also@@ -109,6 +128,13 @@ private:int m_slowKeysDelay = 500;bool m_bounceKeys = false;int m_bounceKeysDelay = 500;+ bool m_windowEffectsInstalled = false;+ bool m_windowEffectsSupported = true;+ bool m_outlineWindows = false;+ bool m_blurBackground = false;+ int m_blurStrength = 3;+ bool m_blurDesktop = true;+ bool m_strongerText = false;QList<KConfigWatcher::Ptr> m_watchers;};diff --git a/packages/wildos-settings/src/autotheme/main.cpp b/packages/wildos-settings/src/autotheme/main.cppindex 2d43649..7bf6cca 100644--- a/packages/wildos-settings/src/autotheme/main.cpp+++ b/packages/wildos-settings/src/autotheme/main.cpp@@ -1,7 +1,9 @@// wildos-auto-theme: switches between the light and dark themes at sunrise// and sunset while Settings' theme is Automatic, and keeps the window title-// bars in step with the colour scheme however it was changed (Settings,-// Welcome, the switch here). Started with every session.+// bars and the Plasma style (the glass of Start and the flyouts) in step+// with the colour scheme, the theme and stronger text on glass however they+// were changed (Settings, Welcome, the switch here). Started with every+// session.#include "sun.h"@@ -14,6 +16,9 @@#include <QDBusConnection>#include <QDBusMessage>#include <QDBusPendingCall>+#include <QFile>+#include <QJsonDocument>+#include <QJsonObject>#include <QProcess>#include <QStandardPaths>#include <QTimer>@@ -28,6 +33,14 @@ const QString decorationGroup = QStringLiteral("org.kde.kdecoration2");const QString darkDecoration = QStringLiteral("__aurorae__svg__WildOS");const QString lightDecoration = QStringLiteral("__aurorae__svg__WildOSLight");+const QString darkStyle = QStringLiteral("wildos");+const QString lightStyle = QStringLiteral("wildos-light");++bool hasStyle(const QString &name)+{+ return !QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("plasma/desktoptheme/%1/metadata.json").arg(name)).isEmpty();+}+// Light or dark goes by the window colour of the scheme applied, the rule// the Wild OS apps and the Kvantum theme use: the scheme's name is only a// label, and can be missing while its colours are there.@@ -56,8 +69,10 @@ public:{m_wildos = KConfigWatcher::create(KSharedConfig::openConfig(QStringLiteral("wildosrc")));connect(m_wildos.data(), &KConfigWatcher::configChanged, this, &Switcher::check);+ connect(m_wildos.data(), &KConfigWatcher::configChanged, this, &Switcher::matchStyle);m_globals = KConfigWatcher::create(KSharedConfig::openConfig(QStringLiteral("kdeglobals")));connect(m_globals.data(), &KConfigWatcher::configChanged, this, &Switcher::matchDecoration);+ connect(m_globals.data(), &KConfigWatcher::configChanged, this, &Switcher::matchStyle);// Checking once a minute also covers waking from sleep, a changed// time zone and a clock set by hand, which a timer aimed at the next@@ -67,6 +82,7 @@ public:connect(&m_tick, &QTimer::timeout, this, &Switcher::check);// Also a backstop for a scheme written without telling anyone.connect(&m_tick, &QTimer::timeout, this, &Switcher::matchDecoration);+ connect(&m_tick, &QTimer::timeout, this, &Switcher::matchStyle);m_tick.start();QDBusConnection::systemBus().connect(QStringLiteral("org.freedesktop.login1"), QStringLiteral("/org/freedesktop/login1"),@@ -74,6 +90,62 @@ public:SLOT(check()));check();matchDecoration();+ matchStyle();+ }++ // Start, the flyouts and tooltips are drawn by the Plasma style, whose+ // glass is fixed in its frames, so each theme glass has a style of its+ // own (wildos-branding builds them) and the style follows the theme and+ // the mode: the theme's while the session is in the theme's mode, the+ // plain dark or light one otherwise, and its solid twin while stronger+ // text on glass is on. A style someone picked themselves is left alone.+ Q_SLOT void matchStyle()+ {+ if (m_styling) {+ // Asked again while a style goes on (stronger text switched on+ // and off quickly): look again once it is in.+ m_restyle = true;+ return;+ }+ KSharedConfigPtr globals = KSharedConfig::openConfig(QStringLiteral("kdeglobals"));+ globals->reparseConfiguration();+ const bool light = schemeIsLight(globals) && globals->group(QStringLiteral("General")).readEntry("ColorScheme") != contrastScheme;++ QString wanted = light && hasStyle(lightStyle) ? lightStyle : darkStyle;+ KSharedConfigPtr wildos = KSharedConfig::openConfig(QStringLiteral("wildosrc"));+ wildos->reparseConfiguration();+ const QString id = wildos->group(QStringLiteral("Theme")).readEntry("Id", QStringLiteral("dawn"));+ QFile file(QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("wildos/themes/%1.json").arg(id)));+ if (file.open(QIODevice::ReadOnly)) {+ const QJsonObject theme = QJsonDocument::fromJson(file.readAll()).object();+ const QString style = theme.value(QStringLiteral("desktopTheme")).toString();+ if ((theme.value(QStringLiteral("mode")).toString() == QLatin1String("light")) == light && !style.isEmpty() && hasStyle(style)) {+ wanted = style;+ }+ }+ // Settings > Accessibility > Stronger text on glass: the same style+ // with its glass made nearly solid.+ if (wildos->group(QStringLiteral("Accessibility")).readEntry("StrongerText", false) && hasStyle(wanted + QStringLiteral("-solid"))) {+ wanted += QStringLiteral("-solid");+ }++ KSharedConfigPtr plasmarc = KSharedConfig::openConfig(QStringLiteral("plasmarc"));+ plasmarc->reparseConfiguration();+ const QString current = plasmarc->group(QStringLiteral("Theme")).readEntry("name", darkStyle);+ if (current == wanted || (current != darkStyle && !current.startsWith(darkStyle + QLatin1Char('-')))) {+ return;+ }+ m_styling = true;+ auto process = new QProcess(this);+ connect(process, &QProcess::finished, this, [this, process] {+ process->deleteLater();+ m_styling = false;+ if (m_restyle) {+ m_restyle = false;+ matchStyle();+ }+ });+ process->start(QStringLiteral("plasma-apply-desktoptheme"), {wanted});}// The title bar is drawn by KWin from an Aurorae theme with fixed@@ -156,6 +228,8 @@ private:KConfigWatcher::Ptr m_globals;QTimer m_tick;bool m_applying = false;+ bool m_styling = false;+ bool m_restyle = false;};}diff --git a/packages/wildos-settings/src/graphics.cpp b/packages/wildos-settings/src/graphics.cppnew file mode 100644index 0000000..efe7f97--- /dev/null+++ b/packages/wildos-settings/src/graphics.cpp@@ -0,0 +1,113 @@+#include "graphics.h"++#include <QDir>+#include <QFile>+#include <QFileInfo>+#include <QProcess>+#include <QRegularExpression>++namespace+{+const QString helper = QStringLiteral("/usr/libexec/wildos/settings-graphics-driver");++QByteArray readFile(const QString &path)+{+ QFile file(path);+ return file.open(QIODevice::ReadOnly) ? file.readAll().trimmed() : QByteArray();+}+}++Graphics::Graphics(QObject *parent)+ : QObject(parent)+{+ // The first NVIDIA display controller (PCI class 0x03xxxx, vendor 0x10de).+ const QDir pci(QStringLiteral("/sys/bus/pci/devices"));+ for (const QString &address : pci.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) {+ const QString path = pci.filePath(address);+ if (readFile(path + QStringLiteral("/vendor")) == "0x10de" && readFile(path + QStringLiteral("/class")).startsWith("0x03")) {+ m_device = path;+ QProcess lspci;+ lspci.start(QStringLiteral("lspci"), {QStringLiteral("-s"), address, QStringLiteral("-mm")});+ if (lspci.waitForFinished(3000)) {+ // 01:00.0 "VGA compatible controller" "NVIDIA Corporation" "GA104M [GeForce RTX 3070 Mobile]" ...+ QStringList fields;+ QRegularExpressionMatchIterator it = QRegularExpression(QStringLiteral("\"([^\"]*)\"")).globalMatch(QString::fromUtf8(lspci.readAllStandardOutput()));+ while (it.hasNext()) {+ fields << it.next().captured(1);+ }+ // The marketing name is the part in brackets, when lspci knows it.+ if (fields.size() >= 3) {+ const QRegularExpressionMatch bracket = QRegularExpression(QStringLiteral("\\[([^\\]]+)\\]")).match(fields.at(2));+ m_name = bracket.hasMatch() ? bracket.captured(1) : fields.at(2);+ }+ }+ if (m_name.isEmpty()) {+ m_name = QStringLiteral("NVIDIA graphics");+ }+ break;+ }+ }+}++QString Graphics::driverInUse() const+{+ if (m_device.isEmpty()) {+ return {};+ }+ const QFileInfo link(m_device + QStringLiteral("/driver"));+ return link.exists() ? QFileInfo(link.symLinkTarget()).fileName() : QString();+}++bool Graphics::nvidiaInstalled() const+{+ return QFile::exists(QStringLiteral("/var/lib/dpkg/info/nvidia-driver.list"));+}++// The firmware's SecureBoot variable: four bytes of attributes, then 1 for on.+bool Graphics::secureBoot() const+{+ const QByteArray value = readFile(QStringLiteral("/sys/firmware/efi/efivars/SecureBoot-8be4df61-93ca-11d2-aa0d-00e098032b8c"));+ return value.size() >= 5 && value.at(4) == 1;+}++bool Graphics::restartNeeded() const+{+ const QString running = driverInUse();+ return nvidiaInstalled() ? running != QLatin1String("nvidia") : running == QLatin1String("nvidia");+}++void Graphics::useDriver(const QString &driver)+{+ if (m_process || (driver != QLatin1String("nvidia") && driver != QLatin1String("open"))) {+ return;+ }+ m_error.clear();+ m_step = QStringLiteral("Waiting for your password");+ m_process = new QProcess(this);+ connect(m_process, &QProcess::readyReadStandardOutput, this, [this] {+ while (m_process->canReadLine()) {+ const QString line = QString::fromUtf8(m_process->readLine()).trimmed();+ if (line.startsWith(QLatin1String("step "))) {+ m_step = line.mid(5);+ } else if (line.startsWith(QLatin1String("code "))) {+ m_code = line.mid(5);+ }+ Q_EMIT changed();+ }+ });+ connect(m_process, &QProcess::finished, this, [this](int code) {+ if (code == 126 || code == 127) {+ m_error = QStringLiteral("Nothing was changed because the password was not given.");+ } else if (code == 4) {+ m_error = QStringLiteral("Debian's NVIDIA driver doesn't support this graphics card, so it keeps the open driver.");+ } else if (code != 0) {+ m_error = QStringLiteral("The driver could not be changed. Check the internet connection and try again.");+ }+ m_process->deleteLater();+ m_process = nullptr;+ m_step.clear();+ Q_EMIT changed();+ });+ m_process->start(QStringLiteral("pkexec"), {helper, driver});+ Q_EMIT changed();+}diff --git a/packages/wildos-settings/src/graphics.h b/packages/wildos-settings/src/graphics.hnew file mode 100644index 0000000..3ee9465--- /dev/null+++ b/packages/wildos-settings/src/graphics.h@@ -0,0 +1,64 @@+#pragma once++#include <QObject>+#include <QQmlEngine>+#include <QString>++class QProcess;++// Settings > System > Display > Graphics driver: an NVIDIA card can use the+// open driver Wild OS ships (nouveau) or NVIDIA's own from Debian.+// settings-graphics-driver does the switching as root and reports its steps;+// with Secure Boot on it also queues this PC's module key and prints the code+// the firmware asks for at the next restart.+class Graphics : public QObject+{+ Q_OBJECT+ QML_ELEMENT+ QML_SINGLETON++ Q_PROPERTY(bool hasNvidia READ hasNvidia CONSTANT)+ // The card's name, as lspci knows it.+ Q_PROPERTY(QString nvidiaName READ nvidiaName CONSTANT)+ // The kernel driver bound to the card now: nouveau, nvidia, or empty.+ Q_PROPERTY(QString driverInUse READ driverInUse NOTIFY changed)+ Q_PROPERTY(bool nvidiaInstalled READ nvidiaInstalled NOTIFY changed)+ Q_PROPERTY(bool secureBoot READ secureBoot CONSTANT)+ // What is installed and what is running differ until the next start-up.+ Q_PROPERTY(bool restartNeeded READ restartNeeded NOTIFY changed)+ Q_PROPERTY(bool busy READ busy NOTIFY changed)+ // The step the helper is on while busy.+ Q_PROPERTY(QString step READ step NOTIFY changed)+ // The code to type into the firmware's key enrolment screen, once queued.+ Q_PROPERTY(QString enrolCode READ enrolCode NOTIFY changed)+ // Why the last switch failed, in plain words, or empty.+ Q_PROPERTY(QString error READ error NOTIFY changed)++public:+ explicit Graphics(QObject *parent = nullptr);++ bool hasNvidia() const { return !m_device.isEmpty(); }+ QString nvidiaName() const { return m_name; }+ QString driverInUse() const;+ bool nvidiaInstalled() const;+ bool secureBoot() const;+ bool restartNeeded() const;+ bool busy() const { return m_process != nullptr; }+ QString step() const { return m_step; }+ QString enrolCode() const { return m_code; }+ QString error() const { return m_error; }++ // "nvidia" or "open".+ Q_INVOKABLE void useDriver(const QString &driver);++Q_SIGNALS:+ void changed();++private:+ QString m_device; // /sys/bus/pci/devices/<address>+ QString m_name;+ QProcess *m_process = nullptr;+ QString m_step;+ QString m_code;+ QString m_error;+};diff --git a/packages/wildos-settings/src/language.cpp b/packages/wildos-settings/src/language.cppindex c1fa6f9..2a6cce1 100644--- a/packages/wildos-settings/src/language.cpp+++ b/packages/wildos-settings/src/language.cpp@@ -22,12 +22,13 @@ const QString helper = QStringLiteral("/usr/libexec/wildos/settings-locale");const QString fallbackFormat = QStringLiteral("en_GB.UTF-8");const QString fallbackLanguage = QStringLiteral("en_GB");-// The separate formats KDE's region module can set; choosing a regional-// format here sets them all, as Windows does.+// Every format variable the installer writes to /etc/default/locale and+// startplasma reads from plasma-localerc; choosing a regional format here+// sets them all, as Windows does.const QStringList categories = {QStringLiteral("LC_NUMERIC"), QStringLiteral("LC_TIME"), QStringLiteral("LC_MONETARY"),QStringLiteral("LC_MEASUREMENT"), QStringLiteral("LC_COLLATE"), QStringLiteral("LC_CTYPE"),QStringLiteral("LC_PAPER"), QStringLiteral("LC_ADDRESS"), QStringLiteral("LC_NAME"),- QStringLiteral("LC_TELEPHONE")};+ QStringLiteral("LC_TELEPHONE"), QStringLiteral("LC_IDENTIFICATION")};// The parts More format options offers on their own, under the keys// kcm_regionandlang writes (regionandlangsettingsbase.kcfg). Addresses,@@ -126,7 +127,7 @@ void Language::read(){auto config = KSharedConfig::openConfig(QStringLiteral("plasma-localerc"), KConfig::NoGlobals);config->reparseConfiguration();- const KConfigGroup formats(config, QStringLiteral("Formats"));+ KConfigGroup formats(config, QStringLiteral("Formats"));const KConfigGroup translations(config, QStringLiteral("Translations"));m_language = firstLanguage(translations.readEntry("LANGUAGE", QString()));if (m_language.isEmpty()) {@@ -136,17 +137,58 @@ void Language::read()if (m_format.isEmpty()) {m_format = m_sessionFormat;}- m_detailed = false;- for (const QString &key : categories) {++ // The installer writes every LC_ variable into /etc/default/locale, and+ // the sign-in passes them to the session, where each one outranks LANG.+ // startplasma only replaces the ones written here, so a part missing+ // here is not "the regional format" but whatever the installer chose.+ // Earlier versions of this page removed the parts that followed the+ // regional format; a page that wrote LC_TIME is one of those, and its+ // missing parts are written out now as the format they were meant to+ // follow, so the next sign-in finally applies it.+ if (formats.hasKey("LANG") && formats.hasKey("LC_TIME")) {+ bool wrote = false;+ for (const QString &key : categories) {+ if (!formats.hasKey(key)) {+ formats.writeEntry(key, m_format, KConfig::Notify);+ wrote = true;+ }+ }+ if (wrote) {+ config->sync();+ }+ }++ // What each part really is: the value written here, or else the one+ // this session was given at sign-in.+ const auto resolved = [this, &formats](const QString &key) {const QString value = canonical(formats.readEntry(key, QString()));- if (!value.isEmpty() && value != m_format) {- m_detailed = true;+ if (!value.isEmpty()) {+ return value;+ }+ const QString session = m_sessionCategories.value(key).toString();+ return session.isEmpty() ? m_format : session;+ };+ m_complete = true;+ for (const QString &key : categories) {+ if (canonical(formats.readEntry(key, QString())) != m_format) {+ m_complete = false;}}+ m_detailed = false;m_overrides.clear();for (const QString &key : shownCategories) {- const QString value = canonical(formats.readEntry(key, QString()));+ const QString value = resolved(key);m_overrides.insert(key, value == m_format ? QString() : value);+ if (value != m_format) {+ m_detailed = true;+ }+ }+ for (const QString &key : categories) {+ const QString value = canonical(formats.readEntry(key, QString()));+ if (!value.isEmpty() && value != m_format) {+ m_detailed = true;+ }}auto globals = KSharedConfig::openConfig(QStringLiteral("kdeglobals"));globals->reparseConfiguration();@@ -168,9 +210,7 @@ bool Language::needsSignOut() constif (!chosen.isEmpty() && chosen != (session.isEmpty() ? m_sessionFormat : session)) {return true;}- // wildos.sh sets LC_TIME itself for some sessions, so a session- // value there says nothing about what was chosen.- if (chosen.isEmpty() && !session.isEmpty() && session != m_format && key != QLatin1String("LC_TIME")) {+ if (chosen.isEmpty() && !session.isEmpty() && session != m_format) {return true;}}@@ -180,7 +220,11 @@ bool Language::needsSignOut() constQVariantList Language::languages() const{// A language counts when the desktop shell itself is translated into it.- QSet<QString> codes = {fallbackLanguage};+ // US English has no translation because it is the language KDE is+ // written in, so it is added by hand. Its list still falls back to UK+ // English (see setLanguage), which keeps Wild OS's own wording, while+ // apps with a US English translation, such as the browser, use it.+ QSet<QString> codes = {fallbackLanguage, QStringLiteral("en_US")};const auto dirs = QDir(QStringLiteral("/usr/share/locale")).entryList(QDir::Dirs | QDir::NoDotAndDotDot);for (const QString &code : dirs) {if (!code.contains(QLatin1Char('@')) && code != QLatin1String("en")@@ -329,19 +373,21 @@ void Language::setLanguage(const QString &code)void Language::setFormat(const QString &locale){const QString chosen = canonical(locale);- if (chosen.isEmpty() || chosen == m_format || m_busy) {+ // Choosing the same format again is how the page puts every part back+ // to it, so it only does nothing when they all follow it already.+ if (chosen.isEmpty() || (chosen == m_format && m_complete) || m_busy) {return;}ensure({chosen}, [this, chosen] {auto config = KSharedConfig::openConfig(QStringLiteral("plasma-localerc"), KConfig::NoGlobals);KConfigGroup formats(config, QStringLiteral("Formats"));formats.writeEntry("LANG", chosen, KConfig::Notify);+ // Every part is written out, not left to follow LANG: the LC_+ // variables the installer set (and wildos.sh's LC_TIME for US+ // English) outrank LANG, so only a value written here replaces them.for (const QString &key : categories) {- formats.deleteEntry(key, KConfig::Notify);+ formats.writeEntry(key, chosen, KConfig::Notify);}- // Written out so Wild OS's day-first, 24-hour default for US English- // sessions (wildos.sh) gives way to a format chosen here.- formats.writeEntry("LC_TIME", chosen, KConfig::Notify);config->sync();read();});@@ -401,14 +447,9 @@ void Language::setCategory(const QString &category, const QString &locale)const auto write = [this, category, chosen] {auto config = KSharedConfig::openConfig(QStringLiteral("plasma-localerc"), KConfig::NoGlobals);KConfigGroup formats(config, QStringLiteral("Formats"));- if (!chosen.isEmpty()) {- formats.writeEntry(category, chosen, KConfig::Notify);- } else if (category == QLatin1String("LC_TIME")) {- // Kept written out for the reason setFormat writes it.- formats.writeEntry(category, m_format, KConfig::Notify);- } else {- formats.deleteEntry(category, KConfig::Notify);- }+ // Following the regional format is written out as that format, for+ // the reason setFormat writes every part.+ formats.writeEntry(category, chosen.isEmpty() ? m_format : chosen, KConfig::Notify);config->sync();read();};diff --git a/packages/wildos-settings/src/language.h b/packages/wildos-settings/src/language.hindex 6ee790f..4b512f2 100644--- a/packages/wildos-settings/src/language.h+++ b/packages/wildos-settings/src/language.h@@ -79,5 +79,7 @@ private:QVariantMap m_overrides;int m_fileSizeUnits = 0;bool m_detailed = false;+ // Every part is written out as the regional format.+ bool m_complete = false;bool m_busy = false;};diff --git a/packages/wildos-settings/src/processor.cpp b/packages/wildos-settings/src/processor.cppnew file mode 100644index 0000000..c29a68f--- /dev/null+++ b/packages/wildos-settings/src/processor.cpp@@ -0,0 +1,77 @@+#include "processor.h"++#include <QFile>+#include <QFileSystemWatcher>+#include <QProcess>++namespace+{+const QString wildosDir = QStringLiteral("/etc/wildos");+const QString choiceFile = QStringLiteral("/etc/wildos/cpu-threads");+const QString helper = QStringLiteral("/usr/libexec/wildos/settings-cpu-threads");++QByteArray readSmt(const char *name)+{+ QFile file(QStringLiteral("/sys/devices/system/cpu/smt/") + QLatin1String(name));+ return file.open(QIODevice::ReadOnly) ? file.readAll().trimmed() : QByteArray();+}+}++Processor::Processor(QObject *parent)+ : QObject(parent)+ , m_watcher(new QFileSystemWatcher(this))+{+ // The choice and the protection level both live in /etc/wildos, written by+ // root helpers, so the switch follows them without Settings asking.+ if (QFile::exists(wildosDir)) {+ m_watcher->addPath(wildosDir);+ }+ connect(m_watcher, &QFileSystemWatcher::directoryChanged, this, &Processor::changed);+}++// "notsupported" and "notimplemented" mean a processor with one thread per core.+bool Processor::threadsAvailable() const+{+ const QByteArray control = readSmt("control");+ return QFile::exists(helper) && !control.isEmpty() && control != "notsupported" && control != "notimplemented";+}++bool Processor::everyThread() const+{+ return QFile::exists(choiceFile);+}++bool Processor::everyThreadActive() const+{+ return readSmt("active") == "1";+}++bool Processor::everyThreadLocked() const+{+ QFile file(QStringLiteral("/etc/wildos/protection-level"));+ const QByteArray level = file.open(QIODevice::ReadOnly) ? file.readAll().trimmed() : QByteArray();+ return level == "strict" || level == "maximum";+}++void Processor::setEveryThread(bool on)+{+ if (m_busy || on == everyThread() || (on && everyThreadLocked())) {+ return;+ }+ m_busy = true;+ Q_EMIT changed();+ auto process = new QProcess(this);+ connect(process, &QProcess::finished, this, [this, process](int code) {+ process->deleteLater();+ m_busy = false;+ if (code == 126 || code == 127) {+ Q_EMIT failed(QStringLiteral("Nothing was changed because the password was not given."));+ } else if (code == 3) {+ Q_EMIT failed(QStringLiteral("Strict and Maximum protection keep this off."));+ } else if (code != 0) {+ Q_EMIT failed(QStringLiteral("The setting could not be changed."));+ }+ Q_EMIT changed();+ });+ process->start(QStringLiteral("pkexec"), {helper, on ? QStringLiteral("on") : QStringLiteral("off")});+}diff --git a/packages/wildos-settings/src/processor.h b/packages/wildos-settings/src/processor.hnew file mode 100644index 0000000..e6acc97--- /dev/null+++ b/packages/wildos-settings/src/processor.h@@ -0,0 +1,48 @@+#pragma once++#include <QObject>+#include <QQmlEngine>++class QFileSystemWatcher;++// "Use every processor thread" (hyper-threading), in System > Power and+// battery, with shortcuts from Windows mode. Wild OS starts with the second+// thread of each core off; turning it on is a boot option written by+// settings-cpu-threads, so what was chosen and what the running kernel does+// can differ until the next start-up. Strict and Maximum protection keep it off.+class Processor : public QObject+{+ Q_OBJECT+ QML_ELEMENT+ QML_SINGLETON++ // Whether the processor has two threads per core at all.+ Q_PROPERTY(bool threadsAvailable READ threadsAvailable CONSTANT)+ // What was chosen; it applies from the next start-up.+ Q_PROPERTY(bool everyThread READ everyThread NOTIFY changed)+ // What the running kernel does.+ Q_PROPERTY(bool everyThreadActive READ everyThreadActive NOTIFY changed)+ // Strict or Maximum protection, which keep it off.+ Q_PROPERTY(bool everyThreadLocked READ everyThreadLocked NOTIFY changed)+ // A change is waiting for the password or being written.+ Q_PROPERTY(bool busy READ busy NOTIFY changed)++public:+ explicit Processor(QObject *parent = nullptr);++ bool threadsAvailable() const;+ bool everyThread() const;+ bool everyThreadActive() const;+ bool everyThreadLocked() const;+ bool busy() const { return m_busy; }++ Q_INVOKABLE void setEveryThread(bool on);++Q_SIGNALS:+ void changed();+ void failed(const QString &message);++private:+ QFileSystemWatcher *m_watcher = nullptr;+ bool m_busy = false;+};diff --git a/packages/wildos-settings/src/soundtheme.cpp b/packages/wildos-settings/src/soundtheme.cppnew file mode 100644index 0000000..1c3dcac--- /dev/null+++ b/packages/wildos-settings/src/soundtheme.cpp@@ -0,0 +1,80 @@+#include "soundtheme.h"++#include <KConfigGroup>+#include <KSharedConfig>++#include <QProcess>+#include <QStandardPaths>++namespace+{+KConfigGroup sounds()+{+ return KSharedConfig::openConfig(QStringLiteral("kdeglobals"))->group(QStringLiteral("Sounds"));+}++KConfigGroup startEvent()+{+ return KSharedConfig::openConfig(QStringLiteral("plasma_workspace.notifyrc"))->group(QStringLiteral("Event/startkde"));+}+}++SoundTheme::SoundTheme(QObject *parent)+ : QObject(parent)+{+}++QString SoundTheme::scheme() const+{+ const auto g = sounds();+ if (!g.readEntry("Enable", true)) {+ return QStringLiteral("none");+ }+ return g.readEntry("Theme", QStringLiteral("ocean")) == QLatin1String("wildos") ? QStringLiteral("wildos") : QStringLiteral("ocean");+}++bool SoundTheme::startupSound() const+{+ return startEvent().readEntry("Action", QString()).contains(QLatin1String("Sound"));+}++void SoundTheme::setScheme(const QString &scheme)+{+ auto g = sounds();+ if (scheme == QLatin1String("none")) {+ g.writeEntry("Enable", false, KConfig::Notify);+ } else {+ // A true Enable is the default, so it isn't written down.+ g.revertToDefault("Enable", KConfig::Notify);+ g.writeEntry("Theme", scheme == QLatin1String("ocean") ? QStringLiteral("ocean") : QStringLiteral("wildos"), KConfig::Notify);+ }+ g.sync();+ Q_EMIT changed();+ if (scheme != QLatin1String("none")) {+ preview(QStringLiteral("message-new-instant"));+ }+}++void SoundTheme::setStartupSound(bool on)+{+ auto g = startEvent();+ g.writeEntry("Action", on ? QStringLiteral("Sound") : QString(), KConfig::Notify);+ g.sync();+ Q_EMIT changed();+}++void SoundTheme::preview(const QString &name)+{+ // The file from the scheme chosen here, played straight through+ // PipeWire: canberra-gtk-play would follow GTK's sound theme setting+ // rather than KDE's.+ const QString theme = sounds().readEntry("Theme", QStringLiteral("ocean"));+ const QString file = QStandardPaths::locate(QStandardPaths::GenericDataLocation,+ QStringLiteral("sounds/%1/stereo/%2.oga").arg(theme, name));+ if (file.isEmpty()) {+ return;+ }+ const QString player = !QStandardPaths::findExecutable(QStringLiteral("pw-play")).isEmpty() ? QStringLiteral("pw-play")+ : QStringLiteral("paplay");+ QProcess::startDetached(player, {file});+}diff --git a/packages/wildos-settings/src/soundtheme.h b/packages/wildos-settings/src/soundtheme.hnew file mode 100644index 0000000..e52d622--- /dev/null+++ b/packages/wildos-settings/src/soundtheme.h@@ -0,0 +1,33 @@+#pragma once++#include <QObject>+#include <QQmlEngine>++// The sound scheme (Wild OS's own, KDE's Ocean, or no sounds) and whether a+// sound plays when the desktop starts. Written where KDE's own sound module+// writes them, kdeglobals [Sounds] Theme and Enable, and the startkde event+// in plasma_workspace.notifyrc, so every KDE app and Plasma follow.+class SoundTheme : public QObject+{+ Q_OBJECT+ QML_ELEMENT+ QML_SINGLETON++ Q_PROPERTY(QString scheme READ scheme NOTIFY changed)+ Q_PROPERTY(bool startupSound READ startupSound NOTIFY changed)++public:+ explicit SoundTheme(QObject *parent = nullptr);++ QString scheme() const;+ bool startupSound() const;++ // "wildos", "ocean" or "none".+ Q_INVOKABLE void setScheme(const QString &scheme);+ Q_INVOKABLE void setStartupSound(bool on);+ // Plays a sound from the current scheme, so a choice can be heard.+ Q_INVOKABLE void preview(const QString &name);++Q_SIGNALS:+ void changed();+};diff --git a/packages/wildos-settings/src/system.cpp b/packages/wildos-settings/src/system.cppindex 0fb467a..2d5a01f 100644--- a/packages/wildos-settings/src/system.cpp+++ b/packages/wildos-settings/src/system.cpp@@ -232,7 +232,7 @@ void System::readHardware().match(readFile(QStringLiteral("/proc/meminfo")));if (memTotal.hasMatch()) {const double gib = memTotal.captured(1).toDouble() / (1024.0 * 1024.0);- m_memory = QStringLiteral("%1 GB usable").arg(QLocale(QLocale::English, QLocale::UnitedKingdom).toString(gib, 'f', 1));+ m_memory = QStringLiteral("%1 GB usable").arg(QLocale::system().toString(gib, 'f', 1));}}@@ -631,19 +631,30 @@ bool System::hasColourScheme(const QString &name) const}void System::setColourScheme(const QString &name)+{+ setColours(name, QColor());+}++void System::setColours(const QString &name, const QColor &newAccent){if (!hasColourScheme(name)) {+ if (newAccent.isValid()) {+ setAccent(newAccent);+ }return;}// Choosing a theme by hand ends automatic switching.setThemeMode(name == QLatin1String("WildOSLight") ? QStringLiteral("light") : QStringLiteral("dark"));if (name == m_colourScheme) {+ if (newAccent.isValid() && newAccent != m_accent) {+ setAccent(newAccent);+ }return;}- QColor accent = m_accent;+ QColor accent = newAccent.isValid() ? newAccent : m_accent;// High contrast has no accent of its own; leaving it for a theme brings// back the accent from before it (Accessibility keeps it).- if (m_colourScheme == QLatin1String("WildOSHighContrast")) {+ if (!newAccent.isValid() && m_colourScheme == QLatin1String("WildOSHighContrast")) {KSharedConfigPtr wildos = KSharedConfig::openConfig(QStringLiteral("wildosrc"));wildos->reparseConfiguration();const QStringList rgb = wildos->group(QStringLiteral("Accessibility")).readEntry("AccentBeforeContrast", QString()).split(QLatin1Char(','));@@ -770,22 +781,59 @@ void System::setSnapEdges(bool on)reconfigureKWin();}+// Snap layouts and snap assist are one KWin effect, org.wildos.snap, which+// reads its two switches from its own kwinrc group. A switch only counts as+// on while the effect is enabled, so turning both off unloads it, and+// systems that turned snap layouts off before assist existed read as both+// off.bool System::snapLayouts() const{- return KSharedConfig::openConfig(QStringLiteral("kwinrc"))->group(QStringLiteral("Plugins")).readEntry("org.wildos.snapEnabled", true);+ KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("kwinrc"));+ return config->group(QStringLiteral("Plugins")).readEntry("org.wildos.snapEnabled", true)+ && config->group(QStringLiteral("Effect-org.wildos.snap")).readEntry("ShowLayouts", true);}void System::setSnapLayouts(bool on)+{+ applySnapEffect(on, snapAssist());+}++bool System::snapAssist() const{KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("kwinrc"));- config->group(QStringLiteral("Plugins")).writeEntry("org.wildos.snapEnabled", on);+ return config->group(QStringLiteral("Plugins")).readEntry("org.wildos.snapEnabled", true)+ && config->group(QStringLiteral("Effect-org.wildos.snap")).readEntry("SnapAssist", true);+}++void System::setSnapAssist(bool on)+{+ applySnapEffect(snapLayouts(), on);+}++void System::applySnapEffect(bool layouts, bool assist)+{+ KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("kwinrc"));+ KConfigGroup plugins = config->group(QStringLiteral("Plugins"));+ const bool wasLoaded = plugins.readEntry("org.wildos.snapEnabled", true);+ const bool load = layouts || assist;+ KConfigGroup effect = config->group(QStringLiteral("Effect-org.wildos.snap"));+ effect.writeEntry("ShowLayouts", layouts);+ effect.writeEntry("SnapAssist", assist);+ plugins.writeEntry("org.wildos.snapEnabled", load);config->sync();- // Effects are loaded and unloaded by name; a plain reconfigure does not- // start or stop one.- auto message = QDBusMessage::createMethodCall(QStringLiteral("org.kde.KWin"), QStringLiteral("/Effects"), QStringLiteral("org.kde.kwin.Effects"),- on ? QStringLiteral("loadEffect") : QStringLiteral("unloadEffect"));- message << QStringLiteral("org.wildos.snap");- QDBusConnection::sessionBus().asyncCall(message);+ // Effects are loaded and unloaded by name; a plain reconfigure neither+ // starts nor stops one, nor makes a running one read its settings again.+ QString method = QStringLiteral("reconfigureEffect");+ if (load != wasLoaded) {+ method = load ? QStringLiteral("loadEffect") : QStringLiteral("unloadEffect");+ } else if (!load) {+ method.clear();+ }+ if (!method.isEmpty()) {+ auto message = QDBusMessage::createMethodCall(QStringLiteral("org.kde.KWin"), QStringLiteral("/Effects"), QStringLiteral("org.kde.kwin.Effects"), method);+ message << QStringLiteral("org.wildos.snap");+ QDBusConnection::sessionBus().asyncCall(message);+ }reconfigureKWin();}@@ -802,6 +850,114 @@ void System::setAltTabAllDesktops(bool on)reconfigureKWin();}+namespace+{+// KWin's corner numbers and the names its [ElectricBorders] group uses.+const QList<std::pair<int, QString>> corners = {+ {1, QStringLiteral("TopRight")},+ {3, QStringLiteral("BottomRight")},+ {5, QStringLiteral("BottomLeft")},+ {7, QStringLiteral("TopLeft")},+};+// KWin's "no corner", which a list needs to stay empty: an empty list would+// read back as the default.+constexpr int noCorner = 9;+// Task view is KWin's Overview, which takes the top left corner unless told+// otherwise.+const QList<int> overviewDefault = {7};+}++QVariantMap System::screenCorners() const+{+ KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("kwinrc"));+ config->reparseConfiguration();+ const QList<int> overview = config->group(QStringLiteral("Effect-overview")).readEntry("BorderActivate", overviewDefault);+ const KConfigGroup borders = config->group(QStringLiteral("ElectricBorders"));+ QVariantMap result;+ for (const auto &[corner, name] : corners) {+ const QString action = borders.readEntry(name, QStringLiteral("None")).toLower();+ QString value = QStringLiteral("none");+ if (overview.contains(corner)) {+ value = QStringLiteral("taskview");+ } else if (action == QLatin1String("showdesktop")) {+ value = QStringLiteral("desktop");+ } else if (action == QLatin1String("lockscreen")) {+ value = QStringLiteral("lock");+ }+ result.insert(QString::number(corner), value);+ }+ return result;+}++void System::setScreenCorner(int corner, const QString &action)+{+ QString name;+ for (const auto &[number, key] : corners) {+ if (number == corner) {+ name = key;+ }+ }+ if (name.isEmpty()) {+ return;+ }+ KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("kwinrc"));+ config->reparseConfiguration();++ KConfigGroup overviewGroup = config->group(QStringLiteral("Effect-overview"));+ QList<int> overview = overviewGroup.readEntry("BorderActivate", overviewDefault);+ overview.removeAll(corner);+ overview.removeAll(noCorner);+ if (action == QLatin1String("taskview")) {+ overview.append(corner);+ }+ overviewGroup.writeEntry("BorderActivate", overview.isEmpty() ? QList<int>{noCorner} : overview);++ // A corner given to KWin's window view by hand would still fire beside+ // the new choice.+ KConfigGroup windowView = config->group(QStringLiteral("Effect-windowview"));+ for (const char *key : {"BorderActivate", "BorderActivateAll", "BorderActivateClass"}) {+ if (windowView.hasKey(key)) {+ QList<int> list = windowView.readEntry(key, QList<int>());+ if (list.removeAll(corner) > 0) {+ windowView.writeEntry(key, list.isEmpty() ? QList<int>{noCorner} : list);+ }+ }+ }++ const QString built = action == QLatin1String("desktop") ? QStringLiteral("ShowDesktop")+ : action == QLatin1String("lock") ? QStringLiteral("LockScreen")+ : QStringLiteral("None");+ config->group(QStringLiteral("ElectricBorders")).writeEntry(name, built);+ config->sync();+ reconfigureKWin();+}++bool System::taskbarShowDesktop() const+{+ return KSharedConfig::openConfig(QStringLiteral("wildosrc"))->group(QStringLiteral("Taskbar")).readEntry("ShowDesktop", true);+}++void System::setTaskbarShowDesktop(bool on)+{+ KSharedConfigPtr wildos = KSharedConfig::openConfig(QStringLiteral("wildosrc"));+ wildos->group(QStringLiteral("Taskbar")).writeEntry("ShowDesktop", on, KConfig::Notify);+ wildos->sync();+ Q_EMIT taskbarShowDesktopChanged();+}++bool System::taskbarPeek() const+{+ return KSharedConfig::openConfig(QStringLiteral("wildosrc"))->group(QStringLiteral("Taskbar")).readEntry("PeekDesktop", false);+}++void System::setTaskbarPeek(bool on)+{+ KSharedConfigPtr wildos = KSharedConfig::openConfig(QStringLiteral("wildosrc"));+ wildos->group(QStringLiteral("Taskbar")).writeEntry("PeekDesktop", on, KConfig::Notify);+ wildos->sync();+ Q_EMIT taskbarShowDesktopChanged();+}+void System::reconfigureKWin(){auto message = QDBusMessage::createMethodCall(QStringLiteral("org.kde.KWin"), QStringLiteral("/KWin"), QStringLiteral("org.kde.KWin"),@@ -836,7 +992,7 @@ QString System::formatBytes(qint64 bytes) const{// Units of 1024 labelled GB, as Windows shows sizes everywhere and as// Files shows them, so a drive reads the same in both places.- const QLocale locale(QLocale::English, QLocale::UnitedKingdom);+ const QLocale locale = QLocale::system();const double value = double(bytes);const double kb = 1024.0, mb = kb * 1024, gb = mb * 1024, tb = gb * 1024;if (value >= tb) {@@ -919,6 +1075,37 @@ void System::setTaskbarAllDesktops(bool all)}}+// The item's own "shown" setting (its contents/config/main.xml), which it+// reads live, so turning it off keeps it on the taskbar, and in its place,+// for turning on again.+namespace+{+const QString winModeScript = QStringLiteral(+ "var items = []; panels().forEach(function (p) { items = items.concat(p.widgets('org.wildos.winmode')); });");+}++void System::readTaskbarWinModeStatus()+{+ const QString shown = evaluatePlasmaScript(winModeScript+ + QStringLiteral("if (items.length) { items[0].currentConfigGroup = ['General']; print(String(items[0].readConfig('shown', true))); }"));+ const bool on = shown != QLatin1String("false");+ if (on != m_taskbarWinModeStatus) {+ m_taskbarWinModeStatus = on;+ Q_EMIT taskbarWinModeStatusChanged();+ }+}++void System::setTaskbarWinModeStatus(bool shown)+{+ evaluatePlasmaScript(winModeScript+ + QStringLiteral("items.forEach(function (w) { w.currentConfigGroup = ['General']; w.writeConfig('shown', %1); w.reloadConfig(); });")+ .arg(shown ? QStringLiteral("true") : QStringLiteral("false")));+ if (shown != m_taskbarWinModeStatus) {+ m_taskbarWinModeStatus = shown;+ Q_EMIT taskbarWinModeStatusChanged();+ }+}+// Plasma's own slideshow wallpaper, pointed at one folder. Turning it off// goes back to the single picture, which the image plugin still remembers.void System::setSlideshow(bool on, const QString &folder)@@ -1038,7 +1225,9 @@ void System::setUsbProtection(bool on)const QString service = QStringLiteral("org.freedesktop.systemd1");const QString path = QStringLiteral("/org/freedesktop/systemd1");const QString manager = QStringLiteral("org.freedesktop.systemd1.Manager");- const QStringList units = {QStringLiteral("usbguard.service")};+ // usbguard-dbus requires usbguard and is enabled on its own, so left+ // enabled it started USBGuard again at the next start-up.+ const QStringList units = {QStringLiteral("usbguard.service"), QStringLiteral("usbguard-dbus.service")};auto unitFiles = QDBusMessage::createMethodCall(service, path, manager, on ? QStringLiteral("EnableUnitFiles") : QStringLiteral("DisableUnitFiles"));if (on) {@@ -1393,6 +1582,32 @@ void System::reloadScreenLocker()QDBusConnection::sessionBus().asyncCall(message);}+namespace+{+// Windows mode's status (boards 4.13 and 4.14) is at the left end of the+// bar in both styles. A bar from when floating put it just before Start gets+// it moved back: Plasma's scripting can't reorder a panel, so the item is+// taken off and dropped on the bar's first pixel, which a panel takes to mean+// "before everything". It holds no settings of its own to lose; it is locked+// again afterwards, as the layout locks it.+const QString placeWinModeScript = QStringLiteral(+ "panels().forEach(function (p) {"+ " var all = p.widgets();"+ " all.sort(function (a, b) { return a.geometry.x - b.geometry.x; });"+ " var w = -1;"+ " for (var i = 0; i < all.length; i++) {"+ " if (all[i].type === 'org.wildos.winmode') w = i;"+ " }"+ " if (w <= 0) return;"+ " var locked = p.locked;"+ " p.locked = false;"+ " all[w].remove();"+ " var item = p.addWidget('org.wildos.winmode', 0, 0, -1, -1);"+ " if (item) { item.currentConfigGroup = []; item.writeConfig('immutability', 2); item.locked = true; }"+ " p.locked = locked;"+ "});");+}+// The panel (wildos-shell) watches this key and redraws straight away.void System::setTaskbarFloating(bool floating){@@ -1402,6 +1617,7 @@ void System::setTaskbarFloating(bool floating)// The panel's height keeps maximised windows clear of the bar: 52 px// docked, 76 floating (62 px pills 14 px above the screen edge).evaluatePlasmaScript(QStringLiteral("panels().forEach(function (p) { if (p.location === 'bottom') p.height = %1; });").arg(floating ? 76 : 52));+ evaluatePlasmaScript(placeWinModeScript);if (floating != m_taskbarFloating) {m_taskbarFloating = floating;Q_EMIT taskbarFloatingChanged();diff --git a/packages/wildos-settings/src/system.h b/packages/wildos-settings/src/system.hindex 6df32c7..0a8b506 100644--- a/packages/wildos-settings/src/system.h+++ b/packages/wildos-settings/src/system.h@@ -51,6 +51,14 @@ class System : public QObject// The taskbar shows windows from every desktop, not only the one in// use. Read on demand, as it costs a call to plasmashell.Q_PROPERTY(bool taskbarAllDesktops READ taskbarAllDesktops NOTIFY taskbarAllDesktopsChanged)+ // Windows mode's status at the taskbar's left end (org.wildos.winmode),+ // which only shows once Windows mode is set up. Read on demand too.+ Q_PROPERTY(bool taskbarWinModeStatus READ taskbarWinModeStatus NOTIFY taskbarWinModeStatusChanged)+ // The sliver at the taskbar's far right end that shows the desktop, and+ // whether resting the pointer on it shows the desktop until it moves+ // away (wildosrc [Taskbar], which the panel in wildos-shell follows).+ Q_PROPERTY(bool taskbarShowDesktop READ taskbarShowDesktop WRITE setTaskbarShowDesktop NOTIFY taskbarShowDesktopChanged)+ Q_PROPERTY(bool taskbarPeek READ taskbarPeek WRITE setTaskbarPeek NOTIFY taskbarShowDesktopChanged)Q_PROPERTY(QString wallpaperName READ wallpaperName NOTIFY wallpaperChanged)Q_PROPERTY(bool slideshow READ slideshow NOTIFY wallpaperChanged)Q_PROPERTY(QString slideshowFolder READ slideshowFolder NOTIFY wallpaperChanged)@@ -68,7 +76,12 @@ class System : public QObjectQ_PROPERTY(bool snapEdges READ snapEdges WRITE setSnapEdges NOTIFY kwinChanged)Q_PROPERTY(bool snapLayouts READ snapLayouts WRITE setSnapLayouts NOTIFY kwinChanged)+ Q_PROPERTY(bool snapAssist READ snapAssist WRITE setSnapAssist NOTIFY kwinChanged)Q_PROPERTY(bool altTabAllDesktops READ altTabAllDesktops WRITE setAltTabAllDesktops NOTIFY kwinChanged)+ // What each screen corner does, keyed by KWin's corner number (1 top+ // right, 3 bottom right, 5 bottom left, 7 top left): "taskview",+ // "desktop", "lock" or "none".+ Q_PROPERTY(QVariantMap screenCorners READ screenCorners NOTIFY kwinChanged)Q_PROPERTY(QString timeZone READ timeZone CONSTANT)Q_PROPERTY(QString region READ region CONSTANT)@@ -105,6 +118,11 @@ public:bool taskbarCentred() const { return m_taskbarCentred; }bool taskbarFloating() const { return m_taskbarFloating; }bool taskbarAllDesktops() const { return m_taskbarAllDesktops; }+ bool taskbarWinModeStatus() const { return m_taskbarWinModeStatus; }+ bool taskbarShowDesktop() const;+ void setTaskbarShowDesktop(bool on);+ bool taskbarPeek() const;+ void setTaskbarPeek(bool on);QString wallpaperName() const;bool slideshow() const { return m_slideshow; }QString slideshowFolder() const { return m_slideshowFolder; }@@ -122,8 +140,12 @@ public:void setSnapEdges(bool on);bool snapLayouts() const;void setSnapLayouts(bool on);+ bool snapAssist() const;+ void setSnapAssist(bool on);bool altTabAllDesktops() const;void setAltTabAllDesktops(bool on);+ QVariantMap screenCorners() const;+ Q_INVOKABLE void setScreenCorner(int corner, const QString &action);QString timeZone() const;QString region() const;@@ -143,12 +165,17 @@ public:// Light or dark: WildOS or WildOSLight, once that scheme is installed.Q_INVOKABLE bool hasColourScheme(const QString &name) const;Q_INVOKABLE void setColourScheme(const QString &name);+ // A scheme and an accent together (a theme), applied one after the+ // other so neither undoes the other.+ Q_INVOKABLE void setColours(const QString &name, const QColor &accent);Q_INVOKABLE void setAutomaticTheme();Q_INVOKABLE void setTaskbarHiding(int mode);Q_INVOKABLE void setTaskbarCentred(bool centred);Q_INVOKABLE void setTaskbarFloating(bool floating);Q_INVOKABLE void readTaskbarDesktops();Q_INVOKABLE void setTaskbarAllDesktops(bool all);+ Q_INVOKABLE void readTaskbarWinModeStatus();+ Q_INVOKABLE void setTaskbarWinModeStatus(bool shown);Q_INVOKABLE void setSlideshow(bool on, const QString &folder = {});Q_INVOKABLE void setTransparency(bool on);Q_INVOKABLE void setTextScale(int percent);@@ -187,6 +214,8 @@ Q_SIGNALS:void taskbarCentredChanged();void taskbarFloatingChanged();void taskbarAllDesktopsChanged();+ void taskbarWinModeStatusChanged();+ void taskbarShowDesktopChanged();void transparencyChanged();void textScaleChanged();void updatePolicyChanged();@@ -212,6 +241,7 @@ private:void readTextScale();void readTaskbarLayout();void reconfigureKWin();+ void applySnapEffect(bool layouts, bool assist);QString evaluatePlasmaScript(const QString &script) const;QString m_osName;@@ -234,6 +264,7 @@ private:bool m_taskbarCentred = true;bool m_taskbarFloating = false;bool m_taskbarAllDesktops = false;+ bool m_taskbarWinModeStatus = true;bool m_slideshow = false;QString m_slideshowFolder;int m_textScale = 100;diff --git a/packages/wildos-settings/src/themes.cpp b/packages/wildos-settings/src/themes.cppnew file mode 100644index 0000000..81e8578--- /dev/null+++ b/packages/wildos-settings/src/themes.cpp@@ -0,0 +1,360 @@+#include "themes.h"++#include "system.h"++#include <KConfigGroup>+#include <KSharedConfig>++#include <QDir>+#include <QFile>+#include <QFileInfo>+#include <QJsonArray>+#include <QJsonDocument>+#include <QJsonObject>+#include <QProcess>+#include <QStandardPaths>+#include <QTimer>++#include <algorithm>++#include <csignal>+#include <unistd.h>++namespace+{+const QString rgbTool = QStringLiteral("/usr/libexec/wildos/rgb-devices");+const QString defaultTheme = QStringLiteral("dawn");+// The underglow renderer's default custom colour, Overclock's neon.+const QColor defaultCustom(0x3d, 0xff, 0x7a);++QJsonObject readJson(const QString &path)+{+ QFile file(path);+ if (!file.open(QIODevice::ReadOnly)) {+ return {};+ }+ return QJsonDocument::fromJson(file.readAll()).object();+}++QColor jsonColour(const QJsonValue &value)+{+ if (value.isString()) {+ return QColor(value.toString());+ }+ const QJsonObject object = value.toObject();+ QColor colour(object.value(QStringLiteral("colour")).toString());+ if (colour.isValid()) {+ colour.setAlphaF(object.value(QStringLiteral("alpha")).toDouble(1.0));+ }+ return colour;+}++QString wallpaperName(const QString &path)+{+ const QString name = readJson(path + QStringLiteral("/metadata.json"))+ .value(QStringLiteral("KPlugin")).toObject()+ .value(QStringLiteral("Name")).toString();+ return name.isEmpty() ? QFileInfo(path).completeBaseName() : name;+}+}++Themes::Themes(QObject *parent)+ : QObject(parent)+{+ loadThemes();+ read();+ refreshRgbDevices();++ // Another Settings window, or the underglow pausing itself, can change+ // these too.+ m_watcher = KConfigWatcher::create(KSharedConfig::openConfig(QStringLiteral("wildosrc")));+ if (m_watcher) {+ connect(m_watcher.data(), &KConfigWatcher::configChanged, this, [this](const KConfigGroup &group) {+ const QString name = group.name();+ if (name == QLatin1String("Theme") || name == QLatin1String("Underglow") || name == QLatin1String("Lighting")) {+ read();+ }+ });+ }+}++void Themes::loadThemes()+{+ QMap<QString, QJsonObject> found;+ const QStringList dirs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("wildos/themes"), QStandardPaths::LocateDirectory);+ for (const QString &dir : dirs) {+ const auto entries = QDir(dir).entryInfoList({QStringLiteral("*.json")}, QDir::Files);+ for (const QFileInfo &info : entries) {+ // The first location wins, as for any XDG data file.+ if (!found.contains(info.completeBaseName())) {+ found.insert(info.completeBaseName(), readJson(info.absoluteFilePath()));+ }+ }+ }++ QList<QJsonObject> sorted = found.values();+ std::stable_sort(sorted.begin(), sorted.end(), [](const QJsonObject &a, const QJsonObject &b) {+ return a.value(QStringLiteral("order")).toInt(1000) < b.value(QStringLiteral("order")).toInt(1000);+ });++ for (const QJsonObject &theme : std::as_const(sorted)) {+ const QString id = theme.value(QStringLiteral("id")).toString();+ if (id.isEmpty()) {+ continue;+ }+ const QJsonObject accent = theme.value(QStringLiteral("accent")).toObject();+ QStringList more;+ const QJsonArray extra = theme.value(QStringLiteral("moreWallpapers")).toArray();+ for (const QJsonValue &path : extra) {+ if (QFileInfo::exists(path.toString())) {+ more << wallpaperName(path.toString());+ }+ }+ m_themes << QVariantMap{+ {QStringLiteral("id"), id},+ {QStringLiteral("name"), theme.value(QStringLiteral("name")).toString()},+ {QStringLiteral("description"), theme.value(QStringLiteral("description")).toString()},+ {QStringLiteral("mode"), theme.value(QStringLiteral("mode")).toString()},+ {QStringLiteral("accent"), jsonColour(accent.value(QStringLiteral("colour")))},+ {QStringLiteral("accentName"), accent.value(QStringLiteral("name")).toString()},+ {QStringLiteral("textOnAccent"), jsonColour(theme.value(QStringLiteral("textOnAccent")))},+ {QStringLiteral("glass"), jsonColour(theme.value(QStringLiteral("glass")))},+ {QStringLiteral("taskbarGlass"), jsonColour(theme.value(QStringLiteral("taskbarGlass")))},+ {QStringLiteral("wallpaper"), theme.value(QStringLiteral("wallpaper")).toString()},+ {QStringLiteral("moreWallpaperNames"), more},+ {QStringLiteral("underglow"), theme.value(QStringLiteral("underglow")).toBool()},+ {QStringLiteral("isDefault"), theme.value(QStringLiteral("default")).toBool()},+ };+ }+}++QVariantMap Themes::currentTheme() const+{+ for (const QVariant &theme : m_themes) {+ if (theme.toMap().value(QStringLiteral("id")).toString() == m_current) {+ return theme.toMap();+ }+ }+ return {};+}++void Themes::read()+{+ KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("wildosrc"));+ config->reparseConfiguration();++ const QString current = config->group(QStringLiteral("Theme")).readEntry("Id", defaultTheme);+ if (current != m_current) {+ m_current = current;+ Q_EMIT currentChanged();+ }++ const KConfigGroup underglow = config->group(QStringLiteral("Underglow"));+ m_underglow = underglow.readEntry("Enabled", false);+ m_underglowFromTheme = underglow.readEntry("FromTheme", false);+ m_underglowColour = underglow.readEntry("Colour", QStringLiteral("accent"));+ if (m_underglowColour != QLatin1String("custom") && m_underglowColour != QLatin1String("rgb")) {+ m_underglowColour = QStringLiteral("accent");+ }+ m_underglowCustom = QColor(underglow.readEntry("Custom", defaultCustom.name()));+ if (!m_underglowCustom.isValid()) {+ m_underglowCustom = defaultCustom;+ }+ m_underglowEffect = underglow.readEntry("Effect", QString());+ if (m_underglowColour == QLatin1String("rgb")) {+ m_underglowEffect = QStringLiteral("flowing");+ } else if (m_underglowEffect != QLatin1String("breathing")) {+ m_underglowEffect = QStringLiteral("steady");+ }+ m_lightingRgb = config->group(QStringLiteral("Lighting")).readEntry("Rgb", false);+ Q_EMIT underglowChanged();+}++namespace+{+// wildos-auto-theme keeps Start and the flyouts' Plasma style in step with+// the theme. It starts with the session, so after an update the one running+// is the old program until the next sign-in, and a version from before+// themes never switches the style. A running copy whose program file has+// been replaced is swapped for the new one.+void restartStaleAutoTheme()+{+ bool stale = false;+ const QStringList pids = QDir(QStringLiteral("/proc")).entryList(QDir::Dirs | QDir::NoDotAndDotDot);+ for (const QString &pid : pids) {+ bool number = false;+ const int value = pid.toInt(&number);+ if (!number || QFileInfo(QStringLiteral("/proc/") + pid).ownerId() != getuid()) {+ continue;+ }+ const QString exe = QFile::symLinkTarget(QStringLiteral("/proc/%1/exe").arg(pid));+ if (exe.startsWith(QStringLiteral("/usr/bin/wildos-auto-theme")) && exe.endsWith(QStringLiteral(" (deleted)"))) {+ ::kill(value, SIGTERM);+ stale = true;+ }+ }+ if (stale) {+ QProcess::startDetached(QStringLiteral("wildos-auto-theme"), {});+ }+}+}++void Themes::apply(const QString &id)+{+ QVariantMap theme;+ for (const QVariant &entry : std::as_const(m_themes)) {+ if (entry.toMap().value(QStringLiteral("id")).toString() == id) {+ theme = entry.toMap();+ }+ }+ if (theme.isEmpty()) {+ return;+ }++ KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("wildosrc"));+ config->reparseConfiguration();+ config->group(QStringLiteral("Theme")).writeEntry("Id", id, KConfig::Notify);++ // Underglow that came on with a theme goes off with it; underglow the+ // person turned on stays. A theme with underglow brings its own look.+ KConfigGroup underglow = config->group(QStringLiteral("Underglow"));+ if (theme.value(QStringLiteral("underglow")).toBool()) {+ const bool theirs = m_underglow && !m_underglowFromTheme;+ underglow.writeEntry("Enabled", true, KConfig::Notify);+ underglow.writeEntry("Colour", QStringLiteral("accent"), KConfig::Notify);+ underglow.writeEntry("Effect", QStringLiteral("steady"), KConfig::Notify);+ underglow.writeEntry("FromTheme", !theirs, KConfig::Notify);+ } else if (m_underglow && m_underglowFromTheme) {+ underglow.writeEntry("Enabled", false, KConfig::Notify);+ underglow.writeEntry("FromTheme", false, KConfig::Notify);+ }+ config->sync();+ read();+ restartStaleAutoTheme();++ QQmlEngine *engine = qmlEngine(this);+ auto system = engine ? engine->singletonInstance<System *>("WildOS.Settings", "System") : nullptr;+ if (!system) {+ return;+ }+ const QString scheme = theme.value(QStringLiteral("mode")).toString() == QLatin1String("light") ? QStringLiteral("WildOSLight") : QStringLiteral("WildOS");+ system->setColours(scheme, theme.value(QStringLiteral("accent")).value<QColor>());+ const QString wallpaper = theme.value(QStringLiteral("wallpaper")).toString();+ if (QFileInfo::exists(wallpaper)) {+ system->setWallpaper(wallpaper);+ }+}++// A change made on this page makes the underglow the person's own, so a+// later theme without underglow leaves it on.+void Themes::writeUnderglow(const QString &key, const QVariant &value)+{+ KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("wildosrc"));+ config->reparseConfiguration();+ KConfigGroup group = config->group(QStringLiteral("Underglow"));+ group.writeEntry(key.toUtf8().constData(), value, KConfig::Notify);+ group.writeEntry("FromTheme", false, KConfig::Notify);+ config->sync();+ read();+}++void Themes::setUnderglow(bool on)+{+ writeUnderglow(QStringLiteral("Enabled"), on);+}++void Themes::setUnderglowColour(const QString &colour)+{+ if (colour != QLatin1String("accent") && colour != QLatin1String("custom") && colour != QLatin1String("rgb")) {+ return;+ }+ KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("wildosrc"));+ config->reparseConfiguration();+ KConfigGroup group = config->group(QStringLiteral("Underglow"));+ group.writeEntry("Colour", colour, KConfig::Notify);+ // RGB only flows; a single colour is steady or breathing.+ if (colour == QLatin1String("rgb")) {+ group.writeEntry("Effect", QStringLiteral("flowing"), KConfig::Notify);+ } else if (m_underglowEffect == QLatin1String("flowing")) {+ group.writeEntry("Effect", QStringLiteral("steady"), KConfig::Notify);+ }+ if (colour == QLatin1String("custom") && !group.hasKey("Custom")) {+ group.writeEntry("Custom", m_underglowCustom.name(), KConfig::Notify);+ }+ group.writeEntry("FromTheme", false, KConfig::Notify);+ config->sync();+ read();+}++void Themes::setUnderglowCustom(const QColor &colour)+{+ if (!colour.isValid()) {+ return;+ }+ writeUnderglow(QStringLiteral("Custom"), colour.name(QColor::HexRgb));+}++void Themes::setUnderglowEffect(const QString &effect)+{+ const bool rgb = m_underglowColour == QLatin1String("rgb");+ if (rgb ? effect != QLatin1String("flowing") : effect != QLatin1String("steady") && effect != QLatin1String("breathing")) {+ return;+ }+ writeUnderglow(QStringLiteral("Effect"), effect);+}++void Themes::setLightingRgb(bool on)+{+ KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("wildosrc"));+ config->reparseConfiguration();+ config->group(QStringLiteral("Lighting")).writeEntry("Rgb", on, KConfig::Notify);+ config->sync();+ read();+}++void Themes::refreshRgbDevices()+{+ if (m_rgbProbe) {+ return;+ }+ if (!QFileInfo(rgbTool).isExecutable()) {+ if (m_rgbDevices != 0) {+ m_rgbDevices = 0;+ Q_EMIT rgbDevicesChanged();+ }+ return;+ }+ m_rgbProbe = new QProcess(this);+ // Looking for lighting can mean waking USB devices; a probe that hangs+ // counts as none rather than holding the row back for ever.+ QTimer::singleShot(15000, m_rgbProbe, [probe = m_rgbProbe] {+ probe->kill();+ });+ connect(m_rgbProbe, &QProcess::finished, this, [this](int code, QProcess::ExitStatus status) {+ const int count = status == QProcess::NormalExit && code == 0 ? QString::fromUtf8(m_rgbProbe->readAllStandardOutput()).trimmed().toInt() : 0;+ m_rgbProbe->deleteLater();+ m_rgbProbe = nullptr;+ if (count != m_rgbDevices) {+ m_rgbDevices = qMax(0, count);+ Q_EMIT rgbDevicesChanged();+ }+ });+ connect(m_rgbProbe, &QProcess::errorOccurred, this, [this](QProcess::ProcessError error) {+ if (error == QProcess::FailedToStart && m_rgbProbe) {+ m_rgbProbe->deleteLater();+ m_rgbProbe = nullptr;+ }+ });+ m_rgbProbe->start(rgbTool, {});+}++QString Themes::accentName(const QColor &colour) const+{+ for (const QVariant &theme : m_themes) {+ const QVariantMap map = theme.toMap();+ if (map.value(QStringLiteral("accent")).value<QColor>().rgb() == colour.rgb()) {+ return map.value(QStringLiteral("accentName")).toString();+ }+ }+ return {};+}diff --git a/packages/wildos-settings/src/themes.h b/packages/wildos-settings/src/themes.hnew file mode 100644index 0000000..3889db7--- /dev/null+++ b/packages/wildos-settings/src/themes.h@@ -0,0 +1,97 @@+#pragma once++#include <QColor>+#include <QObject>+#include <QQmlEngine>+#include <QVariantList>++#include <KConfigWatcher>++class QProcess;++// Settings > Personalisation > Themes (SettingsThemes.dc). A theme is one+// of /usr/share/wildos/themes/<id>.json (wildos-branding): the wallpaper,+// light or dark, the accent and the glass tint in one go. Applying one+// writes the choice to wildosrc [Theme] Id, which WildOS.UI's Theme reads+// for the glass and wildos-auto-theme for the Plasma style, and sets the+// scheme, accent and wallpaper through System like the pages for each.+//+// It also holds the taskbar underglow and RGB lighting settings, which the+// underglow renderer (KWin) and the OpenRGB mirroring read from wildosrc:+// [Underglow] Enabled, Colour=accent|custom|rgb, Custom=#rrggbb,+// Effect=steady|breathing|flowing+// [Lighting] Rgb+// [Underglow] FromTheme marks underglow that is on only because a theme+// turned it on, so the next theme can turn it off again.+class Themes : public QObject+{+ Q_OBJECT+ QML_ELEMENT+ QML_SINGLETON++ // Every installed theme in its order: {id, name, description, mode,+ // accent, accentName, textOnAccent, glass, taskbarGlass, wallpaper,+ // moreWallpaperNames, underglow, isDefault}.+ Q_PROPERTY(QVariantList themes READ themes CONSTANT)+ Q_PROPERTY(QString current READ current NOTIFY currentChanged)+ Q_PROPERTY(QVariantMap currentTheme READ currentTheme NOTIFY currentChanged)++ Q_PROPERTY(bool underglow READ underglow NOTIFY underglowChanged)+ Q_PROPERTY(QString underglowColour READ underglowColour NOTIFY underglowChanged)+ Q_PROPERTY(QColor underglowCustom READ underglowCustom NOTIFY underglowChanged)+ Q_PROPERTY(QString underglowEffect READ underglowEffect NOTIFY underglowChanged)+ Q_PROPERTY(bool lightingRgb READ lightingRgb NOTIFY underglowChanged)+ // Keyboards, mice and other lighting OpenRGB can drive; 0 when there+ // are none or the counting tool is missing.+ Q_PROPERTY(int rgbDevices READ rgbDevices NOTIFY rgbDevicesChanged)++public:+ explicit Themes(QObject *parent = nullptr);++ QVariantList themes() const { return m_themes; }+ QString current() const { return m_current; }+ QVariantMap currentTheme() const;++ bool underglow() const { return m_underglow; }+ QString underglowColour() const { return m_underglowColour; }+ QColor underglowCustom() const { return m_underglowCustom; }+ QString underglowEffect() const { return m_underglowEffect; }+ bool lightingRgb() const { return m_lightingRgb; }+ int rgbDevices() const { return m_rgbDevices; }++ Q_INVOKABLE void apply(const QString &id);++ Q_INVOKABLE void setUnderglow(bool on);+ // accent, custom or rgb; the effect follows (rgb flows, the others are+ // steady unless breathing was chosen).+ Q_INVOKABLE void setUnderglowColour(const QString &colour);+ Q_INVOKABLE void setUnderglowCustom(const QColor &colour);+ Q_INVOKABLE void setUnderglowEffect(const QString &effect);+ Q_INVOKABLE void setLightingRgb(bool on);+ Q_INVOKABLE void refreshRgbDevices();++ // A theme accent's name ("Neon"), or "" for any other colour.+ Q_INVOKABLE QString accentName(const QColor &colour) const;++Q_SIGNALS:+ void currentChanged();+ void underglowChanged();+ void rgbDevicesChanged();++private:+ void loadThemes();+ void read();+ void writeUnderglow(const QString &key, const QVariant &value);++ QVariantList m_themes;+ QString m_current;+ bool m_underglow = false;+ bool m_underglowFromTheme = false;+ QString m_underglowColour;+ QColor m_underglowCustom;+ QString m_underglowEffect;+ bool m_lightingRgb = false;+ int m_rgbDevices = 0;+ QProcess *m_rgbProbe = nullptr;+ KConfigWatcher::Ptr m_watcher;+};diff --git a/packages/wildos-settings/src/updates.cpp b/packages/wildos-settings/src/updates.cppindex 2b84374..a47faf9 100644--- a/packages/wildos-settings/src/updates.cpp+++ b/packages/wildos-settings/src/updates.cpp@@ -191,6 +191,7 @@ void Updates::listUpdates()});connect(list, &Transaction::finished, this, [this, collected, ids](Transaction::Exit status, uint) {if (status != Transaction::ExitSuccess) {+ m_installAfterList = false;if (m_state != QLatin1String("error")) {setState(QStringLiteral("error"), QStringLiteral("Wild OS could not read the list of updates."));}@@ -210,6 +211,12 @@ void Updates::listUpdates()m_pending = *ids;Q_EMIT updatesChanged();setState(m_updates.isEmpty() ? QStringLiteral("uptodate") : QStringLiteral("available"));+ if (m_installAfterList) {+ m_installAfterList = false;+ if (!m_pending.isEmpty()) {+ startInstall();+ }+ }});}@@ -218,14 +225,37 @@ void Updates::install()if (m_pending.isEmpty() || m_state == QLatin1String("installing")) {return;}+ m_staleRetried = false;+ startInstall();+}++void Updates::startInstall()+{+ m_staleRetrying = false;setState(QStringLiteral("installing"));Transaction *update = Daemon::updatePackages(m_pending, Transaction::TransactionFlagOnlyTrusted);watchProgress(update);connect(update, &Transaction::errorCode, this, [this](Transaction::Error error, const QString &) {+ // The list being installed came from the last check, and the update+ // server may have moved on since (a newer build replaces the files+ // it named). Checking again fixes that, so it happens once here+ // rather than as an error the person has to retry by hand.+ const bool stale = error == Transaction::ErrorPackageDownloadFailed || error == Transaction::ErrorPackageNotFound+ || error == Transaction::ErrorUpdateNotFound || error == Transaction::ErrorDepResolutionFailed;+ if (stale && !m_staleRetried) {+ m_staleRetrying = true;+ return;+ }setState(QStringLiteral("error"), errorText(error, true));});connect(update, &Transaction::finished, this, [this](Transaction::Exit status, uint) {loadHistory();+ if (status != Transaction::ExitSuccess && m_staleRetrying) {+ m_staleRetrying = false;+ m_staleRetried = true;+ refreshThenInstall();+ return;+ }if (status == Transaction::ExitSuccess) {if (needsRestart(m_pending)) {QFile marker(restartMarker());@@ -252,6 +282,24 @@ void Updates::install()});}+void Updates::refreshThenInstall()+{+ Transaction *refresh = Daemon::refreshCache(true);+ watchProgress(refresh);+ connect(refresh, &Transaction::errorCode, this, [this](Transaction::Error error, const QString &) {+ setState(QStringLiteral("error"), errorText(error, true));+ });+ connect(refresh, &Transaction::finished, this, [this](Transaction::Exit status, uint) {+ readLastChecked();+ if (status == Transaction::ExitSuccess) {+ m_installAfterList = true;+ listUpdates();+ } else if (m_state != QLatin1String("error")) {+ setState(QStringLiteral("error"), QStringLiteral("The updates could not be installed."));+ }+ });+}+void Updates::loadHistory(){// PackageKit-Qt listens for the daemon's Transaction signal with a@@ -340,6 +388,8 @@ QString Updates::errorText(Transaction::Error error, bool installing)case Transaction::ErrorNotAuthorized:return installing ? QStringLiteral("Installing needs the administrator password, and it was not given."): QStringLiteral("Checking needs the administrator password, and it was not given.");+ case Transaction::ErrorPackageDownloadFailed:+ return QStringLiteral("Some updates could not be downloaded. Check your internet connection and try again.");case Transaction::ErrorNoSpaceOnDevice:return QStringLiteral("There is not enough free space to install the updates.");case Transaction::ErrorLockRequired:diff --git a/packages/wildos-settings/src/updates.h b/packages/wildos-settings/src/updates.hindex 3153de2..998bfcb 100644--- a/packages/wildos-settings/src/updates.h+++ b/packages/wildos-settings/src/updates.h@@ -72,6 +72,8 @@ private:void readLastChecked();void watchProgress(PackageKit::Transaction *transaction);static QString errorText(PackageKit::Transaction::Error error, bool installing);+ void startInstall();+ void refreshThenInstall();QString m_state = QStringLiteral("idle");QVariantList m_updates;@@ -84,4 +86,10 @@ private:QString m_detail;QString m_error;bool m_restartNeeded = false;+ // An install that failed because the update lists were out of date+ // (a package file the lists name is gone) checks again and retries+ // once by itself.+ bool m_staleRetrying = false;+ bool m_staleRetried = false;+ bool m_installAfterList = false;};diff --git a/packages/wildos-settings/src/windowsmode.cpp b/packages/wildos-settings/src/windowsmode.cppindex 09ef8ef..9c77aef 100644--- a/packages/wildos-settings/src/windowsmode.cpp+++ b/packages/wildos-settings/src/windowsmode.cpp@@ -89,10 +89,28 @@ QString WindowsMode::setOption(const QString &key, const QString &value)return call(QStringLiteral("SetOption"), {key, value});}-QString WindowsMode::setProductKey(const QString &key)+void WindowsMode::setProductKey(const QString &key){- // Activation waits on Microsoft's servers.- return call(QStringLiteral("SetProductKey"), {key}, 300000);+ if (!m_service) {+ Q_EMIT productKeyDone(QStringLiteral("Windows mode isn't installed on this PC."));+ return;+ }+ if (m_activating) {+ return;+ }+ m_activating = true;+ Q_EMIT activatingChanged();+ // Windows may have to start first, and activation then waits on+ // Microsoft's servers, so Settings carries on meanwhile.+ m_service->setTimeout(900000);+ auto *watcher = new QDBusPendingCallWatcher(m_service->asyncCall(QStringLiteral("SetProductKey"), key), this);+ connect(watcher, &QDBusPendingCallWatcher::finished, this, [this, watcher] {+ watcher->deleteLater();+ const QDBusPendingReply<QString> reply = *watcher;+ m_activating = false;+ Q_EMIT activatingChanged();+ Q_EMIT productKeyDone(reply.isError() ? QStringLiteral("Windows mode didn't answer. Restart the PC, then try again.") : reply.value());+ });}bool WindowsMode::keyShapeValid(const QString &key) const@@ -132,7 +150,7 @@ QString WindowsMode::size(double bytes) constif (!(bytes > 0)) {return {};}- const QLocale locale(QLocale::English, QLocale::UnitedKingdom);+ const QLocale locale = QLocale::system();const double gb = bytes / 1e9;return gb >= 1 ? QStringLiteral("%1 GB").arg(locale.toString(gb, 'f', 1)) : QStringLiteral("%1 MB").arg(qRound(bytes / 1e6));}diff --git a/packages/wildos-settings/src/windowsmode.h b/packages/wildos-settings/src/windowsmode.hindex 3565f30..ca1b252 100644--- a/packages/wildos-settings/src/windowsmode.h+++ b/packages/wildos-settings/src/windowsmode.h@@ -24,6 +24,9 @@ class WindowsMode : public QObjectQ_PROPERTY(QString state READ state NOTIFY statusChanged)// The memory limits this PC can offer: [{value, text}]Q_PROPERTY(QVariantList memoryChoices READ memoryChoices CONSTANT)+ // A product key is going in; it can take minutes (Windows starting,+ // then Microsoft's activation servers).+ Q_PROPERTY(bool activating READ activating NOTIFY activatingChanged)public:explicit WindowsMode(QObject *parent = nullptr);@@ -32,9 +35,11 @@ public:QVariantMap status() const { return m_status; }QString state() const { return m_status.value(QStringLiteral("state")).toString(); }QVariantList memoryChoices() const;+ bool activating() const { return m_activating; }Q_INVOKABLE QString setOption(const QString &key, const QString &value);- Q_INVOKABLE QString setProductKey(const QString &key);+ // Answers with productKeyDone: "" once activated, or why not.+ Q_INVOKABLE void setProductKey(const QString &key);Q_INVOKABLE bool keyShapeValid(const QString &key) const;Q_INVOKABLE QString checkUpdates();Q_INVOKABLE QString openDesktop();@@ -47,6 +52,8 @@ public:Q_SIGNALS:void statusChanged();+ void activatingChanged();+ void productKeyDone(const QString &result);private Q_SLOTS:void refresh();@@ -56,4 +63,5 @@ private:QDBusInterface *m_service = nullptr;QVariantMap m_status;+ bool m_activating = false;};diff --git a/packages/wildos-setup/CMakeLists.txt b/packages/wildos-setup/CMakeLists.txtindex 1060e3e..ac76334 100644--- a/packages/wildos-setup/CMakeLists.txt+++ b/packages/wildos-setup/CMakeLists.txt@@ -5,17 +5,22 @@ set(CMAKE_CXX_STANDARD 20)set(CMAKE_CXX_STANDARD_REQUIRED ON)include(GNUInstallDirs)-find_package(Qt6 6.8 REQUIRED COMPONENTS Core DBus)+find_package(Qt6 6.8 REQUIRED COMPONENTS Core DBus Network)qt_standard_project_setup(REQUIRES 6.8)qt_add_executable(wildos-setup-helper src/main.cpp src/service.cpp src/service.h)-target_link_libraries(wildos-setup-helper PRIVATE Qt6::Core Qt6::DBus)+target_link_libraries(wildos-setup-helper PRIVATE Qt6::Core Qt6::DBus Qt6::Network)++# Runs as the new account, in its first session.+qt_add_executable(wildos-setup-wallet src/wallet.cpp)+target_link_libraries(wildos-setup-wallet PRIVATE Qt6::Core Qt6::DBus)set(LIBEXEC ${CMAKE_INSTALL_PREFIX}/libexec/wildos)-install(TARGETS wildos-setup-helper RUNTIME DESTINATION ${LIBEXEC})+install(TARGETS wildos-setup-helper wildos-setup-wallet RUNTIME DESTINATION ${LIBEXEC})install(PROGRAMS data/wildos-setup-boot data/wildos-setup-session DESTINATION ${LIBEXEC})install(FILES data/wildos-setup-boot.service data/wildos-setup-helper.serviceDESTINATION ${CMAKE_INSTALL_PREFIX}/lib/systemd/system)+install(FILES data/wildos-setup-wallet.service DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/systemd/user)install(FILES data/org.wildos.Setup1.service DESTINATION ${CMAKE_INSTALL_DATADIR}/dbus-1/system-services)install(FILES data/org.wildos.Setup1.conf DESTINATION ${CMAKE_INSTALL_DATADIR}/dbus-1/system.d)install(FILES data/org.wildos.setup.policy DESTINATION ${CMAKE_INSTALL_DATADIR}/polkit-1/actions)diff --git a/packages/wildos-setup/data/org.wildos.Setup1.conf b/packages/wildos-setup/data/org.wildos.Setup1.confindex 4614adf..839fa51 100644--- a/packages/wildos-setup/data/org.wildos.Setup1.conf+++ b/packages/wildos-setup/data/org.wildos.Setup1.conf@@ -2,7 +2,8 @@<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN""http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd"><!-- Anyone may ask; the helper checks polkit (org.wildos.setup.policy) on- every call and refuses everything once setup has finished. -->+ every call and refuses everything once setup has finished, except+ TakeWalletKey, which it answers only for the account setup made. --><busconfig><policy user="root"><allow own="org.wildos.Setup1"/>diff --git a/packages/wildos-setup/data/wildos-setup-wallet.service b/packages/wildos-setup/data/wildos-setup-wallet.servicenew file mode 100644index 0000000..9f39d18--- /dev/null+++ b/packages/wildos-setup/data/wildos-setup-wallet.service@@ -0,0 +1,17 @@+[Unit]+Description=Open the wallet of the account first boot setup made+# Setup leaves the wallet's salt and no wallet; every later session has both.+ConditionPathExists=%h/.local/share/kwalletd/kdewallet.salt+ConditionPathExists=!%h/.local/share/kwalletd/kdewallet.kwl+PartOf=graphical-session.target+# Where pam_kwallet's own unit opens the wallet, so nothing in the session+# asks for a secret first and gets KWallet's create-a-wallet dialog.+Before=plasma-plasmashell.service plasma-kded6.service xdg-desktop-autostart.target+After=plasma-kwin_wayland.service plasma-kcminit.service++[Service]+Type=oneshot+ExecStart=/usr/libexec/wildos/wildos-setup-wallet+Slice=background.slice+# The desktop waits for this; it must never hold the first sign-in up.+TimeoutStartSec=30diff --git a/packages/wildos-setup/debian/links b/packages/wildos-setup/debian/linksnew file mode 100644index 0000000..b7407bf--- /dev/null+++ b/packages/wildos-setup/debian/links@@ -0,0 +1 @@+usr/lib/systemd/user/wildos-setup-wallet.service usr/lib/systemd/user/plasma-workspace.target.wants/wildos-setup-wallet.servicediff --git a/packages/wildos-setup/src/service.cpp b/packages/wildos-setup/src/service.cppindex 7091a5e..0bd8f68 100644--- a/packages/wildos-setup/src/service.cpp+++ b/packages/wildos-setup/src/service.cpp@@ -13,6 +13,7 @@#include <QFileInfo>#include <QJsonDocument>#include <QJsonObject>+#include <QPasswordDigestor>#include <QProcess>#include <QRegularExpression>@@ -20,6 +21,7 @@#include <fcntl.h>#include <grp.h>#include <pwd.h>+#include <sys/random.h>#include <sys/stat.h>#include <unistd.h>@@ -42,6 +44,13 @@ const QStringList baseGroups = {QStringLiteral("console"), QStringLiteral("audioQStringLiteral("netdev"), QStringLiteral("bluetooth"), QStringLiteral("scanner"), QStringLiteral("privleap")};const QStringList adminGroups = {QStringLiteral("sudo"), QStringLiteral("lpadmin")};+// pam_kwallet's own numbers (KWALLET_PAM_* in kwallet-pam's pam_kwallet.c).+// The key made here has to be the one it makes from the same password at+// every later sign-in, or the wallet stops opening.+constexpr int walletSaltSize = 56;+constexpr int walletKeySize = 56;+constexpr int walletIterations = 50000;+struct Result {int code = -1;QString error;@@ -289,25 +298,33 @@ void setHint(const QString &userName, const QString &hint)bus.call(set, QDBus::Block, 10000);}-// ~/.local/state/wildos-welcome/first-run.json, owned by the account.-bool writePlan(const struct passwd *pw, const QByteArray &plan)+// Folders under the account's home, made and owned by it; empty when one+// could not be made, or is not a plain folder.+QString accountFolder(const struct passwd *pw, const QStringList &parts){- if (plan.size() > 1024 * 1024 || !QJsonDocument::fromJson(plan).isObject()) {- return false;- }QString dir = QFile::decodeName(pw->pw_dir);- for (const QString &part : {QStringLiteral(".local"), QStringLiteral("state"), QStringLiteral("wildos-welcome")}) {+ for (const QString &part : parts) {dir += QLatin1Char('/') + part;const QByteArray path = QFile::encodeName(dir);if (::mkdir(path.constData(), 0700) != 0 && errno != EEXIST) {- return false;+ return {};}struct stat st;if (::lstat(path.constData(), &st) != 0 || !S_ISDIR(st.st_mode) || ::chown(path.constData(), pw->pw_uid, pw->pw_gid) != 0) {- return false;+ return {};}}- return writeAtomically(dir + QStringLiteral("/first-run.json"), plan, 0600, pw->pw_uid, pw->pw_gid);+ return dir;+}++// ~/.local/state/wildos-welcome/first-run.json, owned by the account.+bool writePlan(const struct passwd *pw, const QByteArray &plan)+{+ if (plan.size() > 1024 * 1024 || !QJsonDocument::fromJson(plan).isObject()) {+ return false;+ }+ const QString dir = accountFolder(pw, {QStringLiteral(".local"), QStringLiteral("state"), QStringLiteral("wildos-welcome")});+ return !dir.isEmpty() && writeAtomically(dir + QStringLiteral("/first-run.json"), plan, 0600, pw->pw_uid, pw->pw_gid);}// The locales Debian can make, from the locales package's list.@@ -376,7 +393,9 @@ SetupService::SetupService(QObject *parent)m_idle.setInterval(20 * 60 * 1000);m_idle.setSingleShot(true);connect(&m_idle, &QTimer::timeout, this, [this] {- if (!m_finishing) {+ // The wallet key exists only in this process, so it stays up until+ // Finish hands over to the account that needs it.+ if (!m_finishing && m_walletKey.isEmpty()) {QCoreApplication::quit();}});@@ -422,6 +441,7 @@ bool SetupService::authorised(const QString &action)void SetupService::removeEarlierAccount(){+ forgetWalletKey();const QString earlier = readText(stateFile).trimmed();if (earlier.isEmpty()) {return;@@ -527,6 +547,7 @@ QString SetupService::CreateAccount(const QString &realName, const QString &passconst struct passwd *pw = ::getpwnam(QFile::encodeName(userName).constData());if (pw) {writeKeyboard(pw);+ prepareWallet(pw, password);}setAvatar(userName, avatar);if (!hint.isEmpty()) {@@ -550,6 +571,43 @@ QString SetupService::CreateAccount(const QString &realName, const QString &passreturn userName;}+// The salt pam_kwallet would otherwise make at the first sign-in with a+// password, and the key it would derive from that password with it. Only+// the key is kept, in this process, never on disk.+void SetupService::prepareWallet(const struct passwd *pw, const QString &password)+{+ forgetWalletKey();+ const QString dir = accountFolder(pw, {QStringLiteral(".local"), QStringLiteral("share"), QStringLiteral("kwalletd")});+ QByteArray salt(walletSaltSize, '\0');+ if (dir.isEmpty() || ::getrandom(salt.data(), salt.size(), 0) != salt.size()+ || !writeAtomically(dir + QStringLiteral("/kdewallet.salt"), salt, 0600, pw->pw_uid, pw->pw_gid)) {+ // pam_kwallet makes its own salt at the first sign-in with the+ // password, so only the first session goes without a wallet.+ qWarning("could not prepare the wallet's salt");+ return;+ }+ m_walletKey = QPasswordDigestor::deriveKeyPbkdf2(QCryptographicHash::Sha512, password.toUtf8(), salt, walletIterations, walletKeySize);+ m_walletUid = pw->pw_uid;+}++void SetupService::forgetWalletKey()+{+ m_walletKey.clear();+ m_walletUid = 0;+}++QByteArray SetupService::TakeWalletKey()+{+ const QDBusReply<uint> caller = connection().interface()->serviceUid(message().service());+ if (!m_finishing || m_walletKey.isEmpty() || !caller.isValid() || caller.value() != m_walletUid) {+ refuse(QStringLiteral("NoKey"), QStringLiteral("There is no wallet key for this account."));+ return {};+ }+ const QByteArray key = m_walletKey;+ forgetWalletKey();+ return key;+}+void SetupService::Finish(const QString &plan){touch();@@ -613,13 +671,19 @@ void SetupService::handOver(const QString &userName, uint uid)// removes it at the next start, whatever happens here.auto *poll = new QTimer(this);auto *waited = new int(0);- connect(poll, &QTimer::timeout, this, [poll, waited, uid, userName] {+ connect(poll, &QTimer::timeout, this, [this, poll, waited, uid, userName] {++*waited;- if (QFile::exists(QStringLiteral("/run/systemd/users/%1").arg(uid)) || *waited >= 180) {+ if (!QFile::exists(QStringLiteral("/run/systemd/users/%1").arg(uid)) && *waited < 180) {+ return;+ }+ if (namesUser(firstSignIn, userName)) {+ removeDurably(firstSignIn);+ }+ // The session takes the wallet key in its first seconds; one that+ // has not after ten minutes is not going to.+ if (m_walletKey.isEmpty() || *waited >= 600) {poll->stop();- if (namesUser(firstSignIn, userName)) {- removeDurably(firstSignIn);- }+ forgetWalletKey();delete waited;QCoreApplication::quit();}diff --git a/packages/wildos-setup/src/service.h b/packages/wildos-setup/src/service.hindex 57ff86b..05f2071 100644--- a/packages/wildos-setup/src/service.h+++ b/packages/wildos-setup/src/service.h@@ -4,6 +4,8 @@#include <QObject>#include <QTimer>+struct passwd;+/* org.wildos.Setup1, the root half of the first boot setup session.** The setup pages run as the locked system user wildos-setup. Everything@@ -11,7 +13,9 @@* naming the computer, and handing over to the new account at the end.* Each call is checked with polkit (actions in org.wildos.setup.policy,* granted only to the setup user in 10-wildos-setup.rules) and refused once- * the first boot marker is gone, so nothing here works after setup.+ * the first boot marker is gone, so nothing here works after setup. The+ * one exception is TakeWalletKey, for the new account itself, while this+ * process is still running from setup.*/class SetupService : public QObject, protected QDBusContext{@@ -45,13 +49,24 @@ public Q_SLOTS:* session. */void Finish(const QString &plan);+ /* The wallet key made from the new account's password in CreateAccount,+ * handed once to that account's first session (wildos-setup-wallet),+ * which opens its KWallet with it. The automatic first sign-in has no+ * password for pam_kwallet to make it from. Only the new account may+ * take it, only after Finish, and it is forgotten once taken. */+ QByteArray TakeWalletKey();+private:bool authorised(const QString &action);bool refuse(const QString &name, const QString &sentence);void removeEarlierAccount();+ void prepareWallet(const struct passwd *pw, const QString &password);+ void forgetWalletKey();void handOver(const QString &userName, uint uid);void touch();QTimer m_idle;bool m_finishing = false;+ QByteArray m_walletKey;+ uint m_walletUid = 0;};diff --git a/packages/wildos-setup/src/wallet.cpp b/packages/wildos-setup/src/wallet.cppnew file mode 100644index 0000000..104e01c--- /dev/null+++ b/packages/wildos-setup/src/wallet.cpp@@ -0,0 +1,69 @@+#include <QCoreApplication>+#include <QDBusConnection>+#include <QDBusMessage>+#include <QDBusReply>+#include <QDir>+#include <QFileInfo>++/* wildos-setup-wallet: opens the KWallet of the account first boot setup+ * made, in that account's first session (wildos-setup-wallet.service).+ *+ * Setup signs the new account in automatically, so pam_kwallet has no+ * password to create the wallet with, and the first app to ask for a+ * secret would get KWallet's own create-a-wallet dialog. A wallet made+ * there with another password never opens at sign-in again. Setup's+ * helper made the key pam_kwallet makes from the password, with the salt+ * pam_kwallet reads; kwalletd creates the wallet with that key here, the+ * same way it does when pam_kwallet hands it one, and every later sign-in+ * with the password opens it.+ */+namespace+{+QDBusMessage kwallet(const QString &method)+{+ return QDBusMessage::createMethodCall(QStringLiteral("org.kde.kwalletd6"), QStringLiteral("/modules/kwalletd6"), QStringLiteral("org.kde.KWallet"),+ method);+}+}++int main(int argc, char *argv[])+{+ QCoreApplication app(argc, argv);+ app.setApplicationName(QStringLiteral("wildos-setup-wallet"));++ // Setup leaves the salt and no wallet. Anything else is a later+ // session, or an account setup did not make.+ const QString dir = QDir::homePath() + QStringLiteral("/.local/share/kwalletd");+ if (!QFileInfo::exists(dir + QStringLiteral("/kdewallet.salt")) || QFileInfo::exists(dir + QStringLiteral("/kdewallet.kwl"))) {+ return 0;+ }++ const QDBusMessage take = QDBusMessage::createMethodCall(QStringLiteral("org.wildos.Setup1"), QStringLiteral("/org/wildos/Setup1"),+ QStringLiteral("org.wildos.Setup1"), QStringLiteral("TakeWalletKey"));+ const QDBusReply<QByteArray> key = QDBusConnection::systemBus().call(take, QDBus::Block, 30000);+ if (!key.isValid()) {+ qWarning("no wallet key from setup: %s", qPrintable(key.error().message()));+ return 1;+ }++ QDBusConnection session = QDBusConnection::sessionBus();+ const QDBusReply<QString> localWallet = session.call(kwallet(QStringLiteral("localWallet")), QDBus::Block, 30000);+ const QString wallet = localWallet.isValid() && !localWallet.value().isEmpty() ? localWallet.value() : QStringLiteral("kdewallet");++ // pamOpen never replies. kwalletd handles one connection's calls in+ // order, so isOpen, sent after it, answers once it has run.+ QDBusMessage open = kwallet(QStringLiteral("pamOpen"));+ open << wallet << key.value() << 0;+ if (!session.send(open)) {+ qWarning("could not reach kwalletd");+ return 1;+ }+ QDBusMessage isOpen = kwallet(QStringLiteral("isOpen"));+ isOpen << wallet;+ const QDBusReply<bool> opened = session.call(isOpen, QDBus::Block, 30000);+ if (!opened.isValid() || !opened.value()) {+ qWarning("kwalletd did not open %s with setup's key", qPrintable(wallet));+ return 1;+ }+ return 0;+}diff --git a/packages/wildos-shell/CMakeLists.txt b/packages/wildos-shell/CMakeLists.txtindex 4de7682..d9207b4 100644--- a/packages/wildos-shell/CMakeLists.txt+++ b/packages/wildos-shell/CMakeLists.txt@@ -17,6 +17,7 @@ qt_add_qml_module(wildosshellNO_GENERATE_PLUGIN_SOURCECLASS_NAME WildOSShellPluginSOURCES src/pillmask.cpp src/pillmask.h src/plugin.cpp src/launchwatcher.cpp src/launchwatcher.h src/taskbarstyle.cpp src/taskbarstyle.h+ src/underglow.cpp src/underglow.h src/underglowsettings.cpp src/underglowsettings.h)target_include_directories(wildosshell PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)target_link_libraries(wildosshell PRIVATE Qt6::Core Qt6::Gui Qt6::Qml Qt6::DBus KF6::ConfigCore)@@ -25,6 +26,19 @@ set(QML_DIR ${QT6_INSTALL_QML}/org/wildos/shell)install(TARGETS wildosshell LIBRARY DESTINATION ${QML_DIR})install(FILES ${CMAKE_CURRENT_BINARY_DIR}/org/wildos/shell/qmldir DESTINATION ${QML_DIR})+# The underglow is a KWin script, not an effect: it uses only KWin's QML+# scripting API, which holds across KWin releases, where a C++ effect has to+# be rebuilt for each KWin version.+install(DIRECTORY kwin/org.wildos.underglow DESTINATION ${CMAKE_INSTALL_DATADIR}/kwin/scripts)+install(DIRECTORY kwin/org.wildos.appwindows DESTINATION ${CMAKE_INSTALL_DATADIR}/kwin/scripts)++include(CTest)+if(BUILD_TESTING)+ add_subdirectory(tests)+endif()+add_subdirectory(effects/roundcorners)+add_subdirectory(effects/outline)+add_subdirectory(effects/blurinactive)add_subdirectory(windowmenu)add_subdirectory(slowkeys)diff --git a/packages/wildos-shell/debian/changelog b/packages/wildos-shell/debian/changelogindex 9327b34..91758d3 100644--- a/packages/wildos-shell/debian/changelog+++ b/packages/wildos-shell/debian/changelog@@ -1,3 +1,10 @@+wildos-shell (0.1.1) trixie; urgency=medium++ * Settings > Accessibility can outline every window, with a thick accent ring+ round the one in use, and blur and dim every window but the one in use.++ -- Wild OS Developers <[email protected]> Tue, 10 Nov 2026 08:10:42 +0000+wildos-shell (0.1.0) trixie; urgency=medium* Initial release.diff --git a/packages/wildos-shell/debian/control b/packages/wildos-shell/debian/controlindex 85daebd..acba7e6 100644--- a/packages/wildos-shell/debian/control+++ b/packages/wildos-shell/debian/control@@ -19,6 +19,7 @@ Depends:libkwin6 (= ${kwin:Version}),qml6-module-qt5compat-graphicaleffects,qml6-module-qt-labs-folderlistmodel,+ qml6-module-qtqml-models,qml6-module-qtquick-templates,wildos-ui,Description: Wild OS changes to Plasma and KWin@@ -37,6 +38,12 @@ Description: Wild OS changes to Plasma and KWin* a KWin effect that rounds the bottom corners of decorated windows tothe title bar's 14 px radius, with the edge and shadow carried round,and squares the corners of maximised, full screen and snapped windows;+ * two KWin effects for Settings > Accessibility, off until turned on+ there: an outline round every window with a thick accent ring round+ the one in use, and a blur that softens and dims every window but the+ one in use;+ * a KWin script that draws the taskbar underglow chosen in Settings, a+ glowing line along the top edge of the docked taskbar;* a "Wild OS" sign-in session in place of Plasma's own entries..The patched files are taken from the Plasma and KWin versions named in thediff --git a/packages/wildos-shell/effects/blurinactive/CMakeLists.txt b/packages/wildos-shell/effects/blurinactive/CMakeLists.txtnew file mode 100644index 0000000..090be69--- /dev/null+++ b/packages/wildos-shell/effects/blurinactive/CMakeLists.txt@@ -0,0 +1,13 @@+# Built the same way as roundcorners, which explains the finds.+find_package(ECM 6.0 REQUIRED NO_MODULE)+list(APPEND CMAKE_MODULE_PATH ${ECM_MODULE_PATH} ${ECM_FIND_MODULE_DIR})+find_package(Qt6 6.8 REQUIRED COMPONENTS DBus Quick Widgets)+find_package(KWin 6.3 REQUIRED)+find_package(KF6 6.10 REQUIRED COMPONENTS Config)++add_library(wildos_blurinactive MODULE blurinactive.cpp blurinactive.h ../focus/focus.h blurinactive.qrc)+set_target_properties(wildos_blurinactive PROPERTIES AUTOMOC ON AUTORCC ON PREFIX "")+set_property(TARGET wildos_blurinactive APPEND PROPERTY AUTOMOC_MACRO_NAMES KWIN_EFFECT_FACTORY_SUPPORTED)+target_link_libraries(wildos_blurinactive PRIVATE KWin::kwin KF6::ConfigCore Qt6::Core Qt6::Gui)++install(TARGETS wildos_blurinactive LIBRARY DESTINATION ${QT6_INSTALL_PLUGINS}/kwin/effects/plugins)diff --git a/packages/wildos-shell/effects/blurinactive/blurinactive.cpp b/packages/wildos-shell/effects/blurinactive/blurinactive.cppnew file mode 100644index 0000000..0a750d5--- /dev/null+++ b/packages/wildos-shell/effects/blurinactive/blurinactive.cpp@@ -0,0 +1,571 @@+/*+ SPDX-FileCopyrightText: 2026 Wild OS Developers <[email protected]>++ SPDX-License-Identifier: GPL-2.0-or-later+*/++#include "blurinactive.h"++#include "../focus/focus.h"++#include <core/output.h>+#include <core/pixelgrid.h>+#include <core/rendertarget.h>+#include <core/renderviewport.h>+#include <effect/effecthandler.h>+#include <effect/effectwindow.h>+#include <opengl/glframebuffer.h>+#include <opengl/glplatform.h>+#include <opengl/glshader.h>+#include <opengl/glshadermanager.h>+#include <opengl/gltexture.h>+#include <opengl/glvertexbuffer.h>+#include <opengl/openglcontext.h>+#include <scene/windowitem.h>+#include <window.h>++#include <KConfigGroup>+#include <KSharedConfig>++#include <QFile>+#include <QVector2D>+#include <QVector3D>++#include <cmath>++Q_LOGGING_CATEGORY(WILDOS_BLURINACTIVE, "wildos.blurinactive", QtWarningMsg)++static void ensureResources()+{+ Q_INIT_RESOURCE(blurinactive);+}++namespace KWin+{++struct Strength {+ int iterations;+ float offset;+ qreal dim;+};++// The five steps of the slider in Settings. Each pass count has a range of+// offsets it can use before the blur shows blocks or diagonal lines; these+// stay inside the ranges KWin's blur effect uses (BlurEffect::+// initBlurStrengthValues). The dim grows with the blur, but stays light+// enough that the windows behind can still be read when looked at.+static constexpr Strength s_strengths[] = {+ {2, 1.5f, 0.08},+ {2, 3.0f, 0.11},+ {3, 3.0f, 0.14},+ {3, 5.0f, 0.17},+ {4, 6.0f, 0.20},+};++static const QString s_configGroup = QStringLiteral("Effect-wildos_blurinactive");++BlurInactiveEffect::BlurInactiveEffect()+{+ reconfigure(ReconfigureAll);++ connect(effects, &EffectsHandler::windowActivated, this, [this](EffectWindow *w) {+ setFocus(WildOS::focusAfterActivation(w, m_focus));+ });+ connect(effects, &EffectsHandler::windowAdded, this, [this](EffectWindow *w) {+ const auto refresh = [this]() {+ updateTargets();+ };+ connect(w, &EffectWindow::windowFullScreenChanged, this, refresh);+ connect(w, &EffectWindow::windowKeepAboveChanged, this, refresh);+ connect(w, &EffectWindow::windowModalityChanged, this, refresh);+ connect(w, &EffectWindow::minimizedChanged, this, [this](EffectWindow *w) {+ // KWin only says which window is next if there is one.+ if (w == m_focus && w->isMinimized()) {+ m_focus = nullptr;+ }+ updateTargets();+ });+ updateTargets();+ });+ connect(effects, &EffectsHandler::windowClosed, this, [this](EffectWindow *w) {+ if (m_focus == w) {+ // KWin hands focus to the next window as this one goes; wait for+ // that rather than blurring everything for a frame.+ m_focus = nullptr;+ QMetaObject::invokeMethod(this, &BlurInactiveEffect::updateTargets, Qt::QueuedConnection);+ }+ });+ connect(effects, &EffectsHandler::windowDeleted, this, &BlurInactiveEffect::forget);+ connect(effects, &EffectsHandler::activeFullScreenEffectChanged, this, &BlurInactiveEffect::updateTargets);+ connect(effects, &EffectsHandler::desktopChanged, this, &BlurInactiveEffect::updateTargets);+ connect(effects, &EffectsHandler::screenLockingChanged, this, [] {+ effects->addRepaintFull();+ });++ m_focus = WildOS::focusAfterActivation(effects->activeWindow(), nullptr);+ updateTargets();+}++BlurInactiveEffect::~BlurInactiveEffect()+{+ effects->makeOpenGLContextCurrent();+ for (auto &[w, state] : m_windows) {+ disconnect(state->damaged);+ disconnect(state->resized);+ }+ m_windows.clear();+ m_downsample.reset();+ m_upsample.reset();+ m_composite.reset();+ effects->addRepaintFull();+}++bool BlurInactiveEffect::supported()+{+ return effects->isOpenGLCompositing();+}++void BlurInactiveEffect::reconfigure(ReconfigureFlags flags)+{+ Q_UNUSED(flags)+ KSharedConfig::Ptr config = KSharedConfig::openConfig(QStringLiteral("kwinrc"));+ config->reparseConfiguration();+ const KConfigGroup group(config, s_configGroup);+ m_strength = std::clamp(group.readEntry("Strength", 3), 1, int(std::size(s_strengths)));+ m_desktop = group.readEntry("Desktop", true);+ const Strength &strength = s_strengths[m_strength - 1];+ m_iterations = strength.iterations;+ m_offset = strength.offset;+ m_dim = strength.dim;+ m_duration = animationTime(std::chrono::milliseconds(250));++ for (auto &[w, state] : m_windows) {+ state->dirty = true;+ w->addRepaintFull();+ }+ updateTargets();+}++bool BlurInactiveEffect::shouldBlur(EffectWindow *w) const+{+ // Overview and the other full screen effects draw windows of their own;+ // the ones underneath are not seen.+ if (effects->activeFullScreenEffect() || w->isMinimized() || !w->isOnCurrentDesktop()) {+ return false;+ }+ if (w->isDesktop()) {+ return m_desktop && m_focus;+ }+ // Full screen video and windows kept above the rest (picture in+ // picture) are being watched even when another window has focus.+ if (!WildOS::isWorkWindow(w) || w->isFullScreen() || w->keepAbove()) {+ return false;+ }+ return !WildOS::belongTogether(w, m_focus);+}++void BlurInactiveEffect::updateTargets()+{+ const auto windows = effects->stackingOrder();+ for (EffectWindow *w : windows) {+ // A closing window keeps what it had while it animates away.+ if (w->isDeleted()) {+ continue;+ }+ const qreal target = shouldBlur(w) ? 1.0 : 0.0;+ auto it = m_windows.find(w);+ if (it == m_windows.end()) {+ if (target == 0.0) {+ continue;+ }+ auto state = std::make_unique<State>();+ state->itemEffect = ItemEffect(w->windowItem());+ state->damaged = connect(w, &EffectWindow::windowDamaged, this, [this](EffectWindow *w) {+ if (auto it = m_windows.find(w); it != m_windows.end()) {+ it->second->dirty = true;+ // The blur reaches past the damaged area, so all of the+ // window is drawn again, not only what changed.+ w->addRepaintFull();+ }+ });+ state->resized = connect(w, &EffectWindow::windowExpandedGeometryChanged, this, [this](EffectWindow *w) {+ if (auto it = m_windows.find(w); it != m_windows.end()) {+ it->second->dirty = true;+ }+ });+ it = m_windows.emplace(w, std::move(state)).first;+ }+ if (it->second->target != target) {+ it->second->target = target;+ w->addRepaintFull();+ }+ }+}++void BlurInactiveEffect::setFocus(EffectWindow *w)+{+ if (w == m_focus) {+ return;+ }+ m_focus = w;+ updateTargets();+}++void BlurInactiveEffect::forget(EffectWindow *w)+{+ auto it = m_windows.find(w);+ if (it == m_windows.end()) {+ return;+ }+ disconnect(it->second->damaged);+ disconnect(it->second->resized);+ effects->makeOpenGLContextCurrent();+ m_windows.erase(it);+ if (m_focus == w) {+ m_focus = nullptr;+ }+}++void BlurInactiveEffect::prePaintScreen(ScreenPrePaintData &data, std::chrono::milliseconds presentTime)+{+ bool moving = false;+ for (const auto &[w, state] : m_windows) {+ moving = moving || state->progress != state->target;+ }+ if (moving) {+ // The first frame of a change only starts the clock.+ const qreal elapsed = m_lastPresent.count() ? qreal((presentTime - m_lastPresent).count()) : 0.0;+ const qreal step = m_duration > 0 ? elapsed / m_duration : 1.0;+ for (auto &[w, state] : m_windows) {+ if (state->progress < state->target) {+ state->progress = std::min(state->target, state->progress + step);+ } else if (state->progress > state->target) {+ state->progress = std::max(state->target, state->progress - step);+ }+ }+ m_lastPresent = presentTime;+ }+ effects->prePaintScreen(data, presentTime);+}++void BlurInactiveEffect::postPaintScreen()+{+ bool moving = false;+ for (auto it = m_windows.begin(); it != m_windows.end();) {+ State &state = *it->second;+ if (state.progress != state.target) {+ it->first->addRepaintFull();+ moving = true;+ }+ // Painting is the one place the compositor's context is known to be+ // current, so a window back to sharp gives up its textures here.+ if (state.progress <= 0.0 && state.target <= 0.0) {+ disconnect(state.damaged);+ disconnect(state.resized);+ it = m_windows.erase(it);+ } else {+ ++it;+ }+ }+ if (!moving) {+ m_lastPresent = std::chrono::milliseconds::zero();+ }+ effects->postPaintScreen();+}++bool BlurInactiveEffect::ensureShaders()+{+ if (m_composite) {+ return true;+ }+ if (m_shadersFailed) {+ return false;+ }+ ensureResources();++ // Same choice of dialect as KWin's own generated shaders.+ const auto context = OpenGlContext::currentContext();+ QByteArray header;+ bool modern;+ if (context->isOpenGLES()) {+ modern = context->glslVersion() >= Version(3, 0);+ header = modern ? QByteArrayLiteral("#version 300 es\n") : QByteArray();+ header += QByteArrayLiteral("precision highp float;\n");+ } else {+ modern = context->glslVersion() >= Version(1, 40);+ header = modern ? QByteArrayLiteral("#version 140\n") : QByteArray();+ }+ if (modern) {+ header += QByteArrayLiteral("#define IN in\n#define TEXTURE texture\n#define FRAG_COLOR fragColor\nout vec4 fragColor;\n");+ } else {+ header += QByteArrayLiteral("#define IN varying\n#define TEXTURE texture2D\n#define FRAG_COLOR gl_FragColor\n");+ }++ const auto load = [&header](const QString &name, ShaderTraits traits) -> std::unique_ptr<GLShader> {+ QFile file(QStringLiteral(":/wildos/blurinactive/") + name);+ if (!file.open(QIODevice::ReadOnly)) {+ qCWarning(WILDOS_BLURINACTIVE) << "Could not read" << name;+ return nullptr;+ }+ auto shader = ShaderManager::instance()->generateCustomShader(traits, QByteArray(), header + file.readAll());+ if (!shader || !shader->isValid()) {+ qCWarning(WILDOS_BLURINACTIVE) << name << "failed to build";+ return nullptr;+ }+ return shader;+ };++ m_downsample = load(QStringLiteral("downsample.frag"), ShaderTrait::MapTexture);+ m_upsample = load(QStringLiteral("upsample.frag"), ShaderTrait::MapTexture);+ m_composite = load(QStringLiteral("composite.frag"),+ ShaderTrait::MapTexture | ShaderTrait::Modulate | ShaderTrait::AdjustSaturation | ShaderTrait::TransformColorspace);+ if (!m_downsample || !m_upsample || !m_composite) {+ m_downsample.reset();+ m_upsample.reset();+ m_composite.reset();+ m_shadersFailed = true;+ return false;+ }++ m_downOffsetLocation = m_downsample->uniformLocation("offset");+ m_downHalfpixelLocation = m_downsample->uniformLocation("halfpixel");+ m_upOffsetLocation = m_upsample->uniformLocation("offset");+ m_upHalfpixelLocation = m_upsample->uniformLocation("halfpixel");+ m_offsetLocation = m_composite->uniformLocation("offset");+ m_halfpixelLocation = m_composite->uniformLocation("halfpixel");+ m_progressLocation = m_composite->uniformLocation("progress");+ m_dimLocation = m_composite->uniformLocation("dim");+ m_expandedOriginLocation = m_composite->uniformLocation("expandedOrigin");+ m_expandedSizeLocation = m_composite->uniformLocation("expandedSize");+ m_frameSizeLocation = m_composite->uniformLocation("frameSize");+ m_radiusLocation = m_composite->uniformLocation("radius");+ return true;+}++bool BlurInactiveEffect::render(EffectWindow *w, State &state)+{+ const Output *screen = w->screen();+ const qreal scale = screen ? screen->scale() : 1.0;+ const QRectF logical = snapToPixels(w->expandedGeometry(), scale);+ const QSize size = (logical.size() * scale).toSize();+ if (size.isEmpty()) {+ return false;+ }++ if (state.textures.size() != size_t(m_iterations + 1) || state.textures[0]->size() != size || state.textureScale != scale) {+ state.textures.clear();+ state.framebuffers.clear();+ for (int i = 0; i <= m_iterations; ++i) {+ const QSize levelSize(std::max(1, size.width() >> i), std::max(1, size.height() >> i));+ auto texture = GLTexture::allocate(GL_RGBA8, levelSize);+ if (!texture) {+ state.textures.clear();+ state.framebuffers.clear();+ return false;+ }+ texture->setFilter(GL_LINEAR);+ texture->setWrapMode(GL_CLAMP_TO_EDGE);+ auto framebuffer = std::make_unique<GLFramebuffer>(texture.get());+ if (!framebuffer->valid()) {+ state.textures.clear();+ state.framebuffers.clear();+ return false;+ }+ state.textures.push_back(std::move(texture));+ state.framebuffers.push_back(std::move(framebuffer));+ }+ state.textureScale = scale;+ state.dirty = true;+ }++ if (state.dirty && !w->isDeleted()) {+ RenderTarget renderTarget(state.framebuffers[0].get());+ RenderViewport viewport(logical, scale, renderTarget);+ GLFramebuffer::pushFramebuffer(state.framebuffers[0].get());+ glClearColor(0.0, 0.0, 0.0, 0.0);+ glClear(GL_COLOR_BUFFER_BIT);+ WindowPaintData data;+ data.setOpacity(1.0);+ // Called from inside this effect's drawWindow, so the window is drawn+ // by the effects after this one (the rounded corners) and not by the+ // ones before it, such as KWin's blur behind translucent windows.+ effects->drawWindow(renderTarget, viewport, w, PAINT_WINDOW_TRANSFORMED | PAINT_WINDOW_TRANSLUCENT, infiniteRegion(), data);+ GLFramebuffer::popFramebuffer();+ blur(state);+ state.dirty = false;+ }+ return true;+}++void BlurInactiveEffect::blur(State &state)+{+ GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer();+ vbo->reset();+ vbo->setAttribLayout(std::span(GLVertexBuffer::GLVertex2DLayout), sizeof(GLVertex2D));+ const auto map = vbo->map<GLVertex2D>(6);+ if (!map) {+ return;+ }+ // The unit square, with the texture's y turned to match the projection:+ // offscreen textures are the GL way up.+ const QVector2D corners[] = {{0, 0}, {1, 1}, {0, 1}, {0, 0}, {1, 0}, {1, 1}};+ for (int i = 0; i < 6; ++i) {+ (*map)[i] = GLVertex2D{.position = corners[i], .texcoord = QVector2D(corners[i].x(), 1.0f - corners[i].y())};+ }+ vbo->unmap();+ vbo->bindArrays();++ QMatrix4x4 projection;+ projection.ortho(QRectF(0.0, 0.0, 1.0, 1.0));+ glDisable(GL_BLEND);++ {+ ShaderBinder binder(m_downsample.get());+ m_downsample->setUniform(GLShader::Mat4Uniform::ModelViewProjectionMatrix, projection);+ m_downsample->setUniform(m_downOffsetLocation, m_offset);+ for (size_t i = 1; i < state.framebuffers.size(); ++i) {+ const GLTexture *read = state.textures[i - 1].get();+ m_downsample->setUniform(m_downHalfpixelLocation, QVector2D(0.5f / read->width(), 0.5f / read->height()));+ state.textures[i - 1]->bind();+ GLFramebuffer::pushFramebuffer(state.framebuffers[i].get());+ vbo->draw(GL_TRIANGLES, 0, 6);+ GLFramebuffer::popFramebuffer();+ }+ }++ {+ ShaderBinder binder(m_upsample.get());+ m_upsample->setUniform(GLShader::Mat4Uniform::ModelViewProjectionMatrix, projection);+ m_upsample->setUniform(m_upOffsetLocation, m_offset);+ // Back up to level 1; the last step up to full size happens as the+ // window is put on screen.+ for (size_t i = state.framebuffers.size() - 1; i > 1; --i) {+ const GLTexture *read = state.textures[i].get();+ m_upsample->setUniform(m_upHalfpixelLocation, QVector2D(0.5f / read->width(), 0.5f / read->height()));+ state.textures[i]->bind();+ GLFramebuffer::pushFramebuffer(state.framebuffers[i - 1].get());+ vbo->draw(GL_TRIANGLES, 0, 6);+ GLFramebuffer::popFramebuffer();+ }+ }++ vbo->unbindArrays();+}++void BlurInactiveEffect::composite(const RenderTarget &renderTarget, const RenderViewport &viewport, EffectWindow *w, const QRegion ®ion, const WindowPaintData &data, State &state)+{+ const qreal scale = viewport.scale();+ const QRectF expanded = snapToPixels(w->expandedGeometry(), scale);+ const QRectF frame = snapToPixels(w->frameGeometry(), scale);+ const QRectF visible = expanded.translated(-frame.topLeft());++ GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer();+ vbo->reset();+ vbo->setAttribLayout(std::span(GLVertexBuffer::GLVertex2DLayout), sizeof(GLVertex2D));+ const auto map = vbo->map<GLVertex2D>(6);+ if (!map) {+ return;+ }+ const float x0 = visible.left() * scale;+ const float y0 = visible.top() * scale;+ const float x1 = visible.right() * scale;+ const float y1 = visible.bottom() * scale;+ (*map)[0] = GLVertex2D{.position = {x0, y0}, .texcoord = {0, 1}};+ (*map)[1] = GLVertex2D{.position = {x1, y1}, .texcoord = {1, 0}};+ (*map)[2] = GLVertex2D{.position = {x0, y1}, .texcoord = {0, 0}};+ (*map)[3] = GLVertex2D{.position = {x0, y0}, .texcoord = {0, 1}};+ (*map)[4] = GLVertex2D{.position = {x1, y0}, .texcoord = {1, 1}};+ (*map)[5] = GLVertex2D{.position = {x1, y1}, .texcoord = {1, 0}};+ vbo->unmap();+ vbo->bindArrays();++ // The blur only covers the window's own rounded shape; its shadow is+ // left as it is drawn. Maximised and snapped windows and the desktop+ // have square corners.+ qreal radius = 12.0;+ const Window *window = w->window();+ if (w->isDesktop()+ || (window && (window->maximizeMode() == MaximizeFull || window->tile() || window->quickTileMode() != QuickTileMode(QuickTileFlag::None)))) {+ radius = 0.0;+ } else if (w->hasDecoration()) {+ radius = 14.0;+ }++ const GLTexture *blurred = state.textures[1].get();+ const qreal rgb = data.brightness() * data.opacity();+ const qreal a = data.opacity();+ const auto toXYZ = renderTarget.colorDescription().containerColorimetry().toXYZ();++ ShaderBinder binder(m_composite.get());+ QMatrix4x4 mvp = viewport.projectionMatrix();+ mvp.translate(std::round(frame.x() * scale), std::round(frame.y() * scale));+ m_composite->setUniform(GLShader::Mat4Uniform::ModelViewProjectionMatrix, mvp * data.toMatrix(scale));+ m_composite->setUniform(GLShader::Vec4Uniform::ModulationConstant, QVector4D(rgb, rgb, rgb, a));+ m_composite->setUniform(GLShader::FloatUniform::Saturation, data.saturation());+ m_composite->setUniform(GLShader::Vec3Uniform::PrimaryBrightness, QVector3D(toXYZ(1, 0), toXYZ(1, 1), toXYZ(1, 2)));+ m_composite->setUniform(GLShader::IntUniform::Sampler, 0);+ m_composite->setUniform(GLShader::IntUniform::Sampler1, 1);+ m_composite->setColorspaceUniforms(ColorDescription::sRGB, renderTarget.colorDescription(), RenderingIntent::Perceptual);+ m_composite->setUniform(m_offsetLocation, m_offset);+ m_composite->setUniform(m_halfpixelLocation, QVector2D(0.5f / blurred->width(), 0.5f / blurred->height()));+ m_composite->setUniform(m_progressLocation, float(state.progress));+ m_composite->setUniform(m_dimLocation, float(m_dim));+ m_composite->setUniform(m_expandedOriginLocation, QVector2D(visible.x(), visible.y()));+ m_composite->setUniform(m_expandedSizeLocation, QVector2D(visible.width(), visible.height()));+ m_composite->setUniform(m_frameSizeLocation, QVector2D(frame.width(), frame.height()));+ m_composite->setUniform(m_radiusLocation, float(radius));++ const bool clipping = region != infiniteRegion();+ const QRegion clipRegion = clipping ? viewport.mapToRenderTarget(region) : infiniteRegion();+ if (clipping) {+ glEnable(GL_SCISSOR_TEST);+ }+ glEnable(GL_BLEND);+ glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);++ glActiveTexture(GL_TEXTURE1);+ state.textures[1]->bind();+ glActiveTexture(GL_TEXTURE0);+ state.textures[0]->bind();+ vbo->draw(clipRegion, GL_TRIANGLES, 0, 6, clipping);+ state.textures[0]->unbind();+ glActiveTexture(GL_TEXTURE1);+ state.textures[1]->unbind();+ glActiveTexture(GL_TEXTURE0);++ glDisable(GL_BLEND);+ if (clipping) {+ glDisable(GL_SCISSOR_TEST);+ }+ vbo->unbindArrays();+}++void BlurInactiveEffect::drawWindow(const RenderTarget &renderTarget, const RenderViewport &viewport, EffectWindow *w, int mask, const QRegion ®ion, WindowPaintData &data)+{+ const auto it = m_windows.find(w);+ if (it == m_windows.end() || it->second->progress <= 0.0 || !ensureShaders() || !render(w, *it->second)) {+ effects->drawWindow(renderTarget, viewport, w, mask, region, data);+ return;+ }+ composite(renderTarget, viewport, w, region, data, *it->second);+}++bool BlurInactiveEffect::isActive() const+{+ return !m_windows.empty() && !effects->isScreenLocked();+}++int BlurInactiveEffect::requestedEffectChainPosition() const+{+ // After KWin's blur behind translucent windows (20), which has to see+ // the screen rather than this effect's texture; after the outline (55),+ // which stays sharp on top; before the rounded corners (60), so the+ // window is blurred already rounded.+ return 58;+}++KWIN_EFFECT_FACTORY_SUPPORTED(BlurInactiveEffect, "metadata.json", return BlurInactiveEffect::supported();)++} // namespace KWin++#include "blurinactive.moc"diff --git a/packages/wildos-shell/effects/blurinactive/blurinactive.h b/packages/wildos-shell/effects/blurinactive/blurinactive.hnew file mode 100644index 0000000..7957c7e--- /dev/null+++ b/packages/wildos-shell/effects/blurinactive/blurinactive.h@@ -0,0 +1,109 @@+/*+ SPDX-FileCopyrightText: 2026 Wild OS Developers <[email protected]>++ SPDX-License-Identifier: GPL-2.0-or-later+*/++#pragma once++#include <effect/effect.h>+#include <scene/item.h>++#include <QMetaObject>++#include <chrono>+#include <map>+#include <memory>+#include <vector>++namespace KWin+{++class GLFramebuffer;+class GLShader;+class GLTexture;+class EffectWindow;++// Settings > Accessibility > Blur windows in the background: every window+// but the one in use (and, if chosen, the desktop) is softened and dimmed a+// little, so the window in use is the only sharp thing on screen. KWin's own+// Dim Inactive only darkens.+//+// A blurred window is drawn into a texture of its own, blurred with the same+// dual Kawase passes KWin's blur effect uses, and composited back with its+// own alpha so its outline and rounded corners stay crisp. The blur is only+// redone when the window's content changes; a window that is not blurred+// costs nothing, and with the setting off the effect is not loaded at all.+class BlurInactiveEffect : public Effect+{+ Q_OBJECT++public:+ BlurInactiveEffect();+ ~BlurInactiveEffect() override;++ static bool supported();++ void reconfigure(ReconfigureFlags flags) override;+ void prePaintScreen(ScreenPrePaintData &data, std::chrono::milliseconds presentTime) override;+ void drawWindow(const RenderTarget &renderTarget, const RenderViewport &viewport, EffectWindow *w, int mask, const QRegion ®ion, WindowPaintData &data) override;+ void postPaintScreen() override;+ bool isActive() const override;+ int requestedEffectChainPosition() const override;++private:+ struct State {+ // 0 sharp, 1 fully blurred and dimmed.+ qreal progress = 0;+ qreal target = 0;+ bool dirty = true;+ qreal textureScale = 1;+ // Level 0 is the window as drawn, each further level half the size+ // of the one before; after blurring, level 1 holds the result.+ std::vector<std::unique_ptr<GLTexture>> textures;+ std::vector<std::unique_ptr<GLFramebuffer>> framebuffers;+ // Keeps the window off direct scanout while it is drawn by us.+ ItemEffect itemEffect;+ QMetaObject::Connection damaged;+ QMetaObject::Connection resized;+ };++ bool shouldBlur(EffectWindow *w) const;+ void updateTargets();+ void setFocus(EffectWindow *w);+ void forget(EffectWindow *w);+ bool ensureShaders();+ bool render(EffectWindow *w, State &state);+ void blur(State &state);+ void composite(const RenderTarget &renderTarget, const RenderViewport &viewport, EffectWindow *w, const QRegion ®ion, const WindowPaintData &data, State &state);++ std::map<EffectWindow *, std::unique_ptr<State>> m_windows;+ EffectWindow *m_focus = nullptr;++ int m_strength = 3;+ bool m_desktop = true;+ int m_iterations = 3;+ float m_offset = 5.0;+ qreal m_dim = 0.14;+ qreal m_duration = 250;+ std::chrono::milliseconds m_lastPresent = std::chrono::milliseconds::zero();++ bool m_shadersFailed = false;+ std::unique_ptr<GLShader> m_downsample;+ std::unique_ptr<GLShader> m_upsample;+ std::unique_ptr<GLShader> m_composite;+ int m_downOffsetLocation = -1;+ int m_downHalfpixelLocation = -1;+ int m_upOffsetLocation = -1;+ int m_upHalfpixelLocation = -1;+ int m_offsetLocation = -1;+ int m_halfpixelLocation = -1;+ int m_progressLocation = -1;+ int m_dimLocation = -1;+ int m_expandedOriginLocation = -1;+ int m_expandedSizeLocation = -1;+ int m_frameSizeLocation = -1;+ int m_radiusLocation = -1;+};++} // namespace KWindiff --git a/packages/wildos-shell/effects/blurinactive/blurinactive.qrc b/packages/wildos-shell/effects/blurinactive/blurinactive.qrcnew file mode 100644index 0000000..5a25d3c--- /dev/null+++ b/packages/wildos-shell/effects/blurinactive/blurinactive.qrc@@ -0,0 +1,7 @@+<!DOCTYPE RCC><RCC version="1.0">+<qresource prefix="/wildos/blurinactive/">+ <file alias="downsample.frag">shaders/downsample.frag</file>+ <file alias="upsample.frag">shaders/upsample.frag</file>+ <file alias="composite.frag">shaders/composite.frag</file>+</qresource>+</RCC>diff --git a/packages/wildos-shell/effects/blurinactive/metadata.json b/packages/wildos-shell/effects/blurinactive/metadata.jsonnew file mode 100644index 0000000..7fff106--- /dev/null+++ b/packages/wildos-shell/effects/blurinactive/metadata.json@@ -0,0 +1,10 @@+{+ "KPlugin": {+ "Category": "Accessibility",+ "Description": "Blurs and dims every window except the one in use",+ "EnabledByDefault": false,+ "License": "GPL",+ "Name": "Blur windows in the background"+ },+ "X-KWin-Internal": true+}diff --git a/packages/wildos-shell/effects/blurinactive/shaders/composite.frag b/packages/wildos-shell/effects/blurinactive/shaders/composite.fragnew file mode 100644index 0000000..d77d418--- /dev/null+++ b/packages/wildos-shell/effects/blurinactive/shaders/composite.frag@@ -0,0 +1,71 @@+// Puts a blurred window on screen. The effect prepends the #version line and+// the IN, TEXTURE and FRAG_COLOR macros.++#include "colormanagement.glsl"+#include "saturation.glsl"++// The window as drawn, and its blur at half size.+uniform sampler2D sampler;+uniform sampler2D sampler1;+uniform vec4 modulation;++uniform float offset;+uniform vec2 halfpixel;+// 0 sharp, 1 fully blurred and dimmed.+uniform float progress;+uniform float dim;++// In logical pixels with the frame's top left at 0,0.+uniform vec2 expandedOrigin;+uniform vec2 expandedSize;+uniform vec2 frameSize;+uniform float radius;++IN vec2 texcoord0;++// The last upsampling step of the dual Kawase blur, done here rather than+// into a full size texture of its own.+vec4 blurred(vec2 uv)+{+ vec4 sum = TEXTURE(sampler1, uv + vec2(-halfpixel.x * 2.0, 0.0) * offset);+ sum += TEXTURE(sampler1, uv + vec2(-halfpixel.x, halfpixel.y) * offset) * 2.0;+ sum += TEXTURE(sampler1, uv + vec2(0.0, halfpixel.y * 2.0) * offset);+ sum += TEXTURE(sampler1, uv + vec2(halfpixel.x, halfpixel.y) * offset) * 2.0;+ sum += TEXTURE(sampler1, uv + vec2(halfpixel.x * 2.0, 0.0) * offset);+ sum += TEXTURE(sampler1, uv + vec2(halfpixel.x, -halfpixel.y) * offset) * 2.0;+ sum += TEXTURE(sampler1, uv + vec2(0.0, -halfpixel.y * 2.0) * offset);+ sum += TEXTURE(sampler1, uv + vec2(-halfpixel.x, -halfpixel.y) * offset) * 2.0;+ return sum / 12.0;+}++float frameDistance(vec2 p)+{+ vec2 halfSize = 0.5 * frameSize;+ vec2 q = abs(p - halfSize) - (halfSize - vec2(radius));+ return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - radius;+}++void main()+{+ vec4 sharp = TEXTURE(sampler, texcoord0);+ vec4 soft = blurred(texcoord0);++ // Offscreen textures are the GL way up: y runs bottom to top.+ vec2 p = expandedOrigin + vec2(texcoord0.x, 1.0 - texcoord0.y) * expandedSize;+ float inside = clamp(0.5 - frameDistance(p), 0.0, 1.0);++ // The blur smears the window's edge into its shadow and the wallpaper+ // showing through its corners. Taking only the colour from the blur and+ // the coverage from the window as drawn keeps the window's shape, so+ // where it ends stays as clear as before.+ vec3 colour = soft.a > 0.004 ? soft.rgb / soft.a : vec3(0.0);+ vec4 shaped = vec4(colour * sharp.a, sharp.a);++ vec4 result = mix(sharp, shaped, progress * inside);+ result.rgb *= 1.0 - dim * progress;++ result = sourceEncodingToNitsInDestinationColorspace(result);+ result = adjustSaturation(result);+ result *= modulation;+ FRAG_COLOR = nitsToDestinationEncoding(result);+}diff --git a/packages/wildos-shell/effects/blurinactive/shaders/downsample.frag b/packages/wildos-shell/effects/blurinactive/shaders/downsample.fragnew file mode 100644index 0000000..c31aea8--- /dev/null+++ b/packages/wildos-shell/effects/blurinactive/shaders/downsample.frag@@ -0,0 +1,20 @@+// The downsampling pass of the dual Kawase blur, as in KWin's blur effect.+// The effect prepends the #version line and the IN, TEXTURE and FRAG_COLOR+// macros.++uniform sampler2D sampler;+uniform float offset;+uniform vec2 halfpixel;++IN vec2 texcoord0;++void main()+{+ vec2 uv = texcoord0;+ vec4 sum = TEXTURE(sampler, uv) * 4.0;+ sum += TEXTURE(sampler, uv - halfpixel.xy * offset);+ sum += TEXTURE(sampler, uv + halfpixel.xy * offset);+ sum += TEXTURE(sampler, uv + vec2(halfpixel.x, -halfpixel.y) * offset);+ sum += TEXTURE(sampler, uv - vec2(halfpixel.x, -halfpixel.y) * offset);+ FRAG_COLOR = sum / 8.0;+}diff --git a/packages/wildos-shell/effects/blurinactive/shaders/upsample.frag b/packages/wildos-shell/effects/blurinactive/shaders/upsample.fragnew file mode 100644index 0000000..ff908cf--- /dev/null+++ b/packages/wildos-shell/effects/blurinactive/shaders/upsample.frag@@ -0,0 +1,23 @@+// The upsampling pass of the dual Kawase blur, as in KWin's blur effect.+// The effect prepends the #version line and the IN, TEXTURE and FRAG_COLOR+// macros.++uniform sampler2D sampler;+uniform float offset;+uniform vec2 halfpixel;++IN vec2 texcoord0;++void main()+{+ vec2 uv = texcoord0;+ vec4 sum = TEXTURE(sampler, uv + vec2(-halfpixel.x * 2.0, 0.0) * offset);+ sum += TEXTURE(sampler, uv + vec2(-halfpixel.x, halfpixel.y) * offset) * 2.0;+ sum += TEXTURE(sampler, uv + vec2(0.0, halfpixel.y * 2.0) * offset);+ sum += TEXTURE(sampler, uv + vec2(halfpixel.x, halfpixel.y) * offset) * 2.0;+ sum += TEXTURE(sampler, uv + vec2(halfpixel.x * 2.0, 0.0) * offset);+ sum += TEXTURE(sampler, uv + vec2(halfpixel.x, -halfpixel.y) * offset) * 2.0;+ sum += TEXTURE(sampler, uv + vec2(0.0, -halfpixel.y * 2.0) * offset);+ sum += TEXTURE(sampler, uv + vec2(-halfpixel.x, -halfpixel.y) * offset) * 2.0;+ FRAG_COLOR = sum / 12.0;+}diff --git a/packages/wildos-shell/effects/focus/focus.h b/packages/wildos-shell/effects/focus/focus.hnew file mode 100644index 0000000..ac735e3--- /dev/null+++ b/packages/wildos-shell/effects/focus/focus.h@@ -0,0 +1,65 @@+/*+ SPDX-FileCopyrightText: 2026 Wild OS Developers <[email protected]>++ SPDX-License-Identifier: GPL-2.0-or-later+*/++#pragma once++#include <effect/effectwindow.h>++// Shared by the outline and background blur effects (Settings >+// Accessibility), so both agree on which window is the one in use.+namespace KWin::WildOS+{++// A window someone works in. Panels, the desktop, menus, tooltips,+// notifications, on-screen displays, Plasma's pop-ups (Start and the+// flyouts), the on-screen keyboard, the lock screen and KWin's own windows+// are none of these.+inline bool isWorkWindow(EffectWindow *w)+{+ // KWin's own windows (the taskbar underglow script draws in one) are+ // part of the desktop, however they are typed.+ if (!w || !w->isManaged() || w->internalWindow()) {+ return false;+ }+ if (w->isSpecialWindow() || w->isPopupWindow() || w->isAppletPopup() || w->isInputMethod() || w->isLockScreen() || w->isOutline()) {+ return false;+ }+ return w->isNormalWindow() || w->isDialog() || w->isUtility();+}++// The window in use after another is activated. Start, a flyout, a menu or+// the taskbar taking focus leaves it where it was, because keyboard focus+// goes back there when they close; so does focus going nowhere for a+// moment, which is how clicking the taskbar to open Start begins. Clicking+// the desktop, or the window in use going away, means no window is in use.+inline EffectWindow *focusAfterActivation(EffectWindow *activated, EffectWindow *current)+{+ if (activated && activated->isDesktop()) {+ return nullptr;+ }+ if (activated && isWorkWindow(activated)) {+ return activated;+ }+ if (current && (current->isDeleted() || current->isMinimized())) {+ return nullptr;+ }+ return current;+}++// A dialog and the window it belongs to are one piece of work: the window+// behind a Save dialog is still the one being used.+inline bool belongTogether(EffectWindow *a, EffectWindow *b)+{+ if (!a || !b) {+ return false;+ }+ if (a == b) {+ return true;+ }+ return a->mainWindows().contains(b) || b->mainWindows().contains(a);+}++}diff --git a/packages/wildos-shell/effects/outline/CMakeLists.txt b/packages/wildos-shell/effects/outline/CMakeLists.txtnew file mode 100644index 0000000..89a54fb--- /dev/null+++ b/packages/wildos-shell/effects/outline/CMakeLists.txt@@ -0,0 +1,13 @@+# Built the same way as roundcorners, which explains the finds.+find_package(ECM 6.0 REQUIRED NO_MODULE)+list(APPEND CMAKE_MODULE_PATH ${ECM_MODULE_PATH} ${ECM_FIND_MODULE_DIR})+find_package(Qt6 6.8 REQUIRED COMPONENTS DBus Quick Widgets)+find_package(KWin 6.3 REQUIRED)+find_package(KF6 6.10 REQUIRED COMPONENTS Config)++add_library(wildos_outline MODULE outline.cpp outline.h ../focus/focus.h outline.qrc)+set_target_properties(wildos_outline PROPERTIES AUTOMOC ON AUTORCC ON PREFIX "")+set_property(TARGET wildos_outline APPEND PROPERTY AUTOMOC_MACRO_NAMES KWIN_EFFECT_FACTORY_SUPPORTED)+target_link_libraries(wildos_outline PRIVATE KWin::kwin KF6::ConfigCore Qt6::Core Qt6::Gui)++install(TARGETS wildos_outline LIBRARY DESTINATION ${QT6_INSTALL_PLUGINS}/kwin/effects/plugins)diff --git a/packages/wildos-shell/effects/outline/metadata.json b/packages/wildos-shell/effects/outline/metadata.jsonnew file mode 100644index 0000000..178d7a0--- /dev/null+++ b/packages/wildos-shell/effects/outline/metadata.json@@ -0,0 +1,10 @@+{+ "KPlugin": {+ "Category": "Accessibility",+ "Description": "Draws a clear edge round every window and a thick accent ring round the one in use",+ "EnabledByDefault": false,+ "License": "GPL",+ "Name": "Outline windows"+ },+ "X-KWin-Internal": true+}diff --git a/packages/wildos-shell/effects/outline/outline.cpp b/packages/wildos-shell/effects/outline/outline.cppnew file mode 100644index 0000000..efee652--- /dev/null+++ b/packages/wildos-shell/effects/outline/outline.cpp@@ -0,0 +1,467 @@+/*+ SPDX-FileCopyrightText: 2026 Wild OS Developers <[email protected]>++ SPDX-License-Identifier: GPL-2.0-or-later+*/++#include "outline.h"++#include "../focus/focus.h"++#include <core/pixelgrid.h>+#include <core/rendertarget.h>+#include <core/renderviewport.h>+#include <effect/effecthandler.h>+#include <effect/effectwindow.h>+#include <opengl/glplatform.h>+#include <opengl/glshader.h>+#include <opengl/glshadermanager.h>+#include <opengl/glvertexbuffer.h>+#include <opengl/openglcontext.h>+#include <window.h>++#include <KConfigGroup>+#include <KSharedConfig>++#include <QFile>+#include <QVector2D>++#include <cmath>++Q_LOGGING_CATEGORY(WILDOS_OUTLINE, "wildos.outline", QtWarningMsg)++static void ensureResources()+{+ Q_INIT_RESOURCE(outline);+}++namespace KWin+{++// The line round a window not in use, the contrasting edge outside it, and+// the accent ring round the window in use, in logical pixels.+static constexpr qreal s_lineWidth = 1.5;+static constexpr qreal s_edgeWidth = 1.0;+static constexpr qreal s_focusWidth = 4.0;+// The Wild OS title bar and the corner effect round windows to 14+// (packages/wildos-branding/files/aurorae/generate.py); GTK, browsers and+// Windows mode draw their own corners at about 12.+static constexpr qreal s_decoratedRadius = 14.0;+static constexpr qreal s_clientRadius = 12.0;++static QColor readRgb(const KConfigGroup &group, const char *key)+{+ const QStringList rgb = group.readEntry(key, QString()).split(QLatin1Char(','));+ if (rgb.size() < 3) {+ return QColor();+ }+ return QColor(rgb[0].trimmed().toInt(), rgb[1].trimmed().toInt(), rgb[2].trimmed().toInt());+}++static qreal luminance(const QColor &c)+{+ const auto f = [](qreal v) {+ return v <= 0.03928 ? v / 12.92 : std::pow((v + 0.055) / 1.055, 2.4);+ };+ return 0.2126 * f(c.redF()) + 0.7152 * f(c.greenF()) + 0.0722 * f(c.blueF());+}++static qreal contrast(const QColor &a, const QColor &b)+{+ const qreal la = luminance(a);+ const qreal lb = luminance(b);+ return (std::max(la, lb) + 0.05) / (std::min(la, lb) + 0.05);+}++// The accent moved lighter or darker until it stands 3:1 against the+// window colour, the contrast WCAG asks of a focus indicator. Light pastel+// accents such as Glacier would otherwise fade into a light theme.+static QColor readableAccent(QColor accent, const QColor &window)+{+ const bool lightWindow = window.lightnessF() >= 0.5;+ float h, s, l, a;+ accent.getHslF(&h, &s, &l, &a);+ for (int i = 0; i < 50 && contrast(accent, window) < 3.0; ++i) {+ l = std::clamp(l + (lightWindow ? -0.02f : 0.02f), 0.0f, 1.0f);+ accent = QColor::fromHslF(h, s, l);+ }+ return accent;+}++static QVector4D straight(const QColor &c, qreal alpha)+{+ return QVector4D(c.redF(), c.greenF(), c.blueF(), alpha);+}++OutlineEffect::OutlineEffect()+{+ reconfigure(ReconfigureAll);++ m_globalsWatcher = KConfigWatcher::create(KSharedConfig::openConfig(QStringLiteral("kdeglobals")));+ connect(m_globalsWatcher.data(), &KConfigWatcher::configChanged, this, [this] {+ readColours();+ effects->addRepaintFull();+ });++ connect(effects, &EffectsHandler::windowActivated, this, [this](EffectWindow *w) {+ setFocus(WildOS::focusAfterActivation(w, m_focus));+ });+ connect(effects, &EffectsHandler::windowAdded, this, &OutlineEffect::track);+ connect(effects, &EffectsHandler::windowClosed, this, [this](EffectWindow *w) {+ repaintRing(w);+ if (m_focus == w) {+ m_focus = nullptr;+ }+ });+ connect(effects, &EffectsHandler::windowDeleted, this, [this](EffectWindow *w) {+ m_progress.remove(w);+ if (m_focus == w) {+ m_focus = nullptr;+ }+ });+ connect(effects, &EffectsHandler::screenLockingChanged, this, [] {+ effects->addRepaintFull();+ });++ const auto windows = effects->stackingOrder();+ for (EffectWindow *w : windows) {+ track(w);+ }+ m_focus = WildOS::focusAfterActivation(effects->activeWindow(), nullptr);+ if (m_focus) {+ m_progress.insert(m_focus, 1.0);+ }+ effects->addRepaintFull();+}++OutlineEffect::~OutlineEffect()+{+ if (m_shader) {+ effects->makeOpenGLContextCurrent();+ m_shader.reset();+ }+ effects->addRepaintFull();+}++void OutlineEffect::track(EffectWindow *w)+{+ connect(w, &EffectWindow::windowFrameGeometryChanged, this, [this](EffectWindow *w, const QRectF &old) {+ // A window without a shadow has nothing of its own painted where+ // its outline was, so the old place is cleared by hand.+ effects->addRepaint(ringRect(w, old).toAlignedRect());+ repaintRing(w);+ });+ connect(w, &EffectWindow::windowFullScreenChanged, this, &OutlineEffect::repaintRing);+ connect(w, &EffectWindow::windowMaximizedStateChanged, this, [this](EffectWindow *w) {+ repaintRing(w);+ });+ connect(w, &EffectWindow::minimizedChanged, this, [this](EffectWindow *w) {+ // KWin only says which window is next if there is one.+ if (w == m_focus && w->isMinimized()) {+ setFocus(nullptr);+ }+ repaintRing(w);+ });+ repaintRing(w);+}++bool OutlineEffect::supported()+{+ return effects->isOpenGLCompositing();+}++void OutlineEffect::reconfigure(ReconfigureFlags flags)+{+ Q_UNUSED(flags)+ m_duration = animationTime(std::chrono::milliseconds(150));+ readColours();+ effects->addRepaintFull();+}++void OutlineEffect::readColours()+{+ KSharedConfig::Ptr config = KSharedConfig::openConfig(QStringLiteral("kdeglobals"));+ config->reparseConfiguration();+ QColor window = readRgb(config->group(QStringLiteral("Colors:Window")), "BackgroundNormal");+ if (!window.isValid()) {+ window = QColor(21, 26, 47);+ }+ QColor accent = readRgb(config->group(QStringLiteral("General")), "AccentColor");+ if (!accent.isValid()) {+ accent = readRgb(config->group(QStringLiteral("Colors:Selection")), "BackgroundNormal");+ }+ if (!accent.isValid()) {+ accent = QColor(0x8f, 0xb4, 0xff);+ }+ m_accent = straight(readableAccent(accent, window), 1.0);+ if (window.lightnessF() >= 0.5) {+ m_line = straight(QColor(21, 27, 44), 0.75);+ m_edge = straight(Qt::white, 0.7);+ } else {+ m_line = straight(Qt::white, 0.75);+ m_edge = straight(Qt::black, 0.6);+ }+}++bool OutlineEffect::outlined(EffectWindow *w) const+{+ if (!WildOS::isWorkWindow(w) || w->isDeleted() || w->isMinimized() || w->isFullScreen()) {+ return false;+ }+ // Minimise and restore animations bend the window into the taskbar;+ // an outline that kept its shape would hang in the air.+ if (w->data(WindowMinimizedGrabRole).value<void *>() || w->data(WindowUnminimizedGrabRole).value<void *>()) {+ return false;+ }+ return true;+}++OutlineEffect::Shape OutlineEffect::shapeFor(EffectWindow *w) const+{+ const Window *window = w->window();+ if (window && (window->maximizeMode() == MaximizeFull || window->tile() || window->quickTileMode() != QuickTileMode(QuickTileFlag::None))) {+ return Shape{.inset = true, .radius = 0};+ }+ return Shape{.inset = false, .radius = w->hasDecoration() ? s_decoratedRadius : s_clientRadius};+}++QRectF OutlineEffect::ringRect(EffectWindow *w, const QRectF &frame) const+{+ if (shapeFor(w).inset) {+ return frame;+ }+ const qreal reach = s_focusWidth + s_edgeWidth + 1.0;+ return frame.adjusted(-reach, -reach, reach, reach);+}++void OutlineEffect::repaintRing(EffectWindow *w)+{+ if (w) {+ effects->addRepaint(ringRect(w, w->frameGeometry()).toAlignedRect());+ }+}++void OutlineEffect::setFocus(EffectWindow *w)+{+ if (w == m_focus) {+ return;+ }+ repaintRing(m_focus);+ m_focus = w;+ if (w && !m_progress.contains(w)) {+ m_progress.insert(w, 0.0);+ }+ repaintRing(w);+ m_animating = true;+}++void OutlineEffect::prePaintScreen(ScreenPrePaintData &data, std::chrono::milliseconds presentTime)+{+ if (m_animating) {+ const qreal elapsed = m_lastPresent.count() ? qreal((presentTime - m_lastPresent).count()) : 0.0;+ const qreal step = m_duration > 0 ? elapsed / m_duration : 1.0;+ bool moving = false;+ for (auto it = m_progress.begin(); it != m_progress.end(); ++it) {+ const qreal target = it.key() == m_focus ? 1.0 : 0.0;+ if (it.value() < target) {+ it.value() = std::min(target, it.value() + step);+ } else if (it.value() > target) {+ it.value() = std::max(target, it.value() - step);+ }+ moving = moving || it.value() != target;+ }+ m_animating = moving;+ m_lastPresent = presentTime;+ }+ effects->prePaintScreen(data, presentTime);+}++void OutlineEffect::postPaintScreen()+{+ for (auto it = m_progress.begin(); it != m_progress.end();) {+ const qreal target = it.key() == m_focus ? 1.0 : 0.0;+ if (it.value() != target) {+ repaintRing(it.key());+ }+ if (it.value() <= 0.0 && target <= 0.0) {+ it = m_progress.erase(it);+ } else {+ ++it;+ }+ }+ if (!m_animating) {+ m_lastPresent = std::chrono::milliseconds::zero();+ }+ effects->postPaintScreen();+}++void OutlineEffect::prePaintWindow(EffectWindow *w, WindowPrePaintData &data, std::chrono::milliseconds presentTime)+{+ // The ring's own repaints are asked for when it changes (focus, moves,+ // the animation), so nothing is added to the window's damage here.+ if (outlined(w)) {+ const QRect ring = ringRect(w, w->frameGeometry()).toAlignedRect();+ // KWin clips an untransformed window to its own extent. A window+ // with a shadow covers the outline; one without needs the clip+ // lifted, at the cost of not hiding the windows under it.+ if (!w->expandedGeometry().toAlignedRect().contains(ring)) {+ data.mask |= PAINT_WINDOW_TRANSFORMED;+ }+ }+ effects->prePaintWindow(w, data, presentTime);+}++bool OutlineEffect::ensureShader()+{+ if (m_shader) {+ return true;+ }+ if (m_shaderFailed) {+ return false;+ }+ ensureResources();+ QFile file(QStringLiteral(":/wildos/outline/outline.frag"));+ if (!file.open(QIODevice::ReadOnly)) {+ qCWarning(WILDOS_OUTLINE) << "Could not read the outline shader";+ m_shaderFailed = true;+ return false;+ }+ // Same choice of dialect as KWin's own generated shaders.+ const auto context = OpenGlContext::currentContext();+ QByteArray header;+ bool modern;+ if (context->isOpenGLES()) {+ modern = context->glslVersion() >= Version(3, 0);+ header = modern ? QByteArrayLiteral("#version 300 es\n") : QByteArray();+ header += QByteArrayLiteral("precision highp float;\n");+ } else {+ modern = context->glslVersion() >= Version(1, 40);+ header = modern ? QByteArrayLiteral("#version 140\n") : QByteArray();+ }+ if (modern) {+ header += QByteArrayLiteral("#define IN in\n#define FRAG_COLOR fragColor\nout vec4 fragColor;\n");+ } else {+ header += QByteArrayLiteral("#define IN varying\n#define FRAG_COLOR gl_FragColor\n");+ }+ // MapTexture only for the generated vertex shader's texcoord, which+ // carries each point's place relative to the frame.+ m_shader = ShaderManager::instance()->generateCustomShader(ShaderTrait::MapTexture | ShaderTrait::TransformColorspace, QByteArray(), header + file.readAll());+ if (!m_shader || !m_shader->isValid()) {+ qCWarning(WILDOS_OUTLINE) << "The outline shader failed to build";+ m_shader.reset();+ m_shaderFailed = true;+ return false;+ }+ m_frameSizeLocation = m_shader->uniformLocation("frameSize");+ m_radiusLocation = m_shader->uniformLocation("radius");+ m_insetLocation = m_shader->uniformLocation("inset");+ m_mainWidthLocation = m_shader->uniformLocation("mainWidth");+ m_edgeWidthLocation = m_shader->uniformLocation("edgeWidth");+ m_mainColourLocation = m_shader->uniformLocation("mainColour");+ m_edgeColourLocation = m_shader->uniformLocation("edgeColour");+ m_devicePixelLocation = m_shader->uniformLocation("devicePixel");+ return true;+}++static void appendRect(GLVertex2D *map, int &index, const QRectF &r, qreal scale)+{+ if (r.width() <= 0 || r.height() <= 0) {+ return;+ }+ const QVector2D tl(r.left(), r.top());+ const QVector2D tr(r.right(), r.top());+ const QVector2D br(r.right(), r.bottom());+ const QVector2D bl(r.left(), r.bottom());+ const float s = scale;+ for (const QVector2D &p : {tl, br, bl, tl, tr, br}) {+ map[index++] = GLVertex2D{.position = p * s, .texcoord = p};+ }+}++void OutlineEffect::drawWindow(const RenderTarget &renderTarget, const RenderViewport &viewport, EffectWindow *w, int mask, const QRegion ®ion, WindowPaintData &data)+{+ effects->drawWindow(renderTarget, viewport, w, mask, region, data);++ if (!outlined(w) || data.opacity() <= 0 || !ensureShader()) {+ return;+ }++ const qreal scale = viewport.scale();+ const QRectF frame = snapToPixels(w->frameGeometry(), scale);+ const Shape shape = shapeFor(w);+ const qreal focus = m_progress.value(w, 0.0);+ const qreal mainWidth = s_lineWidth + (s_focusWidth - s_lineWidth) * focus;+ const qreal reach = mainWidth + s_edgeWidth + 1.0;++ // Four strips round the frame, so the shader runs only where the ring+ // can be and never across the window itself. Outside the frame they+ // reach in as far as the corner radius, where the ring curves in.+ const QRectF local(0, 0, frame.width(), frame.height());+ const QRectF outer = shape.inset ? local : local.adjusted(-reach, -reach, reach, reach);+ const qreal in = shape.inset ? reach : shape.radius;+ const QRectF inner = local.adjusted(in, in, -in, -in);++ GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer();+ vbo->reset();+ vbo->setAttribLayout(std::span(GLVertexBuffer::GLVertex2DLayout), sizeof(GLVertex2D));+ const auto map = vbo->map<GLVertex2D>(24);+ if (!map) {+ return;+ }+ int count = 0;+ appendRect(map->data(), count, QRectF(outer.left(), outer.top(), outer.width(), inner.top() - outer.top()), scale);+ appendRect(map->data(), count, QRectF(outer.left(), inner.bottom(), outer.width(), outer.bottom() - inner.bottom()), scale);+ appendRect(map->data(), count, QRectF(outer.left(), inner.top(), inner.left() - outer.left(), inner.height()), scale);+ appendRect(map->data(), count, QRectF(inner.right(), inner.top(), outer.right() - inner.right(), inner.height()), scale);+ vbo->unmap();+ vbo->bindArrays();++ const QVector4D main = m_line + (m_accent - m_line) * focus;++ ShaderBinder binder(m_shader.get());+ QMatrix4x4 mvp = viewport.projectionMatrix();+ mvp.translate(std::round(frame.x() * scale), std::round(frame.y() * scale));+ m_shader->setUniform(GLShader::Mat4Uniform::ModelViewProjectionMatrix, mvp * data.toMatrix(scale));+ m_shader->setColorspaceUniforms(ColorDescription::sRGB, renderTarget.colorDescription(), RenderingIntent::Perceptual);+ m_shader->setUniform(m_frameSizeLocation, QVector2D(frame.width(), frame.height()));+ m_shader->setUniform(m_radiusLocation, float(shape.radius));+ m_shader->setUniform(m_insetLocation, shape.inset ? 1.0f : 0.0f);+ m_shader->setUniform(m_mainWidthLocation, float(mainWidth));+ m_shader->setUniform(m_edgeWidthLocation, float(s_edgeWidth));+ m_shader->setUniform(m_mainColourLocation, QVector4D(main.x(), main.y(), main.z(), main.w() * data.opacity()));+ m_shader->setUniform(m_edgeColourLocation, QVector4D(m_edge.x(), m_edge.y(), m_edge.z(), m_edge.w() * data.opacity()));+ m_shader->setUniform(m_devicePixelLocation, float(1.0 / scale));++ const bool clipping = region != infiniteRegion();+ const QRegion clipRegion = clipping ? viewport.mapToRenderTarget(region) : infiniteRegion();+ if (clipping) {+ glEnable(GL_SCISSOR_TEST);+ }+ glEnable(GL_BLEND);+ glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);+ vbo->draw(clipRegion, GL_TRIANGLES, 0, count, clipping);+ glDisable(GL_BLEND);+ if (clipping) {+ glDisable(GL_SCISSOR_TEST);+ }+ vbo->unbindArrays();+}++bool OutlineEffect::isActive() const+{+ return !effects->isScreenLocked();+}++int OutlineEffect::requestedEffectChainPosition() const+{+ // Before the background blur (58), so the outline is drawn on top of a+ // blurred window rather than blurred with it, and before the corner+ // effect (60).+ return 55;+}++KWIN_EFFECT_FACTORY_SUPPORTED(OutlineEffect, "metadata.json", return OutlineEffect::supported();)++} // namespace KWin++#include "outline.moc"diff --git a/packages/wildos-shell/effects/outline/outline.h b/packages/wildos-shell/effects/outline/outline.hnew file mode 100644index 0000000..ee2147f--- /dev/null+++ b/packages/wildos-shell/effects/outline/outline.h@@ -0,0 +1,95 @@+/*+ SPDX-FileCopyrightText: 2026 Wild OS Developers <[email protected]>++ SPDX-License-Identifier: GPL-2.0-or-later+*/++#pragma once++#include <effect/effect.h>++#include <KConfigWatcher>++#include <QColor>+#include <QHash>+#include <QVector4D>++#include <chrono>+#include <memory>++namespace KWin+{++class GLShader;+class EffectWindow;++// Settings > Accessibility > Outline windows, for people who cannot see+// where one window ends and the next begins, or which one has focus: a+// two-tone edge round every window, light against dark and dark against+// light so it shows on any wallpaper or window, and a thick ring in the+// accent colour round the window in use.+//+// It is drawn by KWin round each window's frame rather than by the title+// bar theme, so windows that draw their own title bar (Wild OS apps, GTK+// apps, browsers, Windows mode) get the same outline as the rest.+class OutlineEffect : public Effect+{+ Q_OBJECT++public:+ OutlineEffect();+ ~OutlineEffect() override;++ static bool supported();++ void reconfigure(ReconfigureFlags flags) override;+ void prePaintScreen(ScreenPrePaintData &data, std::chrono::milliseconds presentTime) override;+ void prePaintWindow(EffectWindow *w, WindowPrePaintData &data, std::chrono::milliseconds presentTime) override;+ void drawWindow(const RenderTarget &renderTarget, const RenderViewport &viewport, EffectWindow *w, int mask, const QRegion ®ion, WindowPaintData &data) override;+ void postPaintScreen() override;+ bool isActive() const override;+ int requestedEffectChainPosition() const override;++private:+ struct Shape {+ // Inset rings sit just inside the frame of a maximised or snapped+ // window, which has no room round it.+ bool inset = false;+ qreal radius = 0;+ };++ void track(EffectWindow *w);+ bool outlined(EffectWindow *w) const;+ Shape shapeFor(EffectWindow *w) const;+ QRectF ringRect(EffectWindow *w, const QRectF &frame) const;+ void repaintRing(EffectWindow *w);+ void setFocus(EffectWindow *w);+ void readColours();+ bool ensureShader();++ std::unique_ptr<GLShader> m_shader;+ bool m_shaderFailed = false;+ KConfigWatcher::Ptr m_globalsWatcher;++ EffectWindow *m_focus = nullptr;+ // How far each window is through becoming the one in use, 0 to 1.+ QHash<EffectWindow *, qreal> m_progress;+ std::chrono::milliseconds m_lastPresent = std::chrono::milliseconds::zero();+ bool m_animating = false;+ qreal m_duration = 150;++ QVector4D m_accent;+ QVector4D m_line;+ QVector4D m_edge;++ int m_frameSizeLocation = -1;+ int m_radiusLocation = -1;+ int m_insetLocation = -1;+ int m_mainWidthLocation = -1;+ int m_edgeWidthLocation = -1;+ int m_mainColourLocation = -1;+ int m_edgeColourLocation = -1;+ int m_devicePixelLocation = -1;+};++} // namespace KWindiff --git a/packages/wildos-shell/effects/outline/outline.qrc b/packages/wildos-shell/effects/outline/outline.qrcnew file mode 100644index 0000000..13f0e6f--- /dev/null+++ b/packages/wildos-shell/effects/outline/outline.qrc@@ -0,0 +1,5 @@+<!DOCTYPE RCC><RCC version="1.0">+<qresource prefix="/wildos/outline/">+ <file alias="outline.frag">shaders/outline.frag</file>+</qresource>+</RCC>diff --git a/packages/wildos-shell/effects/outline/shaders/outline.frag b/packages/wildos-shell/effects/outline/shaders/outline.fragnew file mode 100644index 0000000..4de0e6b--- /dev/null+++ b/packages/wildos-shell/effects/outline/shaders/outline.frag@@ -0,0 +1,48 @@+// The effect prepends the #version line and the IN and FRAG_COLOR macros, so+// one source serves GLSL 1.10, 1.40 and GLSL ES.++#include "colormanagement.glsl"++// In logical pixels with the frame's top left at 0,0.+uniform vec2 frameSize;+uniform float radius;+// 1 when the ring sits inside the frame (maximised and snapped windows).+uniform float inset;+uniform float mainWidth;+uniform float edgeWidth;+// Straight alpha, already multiplied by the window's opacity.+uniform vec4 mainColour;+uniform vec4 edgeColour;+uniform float devicePixel;++IN vec2 texcoord0;++// Signed distance to the frame's rounded rectangle, negative inside.+float frameDistance(vec2 p)+{+ vec2 halfSize = 0.5 * frameSize;+ vec2 q = abs(p - halfSize) - (halfSize - vec2(radius));+ return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - radius;+}++// Coverage of the band [lo, hi) by the device pixel centred on s.+float band(float s, float lo, float hi)+{+ float h = 0.5 * devicePixel;+ return clamp((min(s + h, hi) - max(s - h, lo)) / devicePixel, 0.0, 1.0);+}++void main()+{+ float d = frameDistance(texcoord0);+ // Distance away from the window's content: outwards for a ring round+ // the frame, inwards for one inside it, so the contrasting edge is+ // always on the far side of the coloured line.+ float s = inset > 0.5 ? -d : d;+ float m = band(s, 0.0, mainWidth);+ float e = band(s, mainWidth, mainWidth + edgeWidth);+ vec4 colour = vec4(mainColour.rgb * mainColour.a, mainColour.a) * m+ + vec4(edgeColour.rgb * edgeColour.a, edgeColour.a) * e;+ colour = sourceEncodingToNitsInDestinationColorspace(colour);+ FRAG_COLOR = nitsToDestinationEncoding(colour);+}diff --git a/packages/wildos-shell/kwin/org.wildos.appwindows/contents/code/main.js b/packages/wildos-shell/kwin/org.wildos.appwindows/contents/code/main.jsnew file mode 100644index 0000000..17092a8--- /dev/null+++ b/packages/wildos-shell/kwin/org.wildos.appwindows/contents/code/main.js@@ -0,0 +1,28 @@+// Windows key + backtick steps through the current app's windows, as Cmd+`+// does on a Mac. KWin's own "Walk Through Windows of Current Application"+// keeps Alt+`, but it orders windows by when they were last used, so with+// three or more windows it flips between the same two. This walks them in+// the order they were opened, so every window comes round in turn.++function appWindows(active) {+ const desktop = workspace.currentDesktop;+ return workspace.windowList().filter(w =>+ w.normalWindow && !w.skipSwitcher && w.resourceClass === active.resourceClass+ && (w.onAllDesktops || w.desktops.indexOf(desktop) !== -1));+}++function step(by) {+ const active = workspace.activeWindow;+ if (!active) {+ return;+ }+ const windows = appWindows(active);+ if (windows.length < 2) {+ return;+ }+ const next = windows[(windows.indexOf(active) + by + windows.length) % windows.length];+ next.minimized = false;+ workspace.activeWindow = next;+}++registerShortcut("Wild OS next window of this app", "Next window of the same app", "Meta+`", () => step(1));diff --git a/packages/wildos-shell/kwin/org.wildos.appwindows/metadata.json b/packages/wildos-shell/kwin/org.wildos.appwindows/metadata.jsonnew file mode 100644index 0000000..6276015--- /dev/null+++ b/packages/wildos-shell/kwin/org.wildos.appwindows/metadata.json@@ -0,0 +1,20 @@+{+ "KPackageStructure": "KWin/Script",+ "KPlugin": {+ "Authors": [+ {+ "Email": "[email protected]",+ "Name": "Wild OS"+ }+ ],+ "Description": "Windows key + backtick steps through the open windows of the app you are using",+ "EnabledByDefault": true,+ "Id": "org.wildos.appwindows",+ "License": "GPL-3.0-or-later",+ "Name": "Same app windows",+ "Version": "0.1.0",+ "Website": "https://wildos.io"+ },+ "X-Plasma-API": "javascript",+ "X-Plasma-MainScript": "code/main.js"+}diff --git a/packages/wildos-shell/kwin/org.wildos.underglow/contents/ui/Glow.qml b/packages/wildos-shell/kwin/org.wildos.underglow/contents/ui/Glow.qmlnew file mode 100644index 0000000..d827cfc--- /dev/null+++ b/packages/wildos-shell/kwin/org.wildos.underglow/contents/ui/Glow.qml@@ -0,0 +1,151 @@+import QtQuick+import QtQuick.Window+import org.wildos.shell as WildOS+import WildOS.UI as UI++// One taskbar's underglow: a strip window across the taskbar's top edge,+// reaching far enough above and below the line for the glow to fade out.+//+// The line lies on the taskbar's top two pixels, over its hairline, rather+// than just above it as the board draws it: above, it would cover the bottom+// two pixels of every maximised window.+Window {+ id: glow++ property var dock: null+ property bool covered: false++ // KWin lets an internal window catch the pointer unless it carries this+ // (InternalWindow::hitTest); clicks go through to the taskbar and the+ // window above it.+ readonly property bool outputOnly: true+ readonly property bool _q_showWithoutActivating: true++ // Past 20px the 0.55 glow is under one 8-bit step (underglowtest).+ readonly property int reach: 20+ readonly property int lineHeight: 2+ readonly property rect bar: dock && !dock.deleted ? dock.frameGeometry : Qt.rect(0, 0, 0, 0)++ readonly property bool rgb: WildOS.Underglow.colour === "rgb"+ readonly property color tint: WildOS.Underglow.colour === "custom" ? WildOS.Underglow.custom : UI.Style.accent+ // The board glows a single colour at 0.55 of itself and lays a soft+ // white at 0.25 under the spectrum.+ readonly property color glowColour: rgb ? Qt.rgba(1, 1, 1, 0.25) : Qt.rgba(tint.r, tint.g, tint.b, 0.55)+ readonly property string effect: WildOS.Underglow.running++ flags: Qt.FramelessWindowHint | Qt.BypassWindowManagerHint | Qt.WindowDoesNotAcceptFocus | Qt.WindowTransparentForInput+ color: "transparent"+ x: Math.round(bar.x)+ y: Math.round(bar.y) - reach+ width: Math.max(1, Math.round(bar.width))+ height: reach * 2 + lineHeight+ visible: WildOS.Underglow.enabled && !WildOS.TaskbarStyle.floating+ && dock !== null && !dock.deleted && !dock.hidden && !covered && bar.width > 0++ Item {+ id: light+ anchors.fill: parent++ // The glow as one-pixel rows, each at the strength CSS's box-shadow+ // gives that distance from the line.+ Column {+ Repeater {+ model: WildOS.Underglow.glowRows(glow.reach)+ delegate: Rectangle {+ required property real modelData+ width: glow.width+ height: 1+ color: Qt.rgba(glow.glowColour.r, glow.glowColour.g, glow.glowColour.b, glow.glowColour.a * modelData)+ }+ }+ }++ // Accent or custom: solid from 18% to 82%, fading to nothing at+ // both ends.+ Rectangle {+ visible: !glow.rgb+ y: glow.reach+ width: parent.width+ height: glow.lineHeight+ gradient: Gradient {+ orientation: Gradient.Horizontal+ GradientStop { position: 0.0; color: Qt.rgba(glow.tint.r, glow.tint.g, glow.tint.b, 0) }+ GradientStop { position: 0.18; color: glow.tint }+ GradientStop { position: 0.82; color: glow.tint }+ GradientStop { position: 1.0; color: Qt.rgba(glow.tint.r, glow.tint.g, glow.tint.b, 0) }+ }+ }++ // RGB: the spectrum one bar wide, twice over, sliding right by one+ // width per cycle so it wraps without a seam, as the board's+ // background-position animation does.+ Item {+ visible: glow.rgb+ y: glow.reach+ width: parent.width+ height: glow.lineHeight+ clip: true++ Row {+ id: spectrum+ x: -glow.width++ Repeater {+ model: 2+ delegate: Rectangle {+ width: glow.width+ height: glow.lineHeight+ gradient: Gradient {+ orientation: Gradient.Horizontal+ GradientStop { position: 0 / 7; color: "#ff3d6e" }+ GradientStop { position: 1 / 7; color: "#ffb03d" }+ GradientStop { position: 2 / 7; color: "#f5ff3d" }+ GradientStop { position: 3 / 7; color: "#3dff7a" }+ GradientStop { position: 4 / 7; color: "#3dd5ff" }+ GradientStop { position: 5 / 7; color: "#5c7cff" }+ GradientStop { position: 6 / 7; color: "#c85cff" }+ GradientStop { position: 7 / 7; color: "#ff3d6e" }+ }+ }+ }++ NumberAnimation on x {+ from: -glow.width+ to: 0+ duration: 6000+ loops: Animation.Infinite+ running: glow.visible && glow.rgb && glow.effect === "flowing"+ }+ }+ }+ }++ // Breathing: 1 to 0.35 and back every 3.2s with CSS's ease-in-out on+ // each half. It starts from full so turning it on does not blink.+ SequentialAnimation {+ running: glow.visible && !glow.rgb && glow.effect === "breathing"+ loops: Animation.Infinite+ onRunningChanged: {+ if (!running) {+ light.opacity = 1;+ }+ }++ NumberAnimation {+ target: light+ property: "opacity"+ to: 0.35+ duration: 1600+ easing.type: Easing.BezierSpline+ easing.bezierCurve: [0.42, 0, 0.58, 1, 1, 1]+ }+ NumberAnimation {+ target: light+ property: "opacity"+ to: 1+ duration: 1600+ easing.type: Easing.BezierSpline+ easing.bezierCurve: [0.42, 0, 0.58, 1, 1, 1]+ }+ }+}diff --git a/packages/wildos-shell/kwin/org.wildos.underglow/contents/ui/main.qml b/packages/wildos-shell/kwin/org.wildos.underglow/contents/ui/main.qmlnew file mode 100644index 0000000..66f8794--- /dev/null+++ b/packages/wildos-shell/kwin/org.wildos.underglow/contents/ui/main.qml@@ -0,0 +1,139 @@+import QtQuick+import QtQml+import org.kde.kwin as KWin+import org.wildos.shell as WildOS++// The taskbar underglow (UnderglowOptions board): a 2px line along the top+// edge of the docked taskbar with a soft glow around it, in the accent, a+// custom colour or a drifting spectrum, as chosen in Settings.+//+// KWin draws it, in a strip window of its own laid over the taskbar's top+// edge. Breathing and flowing then repaint only that strip inside the+// compositor and never make plasmashell redraw the panel. It is a KWin script+// rather than a C++ effect because the scripting API it uses holds across+// KWin releases, where a binary effect must be rebuilt for each one.+Item {+ id: root++ // KWin reports the glow windows like any other; this title is how they+ // are told apart and kept out of Alt+Tab, Overview and the taskbar.+ readonly property string glowTitle: "Wild OS taskbar underglow"++ // The docked taskbars, one per screen that has one.+ property var docks: []+ // The ones a full screen window is stacked over, whose glow would+ // otherwise sit on top of the game or video.+ property var covered: []++ function onCurrentDesktop(w: var): bool {+ return w.onAllDesktops || w.desktops.indexOf(KWin.Workspace.currentDesktop) >= 0;+ }++ function onScreen(w: var): bool {+ return !w.deleted && !w.minimized && !w.hidden && onCurrentDesktop(w);+ }++ // Plasma's panel is a dock window. Docked, the taskbar runs the full+ // width of its screen along the bottom edge. A floating taskbar is a+ // taller window with the pills drawn inside it, and a panel at another+ // edge is not the taskbar, so neither has a top edge to light.+ function isDockedTaskbar(w: var): bool {+ if (!w || w.deleted || !w.dock || !w.output) {+ return false;+ }+ const g = w.frameGeometry;+ const s = w.output.geometry;+ return g.x <= s.x + 1 && g.x + g.width >= s.x + s.width - 1+ && Math.abs(g.y + g.height - (s.y + s.height)) <= 1+ && g.height * 4 < g.width;+ }++ function sameList(a: var, b: var): bool {+ return a.length === b.length && a.every((w, i) => w === b[i]);+ }++ function refresh(): void {+ const windows = KWin.Workspace.stackingOrder;+ const found = windows.filter(isDockedTaskbar);+ if (!sameList(found, docks)) {+ docks = found;+ }+ const fullScreen = windows.filter(w => w.fullScreen && onScreen(w));+ WildOS.Underglow.fullScreen = fullScreen.length > 0;+ const over = found.filter(d => fullScreen.some(f => f.output === d.output && f.stackingOrder > d.stackingOrder));+ if (!sameList(over, covered)) {+ covered = over;+ }+ }++ Timer {+ id: refreshTimer+ interval: 0+ onTriggered: root.refresh()+ }++ function refreshLater(): void {+ refreshTimer.restart();+ }++ function watch(w: var): void {+ if (w.caption === glowTitle) {+ w.skipSwitcher = true;+ w.skipTaskbar = true;+ w.skipPager = true;+ return;+ }+ w.fullScreenChanged.connect(refreshLater);+ w.minimizedChanged.connect(refreshLater);+ w.hiddenChanged.connect(refreshLater);+ w.outputChanged.connect(refreshLater);+ w.desktopsChanged.connect(refreshLater);+ w.stackingOrderChanged.connect(refreshLater);+ // Only a dock can become or stop being the taskbar by moving, and+ // watching every window would refresh on each frame of a drag.+ if (w.dock) {+ w.frameGeometryChanged.connect(refreshLater);+ }+ }++ Connections {+ target: KWin.Workspace++ function onWindowAdded(window: var): void {+ root.watch(window);+ root.refreshLater();+ }++ function onWindowRemoved(): void {+ root.refreshLater();+ }++ function onWindowActivated(): void {+ root.refreshLater();+ }++ function onCurrentDesktopChanged(): void {+ root.refreshLater();+ }++ function onScreensChanged(): void {+ root.refreshLater();+ }+ }++ Instantiator {+ model: root.docks+ delegate: Glow {+ dock: modelData+ covered: root.covered.indexOf(modelData) >= 0+ title: root.glowTitle+ }+ }++ Component.onCompleted: {+ for (const w of KWin.Workspace.stackingOrder) {+ watch(w);+ }+ refresh();+ }+}diff --git a/packages/wildos-shell/kwin/org.wildos.underglow/metadata.json b/packages/wildos-shell/kwin/org.wildos.underglow/metadata.jsonnew file mode 100644index 0000000..fa03e15--- /dev/null+++ b/packages/wildos-shell/kwin/org.wildos.underglow/metadata.json@@ -0,0 +1,20 @@+{+ "KPackageStructure": "KWin/Script",+ "KPlugin": {+ "Authors": [+ {+ "Email": "[email protected]",+ "Name": "Wild OS"+ }+ ],+ "Description": "Draws the taskbar underglow chosen in Settings along the top edge of the docked taskbar",+ "EnabledByDefault": true,+ "Id": "org.wildos.underglow",+ "License": "GPL-3.0-or-later",+ "Name": "Taskbar underglow",+ "Version": "0.1.0",+ "Website": "https://wildos.io"+ },+ "X-Plasma-API": "declarativescript",+ "X-Plasma-MainScript": "ui/main.qml"+}diff --git a/packages/wildos-shell/panel/Panel.qml b/packages/wildos-shell/panel/Panel.qmlindex 5eb2793..8cd2b75 100644--- a/packages/wildos-shell/panel/Panel.qml+++ b/packages/wildos-shell/panel/Panel.qml@@ -82,18 +82,21 @@ Item {}const p = child.mapToItem(root, 0, 0);if (!run) {- run = { left: p.x, right: p.x + child.width };+ run = { left: p.x, right: p.x + child.width, first: plugin };runs.push(run);} else {run.right = p.x + child.width;}}// The status pill at the right end has 6 px inside its left edge and- // 8 px inside its right; the apps pill 9 px each side.+ // 8 px inside its right; the apps pill 9 px each side. Windows mode's+ // item at the left end mirrors the status pill: it carries its own+ // 13 px and its pill starts 5 px in, 8 px before its button.pillRects = runs.map((r, i) => {const last = runs.length > 1 && i === runs.length - 1;- const left = Math.round(r.left - (last ? 6 : 9));- const right = Math.round(r.right + (last ? 8 : 9));+ const winmode = i === 0 && runs.length > 2 && r.first === "org.wildos.winmode";+ const left = Math.round(r.left - (last ? 6 : winmode ? -5 : 9));+ const right = Math.round(r.right + (last ? 8 : winmode ? 6 : 9));return Qt.rect(left, 0, right - left, pillHeight);});}@@ -159,7 +162,7 @@ Item {verticalOffset: 16radius: 40samples: 81- color: UI.Style.dark ? Qt.rgba(6 / 255, 10 / 255, 28 / 255, 0.35) : Qt.rgba(20 / 255, 30 / 255, 60 / 255, 0.14)+ color: UI.Style.taskbarShadow}}Item {@@ -187,7 +190,7 @@ Item {visible: !root.dockedanchors.fill: parentradius: root.pillRadius- color: UI.Style.dark ? Qt.rgba(12 / 255, 16 / 255, 32 / 255, 0.55) : Qt.rgba(250 / 255, 251 / 255, 254 / 255, 0.67)+ color: UI.Style.taskbarFloatingborder.width: 1border.color: UI.Style.dark ? Qt.rgba(1, 1, 1, 0.12) : Qt.rgba(30 / 255, 40 / 255, 70 / 255, 0.09)}@@ -206,7 +209,7 @@ Item {Rectangle {visible: root.dockedanchors.fill: parent- color: UI.Style.dark ? Qt.rgba(14 / 255, 18 / 255, 34 / 255, 0.88) : Qt.rgba(246 / 255, 248 / 255, 252 / 255, 0.90)+ color: UI.Style.taskbarDocked}Rectangle {visible: root.docked@@ -625,6 +628,87 @@ Item {onClicked: mouse => root.openTaskbarMenu(mouse.x)}+ // Show desktop, as on Windows: the last 8 px of the bar, down to the+ // screen's corner pixel, so a flick of the pointer into the corner finds+ // it. Clicking shows the desktop and clicking again brings the windows+ // back. With peek on, resting the pointer there shows the desktop until+ // it moves away, and a click while peeking keeps it shown. Settings >+ // Personalisation > Taskbar turns both on and off (wildosrc [Taskbar]).+ MouseArea {+ id: showDesktopCorner+ visible: root.usePills && WildOS.TaskbarStyle.showDesktop+ x: root.width - width+ y: 0+ width: 8+ height: root.height+ hoverEnabled: true+ acceptedButtons: Qt.LeftButton+ Accessible.role: Accessible.Button+ Accessible.name: "Show the desktop"++ // The desktop is showing because of a peek, so leaving undoes it.+ property bool peeking: false++ onContainsMouseChanged: {+ if (containsMouse) {+ if (WildOS.TaskbarStyle.peek && !KWindowSystem.showingDesktop) {+ peekTimer.restart();+ }+ return;+ }+ peekTimer.stop();+ if (peeking) {+ peeking = false;+ KWindowSystem.showingDesktop = false;+ }+ }+ onClicked: {+ peekTimer.stop();+ if (peeking) {+ peeking = false;+ return;+ }+ KWindowSystem.showingDesktop = !KWindowSystem.showingDesktop;+ }+ onVisibleChanged: {+ if (!visible && peeking) {+ peeking = false;+ KWindowSystem.showingDesktop = false;+ }+ }++ // Windows waits about half a second before peeking, so passing+ // through the corner on the way somewhere does nothing.+ Timer {+ id: peekTimer+ interval: 500+ onTriggered: {+ showDesktopCorner.peeking = true;+ KWindowSystem.showingDesktop = true;+ }+ }+ Connections {+ target: root+ function onShowingDesktopChanged() {+ if (!root.showingDesktop) {+ showDesktopCorner.peeking = false;+ }+ }+ }++ // A hairline on its left edge while the pointer is on it, so it can+ // be found, and nothing otherwise. Floating, the status pill's edge+ // can reach into the sliver, so the line sits nearer the screen edge.+ Rectangle {+ visible: showDesktopCorner.containsMouse+ x: root.docked ? 0 : 5+ y: Math.round((root.pillHeight - height) / 2)+ width: 1+ height: 24+ color: UI.Style.dark ? Qt.rgba(1, 1, 1, 0.35) : Qt.rgba(30 / 255, 40 / 255, 70 / 255, 0.35)+ }+ }+function openTaskbarMenu(x: real): void {const entries = [];if (taskManagerEntry.count > 0) {diff --git a/packages/wildos-shell/src/taskbarstyle.cpp b/packages/wildos-shell/src/taskbarstyle.cppindex 00b7d13..316b463 100644--- a/packages/wildos-shell/src/taskbarstyle.cpp+++ b/packages/wildos-shell/src/taskbarstyle.cpp@@ -19,9 +19,26 @@ void TaskbarStyle::read(){KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("wildosrc"));config->reparseConfiguration();- const bool floating = config->group(QStringLiteral("Taskbar")).readEntry("Style") == QLatin1String("floating");+ const KConfigGroup taskbar = config->group(QStringLiteral("Taskbar"));+ const bool floating = taskbar.readEntry("Style") == QLatin1String("floating");if (floating != m_floating) {m_floating = floating;Q_EMIT floatingChanged();}+ const bool showDesktop = taskbar.readEntry("ShowDesktop", true);+ const bool peek = taskbar.readEntry("PeekDesktop", false);+ if (showDesktop != m_showDesktop || peek != m_peek) {+ m_showDesktop = showDesktop;+ m_peek = peek;+ Q_EMIT showDesktopChanged();+ }+ const bool seconds = taskbar.readEntry("ClockSeconds", false);+ const bool longDate = taskbar.readEntry("ClockLongDate", false);+ const bool battery = taskbar.readEntry("BatteryPercent", false);+ if (seconds != m_clockSeconds || longDate != m_clockLongDate || battery != m_batteryPercent) {+ m_clockSeconds = seconds;+ m_clockLongDate = longDate;+ m_batteryPercent = battery;+ Q_EMIT itemsChanged();+ }}diff --git a/packages/wildos-shell/src/taskbarstyle.h b/packages/wildos-shell/src/taskbarstyle.hindex 313fc59..8fafee1 100644--- a/packages/wildos-shell/src/taskbarstyle.h+++ b/packages/wildos-shell/src/taskbarstyle.h@@ -8,25 +8,45 @@// The taskbar style chosen in Settings > Personalisation: docked along the// bottom of the screen (the default, as Windows does it) or floating glass// panels. Settings writes wildosrc [Taskbar] Style; the panel follows the-// change straight away.+// change straight away. The same group holds the show desktop sliver at the+// bar's right end (ShowDesktop) and whether hovering it peeks (PeekDesktop),+// and the clock and battery choices (ClockSeconds, ClockLongDate,+// BatteryPercent).class TaskbarStyle : public QObject{Q_OBJECTQML_ELEMENTQML_SINGLETONQ_PROPERTY(bool floating READ floating NOTIFY floatingChanged)+ Q_PROPERTY(bool showDesktop READ showDesktop NOTIFY showDesktopChanged)+ Q_PROPERTY(bool peek READ peek NOTIFY showDesktopChanged)+ Q_PROPERTY(bool clockSeconds READ clockSeconds NOTIFY itemsChanged)+ Q_PROPERTY(bool clockLongDate READ clockLongDate NOTIFY itemsChanged)+ Q_PROPERTY(bool batteryPercent READ batteryPercent NOTIFY itemsChanged)public:explicit TaskbarStyle(QObject *parent = nullptr);bool floating() const { return m_floating; }+ bool showDesktop() const { return m_showDesktop; }+ bool peek() const { return m_peek; }+ bool clockSeconds() const { return m_clockSeconds; }+ bool clockLongDate() const { return m_clockLongDate; }+ bool batteryPercent() const { return m_batteryPercent; }Q_SIGNALS:void floatingChanged();+ void showDesktopChanged();+ void itemsChanged();private:void read();KConfigWatcher::Ptr m_watcher;bool m_floating = false;+ bool m_showDesktop = true;+ bool m_peek = false;+ bool m_clockSeconds = false;+ bool m_clockLongDate = false;+ bool m_batteryPercent = false;};diff --git a/packages/wildos-shell/src/underglow.cpp b/packages/wildos-shell/src/underglow.cppnew file mode 100644index 0000000..9eddee7--- /dev/null+++ b/packages/wildos-shell/src/underglow.cpp@@ -0,0 +1,130 @@+#include "underglow.h"++#include <KConfigGroup>+#include <KSharedConfig>++#include <QDBusConnection>+#include <QDBusMessage>+#include <QDBusPendingCallWatcher>+#include <QDBusPendingReply>+#include <QDBusVariant>++namespace+{+const QString upowerService = QStringLiteral("org.freedesktop.UPower");+const QString upowerPath = QStringLiteral("/org/freedesktop/UPower");+const QString propertiesInterface = QStringLiteral("org.freedesktop.DBus.Properties");+}++Underglow::Underglow(QObject *parent)+ : QObject(parent)+ , m_wildos(KConfigWatcher::create(KSharedConfig::openConfig(QStringLiteral("wildosrc"))))+ , m_globals(KConfigWatcher::create(KSharedConfig::openConfig(QStringLiteral("kdeglobals"))))+{+ connect(m_wildos.data(), &KConfigWatcher::configChanged, this, [this](const KConfigGroup &group) {+ if (group.name() == QLatin1String("Underglow")) {+ readSettings();+ }+ });+ connect(m_globals.data(), &KConfigWatcher::configChanged, this, [this](const KConfigGroup &group) {+ if (group.name() == QLatin1String("KDE")) {+ readMotion();+ }+ });++ // UPower sends OnBattery changes as a properties signal; a laptop+ // unplugged mid-breath settles to steady straight away.+ QDBusConnection::systemBus().connect(upowerService, upowerPath, propertiesInterface, QStringLiteral("PropertiesChanged"), this,+ SLOT(upowerPropertiesChanged(QString, QVariantMap, QStringList)));++ readSettings();+ readMotion();+ readBattery();+}++void Underglow::readSettings()+{+ KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("wildosrc"));+ config->reparseConfiguration();+ const KConfigGroup group = config->group(QStringLiteral("Underglow"));+ const UnderglowSettings::Settings settings = UnderglowSettings::parse(group.readEntry("Enabled", false),+ group.readEntry("Colour", QString()),+ group.readEntry("Custom", QString()),+ group.readEntry("Effect", QString()));+ if (settings.enabled != m_settings.enabled || settings.colour != m_settings.colour || settings.custom != m_settings.custom+ || settings.effect != m_settings.effect) {+ m_settings = settings;+ Q_EMIT settingsChanged();+ update();+ }+}++void Underglow::readMotion()+{+ // Settings > Accessibility > Reduce motion sets KDE's animation speed to+ // instant, the same key WildOS.UI's Theme follows.+ KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("kdeglobals"));+ config->reparseConfiguration();+ const bool reduced = config->group(QStringLiteral("KDE")).readEntry("AnimationDurationFactor", 1.0) <= 0.0;+ if (reduced != m_reducedMotion) {+ m_reducedMotion = reduced;+ Q_EMIT reducedMotionChanged();+ update();+ }+}++void Underglow::readBattery()+{+ QDBusMessage call = QDBusMessage::createMethodCall(upowerService, upowerPath, propertiesInterface, QStringLiteral("Get"));+ call << upowerService << QStringLiteral("OnBattery");+ // Asynchronous, so a missing or slow UPower never holds up KWin; until+ // it answers the glow counts as on mains power.+ auto watcher = new QDBusPendingCallWatcher(QDBusConnection::systemBus().asyncCall(call), this);+ connect(watcher, &QDBusPendingCallWatcher::finished, this, [this, watcher] {+ watcher->deleteLater();+ const QDBusPendingReply<QDBusVariant> reply = *watcher;+ if (!reply.isError()) {+ setOnBattery(reply.value().variant().toBool());+ }+ });+}++void Underglow::upowerPropertiesChanged(const QString &interface, const QVariantMap &changed, const QStringList &invalidated)+{+ if (interface != upowerService) {+ return;+ }+ const auto it = changed.constFind(QStringLiteral("OnBattery"));+ if (it != changed.constEnd()) {+ setOnBattery(it->toBool());+ } else if (invalidated.contains(QLatin1String("OnBattery"))) {+ readBattery();+ }+}++void Underglow::setOnBattery(bool onBattery)+{+ if (onBattery != m_onBattery) {+ m_onBattery = onBattery;+ Q_EMIT onBatteryChanged();+ update();+ }+}++void Underglow::setFullScreen(bool fullScreen)+{+ if (fullScreen != m_fullScreen) {+ m_fullScreen = fullScreen;+ Q_EMIT fullScreenChanged();+ update();+ }+}++void Underglow::update()+{+ const QString running = UnderglowSettings::effectName(UnderglowSettings::running(m_settings, m_onBattery, m_fullScreen, m_reducedMotion));+ if (running != m_running) {+ m_running = running;+ Q_EMIT runningChanged();+ }+}diff --git a/packages/wildos-shell/src/underglow.h b/packages/wildos-shell/src/underglow.hnew file mode 100644index 0000000..6d4c44c--- /dev/null+++ b/packages/wildos-shell/src/underglow.h@@ -0,0 +1,72 @@+#pragma once++#include "underglowsettings.h"++#include <KConfigWatcher>++#include <QColor>+#include <QObject>+#include <QQmlEngine>++// The taskbar underglow as KWin's org.wildos.underglow script draws it:+// what Settings chose in wildosrc [Underglow], and whether the effect may run+// now. Battery and Reduce motion are read here; whether an app is full+// screen only KWin knows, so the script sets fullScreen.+class Underglow : public QObject+{+ Q_OBJECT+ QML_ELEMENT+ QML_SINGLETON++ Q_PROPERTY(bool enabled READ enabled NOTIFY settingsChanged)+ // "accent", "custom" or "rgb".+ Q_PROPERTY(QString colour READ colour NOTIFY settingsChanged)+ Q_PROPERTY(QColor custom READ custom NOTIFY settingsChanged)+ // The chosen effect: "steady", "breathing" or "flowing".+ Q_PROPERTY(QString effect READ effect NOTIFY settingsChanged)+ Q_PROPERTY(bool fullScreen READ fullScreen WRITE setFullScreen NOTIFY fullScreenChanged)+ Q_PROPERTY(bool onBattery READ onBattery NOTIFY onBatteryChanged)+ Q_PROPERTY(bool reducedMotion READ reducedMotion NOTIFY reducedMotionChanged)+ // The effect to draw now, after the steady fallbacks.+ Q_PROPERTY(QString running READ running NOTIFY runningChanged)++public:+ explicit Underglow(QObject *parent = nullptr);++ bool enabled() const { return m_settings.enabled; }+ QString colour() const { return UnderglowSettings::colourName(m_settings.colour); }+ QColor custom() const { return m_settings.custom; }+ QString effect() const { return UnderglowSettings::effectName(m_settings.effect); }+ bool fullScreen() const { return m_fullScreen; }+ void setFullScreen(bool fullScreen);+ bool onBattery() const { return m_onBattery; }+ bool reducedMotion() const { return m_reducedMotion; }+ QString running() const { return m_running; }++ Q_INVOKABLE QList<qreal> glowRows(int reach) const { return UnderglowSettings::glowRows(reach); }++Q_SIGNALS:+ void settingsChanged();+ void fullScreenChanged();+ void onBatteryChanged();+ void reducedMotionChanged();+ void runningChanged();++private Q_SLOTS:+ void upowerPropertiesChanged(const QString &interface, const QVariantMap &changed, const QStringList &invalidated);++private:+ void readSettings();+ void readMotion();+ void readBattery();+ void setOnBattery(bool onBattery);+ void update();++ KConfigWatcher::Ptr m_wildos;+ KConfigWatcher::Ptr m_globals;+ UnderglowSettings::Settings m_settings;+ bool m_fullScreen = false;+ bool m_onBattery = false;+ bool m_reducedMotion = false;+ QString m_running = QStringLiteral("steady");+};diff --git a/packages/wildos-shell/src/underglowsettings.cpp b/packages/wildos-shell/src/underglowsettings.cppnew file mode 100644index 0000000..5ecde9e--- /dev/null+++ b/packages/wildos-shell/src/underglowsettings.cpp@@ -0,0 +1,94 @@+#include "underglowsettings.h"++#include <QRegularExpression>++#include <cmath>++namespace UnderglowSettings+{++Settings parse(bool enabled, const QString &colour, const QString &custom, const QString &effect)+{+ Settings s;+ s.enabled = enabled;++ const QString c = colour.trimmed().toLower();+ if (c == QLatin1String("rgb")) {+ s.colour = Colour::Rgb;+ } else if (c == QLatin1String("custom")) {+ // QColor would also take names such as "red" and #rgb shorthand;+ // Settings only ever writes #rrggbb, so anything else is a damaged+ // file, not a colour choice.+ static const QRegularExpression hex(QStringLiteral("^#[0-9a-fA-F]{6}$"));+ const QString value = custom.trimmed();+ if (hex.match(value).hasMatch()) {+ s.colour = Colour::Custom;+ s.custom = QColor(value);+ }+ }++ const QString e = effect.trimmed().toLower();+ if (s.colour == Colour::Rgb) {+ s.effect = e == QLatin1String("steady") ? Effect::Steady : Effect::Flowing;+ } else {+ s.effect = e == QLatin1String("breathing") ? Effect::Breathing : Effect::Steady;+ }+ return s;+}++Effect running(const Settings &settings, bool onBattery, bool fullScreen, bool reducedMotion)+{+ if (onBattery || fullScreen || reducedMotion) {+ return Effect::Steady;+ }+ return settings.effect;+}++QList<qreal> glowRows(int reach)+{+ constexpr qreal lineHeight = 2;+ constexpr qreal spread = 2;+ constexpr qreal sigma = 14.0 / 2;+ const qreal half = lineHeight / 2 + spread;+ const auto phi = [](qreal x) {+ return 0.5 * (1 + std::erf(x / std::sqrt(2.0)));+ };++ QList<qreal> rows;+ const int count = reach * 2 + int(lineHeight);+ rows.reserve(count);+ const qreal centre = reach + lineHeight / 2;+ for (int y = 0; y < count; ++y) {+ const qreal d = y + 0.5 - centre;+ rows.append(phi((d + half) / sigma) - phi((d - half) / sigma));+ }+ return rows;+}++QString effectName(Effect effect)+{+ switch (effect) {+ case Effect::Breathing:+ return QStringLiteral("breathing");+ case Effect::Flowing:+ return QStringLiteral("flowing");+ case Effect::Steady:+ break;+ }+ return QStringLiteral("steady");+}++QString colourName(Colour colour)+{+ switch (colour) {+ case Colour::Custom:+ return QStringLiteral("custom");+ case Colour::Rgb:+ return QStringLiteral("rgb");+ case Colour::Accent:+ break;+ }+ return QStringLiteral("accent");+}++}diff --git a/packages/wildos-shell/src/underglowsettings.h b/packages/wildos-shell/src/underglowsettings.hnew file mode 100644index 0000000..e9e4a27--- /dev/null+++ b/packages/wildos-shell/src/underglowsettings.h@@ -0,0 +1,53 @@+#pragma once++#include <QColor>+#include <QList>+#include <QString>++// The rules behind the taskbar underglow (Settings > Personalisation >+// Taskbar underglow), kept apart from KConfig and D-Bus so they can be+// tested on their own. Settings writes wildosrc [Underglow] as plain strings;+// anything it does not recognise falls back to the default rather than to no+// glow at all.+namespace UnderglowSettings+{+enum class Colour {+ Accent,+ Custom,+ Rgb,+};++enum class Effect {+ Steady,+ Breathing,+ Flowing,+};++struct Settings {+ bool enabled = false;+ Colour colour = Colour::Accent;+ // Only valid when colour is Custom.+ QColor custom;+ Effect effect = Effect::Steady;+};++// A single colour cannot flow and the spectrum does not breathe (the board+// pairs accent and custom with steady or breathing, RGB with flowing), so an+// effect that does not suit the colour becomes the one that does. A custom+// colour that is not #rrggbb falls back to the accent.+Settings parse(bool enabled, const QString &colour, const QString &custom, const QString &effect);++// The effect to run now. It holds steady on battery, while an app is full+// screen and when Reduce motion is on.+Effect running(const Settings &settings, bool onBattery, bool fullScreen, bool reducedMotion);++// The board's glow is box-shadow: 0 0 14px 2px around the 2px line. CSS+// draws that as the line grown by the 2px spread and blurred with a Gaussian+// whose standard deviation is half the 14px blur. This gives the shadow's+// coverage (0 to 1) for each one-pixel row of a band reaching `reach` pixels+// above and below the line, top to bottom, line rows included.+QList<qreal> glowRows(int reach);++QString effectName(Effect effect);+QString colourName(Colour colour);+}diff --git a/packages/wildos-shell/tests/CMakeLists.txt b/packages/wildos-shell/tests/CMakeLists.txtnew file mode 100644index 0000000..9506b78--- /dev/null+++ b/packages/wildos-shell/tests/CMakeLists.txt@@ -0,0 +1,6 @@+find_package(Qt6 6.8 REQUIRED COMPONENTS Test)++add_executable(underglowtest underglowtest.cpp ../src/underglowsettings.cpp)+target_include_directories(underglowtest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../src)+target_link_libraries(underglowtest PRIVATE Qt6::Core Qt6::Gui Qt6::Test)+add_test(NAME underglow COMMAND underglowtest)diff --git a/packages/wildos-shell/tests/underglowtest.cpp b/packages/wildos-shell/tests/underglowtest.cppnew file mode 100644index 0000000..b28031b--- /dev/null+++ b/packages/wildos-shell/tests/underglowtest.cpp@@ -0,0 +1,119 @@+#include "underglowsettings.h"++#include <QTest>++using namespace UnderglowSettings;++class UnderglowTest : public QObject+{+ Q_OBJECT++private Q_SLOTS:+ void defaults()+ {+ const Settings s = parse(false, QString(), QString(), QString());+ QCOMPARE(s.enabled, false);+ QCOMPARE(s.colour, Colour::Accent);+ QCOMPARE(s.effect, Effect::Steady);+ }++ void accentBreathing()+ {+ const Settings s = parse(true, QStringLiteral("accent"), QString(), QStringLiteral("breathing"));+ QCOMPARE(s.enabled, true);+ QCOMPARE(s.colour, Colour::Accent);+ QCOMPARE(s.effect, Effect::Breathing);+ }++ void customColour()+ {+ const Settings s = parse(true, QStringLiteral("custom"), QStringLiteral("#FF2D95"), QStringLiteral("steady"));+ QCOMPARE(s.colour, Colour::Custom);+ QCOMPARE(s.custom, QColor(0xff, 0x2d, 0x95));+ }++ void customNotHexFallsBackToAccent_data()+ {+ QTest::addColumn<QString>("value");+ QTest::newRow("empty") << QString();+ QTest::newRow("name") << QStringLiteral("red");+ QTest::newRow("short") << QStringLiteral("#f0f");+ QTest::newRow("alpha") << QStringLiteral("#80ff2d95");+ QTest::newRow("junk") << QStringLiteral("#ff2d9g");+ }++ void customNotHexFallsBackToAccent()+ {+ QFETCH(QString, value);+ const Settings s = parse(true, QStringLiteral("custom"), value, QStringLiteral("breathing"));+ QCOMPARE(s.colour, Colour::Accent);+ QCOMPARE(s.effect, Effect::Breathing);+ }++ void effectFollowsColour_data()+ {+ QTest::addColumn<QString>("colour");+ QTest::addColumn<QString>("effect");+ QTest::addColumn<int>("expected");+ QTest::newRow("accent flowing") << "accent" << "flowing" << int(Effect::Steady);+ QTest::newRow("accent unknown") << "accent" << "sparkle" << int(Effect::Steady);+ QTest::newRow("rgb default") << "rgb" << "" << int(Effect::Flowing);+ QTest::newRow("rgb breathing") << "rgb" << "breathing" << int(Effect::Flowing);+ QTest::newRow("rgb steady") << "rgb" << "steady" << int(Effect::Steady);+ QTest::newRow("rgb any case") << "RGB" << "Flowing" << int(Effect::Flowing);+ QTest::newRow("unknown colour") << "plaid" << "breathing" << int(Effect::Breathing);+ }++ void effectFollowsColour()+ {+ QFETCH(QString, colour);+ QFETCH(QString, effect);+ QFETCH(int, expected);+ QCOMPARE(int(parse(true, colour, QStringLiteral("#123456"), effect).effect), expected);+ }++ void fallsBackToSteady_data()+ {+ QTest::addColumn<bool>("battery");+ QTest::addColumn<bool>("fullScreen");+ QTest::addColumn<bool>("reduced");+ QTest::addColumn<int>("expected");+ QTest::newRow("free to run") << false << false << false << int(Effect::Flowing);+ QTest::newRow("battery") << true << false << false << int(Effect::Steady);+ QTest::newRow("full screen") << false << true << false << int(Effect::Steady);+ QTest::newRow("reduce motion") << false << false << true << int(Effect::Steady);+ QTest::newRow("all three") << true << true << true << int(Effect::Steady);+ }++ void fallsBackToSteady()+ {+ QFETCH(bool, battery);+ QFETCH(bool, fullScreen);+ QFETCH(bool, reduced);+ QFETCH(int, expected);+ const Settings s = parse(true, QStringLiteral("rgb"), QString(), QStringLiteral("flowing"));+ QCOMPARE(int(running(s, battery, fullScreen, reduced)), expected);+ }++ void glowMatchesCss()+ {+ const int reach = 20;+ const QList<qreal> rows = glowRows(reach);+ QCOMPARE(rows.size(), reach * 2 + 2);+ // Symmetric about the line, brightest on it.+ for (int i = 0; i < rows.size() / 2; ++i) {+ QVERIFY(qAbs(rows[i] - rows[rows.size() - 1 - i]) < 1e-9);+ QVERIFY(rows[i] <= rows[i + 1] + 1e-9);+ }+ // A row on the line, 0.5px off its centre, sees the 6px spread box+ // through a 7px sigma blur: about a third of full strength.+ QVERIFY(qAbs(rows[reach] - std::erf(2.5 / (7 * std::sqrt(2.0))) / 2 - std::erf(3.5 / (7 * std::sqrt(2.0))) / 2) < 1e-9);+ // At the band's edges the glow is under one 8-bit step even at the+ // 0.55 alpha the board uses, so the band is wide enough.+ QVERIFY(rows.first() * 0.55 * 255 < 1.0);+ }+};++QTEST_GUILESS_MAIN(UnderglowTest)++#include "underglowtest.moc"diff --git a/packages/wildos-store/CMakeLists.txt b/packages/wildos-store/CMakeLists.txtindex 0fbebbe..e23e573 100644--- a/packages/wildos-store/CMakeLists.txt+++ b/packages/wildos-store/CMakeLists.txt@@ -5,7 +5,7 @@ set(CMAKE_CXX_STANDARD 20)set(CMAKE_CXX_STANDARD_REQUIRED ON)include(GNUInstallDirs)-find_package(Qt6 6.8 REQUIRED COMPONENTS Core Gui DBus Qml Quick QuickControls2)+find_package(Qt6 6.8 REQUIRED COMPONENTS Core Gui DBus Network Qml Quick QuickControls2)find_package(KF6KIO REQUIRED)find_package(KF6Service REQUIRED)find_package(packagekitqt6 REQUIRED)@@ -32,20 +32,28 @@ qt_add_qml_module(wildos-storeRESOURCESdata/curated.jsondata/flathub.flatpakrepo- data/hero.jpg+ data/heroes/contours.jpg+ data/photos/create-timeline.jpg+ data/photos/make-krita.jpg+ data/photos/play-controller.jpg+ data/photos/swap-desk.jpg+ data/heroes/dusk-hills.jpg+ data/heroes/waves-green.jpgdata/org.wildos.store.svgSOURCESsrc/catalog.cpp src/catalog.hsrc/storeapp.cpp src/storeapp.hsrc/packagekitbackend.cpp src/packagekitbackend.hsrc/flatpakbackend.cpp src/flatpakbackend.h- src/themeiconprovider.h+ src/localpackage.cpp src/localpackage.h+ src/network.cpp src/network.h+ src/themeiconprovider.h src/timing.h)target_include_directories(wildos-store PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)target_link_libraries(wildos-store PRIVATE- Qt6::Gui Qt6::DBus Qt6::Qml Qt6::Quick Qt6::QuickControls2+ Qt6::Gui Qt6::DBus Qt6::Network Qt6::Qml Qt6::Quick Qt6::QuickControls2KF6::KIOGui KF6::ServicePK::packagekitqt6AppStreamQt@@ -57,3 +65,4 @@ install(FILES data/org.wildos.store.desktop DESTINATION ${CMAKE_INSTALL_DATADIR}install(FILES data/curated.json DESTINATION ${CMAKE_INSTALL_DATADIR}/wildos-store)install(FILES data/org.wildos.store.svg DESTINATION ${CMAKE_INSTALL_DATADIR}/icons/hicolor/scalable/apps)install(FILES data/60wildos-store-icons DESTINATION ${CMAKE_INSTALL_SYSCONFDIR}/apt/apt.conf.d)+install(FILES data/wildos-store-update.service data/wildos-store-update.timer DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/systemd/user)diff --git a/packages/wildos-store/data/hero.jpg b/packages/wildos-store/data/hero.jpgdeleted file mode 100644index aa474dd..0000000Binary files a/packages/wildos-store/data/hero.jpg and /dev/null differdiff --git a/packages/wildos-store/data/heroes/contours.jpg b/packages/wildos-store/data/heroes/contours.jpgnew file mode 100644index 0000000..f67f5c0Binary files /dev/null and b/packages/wildos-store/data/heroes/contours.jpg differdiff --git a/packages/wildos-store/data/heroes/dusk-hills.jpg b/packages/wildos-store/data/heroes/dusk-hills.jpgnew file mode 100644index 0000000..eed36a3Binary files /dev/null and b/packages/wildos-store/data/heroes/dusk-hills.jpg differdiff --git a/packages/wildos-store/data/heroes/waves-green.jpg b/packages/wildos-store/data/heroes/waves-green.jpgnew file mode 100644index 0000000..fbfc472Binary files /dev/null and b/packages/wildos-store/data/heroes/waves-green.jpg differdiff --git a/packages/wildos-store/data/org.wildos.store.desktop b/packages/wildos-store/data/org.wildos.store.desktopindex abbd4ec..3957463 100644--- a/packages/wildos-store/data/org.wildos.store.desktop+++ b/packages/wildos-store/data/org.wildos.store.desktop@@ -8,7 +8,7 @@ Icon=org.wildos.storeTerminal=falseCategories=System;PackageManager;Keywords=apps;install;software;store;updates;programs;-MimeType=x-scheme-handler/appstream;+MimeType=x-scheme-handler/appstream;application/vnd.debian.binary-package;application/x-deb;application/vnd.flatpak.ref;application/x-flatpak-ref;application/vnd.flatpak;application/x-flatpak;StartupNotify=trueStartupWMClass=wildos-storeSingleMainWindow=truediff --git a/packages/wildos-store/data/photos/CREDITS.md b/packages/wildos-store/data/photos/CREDITS.mdnew file mode 100644index 0000000..9d3e054--- /dev/null+++ b/packages/wildos-store/data/photos/CREDITS.md@@ -0,0 +1,12 @@+# Store photographs++Bundled with the Store and shown from disk, so opening the Store never+contacts the photographers' sites. Both licences allow this use without+credit; they are credited here anyway.++| File | Photographer | Source | Licence |+|---|---|---|---|+| swap-desk.jpg | Kawê Rodrigues | https://www.pexels.com/photo/15977087/ | Pexels License |+| make-krita.jpg | Asfand Effandi | https://unsplash.com/photos/aNOavzNktK4 | Unsplash License |+| play-controller.jpg | to confirm (from the design canvas, 13.1) | to confirm | to confirm |+| create-timeline.jpg | Peter Stumpf | https://unsplash.com/photos/yk9VXp4W5-Q | Unsplash License |diff --git a/packages/wildos-store/data/photos/create-timeline.jpg b/packages/wildos-store/data/photos/create-timeline.jpgnew file mode 100644index 0000000..4de60d6Binary files /dev/null and b/packages/wildos-store/data/photos/create-timeline.jpg differdiff --git a/packages/wildos-store/data/photos/make-krita.jpg b/packages/wildos-store/data/photos/make-krita.jpgnew file mode 100644index 0000000..f53f564Binary files /dev/null and b/packages/wildos-store/data/photos/make-krita.jpg differdiff --git a/packages/wildos-store/data/photos/play-controller.jpg b/packages/wildos-store/data/photos/play-controller.jpgnew file mode 100644index 0000000..404b3aeBinary files /dev/null and b/packages/wildos-store/data/photos/play-controller.jpg differdiff --git a/packages/wildos-store/data/photos/swap-desk.jpg b/packages/wildos-store/data/photos/swap-desk.jpgnew file mode 100644index 0000000..0d5e195Binary files /dev/null and b/packages/wildos-store/data/photos/swap-desk.jpg differdiff --git a/packages/wildos-store/data/wildos-store-update.service b/packages/wildos-store/data/wildos-store-update.servicenew file mode 100644index 0000000..8164c4b--- /dev/null+++ b/packages/wildos-store/data/wildos-store-update.service@@ -0,0 +1,13 @@+[Unit]+Description=Update Flathub apps+# Overnight on mains power only, as the Store's Updates page promises.+ConditionACPower=true+After=network-online.target++[Service]+Type=oneshot+# A running app keeps its version until it is closed; flatpak puts the new+# one in place beside it.+ExecStart=/usr/bin/flatpak update --user --noninteractive --assumeyes+Nice=10+IOSchedulingClass=idlediff --git a/packages/wildos-store/data/wildos-store-update.timer b/packages/wildos-store/data/wildos-store-update.timernew file mode 100644index 0000000..ec95627--- /dev/null+++ b/packages/wildos-store/data/wildos-store-update.timer@@ -0,0 +1,9 @@+[Unit]+Description=Update Flathub apps overnight++[Timer]+OnCalendar=*-*-* 03:00+RandomizedDelaySec=90min++[Install]+WantedBy=timers.targetdiff --git a/packages/wildos-store/debian/changelog b/packages/wildos-store/debian/changelogindex fd17094..1c75dbe 100644--- a/packages/wildos-store/debian/changelog+++ b/packages/wildos-store/debian/changelog@@ -1,3 +1,16 @@+wildos-store (0.1.1) trixie; urgency=medium++ * Opening a .deb, .flatpakref or .flatpak file shows its own install+ page: what the file says it is, its version against the installed one+ (Already installed, Newer version installed, Update), what it needs+ and what it would remove, and plainly that nothing has checked it. A+ .deb installs through PackageKit, which fetches what it depends on from+ the Wild OS repositories and asks for the password; a package made for+ another system or another kind of computer says so before anything is+ installed. Flatpak files install for the signed-in user.++ -- Wild OS Developers <[email protected]> Tue, 10 Nov 2026 07:50:00 +0000+wildos-store (0.1.0) trixie; urgency=medium* Initial release.diff --git a/packages/wildos-store/qml/Main.qml b/packages/wildos-store/qml/Main.qmlindex 344d0fd..0046d23 100644--- a/packages/wildos-store/qml/Main.qml+++ b/packages/wildos-store/qml/Main.qml@@ -3,8 +3,10 @@ import QtQuick.Windowimport WildOS.Storeimport WildOS.UI as UI-// The Store window as Store.dc.html draws it: its own 52px title bar with-// search in it, sections down the left, the current page on the right.+// The Store window as the StoreDiscover board draws it: a 248px sidebar+// with the title, search, the sections and the privacy note, and the+// current page on the right under a 46px bar that holds the way back and+// the window buttons.UI.AppWindow {id: root@@ -12,42 +14,54 @@ UI.AppWindow {required property string startSearchrequired property string startPage- property var current: ({ page: "", arg: "", section: "home" })+ property var current: ({ page: "", arg: "", section: "discover" })property var history: []property var pending: null- // The design's column, wider when larger text needs it.+ // The board's sidebar, wider when larger text needs it.readonly property real navWidth: {let widest = 0;for (let i = 0; i < nav.children.length; ++i) {widest = Math.max(widest, nav.children[i].implicitWidth);}- return Math.max(Metrics.navWidth, widest + 24);+ return Math.max(Metrics.navWidth, widest + 20);}- width: 1220- height: 760+ // The board's 1384 by 802, smaller on a smaller screen.+ width: Screen.desktopAvailableWidth > 0 ? Math.max(minimumWidth, Math.min(1384, Screen.desktopAvailableWidth - 48)) : 1384+ height: Screen.desktopAvailableHeight > 0 ? Math.max(minimumHeight, Math.min(802, Screen.desktopAvailableHeight - 48)) : 802minimumWidth: 880minimumHeight: 560visible: truetitle: "Store"- // Store.dc.html draws the deeper window glass, rgba(18,22,40,0.86).deep: true+ readonly property var sections: ["discover", "swap", "create", "work", "play", "develop", "categories", "windowsapps", "updates", "library"]+ // Names other parts of Wild OS, the command line and D-Bus may still+ // use for the pages these replaced.+ readonly property var aliases: ({ home: "discover", installed: "library", windows: "swap" })+function titleOf(entry) {switch (entry.page) {- case "home": return "Home";- case "apps": return entry.arg ? Catalog.categoryLabel(entry.arg) : "Apps";+ case "discover": return "Discover";+ case "swap": return "Swap from Windows";+ case "create": return "Create";+ case "work": return "Work";+ case "play": return "Play";+ case "develop": return "Develop";+ case "categories": return "Categories";+ case "apps": return entry.arg ? Catalog.categoryLabel(entry.arg) : "All apps";case "games": return entry.arg ? Catalog.categoryLabel(entry.arg) : "Games";- case "windows": return "Windows apps";+ case "windowsapps": return "Windows apps";case "updates": return "Updates";- case "installed": return "Installed";+ case "library": return "Library";case "search": return "Search";case "app": {const a = Catalog.app(entry.arg);return a ? a.name : "App";}+ case "file": return "Package file";}- return "Home";+ return "Discover";}function load(entry) {@@ -56,29 +70,40 @@ UI.AppWindow {search.text = "";}const urls = {- home: "pages/HomePage.qml",+ discover: "pages/DiscoverPage.qml",+ swap: "pages/SwapPage.qml",+ create: "pages/CategoryPage.qml",+ work: "pages/CategoryPage.qml",+ play: "pages/CategoryPage.qml",+ develop: "pages/CategoryPage.qml",+ categories: "pages/CategoriesPage.qml",apps: "pages/BrowsePage.qml",games: "pages/BrowsePage.qml",- windows: "pages/WindowsAppsPage.qml",+ windowsapps: "pages/WindowsAppsPage.qml",updates: "pages/UpdatesPage.qml",- installed: "pages/InstalledPage.qml",+ library: "pages/LibraryPage.qml",search: "pages/SearchPage.qml",- app: "pages/AppPage.qml"+ app: "pages/AppPage.qml",+ file: "pages/FilePage.qml"};- pageLoader.setSource(urls[entry.page] || urls.home, { store: root, arg: entry.arg, kind: entry.page });+ pageLoader.setSource(urls[entry.page] || urls.discover, { store: root, arg: entry.arg, kind: entry.page });}function open(page, arg) {- const isSection = ["home", "apps", "games", "windows", "updates", "installed"].indexOf(page) >= 0;- const entry = { page: page, arg: arg || "", section: isSection ? page : current.section };+ page = aliases[page] || page;+ const isSection = sections.indexOf(page) >= 0;+ // A package file belongs to no section.+ const section = isSection ? page : (page === "apps" || page === "games") ? "categories" : page === "file" ? "" : current.section;+ const entry = { page: page, arg: arg || "", section: section };if (current.page === entry.page && current.arg === entry.arg) {return;}- // Picking a section starts a fresh trail; going deeper remembers the- // way back.- if (isSection && !(page === current.section && (page === "apps" || page === "games") && current.page === page)) {+ if (isSection) {+ // Picking a section starts a fresh trail.history = [];- } else if (current.page.length > 0) {+ } else if (current.page.length > 0 && !(current.page === page && (page === "apps" || page === "games"))) {+ // Going deeper remembers the way back; another filter on the+ // same list does not.history = history.concat([current]);}load(entry);@@ -88,7 +113,17 @@ UI.AppWindow {open("app", key);}- // The menu every app tile, card and row shares (AppMenuArea).+ // Get on a Flathub app whose choices are known asks first+ // (StoreConsent.dc.html). True when the dialog took over.+ function requestInstall(app) {+ if (app && !app.installed && app.source === "flatpak" && app.consentItems.length > 0) {+ consent.ask(app);+ return true;+ }+ return false;+ }++ // The menu every app row, card and tile shares (AppMenuArea).function showAppMenu(key, item, x, y) {const a = Catalog.app(key);if (!a) {@@ -102,7 +137,11 @@ UI.AppWindow {entries.push({ text: "Update", icon: "update", run: () => a.update() });}if (!a.installed) {- entries.push({ text: "Install", icon: "download", enabled: a.source.length > 0 && !a.busy && !a.queued, run: () => a.install() });+ entries.push({ text: "Install", icon: "download", enabled: a.source.length > 0 && !a.busy && !a.queued, run: () => {+ if (!root.requestInstall(a)) {+ a.install();+ }+ } });}entries.push({ separator: true });entries.push({ text: "Copy link", icon: "link", enabled: a.appstreamId.length > 0, run: () => root.copyLink(a) });@@ -131,7 +170,7 @@ UI.AppWindow {function back() {if (history.length === 0) {- open("home");+ open("discover");return;}const previous = history[history.length - 1];@@ -140,7 +179,7 @@ UI.AppWindow {}function backTitle() {- return history.length > 0 ? titleOf(history[history.length - 1]) : "Home";+ return history.length > 0 ? titleOf(history[history.length - 1]) : "Discover";}function runSearch(text) {@@ -161,8 +200,13 @@ UI.AppWindow {}}- // From the command line, D-Bus and appstream: links.+ // From the command line, D-Bus and appstream: links. A package file+ // comes as page "file" with its path in app, and needs no catalogue.function openTarget(app, text, page) {+ if (page === "file") {+ open("file", app);+ return;+ }if (!Catalog.ready) {pending = { app: app, text: text, page: page };return;@@ -186,6 +230,11 @@ UI.AppWindow {}Component.onCompleted: {+ if (startPage === "file") {+ open("discover");+ open("file", startApp);+ return;+ }open(startPage);if (startApp.length > 0 || startSearch.length > 0) {openTarget(startApp, startSearch, "");@@ -219,114 +268,169 @@ UI.AppWindow {onActivated: search.forceActiveFocus()}- // The design's border sits outside the 1220 by 760 content box.+ // The window's 1px edge sits outside the content.Item {id: inneranchors.fill: parentanchors.margins: root.maximised ? 0 : 1+ Rectangle {+ id: sidebar+ width: root.navWidth+ height: parent.height+ topLeftRadius: root.maximised ? 0 : UI.Style.windowRadius - 1+ bottomLeftRadius: topLeftRadius+ color: Metrics.sidebar++ Rectangle {+ anchors.right: parent.right+ width: 1+ height: parent.height+ color: Metrics.divider+ }+ }+UI.TitleBar {id: titleBarwidth: parent.width- height: Metrics.titleBarHeight+ height: Metrics.topBarHeightframe: root.frame- buttons.buttonHeight: Metrics.titleBarHeight-- Image {- id: logo- anchors.verticalCenter: parent.verticalCenter- width: 20- height: 20- sourceSize: Qt.size(40, 40)- source: "qrc:/qt/qml/WildOS/Store/data/org.wildos.store.svg"- }+ buttons.buttonHeight: Metrics.topBarHeightUI.Label {- id: appName- anchors.left: logo.right- anchors.leftMargin: 12anchors.verticalCenter: parent.verticalCentertext: "Store"+ size: 14+ font.weight: Font.DemiBoldcolor: root.active ? UI.Style.ink : UI.Style.inkMuted}- UI.SearchField {- id: search- pill: true- anchors.left: appName.right- anchors.leftMargin: 12 + 160+ StoreLink {+ // The page's 24px in from the sidebar, less the title bar's+ // own 16px and the link's 4px of padding.+ x: root.navWidth + 24 - 16 - 4anchors.verticalCenter: parent.verticalCenter- width: Math.min(440, parent.width - x - 16)- height: 34- placeholderText: "Search apps, or the Windows app you used before"- Accessible.name: "Search apps"- Accessible.description: placeholderText- onTextEdited: searchDelay.restart()- // The clear button and Escape empty the box without an edit.- onTextChanged: if (text.length === 0) searchDelay.restart()- onAccepted: {- searchDelay.stop();- root.runSearch(text);- }+ visible: root.history.length > 0+ iconName: "chevron-left"+ text: root.backTitle()+ Accessible.name: "Back to " + root.backTitle()+ onClicked: root.back()}+ }- Timer {- id: searchDelay- interval: 250- onTriggered: root.runSearch(search.text)+ UI.SearchField {+ id: search+ x: 16+ y: Metrics.topBarHeight + 2+ width: root.navWidth - 32+ height: 34+ iconLeading: true+ iconInset: 11+ iconSize: 15+ font.pixelSize: UI.Style.px(13.5)+ placeholderText: "Search"+ placeholderTextColor: Metrics.inkTertiary+ Accessible.name: "Search apps"+ Accessible.description: "Search apps, or the Windows app you used before"+ background: Rectangle {+ radius: 9+ color: search.activeFocus ? Metrics.buttonFill : UI.Style.tone(0.06)+ border.width: search.activeFocus ? 2 : 0+ border.color: UI.Style.accent+ }+ onTextEdited: searchDelay.restart()+ // The clear button and Escape empty the box without an edit.+ onTextChanged: if (text.length === 0) searchDelay.restart()+ onAccepted: {+ searchDelay.stop();+ root.runSearch(text);}}+ Timer {+ id: searchDelay+ interval: 250+ onTriggered: root.runSearch(search.text)+ }+Column {id: nav- y: titleBar.height + 8- x: 12- width: root.navWidth - 24+ x: 10+ y: search.y + search.height + 14+ width: root.navWidth - 20spacing: 2NavItem {- iconName: "home"- text: "Home"- current: root.current.section === "home"- onClicked: root.open("home")+ iconName: "discover"+ text: "Discover"+ current: root.current.section === "discover"+ onClicked: root.open("discover")}NavItem {- iconName: "apps"- text: "Apps"- current: root.current.section === "apps"- onClicked: root.open("apps")+ iconName: "swap-windows"+ text: "Swap from Windows"+ current: root.current.section === "swap"+ onClicked: root.open("swap")}NavItem {- iconName: "games"- text: "Games"- current: root.current.section === "games"- onClicked: root.open("games")+ iconName: "create"+ text: "Create"+ current: root.current.section === "create"+ onClicked: root.open("create")}NavItem {- iconName: "windowsapps"+ iconName: "work"+ text: "Work"+ current: root.current.section === "work"+ onClicked: root.open("work")+ }++ NavItem {+ iconName: "play"+ text: "Play"+ current: root.current.section === "play"+ onClicked: root.open("play")+ }++ NavItem {+ iconName: "develop"+ text: "Develop"+ current: root.current.section === "develop"+ onClicked: root.open("develop")+ }++ NavItem {+ iconName: "categories"+ text: "Categories"+ current: root.current.section === "categories"+ onClicked: root.open("categories")+ }++ NavItem {+ iconName: "windows-apps"text: "Windows apps"- current: root.current.section === "windows"- onClicked: root.open("windows")+ current: root.current.section === "windowsapps"+ onClicked: root.open("windowsapps")}Item {width: parent.width- height: 17+ height: 25Rectangle {- x: 12- y: 8- width: parent.width - 24+ x: 10+ y: 12+ width: parent.width - 20height: 1- color: UI.Style.tone(0.08)+ color: Metrics.divider}}NavItem {- iconName: "update"+ iconName: "updates"text: "Updates"badge: Catalog.updateCountcurrent: root.current.section === "updates"@@ -334,22 +438,76 @@ UI.AppWindow {}NavItem {- iconName: "installed"- text: "Installed"- current: root.current.section === "installed"- onClicked: root.open("installed")+ iconName: "library"+ text: "Library"+ working: Catalog.workingCount > 0+ current: root.current.section === "library"+ onClicked: root.open("library")+ }+ }++ // What the Store knows about the person using it, which is nothing+ // beyond what any download gives away.+ Rectangle {+ id: privacy+ x: 14+ width: root.navWidth - 28+ height: privacyRow.implicitHeight + 26+ anchors.bottom: parent.bottom+ anchors.bottomMargin: 14+ // Larger text on a short window would push it over the+ // sections; it steps aside rather than cover them.+ visible: y > nav.y + nav.height + 14+ radius: 12+ color: Metrics.privacyCard+ border.width: 1+ border.color: Metrics.divider++ Row {+ id: privacyRow+ x: 14+ y: 13+ width: parent.width - 28+ spacing: 10++ StoreIcon {+ name: "private"+ size: 18+ color: UI.Style.accent+ }++ Column {+ width: parent.width - 28+ spacing: 3++ UI.Label {+ width: parent.width+ text: "No account needed"+ font.weight: Font.DemiBold+ }++ UI.Label {+ width: parent.width+ text: "The Store never asks who you are. Flathub sees your IP address when you download, like any website."+ size: 12+ lineHeight: 1.45+ color: Metrics.inkSecondary+ wrapMode: Text.Wrap+ elide: Text.ElideNone+ }+ }}}Loader {id: pageLoaderx: root.navWidth- y: titleBar.height+ y: Metrics.topBarHeightwidth: parent.width - root.navWidth- height: parent.height - titleBar.height+ height: parent.height - Metrics.topBarHeightclip: truefocus: true- // Each page rises a little as it fades in, as the Microsoft Store does.+ // Each page rises a little as it fades in.transform: UI.Reveal {item: pageLoaderkey: pageLoader.item@@ -370,6 +528,10 @@ UI.AppWindow {id: appMenu}+ ConsentDialog {+ id: consent+ }+UI.Dialog {id: removeDialogtitle: root.removing ? "Uninstall " + root.removing.name + "?" : ""diff --git a/packages/wildos-store/qml/components/AppGrid.qml b/packages/wildos-store/qml/components/AppGrid.qmlindex f183201..3820c28 100644--- a/packages/wildos-store/qml/components/AppGrid.qml+++ b/packages/wildos-store/qml/components/AppGrid.qml@@ -1,45 +1,63 @@import QtQuickimport QtQuick.Controls+import WildOS.Storeimport WildOS.UI as UI-// A long list of apps as a scrolling grid of compact cards, for categories-// and search results that can run to thousands of apps.+// A long list of apps in the boards' three columns, for categories and+// search results that can run to thousands: only the rows in view are+// made, and they are reused as the list scrolls. The page's title and+// anything above the list go in `header`.GridView {id: gridproperty var keys: []+ // Rows get a button for the app's menu (Library, where Uninstall is).+ property bool showMore: false+ // The header's width, inside the page's 44px sides.+ readonly property real innerWidth: width - 2 * Metrics.sidePaddingsignal activated(string key)- readonly property int columns: width > 912 ? 4 : width > 600 ? 3 : 2- leftMargin: Metrics.contentLeft- rightMargin: Metrics.contentRight - 12- topMargin: Metrics.contentTop- bottomMargin: 28+ readonly property int columns: innerWidth > 900 ? 3 : innerWidth > 560 ? 2 : 1+ readonly property int lastRowStart: {+ const n = keys.length;+ const rem = n % columns;+ return n - (rem === 0 ? columns : rem);+ }+ leftMargin: Metrics.sidePadding+ // The last column's gap hangs into the right margin.+ rightMargin: Metrics.sidePadding - Metrics.columnGap+ topMargin: Metrics.pageTop+ bottomMargin: 32cellWidth: Math.floor((width - leftMargin - rightMargin) / columns)- cellHeight: probe.implicitHeight + 12+ cellHeight: probe.implicitHeightclip: trueboundsBehavior: Flickable.StopAtBoundsmodel: keysreuseItems: trueScrollBar.vertical: UI.ScrollBar {}- // Every cell is as tall as one card at the current text size.- AppTile {+ // Every cell is as tall as one row at the current text size.+ AppListRow {id: probevisible: false- width: 200+ showMore: grid.showMore+ width: 300}delegate: Item {+ id: cellrequired property string modelData+ required property int indexwidth: grid.cellWidthheight: grid.cellHeight- AppTile {- width: parent.width - 12- height: grid.cellHeight - 12- appKey: parent.modelData+ AppListRow {+ width: parent.width - Metrics.columnGap+ height: parent.height+ appKey: cell.modelData+ divider: cell.index < grid.lastRowStart+ showMore: grid.showMoreonActivated: key => grid.activated(key)}}diff --git a/packages/wildos-store/qml/components/AppList.qml b/packages/wildos-store/qml/components/AppList.qmlnew file mode 100644index 0000000..5bc9c13--- /dev/null+++ b/packages/wildos-store/qml/components/AppList.qml@@ -0,0 +1,56 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Store++// A short list of apps in the boards' columns (three across, 34px apart,+// filled a row at a time), for the handful on Discover, a category's top+// picks or a search's swaps. Long lists use AppGrid, which only makes the+// rows in view.+Grid {+ id: list++ property var keys: []+ property int maxItems: -1+ property bool numbered: false+ // The curated note under the button ("Opens PSD files"), for swaps.+ property bool showNotes: false++ signal activated(string key)++ readonly property var shownKeys: maxItems > 0 ? keys.slice(0, maxItems) : keys+ readonly property int lastRowStart: {+ const n = shownKeys.length;+ const rem = n % columns;+ return n - (rem === 0 ? columns : rem);+ }++ Layout.fillWidth: true+ columns: width > 900 ? 3 : width > 560 ? 2 : 1+ columnSpacing: Metrics.columnGap+ rowSpacing: 0+ readonly property real cellWidth: (width - columnSpacing * (columns - 1)) / columns++ function noteOf(key) {+ const a = Catalog.app(key);+ if (!a || a.cardNote.length === 0) {+ return "";+ }+ const note = a.cardNote.replace(/^Free, /, "");+ return note.charAt(0).toUpperCase() + note.slice(1);+ }++ Repeater {+ model: list.shownKeys++ AppListRow {+ required property string modelData+ required property int index+ width: list.cellWidth+ appKey: modelData+ number: list.numbered ? index + 1 : 0+ divider: index < list.lastRowStart+ note: list.showNotes ? list.noteOf(modelData) : ""+ onActivated: key => list.activated(key)+ }+ }+}diff --git a/packages/wildos-store/qml/components/AppListRecent.qml b/packages/wildos-store/qml/components/AppListRecent.qmlnew file mode 100644index 0000000..824241c--- /dev/null+++ b/packages/wildos-store/qml/components/AppListRecent.qml@@ -0,0 +1,90 @@+import QtQuick+import QtQuick.Templates as T+import WildOS.Store+import WildOS.UI as UI++// A row under "Updated recently": the 40px icon, the name, when it was+// updated and the app's button.+T.AbstractButton {+ id: row++ property string appKey+ readonly property var app: Catalog.app(appKey)++ signal activated(string key)++ implicitHeight: Math.max(40, Math.ceil(name.implicitHeight), button.implicitHeight) + 22+ hoverEnabled: true+ focusPolicy: Qt.TabFocus+ Accessible.role: Accessible.Button+ Accessible.name: app ? app.name + ", updated " + app.updatedText : ""+ onClicked: activated(appKey)++ AppMenuArea {+ appKey: row.appKey+ }++ background: Item {+ Rectangle {+ anchors.fill: parent+ anchors.leftMargin: -8+ anchors.rightMargin: -8+ anchors.topMargin: 1+ radius: UI.Style.radiusSm+ color: row.down ? Metrics.pill : row.hovered ? Metrics.rowHover : "transparent"+ Behavior on color {+ ColorAnimation { duration: UI.Style.hoverDuration }+ }++ UI.FocusRing {+ visible: row.visualFocus+ targetRadius: UI.Style.radiusSm+ }+ }++ Rectangle {+ width: parent.width+ height: 1+ color: Metrics.divider+ }+ }++ contentItem: Item {+ AppIcon {+ id: icon+ anchors.verticalCenter: parent.verticalCenter+ size: 40+ source: row.app ? row.app.iconSource : ""+ }++ UI.Label {+ id: name+ anchors.left: icon.right+ anchors.leftMargin: 14+ anchors.right: when.left+ anchors.rightMargin: 14+ anchors.verticalCenter: parent.verticalCenter+ text: row.app ? row.app.name : ""+ size: 14+ font.weight: Font.DemiBold+ }++ UI.Label {+ id: when+ anchors.right: button.left+ anchors.rightMargin: 14+ anchors.verticalCenter: parent.verticalCenter+ width: 110+ text: row.app ? row.app.updatedText : ""+ size: 13+ color: Metrics.inkTertiary+ }++ StoreButton {+ id: button+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ app: row.app+ }+ }+}diff --git a/packages/wildos-store/qml/components/AppListRow.qml b/packages/wildos-store/qml/components/AppListRow.qmlnew file mode 100644index 0000000..86b7536--- /dev/null+++ b/packages/wildos-store/qml/components/AppListRow.qml@@ -0,0 +1,140 @@+import QtQuick+import QtQuick.Templates as T+import QtQuick.Window+import WildOS.Store+import WildOS.UI as UI++// An app in the boards' three-column lists: an optional place number, the+// 56px icon, name and one line, and the app's button at the right. A right+// click gives the app's menu; `showMore` adds a button that opens it too.+T.AbstractButton {+ id: row++ property string appKey+ property int number: 0+ property bool divider: true+ property string note+ property bool showMore: false+ property string subtitle: app ? app.tagline : ""+ readonly property var app: Catalog.app(appKey)++ signal activated(string key)++ implicitHeight: Math.max(56, Math.ceil(texts.implicitHeight), Math.ceil(button.implicitHeight)) + 22+ hoverEnabled: true+ focusPolicy: Qt.TabFocus+ Accessible.role: Accessible.Button+ Accessible.name: app ? app.name + ", " + subtitle : ""+ onClicked: activated(appKey)++ AppMenuArea {+ appKey: row.appKey+ }++ background: Item {+ Rectangle {+ anchors.fill: parent+ anchors.leftMargin: -8+ anchors.rightMargin: -8+ anchors.topMargin: 1+ anchors.bottomMargin: 1+ radius: UI.Style.radiusSm+ color: row.down ? Metrics.pill : row.hovered ? Metrics.rowHover : "transparent"+ Behavior on color {+ ColorAnimation { duration: UI.Style.hoverDuration }+ }++ UI.FocusRing {+ visible: row.visualFocus+ targetRadius: UI.Style.radiusSm+ }+ }++ Rectangle {+ visible: row.divider+ anchors.bottom: parent.bottom+ width: parent.width+ height: 1+ color: Metrics.divider+ }+ }++ contentItem: Item {+ UI.Label {+ id: place+ visible: row.number > 0+ width: visible ? 22 : 0+ anchors.verticalCenter: parent.verticalCenter+ text: row.number+ size: 16+ font.weight: Font.Bold+ font.features: { "tnum": 1 }+ color: Metrics.inkSecondary+ }++ AppIcon {+ id: icon+ x: place.visible ? place.width + 13 : 0+ anchors.verticalCenter: parent.verticalCenter+ size: 56+ source: row.app ? row.app.iconSource : ""+ }++ Column {+ id: texts+ anchors.left: icon.right+ anchors.leftMargin: 13+ anchors.right: actions.left+ anchors.rightMargin: 13+ anchors.verticalCenter: parent.verticalCenter+ spacing: 3++ UI.Label {+ width: parent.width+ text: row.app ? row.app.name : ""+ size: 14.5+ font.weight: Font.DemiBold+ }++ UI.Label {+ width: parent.width+ visible: text.length > 0+ text: row.subtitle+ size: 13+ color: Metrics.inkSecondary+ }+ }++ Row {+ id: actions+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ spacing: 4++ StoreButton {+ id: button+ anchors.verticalCenter: parent.verticalCenter+ app: row.app+ note: row.note+ }++ UI.IconButton {+ id: more+ visible: row.showMore+ anchors.verticalCenter: parent.verticalCenter+ width: 28+ height: 28+ radius: 14+ iconName: "more"+ iconSize: 15+ tip: "More options"+ onClicked: {+ const window = row.Window.window;+ if (window && window.showAppMenu) {+ window.showAppMenu(row.appKey, more, more.width / 2, more.height);+ }+ }+ }+ }+ }+}diff --git a/packages/wildos-store/qml/components/AppRow.qml b/packages/wildos-store/qml/components/AppRow.qmldeleted file mode 100644index ad48058..0000000--- a/packages/wildos-store/qml/components/AppRow.qml+++ /dev/null@@ -1,127 +0,0 @@-import QtQuick-import QtQuick.Templates as T-import WildOS.Store-import WildOS.UI as UI--// An app as a row in Updates and Installed: icon, name, where it came from,-// and its actions on the right.-T.AbstractButton {- id: row-- property string appKey- property bool showRemove: false- readonly property var app: Catalog.app(appKey)-- signal activated(string key)-- width: parent ? parent.width : implicitWidth- implicitHeight: Math.max(62, Math.ceil(texts.implicitHeight) + 24)- hoverEnabled: true- focusPolicy: Qt.TabFocus- Accessible.role: Accessible.Button- Accessible.name: app ? app.name : ""- onClicked: activated(appKey)-- AppMenuArea {- appKey: row.appKey- }-- background: Rectangle {- color: row.down ? UI.Style.surfacePressed : row.hovered ? UI.Style.surfaceHover : "transparent"- Behavior on color {- ColorAnimation { duration: UI.Style.hoverDuration }- }-- Rectangle {- anchors.bottom: parent.bottom- width: parent.width- height: 1- color: UI.Style.divider- }-- UI.FocusRing {- visible: row.visualFocus- anchors.margins: 2- targetRadius: UI.Style.radiusXs- }- }-- contentItem: Item {- AppIcon {- id: icon- x: 18- anchors.verticalCenter: parent.verticalCenter- size: 34- source: row.app ? row.app.iconSource : ""- }-- Column {- id: texts- anchors.left: icon.right- anchors.leftMargin: 14- anchors.right: actions.left- anchors.rightMargin: 16- anchors.verticalCenter: parent.verticalCenter- spacing: 2-- UI.Label {- width: parent.width- text: row.app ? row.app.name : ""- size: 14- }-- UI.Label {- width: parent.width- size: 12- color: UI.Style.inkMuted- text: {- if (!row.app) {- return "";- }- const from = row.app.source === "flatpak" ? "Sandboxed app" : "Wild OS app";- const extra = row.app.sizeText.length > 0 ? row.app.sizeText : row.app.version.length > 0 ? "Version " + row.app.version : "";- return extra.length > 0 ? from + ", " + extra.charAt(0).toLowerCase() + extra.slice(1) : from;- }- }- }-- Row {- id: actions- anchors.right: parent.right- anchors.rightMargin: 18- anchors.verticalCenter: parent.verticalCenter- spacing: 10-- UI.Button {- visible: row.showRemove && row.app && row.app.installed && !row.app.busy && !row.app.queued- size: "small"- text: "Uninstall"- onClicked: removeDialog.open()- }-- InstallButton {- app: row.app- }- }- }-- UI.Dialog {- id: removeDialog- title: row.app ? "Uninstall " + row.app.name + "?" : ""- text: "Your files stay where they are."- buttons: [- UI.Button {- text: "Cancel"- onClicked: removeDialog.close()- },- UI.Button {- kind: "primary"- text: "Uninstall"- onClicked: {- removeDialog.close();- row.app.remove();- }- }- ]- }-}diff --git a/packages/wildos-store/qml/components/AppTile.qml b/packages/wildos-store/qml/components/AppTile.qmldeleted file mode 100644index 961bb3b..0000000--- a/packages/wildos-store/qml/components/AppTile.qml+++ /dev/null@@ -1,86 +0,0 @@-import QtQuick-import QtQuick.Templates as T-import WildOS.Store-import WildOS.UI as UI--// The compact app card from the bottom row of Store.dc.html: 34px icon, the-// name and one line under it. Used for every list of apps. A right click-// gives the app's menu, as tiles do in the Microsoft Store.-T.AbstractButton {- id: tile-- property string appKey- property string subtitle: app ? (app.busy || app.queued ? progressLabel : app.installed ? "Installed" : app.tagline) : ""- readonly property var app: Catalog.app(appKey)- readonly property string progressLabel: {- if (!app) {- return "";- }- if (app.queued) {- return "Waiting to install";- }- const pct = app.progress >= 0 ? " " + app.progress + "%" : "";- return (app.action === "remove" ? "Removing" : app.action === "update" ? "Updating" : "Installing") + pct;- }-- signal activated(string key)-- implicitHeight: Math.max(62, Math.ceil(texts.implicitHeight) + 24)- hoverEnabled: true- focusPolicy: Qt.TabFocus- Accessible.role: Accessible.Button- Accessible.name: app ? app.name + ", " + subtitle : ""- onClicked: activated(appKey)-- AppMenuArea {- appKey: tile.appKey- }-- background: Rectangle {- radius: UI.Style.radiusMd- color: tile.down ? UI.Style.surfacePressed : tile.hovered ? Metrics.tileHover : UI.Style.surfaceRaised- border.width: 1- border.color: UI.Style.borderSubtle- Behavior on color {- ColorAnimation { duration: UI.Style.hoverDuration }- }-- UI.FocusRing {- visible: tile.visualFocus- targetRadius: UI.Style.radiusMd- }- }-- contentItem: Item {- AppIcon {- id: icon- x: 16- anchors.verticalCenter: parent.verticalCenter- size: 34- source: tile.app ? tile.app.iconSource : ""- }-- Column {- id: texts- anchors.left: icon.right- anchors.leftMargin: 12- anchors.right: parent.right- anchors.rightMargin: 16- anchors.verticalCenter: parent.verticalCenter- spacing: 2-- UI.Label {- width: parent.width- text: tile.app ? tile.app.name : ""- font.weight: Font.DemiBold- }-- UI.Label {- width: parent.width- text: tile.subtitle- size: 12- color: tile.app && (tile.app.busy || tile.app.queued) ? UI.Style.accentText : UI.Style.inkMuted- }- }- }-}diff --git a/packages/wildos-store/qml/components/ConsentDialog.qml b/packages/wildos-store/qml/components/ConsentDialog.qmlnew file mode 100644index 0000000..525b939--- /dev/null+++ b/packages/wildos-store/qml/components/ConsentDialog.qml@@ -0,0 +1,281 @@+import QtQuick+import QtQuick.Effects+import QtQuick.Layouts+import QtQuick.Templates as T+import QtQuick.Window+import WildOS.Store+import WildOS.UI as UI++// "Before OBS Studio installs", StoreConsent.dc.html: what a Flathub app+// asks to reach, each with a switch, before anything downloads. Install+// sets the choices and starts the install; Cancel leaves the app as it was.+T.Popup {+ id: dialog++ property var app: null+ // The items as they were when the dialog opened, and the switches'+ // positions by token.+ property var items: []+ property var choices: ({})++ function ask(target) {+ app = target;+ items = target.consentItems;+ const c = {};+ for (const item of items) {+ c[item.token] = item.required || item.allowed;+ }+ choices = c;+ open();+ }++ function install() {+ const target = app;+ const picked = choices;+ close();+ target.installWith(picked);+ }++ parent: T.Overlay.overlay+ anchors.centerIn: parent+ width: Math.min(448, parent ? parent.width - 48 : 448)+ height: Math.min(implicitHeight, parent ? parent.height - 48 : implicitHeight)+ implicitHeight: content.implicitHeight + topPadding + bottomPadding+ modal: true+ focus: true+ topPadding: 28+ leftPadding: 28+ rightPadding: 28+ bottomPadding: 22+ closePolicy: T.Popup.CloseOnEscape++ T.Overlay.modal: Rectangle {+ radius: Window.window && Window.window.visibility !== Window.Maximized && Window.window.visibility !== Window.FullScreen ? UI.Style.windowRadius : 0+ color: UI.Style.dark ? Qt.rgba(4 / 255, 6 / 255, 16 / 255, 0.55) : UI.Style.scrim+ Behavior on opacity {+ NumberAnimation { duration: UI.Style.motionFast }+ }+ }++ background: Rectangle {+ radius: UI.Style.radiusDialog+ color: Metrics.dialog+ border.width: 1+ border.color: UI.Style.tone(0.12)+ layer.enabled: true+ layer.effect: MultiEffect {+ shadowEnabled: true+ shadowColor: Qt.rgba(0, 0, 0, UI.Style.dark ? 0.6 : 0.2)+ shadowVerticalOffset: 40+ shadowBlur: 1.0+ blurMax: 64+ }+ }++ contentItem: Flickable {+ Accessible.role: Accessible.Dialog+ Accessible.name: dialog.app ? "Before " + dialog.app.name + " installs" : ""+ contentHeight: content.implicitHeight+ clip: contentHeight > height+ boundsBehavior: Flickable.StopAtBounds+ interactive: contentHeight > height++ ColumnLayout {+ id: content+ width: dialog.availableWidth+ spacing: 6++ ColumnLayout {+ Layout.fillWidth: true+ spacing: 12++ AppIcon {+ Layout.alignment: Qt.AlignHCenter+ size: 72+ source: dialog.app ? dialog.app.iconSource : ""+ }++ UI.Label {+ Layout.fillWidth: true+ horizontalAlignment: Text.AlignHCenter+ text: dialog.app ? "Before " + dialog.app.name + " installs" : ""+ size: 20+ font.weight: Font.Bold+ wrapMode: Text.Wrap+ elide: Text.ElideNone+ Accessible.role: Accessible.Heading+ }++ UI.Label {+ Layout.fillWidth: true+ horizontalAlignment: Text.AlignHCenter+ text: "Choose what it can reach. Anything you leave off, it simply can't see. You can change this later in Settings."+ size: 13.5+ lineHeight: 1.5+ color: Metrics.inkSecondary+ wrapMode: Text.Wrap+ elide: Text.ElideNone+ }+ }++ Column {+ Layout.fillWidth: true+ Layout.topMargin: 12++ Repeater {+ model: dialog.items++ Item {+ id: choice+ required property var modelData+ required property int index+ width: parent.width+ height: Math.max(34, texts.implicitHeight) + 24++ Rectangle {+ visible: choice.index > 0+ width: parent.width+ height: 1+ color: Metrics.divider+ }++ Rectangle {+ id: well+ anchors.verticalCenter: parent.verticalCenter+ width: 34+ height: 34+ radius: 9+ color: Metrics.iconWell++ StoreIcon {+ anchors.centerIn: parent+ name: Metrics.reachIcons[choice.modelData.icon] || "shield"+ size: 18+ color: UI.Style.iconInk+ }+ }++ Column {+ id: texts+ anchors.left: well.right+ anchors.leftMargin: 13+ anchors.right: trailing.left+ anchors.rightMargin: 13+ anchors.verticalCenter: parent.verticalCenter+ spacing: 2++ UI.Label {+ width: parent.width+ text: choice.modelData.label+ size: 14+ font.weight: Font.DemiBold+ }++ UI.Label {+ width: parent.width+ visible: text.length > 0+ text: choice.modelData.detail || ""+ size: 12.5+ color: Metrics.inkSecondary+ wrapMode: Text.Wrap+ elide: Text.ElideNone+ }+ }++ Item {+ id: trailing+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ width: choice.modelData.required ? requiredLabel.implicitWidth : toggle.implicitWidth+ height: 24++ UI.Label {+ id: requiredLabel+ visible: choice.modelData.required+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ text: "Required"+ size: 12+ color: Metrics.inkTertiary+ }++ UI.Toggle {+ id: toggle+ visible: !choice.modelData.required+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ checked: dialog.choices[choice.modelData.token] === true+ Accessible.name: choice.modelData.label+ onToggled: {+ const c = Object.assign({}, dialog.choices);+ c[choice.modelData.token] = checked;+ dialog.choices = c;+ }+ }+ }+ }+ }+ }++ RowLayout {+ Layout.fillWidth: true+ Layout.topMargin: 12+ spacing: 10++ component DialogButton: T.Button {+ id: button+ property bool primary: false+ Layout.fillWidth: true+ Layout.preferredWidth: 1+ implicitHeight: Math.max(40, Math.ceil(buttonLabel.implicitHeight) + 16)+ hoverEnabled: true+ focusPolicy: Qt.StrongFocus+ Accessible.name: text++ background: Rectangle {+ radius: 10+ color: button.primary ? (button.down ? UI.Style.accentPressed : button.hovered ? UI.Style.accentHover : UI.Style.accent)+ : button.down ? Metrics.buttonPressed : button.hovered ? Metrics.buttonHover : UI.Style.tone(0.09)+ Behavior on color {+ ColorAnimation { duration: UI.Style.hoverDuration }+ }++ UI.FocusRing {+ visible: button.visualFocus+ targetRadius: 10+ }+ }++ contentItem: UI.Label {+ id: buttonLabel+ horizontalAlignment: Text.AlignHCenter+ text: button.text+ size: 14+ font.weight: button.primary ? Font.Bold : Font.DemiBold+ color: button.primary ? UI.Style.textOnAccent : UI.Style.ink+ }+ }++ DialogButton {+ text: "Cancel"+ onClicked: dialog.close()+ }++ DialogButton {+ primary: true+ text: "Install"+ focus: true+ onClicked: dialog.install()+ }+ }+ }+ }++ enter: Transition {+ NumberAnimation { property: "opacity"; from: 0; to: 1; duration: UI.Style.motionFast; easing.type: Easing.OutCubic }+ NumberAnimation { property: "scale"; from: UI.Style.scaleEnter; to: 1; duration: UI.Style.motionNormal; easing.type: UI.Style.easeEnter }+ }+ exit: Transition {+ NumberAnimation { property: "opacity"; from: 1; to: 0; duration: UI.Style.motionFast; easing.type: UI.Style.easeExit }+ }+}diff --git a/packages/wildos-store/qml/components/FactStrip.qml b/packages/wildos-store/qml/components/FactStrip.qmlnew file mode 100644index 0000000..4ee7ffa--- /dev/null+++ b/packages/wildos-store/qml/components/FactStrip.qml@@ -0,0 +1,103 @@+import QtQuick+import WildOS.UI as UI++// The app page's strip of facts under the title (StoreAppPage.dc.html):+// hairlines above and below, cells split evenly with a hairline between,+// each a small capitalised label, the value and a quiet line under it.+Item {+ id: facts+ implicitHeight: factRow.implicitHeight + 28++ // Each {label, value, sub}, or {label, icon, sub} for a picture+ // in place of the value.+ property var cells: []++ Rectangle {+ width: parent.width+ height: 1+ color: Metrics.divider+ }++ Rectangle {+ anchors.bottom: parent.bottom+ width: parent.width+ height: 1+ color: Metrics.divider+ }++ Row {+ id: factRow+ y: 14+ width: parent.width++ Repeater {+ model: facts.cells++ Item {+ id: cell+ required property var modelData+ required property int index+ width: factRow.width / facts.cells.length+ implicitHeight: cellColumn.implicitHeight++ Rectangle {+ visible: cell.index > 0+ width: 1+ height: parent.height+ color: Metrics.divider+ }++ Column {+ id: cellColumn+ x: 8+ width: parent.width - 16+ spacing: 5++ UI.Label {+ width: parent.width+ horizontalAlignment: Text.AlignHCenter+ text: cell.modelData.label.toUpperCase()+ size: 10.5+ font.weight: Font.Bold+ font.letterSpacing: 0.74+ color: Metrics.inkTertiary+ }++ Item {+ width: parent.width+ height: 24++ UI.Label {+ visible: !cell.modelData.icon+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width+ horizontalAlignment: Text.AlignHCenter+ text: cell.modelData.value+ size: 18+ font.weight: Font.Bold+ color: Metrics.inkSecondary+ }++ UI.Icon {+ visible: !!cell.modelData.icon+ anchors.centerIn: parent+ name: cell.modelData.icon || ""+ size: 22+ strokeWidth: 2+ color: Metrics.success+ }+ }++ UI.Label {+ width: parent.width+ horizontalAlignment: Text.AlignHCenter+ // An empty line keeps every cell the same height.+ text: cell.modelData.sub || " "+ size: 12+ color: Metrics.inkTertiary+ }+ }+ }+ }+ }+}diff --git a/packages/wildos-store/qml/components/FilterPill.qml b/packages/wildos-store/qml/components/FilterPill.qmlindex 2c6643f..0978cb3 100644--- a/packages/wildos-store/qml/components/FilterPill.qml+++ b/packages/wildos-store/qml/components/FilterPill.qml@@ -2,13 +2,14 @@ import QtQuickimport QtQuick.Templates as Timport WildOS.UI as UI-// A category to filter by: the chip shape, accent when picked.+// A filter at the top of a category: a 32px pill, filled with the accent+// when picked.T.AbstractButton {id: pillproperty bool selected: false- implicitWidth: label.implicitWidth + 28+ implicitWidth: label.implicitWidth + 30implicitHeight: Math.max(32, Math.ceil(label.implicitHeight) + 12)hoverEnabled: truefocusPolicy: Qt.TabFocus@@ -18,9 +19,8 @@ T.AbstractButton {background: Rectangle {radius: height / 2- color: pill.selected ? UI.Style.accentChip : pill.down ? UI.Style.surfacePressed : pill.hovered ? UI.Style.surfaceHover : Metrics.chip- border.width: pill.selected ? 1 : 0- border.color: UI.Style.accentBorder+ color: pill.selected ? (pill.hovered ? UI.Style.accentHover : UI.Style.accent)+ : pill.hovered || pill.down ? Metrics.buttonFill : Metrics.pillBehavior on color {ColorAnimation { duration: UI.Style.hoverDuration }}@@ -35,7 +35,8 @@ T.AbstractButton {id: labelhorizontalAlignment: Text.AlignHCentertext: pill.text- font.weight: Font.Medium- color: pill.selected ? UI.Style.accentText : Metrics.inkBody+ size: 13.5+ font.weight: pill.selected ? Font.DemiBold : Font.Medium+ color: pill.selected ? UI.Style.textOnAccent : UI.Style.ink}}diff --git a/packages/wildos-store/qml/components/HeroCard.qml b/packages/wildos-store/qml/components/HeroCard.qmlnew file mode 100644index 0000000..f11ebfb--- /dev/null+++ b/packages/wildos-store/qml/components/HeroCard.qml@@ -0,0 +1,180 @@+import QtQuick+import QtQuick.Effects+import QtQuick.Templates as T+import WildOS.Store+import WildOS.UI as UI++// The boards' feature card: a photograph, or the deep navy card it falls+// back to, darkened towards the bottom, with app icons at the top and an+// eyebrow, a title and a line of text at the bottom in white.+T.AbstractButton {+ id: card++ property string eyebrow+ property string title+ property string body+ property var keys: []+ property url photo+ // Where the photograph is cropped, as CSS object-position's second+ // value: 0 keeps the top, 1 the bottom.+ property real photoY: 0.5+ property bool iconsRight: false+ property real iconSize: 50+ property real titleSize: 20+ property real bodySize: 13+ property real shadeStrength: 0.75+ // Busy photographs on the small cards: the shade runs from the left,+ // under the text, rather than up from the bottom.+ property bool shadeFromLeft: false++ implicitHeight: 154+ hoverEnabled: true+ focusPolicy: Qt.TabFocus+ Accessible.role: Accessible.Button+ Accessible.name: title + ". " + body++ background: Item {+ Item {+ id: art+ anchors.fill: parent+ visible: false+ layer.enabled: true++ Rectangle {+ anchors.fill: parent+ color: Metrics.heroBase+ }++ Image {+ id: photoImage+ visible: card.photo.toString().length > 0+ readonly property real aspect: implicitHeight > 0 ? implicitWidth / implicitHeight : 1.5+ width: Math.max(parent.width, parent.height * aspect)+ height: width / aspect+ x: (parent.width - width) / 2+ y: -(height - parent.height) * card.photoY+ source: card.photo+ sourceSize.width: 2000+ asynchronous: true+ }++ Rectangle {+ anchors.fill: parent+ visible: card.shadeFromLeft+ gradient: Gradient {+ orientation: Gradient.Horizontal+ GradientStop { position: 0.0; color: Qt.rgba(8 / 255, 10 / 255, 24 / 255, 0.9) }+ GradientStop { position: 0.75; color: Qt.rgba(8 / 255, 10 / 255, 24 / 255, 0.1) }+ }+ }++ Rectangle {+ anchors.fill: parent+ visible: !card.shadeFromLeft+ gradient: Gradient {+ GradientStop { position: 0.3; color: Qt.rgba(8 / 255, 10 / 255, 24 / 255, 0) }+ GradientStop { position: 1.0; color: Qt.rgba(8 / 255, 10 / 255, 24 / 255, card.shadeStrength) }+ }+ }++ Rectangle {+ anchors.fill: parent+ color: card.down ? Qt.rgba(1, 1, 1, 0.04) : card.hovered ? Qt.rgba(1, 1, 1, 0.03) : "transparent"+ Behavior on color {+ ColorAnimation { duration: UI.Style.hoverDuration }+ }+ }+ }++ Rectangle {+ id: mask+ anchors.fill: parent+ radius: Metrics.radiusHero+ visible: false+ layer.enabled: true+ }++ MultiEffect {+ anchors.fill: parent+ source: art+ maskEnabled: true+ maskSource: mask+ maskThresholdMin: 0.5+ maskSpreadAtMin: 1.0+ }++ UI.FocusRing {+ visible: card.visualFocus+ targetRadius: Metrics.radiusHero+ }+ }++ contentItem: Item {+ Row {+ id: icons+ x: card.iconsRight ? parent.width - width - 20 : 24+ y: card.iconsRight ? 18 : 22+ spacing: card.iconsRight ? 10 : 12+ layer.enabled: true+ layer.effect: MultiEffect {+ shadowEnabled: true+ shadowColor: Qt.rgba(0, 0, 0, 0.35)+ shadowVerticalOffset: 10+ shadowBlur: 0.6+ blurMax: 24+ }++ Repeater {+ model: card.keys++ AppIcon {+ required property string modelData+ readonly property var app: Catalog.app(modelData)+ size: card.iconSize+ source: app ? app.iconSource : ""+ }+ }+ }++ Column {+ x: 24+ width: parent.width - 48+ anchors.bottom: parent.bottom+ anchors.bottomMargin: 22+ spacing: 6++ UI.Label {+ visible: card.eyebrow.length > 0+ text: card.eyebrow.toUpperCase()+ size: 11.5+ font.weight: Font.Bold+ font.letterSpacing: 0.92+ color: Metrics.onPhotoAlpha(0.75)+ }++ UI.Label {+ width: parent.width+ text: card.title+ size: card.titleSize+ font.weight: Font.Bold+ font.letterSpacing: -0.015 * card.titleSize+ lineHeight: 1.15+ color: Metrics.onPhoto+ wrapMode: Text.Wrap+ elide: Text.ElideNone+ Accessible.role: Accessible.Heading+ }++ UI.Label {+ visible: card.body.length > 0+ width: parent.width+ text: card.body+ size: card.bodySize+ lineHeight: 1.4+ color: Metrics.onPhotoAlpha(0.8)+ wrapMode: Text.Wrap+ elide: Text.ElideNone+ }+ }+ }+}diff --git a/packages/wildos-store/qml/components/InfoRow.qml b/packages/wildos-store/qml/components/InfoRow.qmldeleted file mode 100644index 921eccf..0000000--- a/packages/wildos-store/qml/components/InfoRow.qml+++ /dev/null@@ -1,77 +0,0 @@-import QtQuick-import WildOS.UI as UI--// One row in a RowGroup: a 14px title, an optional 12px line under it, and-// whatever controls are given on the right.-Item {- id: row-- property string title- property string subtitle- property int minHeight: 62- property bool warning: false- property bool last: false- default property alias trailing: trailingRow.data-- width: parent ? parent.width : implicitWidth- implicitHeight: visible ? Math.max(minHeight, texts.implicitHeight + 20) : 0- height: implicitHeight-- Rectangle {- anchors.fill: parent- visible: row.warning- color: UI.Style.warningSoft- }-- UI.Icon {- id: warnIcon- visible: row.warning- x: 18- anchors.verticalCenter: parent.verticalCenter- name: "warning"- size: 18- color: UI.Style.warning- }-- Column {- id: texts- x: row.warning ? 18 + 18 + 14 : 18- anchors.verticalCenter: parent.verticalCenter- width: parent.width - x - 18 - (trailingRow.implicitWidth > 0 ? trailingRow.implicitWidth + 16 : 0)- spacing: 2-- UI.Label {- width: parent.width- text: row.title- size: 14- wrapMode: Text.Wrap- elide: Text.ElideNone- }-- UI.Label {- visible: row.subtitle.length > 0- width: parent.width- text: row.subtitle- size: 12- color: UI.Style.inkMuted- wrapMode: Text.Wrap- elide: Text.ElideNone- }- }-- Row {- id: trailingRow- anchors.right: parent.right- anchors.rightMargin: 18- height: parent.height- spacing: 16- }-- Rectangle {- visible: !row.last- anchors.bottom: parent.bottom- width: parent.width- height: 1- color: UI.Style.divider- }-}diff --git a/packages/wildos-store/qml/components/InstallButton.qml b/packages/wildos-store/qml/components/InstallButton.qmldeleted file mode 100644index 3daf3bb..0000000--- a/packages/wildos-store/qml/components/InstallButton.qml+++ /dev/null@@ -1,50 +0,0 @@-import QtQuick-import WildOS.UI as UI--// The one action a card or row offers for an app: Install, Update or Open,-// turning into progress while something is happening to it.-Item {- id: root-- property var app- property string size: "small"-- signal opened()-- readonly property bool working: app && (app.busy || app.queued)-- implicitWidth: working ? pill.implicitWidth : button.implicitWidth- implicitHeight: Math.max(button.implicitHeight, working ? pill.implicitHeight : 0)-- ProgressPill {- id: pill- anchors.fill: parent- visible: root.working- app: root.app- fontSize: button.fontSize- }-- UI.Button {- id: button- anchors.fill: parent- visible: !root.working- size: root.size- kind: !root.app || !root.app.installed || root.app.updateAvailable ? "primary" : "secondary"- // An app with no catalogue left to install it from cannot install.- enabled: root.app && (root.app.installed ? root.app.updateAvailable || root.app.canOpen : root.app.source.length > 0)- text: !root.app ? "Install"- : !root.app.installed ? "Install"- : root.app.updateAvailable ? "Update"- : root.app.canOpen ? "Open" : "Installed"- Accessible.name: root.app ? text + " " + root.app.name : text- onClicked: {- if (!root.app.installed) {- root.app.install();- } else if (root.app.updateAvailable) {- root.app.update();- } else if (root.app.open()) {- root.opened();- }- }- }-}diff --git a/packages/wildos-store/qml/components/Metrics.qml b/packages/wildos-store/qml/components/Metrics.qmlindex 65b0f93..261457b 100644--- a/packages/wildos-store/qml/components/Metrics.qml+++ b/packages/wildos-store/qml/components/Metrics.qml@@ -3,37 +3,92 @@ pragma Singletonimport QtQuickimport WildOS.UI as UI-// The Store's layout from Store.dc.html and StoreApp.dc.html, and the few-// colours only its pages use. Every colour comes from WildOS.UI tokens, so-// the accent, the text size and light mode reach the Store with the rest of+// The Store's layout and colours from the StoreDiscover to StoreStates+// boards. Colours are WildOS.UI tokens at the boards' strengths, so the+// accent, the text size and light mode reach the Store with the rest of// the system.QtObject {- readonly property int titleBarHeight: 52- readonly property int navWidth: 200- readonly property int contentLeft: 12- readonly property int contentRight: 32- readonly property int contentTop: 6+ readonly property int navWidth: 248+ readonly property int topBarHeight: 46+ readonly property int sidePadding: 44+ readonly property int pageTop: 4readonly property int sectionGap: 26+ readonly property int columnGap: 34readonly property int radiusHero: 16+ readonly property int radiusCard: 14- // Body copy and card captions sit between ink and muted ink.- readonly property color inkBody: UI.Style.inkAlpha(0.85, 0.80)- readonly property color inkSub: UI.Style.inkAlpha(0.82, 0.76)- readonly property color inkCard: UI.Style.inkAlpha(0.75, 0.70)- readonly property color chip: UI.Style.tone(0.07)+ // The boards' three strengths of text: ink, 62% and 40%.+ readonly property color inkSecondary: UI.Style.inkAlpha(0.62, 0.68)+ readonly property color inkTertiary: UI.Style.inkAlpha(0.40, 0.52)+ readonly property color inkDim: UI.Style.inkAlpha(0.35, 0.42)+ readonly property color divider: UI.Style.tone(0.08)+ readonly property color sidebar: UI.Style.tone(0.03)+ readonly property color card: UI.Style.tone(0.045)+ readonly property color privacyCard: UI.Style.tone(0.04)+ readonly property color buttonFill: UI.Style.tone(0.10)+ readonly property color buttonHover: UI.Style.tone(0.14)+ readonly property color buttonPressed: UI.Style.tone(0.18)+ readonly property color pill: UI.Style.tone(0.07)+ readonly property color rowHover: UI.Style.tone(0.05)+ readonly property color iconWell: UI.Style.tone(0.07)+ readonly property color ringTrack: UI.Style.tone(0.16)+ readonly property color navSelected: UI.Style.accentAlpha(0.16, 0.13)+ readonly property color danger: UI.Style.dark ? "#ff9a8a" : UI.Style.danger+ readonly property color success: UI.Style.dark ? "#5fd39a" : UI.Style.successreadonly property color iconTile: UI.Style.surfaceControl- readonly property color tileHover: UI.Style.tone(0.075)- readonly property color warningBorder: Qt.rgba(UI.Style.warning.r, UI.Style.warning.g, UI.Style.warning.b, 0.30)+ readonly property color dialog: UI.Style.dark ? "#1b2138" : UI.Style.windowOpaque- // The hero banner is a photograph in either scheme: white words and a- // navy shade over it, and an eyebrow in the accent lifted most of the- // way to white (Glacier gives #dbe6ff).+ // Hero cards are photographs or, without one, a deep navy card in+ // either scheme, so their words stay white.+ readonly property color heroBase: "#1a2140"readonly property color onPhoto: UI.Style.inkOnWallpaperfunction onPhotoAlpha(alpha) {return Qt.rgba(onPhoto.r, onPhoto.g, onPhoto.b, alpha);}- readonly property color heroShade: Qt.rgba(Qt.darker(UI.Style.lakeNavy, 2.4).r, Qt.darker(UI.Style.lakeNavy, 2.4).g, Qt.darker(UI.Style.lakeNavy, 2.4).b, 0.48)- readonly property color eyebrow: Qt.rgba(UI.Style.systemAccent.r + (1 - UI.Style.systemAccent.r) * 0.7, UI.Style.systemAccent.g + (1 - UI.Style.systemAccent.g) * 0.7, UI.Style.systemAccent.b + (1 - UI.Style.systemAccent.b) * 0.7, 1)// Full-size screenshots sit on a deep shade, darker than a dialog's.readonly property color viewerShade: Qt.rgba(UI.Style.scrim.r, UI.Style.scrim.g, UI.Style.scrim.b, 0.8)++ // Line icons the boards draw that WildOS.UI has no shape for, on the+ // same 24px grid. Anything else comes from UI.Icons.+ readonly property var icons: ({+ "discover": "M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8zM19 15l.8 2.2L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-.8z",+ "swap-windows": "M4 8h14l-3-3M20 16H6l3 3",+ "create": "M18.5 3.5a2.1 2.1 0 0 1 3 3L12 16l-4-4zM8 12c-3 0-4 2-4 4s-1 3-2 4c4 0 8-1 8-4",+ "work": "M3 7h18v13H3zM8 7V4h8v3M3 12h18",+ "play": "M6 8h12a4 4 0 0 1 4 4v2a3 3 0 0 1-5.2 2L15 14H9l-1.8 2A3 3 0 0 1 2 14v-2a4 4 0 0 1 4-4zM7 10.5v3M5.5 12h3M16 11h.01M18 13h.01",+ "develop": "M8 7l-5 5 5 5M16 7l5 5-5 5M14 4l-4 16",+ "categories": "M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4zM14 14h6v6h-6z",+ "windows-apps": "M3 4h18v16H3zM3 9h18M6 6.5h.01M8.5 6.5h.01",+ "updates": "M20 11a8 8 0 1 0-2.3 5.7M20 4v7h-7",+ "library": "M12 4v11M7 10l5 5 5-5M5 20h14",+ "private": "M3 3l18 18M10.6 6.1A9.8 9.8 0 0 1 12 6c6 0 9.5 6 9.5 6a17 17 0 0 1-3 3.6M6.3 7.6A16.6 16.6 0 0 0 2.5 12S6 18 12 18a9 9 0 0 0 4-.9M9.9 10a3 3 0 0 0 4.2 4.2",+ "tick": "M5 12l5 5L20 7",+ "reach-file": "M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",+ "reach-image": "M3 5h18v14H3zM3 16l5-5 4 4 3-3 6 6",+ "reach-printer": "M6 9V3h12v6M6 18H4v-7h16v7h-2M6 14h12v7H6z",+ "reach-globe": "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM3 12h18M12 3c2.5 2.5 3.5 5.5 3.5 9s-1 6.5-3.5 9c-2.5-2.5-3.5-5.5-3.5-9s1-6.5 3.5-9z",+ "reach-camera": "M3 7h12v10H3zM15 10l6-3v10l-6-3",+ "reach-location": "M12 21s-7-6-7-11a7 7 0 0 1 14 0c0 5-7 11-7 11zM12 12a2 2 0 1 0 0-4 2 2 0 0 0 0 4z",+ "reach-screen": "M3 4h18v12H3zM8 20h8M12 16v4",+ "retry": "M20 11a8 8 0 1 0-2.3 5.7M20 4v7h-7"+ })++ // What StoreApp calls each thing an app can reach, as icon names.+ readonly property var reachIcons: ({+ "file": "reach-file",+ "folder": "folder",+ "home": "home",+ "drive": "drive",+ "image": "reach-image",+ "music": "music",+ "film": "videos",+ "download": "download",+ "desktop": "reach-screen",+ "gpu": "chip",+ "camera": "reach-camera",+ "mic": "mic",+ "printer": "reach-printer",+ "globe": "reach-globe",+ "location": "reach-location"+ })}diff --git a/packages/wildos-store/qml/components/NavItem.qml b/packages/wildos-store/qml/components/NavItem.qmlindex 6164e75..c7e190a 100644--- a/packages/wildos-store/qml/components/NavItem.qml+++ b/packages/wildos-store/qml/components/NavItem.qml@@ -2,43 +2,36 @@ import QtQuickimport QtQuick.Templates as Timport WildOS.UI as UI-// A Store section in the left column: 38px, 17px line icon, 13px label. The-// current one gets the selected fill, a short accent bar and an accent icon.+// A section in the Store's sidebar: 34px, a 17px line icon, 14px name. The+// current one gets the accent wash, an accent icon and a bolder name.+// Updates carries a count; Library a small ring while apps install.T.AbstractButton {id: itemproperty string iconNameproperty bool current: falseproperty int badge: 0+ property bool working: false- implicitHeight: Math.max(38, Math.ceil(label.implicitHeight) + 16)- // Read by the window, which widens the column to fit the longest name.- implicitWidth: 12 + 17 + 12 + Math.ceil(label.implicitWidth) + 12 + (badge > 0 ? badgePill.width + 12 : 0)+ implicitHeight: Math.max(34, Math.ceil(label.implicitHeight) + 14)+ // Read by the window, which widens the sidebar to fit the longest name.+ implicitWidth: 10 + 17 + 11 + Math.ceil(label.implicitWidth) + 10 + (badge > 0 ? badgePill.width + 11 : working ? 29 : 0)width: parent ? parent.width : implicitWidthhoverEnabled: truefocusPolicy: Qt.TabFocusAccessible.role: Accessible.PageTab- Accessible.name: badge > 0 ? text + ", " + badge : text+ Accessible.name: badge > 0 ? text + ", " + badge : working ? text + ", installing" : textAccessible.selected: currentbackground: Rectangle {radius: UI.Style.radiusSm- color: item.down ? UI.Style.surfacePressed- : item.hovered ? UI.Style.surfaceHover- : item.current ? UI.Style.surfaceSelected : "transparent"+ color: item.current ? Metrics.navSelected+ : item.down ? Metrics.pill+ : item.hovered ? Metrics.rowHover : "transparent"Behavior on color {ColorAnimation { duration: UI.Style.hoverDuration }}- Rectangle {- visible: item.current- anchors.verticalCenter: parent.verticalCenter- width: 3- height: 16- radius: 2- color: UI.Style.accent- }-UI.FocusRing {visible: item.visualFocustargetRadius: UI.Style.radiusSm@@ -46,32 +39,33 @@ T.AbstractButton {}contentItem: Item {- UI.Icon {+ StoreIcon {id: icon- x: 12+ x: 10anchors.verticalCenter: parent.verticalCentername: item.iconNamesize: 17- strokeWidth: item.current ? 1.9 : 1.8- color: item.current ? UI.Style.accent : UI.Style.iconInk+ strokeWidth: 1.8+ color: item.current ? UI.Style.accent : Metrics.inkSecondary}UI.Label {id: labelanchors.left: icon.right- anchors.leftMargin: 12- anchors.right: badgePill.visible ? badgePill.left : parent.right- anchors.rightMargin: 12+ anchors.leftMargin: 11+ anchors.right: badgePill.visible ? badgePill.left : ring.visible ? ring.left : parent.right+ anchors.rightMargin: 10anchors.verticalCenter: parent.verticalCentertext: item.text- font.weight: item.current ? Font.DemiBold : Font.Normal+ size: 14+ font.weight: item.current ? Font.DemiBold : Font.Medium}Rectangle {id: badgePillvisible: item.badge > 0anchors.right: parent.right- anchors.rightMargin: 12+ anchors.rightMargin: 10anchors.verticalCenter: parent.verticalCenterwidth: Math.max(20, badgeText.implicitWidth + 12)height: 20@@ -82,10 +76,21 @@ T.AbstractButton {id: badgeTextanchors.centerIn: parenttext: item.badge > 99 ? "99+" : item.badge- size: 11+ size: 11.5font.weight: Font.Boldcolor: UI.Style.textOnAccent}}++ Ring {+ id: ring+ visible: item.working && !badgePill.visible+ anchors.right: parent.right+ anchors.rightMargin: 11+ anchors.verticalCenter: parent.verticalCenter+ size: 18+ mode: "spin"+ centre: "stop"+ }}}diff --git a/packages/wildos-store/qml/components/PageFlick.qml b/packages/wildos-store/qml/components/PageFlick.qmlindex f65710a..d557e7c 100644--- a/packages/wildos-store/qml/components/PageFlick.qml+++ b/packages/wildos-store/qml/components/PageFlick.qml@@ -3,8 +3,8 @@ import QtQuick.Controlsimport QtQuick.Layoutsimport WildOS.UI as UI-// The scrolling body of a page, with the design's content padding (6px top,-// 12px left, 32px right) and 26px between sections.+// The scrolling body of a page, with the boards' padding (4px top, 44px+// each side) and 26px between sections.Flickable {id: flick@@ -12,16 +12,16 @@ Flickable {property alias spacing: column.spacingcontentWidth: width- contentHeight: column.implicitHeight + Metrics.contentTop + 28+ contentHeight: column.implicitHeight + Metrics.pageTop + 32clip: trueboundsBehavior: Flickable.StopAtBoundsScrollBar.vertical: UI.ScrollBar {}ColumnLayout {id: column- x: Metrics.contentLeft- y: Metrics.contentTop- width: flick.width - Metrics.contentLeft - Metrics.contentRight+ x: Metrics.sidePadding+ y: Metrics.pageTop+ width: flick.width - 2 * Metrics.sidePaddingspacing: Metrics.sectionGap}}diff --git a/packages/wildos-store/qml/components/PageTitle.qml b/packages/wildos-store/qml/components/PageTitle.qmlindex 8d6c8cc..a5c145a 100644--- a/packages/wildos-store/qml/components/PageTitle.qml+++ b/packages/wildos-store/qml/components/PageTitle.qml@@ -2,37 +2,43 @@ import QtQuickimport QtQuick.Layoutsimport WildOS.UI as UI-// A page heading with an optional line under it and actions at the right.+// A page's 32px bold title, an optional line under it, and anything given+// (a button, filter pills) at the right, level with the bottom of the text.Item {id: headerproperty string titleproperty string subtitledefault property alias actions: actionRow.data+ // Pills too wide to sit beside the title go under it instead.+ readonly property bool stacked: actionRow.implicitWidth > 0 && textColumn.titleWidth + actionRow.implicitWidth + 32 > widthLayout.fillWidth: true- implicitHeight: Math.max(textColumn.implicitHeight, actionRow.implicitHeight)+ implicitHeight: stacked ? textColumn.implicitHeight + 16 + actionRow.implicitHeight : Math.max(textColumn.implicitHeight, actionRow.implicitHeight)Column {id: textColumn- width: parent.width - actionRow.implicitWidth - 24- spacing: 6+ readonly property real titleWidth: Math.max(titleLabel.implicitWidth, subtitleLabel.visible ? subtitleLabel.implicitWidth : 0)+ width: header.stacked || actionRow.implicitWidth === 0 ? parent.width : Math.min(titleWidth, parent.width - actionRow.implicitWidth - 32)+ spacing: 4UI.Label {+ id: titleLabelwidth: parent.widthtext: header.title- size: 28- font.weight: Font.DemiBold- font.letterSpacing: -0.28+ size: 32+ font.weight: Font.Bold+ font.letterSpacing: -0.64Accessible.role: Accessible.Heading}UI.Label {+ id: subtitleLabelvisible: header.subtitle.length > 0width: parent.widthtext: header.subtitle- size: 14- color: Metrics.inkSub+ size: 15+ color: Metrics.inkSecondarywrapMode: Text.Wrapelide: Text.ElideNone}@@ -40,8 +46,8 @@ Item {Row {id: actionRow- anchors.right: parent.right- anchors.verticalCenter: textColumn.verticalCenter- spacing: 10+ x: header.stacked ? 0 : header.width - width+ y: header.stacked ? textColumn.implicitHeight + 16 : textColumn.implicitHeight - height+ spacing: 8}}diff --git a/packages/wildos-store/qml/components/PillButton.qml b/packages/wildos-store/qml/components/PillButton.qmlnew file mode 100644index 0000000..d81e996--- /dev/null+++ b/packages/wildos-store/qml/components/PillButton.qml@@ -0,0 +1,43 @@+import QtQuick+import QtQuick.Templates as T+import WildOS.UI as UI++// The boards' pill for actions that are not an app's own button ("Update+// all", "Windows app settings"): 28px with accent words on a light tint,+// or `big` and `filled` in the accent.+T.Button {+ id: control++ property bool big: false+ property bool filled: false++ implicitWidth: Math.max(big ? 84 : 66, Math.ceil(label.implicitWidth) + (big ? 44 : 32))+ implicitHeight: Math.max(big ? 34 : 28, Math.ceil(label.implicitHeight) + 10)+ hoverEnabled: true+ focusPolicy: Qt.StrongFocus+ Accessible.name: text++ background: Rectangle {+ radius: height / 2+ color: !control.enabled ? Metrics.buttonFill+ : control.filled ? (control.down ? UI.Style.accentPressed : control.hovered ? UI.Style.accentHover : UI.Style.accent)+ : control.down ? Metrics.buttonPressed : control.hovered ? Metrics.buttonHover : Metrics.buttonFill+ Behavior on color {+ ColorAnimation { duration: UI.Style.hoverDuration }+ }++ UI.FocusRing {+ visible: control.visualFocus+ targetRadius: parent.radius+ }+ }++ contentItem: UI.Label {+ id: label+ horizontalAlignment: Text.AlignHCenter+ text: control.text+ size: control.big ? 14 : 13+ font.weight: Font.Bold+ color: !control.enabled ? Metrics.inkDim : control.filled ? UI.Style.textOnAccent : UI.Style.accent+ }+}diff --git a/packages/wildos-store/qml/components/ProgressPill.qml b/packages/wildos-store/qml/components/ProgressPill.qmldeleted file mode 100644index b581862..0000000--- a/packages/wildos-store/qml/components/ProgressPill.qml+++ /dev/null@@ -1,92 +0,0 @@-import QtQuick-import WildOS.UI as UI--// Takes the place of an app's button while it installs, updates or is-// removed: the button's own shape, filling with the accent as it goes, with-// the step and percentage written on it.-Rectangle {- id: pill-- property var app- property int fontSize: 12-- readonly property bool known: app && app.progress >= 0- readonly property string label: {- if (!app) {- return "";- }- if (app.queued) {- return "Waiting";- }- const pct = known ? " " + app.progress + "%" : "";- if (app.phase === "auth") {- return "Waiting for password";- }- if (app.action === "remove") {- return "Removing" + pct;- }- if (app.action === "update") {- return "Updating" + pct;- }- if (app.phase === "download") {- return "Downloading" + pct;- }- if (app.phase === "install") {- return "Installing" + pct;- }- return known && app.progress > 0 ? "Installing" + pct : "Getting ready";- }-- implicitWidth: Math.max(120, text.implicitWidth + 32)- implicitHeight: Math.max(32, Math.ceil(text.implicitHeight) + 12)- radius: UI.Style.radiusSm- color: UI.Style.surfaceControl- border.width: 1- border.color: UI.Style.accentBorderStrong- clip: true- Accessible.role: Accessible.ProgressBar- Accessible.name: label-- Rectangle {- id: fill- visible: pill.known- x: 1- y: 1- height: parent.height - 2- radius: pill.radius - 1- width: Math.max(0, (parent.width - 2) * (pill.app ? pill.app.progress : 0) / 100)- color: UI.Style.accentSelected- Behavior on width {- NumberAnimation { duration: 250; easing.type: Easing.OutCubic }- }- }-- // Before PackageKit or Flathub know how much there is to do, a short- // band sweeps across instead of a stalled bar.- Rectangle {- id: sweep- visible: !pill.known && pill.app && !pill.app.queued- y: 1- height: parent.height - 2- width: parent.width * 0.35- radius: pill.radius - 1- color: UI.Style.accentSelected- NumberAnimation on x {- running: sweep.visible- loops: Animation.Infinite- from: -sweep.width- to: pill.width- duration: 1300- easing.type: Easing.InOutQuad- }- }-- UI.Label {- id: text- anchors.centerIn: parent- text: pill.label- size: pill.fontSize- font.weight: Font.DemiBold- font.features: { "tnum": 1 }- }-}diff --git a/packages/wildos-store/qml/components/ReachCard.qml b/packages/wildos-store/qml/components/ReachCard.qmlnew file mode 100644index 0000000..865f8f4--- /dev/null+++ b/packages/wildos-store/qml/components/ReachCard.qml@@ -0,0 +1,96 @@+import QtQuick+import QtQuick.Layouts+import WildOS.UI as UI++// One of the cards under "What it can reach": a tinted badge and a title,+// then a line per thing with its icon, or a sentence instead.+Rectangle {+ id: card++ property string title+ property string iconName+ property color tint: UI.Style.accent+ // Each {icon, label} from StoreApp, or {tick: true, label}.+ property var rows: []+ property string text++ Layout.fillWidth: true+ Layout.preferredWidth: 1+ Layout.alignment: Qt.AlignTop+ implicitHeight: column.implicitHeight + 36+ radius: Metrics.radiusCard+ color: Metrics.card++ Column {+ id: column+ x: 20+ y: 18+ width: parent.width - 40+ spacing: 12++ Row {+ width: parent.width+ spacing: 10++ Rectangle {+ id: badge+ width: 32+ height: 32+ radius: 9+ color: Qt.rgba(card.tint.r, card.tint.g, card.tint.b, 0.13)++ StoreIcon {+ anchors.centerIn: parent+ name: card.iconName+ size: 18+ strokeWidth: 2+ color: card.tint+ }+ }++ UI.Label {+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - badge.width - 10+ text: card.title+ size: 15+ font.weight: Font.Bold+ }+ }++ Repeater {+ model: card.rows++ Row {+ id: line+ required property var modelData+ width: column.width+ spacing: 10++ StoreIcon {+ anchors.verticalCenter: parent.verticalCenter+ name: line.modelData.tick ? "tick" : (Metrics.reachIcons[line.modelData.icon] || "shield")+ size: 16+ color: Metrics.inkSecondary+ }++ UI.Label {+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - 26+ text: line.modelData.label+ size: 13.5+ }+ }+ }++ UI.Label {+ visible: card.text.length > 0+ width: parent.width+ text: card.text+ size: 13.5+ lineHeight: 1.45+ color: Metrics.inkSecondary+ wrapMode: Text.Wrap+ elide: Text.ElideNone+ }+ }+}diff --git a/packages/wildos-store/qml/components/Ring.qml b/packages/wildos-store/qml/components/Ring.qmlnew file mode 100644index 0000000..d42c569--- /dev/null+++ b/packages/wildos-store/qml/components/Ring.qml@@ -0,0 +1,131 @@+import QtQuick+import QtQuick.Shapes+import WildOS.UI as UI++// The Store's progress ring from StoreStates.dc.html, drawn on the board's+// 28px grid (radius 11.5, 2.4 stroke) at any size. "dashed" is waiting in+// the queue, "progress" fills with `progress`, "spin" is an open arc that+// turns while the amount of work is unknown, "paused" holds the filled+// part in muted ink. `centre` puts the stop square or the play triangle in+// the middle.+Item {+ id: ring++ property string mode: "progress"+ property real progress: 0+ property string centre: "none"+ property real size: 28+ property color color: UI.Style.accent+ property color trackColor: Metrics.ringTrack++ readonly property real k: size / 28+ readonly property bool turning: (mode === "spin" || mode === "dashed") && visible && opacity > 0+ // The board's open arc is 20.2 of the 72.3 circumference.+ readonly property real spinSweep: 100++ property real shown: progress+ Behavior on shown {+ enabled: !UI.Style.reducedMotion+ NumberAnimation { duration: 600; easing.type: Easing.OutCubic }+ }++ implicitWidth: size+ implicitHeight: size++ // A filling ring always starts from the top, wherever the arc had+ // turned to.+ onTurningChanged: if (!turning) turner.rotation = 0++ Item {+ id: turner+ anchors.fill: parent++ // The queue's dotted ring: the board's 2.2 on, 3.2 off around the+ // 72.3 circumference, as thirteen short dashes.+ Repeater {+ model: ring.mode === "dashed" ? 13 : 0++ Rectangle {+ required property int index+ readonly property real angle: index * 2 * Math.PI / 13+ width: 2.4 * ring.k+ height: 2.2 * ring.k+ x: ring.size / 2 + 11.5 * ring.k * Math.sin(angle) - width / 2+ y: ring.size / 2 - 11.5 * ring.k * Math.cos(angle) - height / 2+ rotation: index * 360 / 13 + 90+ antialiasing: true+ color: ring.trackColor+ }+ }++ RotationAnimator on rotation {+ running: ring.turning+ loops: Animation.Infinite+ from: 0+ to: 360+ // The queue ring drifts; the working arc turns about once a+ // second. Reduced motion slows both to a crawl rather than+ // freezing them, so the button still reads as busy.+ duration: (ring.mode === "dashed" ? 9000 : 1100) * (UI.Style.reducedMotion ? 4 : 1)+ }++ Shape {+ anchors.fill: parent+ preferredRendererType: Shape.CurveRenderer++ ShapePath {+ strokeColor: ring.mode === "dashed" ? "transparent" : ring.trackColor+ strokeWidth: 2.4 * ring.k+ fillColor: "transparent"+ PathAngleArc {+ centerX: ring.size / 2+ centerY: ring.size / 2+ radiusX: 11.5 * ring.k+ radiusY: 11.5 * ring.k+ startAngle: 0+ sweepAngle: 360+ }+ }++ ShapePath {+ strokeColor: ring.mode === "dashed" ? "transparent" : ring.mode === "paused" ? Metrics.inkSecondary : ring.color+ strokeWidth: 2.4 * ring.k+ fillColor: "transparent"+ capStyle: ShapePath.RoundCap+ PathAngleArc {+ centerX: ring.size / 2+ centerY: ring.size / 2+ radiusX: 11.5 * ring.k+ radiusY: 11.5 * ring.k+ startAngle: -90+ sweepAngle: ring.mode === "spin" ? ring.spinSweep+ : ring.mode === "dashed" ? 0+ : Math.max(0.5, Math.min(100, ring.shown)) * 3.6+ }+ }+ }+ }++ Rectangle {+ visible: ring.centre === "stop"+ anchors.centerIn: parent+ width: 7 * ring.k+ height: 7 * ring.k+ radius: 1.5 * ring.k+ color: ring.color+ }++ Shape {+ visible: ring.centre === "play"+ anchors.fill: parent+ preferredRendererType: Shape.CurveRenderer++ ShapePath {+ strokeColor: "transparent"+ fillColor: Metrics.inkSecondary+ PathSvg {+ path: "M" + 11.5 * ring.k + " " + 9.5 * ring.k + "l" + 7 * ring.k + " " + 4.5 * ring.k + "l" + -7 * ring.k + " " + 4.5 * ring.k + "z"+ }+ }+ }+}diff --git a/packages/wildos-store/qml/components/RowGroup.qml b/packages/wildos-store/qml/components/RowGroup.qmldeleted file mode 100644index e8b78da..0000000--- a/packages/wildos-store/qml/components/RowGroup.qml+++ /dev/null@@ -1,15 +0,0 @@-import QtQuick-import WildOS.UI as UI--// Rows stacked in one Wild OS card, as the design groups settings and-// facts; the card masks them to its rounded corners.-UI.Card {- id: group-- default property alias rows: column.data-- Column {- id: column- width: group.availableWidth- }-}diff --git a/packages/wildos-store/qml/components/ScreenshotViewer.qml b/packages/wildos-store/qml/components/ScreenshotViewer.qmlindex 3cd5baf..e3d94de 100644--- a/packages/wildos-store/qml/components/ScreenshotViewer.qml+++ b/packages/wildos-store/qml/components/ScreenshotViewer.qml@@ -1,5 +1,7 @@import QtQuickimport QtQuick.Controls+import QtQuick.Window+import WildOS.Storeimport WildOS.UI as UI// Screenshots at full size over the window, with arrows between them.@@ -35,20 +37,45 @@ Popup {Keys.onLeftPressed: viewer.index = Math.max(0, viewer.index - 1)Keys.onRightPressed: viewer.index = Math.min(viewer.shots.length - 1, viewer.index + 1)+ // The size closest to the space it fills, rather than the original,+ // which can be several times larger than any screen.+ function sourceFor(i, w, h) {+ if (i < 0 || i >= viewer.shots.length) {+ return "";+ }+ const dpr = Screen.devicePixelRatio;+ return Catalog.pickImage(viewer.shots[i].images, Math.round(w * dpr), Math.round(h * dpr));+ }+Image {id: biganchors.fill: parentanchors.margins: 56fillMode: Image.PreserveAspectFitasynchronous: true- source: viewer.shots.length > 0 ? viewer.shots[viewer.index].full : ""+ source: viewer.opened ? parent.sourceFor(viewer.index, width, height) : ""}+ // The page's own copy, already on screen, while the larger one loads.Image {anchors.fill: bigfillMode: Image.PreserveAspectFit+ asynchronous: truevisible: big.status !== Image.Ready- source: viewer.shots.length > 0 ? viewer.shots[viewer.index].thumb : ""+ source: viewer.opened ? parent.sourceFor(viewer.index, 391, 220) : ""+ }++ // The pictures either side, fetched while this one is looked at, so+ // the arrows show them at once.+ Repeater {+ model: viewer.opened ? [viewer.index + 1, viewer.index - 1, viewer.index + 2] : []++ Image {+ required property int modelData+ visible: false+ asynchronous: true+ source: parent.sourceFor(modelData, big.width, big.height)+ }}UI.Label {@@ -56,7 +83,7 @@ Popup {anchors.bottom: parent.bottomanchors.bottomMargin: 18text: viewer.shots.length > 0 ? viewer.shots[viewer.index].caption : ""- color: Metrics.inkSub+ color: Metrics.inkSecondary}component ViewerButton: UI.IconButton {diff --git a/packages/wildos-store/qml/components/SectionHeader.qml b/packages/wildos-store/qml/components/SectionHeader.qmlindex a67ce39..c1f919b 100644--- a/packages/wildos-store/qml/components/SectionHeader.qml+++ b/packages/wildos-store/qml/components/SectionHeader.qml@@ -2,35 +2,43 @@ import QtQuickimport QtQuick.Layoutsimport WildOS.UI as UI-// A section title with an optional link at the right, baselines aligned.+// A section's 21px heading with an optional link at the right, over the+// boards' hairline.Item {id: headerproperty string titleproperty string linkText- property int fontSize: 17signal linkClicked()- implicitHeight: heading.implicitHeight+ implicitHeight: heading.implicitHeight + 11Layout.fillWidth: trueUI.Label {id: headingtext: header.title- size: header.fontSize- font.weight: Font.DemiBold+ size: 21+ font.weight: Font.Bold+ font.letterSpacing: -0.21width: parent.width - (link.visible ? link.width + 16 : 0)Accessible.role: Accessible.Heading}- UI.LinkButton {+ StoreLink {id: linkvisible: header.linkText.length > 0anchors.right: parent.rightanchors.rightMargin: -4- y: heading.baselineOffset - contentItem.y - contentItem.baselineOffset+ y: heading.baselineOffset - baselineOffsettext: header.linkTextonClicked: header.linkClicked()}++ Rectangle {+ anchors.bottom: parent.bottom+ width: parent.width+ height: 1+ color: Metrics.divider+ }}diff --git a/packages/wildos-store/qml/components/StoreButton.qml b/packages/wildos-store/qml/components/StoreButton.qmlnew file mode 100644index 0000000..d435872--- /dev/null+++ b/packages/wildos-store/qml/components/StoreButton.qml@@ -0,0 +1,263 @@+import QtQuick+import QtQuick.Templates as T+import QtQuick.Window+import WildOS.UI as UI++// The one button every app has, in each state StoreStates.dc.html draws:+// Get, the waiting, downloading and installing rings, Open, Update,+// Paused, Retry and the greyed Get when space is short. `big` is the app+// page's 34px size, otherwise the 28px list size. In a list the button+// keeps one width whatever its state and sits at the right of it, so rows+// never move while apps install; `showStatus` adds the board's short line+// underneath ("Needs 720 MB free", "Download failed").+T.AbstractButton {+ id: control++ property var app+ property bool big: false+ property bool alignRight: !big+ property bool showStatus: !big+ // A curated line for when there is no status to give ("Opens PSD").+ property string note++ // Turned into Open (or Update, or Installed) from a ring: the app page+ // gives its icon a small bounce.+ signal landed()++ readonly property string realState: app ? app.buttonState : "get"+ // Get answers at once: the ring shows before the Store has queued the+ // job, and the real state takes over as soon as it changes.+ property bool asked: false+ readonly property string shown: asked && (realState === "get" || realState === "retry" || realState === "paused") ? "waiting" : realState+ readonly property bool ring: ["waiting", "preparing", "downloading", "installing", "removing", "paused"].indexOf(shown) >= 0+ readonly property string label: shown === "open" ? "Open"+ : shown === "installed" ? "Installed"+ : shown === "update" ? "Update"+ : shown === "retry" ? "Retry"+ : "Get"++ readonly property int buttonHeight: big ? 34 : 28+ readonly property int minWidth: big ? 84 : 66+ readonly property int sidePadding: big ? 22 : 16+ readonly property real fontSize: big ? 14 : 13+ readonly property real pillWidth: Math.max(minWidth, Math.ceil(labelText.implicitWidth) + 2 * sidePadding + (retryIcon.visible ? retryIcon.width + 6 : 0))+ // The widest the pill gets in a list ("Installed"), so every state+ // fits the same slot.+ readonly property real slotWidth: Math.max(minWidth, Math.ceil(widest.advanceWidth) + 2 * sidePadding)++ implicitWidth: alignRight ? Math.max(slotWidth, pillWidth, statusLabel.visible ? Math.ceil(statusLabel.implicitWidth) : 0) : (ring ? minWidth : pillWidth)+ implicitHeight: buttonHeight + (statusLabel.visible ? statusLabel.implicitHeight + 3 : 0)+ hoverEnabled: true+ focusPolicy: Qt.TabFocus+ enabled: !!app && ["nospace", "installed", "installing", "removing"].indexOf(shown) < 0+ Accessible.role: ring ? Accessible.ProgressBar : Accessible.Button+ Accessible.name: {+ const name = app ? app.name : "";+ switch (shown) {+ case "waiting": return name + ", waiting to download. Press to cancel.";+ case "preparing": return name + ", getting ready";+ case "downloading": return name + ", downloading, " + app.progress + "%. Press to pause.";+ case "installing": return name + ", installing";+ case "removing": return name + ", uninstalling";+ case "paused": return name + ", paused. Press to carry on.";+ case "nospace": return "Get " + name + ". " + (app ? app.statusLine : "");+ }+ return label + " " + name;+ }++ onRealStateChanged: asked = false++ Timer {+ // Nothing came back (the request was refused at once): show the+ // real state again rather than a ring that never fills.+ running: control.asked+ interval: 5000+ onTriggered: control.asked = false+ }++ property string previous: shown+ onShownChanged: {+ const wasRing = ["waiting", "preparing", "downloading", "installing"].indexOf(previous) >= 0;+ previous = shown;+ // Cancelling back to Get is not an arrival.+ if (wasRing && ["open", "installed", "update"].indexOf(shown) >= 0) {+ if (!UI.Style.reducedMotion) {+ spring.restart();+ }+ landed();+ }+ }++ function act() {+ if (!app) {+ return;+ }+ switch (shown) {+ case "get": {+ const w = control.Window.window;+ if (w && w.requestInstall && w.requestInstall(app)) {+ return;+ }+ asked = true;+ app.install();+ return;+ }+ case "retry":+ case "paused":+ asked = true;+ app.install();+ return;+ case "waiting":+ app.cancel();+ return;+ case "preparing":+ if (app.cancellable) {+ app.cancel();+ }+ return;+ case "downloading":+ app.pause();+ return;+ case "update":+ app.update();+ return;+ case "open":+ app.open();+ return;+ }+ }++ onClicked: act()++ TextMetrics {+ id: widest+ font.family: UI.Style.fontFamily+ font.pixelSize: UI.Style.px(control.fontSize)+ font.weight: Font.Bold+ text: "Installed"+ }++ contentItem: Item {}++ background: Item {+ Item {+ id: pillLayer+ readonly property real centreX: control.alignRight ? control.width - control.pillWidth / 2 : control.pillWidth / 2+ x: control.alignRight ? control.width - control.pillWidth : 0+ width: control.pillWidth+ height: control.buttonHeight+ opacity: control.ring ? 0 : 1+ transformOrigin: Item.Center+ Behavior on opacity {+ NumberAnimation { duration: UI.Style.hoverDuration }+ }++ NumberAnimation {+ id: spring+ target: pillLayer+ property: "scale"+ from: 0.72+ to: 1+ duration: 420+ easing.type: Easing.OutBack+ easing.overshoot: 2.4+ }++ Rectangle {+ id: pill+ anchors.fill: parent+ radius: height / 2+ readonly property bool filled: control.big && control.shown === "get"+ readonly property bool live: ["get", "open", "update", "retry"].indexOf(control.shown) >= 0+ color: filled ? (control.down ? UI.Style.accentPressed : control.hovered ? UI.Style.accentHover : UI.Style.accent)+ : live && control.down ? Metrics.buttonPressed+ : live && control.hovered ? Metrics.buttonHover+ : Metrics.buttonFill+ Behavior on color {+ ColorAnimation { duration: UI.Style.hoverDuration }+ }++ UI.FocusRing {+ visible: control.visualFocus && !control.ring+ targetRadius: pill.radius+ }+ }++ Row {+ anchors.centerIn: parent+ spacing: 6++ StoreIcon {+ id: retryIcon+ visible: control.shown === "retry"+ anchors.verticalCenter: parent.verticalCenter+ name: "retry"+ size: control.big ? 15 : 13+ strokeWidth: 2.2+ color: Metrics.danger+ }++ UI.Label {+ id: labelText+ anchors.verticalCenter: parent.verticalCenter+ text: control.label+ size: control.fontSize+ font.weight: Font.Bold+ color: pill.filled ? UI.Style.textOnAccent+ : control.shown === "retry" ? Metrics.danger+ : control.shown === "nospace" ? Metrics.inkDim+ : control.shown === "installed" ? Metrics.inkTertiary+ : UI.Style.accent+ }+ }+ }++ Item {+ id: ringLayer+ x: control.alignRight ? control.width - control.minWidth : 0+ width: control.minWidth+ height: control.buttonHeight+ opacity: control.ring ? 1 : 0+ visible: opacity > 0+ Behavior on opacity {+ NumberAnimation { duration: UI.Style.hoverDuration }+ }++ Rectangle {+ anchors.centerIn: parent+ width: control.buttonHeight + 6+ height: width+ radius: width / 2+ readonly property bool live: ["waiting", "preparing", "downloading", "paused"].indexOf(control.shown) >= 0+ color: live && control.down ? Metrics.buttonFill : live && control.hovered ? Metrics.rowHover : "transparent"++ UI.FocusRing {+ visible: control.visualFocus && control.ring+ targetRadius: parent.radius+ }+ }++ Ring {+ anchors.centerIn: parent+ size: control.buttonHeight+ mode: control.shown === "waiting" ? "dashed"+ : control.shown === "downloading" ? "progress"+ : control.shown === "paused" ? "paused"+ : "spin"+ progress: control.app ? Math.max(0, control.app.progress) : 0+ centre: control.shown === "downloading" || control.shown === "preparing" ? "stop"+ : control.shown === "paused" ? "play" : "none"+ }+ }++ UI.Label {+ id: statusLabel+ visible: control.showStatus && text.length > 0+ y: control.buttonHeight + 3+ x: Math.min(control.width - width, pillLayer.centreX - width / 2)+ text: control.app && control.app.statusLine.length > 0 ? control.app.statusLine : control.note+ size: 11+ color: Metrics.inkTertiary+ }+ }+}diff --git a/packages/wildos-store/qml/components/StoreIcon.qml b/packages/wildos-store/qml/components/StoreIcon.qmlnew file mode 100644index 0000000..5c951d0--- /dev/null+++ b/packages/wildos-store/qml/components/StoreIcon.qml@@ -0,0 +1,40 @@+import QtQuick+import QtQuick.Shapes+import WildOS.UI as UI++// A line icon from the Store's own set in Metrics, or from WildOS.UI when+// the name is one of the system's.+Item {+ id: icon++ property string name+ property color color: UI.Style.iconInk+ property real size: 16+ property real strokeWidth: size <= 16 ? 2 : 1.8++ readonly property string path: Metrics.icons[name] || UI.Icons.paths[name] || ""++ implicitWidth: size+ implicitHeight: size++ Shape {+ width: 24+ height: 24+ preferredRendererType: Shape.CurveRenderer+ transform: Scale {+ xScale: icon.size / 24+ yScale: icon.size / 24+ }++ ShapePath {+ strokeColor: icon.color+ strokeWidth: icon.strokeWidth+ fillColor: "transparent"+ capStyle: ShapePath.RoundCap+ joinStyle: ShapePath.RoundJoin+ PathSvg {+ path: icon.path+ }+ }+ }+}diff --git a/packages/wildos-store/qml/components/StoreLink.qml b/packages/wildos-store/qml/components/StoreLink.qmlnew file mode 100644index 0000000..7a80bf7--- /dev/null+++ b/packages/wildos-store/qml/components/StoreLink.qml@@ -0,0 +1,56 @@+import QtQuick+import QtQuick.Templates as T+import WildOS.UI as UI++// The boards' links ("See all", "Open Settings", the way back): words in+// the accent at medium weight, with an optional chevron before them.+T.AbstractButton {+ id: control++ property real size: 14+ property string iconName++ implicitWidth: row.implicitWidth + 8+ implicitHeight: row.implicitHeight + 6+ // So a heading beside it can line up with its words.+ baselineOffset: (height - row.height) / 2 + (row.height - label.height) / 2 + label.baselineOffset+ focusPolicy: Qt.StrongFocus+ hoverEnabled: true+ Accessible.name: text+ Accessible.role: Accessible.Link++ background: Item {+ UI.FocusRing {+ visible: control.visualFocus+ targetRadius: UI.Style.radiusXs+ }+ }++ contentItem: Item {+ Row {+ id: row+ anchors.centerIn: parent+ spacing: 4+ opacity: control.down ? 0.75 : 1++ UI.Icon {+ visible: control.iconName.length > 0+ anchors.verticalCenter: parent.verticalCenter+ name: control.iconName+ size: 16+ strokeWidth: 2+ color: UI.Style.accent+ }++ UI.Label {+ id: label+ anchors.verticalCenter: parent.verticalCenter+ text: control.text+ size: control.size+ font.weight: Font.Medium+ font.underline: control.hovered+ color: UI.Style.accent+ }+ }+ }+}diff --git a/packages/wildos-store/qml/components/SwapCard.qml b/packages/wildos-store/qml/components/SwapCard.qmlindex 66d60c8..57a767b 100644--- a/packages/wildos-store/qml/components/SwapCard.qml+++ b/packages/wildos-store/qml/components/SwapCard.qml@@ -25,10 +25,8 @@ T.AbstractButton {}background: Rectangle {- radius: UI.Style.radiusLg- color: card.down ? UI.Style.surfacePressed : card.hovered ? Metrics.tileHover : UI.Style.surfaceRaised- border.width: 1- border.color: UI.Style.borderSubtle+ radius: Metrics.radiusCard+ color: card.down ? Metrics.buttonFill : card.hovered ? Metrics.pill : Metrics.cardBehavior on color {ColorAnimation { duration: UI.Style.hoverDuration }}@@ -54,7 +52,7 @@ T.AbstractButton {anchors.verticalCenter: parent.verticalCentertext: card.app ? "Instead of " + card.app.insteadOf : ""size: 12- color: Metrics.inkCard+ color: Metrics.inkSecondarywidth: Math.min(implicitWidth, column.width - 20)}@@ -63,7 +61,7 @@ T.AbstractButton {name: "arrow"size: 12strokeWidth: 2.2- color: Metrics.inkCard+ color: Metrics.inkSecondary}}@@ -73,7 +71,7 @@ T.AbstractButton {AppIcon {id: icon- size: 48+ size: 56source: card.app ? card.app.iconSource : ""}@@ -85,15 +83,15 @@ T.AbstractButton {UI.Label {width: parent.widthtext: card.app ? card.app.name : ""- size: 15+ size: 14.5font.weight: Font.DemiBold}UI.Label {width: parent.widthtext: card.app ? card.app.tagline : ""- size: 12- color: Metrics.inkCard+ size: 13+ color: Metrics.inkSecondary}}}@@ -124,7 +122,7 @@ T.AbstractButton {}}- InstallButton {+ StoreButton {id: actionanchors.right: parent.rightwidth: implicitWidthdiff --git a/packages/wildos-store/qml/components/TileGrid.qml b/packages/wildos-store/qml/components/TileGrid.qmldeleted file mode 100644index afecb87..0000000--- a/packages/wildos-store/qml/components/TileGrid.qml+++ /dev/null@@ -1,29 +0,0 @@-import QtQuick-import QtQuick.Layouts--// A grid of compact app cards, four across with 12px gaps as on Home.-Grid {- id: grid-- property var keys: []- property int maxItems: -1-- signal activated(string key)-- Layout.fillWidth: true- columns: width > 900 ? 4 : width > 600 ? 3 : 2- columnSpacing: 12- rowSpacing: 12- readonly property real cellWidth: (width - columnSpacing * (columns - 1)) / columns-- Repeater {- model: grid.maxItems > 0 ? grid.keys.slice(0, grid.maxItems) : grid.keys-- AppTile {- required property string modelData- width: grid.cellWidth- appKey: modelData- onActivated: key => grid.activated(key)- }- }-}diff --git a/packages/wildos-store/qml/components/WindowsModeRow.qml b/packages/wildos-store/qml/components/WindowsModeRow.qmlnew file mode 100644index 0000000..7217e93--- /dev/null+++ b/packages/wildos-store/qml/components/WindowsModeRow.qml@@ -0,0 +1,73 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Store+import WildOS.UI as UI++// The way to the Windows program itself, from StoreSearch.dc.html's+// Windows apps row: the window tile, what Wild OS can do, and its+// settings.+Item {+ id: row++ property string title: "Need the Windows app itself?"++ Layout.fillWidth: true+ implicitHeight: Math.max(56, texts.implicitHeight) + 32++ Rectangle {+ id: tile+ anchors.verticalCenter: parent.verticalCenter+ width: 56+ height: 56+ radius: 13+ gradient: Gradient {+ orientation: Gradient.Vertical+ GradientStop { position: 0; color: "#3a4466" }+ GradientStop { position: 1; color: "#1a2036" }+ }++ StoreIcon {+ anchors.centerIn: parent+ name: "windows-apps"+ size: 26+ color: "#cfd9ff"+ }+ }++ Column {+ id: texts+ anchors.left: tile.right+ anchors.leftMargin: 16+ anchors.right: action.left+ anchors.rightMargin: 16+ anchors.verticalCenter: parent.verticalCenter+ spacing: 3++ UI.Label {+ width: parent.width+ text: row.title+ size: 14.5+ font.weight: Font.DemiBold+ wrapMode: Text.Wrap+ elide: Text.ElideNone+ }++ UI.Label {+ width: parent.width+ text: "Wild OS can run many Windows programs in a sandbox. Open the .exe file from Files and Wild OS will offer to install it."+ size: 13+ lineHeight: 1.45+ color: Metrics.inkSecondary+ wrapMode: Text.Wrap+ elide: Text.ElideNone+ }+ }++ PillButton {+ id: action+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ text: "Windows app settings"+ onClicked: Catalog.openSettings("windowsapps")+ }+}diff --git a/packages/wildos-store/qml/pages/AppPage.qml b/packages/wildos-store/qml/pages/AppPage.qmlindex 45bd767..bbc5b38 100644--- a/packages/wildos-store/qml/pages/AppPage.qml+++ b/packages/wildos-store/qml/pages/AppPage.qml@@ -3,11 +3,14 @@ import QtQuick.Controlsimport QtQuick.Effectsimport QtQuick.Layoutsimport QtQuick.Templates as T+import QtQuick.Windowimport WildOS.Storeimport WildOS.UI as UI-// One app, as StoreApp.dc.html: icon, name and facts, the buttons that act on-// it, what it does, and what it can reach on this computer.+// One app, as StoreAppPage.dc.html and StoreDownloading.dc.html: the icon,+// name and button, with the download's progress beside the button while it+// installs; the facts strip; screenshots; what it can reach; then what it+// does and the rest of its details.PageFlick {id: page@@ -15,15 +18,16 @@ PageFlick {property string argproperty string kindreadonly property var app: Catalog.app(arg)- readonly property bool working: app && (app.busy || app.queued)readonly property bool sandboxed: app && app.source === "flatpak"+ readonly property string step: button.shown+ readonly property bool working: ["waiting", "preparing", "downloading", "installing", "removing", "paused"].indexOf(step) >= 0property bool expanded: false// Flathub answers within seconds; if nothing comes back (no network, no// metadata for this app) the page says so instead of checking for ever.property bool checkGaveUp: falseTimer {- running: page.sandboxed && page.app && page.app.permissions.length === 0 && !page.app.permissionsUnknown+ running: page.sandboxed && page.app && !page.app.reachKnown && !page.app.permissionsUnknowninterval: 20000onTriggered: page.checkGaveUp = true}@@ -37,474 +41,280 @@ PageFlick {}}- UI.Button {- id: backLink- kind: "text"- iconName: "chevron-left"- iconSize: 15- iconStroke: 2- implicitHeight: 32- leftPadding: 6- rightPadding: 10- text: page.store.backTitle()- Accessible.name: "Back to " + page.store.backTitle()- onClicked: page.store.back()- }-RowLayout {Layout.fillWidth: truespacing: 24- Rectangle {- Layout.preferredWidth: 120- Layout.preferredHeight: 120- radius: 24- color: Metrics.iconTile+ Item {+ Layout.preferredWidth: 128+ Layout.preferredHeight: 128+ Layout.alignment: Qt.AlignTopAppIcon {- anchors.centerIn: parent- size: 88+ id: bigIcon+ anchors.fill: parent+ size: 128source: page.app ? page.app.iconSource : ""+ layer.enabled: true+ layer.effect: MultiEffect {+ shadowEnabled: true+ shadowColor: Qt.rgba(0, 0, 0, 0.35)+ shadowVerticalOffset: 14+ shadowBlur: 0.8+ blurMax: 40+ }+ }++ // A small hop when the app has just arrived.+ SequentialAnimation {+ id: bounce+ NumberAnimation { target: bigIcon; property: "scale"; to: 1.07; duration: 140; easing.type: Easing.OutQuad }+ NumberAnimation { target: bigIcon; property: "scale"; to: 1; duration: 420; easing.type: Easing.OutBack; easing.overshoot: 2.6 }}}ColumnLayout {Layout.fillWidth: true- spacing: 8+ Layout.alignment: Qt.AlignVCenter+ spacing: 5UI.Label {Layout.fillWidth: truetext: page.app ? page.app.name : ""- font.pixelSize: UI.Style.px(30)- font.weight: Font.DemiBold- font.letterSpacing: -0.3+ size: 32+ font.weight: Font.Bold+ font.letterSpacing: -0.64Accessible.role: Accessible.Heading}UI.Label {Layout.fillWidth: true- text: page.app ? page.app.byline : ""- font.pixelSize: UI.Style.px(14)- color: Metrics.inkSub+ visible: text.length > 0+ text: page.app ? page.app.tagline || page.app.summary : ""+ size: 17+ color: Metrics.inkSecondary}- Flow {- Layout.fillWidth: true- Layout.topMargin: 4- spacing: 8-- // Every app here is free to download, so the chip says what- // kind of free it is.- UI.Chip {- granted: false- text: page.app && page.app.openSource ? "Open source" : "Free to use"- }-- UI.Chip {- visible: page.sandboxed- iconName: "shield"- text: "Checked and sandboxed"- }-- UI.Chip {- visible: page.app && page.app.chip.length > 0- granted: false- text: page.app ? page.app.chip : ""- }+ StoreLink {+ Layout.leftMargin: -4+ visible: page.app && page.app.developer.length > 0+ enabled: page.app && page.app.homepage.length > 0+ text: page.app ? page.app.developer : ""+ Accessible.description: "Opens the website"+ onClicked: Qt.openUrlExternally(page.app.homepage)}- }- Row {- Layout.alignment: Qt.AlignVCenter- spacing: 10-- ProgressPill {- visible: page.working- height: Math.max(40, implicitHeight)- width: Math.max(180, implicitWidth)- fontSize: 13- app: page.app- }-- UI.Button {- size: "large"- visible: !page.working && page.app && page.app.installed- text: "Uninstall"- onClicked: removeDialog.open()- }-- UI.Button {- size: "large"- kind: !page.app.updateAvailable ? "primary" : "secondary"- visible: !page.working && page.app && page.app.installed && page.app.canOpen- text: "Open"- onClicked: page.app.open()- }-- UI.Button {- size: "large"- kind: "primary"- visible: !page.working && page.app && page.app.installed && page.app.updateAvailable- text: "Update"- onClicked: page.app.update()- }-- UI.Button {- size: "large"- kind: "primary"- visible: !page.working && page.app && !page.app.installed- enabled: page.app && page.app.source.length > 0- text: "Install"- onClicked: page.app.install()- }- }- }-- RowLayout {- Layout.fillWidth: true- spacing: 24-- ColumnLayout {- Layout.fillWidth: true- Layout.alignment: Qt.AlignTop- spacing: 18-- ColumnLayout {+ RowLayout {Layout.fillWidth: true- spacing: 8-- UI.Label {- text: "About"- font.pixelSize: UI.Style.px(15)- font.weight: Font.DemiBold- Accessible.role: Accessible.Heading+ Layout.topMargin: 10+ spacing: 14++ StoreButton {+ id: button+ Layout.alignment: Qt.AlignVCenter+ big: true+ app: page.app+ onLanded: if (!UI.Style.reducedMotion) bounce.restart()}- Item {- id: aboutClip- Layout.fillWidth: true- implicitHeight: page.expanded || !about.truncatedText ? about.implicitHeight : 6 * about.lineHeightPx- clip: true- // Fades the cut-off line instead of slicing it in half.- layer.enabled: !page.expanded && about.truncatedText- layer.effect: MultiEffect {- maskEnabled: true- maskSource: fadeMask- maskSpreadAtMin: 1.0- }+ // Beside the ring while it works: what is happening, how far+ // it has got and how long is left (StoreDownloading).+ Column {+ id: progress+ visible: page.working+ Layout.preferredWidth: 260+ Layout.alignment: Qt.AlignVCenter+ spacing: 6- Text {- id: about- readonly property real lineHeightPx: font.pixelSize * 1.6- readonly property bool truncatedText: implicitHeight > 6 * lineHeightPx + 4+ Item {width: parent.width- text: page.app ? page.app.description : ""- textFormat: Text.RichText- wrapMode: Text.Wrap- color: Metrics.inkBody- font.family: UI.Style.fontFamily- font.pixelSize: UI.Style.px(14)- lineHeight: 1.6- onLinkActivated: link => Qt.openUrlExternally(link)- }- }-- Item {- id: fadeMask- width: aboutClip.width- height: aboutClip.height- visible: false- layer.enabled: true-- Rectangle {- anchors.fill: parent- gradient: Gradient {- GradientStop { position: 0; color: "white" }- GradientStop { position: 0.75; color: "white" }- GradientStop { position: 1; color: "transparent" }- }- }- }-- UI.LinkButton {- visible: about.truncatedText- Layout.leftMargin: -4- text: page.expanded ? "Show less" : "Read more"- onClicked: page.expanded = !page.expanded- }- }-- Rectangle {- visible: page.app && page.app.swapTitle.length > 0- Layout.fillWidth: true- implicitHeight: swapRow.implicitHeight + 32- radius: UI.Style.radiusMd- color: UI.Style.accentTint- border.width: 1- border.color: UI.Style.accentBorder-- Row {- id: swapRow- x: 18- anchors.verticalCenter: parent.verticalCenter- width: parent.width - 36- spacing: 14-- UI.Icon {- anchors.verticalCenter: parent.verticalCenter- name: "swap"- size: 20- strokeWidth: 2- color: UI.Style.accentText- }-- Column {- anchors.verticalCenter: parent.verticalCenter- width: parent.width - 34- spacing: 2+ height: stepLabel.implicitHeightUI.Label {- width: parent.width- text: page.app ? page.app.swapTitle : ""- font.pixelSize: UI.Style.px(14)+ id: stepLabel+ text: {+ switch (page.step) {+ case "waiting": return "Waiting";+ case "preparing": return "Getting ready";+ case "installing": return "Installing";+ case "removing": return "Uninstalling";+ case "paused": return "Paused";+ }+ return page.app && page.app.action === "update" ? "Downloading the update" : "Downloading";+ }+ size: 13font.weight: Font.DemiBold}UI.Label {- width: parent.width- text: page.app ? page.app.swapText : ""- font.pixelSize: UI.Style.px(12)- color: UI.Style.inkMuted- wrapMode: Text.Wrap- elide: Text.ElideNone+ anchors.right: parent.right+ visible: page.step === "downloading" || page.step === "paused"+ text: page.app ? page.app.bytesText : ""+ size: 13+ font.features: { "tnum": 1 }+ color: Metrics.inkSecondary}}- }- }-- ColumnLayout {- Layout.fillWidth: true- spacing: 8- UI.Label {- text: "Status"- font.pixelSize: UI.Style.px(15)- font.weight: Font.DemiBold- Accessible.role: Accessible.Heading- }+ Rectangle {+ id: track+ width: parent.width+ height: 5+ radius: 3+ color: UI.Style.tone(0.12)+ clip: true++ readonly property bool known: page.step === "downloading" || page.step === "paused"+ property real shown: page.app ? Math.max(0, page.app.progress) : 0+ Behavior on shown {+ enabled: !UI.Style.reducedMotion+ NumberAnimation { duration: 600; easing.type: Easing.OutCubic }+ }- RowGroup {- Layout.fillWidth: true+ Rectangle {+ visible: track.known+ width: track.width * Math.min(100, track.shown) / 100+ height: parent.height+ radius: 3+ color: page.step === "paused" ? Metrics.inkSecondary : UI.Style.accent+ }- InfoRow {- visible: page.app && page.app.error.length > 0- warning: true- title: page.app && page.app.action === "remove" ? "Couldn't uninstall" : page.app && page.app.action === "update" ? "Couldn't update" : "Couldn't install"- subtitle: page.app ? page.app.error : ""-- UI.Button {- size: "small"- anchors.verticalCenter: parent.verticalCenter- text: "Dismiss"- onClicked: page.app.clearError()+ // While the amount of work is unknown a short band+ // drifts along the bar instead of it standing still.+ Rectangle {+ id: sweep+ visible: !track.known && page.step !== "waiting"+ height: parent.height+ width: parent.width * 0.3+ radius: 3+ color: UI.Style.accent+ NumberAnimation on x {+ running: sweep.visible+ loops: Animation.Infinite+ from: -sweep.width+ to: track.width+ duration: UI.Style.reducedMotion ? 4000 : 1400+ easing.type: Easing.InOutQuad+ }}}- InfoRow {- title: !page.app ? "" : page.working ? progressTitle.label- : page.app.installed ? "Installed" : "Not installed"- subtitle: {- if (!page.app) {- return "";- }- if (page.working) {- return page.app.queued ? "It starts when the apps before it finish" : "You can keep using the Store while it works";+ UI.Label {+ width: parent.width+ text: {+ if (page.step === "waiting") {+ return "It starts when the apps before it finish.";}- if (page.app.installed) {- return page.app.updateAvailable ? "An update is ready" : "Up to date, updates arrive with your other apps";+ if (page.step === "paused") {+ return "Press play to carry on.";}- return page.app.sizeText.length > 0 ? page.app.sizeText : "Free to install";- }-- ProgressPill {- id: progressTitle- visible: false- app: page.app+ const left = page.app ? page.app.timeLeftText : "";+ return left.length > 0 ? left + ". You can keep browsing." : "You can keep browsing.";}+ size: 12+ color: Metrics.inkTertiary}- InfoRow {- visible: page.app && page.app.installed && page.app.inStart- title: "Added to Start"- subtitle: page.app ? "In All apps under " + page.app.categoryLabel : ""- }-- InfoRow {- visible: page.app && page.app.source.length > 0- title: page.sandboxed ? "Sandboxed app" : "Wild OS app"- subtitle: page.sandboxed ? "Runs in a sandbox, separate from your other apps" : "Updated along with the rest of Wild OS"-- UI.LinkButton {- anchors.verticalCenter: parent.verticalCenter- visible: page.app && !page.app.installed && !page.working && page.app.hasFlatpak && page.app.hasApt- text: page.sandboxed ? "Use the Wild OS version" : "Use the sandboxed version"- onClicked: page.app.useSource(page.sandboxed ? "apt" : "flatpak")- }+ UI.Label {+ width: parent.width+ visible: text.length > 0 && page.step !== "removing"+ text: page.app ? page.app.sharedNote : ""+ size: 12+ color: Metrics.inkTertiary+ wrapMode: Text.Wrap+ elide: Text.ElideNone}}- }- }-- ColumnLayout {- Layout.preferredWidth: 380- Layout.maximumWidth: 380- Layout.alignment: Qt.AlignTop- spacing: 8-- UI.Label {- text: page.sandboxed ? "What it can reach" : "Details"- font.pixelSize: UI.Style.px(15)- font.weight: Font.DemiBold- Accessible.role: Accessible.Heading- }-- RowGroup {- visible: page.sandboxed- Layout.fillWidth: true-- InfoRow {- visible: page.app && page.app.permissions.length === 0- minHeight: 54- readonly property bool failed: page.app && (page.app.permissionsUnknown || page.checkGaveUp)- title: failed ? "Couldn't check what it asks for" : "Checking what it asks for"- subtitle: failed ? "The app library can't be reached right now. Try again when you're online." : ""- }-- Repeater {- model: page.sandboxed && page.app ? page.app.permissions : []-- InfoRow {- id: permission- required property var modelData- minHeight: 54- title: modelData.label- last: false- UI.Label {- anchors.verticalCenter: parent.verticalCenter- text: permission.modelData.fixed ? "Always" : permission.modelData.allowed ? "On" : "Off"- font.pixelSize: UI.Style.px(12)- color: UI.Style.inkMuted+ UI.Label {+ visible: !page.working && text.length > 0+ Layout.fillWidth: true+ text: {+ if (!page.app) {+ return "";}-- UI.Toggle {- visible: !permission.modelData.fixed- anchors.verticalCenter: parent.verticalCenter- checked: permission.modelData.allowed- locked: !permission.modelData.editable- lockedReason: "Change this once the app is installed"- Accessible.name: permission.modelData.label- onToggled: page.app.setPermission(permission.modelData.token, checked)+ if (page.app.error.length > 0) {+ return page.app.error;}+ if (page.step === "nospace") {+ return page.app.statusLine;+ }+ return page.step === "get" ? "Free" : "";}- }- }-- RowGroup {- visible: !page.sandboxed- Layout.fillWidth: true-- InfoRow {- minHeight: 54- title: "Version"- visible: page.app && page.app.version.length > 0-- UI.Label {- anchors.verticalCenter: parent.verticalCenter- text: page.app ? page.app.version : ""- font.pixelSize: UI.Style.px(12)- color: UI.Style.inkMuted- }- }-- InfoRow {- minHeight: 54- title: "Developer"- visible: page.app && page.app.developer.length > 0-- UI.Label {- anchors.verticalCenter: parent.verticalCenter- width: Math.min(implicitWidth, 200)- text: page.app ? page.app.developer : ""- font.pixelSize: UI.Style.px(12)- color: UI.Style.inkMuted- }+ size: 12.5+ color: page.app && page.app.error.length > 0 ? Metrics.danger : Metrics.inkTertiary}- InfoRow {- minHeight: 54- title: "Licence"- subtitle: page.app ? page.app.licence : ""- visible: page.app && page.app.licence.length > 0-- UI.Label {- anchors.verticalCenter: parent.verticalCenter- width: Math.min(implicitWidth, 200)- text: !page.app ? "" : page.app.openSource ? "Open source" : "Free to use"- font.pixelSize: UI.Style.px(12)- color: UI.Style.inkMuted- }+ UI.IconButton {+ visible: !page.working && page.app && page.app.error.length > 0+ Layout.preferredWidth: 28+ Layout.preferredHeight: 28+ radius: 14+ iconName: "close"+ iconSize: 12+ tip: "Dismiss"+ onClicked: page.app.clearError()}- InfoRow {- minHeight: 54- title: "Website"- visible: page.app && page.app.homepage.length > 0-- UI.LinkButton {- anchors.verticalCenter: parent.verticalCenter- size: 12- text: page.app ? page.app.homepage.replace(/^https?:\/\//, "").replace(/\/$/, "") : ""- onClicked: Qt.openUrlExternally(page.app.homepage)- }+ Item {+ Layout.fillWidth: true+ visible: page.working}}+ }- UI.Label {- Layout.fillWidth: true- Layout.topMargin: 4- Layout.leftMargin: 2- Layout.rightMargin: 2- font.pixelSize: UI.Style.px(12)- lineHeight: 1.5- color: UI.Style.inkMuted- wrapMode: Text.Wrap- elide: Text.ElideNone- text: !page.app ? ""- : !page.sandboxed ? page.app.name + " runs like any program on your computer, without a sandbox, so it can open any of your files."- : page.app.installed ? "Changes apply the next time " + page.app.name + " opens. " + page.app.name + " will ask if it ever needs something new."- : "This is what " + page.app.name + " asks for. You can change it once it's installed."- }+ UI.IconButton {+ Layout.alignment: Qt.AlignVCenter+ Layout.preferredWidth: 38+ Layout.preferredHeight: 38+ iconName: "share"+ iconSize: 18+ iconColor: Metrics.inkSecondary+ enabled: page.app && page.app.appstreamId.length > 0+ tip: "Copy link"+ onClicked: page.store.copyLink(page.app)}}- UI.Label {- visible: shots.count > 0- text: "Screenshots"- font.pixelSize: UI.Style.px(15)- font.weight: Font.DemiBold- Accessible.role: Accessible.Heading+ // Price, size, category, maker, licence and, for Flathub apps, safety.+ FactStrip {+ Layout.fillWidth: true+ cells: {+ const a = page.app;+ if (!a) {+ return [];+ }+ const out = [{ label: "Price", value: "Free", sub: "" }];+ const size = a.installed ? a.sizeText : a.downloadText;+ if (size.length > 0) {+ out.push({ label: "Size", value: size, sub: a.installed ? "Installed" : "Download" });+ }+ if (a.categoryLabel.length > 0) {+ out.push({ label: "Category", value: a.categoryLabel, sub: "" });+ }+ if (a.developer.length > 0) {+ out.push({ label: "Made by", value: a.developer, sub: "" });+ }+ out.push(a.openSource ? { label: "Licence", value: "Open source", sub: a.licence } : { label: "Licence", value: "Free to use", sub: "" });+ if (page.sandboxed) {+ out.push({ label: "Safety", value: "", icon: "shield-check", sub: a.checked ? "Checked and sandboxed" : "Sandboxed" });+ }+ return out;+ }}ListView {id: shotsLayout.fillWidth: true- Layout.topMargin: -18- Layout.preferredHeight: 220+ // The strip runs on to the window's edge, as the board's does.+ Layout.rightMargin: -Metrics.sidePadding+ Layout.preferredHeight: 262visible: count > 0orientation: ListView.Horizontal- spacing: 12+ spacing: 18clip: true+ // Only the pictures in view load, and the next two after them.+ cacheBuffer: 2 * (440 + 18)boundsBehavior: Flickable.StopAtBoundsmodel: page.app ? page.app.screenshots : []ScrollBar.horizontal: UI.ScrollBar {}@@ -513,8 +323,12 @@ PageFlick {id: shotrequired property var modelDatarequired property int index- height: 220- width: modelData.width > 0 ? Math.round(220 * modelData.width / modelData.height) : 391+ height: 262+ readonly property int naturalWidth: modelData.width > 0 && modelData.height > 0 ? Math.round(262 * modelData.width / modelData.height) : 466+ width: failed ? 0 : naturalWidth+ visible: !failed+ // A picture the server no longer has takes no room at all.+ readonly property bool failed: shotImage.status === Image.ErrorhoverEnabled: truefocusPolicy: Qt.TabFocusAccessible.role: Accessible.Button@@ -536,7 +350,11 @@ PageFlick {id: shotImageanchors.fill: parentanchors.margins: 1- source: shot.modelData.thumb+ // The catalogue's size closest to the card, never the+ // original, decoded at the size it is drawn.+ source: Catalog.pickImage(shot.modelData.images, Math.round(shot.naturalWidth * Screen.devicePixelRatio), Math.round(262 * Screen.devicePixelRatio))+ sourceSize.width: Math.round(shot.naturalWidth * Screen.devicePixelRatio)+ sourceSize.height: Math.round(262 * Screen.devicePixelRatio)fillMode: Image.PreserveAspectCropasynchronous: truesmooth: true@@ -555,29 +373,314 @@ PageFlick {radius: UI.Style.radiusMdcolor: shot.hovered ? UI.Style.tone(0.06) : "transparent"border.width: 1- border.color: UI.Style.borderSubtle+ border.color: Metrics.divider+ }+ }+ }+ }++ ColumnLayout {+ Layout.fillWidth: true+ spacing: 14++ SectionHeader {+ title: "What it can reach"+ linkText: page.sandboxed && page.app && page.app.permissions.length > 0 ? "Details" : ""+ onLinkClicked: permissionsDialog.open()+ }++ // Flathub apps: what the sandbox lets it reach and what it keeps+ // it from, from the app's own metadata.+ RowLayout {+ visible: page.sandboxed && page.app && page.app.reachKnown+ Layout.fillWidth: true+ spacing: 16++ ReachCard {+ visible: page.app && page.app.canReach.length > 0+ title: "Can reach"+ iconName: "tick"+ tint: Metrics.success+ rows: page.app ? page.app.canReach : []+ }++ ReachCard {+ visible: page.app && page.app.cantReach.length > 0+ title: "Can't reach"+ iconName: "close"+ tint: Metrics.danger+ rows: page.app ? page.app.cantReach : []+ }++ ReachCard {+ visible: page.app && page.app.worksOffline+ title: "Good to know"+ iconName: "info"+ tint: UI.Style.accent+ rows: [{ tick: true, label: "Works fully offline" }]+ }+ }++ ReachCard {+ visible: page.sandboxed && page.app && !page.app.reachKnown+ readonly property bool failed: page.app && (page.app.permissionsUnknown || page.checkGaveUp)+ title: failed ? "Couldn't check what it asks for" : "Checking what it asks for"+ iconName: "info"+ tint: UI.Style.accent+ text: failed ? "The app library can't be reached right now. Try again when you're online." : ""+ }++ ReachCard {+ visible: page.app && !page.sandboxed && page.app.source.length > 0+ title: "Runs without a sandbox"+ iconName: "info"+ tint: UI.Style.accent+ text: page.app ? page.app.name + " runs like any program on your computer, so it can open any of your files. It is updated along with the rest of Wild OS." : ""+ }+ }++ ColumnLayout {+ Layout.fillWidth: true+ spacing: 14+ visible: page.app && page.app.description.length > 0++ SectionHeader {+ title: "About"+ }++ Item {+ id: aboutClip+ Layout.fillWidth: true+ Layout.maximumWidth: 820+ implicitHeight: page.expanded || !about.truncatedText ? about.implicitHeight : 6 * about.lineHeightPx+ clip: true+ // Fades the cut-off line instead of slicing it in half.+ layer.enabled: !page.expanded && about.truncatedText+ layer.effect: MultiEffect {+ maskEnabled: true+ maskSource: fadeMask+ maskSpreadAtMin: 1.0+ }++ Text {+ id: about+ readonly property real lineHeightPx: font.pixelSize * 1.6+ readonly property bool truncatedText: implicitHeight > 6 * lineHeightPx + 4+ width: parent.width+ text: page.app ? page.app.description : ""+ textFormat: Text.RichText+ wrapMode: Text.Wrap+ color: Metrics.inkSecondary+ linkColor: UI.Style.accent+ font.family: UI.Style.fontFamily+ font.pixelSize: UI.Style.px(14)+ lineHeight: 1.6+ onLinkActivated: link => Qt.openUrlExternally(link)+ }+ }++ Item {+ id: fadeMask+ width: aboutClip.width+ height: aboutClip.height+ visible: false+ layer.enabled: true++ Rectangle {+ anchors.fill: parent+ gradient: Gradient {+ GradientStop { position: 0; color: "white" }+ GradientStop { position: 0.75; color: "white" }+ GradientStop { position: 1; color: "transparent" }+ }+ }+ }++ StoreLink {+ visible: about.truncatedText+ Layout.leftMargin: -4+ Layout.topMargin: -8+ text: page.expanded ? "Show less" : "Read more"+ onClicked: page.expanded = !page.expanded+ }+ }++ Rectangle {+ visible: page.app && page.app.swapTitle.length > 0+ Layout.fillWidth: true+ implicitHeight: swapRow.implicitHeight + 36+ radius: Metrics.radiusCard+ gradient: Gradient {+ orientation: Gradient.Horizontal+ GradientStop { position: 0; color: UI.Style.accentAlpha(0.16, 0.12) }+ GradientStop { position: 1; color: Qt.rgba(196 / 255, 122 / 255, 138 / 255, UI.Style.dark ? 0.12 : 0.09) }+ }+ border.width: 1+ border.color: UI.Style.accentAlpha(0.22, 0.20)++ Row {+ id: swapRow+ x: 22+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - 44+ spacing: 18++ Rectangle {+ anchors.verticalCenter: parent.verticalCenter+ width: 44+ height: 44+ radius: 12+ color: UI.Style.accentAlpha(0.18, 0.14)++ StoreIcon {+ anchors.centerIn: parent+ name: "swap-windows"+ size: 22+ color: UI.Style.accent+ }+ }++ Column {+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - 62+ spacing: 4++ UI.Label {+ width: parent.width+ text: page.app ? page.app.swapTitle : ""+ size: 16+ font.weight: Font.Bold+ }++ UI.Label {+ width: parent.width+ text: page.app ? page.app.swapText : ""+ size: 13.5+ lineHeight: 1.45+ color: Metrics.inkSecondary+ wrapMode: Text.Wrap+ elide: Text.ElideNone}}}}+ Flow {+ Layout.fillWidth: true+ Layout.topMargin: -10+ spacing: 18++ StoreLink {+ visible: page.app && page.app.homepage.length > 0+ text: "Website"+ onClicked: Qt.openUrlExternally(page.app.homepage)+ }++ StoreLink {+ visible: page.app && page.app.installed && !page.working+ text: "Uninstall"+ onClicked: page.store.askRemove(page.app)+ }++ UI.Label {+ visible: page.app && page.app.version.length > 0+ height: 26+ text: page.app ? "Version " + page.app.version : ""+ size: 13+ color: Metrics.inkTertiary+ }+ }++ // Some apps come both from Flathub and from Wild OS's own (Debian)+ // packages. Which one is about to install, and what that means for the+ // person, in plain words, with the switch to the other.+ Column {+ Layout.fillWidth: true+ visible: page.app && !page.app.installed && !page.working && page.app.hasFlatpak && page.app.hasApt+ spacing: 4++ UI.Label {+ width: parent.width+ text: page.sandboxed ? "Installing the sandboxed version, from Flathub" : "Installing the Wild OS version, from Debian"+ size: 13.5+ font.weight: Font.DemiBold+ }++ UI.Label {+ width: parent.width+ text: page.sandboxed+ ? "Usually the newest release. It runs in a sandbox, so it only reaches what you allow. It updates on its own, separately from Wild OS."+ : "Tested with Wild OS and updated with the rest of your system. It isn't sandboxed, so it can reach everything your account can. Often an older release."+ size: 13+ lineHeight: 1.45+ color: Metrics.inkSecondary+ wrapMode: Text.Wrap+ elide: Text.ElideNone+ }++ StoreLink {+ text: page.sandboxed ? "Install the Wild OS version instead" : "Install the sandboxed version instead"+ onClicked: page.app.useSource(page.sandboxed ? "apt" : "flatpak")+ }+ }+UI.Dialog {- id: removeDialog- title: page.app ? "Uninstall " + page.app.name + "?" : ""- text: page.sandboxed ? "Your files stay where they are. Its settings stay too, in case you install it again."- : "Your files stay where they are. Wild OS will ask for the administrator password."+ id: permissionsDialog+ title: page.app ? "What " + page.app.name + " can reach" : ""+ text: !page.app ? ""+ : page.app.installed ? "Changes apply the next time " + page.app.name + " opens. " + page.app.name + " will ask if it ever needs something new."+ : "This is what " + page.app.name + " asks for. You can change it once it's installed."++ Repeater {+ model: page.sandboxed && page.app ? page.app.permissions : []++ Item {+ id: permission+ required property var modelData+ Layout.fillWidth: true+ implicitHeight: Math.max(36, permissionLabel.implicitHeight + 12)++ UI.Label {+ id: permissionLabel+ anchors.left: parent.left+ anchors.right: permissionState.left+ anchors.rightMargin: 12+ anchors.verticalCenter: parent.verticalCenter+ text: permission.modelData.label+ size: 14+ }++ Row {+ id: permissionState+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ spacing: 10++ UI.Label {+ anchors.verticalCenter: parent.verticalCenter+ text: permission.modelData.fixed ? "Always" : permission.modelData.allowed ? "On" : "Off"+ size: 12+ color: Metrics.inkSecondary+ }++ UI.Toggle {+ visible: !permission.modelData.fixed+ anchors.verticalCenter: parent.verticalCenter+ checked: permission.modelData.allowed+ locked: !permission.modelData.editable+ lockedReason: "Change this once the app is installed"+ Accessible.name: permission.modelData.label+ onToggled: page.app.setPermission(permission.modelData.token, checked)+ }+ }+ }+ }+buttons: [- UI.Button {- text: "Cancel"- onClicked: removeDialog.close()- },UI.Button {kind: "primary"- text: "Uninstall"- onClicked: {- removeDialog.close();- page.app.remove();- }+ text: "Done"+ onClicked: permissionsDialog.close()}]}diff --git a/packages/wildos-store/qml/pages/BrowsePage.qml b/packages/wildos-store/qml/pages/BrowsePage.qmlindex bd9cc47..dffde32 100644--- a/packages/wildos-store/qml/pages/BrowsePage.qml+++ b/packages/wildos-store/qml/pages/BrowsePage.qml@@ -3,7 +3,8 @@ import QtQuick.Layoutsimport WildOS.Storeimport WildOS.UI as UI-// Apps and Games: every app in the catalogue, narrowed by category.+// Every app or every game in the catalogue, narrowed by category, from+// Categories.AppGrid {id: page@@ -13,52 +14,47 @@ AppGrid {readonly property bool games: kind === "games"readonly property string categoryId: arg.length > 0 ? arg : (games ? "games" : "all")- keys: Catalog.revision >= 0 ? Catalog.category(categoryId) : []+ keys: Catalog.catalogRevision >= 0 ? Catalog.category(categoryId) : []onActivated: key => store.openApp(key)- header: Item {- width: page.width - page.leftMargin - page.rightMargin - 12- height: headerColumn.implicitHeight + 22+ header: Column {+ width: page.innerWidth+ spacing: 18+ bottomPadding: 4- Column {- id: headerColumn+ PageTitle {width: parent.width- spacing: 16+ title: page.arg.length > 0 ? Catalog.categoryLabel(page.arg) : page.games ? "Games" : "All apps"+ subtitle: !Catalog.ready ? "Getting the list of apps"+ : page.keys.length === 1 ? (page.games ? "1 game" : "1 app") :page.keys.length + (page.games ? " games" : " apps")+ }++ Flow {+ width: parent.width+ spacing: 8- PageTitle {- width: parent.width- title: page.games ? "Games" : "Apps"- subtitle: page.games ? "Free games, and Steam for the ones you bought on Windows."- : "Free apps for everything you did on Windows."+ FilterPill {+ text: page.games ? "All games" : "All apps"+ selected: page.arg.length === 0+ onClicked: page.store.open(page.kind, "")}- Flow {- width: parent.width- spacing: 8+ Repeater {+ model: page.games ? Catalog.gameCategories : Catalog.appCategoriesFilterPill {- text: page.games ? "All games" : "All apps"- selected: page.arg.length === 0- onClicked: page.store.open(page.kind, "")- }-- Repeater {- model: page.games ? Catalog.gameCategories : Catalog.appCategories-- FilterPill {- required property var modelData- text: modelData.label- selected: page.arg === modelData.id- onClicked: page.store.open(page.kind, modelData.id)- }+ required property var modelData+ text: modelData.label+ selected: page.arg === modelData.id+ onClicked: page.store.open(page.kind, modelData.id)}}+ }- UI.Label {- visible: !Catalog.ready- text: "Getting the list of apps"- color: UI.Style.inkMuted- }+ Rectangle {+ width: parent.width+ height: 1+ color: Metrics.divider}}}diff --git a/packages/wildos-store/qml/pages/CategoriesPage.qml b/packages/wildos-store/qml/pages/CategoriesPage.qmlnew file mode 100644index 0000000..81d158e--- /dev/null+++ b/packages/wildos-store/qml/pages/CategoriesPage.qml@@ -0,0 +1,150 @@+import QtQuick+import QtQuick.Layouts+import QtQuick.Templates as T+import WildOS.Store+import WildOS.UI as UI++// Every category of apps and of games, each opening the full list.+PageFlick {+ id: page++ property var store+ property string arg+ property string kind++ component CategoryTile: T.AbstractButton {+ id: tile+ property string iconName+ implicitHeight: Math.max(56, Math.ceil(tileLabel.implicitHeight) + 24)+ hoverEnabled: true+ focusPolicy: Qt.TabFocus+ Accessible.role: Accessible.Button+ Accessible.name: text++ background: Rectangle {+ radius: Metrics.radiusCard+ color: tile.down ? Metrics.pill : tile.hovered ? Metrics.buttonFill : Metrics.card+ Behavior on color {+ ColorAnimation { duration: UI.Style.hoverDuration }+ }++ UI.FocusRing {+ visible: tile.visualFocus+ targetRadius: Metrics.radiusCard+ }+ }++ contentItem: Item {+ Rectangle {+ id: well+ x: 12+ anchors.verticalCenter: parent.verticalCenter+ width: 32+ height: 32+ radius: 9+ color: UI.Style.accentAlpha(0.13, 0.11)++ StoreIcon {+ anchors.centerIn: parent+ name: tile.iconName+ size: 18+ color: UI.Style.accent+ }+ }++ UI.Label {+ id: tileLabel+ anchors.left: well.right+ anchors.leftMargin: 12+ anchors.right: parent.right+ anchors.rightMargin: 12+ anchors.verticalCenter: parent.verticalCenter+ text: tile.text+ size: 14.5+ font.weight: Font.DemiBold+ }+ }+ }++ component TileGrid: Grid {+ Layout.fillWidth: true+ columns: width > 900 ? 4 : width > 560 ? 3 : 2+ columnSpacing: 12+ rowSpacing: 12+ readonly property real cellWidth: (width - columnSpacing * (columns - 1)) / columns+ }++ readonly property var appIcons: ({+ office: "document", internet: "globe", graphics: "reach-image", media: "videos",+ education: "info", development: "develop", utilities: "box", system: "cog"+ })++ PageTitle {+ title: "Categories"+ subtitle: "Every app and game in the Store, by what it does."+ }++ ColumnLayout {+ Layout.fillWidth: true+ spacing: 14++ SectionHeader {+ title: "Apps"+ }++ TileGrid {+ id: appGrid++ CategoryTile {+ width: appGrid.cellWidth+ iconName: "categories"+ text: "All apps"+ onClicked: page.store.open("apps", "")+ }++ Repeater {+ model: Catalog.appCategories++ CategoryTile {+ required property var modelData+ width: appGrid.cellWidth+ iconName: page.appIcons[modelData.id] || "categories"+ text: modelData.label+ onClicked: page.store.open("apps", modelData.id)+ }+ }+ }+ }++ ColumnLayout {+ Layout.fillWidth: true+ spacing: 14++ SectionHeader {+ title: "Games"+ }++ TileGrid {+ id: gameGrid++ CategoryTile {+ width: gameGrid.cellWidth+ iconName: "play"+ text: "All games"+ onClicked: page.store.open("games", "")+ }++ Repeater {+ model: Catalog.gameCategories++ CategoryTile {+ required property var modelData+ width: gameGrid.cellWidth+ iconName: "play"+ text: modelData.label+ onClicked: page.store.open("games", modelData.id)+ }+ }+ }+ }+}diff --git a/packages/wildos-store/qml/pages/CategoryPage.qml b/packages/wildos-store/qml/pages/CategoryPage.qmlnew file mode 100644index 0000000..9e02ca1--- /dev/null+++ b/packages/wildos-store/qml/pages/CategoryPage.qml@@ -0,0 +1,212 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Store+import WildOS.UI as UI++// Create, Work, Play and Develop, as StoreCreate.dc.html: the title and a+// line about it, filters at the right, a feature card, the top picks+// numbered in three columns, then everything else in the category. The+// filters are freedesktop categories; an app is in a filter when it has+// any of `any`, and also one of `also` when that is given, and none of+// `not`.+AppGrid {+ id: page++ property var store+ property string arg+ property string kind+ property int selected: 0++ readonly property var spec: {+ switch (kind) {+ case "work": return {+ title: "Work",+ subtitle: "Documents, email, calls and money.",+ filters: [+ { label: "All", any: ["Office", "Email", "Finance", "ProjectManagement", "Calendar", "ContactManagement", "WordProcessor", "Spreadsheet", "Presentation", "VideoConference"] },+ { label: "Documents", any: ["WordProcessor", "Spreadsheet", "Presentation", "Publishing", "Office"], not: ["Email", "Finance", "ProjectManagement", "Calendar"] },+ { label: "Email and calls", any: ["Email", "VideoConference", "InstantMessaging", "Telephony", "Chat"] },+ { label: "Planning", any: ["ProjectManagement", "Calendar", "ContactManagement"] },+ { label: "Money", any: ["Finance"] }+ ],+ hero: {+ eyebrow: "Office files",+ photo: "qrc:/qt/qml/WildOS/Store/data/heroes/contours.jpg",+ photoY: 0.5,+ title: "Open Word, Excel and PowerPoint files",+ body: "LibreOffice opens them and saves back to them, so you can keep working with people who use Office.",+ apps: ["libreoffice"],+ open: "libreoffice"+ }+ };+ case "play": return {+ title: "Play",+ subtitle: "Free games, and Steam for the ones you bought on Windows.",+ filters: [+ { label: "All", any: ["Game"] },+ { label: "Action", any: ["ActionGame", "Shooter"] },+ { label: "Adventure", any: ["AdventureGame", "RolePlaying"] },+ { label: "Puzzles", any: ["LogicGame", "BlocksGame"] },+ { label: "Strategy", any: ["StrategyGame"] },+ { label: "Racing and sports", any: ["SportsGame"] },+ { label: "Board and cards", any: ["BoardGame", "CardGame"] }+ ],+ hero: {+ eyebrow: "Your Steam games",+ photo: "qrc:/qt/qml/WildOS/Store/data/heroes/waves-green.jpg",+ photoY: 0.5,+ title: "Bring your Steam library",+ body: "Steam plays most Windows games here. Sign in and your library is there.",+ apps: ["steam"],+ open: "steam"+ }+ };+ case "develop": return {+ title: "Develop",+ subtitle: "Code editors, version control and the tools around them.",+ filters: [+ { label: "All", any: ["Development"] },+ { label: "Editors", any: ["IDE", "TextEditor"], also: ["Development"] },+ { label: "Version control", any: ["RevisionControl"] },+ { label: "Debugging", any: ["Debugger", "Profiling"] },+ { label: "Databases", any: ["Database"] },+ { label: "Web", any: ["WebDevelopment"] }+ ],+ hero: {+ eyebrow: "Start here",+ photo: "qrc:/qt/qml/WildOS/Store/data/heroes/dusk-hills.jpg",+ photoY: 0.4,+ title: "Write code in a proper editor",+ body: "Free code editors, from quick and simple to full development environments.",+ apps: [],+ topApps: 2,+ filter: 1+ }+ };+ }+ return {+ title: "Create",+ subtitle: "Paint, edit photos, cut video, make music.",+ filters: [+ { label: "All", any: ["Graphics", "2DGraphics", "RasterGraphics", "VectorGraphics", "Photography", "3DGraphics", "AudioVideoEditing", "Music", "Midi", "Sequencer", "Mixer"] },+ { label: "Photo", any: ["Photography", "RasterGraphics"] },+ { label: "Drawing", any: ["2DGraphics", "VectorGraphics"] },+ { label: "Video", any: ["AudioVideoEditing"], not: ["Audio"] },+ { label: "Audio", any: ["Audio"], also: ["AudioVideoEditing", "Music", "Midi", "Sequencer", "Mixer", "Recorder"] },+ { label: "3D", any: ["3DGraphics"] }+ ],+ hero: {+ eyebrow: "Get started",+ photo: "qrc:/qt/qml/WildOS/Store/data/photos/create-timeline.jpg",+ photoY: 0.5,+ title: "Make your first video tonight",+ body: "Kdenlive and Shotcut are free and never put a watermark on your videos.",+ apps: ["kdenlive", "org.shotcut.Shotcut"],+ filter: 3+ }+ };+ }++ function keysFor(f) {+ let keys = Catalog.matching(f.any);+ if (f.also) {+ const also = new Set(Catalog.matching(f.also));+ keys = keys.filter(k => also.has(k));+ }+ if (f.not) {+ const not = new Set(Catalog.matching(f.not));+ keys = keys.filter(k => !not.has(k));+ }+ return keys;+ }++ readonly property var allKeys: Catalog.catalogRevision >= 0 ? keysFor(spec.filters[Math.min(selected, spec.filters.length - 1)]) : []+ readonly property var topKeys: allKeys.slice(0, 9)+ readonly property var heroKeys: {+ if (Catalog.catalogRevision < 0) {+ return [];+ }+ if (spec.hero.topApps) {+ return keysFor(spec.filters[0]).slice(0, spec.hero.topApps);+ }+ return spec.hero.apps.map(id => Catalog.resolve(id)).filter(k => k.length > 0);+ }++ keys: allKeys.slice(9)+ onActivated: key => store.openApp(key)++ header: Column {+ width: page.innerWidth+ spacing: Metrics.sectionGap++ PageTitle {+ width: parent.width+ title: page.spec.title+ subtitle: page.spec.subtitle++ Repeater {+ model: page.spec.filters++ FilterPill {+ required property var modelData+ required property int index+ text: modelData.label+ selected: page.selected === index+ onClicked: page.selected = index+ }+ }+ }++ HeroCard {+ width: parent.width+ height: 220+ eyebrow: page.spec.hero.eyebrow+ title: page.spec.hero.title+ body: page.spec.hero.body+ photo: page.spec.hero.photo || ""+ photoY: page.spec.hero.photoY !== undefined ? page.spec.hero.photoY : 0.5+ keys: page.heroKeys+ shadeStrength: 0.85+ onClicked: {+ const hero = page.spec.hero;+ if (hero.open) {+ const key = Catalog.resolve(hero.open);+ if (key.length > 0) {+ page.store.openApp(key);+ }+ } else if (hero.filter !== undefined) {+ page.selected = hero.filter;+ }+ }+ }++ Column {+ width: parent.width++ SectionHeader {+ width: parent.width+ title: "Top picks"+ }++ AppList {+ width: parent.width+ keys: page.topKeys+ numbered: true+ onActivated: key => page.store.openApp(key)+ }++ UI.Label {+ visible: page.topKeys.length === 0+ topPadding: 16+ text: Catalog.ready ? "Nothing here yet." : "Getting the list of apps"+ color: Metrics.inkSecondary+ }+ }++ SectionHeader {+ visible: page.keys.length > 0+ width: parent.width+ title: page.selected > 0 ? "More in " + page.spec.filters[page.selected].label : page.kind === "play" ? "More games" : "More apps"+ }+ }+}diff --git a/packages/wildos-store/qml/pages/DiscoverPage.qml b/packages/wildos-store/qml/pages/DiscoverPage.qmlnew file mode 100644index 0000000..a101047--- /dev/null+++ b/packages/wildos-store/qml/pages/DiscoverPage.qml@@ -0,0 +1,154 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Store+import WildOS.UI as UI++// Discover, StoreDiscover.dc.html: the big swap card with two smaller ones+// beside it, then the essentials in three columns, and the curated lists+// for making things and playing below.+PageFlick {+ id: page++ property var store+ property string arg+ property string kind++ readonly property var swapKeys: Catalog.catalogRevision >= 0 ? Catalog.swaps() : []+ readonly property var createKeys: Catalog.catalogRevision >= 0 ? Catalog.featured("create") : []+ readonly property var gameKeys: Catalog.catalogRevision >= 0 ? Catalog.featured("games") : []+ // The essentials, topped up from the popular list to fill three rows.+ readonly property var essentialKeys: {+ if (Catalog.catalogRevision < 0) {+ return [];+ }+ const out = Catalog.essentials().slice();+ for (const k of Catalog.featured("popular")) {+ if (out.length >= 9) {+ break;+ }+ if (out.indexOf(k) < 0) {+ out.push(k);+ }+ }+ return out.slice(0, 9);+ }++ PageTitle {+ title: "Discover"+ }++ Item {+ id: heroes+ Layout.fillWidth: true+ Layout.preferredHeight: 330+ // The board's 640 of 1136, kept in proportion on a narrower window.+ readonly property real bigWidth: Math.round((width - 22) * 0.5745)++ HeroCard {+ width: heroes.bigWidth+ height: parent.height+ eyebrow: "The big swap"+ title: "Leave Windows behind.\nKeep everything you do."+ body: "Free apps that open your Office and Photoshop files, picked by us."+ photo: "qrc:/qt/qml/WildOS/Store/data/photos/swap-desk.jpg"+ photoY: 0.7+ keys: page.swapKeys.slice(0, 4)+ iconSize: 64+ titleSize: 28+ bodySize: 15+ onClicked: page.store.open("swap")+ }++ Column {+ x: heroes.bigWidth + 22+ width: parent.width - x+ spacing: 22++ HeroCard {+ width: parent.width+ height: 154+ eyebrow: "Make something"+ title: "Paint, edit and record"+ photo: "qrc:/qt/qml/WildOS/Store/data/photos/make-krita.jpg"+ photoY: 0.4+ shadeFromLeft: true+ body: "Free tools for pictures, video and sound."+ keys: page.createKeys.slice(0, 1)+ iconsRight: true+ onClicked: page.store.open("create")+ }++ HeroCard {+ width: parent.width+ height: 154+ eyebrow: "Play"+ title: "Games, free and on Steam"+ photo: "qrc:/qt/qml/WildOS/Store/data/photos/play-controller.jpg"+ photoY: 0.62+ shadeFromLeft: true+ body: "Free games to start with, and Steam for the ones you own."+ keys: page.gameKeys.slice(0, 2)+ iconsRight: true+ onClicked: page.store.open("play")+ }+ }+ }++ ColumnLayout {+ Layout.fillWidth: true+ spacing: 0++ SectionHeader {+ title: "Essentials for a new PC"+ linkText: "See all"+ onLinkClicked: page.store.open("swap")+ }++ AppList {+ keys: page.essentialKeys+ onActivated: key => page.store.openApp(key)+ }+ }++ ColumnLayout {+ Layout.fillWidth: true+ spacing: 0+ visible: page.createKeys.length > 0++ SectionHeader {+ title: "Make something"+ linkText: "See all"+ onLinkClicked: page.store.open("create")+ }++ AppList {+ keys: page.createKeys+ maxItems: 6+ onActivated: key => page.store.openApp(key)+ }+ }++ ColumnLayout {+ Layout.fillWidth: true+ spacing: 0+ visible: page.gameKeys.length > 0++ SectionHeader {+ title: "Play"+ linkText: "See all"+ onLinkClicked: page.store.open("play")+ }++ AppList {+ keys: page.gameKeys+ maxItems: 6+ onActivated: key => page.store.openApp(key)+ }+ }++ UI.Label {+ visible: !Catalog.ready+ text: "Getting the list of apps"+ color: Metrics.inkSecondary+ }+}diff --git a/packages/wildos-store/qml/pages/FilePage.qml b/packages/wildos-store/qml/pages/FilePage.qmlnew file mode 100644index 0000000..2222aab--- /dev/null+++ b/packages/wildos-store/qml/pages/FilePage.qml@@ -0,0 +1,382 @@+import QtQuick+import QtQuick.Effects+import QtQuick.Layouts+import WildOS.Store+import WildOS.UI as UI++// A package file someone opened (.deb, .flatpakref or .flatpak), laid out+// as an app's own page: the icon, name and button with the progress beside+// it, the facts strip, then where it comes from, what it needs and what it+// says it does. Nothing in the file has been checked, and the page says so+// in as many words; the name, maker and description are what the file says+// about itself.+PageFlick {+ id: page++ property var store+ property string arg+ property string kind++ readonly property bool isDeb: pkg.kind === "deb"+ readonly property bool working: pkg.state === "working"+ readonly property bool installable: pkg.state === "get" || pkg.state === "update" || pkg.state === "failed"+ // A .flatpakref that only points at Flathub has a proper Store page,+ // with its permissions and whether Flathub checked it.+ readonly property string flathubKey: pkg.flathubId.length > 0 && Catalog.ready ? Catalog.resolve(pkg.flathubId) : ""++ LocalPackage {+ id: pkg+ path: page.arg+ }++ // The Store's own button, driven by the file instead of a catalogue+ // app, so it looks and moves the same.+ QtObject {+ id: buttonApp+ readonly property string name: pkg.name+ readonly property int progress: pkg.progress+ readonly property string statusLine: ""+ readonly property bool cancellable: false+ readonly property bool installed: pkg.state === "installed" || pkg.state === "done" || pkg.state === "newer"+ readonly property string source: ""+ readonly property string buttonState: {+ switch (pkg.state) {+ case "get": return "get";+ case "update": return "update";+ case "failed": return "retry";+ case "working": return "installing";+ case "installed":+ case "done":+ case "newer":+ return pkg.canOpen ? "open" : "installed";+ }+ return "nospace";+ }+ function install() { pkg.install(); }+ function update() { pkg.install(); }+ function open() { pkg.open(); }+ function cancel() {}+ function pause() {}+ }++ RowLayout {+ Layout.fillWidth: true+ spacing: 24++ Item {+ Layout.preferredWidth: 128+ Layout.preferredHeight: 128+ Layout.alignment: Qt.AlignTop++ AppIcon {+ id: bigIcon+ anchors.fill: parent+ size: 128+ source: pkg.iconSource+ layer.enabled: true+ layer.effect: MultiEffect {+ shadowEnabled: true+ shadowColor: Qt.rgba(0, 0, 0, 0.35)+ shadowVerticalOffset: 14+ shadowBlur: 0.8+ blurMax: 40+ }+ }++ SequentialAnimation {+ id: bounce+ NumberAnimation { target: bigIcon; property: "scale"; to: 1.07; duration: 140; easing.type: Easing.OutQuad }+ NumberAnimation { target: bigIcon; property: "scale"; to: 1; duration: 420; easing.type: Easing.OutBack; easing.overshoot: 2.6 }+ }+ }++ ColumnLayout {+ Layout.fillWidth: true+ Layout.alignment: Qt.AlignVCenter+ spacing: 5++ UI.Label {+ Layout.fillWidth: true+ text: pkg.name+ size: 32+ font.weight: Font.Bold+ font.letterSpacing: -0.64+ Accessible.role: Accessible.Heading+ }++ UI.Label {+ Layout.fillWidth: true+ visible: text.length > 0+ text: pkg.summary+ size: 17+ color: Metrics.inkSecondary+ }++ UI.Label {+ Layout.fillWidth: true+ text: "From the file " + pkg.fileName+ size: 13+ color: Metrics.inkTertiary+ }++ RowLayout {+ Layout.fillWidth: true+ Layout.topMargin: 10+ spacing: 14++ StoreButton {+ id: button+ Layout.alignment: Qt.AlignVCenter+ big: true+ app: buttonApp+ onLanded: if (!UI.Style.reducedMotion) bounce.restart()+ }++ // Beside the ring while it works, as on an app's page.+ Column {+ visible: page.working+ Layout.preferredWidth: 260+ Layout.alignment: Qt.AlignVCenter+ spacing: 6++ UI.Label {+ text: {+ switch (pkg.phase) {+ case "auth": return "Waiting for the password";+ case "download": return "Downloading";+ case "install": return "Installing";+ }+ return "Getting ready";+ }+ size: 13+ font.weight: Font.DemiBold+ }++ Rectangle {+ id: track+ width: parent.width+ height: 5+ radius: 3+ color: UI.Style.tone(0.12)+ clip: true++ readonly property bool known: pkg.progress >= 0 && pkg.phase !== "auth"+ property real shown: Math.max(0, pkg.progress)+ Behavior on shown {+ enabled: !UI.Style.reducedMotion+ NumberAnimation { duration: 600; easing.type: Easing.OutCubic }+ }++ Rectangle {+ visible: track.known+ width: track.width * Math.min(100, track.shown) / 100+ height: parent.height+ radius: 3+ color: UI.Style.accent+ }++ Rectangle {+ id: sweep+ visible: !track.known+ height: parent.height+ width: parent.width * 0.3+ radius: 3+ color: UI.Style.accent+ NumberAnimation on x {+ running: sweep.visible && page.working+ loops: Animation.Infinite+ from: -sweep.width+ to: track.width+ duration: UI.Style.reducedMotion ? 4000 : 1400+ easing.type: Easing.InOutQuad+ }+ }+ }++ UI.Label {+ width: parent.width+ text: page.isDeb ? "Its own setup runs as part of this, which can take a minute." : "You can keep browsing."+ size: 12+ color: Metrics.inkTertiary+ wrapMode: Text.Wrap+ elide: Text.ElideNone+ }+ }++ UI.Label {+ visible: !page.working && text.length > 0+ Layout.fillWidth: true+ readonly property bool bad: ["unreadable", "blocked", "failed"].indexOf(pkg.state) >= 0+ text: {+ switch (pkg.state) {+ case "reading": return "Reading the file";+ case "unreadable":+ case "blocked":+ case "failed":+ return pkg.problem;+ case "update": return "Version " + pkg.installedVersion + " is installed. This file has " + pkg.version + ".";+ case "installed": return "This version is installed.";+ case "newer": return "A newer version is installed (" + pkg.installedVersion + ").";+ case "done": return pkg.canOpen ? "Installed. It's in Start too." : "Installed.";+ }+ return "";+ }+ size: 12.5+ color: bad ? Metrics.danger : Metrics.inkTertiary+ wrapMode: Text.Wrap+ elide: Text.ElideNone+ maximumLineCount: 5+ }++ Item {+ Layout.fillWidth: true+ visible: page.working+ }+ }+ }+ }++ FactStrip {+ Layout.fillWidth: true+ visible: cells.length > 0+ cells: {+ if (pkg.state === "reading" || pkg.state === "unreadable") {+ return [];+ }+ const out = [];+ if (pkg.version.length > 0) {+ out.push({ label: "Version", value: pkg.version, sub: pkg.installedVersion.length > 0 && pkg.installedVersion !== pkg.version ? "You have " + pkg.installedVersion : "" });+ }+ if (pkg.installedSizeText.length > 0) {+ out.push({ label: "Size", value: pkg.installedSizeText, sub: "Once installed" });+ } else if (pkg.fileSizeText.length > 0) {+ out.push({ label: "Size", value: pkg.fileSizeText, sub: "The file" });+ }+ out.push(page.isDeb ? { label: "Kind", value: "Debian package", sub: "Not sandboxed" } : { label: "Kind", value: "Flatpak", sub: "Sandboxed" });+ if (pkg.maker.length > 0) {+ out.push({ label: "Made by", value: pkg.maker, sub: "As the file says" });+ }+ if (!page.isDeb) {+ out.push({ label: "Updates from", value: pkg.origin.length > 0 ? pkg.origin : "None", sub: pkg.origin.length > 0 ? "" : "It won't update itself" });+ }+ return out;+ }+ }++ ColumnLayout {+ Layout.fillWidth: true+ spacing: 14+ visible: pkg.state !== "reading" && pkg.state !== "unreadable"++ SectionHeader {+ title: "Where it comes from"+ }++ ReachCard {+ visible: page.flathubKey.length > 0+ title: "This app is on Flathub"+ iconName: "info"+ tint: UI.Style.accent+ text: "Its page in the Store shows what it can reach and whether Flathub has checked who makes it."+ }++ StoreLink {+ visible: page.flathubKey.length > 0+ Layout.leftMargin: -4+ Layout.topMargin: -6+ text: "See it in the Store"+ onClicked: page.store.openApp(page.flathubKey)+ }++ ReachCard {+ visible: page.flathubKey.length === 0+ title: page.isDeb ? "Not from Wild OS, and not checked" : "Not from the Store, and not checked"+ iconName: "info"+ tint: Metrics.danger+ text: {+ if (page.isDeb) {+ return "Wild OS didn't make this package and nothing has checked it. Installing it runs its own setup with full access to your computer, "+ + "and the app it installs can open any of your files. Wild OS won't update it, unless the package adds its own source of updates. "+ + "Only install it if you trust where it came from.";+ }+ const updates = pkg.origin.length > 0 ? "It downloads from " + pkg.origin + ", and its updates come from there too. " : "It won't get updates. ";+ return "Nothing has checked this app. It runs in a sandbox, but the app itself decides how much that sandbox lets it reach. "+ + updates + "Only install it if you trust where it came from.";+ }+ }+ }++ // What a .deb needs from the Wild OS repositories, as PackageKit works+ // it out before anything is installed.+ ColumnLayout {+ Layout.fillWidth: true+ spacing: 14+ visible: page.isDeb && pkg.depends.length > 0 && pkg.state !== "unreadable"++ SectionHeader {+ title: "What it needs"+ }++ ReachCard {+ readonly property string needs: "It asks for " + pkg.depends.join(", ") + "."+ title: pkg.checkingDepends ? "Checking what it needs"+ : !page.installable ? "Parts it needs"+ : pkg.extras.length > 0 ? "Also installs " + pkg.extras.length + (pkg.extras.length === 1 ? " part" : " parts") + " from Wild OS"+ : "Everything it needs is already here"+ iconName: pkg.state === "blocked" ? "close" : "tick"+ tint: pkg.state === "blocked" ? Metrics.danger : Metrics.success+ text: page.installable && pkg.extras.length > 0 ? pkg.extras.join(", ") + ".\n\n" + needs : needs+ }++ ReachCard {+ visible: page.installable && pkg.removes.length > 0+ title: "Removes " + pkg.removes.length + (pkg.removes.length === 1 ? " part" : " parts") + " of your system"+ iconName: "close"+ tint: Metrics.danger+ text: "To make room, installing it takes " + pkg.removes.join(", ") + " off your computer. Anything that uses them stops working."+ }+ }++ ColumnLayout {+ Layout.fillWidth: true+ spacing: 14+ visible: pkg.description.length > 0 && pkg.state !== "unreadable"++ SectionHeader {+ title: "What it says it does"+ }++ Text {+ Layout.fillWidth: true+ Layout.maximumWidth: 820+ text: pkg.description+ textFormat: Text.PlainText+ wrapMode: Text.Wrap+ color: Metrics.inkSecondary+ font.family: UI.Style.fontFamily+ font.pixelSize: UI.Style.px(14)+ lineHeight: 1.6+ }+ }++ Flow {+ Layout.fillWidth: true+ Layout.topMargin: -10+ spacing: 18++ StoreLink {+ visible: pkg.homepage.length > 0+ text: "Website"+ Accessible.description: "Opens the website the file names"+ onClicked: Qt.openUrlExternally(pkg.homepage)+ }++ UI.Label {+ visible: pkg.id.length > 0+ height: 26+ text: (page.isDeb ? "Package " : "App ID ") + pkg.id+ size: 13+ color: Metrics.inkTertiary+ }+ }+}diff --git a/packages/wildos-store/qml/pages/HomePage.qml b/packages/wildos-store/qml/pages/HomePage.qmldeleted file mode 100644index 720e1e2..0000000--- a/packages/wildos-store/qml/pages/HomePage.qml+++ /dev/null@@ -1,240 +0,0 @@-import QtQuick-import QtQuick.Effects-import QtQuick.Layouts-import WildOS.Store-import WildOS.UI as UI--// Home, as Store.dc.html: the welcome banner, the Windows swaps and what is-// already installed, then more to browse below the fold.-PageFlick {- id: page-- property var store- property string arg- property string kind-- readonly property var essentials: Catalog.revision >= 0 ? Catalog.essentials() : []- readonly property int essentialsLeft: {- let n = 0;- for (const k of essentials) {- const a = Catalog.app(k);- if (a && !a.installed) {- n++;- }- }- return n;- }- readonly property bool essentialsBusy: {- for (const k of essentials) {- const a = Catalog.app(k);- if (a && (a.busy || a.queued)) {- return true;- }- }- return false;- }-- Item {- id: hero- Layout.fillWidth: true- Layout.preferredHeight: Math.max(210, heroText.implicitHeight + 60)-- Item {- id: heroArt- anchors.fill: parent- visible: false- layer.enabled: true-- // object-position: center 62%, as the design crops it.- Image {- readonly property real scaledHeight: width * 1334 / 2000- width: Math.max(parent.width, parent.height * 2000 / 1334)- height: scaledHeight- x: (parent.width - width) / 2- y: -(scaledHeight - parent.height) * 0.62- source: "qrc:/qt/qml/WildOS/Store/data/hero.jpg"- sourceSize.width: 2000- asynchronous: true- }-- Rectangle {- anchors.fill: parent- color: Metrics.heroShade- }- }-- Rectangle {- id: heroMask- anchors.fill: parent- radius: Metrics.radiusHero- visible: false- layer.enabled: true- }-- MultiEffect {- anchors.fill: parent- source: heroArt- maskEnabled: true- maskSource: heroMask- maskThresholdMin: 0.5- maskSpreadAtMin: 1.0- }-- Column {- id: heroText- x: 36- y: 36- width: Math.min(520, parent.width - 72)- spacing: 10-- UI.Label {- text: "NEW TO WILD OS"- font.pixelSize: UI.Style.px(12)- font.weight: Font.DemiBold- font.letterSpacing: 0.72- color: Metrics.eyebrow- }-- UI.Label {- width: parent.width- text: "The free apps that replace what you used on Windows"- color: Metrics.onPhoto- font.pixelSize: UI.Style.px(30)- font.weight: Font.DemiBold- font.letterSpacing: -0.3- lineHeight: 36 * UI.Style.textScale- lineHeightMode: Text.FixedHeight- wrapMode: Text.Wrap- elide: Text.ElideNone- Accessible.role: Accessible.Heading- }-- Row {- topPadding: 6- spacing: 10-- UI.Button {- size: "large"- kind: "primary"- enabled: page.essentialsLeft > 0 && !page.essentialsBusy- text: page.essentialsBusy ? "Installing the essentials" : page.essentialsLeft === 0 && page.essentials.length > 0 ? "Essentials installed" : "Install the essentials"- onClicked: Catalog.installEssentials()- }-- UI.Button {- size: "large"- textColor: Metrics.onPhoto- // A glass button on the photograph, light in either scheme.- background: Rectangle {- radius: 10- color: Metrics.onPhotoAlpha(parent.down ? 0.18 : parent.hovered ? 0.14 : 0.10)- border.width: 1- border.color: Metrics.onPhotoAlpha(0.30)-- UI.FocusRing {- visible: parent.parent.visualFocus- targetRadius: 10- }- }- text: "See the list"- onClicked: page.store.open("windows")- }- }- }- }-- ColumnLayout {- Layout.fillWidth: true- spacing: 12-- SectionHeader {- title: "Swap your Windows apps"- linkText: "See all"- onLinkClicked: page.store.open("windows")- }-- SwapGrid {- keys: Catalog.revision >= 0 ? Catalog.homeSwaps() : []- onActivated: key => page.store.openApp(key)- }- }-- ColumnLayout {- Layout.fillWidth: true- spacing: 12- visible: installedGrid.keys.length > 0-- SectionHeader {- title: "Already on this computer"- linkText: "How we check apps"- onLinkClicked: checkDialog.open()- }-- TileGrid {- id: installedGrid- keys: Catalog.revision >= 0 ? Catalog.homeInstalled() : []- maxItems: 4- columns: 4- onActivated: key => page.store.openApp(key)- }- }-- ColumnLayout {- Layout.fillWidth: true- spacing: 12-- SectionHeader {- title: "Popular apps"- linkText: "See all apps"- onLinkClicked: page.store.open("apps")- }-- TileGrid {- keys: Catalog.revision >= 0 ? Catalog.featured("popular") : []- onActivated: key => page.store.openApp(key)- }- }-- ColumnLayout {- Layout.fillWidth: true- spacing: 12-- SectionHeader {- title: "Make something"- }-- TileGrid {- keys: Catalog.revision >= 0 ? Catalog.featured("create") : []- onActivated: key => page.store.openApp(key)- }- }-- ColumnLayout {- Layout.fillWidth: true- spacing: 12-- SectionHeader {- title: "Play"- linkText: "See all games"- onLinkClicked: page.store.open("games")- }-- TileGrid {- keys: Catalog.revision >= 0 ? Catalog.featured("games") : []- onActivated: key => page.store.openApp(key)- }- }-- UI.Dialog {- id: checkDialog- title: "How we check apps"- text: "Apps marked Checked and sandboxed come from Flathub, the app library Wild OS uses. Each one is reviewed before it is listed, and runs in a sandbox that only reaches the folders and devices you allow on its page.\n\nApps from Wild OS packages are built and signed by the Wild OS maintainers, and get security fixes with your other updates. They run like any program on your computer, so their page says so."- buttons: [- UI.Button {- kind: "primary"- text: "Got it"- onClicked: checkDialog.close()- }- ]- }-}diff --git a/packages/wildos-store/qml/pages/InstalledPage.qml b/packages/wildos-store/qml/pages/InstalledPage.qmldeleted file mode 100644index 2d7401e..0000000--- a/packages/wildos-store/qml/pages/InstalledPage.qml+++ /dev/null@@ -1,35 +0,0 @@-import QtQuick-import QtQuick.Layouts-import WildOS.Store--// Every app installed from either catalogue, to open or remove.-PageFlick {- id: page-- property var store- property string arg- property string kind- readonly property var keys: Catalog.revision >= 0 ? Catalog.installedApps() : []-- PageTitle {- title: "Installed"- subtitle: !Catalog.ready ? "Getting the list of apps"- : page.keys.length === 1 ? "1 app" : page.keys.length + " apps"- }-- RowGroup {- visible: page.keys.length > 0- Layout.fillWidth: true-- Repeater {- model: page.keys-- AppRow {- required property string modelData- appKey: modelData- showRemove: true- onActivated: key => page.store.openApp(key)- }- }- }-}diff --git a/packages/wildos-store/qml/pages/LibraryPage.qml b/packages/wildos-store/qml/pages/LibraryPage.qmlnew file mode 100644index 0000000..c78aae0--- /dev/null+++ b/packages/wildos-store/qml/pages/LibraryPage.qml@@ -0,0 +1,54 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Store+import WildOS.UI as UI++// Library: every app installed from either catalogue, to open, update or+// uninstall from its menu.+AppGrid {+ id: page++ property var store+ property string arg+ property string kind++ keys: Catalog.catalogRevision + Catalog.stateRevision >= 0 ? Catalog.installedApps() : []+ showMore: true+ onActivated: key => store.openApp(key)++ header: Column {+ width: page.innerWidth+ spacing: 18+ bottomPadding: 4++ PageTitle {+ width: parent.width+ title: "Library"+ subtitle: !Catalog.ready ? "Getting the list of apps"+ : page.keys.length === 0 ? "No apps to show yet."+ : page.keys.length === 1 ? "1 app" : page.keys.length + " apps"+ }++ // What the sidebar's ring stands for: apps on their way in or out.+ SectionHeader {+ visible: working.keys.length > 0+ width: parent.width+ title: "Getting now"+ }++ AppList {+ id: working+ visible: keys.length > 0+ width: parent.width+ keys: Catalog.stateRevision >= 0 ? Catalog.workingApps() : []+ onActivated: key => page.store.openApp(key)+ }++ Rectangle {+ visible: page.keys.length > 0+ width: parent.width+ height: 1+ color: Metrics.divider+ }+ }+}diff --git a/packages/wildos-store/qml/pages/SearchPage.qml b/packages/wildos-store/qml/pages/SearchPage.qmlindex de71882..4fd6a10 100644--- a/packages/wildos-store/qml/pages/SearchPage.qml+++ b/packages/wildos-store/qml/pages/SearchPage.qml@@ -3,59 +3,136 @@ import QtQuick.Layoutsimport WildOS.Storeimport WildOS.UI as UI-// Search results. Typing a Windows app's name ("Photoshop") puts the apps-// that replace it first, as their own cards.+// Search results, StoreSearch.dc.html. Typing a Windows app's name+// ("photoshop") puts the free apps that do its job first, under a note+// saying what they replace, with the way to the Windows program itself+// after them. Everything else that matches follows.AppGrid {id: pageproperty var storeproperty string argproperty string kind- readonly property var swapKeys: Catalog.revision >= 0 ? Catalog.swapMatches(arg) : []+ readonly property var swapKeys: Catalog.catalogRevision >= 0 ? Catalog.swapMatches(arg) : []+ readonly property string windowsName: {+ if (swapKeys.length === 0) {+ return "";+ }+ const a = Catalog.app(swapKeys[0]);+ return a ? a.insteadOf : "";+ }keys: {- const all = Catalog.revision >= 0 ? Catalog.search(arg) : [];+ const all = Catalog.catalogRevision >= 0 ? Catalog.search(arg) : [];return all.filter(k => swapKeys.indexOf(k) < 0);}onActivated: key => store.openApp(key)- header: Item {- width: page.width - page.leftMargin - page.rightMargin - 12- height: headerColumn.implicitHeight + 22+ header: Column {+ width: page.innerWidth+ spacing: Metrics.sectionGap+ bottomPadding: page.swapKeys.length > 0 ? 0 : 10- Column {- id: headerColumn+ PageTitle {width: parent.width- spacing: 16+ title: "Results for “" + page.arg + "”"+ subtitle: !Catalog.ready ? "Getting the list of apps"+ : page.keys.length + page.swapKeys.length === 0 ? "Nothing matches. Try the name of the Windows app you used, or what you want to do, like “edit photos”." : ""+ }- PageTitle {- width: parent.width- title: "Results for “" + page.arg + "”"- subtitle: !Catalog.ready ? "Getting the list of apps"- : page.keys.length + page.swapKeys.length === 0 ? "Nothing matches. Try the name of the Windows app you used, or what you want to do, like “edit photos”." : ""+ Rectangle {+ visible: page.windowsName.length > 0+ width: parent.width+ height: bannerText.implicitHeight + 36+ radius: Metrics.radiusCard+ gradient: Gradient {+ orientation: Gradient.Horizontal+ GradientStop { position: 0; color: UI.Style.accentAlpha(0.16, 0.12) }+ GradientStop { position: 1; color: Qt.rgba(196 / 255, 122 / 255, 138 / 255, UI.Style.dark ? 0.12 : 0.09) }}+ border.width: 1+ border.color: UI.Style.accentAlpha(0.22, 0.20)- UI.Label {- visible: page.swapKeys.length > 0- text: "Instead of what you used on Windows"- font.pixelSize: UI.Style.px(17)- font.weight: Font.DemiBold+ Rectangle {+ id: bannerIcon+ x: 22+ anchors.verticalCenter: parent.verticalCenter+ width: 44+ height: 44+ radius: 12+ color: UI.Style.accentAlpha(0.18, 0.14)++ StoreIcon {+ anchors.centerIn: parent+ name: "swap-windows"+ size: 22+ color: UI.Style.accent+ }}- SwapGrid {- visible: page.swapKeys.length > 0+ Column {+ id: bannerText+ anchors.left: bannerIcon.right+ anchors.leftMargin: 18+ anchors.right: parent.right+ anchors.rightMargin: 22+ anchors.verticalCenter: parent.verticalCenter+ spacing: 4++ UI.Label {+ width: parent.width+ text: "Looking for " + page.windowsName + "?"+ size: 16+ font.weight: Font.Bold+ }++ UI.Label {+ width: parent.width+ text: "These free apps do the same job on Wild OS."+ size: 13.5+ lineHeight: 1.45+ color: Metrics.inkSecondary+ wrapMode: Text.Wrap+ elide: Text.ElideNone+ }+ }+ }++ Column {+ visible: page.swapKeys.length > 0+ width: parent.width++ SectionHeader {+ width: parent.width+ title: "Free apps that do the job"+ }++ AppList {width: parent.widthkeys: page.swapKeys+ showNotes: trueonActivated: key => page.store.openApp(key)}+ }++ Column {+ visible: page.swapKeys.length > 0+ width: parent.width++ SectionHeader {+ width: parent.width+ title: "Windows apps"+ }- UI.Label {- visible: page.swapKeys.length > 0 && page.keys.length > 0- topPadding: 10- text: "More apps"- font.pixelSize: UI.Style.px(17)- font.weight: Font.DemiBold+ WindowsModeRow {+ width: parent.width}}++ SectionHeader {+ visible: page.swapKeys.length > 0 && page.keys.length > 0+ width: parent.width+ title: "More results"+ }}}diff --git a/packages/wildos-store/qml/pages/SwapPage.qml b/packages/wildos-store/qml/pages/SwapPage.qmlnew file mode 100644index 0000000..2c99d45--- /dev/null+++ b/packages/wildos-store/qml/pages/SwapPage.qml@@ -0,0 +1,53 @@+import QtQuick+import QtQuick.Layouts+import WildOS.Store+import WildOS.UI as UI++// Swap from Windows: each Windows app people know, and the free app that+// does its job here.+PageFlick {+ id: page++ property var store+ property string arg+ property string kind++ readonly property var essentials: Catalog.catalogRevision >= 0 ? Catalog.essentials() : []+ readonly property int essentialsLeft: {+ let n = 0;+ for (const k of essentials) {+ const a = Catalog.app(k);+ if (a && !a.installed) {+ n++;+ }+ }+ return n;+ }+ readonly property bool essentialsBusy: {+ for (const k of essentials) {+ const a = Catalog.app(k);+ if (a && (a.busy || a.queued)) {+ return true;+ }+ }+ return false;+ }++ PageTitle {+ title: "Swap from Windows"+ subtitle: "Free apps that do what your Windows apps did. Most open the same files, so nothing gets left behind."++ PillButton {+ big: true+ filled: true+ enabled: page.essentialsLeft > 0 && !page.essentialsBusy+ text: page.essentialsBusy ? "Installing the essentials" : page.essentialsLeft === 0 && page.essentials.length > 0 ? "Essentials installed" : "Install the essentials"+ onClicked: Catalog.installEssentials()+ }+ }++ SwapGrid {+ keys: Catalog.catalogRevision >= 0 ? Catalog.swaps() : []+ onActivated: key => page.store.openApp(key)+ }+}diff --git a/packages/wildos-store/qml/pages/UpdatesPage.qml b/packages/wildos-store/qml/pages/UpdatesPage.qmlindex 93db279..264200f 100644--- a/packages/wildos-store/qml/pages/UpdatesPage.qml+++ b/packages/wildos-store/qml/pages/UpdatesPage.qml@@ -3,71 +3,331 @@ import QtQuick.Layoutsimport WildOS.Storeimport WildOS.UI as UI-// App updates from both catalogues. Updates to Wild OS itself are in-// Settings, as Windows keeps the Store and Windows Update apart.+// Updates, StoreUpdates.dc.html: the apps with an update and what changed,+// the ones updated lately, and at the side the overnight switch and the+// way to Wild OS's own updates, which live in Settings.PageFlick {id: pageproperty var storeproperty string argproperty string kind- readonly property var keys: Catalog.revision >= 0 ? Catalog.updates() : []+ readonly property var keys: Catalog.catalogRevision + Catalog.stateRevision >= 0 ? Catalog.updates() : []+ readonly property var recent: Catalog.catalogRevision + Catalog.stateRevision >= 0 ? Catalog.recentlyUpdated(5) : []+ readonly property bool updatingAll: Catalog.updateAllProgress >= 0+ readonly property bool sideBySide: width - 2 * Metrics.sidePadding > 760PageTitle {title: "Updates"- subtitle: page.keys.length === 1 ? "1 app has an update."- : page.keys.length > 1 ? page.keys.length + " apps have updates."- : Catalog.checking ? "Checking for updates."+ subtitle: {+ const n = page.keys.length;+ if (n > 0) {+ const count = n === 1 ? "1 update" : n + " updates";+ return Catalog.updatesBytes >= 0 ? count + ", " + Catalog.sizeText(Catalog.updatesBytes) + " in total" : count;+ }+ return Catalog.checking ? "Checking for updates.": Catalog.checkResult === "failed" ? "Couldn't check every app for updates. Check you're online and try again.": Catalog.checkResult === "ok" ? "Your apps are up to date. Checked at " + Catalog.checkedAt + "."- : "Your apps are up to date."+ : "Your apps are up to date.";+ }- UI.Button {- size: "large"- visible: page.keys.length === 0- enabled: !Catalog.checking- text: Catalog.checking ? "Checking" : "Check for updates"- onClicked: Catalog.refresh()+ Row {+ visible: page.updatingAll+ spacing: 10+ height: 34++ UI.Label {+ anchors.verticalCenter: parent.verticalCenter+ text: "Updating"+ size: 13+ font.weight: Font.DemiBold+ }++ Ring {+ anchors.verticalCenter: parent.verticalCenter+ size: 34+ mode: Catalog.updateAllProgress > 0 ? "progress" : "spin"+ progress: Math.max(0, Catalog.updateAllProgress)+ Accessible.role: Accessible.ProgressBar+ Accessible.name: "Updating all apps, " + Math.max(0, Catalog.updateAllProgress) + "%"+ }}- UI.Button {- size: "large"- kind: "primary"- visible: page.keys.length > 0+ PillButton {+ visible: !page.updatingAll && page.keys.length > 0+ big: true+ filled: trueenabled: !Catalog.busytext: "Update all"onClicked: Catalog.updateAll()}++ PillButton {+ visible: !page.updatingAll && page.keys.length === 0+ big: true+ enabled: !Catalog.checking+ text: Catalog.checking ? "Checking" : "Check for updates"+ onClicked: Catalog.refresh()+ }}- RowGroup {- visible: page.keys.length > 0+ GridLayout {Layout.fillWidth: true+ columns: page.sideBySide ? 2 : 1+ columnSpacing: 40+ rowSpacing: Metrics.sectionGap++ ColumnLayout {+ Layout.fillWidth: true+ Layout.alignment: Qt.AlignTop+ spacing: Metrics.sectionGap++ ColumnLayout {+ visible: page.keys.length > 0+ Layout.fillWidth: true+ spacing: 0++ SectionHeader {+ title: "Available"+ }++ Repeater {+ model: page.keys++ Item {+ id: entry+ required property string modelData+ required property int index+ readonly property var app: Catalog.app(modelData)+ Layout.fillWidth: true+ implicitHeight: Math.max(60, notes.implicitHeight, button.implicitHeight + 2) + 32++ Rectangle {+ visible: entry.index > 0+ width: parent.width+ height: 1+ color: Metrics.divider+ }++ AppIcon {+ id: icon+ y: 16+ size: 60+ source: entry.app ? entry.app.iconSource : ""++ TapHandler {+ onTapped: page.store.openApp(entry.modelData)+ }+ }++ Column {+ id: notes+ anchors.left: icon.right+ anchors.leftMargin: 16+ anchors.right: button.left+ anchors.rightMargin: 16+ y: 16+ spacing: 4- Repeater {- model: page.keys+ Row {+ width: parent.width+ spacing: 10- AppRow {- required property string modelData- appKey: modelData- onActivated: key => page.store.openApp(key)+ UI.Label {+ id: name+ text: entry.app ? entry.app.name : ""+ size: 15+ font.weight: Font.DemiBold+ width: Math.min(implicitWidth, parent.width)+ }++ UI.Label {+ y: name.baselineOffset - baselineOffset+ width: Math.max(0, parent.width - name.width - 10)+ text: {+ const a = entry.app;+ if (!a) {+ return "";+ }+ const parts = [];+ if (a.newVersion.length > 0) {+ parts.push("Version " + a.newVersion);+ }+ if (a.updateSizeText.length > 0) {+ parts.push(a.updateSizeText);+ }+ return parts.join(", ");+ }+ size: 12.5+ color: Metrics.inkTertiary+ }+ }++ Text {+ width: parent.width+ visible: text.length > 0+ textFormat: Text.StyledText+ wrapMode: Text.Wrap+ font.family: UI.Style.fontFamily+ font.pixelSize: UI.Style.px(13.5)+ lineHeight: 1.5+ color: Metrics.inkSecondary+ linkColor: UI.Style.accent+ // The note is plain text from the catalogue;+ // only the More link is markup.+ text: {+ const a = entry.app;+ if (!a) {+ return "";+ }+ const note = a.releaseNote.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");+ return note.length > 0 ? note + " <a href=\"more\">More</a>" : "";+ }+ onLinkActivated: page.store.openApp(entry.modelData)++ HoverHandler {+ cursorShape: parent.hoveredLink.length > 0 ? Qt.PointingHandCursor : Qt.ArrowCursor+ }+ }+ }++ StoreButton {+ id: button+ anchors.right: parent.right+ y: 18+ app: entry.app+ }+ }+ }+ }++ ColumnLayout {+ visible: page.recent.length > 0+ Layout.fillWidth: true+ spacing: 0++ SectionHeader {+ title: "Updated recently"+ }++ Repeater {+ model: page.recent++ AppListRecent {+ required property string modelData+ Layout.fillWidth: true+ appKey: modelData+ onActivated: key => page.store.openApp(key)+ }+ }}}- }- RowGroup {- Layout.fillWidth: true+ ColumnLayout {+ Layout.preferredWidth: page.sideBySide ? 320 : -1+ Layout.maximumWidth: page.sideBySide ? 320 : Number.POSITIVE_INFINITY+ Layout.fillWidth: !page.sideBySide+ Layout.alignment: Qt.AlignTop+ spacing: 16- InfoRow {- title: "Wild OS updates"- subtitle: "Security fixes and updates for Wild OS itself are in Settings."- last: true+ Rectangle {+ Layout.fillWidth: true+ implicitHeight: autoColumn.implicitHeight + 40+ radius: Metrics.radiusCard+ color: Metrics.card- UI.Button {- size: "small"- anchors.verticalCenter: parent.verticalCenter- text: "Open Settings"- onClicked: Catalog.openSettings("update")+ Column {+ id: autoColumn+ x: 20+ y: 20+ width: parent.width - 40+ spacing: 10++ Item {+ width: parent.width+ height: Math.max(autoTitle.implicitHeight, autoToggle.implicitHeight)++ UI.Label {+ id: autoTitle+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - autoToggle.width - 12+ text: "Update automatically"+ size: 15+ font.weight: Font.Bold+ }++ UI.Toggle {+ id: autoToggle+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ checked: Catalog.autoUpdate+ Accessible.name: "Update automatically"+ onToggled: Catalog.autoUpdate = checked+ }+ }++ UI.Label {+ width: parent.width+ text: "Apps update overnight while your PC is plugged in. An app that's open waits until you close it."+ size: 13+ lineHeight: 1.5+ color: Metrics.inkSecondary+ wrapMode: Text.Wrap+ elide: Text.ElideNone+ }+ }+ }++ Rectangle {+ Layout.fillWidth: true+ implicitHeight: systemColumn.implicitHeight + 40+ radius: Metrics.radiusCard+ color: Metrics.card++ Column {+ id: systemColumn+ x: 20+ y: 20+ width: parent.width - 40+ spacing: 10++ Row {+ width: parent.width+ spacing: 10++ UI.Icon {+ anchors.verticalCenter: parent.verticalCenter+ name: "shield-check"+ size: 20+ color: Metrics.success+ }++ UI.Label {+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - 30+ text: "Wild OS updates"+ size: 15+ font.weight: Font.Bold+ }+ }++ UI.Label {+ width: parent.width+ text: "System updates live in Settings, so this list is only your apps."+ size: 13+ lineHeight: 1.5+ color: Metrics.inkSecondary+ wrapMode: Text.Wrap+ elide: Text.ElideNone+ }++ StoreLink {+ x: -4+ size: 13+ text: "Open Settings"+ onClicked: Catalog.openSettings("update")+ }+ }}}}diff --git a/packages/wildos-store/qml/pages/WindowsAppsPage.qml b/packages/wildos-store/qml/pages/WindowsAppsPage.qmlindex 1c745cc..090591a 100644--- a/packages/wildos-store/qml/pages/WindowsAppsPage.qml+++ b/packages/wildos-store/qml/pages/WindowsAppsPage.qml@@ -3,8 +3,8 @@ import QtQuick.Layoutsimport WildOS.Storeimport WildOS.UI as UI-// The full list behind "Swap your Windows apps": each Windows app people-// know, and the free app that does its job here.+// Windows apps: for the programs that have no free swap, running the+// Windows program itself, set up from Settings.PageFlick {id: page@@ -12,59 +12,39 @@ PageFlick {property string argproperty string kind- readonly property var essentials: Catalog.revision >= 0 ? Catalog.essentials() : []- readonly property int essentialsLeft: {- let n = 0;- for (const k of essentials) {- const a = Catalog.app(k);- if (a && !a.installed) {- n++;- }- }- return n;- }- readonly property bool essentialsBusy: {- for (const k of essentials) {- const a = Catalog.app(k);- if (a && (a.busy || a.queued)) {- return true;- }- }- return false;- }-PageTitle {title: "Windows apps"- subtitle: "Free apps that do what your Windows apps did. Most open the same files, so nothing gets left behind."+ subtitle: "For the programs nothing here replaces, Wild OS can run the Windows version."+ }- UI.Button {- size: "large"- kind: "primary"- enabled: page.essentialsLeft > 0 && !page.essentialsBusy- text: page.essentialsBusy ? "Installing the essentials" : page.essentialsLeft === 0 && page.essentials.length > 0 ? "Essentials installed" : "Install the essentials"- onClicked: Catalog.installEssentials()+ ColumnLayout {+ Layout.fillWidth: true+ spacing: 0++ SectionHeader {+ title: "Run a Windows program"}- }- SwapGrid {- keys: Catalog.revision >= 0 ? Catalog.swaps() : []- onActivated: key => page.store.openApp(key)+ WindowsModeRow {+ title: "Install the Windows program you already have"+ }}- RowGroup {+ ColumnLayout {Layout.fillWidth: true+ spacing: 0- InfoRow {- title: "Need the Windows app itself?"- subtitle: "Wild OS can run many Windows programs in a sandbox. Open the .exe file from Files and Wild OS will offer to install it."- last: true+ SectionHeader {+ title: "Or swap it for a free app"+ linkText: "See all"+ onLinkClicked: page.store.open("swap")+ }- UI.Button {- size: "small"- anchors.verticalCenter: parent.verticalCenter- text: "Windows app settings"- onClicked: Catalog.openSettings("windowsapps")- }+ AppList {+ keys: Catalog.catalogRevision >= 0 ? Catalog.swaps() : []+ maxItems: 6+ showNotes: true+ onActivated: key => page.store.openApp(key)}}}diff --git a/packages/wildos-store/src/catalog.cpp b/packages/wildos-store/src/catalog.cppindex d6b14b8..712eb04 100644--- a/packages/wildos-store/src/catalog.cpp+++ b/packages/wildos-store/src/catalog.cpp@@ -3,6 +3,7 @@#include "flatpakbackend.h"#include "packagekitbackend.h"#include "storeapp.h"+#include "timing.h"#include <AppStreamQt/bundle.h>#include <AppStreamQt/developer.h>@@ -11,18 +12,29 @@#include <AppStreamQt/pool.h>#include <AppStreamQt/screenshot.h>-#include <KService>+#include <KSycoca>+#include <QCoreApplication>+#include <QCryptographicHash>+#include <QDataStream>+#include <QDateTime>+#include <QDir>+#include <QDirIterator>+#include <QElapsedTimer>#include <QFile>-#include <QLoggingCategory>#include <QFileInfo>#include <QJsonArray>#include <QJsonDocument>#include <QJsonObject>#include <QLocale>+#include <QLoggingCategory>#include <QProcess>+#include <QSaveFile>#include <QStandardPaths>+#include <QThreadPool>#include <QTime>+#include <QTimer>+#include <QUrl>#include <algorithm>@@ -68,6 +80,13 @@ const QList<CategoryDef> &gameCategoryDefs()return defs;}+const QString allApps = QStringLiteral("@apps");+const QString allGames = QStringLiteral("@games");++// Bump when the snapshot's layout changes; an older file is then ignored.+constexpr quint32 snapshotMagic = 0x57534331;+constexpr qint32 snapshotVersion = 2;+QString normalise(const QString &id){QString key = id.trimmed().toLower();@@ -106,175 +125,157 @@ int qualityOf(const AppStream::Component &c)}return score;}-}-Catalog::Catalog(QObject *parent)- : QObject(parent)- , m_packagekit(new PackageKitBackend(this))- , m_flatpak(new FlatpakBackend(this))+QString themeIcon(const QString &name){- s_instance = this;- loadCurated();-- connect(m_packagekit, &PackageKitBackend::installedChanged, this, &Catalog::bump);- connect(m_packagekit, &PackageKitBackend::updatesChanged, this, &Catalog::bump);- connect(m_packagekit, &PackageKitBackend::catalogueRefreshed, this, &Catalog::loadOsPool);- connect(m_packagekit, &PackageKitBackend::refreshFinished, this, &Catalog::checkPartDone);- connect(m_packagekit, &PackageKitBackend::progress, this, &Catalog::onProgress);- connect(m_packagekit, &PackageKitBackend::finished, this, &Catalog::onFinished);- connect(m_packagekit, &PackageKitBackend::detailsReady, this, [this](const QString &key, qint64 download, qint64, const QString &version) {- AppState &s = m_states[key];- s.downloadSize = download;- s.candidateVersion = version;- stateChangedFor(key);- });+ return QStringLiteral("image://theme/") + QString::fromUtf8(QUrl::toPercentEncoding(name));+}- connect(m_flatpak, &FlatpakBackend::appstreamChanged, this, &Catalog::loadFlatpakPool);- connect(m_flatpak, &FlatpakBackend::installedChanged, this, &Catalog::bump);- connect(m_flatpak, &FlatpakBackend::refreshFinished, this, &Catalog::checkPartDone);- connect(m_flatpak, &FlatpakBackend::progress, this, &Catalog::onProgress);- connect(m_flatpak, &FlatpakBackend::finished, this, &Catalog::onFinished);- connect(m_flatpak, &FlatpakBackend::metadataReady, this, [this](const QString &appId, const QString &metadata) {- for (auto it = m_records.cbegin(); it != m_records.cend(); ++it) {- if (it->flatpakId == appId) {- AppState &s = m_states[it.key()];- if (metadata.isEmpty()) {- s.metadataFailed = s.flatpakMetadata.isEmpty();- } else {- s.flatpakMetadata = metadata;- s.metadataFailed = false;+// The catalogue's own icon for a component: the largest copy on disk, then+// the remote one, then the theme's. Done while building, because looking for+// files is too slow to do for every card as it is drawn.+QString iconFor(const AppStream::Component &c, bool flat, const QString &flatDir, const QSet<QString> &flatIcons, const Curated *curated)+{+ QString best;+ uint bestSize = 0;+ QString remote;+ QString stock;+ const QList<AppStream::Icon> icons = c.icons();+ for (const AppStream::Icon &icon : icons) {+ if (icon.kind() == AppStream::Icon::KindCached || icon.kind() == AppStream::Icon::KindLocal) {+ if (icon.width() <= bestSize && bestSize > 0) {+ continue;+ }+ // Flathub's icons are looked up in a listing made once per build;+ // a file check for each of thousands of icons took most of it.+ if (flat && !flatDir.isEmpty()) {+ const QString cached = QStringLiteral("%1/icons/%2x%3/%4").arg(flatDir).arg(icon.width()).arg(icon.height()).arg(icon.name());+ if (flatIcons.contains(cached)) {+ best = cached;+ bestSize = icon.width();+ continue;}- stateChangedFor(it.key());}+ const QString path = icon.url().isLocalFile() ? icon.url().toLocalFile() : icon.url().toString();+ if (QFileInfo::exists(path)) {+ best = path;+ bestSize = icon.width();+ }+ } else if (icon.kind() == AppStream::Icon::KindRemote && remote.isEmpty()) {+ remote = icon.url().toString();+ } else if (icon.kind() == AppStream::Icon::KindStock && stock.isEmpty()) {+ stock = icon.name();}- });-- loadOsPool();- m_packagekit->start();- m_flatpak->start();-}--Catalog::~Catalog()-{- s_instance = nullptr;-}--Catalog *Catalog::instance()-{- return s_instance;-}--Catalog *Catalog::create(QQmlEngine *, QJSEngine *)-{- if (!s_instance) {- new Catalog;- }- QJSEngine::setObjectOwnership(s_instance, QJSEngine::CppOwnership);- return s_instance;-}--void Catalog::loadCurated()-{- // The installed copy wins so the list can be tuned without a rebuild;- // the one inside the binary keeps the Store whole if it goes missing.- QFile file(QStringLiteral(WILDOS_STORE_DATADIR "/curated.json"));- if (!file.exists()) {- file.setFileName(QStringLiteral(":/qt/qml/WildOS/Store/data/curated.json"));}- if (!file.open(QIODevice::ReadOnly)) {- return;+ // Catalogue icons on disk first: the remote copies of older catalogue+ // entries are not always kept online.+ if (!best.isEmpty()) {+ return QUrl::fromLocalFile(best).toString();}- const QJsonObject root = QJsonDocument::fromJson(file.readAll()).object();- for (const QJsonValue &v : root.value(QStringLiteral("apps")).toArray()) {- const QJsonObject o = v.toObject();- Curated c;- c.key = o.value(QStringLiteral("key")).toString();- c.ids = strings(o.value(QStringLiteral("ids")));- c.packages = strings(o.value(QStringLiteral("packages")));- c.flatpak = o.value(QStringLiteral("flatpak")).toString();- c.prefer = o.value(QStringLiteral("prefer")).toString();- c.name = o.value(QStringLiteral("name")).toString();- c.summary = o.value(QStringLiteral("summary")).toString();- c.tagline = o.value(QStringLiteral("tagline")).toString();- c.insteadOf = o.value(QStringLiteral("insteadOf")).toString();- c.aliases = strings(o.value(QStringLiteral("aliases")));- c.cardNote = o.value(QStringLiteral("cardNote")).toString();- c.chip = o.value(QStringLiteral("chip")).toString();- c.swapTitle = o.value(QStringLiteral("swapTitle")).toString();- c.swapText = o.value(QStringLiteral("swapText")).toString();- c.description = o.value(QStringLiteral("description")).toString();- c.icon = o.value(QStringLiteral("icon")).toString();- c.desktop = o.value(QStringLiteral("desktop")).toString();- c.category = o.value(QStringLiteral("category")).toString();- m_curated.append(c);+ if (!remote.isEmpty()) {+ return remote;}- m_homeSwaps = strings(root.value(QStringLiteral("homeSwaps")));- m_homeInstalled = strings(root.value(QStringLiteral("homeInstalled")));- m_essentials = strings(root.value(QStringLiteral("essentials")));- const QJsonObject featured = root.value(QStringLiteral("featured")).toObject();- for (auto it = featured.begin(); it != featured.end(); ++it) {- m_featured.insert(it.key(), strings(it.value()));+ if (curated && !curated->icon.isEmpty()) {+ return themeIcon(curated->icon);}- for (const QString &id : strings(root.value(QStringLiteral("hidden")))) {- m_hidden.insert(normalise(id));+ if (!stock.isEmpty()) {+ return themeIcon(stock);}+ return themeIcon(QStringLiteral("application-x-executable"));}-void Catalog::loadOsPool()+QString displayName(const Record &r){- auto pool = std::make_unique<AppStream::Pool>();- pool->setLocale(QLocale::system().name());- // Flathub is read separately so each app knows where it came from.- pool->setFlags(AppStream::Pool::Flags(AppStream::Pool::FlagLoadOsCatalog | AppStream::Pool::FlagLoadOsMetainfo));- AppStream::Pool *raw = pool.get();- connect(raw, &AppStream::Pool::loadFinished, this, [this, raw](bool) {- qCDebug(lcStore) << "Wild OS catalogue loaded" << raw->lastError();- if (m_osPool.get() != raw) {- m_osPool.reset(raw);- }- m_osLoaded = true;- rebuild();- });- pool.release()->loadAsync();+ if (r.curated && !r.curated->name.isEmpty()) {+ return r.curated->name;+ }+ if (!r.flatName.isEmpty()) {+ return r.flatName;+ }+ return r.aptName.isEmpty() ? r.key : r.aptName;}-void Catalog::loadFlatpakPool()+void indexForSearch(Record &r){- const QString dir = m_flatpak->appstreamDir();- if (dir.isEmpty()) {- return;- }- auto pool = new AppStream::Pool;- pool->setLocale(QLocale::system().name());- pool->setFlags(AppStream::Pool::FlagNone);- pool->setLoadStdDataLocations(false);- pool->addExtraDataLocation(dir, AppStream::Metadata::FormatStyleCatalog);- connect(pool, &AppStream::Pool::loadFinished, this, [this, pool](bool ok) {- qCDebug(lcStore) << "Flathub catalogue loaded" << ok << pool->lastError();- m_flatPool.reset(pool);- if (m_osLoaded) {- rebuild();+ r.searchName = displayName(r).toLower();+ QStringList words{r.key, r.aptSummary, r.flatSummary, r.aptName, r.flatName, r.flatpakId};+ words += r.packages;+ if (r.curated) {+ words << r.curated->summary << r.curated->tagline << r.curated->insteadOf;+ words += r.curated->aliases;+ }+ for (const auto *c : {r.apt ? &*r.apt : nullptr, r.flat ? &*r.flat : nullptr}) {+ if (c) {+ words += c->categories();}- });- pool->loadAsync();+ }+ r.searchText = words.join(QLatin1Char(' ')).toLower();}-QString Catalog::flatpakAppstreamDir() const+QHash<QString, QStringList> categoriesFor(const QHash<QString, Record> &records, const QStringList &sorted){- return m_flatpak->appstreamDir();+ QHash<QString, QStringList> out;+ QList<const CategoryDef *> defs;+ for (const CategoryDef &d : appCategoryDefs()) {+ defs << &d;+ }+ for (const CategoryDef &d : gameCategoryDefs()) {+ defs << &d;+ }+ for (const QString &key : sorted) {+ const Record &r = records[key];+ const bool isGame = r.categories.contains(QStringLiteral("Game"));+ out[isGame ? allGames : allApps] << key;+ for (const CategoryDef *d : std::as_const(defs)) {+ const QString id = QString::fromLatin1(d->id);+ if (id.startsWith(QLatin1String("game")) != isGame) {+ continue;+ }+ bool in;+ if (r.curated && !r.curated->category.isEmpty()) {+ in = r.curated->category == id;+ } else {+ in = std::any_of(d->freedesktop.cbegin(), d->freedesktop.cend(), [&r](const QString &c) {+ return r.categories.contains(c);+ });+ }+ if (in) {+ out[id] << key;+ }+ }+ }+ return out;}-void Catalog::rebuild()+struct BuildInput {+ std::shared_ptr<AppStream::Pool> os;+ std::shared_ptr<AppStream::Pool> flat;+ const QList<Curated> *curated;+ QSet<QString> hidden;+ QString flatDir;+};++// Joins both catalogues and the curated file. Runs on a pool thread; it only+// reads the pools, which AppStream guards with its own lock.+CatalogData buildCatalog(const BuildInput &in){- QHash<QString, Record> records;- QHash<QString, QString> aliases;+ CatalogData out;+ QSet<QString> flatIcons;+ if (!in.flatDir.isEmpty()) {+ QDirIterator it(in.flatDir + QStringLiteral("/icons"), QDir::Files, QDirIterator::Subdirectories);+ while (it.hasNext()) {+ flatIcons.insert(it.next());+ }+ }+ QHash<QString, Record> &records = out.records;+ QHash<QString, QString> &aliases = out.aliases;auto addComponent = [&](const AppStream::Component &c, bool flat) {if (c.kind() != AppStream::Component::KindDesktopApp) {return;}const QString key = normalise(c.id());- if (m_hidden.contains(key)) {+ if (in.hidden.contains(key)) {return;}Record &r = records[key];@@ -304,13 +305,13 @@ void Catalog::rebuild()}};- if (m_osPool) {- for (const AppStream::Component &c : m_osPool->componentsByKind(AppStream::Component::KindDesktopApp).toList()) {+ if (in.os) {+ for (const AppStream::Component &c : in.os->componentsByKind(AppStream::Component::KindDesktopApp).toList()) {addComponent(c, false);}}- if (m_flatPool) {- for (const AppStream::Component &c : m_flatPool->componentsByKind(AppStream::Component::KindDesktopApp).toList()) {+ if (in.flat) {+ for (const AppStream::Component &c : in.flat->componentsByKind(AppStream::Component::KindDesktopApp).toList()) {addComponent(c, true);}}@@ -318,7 +319,7 @@ void Catalog::rebuild()// Some apps carry different IDs in each catalogue (Thunderbird is// net.thunderbird.Thunderbird in one and org.mozilla.Thunderbird in the// other); the curated entry joins them under its first ID.- for (const Curated &c : std::as_const(m_curated)) {+ for (const Curated &c : *in.curated) {QString home;for (const QString &id : c.ids) {if (records.contains(normalise(id))) {@@ -380,156 +381,620 @@ void Catalog::rebuild()}}- for (auto it = records.cbegin(); it != records.cend(); ++it) {- for (const QString &pkg : it->packages) {+ for (auto it = records.begin(); it != records.end(); ++it) {+ Record &r = it.value();+ for (const QString &pkg : std::as_const(r.packages)) {if (!aliases.contains(pkg)) {aliases.insert(pkg, it.key());}}- if (!it->flatpakId.isEmpty()) {- aliases.insert(it->flatpakId.toLower(), it.key());+ if (!r.flatpakId.isEmpty()) {+ aliases.insert(r.flatpakId.toLower(), it.key());}- }-- // There are no download counts in either catalogue. An app packaged- // both by Wild OS and on Flathub is almost always a well known one, so- // that stands in for popularity.- for (auto it = records.begin(); it != records.end(); ++it) {- if (it->apt && it->flat) {- it->quality += 4;+ // There are no download counts in either catalogue. An app packaged+ // both by Wild OS and on Flathub is almost always a well known one,+ // so that stands in for popularity.+ if (r.apt && r.flat) {+ r.quality += 4;}- }-- QStringList sorted = records.keys();- std::sort(sorted.begin(), sorted.end(), [&records](const QString &a, const QString &b) {- const Record &ra = records[a];- const Record &rb = records[b];- if (ra.quality != rb.quality) {- return ra.quality > rb.quality;- }- const QString na = ra.curated && !ra.curated->name.isEmpty() ? ra.curated->name : (ra.flat ? ra.flat->name() : ra.apt ? ra.apt->name() : a);- const QString nb = rb.curated && !rb.curated->name.isEmpty() ? rb.curated->name : (rb.flat ? rb.flat->name() : rb.apt ? rb.apt->name() : b);- return na.compare(nb, Qt::CaseInsensitive) < 0;- });-- qCDebug(lcStore) << "apps:" << records.size() << "os:" << (m_osPool ? m_osPool->components().size() : 0)- << "flathub:" << (m_flatPool ? m_flatPool->components().size() : 0);- m_records = std::move(records);- m_aliases = std::move(aliases);- m_sorted = std::move(sorted);-- for (auto it = m_apps.begin(); it != m_apps.end();) {- if (it.value()) {- Q_EMIT it.value()->dataChanged();- Q_EMIT it.value()->stateChanged();- ++it;- } else {- it = m_apps.erase(it);+ r.hasApt = r.apt.has_value() || !r.packages.isEmpty();+ r.hasFlat = r.flat.has_value();+ if (r.apt) {+ r.aptName = r.apt->name();+ r.aptSummary = r.apt->summary();+ r.aptIcon = iconFor(*r.apt, false, in.flatDir, flatIcons, r.curated);}+ if (r.flat) {+ r.flatName = r.flat->name();+ r.flatSummary = r.flat->summary();+ r.flatIcon = iconFor(*r.flat, true, in.flatDir, flatIcons, r.curated);+ }+ if (r.aptIcon.isEmpty() && r.flatIcon.isEmpty() && r.curated && !r.curated->icon.isEmpty()) {+ r.aptIcon = themeIcon(r.curated->icon);+ }+ indexForSearch(r);}- if (!m_ready) {- m_ready = true;- Q_EMIT readyChanged();+ QStringList sorted = records.keys();+ QHash<QString, QString> names;+ names.reserve(records.size());+ for (auto it = records.cbegin(); it != records.cend(); ++it) {+ names.insert(it.key(), displayName(it.value()));}- ++m_revision;- Q_EMIT revisionChanged();+ std::sort(sorted.begin(), sorted.end(), [&records, &names](const QString &a, const QString &b) {+ const int qa = records[a].quality;+ const int qb = records[b].quality;+ if (qa != qb) {+ return qa > qb;+ }+ // The key settles ties, so the same catalogue always sorts the same+ // way and a rebuild that changes nothing leaves the lists alone.+ const int byName = names[a].compare(names[b], Qt::CaseInsensitive);+ return byName != 0 ? byName < 0 : a < b;+ });+ out.sorted = std::move(sorted);+ out.categories = categoriesFor(records, out.sorted);+ return out;}-void Catalog::bump()+// Every file the Wild OS catalogue is read from, by path, size and time.+QString osInputs(){- for (auto it = m_apps.cbegin(); it != m_apps.cend(); ++it) {- if (it.value()) {- Q_EMIT it.value()->stateChanged();+ QCryptographicHash hash(QCryptographicHash::Sha1);+ static const QStringList roots = {+ QStringLiteral("/usr/share/swcatalog"), QStringLiteral("/var/lib/swcatalog"), QStringLiteral("/var/cache/swcatalog"),+ QStringLiteral("/usr/share/app-info"), QStringLiteral("/var/lib/app-info"), QStringLiteral("/var/cache/app-info"),+ QStringLiteral("/usr/share/metainfo"), QStringLiteral("/usr/share/appdata"),+ };+ QStringList entries;+ for (const QString &root : roots) {+ QDirIterator it(root, QDir::Files | QDir::NoDotAndDotDot, QDirIterator::Subdirectories | QDirIterator::FollowSymlinks);+ while (it.hasNext()) {+ it.next();+ const QFileInfo info = it.fileInfo();+ entries << QStringLiteral("%1 %2 %3").arg(info.filePath()).arg(info.size()).arg(info.lastModified().toMSecsSinceEpoch());}}- ++m_revision;- Q_EMIT revisionChanged();+ entries.sort();+ hash.addData(entries.join(QLatin1Char('\n')).toUtf8());+ hash.addData(QLocale::system().name().toUtf8());+ return QString::fromLatin1(hash.result().toHex());}-void Catalog::stateChangedFor(const QString &key)+QString flatInputs(const QString &dir){- if (auto a = m_apps.value(key)) {- Q_EMIT a->stateChanged();+ if (dir.isEmpty()) {+ return {};}- Q_EMIT appStateChanged(key);+ QFileInfo info(dir + QStringLiteral("/appstream.xml.gz"));+ if (!info.exists()) {+ info.setFile(dir + QStringLiteral("/appstream.xml"));+ }+ return QStringLiteral("%1 %2 %3 %4").arg(info.canonicalFilePath()).arg(info.size()).arg(info.lastModified().toMSecsSinceEpoch()).arg(QLocale::system().name());}-const Record *Catalog::record(const QString &key) const+QString snapshotPath(){- auto it = m_records.constFind(key);- return it == m_records.cend() ? nullptr : &it.value();+ return QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation) + QStringLiteral("/wildos-store/catalogue.bin");}-QString Catalog::keyFor(const QString &id) const+template<typename Work, typename Then>+void runAsync(QObject *context, Work work, Then then){- const QString key = normalise(id);- if (m_records.contains(key)) {- return key;- }- return m_aliases.value(key);+ QThreadPool::globalInstance()->start([context = QPointer<QObject>(context), work, then]() mutable {+ auto result = work();+ if (!context) {+ return;+ }+ QMetaObject::invokeMethod(+ context.data(),+ [context, then, result = std::move(result)]() mutable {+ if (context) {+ then(std::move(result));+ }+ },+ Qt::QueuedConnection);+ });}-StoreApp *Catalog::app(const QString &key)+// Pools are QObjects that live on the window's thread; the last reference+// may go on a pool thread, so they are always deleted from their own.+std::shared_ptr<AppStream::Pool> sharedPool(AppStream::Pool *pool){- if (key.isEmpty()) {- return nullptr;- }- const QString k = keyFor(key).isEmpty() ? key : keyFor(key);- if (auto existing = m_apps.value(k)) {- return existing;- }- auto a = new StoreApp(this, k);- QJSEngine::setObjectOwnership(a, QJSEngine::CppOwnership);- m_apps.insert(k, a);- return a;+ return std::shared_ptr<AppStream::Pool>(pool, [](AppStream::Pool *p) {+ p->deleteLater();+ });}--QString Catalog::resolve(const QString &query) const-{- QString q = query.trimmed();- // appstream://org.kde.krita, appstream:org.kde.krita and the- // apt-style appstream:krita all name the same app.- if (q.startsWith(QLatin1String("appstream:"), Qt::CaseInsensitive)) {- q = q.mid(10);- while (q.startsWith(QLatin1Char('/'))) {- q.remove(0, 1);- }- q = q.section(QLatin1Char('?'), 0, 0);- }- if (q.startsWith(QLatin1String("app/"))) {- q = q.section(QLatin1Char('/'), 1, 1);- }- return keyFor(q);}-QString Catalog::source(const QString &key) const+Catalog::Catalog(QObject *parent)+ : QObject(parent)+ , m_packagekit(new PackageKitBackend(this))+ , m_flatpak(new FlatpakBackend(this)){- const Record *r = record(key);- if (!r) {- return {};- }- const QString installedFrom = installedSource(key);- if (!installedFrom.isEmpty()) {- return installedFrom;- }- const QString chosen = m_states.value(key).chosenSource;- const bool hasApt = r->apt.has_value() || !r->packages.isEmpty();- const bool hasFlat = r->flat.has_value() || (!r->flatpakId.isEmpty() && flathubAvailable());- if (chosen == QLatin1String("apt") && hasApt) {- return chosen;- }- if (chosen == QLatin1String("flatpak") && hasFlat) {- return chosen;- }- if (r->curated && r->curated->prefer == QLatin1String("apt") && hasApt) {- return QStringLiteral("apt");- }- // Flathub apps run in a sandbox and are usually newer, so they win when- // an app is in both catalogues.- if (hasFlat && r->flat) {- return QStringLiteral("flatpak");- }+ s_instance = this;+ loadCurated();++ // An app installed or removed changes which launchers exist.+ auto installsChanged = [this] {+ StoreApp::forgetServices();+ bumpState();+ };+ connect(m_packagekit, &PackageKitBackend::installedChanged, this, installsChanged);+ connect(m_packagekit, &PackageKitBackend::updatesChanged, this, &Catalog::bumpState);+ connect(m_packagekit, &PackageKitBackend::catalogueRefreshed, this, &Catalog::loadOsPool);+ connect(m_packagekit, &PackageKitBackend::refreshFinished, this, &Catalog::checkPartDone);+ connect(m_packagekit, &PackageKitBackend::progress, this, &Catalog::onProgress);+ connect(m_packagekit, &PackageKitBackend::finished, this, &Catalog::onFinished);+ connect(m_packagekit, &PackageKitBackend::detailsReady, this, [this](const QString &key, qint64 download, qint64, const QString &version) {+ AppState &s = m_states[key];+ s.downloadSize = download;+ s.candidateVersion = version;+ stateChangedFor(key);+ });++ connect(m_flatpak, &FlatpakBackend::appstreamChanged, this, &Catalog::loadFlatpakPool);+ connect(m_flatpak, &FlatpakBackend::installedChanged, this, installsChanged);+ connect(m_flatpak, &FlatpakBackend::updatesChanged, this, &Catalog::bumpState);+ connect(m_flatpak, &FlatpakBackend::unavailable, this, [this] {+ // No Flathub catalogue is coming, so stop waiting for one.+ if (!m_flatLoaded) {+ m_flatLoaded = true;+ rebuild();+ }+ });+ connect(m_flatpak, &FlatpakBackend::refreshFinished, this, &Catalog::checkPartDone);+ connect(m_flatpak, &FlatpakBackend::progress, this, &Catalog::onProgress);+ connect(m_flatpak, &FlatpakBackend::finished, this, &Catalog::onFinished);+ connect(m_flatpak, &FlatpakBackend::planReady, this, &Catalog::onPlan);+ connect(m_flatpak, &FlatpakBackend::metadataReady, this, [this](const QString &appId, const QString &metadata) {+ if (m_detailsAsked.contains(appId)) {+ qCInfo(lcStore) << "timing: app page details for" << appId << "arrived" << storeClock() - m_detailsAsked.take(appId) << "ms after the page asked";+ }+ for (auto it = m_records.cbegin(); it != m_records.cend(); ++it) {+ if (it->flatpakId == appId) {+ AppState &s = m_states[it.key()];+ if (metadata.isEmpty()) {+ s.metadataFailed = s.flatpakMetadata.isEmpty();+ } else {+ s.flatpakMetadata = metadata;+ s.metadataFailed = false;+ }+ stateChangedFor(it.key());+ }+ }+ });++ // Names and icons of installed apps come from KDE's service cache;+ // StoreApp keeps what it read until the cache or the installs change.+ // Queued: a lookup made while a binding reads an app's name can find the+ // cache out of date and announce it there and then, which would make+ // that binding read itself again.+ connect(KSycoca::self(), &KSycoca::databaseChanged, this, [this] {+ StoreApp::forgetServices();+ bumpState();+ }, Qt::QueuedConnection);++ auto enabled = new QProcess(this);+ connect(enabled, &QProcess::finished, this, [this, enabled](int code) {+ enabled->deleteLater();+ m_autoUpdate = code == 0;+ Q_EMIT autoUpdateChanged();+ });+ enabled->start(QStringLiteral("systemctl"), {QStringLiteral("--user"), QStringLiteral("--quiet"), QStringLiteral("is-enabled"), QStringLiteral("wildos-store-update.timer")});++ const qint64 began = storeClock();+ if (loadSnapshot()) {+ qCInfo(lcStore) << "timing: snapshot read in" << storeClock() - began << "ms," << m_records.size() << "apps";+ // The snapshot fills the window, so reading the catalogues and asking+ // the package systems can wait until it is on screen instead of+ // competing with it for the processor. The timer covers a window+ // that never draws.+ QTimer::singleShot(1500, this, &Catalog::startBackgroundWork);+ return;+ }+ startBackgroundWork();+}++void Catalog::startBackgroundWork()+{+ if (m_started) {+ return;+ }+ m_started = true;+ qCInfo(lcStore) << "timing: catalogues and package systems started at" << storeClock() << "ms";+ loadOsPool();+ m_packagekit->start();+ m_flatpak->start();+}++Catalog::~Catalog()+{+ s_instance = nullptr;+}++Catalog *Catalog::instance()+{+ return s_instance;+}++Catalog *Catalog::create(QQmlEngine *, QJSEngine *)+{+ if (!s_instance) {+ new Catalog;+ }+ QJSEngine::setObjectOwnership(s_instance, QJSEngine::CppOwnership);+ return s_instance;+}++void Catalog::loadCurated()+{+ // The installed copy wins so the list can be tuned without a rebuild;+ // the one inside the binary keeps the Store whole if it goes missing.+ QFile file(QStringLiteral(WILDOS_STORE_DATADIR "/curated.json"));+ if (!file.exists()) {+ file.setFileName(QStringLiteral(":/qt/qml/WildOS/Store/data/curated.json"));+ }+ if (!file.open(QIODevice::ReadOnly)) {+ return;+ }+ const QJsonObject root = QJsonDocument::fromJson(file.readAll()).object();+ for (const QJsonValue &v : root.value(QStringLiteral("apps")).toArray()) {+ const QJsonObject o = v.toObject();+ Curated c;+ c.key = o.value(QStringLiteral("key")).toString();+ c.ids = strings(o.value(QStringLiteral("ids")));+ c.packages = strings(o.value(QStringLiteral("packages")));+ c.flatpak = o.value(QStringLiteral("flatpak")).toString();+ c.prefer = o.value(QStringLiteral("prefer")).toString();+ c.name = o.value(QStringLiteral("name")).toString();+ c.summary = o.value(QStringLiteral("summary")).toString();+ c.tagline = o.value(QStringLiteral("tagline")).toString();+ c.insteadOf = o.value(QStringLiteral("insteadOf")).toString();+ c.aliases = strings(o.value(QStringLiteral("aliases")));+ c.cardNote = o.value(QStringLiteral("cardNote")).toString();+ c.chip = o.value(QStringLiteral("chip")).toString();+ c.swapTitle = o.value(QStringLiteral("swapTitle")).toString();+ c.swapText = o.value(QStringLiteral("swapText")).toString();+ c.description = o.value(QStringLiteral("description")).toString();+ c.icon = o.value(QStringLiteral("icon")).toString();+ c.desktop = o.value(QStringLiteral("desktop")).toString();+ c.category = o.value(QStringLiteral("category")).toString();+ m_curated.append(c);+ }+ m_homeSwaps = strings(root.value(QStringLiteral("homeSwaps")));+ m_homeInstalled = strings(root.value(QStringLiteral("homeInstalled")));+ m_essentials = strings(root.value(QStringLiteral("essentials")));+ const QJsonObject featured = root.value(QStringLiteral("featured")).toObject();+ for (auto it = featured.begin(); it != featured.end(); ++it) {+ m_featured.insert(it.key(), strings(it.value()));+ }+ for (const QString &id : strings(root.value(QStringLiteral("hidden")))) {+ m_hidden.insert(normalise(id));+ }+}++void Catalog::loadOsPool()+{+ const qint64 began = storeClock();+ runAsync(this, osInputs, [this, began](QString inputs) {+ // PackageKit's refresh often finds nothing new; reading the same+ // files again would only rebuild the same catalogue.+ if (m_osLoaded && inputs == m_osInputs) {+ qCInfo(lcStore) << "timing: Wild OS catalogue unchanged, not read again (checked in" << storeClock() - began << "ms)";+ return;+ }+ auto pool = new AppStream::Pool;+ pool->setLocale(QLocale::system().name());+ // Flathub is read separately so each app knows where it came from.+ pool->setFlags(AppStream::Pool::Flags(AppStream::Pool::FlagLoadOsCatalog | AppStream::Pool::FlagLoadOsMetainfo));+ connect(pool, &AppStream::Pool::loadFinished, this, [this, pool, began, inputs](bool) {+ qCInfo(lcStore) << "timing: Wild OS catalogue loaded at" << storeClock() << "ms, took" << storeClock() - began << "ms" << pool->lastError();+ m_osPool = sharedPool(pool);+ m_osInputs = inputs;+ m_osLoaded = true;+ rebuild();+ });+ pool->loadAsync();+ });+}++void Catalog::loadFlatpakPool()+{+ const QString dir = m_flatpak->appstreamDir();+ if (dir.isEmpty()) {+ return;+ }+ const qint64 began = storeClock();+ runAsync(this, [dir] { return flatInputs(dir); }, [this, dir, began](QString inputs) {+ if (m_flatPool && inputs == m_flatInputs) {+ qCInfo(lcStore) << "timing: Flathub catalogue unchanged, not read again";+ return;+ }+ auto pool = new AppStream::Pool;+ pool->setLocale(QLocale::system().name());+ pool->setFlags(AppStream::Pool::FlagNone);+ pool->setLoadStdDataLocations(false);+ pool->addExtraDataLocation(dir, AppStream::Metadata::FormatStyleCatalog);+ connect(pool, &AppStream::Pool::loadFinished, this, [this, pool, began, inputs](bool ok) {+ qCInfo(lcStore) << "timing: Flathub catalogue loaded at" << storeClock() << "ms, took" << storeClock() - began << "ms" << ok << pool->lastError();+ m_flatPool = sharedPool(pool);+ m_flatInputs = inputs;+ m_flatLoaded = true;+ rebuild();+ });+ pool->loadAsync();+ });+}++QString Catalog::flatpakAppstreamDir() const+{+ return m_flatpak->appstreamDir();+}++void Catalog::rebuild()+{+ if (!m_osLoaded) {+ return;+ }+ // With a snapshot on screen, a catalogue without Flathub would take most+ // apps away until Flathub's arrived, so wait for both.+ if (m_fromSnapshot && !m_flatLoaded && !m_flatInputs.isEmpty()) {+ return;+ }+ if (m_building) {+ m_rebuildAgain = true;+ return;+ }+ m_building = true;+ BuildInput input{m_osPool, m_flatPool, &m_curated, m_hidden, m_flatpak->appstreamDir()};+ const qint64 began = storeClock();+ runAsync(this, [input] { return buildCatalog(input); }, [this, began](CatalogData data) {+ m_building = false;+ adopt(std::move(data), storeClock() - began);+ if (m_rebuildAgain) {+ m_rebuildAgain = false;+ rebuild();+ }+ });+}++void Catalog::adopt(CatalogData data, qint64 built)+{+ QElapsedTimer took;+ took.start();+ // Lists only need drawing again when the apps in them changed, not when+ // the same apps were read again or gained their full details.+ bool listsChanged = data.sorted != m_sorted || data.aliases != m_aliases;+ if (!listsChanged) {+ for (auto it = data.records.cbegin(); it != data.records.cend() && !listsChanged; ++it) {+ const Record *old = record(it.key());+ listsChanged = !old || old->aptName != it->aptName || old->flatName != it->flatName || old->aptIcon != it->aptIcon+ || old->flatIcon != it->flatIcon || old->aptSummary != it->aptSummary || old->flatSummary != it->flatSummary+ || old->hasFlat != it->hasFlat || old->hasApt != it->hasApt;+ }+ }+ m_records = std::move(data.records);+ m_aliases = std::move(data.aliases);+ m_sorted = std::move(data.sorted);+ m_categories = std::move(data.categories);+ m_fromSnapshot = false;++ for (auto it = m_apps.begin(); it != m_apps.end();) {+ if (it.value()) {+ Q_EMIT it.value()->dataChanged();+ Q_EMIT it.value()->stateChanged();+ ++it;+ } else {+ it = m_apps.erase(it);+ }+ }+ if (!m_ready) {+ m_ready = true;+ Q_EMIT readyChanged();+ }+ if (listsChanged) {+ bumpCatalog();+ }+ qCInfo(lcStore) << "timing: rebuild took" << built << "ms on a worker and" << took.elapsed() << "ms on the UI thread, at" << storeClock()+ << "ms," << m_records.size() << "apps," << (listsChanged ? "lists changed" : "lists unchanged");+ if (m_osLoaded && (m_flatLoaded || m_flatpak->appstreamDir().isEmpty())) {+ saveSnapshot();+ }+}++bool Catalog::loadSnapshot()+{+ QFile file(snapshotPath());+ if (!file.open(QIODevice::ReadOnly)) {+ return false;+ }+ const QByteArray bytes = file.readAll();+ QDataStream in(bytes);+ in.setVersion(QDataStream::Qt_6_8);+ quint32 magic = 0;+ qint32 version = 0;+ QString locale;+ in >> magic >> version >> locale;+ if (magic != snapshotMagic || version != snapshotVersion || locale != QLocale::system().name()) {+ return false;+ }+ QHash<QString, const Curated *> curated;+ for (const Curated &c : std::as_const(m_curated)) {+ curated.insert(c.key, &c);+ }+ QString osIn, flatIn;+ QStringList sorted;+ QHash<QString, QString> aliases;+ QStringList flatInstalled, aptInstalled;+ qint32 count = 0;+ in >> osIn >> flatIn >> sorted >> aliases >> flatInstalled >> aptInstalled >> count;+ QHash<QString, Record> records;+ records.reserve(count);+ for (qint32 i = 0; i < count && in.status() == QDataStream::Ok; ++i) {+ Record r;+ QString curatedKey;+ in >> r.key >> curatedKey >> r.packages >> r.flatpakId >> r.flatpakRef >> r.categories >> r.quality >> r.hasApt >> r.hasFlat >> r.aptName+ >> r.flatName >> r.aptSummary >> r.flatSummary >> r.aptIcon >> r.flatIcon >> r.searchName >> r.searchText;+ r.curated = curated.value(curatedKey);+ records.insert(r.key, r);+ }+ if (in.status() != QDataStream::Ok) {+ return false;+ }+ m_records = std::move(records);+ m_aliases = std::move(aliases);+ m_sorted = std::move(sorted);+ m_categories = categoriesFor(m_records, m_sorted);+ // Kept so the first rebuild knows whether Flathub's catalogue is coming.+ m_flatInputs = flatIn;+ Q_UNUSED(osIn)+ m_flatpak->seedInstalled(QSet<QString>(flatInstalled.begin(), flatInstalled.end()));+ m_packagekit->seedInstalled(QSet<QString>(aptInstalled.begin(), aptInstalled.end()));+ m_fromSnapshot = true;+ m_ready = true;+ return true;+}++void Catalog::saveSnapshot()+{+ struct Saved {+ QHash<QString, Record> records;+ QHash<QString, QString> aliases;+ QStringList sorted;+ QString osInputs, flatInputs;+ QStringList flatInstalled, aptInstalled;+ };+ const QSet<QString> flat = m_flatpak->installed();+ const QSet<QString> apt = m_packagekit->installed();+ Saved saved{m_records, m_aliases, m_sorted, m_osInputs, m_flatInputs, QStringList(flat.begin(), flat.end()), QStringList(apt.begin(), apt.end())};+ QThreadPool::globalInstance()->start([saved = std::move(saved)] {+ const qint64 began = storeClock();+ QByteArray bytes;+ QDataStream out(&bytes, QIODevice::WriteOnly);+ out.setVersion(QDataStream::Qt_6_8);+ out << snapshotMagic << snapshotVersion << QLocale::system().name();+ out << saved.osInputs << saved.flatInputs << saved.sorted << saved.aliases << saved.flatInstalled << saved.aptInstalled+ << qint32(saved.records.size());+ for (const Record &r : saved.records) {+ out << r.key << (r.curated ? r.curated->key : QString()) << r.packages << r.flatpakId << r.flatpakRef << r.categories << r.quality << r.hasApt+ << r.hasFlat << r.aptName << r.flatName << r.aptSummary << r.flatSummary << r.aptIcon << r.flatIcon << r.searchName << r.searchText;+ }+ const QString path = snapshotPath();+ QDir().mkpath(QFileInfo(path).absolutePath());+ QSaveFile file(path);+ if (file.open(QIODevice::WriteOnly) && file.write(bytes) == bytes.size() && file.commit()) {+ qCInfo(lcStore) << "timing: snapshot saved," << bytes.size() << "bytes in" << storeClock() - began << "ms";+ }+ });+}++void Catalog::bumpCatalog()+{+ ++m_catalogRevision;+ Q_EMIT catalogRevisionChanged();+ Q_EMIT revisionChanged();+}++void Catalog::bumpState()+{+ for (auto it = m_apps.cbegin(); it != m_apps.cend(); ++it) {+ if (it.value()) {+ Q_EMIT it.value()->stateChanged();+ }+ }+ ++m_stateRevision;+ Q_EMIT stateRevisionChanged();+ Q_EMIT revisionChanged();+}++void Catalog::stateChangedFor(const QString &key)+{+ if (auto a = m_apps.value(key)) {+ Q_EMIT a->stateChanged();+ }+ Q_EMIT appStateChanged(key);+}++const Record *Catalog::record(const QString &key) const+{+ auto it = m_records.constFind(key);+ return it == m_records.cend() ? nullptr : &it.value();+}++QString Catalog::keyFor(const QString &id) const+{+ const QString key = normalise(id);+ if (m_records.contains(key)) {+ return key;+ }+ return m_aliases.value(key);+}++StoreApp *Catalog::app(const QString &key)+{+ if (key.isEmpty()) {+ return nullptr;+ }+ if (auto existing = m_apps.value(key)) {+ return existing;+ }+ const QString found = keyFor(key);+ const QString k = found.isEmpty() ? key : found;+ if (auto existing = m_apps.value(k)) {+ return existing;+ }+ auto a = new StoreApp(this, k);+ QJSEngine::setObjectOwnership(a, QJSEngine::CppOwnership);+ m_apps.insert(k, a);+ return a;+}++QString Catalog::resolve(const QString &query) const+{+ QString q = query.trimmed();+ // appstream://org.kde.krita, appstream:org.kde.krita and the+ // apt-style appstream:krita all name the same app.+ if (q.startsWith(QLatin1String("appstream:"), Qt::CaseInsensitive)) {+ q = q.mid(10);+ while (q.startsWith(QLatin1Char('/'))) {+ q.remove(0, 1);+ }+ q = q.section(QLatin1Char('?'), 0, 0);+ }+ if (q.startsWith(QLatin1String("app/"))) {+ q = q.section(QLatin1Char('/'), 1, 1);+ }+ return keyFor(q);+}++QString Catalog::source(const QString &key) const+{+ const Record *r = record(key);+ if (!r) {+ return {};+ }+ const QString installedFrom = installedSource(key);+ if (!installedFrom.isEmpty()) {+ return installedFrom;+ }+ const QString chosen = m_states.value(key).chosenSource;+ const bool hasApt = r->hasApt;+ const bool hasFlat = r->hasFlat || (!r->flatpakId.isEmpty() && flathubAvailable());+ if (chosen == QLatin1String("apt") && hasApt) {+ return chosen;+ }+ if (chosen == QLatin1String("flatpak") && hasFlat) {+ return chosen;+ }+ if (r->curated && r->curated->prefer == QLatin1String("apt") && hasApt) {+ return QStringLiteral("apt");+ }+ // Flathub apps run in a sandbox and are usually newer, so they win when+ // an app is in both catalogues.+ if (hasFlat && r->hasFlat) {+ return QStringLiteral("flatpak");+ }if (hasApt) {return QStringLiteral("apt");}@@ -598,9 +1063,41 @@ int Catalog::updateCount() constreturn updates().size();}+int Catalog::workingCount() const+{+ int count = 0;+ for (const Job &j : m_jobs) {+ count += j.keys.size();+ }+ return count;+}++int Catalog::updateAllProgress() const+{+ // One figure for every app "Update all" started, so its button can show+ // a single ring.+ int sum = 0;+ int count = 0;+ bool any = false;+ for (const Job &j : m_jobs) {+ if (!j.all) {+ continue;+ }+ any = true;+ for (const QString &key : j.keys) {+ sum += qMax(0, m_states.value(key).progress);+ ++count;+ }+ }+ if (!any) {+ return -1;+ }+ return count > 0 ? sum / count : 0;+}+bool Catalog::flathubAvailable() const{- return !m_flatpak->appstreamDir().isEmpty();+ return !m_flatpak->appstreamDir().isEmpty() || !m_flatInputs.isEmpty();}QVariantList Catalog::appCategories() const@@ -639,6 +1136,32 @@ QString Catalog::categoryLabel(const QString &id) constreturn QStringLiteral("All apps");}+QString Catalog::pickImage(const QVariantList &images, int width, int height) const+{+ QString best;+ int bestWidth = 0;+ QString largest;+ int largestWidth = -1;+ for (const QVariant &v : images) {+ const QVariantMap m = v.toMap();+ const int w = m.value(QStringLiteral("width")).toInt();+ const int h = m.value(QStringLiteral("height")).toInt();+ const QString url = m.value(QStringLiteral("url")).toString();+ // Sizes the catalogue leaves out (often the original) count as large.+ const int effective = w > 0 ? w : 100000;+ if (effective > largestWidth) {+ largest = url;+ largestWidth = effective;+ }+ const bool fits = w <= 0 || (w >= width && (h <= 0 || h >= height));+ if (fits && (best.isEmpty() || effective < bestWidth)) {+ best = url;+ bestWidth = effective;+ }+ }+ return best.isEmpty() ? largest : best;+}+QStringList Catalog::homeSwaps() const{QStringList out;@@ -697,60 +1220,32 @@ QStringList Catalog::essentials() const}return out;}--QStringList Catalog::featured(const QString &list) const-{- QStringList out;- for (const QString &k : m_featured.value(list)) {- const QString key = keyFor(k);- if (!key.isEmpty() && !out.contains(key)) {- out << key;- }- }- return out;-}--QStringList Catalog::category(const QString &id, int limit) const-{- QStringList wanted;- bool games = id.startsWith(QLatin1String("game"));- for (const CategoryDef &d : appCategoryDefs()) {- if (id == QLatin1String(d.id)) {- wanted = d.freedesktop;- }- }- for (const CategoryDef &d : gameCategoryDefs()) {- if (id == QLatin1String(d.id)) {- wanted = d.freedesktop;- }- }-- QStringList out;- for (const QString &key : m_sorted) {- const Record &r = m_records[key];- const bool isGame = r.categories.contains(QStringLiteral("Game"));- if (isGame != games) {- continue;- }- if (!wanted.isEmpty()) {- if (r.curated && !r.curated->category.isEmpty()) {- if (r.curated->category != id) {- continue;- }- } else if (!std::any_of(wanted.cbegin(), wanted.cend(), [&r](const QString &c) {- return r.categories.contains(c);- })) {- continue;- }- }- out << key;- if (limit > 0 && out.size() >= limit) {- break;++QStringList Catalog::featured(const QString &list) const+{+ QStringList out;+ for (const QString &k : m_featured.value(list)) {+ const QString key = keyFor(k);+ if (!key.isEmpty() && !out.contains(key)) {+ out << key;}}return out;}+QStringList Catalog::category(const QString &id, int limit) const+{+ bool known = false;+ for (const auto *defs : {&appCategoryDefs(), &gameCategoryDefs()}) {+ for (const CategoryDef &d : *defs) {+ known = known || id == QLatin1String(d.id);+ }+ }+ const QString list = known ? id : id.startsWith(QLatin1String("game")) ? allGames : allApps;+ const QStringList &all = m_categories[list];+ return limit > 0 ? all.mid(0, limit) : all;+}+QStringList Catalog::swapMatches(const QString &text) const{const QString q = text.trimmed().toLower();@@ -775,82 +1270,97 @@ QStringList Catalog::swapMatches(const QString &text) constQStringList Catalog::search(const QString &text) const{- const QString q = text.trimmed();+ const QString q = text.trimmed().toLower();if (q.isEmpty()) {return {};}- QHash<QString, uint> scores;- auto collect = [&](AppStream::Pool *pool) {- if (!pool) {- return;+ QElapsedTimer took;+ took.start();+ // Matched against text gathered when the catalogue was built, rather+ // than through AppStream, so it runs as someone types and works from the+ // snapshot before either catalogue has loaded.+ const QStringList words = q.split(QLatin1Char(' '), Qt::SkipEmptyParts);+ QList<QPair<uint, QString>> scored;+ for (auto it = m_records.cbegin(); it != m_records.cend(); ++it) {+ const Record &r = it.value();+ uint score = 0;+ if (r.searchName == q) {+ score = 1000000;+ } else if (r.searchName.startsWith(q)) {+ score = 500000;+ } else if (r.searchName.contains(QLatin1Char(' ') + q)) {+ score = 200000;+ } else if (r.searchName.contains(q)) {+ score = 100000;}- for (const AppStream::Component &c : pool->search(q).toList()) {- if (c.kind() != AppStream::Component::KindDesktopApp) {- continue;- }- const QString key = keyFor(c.id());- if (key.isEmpty()) {- continue;+ bool all = true;+ for (const QString &w : words) {+ if (!r.searchName.contains(w) && !r.searchText.contains(w)) {+ all = false;+ break;}- scores[key] = std::max(scores.value(key), c.sortScore());}- };- collect(m_osPool.get());- collect(m_flatPool.get());-- const QString lq = q.toLower();- for (auto it = m_records.cbegin(); it != m_records.cend(); ++it) {- const Record &r = it.value();- QString name = r.curated && !r.curated->name.isEmpty() ? r.curated->name : (r.flat ? r.flat->name() : r.apt ? r.apt->name() : QString());- name = name.toLower();- uint bonus = 0;- if (name == lq) {- bonus = 1000000;- } else if (name.startsWith(lq)) {- bonus = 500000;+ if (!score && !all) {+ continue;}- if (bonus) {- scores[it.key()] = scores.value(it.key()) + bonus;+ if (all) {+ score += 10000;}+ scored.append({score + uint(r.quality) * 10, it.key()});}-- QStringList out = scores.keys();- std::sort(out.begin(), out.end(), [&](const QString &a, const QString &b) {- const uint sa = scores.value(a) + uint(m_records[a].quality) * 10;- const uint sb = scores.value(b) + uint(m_records[b].quality) * 10;- if (sa != sb) {- return sa > sb;+ std::sort(scored.begin(), scored.end(), [](const auto &a, const auto &b) {+ if (a.first != b.first) {+ return a.first > b.first;}- return a < b;+ return a.second < b.second;});+ QStringList out;+ out.reserve(scored.size());+ for (const auto &s : std::as_const(scored)) {+ out << s.second;+ }// Apps that stand in for the Windows app someone typed come first.const QStringList swapsFirst = swapMatches(q);for (auto it = swapsFirst.crbegin(); it != swapsFirst.crend(); ++it) {out.removeAll(*it);out.prepend(*it);}+ qCInfo(lcStore) << "timing: search" << q << "took" << took.elapsed() << "ms," << out.size() << "results";return out;}QStringList Catalog::installedApps() const{- QStringList out;+ QElapsedTimer took;+ took.start();+ // Names are read once each rather than in every comparison: an installed+ // app's name comes from KDE's service cache.+ QList<QPair<QString, QString>> named;for (const QString &key : m_sorted) {if (isInstalled(key)) {- out << key;+ named.append({const_cast<Catalog *>(this)->app(key)->name(), key});}}- std::sort(out.begin(), out.end(), [this](const QString &a, const QString &b) {- auto na = const_cast<Catalog *>(this)->app(a)->name();- auto nb = const_cast<Catalog *>(this)->app(b)->name();- return na.compare(nb, Qt::CaseInsensitive) < 0;+ std::sort(named.begin(), named.end(), [](const auto &a, const auto &b) {+ return a.first.compare(b.first, Qt::CaseInsensitive) < 0;});+ QStringList out;+ for (const auto &n : std::as_const(named)) {+ out << n.second;+ }+ qCInfo(lcStore) << "timing: installed list took" << took.elapsed() << "ms";return out;}QStringList Catalog::updates() const{QStringList out;+ // Only installed apps can have updates; there are far fewer of those.+ const QSet<QString> flat = m_flatpak->updates();+ const QSet<QString> apt = m_packagekit->updates();+ if (flat.isEmpty() && apt.isEmpty()) {+ return out;+ }for (const QString &key : m_sorted) {if (hasUpdate(key)) {out << key;@@ -859,6 +1369,163 @@ QStringList Catalog::updates() constreturn out;}+qint64 Catalog::updatedTime(const QString &key) const+{+ const Record *r = record(key);+ const QString from = installedSource(key);+ if (!r || from.isEmpty()) {+ return -1;+ }+ if (from == QLatin1String("flatpak")) {+ return m_flatpak->updatedTimes().value(r->flatpakId, -1);+ }+ // dpkg rewrites a package's file list each time it unpacks a version.+ const QString package = r->packages.constFirst();+ for (const QString &name : {package + QStringLiteral(".list"), package + QStringLiteral(":amd64.list")}) {+ const QFileInfo info(QStringLiteral("/var/lib/dpkg/info/") + name);+ if (info.exists()) {+ return info.lastModified().toMSecsSinceEpoch();+ }+ }+ return -1;+}++qint64 Catalog::updateSize(const QString &key) const+{+ const Record *r = record(key);+ if (!r || installedSource(key) != QLatin1String("flatpak")) {+ return -1;+ }+ return m_flatpak->updateSizes().value(r->flatpakId, -1);+}++qint64 Catalog::updatesBytes() const+{+ qint64 total = 0;+ bool any = false;+ for (const QString &key : updates()) {+ const qint64 size = updateSize(key);+ if (size > 0) {+ total += size;+ any = true;+ }+ }+ return any ? total : -1;+}++QStringList Catalog::recentlyUpdated(int limit) const+{+ const qint64 since = QDateTime::currentDateTime().addDays(-30).toMSecsSinceEpoch();+ QList<QPair<qint64, QString>> found;+ for (const QString &key : m_sorted) {+ if (!isInstalled(key) || hasUpdate(key)) {+ continue;+ }+ const qint64 when = updatedTime(key);+ if (when >= since) {+ found.append({when, key});+ }+ }+ std::sort(found.begin(), found.end(), [](const auto &a, const auto &b) {+ return a.first > b.first;+ });+ QStringList out;+ for (const auto &f : std::as_const(found)) {+ if (limit > 0 && out.size() >= limit) {+ break;+ }+ out << f.second;+ }+ return out;+}++QStringList Catalog::workingApps() const+{+ QStringList out;+ for (const Job &j : m_jobs) {+ for (const QString &key : j.keys) {+ if (!out.contains(key)) {+ out << key;+ }+ }+ }+ return out;+}++QStringList Catalog::matching(const QStringList &categories, int limit) const+{+ QStringList out;+ for (const QString &key : m_sorted) {+ const Record &r = m_records[key];+ if (std::any_of(categories.cbegin(), categories.cend(), [&r](const QString &c) {+ return r.categories.contains(c);+ })) {+ out << key;+ if (limit > 0 && out.size() >= limit) {+ break;+ }+ }+ }+ return out;+}++QString Catalog::dayText(qint64 msecs) const+{+ if (msecs <= 0) {+ return {};+ }+ const QDate day = QDateTime::fromMSecsSinceEpoch(msecs).date();+ const QDate today = QDate::currentDate();+ if (day == today) {+ return QStringLiteral("Today");+ }+ if (day == today.addDays(-1)) {+ return QStringLiteral("Yesterday");+ }+ if (day > today.addDays(-7)) {+ return QLocale().dayName(day.dayOfWeek(), QLocale::ShortFormat);+ }+ return QLocale().toString(day, QLocale::ShortFormat);+}++QString Catalog::sizeText(qint64 bytes) const+{+ if (bytes < 0) {+ return {};+ }+ return QLocale().formattedDataSize(bytes, bytes >= 1000 * 1000 * 1000 ? 1 : 0, QLocale::DataSizeSIFormat);+}++void Catalog::setAutoUpdate(bool on)+{+ if (on == m_autoUpdate) {+ return;+ }+ m_autoUpdate = on;+ Q_EMIT autoUpdateChanged();+ // The timer is switched on for every account by the package, so one+ // account turns it off for itself by masking it.+ const QString unit = QStringLiteral("wildos-store-update.timer");+ const QString script = on ? QStringLiteral("systemctl --user unmask %1; systemctl --user start %1").arg(unit)+ : QStringLiteral("systemctl --user stop %1; systemctl --user mask %1").arg(unit);+ QProcess::startDetached(QStringLiteral("sh"), {QStringLiteral("-c"), script});+}++void Catalog::pause(const QString &key)+{+ for (const Job &j : std::as_const(m_jobs)) {+ if (j.keys.contains(key) && j.running) {+ m_pausing.insert(j.id);+ AppState &s = m_states[key];+ s.stopping = true;+ s.resumeAfterStop = false;+ stateChangedFor(key);+ break;+ }+ }+ cancel(key);+}+void Catalog::fetchDetails(const QString &key){const Record *r = record(key);@@ -869,13 +1536,112 @@ void Catalog::fetchDetails(const QString &key)if (from == QLatin1String("apt")) {m_packagekit->fetchDetails(key, r->packages);} else if (from == QLatin1String("flatpak") && !r->flatpakId.isEmpty()) {- m_flatpak->fetchMetadata(r->flatpakId, r->flatpakRef);+ const AppState &s = m_states[key];+ // Asked once per run: neither the permissions nor the sizes change+ // while the Store is open.+ if (!s.flatpakMetadata.isEmpty() && (s.planTotal >= 0 || isInstalled(key))) {+ return;+ }+ if (m_detailsAsked.contains(r->flatpakId)) {+ return;+ }+ if (!isInstalled(key) && loadDetails(key)) {+ qCInfo(lcStore) << "timing: details for" << r->flatpakId << "read from disk";+ stateChangedFor(key);+ return;+ }+ m_detailsAsked.insert(r->flatpakId, storeClock());+ m_flatpak->fetchDetails(r->flatpakId, r->flatpakRef);+ }+}++namespace+{+QString detailsPath(const QString &flatpakId)+{+ return QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation) + QStringLiteral("/wildos-store/details/") + flatpakId + QStringLiteral(".json");+}++// flatpak touches this file whenever the installation changes; sizes worked+// out before then may count a runtime that is now installed.+qint64 installationChanged()+{+ return QFileInfo(FlatpakBackend::userDataDir() + QStringLiteral("/.changed")).lastModified().toMSecsSinceEpoch();+}+}++bool Catalog::loadDetails(const QString &key)+{+ // An app page opened again, in this run or a later one, gets its+ // permissions and sizes from disk while Flathub's catalogue and the+ // installation are as they were when they were fetched.+ const Record *r = record(key);+ QFile file(detailsPath(r->flatpakId));+ if (m_flatInputs.isEmpty() || !file.open(QIODevice::ReadOnly)) {+ return false;+ }+ const QJsonObject o = QJsonDocument::fromJson(file.readAll()).object();+ if (o.value(QStringLiteral("inputs")).toString() != m_flatInputs || o.value(QStringLiteral("saved")).toInteger() < installationChanged()+ || o.value(QStringLiteral("metadata")).toString().isEmpty() || o.value(QStringLiteral("total")).toInteger(-1) < 0) {+ return false;+ }+ AppState &s = m_states[key];+ s.flatpakMetadata = o.value(QStringLiteral("metadata")).toString();+ s.metadataFailed = false;+ s.planTotal = o.value(QStringLiteral("total")).toInteger(-1);+ s.planShared = o.value(QStringLiteral("shared")).toInteger(-1);+ s.planInstalled = o.value(QStringLiteral("installed")).toInteger(-1);+ s.planRuntime = o.value(QStringLiteral("runtime")).toString();+ return true;+}++void Catalog::saveDetails(const QString &key)+{+ const Record *r = record(key);+ const AppState &s = m_states[key];+ if (!r || r->flatpakId.isEmpty() || m_flatInputs.isEmpty() || s.flatpakMetadata.isEmpty() || s.planTotal < 0 || isInstalled(key)) {+ return;+ }+ const QJsonObject o{+ {QStringLiteral("inputs"), m_flatInputs},+ {QStringLiteral("saved"), QDateTime::currentMSecsSinceEpoch()},+ {QStringLiteral("metadata"), s.flatpakMetadata},+ {QStringLiteral("total"), s.planTotal},+ {QStringLiteral("shared"), s.planShared},+ {QStringLiteral("installed"), s.planInstalled},+ {QStringLiteral("runtime"), s.planRuntime},+ };+ const QString path = detailsPath(r->flatpakId);+ QDir().mkpath(QFileInfo(path).absolutePath());+ QSaveFile file(path);+ if (file.open(QIODevice::WriteOnly)) {+ file.write(QJsonDocument(o).toJson(QJsonDocument::Compact));+ file.commit();+ }+}++void Catalog::onPlan(const QString &appId, const FlatpakPlan &plan)+{+ for (auto it = m_records.cbegin(); it != m_records.cend(); ++it) {+ if (it->flatpakId == appId) {+ AppState &s = m_states[it.key()];+ s.planTotal = plan.total;+ s.planShared = plan.shared;+ s.planRuntime = plan.runtime;+ s.planInstalled = plan.installed;+ stateChangedFor(it.key());+ saveDetails(it.key());+ }}}void Catalog::install(const QString &key){const Record *r = record(key);+ if (r && m_states.value(key).stopping) {+ m_states[key].resumeAfterStop = true;+ return;+ }if (!r || isInstalled(key) || m_states.value(key).busy || m_states.value(key).queued) {return;}@@ -915,6 +1681,37 @@ void Catalog::update(const QString &key)}}+void Catalog::cancel(const QString &key)+{+ for (int i = 0; i < m_jobs.size(); ++i) {+ Job &j = m_jobs[i];+ if (!j.keys.contains(key)) {+ continue;+ }+ if (j.running) {+ m_cancelled.insert(j.id);+ if (j.source == QLatin1String("flatpak")) {+ m_flatpak->cancel(j.id);+ } else {+ m_packagekit->cancel(j.id);+ }+ return;+ }+ const Job gone = m_jobs.takeAt(i);+ for (const QString &k : gone.keys) {+ AppState &s = m_states[k];+ s.queued = false;+ s.busy = false;+ s.progress = -1;+ s.phase.clear();+ stateChangedFor(k);+ }+ bumpState();+ Q_EMIT updateAllProgressChanged();+ return;+ }+}+void Catalog::installEssentials(){for (const QString &key : essentials()) {@@ -946,10 +1743,10 @@ void Catalog::updateAll()if (!flatKeys.isEmpty()) {// An empty list updates every Flathub app and runtime together, so// shared runtimes are fetched once.- enqueue(JobKind::Update, QStringLiteral("flatpak"), flatKeys, {});+ enqueue(JobKind::Update, QStringLiteral("flatpak"), flatKeys, {}, true);}if (!aptKeys.isEmpty()) {- enqueue(JobKind::Update, QStringLiteral("apt"), aptKeys, aptPackages);+ enqueue(JobKind::Update, QStringLiteral("apt"), aptKeys, aptPackages, true);}}@@ -979,7 +1776,7 @@ void Catalog::checkPartDone(bool ok)}m_checking = false;m_checkResult = m_checkOk ? QStringLiteral("ok") : QStringLiteral("failed");- m_checkedAt = QTime::currentTime().toString(QStringLiteral("HH:mm"));+ m_checkedAt = QLocale::system().toString(QTime::currentTime(), QLocale::ShortFormat);Q_EMIT checkChanged();}@@ -988,110 +1785,251 @@ void Catalog::openSettings(const QString &page)QProcess::startDetached(QStringLiteral("wildos-settings"), {QStringLiteral("--page"), page});}-void Catalog::enqueue(JobKind kind, const QString &source, const QStringList &keys, const QStringList &targets)+Catalog::Job *Catalog::job(int id)+{+ for (Job &j : m_jobs) {+ if (j.id == id) {+ return &j;+ }+ }+ return nullptr;+}++void Catalog::enqueue(JobKind kind, const QString &source, const QStringList &keys, const QStringList &targets, bool all){Job job{m_nextJob++, kind, source, keys, targets};+ job.all = all;const QString action = kind == JobKind::Install ? QStringLiteral("install") : kind == JobKind::Remove ? QStringLiteral("remove") : QStringLiteral("update");for (const QString &key : keys) {AppState &s = m_states[key];s.queued = true;+ s.paused = false;s.action = action;s.error.clear();s.progress = -1;+ s.secondsLeft = -1;+ s.rateStarted = -1;+ s.detail.clear();+ s.doneBytes = -1;+ s.totalBytes = -1;s.phase = QStringLiteral("queued");stateChangedFor(key);}m_jobs.append(job);- ++m_revision;- Q_EMIT revisionChanged();- runNext();+ bumpState();+ Q_EMIT updateAllProgressChanged();+ scheduleRun();}-void Catalog::runNext()+void Catalog::scheduleRun(){- if (m_running || m_jobs.isEmpty()) {+ // Installs asked for together (Install all, or clicks in quick+ // succession) are started together, so Flathub ones share a transaction.+ if (m_runQueued) {return;}- m_running = true;- const Job &job = m_jobs.constFirst();- for (const QString &key : job.keys) {- AppState &s = m_states[key];- s.queued = false;- s.busy = true;- s.phase = QStringLiteral("prepare");- stateChangedFor(key);- }- if (job.source == QLatin1String("flatpak")) {- switch (job.kind) {- case JobKind::Install:- m_flatpak->install(job.id, job.targets.value(0));- break;- case JobKind::Remove:- m_flatpak->uninstall(job.id, job.targets.value(0));- break;- case JobKind::Update:- m_flatpak->update(job.id, job.targets);- break;+ m_runQueued = true;+ QTimer::singleShot(0, this, [this] {+ m_runQueued = false;+ runNext();+ });+}++void Catalog::runNext()+{+ // Wild OS packages and Flathub apps go through different systems, so one+ // of each can run at once.+ for (const QString &src : {QStringLiteral("flatpak"), QStringLiteral("apt")}) {+ const bool running = std::any_of(m_jobs.cbegin(), m_jobs.cend(), [&src](const Job &j) {+ return j.running && j.source == src;+ });+ if (running) {+ continue;}- } else {- switch (job.kind) {- case JobKind::Install:- m_packagekit->install(job.id, job.targets);- break;- case JobKind::Remove:- m_packagekit->remove(job.id, job.targets);- break;- case JobKind::Update:- m_packagekit->update(job.id, job.targets);- break;+ QList<int> ids;+ for (const Job &j : std::as_const(m_jobs)) {+ if (j.running || j.source != src) {+ continue;+ }+ if (ids.isEmpty()) {+ ids << j.id;+ if (!(src == QLatin1String("flatpak") && j.kind == JobKind::Install)) {+ break;+ }+ continue;+ }+ // Further Flathub installs join the first one's transaction.+ if (j.kind == JobKind::Install) {+ ids << j.id;+ }+ }+ if (!ids.isEmpty()) {+ start(ids);}}}-void Catalog::onProgress(int job, int percent, const QString &phase)+void Catalog::start(const QList<int> &ids){- for (const Job &j : std::as_const(m_jobs)) {- if (j.id != job) {+ FlatpakBatch batch;+ for (int id : ids) {+ Job *j = job(id);+ if (!j) {continue;}- for (const QString &key : j.keys) {+ j->running = true;+ m_jobStarted.insert(j->id, storeClock());+ for (const QString &key : std::as_const(j->keys)) {AppState &s = m_states[key];- s.progress = percent;- s.phase = phase;+ s.queued = false;+ s.busy = true;+ s.phase = QStringLiteral("prepare");stateChangedFor(key);}+ if (j->source == QLatin1String("flatpak")) {+ switch (j->kind) {+ case JobKind::Install:+ batch.append({j->id, j->targets.value(0)});+ break;+ case JobKind::Remove:+ m_flatpak->uninstall(j->id, j->targets.value(0));+ break;+ case JobKind::Update:+ m_flatpak->update(j->id, j->targets);+ break;+ }+ } else {+ switch (j->kind) {+ case JobKind::Install:+ m_packagekit->install(j->id, j->targets);+ break;+ case JobKind::Remove:+ m_packagekit->remove(j->id, j->targets);+ break;+ case JobKind::Update:+ m_packagekit->update(j->id, j->targets);+ break;+ }+ }+ }+ if (!batch.isEmpty()) {+ qCInfo(lcStore) << "timing: Flathub install of" << batch.size() << "apps in one transaction";+ m_flatpak->install(batch);}+ bumpState();}-void Catalog::onFinished(int job, bool ok, const QString &error)+void Catalog::onProgress(int id, int percent, const QString &phase, const QString &detail, qint64 done, qint64 total){- for (int i = 0; i < m_jobs.size(); ++i) {- const Job j = m_jobs.at(i);- if (j.id != job) {- continue;+ const Job *j = job(id);+ if (!j) {+ return;+ }+ for (const QString &key : j->keys) {+ AppState &s = m_states[key];+ // The bar only ever moves forward; a step that cannot say how far it+ // has got leaves the last figure in place.+ if (percent >= 0) {+ s.progress = qMax(s.progress, percent);}- m_jobs.removeAt(i);- for (const QString &key : j.keys) {+ s.phase = phase;+ s.detail = detail;+ if (total > 0) {+ s.totalBytes = total;+ s.doneBytes = qMax(s.doneBytes, done);+ // Time left from the average speed since the download began,+ // once there is enough of it to go on.+ const qint64 now = storeClock();+ if (s.rateStarted < 0 && s.doneBytes > 0) {+ s.rateStarted = now;+ s.rateStartBytes = s.doneBytes;+ } else if (s.rateStarted >= 0 && now - s.rateStarted > 2000 && s.doneBytes > s.rateStartBytes) {+ const double perMs = double(s.doneBytes - s.rateStartBytes) / double(now - s.rateStarted);+ s.secondsLeft = qint64(double(s.totalBytes - s.doneBytes) / perMs / 1000.0);+ }+ }+ stateChangedFor(key);+ }+ if (j->all) {+ Q_EMIT updateAllProgressChanged();+ }+}++void Catalog::onFinished(int id, bool ok, const QString &error)+{+ Job *found = job(id);+ if (!found) {+ return;+ }+ // A batch is one Flathub transaction: cancelling one app in it stops+ // the others too, and they go back in the queue to start again.+ if (!ok && error == QLatin1String(cancelledMarker) && !m_cancelled.contains(id)) {+ found->running = false;+ for (const QString &key : std::as_const(found->keys)) {AppState &s = m_states[key];s.busy = false;- s.queued = false;- s.progress = -1;- s.phase.clear();- s.error = ok ? QString() : error;- if (ok && j.kind == JobKind::Remove) {- s.chosenSource.clear();- }+ s.queued = true;+ s.phase = QStringLiteral("queued");stateChangedFor(key);- if (ok && j.kind == JobKind::Install) {- Q_EMIT installed(key);- } else if (!ok) {- Q_EMIT failed(key, error);- }}- break;+ scheduleRun();+ return;+ }+ const bool cancelled = m_cancelled.remove(id);+ // Stopped with its stop button, or cut off from Flathub: either way it+ // can carry on from what it already fetched.+ const bool paused = m_pausing.remove(id) || (!ok && error.startsWith(QLatin1String("Couldn't reach")));+ Job j = *found;+ m_jobs.removeIf([id](const Job &x) {+ return x.id == id;+ });+ qCInfo(lcStore) << "timing: job" << id << j.source << j.targets << (ok ? "finished" : cancelled ? "cancelled" : "failed") << "after"+ << storeClock() - m_jobStarted.take(id) << "ms";+ for (const QString &key : std::as_const(j.keys)) {+ AppState &s = m_states[key];+ s.busy = false;+ s.queued = false;+ s.progress = -1;+ s.phase.clear();+ s.detail.clear();+ s.doneBytes = -1;+ s.totalBytes = -1;+ s.rateStarted = -1;+ s.secondsLeft = -1;+ s.paused = paused && j.kind != JobKind::Remove;+ s.stopping = false;+ s.error = ok || cancelled || s.paused ? QString() : error;+ if (ok && j.kind == JobKind::Remove) {+ s.chosenSource.clear();+ s.planTotal = -1;+ s.planRuntime.clear();+ }+ stateChangedFor(key);+ if (ok && j.kind == JobKind::Install) {+ Q_EMIT installed(key);+ } else if (!ok && !cancelled && !paused) {+ Q_EMIT failed(key, error);+ }+ }+ // Sizes of apps on the same runtime change once it is installed.+ if (ok && j.source == QLatin1String("flatpak")) {+ for (auto &s : m_states) {+ s.planTotal = -1;+ s.planShared = -1;+ s.planRuntime.clear();+ }+ m_detailsAsked.clear();+ }+ bumpState();+ Q_EMIT updateAllProgressChanged();+ scheduleRun();+ if (ok) {+ saveSnapshot();+ }+ for (const QString &key : std::as_const(j.keys)) {+ if (m_states[key].resumeAfterStop) {+ m_states[key].resumeAfterStop = false;+ install(key);+ }}- m_running = false;- ++m_revision;- Q_EMIT revisionChanged();- runNext();}diff --git a/packages/wildos-store/src/catalog.h b/packages/wildos-store/src/catalog.hindex ce44d6e..5515668 100644--- a/packages/wildos-store/src/catalog.h+++ b/packages/wildos-store/src/catalog.h@@ -23,6 +23,7 @@ class Pool;class FlatpakBackend;class PackageKitBackend;+struct FlatpakPlan;// Hand-picked details that AppStream does not carry: what an app replaces// on Windows, the short lines the design shows on cards, and which source to@@ -49,7 +50,10 @@ struct Curated {};// One app as the Store shows it, joined from the Wild OS (apt) catalogue,-// Flathub and the curated file.+// Flathub and the curated file. The name, summary and icon are worked out+// when the catalogue is built, off the window's thread, and saved with it,+// so lists never touch AppStream and the next start can draw them from disk+// before either catalogue has loaded.struct Record {QString key;std::optional<AppStream::Component> apt;@@ -60,6 +64,17 @@ struct Record {QString flatpakRef;QStringList categories;int quality = 0;+ bool hasApt = false;+ bool hasFlat = false;+ QString aptName;+ QString flatName;+ QString aptSummary;+ QString flatSummary;+ QString aptIcon;+ QString flatIcon;+ // Lower case name, then everything else search looks at.+ QString searchName;+ QString searchText;};struct AppState {@@ -74,6 +89,37 @@ struct AppState {QString candidateVersion;QString flatpakMetadata;bool metadataFailed = false;+ // The step a download is on when it is worth naming (a shared runtime),+ // and how far it has got in bytes.+ QString detail;+ qint64 doneBytes = -1;+ qint64 totalBytes = -1;+ // From Flathub before installing: everything it downloads, and the part+ // of that a later app of the same kind would not need again.+ qint64 planTotal = -1;+ qint64 planShared = -1;+ QString planRuntime;+ qint64 planInstalled = -1;+ // Stopped part way by its stop button or a lost connection; Get carries+ // on from what was already fetched.+ bool paused = false;+ // The stop square was pressed and libflatpak is still winding down; the+ // button shows Paused at once. Pressing it again in that time carries+ // on as soon as the stop has gone through.+ bool stopping = false;+ bool resumeAfterStop = false;+ // For the time left: when the download began and how much was in hand.+ qint64 rateStarted = -1;+ qint64 rateStartBytes = 0;+ qint64 secondsLeft = -1;+};++// Everything a rebuild makes, swapped in whole on the window's thread.+struct CatalogData {+ QHash<QString, Record> records;+ QHash<QString, QString> aliases;+ QStringList sorted;+ QHash<QString, QStringList> categories;};class Catalog : public QObject@@ -83,12 +129,23 @@ class Catalog : public QObjectQML_SINGLETONQ_PROPERTY(bool ready READ isReady NOTIFY readyChanged)+ // Bumps when the list of apps changes; pages showing lists of apps bind+ // to it. stateRevision bumps when what is installed, updatable or busy+ // changes, which only the Installed and Updates pages list by.+ Q_PROPERTY(int catalogRevision READ catalogRevision NOTIFY catalogRevisionChanged)+ Q_PROPERTY(int stateRevision READ stateRevision NOTIFY stateRevisionChanged)Q_PROPERTY(int revision READ revision NOTIFY revisionChanged)- Q_PROPERTY(int updateCount READ updateCount NOTIFY revisionChanged)- Q_PROPERTY(bool flathubAvailable READ flathubAvailable NOTIFY revisionChanged)+ Q_PROPERTY(int updateCount READ updateCount NOTIFY stateRevisionChanged)+ Q_PROPERTY(int workingCount READ workingCount NOTIFY stateRevisionChanged)+ Q_PROPERTY(int updateAllProgress READ updateAllProgress NOTIFY updateAllProgressChanged)+ Q_PROPERTY(bool flathubAvailable READ flathubAvailable NOTIFY catalogRevisionChanged)+ // What every pending update downloads together, when Flathub said.+ Q_PROPERTY(qint64 updatesBytes READ updatesBytes NOTIFY stateRevisionChanged)+ // Flathub apps update overnight on mains power (a systemd user timer).+ Q_PROPERTY(bool autoUpdate READ autoUpdate WRITE setAutoUpdate NOTIFY autoUpdateChanged)Q_PROPERTY(QVariantList appCategories READ appCategories CONSTANT)Q_PROPERTY(QVariantList gameCategories READ gameCategories CONSTANT)- Q_PROPERTY(bool busy READ isBusy NOTIFY revisionChanged)+ Q_PROPERTY(bool busy READ isBusy NOTIFY stateRevisionChanged)// "Check for updates": running, and how the last one went ("", ok or// failed) and when, so the button can say what it did.Q_PROPERTY(bool checking READ isChecking NOTIFY checkChanged)@@ -101,15 +158,25 @@ public:static Catalog *instance();static Catalog *create(QQmlEngine *, QJSEngine *);+ // Reads the catalogues and starts the package systems; called once the+ // first frame is on screen, or at once without a snapshot to show.+ void startBackgroundWork();bool isReady() const { return m_ready; }- int revision() const { return m_revision; }+ int catalogRevision() const { return m_catalogRevision; }+ int stateRevision() const { return m_stateRevision; }+ int revision() const { return m_catalogRevision + m_stateRevision; }int updateCount() const;+ int workingCount() const;+ int updateAllProgress() const;bool flathubAvailable() const;QVariantList appCategories() const;QVariantList gameCategories() const;bool isBusy() const { return !m_jobs.isEmpty(); }bool isChecking() const { return m_checking; }+ qint64 updatesBytes() const;+ bool autoUpdate() const { return m_autoUpdate; }+ void setAutoUpdate(bool on);QString checkResult() const { return m_checkResult; }QString checkedAt() const { return m_checkedAt; }@@ -125,12 +192,31 @@ public:Q_INVOKABLE QStringList swapMatches(const QString &text) const;Q_INVOKABLE QStringList installedApps() const;Q_INVOKABLE QStringList updates() const;+ // Installed apps whose current version arrived in the last month, newest+ // first, read from the installed files rather than any record the+ // Store keeps.+ Q_INVOKABLE QStringList recentlyUpdated(int limit = 5) const;+ // Apps being installed, updated or removed, and those waiting, in the+ // order they will run.+ Q_INVOKABLE QStringList workingApps() const;+ // Apps in any of these freedesktop categories, best first.+ Q_INVOKABLE QStringList matching(const QStringList &categories, int limit = -1) const;+ // "Yesterday", "Sat" or a date, for a time in milliseconds.+ Q_INVOKABLE QString dayText(qint64 msecs) const;+ Q_INVOKABLE QString sizeText(qint64 bytes) const;Q_INVOKABLE QString categoryLabel(const QString &id) const;+ // The image from a screenshot's list of sizes that fills width by height+ // device pixels without being much larger.+ Q_INVOKABLE QString pickImage(const QVariantList &images, int width, int height) const;Q_INVOKABLE void installEssentials();Q_INVOKABLE void updateAll();Q_INVOKABLE void refresh();Q_INVOKABLE void openSettings(const QString &page);+ // Used by LocalPackage, for files someone opened.+ FlatpakBackend *flatpakBackend() const { return m_flatpak; }+ PackageKitBackend *packageKitBackend() const { return m_packagekit; }+// Used by StoreApp.const Record *record(const QString &key) const;AppState &state(const QString &key) { return m_states[key]; }@@ -144,12 +230,20 @@ public:void install(const QString &key);void remove(const QString &key);void update(const QString &key);+ void cancel(const QString &key);+ void pause(const QString &key);+ qint64 updatedTime(const QString &key) const;+ qint64 updateSize(const QString &key) const;void fetchDetails(const QString &key);void stateChangedFor(const QString &key);Q_SIGNALS:void readyChanged();+ void catalogRevisionChanged();+ void stateRevisionChanged();void revisionChanged();+ void updateAllProgressChanged();+ void autoUpdateChanged();void checkChanged();void appStateChanged(const QString &key);// A finished install, so the window can offer to open it.@@ -164,27 +258,49 @@ private:QString source;QStringList keys;QStringList targets;+ bool running = false;+ bool all = false;};void loadCurated();void loadOsPool();void loadFlatpakPool();void rebuild();- void bump();- void enqueue(JobKind kind, const QString &source, const QStringList &keys, const QStringList &targets);+ void adopt(CatalogData data, qint64 built);+ bool loadSnapshot();+ void saveSnapshot();+ void bumpCatalog();+ void bumpState();+ void enqueue(JobKind kind, const QString &source, const QStringList &keys, const QStringList &targets, bool all = false);+ void scheduleRun();void runNext();- void onProgress(int job, int percent, const QString &phase);+ void start(const QList<int> &ids);+ void onProgress(int job, int percent, const QString &phase, const QString &detail, qint64 done, qint64 total);void onFinished(int job, bool ok, const QString &error);+ void onPlan(const QString &appId, const FlatpakPlan &plan);+ bool loadDetails(const QString &key);+ void saveDetails(const QString &key);void checkPartDone(bool ok);QString keyFor(const QString &id) const;+ Job *job(int id);static Catalog *s_instance;- std::unique_ptr<AppStream::Pool> m_osPool;- std::unique_ptr<AppStream::Pool> m_flatPool;+ std::shared_ptr<AppStream::Pool> m_osPool;+ std::shared_ptr<AppStream::Pool> m_flatPool;+ // What each catalogue was read from last, so a reload that would read+ // the same files again is skipped.+ QString m_osInputs;+ QString m_flatInputs;bool m_osLoaded = false;+ bool m_flatLoaded = false;bool m_ready = false;- int m_revision = 0;+ bool m_fromSnapshot = false;+ bool m_started = false;+ bool m_building = false;+ bool m_rebuildAgain = false;+ int m_catalogRevision = 0;+ int m_stateRevision = 0;QList<Curated> m_curated;QStringList m_homeSwaps;@@ -196,13 +312,19 @@ private:QHash<QString, Record> m_records;QHash<QString, QString> m_aliases;QStringList m_sorted;+ QHash<QString, QStringList> m_categories;QHash<QString, AppState> m_states;QHash<QString, QPointer<StoreApp>> m_apps;QList<Job> m_jobs;+ QSet<int> m_cancelled;+ QSet<int> m_pausing;+ bool m_autoUpdate = false;int m_nextJob = 1;- bool m_running = false;+ bool m_runQueued = false;+ QHash<int, qint64> m_jobStarted;+ QHash<QString, qint64> m_detailsAsked;PackageKitBackend *m_packagekit;FlatpakBackend *m_flatpak;diff --git a/packages/wildos-store/src/flatpakbackend.cpp b/packages/wildos-store/src/flatpakbackend.cppindex 3c038a8..942ea10 100644--- a/packages/wildos-store/src/flatpakbackend.cpp+++ b/packages/wildos-store/src/flatpakbackend.cpp@@ -1,9 +1,12 @@#include "flatpakbackend.h"+#include "timing.h"#include <QDateTime>#include <QDir>#include <QFile>#include <QFileInfo>+#include <QLocale>+#include <QMutex>#include <QStandardPaths>#include <flatpak.h>@@ -12,6 +15,10 @@ namespace{const char *const remoteName = "flathub";+// Adding the Flathub remote must happen once, whichever thread gets there+// first; the others then find it on disk.+QMutex installationMutex;+QString takeError(GError *&error, const QString &fallback = {}){QString text = fallback;@@ -24,34 +31,136 @@ QString takeError(GError *&error, const QString &fallback = {})return text;}+// The platforms apps are built on, as people are told about them: "the KDE+// base". Anything else a transaction pulls in (graphics drivers, codecs,+// translations) is counted but not named.+QString platformLabel(const QString &name)+{+ if (name == QLatin1String("org.kde.Platform")) {+ return QStringLiteral("the KDE base");+ }+ if (name == QLatin1String("org.gnome.Platform")) {+ return QStringLiteral("the GNOME base");+ }+ if (name == QLatin1String("org.freedesktop.Platform")) {+ return QStringLiteral("the Freedesktop base");+ }+ if (name == QLatin1String("io.elementary.Platform")) {+ return QStringLiteral("the elementary base");+ }+ if (name.endsWith(QLatin1String(".Platform"))) {+ return QStringLiteral("a shared base");+ }+ return {};+}++// libflatpak's messages are written for the command line; the line under an+// app's button says what happened in plain words. The original goes to the+// log.+QString plainError(const QString &message)+{+ const QString m = message.toLower();+ if (m.contains(QLatin1String("resolve")) || m.contains(QLatin1String("connect")) || m.contains(QLatin1String("network"))+ || m.contains(QLatin1String("timeout")) || m.contains(QLatin1String("timed out")) || m.contains(QLatin1String("curl"))) {+ return QStringLiteral("Couldn't reach Flathub. Check you're online.");+ }+ if (m.contains(QLatin1String("space"))) {+ return QStringLiteral("There isn't enough free space for this app.");+ }+ if (m.contains(QLatin1String("not found")) || m.contains(QLatin1String("nothing matches"))) {+ return QStringLiteral("Flathub doesn't have this app any more.");+ }+ return QStringLiteral("Flathub stopped part way through. Try again in a few minutes.");+}++// The same for an app installed from a file, which may come from anywhere.+QString plainFileError(const QString &message)+{+ const QString m = message.toLower();+ if (m.contains(QLatin1String("resolve")) || m.contains(QLatin1String("connect")) || m.contains(QLatin1String("network"))+ || m.contains(QLatin1String("timeout")) || m.contains(QLatin1String("timed out")) || m.contains(QLatin1String("curl"))) {+ return QStringLiteral("Couldn't reach the place this app downloads from. Check you're online.");+ }+ if (m.contains(QLatin1String("space"))) {+ return QStringLiteral("There isn't enough free space for this app.");+ }+ if (m.contains(QLatin1String("gpg")) || m.contains(QLatin1String("signature")) || m.contains(QLatin1String("signed"))) {+ return QStringLiteral("The app's signature didn't match, so nothing was installed. The file may be damaged or changed.");+ }+ if (m.contains(QLatin1String("runtime")) || m.contains(QLatin1String("not found")) || m.contains(QLatin1String("nothing matches"))) {+ return QStringLiteral("This app needs a part Wild OS can't find on Flathub, so it can't be installed.");+ }+ if (m.contains(QLatin1String("invalid")) || m.contains(QLatin1String("not a")) || m.contains(QLatin1String("parse"))) {+ return QStringLiteral("This file can't be read. It may be damaged or only partly downloaded.");+ }+ return QStringLiteral("The install stopped part way through. Try again, or download the file again.");+}++QString refName(const char *ref)+{+ return QString::fromUtf8(ref).section(QLatin1Char('/'), 1, 1);+}++bool isRuntimeRef(const char *ref)+{+ return qstrncmp(ref, "runtime/", 8) == 0;+}++struct OpInfo {+ qint64 weight = 1;+ qint64 bytes = 0;+ QString detail;+};+struct TransactionState {FlatpakWorker *worker;- int job;- int opIndex = -1;- int opCount = 1;+ QList<int> jobs;+ bool batch = false;+ QHash<FlatpakTransactionOperation *, OpInfo> ops;+ qint64 totalWeight = 0;+ qint64 doneWeight = 0;+ qint64 totalBytes = 0;+ qint64 doneBytes = 0;+ FlatpakTransactionOperation *current = nullptr;bool removing = false;QString error;+ QHash<QString, QString> refErrors;};void onProgressChanged(FlatpakTransactionProgress *progress, gpointer data){auto state = static_cast<TransactionState *>(data);const int part = qBound(0, flatpak_transaction_progress_get_progress(progress), 100);- const int whole = (qMax(0, state->opIndex) * 100 + part) / qMax(1, state->opCount);+ const OpInfo info = state->ops.value(state->current);+ // Weighted by what each step downloads, so a large runtime moves the bar+ // as much as it costs and a small translation barely does.+ int whole = 0;+ if (state->totalWeight > 0) {+ whole = int((state->doneWeight + info.weight * part / 100) * 100 / state->totalWeight);+ }+ whole = qBound(0, whole, 100);const bool estimating = flatpak_transaction_progress_get_is_estimating(progress);QString status;if (state->removing) {status = QStringLiteral("remove");} else {- status = estimating ? QStringLiteral("prepare") : QStringLiteral("download");+ // A step at 100% is being unpacked into place.+ status = estimating ? QStringLiteral("prepare") : part >= 100 ? QStringLiteral("install") : QStringLiteral("download");+ }+ const qint64 done = state->doneBytes + info.bytes * part / 100;+ for (int job : std::as_const(state->jobs)) {+ Q_EMIT state->worker->progress(job, whole, status, info.detail, done, state->totalBytes);}- QMetaObject::invokeMethod(state->worker, "progress", Qt::DirectConnection, Q_ARG(int, state->job), Q_ARG(int, whole), Q_ARG(QString, status));}void onNewOperation(FlatpakTransaction *, FlatpakTransactionOperation *operation, FlatpakTransactionProgress *progress, gpointer data){auto state = static_cast<TransactionState *>(data);- ++state->opIndex;+ if (state->current) {+ state->doneWeight += state->ops.value(state->current).weight;+ state->doneBytes += state->ops.value(state->current).bytes;+ }+ state->current = operation;state->removing = flatpak_transaction_operation_get_operation_type(operation) == FLATPAK_TRANSACTION_OPERATION_UNINSTALL;flatpak_transaction_progress_set_update_frequency(progress, 250);g_signal_connect(progress, "changed", G_CALLBACK(onProgressChanged), data);@@ -62,22 +171,44 @@ gboolean onReady(FlatpakTransaction *transaction, gpointer data){auto state = static_cast<TransactionState *>(data);GList *ops = flatpak_transaction_get_operations(transaction);- state->opCount = qMax(1, int(g_list_length(ops)));+ for (GList *l = ops; l; l = l->next) {+ auto op = static_cast<FlatpakTransactionOperation *>(l->data);+ OpInfo info;+ const auto type = flatpak_transaction_operation_get_operation_type(op);+ if (type != FLATPAK_TRANSACTION_OPERATION_UNINSTALL && !flatpak_transaction_operation_get_is_skipped(op)) {+ info.bytes = qint64(flatpak_transaction_operation_get_download_size(op));+ // A floor, so steps that report no size still move the bar.+ info.weight = qMax<qint64>(info.bytes, 256 * 1024);+ }+ const char *ref = flatpak_transaction_operation_get_ref(op);+ if (type == FLATPAK_TRANSACTION_OPERATION_INSTALL && isRuntimeRef(ref)) {+ info.detail = platformLabel(refName(ref));+ }+ state->totalWeight += info.weight;+ state->totalBytes += info.bytes;+ state->ops.insert(op, info);+ }g_list_free_full(ops, g_object_unref);return TRUE;}-gboolean onOperationError(FlatpakTransaction *, FlatpakTransactionOperation *, GError *error, gint details, gpointer data)+gboolean onOperationError(FlatpakTransaction *, FlatpakTransactionOperation *operation, GError *error, gint details, gpointer data){auto state = static_cast<TransactionState *>(data);// A related ref that fails (a translation, say) should not undo the app.if (details & FLATPAK_TRANSACTION_ERROR_DETAILS_NON_FATAL) {return TRUE;}- if (error && state->error.isEmpty()) {- state->error = QString::fromUtf8(error->message);+ const QString message = error ? QString::fromUtf8(error->message) : QString();+ if (!message.isEmpty() && state->error.isEmpty()) {+ state->error = message;}- return FALSE;+ if (operation) {+ state->refErrors.insert(QString::fromUtf8(flatpak_transaction_operation_get_ref(operation)), message);+ }+ // In a batch the other apps carry on; whatever needed the failed step is+ // skipped by libflatpak and reported here too.+ return state->batch ? TRUE : FALSE;}gboolean onAddNewRemote(FlatpakTransaction *, FlatpakTransactionRemoteReason, const char *, const char *, const char *, gpointer)@@ -95,49 +226,134 @@ int onChooseRemote(FlatpakTransaction *, const char *, const char *, const char}return 0;}++struct PlanState {+ QString appId;+ bool resolved = false;+ FlatpakPlan plan;+ QString metadata;+ qint64 runtimeBytes = 0;+};++gboolean onPlanReady(FlatpakTransaction *transaction, gpointer data)+{+ auto state = static_cast<PlanState *>(data);+ state->resolved = true;+ state->plan.total = 0;+ state->plan.shared = 0;+ state->plan.installed = 0;+ GList *ops = flatpak_transaction_get_operations(transaction);+ for (GList *l = ops; l; l = l->next) {+ auto op = static_cast<FlatpakTransactionOperation *>(l->data);+ if (flatpak_transaction_operation_get_is_skipped(op)) {+ continue;+ }+ const qint64 size = qint64(flatpak_transaction_operation_get_download_size(op));+ const char *ref = flatpak_transaction_operation_get_ref(op);+ state->plan.total += size;+ state->plan.installed += qint64(flatpak_transaction_operation_get_installed_size(op));+ if (!isRuntimeRef(ref) && refName(ref) == state->appId) {+ GKeyFile *meta = flatpak_transaction_operation_get_metadata(op);+ if (meta) {+ gsize length = 0;+ char *text = g_key_file_to_data(meta, &length, nullptr);+ state->metadata = QString::fromUtf8(text, qsizetype(length));+ g_free(text);+ }+ continue;+ }+ state->plan.shared += size;+ const QString label = platformLabel(refName(ref));+ if (flatpak_transaction_operation_get_operation_type(op) == FLATPAK_TRANSACTION_OPERATION_INSTALL && !label.isEmpty() && size > state->runtimeBytes) {+ state->plan.runtime = label;+ state->runtimeBytes = size;+ }+ }+ g_list_free_full(ops, g_object_unref);+ // Resolved is all this was for; stop before anything downloads.+ return FALSE;+}}FlatpakBackend::FlatpakBackend(QObject *parent): QObject(parent){- m_worker = new FlatpakWorker;- m_worker->moveToThread(&m_thread);- connect(&m_thread, &QThread::finished, m_worker, &QObject::deleteLater);+ qRegisterMetaType<FlatpakPlan>();+ qRegisterMetaType<FlatpakBatch>();++ m_catalogue = new FlatpakWorker("catalogue");+ m_details = new FlatpakWorker("details");+ m_installer = new FlatpakWorker("install");+ const QList<QPair<FlatpakWorker *, QThread *>> pairs = {+ {m_catalogue, &m_catalogueThread},+ {m_details, &m_detailsThread},+ {m_installer, &m_installThread},+ };+ for (const auto &[worker, thread] : pairs) {+ worker->moveToThread(thread);+ connect(thread, &QThread::finished, worker, &QObject::deleteLater);+ connect(worker, &FlatpakWorker::unavailable, this, &FlatpakBackend::unavailable);+ connect(worker, &FlatpakWorker::installedListed, this,+ [this](const QStringList &apps, const QHash<QString, qint64> &sizes, const QHash<QString, qint64> &updated) {+ m_installed = QSet<QString>(apps.begin(), apps.end());+ m_sizes = sizes;+ m_updated = updated;+ m_ready = true;+ Q_EMIT installedChanged();+ });+ }- connect(this, &FlatpakBackend::requestStart, m_worker, &FlatpakWorker::start);- connect(this, &FlatpakBackend::requestInstall, m_worker, &FlatpakWorker::install);- connect(this, &FlatpakBackend::requestUninstall, m_worker, &FlatpakWorker::uninstall);- connect(this, &FlatpakBackend::requestUpdate, m_worker, &FlatpakWorker::update);- connect(this, &FlatpakBackend::requestMetadata, m_worker, &FlatpakWorker::metadata);- connect(this, &FlatpakBackend::requestAppstream, m_worker, &FlatpakWorker::appstream);- connect(this, &FlatpakBackend::requestCheck, m_worker, &FlatpakWorker::check);+ connect(this, &FlatpakBackend::requestStart, m_catalogue, &FlatpakWorker::start);+ connect(this, &FlatpakBackend::requestCheck, m_catalogue, &FlatpakWorker::check);+ connect(this, &FlatpakBackend::requestUpdateCheck, m_catalogue, &FlatpakWorker::checkUpdates);+ connect(this, &FlatpakBackend::requestDetails, m_details, &FlatpakWorker::details);+ connect(this, &FlatpakBackend::requestInstall, m_installer, &FlatpakWorker::install);+ connect(this, &FlatpakBackend::requestUninstall, m_installer, &FlatpakWorker::uninstall);+ connect(this, &FlatpakBackend::requestUpdate, m_installer, &FlatpakWorker::update);+ connect(this, &FlatpakBackend::requestInstallFile, m_installer, &FlatpakWorker::installFile);- connect(m_worker, &FlatpakWorker::appstreamReady, this, [this](const QString &dir) {+ connect(m_catalogue, &FlatpakWorker::appstreamReady, this, [this](const QString &dir) {m_appstreamDir = dir;Q_EMIT appstreamChanged();});- connect(m_worker, &FlatpakWorker::installedListed, this,- [this](const QStringList &apps, const QStringList &updates, const QHash<QString, qint64> &sizes) {- m_installed = QSet<QString>(apps.begin(), apps.end());- m_updates = QSet<QString>(updates.begin(), updates.end());- m_sizes = sizes;- m_ready = true;- Q_EMIT installedChanged();- });- connect(m_worker, &FlatpakWorker::progress, this, &FlatpakBackend::progress);- connect(m_worker, &FlatpakWorker::finished, this, &FlatpakBackend::finished);- connect(m_worker, &FlatpakWorker::metadataReady, this, &FlatpakBackend::metadataReady);- connect(m_worker, &FlatpakWorker::unavailable, this, &FlatpakBackend::unavailable);- connect(m_worker, &FlatpakWorker::checked, this, &FlatpakBackend::refreshFinished);-- m_thread.setObjectName(QStringLiteral("flatpak"));- m_thread.start();+ connect(m_catalogue, &FlatpakWorker::updatesListed, this, [this](const QStringList &updates, const QHash<QString, qint64> &sizes) {+ m_updateCheckQueued = false;+ const QSet<QString> fresh(updates.begin(), updates.end());+ if (fresh != m_updates || sizes != m_updateSizes) {+ m_updates = fresh;+ m_updateSizes = sizes;+ Q_EMIT updatesChanged();+ }+ });+ connect(m_catalogue, &FlatpakWorker::checked, this, &FlatpakBackend::refreshFinished);+ connect(m_installer, &FlatpakWorker::progress, this, &FlatpakBackend::progress);+ connect(m_installer, &FlatpakWorker::finished, this, [this](int job, bool ok, const QString &error) {+ if (!ok && error != QLatin1String(cancelledMarker)) {+ qCWarning(lcStore) << "Flathub job" << job << "failed:" << error;+ }+ const bool plain = ok || error == QLatin1String(cancelledMarker);+ Q_EMIT finished(job, ok, plain ? error : job < 0 ? plainFileError(error) : plainError(error));+ checkUpdatesSoon();+ });+ connect(m_details, &FlatpakWorker::metadataReady, this, &FlatpakBackend::metadataReady);+ connect(m_details, &FlatpakWorker::planReady, this, &FlatpakBackend::planReady);++ m_catalogueThread.setObjectName(QStringLiteral("flatpak-catalogue"));+ m_detailsThread.setObjectName(QStringLiteral("flatpak-details"));+ m_installThread.setObjectName(QStringLiteral("flatpak-install"));+ m_catalogueThread.start();+ m_detailsThread.start();+ m_installThread.start();}FlatpakBackend::~FlatpakBackend(){- m_thread.quit();- m_thread.wait(3000);+ for (QThread *thread : {&m_catalogueThread, &m_detailsThread, &m_installThread}) {+ thread->quit();+ }+ for (QThread *thread : {&m_catalogueThread, &m_detailsThread, &m_installThread}) {+ thread->wait(3000);+ }}QString FlatpakBackend::userDataDir()@@ -145,14 +361,21 @@ QString FlatpakBackend::userDataDir()return QDir(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation)).filePath(QStringLiteral("flatpak"));}+void FlatpakBackend::seedInstalled(const QSet<QString> &apps)+{+ if (!m_ready) {+ m_installed = apps;+ }+}+void FlatpakBackend::start(){Q_EMIT requestStart();}-void FlatpakBackend::install(int job, const QString &ref)+void FlatpakBackend::install(const FlatpakBatch &jobs){- Q_EMIT requestInstall(job, ref);+ Q_EMIT requestInstall(jobs);}void FlatpakBackend::uninstall(int job, const QString &ref)@@ -165,9 +388,19 @@ void FlatpakBackend::update(int job, const QStringList &refs)Q_EMIT requestUpdate(job, refs);}-void FlatpakBackend::fetchMetadata(const QString &appId, const QString &ref)+void FlatpakBackend::cancel(int job)+{+ m_installer->cancel(job);+}++void FlatpakBackend::installFile(int job, const QString &path, bool bundle)+{+ Q_EMIT requestInstallFile(job, path, bundle);+}++void FlatpakBackend::fetchDetails(const QString &appId, const QString &ref){- Q_EMIT requestMetadata(appId, ref);+ Q_EMIT requestDetails(appId, ref);}void FlatpakBackend::refreshAppstream()@@ -175,18 +408,41 @@ void FlatpakBackend::refreshAppstream()Q_EMIT requestCheck();}-FlatpakWorker::FlatpakWorker() = default;+void FlatpakBackend::checkUpdatesSoon()+{+ // The update check asks Flathub, so it runs on the catalogue thread after+ // the install has been reported, and several finishing together share one.+ if (m_updateCheckQueued) {+ return;+ }+ m_updateCheckQueued = true;+ Q_EMIT requestUpdateCheck();+}++FlatpakWorker::FlatpakWorker(const char *role)+ : m_role(role)+{+}FlatpakWorker::~FlatpakWorker(){g_clear_object(&m_installation);}+void FlatpakWorker::cancel(int job)+{+ QMutexLocker lock(&m_runningMutex);+ if (m_cancellable && m_runningJobs.contains(job)) {+ g_cancellable_cancel(m_cancellable);+ }+}+bool FlatpakWorker::ensureInstallation(){if (m_installation) {return true;}+ QMutexLocker lock(&installationMutex);GError *error = nullptr;m_installation = flatpak_installation_new_user(nullptr, &error);if (!m_installation) {@@ -209,6 +465,7 @@ bool FlatpakWorker::ensureInstallation()QFile file(QStringLiteral(":/qt/qml/WildOS/Store/data/flathub.flatpakrepo"));if (!file.open(QIODevice::ReadOnly)) {+ g_clear_object(&m_installation);Q_EMIT unavailable(QStringLiteral("The Flathub details are missing from the Store."));return false;}@@ -217,6 +474,7 @@ bool FlatpakWorker::ensureInstallation()remote = flatpak_remote_new_from_file(remoteName, bytes, &error);g_bytes_unref(bytes);if (!remote) {+ g_clear_object(&m_installation);Q_EMIT unavailable(takeError(error));return false;}@@ -224,6 +482,7 @@ bool FlatpakWorker::ensureInstallation()const bool added = flatpak_installation_add_remote(m_installation, remote, TRUE, nullptr, &error);g_object_unref(remote);if (!added) {+ g_clear_object(&m_installation);Q_EMIT unavailable(takeError(error));return false;}@@ -236,8 +495,13 @@ void FlatpakWorker::start()if (!ensureInstallation()) {return;}+ qCInfo(lcStore) << "timing: Flathub installation open at" << storeClock() << "ms";+ // Everything on disk first, so the Store fills before Flathub is asked+ // anything.listInstalled();+ qCInfo(lcStore) << "timing: Flathub apps listed at" << storeClock() << "ms";appstream(false);+ checkUpdates();}bool FlatpakWorker::appstream(bool force)@@ -276,6 +540,7 @@ bool FlatpakWorker::appstream(bool force)return true;}gboolean changed = FALSE;+ const qint64 began = storeClock();if (!flatpak_installation_update_appstream_full_sync(m_installation, remoteName, nullptr, nullptr, nullptr, &changed, nullptr, &error)) {const QString message = takeError(error);if (!present) {@@ -283,26 +548,28 @@ bool FlatpakWorker::appstream(bool force)}return false;}+ qCInfo(lcStore) << "timing: Flathub catalogue download took" << storeClock() - began << "ms, changed" << bool(changed);if (changed || !present) {Q_EMIT appstreamReady(dir);}- // Updates are only known once the remote's summary is fresh.- listInstalled();return true;}void FlatpakWorker::check(){- Q_EMIT checked(appstream(true));+ const bool ok = appstream(true);+ checkUpdates();+ Q_EMIT checked(ok);}void FlatpakWorker::listInstalled(){+ // Only what is on disk: this runs after every transaction, and nothing+ // here may wait on the network.GError *error = nullptr;QStringList apps;- QStringList updates;QHash<QString, qint64> sizes;-+ QHash<QString, qint64> updated;GPtrArray *refs = flatpak_installation_list_installed_refs_by_kind(m_installation, FLATPAK_REF_KIND_APP, nullptr, &error);if (refs) {for (guint i = 0; i < refs->len; ++i) {@@ -310,45 +577,127 @@ void FlatpakWorker::listInstalled()const QString name = QString::fromUtf8(flatpak_ref_get_name(FLATPAK_REF(ref)));apps << name;sizes.insert(name, qint64(flatpak_installed_ref_get_installed_size(ref)));+ // A deploy folder is made for each version, so its time is when+ // this version arrived.+ const QFileInfo deployed(QString::fromUtf8(flatpak_installed_ref_get_deploy_dir(ref)));+ updated.insert(name, deployed.lastModified().toMSecsSinceEpoch());}g_ptr_array_unref(refs);}takeError(error);+ Q_EMIT installedListed(apps, sizes, updated);+}++namespace+{+struct SizesState {+ QHash<QString, qint64> sizes;+};- refs = flatpak_installation_list_installed_refs_for_update(m_installation, nullptr, &error);+gboolean onSizesReady(FlatpakTransaction *transaction, gpointer data)+{+ auto state = static_cast<SizesState *>(data);+ GList *ops = flatpak_transaction_get_operations(transaction);+ for (GList *l = ops; l; l = l->next) {+ auto op = static_cast<FlatpakTransactionOperation *>(l->data);+ const char *ref = flatpak_transaction_operation_get_ref(op);+ if (!flatpak_transaction_operation_get_is_skipped(op) && !isRuntimeRef(ref)) {+ state->sizes.insert(refName(ref), qint64(flatpak_transaction_operation_get_download_size(op)));+ }+ }+ g_list_free_full(ops, g_object_unref);+ return FALSE;+}+}++QHash<QString, qint64> FlatpakWorker::updateSizes(const QStringList &refs)+{+ // Resolved and stopped before it downloads, like the install plans.+ SizesState state;+ if (refs.isEmpty()) {+ return state.sizes;+ }+ GMainContext *context = g_main_context_new();+ g_main_context_push_thread_default(context);+ GError *error = nullptr;+ FlatpakTransaction *transaction = flatpak_transaction_new_for_installation(m_installation, nullptr, &error);+ if (transaction) {+ flatpak_transaction_set_no_interaction(transaction, TRUE);+ for (const QString &ref : refs) {+ flatpak_transaction_add_update(transaction, ref.toUtf8().constData(), nullptr, nullptr, nullptr);+ }+ g_signal_connect(transaction, "ready", G_CALLBACK(onSizesReady), &state);+ flatpak_transaction_run(transaction, nullptr, nullptr);+ g_object_unref(transaction);+ }+ g_clear_error(&error);+ g_main_context_pop_thread_default(context);+ g_main_context_unref(context);+ return state.sizes;+}++void FlatpakWorker::checkUpdates()+{+ if (!ensureInstallation()) {+ return;+ }+ const qint64 began = storeClock();+ GError *error = nullptr;+ QStringList updates;+ QStringList full;+ // Asks Flathub for the current summary, so it never runs where something+ // waits on it.+ GPtrArray *refs = flatpak_installation_list_installed_refs_for_update(m_installation, nullptr, &error);if (refs) {for (guint i = 0; i < refs->len; ++i) {auto ref = static_cast<FlatpakInstalledRef *>(g_ptr_array_index(refs, i));if (flatpak_ref_get_kind(FLATPAK_REF(ref)) == FLATPAK_REF_KIND_APP) {updates << QString::fromUtf8(flatpak_ref_get_name(FLATPAK_REF(ref)));+ char *formatted = flatpak_ref_format_ref(FLATPAK_REF(ref));+ full << QString::fromUtf8(formatted);+ g_free(formatted);}}g_ptr_array_unref(refs);}takeError(error);-- Q_EMIT installedListed(apps, updates, sizes);+ const QHash<QString, qint64> sizes = updateSizes(full);+ qCInfo(lcStore) << "timing: Flathub update check took" << storeClock() - began << "ms";+ Q_EMIT updatesListed(updates, sizes);}-void FlatpakWorker::install(int job, const QString &ref)+void FlatpakWorker::install(const FlatpakBatch &jobs){- runTransaction(job, Op::Install, {ref});+ QList<int> ids;+ QStringList refs;+ for (const auto &[job, ref] : jobs) {+ ids << job;+ refs << ref;+ }+ runTransaction(ids, Op::Install, refs);}void FlatpakWorker::uninstall(int job, const QString &ref){- runTransaction(job, Op::Uninstall, {ref});+ runTransaction({job}, Op::Uninstall, {ref});}void FlatpakWorker::update(int job, const QStringList &refs){- runTransaction(job, Op::Update, refs);+ runTransaction({job}, Op::Update, refs);+}++void FlatpakWorker::installFile(int job, const QString &path, bool bundle)+{+ runTransaction({job}, bundle ? Op::InstallBundle : Op::InstallRefFile, {path});}-void FlatpakWorker::runTransaction(int job, Op op, const QStringList &refs)+void FlatpakWorker::runTransaction(const QList<int> &jobs, Op op, const QStringList &refs){if (!ensureInstallation()) {- Q_EMIT finished(job, false, QStringLiteral("Flathub is not available right now."));+ for (int job : jobs) {+ Q_EMIT finished(job, false, QStringLiteral("Flathub is not available right now."));+ }return;}@@ -360,10 +709,13 @@ void FlatpakWorker::runTransaction(int job, Op op, const QStringList &refs)GError *error = nullptr;FlatpakTransaction *transaction = flatpak_transaction_new_for_installation(m_installation, nullptr, &error);QString failure;+ TransactionState state{this, jobs};+ state.batch = jobs.size() > 1;if (!transaction) {failure = takeError(error);} else {flatpak_transaction_set_no_interaction(transaction, TRUE);+ // Runtimes already in the system installation are used from there.flatpak_transaction_add_default_dependency_sources(transaction);if (op == Op::Uninstall) {// Runtimes nothing else uses go with the app, as Windows would.@@ -384,44 +736,87 @@ void FlatpakWorker::runTransaction(int job, Op op, const QStringList &refs)takeError(error);}+ int added = 0;for (const QString &ref : std::as_const(targets)) {const QByteArray r = ref.toUtf8();- bool added = false;+ bool ok = false;switch (op) {case Op::Install:- added = flatpak_transaction_add_install(transaction, remoteName, r.constData(), nullptr, &error);+ ok = flatpak_transaction_add_install(transaction, remoteName, r.constData(), nullptr, &error);break;case Op::Uninstall:- added = flatpak_transaction_add_uninstall(transaction, r.constData(), &error);+ ok = flatpak_transaction_add_uninstall(transaction, r.constData(), &error);break;case Op::Update:- added = flatpak_transaction_add_update(transaction, r.constData(), nullptr, nullptr, &error);+ ok = flatpak_transaction_add_update(transaction, r.constData(), nullptr, nullptr, &error);break;- }- if (!added) {- if (error && g_error_matches(error, FLATPAK_ERROR, FLATPAK_ERROR_ALREADY_INSTALLED)) {- g_clear_error(&error);- continue;+ case Op::InstallRefFile: {+ // The file names its own repository. libflatpak adds it as+ // the app's origin, for this app alone; onAddNewRemote still+ // refuses to add it as a source of other apps.+ QFile file(ref);+ if (!file.open(QIODevice::ReadOnly)) {+ g_set_error_literal(&error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND, "The file can't be read.");+ break;}- failure = takeError(error);+ const QByteArray data = file.readAll();+ GBytes *bytes = g_bytes_new(data.constData(), gsize(data.size()));+ ok = flatpak_transaction_add_install_flatpakref(transaction, bytes, &error);+ g_bytes_unref(bytes);break;}+ case Op::InstallBundle: {+ GFile *file = g_file_new_for_path(r.constData());+ ok = flatpak_transaction_add_install_bundle(transaction, file, nullptr, &error);+ g_object_unref(file);+ break;+ }+ }+ if (ok) {+ ++added;+ continue;+ }+ if (error && g_error_matches(error, FLATPAK_ERROR, FLATPAK_ERROR_ALREADY_INSTALLED)) {+ g_clear_error(&error);+ continue;+ }+ if (state.batch) {+ state.refErrors.insert(ref, takeError(error));+ continue;+ }+ failure = takeError(error);+ break;}- if (failure.isEmpty() && !flatpak_transaction_is_empty(transaction)) {- TransactionState state{this, job};+ if (failure.isEmpty() && added > 0 && !flatpak_transaction_is_empty(transaction)) {g_signal_connect(transaction, "new-operation", G_CALLBACK(onNewOperation), &state);g_signal_connect(transaction, "ready", G_CALLBACK(onReady), &state);g_signal_connect(transaction, "operation-error", G_CALLBACK(onOperationError), &state);g_signal_connect(transaction, "add-new-remote", G_CALLBACK(onAddNewRemote), &state);g_signal_connect(transaction, "choose-remote-for-ref", G_CALLBACK(onChooseRemote), &state);- if (!flatpak_transaction_run(transaction, nullptr, &error)) {- failure = state.error.isEmpty() ? takeError(error) : state.error;+ GCancellable *cancellable = g_cancellable_new();+ {+ QMutexLocker lock(&m_runningMutex);+ m_runningJobs = jobs;+ m_cancellable = cancellable;+ }+ if (!flatpak_transaction_run(transaction, cancellable, &error)) {+ if (g_cancellable_is_cancelled(cancellable)) {+ failure = QString::fromLatin1(cancelledMarker);+ } else {+ failure = state.error.isEmpty() ? takeError(error) : state.error;+ }g_clear_error(&error);if (failure.isEmpty()) {failure = QStringLiteral("Flathub stopped part way through.");}}+ {+ QMutexLocker lock(&m_runningMutex);+ m_runningJobs.clear();+ m_cancellable = nullptr;+ }+ g_object_unref(cancellable);}g_object_unref(transaction);}@@ -431,14 +826,80 @@ void FlatpakWorker::runTransaction(int job, Op op, const QStringList &refs)flatpak_installation_drop_caches(m_installation, nullptr, nullptr);listInstalled();- Q_EMIT finished(job, failure.isEmpty(), failure);++ if (op != Op::Install || !state.batch) {+ Q_EMIT finished(jobs.value(0), failure.isEmpty(), failure);+ return;+ }+ // A batch reports each app by whether it is now installed, since one+ // app failing leaves the others in place.+ QSet<QString> installedNow;+ GPtrArray *apps = flatpak_installation_list_installed_refs_by_kind(m_installation, FLATPAK_REF_KIND_APP, nullptr, nullptr);+ if (apps) {+ for (guint i = 0; i < apps->len; ++i) {+ installedNow.insert(QString::fromUtf8(flatpak_ref_get_name(FLATPAK_REF(g_ptr_array_index(apps, i)))));+ }+ g_ptr_array_unref(apps);+ }+ for (int i = 0; i < jobs.size(); ++i) {+ const QString ref = refs.value(i);+ if (installedNow.contains(ref.section(QLatin1Char('/'), 1, 1))) {+ Q_EMIT finished(jobs.at(i), true, QString());+ continue;+ }+ QString message = failure == QLatin1String(cancelledMarker) ? failure : state.refErrors.value(ref);+ if (message.isEmpty()) {+ message = failure.isEmpty() ? state.error : failure;+ }+ if (message.isEmpty()) {+ message = QStringLiteral("Flathub stopped part way through.");+ }+ Q_EMIT finished(jobs.at(i), false, message);+ }+}++bool FlatpakWorker::plan(const QString &appId, const QString &ref)+{+ GMainContext *context = g_main_context_new();+ g_main_context_push_thread_default(context);+ GError *error = nullptr;+ PlanState state;+ state.appId = appId;+ FlatpakTransaction *transaction = flatpak_transaction_new_for_installation(m_installation, nullptr, &error);+ if (transaction) {+ flatpak_transaction_set_no_interaction(transaction, TRUE);+ flatpak_transaction_add_default_dependency_sources(transaction);+ if (flatpak_transaction_add_install(transaction, remoteName, ref.toUtf8().constData(), nullptr, &error)) {+ g_signal_connect(transaction, "ready", G_CALLBACK(onPlanReady), &state);+ g_signal_connect(transaction, "add-new-remote", G_CALLBACK(onAddNewRemote), &state);+ g_signal_connect(transaction, "choose-remote-for-ref", G_CALLBACK(onChooseRemote), &state);+ // Fails with "aborted" by design once onPlanReady has what it needs.+ flatpak_transaction_run(transaction, nullptr, &error);+ }+ g_clear_error(&error);+ g_object_unref(transaction);+ }+ g_clear_error(&error);+ g_main_context_pop_thread_default(context);+ g_main_context_unref(context);++ if (!state.resolved) {+ return false;+ }+ if (!state.metadata.isEmpty()) {+ Q_EMIT metadataReady(appId, state.metadata);+ }+ Q_EMIT planReady(appId, state.plan);+ return !state.metadata.isEmpty();}-void FlatpakWorker::metadata(const QString &appId, const QString &ref)+void FlatpakWorker::details(const QString &appId, const QString &ref){if (!ensureInstallation()) {+ Q_EMIT metadataReady(appId, QString());return;}+ const qint64 began = storeClock();GError *error = nullptr;GBytes *bytes = nullptr;FlatpakInstalledRef *installed = flatpak_installation_get_installed_ref(m_installation, FLATPAK_REF_KIND_APP, appId.toUtf8().constData(),@@ -448,22 +909,49 @@ void FlatpakWorker::metadata(const QString &appId, const QString &ref)g_object_unref(installed);}g_clear_error(&error);- if (!bytes && !ref.isEmpty()) {- FlatpakRef *parsed = flatpak_ref_parse(ref.toUtf8().constData(), &error);- if (parsed) {- bytes = flatpak_installation_fetch_remote_metadata_sync(m_installation, remoteName, parsed, nullptr, &error);- g_object_unref(parsed);+ if (bytes || ref.isEmpty()) {+ QString text;+ if (bytes) {+ gsize size = 0;+ const auto data = static_cast<const char *>(g_bytes_get_data(bytes, &size));+ text = QString::fromUtf8(data, qsizetype(size));+ g_bytes_unref(bytes);}+ // Said out loud even when empty, so the app's page stops waiting.+ Q_EMIT metadataReady(appId, text);+ return;+ }++ // The permissions first: they are one small fetch, while resolving the+ // whole install for its sizes fetches the runtime's details too.+ FlatpakRef *parsed = flatpak_ref_parse(ref.toUtf8().constData(), &error);+ if (parsed) {+ bytes = flatpak_installation_fetch_remote_metadata_sync(m_installation, remoteName, parsed, nullptr, &error);g_clear_error(&error);}- if (!bytes) {- // Said out loud, so the app's page stops waiting for it.- Q_EMIT metadataReady(appId, QString());- return;+ QString text;+ if (bytes) {+ gsize size = 0;+ const auto data = static_cast<const char *>(g_bytes_get_data(bytes, &size));+ text = QString::fromUtf8(data, qsizetype(size));+ g_bytes_unref(bytes);}- gsize size = 0;- const auto data = static_cast<const char *>(g_bytes_get_data(bytes, &size));- const QString text = QString::fromUtf8(data, qsizetype(size));- g_bytes_unref(bytes);Q_EMIT metadataReady(appId, text);+ qCInfo(lcStore) << "timing: permissions for" << appId << "took" << storeClock() - began << "ms";++ if (!plan(appId, ref) && parsed) {+ guint64 download = 0;+ guint64 installedSize = 0;+ if (flatpak_installation_fetch_remote_size_sync(m_installation, remoteName, parsed, &download, &installedSize, nullptr, &error)) {+ FlatpakPlan fallback;+ fallback.total = qint64(download);+ fallback.installed = qint64(installedSize);+ Q_EMIT planReady(appId, fallback);+ }+ g_clear_error(&error);+ }+ if (parsed) {+ g_object_unref(parsed);+ }+ qCInfo(lcStore) << "timing: sizes for" << appId << "took" << storeClock() - began << "ms";}diff --git a/packages/wildos-store/src/flatpakbackend.h b/packages/wildos-store/src/flatpakbackend.hindex 87de85e..7adbefd 100644--- a/packages/wildos-store/src/flatpakbackend.h+++ b/packages/wildos-store/src/flatpakbackend.h@@ -1,17 +1,42 @@#pragma once#include <QHash>+#include <QList>+#include <QMutex>#include <QObject>+#include <QPair>#include <QSet>#include <QStringList>#include <QThread>-// Flathub support through libflatpak. Everything that touches the network or-// the disk runs on a worker thread, so the window never stalls on a download.-// Apps go into the user's own installation: no password is needed, and the-// Flathub remote is added there the first time the Store runs.+// Flathub support through libflatpak. Apps go into the user's own+// installation: no password is needed, and the Flathub remote is added there+// the first time the Store runs.+//+// The work runs on three threads, each with its own FlatpakInstallation, so+// none waits on another: one keeps the catalogue and the update list fresh,+// one answers app pages (permissions and download sizes), and one installs.+// libflatpak takes the repository locks that make this safe, the same ones+// that let two flatpak commands run at once.class FlatpakWorker;+// What installing an app would download, from a transaction resolved and+// then stopped before it fetches anything.+struct FlatpakPlan {+ qint64 total = -1;+ qint64 shared = -1;+ QString runtime;+ // Room it takes once unpacked, which is what has to be free.+ qint64 installed = -1;+};+Q_DECLARE_METATYPE(FlatpakPlan)++using FlatpakBatch = QList<QPair<int, QString>>;++// The error both backends finish a job with when it was cancelled, so the+// Store can tell a cancel from a failure.+inline constexpr char cancelledMarker[] = "cancelled";+class FlatpakBackend : public QObject{Q_OBJECT@@ -21,47 +46,73 @@ public:~FlatpakBackend() override;void start();- void install(int job, const QString &ref);+ // Each pair is a job and the app ref it installs; they share one+ // transaction, so a runtime two of them need is fetched once.+ void install(const FlatpakBatch &jobs);void uninstall(int job, const QString &ref);void update(int job, const QStringList &refs);- void fetchMetadata(const QString &appId, const QString &ref);+ // Stops the transaction the job is in, at once, from this thread.+ void cancel(int job);+ void fetchDetails(const QString &appId, const QString &ref);void refreshAppstream();+ // A .flatpakref or .flatpak file someone opened. Local jobs have+ // negative numbers, so the Catalog's queue never mistakes them for its+ // own; they report through progress() and finished() like the rest.+ void installFile(int job, const QString &path, bool bundle);QString appstreamDir() const { return m_appstreamDir; }QSet<QString> installed() const { return m_installed; }QSet<QString> updates() const { return m_updates; }QHash<QString, qint64> installedSizes() const { return m_sizes; }+ // When each installed version arrived, and what each update downloads.+ QHash<QString, qint64> updatedTimes() const { return m_updated; }+ QHash<QString, qint64> updateSizes() const { return m_updateSizes; }bool isReady() const { return m_ready; }+ // Seeds the installed list from the last run until the real one is in.+ void seedInstalled(const QSet<QString> &apps);static QString userDataDir();Q_SIGNALS:void appstreamChanged();void installedChanged();- void progress(int job, int percent, const QString &status);+ void updatesChanged();+ // detail names a shared runtime while it downloads, with its size.+ void progress(int job, int percent, const QString &status, const QString &detail, qint64 done, qint64 total);void finished(int job, bool ok, const QString &error);void metadataReady(const QString &appId, const QString &metadata);+ void planReady(const QString &appId, const FlatpakPlan &plan);void unavailable(const QString &reason);// A check asked for with refreshAppstream() is over.void refreshFinished(bool ok);- // Internal, queued to the worker.+ // Internal, queued to the workers.void requestStart();- void requestInstall(int job, const QString &ref);+ void requestInstall(const FlatpakBatch &jobs);void requestUninstall(int job, const QString &ref);void requestUpdate(int job, const QStringList &refs);- void requestMetadata(const QString &appId, const QString &ref);- void requestAppstream(bool force);+ void requestDetails(const QString &appId, const QString &ref);void requestCheck();+ void requestUpdateCheck();+ void requestInstallFile(int job, const QString &path, bool bundle);private:- QThread m_thread;- FlatpakWorker *m_worker = nullptr;+ void checkUpdatesSoon();++ QThread m_catalogueThread;+ QThread m_detailsThread;+ QThread m_installThread;+ FlatpakWorker *m_catalogue = nullptr;+ FlatpakWorker *m_details = nullptr;+ FlatpakWorker *m_installer = nullptr;QString m_appstreamDir;QSet<QString> m_installed;QSet<QString> m_updates;QHash<QString, qint64> m_sizes;+ QHash<QString, qint64> m_updated;+ QHash<QString, qint64> m_updateSizes;bool m_ready = false;+ bool m_updateCheckQueued = false;};class FlatpakWorker : public QObject@@ -69,32 +120,45 @@ class FlatpakWorker : public QObjectQ_OBJECTpublic:- FlatpakWorker();+ explicit FlatpakWorker(const char *role);~FlatpakWorker() override;+ // Called from the window's thread while a transaction runs on this one.+ void cancel(int job);+public Q_SLOTS:void start();- void install(int job, const QString &ref);+ void install(const FlatpakBatch &jobs);void uninstall(int job, const QString &ref);void update(int job, const QStringList &refs);- void metadata(const QString &appId, const QString &ref);+ void installFile(int job, const QString &path, bool bundle);+ void details(const QString &appId, const QString &ref);bool appstream(bool force);void check();+ void checkUpdates();Q_SIGNALS:void appstreamReady(const QString &dir);- void installedListed(const QStringList &apps, const QStringList &updates, const QHash<QString, qint64> &sizes);- void progress(int job, int percent, const QString &status);+ void installedListed(const QStringList &apps, const QHash<QString, qint64> &sizes, const QHash<QString, qint64> &updated);+ void updatesListed(const QStringList &updates, const QHash<QString, qint64> &sizes);+ void progress(int job, int percent, const QString &status, const QString &detail, qint64 done, qint64 total);void finished(int job, bool ok, const QString &error);void metadataReady(const QString &appId, const QString &metadata);+ void planReady(const QString &appId, const FlatpakPlan &plan);void unavailable(const QString &reason);void checked(bool ok);private:- enum class Op { Install, Uninstall, Update };+ enum class Op { Install, Uninstall, Update, InstallRefFile, InstallBundle };bool ensureInstallation();void listInstalled();- void runTransaction(int job, Op op, const QStringList &refs);+ void runTransaction(const QList<int> &jobs, Op op, const QStringList &refs);+ bool plan(const QString &appId, const QString &ref);+ QHash<QString, qint64> updateSizes(const QStringList &refs);+ const char *m_role;struct _FlatpakInstallation *m_installation = nullptr;+ QMutex m_runningMutex;+ QList<int> m_runningJobs;+ struct _GCancellable *m_cancellable = nullptr;};diff --git a/packages/wildos-store/src/localpackage.cpp b/packages/wildos-store/src/localpackage.cppnew file mode 100644index 0000000..70a4171--- /dev/null+++ b/packages/wildos-store/src/localpackage.cpp@@ -0,0 +1,1013 @@+#include "localpackage.h"++#include "catalog.h"+#include "flatpakbackend.h"+#include "packagekitbackend.h"+#include "storeapp.h"++#include <PackageKit/Daemon>+#include <PackageKit/Transaction>++#include <KIO/ApplicationLauncherJob>+#include <KService>++#include <QCoreApplication>+#include <QDir>+#include <QFile>+#include <QFileInfo>+#include <QLocale>+#include <QMimeDatabase>+#include <QPointer>+#include <QProcess>+#include <QRegularExpression>+#include <QStandardPaths>+#include <QThreadPool>+#include <QUrl>+#include <QXmlStreamReader>++#include <flatpak.h>++using PackageKit::Daemon;+using PackageKit::Transaction;++struct LocalInfo {+ QString kind;+ bool readable = false;+ bool blocked = false;+ QString problem;+ QString name;+ QString id;+ QString summary;+ QString description;+ QString version;+ QString installedVersion;+ bool installed = false;+ // The file's version against the installed one: 1 newer, 0 the same,+ // -1 older.+ int compare = 0;+ qint64 fileSize = -1;+ qint64 installedSize = -1;+ QString homepage;+ QString maker;+ QString icon;+ QString origin;+ QString flathubId;+ QString desktopId;+ QStringList depends;+};++namespace+{+const QString unreadableText = QStringLiteral("This file can't be read. It may be damaged or only partly downloaded.");+const QString elsewhereText = QStringLiteral("It was probably made for Ubuntu or another system rather than Debian, which Wild OS is built on. "+ "Look for the app in the Store, or for a Flatpak or Debian version where you got this file.");++QString run(const QString &program, const QStringList &arguments, int *exitCode = nullptr)+{+ QProcess process;+ QProcessEnvironment env = QProcessEnvironment::systemEnvironment();+ env.insert(QStringLiteral("LC_ALL"), QStringLiteral("C"));+ process.setProcessEnvironment(env);+ process.start(program, arguments);+ const bool done = process.waitForFinished(60000);+ if (!done) {+ process.kill();+ process.waitForFinished(2000);+ }+ if (exitCode) {+ *exitCode = done && process.exitStatus() == QProcess::NormalExit ? process.exitCode() : -1;+ }+ return QString::fromUtf8(process.readAllStandardOutput());+}++QString kindOf(const QString &path)+{+ const QString suffix = QFileInfo(path).suffix().toLower();+ if (suffix == QLatin1String("deb")) {+ return QStringLiteral("deb");+ }+ if (suffix == QLatin1String("flatpakref")) {+ return QStringLiteral("flatpakref");+ }+ if (suffix == QLatin1String("flatpak")) {+ return QStringLiteral("flatpak");+ }+ const QMimeType mime = QMimeDatabase().mimeTypeForFile(path);+ if (mime.inherits(QStringLiteral("application/vnd.debian.binary-package"))) {+ return QStringLiteral("deb");+ }+ if (mime.inherits(QStringLiteral("application/vnd.flatpak.ref"))) {+ return QStringLiteral("flatpakref");+ }+ if (mime.inherits(QStringLiteral("application/vnd.flatpak"))) {+ return QStringLiteral("flatpak");+ }+ return {};+}++QString archLabel(const QString &arch)+{+ if (arch == QLatin1String("amd64") || arch == QLatin1String("x86_64")) {+ return QStringLiteral("64-bit Intel and AMD computers");+ }+ if (arch == QLatin1String("i386") || arch == QLatin1String("i686")) {+ return QStringLiteral("older 32-bit computers");+ }+ if (arch == QLatin1String("arm64") || arch == QLatin1String("aarch64")) {+ return QStringLiteral("64-bit ARM computers");+ }+ if (arch.startsWith(QLatin1String("arm"))) {+ return QStringLiteral("32-bit ARM computers");+ }+ return QStringLiteral("another kind of computer");+}++QString archProblem(const QString &arch, const QString &native)+{+ return QStringLiteral("This package is made for %1 (%2), so it can't run on this computer. Look for the %3 version where you got it.")+ .arg(archLabel(arch), arch, native);+}++QString listText(QStringList items)+{+ if (items.size() > 4) {+ const int more = int(items.size()) - 3;+ items = items.mid(0, 3);+ items << QStringLiteral("%1 more").arg(more);+ }+ if (items.size() < 2) {+ return items.value(0);+ }+ return QStringList(items.mid(0, items.size() - 1)).join(QStringLiteral(", ")) + QStringLiteral(" and ") + items.constLast();+}++// PackageKit passes apt's own explanation on: "foo : Depends: libbar (>=+// 2) but it is not installable".+QString dependsProblem(const QString &details)+{+ QStringList missing;+ static const QRegularExpression depends(QStringLiteral("(?:Pre-)?Depends: ([A-Za-z0-9.+-]+)"));+ auto it = depends.globalMatch(details);+ while (it.hasNext()) {+ const QString name = it.next().captured(1);+ if (!missing.contains(name)) {+ missing << name;+ }+ }+ if (missing.isEmpty()) {+ return QStringLiteral("It needs parts Wild OS doesn't have. ") + elsewhereText;+ }+ return QStringLiteral("It needs %1, which Wild OS doesn't have. ").arg(listText(missing)) + elsewhereText;+}++QString debError(Transaction::Error error, const QString &details)+{+ switch (error) {+ case Transaction::ErrorDepResolutionFailed:+ return dependsProblem(details);+ case Transaction::ErrorIncompatibleArchitecture:+ return QStringLiteral("This package is made for another kind of computer, so it can't run on this one.");+ case Transaction::ErrorInvalidPackageFile:+ case Transaction::ErrorPackageCorrupt:+ return unreadableText;+ case Transaction::ErrorFileConflicts:+ return QStringLiteral("It would overwrite files that belong to another part of Wild OS, so it wasn't installed.");+ case Transaction::ErrorPackageFailedToConfigure:+ case Transaction::ErrorPackageFailedToInstall:+ return QStringLiteral("The package's own setup failed, so it may be only partly installed. Its maker may have a newer version.");+ default:+ return PackageKitBackend::errorText(error, false);+ }+}++// A Debian control file: "Field: value", with continuation lines that start+// with a space.+QHash<QString, QString> controlFields(const QString &text)+{+ QHash<QString, QString> fields;+ QString last;+ for (const QString &line : text.split(QLatin1Char('\n'))) {+ if ((line.startsWith(QLatin1Char(' ')) || line.startsWith(QLatin1Char('\t'))) && !last.isEmpty()) {+ fields[last] += QLatin1Char('\n') + line.mid(1);+ continue;+ }+ const int colon = line.indexOf(QLatin1Char(':'));+ if (colon > 0) {+ last = line.left(colon).trimmed();+ fields.insert(last, line.mid(colon + 1).trimmed());+ }+ }+ return fields;+}++// The long description's own markup: a lone "." is a blank line, a line+// with more indent is kept as it is, the rest runs on.+QString debDescription(const QString &body)+{+ QStringList paragraphs;+ QString current;+ for (const QString &line : body.split(QLatin1Char('\n'))) {+ if (line.trimmed() == QLatin1String(".")) {+ if (!current.isEmpty()) {+ paragraphs << current;+ current.clear();+ }+ } else if (line.startsWith(QLatin1Char(' '))) {+ current += (current.isEmpty() ? QString() : QStringLiteral("\n")) + line.trimmed();+ } else {+ current += (current.isEmpty() ? QString() : QStringLiteral(" ")) + line.trimmed();+ }+ }+ if (!current.isEmpty()) {+ paragraphs << current;+ }+ return paragraphs.join(QStringLiteral("\n\n"));+}++QStringList dependNames(const QString &field)+{+ QStringList names;+ for (const QString &clause : field.split(QLatin1Char(','), Qt::SkipEmptyParts)) {+ QStringList alternatives;+ for (QString alt : clause.split(QLatin1Char('|'), Qt::SkipEmptyParts)) {+ alt = alt.section(QLatin1Char('('), 0, 0).section(QLatin1Char('['), 0, 0).section(QLatin1Char('<'), 0, 0).trimmed();+ alt = alt.section(QLatin1Char(':'), 0, 0);+ if (!alt.isEmpty()) {+ alternatives << alt;+ }+ }+ if (!alternatives.isEmpty()) {+ names << alternatives.join(QStringLiteral(" or "));+ }+ }+ return names;+}++// The launcher and icon a .deb carries, so the page can call the app what+// Start will. Only regular files leave the archive, each through cat into a+// file named by a hash of its path, so nothing in it can write outside the+// scratch folder by way of a link or an odd name.+void readDebLauncher(const QString &path, const QString &scratch, LocalInfo &info)+{+ const QString out = QDir(scratch).filePath(QStringLiteral("files"));+ QDir().mkpath(out);+ QProcess unpack;+ QProcess tar;+ unpack.setStandardOutputProcess(&tar);+ QProcessEnvironment env = QProcessEnvironment::systemEnvironment();+ env.insert(QStringLiteral("WILDOS_OUT"), out);+ tar.setProcessEnvironment(env);+ unpack.start(QStringLiteral("dpkg-deb"), {QStringLiteral("--fsys-tarfile"), path});+ tar.start(QStringLiteral("tar"), {+ QStringLiteral("-x"),+ QStringLiteral("--wildcards"),+ QStringLiteral("--to-command=n=$(printf %s \"$TAR_FILENAME\" | md5sum | cut -c1-32); printf %s \"$TAR_FILENAME\" > \"$WILDOS_OUT/$n.name\"; cat > \"$WILDOS_OUT/$n\""),+ QStringLiteral("*usr/share/applications/*.desktop"),+ QStringLiteral("*usr/share/icons/hicolor/*/apps/*"),+ QStringLiteral("*usr/share/pixmaps/*"),+ });+ unpack.waitForFinished(120000);+ tar.waitForFinished(120000);++ QHash<QString, QString> files;+ const auto names = QDir(out).entryInfoList({QStringLiteral("*.name")}, QDir::Files);+ for (const QFileInfo &name : names) {+ QFile file(name.filePath());+ if (file.open(QIODevice::ReadOnly)) {+ QString member = QString::fromUtf8(file.readAll());+ if (member.startsWith(QLatin1String("./"))) {+ member = member.mid(1);+ } else if (!member.startsWith(QLatin1Char('/'))) {+ member.prepend(QLatin1Char('/'));+ }+ files.insert(member, name.path() + QLatin1Char('/') + name.completeBaseName());+ }+ }++ QStringList launchers;+ for (auto it = files.cbegin(); it != files.cend(); ++it) {+ if (it.key().startsWith(QLatin1String("/usr/share/applications/")) && it.key().endsWith(QLatin1String(".desktop"))) {+ launchers << it.key();+ }+ }+ launchers.sort();+ QString iconName;+ for (const QString &launcher : std::as_const(launchers)) {+ GKeyFile *key = g_key_file_new();+ if (g_key_file_load_from_file(key, files.value(launcher).toUtf8().constData(), G_KEY_FILE_NONE, nullptr)) {+ const char *group = "Desktop Entry";+ char *type = g_key_file_get_string(key, group, "Type", nullptr);+ const bool app = qstrcmp(type, "Application") == 0 && !g_key_file_get_boolean(key, group, "NoDisplay", nullptr);+ g_free(type);+ if (app) {+ char *name = g_key_file_get_locale_string(key, group, "Name", nullptr, nullptr);+ char *comment = g_key_file_get_locale_string(key, group, "Comment", nullptr, nullptr);+ char *icon = g_key_file_get_string(key, group, "Icon", nullptr);+ info.name = QString::fromUtf8(name).trimmed();+ if (info.summary.isEmpty()) {+ info.summary = QString::fromUtf8(comment).trimmed();+ }+ iconName = QString::fromUtf8(icon).trimmed();+ info.desktopId = QFileInfo(launcher).fileName();+ g_free(name);+ g_free(comment);+ g_free(icon);+ }+ }+ g_key_file_free(key);+ if (!info.desktopId.isEmpty()) {+ break;+ }+ }++ if (iconName.isEmpty()) {+ return;+ }+ QStringList candidates;+ if (iconName.startsWith(QLatin1Char('/'))) {+ candidates << iconName;+ } else {+ const QString hicolor = QStringLiteral("/usr/share/icons/hicolor/%1/apps/%2.%3");+ candidates << hicolor.arg(QStringLiteral("scalable"), iconName, QStringLiteral("svg"));+ for (const char *size : {"512x512", "256x256", "192x192", "128x128", "96x96", "64x64", "48x48"}) {+ candidates << hicolor.arg(QLatin1String(size), iconName, QStringLiteral("png"));+ }+ candidates << QStringLiteral("/usr/share/pixmaps/%1.png").arg(iconName) << QStringLiteral("/usr/share/pixmaps/%1.svg").arg(iconName);+ }+ for (const QString &candidate : std::as_const(candidates)) {+ const QString source = files.value(candidate);+ if (source.isEmpty()) {+ continue;+ }+ const QString target = QDir(scratch).filePath(QStringLiteral("icon.") + QFileInfo(candidate).suffix());+ if (QFile::copy(source, target)) {+ info.icon = QUrl::fromLocalFile(target).toString();+ }+ return;+ }+}++LocalInfo readDeb(const QString &path, const QString &scratch)+{+ LocalInfo info;+ info.kind = QStringLiteral("deb");+ int code = 0;+ const auto fields = controlFields(run(QStringLiteral("dpkg-deb"), {QStringLiteral("-f"), path}, &code));+ info.id = fields.value(QStringLiteral("Package"));+ if (code != 0 || info.id.isEmpty()) {+ info.problem = unreadableText;+ return info;+ }+ info.readable = true;+ info.version = fields.value(QStringLiteral("Version"));+ const QString description = fields.value(QStringLiteral("Description"));+ info.summary = description.section(QLatin1Char('\n'), 0, 0).trimmed();+ info.description = debDescription(description.section(QLatin1Char('\n'), 1));+ info.homepage = fields.value(QStringLiteral("Homepage"));+ info.maker = fields.value(QStringLiteral("Maintainer")).section(QLatin1Char('<'), 0, 0).trimmed();+ info.depends = dependNames(fields.value(QStringLiteral("Pre-Depends"))) + dependNames(fields.value(QStringLiteral("Depends")));+ bool sized = false;+ const qint64 kib = fields.value(QStringLiteral("Installed-Size")).toLongLong(&sized);+ info.installedSize = sized ? kib * 1024 : -1;++ const QString arch = fields.value(QStringLiteral("Architecture"));+ const QString native = run(QStringLiteral("dpkg"), {QStringLiteral("--print-architecture")}).trimmed();+ const QStringList foreign = run(QStringLiteral("dpkg"), {QStringLiteral("--print-foreign-architectures")}).split(QLatin1Char('\n'), Qt::SkipEmptyParts);+ if (!arch.isEmpty() && arch != QLatin1String("all") && !native.isEmpty() && arch != native && !foreign.contains(arch)) {+ info.blocked = true;+ info.problem = archProblem(arch, native);+ }++ const QString status = run(QStringLiteral("dpkg-query"), {QStringLiteral("-W"), QStringLiteral("-f=${db:Status-Status}\\n${Version}\\n"), info.id}, &code);+ const QStringList lines = status.split(QLatin1Char('\n'));+ if (code == 0 && lines.value(0) == QLatin1String("installed")) {+ info.installed = true;+ info.installedVersion = lines.value(1);+ const auto test = [&](const char *op) {+ int result = 1;+ run(QStringLiteral("dpkg"), {QStringLiteral("--compare-versions"), info.version, QLatin1String(op), info.installedVersion}, &result);+ return result == 0;+ };+ info.compare = test("gt") ? 1 : test("eq") ? 0 : -1;+ }++ readDebLauncher(path, scratch, info);+ if (info.name.isEmpty()) {+ info.name = info.id;+ }+ return info;+}++// Whether the app is in the user's or the system's Flatpak installation,+// and the version it says it is.+void flatpakInstalled(LocalInfo &info, const QString &branch)+{+ FlatpakInstallation *installations[2] = {flatpak_installation_new_user(nullptr, nullptr), flatpak_installation_new_system(nullptr, nullptr)};+ for (FlatpakInstallation *installation : installations) {+ if (!installation) {+ continue;+ }+ if (!info.installed) {+ FlatpakInstalledRef *ref = flatpak_installation_get_installed_ref(installation, FLATPAK_REF_KIND_APP, info.id.toUtf8().constData(), nullptr,+ branch.isEmpty() ? nullptr : branch.toUtf8().constData(), nullptr, nullptr);+ if (ref) {+ info.installed = true;+ info.installedVersion = QString::fromUtf8(flatpak_installed_ref_get_appdata_version(ref));+ g_object_unref(ref);+ }+ }+ g_object_unref(installation);+ }+}++QString keyString(GKeyFile *file, const char *key)+{+ char *value = g_key_file_get_string(file, "Flatpak Ref", key, nullptr);+ const QString text = QString::fromUtf8(value).trimmed();+ g_free(value);+ return text;+}++LocalInfo readFlatpakRef(const QString &path)+{+ LocalInfo info;+ info.kind = QStringLiteral("flatpakref");+ GKeyFile *file = g_key_file_new();+ if (!g_key_file_load_from_file(file, path.toUtf8().constData(), G_KEY_FILE_NONE, nullptr) || keyString(file, "Name").isEmpty()) {+ g_key_file_free(file);+ info.problem = unreadableText;+ return info;+ }+ info.readable = true;+ info.id = keyString(file, "Name");+ info.name = keyString(file, "Title");+ if (info.name.isEmpty()) {+ info.name = info.id.section(QLatin1Char('.'), -1);+ }+ info.summary = keyString(file, "Comment");+ info.description = keyString(file, "Description");+ info.homepage = keyString(file, "Homepage");+ const QString branch = keyString(file, "Branch");+ const QUrl url(keyString(file, "Url"));+ info.origin = url.host();+ if (info.origin == QLatin1String("dl.flathub.org") || info.origin == QLatin1String("flathub.org")) {+ info.flathubId = info.id;+ }+ if (g_key_file_get_boolean(file, "Flatpak Ref", "IsRuntime", nullptr)) {+ info.blocked = true;+ info.problem = QStringLiteral("This file is for a part apps run on, not an app. Wild OS fetches those by itself when an app needs one.");+ }+ g_key_file_free(file);+ flatpakInstalled(info, branch);+ return info;+}++QByteArray gunzip(GBytes *bytes)+{+ QByteArray out;+ GConverter *converter = G_CONVERTER(g_zlib_decompressor_new(G_ZLIB_COMPRESSOR_FORMAT_GZIP));+ GInputStream *memory = g_memory_input_stream_new_from_bytes(bytes);+ GInputStream *stream = g_converter_input_stream_new(memory, converter);+ char buffer[16384];+ gssize n = 0;+ while ((n = g_input_stream_read(stream, buffer, sizeof buffer, nullptr, nullptr)) > 0 && out.size() < 32 * 1024 * 1024) {+ out.append(buffer, n);+ }+ g_object_unref(stream);+ g_object_unref(memory);+ g_object_unref(converter);+ return out;+}++// The first component of the AppStream data a bundle carries, in the+// untranslated text.+void readAppstream(const QByteArray &xml, LocalInfo &info)+{+ QXmlStreamReader reader(xml);+ bool inComponent = false;+ bool inDescription = false;+ bool inDeveloper = false;+ QStringList paragraphs;+ while (!reader.atEnd()) {+ reader.readNext();+ if (reader.isEndElement()) {+ if (reader.name() == QLatin1String("component")) {+ break;+ }+ if (reader.name() == QLatin1String("description")) {+ inDescription = false;+ } else if (reader.name() == QLatin1String("developer")) {+ inDeveloper = false;+ }+ continue;+ }+ if (!reader.isStartElement()) {+ continue;+ }+ const QString name = reader.name().toString();+ if (name == QLatin1String("component")) {+ inComponent = true;+ continue;+ }+ if (!inComponent) {+ continue;+ }+ if (!reader.attributes().value(QLatin1String("xml:lang")).isEmpty()+ || !reader.attributes().value(QLatin1String("http://www.w3.org/XML/1998/namespace"), QLatin1String("lang")).isEmpty()) {+ reader.skipCurrentElement();+ continue;+ }+ if (name == QLatin1String("description")) {+ inDescription = true;+ } else if (name == QLatin1String("developer")) {+ inDeveloper = true;+ } else if (inDescription && (name == QLatin1String("p") || name == QLatin1String("li"))) {+ const QString text = reader.readElementText(QXmlStreamReader::IncludeChildElements).simplified();+ if (!text.isEmpty()) {+ paragraphs << (name == QLatin1String("li") ? QStringLiteral("- ") + text : text);+ }+ } else if (name == QLatin1String("name")) {+ const QString text = reader.readElementText(QXmlStreamReader::IncludeChildElements).simplified();+ if (inDeveloper) {+ info.maker = text;+ } else if (info.name.isEmpty()) {+ info.name = text;+ }+ } else if (name == QLatin1String("developer_name") && info.maker.isEmpty()) {+ info.maker = reader.readElementText(QXmlStreamReader::IncludeChildElements).simplified();+ } else if (name == QLatin1String("summary") && info.summary.isEmpty()) {+ info.summary = reader.readElementText(QXmlStreamReader::IncludeChildElements).simplified();+ } else if (name == QLatin1String("url") && reader.attributes().value(QLatin1String("type")) == QLatin1String("homepage")) {+ info.homepage = reader.readElementText().trimmed();+ } else if (name == QLatin1String("release") && info.version.isEmpty()) {+ info.version = reader.attributes().value(QLatin1String("version")).toString();+ }+ }+ info.description = paragraphs.join(QStringLiteral("\n\n"));+}++LocalInfo readBundle(const QString &path, const QString &scratch)+{+ LocalInfo info;+ info.kind = QStringLiteral("flatpak");+ GFile *file = g_file_new_for_path(path.toUtf8().constData());+ FlatpakBundleRef *bundle = flatpak_bundle_ref_new(file, nullptr);+ g_object_unref(file);+ if (!bundle) {+ info.problem = unreadableText;+ return info;+ }+ info.readable = true;+ FlatpakRef *ref = FLATPAK_REF(bundle);+ info.id = QString::fromUtf8(flatpak_ref_get_name(ref));+ const QString arch = QString::fromUtf8(flatpak_ref_get_arch(ref));+ const QString branch = QString::fromUtf8(flatpak_ref_get_branch(ref));+ info.installedSize = qint64(flatpak_bundle_ref_get_installed_size(bundle));++ char *origin = flatpak_bundle_ref_get_origin(bundle);+ info.origin = QUrl(QString::fromUtf8(origin)).host();+ g_free(origin);++ if (GBytes *appstream = flatpak_bundle_ref_get_appstream(bundle)) {+ readAppstream(gunzip(appstream), info);+ g_bytes_unref(appstream);+ }+ if (info.name.isEmpty()) {+ info.name = info.id.section(QLatin1Char('.'), -1);+ }+ GBytes *icon = flatpak_bundle_ref_get_icon(bundle, 128);+ if (!icon) {+ icon = flatpak_bundle_ref_get_icon(bundle, 64);+ }+ if (icon) {+ QFile out(QDir(scratch).filePath(QStringLiteral("icon.png")));+ gsize size = 0;+ const auto data = static_cast<const char *>(g_bytes_get_data(icon, &size));+ if (out.open(QIODevice::WriteOnly) && out.write(data, qint64(size)) == qint64(size)) {+ info.icon = QUrl::fromLocalFile(out.fileName()).toString();+ }+ g_bytes_unref(icon);+ }++ if (flatpak_ref_get_kind(ref) != FLATPAK_REF_KIND_APP) {+ info.blocked = true;+ info.problem = QStringLiteral("This file is for a part apps run on, not an app. Wild OS fetches those by itself when an app needs one.");+ } else {+ bool supported = false;+ const char *const *arches = flatpak_get_supported_arches();+ for (int i = 0; arches && arches[i]; ++i) {+ supported = supported || arch == QLatin1String(arches[i]);+ }+ if (!supported) {+ info.blocked = true;+ info.problem = archProblem(arch, QString::fromUtf8(flatpak_get_default_arch()));+ }+ }+ g_object_unref(bundle);+ flatpakInstalled(info, branch);+ return info;+}++KService::Ptr launcher(const QString &desktopId)+{+ if (desktopId.isEmpty()) {+ return {};+ }+ KService::Ptr service = KService::serviceByStorageId(desktopId);+ if (service && service->isValid()) {+ return service;+ }+ // Installed a moment ago: KDE's service cache has not caught up yet.+ const QString file = QStandardPaths::locate(QStandardPaths::ApplicationsLocation, desktopId);+ if (!file.isEmpty()) {+ service = KService::Ptr(new KService(file));+ if (service->isValid()) {+ return service;+ }+ }+ return {};+}++int nextJob = -1;+}++LocalPackage::LocalPackage(QObject *parent)+ : QObject(parent)+{+ Catalog *catalog = Catalog::instance();+ if (!catalog) {+ return;+ }+ FlatpakBackend *flatpak = catalog->flatpakBackend();+ connect(flatpak, &FlatpakBackend::progress, this, [this](int job, int percent, const QString &status, const QString &, qint64, qint64) {+ if (job != m_job || m_state != QLatin1String("working")) {+ return;+ }+ m_progress = percent;+ m_phase = status;+ Q_EMIT changed();+ });+ connect(flatpak, &FlatpakBackend::finished, this, [this](int job, bool ok, const QString &error) {+ if (job == m_job && m_state == QLatin1String("working")) {+ finish(ok, error);+ }+ });+}++LocalPackage::~LocalPackage() = default;++QString LocalPackage::fileArgument(const QString &argument)+{+ if (argument.isEmpty()) {+ return {};+ }+ QString local;+ if (argument.startsWith(QLatin1String("file:"), Qt::CaseInsensitive)) {+ local = QUrl(argument).toLocalFile();+ } else if (argument.contains(QLatin1String("://")) || argument.startsWith(QLatin1String("appstream:"), Qt::CaseInsensitive)) {+ return {};+ } else {+ local = argument;+ }+ const QFileInfo info(local);+ if (!info.isFile() || kindOf(info.absoluteFilePath()).isEmpty()) {+ return {};+ }+ return info.absoluteFilePath();+}++void LocalPackage::setPath(const QString &path)+{+ const QString local = path.startsWith(QLatin1String("file:")) ? QUrl(path).toLocalFile() : path;+ if (local == m_path) {+ return;+ }+ m_path = local;+ Q_EMIT pathChanged();+ read();+}++void LocalPackage::read()+{+ ++m_generation;+ m_info.reset();+ m_extras.clear();+ m_removes.clear();+ m_checkingDepends = false;+ m_problem.clear();+ m_progress = -1;+ m_phase.clear();+ m_state = QStringLiteral("reading");+ m_scratch = std::make_shared<QTemporaryDir>();+ Q_EMIT changed();++ const QString kind = kindOf(m_path);+ if (kind.isEmpty() || !QFileInfo(m_path).isFile()) {+ LocalInfo info;+ info.problem = QFileInfo::exists(m_path) ? QStringLiteral("The Store can install .deb, .flatpakref and .flatpak files, and this isn't one of them.")+ : QStringLiteral("This file isn't there any more. It may have been moved or deleted.");+ adopt(info);+ return;+ }++ QPointer<LocalPackage> self(this);+ const int generation = m_generation;+ const QString path = m_path;+ const QString scratch = m_scratch->isValid() ? m_scratch->path() : QDir::tempPath();+ // Holds the folder until the reading is done, even if the page closes.+ std::shared_ptr<QTemporaryDir> keep = m_scratch;+ QThreadPool::globalInstance()->start([self, generation, path, scratch, kind, keep] {+ LocalInfo info = kind == QLatin1String("deb") ? readDeb(path, scratch)+ : kind == QLatin1String("flatpakref") ? readFlatpakRef(path)+ : readBundle(path, scratch);+ info.fileSize = QFileInfo(path).size();+ QMetaObject::invokeMethod(qApp, [self, generation, info, keep] {+ if (self && self->m_generation == generation) {+ self->adopt(info);+ }+ }, Qt::QueuedConnection);+ });+}++void LocalPackage::adopt(const LocalInfo &info)+{+ m_info = std::make_unique<LocalInfo>(info);+ m_problem = info.problem;+ if (!info.readable) {+ m_state = QStringLiteral("unreadable");+ } else if (info.blocked) {+ m_state = QStringLiteral("blocked");+ } else if (!info.installed) {+ m_state = QStringLiteral("get");+ } else if (info.kind != QLatin1String("deb")) {+ m_state = QStringLiteral("installed");+ } else {+ m_state = info.compare > 0 ? QStringLiteral("update") : info.compare == 0 ? QStringLiteral("installed") : QStringLiteral("newer");+ }+ Q_EMIT changed();+ if (info.kind == QLatin1String("deb") && (m_state == QLatin1String("get") || m_state == QLatin1String("update"))) {+ checkDepends();+ }+}++// PackageKit works out what the package would bring with it, or that it+// can't be installed at all, without changing anything. A simulation needs+// no password; it is marked non-interactive so it can never ask for one.+void LocalPackage::checkDepends()+{+ Catalog *catalog = Catalog::instance();+ if (!catalog || !catalog->packageKitBackend()->isAvailable()) {+ return;+ }+ m_checkingDepends = true;+ Q_EMIT changed();++ const int generation = m_generation;+ const QString self = m_info->id;+ auto extras = std::make_shared<QStringList>();+ auto removes = std::make_shared<QStringList>();+ auto error = std::make_shared<std::pair<Transaction::Error, QString>>(Transaction::ErrorUnknown, QString());+ auto failed = std::make_shared<bool>(false);+ Transaction *t = Daemon::installFiles({m_path}, Transaction::TransactionFlagSimulate);+ t->setHints(QStringList{QStringLiteral("interactive=false")});+ connect(t, &Transaction::package, this, [extras, removes, self](Transaction::Info info, const QString &id, const QString &) {+ const QString name = Transaction::packageName(id);+ if (name == self) {+ return;+ }+ if (info == Transaction::InfoRemoving || info == Transaction::InfoObsoleting) {+ removes->append(name);+ } else if (info == Transaction::InfoInstalling || info == Transaction::InfoUpdating) {+ extras->append(name);+ }+ });+ connect(t, &Transaction::errorCode, this, [error, failed](Transaction::Error code, const QString &details) {+ *failed = true;+ *error = {code, details};+ });+ connect(t, &Transaction::finished, this, [this, generation, extras, removes, error, failed](Transaction::Exit status, uint) {+ if (generation != m_generation) {+ return;+ }+ m_checkingDepends = false;+ if (status == Transaction::ExitSuccess && !*failed) {+ extras->removeDuplicates();+ removes->removeDuplicates();+ extras->sort();+ removes->sort();+ m_extras = *extras;+ m_removes = *removes;+ } else if (m_state == QLatin1String("get") || m_state == QLatin1String("update")) {+ // Only what the package itself rules out stops it here; a check+ // that could not run (no answer, no network) leaves the install+ // to say what went wrong.+ const auto code = error->first;+ if (code == Transaction::ErrorDepResolutionFailed || code == Transaction::ErrorIncompatibleArchitecture+ || code == Transaction::ErrorInvalidPackageFile || code == Transaction::ErrorPackageCorrupt+ || code == Transaction::ErrorFileConflicts) {+ m_problem = debError(code, error->second);+ m_state = QStringLiteral("blocked");+ }+ }+ Q_EMIT changed();+ });+}++void LocalPackage::install()+{+ if (!m_info || (m_state != QLatin1String("get") && m_state != QLatin1String("update") && m_state != QLatin1String("failed"))) {+ return;+ }+ m_problem.clear();+ m_progress = -1;+ m_phase = QStringLiteral("prepare");+ m_state = QStringLiteral("working");+ Q_EMIT changed();+ if (m_info->kind == QLatin1String("deb")) {+ installDeb();+ } else {+ installFlatpak();+ }+}++void LocalPackage::installDeb()+{+ Catalog *catalog = Catalog::instance();+ if (!catalog || !catalog->packageKitBackend()->isAvailable()) {+ finish(false, QStringLiteral("The part of Wild OS that installs packages isn't running. Restart the computer and try again."));+ return;+ }+ auto error = std::make_shared<QString>();+ // Not "only trusted": a file is never signed by a repository Wild OS+ // knows, so PackageKit asks under its own action for unsigned packages,+ // which the permission prompt shows as not verified.+ Transaction *t = Daemon::installFiles({m_path}, Transaction::TransactionFlagNone);+ connect(t, &Transaction::percentageChanged, this, [this, t] {+ if (m_state != QLatin1String("working")) {+ return;+ }+ const uint pct = t->percentage();+ switch (t->status()) {+ case Transaction::StatusWaitingForAuth:+ m_phase = QStringLiteral("auth");+ break;+ case Transaction::StatusDownload:+ m_phase = QStringLiteral("download");+ break;+ case Transaction::StatusInstall:+ case Transaction::StatusUpdate:+ case Transaction::StatusCommit:+ case Transaction::StatusRunHook:+ m_phase = QStringLiteral("install");+ break;+ default:+ break;+ }+ m_progress = pct > 100 ? -1 : int(pct);+ Q_EMIT changed();+ });+ connect(t, &Transaction::statusChanged, t, &Transaction::percentageChanged);+ connect(t, &Transaction::errorCode, this, [error](Transaction::Error code, const QString &details) {+ *error = debError(code, details);+ });+ connect(t, &Transaction::finished, this, [this, error](Transaction::Exit status, uint) {+ if (Catalog *catalog = Catalog::instance()) {+ catalog->packageKitBackend()->listInstalled();+ }+ if (status == Transaction::ExitSuccess) {+ finish(true, {});+ } else if (status == Transaction::ExitCancelled) {+ finish(false, QString::fromLatin1(cancelledMarker));+ } else {+ finish(false, error->isEmpty() ? QStringLiteral("Something went wrong. Try again in a few minutes.") : *error);+ }+ });+}++void LocalPackage::installFlatpak()+{+ Catalog *catalog = Catalog::instance();+ if (!catalog) {+ finish(false, QStringLiteral("Something went wrong. Try again in a few minutes."));+ return;+ }+ m_job = nextJob--;+ catalog->flatpakBackend()->installFile(m_job, m_path, m_info->kind == QLatin1String("flatpak"));+}++void LocalPackage::finish(bool ok, const QString &error)+{+ m_progress = -1;+ m_phase.clear();+ if (ok) {+ StoreApp::forgetServices();+ m_info->installed = true;+ m_info->installedVersion = m_info->version;+ m_info->compare = 0;+ m_state = QStringLiteral("done");+ } else if (error == QLatin1String(cancelledMarker)) {+ m_state = m_info->installed ? QStringLiteral("update") : QStringLiteral("get");+ } else {+ m_problem = error;+ m_state = QStringLiteral("failed");+ }+ Q_EMIT changed();+}++QString LocalPackage::kind() const+{+ return m_info ? m_info->kind : kindOf(m_path);+}++QString LocalPackage::fileName() const+{+ return QFileInfo(m_path).fileName();+}++#define INFO_FIELD(fn, field) \+ QString LocalPackage::fn() const \+ { \+ return m_info ? m_info->field : QString(); \+ }++INFO_FIELD(id, id)+INFO_FIELD(summary, summary)+INFO_FIELD(description, description)+INFO_FIELD(version, version)+INFO_FIELD(installedVersion, installedVersion)+INFO_FIELD(homepage, homepage)+INFO_FIELD(maker, maker)+INFO_FIELD(origin, origin)+INFO_FIELD(flathubId, flathubId)++QString LocalPackage::name() const+{+ if (m_info && !m_info->name.isEmpty()) {+ return m_info->name;+ }+ return QFileInfo(m_path).completeBaseName();+}++QStringList LocalPackage::depends() const+{+ return m_info ? m_info->depends : QStringList();+}++QString LocalPackage::fileSizeText() const+{+ if (!m_info || m_info->fileSize < 0 || kind() == QLatin1String("flatpakref")) {+ return {};+ }+ return QLocale().formattedDataSize(m_info->fileSize, m_info->fileSize >= 1000 * 1000 * 1000 ? 1 : 0, QLocale::DataSizeSIFormat);+}++QString LocalPackage::installedSizeText() const+{+ if (!m_info || m_info->installedSize <= 0) {+ return {};+ }+ return QLocale().formattedDataSize(m_info->installedSize, m_info->installedSize >= 1000 * 1000 * 1000 ? 1 : 0, QLocale::DataSizeSIFormat);+}++QString LocalPackage::iconSource() const+{+ if (m_info && !m_info->icon.isEmpty()) {+ return m_info->icon;+ }+ if (m_state == QLatin1String("done") || m_state == QLatin1String("installed")) {+ const QString id = m_info ? (m_info->kind == QLatin1String("deb") ? m_info->desktopId : m_info->id + QStringLiteral(".desktop")) : QString();+ if (KService::Ptr service = launcher(id); service && !service->icon().isEmpty()) {+ return QStringLiteral("image://theme/") + QString::fromUtf8(QUrl::toPercentEncoding(service->icon()));+ }+ }+ const QString k = kind();+ const QString icon = k == QLatin1String("deb") ? QStringLiteral("application-vnd.debian.binary-package")+ : k == QLatin1String("flatpakref") ? QStringLiteral("application-vnd.flatpak.ref")+ : QStringLiteral("application-vnd.flatpak");+ return QStringLiteral("image://theme/") + icon;+}++bool LocalPackage::canOpen() const+{+ if (!m_info || (m_state != QLatin1String("done") && m_state != QLatin1String("installed") && m_state != QLatin1String("newer"))) {+ return false;+ }+ if (m_info->kind == QLatin1String("deb")) {+ return launcher(m_info->desktopId).data() != nullptr;+ }+ return true;+}++bool LocalPackage::open()+{+ if (!canOpen()) {+ return false;+ }+ const QString desktopId = m_info->kind == QLatin1String("deb") ? m_info->desktopId : m_info->id + QStringLiteral(".desktop");+ if (KService::Ptr service = launcher(desktopId)) {+ auto job = new KIO::ApplicationLauncherJob(service);+ job->start();+ return true;+ }+ return QProcess::startDetached(QStringLiteral("flatpak"), {QStringLiteral("run"), m_info->id});+}diff --git a/packages/wildos-store/src/localpackage.h b/packages/wildos-store/src/localpackage.hnew file mode 100644index 0000000..96b7009--- /dev/null+++ b/packages/wildos-store/src/localpackage.h@@ -0,0 +1,133 @@+#pragma once++#include <QObject>+#include <QQmlEngine>+#include <QStringList>+#include <QTemporaryDir>++#include <memory>++struct LocalInfo;++// A package file someone opened from Files or a download: a .deb, a+// .flatpakref or a .flatpak bundle. It reads what the file says about+// itself, compares that with what is installed, and installs it. A .deb goes+// through PackageKit, which fetches what it depends on from the Wild OS+// repositories and asks for the password; a Flatpak goes through the Store's+// own libflatpak backend, for the signed-in user.+//+// Nothing here vouches for the file. A .deb's fields (its name, its+// maker) are whatever whoever built it typed, so the page shows them as+// what the file says, never as checked.+class LocalPackage : public QObject+{+ Q_OBJECT+ QML_ELEMENT++ Q_PROPERTY(QString path READ path WRITE setPath NOTIFY pathChanged)+ // deb, flatpakref or flatpak; empty for a file the Store can't install.+ Q_PROPERTY(QString kind READ kind NOTIFY changed)+ // reading, unreadable, blocked, get, update, installed, newer, working,+ // done or failed.+ Q_PROPERTY(QString state READ state NOTIFY changed)+ Q_PROPERTY(QString fileName READ fileName NOTIFY changed)+ Q_PROPERTY(QString name READ name NOTIFY changed)+ // The package name or the Flatpak app ID.+ Q_PROPERTY(QString id READ id NOTIFY changed)+ Q_PROPERTY(QString summary READ summary NOTIFY changed)+ // Plain text, paragraphs separated by blank lines.+ Q_PROPERTY(QString description READ description NOTIFY changed)+ Q_PROPERTY(QString version READ version NOTIFY changed)+ Q_PROPERTY(QString installedVersion READ installedVersion NOTIFY changed)+ Q_PROPERTY(QString fileSizeText READ fileSizeText NOTIFY changed)+ Q_PROPERTY(QString installedSizeText READ installedSizeText NOTIFY changed)+ Q_PROPERTY(QString homepage READ homepage NOTIFY changed)+ Q_PROPERTY(QString maker READ maker NOTIFY changed)+ Q_PROPERTY(QString iconSource READ iconSource NOTIFY changed)+ // Where a Flatpak downloads from and takes its updates from, as a host+ // name; empty when it has nowhere (a bundle with no origin).+ Q_PROPERTY(QString origin READ origin NOTIFY changed)+ // What a .deb says it needs, by package name.+ Q_PROPERTY(QStringList depends READ depends NOTIFY changed)+ // What installing it would also bring from the Wild OS repositories,+ // once PackageKit has worked that out.+ Q_PROPERTY(QStringList extras READ extras NOTIFY changed)+ // What it would take off the computer to make room, which a .deb that+ // conflicts with something installed does.+ Q_PROPERTY(QStringList removes READ removes NOTIFY changed)+ Q_PROPERTY(bool checkingDepends READ checkingDepends NOTIFY changed)+ // Why it can't be read, installed, or why the install failed.+ Q_PROPERTY(QString problem READ problem NOTIFY changed)+ // A .flatpakref that only points at Flathub: the app's own Store page+ // is the better place for it.+ Q_PROPERTY(QString flathubId READ flathubId NOTIFY changed)+ Q_PROPERTY(int progress READ progress NOTIFY changed)+ // auth, prepare, download or install, while working.+ Q_PROPERTY(QString phase READ phase NOTIFY changed)+ Q_PROPERTY(bool canOpen READ canOpen NOTIFY changed)++public:+ explicit LocalPackage(QObject *parent = nullptr);+ ~LocalPackage() override;++ QString path() const { return m_path; }+ void setPath(const QString &path);++ QString kind() const;+ QString state() const { return m_state; }+ QString fileName() const;+ QString name() const;+ QString id() const;+ QString summary() const;+ QString description() const;+ QString version() const;+ QString installedVersion() const;+ QString fileSizeText() const;+ QString installedSizeText() const;+ QString homepage() const;+ QString maker() const;+ QString iconSource() const;+ QString origin() const;+ QStringList depends() const;+ QStringList extras() const { return m_extras; }+ QStringList removes() const { return m_removes; }+ bool checkingDepends() const { return m_checkingDepends; }+ QString problem() const { return m_problem; }+ QString flathubId() const;+ int progress() const { return m_progress; }+ QString phase() const { return m_phase; }+ bool canOpen() const;++ Q_INVOKABLE void install();+ Q_INVOKABLE bool open();++ // The local path for a command line or D-Bus argument that names a+ // package file (a path or a file: URL), or empty when it names none.+ static QString fileArgument(const QString &argument);++Q_SIGNALS:+ void pathChanged();+ void changed();++private:+ void read();+ void adopt(const LocalInfo &info);+ void checkDepends();+ void installDeb();+ void installFlatpak();+ void finish(bool ok, const QString &error);++ QString m_path;+ QString m_state = QStringLiteral("reading");+ std::unique_ptr<LocalInfo> m_info;+ QStringList m_extras;+ QStringList m_removes;+ bool m_checkingDepends = false;+ QString m_problem;+ int m_progress = -1;+ QString m_phase;+ int m_job = 0;+ int m_generation = 0;+ // Where the icon read from the file is kept while the page is open.+ std::shared_ptr<QTemporaryDir> m_scratch;+};diff --git a/packages/wildos-store/src/main.cpp b/packages/wildos-store/src/main.cppindex 4c92fcc..7c8ced6 100644--- a/packages/wildos-store/src/main.cpp+++ b/packages/wildos-store/src/main.cpp@@ -1,5 +1,8 @@#include "catalog.h"+#include "localpackage.h"+#include "network.h"#include "themeiconprovider.h"+#include "timing.h"#include <QCommandLineParser>#include <QDBusConnection>@@ -11,6 +14,9 @@#include <QQuickStyle>#include <QQuickWindow>+#include <atomic>+#include <memory>+namespace{const QString serviceName = QStringLiteral("org.wildos.Store");@@ -57,7 +63,9 @@ private:int main(int argc, char *argv[]){+ storeClock();QGuiApplication app(argc, argv);+ qCInfo(lcStore) << "timing: application up at" << storeClock() << "ms";app.setApplicationName(QStringLiteral("wildos-store"));app.setOrganizationDomain(QStringLiteral("wildos.io"));app.setApplicationDisplayName(QStringLiteral("Store"));@@ -72,21 +80,30 @@ int main(int argc, char *argv[])QCommandLineOption appOption(QStringLiteral("app"), QStringLiteral("Open the page of this app (an AppStream ID, package or Flathub ID)."),QStringLiteral("id"));QCommandLineOption searchOption(QStringLiteral("search"), QStringLiteral("Search for this text."), QStringLiteral("text"));- QCommandLineOption pageOption(QStringLiteral("page"), QStringLiteral("Open home, apps, games, windows, updates or installed."), QStringLiteral("page"));+ QCommandLineOption pageOption(QStringLiteral("page"), QStringLiteral("Open discover, swap, create, work, play, develop, categories, windowsapps, updates or library."), QStringLiteral("page"));parser.addOption(appOption);parser.addOption(searchOption);parser.addOption(pageOption);- parser.addPositionalArgument(QStringLiteral("url"), QStringLiteral("An appstream: link."), QStringLiteral("[url]"));+ parser.addPositionalArgument(QStringLiteral("url"), QStringLiteral("An appstream: link, or a .deb, .flatpakref or .flatpak file to install."), QStringLiteral("[url]"));parser.process(app);QString target = parser.value(appOption);+ QString page = parser.value(pageOption);const QStringList positional = parser.positionalArguments();if (target.isEmpty() && !positional.isEmpty()) {target = positional.constFirst();+ // A package file opened from Files or a download gets its own+ // install page. The path is made absolute here, since a Store+ // already open elsewhere has another working folder.+ const QString file = LocalPackage::fileArgument(target);+ if (!file.isEmpty()) {+ target = file;+ page = QStringLiteral("file");+ }}const QString search = parser.value(searchOption);- const QString page = parser.value(pageOption);+ qCInfo(lcStore) << "timing: options read at" << storeClock() << "ms";QDBusConnection bus = QDBusConnection::sessionBus();if (bus.isConnected() && bus.interface()->isServiceRegistered(serviceName)) {auto message = QDBusMessage::createMethodCall(serviceName, objectPath, interfaceName, QStringLiteral("show"));@@ -96,8 +113,11 @@ int main(int argc, char *argv[])}QQuickStyle::setStyle(QStringLiteral("Basic"));+ qCInfo(lcStore) << "timing: building the window from" << storeClock() << "ms";+ StoreNetworkFactory networkFactory;QQmlApplicationEngine engine;+ engine.setNetworkAccessManagerFactory(&networkFactory);engine.addImageProvider(QStringLiteral("theme"), new ThemeIconProvider);engine.setInitialProperties({{QStringLiteral("startApp"), target},@@ -108,6 +128,32 @@ int main(int argc, char *argv[])QCoreApplication::exit(1);}, Qt::QueuedConnection);engine.loadFromModule("WildOS.Store", "Main");+ qCInfo(lcStore) << "timing: window built at" << storeClock() << "ms";++ // The first frame, and the first one drawn once the catalogue is in, are+ // what someone opening the Store waits for. frameSwapped comes from the+ // render thread, hence the atomics.+ if (auto window = engine.rootObjects().isEmpty() ? nullptr : qobject_cast<QQuickWindow *>(engine.rootObjects().constFirst())) {+ auto firstFrame = std::make_shared<std::atomic_bool>(false);+ auto filledFrame = std::make_shared<std::atomic_bool>(false);+ auto catalogueIn = std::make_shared<std::atomic_bool>(Catalog::instance() && Catalog::instance()->isReady());+ if (Catalog *catalog = Catalog::instance()) {+ QObject::connect(catalog, &Catalog::readyChanged, window, [catalogueIn] {+ catalogueIn->store(true);+ });+ }+ QObject::connect(window, &QQuickWindow::frameSwapped, window, [firstFrame, filledFrame, catalogueIn] {+ if (!firstFrame->exchange(true)) {+ qCInfo(lcStore) << "timing: first frame at" << storeClock() << "ms";+ if (Catalog *catalog = Catalog::instance()) {+ QMetaObject::invokeMethod(catalog, &Catalog::startBackgroundWork, Qt::QueuedConnection);+ }+ }+ if (catalogueIn->load() && !filledFrame->exchange(true)) {+ qCInfo(lcStore) << "timing: first frame with the catalogue at" << storeClock() << "ms";+ }+ }, Qt::DirectConnection);+ }if (bus.isConnected()) {auto remote = new Remote(&engine);diff --git a/packages/wildos-store/src/network.cpp b/packages/wildos-store/src/network.cppnew file mode 100644index 0000000..b3172c3--- /dev/null+++ b/packages/wildos-store/src/network.cpp@@ -0,0 +1,98 @@+#include "network.h"+#include "timing.h"++#include <QMutex>+#include <QNetworkDiskCache>+#include <QNetworkReply>+#include <QSet>+#include <QStandardPaths>+#include <QTimer>++namespace+{+// Addresses that answered 404 this session. Debian's screenshot links often+// point at pictures that have been pruned; asking again only spins.+QMutex missingMutex;+QSet<QUrl> missing;++// Answers at once, as the server did the first time.+class MissingReply : public QNetworkReply+{+public:+ MissingReply(const QNetworkRequest &request, QObject *parent)+ : QNetworkReply(parent)+ {+ setRequest(request);+ setUrl(request.url());+ setOperation(QNetworkAccessManager::GetOperation);+ setAttribute(QNetworkRequest::HttpStatusCodeAttribute, 404);+ setError(ContentNotFoundError, QStringLiteral("Not found"));+ open(ReadOnly);+ setFinished(true);+ QTimer::singleShot(0, this, [this] {+ Q_EMIT errorOccurred(ContentNotFoundError);+ Q_EMIT finished();+ });+ }++ void abort() override+ {+ }++protected:+ qint64 readData(char *, qint64) override+ {+ return -1;+ }+};+}++StoreNetworkAccessManager::StoreNetworkAccessManager(QObject *parent)+ : QNetworkAccessManager(parent)+{+ // Icons and screenshots on Flathub and Debian live at addresses that+ // change whenever the picture does, so a copy on disk never goes stale.+ auto cache = new QNetworkDiskCache(this);+ cache->setCacheDirectory(QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation) + QStringLiteral("/wildos-store/images"));+ cache->setMaximumCacheSize(qint64(400) * 1024 * 1024);+ setCache(cache);+}++QNetworkReply *StoreNetworkAccessManager::createRequest(Operation op, const QNetworkRequest &original, QIODevice *outgoingData)+{+ QNetworkRequest request(original);+ if (op == GetOperation) {+ {+ QMutexLocker lock(&missingMutex);+ if (missing.contains(request.url())) {+ return new MissingReply(request, this);+ }+ }+ // Use the copy on disk whatever the server's caching headers say;+ // see the constructor.+ request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache);+ request.setAttribute(QNetworkRequest::CacheSaveControlAttribute, true);+ }+ QNetworkReply *reply = QNetworkAccessManager::createRequest(op, request, outgoingData);+ const qint64 began = storeClock();+ connect(reply, &QNetworkReply::finished, reply, [reply, began] {+ const int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();+ if (status == 404 || status == 410) {+ QMutexLocker lock(&missingMutex);+ missing.insert(reply->request().url());+ }+ if (!lcStore().isInfoEnabled()) {+ return;+ }+ const bool cached = reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool();+ qCInfo(lcStore).noquote() << "image:" << reply->request().url().host() << storeClock() - began << "ms"+ << reply->header(QNetworkRequest::ContentLengthHeader).toLongLong() << "bytes"+ << (cached ? "from disk cache" : "from network") << status << reply->url().toString();+ });+ return reply;+}++QNetworkAccessManager *StoreNetworkFactory::create(QObject *parent)+{+ return new StoreNetworkAccessManager(parent);+}diff --git a/packages/wildos-store/src/network.h b/packages/wildos-store/src/network.hnew file mode 100644index 0000000..ea5c10d--- /dev/null+++ b/packages/wildos-store/src/network.h@@ -0,0 +1,24 @@+#pragma once++#include <QNetworkAccessManager>+#include <QQmlNetworkAccessManagerFactory>++// The network access QML's Image uses for remote icons and screenshots.+// Every fetch is logged with its host and time, so slow pages can be put+// down to Flathub's CDN or Debian's screenshot server.+class StoreNetworkAccessManager : public QNetworkAccessManager+{+ Q_OBJECT++public:+ explicit StoreNetworkAccessManager(QObject *parent = nullptr);++protected:+ QNetworkReply *createRequest(Operation op, const QNetworkRequest &request, QIODevice *outgoingData) override;+};++class StoreNetworkFactory : public QQmlNetworkAccessManagerFactory+{+public:+ QNetworkAccessManager *create(QObject *parent) override;+};diff --git a/packages/wildos-store/src/packagekitbackend.cpp b/packages/wildos-store/src/packagekitbackend.cppindex 51170da..e673802 100644--- a/packages/wildos-store/src/packagekitbackend.cpp+++ b/packages/wildos-store/src/packagekitbackend.cpp@@ -1,4 +1,5 @@#include "packagekitbackend.h"+#include "flatpakbackend.h"#include <PackageKit/Daemon>#include <PackageKit/Details>@@ -143,8 +144,13 @@ void PackageKitBackend::resolveThen(const QStringList &packages, Transaction::Fivoid PackageKitBackend::watch(int job, Transaction *transaction, bool removing){auto error = std::make_shared<QString>();- Q_EMIT progress(job, -1, QStringLiteral("prepare"));- connect(transaction, &Transaction::percentageChanged, this, [this, job, transaction, removing] {+ auto total = std::make_shared<qint64>(0);+ m_running.insert(job, transaction);+ if (m_cancelSoon.remove(job)) {+ transaction->cancel();+ }+ Q_EMIT progress(job, -1, QStringLiteral("prepare"), {}, -1, -1);+ connect(transaction, &Transaction::percentageChanged, this, [this, job, transaction, removing, total] {// 101 is PackageKit's "not known yet".const uint pct = transaction->percentage();QString status;@@ -168,28 +174,51 @@ void PackageKitBackend::watch(int job, Transaction *transaction, bool removing)status = removing ? QStringLiteral("remove") : QStringLiteral("prepare");break;}- Q_EMIT progress(job, pct > 100 ? -1 : int(pct), status);+ // The first figure PackageKit gives for what is left to download is+ // the whole download.+ const qint64 remaining = qint64(transaction->downloadSizeRemaining());+ *total = qMax(*total, remaining);+ const qint64 done = *total > 0 ? *total - remaining : -1;+ Q_EMIT progress(job, pct > 100 ? -1 : int(pct), status, {}, done, *total > 0 ? *total : -1);});connect(transaction, &Transaction::statusChanged, transaction, &Transaction::percentageChanged);connect(transaction, &Transaction::errorCode, this, [error, removing](Transaction::Error code, const QString &) {*error = errorText(code, removing);});connect(transaction, &Transaction::finished, this, [this, job, error](Transaction::Exit status, uint) {+ m_running.remove(job);listInstalled();listUpdates();if (status == Transaction::ExitSuccess) {Q_EMIT finished(job, true, {});} else if (status == Transaction::ExitCancelled) {- Q_EMIT finished(job, false, QStringLiteral("Cancelled."));+ Q_EMIT finished(job, false, QString::fromLatin1(cancelledMarker));} else {Q_EMIT finished(job, false, error->isEmpty() ? QStringLiteral("Something went wrong. Try again in a few minutes.") : *error);}});}+void PackageKitBackend::cancel(int job)+{+ if (QPointer<Transaction> t = m_running.value(job)) {+ t->cancel();+ return;+ }+ // Still resolving the package names; cancelled as soon as it starts.+ m_cancelSoon.insert(job);+}++void PackageKitBackend::seedInstalled(const QSet<QString> &packages)+{+ if (!m_ready) {+ m_installed = packages;+ }+}+void PackageKitBackend::install(int job, const QStringList &packages){- Q_EMIT progress(job, -1, QStringLiteral("prepare"));+ Q_EMIT progress(job, -1, QStringLiteral("prepare"), {}, -1, -1);resolveThen(packages, Transaction::FilterNotInstalled | Transaction::FilterArch | Transaction::FilterNewest, job, [this, job](const QStringList &ids) {Transaction *t = Daemon::installPackages(ids);watch(job, t, false);@@ -199,7 +228,7 @@ void PackageKitBackend::install(int job, const QStringList &packages)void PackageKitBackend::remove(int job, const QStringList &packages){- Q_EMIT progress(job, -1, QStringLiteral("remove"));+ Q_EMIT progress(job, -1, QStringLiteral("remove"), {}, -1, -1);resolveThen(packages, Transaction::FilterInstalled, job, [this, job](const QStringList &ids) {// Never take anything else with it: if another part of Wild OS// depends on this app, PackageKit refuses and we say so.diff --git a/packages/wildos-store/src/packagekitbackend.h b/packages/wildos-store/src/packagekitbackend.hindex 2d035bc..e6456e6 100644--- a/packages/wildos-store/src/packagekitbackend.h+++ b/packages/wildos-store/src/packagekitbackend.h@@ -2,6 +2,7 @@#include <QHash>#include <QObject>+#include <QPointer>#include <QSet>#include <QStringList>@@ -32,11 +33,17 @@ public:void remove(int job, const QStringList &packages);void update(int job, const QStringList &packages);void fetchDetails(const QString &key, const QStringList &packages);+ void cancel(int job);+ // Seeds the installed list from the last run until the real one is in.+ void seedInstalled(const QSet<QString> &packages);QSet<QString> installed() const { return m_installed; }QSet<QString> updates() const { return QSet<QString>(m_updateNames.begin(), m_updateNames.end()); }QString installedVersion(const QString &package) const { return m_versions.value(package); }+ // What a failed transaction tells people, in plain words.+ static QString errorText(PackageKit::Transaction::Error error, bool removing);+Q_SIGNALS:void installedChanged();void updatesChanged();@@ -44,7 +51,7 @@ Q_SIGNALS:void catalogueRefreshed();// A refresh asked for with refresh() is over, and the update list with it.void refreshFinished(bool ok);- void progress(int job, int percent, const QString &status);+ void progress(int job, int percent, const QString &status, const QString &detail, qint64 done, qint64 total);void finished(int job, bool ok, const QString &error);void detailsReady(const QString &key, qint64 downloadSize, qint64 installedSize, const QString &version);@@ -52,11 +59,12 @@ private:void resolveThen(const QStringList &packages, PackageKit::Transaction::Filters filters, int job,std::function<PackageKit::Transaction *(const QStringList &ids)> next);void watch(int job, PackageKit::Transaction *transaction, bool removing);- static QString errorText(PackageKit::Transaction::Error error, bool removing);QSet<QString> m_installed;QHash<QString, QString> m_versions;QHash<QString, QString> m_updateIds;QStringList m_updateNames;bool m_ready = false;+ QHash<int, QPointer<PackageKit::Transaction>> m_running;+ QSet<int> m_cancelSoon;};diff --git a/packages/wildos-store/src/storeapp.cpp b/packages/wildos-store/src/storeapp.cppindex 81ca725..f685d20 100644--- a/packages/wildos-store/src/storeapp.cpp+++ b/packages/wildos-store/src/storeapp.cpp@@ -23,12 +23,24 @@#include <QProcess>#include <QRegularExpression>#include <QStandardPaths>+#include <QStorageInfo>#include <QUrl>#include <glib.h>namespace{+// Looking a launcher up checks KDE's service cache against the disk, which+// is far too slow to do for every card each time it is drawn, so each answer+// is kept until StoreApp::forgetServices().+QHash<QString, KService::Ptr> &serviceCache()+{+ static QHash<QString, KService::Ptr> cache;+ return cache;+}++bool serviceCacheChecked = false;+// Apps installed while the Store is open are not in KDE's service cache// yet; reading the launcher file directly finds them anyway.KService::Ptr findService(const QString &desktopId)@@ -36,16 +48,24 @@ KService::Ptr findService(const QString &desktopId)if (desktopId.isEmpty()) {return {};}- KSycoca::self()->ensureCacheValid();- KService::Ptr service = KService::serviceByStorageId(desktopId);- if (service) {- return service;+ auto &cache = serviceCache();+ auto it = cache.constFind(desktopId);+ if (it != cache.cend()) {+ return it.value();}- const QString path = QStandardPaths::locate(QStandardPaths::ApplicationsLocation, desktopId);- if (!path.isEmpty()) {- return KService::Ptr(new KService(path));+ if (!serviceCacheChecked) {+ KSycoca::self()->ensureCacheValid();+ serviceCacheChecked = true;}- return {};+ KService::Ptr service = KService::serviceByStorageId(desktopId);+ if (!service) {+ const QString path = QStandardPaths::locate(QStandardPaths::ApplicationsLocation, desktopId);+ if (!path.isEmpty()) {+ service = KService::Ptr(new KService(path));+ }+ }+ cache.insert(desktopId, service);+ return service;}const AppStream::Component *primary(const Record *r, const QString &source)@@ -138,6 +158,12 @@ const QList<PermissionDef> &permissionDefs()}}+void StoreApp::forgetServices()+{+ serviceCache().clear();+ serviceCacheChecked = false;+}+StoreApp::StoreApp(Catalog *catalog, const QString &key): QObject(catalog), m_catalog(catalog)@@ -175,21 +201,30 @@ QString StoreApp::name() constreturn fromStart;}const Record *r = m_catalog->record(m_key);- if (r && r->curated && !r->curated->name.isEmpty()) {+ if (!r) {+ return m_key;+ }+ if (r->curated && !r->curated->name.isEmpty()) {return r->curated->name;}- const auto c = primary(r, source());- return c ? c->name() : m_key;+ const bool flat = source() == QLatin1String("flatpak");+ const QString &first = flat ? r->flatName : r->aptName;+ const QString &second = flat ? r->aptName : r->flatName;+ return !first.isEmpty() ? first : !second.isEmpty() ? second : m_key;}QString StoreApp::summary() const{const Record *r = m_catalog->record(m_key);- if (r && r->curated && !r->curated->summary.isEmpty()) {+ if (!r) {+ return {};+ }+ if (r->curated && !r->curated->summary.isEmpty()) {return r->curated->summary;}- const auto c = primary(r, source());- return c ? c->summary() : QString();+ const bool flat = source() == QLatin1String("flatpak");+ const QString &first = flat ? r->flatSummary : r->aptSummary;+ return !first.isEmpty() ? first : flat ? r->aptSummary : r->flatSummary;}QString StoreApp::tagline() const@@ -278,57 +313,22 @@ QString StoreApp::iconSource() const}}- const auto c = primary(r, source());+ // Worked out when the catalogue was built (see iconFor in catalog.cpp).+ const bool flat = source() == QLatin1String("flatpak");+ const QString &first = flat ? r->flatIcon : r->aptIcon;+ const QString &second = flat ? r->aptIcon : r->flatIcon;// Flathub's catalogue arrives a few seconds after the first launch.- // Until then a curated app has a name but nothing to draw, and an empty- // tile reads better than a broken file icon.- if (!c && !(r->curated && !r->curated->icon.isEmpty())) {- return QString();- }- const QList<AppStream::Icon> icons = c ? c->icons() : QList<AppStream::Icon>();-- QString best;- uint bestSize = 0;- QString remote;- const QString flatDir = m_catalog->flatpakAppstreamDir();- for (const AppStream::Icon &icon : icons) {- if (icon.kind() == AppStream::Icon::KindCached || icon.kind() == AppStream::Icon::KindLocal) {- QString path = icon.url().isLocalFile() ? icon.url().toLocalFile() : icon.url().toString();- if (!QFileInfo::exists(path) && c == (r->flat ? &*r->flat : nullptr) && !flatDir.isEmpty()) {- path = QStringLiteral("%1/icons/%2x%3/%4").arg(flatDir).arg(icon.width()).arg(icon.height()).arg(icon.name());- }- if (QFileInfo::exists(path) && icon.width() > bestSize) {- best = path;- bestSize = icon.width();- }- } else if (icon.kind() == AppStream::Icon::KindRemote && remote.isEmpty()) {- remote = icon.url().toString();- }- }- // Catalogue icons on disk first: the remote copies of older catalogue- // entries are not always kept online.- if (!best.isEmpty()) {- return QUrl::fromLocalFile(best).toString();- }- if (!remote.isEmpty()) {- return remote;- }- if (r->curated && !r->curated->icon.isEmpty()) {- return themeIcon(r->curated->icon);- }- for (const AppStream::Icon &icon : icons) {- if (icon.kind() == AppStream::Icon::KindStock) {- return themeIcon(icon.name());- }- }- return themeIcon(QStringLiteral("application-x-executable"));+ // Until then a curated app may have nothing to draw, and an empty tile+ // reads better than a broken file icon.+ return !first.isEmpty() ? first : second;}QVariantList StoreApp::screenshots() const{const Record *r = m_catalog->record(m_key);- // Flathub keeps every screenshot online; the Wild OS catalogue's links- // can point at media that has since been pruned.+ // Flathub keeps every screenshot online and its CDN is quick; the Wild+ // OS catalogue's links can point at media that has since been pruned.+ // So Flathub's pictures are used whenever the app is there too.auto c = primary(r, source());if (r && r->flat && !r->flat->screenshotsAll().isEmpty()) {c = &*r->flat;@@ -345,21 +345,27 @@ QVariantList StoreApp::screenshots() constif (images.isEmpty()) {continue;}- AppStream::Image thumb = images.constFirst();- AppStream::Image full = images.constFirst();+ // Every size the catalogue has, so the page can fetch the one+ // closest to what it shows (Catalog::pickImage). The shape comes+ // from whichever size says it.+ QVariantList sizes;+ uint width = 0;+ uint height = 0;for (const AppStream::Image &img : images) {- if (qAbs(int(img.width()) - 752) < qAbs(int(thumb.width()) - 752)) {- thumb = img;- }- if (img.kind() == AppStream::Image::KindSource || img.width() > full.width()) {- full = img;+ sizes << QVariantMap{+ {QStringLiteral("url"), img.url().toString()},+ {QStringLiteral("width"), img.width()},+ {QStringLiteral("height"), img.height()},+ };+ if (img.width() > width && img.height() > 0) {+ width = img.width();+ height = img.height();}}out << QVariantMap{- {QStringLiteral("thumb"), thumb.url().toString()},- {QStringLiteral("full"), full.url().toString()},- {QStringLiteral("width"), thumb.width()},- {QStringLiteral("height"), thumb.height()},+ {QStringLiteral("images"), sizes},+ {QStringLiteral("width"), width},+ {QStringLiteral("height"), height},{QStringLiteral("caption"), shot.caption()},};if (out.size() >= 8) {@@ -434,13 +440,13 @@ CURATED_FIELD(swapText, swapText)bool StoreApp::hasFlatpak() const{const Record *r = m_catalog->record(m_key);- return r && (r->flat.has_value() || (!r->flatpakId.isEmpty() && m_catalog->flathubAvailable()));+ return r && (r->hasFlat || (!r->flatpakId.isEmpty() && m_catalog->flathubAvailable()));}bool StoreApp::hasApt() const{const Record *r = m_catalog->record(m_key);- return r && (r->apt.has_value() || !r->packages.isEmpty()) && !r->packages.isEmpty();+ return r && !r->packages.isEmpty();}QString StoreApp::source() const@@ -513,15 +519,441 @@ QString StoreApp::sizeText() constconst qint64 size = m_catalog->installedSize(m_key);return size > 0 ? QStringLiteral("Uses %1").arg(locale.formattedDataSize(size, 0, QLocale::DataSizeTraditionalFormat)) : QString();}- // The download size comes from PackageKit, so it only describes the Wild- // OS package.- const qint64 download = m_catalog->state(m_key).downloadSize;- if (download > 0 && source() == QLatin1String("apt")) {+ const AppState &s = m_catalog->state(m_key);+ // PackageKit sizes the Wild OS package; Flathub's figure is everything+ // the install would download, shared parts included.+ const qint64 download = source() == QLatin1String("apt") ? s.downloadSize : s.planTotal;+ if (download > 0) {return QStringLiteral("About %1 to download").arg(locale.formattedDataSize(download, 0, QLocale::DataSizeTraditionalFormat));}return {};}+QString StoreApp::progressText() const+{+ const AppState &s = m_catalog->state(m_key);+ if (!s.error.isEmpty() && !s.busy && !s.queued) {+ return s.error;+ }+ if (s.queued) {+ return QStringLiteral("Waiting for the apps before it");+ }+ if (!s.busy) {+ return {};+ }+ const QLocale locale;+ auto size = [&locale](qint64 bytes) {+ return locale.formattedDataSize(bytes, 0, QLocale::DataSizeTraditionalFormat);+ };+ if (s.phase == QLatin1String("auth")) {+ return QStringLiteral("Waiting for the administrator password");+ }+ if (s.action == QLatin1String("remove")) {+ return QStringLiteral("Uninstalling");+ }+ const bool downloading = s.phase == QLatin1String("download") && s.totalBytes > 0 && s.doneBytes < s.totalBytes;+ if (downloading) {+ return QStringLiteral("Downloading %1 of %2").arg(size(qMax<qint64>(0, s.doneBytes)), size(s.totalBytes));+ }+ if (s.phase == QLatin1String("download")) {+ return QStringLiteral("Downloading");+ }+ if (s.phase == QLatin1String("install") || s.progress >= 99) {+ return s.action == QLatin1String("update") ? QStringLiteral("Updating") : QStringLiteral("Installing");+ }+ return QStringLiteral("Getting ready");+}++QString StoreApp::sharedNote() const+{+ const AppState &s = m_catalog->state(m_key);+ if (isInstalled() || source() != QLatin1String("flatpak")) {+ return {};+ }+ // Named while it downloads, or before installing when Flathub said this+ // app would bring it.+ const QString runtime = !s.detail.isEmpty() ? s.detail : s.planRuntime;+ if (runtime.isEmpty()) {+ return {};+ }+ if (!s.busy && !s.queued && s.planShared > 0) {+ const QLocale locale;+ return QStringLiteral("Includes %1 (%2), shared with other apps").arg(runtime, locale.formattedDataSize(s.planShared, 0, QLocale::DataSizeTraditionalFormat));+ }+ return QStringLiteral("Includes %1, shared with other apps").arg(runtime);+}++bool StoreApp::cancellable() const+{+ const AppState &s = m_catalog->state(m_key);+ // Once files are being put in place, stopping would leave the app half+ // installed, so only waiting and downloading can be cancelled.+ if (s.queued) {+ return true;+ }+ return s.busy && s.action != QLatin1String("remove") && s.phase != QLatin1String("install") && s.phase != QLatin1String("auth");+}++void StoreApp::cancel()+{+ m_catalog->cancel(m_key);+}++void StoreApp::pause()+{+ m_catalog->pause(m_key);+}++namespace+{+// What a Flathub app may reach: the permissions in its metadata with the+// person's overrides on top, as flatpak itself combines them.+struct Access {+ QHash<QString, QSet<QString>> granted;+ QSet<QString> requested;+ QSet<QString> busNames;+};++Access accessOf(const QString &metadata, const QString &overridePath)+{+ Access access;+ GKeyFile *meta = g_key_file_new();+ const QByteArray data = metadata.toUtf8();+ g_key_file_load_from_data(meta, data.constData(), data.size(), G_KEY_FILE_NONE, nullptr);+ GKeyFile *over = g_key_file_new();+ g_key_file_load_from_file(over, QFile::encodeName(overridePath).constData(), G_KEY_FILE_NONE, nullptr);+ for (const char *group : {"filesystems", "devices", "sockets", "shared", "features"}) {+ QSet<QString> &set = access.granted[QString::fromLatin1(group)];+ for (const QString &e : keyList(meta, group)) {+ if (!e.startsWith(QLatin1Char('!'))) {+ set.insert(baseOf(e));+ access.requested.insert(QString::fromLatin1(group) + QLatin1Char(':') + baseOf(e));+ }+ }+ for (const QString &e : keyList(over, group)) {+ if (e.startsWith(QLatin1Char('!'))) {+ set.remove(baseOf(e));+ } else {+ set.insert(baseOf(e));+ }+ }+ }+ for (const char *policy : {"Session Bus Policy", "System Bus Policy"}) {+ gchar **keys = g_key_file_get_keys(meta, policy, nullptr, nullptr);+ for (gchar **k = keys; k && *k; ++k) {+ access.busNames.insert(QString::fromUtf8(*k));+ }+ g_strfreev(keys);+ }+ g_key_file_free(meta);+ g_key_file_free(over);+ return access;+}++struct Reach {+ const char *group;+ const char *base;+ const char *icon;+ const char *label;+ const char *detail;+};++// In the order the app page lists them. The details are what each one+// lets an app do in general; nothing here claims to know why an app asks.+const QList<Reach> &reaches()+{+ static const QList<Reach> list = {+ {"filesystems", "host", "drive", "Every file on this computer", "Including other people's files it can open"},+ {"filesystems", "home", "home", "Your home folder", "All your documents, pictures and settings"},+ {"filesystems", "xdg-documents", "folder", "Documents folder", "To open and save documents there"},+ {"filesystems", "xdg-pictures", "image", "Pictures folder", "To open and save pictures there"},+ {"filesystems", "xdg-music", "music", "Music folder", "To open and save music there"},+ {"filesystems", "xdg-videos", "film", "Videos folder", "To open and save videos there"},+ {"filesystems", "xdg-download", "download", "Downloads folder", "To open and save downloads there"},+ {"filesystems", "xdg-desktop", "desktop", "Desktop", "To open and save files there"},+ {"devices", "dri", "gpu", "Your graphics card", ""},+ {"devices", "all", "camera", "Camera and other devices", "Webcams, game controllers and USB devices"},+ {"sockets", "pulseaudio", "mic", "Sound and microphone", "To play sound and hear your microphone"},+ {"sockets", "cups", "printer", "Printer", "To print"},+ {"shared", "network", "globe", "The internet", "To go online"},+ };+ return list;+}++QVariantMap reachEntry(const Reach &r)+{+ return {{QStringLiteral("icon"), QString::fromLatin1(r.icon)}, {QStringLiteral("label"), QString::fromLatin1(r.label)}};+}+}++bool StoreApp::sandboxed() const+{+ return source() == QLatin1String("flatpak");+}++bool StoreApp::isChecked() const+{+ const Record *r = m_catalog->record(m_key);+ if (!r) {+ return false;+ }+ return r->curated || (r->flat && r->flat->customValue(QStringLiteral("flathub::verification::verified")) == QLatin1String("true"));+}++bool StoreApp::reachKnown() const+{+ return sandboxed() && !m_catalog->state(m_key).flatpakMetadata.isEmpty();+}++QVariantList StoreApp::canReach() const+{+ QVariantList out;+ if (!reachKnown()) {+ return out;+ }+ const Access a = accessOf(m_catalog->state(m_key).flatpakMetadata, flatpakOverridePath());+ // The file picker always works: it is how a sandboxed app opens anything.+ out << QVariantMap{{QStringLiteral("icon"), QStringLiteral("file")}, {QStringLiteral("label"), QStringLiteral("Files you open with it")}};+ const bool wholeHome = a.granted.value(QStringLiteral("filesystems")).contains(QStringLiteral("home"))+ || a.granted.value(QStringLiteral("filesystems")).contains(QStringLiteral("host"));+ for (const Reach &r : reaches()) {+ if (wholeHome && QByteArray(r.base).startsWith("xdg-")) {+ continue;+ }+ if (a.granted.value(QString::fromLatin1(r.group)).contains(QString::fromLatin1(r.base))) {+ out << reachEntry(r);+ }+ }+ if (a.busNames.contains(QStringLiteral("org.freedesktop.GeoClue2"))) {+ out << QVariantMap{{QStringLiteral("icon"), QStringLiteral("location")}, {QStringLiteral("label"), QStringLiteral("Your location")}};+ }+ return out;+}++QVariantList StoreApp::cantReach() const+{+ QVariantList out;+ if (!reachKnown()) {+ return out;+ }+ const Access a = accessOf(m_catalog->state(m_key).flatpakMetadata, flatpakOverridePath());+ auto has = [&a](const char *group, const char *base) {+ return a.granted.value(QString::fromLatin1(group)).contains(QString::fromLatin1(base));+ };+ if (!has("shared", "network")) {+ out << QVariantMap{{QStringLiteral("icon"), QStringLiteral("globe")}, {QStringLiteral("label"), QStringLiteral("The internet")}};+ }+ const bool camera = has("devices", "all");+ const bool microphone = has("sockets", "pulseaudio");+ if (!camera && !microphone) {+ out << QVariantMap{{QStringLiteral("icon"), QStringLiteral("camera")}, {QStringLiteral("label"), QStringLiteral("Camera and microphone")}};+ } else if (!camera) {+ out << QVariantMap{{QStringLiteral("icon"), QStringLiteral("camera")}, {QStringLiteral("label"), QStringLiteral("Your camera")}};+ }+ if (!a.busNames.contains(QStringLiteral("org.freedesktop.GeoClue2"))) {+ out << QVariantMap{{QStringLiteral("icon"), QStringLiteral("location")}, {QStringLiteral("label"), QStringLiteral("Your location")}};+ }+ if (!has("filesystems", "home") && !has("filesystems", "host")) {+ out << QVariantMap{{QStringLiteral("icon"), QStringLiteral("home")}, {QStringLiteral("label"), QStringLiteral("The rest of your files")}};+ }+ return out.mid(0, 3);+}++bool StoreApp::worksOffline() const+{+ if (!reachKnown()) {+ return false;+ }+ const Access a = accessOf(m_catalog->state(m_key).flatpakMetadata, flatpakOverridePath());+ return !a.granted.value(QStringLiteral("shared")).contains(QStringLiteral("network"));+}++QVariantList StoreApp::consentItems() const+{+ QVariantList out;+ if (!reachKnown() || isInstalled()) {+ return out;+ }+ const Access a = accessOf(m_catalog->state(m_key).flatpakMetadata, flatpakOverridePath());+ for (const Reach &r : reaches()) {+ const QString token = QString::fromLatin1(r.group) + QLatin1Char(':') + QString::fromLatin1(r.base);+ // The graphics card is left out: switching it off breaks drawing in+ // nearly every app, so it is not a real choice.+ if (!a.requested.contains(token) || qstrcmp(r.base, "dri") == 0) {+ continue;+ }+ out << QVariantMap{+ {QStringLiteral("token"), token},+ {QStringLiteral("icon"), QString::fromLatin1(r.icon)},+ {QStringLiteral("label"), QString::fromLatin1(r.label)},+ {QStringLiteral("detail"), QString::fromLatin1(r.detail)},+ {QStringLiteral("allowed"), a.granted.value(QString::fromLatin1(r.group)).contains(QString::fromLatin1(r.base))},+ {QStringLiteral("required"), false},+ };+ }+ return out;+}++void StoreApp::installWith(const QVariantMap &choices)+{+ for (const QVariant &v : consentItems()) {+ const QVariantMap item = v.toMap();+ const QString token = item.value(QStringLiteral("token")).toString();+ if (choices.contains(token)) {+ setPermission(token, choices.value(token).toBool());+ }+ }+ install();+}++qint64 StoreApp::spaceShort() const+{+ const AppState &s = m_catalog->state(m_key);+ if (s.planInstalled <= 0 || isInstalled() || source() != QLatin1String("flatpak")) {+ return 0;+ }+ QString dir = FlatpakBackend::userDataDir();+ while (!dir.isEmpty() && !QFileInfo::exists(dir)) {+ dir = QFileInfo(dir).absolutePath();+ if (dir == QLatin1String("/")) {+ break;+ }+ }+ const qint64 free = QStorageInfo(dir).bytesAvailable();+ return free >= 0 && free < s.planInstalled ? s.planInstalled - free : 0;+}++QString StoreApp::buttonState() const+{+ const AppState &s = m_catalog->state(m_key);+ if (s.queued) {+ return QStringLiteral("waiting");+ }+ if (s.stopping) {+ return QStringLiteral("paused");+ }+ if (s.busy) {+ if (s.action == QLatin1String("remove")) {+ return QStringLiteral("removing");+ }+ if (s.phase == QLatin1String("install") || s.progress >= 99) {+ return QStringLiteral("installing");+ }+ if (s.phase == QLatin1String("download") || s.progress > 0) {+ return QStringLiteral("downloading");+ }+ return QStringLiteral("preparing");+ }+ if (isInstalled()) {+ if (updateAvailable()) {+ return QStringLiteral("update");+ }+ return canOpen() ? QStringLiteral("open") : QStringLiteral("installed");+ }+ if (s.paused) {+ return QStringLiteral("paused");+ }+ if (!s.error.isEmpty()) {+ return QStringLiteral("retry");+ }+ if (spaceShort() > 0) {+ return QStringLiteral("nospace");+ }+ return QStringLiteral("get");+}++QString StoreApp::statusLine() const+{+ const QString state = buttonState();+ if (state == QLatin1String("nospace")) {+ return QStringLiteral("Needs %1 free").arg(m_catalog->sizeText(m_catalog->state(m_key).planInstalled));+ }+ if (state == QLatin1String("retry")) {+ return QStringLiteral("Download failed");+ }+ if (state == QLatin1String("paused")) {+ return QStringLiteral("Paused");+ }+ return {};+}++QString StoreApp::bytesText() const+{+ const AppState &s = m_catalog->state(m_key);+ if (s.totalBytes <= 0 || s.doneBytes < 0) {+ return {};+ }+ const QLocale locale;+ // Both in the larger unit, as "412 of 1,080 MB" reads.+ if (s.totalBytes >= qint64(10) * 1000 * 1000 * 1000) {+ return QStringLiteral("%1 of %2 GB").arg(locale.toString(double(s.doneBytes) / 1e9, 'f', 1), locale.toString(double(s.totalBytes) / 1e9, 'f', 1));+ }+ return QStringLiteral("%1 of %2 MB").arg(locale.toString(qRound64(double(s.doneBytes) / 1e6)), locale.toString(qMax<qint64>(1, qRound64(double(s.totalBytes) / 1e6))));+}++QString StoreApp::timeLeftText() const+{+ const qint64 left = m_catalog->state(m_key).secondsLeft;+ if (left < 0) {+ return {};+ }+ if (left < 45) {+ return QStringLiteral("Less than a minute left");+ }+ if (left < 90) {+ return QStringLiteral("About a minute left");+ }+ if (left < 90 * 60) {+ return QStringLiteral("About %1 minutes left").arg((left + 30) / 60);+ }+ return QStringLiteral("About %1 hours left").arg((left + 1800) / 3600);+}++QString StoreApp::downloadText() const+{+ const AppState &s = m_catalog->state(m_key);+ const qint64 bytes = source() == QLatin1String("apt") ? s.downloadSize : s.planTotal;+ return bytes > 0 ? m_catalog->sizeText(bytes) : QString();+}++QString StoreApp::updateSizeText() const+{+ const qint64 bytes = m_catalog->updateSize(m_key);+ return bytes > 0 ? m_catalog->sizeText(bytes) : QString();+}++QString StoreApp::releaseNote() const+{+ const auto c = primary(m_catalog->record(m_key), source());+ if (!c) {+ return {};+ }+ const auto releases = c->releasesPlain().entries();+ if (releases.isEmpty()) {+ return {};+ }+ QString text = releases.constFirst().description();+ // The first paragraph or list item, without markup.+ text.replace(QRegularExpression(QStringLiteral("</(p|li)>.*"), QRegularExpression::DotMatchesEverythingOption), QString());+ text.remove(QRegularExpression(QStringLiteral("<[^>]*>")));+ return text.simplified();+}++QString StoreApp::newVersion() const+{+ const auto c = primary(m_catalog->record(m_key), source());+ if (!c) {+ return {};+ }+ const auto releases = c->releasesPlain().entries();+ return releases.isEmpty() ? QString() : releases.constFirst().version();+}++QString StoreApp::updatedText() const+{+ return m_catalog->dayText(m_catalog->updatedTime(m_key));+}+QString StoreApp::desktopId() const{const Record *r = m_catalog->record(m_key);diff --git a/packages/wildos-store/src/storeapp.h b/packages/wildos-store/src/storeapp.hindex 6bb9899..793f6a6 100644--- a/packages/wildos-store/src/storeapp.h+++ b/packages/wildos-store/src/storeapp.h@@ -52,6 +52,45 @@ class StoreApp : public QObjectQ_PROPERTY(bool inStart READ inStart NOTIFY stateChanged)Q_PROPERTY(QVariantList permissions READ permissions NOTIFY stateChanged)Q_PROPERTY(bool permissionsUnknown READ permissionsUnknown NOTIFY stateChanged)+ // The quiet line under an app's button: "Downloading 214 MB of 480 MB",+ // then "Installing", then nothing.+ Q_PROPERTY(QString progressText READ progressText NOTIFY stateChanged)+ // "Includes the KDE base, shared with other apps", when installing this+ // app would also bring the base its kind of app runs on.+ Q_PROPERTY(QString sharedNote READ sharedNote NOTIFY stateChanged)+ // Whether the step running now can be stopped part way.+ Q_PROPERTY(bool cancellable READ cancellable NOTIFY stateChanged)++ // The Store button's state, as StoreStates.dc.html draws them: get,+ // waiting, preparing, downloading, installing, removing, open,+ // installed, update, paused, retry or nospace.+ Q_PROPERTY(QString buttonState READ buttonState NOTIFY stateChanged)+ // The short line under a button in lists ("Needs 720 MB free",+ // "Download failed"), empty when there is nothing to say.+ Q_PROPERTY(QString statusLine READ statusLine NOTIFY stateChanged)+ // "412 of 1,080 MB" and "About a minute left", while downloading.+ Q_PROPERTY(QString bytesText READ bytesText NOTIFY stateChanged)+ Q_PROPERTY(QString timeLeftText READ timeLeftText NOTIFY stateChanged)+ // What installing downloads ("312 MB"), or what an update downloads.+ Q_PROPERTY(QString downloadText READ downloadText NOTIFY stateChanged)+ Q_PROPERTY(QString updateSizeText READ updateSizeText NOTIFY stateChanged)+ // The newest release's notes, as one plain line.+ Q_PROPERTY(QString releaseNote READ releaseNote NOTIFY dataChanged)+ Q_PROPERTY(QString newVersion READ newVersion NOTIFY dataChanged)+ Q_PROPERTY(QString updatedText READ updatedText NOTIFY stateChanged)+ // Sandboxed is true of every Flathub app. Checked only when Flathub+ // has verified who publishes it, or Wild OS picked it.+ Q_PROPERTY(bool sandboxed READ sandboxed NOTIFY stateChanged)+ Q_PROPERTY(bool checked READ isChecked NOTIFY dataChanged)+ // From the permissions in the app's Flatpak metadata, each entry an+ // {icon, label} map. Empty until the metadata is in.+ Q_PROPERTY(QVariantList canReach READ canReach NOTIFY stateChanged)+ Q_PROPERTY(QVariantList cantReach READ cantReach NOTIFY stateChanged)+ Q_PROPERTY(bool worksOffline READ worksOffline NOTIFY stateChanged)+ Q_PROPERTY(bool reachKnown READ reachKnown NOTIFY stateChanged)+ // The choices before installing: only what the app asks for, each+ // {token, icon, label, detail, allowed, required}.+ Q_PROPERTY(QVariantList consentItems READ consentItems NOTIFY stateChanged)public:StoreApp(Catalog *catalog, const QString &key);@@ -94,8 +133,39 @@ public:bool inStart() const;QVariantList permissions() const;bool permissionsUnknown() const;+ QString progressText() const;+ QString sharedNote() const;+ bool cancellable() const;+ QString buttonState() const;+ QString statusLine() const;+ QString bytesText() const;+ QString timeLeftText() const;+ QString downloadText() const;+ QString updateSizeText() const;+ QString releaseNote() const;+ QString newVersion() const;+ QString updatedText() const;+ bool sandboxed() const;+ bool isChecked() const;+ QVariantList canReach() const;+ QVariantList cantReach() const;+ bool worksOffline() const;+ bool reachKnown() const;+ QVariantList consentItems() const;+ // Bytes short of what installing needs, or 0.+ qint64 spaceShort() const;++ // Launchers are looked up once each, until something is installed or+ // removed or KDE's service cache is rebuilt.+ static void forgetServices();Q_INVOKABLE void install();+ Q_INVOKABLE void cancel();+ // The stop square: stops the download, keeping what it fetched.+ Q_INVOKABLE void pause();+ // Writes the choices made before installing as the app's Flatpak+ // overrides, then installs. choices maps a consent token to on or off.+ Q_INVOKABLE void installWith(const QVariantMap &choices);Q_INVOKABLE void remove();Q_INVOKABLE void update();Q_INVOKABLE bool open();diff --git a/packages/wildos-store/src/timing.h b/packages/wildos-store/src/timing.hnew file mode 100644index 0000000..ce5cca7--- /dev/null+++ b/packages/wildos-store/src/timing.h@@ -0,0 +1,18 @@+#pragma once++#include <QElapsedTimer>+#include <QLoggingCategory>++Q_DECLARE_LOGGING_CATEGORY(lcStore)++// Milliseconds since main() began. The timing lines are written at info+// level, so they only show with QT_LOGGING_RULES="wildos.store.info=true".+inline qint64 storeClock()+{+ static const QElapsedTimer clock = [] {+ QElapsedTimer t;+ t.start();+ return t;+ }();+ return clock.elapsed();+}diff --git a/packages/wildos-system-dialogs/debian/changelog b/packages/wildos-system-dialogs/debian/changelogindex 0ce7f7b..b456132 100644--- a/packages/wildos-system-dialogs/debian/changelog+++ b/packages/wildos-system-dialogs/debian/changelog@@ -1,3 +1,11 @@+wildos-system-dialogs (0.1.1) trixie; urgency=medium++ * Installing a package from a file is never shown as verified, nor as+ coming from Debian or Wild OS: the permission prompt says nothing has+ checked it.++ -- Wild OS Developers <[email protected]> Tue, 10 Nov 2026 07:50:00 +0000+wildos-system-dialogs (0.1.0) trixie; urgency=medium* Initial release.diff --git a/packages/wildos-system-dialogs/src/prompts.cpp b/packages/wildos-system-dialogs/src/prompts.cppindex 43aa605..a168b1a 100644--- a/packages/wildos-system-dialogs/src/prompts.cpp+++ b/packages/wildos-system-dialogs/src/prompts.cpp@@ -72,11 +72,11 @@ KConfigGroup restartConfig()return KSharedConfig::openConfig(Prompts::configFile())->group(QStringLiteral("Restart"));}-// "Tonight at 23:00", "Tomorrow at 12:00", in the 24-hour clock Wild OS-// uses everywhere.+// "Tonight at 23:00", "Tomorrow at 12:00", in the clock of the regional+// format chosen in Settings.QString describe(const QDateTime &when, const QDateTime &now){- const QString time = QLocale(QLocale::English, QLocale::UnitedKingdom).toString(when.time(), QStringLiteral("HH:mm"));+ const QString time = QLocale::system().toString(when.time(), QLocale::ShortFormat);const int days = now.date().daysTo(when.date());const bool night = when.time().hour() >= 18 || when.time().hour() < 5;if (days == 0) {diff --git a/packages/wildos-system-dialogs/src/verifier.cpp b/packages/wildos-system-dialogs/src/verifier.cppindex ae5f52a..04b4da8 100644--- a/packages/wildos-system-dialogs/src/verifier.cpp+++ b/packages/wildos-system-dialogs/src/verifier.cpp@@ -394,7 +394,7 @@ const QHash<QString, Wording> &wordings(){QStringLiteral("org.freedesktop.packagekit.trigger-offline-upgrade"), {"Wants to upgrade Wild OS the next time the computer restarts.", "Updates", "wildos-updates"}},{QStringLiteral("org.freedesktop.packagekit.upgrade-system"), {"Wants to upgrade Wild OS to a new version.", "Updates", "wildos-updates"}},{QStringLiteral("org.freedesktop.packagekit.package-install"), {"Wants to install an app for everyone on this computer."}},- {QStringLiteral("org.freedesktop.packagekit.package-install-untrusted"), {"Wants to install an app that isn't signed by its maker."}},+ {QStringLiteral("org.freedesktop.packagekit.package-install-untrusted"), {"Wants to install a package from a file. Its setup runs with full access to this computer."}},{QStringLiteral("org.freedesktop.packagekit.package-reinstall"), {"Wants to repair an app by installing it again."}},{QStringLiteral("org.freedesktop.packagekit.package-downgrade"), {"Wants to replace an app with an older version."}},{QStringLiteral("org.freedesktop.packagekit.package-remove"), {"Wants to remove an app from this computer."}},@@ -638,10 +638,24 @@ Verdict Verifier::check(const QString &actionId, const QString &message, const Qreasons << callerCheck.why;}}+ // A package installed from a file (the Store's install page, or any+ // PackageKit client's InstallFiles). The request and the app asking+ // check out, both being PackageKit's and Wild OS's own, but what gets+ // installed is the file, which nothing has vouched for: whatever name+ // or maker it gives is only what its builder typed (see sourceOf). So+ // it is never verified, and the Package line does not name PackageKit+ // as if it were the thing coming from Debian.+ const bool fromFile = actionId == QLatin1String("org.freedesktop.packagekit.package-install-untrusted")+ || details.value(QStringLiteral("role")) == QLatin1String("install-files");+ if (fromFile) {+ reasons.prepend(QStringLiteral("It installs a package from a file, from outside Wild OS, and nothing has checked it."));+ }verdict.verified = reasons.isEmpty();verdict.why = reasons.isEmpty() ? QString() : reasons.constFirst();- verdict.package = !programCheck.package.isEmpty() ? programCheck.package : policyCheck.package;- verdict.origin = !programCheck.origin.isEmpty() ? programCheck.origin : policyCheck.origin;+ if (!fromFile) {+ verdict.package = !programCheck.package.isEmpty() ? programCheck.package : policyCheck.package;+ verdict.origin = !programCheck.origin.isEmpty() ? programCheck.origin : policyCheck.origin;+ }// The name and icon people know the asker by.const auto &map = wordings();diff --git a/packages/wildos-system-dialogs/src/verifier.h b/packages/wildos-system-dialogs/src/verifier.hindex d968559..7e08bde 100644--- a/packages/wildos-system-dialogs/src/verifier.h+++ b/packages/wildos-system-dialogs/src/verifier.h@@ -18,7 +18,8 @@// shipped in the image (/usr/share/wildos/image-packages) or comes, by// apt, from Debian, Debian security, Kicksecure or the Wild OS repository.// Anything else is unverified: a script in a home folder, a Flatpak, a-// package from another vendor or installed by hand.+// package from another vendor or installed by hand. So is any install of a+// package file through PackageKit, whoever asks for it.struct Verdict {QString appName;QString iconName;diff --git a/packages/wildos-taskmanager/qml/Format.qml b/packages/wildos-taskmanager/qml/Format.qmlindex 89f3032..4cd0464 100644--- a/packages/wildos-taskmanager/qml/Format.qml+++ b/packages/wildos-taskmanager/qml/Format.qml@@ -3,9 +3,10 @@ pragma Singletonimport QtQuick// Numbers the way Windows Task Manager writes them: one decimal for CPU and-// rates, whole megabytes with thousands separators for memory.+// rates, whole megabytes with thousands separators for memory, with the+// separators of the regional format chosen in Settings (LC_NUMERIC).QtObject {- readonly property var locale: Qt.locale("en_GB")+ readonly property var locale: Qt.locale()function cpu(value) {return Number(value || 0).toLocaleString(locale, "f", 1) + "%";@@ -21,11 +22,11 @@ QtObject {function disk(bytesPerSecond) {const mb = (bytesPerSecond || 0) / 1048576;- return (mb === 0 ? "0" : mb < 0.05 ? "0.1" : Number(mb).toLocaleString(locale, "f", 1)) + " MB/s";+ return (mb === 0 ? "0" : Number(Math.max(mb, 0.1)).toLocaleString(locale, "f", 1)) + " MB/s";}function network(bytesPerSecond) {const mbps = (bytesPerSecond || 0) * 8 / 1000000;- return (mbps === 0 ? "0" : mbps < 0.05 ? "0.1" : Number(mbps).toLocaleString(locale, "f", 1)) + " Mbps";+ return (mbps === 0 ? "0" : Number(Math.max(mbps, 0.1)).toLocaleString(locale, "f", 1)) + " Mbps";}}diff --git a/packages/wildos-taskmanager/src/systemstats.cpp b/packages/wildos-taskmanager/src/systemstats.cppindex cfe772a..9186d86 100644--- a/packages/wildos-taskmanager/src/systemstats.cpp+++ b/packages/wildos-taskmanager/src/systemstats.cpp@@ -42,7 +42,7 @@ QString readLine(const QString &path)// One decimal under 10 and none above, as Windows Task Manager writes them.QString number(double value, int decimals = 1){- return QLocale(QLocale::English, QLocale::UnitedKingdom).toString(value, 'f', decimals);+ return QLocale::system().toString(value, 'f', decimals);}QString bytes(double value)@@ -846,8 +846,8 @@ QVariantMap SystemStats::details(const QString &id) constpair(QStringLiteral("Utilisation"), percent(m_cpu)),pair(QStringLiteral("Speed"), m_speedMhz > 0 ? number(m_speedMhz / 1000, 1) + QStringLiteral(" GHz") : QStringLiteral("Unknown")),pair(QStringLiteral("Temperature"), m_temperature > 0 ? number(m_temperature, 0) + QStringLiteral("°C") : QStringLiteral("Unknown")),- pair(QStringLiteral("Processes"), QLocale(QLocale::English, QLocale::UnitedKingdom).toString(p->processCount())),- pair(QStringLiteral("Threads"), QLocale(QLocale::English, QLocale::UnitedKingdom).toString(p->threadCount())),+ pair(QStringLiteral("Processes"), QLocale::system().toString(p->processCount())),+ pair(QStringLiteral("Threads"), QLocale::system().toString(p->threadCount())),pair(QStringLiteral("Up time"), upTime()),};QVariantList specs;diff --git a/packages/wildos-ui/debian/changelog b/packages/wildos-ui/debian/changelogindex f6404a9..dd941ca 100644--- a/packages/wildos-ui/debian/changelog+++ b/packages/wildos-ui/debian/changelog@@ -1,3 +1,10 @@+wildos-ui (0.1.1) trixie; urgency=medium++ * Stronger text on glass makes glass behind text nearly solid and muted text+ brighter.++ -- Wild OS Developers <[email protected]> Tue, 10 Nov 2026 08:10:42 +0000+wildos-ui (0.1.0) trixie; urgency=medium* Initial release.diff --git a/packages/wildos-ui/qml/Dialog.qml b/packages/wildos-ui/qml/Dialog.qmlindex 769fadb..1f0b6c0 100644--- a/packages/wildos-ui/qml/Dialog.qml+++ b/packages/wildos-ui/qml/Dialog.qml@@ -30,6 +30,43 @@ T.Dialog {readonly property bool large: size === "large"+ function holdsFocus(item) {+ for (let i = item; i; i = i.parent) {+ if (i === control.contentItem) {+ return true;+ }+ }+ return false;+ }++ // Enter presses the button that has the keyboard, otherwise the main+ // action, as Windows dialogs do. Fields that use Enter themselves accept+ // it first and never get here.+ function pressDefault(event) {+ const w = control.contentItem.Window.window;+ const f = w ? w.activeFocusItem : null;+ const shown = Array.from(buttonRow.children).filter(b => b.visible && b.enabled && b.clicked !== undefined);+ let target = shown.find(b => b === f);+ if (!target) {+ const primaries = shown.filter(b => b.primary === true);+ target = primaries[primaries.length - 1];+ }+ if (target) {+ target.clicked();+ } else {+ event.accepted = false;+ }+ }++ // Without this the keyboard can stay on whatever opened the dialog+ // behind it, and Enter never reaches the dialog.+ onOpened: {+ const w = contentItem.Window.window;+ if (!holdsFocus(w ? w.activeFocusItem : null)) {+ contentItem.forceActiveFocus(Qt.PopupFocusReason);+ }+ }+parent: T.Overlay.overlayanchors.centerIn: parentwidth: Math.min(large ? 640 : 440, parent ? parent.width - 48 : 640)@@ -68,6 +105,9 @@ T.Dialog {contentItem: ColumnLayout {spacing: control.large ? 18 : 12+ focus: true+ Keys.onReturnPressed: event => control.pressDefault(event)+ Keys.onEnterPressed: event => control.pressDefault(event)RowLayout {Layout.fillWidth: true@@ -153,8 +193,14 @@ T.Dialog {ordering = true;const kids = Array.from(children);const primaries = kids.filter(c => c.primary === true);- const last = kids[kids.length - 1];- if (primaries.length > 0 && !(primaries.length === 1 && last === primaries[0])) {+ // Only moves them when they are not already the last+ // ones. Moving changes children and runs this again,+ // so a dialog with two primaries (Files' questions)+ // used to move them for ever, and every move took the+ // keyboard off the button being clicked and cancelled+ // the click.+ const tail = kids.slice(kids.length - primaries.length);+ if (primaries.some((b, i) => tail[i] !== b)) {// Re-adding an item appends it, so this moves the// primary buttons to the end in their own order.for (const b of primaries) {diff --git a/packages/wildos-ui/qml/Menu.qml b/packages/wildos-ui/qml/Menu.qmlindex 23b8d50..81aa1ac 100644--- a/packages/wildos-ui/qml/Menu.qml+++ b/packages/wildos-ui/qml/Menu.qml@@ -58,6 +58,19 @@ T.Menu {}onOpened: updateBackdrop()++ // A menu drawn inside its window never sees a click on another window+ // or the desktop, so it closes when its window stops being the active+ // one, as menus on Windows do. Menus in a window of their own are+ // closed by the compositor.+ Connections {+ target: control.popupType === T.Popup.Item && control.parent ? control.parent.Window.window : null+ function onActiveChanged() {+ if (control.visible && !control.parent.Window.window.active) {+ control.dismiss();+ }+ }+ }onXChanged: updateBackdrop()onYChanged: updateBackdrop()onWidthChanged: updateBackdrop()diff --git a/packages/wildos-ui/qml/Style.qml b/packages/wildos-ui/qml/Style.qmlindex 637ed75..6d1941b 100644--- a/packages/wildos-ui/qml/Style.qml+++ b/packages/wildos-ui/qml/Style.qml@@ -10,8 +10,9 @@ import WildOS.UI// rgba(250,251,254,a), ink is #151b2c, and hairlines, hovers and cards use// rgba(30,40,70,a) at three quarters of the dark white alpha.//-// The accent and the scheme come from the system (Theme reads kdeglobals),-// so nothing here needs an app's own backend.+// The accent, the scheme and the theme's glass come from the system (Theme+// reads kdeglobals and wildosrc), so nothing here needs an app's own+// backend.QtObject {id: style@@ -23,6 +24,19 @@ QtObject {readonly property bool contrast: Theme.highContrastreadonly property color contrastEdge: "#ffffff"readonly property color contrastDivider: Qt.rgba(1, 1, 1, 0.6)+ // Stronger text on glass (Settings > Accessibility): every glass+ // surface behind text goes most of the way to solid, so the wallpaper+ // and windows behind no longer show through the letters, and muted text+ // moves halfway to full strength. High contrast is solid already.+ readonly property bool stronger: Theme.strongerText && !contrast+ // wildos-branding's theme-variants.py makes the "-solid" Plasma styles+ // behind Start and the flyouts with the same rule; keep the two in step.+ function solid(alpha) {+ return stronger ? alpha + (1 - alpha) * 0.8 : alpha;+ }+ function legible(alpha) {+ return stronger ? alpha + (1 - alpha) * 0.5 : alpha;+ }// Text size contract: Settings > Personalisation > Text size sets the// system font, Inter 10 pt by default, and Theme follows it live. Every@@ -57,7 +71,7 @@ QtObject {if (contrast) {return darkAlpha >= 0.5 ? "#ffffff" : "#a6a6a6";}- return dark ? Qt.rgba(232 / 255, 236 / 255, 248 / 255, darkAlpha) : Qt.rgba(21 / 255, 27 / 255, 44 / 255, lightAlpha);+ return dark ? Qt.rgba(232 / 255, 236 / 255, 248 / 255, legible(darkAlpha)) : Qt.rgba(21 / 255, 27 / 255, 44 / 255, legible(lightAlpha));}// The deep navy shade under a title bar or a side column (Main.dc// rgba(6,8,20,a)); light mode uses the navy tone instead.@@ -65,38 +79,55 @@ QtObject {if (contrast) {return "#000000";}- return dark ? Qt.rgba(6 / 255, 8 / 255, 20 / 255, darkAlpha) : Qt.rgba(30 / 255, 40 / 255, 70 / 255, lightAlpha);+ return dark ? tinted(6, 8, 20, darkAlpha) : Qt.rgba(30 / 255, 40 / 255, 70 / 255, lightAlpha);}function glass(r, g, b, darkAlpha, lightAlpha) {if (contrast) {return "#000000";}- return dark ? Qt.rgba(r / 255, g / 255, b / 255, darkAlpha) : Qt.rgba(250 / 255, 251 / 255, 254 / 255, lightAlpha);+ const c = dark ? tinted(r, g, b, darkAlpha) : tinted(250, 251, 254, lightAlpha);+ return Qt.rgba(c.r, c.g, c.b, solid(c.a));+ }+ // A theme gives one glass colour (Settings > Personalisation > Themes);+ // every surface keeps its relation to the reference surface it was+ // designed against. Each channel is scaled by the theme's share of the+ // reference, which keeps the hue of the theme in the darkest shades,+ // and the alpha moves by the theme's difference. With the stock theme+ // the tint is the reference and every value comes out as designed.+ // wildos-branding's theme-variants.py does the same for the Plasma+ // frames behind Start and the flyouts; keep the two in step.+ readonly property color glassTint: Theme.glassTint+ readonly property color glassReference: Theme.glassReference+ function tinted(r, g, b, a) {+ const t = glassTint;+ const ref = glassReference;+ return Qt.rgba(Math.min(1, r / 255 * t.r / ref.r), Math.min(1, g / 255 * t.g / ref.g), Math.min(1, b / 255 * t.b / ref.b),+ Math.max(0, Math.min(1, a + t.a - ref.a)));}- readonly property color ink: contrast ? "#ffffff" : dark ? "#eef1f8" : "#151b2c"+ readonly property color ink: contrast || (stronger && dark) ? "#ffffff" : dark ? "#eef1f8" : stronger ? "#0b1020" : "#151b2c"readonly property color inkStrong: dark ? "#ffffff" : "#0b1020"readonly property color inkField: contrast ? "#ffffff" : dark ? "#f3f5fb" : "#151b2c"readonly property color inkMuted: inkAlpha(0.72, 0.66)readonly property color inkStatus: inkAlpha(0.80, 0.74)readonly property color inkPlaceholder: inkAlpha(0.60, 0.55)readonly property color inkSubtle: inkAlpha(0.58, 0.55)- readonly property color inkDisabled: inkAlpha(0.40, 0.38)+ readonly property color inkDisabled: contrast ? "#a6a6a6" : dark ? Qt.rgba(232 / 255, 236 / 255, 248 / 255, 0.40) : Qt.rgba(21 / 255, 27 / 255, 44 / 255, 0.38)// UI line icons; app icons never change between schemes.readonly property color iconInk: contrast ? "#ffffff" : dark ? "#eef1f8" : "#2a3147"- readonly property color iconMuted: contrast ? "#ffffff" : dark ? Qt.rgba(238 / 255, 241 / 255, 248 / 255, 0.75) : Qt.rgba(42 / 255, 49 / 255, 71 / 255, 0.75)+ readonly property color iconMuted: contrast ? "#ffffff" : dark ? Qt.rgba(238 / 255, 241 / 255, 248 / 255, legible(0.75)) : Qt.rgba(42 / 255, 49 / 255, 71 / 255, legible(0.75))// Desktop labels and the lock screen sit on the photograph.readonly property color inkOnWallpaper: "#ffffff"// Everything else that sits straight on the photograph (the lock and// sign-in screens, Lock.dc) keeps the same dark glass and light ink in// either scheme, so it reads on any picture.- readonly property color inkOnWallpaperMuted: contrast ? "#ffffff" : Qt.rgba(232 / 255, 236 / 255, 248 / 255, 0.72)+ readonly property color inkOnWallpaperMuted: contrast ? "#ffffff" : Qt.rgba(232 / 255, 236 / 255, 248 / 255, legible(0.72))readonly property color wallpaperDim: Qt.rgba(8 / 255, 12 / 255, 30 / 255, 0.22)readonly property color textShadowOnWallpaper: Qt.rgba(8 / 255, 12 / 255, 30 / 255, 0.45)- readonly property color glassOnWallpaper: contrast ? "#000000" : Qt.rgba(12 / 255, 16 / 255, 32 / 255, 0.45)- readonly property color glassOnWallpaperField: contrast ? "#000000" : Qt.rgba(12 / 255, 16 / 255, 32 / 255, 0.50)- readonly property color glassOnWallpaperHover: Qt.rgba(28 / 255, 33 / 255, 54 / 255, 0.60)- readonly property color glassOnWallpaperPressed: Qt.rgba(40 / 255, 46 / 255, 72 / 255, 0.68)+ readonly property color glassOnWallpaper: contrast ? "#000000" : Qt.rgba(12 / 255, 16 / 255, 32 / 255, solid(0.45))+ readonly property color glassOnWallpaperField: contrast ? "#000000" : Qt.rgba(12 / 255, 16 / 255, 32 / 255, solid(0.50))+ readonly property color glassOnWallpaperHover: Qt.rgba(28 / 255, 33 / 255, 54 / 255, solid(0.60))+ readonly property color glassOnWallpaperPressed: Qt.rgba(40 / 255, 46 / 255, 72 / 255, solid(0.68))readonly property color borderOnWallpaper: contrast ? contrastEdge : Qt.rgba(1, 1, 1, 0.14)readonly property color borderOnWallpaperField: contrast ? contrastEdge : Qt.rgba(1, 1, 1, 0.22)// Controls drawn straight on a dimmed photograph (CtrlAltDel.dc): the@@ -128,11 +159,14 @@ QtObject {return out;}readonly property bool glacier: Qt.colorEqual(systemAccent, "#8fb4ff")- readonly property color accent: contrast ? "#75e9fc" : dark ? systemAccent : glacier ? "#3563d8" : deepen(systemAccent, 0.676, 0.527, 4.5)- readonly property color textOnAccent: contrast ? "#000000" : dark ? "#0f1530" : "#ffffff"+ // A theme's own accent in its own mode is used as the theme gives it,+ // with the text colours the theme was checked with (WCAG AA).+ readonly property bool themeAccent: !contrast && Theme.themeAccent+ readonly property color accent: contrast ? "#75e9fc" : dark || themeAccent ? systemAccent : glacier ? "#3563d8" : deepen(systemAccent, 0.676, 0.527, 4.5)+ readonly property color textOnAccent: contrast ? "#000000" : themeAccent ? Theme.textOnAccent : dark ? "#0f1530" : "#ffffff"// Glacier's dark accent-text is #b9cfff, 40% of the way to white; the// other accents get the same lift.- readonly property color accentText: contrast ? accent : dark+ readonly property color accentText: contrast ? accent : themeAccent ? Theme.accentText : dark? Qt.rgba(accent.r + (1 - accent.r) * 0.4, accent.g + (1 - accent.g) * 0.4, accent.b + (1 - accent.b) * 0.4, 1): glacier ? "#2a55c4" : deepen(systemAccent, 0.647, 0.467, 5.5)readonly property color accentHover: dark ? Qt.lighter(accent, 1.08) : Qt.darker(accent, 1.08)@@ -148,6 +182,18 @@ QtObject {readonly property color accentBorderStrong: accentAlpha(0.55, 0.413)readonly property color glassBar: glass(12, 16, 32, 0.55, 0.55)+ // The taskbar (wildos-shell): docked along the bottom, or the floating+ // pills. A theme can give the docked bar a glass of its own; the pills+ // then take the same colour, as much lighter as the stock pills are.+ readonly property color taskbarDocked: contrast ? "#000000" : solidified(Theme.hasTaskbarTint ? Theme.taskbarTint+ : dark ? tinted(14, 18, 34, 0.88) : tinted(246, 248, 252, 0.90))+ readonly property color taskbarFloating: contrast ? "#000000" : solidified(Theme.hasTaskbarTint+ ? Qt.rgba(Theme.taskbarTint.r, Theme.taskbarTint.g, Theme.taskbarTint.b, Math.max(0, Theme.taskbarTint.a - (dark ? 0.33 : 0.23)))+ : dark ? tinted(12, 16, 32, 0.55) : tinted(250, 251, 254, 0.67))+ function solidified(c) {+ return Qt.rgba(c.r, c.g, c.b, solid(c.a));+ }+ readonly property color taskbarShadow: dark ? tinted(6, 10, 28, 0.35) : Qt.rgba(20 / 255, 30 / 255, 60 / 255, 0.14)readonly property color glassPanel: glass(16, 20, 38, 0.76, 0.86)readonly property color glassWindow: glass(20, 24, 42, 0.80, 0.92)readonly property color glassWindowDeep: glass(18, 22, 40, 0.86, 0.94)@@ -158,13 +204,13 @@ QtObject {// and 7px row corners.readonly property color glassContextMenu: glass(16, 20, 38, 0.86, 0.95)readonly property color borderContextMenu: contrast ? contrastEdge : tone(0.12)- readonly property color shadowContextMenu: dark ? Qt.rgba(4 / 255, 8 / 255, 24 / 255, 0.45) : Qt.rgba(20 / 255, 30 / 255, 60 / 255, 0.18)+ readonly property color shadowContextMenu: dark ? tinted(4, 8, 24, 0.45) : Qt.rgba(20 / 255, 30 / 255, 60 / 255, 0.18)// Behind a window when transparency effects are off or blur is missing.- readonly property color windowOpaque: contrast ? "#000000" : dark ? "#151a2f" : "#f4f6fb"- readonly property color ground: contrast ? "#000000" : dark ? "#0f1326" : "#eef1f7"+ readonly property color windowOpaque: contrast ? "#000000" : dark ? tinted(21, 26, 47, 1) : "#f4f6fb"+ readonly property color ground: contrast ? "#000000" : dark ? tinted(15, 19, 38, 1) : "#eef1f7"readonly property color lakeNavy: "#1d2b52"- readonly property color surfaceSunken: contrast ? "#000000" : dark ? Qt.rgba(6 / 255, 8 / 255, 20 / 255, 0.35) : Qt.rgba(250 / 255, 251 / 255, 254 / 255, 0.55)+ readonly property color surfaceSunken: contrast ? "#000000" : dark ? tinted(6, 8, 20, 0.35) : tinted(250, 251, 254, 0.55)readonly property color surfaceRaised: tone(0.05)readonly property color surfaceRest: tone(0.04)readonly property color surfaceControl: tone(0.06)@@ -176,7 +222,7 @@ QtObject {// The band along the foot of Start and the flyouts (account and power,// battery): darker than the glass in dark mode, paler in light// (Flyouts.dc rgba(4,6,18,0.30), FlyoutsLight.dc rgba(250,251,254,0.55)).- readonly property color surfaceBand: contrast ? "#000000" : dark ? Qt.rgba(4 / 255, 6 / 255, 18 / 255, 0.30) : Qt.rgba(250 / 255, 251 / 255, 254 / 255, 0.55)+ readonly property color surfaceBand: contrast ? "#000000" : dark ? tinted(4, 6, 18, 0.30) : tinted(250, 251, 254, 0.55)readonly property color borderSubtle: contrast ? contrastEdge : tone(0.07)readonly property color divider: contrast ? contrastDivider : tone(0.06)@@ -197,9 +243,9 @@ QtObject {readonly property color scrim: contrast ? Qt.rgba(0, 0, 0, 0.75) : dark ? Qt.rgba(6 / 255, 10 / 255, 26 / 255, 0.45) : Qt.rgba(20 / 255, 30 / 255, 60 / 255, 0.22)// Shadows keep their shape and drop to about 40% strength in light mode.- readonly property color shadowWindow: dark ? Qt.rgba(4 / 255, 8 / 255, 24 / 255, 0.45) : Qt.rgba(20 / 255, 30 / 255, 60 / 255, 0.18)- readonly property color shadowFlyout: dark ? Qt.rgba(4 / 255, 8 / 255, 24 / 255, 0.55) : Qt.rgba(20 / 255, 30 / 255, 60 / 255, 0.22)- readonly property color shadowMenu: dark ? Qt.rgba(4 / 255, 8 / 255, 24 / 255, 0.60) : Qt.rgba(20 / 255, 30 / 255, 60 / 255, 0.24)+ readonly property color shadowWindow: dark ? tinted(4, 8, 24, 0.45) : Qt.rgba(20 / 255, 30 / 255, 60 / 255, 0.18)+ readonly property color shadowFlyout: dark ? tinted(4, 8, 24, 0.55) : Qt.rgba(20 / 255, 30 / 255, 60 / 255, 0.22)+ readonly property color shadowMenu: dark ? tinted(4, 8, 24, 0.60) : Qt.rgba(20 / 255, 30 / 255, 60 / 255, 0.24)readonly property color closeHover: "#c4463f"readonly property color closePressed: "#a63a34"diff --git a/packages/wildos-ui/src/theme.cpp b/packages/wildos-ui/src/theme.cppindex 8ed9204..86bffc2 100644--- a/packages/wildos-ui/src/theme.cpp+++ b/packages/wildos-ui/src/theme.cpp@@ -4,8 +4,12 @@#include <KSharedConfig>#include <QEvent>+#include <QFile>#include <QFont>#include <QGuiApplication>+#include <QJsonDocument>+#include <QJsonObject>+#include <QStandardPaths>namespace{@@ -22,6 +26,26 @@ QColor parseColour(const QString &value)}return value.isEmpty() ? QColor() : QColor(value);}++// Dawn's window glass and the light glass of the theme cards. A theme's+// glass is given as this one surface; every other surface keeps its+// relation to it (see Style.tinted).+const QColor darkReference = QColor::fromRgbF(18 / 255.0, 22 / 255.0, 40 / 255.0, 0.86);+const QColor lightReference = QColor::fromRgbF(250 / 255.0, 251 / 255.0, 254 / 255.0, 0.82);++// {"colour": "#rrggbb", "alpha": 0.86}, or a bare "#rrggbb".+QColor jsonColour(const QJsonValue &value)+{+ if (value.isString()) {+ return QColor(value.toString());+ }+ const QJsonObject object = value.toObject();+ QColor colour(object.value(QStringLiteral("colour")).toString());+ if (colour.isValid()) {+ colour.setAlphaF(object.value(QStringLiteral("alpha")).toDouble(1.0));+ }+ return colour;+}}Theme::Theme(QObject *parent)@@ -36,6 +60,22 @@ Theme::Theme(QObject *parent)m_settle.setSingleShot(true);m_settle.setInterval(150);connect(&m_settle, &QTimer::timeout, this, &Theme::read);+ // Whether the theme's glass and text colours apply depends on the mode+ // and the accent, so either change can change them.+ connect(this, &Theme::darkChanged, this, &Theme::themeChanged);+ connect(this, &Theme::accentChanged, this, &Theme::themeChanged);+ readTheme();+ readAccessibility();+ m_wildosWatcher = KConfigWatcher::create(KSharedConfig::openConfig(QStringLiteral("wildosrc")));+ if (m_wildosWatcher) {+ connect(m_wildosWatcher.data(), &KConfigWatcher::configChanged, this, [this](const KConfigGroup &group) {+ if (group.name() == QLatin1String("Theme")) {+ readTheme();+ } else if (group.name() == QLatin1String("Accessibility")) {+ readAccessibility();+ }+ });+ }m_watcher = KConfigWatcher::create(KSharedConfig::openConfig(QStringLiteral("kdeglobals")));if (m_watcher) {connect(m_watcher.data(), &KConfigWatcher::configChanged, this, [this](const KConfigGroup &group) {@@ -93,6 +133,64 @@ void Theme::read()}}+void Theme::readTheme()+{+ KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("wildosrc"));+ config->reparseConfiguration();+ const QString id = config->group(QStringLiteral("Theme")).readEntry("Id", QStringLiteral("dawn"));++ QJsonObject theme;+ const QString path = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("wildos/themes/%1.json").arg(id));+ QFile file(path);+ if (!path.isEmpty() && file.open(QIODevice::ReadOnly)) {+ theme = QJsonDocument::fromJson(file.readAll()).object();+ }++ m_themeId = id;+ m_themeMode = theme.value(QStringLiteral("mode")).toString();+ m_themeAccent = jsonColour(theme.value(QStringLiteral("accent")).toObject().value(QStringLiteral("colour")));+ m_glass = jsonColour(theme.value(QStringLiteral("glass")));+ m_taskbarTint = jsonColour(theme.value(QStringLiteral("taskbarGlass")));+ m_textOnAccent = jsonColour(theme.value(QStringLiteral("textOnAccent")));+ m_accentText = jsonColour(theme.value(QStringLiteral("accentText")));+ Q_EMIT themeChanged();+}++void Theme::readAccessibility()+{+ KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("wildosrc"));+ config->reparseConfiguration();+ const bool stronger = config->group(QStringLiteral("Accessibility")).readEntry("StrongerText", false);+ if (stronger != m_strongerText) {+ m_strongerText = stronger;+ Q_EMIT strongerTextChanged();+ }+}++bool Theme::themeMode() const+{+ if (highContrast() || m_themeMode.isEmpty()) {+ return false;+ }+ return (m_themeMode == QLatin1String("dark")) == m_dark;+}++QColor Theme::glassReference() const+{+ return m_dark ? darkReference : lightReference;+}++QColor Theme::glassTint() const+{+ return themeMode() && m_glass.isValid() ? m_glass : glassReference();+}++bool Theme::themeAccent() const+{+ return themeMode() && m_themeAccent.isValid() && m_themeAccent.rgb() == m_accent.rgb() && m_textOnAccent.isValid()+ && m_accentText.isValid();+}+qreal Theme::fontPointSize() const{// A font set in pixels reports no point size; 96 dpi is what thediff --git a/packages/wildos-ui/src/theme.h b/packages/wildos-ui/src/theme.hindex d5457c6..cc6f155 100644--- a/packages/wildos-ui/src/theme.h+++ b/packages/wildos-ui/src/theme.h@@ -7,10 +7,12 @@#include <QTimer>// What the system decides for every Wild OS surface: the accent chosen in-// Settings > Personalisation and whether the session is dark or light. Both-// live in kdeglobals ([General] AccentColor and ColorScheme), which Settings-// writes with KConfig::Notify, so apps, plasmoids and the shell repaint the-// moment either changes.+// Settings > Personalisation, whether the session is dark or light, and the+// theme's glass tint. The first two live in kdeglobals ([General]+// AccentColor and ColorScheme), the theme in wildosrc ([Theme] Id, one of+// /usr/share/wildos/themes/<id>.json). Settings writes all of them with+// KConfig::Notify, so apps, plasmoids and the shell repaint the moment any+// changes.class Theme : public QObject{Q_OBJECT@@ -31,6 +33,29 @@ class Theme : public QObject// Settings > Accessibility > Reduce motion, which sets KDE's animation// speed to instant (kdeglobals [KDE] AnimationDurationFactor=0).Q_PROPERTY(bool reducedMotion READ reducedMotion NOTIFY reducedMotionChanged)+ // Settings > Accessibility > Stronger text on glass (wildosrc+ // [Accessibility] StrongerText): Style makes glass nearly solid and+ // muted text brighter.+ Q_PROPERTY(bool strongerText READ strongerText NOTIFY strongerTextChanged)++ // The theme picked in Settings > Personalisation > Themes ("dawn" when+ // none has been).+ Q_PROPERTY(QString themeId READ themeId NOTIFY themeChanged)+ // Every glass surface is tinted relative to glassReference, the colour+ // of the reference surface (window glass in dark mode, the theme cards'+ // light glass in light mode). glassTint is the theme's glass while the+ // session is in the theme's own mode, otherwise the reference, so a+ // light theme switched to dark by hand falls back to the stock glass.+ Q_PROPERTY(QColor glassReference READ glassReference NOTIFY themeChanged)+ Q_PROPERTY(QColor glassTint READ glassTint NOTIFY themeChanged)+ // A taskbar glass of its own (Overclock's is darker than its windows).+ Q_PROPERTY(bool hasTaskbarTint READ hasTaskbarTint NOTIFY themeChanged)+ Q_PROPERTY(QColor taskbarTint READ taskbarTint NOTIFY themeChanged)+ // The theme's text colours hold only for the theme's own accent in its+ // own mode; any other accent gets the computed ones.+ Q_PROPERTY(bool themeAccent READ themeAccent NOTIFY themeChanged)+ Q_PROPERTY(QColor textOnAccent READ textOnAccent NOTIFY themeChanged)+ Q_PROPERTY(QColor accentText READ accentText NOTIFY themeChanged)public:explicit Theme(QObject *parent = nullptr);@@ -41,6 +66,16 @@ public:bool highContrast() const { return m_scheme == QLatin1String("WildOSHighContrast"); }qreal fontPointSize() const;bool reducedMotion() const { return m_reducedMotion; }+ bool strongerText() const { return m_strongerText; }++ QString themeId() const { return m_themeId; }+ QColor glassReference() const;+ QColor glassTint() const;+ bool hasTaskbarTint() const { return themeMode() && m_taskbarTint.isValid(); }+ QColor taskbarTint() const { return m_taskbarTint; }+ bool themeAccent() const;+ QColor textOnAccent() const { return m_textOnAccent; }+ QColor accentText() const { return m_accentText; }protected:bool eventFilter(QObject *watched, QEvent *event) override;@@ -50,14 +85,30 @@ Q_SIGNALS:void darkChanged();void fontPointSizeChanged();void reducedMotionChanged();+ void strongerTextChanged();+ void themeChanged();private:void read();+ void readTheme();+ void readAccessibility();+ // The session is in the mode the theme was made for.+ bool themeMode() const;KConfigWatcher::Ptr m_watcher;+ KConfigWatcher::Ptr m_wildosWatcher;QTimer m_settle;QColor m_accent;bool m_dark = true;bool m_reducedMotion = false;+ bool m_strongerText = false;QString m_scheme;++ QString m_themeId;+ QString m_themeMode;+ QColor m_themeAccent;+ QColor m_glass;+ QColor m_taskbarTint;+ QColor m_textOnAccent;+ QColor m_accentText;};diff --git a/packages/wildos-welcome/src/windowsimport.cpp b/packages/wildos-welcome/src/windowsimport.cppindex 71819c0..999981e 100644--- a/packages/wildos-welcome/src/windowsimport.cpp+++ b/packages/wildos-welcome/src/windowsimport.cpp@@ -666,7 +666,7 @@ void WindowsImport::release()QString WindowsImport::formatBytes(qint64 bytes, bool whole) const{// Decimal units, the way drives are sold and Windows shows them.- const QLocale locale(QLocale::English, QLocale::UnitedKingdom);+ const QLocale locale = QLocale::system();const double value = double(bytes);if (value >= 1e12) {return QStringLiteral("%1 TB").arg(locale.toString(value / 1e12, 'f', 1));diff --git a/packages/wildos-welcome/src/windowsprograms.cpp b/packages/wildos-welcome/src/windowsprograms.cppindex 87a498a..3cdd600 100644--- a/packages/wildos-welcome/src/windowsprograms.cpp+++ b/packages/wildos-welcome/src/windowsprograms.cpp@@ -165,7 +165,7 @@ qint64 folderSize(const QString &path)QString formatBytes(qint64 bytes){- const QLocale locale(QLocale::English, QLocale::UnitedKingdom);+ const QLocale locale = QLocale::system();if (bytes >= 1000000000) {return QStringLiteral("%1 GB").arg(locale.toString(bytes / 1e9, 'f', 1));}diff --git a/packages/wildos-winmode/data/templates/domain.xml.in b/packages/wildos-winmode/data/templates/domain.xml.inindex 362b494..7d2c7e8 100644--- a/packages/wildos-winmode/data/templates/domain.xml.in+++ b/packages/wildos-winmode/data/templates/domain.xml.in@@ -3,7 +3,7 @@set follows the old builder's generator (packages/wildos-winmode/src/domain.cpp), moved to the brief's network, disk and firmware-key choices.-->-<domain type='kvm' xmlns:qemu='http://libvirt.org/schemas/domain/qemu/1.0'>+<domain type='kvm'><name>@NAME@</name><title>Windows mode</title><memory unit='MiB'>@MEMORY_MB@</memory>@@ -27,6 +27,7 @@<feature enabled='yes' name='enrolled-keys'/></firmware><smbios mode='sysinfo'/>+ @ACPI_TABLES@</os><features><acpi/>@@ -128,5 +129,4 @@<backend model='random'>/dev/urandom</backend></rng></devices>- @QEMU_COMMANDLINE@</domain>diff --git a/packages/wildos-winmode/debian/changelog b/packages/wildos-winmode/debian/changelogindex 689c901..c5a697b 100644--- a/packages/wildos-winmode/debian/changelog+++ b/packages/wildos-winmode/debian/changelog@@ -1,3 +1,20 @@+wildos-winmode (0.3.1) trixie; urgency=medium++ * Windows has all the memory it is set to while any Windows app is open.+ Unused memory went back to Wild OS every 30 seconds whatever Windows+ was doing, and Windows only grew back into it a step at a time, so+ with 8 GB set it worked like a 4 GB PC: a program asking for 5 GB+ took 94 seconds to get it. Memory now goes back only while no Windows+ app is open, and the first app to open gets all of it at once,+ including one opened from inside Windows.+ * After a change of memory in Settings, an app opening before Windows+ had restarted got none of Windows' memory back: the service asked for+ the new amount, which a running Windows can't take, and libvirt+ refused the lot. It now gives back everything Windows started with,+ and the new amount comes with the restart as before.++ -- Wild OS Developers <[email protected]> Tue, 10 Nov 2026 09:30:00 +0000+wildos-winmode (0.3.0) trixie; urgency=medium* Setting up Windows mode: the wizard (boards 9.1 to 9.7) and the setupdiff --git a/packages/wildos-winmode/debian/control b/packages/wildos-winmode/debian/controlindex 3546cbe..183ee53 100644--- a/packages/wildos-winmode/debian/control+++ b/packages/wildos-winmode/debian/control@@ -69,6 +69,7 @@ Depends:swtpm-tools,virtiofsd,freerdp3-x11,+ wildos-rdp,xorriso,Description: Wild OS Windows mode, the virtual PC it runs onQEMU, libvirt and FreeRDP, which Windows mode needs only once it is setdiff --git a/packages/wildos-winmode/debian/wildos-winmode.install b/packages/wildos-winmode/debian/wildos-winmode.installindex 1326586..0ec4220 100644--- a/packages/wildos-winmode/debian/wildos-winmode.install+++ b/packages/wildos-winmode/debian/wildos-winmode.install@@ -18,6 +18,7 @@ bin/winmoded usr/libexec/wildosbin/wildos-winmode usr/binbuild/wild-guest.exe usr/share/wildos/winmode/guestguest/setup.ps1 usr/share/wildos/winmode/guest+guest/opengl.ps1 usr/share/wildos/winmode/guestdata/mimeapps.list usr/share/wildos/winmodedata/org.wildos.WindowsMode1.conf usr/share/dbus-1/system.ddata/org.wildos.winmode.policy usr/share/polkit-1/actionsdiff --git a/packages/wildos-winmode/guest/api.txt b/packages/wildos-winmode/guest/api.txtindex 3cbae14..175b2b2 100644--- a/packages/wildos-winmode/guest/api.txt+++ b/packages/wildos-winmode/guest/api.txt@@ -15,8 +15,12 @@ member [System.ServiceProcess]System.ServiceProcess.SessionChangeDescription.getmember [System.ServiceProcess]System.ServiceProcess.SessionChangeDescription.get_SessionId :: instance int32()member [System]System.ComponentModel.Win32Exception.get_NativeErrorCode :: instance int32()member [System]System.Diagnostics.Process.GetCurrentProcess :: class [System]System.Diagnostics.Process()+member [System]System.Diagnostics.Process.GetProcessesByName :: class [System]System.Diagnostics.Process[](string)member [System]System.Diagnostics.Process.Start :: class [System]System.Diagnostics.Process(class [System]System.Diagnostics.ProcessStartInfo)member [System]System.Diagnostics.Process.get_Id :: instance int32()+member [System]System.Diagnostics.Process.get_SessionId :: instance int32()+member [System]System.Diagnostics.Process.get_StartTime :: instance valuetype [mscorlib]System.DateTime()+member [System]System.Diagnostics.Process.set_PriorityClass :: instance void(valuetype [System]System.Diagnostics.ProcessPriorityClass)member [System]System.Diagnostics.ProcessStartInfo..ctor :: instance void(string, string)member [System]System.Diagnostics.ProcessStartInfo.set_UseShellExecute :: instance void(bool)member [System]System.Diagnostics.ProcessStartInfo.set_WorkingDirectory :: instance void(string)@@ -49,10 +53,12 @@ member [mscorlib]System.Convert.ToDouble :: float64(object, class [mscorlib]Systmember [mscorlib]System.Convert.ToInt64 :: int64(object, class [mscorlib]System.IFormatProvider)member [mscorlib]System.Convert.ToString :: string(object)member [mscorlib]System.DateTime..ctor :: instance void(int32, int32, int32, int32, int32, int32, valuetype [mscorlib]System.DateTimeKind)+member [mscorlib]System.DateTime..ctor :: instance void(int64, valuetype [mscorlib]System.DateTimeKind)member [mscorlib]System.DateTime.AddMilliseconds :: instance valuetype [mscorlib]System.DateTime(float64)member [mscorlib]System.DateTime.AddSeconds :: instance valuetype [mscorlib]System.DateTime(float64)member [mscorlib]System.DateTime.MinValue :: valuetype [mscorlib]System.DateTimemember [mscorlib]System.DateTime.ToString :: instance string(string)+member [mscorlib]System.DateTime.ToUniversalTime :: instance valuetype [mscorlib]System.DateTime()member [mscorlib]System.DateTime.get_Day :: instance int32()member [mscorlib]System.DateTime.get_DayOfWeek :: instance valuetype [mscorlib]System.DayOfWeek()member [mscorlib]System.DateTime.get_Hour :: instance int32()@@ -61,6 +67,7 @@ member [mscorlib]System.DateTime.get_Minute :: instance int32()member [mscorlib]System.DateTime.get_Month :: instance int32()member [mscorlib]System.DateTime.get_Now :: valuetype [mscorlib]System.DateTime()member [mscorlib]System.DateTime.get_Second :: instance int32()+member [mscorlib]System.DateTime.get_Ticks :: instance int64()member [mscorlib]System.DateTime.get_UtcNow :: valuetype [mscorlib]System.DateTime()member [mscorlib]System.DateTime.get_Year :: instance int32()member [mscorlib]System.DateTime.op_GreaterThan :: bool(valuetype [mscorlib]System.DateTime, valuetype [mscorlib]System.DateTime)@@ -113,6 +120,7 @@ member [mscorlib]System.IO.Stream.Write :: instance void(unsigned int8[], int32,member [mscorlib]System.Int32.Parse :: int32(string, valuetype [mscorlib]System.Globalization.NumberStyles, class [mscorlib]System.IFormatProvider)member [mscorlib]System.Int32.ToString :: instance string(string, class [mscorlib]System.IFormatProvider)member [mscorlib]System.Int32.TryParse :: bool(string, valuetype [mscorlib]System.Globalization.NumberStyles, class [mscorlib]System.IFormatProvider, [out] int32&)+member [mscorlib]System.Int64.Parse :: int64(string)member [mscorlib]System.Int64.ToString :: instance string(class [mscorlib]System.IFormatProvider)member [mscorlib]System.IntPtr..ctor :: instance void(int32)member [mscorlib]System.IntPtr..ctor :: instance void(int64)@@ -341,6 +349,7 @@ type [System.ServiceProcess]System.ServiceProcess.SessionChangeDescriptiontype [System.ServiceProcess]System.ServiceProcess.SessionChangeReasontype [System]System.ComponentModel.Win32Exceptiontype [System]System.Diagnostics.Process+type [System]System.Diagnostics.ProcessPriorityClasstype [System]System.Diagnostics.ProcessStartInfotype [System]System.Text.RegularExpressions.Regextype [System]System.Text.RegularExpressions.RegexOptionsdiff --git a/packages/wildos-winmode/guest/opengl.ps1 b/packages/wildos-winmode/guest/opengl.ps1new file mode 100644index 0000000..6797f24--- /dev/null+++ b/packages/wildos-winmode/guest/opengl.ps1@@ -0,0 +1,81 @@+# Wild OS Windows mode: OpenGL for programs that need more than 1.1.+#+# Windows here has no graphics driver of its own (the virtual PC has a plain+# display adapter, and Remote Desktop draws the windows), so the only OpenGL+# is Microsoft's software one, which stops at version 1.1. A program that+# asks for anything newer gets no functions back and usually crashes at once+# (MagicaVoxel does, with an access violation at address 0).+#+# This puts Mesa's llvmpipe, a modern software OpenGL renderer, behind Windows'+# own opengl32.dll, the way mesa-dist-win's system-wide deployment does: the+# driver goes in as mesadrv.dll and is registered as the MSOGL driver, the+# one opengl32.dll uses when no graphics driver offers OpenGL. GALLIUM_DRIVER+# keeps Mesa on llvmpipe; left to choose, it takes its Direct3D 12 driver,+# which runs on Windows' WARP renderer and crashed MagicaVoxel too.+#+# Run by setup.ps1, and by the host for a Windows that was set up before+# this existed. It does nothing when the pinned release is already in place.++$ErrorActionPreference = 'Stop'+$ProgressPreference = 'SilentlyContinue'++$version = '26.2.5'+$url = "https://github.com/pal1000/mesa-dist-win/releases/download/$version/mesa3d-$version-release-msvc.7z"+$sha256 = '997123EF4CE8896204AB912D5B54F19372C487FF9835BCEFAFA2FCA23B8953C2'+$state = 'C:\ProgramData\WildOS'+$marker = "$state\opengl.json"++New-Item -ItemType Directory -Force -Path $state | Out-Null+$targets = @{ "$env:windir\System32\mesadrv.dll" = 'x64/libgallium_wgl.dll'; "$env:windir\SysWOW64\mesadrv.dll" = 'x86/libgallium_wgl.dll' }++$have = $null+if (Test-Path $marker) { $have = (Get-Content -Raw $marker | ConvertFrom-Json).version }+$present = @($targets.Keys | Where-Object { Test-Path $_ }).Count -eq $targets.Count+if ($have -eq $version -and $present) { 'already'; exit 0 }++$work = Join-Path $env:TEMP "wildos-opengl"+Remove-Item -Recurse -Force $work -ErrorAction SilentlyContinue+New-Item -ItemType Directory -Force -Path $work | Out-Null+try {+ $archive = "$work\mesa.7z"+ Invoke-WebRequest -UseBasicParsing -Uri $url -OutFile $archive+ $got = (Get-FileHash -Algorithm SHA256 $archive).Hash+ if ($got -ne $sha256) { throw "the Mesa download does not match (got $got)" }+ # Windows' own tar.exe (libarchive) reads 7z.+ & "$env:windir\System32\tar.exe" -x -f $archive -C $work @($targets.Values)+ if ($LASTEXITCODE -ne 0) { throw "tar.exe could not unpack the Mesa download ($LASTEXITCODE)" }++ foreach ($target in $targets.Keys) {+ $source = Join-Path $work ($targets[$target] -replace '/', '\')+ # A program using the old copy keeps it open; a loaded DLL can be+ # renamed but not overwritten. Windows deletes the old copy at its+ # next start.+ if (Test-Path $target) {+ try { Remove-Item -Force $target }+ catch {+ $old = $target + (Get-Date -Format '.yyyyMMddHHmmss') + '.old'+ Rename-Item -Force $target (Split-Path -Leaf $old)+ if (-not ('WildOS.Native' -as [type])) { Add-Type -Namespace WildOS -Name Native -MemberDefinition '[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool MoveFileEx(string from, string to, int flags);' }+ # MOVEFILE_DELAY_UNTIL_REBOOT with no destination: delete then.+ [WildOS.Native]::MoveFileEx($old, [NullString]::Value, 4) | Out-Null+ }+ }+ Copy-Item -Force $source $target+ }++ foreach ($key in 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\OpenGLDrivers\MSOGL',+ 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows NT\CurrentVersion\OpenGLDrivers\MSOGL') {+ New-Item -Force -Path $key | Out-Null+ New-ItemProperty -Force -Path $key -Name 'DLL' -Value 'mesadrv.dll' -PropertyType String | Out-Null+ New-ItemProperty -Force -Path $key -Name 'DriverVersion' -Value 1 -PropertyType DWord | Out-Null+ New-ItemProperty -Force -Path $key -Name 'Flags' -Value 1 -PropertyType DWord | Out-Null+ New-ItemProperty -Force -Path $key -Name 'Version' -Value 2 -PropertyType DWord | Out-Null+ }+ [Environment]::SetEnvironmentVariable('GALLIUM_DRIVER', 'llvmpipe', 'Machine')++ @{ version = $version; installed = (Get-Date).ToString('s') } | ConvertTo-Json -Compress | Set-Content -Encoding UTF8 $marker+ 'installed'+}+finally {+ Remove-Item -Recurse -Force $work -ErrorAction SilentlyContinue+}diff --git a/packages/wildos-winmode/guest/setup.ps1 b/packages/wildos-winmode/guest/setup.ps1index bebc9cd..e411477 100644--- a/packages/wildos-winmode/guest/setup.ps1+++ b/packages/wildos-winmode/guest/setup.ps1@@ -333,6 +333,12 @@ Step 'startup-trim' $false {}}+# OpenGL past 1.1 for the programs that need it (opengl.ps1 says why). Not+# critical: without it Windows mode works and only those programs fail.+Step 'opengl' $false {+ & "$here\opengl.ps1"+}+# 8. Wild OS's light or dark look and accent colour (brief 5.4 step 8):# wild-guest applies theme.json in each session and keeps it up to date.Step 'theme' $false {diff --git a/packages/wildos-winmode/guest/wild-guest/Service.cs b/packages/wildos-winmode/guest/wild-guest/Service.csindex 47eb40a..7191dec 100644--- a/packages/wildos-winmode/guest/wild-guest/Service.cs+++ b/packages/wildos-winmode/guest/wild-guest/Service.cs@@ -238,6 +238,7 @@ namespace WildOS.Guestbreak;case "windows":case "window":+ case "running":case "launch":case "warm-list":var target = Target(m);diff --git a/packages/wildos-winmode/guest/wild-guest/Session.cs b/packages/wildos-winmode/guest/wild-guest/Session.csindex 706751a..5e9fe40 100644--- a/packages/wildos-winmode/guest/wild-guest/Session.cs+++ b/packages/wildos-winmode/guest/wild-guest/Session.cs@@ -88,26 +88,15 @@ namespace WildOS.Guest// the moment it sees one, so taskbar grouping does not wait for it.static void Watch(){- MapDrive();+ OnConnect(false);long connected = ConnectTime();while (true){- // Windows does not send a reconnecting RemoteApp client the- // windows already on screen, so they arrive blank until they- // next change. Every window is redrawn whenever a client- // connects (the session's connect time moves, which also- // catches a connection taking over one Windows still thinks- // is open), and once more a moment later for apps that paint- // late.long now = ConnectTime();if (now != connected){connected = now;- MapDrive();- Thread.Sleep(500);- RedrawAll();- Thread.Sleep(1500);- RedrawAll();+ OnConnect(true);}try{@@ -127,6 +116,34 @@ namespace WildOS.Guest}}+ static readonly object connecting = new object();++ // Windows does not send a reconnecting RemoteApp client the windows+ // already on screen, so they arrive blank until they next change.+ // Every window is redrawn whenever a client connects (the session's+ // connect time moves, which also catches a connection taking over one+ // Windows still thinks is open), and once more a moment later for+ // apps that paint late. Mapping the drive can take up to 15 seconds,+ // so all of it runs beside the window list, which must keep going:+ // Wild OS reads from it whether an app is still open.+ static void OnConnect(bool redraw)+ {+ var t = new Thread(delegate ()+ {+ lock (connecting)+ {+ MapDrive();+ if (!redraw) return;+ Thread.Sleep(500);+ RedrawAll();+ Thread.Sleep(1500);+ RedrawAll();+ }+ });+ t.IsBackground = true;+ t.Start();+ }+// Z: is the folders Wild OS shares through the RemoteApp connection// (FreeRDP's /drive:wildos), which exists only while it is connected,// so it is mapped again on every connect. \\tsclient appears a moment@@ -222,6 +239,9 @@ namespace WildOS.Guestcase "window":reply = Message("window", "window", Windows.Describe(new IntPtr(Json.Num(m, "hwnd", 0)), false));break;+ case "running":+ reply = Running(m);+ break;case "launch":reply = LaunchWarm(m) ?? Launch(m);break;@@ -280,6 +300,51 @@ namespace WildOS.Guest}}+ // When each program was last started, kept beside the session's log:+ // a program started through Remote Desktop's own request (StartOnce,+ // a process of its own) and one started here both leave it, so+ // "running" can say a program started and has already ended.+ static string StartedFile(string path)+ {+ return Path.Combine(Path.GetDirectoryName(SessionLog), "started-" + Path.GetFileNameWithoutExtension(path ?? "").ToLowerInvariant());+ }++ static void Started(string path)+ {+ try { File.WriteAllText(StartedFile(path), DateTime.UtcNow.Ticks.ToString()); }+ catch (Exception) { }+ }++ static bool StartedSince(string path, DateTime since)+ {+ try { return new DateTime(long.Parse(File.ReadAllText(StartedFile(path))), DateTimeKind.Utc) >= since; }+ catch (Exception) { return false; }+ }++ // Whether a program started since a moment (milliseconds since 1970,+ // UTC) is still running in this session: by its file name, so a+ // launcher that hands over to the real program of the same name+ // (System32's notepad.exe, an app alias) still counts.+ static Dictionary<string, object> Running(Dictionary<string, object> m)+ {+ string stem = Path.GetFileNameWithoutExtension(Json.Str(m, "path") ?? "");+ DateTime since = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(Json.Num(m, "since", 0)).AddSeconds(-2);+ int session = Process.GetCurrentProcess().SessionId;+ long count = 0;+ if (stem.Length > 0)+ {+ foreach (var p in Process.GetProcessesByName(stem))+ {+ try+ {+ if (p.SessionId == session && p.StartTime.ToUniversalTime() >= since) count++;+ }+ catch (Exception) { }+ }+ }+ return Message("running", "running", count > 0, "count", count, "started", StartedSince(Json.Str(m, "path"), since));+ }+static Dictionary<string, object> Launch(Dictionary<string, object> m){string path = Json.Str(m, "path");@@ -304,6 +369,7 @@ namespace WildOS.Guesttry{var p = Process.Start(start);+ Started(path);return Message("launched", "pid", p == null ? 0L : (long)p.Id, "warm", false);}catch (Win32Exception e)diff --git a/packages/wildos-winmode/guest/wild-guest/Warm.cs b/packages/wildos-winmode/guest/wild-guest/Warm.csindex 9e3f89e..d7d6ef0 100644--- a/packages/wildos-winmode/guest/wild-guest/Warm.cs+++ b/packages/wildos-winmode/guest/wild-guest/Warm.cs@@ -155,10 +155,14 @@ namespace WildOS.Guest}// Not while the session has just started or someone has just opened- // something: a warm app must never slow down a real launch.+ // something: a warm app must never slow down a real launch. Nor in a+ // session nobody has used yet (Wild OS signs in ahead of time, and+ // the first app the person asks for must have Windows to itself):+ // only once one of their apps is on screen.void Refill(){if ((DateTime.UtcNow - created).TotalSeconds < 20 || (DateTime.UtcNow - lastLaunch).TotalSeconds < 15) return;+ if (!AnyAppOnScreen()) return;warm.RemoveAll(e => !Alive(e));int count = 0;foreach (var app in wanted)@@ -201,7 +205,11 @@ namespace WildOS.Guestif (!officeProgIds.TryGetValue(Stem(path), out progId)) return null;Type t = Type.GetTypeFromProgID(progId);if (t == null) return null;- return new Entry { Path = path, Id = id ?? Stem(path), Office = Activator.CreateInstance(t) };+ var entry = new Entry { Path = path, Id = id ?? Stem(path), Office = Activator.CreateInstance(t) };+ // It loads in the background: whatever the person opens next+ // comes first. Taken, it gets its normal share back.+ SetPriority(Stem(path), System.Diagnostics.ProcessPriorityClass.BelowNormal);+ return entry;}bool Alive(Entry e)@@ -217,6 +225,28 @@ namespace WildOS.Guest}}+ static void SetPriority(string stem, System.Diagnostics.ProcessPriorityClass priority)+ {+ int session = System.Diagnostics.Process.GetCurrentProcess().SessionId;+ foreach (var p in System.Diagnostics.Process.GetProcessesByName(stem))+ {+ try+ {+ if (p.SessionId == session) p.PriorityClass = priority;+ }+ catch (Exception) { }+ }+ }++ static bool AnyAppOnScreen()+ {+ foreach (Dictionary<string, object> w in Windows.List())+ {+ if (!(bool)w["tool"] && (long)w["owner"] == 0) return true;+ }+ return false;+ }+static bool VisiblyRunning(string path){foreach (Dictionary<string, object> w in Windows.List())@@ -235,6 +265,7 @@ namespace WildOS.Guestvar reply = new Dictionary<string, object>();reply["type"] = "launched";reply["warm"] = true;+ SetPriority(Stem(path), System.Diagnostics.ProcessPriorityClass.Normal);ShowOffice(entry.Office, Stem(path), args);reply["pid"] = 0L;return reply;diff --git a/packages/wildos-winmode/guest/wild-guest/Windows.cs b/packages/wildos-winmode/guest/wild-guest/Windows.csindex d5481fa..55d7d31 100644--- a/packages/wildos-winmode/guest/wild-guest/Windows.cs+++ b/packages/wildos-winmode/guest/wild-guest/Windows.cs@@ -18,6 +18,16 @@ namespace WildOS.Guest"shellexperiencehost", "startmenuexperiencehost", "searchhost", "lockapp", "applicationframehost", "shellappruntime",};+ // Except these windows of theirs, which the person did open: a folder+ // window, a copy in progress and Explorer's dialogs, and a packaged+ // app's frame (Calculator, Settings; a suspended one is cloaked and+ // left out already). Counted as apps, Windows is never paused under+ // them.+ static readonly List<string> openedClasses = new List<string>+ {+ "CabinetWClass", "OperationStatusWindow", "#32770", "ApplicationFrameWindow",+ };+public static List<object> List(){var result = new List<object>();@@ -49,13 +59,14 @@ namespace WildOS.GuestNative.GetWindowThreadProcessId(hwnd, out pid);string image = ImagePath(pid);string app = image == null ? "" : Path.GetFileNameWithoutExtension(image).ToLowerInvariant();- if (filter && shell.Contains(app)) return null;+ var cls = new StringBuilder(256);+ Native.GetClassName(hwnd, cls, cls.Capacity);+ if (filter && shell.Contains(app)+ && !((app == "explorer" || app == "applicationframehost") && openedClasses.Contains(cls.ToString()))) return null;int length = Native.GetWindowTextLength(hwnd);var title = new StringBuilder(Math.Max(length + 1, 1));Native.GetWindowText(hwnd, title, title.Capacity);- var cls = new StringBuilder(256);- Native.GetClassName(hwnd, cls, cls.Capacity);var w = new Dictionary<string, object>();w["hwnd"] = hwnd.ToInt64();diff --git a/packages/wildos-winmode/setup/qml/Main.qml b/packages/wildos-winmode/setup/qml/Main.qmlindex c7af519..36f4f55 100644--- a/packages/wildos-winmode/setup/qml/Main.qml+++ b/packages/wildos-winmode/setup/qml/Main.qml@@ -133,6 +133,20 @@ UI.AppWindow {}}+ // Closing is always possible until setup starts; from then on the+ // setup and ready steps have their own buttons, since closing no longer+ // stops what is under way.+ UI.IconButton {+ anchors.top: parent.top+ anchors.right: parent.right+ anchors.topMargin: 14+ anchors.rightMargin: 14+ visible: window.page === "check" || window.page === "licence" || window.page === "options"+ iconName: "close"+ tip: "Close"+ onClicked: window.close()+ }+T.Popup {id: problemPopupparent: T.Overlay.overlay@@ -154,6 +168,7 @@ UI.AppWindow {kind: window.problemreceived: (Setup.status.problem || {}).received || 0failure: window.startError.length > 0 ? window.startError : ((Setup.status.problem || {}).text || "")+ detail: window.startError.length > 0 ? "" : ((Setup.status.problem || {}).detail || "")onDismissed: problemPopup.close()onRetry: {if (window.startError.length > 0 || Setup.status.state === "failed") {diff --git a/packages/wildos-winmode/setup/qml/Page.qml b/packages/wildos-winmode/setup/qml/Page.qmlindex 756e327..15d81f5 100644--- a/packages/wildos-winmode/setup/qml/Page.qml+++ b/packages/wildos-winmode/setup/qml/Page.qml@@ -1,5 +1,6 @@import QtQuickimport QtQuick.Layouts+import QtQuick.Templates as Timport WildOS.UI as UI// One step of setup: 36 / 40 padding, a 28px title over a 14px line, the@@ -63,15 +64,26 @@ Item {}}- ColumnLayout {- id: body+ // The step's content scrolls when it is taller than the room above+ // the footer, so a longer step never pushes its buttons out of the+ // window.+ Flickable {+ id: scrollerLayout.fillWidth: true+ Layout.fillHeight: trueLayout.topMargin: page.spacing- spacing: page.spacing- }+ Layout.rightMargin: -14+ contentWidth: width+ contentHeight: body.implicitHeight + 16+ clip: true+ boundsBehavior: Flickable.StopAtBounds+ T.ScrollBar.vertical: UI.ScrollBar {}- Item {- Layout.fillHeight: true+ ColumnLayout {+ id: body+ width: scroller.width - 14+ spacing: page.spacing+ }}Item {diff --git a/packages/wildos-winmode/setup/qml/ProblemCard.qml b/packages/wildos-winmode/setup/qml/ProblemCard.qmlindex abc8f15..4b036fc 100644--- a/packages/wildos-winmode/setup/qml/ProblemCard.qml+++ b/packages/wildos-winmode/setup/qml/ProblemCard.qml@@ -15,6 +15,8 @@ Item {property string kindproperty real received: 0property string failure+ // An unexpected error's own words, for reporting it.+ property string detail// Over the setup window there is no compositor blur behind a popup, so// the card is drawn solid there; on the wallpaper it is glass.property bool solid: false@@ -27,7 +29,7 @@ Item {Accessible.name: title.textfunction gb(bytes) {- return (bytes / 1e9).toLocaleString(Qt.locale("en_GB"), "f", 1) + " GB";+ return (bytes / 1e9).toLocaleString(Qt.locale(), "f", 1) + " GB";}Rectangle {@@ -119,6 +121,16 @@ Item {}}+ UI.Label {+ Layout.fillWidth: true+ visible: card.kind === "failed" && card.detail.length > 0+ text: "Details: " + card.detail+ size: 12+ color: UI.Style.inkAlpha(0.66, 0.6)+ wrapMode: Text.Wrap+ elide: Text.ElideNone+ }+UI.Label {Layout.fillWidth: truevisible: card.kind === "download" && Setup.internet === "metered"diff --git a/packages/wildos-winmode/setup/qml/StepCheck.qml b/packages/wildos-winmode/setup/qml/StepCheck.qmlindex 2fbeef8..4d4d427 100644--- a/packages/wildos-winmode/setup/qml/StepCheck.qml+++ b/packages/wildos-winmode/setup/qml/StepCheck.qml@@ -40,7 +40,7 @@ Page {return Setup.edition === "pro" ? "Windows 11 Pro is built into this PC, so Windows mode uses it. There is nothing to buy.": Setup.edition === "home" ? "Windows 11 Home is built into this PC, so Windows mode uses it. There is nothing to buy.": "A Windows licence is built into this PC, so Windows mode uses it. Windows confirms whether it's Home or Pro while it sets itself up.";- case "inuse": return "Its licence covers one copy of Windows at a time, so Windows mode needs a product key of its own.";+ case "inuse": return "Its licence is built into this PC. On the next step, choose to use it for Windows mode as well or add a product key.";case "error": return "You can still carry on and enter a product key.";default: return "You can enter a product key on the next step.";}diff --git a/packages/wildos-winmode/setup/qml/StepLicence.qml b/packages/wildos-winmode/setup/qml/StepLicence.qmlindex ea17640..b763612 100644--- a/packages/wildos-winmode/setup/qml/StepLicence.qml+++ b/packages/wildos-winmode/setup/qml/StepLicence.qml@@ -27,7 +27,7 @@ Page {tone: "warning"title: page.home ? "This PC came with Windows 11 Home" : page.kind === "inuse" ? "Windows is still installed on this PC" : "No Windows licence built into this PC"text: page.home ? "Windows mode needs Windows 11 Pro, so this licence can't activate it. Set it up without activating, or with a Pro key."- : page.kind === "inuse" ? "Its licence covers one copy of Windows at a time, and that copy is still on this PC. A key from another licence works for Windows mode."+ : page.kind === "inuse" ? "Its licence is built into this PC. Windows mode can use it as well, or a key from another licence.": "Common on self-built PCs and older machines. A key from a previous PC often still works."}@@ -73,6 +73,16 @@ Page {}}+ // The built-in licence while Windows is still installed: the+ // person's call. The installed Windows and its licence are left as+ // they are; Windows mode activates with the same key.+ RadioCard {+ id: thisPc+ visible: page.kind === "inuse" && Setup.edition !== "home"+ title: "Use this PC's licence"+ description: "Windows mode activates with the licence built into this PC. The Windows already installed isn't changed. Microsoft's terms count each copy of Windows, so you may want to remove the old one later."+ }+RadioCard {id: noKeytitle: "Continue without activating"@@ -98,6 +108,8 @@ Page {onClicked: {if (skipNone.checked) {page.skipped();+ } else if (thisPc.checked && thisPc.visible) {+ page.chosen("firmware", "", "");} else if (noKey.checked) {page.chosen("none", "", "");} else {diff --git a/packages/wildos-winmode/setup/qml/StepOptions.qml b/packages/wildos-winmode/setup/qml/StepOptions.qmlindex 1737394..0f7c5e0 100644--- a/packages/wildos-winmode/setup/qml/StepOptions.qml+++ b/packages/wildos-winmode/setup/qml/StepOptions.qml@@ -12,10 +12,13 @@ Page {signal back()signal setUp()+ // Windows' own licence page is skipped by the answer file, so this is+ // where the terms are accepted, and nothing starts until they are.+ property bool termsAccepted: false+title: "Choose options"text: "These suit most people. You can change any of them later in Settings, under Windows apps."- note: (Setup.office ? "About 30 GB in total, including Microsoft 365." : "About 26 GB in total.")- + " Setting up accepts Microsoft's licence terms."+ note: Setup.office ? "About 30 GB in total, including Microsoft 365." : "About 26 GB in total."UI.Card {Layout.fillWidth: true@@ -125,6 +128,20 @@ Page {onActivated: Setup.memoryGb = currentValue}}++ UI.ListRow {+ visible: Setup.hyperThreadingAvailable+ title: "Use every processor thread"+ description: "Faster heavy apps, one less CPU-flaw protection for the whole PC. Needs a restart."+ interactive: true+ onClicked: Setup.hyperThreading = !Setup.hyperThreading++ leading: UI.CheckBox {+ checked: Setup.hyperThreading+ Accessible.name: "Use every processor thread"+ onToggled: Setup.hyperThreading = checked+ }+ }}}}@@ -168,6 +185,28 @@ Page {}}+ UI.Card {+ Layout.fillWidth: true++ Column {+ width: parent.width++ UI.ListRow {+ title: "I accept Microsoft's licence terms"+ description: Setup.office+ ? "Windows and Microsoft 365 are installed under Microsoft's licence terms."+ : "Windows is installed under Microsoft's licence terms."+ interactive: true+ onClicked: page.termsAccepted = !page.termsAccepted+ leading: UI.CheckBox {+ checked: page.termsAccepted+ Accessible.name: "I accept Microsoft's licence terms"+ onToggled: page.termsAccepted = checked+ }+ }+ }+ }+buttons: [UI.LinkButton {text: "Read the terms"@@ -181,7 +220,7 @@ Page {UI.Button {kind: "primary"text: "Set up"- enabled: Setup.spaceOk+ enabled: Setup.spaceOk && page.termsAcceptedonClicked: page.setUp()}]diff --git a/packages/wildos-winmode/setup/qml/StepReady.qml b/packages/wildos-winmode/setup/qml/StepReady.qmlindex 45fbca1..5c886d9 100644--- a/packages/wildos-winmode/setup/qml/StepReady.qml+++ b/packages/wildos-winmode/setup/qml/StepReady.qml@@ -123,6 +123,13 @@ Page {}}+ Banner {+ visible: Setup.hyperThreadingNeedsRestart+ iconName: "restart"+ title: "Restart to use every processor thread"+ text: "Windows apps get the extra speed after the PC restarts."+ }+Banner {visible: page.options.office === trueiconName: "account"diff --git a/packages/wildos-winmode/setup/src/pccheck.cpp b/packages/wildos-winmode/setup/src/pccheck.cppindex e4d1044..02a9031 100644--- a/packages/wildos-winmode/setup/src/pccheck.cpp+++ b/packages/wildos-winmode/setup/src/pccheck.cpp@@ -106,7 +106,7 @@ qint64 freeBytes(const QString &path)QString sizeLabel(qint64 bytes){- const QLocale locale(QLocale::English, QLocale::UnitedKingdom);+ const QLocale locale = QLocale::system();const double gb = double(bytes) / 1e9;if (gb >= 10) {return QStringLiteral("%1 GB").arg(qRound64(gb));diff --git a/packages/wildos-winmode/setup/src/setupapp.cpp b/packages/wildos-winmode/setup/src/setupapp.cppindex 6cd5944..cbfc605 100644--- a/packages/wildos-winmode/setup/src/setupapp.cpp+++ b/packages/wildos-winmode/setup/src/setupapp.cpp@@ -322,11 +322,47 @@ QString SetupApp::normaliseKey(const QString &typed) constreturn Licence::normaliseKey(typed);}+namespace+{+const QString cpuThreadsHelper = QStringLiteral("/usr/libexec/wildos/settings-cpu-threads");++QByteArray readSmt(const char *name)+{+ QFile file(QStringLiteral("/sys/devices/system/cpu/smt/") + QLatin1String(name));+ return file.open(QIODevice::ReadOnly) ? file.readAll().trimmed() : QByteArray();+}+}++// Offered only on a processor with two threads per core, while it is off, and+// not at Strict or Maximum protection, which keep it off.+bool SetupApp::hyperThreadingAvailable() const+{+ const QByteArray control = readSmt("control");+ QFile levelFile(QStringLiteral("/etc/wildos/protection-level"));+ const QByteArray level = levelFile.open(QIODevice::ReadOnly) ? levelFile.readAll().trimmed() : QByteArray();+ return QFile::exists(cpuThreadsHelper) && !control.isEmpty() && control != "notsupported" && control != "notimplemented"+ && !QFile::exists(QStringLiteral("/etc/wildos/cpu-threads")) && level != "strict" && level != "maximum";+}++bool SetupApp::hyperThreadingNeedsRestart() const+{+ return QFile::exists(QStringLiteral("/etc/wildos/cpu-threads")) && readSmt("active") != "1";+}+QString SetupApp::startSetup(const QString &licence, const QString &key, const QString &homeChoice){if (preview()) {return {};}+ // A boot option, so it needs the administrator; setup goes ahead either way.+ if (m_hyperThreading && hyperThreadingAvailable()) {+ auto process = new QProcess(this);+ connect(process, &QProcess::finished, this, [this, process] {+ process->deleteLater();+ Q_EMIT optionsChanged();+ });+ process->start(QStringLiteral("pkexec"), {cpuThreadsHelper, QStringLiteral("on")});+ }Options o = Options::load();o.office = m_office;o.officePlan = m_officePlan;diff --git a/packages/wildos-winmode/setup/src/setupapp.h b/packages/wildos-winmode/setup/src/setupapp.hindex c8d3ce3..3affa51 100644--- a/packages/wildos-winmode/setup/src/setupapp.h+++ b/packages/wildos-winmode/setup/src/setupapp.h@@ -42,6 +42,12 @@ class SetupApp : public QObjectQ_PROPERTY(QString whenIdle MEMBER m_whenIdle NOTIFY optionsChanged)Q_PROPERTY(int memoryGb MEMBER m_memoryGb NOTIFY optionsChanged)Q_PROPERTY(QStringList folders READ folders NOTIFY optionsChanged)+ // Hyper-threading is off in Wild OS; choosing it here turns it on from the+ // next start-up through Settings' helper, which asks for the password.+ Q_PROPERTY(bool hyperThreading MEMBER m_hyperThreading NOTIFY optionsChanged)+ Q_PROPERTY(bool hyperThreadingAvailable READ hyperThreadingAvailable CONSTANT)+ // True once the helper has turned it on and only a restart is left.+ Q_PROPERTY(bool hyperThreadingNeedsRestart READ hyperThreadingNeedsRestart NOTIFY optionsChanged)// The daemon's Status, or empty while it has not answered.Q_PROPERTY(QVariantMap status READ status NOTIFY statusChanged)@@ -58,6 +64,8 @@ public:QString memoryState() const { return m_memoryState; }QString freeLabel() const { return m_freeLabel; }QString needLabel() const;+ bool hyperThreadingAvailable() const;+ bool hyperThreadingNeedsRestart() const;bool spaceOk() const;QString internet() const { return m_internet; }QString licence() const { return m_licence; }@@ -127,6 +135,7 @@ private:QString m_whenIdle = QStringLiteral("automatic");int m_memoryGb = 4;QStringList m_folders;+ bool m_hyperThreading = false;QVariantMap m_status;QDBusInterface *m_daemon = nullptr;diff --git a/packages/wildos-winmode/tests/test_winmode.py b/packages/wildos-winmode/tests/test_winmode.pyindex 5c9741e..09fc535 100644--- a/packages/wildos-winmode/tests/test_winmode.py+++ b/packages/wildos-winmode/tests/test_winmode.py@@ -3,6 +3,7 @@ import ioimport jsonimport osimport tempfile+import timeimport unittestfrom winmode import compat, firewall, guestlink, launchers, lifecycle, paths, rdp, theme, windows@@ -143,6 +144,25 @@ class Launchers(unittest.TestCase):self.assertTrue(launchers.is_shell(r"C:\Windows\System32\rdpinit.exe"))self.assertFalse(launchers.is_shell(r"C:\X\WINWORD.EXE"))+ def test_open_windows_for_the_taskbar_panel(self):+ reg = {"word": {"name": "Word", "target": r"C:\O\WINWORD.EXE"}}+ ws = [{"image": r"C:\O\WINWORD.EXE", "title": "Quarterly report.docx - Word", "owner": 0},+ {"image": r"C:\O\WINWORD.EXE", "title": "Save As", "owner": 4242},+ {"image": r"C:\Windows\System32\rdpinit.exe", "title": "", "owner": 0},+ {"image": r"C:\Tools\notepad.exe", "title": "Notepad", "owner": 0}]+ self.assertEqual(launchers.open_windows(ws, reg), [+ {"id": "word", "name": "Word", "icon": "wildos-winmode-word", "title": "Quarterly report.docx", "installed": True},+ {"id": "notepad", "name": "Notepad", "icon": "wildos-windows-app", "title": "", "installed": False}])+ self.assertEqual(launchers.document_title("Budget 2027.xlsx - Excel", "Excel"), "Budget 2027.xlsx")+ self.assertEqual(launchers.document_title("Report - Draft - Word", "Microsoft Word"), "Report - Draft")+ self.assertEqual(launchers.document_title("Pay - Slip", "Invoices"), "Pay - Slip")++ def test_last_app(self):+ reg = {"word": {}, "excel": {}}+ self.assertEqual(launchers.last_app(reg, "excel", {"word": 9}), "excel")+ self.assertEqual(launchers.last_app(reg, "gone", {"word": 9, "excel": 2, "gone": 50}), "word")+ self.assertIsNone(launchers.last_app(reg, None, {}))+def test_write_all_makes_and_removes_entries(self):reg = launchers.write_all([{"name": "Word", "target": r"C:\O\WINWORD.EXE"}, {"name": "Old", "target": r"C:\O\old.exe"}])apps = os.path.join(self.dir, "data", "applications")@@ -232,6 +252,230 @@ class RemoteApp(unittest.TestCase):self.assertEqual(app.count(","), 2)+NL = chr(10)+++class NativeClient(unittest.TestCase):+ """wildos-rdp, Wild OS's own RemoteApp client, and its fallback."""++ def setUp(self):+ self.dir = tempfile.mkdtemp()+ self.client = os.path.join(self.dir, "wildos-rdp")+ # Stands in for the client: keeps its arguments and what it is given+ # on standard input.+ with open(self.client, "w") as f:+ f.write('#!/bin/sh\nprintf "%s\\n" "$@" > "$0.argv"\ncat > "$0.stdin"\n')+ os.chmod(self.client, 0o755)++ def test_the_own_client_unless_missing_or_asked_not_to(self):+ self.assertEqual(rdp.client_program("auto", native=self.client), self.client)+ self.assertEqual(rdp.client_program("xfreerdp3", native=self.client), "xfreerdp3")+ self.assertEqual(rdp.client_program("auto", native=os.path.join(self.dir, "missing")), "xfreerdp3")++ def test_the_desktop_opens_in_xfreerdp3_unless_remote_is_asked_for(self):+ remote = os.path.join(self.dir, "wildos-remote")+ with open(remote, "w") as f:+ f.write("#!/bin/sh\n")+ os.chmod(remote, 0o755)+ self.assertEqual(rdp.desktop_client("xfreerdp3", remote=remote), "xfreerdp3")+ self.assertEqual(rdp.desktop_client("remote", remote=remote), remote)+ self.assertEqual(rdp.desktop_client("remote", remote=os.path.join(self.dir, "missing")), "xfreerdp3")++ def test_loading_arguments_are_one_line_each(self):+ args = rdp.loading_arguments("wildos-winmode-word", "Word\n/drive:all,/", "wildos-winmode-word", "Slow, really",+ r"C:\O\WINWORD.EXE")+ self.assertEqual(args[:2], ["--app-id", "wildos-winmode-word"])+ self.assertTrue(all("\n" not in a for a in args))+ # The name is the value of --title, never an argument of its own.+ self.assertEqual(args[args.index("--title") + 1], "Word /drive:all,/")+ self.assertEqual(args[args.index("--reason") + 1], "Slow, really")+ # The program its first window is matched by.+ self.assertEqual(args[-2:], ["--program", r"C:\O\WINWORD.EXE"])++ def wait(self, conn):+ conn.proc.wait(5)++ def test_preparing_a_session_signs_in_only(self):+ args = rdp.prepare_arguments("192.168.207.10", 3389, "wild", "PC", drive="/srv/share")+ # It must never take the session back from the connection an app+ # opens with.+ self.assertNotIn("+auto-reconnect", args)+ self.assertIn("/drive:wildos,/srv/share", args)+ self.assertFalse(any("secret" in a for a in args))+ ended = []+ proc = rdp.prepare_session(args, "secret", os.path.join(self.dir, "log", "p.log"), ended.append, native=self.client)+ proc.wait(5)+ argv = read(self.client + ".argv").split(NL)+ self.assertEqual(argv[:2], ["--prepare-session", "/args-from:stdin"])+ self.assertNotIn("secret", read(self.client + ".argv"))+ self.assertEqual(read(self.client + ".stdin").splitlines()[-1], "/p:secret")++ def test_spawned_early_then_given_the_connection(self):+ changes = []+ conn = rdp.Connection(changes.append, lambda: None, os.path.join(self.dir, "log", "c.log"))+ conn.native_client = self.client+ self.assertTrue(conn.spawn("wildos-winmode-word", "Word", "wildos-winmode-word"))+ self.assertFalse(conn.open)+ self.assertTrue(conn.running)+ self.assertFalse(conn.spawn("x", "y", "z"))+ conn.start(["/v:192.168.207.10:3389", "/u:wild"], "secret")+ self.assertTrue(changes == [True])+ self.wait(conn)+ argv = read(self.client + ".argv").split("\n")+ self.assertIn("--app-id", argv)+ self.assertEqual(argv[-2], "/args-from:stdin")+ self.assertNotIn("secret", read(self.client + ".argv"))+ lines = read(self.client + ".stdin").splitlines()+ self.assertEqual(lines, ["/v:192.168.207.10:3389", "/u:wild", "/p:secret"])++ def test_the_connection_before_keeps_its_log(self):+ path = os.path.join(self.dir, "log", "c.log")+ conn = rdp.Connection(lambda o: None, lambda: None, path)+ conn.native_client = self.client+ conn.spawn("a", "A", "")+ conn.abandon()+ self.wait(conn)+ with open(path, "a") as f:+ f.write("why the first one ended\n")+ conn.spawn("b", "B", "")+ conn.abandon()+ self.wait(conn)+ self.assertIn("why the first one ended", read(path + ".1"))+ self.assertNotIn("why the first one ended", read(path))++ def test_abandoned_before_connecting(self):+ conn = rdp.Connection(lambda o: None, lambda: None, os.path.join(self.dir, "log", "c.log"))+ conn.native_client = self.client+ conn.spawn("wildos-winmode-word", "Word", "")+ conn.abandon()+ self.wait(conn)+ self.assertEqual(read(self.client + ".stdin"), "")+ self.assertFalse(conn.open)++ def test_xfreerdp_is_never_started_early(self):+ conn = rdp.Connection(lambda o: None, lambda: None, os.path.join(self.dir, "c.log"), program="xfreerdp3")+ self.assertFalse(conn.native)+ self.assertFalse(conn.spawn("a", "b", "c"))+ self.assertIsNone(conn.proc)++ def test_slow_reasons_say_only_what_is_known(self):+ from winmode import agent+ self.assertIn("starting from the beginning", agent.slow_reason("Stopped", "Word"))+ self.assertIn("Word will open", agent.slow_reason("Saved", "Word"))+ self.assertEqual(agent.slow_reason("Running", "Word"), "")+ for text in (agent.slow_reason("Stopped", "Word"), agent.slow_reason("Saved", "Word")):+ # No technical words on screen, and no long dashes (the regex+ # escapes for U+2014 and U+2013).+ self.assertNotRegex(text, "VM|RDP|\\u2014|\\u2013")+++class Reliability(unittest.TestCase):+ """Opening and closing that must never hang."""++ def test_ending_a_stuck_program_names_only_that_process(self):+ from winmode import system+ script = system.end_program_script(4242, r"C:\Windows\System32\notepad.exe")+ self.assertIn("Get-Process -Id 4242", script)+ self.assertIn("SessionId -ne 0", script)+ self.assertIn(r"-ieq 'C:\Windows\System32\notepad.exe'", script)+ # A quote in the path cannot end the string early, curly ones too.+ script = system.end_program_script(4242, "C:\\a'b\u2019c.exe")+ self.assertIn("'C:\\a''b\u2019\u2019c.exe'", script)+ for pid, image in ((0, "x.exe"), (4, "x.exe"), ("x", "x.exe"), (100, ""), (100, "a\nb.exe")):+ self.assertIsNone(system.end_program_script(pid, image))++ def test_refreshing_the_menus_never_holds_the_agent(self):+ # kbuildsycoca6 can take seconds; the agent's main loop must go on+ # answering meanwhile.+ from unittest import mock+ from winmode import launchers+ slow = lambda *a, **k: time.sleep(2)+ with mock.patch.object(launchers.subprocess, "run", slow):+ t = time.monotonic()+ launchers.refresh_menus()+ self.assertLess(time.monotonic() - t, 0.5)++ def test_a_program_that_ends_before_its_window_ends_the_wait(self):+ from unittest import mock+ from winmode import agent+ a = self.bare_agent()+ a.watched, a.ended_launches, a.windows = [], [], []+ updates = []+ a.remote = type("Remote", (), {"update": lambda self, token, stage="": updates.append((token, stage))})()+ answers = []+ a.call_json = lambda method, args=None, signature=None, done=None, timeout=600: done(answers.pop(0))+ polls = []+ with mock.patch.object(agent.GLib, "timeout_add", lambda ms, fn: polls.append(fn)):+ a.watch_launch({"token": 7, "closed": False}, r"C:\Games\Voxel.exe", [], "MagicaVoxel", "voxel")+ poll = polls[0]+ # Not yet started: not running is no news.+ answers.append({"type": "running", "running": False})+ poll()+ answers.append({"type": "running", "running": True})+ poll()+ for _ in range(agent.LAUNCH_GONE_POLLS):+ answers.append({"type": "running", "running": False})+ poll()+ self.assertEqual(updates, [(7, "ended")])+ self.assertEqual(a.ended_launches[0]["name"], "MagicaVoxel")++ def test_try_again_opens_the_same_program_again(self):+ a = self.bare_agent()+ cancelled, launched = [], []+ a.remote = type("Remote", (), {"cancel": lambda self, token: cancelled.append(token)})()+ a.launch = lambda path, args, name, app_id, done: launched.append((path, args, name, app_id))+ # The client's own loading window (token 0 here, 1 to the client).+ a.ended_launches = [{"window": {"token": 0}, "path": "C:/Games/Voxel.exe", "args": ["-x"], "name": "MagicaVoxel",+ "app_id": "voxel"}]+ a.remote_retry(1)+ self.assertEqual(cancelled, [1])+ self.assertEqual(launched, [("C:/Games/Voxel.exe", ["-x"], "MagicaVoxel", "voxel")])+ self.assertEqual(a.ended_launches, [])++ def test_a_new_window_anywhere_stops_the_watch(self):+ from unittest import mock+ from winmode import agent+ a = self.bare_agent()+ a.watched, a.ended_launches, a.windows = [], [], [{"hwnd": 1}]+ a.remote = type("Remote", (), {"update": lambda self, token, stage="": self.fail("no update")})()+ polls = []+ with mock.patch.object(agent.GLib, "timeout_add", lambda ms, fn: polls.append(fn)):+ a.watch_launch({"token": 7, "closed": False}, r"C:\Windows\notepad.exe", [], "Notepad", "notepad")+ # A launcher handed over to a program of another name, whose window+ # came: no longer watched.+ a.windows.append({"hwnd": 2})+ self.assertFalse(polls[0]())+ self.assertEqual(a.watched, [])++ def bare_agent(self):+ from winmode import agent+ a = agent.Agent.__new__(agent.Agent)+ a.queue, a.waking, a.launches, a.windows, a.loading = [], False, {}, [], {}+ a.calls = []+ a.call_json = lambda method, args=None, signature=None, done=None, timeout=600: a.calls.append((method, done))+ a.app_window_stage = lambda app_id, stage: None+ return a++ def test_a_launch_waiting_for_a_session_that_ended_reconnects(self):+ # The last app closed just as this one opened: Windows signed the+ # session out and the connection ended. The launch must open a new+ # connection, not wait 90 s for a session nothing will bring.+ a = self.bare_agent()+ a.conn = type("Conn", (), {"running": False, "open": False})()+ done = []+ a.launch_in_session(r"C:\Windows\notepad.exe", [], "Notepad", "notepad", 0.0, done.append, {"from": "running"})+ self.assertEqual([c[0] for c in a.calls], ["Wake"])+ self.assertEqual(len(a.queue), 1)+ self.assertEqual(a.queue[0][2], "Notepad")+ self.assertEqual(done, [])++ def test_a_launch_in_a_live_session_goes_to_wild_guest(self):+ a = self.bare_agent()+ a.conn = type("Conn", (), {"running": True, "open": True})()+ a.launch_in_session(r"C:\Windows\notepad.exe", [], "Notepad", "notepad", 0.0, lambda m: None, {"from": "running"})+ self.assertEqual([c[0] for c in a.calls], ["Launch"])++class Theme(unittest.TestCase):def test_dark_and_accent(self):d = tempfile.mkdtemp()diff --git a/packages/wildos-winmode/winmode/agent.py b/packages/wildos-winmode/winmode/agent.pyindex 9bb19e4..8a317c9 100644--- a/packages/wildos-winmode/winmode/agent.py+++ b/packages/wildos-winmode/winmode/agent.py@@ -15,6 +15,7 @@ a sentence to show, or nothing.import jsonimport osimport shutil+import signalimport subprocessimport sysimport time@@ -85,7 +86,13 @@ NOT_YET = "This isn't available yet."# How long a launch waits for a new connection's session to be up.SESSION_WAIT = 90# Seconds after sign-in before Windows is started ahead of time.-PRESTART_DELAY = 120+PRESTART_DELAY = 45+# A launch is watched every 1.5 s for up to two minutes; its program gone+# on three polls in a row (4.5 s, longer than any launcher takes to hand+# over) with no new window means it ended before it opened.+LAUNCH_WATCH_MS = 1500+LAUNCH_WATCH_POLLS = 80+LAUNCH_GONE_POLLS = 3SECRET_ATTRS = ["service", "org.wildos.WindowsMode1", "account"]@@ -126,6 +133,18 @@ DEFAULT_WAKE = {}+def slow_reason(lifecycle, name):+ """Why opening an app is taking longer (board 9.13), from what the agent+ knows: how Windows was when the app was opened. Empty when nothing is+ known, and wildos-rdp says it plainly in its own words."""+ if lifecycle in ("Stopped", "NotInstalled", None):+ return (f"Windows mode is starting from the beginning, which takes longer than waking it. "+ f"{name} will open as soon as it's ready.")+ if lifecycle == "Saved":+ return f"Windows mode is being brought back from where it was saved. {name} will open as soon as it's ready."+ return ""++def launch_state(rec):"""The target a launch is held to (brief 5.5a): warm or cold when Windowswas paused or running, saved or stopped otherwise."""@@ -145,10 +164,21 @@ class Keyring:self.memory = {}self.tool = shutil.which("secret-tool")+ def usable(self):+ """Only a keyring that already exists. Asking KWallet for one that+ doesn't makes it ask the person to create one (the Blowfish or GPG+ dialog), which happens after an automatic first sign-in, when+ pam_kwallet had no password to make it with. Without one the+ password stays in memory and a new one is set next time."""+ if not self.tool:+ return False+ data = os.environ.get("XDG_DATA_HOME") or os.path.join(os.path.expanduser("~"), ".local", "share")+ return os.path.exists(os.path.join(data, "kwalletd", "kdewallet.kwl"))+def get(self, account):if account in self.memory:return self.memory[account]- if self.tool:+ if self.usable():try:p = subprocess.run([self.tool, "lookup", *SECRET_ATTRS, account], capture_output=True, text=True, timeout=10)if p.returncode == 0 and p.stdout:@@ -160,7 +190,7 @@ class Keyring:def put(self, account, password):self.memory[account] = password- if self.tool:+ if self.usable():try:subprocess.run([self.tool, "store", "--label", "Windows mode", *SECRET_ATTRS, account],input=password, text=True, capture_output=True, timeout=10)@@ -169,7 +199,7 @@ class Keyring:def forget(self, account):self.memory.pop(account, None)- if self.tool:+ if self.usable():try:subprocess.run([self.tool, "clear", *SECRET_ATTRS, account], capture_output=True, timeout=10)except (OSError, subprocess.TimeoutExpired):@@ -187,14 +217,21 @@ class Agent:self.host = {}self.windows = []self.queue = []+ # The sign-in-only connection after Windows starts ahead of time.+ self.preparing = Noneself.waking = Falseself.launches = {}self.last_launch = None+ self.last_app = Noneself.refreshed = False# Installers handed over by RunInstaller, by program name: once their# windows have all closed, Windows' Start menu is read again so the# new app gets its Start entry.self.installers = {}+ # An installer was run since the Start menu was last read. Some hand+ # over to a second program and close, so their own windows never+ # show; the menu is then read once every Windows app has closed.+ self.installed_since_refresh = Falseself.history = config.read_json(os.path.join(config.user_data_dir(), "history.json"), {}) or {}self.wake_times = config.read_json(os.path.join(config.user_data_dir(), "wake-times.json"), {}) or {}# The windows already open when the "Starting Windows" card went up.@@ -202,8 +239,21 @@ class Agent:self.starting_timer = Noneself.conn = rdp.Connection(self.connection_changed, self.auth_failed,os.path.join(config.user_data_dir(), "connection.log"))- self.desktop = rdp.Connection(lambda is_open: None, self.auth_failed,- os.path.join(config.user_data_dir(), "desktop.log"))+ # Anything installed from the whole Windows desktop gets its Start+ # entry once the desktop closes.+ self.desktop = rdp.Connection(self.desktop_changed, self.auth_failed,+ os.path.join(config.user_data_dir(), "desktop.log"), program=rdp.desktop_client())+ # wildos-rdp's windows for apps being opened, by token, and its+ # interface on the session bus.+ self.loading = {}+ self.remote = rdp.RemoteApp(session, on_window=self.remote_window, on_loading=self.remote_loading,+ on_details=self.remote_details, on_close_stalled=self.remote_close_stalled,+ on_retry=self.remote_retry)+ # Launches still waiting for their first window, watched for a+ # program that ends before it shows one.+ self.watched = []+ # Those whose program ended, for Try again.+ self.ended_launches = []self.export = dbusutil.Exported(session, config.OBJECT_PATH, XML, config.AGENT_INTERFACE, {"Status": (self.m_status, "s", False),"Launch": (self.m_launch, "s", False),@@ -241,9 +291,10 @@ class Agent:self.refresh_host_now()self.watch_theme()GLib.timeout_add_seconds(5, lambda: (self.push_warm(), False)[1])- # Two minutes after sign-in, once the desktop and its startup apps- # have settled, Windows is started ahead of time so the first- # Windows app opens from memory. The service declines on battery,+ # Shortly after sign-in, once the desktop and its startup apps have+ # settled, Windows is started ahead of time (with a small share of the+ # processor) and signed in to, so the first Windows app opens from+ # memory into a session that is ready. The service declines on battery,# without enough free memory, or when Windows is already up.GLib.timeout_add_seconds(PRESTART_DELAY, lambda: (self.prestart(), False)[1])@@ -251,8 +302,52 @@ class Agent:def done(reply):if isinstance(reply, GLib.Error):log("starting Windows ahead of time:", reply.message)+ return+ try:+ result = json.loads(reply or "{}")+ except ValueError:+ return+ if result.get("ok"):+ self.prepare_session()self.call("Prestart", done=done, timeout=600)+ def prepare_session(self):+ """Windows was started ahead of time: it is signed in to as well, and+ the session left disconnected, so the first app takes it over in a+ couple of seconds instead of waiting for Windows to sign in and start+ its shell (about three seconds more, measured). Only with wildos-rdp,+ and only while no connection is open or opening."""+ if not self.conn.native or self.conn.running or self.preparing is not None:+ return++ def go(creds):+ if not creds.get("password") or self.conn.running:+ return+ args = rdp.prepare_arguments(self.host.get("guest_address"), self.host.get("rdp_port", 3389), creds["account"],+ creds.get("domain", ""), drive=self.drive_folder())++ def ended(ok):+ self.preparing = None+ log("session prepared" if ok else "preparing the session didn't finish")+ try:+ self.preparing = rdp.prepare_session(args, creds["password"], os.path.join(config.user_data_dir(), "prepare.log"),+ ended, native=self.conn.native_client)+ except OSError as e:+ log("couldn't prepare the session:", e)+ if self.host.get("guest_address"):+ self.credentials(go)+ else:+ self.refresh_host(lambda: self.credentials(go) if self.host.get("guest_address") else None)++ def end_preparing(self):+ """A launch needs the session now: the sign-in-only connection ends+ (the session stays, disconnected) so it cannot hold it."""+ if self.preparing is not None and self.preparing.poll() is None:+ try:+ os.killpg(self.preparing.pid, signal.SIGTERM)+ except OSError:+ pass+# The system service.def call(self, method, args=None, signature=None, done=None, timeout=600):params = GLib.Variant(signature, args) if signature else None@@ -302,7 +397,7 @@ class Agent:if isinstance(st.get("windows"), list):self.windows = st["windows"]- def refresh_host(self):+ def refresh_host(self, then=None):def got(st):if isinstance(st, dict) and "state" in st:was = (self.host.get("setup") or {}).get("running")@@ -312,6 +407,8 @@ class Agent:if isinstance(st.get("windows"), list):self.set_windows(st["windows"])self.changed()+ if then:+ then()self.call_json("Status", done=got, timeout=10)def changed(self):@@ -334,6 +431,9 @@ class Agent:elif seen:del self.installers[stem]GLib.timeout_add_seconds(5, lambda: (self.m_refresh(None), False)[1])+ if self.installed_since_refresh and not any(self.app_for(w) != "" for w in ws):+ self.installed_since_refresh = False+ GLib.timeout_add_seconds(5, lambda: (self.m_refresh(None), False)[1])# The guest lists windows once a second, so a window it lists may# well be on screen already: the screen's own time is used when the# window has been seen there.@@ -371,6 +471,7 @@ class Agent:def count_launch(self, app_id):if app_id and app_id in self.registry:+ self.last_app = app_idself.history[app_id] = self.history.get(app_id, 0) + 1try:config.write_json(os.path.join(config.user_data_dir(), "history.json"), self.history)@@ -435,6 +536,10 @@ class Agent:def window_tagged(self, xid, handle, app_id, seen_at):self.window_appeared(app_id, handle, seen_at or time.monotonic(), "window on screen")+ def desktop_changed(self, is_open):+ if not is_open:+ GLib.timeout_add_seconds(5, lambda: (self.m_refresh(None), False)[1])+def connection_changed(self, is_open):log("connection", "open" if is_open else "closed")self.call("ConnectionChanged", (is_open,), "(b)")@@ -442,7 +547,7 @@ class Agent:def auth_failed(self):log("Windows refused the stored password; a new one is set next time")- self.keyring.forget(self.host.get("account", "wild"))+ dbusutil.in_thread(self.keyring.forget, self.host.get("account", "wild"))def guest_paths(self, files):mapping = paths.folder_map(self.host.get("folders", []), self.host.get("share_root", ""))@@ -453,17 +558,85 @@ class Agent:"""Starts a Windows program. Windows is woken first (resumed,restored or started; immediate when it is running). With theconnection open the program starts inside the session through- wild-guest; otherwise the connection opens with it."""+ wild-guest; otherwise the connection opens with it.++ With wildos-rdp the app's window is on screen at once, with the+ loading W, and becomes the app when Windows shows it (boards 9.11 to+ 9.13); the "Starting Windows" card is then not needed."""started = time.monotonic()- self.show_starting(name, app_id)+ self.end_preparing()+ window = self.open_app_window(app_id, name, path)+ if not window:+ self.show_starting(name, app_id)finish = donedef done(message):if message:self.hide_starting()+ self.close_app_window(window)finish(message)self.queue.append((path, args, name, app_id, started, done))+ self.wake_then_launch()+ if window:+ self.watch_launch(window, path, args, name, app_id)++ def watch_launch(self, window, path, args, name, app_id):+ """A program that ends before it shows a window (it crashed, or gave+ up) would leave its loading window saying it is still opening. Once+ the program has been seen running in Windows (or wild-guest says it+ started it), its being gone for a few seconds with no new window+ anywhere ends the wait: the loading window says it closed before it+ opened, and offers Try again."""+ w = {"window": window, "path": path, "args": args, "name": name, "app_id": app_id,+ "since_ms": int(time.time() * 1000), "seen": False, "gone": 0, "polls": 0,+ "windows": {x.get("hwnd") for x in self.windows}}+ self.watched.append(w)++ def poll():+ if w not in self.watched:+ return False+ w["polls"] += 1+ new_window = any(x.get("hwnd") not in w["windows"] for x in self.windows)+ if window["closed"] or new_window or w["polls"] > LAUNCH_WATCH_POLLS:+ self.watched.remove(w)+ return False++ def answered(reply):+ if w not in self.watched or not isinstance(reply, dict) or reply.get("type") != "running":+ return+ if reply.get("running"):+ w["seen"], w["gone"] = True, 0+ return+ # Started and already gone before it was ever seen running+ # (wild-guest notes every start).+ if reply.get("started"):+ w["seen"] = True+ if w["seen"]:+ w["gone"] += 1+ if w["gone"] >= LAUNCH_GONE_POLLS:+ self.watched.remove(w)+ self.ended_launches = self.ended_launches[-4:] + [w]+ log(name, "ended before it showed a window")+ self.remote.update(window["token"], "ended")+ self.call_json("GuestRequest", (json.dumps({"type": "running", "path": path, "since": w["since_ms"]}),), "(s)",+ answered, timeout=10)+ return True+ GLib.timeout_add(LAUNCH_WATCH_MS, poll)++ def remote_retry(self, token):+ """Try again on a loading window whose program ended: the same launch,+ in a new loading window."""+ for w in list(self.ended_launches):+ if w["window"]["token"] == token or (token and not w["window"]["token"]):+ self.ended_launches.remove(w)+ self.remote.cancel(token)+ self.launch(w["path"], w["args"], w["name"], w["app_id"], lambda message: None)+ return++ def wake_then_launch(self):+ """Wakes Windows, then starts every queued launch: inside the+ session when the connection is open, or with a new connection."""if self.waking:returnself.waking = True@@ -481,10 +654,94 @@ class Agent:self.launch_in_session(*item, wake=reply)returnself.queue = pending- self.credentials(lambda creds: self.open_connection(creds, reply))+ # Where Windows is comes from the service; an agent that started+ # before it could answer asks again first, rather than connect+ # to nowhere.+ def connect():+ self.credentials(lambda creds: self.open_connection(creds, reply))+ if self.host.get("guest_address"):+ connect()+ else:+ self.refresh_host(connect)self.call_json("Wake", done=woke)+ def open_app_window(self, app_id, name, program=""):+ """wildos-rdp's window for an app being opened: through the running+ client when the connection is open, or by starting the client now+ when it is not, so the window is there while Windows wakes. Returns+ what close_app_window() needs, or None with xfreerdp3."""+ if not self.conn.native:+ return None+ known = app_id in self.registry+ desktop_id = launchers.PREFIX + app_id if known else ""+ icon = launchers.PREFIX + app_id if known else ""+ window = {"token": 0, "spawned": False, "closed": False, "app": app_id}+ if self.conn.open:+ # Board 9.12: an app that opens within half a second of the click+ # (Windows awake, the app warm) opens without the loader.+ warm = self.host.get("state") == "Running"++ def got(token):+ window["token"] = token or 0+ if window["closed"]:+ self.remote.cancel(window["token"])+ elif window["token"]:+ self.loading[window["token"]] = window+ self.remote.prepare(desktop_id, name, icon, program, 500 if warm else 0, got)+ elif not self.conn.running:+ reason = slow_reason(self.host.get("state"), name)+ window["spawned"] = self.conn.spawn(desktop_id, name, icon, reason, program)+ return window++ def close_app_window(self, window):+ if not window or window["closed"]:+ return+ window["closed"] = True+ if window["spawned"]:+ self.conn.abandon()+ self.remote.cancel(window["token"])++ def app_window_stage(self, app_id, stage):+ """News for the app's window: "almost" once its process is up."""+ for token, window in list(self.loading.items()):+ if window["app"] == app_id and not window["closed"]:+ self.remote.update(token, stage)++ def remote_window(self, window_id, title):+ """A window from wildos-rdp: which app it is decides its taskbar+ group, and its arrival is the launch's time to window."""+ now = time.monotonic()+ self.connection_seen(now)++ def found(app_id):+ if app_id:+ self.remote.set_window_app(window_id, launchers.PREFIX + app_id)+ self.window_appeared(app_id, window_id, now, "window on screen")+ self.lookup_window(window_id, found)++ def remote_loading(self, token, reason, window_id):+ window = self.loading.pop(token, None)+ if window and reason == "cancelled":+ # Cancel on board 9.13: the person stopped waiting. Windows keeps+ # going; the app simply opens without its loader if it still comes.+ window["closed"] = True+ log("launch cancelled from its window:", window["app"])++ def remote_close_stalled(self, window_id, pid, program):+ """A window closed on the desktop that Windows did not close, with+ nothing unsaved in it (wildos-rdp only asks then): its program is+ ended in the background, so nothing frozen is left behind."""+ log("window", hex(window_id), "did not close; ending", program, pid)+ self.call("EndProgram", (pid, program), "(us)", lambda r: log("end program:", r), timeout=60)++ def remote_details(self, token):+ try:+ subprocess.Popen(["wildos-settings", "--page", "windowsmode"], start_new_session=True,+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ except OSError as e:+ log("Settings couldn't open:", e)+def show_starting(self, name, app_id):"""The card that says Windows is starting (wildos-system-dialogs),whenever the app will wait more than a moment for Windows. The@@ -525,9 +782,20 @@ class Agent:deadline = time.monotonic() + SESSION_WAITdef attempt():+ if not self.conn.running:+ # The connection ended while this launch waited for its session+ # (the last app was closed just as this one was opened, and+ # Windows signed the session out): it opens again, with this+ # app, rather than wait for a session nothing will bring.+ log("the connection ended before", name, "could open; opening it again")+ self.queue.append((path, args, name, app_id, started, done))+ self.wake_then_launch()+ return+def got(reply):if reply.get("type") == "launched":self.mark(app_id, "process_started")+ self.app_window_stage(app_id, "almost")self.mark(app_id, "warm", bool(reply.get("warm")))done("")elif reply.get("error") in ("no-session", "not-connected", "timeout") and time.monotonic() < deadline:@@ -549,7 +817,8 @@ class Agent:def done(reply):self.refresh_host()defer.done(reply if isinstance(reply, str) else "Windows mode's background service didn't answer.")- self.call("SetProductKey", (key,), "(s)", done, timeout=300)+ # Windows may have to start from off before the key can go in.+ self.call("SetProductKey", (key,), "(s)", done, timeout=840)return deferdef m_open_desktop(self, sender, defer):@@ -582,17 +851,25 @@ class Agent:return deferdef credentials(self, done):+ """The account and its password: from the keyring (secret-tool, which+ KWallet can keep waiting for seconds, so off the main loop) or else+ from the service."""account = self.host.get("account", "wild")- pw = self.keyring.get(account)- if pw:- done({"account": account, "password": pw, "domain": self.host.get("computer_name", "")})- return- def got(reply):- if reply.get("password"):- self.keyring.put(reply["account"], reply["password"])- done(reply)- self.call_json("Credentials", done=got, timeout=120)+ def looked_up(pw):+ if isinstance(pw, str) and pw:+ done({"account": account, "password": pw, "domain": self.host.get("computer_name", "")})+ return++ def got(reply):+ if reply.get("password"):+ dbusutil.in_thread(self.keyring.put, reply["account"], reply["password"])+ done(reply)+ self.call_json("Credentials", done=got, timeout=120)+ if account in self.keyring.memory:+ looked_up(self.keyring.memory[account])+ else:+ dbusutil.in_thread(self.keyring.get, account, done=looked_up)def open_connection(self, creds, wake):pending, self.queue = self.queue, []@@ -605,7 +882,10 @@ class Agent:returnpath, args, name, app_id, started, done = pending[0]info = {"from": wake.get("from"), "wake_seconds": wake.get("seconds"), "via": "new connection"}+ if isinstance(wake.get("stages"), dict):+ info["wake_stages"] = wake["stages"]self.start_timing(app_id, started, info)+ self.mark(app_id, "connection_started")rdp_args = rdp.arguments(self.host.get("guest_address"), self.host.get("rdp_port", 3389), creds["account"], creds.get("domain", ""),name, path, args, drive=self.drive_folder())try:@@ -650,6 +930,7 @@ class Agent:for i, a in sorted(self.registry.items(), key=lambda kv: kv[1]["name"].lower())],"lifecycle": h.get("state"),"diskBytes": h.get("disk_bytes") or 0,+ "memoryPending": bool(h.get("memory_pending")),"vm": h.get("vm"),"connection": self.conn.open,"windows": len(self.windows),@@ -657,8 +938,16 @@ class Agent:"idleIn": h.get("idle_in"),"lastLaunch": self.last_launch,"lastHostAction": h.get("last"),+ # For the taskbar's Windows mode panel.+ "starting": self.waking or self.starting is not None,+ "openApps": launchers.open_windows(self.windows, self.registry),+ "lastApp": self.app_summary(launchers.last_app(self.registry, self.last_app, self.history)),}+ def app_summary(self, app_id):+ app = self.registry.get(app_id)+ return {"id": app_id, "name": app["name"]} if app else None+def m_status(self, sender):return json.dumps(self.status())@@ -697,6 +986,7 @@ class Agent:guest = [paths.to_guest(copy, mapping, self.host.get("drive", "Z"))]name = os.path.basename(host_path)self.installers["msiexec" if name.lower().endswith(".msi") else launchers.exe_stem(name)] = False+ self.installed_since_refresh = Trueif name.lower().endswith(".msi"):self.launch(r"C:\Windows\System32\msiexec.exe", ["/i", guest[0]], name, "installer", defer.done)else:@@ -752,9 +1042,11 @@ class Agent:def setup_control(self, action, argument, defer):def done(reply):# Read again before answering, so whatever asks next (the wizard- # after Start over) sees the state the action left.- self.refresh_host_now()- defer.done(reply if isinstance(reply, str) else "Windows mode's background service didn't answer.")+ # after Start over) sees the state the action left. Asked without+ # waiting, like every call to the service: the agent never stops+ # answering while the service is busy.+ self.refresh_host(lambda: defer.done(reply if isinstance(reply, str)+ else "Windows mode's background service didn't answer."))self.call("SetupControl", (action, argument), "(ss)", done, timeout=900)return defer@@ -792,6 +1084,11 @@ class Agent:self.call("SetOption", ("when_idle", mapped), "(ss)",lambda r: defer.done(r if isinstance(r, str) else "That setting couldn't be changed."))return defer+ if key == "memoryGb":+ # The system service changes the virtual PC itself.+ self.call("SetOption", ("memoryGb", value), "(ss)",+ lambda r: defer.done(r if isinstance(r, str) else "That setting couldn't be changed."))+ return deferreturn "That setting isn't available."# Theme.diff --git a/packages/wildos-winmode/winmode/cli.py b/packages/wildos-winmode/winmode/cli.pyindex 8ac9386..a35e274 100644--- a/packages/wildos-winmode/winmode/cli.py+++ b/packages/wildos-winmode/winmode/cli.py@@ -8,10 +8,13 @@ agent itself.wildos-winmode run-installer <file> run a Windows installer in Windows modewildos-winmode open <file> open a Windows shortcut (.lnk) in Windows modewildos-winmode agent the per-user agent (user unit)- wildos-winmode status the agent's and the system service's status+ wildos-winmode status [--if-set-up] the agent's and the system service's status; with+ --if-set-up, starts neither on a PC where this+ account hasn't set up Windows mode, and never+ notifies (the taskbar asks every few seconds)wildos-winmode refresh-apps make Start entries for Windows' apps againwildos-winmode windows the Windows windows open now- wildos-winmode idle pause|save apply the idle policy now (testing)+ wildos-winmode idle pause|save pause or save Windows now (the taskbar panel's buttons)wildos-winmode launch-stats [--check] launch times by state, 50th and 95th percentile;--check fails when a 95th percentile misses its targetwildos-winmode install-guest put this package's wild-guest into Windows@@ -27,7 +30,7 @@ from urllib.parse import unquote, urlparsefrom gi.repository import Gio, GLib-from . import config+from . import config, launchersdef call(bus_type, interface, method, args=None, signature=None, timeout=600):@@ -136,6 +139,32 @@ def launch_stats(check, path=None):return 1 if check and failed else 0+def agent_running():+ bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)+ reply = bus.call_sync("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "NameHasOwner",+ GLib.Variant("(s)", (config.BUS_NAME,)), GLib.VariantType("(b)"),+ Gio.DBusCallFlags.NONE, 2000, None)+ return reply.unpack()[0]+++def taskbar_status():+ """The taskbar's Windows mode item asks this every few seconds. Asking+ starts the agent and the system service, which a PC without Windows+ mode must never pay for, so they are only asked once this account has+ Windows apps or the agent is up anyway. "answering" false means Windows+ mode is set up but its services didn't reply."""+ try:+ if not os.path.exists(launchers.registry_file()) and not agent_running():+ print(json.dumps({"agent": None, "system": None}))+ return 0+ print(json.dumps({"agent": json.loads(agent("Status", timeout=10)),+ "system": json.loads(host("Status", timeout=10))}))+ except (GLib.Error, ValueError) as e:+ print(json.dumps({"agent": None, "system": None, "answering": False}))+ print(getattr(e, "message", str(e)), file=sys.stderr)+ return 0++SETUP_APP = "/usr/libexec/wildos/wildos-winmode-setup"@@ -179,6 +208,8 @@ def main(argv):if sentence:tell(sentence)return 1 if sentence else 0+ if cmd == "status" and "--if-set-up" in rest:+ return taskbar_status()if cmd == "status":print(json.dumps({"agent": json.loads(agent("Status", timeout=10)),"system": json.loads(host("Status", timeout=10))}, indent=1))diff --git a/packages/wildos-winmode/winmode/config.py b/packages/wildos-winmode/winmode/config.pyindex c17d421..f0e8ac8 100644--- a/packages/wildos-winmode/winmode/config.py+++ b/packages/wildos-winmode/winmode/config.py@@ -38,6 +38,12 @@ DEFAULTS = {# keep, save or automatic"when_idle": "automatic","guest_exe": DATA + "/guest/wild-guest.exe",+ # The RemoteApp client: "auto" is Wild OS's own (wildos-rdp) when it is+ # installed, "xfreerdp3" the fallback.+ "rdp_client": "auto",+ # The whole Windows desktop (Settings, "Open Windows desktop"):+ # "xfreerdp3", or "remote" for the Remote app's desktop window.+ "desktop_client": "xfreerdp3",}OPTION_KEYS = {"when_idle": ("keep", "save", "automatic")}diff --git a/packages/wildos-winmode/winmode/launchers.py b/packages/wildos-winmode/winmode/launchers.pyindex 59a0891..56c6fa4 100644--- a/packages/wildos-winmode/winmode/launchers.py+++ b/packages/wildos-winmode/winmode/launchers.py@@ -12,6 +12,7 @@ import ioimport osimport reimport subprocess+import threadingfrom . import config@@ -92,6 +93,46 @@ def app_id_for_image(image, registry):return None+def document_title(title, name):+ """What a window has open, from its title: Windows apps put their own+ name last ("Budget 2027.xlsx - Excel"), which the taskbar's panel+ already shows beside it."""+ title = (title or "").strip()+ name = (name or "").lower()+ head, sep, tail = title.rpartition(" - ")+ tail = tail.strip().lower()+ if sep and head and tail and (tail == name or name.endswith(" " + tail)):+ return head.strip()+ return "" if title.lower() == name else title+++def open_windows(windows, registry):+ """The Windows app windows open now, each with its app's id, name and+ icon and the document in it, for the taskbar's Windows mode panel.+ Dialogs are left out: the window that owns one is listed already."""+ out = []+ for w in windows:+ if not isinstance(w, dict) or w.get("owner") or is_shell(w.get("image")):+ continue+ app_id = app_id_for_image(w.get("image"), registry)+ if not app_id:+ continue+ app = registry.get(app_id)+ name = app["name"] if app and app.get("name") else exe_stem(w.get("image")).capitalize()+ out.append({"id": app_id, "name": name, "icon": PREFIX + app_id if app else "wildos-windows-app",+ "title": document_title(w.get("title"), name), "installed": app is not None})+ return out+++def last_app(registry, last, history):+ """The app to offer to open again: the last one opened, or else the one+ opened most often. None when neither is still installed."""+ if last in registry:+ return last+ counts = [(n, i) for i, n in (history or {}).items() if i in registry and isinstance(n, int)]+ return max(counts)[1] if counts else None++def registry_file():return os.path.join(config.user_data_dir(), "apps.json")@@ -188,11 +229,16 @@ def remove_all():def refresh_menus():- for cmd in (["update-desktop-database", config.applications_dir()], ["kbuildsycoca6"]):- try:- subprocess.run(cmd, capture_output=True, timeout=60)- except (OSError, subprocess.TimeoutExpired):- pass+ """The desktop's menus read the app entries again. kbuildsycoca6 can take+ seconds, so it runs beside the caller (the agent's main loop), which+ never waits for it."""+ def run():+ for cmd in (["update-desktop-database", config.applications_dir()], ["kbuildsycoca6"]):+ try:+ subprocess.run(cmd, capture_output=True, timeout=60)+ except (OSError, subprocess.TimeoutExpired):+ pass+ threading.Thread(target=run, daemon=True).start()def mimeapps_path():diff --git a/packages/wildos-winmode/winmode/rdp.py b/packages/wildos-winmode/winmode/rdp.pyindex c305224..dd6a719 100644--- a/packages/wildos-winmode/winmode/rdp.py+++ b/packages/wildos-winmode/winmode/rdp.py@@ -6,6 +6,14 @@ opened with the first app; every later app is started inside the sessionby wild-guest. Its first program is wild-guest's "--start", which startsthe app and ends, because FreeRDP's /app option splits on commas andcannot carry a file name that has one.++The client is Wild OS's own, wildos-rdp, when it is installed: native+Wayland windows at the screen's own scale, and the app's window on screen+with the loading W the moment the app is opened (boards 9.11 to 9.13).+xfreerdp3, under XWayland, is the fallback, and is what "rdp_client":+"xfreerdp3" in /etc/wildos/winmode.json, or WILDOS_RDP_CLIENT=xfreerdp3 in+the agent's environment, asks for. Both take the same arguments the same+way."""import base64@@ -14,8 +22,13 @@ import osimport signalimport subprocess-from gi.repository import GLib+from gi.repository import Gio, GLib++from . import config+NATIVE_CLIENT = "/usr/libexec/wildos/wildos-rdp"+REMOTE_CLIENT = "/usr/bin/wildos-remote"+REMOTE_APP_BUS = ("org.wildos.RemoteApp", "/org/wildos/RemoteApp", "org.wildos.RemoteApp")GUEST_EXE = r"C:\Program Files\Wild OS\wild-guest.exe"AUTH_FAILED = ("LOGON_FAILURE", "AUTHENTICATION_FAILED", "ERRCONNECT_LOGON_FAILURE", "STATUS_LOGON_FAILURE","ERRCONNECT_PASSWORD")@@ -83,6 +96,28 @@ def arguments(host, port, account, domain, name, path, args, cwd=None, drive=Nonreturn out+def prepare_arguments(host, port, account, domain, drive=None):+ """A connection that only signs in (wildos-rdp's --prepare-session): the+ session starts, then is left disconnected for the first app to take+ over. It asks Windows for no app, and never reconnects on its own, so it+ cannot take the session back from the connection that opens an app."""+ out = arguments(host, port, account, domain, "Windows mode", GUEST_EXE, [], drive=drive)+ return [a for a in out if a != "+auto-reconnect"]+++def prepare_session(args, password, log_path, done, native=NATIVE_CLIENT):+ """Runs the sign-in-only connection; done(ok) when it ends. Returns the+ process, so a launch that comes first can end it."""+ os.makedirs(os.path.dirname(log_path), exist_ok=True)+ with open(log_path, "wb") as log:+ proc = subprocess.Popen([native, "--prepare-session", "/args-from:stdin"], stdin=subprocess.PIPE, stdout=log,+ stderr=subprocess.STDOUT, start_new_session=True)+ proc.stdin.write(("\n".join(args + [f"/p:{password}"]) + "\n").encode())+ proc.stdin.close()+ GLib.child_watch_add(GLib.PRIORITY_DEFAULT, proc.pid, lambda pid, status: done(status == 0))+ return proc++def drive_arguments(drive):"""The shared folders, as the redirected drive wild-guest maps to Z:."""return [f"/drive:wildos,{drive}"] if drive else []@@ -109,37 +144,128 @@ def desktop_arguments(host, port, account, domain, drive=None):]+def client_program(choice=None, native=NATIVE_CLIENT):+ """The RemoteApp client to run: wildos-rdp unless it is missing or the+ installation asks for xfreerdp3."""+ choice = choice or os.environ.get("WILDOS_RDP_CLIENT") or config.load().get("rdp_client", "auto")+ if choice != "xfreerdp3" and os.access(native, os.X_OK):+ return native+ return "xfreerdp3"+++def desktop_client(choice=None, remote=REMOTE_CLIENT):+ """The client for the whole Windows desktop: xfreerdp3 unless the+ installation asks for Remote ("desktop_client": "remote" in+ /etc/wildos/winmode.json, or WILDOS_DESKTOP_CLIENT=remote) and it is+ installed. Remote reads the same arguments from standard input."""+ choice = choice or os.environ.get("WILDOS_DESKTOP_CLIENT") or config.load().get("desktop_client", "xfreerdp3")+ if choice == "remote" and os.access(remote, os.X_OK):+ return remote+ return "xfreerdp3"+++def loading_arguments(app_id, title, icon, reason="", program=""):+ """wildos-rdp's window for the app being opened, before the connection's+ own arguments arrive on standard input. Nothing here is secret: an app+ id, the app's name, its icon's name, why it may take a while and the+ program in Windows whose first window becomes the app's window. Each+ is one argument (no shell), kept to one line."""+ def line(text):+ return "".join(" " if ch < " " or ord(ch) == 127 else ch for ch in str(text))+ out = []+ for option, value in (("--app-id", app_id), ("--title", title), ("--icon", icon), ("--reason", reason),+ ("--program", program)):+ if value:+ out += [option, line(value)]+ return out++class Connection:- """One xfreerdp3 process. on_change(open) runs when it opens or ends;- on_auth_failed runs when Windows refused the password."""+ """One RemoteApp client process. on_change(open) runs when it opens or+ ends; on_auth_failed runs when Windows refused the password.++ wildos-rdp can start before Windows is awake (spawn()), with the app's+ window already on screen, and take the connection's arguments when they+ are known (start()). Until then the connection does not count as open."""- def __init__(self, on_change, on_auth_failed, log_path):+ # Where wildos-rdp is; tests point it elsewhere.+ native_client = NATIVE_CLIENT++ def __init__(self, on_change, on_auth_failed, log_path, program=None):self.proc = Noneself.on_change = on_changeself.on_auth_failed = on_auth_failedself.log_path = log_pathself.started = None+ self.program = program+ self.waiting = False@property- def open(self):+ def native(self):+ return (self.program or client_program(native=self.native_client)) == self.native_client++ @property+ def running(self):return self.proc is not None and self.proc.poll() is None- def start(self, args, password, env=None):+ @property+ def open(self):+ return self.running and not self.waiting++ def _popen(self, cmd, env):os.makedirs(os.path.dirname(self.log_path), exist_ok=True)+ # The connection before this one is kept beside it: when a launch+ # fails, the client that ended is usually the one that says why.+ if os.path.exists(self.log_path):+ os.replace(self.log_path, self.log_path + ".1")log = open(self.log_path, "wb")- self.proc = subprocess.Popen(["xfreerdp3", "/args-from:stdin"], stdin=subprocess.PIPE, stdout=log,- stderr=subprocess.STDOUT, env=env, start_new_session=True)+ self.proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT, env=env,+ start_new_session=True)log.close()+ GLib.child_watch_add(GLib.PRIORITY_DEFAULT, self.proc.pid, self._ended, self.proc)++ def spawn(self, app_id="", title="", icon="", reason="", program="", env=None):+ """Starts wildos-rdp now, the app's window up at once, the+ connection's arguments to follow. False with xfreerdp3, or when a+ client is already running."""+ if self.running or not self.native:+ return False+ self.program = self.native_client+ self.waiting = True+ self._popen([self.native_client, *loading_arguments(app_id, title, icon, reason, program), "/args-from:stdin"], env)+ return True++ def abandon(self):+ """The launch that spawned the client failed before it connected:+ its input closes with nothing on it, and it closes its window and+ ends."""+ if self.waiting and self.proc is not None:+ self.waiting = False+ try:+ self.proc.stdin.close()+ except OSError:+ pass++ def start(self, args, password, env=None):+ if not (self.waiting and self.running):+ self.waiting = False+ self.program = self.program or client_program(native=self.native_client)+ self._popen([self.program, "/args-from:stdin"], env)+ self.waiting = Falseself.proc.stdin.write(("\n".join(args + [f"/p:{password}"]) + "\n").encode())self.proc.stdin.close()self.started = GLib.get_monotonic_time()- GLib.child_watch_add(GLib.PRIORITY_DEFAULT, self.proc.pid, self._ended, self.proc)self.on_change(True)def _ended(self, pid, status, proc):if proc is not self.proc:return+ was_open = not self.waitingself.proc = None+ self.waiting = False+ self.program = None+ if not was_open:+ returnfailed = Falsetry:with open(self.log_path, "rb") as f:@@ -155,7 +281,7 @@ class Connection:def stop_now(self):"""For the agent's own exit, when no main loop is left to finishclose()'s work."""- if self.open:+ if self.running:proc = self.procfor sig, wait in ((signal.SIGTERM, 3), (signal.SIGKILL, 2)):try:@@ -168,7 +294,7 @@ class Connection:returndef close(self):- if self.open:+ if self.running:proc = self.proctry:os.killpg(proc.pid, signal.SIGTERM)@@ -185,3 +311,53 @@ class Connection:passreturn FalseGLib.timeout_add_seconds(3, kill)+++class RemoteApp:+ """wildos-rdp's org.wildos.RemoteApp while a connection is open: the+ app's window for later launches, news for it, and each window's taskbar+ group. Calls never wait, and do nothing when no wildos-rdp is on the+ bus."""++ def __init__(self, bus, on_window=None, on_window_gone=None, on_loading=None, on_details=None, on_close_stalled=None,+ on_retry=None):+ self.bus = bus+ name, path, iface = REMOTE_APP_BUS+ handlers = {"WindowAdded": on_window, "WindowRemoved": on_window_gone, "LoadingFinished": on_loading,+ "DetailsRequested": on_details, "CloseStalled": on_close_stalled, "RetryRequested": on_retry}++ def signal(conn, sender, obj, interface, member, params):+ handler = handlers.get(member)+ if handler:+ handler(*params.unpack())++ self.subscription = bus.signal_subscribe(name, iface, None, path, None, Gio.DBusSignalFlags.NONE, signal)++ def call(self, method, signature, args, done=None):+ name, path, iface = REMOTE_APP_BUS++ def finished(conn, res):+ try:+ value = conn.call_finish(res).unpack()+ except GLib.Error:+ value = None+ if done:+ done(value[0] if value else None)++ self.bus.call(name, path, iface, method, GLib.Variant(signature, args) if signature else None, None,+ Gio.DBusCallFlags.NO_AUTO_START, 2000, None, finished)++ def prepare(self, app_id, title, icon, program="", delay_ms=0, done=None):+ self.call("Prepare", "(ssssu)", (app_id or "", title or "", icon or "", program or "", delay_ms), done)++ def update(self, token, stage="", reason="", percent=-1, progress=""):+ """Token 0 is the loading window the client was started with (spawn),+ which the agent has no token for."""+ self.call("Update", "(ussis)", (token, stage, reason, percent, progress))++ def cancel(self, token):+ if token:+ self.call("Cancel", "(u)", (token,))++ def set_window_app(self, window_id, app_id):+ self.call("SetWindowApp", "(ts)", (window_id, app_id))diff --git a/packages/wildos-winmode/winmode/setup.py b/packages/wildos-winmode/winmode/setup.pyindex ca5a923..bc2abbb 100644--- a/packages/wildos-winmode/winmode/setup.py+++ b/packages/wildos-winmode/winmode/setup.py@@ -56,7 +56,7 @@ BOOT_WAIT = 300BOOT_TRIES = 3# setup.ps1's steps, in order (guest/setup.ps1), for the "tune" stage.GUEST_STEPS = ["guest-tools", "shared-folder", "wild-guest", "remote-desktop", "account", "tuning", "updates",- "known-folders", "office-policies", "startup-trim", "theme", "ready-task"]+ "known-folders", "office-policies", "startup-trim", "opengl", "theme", "ready-task"]TOOL_AGENT = "wildos-winmode (+https://wildos.io)"VIRTIO_BASE = "https://fedorapeople.org/groups/virt/virtio-win/direct-downloads"@@ -121,6 +121,46 @@ def key_shape_ok(key):return bool(re.fullmatch(rf"([{KEY_ALPHABET}N]{{5}}-){{4}}[{KEY_ALPHABET}N]{{5}}", key or "")) and key.count("N") <= 1+# Why slmgr /ato failed, by the error code it prints (the text around it+# follows Windows' language, the code does not). Only a missing connection+# clears up by itself; every other answer needs something from the person.+EDITION_ERRORS = {"C004F069", "C004F050", "C004F015", "C004F210"}+ACTIVATION_ERRORS = [+ ({"C004C008", "C004C770", "C004C771", "803FA071"},+ "Microsoft says this key is already in use on another PC, or on an earlier Windows mode. Microsoft may let you move it: "+ "open the Windows desktop, then Settings, Activation, and choose Troubleshoot."),+ ({"C004C003", "C004C060", "C004C4A2", "C004E028"},+ "Microsoft won't activate with this key. It may be blocked or not genuine. Check where it came from."),+ ({"C004F074", "8007232B", "C004F039", "C004F038"},+ "This is a volume licence key that activates through an organisation's own server, which Windows mode can't reach."),+ ({"803FA067", "C004F213", "C004C020"},+ "Microsoft found no licence for this PC with this key. Check the key is for Windows 11 Pro."),+]+OFFLINE_ERRORS = {"80072EE7", "80072EFD", "80072EE2", "80072F8F", "8007267C", "80072F78", "C004C001"}+NOT_ONLINE = "The key is in, but Windows couldn't reach Microsoft to activate. It tries again by itself when it's online."+++def activation_reason(output, firmware=False):+ """What to tell someone whose key went in but did not activate, from+ slmgr /ato's output. None when it was only the connection, which Windows+ retries by itself."""+ codes = [c.upper() for c in re.findall(r"0x([0-9A-Fa-f]{8})", output or "")]+ for code in codes:+ if code in OFFLINE_ERRORS:+ return None+ if code in EDITION_ERRORS:+ return ("This PC's licence is for another edition of Windows, usually Home, which Windows mode can't use."+ if firmware else+ "Microsoft says this key is for another edition of Windows, usually Home. Windows mode runs "+ "Windows 11 Pro, so it needs a Windows 11 Pro key.")+ for known, text in ACTIVATION_ERRORS:+ if code in known:+ return text+ if codes:+ return f"Windows didn't activate. Microsoft's answer was 0x{codes[0]}; check the key, or try again later."+ return None++def parse_msdm(table):"""The product key in an ACPI MSDM table: the 36 byte header, thenversion 1, reserved, data type 1, reserved, data length 29, and the key.@@ -408,7 +448,7 @@ class Setup:"paused": bool(rec.get("paused")),"problem": rec.get("problem"),"licence": {"source": licence.get("source"), "edition": licence.get("edition"),- "activated": licence.get("activated")},+ "activated": licence.get("activated"), "keyEnd": licence.get("last5") if licence.get("source") == "key" else None},"options": rec.get("options") or {},"failed": rec.get("failed"),}@@ -421,8 +461,16 @@ class Setup:return "Windows mode is already being set up."if self.rec.get("running"):# Trying again after a problem: carry on from the step it was on,- # keeping everything done so far.- self.save(failed=None, problem=None, paused=False)+ # keeping everything done so far, with the options as chosen this+ # time (the virtual PC is defined again from them).+ o = request.get("options") if isinstance(request.get("options"), dict) else {}+ options = dict(self.rec.get("options") or {})+ if o.get("memoryGb"):+ options["memoryGb"] = max(4, min(int(o.get("memoryGb") or 4), 32))+ for k in ("office", "openFiles"):+ if k in o:+ options[k] = bool(o[k])+ self.save(failed=None, problem=None, paused=False, options=options)self.launch()return ""if virsh.state(self.cfg["domain"]) != "":@@ -498,6 +546,10 @@ class Setup:self.svc.state.pop("setup", None)self.svc.state["setting_up"] = Falseself.svc.save_state()+ # The service keeps the virtual PC's last state to answer status+ # quickly, and an undefine sends nothing that clears it, so it still+ # said "shut off" and the wizard showed Start over as set up.+ self.svc.refresh()self.svc.notify()def choose_iso(self, path):@@ -577,7 +629,10 @@ class Setup:stage = self.rec.get("stage") or "media"self.set_stage(stage, "failed")text = "Windows mode couldn't finish setting up. Try again, and if it happens twice, restart the PC first."- self.save(problem={"kind": "failed", "text": text}, failed=f"{text} ({e})")+ # The unexpected error itself goes on the card too, small, so a+ # failure can be reported without digging through the log.+ self.save(problem={"kind": "failed", "text": text, "detail": f"{type(e).__name__}: {e}"[:300]},+ failed=f"{text} ({e})")def check(self):if self.stop.is_set():@@ -656,7 +711,6 @@ class Setup:os.chown(SECRETS, 0, _gid(group))os.chmod(SECRETS, 0o710)os.chmod(msdm_copy, 0o640)- _apparmor_allow(msdm_copy)elif lic.get("source") == "key":with open(os.path.join(SECRETS, ACTIVATION_KEY)) as f:key = f.read().strip()@@ -801,6 +855,10 @@ class Setup:self.payload()self.network()self.define()+ elif virsh.state(domain) == "shut off":+ # Trying again: defined afresh, so a fix to the definition (the+ # licence table) reaches a virtual PC an earlier try made.+ self.define()self.check()started = self.rec.get("install_started")if virsh.state(domain) in ("shut off", "saved"):@@ -882,6 +940,7 @@ class Setup:"ACCOUNT": self.cfg["account"], "PASSWORD": xml_escape(pw), "PRODUCT_KEY": key, "FULL_NAME": "Wild OS"}))guest = os.path.join(config.DATA, "guest")shutil.copy(os.path.join(guest, "setup.ps1"), os.path.join(work, "wildos", "setup.ps1"))+ shutil.copy(os.path.join(guest, "opengl.ps1"), os.path.join(work, "wildos", "opengl.ps1"))shutil.copy(self.cfg["guest_exe"], os.path.join(work, "wildos", "wild-guest.exe"))plan = (self.rec.get("options") or {}).get("officePlan", "personal")with open(os.path.join(work, "wildos", "office.xml"), "w", encoding="utf-8") as f:@@ -931,8 +990,10 @@ class Setup:vendor = _read("/sys/class/dmi/id/sys_vendor") or "Wild OS"product = _read("/sys/class/dmi/id/product_name") or "Windows mode"msdm = os.path.join(SECRETS, "msdm.bin")- acpi = (f"<qemu:commandline><qemu:arg value='-acpitable'/><qemu:arg value='file={msdm}'/></qemu:commandline>"- if os.path.exists(msdm) else "")+ # libvirt attaches the licence table itself, so it also lets QEMU read+ # it (file ownership and AppArmor). Passed on QEMU's own command+ # line, as it was, QEMU was refused the file.+ acpi = f"<acpi><table type='msdm'>{xml_escape(msdm)}</table></acpi>" if os.path.exists(msdm) else ""memory_mb = 1024 * (self.rec.get("options") or {}).get("memoryGb", 4)os.makedirs(self.cfg["share_root"], exist_ok=True)xml = render("domain.xml.in", {@@ -940,7 +1001,12 @@ class Setup:"WINDOWS_ISO": os.path.join(CACHE, "windows.iso"), "VIRTIO_ISO": os.path.join(CACHE, "virtio-win.iso"),"PAYLOAD_ISO": os.path.join(CACHE, "payload.iso"), "NET": self.cfg["network"], "GUEST_MAC": GUEST_MAC,"SHARE": self.cfg["share_root"], "VIRTIOFSD_BINARY": "", "SMBIOS_MANUFACTURER": xml_escape(vendor),- "SMBIOS_PRODUCT": xml_escape(product), "QEMU_COMMANDLINE": acpi})+ "SMBIOS_PRODUCT": xml_escape(product), "ACPI_TABLES": acpi})+ if virsh.state(self.cfg["domain"]) != "":+ # Defining it again: libvirt only updates a domain whose UUID+ # matches, and refuses a second one under the same name.+ uuid = virsh.run("domuuid", self.cfg["domain"]).strip()+ xml = xml.replace("</name>", f"</name>\n <uuid>{uuid}</uuid>", 1)path = os.path.join(config.STATE_DIR, "domain.xml")with open(path, "w") as f:f.write(xml)@@ -990,18 +1056,20 @@ class Setup:self.mark("activate")returncode = None+ answer = ""# The network may come up a moment after the agent does.for _ in range(6):self.check()try:- qga.powershell(domain, r"cscript //nologo $env:SystemRoot\System32\slmgr.vbs /ato 2>&1 | Out-String", 180)+ _, answer, _ = qga.powershell(domain, r"cscript //nologo $env:SystemRoot\System32\slmgr.vbs /ato 2>&1 | Out-String", 180)_, out, _ = qga.powershell(domain, ("(Get-CimInstance SoftwareLicensingProduct -Filter \"ApplicationID='55c92734-d682-4d71-983e-d6ec3f16059f'"" and PartialProductKey is not null\" | Select-Object -First 1).LicenseStatus"), 60)code = int(out.strip().splitlines()[-1]) if out.strip() else Noneexcept (virsh.VirshError, ValueError, KeyError, TimeoutError, IndexError) as e:log("activation:", e)- if code == 1:+ if code == 1 or activation_reason(answer):+ # Asking again won't change an answer other than "offline".breaktime.sleep(30)lic["activated"] = code == 1@@ -1010,8 +1078,13 @@ class Setup:self.forget_activation_key()# Not activating is not a failure: Windows works, and a key can be# added in Settings (board 9.8).+ reason = None if code == 1 else activation_reason(answer, lic.get("source") == "firmware")+ if code != 1:+ log("activation:", " ".join((answer or "").split())[-300:])self.set_stage("activate", "done", 100,- None if code == 1 else "Not activated yet. Windows works; add a key any time in Settings.")+ None if code == 1 else+ (reason + " " if reason else "Not activated yet. ")+ + "Windows works without activating; add a Windows 11 Pro key any time in Settings.")self.mark("activate")def activation_key(self, lic):@@ -1057,19 +1130,21 @@ class Setup:f"$s = Get-CimInstance SoftwareLicensingService; try {{ $s | Invoke-CimMethod -MethodName InstallProductKey "f"-Arguments @{{ProductKey='{key}'}} -ErrorAction Stop | Out-Null }} catch {{ 'refused'; exit }}; ""$s | Invoke-CimMethod -MethodName RefreshLicenseStatus | Out-Null; "- r"cscript //nologo $env:SystemRoot\System32\slmgr.vbs /ato | Out-Null; "+ r"cscript //nologo $env:SystemRoot\System32\slmgr.vbs /ato 2>&1 | Out-String; ""(Get-CimInstance SoftwareLicensingProduct -Filter \"ApplicationID='55c92734-d682-4d71-983e-d6ec3f16059f'"" and PartialProductKey is not null\" | Select-Object -First 1).LicenseStatus"), 240)if out.strip().endswith("refused"):return "Windows didn't accept that key. Check it, and that it's for Windows 11 Pro: Windows mode can't use a Home key."code = int(out.strip().splitlines()[-1]) if out.strip() else None+ if code != 1:+ log("activation:", " ".join(out.split())[-300:])except (virsh.VirshError, ValueError, KeyError, TimeoutError, IndexError) as e:log("product key:", e)return "Windows didn't take that key. Check it, and that this PC is online, then try again."lic = dict(self.rec.get("licence") or {})lic.update(source=source, last5=key[-5:], activated=code == 1)self.save(licence=lic)- return "" if code == 1 else "The key is in, but Windows couldn't activate yet. It tries again by itself when it's online."+ return "" if code == 1 else activation_reason(out, source == "firmware") or NOT_ONLINE# tunedef step_tune(self):@@ -1172,22 +1247,6 @@ def _gid(group):return None-def _apparmor_allow(path):- """libvirt's AppArmor profile for QEMU only lists the files it knows- about; the MSDM copy goes on QEMU's raw command line."""- for target in ("/etc/apparmor.d/abstractions/libvirt-qemu.d/wildos-winmode",- "/etc/apparmor.d/local/abstractions/libvirt-qemu"):- if os.path.isdir(os.path.dirname(target)):- try:- text = open(target).read() if os.path.exists(target) else ""- if path not in text:- with open(target, "a") as f:- f.write(f" {path} r,\n")- except OSError as e:- log("apparmor:", e)- return--def _redirect(url):req = urllib.request.Request(url, method="HEAD", headers={"User-Agent": msdl.AGENT})diff --git a/packages/wildos-winmode/winmode/system.py b/packages/wildos-winmode/winmode/system.pyindex 80b151f..294a42e 100644--- a/packages/wildos-winmode/winmode/system.py+++ b/packages/wildos-winmode/winmode/system.py@@ -11,6 +11,7 @@ system bus; polkit lets the active local user in (org.wildos.winmode.use).import jsonimport osimport pwd+import reimport secretsimport socketimport subprocess@@ -79,6 +80,11 @@ XML = """<arg name="key" type="s" direction="in"/><arg type="s" direction="out"/></method>+ <method name="EndProgram">+ <arg name="pid" type="u" direction="in"/>+ <arg name="image" type="s" direction="in"/>+ <arg type="s" direction="out"/>+ </method><method name="GuestRequest"><arg name="message" type="s" direction="in"/><arg type="s" direction="out"/>@@ -90,6 +96,15 @@ XML = """"""LAUNCH_HOLD = "launch"+# A product key going in: Windows has to stay running until it is done.+LICENCE_HOLD = "licence"+# How long to wait before trying again to restart Windows for a new memory+# limit when the last try didn't finish.+MEMORY_RETRY = 600+PRESTART_HOLD = "prestart"+# How long Windows started ahead of time stays up for the agent to sign in+# to it (measured: about 6 seconds just after a boot).+PRESTART_SIGN_IN_SECONDS = 45# From the moment Windows runs until wild-guest's first window list, the# window count is unknown, not zero: an app may well be open.WINDOW_LIST_HOLD = "window list"@@ -101,6 +116,24 @@ def log(*parts):print(*parts, file=sys.stderr, flush=True)+def end_program_script(pid, image):+ """PowerShell that ends process `pid` if it is still `image` in a+ person's session; None for anything that cannot be named safely."""+ try:+ pid = int(pid)+ except (TypeError, ValueError):+ return None+ if pid <= 4 or not image or len(image) > 260 or any(ch < " " for ch in image):+ return None+ # PowerShell takes the curly single quotes as quotes too.+ quoted = image+ for q in ("'", "‘", "’", "‚", "‛"):+ quoted = quoted.replace(q, q + q)+ return (f"$p = Get-Process -Id {pid} -ErrorAction SilentlyContinue; "+ f"if ($p -and $p.SessionId -ne 0 -and $p.Path -ieq '{quoted}') "+ f"{{ Stop-Process -Id {pid} -Force; 'ended' }} else {{ 'not running' }}")++def random_password():# The old builder's alphabet, without look-alike characters, and a fixed# tail that meets Windows' complexity rule.@@ -116,6 +149,8 @@ def app_windows(windows):SAVE_TO_DISK = False+# Windows' processor share while it boots ahead of time (the default is 100).+BACKGROUND_CPU_WEIGHT = 20# Windows' share of memory follows what it uses (trim_memory), in KiB.TRIM_HEADROOM_KIB = 1536 * 1024TRIM_FLOOR_KIB = 3 * 1024 * 1024@@ -137,8 +172,10 @@ class Service:self.windows = {}self.error = Noneself.busy_action = None+ self.memory_tried = -MEMORY_RETRYself.idle_timer = Noneself.window_list_timer = None+ self.upkeep_running = Falseself.auth_cache = {}# Taken from the main loop (claim) and from wake's worker thread.self.bind_lock = threading.Lock()@@ -159,6 +196,7 @@ class Service:"Credentials": (self.m_credentials, "s", True),"InstallGuestHelper": (self.m_install_guest, "s", True),"GuestRequest": (self.m_guest_request, "s", True),+ "EndProgram": (self.m_end_program, "s", True),"SetupStart": (self.m_setup_start, "s", True),"SetupControl": (self.m_setup_control, "s", True),"Firmware": (self.m_firmware, "s", True),@@ -363,7 +401,19 @@ class Service:the window list, read afresh in case an update was lost (the guestdrops what it cannot send while the channel reconnects)."""self.host_changed()- if virsh.state(self.domain) == "running":+ st = virsh.state(self.domain)+ if self.restart_wanted() and not self.busy_action:+ if st == "shut off":+ # Off already: the next start takes the new limit.+ self.state["memory_pending"] = False+ self.state["restart_pending"] = False+ self.save_state()+ self.changed()+ elif st in ("paused", "saved") and time.monotonic() - self.memory_tried > MEMORY_RETRY:+ # A shutdown that timed out (Windows busy updating, say) is+ # tried again, as nothing else would bring it round.+ self.restart_for_memory()+ if st == "running":self.trim_memory()if not self.link.connected:self.connect_guest()@@ -374,19 +424,23 @@ class Service:def trim_memory(self):"""Windows keeps the memory it was given even when it isn't usingit (free page reporting only works with Linux guests), which left a- 16 GB PC with 8 GB tied up and the desktop in swap. Every 30 s the- balloon is set to what Windows uses plus headroom; a launch gives it- everything back first (wake), so apps never start short."""- if self.busy_action or time.monotonic() - self.last_wake < TRIM_AFTER:+ 16 GB PC with 8 GB tied up and the desktop in swap. So while no+ Windows app is open, every 30 s the balloon is set to what Windows+ uses plus headroom, and Windows goes into its pause holding only+ that. Never while an app is open: Windows only grows into what the+ balloon hands back, a step every 30 s, so whatever the limit, a+ trimmed Windows worked like a 4 GB PC. The first app window and+ every launch (wake) give it everything back."""+ if self.busy_action or self.life.busy() or time.monotonic() - self.last_wake < TRIM_AFTER:returntry:stats = virsh.memory_stats(self.domain)except virsh.VirshError:returnactual, usable = stats.get("actual"), stats.get("usable")- if not actual or usable is None or not self.memory:+ ceiling = virsh.defined_memory(self.domain, inactive=False) // 1024+ if not actual or usable is None or not ceiling:return- ceiling = self.memory // 1024used = actual - usabletarget = max(TRIM_FLOOR_KIB, min(ceiling, used + TRIM_HEADROOM_KIB))# Small moves cost more than they save; growing is never held back.@@ -396,10 +450,37 @@ class Service:except virsh.VirshError as e:log("memory:", e)+ def match_cpus(self):+ """Windows gets every processor thread, up to 8, when setup defines it+ (setup.define). Turning hyper-threading on or off in Settings changes+ how many the host has, so a cold start brings the guest in line. A+ saved Windows keeps its count until it next starts from scratch."""+ want = max(2, min(8, os.cpu_count() or 4))+ try:+ xml = virsh.dumpxml(self.domain, inactive=True)+ except virsh.VirshError as e:+ log("processor count:", e)+ return+ m = re.search(r"<vcpu\b[^>]*>(\d+)</vcpu>", xml)+ if not m or int(m.group(1)) == want:+ return+ xml = re.sub(r"(<vcpu\b[^>]*>)\d+(</vcpu>)", rf"\g<1>{want}\g<2>", xml, count=1)+ xml = re.sub(r"(<topology\b[^>]*\bcores=')\d+(')", rf"\g<1>{want}\g<2>", xml, count=1)+ path = os.path.join(config.STATE_DIR, "domain.xml")+ with open(path, "w") as f:+ f.write(xml)+ virsh.run("define", path)+ log(f"Windows now gets {want} processor threads (was {m.group(1)})")+def full_memory(self):- if self.memory:+ """Everything Windows started with, back from the balloon. Not the+ definition's limit: a new one waiting for Windows' next start is+ more than libvirt lets the running Windows have, and asking for it+ gave nothing back at all."""+ limit = virsh.defined_memory(self.domain, inactive=False)+ if limit:try:- virsh.set_memory(self.domain, self.memory // 1024)+ virsh.set_memory(self.domain, limit // 1024)except virsh.VirshError as e:log("memory:", e)@@ -460,8 +541,59 @@ class Service:if warm:self.link.send(dict(warm, type="warm"))self.link.request({"type": "windows"}, self.guest_event)+ self.guest_upkeep()self.changed()+ def guest_upkeep(self):+ """A Windows set up before guest/opengl.ps1 existed (or whose setup+ could not download Mesa) gets it the first time wild-guest connects,+ in the background. Programs only see it from Windows' next sign-in:+ GALLIUM_DRIVER reaches new sign-ins only, and apps start from the+ session's own environment. Without it Mesa picks its Direct3D 12+ driver, which crashes MagicaVoxel just like OpenGL 1.1 did. The PC's+ next restart was meant to bring that sign-in, but this runs as+ Windows starts, so the download often finished after the session+ had signed in, and every app stayed on the old environment until+ the restart after that. Windows now shuts down cleanly the next+ time no Windows app is open, as for a new memory limit."""+ if self.state.get("setting_up") or self.upkeep_running:+ return+ try:+ with open(os.path.join(config.DATA, "guest", "opengl.ps1"), encoding="utf-8") as f:+ script = f.read()+ except OSError as e:+ log("opengl:", e)+ return+ m = re.search(r"^\$version = '([^']+)'", script, re.M)+ if not m or self.state.get("opengl") == m.group(1):+ return+ version = m.group(1)+ self.upkeep_running = True+ self.life.hold(time.monotonic(), "upkeep", True)++ def work():+ code, out, err = qga.powershell(self.domain, script, 600)+ return code, (out + err).strip()++ def finished(result):+ self.upkeep_running = False+ self.life.hold(time.monotonic(), "upkeep", False)+ self.schedule_idle()+ if isinstance(result, Exception) or result[0] != 0:+ # Tried again when wild-guest next connects.+ log("opengl: not installed:", result if isinstance(result, Exception) else result[1][-300:])+ return+ last = result[1].splitlines()[-1] if result[1] else "done"+ log("opengl:", last, version)+ self.state["opengl"] = version+ if last.strip() == "installed":+ self.state["restart_pending"] = True+ if virsh.state(self.domain) in ("paused", "saved") and not self.busy_action:+ self.restart_for_memory()+ self.save_state()++ dbusutil.in_thread(work, done=finished)+def guest_event(self, msg):t = msg.get("type")if t == "windows":@@ -489,6 +621,10 @@ class Service:self.windows = windowsafter = self.all_windows()self.life.update(time.monotonic(), windows=len(after))+ if after and not before:+ # An app opened from inside Windows (the Windows desktop, or a+ # program starting another) never went through wake.+ self.full_memory()self.schedule_idle()if before != after:self.export.emit("WindowsChanged", "(s)", json.dumps(after))@@ -504,8 +640,54 @@ class Service:wait = max(0, d - time.monotonic())self.idle_timer = GLib.timeout_add(int(wait * 1000) + 50, self.idle_fired)+ def restart_wanted(self):+ """A new memory limit, or Windows' sign-in needing to start afresh+ (opengl), both waiting for a clean shutdown while no app is open."""+ return bool(self.state.get("memory_pending") or self.state.get("restart_pending"))++ def restart_for_memory(self):+ """Shuts Windows down cleanly so the next app starts it with the new+ memory limit, or a fresh sign-in. Only when no Windows app is open."""+ self.busy_action = "shutdown"+ self.memory_tried = time.monotonic()++ def work():+ st = virsh.state(self.domain)+ if st == "paused":+ virsh.run("resume", self.domain)+ elif st == "saved":+ # Loaded back first, so Windows shuts down properly rather+ # than losing the save as a power cut would.+ self.wake()+ elif st == "shut off":+ return True+ virsh.run("shutdown", self.domain)+ deadline = time.monotonic() + 180+ while time.monotonic() < deadline:+ if virsh.state(self.domain) == "shut off":+ return True+ time.sleep(2)+ return False++ def finished(result):+ self.busy_action = None+ if result is True:+ self.state["memory_pending"] = False+ self.state["restart_pending"] = False+ log("Windows shut down for its new memory limit or a fresh sign-in")+ else:+ log("Windows didn't shut down for its new memory limit or a fresh sign-in:", result)+ self.save_state()+ self.refresh()++ dbusutil.in_thread(work, done=finished)+def idle_fired(self):self.idle_timer = None+ if self.life.due(time.monotonic()) and not self.busy_action and self.restart_wanted():+ log(f"no Windows app open for {self.cfg['idle_seconds']} s: shutting down for the new memory limit or a fresh sign-in")+ self.restart_for_memory()+ return Falseif self.life.due(time.monotonic()) and not self.busy_action:action = lifecycle.idle_action(self.state["when_idle"], self.power.on_battery, *hostinfo.meminfo(),hostinfo.under_pressure())@@ -619,10 +801,17 @@ class Service:time.sleep(0.2)return False- def wake(self):+ def set_cpu_weight(self, weight):+ """Windows' share of the processor when it competes with the desktop+ (cgroup weight; 100 is everyone's default)."""+ virsh.run("schedinfo", self.domain, "--live", f"cpu_shares={weight}", check=False, timeout=10)++ def wake(self, background=False):"""Gets the guest running and ready for a RemoteApp connection:resume, restore or boot, then the clock, the guest agent and- Remote Desktop (brief 5.6, Resume)."""+ Remote Desktop (brief 5.6, Resume). In the background (started ahead+ of time) it boots with a small share of the processor, so the+ desktop that has just started is not slowed by it."""t0 = time.monotonic()self.last_wake = t0st = virsh.state(self.domain)@@ -633,10 +822,14 @@ class Service:virsh.resume(self.domain)elif st in ("saved", "shut off"):firewall.apply(self.cfg, self.state.get("file_sharing", False))+ if st == "shut off":+ self.match_cpus()# virtiofsd starts with the guest and sees the binds made before it.self.bind_folders()try:virsh.start(self.domain)+ if background:+ self.set_cpu_weight(BACKGROUND_CPU_WEIGHT)except virsh.VirshError as e:if st != "saved":raise@@ -651,14 +844,19 @@ class Service:self.save_state()elif st != "running":raise RuntimeError(f"Windows is {st}")- # An app is about to start: all the memory first (trim_memory takes- # back what goes unused a minute later).- if st in ("running", "paused"):+ # Where a wake's time goes, in seconds from its start, for+ # launch-stats.+ stages = {"started": round(time.monotonic() - t0, 2)}+ # An app is about to start: all the memory first, which it keeps+ # until no app is open (trim_memory). A restored Windows comes back+ # with the balloon it was saved with.+ if st in ("running", "paused", "saved"):self.full_memory()resumed = time.monotonic() - t0if st != "running":if not qga.wait(self.domain, 30 if st != "shut off" else 240):raise RuntimeError("Windows didn't respond after starting")+ stages["guest_agent"] = round(time.monotonic() - t0, 2)try:qga.set_time(self.domain)except (virsh.VirshError, ValueError, KeyError) as e:@@ -675,7 +873,9 @@ class Service:self.reattach_share()if not self.wait_rdp(30 if st != "shut off" else 240):raise RuntimeError("Windows isn't accepting the connection")- return {"ok": True, "from": came_from, "seconds": round(time.monotonic() - t0, 2), "resume_seconds": round(resumed, 2)}+ stages["remote_desktop"] = round(time.monotonic() - t0, 2)+ return {"ok": True, "from": came_from, "seconds": round(time.monotonic() - t0, 2), "resume_seconds": round(resumed, 2),+ "stages": stages}def qemu_usage(self):"""QEMU's CPU time and memory, for Task Manager: a root process that@@ -692,7 +892,17 @@ class Service:for line in f:if line.startswith("VmRSS:"):rss = int(line.split()[1]) * 1024- return {"pid": pid, "cpu_seconds": round(cpu, 2), "rss_bytes": rss}+ # QEMU names each virtual processor's thread "CPU n/KVM", so+ # their count is the processors Windows has now, which a saved+ # Windows can hold at an older number than match_cpus sets.+ vcpus = 0+ for task in os.listdir(f"/proc/{pid}/task"):+ try:+ with open(f"/proc/{pid}/task/{task}/comm") as f:+ vcpus += f.read().startswith("CPU ")+ except OSError:+ pass+ return {"pid": pid, "cpu_seconds": round(cpu, 2), "rss_bytes": rss, "vcpus": vcpus}except (OSError, ValueError, IndexError):return None@@ -717,6 +927,8 @@ class Service:"share_detached": self.state.get("share_detached", False),"last": self.state.get("last"),"action": self.busy_action,+ "save_to_disk": SAVE_TO_DISK,+ "memory_pending": bool(self.state.get("memory_pending")),"error": self.error,"computer_name": self.cfg["computer_name"] or self.state.get("computer_name", ""),"account": self.cfg["account"],@@ -736,6 +948,11 @@ class Service:return json.dumps(self.status())def m_wake(self, sender, defer):+ if self.state.get("setting_up"):+ # Setup owns the virtual PC until it finishes; a Windows app+ # opened meanwhile would otherwise get "couldn't start".+ return json.dumps({"ok": False, "error": "setting up",+ "message": "Windows mode is still being set up. Windows apps open once it's finished."})why = self.claim(sender)if why:return json.dumps({"ok": False, "error": why, "message": why})@@ -759,6 +976,10 @@ class Service:# A pause or save already under way finishes first.while self.busy_action:time.sleep(0.1)+ # Someone is waiting now: a boot started ahead of time gets the+ # whole processor again.+ if virsh.state(self.domain) == "running":+ self.set_cpu_weight(100)return self.wake()dbusutil.in_thread(work, done=finished)@@ -799,8 +1020,18 @@ class Service:log("not starting Windows ahead of time:", blocker)return json.dumps({"ok": False, "skipped": blocker})log("starting Windows ahead of time")+ # Not idle while it boots, nor while the agent signs in to it after:+ # paused halfway through signing in, Windows did not answer when it+ # was woken next.+ self.life.hold(time.monotonic(), PRESTART_HOLD, True)++ def release():+ self.life.hold(time.monotonic(), PRESTART_HOLD, False)+ self.schedule_idle()+ return Falsedef finished(result):+ GLib.timeout_add_seconds(PRESTART_SIGN_IN_SECONDS, release)self.refresh()self.schedule_idle()if isinstance(result, Exception):@@ -808,7 +1039,13 @@ class Service:else:defer.done(json.dumps(result))- dbusutil.in_thread(self.wake, done=finished)+ def work():+ try:+ return self.wake(background=True)+ finally:+ self.set_cpu_weight(100)++ dbusutil.in_thread(work, done=finished)return deferdef release_launch(self):@@ -816,10 +1053,13 @@ class Service:self.schedule_idle()def m_idle(self, sender, mode, defer):- """Pause or save now, for testing and for the command line."""+ """Pause or save now: Pause now and Save to disk in the taskbar's+ Windows mode panel, and the command line."""if mode not in (lifecycle.PAUSE, lifecycle.SAVE):return json.dumps({"ok": False, "error": "mode is pause or save"})- if virsh.state(self.domain) != "running":+ st = virsh.state(self.domain)+ # A paused Windows can still go to disk, which frees its memory.+ if st != "running" and not (st == "paused" and mode == lifecycle.SAVE and SAVE_TO_DISK):return json.dumps({"ok": False, "error": "not running"})self.run_idle(mode, done=lambda r: defer.done(json.dumps({"ok": False, "error": str(r)} if isinstance(r, Exception) else {"ok": True, "seconds": round(r, 2)})))@@ -878,6 +1118,8 @@ class Service:return ""def m_set_option(self, sender, key, value):+ if key == "memoryGb":+ return self.set_memory(value)if key == "whenIdle":key = "when_idle"allowed = config.OPTION_KEYS.get(key)@@ -888,6 +1130,41 @@ class Service:self.changed()return ""+ def set_memory(self, value):+ """Settings' memory limit. The virtual PC's definition changes now,+ and Windows only gets it by starting from off: a paused Windows (no+ app open) is shut down now, a running one when it next goes idle,+ instead of being paused."""+ try:+ gb = int(value)+ except ValueError:+ return "That setting isn't available."+ host = os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES")+ if gb < 4 or gb > 32 or (gb > 4 and gb * 1024 ** 3 > host * 0.75):+ return "That's more memory than this PC can spare."+ if virsh.state(self.domain) != "":+ kib = str(gb * 1024 * 1024)+ try:+ virsh.run("setmaxmem", self.domain, kib, "--config")+ virsh.run("setmem", self.domain, kib, "--config")+ except virsh.VirshError as e:+ log("memory:", e)+ return "Windows mode couldn't change its memory. Try again."+ self.memory = virsh.defined_memory(self.domain)+ st = virsh.state(self.domain)+ # A saved Windows loads back with the memory it was saved with,+ # whatever the definition now says, so it needs the same clean+ # restart as a running one.+ if st in ("running", "paused", "saved"):+ self.state["memory_pending"] = True+ if st in ("paused", "saved") and not self.busy_action:+ self.restart_for_memory()+ rec = self.state.get("setup") or {}+ self.state["setup"] = dict(rec, options=dict(rec.get("options") or {}, memoryGb=gb))+ self.save_state()+ self.changed()+ return ""+def m_connection(self, sender, is_open):self.life.update(time.monotonic(), connection=bool(is_open))self.schedule_idle()@@ -964,9 +1241,32 @@ class Service:def m_set_product_key(self, sender, key, defer):"""Settings' Add a key (board 9.8): installs a Windows product key,or this PC's own built-in one when the key is "firmware", and- activates. "" when Windows is activated, or why not."""- dbusutil.in_thread(lambda: self.setup.set_key(key),- done=lambda r: defer.done(str(r) if isinstance(r, Exception) else r))+ activates. "" when Windows is activated, or why not. Windows is+ usually paused when nobody has an app open, and the key can only go+ in while it runs, so it is woken first and kept awake until done."""+ why = self.claim(sender)+ if why:+ return why+ self.life.hold(time.monotonic(), LICENCE_HOLD, True)+ self.schedule_idle()++ def work():+ while self.busy_action:+ time.sleep(0.1)+ try:+ self.wake()+ except (RuntimeError, virsh.VirshError) as e:+ log("waking Windows for a product key:", e)+ return "Windows mode couldn't start Windows to add the key. Try again, or restart the PC."+ return self.setup.set_key(key)++ def finished(result):+ self.life.hold(time.monotonic(), LICENCE_HOLD, False)+ self.schedule_idle()+ self.refresh()+ defer.done(str(result) if isinstance(result, Exception) else result)++ dbusutil.in_thread(work, done=finished)return deferdef m_firmware(self, sender, defer):@@ -976,6 +1276,34 @@ class Service:json.dumps({"error": str(r)} if isinstance(r, Exception) else r)))return defer+ def m_end_program(self, sender, pid, image, defer):+ """Ends a Windows program that did not close when its window was+ closed on the desktop. Only that process, only if it still runs the+ program the window said it belonged to, and only in a person's+ session, never one of Windows' own (session 0)."""+ why = self.claim(sender)+ if why:+ defer.error(why)+ return defer+ script = end_program_script(pid, image)+ if not script:+ return "not a program that can be ended"++ def work():+ code, out, err = qga.powershell(self.domain, script, timeout=30)+ return (out or err).strip()++ def finished(result):+ if isinstance(result, Exception):+ log("ending a program that did not close:", result)+ defer.done(f"couldn't end it: {result}")+ else:+ log(f"ending process {pid} ({image}) that did not close:", result)+ defer.done(result)++ dbusutil.in_thread(work, done=finished)+ return defer+def m_guest_request(self, sender, message, defer):"""Any wild-guest request, answered with its reply: for tests andtroubleshooting."""diff --git a/packages/wildos-winmode/winmode/virsh.py b/packages/wildos-winmode/winmode/virsh.pyindex b95848c..03851ae 100644--- a/packages/wildos-winmode/winmode/virsh.py+++ b/packages/wildos-winmode/winmode/virsh.py@@ -101,9 +101,11 @@ def memory_stats(domain):return stats-def defined_memory(domain):+def defined_memory(domain, inactive=True):+ """The memory limit in bytes: the definition's, which the next start+ takes, or with inactive=False the one the running Windows started with."""try:- root = ET.fromstring(dumpxml(domain, inactive=True))+ root = ET.fromstring(dumpxml(domain, inactive=inactive))except (VirshError, ET.ParseError):return 0mem = root.find("memory")