Skip to content

A hardened Linux desktop, rebuilt from scratch, with your Windows apps built in. Free and open source.

Settings without KDE's pages, network privacy, accessibility and more fixes

Dan93f6ca9e5b87
diff --git a/build/Dockerfile b/build/Dockerfile
index d0cab42..99c7b11 100644
--- a/build/Dockerfile
+++ b/build/Dockerfile
@@ -20,6 +20,12 @@ RUN apt-get update \
libkf6solid-dev \
libkf6windowsystem-dev \
libkf6colorscheme-dev \
+ libkscreen-dev \
+ libkf6sonnet-dev \
+ libkf6networkmanagerqt-dev \
+ libkf6globalaccel-dev \
+ libsdl2-dev \
+ breeze-cursor-theme \
libkf6purpose-dev \
libkf6guiaddons-dev \
libkf6notifications-dev \
diff --git a/build/build.sh b/build/build.sh
index 717ad04..28b0c44 100644
--- a/build/build.sh
+++ b/build/build.sh
@@ -409,9 +409,16 @@ mv "$ROOTFS/live-initrd.img" "$WORK/iso/live/initrd.img"
# GRUB packages for the installer; must sit outside the squashfs or the
# installed system would carry a copy of both.
mv "$ROOTFS/live-pool" "$WORK/iso/pool"
-sed "s/@VOLID@/$VOLID/g; s/@VERSION@/$VERSION/g" "$SRC/build/iso/grub.cfg" > "$WORK/iso/boot/grub/grub.cfg"
+LANGUAGES="$SRC/packages/wildos-live/files/languages"
+# One entry per language: picking it shows the main menu again with that
+# language passed to the live system.
+grep -v '^#' "$LANGUAGES" | awk -F '\t' '{
+ printf " menuentry \"%s\" --class wildos-lang-%s {\n set wildos_lang=%s\n export wildos_lang\n configfile /boot/grub/grub.cfg\n }\n", $3, $1, $1
+}' > "$WORK/grub-languages.cfg"
+sed "s/@VOLID@/$VOLID/g; s/@VERSION@/$VERSION/g" "$SRC/build/iso/grub.cfg" \
+ | sed -e "/^@LANGUAGES@\$/{r $WORK/grub-languages.cfg" -e 'd}' > "$WORK/iso/boot/grub/grub.cfg"
bash "$SRC/packages/wildos-branding/tools/grub-theme.sh" usb "$WORK/iso/boot/grub/themes/wildos" \
- "$SRC/branding/logo/wild-os-icon.svg" "$VERSION"
+ "$SRC/branding/logo/wild-os-icon.svg" "$VERSION" "$LANGUAGES"
log "Compressing root filesystem"
mksquashfs "$ROOTFS" "$WORK/iso/LiveOS/squashfs.img" \
diff --git a/build/hooks/10-locale.sh b/build/hooks/10-locale.sh
index 8a052ba..1aedb94 100644
--- a/build/hooks/10-locale.sh
+++ b/build/hooks/10-locale.sh
@@ -1,10 +1,12 @@
-# English (UK) until someone picks another language, the same default the
-# installer, first start and Settings use (the start-up menu passes no
-# language yet). The installer takes the live session's LANG, so an en_US
-# here installed every PC with a US keyboard and New York time. The live
-# session needs a generated UTF-8 locale or Plasma and Qt apps fall back to
-# ASCII.
-sed -i 's/^# *\(en_US.UTF-8 UTF-8\)/\1/; s/^# *\(en_GB.UTF-8 UTF-8\)/\1/' /etc/locale.gen
+# English (UK) until someone picks another language on the start-up menu,
+# the same default the installer, first start and Settings use. The
+# installer takes the live session's LANG, so an en_US here installed every
+# PC with a US keyboard and New York time. Every language the menu offers
+# (wildos-live's list) needs a generated UTF-8 locale, or Plasma and Qt apps
+# fall back to ASCII.
+for code in $(grep -v '^#' /usr/share/wildos-live/languages | cut -f 1); do
+ sed -i "s/^# *\($code\.UTF-8 UTF-8\)/\1/" /etc/locale.gen
+done
locale-gen
update-locale LANG=en_GB.UTF-8
diff --git a/build/hooks/95-resolv-conf.sh b/build/hooks/95-resolv-conf.sh
new file mode 100644
index 0000000..c9652fa
--- /dev/null
+++ b/build/hooks/95-resolv-conf.sh
@@ -0,0 +1,8 @@
+# Lookups go through systemd-resolved (wildos-settings depends on it), which
+# is what lets them be encrypted. Left alone, the build container's own
+# resolv.conf would ship in place of the link to resolved, and programs
+# reading it would ask that address directly. This runs last, since the
+# hooks before it may still need the container's DNS.
+if [ -x /usr/lib/systemd/systemd-resolved ]; then
+ ln -sfn ../run/systemd/resolve/stub-resolv.conf /etc/resolv.conf
+fi
diff --git a/build/iso/grub.cfg b/build/iso/grub.cfg
index 16dab33..3acae94 100644
--- a/build/iso/grub.cfg
+++ b/build/iso/grub.cfg
@@ -4,10 +4,20 @@
# The live system reads wildos.mode from the kernel command line:
# install straight into the installer, full screen, no desktop first
# try the live desktop with the Install launcher
+# and wildos.lang, the language picked under Language (wildos-live's list).
set default=0
set timeout_style=menu
set timeout=8
+# Picking a language shows this menu again with it, without the countdown,
+# since someone is clearly at the keyboard.
+if [ -z "$wildos_lang" ]; then
+ set wildos_lang=en_GB
+else
+ set timeout=-1
+fi
+export wildos_lang
+
insmod all_video
insmod gfxterm
insmod gfxmenu
@@ -32,6 +42,7 @@ background_image $theme_dir/background.png
set color_normal=light-gray/black
set live="root=live:CDLABEL=@VOLID@ rd.live.image rd.live.overlay.overlayfs=1"
+set live="$live wildos.lang=$wildos_lang"
set quiet="quiet splash loglevel=3 rd.udev.log_level=3 vt.global_cursor_default=0"
export live quiet
@@ -52,6 +63,14 @@ menuentry "Check this USB stick" --class wildos-check {
initrd /live/initrd.img
}
+# The entry shows the language in use; each language in the list is named in
+# itself. build.sh writes the list from wildos-live's languages file.
+submenu "Language" --class "wildos-language-$wildos_lang" {
+ set timeout=-1
+ set theme=$theme_dir/language.txt
+@LANGUAGES@
+}
+
submenu "Advanced" --class wildos-advanced {
set timeout=-1
if [ "$grub_platform" = "efi" ]; then
diff --git a/build/patches/kxmlgui/wildos-slim-header.patch b/build/patches/kxmlgui/wildos-slim-header.patch
index 2241a41..8ad3974 100644
--- a/build/patches/kxmlgui/wildos-slim-header.patch
+++ b/build/patches/kxmlgui/wildos-slim-header.patch
@@ -24,15 +24,14 @@ diff -ru a/src/kmainwindow.cpp b/src/kmainwindow.cpp
#include "kactionconflictdetector_p.h"
#include "kcheckaccelerators.h"
-@@ -584,6 +589,49 @@
+@@ -584,6 +589,93 @@
d->autoSaveWindowSize = oldASWS;
}
-+// Wild OS: whether the window has a hamburger menu, which holds the same
-+// menus as the menu bar. Its actions live in the window's action
++// Wild OS: the toolbars holding the window's hamburger menu, which holds
++// the same menus as the menu bar. Its actions live in the window's action
+// collection, which is not a child object of the window.
-+// Whether a hamburger menu is on screen in a toolbar that shows.
-+static bool wildosHamburgerShown(KMainWindow *window)
++static QList<QToolBar *> wildosHamburgerToolBars(KMainWindow *window)
+{
+ QList<KHamburgerMenu *> menus = window->findChildren<KHamburgerMenu *>();
+ if (auto *gui = qobject_cast<KXmlGuiWindow *>(window)) {
@@ -43,18 +42,63 @@ diff -ru a/src/kmainwindow.cpp b/src/kmainwindow.cpp
+ }
+ }
+ }
++ QList<QToolBar *> bars;
+ for (KHamburgerMenu *menu : std::as_const(menus)) {
+ const auto objects = menu->associatedObjects();
+ for (QObject *object : objects) {
-+ auto *bar = qobject_cast<QToolBar *>(object);
-+ if (bar && !bar->isHidden()) {
-+ return true;
++ if (auto *bar = qobject_cast<QToolBar *>(object); bar && !bars.contains(bar)) {
++ bars << bar;
+ }
+ }
+ }
++ return bars;
++}
++
++// Whether a hamburger menu is on screen in a toolbar that shows.
++static bool wildosHamburgerShown(KMainWindow *window)
++{
++ const auto bars = wildosHamburgerToolBars(window);
++ for (QToolBar *bar : bars) {
++ if (!bar->isHidden()) {
++ return true;
++ }
++ }
+ return false;
+}
+
++// Set on a menu bar shown only because no hamburger menu was in sight. Such
++// a menu bar isn't the person's choice: it isn't saved as one, and it goes
++// again once the hamburger's toolbar is back. Without this, hiding the
++// toolbar once brought the stock menu bar back for good.
++static const char wildosFallbackProperty[] = "_wildos_menubar_fallback";
++
++static void wildosShowFallbackMenuBar(QMenuBar *mb)
++{
++ mb->show();
++ mb->setProperty(wildosFallbackProperty, true);
++}
++
++static void wildosFollowHamburgerToolBars(KMainWindow *window, QMenuBar *mb)
++{
++ const auto bars = wildosHamburgerToolBars(window);
++ for (QToolBar *bar : bars) {
++ if (bar->property("_wildos_watched").toBool()) {
++ continue;
++ }
++ bar->setProperty("_wildos_watched", true);
++ QObject::connect(bar, &QToolBar::visibilityChanged, mb, [window, mb] {
++ if (wildosHamburgerShown(window)) {
++ if (mb->property(wildosFallbackProperty).toBool()) {
++ mb->hide();
++ mb->setProperty(wildosFallbackProperty, false);
++ }
++ } else if (mb->isHidden()) {
++ wildosShowFallbackMenuBar(mb);
++ }
++ });
++ }
++}
++
+static bool wildosHasHamburger(KMainWindow *window)
+{
+ if (window->findChild<KHamburgerMenu *>()) {
@@ -74,7 +118,7 @@ diff -ru a/src/kmainwindow.cpp b/src/kmainwindow.cpp
void KMainWindow::saveMainWindowSettings(KConfigGroup &cg)
{
Q_D(KMainWindow);
-@@ -612,7 +660,10 @@
+@@ -612,10 +704,14 @@
QMenuBar *mb = internalMenuBar(this);
if (mb && !mb->isNativeMenuBar()) {
@@ -82,11 +126,16 @@ diff -ru a/src/kmainwindow.cpp b/src/kmainwindow.cpp
+ // Wild OS: the default depends on the window (see below), so a
+ // menu bar shown or hidden against it is written down either way.
+ const bool hiddenByDefault = wildosHasHamburger(this);
-+ if (!cg.hasDefault("MenuBar") && mb->isHidden() == hiddenByDefault) {
++ const bool hidden = mb->isHidden() || mb->property(wildosFallbackProperty).toBool();
++ if (!cg.hasDefault("MenuBar") && hidden == hiddenByDefault) {
cg.revertToDefault("MenuBar");
} else {
- cg.writeEntry("MenuBar", mb->isHidden() ? "Disabled" : "Enabled");
-@@ -725,7 +776,11 @@
+- cg.writeEntry("MenuBar", mb->isHidden() ? "Disabled" : "Enabled");
++ cg.writeEntry("MenuBar", hidden ? "Disabled" : "Enabled");
+ }
+ }
+
+@@ -725,7 +821,11 @@
QMenuBar *mb = internalMenuBar(this);
if (mb && !mb->isNativeMenuBar()) {
@@ -99,16 +148,19 @@ diff -ru a/src/kmainwindow.cpp b/src/kmainwindow.cpp
mb->setVisible(entry != QLatin1String("Disabled"));
}
-@@ -760,6 +815,13 @@
+@@ -760,6 +860,16 @@
d->settingsDirty = false;
d->letDirtySettings = oldLetDirtySettings;
+
+ // Wild OS: the menus must always be reachable. With the menu bar hidden
+ // and no hamburger menu on a toolbar that shows (its toolbar was hidden,
-+ // say), the menu bar comes back.
-+ if (mb && !mb->isNativeMenuBar() && mb->isHidden() && !wildosHamburgerShown(this)) {
-+ mb->show();
++ // say), the menu bar comes back, and follows that toolbar from then on.
++ if (mb && !mb->isNativeMenuBar()) {
++ wildosFollowHamburgerToolBars(this, mb);
++ if (mb->isHidden() && !wildosHamburgerShown(this)) {
++ wildosShowFallbackMenuBar(mb);
++ }
+ }
}
diff --git a/packages/wildos-branding/debian/control b/packages/wildos-branding/debian/control
index 5f81792..d1ceadb 100644
--- a/packages/wildos-branding/debian/control
+++ b/packages/wildos-branding/debian/control
@@ -2,7 +2,7 @@ Source: wildos-branding
Section: x11
Priority: optional
Maintainer: Wild OS Developers <[email protected]>
-Build-Depends: debhelper-compat (= 13), imagemagick, librsvg2-bin, python3, fonts-inter
+Build-Depends: debhelper-compat (= 13), imagemagick, librsvg2-bin, python3, fonts-inter, breeze-cursor-theme
Standards-Version: 4.7.0
Rules-Requires-Root: no
@@ -15,6 +15,7 @@ Depends:
wildos-overlays,
wildos-desktop-view,
breeze,
+ breeze-cursor-theme,
plasma-workspace,
kded6,
libnotify-bin,
diff --git a/packages/wildos-branding/debian/install b/packages/wildos-branding/debian/install
index 3b3aebe..b686eeb 100644
--- a/packages/wildos-branding/debian/install
+++ b/packages/wildos-branding/debian/install
@@ -21,3 +21,4 @@ files/aurorae/WildOSLight/* usr/share/aurorae/themes/WildOSLight/
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/
diff --git a/packages/wildos-branding/debian/postinst b/packages/wildos-branding/debian/postinst
index ddeb4e8..cd06bb1 100644
--- a/packages/wildos-branding/debian/postinst
+++ b/packages/wildos-branding/debian/postinst
@@ -39,6 +39,13 @@ if [ "$1" = "configure" ]; then
fi
fi
+ # The sign-in screen picks up the last person's accessibility choices
+ # through a PAM session step (see /usr/libexec/wildos/greeter-access);
+ # pam-auth-update adds it to common-session without touching the rest.
+ if command -v pam-auth-update >/dev/null; then
+ pam-auth-update --package
+ fi
+
# grub.cfg names the theme, so a system that had none picks it up here.
# The image has no grub.cfg (the installer makes one).
if [ -e /boot/grub/grub.cfg ] && command -v update-grub >/dev/null; then
diff --git a/packages/wildos-branding/debian/postrm b/packages/wildos-branding/debian/postrm
index 9698815..55077b6 100644
--- a/packages/wildos-branding/debian/postrm
+++ b/packages/wildos-branding/debian/postrm
@@ -10,6 +10,12 @@ if [ "$1" = "remove" ] || [ "$1" = "purge" ] || [ "$1" = "abort-install" ]; then
--divert /etc/xdg/arkrc.ark /etc/xdg/arkrc >/dev/null || true
fi
+if [ "$1" = "remove" ] || [ "$1" = "purge" ]; then
+ if command -v pam-auth-update >/dev/null; then
+ pam-auth-update --package --remove wildos-greeter-access
+ fi
+fi
+
# Without this, grub.cfg would go on naming a theme that is no longer there.
if [ "$1" = "remove" ] || [ "$1" = "purge" ]; then
if [ -e /boot/grub/grub.cfg ] && command -v update-grub >/dev/null; then
diff --git a/packages/wildos-branding/debian/rules b/packages/wildos-branding/debian/rules
index bcb1a83..3d158d7 100644
--- a/packages/wildos-branding/debian/rules
+++ b/packages/wildos-branding/debian/rules
@@ -61,6 +61,10 @@ execute_after_dh_install:
{ echo; echo "# Generated at build time from WildOS.colors."; \
awk -f debian/scheme-to-kdeglobals.awk files/WildOS.colors; } \
>> debian/wildos-branding/etc/xdg/kdeglobals
+ # The yellow and sea glass pointers Settings > Accessibility offers,
+ # recoloured from the Breeze Light this is built against so they keep
+ # Breeze's shapes and sizes.
+ python3 tools/cursor-colours.py /usr/share/icons/Breeze_Light debian/wildos-branding/usr/share/icons
# The start-up animation and disk unlock screen, every frame drawn from
# the logo masters and Inter at each screen scale (see the tool for why).
python3 tools/render-boot-assets.py debian/wildos-branding/usr/share/plymouth/themes/wildos \
diff --git a/packages/wildos-branding/files/WildOSHighContrast.colors b/packages/wildos-branding/files/WildOSHighContrast.colors
new file mode 100644
index 0000000..5314fe8
--- /dev/null
+++ b/packages/wildos-branding/files/WildOSHighContrast.colors
@@ -0,0 +1,157 @@
+# The Wild OS high contrast scheme (Settings > Accessibility > High
+# contrast, Super Alt H), after Windows' Aquatic contrast theme: white text
+# on solid black, a bright cyan for selection, focus and links with black
+# text on it, and frames drawn at full contrast. Wild OS's own apps draw
+# their high contrast look from WildOS.UI's Style, which switches when this
+# scheme is applied; this file covers KDE and Qt apps.
+#
+# ink #ffffff ink-muted #c8c8c8 ground #000000
+# accent #75e9fc on-accent #000000 visited #d6b4fd
+
+[ColorEffects:Disabled]
+Color=56,56,56
+ColorAmount=0
+ColorEffect=0
+ContrastAmount=0.45
+ContrastEffect=1
+IntensityAmount=0
+IntensityEffect=0
+
+[ColorEffects:Inactive]
+ChangeSelectionColor=false
+Color=0,0,0
+ColorAmount=0
+ColorEffect=0
+ContrastAmount=0
+ContrastEffect=0
+Enable=false
+IntensityAmount=0
+IntensityEffect=0
+
+[Colors:Button]
+BackgroundAlternate=24,24,24
+BackgroundNormal=0,0,0
+DecorationFocus=117,233,252
+DecorationHover=117,233,252
+ForegroundActive=117,233,252
+ForegroundInactive=200,200,200
+ForegroundLink=117,233,252
+ForegroundNegative=255,128,128
+ForegroundNeutral=255,214,10
+ForegroundNormal=255,255,255
+ForegroundPositive=63,242,63
+ForegroundVisited=214,180,253
+
+[Colors:Complementary]
+BackgroundAlternate=0,0,0
+BackgroundNormal=0,0,0
+DecorationFocus=117,233,252
+DecorationHover=117,233,252
+ForegroundActive=117,233,252
+ForegroundInactive=200,200,200
+ForegroundLink=117,233,252
+ForegroundNegative=255,128,128
+ForegroundNeutral=255,214,10
+ForegroundNormal=255,255,255
+ForegroundPositive=63,242,63
+ForegroundVisited=214,180,253
+
+[Colors:Header]
+BackgroundAlternate=0,0,0
+BackgroundNormal=0,0,0
+DecorationFocus=117,233,252
+DecorationHover=117,233,252
+ForegroundActive=117,233,252
+ForegroundInactive=200,200,200
+ForegroundLink=117,233,252
+ForegroundNegative=255,128,128
+ForegroundNeutral=255,214,10
+ForegroundNormal=255,255,255
+ForegroundPositive=63,242,63
+ForegroundVisited=214,180,253
+
+[Colors:Header][Inactive]
+BackgroundAlternate=0,0,0
+BackgroundNormal=0,0,0
+DecorationFocus=117,233,252
+DecorationHover=117,233,252
+ForegroundActive=117,233,252
+ForegroundInactive=200,200,200
+ForegroundLink=117,233,252
+ForegroundNegative=255,128,128
+ForegroundNeutral=255,214,10
+ForegroundNormal=255,255,255
+ForegroundPositive=63,242,63
+ForegroundVisited=214,180,253
+
+[Colors:Tooltip]
+BackgroundAlternate=0,0,0
+BackgroundNormal=0,0,0
+DecorationFocus=117,233,252
+DecorationHover=117,233,252
+ForegroundActive=117,233,252
+ForegroundInactive=200,200,200
+ForegroundLink=117,233,252
+ForegroundNegative=255,128,128
+ForegroundNeutral=255,214,10
+ForegroundNormal=255,255,255
+ForegroundPositive=63,242,63
+ForegroundVisited=214,180,253
+
+[Colors:View]
+BackgroundAlternate=24,24,24
+BackgroundNormal=0,0,0
+DecorationFocus=117,233,252
+DecorationHover=117,233,252
+ForegroundActive=117,233,252
+ForegroundInactive=200,200,200
+ForegroundLink=117,233,252
+ForegroundNegative=255,128,128
+ForegroundNeutral=255,214,10
+ForegroundNormal=255,255,255
+ForegroundPositive=63,242,63
+ForegroundVisited=214,180,253
+
+[Colors:Window]
+BackgroundAlternate=0,0,0
+BackgroundNormal=0,0,0
+DecorationFocus=117,233,252
+DecorationHover=117,233,252
+ForegroundActive=117,233,252
+ForegroundInactive=200,200,200
+ForegroundLink=117,233,252
+ForegroundNegative=255,128,128
+ForegroundNeutral=255,214,10
+ForegroundNormal=255,255,255
+ForegroundPositive=63,242,63
+ForegroundVisited=214,180,253
+
+[Colors:Selection]
+BackgroundAlternate=95,200,220
+BackgroundNormal=117,233,252
+DecorationFocus=117,233,252
+DecorationHover=117,233,252
+ForegroundActive=0,0,0
+ForegroundInactive=0,0,0
+ForegroundLink=0,0,0
+ForegroundNegative=120,0,0
+ForegroundNeutral=80,60,0
+ForegroundNormal=0,0,0
+ForegroundPositive=0,80,0
+ForegroundVisited=60,0,110
+
+[General]
+ColorScheme=WildOSHighContrast
+Name=Wild OS High Contrast
+shadeSortColumn=false
+
+[KDE]
+contrast=10
+
+[WM]
+activeBackground=0,0,0
+activeBlend=255,255,255
+activeForeground=255,255,255
+inactiveBackground=0,0,0
+inactiveBlend=200,200,200
+inactiveForeground=200,200,200
diff --git a/packages/wildos-branding/files/libexec/greeter-access b/packages/wildos-branding/files/libexec/greeter-access
new file mode 100644
index 0000000..02bfed8
--- /dev/null
+++ b/packages/wildos-branding/files/libexec/greeter-access
@@ -0,0 +1,113 @@
+#!/bin/sh
+# Carries the accessibility choices of whoever signs in or out to the
+# sign-in screen, so someone who needs the screen reader, high contrast, a
+# large pointer or sticky keys finds them already on at the next sign-in,
+# as on Windows. The sign-in screen runs as the sddm user with settings of
+# its own; this copies a fixed list of keys into them. Run as root by
+# pam_exec (the wildos-greeter-access PAM profile) when an SDDM session
+# starts and when it ends, so changes made during the session are there by
+# the time the sign-in screen comes back.
+#
+# Each file is read as the person and written as the sddm user, and every
+# value is checked against what it may hold, so neither account can point
+# root at a file of its choosing or carry anything else across.
+set -u
+
+case "${PAM_SERVICE:-}" in
+ sddm | sddm-autologin) ;;
+ *) exit 0 ;;
+esac
+case "${PAM_TYPE:-}" in
+ open_session | close_session) ;;
+ *) exit 0 ;;
+esac
+
+user=${PAM_USER:-}
+[ -n "$user" ] || exit 0
+entry=$(getent passwd "$user") || exit 0
+uid=$(printf '%s\n' "$entry" | cut -d: -f3)
+home=$(printf '%s\n' "$entry" | cut -d: -f6)
+[ "$uid" -ge 1000 ] 2>/dev/null || exit 0
+[ -d "$home" ] || exit 0
+
+greeter=$(getent passwd sddm) || exit 0
+greeter_home=$(printf '%s\n' "$greeter" | cut -d: -f6)
+[ -d "$greeter_home" ] || exit 0
+
+PATH=/usr/sbin:/usr/bin:/sbin:/bin
+
+as_user() {
+ setpriv --reuid="$user" --regid="$(id -g "$user")" --init-groups -- \
+ env -i HOME="$home" PATH="$PATH" "$@"
+}
+
+as_greeter() {
+ setpriv --reuid=sddm --regid="$(id -g sddm)" --init-groups -- \
+ env -i HOME="$greeter_home" PATH="$PATH" "$@"
+}
+
+read_key() {
+ as_user kreadconfig6 --file "$home/.config/$1" --group "$2" --key "$3" --default "$4" 2>/dev/null
+}
+
+write_key() {
+ as_greeter kwriteconfig6 --file "$greeter_home/.config/$1" --group "$2" --key "$3" "$4" "$5"
+}
+
+# file group key fallback
+copy_bool() {
+ value=$(read_key "$1" "$2" "$3" "$4")
+ case $value in
+ true | false) ;;
+ *) value=$4 ;;
+ esac
+ write_key "$1" "$2" "$3" --type=bool "$value"
+}
+
+# file group key fallback lowest highest
+copy_int() {
+ value=$(read_key "$1" "$2" "$3" "$4")
+ case $value in
+ '' | *[!0-9]*) value=$4 ;;
+ esac
+ if [ "$value" -lt "$5" ] || [ "$value" -gt "$6" ]; then
+ value=$4
+ fi
+ write_key "$1" "$2" "$3" --type=int "$value"
+}
+
+as_greeter mkdir -p "$greeter_home/.config" || exit 0
+
+# Sticky, slow and bounce keys and the screen flash, read by the sign-in
+# screen's KWin; the screen reader, started by the sign-in screen itself.
+copy_bool kaccessrc Keyboard StickyKeys false
+copy_bool kaccessrc Keyboard StickyKeysLatch true
+copy_bool kaccessrc Keyboard SlowKeys false
+copy_int kaccessrc Keyboard SlowKeysDelay 500 50 10000
+copy_bool kaccessrc Keyboard BounceKeys false
+copy_int kaccessrc Keyboard BounceKeysDelay 500 50 10000
+copy_bool kaccessrc Bell VisibleBell false
+copy_bool kaccessrc ScreenReader Enabled false
+copy_bool wildosrc Accessibility OnScreenKeyboard false
+
+# The pointer, only as one of the themes installed here.
+theme=$(read_key kcminputrc Mouse cursorTheme "")
+case $theme in
+ '' | *[!A-Za-z0-9_.-]* | .*) theme= ;;
+esac
+if [ -n "$theme" ] && [ -f "/usr/share/icons/$theme/index.theme" ]; then
+ write_key kcminputrc Mouse cursorTheme --type=string "$theme"
+fi
+copy_int kcminputrc Mouse cursorSize 24 16 256
+
+# High contrast: the sign-in screen has no other colour settings, so its
+# kdeglobals is the scheme itself, or nothing.
+scheme=$(read_key kdeglobals General ColorScheme "")
+current=$(as_greeter kreadconfig6 --file "$greeter_home/.config/kdeglobals" --group General --key ColorScheme --default "" 2>/dev/null)
+if [ "$scheme" = WildOSHighContrast ] && [ -f /usr/share/color-schemes/WildOSHighContrast.colors ]; then
+ as_greeter cp /usr/share/color-schemes/WildOSHighContrast.colors "$greeter_home/.config/kdeglobals"
+elif [ "$current" = WildOSHighContrast ]; then
+ as_greeter rm -f "$greeter_home/.config/kdeglobals"
+fi
+
+exit 0
diff --git a/packages/wildos-branding/files/look-and-feel/contents/lockscreen/LockScreenUi.qml b/packages/wildos-branding/files/look-and-feel/contents/lockscreen/LockScreenUi.qml
index f832989..799aee9 100644
--- a/packages/wildos-branding/files/look-and-feel/contents/lockscreen/LockScreenUi.qml
+++ b/packages/wildos-branding/files/look-and-feel/contents/lockscreen/LockScreenUi.qml
@@ -436,4 +436,29 @@ Item {
}
}
}
+
+ // The accessibility shortcuts from Settings > Accessibility. The lock
+ // screen lets only KWin's magnifier keys through as global shortcuts, so
+ // the rest are caught here and run the same switches as on the desktop.
+ UI.AccessShortcuts {
+ id: access
+ onKeyboardRequested: {
+ if (inputPanel.status !== Loader.Ready)
+ return;
+ mainBlock.mainPasswordBox.forceActiveFocus();
+ inputPanel.showHide();
+ }
+ }
+
+ // Someone who uses the on-screen keyboard gets it here straight away.
+ Timer {
+ running: access.keyboardOn
+ interval: 300
+ onTriggered: {
+ if (inputPanel.status === Loader.Ready && !inputPanel.keyboardActive) {
+ mainBlock.mainPasswordBox.forceActiveFocus();
+ inputPanel.showHide();
+ }
+ }
+ }
}
diff --git a/packages/wildos-branding/files/pam-configs/wildos-greeter-access b/packages/wildos-branding/files/pam-configs/wildos-greeter-access
new file mode 100644
index 0000000..e7cf39f
--- /dev/null
+++ b/packages/wildos-branding/files/pam-configs/wildos-greeter-access
@@ -0,0 +1,7 @@
+Name: Wild OS sign-in screen accessibility (carries the last person's choices to the sign-in screen)
+Default: yes
+Priority: 0
+Session-Type: Additional
+Session-Interactive-Only: yes
+Session:
+ optional pam_exec.so quiet /usr/libexec/wildos/greeter-access
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.start/contents/ui/code/helpers.js b/packages/wildos-branding/files/plasmoids/org.wildos.start/contents/ui/code/helpers.js
index dbbf909..4ecadcb 100644
--- a/packages/wildos-branding/files/plasmoids/org.wildos.start/contents/ui/code/helpers.js
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.start/contents/ui/code/helpers.js
@@ -31,9 +31,8 @@ function isCoreApp(favoriteId) {
// KDE settings modules as a Windows user would know them: the page title,
// the Settings category it lives in, and the Wild OS Settings page to open.
// Modules missing from this list are developer or Plasma internals, or have
-// no Wild OS Settings page yet (accessibility, phone link, firewall and the
-// like), and are left out of search rather than landing on a page that does
-// not show them.
+// no Wild OS Settings page yet (phone link, firewall and the like), and are
+// left out of search rather than landing on a page that does not show them.
const settingsPages = {
"kcm_kscreen": ["Display", "System", "display"],
"kcm_nightlight": ["Night light", "System › Display", "nightlight"],
@@ -55,7 +54,9 @@ const settingsPages = {
"kcm_lookandfeel": ["Themes", "Personalisation", "personalisation"],
"kcm_colors": ["Colours", "Personalisation", "colours"],
"kcm_fonts": ["Fonts", "Personalisation", "fonts"],
- "kcm_cursortheme": ["Mouse pointer", "Personalisation", "mouse"],
+ "kcm_cursortheme": ["Mouse pointer", "Accessibility", "accessibility"],
+ "kcm_access": ["Accessibility", "Settings", "accessibility"],
+ "kcm_virtualkeyboard": ["On-screen keyboard", "Accessibility", "accessibility"],
"kcm_screenlocker": ["Lock screen", "Personalisation", "lockscreen"],
"kcm_componentchooser": ["Default apps", "Apps", "defaultapps"],
"kcm_autostart": ["Startup apps", "Apps", "startup"],
@@ -64,6 +65,21 @@ const settingsPages = {
"kcm_clock": ["Date and time", "Time and language", "datetime"],
"kcm_flatpak": ["App permissions", "Privacy and security", "apppermissions"],
"kcm_app-permissions": ["App permissions", "Privacy and security", "apppermissions"],
+ "kcm_kwin_virtualdesktops": ["Desktops", "System › Multitasking", "desktops"],
+ "kcm_device_automounter": ["AutoPlay", "Bluetooth and devices", "autoplay"],
+ "kcm_gamecontroller": ["Game controllers", "Bluetooth and devices", "gamecontrollers"],
+ "kcm_tablet": ["Pen and tablet", "Bluetooth and devices", "pen"],
+ "kcm_touchscreen": ["Touchscreen", "Bluetooth and devices", "touchscreen"],
+ "kcm_bolt": ["Thunderbolt", "Bluetooth and devices", "thunderbolt"],
+ "kcm_fontinst": ["Fonts", "Personalisation", "fonts"],
+ "kcmspellchecking": ["Typing", "Time and language", "typing"],
+ "kcm_filetypes": ["Default apps by file type", "Apps › Default apps", "filetypes"],
+ "kcm_smserver": ["Sign-in options", "Accounts", "signin"],
+ "kcm_baloofile": ["Searching files", "Privacy and security", "searching"],
+ "kcm_recentFiles": ["Activity history", "Privacy and security", "activityhistory"],
+ "kcm_kwinxwayland": ["Old app compatibility", "Apps", "oldapps"],
+ "kcm_access": ["Accessibility", "Settings", "accessibility"],
+ "kcm_virtualkeyboard": ["On-screen keyboard", "Accessibility", "accessibility"],
};
function settingsPage(url) {
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/config/main.xml b/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/config/main.xml
index 100c5d5..323b670 100644
--- a/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/config/main.xml
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/config/main.xml
@@ -30,5 +30,9 @@
<entry name="minimizeActiveTaskOnClick" type="Bool">
<default>true</default>
</entry>
+ <entry name="showOnlyCurrentDesktop" type="Bool">
+ <label>Show only the windows on the desktop in use. Settings, Multitasking changes it.</label>
+ <default>true</default>
+ </entry>
</group>
</kcfg>
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.qml
index 41f86a5..a30fbbb 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
@@ -124,7 +124,7 @@ PlasmoidItem {
screenGeometry: Plasmoid.containment.screenGeometry
activity: activityInfo.currentActivity
- filterByVirtualDesktop: true
+ filterByVirtualDesktop: Plasmoid.configuration.showOnlyCurrentDesktop
filterByScreen: false
filterByActivity: true
diff --git a/packages/wildos-branding/files/plymouth/wildos/wildos.script b/packages/wildos-branding/files/plymouth/wildos/wildos.script
index caa87e8..4de2972 100644
--- a/packages/wildos-branding/files/plymouth/wildos/wildos.script
+++ b/packages/wildos-branding/files/plymouth/wildos/wildos.script
@@ -190,7 +190,7 @@ for (i = 0; i < BULLET_MAX; i++)
bullets[i] = place("bullet.png", -145 + 10 * i, 20, 21);
# The W after unlocking: the glide out of the tile, then its own loop.
-glide = place("", -50, -205, 22);
+glide = place("", -85, -205, 22);
glide_k = -1;
fill_u = place("fill-u.png", -100, -85, 22);
base_u = place("base-u.png", -100, -85, 23);
diff --git a/packages/wildos-branding/files/sddm/wildos/Main.qml b/packages/wildos-branding/files/sddm/wildos/Main.qml
index f63d0e4..fe89cf4 100644
--- a/packages/wildos-branding/files/sddm/wildos/Main.qml
+++ b/packages/wildos-branding/files/sddm/wildos/Main.qml
@@ -518,5 +518,26 @@ Item {
easing.type: UI.Style.easeExit
}
- Component.onCompleted: focusPassword()
+ // The accessibility shortcuts from Settings > Accessibility, here before
+ // anyone has signed in. This screen's KWin has no global shortcuts, so
+ // the magnifier keys are handled here too. What the last person to sign
+ // out left on is copied to this screen's own settings
+ // (/usr/libexec/wildos/greeter-access), so it comes back on here.
+ UI.AccessShortcuts {
+ id: access
+ magnifier: true
+ onKeyboardRequested: {
+ if (keyboardLoader.item)
+ keyboardButton.clicked();
+ }
+ }
+
+ Component.onCompleted: {
+ focusPassword();
+ access.restore();
+ if (access.keyboardOn && keyboardLoader.item) {
+ keyboardLoader.item.wanted = true;
+ Qt.inputMethod.show();
+ }
+ }
}
diff --git a/packages/wildos-branding/files/xdg/kwinrc b/packages/wildos-branding/files/xdg/kwinrc
index 0388aa4..9fe6f8f 100644
--- a/packages/wildos-branding/files/xdg/kwinrc
+++ b/packages/wildos-branding/files/xdg/kwinrc
@@ -40,3 +40,10 @@ OutScale=0.96
[Effect-slidingpopups]
SlideInTime=200
SlideOutTime=150
+
+# Older (X11) apps may not see what is typed into other apps unless the
+# person allows it in Settings > Apps > Old app compatibility. KWin's own
+# default lets them see keys pressed with Ctrl, Alt or the Windows key.
+[Xwayland]
+XwaylandEavesdrops=None
+XwaylandEavesdropsMouse=false
diff --git a/packages/wildos-branding/tools/cursor-colours.py b/packages/wildos-branding/tools/cursor-colours.py
new file mode 100644
index 0000000..a5544bc
--- /dev/null
+++ b/packages/wildos-branding/tools/cursor-colours.py
@@ -0,0 +1,131 @@
+#!/usr/bin/env python3
+"""Builds the coloured pointer themes Settings > Accessibility offers.
+
+Usage: cursor-colours.py SOURCE_THEME_DIR OUTPUT_ICONS_DIR
+
+Breeze Light (white with a dark edge) is copied once per colour with its
+white fill turned into that colour, in both forms KWin and apps read: the
+SVG cursors (cursors_scalable, which KWin draws at any size) and the
+X cursor images (cursors, for X11 apps under Xwayland). The dark edge,
+the shadow and anything already coloured, such as the busy spinner, are
+kept, so every shape stays as easy to see as Breeze's own.
+
+Generated at build time from the Breeze Light the package is built
+against, so the pointers follow Breeze's shapes as it is updated.
+"""
+
+import os
+import re
+import shutil
+import struct
+import sys
+
+THEMES = {
+ "WildOS-Yellow": ("Wild OS Yellow", (0xF2, 0xD3, 0x4A)),
+ "WildOS-SeaGlass": ("Wild OS Sea Glass", (0x7F, 0xD6, 0xC8)),
+}
+
+XCURSOR_IMAGE = 0xFFFD0002
+
+# White and the near whites Breeze uses for a fill, in an SVG attribute or
+# style declaration.
+SVG_WHITE = re.compile(
+ r'((?:fill|stop-color)\s*[:=]\s*"?\s*)#(?:fff|ffffff|fcfcfc|fdfdfd|fefefe)\b',
+ re.IGNORECASE,
+)
+
+
+def smoothstep(edge0, edge1, x):
+ t = min(1.0, max(0.0, (x - edge0) / (edge1 - edge0)))
+ return t * t * (3 - 2 * t)
+
+
+def recolour_pixel(argb, colour):
+ a = argb >> 24
+ if a == 0:
+ return argb
+ # Xcursor pixels are premultiplied.
+ r = min(255, ((argb >> 16) & 0xFF) * 255 // a)
+ g = min(255, ((argb >> 8) & 0xFF) * 255 // a)
+ b = min(255, (argb & 0xFF) * 255 // a)
+ if max(r, g, b) - min(r, g, b) > 24:
+ return argb
+ # Light greys move towards the colour, the dark edge stays; the
+ # anti-aliased pixels in between blend, so edges stay smooth.
+ t = smoothstep(0.35, 0.95, (r + g + b) / 765.0)
+ nr, ng, nb = (round(c + (k - c) * t) for c, k in zip((r, g, b), colour))
+ return (a << 24) | ((nr * a // 255) << 16) | ((ng * a // 255) << 8) | (nb * a // 255)
+
+
+def recolour_xcursor(path, colour):
+ with open(path, "rb") as f:
+ data = bytearray(f.read())
+ if data[:4] != b"Xcur":
+ return
+ header, _version, ntoc = struct.unpack_from("<III", data, 4)
+ for i in range(ntoc):
+ chunk_type, _subtype, position = struct.unpack_from("<III", data, header + i * 12)
+ if chunk_type != XCURSOR_IMAGE:
+ continue
+ chunk_header, _t, _s, _v, width, height = struct.unpack_from("<IIIIII", data, position)
+ start = position + chunk_header
+ for p in range(width * height):
+ offset = start + p * 4
+ (pixel,) = struct.unpack_from("<I", data, offset)
+ struct.pack_into("<I", data, offset, recolour_pixel(pixel, colour))
+ with open(path, "wb") as f:
+ f.write(data)
+
+
+def recolour_svg(path, colour):
+ with open(path, encoding="utf-8") as f:
+ text = f.read()
+ hex_colour = "#%02x%02x%02x" % colour
+ changed = SVG_WHITE.sub(lambda m: m.group(1) + hex_colour, text)
+ if changed != text:
+ with open(path, "w", encoding="utf-8") as f:
+ f.write(changed)
+
+
+def build(source, output, name, title, colour):
+ target = os.path.join(output, name)
+ if os.path.exists(target):
+ shutil.rmtree(target)
+ os.makedirs(target)
+ for sub in ("cursors", "cursors_scalable"):
+ src = os.path.join(source, sub)
+ if os.path.isdir(src):
+ # Aliases are symbolic links in Breeze and stay links here.
+ shutil.copytree(src, os.path.join(target, sub), symlinks=True)
+ for root, _dirs, files in os.walk(target):
+ for file in files:
+ path = os.path.join(root, file)
+ if os.path.islink(path):
+ continue
+ if os.path.basename(root) == "cursors":
+ recolour_xcursor(path, colour)
+ elif file.endswith(".svg"):
+ recolour_svg(path, colour)
+ with open(os.path.join(target, "index.theme"), "w", encoding="utf-8") as f:
+ f.write(
+ "[Icon Theme]\n"
+ f"Name={title}\n"
+ "Comment=Breeze Light pointers in a colour that stands out, from Settings > Accessibility\n"
+ "Inherits=Breeze_Light\n"
+ )
+ # Some toolkits only look for cursor.theme.
+ shutil.copyfile(os.path.join(target, "index.theme"), os.path.join(target, "cursor.theme"))
+
+
+def main():
+ if len(sys.argv) != 3:
+ sys.exit(__doc__)
+ source, output = sys.argv[1], sys.argv[2]
+ if not os.path.isdir(os.path.join(source, "cursors")):
+ sys.exit(f"{source} has no cursors")
+ for name, (title, colour) in THEMES.items():
+ build(source, output, name, title, colour)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/packages/wildos-branding/tools/grub-theme.sh b/packages/wildos-branding/tools/grub-theme.sh
index 15e8507..c87833b 100644
--- a/packages/wildos-branding/tools/grub-theme.sh
+++ b/packages/wildos-branding/tools/grub-theme.sh
@@ -23,7 +23,7 @@ set -euo pipefail
shopt -u patsub_replacement 2>/dev/null || true
usage() {
- echo "usage: grub-theme.sh usb <theme dir> <logo svg> <version>" >&2
+ echo "usage: grub-theme.sh usb <theme dir> <logo svg> <version> <languages file>" >&2
echo " grub-theme.sh installed <theme dir> <logo svg>" >&2
exit 2
}
@@ -32,7 +32,7 @@ mode=$1
out=$2
logo=$3
case $mode in
- usb) [ $# -eq 4 ] || usage; version=$4 ;;
+ usb) [ $# -eq 5 ] || usage; version=$4; languages=$5 ;;
installed) [ $# -eq 3 ] || usage ;;
*) usage ;;
esac
@@ -99,6 +99,13 @@ if [ "$mode" = usb ]; then
item wildos-install 600 "Install Wild OS" "Set up Wild OS on this computer"
item wildos-try 500 "Try Wild OS" "Use it from the USB stick. Nothing on your computer changes."
item wildos-check 500 "Check this USB stick" "Looks for download or copying errors first"
+ # The Language entry names the language in use, so there is one picture
+ # per language; each language in the list is named in itself.
+ while IFS=$' ' read -r code _ native english; do
+ case $code in '#'* | '') continue ;; esac
+ item "wildos-language-$code" 500 "Language" "$native"
+ item "wildos-lang-$code" 500 "$native" "$english"
+ done < "$languages"
item wildos-advanced 500 "Advanced" "Safe graphics, other options"
item wildos-install-safe 500 "Install with safe graphics" "Use this if the screen stays black or garbled"
item wildos-try-safe 500 "Try with safe graphics" "The same fix, without installing anything"
@@ -347,6 +354,8 @@ EOF
menu $((menu_h + 6))
} > "$out/$1"
}
-theme theme.txt hint.png 4 yes
+theme theme.txt hint.png 5 yes
theme advanced-efi.txt hint-advanced.png 4 no
theme advanced-pc.txt hint-advanced.png 3 no
+# The language list scrolls past six.
+theme language.txt hint-advanced.png 6 no
diff --git a/packages/wildos-branding/tools/render-boot-assets.py b/packages/wildos-branding/tools/render-boot-assets.py
index b2382d1..4266d25 100644
--- a/packages/wildos-branding/tools/render-boot-assets.py
+++ b/packages/wildos-branding/tools/render-boot-assets.py
@@ -194,8 +194,10 @@ COMPLETE_FRAMES = 46
STATUS_TOP = {"i": 50 + 30 * 1.2109375 + 30 - 62, "u": 548 - 450}
STATUS_CANVAS = {"i": (-100, 50, 200, 25), "u": (-100, 95, 200, 25)}
-# The glide from the tile to the glass W: 1 s at 50 frames a second.
-GLIDE_CANVAS = (-50, -205, 135, 255)
+# The glide from the tile to the glass W: 1 s at 50 frames a second. The
+# canvas spans where the W ends up (78px either side of centre), or its left
+# side was cut off until the finished W took over.
+GLIDE_CANVAS = (-85, -205, 170, 255)
GLIDE_FRAMES = 50
TILE_CANVAS = (-45, -200, 90, 90)
diff --git a/packages/wildos-desktop/debian/postinst b/packages/wildos-desktop/debian/postinst
index 5a5d765..671e6f1 100644
--- a/packages/wildos-desktop/debian/postinst
+++ b/packages/wildos-desktop/debian/postinst
@@ -4,7 +4,9 @@ set -e
# Kicksecure's desktop helpers are built for its own LXQt desktop and show
# technical pop-ups (system check warnings, update checks, a deprecation
# notice, a time-sync tray icon, and a display resize helper written for
-# wlroots desktops that fails and restarts every few seconds under KWin).
+# wlroots desktops that fails and restarts every few seconds under KWin,
+# and a shared-folder bookmark for virtual machines that fails at every
+# sign-in on a real computer).
# Wild OS surfaces the same information in
# plain English through the security chip and the Store, so the helpers are
# taken out of autostart. A diversion survives updates of the packages that
@@ -18,6 +20,7 @@ systemcheck.desktop
updatecheck.desktop
sdwdate-gui.desktop
wlr-resize-watcher.desktop
+config-mnt-shared-bookmark.desktop
"
if [ "$1" = "triggered" ]; then
diff --git a/packages/wildos-desktop/debian/postrm b/packages/wildos-desktop/debian/postrm
index d800edf..d5ad023 100644
--- a/packages/wildos-desktop/debian/postrm
+++ b/packages/wildos-desktop/debian/postrm
@@ -9,6 +9,7 @@ systemcheck.desktop
updatecheck.desktop
sdwdate-gui.desktop
wlr-resize-watcher.desktop
+config-mnt-shared-bookmark.desktop
"
if [ "$1" = "remove" ] || [ "$1" = "purge" ]; then
diff --git a/packages/wildos-desktop/debian/rules b/packages/wildos-desktop/debian/rules
index 13248bc..919df4e 100644
--- a/packages/wildos-desktop/debian/rules
+++ b/packages/wildos-desktop/debian/rules
@@ -13,6 +13,10 @@ execute_after_dh_install:
install -Dm644 files/brave/managed.json debian/wildos-desktop/etc/brave/policies/managed/wildos.json
install -Dm644 files/brave/recommended.json debian/wildos-desktop/etc/brave/policies/recommended/wildos.json
install -Dm755 files/brave/brave-browser-stable debian/wildos-desktop/usr/bin/brave-browser-stable
+ # Sponsored new tab backgrounds have no policy, only a preference, so
+ # every new profile starts with them off. Brave reads this file from
+ # beside its own binary and ships none of its own.
+ install -Dm644 files/brave/initial_preferences debian/wildos-desktop/opt/brave.com/brave/initial_preferences
execute_after_dh_fixperms:
chmod 0755 debian/wildos-desktop/usr/libexec/wildos/wildos-app-names \
diff --git a/packages/wildos-desktop/files/brave/initial_preferences b/packages/wildos-desktop/files/brave/initial_preferences
new file mode 100644
index 0000000..964008d
--- /dev/null
+++ b/packages/wildos-desktop/files/brave/initial_preferences
@@ -0,0 +1,12 @@
+{
+ "brave": {
+ "brave_ads": {
+ "sponsored": {
+ "enabled": false
+ }
+ },
+ "new_tab_page": {
+ "show_branded_background_image": false
+ }
+ }
+}
diff --git a/packages/wildos-live/debian/install b/packages/wildos-live/debian/install
index 4f1eb59..8aaede4 100644
--- a/packages/wildos-live/debian/install
+++ b/packages/wildos-live/debian/install
@@ -5,3 +5,6 @@ files/session/wildos-live.desktop usr/share/wayland-sessions/
files/session/live-session usr/libexec/wildos-live/
files/dev/wildos-dev-only.conf usr/lib/systemd/system/qemu-guest-agent.service.d/
files/systemd/wildos-live.conf etc/systemd/system/sddm.service.d/
+files/session/live-language usr/libexec/wildos-live/
+files/languages usr/share/wildos-live/
+files/systemd/wildos-live-language.service usr/lib/systemd/system/
diff --git a/packages/wildos-live/debian/links b/packages/wildos-live/debian/links
new file mode 100644
index 0000000..b02675a
--- /dev/null
+++ b/packages/wildos-live/debian/links
@@ -0,0 +1 @@
+usr/lib/systemd/system/wildos-live-language.service etc/systemd/system/multi-user.target.wants/wildos-live-language.service
diff --git a/packages/wildos-live/debian/rules b/packages/wildos-live/debian/rules
index 0de7330..1ddae13 100644
--- a/packages/wildos-live/debian/rules
+++ b/packages/wildos-live/debian/rules
@@ -5,4 +5,4 @@
# The build normalises every source file to 0644.
execute_after_dh_fixperms:
- chmod 0755 debian/wildos-live/usr/libexec/wildos-live/live-session
+ chmod 0755 debian/wildos-live/usr/libexec/wildos-live/live-session debian/wildos-live/usr/libexec/wildos-live/live-language
diff --git a/packages/wildos-live/files/languages b/packages/wildos-live/files/languages
new file mode 100644
index 0000000..d935dd5
--- /dev/null
+++ b/packages/wildos-live/files/languages
@@ -0,0 +1,23 @@
+# The languages the USB start-up menu offers. One per line, tab separated:
+# locale, keyboard layout (XKB, a second one for typing in Latin letters),
+# the name in that language, and in English. The first is the default.
+# build.sh makes the menu from this file, the image build generates each
+# locale, and wildos-live-language applies the one chosen.
+en_GB gb English (UK) English (UK)
+en_US us English (US) English (US)
+de_DE de Deutsch German
+fr_FR fr Français French
+es_ES es Español Spanish
+it_IT it Italiano Italian
+nl_NL us Nederlands Dutch
+pt_PT pt Português Portuguese
+pt_BR br Português (Brasil) Portuguese (Brazil)
+pl_PL pl Polski Polish
+sv_SE se Svenska Swedish
+nb_NO no Norsk Norwegian
+da_DK dk Dansk Danish
+fi_FI fi Suomi Finnish
+cs_CZ cz Čeština Czech
+tr_TR tr Türkçe Turkish
+el_GR us,gr Ελληνικά Greek
+uk_UA us,ua Українська Ukrainian
diff --git a/packages/wildos-live/files/session/live-language b/packages/wildos-live/files/session/live-language
new file mode 100644
index 0000000..0a5130d
--- /dev/null
+++ b/packages/wildos-live/files/session/live-language
@@ -0,0 +1,27 @@
+#!/bin/sh
+# Applies the language picked on the USB start-up menu, which GRUB passes as
+# wildos.lang=de_DE. It runs before the display manager, so the live desktop
+# and the installer start in it, and the installer takes the language and
+# keyboard from the live session for the computer it installs. Only a
+# language from the menu's own list is accepted.
+set -eu
+
+list=/usr/share/wildos-live/languages
+want=$(tr ' ' '\n' < /proc/cmdline | sed -n 's/^wildos\.lang=//p' | tail -n 1)
+[ -n "$want" ] || exit 0
+
+line=$(grep -v '^#' "$list" | awk -F '\t' -v want="$want" '$1 == want { print; exit }')
+[ -n "$line" ] || exit 0
+layout=$(printf '%s' "$line" | cut -f 2)
+
+update-locale LANG="$want.UTF-8"
+if [ -f /etc/default/keyboard ]; then
+ sed -i "s/^XKBLAYOUT=.*/XKBLAYOUT=\"$layout\"/" /etc/default/keyboard
+else
+ printf 'XKBMODEL="pc105"\nXKBLAYOUT="%s"\n' "$layout" > /etc/default/keyboard
+fi
+# A second layout is only there for typing addresses and passwords in Latin
+# letters; Alt+Shift switches, as on Windows.
+case $layout in
+ *,*) sed -i 's/^XKBOPTIONS=.*/XKBOPTIONS="grp:alt_shift_toggle"/' /etc/default/keyboard ;;
+esac
diff --git a/packages/wildos-live/files/systemd/wildos-live-language.service b/packages/wildos-live/files/systemd/wildos-live-language.service
new file mode 100644
index 0000000..c433550
--- /dev/null
+++ b/packages/wildos-live/files/systemd/wildos-live-language.service
@@ -0,0 +1,13 @@
+[Unit]
+Description=Wild OS live language from the start-up menu
+DefaultDependencies=no
+After=local-fs.target
+Before=display-manager.service sddm.service systemd-localed.service
+ConditionKernelCommandLine=wildos.lang
+
+[Service]
+Type=oneshot
+ExecStart=/usr/libexec/wildos-live/live-language
+
+[Install]
+WantedBy=multi-user.target
diff --git a/packages/wildos-settings/CMakeLists.txt b/packages/wildos-settings/CMakeLists.txt
index 8fcc29a..68e4c5b 100644
--- a/packages/wildos-settings/CMakeLists.txt
+++ b/packages/wildos-settings/CMakeLists.txt
@@ -5,15 +5,20 @@ set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
include(GNUInstallDirs)
-find_package(Qt6 6.8 REQUIRED COMPONENTS Core Gui Widgets DBus Qml Quick QuickControls2)
+find_package(Qt6 6.8 REQUIRED COMPONENTS Core Gui Widgets DBus Network Qml Quick QuickControls2)
find_package(KF6KCMUtils REQUIRED)
find_package(KF6Config REQUIRED)
find_package(KF6CoreAddons REQUIRED)
find_package(KF6Service REQUIRED)
find_package(KF6I18n REQUIRED)
find_package(KF6ColorScheme REQUIRED)
+find_package(KF6Sonnet REQUIRED)
+find_package(KF6Screen REQUIRED)
+find_package(KF6NetworkManagerQt REQUIRED)
+find_package(KF6GlobalAccel REQUIRED)
find_package(packagekitqt6 REQUIRED)
find_package(Cups REQUIRED)
+find_package(SDL2 2.0.16 REQUIRED)
find_package(PkgConfig REQUIRED)
pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0)
@@ -48,15 +53,33 @@ qt_add_qml_module(wildos-settings
src/users.cpp src/users.h
src/language.cpp src/language.h
src/appaccess.cpp src/appaccess.h
+ src/poweroptions.cpp src/poweroptions.h
+ src/appnotifications.cpp src/appnotifications.h
+ src/desktops.cpp src/desktops.h
+ src/autoplay.cpp src/autoplay.h
+ src/gamecontrollers.cpp src/gamecontrollers.h
+ src/thunderbolt.cpp src/thunderbolt.h
+ src/spelling.cpp src/spelling.h
+ src/fonts.cpp src/fonts.h
+ src/display.cpp src/display.h
+ src/filesearch.cpp src/filesearch.h
+ src/activityhistory.cpp src/activityhistory.h
+ src/olderapps.cpp src/olderapps.h
+ src/network.cpp src/network.h src/netshared.h
+ src/accessibility.cpp src/accessibility.h
+ src/accesscore.cpp src/accesscore.h
)
target_include_directories(wildos-settings PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
target_link_libraries(wildos-settings PRIVATE
- Qt6::Widgets Qt6::DBus Qt6::Qml Qt6::Quick Qt6::QuickControls2
- KF6::KCMUtils KF6::KCMUtilsQuick KF6::ConfigCore KF6::CoreAddons KF6::Service KF6::I18n KF6::ColorScheme
+ Qt6::Widgets Qt6::DBus Qt6::Network Qt6::Qml Qt6::Quick Qt6::QuickControls2
+ KF6::KCMUtils KF6::KCMUtilsQuick KF6::ConfigCore KF6::CoreAddons KF6::Service KF6::I18n KF6::ColorScheme KF6::SonnetCore
+ KF6::Screen
+ KF6::NetworkManagerQt
PK::packagekitqt6
Cups::Cups
+ SDL2::SDL2
PkgConfig::GLIB
util
)
@@ -65,7 +88,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 DESTINATION ${CMAKE_INSTALL_PREFIX}/libexec/wildos)
+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(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 the
@@ -74,5 +97,28 @@ qt_add_executable(wildos-auto-theme src/autotheme/main.cpp src/autotheme/sun.h)
target_link_libraries(wildos-auto-theme PRIVATE Qt6::Core Qt6::Gui Qt6::DBus KF6::ConfigCore)
install(TARGETS wildos-auto-theme RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
install(FILES data/org.wildos.auto-theme.desktop DESTINATION ${CMAKE_INSTALL_SYSCONFDIR}/xdg/autostart)
+# The accessibility shortcuts: a service in every session and the switches
+# the lock and sign-in screens run. It shares AccessCore with Settings so a
+# shortcut and its switch do the same thing.
+qt_add_executable(wildos-access src/access/main.cpp src/accesscore.cpp src/accesscore.h)
+target_include_directories(wildos-access PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
+target_link_libraries(wildos-access PRIVATE Qt6::Core Qt6::Gui Qt6::DBus KF6::ConfigCore KF6::GlobalAccel)
+install(TARGETS wildos-access RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
+install(FILES data/org.wildos.access.desktop DESTINATION ${CMAKE_INSTALL_SYSCONFDIR}/xdg/autostart)
+# Mono audio: a PipeWire filter run as its own user service.
+install(FILES data/wildos-mono-audio.conf DESTINATION ${CMAKE_INSTALL_DATADIR}/pipewire)
+install(FILES data/wildos-mono-audio.service DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/systemd/user)
# Loads the firewall for a Strict or Maximum protection level at start-up.
install(FILES data/wildos-protection.service DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/systemd/system)
+
+# The root half of Advanced network settings: encrypted DNS for each new
+# network and the VPN kill switch. A system service, so it carries none of
+# the Settings app's QML or KDE dependencies.
+qt_add_executable(wildos-network src/networkd/main.cpp src/netshared.h)
+target_include_directories(wildos-network PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
+target_link_libraries(wildos-network PRIVATE Qt6::Core Qt6::DBus Qt6::Network)
+install(TARGETS wildos-network RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/libexec/wildos)
+install(FILES data/wildos-network.service DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/systemd/system)
+install(FILES data/org.wildos.Network.conf DESTINATION ${CMAKE_INSTALL_DATADIR}/dbus-1/system.d)
+install(FILES data/90-wildos-network.conf DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/NetworkManager/conf.d)
+install(FILES data/60-wildos-resolved.conf DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/systemd/resolved.conf.d)
diff --git a/packages/wildos-settings/data/60-wildos-resolved.conf b/packages/wildos-settings/data/60-wildos-resolved.conf
new file mode 100644
index 0000000..74bf6ae
--- /dev/null
+++ b/packages/wildos-settings/data/60-wildos-resolved.conf
@@ -0,0 +1,9 @@
+# Wild OS (wildos-settings). Each network's DNS servers, Quad9 over TLS by
+# default, come from NetworkManager. Names on the local network are found
+# with Avahi, so systemd-resolved does not answer multicast DNS itself, and
+# LLMNR, which broadcasts every name looked up, stays off.
+[Resolve]
+LLMNR=no
+MulticastDNS=no
+# Only used when no network offers any servers.
+FallbackDNS=9.9.9.9#dns.quad9.net 149.112.112.112#dns.quad9.net 2620:fe::fe#dns.quad9.net 2620:fe::9#dns.quad9.net
diff --git a/packages/wildos-settings/data/90-wildos-network.conf b/packages/wildos-settings/data/90-wildos-network.conf
new file mode 100644
index 0000000..ebf02cd
--- /dev/null
+++ b/packages/wildos-settings/data/90-wildos-network.conf
@@ -0,0 +1,22 @@
+# Wild OS network defaults (wildos-settings). Settings > Network and
+# internet > Advanced network settings changes them network by network.
+
+[main]
+# Lookups go through systemd-resolved, which can encrypt them (DNS over
+# TLS). wildos-network gives each new network Quad9 over TLS.
+dns=systemd-resolved
+
+[connection-wildos-private-address]
+# Private hardware address, as GrapheneOS does it: Wi-Fi shows a new random
+# address every time it connects, so no network can recognise this computer
+# from one visit or place to the next. Wired networks get a random address
+# of their own each, kept between visits, so office ports and home address
+# reservations keep working. Settings turns it off network by network.
+wifi.cloned-mac-address=random
+ethernet.cloned-mac-address=stable
+# The computer's name isn't announced to the network either.
+ipv4.dhcp-send-hostname=false
+ipv6.dhcp-send-hostname=false
+# IPv6 uses short-lived addresses for outgoing connections, rather than one
+# that stays the same everywhere.
+ipv6.ip6-privacy=2
diff --git a/packages/wildos-settings/data/kde-settings-redirect b/packages/wildos-settings/data/kde-settings-redirect
new file mode 100644
index 0000000..a51a77d
--- /dev/null
+++ b/packages/wildos-settings/data/kde-settings-redirect
@@ -0,0 +1,24 @@
+#!/bin/sh
+# Stands in for KDE's systemsettings and kcmshell6. KDE apps and Plasma open
+# those to show a settings module (a notification's Configure button,
+# Spectacle's shortcut settings), which would put KDE's own pages in front
+# of people. Settings knows every KDE module name and opens the Wild OS page
+# for it, so the module named here goes there instead.
+page=
+while [ $# -gt 0 ]; do
+ case $1 in
+ --args | --icon | --caption | --lang | -platform | --platform | -qwindowtitle | --qwindowtitle)
+ shift
+ ;;
+ -*) ;;
+ *)
+ [ -z "$page" ] && page=$1
+ ;;
+ esac
+ [ $# -gt 0 ] && shift
+done
+page=${page%.desktop}
+if [ -n "$page" ]; then
+ exec wildos-settings --page "$page"
+fi
+exec wildos-settings
diff --git a/packages/wildos-settings/data/org.wildos.Network.conf b/packages/wildos-settings/data/org.wildos.Network.conf
new file mode 100644
index 0000000..81b31fe
--- /dev/null
+++ b/packages/wildos-settings/data/org.wildos.Network.conf
@@ -0,0 +1,14 @@
+<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
+ "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
+<!-- wildos-network (root). Anyone may tell it that they switched a VPN
+ off on purpose (Release), which they could equally do through
+ NetworkManager; nothing else is offered. -->
+<busconfig>
+ <policy user="root">
+ <allow own="org.wildos.Network"/>
+ </policy>
+ <policy context="default">
+ <allow send_destination="org.wildos.Network" send_interface="org.wildos.Network" send_member="Release"/>
+ <allow send_destination="org.wildos.Network" send_interface="org.freedesktop.DBus.Introspectable"/>
+ </policy>
+</busconfig>
diff --git a/packages/wildos-settings/data/org.wildos.access.desktop b/packages/wildos-settings/data/org.wildos.access.desktop
new file mode 100644
index 0000000..427c314
--- /dev/null
+++ b/packages/wildos-settings/data/org.wildos.access.desktop
@@ -0,0 +1,8 @@
+[Desktop Entry]
+Type=Application
+Name=Accessibility shortcuts
+Comment=High contrast, the on-screen keyboard and sticky keys from the keyboard
+Exec=/usr/bin/wildos-access
+NoDisplay=true
+OnlyShowIn=KDE;
+X-KDE-autostart-phase=1
diff --git a/packages/wildos-settings/data/org.wildos.settings.policy b/packages/wildos-settings/data/org.wildos.settings.policy
index 13fd010..fe3d70b 100644
--- a/packages/wildos-settings/data/org.wildos.settings.policy
+++ b/packages/wildos-settings/data/org.wildos.settings.policy
@@ -5,8 +5,8 @@
<!-- The password prompts behind Settings. Each action runs one helper in
/usr/libexec/wildos, which takes only its own fixed requests:
settings-update-policy (Updates), settings-users (Accounts),
- settings-locale (Time and language) and settings-protection (Privacy
- and security). -->
+ settings-locale (Time and language), settings-protection (Privacy
+ and security) and settings-network (the VPN kill switch). -->
<policyconfig>
<vendor>Wild OS</vendor>
<vendor_url>https://wildos.io</vendor_url>
@@ -35,6 +35,18 @@
<annotate key="org.freedesktop.policykit.exec.path">/usr/libexec/wildos/settings-protection</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>
+ <icon_name>network-vpn</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-network</annotate>
+ </action>
+
<action id="org.wildos.settings.users">
<description>Change the accounts on this computer</description>
<message>Change who can use this computer?</message>
diff --git a/packages/wildos-settings/data/settings-network b/packages/wildos-settings/data/settings-network
new file mode 100644
index 0000000..c64f9f4
--- /dev/null
+++ b/packages/wildos-settings/data/settings-network
@@ -0,0 +1,31 @@
+#!/bin/sh
+# Turns the VPN kill switch on or off for Settings > Network and internet >
+# Advanced network settings. Runs as root through pkexec
+# (org.wildos.settings.policy) and takes only the requests below. The
+# wildos-network service watches the file and does the rest.
+#
+# kill-switch on Block the internet whenever a VPN that was connected
+# drops, until it reconnects or is switched off.
+# kill-switch off Stop blocking.
+
+set -eu
+
+FLAG=/etc/wildos/vpn-kill-switch
+
+case "${1:-} ${2:-}" in
+ "kill-switch on")
+ mkdir -p "$(dirname "$FLAG")"
+ echo "# Written by Wild OS Settings: the VPN kill switch is on." > "$FLAG"
+ ;;
+ "kill-switch off")
+ rm -f "$FLAG"
+ ;;
+ *)
+ echo "usage: settings-network kill-switch on|off" >&2
+ exit 2
+ ;;
+esac
+
+# The service is normally running; start it if something stopped it, so
+# the switch never says on while nothing guards.
+systemctl start wildos-network.service >/dev/null 2>&1 || true
diff --git a/packages/wildos-settings/data/wildos-mono-audio.conf b/packages/wildos-settings/data/wildos-mono-audio.conf
new file mode 100644
index 0000000..f58bf11
--- /dev/null
+++ b/packages/wildos-settings/data/wildos-mono-audio.conf
@@ -0,0 +1,49 @@
+# Mono audio (Settings > Accessibility): one filter that every app's sound
+# passes through on its way to the speakers or headphones in use. Its input
+# has a single channel, so PipeWire mixes left and right together going in,
+# and its single channel output is spread back over both sides of the
+# device. WirePlumber's smart filter policy puts it in front of whichever
+# output is the default and follows a change of device; it is never chosen
+# as the default itself (it has no session priority).
+#
+# Run by wildos-mono-audio.service as a PipeWire client of its own, like
+# PipeWire's filter-chain service, so switching it on or off never restarts
+# PipeWire.
+
+context.properties = {
+ log.level = 0
+}
+
+context.spa-libs = {
+ audio.convert.* = audioconvert/libspa-audioconvert
+ support.* = support/libspa-support
+}
+
+context.modules = [
+ { name = libpipewire-module-rt
+ args = { }
+ flags = [ ifexists nofail ]
+ }
+ { name = libpipewire-module-protocol-native }
+ { name = libpipewire-module-client-node }
+ { name = libpipewire-module-adapter }
+ { name = libpipewire-module-loopback
+ args = {
+ node.description = "Mono audio"
+ capture.props = {
+ node.name = "wildos-mono-audio"
+ media.class = "Audio/Sink"
+ audio.position = [ MONO ]
+ priority.session = 0
+ priority.driver = 0
+ filter.smart = true
+ filter.smart.name = "wildos-mono-audio"
+ }
+ playback.props = {
+ node.name = "wildos-mono-audio.output"
+ audio.position = [ MONO ]
+ node.passive = true
+ }
+ }
+ }
+]
diff --git a/packages/wildos-settings/data/wildos-mono-audio.service b/packages/wildos-settings/data/wildos-mono-audio.service
new file mode 100644
index 0000000..13fc630
--- /dev/null
+++ b/packages/wildos-settings/data/wildos-mono-audio.service
@@ -0,0 +1,19 @@
+[Unit]
+Description=Mono audio for Wild OS accessibility
+After=pipewire.service wireplumber.service
+BindsTo=pipewire.service
+
+[Service]
+LockPersonality=yes
+MemoryDenyWriteExecute=yes
+NoNewPrivileges=yes
+RestrictNamespaces=yes
+SystemCallArchitectures=native
+SystemCallFilter=@system-service
+Type=simple
+ExecStart=/usr/bin/pipewire -c wildos-mono-audio.conf
+Restart=on-failure
+Slice=session.slice
+
+[Install]
+WantedBy=pipewire.service
diff --git a/packages/wildos-settings/data/wildos-network.service b/packages/wildos-settings/data/wildos-network.service
new file mode 100644
index 0000000..cb9e841
--- /dev/null
+++ b/packages/wildos-settings/data/wildos-network.service
@@ -0,0 +1,15 @@
+[Unit]
+Description=Wild OS network privacy: encrypted DNS for new networks and the VPN kill switch
+Documentation=file:///usr/libexec/wildos/settings-network
+After=NetworkManager.service dbus.service
+Wants=NetworkManager.service
+
+[Service]
+Type=dbus
+BusName=org.wildos.Network
+ExecStart=/usr/libexec/wildos/wildos-network
+Restart=on-failure
+RestartSec=2
+
+[Install]
+WantedBy=multi-user.target
diff --git a/packages/wildos-settings/debian/control b/packages/wildos-settings/debian/control
index 74de6a4..dac0cf3 100644
--- a/packages/wildos-settings/debian/control
+++ b/packages/wildos-settings/debian/control
@@ -13,8 +13,13 @@ Build-Depends:
libkf6service-dev,
libkf6i18n-dev,
libkf6colorscheme-dev,
+ libkf6sonnet-dev,
+ libkscreen-dev,
+ libkf6networkmanagerqt-dev,
+ libkf6globalaccel-dev,
libpackagekitqt6-dev,
libcups2-dev,
+ libsdl2-dev,
libglib2.0-dev,
pkgconf,
Standards-Version: 4.7.0
@@ -26,6 +31,9 @@ Depends:
${shlibs:Depends},
${misc:Depends},
nftables,
+ network-manager,
+ network-manager-openvpn,
+ systemd-resolved,
qml6-module-qtquick-controls,
qml6-module-qtquick-templates,
qml6-module-qtquick-layouts,
@@ -39,9 +47,12 @@ Depends:
qml6-module-org-kde-desktop,
qml6-module-org-kde-bluezqt,
qml6-module-org-kde-plasma-plasma5support,
+ qml6-module-org-kde-kitemmodels,
plasma-nm,
+ plasma-pa,
plasma-workspace,
plasma-desktop,
+ libkscreen-bin,
wildos-branding,
wildos-ui,
kio6,
@@ -53,12 +64,24 @@ Depends:
locales,
accountsservice,
passwd,
+ fontconfig,
+ sonnet6-plugins,
+ hunspell-en-gb | hunspell-dictionary,
+ pipewire-bin,
+ libpipewire-0.3-modules,
+ libglib2.0-bin,
Recommends:
systemsettings,
+ bolt,
flatpak,
cups,
cups-filters,
xdg-desktop-portal,
+ baloo6,
+ kactivitymanagerd,
+ orca,
+ speech-dispatcher-espeak-ng,
+ maliit-keyboard,
Description: Wild OS Settings
The Settings app of Wild OS, laid out and worded the way Windows 11
Settings is: system, devices, network, personalisation, apps, Windows apps,
@@ -69,7 +92,22 @@ Description: Wild OS Settings
.
Its keyboard, printer, account, language and app permission pages work
through kxkbrc and KWin, CUPS, AccountsService and two small root helpers,
- the regional settings KDE uses and Flatpak's override files.
+ the regional settings KDE uses and Flatpak's override files. Its
+ touchscreen, pen, game controller, AutoPlay and Thunderbolt pages use
+ KWin, SDL, Plasma's device automounter and boltd. Spell checking goes
+ through Sonnet, and fonts are installed for the account with fontconfig.
+ File search and activity history use Baloo's and the activity manager's
+ own settings.
+ .
+ Its accessibility page keeps every choice where KDE and KWin read it, and
+ wildos-access gives high contrast, the on-screen keyboard and sticky keys
+ their keyboard shortcuts in the session and on the lock and sign-in
+ screens. Mono audio is a PipeWire filter run as a user service.
.
It also points the desktop's right-click "Personalise" entry at Settings
and installs the small helper that sets automatic security updates.
+ .
+ Advanced network settings work through NetworkManager. The wildos-network
+ service gives each new network Quad9's encrypted DNS (DNS over TLS through
+ systemd-resolved) and runs the VPN kill switch with nftables; Wi-Fi uses a
+ private hardware address for each network by default.
diff --git a/packages/wildos-settings/debian/install b/packages/wildos-settings/debian/install
new file mode 100644
index 0000000..5aebc1b
--- /dev/null
+++ b/packages/wildos-settings/debian/install
@@ -0,0 +1 @@
+data/kde-settings-redirect usr/libexec/wildos/
diff --git a/packages/wildos-settings/debian/links b/packages/wildos-settings/debian/links
new file mode 100644
index 0000000..00ab94f
--- /dev/null
+++ b/packages/wildos-settings/debian/links
@@ -0,0 +1,2 @@
+usr/libexec/wildos/kde-settings-redirect usr/bin/systemsettings
+usr/libexec/wildos/kde-settings-redirect usr/bin/kcmshell6
diff --git a/packages/wildos-settings/debian/postinst b/packages/wildos-settings/debian/postinst
index 77ce9e3..2b599e6 100644
--- a/packages/wildos-settings/debian/postinst
+++ b/packages/wildos-settings/debian/postinst
@@ -12,6 +12,12 @@ if [ "$1" = "configure" ]; then
rm -f "$MENU"
dpkg-divert --package wildos-settings --remove --rename --divert "$MENU.plasma" "$MENU" >/dev/null
fi
+ # NetworkManager reads its new defaults (lookups through
+ # systemd-resolved, private Wi-Fi addresses) without dropping the
+ # connections it has up.
+ if [ -d /run/systemd/system ] && systemctl is-active --quiet NetworkManager.service; then
+ nmcli general reload >/dev/null 2>&1 || true
+ fi
fi
#DEBHELPER#
diff --git a/packages/wildos-settings/debian/postrm b/packages/wildos-settings/debian/postrm
new file mode 100644
index 0000000..2db3baa
--- /dev/null
+++ b/packages/wildos-settings/debian/postrm
@@ -0,0 +1,18 @@
+#!/bin/sh
+set -e
+
+if [ "$1" = "remove" ] || [ "$1" = "purge" ] || [ "$1" = "abort-install" ]; then
+ for bin in systemsettings kcmshell6; do
+ dpkg-divert --package wildos-settings --remove --rename \
+ --divert "/usr/bin/$bin.kde" "/usr/bin/$bin" >/dev/null || true
+ done
+ # The kill switch's rules outlive its service on purpose (a crash must
+ # not let traffic out), so they go with the package.
+ nft delete table inet wildos_kill_switch 2>/dev/null || true
+fi
+
+if [ "$1" = "purge" ]; then
+ rm -f /etc/wildos/vpn-kill-switch /var/lib/wildos/network-dns-defaulted
+fi
+
+#DEBHELPER#
diff --git a/packages/wildos-settings/debian/preinst b/packages/wildos-settings/debian/preinst
new file mode 100644
index 0000000..adcd1aa
--- /dev/null
+++ b/packages/wildos-settings/debian/preinst
@@ -0,0 +1,13 @@
+#!/bin/sh
+set -e
+
+# KDE's systemsettings and kcmshell6 move aside so the redirect to Wild OS
+# Settings can take their names (see kde-settings-redirect).
+if [ "$1" = "install" ] || [ "$1" = "upgrade" ]; then
+ for bin in systemsettings kcmshell6; do
+ dpkg-divert --package wildos-settings --add --rename \
+ --divert "/usr/bin/$bin.kde" "/usr/bin/$bin" >/dev/null
+ done
+fi
+
+#DEBHELPER#
diff --git a/packages/wildos-settings/debian/rules b/packages/wildos-settings/debian/rules
index c5023d6..7e1501c 100644
--- a/packages/wildos-settings/debian/rules
+++ b/packages/wildos-settings/debian/rules
@@ -5,3 +5,9 @@
override_dh_auto_configure:
dh_auto_configure -- -Wno-dev
+
+# Mono audio is a choice in Settings > Accessibility, switched on per
+# person (systemctl --user enable); debhelper would otherwise enable it for
+# every account on install.
+override_dh_installsystemduser:
+ dh_installsystemduser --no-enable
diff --git a/packages/wildos-settings/qml/Main.qml b/packages/wildos-settings/qml/Main.qml
index 6658b64..79ed9c2 100644
--- a/packages/wildos-settings/qml/Main.qml
+++ b/packages/wildos-settings/qml/Main.qml
@@ -20,6 +20,7 @@ UI.AppWindow {
property string pendingId: ""
readonly property var current: Pages.page(currentId)
property string currentKcm: ""
+ property string pageError: ""
readonly property bool currentIsKcm: currentKcm.length > 0
readonly property bool canGoBack: history.length > 0 || (pageLoader.item !== null && pageLoader.item.depth !== undefined && pageLoader.item.depth > 1)
@@ -66,15 +67,17 @@ UI.AppWindow {
}
currentId = id;
pageLoader.sourceComponent = null;
- // A Wild OS page that cannot load (a desktop part it relies on is
- // missing) falls back to the KDE module for the same setting.
+ // A Wild OS page that cannot load says so, rather than quietly
+ // showing KDE's module for the same setting in its place.
let page = p.component ? Qt.createComponent("WildOS.Settings", p.component) : null;
+ pageError = "";
if (page && page.status === Component.Error) {
console.warn(page.errorString());
+ pageError = page.errorString();
page = null;
}
- currentKcm = page ? "" : (p.kcm || p.fallback || "");
- pageLoader.sourceComponent = page || kcmComponent;
+ currentKcm = page ? "" : (p.kcm || "");
+ pageLoader.sourceComponent = page || (currentKcm.length > 0 ? kcmComponent : errorComponent);
search.text = "";
}
@@ -125,6 +128,14 @@ UI.AppWindow {
onActivated: search.forceActiveFocus()
}
+ Component {
+ id: errorComponent
+ PageError {
+ pageTitle: (Pages.page(window.currentId) || {}).title || ""
+ detail: window.pageError
+ }
+ }
+
Component {
id: kcmComponent
KcmPage {
diff --git a/packages/wildos-settings/qml/components/PageError.qml b/packages/wildos-settings/qml/components/PageError.qml
new file mode 100644
index 0000000..b5d8500
--- /dev/null
+++ b/packages/wildos-settings/qml/components/PageError.qml
@@ -0,0 +1,35 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.UI as UI
+
+// What shows when a Wild OS page can't load. It used to fall back to KDE's
+// own module for the setting, which put KDE's look in front of people and
+// hid the fault; now the fault is visible and can be reported.
+PageScroll {
+ id: page
+
+ property string pageTitle
+ property string detail
+
+ StatusCard {
+ warning: true
+ iconName: "warning"
+ title: page.pageTitle.length > 0 ? page.pageTitle + " couldn't open" : "This page couldn't open"
+ description: "Something this page needs is missing or broken. Updating Wild OS usually fixes it. If it doesn't, please tell us what you were doing."
+
+ UI.Button {
+ text: "Report the problem"
+ onClicked: Qt.openUrlExternally("https://help.wildos.io/troubleshooting/report-a-problem/")
+ }
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ visible: page.detail.length > 0
+ text: page.detail
+ size: 12
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ textFormat: Text.PlainText
+ }
+}
diff --git a/packages/wildos-settings/qml/components/Pages.qml b/packages/wildos-settings/qml/components/Pages.qml
index e8ac7bd..30974a4 100644
--- a/packages/wildos-settings/qml/components/Pages.qml
+++ b/packages/wildos-settings/qml/components/Pages.qml
@@ -13,7 +13,7 @@ QtObject {
id: pages
readonly property var navigation: ["home", "system", "devices", "network", "personalisation", "apps",
- "windowsapps", "accounts", "time", "privacy", "update"]
+ "windowsapps", "accounts", "time", "accessibility", "privacy", "update"]
readonly property var all: ({
"home": { title: "Home", icon: "home", component: "HomePage",
@@ -24,13 +24,13 @@ QtObject {
keywords: "system" },
"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 hdr second screen projector" },
+ 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" },
"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" },
+ 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" },
"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,28 +42,22 @@ 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" },
- "displayadvanced": { title: "Advanced display", parent: "display", icon: "display", kcm: "kcm_kscreen",
- description: "Arrange screens, refresh rate, HDR and more",
- keywords: "arrange screens multiple monitors refresh rate hdr overscan rgb range" },
- "soundadvanced": { title: "All sound devices", parent: "sound", icon: "sound", kcm: "kcm_pulseaudio",
- description: "Every device and app volume, profiles",
- keywords: "app volume mixer devices profiles" },
- "appnotifications": { title: "Notifications from apps", parent: "notifications", icon: "bell", kcm: "kcm_notifications",
+ keywords: "snap layouts 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 sounds popups per app" },
- "poweradvanced": { title: "More power settings", parent: "power", icon: "battery", kcm: "kcm_powerdevilprofilesconfig",
+ keywords: "app notifications notify sounds popups pop ups banners history notification list per app senders turn off mute" },
+ "poweradvanced": { title: "More power settings", parent: "power", icon: "battery", component: "PowerAdvancedPage",
description: "Lid, power button and dimming",
- keywords: "lid close power button dim screen brightness battery critical" },
- "desktops": { title: "Desktops", parent: "multitasking", icon: "desktops", kcm: "kcm_kwin_virtualdesktops",
+ keywords: "lid close closing laptop power button press dim dimming screen brightness battery critical low level hibernate shut down external monitor" },
+ "desktops": { title: "Desktops", parent: "multitasking", icon: "desktops", component: "DesktopsPage",
description: "Extra desktops for separate sets of windows",
- keywords: "virtual desktops workspaces" },
+ keywords: "virtual desktops workspaces add desktop new desktop rename remove task view" },
"about": { title: "About", parent: "system", icon: "info", component: "AboutPage",
description: "Device specifications, rename this PC",
keywords: "device name rename pc computer name hostname specifications specs processor cpu memory ram version secure boot" },
"devices": { title: "Bluetooth and devices", icon: "bluetooth", component: "CategoryPage",
- children: ["bluetooth", "mouse", "touchpad", "keyboard", "printers"],
+ children: ["bluetooth", "mouse", "touchpad", "touchscreen", "pen", "keyboard", "printers", "gamecontrollers", "autoplay", "thunderbolt"],
keywords: "devices peripherals" },
"bluetooth": { title: "Bluetooth", parent: "devices", icon: "bluetooth", component: "BluetoothPage", fallback: "kcm_bluetooth",
description: "Pair headphones, speakers and other devices",
@@ -77,24 +71,46 @@ QtObject {
"keyboard": { title: "Keyboard", parent: "devices", icon: "keyboard", component: "KeyboardPage", fallback: "kcm_keyboard",
description: "Layouts, key repeat and Num Lock",
keywords: "keyboard layout layouts language typing input repeat delay rate num lock caps lock switch" },
- "keyboardadvanced": { title: "More keyboard options", parent: "keyboard", icon: "keyboard", kcm: "kcm_keyboard",
- description: "Keyboard model, compose key and other special keys",
- keywords: "compose key keyboard model alt gr special characters xkb options" },
+ "keyboardadvanced": { title: "More keyboard options", parent: "keyboard", icon: "keyboard", component: "KeyboardAdvancedPage",
+ description: "Keyboard model, compose key and Alt Gr",
+ keywords: "compose key keyboard model alt gr special characters accents third level xkb options" },
+ "touchscreen": { title: "Touchscreen", parent: "devices", icon: "display", component: "TouchscreenPage",
+ description: "Turn touch on or off, choose its screen",
+ keywords: "touch screen touchscreen touch input finger tap map screen" },
+ "pen": { title: "Pen and tablet", parent: "devices", icon: "pencil", component: "PenPage",
+ description: "Drawing tablets and pens, left-handed use",
+ keywords: "pen stylus tablet drawing tablet graphics tablet wacom left handed map screen windows ink" },
+ "gamecontrollers": { title: "Game controllers", parent: "devices", icon: "games", component: "GameControllersPage",
+ description: "Gamepads and joysticks, test buttons and sticks",
+ keywords: "game controller gamepad joystick xbox playstation controller test buttons sticks" },
+ "autoplay": { title: "AutoPlay", parent: "devices", icon: "play", component: "AutoPlayPage",
+ description: "What happens when you plug in a drive or memory card",
+ keywords: "autoplay auto play usb stick memory card sd card removable drive mount automount" },
+ "thunderbolt": { title: "Thunderbolt", parent: "devices", icon: "bolt", component: "ThunderboltPage",
+ description: "Allow docks and other Thunderbolt devices",
+ keywords: "thunderbolt usb4 dock docking station authorise authorize allow" },
"printers": { title: "Printers and scanners", parent: "devices", icon: "printer", component: "PrintersPage", fallback: "kcm_printer_manager",
description: "Add and manage printers",
keywords: "printer printers print scanner add printer default printer test page" },
- "printersadvanced": { title: "More printer settings", parent: "printers", icon: "printer", kcm: "kcm_printer_manager",
+ "printersadvanced": { title: "More printer settings", parent: "printers", icon: "printer", component: "PrintersAdvancedPage",
description: "Printers that need a driver, USB printers and print queues",
- keywords: "printer driver usb printer print queue share printer" },
+ keywords: "printer driver usb printer print queue pause printing cancel document paper size a4 letter two-sided duplex colour color black and white ppd" },
"network": { title: "Network and internet", icon: "wifi", component: "NetworkPage",
keywords: "wifi wi-fi wireless internet ethernet network airplane flight mode connect hotspot" },
- "networkadvanced": { title: "Advanced network settings", parent: "network", icon: "globe", window: "kcm_networkmanagement",
+ "networkadvanced": { title: "Advanced network settings", parent: "network", icon: "globe", component: "NetworkAdvancedPage",
+ fallback: "kcm_networkmanagement",
description: "VPN, proxy, IP addresses and saved networks",
- keywords: "vpn proxy dns ip address advanced connections saved networks forget" },
+ keywords: "vpn wireguard openvpn kill switch proxy dns encrypted dns over tls quad9 cloudflare mullvad ip address static ip mac address hardware address random private metered advanced connections saved networks forget" },
+ // KDE's editor for what Wild OS has no page for: work Wi-Fi that
+ // signs in with a username (802.1X), other kinds of VPN, bridges.
+ // Search finds it.
+ "networkconnections": { title: "All connection settings", parent: "networkadvanced", icon: "globe", window: "kcm_networkmanagement",
+ description: "Every setting of every connection, in KDE's editor",
+ 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"],
+ children: ["background", "colours", "lockscreen", "taskbar", "fonts"],
keywords: "personalize personalise customise customize theme look light dark font fonts text size bigger" },
"background": { title: "Background", parent: "personalisation", icon: "image", component: "BackgroundPage",
description: "Pictures and your own photos",
@@ -108,9 +124,12 @@ QtObject {
"taskbar": { title: "Taskbar", parent: "personalisation", icon: "taskbar", component: "TaskbarPage",
description: "Hiding the taskbar",
keywords: "taskbar panel auto hide autohide" },
+ "fonts": { title: "Fonts", parent: "personalisation", icon: "font", component: "FontsPage",
+ description: "Install and remove fonts",
+ keywords: "font fonts typeface install font ttf otf typography" },
"apps": { title: "Apps", icon: "apps", component: "CategoryPage",
- children: ["installedapps", "defaultapps", "startup"],
+ children: ["installedapps", "defaultapps", "startup", "oldapps"],
keywords: "apps programs applications" },
"installedapps": { title: "Installed apps", parent: "apps", icon: "list", component: "InstalledAppsPage",
description: "Uninstall apps",
@@ -118,9 +137,15 @@ QtObject {
"defaultapps": { title: "Default apps", parent: "apps", icon: "default-apps", component: "DefaultAppsPage", fallback: "kcm_componentchooser",
description: "Browser, email and other default apps",
keywords: "default browser email mail open with file associations" },
+ "filetypes": { title: "Choose defaults by file type", parent: "defaultapps", icon: "document", component: "FileTypesPage",
+ description: "Pick the app for .pdf, .docx and every other kind of file",
+ keywords: "file type file types extension extensions mime associations open with pdf docx" },
"startup": { title: "Startup", parent: "apps", icon: "startup", component: "StartupPage", fallback: "kcm_autostart",
description: "Apps that start when you sign in",
keywords: "startup autostart login sign in boot" },
+ "oldapps": { title: "Old app compatibility", parent: "apps", icon: "app", component: "OldAppCompatibilityPage",
+ description: "What older apps can see you type in other apps",
+ keywords: "x11 xwayland legacy older apps keyboard shortcuts push to talk eavesdrop global shortcuts" },
"windowsapps": { title: "Windows apps", icon: "windowsapps", component: "WindowsAppsPage",
keywords: "windows exe programs sandbox" },
@@ -134,8 +159,8 @@ QtObject {
description: "Your name and picture",
keywords: "user picture avatar photo name profile account picture" },
"signin": { title: "Sign-in options", parent: "accounts", icon: "lock", component: "SignInPage",
- description: "Password and automatic sign-in",
- keywords: "password change password hint automatic sign in auto login autologin" },
+ description: "Password, automatic sign-in and restarting apps",
+ keywords: "password change password hint automatic sign in auto login autologin restart apps restore session reopen restartable" },
"otherusers": { title: "Other users", parent: "accounts", icon: "people", component: "OtherUsersPage",
description: "Add and remove the people who share this computer",
keywords: "add user other users family administrator standard user remove account delete account" },
@@ -148,9 +173,18 @@ QtObject {
"language": { title: "Language and region", parent: "time", icon: "language", component: "LanguagePage", fallback: "kcm_regionandlang",
description: "Display language, formats and region",
keywords: "language display language region format formats regional format currency locale country" },
- "formatsadvanced": { title: "More format options", parent: "language", icon: "language", kcm: "kcm_regionandlang",
+ "formatsadvanced": { title: "More format options", parent: "language", icon: "language", component: "FormatsPage",
description: "Numbers, time, money and measurements separately",
- keywords: "number format currency format measurement units paper size" },
+ keywords: "number format currency format date format time format measurement units metric imperial paper size a4 letter file sizes" },
+ "typing": { title: "Typing", parent: "time", icon: "pencil", component: "TypingPage",
+ description: "Spell checking and your dictionary",
+ 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" },
+ "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" },
"privacy": { title: "Privacy and security", icon: "shield", component: "PrivacyPage",
keywords: "security privacy protection encryption firewall secure boot sandbox" },
@@ -172,12 +206,18 @@ QtObject {
"appnetwork": { title: "Internet", parent: "apppermissions", icon: "globe", component: "AppAccessPage",
description: "Apps that can go online",
keywords: "internet network online offline" },
- "apppermissionsadvanced": { title: "Everything an app can reach", parent: "apppermissions", icon: "sandbox", kcm: "kcm_flatpak",
+ "apppermissionsadvanced": { title: "Everything an app can reach", parent: "apppermissions", icon: "sandbox", component: "AppPermissionsAdvancedPage",
description: "Every sandbox permission, app by app",
- keywords: "flatpak permissions dbus environment devices advanced" },
+ keywords: "flatpak permissions dbus d-bus environment variables devices sockets filesystem override reset advanced" },
"screenlock": { title: "Screen lock", parent: "privacy", icon: "lock", component: "ScreenLockPage", fallback: "kcm_screenlocker",
description: "Lock after a while and ask for your password",
keywords: "lock screen timeout password sign in wake" },
+ "searching": { title: "Searching files", parent: "privacy", icon: "search", component: "SearchingFilesPage",
+ description: "File indexing and the folders search looks in",
+ keywords: "search indexing index baloo find files excluded folders hidden files contents rebuild" },
+ "activityhistory": { title: "Activity history", parent: "privacy", icon: "clock", component: "ActivityHistoryPage",
+ description: "Recent files and clearing your history",
+ keywords: "activity history recent files recently opened documents clear history forget" },
"update": { title: "Updates", icon: "update", component: "UpdatePage",
keywords: "update updates upgrade patch security updates check for updates install" }
@@ -201,20 +241,43 @@ QtObject {
"security": "privacy",
"network-advanced": "networkadvanced",
"kcm_kscreen": "display",
+ // Advanced display was KDE's module; everything it offered that Wild
+ // OS keeps is on Display now.
+ "displayadvanced": "display",
"kcm_networkmanagement": "networkadvanced",
"kcm_wallpaper": "background",
"kcm_lookandfeel": "personalisation",
"kcm_colors": "colours",
"kcm_about-distro": "about",
"kcm_updates": "update",
- "kcm_cursortheme": "mouse",
+ "kcm_cursortheme": "accessibility",
"kcm_proxy": "networkadvanced",
"kcm_soundtheme": "sound",
+ // The volume mixer and every device are on Sound itself now.
+ "soundadvanced": "sound",
+ "kcm_pulseaudio": "sound",
"kcm_energyinfo": "power",
- "kcm_virtualkeyboard": "keyboard",
- // Text size in Personalisation is the Wild OS way to change fonts.
+ "kcm_kwin_virtualdesktops": "desktops",
+ "kcm_smserver": "signin",
+ "kcm_keyboard": "keyboard",
+ "kcm_device_automounter": "autoplay",
+ "kcm_gamecontroller": "gamecontrollers",
+ "kcm_tablet": "pen",
+ "kcm_touchscreen": "touchscreen",
+ "kcm_bolt": "thunderbolt",
+ "kcm_baloofile": "searching",
+ "kcm_recentFiles": "activityhistory",
+ "kcm_kwinxwayland": "oldapps",
+ "kcm_virtualkeyboard": "accessibility",
+ "kcm_access": "accessibility",
+ "easeofaccess": "accessibility",
+ "ease-of-access": "accessibility",
+ // Text size in Personalisation is the Wild OS way to change the
+ // fonts apps use; installing fonts has its own page.
"kcm_fonts": "personalisation",
- "fonts": "personalisation"
+ "kcm_fontinst": "fonts",
+ "kcmspellchecking": "typing",
+ "kcm_filetypes": "filetypes"
})
function resolve(id) {
diff --git a/packages/wildos-settings/qml/components/ScreenChoices.qml b/packages/wildos-settings/qml/components/ScreenChoices.qml
new file mode 100644
index 0000000..994e7ef
--- /dev/null
+++ b/packages/wildos-settings/qml/components/ScreenChoices.qml
@@ -0,0 +1,30 @@
+import QtQuick
+
+// The screens a touchscreen or pen can be tied to, by the connector name
+// KWin keys them on (QScreen.name, such as eDP-1), labelled with the
+// screen's model and size, as KDE's touchscreen and tablet modules do.
+QtObject {
+ id: choices
+
+ property string automaticText: "Automatic"
+ property bool allScreens: false
+
+ readonly property int screenCount: Qt.application.screens.length
+ readonly property var model: {
+ const list = [{ value: "", text: automaticText }];
+ if (allScreens) {
+ list.push({ value: "*", text: "All screens" });
+ }
+ const screens = Qt.application.screens;
+ for (let i = 0; i < screens.length; ++i) {
+ const s = screens[i];
+ const label = s.model && s.model.length > 0 ? s.model : s.name;
+ list.push({ value: s.name, text: label + " (" + s.width + " × " + s.height + ")" });
+ }
+ return list;
+ }
+
+ function indexOf(value) {
+ return Math.max(0, model.findIndex(o => o.value === value));
+ }
+}
diff --git a/packages/wildos-settings/qml/components/TextSizeBox.qml b/packages/wildos-settings/qml/components/TextSizeBox.qml
new file mode 100644
index 0000000..ee2356c
--- /dev/null
+++ b/packages/wildos-settings/qml/components/TextSizeBox.qml
@@ -0,0 +1,16 @@
+import QtQuick
+import WildOS.Settings
+import WildOS.UI as UI
+
+// The text size choice, shown in Personalisation and in Accessibility; both
+// change the one setting through System.setTextScale. A size set elsewhere
+// (KDE's fonts module) is listed too, so the box never shows nothing.
+UI.ComboBox {
+ readonly property var sizes: [100, 110, 125, 150]
+ readonly property var choice: System.textScale
+
+ Accessible.name: "Text size"
+ model: sizes.concat(sizes.includes(System.textScale) ? [] : [System.textScale]).map(p => ({ value: p, text: p + "%" }))
+ currentIndex: model ? model.findIndex(o => o.value === choice) : -1
+ onActivated: index => System.setTextScale(model[index].value)
+}
diff --git a/packages/wildos-settings/qml/pages/AccessibilityPage.qml b/packages/wildos-settings/qml/pages/AccessibilityPage.qml
new file mode 100644
index 0000000..23d7118
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/AccessibilityPage.qml
@@ -0,0 +1,324 @@
+import QtQuick
+import QtQuick.Layouts
+import QtQuick.Templates as T
+import WildOS.Settings
+import WildOS.UI as UI
+
+// Accessibility, laid out as SettingsAccessibility.dc.html: a line about the
+// shortcuts, then Seeing on the left beside Hearing and Keyboard and touch
+// on the right (one column when the window is narrow). Every switch is bound
+// to Accessibility, which reads the system each time this page is made, so
+// leaving and coming back always shows what is really set. Each row with a
+// shortcut shows its keys; wildos-access makes them work on the lock and
+// sign-in screens as well.
+PageScroll {
+ id: page
+
+ readonly property bool wide: width >= 760
+
+ function onOff(on) {
+ return on ? "On" : "Off";
+ }
+
+ Component.onCompleted: {
+ Accessibility.refresh();
+ Accessibility.refreshMagnifier();
+ }
+
+ // KWin says nothing when zoom changes (Super and plus from the
+ // keyboard), so the switch looks while the page is showing.
+ Timer {
+ interval: 1000
+ repeat: true
+ running: page.visible && Qt.application.state === Qt.ApplicationActive
+ onTriggered: Accessibility.refreshMagnifier()
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ Layout.topMargin: -6
+ text: "Every shortcut here also works on the sign-in and unlock screens, so help is there before you've signed in."
+ size: 13
+ color: UI.Style.inkStatus
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ lineHeight: 1.5
+ }
+
+ GridLayout {
+ Layout.fillWidth: true
+ columns: page.wide ? 2 : 1
+ columnSpacing: 20
+ rowSpacing: 18
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ Layout.preferredWidth: 1
+ Layout.horizontalStretchFactor: 108
+ Layout.alignment: Qt.AlignTop
+ spacing: 10
+
+ SectionTitle {
+ text: "Seeing"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ title: "Text size"
+ description: "Larger text everywhere, without changing scale"
+
+ TextSizeBox {
+ anchors.verticalCenter: parent.verticalCenter
+ }
+ }
+
+ UI.SettingRow {
+ id: pointerRow
+
+ readonly property var sizes: Accessibility.pointerSizes
+
+ function nearest(size) {
+ let best = 0;
+ for (let i = 1; i < sizes.length; ++i) {
+ if (Math.abs(sizes[i] - size) < Math.abs(sizes[best] - size)) {
+ best = i;
+ }
+ }
+ return best;
+ }
+
+ title: "Pointer"
+ description: "Size and colour"
+
+ Row {
+ anchors.verticalCenter: parent.verticalCenter
+ spacing: 16
+
+ UI.Slider {
+ id: pointerSize
+ anchors.verticalCenter: parent.verticalCenter
+ implicitWidth: 90
+ implicitHeight: 20
+ flat: true
+ from: 0
+ to: Math.max(1, pointerRow.sizes.length - 1)
+ stepSize: 1
+ snapMode: T.Slider.SnapAlways
+ wheelEnabled: false
+ value: pointerRow.nearest(Accessibility.pointerSize)
+ accessibleName: "Pointer size"
+ Accessible.description: pointerRow.sizes[Math.round(value)] + " pixels"
+ // Applied once the slider settles, so dragging
+ // across it does not reload the pointer at
+ // every step.
+ onMoved: pointerApply.restart()
+
+ Timer {
+ id: pointerApply
+ interval: 250
+ onTriggered: {
+ if (pointerSize.pressed) {
+ restart();
+ return;
+ }
+ Accessibility.setPointerSize(pointerRow.sizes[Math.round(pointerSize.value)]);
+ pointerSize.value = Qt.binding(() => pointerRow.nearest(Accessibility.pointerSize));
+ }
+ }
+ }
+
+ Row {
+ anchors.verticalCenter: parent.verticalCenter
+ spacing: 8
+ Accessible.role: Accessible.Grouping
+ Accessible.name: "Pointer colour"
+
+ Repeater {
+ model: Accessibility.pointerColours
+
+ UI.Swatch {
+ required property var modelData
+ colour: modelData.colour
+ name: modelData.name
+ selected: Accessibility.pointerColour === modelData.id
+ onClicked: Accessibility.setPointerColour(modelData.id)
+ }
+ }
+ }
+ }
+ }
+
+ UI.SettingRow {
+ title: "Magnifier"
+ description: "Zoom into any part of the screen"
+ status: page.onOff(Accessibility.magnifier)
+ below: UI.ShortcutKeys {
+ keys: ["Super", "+"]
+ }
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: Accessibility.magnifier
+ Accessible.name: "Magnifier"
+ onToggled: Accessibility.setMagnifier(checked)
+ }
+ }
+
+ UI.SettingRow {
+ title: "Screen reader"
+ description: "Reads out what's on screen"
+ status: page.onOff(Accessibility.screenReader)
+ below: UI.ShortcutKeys {
+ keys: ["Super", "Alt", "S"]
+ }
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: Accessibility.screenReader
+ locked: !Accessibility.screenReaderInstalled
+ lockedReason: "The screen reader isn't installed on this computer"
+ Accessible.name: "Screen reader"
+ onToggled: Accessibility.setScreenReader(checked)
+ }
+ }
+
+ UI.SettingRow {
+ title: "High contrast"
+ description: "Strong colours and clear edges"
+ status: page.onOff(Accessibility.highContrast)
+ below: UI.ShortcutKeys {
+ keys: ["Super", "Alt", "H"]
+ }
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: Accessibility.highContrast
+ enabled: !Accessibility.highContrastBusy
+ locked: !Accessibility.highContrastInstalled
+ lockedReason: "The high contrast theme isn't installed on this computer"
+ Accessible.name: "High contrast"
+ onToggled: Accessibility.setHighContrast(checked)
+ }
+ }
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ Layout.preferredWidth: 1
+ Layout.horizontalStretchFactor: 100
+ Layout.alignment: Qt.AlignTop
+ spacing: 18
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ SectionTitle {
+ text: "Hearing"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ title: "Flash the screen for alert sounds"
+ description: "For when you can't hear them"
+ status: page.onOff(Accessibility.visibleBell)
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: Accessibility.visibleBell
+ Accessible.name: "Visual alerts"
+ onToggled: Accessibility.setVisibleBell(checked)
+ }
+ }
+
+ UI.SettingRow {
+ title: "Mono audio"
+ description: "Both ears get the same sound"
+ status: page.onOff(Accessibility.monoAudio)
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: Accessibility.monoAudio
+ locked: !Accessibility.monoAudioInstalled
+ lockedReason: "Mono audio isn't available on this computer"
+ Accessible.name: "Mono audio"
+ onToggled: Accessibility.setMonoAudio(checked)
+ }
+ }
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ SectionTitle {
+ text: "Keyboard and touch"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ title: "On-screen keyboard"
+ description: "Type with a mouse, touch or switch"
+ status: page.onOff(Accessibility.onScreenKeyboard)
+ below: UI.ShortcutKeys {
+ keys: ["Super", "Ctrl", "O"]
+ }
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: Accessibility.onScreenKeyboard
+ locked: !Accessibility.onScreenKeyboardInstalled
+ lockedReason: "No on-screen keyboard is installed on this computer"
+ Accessible.name: "On-screen keyboard"
+ onToggled: Accessibility.setOnScreenKeyboard(checked)
+ }
+ }
+
+ UI.SettingRow {
+ title: "Sticky keys"
+ description: "Press shortcuts one at a time"
+ status: page.onOff(Accessibility.stickyKeys)
+ below: UI.ShortcutKeys {
+ keys: ["Shift ×5"]
+ }
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: Accessibility.stickyKeys
+ Accessible.name: "Sticky keys"
+ onToggled: Accessibility.setStickyKeys(checked)
+ }
+ }
+
+ UI.SettingRow {
+ readonly property var info: Pages.page("slowbouncekeys")
+ title: info.title
+ description: info.description
+ chevron: true
+ onClicked: Navigator.open("slowbouncekeys")
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/ActivityHistoryPage.qml b/packages/wildos-settings/qml/pages/ActivityHistoryPage.qml
new file mode 100644
index 0000000..677b068
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/ActivityHistoryPage.qml
@@ -0,0 +1,206 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.Settings
+import WildOS.UI as UI
+
+// Activity history, after Windows 11: whether this computer remembers the
+// files you open, so Start and Files can offer them again, for how long,
+// apps it never remembers, and Clear history. Nothing here leaves this
+// computer.
+PageScroll {
+ id: page
+
+ Connections {
+ target: ActivityHistory
+ function onCleared() {
+ notice.show("History cleared", "The files you opened are no longer listed as recent.", false);
+ }
+ function onFailed(reason) {
+ notice.show("History was not cleared", reason, true);
+ }
+ }
+
+ Component.onCompleted: ActivityHistory.reload()
+
+ Notice {
+ id: notice
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: "This computer can remember the files you open so you can get back to them from Start and Files. The history stays on this computer."
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ iconName: "clock"
+ title: "Remember the files I open"
+ description: "Shows recent files in Start and Files"
+ status: ActivityHistory.remember ? "On" : "Off"
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: ActivityHistory.remember
+ Accessible.name: "Remember the files I open"
+ onToggled: ActivityHistory.remember = checked
+ }
+ }
+
+ UI.SettingRow {
+ iconName: "restore"
+ title: "Keep history for"
+ description: "Older activity is deleted automatically"
+ enabled: ActivityHistory.remember
+
+ UI.ComboBox {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "Keep history for"
+ model: [
+ { value: 1, text: "1 month" },
+ { value: 3, text: "3 months" },
+ { value: 6, text: "6 months" },
+ { value: 12, text: "1 year" },
+ { value: 0, text: "Forever" }
+ ]
+ readonly property int choice: ActivityHistory.keepMonths
+ // A length set elsewhere shows as the nearest longer one
+ // until it is changed here.
+ currentIndex: {
+ if (choice === 0) {
+ return 4;
+ }
+ const i = model.findIndex(o => o.value !== 0 && o.value >= choice);
+ return i >= 0 ? i : 4;
+ }
+ onActivated: index => ActivityHistory.keepMonths = model[index].value
+ }
+ }
+
+ UI.SettingRow {
+ iconName: "delete"
+ title: "Clear activity history"
+ description: "Forgets every file this computer remembers you opening"
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Clear history"
+ busy: ActivityHistory.clearing
+ enabled: !ActivityHistory.clearing
+ onClicked: clearDialog.open()
+ }
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ SectionTitle {
+ text: "Apps that are never remembered"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ Repeater {
+ model: ActivityHistory.blocked
+
+ UI.SettingRow {
+ id: blockedRow
+ required property var modelData
+ themeIcon: modelData.icon
+ title: modelData.name
+ enabled: ActivityHistory.remember
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Remove"
+ onClicked: ActivityHistory.unblock(blockedRow.modelData.id)
+ }
+ }
+ }
+
+ UI.SettingRow {
+ iconName: "plus"
+ title: "Add an app"
+ description: "Files you open in it are never added to your history"
+ enabled: ActivityHistory.remember
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Choose an app"
+ onClicked: appDialog.show()
+ }
+ }
+ }
+ }
+ }
+
+ UI.Dialog {
+ id: clearDialog
+ title: "Clear activity history?"
+ text: "Recent files disappear from Start and Files. The files themselves are not touched."
+ buttons: [
+ UI.Button {
+ text: "Clear"
+ kind: "primary"
+ onClicked: {
+ clearDialog.close();
+ notice.hide();
+ ActivityHistory.clear();
+ }
+ },
+ UI.Button {
+ text: "Cancel"
+ onClicked: clearDialog.close()
+ }
+ ]
+ }
+
+ UI.Dialog {
+ id: appDialog
+
+ function show() {
+ appBox.model = ActivityHistory.apps();
+ appBox.currentIndex = 0;
+ open();
+ }
+
+ title: "Never remember files from"
+ text: "Files you open in this app are left out of your history from now on."
+
+ UI.ComboBox {
+ id: appBox
+ Layout.fillWidth: true
+ Accessible.name: "App"
+ }
+
+ buttons: [
+ UI.Button {
+ text: "Add"
+ kind: "primary"
+ enabled: appBox.count > 0
+ onClicked: {
+ appDialog.close();
+ ActivityHistory.block(appBox.currentValue);
+ }
+ },
+ UI.Button {
+ text: "Cancel"
+ onClicked: appDialog.close()
+ }
+ ]
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/AppNotificationsPage.qml b/packages/wildos-settings/qml/pages/AppNotificationsPage.qml
new file mode 100644
index 0000000..08ab060
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/AppNotificationsPage.qml
@@ -0,0 +1,145 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.Settings
+import WildOS.UI as UI
+
+// Notifications from apps, after Windows 11's "Notifications from apps and
+// other senders": every app that can notify, by name, with its switch.
+// Selecting an app shows its own choices underneath it.
+PageScroll {
+ id: page
+
+ property string expanded: ""
+
+ Component.onCompleted: AppNotifications.reload()
+
+ function summary(app) {
+ if (!app.enabled) {
+ return "Off";
+ }
+ const parts = [];
+ if (app.banners) {
+ parts.push("Banners");
+ }
+ if (app.hasSound && app.sound) {
+ parts.push("Sounds");
+ }
+ if (!app.banners && app.history) {
+ parts.push("Notification list only");
+ }
+ return parts.join(", ");
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: "Choose which apps can send you notifications. Select an app for banners, sounds and the notification list."
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ Repeater {
+ model: AppNotifications.apps
+
+ Column {
+ id: entry
+ required property var modelData
+ readonly property bool open: page.expanded === modelData.id
+ width: parent.width
+
+ Rectangle {
+ visible: entry.y > 0
+ width: parent.width
+ height: 1
+ color: UI.Style.divider
+ }
+
+ UI.SettingRow {
+ themeIcon: entry.modelData.icon.length > 0 ? entry.modelData.icon : "application-x-executable"
+ title: entry.modelData.name
+ description: page.summary(entry.modelData)
+ divider: false
+ interactive: true
+ Accessible.description: entry.open ? "Hide this app's notification options" : "Show this app's notification options"
+ onClicked: page.expanded = entry.open ? "" : entry.modelData.id
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: entry.modelData.enabled
+ Accessible.name: "Notifications from " + entry.modelData.name
+ onToggled: AppNotifications.setEnabled(entry.modelData.id, checked)
+ }
+
+ UI.Icon {
+ anchors.verticalCenter: parent.verticalCenter
+ name: entry.open ? "chevron-up" : "chevron-down"
+ size: 14
+ strokeWidth: 2
+ color: UI.Style.iconMuted
+ }
+ }
+
+ UI.SettingRow {
+ visible: entry.open
+ enabled: entry.modelData.enabled
+ leading: Item { width: 24; height: 1 }
+ title: "Show notification banners"
+ description: "Notifications pop up in the corner of the screen"
+ status: entry.modelData.banners ? "On" : "Off"
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: entry.modelData.banners
+ Accessible.name: "Show notification banners from " + entry.modelData.name
+ onToggled: AppNotifications.setBanners(entry.modelData.id, checked)
+ }
+ }
+
+ UI.SettingRow {
+ visible: entry.open && entry.modelData.hasSound
+ enabled: entry.modelData.enabled
+ leading: Item { width: 24; height: 1 }
+ title: "Play a sound when a notification arrives"
+ status: entry.modelData.sound ? "On" : "Off"
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: entry.modelData.sound
+ Accessible.name: "Play a sound for notifications from " + entry.modelData.name
+ onToggled: AppNotifications.setSound(entry.modelData.id, checked)
+ }
+ }
+
+ UI.SettingRow {
+ visible: entry.open
+ enabled: entry.modelData.enabled
+ leading: Item { width: 24; height: 1 }
+ title: "Show notifications in the notification list"
+ description: "Notifications stay in the list after their banner goes"
+ status: entry.modelData.history ? "On" : "Off"
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: entry.modelData.history
+ Accessible.name: "Show notifications from " + entry.modelData.name + " in the notification list"
+ onToggled: AppNotifications.setHistory(entry.modelData.id, checked)
+ }
+ }
+ }
+ }
+
+ UI.SettingRow {
+ visible: AppNotifications.apps.length === 0
+ iconName: "bell"
+ title: "No apps have sent notifications yet"
+ description: "Apps appear here once they can notify you, each with a switch."
+ }
+ }
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/AppPermissionsAdvancedPage.qml b/packages/wildos-settings/qml/pages/AppPermissionsAdvancedPage.qml
new file mode 100644
index 0000000..64411da
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/AppPermissionsAdvancedPage.qml
@@ -0,0 +1,285 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.Settings
+import WildOS.UI as UI
+
+// Everything an app from the Store can reach, app by app: every folder,
+// device, socket, service and variable in its sandbox with a switch, ways
+// to give it more, and a reset to what it asked for when installed. All of
+// it is the user override file "flatpak override --user" writes, so the
+// simple permission pages and the Store show the same answers.
+PageScroll {
+ id: page
+
+ property string selected
+ property var apps: []
+ property var sections: []
+ readonly property var app: {
+ for (const a of apps) {
+ if (a.id === selected) {
+ return a;
+ }
+ }
+ return null;
+ }
+
+ readonly property int depth: selected.length > 0 ? 2 : 1
+ readonly property var subTitles: app ? [app.name] : []
+
+ function back() {
+ if (selected.length > 0) {
+ selected = "";
+ return true;
+ }
+ return false;
+ }
+
+ function refresh() {
+ apps = AppAccess.everyApp();
+ sections = selected.length > 0 ? AppAccess.details(selected) : [];
+ }
+
+ onSelectedChanged: refresh()
+
+ Connections {
+ target: AppAccess
+ function onChanged() {
+ page.refresh();
+ }
+ }
+
+ Component.onCompleted: AppAccess.reload()
+
+ UI.Label {
+ Layout.fillWidth: true
+ visible: page.selected.length === 0
+ text: "Every permission an app from the Store has, including the technical ones the other pages leave out. Changes apply the next time the app opens."
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+ visible: page.selected.length === 0
+
+ Column {
+ width: parent.width
+
+ Repeater {
+ model: page.selected.length === 0 ? page.apps : []
+
+ UI.SettingRow {
+ required property var modelData
+ themeIcon: modelData.icon
+ title: modelData.name
+ description: modelData.changed ? "Changed from what the app asked for" : "As the app asked for"
+ chevron: true
+ onClicked: page.selected = modelData.id
+ }
+ }
+
+ UI.SettingRow {
+ visible: page.apps.length === 0
+ iconName: "sandbox"
+ title: "No apps from the Store yet"
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ visible: page.app !== null
+ spacing: Metrics.sectionGap
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ themeIcon: page.app ? page.app.icon : ""
+ iconTile: true
+ minHeight: 68
+ title: page.app ? page.app.name : ""
+ description: page.app && page.app.changed ? "You have changed what this app can reach" : "This app has what it asked for when installed"
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: page.app !== null && page.app.changed
+ text: "Reset to the app's defaults"
+ onClicked: resetDialog.open()
+ }
+ }
+ }
+ }
+
+ Repeater {
+ model: page.sections
+
+ ColumnLayout {
+ id: block
+ required property var modelData
+ // Lists the app may add to are shown even when empty, so
+ // there is somewhere to add from.
+ readonly property string addKind: ({ "filesystems": "folder", "session-bus": "bus", "env": "env" })[modelData.key] || ""
+ Layout.fillWidth: true
+ visible: modelData.items.length > 0 || addKind.length > 0
+ spacing: 10
+
+ SectionTitle {
+ text: block.modelData.title
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ Repeater {
+ model: block.modelData.items
+
+ UI.SettingRow {
+ id: permission
+ required property var modelData
+ title: modelData.label
+ description: [modelData.detail, modelData.changed ? "Changed by you" : ""].filter(t => t.length > 0).join(". ")
+ status: modelData.allowed ? "On" : "Off"
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: permission.modelData.allowed
+ Accessible.name: permission.modelData.label
+ onToggled: AppAccess.set(page.selected, permission.modelData.token, checked, permission.modelData.grant)
+ }
+ }
+ }
+
+ UI.SettingRow {
+ visible: block.addKind.length > 0
+ iconName: "plus"
+ title: block.addKind === "folder" ? "Give it another folder"
+ : block.addKind === "bus" ? "Let it talk to another service"
+ : "Set a variable"
+ description: block.modelData.items.length === 0
+ ? (block.addKind === "folder" ? "It can only open files you choose for it"
+ : block.addKind === "bus" ? "It can only use the desktop's own services"
+ : "It has no variables of its own")
+ : ""
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Add"
+ onClicked: addDialog.show(block.addKind)
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ UI.Dialog {
+ id: addDialog
+
+ property string kind
+ property string error
+
+ function show(k) {
+ kind = k;
+ error = "";
+ valueField.text = "";
+ extraField.text = "";
+ accessBox.currentIndex = 0;
+ open();
+ valueField.forceActiveFocus();
+ }
+
+ title: kind === "folder" ? "Give it another folder" : kind === "bus" ? "Let it talk to another service" : "Set a variable"
+ text: kind === "folder" ? "Type the folder's path. ~ is your home folder."
+ : kind === "bus" ? "Type the service's name. Only add one the app's makers ask you to."
+ : "Type the variable's name and the value the app sees."
+
+ UI.TextField {
+ id: valueField
+ Layout.fillWidth: true
+ placeholderText: addDialog.kind === "folder" ? "For example ~/Projects" : addDialog.kind === "bus" ? "For example org.freedesktop.Notifications" : "Name, for example GTK_THEME"
+ onAccepted: addButton.clicked()
+ }
+
+ UI.TextField {
+ id: extraField
+ Layout.fillWidth: true
+ visible: addDialog.kind === "env"
+ placeholderText: "Value"
+ onAccepted: addButton.clicked()
+ }
+
+ UI.ComboBox {
+ id: accessBox
+ Layout.fillWidth: true
+ visible: addDialog.kind !== "env"
+ Accessible.name: "Access"
+ model: addDialog.kind === "folder"
+ ? [{ value: "rw", text: "Can open and change files" }, { value: "ro", text: "Can open files, not change them" }]
+ : [{ value: "talk", text: "Can talk to it" }, { value: "own", text: "Can talk to it and take its name" }]
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ visible: addDialog.error.length > 0
+ text: addDialog.error
+ size: 12
+ color: UI.Style.danger
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+
+ buttons: [
+ UI.Button {
+ id: addButton
+ text: "Add"
+ kind: "primary"
+ enabled: valueField.text.trim().length > 0
+ onClicked: {
+ if (!enabled) {
+ return;
+ }
+ const extra = addDialog.kind === "env" ? extraField.text : accessBox.currentValue;
+ const why = AppAccess.add(page.selected, addDialog.kind, valueField.text, extra);
+ if (why.length > 0) {
+ addDialog.error = why;
+ } else {
+ addDialog.close();
+ }
+ }
+ },
+ UI.Button {
+ text: "Cancel"
+ onClicked: addDialog.close()
+ }
+ ]
+ }
+
+ UI.Dialog {
+ id: resetDialog
+ title: page.app ? "Reset " + page.app.name + "?" : ""
+ text: "Every sandbox permission you changed for this app is undone, here and in the Store, and it gets exactly what it asked for when you installed it."
+ buttons: [
+ UI.Button {
+ text: "Reset"
+ kind: "primary"
+ onClicked: {
+ resetDialog.close();
+ AppAccess.reset(page.selected);
+ }
+ },
+ UI.Button {
+ text: "Cancel"
+ onClicked: resetDialog.close()
+ }
+ ]
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/AutoPlayPage.qml b/packages/wildos-settings/qml/pages/AutoPlayPage.qml
new file mode 100644
index 0000000..790add0
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/AutoPlayPage.qml
@@ -0,0 +1,147 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.Settings
+import WildOS.UI as UI
+
+// AutoPlay, after Windows 11: one switch for every drive and memory card,
+// then when it applies, and the drives this PC has seen. "Ready" here is
+// what Plasma's automounter does: the drive is mounted and shows in Files
+// without a click. Nothing on a drive is ever run.
+PageScroll {
+ id: page
+
+ readonly property bool on: AutoPlay.onPlugin || AutoPlay.onLogin
+
+ Component.onCompleted: AutoPlay.reload()
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ iconName: "play"
+ title: "Use AutoPlay for all media and devices"
+ description: "Drives and memory cards are ready in Files as soon as you plug them in"
+ status: page.on ? "On" : "Off"
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: page.on
+ Accessible.name: "Use AutoPlay for all media and devices"
+ onToggled: {
+ AutoPlay.setOnPlugin(checked);
+ AutoPlay.setOnLogin(checked);
+ }
+ }
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ visible: page.on
+ spacing: 10
+
+ SectionTitle {
+ text: "When to use AutoPlay"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ title: "When you plug in a drive or memory card"
+ status: AutoPlay.onPlugin ? "On" : "Off"
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: AutoPlay.onPlugin
+ Accessible.name: "When you plug in a drive or memory card"
+ onToggled: AutoPlay.setOnPlugin(checked)
+ }
+ }
+
+ UI.SettingRow {
+ title: "When you sign in"
+ description: "For drives that are already plugged in"
+ status: AutoPlay.onLogin ? "On" : "Off"
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: AutoPlay.onLogin
+ Accessible.name: "When you sign in"
+ onToggled: AutoPlay.setOnLogin(checked)
+ }
+ }
+
+ UI.SettingRow {
+ title: "Include drives this PC hasn't seen before"
+ description: "Otherwise only drives you've opened here before are made ready"
+ status: AutoPlay.unknownDevices ? "On" : "Off"
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: AutoPlay.unknownDevices
+ Accessible.name: "Include drives this PC hasn't seen before"
+ onToggled: AutoPlay.setUnknownDevices(checked)
+ }
+ }
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ SectionTitle {
+ text: "Drives"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ Repeater {
+ id: driveList
+ model: AutoPlay.drives
+
+ UI.SettingRow {
+ id: driveRow
+ required property var modelData
+ iconName: "usb"
+ title: modelData.name
+
+ UI.ComboBox {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "AutoPlay for " + driveRow.modelData.name
+ model: [{ value: false, text: "Use the settings above" }, { value: true, text: "Always" }]
+ readonly property bool choice: driveRow.modelData.always === true
+ currentIndex: model.findIndex(o => o.value === choice)
+ onActivated: index => AutoPlay.setAlways(driveRow.modelData.udi, model[index].value)
+ }
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Forget"
+ onClicked: AutoPlay.forget(driveRow.modelData.udi)
+ }
+ }
+ }
+
+ UI.SettingRow {
+ visible: driveList.count === 0
+ title: "No drives yet"
+ description: "Drives and memory cards you plug in appear here."
+ }
+ }
+ }
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/DefaultAppsPage.qml b/packages/wildos-settings/qml/pages/DefaultAppsPage.qml
index a048133..f4a2a73 100644
--- a/packages/wildos-settings/qml/pages/DefaultAppsPage.qml
+++ b/packages/wildos-settings/qml/pages/DefaultAppsPage.qml
@@ -49,6 +49,14 @@ PageScroll {
Column {
width: parent.width
+ UI.SettingRow {
+ iconName: "document"
+ title: "Choose defaults by file type"
+ description: "Pick the app for .pdf, .docx and every other kind of file"
+ chevron: true
+ onClicked: Navigator.open("filetypes")
+ }
+
UI.SettingRow {
visible: System.storeApp.length > 0
iconName: "store"
diff --git a/packages/wildos-settings/qml/pages/DesktopsPage.qml b/packages/wildos-settings/qml/pages/DesktopsPage.qml
new file mode 100644
index 0000000..c3bce92
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/DesktopsPage.qml
@@ -0,0 +1,138 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.Settings
+import WildOS.UI as UI
+
+// Desktops, after Windows 11's virtual desktops: the list of desktops with
+// adding, renaming and removing. The desktops are KWin's, changed over its
+// D-Bus interface, so Task View and the shortcuts follow at once. Which
+// windows the taskbar and Alt+Tab show sits on Multitasking, as in Windows.
+PageScroll {
+ id: page
+
+ readonly property bool several: Desktops.desktops.length > 1
+
+ function openMenu(button, desktop) {
+ renameDialog.desktop = desktop;
+ desktopMenu.entries = [
+ { text: "Switch to this desktop", icon: "check", enabled: desktop.id !== Desktops.current, run: () => Desktops.switchTo(desktop.id) },
+ { separator: true },
+ { text: "Rename", icon: "rename", run: () => renameDialog.open() },
+ { text: "Remove", icon: "delete", danger: true, enabled: page.several, run: () => Desktops.remove(desktop.id) }
+ ];
+ desktopMenu.popup(button, 0, button.height + 4);
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ RowLayout {
+ Layout.fillWidth: true
+ spacing: 12
+
+ SectionTitle {
+ Layout.fillWidth: true
+ text: "Your desktops"
+ }
+
+ UI.Button {
+ text: "Add a desktop"
+ iconName: "plus"
+ enabled: Desktops.available && Desktops.desktops.length < Desktops.maximum
+ onClicked: Desktops.add()
+ }
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ Repeater {
+ model: Desktops.desktops
+
+ UI.SettingRow {
+ id: desktopRow
+ required property var modelData
+ iconName: "desktops"
+ title: modelData.name
+ status: modelData.id === Desktops.current ? "In use" : ""
+ statusColor: UI.Style.accentText
+
+ UI.IconButton {
+ id: moreButton
+ anchors.verticalCenter: parent.verticalCenter
+ iconName: "more"
+ tip: "Options for " + desktopRow.modelData.name
+ onClicked: page.openMenu(moreButton, desktopRow.modelData)
+ }
+ }
+ }
+
+ UI.SettingRow {
+ visible: !Desktops.available
+ iconName: "desktops"
+ title: "Desktops aren't available right now"
+ description: "The window manager isn't answering. Try again after signing out and back in."
+ }
+ }
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: "Removing a desktop moves its windows to the desktop next to it."
+ color: UI.Style.inkMuted
+ size: 12
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+ }
+
+ UI.Menu {
+ id: desktopMenu
+ }
+
+ UI.Dialog {
+ id: renameDialog
+
+ property var desktop: null
+ readonly property string trimmed: nameField.text.trim()
+
+ title: "Rename desktop"
+ onAboutToShow: {
+ nameField.text = desktop ? desktop.name : "";
+ nameField.selectAll();
+ nameField.forceActiveFocus();
+ }
+
+ UI.TextField {
+ id: nameField
+ Layout.fillWidth: true
+ placeholderText: "Desktop name"
+ maximumLength: 64
+ onAccepted: renameButton.clicked()
+ }
+
+ buttons: [
+ UI.Button {
+ id: renameButton
+ text: "Rename"
+ kind: "primary"
+ enabled: renameDialog.desktop !== null && renameDialog.trimmed.length > 0 && renameDialog.trimmed !== renameDialog.desktop.name
+ onClicked: {
+ if (!enabled) {
+ return;
+ }
+ Desktops.rename(renameDialog.desktop.id, renameDialog.trimmed);
+ renameDialog.close();
+ }
+ },
+ UI.Button {
+ text: "Cancel"
+ onClicked: renameDialog.close()
+ }
+ ]
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/DisplayPage.qml b/packages/wildos-settings/qml/pages/DisplayPage.qml
index 11c1181..988fb31 100644
--- a/packages/wildos-settings/qml/pages/DisplayPage.qml
+++ b/packages/wildos-settings/qml/pages/DisplayPage.qml
@@ -1,194 +1,619 @@
import QtQuick
import QtQuick.Layouts
+import QtQuick.Templates as T
+import QtQuick.Window
import org.kde.plasma.private.brightnesscontrolplugin
import WildOS.Settings
import WildOS.UI as UI
-// Display, after Windows 11: brightness and night light, then scale,
-// resolution and orientation for each screen. Brightness goes through
-// powerdevil like the quick settings slider; screens through KScreen, so a
-// change is kept for the next sign-in.
+// Display (SettingsDisplay.dc): the screens as they sit on the desk, then
+// everything about the screen picked there, with brightness and night light
+// below. Screens go through Displays (libkscreen, as KDE's display module);
+// brightness through powerdevil like the quick settings slider.
+//
+// Every value here is a binding to Displays, which outlives the page, so the
+// page shows the same thing however often Settings rebuilds it; only a drag
+// in progress lives in the page.
PageScroll {
id: page
- Component.onCompleted: System.refreshDisplays()
+ // The screen the rows change. Until one is picked, and if the picked one
+ // goes away, it is the main display.
+ property int chosenId: -1
- ScreenBrightnessControl {
- id: brightness
- isSilent: true
- }
+ // A mouse drag on a screen tile moves the screen, not the page.
+ interactive: !canvas.holding && canvas.moving === null
- NightLightControl {
- id: nightLight
- }
+ readonly property var outputs: Displays.outputs
+ readonly property var enabledOutputs: outputs.filter(o => o.enabled)
+ readonly property bool several: outputs.length > 1
+ readonly property var blank: ({ id: -1, number: 0, label: "", enabled: false, primary: false, resolutions: [], resolution: "",
+ rates: [], rate: "", scale: 1, recommendedScale: 1, rotation: 1, vrrCapable: false, vrr: false, hdrCapable: false,
+ hdr: false, sdrBrightness: 200, sdrMin: 50, sdrMax: 500 })
+ readonly property var selected: outputs.find(o => o.id === chosenId) || outputs.find(o => o.primary) || outputs[0] || blank
- property var dimmable: []
+ readonly property var rotations: [
+ { value: 1, text: "Landscape" },
+ { value: 2, text: "Portrait" },
+ { value: 4, text: "Landscape (flipped)" },
+ { value: 8, text: "Portrait (flipped)" }
+ ]
- Instantiator {
- id: dimmableDisplays
- model: brightness.displays
- delegate: QtObject {
- required property string displayName
- required property string label
- required property int brightness
- required property int maxBrightness
+ function scaleOptions(current, recommended) {
+ const list = [1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75, 3];
+ for (const extra of [recommended, current]) {
+ if (!list.some(s => Math.abs(s - extra) < 0.001)) {
+ list.push(extra);
+ }
}
- onObjectAdded: page.dimmable = page.collect()
- onObjectRemoved: page.dimmable = page.collect()
+ list.sort((a, b) => a - b);
+ return list.map(s => ({
+ value: s,
+ text: Math.round(s * 100) + "%" + (Math.abs(s - recommended) < 0.001 ? " (recommended)" : "")
+ }));
}
- function collect() {
- const list = [];
- for (let i = 0; i < dimmableDisplays.count; ++i) {
- list.push(dimmableDisplays.objectAt(i));
+ function arrangementOptions(screen) {
+ const list = [
+ { value: "extend", text: "Extend" },
+ { value: "duplicate", text: "Duplicate" },
+ { value: "only", text: "Only this screen" }
+ ];
+ if (!screen.enabled || enabledOutputs.length > 1) {
+ list.push({ value: "off", text: "Off" });
}
return list;
}
- // The mode to go back to when a new resolution is not kept.
- property var pending: null
+ function arrangementOf(screen) {
+ if (!screen.enabled) {
+ return "off";
+ }
+ return Displays.arrangement;
+ }
- function changeMode(display, modeId) {
- pending = { output: display.name, mode: display.currentMode };
- System.setDisplay(display.name, "mode", modeId);
- keepDialog.seconds = 15;
- keepDialog.open();
+ Notice {
+ id: notice
+ Layout.fillWidth: true
}
- readonly property var rotations: [
- { value: 1, text: "Landscape", arg: "normal" },
- { value: 2, text: "Portrait", arg: "left" },
- { value: 4, text: "Landscape (flipped)", arg: "inverted" },
- { value: 8, text: "Portrait (flipped)", arg: "right" }
- ]
+ Connections {
+ target: Displays
+ function onFailed(reason) {
+ notice.show("The screens were not changed", reason, true);
+ }
+ function onConfirmChanged() {
+ if (Displays.confirming && !keepDialog.visible) {
+ keepDialog.open();
+ } else if (!Displays.confirming && keepDialog.visible) {
+ keepDialog.close();
+ }
+ }
+ }
- function scaleOptions(current) {
- const list = [1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 3];
- if (!list.some(s => Math.abs(s - current) < 0.001)) {
- list.push(current);
- list.sort((a, b) => a - b);
+ // A change still counting down when the page is opened again asks again.
+ Component.onCompleted: {
+ if (Displays.confirming) {
+ keepDialog.open();
}
- return list.map(s => ({ value: s, text: Math.round(s * 100) + "%" }));
}
- UI.Card {
+ Rectangle {
+ id: canvas
+
+ // The part of the desk drawing the screens fill, above the hint and
+ // buttons along the foot (SettingsDisplay.dc: 26px down, 141px tall).
+ readonly property real areaTop: 26
+ readonly property real areaHeight: height - areaTop - 39
+ readonly property real areaWidth: width - 48
+
+ readonly property bool mirrored: Displays.arrangement === "duplicate"
+ readonly property var bounds: {
+ const list = page.enabledOutputs;
+ if (list.length === 0) {
+ return null;
+ }
+ let left = Infinity, top = Infinity, right = -Infinity, bottom = -Infinity;
+ for (const o of list) {
+ left = Math.min(left, o.x);
+ top = Math.min(top, o.y);
+ right = Math.max(right, o.x + o.width);
+ bottom = Math.max(bottom, o.y + o.height);
+ }
+ return right > left && bottom > top ? { x: left, y: top, w: right - left, h: bottom - top } : null;
+ }
+ readonly property real factor: bounds ? Math.min(areaWidth / bounds.w, areaHeight / bounds.h) : 0
+ readonly property real originX: bounds ? (width - bounds.w * factor) / 2 - bounds.x * factor : 0
+ readonly property real originY: bounds ? areaTop + (areaHeight - bounds.h * factor) / 2 - bounds.y * factor : 0
+
+ // Duplicated screens show the same picture, so they are one tile,
+ // numbered "1 | 2" as Windows does.
+ readonly property var tiles: {
+ if (!bounds) {
+ return [];
+ }
+ if (mirrored) {
+ return [{ id: -1, members: page.enabledOutputs.map(o => o.id), x: bounds.x, y: bounds.y, width: bounds.w, height: bounds.h,
+ title: page.enabledOutputs.map(o => o.number).join(" | "), caption: "" }];
+ }
+ return page.enabledOutputs.map(o => ({ id: o.id, members: [o.id], x: o.x, y: o.y, width: o.width, height: o.height,
+ title: String(o.number), caption: o.label }));
+ }
+
+ // { id, x, y } of a screen being dragged, where it would land.
+ property var moving: null
+ property bool holding: false
+
+ // The 2px accent lines where the picked (or dragged) screen meets
+ // another.
+ readonly property var edges: {
+ if (mirrored || factor <= 0 || page.enabledOutputs.length < 2) {
+ return [];
+ }
+ const focus = page.enabledOutputs.find(o => o.id === (moving ? moving.id : page.selected.id));
+ if (!focus) {
+ return [];
+ }
+ const fx = moving ? moving.x : focus.x;
+ const fy = moving ? moving.y : focus.y;
+ const list = [];
+ for (const o of page.enabledOutputs) {
+ if (o.id === focus.id) {
+ continue;
+ }
+ if (fx + focus.width === o.x || o.x + o.width === fx) {
+ const from = Math.max(fy, o.y);
+ const to = Math.min(fy + focus.height, o.y + o.height);
+ if (to > from) {
+ list.push({ x: fx + focus.width === o.x ? o.x : fx, y: from, length: to - from, upright: true });
+ }
+ }
+ if (fy + focus.height === o.y || o.y + o.height === fy) {
+ const from = Math.max(fx, o.x);
+ const to = Math.min(fx + focus.width, o.x + o.width);
+ if (to > from) {
+ list.push({ x: from, y: fy + focus.height === o.y ? o.y : fy, length: to - from, upright: false });
+ }
+ }
+ }
+ return list;
+ }
+
Layout.fillWidth: true
+ Layout.preferredHeight: 206
+ visible: Displays.available
+ radius: UI.Style.radiusMd
+ color: UI.Style.shade(0.32, 0.05)
+ border.width: 1
+ border.color: UI.Style.borderSubtle
+ clip: true
+
+ // The dotted desk: a 1px dot every 16px.
+ Canvas {
+ id: dots
+
+ property color dot: UI.Style.tone(0.08)
+
+ anchors.fill: parent
+ anchors.margins: 1
+ onDotChanged: requestPaint()
+ onWidthChanged: requestPaint()
+ onHeightChanged: requestPaint()
+ onPaint: {
+ const ctx = getContext("2d");
+ ctx.clearRect(0, 0, width, height);
+ ctx.fillStyle = dot;
+ for (let y = 7; y < height; y += 16) {
+ for (let x = 7; x < width; x += 16) {
+ ctx.beginPath();
+ ctx.arc(x, y, 1, 0, 2 * Math.PI);
+ ctx.fill();
+ }
+ }
+ }
+ }
- Column {
- width: parent.width
+ Repeater {
+ model: canvas.edges
+
+ Rectangle {
+ required property var modelData
+ x: canvas.originX + modelData.x * canvas.factor + (modelData.upright ? 0 : 3)
+ y: canvas.originY + modelData.y * canvas.factor + (modelData.upright ? 3 : 0)
+ width: modelData.upright ? 2 : modelData.length * canvas.factor - 6
+ height: modelData.upright ? modelData.length * canvas.factor - 6 : 2
+ color: UI.Style.accent
+ opacity: 0.8
+ z: 3
+ }
+ }
- Repeater {
- model: page.dimmable
+ Repeater {
+ model: canvas.tiles
+
+ T.AbstractButton {
+ id: tile
+
+ required property var modelData
+ readonly property bool current: modelData.members.indexOf(page.selected.id) >= 0
+ readonly property bool movable: !canvas.mirrored && page.enabledOutputs.length > 1
+ // Where the screen would land if let go now, in desktop
+ // pixels; snapping is Displays', so the drop lands exactly
+ // where the drag showed. 12 canvas pixels pull an edge in.
+ readonly property point landing: drag.active
+ ? Displays.snap(modelData.id,
+ Math.round(modelData.x + drag.activeTranslation.x / canvas.factor),
+ Math.round(modelData.y + drag.activeTranslation.y / canvas.factor),
+ Math.round(12 / canvas.factor))
+ : Qt.point(modelData.x, modelData.y)
+
+ x: canvas.originX + landing.x * canvas.factor + 3
+ y: canvas.originY + landing.y * canvas.factor + 3
+ width: Math.max(0, modelData.width * canvas.factor - 6)
+ height: Math.max(0, modelData.height * canvas.factor - 6)
+ z: drag.active ? 2 : current ? 1 : 0
+ hoverEnabled: true
+ focusPolicy: Qt.StrongFocus
+ Accessible.role: Accessible.RadioButton
+ Accessible.name: "Display " + modelData.title + (modelData.caption.length > 0 ? ", " + modelData.caption : "")
+ Accessible.checked: current
+
+ onClicked: page.chosenId = modelData.members[0]
+ onPressedChanged: canvas.holding = pressed
+ onLandingChanged: {
+ if (drag.active) {
+ canvas.moving = { id: modelData.id, x: landing.x, y: landing.y };
+ }
+ }
- UI.SettingRow {
- id: brightnessRow
- required property var modelData
- readonly property int percent: modelData.maxBrightness > 0 ? Math.round(modelData.brightness / modelData.maxBrightness * 100) : 0
- iconName: "sun"
- title: page.dimmable.length > 1 ? "Brightness of " + modelData.label : "Brightness"
- description: page.dimmable.length > 1 ? "Makes this screen brighter or dimmer" : "Makes the screen brighter or dimmer"
- status: percent + "%"
+ DragHandler {
+ id: drag
+ target: null
+ enabled: tile.movable
+ cursorShape: Qt.ClosedHandCursor
+ // The page scrolls by mouse drag too; once a screen is
+ // moving, the page may not take the drag over.
+ grabPermissions: PointerHandler.CanTakeOverFromItems | PointerHandler.CanTakeOverFromHandlersOfDifferentType
+ onActiveChanged: {
+ if (active) {
+ page.chosenId = tile.modelData.id;
+ } else if (canvas.moving) {
+ const to = canvas.moving;
+ canvas.moving = null;
+ Displays.move(to.id, to.x, to.y);
+ }
+ }
+ }
- UI.Slider {
- anchors.verticalCenter: parent.verticalCenter
- width: 240
- accessibleName: brightnessRow.title
- from: 1
- value: brightnessRow.percent
- onMoved: brightness.setBrightness(brightnessRow.modelData.displayName,
- Math.max(1, Math.round(value / 100 * brightnessRow.modelData.maxBrightness)))
+ HoverHandler {
+ enabled: tile.movable
+ cursorShape: Qt.OpenHandCursor
+ }
+
+ background: Rectangle {
+ radius: UI.Style.radiusSm
+ color: tile.current ? UI.Style.accentAlpha(0.16, 0.12)
+ : tile.hovered ? UI.Style.tone(0.10) : UI.Style.tone(0.07)
+ border.width: tile.current ? 2 : 1
+ border.color: tile.current ? UI.Style.accent : UI.Style.tone(0.25)
+ Behavior on color {
+ ColorAnimation { duration: UI.Style.hoverDuration }
+ }
+
+ UI.FocusRing {
+ visible: tile.visualFocus
+ targetRadius: UI.Style.radiusSm
+ }
+ }
+
+ contentItem: Item {
+ Column {
+ anchors.centerIn: parent
+ width: parent.width - 8
+ spacing: 4
+
+ UI.Label {
+ width: parent.width
+ horizontalAlignment: Text.AlignHCenter
+ text: tile.modelData.title
+ size: 30
+ font.weight: Font.Light
+ }
+
+ UI.Label {
+ width: parent.width
+ visible: text.length > 0 && tile.height > 60
+ horizontalAlignment: Text.AlignHCenter
+ text: tile.modelData.caption
+ size: 11
+ color: UI.Style.inkMuted
+ }
}
}
}
+ }
- UI.SettingRow {
- visible: Pages.exists("nightlight")
- iconName: "moon"
- title: "Night light"
- description: "Warmer colours to help you sleep"
- status: nightLight.enabled ? (nightLight.inhibited ? "Paused" : "On") : "Off"
- chevron: true
- onClicked: Navigator.open("nightlight")
+ UI.Label {
+ anchors.left: parent.left
+ anchors.leftMargin: 16
+ anchors.right: canvasButtons.left
+ anchors.rightMargin: 12
+ anchors.bottom: parent.bottom
+ anchors.bottomMargin: 12
+ text: "Drag the screens to match how they sit on your desk. Edges snap together."
+ size: 12
+ color: UI.Style.inkMuted
+ }
+
+ Row {
+ id: canvasButtons
+ anchors.right: parent.right
+ anchors.rightMargin: 12
+ anchors.bottom: parent.bottom
+ anchors.bottomMargin: 10
+ spacing: 8
+
+ UI.Button {
+ text: "Identify"
+ implicitHeight: 30
+ onClicked: {
+ identify.active = true;
+ identifyTimer.restart();
+ }
+ }
+
+ UI.Button {
+ text: "Detect"
+ implicitHeight: 30
+ onClicked: Displays.reload()
}
}
}
- Repeater {
- model: System.displays
+ RowLayout {
+ Layout.fillWidth: true
+ visible: Displays.available && page.several
+ spacing: 12
+
+ Rectangle {
+ implicitWidth: choices.implicitWidth + 6
+ implicitHeight: choices.implicitHeight + 6
+ radius: 10
+ color: UI.Style.tone(0.06)
+ border.width: 1
+ border.color: UI.Style.tone(0.08)
+ Accessible.role: Accessible.Grouping
+ Accessible.name: "Display to change"
+
+ Row {
+ id: choices
+ x: 3
+ y: 3
+ spacing: 2
+
+ Repeater {
+ model: page.outputs
+
+ ScreenChoice {
+ required property var modelData
+ text: modelData.number + " " + modelData.label
+ current: modelData.id === page.selected.id
+ onClicked: page.chosenId = modelData.id
+ }
+ }
+ }
+ }
- ColumnLayout {
- id: screen
- required property var modelData
- required property int index
+ Item {
Layout.fillWidth: true
+ }
+
+ Row {
+ visible: page.selected.enabled && page.enabledOutputs.length > 1
spacing: 10
- SectionTitle {
- text: System.displays.length > 1
- ? "Screen " + (screen.index + 1) + (screen.modelData.builtIn ? ", built in" : ", " + screen.modelData.name)
- : "Scale and layout"
+ UI.Label {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Main display"
+ size: 13
}
- UI.Card {
- Layout.fillWidth: true
+ UI.Label {
+ anchors.verticalCenter: parent.verticalCenter
+ text: page.selected.primary ? "On" : "Off"
+ size: 12
+ color: UI.Style.inkMuted
+ }
- Column {
- width: parent.width
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "Make this my main display"
+ checked: page.selected.primary
+ // There is always a main display; another screen takes the
+ // role over rather than this one giving it up.
+ checkable: !page.selected.primary
+ onToggled: Displays.setPrimary(page.selected.id)
+ }
+ }
+ }
- UI.SettingRow {
- iconName: "display"
- title: "Scale"
- description: "Makes text, apps and other items bigger"
+ GridLayout {
+ Layout.fillWidth: true
+ visible: Displays.available
+ columns: width >= 640 ? 2 : 1
+ columnSpacing: 14
+ rowSpacing: 14
- UI.ComboBox {
- anchors.verticalCenter: parent.verticalCenter
- Accessible.name: "Scale"
- model: page.scaleOptions(screen.modelData.scale)
- readonly property var choice: screen.modelData.scale
- currentIndex: model ? model.findIndex(o => o.value === choice) : -1
- onActivated: index => System.setDisplay(screen.modelData.name, "scale", String(model[index].value))
- }
+ UI.Card {
+ Layout.fillWidth: true
+ Layout.preferredWidth: 1
+ Layout.alignment: Qt.AlignTop
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ title: "Resolution"
+ minHeight: 52
+ enabled: page.selected.enabled
+
+ UI.ComboBox {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "Resolution"
+ model: page.selected.resolutions
+ readonly property string choice: page.selected.resolution
+ currentIndex: model ? model.findIndex(o => o.value === choice) : -1
+ onActivated: index => Displays.setResolution(page.selected.id, model[index].value)
}
+ }
- UI.SettingRow {
- iconName: "resolution"
- title: "Display resolution"
- description: screen.modelData.currentRate > 0 ? "Refreshes " + Math.round(screen.modelData.currentRate) + " times a second" : ""
+ UI.SettingRow {
+ title: "Scale"
+ description: "Size of text and apps"
+ minHeight: 52
+ enabled: page.selected.enabled
- UI.ComboBox {
- anchors.verticalCenter: parent.verticalCenter
- Accessible.name: "Display resolution"
- model: screen.modelData.modes.map((m, i) => ({ value: m.id, text: m.text + (i === 0 ? " (recommended)" : "") }))
- readonly property var choice: {
- const current = screen.modelData.modes.find(m => m.text === screen.modelData.currentSize);
- return current ? current.id : "";
+ UI.ComboBox {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "Scale"
+ model: page.scaleOptions(page.selected.scale, page.selected.recommendedScale)
+ readonly property real choice: page.selected.scale
+ currentIndex: model ? model.findIndex(o => Math.abs(o.value - choice) < 0.001) : -1
+ onActivated: index => Displays.setScale(page.selected.id, model[index].value)
+ }
+ }
+
+ UI.SettingRow {
+ title: "Orientation"
+ minHeight: 52
+ enabled: page.selected.enabled
+
+ UI.ComboBox {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "Orientation"
+ model: page.rotations
+ readonly property int choice: page.selected.rotation
+ currentIndex: model ? model.findIndex(o => o.value === choice) : -1
+ onActivated: index => Displays.setRotation(page.selected.id, model[index].value)
+ }
+ }
+
+ UI.SettingRow {
+ visible: page.several
+ title: "With more than one display"
+ minHeight: 52
+
+ UI.ComboBox {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "Multiple displays"
+ model: page.arrangementOptions(page.selected)
+ readonly property string choice: page.arrangementOf(page.selected)
+ currentIndex: model ? model.findIndex(o => o.value === choice) : -1
+ onActivated: index => {
+ if (model[index].value !== choice) {
+ Displays.setArrangement(page.selected.id, model[index].value);
}
- currentIndex: model ? model.findIndex(o => o.value === choice) : -1
- onActivated: index => page.changeMode(screen.modelData, model[index].value)
}
}
+ }
+ }
+ }
- UI.SettingRow {
- iconName: "rotate"
- title: "Display orientation"
+ UI.Card {
+ Layout.fillWidth: true
+ Layout.preferredWidth: 1
+ Layout.alignment: Qt.AlignTop
+ visible: page.selected.rates.length > 0 || page.selected.vrrCapable || page.selected.hdrCapable
- UI.ComboBox {
- anchors.verticalCenter: parent.verticalCenter
- Accessible.name: "Display orientation"
- model: page.rotations
- readonly property var choice: screen.modelData.rotation
- currentIndex: model ? model.findIndex(o => o.value === choice) : -1
- onActivated: index => System.setDisplay(screen.modelData.name, "rotation", page.rotations.find(r => r.value === model[index].value).arg)
- }
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ visible: page.selected.rates.length > 0
+ title: "Refresh rate"
+ description: "Smoother motion, more power"
+ minHeight: 52
+ enabled: page.selected.enabled
+
+ UI.ComboBox {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "Refresh rate"
+ model: page.selected.rates
+ readonly property string choice: page.selected.rate
+ currentIndex: model ? model.findIndex(o => o.value === choice) : -1
+ onActivated: index => Displays.setRefreshRate(page.selected.id, model[index].value)
+ }
+ }
+
+ UI.SettingRow {
+ visible: page.selected.vrrCapable
+ title: "Variable refresh rate"
+ description: "Stops tearing in games and video"
+ status: page.selected.vrr ? "On" : "Off"
+ minHeight: 52
+ enabled: page.selected.enabled
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "Variable refresh rate"
+ checked: page.selected.vrr
+ onToggled: Displays.setVrr(page.selected.id, checked)
+ }
+ }
+
+ UI.SettingRow {
+ visible: page.selected.hdrCapable
+ title: "HDR"
+ description: "Brighter, richer video and games"
+ status: page.selected.hdr ? "On" : "Off"
+ minHeight: 52
+ enabled: page.selected.enabled
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "HDR"
+ checked: page.selected.hdr
+ onToggled: Displays.setHdr(page.selected.id, checked)
+ }
+ }
+
+ UI.SettingRow {
+ visible: page.selected.hdrCapable && page.selected.hdr
+ title: "Brightness of everyday content"
+ description: "With HDR on"
+ minHeight: 52
+ enabled: page.selected.enabled
+
+ UI.Slider {
+ anchors.verticalCenter: parent.verticalCenter
+ width: 120
+ flat: true
+ accessibleName: "SDR content brightness"
+ from: page.selected.sdrMin
+ to: page.selected.sdrMax
+ stepSize: 10
+ value: page.selected.sdrBrightness
+ onMoved: Displays.setSdrBrightness(page.selected.id, Math.round(value))
}
}
}
}
}
+ UI.Label {
+ Layout.fillWidth: true
+ visible: 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."
+ size: 12
+ color: UI.Style.inkMuted
+ lineHeight: 1.5
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+
UI.Card {
Layout.fillWidth: true
- visible: System.displays.length === 0
+ visible: Displays.ready && !Displays.available
Column {
width: parent.width
@@ -196,70 +621,204 @@ PageScroll {
UI.SettingRow {
iconName: "display"
title: "Screen settings are not available"
- description: "Wild OS could not read the screens from the display service. Advanced display may still help."
+ description: "Wild OS could not read the screens from the display service."
}
}
}
- UI.Card {
- Layout.fillWidth: true
+ ScreenBrightnessControl {
+ id: brightness
+ isSilent: true
+ }
- Column {
- width: parent.width
+ NightLightControl {
+ id: nightLight
+ }
- UI.SettingRow {
- visible: Pages.exists("displayadvanced")
- title: Pages.page("displayadvanced").title
- description: Pages.page("displayadvanced").description
- chevron: true
- onClicked: Navigator.open("displayadvanced")
- }
+ property var dimmable: []
+
+ Instantiator {
+ id: dimmableDisplays
+ model: brightness.displays
+ delegate: QtObject {
+ required property string displayName
+ required property string label
+ required property int brightness
+ required property int maxBrightness
}
+ onObjectAdded: page.dimmable = page.collect()
+ onObjectRemoved: page.dimmable = page.collect()
}
- UI.Dialog {
- id: keepDialog
+ function collect() {
+ const list = [];
+ for (let i = 0; i < dimmableDisplays.count; ++i) {
+ list.push(dimmableDisplays.objectAt(i));
+ }
+ return list;
+ }
- property int seconds: 15
+ ColumnLayout {
+ Layout.fillWidth: true
+ visible: page.dimmable.length > 0 || Pages.exists("nightlight")
+ spacing: 10
- title: "Keep these display settings?"
- text: "Going back to the previous resolution in " + seconds + (seconds === 1 ? " second." : " seconds.")
- onOpened: countdown.restart()
- onClosed: countdown.stop()
-
- Timer {
- id: countdown
- interval: 1000
- repeat: true
- onTriggered: {
- keepDialog.seconds -= 1;
- if (keepDialog.seconds <= 0) {
- keepDialog.revert();
+ SectionTitle {
+ text: "Brightness and colour"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ Repeater {
+ model: page.dimmable
+
+ UI.SettingRow {
+ id: brightnessRow
+ required property var modelData
+ readonly property int percent: modelData.maxBrightness > 0 ? Math.round(modelData.brightness / modelData.maxBrightness * 100) : 0
+ iconName: "sun"
+ title: page.dimmable.length > 1 ? "Brightness of " + modelData.label : "Brightness"
+ description: page.dimmable.length > 1 ? "Makes this screen brighter or dimmer" : "Makes the screen brighter or dimmer"
+ status: percent + "%"
+
+ UI.Slider {
+ anchors.verticalCenter: parent.verticalCenter
+ width: 240
+ accessibleName: brightnessRow.title
+ from: 1
+ value: brightnessRow.percent
+ onMoved: brightness.setBrightness(brightnessRow.modelData.displayName,
+ Math.max(1, Math.round(value / 100 * brightnessRow.modelData.maxBrightness)))
+ }
+ }
+ }
+
+ UI.SettingRow {
+ visible: Pages.exists("nightlight")
+ iconName: "moon"
+ title: "Night light"
+ description: "Warmer colours to help you sleep"
+ status: nightLight.enabled ? (nightLight.inhibited ? "Paused" : "On") : "Off"
+ chevron: true
+ onClicked: Navigator.open("nightlight")
}
}
}
+ }
+
+ // Identify: each screen's number, large in its bottom left corner, for
+ // three seconds. A full-screen window is the one placement Wayland lets
+ // an app ask for on a given screen; it is see-through and lets every
+ // click pass, so nothing under it is blocked.
+ Instantiator {
+ id: identify
+ active: false
+ model: page.enabledOutputs
- function revert() {
- if (page.pending) {
- System.setDisplay(page.pending.output, "mode", page.pending.mode);
- page.pending = null;
+ delegate: Window {
+ id: marker
+
+ required property var modelData
+
+ screen: {
+ const screens = Qt.application.screens;
+ for (let i = 0; i < screens.length; ++i) {
+ if (screens[i].name === modelData.name) {
+ return screens[i];
+ }
+ }
+ return null;
+ }
+ transientParent: null
+ flags: Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.WindowDoesNotAcceptFocus | Qt.WindowTransparentForInput
+ color: "transparent"
+ title: "Display " + modelData.number
+ visibility: Window.FullScreen
+
+ UI.Glass {
+ level: "menu"
+ anchors.left: parent.left
+ anchors.bottom: parent.bottom
+ anchors.margins: 48
+ width: 168
+ height: 168
+
+ UI.Label {
+ anchors.centerIn: parent
+ text: marker.modelData.number
+ size: 110
+ font.weight: Font.Light
+ }
}
- close();
}
+ }
+
+ Timer {
+ id: identifyTimer
+ interval: 3000
+ onTriggered: identify.active = false
+ }
+
+ UI.Dialog {
+ id: keepDialog
+
+ title: "Keep these display settings?"
+ text: "Switching back to the previous settings in " + Displays.secondsLeft + (Displays.secondsLeft === 1 ? " second." : " seconds.")
+ // Only Keep or the countdown ends it; a stray Escape must not leave
+ // an unreadable screen in place.
+ closePolicy: T.Popup.NoAutoClose
buttons: [
UI.Button {
- text: "Keep changes"
+ text: "Keep"
kind: "primary"
- onClicked: {
- page.pending = null;
- keepDialog.close();
- }
+ onClicked: Displays.keep()
},
UI.Button {
- text: "Revert"
- onClicked: keepDialog.revert()
+ text: "Switch back"
+ onClicked: Displays.revert()
}
]
}
+
+ component ScreenChoice: T.AbstractButton {
+ id: choice
+
+ property bool current: false
+
+ implicitWidth: label.implicitWidth + 28
+ implicitHeight: 30
+ padding: 0
+ hoverEnabled: true
+ focusPolicy: Qt.StrongFocus
+ Accessible.role: Accessible.RadioButton
+ Accessible.name: text
+ Accessible.checked: current
+
+ background: Rectangle {
+ radius: 7
+ color: choice.current ? UI.Style.tone(0.14) : choice.down ? UI.Style.surfacePressed : choice.hovered ? UI.Style.surfaceHover : "transparent"
+ Behavior on color {
+ ColorAnimation { duration: UI.Style.hoverDuration }
+ }
+
+ UI.FocusRing {
+ visible: choice.visualFocus
+ targetRadius: 7
+ }
+ }
+
+ contentItem: UI.Label {
+ id: label
+ text: choice.text
+ size: 13
+ horizontalAlignment: Text.AlignHCenter
+ font.weight: choice.current ? Font.DemiBold : Font.Normal
+ color: choice.current ? UI.Style.ink : UI.Style.inkAlpha(0.85, 0.80)
+ }
+ }
}
diff --git a/packages/wildos-settings/qml/pages/FileTypesPage.qml b/packages/wildos-settings/qml/pages/FileTypesPage.qml
new file mode 100644
index 0000000..3a852a9
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/FileTypesPage.qml
@@ -0,0 +1,95 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.Settings
+import WildOS.UI as UI
+
+// Choose defaults by file type, after Windows 11: search for an extension
+// such as .pdf or .docx, or a kind of file, and pick the app that opens it.
+// Only apps that say they can open that type are offered.
+PageScroll {
+ id: page
+
+ property var results: []
+
+ function refresh() {
+ results = DefaultApps.fileTypes(search.text);
+ }
+
+ // Searching every type on each letter would lag the field.
+ Timer {
+ id: searchTimer
+ interval: 250
+ onTriggered: page.refresh()
+ }
+
+ Connections {
+ target: DefaultApps
+ function onChanged() {
+ page.refresh();
+ }
+ }
+
+ UI.SearchField {
+ id: search
+ Layout.fillWidth: true
+ Layout.maximumWidth: 420
+ placeholderText: "Enter a file type, such as .pdf"
+ onTextChanged: searchTimer.restart()
+ Component.onCompleted: forceActiveFocus()
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ visible: page.results.length === 0
+ iconName: "search"
+ title: search.text.trim().length === 0 ? "Search for a file type" : "No file types match"
+ description: search.text.trim().length === 0 ? "Type an extension, such as .docx or .mp3, or a kind of file, such as spreadsheet"
+ : "Check the spelling, or try the extension on its own"
+ }
+
+ Repeater {
+ model: page.results
+
+ UI.SettingRow {
+ id: row
+ required property var modelData
+ themeIcon: modelData.icon
+ title: modelData.extensions
+ description: modelData.apps.length === 0 ? modelData.description + ". No app installed can open these."
+ : modelData.description
+
+ UI.ComboBox {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: row.modelData.apps.length > 0
+ Accessible.name: "Default app for " + row.modelData.extensions
+ model: row.modelData.current.length === 0 ? [{ value: "", text: "Choose an app" }].concat(row.modelData.apps)
+ : row.modelData.apps.some(a => a.value === row.modelData.current) ? row.modelData.apps
+ : row.modelData.apps.concat([{ value: row.modelData.current, text: row.modelData.current.replace(/\.desktop$/, "") }])
+ readonly property var choice: row.modelData.current
+ currentIndex: model ? model.findIndex(o => o.value === choice) : -1
+ onActivated: index => {
+ if (model[index].value.length > 0) {
+ DefaultApps.setDefaultForType(row.modelData.mime, model[index].value);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ visible: page.results.length >= 40
+ text: "Only the first 40 matches are shown. Type more of the name to find others."
+ size: 12
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/FontsPage.qml b/packages/wildos-settings/qml/pages/FontsPage.qml
new file mode 100644
index 0000000..96e464b
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/FontsPage.qml
@@ -0,0 +1,172 @@
+import QtQuick
+import QtCore
+import QtQuick.Dialogs
+import QtQuick.Layouts
+import WildOS.Settings
+import WildOS.UI as UI
+
+// Fonts, after Windows 11's Personalisation > Fonts: install a font file
+// for your account, search the fonts on this computer with a line of each,
+// and remove the ones you installed. Text size is on Personalisation.
+PageScroll {
+ id: page
+
+ readonly property int pageSize: 60
+ property int shown: pageSize
+ readonly property string query: search.text.trim().toLowerCase()
+ readonly property var matches: query.length === 0 ? Fonts.families
+ : Fonts.families.filter(f => f.family.toLowerCase().includes(query))
+ readonly property string sample: "The quick brown fox jumps over the lazy dog"
+
+ onQueryChanged: shown = pageSize
+
+ Component.onCompleted: Fonts.reload()
+
+ Connections {
+ target: Fonts
+ function onFinished(title, message, failed) {
+ notice.show(title, message, failed);
+ }
+ }
+
+ Notice {
+ id: notice
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ iconName: "font"
+ title: "Add fonts"
+ description: "Install a font file (.ttf or .otf) for your account"
+
+ UI.Spinner {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: Fonts.busy
+ }
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Browse and install fonts"
+ enabled: !Fonts.busy
+ onClicked: fontDialog.open()
+ }
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ RowLayout {
+ Layout.fillWidth: true
+ spacing: 12
+
+ SectionTitle {
+ Layout.fillWidth: true
+ text: "Available fonts"
+ }
+
+ UI.SearchField {
+ id: search
+ Layout.preferredWidth: 260
+ placeholderText: "Search fonts"
+ }
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: page.matches.length === 1 ? "1 font" : page.matches.length + " fonts"
+ size: 12
+ color: UI.Style.inkMuted
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ visible: page.matches.length === 0
+ title: Fonts.families.length === 0 ? "Looking for fonts" : "No fonts match"
+ }
+
+ Repeater {
+ model: page.matches.slice(0, page.shown)
+
+ UI.SettingRow {
+ id: fontRow
+ required property var modelData
+ title: modelData.family
+ description: (modelData.styles === 1 ? "1 style" : modelData.styles + " styles")
+ + (modelData.removable ? ", installed by you" : "")
+
+ below: UI.Label {
+ width: fontRow.width - 120
+ text: page.sample
+ size: 18
+ font.family: fontRow.modelData.family
+ elide: Text.ElideRight
+ }
+
+ UI.IconButton {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: fontRow.modelData.removable
+ enabled: !Fonts.busy
+ iconName: "delete"
+ tip: "Remove " + fontRow.modelData.family
+ onClicked: {
+ confirm.family = fontRow.modelData.family;
+ confirm.open();
+ }
+ }
+ }
+ }
+ }
+ }
+
+ UI.Button {
+ visible: page.matches.length > page.shown
+ text: "Show more fonts"
+ onClicked: page.shown += page.pageSize
+ }
+ }
+
+ FileDialog {
+ id: fontDialog
+ title: "Choose fonts to install"
+ fileMode: FileDialog.OpenFiles
+ nameFilters: ["Fonts (*.ttf *.otf *.ttc *.otc *.TTF *.OTF)"]
+ currentFolder: StandardPaths.writableLocation(StandardPaths.DownloadLocation)
+ onAccepted: Fonts.install(selectedFiles)
+ }
+
+ UI.Dialog {
+ id: confirm
+
+ property string family
+
+ title: "Remove " + family + "?"
+ text: "Apps you open from now on will not have " + family + ". Documents that use it will show another font."
+ buttons: [
+ UI.Button {
+ text: "Remove"
+ kind: "primary"
+ onClicked: {
+ confirm.close();
+ Fonts.remove(confirm.family);
+ }
+ },
+ UI.Button {
+ text: "Keep it"
+ onClicked: confirm.close()
+ }
+ ]
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/FormatsPage.qml b/packages/wildos-settings/qml/pages/FormatsPage.qml
new file mode 100644
index 0000000..9b04576
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/FormatsPage.qml
@@ -0,0 +1,150 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.Settings
+import WildOS.UI as UI
+
+// More format options, after Windows 11's "Customise format": numbers,
+// money, dates and times, measurements and paper each follow the regional
+// format or a format of their own, with how it looks beside each choice.
+// Linux keeps the date and the time together in one part (LC_TIME), so
+// they are chosen together here.
+PageScroll {
+ id: page
+
+ readonly property var formats: Language.formats()
+ readonly property var choices: [{ value: "", text: "Same as regional format" }].concat(formats)
+ readonly property string regional: formats.find(o => o.value === Language.format)?.text ?? Language.format
+
+ readonly property var parts: [
+ { key: "LC_NUMERIC", icon: "list", title: "Numbers", what: "Decimal point and thousands separator" },
+ { key: "LC_MONETARY", icon: "store", title: "Currency", what: "Currency symbol and where it goes" },
+ { key: "LC_TIME", icon: "clock", title: "Dates and times", what: "Date order, 12 or 24 hour clock, first day of the week" },
+ { key: "LC_MEASUREMENT", icon: "resolution", title: "Measurement units", what: "Metric or imperial" },
+ { key: "LC_PAPER", icon: "printer", title: "Paper size", what: "The paper documents are laid out on" }
+ ]
+
+ readonly property var fileSizeChoices: [
+ { value: 0, text: "KiB, MiB (1,024 bytes)" },
+ { value: 1, text: "KB, MB (1,024 bytes)" },
+ { value: 2, text: "kB, MB (1,000 bytes)" }
+ ]
+
+ // Typing to pick in a closed list chooses at every letter; only the
+ // choice it settles on is applied, so setting up a format the computer
+ // lacks asks for a password once.
+ Timer {
+ id: applyTimer
+ property string key
+ property string choice
+ interval: 700
+ onTriggered: Language.setCategory(key, choice)
+ }
+
+ function choose(key, value) {
+ if (applyTimer.running && applyTimer.key !== key) {
+ applyTimer.stop();
+ Language.setCategory(applyTimer.key, applyTimer.choice);
+ }
+ applyTimer.key = key;
+ applyTimer.choice = value;
+ applyTimer.restart();
+ }
+
+ Connections {
+ target: Language
+ function onFailed(reason) {
+ notice.show("The format was not changed", reason, true);
+ }
+ }
+
+ Notice {
+ id: notice
+ }
+
+ StatusCard {
+ visible: Language.needsSignOut
+ iconName: "sign-out"
+ title: "Sign out to finish"
+ description: "Apps use the new formats when you sign out and back in. Save your work first."
+
+ UI.Button {
+ text: "Sign out now"
+ onClicked: Language.signOut()
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ SectionTitle {
+ text: "Formats"
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: "Your regional format is " + page.regional + ". Choose another format for any of these and the rest stay as they are."
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ Repeater {
+ model: page.parts
+
+ UI.SettingRow {
+ id: part
+ required property var modelData
+ readonly property string chosen: Language.overrides[modelData.key] || ""
+ readonly property string effective: chosen.length > 0 ? chosen : Language.format
+ iconName: modelData.icon
+ title: modelData.title
+ description: Language.example(modelData.key, effective)
+ enabled: !Language.busy
+
+ UI.ComboBox {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: part.modelData.title
+ Accessible.description: part.modelData.what
+ model: page.choices
+ readonly property string choice: part.chosen
+ currentIndex: model.findIndex(o => o.value === choice)
+ displayText: currentIndex >= 0 ? currentText : choice
+ onActivated: index => page.choose(part.modelData.key, model[index].value)
+ }
+ }
+ }
+
+ UI.SettingRow {
+ iconName: "storage"
+ title: "File sizes"
+ description: "A file of 1,536,000 bytes shows as " + Language.fileSizeExample(Language.fileSizeUnits)
+
+ UI.ComboBox {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "File sizes"
+ model: page.fileSizeChoices
+ readonly property int choice: Language.fileSizeUnits
+ currentIndex: Math.max(0, model.findIndex(o => o.value === choice))
+ onActivated: index => Language.setFileSizeUnits(model[index].value)
+ }
+ }
+ }
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: Language.busy ? "Getting the format ready on this computer" : "File sizes change in each app the next time it opens."
+ size: 12
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/GameControllersPage.qml b/packages/wildos-settings/qml/pages/GameControllersPage.qml
new file mode 100644
index 0000000..37694cc
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/GameControllersPage.qml
@@ -0,0 +1,109 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.Settings
+import WildOS.UI as UI
+
+// Game controllers, after the Windows game controller test: each
+// controller with its battery, and its buttons and sticks moving live, so
+// a person can see that every one works before blaming the game.
+PageScroll {
+ id: page
+
+ readonly property var controllers: GameControllers.controllers
+
+ Component.onCompleted: GameControllers.active = true
+ Component.onDestruction: GameControllers.active = false
+
+ function batteryText(level) {
+ switch (level) {
+ case "full": return "Battery full";
+ case "medium": return "Battery half full";
+ case "low": return "Battery low";
+ case "empty": return "Battery almost empty";
+ case "wired": return "Connected by cable";
+ default: return "Connected";
+ }
+ }
+
+ StatusCard {
+ visible: page.controllers.length === 0
+ iconName: "games"
+ warning: true
+ title: "No game controller connected"
+ description: "Plug in a controller, or pair one in Bluetooth, and it appears here."
+
+ UI.Button {
+ visible: Pages.exists("bluetooth")
+ text: "Bluetooth"
+ onClicked: Navigator.open("bluetooth")
+ }
+ }
+
+ // The state changes many times a second while a stick moves, so the
+ // repeaters count rather than take the lists, and the rows stay put
+ // while their values follow.
+ Repeater {
+ model: page.controllers.length
+
+ ColumnLayout {
+ id: controller
+ required property int index
+ readonly property var modelData: page.controllers[index] || ({ name: "", battery: "", buttons: [], axes: [] })
+ Layout.fillWidth: true
+ spacing: 10
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ iconName: "games"
+ title: controller.modelData.name
+ description: page.batteryText(controller.modelData.battery)
+ descriptionColor: controller.modelData.battery === "low" || controller.modelData.battery === "empty" ? UI.Style.warning : UI.Style.inkMuted
+ }
+
+ UI.SettingRow {
+ visible: controller.modelData.buttons.length > 0
+ title: "Buttons"
+ description: "Press a button and it lights up"
+
+ below: Repeater {
+ model: controller.modelData.buttons.length
+
+ UI.Chip {
+ required property int index
+ readonly property var button: controller.modelData.buttons[index] || ({ name: "", pressed: false })
+ text: button.name
+ granted: button.pressed
+ }
+ }
+ }
+
+ Repeater {
+ model: controller.modelData.axes.length
+
+ UI.SettingRow {
+ id: axisRow
+ required property int index
+ readonly property var modelData: controller.modelData.axes[index] || ({ name: "", value: 0 })
+ title: modelData.name
+
+ UI.ProgressBar {
+ anchors.verticalCenter: parent.verticalCenter
+ width: 240
+ barHeight: 6
+ from: 0
+ to: 1
+ value: axisRow.modelData.value
+ Accessible.name: axisRow.modelData.name
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/KeyboardAdvancedPage.qml b/packages/wildos-settings/qml/pages/KeyboardAdvancedPage.qml
new file mode 100644
index 0000000..040aff0
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/KeyboardAdvancedPage.qml
@@ -0,0 +1,246 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.Settings
+import WildOS.UI as UI
+
+// More keyboard options: the keyboard model, and where the compose and Alt
+// Gr keys are, the XKB options people actually reach for. Caps Lock and
+// the keys that switch layouts are on the Keyboard page itself. KWin
+// rebuilds the keymap as soon as a choice is made.
+PageScroll {
+ id: page
+
+ readonly property var composeChoices: [
+ { value: "", text: "None" },
+ { value: "compose:ralt", text: "Right Alt" },
+ { value: "compose:rwin", text: "Right Windows key" },
+ { value: "compose:menu", text: "Menu key" },
+ { value: "compose:rctrl", text: "Right Ctrl" },
+ { value: "compose:caps", text: "Caps Lock" },
+ { value: "compose:prsc", text: "Print Screen" },
+ { value: "compose:sclk", text: "Scroll Lock" },
+ { value: "compose:paus", text: "Pause" },
+ { value: "compose:ins", text: "Insert" }
+ ]
+
+ readonly property var altGrChoices: [
+ { value: "", text: "As the layout has it" },
+ { value: "lv3:ralt_switch", text: "Right Alt" },
+ { value: "lv3:lalt_switch", text: "Left Alt" },
+ { value: "lv3:alt_switch", text: "Either Alt" },
+ { value: "lv3:rwin_switch", text: "Right Windows key" },
+ { value: "lv3:menu_switch", text: "Menu key" },
+ { value: "lv3:switch", text: "Right Ctrl" },
+ { value: "lv3:caps_switch", text: "Caps Lock" },
+ { value: "lv3:ralt_alt", text: "None, Right Alt is a normal Alt" }
+ ]
+
+ // A choice made somewhere else, such as by hand in kxkbrc, still shows
+ // as itself instead of passing for the first entry.
+ function withCurrent(choices, current) {
+ if (choices.some(o => o.value === current)) {
+ return choices;
+ }
+ return choices.concat([{ value: current, text: "Another key" }]);
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ iconName: "keyboard"
+ title: "Keyboard model"
+ description: Keyboard.modelName
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Change"
+ onClicked: modelDialog.open()
+ }
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ SectionTitle {
+ text: "Special keys"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ title: "Compose key"
+ description: "Press it, then two keys in turn, to type characters such as é, ñ or €"
+
+ UI.ComboBox {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "Compose key"
+ readonly property string choice: Keyboard.compose
+ model: page.withCurrent(page.composeChoices, choice)
+ currentIndex: Math.max(0, model.findIndex(o => o.value === choice))
+ onActivated: index => Keyboard.setCompose(model[index].value)
+ }
+ }
+
+ UI.SettingRow {
+ title: "Alt Gr key"
+ description: "Hold it to type the extra characters shown on some keys"
+
+ UI.ComboBox {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "Alt Gr key"
+ readonly property string choice: Keyboard.altGr
+ model: page.withCurrent(page.altGrChoices, choice)
+ currentIndex: Math.max(0, model.findIndex(o => o.value === choice))
+ onActivated: index => Keyboard.setAltGr(model[index].value)
+ }
+ }
+
+ UI.SettingRow {
+ title: "Try it here"
+
+ UI.TextField {
+ anchors.verticalCenter: parent.verticalCenter
+ width: 240
+ placeholderText: "Type in this box"
+ }
+ }
+ }
+ }
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ iconName: "caps-lock"
+ title: "Caps Lock and switching layouts"
+ description: "Set on the Keyboard page"
+ chevron: true
+ onClicked: Navigator.open("keyboard")
+ }
+ }
+ }
+
+ UI.Dialog {
+ id: modelDialog
+
+ property var all: []
+ property int chosen: -1
+ readonly property var shown: {
+ const query = filter.text.trim().toLowerCase();
+ return all.filter(m => query.length === 0 || m.name.toLowerCase().includes(query) || m.model.toLowerCase().includes(query));
+ }
+
+ title: "Keyboard model"
+ text: "Most keyboards work as a Generic 105-key PC. Choose your own model if some of its keys do nothing."
+ onAboutToShow: {
+ if (all.length === 0) {
+ all = Keyboard.models();
+ }
+ filter.text = "";
+ chosen = shown.findIndex(m => m.model === Keyboard.model);
+ filter.forceActiveFocus();
+ }
+
+ UI.SearchField {
+ id: filter
+ Layout.fillWidth: true
+ placeholderText: "Search models, for example Logitech"
+ onTextChanged: modelDialog.chosen = -1
+ onDownPressed: {
+ modelDialog.chosen = Math.max(0, modelDialog.chosen);
+ list.forceActiveFocus();
+ }
+ onAccepted: {
+ if (modelDialog.shown.length === 1) {
+ modelDialog.chosen = 0;
+ }
+ useButton.clicked();
+ }
+ }
+
+ Rectangle {
+ Layout.fillWidth: true
+ Layout.preferredHeight: 280
+ radius: UI.Style.radiusSm
+ color: UI.Style.surfaceSunken
+ border.width: 1
+ border.color: UI.Style.borderField
+
+ ListView {
+ id: list
+ anchors.fill: parent
+ anchors.margins: 4
+ clip: true
+ model: modelDialog.shown
+ currentIndex: modelDialog.chosen
+ boundsBehavior: Flickable.StopAtBounds
+ keyNavigationEnabled: true
+ onCurrentIndexChanged: modelDialog.chosen = currentIndex
+ Keys.onReturnPressed: useButton.clicked()
+
+ delegate: UI.ListRow {
+ required property var modelData
+ required property int index
+ width: ListView.view.width
+ minHeight: 36
+ divider: false
+ radius: UI.Style.radiusXs
+ interactive: true
+ title: modelData.name
+ checked: index === modelDialog.chosen
+ background: Rectangle {
+ radius: UI.Style.radiusXs
+ color: parent.checked ? UI.Style.accentSelected : parent.hovered ? UI.Style.surfaceHover : "transparent"
+ }
+ onClicked: modelDialog.chosen = index
+ onDoubleClicked: {
+ modelDialog.chosen = index;
+ useButton.clicked();
+ }
+ }
+
+ UI.Label {
+ anchors.centerIn: parent
+ visible: list.count === 0
+ text: "No models match"
+ color: UI.Style.inkMuted
+ }
+ }
+ }
+
+ buttons: [
+ UI.Button {
+ id: useButton
+ text: "Use"
+ kind: "primary"
+ enabled: modelDialog.chosen >= 0 && modelDialog.chosen < modelDialog.shown.length
+ onClicked: {
+ if (!enabled) {
+ return;
+ }
+ Keyboard.setModel(modelDialog.shown[modelDialog.chosen].model);
+ modelDialog.close();
+ }
+ },
+ UI.Button {
+ text: "Cancel"
+ onClicked: modelDialog.close()
+ }
+ ]
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/MultitaskingPage.qml b/packages/wildos-settings/qml/pages/MultitaskingPage.qml
index eca6c63..2534aa2 100644
--- a/packages/wildos-settings/qml/pages/MultitaskingPage.qml
+++ b/packages/wildos-settings/qml/pages/MultitaskingPage.qml
@@ -3,11 +3,15 @@ import QtQuick.Layouts
import WildOS.Settings
import WildOS.UI as UI
-// Multitasking: snapping and Alt+Tab. Each switch writes kwinrc and asks
-// KWin to reload, so the change applies without signing out.
+// 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.
PageScroll {
id: page
+ Component.onCompleted: System.readTaskbarDesktops()
+
UI.Card {
Layout.fillWidth: true
@@ -58,6 +62,22 @@ PageScroll {
Column {
width: parent.width
+ UI.SettingRow {
+ title: "On the taskbar, show all open windows"
+
+ UI.ComboBox {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "On the taskbar, show all open windows"
+ model: [
+ { value: false, text: "Only on the desktop I'm using" },
+ { value: true, text: "On all desktops" }
+ ]
+ readonly property bool choice: System.taskbarAllDesktops
+ currentIndex: model.findIndex(o => o.value === choice)
+ onActivated: index => System.setTaskbarAllDesktops(model[index].value)
+ }
+ }
+
UI.SettingRow {
title: "Show windows from all desktops in Alt+Tab"
description: "When this is off, Alt+Tab only shows windows on the desktop you are using"
diff --git a/packages/wildos-settings/qml/pages/NetworkAdvancedPage.qml b/packages/wildos-settings/qml/pages/NetworkAdvancedPage.qml
new file mode 100644
index 0000000..258b61c
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/NetworkAdvancedPage.qml
@@ -0,0 +1,990 @@
+import QtQuick
+import QtCore
+import QtQuick.Dialogs
+import QtQuick.Layouts
+import WildOS.Settings
+import WildOS.UI as UI
+
+// Advanced network settings, laid out as SettingsNetwork.dc.html: VPN and
+// saved Wi-Fi networks on the left, the network in use and the proxy on the
+// right. "See all" and "Hardware details" open inside this page and stack
+// in the breadcrumb, as Printers does.
+//
+// Everything shown is bound to NetworkSettings, which outlives the page, so
+// coming back to it rebuilds the same thing; nothing here is set up once
+// and kept.
+PageScroll {
+ id: page
+
+ // "", "saved" or "hardware"
+ property string view: ""
+ readonly property int depth: view.length > 0 ? 2 : 1
+ readonly property var subTitles: view === "saved" ? ["Saved Wi-Fi networks"] : view === "hardware" ? ["Hardware details"] : []
+
+ function back() {
+ if (view.length > 0) {
+ view = "";
+ return true;
+ }
+ return false;
+ }
+
+ readonly property var current: NetworkSettings.current
+ readonly property bool connected: current.uuid !== undefined
+ readonly property string busy: NetworkSettings.busy
+
+ // A choice that needs more typed before it is saved.
+ property bool customDnsOpen: false
+ property string proxyEditing: ""
+ readonly property string dnsShown: customDnsOpen ? "custom" : (current.dns || "automatic")
+ readonly property string proxyShown: proxyEditing.length > 0 ? proxyEditing : NetworkSettings.proxy.mode
+
+ // Keeps "Connected 2 h 14 min" and "Last used" true while the page is
+ // open, and catches changes NetworkManager makes without a signal.
+ property date now: new Date()
+ Timer {
+ interval: 5000
+ running: true
+ repeat: true
+ onTriggered: {
+ page.now = new Date();
+ NetworkSettings.refresh();
+ }
+ }
+
+ Component.onCompleted: NetworkSettings.refresh()
+
+ function duration(ms) {
+ const minutes = Math.floor(ms / 60000);
+ if (minutes < 1) {
+ return "just now";
+ }
+ const hours = Math.floor(minutes / 60);
+ if (hours === 0) {
+ return minutes + " min";
+ }
+ return minutes % 60 === 0 ? hours + " h" : hours + " h " + (minutes % 60) + " min";
+ }
+
+ function vpnDescription(vpn) {
+ page.now;
+ if (vpn.state === "on") {
+ return vpn.kind + ". Connected" + (vpn.since > 0 ? " " + duration(Date.now() - vpn.since) : "");
+ }
+ if (vpn.state === "connecting") {
+ return vpn.kind + ". Connecting";
+ }
+ if (vpn.state === "dropped") {
+ return vpn.kind + ". Dropped, so the internet is blocked until it connects again";
+ }
+ return vpn.server.length > 0 ? vpn.kind + ". " + vpn.server : vpn.kind;
+ }
+
+ function lastUsed(ms) {
+ page.now;
+ if (!ms) {
+ return "Not used yet";
+ }
+ const then = new Date(ms);
+ const today = new Date();
+ const midnight = new Date(today.getFullYear(), today.getMonth(), today.getDate());
+ const days = Math.ceil((midnight - new Date(then.getFullYear(), then.getMonth(), then.getDate())) / 86400000);
+ if (days <= 0) {
+ return "Last used today";
+ }
+ if (days === 1) {
+ return "Last used yesterday";
+ }
+ if (days < 7) {
+ return "Last used " + days + " days ago";
+ }
+ if (days < 14) {
+ return "Last used last week";
+ }
+ if (days < 31) {
+ return "Last used " + Math.floor(days / 7) + " weeks ago";
+ }
+ if (days < 365) {
+ return "Last used in " + Format.months[then.getMonth()];
+ }
+ return "Last used over a year ago";
+ }
+
+ function wifiDescription(net) {
+ const parts = [];
+ if (net.active) {
+ parts.push("Connected");
+ } else if (net.connecting) {
+ parts.push("Connecting");
+ }
+ if (net.metered) {
+ parts.push("Metered");
+ }
+ if (net.active) {
+ if (net.autoconnect) {
+ parts.push("Joins automatically");
+ }
+ } else if (!net.connecting) {
+ parts.push(lastUsed(net.lastUsed));
+ }
+ return parts.join(". ");
+ }
+
+ function speedText(kbits) {
+ if (!kbits) {
+ return "";
+ }
+ return kbits >= 1000000 ? (kbits / 1000000).toFixed(1).replace(/\.0$/, "") + " Gbps" : Math.round(kbits / 1000) + " Mbps";
+ }
+
+ function frequencyText(mhz) {
+ if (!mhz) {
+ return "";
+ }
+ const band = mhz >= 5925 ? "6 GHz" : mhz >= 4900 ? "5 GHz" : "2.4 GHz";
+ return band + ", " + mhz + " MHz";
+ }
+
+ readonly property string dnsDescription: {
+ if (dnsShown === "automatic") {
+ return "From the network, so your provider can see the sites you visit";
+ }
+ if (dnsShown === "custom" && !current.dnsEncrypted) {
+ return "Not encrypted unless each server has its name after #";
+ }
+ return "Encrypted, so your provider can't see the sites you visit";
+ }
+
+ readonly property string killSwitchDescription: {
+ if (!NetworkSettings.killSwitch) {
+ return "Block the internet if the VPN drops";
+ }
+ if (NetworkSettings.killSwitchState === "blocking") {
+ return "The VPN dropped, so the internet is blocked until it connects again or you turn it off";
+ }
+ if (NetworkSettings.killSwitchState === "mullvad") {
+ return "The Mullvad app's own kill switch is guarding its connection";
+ }
+ return "Block the internet if the VPN drops";
+ }
+
+ Connections {
+ target: NetworkSettings
+ function onDone(title, message) {
+ notice.show(title, message, false);
+ }
+ function onFailed(title, reason) {
+ notice.show(title, reason, true);
+ page.customDnsOpen = false;
+ }
+ }
+
+ Notice {
+ id: notice
+ }
+
+ GridLayout {
+ Layout.fillWidth: true
+ visible: page.view === ""
+ columns: width >= 820 ? 2 : 1
+ columnSpacing: 20
+ rowSpacing: Metrics.sectionGap
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ Layout.preferredWidth: 1
+ Layout.alignment: Qt.AlignTop
+ spacing: 18
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ SectionTitle {
+ text: "VPN"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ Repeater {
+ model: NetworkSettings.vpns
+
+ UI.SettingRow {
+ id: vpnRow
+ required property var modelData
+ readonly property bool wanted: modelData.state !== "off"
+ readonly property bool up: modelData.state === "on"
+
+ minHeight: 58
+ title: modelData.name
+ description: page.vpnDescription(modelData)
+ descriptionColor: modelData.state === "dropped" ? UI.Style.warning : UI.Style.inkMuted
+ status: wanted ? "On" : "Off"
+ leading: Rectangle {
+ width: 34
+ height: 34
+ radius: 9
+ color: vpnRow.up ? UI.Style.successSoft : UI.Style.surfaceTile
+
+ UI.Icon {
+ anchors.centerIn: parent
+ name: "lock"
+ size: 16
+ strokeWidth: 1.8
+ color: vpnRow.up ? UI.Style.success : UI.Style.iconInk
+ }
+ }
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: vpnRow.wanted
+ Accessible.name: "Connect to " + vpnRow.modelData.name
+ onToggled: NetworkSettings.setVpnActive(vpnRow.modelData.uuid, checked)
+ }
+ }
+ }
+
+ UI.SettingRow {
+ minHeight: 58
+ title: "Add a VPN"
+ description: "Import a WireGuard or OpenVPN file, or type the details"
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Add"
+ busy: page.busy === "import"
+ enabled: page.busy.length === 0
+ onClicked: addVpnDialog.open()
+ }
+ }
+
+ UI.SettingRow {
+ minHeight: 58
+ title: "Kill switch"
+ description: page.killSwitchDescription
+ descriptionColor: NetworkSettings.killSwitchState === "blocking" ? UI.Style.warning : UI.Style.inkMuted
+ status: NetworkSettings.killSwitch ? "On" : "Off"
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: NetworkSettings.killSwitch
+ enabled: page.busy.length === 0
+ Accessible.name: "VPN kill switch"
+ onToggled: NetworkSettings.setKillSwitch(checked)
+ }
+ }
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ SectionTitle {
+ text: "Saved Wi-Fi networks"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ Repeater {
+ model: NetworkSettings.savedWifi.slice(0, 3)
+
+ SavedNetworkRow {
+ required property var modelData
+ network: modelData
+ description: page.wifiDescription(modelData)
+ }
+ }
+
+ UI.SettingRow {
+ visible: NetworkSettings.savedWifi.length === 0
+ minHeight: 46
+ title: "No saved networks"
+ description: "Networks you join are remembered here"
+ }
+
+ UI.SettingRow {
+ visible: NetworkSettings.savedWifi.length > 3
+ minHeight: 44
+ title: "See all " + NetworkSettings.savedWifi.length + " networks"
+ chevron: true
+ onClicked: page.view = "saved"
+ }
+ }
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ Layout.preferredWidth: 1
+ Layout.alignment: Qt.AlignTop
+ spacing: 18
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ SectionTitle {
+ text: page.connected ? page.current.name : "Network in use"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ visible: !page.connected
+ minHeight: 52
+ title: "Not connected"
+ description: "Connect to a network to change its address, DNS and other settings here"
+ }
+
+ UI.SettingRow {
+ visible: page.connected
+ minHeight: 52
+ title: "IP address"
+ description: (page.current.address || "No address yet") + (page.current.manual ? ", set by you" : ", set automatically")
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Edit"
+ busy: page.busy === "address"
+ enabled: page.busy.length === 0
+ onClicked: ipDialog.open()
+ }
+ }
+
+ UI.SettingRow {
+ visible: page.connected
+ minHeight: 52
+ title: "DNS"
+ description: page.dnsDescription
+
+ UI.ComboBox {
+ id: dnsBox
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "DNS server"
+ enabled: page.busy.length === 0 || page.busy === "dns"
+ model: [
+ { value: "automatic", text: "Automatic" },
+ { value: "quad9", text: "Quad9 encrypted" },
+ { value: "cloudflare", text: "Cloudflare encrypted" },
+ { value: "mullvad", text: "Mullvad encrypted" },
+ { value: "custom", text: "Custom" }
+ ]
+ currentIndex: model.findIndex(o => o.value === page.dnsShown)
+ onActivated: index => {
+ const choice = valueAt(index);
+ if (choice === "custom") {
+ customDnsField.text = page.current.dnsCustom || "";
+ page.customDnsOpen = true;
+ customDnsField.forceActiveFocus();
+ } else {
+ page.customDnsOpen = false;
+ if (choice !== page.current.dns) {
+ NetworkSettings.setDns(choice);
+ }
+ }
+ }
+ }
+ }
+
+ UI.SettingRow {
+ visible: page.connected && page.dnsShown === "custom"
+ minHeight: 52
+ title: "DNS servers"
+ description: customDnsField.text.length > 0 ? NetworkSettings.checkCustomDns(customDnsField.text)
+ : "Separate them with commas. Add #name after an address to encrypt it, as in 9.9.9.9#dns.quad9.net"
+ descriptionColor: customDnsField.text.length > 0 ? UI.Style.danger : UI.Style.inkMuted
+
+ UI.TextField {
+ id: customDnsField
+ anchors.verticalCenter: parent.verticalCenter
+ width: 200
+ placeholderText: "Addresses"
+ Accessible.name: "DNS servers"
+ Component.onCompleted: text = page.current.dnsCustom || ""
+ onAccepted: dnsSave.clicked()
+ }
+
+ UI.Button {
+ id: dnsSave
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Save"
+ kind: "primary"
+ busy: page.busy === "dns"
+ enabled: page.busy.length === 0 && NetworkSettings.checkCustomDns(customDnsField.text).length === 0
+ && (page.customDnsOpen || customDnsField.text !== page.current.dnsCustom)
+ onClicked: {
+ if (!enabled) {
+ return;
+ }
+ page.customDnsOpen = false;
+ NetworkSettings.setDns("custom", customDnsField.text);
+ }
+ }
+ }
+
+ UI.SettingRow {
+ visible: page.connected
+ minHeight: 52
+ title: "Private hardware address"
+ description: page.current.wifi ? "A new random address every time you connect" : "A random address of its own for this network"
+ status: page.current.privateAddress ? "On" : "Off"
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: page.current.privateAddress === true
+ enabled: page.busy.length === 0
+ Accessible.name: "Private hardware address"
+ onToggled: NetworkSettings.setPrivateAddress(checked)
+ }
+ }
+
+ UI.SettingRow {
+ visible: page.connected
+ minHeight: 52
+ title: "Metered connection"
+ description: "Holds back big downloads and updates"
+ status: page.current.metered ? "On" : "Off"
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: page.current.metered === true
+ enabled: page.busy.length === 0
+ Accessible.name: "Metered connection"
+ onToggled: NetworkSettings.setMetered(checked)
+ }
+ }
+
+ UI.SettingRow {
+ visible: page.connected
+ minHeight: 52
+ title: "Hardware details"
+ description: "Speed, frequency, IPv6 and MAC address"
+ chevron: true
+ onClicked: page.view = "hardware"
+ }
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ SectionTitle {
+ text: "Proxy"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ minHeight: 52
+ title: "Use a proxy server"
+ description: "Usually only needed at work or school"
+
+ UI.ComboBox {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "Proxy"
+ model: [
+ { value: "off", text: "Off" },
+ { value: "automatic", text: "Find automatically" },
+ { value: "script", text: "Setup script" },
+ { value: "manual", text: "Manual" }
+ ]
+ currentIndex: model.findIndex(o => o.value === page.proxyShown)
+ onActivated: index => {
+ const mode = valueAt(index);
+ if (mode === "manual" || mode === "script") {
+ proxyHost.text = NetworkSettings.proxy.host || "";
+ proxyPort.text = NetworkSettings.proxy.port > 0 ? "" + NetworkSettings.proxy.port : "";
+ proxyScript.text = NetworkSettings.proxy.script || "";
+ page.proxyEditing = mode;
+ } else {
+ page.proxyEditing = "";
+ NetworkSettings.setProxy(mode);
+ }
+ }
+ }
+ }
+
+ UI.SettingRow {
+ visible: page.proxyShown === "manual"
+ minHeight: 52
+ title: "Proxy server"
+
+ UI.TextField {
+ id: proxyHost
+ anchors.verticalCenter: parent.verticalCenter
+ width: 170
+ placeholderText: "Address"
+ Accessible.name: "Proxy address"
+ Component.onCompleted: text = NetworkSettings.proxy.host || ""
+ onTextEdited: page.proxyEditing = "manual"
+ onAccepted: proxySave.clicked()
+ }
+
+ UI.TextField {
+ id: proxyPort
+ anchors.verticalCenter: parent.verticalCenter
+ width: 76
+ placeholderText: "Port"
+ Accessible.name: "Proxy port"
+ validator: IntValidator { bottom: 1; top: 65535 }
+ Component.onCompleted: text = NetworkSettings.proxy.port > 0 ? "" + NetworkSettings.proxy.port : ""
+ onTextEdited: page.proxyEditing = "manual"
+ onAccepted: proxySave.clicked()
+ }
+
+ UI.Button {
+ id: proxySave
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Save"
+ kind: "primary"
+ visible: page.proxyEditing === "manual"
+ enabled: proxyHost.text.trim().length > 0 && parseInt(proxyPort.text) > 0
+ onClicked: {
+ if (!enabled) {
+ return;
+ }
+ NetworkSettings.setProxy("manual", proxyHost.text.trim(), parseInt(proxyPort.text));
+ page.proxyEditing = "";
+ }
+ }
+ }
+
+ UI.SettingRow {
+ visible: page.proxyShown === "script"
+ minHeight: 52
+ title: "Script address"
+
+ UI.TextField {
+ id: proxyScript
+ anchors.verticalCenter: parent.verticalCenter
+ width: 220
+ placeholderText: "For example http://wpad/proxy.pac"
+ Accessible.name: "Setup script address"
+ Component.onCompleted: text = NetworkSettings.proxy.script || ""
+ onTextEdited: page.proxyEditing = "script"
+ onAccepted: scriptSave.clicked()
+ }
+
+ UI.Button {
+ id: scriptSave
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Save"
+ kind: "primary"
+ visible: page.proxyEditing === "script"
+ enabled: proxyScript.text.trim().length > 0
+ onClicked: {
+ if (!enabled) {
+ return;
+ }
+ NetworkSettings.setProxy("script", "", 0, proxyScript.text.trim());
+ page.proxyEditing = "";
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+ visible: page.view === "saved"
+
+ Column {
+ width: parent.width
+
+ Repeater {
+ model: page.view === "saved" ? NetworkSettings.savedWifi : []
+
+ SavedNetworkRow {
+ required property var modelData
+ network: modelData
+ description: page.wifiDescription(modelData)
+ }
+ }
+
+ UI.SettingRow {
+ visible: NetworkSettings.savedWifi.length === 0
+ minHeight: 46
+ title: "No saved networks"
+ description: "Networks you join are remembered here"
+ }
+ }
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+ visible: page.view === "hardware"
+
+ Column {
+ width: parent.width
+
+ Repeater {
+ model: {
+ const c = page.current;
+ const rows = [];
+ if (!page.connected) {
+ return [{ title: "Not connected", value: "" }];
+ }
+ rows.push({ title: "Connection", value: c.wifi ? "Wi-Fi" : "Ethernet" });
+ if (c.speed) {
+ rows.push({ title: "Speed", value: page.speedText(c.speed) });
+ }
+ if (c.frequency) {
+ rows.push({ title: "Frequency", value: page.frequencyText(c.frequency) });
+ }
+ if (c.address) {
+ rows.push({ title: "IPv4 address", value: c.address + "/" + c.prefix });
+ }
+ if (c.gateway) {
+ rows.push({ title: "Default gateway", value: c.gateway });
+ }
+ rows.push({ title: "IPv6 address", value: c.ipv6 && c.ipv6.length > 0 ? c.ipv6.join("\n") : "None" });
+ if (c.dnsServers && c.dnsServers.length > 0) {
+ rows.push({ title: "DNS servers", value: c.dnsServers.join("\n") });
+ }
+ if (c.mac) {
+ rows.push({ title: "MAC address", value: c.mac });
+ }
+ if (c.permanentMac && c.permanentMac !== c.mac) {
+ rows.push({ title: "Built-in MAC address", value: c.permanentMac });
+ }
+ if (c.interface) {
+ rows.push({ title: "Device", value: c.interface });
+ }
+ return rows;
+ }
+
+ UI.SettingRow {
+ id: detailRow
+ required property var modelData
+ minHeight: 46
+ title: modelData.title
+ Accessible.description: modelData.value
+
+ UI.Label {
+ anchors.verticalCenter: parent.verticalCenter
+ text: detailRow.modelData.value
+ // Several addresses go one to a line.
+ wrapMode: Text.Wrap
+ size: 13
+ horizontalAlignment: Text.AlignRight
+ }
+ }
+ }
+ }
+ }
+
+ // An inline component cannot see this page's ids, so the row is handed
+ // its wording.
+ component SavedNetworkRow: UI.SettingRow {
+ id: savedRow
+
+ property var network: ({})
+
+ minHeight: 46
+ title: network.name || ""
+
+ UI.LinkButton {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Forget"
+ enabled: NetworkSettings.busy.length === 0
+ Accessible.name: "Forget " + savedRow.network.name
+ onClicked: NetworkSettings.forget(savedRow.network.uuid)
+ }
+ }
+
+ UI.Dialog {
+ id: addVpnDialog
+
+ property bool typing: false
+ readonly property var details: ({
+ name: vpnName.text,
+ endpoint: vpnEndpoint.text,
+ publicKey: vpnPublicKey.text,
+ privateKey: vpnPrivateKey.text,
+ address: vpnAddress.text,
+ dns: vpnDns.text
+ })
+ readonly property string problem: typing ? NetworkSettings.checkWireGuard(details) : ""
+ readonly property bool started: vpnName.text.length > 0 || vpnEndpoint.text.length > 0 || vpnPublicKey.text.length > 0
+ || vpnPrivateKey.text.length > 0 || vpnAddress.text.length > 0
+
+ title: "Add a VPN"
+ text: typing ? "Type the WireGuard details your VPN provider gave you."
+ : "Import the file your VPN provider gave you: a WireGuard .conf or an OpenVPN .ovpn file. If you only have the details, type them instead."
+ onAboutToShow: {
+ typing = false;
+ vpnName.text = "";
+ vpnEndpoint.text = "";
+ vpnPublicKey.text = "";
+ vpnPrivateKey.text = "";
+ vpnAddress.text = "";
+ vpnDns.text = "";
+ }
+
+ FieldLabel {
+ visible: addVpnDialog.typing
+ text: "Name"
+ }
+
+ UI.TextField {
+ id: vpnName
+ Layout.fillWidth: true
+ visible: addVpnDialog.typing
+ placeholderText: "For example Home office"
+ }
+
+ FieldLabel {
+ visible: addVpnDialog.typing
+ text: "Server, with its port"
+ }
+
+ UI.TextField {
+ id: vpnEndpoint
+ Layout.fillWidth: true
+ visible: addVpnDialog.typing
+ placeholderText: "For example vpn.example.com:51820"
+ }
+
+ FieldLabel {
+ visible: addVpnDialog.typing
+ text: "Server's public key"
+ }
+
+ UI.TextField {
+ id: vpnPublicKey
+ Layout.fillWidth: true
+ visible: addVpnDialog.typing
+ }
+
+ FieldLabel {
+ visible: addVpnDialog.typing
+ text: "Your private key"
+ }
+
+ UI.TextField {
+ id: vpnPrivateKey
+ Layout.fillWidth: true
+ visible: addVpnDialog.typing
+ revealable: true
+ }
+
+ FieldLabel {
+ visible: addVpnDialog.typing
+ text: "Your address on the VPN"
+ }
+
+ UI.TextField {
+ id: vpnAddress
+ Layout.fillWidth: true
+ visible: addVpnDialog.typing
+ placeholderText: "For example 10.64.0.2/32"
+ }
+
+ FieldLabel {
+ visible: addVpnDialog.typing
+ text: "DNS server, if your provider gave one"
+ }
+
+ UI.TextField {
+ id: vpnDns
+ Layout.fillWidth: true
+ visible: addVpnDialog.typing
+ onAccepted: vpnAdd.clicked()
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ visible: addVpnDialog.started && text.length > 0
+ text: addVpnDialog.problem
+ size: 12
+ color: UI.Style.danger
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+
+ buttons: [
+ UI.Button {
+ visible: !addVpnDialog.typing
+ text: "Type the details"
+ onClicked: {
+ addVpnDialog.typing = true;
+ vpnName.forceActiveFocus();
+ }
+ },
+ UI.Button {
+ visible: !addVpnDialog.typing
+ text: "Import a file"
+ kind: "primary"
+ onClicked: {
+ addVpnDialog.close();
+ vpnFileDialog.open();
+ }
+ },
+ UI.Button {
+ id: vpnAdd
+ visible: addVpnDialog.typing
+ text: "Add"
+ kind: "primary"
+ enabled: addVpnDialog.problem.length === 0 && page.busy.length === 0
+ onClicked: {
+ if (!enabled) {
+ return;
+ }
+ NetworkSettings.addWireGuard(addVpnDialog.details);
+ addVpnDialog.close();
+ }
+ },
+ UI.Button {
+ text: "Cancel"
+ onClicked: addVpnDialog.close()
+ }
+ ]
+ }
+
+ FileDialog {
+ id: vpnFileDialog
+ title: "Import a VPN"
+ nameFilters: ["WireGuard and OpenVPN files (*.conf *.ovpn)", "All files (*)"]
+ currentFolder: StandardPaths.writableLocation(StandardPaths.DownloadLocation)
+ onAccepted: NetworkSettings.importVpn(selectedFile)
+ }
+
+ UI.Dialog {
+ id: ipDialog
+
+ readonly property bool manual: ipMode.currentValue === "manual"
+ readonly property string problem: manual ? NetworkSettings.checkAddress(ipAddress.text, ipMask.text, ipGateway.text) : ""
+
+ title: "Edit IP address"
+ text: "Most networks give this computer an address automatically. Set one yourself only if the network needs it."
+ onAboutToShow: {
+ ipMode.currentIndex = page.current.manual ? 1 : 0;
+ ipAddress.text = page.current.manualAddress || page.current.address || "";
+ const prefix = page.current.manualPrefix || page.current.prefix || 24;
+ ipMask.text = maskFromPrefix(prefix);
+ ipGateway.text = page.current.manualGateway || page.current.gateway || "";
+ }
+
+ function maskFromPrefix(prefix) {
+ const parts = [];
+ for (let i = 0; i < 4; ++i) {
+ const bits = Math.max(0, Math.min(8, prefix - i * 8));
+ parts.push(256 - Math.pow(2, 8 - bits));
+ }
+ return parts.join(".");
+ }
+
+ RowLayout {
+ Layout.fillWidth: true
+ spacing: 12
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: "Set the address"
+ }
+
+ UI.ComboBox {
+ id: ipMode
+ Accessible.name: "Set the address"
+ model: [{ value: "auto", text: "Automatically" }, { value: "manual", text: "Myself" }]
+ }
+ }
+
+ FieldLabel {
+ visible: ipDialog.manual
+ text: "IP address"
+ }
+
+ UI.TextField {
+ id: ipAddress
+ Layout.fillWidth: true
+ visible: ipDialog.manual
+ placeholderText: "For example 192.168.1.42"
+ }
+
+ FieldLabel {
+ visible: ipDialog.manual
+ text: "Subnet mask"
+ }
+
+ UI.TextField {
+ id: ipMask
+ Layout.fillWidth: true
+ visible: ipDialog.manual
+ placeholderText: "For example 255.255.255.0"
+ }
+
+ FieldLabel {
+ visible: ipDialog.manual
+ text: "Gateway"
+ }
+
+ UI.TextField {
+ id: ipGateway
+ Layout.fillWidth: true
+ visible: ipDialog.manual
+ placeholderText: "For example 192.168.1.1"
+ onAccepted: ipSave.clicked()
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ visible: text.length > 0
+ text: ipDialog.problem
+ size: 12
+ color: UI.Style.danger
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+
+ buttons: [
+ UI.Button {
+ id: ipSave
+ text: "Save"
+ kind: "primary"
+ enabled: ipDialog.problem.length === 0 && page.busy.length === 0
+ onClicked: {
+ if (!enabled) {
+ return;
+ }
+ NetworkSettings.setAddress(!ipDialog.manual, ipAddress.text, ipMask.text, ipGateway.text);
+ ipDialog.close();
+ }
+ },
+ UI.Button {
+ text: "Cancel"
+ onClicked: ipDialog.close()
+ }
+ ]
+ }
+
+ component FieldLabel: UI.Label {
+ Layout.fillWidth: true
+ size: 12
+ color: UI.Style.inkMuted
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/NetworkPage.qml b/packages/wildos-settings/qml/pages/NetworkPage.qml
index f8becd1..6da7609 100644
--- a/packages/wildos-settings/qml/pages/NetworkPage.qml
+++ b/packages/wildos-settings/qml/pages/NetworkPage.qml
@@ -7,7 +7,7 @@ import WildOS.UI as UI
// Network and internet: Wi-Fi on or off, flight mode, nearby networks with
// connecting and password entry, and Ethernet. Everything goes through
// plasma-nm, the same code as the network icon in the tray; the rarer
-// settings (VPN, proxy, IP addresses) open KDE's full editor.
+// settings (VPN, proxy, IP addresses) are on Advanced network settings.
PageScroll {
id: page
@@ -208,7 +208,7 @@ PageScroll {
iconName: "ethernet"
title: "Ethernet"
description: summary.connected && !summary.wifi ? "Connected. Addresses and other details are in the advanced settings." : "Not connected. Plug in a network cable to use it."
- external: Pages.exists("networkadvanced")
+ chevron: true
onClicked: Navigator.open("networkadvanced")
}
@@ -216,7 +216,7 @@ PageScroll {
iconName: "globe"
title: "Advanced network settings"
description: "VPN, proxy, IP addresses and saved networks"
- external: true
+ chevron: true
onClicked: Navigator.open("networkadvanced")
}
}
diff --git a/packages/wildos-settings/qml/pages/OldAppCompatibilityPage.qml b/packages/wildos-settings/qml/pages/OldAppCompatibilityPage.qml
new file mode 100644
index 0000000..93d12bd
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/OldAppCompatibilityPage.qml
@@ -0,0 +1,97 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.Settings
+import WildOS.UI as UI
+
+// Old app compatibility: how much older apps may see of what you type in
+// other apps, the keyboard half of KDE's Legacy X11 App Support. Each choice
+// writes kwinrc and asks KWin to reload, so it applies at once.
+PageScroll {
+ id: page
+
+ readonly property var choices: [
+ { level: 0, title: "Never", description: "Older apps only see what you type into them. Recommended." },
+ { level: 1, title: "Ctrl, Alt, Shift and the Windows key", description: "Lets them notice those keys pressed on their own" },
+ { level: 2, title: "Shortcuts", description: "Also keys pressed while holding Ctrl, Alt or the Windows key, for global shortcuts" },
+ { level: 3, title: "Everything", description: "Every key you press, in any app. Only for an app you fully trust." }
+ ]
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: "Older apps (built for X11) can be allowed to see keys you press while you use other apps, which a few need for a shortcut such as push to talk, but it also lets them see what you type, passwords included."
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ SectionTitle {
+ text: "Let older apps see keys typed in other apps"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ Repeater {
+ model: page.choices
+
+ UI.SettingRow {
+ id: choice
+ required property var modelData
+ readonly property bool selected: OlderApps.keys === modelData.level
+ title: modelData.title
+ description: modelData.description
+ descriptionColor: modelData.level === 3 ? UI.Style.warning : UI.Style.inkMuted
+ interactive: true
+ Accessible.role: Accessible.RadioButton
+ Accessible.checked: selected
+ onClicked: OlderApps.keys = modelData.level
+
+ leading: UI.RadioButton {
+ checked: choice.selected
+ focusPolicy: Qt.NoFocus
+ Accessible.ignored: true
+ onClicked: OlderApps.keys = choice.modelData.level
+ }
+ }
+ }
+ }
+ }
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ iconName: "mouse"
+ title: "Mouse buttons too"
+ description: OlderApps.keys === 0 ? "Choose something other than Never first"
+ : "Lets older apps see mouse clicks in other apps as well"
+ status: OlderApps.mouse ? "On" : "Off"
+ enabled: OlderApps.keys > 0
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: OlderApps.mouse
+ Accessible.name: "Mouse buttons too"
+ onToggled: OlderApps.mouse = checked
+ }
+ }
+
+ UI.SettingRow {
+ iconName: "display"
+ title: "Screen"
+ description: "Older apps only see their own windows and those of other older apps. Seeing the rest of your screen needs your permission each time."
+ }
+ }
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/PenPage.qml b/packages/wildos-settings/qml/pages/PenPage.qml
new file mode 100644
index 0000000..596e251
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/PenPage.qml
@@ -0,0 +1,86 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.Settings
+import WildOS.UI as UI
+
+// Pen and tablet, after Windows 11's Pen and Windows Ink: which hand you
+// write with, and which screen a drawing tablet's surface stands for.
+// KWin applies each change straight away and keeps it for the pen.
+PageScroll {
+ id: page
+
+ readonly property var pens: InputDevices.pens
+
+ ScreenChoices {
+ id: screenChoices
+ automaticText: "The screen the pointer is on"
+ allScreens: true
+ }
+
+ // KWin keeps "all screens" as its own switch beside the screen name, so
+ // the one choice here sets both, as KDE's tablet module does.
+ function setScreen(pen, value) {
+ InputDevices.setDevice(pen.sysName, "mapToWorkspace", value === "*");
+ InputDevices.setDevice(pen.sysName, "outputName", value === "*" ? "" : value);
+ }
+
+ StatusCard {
+ visible: page.pens.length === 0
+ iconName: "pencil"
+ warning: true
+ title: "No pen or tablet connected"
+ description: "Plug in a drawing tablet, or use the pen of a touchscreen PC, and its settings appear here."
+ }
+
+ Repeater {
+ model: page.pens
+
+ ColumnLayout {
+ id: pen
+ required property var modelData
+ Layout.fillWidth: true
+ spacing: 10
+
+ SectionTitle {
+ text: pen.modelData.name
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ visible: pen.modelData.supportsLeftHanded === true
+ iconName: "pencil"
+ title: "Which hand do you write with?"
+ description: "A tablet held for the left hand is turned round"
+
+ UI.ComboBox {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "Which hand do you write with?"
+ model: [{ value: false, text: "Right hand" }, { value: true, text: "Left hand" }]
+ readonly property bool choice: pen.modelData.leftHanded === true
+ currentIndex: model.findIndex(o => o.value === choice)
+ onActivated: index => InputDevices.setDevice(pen.modelData.sysName, "leftHanded", model[index].value)
+ }
+ }
+
+ UI.SettingRow {
+ title: "Screen"
+ description: "Where the pen points when it touches the tablet"
+
+ UI.ComboBox {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "Screen for " + pen.modelData.name
+ model: screenChoices.model
+ currentIndex: screenChoices.indexOf(pen.modelData.mapToWorkspace === true ? "*" : (pen.modelData.outputName || ""))
+ onActivated: index => page.setScreen(pen.modelData, model[index].value)
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/PersonalisationPage.qml b/packages/wildos-settings/qml/pages/PersonalisationPage.qml
index 6946add..301737b 100644
--- a/packages/wildos-settings/qml/pages/PersonalisationPage.qml
+++ b/packages/wildos-settings/qml/pages/PersonalisationPage.qml
@@ -237,14 +237,8 @@ PageScroll {
title: "Text size"
description: "Makes text larger across every app"
- UI.ComboBox {
+ TextSizeBox {
anchors.verticalCenter: parent.verticalCenter
- Accessible.name: "Text size"
- model: [100, 110, 125, 150].concat([100, 110, 125, 150].includes(System.textScale) ? [] : [System.textScale])
- .map(p => ({ value: p, text: p + "%" }))
- readonly property var choice: System.textScale
- currentIndex: model ? model.findIndex(o => o.value === choice) : -1
- onActivated: index => System.setTextScale(model[index].value)
}
}
}
@@ -258,7 +252,7 @@ PageScroll {
width: parent.width
Repeater {
- model: ["background", "lockscreen", "taskbar"]
+ model: ["background", "lockscreen", "taskbar", "fonts"]
UI.SettingRow {
required property string modelData
diff --git a/packages/wildos-settings/qml/pages/PowerAdvancedPage.qml b/packages/wildos-settings/qml/pages/PowerAdvancedPage.qml
new file mode 100644
index 0000000..8992e8b
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/PowerAdvancedPage.qml
@@ -0,0 +1,347 @@
+import QtQuick
+import QtQuick.Layouts
+import org.kde.plasma.private.battery
+import WildOS.Settings
+import WildOS.UI as UI
+
+// More power settings, after Windows' "Lid and power button controls": what
+// closing the lid and pressing the power button do, when the screen dims,
+// and what happens when the battery is nearly flat. These are powerdevil's
+// own settings in powerdevilrc, under the keys its settings module writes,
+// and powerdevil rereads them when told to. Turning the screen off and
+// sleeping are on Power and battery, so they are not repeated here.
+PageScroll {
+ id: page
+
+ Component.onCompleted: PowerOptions.refresh()
+
+ BatteryControlModel {
+ id: battery
+ }
+
+ readonly property bool hasBattery: battery.hasInternalBatteries && battery.hasCumulative
+
+ property int revision: 0
+
+ // powerdevil's PowerButtonAction values (powerdevilenums.h).
+ readonly property int doNothing: 0
+ readonly property int sleep: 1
+ readonly property int hibernate: 2
+ readonly property int shutDown: 8
+ readonly property int askWhatToDo: 16
+ readonly property int lock: 32
+ readonly property int screenOff: 64
+ readonly property int screenToggle: 128
+
+ readonly property var profiles: hasBattery
+ ? [{ id: "Battery", prefix: "On battery power, " }, { id: "AC", prefix: "When plugged in, " }]
+ : [{ id: "AC", prefix: "" }]
+
+ function capitalise(text) {
+ return text.charAt(0).toUpperCase() + text.slice(1);
+ }
+
+ function actionText(value) {
+ switch (value) {
+ case page.doNothing: return "Do nothing";
+ case page.sleep: return "Sleep";
+ case page.hibernate: return "Hibernate";
+ case page.shutDown: return "Shut down";
+ case page.askWhatToDo: return "Ask me what to do";
+ case page.lock: return "Lock";
+ case page.screenOff: return "Turn off the screen";
+ case page.screenToggle: return "Turn the screen off or on";
+ }
+ return "Something else";
+ }
+
+ // The same choices powerdevil's own settings offer for each, without
+ // sleep or hibernate where this computer cannot do them. A value set
+ // elsewhere that is not on the list still shows, so nothing is changed
+ // just by opening the page.
+ function actionChoices(values, current) {
+ const list = values.filter(v => (v !== page.sleep || PowerOptions.canSuspend) && (v !== page.hibernate || PowerOptions.canHibernate));
+ if (!list.includes(current)) {
+ list.push(current);
+ }
+ return list.map(v => ({ value: v, text: page.actionText(v) }));
+ }
+
+ // powerdevil's defaults (powerdevilsettingsdefaults.cpp) for keys nobody
+ // has set yet.
+ function lidAction(profile) {
+ revision;
+ return System.config("powerdevilrc", profile + "/SuspendAndShutdown", "LidAction", PowerOptions.canSuspend ? page.sleep : page.screenOff);
+ }
+
+ function powerButtonAction(profile) {
+ revision;
+ return System.config("powerdevilrc", profile + "/SuspendAndShutdown", "PowerButtonAction", page.askWhatToDo);
+ }
+
+ // The low battery profile is powerdevil's third, used below the low
+ // battery level. Wild OS shows two like Windows, so the battery choice
+ // covers it too and the lid never behaves differently at 9%.
+ function setButtonAction(profile, key, value) {
+ System.setConfig("powerdevilrc", profile + "/SuspendAndShutdown", key, value);
+ if (profile === "Battery") {
+ System.setConfig("powerdevilrc", "LowBattery/SuspendAndShutdown", key, value);
+ }
+ System.reloadPowerManagement();
+ revision++;
+ }
+
+ readonly property bool lidWithScreen: {
+ revision;
+ return !System.config("powerdevilrc", "AC/SuspendAndShutdown", "InhibitLidActionWhenExternalMonitorPresent", true);
+ }
+
+ function setLidWithScreen(on) {
+ for (const profile of ["AC", "Battery", "LowBattery"]) {
+ System.setConfig("powerdevilrc", profile + "/SuspendAndShutdown", "InhibitLidActionWhenExternalMonitorPresent", !on);
+ }
+ System.reloadPowerManagement();
+ revision++;
+ }
+
+ readonly property var dimDefaults: ({ "AC": 300, "Battery": 120 })
+ readonly property var screenOffDefaults: ({ "AC": 600, "Battery": 300 })
+
+ function dimAfter(profile) {
+ revision;
+ if (!System.config("powerdevilrc", profile + "/Display", "DimDisplayWhenIdle", true)) {
+ return 0;
+ }
+ return System.config("powerdevilrc", profile + "/Display", "DimDisplayIdleTimeoutSec", dimDefaults[profile]);
+ }
+
+ function screenOffAfter(profile) {
+ revision;
+ if (!System.config("powerdevilrc", profile + "/Display", "TurnOffDisplayWhenIdle", true)) {
+ return 0;
+ }
+ return System.config("powerdevilrc", profile + "/Display", "TurnOffDisplayIdleTimeoutSec", screenOffDefaults[profile]);
+ }
+
+ function setDimAfter(profile, seconds) {
+ System.setConfig("powerdevilrc", profile + "/Display", "DimDisplayWhenIdle", seconds > 0);
+ if (seconds > 0) {
+ System.setConfig("powerdevilrc", profile + "/Display", "DimDisplayIdleTimeoutSec", seconds);
+ }
+ System.reloadPowerManagement();
+ revision++;
+ }
+
+ function dimTimeouts(current) {
+ const list = [{ value: 30, text: "30 seconds" }].concat([1, 2, 3, 5, 10, 15, 20, 30].map(m => ({ value: m * 60, text: Format.plural(m, "minute", "minutes") })));
+ if (current > 0 && !list.some(o => o.value === current)) {
+ list.push({ value: current, text: current < 60 ? Format.plural(current, "second", "seconds") : Format.plural(Math.round(current / 60), "minute", "minutes") });
+ list.sort((a, b) => a.value - b.value);
+ }
+ return [{ value: 0, text: "Never" }].concat(list);
+ }
+
+ readonly property int criticalAction: {
+ revision;
+ const fallback = PowerOptions.canHibernate ? page.hibernate : PowerOptions.canSuspend ? page.sleep : page.doNothing;
+ return System.config("powerdevilrc", "BatteryManagement", "BatteryCriticalAction", fallback);
+ }
+
+ readonly property int lowLevel: {
+ revision;
+ return System.config("powerdevilrc", "BatteryManagement", "BatteryLowLevel", 10);
+ }
+
+ readonly property int criticalLevel: {
+ revision;
+ return System.config("powerdevilrc", "BatteryManagement", "BatteryCriticalLevel", 5);
+ }
+
+ function setBattery(key, value) {
+ System.setConfig("powerdevilrc", "BatteryManagement", key, value);
+ System.reloadPowerManagement();
+ revision++;
+ }
+
+ // Critical has to stay below low, or the low battery warning never shows.
+ function criticalLevels(current) {
+ const list = [2, 3, 4, 5, 6, 7, 8, 9, 10, 15].filter(n => n < page.lowLevel);
+ if (!list.includes(current)) {
+ list.push(current);
+ list.sort((a, b) => a - b);
+ }
+ return list.map(n => ({ value: n, text: n + "%" }));
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ SectionTitle {
+ text: PowerOptions.lidPresent ? "Lid and power button" : "Power button"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ Repeater {
+ model: page.profiles
+
+ Column {
+ id: block
+ required property var modelData
+ required property int index
+ width: parent.width
+
+ Rectangle {
+ visible: block.index > 0
+ width: parent.width
+ height: 1
+ color: UI.Style.divider
+ }
+
+ UI.SettingRow {
+ id: powerRow
+ readonly property string label: page.capitalise(block.modelData.prefix + "pressing the power button will")
+ iconName: "power"
+ title: label
+
+ UI.ComboBox {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: powerRow.label
+ readonly property var choice: page.powerButtonAction(block.modelData.id)
+ model: page.actionChoices([page.doNothing, page.sleep, page.hibernate, page.shutDown, page.lock, page.askWhatToDo, page.screenOff], choice)
+ currentIndex: model ? model.findIndex(o => o.value === choice) : -1
+ onActivated: index => page.setButtonAction(block.modelData.id, "PowerButtonAction", model[index].value)
+ }
+ }
+
+ UI.SettingRow {
+ id: lidRow
+ readonly property string label: page.capitalise(block.modelData.prefix + "closing the lid will")
+ visible: PowerOptions.lidPresent
+ iconName: "computer"
+ title: label
+
+ UI.ComboBox {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: lidRow.label
+ readonly property var choice: page.lidAction(block.modelData.id)
+ model: page.actionChoices([page.doNothing, page.sleep, page.hibernate, page.shutDown, page.lock, page.screenOff], choice)
+ currentIndex: model ? model.findIndex(o => o.value === choice) : -1
+ onActivated: index => page.setButtonAction(block.modelData.id, "LidAction", model[index].value)
+ }
+ }
+ }
+ }
+
+ UI.SettingRow {
+ visible: PowerOptions.lidPresent
+ iconName: "monitor"
+ title: "Do this even when another screen is connected"
+ description: "When this is off, closing the lid with a monitor plugged in leaves the computer running on the monitor"
+ status: page.lidWithScreen ? "On" : "Off"
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: page.lidWithScreen
+ Accessible.name: "Do this even when another screen is connected"
+ onToggled: page.setLidWithScreen(checked)
+ }
+ }
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ SectionTitle {
+ text: "Screen dimming"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ Repeater {
+ model: page.profiles
+
+ UI.SettingRow {
+ id: dimRow
+ required property var modelData
+ readonly property string label: page.capitalise(modelData.prefix + "dim my screen after")
+ readonly property int dim: page.dimAfter(modelData.id)
+ readonly property int off: page.screenOffAfter(modelData.id)
+ iconName: "sun"
+ title: label
+ description: dim > 0 && off > 0 && dim >= off ? "The screen turns off before then, so it won't dim first" : ""
+ descriptionColor: UI.Style.warning
+
+ UI.ComboBox {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: dimRow.label
+ model: page.dimTimeouts(dimRow.dim)
+ readonly property var choice: dimRow.dim
+ currentIndex: model ? model.findIndex(o => o.value === choice) : -1
+ onActivated: index => page.setDimAfter(dimRow.modelData.id, model[index].value)
+ }
+ }
+ }
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+ visible: page.hasBattery
+
+ SectionTitle {
+ text: "Battery"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ iconName: "battery"
+ title: "Critical battery level"
+ description: "Below this, Wild OS acts before the battery runs out"
+
+ UI.ComboBox {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "Critical battery level"
+ readonly property var choice: page.criticalLevel
+ model: page.criticalLevels(choice)
+ currentIndex: model ? model.findIndex(o => o.value === choice) : -1
+ onActivated: index => page.setBattery("BatteryCriticalLevel", model[index].value)
+ }
+ }
+
+ UI.SettingRow {
+ iconName: "alert"
+ title: "When the battery is critically low"
+
+ UI.ComboBox {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "When the battery is critically low"
+ readonly property var choice: page.criticalAction
+ model: page.actionChoices([page.doNothing, page.sleep, page.hibernate, page.shutDown], choice)
+ currentIndex: model ? model.findIndex(o => o.value === choice) : -1
+ onActivated: index => page.setBattery("BatteryCriticalAction", model[index].value)
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/PrintersAdvancedPage.qml b/packages/wildos-settings/qml/pages/PrintersAdvancedPage.qml
new file mode 100644
index 0000000..5ef15c5
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/PrintersAdvancedPage.qml
@@ -0,0 +1,513 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.Settings
+import WildOS.UI as UI
+
+// More printer settings: what Printers and scanners leaves out. Each
+// printer opens its print queue, with Cancel per document and Pause, and
+// its printing preferences (paper size, two-sided, colour), kept for this
+// account. "Add a printer that needs a driver" covers USB printers and
+// older network printers: choose the printer, then its maker and model from
+// the drivers installed.
+PageScroll {
+ id: page
+
+ property string selected
+ property bool adding: false
+ readonly property var printer: {
+ for (const p of Printers.printers) {
+ if (p.name === selected) {
+ return p;
+ }
+ }
+ return null;
+ }
+ property var prefs: ({})
+
+ readonly property int depth: selected.length > 0 || adding ? 2 : 1
+ readonly property var subTitles: adding ? ["Add a printer that needs a driver"] : printer ? [printer.info] : []
+
+ function back() {
+ if (selected.length > 0 || adding) {
+ selected = "";
+ adding = false;
+ return true;
+ }
+ return false;
+ }
+
+ function statusOf(p) {
+ return (p.isDefault ? "Default, " + p.status.charAt(0).toLowerCase() + p.status.slice(1) : p.status)
+ + (p.jobs > 0 ? ", " + Format.plural(p.jobs, "document", "documents") + " waiting" : "");
+ }
+
+ function startAdding() {
+ nameField.text = "";
+ addressField.text = "";
+ adding = true;
+ Printers.findDevices();
+ Printers.loadDrivers();
+ }
+
+ onSelectedChanged: prefs = selected.length > 0 ? Printers.preferences(selected) : ({})
+
+ Timer {
+ interval: 4000
+ running: Printers.available && page.visible
+ repeat: true
+ onTriggered: Printers.reload()
+ }
+
+ Connections {
+ target: Printers
+ function onDone(title, message) {
+ notice.show(title, message, false);
+ if (title === "Printer added") {
+ page.adding = false;
+ }
+ }
+ function onFailed(title, reason) {
+ notice.show(title, reason, true);
+ }
+ }
+
+ Notice {
+ id: notice
+ }
+
+ StatusCard {
+ visible: !Printers.available
+ iconName: "printer"
+ warning: true
+ title: "Printing isn't running"
+ description: "The service that talks to printers is not running on this computer, so printers can't be added or used."
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ visible: Printers.available && page.depth === 1
+ spacing: Metrics.sectionGap
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ iconName: "printer"
+ iconTile: true
+ minHeight: 68
+ title: "Add a printer that needs a driver"
+ description: "For printers plugged in with USB, and older network printers"
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Add a printer"
+ kind: "primary"
+ enabled: Printers.busy.length === 0
+ onClicked: page.startAdding()
+ }
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ visible: Printers.printers.length > 0
+ spacing: 10
+
+ SectionTitle {
+ text: "Print queues and preferences"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ Repeater {
+ model: Printers.printers
+
+ UI.SettingRow {
+ required property var modelData
+ iconName: "printer"
+ title: modelData.info
+ description: page.statusOf(modelData)
+ descriptionColor: modelData.problem ? UI.Style.warning : UI.Style.inkMuted
+ chevron: true
+ onClicked: page.selected = modelData.name
+ }
+ }
+ }
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ visible: page.printer !== null && !page.adding
+ spacing: Metrics.sectionGap
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ iconName: "printer"
+ iconTile: true
+ minHeight: 68
+ title: page.printer ? page.printer.info : ""
+ description: page.printer ? page.statusOf(page.printer) : ""
+ descriptionColor: page.printer && page.printer.problem ? UI.Style.warning : UI.Style.inkMuted
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: page.printer !== null && !page.printer.isDefault
+ text: "Set as default"
+ onClicked: Printers.setDefault(page.selected)
+ }
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: page.printer && page.printer.paused ? "Resume printing" : "Pause printing"
+ busy: Printers.busy === page.selected
+ enabled: Printers.busy.length === 0
+ onClicked: page.printer.paused ? Printers.resume(page.selected) : Printers.pause(page.selected)
+ }
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ SectionTitle {
+ text: "Print queue"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ Repeater {
+ model: page.printer ? page.printer.queue : []
+
+ UI.SettingRow {
+ id: job
+ required property var modelData
+ iconName: "document"
+ title: modelData.title.length > 0 ? modelData.title : "Document"
+ description: [modelData.state, modelData.user, Format.time(modelData.created)].filter(t => t && t.length > 0).join(", ")
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Cancel"
+ onClicked: Printers.cancelJob(page.selected, job.modelData.id)
+ }
+ }
+ }
+
+ UI.SettingRow {
+ visible: page.printer !== null && page.printer.queue.length === 0
+ iconName: "check"
+ title: "No documents waiting"
+ }
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ visible: page.prefs.media !== undefined || page.prefs.sides !== undefined || page.prefs.color !== undefined
+ spacing: 10
+
+ SectionTitle {
+ text: "Printing preferences"
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: "What apps choose for this printer unless you change it when printing. Kept for your account only."
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ Repeater {
+ model: [
+ { key: "media", option: "media", icon: "document", title: "Paper size" },
+ { key: "sides", option: "sides", icon: "copy", title: "Two-sided printing" },
+ { key: "color", option: "print-color-mode", icon: "palette", title: "Colour" }
+ ].filter(r => page.prefs[r.key] !== undefined)
+
+ UI.SettingRow {
+ id: pref
+ required property var modelData
+ readonly property var setting: page.prefs[modelData.key]
+ iconName: modelData.icon
+ title: modelData.title
+
+ UI.ComboBox {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: pref.modelData.title
+ model: pref.setting ? pref.setting.choices : []
+ currentIndex: pref.setting ? pref.setting.choices.findIndex(c => c.value === pref.setting.value) : -1
+ onActivated: index => {
+ Printers.setPreference(page.selected, pref.modelData.option, model[index].value);
+ page.prefs = Printers.preferences(page.selected);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ ColumnLayout {
+ id: add
+ Layout.fillWidth: true
+ visible: page.adding && Printers.available
+ spacing: Metrics.sectionGap
+
+ // The device list plus a last choice for typing an address.
+ readonly property var connections: Printers.devices.map(d => ({
+ value: d.uri,
+ text: (d.kind === "usb" ? "USB: " : "Network: ") + (d.name.length > 0 ? d.name : d.uri),
+ device: d
+ })).concat([{ value: "", text: "A network printer by its address", device: null }])
+ readonly property var connection: connectionBox.currentIndex >= 0 && connectionBox.currentIndex < connections.length
+ ? connections[connectionBox.currentIndex] : null
+ readonly property bool byAddress: connection !== null && connection.device === null
+ readonly property string uri: byAddress ? Printers.addressUri(addressField.text, protocolBox.currentValue || "socket")
+ : connection ? connection.value : ""
+ property var makeList: []
+ property var modelList: []
+ property string suggestedName
+
+ function suggest() {
+ const d = connection ? connection.device : null;
+ const model = d ? d.model : "";
+ if (model.length > 0) {
+ const make = Printers.makeFor(model);
+ const i = makeList.indexOf(make);
+ if (i >= 0) {
+ makeBox.currentIndex = i;
+ modelList = Printers.models(make);
+ const m = modelList.findIndex(o => o.text.toLowerCase().startsWith(model.toLowerCase()));
+ modelBox.currentIndex = m >= 0 ? m : 0;
+ }
+ }
+ // A name typed in is kept; one filled in from the device follows
+ // the device.
+ const name = d ? (d.name.length > 0 ? d.name : d.model) : addressField.text.trim();
+ if (nameField.text.length === 0 || nameField.text === suggestedName) {
+ nameField.text = name;
+ }
+ suggestedName = name;
+ }
+
+ Connections {
+ target: Printers
+ function onDriversChanged() {
+ add.makeList = Printers.makes();
+ add.modelList = add.makeList.length > 0 ? Printers.models(add.makeList[Math.max(0, makeBox.currentIndex)]) : [];
+ add.suggest();
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ SectionTitle {
+ text: "Printer"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ iconName: "plug"
+ title: "Connected by"
+ description: Printers.findingDevices ? "Looking for printers" : ""
+
+ UI.Spinner {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: Printers.findingDevices
+ }
+
+ UI.ComboBox {
+ id: connectionBox
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "Connected by"
+ enabled: !Printers.findingDevices
+ model: add.connections
+ onActivated: add.suggest()
+ onModelChanged: {
+ currentIndex = 0;
+ add.suggest();
+ }
+ }
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Look again"
+ enabled: !Printers.findingDevices
+ onClicked: Printers.findDevices()
+ }
+ }
+
+ UI.SettingRow {
+ visible: add.byAddress
+ title: "Address"
+ description: "The printer's network name or IP address"
+
+ UI.TextField {
+ id: addressField
+ anchors.verticalCenter: parent.verticalCenter
+ width: 240
+ placeholderText: "For example 192.168.1.20"
+ onTextChanged: if (add.byAddress) add.suggest()
+ }
+
+ UI.ComboBox {
+ id: protocolBox
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "How it prints"
+ model: [
+ { value: "socket", text: "Port 9100 (most printers)" },
+ { value: "lpd", text: "LPD" },
+ { value: "ipp", text: "IPP" }
+ ]
+ }
+ }
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ SectionTitle {
+ text: "Driver"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ iconName: "cog"
+ title: "Maker"
+ description: Printers.loadingDrivers ? "Reading the installed drivers, which can take a moment" : ""
+
+ UI.Spinner {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: Printers.loadingDrivers
+ }
+
+ UI.ComboBox {
+ id: makeBox
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "Maker"
+ enabled: add.makeList.length > 0
+ model: add.makeList.map(m => ({ value: m, text: m }))
+ onActivated: index => {
+ add.modelList = Printers.models(add.makeList[index]);
+ modelBox.currentIndex = 0;
+ }
+ }
+ }
+
+ UI.SettingRow {
+ iconName: "printer"
+ title: "Model"
+ description: "Pick the exact model, or the nearest one from the same series"
+
+ UI.ComboBox {
+ id: modelBox
+ anchors.verticalCenter: parent.verticalCenter
+ width: Math.min(implicitWidth, 420)
+ Accessible.name: "Model"
+ enabled: add.modelList.length > 0
+ model: add.modelList
+ }
+ }
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ SectionTitle {
+ text: "Name"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ iconName: "rename"
+ title: "Printer name"
+ description: "How apps show it when you print"
+
+ UI.TextField {
+ id: nameField
+ anchors.verticalCenter: parent.verticalCenter
+ width: 280
+ placeholderText: "For example Office printer"
+ }
+ }
+ }
+ }
+ }
+
+ RowLayout {
+ Layout.fillWidth: true
+ spacing: 8
+
+ Item {
+ Layout.fillWidth: true
+ }
+
+ UI.Button {
+ text: "Cancel"
+ onClicked: page.adding = false
+ }
+
+ UI.Button {
+ text: "Add printer"
+ kind: "primary"
+ busy: Printers.busy === "add"
+ enabled: Printers.busy.length === 0 && add.uri.length > 0 && modelBox.currentIndex >= 0 && add.modelList.length > 0
+ && nameField.text.trim().length > 0
+ onClicked: Printers.addWithDriver(add.uri, add.modelList[modelBox.currentIndex].value, nameField.text)
+ }
+ }
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/PrivacyPage.qml b/packages/wildos-settings/qml/pages/PrivacyPage.qml
index 52e2101..b80fe39 100644
--- a/packages/wildos-settings/qml/pages/PrivacyPage.qml
+++ b/packages/wildos-settings/qml/pages/PrivacyPage.qml
@@ -5,7 +5,8 @@ import WildOS.UI as UI
// Privacy and security, laid out as Settings.dc.html: the protection status
// from security-status, a tile per protection, the protection level, what
-// apps can reach, then USB protection and usage data.
+// apps can reach, searching files and activity history, then USB protection
+// and usage data.
PageScroll {
id: page
@@ -231,6 +232,40 @@ PageScroll {
}
}
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ SectionTitle {
+ text: "Search and history"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ iconName: "search"
+ title: "Searching files"
+ description: !FileSearch.available ? "File indexing isn't installed"
+ : FileSearch.enabled ? "Your files are indexed so search finds them at once" : "Indexing is off"
+ chevron: true
+ onClicked: Navigator.open("searching")
+ }
+
+ UI.SettingRow {
+ iconName: "clock"
+ title: "Activity history"
+ description: ActivityHistory.remember ? "Recent files are remembered on this computer" : "Recent files are not remembered"
+ chevron: true
+ onClicked: Navigator.open("activityhistory")
+ }
+ }
+ }
+ }
+
UI.Card {
Layout.fillWidth: true
diff --git a/packages/wildos-settings/qml/pages/SearchingFilesPage.qml b/packages/wildos-settings/qml/pages/SearchingFilesPage.qml
new file mode 100644
index 0000000..b8828ea
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/SearchingFilesPage.qml
@@ -0,0 +1,236 @@
+import QtQuick
+import QtCore
+import QtQuick.Dialogs
+import QtQuick.Layouts
+import WildOS.Settings
+import WildOS.UI as UI
+
+// Searching files, after Windows 11's "Searching Windows": whether files
+// are indexed so Start and Files find them at once, whether what is inside
+// them is read too, which folders are searched and which are left out.
+// Everything stays on this computer.
+PageScroll {
+ id: page
+
+ property string error
+
+ Connections {
+ target: FileSearch
+ function onFailed(reason) {
+ page.error = reason.length > 0 ? reason : "The index was not rebuilt.";
+ }
+ }
+
+ Component.onCompleted: FileSearch.reload()
+
+ StatusCard {
+ visible: !FileSearch.available
+ iconName: "search"
+ warning: true
+ title: "File indexing isn't available"
+ description: "The indexer is not installed on this computer. Files can still search a folder as you type, it just takes longer."
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ visible: FileSearch.available
+ text: "Indexing keeps a list of your files so Start and Files can find them straight away. The index never leaves this computer."
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+ visible: FileSearch.available
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ iconName: "search"
+ title: "Index my files"
+ description: "Find files by name and content as soon as you type"
+ status: FileSearch.enabled ? "On" : "Off"
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: FileSearch.enabled
+ Accessible.name: "Index my files"
+ onToggled: FileSearch.enabled = checked
+ }
+ }
+
+ UI.SettingRow {
+ iconName: "document-lines"
+ title: "What to index"
+ description: "Reading inside files finds words in documents too, and uses more disk space"
+ enabled: FileSearch.enabled
+
+ UI.ComboBox {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "What to index"
+ model: [{ value: true, text: "Names and contents" }, { value: false, text: "Names only" }]
+ currentIndex: FileSearch.contents ? 0 : 1
+ onActivated: index => FileSearch.contents = model[index].value
+ }
+ }
+
+ UI.SettingRow {
+ iconName: "hidden"
+ title: "Include hidden files and folders"
+ description: "Hidden files are mostly settings kept by apps"
+ status: FileSearch.hidden ? "On" : "Off"
+ enabled: FileSearch.enabled
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: FileSearch.hidden
+ Accessible.name: "Include hidden files and folders"
+ onToggled: FileSearch.hidden = checked
+ }
+ }
+
+ UI.SettingRow {
+ iconName: "refresh"
+ title: "Rebuild the index"
+ description: page.error.length > 0 ? page.error
+ : FileSearch.indexSize.length > 0 ? "The index takes up " + FileSearch.indexSize + ". Rebuild it if search misses files you know are there."
+ : "Rebuild it if search misses files you know are there"
+ descriptionColor: page.error.length > 0 ? UI.Style.danger : UI.Style.inkMuted
+ enabled: FileSearch.enabled
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: FileSearch.rebuilding ? "Rebuilding" : "Rebuild"
+ busy: FileSearch.rebuilding
+ enabled: !FileSearch.rebuilding
+ onClicked: {
+ page.error = "";
+ FileSearch.rebuild();
+ }
+ }
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ visible: FileSearch.available
+ spacing: 10
+
+ SectionTitle {
+ text: "Folders that are indexed"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ Repeater {
+ model: FileSearch.folders
+
+ UI.SettingRow {
+ id: folderRow
+ required property string modelData
+ iconName: "folder"
+ title: FileSearch.display(modelData)
+ enabled: FileSearch.enabled
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Remove"
+ onClicked: FileSearch.removeFolder(folderRow.modelData)
+ }
+ }
+ }
+
+ UI.SettingRow {
+ iconName: "plus"
+ title: "Index another folder"
+ description: FileSearch.folders.length === 0 ? "No folders are indexed" : ""
+ enabled: FileSearch.enabled
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Add a folder"
+ onClicked: {
+ folderDialog.excluding = false;
+ folderDialog.open();
+ }
+ }
+ }
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ visible: FileSearch.available
+ spacing: 10
+
+ SectionTitle {
+ text: "Excluded folders"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ Repeater {
+ model: FileSearch.excluded
+
+ UI.SettingRow {
+ id: excludedRow
+ required property string modelData
+ iconName: "folder"
+ title: FileSearch.display(modelData)
+ enabled: FileSearch.enabled
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Remove"
+ onClicked: FileSearch.include(excludedRow.modelData)
+ }
+ }
+ }
+
+ UI.SettingRow {
+ iconName: "plus"
+ title: "Add an excluded folder"
+ description: "Search never looks inside it"
+ enabled: FileSearch.enabled
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Add a folder"
+ onClicked: {
+ folderDialog.excluding = true;
+ folderDialog.open();
+ }
+ }
+ }
+ }
+ }
+ }
+
+ FolderDialog {
+ id: folderDialog
+
+ property bool excluding: false
+
+ title: excluding ? "Choose a folder to exclude" : "Choose a folder to index"
+ currentFolder: StandardPaths.writableLocation(StandardPaths.HomeLocation)
+ onAccepted: {
+ if (excluding) {
+ FileSearch.exclude(selectedFolder.toString());
+ } else {
+ FileSearch.addFolder(selectedFolder.toString());
+ }
+ }
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/SignInPage.qml b/packages/wildos-settings/qml/pages/SignInPage.qml
index ac20484..e3321eb 100644
--- a/packages/wildos-settings/qml/pages/SignInPage.qml
+++ b/packages/wildos-settings/qml/pages/SignInPage.qml
@@ -5,13 +5,28 @@ import WildOS.UI as UI
// Sign-in options, after Windows 11: changing the password (current one
// first, then the new one twice and an optional hint), signing in
-// automatically when the computer starts, and the way to the screen lock.
+// automatically when the computer starts, restarting apps after signing
+// in, and the way to the screen lock.
PageScroll {
id: page
readonly property bool autoOn: Users.autoLogin.length > 0 && Users.autoLogin === Users.me.userName
readonly property bool autoOther: Users.autoLogin.length > 0 && Users.autoLogin !== Users.me.userName
+ // ksmserver's loginMode, as KDE's session settings write it. It saves
+ // the open apps at sign-out only in restorePreviousLogout; a session
+ // someone saved by hand (restoreSavedSession) also counts as on.
+ property int sessionRevision: 0
+ readonly property bool restoreApps: {
+ sessionRevision;
+ return System.config("ksmserverrc", "General", "loginMode", "restorePreviousLogout") !== "emptySession";
+ }
+
+ function setRestoreApps(on) {
+ System.setConfig("ksmserverrc", "General", "loginMode", on ? "restorePreviousLogout" : "emptySession");
+ sessionRevision++;
+ }
+
Connections {
target: Users
function onDone(what, message) {
@@ -99,6 +114,21 @@ PageScroll {
}
}
+ UI.SettingRow {
+ iconName: "restart"
+ minHeight: 72
+ title: "Restart my apps when I sign back in"
+ description: "Apps that were open when you signed out or restarted open again, where the app supports it"
+ status: page.restoreApps ? "On" : "Off"
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: page.restoreApps
+ Accessible.name: "Restart my apps when I sign back in"
+ onToggled: page.setRestoreApps(checked)
+ }
+ }
+
UI.SettingRow {
iconName: "clock"
title: "Screen lock"
diff --git a/packages/wildos-settings/qml/pages/SlowBounceKeysPage.qml b/packages/wildos-settings/qml/pages/SlowBounceKeysPage.qml
new file mode 100644
index 0000000..6643bff
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/SlowBounceKeysPage.qml
@@ -0,0 +1,134 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.Settings
+import WildOS.UI as UI
+
+// Accessibility > Slow and bounce keys: kaccessrc [Keyboard] SlowKeys and
+// BounceKeys with their delays, as kcm_access keeps them. KWin applies
+// bounce keys itself; slow keys come from the Wild OS KWin plugin
+// (wildos-shell), as KWin 6.3 has none of its own.
+PageScroll {
+ id: page
+
+ function seconds(ms) {
+ const s = Math.round(ms / 100) / 10;
+ return s === 1 ? "1 second" : s + " seconds";
+ }
+
+ Component.onCompleted: Accessibility.refresh()
+
+ component DelaySlider: UI.Slider {
+ id: slider
+
+ property int delay
+ signal settled(int ms)
+
+ anchors.verticalCenter: parent ? parent.verticalCenter : undefined
+ implicitWidth: 180
+ from: 100
+ to: 2000
+ stepSize: 100
+ value: delay
+ // Written once the slider settles rather than at every step.
+ onMoved: settle.restart()
+
+ Timer {
+ id: settle
+ interval: 300
+ onTriggered: {
+ if (slider.pressed) {
+ restart();
+ return;
+ }
+ slider.settled(Math.round(slider.value));
+ slider.value = Qt.binding(() => slider.delay);
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ SectionTitle {
+ text: "Slow keys"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ title: "Slow keys"
+ description: "Only count a key that's held down for a moment, so brushing one does nothing"
+ status: Accessibility.slowKeys ? "On" : "Off"
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: Accessibility.slowKeys
+ Accessible.name: "Slow keys"
+ onToggled: Accessibility.setSlowKeys(checked)
+ }
+ }
+
+ UI.SettingRow {
+ title: "How long to hold a key"
+ description: page.seconds(slowDelay.value)
+ enabled: Accessibility.slowKeys
+
+ DelaySlider {
+ id: slowDelay
+ delay: Accessibility.slowKeysDelay
+ accessibleName: "How long to hold a key"
+ onSettled: ms => Accessibility.setSlowKeysDelay(ms)
+ }
+ }
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ SectionTitle {
+ text: "Bounce keys"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ title: "Bounce keys"
+ description: "Ignore a key pressed again straight away, so a shaky press types one letter"
+ status: Accessibility.bounceKeys ? "On" : "Off"
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: Accessibility.bounceKeys
+ Accessible.name: "Bounce keys"
+ onToggled: Accessibility.setBounceKeys(checked)
+ }
+ }
+
+ UI.SettingRow {
+ title: "Ignore repeats within"
+ description: page.seconds(bounceDelay.value)
+ enabled: Accessibility.bounceKeys
+
+ DelaySlider {
+ id: bounceDelay
+ delay: Accessibility.bounceKeysDelay
+ accessibleName: "Ignore repeats within"
+ onSettled: ms => Accessibility.setBounceKeysDelay(ms)
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/SoundPage.qml b/packages/wildos-settings/qml/pages/SoundPage.qml
index 7a207d3..117ad84 100644
--- a/packages/wildos-settings/qml/pages/SoundPage.qml
+++ b/packages/wildos-settings/qml/pages/SoundPage.qml
@@ -1,31 +1,174 @@
import QtQuick
import QtQuick.Layouts
+import QtQuick.Templates as T
+import org.kde.bluezqt as BluezQt
import org.kde.plasma.private.volume
import WildOS.Settings
import WildOS.UI as UI
-// Sound, after Windows 11: where sound plays and how loud, then the
-// microphone. Devices and volumes come from plasma-pa, the same service the
-// taskbar's volume uses, so both always agree.
+// Sound, after Windows 11 (SettingsSound.dc): where sound plays and how
+// loud, the microphone with a live level, then every app playing sound with
+// its own volume and output. Everything goes through plasma-pa, the same
+// service the taskbar's volume uses, so both always agree.
+//
+// The page is built again on every visit and mixer rows come and go with
+// the apps, so all of it is bindings to plasma-pa's objects: nothing is set
+// up once in a handler and then lost when an item is recreated.
PageScroll {
id: page
- function nodeName(device) {
- return device ? (device.description || device.name || "Unknown device") : "";
- }
-
function percent(volume) {
return Math.round(volume / PulseAudio.NormalVolume * 100);
}
- function options(list) {
- return list.map(d => ({ value: d.index, text: page.nodeName(d) }));
+ function toVolume(value) {
+ return Math.round(value / 100 * PulseAudio.NormalVolume);
+ }
+
+ function props(object) {
+ return object && object.properties ? object.properties : {};
+ }
+
+ function activePort(device) {
+ if (!device || !device.ports) {
+ return null;
+ }
+ const i = device.activePortIndex;
+ return i >= 0 && i < device.ports.length ? device.ports[i] : null;
+ }
+
+ function isBluetooth(device) {
+ const p = props(device);
+ return p["device.bus"] === "bluetooth" || p["device.api"] === "bluez5";
+ }
+
+ // The battery of a Bluetooth output, from BlueZ's Battery1 through
+ // BluezQt; -1 when the device does not report one. Reading the device
+ // list and its battery here keeps the card's text bound to both.
+ function batteryOf(device) {
+ const p = props(device);
+ const address = String(p["api.bluez5.address"] || p["device.string"] || "").toUpperCase();
+ if (address.length === 0) {
+ return -1;
+ }
+ const devices = BluezQt.Manager.devices;
+ for (let i = 0; i < devices.length; ++i) {
+ const d = devices[i];
+ if (d && d.address.toUpperCase() === address) {
+ return d.battery ? d.battery.percentage : -1;
+ }
+ }
+ return -1;
+ }
+
+ // What a Bluetooth or USB device is, from the form factor it reports.
+ function kindOf(device) {
+ switch (device.formFactor) {
+ case "headphone":
+ return "Headphones";
+ case "headset":
+ case "hands-free":
+ return "Headset";
+ case "speaker":
+ case "portable":
+ return "Speaker";
+ case "car":
+ return "Car";
+ default:
+ return "";
+ }
+ }
+
+ // A card's words as the design has them: what it is on top ("Speakers",
+ // "Headphones", "External display"), how it is connected underneath.
+ function outputInfo(sink) {
+ const p = props(sink);
+ const port = activePort(sink);
+ const portName = port ? port.name : "";
+ const description = sink.description || sink.name || "Unknown device";
+ if (isBluetooth(sink)) {
+ const battery = batteryOf(sink);
+ const kind = kindOf(sink);
+ return {
+ title: kind || "Headphones",
+ caption: battery >= 0 ? "Bluetooth, " + battery + "% battery" : "Bluetooth",
+ icon: kind === "Speaker" || kind === "Car" ? "sound" : "headphones"
+ };
+ }
+ if (/hdmi|displayport/i.test(portName) || (port && port.type === Port.HDMI) || /hdmi|displayport/i.test(description)) {
+ return {
+ title: "External display",
+ caption: /displayport/i.test(portName + " " + description) && !/hdmi/i.test(portName) ? "DisplayPort" : "HDMI",
+ icon: "display"
+ };
+ }
+ if (p["device.bus"] === "usb") {
+ const kind = kindOf(sink);
+ return {
+ title: kind || description,
+ caption: "USB",
+ icon: kind === "Headphones" || kind === "Headset" ? "headphones" : "sound"
+ };
+ }
+ if (/headphone/i.test(portName) || (port && port.type === Port.Headphones)) {
+ return { title: "Headphones", caption: "Headphone jack", icon: "headphones" };
+ }
+ if (/lineout/i.test(portName) || (port && port.type === Port.Line)) {
+ return { title: "Line out", caption: "Built-in", icon: "sound" };
+ }
+ if (/speaker/i.test(portName) || sink.formFactor === "internal" || (port && port.type === Port.Speaker)) {
+ return { title: "Speakers", caption: "Built-in", icon: "sound" };
+ }
+ return { title: description, caption: "Sound output", icon: "sound" };
+ }
+
+ // The microphone's name for the drop-down ("Headphones") and for the
+ // sentence above the level ("Headphones microphone").
+ function inputInfo(source) {
+ const p = props(source);
+ const port = activePort(source);
+ const portName = port ? port.name : "";
+ const description = source.description || source.name || "Unknown device";
+ if (isBluetooth(source)) {
+ const kind = kindOf(source);
+ const title = kind === "Speaker" || kind === "Car" || kind === "" ? "Headphones" : kind;
+ return { title: title, phrase: title + " microphone" };
+ }
+ if (p["device.bus"] === "usb") {
+ return { title: description, phrase: description };
+ }
+ if (/headset/i.test(portName)) {
+ return { title: "Headset", phrase: "Headset microphone" };
+ }
+ if (/internal|builtin/i.test(portName) || source.formFactor === "internal") {
+ return { title: "Built-in", phrase: "Built-in microphone" };
+ }
+ if (/mic/i.test(portName)) {
+ return { title: "Microphone jack", phrase: "Plugged-in microphone" };
+ }
+ return { title: description, phrase: description };
+ }
+
+ // Short names, with a device's full description where two would read
+ // the same (two pairs of Bluetooth headphones).
+ function labels(list, info) {
+ const titles = list.map(d => info(d).title);
+ return list.map((d, i) => titles.indexOf(titles[i]) !== titles.lastIndexOf(titles[i]) ? (d.description || titles[i]) : titles[i]);
+ }
+
+ function options(list, info) {
+ const names = labels(list, info);
+ return list.map((d, i) => ({ value: d.index, text: names[i] }));
}
function byIndex(list, index) {
return list.find(d => d.index === index) || null;
}
+ function byName(list, name) {
+ return list.find(d => d.name === name) || null;
+ }
+
// Physical devices only, as the volume flyout lists them.
PulseObjectFilterModel {
id: sinks
@@ -41,43 +184,111 @@ PageScroll {
sourceModel: SourceModel {}
}
+ // Apps' playback streams, without the ones PipeWire makes for itself,
+ // as the volume flyout lists them.
+ PulseObjectFilterModel {
+ id: streams
+ filters: [ { role: "VirtualStream", value: false } ]
+ sourceModel: SinkInputModel {}
+ }
+
+ // The saved volume and output for notification and alert sounds, which
+ // the KDE sound module shows as Notification Sounds. plasma-pa makes this
+ // entry itself when the sound server has none yet.
+ PulseObjectFilterModel {
+ id: restores
+ filters: [ { role: "Name", value: "sink-input-by-media-role:event" } ]
+ sourceModel: StreamRestoreModel {}
+ }
+
property var outputs: []
property var inputs: []
+ property var playing: []
+ property var eventSounds: null
- Instantiator {
- model: sinks
+ readonly property var outputOptions: options(outputs, outputInfo)
+
+ component Collector: Instantiator {
delegate: QtObject {
required property var model
- readonly property var device: model.PulseObject
+ readonly property var object: model.PulseObject
+ }
+ function collect() {
+ const list = [];
+ for (let i = 0; i < count; ++i) {
+ const o = objectAt(i);
+ if (o && o.object) {
+ list.push(o.object);
+ }
+ }
+ return list;
}
- onObjectAdded: page.outputs = page.collect(this)
- onObjectRemoved: page.outputs = page.collect(this)
}
- Instantiator {
+ Collector {
+ model: sinks
+ onObjectAdded: page.outputs = collect()
+ onObjectRemoved: page.outputs = collect()
+ }
+
+ Collector {
model: sources
- delegate: QtObject {
- required property var model
- readonly property var device: model.PulseObject
- }
- onObjectAdded: page.inputs = page.collect(this)
- onObjectRemoved: page.inputs = page.collect(this)
+ onObjectAdded: page.inputs = collect()
+ onObjectRemoved: page.inputs = collect()
+ }
+
+ Collector {
+ model: streams
+ onObjectAdded: page.playing = collect()
+ onObjectRemoved: page.playing = collect()
+ }
+
+ Collector {
+ model: restores
+ onObjectAdded: page.eventSounds = collect()[0] || null
+ onObjectRemoved: page.eventSounds = collect()[0] || null
+ }
+
+ readonly property var output: PreferredDevice.sink && PreferredDevice.sink.name !== "auto_null" ? PreferredDevice.sink : null
+ readonly property var input: PreferredDevice.source
+
+ // Windows mode's apps all play through its one FreeRDP connection,
+ // whose PulseAudio backend names itself "freerdp" (rdpsnd_pulse.c) and
+ // runs as xfreerdp3 (wildos-winmode rdp.py), so they are one stream and
+ // one row.
+ function isWindows(stream) {
+ const p = props(stream);
+ const binary = String(p["application.process.binary"] || "");
+ return p["application.name"] === "freerdp" || /freerdp/i.test(binary)
+ || (stream.client !== null && stream.client !== undefined && stream.client.name === "freerdp");
}
- function collect(instantiator) {
+ function appName(stream) {
+ const p = props(stream);
+ return String(p["application.name"] || (stream.client ? stream.client.name : "") || stream.name || "App");
+ }
+
+ // One row per app, as Windows has it: a browser with three tabs playing
+ // is one Brave, and all of Windows mode is one Windows apps.
+ readonly property var groups: {
const list = [];
- for (let i = 0; i < instantiator.count; ++i) {
- const o = instantiator.objectAt(i);
- if (o && o.device) {
- list.push(o.device);
+ const found = {};
+ for (const s of playing) {
+ if (!s) {
+ continue;
}
+ const windows = isWindows(s);
+ const p = props(s);
+ const key = windows ? "windows" : "app:" + String(p["application.process.binary"] || appName(s));
+ if (found[key] === undefined) {
+ found[key] = list.length;
+ list.push({ key: key, windows: windows, name: windows ? "Windows apps" : appName(s), streams: [] });
+ }
+ list[found[key]].streams.push(s);
}
return list;
}
- readonly property var output: PreferredDevice.sink && PreferredDevice.sink.name !== "auto_null" ? PreferredDevice.sink : null
- readonly property var input: PreferredDevice.source
-
ColumnLayout {
Layout.fillWidth: true
spacing: 10
@@ -86,6 +297,26 @@ PageScroll {
text: "Output"
}
+ GridLayout {
+ Layout.fillWidth: true
+ visible: page.outputs.length > 0
+ columns: 3
+ columnSpacing: 10
+ rowSpacing: 10
+
+ Repeater {
+ model: page.outputs
+
+ OutputCard {
+ required property var modelData
+ Layout.fillWidth: true
+ Layout.preferredWidth: 100
+ Layout.minimumWidth: 0
+ device: modelData
+ }
+ }
+ }
+
UI.Card {
Layout.fillWidth: true
@@ -93,31 +324,43 @@ PageScroll {
width: parent.width
UI.SettingRow {
+ visible: page.output === null
iconName: "sound"
- title: "Choose where to play sound"
- description: page.output ? "Apps may have their own settings" : "No speakers or headphones found"
+ title: "No speakers or headphones found"
+ description: "Plug some in or connect them over Bluetooth"
+ }
- UI.ComboBox {
+ UI.SettingRow {
+ id: volumeRow
+ visible: page.output !== null
+ title: "Volume"
+ minHeight: 50
+
+ readonly property int level: page.output ? Math.min(100, page.percent(page.output.volume)) : 0
+
+ UI.Slider {
anchors.verticalCenter: parent.verticalCenter
- visible: page.outputs.length > 0
- Accessible.name: "Output device"
- model: page.options(page.outputs)
- readonly property var choice: page.output ? page.output.index : -1
- currentIndex: model ? model.findIndex(o => o.value === choice) : -1
- onActivated: index => {
- const value = model[index].value;
- const device = page.byIndex(page.outputs, value);
- if (device) {
- device.default = true;
+ width: 260
+ flat: true
+ accessibleName: "Output volume"
+ dimmed: page.output !== null && page.output.muted
+ value: volumeRow.level
+ onMoved: {
+ const device = page.output;
+ if (!device) {
+ return;
+ }
+ device.volume = page.toVolume(value);
+ if (device.muted && value > 0) {
+ device.muted = false;
}
}
}
- }
- VolumeRow {
- visible: page.output !== null
- title: "Volume"
- device: page.output
+ Percent {
+ anchors.verticalCenter: parent.verticalCenter
+ text: volumeRow.level + "%"
+ }
}
}
}
@@ -138,88 +381,459 @@ PageScroll {
width: parent.width
UI.SettingRow {
- iconName: "mic"
- title: "Choose a device for speaking or recording"
- description: page.input ? "Apps may have their own settings" : "No microphone found"
+ title: "Microphone"
+ description: page.input ? page.inputInfo(page.input).phrase + ". Speak to test it." : "No microphone found"
+ minHeight: 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.
+ VolumeMonitor {
+ id: micLevel
+ target: page.input
+ }
+
+ Row {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: page.input !== null
+ spacing: 3
+ Accessible.role: Accessible.Indicator
+ Accessible.name: "Microphone level"
+
+ // Peaks are linear, so ordinary speech would barely
+ // light the first bars; the square root spreads it
+ // across the meter as Windows' does.
+ readonly property int lit: page.input && !page.input.muted
+ ? Math.round(Math.sqrt(Math.max(0, Math.min(1, micLevel.volume))) * 14) : 0
+
+ Repeater {
+ model: 14
+
+ Rectangle {
+ required property int index
+ width: 5
+ height: 14
+ radius: 2
+ color: index < parent.lit ? UI.Style.accent : UI.Style.tone(0.14)
+ }
+ }
+ }
UI.ComboBox {
anchors.verticalCenter: parent.verticalCenter
visible: page.inputs.length > 0
- Accessible.name: "Input device"
- model: page.options(page.inputs)
+ Accessible.name: "Microphone"
+ model: page.options(page.inputs, page.inputInfo)
readonly property var choice: page.input ? page.input.index : -1
currentIndex: model ? model.findIndex(o => o.value === choice) : -1
onActivated: index => {
- const value = model[index].value;
- const device = page.byIndex(page.inputs, value);
+ const device = page.byIndex(page.inputs, model[index].value);
if (device) {
device.default = true;
}
}
}
}
+ }
+ }
+ }
- VolumeRow {
- visible: page.input !== null
- title: "Volume"
- device: page.input
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ SectionTitle {
+ text: "Volume mixer"
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: "Set the volume and output for each app on its own. Apps appear here while they're playing sound."
+ size: 12
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+ visible: page.groups.length > 0 || page.eventSounds !== null
+
+ Column {
+ width: parent.width
+
+ Repeater {
+ model: page.groups
+
+ AppRow {
+ required property var modelData
+ group: modelData
+ }
+ }
+
+ SystemSoundsRow {
+ visible: page.eventSounds !== null
+ entry: page.eventSounds
}
}
}
}
- UI.Card {
- Layout.fillWidth: true
+ // The percentage beside a slider keeps its place as the digits change.
+ component Percent: UI.Label {
+ width: 34
+ Layout.preferredWidth: 34
+ size: 12
+ color: UI.Style.inkMuted
+ font.features: ({ "tnum": 1 })
+ }
+
+ // One output device as a card (SettingsSound.dc): the chosen one has
+ // the accent edge. Choosing one makes it the default, so apps that have
+ // no output of their own move to it, as in the volume flyout.
+ component OutputCard: T.AbstractButton {
+ id: card
- Column {
- width: parent.width
+ property var device: null
+ readonly property var info: device ? page.outputInfo(device) : ({ title: "", caption: "", icon: "sound" })
+ readonly property bool chosen: device !== null && page.output !== null && page.output.index === device.index
+
+ implicitHeight: 62
+ padding: 0
+ leftPadding: 14
+ rightPadding: 14
+ hoverEnabled: true
+ focusPolicy: Qt.StrongFocus
+ Accessible.role: Accessible.RadioButton
+ Accessible.name: info.title
+ Accessible.description: info.caption
+ Accessible.checked: chosen
+
+ onClicked: if (device && !chosen) device.default = true
+
+ background: Rectangle {
+ radius: UI.Style.radiusMd
+ color: card.chosen ? UI.Style.accentSoft : card.down ? UI.Style.surfacePressed : card.hovered ? UI.Style.surfaceHover : UI.Style.surfaceRest
+ border.width: card.chosen ? 2 : 1
+ border.color: card.chosen ? UI.Style.accent : UI.Style.borderField
+ Behavior on color {
+ ColorAnimation { duration: UI.Style.hoverDuration }
+ }
- UI.SettingRow {
- visible: Pages.exists("soundadvanced")
- title: Pages.page("soundadvanced").title
- description: Pages.page("soundadvanced").description
- chevron: true
- onClicked: Navigator.open("soundadvanced")
+ UI.FocusRing {
+ visible: card.visualFocus
+ targetRadius: UI.Style.radiusMd
+ }
+ }
+
+ contentItem: RowLayout {
+ spacing: 12
+
+ Rectangle {
+ Layout.preferredWidth: 34
+ Layout.preferredHeight: 34
+ radius: 9
+ color: UI.Style.surfaceTile
+
+ UI.Icon {
+ anchors.centerIn: parent
+ name: card.info.icon
+ size: 18
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ Layout.minimumWidth: 0
+ spacing: 2
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: card.info.title
+ size: 13
+ font.weight: Font.DemiBold
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: card.info.caption
+ size: 11
+ color: UI.Style.inkMuted
+ }
}
}
}
- component VolumeRow: UI.SettingRow {
+ // The parts every mixer row shares: a 30px tile, the name over a
+ // second line in a 200px column, mute, a 200px slider, the percentage
+ // and the output drop-down on the right (SettingsSound.dc).
+ component MixerRow: Item {
id: row
- property var device: null
- readonly property bool muted: device !== null && device.muted
+ property string title
+ property string subtitle
+ property bool windowsMode: false
+ property bool muted: false
+ property int level: 0
+ property int deviceIndex: -1
+ default property alias tile: tileBox.data
+
+ signal volumeMoved(int value)
+ signal muteClicked()
+ signal deviceChosen(int index)
+
+ width: parent ? parent.width : 0
+ implicitHeight: Math.max(56, layout.implicitHeight + 16)
+
+ Rectangle {
+ visible: row.y > 0
+ anchors.left: parent.left
+ anchors.right: parent.right
+ height: 1
+ color: UI.Style.divider
+ }
- status: device ? (muted ? "Muted" : page.percent(device.volume) + "%") : ""
+ RowLayout {
+ id: layout
+ anchors.fill: parent
+ anchors.leftMargin: 18
+ anchors.rightMargin: 18
+ spacing: 14
+
+ Item {
+ id: tileBox
+ Layout.preferredWidth: 30
+ Layout.preferredHeight: 30
+ }
+
+ ColumnLayout {
+ Layout.preferredWidth: 200
+ Layout.maximumWidth: 200
+ spacing: 2
+
+ RowLayout {
+ Layout.fillWidth: true
+ spacing: 8
+
+ UI.Label {
+ Layout.fillWidth: !row.windowsMode
+ Layout.maximumWidth: 200
+ text: row.title
+ size: 13
+ }
+
+ UI.Chip {
+ visible: row.windowsMode
+ text: "Windows mode"
+ }
+
+ Item {
+ visible: row.windowsMode
+ Layout.fillWidth: true
+ }
+ }
- Row {
- anchors.verticalCenter: parent.verticalCenter
- spacing: 8
+ UI.Label {
+ Layout.fillWidth: true
+ visible: text.length > 0
+ text: row.subtitle
+ size: 11
+ color: UI.Style.inkMuted
+ }
+ }
UI.IconButton {
- anchors.verticalCenter: parent.verticalCenter
- width: 34
- height: 34
+ Layout.preferredWidth: 30
+ Layout.preferredHeight: 30
+ radius: 7
iconName: row.muted ? "sound-off" : "sound"
- iconSize: 18
- tip: row.muted ? "Unmute" : "Mute"
- onClicked: row.device.muted = !row.device.muted
+ iconSize: 16
+ tip: (row.muted ? "Unmute " : "Mute ") + row.title
+ onClicked: row.muteClicked()
}
UI.Slider {
- anchors.verticalCenter: parent.verticalCenter
- width: 240
- accessibleName: row.title
+ Layout.preferredWidth: 200
+ flat: true
+ accessibleName: row.title + " volume"
dimmed: row.muted
- to: 100
- value: row.device ? Math.min(100, page.percent(row.device.volume)) : 0
- onMoved: {
- row.device.volume = Math.round(value / 100 * PulseAudio.NormalVolume);
- if (row.device.muted && value > 0) {
- row.device.muted = false;
+ value: row.level
+ onMoved: row.volumeMoved(Math.round(value))
+ }
+
+ Percent {
+ text: row.level + "%"
+ }
+
+ Item {
+ Layout.fillWidth: true
+ }
+
+ UI.ComboBox {
+ visible: page.outputOptions.length > 0
+ Accessible.name: row.title + " output device"
+ model: page.outputOptions
+ currentIndex: model ? model.findIndex(o => o.value === row.deviceIndex) : -1
+ onActivated: index => row.deviceChosen(model[index].value)
+ }
+ }
+ }
+
+ // An app, or all of Windows mode, with every stream it has open. The
+ // first stream speaks for the row; a change goes to all of them, so a
+ // second tab never plays louder than the slider says.
+ component AppRow: MixerRow {
+ id: app
+
+ property var group: ({ streams: [], windows: false, name: "" })
+ readonly property var lead: group.streams.length > 0 ? group.streams[0] : null
+ readonly property bool paused: group.streams.length > 0 && group.streams.every(s => s && s.corked)
+
+ // What the app is playing, unless it only names itself.
+ readonly property string mediaName: {
+ const shown = group.streams.find(s => s && !s.corked) || lead;
+ if (!shown) {
+ return "";
+ }
+ const text = String(page.props(shown)["media.name"] || shown.name || "");
+ return /^(playback|audio ?stream|output|sound|audio|simple ?dsp)$/i.test(text.trim()) || text === group.name ? "" : text;
+ }
+
+ // The Windows apps that are open now, from Windows mode's service.
+ readonly property string openWindowsApps: {
+ if (!group.windows) {
+ return "";
+ }
+ const apps = WindowsMode.status.apps || [];
+ return apps.filter(a => a.open).map(a => a.name).join(", ");
+ }
+
+ title: group.name
+ windowsMode: group.windows
+ subtitle: group.windows
+ ? (openWindowsApps.length > 0 ? openWindowsApps + ". Share one volume" : "All Windows apps share one volume")
+ : paused ? "Paused" : mediaName
+ muted: lead !== null && lead.muted
+ level: lead ? Math.min(100, page.percent(lead.volume)) : 0
+ deviceIndex: lead ? lead.deviceIndex : -1
+
+ onVolumeMoved: value => {
+ for (const s of group.streams) {
+ if (!s) {
+ continue;
+ }
+ s.volume = page.toVolume(value);
+ if (s.muted && value > 0) {
+ s.muted = false;
+ }
+ }
+ }
+ onMuteClicked: {
+ const mute = !muted;
+ for (const s of group.streams) {
+ if (s) {
+ s.muted = mute;
+ }
+ }
+ }
+ // Moving the streams is PipeWire's own per-stream routing; it
+ // remembers the choice for the app next time.
+ onDeviceChosen: index => {
+ for (const s of group.streams) {
+ if (s && s.deviceIndex !== index) {
+ s.deviceIndex = index;
+ }
+ }
+ }
+
+ Rectangle {
+ anchors.fill: parent
+ visible: app.group.windows
+ radius: 8
+ color: "#2b3556"
+
+ Grid {
+ anchors.centerIn: parent
+ columns: 2
+ spacing: 2
+
+ Repeater {
+ model: 4
+
+ Rectangle {
+ width: 6
+ height: 6
+ color: "#8fb4ff"
}
}
}
}
+
+ UI.ThemeIcon {
+ id: appIcon
+ anchors.fill: parent
+ visible: !app.group.windows && valid
+ name: app.lead ? app.lead.iconName : ""
+ fallback: app.lead ? String(page.props(app.lead)["application.icon_name"] || page.props(app.lead)["application.process.binary"] || "") : ""
+ }
+
+ Rectangle {
+ anchors.fill: parent
+ visible: !app.group.windows && !appIcon.valid
+ radius: 8
+ color: UI.Style.tone(0.10)
+
+ UI.Icon {
+ anchors.centerIn: parent
+ name: "music"
+ size: 15
+ }
+ }
+ }
+
+ // Notifications and alerts: plasma-pa's saved entry for the "event"
+ // role, which every notification sound plays under. Its output is a
+ // device name; none means the default output.
+ component SystemSoundsRow: MixerRow {
+ id: sounds
+
+ property var entry: null
+ readonly property var target: entry && entry.device ? page.byName(page.outputs, entry.device) : null
+
+ title: "System sounds"
+ subtitle: "Notifications and alerts"
+ muted: entry !== null && entry.muted
+ level: entry ? Math.min(100, page.percent(entry.volume)) : 0
+ deviceIndex: target ? target.index : page.output ? page.output.index : -1
+
+ onVolumeMoved: value => {
+ if (!entry) {
+ return;
+ }
+ entry.volume = page.toVolume(value);
+ if (entry.muted && value > 0) {
+ entry.muted = false;
+ }
+ }
+ onMuteClicked: if (entry) entry.muted = !entry.muted
+ onDeviceChosen: index => {
+ const sink = page.byIndex(page.outputs, index);
+ if (entry && sink) {
+ entry.device = sink.name;
+ }
+ }
+
+ Rectangle {
+ anchors.fill: parent
+ radius: 8
+ color: UI.Style.tone(0.10)
+
+ UI.Icon {
+ anchors.centerIn: parent
+ name: "bell"
+ size: 15
+ }
+ }
}
}
diff --git a/packages/wildos-settings/qml/pages/ThunderboltPage.qml b/packages/wildos-settings/qml/pages/ThunderboltPage.qml
new file mode 100644
index 0000000..8090f3b
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/ThunderboltPage.qml
@@ -0,0 +1,107 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.Settings
+import WildOS.UI as UI
+
+// Thunderbolt: the docks, drives and screens plugged into a Thunderbolt or
+// USB4 port. A new device stays shut out until someone allows it, as a
+// device on these ports can reach the PC's memory; once allowed it is
+// remembered until forgotten.
+PageScroll {
+ id: page
+
+ readonly property bool usable: Thunderbolt.available && Thunderbolt.hasPorts && !Thunderbolt.firmwareOff
+
+ Component.onCompleted: Thunderbolt.reload()
+
+ function statusText(device) {
+ switch (device.status) {
+ case "authorized": return device.stored ? "Connected, allowed" : "Connected, allowed until it is unplugged";
+ case "connected": return "Waiting to be allowed";
+ case "authorizing": return "Allowing";
+ case "auth-error": return "Could not be allowed";
+ case "connecting": return "Connecting";
+ case "disconnected": return "Not connected, allowed when plugged in";
+ default: return "Not ready";
+ }
+ }
+
+ Connections {
+ target: Thunderbolt
+ function onFailed(title, reason) {
+ notice.show(title, reason, true);
+ }
+ }
+
+ Notice {
+ id: notice
+ }
+
+ StatusCard {
+ visible: !page.usable
+ iconName: "bolt"
+ warning: true
+ title: Thunderbolt.firmwareOff ? "Thunderbolt is turned off in this PC's firmware" : "This PC has no Thunderbolt ports"
+ description: Thunderbolt.firmwareOff ? "Turn on Thunderbolt support in the PC's UEFI settings to use Thunderbolt devices."
+ : ""
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ visible: page.usable
+ spacing: 10
+
+ SectionTitle {
+ text: "Devices"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ Repeater {
+ id: deviceList
+ model: Thunderbolt.devices
+
+ UI.SettingRow {
+ id: deviceRow
+ required property var modelData
+ readonly property bool busy: Thunderbolt.busy === modelData.uid || modelData.status === "authorizing"
+ iconName: "bolt"
+ title: modelData.vendor && modelData.vendor.length > 0 ? modelData.vendor + " " + modelData.name : modelData.name
+ description: page.statusText(modelData)
+ descriptionColor: modelData.status === "connected" || modelData.status === "auth-error" ? UI.Style.warning : UI.Style.inkMuted
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: deviceRow.modelData.status === "connected" || deviceRow.modelData.status === "auth-error"
+ || (deviceRow.modelData.status === "authorized" && !deviceRow.modelData.stored)
+ kind: deviceRow.modelData.status === "authorized" ? "secondary" : "primary"
+ text: deviceRow.modelData.status === "authorized" ? "Always allow" : "Allow"
+ busy: deviceRow.busy
+ enabled: Thunderbolt.busy.length === 0
+ onClicked: Thunderbolt.allow(deviceRow.modelData.uid)
+ }
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: deviceRow.modelData.stored === true
+ text: "Forget"
+ busy: deviceRow.busy
+ enabled: Thunderbolt.busy.length === 0
+ onClicked: Thunderbolt.forget(deviceRow.modelData.uid)
+ }
+ }
+ }
+
+ UI.SettingRow {
+ visible: deviceList.count === 0
+ title: "No Thunderbolt devices connected"
+ description: "Plug in a dock or other Thunderbolt device and it appears here."
+ }
+ }
+ }
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/TimePage.qml b/packages/wildos-settings/qml/pages/TimePage.qml
index 0ba6421..55d84b9 100644
--- a/packages/wildos-settings/qml/pages/TimePage.qml
+++ b/packages/wildos-settings/qml/pages/TimePage.qml
@@ -83,6 +83,15 @@ PageScroll {
onClicked: Navigator.open("language")
}
+ UI.SettingRow {
+ visible: Pages.exists("typing")
+ iconName: "pencil"
+ title: "Typing"
+ description: "Spell checking and your dictionary"
+ chevron: true
+ onClicked: Navigator.open("typing")
+ }
+
UI.SettingRow {
visible: Pages.exists("keyboard")
iconName: "keyboard"
diff --git a/packages/wildos-settings/qml/pages/TouchscreenPage.qml b/packages/wildos-settings/qml/pages/TouchscreenPage.qml
new file mode 100644
index 0000000..e6d0049
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/TouchscreenPage.qml
@@ -0,0 +1,79 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.Settings
+import WildOS.UI as UI
+
+// Touchscreen, after Windows 11's Touch settings and the old Tablet PC
+// settings' "which screen is this": turn touch on or off, and tie each
+// touchscreen to the screen it sits on, for a PC with more than one.
+// KWin applies each change straight away and keeps it for the device.
+PageScroll {
+ id: page
+
+ readonly property var screens: InputDevices.touchscreens
+
+ ScreenChoices {
+ id: screenChoices
+ }
+
+ StatusCard {
+ visible: page.screens.length === 0
+ iconName: "display"
+ warning: true
+ title: "No touchscreen connected"
+ description: "A touchscreen built into this PC or plugged in appears here."
+ }
+
+ Repeater {
+ model: page.screens
+
+ ColumnLayout {
+ id: touchscreen
+ required property var modelData
+ Layout.fillWidth: true
+ spacing: 10
+
+ SectionTitle {
+ visible: page.screens.length > 1
+ text: touchscreen.modelData.name
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ visible: touchscreen.modelData.supportsDisableEvents === true
+ iconName: "display"
+ title: "Touch"
+ description: "Use your fingers on the screen"
+ status: touchscreen.modelData.enabled === true ? "On" : "Off"
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: touchscreen.modelData.enabled === true
+ Accessible.name: "Touch on " + touchscreen.modelData.name
+ onToggled: InputDevices.setDevice(touchscreen.modelData.sysName, "enabled", checked)
+ }
+ }
+
+ UI.SettingRow {
+ title: "Screen"
+ description: screenChoices.screenCount > 1 ? "The screen this touchscreen is part of" : "Only one screen is connected"
+ enabled: screenChoices.screenCount > 1
+
+ UI.ComboBox {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "Screen for " + touchscreen.modelData.name
+ model: screenChoices.model
+ currentIndex: screenChoices.indexOf(touchscreen.modelData.outputName || "")
+ onActivated: index => InputDevices.setDevice(touchscreen.modelData.sysName, "outputName", model[index].value)
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/TypingPage.qml b/packages/wildos-settings/qml/pages/TypingPage.qml
new file mode 100644
index 0000000..ec42c9e
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/TypingPage.qml
@@ -0,0 +1,224 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.Settings
+import WildOS.UI as UI
+
+// Typing, after Windows 11's Time and language > Typing: spell checking,
+// the languages it checks in and the words you have taught it. It covers
+// the apps that check spelling through KDE's Sonnet; browsers and office
+// suites keep their own spelling settings.
+PageScroll {
+ id: page
+
+ readonly property bool hasDictionaries: Spelling.dictionaries.length > 0
+ readonly property var others: Spelling.dictionaries.filter(d => d.value !== Spelling.language)
+
+ function addWord() {
+ if (Spelling.addWord(wordField.text)) {
+ wordField.clear();
+ }
+ }
+
+ StatusCard {
+ visible: !page.hasDictionaries
+ iconName: "warning"
+ warning: true
+ title: "No spelling dictionaries are installed"
+ description: "Spell checking needs a dictionary for each language. Install one, such as hunspell-en-gb, and open this page again."
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ SectionTitle {
+ text: "Spelling"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ iconName: "pencil"
+ title: "Check spelling"
+ description: "Underline misspelt words in apps that check spelling"
+ status: Spelling.enabled ? "On" : "Off"
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: Spelling.enabled
+ Accessible.name: "Check spelling"
+ onToggled: Spelling.setEnabled(checked)
+ }
+ }
+
+ UI.SettingRow {
+ title: "Check as I type"
+ description: "Look over each word as you write it, not only when you ask"
+ enabled: Spelling.enabled
+ status: Spelling.asYouType ? "On" : "Off"
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: Spelling.asYouType
+ Accessible.name: "Check as I type"
+ onToggled: Spelling.setAsYouType(checked)
+ }
+ }
+
+ UI.SettingRow {
+ title: "Ignore words in capitals"
+ description: "Leave words such as NASA or HTML alone"
+ enabled: Spelling.enabled
+ status: Spelling.skipUppercase ? "On" : "Off"
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: Spelling.skipUppercase
+ Accessible.name: "Ignore words in capitals"
+ onToggled: Spelling.setSkipUppercase(checked)
+ }
+ }
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+ visible: page.hasDictionaries
+
+ SectionTitle {
+ text: "Languages"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ iconName: "language"
+ title: "Spelling language"
+ description: "The dictionary used first"
+
+ UI.ComboBox {
+ anchors.verticalCenter: parent.verticalCenter
+ Accessible.name: "Spelling language"
+ model: Spelling.dictionaries
+ readonly property string choice: Spelling.language
+ currentIndex: model.findIndex(o => o.value === choice)
+ displayText: currentIndex >= 0 ? currentText : choice
+ onActivated: index => Spelling.setLanguage(model[index].value)
+ }
+ }
+
+ UI.SettingRow {
+ visible: page.others.length > 0
+ title: "Detect the language I'm writing in"
+ description: "Switch to whichever of your languages a sentence is in"
+ status: Spelling.autodetect ? "On" : "Off"
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: Spelling.autodetect
+ Accessible.name: "Detect the language I'm writing in"
+ onToggled: Spelling.setAutodetect(checked)
+ }
+ }
+
+ Repeater {
+ model: Spelling.autodetect ? page.others : []
+
+ UI.SettingRow {
+ id: other
+ required property var modelData
+ minHeight: 44
+ title: modelData.text
+
+ leading: UI.CheckBox {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: Spelling.otherLanguages.includes(other.modelData.value)
+ Accessible.name: "Also check " + other.modelData.text
+ onToggled: Spelling.setOtherLanguage(other.modelData.value, checked)
+ }
+ }
+ }
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+ visible: page.hasDictionaries
+
+ SectionTitle {
+ text: "Your dictionary"
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: "Words here are never marked as misspelt. Names, places and words from your work are good ones to add."
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ title: "Add a word"
+
+ UI.TextField {
+ id: wordField
+ anchors.verticalCenter: parent.verticalCenter
+ width: 220
+ placeholderText: "Type a word"
+ onAccepted: page.addWord()
+ }
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Add"
+ iconName: "plus"
+ enabled: wordField.text.trim().length > 0 && !wordField.text.trim().includes(" ")
+ onClicked: page.addWord()
+ }
+ }
+
+ UI.SettingRow {
+ visible: Spelling.words.length === 0
+ title: "No words added yet"
+ description: "Add words here, or choose Add to dictionary when an app underlines one"
+ }
+
+ Repeater {
+ model: Spelling.words
+
+ UI.SettingRow {
+ id: wordRow
+ required property string modelData
+ minHeight: 44
+ title: modelData
+
+ UI.IconButton {
+ anchors.verticalCenter: parent.verticalCenter
+ iconName: "delete"
+ tip: "Remove " + wordRow.modelData
+ onClicked: Spelling.removeWord(wordRow.modelData)
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/packages/wildos-settings/src/access/main.cpp b/packages/wildos-settings/src/access/main.cpp
new file mode 100644
index 0000000..0b69fbd
--- /dev/null
+++ b/packages/wildos-settings/src/access/main.cpp
@@ -0,0 +1,155 @@
+// wildos-access: the accessibility shortcuts Plasma has no owner for, and
+// the switches the lock and sign-in screens flip.
+//
+// wildos-access in the session (autostart): Super
+// Alt H for high contrast, Super Ctrl
+// O for the on-screen keyboard and
+// Shift pressed five times for sticky
+// keys, through KDE's global shortcuts
+// wildos-access toggle WHAT high-contrast, screen-reader or
+// sticky-keys, for the lock and
+// sign-in screens, where global
+// shortcuts do not reach
+// wildos-access zoom in|out|reset the magnifier, for the sign-in
+// screen
+// wildos-access restore starts the screen reader if it was
+// left on (sign-in screen start-up)
+//
+// Super Alt S in the session belongs to kaccess and Super plus and minus
+// to KWin; both work as Plasma ships them.
+
+#include "accesscore.h"
+
+#include <KGlobalAccel>
+
+#include <QAction>
+#include <QCoreApplication>
+#include <QDBusConnection>
+#include <QDBusMessage>
+#include <QElapsedTimer>
+#include <QGuiApplication>
+#include <QKeySequence>
+#include <QTimer>
+#include <QVariantMap>
+
+#include <memory>
+
+namespace
+{
+void notify(const QString &summary, const QString &body)
+{
+ QDBusMessage message = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.Notifications"), QStringLiteral("/org/freedesktop/Notifications"),
+ QStringLiteral("org.freedesktop.Notifications"), QStringLiteral("Notify"));
+ message << QStringLiteral("Accessibility") << uint(0) << QStringLiteral("preferences-desktop-accessibility") << summary << body << QStringList()
+ << QVariantMap() << int(5000);
+ // A short-lived command: wait for the reply, or it can exit before the
+ // message has left.
+ QDBusConnection::sessionBus().call(message, QDBus::Block, 2000);
+}
+
+void toggleStickyKeys(bool tell)
+{
+ const bool on = !AccessCore::stickyKeys();
+ AccessCore::setStickyKeys(on);
+ if (tell) {
+ notify(on ? QStringLiteral("Sticky keys are on") : QStringLiteral("Sticky keys are off"),
+ on ? QStringLiteral("Press the keys of a shortcut one at a time. Press Shift five times to turn this off.")
+ : QStringLiteral("Press Shift five times to turn them on again."));
+ }
+}
+
+QAction *shortcut(QObject *parent, const QString &name, const QString &text, const QKeySequence &keys)
+{
+ auto action = new QAction(parent);
+ action->setObjectName(name);
+ action->setText(text);
+ action->setProperty("componentName", QStringLiteral("wildos-access"));
+ action->setProperty("componentDisplayName", QStringLiteral("Accessibility"));
+ KGlobalAccel::self()->setGlobalShortcut(action, keys);
+ return action;
+}
+
+int runService(int argc, char **argv)
+{
+ QGuiApplication app(argc, argv);
+ app.setApplicationName(QStringLiteral("wildos-access"));
+ app.setQuitOnLastWindowClosed(false);
+
+ // One per session, however often it is started.
+ if (!QDBusConnection::sessionBus().registerService(QStringLiteral("org.wildos.Access"))) {
+ return 0;
+ }
+
+ QAction *contrast = shortcut(&app, QStringLiteral("high-contrast"), QStringLiteral("Turn high contrast on or off"), QKeySequence(Qt::META | Qt::ALT | Qt::Key_H));
+ QObject::connect(contrast, &QAction::triggered, &app, [&app] {
+ AccessCore::setHighContrast(!AccessCore::highContrast(), &app);
+ });
+
+ QAction *keyboard = shortcut(&app, QStringLiteral("on-screen-keyboard"), QStringLiteral("Show or hide the on-screen keyboard"),
+ QKeySequence(Qt::META | Qt::CTRL | Qt::Key_O));
+ QObject::connect(keyboard, &QAction::triggered, &app, [&app] {
+ AccessCore::setOnScreenKeyboard(!AccessCore::onScreenKeyboard(), &app);
+ });
+
+ // A shortcut of Shift alone fires each time Shift is pressed and let go
+ // with no other key, the way Super alone opens Start. KWin passes the
+ // key on to the app as well, so nothing is lost in typing. Five in a
+ // row, each within a second of the last, toggle sticky keys, as on
+ // Windows.
+ QAction *shift = shortcut(&app, QStringLiteral("sticky-keys"), QStringLiteral("Sticky keys (press Shift five times)"), QKeySequence(Qt::Key_Shift));
+ auto last = std::make_shared<QElapsedTimer>();
+ auto count = std::make_shared<int>(0);
+ QObject::connect(shift, &QAction::triggered, &app, [last, count] {
+ if (!last->isValid() || last->elapsed() > 1000) {
+ *count = 0;
+ }
+ last->restart();
+ if (++*count == 5) {
+ *count = 0;
+ toggleStickyKeys(true);
+ }
+ });
+
+ return app.exec();
+}
+}
+
+int main(int argc, char **argv)
+{
+ if (argc < 2) {
+ return runService(argc, argv);
+ }
+
+ QCoreApplication app(argc, argv);
+ app.setApplicationName(QStringLiteral("wildos-access"));
+ const QString command = QString::fromLocal8Bit(argv[1]);
+ const QString what = argc > 2 ? QString::fromLocal8Bit(argv[2]) : QString();
+
+ // Settings written with KConfig::Notify are announced on the session
+ // bus, and those announcements are sent from the event loop; quitting
+ // straight away could lose them, so the tool lingers for a moment.
+ const auto finish = [&app] {
+ QTimer::singleShot(500, &app, &QCoreApplication::quit);
+ };
+
+ if (command == QLatin1String("toggle") && what == QLatin1String("high-contrast")) {
+ AccessCore::setHighContrast(!AccessCore::highContrast(), &app, finish);
+ } else if (command == QLatin1String("toggle") && what == QLatin1String("screen-reader")) {
+ AccessCore::setScreenReader(!AccessCore::screenReader());
+ finish();
+ } else if (command == QLatin1String("toggle") && what == QLatin1String("sticky-keys")) {
+ // The lock and sign-in screens have nowhere to show a notification.
+ toggleStickyKeys(false);
+ finish();
+ } else if (command == QLatin1String("zoom") && (what == QLatin1String("in") || what == QLatin1String("out") || what == QLatin1String("reset"))) {
+ AccessCore::zoom(what);
+ finish();
+ } else if (command == QLatin1String("restore")) {
+ AccessCore::restoreScreenReader();
+ finish();
+ } else {
+ qWarning("Usage: wildos-access [toggle high-contrast|screen-reader|sticky-keys] [zoom in|out|reset] [restore]");
+ return 2;
+ }
+ return app.exec();
+}
diff --git a/packages/wildos-settings/src/accesscore.cpp b/packages/wildos-settings/src/accesscore.cpp
new file mode 100644
index 0000000..a849ec9
--- /dev/null
+++ b/packages/wildos-settings/src/accesscore.cpp
@@ -0,0 +1,625 @@
+#include "accesscore.h"
+
+#include <KConfig>
+#include <KConfigGroup>
+#include <KDesktopFile>
+#include <KSharedConfig>
+
+#include <QColor>
+#include <QDBusConnection>
+#include <QDBusConnectionInterface>
+#include <QDBusMessage>
+#include <QDBusReply>
+#include <QDBusVariant>
+#include <QDir>
+#include <QFile>
+#include <QFileInfo>
+#include <QPointer>
+#include <QProcess>
+#include <QStandardPaths>
+#include <QTimer>
+
+#include <signal.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+namespace
+{
+const QString kwinService = QStringLiteral("org.kde.KWin");
+const QString properties = QStringLiteral("org.freedesktop.DBus.Properties");
+const QString contrastScheme = QStringLiteral("WildOSHighContrast");
+const QString monoUnit = QStringLiteral("wildos-mono-audio.service");
+
+KSharedConfigPtr fresh(const QString &file)
+{
+ // Settings and the shortcut service both live for a whole session and
+ // either can change a value the other has cached.
+ KSharedConfigPtr config = KSharedConfig::openConfig(file, KConfig::NoGlobals);
+ config->reparseConfiguration();
+ return config;
+}
+
+template<typename T>
+T readAccess(const char *group, const char *key, const T &fallback)
+{
+ return fresh(QStringLiteral("kaccessrc"))->group(QString::fromLatin1(group)).readEntry(key, fallback);
+}
+
+template<typename T>
+void writeAccess(const char *group, const char *key, const T &value)
+{
+ KSharedConfigPtr config = fresh(QStringLiteral("kaccessrc"));
+ config->group(QString::fromLatin1(group)).writeEntry(key, value, KConfig::Notify);
+ config->sync();
+}
+
+// What kcm_access does after saving: kaccess applies the same choices to
+// X11 apps under Xwayland, and rereads the file when started again.
+void pokeKaccess()
+{
+ if (!QStandardPaths::findExecutable(QStringLiteral("kaccess")).isEmpty()) {
+ QProcess::startDetached(QStringLiteral("kaccess"), {});
+ }
+}
+
+bool kaccessRunning()
+{
+ const QDBusConnection bus = QDBusConnection::sessionBus();
+ return bus.interface() && bus.interface()->isServiceRegistered(QStringLiteral("org.kde.kaccess"));
+}
+
+QVariant getProperty(const QString &service, const QString &path, const QString &interface, const QString &name)
+{
+ QDBusMessage message = QDBusMessage::createMethodCall(service, path, properties, QStringLiteral("Get"));
+ message << interface << name;
+ const QDBusMessage reply = QDBusConnection::sessionBus().call(message, QDBus::Block, 2000);
+ if (reply.type() != QDBusMessage::ReplyMessage || reply.arguments().isEmpty()) {
+ return {};
+ }
+ return reply.arguments().constFirst().value<QDBusVariant>().variant();
+}
+
+void setProperty(const QString &service, const QString &path, const QString &interface, const QString &name, const QVariant &value)
+{
+ QDBusMessage message = QDBusMessage::createMethodCall(service, path, properties, QStringLiteral("Set"));
+ message << interface << name << QVariant::fromValue(QDBusVariant(value));
+ QDBusConnection::sessionBus().call(message, QDBus::Block, 2000);
+}
+
+void invokeKWinShortcut(const QString &name)
+{
+ QDBusMessage message = QDBusMessage::createMethodCall(QStringLiteral("org.kde.kglobalaccel"), QStringLiteral("/component/kwin"),
+ QStringLiteral("org.kde.kglobalaccel.Component"), QStringLiteral("invokeShortcut"));
+ message << name;
+ QDBusConnection::sessionBus().asyncCall(message);
+}
+
+void runAfter(QProcess *process, QObject *context, const std::function<void()> &next)
+{
+ QObject::connect(process, &QProcess::finished, context, [process, next] {
+ process->deleteLater();
+ if (next) {
+ next();
+ }
+ });
+ QObject::connect(process, &QProcess::errorOccurred, context, [process, next](QProcess::ProcessError error) {
+ if (error == QProcess::FailedToStart) {
+ process->deleteLater();
+ if (next) {
+ next();
+ }
+ }
+ });
+}
+
+// Orca has no command that stops it, and kaccess only clears the GNOME key
+// it would be started by, which leaves a running Orca talking. Orca shuts
+// down cleanly on SIGTERM.
+void stopOrca()
+{
+ const uid_t me = ::getuid();
+ const QStringList pids = QDir(QStringLiteral("/proc")).entryList(QDir::Dirs | QDir::NoDotAndDotDot);
+ for (const QString &entry : pids) {
+ bool ok = false;
+ const int pid = entry.toInt(&ok);
+ if (!ok) {
+ continue;
+ }
+ struct stat info;
+ if (::stat(QFile::encodeName(QStringLiteral("/proc/%1").arg(pid)).constData(), &info) != 0 || info.st_uid != me) {
+ continue;
+ }
+ QFile comm(QStringLiteral("/proc/%1/comm").arg(pid));
+ bool orca = comm.open(QIODevice::ReadOnly) && comm.readAll().trimmed() == "orca";
+ if (!orca) {
+ // Started as "python3 /usr/bin/orca" where the title could not
+ // be set.
+ QFile cmdline(QStringLiteral("/proc/%1/cmdline").arg(pid));
+ if (cmdline.open(QIODevice::ReadOnly)) {
+ const QList<QByteArray> args = cmdline.readAll().split('\0');
+ orca = args.size() > 1 && args.at(0).contains("python") && args.at(1).endsWith("/orca");
+ }
+ }
+ if (orca) {
+ ::kill(pid, SIGTERM);
+ }
+ }
+}
+
+void startOrca()
+{
+ // The GNOME key is what Orca and toolkits check to know a screen reader
+ // is wanted; kaccess sets it the same way before starting Orca.
+ QProcess::execute(QStringLiteral("gsettings"),
+ {QStringLiteral("set"), QStringLiteral("org.gnome.desktop.a11y.applications"), QStringLiteral("screen-reader-enabled"),
+ QStringLiteral("true")});
+ QProcess::startDetached(QStringLiteral("orca"), {QStringLiteral("--replace")});
+}
+
+void clearOrcaKey()
+{
+ QProcess::startDetached(QStringLiteral("gsettings"),
+ {QStringLiteral("set"), QStringLiteral("org.gnome.desktop.a11y.applications"), QStringLiteral("screen-reader-enabled"),
+ QStringLiteral("false")});
+}
+
+bool hasScheme(const QString &name)
+{
+ return !QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("color-schemes/%1.colors").arg(name)).isEmpty();
+}
+
+void writeWildos(const char *group, const char *key, const QVariant &value)
+{
+ KSharedConfigPtr wildos = fresh(QStringLiteral("wildosrc"));
+ wildos->group(QString::fromLatin1(group)).writeEntry(key, value, KConfig::Notify);
+ wildos->sync();
+}
+
+struct PointerColour {
+ const char *id;
+ const char *name;
+ const char *colour;
+ const char *theme;
+};
+
+// White and black are Breeze's own cursors; yellow and sea glass are
+// recoloured from Breeze Light when wildos-branding is built.
+const PointerColour pointerList[] = {
+ {"white", "White", "#ffffff", "Breeze_Light"},
+ {"black", "Black", "#111111", "breeze_cursors"},
+ {"yellow", "Yellow", "#f2d34a", "WildOS-Yellow"},
+ {"seaglass", "Sea glass", "#7fd6c8", "WildOS-SeaGlass"},
+};
+
+QString cursorTheme()
+{
+ QString theme = fresh(QStringLiteral("kcminputrc"))->group(QStringLiteral("Mouse")).readEntry("cursorTheme", QString());
+ if (theme.isEmpty() || theme == QLatin1String("default")) {
+ // Nothing chosen yet: Debian's x-cursor-theme alternative decides.
+ const KConfig fallback(QStringLiteral("/usr/share/icons/default/index.theme"), KConfig::SimpleConfig);
+ const QStringList inherits = fallback.group(QStringLiteral("Icon Theme")).readEntry("Inherits", QStringList());
+ theme = inherits.isEmpty() ? QStringLiteral("breeze_cursors") : inherits.constFirst();
+ }
+ return theme;
+}
+}
+
+namespace AccessCore
+{
+QString highContrastScheme()
+{
+ return contrastScheme;
+}
+
+bool stickyKeys()
+{
+ return readAccess("Keyboard", "StickyKeys", false);
+}
+
+void setStickyKeys(bool on)
+{
+ writeAccess("Keyboard", "StickyKeys", on);
+ pokeKaccess();
+}
+
+bool slowKeys()
+{
+ return readAccess("Keyboard", "SlowKeys", false);
+}
+
+int slowKeysDelay()
+{
+ return readAccess("Keyboard", "SlowKeysDelay", 500);
+}
+
+void setSlowKeys(bool on)
+{
+ writeAccess("Keyboard", "SlowKeys", on);
+ pokeKaccess();
+}
+
+void setSlowKeysDelay(int ms)
+{
+ writeAccess("Keyboard", "SlowKeysDelay", ms);
+ pokeKaccess();
+}
+
+bool bounceKeys()
+{
+ return readAccess("Keyboard", "BounceKeys", false);
+}
+
+int bounceKeysDelay()
+{
+ return readAccess("Keyboard", "BounceKeysDelay", 500);
+}
+
+void setBounceKeys(bool on)
+{
+ writeAccess("Keyboard", "BounceKeys", on);
+ pokeKaccess();
+}
+
+void setBounceKeysDelay(int ms)
+{
+ writeAccess("Keyboard", "BounceKeysDelay", ms);
+ pokeKaccess();
+}
+
+bool visibleBell()
+{
+ return readAccess("Bell", "VisibleBell", false);
+}
+
+void setVisibleBell(bool on)
+{
+ writeAccess("Bell", "VisibleBell", on);
+ if (on) {
+ // kcm_access turns the system bell on whenever any bell is wanted;
+ // without it no bell event reaches KWin's flash.
+ KSharedConfigPtr globals = KSharedConfig::openConfig(QStringLiteral("kdeglobals"));
+ globals->group(QStringLiteral("General")).writeEntry("UseSystemBell", true, KConfig::Notify);
+ globals->sync();
+ }
+ pokeKaccess();
+}
+
+bool screenReaderInstalled()
+{
+ return !QStandardPaths::findExecutable(QStringLiteral("orca")).isEmpty();
+}
+
+bool screenReader()
+{
+ return readAccess("ScreenReader", "Enabled", false);
+}
+
+void setScreenReader(bool on)
+{
+ writeAccess("ScreenReader", "Enabled", on);
+ if (kaccessRunning()) {
+ // kaccess owns Super Alt S in the session and keeps the value in
+ // memory; starting it again makes it reread the file and start Orca
+ // itself, so its shortcut stays in step with this switch.
+ pokeKaccess();
+ } else if (on) {
+ startOrca();
+ }
+ if (!on) {
+ clearOrcaKey();
+ stopOrca();
+ }
+}
+
+void restoreScreenReader()
+{
+ if (screenReader() && screenReaderInstalled()) {
+ startOrca();
+ }
+}
+
+bool highContrast()
+{
+ return fresh(QStringLiteral("kdeglobals"))->group(QStringLiteral("General")).readEntry("ColorScheme", QString()) == contrastScheme;
+}
+
+void setHighContrast(bool on, QObject *context, const std::function<void()> &done)
+{
+ KSharedConfigPtr globals = fresh(QStringLiteral("kdeglobals"));
+ const KConfigGroup general = globals->group(QStringLiteral("General"));
+ const QString current = general.readEntry("ColorScheme", QStringLiteral("WildOS"));
+ const bool tool = !QStandardPaths::findExecutable(QStringLiteral("plasma-apply-colorscheme")).isEmpty();
+
+ QString scheme;
+ QString accent;
+ if (on) {
+ if (current == contrastScheme || !hasScheme(contrastScheme)) {
+ if (done) {
+ done();
+ }
+ return;
+ }
+ // Remembered so turning high contrast off puts back exactly the
+ // theme and accent that were there.
+ KSharedConfigPtr wildos = fresh(QStringLiteral("wildosrc"));
+ KConfigGroup access = wildos->group(QStringLiteral("Accessibility"));
+ access.writeEntry("SchemeBeforeContrast", current);
+ access.writeEntry("AccentBeforeContrast", general.readEntry("AccentColor", QString()));
+ wildos->sync();
+ scheme = contrastScheme;
+ } else {
+ if (current != contrastScheme) {
+ if (done) {
+ done();
+ }
+ return;
+ }
+ const KConfigGroup access = fresh(QStringLiteral("wildosrc"))->group(QStringLiteral("Accessibility"));
+ scheme = access.readEntry("SchemeBeforeContrast", QStringLiteral("WildOS"));
+ if (scheme == contrastScheme || !hasScheme(scheme)) {
+ scheme = QStringLiteral("WildOS");
+ }
+ accent = access.readEntry("AccentBeforeContrast", QString());
+ }
+
+ const auto writeAccent = [accent] {
+ if (accent.isEmpty()) {
+ return;
+ }
+ KSharedConfigPtr config = fresh(QStringLiteral("kdeglobals"));
+ KConfigGroup group = config->group(QStringLiteral("General"));
+ group.writeEntry("AccentColor", accent, KConfig::Notify);
+ group.writeEntry("LastUsedCustomAccentColor", accent, KConfig::Notify);
+ config->sync();
+ };
+
+ if (!tool) {
+ KConfigGroup group = globals->group(QStringLiteral("General"));
+ group.writeEntry("ColorScheme", scheme, KConfig::Notify);
+ globals->sync();
+ writeAccent();
+ if (done) {
+ done();
+ }
+ return;
+ }
+
+ // As Settings and wildos-auto-theme apply a scheme: the tool resets the
+ // accent key, so the accent goes back on afterwards through the tool's
+ // own option and then the key Wild OS widgets read.
+ auto apply = new QProcess(context);
+ QPointer<QObject> guard(context);
+ runAfter(apply, context, [accent, writeAccent, context, guard, done] {
+ if (accent.isEmpty() || !guard) {
+ if (done) {
+ done();
+ }
+ return;
+ }
+ const QStringList rgb = accent.split(QLatin1Char(','));
+ const QColor colour = rgb.size() >= 3 ? QColor(rgb[0].trimmed().toInt(), rgb[1].trimmed().toInt(), rgb[2].trimmed().toInt()) : QColor(accent);
+ auto restore = new QProcess(context);
+ runAfter(restore, context, [writeAccent, done] {
+ writeAccent();
+ if (done) {
+ done();
+ }
+ });
+ restore->start(QStringLiteral("plasma-apply-colorscheme"), {QStringLiteral("--accent-color"), colour.name(QColor::HexRgb)});
+ });
+ apply->start(QStringLiteral("plasma-apply-colorscheme"), {scheme});
+}
+
+bool magnifier()
+{
+ return getProperty(kwinService, QStringLiteral("/Effects"), QStringLiteral("org.kde.kwin.Effects"), QStringLiteral("activeEffects"))
+ .toStringList()
+ .contains(QLatin1String("zoom"));
+}
+
+void zoom(const QString &action)
+{
+ // The effect stays loaded whether or not the screen is magnified, so
+ // Super and plus works at any time, as it does in Plasma by default.
+ KSharedConfigPtr kwin = KSharedConfig::openConfig(QStringLiteral("kwinrc"));
+ KConfigGroup plugins = kwin->group(QStringLiteral("Plugins"));
+ if (!plugins.readEntry("zoomEnabled", true)) {
+ plugins.writeEntry("zoomEnabled", true);
+ kwin->sync();
+ }
+ QDBusMessage load = QDBusMessage::createMethodCall(kwinService, QStringLiteral("/Effects"), QStringLiteral("org.kde.kwin.Effects"),
+ QStringLiteral("loadEffect"));
+ load << QStringLiteral("zoom");
+ // Waited for, so the zoom actions exist before they are invoked.
+ QDBusConnection::sessionBus().call(load, QDBus::Block, 2000);
+ if (action == QLatin1String("in")) {
+ invokeKWinShortcut(QStringLiteral("view_zoom_in"));
+ } else if (action == QLatin1String("out")) {
+ invokeKWinShortcut(QStringLiteral("view_zoom_out"));
+ } else {
+ invokeKWinShortcut(QStringLiteral("view_actual_size"));
+ }
+}
+
+void setMagnifier(bool on)
+{
+ // As Windows' Magnifier switch: on starts magnifying, off goes back to
+ // the normal size.
+ zoom(on ? QStringLiteral("in") : QStringLiteral("reset"));
+}
+
+QString keyboardDesktopFile()
+{
+ const QStringList dirs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("applications"), QStandardPaths::LocateDirectory);
+ QString found;
+ for (const QString &dir : dirs) {
+ const QStringList files = QDir(dir).entryList({QStringLiteral("*.desktop")}, QDir::Files);
+ for (const QString &name : files) {
+ const QString path = dir + QLatin1Char('/') + name;
+ const KDesktopFile file(path);
+ if (!file.desktopGroup().readEntry("X-KDE-Wayland-VirtualKeyboard", false)) {
+ continue;
+ }
+ if (name == QLatin1String("com.github.maliit.keyboard.desktop")) {
+ return path;
+ }
+ if (found.isEmpty()) {
+ found = path;
+ }
+ }
+ }
+ return found;
+}
+
+bool onScreenKeyboard()
+{
+ const KConfigGroup wayland = fresh(QStringLiteral("kwinrc"))->group(QStringLiteral("Wayland"));
+ if (wayland.readPathEntry("InputMethod", QString()).isEmpty()) {
+ return false;
+ }
+ const QVariant live = getProperty(kwinService, QStringLiteral("/VirtualKeyboard"), QStringLiteral("org.kde.kwin.VirtualKeyboard"), QStringLiteral("enabled"));
+ return live.isValid() ? live.toBool() : wayland.readEntry("VirtualKeyboardEnabled", true);
+}
+
+void setOnScreenKeyboard(bool on, QObject *context, const std::function<void()> &done)
+{
+ const QString desktopFile = keyboardDesktopFile();
+ if (on && desktopFile.isEmpty()) {
+ if (done) {
+ done();
+ }
+ return;
+ }
+ KSharedConfigPtr kwin = fresh(QStringLiteral("kwinrc"));
+ KConfigGroup wayland = kwin->group(QStringLiteral("Wayland"));
+ if (on) {
+ // What kcm_virtualkeyboard writes; KWin watches the key and starts
+ // the keyboard at once.
+ wayland.writePathEntry("InputMethod", desktopFile, KConfig::Notify);
+ }
+ wayland.writeEntry("VirtualKeyboardEnabled", on);
+ kwin->sync();
+ writeWildos("Accessibility", "OnScreenKeyboard", on);
+
+ setProperty(kwinService, QStringLiteral("/VirtualKeyboard"), QStringLiteral("org.kde.kwin.VirtualKeyboard"), QStringLiteral("enabled"), on);
+ if (!on) {
+ if (done) {
+ done();
+ }
+ return;
+ }
+ // KWin only shows its keyboard by itself after a touch; turned on here
+ // it should appear now, for someone using a mouse or a switch. The
+ // keyboard process needs a moment to connect before it can be shown.
+ QTimer::singleShot(1200, context, [done] {
+ QDBusConnection::sessionBus().asyncCall(QDBusMessage::createMethodCall(kwinService, QStringLiteral("/VirtualKeyboard"),
+ QStringLiteral("org.kde.kwin.VirtualKeyboard"), QStringLiteral("forceActivate")));
+ if (done) {
+ done();
+ }
+ });
+}
+
+QVariantList pointerColours()
+{
+ QVariantList list;
+ for (const PointerColour &p : pointerList) {
+ // A colour whose theme is missing is not offered.
+ bool installed = false;
+ for (const QString &dir : QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("icons"), QStandardPaths::LocateDirectory)) {
+ if (QFileInfo::exists(dir + QLatin1Char('/') + QString::fromLatin1(p.theme) + QStringLiteral("/index.theme"))) {
+ installed = true;
+ break;
+ }
+ }
+ if (installed) {
+ list.append(QVariantMap{{QStringLiteral("id"), QString::fromLatin1(p.id)},
+ {QStringLiteral("name"), QString::fromLatin1(p.name)},
+ {QStringLiteral("colour"), QColor(QString::fromLatin1(p.colour))},
+ {QStringLiteral("theme"), QString::fromLatin1(p.theme)}});
+ }
+ }
+ return list;
+}
+
+QString pointerColour()
+{
+ const QString theme = cursorTheme();
+ for (const PointerColour &p : pointerList) {
+ if (theme == QLatin1String(p.theme)) {
+ return QString::fromLatin1(p.id);
+ }
+ }
+ return {};
+}
+
+QList<int> pointerSizes()
+{
+ // Breeze's own sizes, so X11 apps draw the same size KWin does, and 96
+ // for the largest Windows offers.
+ return {24, 30, 36, 48, 60, 72, 96};
+}
+
+int pointerSize()
+{
+ return fresh(QStringLiteral("kcminputrc"))->group(QStringLiteral("Mouse")).readEntry("cursorSize", 24);
+}
+
+void setPointer(const QString &colourId, int size)
+{
+ QString theme;
+ for (const PointerColour &p : pointerList) {
+ if (colourId == QLatin1String(p.id)) {
+ theme = QString::fromLatin1(p.theme);
+ }
+ }
+ KSharedConfigPtr input = fresh(QStringLiteral("kcminputrc"));
+ KConfigGroup mouse = input->group(QStringLiteral("Mouse"));
+ if (!theme.isEmpty()) {
+ mouse.writeEntry("cursorTheme", theme, KConfig::Notify);
+ }
+ mouse.writeEntry("cursorSize", size, KConfig::Notify);
+ input->sync();
+ // What kcm_cursortheme sends (CursorChanged): KWin reloads its cursor
+ // and the GTK settings bridge follows.
+ auto message = QDBusMessage::createSignal(QStringLiteral("/KGlobalSettings"), QStringLiteral("org.kde.KGlobalSettings"), QStringLiteral("notifyChange"));
+ message << 5 << 0;
+ QDBusConnection::sessionBus().send(message);
+}
+
+bool monoAudio()
+{
+ QDBusMessage message = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.systemd1"), QStringLiteral("/org/freedesktop/systemd1"),
+ QStringLiteral("org.freedesktop.systemd1.Manager"), QStringLiteral("GetUnitFileState"));
+ message << monoUnit;
+ const QDBusReply<QString> reply = QDBusConnection::sessionBus().call(message, QDBus::Block, 2000);
+ return reply.isValid() && reply.value() == QLatin1String("enabled");
+}
+
+void setMonoAudio(bool on)
+{
+ // The mono mix is a PipeWire filter in a process of its own (the unit
+ // runs "pipewire -c wildos-mono-audio.conf"), so turning it on or off
+ // never restarts PipeWire or interrupts what is playing. Enabling the
+ // unit keeps the choice for the next sign-in.
+ const QString service = QStringLiteral("org.freedesktop.systemd1");
+ const QString path = QStringLiteral("/org/freedesktop/systemd1");
+ const QString manager = QStringLiteral("org.freedesktop.systemd1.Manager");
+ QDBusConnection bus = QDBusConnection::sessionBus();
+ if (on) {
+ QDBusMessage enable = QDBusMessage::createMethodCall(service, path, manager, QStringLiteral("EnableUnitFiles"));
+ enable << QStringList{monoUnit} << false << true;
+ bus.call(enable, QDBus::Block, 5000);
+ QDBusMessage start = QDBusMessage::createMethodCall(service, path, manager, QStringLiteral("StartUnit"));
+ start << monoUnit << QStringLiteral("replace");
+ bus.asyncCall(start);
+ } else {
+ QDBusMessage stop = QDBusMessage::createMethodCall(service, path, manager, QStringLiteral("StopUnit"));
+ stop << monoUnit << QStringLiteral("replace");
+ bus.asyncCall(stop);
+ QDBusMessage disable = QDBusMessage::createMethodCall(service, path, manager, QStringLiteral("DisableUnitFiles"));
+ disable << QStringList{monoUnit} << false;
+ bus.call(disable, QDBus::Block, 5000);
+ }
+}
+}
diff --git a/packages/wildos-settings/src/accesscore.h b/packages/wildos-settings/src/accesscore.h
new file mode 100644
index 0000000..1b6686f
--- /dev/null
+++ b/packages/wildos-settings/src/accesscore.h
@@ -0,0 +1,76 @@
+#pragma once
+
+#include <QObject>
+#include <QString>
+#include <QVariantList>
+
+#include <functional>
+
+// Where every accessibility choice lives and how the desktop is told about
+// it, shared by Settings' Accessibility page and wildos-access (the
+// shortcuts in the session, on the lock screen and on the sign-in screen),
+// so a switch and its shortcut can never disagree. Each value is kept where
+// KDE keeps it, so Plasma's own modules and KWin read what is written here:
+//
+// kaccessrc sticky, slow and bounce keys, the visible bell and the
+// 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
+// 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
+namespace AccessCore
+{
+// Wild OS's high contrast scheme (wildos-branding).
+QString highContrastScheme();
+
+bool stickyKeys();
+void setStickyKeys(bool on);
+bool slowKeys();
+int slowKeysDelay();
+void setSlowKeys(bool on);
+void setSlowKeysDelay(int ms);
+bool bounceKeys();
+int bounceKeysDelay();
+void setBounceKeys(bool on);
+void setBounceKeysDelay(int ms);
+bool visibleBell();
+void setVisibleBell(bool on);
+
+bool screenReaderInstalled();
+bool screenReader();
+void setScreenReader(bool on);
+// Starts Orca if it was left on, for a screen with no kaccess of its own
+// (the sign-in screen).
+void restoreScreenReader();
+
+bool highContrast();
+// plasma-apply-colorscheme runs in the background; done is called on
+// context's thread once the scheme (and the accent, when going back) is in.
+void setHighContrast(bool on, QObject *context, const std::function<void()> &done = {});
+
+// "zoom" in KWin's active effects means the screen is magnified now.
+bool magnifier();
+void setMagnifier(bool on);
+// in, out or reset: KWin's own zoom actions, so they behave exactly like
+// Super and plus, minus and 0.
+void zoom(const QString &action);
+
+// The input method KWin runs as its on-screen keyboard: any installed
+// keyboard that declares itself one (X-KDE-Wayland-VirtualKeyboard), Maliit
+// first.
+QString keyboardDesktopFile();
+bool onScreenKeyboard();
+void setOnScreenKeyboard(bool on, QObject *context, const std::function<void()> &done = {});
+
+// The pointer colours Settings offers, as { id, name, colour, theme }.
+QVariantList pointerColours();
+QString pointerColour();
+int pointerSize();
+QList<int> pointerSizes();
+void setPointer(const QString &colourId, int size);
+
+bool monoAudio();
+void setMonoAudio(bool on);
+}
diff --git a/packages/wildos-settings/src/accessibility.cpp b/packages/wildos-settings/src/accessibility.cpp
new file mode 100644
index 0000000..83c2619
--- /dev/null
+++ b/packages/wildos-settings/src/accessibility.cpp
@@ -0,0 +1,174 @@
+#include "accessibility.h"
+
+#include "accesscore.h"
+
+#include <KSharedConfig>
+
+#include <QDBusConnection>
+#include <QFile>
+#include <QStandardPaths>
+
+Accessibility::Accessibility(QObject *parent)
+ : QObject(parent)
+{
+ m_pointerColours = AccessCore::pointerColours();
+ m_screenReaderInstalled = AccessCore::screenReaderInstalled();
+ m_highContrastInstalled =
+ !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();
+
+ // Shortcuts, kcm_access, the Plasma keyboard indicator or another
+ // Settings window can change any of these while the page is open.
+ watch(QStringLiteral("kaccessrc"));
+ watch(QStringLiteral("kdeglobals"));
+ watch(QStringLiteral("kcminputrc"));
+ watch(QStringLiteral("kwinrc"));
+ QDBusConnection::sessionBus().connect(QStringLiteral("org.kde.KWin"), QStringLiteral("/VirtualKeyboard"), QStringLiteral("org.kde.kwin.VirtualKeyboard"),
+ QStringLiteral("enabledChanged"), this, SLOT(refresh()));
+
+ m_monoAudio = AccessCore::monoAudio();
+ refresh();
+ refreshMagnifier();
+}
+
+void Accessibility::watch(const QString &file)
+{
+ KConfigWatcher::Ptr watcher = KConfigWatcher::create(KSharedConfig::openConfig(file, KConfig::NoGlobals));
+ if (watcher) {
+ connect(watcher.data(), &KConfigWatcher::configChanged, this, &Accessibility::refresh);
+ m_watchers.append(watcher);
+ }
+}
+
+QList<int> Accessibility::pointerSizes() const
+{
+ return AccessCore::pointerSizes();
+}
+
+void Accessibility::refresh()
+{
+ m_pointerColour = AccessCore::pointerColour();
+ m_pointerSize = AccessCore::pointerSize();
+ m_screenReader = AccessCore::screenReader();
+ if (!m_highContrastBusy) {
+ m_highContrast = AccessCore::highContrast();
+ }
+ m_visibleBell = AccessCore::visibleBell();
+ m_onScreenKeyboard = AccessCore::onScreenKeyboard();
+ m_stickyKeys = AccessCore::stickyKeys();
+ m_slowKeys = AccessCore::slowKeys();
+ m_slowKeysDelay = AccessCore::slowKeysDelay();
+ m_bounceKeys = AccessCore::bounceKeys();
+ m_bounceKeysDelay = AccessCore::bounceKeysDelay();
+ Q_EMIT changed();
+}
+
+void Accessibility::refreshMagnifier()
+{
+ const bool on = AccessCore::magnifier();
+ if (on != m_magnifier) {
+ m_magnifier = on;
+ Q_EMIT magnifierChanged();
+ }
+}
+
+void Accessibility::setPointerColour(const QString &id)
+{
+ AccessCore::setPointer(id, m_pointerSize);
+ m_pointerColour = id;
+ Q_EMIT changed();
+}
+
+void Accessibility::setPointerSize(int size)
+{
+ AccessCore::setPointer(m_pointerColour, size);
+ m_pointerSize = size;
+ Q_EMIT changed();
+}
+
+void Accessibility::setMagnifier(bool on)
+{
+ AccessCore::setMagnifier(on);
+ m_magnifier = on;
+ Q_EMIT magnifierChanged();
+}
+
+void Accessibility::setScreenReader(bool on)
+{
+ AccessCore::setScreenReader(on);
+ m_screenReader = on;
+ Q_EMIT changed();
+}
+
+void Accessibility::setHighContrast(bool on)
+{
+ if (m_highContrastBusy) {
+ return;
+ }
+ m_highContrastBusy = true;
+ m_highContrast = on;
+ Q_EMIT changed();
+ AccessCore::setHighContrast(on, this, [this] {
+ m_highContrastBusy = false;
+ refresh();
+ });
+}
+
+void Accessibility::setVisibleBell(bool on)
+{
+ AccessCore::setVisibleBell(on);
+ m_visibleBell = on;
+ Q_EMIT changed();
+}
+
+void Accessibility::setMonoAudio(bool on)
+{
+ AccessCore::setMonoAudio(on);
+ m_monoAudio = on;
+ Q_EMIT changed();
+}
+
+void Accessibility::setOnScreenKeyboard(bool on)
+{
+ m_onScreenKeyboard = on;
+ Q_EMIT changed();
+ AccessCore::setOnScreenKeyboard(on, this, [this] {
+ refresh();
+ });
+}
+
+void Accessibility::setStickyKeys(bool on)
+{
+ AccessCore::setStickyKeys(on);
+ m_stickyKeys = on;
+ Q_EMIT changed();
+}
+
+void Accessibility::setSlowKeys(bool on)
+{
+ AccessCore::setSlowKeys(on);
+ m_slowKeys = on;
+ Q_EMIT changed();
+}
+
+void Accessibility::setSlowKeysDelay(int ms)
+{
+ AccessCore::setSlowKeysDelay(ms);
+ m_slowKeysDelay = ms;
+ Q_EMIT changed();
+}
+
+void Accessibility::setBounceKeys(bool on)
+{
+ AccessCore::setBounceKeys(on);
+ m_bounceKeys = on;
+ Q_EMIT changed();
+}
+
+void Accessibility::setBounceKeysDelay(int ms)
+{
+ AccessCore::setBounceKeysDelay(ms);
+ m_bounceKeysDelay = ms;
+ Q_EMIT changed();
+}
diff --git a/packages/wildos-settings/src/accessibility.h b/packages/wildos-settings/src/accessibility.h
new file mode 100644
index 0000000..e0dc3cc
--- /dev/null
+++ b/packages/wildos-settings/src/accessibility.h
@@ -0,0 +1,114 @@
+#pragma once
+
+#include <KConfigWatcher>
+
+#include <QObject>
+#include <QQmlEngine>
+#include <QVariantList>
+
+// Settings > Accessibility. The values and how they are applied live in
+// AccessCore, which the shortcut service shares; this follows them live,
+// so a shortcut pressed while the page is open (Super Alt H, Shift five
+// times) moves its switch too, and a page made again by the Loader reads
+// the current state rather than anything remembered from last time.
+class Accessibility : public QObject
+{
+ Q_OBJECT
+ QML_ELEMENT
+ QML_SINGLETON
+
+ Q_PROPERTY(QVariantList pointerColours READ pointerColours CONSTANT)
+ Q_PROPERTY(QList<int> pointerSizes READ pointerSizes CONSTANT)
+ Q_PROPERTY(QString pointerColour READ pointerColour NOTIFY changed)
+ Q_PROPERTY(int pointerSize READ pointerSize NOTIFY changed)
+ Q_PROPERTY(bool magnifier READ magnifier NOTIFY magnifierChanged)
+ Q_PROPERTY(bool screenReaderInstalled READ screenReaderInstalled CONSTANT)
+ Q_PROPERTY(bool screenReader READ screenReader NOTIFY changed)
+ Q_PROPERTY(bool highContrastInstalled READ highContrastInstalled CONSTANT)
+ Q_PROPERTY(bool highContrast READ highContrast NOTIFY changed)
+ // True while the colour scheme is being applied, which takes a moment.
+ Q_PROPERTY(bool highContrastBusy READ highContrastBusy NOTIFY changed)
+ Q_PROPERTY(bool visibleBell READ visibleBell NOTIFY changed)
+ Q_PROPERTY(bool monoAudioInstalled READ monoAudioInstalled CONSTANT)
+ Q_PROPERTY(bool monoAudio READ monoAudio NOTIFY changed)
+ Q_PROPERTY(bool onScreenKeyboardInstalled READ onScreenKeyboardInstalled CONSTANT)
+ Q_PROPERTY(bool onScreenKeyboard READ onScreenKeyboard NOTIFY changed)
+ Q_PROPERTY(bool stickyKeys READ stickyKeys NOTIFY changed)
+ Q_PROPERTY(bool slowKeys READ slowKeys NOTIFY changed)
+ Q_PROPERTY(int slowKeysDelay READ slowKeysDelay NOTIFY changed)
+ Q_PROPERTY(bool bounceKeys READ bounceKeys NOTIFY changed)
+ Q_PROPERTY(int bounceKeysDelay READ bounceKeysDelay NOTIFY changed)
+
+public:
+ explicit Accessibility(QObject *parent = nullptr);
+
+ QVariantList pointerColours() const { return m_pointerColours; }
+ QList<int> pointerSizes() const;
+ QString pointerColour() const { return m_pointerColour; }
+ int pointerSize() const { return m_pointerSize; }
+ bool magnifier() const { return m_magnifier; }
+ bool screenReaderInstalled() const { return m_screenReaderInstalled; }
+ bool screenReader() const { return m_screenReader; }
+ bool highContrastInstalled() const { return m_highContrastInstalled; }
+ bool highContrast() const { return m_highContrast; }
+ bool highContrastBusy() const { return m_highContrastBusy; }
+ bool visibleBell() const { return m_visibleBell; }
+ bool monoAudioInstalled() const { return m_monoAudioInstalled; }
+ bool monoAudio() const { return m_monoAudio; }
+ bool onScreenKeyboardInstalled() const { return m_keyboardInstalled; }
+ bool onScreenKeyboard() const { return m_onScreenKeyboard; }
+ bool stickyKeys() const { return m_stickyKeys; }
+ bool slowKeys() const { return m_slowKeys; }
+ int slowKeysDelay() const { return m_slowKeysDelay; }
+ bool bounceKeys() const { return m_bounceKeys; }
+ int bounceKeysDelay() const { return m_bounceKeysDelay; }
+
+ Q_INVOKABLE void setPointerColour(const QString &id);
+ Q_INVOKABLE void setPointerSize(int size);
+ Q_INVOKABLE void setMagnifier(bool on);
+ Q_INVOKABLE void setScreenReader(bool on);
+ Q_INVOKABLE void setHighContrast(bool on);
+ Q_INVOKABLE void setVisibleBell(bool on);
+ Q_INVOKABLE void setMonoAudio(bool on);
+ Q_INVOKABLE void setOnScreenKeyboard(bool on);
+ Q_INVOKABLE void setStickyKeys(bool on);
+ Q_INVOKABLE void setSlowKeys(bool on);
+ Q_INVOKABLE void setSlowKeysDelay(int ms);
+ Q_INVOKABLE void setBounceKeys(bool on);
+ Q_INVOKABLE void setBounceKeysDelay(int ms);
+
+public Q_SLOTS:
+ // Rereads everything. KWin has no signal for zoom, so the page also
+ // calls refreshMagnifier while it is showing.
+ void refresh();
+ void refreshMagnifier();
+
+Q_SIGNALS:
+ void changed();
+ void magnifierChanged();
+
+private:
+ void watch(const QString &file);
+
+ QVariantList m_pointerColours;
+ QString m_pointerColour;
+ int m_pointerSize = 24;
+ bool m_magnifier = false;
+ bool m_screenReaderInstalled = false;
+ bool m_screenReader = false;
+ bool m_highContrastInstalled = false;
+ bool m_highContrast = false;
+ bool m_highContrastBusy = false;
+ bool m_visibleBell = false;
+ bool m_monoAudioInstalled = false;
+ bool m_monoAudio = false;
+ bool m_keyboardInstalled = false;
+ bool m_onScreenKeyboard = false;
+ bool m_stickyKeys = false;
+ bool m_slowKeys = false;
+ int m_slowKeysDelay = 500;
+ bool m_bounceKeys = false;
+ int m_bounceKeysDelay = 500;
+
+ QList<KConfigWatcher::Ptr> m_watchers;
+};
diff --git a/packages/wildos-settings/src/activityhistory.cpp b/packages/wildos-settings/src/activityhistory.cpp
new file mode 100644
index 0000000..6fe241e
--- /dev/null
+++ b/packages/wildos-settings/src/activityhistory.cpp
@@ -0,0 +1,174 @@
+#include "activityhistory.h"
+
+#include <KApplicationTrader>
+#include <KConfig>
+#include <KConfigGroup>
+#include <KService>
+
+#include <QDBusConnection>
+#include <QDBusMessage>
+#include <QDBusPendingCallWatcher>
+#include <QDBusPendingReply>
+#include <QFile>
+#include <QStandardPaths>
+
+namespace
+{
+const QString pluginsrc = QStringLiteral("kactivitymanagerd-pluginsrc");
+// definitions.h SQLITE_PLUGIN_CONFIG_KEY
+const QString scoring = QStringLiteral("Plugin-org.kde.ActivityManager.Resources.Scoring");
+
+// kcm_recentFiles.h WhatToRemember
+enum WhatToRemember {
+ AllApplications = 0,
+ SpecificApplications = 1,
+ NoApplications = 2,
+};
+
+QVariantMap describe(const QString &name)
+{
+ const KService::Ptr service = KService::serviceByDesktopName(name);
+ return {{QStringLiteral("id"), name},
+ {QStringLiteral("name"), service ? service->name() : name},
+ {QStringLiteral("icon"), service ? service->icon() : QStringLiteral("application-x-executable")}};
+}
+}
+
+ActivityHistory::ActivityHistory(QObject *parent)
+ : QObject(parent)
+{
+}
+
+bool ActivityHistory::remember() const
+{
+ const KConfig config(pluginsrc, KConfig::NoGlobals);
+ return config.group(scoring).readEntry("what-to-remember", int(AllApplications)) != NoApplications;
+}
+
+int ActivityHistory::keepMonths() const
+{
+ const KConfig config(pluginsrc, KConfig::NoGlobals);
+ return config.group(scoring).readEntry("keep-history-for", 0);
+}
+
+QStringList ActivityHistory::blockedNames() const
+{
+ const KConfig config(pluginsrc, KConfig::NoGlobals);
+ return config.group(scoring).readEntry("blocked-applications", QStringList());
+}
+
+QVariantList ActivityHistory::blocked() const
+{
+ QVariantList out;
+ for (const QString &name : blockedNames()) {
+ out << describe(name);
+ }
+ return out;
+}
+
+QVariantList ActivityHistory::apps() const
+{
+ const QStringList taken = blockedNames();
+ const KService::List services = KApplicationTrader::query([&taken](const KService::Ptr &service) {
+ return !service->noDisplay() && !taken.contains(service->desktopEntryName());
+ });
+ QVariantList out;
+ for (const KService::Ptr &service : services) {
+ out << QVariantMap{{QStringLiteral("value"), service->desktopEntryName()}, {QStringLiteral("text"), service->name()}};
+ }
+ std::sort(out.begin(), out.end(), [](const QVariant &a, const QVariant &b) {
+ return a.toMap().value(QStringLiteral("text")).toString().localeAwareCompare(b.toMap().value(QStringLiteral("text")).toString()) < 0;
+ });
+ return out;
+}
+
+void ActivityHistory::writeMode(bool on, const QStringList &blocked)
+{
+ KConfig plugins(pluginsrc, KConfig::NoGlobals);
+ KConfigGroup group = plugins.group(scoring);
+ // A blocked list only counts in "specific applications" mode, with
+ // blocked-by-default off so the list holds the apps left out
+ // (StatsPlugin::acceptedEvent).
+ const int mode = !on ? NoApplications : blocked.isEmpty() ? AllApplications : SpecificApplications;
+ group.writeEntry("what-to-remember", mode);
+ group.writeEntry("blocked-by-default", false);
+ group.writeEntry("blocked-applications", blocked);
+ plugins.sync();
+
+ // The recent files module turns the scoring plugin off with "do not
+ // remember" (RecentFilesKcm::save).
+ KConfig daemon(QStringLiteral("kactivitymanagerdrc"), KConfig::NoGlobals);
+ daemon.group(QStringLiteral("Plugins")).writeEntry("org.kde.ActivityManager.ResourceScoringEnabled", on);
+ daemon.sync();
+
+ // KRecentDocument::add reads this in every KDE app before it adds a file.
+ KConfig globals(QStringLiteral("kdeglobals"));
+ globals.group(QStringLiteral("RecentDocuments")).writeEntry("UseRecent", on, KConfig::Notify);
+ globals.sync();
+ Q_EMIT changed();
+}
+
+void ActivityHistory::setRemember(bool on)
+{
+ writeMode(on, blockedNames());
+}
+
+void ActivityHistory::setKeepMonths(int months)
+{
+ KConfig plugins(pluginsrc, KConfig::NoGlobals);
+ plugins.group(scoring).writeEntry("keep-history-for", qMax(0, months));
+ plugins.sync();
+ Q_EMIT changed();
+}
+
+void ActivityHistory::block(const QString &app)
+{
+ QStringList list = blockedNames();
+ if (!app.isEmpty() && !list.contains(app)) {
+ list << app;
+ list.sort();
+ writeMode(remember(), list);
+ }
+}
+
+void ActivityHistory::unblock(const QString &app)
+{
+ QStringList list = blockedNames();
+ if (list.removeAll(app) > 0) {
+ writeMode(remember(), list);
+ }
+}
+
+void ActivityHistory::clear()
+{
+ if (m_clearing) {
+ return;
+ }
+ m_clearing = true;
+ Q_EMIT clearingChanged();
+
+ // KRecentDocument::clear() is exactly this.
+ QFile::remove(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QStringLiteral("/recently-used.xbel"));
+
+ // RecentFilesKcm::forgetAll: every activity, everything.
+ auto message = QDBusMessage::createMethodCall(QStringLiteral("org.kde.ActivityManager"), QStringLiteral("/ActivityManager/Resources/Scoring"),
+ QStringLiteral("org.kde.ActivityManager.ResourcesScoring"), QStringLiteral("DeleteRecentStats"));
+ message << QString() << 0 << QStringLiteral("everything");
+ auto watcher = new QDBusPendingCallWatcher(QDBusConnection::sessionBus().asyncCall(message), this);
+ connect(watcher, &QDBusPendingCallWatcher::finished, this, [this](QDBusPendingCallWatcher *call) {
+ const QDBusPendingReply<> reply = *call;
+ call->deleteLater();
+ m_clearing = false;
+ Q_EMIT clearingChanged();
+ if (reply.isError()) {
+ Q_EMIT failed(QStringLiteral("The activity service did not answer. Try again in a moment."));
+ } else {
+ Q_EMIT cleared();
+ }
+ });
+}
+
+void ActivityHistory::reload()
+{
+ Q_EMIT changed();
+}
diff --git a/packages/wildos-settings/src/activityhistory.h b/packages/wildos-settings/src/activityhistory.h
new file mode 100644
index 0000000..ad1cf29
--- /dev/null
+++ b/packages/wildos-settings/src/activityhistory.h
@@ -0,0 +1,62 @@
+#pragma once
+
+#include <QObject>
+#include <QQmlEngine>
+#include <QVariantList>
+
+// Activity history, after Windows 11's Privacy and security > Activity
+// history: whether this computer remembers the files you open (for Recent
+// in Start and Files), for how long, apps it never remembers, and clearing
+// it.
+//
+// The settings are KDE's recent files module's own (plasma-desktop
+// kcms/recentFiles): kactivitymanagerd-pluginsrc
+// [Plugin-org.kde.ActivityManager.Resources.Scoring] what-to-remember (0
+// every app, 1 all but blocked-applications, 2 none), keep-history-for in
+// months (0 is forever) and blocked-applications, plus kactivitymanagerdrc
+// [Plugins] org.kde.ActivityManager.ResourceScoringEnabled. kactivitymanagerd
+// watches both files, so a change applies at once. KIO's own recent
+// documents list (recently-used.xbel) follows kdeglobals [RecentDocuments]
+// UseRecent and is cleared with the rest.
+class ActivityHistory : public QObject
+{
+ Q_OBJECT
+ QML_ELEMENT
+ QML_SINGLETON
+
+ Q_PROPERTY(bool remember READ remember WRITE setRemember NOTIFY changed)
+ Q_PROPERTY(int keepMonths READ keepMonths WRITE setKeepMonths NOTIFY changed)
+ Q_PROPERTY(QVariantList blocked READ blocked NOTIFY changed)
+ Q_PROPERTY(bool clearing READ clearing NOTIFY clearingChanged)
+
+public:
+ explicit ActivityHistory(QObject *parent = nullptr);
+
+ bool remember() const;
+ void setRemember(bool on);
+ int keepMonths() const;
+ void setKeepMonths(int months);
+ // { id, name, icon } by desktop file name, as kactivitymanagerd records
+ // the app that opened a file.
+ QVariantList blocked() const;
+ bool clearing() const { return m_clearing; }
+
+ // Apps from Start that are not blocked yet, for choosing one.
+ Q_INVOKABLE QVariantList apps() const;
+ Q_INVOKABLE void block(const QString &app);
+ Q_INVOKABLE void unblock(const QString &app);
+ Q_INVOKABLE void clear();
+ Q_INVOKABLE void reload();
+
+Q_SIGNALS:
+ void changed();
+ void clearingChanged();
+ void cleared();
+ void failed(const QString &reason);
+
+private:
+ QStringList blockedNames() const;
+ void writeMode(bool remember, const QStringList &blocked);
+
+ bool m_clearing = false;
+};
diff --git a/packages/wildos-settings/src/appaccess.cpp b/packages/wildos-settings/src/appaccess.cpp
index 20d925b..7bf15c1 100644
--- a/packages/wildos-settings/src/appaccess.cpp
+++ b/packages/wildos-settings/src/appaccess.cpp
@@ -9,6 +9,7 @@
#include <QDir>
#include <QFile>
#include <QFileInfo>
+#include <QRegularExpression>
#include <QStandardPaths>
#include <glib.h>
@@ -116,6 +117,189 @@ QString busPolicy(GKeyFile *file)
g_free(value);
return out;
}
+
+QStringList groupKeys(GKeyFile *file, const char *group)
+{
+ QStringList out;
+ gsize length = 0;
+ gchar **keys = g_key_file_get_keys(file, group, &length, nullptr);
+ for (gsize i = 0; keys && i < length; ++i) {
+ out << QString::fromUtf8(keys[i]);
+ }
+ g_strfreev(keys);
+ return out;
+}
+
+bool hasEntry(GKeyFile *file, const char *group, const QString &key)
+{
+ return g_key_file_has_key(file, group, key.toUtf8().constData(), nullptr);
+}
+
+QString entry(GKeyFile *file, const char *group, const QString &key)
+{
+ gchar *value = g_key_file_get_string(file, group, key.toUtf8().constData(), nullptr);
+ const QString out = QString::fromUtf8(value);
+ g_free(value);
+ return out;
+}
+
+void setEntry(GKeyFile *file, const char *group, const QString &key, const QString &value)
+{
+ g_key_file_set_string(file, group, key.toUtf8().constData(), value.toUtf8().constData());
+}
+
+void removeEntry(GKeyFile *file, const char *group, const QString &key)
+{
+ g_key_file_remove_key(file, group, key.toUtf8().constData(), nullptr);
+}
+
+void setContextList(GKeyFile *file, const char *key, const QStringList &entries)
+{
+ if (entries.isEmpty()) {
+ g_key_file_remove_key(file, "Context", key, nullptr);
+ return;
+ }
+ QList<QByteArray> raw;
+ for (const QString &e : entries) {
+ raw << e.toUtf8();
+ }
+ QList<const char *> ptrs;
+ for (const QByteArray &b : std::as_const(raw)) {
+ ptrs << b.constData();
+ }
+ g_key_file_set_string_list(file, "Context", key, ptrs.constData(), gsize(ptrs.size()));
+}
+
+// The entry that grants base, with its ":ro" or ":create", if any does.
+QString grantingEntry(const QStringList &entries, const QString &base)
+{
+ QString out;
+ for (const QString &e : entries) {
+ if (baseOf(e) == base) {
+ out = e.startsWith(QLatin1Char('!')) ? QString() : e;
+ }
+ }
+ return out;
+}
+
+struct Choice {
+ const char *value;
+ const char *label;
+};
+
+struct ContextKey {
+ const char *key;
+ const char *title;
+ QList<Choice> choices;
+};
+
+// Every value Flatpak knows for each list (flatpak-context.c), so an app can
+// be given one it did not ask for as well as lose one it did.
+const QList<ContextKey> &contextKeys()
+{
+ static const QList<ContextKey> list = {
+ {"shared", "Network",
+ {{"network", "Internet and your local network"}, {"ipc", "Shared memory with apps outside its sandbox"}}},
+ {"devices", "Devices",
+ {{"dri", "Graphics acceleration"},
+ {"input", "Game controllers and other input devices"},
+ {"usb", "USB devices"},
+ {"kvm", "Running virtual machines"},
+ {"shm", "Shared memory between apps"},
+ {"all", "Every device, including cameras"}}},
+ {"features", "Other features",
+ {{"bluetooth", "Bluetooth"},
+ {"canbus", "Vehicle and machine networks (CAN bus)"},
+ {"devel", "Debugging other programs"},
+ {"multiarch", "Running 32-bit programs"},
+ {"per-app-dev-shm", "Its own shared memory folder"}}},
+ {"sockets", "Display, sound and system",
+ {{"wayland", "Showing windows"},
+ {"x11", "Showing windows the older way (X11)"},
+ {"fallback-x11", "The older way when the newer one is missing"},
+ {"inherit-wayland-socket", "Showing windows through the app that started it"},
+ {"pulseaudio", "Sound and your microphone"},
+ {"cups", "Printing"},
+ {"pcsc", "Smart cards"},
+ {"ssh-auth", "Your SSH keys"},
+ {"gpg-agent", "Your GPG keys"},
+ {"session-bus", "Every service in your session"},
+ {"system-bus", "Every service on this computer"}}},
+ };
+ return list;
+}
+
+QString folderLabel(const QString &base)
+{
+ for (const Folder &f : folders()) {
+ if (base == QLatin1String(f.base)) {
+ return QString::fromLatin1(f.label);
+ }
+ }
+ static const QList<std::pair<const char *, const char *>> more = {
+ {"host-os", "This computer's programs and libraries"},
+ {"host-etc", "This computer's system settings"},
+ {"xdg-config", "Settings of every app"},
+ {"xdg-cache", "Cached files of every app"},
+ {"xdg-data", "Data of every app"},
+ {"xdg-templates", "Your Templates folder"},
+ {"xdg-public-share", "Your Public folder"},
+ };
+ for (const auto &[key, label] : more) {
+ if (base == QLatin1String(key)) {
+ return QString::fromLatin1(label);
+ }
+ }
+ return base;
+}
+
+QString folderDetail(const QString &grant, bool allowed)
+{
+ if (!allowed) {
+ return QStringLiteral("No access");
+ }
+ if (grant.endsWith(QLatin1String(":ro"))) {
+ return QStringLiteral("Can open files, not change them");
+ }
+ if (grant.endsWith(QLatin1String(":create"))) {
+ return QStringLiteral("Can open and change files, and create the folder");
+ }
+ return QStringLiteral("Can open and change files");
+}
+
+bool policyAllows(const QString &policy)
+{
+ return !policy.isEmpty() && policy != QLatin1String("none");
+}
+
+QString policyDetail(const QString &policy)
+{
+ if (policy == QLatin1String("own")) {
+ return QStringLiteral("Can talk to it and take its name");
+ }
+ if (policy == QLatin1String("talk")) {
+ return QStringLiteral("Can talk to it");
+ }
+ if (policy == QLatin1String("see")) {
+ return QStringLiteral("Can see it is there");
+ }
+ return QStringLiteral("No access");
+}
+
+QVariantMap item(const QString &token, const QString &label, const QString &detail, bool allowed, const QString &grant, bool changed)
+{
+ return {{QStringLiteral("token"), token},
+ {QStringLiteral("label"), label},
+ {QStringLiteral("detail"), detail},
+ {QStringLiteral("allowed"), allowed},
+ {QStringLiteral("grant"), grant},
+ {QStringLiteral("changed"), changed}};
+}
+
+const char *busGroup(const QString &token)
+{
+ return token == QLatin1String("system-bus") ? "System Bus Policy" : "Session Bus Policy";
+}
}
AppAccess::AppAccess(QObject *parent)
@@ -304,15 +488,21 @@ QVariantList AppAccess::apps(const QString &kind) const
return rows;
}
-void AppAccess::set(const QString &id, const QString &token, bool allowed)
+auto AppAccess::find(const QString &id) const -> const App *
{
auto it = std::find_if(m_apps.cbegin(), m_apps.cend(), [&id](const App &a) {
return a.id == id;
});
- if (it == m_apps.cend()) {
+ return it == m_apps.cend() ? nullptr : &*it;
+}
+
+void AppAccess::set(const QString &id, const QString &token, bool allowed, const QString &grant)
+{
+ const App *found = find(id);
+ if (!found) {
return;
}
- const App app = *it;
+ const App app = *found;
const QString path = overridePath(id);
QDir().mkpath(QFileInfo(path).absolutePath());
const QByteArray file = QFile::encodeName(path);
@@ -321,7 +511,8 @@ void AppAccess::set(const QString &id, const QString &token, bool allowed)
auto writeContext = [&](const QString &group, const QString &base) {
const QByteArray groupName = group.toUtf8();
- const bool byDefault = stateIn(keyList(meta, groupName.constData()), base) == 1;
+ const QStringList defaults = keyList(meta, groupName.constData());
+ const bool byDefault = stateIn(defaults, base) == 1;
QStringList entries = keyList(over, groupName.constData());
entries.erase(std::remove_if(entries.begin(), entries.end(), [&base](const QString &e) {
return baseOf(e) == base;
@@ -329,22 +520,56 @@ void AppAccess::set(const QString &id, const QString &token, bool allowed)
entries.end());
// Only differences from what the app asked for are written, the
// same way "flatpak override" and the Store do it.
- if (allowed != byDefault) {
- entries << (allowed ? base : QStringLiteral("!") + base);
+ const QString wanted = grant.isEmpty() ? base : grant;
+ if (allowed && !byDefault) {
+ entries << wanted;
+ } else if (allowed && !grant.isEmpty() && wanted != grantingEntry(defaults, base)) {
+ // The same folder with other access than the app asked for.
+ entries << wanted;
+ } else if (!allowed && byDefault) {
+ entries << QStringLiteral("!") + base;
+ } else if (!allowed && group == QLatin1String("filesystems") && !grant.isEmpty()) {
+ // A folder the app never asked for stays listed, turned off,
+ // instead of vanishing from the page the moment it is switched.
+ entries << QStringLiteral("!") + base;
}
- if (entries.isEmpty()) {
- g_key_file_remove_key(over, "Context", groupName.constData(), nullptr);
- } else {
- QList<QByteArray> raw;
- for (const QString &e : std::as_const(entries)) {
- raw << e.toUtf8();
+ setContextList(over, groupName.constData(), entries);
+ };
+
+ auto writeBus = [&](const char *group, const QString &name) {
+ const QString byDefault = entry(meta, group, name);
+ const bool defaultAllows = policyAllows(byDefault);
+ if (allowed) {
+ const QString wanted = !grant.isEmpty() ? grant : defaultAllows ? byDefault : QStringLiteral("talk");
+ if (defaultAllows && wanted == byDefault) {
+ removeEntry(over, group, name);
+ } else {
+ setEntry(over, group, name, wanted);
}
- QList<const char *> ptrs;
- for (const QByteArray &b : std::as_const(raw)) {
- ptrs << b.constData();
+ } else {
+ // "none" is what "flatpak override --no-talk-name" writes, and
+ // keeps a name the app never asked for listed as off.
+ setEntry(over, group, name, QStringLiteral("none"));
+ }
+ };
+
+ auto writeEnv = [&](const QString &name) {
+ QStringList unset = keyList(over, "unset-environment");
+ unset.removeAll(name);
+ const bool byDefault = hasEntry(meta, "Environment", name);
+ if (allowed) {
+ if (byDefault && grant == entry(meta, "Environment", name)) {
+ removeEntry(over, "Environment", name);
+ } else {
+ setEntry(over, "Environment", name, grant);
}
- g_key_file_set_string_list(over, "Context", groupName.constData(), ptrs.constData(), gsize(ptrs.size()));
+ } else {
+ // Both forms, as Flatpak writes them: older versions read an
+ // empty value as unset, newer ones read unset-environment.
+ setEntry(over, "Environment", name, QString());
+ unset << name;
}
+ setContextList(over, "unset-environment", unset);
};
if (token == QLatin1String("camera")) {
@@ -374,8 +599,18 @@ void AppAccess::set(const QString &id, const QString &token, bool allowed)
} else {
const QString group = token.section(QLatin1Char(':'), 0, 0);
const QString base = token.section(QLatin1Char(':'), 1);
- if (!group.isEmpty() && !base.isEmpty()) {
- writeContext(group, base);
+ const bool contextKey = group == QLatin1String("filesystems")
+ || std::any_of(contextKeys().cbegin(), contextKeys().cend(), [&group](const ContextKey &k) {
+ return group == QLatin1String(k.key);
+ });
+ if (!base.isEmpty()) {
+ if (group == QLatin1String("session-bus") || group == QLatin1String("system-bus")) {
+ writeBus(busGroup(group), base);
+ } else if (group == QLatin1String("env")) {
+ writeEnv(base);
+ } else if (contextKey) {
+ writeContext(group, base);
+ }
}
}
@@ -384,3 +619,175 @@ void AppAccess::set(const QString &id, const QString &token, bool allowed)
g_key_file_free(meta);
reload();
}
+
+QVariantList AppAccess::everyApp() const
+{
+ QVariantList rows;
+ for (const App &app : m_apps) {
+ rows << QVariantMap{{QStringLiteral("id"), app.id},
+ {QStringLiteral("name"), app.name},
+ {QStringLiteral("icon"), app.icon},
+ {QStringLiteral("changed"), QFileInfo::exists(overridePath(app.id))}};
+ }
+ return rows;
+}
+
+QVariantList AppAccess::details(const QString &id) const
+{
+ const App *app = find(id);
+ if (!app) {
+ return {};
+ }
+ GKeyFile *meta = load(app->metadata);
+ GKeyFile *over = loadFile(overridePath(id));
+ QVariantList sections;
+ auto section = [&sections](const QString &key, const QString &title, const QVariantList &items) {
+ sections << QVariantMap{{QStringLiteral("key"), key}, {QStringLiteral("title"), title}, {QStringLiteral("items"), items}};
+ };
+
+ {
+ const QStringList defaults = keyList(meta, "filesystems");
+ const QStringList user = keyList(over, "filesystems");
+ QStringList bases;
+ for (const QString &e : defaults + user) {
+ const QString base = baseOf(e);
+ // host-reset is Flatpak's marker for "forget the app's own
+ // folders", not a folder.
+ if (!base.isEmpty() && base != QLatin1String("host-reset") && !bases.contains(base)) {
+ bases << base;
+ }
+ }
+ QVariantList items;
+ for (const QString &base : std::as_const(bases)) {
+ const int def = stateIn(defaults, base);
+ const int mine = stateIn(user, base);
+ const bool allowed = mine >= 0 ? mine == 1 : def == 1;
+ QString grant = grantingEntry(user, base);
+ if (grant.isEmpty()) {
+ grant = grantingEntry(defaults, base);
+ }
+ if (grant.isEmpty()) {
+ grant = base;
+ }
+ const bool changed = mine >= 0 && (allowed != (def == 1) || grantingEntry(user, base) != grantingEntry(defaults, base));
+ items << item(QStringLiteral("filesystems:") + base, folderLabel(base), folderDetail(grant, allowed), allowed, grant, changed);
+ }
+ section(QStringLiteral("filesystems"), QStringLiteral("Files and folders"), items);
+ }
+
+ for (const ContextKey &key : contextKeys()) {
+ const QStringList defaults = keyList(meta, key.key);
+ const QStringList user = keyList(over, key.key);
+ QVariantList items;
+ for (const Choice &choice : key.choices) {
+ const QString value = QString::fromLatin1(choice.value);
+ const int def = stateIn(defaults, value);
+ const int mine = stateIn(user, value);
+ const bool allowed = mine >= 0 ? mine == 1 : def == 1;
+ items << item(QString::fromLatin1(key.key) + QLatin1Char(':') + value, QString::fromLatin1(choice.label), QString(), allowed, value,
+ mine >= 0 && allowed != (def == 1));
+ }
+ section(QString::fromLatin1(key.key), QString::fromLatin1(key.title), items);
+ }
+
+ for (const QString &bus : {QStringLiteral("session-bus"), QStringLiteral("system-bus")}) {
+ const char *group = busGroup(bus);
+ QStringList names = groupKeys(meta, group);
+ for (const QString &name : groupKeys(over, group)) {
+ if (!names.contains(name)) {
+ names << name;
+ }
+ }
+ QVariantList items;
+ for (const QString &name : std::as_const(names)) {
+ const QString def = entry(meta, group, name);
+ const QString mine = entry(over, group, name);
+ const QString effective = mine.isEmpty() ? def : mine;
+ const QString grant = policyAllows(mine) ? mine : policyAllows(def) ? def : QStringLiteral("talk");
+ items << item(bus + QLatin1Char(':') + name, name, policyDetail(effective), policyAllows(effective), grant, !mine.isEmpty() && mine != def);
+ }
+ section(bus, bus == QLatin1String("system-bus") ? QStringLiteral("System services") : QStringLiteral("Services in your session"), items);
+ }
+
+ {
+ const QStringList unset = keyList(over, "unset-environment");
+ QStringList names = groupKeys(meta, "Environment");
+ for (const QString &name : groupKeys(over, "Environment") + unset) {
+ if (!names.contains(name)) {
+ names << name;
+ }
+ }
+ QVariantList items;
+ for (const QString &name : std::as_const(names)) {
+ const bool byDefault = hasEntry(meta, "Environment", name);
+ const bool cleared = unset.contains(name);
+ const bool mine = hasEntry(over, "Environment", name) && !cleared;
+ const bool allowed = !cleared && (mine || byDefault);
+ const QString value = mine ? entry(over, "Environment", name) : entry(meta, "Environment", name);
+ const QString detail = !allowed ? QStringLiteral("Not set") : value.isEmpty() ? QStringLiteral("Set, but empty") : value;
+ items << item(QStringLiteral("env:") + name, name, detail, allowed, value,
+ cleared || (mine && (!byDefault || value != entry(meta, "Environment", name))));
+ }
+ section(QStringLiteral("env"), QStringLiteral("Environment variables"), items);
+ }
+
+ g_key_file_free(over);
+ g_key_file_free(meta);
+ return sections;
+}
+
+QString AppAccess::add(const QString &id, const QString &kind, const QString &value, const QString &extra)
+{
+ if (!find(id)) {
+ return QStringLiteral("That app is no longer installed.");
+ }
+ QString v = value.trimmed();
+ if (kind == QLatin1String("folder")) {
+ static const QStringList special = {QStringLiteral("home"), QStringLiteral("host"), QStringLiteral("host-os"), QStringLiteral("host-etc")};
+ if (v == QLatin1String("/")) {
+ v = QStringLiteral("host");
+ }
+ while (v.length() > 1 && v.endsWith(QLatin1Char('/'))) {
+ v.chop(1);
+ }
+ // A colon would be read as the access mode, and Flatpak refuses
+ // anything that is not a path or one of its own names.
+ if (v.contains(QLatin1Char(':')) || v.contains(QLatin1Char('\n')) || v.startsWith(QLatin1Char('!'))
+ || !(v.startsWith(QLatin1Char('/')) || v.startsWith(QLatin1String("~/")) || v.startsWith(QLatin1String("xdg-")) || special.contains(v))) {
+ return QStringLiteral("Type a folder such as ~/Projects or /media/backup.");
+ }
+ set(id, QStringLiteral("filesystems:") + v, true, extra == QLatin1String("ro") ? v + QStringLiteral(":ro") : v);
+ return {};
+ }
+ if (kind == QLatin1String("bus")) {
+ // flatpak_verify_dbus_name: two or more elements, with ".*" allowed
+ // at the end for every name below one.
+ static const QRegularExpression name(QStringLiteral("^[A-Za-z_-][A-Za-z0-9_-]*(\\.[A-Za-z_-][A-Za-z0-9_-]*)+(\\.\\*)?$"));
+ if (v.length() > 255 || !name.match(v).hasMatch()) {
+ return QStringLiteral("Type a service name such as org.freedesktop.Notifications.");
+ }
+ const QString policy = QStringList{QStringLiteral("see"), QStringLiteral("talk"), QStringLiteral("own")}.contains(extra) ? extra : QStringLiteral("talk");
+ set(id, QStringLiteral("session-bus:") + v, true, policy);
+ return {};
+ }
+ if (kind == QLatin1String("env")) {
+ static const QRegularExpression name(QStringLiteral("^[A-Za-z_][A-Za-z0-9_]*$"));
+ if (!name.match(v).hasMatch()) {
+ return QStringLiteral("A variable's name is letters, digits and underscores, such as GTK_THEME.");
+ }
+ if (extra.contains(QLatin1Char('\n'))) {
+ return QStringLiteral("The value has to fit on one line.");
+ }
+ set(id, QStringLiteral("env:") + v, true, extra);
+ return {};
+ }
+ return QStringLiteral("That can't be added.");
+}
+
+void AppAccess::reset(const QString &id)
+{
+ if (find(id)) {
+ QFile::remove(overridePath(id));
+ reload();
+ }
+}
diff --git a/packages/wildos-settings/src/appaccess.h b/packages/wildos-settings/src/appaccess.h
index 273ed7f..e1c1a75 100644
--- a/packages/wildos-settings/src/appaccess.h
+++ b/packages/wildos-settings/src/appaccess.h
@@ -15,6 +15,11 @@
// with the same tokens, so both always agree. Apps that ask through the
// desktop's camera or location prompts are remembered by the portal's
// permission store, and their switch changes that answer.
+//
+// "Everything an app can reach" lists the whole sandbox of one app, as
+// "flatpak info --show-permissions" would, and changes any of it through
+// the same override file: the same tokens and negations "flatpak override
+// --user" writes, so the command line, the Store and Settings all agree.
class AppAccess : public QObject
{
Q_OBJECT
@@ -34,9 +39,25 @@ public:
// { id, name, icon, allowed, token } and, for files, { ..., items:
// [{ token, label, allowed }] } with one item per folder asked for.
Q_INVOKABLE QVariantList apps(const QString &kind) const;
- Q_INVOKABLE void set(const QString &app, const QString &token, bool allowed);
+ // token is "<Context key>:<value>" (shared, sockets, devices, features,
+ // filesystems), "session-bus:<name>", "system-bus:<name>", "env:<NAME>",
+ // or camera and location. grant is what an allowed entry is written as
+ // when it differs from the app's own: a folder with its ":ro", a bus
+ // name's talk or own, a variable's value.
+ Q_INVOKABLE void set(const QString &app, const QString &token, bool allowed, const QString &grant = QString());
Q_INVOKABLE void reload();
+ // Every app from the Store: { id, name, icon, changed }.
+ Q_INVOKABLE QVariantList everyApp() const;
+ // One app's whole sandbox as sections { key, title, items: [{ token,
+ // label, detail, allowed, grant, changed }] }.
+ Q_INVOKABLE QVariantList details(const QString &app) const;
+ // Gives an app something it did not ask for. kind is folder, bus or env;
+ // returns why it was refused, or nothing.
+ Q_INVOKABLE QString add(const QString &app, const QString &kind, const QString &value, const QString &extra);
+ // Deletes the app's override file, so it gets exactly what it asked for.
+ Q_INVOKABLE void reset(const QString &app);
+
Q_SIGNALS:
void changed();
@@ -49,6 +70,7 @@ private:
};
QString overridePath(const QString &id) const;
+ const App *find(const QString &id) const;
int state(const App &app, const QString &group, const QString &base) const;
QVariantMap portal(const QString &table, const QString &id) const;
void setPortal(const QString &table, const QString &id, const QString &app, const QStringList &value);
diff --git a/packages/wildos-settings/src/appnotifications.cpp b/packages/wildos-settings/src/appnotifications.cpp
new file mode 100644
index 0000000..3f34f27
--- /dev/null
+++ b/packages/wildos-settings/src/appnotifications.cpp
@@ -0,0 +1,295 @@
+#include "appnotifications.h"
+
+#include <KApplicationTrader>
+#include <KConfig>
+#include <KConfigGroup>
+#include <KService>
+#include <KSharedConfig>
+
+#include <QCollator>
+#include <QDBusConnection>
+#include <QDBusMessage>
+#include <QDir>
+#include <QSet>
+#include <QStandardPaths>
+
+#include <algorithm>
+
+namespace
+{
+const QString soundAction = QStringLiteral("Sound");
+
+KConfigGroup applicationGroup(const KSharedConfigPtr &config, const QString &app)
+{
+ return config->group(QStringLiteral("Applications")).group(app);
+}
+
+// The app's own events file, as installed. KNotification reads it under
+// the user's file, which only holds what the user changed.
+QString eventsFile(const QString &notifyRc)
+{
+ const QString name = notifyRc + QStringLiteral(".notifyrc");
+ QString path = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("knotifications6/") + name);
+ if (path.isEmpty()) {
+ path = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("knotifications5/") + name);
+ }
+ return path;
+}
+
+KSharedConfigPtr userEvents(const QString &notifyRc)
+{
+ KSharedConfigPtr config = KSharedConfig::openConfig(notifyRc + QStringLiteral(".notifyrc"), KConfig::NoGlobals);
+ config->reparseConfiguration();
+ return config;
+}
+
+QStringList split(const QString &actions)
+{
+ return actions.split(QLatin1Char('|'), Qt::SkipEmptyParts);
+}
+
+QSet<QString> asSet(const QStringList &list)
+{
+ return QSet<QString>(list.cbegin(), list.cend());
+}
+
+struct Sound {
+ bool available = false;
+ bool on = false;
+};
+
+// Only events that play a sound out of the box count: an app's quiet
+// events stay quiet when its sound is turned on.
+Sound soundOf(const QString &notifyRc)
+{
+ Sound sound;
+ const QString path = eventsFile(notifyRc);
+ if (path.isEmpty()) {
+ return sound;
+ }
+ const KConfig defaults(path, KConfig::SimpleConfig);
+ const KSharedConfigPtr user = userEvents(notifyRc);
+ const QStringList groups = defaults.groupList();
+ for (const QString &name : groups) {
+ if (!name.startsWith(QLatin1String("Event/"))) {
+ continue;
+ }
+ const QString fallback = defaults.group(name).readEntry("Action");
+ if (!split(fallback).contains(soundAction)) {
+ continue;
+ }
+ sound.available = true;
+ const KConfigGroup mine = user->group(name);
+ const QString actions = mine.hasKey("Action") ? mine.readEntry("Action") : fallback;
+ if (split(actions).contains(soundAction)) {
+ sound.on = true;
+ }
+ }
+ return sound;
+}
+
+KService::Ptr appService(const QString &desktopEntry)
+{
+ if (desktopEntry.isEmpty()) {
+ return {};
+ }
+ KService::Ptr service = KService::serviceByDesktopName(desktopEntry);
+ if (!service || service->noDisplay() || service->name().isEmpty()) {
+ return {};
+ }
+ return service;
+}
+}
+
+AppNotifications::AppNotifications(QObject *parent)
+ : QObject(parent)
+{
+}
+
+// The same three sources kcm_notifications lists apps from, in its order,
+// so an app with an events file keeps its sound switch.
+void AppNotifications::reload()
+{
+ m_list.clear();
+ QSet<QString> seen;
+
+ const auto add = [this, &seen](const KService::Ptr &service, const QString &notifyRc) {
+ const QString id = service->desktopEntryName();
+ if (seen.contains(id)) {
+ return;
+ }
+ seen.insert(id);
+ m_list.append(App{id, service->name(), service->icon(), notifyRc});
+ };
+
+ QSet<QString> files;
+ const QStringList dirs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("knotifications6"), QStandardPaths::LocateDirectory)
+ + QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("knotifications5"), QStandardPaths::LocateDirectory);
+ for (const QString &dir : dirs) {
+ const QStringList names = QDir(dir).entryList({QStringLiteral("*.notifyrc")}, QDir::Files);
+ for (const QString &file : names) {
+ if (files.contains(file)) {
+ continue;
+ }
+ files.insert(file);
+ const KConfig events(dir + QLatin1Char('/') + file, KConfig::SimpleConfig);
+ const QString desktopEntry = events.group(QStringLiteral("Global")).readEntry("DesktopEntry");
+ // No desktop entry means a background service (the desktop's own
+ // parts), which Windows does not list either.
+ if (const KService::Ptr service = appService(desktopEntry)) {
+ add(service, file.section(QLatin1Char('.'), 0, -2));
+ }
+ }
+ }
+
+ const KService::List announced = KApplicationTrader::query([](const KService::Ptr &service) {
+ return !service->noDisplay() && service->property<bool>(QStringLiteral("X-GNOME-UsesNotifications"));
+ });
+ for (const KService::Ptr &service : announced) {
+ if (!service->name().isEmpty()) {
+ add(service, {});
+ }
+ }
+
+ // Apps the notification server has heard from.
+ KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("plasmanotifyrc"));
+ config->reparseConfiguration();
+ const QStringList known = config->group(QStringLiteral("Applications")).groupList();
+ for (const QString &desktopEntry : known) {
+ if (const KService::Ptr service = appService(desktopEntry)) {
+ add(service, {});
+ }
+ }
+
+ QCollator collator;
+ collator.setCaseSensitivity(Qt::CaseInsensitive);
+ collator.setNumericMode(true);
+ std::sort(m_list.begin(), m_list.end(), [&collator](const App &a, const App &b) {
+ return collator.compare(a.name, b.name) < 0;
+ });
+
+ publish();
+}
+
+void AppNotifications::publish()
+{
+ KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("plasmanotifyrc"));
+ config->reparseConfiguration();
+
+ m_apps.clear();
+ for (const App &app : std::as_const(m_list)) {
+ const KConfigGroup group = applicationGroup(config, app.id);
+ const bool banners = group.readEntry("ShowPopups", true);
+ const bool history = group.readEntry("ShowInHistory", true);
+ const Sound sound = app.notifyRc.isEmpty() ? Sound{} : soundOf(app.notifyRc);
+ m_apps.append(QVariantMap{
+ {QStringLiteral("id"), app.id},
+ {QStringLiteral("name"), app.name},
+ {QStringLiteral("icon"), app.icon},
+ {QStringLiteral("enabled"), banners || history},
+ {QStringLiteral("banners"), banners},
+ {QStringLiteral("history"), history},
+ {QStringLiteral("hasSound"), sound.available},
+ {QStringLiteral("sound"), sound.on},
+ });
+ }
+ Q_EMIT appsChanged();
+}
+
+QString AppNotifications::notifyRcFor(const QString &app) const
+{
+ for (const App &entry : m_list) {
+ if (entry.id == app) {
+ return entry.notifyRc;
+ }
+ }
+ return {};
+}
+
+// As NotificationManager::Settings writes them: a value that matches the
+// default is removed rather than written, and every write carries Notify
+// so plasmashell's config watcher applies it straight away.
+void AppNotifications::writeBehaviour(const QString &app, const QString &key, bool on)
+{
+ KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("plasmanotifyrc"));
+ KConfigGroup group = applicationGroup(config, app);
+ if (on && !group.hasDefault(key)) {
+ group.revertToDefault(key, KConfig::Notify);
+ } else {
+ group.writeEntry(key, on, KConfig::Notify);
+ }
+ config->sync();
+}
+
+void AppNotifications::writeSound(const QString &notifyRc, bool on)
+{
+ const QString path = eventsFile(notifyRc);
+ if (path.isEmpty()) {
+ return;
+ }
+ const KConfig defaults(path, KConfig::SimpleConfig);
+ KSharedConfigPtr user = userEvents(notifyRc);
+ const QStringList groups = defaults.groupList();
+ for (const QString &name : groups) {
+ if (!name.startsWith(QLatin1String("Event/"))) {
+ continue;
+ }
+ const QString fallback = defaults.group(name).readEntry("Action");
+ if (!split(fallback).contains(soundAction)) {
+ continue;
+ }
+ KConfigGroup mine = user->group(name);
+ QStringList actions = split(mine.hasKey("Action") ? mine.readEntry("Action") : fallback);
+ actions.removeAll(soundAction);
+ if (on) {
+ actions.append(soundAction);
+ }
+ // Back to exactly what the app ships means no override at all, so a
+ // later update to the app's own events still reaches the user.
+ if (asSet(actions) == asSet(split(fallback))) {
+ mine.deleteEntry("Action");
+ } else {
+ mine.writeEntry("Action", actions.join(QLatin1Char('|')));
+ }
+ }
+ user->sync();
+
+ // What kcm_notifications sends after saving: every running app with
+ // these events rereads them.
+ QDBusMessage message = QDBusMessage::createSignal(QStringLiteral("/Config"), QStringLiteral("org.kde.knotification"), QStringLiteral("reparseConfiguration"));
+ message.setArguments({notifyRc});
+ QDBusConnection::sessionBus().send(message);
+}
+
+void AppNotifications::setEnabled(const QString &app, bool on)
+{
+ writeBehaviour(app, QStringLiteral("ShowPopups"), on);
+ writeBehaviour(app, QStringLiteral("ShowInHistory"), on);
+ writeBehaviour(app, QStringLiteral("ShowBadges"), on);
+ const QString notifyRc = notifyRcFor(app);
+ if (!notifyRc.isEmpty()) {
+ writeSound(notifyRc, on);
+ }
+ publish();
+}
+
+void AppNotifications::setBanners(const QString &app, bool on)
+{
+ writeBehaviour(app, QStringLiteral("ShowPopups"), on);
+ publish();
+}
+
+void AppNotifications::setHistory(const QString &app, bool on)
+{
+ writeBehaviour(app, QStringLiteral("ShowInHistory"), on);
+ publish();
+}
+
+void AppNotifications::setSound(const QString &app, bool on)
+{
+ const QString notifyRc = notifyRcFor(app);
+ if (!notifyRc.isEmpty()) {
+ writeSound(notifyRc, on);
+ }
+ publish();
+}
diff --git a/packages/wildos-settings/src/appnotifications.h b/packages/wildos-settings/src/appnotifications.h
new file mode 100644
index 0000000..04b491f
--- /dev/null
+++ b/packages/wildos-settings/src/appnotifications.h
@@ -0,0 +1,62 @@
+#pragma once
+
+#include <QObject>
+#include <QQmlEngine>
+#include <QVariantList>
+
+// Notifications from apps, after Windows 11: every app that can notify,
+// sorted by name, with whether it may notify at all and, per app, banners,
+// sound and the notification list.
+//
+// The apps are the ones KDE's notification settings list (an app with a
+// KNotification events file, a desktop file that says it uses
+// notifications, or an app the notification server has seen), less
+// services that are not apps. Banners and the list are the notification
+// server's per-app settings in plasmanotifyrc, [Applications][<desktop
+// entry>] ShowPopups and ShowInHistory, written the way
+// NotificationManager::Settings writes them so plasmashell picks them up
+// at once. Sound exists only for apps with an events file: it is the Sound
+// action of each of the app's events in ~/.config/<app>.notifyrc, which
+// KNotification rereads when told to. Apps that send plain freedesktop
+// notifications play their own sounds, if any, so they get no sound switch.
+class AppNotifications : public QObject
+{
+ Q_OBJECT
+ QML_ELEMENT
+ QML_SINGLETON
+
+ Q_PROPERTY(QVariantList apps READ apps NOTIFY appsChanged)
+
+public:
+ explicit AppNotifications(QObject *parent = nullptr);
+
+ QVariantList apps() const { return m_apps; }
+
+ Q_INVOKABLE void reload();
+ // Off turns off banners, the list, badges and sound together; on turns
+ // them all back to their defaults.
+ Q_INVOKABLE void setEnabled(const QString &app, bool on);
+ Q_INVOKABLE void setBanners(const QString &app, bool on);
+ Q_INVOKABLE void setHistory(const QString &app, bool on);
+ Q_INVOKABLE void setSound(const QString &app, bool on);
+
+Q_SIGNALS:
+ void appsChanged();
+
+private:
+ struct App {
+ QString id;
+ QString name;
+ QString icon;
+ // The events file's name without .notifyrc, for apps that have one.
+ QString notifyRc;
+ };
+
+ QString notifyRcFor(const QString &app) const;
+ void writeBehaviour(const QString &app, const QString &key, bool on);
+ void writeSound(const QString &notifyRc, bool on);
+ void publish();
+
+ QList<App> m_list;
+ QVariantList m_apps;
+};
diff --git a/packages/wildos-settings/src/autoplay.cpp b/packages/wildos-settings/src/autoplay.cpp
new file mode 100644
index 0000000..0332558
--- /dev/null
+++ b/packages/wildos-settings/src/autoplay.cpp
@@ -0,0 +1,128 @@
+#include "autoplay.h"
+
+#include <KConfigGroup>
+#include <KSharedConfig>
+
+#include <QCollator>
+#include <QDBusConnection>
+#include <QDBusMessage>
+
+#include <algorithm>
+
+namespace
+{
+const QString configFile = QStringLiteral("kded_device_automounterrc");
+const QString module = QStringLiteral("device_automounter");
+
+KSharedConfigPtr config()
+{
+ return KSharedConfig::openConfig(configFile, KConfig::NoGlobals);
+}
+
+void callKded(const QString &method, const QVariantList &arguments)
+{
+ auto message = QDBusMessage::createMethodCall(QStringLiteral("org.kde.kded6"), QStringLiteral("/kded"), QStringLiteral("org.kde.kded6"), method);
+ message.setArguments(arguments);
+ QDBusConnection::sessionBus().call(message, QDBus::NoBlock);
+}
+}
+
+AutoPlay::AutoPlay(QObject *parent)
+ : QObject(parent)
+{
+ reload();
+}
+
+void AutoPlay::reload()
+{
+ KSharedConfigPtr cfg = config();
+ // The automounter writes here as drives come and go.
+ cfg->reparseConfiguration();
+ const KConfigGroup general(cfg, QStringLiteral("General"));
+ m_onPlugin = general.readEntry("AutomountOnPlugin", false);
+ m_onLogin = general.readEntry("AutomountOnLogin", false);
+ m_unknownDevices = general.readEntry("AutomountUnknownDevices", false);
+
+ m_drives.clear();
+ const KConfigGroup devices(cfg, QStringLiteral("Devices"));
+ const QStringList udis = devices.groupList();
+ for (const QString &udi : udis) {
+ const KConfigGroup device = devices.group(udi);
+ QString name = device.readEntry("LastNameSeen", QString());
+ if (name.isEmpty()) {
+ name = udi.section(QLatin1Char('/'), -1);
+ }
+ const bool always = device.readEntry("ForceAttachAutomount", false) || device.readEntry("ForceLoginAutomount", false);
+ m_drives.append(QVariantMap{{QStringLiteral("udi"), udi}, {QStringLiteral("name"), name}, {QStringLiteral("always"), always}});
+ }
+ QCollator collator;
+ collator.setNumericMode(true);
+ std::sort(m_drives.begin(), m_drives.end(), [&collator](const QVariant &a, const QVariant &b) {
+ return collator.compare(a.toMap().value(QStringLiteral("name")).toString(), b.toMap().value(QStringLiteral("name")).toString()) < 0;
+ });
+ Q_EMIT changed();
+}
+
+void AutoPlay::save()
+{
+ KSharedConfigPtr cfg = config();
+ KConfigGroup general(cfg, QStringLiteral("General"));
+ general.writeEntry("AutomountOnPlugin", m_onPlugin);
+ general.writeEntry("AutomountOnLogin", m_onLogin);
+ general.writeEntry("AutomountUnknownDevices", m_unknownDevices);
+
+ // The automounter unloads itself at start when AutomountEnabled is
+ // false, so it is on whenever anything at all should be mounted,
+ // worked out the way KDE's module does.
+ bool enabled = m_onPlugin || m_onLogin;
+ const KConfigGroup devices(cfg, QStringLiteral("Devices"));
+ const QStringList udis = devices.groupList();
+ for (const QString &udi : udis) {
+ const KConfigGroup device = devices.group(udi);
+ enabled = enabled || device.readEntry("ForceAttachAutomount", false) || device.readEntry("ForceLoginAutomount", false);
+ }
+ general.writeEntry("AutomountEnabled", enabled);
+ cfg->sync();
+
+ callKded(QStringLiteral("setModuleAutoloading"), {module, enabled});
+ callKded(enabled ? QStringLiteral("loadModule") : QStringLiteral("unloadModule"), {module});
+ reload();
+}
+
+void AutoPlay::setOnPlugin(bool on)
+{
+ m_onPlugin = on;
+ save();
+}
+
+void AutoPlay::setOnLogin(bool on)
+{
+ m_onLogin = on;
+ save();
+}
+
+void AutoPlay::setUnknownDevices(bool on)
+{
+ m_unknownDevices = on;
+ save();
+}
+
+void AutoPlay::setAlways(const QString &udi, bool always)
+{
+ KConfigGroup device = KConfigGroup(config(), QStringLiteral("Devices")).group(udi);
+ if (!device.exists()) {
+ return;
+ }
+ device.writeEntry("ForceAttachAutomount", always);
+ device.writeEntry("ForceLoginAutomount", always);
+ save();
+}
+
+void AutoPlay::forget(const QString &udi)
+{
+ KConfigGroup device = KConfigGroup(config(), QStringLiteral("Devices")).group(udi);
+ if (device.exists()) {
+ device.deleteGroup();
+ }
+ save();
+}
diff --git a/packages/wildos-settings/src/autoplay.h b/packages/wildos-settings/src/autoplay.h
new file mode 100644
index 0000000..02410ea
--- /dev/null
+++ b/packages/wildos-settings/src/autoplay.h
@@ -0,0 +1,51 @@
+#pragma once
+
+#include <QObject>
+#include <QQmlEngine>
+#include <QVariantList>
+
+// AutoPlay, as Plasma's device automounter does it: whether drives and
+// memory cards are mounted, ready in Files, when they are plugged in or
+// already there at sign-in, and which drives always are. The settings live
+// in kded_device_automounterrc, read by the device_automounter module of
+// kded, which is loaded or unloaded to match, as KDE's own module does.
+class AutoPlay : public QObject
+{
+ Q_OBJECT
+ QML_ELEMENT
+ QML_SINGLETON
+
+ Q_PROPERTY(bool onPlugin READ onPlugin NOTIFY changed)
+ Q_PROPERTY(bool onLogin READ onLogin NOTIFY changed)
+ Q_PROPERTY(bool unknownDevices READ unknownDevices NOTIFY changed)
+ Q_PROPERTY(QVariantList drives READ drives NOTIFY changed)
+
+public:
+ explicit AutoPlay(QObject *parent = nullptr);
+
+ bool onPlugin() const { return m_onPlugin; }
+ bool onLogin() const { return m_onLogin; }
+ bool unknownDevices() const { return m_unknownDevices; }
+ // Drives the automounter has seen, as { udi, name, always }.
+ QVariantList drives() const { return m_drives; }
+
+ Q_INVOKABLE void reload();
+ Q_INVOKABLE void setOnPlugin(bool on);
+ Q_INVOKABLE void setOnLogin(bool on);
+ Q_INVOKABLE void setUnknownDevices(bool on);
+ // Mount this drive whenever it is plugged in or there at sign-in,
+ // whatever the general settings say.
+ Q_INVOKABLE void setAlways(const QString &udi, bool always);
+ Q_INVOKABLE void forget(const QString &udi);
+
+Q_SIGNALS:
+ void changed();
+
+private:
+ void save();
+
+ bool m_onPlugin = false;
+ bool m_onLogin = false;
+ bool m_unknownDevices = false;
+ QVariantList m_drives;
+};
diff --git a/packages/wildos-settings/src/autotheme/main.cpp b/packages/wildos-settings/src/autotheme/main.cpp
index 024a99e..2d43649 100644
--- a/packages/wildos-settings/src/autotheme/main.cpp
+++ b/packages/wildos-settings/src/autotheme/main.cpp
@@ -22,6 +22,7 @@ namespace
{
const QString darkScheme = QStringLiteral("WildOS");
const QString lightScheme = QStringLiteral("WildOSLight");
+const QString contrastScheme = QStringLiteral("WildOSHighContrast");
const QString decorationGroup = QStringLiteral("org.kde.kdecoration2");
const QString darkDecoration = QStringLiteral("__aurorae__svg__WildOS");
@@ -107,6 +108,12 @@ public:
}
KSharedConfigPtr globals = KSharedConfig::openConfig(QStringLiteral("kdeglobals"));
globals->reparseConfiguration();
+ // High contrast (Settings > Accessibility) is not a time of day
+ // choice; it stays until it is turned off, which brings the
+ // automatic theme back.
+ if (globals->group(QStringLiteral("General")).readEntry("ColorScheme") == contrastScheme) {
+ return;
+ }
if (schemeIsLight(globals) == (wanted == lightScheme)) {
return;
}
diff --git a/packages/wildos-settings/src/defaultapps.cpp b/packages/wildos-settings/src/defaultapps.cpp
index fffc70d..221ad41 100644
--- a/packages/wildos-settings/src/defaultapps.cpp
+++ b/packages/wildos-settings/src/defaultapps.cpp
@@ -6,10 +6,13 @@
#include <KSharedConfig>
#include <QCollator>
+#include <QMimeDatabase>
#include <QProcess>
#include <QSet>
#include <QStandardPaths>
+#include <algorithm>
+
namespace
{
struct Category {
@@ -52,6 +55,47 @@ const QList<Category> &categoryList()
return list;
}
+QVariantList appsFor(const QString &mime, const QString &desktopCategory = QString())
+{
+ QCollator collator;
+ collator.setCaseSensitivity(Qt::CaseInsensitive);
+ QVariantList apps;
+ QSet<QString> seen;
+ const KService::List services = KApplicationTrader::queryByMimeType(mime);
+ for (const KService::Ptr &service : services) {
+ if (service->noDisplay() || seen.contains(service->storageId())) {
+ continue;
+ }
+ if (!desktopCategory.isEmpty() && !service->categories().contains(desktopCategory)) {
+ continue;
+ }
+ seen.insert(service->storageId());
+ apps << QVariantMap{{QStringLiteral("value"), service->storageId()}, {QStringLiteral("text"), service->name()}};
+ }
+ std::sort(apps.begin(), apps.end(), [&collator](const QVariant &a, const QVariant &b) {
+ return collator.compare(a.toMap().value(QStringLiteral("text")).toString(), b.toMap().value(QStringLiteral("text")).toString()) < 0;
+ });
+ return apps;
+}
+
+// The account's own mimeapps.list, which outranks the system one. The
+// app also goes first under Added Associations, as Dolphin's "Open with"
+// does, so it stays offered for each type.
+void writeDefault(const QStringList &types, const QString &storageId)
+{
+ KSharedConfig::Ptr config = KSharedConfig::openConfig(QStringLiteral("mimeapps.list"), KConfig::NoGlobals, QStandardPaths::GenericConfigLocation);
+ KConfigGroup defaults = config->group(QStringLiteral("Default Applications"));
+ KConfigGroup added = config->group(QStringLiteral("Added Associations"));
+ for (const QString &mime : types) {
+ defaults.writeXdgListEntry(mime, {storageId});
+ QStringList associated = added.readXdgListEntry(mime);
+ associated.removeAll(storageId);
+ associated.prepend(storageId);
+ added.writeXdgListEntry(mime, associated);
+ }
+ config->sync();
+}
+
const Category *findCategory(const QString &id)
{
for (const Category &c : categoryList()) {
@@ -71,27 +115,10 @@ DefaultApps::DefaultApps(QObject *parent)
void DefaultApps::reload()
{
- QCollator collator;
- collator.setCaseSensitivity(Qt::CaseInsensitive);
QVariantList list;
for (const Category &c : categoryList()) {
const QString mime = c.types.constFirst();
- QVariantList apps;
- QSet<QString> seen;
- const KService::List services = KApplicationTrader::queryByMimeType(mime);
- for (const KService::Ptr &service : services) {
- if (service->noDisplay() || seen.contains(service->storageId())) {
- continue;
- }
- if (!c.desktopCategory.isEmpty() && !service->categories().contains(c.desktopCategory)) {
- continue;
- }
- seen.insert(service->storageId());
- apps << QVariantMap{{QStringLiteral("value"), service->storageId()}, {QStringLiteral("text"), service->name()}};
- }
- std::sort(apps.begin(), apps.end(), [&collator](const QVariant &a, const QVariant &b) {
- return collator.compare(a.toMap().value(QStringLiteral("text")).toString(), b.toMap().value(QStringLiteral("text")).toString()) < 0;
- });
+ const QVariantList apps = appsFor(mime, c.desktopCategory);
const KService::Ptr preferred = KApplicationTrader::preferredService(mime);
list << QVariantMap{
{QStringLiteral("id"), QString::fromLatin1(c.id)},
@@ -114,20 +141,7 @@ void DefaultApps::setDefault(const QString &categoryId, const QString &storageId
return;
}
- // The account's own mimeapps.list, which outranks the system one. The
- // app also goes first under Added Associations, as Dolphin's "Open
- // with" does, so it stays offered for each type.
- KSharedConfig::Ptr config = KSharedConfig::openConfig(QStringLiteral("mimeapps.list"), KConfig::NoGlobals, QStandardPaths::GenericConfigLocation);
- KConfigGroup defaults = config->group(QStringLiteral("Default Applications"));
- KConfigGroup added = config->group(QStringLiteral("Added Associations"));
- for (const QString &mime : category->types) {
- defaults.writeXdgListEntry(mime, {storageId});
- QStringList associated = added.readXdgListEntry(mime);
- associated.removeAll(storageId);
- associated.prepend(storageId);
- added.writeXdgListEntry(mime, associated);
- }
- config->sync();
+ writeDefault(category->types, storageId);
// KDE apps open web links through the browser named here, and email
// through the one named in emaildefaults.
@@ -143,6 +157,11 @@ void DefaultApps::setDefault(const QString &categoryId, const QString &storageId
email->sync();
}
+ rebuild();
+}
+
+void DefaultApps::rebuild()
+{
// The service database caches associations; rebuilding it makes the
// new default count everywhere straight away.
auto process = new QProcess(this);
@@ -152,3 +171,83 @@ void DefaultApps::setDefault(const QString &categoryId, const QString &storageId
});
process->start(QStringLiteral("kbuildsycoca6"), {});
}
+
+QVariantList DefaultApps::fileTypes(const QString &search) const
+{
+ QString query = search.trimmed().toLower();
+ const bool extensionOnly = query.startsWith(QLatin1Char('.'));
+ if (extensionOnly) {
+ query.remove(0, 1);
+ }
+ if (query.isEmpty()) {
+ return {};
+ }
+
+ struct Match {
+ QMimeType type;
+ int rank;
+ };
+ QList<Match> matches;
+ const QList<QMimeType> all = QMimeDatabase().allMimeTypes();
+ for (const QMimeType &type : all) {
+ // Only types a file can have by its name; the rest are not what
+ // anyone looks for by file type.
+ const QStringList suffixes = type.suffixes();
+ if (suffixes.isEmpty()) {
+ continue;
+ }
+ int rank = -1;
+ if (suffixes.contains(query, Qt::CaseInsensitive)) {
+ rank = 0;
+ } else if (std::any_of(suffixes.cbegin(), suffixes.cend(), [&query](const QString &s) {
+ return s.startsWith(query, Qt::CaseInsensitive);
+ })) {
+ rank = 1;
+ } else if (!extensionOnly && query.size() >= 3 && type.comment().contains(query, Qt::CaseInsensitive)) {
+ rank = 2;
+ }
+ if (rank >= 0) {
+ matches << Match{type, rank};
+ }
+ }
+ QCollator collator;
+ collator.setCaseSensitivity(Qt::CaseInsensitive);
+ std::sort(matches.begin(), matches.end(), [&collator](const Match &a, const Match &b) {
+ if (a.rank != b.rank) {
+ return a.rank < b.rank;
+ }
+ return collator.compare(a.type.suffixes().constFirst(), b.type.suffixes().constFirst()) < 0;
+ });
+
+ // A search as short as one letter matches hundreds of types; the
+ // first few are enough to narrow it down.
+ QVariantList list;
+ for (const Match &match : std::as_const(matches)) {
+ if (list.size() >= 40) {
+ break;
+ }
+ QStringList extensions;
+ for (const QString &suffix : match.type.suffixes()) {
+ extensions << QStringLiteral(".") + suffix;
+ }
+ const KService::Ptr preferred = KApplicationTrader::preferredService(match.type.name());
+ list << QVariantMap{
+ {QStringLiteral("mime"), match.type.name()},
+ {QStringLiteral("description"), match.type.comment()},
+ {QStringLiteral("extensions"), extensions.join(QStringLiteral(", "))},
+ {QStringLiteral("icon"), match.type.iconName()},
+ {QStringLiteral("current"), preferred ? preferred->storageId() : QString()},
+ {QStringLiteral("apps"), appsFor(match.type.name())},
+ };
+ }
+ return list;
+}
+
+void DefaultApps::setDefaultForType(const QString &mime, const QString &storageId)
+{
+ if (!QMimeDatabase().mimeTypeForName(mime).isValid() || !KService::serviceByStorageId(storageId)) {
+ return;
+ }
+ writeDefault({mime}, storageId);
+ rebuild();
+}
diff --git a/packages/wildos-settings/src/defaultapps.h b/packages/wildos-settings/src/defaultapps.h
index e8c3de9..d1d3271 100644
--- a/packages/wildos-settings/src/defaultapps.h
+++ b/packages/wildos-settings/src/defaultapps.h
@@ -24,9 +24,17 @@ public:
Q_INVOKABLE void reload();
Q_INVOKABLE void setDefault(const QString &category, const QString &storageId);
+ // File types whose extension or name matches the search, after
+ // Windows' "Choose defaults by file type": [{ mime, description,
+ // extensions, icon, current, apps: [{ value, text }] }].
+ Q_INVOKABLE QVariantList fileTypes(const QString &search) const;
+ Q_INVOKABLE void setDefaultForType(const QString &mime, const QString &storageId);
+
Q_SIGNALS:
void changed();
private:
+ void rebuild();
+
QVariantList m_categories;
};
diff --git a/packages/wildos-settings/src/desktops.cpp b/packages/wildos-settings/src/desktops.cpp
new file mode 100644
index 0000000..e65a77a
--- /dev/null
+++ b/packages/wildos-settings/src/desktops.cpp
@@ -0,0 +1,125 @@
+#include "desktops.h"
+
+#include <QDBusArgument>
+#include <QDBusConnection>
+#include <QDBusMessage>
+#include <QDBusPendingCallWatcher>
+#include <QDBusPendingReply>
+#include <QDBusVariant>
+#include <QVariantMap>
+
+#include <algorithm>
+
+namespace
+{
+const QString service = QStringLiteral("org.kde.KWin");
+const QString path = QStringLiteral("/VirtualDesktopManager");
+const QString interface = QStringLiteral("org.kde.KWin.VirtualDesktopManager");
+const QString properties = QStringLiteral("org.freedesktop.DBus.Properties");
+}
+
+Desktops::Desktops(QObject *parent)
+ : QObject(parent)
+{
+ QDBusConnection bus = QDBusConnection::sessionBus();
+ for (const char *name : {"countChanged", "currentChanged", "desktopsChanged", "desktopCreated", "desktopRemoved", "desktopDataChanged"}) {
+ bus.connect(service, path, interface, QString::fromLatin1(name), this, SLOT(reload()));
+ }
+ reload();
+}
+
+void Desktops::reload()
+{
+ auto message = QDBusMessage::createMethodCall(service, path, properties, QStringLiteral("GetAll"));
+ message << interface;
+ auto watcher = new QDBusPendingCallWatcher(QDBusConnection::sessionBus().asyncCall(message), this);
+ connect(watcher, &QDBusPendingCallWatcher::finished, this, [this, watcher] {
+ watcher->deleteLater();
+ QDBusPendingReply<QVariantMap> reply = *watcher;
+ if (reply.isError()) {
+ m_available = false;
+ m_desktops.clear();
+ m_current.clear();
+ Q_EMIT changed();
+ return;
+ }
+ const QVariantMap values = reply.value();
+
+ // desktops is a(uss), KWin's DBusDesktopDataVector: position, id, name.
+ QVariantList list;
+ const QDBusArgument argument = values.value(QStringLiteral("desktops")).value<QDBusArgument>();
+ argument.beginArray();
+ while (!argument.atEnd()) {
+ uint position = 0;
+ QString id;
+ QString name;
+ argument.beginStructure();
+ argument >> position >> id >> name;
+ argument.endStructure();
+ list.append(QVariantMap{
+ {QStringLiteral("id"), id},
+ {QStringLiteral("name"), name},
+ {QStringLiteral("position"), position},
+ });
+ }
+ argument.endArray();
+ std::sort(list.begin(), list.end(), [](const QVariant &a, const QVariant &b) {
+ return a.toMap().value(QStringLiteral("position")).toUInt() < b.toMap().value(QStringLiteral("position")).toUInt();
+ });
+
+ m_available = true;
+ m_desktops = list;
+ m_current = values.value(QStringLiteral("current")).toString();
+ Q_EMIT changed();
+ });
+}
+
+void Desktops::call(const QString &method, const QVariantList &arguments)
+{
+ auto message = QDBusMessage::createMethodCall(service, path, interface, method);
+ message.setArguments(arguments);
+ auto watcher = new QDBusPendingCallWatcher(QDBusConnection::sessionBus().asyncCall(message), this);
+ connect(watcher, &QDBusPendingCallWatcher::finished, this, [this, watcher] {
+ watcher->deleteLater();
+ reload();
+ });
+}
+
+// At the end, with no name, so KWin gives it its own "Desktop N" in the
+// session's language.
+void Desktops::add()
+{
+ if (m_desktops.size() >= maximum()) {
+ return;
+ }
+ call(QStringLiteral("createDesktop"), {QVariant::fromValue(uint(m_desktops.size())), QString()});
+}
+
+void Desktops::rename(const QString &id, const QString &name)
+{
+ const QString trimmed = name.simplified();
+ if (trimmed.isEmpty()) {
+ return;
+ }
+ call(QStringLiteral("setDesktopName"), {id, trimmed});
+}
+
+// KWin moves the desktop's windows to the one next to it, as Windows does.
+void Desktops::remove(const QString &id)
+{
+ if (m_desktops.size() <= 1) {
+ return;
+ }
+ call(QStringLiteral("removeDesktop"), {id});
+}
+
+void Desktops::switchTo(const QString &id)
+{
+ auto message = QDBusMessage::createMethodCall(service, path, properties, QStringLiteral("Set"));
+ message << interface << QStringLiteral("current") << QVariant::fromValue(QDBusVariant(id));
+ auto watcher = new QDBusPendingCallWatcher(QDBusConnection::sessionBus().asyncCall(message), this);
+ connect(watcher, &QDBusPendingCallWatcher::finished, this, [this, watcher] {
+ watcher->deleteLater();
+ reload();
+ });
+}
diff --git a/packages/wildos-settings/src/desktops.h b/packages/wildos-settings/src/desktops.h
new file mode 100644
index 0000000..9e90d71
--- /dev/null
+++ b/packages/wildos-settings/src/desktops.h
@@ -0,0 +1,50 @@
+#pragma once
+
+#include <QObject>
+#include <QQmlEngine>
+#include <QVariantList>
+
+// Virtual desktops, through KWin's org.kde.KWin.VirtualDesktopManager on
+// /VirtualDesktopManager, the interface kcm_kwin_virtualdesktops and the
+// pager use. KWin saves every change to kwinrc [Desktops] itself, and its
+// signals keep this list current when desktops change elsewhere (Task
+// View, a shortcut, another app).
+class Desktops : public QObject
+{
+ Q_OBJECT
+ QML_ELEMENT
+ QML_SINGLETON
+
+ Q_PROPERTY(bool available READ available NOTIFY changed)
+ // { id, name, position } in order, position counting from 0.
+ Q_PROPERTY(QVariantList desktops READ desktops NOTIFY changed)
+ Q_PROPERTY(QString current READ current NOTIFY changed)
+ // KWin's own limit (VirtualDesktopManager::maximum()).
+ Q_PROPERTY(int maximum READ maximum CONSTANT)
+
+public:
+ explicit Desktops(QObject *parent = nullptr);
+
+ bool available() const { return m_available; }
+ QVariantList desktops() const { return m_desktops; }
+ QString current() const { return m_current; }
+ int maximum() const { return 20; }
+
+ Q_INVOKABLE void add();
+ Q_INVOKABLE void rename(const QString &id, const QString &name);
+ Q_INVOKABLE void remove(const QString &id);
+ Q_INVOKABLE void switchTo(const QString &id);
+
+Q_SIGNALS:
+ void changed();
+
+private Q_SLOTS:
+ void reload();
+
+private:
+ void call(const QString &method, const QVariantList &arguments);
+
+ bool m_available = false;
+ QVariantList m_desktops;
+ QString m_current;
+};
diff --git a/packages/wildos-settings/src/display.cpp b/packages/wildos-settings/src/display.cpp
new file mode 100644
index 0000000..c38fb73
--- /dev/null
+++ b/packages/wildos-settings/src/display.cpp
@@ -0,0 +1,828 @@
+#include "display.h"
+
+#include <kscreen/config.h>
+#include <kscreen/configmonitor.h>
+#include <kscreen/getconfigoperation.h>
+#include <kscreen/mode.h>
+#include <kscreen/output.h>
+#include <kscreen/setconfigoperation.h>
+
+#include <QRect>
+#include <QSizeF>
+
+#include <algorithm>
+#include <climits>
+#include <cmath>
+#include <functional>
+#include <optional>
+
+using namespace KScreen;
+
+namespace
+{
+// Windows gives a new resolution 15 seconds before it switches back.
+constexpr int previewSeconds = 15;
+
+// KScreen treats rates this close as the same, so 59.94 and 60 Hz are one
+// choice.
+bool sameRate(float a, float b)
+{
+ return std::abs(a - b) < 0.5f;
+}
+
+QString sizeKey(const QSize &size)
+{
+ return QStringLiteral("%1x%2").arg(size.width()).arg(size.height());
+}
+
+QString rateKey(float rate)
+{
+ return QString::number(double(rate), 'f', 3);
+}
+
+bool isBuiltIn(const OutputPtr &output)
+{
+ return output->type() == Output::Panel;
+}
+
+// Largest first, as Windows and kcm_kscreen list them.
+QList<QSize> resolutions(const OutputPtr &output)
+{
+ QList<QSize> sizes;
+ const auto modes = output->modes();
+ for (const ModePtr &mode : modes) {
+ if (!sizes.contains(mode->size())) {
+ sizes << mode->size();
+ }
+ }
+ std::sort(sizes.begin(), sizes.end(), [](const QSize &a, const QSize &b) {
+ return a.width() > b.width() || (a.width() == b.width() && a.height() > b.height());
+ });
+ return sizes;
+}
+
+QList<float> refreshRates(const OutputPtr &output)
+{
+ QList<float> rates;
+ const ModePtr base = output->currentMode() ? output->currentMode() : output->preferredMode();
+ if (!base) {
+ return rates;
+ }
+ const auto modes = output->modes();
+ for (const ModePtr &mode : modes) {
+ if (mode->size() != base->size()) {
+ continue;
+ }
+ const float rate = mode->refreshRate();
+ if (std::none_of(rates.cbegin(), rates.cend(), [rate](float r) {
+ return sameRate(r, rate);
+ })) {
+ rates << rate;
+ }
+ }
+ std::sort(rates.begin(), rates.end(), std::greater<>());
+ return rates;
+}
+
+// The mode at `size` closest to `rate`, or the fastest one at that size when
+// it cannot keep the rate (kcm_kscreen's setResolution).
+ModePtr modeFor(const OutputPtr &output, const QSize &size, float rate)
+{
+ ModePtr fastest;
+ const auto modes = output->modes();
+ for (const ModePtr &mode : modes) {
+ if (mode->size() != size) {
+ continue;
+ }
+ if (sameRate(mode->refreshRate(), rate)) {
+ return mode;
+ }
+ if (!fastest || mode->refreshRate() > fastest->refreshRate()) {
+ fastest = mode;
+ }
+ }
+ return fastest;
+}
+
+// KWin's own choice for a screen it has not seen before
+// (OutputConfigurationStore::chooseScale in Plasma 6.3), so "recommended" is
+// the scale the screen started with. A built-in panel is taken to be a
+// laptop's.
+double recommendedScale(const OutputPtr &output)
+{
+ const ModePtr mode = output->preferredMode() ? output->preferredMode() : output->currentMode();
+ const QSize mm = output->sizeMm();
+ if (!mode || mm.width() < 3 || mm.height() < 3) {
+ return 1.0;
+ }
+ const double targetDpi = isBuiltIn(output) ? 125 : 96;
+ const double minSize = 800;
+ const QSize px = mode->size();
+
+ const double dpiX = px.width() / (mm.width() / 25.4);
+ const double maxX = std::clamp(px.width() / minSize, 1.0, 3.0);
+ const double scaleX = std::clamp(dpiX / targetDpi, 1.0, maxX);
+
+ const double dpiY = px.height() / (mm.height() / 25.4);
+ const double maxY = std::clamp(px.height() / minSize, 1.0, 3.0);
+ const double scaleY = std::clamp(dpiY / targetDpi, 1.0, maxY);
+
+ return std::round(100.0 * std::min(scaleX, scaleY) / 5.0) * 5.0 / 100.0;
+}
+
+QString label(const OutputPtr &output)
+{
+ if (isBuiltIn(output)) {
+ return QStringLiteral("Built-in");
+ }
+ // Projectors and some TVs report an aspect ratio in place of a size.
+ const QSize mm = output->sizeMm();
+ if (mm.width() >= 100 && mm.height() >= 100) {
+ const int inches = int(std::round(std::hypot(mm.width(), mm.height()) / 25.4));
+ return QStringLiteral("External, %1 inch").arg(inches);
+ }
+ return QStringLiteral("External");
+}
+}
+
+Displays::Displays(QObject *parent)
+ : QObject(parent)
+{
+ m_countdown.setInterval(1000);
+ connect(&m_countdown, &QTimer::timeout, this, [this] {
+ if (--m_secondsLeft <= 0) {
+ revert();
+ return;
+ }
+ Q_EMIT confirmChanged();
+ });
+
+ // KScreen reports a change once per setting; reading once they settle
+ // keeps the page from flickering through the steps.
+ m_reloadSoon.setSingleShot(true);
+ m_reloadSoon.setInterval(300);
+ connect(&m_reloadSoon, &QTimer::timeout, this, [this] {
+ if (m_applying > 0) {
+ m_reloadSoon.start();
+ return;
+ }
+ reload();
+ });
+ connect(ConfigMonitor::instance(), &ConfigMonitor::configurationChanged, &m_reloadSoon, qOverload<>(&QTimer::start));
+
+ // A slider sends a value for every step; KWin needs only where it stops.
+ m_applySoon.setSingleShot(true);
+ m_applySoon.setInterval(150);
+ connect(&m_applySoon, &QTimer::timeout, this, &Displays::apply);
+
+ reload();
+}
+
+bool Displays::available() const
+{
+ return m_config && m_config->supportedFeatures().testFlag(Config::Feature::Writable) && !m_outputs.isEmpty();
+}
+
+void Displays::reload()
+{
+ if (m_loading) {
+ m_reloadAgain = true;
+ return;
+ }
+ m_loading = true;
+ connect(new GetConfigOperation(), &GetConfigOperation::finished, this, [this](ConfigOperation *op) {
+ m_loading = false;
+ m_ready = true;
+ if (op->hasError()) {
+ m_config.reset();
+ } else {
+ m_config = qobject_cast<GetConfigOperation *>(op)->config();
+ // As kcm_kscreen's ConfigHandler::initOutput: geometry() is only
+ // right once the logical size is set.
+ const auto all = m_config->outputs();
+ for (const OutputPtr &output : all) {
+ output->setExplicitLogicalSize(m_config->logicalSizeForOutput(*output));
+ }
+ }
+ // A screen plugged in or out mid-countdown would make the old
+ // settings name screens that are no longer there.
+ if (m_revert && (!m_config || m_config->connectedOutputsHash() != m_revert->connectedOutputsHash())) {
+ stopCountdown();
+ }
+ refresh();
+ if (m_reloadAgain) {
+ m_reloadAgain = false;
+ reload();
+ }
+ });
+}
+
+OutputPtr Displays::output(int id) const
+{
+ if (!m_config) {
+ return {};
+ }
+ const OutputPtr output = m_config->output(id);
+ return output && output->isConnected() ? output : OutputPtr();
+}
+
+// Windows numbers the built-in screen 1; the rest follow by connector, so a
+// screen keeps its number when another becomes the main display.
+QList<OutputPtr> Displays::ordered() const
+{
+ if (!m_config) {
+ return {};
+ }
+ QList<OutputPtr> list = m_config->connectedOutputs().values();
+ std::sort(list.begin(), list.end(), [](const OutputPtr &a, const OutputPtr &b) {
+ if (isBuiltIn(a) != isBuiltIn(b)) {
+ return isBuiltIn(a);
+ }
+ return a->name() < b->name();
+ });
+ return list;
+}
+
+QList<OutputPtr> Displays::enabledOutputs() const
+{
+ QList<OutputPtr> list = ordered();
+ list.removeIf([](const OutputPtr &output) {
+ return !output->isEnabled();
+ });
+ return list;
+}
+
+// Keys: id, name (connector), number, label, builtIn, enabled, primary,
+// x, y, width, height (desktop pixels), rotation, scale, recommendedScale,
+// resolutions and rates ([{ value, text }]), resolution, rate, vrrCapable,
+// vrr, hdrCapable, hdr, sdrBrightness, sdrMin, sdrMax.
+QVariantMap Displays::describe(const OutputPtr &output, int number) const
+{
+ const QRect geometry = output->geometry();
+ const ModePtr current = output->currentMode();
+ const ModePtr preferred = output->preferredMode();
+
+ QVariantList sizes;
+ const auto sizeList = resolutions(output);
+ for (const QSize &size : sizeList) {
+ QString text = QStringLiteral("%1 × %2").arg(size.width()).arg(size.height());
+ if (preferred && preferred->size() == size) {
+ text += QStringLiteral(" (recommended)");
+ }
+ sizes << QVariantMap{{QStringLiteral("value"), sizeKey(size)}, {QStringLiteral("text"), text}};
+ }
+
+ QVariantList rates;
+ QString rate;
+ const auto rateList = refreshRates(output);
+ for (const float r : rateList) {
+ rates << QVariantMap{{QStringLiteral("value"), rateKey(r)}, {QStringLiteral("text"), QStringLiteral("%1 Hz").arg(int(std::lround(r)))}};
+ if (current && rate.isEmpty() && sameRate(r, current->refreshRate())) {
+ rate = rateKey(r);
+ }
+ }
+
+ const auto caps = output->capabilities();
+ const bool hdrCapable = caps.testFlag(Output::Capability::HighDynamicRange) && caps.testFlag(Output::Capability::WideColorGamut);
+ const double peak = output->maxPeakBrightnessOverride().value_or(output->maxPeakBrightness());
+
+ return {
+ {QStringLiteral("id"), output->id()},
+ {QStringLiteral("name"), output->name()},
+ {QStringLiteral("number"), number},
+ {QStringLiteral("label"), label(output)},
+ {QStringLiteral("builtIn"), isBuiltIn(output)},
+ {QStringLiteral("enabled"), output->isEnabled()},
+ {QStringLiteral("primary"), output->isEnabled() && output->priority() == 1},
+ {QStringLiteral("x"), geometry.x()},
+ {QStringLiteral("y"), geometry.y()},
+ {QStringLiteral("width"), geometry.width()},
+ {QStringLiteral("height"), geometry.height()},
+ {QStringLiteral("rotation"), int(output->rotation())},
+ {QStringLiteral("scale"), output->scale()},
+ {QStringLiteral("recommendedScale"), recommendedScale(output)},
+ {QStringLiteral("resolutions"), sizes},
+ {QStringLiteral("resolution"), current ? sizeKey(current->size()) : QString()},
+ {QStringLiteral("rates"), rates},
+ {QStringLiteral("rate"), rate},
+ {QStringLiteral("vrrCapable"), caps.testFlag(Output::Capability::Vrr)},
+ {QStringLiteral("vrr"), output->vrrPolicy() != Output::VrrPolicy::Never},
+ {QStringLiteral("hdrCapable"), hdrCapable},
+ {QStringLiteral("hdr"), output->isHdrEnabled()},
+ {QStringLiteral("sdrBrightness"), int(output->sdrBrightness())},
+ // kcm_kscreen's "Maximum SDR Brightness" range.
+ {QStringLiteral("sdrMin"), 50},
+ {QStringLiteral("sdrMax"), peak > 50 ? int(peak) : 500},
+ };
+}
+
+void Displays::refresh()
+{
+ QVariantList list;
+ const auto all = ordered();
+ for (int i = 0; i < all.size(); ++i) {
+ list << describe(all[i], i + 1);
+ }
+ m_outputs = list;
+
+ const auto on = enabledOutputs();
+ if (all.size() < 2) {
+ m_arrangement = QStringLiteral("single");
+ } else if (on.size() == 1) {
+ m_arrangement = QStringLiteral("only");
+ } else {
+ // KWin is not told which screen copies which; a duplicate is screens
+ // showing the same part of the desktop, as kcm_kscreen arranges them.
+ bool overlap = true;
+ for (int i = 0; i < on.size() && overlap; ++i) {
+ for (int j = i + 1; j < on.size() && overlap; ++j) {
+ overlap = on[i]->geometry().intersects(on[j]->geometry());
+ }
+ }
+ m_arrangement = overlap ? QStringLiteral("duplicate") : QStringLiteral("extend");
+ }
+ Q_EMIT changed();
+}
+
+void Displays::apply()
+{
+ m_applySoon.stop();
+ if (!m_config) {
+ return;
+ }
+ if (!Config::canBeApplied(m_config)) {
+ Q_EMIT failed(QStringLiteral("These screen settings cannot be used."));
+ reload();
+ return;
+ }
+ ++m_applying;
+ // Not exec(): its nested event loop lets the page run while the config
+ // it holds is replaced (KDE bug 466960).
+ auto op = new SetConfigOperation(m_config);
+ connect(op, &ConfigOperation::finished, this, [this](ConfigOperation *op) {
+ --m_applying;
+ if (op->hasError()) {
+ Q_EMIT failed(op->errorString());
+ reload();
+ }
+ });
+}
+
+void Displays::preview(const ConfigPtr &before)
+{
+ if (!m_revert) {
+ m_revert = before;
+ }
+ m_secondsLeft = previewSeconds;
+ m_countdown.start();
+ Q_EMIT confirmChanged();
+}
+
+void Displays::stopCountdown()
+{
+ const bool was = bool(m_revert);
+ m_revert.reset();
+ m_countdown.stop();
+ m_secondsLeft = 0;
+ if (was) {
+ Q_EMIT confirmChanged();
+ }
+}
+
+void Displays::keep()
+{
+ stopCountdown();
+}
+
+void Displays::revert()
+{
+ const ConfigPtr target = m_revert;
+ stopCountdown();
+ if (!target || !Config::canBeApplied(target)) {
+ return;
+ }
+ m_config = target;
+ refresh();
+ apply();
+}
+
+// A screen that grows or shrinks pushes the screens right of and below its
+// middle along with its edge, so they stay touching (kcm_kscreen's
+// maintainSnapping).
+void Displays::resize(const OutputPtr &changed, const QSize &oldSize)
+{
+ const QSize newSize = m_config->logicalSizeForOutputInt(*changed);
+ changed->setExplicitLogicalSize(QSizeF(newSize));
+ const QPoint centre = QRect(changed->pos(), oldSize).center();
+ const QSize delta = newSize - oldSize;
+ const auto all = enabledOutputs();
+ for (const OutputPtr &other : all) {
+ if (other->id() == changed->id()) {
+ continue;
+ }
+ const QPoint pos = other->pos();
+ const QPoint shift(pos.x() >= centre.x() ? delta.width() : 0, pos.y() >= centre.y() ? delta.height() : 0);
+ if (!shift.isNull()) {
+ other->setPos(pos + shift);
+ }
+ }
+ normalise();
+}
+
+// KWin expects the desktop to start at 0, 0.
+void Displays::normalise()
+{
+ const auto on = enabledOutputs();
+ if (on.isEmpty()) {
+ return;
+ }
+ int left = INT_MAX;
+ int top = INT_MAX;
+ for (const OutputPtr &output : on) {
+ left = std::min(left, output->pos().x());
+ top = std::min(top, output->pos().y());
+ }
+ for (const OutputPtr &output : on) {
+ output->setPos(output->pos() - QPoint(left, top));
+ }
+}
+
+// Side by side in Windows' numbering, tops level.
+void Displays::lineUp()
+{
+ int x = 0;
+ const auto on = enabledOutputs();
+ for (const OutputPtr &output : on) {
+ output->setReplicationSource(0);
+ output->setPos(QPoint(x, 0));
+ x += output->geometry().width();
+ }
+}
+
+void Displays::switchOn(const OutputPtr &output)
+{
+ if (output->isEnabled()) {
+ return;
+ }
+ if (!output->currentMode()) {
+ output->setCurrentModeId(output->preferredModeId());
+ }
+ if (!output->currentMode()) {
+ return;
+ }
+ int right = 0;
+ const auto on = enabledOutputs();
+ for (const OutputPtr &other : on) {
+ right = std::max(right, other->geometry().x() + other->geometry().width());
+ }
+ output->setEnabled(true);
+ output->setSize(output->currentMode()->size());
+ output->setExplicitLogicalSize(QSizeF(m_config->logicalSizeForOutputInt(*output)));
+ output->setPos(QPoint(right, 0));
+ // A screen that was off has no place in the order; this gives it the
+ // next one.
+ m_config->adjustPriorities();
+}
+
+// kcm_kscreen's setReplicationSourceIndex: the copy takes the mode nearest
+// the source's shape and is scaled and placed so it shows exactly the
+// source's part of the desktop.
+void Displays::mirror(const OutputPtr &replica, const OutputPtr &source)
+{
+ const ModePtr sourceMode = source->currentMode();
+ if (!sourceMode) {
+ return;
+ }
+ const auto turned = [](const OutputPtr &output, QSize size) {
+ return output->isHorizontal() ? size : size.transposed();
+ };
+ const auto ratio = [&turned](const OutputPtr &output, const ModePtr &mode) {
+ const QSize size = turned(output, mode->size());
+ return size.width() / qreal(size.height());
+ };
+
+ const qreal sourceRatio = ratio(source, sourceMode);
+ QList<ModePtr> fitting;
+ const auto modes = replica->modes();
+ for (const ModePtr &mode : modes) {
+ if (qFuzzyCompare(ratio(replica, mode), sourceRatio)) {
+ fitting << mode;
+ }
+ }
+ ModePtr best = replica->currentMode();
+ if (!fitting.isEmpty()) {
+ std::sort(fitting.begin(), fitting.end(), [](const ModePtr &a, const ModePtr &b) {
+ return a->size().width() < b->size().width();
+ });
+ const QSize sourceSize = turned(source, sourceMode->size());
+ const auto it = std::find_if(fitting.cbegin(), fitting.cend(), [&](const ModePtr &mode) {
+ return turned(replica, mode->size()).width() >= sourceSize.width();
+ });
+ best = it != fitting.cend() ? *it : fitting.last();
+ }
+ if (!best) {
+ return;
+ }
+
+ const QSize sourceSize = turned(source, sourceMode->size());
+ const QSize replicaSize = turned(replica, best->size());
+ qreal scale = source->scale() * std::max(replicaSize.width() / qreal(sourceSize.width()), replicaSize.height() / qreal(sourceSize.height()));
+ // Whole 1/120ths, the steps of Wayland's fractional scale, so no sliver
+ // is left at the edge to trip hidden panels.
+ scale = std::ceil(scale * 120.0) / 120.0;
+ const QPoint offset((sourceSize.width() / source->scale() - replicaSize.width() / scale) / 2,
+ (sourceSize.height() / source->scale() - replicaSize.height() / scale) / 2);
+
+ replica->setCurrentModeId(best->id());
+ replica->setSize(best->size());
+ replica->setScale(scale);
+ replica->setExplicitLogicalSize(QSizeF(m_config->logicalSizeForOutputInt(*replica)));
+ replica->setReplicationSource(source->id());
+ replica->setPos(source->pos() + offset);
+}
+
+QPoint Displays::snapped(const OutputPtr &moving, const QPoint &dest, int threshold) const
+{
+ const QSize size = moving->geometry().size();
+ QList<QRect> others;
+ const auto on = enabledOutputs();
+ for (const OutputPtr &other : on) {
+ if (other->id() != moving->id()) {
+ others << other->geometry();
+ }
+ }
+ if (others.isEmpty() || size.isEmpty()) {
+ return moving->pos();
+ }
+
+ std::optional<QPoint> best;
+ int bestDistance = INT_MAX;
+ const auto consider = [&](const QPoint &candidate) {
+ const QRect rect(candidate, size);
+ for (const QRect &other : others) {
+ if (rect.intersects(other)) {
+ return;
+ }
+ }
+ const int distance = (candidate - dest).manhattanLength();
+ if (distance < bestDistance) {
+ best = candidate;
+ bestDistance = distance;
+ }
+ };
+ const auto align = [threshold](int value, int length, int start, int span) {
+ if (std::abs(value - start) < threshold) {
+ return start;
+ }
+ if (std::abs(value + length - (start + span)) < threshold) {
+ return start + span - length;
+ }
+ if (std::abs(value + length / 2 - (start + span / 2)) < threshold) {
+ return start + span / 2 - length / 2;
+ }
+ return value;
+ };
+
+ // Every way of touching each other screen along a whole edge, keeping a
+ // quarter of the shorter side shared so a corner never counts as
+ // touching; the nearest one wins. Screens always end up edge to edge,
+ // which KWin needs for the pointer to cross between them.
+ for (const QRect &target : others) {
+ const int shareY = std::max(1, std::min(size.height(), target.height()) / 4);
+ int y = std::clamp(dest.y(), target.y() - size.height() + shareY, target.y() + target.height() - shareY);
+ y = align(y, size.height(), target.y(), target.height());
+ consider(QPoint(target.x() + target.width(), y));
+ consider(QPoint(target.x() - size.width(), y));
+
+ const int shareX = std::max(1, std::min(size.width(), target.width()) / 4);
+ int x = std::clamp(dest.x(), target.x() - size.width() + shareX, target.x() + target.width() - shareX);
+ x = align(x, size.width(), target.x(), target.width());
+ consider(QPoint(x, target.y() + target.height()));
+ consider(QPoint(x, target.y() - size.height()));
+ }
+ return best.value_or(moving->pos());
+}
+
+QPoint Displays::snap(int id, int x, int y, int threshold) const
+{
+ const OutputPtr moving = output(id);
+ if (!moving) {
+ return QPoint(x, y);
+ }
+ return snapped(moving, QPoint(x, y), threshold);
+}
+
+void Displays::move(int id, int x, int y)
+{
+ const OutputPtr moving = output(id);
+ if (!moving || !moving->isEnabled()) {
+ return;
+ }
+ const auto positions = [this] {
+ QList<QPoint> list;
+ const auto on = enabledOutputs();
+ for (const OutputPtr &output : on) {
+ list << output->pos();
+ }
+ return list;
+ };
+ const QList<QPoint> before = positions();
+ moving->setPos(snapped(moving, QPoint(x, y), 0));
+ normalise();
+ refresh();
+ if (positions() != before) {
+ apply();
+ }
+}
+
+void Displays::setPrimary(int id)
+{
+ const OutputPtr target = output(id);
+ if (!target || !target->isEnabled() || target->priority() == 1) {
+ return;
+ }
+ m_config->setOutputPriority(target, 1);
+ refresh();
+ apply();
+}
+
+void Displays::setResolution(int id, const QString &size)
+{
+ const OutputPtr target = output(id);
+ const QStringList parts = size.split(QLatin1Char('x'));
+ if (!target || !target->isEnabled() || parts.size() != 2) {
+ return;
+ }
+ const ModePtr current = target->currentMode();
+ const ModePtr mode = modeFor(target, QSize(parts[0].toInt(), parts[1].toInt()), current ? current->refreshRate() : 0);
+ if (!mode || (current && mode->id() == current->id())) {
+ return;
+ }
+ const ConfigPtr before = m_config->clone();
+ const QSize oldSize = target->explicitLogicalSizeInt();
+ target->setCurrentModeId(mode->id());
+ target->setSize(mode->size());
+ resize(target, oldSize);
+ refresh();
+ preview(before);
+ apply();
+}
+
+void Displays::setRefreshRate(int id, const QString &rate)
+{
+ const OutputPtr target = output(id);
+ if (!target || !target->isEnabled() || !target->currentMode()) {
+ return;
+ }
+ const ModePtr current = target->currentMode();
+ const float wanted = rate.toFloat();
+ if (sameRate(current->refreshRate(), wanted)) {
+ return;
+ }
+ const ModePtr mode = modeFor(target, current->size(), wanted);
+ if (!mode || !sameRate(mode->refreshRate(), wanted)) {
+ return;
+ }
+ const ConfigPtr before = m_config->clone();
+ target->setCurrentModeId(mode->id());
+ refresh();
+ preview(before);
+ apply();
+}
+
+void Displays::setScale(int id, double scale)
+{
+ const OutputPtr target = output(id);
+ if (!target || !target->isEnabled()) {
+ return;
+ }
+ scale = std::clamp(std::round(scale * 120.0) / 120.0, 0.5, 3.0);
+ if (qFuzzyCompare(target->scale(), scale)) {
+ return;
+ }
+ const QSize oldSize = target->explicitLogicalSizeInt();
+ target->setScale(scale);
+ resize(target, oldSize);
+ refresh();
+ apply();
+}
+
+void Displays::setRotation(int id, int rotation)
+{
+ const OutputPtr target = output(id);
+ const auto value = Output::Rotation(rotation);
+ if (!target || !target->isEnabled()
+ || (value != Output::None && value != Output::Left && value != Output::Inverted && value != Output::Right)
+ || target->rotation() == value) {
+ return;
+ }
+ const QSize oldSize = target->explicitLogicalSizeInt();
+ target->setRotation(value);
+ resize(target, oldSize);
+ refresh();
+ apply();
+}
+
+void Displays::setArrangement(int id, const QString &mode)
+{
+ const OutputPtr target = output(id);
+ if (!target) {
+ return;
+ }
+ const auto all = ordered();
+ if (mode == QLatin1String("only")) {
+ switchOn(target);
+ for (const OutputPtr &other : all) {
+ if (other->id() != target->id() && other->isEnabled()) {
+ m_config->setOutputPriority(other, 0);
+ }
+ }
+ target->setReplicationSource(0);
+ target->setPos(QPoint(0, 0));
+ } else if (mode == QLatin1String("off")) {
+ if (enabledOutputs().size() < 2 || !target->isEnabled()) {
+ return;
+ }
+ m_config->setOutputPriority(target, 0);
+ for (const OutputPtr &other : all) {
+ if (other->replicationSource() == target->id()) {
+ other->setReplicationSource(0);
+ }
+ }
+ } else if (mode == QLatin1String("extend")) {
+ const bool wasDuplicate = m_arrangement == QLatin1String("duplicate");
+ for (const OutputPtr &other : all) {
+ if (!other->isEnabled()) {
+ switchOn(other);
+ } else if (wasDuplicate && other->id() != target->id()) {
+ // A copy was given its source's shape; on its own it goes
+ // back to what suits it.
+ if (const ModePtr preferred = other->preferredMode()) {
+ other->setCurrentModeId(preferred->id());
+ other->setSize(preferred->size());
+ }
+ other->setScale(recommendedScale(other));
+ other->setExplicitLogicalSize(QSizeF(m_config->logicalSizeForOutputInt(*other)));
+ }
+ }
+ if (wasDuplicate) {
+ lineUp();
+ }
+ } else if (mode == QLatin1String("duplicate")) {
+ switchOn(target);
+ target->setReplicationSource(0);
+ for (const OutputPtr &other : all) {
+ if (other->id() == target->id()) {
+ continue;
+ }
+ switchOn(other);
+ mirror(other, target);
+ }
+ } else {
+ return;
+ }
+ normalise();
+ refresh();
+ apply();
+}
+
+void Displays::setVrr(int id, bool on)
+{
+ const OutputPtr target = output(id);
+ if (!target || !target->capabilities().testFlag(Output::Capability::Vrr)) {
+ return;
+ }
+ // Automatic is KWin's "only for full-screen games and video"; Always
+ // would also change the rate under the desktop, which flickers on many
+ // screens.
+ target->setVrrPolicy(on ? Output::VrrPolicy::Automatic : Output::VrrPolicy::Never);
+ refresh();
+ apply();
+}
+
+void Displays::setHdr(int id, bool on)
+{
+ const OutputPtr target = output(id);
+ if (!target || !target->capabilities().testFlag(Output::Capability::HighDynamicRange) || target->isHdrEnabled() == on) {
+ return;
+ }
+ const ConfigPtr before = m_config->clone();
+ // kcm_kscreen switches the wide colour gamut with HDR; KWin's HDR needs
+ // both.
+ target->setHdrEnabled(on);
+ target->setWcgEnabled(on);
+ refresh();
+ preview(before);
+ apply();
+}
+
+void Displays::setSdrBrightness(int id, int nits)
+{
+ const OutputPtr target = output(id);
+ if (!target || !target->isHdrEnabled()) {
+ return;
+ }
+ target->setSdrBrightness(uint32_t(std::max(50, nits)));
+ refresh();
+ m_applySoon.start();
+}
diff --git a/packages/wildos-settings/src/display.h b/packages/wildos-settings/src/display.h
new file mode 100644
index 0000000..99140dc
--- /dev/null
+++ b/packages/wildos-settings/src/display.h
@@ -0,0 +1,111 @@
+#pragma once
+
+#include <kscreen/types.h>
+
+#include <QObject>
+#include <QPoint>
+#include <QQmlEngine>
+#include <QSize>
+#include <QTimer>
+#include <QVariantList>
+
+// Settings > System > Display. The screens are read and changed through
+// libkscreen, the library KDE's own display module uses, so KWin keeps every
+// change for the next sign-in exactly as if it had been made there. Each
+// change is applied at once, as on Windows; a new resolution, refresh rate
+// or HDR switch is kept only once the person says so, and switches back
+// after 15 seconds otherwise.
+//
+// The countdown lives here rather than in the page: Settings rebuilds a page
+// each time it is opened, and leaving Display mid-countdown must still
+// switch back.
+class Displays : public QObject
+{
+ Q_OBJECT
+ QML_ELEMENT
+ QML_SINGLETON
+
+ // False until KScreen has answered the first time.
+ Q_PROPERTY(bool ready READ ready NOTIFY changed)
+ // KScreen answered and its screens can be changed.
+ Q_PROPERTY(bool available READ available NOTIFY changed)
+ // Connected screens in Windows' numbering, built-in first. Each is a map;
+ // see describe() in display.cpp for the keys.
+ Q_PROPERTY(QVariantList outputs READ outputs NOTIFY changed)
+ // single (one screen connected), extend, duplicate or only (one of
+ // several screens is on).
+ Q_PROPERTY(QString arrangement READ arrangement NOTIFY changed)
+ Q_PROPERTY(bool confirming READ confirming NOTIFY confirmChanged)
+ Q_PROPERTY(int secondsLeft READ secondsLeft NOTIFY confirmChanged)
+
+public:
+ explicit Displays(QObject *parent = nullptr);
+
+ bool ready() const { return m_ready; }
+ bool available() const;
+ QVariantList outputs() const { return m_outputs; }
+ QString arrangement() const { return m_arrangement; }
+ bool confirming() const { return bool(m_revert); }
+ int secondsLeft() const { return m_secondsLeft; }
+
+ // Asks KScreen for the screens again (Detect).
+ Q_INVOKABLE void reload();
+
+ // Where a screen dragged to x, y (desktop pixels) lands: against the
+ // nearest edge of another screen, never overlapping one, with edges and
+ // centres closer than `threshold` lined up.
+ Q_INVOKABLE QPoint snap(int id, int x, int y, int threshold) const;
+ Q_INVOKABLE void move(int id, int x, int y);
+
+ Q_INVOKABLE void setPrimary(int id);
+ // size is "3840x2160", as in each output's resolutions.
+ Q_INVOKABLE void setResolution(int id, const QString &size);
+ // rate is a value from the output's rates.
+ Q_INVOKABLE void setRefreshRate(int id, const QString &rate);
+ Q_INVOKABLE void setScale(int id, double scale);
+ // KScreen's rotation: 1 none, 2 left, 4 inverted, 8 right.
+ Q_INVOKABLE void setRotation(int id, int rotation);
+ // extend, duplicate, only or off, for the screen `id`.
+ Q_INVOKABLE void setArrangement(int id, const QString &mode);
+ Q_INVOKABLE void setVrr(int id, bool on);
+ Q_INVOKABLE void setHdr(int id, bool on);
+ Q_INVOKABLE void setSdrBrightness(int id, int nits);
+
+ Q_INVOKABLE void keep();
+ Q_INVOKABLE void revert();
+
+Q_SIGNALS:
+ void changed();
+ void confirmChanged();
+ void failed(const QString &reason);
+
+private:
+ KScreen::OutputPtr output(int id) const;
+ QList<KScreen::OutputPtr> ordered() const;
+ QList<KScreen::OutputPtr> enabledOutputs() const;
+ QVariantMap describe(const KScreen::OutputPtr &output, int number) const;
+ void refresh();
+ void apply();
+ void preview(const KScreen::ConfigPtr &before);
+ void resize(const KScreen::OutputPtr &output, const QSize &oldSize);
+ void normalise();
+ void lineUp();
+ void switchOn(const KScreen::OutputPtr &output);
+ void mirror(const KScreen::OutputPtr &replica, const KScreen::OutputPtr &source);
+ QPoint snapped(const KScreen::OutputPtr &moving, const QPoint &dest, int threshold) const;
+ void stopCountdown();
+
+ KScreen::ConfigPtr m_config;
+ // What to go back to when a previewed change is not kept.
+ KScreen::ConfigPtr m_revert;
+ QVariantList m_outputs;
+ QString m_arrangement;
+ bool m_ready = false;
+ bool m_loading = false;
+ bool m_reloadAgain = false;
+ int m_applying = 0;
+ int m_secondsLeft = 0;
+ QTimer m_countdown;
+ QTimer m_reloadSoon;
+ QTimer m_applySoon;
+};
diff --git a/packages/wildos-settings/src/filesearch.cpp b/packages/wildos-settings/src/filesearch.cpp
new file mode 100644
index 0000000..06c781a
--- /dev/null
+++ b/packages/wildos-settings/src/filesearch.cpp
@@ -0,0 +1,250 @@
+#include "filesearch.h"
+
+#include <KConfig>
+#include <KConfigGroup>
+#include <KFormat>
+
+#include <QDBusConnection>
+#include <QDBusMessage>
+#include <QDir>
+#include <QFileInfo>
+#include <QProcess>
+#include <QStandardPaths>
+#include <QUrl>
+
+namespace
+{
+const QString configName = QStringLiteral("baloofilerc");
+
+QString balooctl()
+{
+ return QStandardPaths::findExecutable(QStringLiteral("balooctl6"));
+}
+
+// The kcm and baloo compare folders with a trailing slash
+// (filteredfoldermodel.cpp addTrailingSlashes), so they are stored that way.
+QString normalise(const QString &folder)
+{
+ QString path = folder.startsWith(QLatin1String("file:")) ? QUrl(folder).toLocalFile() : folder;
+ if (path.startsWith(QLatin1String("~/")) || path == QLatin1String("~")) {
+ path.replace(0, 1, QDir::homePath());
+ }
+ path = QDir::cleanPath(path);
+ if (!path.endsWith(QLatin1Char('/'))) {
+ path += QLatin1Char('/');
+ }
+ return path;
+}
+
+QStringList normalised(const QStringList &list)
+{
+ QStringList out;
+ for (const QString &f : list) {
+ const QString n = normalise(f);
+ if (!out.contains(n)) {
+ out << n;
+ }
+ }
+ return out;
+}
+
+QString indexPath()
+{
+ // baloo's own fileIndexDbPath(): BALOO_DB_PATH when set.
+ const QString moved = QString::fromLocal8Bit(qgetenv("BALOO_DB_PATH"));
+ if (!moved.isEmpty()) {
+ return moved + QStringLiteral("/index");
+ }
+ return QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QStringLiteral("/baloo/index");
+}
+}
+
+FileSearch::FileSearch(QObject *parent)
+ : QObject(parent)
+{
+}
+
+bool FileSearch::available() const
+{
+ return !balooctl().isEmpty();
+}
+
+bool FileSearch::enabled() const
+{
+ const KConfig config(configName, KConfig::NoGlobals);
+ return available() && config.group(QStringLiteral("Basic Settings")).readEntry("Indexing-Enabled", true);
+}
+
+bool FileSearch::contents() const
+{
+ const KConfig config(configName, KConfig::NoGlobals);
+ return !config.group(QStringLiteral("General")).readEntry("only basic indexing", false);
+}
+
+bool FileSearch::hidden() const
+{
+ const KConfig config(configName, KConfig::NoGlobals);
+ return config.group(QStringLiteral("General")).readEntry("index hidden folders", false);
+}
+
+QStringList FileSearch::folders() const
+{
+ const KConfig config(configName, KConfig::NoGlobals);
+ return normalised(config.group(QStringLiteral("General")).readPathEntry("folders", QStringList{QDir::homePath()}));
+}
+
+QStringList FileSearch::excluded() const
+{
+ const KConfig config(configName, KConfig::NoGlobals);
+ return normalised(config.group(QStringLiteral("General")).readPathEntry("exclude folders", QStringList()));
+}
+
+QString FileSearch::indexSize() const
+{
+ const QFileInfo index(indexPath());
+ return index.exists() ? KFormat().formatByteSize(double(index.size())) : QString();
+}
+
+QString FileSearch::display(const QString &folder) const
+{
+ QString path = normalise(folder);
+ path.chop(1);
+ const QString home = QDir::homePath();
+ if (path == home) {
+ return QStringLiteral("Your home folder");
+ }
+ if (path.startsWith(home + QLatin1Char('/'))) {
+ return QLatin1Char('~') + path.mid(home.length());
+ }
+ return path.isEmpty() ? QStringLiteral("/") : path;
+}
+
+void FileSearch::setEnabled(bool on)
+{
+ if (!available()) {
+ return;
+ }
+ KConfig config(configName, KConfig::NoGlobals);
+ config.group(QStringLiteral("Basic Settings")).writeEntry("Indexing-Enabled", on);
+ config.sync();
+ // KDE's module turns the search runner off with indexing, so nothing
+ // offers to search an index that is not kept.
+ KConfig runner(QStringLiteral("krunnerrc"));
+ runner.group(QStringLiteral("Plugins")).writeEntry("baloosearchEnabled", on, KConfig::Notify);
+ runner.sync();
+ apply(true);
+}
+
+void FileSearch::setContents(bool on)
+{
+ KConfig config(configName, KConfig::NoGlobals);
+ config.group(QStringLiteral("General")).writeEntry("only basic indexing", !on);
+ config.sync();
+ apply(false);
+}
+
+void FileSearch::setHidden(bool on)
+{
+ KConfig config(configName, KConfig::NoGlobals);
+ config.group(QStringLiteral("General")).writeEntry("index hidden folders", on);
+ config.sync();
+ apply(false);
+}
+
+void FileSearch::writeList(const char *key, const QStringList &list)
+{
+ KConfig config(configName, KConfig::NoGlobals);
+ QStringList sorted = list;
+ sorted.sort();
+ config.group(QStringLiteral("General")).writePathEntry(key, sorted);
+ config.sync();
+ apply(false);
+}
+
+void FileSearch::addFolder(const QString &folder)
+{
+ const QString path = normalise(folder);
+ QStringList list = folders();
+ QStringList out = excluded();
+ if (out.removeAll(path) > 0) {
+ writeList("exclude folders", out);
+ }
+ if (!list.contains(path)) {
+ list << path;
+ writeList("folders", list);
+ }
+}
+
+void FileSearch::removeFolder(const QString &folder)
+{
+ QStringList list = folders();
+ if (list.removeAll(normalise(folder)) > 0) {
+ writeList("folders", list);
+ }
+}
+
+void FileSearch::exclude(const QString &folder)
+{
+ const QString path = normalise(folder);
+ QStringList list = excluded();
+ QStringList in = folders();
+ if (in.removeAll(path) > 0) {
+ writeList("folders", in);
+ }
+ if (!list.contains(path)) {
+ list << path;
+ writeList("exclude folders", list);
+ }
+}
+
+void FileSearch::include(const QString &folder)
+{
+ QStringList list = excluded();
+ if (list.removeAll(normalise(folder)) > 0) {
+ writeList("exclude folders", list);
+ }
+}
+
+void FileSearch::apply(bool startOrStop)
+{
+ if (startOrStop) {
+ // "balooctl6 enable" starts baloo_file from where the build put it
+ // (KDE_INSTALL_FULL_LIBEXECDIR_KF), which is not on PATH.
+ QProcess::startDetached(balooctl(), {enabled() ? QStringLiteral("enable") : QStringLiteral("disable")});
+ } else if (enabled()) {
+ // Goes nowhere when the indexer is not running, which is fine: it
+ // reads the file when it starts.
+ auto message = QDBusMessage::createMethodCall(QStringLiteral("org.kde.baloo"), QStringLiteral("/"), QStringLiteral("org.kde.baloo.main"),
+ QStringLiteral("updateConfig"));
+ QDBusConnection::sessionBus().send(message);
+ }
+ Q_EMIT changed();
+}
+
+void FileSearch::rebuild()
+{
+ if (!available() || m_rebuilding) {
+ return;
+ }
+ m_rebuilding = true;
+ Q_EMIT rebuildingChanged();
+ auto process = new QProcess(this);
+ process->setProcessChannelMode(QProcess::MergedChannels);
+ connect(process, &QProcess::finished, this, [this, process](int code, QProcess::ExitStatus status) {
+ const QString output = QString::fromUtf8(process->readAll()).trimmed();
+ process->deleteLater();
+ m_rebuilding = false;
+ Q_EMIT rebuildingChanged();
+ if (status != QProcess::NormalExit || code != 0) {
+ Q_EMIT failed(output.section(QLatin1Char('\n'), -1));
+ }
+ Q_EMIT changed();
+ });
+ // purge stops the indexer, deletes the index and starts it again.
+ process->start(balooctl(), {QStringLiteral("purge")});
+}
+
+void FileSearch::reload()
+{
+ Q_EMIT changed();
+}
diff --git a/packages/wildos-settings/src/filesearch.h b/packages/wildos-settings/src/filesearch.h
new file mode 100644
index 0000000..d33a40f
--- /dev/null
+++ b/packages/wildos-settings/src/filesearch.h
@@ -0,0 +1,68 @@
+#pragma once
+
+#include <QObject>
+#include <QQmlEngine>
+#include <QStringList>
+
+// Searching files, after Windows 11's Privacy and security > Searching
+// Windows: Baloo, the file indexer behind search in Start and Files.
+//
+// The settings are baloofilerc, the same keys KDE's own file search module
+// writes (baloo's baloosettings.kcfg): [Basic Settings] Indexing-Enabled,
+// [General] folders, exclude folders, only basic indexing and index hidden
+// folders. After a change the running indexer is asked to read them again
+// (org.kde.baloo / org.kde.baloo.main.updateConfig), and turning indexing
+// on or off goes through balooctl6, which also starts or stops it.
+class FileSearch : public QObject
+{
+ Q_OBJECT
+ QML_ELEMENT
+ QML_SINGLETON
+
+ Q_PROPERTY(bool available READ available CONSTANT)
+ Q_PROPERTY(bool enabled READ enabled WRITE setEnabled NOTIFY changed)
+ Q_PROPERTY(bool contents READ contents WRITE setContents NOTIFY changed)
+ Q_PROPERTY(bool hidden READ hidden WRITE setHidden NOTIFY changed)
+ Q_PROPERTY(QStringList folders READ folders NOTIFY changed)
+ Q_PROPERTY(QStringList excluded READ excluded NOTIFY changed)
+ Q_PROPERTY(QString indexSize READ indexSize NOTIFY changed)
+ Q_PROPERTY(bool rebuilding READ rebuilding NOTIFY rebuildingChanged)
+
+public:
+ explicit FileSearch(QObject *parent = nullptr);
+
+ bool available() const;
+ bool enabled() const;
+ void setEnabled(bool on);
+ bool contents() const;
+ void setContents(bool on);
+ bool hidden() const;
+ void setHidden(bool on);
+ QStringList folders() const;
+ QStringList excluded() const;
+ QString indexSize() const;
+ bool rebuilding() const { return m_rebuilding; }
+
+ // Paths or file:// URLs from a folder dialog.
+ Q_INVOKABLE void addFolder(const QString &folder);
+ Q_INVOKABLE void removeFolder(const QString &folder);
+ Q_INVOKABLE void exclude(const QString &folder);
+ Q_INVOKABLE void include(const QString &folder);
+ // Deletes the index and builds it again from the start.
+ Q_INVOKABLE void rebuild();
+ Q_INVOKABLE void reload();
+
+ // "~/Documents" for a folder in home, the path otherwise.
+ Q_INVOKABLE QString display(const QString &folder) const;
+
+Q_SIGNALS:
+ void changed();
+ void rebuildingChanged();
+ void failed(const QString &reason);
+
+private:
+ void writeList(const char *key, const QStringList &list);
+ void apply(bool startOrStop);
+
+ bool m_rebuilding = false;
+};
diff --git a/packages/wildos-settings/src/fonts.cpp b/packages/wildos-settings/src/fonts.cpp
new file mode 100644
index 0000000..44896cb
--- /dev/null
+++ b/packages/wildos-settings/src/fonts.cpp
@@ -0,0 +1,202 @@
+#include "fonts.h"
+
+#include <QCollator>
+#include <QDir>
+#include <QFile>
+#include <QFileInfo>
+#include <QMap>
+#include <QProcess>
+#include <QSet>
+#include <QStandardPaths>
+
+namespace
+{
+QString userFontDir()
+{
+ return QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QStringLiteral("/fonts");
+}
+
+// ~/.fonts is the older place for one account's fonts and fontconfig
+// still reads it, so fonts there count as the user's too.
+bool isUserFile(const QString &path)
+{
+ const QString legacy = QDir::homePath() + QStringLiteral("/.fonts/");
+ return path.startsWith(userFontDir() + QLatin1Char('/')) || path.startsWith(legacy);
+}
+
+const QStringList fontSuffixes = {QStringLiteral("ttf"), QStringLiteral("otf"), QStringLiteral("ttc"), QStringLiteral("otc")};
+
+// The family fontconfig reads from a file, or nothing when it is not a
+// font it can use.
+QString scanFamily(const QString &path)
+{
+ QProcess process;
+ process.start(QStringLiteral("fc-scan"), {QStringLiteral("--format"), QStringLiteral("%{family[0]}\\n"), path});
+ if (!process.waitForFinished(10000)) {
+ process.kill();
+ return {};
+ }
+ return QString::fromUtf8(process.readAllStandardOutput()).section(QLatin1Char('\n'), 0, 0).trimmed();
+}
+}
+
+Fonts::Fonts(QObject *parent)
+ : QObject(parent)
+{
+ reload();
+}
+
+void Fonts::setBusy(bool busy)
+{
+ if (m_busy != busy) {
+ m_busy = busy;
+ Q_EMIT busyChanged();
+ }
+}
+
+void Fonts::reload()
+{
+ // Three lines a font, so a family name with any punctuation in it
+ // cannot be mistaken for a separator.
+ auto process = new QProcess(this);
+ connect(process, &QProcess::finished, this, [this, process] {
+ const QStringList lines = QString::fromUtf8(process->readAllStandardOutput()).split(QLatin1Char('\n'));
+ process->deleteLater();
+
+ struct Family {
+ QSet<QString> styles;
+ QStringList files;
+ bool system = false;
+ };
+ QMap<QString, Family> byName;
+ for (qsizetype i = 0; i + 2 < lines.size(); i += 3) {
+ const QString file = lines.at(i);
+ const QString name = lines.at(i + 1).trimmed();
+ // Names starting with a dot are fontconfig's way of hiding a
+ // font from lists like this one.
+ if (name.isEmpty() || name.startsWith(QLatin1Char('.'))) {
+ continue;
+ }
+ Family &family = byName[name];
+ family.styles.insert(lines.at(i + 2).trimmed());
+ if (isUserFile(file)) {
+ if (!family.files.contains(file)) {
+ family.files << file;
+ }
+ } else {
+ family.system = true;
+ }
+ }
+
+ QVariantList list;
+ m_userFiles.clear();
+ for (auto it = byName.cbegin(); it != byName.cend(); ++it) {
+ // A family with any file from the system stays: removing only
+ // your copy would leave it installed anyway.
+ const bool removable = !it->system && !it->files.isEmpty();
+ if (removable) {
+ m_userFiles.insert(it.key(), it->files);
+ }
+ list << QVariantMap{
+ {QStringLiteral("family"), it.key()},
+ {QStringLiteral("styles"), int(it->styles.size())},
+ {QStringLiteral("removable"), removable},
+ };
+ }
+ QCollator collator;
+ collator.setCaseSensitivity(Qt::CaseInsensitive);
+ collator.setNumericMode(true);
+ std::sort(list.begin(), list.end(), [&collator](const QVariant &a, const QVariant &b) {
+ return collator.compare(a.toMap().value(QStringLiteral("family")).toString(), b.toMap().value(QStringLiteral("family")).toString()) < 0;
+ });
+ m_families = list;
+ Q_EMIT changed();
+ });
+ process->start(QStringLiteral("fc-list"), {QStringLiteral("--format"), QStringLiteral("%{file}\\n%{family[0]}\\n%{style[0]}\\n")});
+}
+
+void Fonts::refreshCache(const QString &title, const QString &message, bool failed)
+{
+ setBusy(true);
+ auto process = new QProcess(this);
+ connect(process, &QProcess::finished, this, [this, process, title, message, failed] {
+ process->deleteLater();
+ setBusy(false);
+ reload();
+ Q_EMIT finished(title, message, failed);
+ });
+ process->start(QStringLiteral("fc-cache"), {QStringLiteral("-f"), userFontDir()});
+}
+
+void Fonts::install(const QList<QUrl> &files)
+{
+ if (m_busy || files.isEmpty()) {
+ return;
+ }
+ const QString dir = userFontDir();
+ QDir().mkpath(dir);
+
+ QStringList installed;
+ QStringList refused;
+ for (const QUrl &url : files) {
+ const QString path = url.toLocalFile();
+ const QFileInfo info(path);
+ if (!fontSuffixes.contains(info.suffix().toLower())) {
+ refused << info.fileName();
+ continue;
+ }
+ const QString family = scanFamily(path);
+ if (family.isEmpty()) {
+ refused << info.fileName();
+ continue;
+ }
+ const QString target = dir + QLatin1Char('/') + info.fileName();
+ if (QFileInfo(target).canonicalFilePath() == info.canonicalFilePath()) {
+ installed << family;
+ continue;
+ }
+ // A newer copy of a font you installed before replaces it.
+ QFile::remove(target);
+ if (QFile::copy(path, target)) {
+ installed << family;
+ } else {
+ refused << info.fileName();
+ }
+ }
+ installed.removeDuplicates();
+
+ if (installed.isEmpty()) {
+ Q_EMIT finished(QStringLiteral("No fonts were installed"),
+ (refused.size() == 1 ? QStringLiteral("%1 is not a font file this computer can use.")
+ : QStringLiteral("%1 are not font files this computer can use."))
+ .arg(refused.join(QStringLiteral(", "))),
+ true);
+ return;
+ }
+ QString message = installed.size() == 1 ? QStringLiteral("%1 is ready in apps you open from now on.").arg(installed.constFirst())
+ : QStringLiteral("%1 are ready in apps you open from now on.").arg(installed.join(QStringLiteral(", ")));
+ if (!refused.isEmpty()) {
+ message += QStringLiteral(" %1 could not be installed.").arg(refused.join(QStringLiteral(", ")));
+ }
+ refreshCache(installed.size() == 1 ? QStringLiteral("Font installed") : QStringLiteral("Fonts installed"), message, false);
+}
+
+void Fonts::remove(const QString &family)
+{
+ if (m_busy || !m_userFiles.contains(family)) {
+ return;
+ }
+ bool ok = true;
+ for (const QString &file : m_userFiles.value(family)) {
+ // Only ever a file in your own font folders.
+ if (isUserFile(file) && QFile::exists(file) && !QFile::remove(file)) {
+ ok = false;
+ }
+ }
+ if (!ok) {
+ Q_EMIT finished(QStringLiteral("The font was not removed"), QStringLiteral("Some of %1's files could not be deleted.").arg(family), true);
+ reload();
+ return;
+ }
+ refreshCache(QStringLiteral("Font removed"), QStringLiteral("%1 is gone from apps you open from now on.").arg(family), false);
+}
diff --git a/packages/wildos-settings/src/fonts.h b/packages/wildos-settings/src/fonts.h
new file mode 100644
index 0000000..a1a916d
--- /dev/null
+++ b/packages/wildos-settings/src/fonts.h
@@ -0,0 +1,48 @@
+#pragma once
+
+#include <QHash>
+#include <QObject>
+#include <QQmlEngine>
+#include <QStringList>
+#include <QUrl>
+#include <QVariantList>
+
+// The fonts on this computer, as fontconfig sees them, after Windows 11's
+// Personalisation > Fonts. Fonts you install go to ~/.local/share/fonts,
+// the folder KDE's font installer uses for one account, and fc-cache is run
+// on it so new apps find them. Fonts that came with the system are listed
+// but cannot be removed here.
+class Fonts : public QObject
+{
+ Q_OBJECT
+ QML_ELEMENT
+ QML_SINGLETON
+
+ // [{ family, styles, removable }], sorted by name.
+ Q_PROPERTY(QVariantList families READ families NOTIFY changed)
+ Q_PROPERTY(bool busy READ busy NOTIFY busyChanged)
+
+public:
+ explicit Fonts(QObject *parent = nullptr);
+
+ QVariantList families() const { return m_families; }
+ bool busy() const { return m_busy; }
+
+ Q_INVOKABLE void reload();
+ Q_INVOKABLE void install(const QList<QUrl> &files);
+ Q_INVOKABLE void remove(const QString &family);
+
+Q_SIGNALS:
+ void changed();
+ void busyChanged();
+ // What happened, in a sentence for the page.
+ void finished(const QString &title, const QString &message, bool failed);
+
+private:
+ void refreshCache(const QString &title, const QString &message, bool failed);
+ void setBusy(bool busy);
+
+ QVariantList m_families;
+ QHash<QString, QStringList> m_userFiles;
+ bool m_busy = false;
+};
diff --git a/packages/wildos-settings/src/gamecontrollers.cpp b/packages/wildos-settings/src/gamecontrollers.cpp
new file mode 100644
index 0000000..2d49621
--- /dev/null
+++ b/packages/wildos-settings/src/gamecontrollers.cpp
@@ -0,0 +1,255 @@
+#include "gamecontrollers.h"
+
+#include <SDL2/SDL.h>
+
+#include <algorithm>
+
+namespace
+{
+// Often enough that a tap of a button shows.
+const int pollInterval = 30;
+
+struct Named {
+ SDL_GameControllerButton button;
+ const char *name;
+};
+
+// Windows' controller test names the buttons after an Xbox controller,
+// which is also the layout SDL maps every known gamepad to.
+const Named gamepadButtons[] = {
+ {SDL_CONTROLLER_BUTTON_A, "A"},
+ {SDL_CONTROLLER_BUTTON_B, "B"},
+ {SDL_CONTROLLER_BUTTON_X, "X"},
+ {SDL_CONTROLLER_BUTTON_Y, "Y"},
+ {SDL_CONTROLLER_BUTTON_LEFTSHOULDER, "LB"},
+ {SDL_CONTROLLER_BUTTON_RIGHTSHOULDER, "RB"},
+ {SDL_CONTROLLER_BUTTON_BACK, "View"},
+ {SDL_CONTROLLER_BUTTON_START, "Menu"},
+ {SDL_CONTROLLER_BUTTON_GUIDE, "Home"},
+ {SDL_CONTROLLER_BUTTON_LEFTSTICK, "Left stick"},
+ {SDL_CONTROLLER_BUTTON_RIGHTSTICK, "Right stick"},
+ {SDL_CONTROLLER_BUTTON_DPAD_UP, "Up"},
+ {SDL_CONTROLLER_BUTTON_DPAD_DOWN, "Down"},
+ {SDL_CONTROLLER_BUTTON_DPAD_LEFT, "Left"},
+ {SDL_CONTROLLER_BUTTON_DPAD_RIGHT, "Right"},
+};
+
+struct NamedAxis {
+ SDL_GameControllerAxis axis;
+ const char *name;
+ bool centred;
+};
+
+const NamedAxis gamepadAxes[] = {
+ {SDL_CONTROLLER_AXIS_LEFTX, "Left stick, left and right", true},
+ {SDL_CONTROLLER_AXIS_LEFTY, "Left stick, up and down", true},
+ {SDL_CONTROLLER_AXIS_RIGHTX, "Right stick, left and right", true},
+ {SDL_CONTROLLER_AXIS_RIGHTY, "Right stick, up and down", true},
+ {SDL_CONTROLLER_AXIS_TRIGGERLEFT, "Left trigger", false},
+ {SDL_CONTROLLER_AXIS_TRIGGERRIGHT, "Right trigger", false},
+};
+
+// SDL's -32768 to 32767 as 0 to 1; a trigger rests at 0.
+double position(Sint16 value, bool centred)
+{
+ const double v = std::clamp(value / 32767.0, -1.0, 1.0);
+ return centred ? (v + 1.0) / 2.0 : std::max(0.0, v);
+}
+
+QVariantMap axis(const QString &name, double value, bool centred)
+{
+ return {{QStringLiteral("name"), name}, {QStringLiteral("value"), qRound(value * 100) / 100.0}, {QStringLiteral("centred"), centred}};
+}
+
+QVariantMap button(const QString &name, bool pressed)
+{
+ return {{QStringLiteral("name"), name}, {QStringLiteral("pressed"), pressed}};
+}
+
+QString battery(SDL_Joystick *joystick)
+{
+ switch (SDL_JoystickCurrentPowerLevel(joystick)) {
+ case SDL_JOYSTICK_POWER_FULL:
+ case SDL_JOYSTICK_POWER_MAX:
+ return QStringLiteral("full");
+ case SDL_JOYSTICK_POWER_MEDIUM:
+ return QStringLiteral("medium");
+ case SDL_JOYSTICK_POWER_LOW:
+ return QStringLiteral("low");
+ case SDL_JOYSTICK_POWER_EMPTY:
+ return QStringLiteral("empty");
+ case SDL_JOYSTICK_POWER_WIRED:
+ return QStringLiteral("wired");
+ default:
+ return {};
+ }
+}
+}
+
+GameControllers::GameControllers(QObject *parent)
+ : QObject(parent)
+{
+ m_timer.setInterval(pollInterval);
+ connect(&m_timer, &QTimer::timeout, this, &GameControllers::poll);
+}
+
+GameControllers::~GameControllers()
+{
+ stop();
+}
+
+void GameControllers::setActive(bool active)
+{
+ if (active == m_active) {
+ return;
+ }
+ m_active = active;
+ if (active) {
+ start();
+ } else {
+ stop();
+ }
+ Q_EMIT activeChanged();
+}
+
+void GameControllers::start()
+{
+ if (m_started) {
+ return;
+ }
+ // SDL would otherwise take over SIGINT and SIGTERM from Qt.
+ SDL_SetHint(SDL_HINT_NO_SIGNAL_HANDLERS, "1");
+ // There is no SDL window to have focus, so input counts regardless.
+ SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1");
+ if (SDL_Init(SDL_INIT_GAMECONTROLLER) != 0) {
+ qWarning("Game controllers: SDL could not start: %s", SDL_GetError());
+ return;
+ }
+ m_started = true;
+ // Controllers already plugged in arrive as added events on the first
+ // poll.
+ poll();
+ m_timer.start();
+}
+
+void GameControllers::stop()
+{
+ m_timer.stop();
+ if (!m_started) {
+ return;
+ }
+ for (const Device &device : std::as_const(m_devices)) {
+ if (device.gamepad) {
+ SDL_GameControllerClose(device.gamepad);
+ }
+ SDL_JoystickClose(device.joystick);
+ }
+ m_devices.clear();
+ SDL_Quit();
+ m_started = false;
+ if (!m_controllers.isEmpty()) {
+ m_controllers.clear();
+ Q_EMIT changed();
+ }
+}
+
+void GameControllers::add(int index)
+{
+ // Steam Input and similar make virtual copies of real controllers.
+ if (SDL_JoystickIsVirtual(index)) {
+ return;
+ }
+ SDL_Joystick *joystick = SDL_JoystickOpen(index);
+ if (!joystick) {
+ return;
+ }
+ const int id = SDL_JoystickInstanceID(joystick);
+ if (m_devices.contains(id)) {
+ SDL_JoystickClose(joystick);
+ return;
+ }
+ Device device;
+ device.joystick = joystick;
+ if (SDL_IsGameController(index)) {
+ device.gamepad = SDL_GameControllerOpen(index);
+ }
+ m_devices.insert(id, device);
+}
+
+void GameControllers::remove(int id)
+{
+ const auto it = m_devices.constFind(id);
+ if (it == m_devices.constEnd()) {
+ return;
+ }
+ if (it->gamepad) {
+ SDL_GameControllerClose(it->gamepad);
+ }
+ SDL_JoystickClose(it->joystick);
+ m_devices.erase(it);
+}
+
+void GameControllers::poll()
+{
+ SDL_Event event{};
+ while (SDL_PollEvent(&event)) {
+ if (event.type == SDL_JOYDEVICEADDED) {
+ add(event.jdevice.which);
+ } else if (event.type == SDL_JOYDEVICEREMOVED) {
+ remove(event.jdevice.which);
+ }
+ }
+ update();
+}
+
+void GameControllers::update()
+{
+ QList<int> ids = m_devices.keys();
+ std::sort(ids.begin(), ids.end());
+
+ QVariantList controllers;
+ for (const int id : std::as_const(ids)) {
+ const Device &device = m_devices[id];
+ QVariantList buttons;
+ QVariantList axes;
+ QString name;
+ if (device.gamepad) {
+ name = QString::fromUtf8(SDL_GameControllerName(device.gamepad));
+ for (const Named &b : gamepadButtons) {
+ if (SDL_GameControllerHasButton(device.gamepad, b.button)) {
+ buttons.append(button(QString::fromLatin1(b.name), SDL_GameControllerGetButton(device.gamepad, b.button) != 0));
+ }
+ }
+ for (const NamedAxis &a : gamepadAxes) {
+ if (SDL_GameControllerHasAxis(device.gamepad, a.axis)) {
+ axes.append(axis(QString::fromLatin1(a.name), position(SDL_GameControllerGetAxis(device.gamepad, a.axis), a.centred), a.centred));
+ }
+ }
+ } else {
+ // A joystick, wheel or pad SDL has no mapping for: its buttons
+ // and axes by number, as the driver reports them.
+ name = QString::fromUtf8(SDL_JoystickName(device.joystick));
+ for (int i = 0; i < SDL_JoystickNumButtons(device.joystick); ++i) {
+ buttons.append(button(QString::number(i + 1), SDL_JoystickGetButton(device.joystick, i) != 0));
+ }
+ for (int i = 0; i < SDL_JoystickNumAxes(device.joystick); ++i) {
+ axes.append(axis(QStringLiteral("Axis %1").arg(i + 1), position(SDL_JoystickGetAxis(device.joystick, i), true), true));
+ }
+ }
+ if (name.isEmpty()) {
+ name = QStringLiteral("Game controller");
+ }
+ controllers.append(QVariantMap{
+ {QStringLiteral("id"), id},
+ {QStringLiteral("name"), name},
+ {QStringLiteral("battery"), battery(device.joystick)},
+ {QStringLiteral("buttons"), buttons},
+ {QStringLiteral("axes"), axes},
+ });
+ }
+
+ if (controllers != m_controllers) {
+ m_controllers = controllers;
+ Q_EMIT changed();
+ }
+}
diff --git a/packages/wildos-settings/src/gamecontrollers.h b/packages/wildos-settings/src/gamecontrollers.h
new file mode 100644
index 0000000..491676b
--- /dev/null
+++ b/packages/wildos-settings/src/gamecontrollers.h
@@ -0,0 +1,60 @@
+#pragma once
+
+#include <QHash>
+#include <QObject>
+#include <QQmlEngine>
+#include <QTimer>
+#include <QVariantList>
+
+struct _SDL_Joystick;
+struct _SDL_GameController;
+
+// Game controllers through SDL2, as KDE's game controller module reads
+// them, so a controller looks here the way games see it: its name, battery
+// and every button and stick live. SDL runs only while the page is open
+// (`active`), as it polls the devices.
+class GameControllers : public QObject
+{
+ Q_OBJECT
+ QML_ELEMENT
+ QML_SINGLETON
+
+ Q_PROPERTY(bool active READ active WRITE setActive NOTIFY activeChanged)
+ Q_PROPERTY(QVariantList controllers READ controllers NOTIFY changed)
+
+public:
+ explicit GameControllers(QObject *parent = nullptr);
+ ~GameControllers() override;
+
+ bool active() const { return m_active; }
+ void setActive(bool active);
+ // Each controller as { id, name, battery, buttons, axes }: battery is
+ // "full", "medium", "low", "empty", "wired" or empty when the
+ // controller does not say; buttons are { name, pressed } and axes
+ // { name, value, centred }, value from 0 to 1 and centred true for a
+ // stick that rests in the middle.
+ QVariantList controllers() const { return m_controllers; }
+
+Q_SIGNALS:
+ void activeChanged();
+ void changed();
+
+private:
+ struct Device {
+ _SDL_Joystick *joystick = nullptr;
+ _SDL_GameController *gamepad = nullptr;
+ };
+
+ void start();
+ void stop();
+ void poll();
+ void add(int index);
+ void remove(int id);
+ void update();
+
+ bool m_active = false;
+ bool m_started = false;
+ QTimer m_timer;
+ QHash<int, Device> m_devices;
+ QVariantList m_controllers;
+};
diff --git a/packages/wildos-settings/src/inputdevices.cpp b/packages/wildos-settings/src/inputdevices.cpp
index dcf0278..963c5ed 100644
--- a/packages/wildos-settings/src/inputdevices.cpp
+++ b/packages/wildos-settings/src/inputdevices.cpp
@@ -65,6 +65,8 @@ void InputDevices::reload()
m_mice.clear();
m_touchpads.clear();
+ m_touchscreens.clear();
+ m_pens.clear();
for (const QString &name : std::as_const(names)) {
QVariantMap device = allProperties(managerPath + QLatin1Char('/') + name);
if (device.isEmpty()) {
@@ -73,6 +75,12 @@ void InputDevices::reload()
device.insert(QStringLiteral("sysName"), name);
if (device.value(QStringLiteral("touchpad")).toBool()) {
m_touchpads << device;
+ } else if (device.value(QStringLiteral("touch")).toBool()) {
+ m_touchscreens << device;
+ } else if (device.value(QStringLiteral("tabletTool")).toBool()) {
+ // The pen side of a tablet; its buttons pad is a separate device
+ // with nothing a person maps or flips.
+ m_pens << device;
} else if (device.value(QStringLiteral("pointer")).toBool() && !device.value(QStringLiteral("tabletTool")).toBool()) {
m_mice << device;
}
@@ -91,3 +99,11 @@ void InputDevices::set(const QString &kind, const QString &property, const QVari
}
reload();
}
+
+void InputDevices::setDevice(const QString &sysName, const QString &property, const QVariant &value)
+{
+ auto message = QDBusMessage::createMethodCall(service, managerPath + QLatin1Char('/') + sysName, properties, QStringLiteral("Set"));
+ message << deviceInterface << property << QVariant::fromValue(QDBusVariant(value));
+ QDBusConnection::sessionBus().call(message, QDBus::Block, 2000);
+ reload();
+}
diff --git a/packages/wildos-settings/src/inputdevices.h b/packages/wildos-settings/src/inputdevices.h
index 14a3156..890fcf2 100644
--- a/packages/wildos-settings/src/inputdevices.h
+++ b/packages/wildos-settings/src/inputdevices.h
@@ -4,9 +4,10 @@
#include <QQmlEngine>
#include <QVariantList>
-// Mice and touchpads as KWin sees them, over its InputDevice D-Bus
-// interface, which is what the KDE mouse and touchpad modules use on
-// Wayland. KWin applies a change at once and saves it for that device.
+// Mice, touchpads, touchscreens and pen tablets as KWin sees them, over
+// its InputDevice D-Bus interface, which is what the KDE mouse, touchpad,
+// touchscreen and tablet modules use on Wayland. KWin applies a change at
+// once and saves it for that device in kcminputrc.
class InputDevices : public QObject
{
Q_OBJECT
@@ -15,18 +16,25 @@ class InputDevices : public QObject
Q_PROPERTY(QVariantList mice READ mice NOTIFY changed)
Q_PROPERTY(QVariantList touchpads READ touchpads NOTIFY changed)
+ Q_PROPERTY(QVariantList touchscreens READ touchscreens NOTIFY changed)
+ Q_PROPERTY(QVariantList pens READ pens NOTIFY changed)
public:
explicit InputDevices(QObject *parent = nullptr);
QVariantList mice() const { return m_mice; }
QVariantList touchpads() const { return m_touchpads; }
+ QVariantList touchscreens() const { return m_touchscreens; }
+ QVariantList pens() const { return m_pens; }
Q_INVOKABLE void reload();
// Sets one property, such as "leftHanded" or "pointerAcceleration", on
// every device of the kind ("mouse" or "touchpad"), as Windows has one
// setting for all mice.
Q_INVOKABLE void set(const QString &kind, const QString &property, const QVariant &value);
+ // Sets one property, such as "outputName" or "enabled", on a single
+ // device by its sysName, as touchscreens and pens are set one by one.
+ Q_INVOKABLE void setDevice(const QString &sysName, const QString &property, const QVariant &value);
Q_SIGNALS:
void changed();
@@ -37,4 +45,6 @@ private Q_SLOTS:
private:
QVariantList m_mice;
QVariantList m_touchpads;
+ QVariantList m_touchscreens;
+ QVariantList m_pens;
};
diff --git a/packages/wildos-settings/src/keyboard.cpp b/packages/wildos-settings/src/keyboard.cpp
index 128687d..230ac77 100644
--- a/packages/wildos-settings/src/keyboard.cpp
+++ b/packages/wildos-settings/src/keyboard.cpp
@@ -23,6 +23,11 @@ const QString interface = QStringLiteral("org.kde.KeyboardLayouts");
// option someone set in the full keyboard module is kept as it is.
const QStringList switchPrefixes = {QStringLiteral("grp:")};
const QStringList capsPrefixes = {QStringLiteral("caps:"), QStringLiteral("ctrl:nocaps"), QStringLiteral("ctrl:swapcaps")};
+const QStringList composePrefixes = {QStringLiteral("compose:")};
+const QStringList altGrPrefixes = {QStringLiteral("lv3:")};
+
+// What KWin builds the keymap with when kxkbrc names no model.
+const QString defaultModel = QStringLiteral("pc104");
// The system layout when the account has none of its own: what the
// installer wrote for the console and the sign-in screen.
@@ -69,8 +74,12 @@ void Keyboard::reload()
QStringList layouts = splitList(layout.readEntry("LayoutList", QString()));
QStringList variants = splitList(layout.readEntry("VariantList", QString()));
m_options = layout.readEntry("Options", QString()).split(QLatin1Char(','), Qt::SkipEmptyParts);
+ m_model = layout.readEntry("Model", QString());
if (!own || layouts.join(QString()).isEmpty()) {
const auto system = systemKeyboard();
+ if (!own && m_model.isEmpty()) {
+ m_model = system.value(QStringLiteral("XKBMODEL"));
+ }
layouts = splitList(system.value(QStringLiteral("XKBLAYOUT"), QStringLiteral("gb")));
variants = splitList(system.value(QStringLiteral("XKBVARIANT")));
if (!own) {
@@ -87,6 +96,9 @@ void Keyboard::reload()
if (m_layouts.isEmpty()) {
m_layouts.append({QStringLiteral("gb"), QString()});
}
+ if (m_model.isEmpty()) {
+ m_model = defaultModel;
+ }
const KConfigGroup keys(KSharedConfig::openConfig(QStringLiteral("kcminputrc"), KConfig::NoGlobals), QStringLiteral("Keyboard"));
m_numLock = keys.readEntry("NumLock", 2);
@@ -107,22 +119,28 @@ void Keyboard::loadNames()
if (!file.open(QIODevice::ReadOnly)) {
return;
}
- // <layout><configItem><name>gb</name><description>English (UK)</description>
- // </configItem><variantList><variant><configItem>... per variant.
+ // <modelList><model><configItem><name>pc105</name><description>
+ // Generic 105-key PC</description>... comes first, then <layoutList>
+ // <layout><configItem><name>gb</name><description>English (UK)
+ // </description></configItem><variantList><variant><configItem>...
+ // per variant. The option groups after the layouts use the same
+ // elements, so reading stops there.
QXmlStreamReader xml(&file);
+ QString section;
QString layout;
QString name;
QString description;
bool inVariant = false;
while (!xml.atEnd()) {
xml.readNext();
- // The option groups after the layouts use the same elements.
if (xml.isEndElement() && xml.name() == QLatin1String("layoutList")) {
break;
}
if (xml.isStartElement()) {
const auto tag = xml.name();
- if (tag == QLatin1String("layout")) {
+ if (tag == QLatin1String("modelList") || tag == QLatin1String("layoutList")) {
+ section = tag.toString();
+ } else if (tag == QLatin1String("layout")) {
layout.clear();
inVariant = false;
} else if (tag == QLatin1String("variant")) {
@@ -139,7 +157,12 @@ void Keyboard::loadNames()
if (name.isEmpty() || description.isEmpty()) {
continue;
}
- if (!inVariant) {
+ if (section == QLatin1String("modelList")) {
+ m_modelNames.insert(name, description);
+ m_models.append(QVariantMap{{QStringLiteral("model"), name}, {QStringLiteral("name"), description}});
+ } else if (section != QLatin1String("layoutList")) {
+ continue;
+ } else if (!inVariant) {
layout = name;
m_names.insert(layout + QLatin1Char('|'), description);
m_available.append(QVariantMap{{QStringLiteral("layout"), layout}, {QStringLiteral("variant"), QString()}, {QStringLiteral("name"), description}});
@@ -156,6 +179,9 @@ void Keyboard::loadNames()
std::sort(m_available.begin(), m_available.end(), [&collator](const QVariant &a, const QVariant &b) {
return collator.compare(a.toMap().value(QStringLiteral("name")).toString(), b.toMap().value(QStringLiteral("name")).toString()) < 0;
});
+ std::sort(m_models.begin(), m_models.end(), [&collator](const QVariant &a, const QVariant &b) {
+ return collator.compare(a.toMap().value(QStringLiteral("name")).toString(), b.toMap().value(QStringLiteral("name")).toString()) < 0;
+ });
}
QString Keyboard::nameOf(const Layout &l) const
@@ -183,6 +209,18 @@ QVariantList Keyboard::available()
return m_available;
}
+QVariantList Keyboard::models()
+{
+ loadNames();
+ return m_models;
+}
+
+QString Keyboard::modelName() const
+{
+ const_cast<Keyboard *>(this)->loadNames();
+ return m_modelNames.value(m_model, m_model);
+}
+
QString Keyboard::optionWithPrefix(const QStringList &prefixes) const
{
for (const QString &option : m_options) {
@@ -219,6 +257,16 @@ QString Keyboard::capsLock() const
return optionWithPrefix(capsPrefixes);
}
+QString Keyboard::compose() const
+{
+ return optionWithPrefix(composePrefixes);
+}
+
+QString Keyboard::altGr() const
+{
+ return optionWithPrefix(altGrPrefixes);
+}
+
void Keyboard::saveLayouts()
{
QStringList layouts;
@@ -234,6 +282,7 @@ void Keyboard::saveLayouts()
// One empty display name per layout, as the keyboard module writes it,
// so the indicator shows each layout's own short name.
group.writeEntry("DisplayNames", QStringList(layouts.size(), QString()).join(QLatin1Char(',')));
+ group.writeEntry("Model", m_model);
group.writeEntry("Options", m_options.join(QLatin1Char(',')));
// Without this KWin adds the options to the ones it started with, so a
// switch key once chosen could never be taken away again.
@@ -316,6 +365,25 @@ void Keyboard::setCapsLock(const QString &option)
replaceOptions(capsPrefixes, option);
}
+void Keyboard::setCompose(const QString &option)
+{
+ replaceOptions(composePrefixes, option);
+}
+
+void Keyboard::setAltGr(const QString &option)
+{
+ replaceOptions(altGrPrefixes, option);
+}
+
+void Keyboard::setModel(const QString &model)
+{
+ if (model.isEmpty() || model == m_model) {
+ return;
+ }
+ m_model = model;
+ saveLayouts();
+}
+
void Keyboard::saveRepeat()
{
// Notify: KWin watches kcminputrc and applies the change at once.
diff --git a/packages/wildos-settings/src/keyboard.h b/packages/wildos-settings/src/keyboard.h
index e96a84a..52e2049 100644
--- a/packages/wildos-settings/src/keyboard.h
+++ b/packages/wildos-settings/src/keyboard.h
@@ -5,10 +5,11 @@
#include <QStringList>
#include <QVariantList>
-// Keyboard layouts, the key that switches between them, Caps Lock and key
-// repeat, kept where KDE's keyboard module keeps them: the layouts and XKB
-// options in kxkbrc (KWin rereads it on org.kde.keyboard reloadConfig) and
-// repeat and Num Lock in kcminputrc, which KWin watches.
+// Keyboard layouts, the key that switches between them, Caps Lock, the
+// compose and Alt Gr keys, the keyboard model and key repeat, kept where
+// KDE's keyboard module keeps them: the layouts, model and XKB options in
+// kxkbrc (KWin rereads it on org.kde.keyboard reloadConfig) and repeat and
+// Num Lock in kcminputrc, which KWin watches.
class Keyboard : public QObject
{
Q_OBJECT
@@ -19,6 +20,10 @@ class Keyboard : public QObject
Q_PROPERTY(int current READ current NOTIFY currentChanged)
Q_PROPERTY(QString switchKeys READ switchKeys NOTIFY changed)
Q_PROPERTY(QString capsLock READ capsLock NOTIFY changed)
+ Q_PROPERTY(QString compose READ compose NOTIFY changed)
+ Q_PROPERTY(QString altGr READ altGr NOTIFY changed)
+ Q_PROPERTY(QString model READ model NOTIFY changed)
+ Q_PROPERTY(QString modelName READ modelName NOTIFY changed)
Q_PROPERTY(int numLock READ numLock NOTIFY changed)
Q_PROPERTY(bool repeat READ repeat NOTIFY changed)
Q_PROPERTY(int repeatDelay READ repeatDelay NOTIFY changed)
@@ -31,6 +36,10 @@ public:
int current() const { return m_current; }
QString switchKeys() const;
QString capsLock() const;
+ QString compose() const;
+ QString altGr() const;
+ QString model() const { return m_model; }
+ QString modelName() const;
int numLock() const { return m_numLock; }
bool repeat() const { return m_repeat; }
int repeatDelay() const { return m_repeatDelay; }
@@ -39,12 +48,17 @@ public:
// Every layout and variant XKB knows, as { layout, variant, name },
// sorted by name. Read once, on first use.
Q_INVOKABLE QVariantList available();
+ // Every keyboard model XKB knows, as { model, name }, sorted by name.
+ Q_INVOKABLE QVariantList models();
Q_INVOKABLE void add(const QString &layout, const QString &variant);
Q_INVOKABLE void remove(int index);
Q_INVOKABLE void move(int from, int to);
Q_INVOKABLE void use(int index);
Q_INVOKABLE void setSwitchKeys(const QString &option);
Q_INVOKABLE void setCapsLock(const QString &option);
+ Q_INVOKABLE void setCompose(const QString &option);
+ Q_INVOKABLE void setAltGr(const QString &option);
+ Q_INVOKABLE void setModel(const QString &model);
Q_INVOKABLE void setNumLock(int state);
Q_INVOKABLE void setRepeat(bool on);
Q_INVOKABLE void setRepeatDelay(int ms);
@@ -74,6 +88,7 @@ private:
QList<Layout> m_layouts;
QStringList m_options;
+ QString m_model;
int m_current = 0;
int m_numLock = 2;
bool m_repeat = true;
@@ -83,4 +98,6 @@ private:
bool m_namesLoaded = false;
QHash<QString, QString> m_names;
QVariantList m_available;
+ QHash<QString, QString> m_modelNames;
+ QVariantList m_models;
};
diff --git a/packages/wildos-settings/src/language.cpp b/packages/wildos-settings/src/language.cpp
index 37f0eae..c1fa6f9 100644
--- a/packages/wildos-settings/src/language.cpp
+++ b/packages/wildos-settings/src/language.cpp
@@ -1,6 +1,7 @@
#include "language.h"
#include <KConfigGroup>
+#include <KFormat>
#include <KSharedConfig>
#include <QCollator>
@@ -8,6 +9,7 @@
#include <QDBusMessage>
#include <QDBusPendingCall>
#include <QDate>
+#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QLocale>
@@ -27,6 +29,13 @@ const QStringList categories = {QStringLiteral("LC_NUMERIC"), QStringLiteral("LC
QStringLiteral("LC_PAPER"), QStringLiteral("LC_ADDRESS"), QStringLiteral("LC_NAME"),
QStringLiteral("LC_TELEPHONE")};
+// The parts More format options offers on their own, under the keys
+// kcm_regionandlang writes (regionandlangsettingsbase.kcfg). Addresses,
+// names and telephone numbers are left to the regional format, as Windows
+// leaves them.
+const QStringList shownCategories = {QStringLiteral("LC_NUMERIC"), QStringLiteral("LC_MONETARY"), QStringLiteral("LC_TIME"),
+ QStringLiteral("LC_MEASUREMENT"), QStringLiteral("LC_PAPER")};
+
// "en_GB.utf8", "en_GB.UTF-8" and "en_GB" are the same locale.
QString canonical(QString locale)
{
@@ -107,6 +116,9 @@ Language::Language(QObject *parent)
if (m_sessionLanguage.isEmpty() || m_sessionLanguage == QLatin1String("en")) {
m_sessionLanguage = m_sessionFormat.startsWith(QLatin1String("en_")) ? fallbackLanguage : m_sessionFormat.section(QLatin1Char('_'), 0, 0);
}
+ for (const QString &key : shownCategories) {
+ m_sessionCategories.insert(key, canonical(qEnvironmentVariable(key.toLatin1().constData())));
+ }
read();
}
@@ -131,12 +143,38 @@ void Language::read()
m_detailed = true;
}
}
+ m_overrides.clear();
+ for (const QString &key : shownCategories) {
+ const QString value = canonical(formats.readEntry(key, QString()));
+ m_overrides.insert(key, value == m_format ? QString() : value);
+ }
+ auto globals = KSharedConfig::openConfig(QStringLiteral("kdeglobals"));
+ globals->reparseConfiguration();
+ const KConfigGroup locale(globals, QStringLiteral("Locale"));
+ m_fileSizeUnits = locale.readEntry("BinaryUnitDialect", int(KFormat::IECBinaryDialect));
Q_EMIT changed();
}
bool Language::needsSignOut() const
{
- return m_language != m_sessionLanguage || m_format != m_sessionFormat;
+ if (m_language != m_sessionLanguage || m_format != m_sessionFormat) {
+ return true;
+ }
+ // A part chosen on its own reaches apps as its LC_ variable at sign-in;
+ // one this session did not get as a variable came from LANG.
+ for (const QString &key : shownCategories) {
+ const QString chosen = m_overrides.value(key).toString();
+ const QString session = m_sessionCategories.value(key).toString();
+ if (!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")) {
+ return true;
+ }
+ }
+ return false;
}
QVariantList Language::languages() const
@@ -309,6 +347,102 @@ void Language::setFormat(const QString &locale)
});
}
+QString Language::example(const QString &category, const QString &format) const
+{
+ const QString name = format.section(QLatin1Char('.'), 0, 0);
+ const QLocale locale(name);
+ if (category == QLatin1String("LC_NUMERIC")) {
+ return locale.toString(1234.56, 'f', 2);
+ }
+ if (category == QLatin1String("LC_MONETARY")) {
+ return locale.toCurrencyString(1234.56);
+ }
+ if (category == QLatin1String("LC_TIME")) {
+ const QDateTime now = QDateTime::currentDateTime();
+ return locale.toString(now.date(), QLocale::ShortFormat) + QStringLiteral(", ") + locale.toString(now.time(), QLocale::ShortFormat);
+ }
+ if (category == QLatin1String("LC_MEASUREMENT")) {
+ switch (locale.measurementSystem()) {
+ case QLocale::ImperialUSSystem:
+ return QStringLiteral("Inches, feet and pounds");
+ case QLocale::ImperialUKSystem:
+ return QStringLiteral("Metric, with miles and pints");
+ default:
+ return QStringLiteral("Centimetres, metres and kilograms");
+ }
+ }
+ if (category == QLatin1String("LC_PAPER")) {
+ // The same list KDE's region module uses (exampleutility.cpp):
+ // these regions measure in metric and still print on Letter.
+ static const QSet<QString> letter = {
+ QStringLiteral("en_CA"), QStringLiteral("en_PH"), QStringLiteral("es_BO"), QStringLiteral("es_CL"), QStringLiteral("es_CO"),
+ QStringLiteral("es_CR"), QStringLiteral("es_GT"), QStringLiteral("es_MX"), QStringLiteral("es_NI"), QStringLiteral("es_PA"),
+ QStringLiteral("es_PR"), QStringLiteral("es_SV"), QStringLiteral("es_VE"), QStringLiteral("fil_PH"), QStringLiteral("fr_CA"),
+ QStringLiteral("ik_CA"), QStringLiteral("iu_CA"), QStringLiteral("miq_NI"), QStringLiteral("nhn_MX"), QStringLiteral("shs_CA"),
+ QStringLiteral("tl_PH")};
+ const bool isLetter = letter.contains(name) || locale.measurementSystem() == QLocale::ImperialUSSystem;
+ return isLetter ? QStringLiteral("Letter, 8.5 by 11 inches") : QStringLiteral("A4, 210 by 297 mm");
+ }
+ return {};
+}
+
+void Language::setCategory(const QString &category, const QString &locale)
+{
+ if (!shownCategories.contains(category) || m_busy) {
+ return;
+ }
+ QString chosen = canonical(locale);
+ if (chosen == m_format) {
+ chosen.clear();
+ }
+ if (chosen == m_overrides.value(category).toString()) {
+ return;
+ }
+ 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);
+ }
+ config->sync();
+ read();
+ };
+ if (chosen.isEmpty()) {
+ write();
+ } else {
+ ensure({chosen}, write);
+ }
+}
+
+QString Language::fileSizeExample(int units) const
+{
+ return KFormat().formatByteSize(1536000, 1, KFormat::BinaryUnitDialect(units));
+}
+
+void Language::setFileSizeUnits(int units)
+{
+ if (units < KFormat::IECBinaryDialect || units > KFormat::MetricBinaryDialect || units == m_fileSizeUnits) {
+ return;
+ }
+ // Saved as kcm_regionandlang saves it: the IEC default is not stored.
+ // KFormat reads this when an app starts, so open apps keep the old
+ // units until they are restarted.
+ auto config = KSharedConfig::openConfig(QStringLiteral("kdeglobals"));
+ KConfigGroup locale(config, QStringLiteral("Locale"));
+ if (units == KFormat::IECBinaryDialect) {
+ locale.deleteEntry("BinaryUnitDialect", KConfig::Notify);
+ } else {
+ locale.writeEntry("BinaryUnitDialect", units, KConfig::Notify);
+ }
+ config->sync();
+ read();
+}
+
void Language::signOut()
{
auto message = QDBusMessage::createMethodCall(QStringLiteral("org.kde.Shutdown"), QStringLiteral("/Shutdown"), QStringLiteral("org.kde.Shutdown"),
diff --git a/packages/wildos-settings/src/language.h b/packages/wildos-settings/src/language.h
index 99627e4..6ee790f 100644
--- a/packages/wildos-settings/src/language.h
+++ b/packages/wildos-settings/src/language.h
@@ -12,7 +12,8 @@
// and the LC_ variables at the next sign-in. A locale the system has not
// generated yet is generated first through
// /usr/libexec/wildos/settings-locale under pkexec, as glibc cannot use it
-// otherwise.
+// otherwise. How file sizes are counted lives beside them in kdeglobals,
+// where KDE's region module keeps it too.
class Language : public QObject
{
Q_OBJECT
@@ -24,6 +25,12 @@ class Language : public QObject
Q_PROPERTY(bool needsSignOut READ needsSignOut NOTIFY changed)
Q_PROPERTY(bool busy READ busy NOTIFY busyChanged)
Q_PROPERTY(bool detailed READ detailed NOTIFY changed)
+ // { LC_NUMERIC: "de_DE.UTF-8", LC_TIME: "" ... }, the formats chosen on
+ // their own in More format options; empty follows the regional format.
+ Q_PROPERTY(QVariantMap overrides READ overrides NOTIFY changed)
+ // KFormat's BinaryUnitDialect: 0 KiB (1,024 bytes), 1 KB (1,024 bytes),
+ // 2 kB (1,000 bytes).
+ Q_PROPERTY(int fileSizeUnits READ fileSizeUnits NOTIFY changed)
public:
explicit Language(QObject *parent = nullptr);
@@ -33,6 +40,8 @@ public:
bool needsSignOut() const;
bool busy() const { return m_busy; }
bool detailed() const { return m_detailed; }
+ QVariantMap overrides() const { return m_overrides; }
+ int fileSizeUnits() const { return m_fileSizeUnits; }
// [{ value: "de", text: "Deutsch (Deutschland)", english: "German" }],
// the languages the desktop has translations for, UK English first.
@@ -44,6 +53,13 @@ public:
Q_INVOKABLE QVariantMap examples(const QString &format) const;
Q_INVOKABLE void setLanguage(const QString &code);
Q_INVOKABLE void setFormat(const QString &locale);
+ // How one part of a format looks: "1,234.56" for LC_NUMERIC, "A4" for
+ // LC_PAPER.
+ Q_INVOKABLE QString example(const QString &category, const QString &locale) const;
+ // An empty locale gives the part back to the regional format.
+ Q_INVOKABLE void setCategory(const QString &category, const QString &locale);
+ Q_INVOKABLE QString fileSizeExample(int units) const;
+ Q_INVOKABLE void setFileSizeUnits(int units);
Q_INVOKABLE void signOut();
Q_SIGNALS:
@@ -59,6 +75,9 @@ private:
QString m_format;
QString m_sessionLanguage;
QString m_sessionFormat;
+ QVariantMap m_sessionCategories;
+ QVariantMap m_overrides;
+ int m_fileSizeUnits = 0;
bool m_detailed = false;
bool m_busy = false;
};
diff --git a/packages/wildos-settings/src/main.cpp b/packages/wildos-settings/src/main.cpp
index b8d629d..3a9b56e 100644
--- a/packages/wildos-settings/src/main.cpp
+++ b/packages/wildos-settings/src/main.cpp
@@ -2,6 +2,7 @@
#include <KColorScheme>
#include <KConfigGroup>
+#include <KConfigWatcher>
#include <KLocalizedString>
#include <KSharedConfig>
@@ -15,6 +16,7 @@
#include <QQuickStyle>
#include <QQuickWindow>
#include <QStandardPaths>
+#include <QTimer>
namespace
{
@@ -59,6 +61,34 @@ private:
QQmlApplicationEngine *m_engine;
};
+// The KDE modules shown inside Settings draw with the colour scheme.
+// Settings always uses a Wild OS one, light or dark to match the account's
+// colours, whatever scheme the account has, so a module never shows a page
+// of another look inside the window. This is what KColorSchemeManager does
+// for an app that picks its own scheme. Light or dark is judged by the
+// window colour, as every other part of Wild OS judges it.
+static void applyScheme(QApplication &app)
+{
+ const KColorScheme window(QPalette::Active, KColorScheme::Window, KSharedConfig::openConfig(QStringLiteral("kdeglobals")));
+ const bool light = window.background().color().lightness() > 127;
+ QString scheme;
+ if (light) {
+ scheme = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("color-schemes/WildOSLight.colors"));
+ }
+ if (scheme.isEmpty()) {
+ scheme = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("color-schemes/WildOS.colors"));
+ }
+ if (scheme.isEmpty() || app.property("KDE_COLOR_SCHEME_PATH").toString() == scheme) {
+ return;
+ }
+ app.setProperty("KDE_COLOR_SCHEME_PATH", scheme);
+ const QPalette palette = KColorScheme::createApplicationPalette(KSharedConfig::openConfig(scheme, KConfig::SimpleConfig));
+ app.setPalette(palette);
+ // QML modules miss QApplication::setPalette alone; plasma-integration
+ // sends this too when it changes the palette.
+ Q_EMIT app.paletteChanged(palette);
+}
+
int main(int argc, char *argv[])
{
// Widgets are needed for the handful of KDE modules that are still
@@ -95,23 +125,22 @@ int main(int argc, char *argv[])
return 0;
}
- // The KDE modules shown inside Settings draw with the colour scheme.
- // Settings always uses a Wild OS one (light when the account picked
- // WildOSLight, dark otherwise), whatever else the account has, so a
- // module never shows a page of another look inside the window. This is
- // what KColorSchemeManager does for an app that picks its own scheme.
- const QString chosen = KSharedConfig::openConfig(QStringLiteral("kdeglobals"))->group(QStringLiteral("General")).readEntry("ColorScheme");
- QString scheme;
- if (chosen == QLatin1String("WildOSLight")) {
- scheme = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("color-schemes/WildOSLight.colors"));
- }
- if (scheme.isEmpty()) {
- scheme = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("color-schemes/WildOS.colors"));
- }
- if (!scheme.isEmpty()) {
- app.setProperty("KDE_COLOR_SCHEME_PATH", scheme);
- app.setPalette(KColorScheme::createApplicationPalette(KSharedConfig::openConfig(scheme, KConfig::SimpleConfig)));
- }
+ applyScheme(app);
+ // Kept up to date while Settings is open: plasma-integration leaves an
+ // app with its own scheme alone, so a switch to light or dark (by hand
+ // or at sunset) left KDE's modules in the old colours until a restart.
+ auto watcher = KConfigWatcher::create(KSharedConfig::openConfig(QStringLiteral("kdeglobals")));
+ auto schemeTimer = new QTimer(&app);
+ schemeTimer->setSingleShot(true);
+ schemeTimer->setInterval(150);
+ QObject::connect(schemeTimer, &QTimer::timeout, &app, [&app] {
+ applyScheme(app);
+ });
+ QObject::connect(watcher.data(), &KConfigWatcher::configChanged, &app, [schemeTimer](const KConfigGroup &group) {
+ if (group.name() == QLatin1String("General") || group.name().startsWith(QLatin1String("Colors:"))) {
+ schemeTimer->start();
+ }
+ });
// KDE's modules are written against the desktop style, which in turn
// follows the Wild OS Kvantum theme.
diff --git a/packages/wildos-settings/src/netshared.h b/packages/wildos-settings/src/netshared.h
new file mode 100644
index 0000000..87ec099
--- /dev/null
+++ b/packages/wildos-settings/src/netshared.h
@@ -0,0 +1,254 @@
+#pragma once
+
+// Shared by Settings (network.cpp) and the root service (networkd/main.cpp),
+// so both agree on what each DNS choice means and read NetworkManager's
+// connection profiles the same way.
+
+#include <QDBusArgument>
+#include <QDBusConnection>
+#include <QDBusMessage>
+#include <QHostAddress>
+#include <QMap>
+#include <QMetaType>
+#include <QStringList>
+#include <QVariantMap>
+#include <QtEndian>
+
+namespace NetShared
+{
+
+using Profile = QMap<QString, QVariantMap>;
+
+inline const QString nmService = QStringLiteral("org.freedesktop.NetworkManager");
+
+// Every DNS service is reached over TLS, so the server name travels with
+// each address in NetworkManager's "address#name" form.
+struct DnsProvider {
+ const char *id;
+ const char *ipv4;
+ const char *ipv6;
+};
+
+inline constexpr DnsProvider dnsProviders[] = {
+ {"quad9", "9.9.9.9#dns.quad9.net,149.112.112.112#dns.quad9.net", "2620:fe::fe#dns.quad9.net,2620:fe::9#dns.quad9.net"},
+ {"cloudflare", "1.1.1.1#cloudflare-dns.com,1.0.0.1#cloudflare-dns.com",
+ "2606:4700:4700::1111#cloudflare-dns.com,2606:4700:4700::1001#cloudflare-dns.com"},
+ {"mullvad", "194.242.2.2#dns.mullvad.net", "2a07:e340::2#dns.mullvad.net"},
+};
+
+inline const DnsProvider *provider(const QString &id)
+{
+ for (const auto &p : dnsProviders) {
+ if (id == QLatin1String(p.id)) {
+ return &p;
+ }
+ }
+ return nullptr;
+}
+
+inline QString serverAddress(const QString &entry)
+{
+ QString address = entry.section(QLatin1Char('#'), 0, 0).trimmed();
+ if (address.startsWith(QLatin1Char('['))) {
+ address = address.mid(1).section(QLatin1Char(']'), 0, 0);
+ }
+ return address;
+}
+
+// The choice a profile's DNS servers amount to. A profile with no servers
+// of its own that still takes the network's is "automatic".
+inline QString dnsChoice(const QStringList &servers, bool ignoreAuto)
+{
+ if (servers.isEmpty()) {
+ return ignoreAuto ? QStringLiteral("custom") : QStringLiteral("automatic");
+ }
+ for (const auto &p : dnsProviders) {
+ const QStringList known = (QString::fromLatin1(p.ipv4) + QLatin1Char(',') + QString::fromLatin1(p.ipv6)).split(QLatin1Char(','));
+ for (const QString &k : known) {
+ if (servers.contains(serverAddress(k))) {
+ return QString::fromLatin1(p.id);
+ }
+ }
+ }
+ return QStringLiteral("custom");
+}
+
+// The "nmcli connection modify" arguments for a choice. A family whose
+// method takes no DNS servers (disabled, link-local, ignore, shared) is left
+// alone, since NetworkManager refuses the profile otherwise. Custom servers
+// are encrypted only when every one of them names its TLS server.
+//
+// asDefault is Wild OS's own default for a network nobody has chosen DNS
+// for: the provider first and encrypted wherever the network allows, with
+// the network's own servers kept behind it. Hotel and café Wi-Fi that hides
+// its sign-in page behind its own DNS then still works. A provider someone
+// picks in Settings is strict instead: encrypted or nothing.
+inline QStringList dnsModifyArgs(const QString &choice, const QStringList &custom, bool ipv4, bool ipv6, bool asDefault = false)
+{
+ QStringList v4;
+ QStringList v6;
+ QString tls = QStringLiteral("yes");
+ bool ignoreAuto = true;
+ if (const DnsProvider *p = provider(choice)) {
+ v4 = QString::fromLatin1(p->ipv4).split(QLatin1Char(','));
+ v6 = QString::fromLatin1(p->ipv6).split(QLatin1Char(','));
+ if (asDefault) {
+ tls = QStringLiteral("opportunistic");
+ ignoreAuto = false;
+ }
+ } else if (choice == QLatin1String("custom")) {
+ for (const QString &entry : custom) {
+ const QHostAddress address(serverAddress(entry));
+ if (address.protocol() == QAbstractSocket::IPv6Protocol) {
+ v6.append(entry);
+ } else {
+ v4.append(entry);
+ }
+ if (!entry.contains(QLatin1Char('#'))) {
+ tls = QStringLiteral("no");
+ }
+ }
+ } else {
+ tls = QStringLiteral("default");
+ ignoreAuto = false;
+ }
+ QStringList args;
+ if (ipv4) {
+ args << QStringLiteral("ipv4.dns") << v4.join(QLatin1Char(','))
+ << QStringLiteral("ipv4.ignore-auto-dns") << (ignoreAuto ? QStringLiteral("yes") : QStringLiteral("no"));
+ }
+ if (ipv6) {
+ args << QStringLiteral("ipv6.dns") << v6.join(QLatin1Char(','))
+ << QStringLiteral("ipv6.ignore-auto-dns") << (ignoreAuto ? QStringLiteral("yes") : QStringLiteral("no"));
+ }
+ args << QStringLiteral("connection.dns-over-tls") << tls;
+ return args;
+}
+
+inline bool ipv4TakesDns(const QString &method)
+{
+ return method.isEmpty() || method == QLatin1String("auto") || method == QLatin1String("manual");
+}
+
+inline bool ipv6TakesDns(const QString &method)
+{
+ return method.isEmpty() || method == QLatin1String("auto") || method == QLatin1String("dhcp") || method == QLatin1String("manual");
+}
+
+// D-Bus hands nested values over as QDBusArgument unless something has
+// registered the type, so both shapes are read.
+template<typename T>
+T unpack(const QVariant &value)
+{
+ if (value.metaType() == QMetaType::fromType<QDBusArgument>()) {
+ T result;
+ value.value<QDBusArgument>() >> result;
+ return result;
+ }
+ return qvariant_cast<T>(value);
+}
+
+// The profile without its secrets, which is all either side needs.
+inline Profile profile(const QString &path)
+{
+ QDBusMessage call = QDBusMessage::createMethodCall(nmService, path, QStringLiteral("org.freedesktop.NetworkManager.Settings.Connection"),
+ QStringLiteral("GetSettings"));
+ const QDBusMessage reply = QDBusConnection::systemBus().call(call, QDBus::Block, 5000);
+ if (reply.type() != QDBusMessage::ReplyMessage || reply.arguments().isEmpty()) {
+ return {};
+ }
+ return unpack<Profile>(reply.arguments().constFirst());
+}
+
+// DNS servers as written in the profile: the text form (with server names)
+// where NetworkManager offers it, else the plain address lists.
+inline QStringList profileDns(const Profile &p, const QString &family)
+{
+ const QVariantMap ip = p.value(family);
+ const QStringList data = unpack<QStringList>(ip.value(QStringLiteral("dns-data")));
+ if (!data.isEmpty()) {
+ return data;
+ }
+ QStringList servers;
+ if (family == QLatin1String("ipv4")) {
+ for (const uint raw : unpack<QList<uint>>(ip.value(QStringLiteral("dns")))) {
+ // Network byte order, as it sits in the message.
+ servers.append(QHostAddress(qFromBigEndian<quint32>(raw)).toString());
+ }
+ } else {
+ for (const QByteArray &raw : unpack<QList<QByteArray>>(ip.value(QStringLiteral("dns")))) {
+ if (raw.size() == 16) {
+ servers.append(QHostAddress(reinterpret_cast<const quint8 *>(raw.constData())).toString());
+ }
+ }
+ }
+ return servers;
+}
+
+inline QStringList profileDnsAddresses(const Profile &p)
+{
+ QStringList addresses;
+ for (const QString &family : {QStringLiteral("ipv4"), QStringLiteral("ipv6")}) {
+ for (const QString &entry : profileDns(p, family)) {
+ addresses.append(serverAddress(entry));
+ }
+ }
+ return addresses;
+}
+
+// The hosts a VPN connects to: WireGuard's peer endpoints, OpenVPN's
+// remotes ("host[:port[:proto]]" or "host port", comma separated).
+inline QStringList vpnServers(const Profile &p)
+{
+ QStringList hosts;
+ const auto addHost = [&hosts](QString text) {
+ text = text.trimmed();
+ if (text.isEmpty()) {
+ return;
+ }
+ QString host;
+ if (text.startsWith(QLatin1Char('['))) {
+ host = text.mid(1).section(QLatin1Char(']'), 0, 0);
+ } else if (text.count(QLatin1Char(':')) > 2) {
+ host = text.section(QLatin1Char(' '), 0, 0);
+ } else {
+ host = text.section(QLatin1Char(' '), 0, 0).section(QLatin1Char(':'), 0, 0);
+ }
+ if (!host.isEmpty() && !hosts.contains(host)) {
+ hosts.append(host);
+ }
+ };
+ const QVariantMap wireguard = p.value(QStringLiteral("wireguard"));
+ for (const QVariantMap &peer : unpack<QList<QVariantMap>>(wireguard.value(QStringLiteral("peers")))) {
+ addHost(peer.value(QStringLiteral("endpoint")).toString());
+ }
+ const QVariantMap vpn = p.value(QStringLiteral("vpn"));
+ const auto data = unpack<QMap<QString, QString>>(vpn.value(QStringLiteral("data")));
+ for (const QString &remote : data.value(QStringLiteral("remote")).split(QLatin1Char(','))) {
+ addHost(remote);
+ }
+ return hosts;
+}
+
+// Splits one line of "nmcli -t" output, where a literal colon or backslash
+// inside a field is escaped with a backslash.
+inline QStringList terseFields(const QString &line)
+{
+ QStringList fields;
+ QString field;
+ for (int i = 0; i < line.size(); ++i) {
+ const QChar c = line.at(i);
+ if (c == QLatin1Char('\\') && i + 1 < line.size()) {
+ field.append(line.at(++i));
+ } else if (c == QLatin1Char(':')) {
+ fields.append(field);
+ field.clear();
+ } else {
+ field.append(c);
+ }
+ }
+ fields.append(field);
+ return fields;
+}
+
+}
diff --git a/packages/wildos-settings/src/network.cpp b/packages/wildos-settings/src/network.cpp
new file mode 100644
index 0000000..c4e3ac7
--- /dev/null
+++ b/packages/wildos-settings/src/network.cpp
@@ -0,0 +1,872 @@
+#include "network.h"
+
+#include <NetworkManagerQt/AccessPoint>
+#include <NetworkManagerQt/ActiveConnection>
+#include <NetworkManagerQt/Connection>
+#include <NetworkManagerQt/Device>
+#include <NetworkManagerQt/IpConfig>
+#include <NetworkManagerQt/Manager>
+#include <NetworkManagerQt/Settings>
+#include <NetworkManagerQt/WiredDevice>
+#include <NetworkManagerQt/WirelessDevice>
+
+#include "netshared.h"
+
+#include <KConfigGroup>
+#include <KSharedConfig>
+
+#include <QDBusConnection>
+#include <QDBusMessage>
+#include <QDBusPendingCallWatcher>
+#include <QDBusPendingReply>
+#include <QDBusVariant>
+#include <QDebug>
+#include <QFile>
+#include <QFileInfo>
+#include <QHostAddress>
+#include <QProcess>
+#include <QRegularExpression>
+#include <QSet>
+#include <QTemporaryDir>
+#include <QTimer>
+
+#include <algorithm>
+#include <memory>
+#include <utility>
+
+namespace
+{
+const QString killSwitchFile = QStringLiteral("/etc/wildos/vpn-kill-switch");
+const QString killSwitchStateFile = QStringLiteral("/run/wildos/kill-switch");
+const QString networkHelper = QStringLiteral("/usr/libexec/wildos/settings-network");
+
+const QString wifiType = QStringLiteral("802-11-wireless");
+const QString wiredType = QStringLiteral("802-3-ethernet");
+
+// NM_SETTINGS_CONNECTION_FLAG_NM_GENERATED and _EXTERNAL: profiles
+// NetworkManager made up for interfaces something else set up, such as the
+// Mullvad app's tunnel. They are not the person's to switch or forget.
+constexpr uint generatedFlags = 0x2 | 0x8;
+
+// NMActiveConnectionState
+constexpr int activating = 1;
+constexpr int activated = 2;
+
+QString str(const QVariantMap &map, const char *key)
+{
+ return map.value(QString::fromLatin1(key)).toString();
+}
+
+uint connectionFlags(const QString &path)
+{
+ QDBusMessage call = QDBusMessage::createMethodCall(NetShared::nmService, path, QStringLiteral("org.freedesktop.DBus.Properties"),
+ QStringLiteral("Get"));
+ call << QStringLiteral("org.freedesktop.NetworkManager.Settings.Connection") << QStringLiteral("Flags");
+ const QDBusMessage reply = QDBusConnection::systemBus().call(call, QDBus::Block, 3000);
+ if (reply.type() != QDBusMessage::ReplyMessage || reply.arguments().isEmpty()) {
+ return 0;
+ }
+ return reply.arguments().constFirst().value<QDBusVariant>().variant().toUInt();
+}
+
+// "wg-home-office" from "Home office": WireGuard names the interface after
+// the file, and Linux allows 15 characters.
+QString interfaceFor(const QString &name, const QStringList &taken)
+{
+ QString base = name.toLower();
+ base.replace(QRegularExpression(QStringLiteral("[^a-z0-9]+")), QStringLiteral("-"));
+ base.remove(QRegularExpression(QStringLiteral("^-+|-+$")));
+ if (base.isEmpty()) {
+ base = QStringLiteral("vpn");
+ }
+ QString candidate = (QStringLiteral("wg-") + base).left(15);
+ while (candidate.endsWith(QLatin1Char('-'))) {
+ candidate.chop(1);
+ }
+ const QString stem = candidate.left(12);
+ for (int n = 2; taken.contains(candidate) && n < 100; ++n) {
+ candidate = stem + QString::number(n);
+ }
+ return candidate;
+}
+
+bool isWireGuardKey(const QString &key)
+{
+ const QByteArray raw = QByteArray::fromBase64(key.trimmed().toLatin1(), QByteArray::AbortOnBase64DecodingErrors);
+ return raw.size() == 32;
+}
+
+// "255.255.255.0", "24" or "/24" to 24; -1 if it is none of those.
+int prefixFromMask(QString mask)
+{
+ mask = mask.trimmed();
+ if (mask.startsWith(QLatin1Char('/'))) {
+ mask.remove(0, 1);
+ }
+ bool number = false;
+ const int n = mask.toInt(&number);
+ if (number) {
+ return n >= 1 && n <= 32 ? n : -1;
+ }
+ const QHostAddress address(mask);
+ if (address.protocol() != QAbstractSocket::IPv4Protocol) {
+ return -1;
+ }
+ const quint32 bits = address.toIPv4Address();
+ const quint32 inverted = ~bits;
+ // A mask is ones then zeros, so its inverse plus one is a power of two.
+ if (bits == 0 || (inverted & (inverted + 1)) != 0) {
+ return -1;
+ }
+ int prefix = 0;
+ for (quint32 b = bits; b & 0x80000000u; b <<= 1) {
+ ++prefix;
+ }
+ return prefix;
+}
+
+QStringList splitServers(const QString &text)
+{
+ return text.split(QRegularExpression(QStringLiteral("[,;\\s]+")), Qt::SkipEmptyParts);
+}
+}
+
+NetworkSettings::NetworkSettings(QObject *parent)
+ : QObject(parent)
+{
+ m_refreshTimer = new QTimer(this);
+ m_refreshTimer->setSingleShot(true);
+ m_refreshTimer->setInterval(150);
+ connect(m_refreshTimer, &QTimer::timeout, this, &NetworkSettings::refresh);
+
+ connect(NetworkManager::notifier(), &NetworkManager::Notifier::activeConnectionsChanged, this, &NetworkSettings::scheduleRefresh);
+ connect(NetworkManager::notifier(), &NetworkManager::Notifier::primaryConnectionChanged, this, &NetworkSettings::scheduleRefresh);
+ connect(NetworkManager::notifier(), &NetworkManager::Notifier::serviceAppeared, this, &NetworkSettings::scheduleRefresh);
+ connect(NetworkManager::settingsNotifier(), &NetworkManager::SettingsNotifier::connectionAdded, this, &NetworkSettings::scheduleRefresh);
+ connect(NetworkManager::settingsNotifier(), &NetworkManager::SettingsNotifier::connectionRemoved, this, &NetworkSettings::scheduleRefresh);
+
+ readProxy();
+ refresh();
+}
+
+void NetworkSettings::scheduleRefresh()
+{
+ m_refreshTimer->start();
+}
+
+void NetworkSettings::profileChanged()
+{
+ if (auto connection = qobject_cast<NetworkManager::Connection *>(sender())) {
+ m_profiles.remove(connection->path());
+ }
+ scheduleRefresh();
+}
+
+void NetworkSettings::setBusy(const QString &busy)
+{
+ if (m_busy != busy) {
+ m_busy = busy;
+ Q_EMIT busyChanged();
+ }
+}
+
+void NetworkSettings::readKillSwitch()
+{
+ m_killSwitch = QFile::exists(killSwitchFile);
+ m_killSwitchState.clear();
+ m_blocked.clear();
+ QFile file(killSwitchStateFile);
+ if (!m_killSwitch || !file.open(QIODevice::ReadOnly)) {
+ return;
+ }
+ const QStringList lines = QString::fromUtf8(file.readAll()).split(QLatin1Char('\n'));
+ for (const QString &line : lines) {
+ const QString key = line.section(QLatin1Char('='), 0, 0);
+ const QString value = line.section(QLatin1Char('='), 1);
+ if (key == QLatin1String("state") && (value == QLatin1String("protecting") || value == QLatin1String("blocking") || value == QLatin1String("mullvad"))) {
+ m_killSwitchState = value;
+ } else if (key == QLatin1String("blocked")) {
+ m_blocked = value.split(QLatin1Char(','), Qt::SkipEmptyParts);
+ }
+ }
+}
+
+void NetworkSettings::refresh()
+{
+ const bool killSwitch = m_killSwitch;
+ const QString killSwitchState = m_killSwitchState;
+ readKillSwitch();
+
+ const auto active = NetworkManager::activeConnections();
+ QHash<QString, NetworkManager::ActiveConnection::Ptr> activeByUuid;
+ for (const auto &ac : active) {
+ activeByUuid.insert(ac->uuid(), ac);
+ connect(ac.data(), &NetworkManager::ActiveConnection::stateChanged, this, &NetworkSettings::scheduleRefresh, Qt::UniqueConnection);
+ }
+
+ const qint64 now = QDateTime::currentMSecsSinceEpoch();
+ QSet<QString> paths;
+ QVariantList vpns;
+ QVariantList wifi;
+ for (const auto &connection : NetworkManager::listConnections()) {
+ const QString path = connection->path();
+ paths.insert(path);
+ connect(connection.data(), &NetworkManager::Connection::updated, this, &NetworkSettings::profileChanged, Qt::UniqueConnection);
+ if (!m_profiles.contains(path)) {
+ m_profiles.insert(path, NetShared::profile(path));
+ m_flags.insert(path, connectionFlags(path));
+ }
+ if (m_flags.value(path) & generatedFlags) {
+ continue;
+ }
+ const NetShared::Profile &p = m_profiles[path];
+ const QVariantMap c = p.value(QStringLiteral("connection"));
+ const QString type = str(c, "type");
+ const QString uuid = str(c, "uuid");
+ const auto ac = activeByUuid.value(uuid);
+ const int state = ac ? int(ac->state()) : 0;
+ // Seconds since 1970 of the last time it was fully connected.
+ const qint64 used = c.value(QStringLiteral("timestamp")).toLongLong() * 1000;
+
+ if (type == QLatin1String("wireguard") || type == QLatin1String("vpn")) {
+ QString kind = QStringLiteral("VPN");
+ const QString service = str(p.value(QStringLiteral("vpn")), "service-type");
+ if (type == QLatin1String("wireguard") || service.contains(QLatin1String("wireguard"))) {
+ kind = QStringLiteral("WireGuard");
+ } else if (service.contains(QLatin1String("openvpn"))) {
+ kind = QStringLiteral("OpenVPN");
+ }
+ // A server's name says something ("se-sto-wg-001.relays..."),
+ // a bare address does not.
+ QString server;
+ for (const QString &host : NetShared::vpnServers(p)) {
+ if (QHostAddress(host).isNull()) {
+ server = host.section(QLatin1Char('.'), 0, 0);
+ break;
+ }
+ }
+ QString vpnState = QStringLiteral("off");
+ if (state == activated) {
+ vpnState = QStringLiteral("on");
+ if (!m_vpnSince.contains(uuid)) {
+ // Seen already up when Settings opened: NetworkManager's
+ // own record of when it connected is the best there is.
+ m_vpnSince.insert(uuid, m_firstRefresh && used > 0 ? used : now);
+ }
+ } else {
+ m_vpnSince.remove(uuid);
+ if (state == activating) {
+ vpnState = QStringLiteral("connecting");
+ } else if (m_blocked.contains(uuid)) {
+ vpnState = QStringLiteral("dropped");
+ }
+ }
+ vpns.append(QVariantMap{
+ {QStringLiteral("uuid"), uuid},
+ {QStringLiteral("name"), str(c, "id")},
+ {QStringLiteral("kind"), kind},
+ {QStringLiteral("server"), server},
+ {QStringLiteral("state"), vpnState},
+ {QStringLiteral("since"), m_vpnSince.value(uuid, 0)},
+ });
+ } else if (type == wifiType) {
+ // A hotspot this computer shares is not a network it joins.
+ if (str(p.value(wifiType), "mode") == QLatin1String("ap")) {
+ continue;
+ }
+ wifi.append(QVariantMap{
+ {QStringLiteral("uuid"), uuid},
+ {QStringLiteral("name"), str(c, "id")},
+ {QStringLiteral("active"), state == activated},
+ {QStringLiteral("connecting"), state == activating},
+ {QStringLiteral("autoconnect"), c.value(QStringLiteral("autoconnect"), true).toBool()},
+ {QStringLiteral("metered"), c.value(QStringLiteral("metered")).toInt() == 1},
+ {QStringLiteral("lastUsed"), used},
+ });
+ }
+ }
+
+ for (auto it = m_profiles.begin(); it != m_profiles.end();) {
+ if (paths.contains(it.key())) {
+ ++it;
+ } else {
+ m_flags.remove(it.key());
+ it = m_profiles.erase(it);
+ }
+ }
+
+ std::sort(vpns.begin(), vpns.end(), [](const QVariant &a, const QVariant &b) {
+ return a.toMap().value(QStringLiteral("name")).toString().localeAwareCompare(b.toMap().value(QStringLiteral("name")).toString()) < 0;
+ });
+ std::sort(wifi.begin(), wifi.end(), [](const QVariant &a, const QVariant &b) {
+ const QVariantMap x = a.toMap();
+ const QVariantMap y = b.toMap();
+ if (x.value(QStringLiteral("active")).toBool() != y.value(QStringLiteral("active")).toBool()) {
+ return x.value(QStringLiteral("active")).toBool();
+ }
+ return x.value(QStringLiteral("lastUsed")).toLongLong() > y.value(QStringLiteral("lastUsed")).toLongLong();
+ });
+
+ m_firstRefresh = false;
+ if (vpns != m_vpns) {
+ m_vpns = vpns;
+ Q_EMIT vpnsChanged();
+ }
+ if (wifi != m_savedWifi) {
+ m_savedWifi = wifi;
+ Q_EMIT savedWifiChanged();
+ }
+ // While a change is on its way the control keeps showing it, rather
+ // than flicking back to the profile it is about to replace.
+ if (m_busy.isEmpty()) {
+ const QVariantMap current = readCurrent();
+ if (current != m_current) {
+ m_current = current;
+ Q_EMIT currentChanged();
+ }
+ }
+ if (killSwitch != m_killSwitch || killSwitchState != m_killSwitchState) {
+ Q_EMIT killSwitchChanged();
+ }
+ const QVariantMap proxy = m_proxy;
+ readProxy();
+ if (proxy != m_proxy) {
+ Q_EMIT proxyChanged();
+ }
+}
+
+QVariantMap NetworkSettings::readCurrent()
+{
+ // The Wi-Fi or Ethernet connection carrying the default route; with a
+ // VPN up that is the one underneath it.
+ NetworkManager::ActiveConnection::Ptr chosen;
+ NetShared::Profile p;
+ for (const auto &ac : NetworkManager::activeConnections()) {
+ if (int(ac->state()) != activated || !ac->connection()) {
+ continue;
+ }
+ const QString path = ac->connection()->path();
+ if (!m_profiles.contains(path)) {
+ m_profiles.insert(path, NetShared::profile(path));
+ }
+ const QString type = str(m_profiles.value(path).value(QStringLiteral("connection")), "type");
+ if (type != wifiType && type != wiredType) {
+ continue;
+ }
+ if (!chosen || ac->default4()) {
+ chosen = ac;
+ p = m_profiles.value(path);
+ }
+ if (ac->default4()) {
+ break;
+ }
+ }
+ if (!chosen) {
+ return {};
+ }
+
+ const QVariantMap c = p.value(QStringLiteral("connection"));
+ const QVariantMap ipv4 = p.value(QStringLiteral("ipv4"));
+ const bool wifi = str(c, "type") == wifiType;
+
+ QVariantMap current{
+ {QStringLiteral("uuid"), str(c, "uuid")},
+ {QStringLiteral("name"), str(c, "id")},
+ {QStringLiteral("wifi"), wifi},
+ {QStringLiteral("manual"), str(ipv4, "method") == QLatin1String("manual")},
+ {QStringLiteral("metered"), c.value(QStringLiteral("metered")).toInt() == 1},
+ };
+
+ // The address a manual setup was given, to start the editor from.
+ const auto addressData = NetShared::unpack<QList<QVariantMap>>(ipv4.value(QStringLiteral("address-data")));
+ if (!addressData.isEmpty()) {
+ current.insert(QStringLiteral("manualAddress"), addressData.constFirst().value(QStringLiteral("address")).toString());
+ current.insert(QStringLiteral("manualPrefix"), addressData.constFirst().value(QStringLiteral("prefix")).toInt());
+ }
+ current.insert(QStringLiteral("manualGateway"), str(ipv4, "gateway"));
+
+ const QStringList dnsEntries = NetShared::profileDns(p, QStringLiteral("ipv4")) + NetShared::profileDns(p, QStringLiteral("ipv6"));
+ const QString dns = NetShared::dnsChoice(NetShared::profileDnsAddresses(p), ipv4.value(QStringLiteral("ignore-auto-dns")).toBool());
+ // connection.dns-over-tls: 2 is "yes"; 1, opportunistic (Wild OS's
+ // default), encrypts wherever the network allows it.
+ const bool tls = c.value(QStringLiteral("dns-over-tls"), -1).toInt() >= 1;
+ current.insert(QStringLiteral("dns"), dns);
+ current.insert(QStringLiteral("dnsCustom"), dns == QLatin1String("custom") ? dnsEntries.join(QStringLiteral(", ")) : QString());
+ current.insert(QStringLiteral("dnsEncrypted"), dns != QLatin1String("automatic") && tls);
+
+ // An empty choice means the default (NetworkManager.conf.d): Wi-Fi gets
+ // a new random address every time it connects, as GrapheneOS does, and
+ // Ethernet an address of its own for each network.
+ const QString assigned = str(p.value(wifi ? wifiType : wiredType), "assigned-mac-address");
+ current.insert(QStringLiteral("privateAddress"),
+ assigned == QLatin1String("stable") || assigned == QLatin1String("random") || assigned.isEmpty());
+
+ NetworkManager::Device::Ptr device;
+ if (!chosen->devices().isEmpty()) {
+ device = NetworkManager::findNetworkInterface(chosen->devices().constFirst());
+ }
+ if (!device) {
+ return current;
+ }
+ current.insert(QStringLiteral("interface"), device->interfaceName());
+
+ const NetworkManager::IpConfig v4 = device->ipV4Config();
+ if (!v4.addresses().isEmpty()) {
+ current.insert(QStringLiteral("address"), v4.addresses().constFirst().ip().toString());
+ current.insert(QStringLiteral("prefix"), v4.addresses().constFirst().prefixLength());
+ }
+ current.insert(QStringLiteral("gateway"), v4.gateway());
+ QStringList servers;
+ for (const QHostAddress &server : v4.nameservers()) {
+ servers.append(server.toString());
+ }
+ QStringList ipv6;
+ QStringList linkLocal;
+ const NetworkManager::IpConfig v6 = device->ipV6Config();
+ for (const auto &address : v6.addresses()) {
+ (address.ip().isLinkLocal() ? linkLocal : ipv6).append(address.ip().toString());
+ }
+ for (const QHostAddress &server : v6.nameservers()) {
+ servers.append(server.toString());
+ }
+ // The profile's servers are what lookups use; the device's list can
+ // also hold the network's own when they are being ignored.
+ current.insert(QStringLiteral("dnsServers"), dns == QLatin1String("automatic") ? servers : NetShared::profileDnsAddresses(p));
+ current.insert(QStringLiteral("ipv6"), ipv6.isEmpty() ? linkLocal : ipv6);
+
+ if (auto wireless = device.objectCast<NetworkManager::WirelessDevice>()) {
+ current.insert(QStringLiteral("speed"), wireless->bitRate());
+ if (auto ap = wireless->activeAccessPoint()) {
+ current.insert(QStringLiteral("frequency"), ap->frequency());
+ }
+ current.insert(QStringLiteral("mac"), wireless->hardwareAddress());
+ current.insert(QStringLiteral("permanentMac"), wireless->permanentHardwareAddress());
+ } else if (auto wired = device.objectCast<NetworkManager::WiredDevice>()) {
+ current.insert(QStringLiteral("speed"), wired->bitRate());
+ current.insert(QStringLiteral("mac"), wired->hardwareAddress());
+ current.insert(QStringLiteral("permanentMac"), wired->permanentHardwareAddress());
+ }
+ return current;
+}
+
+void NetworkSettings::nmcli(const QStringList &args, const Finished &finished)
+{
+ auto process = new QProcess(this);
+ QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
+ env.insert(QStringLiteral("LC_ALL"), QStringLiteral("C"));
+ process->setProcessEnvironment(env);
+ connect(process, &QProcess::finished, this, [process, finished](int code, QProcess::ExitStatus status) {
+ process->deleteLater();
+ const bool ok = status == QProcess::NormalExit && code == 0;
+ if (!ok) {
+ qWarning() << "nmcli" << process->arguments() << QString::fromUtf8(process->readAllStandardError()).trimmed();
+ }
+ finished(ok, QString::fromUtf8(process->readAllStandardOutput()));
+ });
+ connect(process, &QProcess::errorOccurred, this, [process, finished](QProcess::ProcessError error) {
+ if (error == QProcess::FailedToStart) {
+ process->deleteLater();
+ finished(false, QString());
+ }
+ });
+ process->start(QStringLiteral("nmcli"), args);
+}
+
+void NetworkSettings::modifyCurrent(const QString &busyKey, const QStringList &settings, bool reconnect, const QString &failTitle)
+{
+ const QString uuid = m_current.value(QStringLiteral("uuid")).toString();
+ const QString iface = m_current.value(QStringLiteral("interface")).toString();
+ if (uuid.isEmpty() || !m_busy.isEmpty()) {
+ // Puts back what the control showed before it was touched.
+ m_current = readCurrent();
+ Q_EMIT currentChanged();
+ return;
+ }
+ setBusy(busyKey);
+ Q_EMIT currentChanged();
+ nmcli(QStringList{QStringLiteral("connection"), QStringLiteral("modify"), uuid} + settings, [=, this](bool ok, const QString &) {
+ if (!ok) {
+ setBusy(QString());
+ m_profiles.clear();
+ refresh();
+ Q_EMIT failed(failTitle, QStringLiteral("NetworkManager did not accept the change, so this network is set up as it was."));
+ return;
+ }
+ const auto finish = [this, failTitle](bool up, const QString &) {
+ setBusy(QString());
+ m_profiles.clear();
+ refresh();
+ if (!up) {
+ Q_EMIT failed(failTitle, QStringLiteral("The change is saved, but the network did not reconnect with it. Try turning Wi-Fi off and on."));
+ }
+ };
+ const QStringList up{QStringLiteral("connection"), QStringLiteral("up"), uuid};
+ if (reconnect || iface.isEmpty()) {
+ nmcli(up, finish);
+ return;
+ }
+ nmcli({QStringLiteral("device"), QStringLiteral("reapply"), iface}, [=, this](bool applied, const QString &output) {
+ if (applied) {
+ finish(true, output);
+ } else {
+ nmcli(up, finish);
+ }
+ });
+ });
+}
+
+void NetworkSettings::setDns(const QString &choice, const QString &custom)
+{
+ if (choice != QLatin1String("automatic") && choice != QLatin1String("custom") && !NetShared::provider(choice)) {
+ return;
+ }
+ if (choice == QLatin1String("custom") && !checkCustomDns(custom).isEmpty()) {
+ return;
+ }
+ const auto connection = NetworkManager::findConnectionByUuid(m_current.value(QStringLiteral("uuid")).toString());
+ const NetShared::Profile p = connection ? m_profiles.value(connection->path()) : NetShared::Profile();
+ const bool ipv4 = NetShared::ipv4TakesDns(str(p.value(QStringLiteral("ipv4")), "method"));
+ const bool ipv6 = NetShared::ipv6TakesDns(str(p.value(QStringLiteral("ipv6")), "method"));
+ m_current.insert(QStringLiteral("dns"), choice);
+ modifyCurrent(QStringLiteral("dns"), NetShared::dnsModifyArgs(choice, splitServers(custom), ipv4, ipv6), false, QStringLiteral("DNS was not changed"));
+}
+
+QString NetworkSettings::checkCustomDns(const QString &custom) const
+{
+ const QStringList entries = splitServers(custom);
+ if (entries.isEmpty()) {
+ return QStringLiteral("Type the address of at least one DNS server.");
+ }
+ static const QRegularExpression hostName(QStringLiteral("^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)*$"));
+ for (const QString &entry : entries) {
+ if (QHostAddress(NetShared::serverAddress(entry)).isNull()) {
+ return QStringLiteral("%1 is not an IP address.").arg(entry.section(QLatin1Char('#'), 0, 0));
+ }
+ const QString name = entry.section(QLatin1Char('#'), 1);
+ if (entry.contains(QLatin1Char('#')) && !hostName.match(name).hasMatch()) {
+ return QStringLiteral("%1 is not a server name.").arg(name);
+ }
+ }
+ return QString();
+}
+
+QString NetworkSettings::checkAddress(const QString &address, const QString &mask, const QString &gateway) const
+{
+ if (QHostAddress(address.trimmed()).protocol() != QAbstractSocket::IPv4Protocol) {
+ return QStringLiteral("Type an IP address such as 192.168.1.42.");
+ }
+ if (prefixFromMask(mask) < 0) {
+ return QStringLiteral("Type a subnet mask such as 255.255.255.0.");
+ }
+ if (!gateway.trimmed().isEmpty() && QHostAddress(gateway.trimmed()).protocol() != QAbstractSocket::IPv4Protocol) {
+ return QStringLiteral("Type a gateway address such as 192.168.1.1.");
+ }
+ return QString();
+}
+
+void NetworkSettings::setAddress(bool automatic, const QString &address, const QString &mask, const QString &gateway)
+{
+ QStringList settings;
+ if (automatic) {
+ settings << QStringLiteral("ipv4.method") << QStringLiteral("auto") << QStringLiteral("ipv4.addresses") << QString()
+ << QStringLiteral("ipv4.gateway") << QString();
+ } else {
+ if (!checkAddress(address, mask, gateway).isEmpty()) {
+ return;
+ }
+ settings << QStringLiteral("ipv4.method") << QStringLiteral("manual") << QStringLiteral("ipv4.addresses")
+ << address.trimmed() + QLatin1Char('/') + QString::number(prefixFromMask(mask)) << QStringLiteral("ipv4.gateway") << gateway.trimmed();
+ // A manual address gets no DNS servers from the network, so a
+ // network that was taking them uses Wild OS's default instead.
+ if (m_current.value(QStringLiteral("dns")).toString() == QLatin1String("automatic")) {
+ settings << NetShared::dnsModifyArgs(QStringLiteral("quad9"), {}, true, false, true);
+ }
+ }
+ modifyCurrent(QStringLiteral("address"), settings, false, QStringLiteral("The IP address was not changed"));
+}
+
+// The new address only takes effect on joining again, so the network
+// reconnects for a moment.
+void NetworkSettings::setPrivateAddress(bool on)
+{
+ const bool wifi = m_current.value(QStringLiteral("wifi")).toBool();
+ const QString key = wifi ? QStringLiteral("802-11-wireless.cloned-mac-address") : QStringLiteral("802-3-ethernet.cloned-mac-address");
+ const QString off = wifi ? QStringLiteral("permanent") : QStringLiteral("preserve");
+ m_current.insert(QStringLiteral("privateAddress"), on);
+ const QString private_ = wifi ? QStringLiteral("random") : QStringLiteral("stable");
+ modifyCurrent(QStringLiteral("private"), {key, on ? private_ : off}, true, QStringLiteral("The hardware address was not changed"));
+}
+
+void NetworkSettings::setMetered(bool on)
+{
+ m_current.insert(QStringLiteral("metered"), on);
+ modifyCurrent(QStringLiteral("metered"), {QStringLiteral("connection.metered"), on ? QStringLiteral("yes") : QStringLiteral("no")}, false,
+ QStringLiteral("Metered connection was not changed"));
+}
+
+void NetworkSettings::forget(const QString &uuid)
+{
+ if (!m_busy.isEmpty()) {
+ return;
+ }
+ setBusy(QStringLiteral("forget:") + uuid);
+ nmcli({QStringLiteral("connection"), QStringLiteral("delete"), QStringLiteral("uuid"), uuid}, [this](bool ok, const QString &) {
+ setBusy(QString());
+ scheduleRefresh();
+ if (!ok) {
+ Q_EMIT failed(QStringLiteral("The network was not forgotten"), QStringLiteral("NetworkManager did not remove it. Try again."));
+ }
+ });
+}
+
+void NetworkSettings::setVpnActive(const QString &uuid, bool on)
+{
+ const auto connection = NetworkManager::findConnectionByUuid(uuid);
+ if (!connection) {
+ return;
+ }
+ const QString name = connection->name();
+ if (on) {
+ auto watcher = new QDBusPendingCallWatcher(NetworkManager::activateConnection(connection->path(), QStringLiteral("/"), QStringLiteral("/")), this);
+ connect(watcher, &QDBusPendingCallWatcher::finished, this, [this, watcher, name] {
+ watcher->deleteLater();
+ if (watcher->isError()) {
+ qWarning() << "VPN" << name << watcher->error().message();
+ Q_EMIT failed(name + QStringLiteral(" did not connect"), QStringLiteral("Check that you are online, then try again."));
+ Q_EMIT vpnsChanged();
+ }
+ scheduleRefresh();
+ });
+ return;
+ }
+ // Switched off on purpose, so the kill switch stops holding the
+ // internet back for it, whether it was up or had dropped.
+ QDBusMessage release = QDBusMessage::createMethodCall(QStringLiteral("org.wildos.Network"), QStringLiteral("/org/wildos/Network"),
+ QStringLiteral("org.wildos.Network"), QStringLiteral("Release"));
+ release << uuid;
+ QDBusConnection::systemBus().asyncCall(release);
+ for (const auto &ac : NetworkManager::activeConnections()) {
+ if (ac->uuid() == uuid) {
+ NetworkManager::deactivateConnection(ac->path());
+ }
+ }
+ scheduleRefresh();
+}
+
+void NetworkSettings::setKillSwitch(bool on)
+{
+ if (!m_busy.isEmpty() || on == m_killSwitch) {
+ Q_EMIT killSwitchChanged();
+ return;
+ }
+ setBusy(QStringLiteral("killswitch"));
+ auto process = new QProcess(this);
+ connect(process, &QProcess::finished, this, [this, process](int code) {
+ process->deleteLater();
+ setBusy(QString());
+ if (code == 126 || code == 127) {
+ Q_EMIT failed(QStringLiteral("The kill switch was not changed"), QStringLiteral("The password was not given."));
+ } else if (code != 0) {
+ Q_EMIT failed(QStringLiteral("The kill switch was not changed"), QStringLiteral("Wild OS could not change it. Try again."));
+ }
+ // Whatever happened, the switch shows the file again.
+ Q_EMIT killSwitchChanged();
+ // The service reports what it is guarding a moment later.
+ refresh();
+ QTimer::singleShot(1500, this, &NetworkSettings::refresh);
+ });
+ process->start(QStringLiteral("pkexec"), {networkHelper, QStringLiteral("kill-switch"), on ? QStringLiteral("on") : QStringLiteral("off")});
+}
+
+QString NetworkSettings::checkWireGuard(const QVariantMap &details) const
+{
+ if (details.value(QStringLiteral("name")).toString().trimmed().isEmpty()) {
+ return QStringLiteral("Give the VPN a name.");
+ }
+ const QString endpoint = details.value(QStringLiteral("endpoint")).toString().trimmed();
+ static const QRegularExpression endpointShape(QStringLiteral("^(\\[[0-9A-Fa-f:.]+\\]|[A-Za-z0-9.-]+):[0-9]{1,5}$"));
+ if (!endpointShape.match(endpoint).hasMatch()) {
+ return QStringLiteral("Type the server with its port, such as vpn.example.com:51820.");
+ }
+ if (!isWireGuardKey(details.value(QStringLiteral("publicKey")).toString())) {
+ return QStringLiteral("The server's public key is 44 characters ending in =.");
+ }
+ if (!isWireGuardKey(details.value(QStringLiteral("privateKey")).toString())) {
+ return QStringLiteral("Your private key is 44 characters ending in =.");
+ }
+ const QStringList addresses = splitServers(details.value(QStringLiteral("address")).toString());
+ if (addresses.isEmpty()) {
+ return QStringLiteral("Type the address your provider gave this computer, such as 10.64.0.2/32.");
+ }
+ for (const QString &address : addresses) {
+ if (QHostAddress::parseSubnet(address).first.isNull() && QHostAddress(address).isNull()) {
+ return QStringLiteral("%1 is not an IP address.").arg(address);
+ }
+ }
+ for (const QString &server : splitServers(details.value(QStringLiteral("dns")).toString())) {
+ if (QHostAddress(server).isNull()) {
+ return QStringLiteral("%1 is not an IP address.").arg(server);
+ }
+ }
+ return QString();
+}
+
+void NetworkSettings::addWireGuard(const QVariantMap &details)
+{
+ if (!checkWireGuard(details).isEmpty() || !m_busy.isEmpty()) {
+ return;
+ }
+ QStringList addresses = splitServers(details.value(QStringLiteral("address")).toString());
+ for (QString &address : addresses) {
+ if (!address.contains(QLatin1Char('/'))) {
+ address += QHostAddress(address).protocol() == QAbstractSocket::IPv6Protocol ? QStringLiteral("/128") : QStringLiteral("/32");
+ }
+ }
+ QString conf = QStringLiteral("[Interface]\nPrivateKey = %1\nAddress = %2\n")
+ .arg(details.value(QStringLiteral("privateKey")).toString().trimmed(), addresses.join(QStringLiteral(", ")));
+ const QStringList dns = splitServers(details.value(QStringLiteral("dns")).toString());
+ if (!dns.isEmpty()) {
+ conf += QStringLiteral("DNS = %1\n").arg(dns.join(QStringLiteral(", ")));
+ }
+ conf += QStringLiteral("\n[Peer]\nPublicKey = %1\nAllowedIPs = 0.0.0.0/0, ::/0\nEndpoint = %2\nPersistentKeepalive = 25\n")
+ .arg(details.value(QStringLiteral("publicKey")).toString().trimmed(), details.value(QStringLiteral("endpoint")).toString().trimmed());
+
+ QTemporaryDir dir;
+ QFile file(dir.filePath(QStringLiteral("typed.conf")));
+ if (!dir.isValid() || !file.open(QIODevice::WriteOnly)) {
+ Q_EMIT failed(QStringLiteral("The VPN was not added"), QStringLiteral("Wild OS could not write its details down. Try again."));
+ return;
+ }
+ file.setPermissions(QFileDevice::ReadOwner | QFileDevice::WriteOwner);
+ file.write(conf.toUtf8());
+ file.close();
+ importFile(file.fileName(), QStringLiteral("wireguard"), details.value(QStringLiteral("name")).toString().trimmed());
+}
+
+void NetworkSettings::importVpn(const QUrl &url)
+{
+ if (!m_busy.isEmpty()) {
+ return;
+ }
+ const QString path = url.isLocalFile() ? url.toLocalFile() : url.toString();
+ QFile file(path);
+ if (!file.open(QIODevice::ReadOnly)) {
+ Q_EMIT failed(QStringLiteral("The VPN was not added"), QStringLiteral("That file could not be opened."));
+ return;
+ }
+ const QString text = QString::fromUtf8(file.read(256 * 1024));
+ QString type;
+ if (text.contains(QRegularExpression(QStringLiteral("^\\s*\\[Interface\\]"), QRegularExpression::MultilineOption))) {
+ type = QStringLiteral("wireguard");
+ } else if (text.contains(QRegularExpression(QStringLiteral("^\\s*(remote|client|dev\\s+tun|<ca>)"), QRegularExpression::MultilineOption))) {
+ type = QStringLiteral("openvpn");
+ } else {
+ Q_EMIT failed(QStringLiteral("The VPN was not added"), QStringLiteral("That file is not a WireGuard or OpenVPN connection."));
+ return;
+ }
+ importFile(path, type, QFileInfo(path).completeBaseName());
+}
+
+// nmcli's import is NetworkManager's own: WireGuard files are read by
+// libnm, OpenVPN files by the network-manager-openvpn plugin, which also
+// finds certificates the file names beside it. WireGuard takes the
+// interface name from the file name, so that file is copied under a name
+// Linux accepts first.
+void NetworkSettings::importFile(const QString &path, const QString &type, const QString &name)
+{
+ setBusy(QStringLiteral("import"));
+ auto dir = std::make_shared<QTemporaryDir>();
+ QString source = path;
+ if (type == QLatin1String("wireguard")) {
+ QStringList taken;
+ for (const auto &p : std::as_const(m_profiles)) {
+ taken.append(str(p.value(QStringLiteral("connection")), "interface-name"));
+ }
+ source = dir->filePath(interfaceFor(name, taken) + QStringLiteral(".conf"));
+ if (!dir->isValid() || !QFile::copy(path, source)) {
+ setBusy(QString());
+ Q_EMIT failed(QStringLiteral("The VPN was not added"), QStringLiteral("That file could not be read."));
+ return;
+ }
+ QFile::setPermissions(source, QFileDevice::ReadOwner | QFileDevice::WriteOwner);
+ }
+ nmcli({QStringLiteral("connection"), QStringLiteral("import"), QStringLiteral("type"), type, QStringLiteral("file"), source},
+ [this, dir, name, type](bool ok, const QString &output) {
+ const auto match = QRegularExpression(QStringLiteral("\\(([0-9a-fA-F-]{36})\\)")).match(output);
+ if (!ok || !match.hasMatch()) {
+ setBusy(QString());
+ Q_EMIT failed(QStringLiteral("The VPN was not added"),
+ type == QLatin1String("openvpn") ? QStringLiteral("NetworkManager could not read that OpenVPN file.")
+ : QStringLiteral("NetworkManager could not read that WireGuard file."));
+ return;
+ }
+ // A VPN starts only when the person turns it on.
+ nmcli({QStringLiteral("connection"), QStringLiteral("modify"), match.captured(1), QStringLiteral("connection.id"), name,
+ QStringLiteral("connection.autoconnect"), QStringLiteral("no")},
+ [this, name](bool, const QString &) {
+ setBusy(QString());
+ scheduleRefresh();
+ Q_EMIT done(name + QStringLiteral(" added"), QStringLiteral("Turn it on with its switch whenever you want to use it."));
+ });
+ });
+}
+
+void NetworkSettings::readProxy()
+{
+ KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("kioslaverc"), KConfig::NoGlobals);
+ config->reparseConfiguration();
+ const KConfigGroup group = config->group(QStringLiteral("Proxy Settings"));
+ static const QStringList modes{QStringLiteral("off"), QStringLiteral("manual"), QStringLiteral("script"), QStringLiteral("automatic"),
+ QStringLiteral("manual")};
+ const int type = group.readEntry("ProxyType", 0);
+ // KIO writes "http://host port"; older files have "host:port".
+ QString http = group.readEntry("httpProxy", QString()).trimmed();
+ http.remove(QRegularExpression(QStringLiteral("^[a-z]+://")));
+ QString host = http.section(QLatin1Char(' '), 0, 0);
+ int port = http.section(QLatin1Char(' '), 1).toInt();
+ if (port == 0 && host.count(QLatin1Char(':')) == 1) {
+ port = host.section(QLatin1Char(':'), 1).toInt();
+ host = host.section(QLatin1Char(':'), 0, 0);
+ }
+ m_proxy = {
+ {QStringLiteral("mode"), modes.value(type, QStringLiteral("off"))},
+ {QStringLiteral("host"), host},
+ {QStringLiteral("port"), port},
+ {QStringLiteral("script"), group.readEntry("Proxy Config Script", QString())},
+ };
+}
+
+// The same settings KDE's proxy module writes. KDE apps and Chromium-based
+// browsers read them; KIO's running workers are told to read them again.
+void NetworkSettings::setProxy(const QString &mode, const QString &host, int port, const QString &script)
+{
+ KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("kioslaverc"), KConfig::NoGlobals);
+ KConfigGroup group = config->group(QStringLiteral("Proxy Settings"));
+ int type = 0;
+ if (mode == QLatin1String("manual")) {
+ type = 1;
+ QString address = host.trimmed();
+ if (!address.contains(QLatin1String("://"))) {
+ address.prepend(QStringLiteral("http://"));
+ }
+ const QString value = address + QLatin1Char(' ') + QString::number(port > 0 ? port : 8080);
+ group.writeEntry("httpProxy", value);
+ group.writeEntry("httpsProxy", value);
+ group.writeEntry("ftpProxy", value);
+ } else if (mode == QLatin1String("script")) {
+ type = 2;
+ group.writeEntry("Proxy Config Script", script.trimmed());
+ } else if (mode == QLatin1String("automatic")) {
+ type = 3;
+ }
+ group.writeEntry("ProxyType", type);
+ config->sync();
+
+ QDBusMessage message = QDBusMessage::createSignal(QStringLiteral("/KIO/Scheduler"), QStringLiteral("org.kde.KIO.Scheduler"),
+ QStringLiteral("reparseSlaveConfiguration"));
+ message << QString();
+ QDBusConnection::sessionBus().send(message);
+
+ readProxy();
+ Q_EMIT proxyChanged();
+}
diff --git a/packages/wildos-settings/src/network.h b/packages/wildos-settings/src/network.h
new file mode 100644
index 0000000..1c14400
--- /dev/null
+++ b/packages/wildos-settings/src/network.h
@@ -0,0 +1,139 @@
+#pragma once
+
+#include <QDateTime>
+#include <QHash>
+#include <QMap>
+#include <QObject>
+#include <QQmlEngine>
+#include <QUrl>
+#include <QVariantList>
+#include <QVariantMap>
+
+#include <functional>
+
+class QTimer;
+
+// Settings > Network and internet > Advanced network settings
+// (SettingsNetwork.dc): VPNs and the kill switch, saved Wi-Fi networks, the
+// current network's address, DNS, private hardware address and metering,
+// and the proxy.
+//
+// Lists, state and switching connections on and off go through
+// NetworkManagerQt. Profiles are read whole from NetworkManager (the parts
+// NetworkManagerQt does not model, such as DNS server names, would be lost
+// on a round trip through it) and changed with nmcli, which knows every
+// setting of the NetworkManager it ships with and leaves the rest of the
+// profile, saved passwords included, as it was. The kill switch belongs to
+// the root service wildos-network; Settings only turns it on or off through
+// the settings-network helper and reads what it reports.
+class NetworkSettings : public QObject
+{
+ Q_OBJECT
+ QML_ELEMENT
+ QML_SINGLETON
+
+ // [{uuid, name, kind, server, state ("on", "connecting", "dropped",
+ // "off"), since (ms since epoch, 0 if unknown)}]
+ Q_PROPERTY(QVariantList vpns READ vpns NOTIFY vpnsChanged)
+ // [{uuid, name, active, autoconnect, metered, lastUsed (ms, 0 never)}],
+ // the network in use first, then the most recently used.
+ Q_PROPERTY(QVariantList savedWifi READ savedWifi NOTIFY savedWifiChanged)
+ // The Wi-Fi or Ethernet connection in use, or empty: uuid, name, wifi,
+ // address, prefix, gateway, manual, dns, dnsServers, dnsCustom,
+ // dnsEncrypted, privateAddress, metered, speed (kbit/s), frequency (MHz),
+ // ipv6 (list), mac, permanentMac, interface.
+ Q_PROPERTY(QVariantMap current READ current NOTIFY currentChanged)
+ Q_PROPERTY(bool killSwitch READ killSwitch NOTIFY killSwitchChanged)
+ // "" (off or nothing to guard), "protecting", "blocking" (a VPN dropped
+ // and the internet is held back) or "mullvad" (the Mullvad app's own
+ // tunnel is up and its kill switch is in charge).
+ Q_PROPERTY(QString killSwitchState READ killSwitchState NOTIFY killSwitchChanged)
+ // What is being changed right now: "dns", "address", "private",
+ // "metered", "killswitch", "import", "vpn:<uuid>", "forget:<uuid>".
+ Q_PROPERTY(QString busy READ busy NOTIFY busyChanged)
+ // {mode ("off", "automatic", "script", "manual"), host, port, script}
+ Q_PROPERTY(QVariantMap proxy READ proxy NOTIFY proxyChanged)
+
+public:
+ explicit NetworkSettings(QObject *parent = nullptr);
+
+ QVariantList vpns() const { return m_vpns; }
+ QVariantList savedWifi() const { return m_savedWifi; }
+ QVariantMap current() const { return m_current; }
+ bool killSwitch() const { return m_killSwitch; }
+ QString killSwitchState() const { return m_killSwitchState; }
+ QString busy() const { return m_busy; }
+ QVariantMap proxy() const { return m_proxy; }
+
+ Q_INVOKABLE void refresh();
+
+ Q_INVOKABLE void setVpnActive(const QString &uuid, bool on);
+ // A WireGuard .conf or an OpenVPN .ovpn file.
+ Q_INVOKABLE void importVpn(const QUrl &file);
+ // {name, privateKey, address, dns, publicKey, endpoint}
+ Q_INVOKABLE void addWireGuard(const QVariantMap &details);
+ // A sentence saying what is wrong with typed WireGuard details, or "".
+ Q_INVOKABLE QString checkWireGuard(const QVariantMap &details) const;
+ Q_INVOKABLE void setKillSwitch(bool on);
+
+ Q_INVOKABLE void forget(const QString &uuid);
+
+ // choice: automatic, quad9, cloudflare, mullvad or custom (servers
+ // separated by commas or spaces, each optionally "address#tls-name").
+ Q_INVOKABLE void setDns(const QString &choice, const QString &custom = QString());
+ Q_INVOKABLE QString checkCustomDns(const QString &custom) const;
+ Q_INVOKABLE void setAddress(bool automatic, const QString &address = QString(), const QString &mask = QString(),
+ const QString &gateway = QString());
+ // A sentence saying what is wrong with a manual address, or "".
+ Q_INVOKABLE QString checkAddress(const QString &address, const QString &mask, const QString &gateway) const;
+ Q_INVOKABLE void setPrivateAddress(bool on);
+ Q_INVOKABLE void setMetered(bool on);
+
+ Q_INVOKABLE void setProxy(const QString &mode, const QString &host = QString(), int port = 0, const QString &script = QString());
+
+Q_SIGNALS:
+ // Each list says when it really changed, so a repeater over one is not
+ // rebuilt (losing focus and hover) because the Wi-Fi speed moved.
+ void vpnsChanged();
+ void savedWifiChanged();
+ void currentChanged();
+ void killSwitchChanged();
+ void busyChanged();
+ void proxyChanged();
+ void done(const QString &title, const QString &message);
+ void failed(const QString &title, const QString &reason);
+
+private Q_SLOTS:
+ void scheduleRefresh();
+ void profileChanged();
+
+private:
+ using Finished = std::function<void(bool ok, const QString &output)>;
+
+ void nmcli(const QStringList &args, const Finished &finished);
+ void setBusy(const QString &busy);
+ // Changes the current connection's profile, then puts the change to
+ // work: reapplied in place where NetworkManager can, else by
+ // reconnecting.
+ void modifyCurrent(const QString &busyKey, const QStringList &settings, bool reconnect, const QString &failTitle);
+ void importFile(const QString &path, const QString &type, const QString &name);
+ QVariantMap readCurrent();
+ void readKillSwitch();
+ void readProxy();
+
+ QVariantList m_vpns;
+ QVariantList m_savedWifi;
+ QVariantMap m_current;
+ QVariantMap m_proxy;
+ bool m_killSwitch = false;
+ QString m_killSwitchState;
+ QString m_busy;
+ QTimer *m_refreshTimer = nullptr;
+ QMap<QString, QMap<QString, QVariantMap>> m_profiles;
+ // When this session saw each VPN come up, for "Connected 2 h 14 min".
+ QHash<QString, qint64> m_vpnSince;
+ QHash<QString, uint> m_flags;
+ // VPNs the kill switch is holding the internet back for.
+ QStringList m_blocked;
+ bool m_firstRefresh = true;
+};
diff --git a/packages/wildos-settings/src/networkd/main.cpp b/packages/wildos-settings/src/networkd/main.cpp
new file mode 100644
index 0000000..d7eaf19
--- /dev/null
+++ b/packages/wildos-settings/src/networkd/main.cpp
@@ -0,0 +1,536 @@
+// wildos-network: the part of Advanced network settings that runs as root.
+//
+// Encrypted DNS by default. NetworkManager has no setting for a default DNS
+// server, and systemd-resolved's global servers would be asked alongside a
+// network's own rather than ahead of them. So each Wi-Fi and Ethernet
+// profile is given Quad9 the first time this service sees it: asked first,
+// over TLS wherever the network allows, with the network's own servers kept
+// behind it so sign-in pages on hotel and café Wi-Fi still load (see
+// NetShared::dnsModifyArgs). A profile that already names its own DNS
+// servers is left as it is, and so is anything the person changes
+// afterwards: each profile is only ever defaulted once.
+//
+// The VPN kill switch, when /etc/wildos/vpn-kill-switch exists. From the
+// moment a VPN is connected, nothing leaves this computer except through a
+// VPN, to the VPN's own servers (so it can reconnect), on the local network
+// (printers, screens) or to keep the network itself up (DHCP, IPv6
+// neighbour discovery). If the VPN drops, that stays so until it connects
+// again or is switched off: NetworkManager says when someone turned it off
+// (reason "user-disconnected"), and Settings says so too (Release). A
+// WireGuard tunnel has no connection to lose, so it only ever goes down
+// because it was turned off. Lookups leave through systemd-resolved only
+// when encrypted (DNS over TLS); plain DNS outside the tunnel is refused.
+// While the Mullvad app's own tunnel is up, its kill switch is in charge
+// and this one stands aside rather than fight it.
+
+#include "netshared.h"
+
+#include <QCoreApplication>
+#include <QDBusConnection>
+#include <QDBusMessage>
+#include <QDBusServiceWatcher>
+#include <QDBusVariant>
+#include <QDebug>
+#include <QDir>
+#include <QFile>
+#include <QFileSystemWatcher>
+#include <QHash>
+#include <QHostAddress>
+#include <QHostInfo>
+#include <QProcess>
+#include <QSaveFile>
+#include <QSet>
+#include <QTimer>
+
+#include <iterator>
+#include <utility>
+
+#include <pwd.h>
+
+namespace
+{
+const QString configDir = QStringLiteral("/etc/wildos");
+const QString killSwitchFile = QStringLiteral("/etc/wildos/vpn-kill-switch");
+const QString runDir = QStringLiteral("/run/wildos");
+const QString stateFile = QStringLiteral("/run/wildos/kill-switch");
+const QString armedFile = QStringLiteral("/run/wildos/kill-switch.armed");
+const QString defaultedFile = QStringLiteral("/var/lib/wildos/network-dns-defaulted");
+const QString table = QStringLiteral("wildos_kill_switch");
+
+const QString wifiType = QStringLiteral("802-11-wireless");
+const QString wiredType = QStringLiteral("802-3-ethernet");
+
+// NMActiveConnectionState and NMActiveConnectionStateReason
+constexpr uint deactivated = 4;
+constexpr uint userDisconnected = 2;
+constexpr uint connectionRemoved = 11;
+
+// NM_SETTINGS_CONNECTION_FLAG_EXTERNAL: a profile NetworkManager made up for
+// an interface something else runs.
+constexpr uint externalFlag = 0x8;
+
+const QStringList localV4{QStringLiteral("10.0.0.0/8"), QStringLiteral("172.16.0.0/12"), QStringLiteral("192.168.0.0/16"),
+ QStringLiteral("169.254.0.0/16"), QStringLiteral("224.0.0.0/4"), QStringLiteral("255.255.255.255")};
+const QStringList localV6{QStringLiteral("fe80::/10"), QStringLiteral("fc00::/7"), QStringLiteral("ff00::/8")};
+
+struct Active {
+ QString uuid;
+ QString type;
+ QString device;
+ QString state;
+ QString path;
+ bool saved = false;
+};
+
+struct Armed {
+ QString type;
+ QStringList addresses;
+};
+
+QString run(const QString &program, const QStringList &args, bool *ok = nullptr, const QByteArray &input = QByteArray())
+{
+ QProcess process;
+ QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
+ env.insert(QStringLiteral("LC_ALL"), QStringLiteral("C"));
+ process.setProcessEnvironment(env);
+ process.start(program, args);
+ if (!input.isEmpty()) {
+ process.write(input);
+ }
+ process.closeWriteChannel();
+ const bool finished = process.waitForFinished(30000);
+ const bool success = finished && process.exitStatus() == QProcess::NormalExit && process.exitCode() == 0;
+ if (!success) {
+ qWarning().noquote() << program << args.join(QLatin1Char(' ')) << QString::fromUtf8(process.readAllStandardError()).trimmed();
+ }
+ if (ok) {
+ *ok = success;
+ }
+ return QString::fromUtf8(process.readAllStandardOutput());
+}
+
+QString nmcli(const QStringList &args, bool *ok = nullptr)
+{
+ return run(QStringLiteral("nmcli"), args, ok);
+}
+
+uint connectionFlags(const QString &path)
+{
+ QDBusMessage call = QDBusMessage::createMethodCall(NetShared::nmService, path, QStringLiteral("org.freedesktop.DBus.Properties"),
+ QStringLiteral("Get"));
+ call << QStringLiteral("org.freedesktop.NetworkManager.Settings.Connection") << QStringLiteral("Flags");
+ const QDBusMessage reply = QDBusConnection::systemBus().call(call, QDBus::Block, 3000);
+ if (reply.type() != QDBusMessage::ReplyMessage || reply.arguments().isEmpty()) {
+ return 0;
+ }
+ return reply.arguments().constFirst().value<QDBusVariant>().variant().toUInt();
+}
+
+QStringList readLines(const QString &path)
+{
+ QFile file(path);
+ if (!file.open(QIODevice::ReadOnly)) {
+ return {};
+ }
+ return QString::fromUtf8(file.readAll()).split(QLatin1Char('\n'), Qt::SkipEmptyParts);
+}
+
+void writeFile(const QString &path, const QString &text)
+{
+ QDir().mkpath(path.section(QLatin1Char('/'), 0, -2));
+ QSaveFile file(path);
+ if (file.open(QIODevice::WriteOnly)) {
+ file.write(text.toUtf8());
+ file.commit();
+ }
+}
+
+bool isVpn(const QString &type)
+{
+ return type == QLatin1String("vpn") || type == QLatin1String("wireguard");
+}
+}
+
+class NetworkService : public QObject
+{
+ Q_OBJECT
+ Q_CLASSINFO("D-Bus Interface", "org.wildos.Network")
+
+public:
+ NetworkService()
+ {
+ m_timer.setSingleShot(true);
+ m_timer.setInterval(300);
+ connect(&m_timer, &QTimer::timeout, this, &NetworkService::reconcile);
+
+ for (const QString &uuid : readLines(defaultedFile)) {
+ m_defaulted.insert(uuid.trimmed());
+ }
+ for (const QString &line : readLines(armedFile)) {
+ const QStringList parts = line.split(QLatin1Char(' '));
+ if (parts.size() >= 2) {
+ m_armed.insert(parts.at(0), Armed{parts.at(1), parts.value(2).split(QLatin1Char(','), Qt::SkipEmptyParts)});
+ }
+ }
+
+ QDBusConnection bus = QDBusConnection::systemBus();
+ bus.connect(NetShared::nmService, QString(), QStringLiteral("org.freedesktop.NetworkManager.Connection.Active"), QStringLiteral("StateChanged"),
+ this, SLOT(activeStateChanged(uint, uint, QDBusMessage)));
+ bus.connect(NetShared::nmService, QStringLiteral("/org/freedesktop/NetworkManager/Settings"), QStringLiteral("org.freedesktop.NetworkManager.Settings"),
+ QStringLiteral("NewConnection"), this, SLOT(schedule()));
+ bus.connect(NetShared::nmService, QStringLiteral("/org/freedesktop/NetworkManager/Settings"), QStringLiteral("org.freedesktop.NetworkManager.Settings"),
+ QStringLiteral("ConnectionRemoved"), this, SLOT(schedule()));
+ auto watcher = new QDBusServiceWatcher(NetShared::nmService, bus, QDBusServiceWatcher::WatchForRegistration, this);
+ connect(watcher, &QDBusServiceWatcher::serviceRegistered, this, &NetworkService::schedule);
+
+ QDir().mkpath(configDir);
+ m_files.addPath(configDir);
+ connect(&m_files, &QFileSystemWatcher::directoryChanged, this, &NetworkService::schedule);
+ // Mullvad's tunnel comes and goes without NetworkManager saying so.
+ m_poll.setInterval(10000);
+ connect(&m_poll, &QTimer::timeout, this, &NetworkService::schedule);
+ m_poll.start();
+
+ bus.registerObject(QStringLiteral("/org/wildos/Network"), this, QDBusConnection::ExportScriptableSlots);
+ bus.registerService(QStringLiteral("org.wildos.Network"));
+
+ reconcile();
+ }
+
+public Q_SLOTS:
+ // The person switched this VPN off in Settings: if it is already down,
+ // stop holding the internet back for it; if it is still up, its
+ // disconnect is a deliberate one.
+ Q_SCRIPTABLE void Release(const QString &uuid)
+ {
+ bool up = false;
+ for (const Active &a : m_active) {
+ up = up || (a.uuid == uuid && a.state == QLatin1String("activated"));
+ }
+ if (up) {
+ m_userOff.insert(uuid);
+ } else {
+ m_armed.remove(uuid);
+ }
+ schedule();
+ }
+
+private Q_SLOTS:
+ void schedule()
+ {
+ m_timer.start();
+ }
+
+ void activeStateChanged(uint state, uint reason, const QDBusMessage &message)
+ {
+ if (state == deactivated && (reason == userDisconnected || reason == connectionRemoved)) {
+ const QString uuid = m_pathToUuid.value(message.path());
+ if (!uuid.isEmpty()) {
+ m_userOff.insert(uuid);
+ }
+ }
+ schedule();
+ }
+
+ void reconcile()
+ {
+ readActive();
+ const auto all = readAll();
+ stampDefaults(all);
+ killSwitch(all);
+ }
+
+private:
+ void readActive()
+ {
+ m_active.clear();
+ bool ok = false;
+ const QString out = nmcli({QStringLiteral("-t"), QStringLiteral("-f"), QStringLiteral("UUID,TYPE,DEVICE,STATE,ACTIVE-PATH,FILENAME"),
+ QStringLiteral("connection"), QStringLiteral("show"), QStringLiteral("--active")},
+ &ok);
+ if (!ok) {
+ return;
+ }
+ for (const QString &line : out.split(QLatin1Char('\n'), Qt::SkipEmptyParts)) {
+ const QStringList f = NetShared::terseFields(line);
+ if (f.size() < 6) {
+ continue;
+ }
+ m_active.append(Active{f.at(0), f.at(1), f.at(2), f.at(3), f.at(4), !f.at(5).isEmpty()});
+ m_pathToUuid.insert(f.at(4), f.at(0));
+ }
+ }
+
+ // uuid to {type, D-Bus path}
+ QHash<QString, QPair<QString, QString>> readAll()
+ {
+ QHash<QString, QPair<QString, QString>> all;
+ bool ok = false;
+ const QString out = nmcli({QStringLiteral("-t"), QStringLiteral("-f"), QStringLiteral("UUID,TYPE,DBUS-PATH"), QStringLiteral("connection"),
+ QStringLiteral("show")},
+ &ok);
+ if (!ok) {
+ return all;
+ }
+ for (const QString &line : out.split(QLatin1Char('\n'), Qt::SkipEmptyParts)) {
+ const QStringList f = NetShared::terseFields(line);
+ if (f.size() >= 3) {
+ all.insert(f.at(0), qMakePair(f.at(1), f.at(2)));
+ }
+ }
+ return all;
+ }
+
+ void stampDefaults(const QHash<QString, QPair<QString, QString>> &all)
+ {
+ const int before = m_defaulted.size();
+ for (auto it = all.cbegin(); it != all.cend(); ++it) {
+ const QString &uuid = it.key();
+ const QString &type = it.value().first;
+ if ((type != wifiType && type != wiredType) || m_defaulted.contains(uuid)) {
+ continue;
+ }
+ if (connectionFlags(it.value().second) & externalFlag) {
+ continue;
+ }
+ const NetShared::Profile p = NetShared::profile(it.value().second);
+ if (p.isEmpty()) {
+ continue;
+ }
+ m_defaulted.insert(uuid);
+ const QString method4 = p.value(QStringLiteral("ipv4")).value(QStringLiteral("method")).toString();
+ const QString method6 = p.value(QStringLiteral("ipv6")).value(QStringLiteral("method")).toString();
+ const bool hotspot = p.value(wifiType).value(QStringLiteral("mode")).toString() == QLatin1String("ap") || method4 == QLatin1String("shared");
+ const bool ownServers = !NetShared::profileDnsAddresses(p).isEmpty()
+ || p.value(QStringLiteral("ipv4")).value(QStringLiteral("ignore-auto-dns")).toBool();
+ if (hotspot || ownServers) {
+ continue;
+ }
+ bool ok = false;
+ nmcli(QStringList{QStringLiteral("connection"), QStringLiteral("modify"), uuid}
+ + NetShared::dnsModifyArgs(QStringLiteral("quad9"), {}, NetShared::ipv4TakesDns(method4), NetShared::ipv6TakesDns(method6), true),
+ &ok);
+ if (ok) {
+ m_reapply.insert(uuid);
+ }
+ }
+ if (m_defaulted.size() != before) {
+ QStringList lines(m_defaulted.cbegin(), m_defaulted.cend());
+ lines.sort();
+ writeFile(defaultedFile, lines.join(QLatin1Char('\n')) + QLatin1Char('\n'));
+ }
+
+ // A connection being joined right now started with the network's
+ // servers; once it is up it takes the new ones in place.
+ for (const Active &a : std::as_const(m_active)) {
+ if (m_reapply.contains(a.uuid) && a.state == QLatin1String("activated") && !a.device.isEmpty()) {
+ m_reapply.remove(a.uuid);
+ nmcli({QStringLiteral("device"), QStringLiteral("reapply"), a.device});
+ }
+ }
+ for (auto it = m_reapply.begin(); it != m_reapply.end();) {
+ bool joining = false;
+ for (const Active &a : std::as_const(m_active)) {
+ joining = joining || a.uuid == *it;
+ }
+ it = joining ? std::next(it) : m_reapply.erase(it);
+ }
+ }
+
+ void killSwitch(const QHash<QString, QPair<QString, QString>> &all)
+ {
+ const bool enabled = QFile::exists(killSwitchFile);
+ const bool mullvad = QFile::exists(QStringLiteral("/sys/class/net/wg0-mullvad")) || QFile::exists(QStringLiteral("/sys/class/net/wg-mullvad"));
+
+ QHash<QString, Active> up;
+ for (const Active &a : std::as_const(m_active)) {
+ if (isVpn(a.type) && a.saved && a.state == QLatin1String("activated")) {
+ up.insert(a.uuid, a);
+ }
+ }
+ QSet<QString> present;
+ for (const Active &a : std::as_const(m_active)) {
+ present.insert(a.uuid);
+ }
+
+ if (!enabled) {
+ m_armed.clear();
+ m_userOff.clear();
+ } else {
+ for (const Active &a : std::as_const(up)) {
+ // Its servers are looked up while it is connected, through
+ // it, and kept for reconnecting after a drop.
+ if (!m_armed.contains(a.uuid) || !m_wasUp.contains(a.uuid)) {
+ m_armed.insert(a.uuid, Armed{a.type, resolveServers(all.value(a.uuid).second)});
+ }
+ }
+ for (auto it = m_armed.begin(); it != m_armed.end();) {
+ const QString uuid = it.key();
+ const bool keep = up.contains(uuid)
+ || (all.contains(uuid) && it->type != QLatin1String("wireguard") && !m_userOff.contains(uuid));
+ if (!keep) {
+ m_userOff.remove(uuid);
+ }
+ it = keep ? std::next(it) : m_armed.erase(it);
+ }
+ }
+ for (auto it = m_userOff.begin(); it != m_userOff.end();) {
+ it = present.contains(*it) || m_armed.contains(*it) ? std::next(it) : m_userOff.erase(it);
+ }
+ m_wasUp = QSet<QString>(up.keyBegin(), up.keyEnd());
+
+ QStringList blocked;
+ for (auto it = m_armed.cbegin(); it != m_armed.cend(); ++it) {
+ if (!up.contains(it.key())) {
+ blocked.append(it.key());
+ }
+ }
+
+ QString state = QStringLiteral("off");
+ if (enabled) {
+ state = mullvad ? QStringLiteral("mullvad") : m_armed.isEmpty() ? QStringLiteral("ready") : blocked.isEmpty() ? QStringLiteral("protecting") : QStringLiteral("blocking");
+ }
+ applyRules(enabled && !mullvad && !m_armed.isEmpty() ? ruleset(up) : QString());
+
+ QString armed;
+ for (auto it = m_armed.cbegin(); it != m_armed.cend(); ++it) {
+ armed += it.key() + QLatin1Char(' ') + it->type + QLatin1Char(' ') + it->addresses.join(QLatin1Char(',')) + QLatin1Char('\n');
+ }
+ const QString report = QStringLiteral("state=%1\nblocked=%2\n").arg(state, blocked.join(QLatin1Char(',')));
+ if (armed != m_armedText || report != m_report) {
+ writeFile(armedFile, armed);
+ writeFile(stateFile, report);
+ m_armedText = armed;
+ m_report = report;
+ }
+ }
+
+ QStringList resolveServers(const QString &path)
+ {
+ QStringList addresses;
+ for (const QString &host : NetShared::vpnServers(NetShared::profile(path))) {
+ const QHostAddress literal(host);
+ if (!literal.isNull()) {
+ addresses.append(literal.toString());
+ continue;
+ }
+ for (const QHostAddress &address : QHostInfo::fromName(host).addresses()) {
+ addresses.append(address.toString());
+ }
+ }
+ addresses.removeDuplicates();
+ return addresses;
+ }
+
+ QString ruleset(const QHash<QString, Active> &up) const
+ {
+ QStringList interfaces{QStringLiteral("wildos-win*")};
+ QStringList v4;
+ QStringList v6;
+ for (auto it = m_armed.cbegin(); it != m_armed.cend(); ++it) {
+ if (it->type == QLatin1String("wireguard")) {
+ if (up.contains(it.key()) && !up.value(it.key()).device.isEmpty()) {
+ interfaces.append(up.value(it.key()).device);
+ }
+ } else {
+ // NetworkManager's VPN plugins bring up tun or tap devices.
+ interfaces << QStringLiteral("tun*") << QStringLiteral("tap*");
+ }
+ for (const QString &address : it->addresses) {
+ (QHostAddress(address).protocol() == QAbstractSocket::IPv6Protocol ? v6 : v4).append(address);
+ }
+ }
+ interfaces.removeDuplicates();
+
+ QString out = QStringLiteral(" oifname \"lo\" accept\n");
+ for (const QString &name : std::as_const(interfaces)) {
+ out += QStringLiteral(" oifname \"%1\" accept\n").arg(name);
+ }
+ if (!v4.isEmpty()) {
+ out += QStringLiteral(" ip daddr { %1 } accept\n").arg(v4.join(QStringLiteral(", ")));
+ }
+ if (!v6.isEmpty()) {
+ out += QStringLiteral(" ip6 daddr { %1 } accept\n").arg(v6.join(QStringLiteral(", ")));
+ }
+ out += QStringLiteral(" udp dport 53 reject\n tcp dport 53 reject\n");
+ if (const passwd *resolved = getpwnam("systemd-resolve")) {
+ out += QStringLiteral(" meta skuid %1 tcp dport 853 accept\n").arg(resolved->pw_uid);
+ }
+ out += QStringLiteral(
+ " udp sport 68 udp dport 67 accept\n"
+ " udp sport 546 udp dport 547 accept\n"
+ " icmpv6 type { nd-router-solicit, nd-neighbor-solicit, nd-neighbor-advert, mld2-listener-report } accept\n"
+ " ip daddr { %1 } accept\n"
+ " ip6 daddr { %2 } accept\n"
+ " reject\n")
+ .arg(localV4.join(QStringLiteral(", ")), localV6.join(QStringLiteral(", ")));
+
+ // Windows mode's virtual PC reaches the internet through this one,
+ // so it is held to the same rule.
+ QString forward = QStringLiteral(" iifname \"wildos-win*\" oifname \"wildos-win*\" accept\n");
+ for (const QString &name : std::as_const(interfaces)) {
+ if (!name.startsWith(QLatin1String("wildos-win"))) {
+ forward += QStringLiteral(" iifname \"wildos-win*\" oifname \"%1\" accept\n").arg(name);
+ }
+ }
+ forward += QStringLiteral(" iifname \"wildos-win*\" ip daddr { %1 } accept\n iifname \"wildos-win*\" reject\n")
+ .arg(localV4.join(QStringLiteral(", ")));
+
+ return QStringLiteral(
+ "table inet %1\n"
+ "delete table inet %1\n"
+ "table inet %1 {\n"
+ " chain output {\n"
+ " type filter hook output priority filter; policy accept;\n"
+ "%2"
+ " }\n"
+ " chain forward {\n"
+ " type filter hook forward priority filter; policy accept;\n"
+ "%3"
+ " }\n"
+ "}\n")
+ .arg(table, out, forward);
+ }
+
+ void applyRules(const QString &rules)
+ {
+ if (rules == m_rules && m_rulesKnown) {
+ return;
+ }
+ bool ok = false;
+ if (rules.isEmpty()) {
+ // Nothing to remove is fine; the table may never have existed.
+ QProcess::execute(QStringLiteral("nft"), {QStringLiteral("delete"), QStringLiteral("table"), QStringLiteral("inet"), table});
+ ok = true;
+ } else {
+ run(QStringLiteral("nft"), {QStringLiteral("-f"), QStringLiteral("-")}, &ok, rules.toUtf8());
+ }
+ m_rulesKnown = ok;
+ m_rules = rules;
+ }
+
+ QTimer m_timer;
+ QTimer m_poll;
+ QFileSystemWatcher m_files;
+ QList<Active> m_active;
+ QHash<QString, QString> m_pathToUuid;
+ QSet<QString> m_defaulted;
+ QSet<QString> m_reapply;
+ QHash<QString, Armed> m_armed;
+ QSet<QString> m_userOff;
+ QSet<QString> m_wasUp;
+ QString m_rules;
+ QString m_armedText;
+ QString m_report;
+ bool m_rulesKnown = false;
+};
+
+int main(int argc, char *argv[])
+{
+ QCoreApplication app(argc, argv);
+ app.setApplicationName(QStringLiteral("wildos-network"));
+ NetworkService service;
+ return app.exec();
+}
+
+#include "main.moc"
diff --git a/packages/wildos-settings/src/olderapps.cpp b/packages/wildos-settings/src/olderapps.cpp
new file mode 100644
index 0000000..4afa0fc
--- /dev/null
+++ b/packages/wildos-settings/src/olderapps.cpp
@@ -0,0 +1,71 @@
+#include "olderapps.h"
+
+#include <KConfig>
+#include <KConfigGroup>
+
+#include <QDBusConnection>
+#include <QDBusMessage>
+
+namespace
+{
+const QStringList choices = {QStringLiteral("None"), QStringLiteral("Modifiers"), QStringLiteral("Combinations"), QStringLiteral("All")};
+
+KConfigGroup xwayland(KConfig &config)
+{
+ return config.group(QStringLiteral("Xwayland"));
+}
+}
+
+OlderApps::OlderApps(QObject *parent)
+ : QObject(parent)
+{
+}
+
+int OlderApps::keys() const
+{
+ KConfig config(QStringLiteral("kwinrc"));
+ const QString value = xwayland(config).readEntry("XwaylandEavesdrops", QStringLiteral("Combinations"));
+ // KConfigSkeleton matches the name without case and falls back to the
+ // number, so both are read the same way here.
+ for (int i = 0; i < choices.size(); ++i) {
+ if (value.compare(choices.at(i), Qt::CaseInsensitive) == 0) {
+ return i;
+ }
+ }
+ bool ok = false;
+ const int number = value.toInt(&ok);
+ return ok && number >= 0 && number < choices.size() ? number : 2;
+}
+
+void OlderApps::setKeys(int level)
+{
+ if (level < 0 || level >= choices.size()) {
+ return;
+ }
+ KConfig config(QStringLiteral("kwinrc"));
+ xwayland(config).writeEntry("XwaylandEavesdrops", choices.at(level), KConfig::Notify);
+ config.sync();
+ reconfigure();
+}
+
+bool OlderApps::mouse() const
+{
+ KConfig config(QStringLiteral("kwinrc"));
+ return xwayland(config).readEntry("XwaylandEavesdropsMouse", false);
+}
+
+void OlderApps::setMouse(bool on)
+{
+ KConfig config(QStringLiteral("kwinrc"));
+ xwayland(config).writeEntry("XwaylandEavesdropsMouse", on, KConfig::Notify);
+ config.sync();
+ reconfigure();
+}
+
+void OlderApps::reconfigure()
+{
+ auto message = QDBusMessage::createMethodCall(QStringLiteral("org.kde.KWin"), QStringLiteral("/KWin"), QStringLiteral("org.kde.KWin"),
+ QStringLiteral("reconfigure"));
+ QDBusConnection::sessionBus().send(message);
+ Q_EMIT changed();
+}
diff --git a/packages/wildos-settings/src/olderapps.h b/packages/wildos-settings/src/olderapps.h
new file mode 100644
index 0000000..ff31d0e
--- /dev/null
+++ b/packages/wildos-settings/src/olderapps.h
@@ -0,0 +1,38 @@
+#pragma once
+
+#include <QObject>
+#include <QQmlEngine>
+
+// Old app compatibility: how much older (X11) apps, which run through
+// Xwayland, may see of what you type into other apps. Some need it for a
+// global shortcut such as push to talk.
+//
+// kwinrc [Xwayland] XwaylandEavesdrops is one of None, Modifiers,
+// Combinations or All (KWin's kwin.kcfg; KConfigSkeleton stores an enum by
+// its choice name) and XwaylandEavesdropsMouse adds mouse buttons, the keys
+// KDE's own Legacy X11 App Support module writes. KWin reads them again on
+// org.kde.KWin.reconfigure. Wild OS ships None (wildos-branding kwinrc).
+class OlderApps : public QObject
+{
+ Q_OBJECT
+ QML_ELEMENT
+ QML_SINGLETON
+
+ // 0 None, 1 Modifiers, 2 Combinations, 3 All.
+ Q_PROPERTY(int keys READ keys WRITE setKeys NOTIFY changed)
+ Q_PROPERTY(bool mouse READ mouse WRITE setMouse NOTIFY changed)
+
+public:
+ explicit OlderApps(QObject *parent = nullptr);
+
+ int keys() const;
+ void setKeys(int level);
+ bool mouse() const;
+ void setMouse(bool on);
+
+Q_SIGNALS:
+ void changed();
+
+private:
+ void reconfigure();
+};
diff --git a/packages/wildos-settings/src/poweroptions.cpp b/packages/wildos-settings/src/poweroptions.cpp
new file mode 100644
index 0000000..bd303b7
--- /dev/null
+++ b/packages/wildos-settings/src/poweroptions.cpp
@@ -0,0 +1,46 @@
+#include "poweroptions.h"
+
+#include <QDBusConnection>
+#include <QDBusMessage>
+#include <QDBusPendingCallWatcher>
+#include <QDBusPendingReply>
+#include <QDBusVariant>
+
+PowerOptions::PowerOptions(QObject *parent)
+ : QObject(parent)
+{
+ refresh();
+}
+
+void PowerOptions::refresh()
+{
+ auto lid = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.UPower"), QStringLiteral("/org/freedesktop/UPower"),
+ QStringLiteral("org.freedesktop.DBus.Properties"), QStringLiteral("Get"));
+ lid << QStringLiteral("org.freedesktop.UPower") << QStringLiteral("LidIsPresent");
+ auto watcher = new QDBusPendingCallWatcher(QDBusConnection::systemBus().asyncCall(lid), this);
+ connect(watcher, &QDBusPendingCallWatcher::finished, this, [this, watcher] {
+ watcher->deleteLater();
+ QDBusPendingReply<QDBusVariant> reply = *watcher;
+ m_lidPresent = !reply.isError() && reply.value().variant().toBool();
+ Q_EMIT changed();
+ });
+
+ ask(QStringLiteral("CanSuspend"), &m_canSuspend);
+ ask(QStringLiteral("CanHibernate"), &m_canHibernate);
+}
+
+// Asked of powerdevil rather than logind directly: its settings module
+// offers sleep and hibernate on the same answers, and they are the ones
+// its actions obey.
+void PowerOptions::ask(const QString &method, bool *target)
+{
+ auto message = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.PowerManagement"), QStringLiteral("/org/freedesktop/PowerManagement"),
+ QStringLiteral("org.freedesktop.PowerManagement"), method);
+ auto watcher = new QDBusPendingCallWatcher(QDBusConnection::sessionBus().asyncCall(message), this);
+ connect(watcher, &QDBusPendingCallWatcher::finished, this, [this, watcher, target] {
+ watcher->deleteLater();
+ QDBusPendingReply<bool> reply = *watcher;
+ *target = !reply.isError() && reply.value();
+ Q_EMIT changed();
+ });
+}
diff --git a/packages/wildos-settings/src/poweroptions.h b/packages/wildos-settings/src/poweroptions.h
new file mode 100644
index 0000000..d2dcfcd
--- /dev/null
+++ b/packages/wildos-settings/src/poweroptions.h
@@ -0,0 +1,39 @@
+#pragma once
+
+#include <QObject>
+#include <QQmlEngine>
+
+// What this computer can do with its lid and power button, so More power
+// settings only offers choices that work here: a lid row only on a laptop,
+// sleep and hibernate only where the system supports them. The answers
+// come from the same places powerdevil's own settings module asks: UPower
+// for the lid, powerdevil's org.freedesktop.PowerManagement for sleep.
+class PowerOptions : public QObject
+{
+ Q_OBJECT
+ QML_ELEMENT
+ QML_SINGLETON
+
+ Q_PROPERTY(bool lidPresent READ lidPresent NOTIFY changed)
+ Q_PROPERTY(bool canSuspend READ canSuspend NOTIFY changed)
+ Q_PROPERTY(bool canHibernate READ canHibernate NOTIFY changed)
+
+public:
+ explicit PowerOptions(QObject *parent = nullptr);
+
+ bool lidPresent() const { return m_lidPresent; }
+ bool canSuspend() const { return m_canSuspend; }
+ bool canHibernate() const { return m_canHibernate; }
+
+ Q_INVOKABLE void refresh();
+
+Q_SIGNALS:
+ void changed();
+
+private:
+ void ask(const QString &method, bool *target);
+
+ bool m_lidPresent = false;
+ bool m_canSuspend = false;
+ bool m_canHibernate = false;
+};
diff --git a/packages/wildos-settings/src/printers.cpp b/packages/wildos-settings/src/printers.cpp
index dad5aa4..849224e 100644
--- a/packages/wildos-settings/src/printers.cpp
+++ b/packages/wildos-settings/src/printers.cpp
@@ -1,6 +1,8 @@
#include "printers.h"
#include <QCoreApplication>
+#include <QDateTime>
+#include <QHash>
#include <QPointer>
#include <QProcess>
#include <QRegularExpression>
@@ -8,7 +10,9 @@
#include <QThread>
#include <QUrl>
+#include <cups/adminutil.h>
#include <cups/cups.h>
+#include <cups/pwg.h>
#include <unistd.h>
@@ -145,6 +149,33 @@ QVariantList readQueues()
}
finish();
ippDelete(response);
+
+ // Every person's documents, as Windows' print queue shows them; CUPS
+ // hides other people's titles itself (JobPrivateValues).
+ QHash<QString, QVariantList> queues;
+ cups_job_t *jobs = nullptr;
+ const int count = cupsGetJobs2(CUPS_HTTP_DEFAULT, &jobs, nullptr, 0, CUPS_WHICHJOBS_ACTIVE);
+ for (int i = 0; i < count; ++i) {
+ const cups_job_t &job = jobs[i];
+ const QString state = job.state == IPP_JSTATE_PROCESSING ? QStringLiteral("Printing")
+ : job.state == IPP_JSTATE_HELD ? QStringLiteral("Held")
+ : job.state == IPP_JSTATE_STOPPED ? QStringLiteral("Stopped")
+ : QStringLiteral("Waiting");
+ queues[QString::fromUtf8(job.dest)] << QVariantMap{
+ {QStringLiteral("id"), job.id},
+ {QStringLiteral("title"), QString::fromUtf8(job.title)},
+ {QStringLiteral("user"), QString::fromUtf8(job.user)},
+ {QStringLiteral("state"), state},
+ {QStringLiteral("size"), job.size},
+ {QStringLiteral("created"), QDateTime::fromSecsSinceEpoch(job.creation_time)},
+ };
+ }
+ cupsFreeJobs(count, jobs);
+ for (QVariant &printer : list) {
+ QVariantMap map = printer.toMap();
+ map.insert(QStringLiteral("queue"), queues.value(map.value(QStringLiteral("name")).toString()));
+ printer = map;
+ }
return list;
}
@@ -497,3 +528,420 @@ void Printers::cancelJobs(const QString &name)
}
reload();
}
+
+void Printers::cancelJob(const QString &name, int job)
+{
+ const QByteArray queue = name.toUtf8();
+ if (cupsCancelJob2(CUPS_HTTP_DEFAULT, queue.constData(), job, 0) == IPP_STATUS_OK) {
+ Q_EMIT done(QStringLiteral("Document cancelled"), QStringLiteral("It was taken out of the queue."));
+ } else {
+ Q_EMIT failed(QStringLiteral("The document was not cancelled"), QString::fromUtf8(cupsLastErrorString()));
+ }
+ reload();
+}
+
+void Printers::pause(const QString &name)
+{
+ admin(name, QStringLiteral("/usr/sbin/cupsdisable"), {name}, QStringLiteral("Printing paused"),
+ QStringLiteral("Documents wait in the queue until you resume the printer."), QStringLiteral("The printer was not paused"));
+}
+
+namespace
+{
+const QStringList preferenceOptions = {QStringLiteral("media"), QStringLiteral("sides"), QStringLiteral("print-color-mode")};
+
+QString choiceText(const QString &option, const QString &value, cups_dest_t *dest, cups_dinfo_t *info)
+{
+ if (option == QLatin1String("sides")) {
+ if (value == QLatin1String("one-sided")) {
+ return QStringLiteral("One-sided");
+ }
+ if (value == QLatin1String("two-sided-long-edge")) {
+ return QStringLiteral("Two-sided, flip on long edge");
+ }
+ if (value == QLatin1String("two-sided-short-edge")) {
+ return QStringLiteral("Two-sided, flip on short edge");
+ }
+ } else if (option == QLatin1String("print-color-mode")) {
+ static const QList<std::pair<const char *, const char *>> words = {
+ {"color", "Colour"},
+ {"monochrome", "Black and white"},
+ {"auto", "Automatic"},
+ {"auto-monochrome", "Automatic, black and white"},
+ {"bi-level", "Black and white, no greys"},
+ {"process-monochrome", "Black and white, using every ink"},
+ {"highlight", "Black and one colour"},
+ };
+ for (const auto &[key, word] : words) {
+ if (value == QLatin1String(key)) {
+ return QString::fromLatin1(word);
+ }
+ }
+ } else if (option == QLatin1String("media")) {
+ // PWG self-describing names (iso_a4_210x297mm) carry the size's
+ // everyday name in the PPD column (A4, Letter).
+ const QByteArray raw = value.toUtf8();
+ if (pwg_media_t *media = pwgMediaForPWG(raw.constData()); media && media->ppd) {
+ return QString::fromUtf8(media->ppd);
+ }
+ }
+ const QByteArray o = option.toUtf8();
+ const QByteArray v = value.toUtf8();
+ const char *localised = cupsLocalizeDestValue(CUPS_HTTP_DEFAULT, dest, info, o.constData(), v.constData());
+ return localised ? QString::fromUtf8(localised) : value;
+}
+}
+
+QVariantMap Printers::preferences(const QString &name) const
+{
+ QVariantMap out;
+ const QByteArray queue = name.toUtf8();
+ cups_dest_t *dest = cupsGetNamedDest(CUPS_HTTP_DEFAULT, queue.constData(), nullptr);
+ if (!dest) {
+ return out;
+ }
+ cups_dinfo_t *info = cupsCopyDestInfo(CUPS_HTTP_DEFAULT, dest);
+ if (!info) {
+ cupsFreeDests(1, dest);
+ return out;
+ }
+ for (const QString &option : preferenceOptions) {
+ const QByteArray o = option.toUtf8();
+ ipp_attribute_t *supported = cupsFindDestSupported(CUPS_HTTP_DEFAULT, dest, info, o.constData());
+ QVariantList choices;
+ QSet<QString> seen;
+ for (int i = 0; supported && i < ippGetCount(supported); ++i) {
+ const QString value = QString::fromUtf8(ippGetString(supported, i, nullptr));
+ // custom_min_ and custom_max_ are the limits of a custom size,
+ // not sizes.
+ if (value.isEmpty() || value.startsWith(QLatin1String("custom_")) || seen.contains(value)) {
+ continue;
+ }
+ seen.insert(value);
+ choices << QVariantMap{{QStringLiteral("value"), value}, {QStringLiteral("text"), choiceText(option, value, dest, info)}};
+ }
+ if (choices.size() < 2) {
+ continue;
+ }
+ // The person's own choice (lpoptions) first, then the printer's.
+ QString current = QString::fromUtf8(cupsGetOption(o.constData(), dest->num_options, dest->options));
+ if (current.isEmpty()) {
+ ipp_attribute_t *def = cupsFindDestDefault(CUPS_HTTP_DEFAULT, dest, info, o.constData());
+ current = def ? QString::fromUtf8(ippGetString(def, 0, nullptr)) : QString();
+ }
+ const QString key = option == QLatin1String("print-color-mode") ? QStringLiteral("color") : option;
+ out.insert(key, QVariantMap{{QStringLiteral("value"), current}, {QStringLiteral("choices"), choices}});
+ }
+ cupsFreeDestInfo(info);
+ cupsFreeDests(1, dest);
+ return out;
+}
+
+void Printers::setPreference(const QString &name, const QString &option, const QString &value)
+{
+ if (!preferenceOptions.contains(option)) {
+ return;
+ }
+ const QByteArray queue = name.toUtf8();
+ const QByteArray o = option.toUtf8();
+ const QByteArray v = value.toUtf8();
+ cups_dest_t *dests = nullptr;
+ const int count = cupsGetDests2(CUPS_HTTP_DEFAULT, &dests);
+ cups_dest_t *dest = cupsGetDest(queue.constData(), nullptr, count, dests);
+ bool saved = false;
+ if (dest) {
+ cups_dinfo_t *info = cupsCopyDestInfo(CUPS_HTTP_DEFAULT, dest);
+ const bool supported = info && cupsCheckDestSupported(CUPS_HTTP_DEFAULT, dest, info, o.constData(), v.constData());
+ if (info) {
+ cupsFreeDestInfo(info);
+ }
+ if (supported) {
+ // Kept per person, as "lpoptions -p name -o option=value" does,
+ // and read by every app's print dialog through CUPS.
+ dest->num_options = cupsAddOption(o.constData(), v.constData(), dest->num_options, &dest->options);
+ saved = cupsSetDests2(CUPS_HTTP_DEFAULT, count, dests) == 0;
+ }
+ }
+ cupsFreeDests(count, dests);
+ if (!saved) {
+ Q_EMIT failed(QStringLiteral("The printing preference was not saved"), QString::fromUtf8(cupsLastErrorString()));
+ }
+}
+
+namespace
+{
+// cupsd asks for a password when the account may not list devices. Without
+// this CUPS would ask on a terminal Settings was started from; with it the
+// request is refused and an administrator is asked through pkexec instead.
+const char *noPassword(const char *, http_t *, const char *, const char *, void *)
+{
+ return nullptr;
+}
+
+struct DeviceList {
+ QSet<QString> known;
+ QVariantList devices;
+};
+
+void onDevice(const char *deviceClass, const char *, const char *info, const char *model, const char *uri, const char *, void *data)
+{
+ auto *list = static_cast<DeviceList *>(data);
+ const QString address = QString::fromUtf8(uri);
+ // Bare scheme names (socket, lpd, ipp) are backends offering to be
+ // typed in, not printers.
+ if (!address.contains(QLatin1Char(':')) || list->known.contains(address)) {
+ return;
+ }
+ QString makeAndModel = QString::fromUtf8(model);
+ if (makeAndModel.compare(QLatin1String("Unknown"), Qt::CaseInsensitive) == 0) {
+ makeAndModel.clear();
+ }
+ list->devices << QVariantMap{{QStringLiteral("uri"), address},
+ {QStringLiteral("name"), QString::fromUtf8(info)},
+ {QStringLiteral("model"), makeAndModel},
+ {QStringLiteral("kind"), qstrcmp(deviceClass, "direct") == 0 ? QStringLiteral("usb") : QStringLiteral("network")}};
+}
+
+// The same list from "lpinfo -l -v", for when only an administrator may see
+// it.
+QVariantList parseLpinfo(const QString &output, const QSet<QString> &known)
+{
+ DeviceList list;
+ list.known = known;
+ QVariantMap current;
+ auto finish = [&] {
+ if (!current.isEmpty()) {
+ const QByteArray cls = current.value(QStringLiteral("class")).toString().toUtf8();
+ const QByteArray info = current.value(QStringLiteral("info")).toString().toUtf8();
+ const QByteArray model = current.value(QStringLiteral("make-and-model")).toString().toUtf8();
+ const QByteArray uri = current.value(QStringLiteral("uri")).toString().toUtf8();
+ onDevice(cls.constData(), nullptr, info.constData(), model.constData(), uri.constData(), nullptr, &list);
+ }
+ current.clear();
+ };
+ static const QRegularExpression field(QStringLiteral("^\\s*([a-z-]+) = (.*)$"));
+ const QStringList lines = output.split(QLatin1Char('\n'));
+ for (const QString &line : lines) {
+ QString body = line;
+ if (line.startsWith(QLatin1String("Device: "))) {
+ finish();
+ body = line.mid(8);
+ }
+ const auto m = field.match(body);
+ if (m.hasMatch()) {
+ current.insert(m.captured(1), m.captured(2).trimmed());
+ }
+ }
+ finish();
+ return list.devices;
+}
+}
+
+void Printers::finishDevices(const QVariantList &devices)
+{
+ m_devices = devices;
+ m_findingDevices = false;
+ Q_EMIT devicesChanged();
+}
+
+void Printers::findDevices()
+{
+ if (m_findingDevices) {
+ return;
+ }
+ m_findingDevices = true;
+ m_devices.clear();
+ Q_EMIT devicesChanged();
+
+ QSet<QString> known;
+ for (const QVariant &p : std::as_const(m_printers)) {
+ known.insert(p.toMap().value(QStringLiteral("uri")).toString());
+ }
+ QPointer<Printers> self(this);
+ QThread *thread = QThread::create([self, known] {
+ cupsSetPasswordCB2(noPassword, nullptr);
+ DeviceList list;
+ list.known = known;
+ const ipp_status_t status = cupsGetDevices(CUPS_HTTP_DEFAULT, 8, CUPS_INCLUDE_ALL, CUPS_EXCLUDE_NONE, onDevice, &list);
+ const bool refused = status == IPP_STATUS_ERROR_FORBIDDEN || status == IPP_STATUS_ERROR_NOT_AUTHORIZED || status == IPP_STATUS_ERROR_NOT_AUTHENTICATED;
+ const QVariantList devices = list.devices;
+ QMetaObject::invokeMethod(qApp, [self, refused, devices, known] {
+ if (!self) {
+ return;
+ }
+ if (!refused) {
+ self->finishDevices(devices);
+ return;
+ }
+ auto process = new QProcess(self);
+ detach(process);
+ QObject::connect(process, &QProcess::finished, self, [self, process, known](int code, QProcess::ExitStatus status) {
+ const QString output = QString::fromUtf8(process->readAllStandardOutput());
+ process->deleteLater();
+ if (!self) {
+ return;
+ }
+ const bool ok = status == QProcess::NormalExit && code == 0;
+ self->finishDevices(ok ? parseLpinfo(output, known) : QVariantList());
+ if (!ok) {
+ Q_EMIT self->failed(QStringLiteral("Printers plugged into this computer can't be listed"),
+ QStringLiteral("An administrator's password is needed to look for them."));
+ }
+ });
+ process->start(QStringLiteral("pkexec"), {QStringLiteral("/usr/sbin/lpinfo"), QStringLiteral("-l"), QStringLiteral("-v")});
+ });
+ });
+ connect(thread, &QThread::finished, thread, &QObject::deleteLater);
+ thread->start();
+}
+
+void Printers::loadDrivers()
+{
+ if (m_loadingDrivers || !m_drivers.isEmpty()) {
+ return;
+ }
+ m_loadingDrivers = true;
+ Q_EMIT driversChanged();
+ QPointer<Printers> self(this);
+ QThread *thread = QThread::create([self] {
+ QList<Driver> drivers;
+ // CUPS-Get-PPDs is open to everyone (lpinfo -m); it can take a few
+ // seconds while cups-driverd reads every driver package.
+ ipp_t *request = ippNewRequest(IPP_OP_CUPS_GET_PPDS);
+ static const char *const wanted[] = {"ppd-name", "ppd-make", "ppd-make-and-model"};
+ ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes", int(std::size(wanted)), nullptr, wanted);
+ if (ipp_t *response = cupsDoRequest(CUPS_HTTP_DEFAULT, request, "/")) {
+ Driver current;
+ auto finish = [&] {
+ // "everywhere" and the driverless PPDs build the queue from
+ // what the printer says, which the main page already does.
+ if (!current.ppd.isEmpty() && !current.make.isEmpty() && current.ppd != QLatin1String("everywhere")
+ && !current.ppd.startsWith(QLatin1String("driverless:"))) {
+ drivers << current;
+ }
+ current = Driver();
+ };
+ for (ipp_attribute_t *attr = ippFirstAttribute(response); attr; attr = ippNextAttribute(response)) {
+ const char *attrName = ippGetName(attr);
+ if (!attrName) {
+ finish();
+ continue;
+ }
+ const QByteArray key(attrName);
+ if (key == "ppd-name") {
+ current.ppd = text(attr);
+ } else if (key == "ppd-make") {
+ current.make = text(attr).trimmed();
+ } else if (key == "ppd-make-and-model") {
+ current.model = text(attr).trimmed();
+ }
+ }
+ finish();
+ ippDelete(response);
+ }
+ std::sort(drivers.begin(), drivers.end(), [](const Driver &a, const Driver &b) {
+ return a.model.compare(b.model, Qt::CaseInsensitive) < 0;
+ });
+ QMetaObject::invokeMethod(qApp, [self, drivers] {
+ if (!self) {
+ return;
+ }
+ self->m_drivers = drivers;
+ self->m_loadingDrivers = false;
+ Q_EMIT self->driversChanged();
+ if (drivers.isEmpty()) {
+ Q_EMIT self->failed(QStringLiteral("No printer drivers were found"),
+ QStringLiteral("Install the driver package from your printer's maker, then try again."));
+ }
+ });
+ });
+ connect(thread, &QThread::finished, thread, &QObject::deleteLater);
+ thread->start();
+}
+
+QStringList Printers::makes() const
+{
+ QStringList out;
+ for (const Driver &d : m_drivers) {
+ if (!out.contains(d.make, Qt::CaseInsensitive)) {
+ out << d.make;
+ }
+ }
+ out.sort(Qt::CaseInsensitive);
+ return out;
+}
+
+QVariantList Printers::models(const QString &make) const
+{
+ QVariantList out;
+ for (const Driver &d : m_drivers) {
+ if (d.make.compare(make, Qt::CaseInsensitive) == 0) {
+ out << QVariantMap{{QStringLiteral("value"), d.ppd}, {QStringLiteral("text"), d.model}};
+ }
+ }
+ return out;
+}
+
+QString Printers::makeFor(const QString &model) const
+{
+ QString best;
+ const QStringList all = makes();
+ for (const QString &make : all) {
+ if (model.startsWith(make, Qt::CaseInsensitive) && make.length() > best.length()) {
+ best = make;
+ }
+ }
+ return best;
+}
+
+QString Printers::addressUri(const QString &address, const QString &protocol) const
+{
+ const QString host = address.trimmed();
+ static const QRegularExpression hostName(QStringLiteral("^[A-Za-z0-9.:\\[\\]-]+$"));
+ if (!hostName.match(host).hasMatch()) {
+ return {};
+ }
+ if (protocol == QLatin1String("lpd")) {
+ return QStringLiteral("lpd://%1/queue").arg(host);
+ }
+ if (protocol == QLatin1String("ipp")) {
+ return QStringLiteral("ipp://%1/ipp/print").arg(host);
+ }
+ // Port 9100 (HP JetDirect, "raw") is what most printers that need a
+ // driver listen on.
+ return QStringLiteral("socket://%1:9100").arg(host);
+}
+
+void Printers::addWithDriver(const QString &uri, const QString &driver, const QString &name)
+{
+ // lpadmin may run as root through pkexec, so only a driver CUPS listed
+ // and a well-formed device address reach it, and neither can be read
+ // as an option.
+ const bool knownDriver = std::any_of(m_drivers.cbegin(), m_drivers.cend(), [&driver](const Driver &d) {
+ return d.ppd == driver;
+ });
+ const QUrl url(uri);
+ static const QRegularExpression scheme(QStringLiteral("^[a-z][a-z0-9+.-]*$"));
+ if (!knownDriver || !url.isValid() || !scheme.match(url.scheme()).hasMatch() || uri.contains(QLatin1Char('\n')) || uri.startsWith(QLatin1Char('-'))
+ || driver.startsWith(QLatin1Char('-'))) {
+ Q_EMIT failed(QStringLiteral("The printer was not added"), QStringLiteral("Choose the printer and its driver again."));
+ return;
+ }
+ const QString info = name.trimmed().isEmpty() ? QStringLiteral("Printer") : name.trimmed();
+ const QString queue = queueName(info);
+ const bool first = m_printers.isEmpty();
+ admin(QStringLiteral("add"), QStringLiteral("/usr/sbin/lpadmin"),
+ {QStringLiteral("-p"), queue, QStringLiteral("-E"), QStringLiteral("-v"), uri, QStringLiteral("-m"), driver, QStringLiteral("-D"), info},
+ QStringLiteral("Printer added"), info + QStringLiteral(" is ready to use."), QStringLiteral("The printer was not added"), [this, queue, first, uri] {
+ for (int i = 0; i < m_devices.size(); ++i) {
+ if (m_devices.at(i).toMap().value(QStringLiteral("uri")).toString() == uri) {
+ m_devices.removeAt(i);
+ Q_EMIT devicesChanged();
+ break;
+ }
+ }
+ if (first) {
+ setDefault(queue, false);
+ }
+ });
+}
diff --git a/packages/wildos-settings/src/printers.h b/packages/wildos-settings/src/printers.h
index 6e87f41..071b3af 100644
--- a/packages/wildos-settings/src/printers.h
+++ b/packages/wildos-settings/src/printers.h
@@ -14,6 +14,12 @@
// "everywhere" model, the account's default printer (lpoptions, as Windows
// keeps the default per person), a test page, and removing a queue.
//
+// More printer settings adds the rest of what KDE's print manager did: each
+// printer's queue with a Cancel per document, pausing a printer, printing
+// preferences kept per person in lpoptions like the default printer, and
+// adding a printer that needs a driver, chosen from the PPDs CUPS knows
+// (CUPS-Get-PPDs) for a device CUPS finds (CUPS-Get-Devices, lpinfo -v).
+//
// Adding and removing are CUPS administration. Members of lpadmin (every
// administrator Wild OS creates) are let in by CUPS itself over the local
// socket; anyone else is asked for an administrator's password through
@@ -29,6 +35,10 @@ class Printers : public QObject
Q_PROPERTY(QVariantList found READ found NOTIFY foundChanged)
Q_PROPERTY(bool searching READ searching NOTIFY foundChanged)
Q_PROPERTY(QString busy READ busy NOTIFY busyChanged)
+ Q_PROPERTY(QVariantList devices READ devices NOTIFY devicesChanged)
+ Q_PROPERTY(bool findingDevices READ findingDevices NOTIFY devicesChanged)
+ Q_PROPERTY(bool driversReady READ driversReady NOTIFY driversChanged)
+ Q_PROPERTY(bool loadingDrivers READ loadingDrivers NOTIFY driversChanged)
public:
explicit Printers(QObject *parent = nullptr);
@@ -39,6 +49,10 @@ public:
QVariantList found() const { return m_found; }
bool searching() const { return m_searching; }
QString busy() const { return m_busy; }
+ QVariantList devices() const { return m_devices; }
+ bool findingDevices() const { return m_findingDevices; }
+ bool driversReady() const { return !m_drivers.isEmpty(); }
+ bool loadingDrivers() const { return m_loadingDrivers; }
Q_INVOKABLE void reload();
Q_INVOKABLE void search();
@@ -53,11 +67,35 @@ public:
Q_INVOKABLE void remove(const QString &name);
Q_INVOKABLE void resume(const QString &name);
Q_INVOKABLE void cancelJobs(const QString &name);
+ Q_INVOKABLE void cancelJob(const QString &name, int job);
+ Q_INVOKABLE void pause(const QString &name);
+
+ // Paper size, two-sided and colour for one printer: { media, sides,
+ // color } each { value, choices: [{ value, text }] }, a choice missing
+ // when the printer has only one.
+ Q_INVOKABLE QVariantMap preferences(const QString &name) const;
+ // option is media, sides or print-color-mode.
+ Q_INVOKABLE void setPreference(const QString &name, const QString &option, const QString &value);
+
+ // Devices CUPS can reach, USB and network, { uri, name, model, kind }.
+ Q_INVOKABLE void findDevices();
+ Q_INVOKABLE void loadDrivers();
+ Q_INVOKABLE QStringList makes() const;
+ // { value: ppd-name, text: make and model } for one make.
+ Q_INVOKABLE QVariantList models(const QString &make) const;
+ // The make CUPS's driver list uses for a model string from a device,
+ // or nothing.
+ Q_INVOKABLE QString makeFor(const QString &model) const;
+ // uri from `devices`, or built from an address with socket, lpd or ipp.
+ Q_INVOKABLE void addWithDriver(const QString &uri, const QString &driver, const QString &name);
+ Q_INVOKABLE QString addressUri(const QString &address, const QString &protocol) const;
Q_SIGNALS:
void changed();
void foundChanged();
void busyChanged();
+ void devicesChanged();
+ void driversChanged();
void failed(const QString &title, const QString &reason);
void done(const QString &title, const QString &message);
@@ -66,6 +104,13 @@ private:
void admin(const QString &busy, const QString &program, const QStringList &arguments, const QString &successTitle, const QString &success,
const QString &failure, const std::function<void()> &then = {});
QString queueName(const QString &name) const;
+ void finishDevices(const QVariantList &devices);
+
+ struct Driver {
+ QString ppd;
+ QString make;
+ QString model;
+ };
bool m_available = false;
QVariantList m_printers;
@@ -74,4 +119,8 @@ private:
QString m_busy;
std::shared_ptr<std::atomic<int>> m_cancelSearch;
int m_searchGeneration = 0;
+ QVariantList m_devices;
+ bool m_findingDevices = false;
+ QList<Driver> m_drivers;
+ bool m_loadingDrivers = false;
};
diff --git a/packages/wildos-settings/src/spelling.cpp b/packages/wildos-settings/src/spelling.cpp
new file mode 100644
index 0000000..1252891
--- /dev/null
+++ b/packages/wildos-settings/src/spelling.cpp
@@ -0,0 +1,234 @@
+#include "spelling.h"
+
+#include <Sonnet/Settings>
+#include <Sonnet/Speller>
+
+#include <QCollator>
+#include <QDir>
+#include <QFile>
+#include <QSaveFile>
+#include <QSettings>
+#include <QSet>
+#include <QTextStream>
+
+namespace
+{
+// Hunspell's "Add to dictionary" file (sonnet hunspelldict.cpp): a word on
+// each line, "word/flags" with affix flags, "*word" for one taken out.
+QString baseWord(const QString &line)
+{
+ if (line.isEmpty() || line.startsWith(QLatin1Char('*'))) {
+ return {};
+ }
+ return line.section(QLatin1Char('/'), 0, 0).trimmed();
+}
+}
+
+Spelling::Spelling(QObject *parent)
+ : QObject(parent)
+ , m_settings(new Sonnet::Settings(this))
+{
+ const QMap<QString, QString> available = Sonnet::Speller().availableDictionaries();
+ QCollator collator;
+ collator.setCaseSensitivity(Qt::CaseInsensitive);
+ for (auto it = available.cbegin(); it != available.cend(); ++it) {
+ m_dictionaries << QVariantMap{{QStringLiteral("value"), it.value()}, {QStringLiteral("text"), it.key()}};
+ }
+ std::sort(m_dictionaries.begin(), m_dictionaries.end(), [&collator](const QVariant &a, const QVariant &b) {
+ return collator.compare(a.toMap().value(QStringLiteral("text")).toString(), b.toMap().value(QStringLiteral("text")).toString()) < 0;
+ });
+ readWords();
+}
+
+Spelling::~Spelling() = default;
+
+bool Spelling::enabled() const
+{
+ return m_settings->checkerEnabledByDefault();
+}
+
+bool Spelling::asYouType() const
+{
+ return m_settings->backgroundCheckerEnabled();
+}
+
+bool Spelling::skipUppercase() const
+{
+ return m_settings->skipUppercase();
+}
+
+bool Spelling::autodetect() const
+{
+ return m_settings->autodetectLanguage();
+}
+
+QString Spelling::language() const
+{
+ return m_settings->defaultLanguage();
+}
+
+QStringList Spelling::otherLanguages() const
+{
+ return m_settings->preferredLanguages();
+}
+
+void Spelling::save()
+{
+ // Sonnet has no change signal for other apps; each reads Sonnet.conf
+ // when it opens a text box, as with KDE's own module.
+ m_settings->save();
+ Q_EMIT changed();
+}
+
+void Spelling::setEnabled(bool on)
+{
+ m_settings->setCheckerEnabledByDefault(on);
+ save();
+}
+
+void Spelling::setAsYouType(bool on)
+{
+ m_settings->setBackgroundCheckerEnabled(on);
+ save();
+}
+
+void Spelling::setSkipUppercase(bool on)
+{
+ m_settings->setSkipUppercase(on);
+ save();
+}
+
+void Spelling::setAutodetect(bool on)
+{
+ m_settings->setAutodetectLanguage(on);
+ save();
+}
+
+void Spelling::setLanguage(const QString &code)
+{
+ if (code.isEmpty() || code == m_settings->defaultLanguage()) {
+ return;
+ }
+ m_settings->setDefaultLanguage(code);
+ if (m_settings->defaultLanguage() != code) {
+ return;
+ }
+ // Sonnet keeps one ignore list a language but loads only the first
+ // one; without this it would save the old language's words under the
+ // new one.
+ const QSettings stored(QStringLiteral("KDE"), QStringLiteral("Sonnet"));
+ m_settings->setCurrentIgnoreList(stored.value(QStringLiteral("ignore_%1").arg(code), Sonnet::Settings::defaultIgnoreList()).toStringList());
+ save();
+ readWords();
+}
+
+void Spelling::setOtherLanguage(const QString &code, bool on)
+{
+ QStringList list = m_settings->preferredLanguages();
+ if (on == list.contains(code)) {
+ return;
+ }
+ if (on) {
+ list << code;
+ } else {
+ list.removeAll(code);
+ }
+ m_settings->setPreferredLanguages(list);
+ save();
+}
+
+QString Spelling::personalFile() const
+{
+ return QDir::home().filePath(QStringLiteral(".hunspell_") + m_settings->defaultLanguage());
+}
+
+QStringList Spelling::personalWords() const
+{
+ QStringList list;
+ QFile file(personalFile());
+ if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
+ QTextStream in(&file);
+ while (!in.atEnd()) {
+ const QString word = baseWord(in.readLine());
+ if (!word.isEmpty()) {
+ list << word;
+ }
+ }
+ }
+ return list;
+}
+
+void Spelling::readWords()
+{
+ // Sonnet's built-in list of KDE product names is not something you
+ // added, so it stays in force without being listed.
+ const QStringList builtIn = Sonnet::Settings::defaultIgnoreList();
+ QSet<QString> seen;
+ QStringList list;
+ for (const QString &word : m_settings->currentIgnoreList() + personalWords()) {
+ if (!builtIn.contains(word) && !seen.contains(word)) {
+ seen.insert(word);
+ list << word;
+ }
+ }
+ QCollator collator;
+ collator.setCaseSensitivity(Qt::CaseInsensitive);
+ std::sort(list.begin(), list.end(), [&collator](const QString &a, const QString &b) {
+ return collator.compare(a, b) < 0;
+ });
+ m_words = list;
+ Q_EMIT changed();
+}
+
+bool Spelling::addWord(const QString &text)
+{
+ const QString word = text.trimmed();
+ if (word.isEmpty() || word.contains(QLatin1Char(' ')) || m_words.contains(word)) {
+ return false;
+ }
+ QStringList ignored = m_settings->currentIgnoreList();
+ if (!ignored.contains(word)) {
+ ignored << word;
+ m_settings->setCurrentIgnoreList(ignored);
+ m_settings->save();
+ }
+ readWords();
+ return true;
+}
+
+void Spelling::removeWord(const QString &word)
+{
+ QStringList ignored = m_settings->currentIgnoreList();
+ if (ignored.removeAll(word) > 0) {
+ m_settings->setCurrentIgnoreList(ignored);
+ m_settings->save();
+ }
+
+ QFile file(personalFile());
+ if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
+ QStringList kept;
+ bool found = false;
+ QTextStream in(&file);
+ while (!in.atEnd()) {
+ const QString line = in.readLine();
+ if (baseWord(line) == word) {
+ found = true;
+ } else {
+ kept << line;
+ }
+ }
+ file.close();
+ if (found) {
+ QSaveFile out(personalFile());
+ if (out.open(QIODevice::WriteOnly | QIODevice::Text)) {
+ QTextStream stream(&out);
+ for (const QString &line : std::as_const(kept)) {
+ stream << line << '\n';
+ }
+ stream.flush();
+ out.commit();
+ }
+ }
+ }
+ readWords();
+}
diff --git a/packages/wildos-settings/src/spelling.h b/packages/wildos-settings/src/spelling.h
new file mode 100644
index 0000000..d6dc4b9
--- /dev/null
+++ b/packages/wildos-settings/src/spelling.h
@@ -0,0 +1,69 @@
+#pragma once
+
+#include <QObject>
+#include <QQmlEngine>
+#include <QStringList>
+#include <QVariantList>
+
+namespace Sonnet
+{
+class Settings;
+}
+
+// Spell checking for every app that uses KDE's Sonnet (Kate, KMail, text
+// boxes in KDE apps), kept where KDE's own spell checking module keeps it:
+// Sonnet::Settings, which writes ~/.config/KDE/Sonnet.conf. Your own words
+// are Sonnet's ignore list for the spelling language, plus the words the
+// "Add to dictionary" menu item saved in Hunspell's ~/.hunspell_<language>.
+class Spelling : public QObject
+{
+ Q_OBJECT
+ QML_ELEMENT
+ QML_SINGLETON
+
+ Q_PROPERTY(bool enabled READ enabled NOTIFY changed)
+ Q_PROPERTY(bool asYouType READ asYouType NOTIFY changed)
+ Q_PROPERTY(bool skipUppercase READ skipUppercase NOTIFY changed)
+ Q_PROPERTY(bool autodetect READ autodetect NOTIFY changed)
+ Q_PROPERTY(QString language READ language NOTIFY changed)
+ Q_PROPERTY(QStringList otherLanguages READ otherLanguages NOTIFY changed)
+ // [{ value: "en_GB", text: "English (United Kingdom)" }]
+ Q_PROPERTY(QVariantList dictionaries READ dictionaries NOTIFY changed)
+ Q_PROPERTY(QStringList words READ words NOTIFY changed)
+
+public:
+ explicit Spelling(QObject *parent = nullptr);
+ ~Spelling() override;
+
+ bool enabled() const;
+ bool asYouType() const;
+ bool skipUppercase() const;
+ bool autodetect() const;
+ QString language() const;
+ QStringList otherLanguages() const;
+ QVariantList dictionaries() const { return m_dictionaries; }
+ QStringList words() const { return m_words; }
+
+ Q_INVOKABLE void setEnabled(bool on);
+ Q_INVOKABLE void setAsYouType(bool on);
+ Q_INVOKABLE void setSkipUppercase(bool on);
+ Q_INVOKABLE void setAutodetect(bool on);
+ Q_INVOKABLE void setLanguage(const QString &code);
+ Q_INVOKABLE void setOtherLanguage(const QString &code, bool on);
+ // False when the word is empty, has a space or is already there.
+ Q_INVOKABLE bool addWord(const QString &word);
+ Q_INVOKABLE void removeWord(const QString &word);
+
+Q_SIGNALS:
+ void changed();
+
+private:
+ void save();
+ void readWords();
+ QString personalFile() const;
+ QStringList personalWords() const;
+
+ Sonnet::Settings *m_settings;
+ QVariantList m_dictionaries;
+ QStringList m_words;
+};
diff --git a/packages/wildos-settings/src/system.cpp b/packages/wildos-settings/src/system.cpp
index 652e04f..0fb467a 100644
--- a/packages/wildos-settings/src/system.cpp
+++ b/packages/wildos-settings/src/system.cpp
@@ -13,11 +13,9 @@
#include <QDirIterator>
#include <QFile>
#include <QFileInfo>
-#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QLocale>
-#include <QMap>
#include <QProcess>
#include <QRegularExpression>
#include <QSet>
@@ -642,7 +640,17 @@ void System::setColourScheme(const QString &name)
if (name == m_colourScheme) {
return;
}
- const QColor accent = m_accent;
+ QColor accent = 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")) {
+ KSharedConfigPtr wildos = KSharedConfig::openConfig(QStringLiteral("wildosrc"));
+ wildos->reparseConfiguration();
+ const QStringList rgb = wildos->group(QStringLiteral("Accessibility")).readEntry("AccentBeforeContrast", QString()).split(QLatin1Char(','));
+ if (rgb.size() >= 3) {
+ accent = QColor(rgb[0].trimmed().toInt(), rgb[1].trimmed().toInt(), rgb[2].trimmed().toInt());
+ }
+ }
// Applying a scheme resets the accent key, so the accent goes back on
// once the tool is done, the way setAccent writes it.
const auto finish = [this, accent] {
@@ -881,6 +889,36 @@ void System::setTaskbarCentred(bool centred)
Q_EMIT taskbarCentredChanged();
}
+// The taskbar's showOnlyCurrentDesktop, the stock task manager's key, which
+// the Wild OS taskbar (org.wildos.tasks) binds its desktop filter to.
+namespace
+{
+const QString tasksScript = QStringLiteral(
+ "var tasks = []; panels().forEach(function (p) { tasks = tasks.concat(p.widgets('org.wildos.tasks')); });");
+}
+
+void System::readTaskbarDesktops()
+{
+ const QString only = evaluatePlasmaScript(tasksScript
+ + QStringLiteral("if (tasks.length) { tasks[0].currentConfigGroup = ['General']; print(String(tasks[0].readConfig('showOnlyCurrentDesktop', true))); }"));
+ const bool all = only == QLatin1String("false");
+ if (all != m_taskbarAllDesktops) {
+ m_taskbarAllDesktops = all;
+ Q_EMIT taskbarAllDesktopsChanged();
+ }
+}
+
+void System::setTaskbarAllDesktops(bool all)
+{
+ evaluatePlasmaScript(tasksScript
+ + QStringLiteral("tasks.forEach(function (t) { t.currentConfigGroup = ['General']; t.writeConfig('showOnlyCurrentDesktop', %1); t.reloadConfig(); });")
+ .arg(all ? QStringLiteral("false") : QStringLiteral("true")));
+ if (all != m_taskbarAllDesktops) {
+ m_taskbarAllDesktops = all;
+ Q_EMIT taskbarAllDesktopsChanged();
+ }
+}
+
// 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)
@@ -1348,91 +1386,6 @@ void System::setPowerProfile(const QString &profile)
Q_EMIT powerChanged();
}
-// Screens are read and changed with kscreen-doctor, the command line side of
-// the same KScreen service the display module uses, so changes are kept and
-// restored at the next sign-in exactly as if made there.
-void System::refreshDisplays()
-{
- if (!hasProgram(QStringLiteral("kscreen-doctor"))) {
- return;
- }
- auto process = new QProcess(this);
- connect(process, &QProcess::finished, this, [this, process] {
- process->deleteLater();
- const QJsonObject root = QJsonDocument::fromJson(process->readAllStandardOutput()).object();
- QVariantList list;
- const QJsonArray outputs = root.value(QStringLiteral("outputs")).toArray();
- for (const QJsonValue &value : outputs) {
- const QJsonObject output = value.toObject();
- if (!output.value(QStringLiteral("connected")).toBool()) {
- continue;
- }
- const QString currentMode = output.value(QStringLiteral("currentModeId")).toVariant().toString();
- QVariantList modes;
- QString currentSize;
- double currentRate = 0;
- // One entry per resolution, at its highest refresh rate, as
- // Windows lists them; the rate has its own setting.
- QMap<qint64, QVariantMap> bySize;
- const QJsonArray modeList = output.value(QStringLiteral("modes")).toArray();
- for (const QJsonValue &m : modeList) {
- const QJsonObject mode = m.toObject();
- const QJsonObject size = mode.value(QStringLiteral("size")).toObject();
- const int w = size.value(QStringLiteral("width")).toInt();
- const int h = size.value(QStringLiteral("height")).toInt();
- const double rate = mode.value(QStringLiteral("refreshRate")).toDouble();
- const QString id = mode.value(QStringLiteral("id")).toVariant().toString();
- if (id == currentMode) {
- currentSize = QStringLiteral("%1 × %2").arg(w).arg(h);
- currentRate = rate;
- }
- const qint64 key = qint64(w) * 100000 + h;
- if (!bySize.contains(key) || bySize[key].value(QStringLiteral("rate")).toDouble() < rate) {
- bySize[key] = {{QStringLiteral("id"), id}, {QStringLiteral("text"), QStringLiteral("%1 × %2").arg(w).arg(h)},
- {QStringLiteral("rate"), rate}, {QStringLiteral("pixels"), qint64(w) * h}};
- }
- }
- for (auto it = bySize.constEnd(); it != bySize.constBegin();) {
- --it;
- modes << it.value();
- }
- list << QVariantMap{
- {QStringLiteral("name"), output.value(QStringLiteral("name")).toString()},
- {QStringLiteral("enabled"), output.value(QStringLiteral("enabled")).toBool()},
- {QStringLiteral("primary"), output.value(QStringLiteral("priority")).toInt() == 1},
- {QStringLiteral("scale"), output.value(QStringLiteral("scale")).toDouble(1.0)},
- {QStringLiteral("rotation"), output.value(QStringLiteral("rotation")).toInt(1)},
- {QStringLiteral("modes"), modes},
- {QStringLiteral("currentMode"), currentMode},
- {QStringLiteral("currentSize"), currentSize},
- {QStringLiteral("currentRate"), currentRate},
- {QStringLiteral("builtIn"), output.value(QStringLiteral("type")).toInt() == 7 || output.value(QStringLiteral("name")).toString().startsWith(QLatin1String("eDP"))},
- };
- }
- // The main screen first, as Windows numbers it 1.
- std::stable_sort(list.begin(), list.end(), [](const QVariant &a, const QVariant &b) {
- return a.toMap().value(QStringLiteral("primary")).toBool() && !b.toMap().value(QStringLiteral("primary")).toBool();
- });
- m_displays = list;
- Q_EMIT displaysChanged();
- });
- process->start(QStringLiteral("kscreen-doctor"), {QStringLiteral("-j")});
-}
-
-void System::setDisplay(const QString &output, const QString &setting, const QString &value)
-{
- static const QRegularExpression safe(QStringLiteral("^[A-Za-z0-9._-]+$"));
- if (!safe.match(output).hasMatch() || !safe.match(setting).hasMatch() || !safe.match(value).hasMatch()) {
- return;
- }
- auto process = new QProcess(this);
- connect(process, &QProcess::finished, this, [this, process] {
- process->deleteLater();
- refreshDisplays();
- });
- process->start(QStringLiteral("kscreen-doctor"), {QStringLiteral("output.%1.%2.%3").arg(output, setting, value)});
-}
-
void System::reloadScreenLocker()
{
auto message = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.ScreenSaver"), QStringLiteral("/ScreenSaver"),
diff --git a/packages/wildos-settings/src/system.h b/packages/wildos-settings/src/system.h
index b325815..6df32c7 100644
--- a/packages/wildos-settings/src/system.h
+++ b/packages/wildos-settings/src/system.h
@@ -48,6 +48,9 @@ class System : public QObject
Q_PROPERTY(bool taskbarCentred READ taskbarCentred NOTIFY taskbarCentredChanged)
// Floating panels instead of the docked bar (wildos-shell reads it).
Q_PROPERTY(bool taskbarFloating READ taskbarFloating NOTIFY taskbarFloatingChanged)
+ // 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)
Q_PROPERTY(QString wallpaperName READ wallpaperName NOTIFY wallpaperChanged)
Q_PROPERTY(bool slideshow READ slideshow NOTIFY wallpaperChanged)
Q_PROPERTY(QString slideshowFolder READ slideshowFolder NOTIFY wallpaperChanged)
@@ -62,7 +65,6 @@ class System : public QObject
Q_PROPERTY(QString storeApp READ storeApp CONSTANT)
Q_PROPERTY(QString powerProfile READ powerProfile NOTIFY powerChanged)
Q_PROPERTY(QStringList powerProfiles READ powerProfiles NOTIFY powerChanged)
- Q_PROPERTY(QVariantList displays READ displays NOTIFY displaysChanged)
Q_PROPERTY(bool snapEdges READ snapEdges WRITE setSnapEdges NOTIFY kwinChanged)
Q_PROPERTY(bool snapLayouts READ snapLayouts WRITE setSnapLayouts NOTIFY kwinChanged)
@@ -102,6 +104,7 @@ public:
int taskbarHiding() const { return m_taskbarHiding; }
bool taskbarCentred() const { return m_taskbarCentred; }
bool taskbarFloating() const { return m_taskbarFloating; }
+ bool taskbarAllDesktops() const { return m_taskbarAllDesktops; }
QString wallpaperName() const;
bool slideshow() const { return m_slideshow; }
QString slideshowFolder() const { return m_slideshowFolder; }
@@ -114,7 +117,6 @@ public:
QString storeApp() const;
QString powerProfile() const { return m_powerProfile; }
QStringList powerProfiles() const { return m_powerProfiles; }
- QVariantList displays() const { return m_displays; }
bool snapEdges() const;
void setSnapEdges(bool on);
@@ -145,6 +147,8 @@ public:
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 setSlideshow(bool on, const QString &folder = {});
Q_INVOKABLE void setTransparency(bool on);
Q_INVOKABLE void setTextScale(int percent);
@@ -164,8 +168,6 @@ public:
Q_INVOKABLE void reloadScreenLocker();
Q_INVOKABLE void refreshPower();
Q_INVOKABLE void setPowerProfile(const QString &profile);
- Q_INVOKABLE void refreshDisplays();
- Q_INVOKABLE void setDisplay(const QString &output, const QString &setting, const QString &value);
Q_INVOKABLE bool hasProgram(const QString &program) const;
Q_INVOKABLE void launch(const QString &program, const QStringList &arguments = {});
@@ -184,6 +186,7 @@ Q_SIGNALS:
void taskbarHidingChanged();
void taskbarCentredChanged();
void taskbarFloatingChanged();
+ void taskbarAllDesktopsChanged();
void transparencyChanged();
void textScaleChanged();
void updatePolicyChanged();
@@ -194,7 +197,6 @@ Q_SIGNALS:
void firmwareRestartFailed(const QString &reason);
void appUpdatesChanged();
void powerChanged();
- void displaysChanged();
void kwinChanged();
void binEmptied();
@@ -231,6 +233,7 @@ private:
int m_taskbarHiding = 0;
bool m_taskbarCentred = true;
bool m_taskbarFloating = false;
+ bool m_taskbarAllDesktops = false;
bool m_slideshow = false;
QString m_slideshowFolder;
int m_textScale = 100;
@@ -242,7 +245,6 @@ private:
int m_appUpdates = -1;
QString m_powerProfile;
QStringList m_powerProfiles;
- QVariantList m_displays;
KConfigWatcher::Ptr m_globals;
};
diff --git a/packages/wildos-settings/src/thunderbolt.cpp b/packages/wildos-settings/src/thunderbolt.cpp
new file mode 100644
index 0000000..6e58de4
--- /dev/null
+++ b/packages/wildos-settings/src/thunderbolt.cpp
@@ -0,0 +1,140 @@
+#include "thunderbolt.h"
+
+#include <QDBusArgument>
+#include <QDBusConnection>
+#include <QDBusError>
+#include <QDBusMessage>
+#include <QDBusObjectPath>
+#include <QDBusPendingCallWatcher>
+#include <QDBusPendingReply>
+#include <QDBusVariant>
+
+namespace
+{
+const QString service = QStringLiteral("org.freedesktop.bolt");
+const QString managerPath = QStringLiteral("/org/freedesktop/bolt");
+const QString managerInterface = QStringLiteral("org.freedesktop.bolt1.Manager");
+const QString deviceInterface = QStringLiteral("org.freedesktop.bolt1.Device");
+const QString properties = QStringLiteral("org.freedesktop.DBus.Properties");
+
+QVariantMap allProperties(const QString &path, const QString &interface)
+{
+ auto message = QDBusMessage::createMethodCall(service, path, properties, QStringLiteral("GetAll"));
+ message << interface;
+ const QDBusMessage reply = QDBusConnection::systemBus().call(message, QDBus::Block, 3000);
+ if (reply.type() != QDBusMessage::ReplyMessage || reply.arguments().isEmpty()) {
+ return {};
+ }
+ QVariantMap map;
+ const QDBusArgument arg = reply.arguments().constFirst().value<QDBusArgument>();
+ arg >> map;
+ for (auto it = map.begin(); it != map.end(); ++it) {
+ if (it.value().canConvert<QDBusVariant>()) {
+ it.value() = it.value().value<QDBusVariant>().variant();
+ }
+ }
+ return map;
+}
+}
+
+Thunderbolt::Thunderbolt(QObject *parent)
+ : QObject(parent)
+{
+ QDBusConnection bus = QDBusConnection::systemBus();
+ bus.connect(service, managerPath, managerInterface, QStringLiteral("DeviceAdded"), this, SLOT(onChanged()));
+ bus.connect(service, managerPath, managerInterface, QStringLiteral("DeviceRemoved"), this, SLOT(onChanged()));
+ // A device's status or stored flag changing, on whichever device path.
+ bus.connect(service, QString(), properties, QStringLiteral("PropertiesChanged"), this, SLOT(onChanged()));
+ reload();
+}
+
+void Thunderbolt::onChanged()
+{
+ reload();
+}
+
+void Thunderbolt::reload()
+{
+ const QVariantMap manager = allProperties(managerPath, managerInterface);
+ m_available = !manager.isEmpty();
+ const QString security = manager.value(QStringLiteral("SecurityLevel")).toString();
+ m_firmwareOff = security == QLatin1String("dponly") || security == QLatin1String("usbonly");
+ m_hasPorts = false;
+ m_devices.clear();
+
+ if (m_available) {
+ auto message = QDBusMessage::createMethodCall(service, managerPath, managerInterface, QStringLiteral("ListDevices"));
+ const QDBusMessage reply = QDBusConnection::systemBus().call(message, QDBus::Block, 3000);
+ QList<QDBusObjectPath> paths;
+ if (reply.type() == QDBusMessage::ReplyMessage && !reply.arguments().isEmpty()) {
+ reply.arguments().constFirst().value<QDBusArgument>() >> paths;
+ }
+ for (const QDBusObjectPath &path : std::as_const(paths)) {
+ const QVariantMap device = allProperties(path.path(), deviceInterface);
+ if (device.isEmpty()) {
+ continue;
+ }
+ // Each Thunderbolt or USB4 controller in the PC is listed as a
+ // "host" device, so a PC with none has no such ports.
+ if (device.value(QStringLiteral("Type")).toString() == QLatin1String("host")) {
+ m_hasPorts = true;
+ continue;
+ }
+ const QString label = device.value(QStringLiteral("Label")).toString();
+ m_devices.append(QVariantMap{
+ {QStringLiteral("uid"), device.value(QStringLiteral("Uid"))},
+ {QStringLiteral("name"), label.isEmpty() ? device.value(QStringLiteral("Name")) : QVariant(label)},
+ {QStringLiteral("vendor"), device.value(QStringLiteral("Vendor"))},
+ {QStringLiteral("status"), device.value(QStringLiteral("Status"))},
+ {QStringLiteral("stored"), device.value(QStringLiteral("Stored"))},
+ });
+ }
+ // A remembered device is listed even when the controller is not.
+ m_hasPorts = m_hasPorts || !m_devices.isEmpty();
+ }
+ Q_EMIT changed();
+}
+
+void Thunderbolt::setBusy(const QString &uid)
+{
+ if (m_busy != uid) {
+ m_busy = uid;
+ Q_EMIT busyChanged();
+ }
+}
+
+void Thunderbolt::call(const QString &uid, const QString &method, const QVariantList &arguments, const QString &failure)
+{
+ if (!m_busy.isEmpty()) {
+ return;
+ }
+ setBusy(uid);
+ auto message = QDBusMessage::createMethodCall(service, managerPath, managerInterface, method);
+ message.setArguments(arguments);
+ // boltd checks with polkit, which may need to ask for a password.
+ message.setInteractiveAuthorizationAllowed(true);
+ auto watcher = new QDBusPendingCallWatcher(QDBusConnection::systemBus().asyncCall(message, 120000), this);
+ connect(watcher, &QDBusPendingCallWatcher::finished, this, [this, watcher, failure] {
+ watcher->deleteLater();
+ const QDBusPendingReply<> reply = *watcher;
+ setBusy(QString());
+ if (reply.isError()) {
+ const QDBusError error = reply.error();
+ Q_EMIT failed(failure, error.type() == QDBusError::AccessDenied ? QStringLiteral("Only an administrator can do this.") : error.message());
+ }
+ reload();
+ });
+}
+
+void Thunderbolt::allow(const QString &uid)
+{
+ // The policy and flags KDE's module enrols with: let the device in
+ // again at start-up too, without a key challenge, which most devices
+ // cannot answer.
+ call(uid, QStringLiteral("EnrollDevice"), {uid, QStringLiteral("default"), QStringLiteral("boot | nokey")}, QStringLiteral("The device was not allowed"));
+}
+
+void Thunderbolt::forget(const QString &uid)
+{
+ call(uid, QStringLiteral("ForgetDevice"), {uid}, QStringLiteral("The device was not forgotten"));
+}
diff --git a/packages/wildos-settings/src/thunderbolt.h b/packages/wildos-settings/src/thunderbolt.h
new file mode 100644
index 0000000..2a3347d
--- /dev/null
+++ b/packages/wildos-settings/src/thunderbolt.h
@@ -0,0 +1,59 @@
+#pragma once
+
+#include <QObject>
+#include <QQmlEngine>
+#include <QVariantList>
+
+// Thunderbolt and USB4 devices through boltd (org.freedesktop.bolt on the
+// system bus), which is what KDE's Thunderbolt module drives. Allowing a
+// device enrols it with boltd, so it is let in again on its own the next
+// time; forgetting takes that away. boltd asks polkit, which lets an
+// administrator in and asks anyone else for a password.
+class Thunderbolt : public QObject
+{
+ Q_OBJECT
+ QML_ELEMENT
+ QML_SINGLETON
+
+ Q_PROPERTY(bool available READ available NOTIFY changed)
+ Q_PROPERTY(bool hasPorts READ hasPorts NOTIFY changed)
+ Q_PROPERTY(bool firmwareOff READ firmwareOff NOTIFY changed)
+ Q_PROPERTY(QVariantList devices READ devices NOTIFY changed)
+ Q_PROPERTY(QString busy READ busy NOTIFY busyChanged)
+
+public:
+ explicit Thunderbolt(QObject *parent = nullptr);
+
+ bool available() const { return m_available; }
+ bool hasPorts() const { return m_hasPorts; }
+ // The firmware leaves the ports to DisplayPort or USB only.
+ bool firmwareOff() const { return m_firmwareOff; }
+ // Peripherals as { uid, name, vendor, status, stored }, where status is
+ // boltd's own word: connected, authorizing, authorized, auth-error,
+ // disconnected and so on.
+ QVariantList devices() const { return m_devices; }
+ // The uid of the device being allowed or forgotten.
+ QString busy() const { return m_busy; }
+
+ Q_INVOKABLE void reload();
+ Q_INVOKABLE void allow(const QString &uid);
+ Q_INVOKABLE void forget(const QString &uid);
+
+Q_SIGNALS:
+ void changed();
+ void busyChanged();
+ void failed(const QString &title, const QString &reason);
+
+private Q_SLOTS:
+ void onChanged();
+
+private:
+ void call(const QString &uid, const QString &method, const QVariantList &arguments, const QString &failure);
+ void setBusy(const QString &uid);
+
+ bool m_available = false;
+ bool m_hasPorts = false;
+ bool m_firmwareOff = false;
+ QVariantList m_devices;
+ QString m_busy;
+};
diff --git a/packages/wildos-shell/CMakeLists.txt b/packages/wildos-shell/CMakeLists.txt
index 81c2b23..4de7682 100644
--- a/packages/wildos-shell/CMakeLists.txt
+++ b/packages/wildos-shell/CMakeLists.txt
@@ -27,3 +27,4 @@ install(FILES ${CMAKE_CURRENT_BINARY_DIR}/org/wildos/shell/qmldir DESTINATION ${
add_subdirectory(effects/roundcorners)
add_subdirectory(windowmenu)
+add_subdirectory(slowkeys)
diff --git a/packages/wildos-shell/slowkeys/CMakeLists.txt b/packages/wildos-shell/slowkeys/CMakeLists.txt
new file mode 100644
index 0000000..7737123
--- /dev/null
+++ b/packages/wildos-shell/slowkeys/CMakeLists.txt
@@ -0,0 +1,14 @@
+# Slow keys for KWin 6.3, which has sticky and bounce keys but not this one
+# (KWin added its own after 6.5). Built against the exact KWin it runs in,
+# like the window menu.
+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_slowkeys MODULE main.cpp slowkeys.cpp slowkeys.h)
+set_target_properties(wildos_slowkeys PROPERTIES AUTOMOC ON PREFIX "")
+target_link_libraries(wildos_slowkeys PRIVATE KWin::kwin KF6::ConfigCore Qt6::Core Qt6::Gui)
+
+install(TARGETS wildos_slowkeys LIBRARY DESTINATION ${QT6_INSTALL_PLUGINS}/kwin/plugins)
diff --git a/packages/wildos-shell/slowkeys/main.cpp b/packages/wildos-shell/slowkeys/main.cpp
new file mode 100644
index 0000000..c3db8ac
--- /dev/null
+++ b/packages/wildos-shell/slowkeys/main.cpp
@@ -0,0 +1,28 @@
+/*
+ SPDX-FileCopyrightText: 2026 Wild OS Developers <[email protected]>
+
+ SPDX-License-Identifier: GPL-2.0-or-later
+*/
+
+#include <main.h>
+#include <plugin.h>
+
+#include "slowkeys.h"
+
+class KWIN_EXPORT SlowKeysFactory : public KWin::PluginFactory
+{
+ Q_OBJECT
+ Q_PLUGIN_METADATA(IID PluginFactory_iid FILE "metadata.json")
+ Q_INTERFACES(KWin::PluginFactory)
+
+public:
+ std::unique_ptr<KWin::Plugin> create() const override
+ {
+ if (KWin::kwinApp()->operationMode() != KWin::Application::OperationModeWayland) {
+ return nullptr;
+ }
+ return std::make_unique<WildOS::SlowKeys>();
+ }
+};
+
+#include "main.moc"
diff --git a/packages/wildos-shell/slowkeys/metadata.json b/packages/wildos-shell/slowkeys/metadata.json
new file mode 100644
index 0000000..17eb24d
--- /dev/null
+++ b/packages/wildos-shell/slowkeys/metadata.json
@@ -0,0 +1,8 @@
+{
+ "KPlugin": {
+ "Description": "Slow keys from Settings > Accessibility: a key counts only once it has been held down for a moment",
+ "EnabledByDefault": true,
+ "License": "GPL",
+ "Name": "Wild OS slow keys"
+ }
+}
diff --git a/packages/wildos-shell/slowkeys/slowkeys.cpp b/packages/wildos-shell/slowkeys/slowkeys.cpp
new file mode 100644
index 0000000..509d63f
--- /dev/null
+++ b/packages/wildos-shell/slowkeys/slowkeys.cpp
@@ -0,0 +1,101 @@
+/*
+ SPDX-FileCopyrightText: 2025 Martin Riethmayer <[email protected]>
+ SPDX-FileCopyrightText: 2026 Wild OS Developers <[email protected]>
+
+ SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
+*/
+
+#include "slowkeys.h"
+
+#include <effect/effect.h>
+#include <effect/effecthandler.h>
+
+namespace WildOS
+{
+
+SlowKeys::SlowKeys()
+ // Ahead of sticky keys, as in KWin's own order, so a brushed Shift is
+ // never latched.
+ : KWin::InputEventFilter(KWin::InputFilterOrder::BounceKeys)
+ , m_configWatcher(KConfigWatcher::create(KSharedConfig::openConfig(QStringLiteral("kaccessrc"))))
+{
+ const QLatin1String groupName("Keyboard");
+ connect(m_configWatcher.get(), &KConfigWatcher::configChanged, this, [this, groupName](const KConfigGroup &group) {
+ if (group.name() == groupName) {
+ loadConfig(group);
+ }
+ });
+ loadConfig(m_configWatcher->config()->group(groupName));
+}
+
+void SlowKeys::loadConfig(const KConfigGroup &group)
+{
+ KWin::input()->uninstallInputEventFilter(this);
+
+ if (group.readEntry<bool>("SlowKeys", false)) {
+ KWin::input()->installInputEventFilter(this);
+ m_delay = std::chrono::milliseconds(group.readEntry<int>("SlowKeysDelay", 500));
+ m_pressBeep = group.readEntry<bool>("SlowKeysPressBeep", false);
+ m_acceptBeep = group.readEntry<bool>("SlowKeysAcceptBeep", false);
+ m_rejectBeep = group.readEntry<bool>("SlowKeysRejectBeep", false);
+ } else {
+ m_keys.clear();
+ }
+}
+
+void SlowKeys::ring() const
+{
+ if (KWin::effects) {
+ if (auto effect = KWin::effects->provides(KWin::Effect::SystemBell)) {
+ effect->perform(KWin::Effect::SystemBell, {});
+ }
+ }
+}
+
+bool SlowKeys::keyboardKey(KWin::KeyboardKeyEvent *event)
+{
+ const auto now = std::chrono::steady_clock::now();
+
+ switch (event->state) {
+ case KWin::KeyboardKeyState::Pressed:
+ case KWin::KeyboardKeyState::Repeated: {
+ const auto it = m_keys.find(event->key);
+ if (it == m_keys.end()) {
+ m_keys.insert(event->key, Key{now, 0});
+ if (m_pressBeep) {
+ ring();
+ }
+ return true;
+ }
+ if (now - it->pressed < m_delay) {
+ if (m_rejectBeep) {
+ ring();
+ }
+ return true;
+ }
+ if (m_acceptBeep && it->sent == 0) {
+ ring();
+ }
+ // Everything before was held back, so the app sees a press first
+ // and only then repeats.
+ event->state = it->sent == 0 ? KWin::KeyboardKeyState::Pressed : KWin::KeyboardKeyState::Repeated;
+ it->pressed = now;
+ ++it->sent;
+ return false;
+ }
+ case KWin::KeyboardKeyState::Released: {
+ const auto it = m_keys.find(event->key);
+ if (it == m_keys.end()) {
+ return false;
+ }
+ const bool seen = it->sent != 0;
+ m_keys.erase(it);
+ return !seen;
+ }
+ }
+ return false;
+}
+
+}
+
+#include "moc_slowkeys.cpp"
diff --git a/packages/wildos-shell/slowkeys/slowkeys.h b/packages/wildos-shell/slowkeys/slowkeys.h
new file mode 100644
index 0000000..0b80181
--- /dev/null
+++ b/packages/wildos-shell/slowkeys/slowkeys.h
@@ -0,0 +1,55 @@
+/*
+ SPDX-FileCopyrightText: 2025 Martin Riethmayer <[email protected]>
+ SPDX-FileCopyrightText: 2026 Wild OS Developers <[email protected]>
+
+ SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
+*/
+
+#pragma once
+
+#include <input.h>
+#include <input_event.h>
+#include <plugin.h>
+
+#include <KConfigWatcher>
+
+#include <QHash>
+
+#include <chrono>
+
+namespace WildOS
+{
+
+// KWin's slow keys filter from after Plasma 6.5, on KWin 6.3's API. It
+// reads the keys kcm_access and Settings write (kaccessrc [Keyboard]
+// SlowKeys, SlowKeysDelay and the three beeps), so it follows Settings >
+// Accessibility live, in the session, on the lock screen and on the
+// sign-in screen alike. A press is held back until the key has been down
+// for the delay; KWin's key repeat delivers the moment it is accepted.
+class SlowKeys : public KWin::Plugin, public KWin::InputEventFilter
+{
+ Q_OBJECT
+
+public:
+ SlowKeys();
+
+ bool keyboardKey(KWin::KeyboardKeyEvent *event) override;
+
+private:
+ struct Key {
+ std::chrono::steady_clock::time_point pressed;
+ uint32_t sent = 0;
+ };
+
+ void loadConfig(const KConfigGroup &group);
+ void ring() const;
+
+ KConfigWatcher::Ptr m_configWatcher;
+ std::chrono::milliseconds m_delay{500};
+ bool m_pressBeep = false;
+ bool m_acceptBeep = false;
+ bool m_rejectBeep = false;
+ QHash<int, Key> m_keys;
+};
+
+}
diff --git a/packages/wildos-ui/CMakeLists.txt b/packages/wildos-ui/CMakeLists.txt
index 3e9cd43..93272a9 100644
--- a/packages/wildos-ui/CMakeLists.txt
+++ b/packages/wildos-ui/CMakeLists.txt
@@ -36,6 +36,7 @@ qt_add_qml_module(wildosui
src/windowframe.cpp src/windowframe.h
src/themeicon.cpp src/themeicon.h
src/system.cpp src/system.h
+ src/accessshortcuts.cpp src/accessshortcuts.h
)
target_include_directories(wildosui PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
diff --git a/packages/wildos-ui/gallery/Gallery.qml b/packages/wildos-ui/gallery/Gallery.qml
index 590e9e1..22d7c31 100644
--- a/packages/wildos-ui/gallery/Gallery.qml
+++ b/packages/wildos-ui/gallery/Gallery.qml
@@ -297,6 +297,19 @@ Window {
UI.Chip { text: "Your Home folder only"; iconName: "folder" }
UI.Chip { text: "No internet"; granted: false }
}
+ States {
+ label: "Shortcut keys"
+ UI.KeyChip { text: "Super" }
+ UI.ShortcutKeys { keys: ["Super", "Alt", "S"] }
+ UI.ShortcutKeys { keys: ["Shift ×5"] }
+ }
+ States {
+ label: "Colour swatches"
+ UI.Swatch { colour: "#ffffff"; name: "White"; selected: true }
+ UI.Swatch { colour: "#111111"; name: "Black" }
+ UI.Swatch { colour: "#f2d34a"; name: "Yellow" }
+ UI.Swatch { colour: "#7fd6c8"; name: "Sea glass" }
+ }
States {
label: "Avatar"
UI.Avatar { size: 60 }
diff --git a/packages/wildos-ui/qml/ComboBox.qml b/packages/wildos-ui/qml/ComboBox.qml
index 2ebb964..05e0343 100644
--- a/packages/wildos-ui/qml/ComboBox.qml
+++ b/packages/wildos-ui/qml/ComboBox.qml
@@ -13,7 +13,9 @@ import QtQuick.Templates as T
//
// Give it `model: [{ value, text }]` (textRole "text", valueRole "value"
// are the defaults), read `currentValue`, and set the choice from the
-// backend with `currentIndex: indexOfValue(backend.value)`.
+// backend with `currentIndex: model.findIndex(o => o.value === backend.value)`.
+// Not indexOfValue(): a binding doesn't see the list it searches, so it ran
+// once before the list was loaded and left the box blank.
T.ComboBox {
id: control
diff --git a/packages/wildos-ui/qml/Icons.qml b/packages/wildos-ui/qml/Icons.qml
index 5b06420..a888512 100644
--- a/packages/wildos-ui/qml/Icons.qml
+++ b/packages/wildos-ui/qml/Icons.qml
@@ -173,7 +173,7 @@ QtObject {
// Lock, sign-in and power screens.
"restart": "M20 12a8 8 0 1 1-2.3-5.7M20 4v5h-5",
"hibernate": r(4, 4, 16, 16, 3) + "M9 9.5h6l-6 5h6",
- "accessibility": c(12, 4.5, 1.8) + "M5 8.5l7 1.5 7-1.5M12 10v5M9 21l3-6 3 6",
+ "accessibility": c(12, 4.5, 1.8) + "M5 8.5l7 1.5 7-1.5M12 10v4.5M12 14.5l-3.5 6M12 14.5l3.5 6",
"caps-lock": "M12 4l7 7h-4v5H9v-5H5zM9 20h6",
"task-manager": "M3 12h4l3-7 4 14 3-7h4",
// Task Manager's pages (TaskManager.dc navigation).
diff --git a/packages/wildos-ui/qml/KeyChip.qml b/packages/wildos-ui/qml/KeyChip.qml
new file mode 100644
index 0000000..9789923
--- /dev/null
+++ b/packages/wildos-ui/qml/KeyChip.qml
@@ -0,0 +1,38 @@
+import QtQuick
+
+// One key of a keyboard shortcut, as the design draws a <kbd> (the
+// Accessibility shortcuts, SettingsAccessibility.dc): 22px tall and at
+// least as wide, 6px either side of an 11px medium label, a 5px corner and
+// a hairline that is a pixel heavier along the bottom, like a keycap. The
+// label grows with the text size; the cap grows with it.
+Rectangle {
+ id: chip
+
+ property string text
+
+ implicitWidth: Math.max(implicitHeight, label.implicitWidth + 12)
+ implicitHeight: Math.max(22, label.implicitHeight + 6)
+ radius: 5
+ color: Style.surfaceControl
+ border.width: 1
+ border.color: Style.tone(0.20)
+ Accessible.ignored: true
+
+ Rectangle {
+ x: 3
+ y: parent.height - 2
+ width: parent.width - 6
+ height: 1
+ color: chip.border.color
+ }
+
+ Label {
+ id: label
+ anchors.centerIn: parent
+ anchors.verticalCenterOffset: -0.5
+ text: chip.text
+ size: 11
+ font.weight: Font.Medium
+ color: Style.ink
+ }
+}
diff --git a/packages/wildos-ui/qml/ShortcutKeys.qml b/packages/wildos-ui/qml/ShortcutKeys.qml
new file mode 100644
index 0000000..9cfb4ef
--- /dev/null
+++ b/packages/wildos-ui/qml/ShortcutKeys.qml
@@ -0,0 +1,22 @@
+import QtQuick
+
+// A keyboard shortcut as a row of KeyChips 4px apart ("Super", "Alt",
+// "S"). Read out as one phrase, the keys joined by "plus".
+Row {
+ id: shortcut
+
+ property var keys: []
+
+ spacing: 4
+ Accessible.role: Accessible.StaticText
+ Accessible.name: "Shortcut: " + shortcut.keys.join(" plus ")
+
+ Repeater {
+ model: shortcut.keys
+
+ KeyChip {
+ required property string modelData
+ text: modelData
+ }
+ }
+}
diff --git a/packages/wildos-ui/qml/Style.qml b/packages/wildos-ui/qml/Style.qml
index 3f845bf..637ed75 100644
--- a/packages/wildos-ui/qml/Style.qml
+++ b/packages/wildos-ui/qml/Style.qml
@@ -16,6 +16,13 @@ QtObject {
id: style
readonly property bool dark: Theme.dark
+ // High contrast (Settings > Accessibility): solid black instead of glass,
+ // white text with no fading, edges that are always visible and a bright
+ // cyan accent with black text on it, after Windows' Aquatic theme. Only
+ // ever with the dark tokens, which it overrides below.
+ readonly property bool contrast: Theme.highContrast
+ readonly property color contrastEdge: "#ffffff"
+ readonly property color contrastDivider: Qt.rgba(1, 1, 1, 0.6)
// Text size contract: Settings > Personalisation > Text size sets the
// system font, Inter 10 pt by default, and Theme follows it live. Every
@@ -41,52 +48,64 @@ QtObject {
// A white-alpha layer in dark mode is the same layer in deep navy at
// three quarters strength in light mode.
function tone(alpha) {
+ if (contrast) {
+ return Qt.rgba(1, 1, 1, Math.min(1, alpha * 1.6));
+ }
return dark ? Qt.rgba(1, 1, 1, alpha) : Qt.rgba(30 / 255, 40 / 255, 70 / 255, alpha * 0.75);
}
function inkAlpha(darkAlpha, lightAlpha) {
+ 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);
}
// 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.
function shade(darkAlpha, lightAlpha) {
+ if (contrast) {
+ return "#000000";
+ }
return dark ? Qt.rgba(6 / 255, 8 / 255, 20 / 255, 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);
}
- readonly property color ink: dark ? "#eef1f8" : "#151b2c"
+ readonly property color ink: contrast ? "#ffffff" : dark ? "#eef1f8" : "#151b2c"
readonly property color inkStrong: dark ? "#ffffff" : "#0b1020"
- readonly property color inkField: dark ? "#f3f5fb" : "#151b2c"
+ 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)
// UI line icons; app icons never change between schemes.
- readonly property color iconInk: dark ? "#eef1f8" : "#2a3147"
- readonly property color iconMuted: dark ? Qt.rgba(238 / 255, 241 / 255, 248 / 255, 0.75) : Qt.rgba(42 / 255, 49 / 255, 71 / 255, 0.75)
+ 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)
// 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: Qt.rgba(232 / 255, 236 / 255, 248 / 255, 0.72)
+ readonly property color inkOnWallpaperMuted: contrast ? "#ffffff" : Qt.rgba(232 / 255, 236 / 255, 248 / 255, 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: Qt.rgba(12 / 255, 16 / 255, 32 / 255, 0.45)
- readonly property color glassOnWallpaperField: Qt.rgba(12 / 255, 16 / 255, 32 / 255, 0.50)
+ 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 borderOnWallpaper: Qt.rgba(1, 1, 1, 0.14)
- readonly property color borderOnWallpaperField: Qt.rgba(1, 1, 1, 0.22)
+ 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
// dark scheme's control fill and edge, in either scheme.
readonly property color controlOnWallpaper: Qt.rgba(1, 1, 1, 0.06)
readonly property color controlOnWallpaperHover: Qt.rgba(1, 1, 1, 0.12)
readonly property color controlOnWallpaperPressed: Qt.rgba(1, 1, 1, 0.16)
readonly property color controlOnWallpaperSelected: Qt.rgba(1, 1, 1, 0.14)
- readonly property color borderControlOnWallpaper: Qt.rgba(1, 1, 1, 0.16)
+ readonly property color borderControlOnWallpaper: contrast ? contrastEdge : Qt.rgba(1, 1, 1, 0.16)
// The accent the user picked is the dark-mode accent. Light mode deepens
// it until white text on it reads (Glacier #8fb4ff becomes #3563d8 and
@@ -109,11 +128,11 @@ QtObject {
return out;
}
readonly property bool glacier: Qt.colorEqual(systemAccent, "#8fb4ff")
- readonly property color accent: dark ? systemAccent : glacier ? "#3563d8" : deepen(systemAccent, 0.676, 0.527, 4.5)
- readonly property color textOnAccent: dark ? "#0f1530" : "#ffffff"
+ 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"
// Glacier's dark accent-text is #b9cfff, 40% of the way to white; the
// other accents get the same lift.
- readonly property color accentText: dark
+ readonly property color accentText: contrast ? accent : 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)
@@ -138,14 +157,14 @@ QtObject {
// 0.86) behind a 0.12 edge, 12px corners, a 0 20px 50px shadow at 0.45
// and 7px row corners.
readonly property color glassContextMenu: glass(16, 20, 38, 0.86, 0.95)
- readonly property color borderContextMenu: tone(0.12)
+ 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)
// Behind a window when transparency effects are off or blur is missing.
- readonly property color windowOpaque: dark ? "#151a2f" : "#f4f6fb"
- readonly property color ground: dark ? "#0f1326" : "#eef1f7"
+ readonly property color windowOpaque: contrast ? "#000000" : dark ? "#151a2f" : "#f4f6fb"
+ readonly property color ground: contrast ? "#000000" : dark ? "#0f1326" : "#eef1f7"
readonly property color lakeNavy: "#1d2b52"
- readonly property color surfaceSunken: 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 ? Qt.rgba(6 / 255, 8 / 255, 20 / 255, 0.35) : Qt.rgba(250 / 255, 251 / 255, 254 / 255, 0.55)
readonly property color surfaceRaised: tone(0.05)
readonly property color surfaceRest: tone(0.04)
readonly property color surfaceControl: tone(0.06)
@@ -157,25 +176,25 @@ 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: 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 ? Qt.rgba(4 / 255, 6 / 255, 18 / 255, 0.30) : Qt.rgba(250 / 255, 251 / 255, 254 / 255, 0.55)
- readonly property color borderSubtle: tone(0.07)
- readonly property color divider: tone(0.06)
- readonly property color borderField: tone(0.10)
- readonly property color windowEdge: tone(0.11)
- readonly property color borderGlass: tone(0.12)
- readonly property color borderMenu: tone(0.14)
- readonly property color borderControl: tone(0.16)
- readonly property color borderDialog: tone(0.13)
+ readonly property color borderSubtle: contrast ? contrastEdge : tone(0.07)
+ readonly property color divider: contrast ? contrastDivider : tone(0.06)
+ readonly property color borderField: contrast ? contrastEdge : tone(0.10)
+ readonly property color windowEdge: contrast ? contrastEdge : tone(0.11)
+ readonly property color borderGlass: contrast ? contrastEdge : tone(0.12)
+ readonly property color borderMenu: contrast ? contrastEdge : tone(0.14)
+ readonly property color borderControl: contrast ? contrastEdge : tone(0.16)
+ readonly property color borderDialog: contrast ? contrastEdge : tone(0.13)
- readonly property color toggleOffBorder: dark ? Qt.rgba(238 / 255, 241 / 255, 248 / 255, 0.55) : Qt.rgba(30 / 255, 40 / 255, 70 / 255, 0.413)
+ readonly property color toggleOffBorder: contrast ? contrastEdge : dark ? Qt.rgba(238 / 255, 241 / 255, 248 / 255, 0.55) : Qt.rgba(30 / 255, 40 / 255, 70 / 255, 0.413)
// SettingsLight draws the off knob in the dark-mode #eef1f8, which
// vanishes on white; the light knob takes the icon ink instead.
- readonly property color toggleOffKnob: dark ? "#eef1f8" : "#2a3147"
- readonly property color radioRing: dark ? Qt.rgba(238 / 255, 241 / 255, 248 / 255, 0.6) : Qt.rgba(30 / 255, 40 / 255, 70 / 255, 0.45)
+ readonly property color toggleOffKnob: contrast ? "#ffffff" : dark ? "#eef1f8" : "#2a3147"
+ readonly property color radioRing: contrast ? contrastEdge : dark ? Qt.rgba(238 / 255, 241 / 255, 248 / 255, 0.6) : Qt.rgba(30 / 255, 40 / 255, 70 / 255, 0.45)
readonly property color scrollThumb: tone(0.30)
readonly property color scrollThumbPressed: tone(0.45)
- readonly property color scrim: dark ? Qt.rgba(6 / 255, 10 / 255, 26 / 255, 0.45) : Qt.rgba(20 / 255, 30 / 255, 60 / 255, 0.22)
+ 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)
diff --git a/packages/wildos-ui/qml/Swatch.qml b/packages/wildos-ui/qml/Swatch.qml
new file mode 100644
index 0000000..d4dd00c
--- /dev/null
+++ b/packages/wildos-ui/qml/Swatch.qml
@@ -0,0 +1,62 @@
+import QtQuick
+import QtQuick.Templates as T
+
+// One colour of a set to choose from, such as the pointer colours in
+// Accessibility (SettingsAccessibility.dc): a 22px disc with a hairline, so
+// white reads on light glass and black on dark, and the chosen one ringed
+// in the accent 2px clear of the disc. Click it to choose it.
+T.AbstractButton {
+ id: swatch
+
+ property color colour
+ property string name
+ property bool selected: false
+ property int size: 22
+
+ implicitWidth: size
+ implicitHeight: size
+ padding: 0
+ hoverEnabled: true
+ focusPolicy: Qt.StrongFocus
+ Accessible.role: Accessible.RadioButton
+ Accessible.name: name
+ Accessible.checked: selected
+
+ background: Rectangle {
+ radius: width / 2
+ color: swatch.down ? Qt.darker(swatch.colour, 1.06) : swatch.colour
+ border.width: 1
+ border.color: Style.tone(0.30)
+
+ Rectangle {
+ visible: swatch.selected
+ anchors.fill: parent
+ anchors.margins: -4
+ radius: width / 2
+ color: "transparent"
+ border.width: 2
+ border.color: Style.accent
+ }
+
+ Rectangle {
+ visible: swatch.hovered && !swatch.selected
+ anchors.fill: parent
+ anchors.margins: -3
+ radius: width / 2
+ color: "transparent"
+ border.width: 1
+ border.color: Style.tone(0.30)
+ }
+
+ FocusRing {
+ visible: swatch.visualFocus
+ anchors.margins: swatch.selected ? -7 : -4
+ targetRadius: width / 2
+ }
+ }
+
+ Tooltip {
+ text: swatch.name
+ visible: swatch.hovered && swatch.name.length > 0
+ }
+}
diff --git a/packages/wildos-ui/src/accessshortcuts.cpp b/packages/wildos-ui/src/accessshortcuts.cpp
new file mode 100644
index 0000000..5a5dec1
--- /dev/null
+++ b/packages/wildos-ui/src/accessshortcuts.cpp
@@ -0,0 +1,105 @@
+#include "accessshortcuts.h"
+
+#include <KConfigGroup>
+#include <KSharedConfig>
+
+#include <QGuiApplication>
+#include <QKeyEvent>
+#include <QProcess>
+#include <QStandardPaths>
+#include <QWindow>
+
+AccessShortcuts::AccessShortcuts(QObject *parent)
+ : QObject(parent)
+{
+ qGuiApp->installEventFilter(this);
+}
+
+bool AccessShortcuts::keyboardOn() const
+{
+ return KSharedConfig::openConfig(QStringLiteral("wildosrc"))->group(QStringLiteral("Accessibility")).readEntry("OnScreenKeyboard", false);
+}
+
+void AccessShortcuts::restore() const
+{
+ run({QStringLiteral("restore")});
+}
+
+void AccessShortcuts::run(const QStringList &arguments) const
+{
+ const QString program = QStandardPaths::findExecutable(QStringLiteral("wildos-access"));
+ if (!program.isEmpty()) {
+ QProcess::startDetached(program, arguments);
+ }
+}
+
+bool AccessShortcuts::eventFilter(QObject *watched, QEvent *event)
+{
+ // A key event is sent to the window and then on to each item in turn;
+ // the window sees it once.
+ if ((event->type() != QEvent::KeyPress && event->type() != QEvent::KeyRelease) || !qobject_cast<QWindow *>(watched)) {
+ return QObject::eventFilter(watched, event);
+ }
+ const auto key = static_cast<QKeyEvent *>(event);
+ if (key->isAutoRepeat()) {
+ return false;
+ }
+ const Qt::KeyboardModifiers modifiers = key->modifiers() & ~(Qt::KeypadModifier | Qt::GroupSwitchModifier);
+
+ if (event->type() == QEvent::KeyRelease) {
+ if (key->key() == Qt::Key_Shift && m_shiftAlone) {
+ // Five taps of Shift on its own, each within a second of the
+ // last, as on Windows.
+ if (!m_lastShift.isValid() || m_lastShift.elapsed() > 1000) {
+ m_shiftTaps = 0;
+ }
+ m_lastShift.restart();
+ if (++m_shiftTaps == 5) {
+ m_shiftTaps = 0;
+ run({QStringLiteral("toggle"), QStringLiteral("sticky-keys")});
+ }
+ }
+ m_shiftAlone = false;
+ return false;
+ }
+
+ if (key->key() == Qt::Key_Shift) {
+ m_shiftAlone = (modifiers & ~Qt::ShiftModifier) == Qt::NoModifier;
+ return false;
+ }
+ m_shiftAlone = false;
+ m_shiftTaps = 0;
+
+ const Qt::KeyboardModifiers superAlt = Qt::MetaModifier | Qt::AltModifier;
+ const Qt::KeyboardModifiers superCtrl = Qt::MetaModifier | Qt::ControlModifier;
+ if (modifiers == superAlt && key->key() == Qt::Key_S) {
+ run({QStringLiteral("toggle"), QStringLiteral("screen-reader")});
+ return true;
+ }
+ if (modifiers == superAlt && key->key() == Qt::Key_H) {
+ run({QStringLiteral("toggle"), QStringLiteral("high-contrast")});
+ return true;
+ }
+ if (modifiers == superCtrl && key->key() == Qt::Key_O) {
+ Q_EMIT keyboardRequested();
+ return true;
+ }
+ // Plus is Shift and = on most layouts, so Shift is allowed with it.
+ if (m_magnifier && (modifiers & ~Qt::ShiftModifier) == Qt::MetaModifier) {
+ switch (key->key()) {
+ case Qt::Key_Plus:
+ case Qt::Key_Equal:
+ run({QStringLiteral("zoom"), QStringLiteral("in")});
+ return true;
+ case Qt::Key_Minus:
+ run({QStringLiteral("zoom"), QStringLiteral("out")});
+ return true;
+ case Qt::Key_0:
+ run({QStringLiteral("zoom"), QStringLiteral("reset")});
+ return true;
+ default:
+ break;
+ }
+ }
+ return false;
+}
diff --git a/packages/wildos-ui/src/accessshortcuts.h b/packages/wildos-ui/src/accessshortcuts.h
new file mode 100644
index 0000000..1fce1d0
--- /dev/null
+++ b/packages/wildos-ui/src/accessshortcuts.h
@@ -0,0 +1,59 @@
+#pragma once
+
+#include <QElapsedTimer>
+#include <QObject>
+#include <QQmlEngine>
+
+// The accessibility shortcuts on the lock and sign-in screens, which KDE's
+// global shortcuts do not reach: the lock screen lets only a short list
+// through (the magnifier among them) and the sign-in screen's KWin runs
+// with none at all. Watching every key that comes to the screen's own
+// windows, it catches
+//
+// Super Alt S screen reader wildos-access toggle screen-reader
+// Super Alt H high contrast wildos-access toggle high-contrast
+// Shift x5 sticky keys wildos-access toggle sticky-keys
+// Super Ctrl O on-screen keyboard keyboardRequested(), as each
+// screen has its own keyboard panel
+// Super + - 0 magnifier wildos-access zoom, when
+// `magnifier` is set (sign-in
+// screen; the lock screen gets
+// these from KWin already)
+//
+// so the shortcuts Settings > Accessibility lists work before anyone has
+// signed in, exactly as they do on the desktop.
+class AccessShortcuts : public QObject
+{
+ Q_OBJECT
+ QML_ELEMENT
+
+ Q_PROPERTY(bool magnifier MEMBER m_magnifier NOTIFY magnifierChanged)
+ // Whether the on-screen keyboard was left on (wildosrc [Accessibility]
+ // OnScreenKeyboard, which Settings writes and the sign-in screen gets a
+ // copy of), so a screen can show its keyboard from the start.
+ Q_PROPERTY(bool keyboardOn READ keyboardOn CONSTANT)
+
+public:
+ explicit AccessShortcuts(QObject *parent = nullptr);
+
+ bool keyboardOn() const;
+
+ // Starts what was left on and needs a process of its own (the screen
+ // reader), for a screen with nobody else to do it.
+ Q_INVOKABLE void restore() const;
+
+Q_SIGNALS:
+ void magnifierChanged();
+ void keyboardRequested();
+
+protected:
+ bool eventFilter(QObject *watched, QEvent *event) override;
+
+private:
+ void run(const QStringList &arguments) const;
+
+ bool m_magnifier = false;
+ bool m_shiftAlone = false;
+ int m_shiftTaps = 0;
+ QElapsedTimer m_lastShift;
+};
diff --git a/packages/wildos-ui/src/theme.cpp b/packages/wildos-ui/src/theme.cpp
index f4ab0bb..8ed9204 100644
--- a/packages/wildos-ui/src/theme.cpp
+++ b/packages/wildos-ui/src/theme.cpp
@@ -71,7 +71,9 @@ void Theme::read()
bool dark = true;
const QByteArray forced = qgetenv("WILDOS_UI_THEME");
const QColor window = parseColour(config->group(QStringLiteral("Colors:Window")).readEntry("BackgroundNormal"));
- if (forced == "light" || forced == "dark") {
+ if (scheme == QLatin1String("WildOSHighContrast")) {
+ dark = true;
+ } else if (forced == "light" || forced == "dark") {
dark = forced == "dark";
} else if (window.isValid()) {
dark = window.lightnessF() < 0.5;
diff --git a/packages/wildos-ui/src/theme.h b/packages/wildos-ui/src/theme.h
index 8f5759c..d5457c6 100644
--- a/packages/wildos-ui/src/theme.h
+++ b/packages/wildos-ui/src/theme.h
@@ -20,6 +20,10 @@ class Theme : public QObject
Q_PROPERTY(QColor accent READ accent NOTIFY accentChanged)
Q_PROPERTY(bool dark READ dark NOTIFY darkChanged)
Q_PROPERTY(QString colourScheme READ colourScheme NOTIFY darkChanged)
+ // Settings > Accessibility > High contrast, which applies the
+ // WildOSHighContrast scheme; Style then draws solid black surfaces,
+ // white text and strong edges instead of glass.
+ Q_PROPERTY(bool highContrast READ highContrast NOTIFY darkChanged)
// Qt.application.font is a constant snapshot in QML, so a text size
// change from Settings would only show after a restart; this follows
// the application's font change events instead.
@@ -34,6 +38,7 @@ public:
QColor accent() const { return m_accent; }
bool dark() const { return m_dark; }
QString colourScheme() const { return m_scheme; }
+ bool highContrast() const { return m_scheme == QLatin1String("WildOSHighContrast"); }
qreal fontPointSize() const;
bool reducedMotion() const { return m_reducedMotion; }
diff --git a/packages/wildos-winmode/guest/setup.ps1 b/packages/wildos-winmode/guest/setup.ps1
index c9e6481..bebc9cd 100644
--- a/packages/wildos-winmode/guest/setup.ps1
+++ b/packages/wildos-winmode/guest/setup.ps1
@@ -87,8 +87,7 @@ Step 'guest-tools' $true {
# 2. The shared folders on Wild OS become drive Z:, through the RemoteApp
# connection itself (settings.json transport "rdp"). Testing on real
-# hardware ruled virtiofs out; the other transports stay
-# for setups made before.
+# hardware ruled virtiofs out. Samba stays as the fallback transport.
Step 'shared-folder' $true {
# The RemoteApp connection carries the folders (FreeRDP's drive
# redirection) and wild-guest maps them to Z: whenever it connects, so
@@ -101,12 +100,6 @@ Step 'shared-folder' $true {
cmdkey /add:$($settings.host) /user:$($settings.samba.user) /pass:$($settings.samba.password) | Out-Null
net use "$($drive):" /delete /y 2>$null | Out-Null
net use "$($drive):" $share /persistent:yes | Out-Null
- } else {
- $p = Start-Process -Wait -PassThru msiexec.exe -ArgumentList '/i', "`"$here\winfsp.msi`"", '/qn', '/norestart'
- if ($p.ExitCode -ne 0 -and $p.ExitCode -ne 3010) { throw "WinFsp install exit $($p.ExitCode)" }
- Set-Value 'HKLM:\SOFTWARE\VirtIO-FS' 'MountPoint' "$($drive):" 'String'
- Set-Service VirtioFsSvc -StartupType Automatic
- Start-Service VirtioFsSvc
}
$deadline = (Get-Date).AddSeconds(90)
while (-not (Test-Path "$($drive):\Documents") -and (Get-Date) -lt $deadline) { Start-Sleep -Seconds 2 }
diff --git a/packages/wildos-winmode/tests/test_winmode.py b/packages/wildos-winmode/tests/test_winmode.py
index f61ac58..5c9741e 100644
--- a/packages/wildos-winmode/tests/test_winmode.py
+++ b/packages/wildos-winmode/tests/test_winmode.py
@@ -375,9 +375,22 @@ class Setup(unittest.TestCase):
def test_office_plan(self):
from winmode import setup
- self.assertIn('Product ID="O365BusinessRetail"', setup.office_config("business"))
- self.assertIn('Product ID="O365HomePremRetail"', setup.office_config("anything"))
- self.assertNotIn('ExcludeApp ID="Excel"', setup.office_config("personal"))
+ self.assertIn('Product ID="O365BusinessRetail"', setup.office_config("business", "en-GB"))
+ self.assertIn('Product ID="O365HomePremRetail"', setup.office_config("anything", "en-GB"))
+ self.assertNotIn('ExcludeApp ID="Excel"', setup.office_config("personal", "en-GB"))
+
+ def test_office_follows_host_language(self):
+ from winmode import setup
+ uk = setup.office_config("personal", "en-GB")
+ self.assertIn('<Language ID="en-gb"/>', uk)
+ self.assertIn('<Product ID="ProofingTools">', uk)
+ self.assertIn('<Language ID="MatchOS"/>', uk)
+ # A language the Office Deployment Tool doesn't know would stop the
+ # install, so it falls back to Windows' own.
+ odd = setup.office_config("personal", "cy-GB")
+ self.assertNotIn("cy-gb", odd)
+ self.assertNotIn("ProofingTools", odd)
+ self.assertIn('<Language ID="MatchOS"/>', odd)
def test_templates_fill_every_field(self):
from winmode import setup
diff --git a/packages/wildos-winmode/winmode/agent.py b/packages/wildos-winmode/winmode/agent.py
index 560c438..9bb19e4 100644
--- a/packages/wildos-winmode/winmode/agent.py
+++ b/packages/wildos-winmode/winmode/agent.py
@@ -84,6 +84,8 @@ XML = """
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
SECRET_ATTRS = ["service", "org.wildos.WindowsMode1", "account"]
@@ -239,6 +241,17 @@ 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,
+ # without enough free memory, or when Windows is already up.
+ GLib.timeout_add_seconds(PRESTART_DELAY, lambda: (self.prestart(), False)[1])
+
+ def prestart(self):
+ def done(reply):
+ if isinstance(reply, GLib.Error):
+ log("starting Windows ahead of time:", reply.message)
+ self.call("Prestart", done=done, timeout=600)
# The system service.
def call(self, method, args=None, signature=None, done=None, timeout=600):
diff --git a/packages/wildos-winmode/winmode/setup.py b/packages/wildos-winmode/winmode/setup.py
index 9f5ca53..ca5a923 100644
--- a/packages/wildos-winmode/winmode/setup.py
+++ b/packages/wildos-winmode/winmode/setup.py
@@ -59,8 +59,6 @@ GUEST_STEPS = ["guest-tools", "shared-folder", "wild-guest", "remote-desktop", "
"known-folders", "office-policies", "startup-trim", "theme", "ready-task"]
TOOL_AGENT = "wildos-winmode (+https://wildos.io)"
-WINFSP_URL = "https://github.com/winfsp/winfsp/releases/download/v2.1/winfsp-2.1.25156.msi"
-WINFSP_SHA256 = "073a70e00f77423e34bed98b86e600def93393ba5822204fac57a29324db9f7a"
VIRTIO_BASE = "https://fedorapeople.org/groups/virt/virtio-win/direct-downloads"
# Microsoft's published generic installation key for Pro: installs Pro but
# never activates. Every setup installs with it, so Windows is always Pro,
@@ -267,16 +265,35 @@ def render(name, values):
return text
-def office_config(plan):
+# The languages Microsoft 365 installs in, as the Office Deployment Tool
+# names them. An ID it doesn't know stops the whole install, so anything else
+# falls back to Windows' own display language.
+OFFICE_LANGUAGES = {
+ "ar-sa", "bg-bg", "cs-cz", "da-dk", "de-de", "el-gr", "en-gb", "en-us", "es-es", "es-mx", "et-ee",
+ "fi-fi", "fr-ca", "fr-fr", "he-il", "hr-hr", "hu-hu", "id-id", "it-it", "ja-jp", "ko-kr", "lt-lt",
+ "lv-lv", "nb-no", "nl-nl", "pl-pl", "pt-br", "pt-pt", "ro-ro", "ru-ru", "sk-sk", "sl-si", "sr-latn-rs",
+ "sv-se", "th-th", "tr-tr", "uk-ua", "vi-vn", "zh-cn", "zh-tw",
+}
+
+
+def office_config(plan, lang):
+ """Microsoft 365 in the host's language, with its spelling and grammar
+ tools, rather than the US English MatchOS alone gave on a UK PC."""
product = OFFICE_PRODUCTS.get(plan, "O365HomePremRetail")
excluded = ["Access", "Bing", "Groove", "Lync", "OneDrive", "OutlookForWindows", "Publisher", "Teams"]
+ office_lang = lang.lower() if lang.lower() in OFFICE_LANGUAGES else ""
+ languages = (f' <Language ID="{office_lang}"/>\n' if office_lang else "") + ' <Language ID="MatchOS"/>\n'
+ proofing = (' <Product ID="ProofingTools">\n'
+ f' <Language ID="{office_lang}"/>\n'
+ " </Product>\n") if office_lang else ""
return ("<Configuration>\n"
' <Add OfficeClientEdition="64" Channel="Current">\n'
f' <Product ID="{product}">\n'
- ' <Language ID="MatchOS"/>\n'
+ + languages
+ "".join(f' <ExcludeApp ID="{a}"/>\n' for a in excluded)
+ " </Product>\n"
- " </Add>\n"
+ + proofing
+ + " </Add>\n"
' <Updates Enabled="FALSE"/>\n'
' <Display Level="None" AcceptEULA="TRUE"/>\n'
' <Property Name="AUTOACTIVATE" Value="0"/>\n'
@@ -583,9 +600,6 @@ class Setup:
self.check()
self.set_stage("media", "active", 92, "Getting the drivers Windows needs")
self.virtio_iso()
- self.check()
- self.set_stage("media", "active", 97, "Getting the shared folder driver")
- self.winfsp()
self.set_stage("media", "done", 100, "")
def check_space(self):
@@ -777,16 +791,6 @@ class Setup:
_remove(iso)
raise Problem("download", "The drivers download came back as something other than the drivers. Try again in a while.")
- def winfsp(self):
- msi = os.path.join(CACHE, "winfsp.msi")
- if os.path.exists(msi) and _sha256(msi) == WINFSP_SHA256:
- return
- _remove(msi)
- self.download(WINFSP_URL, msi, "media", 97, 99, "Shared folder driver")
- if _sha256(msi) != WINFSP_SHA256:
- _remove(msi)
- raise Problem("download", "A part Windows mode downloads didn't pass its check, so it was deleted. Try again later.")
-
# install
def step_install(self):
if self.done("install"):
@@ -879,10 +883,9 @@ class Setup:
guest = os.path.join(config.DATA, "guest")
shutil.copy(os.path.join(guest, "setup.ps1"), os.path.join(work, "wildos", "setup.ps1"))
shutil.copy(self.cfg["guest_exe"], os.path.join(work, "wildos", "wild-guest.exe"))
- shutil.copy(os.path.join(CACHE, "winfsp.msi"), os.path.join(work, "wildos", "winfsp.msi"))
plan = (self.rec.get("options") or {}).get("officePlan", "personal")
with open(os.path.join(work, "wildos", "office.xml"), "w", encoding="utf-8") as f:
- f.write(office_config(plan))
+ f.write(office_config(plan, lang))
with open(os.path.join(work, "wildos", "settings.json"), "w", encoding="utf-8") as f:
json.dump({"host": self.cfg["host_address"], "guest": self.cfg["guest_address"],
"account": self.cfg["account"], "folders": self.cfg["folders"], "drive": self.cfg["drive"],
diff --git a/packages/wildos-winmode/winmode/system.py b/packages/wildos-winmode/winmode/system.py
index 4e768f9..80b151f 100644
--- a/packages/wildos-winmode/winmode/system.py
+++ b/packages/wildos-winmode/winmode/system.py
@@ -27,6 +27,7 @@ XML = """
<interface name="org.wildos.WindowsMode1.Host">
<method name="Status"><arg type="s" direction="out"/></method>
<method name="Wake"><arg type="s" direction="out"/></method>
+ <method name="Prestart"><arg type="s" direction="out"/></method>
<method name="Idle">
<arg name="mode" type="s" direction="in"/>
<arg type="s" direction="out"/>
@@ -145,6 +146,7 @@ class Service:
self.export = dbusutil.Exported(bus, config.OBJECT_PATH, XML, config.HOST_INTERFACE, {
"Status": (self.m_status, "s", False),
"Wake": (self.m_wake, "s", True),
+ "Prestart": (self.m_prestart, "s", True),
"Idle": (self.m_idle, "s", True),
"Launch": (self.m_launch, "s", True),
"Windows": (self.m_windows, "s", True),
@@ -762,6 +764,53 @@ class Service:
dbusutil.in_thread(work, done=finished)
return defer
+ def prestart_blocker(self):
+ """Why Windows shouldn't be started ahead of time now, or None. Only
+ on mains, with room for it to stay paused in memory afterwards
+ (where the Automatic idle policy would otherwise save it straight
+ to disk), and only from switched off or saved."""
+ st = virsh.state(self.domain)
+ if st not in ("shut off", "saved"):
+ return f"it is {st or 'not set up'}"
+ if self.state.get("setting_up"):
+ return "it is being set up"
+ if self.state["when_idle"] == "save":
+ return "it is set to go to disk when idle"
+ if self.power.on_battery:
+ return "the PC is on battery"
+ if hostinfo.under_pressure():
+ return "memory is under pressure"
+ available, total = hostinfo.meminfo()
+ if total and (available - self.memory) / total < lifecycle.MEMORY_FREE_SHARE:
+ return "there isn't enough free memory"
+ if self.busy_action:
+ return "something else is under way"
+ return None
+
+ def m_prestart(self, sender, defer):
+ """Called by the session agent once sign-in has settled, so the first
+ Windows app opens from memory instead of a cold start. The guest
+ then idles into the paused state like any other."""
+ why = self.claim(sender)
+ if why:
+ return json.dumps({"ok": False, "error": why})
+ blocker = self.prestart_blocker()
+ if blocker:
+ log("not starting Windows ahead of time:", blocker)
+ return json.dumps({"ok": False, "skipped": blocker})
+ log("starting Windows ahead of time")
+
+ def finished(result):
+ self.refresh()
+ self.schedule_idle()
+ if isinstance(result, Exception):
+ defer.done(json.dumps({"ok": False, "error": str(result)}))
+ else:
+ defer.done(json.dumps(result))
+
+ dbusutil.in_thread(self.wake, done=finished)
+ return defer
+
def release_launch(self):
self.life.hold(time.monotonic(), LAUNCH_HOLD, False)
self.schedule_idle()